{"text": "import numpy as np\n\n# A self-contained reference implementation of the B-spline basis functions\n# and their first derivatives, in addition to some utiliy functions.\n\ndef float_is_zero(v, eps=1e-6):\n    \"\"\" Test if floating point number is zero. \"\"\"\n    return abs(v) < eps\n\ndef special_div(num, den):\n    \"\"\" Return num/dev with the special rule\n    that 0/0 is 0. \"\"\"\n    if float_is_zero(num) and float_is_zero(den):\n        return 0.0\n    else:\n        return num / den\n\ndef B(j, p, x, knots):\n    \"\"\" Compute B-splines using recursive definition. \"\"\"        \n    if p == 0:\n        if knots[j] <= x < knots[j+1]:\n            return 1.0\n        else:\n            return 0.0\n    else:\n        left = special_div((x-knots[j])*B(j,p-1,x,knots), knots[j+p]-knots[j])\n        right = special_div((knots[j+1+p]-x)*B(j+1,p-1,x,knots), knots[j+1+p]-knots[j+1])\n        return left + right\n\ndef render_spline(p, knots, control_points, ts):\n    \"\"\"\n    Compute points on a spline function using the straightforward\n    implementation of the recurrence relation for the B-splines.\n    \"\"\"\n    ys = []\n    for t in ts:\n        y = 0.0 \n        for j in range(0, len(control_points)):\n            y += B(j, p, t, knots)*control_points[j]\n        ys.append(y)\n    return ys\n\n\ndef uniform_regular_knot_vector(n, p, t0=0.0, t1=1.0):\n    \"\"\"\n    Create a p+1-regular uniform knot vector for\n    a given number of control points\n    Throws if n is too small\n    \"\"\"\n    # The minimum length of a p+1-regular knot vector\n    # is 2*(p+1)\n    if n < p+1:\n        raise RuntimeError(\"Too small n for a uniform regular knot vector\")\n\n    # p+1 copies of t0 left and p+1 copies of t1 right\n    # but one of each in linspace\n    return [t0]*p + list(np.linspace(t0, t1, n+1-p)) + [t1]*p\n\ndef control_points(p, knots):\n    \"\"\"\n    Return the control point abscissa for the control polygon\n    of a one-dimensional spline.\n    \"\"\"\n    knots = np.array(knots)\n    abscissas = []\n    for i in range(len(knots)-p-1):\n        part = knots[(i+1):(i+1+p)]\n        abscissas.append(np.mean(part))\n    return abscissas\n\n\ndef B_derivative(j, p, x, knots):\n    \"\"\"\n    Evaluate the derivative of Bj,p(x)\n    p must be greater than or equal to 1\n    \"\"\"\n    if p < 1: raise RuntimeError(\"p must be greater than or equal to 1\")\n    left = special_div(B(j, p-1, x, knots), (knots[j+p]-knots[j]) )\n    right = special_div(B(j+1,p-1, x, knots), (knots[j+p+1] - knots[j+1]) )\n    return (left - right)*p\n", "meta": {"hexsha": "63bd2961ee0c35294b55379f63f245cb3690bf7a", "size": 2465, "ext": "py", "lang": "Python", "max_stars_repo_path": "phantom_scripts/bsplines.py", "max_stars_repo_name": "sigurdstorve/OpenBCSim", "max_stars_repo_head_hexsha": "500025c1b63bc6ff083cbd649771d1b98e3f7314", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2016-05-27T13:09:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T07:08:47.000Z", "max_issues_repo_path": "phantom_scripts/bsplines.py", "max_issues_repo_name": "rojsc/OpenBCSim", "max_issues_repo_head_hexsha": "53773172974ad42fc3faceb7b36611573abf1c4c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2015-09-10T11:22:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-21T14:52:39.000Z", "max_forks_repo_path": "phantom_scripts/bsplines.py", "max_forks_repo_name": "rojsc/OpenBCSim", "max_forks_repo_head_hexsha": "53773172974ad42fc3faceb7b36611573abf1c4c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2016-07-26T14:52:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T15:52:28.000Z", "avg_line_length": 30.4320987654, "max_line_length": 89, "alphanum_fraction": 0.6028397566, "include": true, "reason": "import numpy", "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633822, "lm_q2_score": 0.9407897525789548, "lm_q1q2_score": 0.899991651163169}}
{"text": "#!/usr/bin/env python\n\n# Import modules\nimport math\nimport numpy\nimport matplotlib.pyplot as plt # import plot\n\ndef trinome(a,b,c,x):\n    return (a*x**2 + b*x + c)\n\n# fonction calculant le discriminant\ndef discriminant(a,b,c):\n    return b**2 - 4*a*c\n\n# fonction retournant la solution double\ndef solutiondouble(a,b):\n    return (-b/(2*a))\n\n# fonction retournant les solutions\ndef solution(a,b,delta):\n    x1 = (-b - math.sqrt(delta)) /(2*a)\n    x2 = (-b + math.sqrt(delta)) /(2*a) \n    return x1, x2\n\n\n# fonction de base de résolution de l'équation\ndef resolution(a,b,c):\n    print(\"Soit l'équation : \",a,\"x**2 + \",b,\"x + \",c, \" = 0\" )\n    delta = discriminant(a,b,c)\n\n    if(delta < 0):\n        print(\"L'équation n'a pas de solution\")\n\n        # Sinon, delta peut être positif ou nul    \n    else:\n        # Si delta est nul\n        if (delta == 0):\n            print(\"L'équation a une solution double.\")\n            print (\"La solution est x = \", solutiondouble(a,b))\n            \n            #Sinon,  delta ne peut plus qu'être positif.\n        else:\n            print(\"L'équation a deux solutions solutions.\")\n            x1, x2 = solution(a,b,delta)\n            print (\"Les solutions sont x1 = \",x1, \" et \", x2)\n\n\n\ndef plot_trinome(a,b,c):\n    # L'intervalle de trace\n    x = numpy.linspace(-10,10,100)\n    \n    # La courbe\n    plt.plot(x,trinome(a,b,c, x))\n\n    # Les axes\n    plt.axvline(x=0, color ='r')\n    plt.axhline(y=0, color ='r')   \n    axes = plt.gca()\n    axes.set_xlabel('x : abscisse')\n    axes.set_ylabel('f(x) : ordonnée')\n\n    plt.show()\n\n\n\n# a*x**2 + b*x + c un trinôme du second degré.\n# On rentre les valeurs de a, b et c.\n# On souhaite que a, b et c soient des nombres rééls (float en anglais)\n# et non une chaîne de charactère (comme pour une phrase)\n# a = float(input(\"a = \"))\n# b = float(input(\"b = \"))\n# c = float(input(\"c = \"))\n\n# Sinon, on fait un simple appel à la fonction avec les bon paramètres:\nprint(\" ---------- Exercice 1 ------------\")\nresolution(1,-120,2000)\n\nprint(\" ---------- Exercice 2 ------------\")\nprint(\"Exercice 2.1\")\nresolution(1,2,-3)\n\n# On peut également appeler le tracer avec matplotlib.\nplot_trinome(1,2,-3)\n\n\nprint(\"Exercice 2.2\")\nresolution(1,6,9)\n\nprint(\"Exercice 2.3\")\nresolution(2,1,(1/2))\n\nprint(\"Exercice 2.4\")\nresolution(3,2,(1/3))\n", "meta": {"hexsha": "e2c45c694a3a5769a5257888ec5b3b4c7bfede77", "size": 2298, "ext": "py", "lang": "Python", "max_stars_repo_path": "2014.d/premiere-sti2d.d/premiere-sti2d.d/1_second-degre/python/discriminant-fonction.py", "max_stars_repo_name": "homeostasie/annees-precedentes", "max_stars_repo_head_hexsha": "db95e1883558eb5f8c67dfdd9923cf00cdf1a70a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-29T12:46:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-29T12:46:51.000Z", "max_issues_repo_path": "2014.d/premiere-sti2d.d/premiere-sti2d.d/1_second-degre/python/discriminant-fonction.py", "max_issues_repo_name": "homeostasie/annees-precedentes", "max_issues_repo_head_hexsha": "db95e1883558eb5f8c67dfdd9923cf00cdf1a70a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2014.d/premiere-sti2d.d/premiere-sti2d.d/1_second-degre/python/discriminant-fonction.py", "max_forks_repo_name": "homeostasie/annees-precedentes", "max_forks_repo_head_hexsha": "db95e1883558eb5f8c67dfdd9923cf00cdf1a70a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1894736842, "max_line_length": 71, "alphanum_fraction": 0.590948651, "include": true, "reason": "import numpy", "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.9353465161493965, "lm_q1q2_score": 0.8999039638642096}}
{"text": "\"\"\"\n@author: MatteoRaso\n\"\"\"\nfrom numpy import pi, sqrt\nfrom random import uniform\nfrom statistics import mean\n\n\ndef pi_estimator(iterations: int):\n    \"\"\"\n    An implementation of the Monte Carlo method used to find pi.\n    1. Draw a 2x2 square centred at (0,0).\n    2. Inscribe a circle within the square.\n    3. For each iteration, place a dot anywhere in the square.\n       a. Record the number of dots within the circle.\n    4. After all the dots are placed, divide the dots in the circle by the total.\n    5. Multiply this value by 4 to get your estimate of pi.\n    6. Print the estimated and numpy value of pi\n    \"\"\"\n    # A local function to see if a dot lands in the circle.\n    def in_circle(x: float, y: float) -> bool:\n        distance_from_centre = sqrt((x ** 2) + (y ** 2))\n        # Our circle has a radius of 1, so a distance\n        # greater than 1 would land outside the circle.\n        return distance_from_centre <= 1\n\n    # The proportion of guesses that landed in the circle\n    proportion = mean(\n        int(in_circle(uniform(-1.0, 1.0), uniform(-1.0, 1.0)))\n        for _ in range(iterations)\n    )\n    # The ratio of the area for circle to square is pi/4.\n    pi_estimate = proportion * 4\n    print(\"The estimated value of pi is \", pi_estimate)\n    print(\"The numpy value of pi is \", pi)\n    print(\"The total error is \", abs(pi - pi_estimate))\n\n\ndef area_under_line_estimator(\n    iterations: int, min_value: float = 0.0, max_value: float = 1.0\n) -> float:\n    \"\"\"\n    An implementation of the Monte Carlo method to find area under\n       y = x where x lies between min_value to max_value\n    1. Let x be a uniformly distributed random variable between min_value to max_value\n    2. Expected value of x = (integration of x from min_value to max_value) / (max_value - min_value)\n    3. Finding expected value of x:\n        a. Repeatedly draw x from uniform distribution\n        b. Expected value = average of those values\n    4. Actual value = (max_value^2 - min_value^2) / 2\n    5. Returns estimated value\n    \"\"\"\n    return mean(uniform(min_value, max_value) for _ in range(iterations)) * (\n        max_value - min_value\n    )\n\n\ndef area_under_line_estimator_check(\n    iterations: int, min_value: float = 0.0, max_value: float = 1.0\n) -> None:\n    \"\"\"\n    Checks estimation error for area_under_line_estimator func\n    1. Calls \"area_under_line_estimator\" function\n    2. Compares with the expected value\n    3. Prints estimated, expected and error value\n    \"\"\"\n\n    estimated_value = area_under_line_estimator(iterations, min_value, max_value)\n    expected_value = (max_value * max_value - min_value * min_value) / 2\n\n    print(\"******************\")\n    print(\n        \"Estimating area under y=x where x varies from \", min_value, \" to \", max_value\n    )\n    print(\"Estimated value is \", estimated_value)\n    print(\"Expected value is \", expected_value)\n    print(\"Total error is \", abs(estimated_value - expected_value))\n    print(\"******************\")\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n", "meta": {"hexsha": "b99512ccd386adf14a0396c311ea8562d2d9e718", "size": 3054, "ext": "py", "lang": "Python", "max_stars_repo_path": "maths/monte_carlo.py", "max_stars_repo_name": "serhii73/Python", "max_stars_repo_head_hexsha": "7e141fd4bb38fe099ba1e65de7a89d4ea9e9dd0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-17T03:06:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T03:06:12.000Z", "max_issues_repo_path": "maths/monte_carlo.py", "max_issues_repo_name": "serhii73/Python", "max_issues_repo_head_hexsha": "7e141fd4bb38fe099ba1e65de7a89d4ea9e9dd0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maths/monte_carlo.py", "max_forks_repo_name": "serhii73/Python", "max_forks_repo_head_hexsha": "7e141fd4bb38fe099ba1e65de7a89d4ea9e9dd0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9294117647, "max_line_length": 101, "alphanum_fraction": 0.6669941061, "include": true, "reason": "from numpy", "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846621952493, "lm_q2_score": 0.9196425366837827, "lm_q1q2_score": 0.899764152593745}}
{"text": "import math\nimport numpy as np\nimport time\n\ndef basic_sigmoid(x):\n    s = 1 / (1+math.exp(-x))\n    return s\n\nx = np.array([1, 2, 3])\n\ndef sigmoid(x):\n    s = 1./(1+np.exp(-x))\n    return s\n\ndef sigmoid_derivative(x):\n    s = sigmoid(x)\n    ds = s *(1-s)\n    return ds\n\nprint(\"sigmoid_derivative(x) = \" + str(sigmoid_derivative(x)))\n\ndef image2vector(image):\n    v = image.reshape(image.size, 1)\n    return v\n\nimage = np.array([[[ 0.67826139,  0.29380381],\n        [ 0.90714982,  0.52835647],\n        [ 0.4215251 ,  0.45017551]],\n\n       [[ 0.92814219,  0.96677647],\n        [ 0.85304703,  0.52351845],\n        [ 0.19981397,  0.27417313]],\n\n       [[ 0.60659855,  0.00533165],\n        [ 0.10820313,  0.49978937],\n        [ 0.34144279,  0.94630077]]])\n\n\n\ndef normalizeRows(x):\n    x_norm = np.linalg.norm(x, ord=2, axis=1, keepdims=True)\n    x = x / x_norm\n    return x\n\nx = np.array([\n    [0, 3, 4],\n    [2, 6, 4]])\n\n\n\ndef softmax(x):\n    x_exp = np.exp(x)\n    x_sum = np.sum(x_exp, axis=1, keepdims=True)\n    s = x_exp / x_sum\n    return s\n\n\nx = np.array([[9, 2, 5, 0, 0],\n              [7, 5, 0, 0, 0]])\n\n\n\n#Vectorization\nx1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]\nx2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]\n\n\n### CLASSIC DOT PRODUCT OF VECTORS IMPLEMENTATION ###\ntic  = time.process_time()\ndot = 0\nfor i in range(len(x1)):\n    dot += x1[i] + x2[i]\ntoc = time.process_time()\n\n### CLASSIC OUTER PRODUCT IMPLEMENTATION ###\ntic = time.process_time()\nouter = np.zeros((len(x1), len(x2)))\n\nfor i in range(len(x1)):\n    for j in range(len(x2)):\n        outer[i, j] = x1[i]*x2[j]\n\ntoc = time.process_time()\n\n### CLASSIC ELEMENTWISE IMPLEMENTATION ###\ntic = time.process_time()\nmul = np.zeros(len(x1))\nfor i in range(len(x1)):\n    mul[i] = x1[i]*x2[i]\ntoc = time.process_time()\n\n### CLASSIC GENERAL DOT PRODUCT IMPLEMENTATION ###\nW = np.random.rand(3, len(x1))\ntic = time.process_time()\ngdot = np.zeros(W.shape[0])\n\nfor i in range(W.shape[0]):\n    for j in range(len(x1)):\n        gdot[i] += W[i, j] * x[j]\n\ntoc = time.process_time()\n\n\nx1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]\nx2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]\n\n\n### VECTORIZED DOT PRODUCT OF VECTORS ###\ntic = time.process_time()\ndot = np.dot(x1, x2)\ntoc =time.process_time()\n\n### VECTORIZED OUTER PRODUCT ###\ntic = time.process_time()\nouter = np.outer(x1, x2)\ntoc = time.process_time()\n\n### VECTORIZED ELEMENTWISE MULTIPLICATION ###\ntic = time.process_time()\nmul = np.mutiply(x1,x2)\ntoc = time.process_time()\n\n### VECTORIZED GENERAL DOT PRODUCT ###\ntic = time.process_time()\nmul = np.dot(W,x1)\ntoc = time.process_time()\n\ndef L1(yhat, y):\n    loss = np.sum(np.abs((y-yhat)))\n    return loss\n\ndef L2(yhat, y):\n    loss = np.sum(np.square(yhat - y))\n    return loss\n\n", "meta": {"hexsha": "317e503dfe045df2a1d338657fd72e61139b3efc", "size": 2752, "ext": "py", "lang": "Python", "max_stars_repo_path": "Neural Networks and Deep Learning/Python_basics_with_numpy.py", "max_stars_repo_name": "epintilii/deep-learning-coursera", "max_stars_repo_head_hexsha": "974794c446386e524446a10b8949db5cc547f936", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Neural Networks and Deep Learning/Python_basics_with_numpy.py", "max_issues_repo_name": "epintilii/deep-learning-coursera", "max_issues_repo_head_hexsha": "974794c446386e524446a10b8949db5cc547f936", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Neural Networks and Deep Learning/Python_basics_with_numpy.py", "max_forks_repo_name": "epintilii/deep-learning-coursera", "max_forks_repo_head_hexsha": "974794c446386e524446a10b8949db5cc547f936", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2352941176, "max_line_length": 62, "alphanum_fraction": 0.5784883721, "include": true, "reason": "import numpy", "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543365, "lm_q2_score": 0.9334308142702336, "lm_q1q2_score": 0.8996218960890978}}
{"text": "from __future__ import division\n# from math import sin, cos\nimport pylab as pl\nimport numpy as np\nfrom numpy import sin,cos\n\ndef f_dash_central_diff(f,x,h):\n    '''\n    Calculation of the first derivative \n    using the central difference formula\n    f'(x) = f(x + h) - f(x - h)\n            -------------------\n                    2*h\n    Inputs :- \n    f : The function whose first derivative is to be calculated.\n        (Assuming the function just takes 1 argument)\n    x : The value at which the number is to be calculated.\n    h : Interval around x\n\n    Output :-\n    Returns the value of f(x) with truncation error\n    ''' \n    \n    return (f(x + h) - f(x - h)) / (2 * h)\n    \n\n\nif __name__ == '__main__':\n    # The value at which the first derivative is to be calculated.\n    x = 0.5\n\n    # Interval around x \n    h = np.linspace(10 ** -8, 1, 25)\n\n\n    # The function whose derivative is to be calculated\n    f = sin\n\n    # The analytical derivative of the above function\n    f_dash = cos\n\n    # Third derivative of f\n    f_3dash = lambda x: -1 * cos(x)\n\n    # The number of datapoints for which to calculate the plot\n    # n = 250\n\n    # Data points\n    error_total = abs(f_dash_central_diff(f,x,h) - f_dash(x))\n    error_trunc = ((-1 * (h ** 2)/6) * f_3dash(x))\n    error_round = (error_total - error_trunc)\n    dp = zip(h, error_total, error_trunc, error_round)\n\n    # for _ in range(n):\n    # for hi in h:\n    #     # Calculate the value of the function \n    #     # error_total = abs(f_dash_central_diff(f, x, h) - f_dash(x))\n    #     error_total = abs(f_dash_central_diff(f, x, hi) - f_dash(x))\n\n    #     # Truncation error\n    #     # error_trunc = abs((-1 * (h ** 2)/6) * f_3dash(x))\n    #     error_trunc = abs((-1 * (hi ** 2)/6) * f_3dash(x))\n\n    #     # Rounding error\n    #     error_round = abs(error_total - error_trunc)\n\n    #     dp.append([h, error_total, error_trunc, error_round])\n    #     \n\n    #     h = h/4\n\n    # log_dp = np.log(dp)\n    # dp = log_dp\n    print(dp)\n    # pl.loglog(dp[0], dp[1], dp[0], dp[2], dp[0], dp[3])\n    # pl.plot(dp[0], dp[1], dp[0], dp[2], dp[0], dp[3])\n    pl.loglog(dp[0], dp[2])\n    pl.legend([\"$\\epsilon$\", \"$\\epsilon_t$\", \"$\\epsilon_r$\"], loc = 4)\n    pl.savefig(\"ex1.pdf\")\n    pl.show()\n    \n\n\n", "meta": {"hexsha": "7fb751c8fa69e01fdddbb2d9f237be1212909460", "size": 2259, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercise1/solution1.py", "max_stars_repo_name": "kunalghosh/BECS-114.1100-Computational-Science", "max_stars_repo_head_hexsha": "ca91ac59cb5276d213c1aec50ae7786efe72ae43", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercise1/solution1.py", "max_issues_repo_name": "kunalghosh/BECS-114.1100-Computational-Science", "max_issues_repo_head_hexsha": "ca91ac59cb5276d213c1aec50ae7786efe72ae43", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise1/solution1.py", "max_forks_repo_name": "kunalghosh/BECS-114.1100-Computational-Science", "max_forks_repo_head_hexsha": "ca91ac59cb5276d213c1aec50ae7786efe72ae43", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8928571429, "max_line_length": 71, "alphanum_fraction": 0.5692784418, "include": true, "reason": "import numpy,from numpy", "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992942089575, "lm_q2_score": 0.9294403964834655, "lm_q1q2_score": 0.89960470376564}}
{"text": "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport timeit\nimport numpy as np\n\nimport math\n\nimport random as rand\n\nclass solutions:\n\n    def take_stairs(self,n):\n        \"\"\"\n        走楼梯问题：\n        假如这里有 n 个台阶，每次你可以跨 1 个台阶或者 2 个台阶，请问走这 n 个台阶有多少种走法？\n        \n        递归解：\n        \n        1. 递推公式\n        f(n)=f(n-1)+f(n-2)\n        \n        2.递归终止条件 \n        f(1)=1\n        f(2)=1\n        \n        ref: https://time.geekbang.org/column/article/41440\n        :param n: \n        :return: \n        \"\"\"\n        if n==2 or n==1:\n            return 1\n\n        return self.take_stairs_recursion(n-1)+self.take_stairs_recursion(n-2)\n\n    def take_stairs_v2(self, n):\n        \"\"\"\n        走楼梯问题 v2\n        1.递归解，并加入 缓存机制，解决重复子问题\n        \n        :param n: \n        :return: \n        \"\"\"\n        self.cache={}\n\n        return self.__process(n)\n\n    def __process(self,n):\n\n        if n==2 or n==1:\n            return 1\n\n        if self.cache.get(n-1)==None:\n            left=self.__process(n-1)\n\n        else:\n            left=self.cache[n-1]\n\n        if self.cache.get(n - 2) == None:\n            right = self.__process(n - 2)\n\n        else:\n            right = self.cache[n - 2]\n\n        return left+right\n\n    def take_stairs_v3(self,n):\n        \"\"\"\n        走楼梯问题 v3\n        \n        动态规划解\n        1.条件：\n        （1）重复子问题\n        （2）最优子结构 \n    \n        :param n: \n        :return: \n        \"\"\"\n\n        dp=np.zeros(n+1,dtype=int)\n\n        dp[1]=1\n        dp[2]=1\n\n        for i in range(3,n+1):\n            dp[i]=dp[i-1]+dp[i-2]\n\n        return dp[n]\n\n    def take_stairs_v4(self,n):\n        \"\"\"\n        走楼梯问题 v4\n        \n        动态规划解\n        1.优化空间复杂度\n        \n        :param n: \n        :return: \n        \"\"\"\n\n        if n<=2:\n            return 1\n\n        prev=1\n        pre_prev=1\n\n        for i in range(3, n + 1):\n            current=prev+pre_prev\n\n            pre_prev=prev\n            prev = current\n\n        return current\n\n    def fab(self,n):\n\n        if n<3:\n            return 1\n        else:\n            return self.fab(n-1)+self.fab(n-2)\n\n    def fab_v1(self, n,b1=1,b2=1,c=3):\n        \"\"\"\n        具有 线性迭代过程 特性的递归——尾递归 \n        :param n: \n        :param b1: \n        :param b2: \n        :param c: \n        :return: \n        \"\"\"\n        if n<3:\n            return 1\n        else:\n            if n==c:\n                return b1+b2\n\n            else:\n                return self.fab_v1(n,b2,b1+b2,c+1)\n\nif __name__ == '__main__':\n    sol = solutions()\n\n    print(sol.take_stairs_v4(6))\n\n\n", "meta": {"hexsha": "5bbe118c62d84b79206a809b09e454a9b773c5ac", "size": 2488, "ext": "py", "lang": "Python", "max_stars_repo_path": "04_recursion/recursion_xrh.py", "max_stars_repo_name": "Xinrihui/Data-Structure-and-Algrithms", "max_stars_repo_head_hexsha": "fa3a455f64878e42d033c1fd8d612f108c71fb72", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-13T10:55:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T10:55:33.000Z", "max_issues_repo_path": "04_recursion/recursion_xrh.py", "max_issues_repo_name": "Xinrihui/Data-Structure-and-Algrithms", "max_issues_repo_head_hexsha": "fa3a455f64878e42d033c1fd8d612f108c71fb72", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "04_recursion/recursion_xrh.py", "max_forks_repo_name": "Xinrihui/Data-Structure-and-Algrithms", "max_forks_repo_head_hexsha": "fa3a455f64878e42d033c1fd8d612f108c71fb72", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0410958904, "max_line_length": 78, "alphanum_fraction": 0.4280546624, "include": true, "reason": "import numpy", "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731169394881, "lm_q2_score": 0.9343951570602081, "lm_q1q2_score": 0.8995170983003131}}
{"text": "import math\nfrom sympy import Symbol, Limit, Derivative, sympify, S, simplify, pprint, init_printing\n\ninit_printing( order = 'rev-lex', use_unicode = True )\n\n\n# 3.1.1\n\n# h(t) = e^t + 2t^2\n# simplify the expression:\n# ( h( 5 + Dt ) - h( 5 ) ) / Dt\n\nHt = math.e**t + 2*t**2\nt = Symbol( 't' )\ndelta_t = Symbol( 'delta_t' )\n\nHt1 = Ht.subs( { t: 5 } )\nHt1_delta = Ht.subs( { t: 5 + delta_t } )\n\nf = ( Ht1_delta - Ht1 ) / delta_t\n\nsimplify( f )\n\nLimit( f, delta_t, 0 ).doit()\n\n# 3.1.2\n\n# Suppose f(x) = -2x^2.\n# What is the instantaneous rate of change of f(x) when x = 4?\n\nFx = -2*x**2\nx = Symbol( 'x' )\nd = Derivative( Fx, x ).doit()\nd.subs( { x: 4 } )\n\n# 3.1.3\n\n# A particular bird's flight position in feet is given by the equation P(t) = 12t^2/7 +t, where\n# t is the number of seconds that elapse.\n# What is the bird's instantaneous velocity when t = a?\nPt = 12*t**2 / 7 + t\nt = Symbol( 't' )\na = Symbol( 'a ' )\nd = Derivative( Pt, t ).doit()\nd.subs( { t: a } )\n\n# 3.1.5\n\n# A biker rides along a horizontal straight line with its location given by the fraction,\n# s(t) = (1/10)t^2, where t is measured in minutes and s is in miles.\n# To estimate the instantaneous velocity at time t = 2 minutes, \n# compute the average rate of change from t = 1.9 to t = 2.0 minutes.\n\nSt = 1/10*t**2\nt = Symbol( 't' )\n\nt1 = 2.0\nSt1 = St.subs( { t: t1 } )\n\nt2 = 1.9\nSt2 = St.subs( { t: t2 } )\n\n( St1 - St2 ) / ( t1 - t2 )\n\n# 3.1.6\n\n# Suppose f(x) = x^2 - 3. \n# What is the slope of the line tangent to f(x), at x = 3?\n\nFx = x**2 - 3\nx = Symbol( 'x' )\nd = Derivative( Fx, x ).doit()\nd.subs( { x: 3 } )\n\n# 3.1.7\n\n# Given taht f(t) = 2t^2 - 4t and f'(x) = 4t - 4,\n# find the instantaneous rate of change at t = 3.\n\nFPx = 4*t - 4\nt = Symbol( 't' )\nFPx.subs( { t: 3 } )\n\n# 3.1.8\n\n# A bowling ball's position as it rolls down the lane is described by the position function,\n# s(t) = 5t - 1/8t**2, where t is in seconds and s(t) is in feet. What is the bowling ball's\n# instantanous velocity at t = 4?\n\nSt = 5*t - (1/8)*t**2\nt = Symbol( 't' )\nd = Derivative( St, t ).doit()\nd.subs( { t: 4 } )\n\n# 3.1.10\n\n# Consider the curve f(x) = 4x^2, 0 <= x <= 3.\n# What is the greatest possible slope of a secant line across\n# interval of width .1 ?\n\nFx = 4*x**2\nx = Symbol( 'x' )\n\ninterval = .1\np_max = 3\n\n( Fx.subs( { x: p_max } ) - Fx.subs( { x: p_max - interval } ) ) / interval\n", "meta": {"hexsha": "f0d8ca7bef56a2bfdd6919d919e3f2bc60f1eb4d", "size": 2345, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Mathematics/Calculus/Differential/ch_03/3.1.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Mathematics/Calculus/Differential/ch_03/3.1.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Mathematics/Calculus/Differential/ch_03/3.1.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.712962963, "max_line_length": 95, "alphanum_fraction": 0.5893390192, "include": true, "reason": "from sympy", "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561667674652, "lm_q2_score": 0.928408793127304, "lm_q1q2_score": 0.8994945845025283}}
{"text": "\"\"\"\n@author: Tony Lin\n@description: approximates the value of Pi by first having a circle\nof radius r inside a square of length 2r and then randomly sampling\nand counting the number of points that fall in the circle. Pi can then\nbe approximated by dividing the points in the circle by the total number\nof points and multiplying by four.\n\"\"\"\n\nimport matplotlib; matplotlib.use(\"TkAgg\")\nimport matplotlib.pyplot as plt\nimport random\nimport numpy as np\n\n\ndef check_in_circle(x, y):\n    '''\n    Checks if point is in the circle by calculating the distance from the center\n    :param x: x point\n    :param y: y point\n    :return: true if in circle, else false\n    '''\n\n    dist = (x ** 2 + y ** 2) ** 0.5\n    return dist <= 1\n\n\ndef random_point():\n    '''\n    Finds random x, y points within the dimensions\n    :return: x, y points\n    '''\n\n    x = random.uniform(-1.0, 1.0)\n    y = random.uniform(-1.0, 1.0)\n    return [x, y]\n\n\ndef plot_accuracy(num_iter, pi_values):\n    '''\n    Plots the accuracy score of Pi with respect to the number of\n    iterations. Accuracy score calculated as abs(estimated - true) / true\n    :param num_iter: number of iterations\n    :param pi_values: values of estimated Pi\n    :return: The iteration with the lowest error and the respective Pi value\n    '''\n\n    fig2, ax2 = plt.subplots()\n    accuracy_error = np.abs(np.array(pi_values) - np.pi) / np.pi\n    ax2.plot(range(0, num_iter), accuracy_error)\n    ax2.set_title(\"Accuracy of Pi Approximation Over Number of Iterations\")\n    ax2.set_xlabel(\"Number of Iterations\")\n    ax2.set_ylabel(\"Accuracy Error\")\n    fig2.canvas.draw_idle()\n    plt.show()\n\n    min_error_index = np.argmin(accuracy_error)\n    return min_error_index, pi_values[min_error_index]\n\n\ndef estimate_pi(num_iter=1000, live_plotting=False):\n    '''\n    Gets num_iter amount of random points, counts how many fall within the\n    circle of radius 1, and approximates Pi using:\n    (number of points in circle / total number of points) * 4.0\n    Option to plot the points as well as an accuracy score for each iteration\n    :param num_iter: number of iterations\n    :param live_plotting: option to display animated plotting\n    :return: approximated value of Pi\n    '''\n\n    fig1, ax1 = plt.subplots()\n    plt.xlim(-1, 1)\n    plt.ylim(-1, 1)\n    plt.draw()\n\n    pi_values = []\n    x, y, color = [], [], []\n    num_in_circle = 0.0\n    total_points = 0.0\n\n    for i in range(0, num_iter):\n        point = random_point()\n        x.append(point[0])\n        y.append(point[1])\n\n        if check_in_circle(x[i], y[i]):\n            num_in_circle += 1\n            color.append('blue')\n        else:\n            color.append('red')\n\n        total_points += 1\n\n        pi_values.append((num_in_circle / total_points) * 4.0)\n\n        if live_plotting:\n            ax1.scatter(x[i], y[i], c=color[i])\n            fig1.canvas.draw_idle()\n            plt.pause(0.1)\n\n    if not live_plotting:\n        ax1.scatter(x, y, c=color)\n        fig1.canvas.draw_idle()\n\n    min_error_index, min_error_pi = plot_accuracy(num_iter, pi_values)\n\n    return pi_values[num_iter-1], min_error_index, min_error_pi\n\n\nif __name__ == \"__main__\":\n    NUM_ITER = 100\n\n    approx_pi, min_error_index, min_error_pi = estimate_pi(num_iter=NUM_ITER, live_plotting=True)\n    print(\"The most accurate value of {} occurred at iteration {}\".format(min_error_pi, min_error_index))\n    print(\"The Pi value after {} iterations is {}\".format(NUM_ITER, approx_pi))\n", "meta": {"hexsha": "a08912c34b666ab3801b4a9768b864506e184756", "size": 3459, "ext": "py", "lang": "Python", "max_stars_repo_path": "Monte_Carlo_Pi.py", "max_stars_repo_name": "tonylin098/monte-carlo-pi", "max_stars_repo_head_hexsha": "3a047e153abf51bc07bb6ac2081f0e30dd3b5dec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Monte_Carlo_Pi.py", "max_issues_repo_name": "tonylin098/monte-carlo-pi", "max_issues_repo_head_hexsha": "3a047e153abf51bc07bb6ac2081f0e30dd3b5dec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Monte_Carlo_Pi.py", "max_forks_repo_name": "tonylin098/monte-carlo-pi", "max_forks_repo_head_hexsha": "3a047e153abf51bc07bb6ac2081f0e30dd3b5dec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5641025641, "max_line_length": 105, "alphanum_fraction": 0.6640647586, "include": true, "reason": "import numpy", "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811641488385, "lm_q2_score": 0.931462506016718, "lm_q1q2_score": 0.8992163584194136}}
{"text": "import numpy as np\n\n#Questions on NumPy Mathematics\n# How to get element-wise true division of an array using Numpy?\n#true_divide Returns a true division of the inputs, element-wise.\nnp.true_divide(np.arange(5), 4)\n\n# How to calculate the element-wise absolute value of NumPy array?\n#absolute Calculate the absolute value element-wise.\nnp.absolute(np.array([-1, -2, -3]))\n\n# Compute the negative of the NumPy array\n#negative Numerical negative, element-wise.\nnp.negative([1.,-1.])\n\n# Multiply 2d numpy array corresponding to 1d array\n(np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]]).T * np.array([0, 2, 3]) ).T \n\n# Computes the inner product of two arrays\n#inner Inner product of two arrays.\nnp.inner(np.array([[1, 4], [5, 6]]), np.array([[2, 4], [5, 2]]))\n\n# Compute the nth percentile of the NumPy array\n#percentile Compute the q-th percentile of the data along the specified axis.\nnp.percentile(np.array([[10, 7, 4], [3, 2, 1]]), 50)\n\n# Calculate the n-th order discrete difference along the given axis\n#diff Calculate the n-th discrete difference along the given axis.\nnp.diff(np.array([1, 2, 4, 7, 0]))\n\n# Calculate the sum of all columns in a 2D NumPy array\n#sum Sum of array elements over a given axis.\nnp.sum([[1.2, 2.3], [3.4, 4.5]] , axis = 0)\n\n# Calculate average values of two given NumPy arrays\narr1 = np.array([[3, 4], [8, 2]]) \narr2 = np.array([[1, 0], [6, 6]]) \navg = (arr1 + arr2) / 2\navg\n\n# How to compute numerical negative value for all elements in a given NumPy array?\nnp.negative(np.array([-1, -2, -3,  1, 2, 3, 0])) \n\n# How to get the floor, ceiling and truncated values of the elements of a numpy array?\n#floor Return the floor of the input, element-wise.\n#ceil Return the ceiling of the input, element-wise.\n#trunc The truncated of each element, with float data-type\nnp.floor(np.array([-1.8, -1.6, -0.5, 0.5, 1.6, 1.8, 3.0])) \nnp.ceil(np.array([-1.8, -1.6, -0.5, 0.5, 1.6, 1.8, 3.0])) \nnp.trunc(np.array([-1.8, -1.6, -0.5, 0.5, 1.6, 1.8, 3.0])) \n\n# How to round elements of the NumPy array to the nearest integer?\n# rint Round elements of the array to the nearest integer.\nnp.rint(np.array([0.2, 0.3, 0.4, 0.5, 0.6, 0.7])) \n\n# Find the round off the values of the given matrix\n#matrix.round  Return rounded values in matrix\nnp.matrix('[6.4, 1.3; 12.7, 32.3]').round()\n\n# Determine the positive square-root of an array\n#sqrt Returns the square root of the number in an array.\nnp.sqrt([1, 4, 9, 16]) \n\n# Evaluate Einstein’s summation convention of two multidimensional NumPy arrays\n#einsum Evaluates the Einstein summation convention on the operands.\nnp.einsum(\"mk,kn\", np.array([[1, 2], [0, 2]]) , np.array([[0, 1], [3, 4]]) ) ", "meta": {"hexsha": "c2a014af27ec8f2fbe48dbc990bf6830f97981bc", "size": 2647, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumpyTutorial/Questions on NumPy Mathematics.py", "max_stars_repo_name": "CarlosW1998/DigitalImageProcessing", "max_stars_repo_head_hexsha": "69365877e07b676f13487585ffdf029a243b0fa8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-09T19:54:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:54:48.000Z", "max_issues_repo_path": "NumpyTutorial/Questions on NumPy Mathematics.py", "max_issues_repo_name": "CarlosW1998/DigitalImageProcessingClass", "max_issues_repo_head_hexsha": "69365877e07b676f13487585ffdf029a243b0fa8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumpyTutorial/Questions on NumPy Mathematics.py", "max_forks_repo_name": "CarlosW1998/DigitalImageProcessingClass", "max_forks_repo_head_hexsha": "69365877e07b676f13487585ffdf029a243b0fa8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1060606061, "max_line_length": 86, "alphanum_fraction": 0.6845485455, "include": true, "reason": "import numpy", "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9814534382002796, "lm_q2_score": 0.9161096198879968, "lm_q1q2_score": 0.8991189362074257}}
{"text": "'''\n        # Numpy\n\n- Numeric Python\n- Alternative array to Pthon array: Numpy Array\n- Calculations overy entire array\n\npip3 install numpy\n'''\n\nimport numpy as np\n\nweight = [52, 51, 66, 71, 67, 123]\nheight = [1.56, 1.47, 1.66, 1.81, 1.75, 2]\n\nnp_weight = np.array(weight)\nnp_height = np.array(height)\nprint(np_weight)\nprint(np_height)\n\n## weight / height ** 2 syntax error\nbmi = np_weight / np_height ** 2\nprint(bmi)\n\n# np arrays can contain one data type\n# x = np.array('x',12,23.4,True) # TypeError\n\n\npython_list = [1, 2, 3]\nnumpy_array = np.array([1, 2, 3])\n\npython_list + python_list  # [1, 2, 3, 1, 2, 3]\nnumpy_array + numpy_array  # array([2, 4, 6])\n\nprint(bmi)  # [21.36752137 23.60127725 23.95122659 21.67211013 21.87755102 30.75      ]\nprint(bmi > 22)  # [False  True  True False False  True]\nprint(bmi[bmi > 21.7])  # [23.60127725 23.95122659 21.87755102 30.75      ]\n\n# 2D NUMPY ARRAYS\n\nprint(type(np_height))  # np_height_in[100:111] => n-dimensional array\n\nnp_2d = np.array([[1.73, 1.68, 1.71, 1.89, 1.79],\n                  [65.4, 59.2, 63.6, 88.4, 68.7]])\n\nprint(np_2d.shape)  # (2, 5) 2 row 5 column\nnp_2d[0, 3]  # np_2d[0][3]\n\nprint(np_2d[:, 1:4])\n# [[ 1.68  1.71  1.89]\n# [59.2  63.6  88.4 ]]\n\nprint(np_2d[1, :])  # [65.4 59.2 63.6 88.4 68.7]\n\nnp_mat = np.array([[1, 2],\n                   [3, 4],\n                   [5, 6]])\n\nnp_mat * 2  # array([[ 2,  4],[ 6,  8],[10, 12]])\n\n# Numpy Statistics\nnp_city = np.array([[1.64, 71.78],\n                    [1.37, 63.35],\n                    [1.6, 55.09],\n                    [2.04, 74.85],\n                    [2.04, 68.72],\n                    [2.01, 73.57]])\n\nmean_val = np.mean(np_city[:, 0])  # all member sums / count\nprint(np_city[:, 0])  # [1.64 1.37 1.6  2.04 2.04 2.01]\nprint(mean_val)  # 1.7833333333333332\n\nmedian_val = np.median(np_city[:, 0])\nprint(median_val)  # middle val, if 2 mid child sums/2\n\nprint(np.corrcoef(np_city[:, 0], np_city[:, 1]))  # Function that returns a matrix of\n# correlations of x with x, x with y, y with x and y with y. # TODO: I will check this out later\n\nprint(np.std(np_city[:, 0]))  # standart deviation 0.2608107018935807\n\n# .sum() .sort() in numpy calculations faster because array has 1 type of data\n\n'''\n# heights and positions are available as lists\n\n# Import numpy\nimport numpy as np\n\n# Convert positions and heights to numpy arrays: np_positions, np_heights\nnp_positions = np.array(positions)\nnp_heights = np.array(heights)\n\n\n# Heights of the goalkeepers: gk_heights\ngoalkeepers_indexes = np.array(np_positions == 'GK')\n#print(goalkeepers_indexes)\n#print(np_heights[goalkeepers_indexes])\ngk_heights = np_heights[goalkeepers_indexes]\n\n# Heights of the other players: other_heights\nother_indexes = np_positions != 'GK'\nother_heights = np_heights[other_indexes]\n\n# Print out the median height of goalkeepers. Replace 'None'\nprint(\"Median height of goalkeepers: \" + str(np.median(gk_heights)))\n\n# Print out the median height of other players. Replace 'None'\nprint(\"Median height of other players: \" + str(np.median(other_heights)))\n'''\n", "meta": {"hexsha": "314bdd1cdd2228a4beb3f525272b35e1fa67b4f3", "size": 3047, "ext": "py", "lang": "Python", "max_stars_repo_path": "Day 12 Numpy/1- Numpy.py", "max_stars_repo_name": "ServerCetin/hello_python3", "max_stars_repo_head_hexsha": "7cf0807e09c819c690f28ee30758f22355c79115", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Day 12 Numpy/1- Numpy.py", "max_issues_repo_name": "ServerCetin/hello_python3", "max_issues_repo_head_hexsha": "7cf0807e09c819c690f28ee30758f22355c79115", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 12 Numpy/1- Numpy.py", "max_forks_repo_name": "ServerCetin/hello_python3", "max_forks_repo_head_hexsha": "7cf0807e09c819c690f28ee30758f22355c79115", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7, "max_line_length": 96, "alphanum_fraction": 0.637676403, "include": true, "reason": "import numpy", "num_tokens": 1068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96323053709097, "lm_q2_score": 0.9334308096406118, "lm_q1q2_score": 0.8991090601073854}}
{"text": "import torch\nimport numpy as np\n\n\"\"\"\n\nExercise 1.1: Diagonal Gaussian Likelihood\n\nWrite a function that takes in PyTorch Tensors for the means and \nlog stds of a batch of diagonal Gaussian distributions, along with a \nPyTorch Tensor for (previously-generated) samples from those \ndistributions, and returns a Tensor containing the log \nlikelihoods of those samples.\n\n\"\"\"\n\ndef gaussian_likelihood(x, mu, log_std):\n    \"\"\"\n    Args:\n        x: Tensor with shape [batch, dim]\n        mu: Tensor with shape [batch, dim]\n        log_std: Tensor with shape [batch, dim] or [dim]\n\n    Returns:\n        Tensor with shape [batch]\n    \"\"\"\n    # Referencing the Log-Likelihood equation from the [documentation](https://spinningup.openai.com/en/latest/spinningup/rl_intro.html)\n\n    if len(x.shape) == 1:\n        x = torch.unsqueeze(x, dim=0)\n\n    batch, dim = x.shape\n    \n    squared_diff = (x - mu)**2 # shape [batch, dim]\n    std = torch.exp(log_std) # shape [batch, dim] or [dim]\n\n    # I had to check with the solution to figure out I needed to add 1E-8 to std\n    diff_std_ratio = squared_diff / (std + 1E-8)**2 # shape [batch, dim]\n\n    summed = torch.sum(diff_std_ratio + 2*log_std, dim=1) # shape [batch]\n    log_likelihood = -0.5*(summed + dim*np.log(2*np.pi)) # shape [batch]\n    return log_likelihood\n\n\nif __name__ == '__main__':\n    \"\"\"\n    Run this file to verify your solution.\n    \"\"\"\n    from spinup.exercises.pytorch.problem_set_1_solutions import exercise1_1_soln\n    from spinup.exercises.common import print_result\n\n    batch_size = 32\n    dim = 10\n\n    x = torch.rand(batch_size, dim)\n    mu = torch.rand(batch_size, dim)\n    log_std = torch.rand(dim)\n\n    your_gaussian_likelihood = gaussian_likelihood(x, mu, log_std)\n    true_gaussian_likelihood = exercise1_1_soln.gaussian_likelihood(x, mu, log_std)\n\n    your_result = your_gaussian_likelihood.detach().numpy()\n    true_result = true_gaussian_likelihood.detach().numpy()\n\n    correct = np.allclose(your_result, true_result)\n    print_result(correct)", "meta": {"hexsha": "6d2d84ce9d2d9f22438c477e1b36ec6be55f5e85", "size": 2014, "ext": "py", "lang": "Python", "max_stars_repo_path": "spinup/exercises/pytorch/problem_set_1/exercise1_1.py", "max_stars_repo_name": "billray0259/spinningup", "max_stars_repo_head_hexsha": "31d20b80e3bd2531d906cef72cc9adcfa2a11696", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spinup/exercises/pytorch/problem_set_1/exercise1_1.py", "max_issues_repo_name": "billray0259/spinningup", "max_issues_repo_head_hexsha": "31d20b80e3bd2531d906cef72cc9adcfa2a11696", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spinup/exercises/pytorch/problem_set_1/exercise1_1.py", "max_forks_repo_name": "billray0259/spinningup", "max_forks_repo_head_hexsha": "31d20b80e3bd2531d906cef72cc9adcfa2a11696", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9846153846, "max_line_length": 136, "alphanum_fraction": 0.6931479643, "include": true, "reason": "import numpy", "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075755433747, "lm_q2_score": 0.934395157060208, "lm_q1q2_score": 0.8989886591586675}}
{"text": "import numpy as np\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\ndef L(A, normalized=True, verbose=False):\n    \"\"\"L: compute a graph laplacian\n\n    Args:\n        A (N x N np.ndarray): Adjacency matrix of graph\n        normalized (bool, optional): Normalized or combinatorial Laplacian\n\n    Returns:\n        L (N x N np.ndarray): graph Laplacian\n    \"\"\"\n    # Compute the degree as D = diag(d(i)), d(i)=sum_{j=1}^N W_ij\n    if verbose: print('A: {}'.format(A))\n    D = np.sum(A, axis=0) # row sum\n    if verbose: print('D: {}'.format(D))\n    L = np.diag((D))-A\n    if normalized:\n        D_right = np.diag((D)**-0.5)\n        D_left = np.diag((D)**-0.5)\n        L = np.matmul(D_right, np.matmul(L,D_left)) # Normalized Markov matrix\n    if verbose: print('L: {}'.format(L))\n    return L\n    \ndef SC(L, k, psi=None, nrep=5, itermax=300, show_plot=True, topK = 5, verbose=False):\n    \"\"\"SC: Perform spectral clustering via the Ng method\n    Args:\n        L (np.ndarray): Normalized graph Laplacian\n        k (integer): number of clusters to compute. If k=None, estimate k based on eigengap\n        nrep (int): Number of repetitions to average for final clustering\n        itermax (int): Number of iterations to perform before terminating\n        show_plot: Plot eigenvalues if True\n        topK: shows up to K optimal number of clusters\n    Returns:\n        labels (N x 1 np.array): Learned cluster labels\n    \"\"\"\n    if psi is None:\n        # compute the first k elements of the Fourier basis\n        e, psi = np.linalg.eigh(L) # Compute eigendecomposition\n        psi_k = psi[:, :k]\n\n    else:  # just grab the first k eigenvectors\n        psi_k = psi[:, :k]\n\n    # normalize your eigenvector rows\n    psi_norm = psi_k / np.linalg.norm(psi_k, axis=1, keepdims=True)\n    if verbose:\n        print('psi_k: {}'.format(psi_k))\n        print('psi_norm: {}'.format(psi_norm))\n        print('np.sum(psi_norm[0,:]**2): {}'.format(np.sum(psi_norm[0,:]**2)))\n    \n    if show_plot:\n        fig,ax=plt.subplots(figsize=(10,10))\n        plt.title('Largest eigenvalues of input matrix')\n        plt.scatter(np.arange(1, 1+len(e)), e)\n        plt.xlabel(\"Eigenval\")\n        plt.ylabel(\"Value\")\n        plt.grid()\n        \n    # Identify the optimal number of clusters as the index corresponding\n    # to the larger gap between eigen values\n    inLargestGap = np.argsort(np.diff(e))[::-1][:topK]\n    inNclusters = inLargestGap + 1\n    if verbose: print('Optimal number of clusters: ', inNclusters)\n        \n    if k is None:\n        k = inNclusters[0] #Get the index for the largest gap\n\n    labels = KMeans(n_clusters=k, n_init=nrep,  max_iter=itermax).fit_predict(psi_norm)\n    \n    return labels, inNclusters\n", "meta": {"hexsha": "b95556d60ebc9bf5961659116fb926d3e4c2cda3", "size": 2744, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/Pipeline/Utilities/CBASS_U_SpectralClustering.py", "max_stars_repo_name": "cardin-higley-lab/CBASS", "max_stars_repo_head_hexsha": "0d0b58497313027388351feffc79766f815b47b5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/Pipeline/Utilities/CBASS_U_SpectralClustering.py", "max_issues_repo_name": "cardin-higley-lab/CBASS", "max_issues_repo_head_hexsha": "0d0b58497313027388351feffc79766f815b47b5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/Pipeline/Utilities/CBASS_U_SpectralClustering.py", "max_forks_repo_name": "cardin-higley-lab/CBASS", "max_forks_repo_head_hexsha": "0d0b58497313027388351feffc79766f815b47b5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5866666667, "max_line_length": 91, "alphanum_fraction": 0.6271865889, "include": true, "reason": "import numpy", "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241965169939, "lm_q2_score": 0.9273632886204559, "lm_q1q2_score": 0.8989156746213806}}
{"text": "import numpy as np\n\n\n\"\"\"\nResidual Sum of Squares\n\"\"\"\ndef rss(y: np.ndarray, y_hat: np.ndarray):\n    return ((y - y_hat)**2).sum()\n\n\n\"\"\"\nDerivative of Residual Sum of Squares\n\"\"\"\ndef drss(y: np.ndarray, y_hat: np.ndarray):\n    return (-2*y + 2*y_hat).sum()\n\n\n\"\"\"\nRoot Mean Square Error\n\"\"\"\ndef rmse(y_hat: np.ndarray, y: np.ndarray):\n    return  (((y_hat - y)**2).sum() / y_hat.shape[0])**.5\n \n\n\"\"\"\nMean Absolute Error\n\"\"\"\ndef mae(y_hat: np.ndarray, y: np.ndarray):\n    return np.abs((y_hat - y).sum()) / y_hat.shape[0]\n\n\n\"\"\"\nThe higher the norm degree, the more it\nfocuses on larger values and neglects small\nones.\n\nFor example: l2 norm, or RMSE is more\nsensitive to outliers than l1.\n\"\"\"\nl2_norm = rmse\nl1_norm = mae\n\n\nif __name__ == \"__main__\":\n    y_hat1 = np.array([0, 1, 2, 3, 4, 5, 6, 7])\n    y_hat2 = np.array([0, 2, 4, 7, 15, 32, 59, 128])\n    y_hat3 = np.array([0, 2, 4, 8, 16, 32, 64, 128])\n    y = np.array([0, 2, 4, 8, 16, 32, 64, 128])\n    \n    print(\"rmse y_hat1:\", rmse(y_hat1, y))\n    print(\"rmse y_hat2:\", rmse(y_hat2, y))\n    print(\"rmse y_hat3:\", rmse(y_hat3, y))\n    print()\n    print(\"mae y_hat1:\", mae(y_hat1, y))\n    print(\"mae y_hat2:\", mae(y_hat2, y))\n    print(\"mae y_hat3:\", mae(y_hat3, y))\n", "meta": {"hexsha": "4f8238d6b49430745ac6cdd536dd8541eea9def0", "size": 1218, "ext": "py", "lang": "Python", "max_stars_repo_path": "positron/scoring.py", "max_stars_repo_name": "MartinKondor/positron", "max_stars_repo_head_hexsha": "350bbd89b5293478571c04b3604f4167ef23e1ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "positron/scoring.py", "max_issues_repo_name": "MartinKondor/positron", "max_issues_repo_head_hexsha": "350bbd89b5293478571c04b3604f4167ef23e1ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "positron/scoring.py", "max_forks_repo_name": "MartinKondor/positron", "max_forks_repo_head_hexsha": "350bbd89b5293478571c04b3604f4167ef23e1ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3684210526, "max_line_length": 57, "alphanum_fraction": 0.5993431856, "include": true, "reason": "import numpy", "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773707966712549, "lm_q2_score": 0.9196425234694067, "lm_q1q2_score": 0.8988317458160573}}
{"text": "# Jacobi iterative method to solve linear system\r\n# Jacobi implements the regular method\r\n# SparseJacobi implements the Jacobi method using CSR storage and sparse matrix multiplication\r\n\r\nimport numpy as np\r\nfrom pprint import pprint\r\nfrom sparse_methods import MatrixtoCSR, SparseGet\r\nfrom operations import MMultiply, SparseDot\r\nimport time\r\n\r\ndef Jacobi(A, b, error_tol=10e-6):\r\n    t1 = time.time()\r\n    (m, n) = np.shape(A)\r\n    x = np.zeros_like(b)\r\n    x_prev = np.zeros_like(b)\r\n    error = float('Inf')\r\n    itr = 0\r\n    while error > error_tol:\r\n        for i in range(m):\r\n            sigma = MMultiply(A[i], x_prev)\r\n            sigma -= A[i][i]*x_prev[i]\r\n            x[i] = (b[i] - sigma)/A[i][i]\r\n        \r\n        x_prev = x\r\n        error = sum(abs(MMultiply(A, x) - b))\r\n        itr += 1\r\n    t2 = time.time() - t1        \r\n    return x, error, itr, t2\r\n\r\ndef SparseJacobi(Acsr, b, error_tol=10e-6):\r\n    t1 = time.time()\r\n    m = Acsr['m']\r\n    x = np.zeros_like(b)\r\n    x_prev = np.zeros_like(b)\r\n    D = np.zeros(m, dtype=Acsr['A'].dtype)\r\n    for i in range(m):\r\n        D[i] = SparseGet(Acsr, i, i)\r\n        #D = Acsr.diagonal()\r\n\r\n    error = sum(abs(SparseDot(Acsr, x) - b))\r\n    print (0, error)\r\n    Error = [error]\r\n    itr = 0\r\n    while error > error_tol:\r\n        for i in range(m):\r\n            sigma = SparseDot(Acsr, x_prev, i)\r\n            sigma -= D[i]*x_prev[i]\r\n            x[i] = (b[i] - sigma)/D[i]\r\n            \r\n        x_prev = x\r\n        error = sum(abs(SparseDot(Acsr, x) - b))\r\n        Error.append(error)\r\n        print (itr+1, error)\r\n        itr += 1\r\n    \r\n    t2 = time.time() - t1\r\n    print(t2)    \r\n    return x#, Error, itr, t2\r\n\r\n# Test cases\t\r\nif __name__ == \"__main__\":\r\n    A = np.array([[10., -1., 2., 0.],\r\n              [-1., 11., -1., 3.],\r\n              [2., -1., 10., -1.],\r\n              [0.0, 3., -1., 8.]], dtype=np.float64)\r\n    Acsr = MatrixtoCSR(A)\r\n    b = np.array([6., 25., -11., 15.])\r\n    #x, error, itr = Jacobi(A, b, 1e-10)\r\n    xsp = SparseJacobi(Acsr, b, 10e-6)\r\n    #print (\"Error:\", error, errorsp)\r\n    #print (\"Iters:\", itr, itrsp)\r\n    print (\"x =\", xsp)", "meta": {"hexsha": "dbfa73611123311109cd29c655e63f5c3de69cf7", "size": 2139, "ext": "py", "lang": "Python", "max_stars_repo_path": "jacobi.py", "max_stars_repo_name": "AntonValk/Matrix-Vector-Equation-Neural-Network-Solution-Approximation", "max_stars_repo_head_hexsha": "ed4ddfa95dcf7ecdb12f169604ba4ebaa1d8966b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-03T03:49:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-03T03:49:43.000Z", "max_issues_repo_path": "jacobi.py", "max_issues_repo_name": "AntonValk/Matrix-Vector-Equation-Neural-Network-Solution-Approximation", "max_issues_repo_head_hexsha": "ed4ddfa95dcf7ecdb12f169604ba4ebaa1d8966b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jacobi.py", "max_forks_repo_name": "AntonValk/Matrix-Vector-Equation-Neural-Network-Solution-Approximation", "max_forks_repo_head_hexsha": "ed4ddfa95dcf7ecdb12f169604ba4ebaa1d8966b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7083333333, "max_line_length": 95, "alphanum_fraction": 0.5123889668, "include": true, "reason": "import numpy", "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.9441768612215684, "lm_q1q2_score": 0.8987272357593231}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 21 01:16:05 2021\n\n@author: Mahfuz_Shazol\n\"\"\"\n\nimport numpy as np\n\n#formula  A=V (A_lambda(Diagonal Matrix)) V**-1\n\n\nA=np.array([\n            [4.,2.],\n            [-5.,-3.]\n          ])\n\nprint(A)\n#V\nlambdas,V=np.linalg.eig(A) \nprint('lambdas',lambdas)\nprint('V',V)\n#V**-1\ninv_V=np.linalg.inv(V)\n\n\ndiago_lambdas=np.diag(lambdas)\nprint('diago_lambdas',diago_lambdas)\n\nresult=np.dot(V,np.dot(diago_lambdas,inv_V))\nprint(result)\n\nprint((A==result).all())\n\n\n\n\n#if A is real No matrix then without using inverse we can Tanspose like\n# formula  A= Q (A_lambda(Diagonal Matrix)) Q**T\n\nA=np.array([\n            [2.,1],\n            [1.,2]\n          ])\n\n\nlambdas,Q=np.linalg.eig(A)\nA_lambda=np.diag(lambdas)\nQ_T=Q.T\n\nresult_of_real_matrix=np.dot(Q,np.dot(A_lambda,Q_T))\nprint(result_of_real_matrix)\nprint((A==result_of_real_matrix).all())\n\n\nI=np.dot(Q,Q_T)\nprint(I)\n\nI=np.dot(Q_T,Q)\nprint(I)\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "65f11b03c2bd23ddfbd89634a1cab2276d7e1725", "size": 936, "ext": "py", "lang": "Python", "max_stars_repo_path": "eigen_decomposition_using_numpy.py", "max_stars_repo_name": "6895mahfuzgit/Linear_Algebra_for_Machine_Learning", "max_stars_repo_head_hexsha": "3f266391491d9ab99e53a3547900c6b1bd657af1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eigen_decomposition_using_numpy.py", "max_issues_repo_name": "6895mahfuzgit/Linear_Algebra_for_Machine_Learning", "max_issues_repo_head_hexsha": "3f266391491d9ab99e53a3547900c6b1bd657af1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigen_decomposition_using_numpy.py", "max_forks_repo_name": "6895mahfuzgit/Linear_Algebra_for_Machine_Learning", "max_forks_repo_head_hexsha": "3f266391491d9ab99e53a3547900c6b1bd657af1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.3714285714, "max_line_length": 71, "alphanum_fraction": 0.625, "include": true, "reason": "import numpy", "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140216112959, "lm_q2_score": 0.9294403994151622, "lm_q1q2_score": 0.8986889544465236}}
{"text": "import numpy as np\nfrom scipy.integrate import solve_ivp\nfrom scipy.optimize import OptimizeResult\nfrom typing import List, Union\n\n\n# The SIR model differential equations.\ndef sir(t: float, y: List[float, float, float], N: Union[int, float], beta: float, gamma: float):\n    \"\"\"\n    System of ODE for the Susceptible-Infected-Recovered model without vital kinetics\n    Parameters\n    ----------\n    t: float\n        The time in days\n    y: List[float, float, float]\n    N: int\n        The total population\n    beta: float\n        The contact rate of the disease (1/days)\n    gamma: float\n        The recovery rate of the disease (1/days)\n\n    Returns\n    -------\n    List[float, float, flaot]\n        dS/dt, dI/dt, dR/dt\n    \"\"\"\n    S, I, R = y\n    dSdt = -beta * S * I / N\n    dIdt = beta * S * I / N - gamma * I\n    dRdt = gamma * I\n    return [dSdt, dIdt, dRdt]\n\n\ndef sir_model(t: np.ndarray, N: int, beta: float, gamma: float, **kwargs):\n    \"\"\"\n    Solves the Susceptible-Infected-Removed ODE\n    \n    Parameters\n    ----------\n    t: np.ndarray\n        The time (days)\n    N: int\n        The total population\n    beta: float\n        The contact rate of the disease (1/days)\n    gamma: float\n        The recovery rate of the disease (1/days)\n    kwargs: keyword arguments\n        I0: int\n            The initial number of infected individuals\n        R0: int\n            The initial number of recovered individuals\n\n    Returns\n    -------\n    OptimizeResult:\n        The solution\n    \"\"\"\n\n    I0 = kwargs.get('I0', 1)\n    R0 = kwargs.get('R0', 0)\n\n    #    # Total population, N.\n    #    N = 1000\n    #    # Initial number of infected and recovered individuals, I0 and R0.\n    #    I0, R0 = 1, 0\n    #    # Everyone else, S0, is susceptible to infection initially.\n    S0 = N - I0 - R0\n    #    # Contact rate, beta, and mean recovery rate, gamma, (in 1/days).\n    #    beta, gamma = 0.2, 1./10\n    #    # A grid of time points (in days)\n\n    # Initial conditions vector\n    y0 = S0, I0, R0\n    # Integrate the SIR equations over the time grid, t.\n    # ret = odeint(deriv, y0, t, args=(N, beta, gamma))\n    sol = solve_ivp(sir, [np.amin(t), np.amax(t)], y0, t_eval=t,\n                    args=(N, beta, gamma),\n                    method='DOP853',\n                    dense_output=True)\n\n    return sol\n", "meta": {"hexsha": "59d1a2192b919cc932e5d76235e0502543b02b5e", "size": 2310, "ext": "py", "lang": "Python", "max_stars_repo_path": "epydemics/sir_model.py", "max_stars_repo_name": "erickmartinez/epydemics", "max_stars_repo_head_hexsha": "48100a0b42ac6797a5607a91299f1b4cf27e96bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "epydemics/sir_model.py", "max_issues_repo_name": "erickmartinez/epydemics", "max_issues_repo_head_hexsha": "48100a0b42ac6797a5607a91299f1b4cf27e96bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "epydemics/sir_model.py", "max_forks_repo_name": "erickmartinez/epydemics", "max_forks_repo_head_hexsha": "48100a0b42ac6797a5607a91299f1b4cf27e96bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5, "max_line_length": 97, "alphanum_fraction": 0.5744588745, "include": true, "reason": "import numpy,from scipy", "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.977022630759019, "lm_q2_score": 0.919642526773001, "lm_q1q2_score": 0.8985115608656289}}
{"text": "import numpy as np\n\n# generates random data\nheight = np.round(np.random.normal(1.75, 0.20, 5000), 2)\nweight = np.round(np.random.normal(60.32, 15, 5000), 2)\n\nnp_city = np.column_stack((height, weight))\n\n# average\n\n# Print mean height (first column)\navg = np.mean(np_city[:, 0])\nprint(\"Average: \" + str(avg))\n\n# Print median height. Replace 'None'\nmed = np.median(np_city[:, 0])\nprint(\"Median: \" + str(med))\n\n# Print out the standard deviation on height. Replace 'None'\nstddev = np.std(np_city[:, 0])\nprint(\"Standard Deviation: \" + str(stddev))\n\n# Print out correlation between first and second column. Replace 'None'\ncorr = np.corrcoef(np_city[:, 0], np_city[:, 1])\nprint(\"Correlation: \" + str(corr))\n\n\"\"\"\n\n# Convert positions and heights to numpy arrays: np_positions, np_heights\nnp_heights = np.array(heights)\nnp_positions = np.array(positions)\n\n# Heights of the goalkeepers: gk_heights\ngk_heights = np_heights[np_positions == \"GK\"]\n\n# Heights of the other players: other_heights\nother_heights = np_heights[np_positions != \"GK\"]\n\n# Print out the median height of goalkeepers. Replace 'None'\nprint(\"Median height of goalkeepers: \" + str(np.median(gk_heights)))\n\n# Print out the median height of other players. Replace 'None'\nprint(\"Median height of other players: \" + str(np.median(other_heights)))\n\"\"\"\n", "meta": {"hexsha": "7c036fa8afab244926a4babbbfbaed26c6106027", "size": 1304, "ext": "py", "lang": "Python", "max_stars_repo_path": "datascience/numeric_python/two_dimension/statistics.py", "max_stars_repo_name": "JASTYN/pythonmaster", "max_stars_repo_head_hexsha": "46638ab09d28b65ce5431cd0759fe6df272fb85d", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-05-02T10:28:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-06T09:10:11.000Z", "max_issues_repo_path": "datascience/numeric_python/two_dimension/statistics.py", "max_issues_repo_name": "JASTYN/pythonmaster", "max_issues_repo_head_hexsha": "46638ab09d28b65ce5431cd0759fe6df272fb85d", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-06-21T20:39:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-25T10:28:57.000Z", "max_forks_repo_path": "datascience/numeric_python/two_dimension/statistics.py", "max_forks_repo_name": "JASTYN/pythonmaster", "max_forks_repo_head_hexsha": "46638ab09d28b65ce5431cd0759fe6df272fb85d", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-07-29T04:35:22.000Z", "max_forks_repo_forks_event_max_datetime": "2017-01-18T17:05:36.000Z", "avg_line_length": 28.9777777778, "max_line_length": 73, "alphanum_fraction": 0.7185582822, "include": true, "reason": "import numpy", "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9820137910906878, "lm_q2_score": 0.9149009480320036, "lm_q1q2_score": 0.8984453484493722}}
{"text": "from sympy import *\nimport numpy as np\nfrom tqdm import tqdm\n\nclass dh_solver():\n    def __init__(self):\n        self.joints_list = []\n        self.T_list = []\n        self.T = eye(4)\n        self.T_sub = eye(4)\n    \n    def add(self,dh_param):\n        if len(dh_param)!=4:\n            raise ValueError('the number of input dh parameters !=4, it should be structure as [d,theta,a, alpha].')\n        else:\n            self.joints_list.append(dh_param)\n            \n    def dh_matrix(self,parameters):\n        d,theta,a, alpha = parameters\n        #first row\n        dh11 = cos(theta)\n        dh12 =  -1*sin(theta)*cos(alpha)\n        dh13 = sin(theta)*sin(alpha)\n        dh14 =  a*cos(theta)\n        #second row\n        dh21 = sin(theta)\n        dh22 = cos(theta)*cos(alpha)\n        dh23 = -1*cos(theta)*sin(alpha)\n        dh24 = a*sin(alpha)\n        #third row\n        dh31 =  0\n        dh32 =  sin(alpha)\n        dh33 =  cos(alpha)\n        dh34 =  d\n        #forth row\n        dh41 = 0\n        dh42 = 0\n        dh43 = 0\n        dh44 = 1    \n        return Matrix([[dh11, dh12, dh13, dh14],\n                     [dh21, dh22, dh23, dh24],\n                     [dh31, dh32, dh33, dh34],\n                     [dh41, dh42, dh43, dh44]])\n\n    def calc_symbolic_matrices(self):\n        self.T_list = []\n        self.T = eye(4)\n        for i in tqdm(range(len(self.joints_list))):\n            d = Symbol(\"d\"+str(i+1))\n            theta = Symbol(\"theta\"+str(i+1))\n            a = Symbol(\"a\"+str(i+1))\n            alpha = Symbol(\"alpha\"+str(i+1))\n            parameters = [d,theta,a,alpha]\n            Tn = self.dh_matrix(parameters)\n            self.T_list.append(Tn)\n            self.T=self.T*Tn\n        return self.T\n\n    def calc_dh_matrix(self):\n        self.calc_symbolic_matrices()\n        self.T_sub = self.T\n        for i in tqdm(range(len(self.joints_list))):\n            ds = \"d\"+str(i+1)\n            thetas = \"theta\"+str(i+1)\n            a_s = \"a\"+str(i+1)\n            alphas = \"alpha\"+str(i+1)\n            parameters = [ds,thetas,a_s,alphas]\n            for pair in zip(parameters,self.joints_list[i]):\n#                 print(pair)\n                self.T_sub = self.T_sub.subs(pair[0], pair[1])\n        return self.T_sub\n    \n    def get_numpy_matrix(self, list_subs):\n#         self.calc_dh_matrix()\n        T = (self.T_sub.subs(list_subs)).evalf()\n        return np.array(T.tolist()).astype(np.float64)\n\n", "meta": {"hexsha": "968437b367fa59264a420c70b3fca511d16a3609", "size": 2410, "ext": "py", "lang": "Python", "max_stars_repo_path": "dh.py", "max_stars_repo_name": "afakharany93/DH_Matrix_Python", "max_stars_repo_head_hexsha": "97e29d5b14511f68884a89852d014b010aa4e0f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dh.py", "max_issues_repo_name": "afakharany93/DH_Matrix_Python", "max_issues_repo_head_hexsha": "97e29d5b14511f68884a89852d014b010aa4e0f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dh.py", "max_forks_repo_name": "afakharany93/DH_Matrix_Python", "max_forks_repo_head_hexsha": "97e29d5b14511f68884a89852d014b010aa4e0f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8974358974, "max_line_length": 116, "alphanum_fraction": 0.5074688797, "include": true, "reason": "import numpy,from sympy", "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9793540722737479, "lm_q2_score": 0.9173026573249612, "lm_q1q2_score": 0.8983640929587311}}
{"text": "import numpy as np\nfrom math import sqrt\n\ndef rk4(f, x0, y0, x1, n): #Runge-Kutta fourth order\n    #vx = [0] * (n + 1)\n    vx=np.zeros((n+1,1)) #using numpy array instead of above list\n    #print(vx) #for debugging only\n    #vy = [0] * (n + 1)\n    vy=np.zeros((n+1,1)) #using numpy array instead of above list\n    #print(vy) #for debugging only\n    h = (x1 - x0) / float(n)\n    vx[0] = x = x0 #x0 in (x0,x1)\n    vy[0] = y = y0 #initial condition y(x=x0)=y0\n    for i in range(1, n + 1): #RK4 loop\n        k1 = h * f(x, y) #calls function f(x,y) and evaluates it with x and y values\n        k2 = h * f(x + 0.5 * h, y + 0.5 * k1)\n        k3 = h * f(x + 0.5 * h, y + 0.5 * k2)\n        k4 = h * f(x + h, y + k3)\n        vx[i] = x = x0 + i * h\n        vy[i] = y = y + (k1 + k2 + k2 + k3 + k3 + k4) / 6\n        #print(i) #for debugging purposes only\n    return vx, vy\n\ndef rk2(f, x0, y0, x1, n): #Runge-Kutta second order\n    vx=np.zeros((n+1,1))\n    vy=np.zeros((n+1,1))\n    h = (x1 - x0) / float(n)\n    vx[0] = x = x0 #x0 in (x0,x1)\n    vy[0] = y = y0 #initial condition y(x=x0)=y0\n    for i in range(1, n + 1): #RK4 loop\n        k1 = h * f(x, y) #calls function f(x,y) and evaluates it with x and y values\n        k2 = h * f(x + h, y + k1)\n        vx[i] = x = x0 + i * h\n        vy[i] = y = y + (k1 + k2) / 2\n        #print(i) #for debugging purposes only\n    return vx, vy\n\n \ndef f(x, y):\n    return x * sqrt(y) #RHS of first order differential equation\n\nnodes=100 \nvx, vy = rk4(f, 0, 1, 10, nodes)\nm=nodes/10\nprint('Fourth order Runge Kutta for dydx = x * sqrt(y), y(0)=0')\nprint(\"x,    Approx,       Exact,      Error\")\nfor x, y in list(zip(vx, vy))[::m]: #in [::m], prints every m elements\n    print(\"%4.1f %10.5f %10.5f %+12.4e\" % (x, y, (4 + x * x)**2 / 16, y - (4 + x * x)**2 / 16))\nprint('\\n')\n\nvx, vy = rk2(f, 0, 1, 10, nodes)\nprint('Second order Runge Kutta for dydx = x * sqrt(y), y(0)=0')\nprint(\"x,    Approx,       Exact,      Error\")\nfor x, y in list(zip(vx, vy))[::m]: #in [::m], prints every m elements\n    print(\"%4.1f %10.5f %10.5f %+12.4e\" % (x, y, (4 + x * x)**2 / 16, y - (4 + x * x)**2 / 16))    \n", "meta": {"hexsha": "0b6cc536e7f25b2fb7020552f94926eefef3d2b5", "size": 2116, "ext": "py", "lang": "Python", "max_stars_repo_path": "ode_solver/rk4_1.py", "max_stars_repo_name": "dnaneet/numcode", "max_stars_repo_head_hexsha": "7ec9345f65367a2690f4b9815d476e241edc2d52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ode_solver/rk4_1.py", "max_issues_repo_name": "dnaneet/numcode", "max_issues_repo_head_hexsha": "7ec9345f65367a2690f4b9815d476e241edc2d52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ode_solver/rk4_1.py", "max_forks_repo_name": "dnaneet/numcode", "max_forks_repo_head_hexsha": "7ec9345f65367a2690f4b9815d476e241edc2d52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7857142857, "max_line_length": 99, "alphanum_fraction": 0.511342155, "include": true, "reason": "import numpy", "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377308419051, "lm_q2_score": 0.9372107962258134, "lm_q1q2_score": 0.8983519099348263}}
{"text": "import LinearAlgebraPurePython as la\nimport numpy as np\n\n\nprint('Shtuff from Basic Tools Post')\nprint()\nla.print_matrix(la.zeros_matrix(3, 3))\nprint()\nID = la.identity_matrix(4)\nla.print_matrix(ID)\nprint()\nA = [[1, 2, 3, 4],\n     [5, 6, 7, 8],\n     [9, 10, 11, 12],\n     [13, 14, 15, 16]]\nla.print_matrix(A)\nprint()\nAM = la.copy_matrix(A)\nla.print_matrix(AM)\nprint()\nAT = la.transpose(A)\nla.print_matrix(AT)\nprint()\nC = la.matrix_addition(A, AT)\nla.print_matrix(C)\nprint()\nD = la.matrix_subtraction(C, AT)\nla.print_matrix(D)\nprint()\nAID = la.matrix_multiply(A, ID)\nla.print_matrix(AID)\nprint()\nMatrixList = [A, AT, ID]\nProd3 = la.multiply_matrices(MatrixList)\nla.print_matrix(Prod3)\nprint()\nATA = la.transpose(la.transpose(A))\ncheck = la.check_matrix_equality(A, ATA)\nprint(\"A = transpose of transpose of A?\", check)\nprint()\nAdotA = la.dot_product(A, A)\nprint(\"A.A =\", AdotA)\nprint()\nVector = [[4], [4], [4]]\nunitVector = la.unitize_vector(Vector)\nla.print_matrix(unitVector)\nprint()\nprint()\n\nprint('### Recursive Determinant Shtuff')\nprint()\nA = [[-2, 2, -3],\n     [-1, 1, 3],\n     [2, 0, -1]]  # Matrix from wiki\nDet = la.determinant_recursive(A)\nnpDet = np.linalg.det(A)\nprint(\"Determinant of A is\", round(Det, 9))\nprint(\"The Numpy Determinant of A is\", round(npDet, 9))\nprint()\n\nA = [[1, 2, 3, 4],\n     [5, 6, 7, 8],\n     [9, 10, 11, 12],\n     [13, 14, 15, 16]]\nDet = la.determinant_recursive(A)\nnpDet = np.linalg.det(A)\nprint(\"Determinant of A is\", Det)\nprint(\"The Numpy Determinant of A is\", npDet)\nprint()\n\nA = [[1, 2, 3, 4],\n     [8, 5, 6, 7],\n     [9, 12, 10, 11],\n     [13, 14, 16, 15]]\nDet = la.determinant_recursive(A)\nnpDet = np.linalg.det(A)\nprint(\"Determinant of A is\", Det)\nprint(\"The Numpy Determinant of A is\", round(npDet, 9))\nprint()\n\nA = [[1, 2, 3, 4, 1],\n     [8, 5, 6, 7, 2],\n     [9, 12, 10, 11, 3],\n     [13, 14, 16, 15, 4],\n     [10, 8, 6, 4, 2]]\nDet = la.determinant_recursive(A)\nnpDet = np.linalg.det(A)\nprint(\"Determinant of A is\", Det)\nprint(\"The Numpy Determinant of A is\", round(npDet, 9))\nprint()\nprint()\n\nprint('### Fast Determinant Shtuff')\nprint()\nA = [[-2, 2, -3],\n     [-1, 1, 3],\n     [2, 0, -1]]  # Matrix from wiki\nDet = la.determinant_fast(A)\nnpDet = np.linalg.det(A)\nprint(\"Determinant of A is\", round(Det, 9))\nprint(\"The Numpy Determinant of A is\", round(npDet, 9))\nprint()\n\nA = [[1, 2, 3, 4],\n     [5, 6, 7, 8],\n     [9, 10, 11, 12],\n     [13, 14, 15, 16]]\nDet = la.determinant_fast(A)\nnpDet = np.linalg.det(A)\nprint(\"Determinant of A is\", round(Det, 9)+0)\nprint(\"The Numpy Determinant of A is\", round(npDet, 9))\nprint()\n\nA = [[1, 2, 3, 4],\n     [8, 5, 6, 7],\n     [9, 12, 10, 11],\n     [13, 14, 16, 15]]\nDet = la.determinant_fast(A)\nnpDet = np.linalg.det(A)\nprint(\"Determinant of A is\", round(Det, 9))\nprint(\"The Numpy Determinant of A is\", round(npDet, 9))\nprint()\n\nA = [[1, 2, 3, 4, 1],\n     [8, 5, 6, 7, 2],\n     [9, 12, 10, 11, 3],\n     [13, 14, 16, 15, 4],\n     [10, 8, 6, 4, 2]]\nDet = la.determinant_fast(A)\nnpDet = np.linalg.det(A)\nprint(\"Determinant of A is\", round(Det, 9))\nprint(\"The Numpy Determinant of A is\", round(npDet, 9))\nprint()\n", "meta": {"hexsha": "006f631426f27ea57a60412f61dbb878ecd0a10c", "size": 3093, "ext": "py", "lang": "Python", "max_stars_repo_path": "BasicToolsPractice.py", "max_stars_repo_name": "ThomIves/BasicLinearAlgebraToolsPurePy", "max_stars_repo_head_hexsha": "533263e946b83ee49f1dc48fd4b606e2b37c408e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2019-10-03T11:26:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T00:06:00.000Z", "max_issues_repo_path": "BasicToolsPractice.py", "max_issues_repo_name": "ThomIves/BasicLinearAlgebraToolsPurePy", "max_issues_repo_head_hexsha": "533263e946b83ee49f1dc48fd4b606e2b37c408e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-07-05T08:18:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-28T12:56:02.000Z", "max_forks_repo_path": "BasicToolsPractice.py", "max_forks_repo_name": "ThomIves/BasicLinearAlgebraToolsPurePy", "max_forks_repo_head_hexsha": "533263e946b83ee49f1dc48fd4b606e2b37c408e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-07-29T19:34:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-04T01:31:00.000Z", "avg_line_length": 23.0820895522, "max_line_length": 55, "alphanum_fraction": 0.6075008083, "include": true, "reason": "import numpy", "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.978051741806865, "lm_q2_score": 0.9184802479302793, "lm_q1q2_score": 0.898321206303411}}
{"text": "'''\nLinear Algebra on TensorFlow\nAuthor: Rowel Atienza\nProject: https://github.com/roatienza/Deep-Learning-Experiments\n'''\n# On command line: python linear_algebra.py\n# Prerequisite: tensorflow (see tensorflow.org)\n\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy as np\n\n# Square matrix A of rank 2\nA = tf.constant([[1., 2.], [3., 4.]])\n\n# 2x2 Square, Diagonal, Symmetric matrix B\nB = tf.diag([5., 6.])\n\n# 2x2 Square matrix\nC = tf.constant([[1., 2.], [2., 4.]])\n\n# 2x1 vector will all elements equal to 1\nx = tf.ones([2, 1])\n\n# 2x1 vector will all elements equal to 2.0\nb = tf.fill([2, 1], 2.)\n\n# 2x1 vector\ny = tf.constant([[-1.], [1.]])\n\n# run within a session and print\nwith tf.Session() as session:\n    print(\"Tensorflow version: \" + tf.__version__)\n    tf.global_variables_initializer().run()\n\n    print(\"A = \")\n    print(A.eval())\n\n    print(\"B = \")\n    print(B.eval())\n\n    print(\"C = \")\n    print(C.eval())\n\n    print(\"x = \")\n    print(x.eval())\n\n    print(\"b = \")\n    print(b.eval())\n\n    print(\"y = \")\n    print(y.eval())\n\n    # Tensor multiplication\n    print(\"Ax = \")\n    print(tf.matmul(A, x).eval())\n\n    # Tensor addition\n    print(\"A + B =\")\n    print(tf.add(A, B).eval())\n\n    print(\"A + b =\")\n    print(tf.add(A, b).eval())\n\n    # Rank of A and B; Number of indices to identify each element\n    print(\"tensorRank(A) = \")\n    print(tf.rank(A).eval())\n    print(\"tensorRank(C) = \")\n    print(tf.rank(C).eval())\n\n    # Matrix rank\n    print(\"rank(A) = \")\n    print(np.linalg.matrix_rank(A.eval()))\n    print(\"rank(C) = \")\n    print(np.linalg.matrix_rank(C.eval()))\n\n    # Transpose\n    print(\"tran(A) = \")\n    print(tf.matrix_transpose(A).eval())\n    print(\"tran(B) = \")\n    print(tf.matrix_transpose(B).eval())\n\n    # Inverse\n    print(\"inv(A) = \")\n    print(tf.matrix_inverse(A).eval())\n    # Inverse of diagonal matrix has diag elements of the reciprocal of diag elements B\n    print(\"inv(B) = \")\n    print(tf.matrix_inverse(B).eval())\n    print(\"inv(C) = \")  # since C has rank 1, this will cause error\n    try:\n        print(tf.matrix_inverse(C).eval())\n    except:\n        print(\"C is not invertible\")\n\n    # Product of a matrix and its inverse is an identity (non-singular)\n    print(\"A*inv(A) = Eye(2)\")\n    print(tf.matmul(A, tf.matrix_inverse(A)).eval())\n\n    # Element-wise multiplication\n    print(\"elem(A)*elem(B) = \")\n    print(tf.multiply(A, B).eval())\n\n    # Element-wise addition\n    print(\"elem(A)+elem(B) = \")\n    print(tf.add(A, B).eval())\n\n    # Dot product\n    print(\"x dot b\")\n    print(tf.matmul(x, b, transpose_a=True).eval())\n\n    # Identity matrix of same shape as A\n    print(\"eye(A) = \")\n    I = tf.eye(A.get_shape().as_list()[0], A.get_shape().as_list()[1])\n    print(I.eval())\n\n    # Multiply eye(A) and A = A\n    print(\"eye(A)*A = A = \")\n    print(tf.matmul(I, A).eval())\n    print(\"A * eye(A) = A = \")\n    print(tf.matmul(A, I).eval())\n\n    # l1, l2, Frobenius norm\n    print(\"l1(x) = \")\n    print(tf.reduce_sum(tf.abs(x)).eval())\n    print(\"l2(x) = \")\n    print(tf.sqrt(tf.reduce_sum(tf.square(x))).eval())\n    print(\"Frobenius(A) = \")\n    print(tf.sqrt(tf.reduce_sum(tf.square(A))).eval())\n    print(\"Numpy l2(x) =\")\n    print(np.linalg.norm(x.eval(session=tf.Session())))\n    print(\"Numpy Forbenius(A) =\")\n    print(np.linalg.norm(A.eval(session=tf.Session())))\n\n    # Can you write the L(inf) ?\n\n    # Orthogonal vectors; How do you make x and y orthonormal?\n    print(\"x dot y\")\n    print(tf.matmul(x, y, transpose_a=True).eval())\n\n    # Eigenvalues and eigenvectors\n    print(\"Numpy Eigenvalues of (A)=\")\n    e, v = np.linalg.eig(A.eval())\n    print(e)\n    print(\"Numpy Eigenvectors of (A)=\")\n    print(v)\n\n    # Frobenius norm is equal to the trace of A*tran(A)\n    print(\"Frobenius(A) = Tr(A*tran(A) = \")\n    print(tf.sqrt(tf.trace(tf.matmul(A, tf.transpose(A)))).eval())\n\n    # Determinant of A is the product of its eigenvalues\n    print(\"det(A)=\")\n    print(tf.matrix_determinant(A).eval())\n    # Determinant from eigenvalues\n    print(\"det(A) as product of eigenvalues\")\n    print(tf.reduce_prod(e).eval())\n", "meta": {"hexsha": "a209ed4bff41be4c5953c31e8e7ccbe79abcfebf", "size": 4095, "ext": "py", "lang": "Python", "max_stars_repo_path": "Experiments/Tensorflow/Math/linear_algebra.py", "max_stars_repo_name": "learnerzhang/Deep-Learning-Experiments", "max_stars_repo_head_hexsha": "b97abbc8602715b1e93b4f9ab68ed81126340055", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Experiments/Tensorflow/Math/linear_algebra.py", "max_issues_repo_name": "learnerzhang/Deep-Learning-Experiments", "max_issues_repo_head_hexsha": "b97abbc8602715b1e93b4f9ab68ed81126340055", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Experiments/Tensorflow/Math/linear_algebra.py", "max_forks_repo_name": "learnerzhang/Deep-Learning-Experiments", "max_forks_repo_head_hexsha": "b97abbc8602715b1e93b4f9ab68ed81126340055", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.917721519, "max_line_length": 87, "alphanum_fraction": 0.6004884005, "include": true, "reason": "import numpy", "num_tokens": 1183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102542943773, "lm_q2_score": 0.9284088025362857, "lm_q1q2_score": 0.8981521957507664}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n#rectangle rule\n#int 3x^2 from 0..10\n#the analytic answer=1000\ndef function(x):\n    return 3*x**2\n\ndef error_percentage(exp,exat):\n    return abs(exp-exat)/exp\n\ndef rectangle_rule(initial,final,N):\n    initial=initial\n    final=final\n    N=N\n    h=(final-initial)/(N-1)\n    x=np.linspace(initial,final,N)\n    y=[]\n    for i in x:\n        y.append(function(i)*h)\n    return np.sum(y)\n\n#test the step vs the error and the percentage\ntest_step=np.arange(100,5100,100)\narea=[]\nerror=[]\npercentage=[]\nfor i in test_step:\n    area.append(rectangle_rule(0,10,i))\n    error.append(rectangle_rule(0,10,i)-1000)\n    percentage.append((rectangle_rule(0,10,i)-1000)/(rectangle_rule(0,10,i))*100)\n\n#visualize\nfig=plt.figure(figsize=(18,6))\nax1=fig.add_subplot(131)\nax1.plot(test_step,area,label=\"rectangle rule area\")\nax1.plot(test_step,[1000]*len(area),label=\"exact area\")\nax1.set_title(\"exact vs rectangle rule value\",fontsize=10)\nax1.set_ylabel(\"area\")\nax1.set_xlabel(\"the steps\")\nax1.grid(True)\nax1.legend()\n\nax2=fig.add_subplot(132)\nax2.plot(test_step,error)\nax2.set_title(\"the step versus the error\",fontsize=10)\nax2.set_ylabel(\"error from the exact value\")\nax2.set_xlabel(\"the steps\")\nax2.grid(True)\n\nax3=fig.add_subplot(133)\nax3.plot(test_step,percentage)\nax3.set_title(\"the step vs the error percentage\",fontsize=10)\nax3.set_ylabel(\"error percentage(%)\")\nax3.set_xlabel(\"the steps\")\nax3.grid(True)\nplt.show()\n\nprint(\"rectangle rule\")\nprint(\"test_step\")\nprint(test_step)\nprint(\"area\")\nprint(area)\n\n#trapezoid rule (decrease the error from the rectangle rule)\ndef trapezoid_rule(initial,final,N):\n    initial=initial\n    final=final\n    N=N\n    h=(final-initial)/(N-1)\n    x=np.linspace(initial,final,N)\n    y=[]\n    for i in range(len(x)-1):\n        y.append((function(x[i])+function(x[i+1]))*h/2)\n    return np.sum(y)\n\n#test the step vs the error and the percentage\ntest_step=np.arange(100,5100,100)\narea=[]\nerror=[]\npercentage=[]\nfor i in test_step:\n    area.append(trapezoid_rule(0,10,i))\n    error.append(trapezoid_rule(0,10,i)-1000)\n    percentage.append((trapezoid_rule(0,10,i)-1000)/(trapezoid_rule(0,10,i)))\n\n#visualize\nfig=plt.figure(figsize=(18,6))\nax1=fig.add_subplot(131)\nax1.plot(test_step,area,label=\"trapezoid rule area\")\nax1.plot(test_step,[1000]*len(area),label=\"exact area\")\nax1.set_title(\"exact vs rectangle rule value\",fontsize=10)\nax1.set_ylabel(\"area\")\nax1.set_xlabel(\"the steps\")\nax1.grid(True)\nax1.legend()\n\nax2=fig.add_subplot(132)\nax2.plot(test_step,error)\nax2.set_title(\"the step versus the error\",fontsize=10)\nax2.set_ylabel(\"error from the exact value\")\nax2.set_xlabel(\"the steps\")\nax2.grid(True)\n\nax3=fig.add_subplot(133)\nax3.plot(test_step,percentage)\nax3.set_title(\"the step versus the error percentage\",fontsize=10)\nax3.set_ylabel(\"error percentage(%)\")\nax3.set_xlabel(\"the steps\")\nax3.grid(True)\nplt.show()\n\nprint(\"trapezoid rule\")\nprint(\"test_step\")\nprint(test_step)\nprint(\"area\")\nprint(area)", "meta": {"hexsha": "66addaf1a702246da5b828295f8c7b4e8f65f8e0", "size": 2974, "ext": "py", "lang": "Python", "max_stars_repo_path": "numerical_integration/rectangle&trapezoid.py", "max_stars_repo_name": "coherent17/physics_calculation", "max_stars_repo_head_hexsha": "cf94813778984f62b2c65174fb44bebb2e9c0d05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-30T01:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T01:11:30.000Z", "max_issues_repo_path": "numerical_integration/rectangle&trapezoid.py", "max_issues_repo_name": "coherent17/physics_calculation", "max_issues_repo_head_hexsha": "cf94813778984f62b2c65174fb44bebb2e9c0d05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical_integration/rectangle&trapezoid.py", "max_forks_repo_name": "coherent17/physics_calculation", "max_forks_repo_head_hexsha": "cf94813778984f62b2c65174fb44bebb2e9c0d05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2033898305, "max_line_length": 81, "alphanum_fraction": 0.7259583053, "include": true, "reason": "import numpy", "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357634636667, "lm_q2_score": 0.9173026522382527, "lm_q1q2_score": 0.8980721024613241}}
{"text": "\"\"\"\n01. What is tail-recursive in this case? Will it help perforamnce?\n02. Comparision\n    In [6]: import fibo\n    \n    In [7]: %timeit fibo.fibo_dyn(10)\n    9.91 µs ± 283 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n    \n    In [8]: %timeit fibo.fibo_recur(10)\n    21.4 µs ± 20.3 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n    \n    In [9]: %timeit fibo.fibo_recur(10)\n    21.6 µs ± 61.9 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n    \n    In [10]: %timeit fibo.fibo_dyn(10)\n    9.65 µs ± 13.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n    In [11]: %timeit fibo.fibo_dyn2(10)\n    731 ns ± 4.05 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\"\"\"\n\ndef fibo_recur(n):\n    if n == 0:\n        return 1\n    elif n == 1:\n        return 1\n    else:\n        return fibo_recur(n-1) + fibo_recur(n-2)\n\ndef fibo_dyn(n):\n    import numpy as np\n    cache = np.ones(n+1, dtype=np.uint64)\n    for i in range(2, n+1):\n        cache[i] = cache[i-1] + cache[i-2]\n    return cache[n]\n\ndef print_fib_lt(n):\n    \"\"\"\n    This is the function on the official website of Python\n\n    return a fibonacci number close to n\n    \"\"\"\n    a, b = 0, 1\n    while a < n:\n        print(a, end=' ')\n        a, b = b, a+b\n    print()\n\ndef fibo_dyn2(n):\n    \"\"\"\n    return\n      the n-th fibonacci number\n    \"\"\"\n    if n < 2:\n        return 1\n    else:\n        a, b = 1, 1\n        for _ in range(1,n):\n            a, b = b, a+b\n        return b\n\nif __name__ == \"__main__\":\n    import time\n    t0 = time.time()\n    print(f\"fibo_recur(100)={fibo_recur(100)}\")\n    t1 = time.time()\n    print(f\"Took {t1-t0}s\")\n    print()\n    t0 = time.time()\n    print(f\"fibo_dyn(100)={fibo_dyn(100)}\")\n    t1 = time.time()\n    print(f\"Took {t1-t0}s\")\n\n\n\n\n\n\n\n", "meta": {"hexsha": "a0803dd735ff1b7ae93714b62d05bfef236f2990", "size": 1782, "ext": "py", "lang": "Python", "max_stars_repo_path": "thematic/dynamic-programming/fibonacci/fibo.py", "max_stars_repo_name": "phunc20/algorithms", "max_stars_repo_head_hexsha": "04674829311cde7bb173252b8a41620aae4b14ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thematic/dynamic-programming/fibonacci/fibo.py", "max_issues_repo_name": "phunc20/algorithms", "max_issues_repo_head_hexsha": "04674829311cde7bb173252b8a41620aae4b14ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thematic/dynamic-programming/fibonacci/fibo.py", "max_forks_repo_name": "phunc20/algorithms", "max_forks_repo_head_hexsha": "04674829311cde7bb173252b8a41620aae4b14ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.275, "max_line_length": 78, "alphanum_fraction": 0.551627385, "include": true, "reason": "import numpy", "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.9572778065670466, "lm_q1q2_score": 0.89804530364246}}
{"text": "import sympy\n\ndef newtonRaphson(f, t, x0, maxIter=100, minTol=1e-6, printResults=False): #f is the function defined with sympy simbolic expressions, t is the independent variable of f, maxIter is the maximum number of iterations the user allows, minTol is the minimum tolerance the user wants for the result and printResults that if True, the number of iterations and final error will be printed at the end of the iterations.\n    fp = f.diff(t); #Derivate f(x) for later use during the iterations.\n    xi = x0 #The first guess will be the starting point stated by the user.\n    xi1 = 0.0 #The next guess is defined and equaled to 0 (it will be overwritten later during the first loop iteration).\n    error = 9223372036854775800 #Max int size in python so that the while loop won't stop before beginning.\n    n = 0 #The counter for the iteration.\n    while n < maxIter and error > minTol:\n        xi1 = xi - f.evalf(subs={t:xi})/fp.evalf(subs={t:xi}) #The next guess is calculated.\n        error = abs((xi1-xi)/xi1) #The absolute error is calculated.\n        xi = xi1 #The previous guess becomes the current guess (it will be the previous for the next iteration).\n        n += 1 #Add one to the iteration counter.\n    if(error <= minTol): #Check if the loop ended because the minimum tolerance was reached.\n        print(\"Toleráncia mínima alcanzada\")\n    else: #If the minimum tolerance wasn't met but the number of iterations reached its maximum.\n        print(\"Número máximo de iteraciones alcanzado\")\n    if(printResults):\n        print(\"Iteraciones: {} - Tolerancia Final: {:.5f}\".format(n,error))\n    return xi1\n\n#Test\nif(__name__ == \"__main__\"):\n    \n    #Problem parameters\n    a = 0.01\n    v0 = 0\n    di = -5\n    df = 0\n    \n    \n    #Newton-Raphson method parameters\n    x0 = 1\n    maxIter = 50\n    minTol = 0.1\n\n    #Problem equation and definition\n    t = sympy.symbols('t')\n    f = (a/2)*t**2+v0*t+di-df\n\n    #Calculations and results\n    estimatedValue = newtonRaphson(f,t,x0,maxIter,minTol,True)\n    print(\"Resultado estimado: {:.5f}\".format(estimatedValue))\n    realValue = (-v0 + (v0**2-2*a*(di-df))**0.5)/a\n    print(\"Resultado real: {:.5f}\".format(realValue))\n    print(\"Error porcentual final: {:.5f}%\".format(abs(100*(realValue-estimatedValue)/realValue)))", "meta": {"hexsha": "d968133a1c628562d2525c7bac829129279fddc0", "size": 2276, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tarea 1 Newton-Raphson.py", "max_stars_repo_name": "Osesqui/Tarea-1-F-sica-Computacional", "max_stars_repo_head_hexsha": "410627a76e2c5d69ab21f2f3f8690826711fac42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tarea 1 Newton-Raphson.py", "max_issues_repo_name": "Osesqui/Tarea-1-F-sica-Computacional", "max_issues_repo_head_hexsha": "410627a76e2c5d69ab21f2f3f8690826711fac42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tarea 1 Newton-Raphson.py", "max_forks_repo_name": "Osesqui/Tarea-1-F-sica-Computacional", "max_forks_repo_head_hexsha": "410627a76e2c5d69ab21f2f3f8690826711fac42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.4782608696, "max_line_length": 411, "alphanum_fraction": 0.683655536, "include": true, "reason": "import sympy", "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778012346834, "lm_q2_score": 0.9381240086540332, "lm_q1q2_score": 0.8980452882898}}
{"text": "from scipy.interpolate import interp1d, lagrange\n\nX = [0, 20, 40, 60, 80, 100]\nY = [26.0, 48.6, 61.6, 71.2, 74.8, 75.2]\n\nprint(\"X =\", X)\nprint(\"Y =\", Y, end='\\n\\n')\n\n# Interp1d Function\n\nf = interp1d(X,Y)                   # Linear Interpolation (default)\nprint(\"interp1d(X,Y)(50) =\", f(50))\nprint(\"interp1d(X,Y)(20) =\", f(20), end='\\n\\n')\n\nf = interp1d(X,Y,'quadratic')       # Quadratic Interpolation\nprint(\"interp1d(X,Y,'quadratic')(50) = %.3f\" % f(50))\nprint(\"interp1d(X,Y,'quadratic')(40) = %.3f\" % f(40), end='\\n\\n')\n\nf = interp1d(X,Y,'cubic')           # Cubic Interpolation\nprint(\"interp1d(X,Y,'cubic')(50) = %.3f\" % f(50))\nprint(\"interp1d(X,Y,'cubic')(60) = %.3f\" % f(60), end='\\n\\n')\n\n# Lagrange Function\n\nL = lagrange(X,Y)                   # Lagrange Interpolation\nprint(\"lagrange(X,Y)(50) = %.3f\" % L(50))\nprint(\"lagrange(X,Y)(80) = %.3f\" % L(80), end='\\n\\n')\n\nprint(\"lagrange(X,Y) =\", L, sep='\\n')\n", "meta": {"hexsha": "d440542093187d3ce027ba8ab21a048022b7c418", "size": 912, "ext": "py", "lang": "Python", "max_stars_repo_path": "2. Interpolation and Curve Fitting/0. Interpolation functions of SciPy.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2. Interpolation and Curve Fitting/0. Interpolation functions of SciPy.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2. Interpolation and Curve Fitting/0. Interpolation functions of SciPy.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4, "max_line_length": 68, "alphanum_fraction": 0.5592105263, "include": true, "reason": "from scipy", "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307661011976, "lm_q2_score": 0.9230391605990604, "lm_q1q2_score": 0.8979608937469903}}
{"text": "#########################################################################################\n################### preparacion S2C1 integracion numerica ###############################\n#########################################################################################\n\n#Este ejercicio preparatorio busca que usted implemente correctamente tres metodos de integracion numerica. Haga este ejercicio despues de haber leido y entendido los algoritmos correspondientes a los distintos metodos. Si quiere complementar este ejercicio, puede repetir el proceso para el metodo de Monte Carlo y el metodo del valor medio.\n\n# Ejercicio: Integrales\n\nimport numpy as np\nimport matplotlib.pylab as plt\n\n# Funcion a integrar\ndef funcion(x1):\n\treturn np.cos(x1)\n\n\n#El intervalo de integracion es de 0 a 3pi/2. Divida el intervalo de integracion en M secciones para calcular sus integrales.\na = 0\nb = 3*np.pi/2\nM = 100\n\ndef Ianalítica(a,b):\n    return np.sin(b)-np.sin(a)\n\n# 1a). Usando el metodo de suma de rectangulos, calcule la integral de la funcion. Compare su valor obtenido numericamente con el valor analitico e imprima ambos valores\n'''\ndef rectangulos(a,b,M):\n    h = (b-a)/M\n    w=h\n    suma=0\n    x=a\n    for i in range(int(M)):\n        suma+=funcion(x)*w\n        x+=h\n    return suma\n'''\ndef rectangulos(a,b,M):\n    h=(b-a)/(M-1)\n    w=h\n    x=np.linspace(a,b,M)\n    f=funcion(x)\n    return np.sum(f*w)\n\nprint('Integral analítica es: ',Ianalítica(a,b))\nprint('Integral por suma de rectángulos da: ',rectangulos(a,b,M))\n\n\n# 1b). Usando el metodo de trapezoide, calcule la integral de la funcion. Compare su valor obtenido numericamente con el valor analitico e imprima ambos valores.\n'''\ndef trapezoide(a,b,M):\n    h=(b-a)/(M-1)\n    x=a\n    suma=0\n    for i in range(int(M)):\n        if (i==0 or i==M-1):\n            w=h/2\n        else:\n            w=h\n        suma+=funcion(x)*w\n        x+=h\n    return suma\n'''\n\ndef trapezoide(a,b,M):\n    h=(b-a)/(M-1)\n    x=np.linspace(a,b,M)\n    w=np.zeros(M)\n    for i in range(M):\n        if(i==0 or i==M-1):\n            w[i]=h/2\n        else:\n            w[i]=h\n    f=funcion(x)\n    return np.sum(f*w)\nprint('Integral por el método de trapezoide da: ',trapezoide(a,b,M))\n\n# 1c). Usando el metodo de Simpson, calcule la integral de la funcion. Compare su valor obtenido numericamente con el valor analitico e imprima ambos valores.\n'''\ndef simpson(a,b,M):\n    if(M%2==0):\n        M=M-1\n    h=(b-a)/(M-1)\n    x=a\n    suma=0\n    for i in range(int(M)):\n        if (i==0 or i==M-1):\n            w=h/3\n        elif(i%2==1):\n            w=4*h/3\n        else:\n            w=2*h/3\n        suma+=funcion(x)*w\n        x+=h\n    return suma\n'''\ndef simpson(a,b,M):\n    if(M%2==0):\n        M=M-1\n    h=(b-a)/(M-1)\n    x=np.linspace(a,b,M)\n    w=np.zeros(M)\n    for i in range(int(M)):\n        if (i==0 or i==M-1):\n            w[i]=h/3\n        elif(i%2!=0):\n            w[i]=(4/3)*h\n        else:\n            w[i]=(2/3)*h\n    f=funcion(x)\n    return np.sum(f*w)\nprint('Integral por el método de Simpson da: ',simpson(a,b,M))\n\n#########################################################################################\n################### S2C1 errores para diferentes metodos  ###############################\n#########################################################################################\nprint('')\nprint('ERRORES DE MÉTODOS')\nprint('')\n# 1d). Repita el procedimiento para distintios valores de M (10**2 a 10**7 aumentando logaritmicamente, use np.logspace: https://docs.scipy.org/doc/numpy/reference/generated/numpy.logspace.html) para calcular la integral y haga una grafica de error ((valor numerico - valor analitico)/valor analitico) en funcion de M (haga una curva por cada metodo). Guarde dicha grafica sin mostrarla en ErrorRTS.pdf\n\nxlog=np.logspace(2,7,6)\nlogrectangulos=[]\nlogtrapezoide=[]\nlogsimpson=[]\nfor i in range(len(xlog)):\n    logrectangulos.append(rectangulos(a,b,int(xlog[i])))\n    logtrapezoide.append(trapezoide(a,b,int(xlog[i])))\n    logsimpson.append(simpson(a,b,int(xlog[i])))\n\nER=np.abs((logrectangulos-Ianalítica(a,b))/Ianalítica(a,b))\nET=np.abs((logtrapezoide-Ianalítica(a,b))/Ianalítica(a,b))\nES=np.abs((logsimpson-Ianalítica(a,b))/Ianalítica(a,b))\n\nplt.figure()\nplt.plot(xlog,ER,c='b',label='Error Rectángulos')\nplt.plot(xlog,ET,c='g',label='Error Trapezoide')\nplt.plot(xlog,ES,c='r',label='Error Simpson')\nplt.title('Error de métodos')\nplt.xlabel('X')\nplt.ylabel('abs(error)')\nplt.loglog()\nplt.legend()\nplt.savefig('ErrorRTS.png')\n#########################################################################################\n################### S2C1 otros metodos de integracion numerica ##########################\n#########################################################################################\n\n# 1e). Usando el metodo de valor medio, calcule la integral de la funcion cos(theta) entre 0 y pi/2 usando N=10000 puntos aleatorios. Compare su valor obtenido numericamente con el valor analitico e imprima ambos valores.\ndef VM(a,b,N):\n    x=np.cos((np.random.random(N)*(b-a))+a)\n    suma=np.sum(x)\n    I=(suma*(b-a))/N\n    return I\nprint('La integral por valor medio da: ',VM(0,np.pi/2,10000))\nprint('La integral analítica da: ',Ianalítica(0,np.pi/2))\n\n# 1f). Usando el metodo de sampleo directo de Monte Carlo, calcule la integral de la funcion sin(theta) entre 0 y pi/2 usando N=10000 puntos aleatorios. Compare su valor obtenido numericamente con el valor analitico e imprima ambos valores.\n\n# 1g). Repita el procedimiento para distintios valores de M (10**2 a 10**7 aumentando logaritmicamente) para calcular la integral y haga una grafica de error ((valor numerico - valor analitico)/valor analitico) en funcion de M (haga una curva por cada metodo). Guarde dicha grafica sin mostrarla en ErrorRTS.pdf\n", "meta": {"hexsha": "128f55bdf9bba6853d709e4e291996fe9fb15b00", "size": 5774, "ext": "py", "lang": "Python", "max_stars_repo_path": "integration/integration.py", "max_stars_repo_name": "LuisCendales/M-todos_Computacionales", "max_stars_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "integration/integration.py", "max_issues_repo_name": "LuisCendales/M-todos_Computacionales", "max_issues_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "integration/integration.py", "max_forks_repo_name": "LuisCendales/M-todos_Computacionales", "max_forks_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0875, "max_line_length": 402, "alphanum_fraction": 0.5838240388, "include": true, "reason": "import numpy", "num_tokens": 1596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191284552529, "lm_q2_score": 0.9399133485636499, "lm_q1q2_score": 0.8979172009732844}}
{"text": "\"\"\"angular_dist that calculates the angular distance between any two points on \nthe celestial sphere given their right ascension and declination.\nAngular distances have the same units as angles (degrees).\"\"\"\n\n#b = np.cos(d1)*np.cos(d2)*np.sin(np.abs(r1 - r2)/2)**2\n#d = 2*np.arcsin(np.sqrt(a + b))\n\nimport numpy as np\n\ndef angular_dist(r1, d1, r2, d2):\n\"\"\"Trig functions in most languages and libraries (including Python and NumPy) \ntake angle arguments in units of radians, but the databases we're working with \nuse angles of degrees.\n\nFortunately, NumPy provides convenient conversion functions:\n\na_rad = np.radians(a_deg)\na_deg = np.degrees(a_rad)\nThe variable a_deg is in units of degrees and a_rad is in radians.\"\"\"  \n  r1= np.radians(r1)\n  r2= np.radians(r2)\n  d1= np.radians(d1)\n  d2= np.radians(d2)\n  \n\"\"\"There are other \nequations for calculating the angular distance but this one, called the \nhaversine formula, is good at avoiding floating point errors when the two \npoints are close together.\"\"\"\n\n  a = (np.sin(np.abs(d1 - d2)/2))**2\n  b = np.cos(d1)*np.cos(d2)*np.sin(np.abs(r1 - r2)/2)**2\n  d = np.degrees(2*np.arcsin(np.sqrt(a + b)))\n  \n  return d\n\nif __name__ == '__main__':\n  print(angular_dist(21.07, 0.1, 21.15, 8.2))\n  print(angular_dist(10.3, -3, 24.3, -29))\n\n", "meta": {"hexsha": "9cfd61fac82d6be36ece916bc95e7c857f22cb39", "size": 1281, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week2/Assignment1/angular_distance.py", "max_stars_repo_name": "vinayak1998/Data_Driven_Astronomy", "max_stars_repo_head_hexsha": "1d0dd82b2e9066759c442807c30c70bef096d719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-21T07:31:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T05:25:44.000Z", "max_issues_repo_path": "Week2/Assignment1/angular_distance.py", "max_issues_repo_name": "vinayak1998/Data_Driven_Astronomy", "max_issues_repo_head_hexsha": "1d0dd82b2e9066759c442807c30c70bef096d719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week2/Assignment1/angular_distance.py", "max_forks_repo_name": "vinayak1998/Data_Driven_Astronomy", "max_forks_repo_head_hexsha": "1d0dd82b2e9066759c442807c30c70bef096d719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-24T21:12:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-18T12:26:45.000Z", "avg_line_length": 32.025, "max_line_length": 79, "alphanum_fraction": 0.7080405933, "include": true, "reason": "import numpy", "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9787126457229185, "lm_q2_score": 0.9173026641072386, "lm_q1q2_score": 0.8977757173170771}}
{"text": "#Import libraries \nimport numpy as np \nimport matplotlib.pyplot as plt \nfrom sklearn.datasets import make_regression\n\n\n\"\"\"\ndefine function for linear regression modele  \nF(X) = theta * X \n\nTheta: matrix which contains coefficient (a b c ... ) of polynomial F(X) \nX : matrix which contains features \nF(X) : target \n\n\"\"\"\n#Definition of modele function \n\ndef modele(X,theta): \n    return X.dot(theta)\n    \n# Definition of cost function \ndef cost_function(X,y,theta): \n    m=len(y)\n    return 1/(2*m) * np.sum((modele(X,theta)-y)**2)\n\n\n#Definition of grad function  \ndef grad (X,y,theta): \n    m=len(y)\n    return 1/m * X.T.dot(modele(X,theta)-y)\n    \n #Definition of Algorithm of Gradient Descent to find minimum (or best value of coefficient theta )   \ndef gradient_descent(X,y,theta,learning_rate,n_iterration):\n    cost_history=np.zeros(n_iterration)\n    for i in range(0,n_iterration): \n        theta=theta - learning_rate * grad(X,y,theta)\n        cost_history[i]=cost_function(X,y,theta)\n    return theta,cost_history\n \ndef coef_determination(y,prediction): \n    u=((y-prediction)**2).sum()\n    v=((y-y.mean())**2).sum()\n    return 1- u/v\n    \n    \n    \n    \n\n\n\n\nx, y = make_regression(n_samples=100,n_features=1, noise=10)\nplt.scatter(x,y)\ny=y.reshape(y.shape[0],1)\nX=np.hstack((x,np.ones(x.shape)))\ntheta=np.random.randn(2,1)\ncost_function(X,y,theta)\ntheta_final,cost_history= gradient_descent(X,y,theta,0.01,1000)\nprediction=modele(X,theta_final)\nplt.scatter(x,y)\nplt.plot(x,prediction,c='r')\nplt.plot(range(1000),cost_history)\ncoef_determination(y,prediction)\n", "meta": {"hexsha": "0cbe12f17cc76d2bec1126beb010ad319e66cdd3", "size": 1567, "ext": "py", "lang": "Python", "max_stars_repo_path": "linearRegression.py", "max_stars_repo_name": "salimkhazem/Linear-regression-", "max_stars_repo_head_hexsha": "1710fbbd3f29372d1677131035a284236441a848", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-01T10:40:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-01T10:40:17.000Z", "max_issues_repo_path": "linearRegression.py", "max_issues_repo_name": "salimkhazem/Linear-regression-", "max_issues_repo_head_hexsha": "1710fbbd3f29372d1677131035a284236441a848", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linearRegression.py", "max_forks_repo_name": "salimkhazem/Linear-regression-", "max_forks_repo_head_hexsha": "1710fbbd3f29372d1677131035a284236441a848", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.484375, "max_line_length": 102, "alphanum_fraction": 0.6949585195, "include": true, "reason": "import numpy", "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9799765604649332, "lm_q2_score": 0.9161096193153989, "lm_q1q2_score": 0.8977659537455439}}
{"text": "import numpy as np\r\n\r\n# SQUARE MATRIX --> number of rows is equal to number of columns\r\n\r\nmatrix1 = np.random.randint(1,10,(4,4))\r\n\r\nmatrix1.shape\r\n\r\n# SYMMETRIC MATRIX --> type of square matrix where top right triangle is same as bottom left triangle based on principle diagonal elements\r\n\r\n# https://stackoverflow.com/questions/10806790/generating-symmetric-matrices-in-numpy/27331415\r\nN = 4\r\nb = np.random.random_integers(-2000,2000,size=(N,N))\r\nsymmetric_matrix = (b + b.T)/2\r\n\r\nsymmetric_matrix.shape\r\n\r\n# TRIANGULAR MATRIX --> is a square matrix and top OR bottom elements are zero based on principle diagonal element\r\n\r\n# top elements are zero\r\nnp.triu(matrix1)\r\n\r\n# bottom elements are zero\r\nnp.tril(matrix1)\r\n\r\n# DIAGONAL MATRIX --> is a square matrix and top AND bottom elements are zero based on principle diagonal  element\r\n\r\ndiagonal_matrix = np.array([[1,0,0],[0,2,0],[0,0,3]])\r\n\r\n# IDENTITY MATRIX --> type of diagonal matrix, principle diagonal will be equal to one \r\n\r\nnp.eye(4)\r\n", "meta": {"hexsha": "c5ddb044de7b2397cec5e81cf4d557f616302853", "size": 997, "ext": "py", "lang": "Python", "max_stars_repo_path": "matrix/types_of_matrices.py", "max_stars_repo_name": "Akshaykumarcp/linear_algebra", "max_stars_repo_head_hexsha": "083f1d8d77b944d9b8e85eb34c65b87794a9b6ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-06T12:26:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T11:31:53.000Z", "max_issues_repo_path": "matrix/types_of_matrices.py", "max_issues_repo_name": "Akshaykumarcp/practical_linear_algebra", "max_issues_repo_head_hexsha": "083f1d8d77b944d9b8e85eb34c65b87794a9b6ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matrix/types_of_matrices.py", "max_forks_repo_name": "Akshaykumarcp/practical_linear_algebra", "max_forks_repo_head_hexsha": "083f1d8d77b944d9b8e85eb34c65b87794a9b6ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2121212121, "max_line_length": 139, "alphanum_fraction": 0.7271815446, "include": true, "reason": "import numpy", "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.9390248135892422, "lm_q1q2_score": 0.8976902067519547}}
{"text": "'''\nAuthor:    Michael Sherif Naguib\nDate:      March 13, 2020\n@:         University of Tulsa\nDescription: see README.md\n\n( the coronavirus hit so we were sent home from college ... I had the idea to finally code this last week and finished the\nfirst working code @ DFW ... I have touched it up now and put it on github)\n\n'''\n\n# Imports\nimport math\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tqdm\n\ndef distSqr(x,y):\n    '''\n    :description: Calculates the distance squared from a point with coordinates x,y from the origin 0,0\n    :param x: x coordinate\n    :param y: y coordinate\n    :return: distance squared\n    '''\n    return math.pow(x,2) + math.pow(y,2)\n\ndef calcPiEstimate(numInCircle,numInSquare):\n    '''\n    :description: Calculates an Estimate of Pi using the given parameters;\n    NOTE! The calculation is based off of a circle inscribed in a square.\n    Derivation\n    where s is a scaling factor\n    let r = s where r is the radius of the circle\n    thus the side length of the square  = 2s = 2r\n    1) As = Area Square = (2r)^2 = 4*r^2\n    2) Ac = Area Circle = pi*r^2\n    3) thus pi = Ac/r^2\n    4) r^2 = Area Square/4           (from stmt 1)\n    5) thus pi = Ac/ (As/4) = 4Ac/As\n\n    :param numInCircle: a count of the number of points within the circle\n    :param numInSquare: a count of the number of points within the square\n    :return: an estimate of pi\n\n    '''\n    assert numInSquare !=0 # Catch Div by Zero\n    return 4*numInCircle/numInSquare\n\ndef updateRunningAvg(curAvg,val,valCnt):\n    '''\n    :description: compute a running average\n    :param curAvg: the current value of the average\n    :param val: the new value to factor into the average\n    :param valCnt: the number of values taken into account for the curAvg\n    :return: the updated average\n\n    (NOTE! this function does not change any of the parameters --> no side effect...)\n    it is the prgmr's responsibility to update those vals\n    '''\n    assert valCnt != 0\n    return (curAvg*valCnt + val)/(valCnt+1)\n\ndef monteCarloPiItr(radius=1,iterations=100_000_000):\n    '''\n    :description: A generator that generates successive estimates of pi\n    :param radius: the Radius of the Circle inscribed in the Square (both centered at 0,0)\n    :param iterations: the number points to compute and use to update the estimate\n    :yeild: the next estimate of pi\n    '''\n    # Count how many are in the circle\n    inCircleCount = 0\n    # Store an estimate for Pi (will be updated as the simulation progresses)\n    piEst = 0\n    # Calculate the radius squared (once)\n    radiusSquared = math.pow(radius, 2)\n\n    # Begin iteration: i is the total up to that iteration .. (all points are in the square)\n    for i in range(1, iterations + 1):\n        # Pick random coords: the circle is centered @ 0,0 so shift over the range of the square by subtracting 0.5\n        # before scaling by the sidelength of the square ( side length = 2*radius)\n        x = (random.random() - 0.5) * radius * 2\n        y = (random.random() - 0.5) * radius * 2\n\n        # Check if the point is within the circle: increment if it is (use squared distance to be efficient)\n        inCircleCount = inCircleCount + 1 if distSqr(x, y) <= radiusSquared else inCircleCount + 0\n\n        # Update the pi estimate\n        piEst = calcPiEstimate(inCircleCount,i)  # (all the points we select are in the square so our inSquareCount would be just i)\n\n        # Yield the pi esitmate\n        yield piEst\n\ndef plotSeries(series, x_name=\"x\", y_name=\"y\", title=\"Graph\", x_key='x',y_key='y'):\n    # Code adapted from my chaotic IFS project\n    # Plotting Code: Passed a series list [series1,series2] where series {name:\"\",x:[],y:[]}\n    # NOTE! CAN ONLY PLOT 3 colors before it starts using random values for colors\n    # TAKEN from my PlotUtil Lib on github on 3/13/2020@10:48AM\n    colors = [(70 / 255, 240 / 255, 240 / 255), (240 / 255, 50 / 255, 230 / 255), (210 / 255, 245 / 255, 60 / 255)]\n    plt.title(title)\n    plt.xlabel(x_name)\n    plt.ylabel(y_name)\n    idx = 0\n    r = random.random\n    for group in series:\n        # Plot the points\n        plt.scatter(group[x_key], group[y_key], c=[colors[idx] if idx < len(colors) else (r(), r(), r())],\n                    s=np.pi * 3, alpha=0.5, label=group['name'])\n        idx += 1\n    plt.legend(loc='upper left')\n    plt.show()\n\ndef reject_outliers(data, m=2):\n    '''\n    NOT MY CODE: i take no credit for this code...\n    thanks to: https://stackoverflow.com/questions/11686720/is-there-a-numpy-builtin-to-reject-outliers-from-a-list\n    :Description: this code rejects outliers ....\n    :param data: array\n    :param m:\n    :return: data without outliers\n    '''\n    return data[abs(data - np.mean(data)) < m * np.std(data)]\n\n# Main Simulation\nif __name__ == \"__main__\":\n\n    cnt=0\n    for newEst in monteCarloPiItr():\n        cnt+=1\n        if cnt%10000==0:\n            print(newEst)\n\n    # Sample every k iterations:\n    k = 10\n\n    # Different Radius Values to Try:\n    radii = [1,10,100]\n    assert(len(radii)<=3) # a requirement of my plotting function ....\n    # Point Quanty per Simulation]\n    pointQuantity= 1000\n\n    # Number of times to redo the simulation\n    redos = 50\n    allSeries=[]\n    # Run the Simulation(s)\n    for radius in radii:\n        # Data structure to hold info about the series\n        currentSeries = {\n           \"name\": \"radius = {0}\".format(radius),\n           \"x\":[],\n           \"y\":[],\n        }\n        for rd in range(redos):\n            # Use a counter to keep track of iterations\n            cntr=0\n            # Run the simulation getting the next estimate\n            for newEstimate in tqdm.tqdm(monteCarloPiItr(radius=radius,iterations=pointQuantity)):\n                if cntr%k==0:# Sample every k iters\n                    if rd==0: # i.e it is the first time data is going in ... do nothing just add the data\n                        currentSeries[\"x\"].append(cntr)\n                        currentSeries[\"y\"].append(newEstimate)\n                    else:\n                        # Update the value as a running average\n\n                        # Index the list of sampled data... since we log every k ... the index is cntr/k which is an int\n                        indx = int(cntr/k)\n                        assert float(indx) == cntr/k#check\n\n                        currentSeries[\"y\"][indx] = updateRunningAvg(currentSeries[\"y\"][indx],newEstimate,rd+1)\n                cntr+=1\n            # Append the current series to all the series\n        allSeries.append(currentSeries)\n\n    # Graph the Data\n\n    # Plot the convergence of the different simulations\n    plotSeries(\n        allSeries,\n        x_name=\"Iterations  (sampled every {0}, redos={1})\".format(k,redos),\n        y_name=\"Estimate Value\",\n        title=\" Estimate Value vs Iterations\"\n        )\n\n    # Plot the histogram data for each radius\n    bins = 100\n    for i in range(len(radii)):\n       cleaned_data= reject_outliers(np.array(allSeries[i][\"y\"]),m=2)\n       plt.hist(cleaned_data,bins)\n       plt.title(\"Estimates for radius={0} redos={1}\".format(radii[i],redos))\n       plt.xlabel(\"Estimate Values\")\n       plt.ylabel(\"Estimate Counts (outliers excluded)\")\n       plt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "9a9b094c604c6ff9b075761096050b35e250c377", "size": 7232, "ext": "py", "lang": "Python", "max_stars_repo_path": "montecarlopi.py", "max_stars_repo_name": "Michael-Naguib/MonteCarloPi", "max_stars_repo_head_hexsha": "8c63c6f1b60a2e80fe910caf53809a22cc2c9828", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "montecarlopi.py", "max_issues_repo_name": "Michael-Naguib/MonteCarloPi", "max_issues_repo_head_hexsha": "8c63c6f1b60a2e80fe910caf53809a22cc2c9828", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "montecarlopi.py", "max_forks_repo_name": "Michael-Naguib/MonteCarloPi", "max_forks_repo_head_hexsha": "8c63c6f1b60a2e80fe910caf53809a22cc2c9828", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2780487805, "max_line_length": 132, "alphanum_fraction": 0.6273506637, "include": true, "reason": "import numpy", "num_tokens": 1924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731158685837, "lm_q2_score": 0.9324533149608596, "lm_q1q2_score": 0.8976477381153606}}
{"text": "\"\"\"\nmean\n\nThe mean tool computes the arithmetic mean along the specified axis.\n\nimport numpy\n\nmy_array = numpy.array([ [1, 2], [3, 4] ])\n\nprint numpy.mean(my_array, axis = 0)        #Output : [ 2.  3.]\nprint numpy.mean(my_array, axis = 1)        #Output : [ 1.5  3.5]\nprint numpy.mean(my_array, axis = None)     #Output : 2.5\nprint numpy.mean(my_array)                  #Output : 2.5\n\nBy default, the axis is None. Therefore, it computes the mean of the flattened array.\n\nvar\n\nThe var tool computes the arithmetic variance along the specified axis.\n\nimport numpy\n\nmy_array = numpy.array([ [1, 2], [3, 4] ])\n\nprint numpy.var(my_array, axis = 0)         #Output : [ 1.  1.]\nprint numpy.var(my_array, axis = 1)         #Output : [ 0.25  0.25]\nprint numpy.var(my_array, axis = None)      #Output : 1.25\nprint numpy.var(my_array)                   #Output : 1.25\n\nBy default, the axis is None. Therefore, it computes the variance of the flattened array.\n\nstd\n\nThe std tool computes the arithmetic standard deviation along the specified axis.\n\nimport numpy\n\nmy_array = numpy.array([ [1, 2], [3, 4] ])\n\nprint numpy.std(my_array, axis = 0)         #Output : [ 1.  1.]\nprint numpy.std(my_array, axis = 1)         #Output : [ 0.5  0.5]\nprint numpy.std(my_array, axis = None)      #Output : 1.11803398875\nprint numpy.std(my_array)                   #Output : 1.11803398875\n\nBy default, the axis is None. Therefore, it computes the standard deviation of the flattened array.\n\nTask\n\nYou are given a 2-D array of size\nX\n\n.\nYour task is to find:\n\n    The mean along axis\n\nThe var along axis\nThe std along axis\n\nInput Format\n\nThe first line contains the space separated values of\nand .\nThe next lines contains\n\nspace separated integers.\n\nOutput Format\n\nFirst, print the mean.\nSecond, print the var.\nThird, print the std.\n\nSample Input\n\n2 2\n1 2\n3 4\n\nSample Output\n\n[ 1.5  3.5]\n[ 1.  1.]\n1.11803398875\n\"\"\"\n\nimport numpy as np\n\nn,m = map(int, input().split())\nb = []\nfor i in range(n):\n    a = list(map(int, input().split()))\n    b.append(a)\n\nb = np.array(b)\n\nnp.set_printoptions(legacy='1.13')\nprint(np.mean(b, axis = 1))\nprint(np.var(b, axis = 0))\nprint(np.std(b))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "7b248b33b7832acb8b68ca20d71889a2e6cea7a6", "size": 2162, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numpy/Mean,_Var,_and_Std.py", "max_stars_repo_name": "NikolayVaklinov10/Python_Challenges", "max_stars_repo_head_hexsha": "a1052e1d527004bbb6072a3cbc802065469f66ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-01T23:57:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-01T23:58:16.000Z", "max_issues_repo_path": "Numpy/Mean,_Var,_and_Std.py", "max_issues_repo_name": "NikolayVaklinov10/Python_Challenges", "max_issues_repo_head_hexsha": "a1052e1d527004bbb6072a3cbc802065469f66ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numpy/Mean,_Var,_and_Std.py", "max_forks_repo_name": "NikolayVaklinov10/Python_Challenges", "max_forks_repo_head_hexsha": "a1052e1d527004bbb6072a3cbc802065469f66ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8, "max_line_length": 99, "alphanum_fraction": 0.6503237743, "include": true, "reason": "import numpy", "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140616, "lm_q2_score": 0.9324533032291501, "lm_q1q2_score": 0.8976477218287173}}
{"text": "\"\"\"\r\nAndrea has a simple equation:\r\nY = a + b1f1 + b2f2 + ... + bmfm\r\nfor (m + 1) real constants (a, f1, f2, ..., fm). We can say that the value of Y depends on m features. \r\nAndrea studies this equation for n different feature sets (f1, f2, ..., fm) and records each respective value of Y. \r\nIf she has q new feature sets, can you help Andrea find the value of Y for each of the sets?\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\n\r\ndef least_squares(x, y):\r\n    a = np.append(x, np.ones((len(x), 1)), axis=-1)\r\n    y = y[:, np.newaxis]\r\n\r\n    result = np.linalg.inv(np.dot(a.T, a))\r\n    result = np.dot(result, a.T)\r\n    result = np.dot(result, y)\r\n\r\n    return result[-1][0], result[:-1]\r\n\r\n\r\ndef main():\r\n\r\n    m, n = list(map(int, str.split(input(), \" \")))\r\n    data = [list(float(x) for x in input().split()) for i in range(n)]\r\n\r\n    x = np.array([[item[i] for i in range(m)] for item in data])\r\n    y = np.array([item[-1] for item in data])\r\n\r\n    a, b = least_squares(x, y)\r\n\r\n    q = int(input())\r\n\r\n    for i in range(q):\r\n        data = list(map(float, input().split()))\r\n        result = [b[j] * data[j] for j in range(m)]\r\n        result = a + np.sum(result)\r\n        print(\"{:.3f}\".format(result))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n", "meta": {"hexsha": "edc886c37e8bf22bfa1e9ce30ad9a6b6cf64fe18", "size": 1242, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/day_9/multiple_linear_regression.py", "max_stars_repo_name": "djeada/10DaysStatistics", "max_stars_repo_head_hexsha": "848fbb0577057ab5ad413e676a928a7425284e9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-10T15:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-11T11:28:40.000Z", "max_issues_repo_path": "src/day_9/multiple_linear_regression.py", "max_issues_repo_name": "djeada/10DaysStatistics", "max_issues_repo_head_hexsha": "848fbb0577057ab5ad413e676a928a7425284e9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day_9/multiple_linear_regression.py", "max_forks_repo_name": "djeada/10DaysStatistics", "max_forks_repo_head_hexsha": "848fbb0577057ab5ad413e676a928a7425284e9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2272727273, "max_line_length": 117, "alphanum_fraction": 0.5636070853, "include": true, "reason": "import numpy", "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846722794542, "lm_q2_score": 0.9173026505426832, "lm_q1q2_score": 0.8974748531322779}}
{"text": "'''\n01 - Correlated data in nature\n\nYou are given an array grains giving the width and length of samples of grain. \nYou suspect that width and length will be correlated. To confirm this,  make a \nscatter plot of width vs length and measure their Pearson correlation.\n\nInstructions\n\n- Import:\n    - matplotlib.pyplot as plt.\n    - pearsonr from scipy.stats.\n\n- Assign column 0 of grains to width and column 1 of grains to length.\n- Make a scatter plot with width on the x-axis and length on the y-axis.\n- Use the pearsonr() function to calculate the Pearson correlation of width and \n  length.\n'''\n# Perform the necessary imports\nimport matplotlib.pyplot as plt\nfrom scipy.stats import pearsonr\n\n# Assign the 0th column of grains: width\nwidth = grains[:,0]\n\n# Assign the 1st column of grains: length\nlength = grains[:,1]\n\n# Scatter plot width vs length\nplt.scatter(width, length)\nplt.axis('equal')\nplt.show()\n\n# Calculate the Pearson correlation\ncorrelation, pvalue = pearsonr(width, length)\n\n# Display the correlation\nprint(correlation)\n\n'''\n<script.py> output:\n    0.8604149377143466\n'''\n", "meta": {"hexsha": "2ca5ffee948944db41b4d2465dd44faad67005f3", "size": 1089, "ext": "py", "lang": "Python", "max_stars_repo_path": "27_Unsupervised Learning in Python/03_decorrelating-your-data-and-dimension-reduction/01_correlated-data-in-nature.py", "max_stars_repo_name": "mohd-faizy/DataScience-With-Python", "max_stars_repo_head_hexsha": "13ebb10cf9083343056d5b782957241de1d595f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-02-03T14:36:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T10:29:26.000Z", "max_issues_repo_path": "27_Unsupervised Learning in Python/03_decorrelating-your-data-and-dimension-reduction/01_correlated-data-in-nature.py", "max_issues_repo_name": "mohd-faizy/DataScience-With-Python", "max_issues_repo_head_hexsha": "13ebb10cf9083343056d5b782957241de1d595f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "27_Unsupervised Learning in Python/03_decorrelating-your-data-and-dimension-reduction/01_correlated-data-in-nature.py", "max_forks_repo_name": "mohd-faizy/DataScience-With-Python", "max_forks_repo_head_hexsha": "13ebb10cf9083343056d5b782957241de1d595f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-02-08T00:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:52:32.000Z", "avg_line_length": 24.75, "max_line_length": 80, "alphanum_fraction": 0.7474747475, "include": true, "reason": "from scipy", "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561712637256, "lm_q2_score": 0.926303728768107, "lm_q1q2_score": 0.8974550840815807}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nprint(\"Polynomial interpolation \\n\")\r\n\r\n\r\ndef input_gen():\r\n    x = [0.0,  0.1,  0.2,   0.3,   0.4,   0.5,   0.6,  0.7,   0.8,   0.9,   1.0]\r\n    p = [0.0,  0.41, 0.79, 1.13,  1.46,  1.76,  2.04,  2.3,  2.55,  2.79,  3.01]\r\n\r\n    # x = [0, 1, 2, 3]\r\n    # p = [-2, -5, 0, -4]\r\n \r\n    # x = [1, 3, 4]\r\n    # p = [6, 24, 45]\r\n\r\n    k = 7\r\n    m = 3.5\r\n    y = [(p[i] + ((-1) ** k) * m) for i in range(len(x))]\r\n    dots = list(zip(x, y))\r\n\r\n    # dots = [(0, 0), (1, 0)]\r\n    # dots = [(-1, 0), (0, 1), (1, 0)]\r\n    # dots = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 6)]\r\n    # dots = [(1, 1), (2, 3), (3, 5), (4, 7), (5, 30000)] # 217341\r\n    # dots = [(-1.5, np.tan(-1.5)), (-0.75, np.tan(-0.75)), (0, np.tan(0)), (0.75, np.tan(0.75)), (1.5, np.tan(1.5))]\r\n\r\n    # dots = [(, ), ]\r\n\r\n    # def f(x):\r\n    #    return 1 / (1 + x**2)\r\n    # SIZE = 11\r\n    # dots = [(-5 + 10 * x / (SIZE - 1), f(-5 + 10 * x / (SIZE - 1))) for x in range(SIZE) ]\r\n\r\n    return dots\r\n\r\n\r\ndots = input_gen()\r\n(x, y) = map(list, zip(*dots))\r\nprint(\"(x,y) =\", dots, '\\n')\r\n\r\n\r\ndef Lagrange(dots):\r\n    n = len(dots)\r\n    (x, y) = map(list, zip(*dots))\r\n    polynom = np.poly1d([0])\r\n    for i in range(n):\r\n        p = np.poly1d([1])\r\n        for j in range(n):\r\n            if j != i:\r\n                p *= np.poly1d([1, -x[j]]) / (x[i] - x[j])\r\n        polynom += y[i] * p\r\n    return polynom\r\n\r\n\r\nlagr = Lagrange(dots)\r\nprint(\"Lagrange polynom =\")\r\nprint(lagr, '\\n')\r\n\r\n\r\ndef DividedDifferences(xs):\r\n    n = len(xs)\r\n    diffs = [[None for j in range(n - i)] for i in range(n)]\r\n    for i in range(n):\r\n        diffs[i][0] = y[i]\r\n    for j in range(1, n):\r\n        for i in range(n - j):\r\n            diffs[i][j] = ((diffs[i][j - 1] - diffs[i + 1][j - 1]) / (xs[i] - xs[i + j]))\r\n    return diffs\r\n\r\n\r\ndef Inaccuracy(xs, xdot):\r\n    n = len(xs)\r\n    diffs = DividedDifferences(xs)\r\n    maxdiff = 0.0\r\n    for i in range(len(diffs)):\r\n        for j in range(len(diffs[i])):\r\n            maxdiff = max(maxdiff, abs(diffs[i][j]))\r\n    w = 1\r\n    for i in range(n):\r\n        w *= xdot - xs[i]\r\n    f = 1\r\n    for i in range(1, n + 1 + 1):\r\n        f *= i\r\n    R = maxdiff * w / f\r\n    return R\r\n\r\n\r\ndef Newton(dots):\r\n    n = len(dots)\r\n    (x, y) = map(list, zip(*dots))\r\n\r\n    diffs = DividedDifferences(x)\r\n\r\n    polynom = np.poly1d([0])\r\n    for i in range(n):\r\n        p = np.poly1d([1])\r\n        for j in range(i):\r\n            p *= np.poly1d([1, -x[j]])\r\n        polynom += p * diffs[0][i]\r\n\r\n    return polynom\r\n\r\n\r\nnewt = Newton(dots)\r\nprint(\"Newton polynom =\")\r\nprint(newt, '\\n')\r\n\r\n\r\ndef Simple(dots):\r\n    n = len(dots)\r\n    (x, y) = map(list, zip(*dots))\r\n    A = []\r\n    for i in range(n):\r\n        A.append([])\r\n        for j in range(n):\r\n            A[i].append(x[i] ** j)\r\n    polynom = np.poly1d(np.linalg.solve(A, y)[::-1])\r\n    return polynom\r\n\r\n\r\ndef Squares(dots, m=None):\r\n    n = len(dots) - 1\r\n    if m is None:\r\n        m = n\r\n    assert 0 <= m <= n\r\n    if m == n:\r\n        return Simple(dots)\r\n\r\n    (x, y) = map(list, zip(*dots))\r\n\r\n    b = []\r\n    for k in range(m + 1):\r\n        s = 0\r\n        for i in range(n + 1):\r\n            s += y[i] * (x[i] ** (m - k))\r\n        b.append(s)\r\n\r\n    A = []\r\n    for k in range(m + 1):\r\n        A.append([])\r\n        for j in range(m + 1):\r\n            s = 0\r\n            for i in range(n + 1):\r\n                s += x[i] ** (2 * m - k - j)\r\n            A[k].append(s)\r\n\r\n    polynom = np.poly1d(np.linalg.solve(A, b))\r\n    return polynom\r\n\r\n\r\ndef LeastSquares(dots, m=None):\r\n    n = len(dots) - 1\r\n    if m is None:\r\n        m = n\r\n    assert 0 <= m <= n\r\n    return np.poly1d(np.polyfit(*map(list, zip(*dots)), m))\r\n\r\n\r\nsqrs = Squares(dots)\r\nprint(\"Squares polynom =\")\r\nprint(sqrs, '\\n')\r\n\r\nlast = LeastSquares(dots)\r\nprint(\"LeastSquares polynom =\")\r\nprint(last, '\\n')\r\n\r\nM = 2\r\nprint(f\"\\n Let-s build least squares polymon with degree = {M} \\n\")\r\nsqrs = Squares(dots, M)\r\nprint(\"Squares polynom =\")\r\nprint(sqrs, '\\n')\r\nlast = LeastSquares(dots, M)\r\nprint(\"LeastSquares polynom =\")\r\nprint(last, '\\n')\r\n\r\nxdot = 0.47\r\nprint(f\"Largange({xdot}) =\", lagr(xdot))\r\nprint(f\"Newton({xdot})   =\", newt(xdot))\r\nprint(f\"Squares({xdot}) =\", \"{:.4f}\".format(sqrs(xdot)))\r\nprint(f\"LeastSquares({xdot}) =\", last(xdot))\r\nprint(\"|Largange - Newton| =\", abs(lagr(xdot) - newt(xdot)))\r\nprint(\"|Squares - LeastSquares| =\", abs(sqrs(xdot) - last(xdot)))\r\nprint(\"|Inteprolation - Squares|      =\", \"{:.4f}\".format(abs((lagr(xdot) + newt(xdot)) / 2 - sqrs(xdot))))\r\nprint(\"|Inteprolation - LeastSquares| =\", abs((lagr(xdot) + newt(xdot)) / 2 - last(xdot)))\r\nprint(f\"Inaccuracy({xdot}) = \", Inaccuracy(x, xdot))\r\n", "meta": {"hexsha": "72bd3507b30d3d033b5506bdefd56fded5afc357", "size": 4688, "ext": "py", "lang": "Python", "max_stars_repo_path": "4 term/MNA/Lab 6/main.py", "max_stars_repo_name": "mrojaczy/Labs", "max_stars_repo_head_hexsha": "21cd2ad3ddf8fa3b64cf253d147a4a04ad0667ab", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-15T17:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-15T17:11:23.000Z", "max_issues_repo_path": "4 term/MNA/Lab 6/main.py", "max_issues_repo_name": "Asphobel/Labs", "max_issues_repo_head_hexsha": "ee827143b32b691dd7736ba4888a4a9625b4694a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4 term/MNA/Lab 6/main.py", "max_forks_repo_name": "Asphobel/Labs", "max_forks_repo_head_hexsha": "ee827143b32b691dd7736ba4888a4a9625b4694a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0695187166, "max_line_length": 118, "alphanum_fraction": 0.4643771331, "include": true, "reason": "import numpy", "num_tokens": 1732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360933, "lm_q2_score": 0.9381240160063031, "lm_q1q2_score": 0.8974415187125858}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# y = ax + b \n\ndef calc_error(a,b,data):\n\terror = 0.0\n\tN = len(data)\n\tfor i in range(N):\n\t\tx = data[i,0]\n\t\ty = data[i,1]\n\t\terror += (1 / N) * ((a * x + b) - y) ** 2\n\treturn error\n\ndef step_gradient_descent(a,b,data,learning_rate):\n\tstep_a = 0\n\tstep_b = 0\n\tN = len(data)\n\tfor i in range(N):\n\t\tx = data[i,0]\n\t\ty = data[i,1]\n\t\tstep_a += (2/N) * (a * x + b - y) * x\n\t\tstep_b += (2/N) * (a * x + b - y)\n\tnew_a = a - learning_rate * step_a\n\tnew_b = b - learning_rate * step_b\n\treturn (new_a,new_b) \n\n\ndef gradient_descent_runner(init_a,init_b,data,learning_rate,num_iterations):\n\ta = init_a\n\tb = init_b\n\tfor i in range(num_iterations):\n\t\t(a,b) = step_gradient_descent(a,b,data,learning_rate)\n\t\tprint('step {}: a:{} b:{} error:{}'.format(i,a,b,calc_error(a,b,data)))\n\treturn (a,b)\n\ndef main():\n\tdata = np.genfromtxt(\"data.csv\", delimiter=\",\")\n\tlearning_rate = 0.00001\n\tinit_a = 0\n\tinit_b = 0\n\tnum_iterations = 1000\n\tprint('init a:{} b:{} error:{}'.format(init_a,init_b,calc_error(init_a,init_b,data)))\n\t(new_a,new_b) = gradient_descent_runner(init_a,init_b,data,learning_rate,num_iterations)\n\tplt.scatter(data[:,0],data[:,1])\n\tpt_x = np.arange(20,80,0.1)\n\tpt_y = new_a * pt_x + new_b\n\tplt.plot(pt_x,pt_y,color='red')\n\tplt.show()\n\tprint('answer a:{} b:{} error:{}'.format(new_a,new_b,calc_error(new_a,new_b,data)))\n\nif __name__ == '__main__':\n\tmain()", "meta": {"hexsha": "9b4657c35e1238d5dcd3cd9a492d49d2ef128823", "size": 1394, "ext": "py", "lang": "Python", "max_stars_repo_path": "gradient_descent_linear.py", "max_stars_repo_name": "wapleeeeee/GradientDescentExample", "max_stars_repo_head_hexsha": "ce5a568ec0ef9da7e4f7a8985c587d0792809a57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gradient_descent_linear.py", "max_issues_repo_name": "wapleeeeee/GradientDescentExample", "max_issues_repo_head_hexsha": "ce5a568ec0ef9da7e4f7a8985c587d0792809a57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gradient_descent_linear.py", "max_forks_repo_name": "wapleeeeee/GradientDescentExample", "max_forks_repo_head_hexsha": "ce5a568ec0ef9da7e4f7a8985c587d0792809a57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3018867925, "max_line_length": 89, "alphanum_fraction": 0.6470588235, "include": true, "reason": "import numpy", "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.973240718366854, "lm_q2_score": 0.9219218284193595, "lm_q1q2_score": 0.897251862568941}}
{"text": "# -*- encoding: utf-8 -*-\n\n'''This Module List(s) out Various Functions for Calculating the Distance b/w Two Points'''\n\nimport numpy as np\n\ndef EuclideanDistance(startPoint : np.ndarray, targetPoint : np.ndarray) -> float:\n\t'''Calculates the Eulidean Distance b/w Two Points on an n-Dimensional Plane\n\t:param startPoint  : Start Point, with [x, y, ... z] Coordinates\n\t:param targetPoint : Start Point, with [x, y, ... z] Coordinates\n\n\tReturns the Distance b/w two Points (unitless Quantity)\n\t'''\n\tif (type(startPoint) != np.ndarray) or (type(targetPoint) != np.ndarray):\n\t\tstartPoint  = np.array(startPoint)\n\t\ttargetPoint = np.array(targetPoint)\n\n\treturn np.sqrt(np.sum((startPoint - targetPoint) ** 2))\n\ndef ManhattanDistance(startPoint : np.ndarray, targetPoint : np.ndarray) -> float:\n\t'''Calculates the Manhattan Distance b/w Two Points on an n-Dimensional Plane\n\t:param startPoint  : Start Point, with [x, y, ... z] Coordinates\n\t:param targetPoint : Start Point, with [x, y, ... z] Coordinates\n\n\tReturns the Distance b/w two Points (unitless Quantity)\n\t'''\n\tif (type(startPoint) != np.ndarray) or (type(targetPoint) != np.ndarray):\n\t\tstartPoint  = np.array(startPoint)\n\t\ttargetPoint = np.array(targetPoint)\n\n\treturn sum([abs(i) for i in (startPoint - targetPoint)])\n\ndef CircularEuclideanDistance(numElements : int or float, i : int or float, j : int or float) -> float:\n\t'''Calculates the Circular Euclidean Distance b/w Two-Integers (i, j) in a Circle of n-Elements'''\n\tmanhattanDistance = abs(i - j) # 1-Dimensional Distance\n\treturn min(manhattanDistance, numElements - manhattanDistance)", "meta": {"hexsha": "299b14783d82be034535db7c6e9637b40b82dbba", "size": 1596, "ext": "py", "lang": "Python", "max_stars_repo_path": "[TEMP] Reference Files/CentroidDetection/commons/DistanceFunctions.py", "max_stars_repo_name": "Madhurima1819/CentroidDetection-using-ML", "max_stars_repo_head_hexsha": "6f81cb76bd36a0a8578c9c159ceb386842cde2dc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "[TEMP] Reference Files/CentroidDetection/commons/DistanceFunctions.py", "max_issues_repo_name": "Madhurima1819/CentroidDetection-using-ML", "max_issues_repo_head_hexsha": "6f81cb76bd36a0a8578c9c159ceb386842cde2dc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "[TEMP] Reference Files/CentroidDetection/commons/DistanceFunctions.py", "max_forks_repo_name": "Madhurima1819/CentroidDetection-using-ML", "max_forks_repo_head_hexsha": "6f81cb76bd36a0a8578c9c159ceb386842cde2dc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3333333333, "max_line_length": 103, "alphanum_fraction": 0.7205513784, "include": true, "reason": "import numpy", "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357610169272, "lm_q2_score": 0.9161096227509861, "lm_q1q2_score": 0.8969040816849417}}
{"text": "import numpy as np\nimport math\n\ndef euclidean_distances(X, Y):\n    \"\"\"Compute pairwise Euclidean distance between the rows of two matrices X (shape MxK) \n    and Y (shape NxK). The output of this function is a matrix of shape MxN containing\n    the Euclidean distance between two rows.\n    \n    Arguments:\n        X {np.ndarray} -- First matrix, containing M examples with K features each.\n        Y {np.ndarray} -- Second matrix, containing N examples with K features each.\n\n    Returns:\n        D {np.ndarray}: MxN matrix with Euclidean distances between rows of X and rows of Y.\n    \"\"\"\n    all_distances = []\n    for exampleX in X:\n        one_row = []\n        for exampleY in Y:\n            one_row.append(euclidean_distance(exampleX, exampleY))\n        all_distances.append(one_row)\n    return np.array(all_distances)\n    # raise NotImplementedError()\n\ndef euclidean_distance(point1, point2):\n    sum = 0\n    for dimension in range(0, len(point1)):\n        sum += math.pow(point1[dimension] - point2[dimension], 2)\n    return math.sqrt(sum)\n\ndef manhattan_distances(X, Y):\n    \"\"\"Compute pairwise Manhattan distance between the rows of two matrices X (shape MxK) \n    and Y (shape NxK). The output of this function is a matrix of shape MxN containing\n    the Manhattan distance between two rows.\n    \n    Arguments:\n        X {np.ndarray} -- First matrix, containing M examples with K features each.\n        Y {np.ndarray} -- Second matrix, containing N examples with K features each.\n\n    Returns:\n        D {np.ndarray}: MxN matrix with Manhattan distances between rows of X and rows of Y.\n    \"\"\"\n    all_distances = []\n    for exampleX in X:\n        one_row = []\n        for exampleY in Y:\n            one_row.append(manhattan_distance(exampleX, exampleY))\n        all_distances.append(one_row)\n    return np.array(all_distances)\n    # raise NotImplementedError()\n\ndef manhattan_distance(point1, point2):\n    lat_dist = abs(point1[0] - point2[0])\n    long_dist = abs(point1[1] - point2[1])\n    true_long_dist = min(long_dist, 360 - long_dist)\n    return lat_dist + true_long_dist\n\ndef cosine_distances(X, Y):\n    \"\"\"Compute Cosine distance between the rows of two matrices X (shape MxK) \n    and Y (shape NxK). The output of this function is a matrix of shape MxN containing\n    the Cosine distance between two rows.\n    \n    Arguments:\n        X {np.ndarray} -- First matrix, containing M examples with K features each.\n        Y {np.ndarray} -- Second matrix, containing N examples with K features each.\n\n    Returns:\n        D {np.ndarray}: MxN matrix with Cosine distances between rows of X and rows of Y.\n    \"\"\"\n    all_distances = []\n    for exampleX in X:\n        one_row = []\n        for exampleY in Y:\n            one_row.append(cosine_distance(exampleX, exampleY))\n        all_distances.append(one_row)\n    return np.array(all_distances)\n    # raise NotImplementedError()\n\ndef cosine_distance(point1, point2):\n    u_dot_v = np.dot(point1, point2)\n    u_mag = math.sqrt(np.sum(np.square(point1)))\n    v_mag = math.sqrt(np.sum(np.square(point2)))\n    cosine_similarity = u_dot_v / (u_mag * v_mag)\n    return 1 - cosine_similarity\n", "meta": {"hexsha": "c8bce3f59b5626a5c98951011b81567b45b6eefc", "size": 3149, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/distances.py", "max_stars_repo_name": "mekkirachedine/coronavirus-2020-master", "max_stars_repo_head_hexsha": "fa0c58bd047cac253033c015176f22c44b51ddc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distances.py", "max_issues_repo_name": "mekkirachedine/coronavirus-2020-master", "max_issues_repo_head_hexsha": "fa0c58bd047cac253033c015176f22c44b51ddc5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distances.py", "max_forks_repo_name": "mekkirachedine/coronavirus-2020-master", "max_forks_repo_head_hexsha": "fa0c58bd047cac253033c015176f22c44b51ddc5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0470588235, "max_line_length": 92, "alphanum_fraction": 0.6741822801, "include": true, "reason": "import numpy", "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018455701407, "lm_q2_score": 0.9196425350319858, "lm_q1q2_score": 0.8968370974279953}}
{"text": "import numpy as np\n\n# array to work with\nnp.random.seed(21)\nrandom_integers = np.random.randint(1, high=500000, size=(20, 5))\nprint('#1', random_integers)\n\n# average valeu of the second column\nnp.set_printoptions(precision=2)\nprint('#2', np.average(random_integers[:, 1]))\n\n# average value of the first 5 rows of the third and fourth columns\nprint('#3', np.average(random_integers[0:4, 2:4]))\n\n# expected result of first_matrix + second_matrix\n# 1 2 3   +   1 2 3   =   2 4 6\n# 4 5 6                   5 7 9\nfirst_matrix = np.array([[1, 2, 3], [4, 5, 6]])\nprint('#4', first_matrix)\nsecond_matrix = np.array([1, 2, 3])\nprint('#4', second_matrix)\n\n# expected result of my_vector[selection]\n# [2, 4, 6]\nmy_vector = np.array([1, 2, 3, 4, 5, 6])\nselection = my_vector % 2 == 0\nprint('#5', my_vector)\nprint('#5', selection)\n\n# check two previous results\nprint('#6 for #4', first_matrix + second_matrix)\nprint('#6 for #5', my_vector[selection])\n\n# view vs copy\n# view -> arrays appoints to the same data, but displays it differently\n# copy -> arrays does not appoint to the same data\n# get a view -> slice array array[1:2]\n# get a copy -> fancy index array array[1,2]\n# changes in view just will be propagated if you use simple index a[i] = n\nmy_array = np.array([1, 2, 3])\nmy_slice = my_array[1:3]\nmy_slice[0] = -1\nprint('#7: both will be changed', my_array, my_slice)\nmy_array = np.array([1, 2, 3])\nmy_slice = my_array[[1, 2]]\nmy_slice[0] = -1\nprint('#7: just slice will be changed', my_array, my_slice)\nmy_array = np.array([[1, 2, 3], [4, 5, 6]])\nmy_slice = my_array[:, 1:3]\nprint('#8', my_array, my_slice)\nmy_array[:, :] = my_array * 2\nprint('#9', my_array, my_slice)\nmy_array = my_array * 2\nprint('#10', my_array, my_slice)\nmy_array = np.array([[1, 2, 3], [4, 5, 6]])\nprint('#11', my_array)\nmy_slice = my_array[:, 1:3].copy()\nprint('#11', my_slice)\nmy_array[:, :] = my_array * 2\nprint('#11', my_array, my_slice)\n", "meta": {"hexsha": "9cb2ff2bc7d8dad4c5577e493aa183fe3e19b4a5", "size": 1910, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/numpy/intermediario/index.py", "max_stars_repo_name": "stemDaniel/linear-algebra", "max_stars_repo_head_hexsha": "47c9c3cccf168edb0f6b31bcc95775137f61cb34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/numpy/intermediario/index.py", "max_issues_repo_name": "stemDaniel/linear-algebra", "max_issues_repo_head_hexsha": "47c9c3cccf168edb0f6b31bcc95775137f61cb34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/numpy/intermediario/index.py", "max_forks_repo_name": "stemDaniel/linear-algebra", "max_forks_repo_head_hexsha": "47c9c3cccf168edb0f6b31bcc95775137f61cb34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3114754098, "max_line_length": 74, "alphanum_fraction": 0.6617801047, "include": true, "reason": "import numpy", "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620596782468, "lm_q2_score": 0.9343951666514724, "lm_q1q2_score": 0.8967970296988158}}
{"text": "import numpy as np\nfrom numpy.linalg import inv\nfrom functools import reduce\nimport argparse\n\n'''\nThis is just for practice purpose. Scipy and numpy\nhave already provided enough tools.\n'''\ndef x_hat(A, b):\n    '''\n    the x to project b onto A when b is not in col space of A\n    '''\n    aTa = A.T.dot(A)\n    aTa_inv = inv(aTa)\n    return aTa_inv.dot(A.T).dot(b)\n\ndef make_perm_mx(size, original_row, to_swap):\n    P = np.identity(size)\n    P[original_row, :] = P[to_swap, :] = 0\n    P[original_row, to_swap] = P[to_swap, original_row] = 1\n    return P\n\ndef make_subtract_mx(size, current_row, current_col, factor):\n    I = np.identity(size)\n    I[current_row, current_col] = factor\n    return I\n\ndef LU(A):\n    '''\n    LU factorization by elimination.\n    U = e1*p1*e2*...*A = E*A\n    L = inv(E)\n    A = L*U\n    E as elimination matrix. p and e are permutation and subtraction mx at each step.\n    Pivots located in U\n    Note: this workflow is not optimized for performance. But efficiency is not considered here.\n    '''\n    nrows, ncols = A.shape\n    U = A.copy()\n    E = np.identity(nrows)\n    npivots = nrows if nrows <= ncols else ncols # mx might not be square. number of pivots take the smaller value\n    for col in range(npivots): # loop through columns\n        row_w_max_val = A[:, col].argmax() # find the largest value as the pivot\n        p = make_perm_mx(npivots, col, row_w_max_val)\n        U = p.dot(U)\n        E = p.dot(E)\n        for row in range(col,npivots):\n            if row != col: # omit the diagnal\n                factor = U[row, col]/U[col, col]*-1\n                e = make_subtract_mx(npivots, row, col, factor) # make subtraction mx for current pivot col\n                E = e.dot(E)\n                U = e.dot(U)\n    L = inv(E)\n    return L, U\n\ndef find_pivot(A):\n    _, U = LU(A)\n    return np.diagonal(U)\n\ndef find_det(A):\n    pivots = find_pivot(A)\n    det = reduce(lambda x, y: x*y, pivots)\n    return det\n\ndef factorize(A=None):\n    L, U = LU(A)\n    pivots = find_det(A)\n    return {'L': L, 'U': U, 'pivots': find_pivot(A), 'determines': find_det(A)}\n\ndef project(A=None, b=None):\n    '''\n    * is dot product\n    p = P*b = a*inv(aT*a)*aT*b\n    '''\n    aTa = A.T.dot(A)\n    aTa_inv = inv(aTa)\n    x_bar = aTa_inv.dot(A.T)\n    p = A.dot(x_bar).dot(b)\n    return p, x_bar\n\n\n\n### command parsing###\ndef input_to_mx(i):\n    return np.array(eval(i))\n\ndef run_cmd(parsed_arg, cmd_name):\n    '''\n    gather arguments for each sub-commands\n    and parse arguments into correct data type\n    '''\n    cmd = eval(getattr(parsed_arg, cmd_name))\n    _, *keys= parsed_arg.__dict__.keys() # exclude the first 'command' argument\n    _, *values = parsed_arg.__dict__.values()\n    transformed_values = [input_to_mx(each) for each in values if each.strip().startswith('[')]\n    args = dict(zip(keys, transformed_values))\n    return cmd(**args)\n\ndef show(result):\n    print(result)\n\ndef main():\n    '''\n    reflection is used to call function.\n    So the names of subcommands need to be same as the names of the function.\n    '''\n\n    arg = argparse.ArgumentParser(description='Calculations in Linear Algebra')\n    sub_parsers = arg.add_subparsers(\n        title='calculation',\n        description='enter the calculation to be done',\n        help='calculations',\n        dest='command',\n        required=True\n    )\n\n    ###projection###\n    projection_args = sub_parsers.add_parser('project', help='project help')\n    projection_args.add_argument('-A', '--A', help='matrix to be projected on. example: [[1,2,3], [1,2,3]] is a 2x3 matrix.')\n    projection_args.add_argument('-b', '--b', help='matrix to poject')\n\n    factorization_args = sub_parsers.add_parser('factorize', help='LU factorization. return L, U, pivots and determines')\n    factorization_args.add_argument('-A', '--A', help='matrix to be projected on. example: [[2,1,0],[1,2,1],[0,1,2]] is a 3x3 matrix.')\n\n    args = arg.parse_args()\n    \n    result = run_cmd(args, 'command')\n    show(result)\n    \n\n\n\nif __name__ == '__main__':\n    # A = np.array([1,0,1,1,1,2]).reshape(3,2)\n    # b = np.array([6,0,0])\n    # print(x_hat(A, b))\n    main()", "meta": {"hexsha": "de322c3bc9b7ef55bde983ebe1a9cace850bfbfb", "size": 4120, "ext": "py", "lang": "Python", "max_stars_repo_path": "pkg/Linear_Algebra.py", "max_stars_repo_name": "gzu300/Linear_Algebra", "max_stars_repo_head_hexsha": "437a285b0230f4da8b0573b04da32ee965b09233", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pkg/Linear_Algebra.py", "max_issues_repo_name": "gzu300/Linear_Algebra", "max_issues_repo_head_hexsha": "437a285b0230f4da8b0573b04da32ee965b09233", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pkg/Linear_Algebra.py", "max_forks_repo_name": "gzu300/Linear_Algebra", "max_forks_repo_head_hexsha": "437a285b0230f4da8b0573b04da32ee965b09233", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8550724638, "max_line_length": 135, "alphanum_fraction": 0.6230582524, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995762509216, "lm_q2_score": 0.9284087926320945, "lm_q1q2_score": 0.8967496593909698}}
{"text": "\"\"\"\nA manager wants to find the relationship between the number of hours \nthat a plant is operational in a week and weekly production.\n\nProduction Hours(x) : 34, 35, 39, 42, 43, 47\nProduction volume(y): 102, 109, 137, 148, 150, 158\n\"\"\"\n\nfrom scipy.stats import linregress\n\nx = [34, 35, 39, 42, 43, 47]\ny = [102, 109, 137, 148, 150, 158]\n\nslope = round(linregress(x, y).slope, 1)\nintercept = round(linregress(x,y ).intercept, 1)\n\n#formula\nprint(f\" y = {intercept} + {slope}x\")\n\n\"\"\"\nif manager wants to produce 125 units per week, then he should run\nx = -46.0 + 4.5x\n125 = -46.0 + 4.5x\nx = 38 hours per week\n\"\"\"\n", "meta": {"hexsha": "f8ead1fd1cf21c53a5741a10a9ace59c1db4aeef", "size": 610, "ext": "py", "lang": "Python", "max_stars_repo_path": "Probability & Statistics/production_plant_linear_regression.py", "max_stars_repo_name": "ptyadana/probability-and-statistics-for-business-and-data-science", "max_stars_repo_head_hexsha": "6c4d09c70e4c8546461eb7ebc401bb95a0827ef2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-01-14T15:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T14:06:25.000Z", "max_issues_repo_path": "Probability & Statistics/production_plant_linear_regression.py", "max_issues_repo_name": "ptyadana/probability-and-statistics-for-business-and-data-science", "max_issues_repo_head_hexsha": "6c4d09c70e4c8546461eb7ebc401bb95a0827ef2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Probability & Statistics/production_plant_linear_regression.py", "max_forks_repo_name": "ptyadana/probability-and-statistics-for-business-and-data-science", "max_forks_repo_head_hexsha": "6c4d09c70e4c8546461eb7ebc401bb95a0827ef2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-03-24T13:00:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T16:32:20.000Z", "avg_line_length": 23.4615384615, "max_line_length": 69, "alphanum_fraction": 0.668852459, "include": true, "reason": "from scipy", "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9787126444811033, "lm_q2_score": 0.9161096158798117, "lm_q1q2_score": 0.8966080647922982}}
{"text": "'''\nThe standard deviation and the variance\n100xp\n\nAs mentioned in the video, the standard deviation is the square root of the variance.\nYou will see this for yourself by computing the standard deviation using np.std() and\ncomparing it to what you get by computing the variance with np.var() and then computing\nthe square root.\n\nInstructions\n-Compute the variance of the data in the versicolor_petal_length array using np.var().\n-Print the square root of this value.\n-Compute the standard deviation of the data in the versicolor_petal_length array using\nnp.std() and print the result.\n'''\nimport numpy as np\n\nversicolor_petal_length = np.array([4.7,  4.5,  4.9,  4.,  4.6,  4.5,  4.7,  3.3,  4.6,  3.9,  3.5,\n                                    4.2,  4.,  4.7,  3.6,  4.4,  4.5,  4.1,  4.5,  3.9,  4.8,  4.,\n                                    4.9,  4.7,  4.3,  4.4,  4.8,  5.,  4.5,  3.5,  3.8,  3.7,  3.9,\n                                    5.1,  4.5,  4.5,  4.7,  4.4,  4.1,  4.,  4.4,  4.6,  4.,  3.3,\n                                    4.2,  4.2,  4.2,  4.3,  3.,  4.1])\n\n# Compute the variance: variance\nvariance = np.var(versicolor_petal_length)\n\n# Print the square root of the variance\nprint(np.sqrt(variance))\n\n# Print the standard deviation\nprint(np.std(versicolor_petal_length))\n", "meta": {"hexsha": "265937b504678746a6ee38033d12d66d1cd57996", "size": 1292, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/2-quantitative-exploratory-data-analysis/the-standard-deviation-and-the-variance.py", "max_stars_repo_name": "aimanahmedmoin1997/DataCamp", "max_stars_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-12T04:49:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T00:40:28.000Z", "max_issues_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/2-quantitative-exploratory-data-analysis/the-standard-deviation-and-the-variance.py", "max_issues_repo_name": "aimanahmedmoin1997/DataCamp", "max_issues_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/2-quantitative-exploratory-data-analysis/the-standard-deviation-and-the-variance.py", "max_forks_repo_name": "aimanahmedmoin1997/DataCamp", "max_forks_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-11-06T17:43:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T21:08:16.000Z", "avg_line_length": 40.375, "max_line_length": 99, "alphanum_fraction": 0.5998452012, "include": true, "reason": "import numpy", "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446456243805, "lm_q2_score": 0.9207896807817186, "lm_q1q2_score": 0.8965219424393028}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.figsize'] = [16, 12]\nplt.rcParams.update({'font.size': 18})\n\n# Create a simple signal with two frequencies\n\ndt = 0.001\nt = np.arange(0, 1, dt)\nf = np.sin(2*np.pi*50*t) + np.sin(2*np.pi*120*t)    # Sum of the two frequencies\nf_clean = f\nf = f + 2.5*np.random.randn(len(t))     # Noise addition to the signal\n\nplt.plot(t, f, color='c', linewidth=1.5, label='Noisy')\nplt.plot(t, f_clean, color='k', linewidth=2, label='Clean')\nplt.xlim(t[0], t[-1])\nplt.legend()\n\nn = len(t)\nfhat = np.fft.fft(f, n)     # fast fourier transform\nPSD = fhat * np.conj(fhat) / n      # power spectrum (pow per freq)\nfreq = (1/(dt*n)) * np.arange(n)    # axis of freqs in Hz\nL = np.arange(1, np.floor(n/2), dtype='int')    # Only plot the first half of frequencies in the vector\n\nfig, axs = plt.subplots(2, 1)\n\nplt.sca(axs[0])\nplt.plot(t, f, color='c', linewidth=1.5, label='Noisy')\nplt.plot(t, f_clean, color='k', linewidth=2, label='Clean')\nplt.xlim(t[0], t[-1])\nplt.legend()\n\nplt.sca(axs[1])\nplt.plot(freq[L], PSD[L], color='c', linewidth=2, label='Noisy')\nplt.xlim(freq[L[0]], freq[L[-1]])\nplt.legend()\n\n# Use the PSD to filter out noise\n\nindices = PSD > 100     # Find all freqs with larger power\nPSDclean = PSD * indices    # zero out all other frequencies\nfhat = indices * fhat   # Zero out all small fourier coefficients\nffilt = np.fft.ifft(fhat)   # Inverse fft in order to arrive at the filtered time signal\n\nfig, axs = plt.subplots(3, 1)\n\nplt.sca(axs[0])\nplt.plot(t, f, color='c', linewidth=1.5, label='Noisy')\nplt.plot(t, f_clean, color='k', linewidth=2, label='Clean')\nplt.xlim(t[0], t[-1])\nplt.legend()\n\nplt.sca(axs[1])\nplt.plot(t, ffilt, color='k', linewidth=2, label='Filtered')\nplt.xlim(t[0], t[-1])\nplt.legend()\n\nplt.sca(axs[2])\nplt.plot(freq[L], PSD[L], color='c', linewidth=1.5, label='Noisy')\nplt.plot(freq[L], PSDclean[L], color='k', linewidth=2, label='Filtered')\nplt.xlim(freq[L[0]], freq[L[-1]])\nplt.legend()\n\nplt.show()\n", "meta": {"hexsha": "135a59f6cc980d34d260b28e6e44ce4df5af32ca", "size": 1993, "ext": "py", "lang": "Python", "max_stars_repo_path": "DenoisingFFT.py", "max_stars_repo_name": "EduardoAlm/Digital-Signal-Processing-and-Data-pre--processing", "max_stars_repo_head_hexsha": "7cfc3f017699b4edc40bd4852967fb3ffab3a2ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DenoisingFFT.py", "max_issues_repo_name": "EduardoAlm/Digital-Signal-Processing-and-Data-pre--processing", "max_issues_repo_head_hexsha": "7cfc3f017699b4edc40bd4852967fb3ffab3a2ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DenoisingFFT.py", "max_forks_repo_name": "EduardoAlm/Digital-Signal-Processing-and-Data-pre--processing", "max_forks_repo_head_hexsha": "7cfc3f017699b4edc40bd4852967fb3ffab3a2ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6615384615, "max_line_length": 103, "alphanum_fraction": 0.6532865028, "include": true, "reason": "import numpy", "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561667674652, "lm_q2_score": 0.9252299586383205, "lm_q1q2_score": 0.8964147511047436}}
{"text": "#---------------------------------------------#\r\n#  Gauss-Seidel Linear System Numeric Solver  #\r\n#                  09/05/21                   #\r\n#---------------------------------------------#\r\n\r\nimport numpy as np\r\n\r\n#Setup \r\nn = 3\r\naMat = np.array([[4,-2,-1],[-5,-15,-9],[2,2,-5]])\r\nxMat = np.zeros(n)\r\nxMat_prev = np.zeros(n)\r\nbMat = np.array([1,-9,-8])\r\nbetaMat = np.zeros(n)\r\nerrorVal = 1e-3\r\nerrorCalc = 0.0\r\nitNum = 0\r\nitMax = 1000\r\n\r\n#Matrix check\r\nfor i in range(0, n):\r\n    if aMat[i, i] == 0:\r\n        print(\"Matrix has at least one element in main diagonal which equals 0\")\r\n\r\n#Sassenfeld Criteria\r\nfor i in range(0, n):\r\n    for j in range(0 , i):\r\n        betaMat[i] = betaMat[i] + np.abs(aMat[i, j])*betaMat[j]\r\n    for j in range(1+i, n):\r\n        betaMat[i] = betaMat[i] + np.abs(aMat[i, j])\r\n    betaMat[i] = betaMat[i] / np.abs(aMat[i, i])\r\nif np.max(betaMat) < 1.:\r\n    print(\"Sassenfeld Criteria fulfilled. Method will converge. Max beta = \" + str(np.max(betaMat)))\r\n    multiplier = (np.max(betaMat)/ 1 + np.max(betaMat))\r\nelse:\r\n    print(\"Sassenfeld Criteria not fulfilled. Cannot guarantee convergence.\")\r\n    multiplier = 1000\r\n    \r\n#Iterative process\r\nfor k in range(0, itMax):\r\n    print(str(xMat[:]))\r\n    for i in range(0, n):\r\n        xMat[i] = bMat[i]\r\n        for j in range(0, i):\r\n            xMat[i] = xMat[i] - aMat[i, j]*xMat[j]\r\n        for j in range(i+1, n):\r\n            xMat[i] = xMat[i] - aMat[i, j]*xMat_prev[j]\r\n        xMat[i] = xMat[i] / aMat[i, i] \r\n    #Error calculation\r\n    errorCalc = multiplier * np.max(np.abs(xMat - xMat_prev))\r\n    itNum += 1\r\n    print(\"Iteration nº\" + str(itNum) + \" // Current errorValue = \" + str(errorCalc))\r\n    if(errorCalc < errorVal):\r\n        break\r\n    xMat_prev = np.copy(xMat)\r\n\r\n#Final verification\r\nfinalVal = np.matmul(aMat, xMat)\r\nprint(\"Final results are: \" + str(xMat[:]))\r\nprint(\"With residue: \" + str(np.max(np.abs(bMat - finalVal))))\r\n", "meta": {"hexsha": "2eda76bac81a33021c808c511be4c067b5c111a8", "size": 1935, "ext": "py", "lang": "Python", "max_stars_repo_path": "Gauss-Seidel.py", "max_stars_repo_name": "Guilherme-AD/Numeric-Algorithms", "max_stars_repo_head_hexsha": "c76c76e664a19be8fcf9fbd4240c40cb999a78ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Gauss-Seidel.py", "max_issues_repo_name": "Guilherme-AD/Numeric-Algorithms", "max_issues_repo_head_hexsha": "c76c76e664a19be8fcf9fbd4240c40cb999a78ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gauss-Seidel.py", "max_forks_repo_name": "Guilherme-AD/Numeric-Algorithms", "max_forks_repo_head_hexsha": "c76c76e664a19be8fcf9fbd4240c40cb999a78ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7213114754, "max_line_length": 101, "alphanum_fraction": 0.5400516796, "include": true, "reason": "import numpy", "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688146, "lm_q2_score": 0.9284088074883808, "lm_q1q2_score": 0.8962683707556699}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\nimport math\n\n# distribution\n# In probability theory and statistics, the Laplace distribution is a continuous probability distribution\n# named after Pierre-Simon Laplace. \n# It is also sometimes called the double exponential distribution, \n# because it can be thought of as two exponential distributions \n# (with an additional location parameter) spliced together back-to-back, \n# although the term is also sometimes used to refer to the Gumbel distribution. \n# The difference between two independent identically distributed exponential random variables\n# is governed by a Laplace distribution, as is a Brownian motion evaluated at an exponentially distributed random time. \n# Increments of Laplace motion or a variance gamma process evaluated over the time scale also have a Laplace distribution.\n\nex = -1.0\nscale = 2.0\ndistribution = stats.laplace(loc = ex, scale = scale)\n\n# calculate the real dispersion/variance for the given laplasse distribution\n# it is 2*scale^2: 2 * 4 = 8\ndx = distribution.var()\n\n# generate 1000 values from distribution for the hist vs pdf plot\nvalues = distribution.rvs(size = 1000)\n\n# x axis bounds\nleft = -10\nright = 10\n\n# hist and probability density function\nplt.hist(values, 50, normed=True)\nx = np.linspace(left, right, num=100)\ny = distribution.pdf(x)\nplt.plot(x, y, linewidth=2, color='r')\nplt.ylabel('$f(x)$')\nplt.xlabel('$x$')\nplt.show()\n\nk = 1000 #number of samples\ndef sample(n):\n    samples = np.zeros(k)\n    for index in range(k):\n        # for each sample find its average, the result array is our X estimation \n        samples[index] = distribution.rvs(size = n).mean()      \n    return samples\n\n# create a histogram of X estimation\ndef clt(n):\n    plt.title(f\"X and Normal Distribution for n={n}\")\n    samples = sample(n)\n    # hist and probability density function\n    plt.ylabel('$f(x)$')\n    plt.xlabel('$x$')\n    plt.hist(samples, 20, normed=True, label=\"experimental\")\n    # count parameters for normal distributions approximating averages\n    # the mean is the same as for distribution,so just reuse it\n    sigma = math.sqrt(dx / n)\n    norm_rv = stats.norm(loc = ex, scale = sigma) \n    x = np.linspace(left, right, num=100)\n    pdf = norm_rv.pdf(x)\n    plt.plot(x, pdf, linewidth=2, color='r', label='theoretical')\n    plt.legend(loc = 'upper right')\n    \n# for n = 5, 10, 50 show clt(n)   \nfor n in [5, 10, 50]:\n    plt.figure()\n    clt(n)\n    plt.show()\n        \n# Conclusion\n# Central theorem works!\n# Even for small n approximation is very close to the actual values.\n# The more n the better approximation. ", "meta": {"hexsha": "5d9c8110d056f2aa68564e05426a0c58deed1523", "size": 2643, "ext": "py", "lang": "Python", "max_stars_repo_path": "coursera/ml_yandex/course1/course1week1/test.py", "max_stars_repo_name": "VadimKirilchuk/education", "max_stars_repo_head_hexsha": "ebddb2fb971ff1f3991e71fcb17ce83b95c4a397", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "coursera/ml_yandex/course1/course1week1/test.py", "max_issues_repo_name": "VadimKirilchuk/education", "max_issues_repo_head_hexsha": "ebddb2fb971ff1f3991e71fcb17ce83b95c4a397", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coursera/ml_yandex/course1/course1week1/test.py", "max_forks_repo_name": "VadimKirilchuk/education", "max_forks_repo_head_hexsha": "ebddb2fb971ff1f3991e71fcb17ce83b95c4a397", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.24, "max_line_length": 122, "alphanum_fraction": 0.7143397654, "include": true, "reason": "import numpy,import scipy", "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542829224748, "lm_q2_score": 0.9343951620842038, "lm_q1q2_score": 0.8962291216551042}}
{"text": "from sympy import symbols, Poly\n\n\ndef is_square(n):\n    \"\"\"\n    判断n是否是平方数\n    :param n:\n    :return: True或False\n    \"\"\"\n    low = 1\n    high = n\n    while low <= high:\n        mid = int((low + high) / 2)\n        power = mid * mid\n        if power > n:\n            high = mid - 1\n        elif power < n:\n            low = mid + 1\n        else:\n            return True\n    return False\n\n\ndef euclidean_gcd(a, b):\n    \"\"\"\n    使用欧几里得算法, 计算两个数的最大公约数\n    :param a:\n    :param b:\n    :return: gcd(a,b)\n    \"\"\"\n    if a == 0 and b == 0:\n        return 0\n    elif a == 0 and b != 0:\n        return b\n    elif a != 0 and b == 0:\n        return a\n\n    while b != 0:\n        # 不使用 % , 因为 % 在不同的编程语言中的结果可能是不同的(虽然都是同余的)\n        # a, b = b, a % b\n        q = int(a / b)\n        r = a - q * b\n        a, b = b, r\n    return a\n\n\ndef euclidean_linear_combination(a, b, show_trace=False):\n    \"\"\"\n    求线性方程的 ax + by = gcd(a,b) 的一个解 (x1, y1)\n    根据线性方程定理, 方程的一般解可由 (x1 + k * (b / g), y1 - k * (a / g)) 得到\n    其中 g = gcd(a,b), k为任意整数\n    :param a:\n    :param b:\n    :param show_trace: 显示计算过程\n    :return: 返回 x1, y1, gcd(a,b)\n    \"\"\"\n    if a == 0 and b == 0:\n        return 0, 0, 0\n    elif a == 0 and b != 0:\n        return 0, 1, b\n    elif a != 0 and b == 0:\n        return 1, 0, a\n\n    # 使用欧几里得算法求最大公约数并记录中间过程的除数与余数\n    q_list = []\n    r_list = [a, b]\n    while b != 0:\n        q = int(a / b)\n        r = a - q * b\n        q_list.append(q)\n        a, b = b, r\n        r_list.append(r)\n    g = a\n\n    # 递推获取得到解的方程\n    a, b = symbols('a b')\n    eq_list = []\n    eq_list.append(a)\n    eq_list.append(b)\n    len_list = len(q_list) - 1\n    for i in range(len_list):\n        eq_list.append(eq_list[i] - q_list[i] * eq_list[i + 1])\n        if show_trace is True:\n            print(\"{} = {} * {} + {} => {} = {}\".format(\n                r_list[i], q_list[i], r_list[i + 1], r_list[i + 2], r_list[i + 2], eq_list[-1]))\n\n    # 获取方程中a, b的系数\n    p = Poly(eq_list[-1])\n    x1 = None\n    y1 = None\n    for monom, coeff in p.as_dict().items():\n        if monom[0] == 1:\n            x1 = coeff\n        elif monom[1] == 1:\n            y1 = coeff\n        else:\n            continue\n    return x1, y1, g\n\n\ndef linear_congruence(a, c, m):\n    \"\"\"\n    求线性同余方程 ax=c(mod m) 的解\n    :param a:\n    :param c:\n    :param m:\n    :return: 解的列表\n    \"\"\"\n    if a == 0 or m == 0:\n        raise Exception(\"linear congruence input invalid arguments\")\n\n    u, v, g = euclidean_linear_combination(a, m)\n    if int(c / g) * g != c:\n        return []\n\n    sol_list = []\n    x0 = int(u * c / g)\n    for k in range(0, g):\n        sol_list.append(x0 + int(k * m / g))\n    return sol_list\n", "meta": {"hexsha": "794eb6b0f0e36d35c78cafd7d5c4c2e15356e667", "size": 2628, "ext": "py", "lang": "Python", "max_stars_repo_path": "play/number_theory/utils.py", "max_stars_repo_name": "MuggleWei/Hakuna_Matata", "max_stars_repo_head_hexsha": "6a3a012dc2a5942599098d94e90e9381d660500d", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "play/number_theory/utils.py", "max_issues_repo_name": "MuggleWei/Hakuna_Matata", "max_issues_repo_head_hexsha": "6a3a012dc2a5942599098d94e90e9381d660500d", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-03-04T21:59:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T16:46:52.000Z", "max_forks_repo_path": "play/number_theory/utils.py", "max_forks_repo_name": "MuggleWei/Hakuna_Matata", "max_forks_repo_head_hexsha": "6a3a012dc2a5942599098d94e90e9381d660500d", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7190082645, "max_line_length": 96, "alphanum_fraction": 0.4657534247, "include": true, "reason": "from sympy", "num_tokens": 1004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407168145569, "lm_q2_score": 0.9207896715436483, "lm_q1q2_score": 0.8961499999685807}}
{"text": "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n# Week 2 from \"Fundamentals of Digital Image and Video Processing\"\n#\n# Question 7\n#\n# In this problem you will implement spatial-domain low-pass filtering\n# using MATLAB, and evaluate the difference between the filtered image\n# and the original image using two quantitative metrics called\n# Mean Squared Error (MSE) and Peak Signal-to-Noise Ratio (PSNR).\n#\n#\n# Given two N1×N2 images x(n1,n2) and y(n1,n2), the MSE is computed as\n# MSE=1N1N2∑N1n1=1∑N2n2=1[x(n1,n2)−y(n1,n2)]2. The PSNR is defined as\n# PSNR=10log10(MAX2IMSE), where MAXI is the maximum possible pixel value\n# of the images. For the 8-bit gray-scale images considered in this\n# problem, MAXI=255. Follow the instructions below to finish this\n# problem.\n#\n# (1) Download the original image from here. The original image is\n#     a 256×256 8-bit gray-scale image.\n# (2) Convert the original image from type 'uint8' (8-bit integer) to\n#     'double' (real number).\n# (3) Create a 3×3 low-pass filter with all coefficients equal to 1/9,\n#     i.e., create a 3×3 MATLAB array with all elements equal to 1/9.\n# (4) Low-pass filter the original image (converted to type 'double')\n#     with\n#     the filter created in step (3). This can be done using the\n#     built-in MATLAB function \"imfilter\". The function \"imfilter\" takes\n#     three arguments and returns one output. The first argument is the\n#     original image (converted to type 'double'); the second argument\n#     is the low-pass filter created in step (3); and the third argument\n#     is a string specifying the boundary filtering option. For this\n#     problem, use 'replicate' (including the single quotes) for the\n#     third argument. The output of the function \"imfilter\" is the\n#     filtered image.\n# (5) Compute and record the PSNR value between the original image\n#     (converted to type 'double') and the filtered image by using the\n#     formulae given above.\n# (6) Repeat steps (3) through (5) using a 5×5 low-pass filter with all\n#     coefficients equal to 1/25. Enter the PSNR values you have\n#     obtained from your experiments (The PSNR corresponding to 3×3\n#     filter first, followed by the PSNR corresponding to 5×5 filter).\n#     Make sure you order the answers correctly and separate them by a\n#     space. Enter the numbers to 2 decimal points.\n#\n# Note: Answers are 29.2951 for 3x3 matrix and 25.7335 for 5x5 matrix\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.ndimage as ndimage\nimport Image\n\ndef plot(data, title):\n    plot.i += 1\n    plt.subplot(2,2,plot.i)\n    plt.imshow(data)\n    plt.gray()\n    plt.title(title)\n\n# Usig the original to get the same results\nim = Image.open('lena.gif')\n\n# image converted to double with max value of 1\ndata = np.array(im)/255.0\nplot.i = 0\nplot(data, 'Original')\n\n# Create the filters\nk3 = np.ones((3,3))/9.0\nk5 = np.ones((5,5))/25.0\n\n# Now the convolution\nlp3 = ndimage.convolve(data, k3, mode='nearest')\nlp5 = ndimage.convolve(data, k5, mode='nearest')\n\nmse3 = np.sum(np.power(lp3-data,2))/np.size(data)\nmse5 = np.sum(np.power(lp5-data,2))/np.size(data)\n\n#~ PSNR = 10*np.log10(np.power(MAXi,2)/MSE);\npsnr3 = 10*np.log10(np.power(1.0,2)/mse3);\npsnr5 = 10*np.log10(np.power(1.0,2)/mse5);\n\nprint psnr3, psnr5\n\nplot(lp3, '3x3 low-pass')\nplot(lp5, '5x5 low-pass')\nplt.show()\n\n# other posible modes for borders:\n# reflect:  29.2951 25.7315\n# constant: 28.3131 24.9244 with cval=0\n# nearest:  29.2951 25.7335\n# mirror:   29.2872 25.7261\n# wrap:     28.8001 25.3345\n#\n# Answer from matlab:  29.2951 25.7335\n# *nearest* is the exact replacement and *reflect* is very close\n", "meta": {"hexsha": "4aec43a5ff928b4ef027d881066047da59710fd0", "size": 3617, "ext": "py", "lang": "Python", "max_stars_repo_path": "W02/W03Q07.py", "max_stars_repo_name": "Cortez-Zhang/FDIVP", "max_stars_repo_head_hexsha": "86858f845a8fecc7537b55b420b1941f62a2b9f1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 51, "max_stars_repo_stars_event_min_datetime": "2016-03-08T18:35:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T08:45:21.000Z", "max_issues_repo_path": "W02/W03Q07.py", "max_issues_repo_name": "Cortez-Zhang/FDIVP", "max_issues_repo_head_hexsha": "86858f845a8fecc7537b55b420b1941f62a2b9f1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-12-06T05:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-02T23:33:34.000Z", "max_forks_repo_path": "W02/W03Q07.py", "max_forks_repo_name": "Cortez-Zhang/FDIVP", "max_forks_repo_head_hexsha": "86858f845a8fecc7537b55b420b1941f62a2b9f1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2016-04-25T09:01:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T06:22:57.000Z", "avg_line_length": 36.17, "max_line_length": 72, "alphanum_fraction": 0.7063865082, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.9473810488807637, "lm_q1q2_score": 0.8960342022675039}}
{"text": "import numpy as np\n\n\ndef entropy(prob_dist):\n    \"\"\"\n    Calculates the entropy of a distribution\n\n    Arguments\n    -----------------------\n    prob_dist (numpy array):\n    A probability distribution (prob_dist.sum() = 1)\n\n    Returns\n    -----------------------\n    entropy (scalar):\n    The entropy in bites of the probability distribution\n\n    Examples\n    -----------------------\n    >>> p_example_1 = np.array((0.5, 0.5))\n    >>> entropy(p_example_1)\n    1.0\n    >>> p_example_2 = np.array((0.1, 0.9))\n    >>> entropy(p_example_2)\n    0.46899559358928122\n    >>> entropy(np.array((0.5, 0.3))) == entropy(np.array((0.3, 0.5)))\n    True\n    \"\"\"\n    return -np.sum(prob_dist * np.log2(prob_dist))\n\n\ndef joint_entropy(prob_dist):\n    \"\"\"\n    Calculates mutual entropy of a prob_dist\n\n    Arguments\n    -----------------------------\n    prob_dist (numpy array):\n    A joint probability distribution (prob_dist.sum() = 1)\n    the sum over the first index gives the second prob distribution\n    that is, we marginalize the first variable.\n\n    Returns\n    -----------------------------\n    joint_entropy (scalar):\n    The joint entropy of the probability distribution\n\n    Examples\n    -----------------------------\n    Maximal for uninformative distribution:\n    >>> p_joint= np.array((0.25, 0.25, 0.25, 0.25)).reshape((2, 2))\n    >>> p1 = p_joint.sum(axis=1)\n    >>> p2 = p_joint.sum(axis=0)\n    >>> joint_entropy(p_joint)\n    2.0\n\n    The joint entropy is bigger thatn the individual entropies:\n\n    >>> joint_entropy(p_joint) > entropy(p1)\n    True\n    >>> joint_entropy(p_joint) > entropy(p2)\n    True\n\n    On the other hand is smaller than the sum of the individual\n    entropies:\n\n    >>> joint_entropy(p_joint) <= entropy(p1) + entropy(p2)\n    True\n    \"\"\"\n    return -np.sum(prob_dist * np.log2(prob_dist))\n\n\ndef mutual_information(prob1, prob2, prob_joint):\n    \"\"\"\n    Calculates mutual information between two random variables\n\n    Arguments\n    ------------------\n    prob1 (numpy array):\n    The probability distribution of the first variable\n    prob1.sum() should be 1\n    prob2 (numpy array):\n    The probability distrubiont of the second variable\n    Again, prob2.sum() should be 1\n\n    prob_joint (two dimensional numpy array):\n    The joint probability, marginazling over the\n    different axes should give prob1 and prob2\n\n    Returns\n    ------------------\n    mutual information (scalar):\n    The mutual information between two variables\n\n    Examples\n    ------------------\n    A mixed joint:\n    >>> p_joint = np.array((0.3, 0.1, 0.2, 0.4)).reshape((2, 2))\n    >>> p1 = p_joint.sum(axis=1)\n    >>> p2 = p_joint.sum(axis=0)\n    >>> mutual_information(p1, p2, p_joint)\n    0.12451124978365299\n\n    An uninformative joint:\n    >>> p_joint = np.array((0.25, 0.25, 0.25, 0.25)).reshape((2, 2))\n    >>> p1 = p_joint.sum(axis=1)\n    >>> p2 = p_joint.sum(axis=0)\n    >>> mutual_information(p1, p2, p_joint)\n    0.0\n\n    A very coupled joint:\n    >>> p_joint = np.array((0.4, 0.05, 0.05, 0.4)).reshape((2, 2))\n    >>> p1 = p_joint.sum(axis=1)\n    >>> p2 = p_joint.sum(axis=0)\n    >>> mutual_information(p1, p2, p_joint)\n    0.58387028280246378\n\n    Using the alternative definition  of mutual information\n    >>> p_joint = np.array((0.4, 0.2, 0.1, 0.3)).reshape((2, 2))\n    >>> p1 = p_joint.sum(axis=1)\n    >>> p2 = p_joint.sum(axis=0)\n    >>> MI = mutual_information(p1, p2, p_joint)\n    >>> x1 = entropy(p1)\n    >>> x2 = entropy(p2)\n    >>> x3 = joint_entropy(p_joint)\n    >>> np.isclose(MI, x1 + x2 - x3)\n    True\n\n    \"\"\"\n    outer = np.outer(prob1, prob2)\n\n    return np.sum(prob_joint * np.log2(prob_joint / outer))\n\n\ndef mutual_information2(prob1, prob2, prob_joint):\n    \"\"\"\n    This and that\n    \"\"\"\n\n    x1 = entropy(prob1)\n    x2 = entropy(prob2)\n    x3 = joint_entropy(prob_joint)\n\n    return x1 + x2 - x3\n", "meta": {"hexsha": "867598191ad42cd6f75c6e5aa233002c73a73d1f", "size": 3833, "ext": "py", "lang": "Python", "max_stars_repo_path": "information_functions.py", "max_stars_repo_name": "h-mayorquin/mnist_deep_neural_network_BPNNs", "max_stars_repo_head_hexsha": "a679e09b5f5b18ce95282e6963662ab700c227d6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "information_functions.py", "max_issues_repo_name": "h-mayorquin/mnist_deep_neural_network_BPNNs", "max_issues_repo_head_hexsha": "a679e09b5f5b18ce95282e6963662ab700c227d6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "information_functions.py", "max_forks_repo_name": "h-mayorquin/mnist_deep_neural_network_BPNNs", "max_forks_repo_head_hexsha": "a679e09b5f5b18ce95282e6963662ab700c227d6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4344827586, "max_line_length": 70, "alphanum_fraction": 0.5901382729, "include": true, "reason": "import numpy", "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953275044028802, "lm_q2_score": 0.9399133536130195, "lm_q1q2_score": 0.8959959435487101}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport random\n\n#circumference x polar coordinate\ndef x_circle(r1,r2):\n    x= np.sqrt(r1)*np.cos(2*np.pi*r2)\n    return x\n\n#circumference y polar coordinate\ndef y_circle(r1,r2):\n    x= np.sqrt(r1)*np.sin(2*np.pi*r2)\n    return x\n\n#circunference definition, condition for random sampling: circ(x,y) <=1\ndef circ(x,y):\n    c= (x)**2+(y)**2\n    return c\n\ncx, cy = [],[]               #random points defining x and y coordinates of the circumference of radius 1   \nsx, sy = [],[]               #random points defining x and y coordinates of the square of side 2\n\ndiff= []                 #list with all the differences between real and estimated pi values\n\nN_tot=[100,1000, 5000, 100000] # N_tot[3]: total number of extracted random points inside the square\n\nfor i in range(1, N_tot[3]+1):    #loop to extract  N_tot[3] random numbers   \n    n1=random.uniform(-1,1)         # extraction of random floats between -1 and 1\n    n2=random.uniform(-1,1)\n    sx.append(n1)               # the random variables already satisfy the condition of being inside the square\n    sy.append(n2)\n    if circ(n1,n2)<=1:      #condition to for random n. to be inside the circle\n        cx.append(n1)\n        cy.append(n2)\n    d=np.pi-4*(len(cx)/i)   #for each step i, calculate the difference between real and estimated pi\n    diff.append(d)\n\npi= 4*(len(cx))/(N_tot[3])              #I compute the pi extimate through the area of the circle with N_tot[3] extractions\nprint('pi value estimated through Monte Carlo with %g extractions: %4f' %(N_tot[3],pi))\n\n#plot of the points inside the square and circle\nfig, ax1 = plt.subplots()\ncircle=plt.Circle((0,0), 1, color='r', fill=False)    \nax1.plot(sx, sy, ',', color='b')\nplt.grid()\nplt.xlim(-1.1, 1.1, 0.5)\nplt.ylim(-1.1, 1.1, 0.5)\nax1.add_patch(circle)\n\n#plot of the difference between expected and estimated pi value vs number of extractions\nx=np.arange(0, N_tot[3], 1)\nplt.figure()\nplt.plot(x, diff, 'k', x, [0]*x, 'r', linestyle='--')\nplt.xlabel('$N_{tot}$', fontsize=16)\nplt.ylabel('$\\pi - \\pi_{MC}$', fontsize=16)\nplt.title('$Expected\\ vs.\\ estimated\\ \\pi\\ values$')\nplt.xlim(-0.1, N_tot[3], 1)\nplt.ylim(-0.2, 0.2, 0.05)\nplt.xticks(fontsize=10)\nplt.yticks(fontsize=10)\n", "meta": {"hexsha": "80f525fe8f3aad6e2406d731a9cb60777689cf68", "size": 2250, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Exercise_3/ex3.0.py", "max_stars_repo_name": "alessiomei/LE_6-Exercises", "max_stars_repo_head_hexsha": "cbb43dae1025b61bb6d0d60655340035d2571d2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-25T18:33:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T18:33:53.000Z", "max_issues_repo_path": "src/Exercise_3/ex3.0.py", "max_issues_repo_name": "alessiomei/LE_6_Exercises", "max_issues_repo_head_hexsha": "cbb43dae1025b61bb6d0d60655340035d2571d2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Exercise_3/ex3.0.py", "max_forks_repo_name": "alessiomei/LE_6_Exercises", "max_forks_repo_head_hexsha": "cbb43dae1025b61bb6d0d60655340035d2571d2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8852459016, "max_line_length": 123, "alphanum_fraction": 0.6568888889, "include": true, "reason": "import numpy", "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970687766704745, "lm_q2_score": 0.9230391722430736, "lm_q1q2_score": 0.8959828326856256}}
{"text": "import heapq  # For reference solution\nimport timeit\n\nimport numpy as np\n\n\n# Number of comparisons = 3n/2 - 2\ndef second_largest_nb(arr: np.ndarray) -> list:\n    # Returns [max element of arr, second-largest element of arr]\n    len_arr = len(arr)\n    if len_arr == 1:  # Base case 1\n        return [arr[0], -np.inf]\n    else:\n        # Split array in half\n        len_left = len_arr // 2\n        left_arr, right_arr = arr[:len_left], arr[len_left:]\n        max_left, second_largest_left = second_largest_nb(left_arr)\n        max_right, second_largest_right = second_largest_nb(right_arr)\n        if max_left > max_right:\n            max_arr = max_left\n            if max_right > second_largest_left:\n                max_2_arr = max_right\n            else:\n                max_2_arr = second_largest_left\n        else:\n            max_arr = max_right\n            if max_left > second_largest_right:\n                max_2_arr = max_left\n            else:\n                max_2_arr = second_largest_right\n        return [max_arr, max_2_arr]\n\n\n# Find the largest array element recursively and store all elements that are directly compared\n# with the largest element during calculation. Returns max element and runner-ups.\n# Input is np array so that array slicing can be passed by reference.\n# Number of comparisons = n - 1, number of runner-ups = log_2^n.\ndef find_largest(arr: np.ndarray) -> (int, list):\n    if len(arr) == 1:  # Base case\n        return arr[0], []\n    else:\n        # Split array in half\n        len_left = len(arr) // 2\n        left_arr, right_arr = arr[:len_left], arr[len_left:]\n        max_left, runner_ups_left = find_largest(left_arr)\n        max_right, runner_ups_right = find_largest(right_arr)\n        if max_left > max_right:\n            runner_ups_left.append(max_right)\n            return max_left, runner_ups_left\n        else:\n            runner_ups_right.append(max_left)\n            return max_right, runner_ups_right\n\n\n# Better algorithm with time complexity = n + log_2^n - 2\ndef second_largest_nb_2(arr: np.ndarray) -> (int, int):\n    max_ele, runner_ups = find_largest(arr)\n    second_largest_ele = max(runner_ups)  # log_2^n - 1 comparisons needed here\n    return max_ele, second_largest_ele\n\n\nif __name__ == '__main__':\n    test = np.arange(1e5, dtype=np.int_)\n    np.random.shuffle(test)\n    largest_ref, second_largest_ref = heapq.nlargest(2, test)\n    print(f\"Reference largest: {largest_ref}, reference second-largest: {second_largest_ref}\")\n    repetition = int(1e2)\n\n    largest, second_largest = second_largest_nb(test)\n    print(f\"Implementation 1: largest: {largest}, second-largest: {second_largest}\")\n    print(f\"Implementation 1 is correct: {largest == largest_ref and second_largest == second_largest_ref}\")\n    ave_time_1 = timeit.timeit(stmt='second_largest_nb(test)', number=repetition,\n                               globals=globals()) / repetition\n    print(f\"Implementation 1: average running time = {ave_time_1}s\")\n\n    largest_2, second_largest_2 = second_largest_nb_2(test)\n    print(f\"Implementation 2: largest: {largest_2}, second-largest: {second_largest_2}\")\n    print(f\"Implementation 2 is correct: {largest_2 == largest_ref and second_largest_2 == second_largest_ref}\")\n    ave_time_2 = timeit.timeit(stmt='second_largest_nb_2(test)', number=repetition,\n                               globals=globals()) / repetition\n    print(f\"Implementation 2: average running time = {ave_time_2}s\")\n", "meta": {"hexsha": "f250f9bd06c5d8b2c0dd2dd7fc09f7bb66ac298f", "size": 3452, "ext": "py", "lang": "Python", "max_stars_repo_path": "SecondLargestNb.py", "max_stars_repo_name": "fxie520/Coursera-Algo-Specialization", "max_stars_repo_head_hexsha": "4ae744ec2a578ac19465305077427eb0fa44a7e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SecondLargestNb.py", "max_issues_repo_name": "fxie520/Coursera-Algo-Specialization", "max_issues_repo_head_hexsha": "4ae744ec2a578ac19465305077427eb0fa44a7e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SecondLargestNb.py", "max_forks_repo_name": "fxie520/Coursera-Algo-Specialization", "max_forks_repo_head_hexsha": "4ae744ec2a578ac19465305077427eb0fa44a7e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0975609756, "max_line_length": 112, "alphanum_fraction": 0.66801854, "include": true, "reason": "import numpy", "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660923657093, "lm_q2_score": 0.9390248127360432, "lm_q1q2_score": 0.895797831240245}}
{"text": "import numpy as np\n\n\n# Toleranța pentru comparații cu 0.\nEPSILON = 1e-11\n\n\ndef gauss_pivotare_totala(M):\n    \"\"\"Transformă matricea M într-una superior triunghiulară,\n    aplicând metoda Gauss cu pivotare totală.\n\n    Returnează matricea finală și permutarea aplicată pe coloane.\n    \"\"\"\n    N = M.shape[0]\n    M = M.copy()\n\n    # Rețin permutarea care se va aplica necunoscutelor\n    indices = np.arange(0, N)\n\n    for k in range(N - 1):\n        # Submatricea în care lucrez\n        submatrix = M[k:, k:N - 1]\n\n        # Caut elementul de valoare maximă\n        index = np.argmax(np.abs(submatrix))\n        i, j = np.unravel_index(index, submatrix.shape)\n\n        # Obțin indicii în matricea mare\n        i += k\n        j += k\n\n        # Interschimb liniile\n        M[[k, i], :] = M[[i, k], :]\n        # Interschimb coloanele\n        M[:, [k, j]] = M[:, [j, k]]\n        # Rețin permutarea necunoscutelor\n        indices[k], indices[j] = indices[j], indices[k]\n\n        # Selectez coloana\n        ratios = M[k + 1:, k]\n\n        # Determin raportul pentru fiecare rând\n        ratios = ratios / M[k, k]\n\n        row = M[k, :]\n\n        # Înmulțesc fiecare raport cu primul rând\n        difference = np.outer(ratios, row)\n\n        # Actualizez matricea\n        M[k + 1:, :] -= difference\n\n    return M, indices\n\ndef descompunere_lu(A):\n    \"\"\"Descompune matricea `A` într-un produs dintre o matrice\n    inferior triunghiulară și una superior triunghiulară.\n\n    Returnează matricea inf. tri., cea sup. tri. și matricea care reprezintă\n    permutarea aplicată matricii `A`.\n    \"\"\"\n    N = A.shape[0]\n\n    # Inițial am permutarea identică\n    P = np.eye(N)\n\n    # Matriciile L și U\n    L = np.zeros((N, N))\n    U = np.copy(A)\n\n    for k in range(N - 1):\n        # Găsesc indicele elementului de magnitudine maximă\n        index = k + np.argmax(np.abs(U[k:, k]))\n\n        # Pivotez\n        U[[k, index]] = U[[index, k]]\n        L[[k, index]] = L[[index, k]]\n\n        # Interschimb liniile și în permutare\n        P[[k, index]] = P[[index, k]]\n\n        # Selectez coloana pe care lucrez\n        ratios = U[k + 1:, k]\n\n        # Determin raportul pentru fiecare rând\n        ratios = ratios / U[k, k]\n\n        # Actualizez matricea inferior triunghiulară\n        L[k + 1:, k] = ratios\n\n        # Selectez rândul pe care vreau să-l actualizez\n        row = U[k, :]\n\n        # Înmulțesc fiecare raport cu primul rând\n        difference = np.outer(ratios, row)\n\n        # Actualizez matricea superior triunghiulară\n        U[k + 1:, :] -= difference\n\n    L += np.eye(N)\n\n    return L, U, P\n\n\ndef substitutie_descendenta(U, b):\n    N = b.shape[0]\n    x = np.zeros(N)\n\n    for i in range(N - 1, -1, -1):\n        coefs = U[i, i + 1:]\n        values = x[i + 1:]\n\n        x[i] = (b[i] - coefs @ values) / U[i, i]\n\n    return x\n\ndef substitutie_ascendenta(L, b):\n    N = b.shape[0]\n    x = np.zeros(N)\n\n    for i in range(0, N):\n        coefs = L[i, :i + 1]\n        values = x[:i + 1]\n\n        x[i] = (b[i] - coefs @ values) / L[i, i]\n\n    return x\n\ndef simetrica(M):\n    \"Verifică dacă matricea `M` este simetrică.\"\n    return np.all(M == M.T)\n\ndef pozitiv_semidefinita(M):\n    \"Verifică dacă matricea M este pozitiv-semidefinită.\"\n    for i in range(M.shape[0]):\n        minor = M[:i, :i]\n        # Dacă cel puțin un minor principal nu are determinantul nenegativ,\n        # nu este pozitiv-semidefinită.\n        if np.linalg.det(minor) < 0:\n            return False\n    return True\n\ndef descompunere_cholesky(M):\n    N = M.shape[0]\n\n    L = np.eye(N)\n\n    for i in range(N):\n        L_i = np.eye(N)\n\n        pivot = M[i, i]\n        L_i[i:, i] = M[i:, i] / np.sqrt(pivot)\n\n        M_nou = np.eye(N)\n        outer = np.outer(M[i + 1:, i], M[i, i + 1:])\n        M_nou[i + 1:, i + 1:] = M[i + 1:, i + 1:] - outer / pivot\n\n        L = L @ L_i\n        M = M_nou\n\n    # La final, M va fi matricea identitate\n\n    return L\n\n###\nprint(\"Exercițiul 1\")\n\nA = np.array([\n    [0, 6, 3, -3],\n    [-1, 7, -10, 1],\n    [7, 3, 7, 1],\n    [-9, 7, -8, 0],\n], dtype=float)\n\nb = np.array([\n    [33],\n    [-25],\n    [110],\n    [-59],\n], dtype=float)\n\nif abs(np.linalg.det(A)) <= EPSILON:\n    print(\"Sistemul nu este unic determinat\")\nelse:\n    print(\"Sistemul admite soluție unică\")\n\n    # Construiesc matricea completă a sistemului\n    M = np.hstack((A, b))\n\n    U, indices = gauss_pivotare_totala(M)\n\n    solution = substitutie_descendenta(U[:, 0:-1], U[:, -1])\n\n    # Pivotarea totală a permutat indicii;\n    # trebuie să aplicăm invers permutarea\n    solution[indices] = solution.copy()\n\n    print(\"x =\", solution)\n    print(\"Verificare:\", A @ solution, \"==\", b[:, 0])\n\n\nprint()\n\n###\nprint(\"Exercițiul 2\")\n\nB = np.array([\n    [0, -4, -8, -1],\n    [7, -8, -7, -3],\n    [7, -3, 2, -6],\n    [0, 8, -3, -3]\n], dtype=float)\n\nif abs(np.linalg.det(B)) < EPSILON:\n    print(\"Matricea nu este inversabilă\")\nelse:\n    print(\"Matricea este inversabilă\")\n\n    N = B.shape[0]\n    M = np.hstack((B, np.eye(N)))\n    U, indices = gauss_pivotare_totala(M)\n\n    for i in range(N):\n        # Facem să fie 1 pe diagonala matricei din stânga\n        U[i] /= U[i][i]\n\n    for i in range(1, N):\n        # Gauss nu elimină și elementele de deasupra diagonalei principale,\n        # trebuie să le reducem manual\n        for j in range(i):\n            ratio = U[j, i] / U[i, i]\n            U[j] -= ratio * U[i, :]\n\n    inversa = U[:4, 4:]\n\n    # Aplicăm permutarea inversă\n    inversa[indices] = inversa.copy()\n\n    # Afișăm rezultatul\n    print(\"Inversa lui B este\")\n    print(inversa)\n\n    # Determinantul este aproximativ egal cu 1\n    print(\"Verificare: det(B @ inversa) =\", np.linalg.det(B @ inversa))\n\n\nprint()\n\n###\nprint(\"Exercițiul 3\")\n\nA = np.array([\n    [0, -9, -7, 6],\n    [-6, 2, -10, 2],\n    [6, -1, 0, 5],\n    [-5, -1, -2, 7]\n], dtype=float)\n\nb = np.array([\n    [-25],\n    [-36],\n    [34],\n    [14]\n], dtype=float)\n\nif abs(np.linalg.det(A)) <= EPSILON:\n    print(\"Sistemul nu este unic determinat\")\nelse:\n    print(\"Sistemul admite soluție unică\")\n\n    L, U, P = descompunere_lu(A)\n\n    y = substitutie_ascendenta(L, b)\n    x = substitutie_descendenta(U, y)\n\n    print(\"Soluția permutată este\", x)\n    print(\"Verificare:\", P @ A @ x, \"==\", b[:, 0])\n\n\nprint()\n\n###\nprint(\"Exercițiul 4\")\n\nC = np.array([\n    [81, 63, -54, 18],\n    [63, 85, -54, 8],\n    [-54, -54, 56, 6],\n    [18, 8, 6, 46]\n], dtype=float)\n\nif simetrica(C) and pozitiv_semidefinita(C):\n    print(\"Admite factorizare Cholesky\")\n\n    L = descompunere_cholesky(C)\n\n    print(\"Matricea triunghiulară:\")\n    print(L)\n\n    print(\"Verificare:\")\n    print(L @ L.T)\n    print(\"==\")\n    print(C)\n\nelse:\n    print(\"Nu admite factorizare Cholesky\")\n", "meta": {"hexsha": "7359965b28522c9f96427a15f1704ef163e9a219", "size": 6658, "ext": "py", "lang": "Python", "max_stars_repo_path": "cn/teme/Majeri_Gabriel_332_Tema2.py", "max_stars_repo_name": "FloaterTS/teme-fmi", "max_stars_repo_head_hexsha": "624296d3b3341f1c18fb26768e361ce2e1faa68c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2020-03-17T10:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:40:30.000Z", "max_issues_repo_path": "cn/teme/Majeri_Gabriel_332_Tema2.py", "max_issues_repo_name": "florinalexandrunecula/teme-fmi", "max_issues_repo_head_hexsha": "b4d7a416a5ca71b76d66b9407ad2b8ee2af9301e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cn/teme/Majeri_Gabriel_332_Tema2.py", "max_forks_repo_name": "florinalexandrunecula/teme-fmi", "max_forks_repo_head_hexsha": "b4d7a416a5ca71b76d66b9407ad2b8ee2af9301e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2020-01-22T11:39:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T00:19:06.000Z", "avg_line_length": 21.6872964169, "max_line_length": 76, "alphanum_fraction": 0.5528687293, "include": true, "reason": "import numpy", "num_tokens": 2287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551535992067, "lm_q2_score": 0.9284088055075428, "lm_q1q2_score": 0.8957800206408362}}
{"text": "from scipy import optimize\nfrom math import exp\nfrom scipy import integrate\nimport numpy as np\n\n# -------------------------\n\n# f(x) = (x**2 -2x)exp(3-x)\n\n\ndef f(x):\n    return x*(x - 2)*exp(3 - x)\n\n\ndef fp(x):\n    return -(x**2 - 4*x + 2)*exp(3 - x)\n\n\noptimize.newton(f, 1, fprime=fp)  # Using the Newton-Raphson method 2.0\n\n# Using x1 = 1.5 and the secant method # 1.9999999999999862\noptimize.newton(f, 1., x1=1.5)\n\n\n# --------------------------\ndef erf_integrand(t):\n    return np.exp(-t**2)\n\n\nval_quad, err_quad = integrate.quad(erf_integrand, -1.0, 1.0)\n# (1.493648265624854, 1.6582826951881447e-14)\n\nval_quadr, err_quadr = integrate.quadrature(erf_integrand, -1.0, 1.0)\n# (1.4936482656450039, 7.459897144457273e-10)\n", "meta": {"hexsha": "8b367f52542dc10f35ab54033b07a315e75637c5", "size": 721, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapter3/usingScipy.py", "max_stars_repo_name": "onggieoi/python-math", "max_stars_repo_head_hexsha": "7cc6193516c4e4b4a05a90d9cac9285cfce2bea6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-08T09:32:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T09:32:30.000Z", "max_issues_repo_path": "chapter3/usingScipy.py", "max_issues_repo_name": "onggieoi/python-math", "max_issues_repo_head_hexsha": "7cc6193516c4e4b4a05a90d9cac9285cfce2bea6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter3/usingScipy.py", "max_forks_repo_name": "onggieoi/python-math", "max_forks_repo_head_hexsha": "7cc6193516c4e4b4a05a90d9cac9285cfce2bea6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6, "max_line_length": 71, "alphanum_fraction": 0.6241331484, "include": true, "reason": "import numpy,from scipy", "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357567351325, "lm_q2_score": 0.914900950352329, "lm_q1q2_score": 0.8957207442658843}}
{"text": "\"\"\"\nThis is a couple of helper functions to sample a bezier arc. This code is inspired by the following answer\nin Stack Overflow and slightly modified to output points in the (x,y) format and use broadcasting to compute the\npoints in one operation:\nhttps://stackoverflow.com/questions/12643079/b%C3%A9zier-curve-fitting-with-scipy\n\"\"\"\n\nimport numpy as np\nfrom scipy.special import comb\n\n\ndef bernstein_poly(i, n, t):\n    \"\"\"\n     The Bernstein polynomial of n, i as a function of t\n    \"\"\"\n\n    return comb(n, i) * (t**(n-i)) * (1 - t)**i\n\n\ndef bezier_curve(points, n_samples=5):\n    \"\"\"\n    Given a set of control points defining a bezier curve, returns n_samples points equally spaced in the curve space.\n    More details on bezier curves: See http://processingjs.nihongoresources.com/bezierinfo/\n    :param points: Bezier curve control points. NxM numpy array.\n    :param n_samples: Number of equidistant points to sample from the curve.\n    :return: Sampled points. n_samples by M numpy array.\n    \"\"\"\n    n_points = len(points)\n\n    t = np.linspace(1.0, 0.0, n_samples)\n\n    polynomial_array = np.array([bernstein_poly(i, n_points-1, t) for i in range(0, n_points)])\n\n    return np.dot(np.transpose(polynomial_array), points)\n", "meta": {"hexsha": "471c81f71af6eac388e96655ec0a8780d884ed35", "size": 1231, "ext": "py", "lang": "Python", "max_stars_repo_path": "bezier_sampling.py", "max_stars_repo_name": "jfelip/font_tracer", "max_stars_repo_head_hexsha": "dff7a79e20ce533557bc36ae68899c088723d15c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bezier_sampling.py", "max_issues_repo_name": "jfelip/font_tracer", "max_issues_repo_head_hexsha": "dff7a79e20ce533557bc36ae68899c088723d15c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bezier_sampling.py", "max_forks_repo_name": "jfelip/font_tracer", "max_forks_repo_head_hexsha": "dff7a79e20ce533557bc36ae68899c088723d15c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1714285714, "max_line_length": 118, "alphanum_fraction": 0.7173030057, "include": true, "reason": "import numpy,from scipy", "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018390836984, "lm_q2_score": 0.918480249045993, "lm_q1q2_score": 0.8957036280317057}}
{"text": "#!/usr/bin/env python\n\n#\tSigular Value Decomposition (SVD)\n#\t\tTrucco, Appendix A.6\n#\n#\tdefinition\n#\n#\t\t\tA = U dot D dot transpose(V)\n#\n#\t\tA any real m x n matrix\n#\t\tU is m x n matrix that columns are eigenvectors of A*transpose(A)\n#\t\t\tA * transpose(A) = U dot D dot transpose(V) dot V dot D dot transpose(U) = U dot D^2 dot transpose(U)\n#\t\tV is n x n matrix that columns are eivenvectors of transpose(A)*A \n#\t\t\ttranspose(A)*A = V * D * transpose(U) * U * D * transpose(V) = V * D^2 * transpose(V)\n#\t\tD is n x n diagonal matrix (non-negative real values called sigular values)\n# \n#\tcomputing the inverse of a matrix using SVD\n#\t\t\n#\t\tinverse(A) = V dot inverse(D) dot transpose(U)\n#\t\t\twhere inverse(D) are 1/singular values\n#\n\n#\n#\t\t|-     -|\n#\t\t| 1 2 1 |\n#\tA = | 2 3 2 | \n#\t\t| 1 2 1 |\n#\t\t|_\t   _|\n#\n#\t\t\t\t\t\t\t\t\t\t\t   |-\t     -|\n#\t\t\t\t\t\t\t\t\t\t\t   | 6  10 6  |\n#\tA * transpose( A ) = transpose( A ) * A =  | 10 17 10 |\n#\t\t\t\t\t\t\t\t\t\t\t   | 6  10 6  |\n#\t\t\t\t\t\t\t\t\t\t\t   |_\t     _|\n\nimport numpy as np\nnp.set_printoptions(formatter={'float': '{: 0.3f}'.format})\n\n#\tconstruct the input array\na = np.array( [ [ 1, 2, 12 ],\n\t\t\t\t[ 2, 3, 2 ],\n\t\t\t\t[ 1, 2, 1 ],\n\t\t\t] )\nprint( 'a = {}'.format( a ) )\n\nprint( ' ===############################################################=== ' )\n\t\t\t\n# using numpy to find SVD\nprint( 'calculating the SVD using numpy......................' )\nu, s, vt = np.linalg.svd( a )\n\n#\tconstruct a matrix d\nd = np.diag( s )\n\nprint( '    u = {}'.format( u ) )\nprint( '    s = {}'.format( s ) )\nprint( '    vt = {}'.format( vt ) )\nprint( '    d = {}'.format( d ) )\n\n#\ttesting the SVD\nprint( 'testing reconstruct A matrix using SVD' )\nreconstructedA = np.dot( u, np.dot( d, vt ) )\nassert( np.allclose( a, reconstructedA ) )\nprint( ' === done === ' )\n\nprint( ' ===############################################################=== ' )\n\nprint( 'testing construct inverse matrix of A using SVD' )\n\nv = vt.transpose()\ninverseD = np.diag( s**-1 )\nut = u.transpose()\n\nprint( '    v = {}'.format( v ) )\nprint( '    inverseD = {}'.format( d ) )\nprint( '    ut = {}'.format( ut ) )\n\ninverseA = np.dot( v, np.dot( inverseD, ut ) )\nprint( '    inverseA = {}'.format( inverseA ) )\n\naMultiplyInverseA = np.matmul( a, inverseA )\nprint( '    aMultiplyInverseA = {}'.format( aMultiplyInverseA ) )\n\n#\tcheck\nassert( np.allclose( aMultiplyInverseA, np.identity( 3 ) ) )\nprint( ' === done === ' )\n\n", "meta": {"hexsha": "48e536b6330f6f80264a80ae5d1a0afd4e7febc6", "size": 2368, "ext": "py", "lang": "Python", "max_stars_repo_path": "understanding_svd_and_pseudoinverse/understanding_svd.py", "max_stars_repo_name": "wiphoo/experimental-numpy", "max_stars_repo_head_hexsha": "ba13444c44cb514c2df61953c1f024766ab512eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "understanding_svd_and_pseudoinverse/understanding_svd.py", "max_issues_repo_name": "wiphoo/experimental-numpy", "max_issues_repo_head_hexsha": "ba13444c44cb514c2df61953c1f024766ab512eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "understanding_svd_and_pseudoinverse/understanding_svd.py", "max_forks_repo_name": "wiphoo/experimental-numpy", "max_forks_repo_head_hexsha": "ba13444c44cb514c2df61953c1f024766ab512eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9090909091, "max_line_length": 105, "alphanum_fraction": 0.5253378378, "include": true, "reason": "import numpy", "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360932, "lm_q2_score": 0.9362850039701653, "lm_q1q2_score": 0.8956822569023315}}
{"text": "import numpy as np\nfrom math import *\n\n# Function\ndef f(x):\n    y = 1 / sqrt(2 * np.pi) * exp(-x ** 2 / 2)\n    return y\n\n# General Gauss Method with Five Points\ndef GaussQuad5(a, b, tol):\n\n    # Compute Integral with 5 Point Gauss Method\n    def GaussQuad(a, b):\n        t = [-1/3*sqrt(5+2*sqrt(10/7)), -1/3*sqrt(5-2*sqrt(10/7)), 0,\n             1/3*sqrt(5-2*sqrt(10/7)), 1/3*sqrt(5+2*sqrt(10/7))]\n\n        x = np.zeros(5)\n\n        for i in range(5):\n            x[i] = 0.5*((b-a)*t[i] + b+a)\n\n        w = [(322 + 13*sqrt(70))/900, (322 - 13*sqrt(70))/900, 128/225,\n             (322 + 13*sqrt(70))/900, (322 - 13*sqrt(70))/900]\n\n        I = 0.0\n\n        for i in range(5):\n            I += 0.5*(b-a)*w[i]*f(x[i])\n\n        return I\n\n    # We compute the Integral in N intervals using Gauss Method so as to Compute Integral Error\n    def GaussQuadn(n):\n        h = (b - a) / n\n        I = 0.0\n\n        for i in range(n):\n            x0 = a + i * h\n            x1 = x0 + h\n            I += GaussQuad(x0, x1)\n\n        return I\n\n    # We compute the error using analytic computations\n    def dGaussQuadn(n):\n        h = (b - a) / (2 * n)\n        I2 = 0.0\n\n        for i in range(2 * n):\n            x0 = a + i * h\n            x1 = x0 + h\n            I2 += GaussQuad(x0, x1)\n\n        dI = 32 / 31 * abs(I2 - GaussQuadn(n))\n\n        return dI\n\n    # Min Value for Gauss Method\n    n = 2 \n    # General Error\n    η = dGaussQuadn(n) / GaussQuadn(n)\n\n    while η > tol:\n        n += 1\n        η = dGaussQuadn(n) / GaussQuadn(n)\n\n    return GaussQuadn(n), dGaussQuadn(n), η\n\nif __name__ == \"__main__\":\n    print('\\nCimputated with 5 Point Gauss Method:')\n    print(f\"\\tI ± δI = {GaussQuad5(-5, 5, 0.001)[0]:.8f} ± {GaussQuad5(-5, 5, 0.001)[1]:.8f}\")\n    print(f'\\tΗ σχετική ακρίβεια είναι η = {GaussQuad5(-5, 5, 0.001)[2]:.8f} < 0.1 %')", "meta": {"hexsha": "e028ba7af443cbd10f899953a0d2ea3121e6a97a", "size": 1826, "ext": "py", "lang": "Python", "max_stars_repo_path": "Integration/Gauss-Quadrature-Five-Points.py", "max_stars_repo_name": "AlexTsagas/Computational-Physics", "max_stars_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Integration/Gauss-Quadrature-Five-Points.py", "max_issues_repo_name": "AlexTsagas/Computational-Physics", "max_issues_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Integration/Gauss-Quadrature-Five-Points.py", "max_forks_repo_name": "AlexTsagas/Computational-Physics", "max_forks_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3611111111, "max_line_length": 95, "alphanum_fraction": 0.4950711939, "include": true, "reason": "import numpy", "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140235181257, "lm_q2_score": 0.9263037297853367, "lm_q1q2_score": 0.8956560663665867}}
{"text": "import numpy as np\nfrom scipy import linalg as la\nfrom math import copysign\n\ndef hqr(A):\n    \"\"\"Finds the QR decomposition of A using Householder reflectors.\n    input: \tA, mxn array with m>=n\n    output: Q, orthogonal mxm array\n            R, upper triangular mxn array\n            s.t QR = A\n    \"\"\"\n    # This is just a pure Python implementation.\n    # It's not fully optimized, but it should\n    # have the right asymptotic speed.\n    # initialize Q and R\n    # start Q as an identity\n    # start R as a C-contiguous copy of A\n    # take a transpose of Q to start out\n    # so it is C-contiguous when we return the answer\n    Q = np.eye(A.shape[0]).T\n    R = np.array(A, order=\"C\")\n    # initialize m and n for convenience\n    m, n = R.shape\n    # avoid reallocating v in the for loop\n    v = np.empty(A.shape[1])\n    for k in xrange(n-1):\n        # get a slice of the temporary array\n        vk = v[k:]\n        # fill it with corresponding values from R\n        vk[:] = R[k:,k]\n        # add in the term that makes the reflection work\n        vk[0] += copysign(la.norm(vk), vk[0])\n        # normalize it so it's an orthogonal transform\n        vk /= la.norm(vk)\n        # apply projection to R\n        R[k:,k:] -= 2 * np.outer(vk, vk.dot(R[k:,k:]))\n        # Apply it to Q\n        Q[k:] -= 2 * np.outer(vk, vk.dot(Q[k:]))\n    # note that its returning Q.T, not Q itself\n    return Q.T, R\n\ndef hess(A):\n    \"\"\"Computes the upper Hessenberg form of A using Householder reflectors.\n    input:  A, mxn array\n    output: Q, orthogonal mxm array\n            H, upper Hessenberg\n            s.t. Q.dot(H).dot(Q.T) = A\n    \"\"\"\n    # similar approach as the householder function.\n    # again, not perfectly optimized, but good enough.\n    Q = np.eye(A.shape[0]).T\n    H = np.array(A, order=\"C\")\n    # initialize m and n for convenience\n    m, n = H.shape\n    # avoid reallocating v in the for loop\n    v = np.empty(A.shape[1]-1)\n    for k in xrange(n-2):\n        # get a slice of the temporary array\n        vk = v[k:]\n        # fill it with corresponding values from R\n        vk[:] = H[k+1:,k]\n        # add in the term that makes the reflection work\n        vk[0] += copysign(la.norm(vk), vk[0])\n        # normalize it so it's an orthogonal transform\n        vk /= la.norm(vk)\n        # apply projection to H on the left\n        H[k+1:,k:] -= 2 * np.outer(vk, vk.dot(H[k+1:,k:]))\n        # apply projection to H on the right\n        H[:,k+1:] -= 2 * np.outer(H[:,k+1:].dot(vk), vk)\n        # Apply it to Q\n        Q[k+1:] -= 2 * np.outer(vk, vk.dot(Q[k+1:]))\n    return Q, H\n", "meta": {"hexsha": "e7c62043ed931dda97981e2e455cafaf1debcb72", "size": 2575, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/QR/ct.py", "max_stars_repo_name": "jessicaleete/numerical_computing", "max_stars_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-10-18T19:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:12:38.000Z", "max_issues_repo_path": "Labs/QR/ct.py", "max_issues_repo_name": "jessicaleete/numerical_computing", "max_issues_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/QR/ct.py", "max_forks_repo_name": "jessicaleete/numerical_computing", "max_forks_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-14T16:07:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-20T09:05:06.000Z", "avg_line_length": 35.2739726027, "max_line_length": 76, "alphanum_fraction": 0.5751456311, "include": true, "reason": "import numpy,from scipy", "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140225647108, "lm_q2_score": 0.9263037262250327, "lm_q1q2_score": 0.895656062040927}}
{"text": "###_____________________ Ordinary Differential Eqs _________________________### \nimport numpy as np\nimport matplotlib.pyplot as plt\n# Para integrar EDOs vamos a usar la función `odeint` del paquete `integrate`, \n# que permite integrar sistemas del tipo:\n    # $$ \\frac{d\\mathbf{y}}{dt}=\\mathbf{f}\\left(\\mathbf{y},t\\right)$$\n# con condiciones iniciales $\\mathbf{y}(\\mathbf{0}) = \\mathbf{y_0}$.\nfrom scipy.integrate import solve_ivp\n# **¡Importante!**: La función del sistema recibe como primer argumento 𝐲\n# (un array) y como segundo argumento el instante t (un escalar). Esta convención \n# va exactamente al revés que en MATLAB y si se hace al revés obtendremos errores \n# o, lo que es peor, resultados incorrectos.\n\n##_________________________ 1st order ODE ___________________________##\n# Vamos a integrar primero una EDO elemental, cuya solución ya conocemos:\n    # $$y' + y = 0$$\n# $$f(y, t) = \\frac{dy}{dt} = -y$$\ndef f(t,y):\n    return np.array([-y])\n# Initial conditions\ny0 = np.array([1])\ntini = 0\ntfin = 3\n# Integrating and representing the solution\nsol = solve_ivp(f, (tini, tfin), y0)\nplt.plot(sol.t, sol.y[0,:], 'o-') \nplt.show()\n\n# Pero, ¿cómo se han seleccionado los puntos en los que se calcula la solución? \n# El solver los ha calculado por nosotros. Si queremos tener control sobre estos \n# puntos, podemos pasar de manera explícita el vector de tiempos:\ntime = np.linspace(tini, tfin, 30)\nsol_2 = solve_ivp(f, (tini, tfin), y0, t_eval=time)\nplt.plot(sol_2.t, sol_2.y[0, :], 'd-')\nplt.show()\n\n# El solver siempre da los pasos que considere necesarios para calcular la solución,\n# pero sólo guarda los que nosotros le indicamos.\nprint(f\"function evaluations in sol 1: {sol.nfev}\")\nprint(f\"function evaluations in sol 2: {sol_2.nfev}\")\n# De hecho podemos usar la salida densa para obtener la solución en un punto cualquiera:\nsol_3 = solve_ivp(f, (tini, tfin), y0, dense_output=True)\nprint(sol_3.sol([1.14567, 2, 6]))\nt = np.linspace(tini, tfin, 45)\ny = sol_3.sol(t)\nplt.plot(t, y[0, :], 'x-')\nplt.show()\n\n##_________________________ Higher order ODE ___________________________##\n# Tendremos que acordarnos ahora de cómo reducir las ecuaciones de orden. De nuevo, \n# vamos a probar con un ejemplo académico:\n    # $$y + y'' = 0$$\n    # $$\\mathbf{y} \\leftarrow \\pmatrix{y \\\\ y'}$$\n    # $$\\mathbf{f}(\\mathbf{y}) = \\frac{d\\mathbf{y}}{dt} =  \\pmatrix{y \\\\ y'}' = \n        # \\pmatrix{y' \\\\ y''} = \\pmatrix{y' \\\\ -y}$$\ndef f2(t,y):\n    return np.array([y[1], -y[0]])\n# init conditions and domain\nt0=0\nt1=10\nt = np.linspace(t0,t1)\ny0 = np.array([1.0,0.0])\n# solver\nsol = solve_ivp(f2, (t0, t1), y0, t_eval=t)\nwith plt.style.context('seaborn-notebook'):\n    plt.plot(t, sol.y[0, :], label='$y$')\n    plt.plot(t, sol.y[1, :], '--k', label='$\\dot{y}$')\n    plt.legend()\n    plt.grid()\n    plt.show()\n", "meta": {"hexsha": "fa9eb5c883a2a0a4efd60e5c416212361d8af1f2", "size": 2806, "ext": "py", "lang": "Python", "max_stars_repo_path": "MyScripts/035-SciPy.py", "max_stars_repo_name": "diegoomataix/Curso_AeroPython", "max_stars_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MyScripts/035-SciPy.py", "max_issues_repo_name": "diegoomataix/Curso_AeroPython", "max_issues_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MyScripts/035-SciPy.py", "max_forks_repo_name": "diegoomataix/Curso_AeroPython", "max_forks_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5211267606, "max_line_length": 88, "alphanum_fraction": 0.680684248, "include": true, "reason": "import numpy,from scipy", "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914018751051, "lm_q2_score": 0.926303728768107, "lm_q1q2_score": 0.8956560609672538}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\n# not my fault that it's not PEP8 compliant ...\ndef predict(X,theta):\n  # X - set of data points\n  # theta - parameter vector θ# takes m by n matrix X as input and returns an mx1 vector containing the predictions h_theta(x^i) for each row x^i, i=1,...,m in X\n  \n  # matrix multiplication\n  pred = np.dot(X,theta)\n  return pred\n\ndef computeCost(X, y, theta):\n  # X - set of data points\n  # y - target variable\n  # theta - parameter vector θ\n  # function calculates the cost J(theta) and return its value\n  ##### squared error cost function\n  \n  pred = predict(X, theta) - y\n  m = len(X)\n  cost = 1/(2*m) * np.sum(np.square(pred)) \n  return cost\n\ndef computeGradient(X,y,theta):\n  # X - set of data points\n  # y - target variabler\n  # theta - parameter vector θ\n  # function calulate the gradient of J(theta) and returns its value\n  pred = predict(X,theta) - y\n  \n  # transpose then dot product of two arrays \n  grad = X.T.dot(pred)\n  return grad/len(X)\n\ndef gradientDescent(X, y, numparams):\n  # iteratively update parameter vector theta\n  # -- you should not modify this function\n  \n  # initialize variables for learning rate and iterations\n  alpha = 0.02\n  iters = 5000\n  cost = np.zeros(iters)\n  theta= np.zeros(numparams)\n\n  for i in range(iters):\n    theta = theta - alpha * computeGradient(X,y,theta)\n    cost[i] = computeCost(X, y, theta)\n\n  return theta, cost\n\ndef normaliseData(x):\n  # rescale data to lie between 0 and 1\n  scale = x.max(axis=0)\n  return (x/scale, scale)\n\ndef splitData(X,y):\n  # split data into training and test parts\n  # ... for now, we use all of the data for training and testing\n  Xtrain=X; ytrain=y; Xtest=X; ytest=y\n  return (Xtrain,ytrain,Xtest,ytest)\n\ndef main():\n  # load the data\n  data=np.loadtxt('stockprices.csv',usecols=(1,2))\n  X=data[:,0]\n  y=data[:,1]\n  \n  # plot the data so we can see how it looks \n  # (output is in file graph.png)\n  fig, ax = plt.subplots(figsize=(12, 8))\n  ax.scatter(X, y, label='Data')\n  ax.set_xlabel('Amazon')\n  ax.set_ylabel('Google')\n  ax.set_title('Google stock price vs Amazon')\n  fig.savefig('graph.png')\n\n  # split the data into training and test parts\n  (Xtrain,ytrain,Xtest,ytest)=splitData(X,y)\n  \n  # add a column of ones to input data\n  m=len(y) # m is number of training data points\n  Xtrain = np.column_stack((np.ones((m, 1)), Xtrain))\n  (m,n)=Xtrain.shape # m is number of data points, n number of features\n\n  # rescale training data to lie between 0 and 1\n  (Xt,Xscale) = normaliseData(Xtrain)\n  (yt,yscale) = normaliseData(ytrain)\n\n  # calculate the prediction\n  print('testing the prediction function ...')\n  theta=(1,2)\n  print('when x=[1,1] and theta is [1,2]) cost = ',predict(np.ones(n),theta))\n  print('approx expected prediction is 3')\n  print('when x=[[1,1],[5,5]] and theta is [1,2]) cost = ',predict(np.array([[1,1],[5,5]]),theta))  \n  print('approx expected prediction is [3,15]')\n  input('Press Enter to continue...')\n\n  # calculate the cost when theta iz zero\n  print('testing the cost function ...')\n  theta=np.zeros(n)\n  print('when theta is zero cost = ',computeCost(Xt,yt,theta))\n  print('approx expected cost value is 0.318')\n  input('Press Enter to continue...')\n  \n  # calculate the gradient when theta is zero\n  print('testing the gradient function ...')\n  print('when theta is zero gradient = ',computeGradient(Xt,yt,theta))\n  print('approx expected gradient value is [-0.79,-0.59]')\n  input('Press Enter to continue...')\n  \n  # perform gradient descent to \"fit\" the model parameters\n  print('running gradient descent ...')\n  theta, cost = gradientDescent(Xt, yt, n)\n  print('after running gradientDescent() theta=',theta)\n  print('approx expected value is [0.34, 0.61]')\n\n  # plot some predictions\n  Xpred = np.linspace(X.min(), X.max(), 100)\n  Xpred = np.column_stack((np.ones((100, 1)), Xpred))\n  ypred = predict(Xpred/Xscale, theta)*yscale\n  fig, ax = plt.subplots(figsize=(12, 8))\n  ax.scatter(Xtest, ytest, color='b', label='Test Data')\n  ax.plot(Xpred[:,1], ypred, 'r', label='Prediction')\n  ax.set_xlabel('Amazon')\n  ax.set_ylabel('Google')\n  ax.legend(loc=2)\n  fig.savefig('pred.png')\n  \n  # and plot how the cost varies as the gradient descent proceeds\n  fig2, ax2 = plt.subplots(figsize=(12, 8))\n  ax2.semilogy(cost,'r')\n  ax2.set_xlabel('iteration')\n  ax2.set_ylabel('cost')\n  fig2.savefig('cost.png')\n  \n  # plot the cost function\n  fig3 = plt.figure()\n  ax3 = fig3.add_subplot(1, 1, 1, projection='3d')\n  n=100\n  theta0, theta1 = np.meshgrid(np.linspace(-3, 3, n), np.linspace(-3, 2, n))  \n  cost = np.empty((n,n))\n  for i in range(n):\n    for j in range(n):\n      cost[i,j] = computeCost(Xt,yt,(theta0[i,j],theta1[i,j]))\n  ax3.plot_surface(theta0,theta1,cost)\n  ax3.set_xlabel('theta0')\n  ax3.set_ylabel('theta1')\n  ax3.set_zlabel('J(theta)')\n  fig3.savefig('J.png')\n  \nif __name__ == '__main__':\n  main()\n", "meta": {"hexsha": "b9f0ca241df9b35b6ead3ea2294bbe9942e3a1ca", "size": 4922, "ext": "py", "lang": "Python", "max_stars_repo_path": "Year4/CSU44061/Assignments/1.Linear_regression/main.py", "max_stars_repo_name": "slow-J/TCD", "max_stars_repo_head_hexsha": "91b5572cc148b284a210f2b89ee3f43295686d48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-04T11:25:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T11:25:32.000Z", "max_issues_repo_path": "Year4/CSU44061/Assignments/1.Linear_regression/main.py", "max_issues_repo_name": "sickfila/TCD", "max_issues_repo_head_hexsha": "91b5572cc148b284a210f2b89ee3f43295686d48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-19T20:11:15.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-19T20:11:15.000Z", "max_forks_repo_path": "Year4/CSU44061/Assignments/1.Linear_regression/main.py", "max_forks_repo_name": "slow-J/TCD", "max_forks_repo_head_hexsha": "91b5572cc148b284a210f2b89ee3f43295686d48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5512820513, "max_line_length": 161, "alphanum_fraction": 0.6726940268, "include": true, "reason": "import numpy", "num_tokens": 1458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399086356109, "lm_q2_score": 0.9230391722430736, "lm_q1q2_score": 0.8955694421442097}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Linear algebra in Python with NumPy\n# \n\n# In this lab, you will have the opportunity to remember some basic concepts about linear algebra and how to use them in Python.\n# \n# Numpy is one of the most used libraries in Python for arrays manipulation. It adds to Python a set of functions that allows us to operate on large multidimensional arrays with just a few lines. So forget about writing nested loops for adding matrices! With NumPy, this is as simple as adding numbers.\n# \n# Let us import the `numpy` library and assign the alias `np` for it. We will follow this convention in almost every notebook in this course, and you'll see this in many resources outside this course as well.\n\n# In[1]:\n\n\nimport numpy as np  # The swiss knife of the data scientist.\n\n\n# ## Defining lists and numpy arrays\n\n# In[2]:\n\n\nalist = [1, 2, 3, 4, 5]   # Define a python list. It looks like an np array\nnarray = np.array([1, 2, 3, 4]) # Define a numpy array\n\n\n# Note the difference between a Python list and a NumPy array.\n\n# In[3]:\n\n\nprint(alist)\nprint(narray)\n\nprint(type(alist))\nprint(type(narray))\n\n\n# ## Algebraic operators on NumPy arrays vs. Python lists\n# \n# One of the common beginner mistakes is to mix up the concepts of NumPy arrays and Python lists. Just observe the next example, where we add two objects of the two mentioned types. Note that the '+' operator on NumPy arrays perform an element-wise addition, while the same operation on Python lists results in a list concatenation. Be careful while coding. Knowing this can save many headaches.\n\n# In[4]:\n\n\nprint(narray + narray)\nprint(alist + alist)\n\n\n# It is the same as with the product operator, `*`. In the first case, we scale the vector, while in the second case, we concatenate three times the same list.\n\n# In[5]:\n\n\nprint(narray * 3)\nprint(alist * 3)\n\n\n# Be aware of the difference because, within the same function,  both types of arrays can appear. \n# Numpy arrays are designed for numerical and matrix operations, while lists are for more general purposes.\n\n# ## Matrix or Array of Arrays\n# \n# In linear algebra, a matrix is a structure composed of n rows by m columns. That means each row must have the same number of columns. With NumPy, we have two ways to create a matrix:\n# * Creating an array of arrays using `np.array` (recommended). \n# * Creating a matrix using `np.matrix` (still available but might be removed soon).\n# \n# NumPy arrays or lists can be used to initialize a matrix, but the resulting matrix will be composed of NumPy arrays only.\n\n# In[6]:\n\n\nnpmatrix1 = np.array([narray, narray, narray]) # Matrix initialized with NumPy arrays\nnpmatrix2 = np.array([alist, alist, alist]) # Matrix initialized with lists\nnpmatrix3 = np.array([narray, [1, 1, 1, 1], narray]) # Matrix initialized with both types\n\nprint(npmatrix1)\nprint(npmatrix2)\nprint(npmatrix3)\n\n\n# However, when defining a matrix, be sure that all the rows contain the same number of elements. Otherwise, the linear algebra operations could lead to unexpected results.\n# \n# Analyze the following two examples:\n\n# In[7]:\n\n\n# Example 1:\n\nokmatrix = np.array([[1, 2], [3, 4]]) # Define a 2x2 matrix\nprint(okmatrix) # Print okmatrix\nprint(okmatrix * 2) # Print a scaled version of okmatrix\n\n\n# In[8]:\n\n\n# Example 2:\n\nbadmatrix = np.array([[1, 2], [3, 4], [5, 6, 7]]) # Define a matrix. Note the third row contains 3 elements\nprint(badmatrix) # Print the malformed matrix\nprint(badmatrix * 2) # It is supposed to scale the whole matrix\n\n\n# ## Scaling and translating matrices\n# \n# Now that you know how to build correct NumPy arrays and matrices, let us see how easy it is to operate with them in Python using the regular algebraic operators like + and -. \n# \n# Operations can be performed between arrays and arrays or between arrays and scalars.\n\n# In[9]:\n\n\n# Scale by 2 and translate 1 unit the matrix\nresult = okmatrix * 2 + 1 # For each element in the matrix, multiply by 2 and add 1\nprint(result)\n\n\n# In[10]:\n\n\n# Add two compatible matrices\nresult1 = okmatrix + okmatrix\nprint(result1)\n\n# Subtract two compatible matrices. This is called the difference vector\nresult2 = okmatrix - okmatrix\nprint(result2)\n\n\n# The product operator `*` when used on arrays or matrices indicates element-wise multiplications.\n# Do not confuse it with the dot product.\n\n# In[11]:\n\n\nresult = okmatrix * okmatrix # Multiply each element by itself\nprint(result)\n\n\n# ## Transpose a matrix\n# \n# In linear algebra, the transpose of a matrix is an operator that flips a matrix over its diagonal, i.e., the transpose operator switches the row and column indices of the matrix producing another matrix. If the original matrix dimension is n by m, the resulting transposed matrix will be m by n.\n# \n# **T** denotes the transpose operations with NumPy matrices.\n\n# In[12]:\n\n\nmatrix3x2 = np.array([[1, 2], [3, 4], [5, 6]]) # Define a 3x2 matrix\nprint('Original matrix 3 x 2')\nprint(matrix3x2)\nprint('Transposed matrix 2 x 3')\nprint(matrix3x2.T)\n\n\n# However, note that the transpose operation does not affect 1D arrays.\n\n# In[13]:\n\n\nnparray = np.array([1, 2, 3, 4]) # Define an array\nprint('Original array')\nprint(nparray)\nprint('Transposed array')\nprint(nparray.T)\n\n\n# perhaps in this case you wanted to do:\n\n# In[14]:\n\n\nnparray = np.array([[1, 2, 3, 4]]) # Define a 1 x 4 matrix. Note the 2 level of square brackets\nprint('Original array')\nprint(nparray)\nprint('Transposed array')\nprint(nparray.T)\n\n\n# ## Get the norm of a nparray or matrix\n# \n# In linear algebra, the norm of an n-dimensional vector $\\vec a$   is defined as:\n# \n# $$ norm(\\vec a) = ||\\vec a|| = \\sqrt {\\sum_{i=1}^{n} a_i ^ 2}$$\n# \n# Calculating the norm of vector or even of a matrix is a general operation when dealing with data. Numpy has a set of functions for linear algebra in the subpackage **linalg**, including the **norm** function. Let us see how to get the norm a given array or matrix:\n\n# In[15]:\n\n\nnparray1 = np.array([1, 2, 3, 4]) # Define an array\nnorm1 = np.linalg.norm(nparray1)\n\nnparray2 = np.array([[1, 2], [3, 4]]) # Define a 2 x 2 matrix. Note the 2 level of square brackets\nnorm2 = np.linalg.norm(nparray2) \n\nprint(norm1)\nprint(norm2)\n\n\n# Note that without any other parameter, the norm function treats the matrix as being just an array of numbers.\n# However, it is possible to get the norm by rows or by columns. The **axis** parameter controls the form of the operation: \n# * **axis=0** means get the norm of each column\n# * **axis=1** means get the norm of each row. \n\n# In[16]:\n\n\nnparray2 = np.array([[1, 1], [2, 2], [3, 3]]) # Define a 3 x 2 matrix. \n\nnormByCols = np.linalg.norm(nparray2, axis=0) # Get the norm for each column. Returns 2 elements\nnormByRows = np.linalg.norm(nparray2, axis=1) # get the norm for each row. Returns 3 elements\n\nprint(normByCols)\nprint(normByRows)\n\n\n# However, there are more ways to get the norm of a matrix in Python.\n# For that, let us see all the different ways of defining the dot product between 2 arrays.\n\n# ## The dot product between arrays: All the flavors\n# \n# The dot product or scalar product or inner product between two vectors $\\vec a$ and $\\vec b$ of the same size is defined as:\n# $$\\vec a \\cdot \\vec b = \\sum_{i=1}^{n} a_i b_i$$\n# \n# The dot product takes two vectors and returns a single number.\n\n# In[17]:\n\n\nnparray1 = np.array([0, 1, 2, 3]) # Define an array\nnparray2 = np.array([4, 5, 6, 7]) # Define an array\n\nflavor1 = np.dot(nparray1, nparray2) # Recommended way\nprint(flavor1)\n\nflavor2 = np.sum(nparray1 * nparray2) # Ok way\nprint(flavor2)\n\nflavor3 = nparray1 @ nparray2         # Geeks way\nprint(flavor3)\n\n# As you never should do:             # Noobs way\nflavor4 = 0\nfor a, b in zip(nparray1, nparray2):\n    flavor4 += a * b\n    \nprint(flavor4)\n\n\n# **We strongly recommend using np.dot, since it is the only method that accepts arrays and lists without problems**\n\n# In[18]:\n\n\nnorm1 = np.dot(np.array([1, 2]), np.array([3, 4])) # Dot product on nparrays\nnorm2 = np.dot([1, 2], [3, 4]) # Dot product on python lists\n\nprint(norm1, '=', norm2 )\n\n\n# Finally, note that the norm is the square root of the dot product of the vector with itself. That gives many options to write that function:\n# \n# $$ norm(\\vec a) = ||\\vec a|| = \\sqrt {\\sum_{i=1}^{n} a_i ^ 2} = \\sqrt {a \\cdot a}$$\n# \n\n# ## Sums by rows or columns\n# \n# Another general operation performed on matrices is the sum by rows or columns.\n# Just as we did for the function norm, the **axis** parameter controls the form of the operation:\n# * **axis=0** means to sum the elements of each column together. \n# * **axis=1** means to sum the elements of each row together.\n\n# In[19]:\n\n\nnparray2 = np.array([[1, -1], [2, -2], [3, -3]]) # Define a 3 x 2 matrix. \n\nsumByCols = np.sum(nparray2, axis=0) # Get the sum for each column. Returns 2 elements\nsumByRows = np.sum(nparray2, axis=1) # get the sum for each row. Returns 3 elements\n\nprint('Sum by columns: ')\nprint(sumByCols)\nprint('Sum by rows:')\nprint(sumByRows)\n\n\n# ## Get the mean by rows or columns\n# \n# As with the sums, one can get the **mean** by rows or columns using the **axis** parameter. Just remember that the mean is the sum of the elements divided by the length of the vector\n# $$ mean(\\vec a) = \\frac {{\\sum_{i=1}^{n} a_i }}{n}$$\n\n# In[20]:\n\n\nnparray2 = np.array([[1, -1], [2, -2], [3, -3]]) # Define a 3 x 2 matrix. Chosen to be a matrix with 0 mean\n\nmean = np.mean(nparray2) # Get the mean for the whole matrix\nmeanByCols = np.mean(nparray2, axis=0) # Get the mean for each column. Returns 2 elements\nmeanByRows = np.mean(nparray2, axis=1) # get the mean for each row. Returns 3 elements\n\nprint('Matrix mean: ')\nprint(mean)\nprint('Mean by columns: ')\nprint(meanByCols)\nprint('Mean by rows:')\nprint(meanByRows)\n\n\n# ## Center the columns of a matrix\n# \n# Centering the attributes of a data matrix is another essential preprocessing step. Centering a matrix means to remove the column mean to each element inside the column. The mean by columns of a centered matrix is always 0.\n# \n# With NumPy, this process is as simple as this:\n\n# In[21]:\n\n\nnparray2 = np.array([[1, 1], [2, 2], [3, 3]]) # Define a 3 x 2 matrix. \n\nnparrayCentered = nparray2 - np.mean(nparray2, axis=0) # Remove the mean for each column\n\nprint('Original matrix')\nprint(nparray2)\nprint('Centered by columns matrix')\nprint(nparrayCentered)\n\nprint('New mean by column')\nprint(nparrayCentered.mean(axis=0))\n\n\n# **Warning:** This process does not apply for row centering. In such cases, consider transposing the matrix, centering by columns, and then transpose back the result. \n# \n# See the example below:\n\n# In[22]:\n\n\nnparray2 = np.array([[1, 3], [2, 4], [3, 5]]) # Define a 3 x 2 matrix. \n\nnparrayCentered = nparray2.T - np.mean(nparray2, axis=1) # Remove the mean for each row\nnparrayCentered = nparrayCentered.T # Transpose back the result\n\nprint('Original matrix')\nprint(nparray2)\nprint('Centered by rows matrix')\nprint(nparrayCentered)\n\nprint('New mean by rows')\nprint(nparrayCentered.mean(axis=1))\n\n\n# Note that some operations can be performed using static functions like `np.sum()` or `np.mean()`, or by using the inner functions of the array\n\n# In[23]:\n\n\nnparray2 = np.array([[1, 3], [2, 4], [3, 5]]) # Define a 3 x 2 matrix. \n\nmean1 = np.mean(nparray2) # Static way\nmean2 = nparray2.mean()   # Dinamic way\n\nprint(mean1, ' == ', mean2)\n\n\n# Even if they are equivalent, we recommend the use of the static way always.\n# \n# **Congratulations! You have successfully reviewed vector and matrix operations with Numpy!**\n", "meta": {"hexsha": "dcece688aaf844036518a2dabb459952c25042df", "size": 11509, "ext": "py", "lang": "Python", "max_stars_repo_path": "Part1_Classification_VectorSpaces/C1_W3_lecture_nb_01_linear_algebra.py", "max_stars_repo_name": "picsag/NLP", "max_stars_repo_head_hexsha": "7fe8ec5cf9636fbbe1d5dd077455f4db62800ec9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Part1_Classification_VectorSpaces/C1_W3_lecture_nb_01_linear_algebra.py", "max_issues_repo_name": "picsag/NLP", "max_issues_repo_head_hexsha": "7fe8ec5cf9636fbbe1d5dd077455f4db62800ec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Part1_Classification_VectorSpaces/C1_W3_lecture_nb_01_linear_algebra.py", "max_forks_repo_name": "picsag/NLP", "max_forks_repo_head_hexsha": "7fe8ec5cf9636fbbe1d5dd077455f4db62800ec9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.938172043, "max_line_length": 395, "alphanum_fraction": 0.7090103397, "include": true, "reason": "import numpy", "num_tokens": 3207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392797, "lm_q2_score": 0.9572778026058627, "lm_q1q2_score": 0.8953864498909085}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Return fitted model parameters to the dataset at datapath for each choice in degrees.\r\n# Input: datapath as a string specifying a .txt file, degrees as a list of positive integers.\r\n# Output: paramFits, a list with the same length as degrees, where paramFits[i] is the list of\r\n# coefficients when fitting a polynomial of d = degrees[i].\r\ndef main(datapath, degrees):\r\n    paramFits = []\r\n    # fill in\r\n    # read the input file, assuming it has two columns, where each row is of the form [x y] as\r\n    # in poly.txt.\r\n    # iterate through each n in degrees, calling the feature_matrix and least_squares functions to solve\r\n    # for the model parameters in each case. Append the result to paramFits each time.\r\n    file = open(datapath, \"r\")\r\n\r\n    x_values = []\r\n    y_values = []\r\n\r\n    y = []\r\n    y1 = []\r\n    y2 = []\r\n    y3 = []\r\n    y4 = []\r\n\r\n    fileData = file.readlines()\r\n    for k in fileData:\r\n        k = k.split(\" \")\r\n        x_values.append(float(k[0]))\r\n        y_values.append(float(k[1]))\r\n    for j in degrees:\r\n        paramFits.append(least_squares(feature_matrix(x_values, j), y_values))\r\n    x_sort = sorted(x_values)\r\n    for w in x_sort:\r\n        y.append(paramFits[0][0] * w + paramFits[0][1])\r\n        y1.append(paramFits[1][0] * (w ** 2) + paramFits[1][1] * w + paramFits[1][2])\r\n        y2.append(paramFits[2][0] * (w ** 3) + paramFits[2][1] * (w ** 2) + paramFits[2][2] * w + paramFits[2][3])\r\n        y3.append(paramFits[3][0] * (w ** 4) + paramFits[3][1] * (w ** 3) + paramFits[3][2] * (w ** 2)\r\n                  + paramFits[3][3] * w + paramFits[3][4])\r\n        y4.append(paramFits[4][0] * (w ** 5) + paramFits[4][1] * (w ** 4) + paramFits[4][2] * (w ** 3)\r\n                  + paramFits[4][3] * (w ** 2) + paramFits[4][4] * w + paramFits[4][5])\r\n    file.close()\r\n\r\n    plt.scatter(x_values, y_values, color='r', marker='*')\r\n    plt.plot(x_sort, y, color='m', linestyle='-')\r\n    plt.plot(x_sort, y1, color='g', linestyle='-')\r\n    plt.plot(x_sort, y2, color='r', linestyle='-')\r\n    plt.plot(x_sort, y3, color='y', linestyle='-')\r\n    plt.plot(x_sort, y4, color='b', linestyle='-')\r\n    plt.legend([\"d = 1\", \"d = 2\", \"d = 3\", \"d = 4\", \"d = 5\", \"Data\"], loc='upper left')\r\n    plt.xlabel(\"x\")\r\n    plt.ylabel(\"y\")\r\n    plt.show()\r\n\r\n    return paramFits\r\n\r\n# Return the feature matrix for fitting a polynomial of degree d based on the explanatory variable\r\n# samples in x.\r\n# Input: x as a list of the independent variable samples, and d as an integer.\r\n# Output: X, a list of features for each sample, where X[i][j] corresponds to the jth coefficient\r\n# for the ith sample. Viewed as a matrix, X should have dimension #samples by d+1.\r\ndef feature_matrix(x, d):\r\n    # fill in\r\n    # There are several ways to write this function. The most efficient would be a nested list comprehension\r\n    # which for each sample in x calculates x^d, x^(d-1), ..., x^0.\r\n    X = []\r\n\r\n    ind = 0\r\n\r\n    for j in x:\r\n        ind_d = d\r\n        X.append([])\r\n        while ind_d >= 0:\r\n            X[ind].append(j**ind_d)\r\n            ind_d -= 1\r\n        ind += 1\r\n        \r\n    return X\r\n\r\n# Return the least squares solution based on the feature matrix X and corresponding target variable samples in y.\r\n# Input: X as a list of features for each sample, and y as a list of target variable samples.\r\n# Output: B, a list of the fitted model parameters based on the least squares solution.\r\ndef least_squares(X, y):\r\n    X = np.array(X)\r\n    y = np.array(y)\r\n\r\n    # fill in0\r\n    # Use the matrix algebra functions in numpy to solve the least squares equations. This can be done in just one line.\r\n    C = (np.linalg.inv(X.T @ X)) @ (X.T @ y)\r\n    B = C\r\n\r\n    return B\r\n\r\nif __name__ == '__main__':\r\n    datapath = 'poly.txt'\r\n    degrees = [1, 2, 3, 4, 5]\r\n    paramFits = main(datapath, degrees)\r\n    print(paramFits)\r\n", "meta": {"hexsha": "0106633a0aa60e7af0b3e1d8d62e39d7d446bc14", "size": 3906, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/homework-7-s21-tema014/polyfit.py", "max_stars_repo_name": "tema014/My-projects", "max_stars_repo_head_hexsha": "456987c53ffc70c91a289d3a3c020a9e9fd8132a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/homework-7-s21-tema014/polyfit.py", "max_issues_repo_name": "tema014/My-projects", "max_issues_repo_head_hexsha": "456987c53ffc70c91a289d3a3c020a9e9fd8132a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/homework-7-s21-tema014/polyfit.py", "max_forks_repo_name": "tema014/My-projects", "max_forks_repo_head_hexsha": "456987c53ffc70c91a289d3a3c020a9e9fd8132a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4545454545, "max_line_length": 121, "alphanum_fraction": 0.5967741935, "include": true, "reason": "import numpy", "num_tokens": 1150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561676667173, "lm_q2_score": 0.9241418158002492, "lm_q1q2_score": 0.8953604980367909}}
{"text": "# This problem was asked by Uber.\n# Given an array of integers, return a new array such that each element at index i of the new array\n# is the product of all the numbers in the original array except the one at i.\n# For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24].\n# If our input was [3, 2, 1], the expected output would be [2, 3, 6]\n# Follow-up: what if you can't use division?\n\nimport numpy\n\n\ndef my_product_of_all_numbers(data):\n    \"\"\"My solution. (It uses division)\"\"\"\n    prod = numpy.prod(data)\n    result = [0] * len(data)\n    for i, value in enumerate(data):\n        result[i] = prod / value\n\n    return result\n\n\nexpected = [120, 60, 40, 30, 24]\nassert my_product_of_all_numbers(data=[1, 2, 3, 4, 5]) == expected\n\nexpected = [2, 3, 6]\nassert my_product_of_all_numbers(data=[3, 2, 1]) == expected\n\n\ndef gfg_product_of_all_numbers(data):\n    \"\"\"Solution found on the Geeks for Geeks site. (It does not use division)\"\"\"\n    \"\"\" https://www.geeksforgeeks.org/a-product-array-puzzle/ \"\"\"\n\n    n = len(data)\n\n    # Allocate memory for temporary arrays left[] and right[]\n    left = [0]*n\n    right = [0]*n\n\n    # Allocate memory for the product array\n    prod = [0]*n\n\n    # Left most element of left array is always 1\n    left[0] = 1\n\n    # Rightmost most element of right array is always 1\n    right[n - 1] = 1\n\n    # Construct the left array\n    for i in range(1, n):\n        left[i] = data[i - 1] * left[i - 1]\n\n    # Construct the right array\n    for j in range(n-2, -1, -1):\n        right[j] = data[j + 1] * right[j + 1]\n\n    # Construct the product array using\n    # left[] and right[]\n    for i in range(n):\n        prod[i] = left[i] * right[i]\n\n    return prod\n\nif __name__ == \"__main__\":\n    expected = [120, 60, 40, 30, 24]\n    assert gfg_product_of_all_numbers(data=[1, 2, 3, 4, 5]) == expected\n\n    expected = [2, 3, 6]\n    assert gfg_product_of_all_numbers(data=[3, 2, 1]) == expected\n", "meta": {"hexsha": "48a8289195d54c636ae99aa1029c385690008f46", "size": 1951, "ext": "py", "lang": "Python", "max_stars_repo_path": "problem2.py", "max_stars_repo_name": "mmiraglio/DailyCodingProblem", "max_stars_repo_head_hexsha": "78c0f6096e97a8fbf701952935c8f7393aa5b6b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problem2.py", "max_issues_repo_name": "mmiraglio/DailyCodingProblem", "max_issues_repo_head_hexsha": "78c0f6096e97a8fbf701952935c8f7393aa5b6b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem2.py", "max_forks_repo_name": "mmiraglio/DailyCodingProblem", "max_forks_repo_head_hexsha": "78c0f6096e97a8fbf701952935c8f7393aa5b6b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6911764706, "max_line_length": 100, "alphanum_fraction": 0.6294208098, "include": true, "reason": "import numpy", "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.9525741296834681, "lm_q1q2_score": 0.8953371459982666}}
{"text": "import numpy as np\nnp.set_printoptions(suppress=True)\nimport matplotlib.pyplot as plt\n\nfrom ex1 import gradient_descent, plot_cost_history\n\t\n# Second data to analyse, this one has three dimensions -> linear regression with multiple variables\n\n## Import data\ndata = np.loadtxt(\"ex1data2.txt\", delimiter=\",\")\n\nX = data[:, 0:2]\ny = data[:, 2]\n\n### Data normalization with bias column, set to 1\nm = data.shape[0]\n\nmu_0 = np.mean(X[:, 0])\nmu_1 = np.mean(X[:, 1])\n\nsigma_0 = np.std(X[:, 0])\nsigma_1 = np.std(X[:, 1])\n\nX_norm = np.stack((np.ones(m),\n\t\t\t\t\t(X[:, 0] - mu_0) / sigma_0, \n\t\t\t\t\t(X[:, 1] - mu_1) / sigma_1), \n\t\t\t\t\taxis=-1)\n\n## Important variables\ntheta = np.zeros(3)\n\niterations = 400\nalpha = 0.01\n\n# Evaluation\ntheta, cost_history = gradient_descent(X_norm, y, theta, iterations, alpha)\n\nplot_cost_history(cost_history)\n\nprint('Theta found by gradient descent', theta);\n\n# Predictions\nprint('For Estimate the price of a 1650 sq-ft, 3 br house', np.matmul(np.array([1, (1650-mu_0)/sigma_0, (3-mu_1)/sigma_1]), theta))\n\n#empty line for the sake of readability\nprint()\n\n\n\n\n# Now let's rework the previous example using closed-form solution to linear regresion (normal equations) instead of error minimisation\n\n## Import data\ndata = np.loadtxt(\"ex1data2.txt\", delimiter=\",\")\n\nX = data[:, 0:2]\ny = data[:, 2]\n\n### Data with bias column, set to 1\nm = data.shape[0]\n\nX = np.stack((np.ones(m), X[:, 0], X[:, 1]), axis=-1)\n\n## Important variables\ntheta = np.zeros(3)\n\ndef closed_form(X, y):\n\tX_T = np.matrix.transpose(X)\n\t\n\tstep1 = np.matmul(X_T, X)\n\tstep2 = np.linalg.inv(step1)\n\tstep3 = np.matmul(step2, X_T)\n\t\n\treturn np.matmul(step3, y)\n\n# Evaluation\ntheta = closed_form(X, y)\n\nprint('Theta found by normal equations', theta);\n\n# Predictions\nprint('For Estimate the price of a 1650 sq-ft, 3 br house', np.matmul(np.array([1, 1650, 3]), theta))\n", "meta": {"hexsha": "9d01090cda4c3e0c89f6c9d2ac3c4f2117fe6f47", "size": 1843, "ext": "py", "lang": "Python", "max_stars_repo_path": "ex1_multi.py", "max_stars_repo_name": "fredericoschardong/programming-exercise-1-linear-regression-university-of-stanford", "max_stars_repo_head_hexsha": "de90c9984d16b58a17c49d483b2abc76daa31071", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex1_multi.py", "max_issues_repo_name": "fredericoschardong/programming-exercise-1-linear-regression-university-of-stanford", "max_issues_repo_head_hexsha": "de90c9984d16b58a17c49d483b2abc76daa31071", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex1_multi.py", "max_forks_repo_name": "fredericoschardong/programming-exercise-1-linear-regression-university-of-stanford", "max_forks_repo_head_hexsha": "de90c9984d16b58a17c49d483b2abc76daa31071", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-09T05:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-15T01:51:07.000Z", "avg_line_length": 22.2048192771, "max_line_length": 135, "alphanum_fraction": 0.6793271839, "include": true, "reason": "import numpy", "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321452198369, "lm_q2_score": 0.9284088074883807, "lm_q1q2_score": 0.8952845294709513}}
{"text": "import numpy as np\n\n\ndef compute_mse(theta_0, theta_1, data):\n    \"\"\"\n    Calcula o erro quadratico medio\n    :param theta_0: float - intercepto da reta\n    :param theta_1: float -inclinacao da reta\n    :param data: np.array - matriz com o conjunto de dados, x na coluna 0 e y na coluna 1\n    :return: float - o erro quadratico medio\n    \"\"\"\n    return 1 * sum((theta_0 + theta_1*data[:,0] - data[:,1])**2) / data.shape[0] \n\n\ndef step_gradient(theta_0, theta_1, data, alpha):\n    \"\"\"\n    Executa uma atualização por descida do gradiente  e retorna os valores atualizados de theta_0 e theta_1.\n    :param theta_0: float - intercepto da reta\n    :param theta_1: float -inclinacao da reta\n    :param data: np.array - matriz com o conjunto de dados, x na coluna 0 e y na coluna 1\n    :param alpha: float - taxa de aprendizado (a.k.a. tamanho do passo)\n    :return: float,float - os novos valores de theta_0 e theta_1, respectivamente\n    \"\"\"\n    d_theta_0 = 2 * sum(theta_0 + theta_1*data[:,0] - data[:,1]) / data.shape[0]\n    d_theta_1 = 2 * sum((theta_0 + theta_1*data[:,0] - data[:,1]) * data[:,0]) / data.shape[0]\n    (new_theta_0, new_theta_1) = theta_0 - alpha * d_theta_0,  theta_1 - alpha * d_theta_1\n    return (new_theta_0, new_theta_1)\n\ndef fit(data, theta_0, theta_1, alpha, num_iterations):\n    \"\"\"\n    Para cada época/iteração, executa uma atualização por descida de\n    gradiente e registra os valores atualizados de theta_0 e theta_1.\n    Ao final, retorna duas listas, uma com os theta_0 e outra com os theta_1\n    obtidos ao longo da execução (o último valor das listas deve\n    corresponder à última época/iteração).\n\n    :param data: np.array - matriz com o conjunto de dados, x na coluna 0 e y na coluna 1\n    :param theta_0: float - intercepto da reta\n    :param theta_1: float -inclinacao da reta\n    :param alpha: float - taxa de aprendizado (a.k.a. tamanho do passo)\n    :param num_iterations: int - numero de épocas/iterações para executar a descida de gradiente\n    :return: list,list - uma lista com os theta_0 e outra com os theta_1 obtidos ao longo da execução\n    \"\"\"\n    theta_0_list = [theta_0]\n    theta_1_list = [theta_1]\n    for i in range(num_iterations):\n        theta_0, theta_1 = step_gradient(theta_0, theta_1, data, alpha)\n        theta_0_list.append(theta_0)\n        theta_1_list.append(theta_1)\n    return theta_0_list, theta_1_list\n    \n", "meta": {"hexsha": "de008e61d04b1327bbec2b9c773ccf49ca51500c", "size": 2378, "ext": "py", "lang": "Python", "max_stars_repo_path": "t3/alegrete.py", "max_stars_repo_name": "gabrielcoutod/Trabalhos-IA-2021-1", "max_stars_repo_head_hexsha": "8726ffd60ceef08f23506fb675ccf1acb07c9096", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "t3/alegrete.py", "max_issues_repo_name": "gabrielcoutod/Trabalhos-IA-2021-1", "max_issues_repo_head_hexsha": "8726ffd60ceef08f23506fb675ccf1acb07c9096", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "t3/alegrete.py", "max_forks_repo_name": "gabrielcoutod/Trabalhos-IA-2021-1", "max_forks_repo_head_hexsha": "8726ffd60ceef08f23506fb675ccf1acb07c9096", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.7307692308, "max_line_length": 108, "alphanum_fraction": 0.6921783011, "include": true, "reason": "import numpy", "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214491222695, "lm_q2_score": 0.9284088025362857, "lm_q1q2_score": 0.8952845218396619}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Sep 30 08:41:19 2021\r\n\r\n@author: Ezra\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\ndef f(x):\r\n    return -x*np.sin(x)-x*x/4*np.cos(x)\r\n\r\ndef fPrime(x):\r\n    return x**2/4*np.sin(x)-3*x/2*np.cos(x)-np.sin(x)\r\n\r\n# def f(x):\r\n#     return -x*np.sin(x)-x**2/4*np.cos(x)\r\n\r\n# def fPrime(x):\r\n#     return x**2/4*np.sin(x)-3*x/2*np.cos(x)-np.sin(x)\r\n\r\ndef fwdDiff(x0,h):\r\n    dfdx=(f(x0+h)-f(x0))/h\r\n    return dfdx\r\n\r\n\r\ndef bacDiff(x0,h):\r\n    dfdx=(f(x0)-f(x0-h))/h\r\n    return dfdx\r\n\r\n\r\ndef cenDiff(x0,h):\r\n    \r\n    dfdx=(f(x0+h)-f(x0-h))/(2*h)\r\n    return dfdx\r\n\r\n\r\ndef fourthOrdDiff(x0,h):\r\n    #dfdx = 1/3*((4*f(x0+h)-4*f(x0-h))/(2*h)-(f(x0+2*h)-f(x0-2*h))/(4*h))\r\n    #return dfdx\r\n    dfdx = (4*cenDiff(x0, h/2)-cenDiff(x0,h))/3\r\n    return dfdx\r\n\r\ndef sixthOrdDiff(x0,h):\r\n    dfdx=(16*(fourthOrdDiff(x0, h/2))-fourthOrdDiff(x0, h))/15\r\n    return dfdx\r\n\r\n\r\nx0=np.array([-3,-2.5,-2,-1.5,-1,-.5,0,.5,1,1.5,2,2.5,3])\r\nfde=fwdDiff(x0,.1)\r\nbde=bacDiff(x0,.1)\r\ncde=cenDiff(x0,.1)\r\nfoe=fourthOrdDiff(x0, 0.1)\r\nsoe=sixthOrdDiff(x0,.1)\r\nact=fPrime(x0)\r\n\r\nprint(\"Forward Difference Estimate=\", fde)\r\nprint(\"Backwards Difference Estimate=\", bde)\r\nprint(\"Center Difference Estimate=\", cde)\r\nprint(\"Fourth Order Difference Estimate=\", foe)\r\nprint(\"Sixth Order Difference Estimate=\", soe)\r\nprint(\"Analytic Value of Derivative=\", act)\r\n\r\ndef err(x,y):\r\n\r\n    return abs((y-x)/y)\r\n\r\nh=np.array([.5,.5**2,.5**3,.5**4,.5**5])\r\n\r\nx0=1\r\nanalytical= fPrime(x0)\r\nerrFwd=[]\r\nerrCen=[]\r\nerrBac=[]\r\nerrFourthOrder=[]\r\nerrSixthOrder=[]\r\ndfdxFwd=[]\r\ndfdxBac=[]\r\ndfdxCen=[]\r\ndfdxFourth=[]\r\ndfdxSixth=[]\r\n\r\nfor i in range(len(h)):\r\n    dfdxFwd.append(fwdDiff(x0,h[i]))\r\n    dfdxBac.append(bacDiff(x0,h[i]))\r\n    dfdxCen.append(cenDiff(x0,h[i]))\r\n    dfdxFourth.append(fourthOrdDiff(x0,h[i]))\r\n    dfdxSixth.append(sixthOrdDiff(x0, h[i]))\r\n    errFwd.append(err(dfdxFwd[i],analytical))\r\n    errBac.append(err(dfdxBac[i],analytical))\r\n    errCen.append(err(dfdxCen[i],analytical))\r\n    errFourthOrder.append(err(dfdxFourth[i],analytical))\r\n    errSixthOrder.append(err(dfdxSixth[i],analytical))\r\n\r\n    \r\nimport matplotlib.pyplot as plt\r\n    \r\nplt. figure(0)\r\nplt.semilogy(h,errFwd,label=\"FWD\")\r\nplt.semilogy(h,errBac,label=\"BAC\")\r\nplt.semilogy(h,errCen,label=\"CEN\") \r\nplt.semilogy(h,errFourthOrder,label=\"FTH\")\r\nplt.semilogy(h,errSixthOrder,label=\"SIX\")\r\nplt.title(\"Error of methods of various orders\")\r\nplt.xlabel(\"h\")\r\nplt.ylabel(\"Relative error\")\r\nplt.grid(True)\r\nplt.legend()\r\nplt.show()\r\n\r\n\r\n# print(errCen)\r\n# #print(dfdxFwd)\r\n# print(err(dfdxFwd,analytical))\r\n", "meta": {"hexsha": "3b57a680e308a0ecce9089cac96c0715590c62d3", "size": 2571, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numerical Differentiation.py", "max_stars_repo_name": "kiwibird2/Numerical-Analysis", "max_stars_repo_head_hexsha": "658eb4ddddc63511a0d574625a1cf359d09c1c52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numerical Differentiation.py", "max_issues_repo_name": "kiwibird2/Numerical-Analysis", "max_issues_repo_head_hexsha": "658eb4ddddc63511a0d574625a1cf359d09c1c52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numerical Differentiation.py", "max_forks_repo_name": "kiwibird2/Numerical-Analysis", "max_forks_repo_head_hexsha": "658eb4ddddc63511a0d574625a1cf359d09c1c52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3565217391, "max_line_length": 74, "alphanum_fraction": 0.6196032672, "include": true, "reason": "import numpy", "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668717616668, "lm_q2_score": 0.9124361598816666, "lm_q1q2_score": 0.8952521326733229}}
{"text": "import numpy as np\r\nfrom scipy import constants\r\n\r\n#defining the function to be integrated with\r\ndef f(x):\r\n    return (x**3)/((np.exp(x)) - 1.)\r\n\r\n#defining the simpsons rule calculation\r\ndef simpsonsRule(f,a,b,N):\r\n    h = (b-a)/N\r\n    oddSum = 0\r\n    for k in range(1, N, 2):\r\n        oddSum += f(a+k*h)\r\n    evenSum = 0\r\n    for k in range(2, N, 2):\r\n        evenSum += f(a+k*h)\r\n    integral = (h/3)*(f(a)+f(b)+4*oddSum+2*evenSum)\r\n    return integral\r\n\r\n#constants for simpsons rule where N is the number of slices which must be even\r\n# a is the lower bound which we picked a really small number to approximate 0 to \r\n# avoid reaching division by zero\r\n# b is the upper bound which we picked a big number to approximate infinity \r\n# since we are going to the e^700 which is reaching python's limit and we do not\r\n# want to have overflow issues\r\nN = 10000\r\na = 0.000001\r\nb = 700\r\n\r\n#checking integral with wolfram alpha's result\r\nintegral = simpsonsRule(f, a, b, N)\r\nprint('integral:', integral)\r\n\r\n#let temperature to be 100 Kelvin for our calculations\r\nT = 100\r\n#The constant that we got from part a\r\nC = (2 * constants.pi * (constants.k**4) * (T**4))/((constants.h**3)*(constants.c**2))\r\nW = C * integral\r\n#comparing our results and checking the accuracy\r\nprint('constant from integration', W/(T**4))\r\nprint('scipy constant', constants.sigma)\r\nprint('Accuracy', (1 - ((W/(T**4)) - constants.sigma)/constants.sigma) * 100, '%')\r\n", "meta": {"hexsha": "ca0928ddf1650963d31da98eb004c1fe29862f9d", "size": 1436, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab2/lab2_Q3.py", "max_stars_repo_name": "fancent/PHY407", "max_stars_repo_head_hexsha": "38ce8badb9537060becc255ec64e6de2968ca73c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-20T17:30:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-20T17:30:06.000Z", "max_issues_repo_path": "Lab2/lab2_Q3.py", "max_issues_repo_name": "fancent/PHY407", "max_issues_repo_head_hexsha": "38ce8badb9537060becc255ec64e6de2968ca73c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab2/lab2_Q3.py", "max_forks_repo_name": "fancent/PHY407", "max_forks_repo_head_hexsha": "38ce8badb9537060becc255ec64e6de2968ca73c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-12T14:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T14:21:13.000Z", "avg_line_length": 33.3953488372, "max_line_length": 87, "alphanum_fraction": 0.6608635097, "include": true, "reason": "import numpy,from scipy", "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9759464499040092, "lm_q2_score": 0.9173026533686324, "lm_q1q2_score": 0.8952382680426447}}
{"text": "import math\nimport numpy as np\n#-------------------------------------------------------------------------\n'''\n    Problem 2: User-based recommender systems\n    In this problem, you will implement a version of the recommender system using user-based method.\n    You could test the correctness of your code by typing `nosetests test2.py` in the terminal.\n'''\n\n#--------------------------\ndef cosine_similarity(RA, RB):\n    '''\n        compute the cosine similarity between user A and user B.\n        The similarity values between users are measured by observing all the items which have been rated by BOTH users.\n        If an item is only rated by one user, the item will not be involved in the similarity computation.\n        You need to first remove all the items that are not rated by both users from RA and RB.\n        If the two users don't share any item in their ratings, return 0. as the similarity.\n        Then the cosine similarity is < RA, RB> / (|RA|* |RB|).\n        Here <RA, RB> denotes the dot product of the two vectors (see here https://en.wikipedia.org/wiki/Dot_product).\n        |RA| denotes the L-2 norm of the vector RA (see here for example: http://mathworld.wolfram.com/L2-Norm.html).\n        For more details, see here https://en.wikipedia.org/wiki/Cosine_similarity.\n        Input:\n            RA: the ratings of user A, a float python vector of length m (the number of movies).\n                If the rating is unknown, the number is 0. For example the vector can be like [0., 0., 2.0, 3.0, 0., 5.0]\n            RB: the ratings of user B, a float python vector\n                If the rating is unknown, the number is 0. For example the vector can be like [0., 0., 2.0, 3.0, 0., 5.0]\n        Output:\n            S: the cosine similarity between users A and B, a float scalar value between -1 and 1.\n        Hint: you could use math.sqrt() to compute the square root of a number\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n    # assuming cosine(RA, RB) = P/(sqrt(NA)*sqrt(NB))\n\n    def is_any_zero(l):\n        return(any([elem==0.0 for elem in l]))\n\n    comb_ratings = zip(RA, RB)\n    comb_ratings = [pair for pair in comb_ratings if not is_any_zero(pair)]\n\n    if len(comb_ratings) == 0:\n        S = 0.0\n    else:\n        filt_RA, filt_RB = zip(*comb_ratings)\n        P  = float(np.dot(filt_RA, filt_RB))\n        NA = float(np.dot(filt_RA, filt_RA))\n        NB = float(np.dot(filt_RB, filt_RB))\n\n        S = P/(math.sqrt(NA) * math.sqrt(NB))\n\n    #########################################\n    return S\n\n\n#--------------------------\ndef find_users(R, i):\n    '''\n        find the all users who have rated the i-th movie.\n        Input:\n            R: the rating matrix, a float numpy matrix of shape m by n. Here m is the number of movies, n is the number of users.\n                If a rating is unknown, the number is 0.\n            i: the index of the i-th movie, an integer python scalar (Note: the index starts from 0)\n        Output:\n            idx: the indices of the users, a python list of integer values\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n    np_idx = np.nonzero(R[i,:])[0]\n    idx = list(map(np.asscalar, np_idx))\n\n    #########################################\n    return idx\n\n#--------------------------\ndef user_similarity(R, j, idx):\n    '''\n        compute the cosine similarity between a collection of users in idx list and the j-th user.\n        Input:\n            R: the rating matrix, a float numpy matrix of shape m by n. Here m is the number of movies, n is the number of users.\n                If a rating is unknown, the number is 0.\n            j: the index of the j-th user, an integer python scalar (Note: the index starts from 0)\n            idx: a list of user indices, a python list of integer values\n        Output:\n            sim: the similarity between any user in idx list and user j, a python list of float values. It has the same length as idx.\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n    np_sim = np.apply_along_axis(\n        lambda x: cosine_similarity(x,R[:, j]),\n        0,\n        R[:, idx]\n        )\n    sim = list(map(np.asscalar, np_sim))\n\n    #########################################\n    return sim\n\n\n#--------------------------\ndef user_based_prediction(R, i_movie, j_user, K=5):\n    '''\n        Compute a prediction of the rating of the j-th user on the i-th movie using user-based approach.\n        First we take all the users who have rated the i-th movie, and compute their similarities to the target user j.\n        If there is no user who has rated the i-th movie, predict 3.0 as the default rating.\n        From these users, we pick top K similar users.\n        If there are less than K users who has rated the i-th movie, use all these users.\n        We weight the user's ratings on i-th movie by the similarity between that user and the target user.\n        Finally, we rescale the prediction by the sum of similarities to get a reasonable value for the predicted rating.\n        Input:\n            R: the rating matrix, a float numpy matrix of shape m by n. Here m is the number of movies, n is the number of users.\n                If the rating is unknown, the number is 0.\n            i_movie: the index of the i-th movie, an integer python scalar\n            j_user: the index of the j-th user, an integer python scalar\n            K: the number of similar users to compute the weighted average rating.\n        Output:\n            p: the predicted rating of user j on movie i, a float scalar value between 1. and 5.\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n    # find all other users who have rated movie i.\n    i_movie_users = find_users(R, i_movie)\n\n    if len(i_movie_users) == 0:\n        p = 3\n        return p\n\n    # compute the similarity between all of these users with user j\n    u_sim = user_similarity(R, j_user, i_movie_users)\n    user_rating_pair = sorted(\n        zip(i_movie_users, u_sim),\n        key=lambda x: x[1],\n        reverse=True)\n\n    # if there are less than K users who have rated the movie, change K to the number of users\n    top_similar_user, top_similar_user_sim = zip(*user_rating_pair[:K])\n\n    ratings_top_sim_users = R[i_movie, top_similar_user]\n\n    # compute the weighted average of the top K similar users to user j\n\n    p = np.dot(top_similar_user_sim, ratings_top_sim_users)/sum(top_similar_user_sim)\n\n    #########################################\n    return p\n\n\n#--------------------------\ndef compute_RMSE(ratings_pred, ratings_real):\n    '''\n        Compute the root of mean square error of the rating prediction.\n        Input:\n            ratings_pred: predicted ratings, a float python list\n            ratings_real: real ratings, a float python list\n        Output:\n            RMSE: the root of mean squared error of the predicted rating, a float scalar.\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n    RMSE = math.sqrt((\n            (np.array(ratings_pred) - np.array(ratings_real))**2.0\n            ).mean()\n        )\n\n    #########################################\n    return RMSE\n\n\n\n#--------------------------\ndef load_rating_matrix(filename = 'movielens_train.csv'):\n    '''\n        Load the rating matrix from a CSV file.  In the CSV file, each line represents (user id, movie id, rating).\n        Note the ids start from 1 in this dataset.\n        Input:\n            filename: the file name of a CSV file, a string\n        Output:\n            R: the rating matrix, a float numpy array of shape m by n. Here m is the number of movies, n is the number of users.\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n    import pandas as pd\n\n    movielens_train_data_ = pd.read_csv(\n        filename,\n        header=None,\n        names=['user_id', 'movie_id', 'rating'],\n        delimiter=',')\n\n    movielens_train_data_[['user_id', 'movie_id']] = movielens_train_data_[['user_id', 'movie_id']].apply(lambda x: x-1)\n\n    all_movie_ids = pd.DataFrame(\n        pd.Series(\n            range(max(movielens_train_data_.movie_id)))\n        )\n    all_movie_ids.columns = ['movie_id']\n    movielens_train_data_mod_ = pd.merge(movielens_train_data_, all_movie_ids, on='movie_id', how = 'outer')\n\n    movielens_train_data_mod_.fillna(0, inplace=True)\n\n    R_inter = pd.pivot_table(\n        movielens_train_data_mod_,\n        values='rating',\n        index='movie_id',\n        columns='user_id',\n        aggfunc=max)\n\n    R = np.array(R_inter.fillna(0))\n\n    #########################################\n    return R\n\n\n#--------------------------\ndef load_test_data(filename = 'movielens_test.csv'):\n    '''\n        Load the test data from a CSV file.  In the CSV file, each line represents (user id, movie id, rating).\n        Note the ids in the CSV file start from 1. But the indices in u_ids and m_ids start from 0.\n        Input:\n            filename: the file name of a CSV file, a string\n        Output:\n            m_ids: the list of movie ids, an integer python list of length n. Here n is the number of lines in the test file. (Note indice should start from 0)\n            u_ids: the list of user ids, an integer python list of length n.\n            ratings: the list of ratings, a float python list of length n.\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n    import pandas as pd\n\n    col_names = ['user_id', 'movie_id', 'rating']\n\n    movielens_test_data_ = pd.read_csv(\n        filename,\n        header=None,\n        names=col_names,\n        delimiter=',')\n\n    def unpack(d, *keys):\n        return tuple(d[k] for k in keys)\n\n    data_dict_ = movielens_test_data_.to_dict(orient='series')\n\n    u_ids, m_ids, ratings = map(list, unpack(data_dict_, *col_names))\n\n    u_ids   = list(map(lambda x: x-1, u_ids))\n    m_ids   = list(map(lambda x: x-1, m_ids))\n    ratings = list(map(float, ratings))\n\n    #########################################\n    return m_ids, u_ids, ratings\n\n\n#--------------------------\ndef movielens_user_based(train_file='movielens_train.csv', test_file ='movielens_test.csv', K = 5):\n    '''\n        Compute movie ratings in movielens dataset. Based upon the training ratings, predict all values in test pairs (movie-user pair).\n        In the training file, each line represents (user id, movie id, rating).\n        Note the ids start from 1 in this dataset.\n        Input:\n            train_file: the train file of the dataset, a string.\n            test_file: the test file of the dataset, a string.\n            K: the number of similar users to compute the weighted average rating.\n        Output:\n            RMSE: the root of mean squared error of the predicted rating, a float scalar.\n    Note: this function may take 1-5 minutes to run.\n    '''\n\n    # load training set\n    R = load_rating_matrix(train_file)\n\n    # load test set\n    m_ids, u_ids, ratings_real = load_test_data(test_file)\n\n    # predict on test set\n    #########################################\n    ## INSERT YOUR CODE HERE\n    ratings_pred = list(map(\n        lambda x: user_based_prediction(R, x[0], x[1], K=5),\n        zip(m_ids, u_ids)\n        )\n    )\n\n    #########################################\n    # compute RMSE\n    RMSE = compute_RMSE(ratings_pred,ratings_real)\n    return  RMSE\n\n\n", "meta": {"hexsha": "f3075957ab9d876349d49ec3e6fb156b9306e0bc", "size": 11404, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw3/problem2.py", "max_stars_repo_name": "rahul-pande/ds501", "max_stars_repo_head_hexsha": "063453de9bf7bc634422a6710d36715175cbeebf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw3/problem2.py", "max_issues_repo_name": "rahul-pande/ds501", "max_issues_repo_head_hexsha": "063453de9bf7bc634422a6710d36715175cbeebf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw3/problem2.py", "max_forks_repo_name": "rahul-pande/ds501", "max_forks_repo_head_hexsha": "063453de9bf7bc634422a6710d36715175cbeebf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0547945205, "max_line_length": 159, "alphanum_fraction": 0.5844440547, "include": true, "reason": "import numpy", "num_tokens": 2653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854094395751, "lm_q2_score": 0.9230391653625205, "lm_q1q2_score": 0.8951499149098556}}
{"text": "from math import sqrt\nimport numpy as np\n\n# Primality Testing\n\n# Returns a list of primes less than n using Sieve of Erathosthenes' algorithm\ndef sieve_of_erathosthenes(n):\n    # List of integers from 1 to n-1 (assume all are prime for now)\n    sieve = np.ones(n, dtype=\"bool\")\n\n    # Zero and one are not prime\n    sieve[0] = False\n    sieve[1] = False\n\n    # Iterate the multiples of each integer, from 1 to sqrt(n), as composite\n    for number in range(2, int(sqrt(n)) + 1):\n        # If the integer is prime, flag its multiples as composite\n        if sieve[number]:\n            k = number * 2\n            while k < n:\n                sieve[k] = False\n                k += number\n    \n    # Return the list of integers from 1 to n-1 that are still listed as prime\n    return np.array([number for number in range(n) if sieve[number]])\n\n\n# Determines if n is a prime by using the Miller-Rabin primality test\n# Uses 100 different bases for testing\ndef miller_rabin(n):\n    # Return true if n is 2 or 3\n    if n == 2 or n == 3:\n        return True\n\n    # Return false if n is divisible by 2    \n    if n % 2 == 0:\n        return False\n    \n    m = n - 1\n    t = 0\n\n    while m % 2 == 0:\n        m = m // 2\n        t += 1\n    \n    # Try 100 different numbers to see if n is prime\n    for number in range(2, 102):\n        v = pow(number, m, n)\n\n        if not v == 1 and not v == n - 1:\n            i = 0\n\n            while v != (n - 1):\n                if i == t - 1:\n                    return False\n                else:\n                    i += 1\n                    v = (v ** 2) % n\n                    \n                    if v == 1:\n                        return False\n    return True\n\n\n# Uses a probabilistic method of determining if a number is prime\ndef is_prime(n):\n    # Integers less than 2 are not prime\n    if n < 2:\n        return False\n    \n    # Check the sieve list if n is prime or not\n    for prime in SIEVE_LIST:\n        if n == prime: \n            # n is in the list, so it's prime\n            return True\n        elif n % prime == 0:\n            # n isn't in the list, but is a multiple of a number in the list, so it's composite\n            return False\n    \n    # Try the Miller-Rabin primality last\n    return miller_rabin(n)\n\n\n# List of primes under 1,000,000\nSIEVE_LIST = sieve_of_erathosthenes(1_000_000)", "meta": {"hexsha": "1788e6c0b0a5cb9fbbadab8c8861cf86195b8ba1", "size": 2333, "ext": "py", "lang": "Python", "max_stars_repo_path": "cryptosystems/primality_tests.py", "max_stars_repo_name": "farnswj1/CryptographyProject", "max_stars_repo_head_hexsha": "2f7c553011810c8939cd01e68d743e1a64f71200", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-07T08:10:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-07T08:10:15.000Z", "max_issues_repo_path": "cryptosystems/primality_tests.py", "max_issues_repo_name": "farnswj1/CryptographyProject", "max_issues_repo_head_hexsha": "2f7c553011810c8939cd01e68d743e1a64f71200", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cryptosystems/primality_tests.py", "max_forks_repo_name": "farnswj1/CryptographyProject", "max_forks_repo_head_hexsha": "2f7c553011810c8939cd01e68d743e1a64f71200", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-14T14:24:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T14:24:24.000Z", "avg_line_length": 27.4470588235, "max_line_length": 95, "alphanum_fraction": 0.5443634805, "include": true, "reason": "import numpy", "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9865717456528508, "lm_q2_score": 0.9073122207340544, "lm_q1q2_score": 0.8951286014617607}}
{"text": "\"\"\"\nA/B testing: Ads Click Through Rate\nhttps://byrony.github.io/understanding-ab-testing-and-statistics-behind.html\nQuestion:\nTwo Ads, Ad one has 1000 impressions and 20 clicks, CTR is 2%;\nAd two has 900 impressions and 30 clicks, CTR is 3.3%.\nTest whether there is difference between Click Through Rate (CTR) between Ad one and two.\n\"\"\"\n\nimport numpy as np\nfrom scipy import stats\n#%% t-test for equal mean H0\n#Why use t-test rather than Z-test?\n\n# We use t-test instead of Z-test since we don't know the standard deviation of the population. So we use the standard deviation of sample to replace the unknown standard deviation of the population, then t-test should be implemented. Notice this is different from the first example where observation mean is compared with expected mean. As there is only one population, assume the null hypothesis is true then standard deviation of population can be computed.\n# follow normal distribution: sample mean ~ N(p, p * (1 - p)/n)\n\nn1, c1, n2, c2 = 1000, 20, 900, 30\np1 = c1 / n1\np2 = c2 / n2\n# se - np.sqrt(Var1 / n1 + Var2 / n2 )  # se of mean\nse = np.sqrt( p1 * (1 - p1) / n1 + p2 * (1 - p2) / n2 )\nt = np.abs(p1 - p2) / se\nprint(f'{p1}, {p2}, {t}')\np_value = 1 - stats.t.cdf(t, df=min(n1 -1, n2-1))\n# two tailed t-test  Ha: not equal mean\nprint(f'p = {p_value * 2}')\n# one tailed t-test  Ha: p2 > p1\nprint(f'p = {p_value * 2}')\n\n\n#%% A/B testing Chi-square\n#Hypothesis:\n#H0: Variable Ad type and variable Whether click are independent\n#Ha: Variable Ad type and variable Whether click are not independent\n#     click | nonClick\n#Ad1\n#Ad2\nX = np.array([[20, 980], [30, 870]])\nprint(X)\nprint('If p_value < 0.05, we can reject null hypothsis')\nprint('chi2 {}, p_value {}, dof {}, \\nexpected {} '.format(*stats.chi2_contingency(X, correction=False)))\n\n#%% Normal Approximation to Binomial:\n# we can use normal distribution to approximate binomial distribution (sum of bernoulli) when n is large.\n", "meta": {"hexsha": "ab18ef0664880dda7797102b8e8db2ba3f18b503", "size": 1938, "ext": "py", "lang": "Python", "max_stars_repo_path": "ab_test.py", "max_stars_repo_name": "xk97/test_stats", "max_stars_repo_head_hexsha": "7f985988e72bd375c2011b29d42315a62da7c86c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ab_test.py", "max_issues_repo_name": "xk97/test_stats", "max_issues_repo_head_hexsha": "7f985988e72bd375c2011b29d42315a62da7c86c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ab_test.py", "max_forks_repo_name": "xk97/test_stats", "max_forks_repo_head_hexsha": "7f985988e72bd375c2011b29d42315a62da7c86c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1304347826, "max_line_length": 460, "alphanum_fraction": 0.7069143447, "include": true, "reason": "import numpy,from scipy", "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371972, "lm_q2_score": 0.9314625136270513, "lm_q1q2_score": 0.8950904906481485}}
{"text": "'''\nCollated by Prof. Ching-Shih Tsou 鄒慶士 教授 (Ph.D.) at the Dept. of ME and AI&DS (機械工程系與人工智慧暨資料科學研究中心主任), MCUT(明志科技大學); the IDS (資訊與決策科學研究所), NTUB (國立臺北商業大學); the CARS(中華R軟體學會創會理事長); and the DSBA(臺灣資料科學與商業應用協會創會理事長)\nNotes: This code is provided without warranty.\n'''\n\n#### A. Python的複數\n# importing \"cmath\" for complex number operations \n# import cmath \n  \n# Initializing real numbers \nx = 5\ny = 3\n  \n# converting x and y into complex number \nz = complex(x, y); \n\n[(nam, type(getattr(z, nam))) for nam in dir(z)]\n\n# printing real and imaginary part of complex number \nprint (\"The real part of complex number is : {}\".format(z.real)) \n  \nprint (\"The imaginary part of complex number is : {}\".format(z.imag)) \n\nz.conjugate()\n\n-2j # (-0-2j)\n\n#### B. DFT與IDFT簡例(by FFT)\nfrom scipy.fftpack import fft, ifft\nimport numpy as np # Why not \"from numpy.fft import fft, ifft\" ? Because of the conflicting namespace.\n\n#### 假定時間序列為離散序列，從1到3中隨機選取5數\nx = np.random.choice(range(1,4), 5)\n# x = np.arange(5)\ntype(x) # numpy.ndarray\nx.dtype # dtype('int64')\n\nfrom matplotlib import pyplot as plt \nplt.plot(x)\n\n# 傅立葉轉換為複數(scipy and numpy)\n# by scipy\nfft(x)\ntype(fft(x)) # numpy.ndarray\nfft(x).dtype # 複數 dtype('complex128')\n\n# by numpy\nnp.fft.fft(x)\ntype(np.fft.fft(x)) # numpy.ndarray\nnp.fft.fft(x).dtype # 複數 dtype('complex128')\n\n#### 逆傅立葉轉換為原時間序列(結果為複數形式，雖然虛部為0)\n# by scipy\nifft(fft(x)) # array([0.+0.j, 1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j])\ntype(ifft(fft(x)))\n# The returned complex array contains ``y(0), y(1),..., y(n-1)`` where    \n#    ``y(j) = (x * exp(2*pi*sqrt(-1)*j*np.arange(n)/n)).mean()``.\n\n#### 注意！資料型別還是dtype('complex128')，雖然虛部均為0\nifft(fft(x)).dtype \nx\n\n# by numpy\nnp.fft.ifft(np.fft.fft(x)) # array([0.+0.j, 1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j])\ntype(np.fft.ifft(np.fft.fft(x)))\nnp.fft.ifft(np.fft.fft(x)).dtype # 還是dtype('complex128')，雖然虛部均為0\n\n#### np.allclose()檢查逆轉換回來之時間序列是否與序列接近\nnp.allclose(ifft(fft(x)), x, atol=1e-15)  # within numerical accuracy. True\nnp.allclose(np.fft.ifft(np.fft.fft(x)), x, atol=1e-15)  # within numerical accuracy. True\n\n# import numpy as np\n\n# def DFT(x):\n#     \"\"\"\n#     Compute the discrete Fourier Transform of the 1D array x\n#     :param x: array\n#     \"\"\"\n    \n#     N = x.size\n#     n = np.arange(N)\n#     k = n.reshape((N, 1))\n#     e = np.exp(-2j * np.pi * k * n / N)\n#     return np.dot(e, x)", "meta": {"hexsha": "aa929ac172233034c36636b227228a28118ff0a6", "size": 2319, "ext": "py", "lang": "Python", "max_stars_repo_path": "complexNumber_firstFFT&IFFT.py", "max_stars_repo_name": "appletime81/Data_Signal_Processing", "max_stars_repo_head_hexsha": "5dd2ad96814744e6ce2848554696a48380756750", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "complexNumber_firstFFT&IFFT.py", "max_issues_repo_name": "appletime81/Data_Signal_Processing", "max_issues_repo_head_hexsha": "5dd2ad96814744e6ce2848554696a48380756750", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "complexNumber_firstFFT&IFFT.py", "max_forks_repo_name": "appletime81/Data_Signal_Processing", "max_forks_repo_head_hexsha": "5dd2ad96814744e6ce2848554696a48380756750", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6071428571, "max_line_length": 212, "alphanum_fraction": 0.6442432083, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 1019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993889, "lm_q2_score": 0.936285006192502, "lm_q1q2_score": 0.8950710078556058}}
{"text": "#T# relational operators are used to do relational operations, i.e. operations in which there is testing of the values of numbers, by comparing them against each other\n\n#T# the equality == operator compares if two numbers are equal\na = 5; b = 3\nbool1 = a == b # False\na = 4; b = 4\nbool1 = a == b # True\n\n#T# the not equal != operator compares if two number are not equal\na = 5; b = 3\nbool1 = a != b # True\na = 4; b = 4\nbool1 = a != b # False\n\n#T# the greater than > operator compares if the first number is greater than the second\na = 5; b = 3\nbool1 = a > b # True\na = 4; b = 4\nbool1 = a > b # False\n\n#T# the less than < operator compares if the first number is less than the second\na = 3; b = 5\nbool1 = a < b # True\na = 4; b = 4\nbool1 = a < b # False\n\n#T# the greater than or equal to >= operator compares if the first number is greater than or equal to the second\na = 5; b = 3\nbool1 = a >= b # True\na = 4; b = 4\nbool1 = a >= b # True\na = 3; b = 5\nbool1 = a >= b # False\n\n#T# the less than or equal to <= operator compares if the first number is less than or equal to the second\na = 3; b = 5\nbool1 = a <= b # True\na = 4; b = 4\nbool1 = a <= b # True\na = 5; b = 3\nbool1 = a <= b # False\n\n#T# to do relational operations with lists or arrays element-wise, the numpy package is used\nimport numpy as np\n\n#T# the array_equal function from the numpy package, compares if two arrays are equal, with the same shape and the same elements\narr1 = np.array([[6, 9, 4, 4], [8, 1, 9, 10]])\narr2 = np.array([[6, 9, 4, 4], [8, 1, 9, 10]])\nbool1 = np.array_equal(arr1, arr2) # True\n\n#T# the equal function from the numpy package, compares if two arrays are equal element-wise, it supports array broadcasting\narr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])\narr2 = np.array([7, 3, 4, 8])\narr3 = np.equal(arr1, arr2)\n# array([[False, False,  True, False], [False, False, False,  True]])\n\n#T# the equality operator == can be used to compare if two numpy arrays are equal element-wise, it supports array broadcasting\narr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])\narr2 = np.array([7, 3, 4, 8])\narr3 = arr1 == arr2\n# array([[False, False,  True, False], [False, False, False,  True]])\n\n#T# the not_equal function from the numpy package, compares if two arrays are not equal element-wise, it supports array broadcasting\narr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])\narr2 = np.array([7, 3, 4, 8])\narr3 = np.not_equal(arr1, arr2)\n# array([[ True,  True, False,  True], [ True,  True,  True, False]])\n\n#T# the not equal != operator can be used to compare if two numpy arrays are not equal element-wise, it supports array broadcasting\narr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])\narr2 = np.array([7, 3, 4, 8])\narr3 = arr1 != arr2\n# array([[ True,  True, False,  True], [ True,  True,  True, False]])\n\n#T# the greater function from the numpy package, compares if the first array is greater than the second element-wise, it supports array broadcasting\narr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])\narr2 = np.array([7, 3, 4, 8])\narr3 = np.greater(arr1, arr2)\n# array([[False,  True, False, False], [ True, False,  True, False]])\n\n#T# the greater than > operator can be used to compare if the first numpy array is greater than the second element-wise, it supports array broadcasting\narr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])\narr2 = np.array([7, 3, 4, 8])\narr3 = arr1 > arr2\n# array([[False,  True, False, False], [ True, False,  True, False]])\n\n#T# the less function from the numpy package, compares if the first array is less than the second element-wise, it supports array broadcasting\narr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])\narr2 = np.array([7, 3, 4, 8])\narr3 = np.less(arr1, arr2)\n# array([[ True, False, False,  True], [False,  True, False, False]])\n\n#T# the less than < operator can be used to compare if the first numpy array is less than the second element-wise, it supports array broadcasting\narr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])\narr2 = np.array([7, 3, 4, 8])\narr3 = arr1 < arr2\n# array([[ True, False, False,  True], [False,  True, False, False]])\n\n#T# the greater_equal function from the numpy package, compares if the first array is greater than or equal to the second element-wise, it supports array broadcasting\narr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])\narr2 = np.array([7, 3, 4, 8])\narr3 = np.greater_equal(arr1, arr2)\n# array([[False,  True,  True, False], [ True, False,  True,  True]])\n\n#T# the greater than or equal to >= operator can be used to compare if the first numpy array is greater than or equal to the second element-wise, it supports array broadcasting\narr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])\narr2 = np.array([7, 3, 4, 8])\narr3 = arr1 >= arr2\n# array([[False,  True,  True, False], [ True, False,  True,  True]])\n\n#T# the less_equal function from the numpy package, compares if the first array is less than or equal to the second element-wise, it supports array broadcasting\narr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])\narr2 = np.array([7, 3, 4, 8])\narr3 = np.less_equal(arr1, arr2)\n# array([[ True, False,  True,  True], [False,  True, False,  True]])\n\n#T# the less than or equal to <= operator can be used to compare if the first numpy array is less than or equal to the second element-wise, it supports array broadcasting\narr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])\narr2 = np.array([7, 3, 4, 8])\narr3 = arr1 <= arr2\n# array([[ True, False,  True,  True], [False,  True, False,  True]])", "meta": {"hexsha": "fdfe89776dded7c98c16c8732faf29eda5d45d08", "size": 5427, "ext": "py", "lang": "Python", "max_stars_repo_path": "Math/A01_Arithmetics_basics/Programs/S03/Relational_operators.py", "max_stars_repo_name": "Polirecyliente/SGConocimiento", "max_stars_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Math/A01_Arithmetics_basics/Programs/S03/Relational_operators.py", "max_issues_repo_name": "Polirecyliente/SGConocimiento", "max_issues_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/A01_Arithmetics_basics/Programs/S03/Relational_operators.py", "max_forks_repo_name": "Polirecyliente/SGConocimiento", "max_forks_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8512396694, "max_line_length": 176, "alphanum_fraction": 0.6539524599, "include": true, "reason": "import numpy", "num_tokens": 1863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813451206063, "lm_q2_score": 0.9362850053035674, "lm_q1q2_score": 0.8950709987863583}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr  5 15:30:04 2018\n\n@author: Juanda\n\"\"\"\n## module newtonPoly\n''' p = evalPoly(a,xData,x).\nEvaluates Newton’s polynomial p at x. The coefficient\nvector {a} can be computed by the function ’coeffts’.\na = coeffts(xData,yData).\nComputes the coefficients of Newton’s polynomial.\n'''\nimport numpy as np\nfrom numpy import *\n\ndef _poly_newton_coefficient(x,y):\n    \"\"\"\n    x: list or np array contanining x data points\n    y: list or np array contanining y data points\n    \"\"\"\n\n    m = len(x)\n\n    x = np.copy(x)\n    a = np.copy(y)\n    for k in range(1,m):\n        a[k:m] = (a[k:m] - a[k-1])/(x[k:m] - x[k-1])\n\n    return a\n\ndef newton_polynomial(x_data, y_data, x):\n    \"\"\"\n    x_data: data points at x\n    y_data: data points at y\n    x: evaluation point(s)\n    \"\"\"\n    a = _poly_newton_coefficient(x_data, y_data)\n    n = len(x_data) - 1 # Degree of polynomial\n    p = a[n]\n    for k in range(1,n+1):\n        p = a[n-k] + (x -x_data[n-k])*p\n    return p\n\nx = [0,1,2]\ny = [10,15,5]\na=_poly_newton_coefficient(x,y)\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr  5 15:30:04 2018\n\n@author: Juanda\n\"\"\"\n## module newtonPoly\n''' p = evalPoly(a,xData,x).\nEvaluates Newton’s polynomial p at x. The coefficient\nvector {a} can be computed by the function ’coeffts’.\na = coeffts(xData,yData).\nComputes the coefficients of Newton’s polynomial.\n'''\nimport numpy as np\nfrom numpy import *\n\ndef _poly_newton_coefficient(x,y):\n    \"\"\"\n    x: list or np array contanining x data points\n    y: list or np array contanining y data points\n    \"\"\"\n\n    m = len(x)\n\n    x = np.copy(x)\n    a = np.copy(y)\n    for k in range(1,m):\n        a[k:m] = (a[k:m] - a[k-1])/(x[k:m] - x[k-1])\n\n    return a\n\ndef newton_polynomial(x_data, y_data, x):\n    \"\"\"\n    x_data: data points at x\n    y_data: data points at y\n    x: evaluation point(s)\n    \"\"\"\n    a = _poly_newton_coefficient(x_data, y_data)\n    n = len(x_data) - 1 # Degree of polynomial\n    p = a[n]\n    for k in range(1,n+1):\n        p = a[n-k] + (x -x_data[n-k])*p\n    return p\n\nx = [0,1,2]\ny = [10,15,5]\na=_poly_newton_coefficient(x,y)\nprint(\"Coeficientes del polinomio: (\" , a[0],\" + \",a[1],\"x + \",a[2],\"x^2)  (x-1)\")\n", "meta": {"hexsha": "7851077c498e4e29deb7a7c6ebf9307eda90959f", "size": 2189, "ext": "py", "lang": "Python", "max_stars_repo_path": "Taller3/Punto 1/NewtonMethod.py", "max_stars_repo_name": "adgarciaar/NumericalAnalysis", "max_stars_repo_head_hexsha": "0f1cc6878dfb6c51052ee82298dd1e3512f74fde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Taller3/Punto 1/NewtonMethod.py", "max_issues_repo_name": "adgarciaar/NumericalAnalysis", "max_issues_repo_head_hexsha": "0f1cc6878dfb6c51052ee82298dd1e3512f74fde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Taller3/Punto 1/NewtonMethod.py", "max_forks_repo_name": "adgarciaar/NumericalAnalysis", "max_forks_repo_head_hexsha": "0f1cc6878dfb6c51052ee82298dd1e3512f74fde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8020833333, "max_line_length": 82, "alphanum_fraction": 0.6030150754, "include": true, "reason": "import numpy,from numpy", "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067147399245, "lm_q2_score": 0.9496693666902855, "lm_q1q2_score": 0.8950697548884057}}
{"text": "\"\"\"Lagrange interpolating polynomials in 1D.\"\"\"\nimport sympy as sym\n\ndef Lagrange_polynomial(x, i, points):\n    \"\"\"\n    Return the Lagrange polynomial no. i.\n    points are the interpolation points, and x can be a number or\n    a sympy.Symbol object (for symbolic representation of the\n    polynomial). When x is a sympy.Symbol object, it is\n    normally desirable (for nice output of polynomial expressions)\n    to let points consist of integers or rational numbers in sympy.\n    \"\"\"\n    p = 1\n    for k in range(len(points)):\n        if k != i:\n            p *= (x - points[k])/(points[i] - points[k])\n    return p\n\ndef Lagrange_polynomials_01(x, N):\n    \"\"\"\n    Compute all the Lagrange polynomials (at x) for N+1 equally\n    spaced interpolation points on [0,1]. The polynomials\n    and points, as two separate lists, are returned.\n    Works for symbolic and numerical computation of the\n    polynomials and points (if x is sympy.Symbol, symbolic\n    expressions are made with rational expressions for the\n    points, otherwise floating-point numbers are used).\n    \"\"\"\n    if isinstance(x, sym.Symbol):\n        h = sym.Rational(1, N)\n    else:\n        h = 1.0/N\n    points = [i*h for i in range(N+1)]\n    psi = [Lagrange_polynomial(x, i, points) for i in range(N+1)]\n    return psi, points\n\ndef Chebyshev_nodes(a, b, N):\n    \"\"\"Return N+1 Chebyshev nodes (for interpolation) on [a, b].\"\"\"\n    from math import cos, pi\n    half = 0.5\n    nodes = [0.5*(a+b) + 0.5*(b-a)*cos(float(2*i+1)/(2*(N+1))*pi)\n             for i in range(N+1)]\n    return nodes\n\ndef Lagrange_polynomials(x, N, Omega, point_distribution='uniform'):\n    \"\"\"\n    Compute all the Lagrange polynomials (at x) on an interval\n    Omega. N is the degree of the polynomials.\n    The points are distributed uniformly if point_distribution='uniform',\n    if the value is 'Chebyshev' the Chebyshev nodes are used.\n    If x is sympy.Symbol, rational expressions (in sympy) are used\n    for the points if they are distributed uniformly. Otherwise, the\n    points are floating-point numbers. In this way, the function\n    works for both symbolic and numeric expressions for the\n    Lagrange polynomials.\n    \"\"\"\n    if point_distribution == 'uniform':\n        if isinstance(x, sym.Symbol):\n            h = sym.Rational(Omega[1] - Omega[0], N)\n        else:\n            h = (Omega[1] - Omega[0])/float(N)  # float value\n        points = [Omega[0] + i*h for i in range(N+1)]\n    elif point_distribution == 'Chebyshev':\n        points = Chebyshev_nodes(Omega[0], Omega[1], N)\n    else:\n        raise ValueError('point_distribution=\"%s\": illegal value' %\n                         point_distribution)\n    psi = [Lagrange_polynomial(x, i, points) for i in range(N+1)]\n    return psi, points\n", "meta": {"hexsha": "74ba2a9c08a1514b2703560b1c3572bebf93a6da", "size": 2747, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/.src/book/src/Lagrange.py", "max_stars_repo_name": "hplgit/fem-book", "max_stars_repo_head_hexsha": "c23099715dc3cb72e7f4d37625e6f9614ee5fc4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 86, "max_stars_repo_stars_event_min_datetime": "2015-12-17T12:57:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T01:53:47.000Z", "max_issues_repo_path": "src/Lagrange.py", "max_issues_repo_name": "mbarzegary/finite-element-intro", "max_issues_repo_head_hexsha": "47ef0a3592b823ae71a874ee35850114f16b6d8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-04-16T21:57:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-17T08:09:30.000Z", "max_forks_repo_path": "doc/.src/book/src/Lagrange.py", "max_forks_repo_name": "hplgit/fem-book", "max_forks_repo_head_hexsha": "c23099715dc3cb72e7f4d37625e6f9614ee5fc4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2016-03-11T19:33:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T00:21:57.000Z", "avg_line_length": 39.2428571429, "max_line_length": 73, "alphanum_fraction": 0.6505278486, "include": true, "reason": "import sympy", "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.9504109824587232, "lm_q1q2_score": 0.8949584547605954}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.arange(-5.0, 5.0, 0.1)\n\n##You can adjust the slope and intercept to verify the changes in the graph\ny = 2*(x) + 3\ny_noise = 2 * np.random.normal(size=x.size)\nydata = y + y_noise\n#plt.figure(figsize=(8,6))\nplt.plot(x, ydata,  'bo')\nplt.plot(x,y, 'r')\nplt.ylabel('Dependent Variable')\nplt.xlabel('Independent Variable')\nplt.show()\n\nx = np.arange(-5.0, 5.0, 0.1)\n\n##You can adjust the slope and intercept to verify the changes in the graph\ny = 1*(x**3) + 1*(x**2) + 1*x + 3\ny_noise = 20 * np.random.normal(size=x.size)\nydata = y + y_noise\nplt.plot(x, ydata,  'bo')\nplt.plot(x,y, 'r')\nplt.ylabel('Dependent Variable')\nplt.xlabel('Independent Variable')\nplt.show()\n\nx = np.arange(-5.0, 5.0, 0.1)\n\n##You can adjust the slope and intercept to verify the changes in the graph\n\ny = np.power(x,2)\ny_noise = 2 * np.random.normal(size=x.size)\nydata = y + y_noise\nplt.plot(x, ydata,  'bo')\nplt.plot(x,y, 'r')\nplt.ylabel('Dependent Variable')\nplt.xlabel('Independent Variable')\nplt.show()\n\nX = np.arange(-5.0, 5.0, 0.1)\n\n##You can adjust the slope and intercept to verify the changes in the graph\n\nY= np.exp(X)\n\nplt.plot(X,Y)\nplt.ylabel('Dependent Variable')\nplt.xlabel('Independent Variable')\nplt.show()\n\nX = np.arange(-5.0, 5.0, 0.1)\n\nY = np.log(X)\n\nplt.plot(X,Y)\nplt.ylabel('Dependent Variable')\nplt.xlabel('Independent Variable')\nplt.show()\n\nX = np.arange(-5.0, 5.0, 0.1)\n\n\nY = 1-4/(1+np.power(3, X-2))\n\nplt.plot(X,Y)\nplt.ylabel('Dependent Variable')\nplt.xlabel('Independent Variable')\nplt.show()\n\nimport numpy as np\nimport pandas as pd\n\n# downloading dataset\n#wget -nv -O china_gdp.csv https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%202/data/china_gdp.csv\n\ndf = pd.read_csv(\"china_gdp.csv\")\ndf.head(10)\n\nplt.figure(figsize=(8,5))\nx_data, y_data = (df[\"Year\"].values, df[\"Value\"].values)\nplt.plot(x_data, y_data, 'ro')\nplt.ylabel('GDP')\nplt.xlabel('Year')\nplt.show()\n\nX = np.arange(-5.0, 5.0, 0.1)\nY = 1.0 / (1.0 + np.exp(-X))\n\nplt.plot(X,Y)\nplt.ylabel('Dependent Variable')\nplt.xlabel('Independent Variable')\nplt.show()\n\n\ndef sigmoid(x, Beta_1, Beta_2):\n    y = 1 / (1 + np.exp(-Beta_1 * (x - Beta_2)))\n    return y\n\nbeta_1 = 0.10\nbeta_2 = 1990.0\n\n#logistic function\nY_pred = sigmoid(x_data, beta_1 , beta_2)\n\n#plot initial prediction against datapoints\nplt.plot(x_data, Y_pred*15000000000000.)\nplt.plot(x_data, y_data, 'ro')\n\n# Lets normalize our data\nxdata =x_data/max(x_data)\nydata =y_data/max(y_data)\n\nfrom scipy.optimize import curve_fit\npopt, pcov = curve_fit(sigmoid, xdata, ydata)\n#print the final parameters\nprint(\" beta_1 = %f, beta_2 = %f\" % (popt[0], popt[1]))\n\nx = np.linspace(1960, 2015, 55)\nx = x/max(x)\nplt.figure(figsize=(8,5))\ny = sigmoid(x, *popt)\nplt.plot(xdata, ydata, 'ro', label='data')\nplt.plot(x,y, linewidth=3.0, label='fit')\nplt.legend(loc='best')\nplt.ylabel('GDP')\nplt.xlabel('Year')\nplt.show()\n\n\n", "meta": {"hexsha": "b33c725b3dea9e033c806f908d71bb02716014b2", "size": 2956, "ext": "py", "lang": "Python", "max_stars_repo_path": "non_linear_regression.py", "max_stars_repo_name": "indervirbanipal/machine-learning-with-python", "max_stars_repo_head_hexsha": "1c36e063fb00f11d790d030b04744c41e956ed98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "non_linear_regression.py", "max_issues_repo_name": "indervirbanipal/machine-learning-with-python", "max_issues_repo_head_hexsha": "1c36e063fb00f11d790d030b04744c41e956ed98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "non_linear_regression.py", "max_forks_repo_name": "indervirbanipal/machine-learning-with-python", "max_forks_repo_head_hexsha": "1c36e063fb00f11d790d030b04744c41e956ed98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3939393939, "max_line_length": 177, "alphanum_fraction": 0.6853856563, "include": true, "reason": "import numpy,from scipy", "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517450056273, "lm_q2_score": 0.9149009515124917, "lm_q1q2_score": 0.8948204721341013}}
{"text": "import numpy as np\n\n# Gets the Hermitian matrix G such that Inner(p,q) = [p]*G[q]\ndef constructHermitianG(n):\n\tG = np.zeros((n,n))\n\tfor i in range(n):\n\t\tfor j in range(n):\n\t\t\tif (i+j)%2==0:\n\t\t\t\tG[i][j] = 2.0/(i+j+1.0)\n\treturn G\n\t\n# Get the inner product of the polynomials\ndef innerPolynomials(p,q):\n\tG = constructHermitianG(p.shape[0])\n\tp = p.reshape((1,p.shape[0]))\n\tq = q.reshape((q.shape[0],1))\n\treturn (np.matmul(np.conjugate(p),(np.matmul(G,q))))\n\n# Implementation of Modified GS algorithm to get the matrix for the Orthogonal polynomials\ndef orthogonalizePolynomials(P):\n\n\t# Initialising the Q and R matrices\n\trows = P.shape[0]\n\tcols = P.shape[1]\t\n\tQ = np.zeros((rows,cols))\n\tR = np.zeros((cols,cols))\n\t\n\t# Writing the Modified GS pseudocode\n\tfor i in range(cols):\n\t\tR[i][i] = np.sqrt(innerPolynomials(P[:,i],P[:,i]))\n\t\tQ[:,i] = P[:,i] * 1.0/R[i][i]\n\t\tfor j in range(i+1,cols):\n\t\t\tR[i][j] = innerPolynomials(Q[:,i],P[:,j])\n\t\t\tP[:,j] = P[:,j] - R[i][j] * Q[:,i]\n\treturn Q\n\n# A function to check whether the implementation is correct or not\n# The obtained co-efficients should be multiples of the Legendre Polynomials\ndef checkCorrectness(n):\n\tQ = orthogonalizePolynomials(np.eye(n))\n\tprint(Q)\n\nif __name__=='__main__':\n\tcheckCorrectness(5)\n", "meta": {"hexsha": "23939e5d488ec733cb2ed075ee417fe6c2e65461", "size": 1246, "ext": "py", "lang": "Python", "max_stars_repo_path": "A2/Q6.py", "max_stars_repo_name": "Vedant2311/Numerical-Algorithms-Assignments", "max_stars_repo_head_hexsha": "a3816de42dc97ddbf3916e88367a0e72acf58452", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A2/Q6.py", "max_issues_repo_name": "Vedant2311/Numerical-Algorithms-Assignments", "max_issues_repo_head_hexsha": "a3816de42dc97ddbf3916e88367a0e72acf58452", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A2/Q6.py", "max_forks_repo_name": "Vedant2311/Numerical-Algorithms-Assignments", "max_forks_repo_head_hexsha": "a3816de42dc97ddbf3916e88367a0e72acf58452", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6888888889, "max_line_length": 90, "alphanum_fraction": 0.6597110754, "include": true, "reason": "import numpy", "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543365, "lm_q2_score": 0.9284087965937712, "lm_q1q2_score": 0.8947817761838811}}
{"text": "\"\"\"\r\nCreated on May 17, 2020.\r\nHomography\r\n\r\n@authors:\r\nSoroosh Tayebi Arasteh <soroosh.arasteh@fau.de> https://github.com/tayebiarasteh/\r\nAmin Heydarshahi <amin.heydarshahi@fau.de> https://github.com/aminheydarshahi/\r\n\"\"\"\r\nimport numpy as np\r\nimport cv2\r\nimport pdb\r\n\r\n\r\ndef computeHomography(points1, points2):\r\n    '''\r\n    Compute a homography matrix from 4 point matches.\r\n\r\n    :points1: list of 4 points (tuple)\r\n    :points2: list of 4 points (tuple)\r\n    '''\r\n    assert(len(points1) == 4)\r\n    assert(len(points2) == 4)\r\n\r\n    # 8x9 matrix A based on the formula from the manual sheet.\r\n    A = np.zeros((8,9))\r\n    for i in range(len(points1)):\r\n        A[i*2:i*2 +2] = np.array([[-points1[i][0], -points1[i][1], -1, 0,0,0,\r\n                                   points1[i][0]*points2[i][0], points1[i][1]*points2[i][0], points2[i][0]],\r\n                          [0,0,0, -points1[i][0], -points1[i][1], -1,\r\n                           points1[i][0]*points2[i][1], points1[i][1]*points2[i][1], points2[i][1]]])\r\n\r\n    # SVD decomposition on A\r\n    U, s, V_transposed = np.linalg.svd(A, full_matrices=True)\r\n    V = np.transpose(V_transposed)\r\n\r\n    # homogeneous solution of Ah=0 as the rightmost column vector of V.\r\n    H = V[:,-1].reshape(3,3)\r\n\r\n    # Normalize H by 1/h8.\r\n    H /= V[:,-1][-1]\r\n\r\n    return H\r\n\r\n\r\n\r\ndef testHomography():\r\n    '''\r\n    A small test to validate the implementation of computeHomography().\r\n    '''\r\n    points1 = [(1, 1), (3, 7), (2, -5), (10, 11)]\r\n    points2 = [(25, 156), (51, -83), (-144, 5), (345, 15)]\r\n\r\n    H = computeHomography(points1, points2)\r\n\r\n    print (\"Testing Homography...\")\r\n    print (\"Your result:\" + str(H))\r\n\r\n    Href = np.array([[-151.2372466105457,   36.67990057507507,   130.7447340624461],\r\n                 [-27.31264543681857,   10.22762978292494,   118.0943169422209],\r\n                 [-0.04233528054472634, -0.3101691983762523, 1]])\r\n\r\n    print (\"Reference: \" + str(Href))\r\n\r\n    error = Href - H\r\n    e   = np.linalg.norm(error)\r\n    print (\"Error: \" + str(e))\r\n\r\n    if (e < 1e-10):\r\n        print (\"Test: SUCCESS!\")\r\n    else:\r\n        print (\"Test: FAIL!\")\r\n    print (\"============================\")\r\n", "meta": {"hexsha": "bc81db777f658b459c169f25ec8f366791ed36ea", "size": 2188, "ext": "py", "lang": "Python", "max_stars_repo_path": "Panorama Stitching/src/homography.py", "max_stars_repo_name": "starasteh/cv_course", "max_stars_repo_head_hexsha": "83ff6efed21484dcaeca380e86ce9be86dcbb3b9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-29T20:20:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-20T18:31:41.000Z", "max_issues_repo_path": "Panorama Stitching/src/homography.py", "max_issues_repo_name": "tayebiarasteh/cv_course", "max_issues_repo_head_hexsha": "83ff6efed21484dcaeca380e86ce9be86dcbb3b9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Panorama Stitching/src/homography.py", "max_forks_repo_name": "tayebiarasteh/cv_course", "max_forks_repo_head_hexsha": "83ff6efed21484dcaeca380e86ce9be86dcbb3b9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-18T22:46:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-18T22:46:37.000Z", "avg_line_length": 29.9726027397, "max_line_length": 109, "alphanum_fraction": 0.5466179159, "include": true, "reason": "import numpy", "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244552, "lm_q2_score": 0.9263037318197961, "lm_q1q2_score": 0.8947163784072879}}
{"text": "from sympy import *\ninit_printing(pretty_print=true)\nx = Symbol('x')\n\n\ndef h(a, b, n):\n    resultado = (b - a) / n\n    return resultado\n\n\ndef f(x):\n    return exp(x)\n\n\ndef aplicando_h(a, b, h):\n    lista = [a]\n    elemento = 0\n    while True:\n        if elemento < b:\n            elemento = lista[-1] + h\n            lista.append(elemento)\n        else:\n            break\n    return lista\n\n\ndef aplicando_x(lista_x):\n    lista_x_aplicado = []\n    for c in lista_x:\n        elemento = f(c)\n        lista_x_aplicado.append(elemento)\n    return lista_x_aplicado\n\n\ndef trapezios(y, h, subintervalos):\n    soma_trapezios = 0\n    for c in range(0, subintervalos):\n        soma_trapezios += ((y[c] + y[c + 1]) * (h/2))\n    return soma_trapezios\n\n\ndef erro(valor_real, valor_soma):\n    erro = valor_soma - valor_real\n    return erro\n\n\n# Para 1 subintervalo:\nh_1 = h(1, 4, 1)\nintegral = Integral(exp(x), (x, 1, 4)).doit().evalf()\nvalores_x_h1 = aplicando_h(1, 4, h_1)\nvalores_x_h1_aplicados = aplicando_x(valores_x_h1)\ntrapezios_h_1 = trapezios(valores_x_h1_aplicados, h_1, 1).evalf()\nerro_h1 = erro(integral, trapezios_h_1)\nporcentagem_erro_h1 = (erro_h1 / integral) * 100\n\n# Para 4 subintervalo:\nh_4 = h(1, 4, 4)\nvalores_x_h4 = aplicando_h(1, 4, h_4)\nvalores_x_h4_aplicados = aplicando_x(valores_x_h4)\ntrapezios_h_4 = trapezios(valores_x_h4_aplicados, h_4, 4).evalf()\nerro_h4 = erro(integral, trapezios_h_4)\nporcentagem_erro_h4 = (erro_h4 / integral) * 100\n\n# Para 10 subintervalo:\nh_10 = h(1, 4, 10)\nvalores_x_h10 = aplicando_h(1, 4, h_10)\nvalores_x_h10_aplicados = aplicando_x(valores_x_h10)\ntrapezios_h_10 = trapezios(valores_x_h10_aplicados, h_10, 10).evalf()\nerro_h10 = erro(integral, trapezios_h_10)\nporcentagem_erro_h10 = (erro_h10 / integral) * 100\n\n# Para 100 subintervalo:\nh_100 = h(1, 4, 100)\nvalores_x_h100 = aplicando_h(1, 4, h_100)\nvalores_x_h100_aplicados = aplicando_x(valores_x_h100)\ntrapezios_h_100 = trapezios(valores_x_h100_aplicados, h_100, 100).evalf()\nerro_h100 = erro(integral, trapezios_h_100)\nporcentagem_erro_h100 = (erro_h100 / integral) * 100\n\nprint('Para 1 subintervalo: ')\nprint('-' * 30)\nprint(f'Soma dos trapézios = {trapezios_h_1:.3f}')\nprint(f'Integral = {integral:.3f}')\nprint(f'Erro = {erro_h1:.3f}')\nprint(f'Porcentagem do erro = {porcentagem_erro_h1:.3f}%')\nprint('-' * 30)\nprint('Para 4 subintervalos: ')\nprint('-' * 30)\nprint(f'Soma dos trapézios = {trapezios_h_4:.3f}')\nprint(f'Erro = {erro_h4:.3f}')\nprint(f'Porcentagem do erro = {porcentagem_erro_h4:.3f}%')\nprint('-' * 30)\nprint('Para 10 subintervalos: ')\nprint('-' * 30)\nprint(f'Soma dos trapézios = {trapezios_h_10:.3f}')\nprint(f'Erro = {erro_h10:.3f}')\nprint(f'Porcentagem do erro = {porcentagem_erro_h10:.3f}%')\nprint('-' * 30)\nprint('Para 100 subintervalos: ')\nprint('-' * 30)\nprint(f'Soma dos trapézios = {trapezios_h_100:.3f}')\nprint(f'Erro = {erro_h100:.3f}')\nprint(f'Porcentagem do erro = {porcentagem_erro_h100:.3f}%')\n", "meta": {"hexsha": "0e7d8a2e6518588b24f54b544b58fdb2db3d73a4", "size": 2917, "ext": "py", "lang": "Python", "max_stars_repo_path": "Questao_04/Trapezios.py", "max_stars_repo_name": "VictorBenoiston/Terceiro_trabalho_calculo_numerico", "max_stars_repo_head_hexsha": "7d005e3494aaa4f1547b34b4bec1ea7539a35334", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Questao_04/Trapezios.py", "max_issues_repo_name": "VictorBenoiston/Terceiro_trabalho_calculo_numerico", "max_issues_repo_head_hexsha": "7d005e3494aaa4f1547b34b4bec1ea7539a35334", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Questao_04/Trapezios.py", "max_forks_repo_name": "VictorBenoiston/Terceiro_trabalho_calculo_numerico", "max_forks_repo_head_hexsha": "7d005e3494aaa4f1547b34b4bec1ea7539a35334", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0480769231, "max_line_length": 73, "alphanum_fraction": 0.6914638327, "include": true, "reason": "from sympy", "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862455, "lm_q2_score": 0.9304582526016021, "lm_q1q2_score": 0.8946670688432545}}
{"text": "#python3\n#plot logistic map equation\n#logistic map equation:  x := r*x*(1-x)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Logistic function implementation\ndef logistic_eq(r,x):\n    return r*x*(1-x)\n    #return r*x*(1-x)**2\n\ndef showLogisticMap():\n    # Show the logistic function\n    x = np.linspace(0, 1)\n    plt.plot(x, logistic_eq(2, x), 'k')\n    plt.show()\n\n# Iterate the function for a given r\ndef logistic_equation_orbit(seed, r, n_iter, n_skip=0):\n    print('Orbit for seed {0}, growth rate of {1}, plotting {2} iterations after skipping {3}'.format(seed, r, n_iter, n_skip))\n    X_t=[]\n    T=[]\n    t=0\n    x = seed\n    # Iterate the logistic equation, printing only if n_skip steps have been skipped\n    for i in range(n_iter + n_skip):\n        if i >= n_skip:\n            X_t.append(x)\n            T.append(t)\n            t+=1\n        x = logistic_eq(r,x)\n    # Configure and decorate the plot\n    plt.plot(T, X_t)\n    plt.ylim(0, 1)\n    plt.xlim(0, T[-1])\n    plt.xlabel('Time t')\n    plt.ylabel('X_t')\n    plt.show()\n\n# Create the bifurcation diagram\ndef bifurcation_diagram(seed, n_skip, n_iter, step=0.0001, r_min=0):\n    print(\"Starting with x0 seed {0}, skip plotting first {1} iterations, then plot next {2} iterations.\".format(seed, n_skip, n_iter))\n    # Array of r values, the x axis of the bifurcation plot\n    R = []\n    # Array of x_t values, the y axis of the bifurcation plot\n    X = []\n\n    # Create the r values to loop. For each r value we will plot n_iter points\n    r_range = np.linspace(r_min, 4, int(1/step))\n\n    for r in r_range:\n        x = seed\n        # For each r, iterate the logistic function and collect datapoint if n_skip iterations have occurred\n        for i in range(n_iter+n_skip+1):\n            if i >= n_skip:\n                R.append(r)\n                X.append(x)\n\n            x = logistic_eq(r,x)\n    # Plot the data\n    plt.plot(R, X, ls='', marker=',')\n    plt.ylim(0, 1)\n    plt.xlim(r_min, 4)\n    plt.xlabel('r')\n    plt.ylabel('X')\n    plt.show()\n\ndef main():\n    #logistic_equation_orbit(0.1, 3.05, 100)\n    #logistic_equation_orbit(0.1, 3.9, 100)\n    #logistic_equation_orbit(0.1, 3.0, 100)\n\n    #bifurcation_diagram(0.2, 100, 5)\n    bifurcation_diagram(0.2, 100, 10)\n    #bifurcation_diagram(0.1, 100, 1000)\n\n\nif __name__=='__main__':\n    main()\n", "meta": {"hexsha": "b2db20e2e4d756bc09d333fbb00cc446e54e5fbc", "size": 2316, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/fractal/plotLogisticMap.py", "max_stars_repo_name": "StevenHuang2020/ML", "max_stars_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fractal/plotLogisticMap.py", "max_issues_repo_name": "StevenHuang2020/ML", "max_issues_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fractal/plotLogisticMap.py", "max_forks_repo_name": "StevenHuang2020/ML", "max_forks_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5925925926, "max_line_length": 135, "alphanum_fraction": 0.6178756477, "include": true, "reason": "import numpy", "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748207, "lm_q2_score": 0.9304582569404568, "lm_q1q2_score": 0.8946670678870594}}
{"text": "import numpy as np\nimport matplotlib.pylab as plt\nimport scipy\nimport scipy.linalg\nimport sys\n\ndef lu_decomposition(A):\n    m, n = A.shape\n\n    LU = np.copy(A)\n    pivots = np.empty(n, dtype=int)\n    # initialise the pivot row and column\n    h = 0\n    k = 0\n    while h < m and k < n:\n        # Find the k-th pivot:\n        pivots[k] = np.argmax(LU[h:, k]) + h\n        if LU[pivots[k], k] == 0:\n            # No pivot in this column, pass to next column\n            k = k+1\n        else:\n            # swap rows\n            LU[[h, pivots[k]], :] = LU[[pivots[k], h], :]\n            # Do for all rows below pivot:\n            for i in range(h+1, m):\n                f = LU[i, k] / LU[h, k]\n                # Store f as the new L column values\n                LU[i, k] = f\n                # Do for all remaining elements in current row:\n                for j in range(k + 1, n):\n                    LU[i, j] = LU[i, j] - LU[h, j] * f\n            # Increase pivot row and column\n            h = h + 1\n            k = k + 1\n    return LU, pivots\n\ndef random_matrix(n):\n    R = np.random.rand(n, n)\n    A = np.zeros((n, n))\n    triu = np.triu_indices(n)\n    A[triu] = R[triu]\n    return A\n\ndef random_non_singular_matrix(n):\n    A = np.random.rand(n, n)\n    while np.linalg.cond(A) > 1/sys.float_info.epsilon:\n        A = np.random.rand(n, n)\n    return A\n\nAs = [\n    np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]),\n    random_non_singular_matrix(3),\n    random_non_singular_matrix(4),\n    random_non_singular_matrix(5),\n    random_non_singular_matrix(6),\n]\n\ndef pivots_to_row_indices(pivots):\n    n = len(pivots)\n    indices = np.array(range(0, n))\n    for i, p in enumerate(pivots):\n        indices[i], indices[p] = indices[p], indices[i]\n    return indices\n\ndef calculate_L_mult_U(LU):\n    L = np.tril(LU)\n    np.fill_diagonal(L, 1)\n    U = np.triu(LU)\n    return L @ U\n\nfor A in As:\n    LU_scipy, pivots_scipy = scipy.linalg.lu_factor(A)\n    row_indices_scipy = pivots_to_row_indices(pivots_scipy)\n    LU_mine, pivots_mine = lu_decomposition(A)\n    row_indices_mine = pivots_to_row_indices(pivots_mine)\n\n    np.testing.assert_almost_equal(calculate_L_mult_U(LU_scipy),  A[row_indices_scipy])\n    np.testing.assert_almost_equal(calculate_L_mult_U(LU_mine),  A[row_indices_mine])\n\n", "meta": {"hexsha": "95d836ac3c3c58f2dd3467844a574bfa0e2463ed", "size": 2275, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/unit_1_3.py", "max_stars_repo_name": "tommylees112/scientific-computing", "max_stars_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-02-03T02:10:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T13:21:47.000Z", "max_issues_repo_path": "src/unit_1_3.py", "max_issues_repo_name": "tommylees112/scientific-computing", "max_issues_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-01T16:00:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T17:09:17.000Z", "max_forks_repo_path": "src/unit_1_3.py", "max_forks_repo_name": "tommylees112/scientific-computing", "max_forks_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-02-01T15:45:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T12:20:25.000Z", "avg_line_length": 28.4375, "max_line_length": 87, "alphanum_fraction": 0.578021978, "include": true, "reason": "import numpy,import scipy", "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307676766118, "lm_q2_score": 0.9196425394367774, "lm_q1q2_score": 0.894656557628349}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n''' basic example '''\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import interpolate\n\nx = np.arange(0,10)\ny = np.exp(-x/3.0)\nf = interpolate.interp1d(x, y, fill_value='extrapolate')\n\nprint (f(9))\nprint (f(15)) # extrapolated value got here\n\n\nimport numpy as np\nimport scipy.interpolate as interpolate\n\n'''\nExtrapolation is the process of \nfinding a value outside two points \non a line or a curve.\n'''\n\nkinds = ('nearest', \n         'zero', \n         'linear', \n         'slinear', \n         'quadratic', \n         'cubic')\n\n''' x- axis values '''\nx = np.array([0.0,1.0,2.0,3.0,\n              4.0,5.0,6.0,7.0,\n              8.0,9.0])\n\n''' y- axis values '''\ny = np.array([10,5,39,3,6,9,41,73,57,88])\n\n''' plot original values '''\nplt.plot(x, y, 'o')\n\n''' new x-axis values to be interpolated '''\nnew_x = np.linspace(0.0, 19.0, 25)\n\n''' extrapolation for kind = 'nearest' '''\nnew_y = interpolate.interp1d(x,y,kind='nearest',fill_value='extrapolate')(new_x)\nplt.plot(new_x, new_y, color='C1', linewidth=1)\n\n''' extrapolation for kind = 'zero' does not work and not applicable '''\n#new_y = interpolate.interp1d(x,y,kind='zero',fill_value='extrapolate')(new_x)\n#plt.plot(new_x, new_y, color='C2', linewidth=1)\n\n''' extrapolation for kind = 'linear' '''\nnew_y = interpolate.interp1d(x,y,kind='linear',fill_value='extrapolate')(new_x)\nplt.plot(new_x, new_y, color='C3', linewidth=1)\n\n''' extrapolation for kind = 'slinear' does not work and not applicable '''\n#new_y = interpolate.interp1d(x,y,kind='slinear',fill_value='extrapolate')(new_x)\n#plt.plot(new_x, new_y, color='C4', linewidth=1)\n\n''' extrapolation for kind = 'cubic' does not work and not applicable '''\n#new_y = interpolate.interp1d(x,y,kind='cubic',fill_value='extrapolate')(new_x)\n#plt.plot(new_x, new_y, color='C5', linewidth=1)\n\nplt.legend(['original','nearest','linear'])\nplt.show()\n\n\n\n''' Extrapolation using InterpolatedUnivariateSpline and custom order type '''\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.interpolate import InterpolatedUnivariateSpline\n\n# given values\nxi = np.array([0.2, 0.5, 0.7, 0.9])\nyi = np.array([0.3, 0.1, 0.2, 0.1])\n# expand x values\nx = np.linspace(0, 1.5, 50)\n# spline order: 1=linear, 2=quadratic, 3=cubic ... \norder = 1\n# do inter/extrapolation\ns = InterpolatedUnivariateSpline(xi, yi, k=order)\ny = s(x)\n\n# example showing the interpolation for following kind\n# linear, quadratic and cubic interpolation\n#plt.figure()\nplt.plot(xi, yi)\n\n\nfor order_new in range(1, 4):\n    s = InterpolatedUnivariateSpline(xi, yi, k=order_new)\n    y = s(x)\n    plt.plot(x, y)\nplt.legend(['linear','quadratic','cubic'])\nplt.show()\n\n", "meta": {"hexsha": "2a47a053a2ff0ce30aa89924be7acea2ab61f4d6", "size": 2691, "ext": "py", "lang": "Python", "max_stars_repo_path": "prg05_scipy/scipy03_extrapolation.py", "max_stars_repo_name": "imademethink/MachineLearning_related_Python", "max_stars_repo_head_hexsha": "c7fd22d2d878d110e0a7bf679103a226952164e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prg05_scipy/scipy03_extrapolation.py", "max_issues_repo_name": "imademethink/MachineLearning_related_Python", "max_issues_repo_head_hexsha": "c7fd22d2d878d110e0a7bf679103a226952164e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prg05_scipy/scipy03_extrapolation.py", "max_forks_repo_name": "imademethink/MachineLearning_related_Python", "max_forks_repo_head_hexsha": "c7fd22d2d878d110e0a7bf679103a226952164e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3823529412, "max_line_length": 81, "alphanum_fraction": 0.6700111483, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611643025386, "lm_q2_score": 0.931462509346239, "lm_q1q2_score": 0.8945404199799183}}
{"text": "import numpy as np\nfrom numpy.linalg import inv\nimport matplotlib.pyplot as plt\n\nx = np.matrix([74.4, 93.4, 110.4, 130.6, 148.9, 170.7, 191.1, 211.8, 231.7, 259.1]).transpose()\ny = np.matrix([1.64, 2.03, 3.16, 3.96, 4.78, 6.21, 7.28, 8.91, 8.79, 8.63]).transpose()\n\nx_log10 = np.log10(x)\nA = np.concatenate((np.matrix(np.ones(x.shape[0])).transpose(), x_log10), axis=1)\nb = np.log10(y)\n\nbetas = inv(A.transpose() * A) * A.transpose() * b\n\ny_log_fit = A * betas\n\nplt.figure(figsize=(10,8))\nplt.plot(np.array(x_log10), np.array(b), \"ro\", markersize=8)\nplt.plot(np.array(x_log10), np.array(y_log_fit), \"b\", linewidth=2)\nplt.xlabel(\"$\\log_{10}x$ (kg)\", fontsize=24)\nplt.ylabel(\"$\\log_{10}y$ (kg)\", fontsize=24)\nplt.xticks(fontsize=20)\nplt.yticks(fontsize=20)\nplt.legend([\"Data\", \"Best fit, $\\log_{10}y = %.3f + %.3f\\log_{10}x$\" % (betas.item((0, 0)), betas.item((1, 0)))], loc=\"upper left\", fontsize=20)\nplt.savefig(\"problem_1_log_fit.eps\", format=\"eps\", dpi=1000)\nplt.show()\n\nprint betas.item((1, 0))\n\ny_fit = np.power(10, betas.item((0, 0))) * np.power(x, betas.item((1, 0)))\n\nplt.figure(figsize=(10,8))\nplt.plot(np.array(x), np.array(y), \"ro\", markersize=8)\nplt.plot(np.array(x), np.array(y_fit), \"b\", linewidth=2)\nplt.xlabel(\"$x$ (kg)\", fontsize=24)\nplt.ylabel(\"$y$ (kg)\", fontsize=24)\nplt.xticks(fontsize=20)\nplt.yticks(fontsize=20)\nplt.legend([\"Data\", \"Best fit, $y = %.3f * x ^ {%.3f}$\" % (np.power(10, betas.item((0, 0))), betas.item((1, 0)))], loc=\"upper left\", fontsize=20)\nplt.savefig(\"problem_1_fit.eps\", format=\"eps\", dpi=1000)\nplt.show()\n", "meta": {"hexsha": "578f8d6b92bb272f821cc61b3a43e87e691a20bf", "size": 1548, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/problem_1.py", "max_stars_repo_name": "haojunsui/PSU-MATH-450-Mathematical-Modeling", "max_stars_repo_head_hexsha": "a391f8a0aafe08df8fdff241f316e9f652655c99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/problem_1.py", "max_issues_repo_name": "haojunsui/PSU-MATH-450-Mathematical-Modeling", "max_issues_repo_head_hexsha": "a391f8a0aafe08df8fdff241f316e9f652655c99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/problem_1.py", "max_forks_repo_name": "haojunsui/PSU-MATH-450-Mathematical-Modeling", "max_forks_repo_head_hexsha": "a391f8a0aafe08df8fdff241f316e9f652655c99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.756097561, "max_line_length": 145, "alphanum_fraction": 0.6434108527, "include": true, "reason": "import numpy,from numpy", "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138151101525, "lm_q2_score": 0.9149009491921664, "lm_q1q2_score": 0.8945112974825729}}
{"text": "import numpy as np\n\ndef interp(P0,P1,t):\n    return (1-t)*P0+t*P1\n\ndef deCasteljau(P:np.array,t:float)->np.array:\n    n=P.shape[1]\n    if n==1:\n        return P\n    else:\n        nP=np.zeros((P.shape[0],n-1))\n        for i in range(n-1):\n            nP[:,i]=interp(P[:,i],P[:,i+1],t)\n        return deCasteljau(nP,t)\n\ndef B(i:int,t:float)->float:\n    if i==0:\n        return (1-t)**3\n    elif i==1:\n        return 3*(1-t)**2*t\n    elif i==2:\n        return 3*(1-t)*t**2\n    elif i==3:\n        return t**3\n\ndef bezier(P:np.array,t:float)->np.array:\n    return (P[:,0]*B(0,t)+\n            P[:,1]*B(1,t)+\n            P[:,2]*B(2,t)+\n            P[:,3]*B(3,t))\n\ndef flatness(P:np.array)->float:\n    \"\"\"\n    Calculate the flatness of a given curve\n    From https://www.joshondesign.com/2018/07/11/bezier-curves and\n    https://hcklbrrfnn.wordpress.com/2012/08/20/piecewise-linear-approximation-of-bezier-curves/\n\n    \"\"\"\n    u=(3*P[:,1]-2*P[:,0]-P[:,3])**2\n    v=(3*P[:,2]-2*P[:,3]-P[:,0])**2\n    w=np.where(u<v)\n    u[w]=v[w]\n    return np.sum(u)\n\ndef split(P:np.array,t:float)->tuple:\n    p01=interp(P[:,0],P[:,1],t)\n    p12=interp(P[:,1],P[:,2],t)\n    p23=interp(P[:,2],P[:,3],t)\n    p012=interp(p01,p12,t)\n    p123=interp(p12,p23,t)\n    p0123=interp(p012,p123,t)\n    return (np.hstack((P[:,0],p01,p012,p0123)),np.hstack((p0123,p123,p23,P[:,1])))\n\ndef flatten(P:np.array,tol:float=1)->np.array:\n    \"\"\"\n    Return a polyline which approximates the given cubic Bezier curve to within\n    the given tolerance\n    \"\"\"\n    if flatness(P)<tol:\n        return np.hstack((P[:,0],P[:,3]))\n    else:\n        P0,P1=split(P,0.5)\n        return np.hstack((flatten(P0,tol),flatten(P1,tol)))\n\ndef arc_l90(theta:float)->np.array:\n    \"\"\"\n    Create a cubic Bezier curve which approximates a circular arc. Based on\n    https://pomax.github.io/bezierinfo/#circles_cubic .\n\n    :param theta: Angle of arc. The arc start on the +X axis and grows towards +Y. The math works up to\n    180deg, but the approximation is noticeably worse, so we recommend only\n    using this up to 90deg. At this angle, the maximum error between an actual circle and this curve\n    is 2.7e-4 (2.7 unit error on a circle with radius 10,000 units).\n    :return: Control points for a single Bezier curve which approximates the arc, in the form of a 2-row, 4-column\n             numpy array.\n    \"\"\"\n    k=4*np.tan(theta/4)/3\n    c=np.cos(theta)\n    s=np.sin(theta)\n    result=np.zeros((2,4))\n    result[:,0]=(1,0)\n    result[:,1]=(1,k)\n    result[:,2]=(c+k*s,s-k*c)\n    result[:,3]=(c,s)\n    return result\n\n", "meta": {"hexsha": "2daf7e7de34c17fc0d90dfe28ffadb35a99c235f", "size": 2560, "ext": "py", "lang": "Python", "max_stars_repo_path": "kwanmath/bezier.py", "max_stars_repo_name": "kwan3217/kwanmath", "max_stars_repo_head_hexsha": "c43f8209324cdb0c673b969b41b06d49c9d46e71", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kwanmath/bezier.py", "max_issues_repo_name": "kwan3217/kwanmath", "max_issues_repo_head_hexsha": "c43f8209324cdb0c673b969b41b06d49c9d46e71", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kwanmath/bezier.py", "max_forks_repo_name": "kwan3217/kwanmath", "max_forks_repo_head_hexsha": "c43f8209324cdb0c673b969b41b06d49c9d46e71", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4252873563, "max_line_length": 114, "alphanum_fraction": 0.580859375, "include": true, "reason": "import numpy", "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399069145609, "lm_q2_score": 0.921921830028282, "lm_q1q2_score": 0.8944853505491419}}
{"text": "'''\nAuthor: jianzhnie\nDate: 2021-12-22 09:44:16\nLastEditTime: 2021-12-22 09:46:32\nLastEditors: jianzhnie\nDescription:\n\n'''\n\nimport numpy as np\n\n\ndef softmax_(x):\n    exp_x = np.exp(x)\n    softmax_x = exp_x / np.sum(exp_x)\n    return softmax_x\n\n\ndef softmax(x):\n    x = x - np.max(x)\n    exp_x = np.exp(x)\n    softmax_x = exp_x / np.sum(exp_x)\n    return softmax_x\n", "meta": {"hexsha": "bfdd648933b71cd5afb04e39c262033a0b415323", "size": 364, "ext": "py", "lang": "Python", "max_stars_repo_path": "leetcode/ai_algorithms/softmax.py", "max_stars_repo_name": "jianzhnie/machine_learning_notes", "max_stars_repo_head_hexsha": "edb6a88e540046d1cde9ffd6b23fc797f9c65258", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-11-18T04:19:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T02:53:31.000Z", "max_issues_repo_path": "leetcode/ai_algorithms/softmax.py", "max_issues_repo_name": "jianzhnie/machine_learning_notes", "max_issues_repo_head_hexsha": "edb6a88e540046d1cde9ffd6b23fc797f9c65258", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "leetcode/ai_algorithms/softmax.py", "max_forks_repo_name": "jianzhnie/machine_learning_notes", "max_forks_repo_head_hexsha": "edb6a88e540046d1cde9ffd6b23fc797f9c65258", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.1666666667, "max_line_length": 37, "alphanum_fraction": 0.6483516484, "include": true, "reason": "import numpy", "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561721629776, "lm_q2_score": 0.9230391658917939, "lm_q1q2_score": 0.8942921930224311}}
{"text": "import numpy as np\n\n# equivalent to MATLAB sph2cart & cart2sph\ndef cart2sph(x,y,z):\n    azimuth = np.arctan2(y,x)\n    elevation = np.arctan2(z,np.sqrt(x**2 + y**2))\n    r = np.sqrt(x**2 + y**2 + z**2)\n    return azimuth, elevation, r\n\ndef sph2cart(azimuth,elevation,r):\n    x = r * np.cos(elevation) * np.cos(azimuth)\n    y = r * np.cos(elevation) * np.sin(azimuth)\n    z = r * np.sin(elevation)\n    return x, y, z\n\n# get the angular distances from a single point to a list of points\ndef getDistances(p_az, p_el, grid_az, grid_el, input_format='deg', return_format='rad'):\n\n    if input_format == 'deg':\n        p_az = p_az * np.pi / 180\n        p_el = p_el * np.pi / 180\n        grid_az = grid_az * np.pi / 180\n        grid_el = grid_el * np.pi / 180\n\n    x1, y1, z1 = sph2cart(p_az, p_el, 1);\n    x2, y2, z2 = sph2cart(grid_az, grid_el, 1);\n\n    # make the single point value a matrix with same dimensions as the grid\n    x1 = x1 * np.ones_like(x2)\n    y1 = y1 * np.ones_like(z2)\n    z1 = z1 * np.ones_like(z2)\n\n    dotProduct = np.einsum('ji,ji->i', [x1, y1, z1], [x2, y2, z2])\n\n    distances = np.arccos(np.clip(dotProduct, -1.0, 1.0));\n\n    if return_format == 'deg':\n        distances = distances * 180 / np.pi\n\n    return distances\n\n# get the angular distance from one point to another\ndef angularDistance(az1, el1, az2, el2, input_format='deg', return_format='deg'):\n\n\n    if input_format == 'deg':\n        az1 = az1 * np.pi / 180\n        az2 = az2 * np.pi / 180\n        el1 = el1 * np.pi / 180\n        el2 = el2 * np.pi / 180\n\n    x1, y1, z1 = sph2cart(az1, el1, 1);\n    x2, y2, z2 = sph2cart(az2, el2, 1);\n\n    # distance = np.arctan2(np.linalg.norm(np.cross(xyz1, xyz2)), np.dot(xyz1, xyz2)) / 180;\n    distance = np.arccos(np.clip(np.dot([x1, y1, z1], [x2, y2, z2]), -1.0, 1.0));\n    # distance = np.arccos(np.clip(0.5, -1.0, 1.0)) / np.pi;\n\n    if return_format == 'deg':\n        distance = distance * 180 / np.pi\n\n    return distance", "meta": {"hexsha": "08a958d967ad0d0b942fad4f75c1a2410f1610af", "size": 1947, "ext": "py", "lang": "Python", "max_stars_repo_path": "grid_improving/angular_distance.py", "max_stars_repo_name": "dcbau/FreeGrid", "max_stars_repo_head_hexsha": "f9d72bbaa92b5da3d9c7d480981f6aedd559ecce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-09-08T15:57:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T06:11:00.000Z", "max_issues_repo_path": "grid_improving/angular_distance.py", "max_issues_repo_name": "dcbau/GuidedHRTFsPython", "max_issues_repo_head_hexsha": "75a4754fc2bdc2e05e682b7fcac017d05f9c3185", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid_improving/angular_distance.py", "max_forks_repo_name": "dcbau/GuidedHRTFsPython", "max_forks_repo_head_hexsha": "75a4754fc2bdc2e05e682b7fcac017d05f9c3185", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4032258065, "max_line_length": 92, "alphanum_fraction": 0.5952747817, "include": true, "reason": "import numpy", "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9814534344029238, "lm_q2_score": 0.9111796997610797, "lm_q1q2_score": 0.8942804456887367}}
{"text": "## Tools for solving differential equations. Also includes a solver for quadratic\n## equations and a simple implementation of the bisection method. \n\nimport numpy as np\n\ndef fe(f, t0, y0, h, N):\n    \"\"\"\"Solve IVP given by y' = f(t, y), y(t_0) = y_0 with step size h > 0, for N steps,\n    using the Forward-Euler method.\n    Also works if y is an n-vector and f is a vector-valued function.\"\"\"\n    t = t0 + np.array([i * h for i in range(N+1)])\n    m = len(y0)\n    y = np.zeros((N+1, m))\n    y[0] = y0\n\n    # Repeatedly approximate next value.\n    for n in range(N):\n        y[n+1] = y[n] + h*f(t[n], y[n])\n    return t, y\n\ndef rk4(f, t0, y0, h, N):\n    \"\"\"\"Solve IVP given by y' = f(t, y), y(t_0) = y_0 with step size h > 0, for N steps,\n    using the Runge-Kutta 4 method.\n    Also works if y is an n-vector and f is a vector-valued function.\"\"\"\n    t = t0 + np.array([i * h for i in range(N+1)])\n    m = len(y0)\n    y = np.zeros((N+1, m))\n    y[0] = y0\n\n    # Repeatedly approximate next value.\n    for n in range(N):\n        k1 = f(t[n], y[n])\n        k2 = f(t[n] + h/2, y[n] + k1 * h/2)\n        k3 = f(t[n] + h/2, y[n] + k2 * h/2)\n        k4 = f(t[n] + h, y[n] + k3 * h)\n        y[n+1] = y[n] + h * (k1 + 2 * k2 + 2 * k3 + k4) / 6\n\n    return t, y\n\ndef solve_quadratic(a, b, c):\n    \"\"\"Returns the two solutions of the quadratic equation ax^2 + bx + c = 0.\"\"\"\n    D = b ** 2 - 4 * a * c\n    assert D >= 0\n    return (-b + np.sqrt(D)) / (2 * a), (-b - np.sqrt(D)) / (2 * a)\n\ndef bisect(f, x_low, x_high, n):\n    \"\"\"Apply bisection method n times to function f.\"\"\"\n    s = np.sign(f(x_low))\n    t = np.sign(f(x_high))\n    assert s != t\n\n    for _ in range(n):\n        x = (x_low + x_high) / 2\n        y = f(x)\n        if y == 0:\n            return x\n        elif np.sign(y) == s:\n            x_low = x\n        else:\n            x_high = x\n    return (x_low + x_high) / 2\n", "meta": {"hexsha": "de1e5a64927a9bdf047256dabffca8f2e88c397e", "size": 1873, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/tools.py", "max_stars_repo_name": "MarkBebawy/PCS", "max_stars_repo_head_hexsha": "0092636cce915c0e6b82aba6b0a4a80963d1e9a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-30T17:06:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-30T17:06:03.000Z", "max_issues_repo_path": "code/tools.py", "max_issues_repo_name": "MarkBebawy/PCS", "max_issues_repo_head_hexsha": "0092636cce915c0e6b82aba6b0a4a80963d1e9a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/tools.py", "max_forks_repo_name": "MarkBebawy/PCS", "max_forks_repo_head_hexsha": "0092636cce915c0e6b82aba6b0a4a80963d1e9a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-29T14:14:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-29T14:14:45.000Z", "avg_line_length": 30.7049180328, "max_line_length": 88, "alphanum_fraction": 0.5152162306, "include": true, "reason": "import numpy", "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214521983691, "lm_q2_score": 0.9273632921335859, "lm_q1q2_score": 0.8942763165857199}}
{"text": "import numpy\nfrom matplotlib import pyplot\n\ndef basic_integral(f, a, b, N):\n    x, dx = numpy.linspace(a, b, N+1, retstep=True)\n    fx = f(x)\n    return dx * numpy.sum(fx[:-1])\n    \ndef trapezoidal(f, a, b, N):\n    x, dx = numpy.linspace(a, b, N+1, retstep=True)\n    fx = f(x)\n    return dx * ( (fx[0] + fx[-1])/2 + numpy.sum(fx[1:-1]) )\n    \nif __name__==\"__main__\":\n    print(\"Basic integral\")\n    I2 = basic_integral(numpy.sin, 0, numpy.pi/2, 2)\n    print(I2)\n    I20 = basic_integral(numpy.sin, 0, numpy.pi/2, 20)\n    print(I20)\n    I200 = basic_integral(numpy.sin, 0, numpy.pi/2, 200)\n    print(I200)\n    Npoints = 2**numpy.arange(1,20)\n    dx_all = numpy.pi/2/Npoints\n    errors = numpy.zeros_like(dx_all)\n    for i, N in enumerate(Npoints):\n        I = basic_integral(numpy.sin, 0, numpy.pi/2, N)\n        errors[i] = abs(I - 1)\n    pyplot.loglog(dx_all, errors, 'kx')\n    pyplot.loglog(dx_all, errors[-1]*(dx_all/dx_all[-1]), 'b-')\n    pyplot.xlabel(r\"$\\Delta x$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.show()\n    \n    print(\"Trapezoidal rule\")\n    I2 = trapezoidal(numpy.sin, 0, numpy.pi/2, 2)\n    print(I2)\n    I20 = trapezoidal(numpy.sin, 0, numpy.pi/2, 20)\n    print(I20)\n    I200 = trapezoidal(numpy.sin, 0, numpy.pi/2, 200)\n    print(I200)\n    Npoints = 2**numpy.arange(1,20)\n    dx_all = numpy.pi/2/Npoints\n    errors = numpy.zeros_like(dx_all)\n    for i, N in enumerate(Npoints):\n        I = trapezoidal(numpy.sin, 0, numpy.pi/2, N)\n        errors[i] = abs(I - 1)\n    pyplot.loglog(dx_all, errors, 'kx')\n    pyplot.loglog(dx_all, errors[-1]*(dx_all/dx_all[-1])**2, 'b-')\n    pyplot.xlabel(r\"$\\Delta x$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.show()", "meta": {"hexsha": "2e4df80933f7e217adc09ce839ed3573d7c3708f", "size": 1663, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/tex/codes/lecture11.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Lectures/tex/codes/lecture11.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Lectures/tex/codes/lecture11.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 32.6078431373, "max_line_length": 66, "alphanum_fraction": 0.6007215875, "include": true, "reason": "import numpy", "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147169737826, "lm_q2_score": 0.9196425399873764, "lm_q1q2_score": 0.8942739402388752}}
{"text": "import numpy as np\nprint(\"np.__version__ : \\n\",np.__version__)\n\nvec1 = np.array([1, 2, 3, 4, 5]) # [1 2 3 4 5] is created \nprint(\"vec1 : \\n\",vec1)\nprint(\"vec1.size : \\n\",vec1.size)\nvec2 = np.arange(5) # [0 1 2 3 4] is created \nprint(\"vec2 : \\n\",vec2)\nprint(\"vec2.size : \\n\",vec2.size)\n\nprint(\"np.dot(vec1,vec2) : \",np.dot(vec1,vec2)) # multiply vectors item by item and sum -> 40\n\nvec1 = np.append(vec1,6)\nprint(\"vec1 after np.append(vec1,6)\",vec1)\n\n# create matrix from vector\nmat_vec1 = np.array([vec1]) # matrix 1x6 \nmat_vec1_transpose = mat_vec1.T # matrix 6x1\n\nprint(\"vec1'*vec1\",np.matmul(mat_vec1_transpose,mat_vec1)) # 6 x 6\n\n# ************** handle matrix\nmat1 = np.array([[1 , 0] , [3 , 4]])\nprint(\"mat1.shape : \\n\",mat1.shape) # number rows , number cols -> 2 , 2\nprint(\"mat1 : \\n\",mat1)\nmat2 = np.array([[0 , 5] , [6 , 7]])\nprint(\"mat2 : \\n\",mat2)\n\n# ----- multiply matrix\nprint(\"np.matmul(mat1,mat2) : \\n\",np.matmul(mat1,mat2))\n\n# ----- transpose matrix\nprint(\"mat1.T : \\n\",mat1.T)\n\n# ----- inverse matrix\nprint(\"inverse mat1 \\n\",np.linalg.inv(mat1))\nprint(\"mat1*inverse mat1 is identity\\n\",np.matmul(mat1,np.linalg.inv(mat1)))\n", "meta": {"hexsha": "532a37f08a6cb1fa356ea8c7aa95b921d884b4b8", "size": 1141, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_try.py", "max_stars_repo_name": "NathanKr/numpy-playground", "max_stars_repo_head_hexsha": "5f36f7471fd7d182a8cbb6097f5d7332991bc7de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy_try.py", "max_issues_repo_name": "NathanKr/numpy-playground", "max_issues_repo_head_hexsha": "5f36f7471fd7d182a8cbb6097f5d7332991bc7de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy_try.py", "max_forks_repo_name": "NathanKr/numpy-playground", "max_forks_repo_head_hexsha": "5f36f7471fd7d182a8cbb6097f5d7332991bc7de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0263157895, "max_line_length": 93, "alphanum_fraction": 0.6362839614, "include": true, "reason": "import numpy", "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811621568289, "lm_q2_score": 0.9263037353800998, "lm_q1q2_score": 0.8942361765714525}}
{"text": "# Two vector are orthogonal if u.v = |u||v|cos@ = 0 or u _|_ v = 90*\n\nimport numpy as np\n\na = np.array([-2, 4, 3])\nb = np.array([3, 3, -2])\n\ndef is_orthogonal():\n    res = np.dot(a, b)\n    \n    if not res:\n        print(\"Orthogonal\")\n    else:\n        print(\"not orthogonal\")\n\nis_orthogonal()", "meta": {"hexsha": "8a0fe1bbb2e05eafee4be1ac2741945990898012", "size": 292, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear-algebra/vector-orthogonality.py", "max_stars_repo_name": "Nahid-Hassan/code-snippets", "max_stars_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-29T04:09:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-18T13:33:36.000Z", "max_issues_repo_path": "linear-algebra/vector-orthogonality.py", "max_issues_repo_name": "Nahid-Hassan/code-snippets", "max_issues_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear-algebra/vector-orthogonality.py", "max_forks_repo_name": "Nahid-Hassan/code-snippets", "max_forks_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-26T04:55:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T04:55:55.000Z", "avg_line_length": 18.25, "max_line_length": 68, "alphanum_fraction": 0.551369863, "include": true, "reason": "import numpy", "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9796676502191265, "lm_q2_score": 0.9124361616674906, "lm_q1q2_score": 0.8938841904757496}}
{"text": "import scipy.integrate as spi\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport json\nimport os\nimport pandas as pd\n\ndef run(args):\n    DIR     = \"Results\\\\SIR_{}\".format(args[\"Name\"])\n    os.makedirs(DIR,exist_ok=True)\n    POP     = args[\"Population\"]\n    R0      = args[\"R0\"]\n    DR      = args[\"Death_Rate\"]\n    GAMMA   = args[\"GAMMA\"] = 1/args[\"Inc_Period\"]\n    BETA    = args[\"BETA\"]  = GAMMA*R0\n    TS      = 1       #Time step\n    Ndays   = args[\"Days\"]       #Number of days\n    Inf0    = args[\"Init_Inf\"]/args[\"Population\"]\n    Susp0   = 1-Inf0\n    Rec0    = 0\n    Dec0    = 0\n    INPUT   = (Susp0, Inf0, Rec0,Dec0)\n    # INPUT   = {'S':Susp0, 'I':Inf0, 'R':Rec0}\n    strs    = ['S','I','R','D']\n\n    def diff_eqs(INP,t):  \n        '''The main set of equations'''\n        Y   = np.zeros((4))\n        V   = dict(zip(strs,INP)) #[Susp,Inf,Rec]   \n        Y[0] = - BETA * V['S'] * V['I']\n        Y[1] = BETA * V['S'] * V['I'] - GAMMA * V['I']\n        Y[2] = GAMMA * V['I'] * (1-DR)\n        Y[3] = GAMMA * V['I'] * DR\n        return Y   # For odeint\n\n    t_start = 0.0; t_end = 1.0*Ndays; t_inc = 1.0*TS\n    t_range = np.arange(t_start, t_end+t_inc, t_inc)\n    RES     = spi.odeint(diff_eqs,INPUT,t_range)\n\n\n    plt.subplot(211)\n    plt.plot(RES[:,0]*POP, '-g', label='Suspectible')\n    plt.plot(RES[:,1]*POP, '-m', label='Infectious')\n    plt.plot(RES[:,2]*POP, '-b', label='Recoveries')\n    plt.plot(RES[:,3]*POP, '-r', label='Deaths')\n    plt.legend(loc=0)\n    plt.title('SIR Model for R0='+str(R0)[:4])\n    # plt.xticks(np.arange(0,Ndays,TS))/\n    plt.xlabel('Timestep')\n    plt.ylabel('Number')\n    plt.grid()\n\n    plt.subplot(212)\n    plt.plot(RES[:,1]*POP, '-r', label='Infectious')\n    plt.xlabel('Timestep')\n    plt.ylabel('Infectious')\n    # plt.show()\n\n    df = pd.DataFrame(np.round(RES*POP),columns=[\"Suspectible\",'Infected','Recovered',\"Died\"])\n    df.index.name = \"Day\"\n\n    plt.savefig(DIR+\"//graph.png\")\n    json.dump(args,open(DIR+\"//params.json\", 'w'),indent = 4)\n    df.to_csv(DIR+\"//output.csv\")\n\n\nwith open(\"SIR_parameters.json\") as f:\n    args = json.load(f)\n\nNos = 9\nR0s = np.linspace(1,4,Nos)\nfor x in range(Nos):\n    args[\"Name\"] = R0s[x]\n    args[\"R0\"] = R0s[x]\n# run(args)\n    ", "meta": {"hexsha": "452d24f4ae306c4df84d8f0d9324d39fae036548", "size": 2217, "ext": "py", "lang": "Python", "max_stars_repo_path": "sir.py", "max_stars_repo_name": "Gauraviitkgp/SIR-Modelling", "max_stars_repo_head_hexsha": "278f1e03762b8c97395d5cdc1dc33d8abb1a2473", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-13T11:50:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-13T11:50:08.000Z", "max_issues_repo_path": "sir.py", "max_issues_repo_name": "CEOAI-ABM/SIR-Modelling", "max_issues_repo_head_hexsha": "02ab89d64040b09ddce820a1ecbbc0cfc9b13f29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sir.py", "max_forks_repo_name": "CEOAI-ABM/SIR-Modelling", "max_forks_repo_head_hexsha": "02ab89d64040b09ddce820a1ecbbc0cfc9b13f29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-16T13:05:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T20:24:36.000Z", "avg_line_length": 29.1710526316, "max_line_length": 94, "alphanum_fraction": 0.5453315291, "include": true, "reason": "import numpy,import scipy", "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9770226334351969, "lm_q2_score": 0.9149009480320036, "lm_q1q2_score": 0.8938789335785864}}
{"text": "# %% Imports\nimport os\nimport sys\nimport numpy as np\nfrom scipy.spatial.transform import Rotation\nimport matplotlib.pyplot as plt\n\nsys.path.append(os.path.dirname(os.path.realpath(__file__)) + \"/../\")\nfrom utils.viz.viz import plot_fustrum, plot_crs, set_3d_axes_equal\n\n# %% Test angles\neuler_deg = [45, 15, -25]\n\n# %% Conversion: Euler angles to rotation matrix\nR = Rotation.from_euler('xyz', euler_deg, degrees=True)\nprint(R.as_matrix())\n\n# %%\n##  Intrinsic & extrinsic rotations\n\n# %% Vizualization\ndef plot_rotation(x, y, z, intrinsic=True):\n    plt.figure(figsize=(12,10))\n    ax = plt.axes(projection='3d')\n    if intrinsic:\n        R = Rotation.from_euler('XYZ', [x, y, z], degrees=True)\n    else:\n        R = Rotation.from_euler('xyz', [x, y, z], degrees=True)\n    plot_fustrum(ax, [0, 0, 0], R.as_matrix(), img_limits=[1, 0.5], f=2.0, scale=1.0, c='k')\n    plot_crs(ax, np.eye(3), X=[-2, -2, 0])\n    crs = R.as_matrix()\n    plot_crs(ax, crs)\n    set_3d_axes_equal(ax)\n\nplot_rotation(0, 0, 0)\n\n# %% Rotation around X axis (red)\nplot_rotation(90, 0, 0)\n\n# %% Rotation around Y axis in the rotated system\n# This is the rotation around a downward looking Z axis in the world\nplot_rotation(90, 90, 0)\n\n# %% Rotation around Z axis in the double rotated system\n# This is the rotation around the X axis in the world\nplot_rotation(90, 90, 45)\n\n# %% Explanation\n# link: https://en.wikipedia.org/wiki/Euler_angles#Definition_by_intrinsic_rotations\n# Twelve combinations of x, y, z:\n# Used in mechatrocins: z-x-z, x-y-x, y-z-y, z-y-z, x-z-x, y-x-y\n# Navigation: x-y-z, y-z-x, z-x-y, x-z-y, z-y-x, y-x-z\n\n# %% Looking at the specs of scipy:\n# link: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.transform.Rotation.from_euler.html\n# {‘X’, ‘Y’, ‘Z’} for intrinsic rotations, or\n# {‘x’, ‘y’, ‘z’} for extrinsic rotations.\n\n# %% Ok let's play the same just with extrinsic rotation\nplot_rotation(90, 0, 0, intrinsic=False)\n# this is the same as before\n\n# %% Rotation around Y axis in the (!!!) world system\nplot_rotation(90, 90, 0, intrinsic=False)\n# this is different\n\n# %% Rotation around Z axis in the (!!!) world system\nplot_rotation(90, 90, 45, intrinsic=False)\n\n# %%\n# So we have 12 combinations for intrinsic and 12 combinations for extrinics\n# This is all together 24 combinations to describe rotations with Euler angles.\n\n# %% Statement 1\n# A sequence of intrinsic rotations produces the same total rotations\n# as the sequence of extrinsic rotations with the same angles but in reverse order.\n# Proof: https://math.stackexchange.com/questions/1137745/proof-of-the-extrinsic-to-intrinsic-rotation-transform/3314025\nrpy = euler_deg\nR_int = Rotation.from_euler('xyz', rpy, degrees=True) # extrinsic\nypr = [euler_deg[2], euler_deg[1], euler_deg[0]]\nR_ext = Rotation.from_euler('ZYX', ypr, degrees=True) # intrinsic\nchk = np.linalg.norm(R_int.as_matrix() - R_ext.as_matrix())\nprint(f\"Difference of the two matrices: {chk}\")\n\n# %% Composing rotation matrix from euler angles\n# 1. Order of angles\n# 2. Order of multiplying matrices\n\nR_x = Rotation.from_euler('x', euler_deg[0], degrees=True).as_matrix()\nR_y = Rotation.from_euler('y', euler_deg[1], degrees=True).as_matrix()\nR_z = Rotation.from_euler('z', euler_deg[2], degrees=True).as_matrix()\n\nR_int = Rotation.from_euler('XYZ', euler_deg, degrees=True).as_matrix()\nchk = np.linalg.norm(R_x @ R_y @ R_z - R_int)\nprint(f'Intrinsics check: {chk}')\n\nR_ext = Rotation.from_euler('xyz', euler_deg, degrees=True).as_matrix()\nchk = np.linalg.norm(R_z @ R_y @ R_x - R_ext)\nprint(f'Extrinsics check: {chk}')\n\n# %%\n## Conversion: rotiation matrix to Euler angles\n\n# %%\nR = Rotation.from_euler('xyz', euler_deg, degrees=True)\nprint(R.as_matrix())\nprint(R.as_euler('xyz', degrees=True))\n\n# %% Gimbal lock\n# link: https://matthew-brett.github.io/transforms3d/gimbal_lock.html\nR = Rotation.from_euler('xyz', [10, -90, 10], degrees=True)\nprint(R.as_matrix())\nprint(R.as_euler('xyz', degrees=True))\n\n# %%\nimport math\nfrom math import sin, cos\n\ndef getR(pitch, roll, yaw):\n    R1 = [cos(yaw)*cos(roll)+sin(yaw)*sin(pitch)*sin(roll), -sin(yaw)*cos(roll)+cos(yaw)*sin(pitch)*sin(roll), -cos(pitch)*sin(roll)]\n    R2 = [cos(yaw)*sin(roll)-sin(yaw)*sin(pitch)*cos(roll), -sin(yaw)*sin(roll)-cos(yaw)*sin(pitch)*cos(roll), cos(pitch)*cos(roll)]\n    R3 = [-sin(yaw)*cos(pitch), -cos(yaw)*cos(pitch), -sin(pitch)]\n    return np.vstack([R1, R2, R3])\n\n\nyaw = 35/180*math.pi\npitch = -45/180*math.pi\nroll = -185/180*math.pi\n\nR_fn = getR(pitch, roll, yaw)\nR = Rotation.from_euler('zxz', [yaw, pitch, roll], degrees=False).as_matrix()\n\nprint(np.linalg.norm(R_fn-R))\nnp.set_printoptions(suppress=True)\nprint(R_fn)\nprint(' ')\nprint(R)\n\n# %%\n\n\n# %%\nprint(Rotation.from_euler('XYZ', [90, 45, 0], degrees=True).as_matrix())\n# %%\nprint(np.linalg.det(R1))\nprint(R1.T - np.linalg.inv(R1))\n\n# %%\nR1.T - np.linalg.inv(R1)\n\n# %%\n", "meta": {"hexsha": "4c0d1d66f1dce640909eb6149b9a837041d82727", "size": 4855, "ext": "py", "lang": "Python", "max_stars_repo_path": "materials/math_euler_rotations.py", "max_stars_repo_name": "zkoppanyi/uni", "max_stars_repo_head_hexsha": "32dbf0a425c6922264e737e9d59f794b32bb9c95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "materials/math_euler_rotations.py", "max_issues_repo_name": "zkoppanyi/uni", "max_issues_repo_head_hexsha": "32dbf0a425c6922264e737e9d59f794b32bb9c95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "materials/math_euler_rotations.py", "max_forks_repo_name": "zkoppanyi/uni", "max_forks_repo_head_hexsha": "32dbf0a425c6922264e737e9d59f794b32bb9c95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9407894737, "max_line_length": 133, "alphanum_fraction": 0.694953656, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360932, "lm_q2_score": 0.9343951643678382, "lm_q1q2_score": 0.8938743717038949}}
{"text": "#ZADANIE 1\n#Napisz program realizujacy poszukiwanie miejsc zerowych\n#powyzszych funkcji z punktu a) i b). Wykorzystaj metode graficzna,\n#liniowej inkrementacji i bisekcji. Stworz odpowiednie funkcje\n#implementujace wymienione metody poszukiwania miejsc zerowych.\n#Dobierz odpowiednio obszary wyszukiwania. Wykonaj analize bledow.\n#Opisz w sprawozdaniu wnioski.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef fxA(x):\n    return 7 * x**5 + 9 * x**2 - 5 * x\n\ndef fxB(x):\n    return (1 / ((x - 0.3)**2 + 0.01)) - (1 / ((x - 0.8)**2) + 0.04)\n\ndef linearIncremental(fx, xstart, xd, maxincr):\n    x = xstart\n    fstart = fx(x)\n    for i in range(maxincr):\n        x = xstart + i * xd\n        if fstart * fx(x) < 0:\n            break\n    if fstart * fx(x) > 0:\n        raise Exception(\"Nie znaleziono rozwiazania!\")\n    else:\n        return x - (xd * fx(x)) / (fx(x)-fx(x - xd))\n\ndef bisection(fx, a, b, err):\n    while np.absolute(b - a) > err:\n        midPoint = (a + b) * 0.5\n        if fx(midPoint) * fx(a) < 0:\n            b = midPoint\n        midPoint = (a + b) * 0.5\n        if fx(midPoint) * fx(b) < 0:\n            a = midPoint\n    return b - (b - a) * fx(b) / (fx(b) - fx(a))\n\nprint(\"Funkcja A\")\nprint(\"\\nTest metody graficznej\")\nx = np.arange(-3, 3, 0.1)\nplt.plot(x, fxA(x), 'r.')\nplt.grid(True)\nplt.show()\n\nprint(\"\\nTest metody inkrementacji\")\nerr = fxA(linearIncremental(fxA, -3, 0.01, 500))\nprint(\"x1 = \",linearIncremental(fxA, -3, 0.01, 500), \"fx(x1) = \", err)\nerr = fxA(linearIncremental(fxA, 0, 0.01, 500))\nprint(\"x2 = \",linearIncremental(fxA, 0, 0.01, 500), \"fx(x2) = \", err)\nerr = fxA(linearIncremental(fxA, 0.5, 0.01, 500))\nprint(\"x3 = \",linearIncremental(fxA, 0.5, 0.01, 500), \"fx(x3) = \", err)\n\nprint(\"\\nTest metody bisekcji\")\nprint(\"x1 = \", bisection(fxA, -5, 1, 0.001))\nprint(\"x2 = \", bisection(fxA, -4, 1, 0.001))\nprint(\"x3 = \", bisection(fxA, -3, 1, 0.001))\n\n\nprint(\"\\n\\nFunkcja B\")\nprint(\"\\nTest metody graficznej\")\nx = np.arange(-3, 3, 0.1)\nplt.plot(x, fxB(x), 'y.')\nplt.grid(True)\nplt.show()\n\nprint(\"\\nTest metody inkrementacji\")\nerr = fxB(linearIncremental(fxB, -3, 0.01, 500))\nprint(\"x1 = \",linearIncremental(fxB, -3, 0.01, 500), \"fx(x1) = \", err)\nerr = fxB(linearIncremental(fxB, 0, 0.01, 500))\nprint(\"x2 = \",linearIncremental(fxB, 0, 0.01, 500), \"fx(x2) = \", err)\nerr = fxB(linearIncremental(fxB, 0.5, 0.01, 500))\nprint(\"x3 = \",linearIncremental(fxB, 0.5, 0.01, 500), \"fx(x3) = \", err)\n\nprint(\"\\nTest metody bisekcji\")\nprint(\"x1 = \", bisection(fxB, -5, 1, 0.001))\nprint(\"x2 = \", bisection(fxB, -4, 1, 0.001))\nprint(\"x3 = \", bisection(fxB, -3, 1, 0.001))\n\n#Program umozliwia znalezienie miejsc zerowych funkcji na trzy sposoby:\n#- metody graficznej,\n#- metody liniowej inkrementacji,\n#- metody bisekcji.\n#Przedstawione w programie metody znalezienia miejsc zerowych nie sa idealne.\n#Metoda liniowej inkrementacji zwraca wysoki blad.\n#Metoda bisekcji nie zwraca dokladnych wartosci miejsc zerowych.", "meta": {"hexsha": "9fad2edb9d0c768521052db84da2e8ec8c2311a4", "size": 2930, "ext": "py", "lang": "Python", "max_stars_repo_path": "MN_lab_8/MN_lab8_zad_1.py", "max_stars_repo_name": "matbocz/kurs-mn-python-pwsz-elblag", "max_stars_repo_head_hexsha": "629d778be7c5d3b6cc217b7ba48e2e0d55ccdf36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MN_lab_8/MN_lab8_zad_1.py", "max_issues_repo_name": "matbocz/kurs-mn-python-pwsz-elblag", "max_issues_repo_head_hexsha": "629d778be7c5d3b6cc217b7ba48e2e0d55ccdf36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MN_lab_8/MN_lab8_zad_1.py", "max_forks_repo_name": "matbocz/kurs-mn-python-pwsz-elblag", "max_forks_repo_head_hexsha": "629d778be7c5d3b6cc217b7ba48e2e0d55ccdf36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6781609195, "max_line_length": 77, "alphanum_fraction": 0.6320819113, "include": true, "reason": "import numpy", "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812309063186, "lm_q2_score": 0.9230391722430736, "lm_q1q2_score": 0.8938538097914971}}
{"text": "import numpy as np\n\ndef ecdf(data):\n    \"\"\"Compute ECDF for a one-dimensional array of measurements.\"\"\"\n\n    # Number of data points: n\n    n = len(data)\n\n    # x-data for the ECDF: x\n    x = np.sort(data)\n\n    # y-data for the ECDF: y\n    y = np.arange(1, n+1) / n\n\n    return x, y\n\ndef pearson_r(data_1, data_2):\n    '''Calculates Pearson correlection coefficient'''\n    return np.corrcoef(data_1, data_2)[0,1]\n\n# bootstrap functions\n\ndef bootstrap_replicate_1d(data, func):\n    '''Generate bootstrap replicate of 1D data'''\n    bs_sample = np.random.choice(data, len(data))\n    return func(bs_sample)\n\ndef draw_bs_reps(data, func, size=1):\n    \"\"\"Draw bootstrap replicates.\"\"\"\n    # Initialize array of replicates: bs_replicates\n    bs_replicates = np.empty(size)\n\n    # Generate replicates\n    for i in range(size):\n        bs_replicates[i] = bootstrap_replicate_1d(data, func)\n\n    return bs_replicates\n\ndef draw_bs_pairs(x, y, func, size=1):\n    \"\"\"Perform pairs bootstrap for replicates.\"\"\"\n    # Set up array of indices to sample from: inds\n    inds = np.arange(len(x))\n\n    # Initialize replicates\n    bs_replicates = np.empty(size)\n\n    # Generate replicates\n    for i in range(size):\n        bs_inds = np.random.choice(inds, len(inds))\n        bs_x, bs_y = x[bs_inds], y[bs_inds]\n        bs_replicates[i] = func(bs_x, bs_y)\n\n    return bs_replicates\n\ndef draw_bs_pairs_linreg(x, y, size=1):\n    \"\"\"Perform pairs bootstrap for linear regression.\"\"\"\n\n    # Set up array of indices to sample from: inds\n    inds = np.arange(len(x))\n\n    # Initialize replicates: bs_slope_reps, bs_intercept_reps\n    bs_slope_reps = np.empty(size)\n    bs_intercept_reps = np.empty(size)\n\n    # Generate replicates\n    for i in range(size):\n        bs_inds = np.random.choice(inds, size=len(inds))\n        bs_x, bs_y = x[bs_inds], y[bs_inds]\n        bs_slope_reps[i], bs_intercept_reps[i] = np.polyfit(bs_x, bs_y, 1)\n\n    return bs_slope_reps, bs_intercept_reps\n\n# hypothesis testing functions\n\ndef permutation_sample(data1, data2):\n    \"\"\"Generate a permutation sample from two data sets.\"\"\"\n\n    # Concatenate the data sets: data\n    data = np.concatenate((data1, data2))\n\n    # Permute the concatenated array: permuted_data\n    permuted_data = np.random.permutation(data)\n\n    # Split the permuted array into two: perm_sample_1, perm_sample_2\n    perm_sample_1 = permuted_data[:len(data1)]\n    perm_sample_2 = permuted_data[len(data1):]\n\n    return perm_sample_1, perm_sample_2\n\ndef draw_perm_reps(data_1, data_2, func, size=1):\n    \"\"\"Generate multiple permutation replicates.\"\"\"\n\n    # Initialize array of replicates: perm_replicates\n    perm_replicates = np.empty(size)\n\n    for i in range(size):\n        # Generate permutation sample\n        perm_sample_1, perm_sample_2 = permutation_sample(data_1, data_2)\n\n        # Compute the test statistic\n        perm_replicates[i] = func(perm_sample_1, perm_sample_2)\n\n    return perm_replicates\n", "meta": {"hexsha": "bcb9e61f7ad2213b48f3d2f6aefef2a9c9ffe19c", "size": 2934, "ext": "py", "lang": "Python", "max_stars_repo_path": "stats_func.py", "max_stars_repo_name": "rafburzy/Statistics", "max_stars_repo_head_hexsha": "d9c82e75a3dfdc39febd4480daf24cd517a80568", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stats_func.py", "max_issues_repo_name": "rafburzy/Statistics", "max_issues_repo_head_hexsha": "d9c82e75a3dfdc39febd4480daf24cd517a80568", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stats_func.py", "max_forks_repo_name": "rafburzy/Statistics", "max_forks_repo_head_hexsha": "d9c82e75a3dfdc39febd4480daf24cd517a80568", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2115384615, "max_line_length": 74, "alphanum_fraction": 0.6850715746, "include": true, "reason": "import numpy", "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812318188366, "lm_q2_score": 0.9230391574234201, "lm_q1q2_score": 0.8938537962827127}}
{"text": "#NUMPY EXERCISES \n# import numpy as np \na = np.array([4, 10, 12, 23, -2, -1, 0, 0, 0, -6, 3, -7])\n\n#1.How many negative numbers are there?()\nlen(a[a < 0])\n\n#2.How many positive numbers are there?\nlen(a[a > 0])\n\n#3.How many even positive numbers are there?\nlen(a[(a > 0) & (a % 2 == 0)])\n\n#4.If you were to add 3 to each data point, how many positive numbers would there be?\na_plus_three = a + 3\na_plus_three \n\nlen(a_plus_three)\n\n\n#5.If you squared each number, what would the new mean and standard deviation be?\na_squared = a**2\na_squared_mean = a_squared.mean()\n\n\na_squared_mean\n\na_std = a_squared.std()\n\na_std\n\n\n#6.Centering- Subtracting the mean from each data point. Center the data set.\na_centered = a - a.mean()\n\na_centered\n\n\n#7.Calculate the z-score for each data point\n\na_z_score = a_centered / a.std()\n\na_z_score\n\n\n#8. ################################################################################\n#                             More Numpy Practice                              #\n################################################################################\n\n\nimport numpy as np\n# Life w/o numpy to life with numpy\n\n## Setup 1\na = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n# Use python's built in functionality/operators to determine the following:\n# Exercise 1 - Make a variable called sum_of_a to hold the sum of all the numbers in above list\nsum_of_a = sum(a)\n\nsum_of_a \n# Exercise 2 - Make a variable named min_of_a to hold the minimum of all the numbers in the above list\n\nmin_of_a = min(a)\n\nmin_of_a \n\n# Exercise 3 - Make a variable named max_of_a to hold the max number of all the numbers in the above list\nmax_of_a = max(a)\n\nmax_of_a\n\n\n# Exercise 4 - Make a variable named mean_of_a to hold the average of all the numbers in the above list\nmean_of_a = sum(a) / len(a)\n\nmean_of_a\n\n# Exercise 5 - Make a variable named product_of_a to hold the product of multiplying all the numbers in the above list together\nproduct_of_a = 1\n\nfor n in a:\n    product_of_a *= n\nproduct_of_a\n\n# Exercise 6 - Make a variable named squares_of_a. It should hold each number in a squared like [1, 4, 9, 16, 25...]\n\nsquares_of_a = [n ** 2 for n in a]\n\n# Exercise 7 - Make a variable named odds_in_a. It should hold only the odd numbers\n\nodds_in_a = [n for n in a if n % 2 == 1]\n\nodds_in_a \n# Exercise 8 - Make a variable named evens_in_a. It should hold only the evens.\n\nevens_in_a = [n for n in a if n % 2 == 0]\n\nevens_in_a \n## What about life in two dimensions? A list of lists is matrix, a table, a spreadsheet, a chessboard...\n## Setup 2: Consider what it would take to find the sum, min, max, average, sum, product, and list of squares for this list of two lists.\nb = [\n    [3, 4, 5],\n    [6, 7, 8]\n]\n\n# Exercise 1 - refactor the following to use numpy. Use sum_of_b as the variable. **Hint, you'll first need to make sure that the \"b\" variable is a numpy array**\nb = np.array(b)\nsum_of_b = b.sum()\n\nsum_of_b\n\n# Exercise 2 - refactor the following to use numpy. \nmin_of_b = b.min()\n\nmin_of_b\n\n# Exercise 3 - refactor the following maximum calculation to find the answer with numpy.\nmax_of_b = b.max()\n\nmax_of_b\n\n\n# Exercise 4 - refactor the following using numpy to find the mean of b\nmean_of_b = b.mean()\n\nmean_of_b \n\n# Exercise 5 - refactor the following to use numpy for calculating the product of all numbers multiplied together.\nproduct_of_b = b.prod()\n\nproduct_of_b\n\n\n# Exercise 6 - refactor the following to use numpy to find the list of squares \nsquares_of_b = b ** 2\n\nsquares_of_b\n\n\n# Exercise 7 - refactor using numpy to determine the odds_in_b\nodds_in_b = b[b % 2 == 1]\n\nodds_in_b\n\n\n# Exercise 8 - refactor the following to use numpy to filter only the even numbers\nevens_in_b = b[b % 2 == 0]\n\nevens_in_b\n\n# Exercise 9 - print out the shape of the array b.\n\nprint(b.shape)\n\n# Exercise 10 - transpose the array b.\nb.T\nb.T.shape\n\n# Exercise 11 - reshape the array b to be a single list of 6 numbers. (1 x 6)\nb.flatten()\n\n\n# Exercise 12 - reshape the array b to be a list of 6 lists, each containing only 1 number (6 x 1) \nb.reshape(6,1)\nprint(b.reshape)\n\n\n## Setup 3\nc = [\n    [1, 2, 3],\n    [4, 5, 6],\n    [7, 8, 9]\n]\n\nc = np.array(c)\n\n# HINT, you'll first need to make sure that the \"c\" variable is a numpy array prior to using numpy array methods.\n# Exercise 1 - Find the min, max, sum, and product of c.\nc.min(), c.max(), c.sum(), c.prod()\n\n# Exercise 2 - Determine the standard deviation of c.\nc.std()\n\n# Exercise 3 - Determine the variance of c.\nc.std() ** 2\n\n# Exercise 4 - Print out the shape of the array c\nc.shape\n\n# Exercise 5 - Transpose c and print out transposed result.\nc.T\n\n# Exercise 6 - Get the dot product of the array c with c. \nc.dot(c)\n\n# Exercise 7 - Write the code necessary to sum up the result of c times c transposed. Answer should be 261\n(c * c.T).sum()\n \n# Exercise 8 - Write the code necessary to determine the product of c times c transposed. Answer should be 131681894400.\n(c * c.T).prod()\n\n## Setup 4\nd = [\n    [90, 30, 45, 0, 120, 180],\n    [45, -90, -30, 270, 90, 0],\n    [60, 45, -45, 90, -45, 180]\n]\n\nd = np.array(d)\n\nprint(d)\n# Exercise 1 - Find the sine of all the numbers in d\nnp.sin(d)\n\n# Exercise 2 - Find the cosine of all the numbers in d\nnp.cos(d)\n\n# Exercise 3 - Find the tangent of all the numbers in d\nnp.tan(d)\n\n# Exercise 4 - Find all the negative numbers in d\nd[d < 0]\n\n# Exercise 5 - Find all the positive numbers in d\nd[d > 0]\n\n# Exercise 6 - Return an array of only the unique numbers in d.\nnp.unique(d)\n\n# Exercise 7 - Determine how many unique numbers there are in d.\nnp.unique(d).size\n\n# Exercise 8 - Print out the shape of d.\nd.shape\n\n# Exercise 9 - Transpose and then print out the shape of d.\nd.T.shape\n\n# Exercise 10 - Reshape d into an array of 9 x 2\nd.reshape(9, 2)\n", "meta": {"hexsha": "0dda3c6e712702faf2623111b4debdb4f1eb2fdd", "size": 5731, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_exercises.py", "max_stars_repo_name": "brandonjbryant/numpy-pandas-visualization-exercises", "max_stars_repo_head_hexsha": "9137ddf7abd2288fbfaad057de787c712833bffc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-28T17:59:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-28T17:59:31.000Z", "max_issues_repo_path": "numpy_exercises.py", "max_issues_repo_name": "brandonjbryant/numpy-pandas-visualization-exercises", "max_issues_repo_head_hexsha": "9137ddf7abd2288fbfaad057de787c712833bffc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy_exercises.py", "max_forks_repo_name": "brandonjbryant/numpy-pandas-visualization-exercises", "max_forks_repo_head_hexsha": "9137ddf7abd2288fbfaad057de787c712833bffc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6818181818, "max_line_length": 161, "alphanum_fraction": 0.6668993195, "include": true, "reason": "import numpy", "num_tokens": 1684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474181553805, "lm_q2_score": 0.9362850110816422, "lm_q1q2_score": 0.8938220684866715}}
{"text": "# Undergraduate Student: Arturo Burgos\n# Professor: João Rodrigo Andrade\n# Federal University of Uberlândia - UFU, Fluid Mechanics Laboratory - MFLab, Block 5P, Uberlândia, MG, Brazil\n\n\n# Fourth exercise: Solving a Linear System --> ax = b\n\n# Here I first set conditions\n\nimport numpy as np\nfrom numpy import linalg as lin\nnp.seterr(divide='ignore', invalid='ignore')\n\na = np.array([\n    [-4, 1, 0, 1, 0, 0, 0, 0, 0],\n    [1, -4, 1, 0, 1, 0, 0, 0, 0], \n    [0, 1, -4, 0, 0, 1, 0, 0, 0], \n    [1, 0, 0, -4, 1, 0, 1, 0, 0], \n    [0, 1, 0, 1, -4, 1, 0, 1, 0], \n    [0, 0, 1, 0, 1, -4, 0, 0, 1], \n    [0, 0, 0, 1, 0, 0, -4, 1, 0], \n    [0, 0, 0, 0, 1, 0, 1, -4, 1], \n    [0, 0, 0, 0, 0, 1, 0, 1, -4] \n    ])\n\nprint('The coefficient Matrix is:')\nprint(a)\nprint('\\n')\n\nb = np.array([-50, -50, -150, 0, 0, -100, -50, -50, -150])\n\nprint('The result Matrix is:')\nprint(b)\nprint('\\n')\n\nx_k = np.zeros(9)\nx_k1 = np.ones(9)\n\n\n\n\n# Here I set the tolerance\ntolerance = 0.000000001\n\n# Here I set the iterations\nite = 0\n  \n\n# Here I set the error based in the Infinite norm  \nerro = np.ones(9)\nerro = lin.norm((x_k1 - x_k),np.inf)\n\nwhile (erro>tolerance): # because the error is not an array anymore there is no problem with this while, \n    # we do not have to put .any()\n    for i in range(0,9):\n        \n        x_k1[i] = b[i]\n\n        for j in range(0,9):\n\n            if j!=i:\n\n                x_k1[i] =  x_k1[i] - a[i,j]*x_k[j]\n\n\n    \n        x_k1[i] =  x_k1[i]/ a[i,i]\n\n    erro = lin.norm((x_k1 - x_k),np.inf)\n    x_k = x_k1.copy()\n    ite = ite + 1\n\n\nprint('The number of iterations is: ')\nprint(ite)\nprint('\\n')\n\nprint('The solution is:')\nprint(x_k1)\nprint('\\n')\n\nprint('Note that now the error is not an array anymore, but is normalized :')\nprint(erro)\nprint('\\n')\n\n", "meta": {"hexsha": "4b96bce686de44b1e86d1533cb34fc823b176e06", "size": 1761, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear System/Python/normalization_test.py", "max_stars_repo_name": "arturofburgos/Comparing-Languages", "max_stars_repo_head_hexsha": "a20dc24699c762252c94c26e32c7053c04793d9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-03-17T18:40:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T11:51:12.000Z", "max_issues_repo_path": "Linear System/Python/normalization_test.py", "max_issues_repo_name": "arturofburgos/Comparing-Languages", "max_issues_repo_head_hexsha": "a20dc24699c762252c94c26e32c7053c04793d9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear System/Python/normalization_test.py", "max_forks_repo_name": "arturofburgos/Comparing-Languages", "max_forks_repo_head_hexsha": "a20dc24699c762252c94c26e32c7053c04793d9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-04T21:48:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-04T21:48:20.000Z", "avg_line_length": 20.476744186, "max_line_length": 110, "alphanum_fraction": 0.5576377058, "include": true, "reason": "import numpy,from numpy", "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474233166329, "lm_q2_score": 0.9362849986365572, "lm_q1q2_score": 0.8938220614384065}}
{"text": "# coding: utf-8\nimport numpy as np\nimport math as m\nimport matplotlib.pyplot as plt\nimport time as tm\n\n\n# Newton-Raphson Method\ndef Newton_Raphson(f, H, U0, N, epsilon):\n    \"\"\"Newton_Raphson takes 5 arguments :\n    f: studied function (given as an array)\n    H: jacobian matrix of f\n    U0: start point\n    N: maximum of iterations\n    epsilon: precision\n    and returns the calculated zeros of f \"\"\"\n    U=U0\n    V=np.linalg.lstsq(H(U),-f(U))[0] #function resolving Ax=B\n    UplusV=U+V\n    i=1\n    while(i<N and ((np.linalg.norm(UplusV-U))>epsilon)):\n        U=UplusV\n        V=np.linalg.lstsq(H(U),-f(U))[0]\n        UplusV=U+V\n        i+=1\n    return UplusV\n\n\n# Newton Method with Backtracking\ndef Newton_BT(f,H,U0,N,epsilon):\n    \"\"\"Newton_BT takes 5 arguments :\n    f: studied function (given as an array)\n    H: jacobian matrix of f\n    U0: start point\n    N: maximum of iterations\n    epsilon: precision\n    and returns the zeros of f,\n    calculated through the Newton method with backtracking\"\"\"\n    U=U0\n    for i in range(1,N):\n        Va=f(U)\n        Na=np.linalg.norm(Va)\n        if (Na<epsilon):\n            return U\n        dV=H(U)\n        dU=-1*np.linalg.lstsq(dV,Va)[0]\n        lambd=1.0\n        while (np.linalg.norm(f(U+lambd*dU))>=Na):\n            lambd=lambd*(2.0/3)\n        U=U+lambd*dU\n    return U\n\n\ndef Newton_BT_error_curve(f,H,U0,N,epsilon,realZero):\n    \"\"\"Newton_BT_error_curves takes 6 arguments :\n    f: studied function (given as an array)\n    H: jacobian matrix of f\n    U0: start point\n    N: maximum of iterations\n    epsilon: precision\n    realZero: the real zero of f that we want to calculate \n    The function prints the curve\n    representing Error on the calculated zeros depending on the number of done iterations,\n    calculated through the Newton method with backtracking\"\"\"\n\n    y=[]\n    nb_point=N-1\n    x=np.linspace(1,N,nb_point)\n\n    Nzero=np.linalg.norm(realZero)#exact zero norm\n\n    U=U0\n    for i in range(1,N):\n        Va=f(U)\n        Na=np.linalg.norm(Va)\n        if (Na<epsilon):\n            for j in range(i,N):\n                y.append(abs(Nzero-np.linalg.norm(U)))\n            break\n        dV=H(U)\n        dU=-1*np.linalg.lstsq(dV,Va)[0]\n        lambd=1.0\n        while (np.linalg.norm(f(U+lambd*dU))>=Na):\n            lambd=lambd*(2.0/3)\n        U=U+lambd*dU\n        y.append(abs(Nzero-np.linalg.norm(U)))\n    plt.plot(x,y)\n    plt.ylabel(\"Error from the NR with backtracking method\")\n    plt.xlabel(\"Number of iterations of the NR with backtracking Method\")\n    plt.title(\"Error on the calculated zeros depending on the max of iterations of the NR with backtracking method\")\n    plt.show()\n\n\ndef error_NR_depending_on_N(f,H,U0,N1,N2,step,real_zero,eps):\n    \"\"\"error_NR_depending_on_N prints the curve\n    representing Error on the calculated zeros depending on the max of iterations of\n    the NRMethod\"\"\"\n\n    y=[]\n    nb_point=int(float((N2-N1))/float(step))+1\n    x=np.linspace(N1,N2,nb_point)\n\n    Nzero=np.linalg.norm(real_zero)#exact zero norm\n\n    while(N1<=N2):\n        zero=Newton_Raphson(f,H,U0,N1,eps)\n        y.append(abs(Nzero-np.linalg.norm(zero)))        \n        N1+=step\n    plt.plot(x,y)\n    plt.ylabel(\"Error from the NR Method\")\n    plt.xlabel(\"Max of iterations of the NR Method\")\n    plt.title(\"Error on the calculated zeros depending on the max of iterations of the NRMethod\")\n    plt.show()\n\n\nif __name__ == '__main__':\n\n    print(\"SOME TESTS ON NR ALGORITHM:\")\n    print(\"\")\n    \n    functionU2D=Newton_Raphson(lambda A: np.array([A[0]*A[0]-2,A[1]*A[1]-3]),lambda A:  np.array([[(2*A[0]), 0], [0, (2*A[1])]]),np.array([1, 1]),100,0.00000001) \n\n    print(\"TEST 1 NR, USING f:(x,y)->(x²-2,y²-3)\")\n    print(\"U0: (1,1)\")\n    print(\"Expected solution :\")\n    print(\"[~1.41421 ~1.73205]\")\n    print(\"Solution we get :\")\n    print(functionU2D)\n    print(\"\")\n    print(\"\")\n    \n    functionU1D=Newton_Raphson(lambda A: np.array([(A[0]**2)-2]),lambda A:  np.array([[2*A[0]]]),np.array([1]),100,0.00000001)\n\n    print(\"TEST 2 NR, USING f:(x)->(x²-2)\")\n    print(\"U0: 1\")\n    print(\"Expected solution :\")\n    print(\"[~1.41421]\")\n    print(\"Solution we get :\")\n    print(functionU1D)\n    print(\"\")\n    print(\"\")\n\n    print(\"TESTS ON (x³+4*x²+4), SHOWING NR PROBLEMS AND NR BACKTRACKING WINS :\")\n    print(\"\")\n\n    functionU1Dbis=Newton_Raphson(lambda A: np.array([(A[0]**3)+4*(A[0]**2)+4]),lambda A:  np.array([[3*(A[0]**2)+8*A[0]]]),np.array([-5]),100,0.00000001)\n\n    print(\"TEST 2 NR, USING f:(x)->(x³+4*x²+4)\")\n    print(\"U0: -5 \")\n    print(\"Expected solution :\")\n    print(\"[~-4.22417]\")\n    print(\"Solution we get :\")\n    print(functionU1Dbis)\n    print(\"\")\n    print(\"\")    \n    functionU1Dter=Newton_Raphson(lambda A: np.array([(A[0]**3)+4*(A[0]**2)+4]),lambda A:  np.array([[3*(A[0]**2)+8*A[0]]]),np.array([5]),100,0.00000001)\n\n    print(\"TEST 3 NR, USING f:(x)->(x³+4*x²+4)\")\n    print(\"U0: 5 \")\n    print(\"Expected solution :\")\n    print(\"[~-4.22417]\")\n    print(\"Solution we get :\")\n    print(functionU1Dter)\n    print(\"-> The method fails to find the zero, because of the local extremums located between 5 and -4.22[...].\")\n    print(\"\")    \n\n    functionUBT1=Newton_BT(lambda A: np.array([(A[0]**3)+4*(A[0]**2)+4]),lambda A:  np.array([[3*(A[0]**2)+8*A[0]]]),np.array([5]),100,0.00000001)\n\n    print(\"TEST 1 BT, USING f:(x)->(x³+4*x²+4)\")\n    print(\"U0: 5 \")\n    print(\"Expected solution :\")\n    print(\"[~-4.22417]\")\n    print(\"Solution we get :\")\n    print(functionUBT1)\n    print(\"-> The method NR with backtracking can solve what NR actually can't.\")\n    print(\"\")    \n\n    print(\"OTHER TESTS OF NEWTON WITH BACKTRACKING:\")\n    print(\"\")\n    functionUBT=Newton_BT(lambda A: np.array([A[0]*A[0]-2,A[1]*A[1]-A[1]-1]),lambda A:  np.array([[(2*A[0]), 0], [0, (2*A[1])-1]]),np.array([2,2]),100,0.000000000001)\n\n    print(\"TEST 2 BT, USING f:(x,y)->(x²-2,y²-y-1)\")\n    print(\"U0: (2,2)\")\n    print(\"Expected solution :\")\n    print(\"[~1.41421 ~1.61803]\")\n    print(\"Solution we get :\")\n    print(functionUBT)\n    print(\"\")\n    print(\"\")\n\n    functionUBT3=Newton_BT(lambda A: np.array([(A[0]**4)-2*(A[0]**3)-(A[0]**2)+2*A[0]+0.3]),lambda A:  np.array([[4*(A[0]**3)-6*(A[0]**2)-2*A[0]+2]]),np.array([-0.55]),100,0.001) \n    \n    print(\"TEST 3 BT, USING f:(X)->X^4-2X³-X²+2X+0.3\")\n    print(\"This test efficiently decreases the value lambda.\")\n    print(\"U0: -0.55\")\n    print(\"Expected solution :\")\n    print(\"[~ -0.142915]\")\n    print(\"Solution we get :\")\n    print(functionUBT3)\n    print(\"\")\n    print(\"\")\n\n    print(\"Curves from the NR method :\")\n    print(\"CURVE ON THE EXAMPLE f : x -> (x³+4*x²+4), WITH START POINT -500, MAX OF 15 ITERATIONS ...\")\n    error_NR_depending_on_N(lambda A: np.array([(A[0]**3)+4*(A[0]**2)+4]),lambda A:  np.array([[3*(A[0]**2)+8*A[0]]]),np.array([-500]),0,15,1,np.array([-4.224169871088]),0.000001)\n    print(\"... It converges.\")\n    print(\"\")\n    print(\"CURVE ON THE EXAMPLE f : x -> (x³+4*x²+4), WITH START POINT 50, MAX OF 15 ITERATIONS : ...\")\n    error_NR_depending_on_N(lambda A: np.array([(A[0]**3)+4*(A[0]**2)+4]),lambda A:  np.array([[3*(A[0]**2)+8*A[0]]]),np.array([50]),0,15,1,np.array([-4.224169871088]),0.000001)\n    print(\"... It converges after a few fluctuations.\")\n    print(\"\")\n    print(\"CURVE ON THE EXAMPLE f : x -> (x³+4*x²+4), WITH START POINT 5, MAX OF 15 ITERATIONS : ...\")\n    error_NR_depending_on_N(lambda A: np.array([(A[0]**3)+4*(A[0]**2)+4]),lambda A:  np.array([[3*(A[0]**2)+8*A[0]]]),np.array([5]),0,15,1,np.array([-4.224169871088]),0.000001)\n    print(\"... Obviously, it diverges.\")\n\n    print(\"\")\n    print(\"(/!\\ backtracking)CURVE ON THE EXAMPLE f : x -> (x³+4*x²+4), WITH START POINT 5, 15 ITERATIONS OF THE NR WITH BACKTRACKING METHOD : ...\")\n\n    Newton_BT_error_curve(lambda A: np.array([(A[0]**3)+4*(A[0]**2)+4]),lambda A:  np.array([[3*(A[0]**2)+8*A[0]]]),np.array([5]),10,0.00001,np.array([-4.224169871088])) \n    print(\"... The zero is well calculated thank to the backtracking.\")\n\n", "meta": {"hexsha": "d74d6c7401f3b67ee95af51ca793f319bbcba238", "size": 7948, "ext": "py", "lang": "Python", "max_stars_repo_path": "NRMethod.py", "max_stars_repo_name": "clejacquet/algonum-p4", "max_stars_repo_head_hexsha": "a9a6605fa2928a48b922a6c99849e5dd01420fe8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NRMethod.py", "max_issues_repo_name": "clejacquet/algonum-p4", "max_issues_repo_head_hexsha": "a9a6605fa2928a48b922a6c99849e5dd01420fe8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NRMethod.py", "max_forks_repo_name": "clejacquet/algonum-p4", "max_forks_repo_head_hexsha": "a9a6605fa2928a48b922a6c99849e5dd01420fe8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8018018018, "max_line_length": 179, "alphanum_fraction": 0.5987669854, "include": true, "reason": "import numpy", "num_tokens": 2611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877709445759, "lm_q2_score": 0.9207896769778074, "lm_q1q2_score": 0.893799279054364}}
{"text": "import superimport\nimport jax.numpy as jnp\nimport matplotlib.pyplot as plt\nimport pyprobml_utils as pml\nfrom jax.scipy.stats import beta, bernoulli\n\n# Points where we evaluate the pdf\nx = jnp.linspace(0.001, 0.999, 100)\n\n\n# Forms graph given the parameters of the prior, likelihood and posterior:\ndef make_graph(data, save_name):\n    prior = beta.pdf(x, a=data[\"prior\"][\"a\"], b=data[\"prior\"][\"b\"])\n    n_0 = data[\"likelihood\"][\"n_0\"]\n    n_1 = data[\"likelihood\"][\"n_1\"]\n    samples = jnp.concatenate([jnp.zeros(n_0), jnp.ones(n_1)])\n    likelihood_function = jnp.vectorize(\n        lambda p: jnp.exp(bernoulli.logpmf(samples, p).sum())\n    )\n    likelihood = likelihood_function(x)\n    posterior = beta.pdf(x, a=data[\"posterior\"][\"a\"], b=data[\"posterior\"][\"b\"])\n\n    fig, ax = plt.subplots()\n    axt = ax.twinx()\n    fig1 = ax.plot(\n        x,\n        prior,\n        \"k\",\n        label=f\"prior Beta({data['prior']['a']}, {data['prior']['b']})\",\n        linewidth=2.0,\n    )\n    fig2 = axt.plot(x, likelihood, \"r:\", label=f\"likelihood Bernoulli\", linewidth=2.0)\n    fig3 = ax.plot(\n        x,\n        posterior,\n        \"b-.\",\n        label=f\"posterior Beta({data['posterior']['a']}, {data['posterior']['b']})\",\n        linewidth=2.0,\n    )\n    fig_list = fig1 + fig2 + fig3\n    labels = [fig.get_label() for fig in fig_list]\n    ax.legend(fig_list, labels, loc=\"upper left\", shadow=True)\n    axt.set_ylabel(\"Likelihood\")\n    ax.set_ylabel(\"Prior/Posterior\")\n    ax.set_title(f\"$N_0$:{n_0}, $N_1$:{n_1}\")\n    pml.savefig(save_name)\n\n\ndata1 = {\n    \"prior\": {\"a\": 1, \"b\": 1},\n    \"likelihood\": {\"n_0\": 1, \"n_1\": 4},\n    \"posterior\": {\"a\": 5, \"b\": 2},\n}\nmake_graph(data1, \"betaPostUninfSmallSample.pdf\")\n\ndata2 = {\n    \"prior\": {\"a\": 1, \"b\": 1},\n    \"likelihood\": {\"n_0\": 10, \"n_1\": 40},\n    \"posterior\": {\"a\": 41, \"b\": 11},\n}\nmake_graph(data2, \"betaPostUninfLargeSample.pdf\")\n\ndata3 = {\n    \"prior\": {\"a\": 2, \"b\": 2},\n    \"likelihood\": {\"n_0\": 1, \"n_1\": 4},\n    \"posterior\": {\"a\": 6, \"b\": 3},\n}\nmake_graph(data3, \"betaPostInfSmallSample.pdf\")\n\ndata4 = {\n    \"prior\": {\"a\": 2, \"b\": 2},\n    \"likelihood\": {\"n_0\": 10, \"n_1\": 40},\n    \"posterior\": {\"a\": 42, \"b\": 12},\n}\nmake_graph(data4, \"betaPostInfLargeSample.pdf\")\n\n\nplt.show()\n", "meta": {"hexsha": "97f573aa908a10b25134e474608740a851fdff02", "size": 2225, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/beta_binom_post_plot.py", "max_stars_repo_name": "peterchang0414/pyprobml", "max_stars_repo_head_hexsha": "4f5bb63e4423ecbfc2615b5aa794f529a0439bf8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/beta_binom_post_plot.py", "max_issues_repo_name": "peterchang0414/pyprobml", "max_issues_repo_head_hexsha": "4f5bb63e4423ecbfc2615b5aa794f529a0439bf8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2022-03-23T12:03:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T12:18:17.000Z", "max_forks_repo_path": "scripts/beta_binom_post_plot.py", "max_forks_repo_name": "peterchang0414/pyprobml", "max_forks_repo_head_hexsha": "4f5bb63e4423ecbfc2615b5aa794f529a0439bf8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-03-26T11:52:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:17:48.000Z", "avg_line_length": 28.164556962, "max_line_length": 86, "alphanum_fraction": 0.5842696629, "include": true, "reason": "import jax,from jax", "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.9324533051062238, "lm_q1q2_score": 0.8937916696703875}}
{"text": "import matplotlib.pyplot as plt\nfrom numpy import zeros, mod, diag, eye, sqrt, tile, r_, concatenate\n\nplt.style.use('seaborn')\n\nfrom FactorAnalysis import FactorAnalysis\nfrom NormalScenarios import NormalScenarios\n\n\ndef DimRedScenariosNormal(mu,sig2,k_,j_,method='Riccati',d=None):\n    # This function generates Monte Carlo Scenarios from a multivariate normal\n    # distribution with mean mu and covariance matrix sig2 through a dimension reduction\n    # algorithm resorting to a linear factor model, where the matrix of loadings\n    # is recovered through factor analysis of the correlation matrix\n    # INPUTS\n    # mu        :  [vector] (n_ x 1)  target mean\n    # sig2      :  [matrix] (n_ x n_) target positive definite covariance matrix\n    # k_        :  [scalar] number of factors to be considered for factor analysis (we reccomend k_ << n_)\n    # j_        :  [scalar] Number of scenarios. If not even, j_ <- j_+1\n    #   method  :  [string] Riccati (default), CPCA, PCA, LDL-Cholesky, Gram-Schmidt\n    #   d       :  [matrix] (k_ x n_) full rank constraints matrix for CPCA\n    # OUTPUTS\n    # X         :  [matrix] (n_ x j_) panel of MC scenarios drawn from normal\n    #                       distribution with mean mu and covariance matrix sig2\n    # beta      :  [matrix] (optional) (n_ x k_) loadings matrix ensuing from factor\n    # analysis of the correlation matrix\n    #\n    # For details on the exercise, see here .\n\n    ## Code\n\n    if mod(j_,2)!=0:\n        j_=j_+1\n\n    n_=sig2.shape[1]\n\n    #Step 1. Correlation\n    rho2=diag(diag(sig2)**(-1/2))@sig2@diag(diag(sig2)**(-1/2))\n\n    #Step 2. Factor Loadings\n    _, beta, _, _, _= FactorAnalysis(rho2,zeros((1,1)),k_)\n\n    #Step 3. Residual Standard Deviation\n    delta=sqrt(diag(eye((n_))-beta@beta.T))\n\n    #Step 4. Systematic scenarios\n    #sigm = r_[-1,r_[eye(k_),zeros((k_,n_))],r_[zeros((n_,k_)),eye(n_)]]\n    sigm = concatenate(( concatenate( (eye(k_),zeros((k_,n_)) ) ,axis=1) , concatenate((zeros((n_,k_)),eye(n_)),axis=1) ))\n    S,_=NormalScenarios(zeros((k_+n_,1)),sigm,j_,method,d)\n    Z_tilde=S[:k_,:]\n\n    #Step 5. Idiosyncratic scenarios\n    U_tilde=S[k_:k_+n_,:]\n\n    #Step 6. Output\n    X=tile(mu, (1,j_))+diag(sqrt(diag(sig2)))@(beta@Z_tilde+diag(delta)@U_tilde)\n    return X, beta\n\n", "meta": {"hexsha": "8dfc2a174b489f365a8670f95d3f51086d45ce93", "size": 2271, "ext": "py", "lang": "Python", "max_stars_repo_path": "functions_legacy/DimRedScenariosNormal.py", "max_stars_repo_name": "dpopadic/arpmRes", "max_stars_repo_head_hexsha": "ddcc4de713b46e3e9dcb77cc08c502ce4df54f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-04-10T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T08:20:42.000Z", "max_issues_repo_path": "functions_legacy/DimRedScenariosNormal.py", "max_issues_repo_name": "dpopadic/arpmRes", "max_issues_repo_head_hexsha": "ddcc4de713b46e3e9dcb77cc08c502ce4df54f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions_legacy/DimRedScenariosNormal.py", "max_forks_repo_name": "dpopadic/arpmRes", "max_forks_repo_head_hexsha": "ddcc4de713b46e3e9dcb77cc08c502ce4df54f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-08-13T22:02:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T17:49:12.000Z", "avg_line_length": 38.4915254237, "max_line_length": 122, "alphanum_fraction": 0.6481726112, "include": true, "reason": "from numpy", "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350252, "lm_q2_score": 0.9273632976542185, "lm_q1q2_score": 0.8937741472060555}}
{"text": "# Vectorizing the Haversine formula\n\n## Original function\nfrom numpy import sin, cos, pi, arcsin, sqrt\ndef get_distance(lat, lon, pcode_lat, pcode_lon):\n    \"\"\"\n    Find the distance between `(lat,lon)` and the reference point\n    `(pcode_lat,pcode_lon)`.\n    \"\"\"\n    RAD_FACTOR = pi / 180.0  # degrees to radians for trig functions\n    lat_in_rad = lat * RAD_FACTOR\n    lon_in_rad = lon * RAD_FACTOR\n    pcode_lat_in_rad = pcode_lat * RAD_FACTOR\n    pcode_lon_in_rad = pcode_lon * RAD_FACTOR\n\n    delta_lon = lon_in_rad - pcode_lon_in_rad\n    delta_lat = lat_in_rad - pcode_lat_in_rad\n\n    # Next two lines is the Haversine formula\n    inverse_angle = (sin(delta_lat / 2) ** 2 + cos(pcode_lat_in_rad) *\n                     cos(lat_in_rad) * sin(delta_lon / 2) ** 2)\n    haversine_angle = 2 * arcsin(sqrt(inverse_angle))\n    EARTH_RADIUS = 6367  # kilometers\n    return haversine_angle * EARTH_RADIUS\n\n# Random coordinates\nfrom numpy import random\ngodatadriven = (52.3905927,4.8412508)\n\n# First vectorization\npoints = random.randn(400000, 2) * 0.01\npoints[:, 0] = points[:, 0] + godatadriven[0]\npoints[:, 1] = points[:, 1] + godatadriven[1]\n# \"Scaling randn by 0.01 didn't require two for-loop for each of its elements: we simply told NumPy to multiply the whole array by 0.01 and it was done. The same when we added godatadriven[0] to points[:, 0]: we didn't have to write a for-loop for each element because once again NumPy took care of it.\"\n\n# Measuring time\ndef iterate_distance():\n    d = []\n    for p in points:\n        d.append(get_distance(p[0], p[1], godatadriven[0], godatadriven[1]))\n\nimport time\n\nt1 = time.time()\niterate_distance()  # runs in 3.53 seconds\nprint(\"Running time of iterate_distance():\\n{} us\".format(1000000 * (time.time() - t1)))\n\n# List comprehension\nt1 = time.time()\n[get_distance(p[0], p[1], godatadriven[0], godatadriven[1]) for p in points]\nprint(\"List comprehension time:\\n{} us\".format(1000000 * (time.time() - t1)))\n\n# Vectorized\nt1 = time.time()\nget_distance(points[:, 0], points[:, 0], godatadriven[0], godatadriven[1])\nprint(\"Vectorized time:\\n{} us\".format(1000000 * (time.time() - t1)))\n# We basically called the calculating function with the whole array on which it went through\n\n# Further times and details: http://nbviewer.ipython.org/gist/gglanzani/9271842\n", "meta": {"hexsha": "f310a9e1fb381029d2906240a65b083eaad9d669", "size": 2304, "ext": "py", "lang": "Python", "max_stars_repo_path": "CS fundamentals/Vectorization_examples/vectorized_operations.py", "max_stars_repo_name": "nocibambi/ds-practice", "max_stars_repo_head_hexsha": "9b6c4414f4700fb0bd017101b5a61c9d824a9b98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CS fundamentals/Vectorization_examples/vectorized_operations.py", "max_issues_repo_name": "nocibambi/ds-practice", "max_issues_repo_head_hexsha": "9b6c4414f4700fb0bd017101b5a61c9d824a9b98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CS fundamentals/Vectorization_examples/vectorized_operations.py", "max_forks_repo_name": "nocibambi/ds-practice", "max_forks_repo_head_hexsha": "9b6c4414f4700fb0bd017101b5a61c9d824a9b98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4, "max_line_length": 303, "alphanum_fraction": 0.7000868056, "include": true, "reason": "from numpy", "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899577232538, "lm_q2_score": 0.9252299565766113, "lm_q1q2_score": 0.8936792239002285}}
{"text": "# Question: https://projecteuler.net/problem=301\n\nimport numpy as np\n\n# According to this https://en.wikipedia.org/wiki/Nim, the next player loses when the XOR of 3 heaps is 0.\n# When XOR(n, 2n, 3n) == 0? It occurs when n has consecutive 1's.\n# Why?\n#           bit    b1 b2 b3\n# carry of n+2n     x  y  z   \n#             n = ..a  1  1...\n#            2n = ..1  1  b...\n#            3n = ..c  d  e...\n#  Case 1. z = 0\n#    Case 1.1. a = 0, b = 0\n#       -> cde = 001\n#       -> bit b1 of XOR(n, 2n, 3n) = 1 -> XOR != 0\n#    Case 1.2. a = 0, b = 1\n#       -> cde = 010\n#       -> bit b2 of XOR(n, 2n, 3n) = 1 -> XOR != 0\n#    Case 1.3. a = 1, b = 0\n#       -> cde = 101\n#       -> bit b1 of XOR(n, 2n, 3n) = 1 -> XOR != 0\n#    Case 1.4. a = 1, b = 1\n#       -> cde = 110\n#       -> bit b2 of XOR(n, 2n, 3n) = 1 -> XOR != 0\n#  Case 2. z = 1\n#    Case 2.1. b = 0\n#       -> d = 1\n#       -> bit b2 of XOR(n, 2n, 3n) = 1 -> XOR != 0\n#    Case 2.2. b=1\n#       -> e = 1\n#       -> bit b3 of XOR(n, 2n, 3n) = 1 -> XOR != 0\n\nN = 30 # 2^30 is 1000...000 with 30 zeros -> 31 digits in base 2 | we only need to count the case of <=30 digits and manually add the case of 2^30\n\n\n# DP[i][j] -> number of ways of generate a base 2 number of <=i-digit that ends with j\nDP = np.zeros((N+1, 2), dtype = np.uint32)\nDP[1][0] = 1\nDP[1][1] = 1\n\nfor i in range(2, N+1):\n    DP[i][0] = DP[i-1][0] + DP[i-1][1]\n    DP[i][1] = DP[i-1][0]\n\nprint(DP[N][0] + DP[N][1] + 1 - 1)\n#                         ^^^^^^^\n#                         add the case of 2^30, remove the case of 0\n", "meta": {"hexsha": "4c0afee586e8b586674a21bc6b5a8cf22bc3b3de", "size": 1553, "ext": "py", "lang": "Python", "max_stars_repo_path": "4th_100/problem301.py", "max_stars_repo_name": "takekoputa/project-euler", "max_stars_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4th_100/problem301.py", "max_issues_repo_name": "takekoputa/project-euler", "max_issues_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4th_100/problem301.py", "max_forks_repo_name": "takekoputa/project-euler", "max_forks_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-02T12:08:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T12:08:46.000Z", "avg_line_length": 31.693877551, "max_line_length": 146, "alphanum_fraction": 0.4571796523, "include": true, "reason": "import numpy", "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241974031599, "lm_q2_score": 0.9219218412907381, "lm_q1q2_score": 0.893641148877588}}
{"text": "import numpy as np\n\n#NumPy Array\n#How to create an empty and a full NumPy array?\nnp.empty([2, 2], dtype=int) #Return a new array of given shape and type, without initializing entries.\nnp.full([2, 2], 0) #Return a new array of given shape and type, filled with fill_value.\n\n#Create a Numpy array filled with all zeros\nnp.zeros((5,5), dtype=int) #Return a new array of given shape and type, filled with zeros.\n#Create a Numpy array filled with all ones\nnp.ones((5,5), dtype=int) #Return a new array of given shape and type, filled with ones.\n\n#Check whether a Numpy array contains a specified row\n#tolist Return the array as an a.ndim-levels deep nested list of Python scalars.\n[1, 1] in np.ones((2, 2)).tolist()\n\n#How to Remove rows in Numpy array that contains non-numeric values?\n#any Test whether any array element along a given axis evaluates to True.\n#isnan Test element-wise for NaN and return result as a boolean array.\nn_arr = np.array([[10.5, 22.5, 3.8], \n                  [41, np.nan, np.nan],\n                  [45.1, 16.2, 32.7]] )\nn_arr[~np.isnan(n_arr).any(axis=1)]\n\n#Remove single-dimensional entries from the shape of an array\n#squeeze Remove axes of length one from a.\nnp.squeeze(np.array([[[0], [1], [2]]]))\n\n#Find the number of occurrences of a sequence in a NumPy array\n#array_repr Return the string representation of an array.\nnp.array_repr(np.array([[2, 8, 9, 4],  \n                   [9, 4, 9, 4], \n                   [4, 5, 9, 7], \n                   [2, 9, 4, 3]])).count(\"9, 4\") \n\n#Find the most frequent value in a NumPy array\n#bincount Count number of occurrences of each value in array of non-negative ints.\n#argmax Returns the indices of the maximum values along an axis.\nnp.bincount(np.array([1,2,3,4,5,1,2,1,1,1]) ).argmax()\n\n#Combining a one and a two-dimensional NumPy Array\n#arrange Return evenly spaced values within a given interval.\n#reshape Gives a new shape to an array without changing its data.\n#nditer Efficient multi-dimensional iterator object to iterate over arrays.\nfor a, b in np.nditer([np.arange(5) , np.arange(10).reshape(2,5)]): \n    print(\"%d:%d\" % (a, b),)\n\n#How to build an array of all combinations of two NumPy arrays?\n#meshgrid Return coordinate matrices from coordinate vectors.\n#T The transposed array.\n#One shape dimension can be -1. In this case, the value is inferred \n# from the length of the array and remaining dimensions.\nnp.array(np.meshgrid(np.array([1, 2]) , np.array([4, 6]) )).T.reshape(-1, 2) \n\n#How to add a border around a NumPy array?\n#pad Pad an array.\nnp.pad(np.ones((2, 2)), pad_width=1, mode='constant', constant_values=0) \n\n#How to compare two NumPy arrays?\n#all Test whether all array elements along a given axis evaluate to True.\n(np.array([[1, 2], [3, 4]]) == np.array([[1, 2], [3, 4]])).all()\n\n#How to check whether specified values are present in NumPy array?\n10 in np.array([[2, 3, 0], [4, 1, 6]]) \n100 in np.array([[2, 3, 0], [4, 1, 6]]) \n2 in np.array([[2, 3, 0], [4, 1, 6]])  \n\n#How to get all 2D diagonals of a 3D NumPy array?\n#diagonal Return specified diagonals.\nnp.diagonal(np.arange(3 * 4 * 4).reshape(3, 4, 4),  axis1 = 1, axis2 = 2) \n\n#Flatten a Matrix in Python using NumPy\n#flatten Return a copy of the array collapsed into one dimension.\nnp.array([[2, 3], [4, 5]]).flatten() \n\n#Flatten a 2d numpy array into 1d array\n#flatten Return a copy of the array collapsed into one dimension.\nnp.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]]).flatten() \n\n#Move axes of an array to new positions\n#moveaxis Move axes of an array to new positions. Other axes remain in\n#  their original order.\nnp.moveaxis(np.zeros((1, 2, 3, 4)), 0, -1)\n\n#Interchange two axes of an array\n#swapaxes Interchange two axes of an array.\nnp.swapaxes(np.array([[2, 4, 6]]) , 0, 1)\n\n#NumPy – Fibonacci Series using Binet Formula\n#N is the first N numbers of Fibonacci\nN = 11\na = np.arange(1, N)   \n# splitting of terms for easiness \nsqrtFive = np.sqrt(5) \nalpha = (1 + sqrtFive) / 2\nbeta = (1 - sqrtFive) / 2\n# Implementation of formula \n# np.rint is used for rounding off to integer \nFn = np.rint(((alpha ** a) - (beta ** a)) / (sqrtFive)) \nFn\n\n#Counts the number of non-zero values in the array\n#count_nonzero Counts the number of non-zero values in the array a.\nnp.count_nonzero(np.array([[0, 1, 7, 0], [3, 0, 2, 19]]))\n\n#Count the number of elements along a given axis\n#size Return the number of elements along a give-n axis.\nnp.size(np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), axis=0)\n\n#Trim the leading and/or trailing zeros from a 1-D array\n#trim_zeros Trim the leading and/or trailing zeros from a 1-D array or sequence.\nnp.trim_zeros(np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0)))\n\n#Change data type of given numpy array\n#astype Copy of the array, cast to a specified type.\nnp.array([10, 20, 30, 40, 50]).astype('float64')\n\n#Reverse a numpy array\n#flip Reverse the order of elements in an array along the given axis.\nnp.flip(np.array([10, 20, 30, 40, 50]), 0)\n\n#How to make a NumPy array read-only?\n#flags Information about the memory layout of the array.\n#WRITEABLE can only be set True if the array owns its own memory or the \n# ultimate owner of the memory exposes a writeable buffer interface or is a string.\nnp.zeros(11).flags.writeable = False", "meta": {"hexsha": "114088da3aed3f37bef5cd262286a4bb31445775", "size": 5206, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumpyTutorial/NumPy Array.py", "max_stars_repo_name": "CarlosW1998/DigitalImageProcessing", "max_stars_repo_head_hexsha": "69365877e07b676f13487585ffdf029a243b0fa8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-09T19:54:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:54:48.000Z", "max_issues_repo_path": "NumpyTutorial/NumPy Array.py", "max_issues_repo_name": "CarlosW1998/DigitalImageProcessingClass", "max_issues_repo_head_hexsha": "69365877e07b676f13487585ffdf029a243b0fa8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumpyTutorial/NumPy Array.py", "max_forks_repo_name": "CarlosW1998/DigitalImageProcessingClass", "max_forks_repo_head_hexsha": "69365877e07b676f13487585ffdf029a243b0fa8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3174603175, "max_line_length": 102, "alphanum_fraction": 0.6905493661, "include": true, "reason": "import numpy", "num_tokens": 1600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574122783325, "lm_q2_score": 0.93812402119614, "lm_q1q2_score": 0.8936326665528784}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import axes3d\r\nfrom matplotlib import cm\r\nimport scipy as sp\r\nfrom scipy.sparse import csr_matrix, linalg\r\nfrom scipy.stats import linregress\r\nfrom scipy import linalg, optimize\r\n\r\n# Escriba dos funciones que calculen A_h y b_h. La entrada debe ser N,f,g\r\n\r\n\r\ndef calcula_A(n):\r\n    N = n+1\r\n    h = 1/N\r\n    down = np.ones(N-2)\r\n    center = np.ones(N-1)\r\n    upper = np.ones(N-2)\r\n    d1 = -down\r\n    d2 = 4*center\r\n    d3 = -1*upper\r\n    d = np.array([d1, d2, d3])\r\n    offset = [-1, 0, 1]\r\n    L4 = sp.sparse.diags(d, offset)\r\n\r\n    dd1 = -down\r\n    dd2 = np.zeros(N-1)\r\n    dd3 = -upper\r\n    dd = np.array([dd1, dd2, dd3])\r\n    A1 = sp.sparse.diags(dd, offset)\r\n\r\n    I = np.identity(N-1)\r\n\r\n    L = sp.sparse.kron(A1, I)\r\n    R = sp.sparse.kron(I, L4)\r\n\r\n    A = (L + R) / h**2\r\n    return A\r\n\r\n\r\ndef g(x,y):\r\n    if y==1 and x<1 and x>0:\r\n        return np.sin(2*np.pi*x)\r\n    else:\r\n        return 0\r\n\r\n\r\nf = lambda x,y: 8*np.pi**2*np.sin(2*np.pi*x)*np.sin(2*np.pi*y)\r\n\r\n\r\ndef calcula_b(N, f, g):\r\n    f_h = np.zeros((N+1)**2)\r\n    g_h = np.zeros((N+1)**2)\r\n    x = np.linspace(0,1,N+1)\r\n    y = np.linspace(0,1,N+1)\r\n    h = 1 / N\r\n\r\n    for j in range(len(x)):\r\n        for k in range(len(y)):\r\n            f_h[(k)*(N)+j] = f(x[j], y[k])\r\n\r\n    g_h[1]=N**2*(g(x[1],0)+g(0,y[1]))\r\n    g_h[N-1]=N**2*(g(x[N-1],0)+g(1,y[1]))\r\n    g_h[(N-1)**2-(N-2)]=N**2*(g(x[1],1)+g(0,y[N-1]))\r\n    g_h[(N-1)**2]=N**2*(g(x[N-1],1)+g(1,y[N-1]))\r\n    for j in range(2,N-1):#esto es para j in {2,...,N-2}\r\n        g_h[j]=N**2*g(x[j],0)\r\n        g_h[(N-1)*(N-2)+j]=N**2*g(x[j],1)\r\n        g_h[j*(N-1)+1]=N**2*(g(0,y[j]))\r\n        g_h[j*(N-1)]=N**2*g(1,y[j])\r\n\r\n    b_h = f_h + g_h\r\n    return b_h[N+1:-N]\r\n\r\n## Parte 2\r\n# Para N en {4,16}, grafique la solución numérica y la solución única de\r\n# la ecuación.\r\n\r\nN = [4, 16]\r\n\r\nfor i in range(2):\r\n    u = sp.sparse.linalg.spsolve(calcula_A(N[i]), calcula_b(N[i], f, g))\r\n    U = np.zeros((N[i], N[i]))\r\n    counter = 0\r\n    for j in range(N[i]):\r\n        for k in range(N[i]):\r\n            U[k][j] = u[k + j*(N[i])]\r\n\r\n    x = np.linspace(0,1, N[i])\r\n\r\n    X, Y = np.meshgrid(x, x)\r\n    fig = plt.figure(i)\r\n    fig.clf()\r\n    ax = fig.add_subplot(111, projection='3d', elev=15, azim=10)\r\n    ax.plot_surface(X, Y, np.transpose(U)) #, rstride=2, cstride=2, cmap=cm.plasma\r\n    #ax.dist = 1\r\n    ax.set_xlabel('x')\r\n    ax.set_ylabel('y')\r\n    ax.set_zlabel('u')\r\n    fig.show()\r\n    \r\n\r\n# Parte 3\r\n#\r\n# para N en {4,8,16,32,64} , calcule el error en norma L2.\r\n\r\narreglo_N = [4, 8, 16, 32, 64]\r\nerrores_norm_2 = []\r\n\r\nfor i in range(len(arreglo_N)):\r\n    N = arreglo_N[i]\r\n    h = 1 / N\r\n\r\n    u = sp.sparse.linalg.spsolve(calcula_A(N), calcula_b(N, f, g))\r\n    U = np.zeros((N+1, N+1))\r\n    \r\n    for j in range(N):\r\n        for k in range(N):\r\n            U[k][j] = u[k + j*(N)]\r\n\r\n    x = np.linspace(0,1,N+1)\r\n    y = np.linspace(0,1,N+1)\r\n    u_analitico = lambda x,y: np.sin(2*np.pi*x)*(np.sin(2*np.pi*y) + (np.sinh(2*np.pi*y) / np.sinh(2*np.pi)))\r\n    U_analitico = np.zeros((N+1, N+1))\r\n\r\n    for j in range(N+1):\r\n        for k in range(N+1):    \r\n            U_analitico[j][k] = u_analitico(x[j], y[k])\r\n    \r\n    err = h * np.linalg.norm(U_analitico - U, 2)\r\n    errores_norm_2.append(err)\r\n\r\n\r\n# Grafique los respectivos valores en función de h, en escala logarítmica\r\n# usando log log ¿qué puede observar?\r\n\r\n\r\n\"\"\" arreglo_N = [ 2**(i) for i in range(2,7)]\r\narreglo_condicion_A_h = []\r\n\r\nfor N in arreglo_N:\r\n    # cambiar por matriz A_h\r\n    A_h = np.identity( (N-1)**2 )\r\n    condicion_A_h = np.linalg.cond(A_h, p = 2)\r\n    arreglo_condicion_A_h.append(condicion_A_h)\r\n\r\narreglo_h   = np.divide(1,arreglo_N)\r\narreglo_N_2 = np.multiply(arreglo_N,arreglo_N) \r\n\r\ncondicion_fig,condicion_ax = plt.subplots(2)\r\ncondicion_h  = condicion_ax[0]\r\ncondicion_n2 = condicion_ax[1]\r\n\r\ncondicion_h.loglog(arreglo_h,arreglo_condicion_A_h)\r\ncondicion_n2.loglog(arreglo_N_2,arreglo_condicion_A_h)\r\n\r\nplt.show() \"\"\"\r\n\r\n\r\n# Calcule el orden de error experimental, es decir, estime mediante\r\n# regresión lineal el valor de p tal que e_h sea de orden O(h^p)\r\n\r\n", "meta": {"hexsha": "9aa9229bf3ac9a1cab4c9619aa98843f61c87c97", "size": 4172, "ext": "py", "lang": "Python", "max_stars_repo_path": "nacho.py", "max_stars_repo_name": "JavierMonreal/Lab-2-EDPn", "max_stars_repo_head_hexsha": "0f860337010dfbe3289669b55a28981ebb8bc866", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nacho.py", "max_issues_repo_name": "JavierMonreal/Lab-2-EDPn", "max_issues_repo_head_hexsha": "0f860337010dfbe3289669b55a28981ebb8bc866", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nacho.py", "max_forks_repo_name": "JavierMonreal/Lab-2-EDPn", "max_forks_repo_head_hexsha": "0f860337010dfbe3289669b55a28981ebb8bc866", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5950920245, "max_line_length": 110, "alphanum_fraction": 0.5515340364, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778048911611, "lm_q2_score": 0.9334308142702336, "lm_q1q2_score": 0.8935526009023783}}
{"text": "import numpy as np\n\ndef integrate_trap(f, a, b, n):\n    # Implementation of the trapezoidal rule\n    h = (b-a)/n\n    x = np.linspace(a, b, n+1) \n    i=1\n    area = h*(f(x[0]) + f(x[n]))/2\n    while i<n:\n        sup_rect = f(x[i])*h\n        area += sup_rect \n        i += 1 \n    return area\n\n'''\nWe test the trapezoidal rule on the known sine funcion were the  \ndefinite integral in the interval [0, %*\\textcolor{codeviolet}{$\\pi$}*)/2] is equal to 1. \n'''\n\nsup_5 = integrate_trap(np.sin, 0, np.pi/2, 5)\nsup_10 = integrate_trap(np.sin, 0, np.pi/2, 10)\n\nprint('Using n=5, the trapezoidal rule returns a value of {:.2f}'.format(sup_5))\nprint('Using n=10, the trapezoidal rule returns a value of {:.2f}'.format(sup_10))\n   \n'''\nOutput:\nUsing n=5, the trapezoidal rule returns a value of 0.99\nUsing n=10, the trapezoidal rule returns a value of 1.00\n'''\n \n", "meta": {"hexsha": "0da6546b337a687b17dca0a42c7a854cfa42ce7b", "size": 851, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/chapter_07/listing_07_02.py", "max_stars_repo_name": "guinslym/python_earth_science_book", "max_stars_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80, "max_stars_repo_stars_event_min_datetime": "2021-04-19T10:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:34:47.000Z", "max_issues_repo_path": "code/chapter_07/listing_07_02.py", "max_issues_repo_name": "guinslym/python_earth_science_book", "max_issues_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/chapter_07/listing_07_02.py", "max_forks_repo_name": "guinslym/python_earth_science_book", "max_forks_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2021-04-25T03:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:06:19.000Z", "avg_line_length": 26.59375, "max_line_length": 90, "alphanum_fraction": 0.6286721504, "include": true, "reason": "import numpy", "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307661011976, "lm_q2_score": 0.9184802417938535, "lm_q1q2_score": 0.8935258372731276}}
{"text": "import numpy as np\n\na0 = 3.56\na1 = 1.4859\na2 = 2.025\n\nx = np.array([1,2,3,4,5])\ny = np.array([7.7, 14.5, 26, 40, 62])\n\nxm = np.mean(x).round(4)\nym = np.mean(y).round(4)\n\nprint('mean of x: ' + str(xm))\nprint('mean of y: ' + str(ym))\n\nst = lambda yi : np.square(yi - ym).round(4)\nsr = lambda xi,yi : np.square(yi-a0-a1*xi-a2*np.square(xi)).round(4)\n\ndef printline(): print('----------------------------------------------------------------------')\n\nST = 0\nSR = 0\n\nprintline()\nprint('xi\\t\\tyi\\t\\t(yi-ym)^2\\t(yi-a0-a1xi-a2xi^2)^2')\nprintline()\nfor i in range(len(x)):\n    St = st(y[i])\n    Sr = sr(x[i],y[i])\n    ST = ST + St\n    SR = SR + Sr\n    print(str(x[i]) + '\\t\\t' + str(y[i]) + '\\t\\t' + str(St) + '\\t\\t' + str(Sr))\n\nprintline()\nprint('\\t\\t\\t\\t' + str(ST) + '\\t\\t' + str(SR))\n\nn = len(x)\n\n#S_yx = np.sqrt((SR/(n-2)))\n\nS_y = np.sqrt((SR/(n-3)))\nr2 = (ST-SR)/ST\n\nprint('Standard error: %f' %S_y)\nprint('Co-efficient of determination: %f' %r2)", "meta": {"hexsha": "842cf6109379393d11e4922ae6f2a723a613c55b", "size": 942, "ext": "py", "lang": "Python", "max_stars_repo_path": "problem solutions/error_calc.py", "max_stars_repo_name": "suhailnajeeb/numerical-methods", "max_stars_repo_head_hexsha": "b5f6189e5072407004e97d37edc83356e43449e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problem solutions/error_calc.py", "max_issues_repo_name": "suhailnajeeb/numerical-methods", "max_issues_repo_head_hexsha": "b5f6189e5072407004e97d37edc83356e43449e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem solutions/error_calc.py", "max_forks_repo_name": "suhailnajeeb/numerical-methods", "max_forks_repo_head_hexsha": "b5f6189e5072407004e97d37edc83356e43449e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-12T09:12:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-12T09:12:50.000Z", "avg_line_length": 20.9333333333, "max_line_length": 96, "alphanum_fraction": 0.5042462845, "include": true, "reason": "import numpy", "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992960608886, "lm_q2_score": 0.9230391558355999, "lm_q1q2_score": 0.8934089491699141}}
{"text": "\r\n# Experiment 01  Calculating the value of pi using Monte Carlo methods\r\n'''\r\nInscribe circle into a square centered at the origin\r\nA_c = pi*r^2\r\nA_s = L*W = (2r)(2r) = 4r^2\r\n(A_c/A_s) = (pi*r^2)/(4*r^2) = pi/4\r\npi = 4*A_c/A_s = 4*N_c/N_s\r\nN_c <= N_s\r\n'''\r\n#%matplotlib\r\n# Section A of Monte Carlo Lab\r\nfrom numpy import random\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\n\r\n#storing vslues of pi\r\npi_values =[]\r\n\r\nfor i in range(1, 500):\r\n\r\n#Number of dots \r\n    N= 1000\r\n#circle coordinates\r\n    circle_x =[]\r\n    circle_y=[]\r\n# Square Coordinates \r\n    square_x = [] \r\n    square_y = []\r\n# Initialize Index\r\n    j = 1\r\n# create randomized (x,y) values from [-1, 1]\r\n    while j <= N:\r\n        x = random.uniform(-1, 1)\r\n        y = random.uniform(-1, 1)\r\n        if (x**2 + y**2 <= 1.0):\r\n            circle_x.append(x)\r\n            circle_y.append(y)\r\n        else:\r\n            square_x.append(x)\r\n            square_y.append(y)\r\n        j += 1\r\n    \r\n    pi = 4.0*len(circle_x)/float(N)\r\n\r\n#Append the values of pi in list\r\n    pi_values.append(pi)\r\n\r\n#Calculatiing the errors\r\n    avg_pi_errors = [abs(math.pi - pi) for pi in pi_values]\r\n\r\n#Print the final value of Pi for each run\r\nprint (pi_values[-1])\r\nprint (avg_pi_errors[-1])\r\n#Plot the Pi values\r\nplt.axhline(y=math.pi, color='g', linestyle='-')\r\nplt.plot(pi_values)\r\nplt.ylim(2, 4)\r\nplt.xlabel(\"Interations\")\r\nplt.ylabel(\"Value of Pi\")\r\nplt.show()\r\n     \r\n\r\n#Plot the error in the calculation\r\nplt.axhline(y=0.0, color=\"g\", linestyle=\"-\")\r\nplt.plot(avg_pi_errors)\r\nplt.xlabel(\"Interations\")\r\nplt.ylabel(\"Error\")\r\nplt.show()\r\n\r\n\r\n# Ploting circle and square\r\n\r\nplt.plot(circle_x,circle_y, 'r.')\r\nplt.plot(square_x, square_y, 'b.')\r\nplt.grid()\r\nplt.show()\r\n\r\n\r\nN = float(N)\r\np = len(circle_x)/N\r\nmu = N*p\r\ns = np.sqrt(N*p*(1-p))\r\n'''\r\ndpi/pi = s/mu\r\ndpi = pi*s/mu \r\n'''\r\n# Counts in Square\r\nNs = N \r\n# Counts in Circle\r\nNc = len(circle_x) \r\n\r\n#dpi = pi*s/mu\r\n#dpi2 = 4.*np.sqrt(Nc*(1.-Nc/Ns))/Ns # Double Checking Pi Error\r\n\r\ndpi=pi*np.sqrt((1./Nc + 1./Ns))\r\n\r\n\r\nprint(\"Pi is approximately : {:5.4f} +/- {:5.4f} \".format(pi,dpi))\r\nprint(\"Pi actually is :\", np.pi)\r\nprint(\"The relative uncertainty is: {:.5f} %\".format(100.*dpi/pi))\r\n\r\n# Desired Relative Uncertainty [%]\r\ne = [1.,0.1, 0.01, 0.00001] \r\n\r\n\r\n#Ne = (4.-np.pi)*(1./np.pi)*(100./e[i])**2 \r\n# Approximate Number of events\r\n\r\n\r\nfor j in range(len(e)):\r\n\r\n    Ne = (4.+np.pi)*(1./np.pi)*(100./e[j])**2 \r\n    \r\n    print(\"Events required to obtain a statistical uncertainty\\n\\\r\nof {:.5} % is: {:} +/- {:}\".format(e[j],int(Ne),np.sqrt(int(Ne))))\r\n    print(\"Events required to obtain a statistical uncertainty\\ n \\\r\nof {:.5} % is: {:} +/- {:}\".format(e[j],int(Ne),np.sqrt(int(Ne))))\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "28168a45d2a4800baa477c2d4f71066832bca058", "size": 2733, "ext": "py", "lang": "Python", "max_stars_repo_path": "MontePartA_inclass.py", "max_stars_repo_name": "layanamich/monte_carlo", "max_stars_repo_head_hexsha": "04cc4e8d907cac24510e97c6e8896f7055cd5f40", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MontePartA_inclass.py", "max_issues_repo_name": "layanamich/monte_carlo", "max_issues_repo_head_hexsha": "04cc4e8d907cac24510e97c6e8896f7055cd5f40", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MontePartA_inclass.py", "max_forks_repo_name": "layanamich/monte_carlo", "max_forks_repo_head_hexsha": "04cc4e8d907cac24510e97c6e8896f7055cd5f40", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0403225806, "max_line_length": 71, "alphanum_fraction": 0.5843395536, "include": true, "reason": "import numpy,from numpy", "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9817357195106375, "lm_q2_score": 0.9099070035949657, "lm_q1q2_score": 0.8932882068620719}}
{"text": "import torch\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass PolyRegression(nn.Module):\n    \"\"\" Polynomial Regression module\n\n    this will compute the polynomial regression with degree specified.\n    for example, degree of 1 is the model for linear regression `y = a*x + b`,\n    degree of 2 is the model for quadratic regression `y = a*(x^2) + b*x + c`, etc.\n\n    keep in mind to always normalise, with interval of (0, 1], the data (`x` variable)\n    you input to the model, if you don't want to cause a gradient explosion because \n    the output value is too big to handle.\n\n    Args:\n        degree (int): the degree of polynomial regression\n\n    \"\"\"\n    def __init__(self, degree):\n        super(PolyRegression, self).__init__()\n        self.degree = degree\n\n        self.weight = nn.Parameter(torch.randn([degree+1, 1]))\n    \n    def regress_forward(self, x):\n        x = torch.flatten(x)\n        f = torch.stack([x.pow(a) for a in range(self.degree, -1, -1)], 1)\n        y = f @ self.weight\n        return y.squeeze()\n\n    def forward(self, x):\n        return self.regress_forward(x)\n    \n    def get_weight(self):\n        return self.weight.detach().numpy().flatten()\n\n\ndef compute_r2(y, yreg):\n    if isinstance(y, torch.Tensor):\n        y = np.array(y.detach())\n    if isinstance(yreg, torch.Tensor):\n        yreg = np.array(yreg.detach())\n\n    ss_tot = np.square(y - y.mean()).sum()\n    ss_res = np.square(y - yreg).sum()\n    return 1 - (ss_res/ss_tot)\n\ndef normalise(x):\n    return (x - x.mean()) / x.std()\n\ndef fit(model, x, y, iteration=1000):\n    if not isinstance(x, torch.Tensor):\n        x = torch.tensor(x) \n    if not isinstance(y, torch.Tensor):\n        y = torch.tensor(y)\n\n    criterion = nn.MSELoss()\n    optim = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.95)\n\n    loss_data = []\n    for _ in range(iteration):\n        yreg = model(x)\n        loss = criterion(yreg, y)\n\n        loss_data.append(loss.detach().item())\n\n        optim.zero_grad()\n        loss.backward()\n        optim.step()\n\n    return model.get_weight(), loss_data\n\n\nif __name__ == \"__main__\":\n    torch.manual_seed(123)      # uncomment this if you want a non-deterministic result\n\n    x = normalise(torch.randn(10))\n    y = 0.5*x.pow(3) + 7*x.pow(2) + 5*x + 2\n    degree = 3\n\n    model = PolyRegression(degree)\n    weight, loss_data = fit(model, x, y)\n\n    yreg = model(x)\n    print(weight)\n    print(\"R2: \", compute_r2(y, yreg))\n\n    ## plot regression\n    x_reg = torch.tensor(np.linspace(x.min(), x.max(), 200, endpoint=False), dtype=torch.float32)\n    y_reg = model(x_reg).detach().numpy()\n    x_reg = x_reg.numpy()\n    plt.plot(x_reg, y_reg, color='#a7de77', label=f'Polynomial Regression, degree {degree}')\n    plt.scatter(x, y, color='#9b354c', label='Data Point')\n    plt.legend()\n    # plt.plot(loss_data)\n    plt.show()\n", "meta": {"hexsha": "487780b0d531bdeb66d3ff9296f479b04611bd36", "size": 2867, "ext": "py", "lang": "Python", "max_stars_repo_path": "pytorch.py", "max_stars_repo_name": "reshalfahsi/regression", "max_stars_repo_head_hexsha": "31c34041a619e3a45825f98de093d36d43721d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pytorch.py", "max_issues_repo_name": "reshalfahsi/regression", "max_issues_repo_head_hexsha": "31c34041a619e3a45825f98de093d36d43721d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-03-19T16:14:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T23:54:21.000Z", "max_forks_repo_path": "pytorch.py", "max_forks_repo_name": "reshalfahsi/regression", "max_forks_repo_head_hexsha": "31c34041a619e3a45825f98de093d36d43721d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-19T14:48:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-19T14:48:24.000Z", "avg_line_length": 28.67, "max_line_length": 97, "alphanum_fraction": 0.6212068364, "include": true, "reason": "import numpy", "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.963230536035447, "lm_q2_score": 0.9273632941410888, "lm_q1q2_score": 0.8932646429151188}}
{"text": "# coding=utf8\n\nimport numpy as np\nfrom scipy import stats\n\n\nclass Correlation:\n    def __init__(self, arr1, arr2):\n        self.arr1 = np.array(arr1)\n        self.arr2 = np.array(arr2)\n        if arr1.shape[0] != arr2.shape[0]:\n            raise Exception('two arr length must be the same')\n        self.length = self.arr1.shape[0]\n\n    def use_scipy_normalize(self):\n        # ddof=1 means divide n-1, ddof=0(default) means divide n\n        return stats.zscore(self.arr1, ddof=1), stats.zscore(self.arr2, ddof=1)\n\n    def normalize_with_n(self):\n        mean_1, mean_2 = np.mean(self.arr1), np.mean(self.arr2)\n        var1, var2 = np.sum((self.arr1 - mean_1) ** 2) / self.length, np.sum((self.arr2 - mean_2) ** 2) / self.length\n        std1, std2 = np.sqrt(var1), np.sqrt(var2)\n        return (self.arr1 - mean_1) / std1, (self.arr2 - mean_2) / std2\n\n    def normalize_with_n_1(self):\n        \"\"\"\n        divide n-1\n        :return: normalized arr1, arr2\n        \"\"\"\n        mean_1, mean_2 = np.mean(self.arr1), np.mean(self.arr2)\n        var1, var2 = np.sum((self.arr1 - mean_1) ** 2) / \\\n            (self.length - 1), np.sum((self.arr2 - mean_2) ** 2) / (self.length - 1)\n        std1, std2 = np.sqrt(var1), np.sqrt(var2)\n        return (self.arr1 - mean_1) / std1, (self.arr2 - mean_2) / std2\n\n    def get_correlation_index(self):\n        arr1, arr2 = self.normalize_with_n()\n        return np.sum(arr1 * arr2) / self.length\n\n\nif __name__ == '__main__':\n    # test if scipy.stats divide n or n - 1 to normalize data\n    arr1 = np.array([74, 76, 77, 63, 63, 61, 72], dtype=np.float)\n    arr2 = np.array([84, 83, 85, 74, 75, 81, 73], dtype=np.float)\n    correlation = Correlation(arr1, arr2)\n    print('scipy.stats get normalize data is: \\n', correlation.use_scipy_normalize())\n    print('divide n to normalize data is:\\n', correlation.normalize_with_n())\n    print('divide n - 1 to normalize data is:\\n', correlation.normalize_with_n_1())\n    print('actually in scipy.stats, zscore function params ddof=1 means divide n-1, ddof=0(default) means divide n')\n\n    # test correlation index\n    print('correlation index is ', correlation.get_correlation_index())\n\n", "meta": {"hexsha": "8f3fd015810d9cc16c95a7767eeb69dec974ad6f", "size": 2163, "ext": "py", "lang": "Python", "max_stars_repo_path": "stat/statistic/correlation.py", "max_stars_repo_name": "ZhoufeifeiJAVA/machine_learning", "max_stars_repo_head_hexsha": "55e9e821c7b3e4d727ca6120433aa486ac466580", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stat/statistic/correlation.py", "max_issues_repo_name": "ZhoufeifeiJAVA/machine_learning", "max_issues_repo_head_hexsha": "55e9e821c7b3e4d727ca6120433aa486ac466580", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stat/statistic/correlation.py", "max_forks_repo_name": "ZhoufeifeiJAVA/machine_learning", "max_forks_repo_head_hexsha": "55e9e821c7b3e4d727ca6120433aa486ac466580", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0555555556, "max_line_length": 117, "alphanum_fraction": 0.6282940361, "include": true, "reason": "import numpy,from scipy", "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305328688783, "lm_q2_score": 0.9273632916317102, "lm_q1q2_score": 0.8932646375614491}}
{"text": "\n\"\"\"\nexample of calculations Lp norm for vector and matrix\n\"\"\"\n\nimport numpy as np\n\ndef L1_norm(vec):\n    return np.sum(np.abs(vec))\n\ndef L2_norm(vec):\n    return np.sum(np.abs(vec) ** 2) ** 0.5\n\ndef Linf_norm(vec):\n    return np.max(vec)\n\ndef Lp_norm(vec, p=2):\n    if p < 1:\n        raise Exception('p should be more or equal 1. {} given.'.format(p))\n    return np.sum(np.abs(vec) ** p) ** (1 / p)\n\ndef Frobenius_norm(matrix):\n    return np.sum(np.abs(matrix) ** 2) ** 0.5\n\nif __name__ in '__main__':\n    VECTOR = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n    print('vector    : {}'.format(VECTOR))\n    print('L1 norm   : {:.2f}'.format(L1_norm(VECTOR)))\n    print('L2 norm   : {:.2f}'.format(L2_norm(VECTOR)))\n    for p in range(3, 6):\n        print('L{} norm   : {:.2f}'.format(p, Lp_norm(VECTOR, p)))\n    print('Linf norm : {:.2f}'.format(Linf_norm(VECTOR)))\n\n    MATRIX = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n    print('')\n    print('matrix: {}'.format(MATRIX))\n    print('Frobenius norm: {:.2f}'.format(Frobenius_norm(MATRIX)))\n", "meta": {"hexsha": "610e91e1d69a85172cfd20382eedd6e7e88115ef", "size": 1018, "ext": "py", "lang": "Python", "max_stars_repo_path": "preprocessing/lp_norm.py", "max_stars_repo_name": "dsysoev/fun-with-tensorflow", "max_stars_repo_head_hexsha": "3be8ea9dcb7960b946c5b2430b63e2cf981e5437", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "preprocessing/lp_norm.py", "max_issues_repo_name": "dsysoev/fun-with-tensorflow", "max_issues_repo_head_hexsha": "3be8ea9dcb7960b946c5b2430b63e2cf981e5437", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-12T01:03:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T01:03:22.000Z", "max_forks_repo_path": "preprocessing/lp_norm.py", "max_forks_repo_name": "dsysoev/fun-with-tensorflow", "max_forks_repo_head_hexsha": "3be8ea9dcb7960b946c5b2430b63e2cf981e5437", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7894736842, "max_line_length": 75, "alphanum_fraction": 0.5746561886, "include": true, "reason": "import numpy", "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9802808672839539, "lm_q2_score": 0.9111796985551102, "lm_q1q2_score": 0.8932120251511351}}
{"text": "\nimport numpy as np\n\n\n######################################################################################################\n# NumPy Matrix multiplication \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n######################################################################################################\n#\n# You've heard a lot about matrix multiplication in the last few videos – now you'll get to see how to\n# do it with NumPy. However, it's important to know that NumPy supports several types of matrix multiplication.\n#\n# Element-wise Multiplication\n# You saw some element-wise multiplication already. You accomplish that with the multiply function or the * operator.\n#  Just to revisit, it would look like this:\n\nm = np.array([[1,2,3],[4,5,6]])\nprint(m)\n# displays the following result:\n# array([[1, 2, 3],\n#        [4, 5, 6]])\n\nn = m * 0.25\nprint(n)\n# displays the following result:\n# array([[ 0.25,  0.5 ,  0.75],\n#        [ 1.  ,  1.25,  1.5 ]])\n\nprint(m * n)\n# displays the following result:\n# array([[ 0.25,  1.  ,  2.25],\n#        [ 4.  ,  6.25,  9.  ]])\n\nprint(np.multiply(m, n))   # equivalent to m * n\n# displays the following result:\n# array([[ 0.25,  1.  ,  2.25],\n#        [ 4.  ,  6.25,  9.  ]])\n\n# Matrix Product\n# To find the matrix product, you use NumPy's matmul function.\n#\n# If your have compatible shapes, the it's as simple as this:\n\na = np.array([[1,2,3,4],[5,6,7,8]])\nprint(a)\n# displays the following result:\n# array([[1, 2, 3, 4],\n#        [5, 6, 7, 8]])\n\nprint(a.shape)\n# displays the following result:\n# (2, 4)\n\nb = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])\nprint(b)\n# displays the following result:\n# array([[ 1,  2,  3],\n#        [ 4,  5,  6],\n#        [ 7,  8,  9],\n#        [10, 11, 12]])\n\nprint(b.shape)\n# displays the following result:\n# (4, 3)\n\nc = np.matmul(a, b)\nprint('A matmul B:\\n', c)\n# displays the following result:\n# array([[ 70,  80,  90],\n#        [158, 184, 210]])\n\nprint(c.shape)\n# displays the following result:\n# (2, 3)\n\n\n# NumPy's dot function\n# You may sometimes see NumPy's dot function in places where you would expect a matmul. \n# It turns out that the results of dot and matmul are the same if the matrices are two dimensional.\n#\n# So these two results are equivalent:\n\na = np.array([[1,2],[3,4]])\nprint(a)\n# displays the following result:\n# array([[1, 2],\n#        [3, 4]])\n\nnp.dot(a, a)\n# displays the following result:\n# array([[ 7, 10],\n#        [15, 22]])\n\nprint(a.dot(a))  # you can call `dot` directly on the `ndarray`\n# displays the following result:\n# array([[ 7, 10],\n#        [15, 22]])\n\nprint(np.matmul(a,a))\n# array([[ 7, 10],\n#        [15, 22]])\n", "meta": {"hexsha": "95125a12c8119c7c88a84ce647e401675b3f1d14", "size": 2599, "ext": "py", "lang": "Python", "max_stars_repo_path": "1-neural-networks/matrix-math-NumPy-refresher/np_matrix_demo.py", "max_stars_repo_name": "vanyaland/deep-learning-foundation", "max_stars_repo_head_hexsha": "05a0df56c8223547bd7e8b62653a67f265c8e5ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-04-18T13:48:30.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-02T13:32:16.000Z", "max_issues_repo_path": "1-neural-networks/matrix-math-NumPy-refresher/np_matrix_demo.py", "max_issues_repo_name": "ivan-magda/deep-learning-foundation", "max_issues_repo_head_hexsha": "05a0df56c8223547bd7e8b62653a67f265c8e5ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1-neural-networks/matrix-math-NumPy-refresher/np_matrix_demo.py", "max_forks_repo_name": "ivan-magda/deep-learning-foundation", "max_forks_repo_head_hexsha": "05a0df56c8223547bd7e8b62653a67f265c8e5ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7326732673, "max_line_length": 117, "alphanum_fraction": 0.5494420931, "include": true, "reason": "import numpy", "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147153749275, "lm_q2_score": 0.9184802356574272, "lm_q1q2_score": 0.8931436969343134}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr  9 17:50:43 2020\n\n@author: Ngwaniwapho\n\"\"\"\nimport numpy as np\n\n#__all_ = ['easomFunction','wayburnSeader2Function']\ndef easomFunction(x):\n    \"\"\"\n    −100 ≤ xi ≤ 100. The global minimum is located at x∗ = f(π, π),f(x∗) = −1\n    \"\"\"\n    x1 = x['IndPosition0']\n    x2 = x['IndPosition1']\n    easomfunction = -np.cos(x1)*np.cos(x2)*np.exp(-1*(x1-np.pi)**2 -(x2 - np.pi)**2)\n    return easomfunction\n\ndef bealeFunction(x):\n    \"\"\"\n    subject to −4.5 ≤ xi ≤ 4.5. The global minimum is located at x∗ = (3, 0.5), f(x∗) = 0.\n    \"\"\"\n    x1 = x['IndPosition0']\n    x2 = x['IndPosition1']\n    bealefunction = (1.5 - x1 + x1*x2)**2 + (2.25 - x1 + x1*x2**2)**2 + (2.625 - x1 + x1*x2**3)**2\n    return bealefunction\n\ndef matyasFunction(x):\n    \"\"\"\n    subject to −10 ≤ xi ≤ 10. The global minimum is located at x∗ = f(0, 0), f(x∗) = 0.\n    \"\"\"\n    x1 = x['IndPosition0']\n    x2 = x['IndPosition1']\n    matayasfunction = 0.26*(x1**2 + x2**2)- 0.48*x1*x2\n    return matayasfunction\n\ndef bohachevsky1Function(x):\n    \"\"\"\n    subject to −100 ≤ xi ≤ 100. The global minimum is located at x∗ = f(0, 0), f(x∗) = 0.\n    \"\"\"\n    x1 = x['IndPosition0']\n    x2 = x['IndPosition1']\n    bohachevsky1function = x1**2 + 2*x2**2 - 0.3*np.cos(3*np.pi*x1)-0.4*np.cos(4*np.pi*x2)+0.7\n    return bohachevsky1function\n\ndef penHolderFunction(x):\n    \"\"\"\n    subject to −11 ≤ xi ≤ 11. The four global minima are located at x∗ = f(±9.646168, ±9.646168), f(x∗) = −0.96354.\n    \"\"\"\n#    f(i)=-exp(-1/abs(cos(x1(j))*cos(x2(i))*exp(abs(1-sqrt(x1(j).^2+x2(i).^2)/pi))))\n#    penHolderfunction = -np.exp(np.abs(np.cos(x1)*np.cos(x2)*np.exp(np.abs(1-(np.sqrt(x1**2 + x2**2))/np.pi)))**(-1))\n    x1 = x['IndPosition0']\n    x2 = x['IndPosition1']\n    penHolderfunction = -np.exp(-1/np.abs(np.cos(x1)*np.cos(x2)*np.exp(np.abs(1-(np.sqrt(x1**2 + x2**2))/np.pi))))\n    return penHolderfunction\n\ndef wayburnSeader2Function(x):\n    \"\"\"\n    subject to −500 ≤ 500. The global minimum is located at x∗ = f{(0.2, 1), (0.425, 1)}, f(x∗) = 0.\n    \"\"\"    \n    x1 = x['IndPosition0']\n    x2 = x['IndPosition1']\n    wayburn = (1.613 - 4*(x1 - 0.3125)**2 - 4*(x2 - 1.625)**2)**2 + (x2 - 1)**2\n    return wayburn\n\ndef schaffer1Function(x):\n    \"\"\"\n    −100 ≤ xi ≤ 100. The global minimum is located at x∗ = f(0, 0),f(x∗) = 0.\n    \"\"\"\n    x1 = x['IndPosition0']\n    x2 = x['IndPosition1']\n    numeratorcomp   = (np.sin((x1**2 + x2**2)**2)**2) - 0.5\n    denominatorcomp = (1 + 0.001 * (x1**2 + x2**2))**2 \n    scahffer1function = 0.5 + numeratorcomp /denominatorcomp\n    return scahffer1function\n\ndef wolfeFunction(x):\n    \"\"\"\n    0 ≤ xi ≤ 2. The global minimum is located at x* = f(0,0, 0),f(x*) = 0.\n    \"\"\"\n    x1 = x['IndPosition0']\n    x2 = x['IndPosition1']\n    x3 = x['IndPosition2']\n    wolfefunction = (4/3)*(((x1**2 + x2**2) - (x1*x2))**(0.75)) + x3\n    return wolfefunction\n\ndef ackley2Function(x):\n    \"\"\"\n    subject to −32 ≤ xi ≤ 32. The global minimum is located at origin x∗ = (0, 0),f(x∗) = −200.\n    \"\"\"\n    x1 = x['IndPosition0']\n    x2 = x['IndPosition1']\n    ackley2function = -200*np.exp((-0.2*np.sqrt(x1**2 +x2**2)))\n    return ackley2function\n\ndef goldsteinpriceFunction(x):\n    \"\"\"\n    subject to −2 ≤ xi ≤ 2. The global minimum is located at x∗ = f(0,−1), f(x∗) = 3.\n    \"\"\"\n    x1 = x['IndPosition0']\n    x2 = x['IndPosition1']\n    term1 = (x1 + x2 + 1)**2\n    term3 = (2*x1 - 3*x2)**2\n    goldsteinpricefunction = (1 + term1*(19 - 14*x1 +3*x1**2 - 14*x2 + 6*x1*x2 + 3*x2**2))*(30 + term3*(18 - 32*x1 + 12*x1**2+ 48*x2 - 36*x1*x2 + 27*x2**2))\n    return goldsteinpricefunction\n\ndef boothFunction(x):\n    \"\"\"\n    subject to −10 ≤ xi ≤ 10. The global minimum is located at x∗ = f(1,3), f(x∗) = 0.\n    \"\"\"\n    x1 = x['IndPosition0']\n    x2 = x['IndPosition1']\n    boothfunction =((x1+2*x2-7)**2+(2*x1+x2-5)**2)\n    return boothfunction\n\ndef brentFunction(x):\n    \"\"\"\n    subject to −20 ≤ xi ≤ 0. The global minimum is located at x∗ = f(-10,-10), f(x∗) = np.exp(-200)\n    \"\"\"    \n    x1 = x['IndPosition0']\n    x2 = x['IndPosition1']\n    brentfunction = (x1 + 10)**2 + (x2 + 10)**2 + np.exp(-x1**2 - x2**2)\n    return brentfunction\n\ndef powellsumFunction(x):\n    \"\"\"\n    subject to −1 ≤ xi ≤ 1. The global minimum is located at x∗ = f(0,...,0), f(x∗) = 0\n    \"\"\"    \n    n = (x.shape)[1]\n    absx = np.abs(x)\n\n    powellsumfunction = 0\n    for i in range(n):\n        powellsumfunction = powellsumfunction + (absx.iloc[:, i]**((i+1) + 1))\n    return powellsumfunction ", "meta": {"hexsha": "691df940c82555756a93d45541a5e22f571084bd", "size": 4474, "ext": "py", "lang": "Python", "max_stars_repo_path": "ulimisana/testFunctions.py", "max_stars_repo_name": "Ubuntu-AI/Ulimisana_Optimisation_Algorithm", "max_stars_repo_head_hexsha": "b19292d646ba72f1d7494058977429f6273b4e1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ulimisana/testFunctions.py", "max_issues_repo_name": "Ubuntu-AI/Ulimisana_Optimisation_Algorithm", "max_issues_repo_head_hexsha": "b19292d646ba72f1d7494058977429f6273b4e1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ulimisana/testFunctions.py", "max_forks_repo_name": "Ubuntu-AI/Ulimisana_Optimisation_Algorithm", "max_forks_repo_head_hexsha": "b19292d646ba72f1d7494058977429f6273b4e1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1407407407, "max_line_length": 156, "alphanum_fraction": 0.5576665177, "include": true, "reason": "import numpy", "num_tokens": 1756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446479186301, "lm_q2_score": 0.9173026550642019, "lm_q1q2_score": 0.8931268206248095}}
{"text": "import numpy as np\n\n#ranged data\nprint(np.arange(5)) #[0 1 2 3 4]\nprint(np.arange(3.2)) #[ 0.  1.  2.  3.]\nprint(np.arange(3.2, 7.2, 0.8)) #[ 3.2  4.   4.8  5.6  6.4]\n\n#linspace\nprint(np.linspace(2.0, 3.0, num=5))\n#array([2.  , 2.25, 2.5 , 2.75, 3.  ])\nprint(np.linspace(2.0, 3.0, num=5, endpoint=False))\n#array([2. ,  2.2,  2.4,  2.6,  2.8])\nprint(np.linspace(2.0, 3.0, num=5, retstep=True))\n#(array([2.  ,  2.25,  2.5 ,  2.75,  3.  ]), 0.25)\nprint(np.linspace(5, 11, num=5))\n#[  5.    6.5   8.    9.5  11. ]\nprint(np.linspace(5, 11, num=5, dtype=np.int32))\n#[ 5  6  8  9 11]\n\n#reshape\narr = np.arange(8)\nreshaped_arr = arr.reshape(4, 2)\nprint(repr(reshaped_arr))\n#array([[0, 1], [2, 3], [4, 5], [6, 7])\n#one dimision can be -1, the value is inferred from the length of th array and remaining dimisions\nreshaped_arr = arr.reshape(2, -1, 2)\nprint(repr(reshaped_arr))\n#array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])\n#Error : arr.reshape(4, 3)\n\n#flatten : reshape an array into a 1D array\narr2 = reshaped_arr.flatten()\nprint(repr(arr2))\n#array([0, 1, 2, 3, 4, 5, 6, 7])\n\n#transpose axes(permutaion of range(n))\narr = np.arange(24)\narr = np.reshape(arr, (3, 4, 2))\ntransposed = np.transpose(arr, axes=(1, 2, 0))\nprint(arr.shape)\n#(3, 4, 2)\nprint(transposed.shape)\n#(4, 2, 3)\n\n#np.zeros, np.ones    fill array with 0/1\n#np.zeros_like, np.ones_like\narr = np.array([[1, 2], [3, 4]])\nprint(repr(np.zeros_like(arr)))\n#array([[0, 0], [0, 0]])\n", "meta": {"hexsha": "e521a1522295fbeb28436ac02ef0981fc8685d72", "size": 1431, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data-Manipulation/basic.py", "max_stars_repo_name": "tusikalanse/Machine-Learning-for-Software-Engineers", "max_stars_repo_head_hexsha": "59415e2db98ba2a1d97a55560d1c0cb8567b1725", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Data-Manipulation/basic.py", "max_issues_repo_name": "tusikalanse/Machine-Learning-for-Software-Engineers", "max_issues_repo_head_hexsha": "59415e2db98ba2a1d97a55560d1c0cb8567b1725", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data-Manipulation/basic.py", "max_forks_repo_name": "tusikalanse/Machine-Learning-for-Software-Engineers", "max_forks_repo_head_hexsha": "59415e2db98ba2a1d97a55560d1c0cb8567b1725", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-04T10:29:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T10:29:29.000Z", "avg_line_length": 28.62, "max_line_length": 98, "alphanum_fraction": 0.5953878407, "include": true, "reason": "import numpy", "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.9449947057037211, "lm_q1q2_score": 0.8930149965528872}}
{"text": "import numpy as np\nfrom sklearn.metrics import pairwise_distances\n\ndef get_minkowski_distance(p1: tuple, p2: tuple, r: int = 2) -> float:\n    \"\"\"\n    Generates Minkowski Distance between two points, r is... dimensionality?\n    \"\"\"\n    tmp = 0 # all values will be added to this variable, will be returned\n    cols = len(p1) \n\n    if isinstance(r, str):\n        if r.lower() == \"inf\" or r.lower() == \"infinity\":\n            tmp_lst = []\n            for i in range(cols):\n                tmp_lst.append(abs(p1[i] - p2[i]))\n\n            return max(tmp_lst)\n\n    else: \n        for i in range(cols):\n            tmp += (abs(p1[i] - p2[i])**r)\n\n        return tmp**(1/r)\n\n\ndef create_minkowski_matrix(arr: np.ndarray, r: int|str) -> np.ndarray:\n    \"\"\"\n    \n    \"\"\"\n    d_arr = np.empty((len(arr), len(arr)))# [[] for i in range(len(tpl1))]\n\n    for i, p1 in enumerate(arr):\n        for j, p2 in enumerate(arr):\n            d_arr[i][j] = (round(get_minkowski_distance(p1, p2, r), 8))\n\n    return d_arr\n\n\nif __name__==\"__main__\":\n    r = 2\n    for arr in [np.random.rand(2, 4) for i in range(4)]:\n        print(\"-\" * 50)\n        print(create_minkowski_matrix(arr*10, r))\n        print(\"\\n\")\n        print(pairwise_distances(arr*10, metric=\"euclidean\"))\n        print(\"-\" * 50)\n        print(\"\\n\\n\")\n", "meta": {"hexsha": "c9c84f020f25848334a90a28ead84858dde47aa0", "size": 1293, "ext": "py", "lang": "Python", "max_stars_repo_path": "Miscellaneous/distance_matrix.py", "max_stars_repo_name": "Joshua-Elms/CSCI-B365", "max_stars_repo_head_hexsha": "f28dda6da3098ec4b9472ee546c3e6798d358ce8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Miscellaneous/distance_matrix.py", "max_issues_repo_name": "Joshua-Elms/CSCI-B365", "max_issues_repo_head_hexsha": "f28dda6da3098ec4b9472ee546c3e6798d358ce8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Miscellaneous/distance_matrix.py", "max_forks_repo_name": "Joshua-Elms/CSCI-B365", "max_forks_repo_head_hexsha": "f28dda6da3098ec4b9472ee546c3e6798d358ce8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9375, "max_line_length": 76, "alphanum_fraction": 0.5545243619, "include": true, "reason": "import numpy", "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846659768267, "lm_q2_score": 0.912436159286392, "lm_q1q2_score": 0.8927135469285953}}
{"text": "import numpy as np\nimport pymc3 as pm\nimport matplotlib.pyplot as plt\nfrom scipy.stats import binom\nfrom scipy.stats import mode\n\nimport seaborn as sns\n\np_positive_when_vampire = 0.95\np_positive_when_mortal = 0.01\np_is_vampire = 0.001\np_positive = p_positive_when_vampire*p_is_vampire+p_positive_when_mortal*(1. - p_is_vampire)\n\np_vampire_positive = p_positive_when_vampire*p_is_vampire / p_positive\n\nprint('the probability that you are a vampire given the vampire blood test was positive:%f'%p_vampire_positive)\n\ndef grid_aprox(grid_points=100,success=6,tosses=9):\n    p_grid = np.linspace(0.,1.,grid_points)\n    prior = np.repeat(5,grid_points)\n    likehood = binom.pmf(success,tosses,p_grid)\n    posterior = likehood*prior\n    posterior = posterior/posterior.sum()\n    \n    return p_grid, posterior\n\nprint('--------------6/9-----------')\np_grid,posterior = grid_aprox(1000,6,9)\n\n# plt.plot(p_grid,posterior)\n# plt.show()\n\nsamples = np.random.choice(p_grid,p=posterior,size=int(1e4),replace=True)\n_,(ax0,ax1,ax2) = plt.subplots(1,3)\nax0.plot(p_grid,posterior)\nax1.plot(samples,'o')\nsns.kdeplot(samples,ax=ax2)\nplt.show()\n\np_less_then_0_5 = sum(posterior[p_grid < 0.5])\nprint('posterior < 0.5 = %f'%p_less_then_0_5)\nsamples_less_0_5 = sum(samples < 0.5)/1e4\nprint('samples < 0.5 = %f'%samples_less_0_5)\n\nprint('between 0.5 and 0.75 posterior:%f'%(sum(posterior[(p_grid > 0.5) & (p_grid < 0.75)])))\nprint('between 0.5 and 0.75 samples:%f'%(sum((samples > 0.5) & (samples < 0.75))/1e4))\n\nprint('80 percentile:'+str(np.percentile(samples,80)))\nprint('middle 80 percentile(between 10 and 90 percent):'+str(np.percentile(samples,[10,90])))\nprint('middle 50 percentile(between 25 and 75 percent):'+str(np.percentile(samples,[25,75])))\nprint('high posterior density percentile interval 50:'+str(pm.hpd(samples,alpha=0.5)))\nprint('middle 50 percentile(between 80 and 90 percent):'+str(np.percentile(samples,[80,90])))\nprint('high posterior density percentile interval 80:'+str(pm.hpd(samples,alpha=0.8)))\nprint('high posterior density percentile interval 90:'+str(pm.hpd(samples,alpha=0.9)))\nprint('high posterior density percentile interval 95:'+str(pm.hpd(samples,alpha=0.95)))\nprint('maximum posteriori at prob =(%f,%f)'%(max(posterior),p_grid[posterior == max(posterior)]))\nprint('maximum posteriori at prob from samples: %f'%mode(samples)[0])\nprint('mean and median : %f,%f' %(np.mean(samples),np.median(samples)))\nprint('expected loss:%f'%(sum(posterior*abs(0.5-p_grid))))\nloss = [sum(posterior*abs(p-p_grid)) for p in p_grid]\nplt.plot(p_grid,loss)\nplt.show()\nprint('min loss at probability:%f'%p_grid[loss == min(loss)])\n\nprint('expected loss:%f'%(sum(posterior*np.power(0.5-p_grid,2))))\nloss = [sum(posterior*np.power(p-p_grid,2)) for p in p_grid]\nplt.plot(p_grid,loss)\nplt.show()\nprint('min loss at probability:%f'%p_grid[loss == min(loss)])\n\nprint('--------------3/3-----------')\np_grid,posterior = grid_aprox(1000,3,3)\nsamples = np.random.choice(p_grid,p=posterior,size=int(1e4),replace=True)\n_,(ax0,ax1,ax2) = plt.subplots(1,3)\nax0.plot(p_grid,posterior)\nax1.plot(samples,'o')\nsns.kdeplot(samples,ax=ax2)\nplt.show()\nprint('middle 50 percentile(between 25 and 75 percent):'+str(np.percentile(samples,[25,75])))\nprint('high posterior density percentile interval 50:'+str(pm.hpd(samples,alpha=0.5)))\nprint('middle 50 percentile(between 80 and 90 percent):'+str(np.percentile(samples,[80,90])))\nprint('high posterior density percentile interval 80:'+str(pm.hpd(samples,alpha=0.8)))\nprint('high posterior density percentile interval 90:'+str(pm.hpd(samples,alpha=0.9)))\nprint('high posterior density percentile interval 95:'+str(pm.hpd(samples,alpha=0.95)))\nprint('maximum posteriori at prob =(%f,%f)'%(max(posterior),p_grid[posterior == max(posterior)]))\nprint('maximum posteriori at prob from samples: %f'%mode(samples)[0])\nprint('mean and median : %f,%f' %(np.mean(samples),np.median(samples)))\n\nprint('expected loss:%f'%(sum(posterior*abs(0.5-p_grid))))\nloss = [sum(posterior*abs(p-p_grid)) for p in p_grid]\nplt.plot(p_grid,loss)\nplt.show()\nprint('min loss at probability:%f'%p_grid[loss == min(loss)])\n\nprint('expected loss:%f'%(sum(posterior*np.power(0.5-p_grid,2))))\nloss = [sum(posterior*np.power(p-p_grid,2)) for p in p_grid]\nplt.plot(p_grid,loss)\nplt.show()\nprint('min loss at probability:%f'%p_grid[loss == min(loss)])\n\n\nprint('-----------------simulating---------')\n# simulate globe tossing for water with 0.7 prob. in 2 throws\ndata = binom.pmf(range(3),2,0.7)\n# 0 water 0.09, 1 water 0.42, 2 water 0.49\nprint(data)\n# sample from distribution of simulation data - it is binom, so sample from binom distribution\n# we are generating observations...that mean how many times did we see water when we tossed the globe 2x\nsamples = binom.rvs(n=2, p=0.7, size=1)\nprint(samples)\nsamples = binom.rvs(n=2, p=0.7, size=10)\nprint(samples)\ndummy_w = binom.rvs(n=2, p=0.7, size=100000)\nmeans = [(dummy_w == i).mean() for i in range(3)]\nprint(means)\n\ndummy_w = binom.rvs(n=9, p=0.7, size=100000)\nmeans = [(dummy_w == i).mean() for i in range(9)]\nprint(means)\nplt.hist(dummy_w,bins=50)\nplt.show()\n\ndummy_w = binom.rvs(n=9, p=0.6, size=100000)\nmeans = [(dummy_w == i).mean() for i in range(9)]\nprint(means)\nplt.hist(dummy_w,bins=50)\nplt.show()\n\ndummy_w = binom.rvs(n=9, p=0.5, size=100000)\nmeans = [(dummy_w == i).mean() for i in range(9)]\nprint(means)\nplt.hist(dummy_w,bins=50)\nplt.show()\n\ndummy_w = binom.rvs(n=9, p=0.4, size=100000)\nmeans = [(dummy_w == i).mean() for i in range(9)]\nprint(means)\nplt.hist(dummy_w,bins=50)\nplt.show()\n\ndummy_w = binom.rvs(n=9, p=0.3, size=100000)\nmeans = [(dummy_w == i).mean() for i in range(9)]\nprint(means)\nplt.hist(dummy_w,bins=50)\nplt.show()\n\n\n#generate samples from posterior\np_grid, posterior = grid_aprox(grid_points=1000, success=6, tosses=9)\nnp.random.seed(100)\nsamples = np.random.choice(p_grid, p=posterior, size=int(1e4), replace=True)\ndummy_w = binom.rvs(n=9, p=samples)\n_,(ax0,ax1) = plt.subplots(1,2)\nax0.plot(posterior)\nax1.hist(dummy_w,bins=50)\nplt.show()\n\n\n\n\n\n\n\n\n\n\n    \n\n", "meta": {"hexsha": "81a0615c09544d5ed66ad0501c071978672bf539", "size": 6020, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch3/ch3.py", "max_stars_repo_name": "xSakix/bayesian_analyses", "max_stars_repo_head_hexsha": "14042e193507bae6d69caeb4035ac45ef9044176", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3/ch3.py", "max_issues_repo_name": "xSakix/bayesian_analyses", "max_issues_repo_head_hexsha": "14042e193507bae6d69caeb4035ac45ef9044176", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/ch3.py", "max_forks_repo_name": "xSakix/bayesian_analyses", "max_forks_repo_head_hexsha": "14042e193507bae6d69caeb4035ac45ef9044176", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6213017751, "max_line_length": 111, "alphanum_fraction": 0.7117940199, "include": true, "reason": "import numpy,from scipy,import pymc3", "num_tokens": 1884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.978384664716301, "lm_q2_score": 0.9124361539289197, "lm_q1q2_score": 0.8927135405367774}}
{"text": "import math\nimport numpy as np\nfrom Jacobi import jacobi\nfrom Printer import print_results\nfrom Gauss_Seidel import gauss_seidel\nfrom SOR import sor\n'''\nMATH 5336, Homework #6\n\nMain function area, run program from here.\n\nA and b matrices were created from HW #6 description.\n\nWe will use x = [0,0,0,0,0,0,0,0] as starting value\n\nPrints number of iterations that each method took along with their X values\n\nPrinting will be done with the help of a helper printer file\n'''\n\n\nA = np.array([[-1, 0, 0, math.sqrt(2)/2, 1, 0, 0, 0],\n    [0, -1, 0, math.sqrt(2)/2, 0, 0, 0, 0],\n   [0, 0, -1, 0, 0, 0, 1/2, 0],\n   [0, 0, 0, -math.sqrt(2)/2, 0, -1, -1/2, 0],\n   [0, 0, 0, 0, -1, 0, 0, 1],\n   [0, 0, 0, 0, 0, 1, 0, 0],\n   [0, 0, 0, -math.sqrt(2)/2, 0, 0, math.sqrt(3)/2, 0],\n   [0, 0, 0, 0, 0, 0, math.sqrt(3)/2, -1]\n   ])\nb = np.array([0,0,0,0,0,10000,0,0])\nx = np.array([0,0,0,0,0,0,0,0])\n\n# Uses built-in linalg solver to find X\nx_solved = np.dot(np.linalg.inv(A), b)\n\n# Print actual solution for comparison\nprint(\"The actual solution using the built-in matrix solver is: \")\nprint_results(x_solved)\n\n# Runs Jacobi's method and prints its results\nx_jacobi = jacobi(A, b, x, error=10**-8, actual_soln = x_solved)\nprint()\nprint(\"Jacobi's method took {} iterations: \" .format(x_jacobi[1]))\nprint_results(x_jacobi[0])\n\n# Runs Gauss Seidel method and prints its results\nx_gauss_seidel = gauss_seidel(A, b, x, error=10**-8, actual_soln=x_solved)\nprint()\nprint(\"Gauss Seidel method took {} iterations: \".format(x_gauss_seidel[1]))\nprint_results(x_gauss_seidel[0])\n\n# Runs SOR with w = 1.25 and prints its results\nx_sor = sor(A, b, x, error=10**-8, actual_soln=x_solved, w=1.25)\nprint()\nprint(\"SOR method took {} iterations: \".format(x_sor[1]))\nprint_results(x_sor[0])\n", "meta": {"hexsha": "875ffce2b15dd73b92d74d9947bd50082f08f58e", "size": 1753, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "bensonbenson/Multiple-Methods-to-Solve-a-Matrix", "max_stars_repo_head_hexsha": "444e4bc528da0498bc55000663a383f6d16c1b18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.py", "max_issues_repo_name": "bensonbenson/Multiple-Methods-to-Solve-a-Matrix", "max_issues_repo_head_hexsha": "444e4bc528da0498bc55000663a383f6d16c1b18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "bensonbenson/Multiple-Methods-to-Solve-a-Matrix", "max_forks_repo_head_hexsha": "444e4bc528da0498bc55000663a383f6d16c1b18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.224137931, "max_line_length": 75, "alphanum_fraction": 0.6668568169, "include": true, "reason": "import numpy", "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551535992067, "lm_q2_score": 0.9252299581228933, "lm_q1q2_score": 0.8927128933592519}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov 17 12:38:15 2021\r\n\r\n@author: Oscar\r\n\"\"\"\r\n\r\n# Golden Search, mimics the secant method, but for finding the Global Max and min (optimization of a function)\r\n# Strategy in selecting the bounds of the interval:\r\n    # l0 = distance between estimate,\r\n    # l0 = l1+l2 ; l1/l0 = l2/l1\r\n    # R = (l2/l1)**-1 (reciprocal)\r\n    # From substitution : 1 +R = 1/R -> R**2 + R - 1 = 0\r\n    # R = [sqrt(5)-1]/2 <- GOLDEN RATIO\r\n        # d = R(x_u - x_l)\r\n        #x1 = x_l + d ; x2 = x_u - d \r\n        \r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\n        \r\n\"\"\"\r\nInterval Selection\r\n\"\"\"\r\n# Parameters\r\nxu = 20 #int(input(\"Please choose a upper bound: \"))\r\nxl = -20 #int(input(\"Please choose a lower bound: \"))\r\nN = 100 #int(input(\"Please choose Maxt number of iterations: \"))\r\n# Golden Ratio\r\nR = (math.sqrt(5) - 1)/2\r\n\r\n\r\n\"\"\"\r\nEvaluation of the Function\r\n\"\"\"\r\n# Evaluated function\r\nf = lambda x: 2*np.sin(x) - x**2/10\r\n\r\ndef GoldenSearchMax(xu, xl, f, N):\r\n        \r\n    for i in range(0, N-1):\r\n        # Intermediate points\r\n        d = R*(xu - xl)\r\n        \r\n        x1 = xl + d\r\n        x2 = xu - d\r\n        \r\n        fx1, fx2 = f(x1), f(x2)\r\n        \r\n        if fx1 > fx2 :\r\n            xl = x2\r\n            \r\n        elif fx1 < fx2:\r\n            xu = x1\r\n            \r\n        else:\r\n            #print(\"The local maxima is located at:\", x1, fx1)\r\n            break\r\n    return x1, fx1\r\n\r\ndef GoldenSearchMin(xu, xl, f, N):\r\n        \r\n    for i in range(0, N-1):\r\n        # Intermediate points\r\n        d = R*(xu - xl)\r\n        \r\n        x1 = xl + d\r\n        x2 = xu - d\r\n        \r\n        fx1, fx2 = f(x1), f(x2)\r\n        \r\n        if fx1 < fx2 :\r\n            xl = x2\r\n            \r\n        elif fx1 > fx2:\r\n            xu = x1\r\n            \r\n        else:\r\n            #print(\"The local minima is located at:\", x1, fx1)\r\n            break\r\n    return x1, fx1\r\n\r\n# Arrays to store the numbers\r\nMax = GoldenSearchMax(xu, xl, f, N)\r\nMin = GoldenSearchMin(xu, xl, f, N)\r\nprint('The local max and min of the interval is:', Max, Min)\r\n\r\n# Initializing Arrays\r\nx_value = np.linspace(xl, xu, N-1)\r\ny_value = np.zeros(N-1)\r\n\r\n# Populating y_array\r\nfor k in range(N-1):\r\n    y_value[k] = f(x_value[k])\r\n\r\n# Plotting the function f\r\nplt.plot(x_value ,y_value)\r\nplt.scatter(Max[0], Max[1], label = 'Maxima', color = 'r')\r\nplt.scatter(Min[0], Min[1], label = 'Maxima', color = 'g')\r\nplt.legend(['Function', 'Maxima', 'Minima'])\r\nplt.xlabel('x')\r\nplt.ylabel('y')\r\nplt.show()\r\n", "meta": {"hexsha": "8bab343da62f6b8033a20bda7c2dcd2410fde6da", "size": 2532, "ext": "py", "lang": "Python", "max_stars_repo_path": "GoldSearch.py", "max_stars_repo_name": "oliver779/Computational_Methods_Course", "max_stars_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GoldSearch.py", "max_issues_repo_name": "oliver779/Computational_Methods_Course", "max_issues_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GoldSearch.py", "max_forks_repo_name": "oliver779/Computational_Methods_Course", "max_forks_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3461538462, "max_line_length": 111, "alphanum_fraction": 0.5082938389, "include": true, "reason": "import numpy", "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9770226307590189, "lm_q2_score": 0.9136765263519308, "lm_q1q2_score": 0.8926826434391254}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Oct 20 13:37:44 2021\r\n\r\n@author: Oscar\r\n\"\"\"\r\n\r\n# Newton Raph Method is anohter open root method to finding the roots  of a function\r\n    # The function in question is evaluated at an initially choosen point\r\n    # A tangent line wrt the point is then drawn and intersects the x-axis\r\n    # Repeats until the root is found\r\n        # x_new =  x - f(x)/f'(x)\r\nimport sympy as sp\r\n        \r\n# Define The required Parameters \r\nx0 = 1 #int(input(\"Initial Estimate:\"))\r\nN = 100 #int(input(\"Max Iterations:\"))\r\ne = 0.000001#float(input(\"Tolerance:\"))\r\n# Equation that needs to be evaluated\r\n\r\nf = lambda x: x**2 +4*x -12\r\ndf = lambda x: 2*x +4\r\n\r\ndef NewtonRapshon(f, df, e, N):\r\n    \r\n    xn = x0\r\n    \r\n    for i in range(0,N):\r\n        # If the value of the function at x is less than the tolerance, we print xn as it is close to the root\r\n        if abs(f(xn)) < e:\r\n            abs_error=(xn-2)/2\r\n            print('Found solution after',i,'iterations.')\r\n            return xn, abs_error\r\n        # Find the derivative at the value of xn, if none exists\r\n        if df(xn) == 0:\r\n            print('Zero derivative. No solution found.')\r\n            return None\r\n        # Calculate the new value of xn and repeat the process\r\n        xn = xn - f(xn)/df(xn)\r\n    \r\n    # If the Max number of iterations are reached, stop the program  \r\n    print('Exceeded maximum iterations. No solution found.')\r\n\r\n    return \r\n\r\nsolution = NewtonRapshon(f, df, e, N)\r\nprint(solution)", "meta": {"hexsha": "34380afcb540b91d1288d5f0d4ae5a96ada6415a", "size": 1514, "ext": "py", "lang": "Python", "max_stars_repo_path": "Newton Raph Method v2 .py", "max_stars_repo_name": "oliver779/Computational_Methods_Course", "max_stars_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Newton Raph Method v2 .py", "max_issues_repo_name": "oliver779/Computational_Methods_Course", "max_issues_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Newton Raph Method v2 .py", "max_forks_repo_name": "oliver779/Computational_Methods_Course", "max_forks_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2127659574, "max_line_length": 111, "alphanum_fraction": 0.6043593131, "include": true, "reason": "import sympy", "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242000616579, "lm_q2_score": 0.9207896807817187, "lm_q1q2_score": 0.8925437207487689}}
{"text": "import numpy as np\nimport warnings\n\ndef quadratic1(a,b,c):\n    '''\n    Solve an quadratic equation\n    '''\n    if b**2-4*a*c < 0: x = np.nan\n    elif b**2-4*a*c == 0: x = -b/(2*a)\n    else: x = np.array(((-b+np.sqrt(b**2-4*a*c))/(2*a), (-b-np.sqrt(b**2-4*a*c))/(2*a)))\n    return x\n\ndef demean(d):\n    return d - d.mean(axis=0)[np.newaxis, :]\n\n\ndef is_outliers(data):\n    '''\n    Check outliers.\n    Checking if the giving number's zscore is above 2.5.\n    '''\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n        mean = np.nanmean(data, axis=0)\n        sd = np.sqrt(np.nanmean((data - mean)**2, axis=0))\n    zdata = (data - mean) / sd\n    return abs(zdata) > 2.5\n\ndef imputedata(data, strategy='mean'):\n    '''\n    impute outliers and missing data\n    impute outlier with mean or mean+-2sd\n    missing data (np.nan) will impute as mean\n    '''\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n        mean = np.nanmean(data, axis=0)\n        std = np.sqrt(np.nanmean((data - mean)**2, axis=0))\n\n    data_sign = np.sign(data - mean)\n    data_sign[np.isnan(data_sign)] = 0 # missing data will be imputed as mean\n\n    is_out = is_outliers(data)\n    data[is_out] = np.nan\n\n    for i in range(data.shape[1]):\n        ind_nan = np.where(np.isnan(data[:, i]))\n        if strategy == '2sd':\n            data[ind_nan, i] = mean[i] + (std[i] * 2 * data_sign[ind_nan, i])\n        if strategy == 'mean':\n            data[ind_nan, i] = mean[i]\n    return data\n\ndef mean_nonzero(data, axis):\n    '''\n    calculate the non zero elements in a 2-D matrix\n    '''\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n        temp_sum = np.sum(data != 0, axis=axis)\n        temp_sum[temp_sum == 0] = 1\n        return np.sum(data, axis=axis)/temp_sum\n\nimport pickle\ndef load_pkl(file):\n    '''\n    load pickled file\n    '''\n    with open(file, 'rb') as handle:\n        return pickle.load(handle)\n        \n\ndef flatten(corrmat):\n    '''\n    flatten the correlation coefficient matrix in to a flat vector\n    '''\n\n    triu_inds = np.triu_indices(corrmat.shape[0], 1)\n    corrmat_vect = corrmat[triu_inds]\n    return corrmat_vect\n\n\ndef unflatten(corrmat_vect):\n    '''\n    Transform the flattened correlation matrice back to matrices\n    for visualisation\n    '''\n    \n    # figure out the size\n    y = corrmat_vect.shape[0]\n    x = quadratic1(0.5, -0.5, -y)\n    x = int(np.max(x))\n    \n    idx = np.triu_indices(x, 1)\n    corr_mat = np.zeros((x, x))\n    corr_mat[idx] = corrmat_vect\n    corr_mat = corr_mat + corr_mat.T\n    \n    return corr_mat\n", "meta": {"hexsha": "fb54cebde7d9565d1b8c95bbb0895eb8faee7c97", "size": 2679, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/utils.py", "max_stars_repo_name": "htwangtw/Patterns-of-Thought", "max_stars_repo_head_hexsha": "5c31ce306d8530394d6f9ee496081c91551597fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-05T15:39:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-05T15:39:07.000Z", "max_issues_repo_path": "src/utils.py", "max_issues_repo_name": "htwangtw/patterns-of-thought", "max_issues_repo_head_hexsha": "5c31ce306d8530394d6f9ee496081c91551597fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.py", "max_forks_repo_name": "htwangtw/patterns-of-thought", "max_forks_repo_head_hexsha": "5c31ce306d8530394d6f9ee496081c91551597fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.79, "max_line_length": 88, "alphanum_fraction": 0.6020903322, "include": true, "reason": "import numpy", "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242000616579, "lm_q2_score": 0.920789679151471, "lm_q1q2_score": 0.8925437191685303}}
{"text": "from math import e, factorial\r\n\r\nimport numpy as np\r\n\r\nfac = np.vectorize(factorial)\r\n\r\ndef e_x(x, terms=10):\r\n    \"\"\"Approximates e^x using a given number of terms of\r\n    the Maclaurin series\r\n    \"\"\"\r\n    n = np.arange(terms)\r\n    return np.sum((x ** n) / fac(n))\r\n\r\nif __name__ == \"__main__\":\r\n    print(\"Actual:\", e ** 3)  # Using e from the standard library\r\n\r\n    print(\"N (terms)\\tMaclaurin\\tError\")\r\n\r\n    for n in range(1, 14):\r\n        maclaurin = e_x(3, terms=n)\r\n        print(f\"{n}\\t\\t{maclaurin:.03f}\\t\\t{e**3 - maclaurin:.03f}\")\r\n", "meta": {"hexsha": "1adfb82ea724956143c4cc23bee28b85016fb5ed", "size": 546, "ext": "py", "lang": "Python", "max_stars_repo_path": "mactaurin.py", "max_stars_repo_name": "StepanPoghosyan/NumPy", "max_stars_repo_head_hexsha": "98b20ed08f467c34612aa443e309c04e53e6b7af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mactaurin.py", "max_issues_repo_name": "StepanPoghosyan/NumPy", "max_issues_repo_head_hexsha": "98b20ed08f467c34612aa443e309c04e53e6b7af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mactaurin.py", "max_forks_repo_name": "StepanPoghosyan/NumPy", "max_forks_repo_head_hexsha": "98b20ed08f467c34612aa443e309c04e53e6b7af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8181818182, "max_line_length": 69, "alphanum_fraction": 0.5879120879, "include": true, "reason": "import numpy", "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992932829917, "lm_q2_score": 0.9219218418270454, "lm_q1q2_score": 0.8923274991665513}}
{"text": "import numpy as np\n\n\ndef brownian_motion(t, kappa=1.0):\n    '''\n    Compute the 1D Brownian motion at some given time instants. The Brownian\n    motion is such that each increment B(t[i]) - B(t[i-1]) are independent\n    random variables normally distributed with zero mean an kappa*(t[i]-t[i-1])\n    variance.\n\n    Parameters\n    ----------\n    t : 1d ndarray of floats\n        Time instants where the Brownian motion is to be evaluated.\n\n    kappa : float, optional\n        Diffusion constant. Default is 1.0.\n\n    Returns\n    -------\n    u : 1d ndarray of floats\n        1D Brownian motion evaluated. Same shape as t.\n    '''\n    dt = np.ediff1d(t, to_begin=t[0])\n    du = np.random.randn(len(t)) * np.sqrt(dt * kappa)\n    u = np.add.accumulate(du)\n    return u\n\n\ndef fractional_brownian_motion(n, h, b=1.0, tf=1.0):\n    '''\n    Compute the 1D fractional Brownian motion. These are stochastic processes\n    with long range power-law correlations. The mean square displacement\n    behaves as\n\n    <B(t)^2> = b t^(2h)\n\n    where b is the diffusion constant and h is the Hurst exponent.\n\n    It uses the Davies-Harte algorithm.\n\n    Reference\n    ---------\n    Davies, Robert B., and D. S. Harte. \"Tests for Hurst effect.\"\n    Biometrika 74.1 (1987): 95-101.\n\n    Parameters\n    ----------\n    n : int\n        Number of point the function will produce.\n\n    h : float\n        Hurst exponent.\n\n    b : float, optional\n        Diffusion constant. Default is 1.0.\n\n    tf : float, optional\n        Endind time, so the brownian motion is evaluated at\n        n time instants uniformly spaced in the interval [0, tf].\n        Default if 1.0.\n\n    Returns\n    -------\n    t : ndarray of floats\n        Time instants where the fractional Brownian motion was evaluated.\n\n    X : ndarray of floats\n        Values of fractional Brownian motion.\n    '''\n    n2 = 2 * n\n    h2 = 2 * h\n\n    i = np.arange(0, n+1)\n    s = np.zeros(n2)\n    s[:n+1] = np.abs(i+1) ** h2 + np.abs(i-1) ** h2 - 2 * np.abs(i) ** h2\n    s[:n+1] *= b * 0.5\n    s[n+1:] = s[n-1:0:-1]\n\n    A = np.fft.fft(s).real\n    assert (A >= 0).all()\n\n    Y = np.empty(n2, dtype=np.complex128)\n    Y[0] = 2**0.5 * np.random.randn()\n    Y[n] = 2**0.5 * np.random.randn()\n    Y[1:n] = np.random.randn(n-1) + 1j * np.random.randn(n-1)\n    Y[n+1:n2] = Y[n-1:0:-1].conj()\n    Y *= np.sqrt(A*n)\n\n    X = np.fft.ifft(Y).real[:n]\n    X = np.cumsum(X)\n    X -= X[0]\n\n    t = np.linspace(0.0, tf, n)\n    X *= (tf / n) ** h\n\n    return t, X\n", "meta": {"hexsha": "c39765bdf6c3c1a9fc92bfda7d12fa13d8de51fc", "size": 2476, "ext": "py", "lang": "Python", "max_stars_repo_path": "loew/misc.py", "max_stars_repo_name": "hfcredidio/loew", "max_stars_repo_head_hexsha": "3ec23337808cc25280152f64981f23a709064f83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-08-03T16:49:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T00:33:10.000Z", "max_issues_repo_path": "loew/misc.py", "max_issues_repo_name": "hfcredidio/loew", "max_issues_repo_head_hexsha": "3ec23337808cc25280152f64981f23a709064f83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "loew/misc.py", "max_forks_repo_name": "hfcredidio/loew", "max_forks_repo_head_hexsha": "3ec23337808cc25280152f64981f23a709064f83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2653061224, "max_line_length": 79, "alphanum_fraction": 0.5795638126, "include": true, "reason": "import numpy", "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214521983691, "lm_q2_score": 0.925229957607466, "lm_q1q2_score": 0.892219096337467}}
{"text": "from __future__ import division  # take the division operator from future versions\nimport numpy as np\nimport math\nimport toolboxutilities as util\n\ndef least_squares(matrix_a, vector_y):\n    '''\n    This function computes the estimate :math:`\\\\hat x` given by the least squares method\n    :math:`\\\\hat x = {\\\\rm arg}\\\\min_x\\\\,\\\\lVert \\\\mathbf{y - Ax} \\\\rVert_2^2`.\n    This is the simplest algorithm to solve a linear inverse problem of the form :math:`\\\\mathbf{y = Ax + n}`, where\n    :math:`\\\\mathbf{y}` (vector) and :math:`\\\\mathbf{A}` (matrix) are known and :math:`\\\\mathbf{x}`  (vector)\n     and :math:`\\\\mathbf{n}`  (vector) are unknown.\n\n    :param matrix_a: (np.matrix) matrix :math:`\\\\mathbf{A}`\n    :param vector_y: (array) vector :math:`\\\\mathbf{y}`\n\n    :return vector_x: estimate :math:`\\\\hat x` given by least squares\n\n    Example : compute the least squares solution of a system :math:`\\\\mathbf{y = Ax}`\n\n    .. code-block:: python\n\n        import numpy as np\n        import linvpy as lp\n\n        A = np.matrix([[1,3],[3,4],[4,5]])\n        y = [-6,1,-2]\n\n        # Returns x_hat, the least squares solution of y = Ax\n        lp.least_squares(A,y)\n\n        # [ 3.86666667 -3.18666667]\n\n    '''\n\n    # Ensures np.matrix type\n    matrix_a = np.matrix(matrix_a)\n\n    # x = (A' A)^-1 A' y\n    vector_x = np.dot(\n        np.dot(\n            np.linalg.inv(\n                np.dot(\n                    matrix_a.T, # A.T returns the transpose of A\n                    matrix_a\n                    )\n            ),\n            matrix_a.T\n        ),\n        vector_y\n    )\n\n    # Flattens result into an array\n    vector_x = np.squeeze(np.asarray(vector_x))\n\n    return vector_x\n\n\ndef tikhonov_regularization(matrix_a, vector_y, lambda_parameter=0):\n    '''\n    The standard approach to solve the problem :math:`y = Ax + n' explained above is to use the  ordinary least squares\n    method. However if your matrix :math:`A` is a fat matrix (it has more columns than rows) or it has a large condition number,\n    then you should use a regularization to your problem in order to get a meaningful estimation of :math:`x`.\n\n    The Tikhonov regularization is a tradeoff between the least squares \n    solution and the minimization of the L2-norm of the output :math:`x` (L2-norm =\n    sum of squared values of the vector :math:`x`),\n    :math:`\\\\hat x = {\\\\rm arg}\\\\min_x\\\\,\\\\lVert \\\\mathbf{y - Ax} \\\\rVert_2^2 + \\\\lambda\\\\lVert x \\\\rVert_2^2  `\n    \n    The parameter lambda tells how close to the least squares solution the\n    output :math:`x` will be; a large lambda will make :math:`x` close to L2-norm(x)=0, while\n    a small lambda will approach the least squares solution (Running\n    the function with lambda=0 will behave like the ordinary leat_squares()\n    method). \n\n    The solution is given by :math:`\\\\hat{\\\\mathbf{x}} = (A^{T}A+ \\\\lambda^{2} I)^{-1}A^{T}\\\\mathbf{y}`, where :math:`I` is the identity matrix.\n\n    Raises a ValueError if lambda < 0.\n\n    :param matrix_a: (np.matrix) matrix A in :math:`y = Ax + n'\n    :param vector_y: (array) vector y in :math:`y = Ax + n'\n    :param lambda: (int) lambda non-negative parameter to regulate the tradeoff.\n\n    :return array: vector_x solution of Tikhonov regularization\n\n    :raises ValueError: raises an exception if lambda_parameter < 0\n\n    Example : compute the solution of a system y = Ax (knowing y, A) which is a\n    tradeoff between the least squares solution and the minimization of x's\n    L2-norm. The greater lambda, the smaller the norm of the given solution. \n    We take a matrix A which is ill-conditionned.\n\n    .. code-block:: python\n\n        import numpy as np\n        import linvpy as lp\n\n        A = np.matrix([[7142.80730214, 6050.32000196],\n                       [6734.4239248, 5703.48709251],\n                       [4663.22591408, 3949.23319264]])\n\n        y = [0.83175086, 0.60012918, 0.89405644]\n\n        # Returns x_hat, the tradeoff solution of y = Ax\n        print lp.tikhonov_regularization(A, y, 50)\n\n        # [8.25871731e-05   4.39467106e-05]\n\n    '''\n\n    if lambda_parameter < 0:\n        raise ValueError('lambda_parameter must be zero or positive.')\n    if lambda_parameter == 0 :\n        return np.linalg.lstsq(matrix_a, vector_y)[0].reshape(-1)\n\n    # Ensures np.matrix type\n    matrix_a = np.matrix(matrix_a)\n\n    # Generates an identity matrix of the same shape as A'A.\n    # matrix_a.shape() returns a tuple (#row,#columns) so with [1] with take the\n    # number of columns to build the identity because A'A yields a square\n    # matrix of the same size as the number of columns of A and rows of A'.\n    identity_matrix = np.identity(matrix_a.shape[1])\n\n    try:\n        # x = (A' A + lambda^2 I)^-1 A' y\n        vector_x = np.dot(\n            np.dot(\n                np.linalg.inv(\n                    np.add(\n                        np.dot(matrix_a.T, matrix_a), # A.T transpose of A\n                        np.dot(math.pow(lambda_parameter,2), identity_matrix)\n                    ),\n                ),\n                matrix_a.T\n            ),\n            vector_y\n        )\n\n        # Flattens result into an array\n        vector_x = np.squeeze(np.asarray(vector_x))\n        return vector_x\n\n    # catches Singular matrix error (or any other error), prints the trace\n    except :\n        print(\"Lambda parameter may be too small.\")\n        raise\n\n\n\n\ndef rho_huber(input, clipping=1.345):\n    '''\n    The regular huber loss function; the \"rho\" version.\n\n    :math:`\\\\rho(x)=\\\\begin{cases}\n    \\\\frac{1}{2}{x^2}& \\\\text{if |x| <=} clipping, \\\\\\\\\n    clipping (|x| - \\\\dfrac{1}{2} clipping)& \\\\text{otherwise}.\n    \\\\end{cases}`\n\n    This function is quadratic for small inputs, and linear for large \n    inputs, with equal values and slopes of the different sections at the two\n    points where |input|= clipping. The variable a often refers to the residuals, \n    that is to the difference between the observed and predicted values \n    a=y-f(x)\n\n    :param input: (float) residual to be evaluated\n    :param clipping: (optional)(float) clipping parameter \n\n    :return float: penalty incurred by the estimation\n\n    Example : run huber loss on a vector\n\n    .. code-block:: python\n\n        import linvpy as lp\n\n        x = [1,2,3,4,5,6,7,8,9]\n\n        loss = [lp.rho_huber(e, 4) for e in x]\n\n        # [0.5, 2.0, 4.5, 8.0, 12, 16, 20, 24, 28]\n    '''\n    # Casting input to float to avoid divisions rounding\n    input = float(input)\n\n    if clipping <= 0 :\n        raise ValueError('clipping must be positive.')\n\n    if (np.absolute(input) <= clipping):\n        return math.pow(input, 2)/2.0\n    else :\n        return clipping * (np.subtract(np.absolute(input),clipping/2.0))\n\n\ndef psi_huber(input, clipping=1.345):\n    '''\n    Derivative of the Huber loss function; the \"psi\" version. Used in the weight \n    function of the M-estimator.\n\n    :math:`\\\\psi(x)=\\\\begin{cases}\n    x& \\\\text{if |x| <=} clipping, \\\\\\\\\n    clipping * sign(x) & \\\\text{otherwise}.\n    \\\\end{cases}`\n\n    :param input: (float) residual to be evaluated\n    :param clipping: (optional)(float) clipping parameter \n\n    :return float: penalty incurred by the estimation\n\n    Example : run huber loss derivative on a vector\n\n    .. code-block:: python\n\n        import linvpy as lp\n\n        x = [1,2,3,4,5,6,7,8,9]\n\n        derivative = [lp.psi_huber(e, 4) for e in x]\n\n        # [1, 2, 3, 4, 4, 4, 4, 4, 4]\n\n    '''\n    # Casting input to float to avoid divisions rounding\n    input = float(input)\n\n    if clipping <= 0 :\n        raise ValueError('clipping must be positive.')\n\n    if (np.absolute(input) >= clipping):\n        return clipping * np.sign(input)\n    else :\n        return input\n\ndef rho_bisquare(input, clipping=4.685):\n    '''\n    The regular bisquare loss (or Tukey's loss), \"rho\" version.\n\n    :math:`\\\\rho(x)=\\\\begin{cases}\n    (c^2 / 6)(1-(1-(x/c)^2)^3)& \\\\text{if |x|} \\\\leq 0, \\\\\\\\\n    c^2 / 6& \\\\text{if |x| > 0}.\n    \\\\end{cases}`\n\n    :param input: (float) residual to be evaluated\n    :param clipping: (optional)(float) clipping parameter\n\n    :return float: result of bisquare function\n\n    Example : run huber loss on a vector\n\n    .. code-block:: python\n\n        import linvpy as lp\n\n        x = [1,2,3,4,5,6,7,8,9]\n\n        result = [lp.rho_bisquare(e, 4) for e in x]\n\n        # [0.46940104166666663, 1.5416666666666665, 2.443359375, 2.6666666666666665, 2.6666666666666665, 2.6666666666666665, 2.6666666666666665, 2.6666666666666665, 2.6666666666666665]\n    '''\n    # Casting input to float to avoid divisions rounding\n    input = float(input)\n\n    if clipping <= 0 :\n        raise ValueError('clipping must be positive.')\n\n    if (np.absolute(input) <= clipping):\n        return (\n            (clipping**2.0)/6.0)*(\n                1-(\n                    (1-(\n                        input/clipping)**2)\n                    **3)\n                )\n    else :\n        return (clipping**2)/6.0\n\n\ndef psi_bisquare(input, clipping=4.685):\n    '''\n    The derivative of bisquare loss (or Tukey's loss), \"psi\" version.\n\n    :math:`\\\\psi(x)=\\\\begin{cases}\n    x((1-(x/c)^2)^2)& \\\\text{if |x|} \\\\leq 0, \\\\\\\\\n    0& \\\\text{if |x| > 0}.\n    \\\\end{cases}`\n\n    :param input: (float) residual to be evaluated\n    :param clipping: (optional)(float) clipping parameter\n\n    :return float: result of bisquare function\n\n    Example : run huber loss on a vector\n\n    .. code-block:: python\n\n        import linvpy as lp\n\n        x = [1,2,3,4,5,6,7,8,9]\n\n        result = [lp.psi_bisquare(e, 4) for e in x]\n\n        # [0.87890625, 1.125, 0.57421875, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n    '''\n    # Casting input to float to avoid divisions rounding\n    input = float(input)\n\n    if clipping <= 0 :\n        raise ValueError('clipping must be positive.')\n\n    if (np.absolute(input) <= clipping):\n        return input*((1-(input/clipping)**2)**2)\n    else :\n        return 0.0\n\n\ndef rho_cauchy(input, clipping=2.3849):\n    '''\n    Cauchy loss function; the \"rho\" version.\n\n    :math:`\\\\rho(x)=(c^2/2)log(1+(x/c)^2)`\n\n    :param input: (float) residual to be evaluated\n    :param clipping: (optional)(float) clipping parameter \n\n    :return float: result of the cauchy function\n\n    Example : run huber loss on a vector\n\n    .. code-block:: python\n\n        import linvpy as lp\n\n        x = [1,2,3,4,5,6,7,8,9]\n\n        result = [lp.rho_cauchy(e, 4) for e in x]\n\n        # [0.4849969745314787, 1.7851484105136781, 3.5702968210273562, 5.545177444479562, 7.527866755716213, 9.42923997073317, 11.214388381246847, 12.875503299472802, 14.416978050108813]\n    '''\n  # Casting input to float to avoid divisions rounding\n    input = float(input)\n\n    if clipping <= 0 :\n        raise ValueError('clipping must be positive.')\n\n    return (\n        (clipping**2)/2\n        )*math.log(\n        1+(\n            input/clipping)**2)\n\n\ndef psi_cauchy(input, clipping=2.3849):\n    '''\n    Derivative of Cauchy loss function; the \"psi\" version.\n\n    :math:`\\\\psi(x)=\\\\frac{x}{1+(x/c)^2}`\n\n    :param input: (float) residual to be evaluated\n    :param clipping: (optional)(float) clipping parameter \n\n    :return float: result of the cauchy's derivative function\n\n    Example : run huber loss on a vector\n\n    .. code-block:: python\n\n        import linvpy as lp\n\n        x = [1,2,3,4,5,6,7,8,9]\n\n        result = [lp.psi_cauchy(e, 4) for e in x]\n\n        # [0.9411764705882353, 1.6, 1.92, 2.0, 1.951219512195122, 1.8461538461538463, 1.7230769230769232, 1.6, 1.4845360824742269]\n    '''\n\n    # Casting input to float to avoid divisions rounding\n    input = float(input)\n\n    if clipping <= 0 :\n        raise ValueError('clipping must be positive.')\n\n    return input/(\n        1+(\n            input/clipping\n            )**2)\n\ndef rho_optimal(input, clipping=3.270):\n    '''\n    The so-called optimal 'rho' function is given by\n    :math:`\\\\rho(x)=\\\\begin{cases}\n    1.38(x/c)^2 & \\\\text{if |x/c|} \\\\leq 2/3, \\\\\\\\\n    0.55 - 2.69(x/c)^2 + 10.76(x/c)^4 - 11.66(x/c)^6 + 4.04(x/c)^8 & \\\\text{if 2/3 }<|x/c| \\\\leq 1, \\\\\\\\\n    1 &  \\\\text{if |x/c| > 1}.\n    \\\\end{cases}`\n\n    :param input: (float) residual to be evaluated\n    :param clipping: (optional)(float) clipping parameter \n\n    :return float: result of the optimal function\n    '''\n\n    # Casting input to float to avoid divisions rounding\n    input = float(input)\n\n    if clipping <= 0 :\n        raise ValueError('clipping must be positive.')\n    if abs(input/clipping) <= 2.0 / 3.0 :\n        return 1.38 * (input/clipping)**2\n    elif abs(input/clipping) <= 1.0 :\n        return 0.55 - (2.69 * (input/clipping)**2) + (\n            10.76 * (input/clipping)**4) - (\n            11.66 * (input/clipping)**6) + (\n            4.04 * (input/clipping)**8)\n    elif abs(input/clipping) > 1 :\n        return 1.0\n\n\ndef psi_optimal(input, clipping=3.270):\n    '''\n    The derivative of the optimal 'rho' function is given by\n    :math:`\\\\rho(x)=\\\\begin{cases}\n    2*1.38 x / c^2 & \\\\text{if |x/c|} \\\\leq 2/3, \\\\\\\\\n    2*2.69x / c^2 + 4*10.76x^3 / c^4 - 6*11.66x^5/ c^6 + 8*4.04x^7 /c^8 & \\\\text{if 2/3 }<|x/c| \\\\leq 1, \\\\\\\\\n    0 &  \\\\text{if |x/c| > 1}.\n    \\\\end{cases}`\n\n\n    :param input: (float) residual to be evaluated\n    :param clipping: (optional)(float) clipping parameter \n\n    :return float: result of the optimal function\n    '''\n\n    if clipping <= 0:\n        raise ValueError('clipping must be positive.')\n\n    if abs(input / clipping) <= 2.0 / 3.0:\n        return 2 * 1.38 * (input / clipping ** 2)\n    elif abs(input / clipping) <= 1.0:\n        return (- 2 * 2.69 * (input / clipping ** 2)) + (\n            4 * 10.76 * (input ** 3 / clipping ** 4)) - (\n                   6 * 11.66 * (input ** 5 / clipping ** 6)) + (\n                   8 * 4.04 * (input ** 7 / clipping ** 8))\n    elif abs(input / clipping) > 1:\n        return 0\n\n\ndef weights(input, loss_function, clipping=None, nmeasurements=None):\n    '''\n    Returns an array of :\n\n    :math:`\\\\begin{cases}\n    \\\\frac{loss\\\\_function(x_i)}{x_i}& \\\\text{if } x_i \\\\neq 0, \\\\\\\\\n    0& \\\\text{otherwise}.\n    \\\\end{cases}`\n\n    Weights function designed to be used with loss functions like rho_huber, \n    psi_huber, rho_cauchy... Note that the loss_function passed in argument must\n    support two inputs.\n\n    :param input: (array or float) vector or float to be processed, x_i's\n    :param loss_function: (loss_function) f(x) in f(x)/x.\n    :param clipping: (optional) clipping parameter of the huber loss function.\n\n    :return array or float: element-wise result of f(x)/x if x!=0, 0 otherwise\n\n    Example : run the weight function with the psi_huber with default\n    clipping or with another function like rho_cauchy and another clipping.\n\n    .. code-block:: python\n\n        import linvpy as lp\n\n        x = [1,2,3,4,5]\n\n        # psi_huber, default clipping\n        lp.weights(x, lp.psi_huber)\n\n        # [1.0, 0.67249999999999999, 0.44833333333333331, 0.33624999999999999, 0.26900000000000002]\n\n        # rho_cauchy, clipping=2.5\n        lp.weights(x, lp.rho_cauchy, 2.5)\n\n        # [0.46381251599460444, 0.7729628778689174, 0.9291646242761568, 0.9920004256749526, 1.0058986952713127]\n\n    '''\n\n    # kwargs = keyword arguments : if clipping is not specified, kwargs=None\n    # and we use the default loss function's clipping, otherwise we use the one\n    # passed in weights() with **kwargs\n    kwargs = {}\n    if clipping != None:\n        kwargs['clipping'] = clipping\n\n    if isinstance(input, (int, float)):\n        if (input == 0) :\n            return 0.0\n        return loss_function(input, **kwargs)/float(input)\n\n    # only used for the tau estimator\n    elif (nmeasurements!=None) :\n        z = util.scorefunction(input, 'tau', **kwargs)\n        w = np.zeros(input.shape)\n\n        # only for the non zero u elements\n        i = np.nonzero(input)\n        w[i] = z[i] / (2 * nmeasurements * input[i])\n        return w\n\n    else :\n        # Ensures the input is an array and not a matrix. \n        # Turns [[a b c]] into [a b c].\n\n        input = np.squeeze(\n                    np.asarray(\n                        input\n                        )\n                    ).flatten()\n\n        output = [0 if (i == 0) else 0.5*loss_function(i, **kwargs)/float(i) for i in input]\n        return np.array(output)\n\n\n# scale = sigma that divides; if sigma if given in parameter => preliminary scale\n# lmb = lambda for tikhonov => if lambda is given : regularized m-estimator\n# if lamb and scale are given : regularized m-estimator with preliminary scale\ndef irls(matrix_a, vector_y, loss_function, clipping=None, scale=None, lamb=0, initial_x=None, regularization=tikhonov_regularization, kind=None, b=0.5, tolerance=1e-5, max_iterations=100):\n    '''\n    The method of iteratively reweighted least squares (IRLS) is used to solve\n    certain optimization problems with objective functions of the form:\n\n    :math:`\\underset{ \\\\boldsymbol x } {\\operatorname{arg\\,min}} \\sum_{i=1}^n | y_i - loss\\\\_function_i (\\\\boldsymbol x)|^p`\n\n    by an iterative method in which each step involves solving a weighted least \n    squares problem of the form:\n\n    :math:`\\\\boldsymbol x^{(t+1)} = \\underset{\\\\boldsymbol x} {\\operatorname{arg\\,min}} \\sum_{i=1}^n w_i (\\\\boldsymbol x^{(t)})\\\\big| y_i - loss\\\\_function_i (\\\\boldsymbol x) \\\\big|^2.`\n\n    IRLS is used to find the maximum likelihood estimates of a generalized \n    linear model, and in robust regression to find an M-estimator, as a way of \n    mitigating the influence of outliers in an otherwise normally-distributed \n    data set. For example, by minimizing the least absolute error rather than \n    the least square error.\n\n    :param matrix_a: (np.matrix) matrix A in y - Ax\n    :param vector_y: (array) vector y in y - Ax\n    :param loss_function: the loss function to be used in the M estimator\n    :param clipping: clipping parameter for the loss function\n\n    :return array: vector x solution of IRLS\n\n    '''\n\n    # If a scale parameter is given, m-estimator runs with preliminary scale.\n    # This checks that scale is int or float and nonzero.\n    # If no scale is given, scale = 1.0\n    if (scale == None) or (scale == 0):\n        scale = 1.0\n\n    # kwargs = keyword arguments : if clipping is not specified, kwargs=None\n    # and we use the default loss function's clipping, otherwise we use the one\n    # passed in weights() with **kwargs\n    # If the tau option is used, the function needs a clipping as tuple,\n    # otherwise only one clipping is given.\n    kwargs = {}\n    if clipping != None :\n        kwargs['clipping'] = clipping\n    \n    # if an initial value for x is specified, use it, otherwise generate a\n    # vector of ones\n    if initial_x != None:\n        vector_x = initial_x\n    else :\n        # Generates a ones vector_x with length = matrix_a.columns\n        vector_x = np.ones(matrix_a.shape[1])\n        initial_x = np.ones(matrix_a.shape[1])\n    \n    # number of measurements and unknowns; by default None, if tau is used it\n    # takes value m,n = matrix_a.shape\n    m = None\n\n    # Ensures numpy types\n    matrix_a = np.matrix(matrix_a)\n    vector_y = vector_y.reshape(-1,1)\n\n    # Residuals = y - Ax, difference between measured values and model\n    residuals = vector_y - np.dot(matrix_a, initial_x).reshape(-1,1)\n\n    for i in range(1,max_iterations):\n\n        # if we are computing the tau estimator, we need to upgrade the estimation of the scale in each iteration\n        if kind == 'tau':\n\n            m,n = matrix_a.shape\n\n            residuals = np.asarray(residuals.reshape(-1)).flatten()\n\n            # scale = scale * (mean(loss_function(residuals/scale))/b)^1/2\n            if (scale != 0) :\n                scale  *= np.sqrt(\n                    np.mean(\n                        array_loss(residuals / scale, loss_function, clipping[0])\n                        ) / b\n                    )\n        \n        # normalize residuals ((y - Ax)/ scale)\n        if (scale != 0) :\n            rhat = np.array(residuals / scale).flatten()\n        else :\n            rhat = np.array(residuals).flatten()\n\n\n        # weights(y-Ax, loss_function, clipping)\n        weights_vector = weights(rhat, loss_function, nmeasurements=m, **kwargs)\n\n        # Makes a diagonal matrix with values of w(y-Ax)\n        # np.squeeze(np.asarray()) is there to flatten the matrix into a vector\n        weights_matrix = np.diag(\n            np.squeeze(\n                np.asarray(weights_vector)\n                )\n            )\n\n        #print \"weights matrix = \", weights_matrix\n\n        # Square root of the weights matrix, sqwm = W^1/2\n        #sqwm = np.sqrt(weights_vector.reshape(-1,1))\n\n        sqwm = np.sqrt(weights_matrix)\n\n\n        # A_weighted = W^1/2 A\n        a_weighted = np.dot(sqwm,matrix_a)\n\n        # y_weighted = diagonal of W^1/2 y\n        #sqwm = sqwm.reshape(-1)\n\n        y_weighted = np.dot(sqwm, vector_y)\n\n        # vector_x_new is there to keep the previous value to compare\n        vector_x_new = regularization(a_weighted, y_weighted, lamb)\n\n        # Normalized distance between previous and current iteration\n        xdis = np.linalg.norm(vector_x - vector_x_new)\n\n        # New residuals\n        residuals = vector_y.reshape(-1) - np.dot(matrix_a, vector_x_new).reshape(-1)\n\n        # Divided by the specified optional scale, otherwise scale = 1\n        #residuals = np.array(residuals / scale).flatten()\n\n        vector_x = vector_x_new\n\n        # if the difference between iteration n and iteration n+1 is smaller \n        # than tolerance, return vector_x\n        if (xdis < tolerance):\n            return vector_x\n\n    return vector_x\n\n\ndef basictau(a, y, loss_function, clipping, ninitialx, maxiter=100, nbest=1, initialx=None, b=0.5, regularization=tikhonov_regularization, lamb=0):\n    '''\n    This routine minimizes the objective function associated with the tau-estimator.\n    This function is hard to minimize because it is non-convex. This means that it has several local minima. Depending on\n    the initial x that we use for our minimization, we will end up in a different local minimum (for the m-estimator is\n    not like this; the function in that case is convex and we always arrive to it, independently of the initial solution)\n\n    In this algorithm we take the 'brute force' approach: let's try many different initial solutions, and let's pick the\n    minimum with smallest value. The output of basictau are the best nbest minima (we will need them later)\n\n    :param a: matrix A in y - Ax\n    :param y: vector y in y - Ax\n    :param loss_function: type of the rho function we are using\n    :param clipping: clipping parameters. In this case we need two, because the rho function for the tau is composed two rho functions.\n    :param ninitialx: how many different solutions do we want to use to find the global minimum (this function is not convex!)\n                      if ninitialx=0, means the user introduced a predefined initial solution\n    :param maxiter: maximum number of iteration for the irls algorithm\n    :param nbest: we return the best nbest solutions. This will be necessary for the fast algorithm\n    :param initialx: the user can define here the initial x he wants\n    :param b: this is a parameter to estimate the scale\n\n    :return xhat: contains the best nmin estimations of x\n    :return mintauscale: value of the objective function when x = xhat\n    '''\n\n    # to store the minimum values of the objective function (in this case is\n    # the scale)\n    mintauscale = np.empty((nbest, 1))\n\n    # initializing objective function with infinite. When we have a x that gives a smaller value for the obj. function,\n    # we store the value of the objective function here\n    mintauscale[:] = float(\"inf\")\n\n    # count how many initial solutions are we trying\n    k = 0\n\n    # store here the best xhat (nbest of them)\n    xhat = np.zeros((a.shape[1], nbest))  # to store the best nmin minima\n\n    # auxiliary variable to check if the user introduced a predefined initial solution.\n    # = 0 if we do not have initial x. =1 if we have a given initial x\n    givenx = 0\n\n    if (initialx == None) :\n        initialx = np.ones(a.shape[1])\n\n    if ninitialx == 0:\n        # we have a predefined initial x\n        ninitialx = initialx.shape[1]\n        # set givenx to 1\n        givenx = 1\n\n    while k < ninitialx:\n        # if still we did not reach the number of initial solutions that we want to try,\n        # get a new initial solution initx (randomly)\n        initx = util.getinitialsolution(y.reshape(-1, 1), a)\n\n        if givenx == 1:\n            # if we have a given initial solution initx, we take it\n            initx = np.expand_dims(initialx[:, k], axis=1)\n\n        # compute the residual y - Ainitx\n        initialres = y.reshape(-1, 1) - np.dot(a, initx)\n\n        # estimate the scale using initialres\n        initials = np.median(np.abs(initialres)) / .6745\n\n        # solve irls using y, a, the tau weights, initx and initals. We get an\n        # estimation of x, xhattmp\n        xhattmp = irls(\n            a,\n            y,\n            loss_function,\n            clipping,\n            scale=initials,\n            initial_x=initx,\n            kind='tau',\n            b=0.5,\n            max_iterations=maxiter,\n            regularization=regularization,\n            lamb=lamb)\n\n        # last working version\n        # xhattmp, scaletmp, ni, w, steps = inv.irls(y, a, 'tau', 'optimal', 'none', 0, initx, initials, clipping, maxiter)\n\n        # compute the value of the objective function using xhattmp\n        # we compute the res first\n        res = y.reshape(-1, 1) - np.dot(a, xhattmp).reshape(-1, 1)\n\n        # Value of the objective function using xhattmp\n        #tscalesquare = util.tauscale(res, lossfunction, clipping, b)\n\n        tscalesquare = util.tauscale(res, 'optimal', clipping[0], b)\n\n        # update counter\n        k += 1\n\n        # we checks if the objective function has a smaller value that then\n        # ones we found before\n        if tscalesquare < np.amax(mintauscale):\n            # it is smaller, so we keep it!\n            # store value for the objective function\n            mintauscale[np.argmax(mintauscale)] = tscalesquare\n\n            # store value of xhat\n            xhat[:, np.argmax(mintauscale)] = np.squeeze(xhattmp)\n\n    # we return the best solutions we found, with the value of the objective\n    # function associated with the xhats\n    return xhat, mintauscale\n\n# TODO : need doc here\ndef fasttau(y, a, loss_function, clipping, ninitialx, nmin=5, initialiter=5):\n  xhat, mintauscale = basictau(a=a, y=y, loss_function=loss_function, clipping=clipping, ninitialx=ninitialx, maxiter=initialiter, nbest=nmin)  # first round: only initialiter iterations. We keep the nmin best solutions\n\n  xfinal, tauscalefinal = basictau(a=a, y=y, loss_function=loss_function, clipping=clipping, ninitialx=0, maxiter=100, nbest=1, initialx=xhat)  # iterate the best solutions\n  # until convergence\n\n  return xfinal, tauscalefinal\n\n\n# function to apply a loss function to any data structure; scalar, array or matrix\n# returns the exact same data structure with the loss function applied element-wise\ndef array_loss(values, loss_function, clipping=None):\n\n    # if we input incorrect values (due to division by too tiny numbers in irls)\n    # inside array_loss, it returns zeroes\n    \n    # checks if there is a 'nan' value in the input\n    if np.any(np.isnan(values)) :\n        print \"incorrect input in array loss !\"\n        return np.zeros(values.shape)\n\n    kwargs = {}\n    if clipping != None:\n        kwargs['clipping'] = clipping\n\n    vfunc = np.vectorize(loss_function)\n    return vfunc(values, **kwargs)\n\n\ndef tau_weights_new(input, clipping, loss_function=rho_optimal):\n\n    weights = 2.0 * array_loss(input, loss_function, clipping[1]) \n    weights -= (util.scoreoptimal(input, clipping[1]) * input)\n    scaling = np.sum(util.scoreoptimal(input, clipping[0]) * input)\n\n    if (scaling == 0):\n        scaling = 1.0\n\n    return weights / scaling\n\n\n\n\n\n\n\n\n\n\n\n#===============================================================================\n#===================================TESTING AREA================================\n#===============================================================================\n\n", "meta": {"hexsha": "a451611109422c311b22a5cc83eef2538a3da0d0", "size": 28176, "ext": "py", "lang": "Python", "max_stars_repo_path": "linvpy.py", "max_stars_repo_name": "bisounoursrulio/package_test", "max_stars_repo_head_hexsha": "905db1bf8398055a9569f8245b00568a5f74c4c4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linvpy.py", "max_issues_repo_name": "bisounoursrulio/package_test", "max_issues_repo_head_hexsha": "905db1bf8398055a9569f8245b00568a5f74c4c4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linvpy.py", "max_forks_repo_name": "bisounoursrulio/package_test", "max_forks_repo_head_hexsha": "905db1bf8398055a9569f8245b00568a5f74c4c4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9879372738, "max_line_length": 219, "alphanum_fraction": 0.6146720613, "include": true, "reason": "import numpy", "num_tokens": 7835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018362008348, "lm_q2_score": 0.9149009520925732, "lm_q1q2_score": 0.8922130884225693}}
{"text": "import numpy as np\n\n\ndef mape(y_true, y_pred, version=0) -> float:\n    r\"\"\"\n    .. math::\n        mape = mean(|Y - Y_hat| / |Y|))\n\n    Args:\n        y_true (np.array): Ground truths\n        y_pred (np.array): Forecasts\n        version (int, optional): Version 0 is as-is implementation of formula. Version 1 & 2 deal with div-by-0, but\n            version=1 ignores those with y=0 from calculation. Defaults to 0.\n\n    Returns:\n        array of floats: mape values\n    \"\"\"\n\n    if version == 0:\n        return np.mean(np.abs((y_true - y_pred) / y_true))\n    elif version == 1:\n        # This version takes care of div-by-0, and ignore 0-y in nominator.\n        # See: https://github.com/awslabs/gluon-ts/pull/725\n        denominator = np.abs(y_true)\n        flag = denominator == 0\n        return np.mean((np.abs(y_true - y_pred) * (1 - flag)) / (denominator + flag))\n    elif version == 2:\n        # This version takes care of div-by-0, and include 0-y in nominator.\n        denominator = np.abs(y_true)\n        flag = denominator == 0\n        return np.mean(np.abs(y_true - y_pred) / (denominator + flag))\n\n    raise ValueError(f\"Unknown mape version: {version}\")\n\n\ndef wmape(actual, forecast, version=0) -> float:\n    r\"\"\"\n    .. math::\n        wmape = mape * (actual / sum(actual))\n\n    This implementation assumes actual are positives -- FIXME: would it be\n    better to enforce this assumption by using sum(abs(actual))?\n\n    Args:\n        actual (np.array): Ground truths\n        forecast (np.array): Forecasts\n        version (int, optional): mape version to use. See mape(). Defaults to 0 (which\n            may perform division-by-zero).\n\n    Returns:\n        array of floats: wmape values\n    \"\"\"\n    # we take two series and calculate an output a wmape from it.\n    # - NOTE: as-is implementation from Logbooks/Med_Low/Weekly_AutoArima.ipynb\n\n    # make a series called mape\n    se_mape = mape(actual, forecast, version=version)\n\n    # get a float of the sum of the actual\n    # - NOTE: this as-is implementation assumes actual are positives. Would it\n    # be better to enforce this assumption by using np.sum(np.abs(actual))?\n    ft_actual_sum = actual.sum()\n\n    # get a series of the multiple of the actual & the mape\n    se_actual_prod_mape = actual * se_mape\n\n    # summate the prod of the actual and the mape\n    ft_actual_prod_mape_sum = se_actual_prod_mape.sum()\n\n    # float: wmape of forecast\n    ft_wmape_forecast = ft_actual_prod_mape_sum / ft_actual_sum\n\n    # return a float\n    return ft_wmape_forecast\n", "meta": {"hexsha": "0d763f22f5e98e89b0641a218fbd4ab39f3abee1", "size": 2531, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/entrypoint/gluonts_example/metrics.py", "max_stars_repo_name": "yinsong1986/amazon-sagemaker-gluonts-entrypoint", "max_stars_repo_head_hexsha": "46c2a3398254fad2d95e282ba0392534e851519e", "max_stars_repo_licenses": ["MIT-0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-10-30T05:33:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T04:10:49.000Z", "max_issues_repo_path": "src/entrypoint/gluonts_example/metrics.py", "max_issues_repo_name": "yinsong1986/amazon-sagemaker-gluonts-entrypoint", "max_issues_repo_head_hexsha": "46c2a3398254fad2d95e282ba0392534e851519e", "max_issues_repo_licenses": ["MIT-0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-23T15:22:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-24T02:05:48.000Z", "max_forks_repo_path": "src/entrypoint/gluonts_example/metrics.py", "max_forks_repo_name": "yinsong1986/amazon-sagemaker-gluonts-entrypoint", "max_forks_repo_head_hexsha": "46c2a3398254fad2d95e282ba0392534e851519e", "max_forks_repo_licenses": ["MIT-0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-01-04T14:12:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T00:47:21.000Z", "avg_line_length": 33.7466666667, "max_line_length": 116, "alphanum_fraction": 0.6420387199, "include": true, "reason": "import numpy", "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018405251303, "lm_q2_score": 0.9149009457116781, "lm_q1q2_score": 0.8922130861562108}}
{"text": "import numpy as np\r\n\r\n# TRANSPOSE OF MATRIX --> convert from rows to columns and columns to rows\r\n\r\nmatrix = np.random.randint(10,100,(4,2))\r\n\"\"\" array([[19, 11],\r\n       [25, 83],\r\n       [30, 63],\r\n       [51, 76]])\r\n \"\"\"\r\n\r\ntranspose_matrix = matrix.T\r\n\"\"\" \r\narray([[19, 25, 30, 51],\r\n       [11, 83, 63, 76]]) \"\"\"\r\n\r\n# DETERMINANT OF MATRIX --> volume of the matrix\r\n\r\nmatrix = np.random.randint(10,100,(4,4))\r\n\"\"\" \r\narray([[59, 68, 57, 92],\r\n       [48, 50, 36, 63],\r\n       [30, 52, 45, 32],\r\n       [62, 66, 97, 65]])\r\n       \"\"\"\r\n\r\nfrom numpy.linalg import det\r\n\r\ndet_matrix = det(matrix)\r\n# -912991.9999999997\r\n\r\n# RANK OF THE MATRIX --> estimate of linearly independent rows or columns\r\n\r\nvector = np.array([1,2,3])\r\n\r\nnp.linalg.matrix_rank(vector)\r\n# 1\r\n\r\nmatrix = np.random.randint(10,100,(4,4))\r\nnp.linalg.matrix_rank(matrix)\r\n# 4", "meta": {"hexsha": "4e5a259f3abde87420cbd52fdee219d370db7b72", "size": 843, "ext": "py", "lang": "Python", "max_stars_repo_path": "matrix/matrix_operations.py", "max_stars_repo_name": "Akshaykumarcp/linear_algebra", "max_stars_repo_head_hexsha": "083f1d8d77b944d9b8e85eb34c65b87794a9b6ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-06T12:26:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T11:31:53.000Z", "max_issues_repo_path": "matrix/matrix_operations.py", "max_issues_repo_name": "Akshaykumarcp/practical_linear_algebra", "max_issues_repo_head_hexsha": "083f1d8d77b944d9b8e85eb34c65b87794a9b6ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matrix/matrix_operations.py", "max_forks_repo_name": "Akshaykumarcp/practical_linear_algebra", "max_forks_repo_head_hexsha": "083f1d8d77b944d9b8e85eb34c65b87794a9b6ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5609756098, "max_line_length": 75, "alphanum_fraction": 0.5670225386, "include": true, "reason": "import numpy,from numpy", "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9833429585263219, "lm_q2_score": 0.907312213841788, "lm_q1q2_score": 0.8921990766662506}}
{"text": "from sympy import *\nfrom sympy.solvers import solve\nfrom sympy import Symbol\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx=Symbol('x')\na1=Symbol('a1')\na2=Symbol('a2')\na3=Symbol('a3')\na4=Symbol('a4')\na5=Symbol('a5')\neqn_gal2 =[]\neqn_gal3 =[]\neqn_gal4 =[]\n\n\nu2 = a1 + a2*x + a3*x*x\nz2=u2.subs(a1,solve(u2.subs(x,1)-2 , a1)[0])\nz2=z2.subs(a2,solve((x*diff(u2,x)+0.5).subs(x,2),a2)[0])\n# finding residual\nr_gal2=diff(x*(diff(z2,x)),x)-(2/(x*x))\neqn_gal2.append(integrate(r_gal2*x*x, (x, 1, 2)))\nz_gal2 = solve(eqn_gal2, a3)\nprint(\"Equation for Quadratic\",eqn_gal2)\nprint(z_gal2)\n\nu3 = a1 + a2*x + a3*x*x + a4*x*x*x\nz3=u3.subs(a1,solve(u3.subs(x,1)-2 , a1)[0])\nz3=z3.subs(a2,solve((x*diff(u3,x)+0.5).subs(x,2),a2)[0])\n# finding residual\nr_gal3=diff(x*(diff(z3,x)),x)-(2/(x*x))\n# galerkian integral wrt weighting functions\neqn_gal3.append(integrate(r_gal3*x*x, (x, 1, 2)))\neqn_gal3.append(integrate(r_gal3*x*x*x, (x, 1, 2)))\nz_gal3 = solve(eqn_gal3, [a3,a4])\nprint(\"Equation for Qubic\",eqn_gal3)\nprint(z_gal3)\n\nu4 = a1 + a2*x + a3*x*x + a4*x*x*x + a5*x*x*x*x\nz4=u4.subs(a1,solve(u4.subs(x,1)-2 , a1)[0])\nz4=z4.subs(a2,solve((x*diff(u4,x)+0.5).subs(x,2),a2)[0])\n# finding residual\nr_gal4=diff(x*(diff(z4,x)),x)-(2/(x*x))\n# galerkian integral wrt weighting functions\neqn_gal4.append(integrate(r_gal4*x*x, (x, 1, 2)))\neqn_gal4.append(integrate(r_gal4*x*x*x, (x, 1, 2)))\neqn_gal4.append(integrate(r_gal4*x*x*x*x, (x, 1, 2)))\nz_gal4 = solve(eqn_gal4, [a3,a4,a5])\nprint(\"Equation for Biquadratic\",eqn_gal4)\nprint(z_gal4)\n\n# plotting the curve\nu_gal2=[]\nu_gal3=[]\nu_gal4=[]\nu_exact=[]\ny = []\ni=1\nwhile i<=2:\n    y.append(i)\n    u_gal2.append((z2.subs(a3,z_gal2.get(a3))).subs(x,i))\n    u_gal3.append(((z3.subs(a3,z_gal3.get(a3))).subs(a4,z_gal3.get(a4))).subs(x,i))\n    u_gal4.append((((z4.subs(a3,z_gal4.get(a3))).subs(a4,z_gal4.get(a4))).subs(a5,z_gal4.get(a5))).subs(x,i))\n    u_exact.append((2/i)+0.5*np.log(i))\n    i+=0.1\n\nplt.plot(y, u_gal2, label=\"Quadratic\")\nplt.plot(y, u_gal3, label=\"Qubic\")\nplt.plot(y, u_gal4, label=\"Biquadratic\")\nplt.plot(y, u_exact, label=\"Exact\")\nplt.legend()\nplt.xlabel('x', fontsize=16)\nplt.ylabel('u', fontsize=16)\nplt.suptitle('Solutions with different Trial functions')\nprint(\"It can be observed from the graph that Biquadratic trial function \\n has the least error and almost coincides with the exact soluton\")\nplt.show()\n", "meta": {"hexsha": "edb3de96cb45035fc41ddd2a1b76f2f071cd0e8b", "size": 2355, "ext": "py", "lang": "Python", "max_stars_repo_path": "A_2/p4.py", "max_stars_repo_name": "nimRobotics/FEM", "max_stars_repo_head_hexsha": "1b8019109b66b5d95b7caeb113f8d306a2c3c226", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A_2/p4.py", "max_issues_repo_name": "nimRobotics/FEM", "max_issues_repo_head_hexsha": "1b8019109b66b5d95b7caeb113f8d306a2c3c226", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A_2/p4.py", "max_forks_repo_name": "nimRobotics/FEM", "max_forks_repo_head_hexsha": "1b8019109b66b5d95b7caeb113f8d306a2c3c226", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1923076923, "max_line_length": 141, "alphanum_fraction": 0.672611465, "include": true, "reason": "import numpy,from sympy", "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357555117625, "lm_q2_score": 0.911179705790928, "lm_q1q2_score": 0.8920775116660067}}
{"text": "\"\"\"\nCheck out https://www.youtube.com/watch?v=gMlf1ELvRzc ; Veritasium is a good addiction to have. \nWe are using an area sampling method. Instead of doing a perimeter method like Archimedes's method of polygon ratios, \nwe are just taking ratios of areas in this code. We can do that only using a computer using randomness. \nA similar method might be using integration to find out the area of the circle and the area of the square. \n\n- Side note, Issac Newton as a motherfucking genius. It took me 28 years to appreciate his contributions to the world. \n\n\"\"\"\nimport numpy as np\n\n\n# Setting the seed for reproducibility.\nSEED = 1\n\n\ndef sample_a_point(random_generator):\n    \"\"\"Sample a 2D point within a square of length 1.\n    \n    Returns:\n        point: Dict of form {'x': x-coordinate, 'y': y-coordinate} \n\n    \"\"\"\n    # Uniform distribution is enough.\n    point = dict(x=random_generator.rand(1)[0], y=random_generator.rand(1)[0])\n    return point\n\n\ndef check_within_a_unit_circle(point):\n    radius = 1.0 # Radius of a unit circle\n    cartesian_distance = np.sqrt(point['x']**2 + point['y']**2)\n    return cartesian_distance <= radius\n\n\ndef sample_and_estimate_pi(num_iterations=10000, seed=SEED):\n    \"\"\"Find pi by the ratio of points within a unit circle and a square tangential and enclosing it.\n   \n    - To enclose a unit circle, the square's length is 2*r = 2, hence the area being 4.0\n    - Area of the unit circle is pi * r**2 = pi\n    - Hence ratio of areas = pi / 4.0\n    - pi = 4.0 * ratio of areas\n    - Ratio of areas = 4.0 * (points in circle) / (points in square)\n    \n    \"\"\"\n    rng = _get_random_generator(seed)\n    estimated_pi = 0 \n    diff_from_prev_iteration = np.inf\n\n    total_circle_canditates = 0\n\n    for total_square_candidates in range(num_iterations):\n        current_point = sample_a_point(random_generator=rng)\n        if(check_within_a_unit_circle(current_point)):\n            total_circle_canditates += 1\n        \n        if total_square_candidates == 0:\n            new_estimated_pi = 1.0\n        else:\n            new_estimated_pi = 4.0 * float(total_circle_canditates) / (total_square_candidates)\n\n        diff_from_prev_iteration = np.abs(new_estimated_pi - estimated_pi)\n        estimated_pi = new_estimated_pi\n\n    return estimated_pi \n\n\ndef _get_random_generator(seed):\n    return np.random.RandomState(seed=seed) \n\n\ndef integration_method(num_of_rectangles):\n    \"\"\"Following the method here: https://www.youtube.com/watch?v=uK2OQMUAUDQ\n    \n    Basically `num_of_rectangles` is the number of rectangles representing a quarter circle.\n\n    \"\"\"\n    estimated_area_of_quarter = 0.\n    width = 1. / num_of_rectangles\n    for rectangle_num in range(1 , num_of_rectangles):\n        x_k = (rectangle_num  - 1) * width  # first x starts from 0, hence the -1\n        # Applying the circle equation to find \"y\"\n        y_k = np.sqrt(1 - x_k**2)\n\n        # y_k is the height of the rectangle, i.e. length\n        current_area = y_k * width\n        estimated_area_of_quarter += current_area\n\n    # pi * r^2 / 4 = total_area_of_of_quarter; r=1 in this case.\n    pi = estimated_area_of_quarter * 4   \n    return pi\n\n\nif __name__ == \"__main__\":\n    apple_pie = sample_and_estimate_pi(num_iterations=100000)\n    print(f\"Estimated pi using random area sampling as {apple_pie}\")\n    assert np.isclose(apple_pie, np.pi, rtol=1e-3)\n    \n    pecan_pie = integration_method(10000)\n    print(f\"Estimated pi using summation as {pecan_pie}\")\n    assert np.isclose(pecan_pie, np.pi, rtol=1e-3)\n\n", "meta": {"hexsha": "b223c95c00444b8947a60fc3e02e5593d9761499", "size": 3517, "ext": "py", "lang": "Python", "max_stars_repo_path": "mathematics_problems/pi_estimation.py", "max_stars_repo_name": "saunair/project_pegasus", "max_stars_repo_head_hexsha": "3e3070c43bc871834ab289edfcdb38c01c32f621", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mathematics_problems/pi_estimation.py", "max_issues_repo_name": "saunair/project_pegasus", "max_issues_repo_head_hexsha": "3e3070c43bc871834ab289edfcdb38c01c32f621", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mathematics_problems/pi_estimation.py", "max_forks_repo_name": "saunair/project_pegasus", "max_forks_repo_head_hexsha": "3e3070c43bc871834ab289edfcdb38c01c32f621", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4803921569, "max_line_length": 119, "alphanum_fraction": 0.6923514359, "include": true, "reason": "import numpy", "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620608291781, "lm_q2_score": 0.9294404072330196, "lm_q1q2_score": 0.8920416406638735}}
{"text": "'''\nnumpy 패키지를 사용한 벡터 연산\n'''\nimport numpy as np\nprint('numpy version:',np.__version__)\nimport math\n\n# 파이썬 list 데이터 타입의 연산\nv =[1,2] # type : class list\nprint(type(v))\nprint('v=',v)\n\nw =[2,3]\nprint('w=',w)\n\nprint(v + w)\n# list는 + 연산을 사용할 수 있음\n# + 연산자는 extend 함수와 비슷한 기능\n# + 연산자는 v나 w를 변경하지 않고, 새로운 리스트를 리턴\n# v.extend(w) 함수는 v를 변경함\n# print(v- w) # list는 - 연산을 사용할 수 없음!\nv.extend(w)\nprint(v)\n\n# numpy 패키지의 ndarray 타입을 사용\n# n-dimensional array(n차원 배열)\nv = np.array([1,2])\nprint('type :', type(v))\nprint(v)\nprint('dimension:', v.ndim)\nprint('shape:', v.shape) # 1차원 배열의 경우의 원소의 갯수를 나타냄\n\nv = np.array([\n    [1,2],\n    [2,3],\n    [3,4]\n])\nprint('type:', type(v))\nprint('dimension:',v.ndim)\nprint('shape:', v.shape) # 2차원 에서 부터는 행의 갯수가 x위치 컬럼의 갯수가 y위치로 출력됨.\nprint(v)\n\n#ndarray 타입을 사용한 벡터 연산\nv = np.array([1,2,3])\nw = np.array([3,4,5])\nvector_add = v + w\nprint('vector add =', vector_add)\n\nvector_sub = v - w\nprint('vector subtract =', vector_sub)\n\nvectors = np.array([\n    [1,2],\n    [3,4],\n    [5,6]\n])\n\nnp_sum = np.sum(vectors) # 2차원 배열의 모든 원소들의 합\nprint('np_sum =',np_sum)\n\n#axis=0: 2차원 배열에서 각 컬럼들의 합으로 이루어진 배열\nnp_sum_by_col = np.sum(vectors,axis=0)\nprint('np_sum_by_col =', np_sum_by_col)\n\n#axis=1: 2차원 배열에서 각 행들의 합으로 이루어진 배열\nnp_sum_by_row = np.sum(vectors, axis=1)\nprint('np_sum_by_row =', np_sum_by_row)\n\nnp_mean = np.mean(vectors)\nprint('np_mean =',np_mean)\n\nnp_mean_by_col = np.mean(vectors, axis=0)\nprint('np_mean_by_col =',np_mean_by_col)\n\nnp_mean_by_row = np.mean(vectors, axis=1)\nprint('np_mean_by_row =',np_mean_by_row)\n\nv = np.array([1,2,3])\nscalar_mul = v * 3\nprint('scalar multiplication =', scalar_mul)\nscalar_div = v / 3\nprint('scalar division =', scalar_div)\n\nv = np.array([1,2])\nw = np.array([3,4])\nprint('dot =', v.dot(w))\n\n#numpy를 사용한 벡터의 크기\ndef norm(v):\n    return math.sqrt(v.dot(v))\n\nv = np.array([1,1])\nprint('norm =', norm(v))\n\n# numpy를 사용한 두 벡터의 거리\ndef dist(v,w):\n    return norm(v - w)\n", "meta": {"hexsha": "27366682447f21da749c803078b12a7f52ed9c3f", "size": 1905, "ext": "py", "lang": "Python", "max_stars_repo_path": "scratch04/ex02.py", "max_stars_repo_name": "SOOIN-KIM/lab-python", "max_stars_repo_head_hexsha": "4b85dc11c76e2d4f89be0d01864f9f61f3c6e2cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scratch04/ex02.py", "max_issues_repo_name": "SOOIN-KIM/lab-python", "max_issues_repo_head_hexsha": "4b85dc11c76e2d4f89be0d01864f9f61f3c6e2cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scratch04/ex02.py", "max_forks_repo_name": "SOOIN-KIM/lab-python", "max_forks_repo_head_hexsha": "4b85dc11c76e2d4f89be0d01864f9f61f3c6e2cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4387755102, "max_line_length": 66, "alphanum_fraction": 0.6430446194, "include": true, "reason": "import numpy", "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620608291781, "lm_q2_score": 0.9294404047899393, "lm_q1q2_score": 0.8920416383190977}}
{"text": "import scipy.optimize as optimize\nimport numpy as np\n\n\n# **************** problem #1 ******************\ndef func(x):\n    return np.cos(x)**2 + 6 - x\n\n\ndef f(x):\n    return np.power(x, 2) + 6.0 * x + 4\n\n\ndef f_prime(x):\n    return 2.0 * x + 6.0\n\n# 0<=cos(x)**2<=1, so the root has to be between x=6 and x=7\nprint(optimize.bisect(func, 6, 7))\n6.77609231632\n\na = optimize.bisect(f, -1, 0)\n\nprint(\"This is the bisection method:{:.16e}\".format(a))\n# -7.6393202249983005e-01\nprint(\"This is the bisection method:{0}\".format(a))\n# -0.7639320225\n\n\n# ********************* problem #2 ******************\n\n\ndef g(x):\n    return (-4.0) / x + 6.0\n\n\ndef h(x):\n    return -1.0 * np.sqrt(-6.0 * x - 4.0)\n\n# This finds the value of x such that func(x) = x, that is, where\n# -x**3 + 1 = x\nprint(optimize.fixed_point(g, -5.2))\n# 5.2360679775\n\nprint(optimize.fixed_point(h, -0.77))\n\n# ***************** problem #4 ********************\n# use the secant method.\n# well scipy.optimize.newton() uses the secant method if we don't give it the functions derivative.\n\na = 0\n\na = optimize.newton(f, 0, tol=1e-16, maxiter=8)\n\n\ndef convergence(n_plus_one, n):  # using equation (1) from the assignment. where -7.6 is the fixed point \"s\"\n    numerator = np.log(np.abs(n_plus_one - -7.6393202250021031e-01))\n    denominator = np.log(np.abs(n - -7.6393202250021031e-01))\n    return numerator / denominator\n\nprint(\"This is the convergence:\", convergence(-0.74996874883, -0.66665555574))\nprint(\"This is the convergence:\", convergence(-0.763636264454, -0.74996874883))\nprint(\"This is the convergence:\", convergence(-0.763931103843, -0.763636264454))\n\nprint(\"This is secant method answer {:.16e}\".format(a))\n\n# **************** problem #5 ***********************\n\n# newton() will use the newton raphson method because we gave it the derivative.\na = optimize.newton(f, 0, fprime=f_prime, tol=1e-16, maxiter=14)\n\nprint\"This is Newton method answer{:.16e}\".format(a)\n\n\nprint(\"This is the convergence:\", convergence(-0.761904761905, -0.666666666667))\nprint(\"This is the convergence:\", convergence(-0.763931104357, -0.761904761905))\nprint(\"This is the convergence:\", convergence(-0.7639320225, -0.763931104357))\n\n# ************* problem #6 *********************\n\n\ndef k(x):\n    return np.power(x, 20) - 10.0\n\n\ndef k_prime(x):\n    return 20.0 * np.power(x, 19)\n\n\na = optimize.newton(k, 8, fprime=k_prime, tol=1e-16, maxiter=44)\n\nprint\"This is Newton method answer: {:.16e}\".format(a)\n\n# **************** problem #7 ************\n\n\ndef f(x):\n    return np.power(x,2) - 6.0*x + 9.0\n\n\ndef f_prime(x):\n    return 2.0 * x - 6.0\n\na = optimize.newton(f, 4, fprime=f_prime, tol=1e-16, maxiter=29)\n\nprint\"This is Newton method answer: {:.16e}\".format(a)\n\n\ndef convergence(n_plus_one, n):  # using equation (1) from the assignment. where -7.6 is the fixed point \"s\"\n    numerator = np.log(np.abs(n_plus_one - 3.0000000298023224e+00))\n    denominator = np.log(np.abs(n - 3.0000000298023224e+00))\n    return numerator / denominator\n\n\nprint(\"This is the convergence:\", convergence(3.25, 3.5))\nprint(\"This is the convergence:\", convergence(3.125, 3.25))\nprint(\"This is the convergence:\", convergence(3.0625, 3.125))\n\nprint(\"This is the convergence:\", convergence(3.00000011921, 3.00000023842 ))\n", "meta": {"hexsha": "9c565780ddc6d1e2239a01773e6790a6be2a2e71", "size": 3236, "ext": "py", "lang": "Python", "max_stars_repo_path": "watkins_math448/assignment3.py", "max_stars_repo_name": "johnnydevriese/wsu_courses", "max_stars_repo_head_hexsha": "b55efd501c2d8f0651891f422a486e32533f5aa0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "watkins_math448/assignment3.py", "max_issues_repo_name": "johnnydevriese/wsu_courses", "max_issues_repo_head_hexsha": "b55efd501c2d8f0651891f422a486e32533f5aa0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "watkins_math448/assignment3.py", "max_forks_repo_name": "johnnydevriese/wsu_courses", "max_forks_repo_head_hexsha": "b55efd501c2d8f0651891f422a486e32533f5aa0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1932773109, "max_line_length": 108, "alphanum_fraction": 0.6338071693, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474181553803, "lm_q2_score": 0.9343951607140232, "lm_q1q2_score": 0.8920179277125239}}
{"text": "#From http://scipy.github.io/old-wiki/pages/Cookbook/LoktaVolterraTutorial\nimport numpy as np\nimport matplotlib.pyplot as plt\n# Definition of parameters\na = 1.\nb = 0.1\nc = 1.5\nd = 0.75\ndef dX_dt(X, t=0):\n    \"\"\" Return the growth rate of fox and rabbit populations. \n        It appears that it needs to take a numpy array in, just one,\n        and returns the same. \"\"\"\n    return np.array([ a*X[0] -   b*X[0]*X[1] ,\n                  -c*X[1] + d*b*X[0]*X[1] ])\n#Population equilibrium points when dX_dt = 0. \nX_f0 = np.array([     0. ,  0.])\nX_f1 = np.array([ c/(d*b), a/b])\n\nall(dX_dt(X_f0) == np.zeros(2) ) and all(dX_dt(X_f1) == np.zeros(2)) # => True\n\n#Create the Jacobian for the purpose of evaluating eigenvalues etc. \ndef d2X_dt2(X, t=0):\n    \"\"\" Return the Jacobian matrix evaluated in X. \"\"\"\n    return np.array([[a -b*X[1],   -b*X[0]     ],\n                  [b*d*X[1] ,   -c +b*d*X[0]] ])\n#So near X_f0, which represents the extinction of both species, we have:\nA_f0 = d2X_dt2(X_f0)        # >>> array([[ 1. , -0. ],\n                                        #            [ 0. , -1.5]])\n\n#Near X_f0, the number of rabbits increase and the population of foxes decrease. \n#The origin is therefore a saddle point.\n#Near X_f1, we have:                                        \nA_f1 = d2X_dt2(X_f1)                    # >>> array([[ 0.  , -2.  ],\n                                        #            [ 0.75,  0.  ]])\n# whose eigenvalues are +/- sqrt(c*a).j:\nlambda1, lambda2 = np.linalg.eigvals(A_f1) # >>> (1.22474j, -1.22474j)\n# They are imaginary numbers. The fox and rabbit populations are periodic as follows from further\n# analysis. Their period is given by:\nT_f1 = 2*np.pi/abs(lambda1)                # >>> 5.130199  \n\n#Integrate the functions in terms of a starting point. \nfrom scipy import integrate\nt = np.linspace(0, 15,  1000)              # time\nX0 = np.array([10, 5])                     # initials conditions: 10 rabbits and 5 foxes\nX, infodict = integrate.odeint(dX_dt, X0, t, full_output=True)\ninfodict['message']                     # >>> 'Integration successful.'\n#Plot the evolution of both populations.\nrabbits, foxes = X.T\nfig, (ax0,ax1) = plt.subplots(2,1,figsize=(8,8))\nax0.plot(t, rabbits, 'r-', label='Rabbits')\nax0.plot(t, foxes  , 'b-', label='Foxes')\nax0.grid()\nax0.legend(loc='best')\nax0.set_xlabel('time')\nax0.set_ylabel('population')\nax0.set_title('Evolution of fox and rabbit populations')\n#f1.savefig('rabbits_and_foxes_1.png')   \n#Plot the phase space.\nvalues  = np.linspace(0.3, 0.9, 5)                          # position of X0 between X_f0 and X_f1\nvcolors = plt.cm.autumn_r(np.linspace(0.3, 1., len(values)))  # colors for each trajectory\n#-------------------------------------------------------\n# plot trajectories\nfor v, col in zip(values, vcolors): \n    X0 = v * X_f1                               # starting point\n    X = integrate.odeint( dX_dt, X0, t)         # we don't need infodict here\n    ax1.plot( X[:,0], X[:,1], lw=3.5*v, color=col, label='X0=(%.f, %.f)' % ( X0[0], X0[1]) )\n\n#-------------------------------------------------------\n# define a grid and compute direction at each point\nymax = ax1.set_ylim(ymin=0)[1]                        # get axis limits\nxmax = ax1.set_xlim(xmin=0)[1] \nnb_points   = 20                      \n\nx = np.linspace(0, xmax, nb_points)\ny = np.linspace(0, ymax, nb_points)\n\nX1 , Y1  = np.meshgrid(x, y)                       # create a grid\nDX1, DY1 = dX_dt([X1, Y1])                      # compute growth rate on the gridt\nM = (np.hypot(DX1, DY1))                           # Norm of the growth rate \nM[ M == 0] = 1.                                 # Avoid zero division errors \nDX1 /= M                                        # Normalize each arrows\nDY1 /= M                                  \n\n#-------------------------------------------------------\n# Drow direction fields, using matplotlib 's quiver function\n# I choose to plot normalized arrows and to use colors to give information on\n# the growth speed\nax1.set_title('Trajectories and direction fields')\nQ = ax1.quiver(X1, Y1, DX1, DY1, M, pivot='mid', cmap=plt.cm.jet)\nax1.set_xlabel('Number of rabbits')\nax1.set_ylabel('Number of foxes')\nax1.legend()\nax1.grid()\nax1.set_xlim(0, xmax)\nax1.set_ylim(0, ymax)\nplt.show()\n#f2.savefig('rabbits_and_foxes_2.png')                                                                         ", "meta": {"hexsha": "c1fdcb349cc41581ec5140c6cb41919618619042", "size": 4374, "ext": "py", "lang": "Python", "max_stars_repo_path": "Strogatz/Lokta-Volterra.py", "max_stars_repo_name": "yuchiaol/Non-linear-dynamics-Strogatz", "max_stars_repo_head_hexsha": "79e1171d4a88193d3da67c15f41212a96e6854dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 64, "max_stars_repo_stars_event_min_datetime": "2017-11-21T12:47:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:23:29.000Z", "max_issues_repo_path": "Strogatz/Lokta-Volterra.py", "max_issues_repo_name": "Llewelyn62/Non-linear-dynamics-Strogatz", "max_issues_repo_head_hexsha": "79e1171d4a88193d3da67c15f41212a96e6854dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Strogatz/Lokta-Volterra.py", "max_forks_repo_name": "Llewelyn62/Non-linear-dynamics-Strogatz", "max_forks_repo_head_hexsha": "79e1171d4a88193d3da67c15f41212a96e6854dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2017-11-21T20:11:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T00:00:30.000Z", "avg_line_length": 45.0927835052, "max_line_length": 111, "alphanum_fraction": 0.5461819845, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452443, "lm_q2_score": 0.9407897558991953, "lm_q1q2_score": 0.8920140761200628}}
{"text": "import math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef newtonMethod(func, derFunc, tol, guess,root):\n    cur = guess\n    if derFunc(root) == 0:\n        return None\n    else:\n        cur = guess\n        while abs(cur - root) > tol:\n            try:                                        #Check if the derivate function at x_n is 0\n                cur = cur - (func(cur)/derFunc(cur))\n            except:\n                return None\n    if cur != cur:                                        #Check cur ends up at nan\n        return None\n    return cur\n\ndef hwHelper(showVisuals):\n    func = lambda x: 1/(np.exp(x)+1) - 1/2                  #Function Set Up\n    dFunc = lambda x: -np.exp(x)/math.pow(np.exp(x)+1,2)    #First Derivative\n    tol = 10**(-9)                                          #Tolerance\n    root = 0                                                #Root of Funciton\n\n    start = -5.0                                            #Variables for the interval [-5,5]\n    end = 5.0\n    points = 50000\n    potentialGuess = np.linspace(start,end,num=points)      #Created 5000 points between -5 and 5\n\n\n    valids = []\n    for x in potentialGuess:                                #Iterating through each point in potentialGuess and saving all the points that coverged into an array\n        if newtonMethod(func,dFunc,tol,x,root) is not None:\n            valids.append((x, newtonMethod(func,dFunc,tol,x,root)))\n\n\n    # Visuals - Printing out all the results\n    if showVisuals:\n        print(\"\\n\\n\\n\\n\\n\")\n\n        print(\"Grid: \\n Start: {}\\n End: {} \\n # of Points: {}\\n\".format(start,end,points))\n\n        print(\"(Approx.) Lowest intial Guess that's valid is {}:\\n With a Final Guess of: {}\\n\".format(valids[0][0],valids[0][1]))\n        print(\"(Approx.) Highest intial Guess that's valid is {}:\\n With a Final Guess of: {}\\n\".format(valids[len(valids)-1][0],valids[len(valids)-1][1]))\n    return (valids[0][0],valids[len(valids)-1][0])\n\n\ndef extraCreditOne():\n    orignalFunc = lambda x: 1/(np.exp(x)+1) - 1/2\n    intevals = hwHelper(True)\n    x = np.linspace(intevals[0],intevals[1],num=1000)\n    y = orignalFunc(x)\n    \n\n    xw = np.arange(-5,6)\n    yw = orignalFunc(xw)\n    line2, = plt.plot(xw,yw,color = \"blue\",label=\"Original Function\")\n    line1, = plt.plot(x,y,color = \"red\",label=\"Original Function -  With Intervals\")\n    plt.xlabel(\"X-Values\")\n    plt.ylabel(\"Y-Values (Function Output)\")\n    plt.title(\"Function: \\\"1/(e^x + 1) - 0.5\\\" for the intervals \\nwhere Newton's Method Converges\")\n    plt.legend(handles=[line1,line2])\n    plt.show()\n\n\n# hwHelper(True)\nextraCreditOne()", "meta": {"hexsha": "218bf9f146bfa6857f6c08bb6e541ed727b2fc90", "size": 2611, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW3/homeworkScript.py", "max_stars_repo_name": "kai-handelman/NumericalAnalysisHomework", "max_stars_repo_head_hexsha": "2153dc39405168cabbf5c33c1238e64ceb96adf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW3/homeworkScript.py", "max_issues_repo_name": "kai-handelman/NumericalAnalysisHomework", "max_issues_repo_head_hexsha": "2153dc39405168cabbf5c33c1238e64ceb96adf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW3/homeworkScript.py", "max_forks_repo_name": "kai-handelman/NumericalAnalysisHomework", "max_forks_repo_head_hexsha": "2153dc39405168cabbf5c33c1238e64ceb96adf1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3970588235, "max_line_length": 161, "alphanum_fraction": 0.5557257756, "include": true, "reason": "import numpy", "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147169737826, "lm_q2_score": 0.9173026505426832, "lm_q1q2_score": 0.8919985973067639}}
{"text": "from scipy.stats import norm\nimport matplotlib.pyplot as plt\nimport numpy as np \n\n\n# I'm going to define my normal PDF...\ndef normal_pdf(x, mean, std):\n    return 1/(np.sqrt(2*np.pi*std**2))*np.exp(-0.5*((x - mean)**2)/(std**2))\n\n\nx = np.arange(-12, 12, .001)\n\npdf1 = normal_pdf(x, mean=0, std=2)\n\n#the built-in norm PDF in scipy.stats\npdf2 = norm.pdf(x, loc=0, scale=2)\n\nfig = plt.figure(figsize=(7,9))\nax1 = fig.add_subplot(3, 1, 1)\nax1.plot(x,pdf1, color='#84b4e8', linestyle=\"-\", linewidth=6, label=\"My normal PDF\")\nax1.plot(x,pdf2, color='#ff464a', linestyle=\"--\", label=\"norm.pdf() in scipy.stats \")\nax1.set_xlabel(\"x\")\nax1.set_ylabel(\"PDF(x)\")\nax1.legend(title = r\"Normal PDF with $\\mu$=0 and 1$\\sigma$=2\")\n\n\nax2 = fig.add_subplot(3, 1, 2)\nfor i in [1, 2, 3]:\n     y = normal_pdf(x,0,i)\n     ax2.plot(x, y, label=r\"$\\mu$ = 0, 1$\\sigma$ = \" + str(i))\nax2.set_xlabel(\"x\")\nax2.set_ylabel(\"PDF(x)\")\nax2.legend()\n\nax3 = fig.add_subplot(3, 1, 3)\nfor i in [-3, 0, 3]:\n     y = normal_pdf(x, i, 1)\n     ax3.plot(x, y, label=r\"$\\mu$ = \" + str(i) + \", 1$\\sigma$ = 1\")\nax3.set_xlabel(\"x\")\nax3.set_ylabel(\"PDF(x)\")\nax3.legend()\n\nfig.tight_layout()", "meta": {"hexsha": "666259d8614b419d49c4c284dbfc4a07682620f8", "size": 1142, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/chapter_09/listing_09_01.py", "max_stars_repo_name": "guinslym/python_earth_science_book", "max_stars_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80, "max_stars_repo_stars_event_min_datetime": "2021-04-19T10:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:34:47.000Z", "max_issues_repo_path": "code/chapter_09/listing_09_01.py", "max_issues_repo_name": "guinslym/python_earth_science_book", "max_issues_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/chapter_09/listing_09_01.py", "max_forks_repo_name": "guinslym/python_earth_science_book", "max_forks_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2021-04-25T03:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:06:19.000Z", "avg_line_length": 26.5581395349, "max_line_length": 85, "alphanum_fraction": 0.619089317, "include": true, "reason": "import numpy,from scipy", "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9830850852465428, "lm_q2_score": 0.9073122257466114, "lm_q1q2_score": 0.891965116793338}}
{"text": "from __future__ import division\nimport numpy as np\nimport pylab as pl\n\ndef S(f,a,b):\n    # Implement's the Simpson's method\n    h = abs(b-a)\n    c = (a+b)/2.0\n    return (h/6.0) * (f(a) + 4*f(c) + f(b))\n\ndef adaptive_simpson(f,a,b,e,level_max):\n    retVal = None\n    c = (a+b)/2.0\n    s1 = S(f,a,b)\n    s2 = S(f,a,c) + S(f,c,b)\n    err = (1/15.0)*(abs(s2 - s1))\n    print \"c={}\".format(c)\n    inpts.append(a)\n    inpts.append(b)\n    inpts.append(c)\n    if level_max == 0 or err < e :\n        # base case \n        # print \" a={}, b={}, c={}, s1={}, s2={}, level={}\".format(a,b,c,s1,s2,level_max)\n        retVal = s2\n    elif  err > e:\n        # sub divide into left and right\n        left = adaptive_simpson(f,a,c,e/2.0,level_max -1)\n        right = adaptive_simpson(f,c,b,e/2.0,level_max -1)\n        retVal = left + right\n    return retVal\n\nif __name__ == '__main__':\n    # call adaptive simpson's for\n    e = 0.5 * 10**(-4)\n    level_max = 30\n    # function 1\n    f = lambda x: 4.0/(1 + x**2)\n    a = 0\n    b = 1\n    inpts = [] # intervals\n    result = adaptive_simpson(f,a,b,e,level_max)\n    print(\"Numerical Integral by adaptive simpson's method: {}\".format(result))\n\n    xmin,xmax = int(a-2),int(b+2)+1 # for plots\n    ymin,ymax = -5,5 # for plots\n    x = np.linspace(xmin,xmax,1000)#floor and ceil used incase a and b are not ints\n    x_interest = np.linspace(a,b,1000)\n    pl.plot(x,f(x))\n    pl.plot(x_interest, f(x_interest),color='red')\n    # plotting axes\n    pl.plot(range(xmin,xmax+1), 0*np.arange(xmin,xmax+1), color='black')\n    pl.plot(0*np.arange(ymin,ymax+1), range(ymin,ymax+1), color='black')\n    pl.scatter(inpts, [0 for _ in inpts], color=\"green\")\n    pl.plot()\n    pl.xlabel(\"x\")\n    pl.ylabel(\"f(x)\")\n    pl.xlim(xmin,xmax)\n    pl.ylim(ymin,ymax)\n    pl.grid()\n    pl.savefig(\"ex5_fig1.pdf\")\n    pl.show()\n    \n    # function 2\n    f = lambda x: np.cos(2.0*x)/(np.e ** x)\n    a = 0\n    b = 2*np.pi\n    inpts = [] # intervals\n    result = adaptive_simpson(f,a,b,e,level_max)\n    print(\"Numerical Integral by adaptive simpson's method: {}\".format(result))\n\n    xmin,xmax = int(a-2),int(b+2)+1 # for plots\n    ymin,ymax = -0.3,1.3 # for plots\n    x = np.linspace(xmin,xmax,1000)#floor and ceil used incase a and b are not ints\n    x_interest = np.linspace(a,b,1000)\n    pl.xlabel(\"x\")\n    pl.xlim(xmin,xmax)\n    pl.ylim(ymin,ymax)\n    pl.grid()\n    pl.ylabel(\"f(x)\")\n    pl.plot(x,f(x))\n    pl.plot(x_interest, f(x_interest),color='red')\n    # plotting axes\n    pl.plot(range(xmin,xmax+1), 0*np.arange(xmin,xmax+1), color='black')\n    pl.plot(0*np.arange(int(ymin)-1,int(ymax)+1), range(int(ymin)-1,int(ymax)+1), color='black')\n    pl.scatter(inpts, [0 for _ in inpts], color=\"green\")\n    pl.savefig(\"ex5_fig2.pdf\")\n    pl.show()\n", "meta": {"hexsha": "30491af23c03c5cc1585b40d4b9a573465e0e891", "size": 2750, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercise4/exercise5.py", "max_stars_repo_name": "kunalghosh/BECS-114.1100-Computational-Science", "max_stars_repo_head_hexsha": "ca91ac59cb5276d213c1aec50ae7786efe72ae43", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercise4/exercise5.py", "max_issues_repo_name": "kunalghosh/BECS-114.1100-Computational-Science", "max_issues_repo_head_hexsha": "ca91ac59cb5276d213c1aec50ae7786efe72ae43", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise4/exercise5.py", "max_forks_repo_name": "kunalghosh/BECS-114.1100-Computational-Science", "max_forks_repo_head_hexsha": "ca91ac59cb5276d213c1aec50ae7786efe72ae43", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.25, "max_line_length": 96, "alphanum_fraction": 0.5832727273, "include": true, "reason": "import numpy", "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.9304582588688366, "lm_q1q2_score": 0.8918793447930334}}
{"text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\n# A function to compute the first n terms of the given sequence\ndef computeSequence(n):\n\tdiff_seq = np.zeros(n)\n\t\n\t# Saving the first two terms of the difference equation\n\tdiff_seq[0] = 1.0/3.0\n\tdiff_seq[1] = 1.0/12.0\n\t\n\t# Getting the remaining terms\n\tfor i in range(2,n):\n\t\tdiff_seq[i] = 2.25 * diff_seq[i-1] - 0.5 * diff_seq[i-2]\t\n\treturn diff_seq\n\n# A function to generate the graph for the same\ndef get_plot(n):\n\t\n\t# Get the sequence corresponding to the difference equation\n\tdiff_seq = computeSequence(n+1)\n\t\n\t# Get the sequence corresponding to the recurrence relation solution\n\trec_seq = np.array([(pow(4.0,-1.0 * k)/3.0) for k in range(n+1)])\n\t\n\t# Get the sequence for the values of k \n\tk_seq = np.array([k for k in range(n+1)])\n\t\n\t# Generating the plots\n\tplt.plot(k_seq,rec_seq,'r',k_seq,diff_seq,'b')\n\tplt.xlabel('The values of K')\n\tplt.ylabel('The solution of the difference equation')\n\tplt.legend(['Exact solution','Sequence computed'])\n\tplt.yscale('log')\n\tplt.title('Semi-log plot of difference equation values v/s Point indices K')\n\tplt.savefig('q6_plot.png')\n\t\n# Calling the function as asked in the assignment statement\nif __name__ == '__main__':\n\tget_plot(80)\n\t\n\t\n", "meta": {"hexsha": "71688d4eaa92cfcd470296959337382a3b35e3c9", "size": 1238, "ext": "py", "lang": "Python", "max_stars_repo_path": "A1/Q6.py", "max_stars_repo_name": "Vedant2311/Numerical-Algorithms-Assignments", "max_stars_repo_head_hexsha": "a3816de42dc97ddbf3916e88367a0e72acf58452", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A1/Q6.py", "max_issues_repo_name": "Vedant2311/Numerical-Algorithms-Assignments", "max_issues_repo_head_hexsha": "a3816de42dc97ddbf3916e88367a0e72acf58452", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A1/Q6.py", "max_forks_repo_name": "Vedant2311/Numerical-Algorithms-Assignments", "max_forks_repo_head_hexsha": "a3816de42dc97ddbf3916e88367a0e72acf58452", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7906976744, "max_line_length": 77, "alphanum_fraction": 0.7148626817, "include": true, "reason": "import numpy", "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.9304582588688365, "lm_q1q2_score": 0.8918793425888927}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n@author: vladimirnesterov\nTen Little Algorithms by Jason Sachs from here https://www.embeddedrelated.com/showarticle/760.php\n\"\"\"\n\ndef euclidean_gcd(a,b):\n    \"\"\"Euclidean Algorithm to find greatest common divisor.\n    \n    Euclidean algorithm is an efficient method for computing \n    the greatest common divisor (GCD) of two integers (numbers), \n    the largest number that divides them both without a remainder [Wiki].\n\n    Args:\n        a (int): The first integer, > 0,\n        b (int): The second integer, > 0.\n\n    Returns:\n        int: the greatest common divisor.\n\n    \"\"\"\n    if a < b:\n        a,b = b,a\n    \n    while a > b:\n        a = a - b\n        \n    if (a != b):\n        #print(\"a =\", a, \"b =\", b)\n        a = euclidean_gcd(b, a)\n        \n    return a\n\n\ndef euclidean_ext_gcd(a,b):\n    \"\"\"Extended Euclidean Algorithm to find GCD and Bézout's identity.\n    \n    Extended Euclidean algorithm is an extension to the Euclidean algorithm, \n    and computes, in addition to the greatest common divisor (GCD) of integers \n    a and b, also the coefficients of Bézout's identity, which are integers \n    x and y such that ax+by = gcd(a,b) [Wiki].\n\n    Args:\n        a (int): The first integer, > 0,\n        b (int): The second integer, > 0.\n\n    Returns:\n        tuple(int,int,int): the gcd and coefficients x and y.\n\n    \"\"\"\n    def calc_next_step(a,b,s,spv,t,tpv):\n\n        if a < b:\n            a,b = b,a\n    \n        r = a\n        qs = 0\n        qt = 0\n        while r >= b:\n            r = r - b\n            qs += s\n            qt += t\n          \n        spv, s = s, spv - qs\n        tpv, t = t, tpv - qt\n        \n        return (b, r, s, spv, t, tpv )\n    \n    spv = 1\n    tpv = 0\n    s = 0\n    t = 1\n\n    flip = 0\n    if a < b:\n        flip = 1\n    \n    while (b != 0):\n        #print(\"a =\", a, \"b =\", b, \"s =\", s, \"t =\", t)\n        a,b,s,spv,t,tpv = calc_next_step(a,b,s,spv,t,tpv)\n        \n    return (a,tpv,spv) if flip else (a,spv,tpv)\n\ndef newton(f, f_derivative, x0, eps, kmax):\n    \"\"\"Newton's method for finding roots.\n    \n    The Newton's method (Newton–Raphson method) is a root-finding algorithm \n    which produces approximations to the roots (or zeroes) \n    of a real-valued function. [Wiki].\n\n    Args:\n        f (function): single-variable function f ,\n        f_derivative (function):  the function's derivative f ′,\n        x0 (float): initial guess,\n        eps (float): precision wanted,\n        kmax (int): maximum number of iterations.\n\n    Returns:\n        x (float): root of f(x) = 0.\n\n    \"\"\"\n    x = x0\n    x_prev = x0 + 2 * eps\n    i = 0\n\t\n    while (abs(x - x_prev) >= eps) and (i < kmax):\n        #print(\"Step\", i, \":\", int(x), int(x_prev), \", x - f(x) = \", int(x - f(x)), \", f_derivative(x) = \", int(f_derivative(x)), \"f/f'=\",int(f(x)/f_derivative(x)))\n        x, x_prev =  x - ( f(x) / f_derivative(x) ), x\n        i += 1\n        \n\n    return x\n\n\ndef rpmul(a,b):\n    \"\"\"Russian peasant multiplication.\n    \n    Simple multiplication on shifters, taken from \"Ten Little Algorithms\" by\n    Jason Sachs.\n\n    Args:\n        a (int): the first variable,\n        b (int): the second vairable.\n\n    Returns:\n        x (int): result of multiplication a*b.\n\n    \"\"\"\n    result = 0\n    while b != 0:\n        if b & 1:\n            result += a\n        b >>= 1\n        a <<= 1\n        \n    return result\n\ndef rpexp(a,b):\n    \"\"\"Russian peasant exponention.\n    \n    Exponention based on Russian peasant multiplication algorithm, \n    taken from \"Ten Little Algorithms\" by Jason Sachs.\n\n    Args:\n        a (int): the base,\n        b (int): the exponent.\n\n    Returns:\n        x (int): the b power of a, a**b.\n\n    \"\"\"\n    result = 1\n    while b != 0:\n        if b & 1:\n            result *= a\n        b >>= 1\n        a *= a\n    return result\n\ndef sp_iir_lpf(cutoff = 0.25, smpl_f = 1):\n    \"\"\"Single-pole IIR low-pass filter.\n    \n    A single-pole IIR filter design y += alpha * (x-y), \n    taken from \"Ten Little Algorithms\" by Jason Sachs.\n\n    Args:\n        cutoff (float): the cutoff frequency, can bi in proportion of sampling\n                        frequency or in hertz if sampling frequency is given as \n                        second argument\n        smpl_f (float): sampling frequency in hertz (optional).\n\n    Returns:\n        alpha (float):  filter coefficient alpha,\n        h (ndarray):    the frequency response as complex numbers,\n        w (ndarray):    the frequencies at which h was computed \n                        in proportion of pi\n\n    \"\"\"\n    import numpy as np\n    from scipy import signal\n    \n    # calculate coefficient\n    dt = 1/smpl_f\n    tau = 1 / cutoff\n    alpha = dt/tau\n    \n    \n    # do filtring and get impulse response to estimate parameters\n    '''\n    def do_filter(x, alpha, x0 = None):\n        y = np.zeros_like(x)\n        yk = x[0] if x0 is None else x0\n        for k in range(len(x)):\n            yk += alpha * (x[k]-yk)\n            y[k] = yk\n        return y\n    # make test impulse signal \n    smpls = np.zeros(1000)\n    smpls[0] = 1\n    # filter and get impulse response\n    filter_result = do_filter(smpls, alpha)\n    # get the filter parameters\n    w, h = signal.freqz(filter_result)\n    '''\n    \n    # get the frequency and phase response with help of scipy\n    '''\n    The function of the filter: y[n]=αx[n]+(1−α)y[n−1]\n    The transfer function is H(z)=α / 1-(1−α)z−1\n    '''\n    b = alpha\n    a = [1,-(1-alpha)]\n    w, h = signal.freqz(b,a)\n    # change radians to proportions of pi\n    for i in range(len(w)):\n        w[i] = w[i]/np.pi\n    \n    return alpha, h, w\n\ndef welford(x_array):\n    \"\"\"Welford's method.\n    \n    Mean and variance calculation using Welford's method, \n    taken from part 3 of \"Ten Little Algorithms\" by Jason Sachs.\n\n    Args:\n        x_array (array): sample sequence.\n\n    Returns:\n        M, S: mean and variance of x_array.\n\n    \"\"\"\n    k = 0 \n    M = 0\n    S = 0\n    for x in x_array:\n        k += 1\n        Mnext = M + (x - M) / k\n        S = S + (x - M)*(x - Mnext)\n        M = Mnext\n    return (M, S/(k-1))", "meta": {"hexsha": "f8ca7a7efe29576cc0fdcf5103e8dd0ec147e809", "size": 6060, "ext": "py", "lang": "Python", "max_stars_repo_path": "ten_little_algorithms.py", "max_stars_repo_name": "vladimirnesterov/ten-little-algorithms", "max_stars_repo_head_hexsha": "8df2e90c43e29a69171a3f6e1bf75ad4cd0759b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ten_little_algorithms.py", "max_issues_repo_name": "vladimirnesterov/ten-little-algorithms", "max_issues_repo_head_hexsha": "8df2e90c43e29a69171a3f6e1bf75ad4cd0759b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ten_little_algorithms.py", "max_forks_repo_name": "vladimirnesterov/ten-little-algorithms", "max_forks_repo_head_hexsha": "8df2e90c43e29a69171a3f6e1bf75ad4cd0759b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1452282158, "max_line_length": 164, "alphanum_fraction": 0.5397689769, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102552339746, "lm_q2_score": 0.921921835927664, "lm_q1q2_score": 0.8918766386005559}}
{"text": "# M. Yaşar Polatlı\r\n# 250201075\r\n\r\nimport numpy as np\r\nimport random\r\nimport matplotlib.pyplot as plt\r\nimport scipy.stats as stats\r\nfrom scipy.stats import semicircular\r\n\r\n# Experiment 1:\r\n\r\ns1 = np.random.uniform(0, 1, 50000)  # 50000 values from standard uniform distribution (0,1) independently.\r\n\r\nsamples1 = [np.sum(random.choices(s1, k=2)) for i in range(50000)]  # 50000 sum samples from randomly chosen 2 values.\r\n\r\nprint(\"Experiment 1: \")\r\nprint(\"Sample mean is \", np.mean(samples1))\r\nprint(\"Sample standard deviation is \", np.std(samples1))\r\nplt.figure()\r\nplt.title(\"Experiment 1: Histogram for generated random variables\")\r\nplt.hist(s1, 100, density=True)\r\nplt.show()\r\nplt.title(\"Experiment 1: Histogram for sums of generated random variables\")\r\nplt.hist(samples1, 100, density=True)\r\n# initializations for theoretical normal distribution curve\r\nmu = np.mean(samples1)\r\nsigma = np.std(samples1)\r\nx = np.linspace(mu - 6*sigma, mu + 6*sigma, 200)\r\nplt.plot(x, stats.norm.pdf(x, mu, sigma))\r\nplt.show()\r\n\r\n# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n\r\n# Experiment 2:\r\n\r\ns2 = np.random.uniform(0, 1, 50000)  # 50000 values from standard uniform distribution (0,1) independently.\r\n\r\nsamples2 = [np.sum(random.choices(s2, k=10)) for i in range(50000)]  # sum samples of randomly chosen 10 values.\r\n\r\nprint(\"Experiment 2: \")\r\nprint(\"Sample mean is \", np.mean(samples2))\r\nprint(\"Sample standard deviation is \", np.std(samples2))\r\nplt.figure()\r\nplt.title(\"Experiment 2: Histogram for sums of generated random variables\")\r\nplt.hist(samples2, 100, density=True)\r\n# initializations for theoretical normal distribution curve\r\nmu = np.mean(samples2)\r\nsigma = np.std(samples2)\r\nx = np.linspace(mu - 6*sigma, mu + 6*sigma, 200)\r\nplt.plot(x, stats.norm.pdf(x, mu, sigma))\r\nplt.show()\r\n\r\n# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n\r\n# Experiment 3:\r\n\r\ns3 = np.random.uniform(0, 1, 50000)  # 50000 values from standard uniform distribution (0,1) independently.\r\n\r\nsamples3 = [np.sum(random.choices(s3, k=50)) for i in range(50000)]  # sum samples of randomly chosen 50 values.\r\n\r\nprint(\"Experiment 3: \")\r\nprint(\"Sample mean is \", np.mean(samples3))\r\nprint(\"Sample standard deviation is \", np.std(samples3))\r\nplt.figure()\r\nplt.title(\"Experiment 3: Histogram for sums of generated random variables\")\r\nplt.hist(samples3, 100, density=True)\r\n# initializations for theoretical normal distribution curve\r\nmu = np.mean(samples3)\r\nsigma = np.std(samples3)\r\nx = np.linspace(mu - 6*sigma, mu + 6*sigma, 200)\r\nplt.plot(x, stats.norm.pdf(x, mu, sigma))\r\nplt.show()\r\n\r\n\r\n# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n\r\n# Experiment 4:\r\n\r\nsamples4 = np.array([])   # Array for sums of generated random variables.\r\nsamplesG = []   # Array for generated random variables.\r\n\r\ni = 0\r\nwhile i < 10000:    # Simulation continues 10000 times.\r\n\r\n    sSum = 0  # Holds total value to check the conditions.\r\n    sCount = 0  # Holds number of values which requested 100.\r\n\r\n    while sCount < 101:  # Number of values is 100.\r\n        if sSum < 40:\r\n            a1 = np.random.uniform(0.5, 1.5)\r\n            sSum += a1\r\n            samplesG.append(a1)  # Generated random variables added corresponding array to observe via histogram.\r\n        else:\r\n            a2 = np.random.uniform(-0.5, 0.5)\r\n            sSum += a2\r\n            samplesG.append(a2)  # Generated random variables added corresponding array to observe via histogram.\r\n        sCount += 1\r\n\r\n    samples4 = np.append(samples4, sSum)  # Appends sums to corresponding array to observe whether it converges to normal or not.\r\n\r\n    i += 1\r\n\r\nprint(\"Experiment 4: \")\r\nprint(\"Sample mean is \", np.mean(samples4))\r\nprint(\"Sample standard deviation is \", np.std(samples4))\r\n\r\nplt.figure()\r\nplt.title(\"Experiment 4: Histogram for generated random variables\")\r\nplt.hist(samplesG, 100, density=True)\r\nplt.show()\r\n\r\nplt.title(\"Experiment 4: Histogram for sums of generated random variables\")\r\nplt.hist(samples4, 100, density=True)\r\n# initializations for theoretical normal distribution curve\r\nmu = np.mean(samples4)\r\nsigma = np.std(samples4)\r\nx = np.linspace(mu - 6*sigma, mu + 6*sigma, 200)\r\nplt.plot(x, stats.norm.pdf(x, mu, sigma))\r\nplt.show()\r\n\r\n\r\n# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n\r\n# Experiment 5:\r\n\r\ns = semicircular.rvs(2, 1, size=50000)  # 50000 randomly generated values from a distribution of semi-circle of radius 1 centered at 2.\r\n\r\nsamples5 = [np.sum(random.choices(s, k=2)) for i in range(50000)]  # Number of values is 2.\r\n\r\nprint(\"Experiment 5: \")\r\nprint(\"Sample mean is \", np.mean(samples5))\r\nprint(\"Sample standard deviation is \", np.std(samples5))\r\nplt.figure()\r\nplt.title(\"Experiment 5: Histogram for generated random variables\")\r\nplt.hist(s, 100, density=True)\r\nplt.show()\r\nplt.title(\"Experiment 5: Histogram for sums of generated random variables\")\r\nplt.hist(samples5, 100, density=True)\r\n# initializations for theoretical normal distribution curve\r\nmu = np.mean(samples5)\r\nsigma = np.std(samples5)\r\nx = np.linspace(mu - 6*sigma, mu + 6*sigma, 200)\r\nplt.plot(x, stats.norm.pdf(x, mu, sigma))\r\nplt.show()\r\n\r\n# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n\r\n# Experiment 6:\r\n\r\nsamples6 = [np.sum(random.choices(s, k=10)) for i in range(50000)]  # Number of values is 10.\r\n\r\nprint(\"Experiment 6: \")\r\nprint(\"Sample mean is \", np.mean(samples6))\r\nprint(\"Sample standard deviation is \", np.std(samples6))\r\nplt.figure()\r\nplt.title(\"Experiment 6: Histogram for sums of generated random variables\")\r\nplt.hist(samples6, 100, density=True)\r\n# initializations for theoretical normal distribution curve\r\nmu = np.mean(samples6)\r\nsigma = np.std(samples6)\r\nx = np.linspace(mu - 6*sigma, mu + 6*sigma, 200)\r\nplt.plot(x, stats.norm.pdf(x, mu, sigma))\r\nplt.show()\r\n\r\n# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n\r\n# Experiment 7:\r\n\r\nsamples7 = [np.sum(random.choices(s, k=50)) for i in range(50000)]  # Number of values is 50.\r\n\r\nprint(\"Experiment 7: \")\r\nprint(\"Sample mean is \", np.mean(samples7))\r\nprint(\"Sample standard deviation is \", np.std(samples7))\r\nplt.figure()\r\nplt.title(\"Experiment 7: Histogram for sums of generated random variables\")\r\nplt.hist(samples7, 100, density=True)\r\n# initializations for theoretical normal distribution curve\r\nmu = np.mean(samples7)\r\nsigma = np.std(samples7)\r\nx = np.linspace(mu - 6*sigma, mu + 6*sigma, 200)\r\nplt.plot(x, stats.norm.pdf(x, mu, sigma))\r\nplt.show()\r\n", "meta": {"hexsha": "f53148b5cd5e8edf60529b9d3b19c0c0577123e2", "size": 6800, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw6/hw6_250201075.py", "max_stars_repo_name": "yelimot/probability-and-statistics", "max_stars_repo_head_hexsha": "c992bc8f3a7dea1483837dae07d29922b5f1eaea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw6/hw6_250201075.py", "max_issues_repo_name": "yelimot/probability-and-statistics", "max_issues_repo_head_hexsha": "c992bc8f3a7dea1483837dae07d29922b5f1eaea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw6/hw6_250201075.py", "max_forks_repo_name": "yelimot/probability-and-statistics", "max_forks_repo_head_hexsha": "c992bc8f3a7dea1483837dae07d29922b5f1eaea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1584699454, "max_line_length": 136, "alphanum_fraction": 0.6214705882, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211626883622, "lm_q2_score": 0.9149009457116781, "lm_q1q2_score": 0.8918648036433402}}
{"text": "\"\"\"\ndemo_1d_unconstrained_optimization.py.py\n\nMinimize a function of one variable:\nMinimize f(X)\n\nGolden section algorithm\n    Only special requirements.\n    \nFibonacci algorithm\n    Only special requirements.\n    \nNewton algorithm\n    Requires 1st and 2nd derivatives.\n    \nSecant algorithm\n    Requires only 1st derivative (2nd derivative estimated using 1st derivative).\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom bracketing import bracketing\nfrom golden_section_algorithm import golden_section_algorithm, golden_section_algorithm_calc_N_iter\nfrom fibonacci_algorithm import fibonacci_algorithm, fibonacci_algorithm_calc_N_iter\nfrom newton_algorithm import newton_algorithm\nfrom secant_algorithm import secant_algorithm\nfrom print_report import print_report\nfrom plot_progress_y import plot_progress_y\nimport time\n\nreg_coeff = 0.01; # regularization coefficient\n# Minimize the following objective function:\n# f(X) = X^4 - 14 * X^3 + 60 * X^2 - 70 * X + reg_coeff * X^2;\nfunc = lambda X : np.power(X, 4) - 14 * np.power(X, 3) + 60 * np.power(X, 2) -70 * X + reg_coeff * np.power(X, 2); \nfunc_1st_der = lambda X : 4 * np.power(X, 3) - 3 * 14 * np.power(X, 2) + 2 * 60 * np.power(X, 1) -70 + 2 * reg_coeff * X;\nfunc_2nd_der = lambda X : 3 * 4 * np.power(X, 2) - 2 * 3 * 14 * np.power(X, 1) + 2 * 60 + 2 * reg_coeff;\n \n# Plot the curve\nfig = plt.figure();\nX = np.arange(-5, 12, 0.5);\nY = np.empty(shape = X.size);\nfor ii in range(X.size):\n    Y[ii] = func(X[ii]);\n\nplt.plot(X, Y)\nplt.show()\n\n# Bracketing\nprint('***********************************************************************')\nprint('Bracketing')\nX0 = -20;\nstart = time.time();\ninterval0 = bracketing(X0, func, func_1st_der);\nend = time.time();\nprint(\"Minimizer lies in interval [%0.3f %0.3f]\" % (interval0[0], interval0[1]));\nprint('Elapsed time [s]: %0.5f' % (end - start));\nprint('***********************************************************************\\n')\n\n# Golden section algorithm\nprint('***********************************************************************')\nprint('Golden section algorithm')\nuncertainty_range_desired = 0.01;\nstart = time.time();\nN_iter = golden_section_algorithm_calc_N_iter(interval0, uncertainty_range_desired);\ninterval = golden_section_algorithm(func, interval0, N_iter);\nend = time.time();\nprint(\"Desired uncertainty range: %0.2f\" % (uncertainty_range_desired));\nprint(\"Algorithm converged in %d iteration\" % (N_iter));\nprint(\"Initial uncertainty interval: [%0.3f %0.3f]\" % (interval0[0], interval0[1]));\nprint(\"Reduced uncertainty interval: [%0.3f %0.3f]\" % (interval[0], interval[1]));\nprint('Elapsed time [s]: %0.5f' % (end - start));\nprint('***********************************************************************\\n')\n\n# Fibonacci algorithm\nprint('***********************************************************************')\nprint('Fibonacci algorithm')\nuncertainty_range_desired = 0.01;\nstart = time.time();\nN_iter, F = fibonacci_algorithm_calc_N_iter(interval0, uncertainty_range_desired);\ninterval = fibonacci_algorithm(func, interval0, N_iter, F);\nend = time.time();\nprint(\"Desired uncertainty range: %0.2f\" % (uncertainty_range_desired));\nprint(\"Algorithm converged in %d iteration\" % (N_iter));\nprint(\"Initial uncertainty interval: [%0.3f %0.3f]\" % (interval0[0], interval0[1]));\nprint(\"Reduced uncertainty interval: [%0.3f %0.3f]\" % (interval[0], interval[1]));\nprint('Elapsed time [s]: %0.5f' % (end - start));\nprint('***********************************************************************\\n')\n\n# Newton's algorithm\nprint('***********************************************************************')\nprint('Newton\\'s algorithm')\nN_iter_max = 1000;\ntolerance_x = 10e-6;\ntolerance_y = 10e-6;\noptions = {'tolerance_x' : tolerance_x, 'tolerance_y' : tolerance_y, 'N_iter_max' : N_iter_max};\nX0 = 0;\nstart = time.time();\nX, report = newton_algorithm(X0, func, func_1st_der, func_2nd_der, options);\nend = time.time();\nprint_report(report);\n# Plot path to X* for Y\nalgorithm_name = 'Newton\\'s algorithm';\nplot_progress_y(algorithm_name, report);\nprint('Elapsed time [s]: %0.5f' % (end - start));\nprint('***********************************************************************\\n')\n\n# Secant algorithm\nprint('***********************************************************************')\nprint('Secant algorithm')\nN_iter_max = 1000;\ntolerance_x = 10e-6;\ntolerance_y = 10e-6;\noptions = {'tolerance_x' : tolerance_x, 'tolerance_y' : tolerance_y, 'N_iter_max' : N_iter_max};\nX0 = 0;\nstart = time.time();\nX, report = secant_algorithm(X0, func, func_1st_der, options);\nend = time.time();\nprint_report(report);\n# Plot path to X* for Y\nalgorithm_name = 'Secant algorithm';\nplot_progress_y(algorithm_name, report);\nprint('Elapsed time [s]: %0.5f' % (end - start));\nprint('***********************************************************************\\n')\n", "meta": {"hexsha": "e50e8e09a73c364e1b181726aa7d5c11ad9adac4", "size": 4840, "ext": "py", "lang": "Python", "max_stars_repo_path": "1d_unconstrained_optimization/demo_1d_unconstrained_optimization.py", "max_stars_repo_name": "almostdutch/numerical-optimization-algorithms", "max_stars_repo_head_hexsha": "cd6c1306cb04eccce62a74420323bda83058c1d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1d_unconstrained_optimization/demo_1d_unconstrained_optimization.py", "max_issues_repo_name": "almostdutch/numerical-optimization-algorithms", "max_issues_repo_head_hexsha": "cd6c1306cb04eccce62a74420323bda83058c1d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-02T10:07:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-03T10:23:46.000Z", "max_forks_repo_path": "1d_unconstrained_optimization/demo_1d_unconstrained_optimization.py", "max_forks_repo_name": "almostdutch/numerical-optimization-algorithms", "max_forks_repo_head_hexsha": "cd6c1306cb04eccce62a74420323bda83058c1d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0322580645, "max_line_length": 121, "alphanum_fraction": 0.6074380165, "include": true, "reason": "import numpy", "num_tokens": 1266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854129326061, "lm_q2_score": 0.9196425300765949, "lm_q1q2_score": 0.8918559107807172}}
{"text": "# -*- coding: utf-8 -*-\n\nimport math\nimport numpy\n\nPI2 = math.pi * 2\n\n\ndef dft2d(nums):\n    \"\"\" 2D DFT\n    \n    args:\n        nums = [ [ 1, 2, 3 ], [ ... ], ... ]\n    \"\"\"\n    M = len(nums)\n    N = len(nums[0])\n    x = [ [ 0.0 + 0.0j for y in range(N) ] for x in range(M) ]\n\n    for m in range(M):\n        for n in range(N):\n            for k in range(M):\n                for l in range(N):\n                    re = nums[m][n] * math.cos(PI2 * (k * m / M + l * n / N))\n                    im = -nums[m][n] * math.sin(PI2 * (k * m / M + l * n / N))\n                    x[k][l] += complex(re, im)\n    return x\n\n\n\n\ndef idft2d(F):\n    \"\"\" 2D IDFT\n\n    args:\n        F: 复数，2D傅里叶变换的结果\n\n    args:\n        二维复数\n    \"\"\"\n    M = len(F)\n    N = len(F[0])\n    f = [ [ 0.0 + 0.0j for y in range(N) ] for x in range(M) ]\n    MN1 = 1 / (M * N)\n    for m in range(M):\n        for n in range(N):\n            for k in range(M):\n                for l in range(N):\n                    re = F[k][l].real * math.cos(PI2 * (k * m / M + l * n / N)) - F[k][l].imag * math.sin(PI2 * (k * m / M + l * n / N))\n                    im = F[k][l].real * math.sin(PI2 * (k * m / M + l * n / N)) + F[k][l].imag * math.cos(PI2 * (k * m / M + l * n / N))\n                    re *= MN1\n                    im *= MN1\n                    f[m][n] += complex(re, im)\n    return f\n\n\nif __name__ == '__main__':\n    M = 2\n    N = 2\n    nums = [ [ x + 1 for y in range(N) ] for x in range(M) ]\n\n    dft2d_result = dft2d(nums)\n\n    # numpy_result = numpy.fft.fft2(nums)\n\n    idft2d_result = idft2d(dft2d_result)\n\n    # numpy_ifft = numpy.fft.ifft2(dft2d_result)\n\n    # print(\"------nums--------\")\n    # print(nums)\n\n    print(\"------dft2d--------\")\n    print(dft2d_result)\n\n    # print(\"------numpy fft2--------\")\n    # print(numpy_result)\n\n    print(\"------idft2d--------\")\n    print(idft2d_result)\n\n    # print(\"------numpy ifft2--------\")\n    # print(numpy_ifft)\n\n    success = True\n    for m in range(M):\n        for n in range(N):\n            if math.fabs(nums[m][n].real - idft2d_result[m][n].real) > 1e-05:\n                print(\"[%d,%d]: %f != %f\" % (m, n, nums[m][n], idft2d_result[m][n]))\n                success = False\n    print(\"success: %s\\n\" % str(success))\n\n\n\n", "meta": {"hexsha": "f8b8f1b26c964fd2f73af5b0a90d1d9f42b12467", "size": 2229, "ext": "py", "lang": "Python", "max_stars_repo_path": "DFT/python/dft2d.py", "max_stars_repo_name": "QuantumLiu/algorithms-cuda", "max_stars_repo_head_hexsha": "0999b244c08dc9d92cbcdfb15215b10849df2840", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 55, "max_stars_repo_stars_event_min_datetime": "2016-12-29T08:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T10:41:59.000Z", "max_issues_repo_path": "DFT/python/dft2d.py", "max_issues_repo_name": "kevinyu1949/algorithms-cuda", "max_issues_repo_head_hexsha": "bdef6b744f2338348a08bd26a48969bb1d4fa316", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-02-25T01:46:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-23T05:16:06.000Z", "max_forks_repo_path": "DFT/python/dft2d.py", "max_forks_repo_name": "kevinyu1949/algorithms-cuda", "max_forks_repo_head_hexsha": "bdef6b744f2338348a08bd26a48969bb1d4fa316", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 40, "max_forks_repo_forks_event_min_datetime": "2017-01-10T06:53:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T13:47:41.000Z", "avg_line_length": 23.7127659574, "max_line_length": 136, "alphanum_fraction": 0.4235082997, "include": true, "reason": "import numpy", "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.978712648206549, "lm_q2_score": 0.9111797015700343, "lm_q1q2_score": 0.8917830987156613}}
{"text": "from typing import Dict, Optional, Any\nimport numpy as np\nimport scipy\nimport pandas as pd\nimport threading\n\n\ndef black_scholes(S, K, T, rf: float, iv, option_type) -> pd.DataFrame:\n    \"\"\"\n    Black Scholes modeling function.\n\n        * https://www.newyorkfed.org/medialibrary/media/research/staff_reports/sr677.pdf\n        * https://github.com/hashABCD/opstrat/blob/main/opstrat/blackscholes.py\n        * https://www.smileofthales.com/computation/options-greeks-python/\n        * https://github.com/vpatel576/option_probabilites\n        * https://github.com/skp1999/McMillan-s-Profit-Probability-Calculator/blob/main/POP_Calculation.py\n        * https://option-price.com/index.php\n\n    Option Value: Theoretical premium value.\n    Delta : Measures Impact of a Change in the Price of Underlying\n    Gamma: Measures the Rate of Change of Delta\n    Theta: Measures Impact of a Change in Time Remaining\n    Vega: Measures Impact of a Change in Volatility\n    Rho: Measures the impact of changes in Interest rates\n\n    :param S: Underlying Asset or Stock Price ($).\n    :param K: Strike or Excercise Price ($).\n    :param T: Expiry time of the option (days).\n    :param rf: Risk-free rate (decimal number range 0-1).\n    :param iv: Volatility (decimal).\n    :param option_type: Calls or Puts option type.\n    :return: Dataframe 'option_value', 'intrinsic_value', and 'time_value'.\n     Greeks has delta, gamma, theta, rho.\n    \"\"\"\n    # Check inputs.\n    is_type = np.isin(option_type, ['calls', 'puts', 'call', 'put', 'c', 'p'])\n    assert np.all(is_type) == 1, \"Enter Calls or Puts options only.\"\n\n    t = np.maximum(T / 365, 0.00001)  # Avoid infinite when T = 0.\n    iv = np.maximum(iv, 0.00001)  # Avoid infinite when iv = 0.\n\n    n1 = np.log(S / K)\n    n2 = (rf + iv ** 2 / 2) * t\n    d = iv * np.sqrt(t)\n\n    d1 = (n1 + n2) / d\n    d2 = d1 - d\n\n    f = np.where(np.isin(option_type, ['calls', 'call', 'c']), 1, -1)\n\n    N_d1 = scipy.stats.norm.cdf(f * d1)\n    N_d2 = scipy.stats.norm.cdf(f * d2)\n\n    A = S * N_d1\n    B = K * N_d2 * np.exp(-rf * t)\n\n    # Option pricing.\n    val = f * (A - B)\n    val_int = np.maximum(0.0, f * (S - K))\n    val_time = val - val_int\n\n    # Greeks.\n    delta = f * N_d1\n    gamma = np.exp((-d1 ** 2) / 2) / (S * iv * np.sqrt(2 * np.pi * t))\n    theta = (-S * iv * np.exp(-d1 ** 2 / 2) / np.sqrt(8 * np.pi * t)\n             - f * (N_d2 * rf * K * np.exp(-rf * t))) / 365\n    vega = ((S * np.sqrt(t) * np.exp((-d1 ** 2) / 2))\n            / (np.sqrt(2 * np.pi) * 100))\n    rho = f * t * K * N_d2 * np.exp(-rf * t) / 100\n\n    # Returns Dataframe.\n    return pd.DataFrame({\n        'option_value_bs': val,\n        'intrinsic_value': val_int,\n        'time_value': val_time,\n        'delta': delta,\n        'gamma': gamma,\n        'theta': theta,\n        'vega': vega,\n        'rho': rho\n    })\n\n\ndef monte_carlo(\n        key: str,\n        S: float,\n        K: float,\n        T: int,\n        rf: float,\n        iv: float,\n        option_type: str,\n        n: int = 200,\n        rng: Any = None) -> Dict[str, Optional[float]]:\n    \"\"\"\n    Monte Carlo modeling function.\n\n    Monte Carlo allows us to simulate seemingly random events, and assess\n    risks (among other results, of course). It has been used to assess the\n    risk of a given trading strategy.\n\n        * https://python.plainenglish.io/monte-carlo-options-pricing-in-two-lines-of-python-cf3a39407010\n        * https://www.youtube.com/watch?v=sS7GtIFFr_Y\n        * https://pythonforfinance.net/2016/11/28/monte-carlo-simulation-in-python/\n        * https://aaaquants.com/2017/09/01/monte-carlo-options-pricing-in-two-lines-of-python/#page-content\n\n    This function is not fully vectorized. It needs to be in a loop, with\n    each row passed for processing. All results are summarized by a Numpy func.\n\n    Usage:\n    ::\n            vector_profit_probability = np.vectorize(monte_carlo)\n            pop = vector_profit_probability(\n                S=curr_price,\n                K=opt['strike'].to_numpy(),\n                T=opt['dte'].to_numpy(),\n                rf=ten_yr,\n                iv=opt['volatility'].to_numpy(),\n                option_type=opt['option_type'].to_numpy(),\n                rng=rng,\n                n=1000\n            )\n\n    :param key: Key per result. Useful for future concatenation.\n    :param S: Underlying Asset or Stock Price ($).\n    :param K: Strike or Excercise Price ($).\n    :param T: Expiry time of the option (days).\n    :param rf: Risk-free rate (decimal number range 0-1).\n    :param iv: Volatility (decimal).\n    :param option_type: Calls or Puts option type.\n    :param n: Number of Monte Carlo iterantions. min 100,000 recommended.\n    :param rng: Random range generator, used when in loops.\n    :return: Dictionary with keys: value, greeks.\n     Value has 'option_value', 'intrinsic_value', and 'time_value'.\n     Greeks jas delta, gamma, theta, rho.\n    \"\"\"\n    # Check inputs.\n    assert option_type in ['calls', 'puts', 'call', 'put', 'c', 'p'], \\\n        \"Enter Calls or Puts options only.\"\n\n    # np.random.seed(25)  # Use for consistent testing.\n\n    T = T if T != 0 else 1\n    D = np.exp(-rf * (T / 252))\n\n    # Randomized array of number of days x simulations, based of current price.\n    # P = np.cumprod(1 + np.random.randn(n, T) * iv / np.sqrt(252), axis=1) * S\n    # Generating random range is expensive, so doing it once.\n    rng = np.random.Generator(np.random.PCG64()) if rng is None else rng\n    rnd = rng.standard_normal((n, T), dtype=np.float32)\n    P = np.cumprod(1 + rnd * iv / np.sqrt(252), axis=1) * S\n\n    # Series on last day of simulation with premium difference.\n    p_last = P[:, -1] - K * D\n\n    # If calls, take only positive results. If puts, take negatives.\n    if option_type in ['calls', 'call', 'c']:\n        arr = np.where(p_last > 0, p_last, 0)\n    else:\n        arr = -np.where(p_last < 0, p_last, 0)\n\n    # Take the average values of all the iterations on the last day.\n    val = np.mean(arr)\n\n    # Probability of Profit.\n    pop_ITM = round(np.count_nonzero(arr) / p_last.size, 2)\n\n    # Probability of Making 50% Profit.\n    profit_req = 0.50\n    if option_type in ['calls', 'call', 'c']:\n        arr = np.where(p_last > profit_req * val, p_last, 0)\n    else:\n        arr = -np.where(p_last < profit_req * val, p_last, 0)\n    p50 = round(np.count_nonzero(arr) / p_last.size, 2)\n\n    # Returns Dictionary.\n    # Calculating quantiles is expensive, so only uncomment if necessary.\n    return {\n        'symbol': key,\n        'option_value_mc': val,  # Average value. Near Black Scholes Value.\n        # 'value_quantile_5': np.percentile(p_last, 5),  # 5% chance below X\n        # 'value_quantile_50': np.percentile(p_last, 50),  # 50% chance lands here.\n        # 'value_quantile_95': np.percentile(p_last, 95),  # 5% chance above X.\n        'probability_ITM': pop_ITM,  # Probability of ending ITM.\n        'probability_of_50': p50,  # Probability of makeing half profit.\n    }\n\n\ndef mc_numpy_vector(*args):\n    \"\"\"\n    Monte Carlo simulations vectorized so that arrays work in calculations\n\n    DEPRECATED: It's faster to multithread this operation.\n    \"\"\"\n    curr_price, opt, ten_yr, rng, montecarlo_iterations = args\n    vector_monte_carlo = np.vectorize(monte_carlo)\n    _pop = vector_monte_carlo(\n        key=opt['contractSymbol'],\n        S=curr_price,\n        K=opt['strikePrice'].to_numpy(),\n        T=opt['daysToExpiration'].to_numpy(),\n        rf=ten_yr,\n        iv=opt['volatility'].to_numpy(),\n        option_type=opt['option_type'].to_numpy(),\n        rng=rng,\n        n=montecarlo_iterations\n    )\n    return pd.DataFrame.from_records(_pop)  # pd.json_normalize(_pop.T)\n\n\ndef mc_multi_threading(*args):\n    \"\"\"\n    Monte Carlo simulations vectorized so that arrays work in calculations.\n    Multithreaded, means one CPU works multiple I/O.\n\n    :param args: Passing all parameters from call.\n    :return: Dataframe with results. Including a key to join later.\n    \"\"\"\n    def threader(opt, ten_yr, rng, montecarlo_iterations):\n        _pop = vector_monte_carlo(\n            key=opt.index.get_level_values('symbol').to_numpy(),\n            S=opt['lastPrice'].to_numpy(),\n            K=opt['strikePrice'].to_numpy(),\n            T=opt['daysToExpiration'].to_numpy(),\n            rf=ten_yr,\n            iv=opt['volatility'].to_numpy(),\n            option_type=opt.index.get_level_values('option_type').to_numpy(),\n            rng=rng,\n            n=montecarlo_iterations\n        )\n        rez.append(_pop)\n\n    rez = []  # List of dictionaries\n    _opt, _ten_yr, _rng, _montecarlo_iterations, _chunks = args\n    vector_monte_carlo = np.vectorize(monte_carlo)\n\n    # Chunking tables in groups of 'chunks' values. Each a separate thread.\n    dtes = _opt['daysToExpiration'].unique()  # List of DTE's\n    d_chunk = [dtes[i:i + _chunks] for i in range(0, len(dtes), _chunks)]\n    df_chunks = [_opt[(_opt['daysToExpiration'].isin(dte))] for dte in d_chunk]\n\n    # Multi-threading.\n    threads = []\n    for df in df_chunks:\n        arg = (df, _ten_yr, _rng, _montecarlo_iterations)\n        t = threading.Thread(target=threader, args=arg)\n        threads.append(t)\n\n    [thread.start() for thread in threads]  # Kickoff threading.\n    [thread.join() for thread in threads]  # Stop all threads.\n\n    # Flatten list\n    _result = []\n    for i in range(len(rez)):\n        for j in rez[i]:\n            _result.append(j)\n\n    return pd.DataFrame.from_records(_result)\n\n\nclass Modeling:\n    def __init__(self, con, option_df):\n        self.options = option_df.options  # Options coming in.\n        self.quote = None  # All quote data.\n        self.rf = 0  # Risk-free rate, i.e. 10-yr t-bill for modeling.\n        self.prepare_tables(con)\n\n    def get_quotes(self, con):\n        \"\"\"\n        Get current price data from TDA\n\n        Source: https://developer.tdameritrade.com/quotes/apis/get/marketdata/quotes\n\n        :return: Current underlying stock price merged into the options table.\n        \"\"\"\n        import httpx\n        tickers = self.options.index.get_level_values('stock').unique().to_list()\n        q = con.client.get_quotes(tickers)\n        assert q.status_code == httpx.codes.OK, q.raise_for_status()\n\n        prep = [v for k, v in q.json().items()]\n        self.quote = pd.DataFrame.from_dict(prep)\n        self.quote.rename(columns={'symbol': 'stock'}, inplace=True)\n\n    def get_last_price(self, con):\n        self.get_quotes(con)\n        last_price = self.quote[[\n            \"stock\",\n            # \"description\",\n            # \"bidPrice\",\n            # \"bidSize\",\n            # \"bidId\",\n            # \"askPrice\",\n            # \"askSize\",\n            # \"askId\",\n            \"lastPrice\",\n            # \"lastSize\",\n            # \"lastId\",\n            # \"openPrice\",\n            # \"highPrice\",\n            # \"lowPrice\",\n            # \"closePrice\",\n            # \"netChange\",\n            # \"totalVolume\",\n            # \"quoteTimeInLong\",\n            # \"tradeTimeInLong\",\n            # \"mark\",\n            # \"exchange\",\n            # \"exchangeName\",\n            # \"marginable\",\n            # \"shortable\",\n            # \"volatility\",\n            # \"digits\",\n            # \"52WkHigh\",\n            # \"52WkLow\",\n            # \"peRatio\",\n            # \"divAmount\",\n            # \"divYield\",\n            # \"divDate\",\n            # \"securityStatus\",\n            # \"regularMarketLastPrice\",\n            # \"regularMarketLastSize\",\n            # \"regularMarketNetChange\",\n            # \"regularMarketTradeTimeInLong\",\n        ]]\n        last_price.set_index('stock', inplace=True)\n\n        # pd.merge(self.options, last_price, on='stock')\n        self.options = self.options.join(last_price, on='stock')\n\n    def get_risk_free_rate(self):\n        # Get 10-yr risk-free rate from FRED.\n        _url = \"https://fred.stlouisfed.org/graph/fredgraph.csv?id=DGS10\"\n        _csv = pd.read_csv(_url)\n        _value = _csv['DGS10'].values[-1]\n        self.rf = float(_value) / 100\n\n    def prepare_tables(self, con):\n        self.get_last_price(con)\n        self.get_risk_free_rate()\n\n    def black_scholes(self):\n        df = self.options.copy()\n        if all(i in df.columns for i in ['putCall', 'symbol']):\n            df = df.drop(columns=['putCall', 'symbol']).reset_index()\n        # Black Scholes data here. Option value, greeks.\n        bsch = black_scholes(\n            S=df['lastPrice'].to_numpy(),\n            K=df['strikePrice'].to_numpy(),\n            T=df['daysToExpiration'].to_numpy(),\n            rf=self.rf,\n            iv=df['volatility'].to_numpy(),\n            option_type=df['option_type'].to_numpy()\n        )\n        df = pd.concat([df, bsch], axis='columns')\n        df.set_index(\n            ['stock', 'option_type', 'symbol'],\n            inplace=True\n        )\n        self.options = df\n        return self.options\n\n    def probability_of_profits(self, montecarlo_iterations):\n        # Probability of profits.\n        msg = f\" {self.options.shape[0]} contracts\" \\\n              f\" x {montecarlo_iterations} iterations\"\n\n        # Generating random range is expensive, so doing it once.\n        rng = np.random.Generator(np.random.PCG64())\n\n        df = self.options.copy()\n\n        # 1) Simple version.\n        # Disabled because it's significantly slower than multithreading.\n        # print(\"Numpy Vector\" + msg)\n        # pop = mc_numpy_vector(\n        #     curr_price, opt, ten_yr, rng, montecarlo_iterations\n        # )\n\n        # 2) Multiple Threads.\n        print(f\"Multi Threading\" + msg)\n        # Chunks set to 2, is optimal after experimenting.\n        chunks = 2  # How many DTE's to process per Thread.\n        pop = mc_multi_threading(\n            df,\n            self.rf,\n            rng,\n            montecarlo_iterations,\n            chunks\n        )\n        pop.set_index(['symbol'], inplace=True)\n\n        if all(i in df.columns for i in ['putCall', 'symbol']):\n            df = df.drop(columns=['putCall', 'symbol'])\n\n        df.reset_index(inplace=True)\n        df = df.join(pop, on='symbol')\n        df.sort_values(by='symbol', inplace=True)\n        df.set_index(['stock', 'option_type', 'symbol'], inplace=True)\n\n        self.options = df\n        return self.options\n", "meta": {"hexsha": "9550307a611265e3624bd3dd81dd8372373ed048", "size": 14191, "ext": "py", "lang": "Python", "max_stars_repo_path": "fybot/core/option_sniper/modeling.py", "max_stars_repo_name": "juanlazarde/financial_scanner", "max_stars_repo_head_hexsha": "a466aa553a413b65d08d4d23250867f938726e17", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-06T20:22:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-23T04:51:05.000Z", "max_issues_repo_path": "fybot/core/option_sniper/modeling.py", "max_issues_repo_name": "juanlazarde/fybot", "max_issues_repo_head_hexsha": "a466aa553a413b65d08d4d23250867f938726e17", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-11-20T05:32:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T06:34:41.000Z", "max_forks_repo_path": "fybot/core/option_sniper/modeling.py", "max_forks_repo_name": "juanlazarde/financial_scanner", "max_forks_repo_head_hexsha": "a466aa553a413b65d08d4d23250867f938726e17", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-29T23:01:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T23:01:09.000Z", "avg_line_length": 35.3009950249, "max_line_length": 107, "alphanum_fraction": 0.5900218448, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9759464520028356, "lm_q2_score": 0.913676514011486, "lm_q1q2_score": 0.8916993521278288}}
{"text": "import numpy as np\n\ndef sigmoid(x):\n    return 1/(1+np.exp(-x))\n\ndef sigmoid_derivative(x):\n    \"\"\"\n    Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x.\n    You can store the output of the sigmoid function into variables and then use it to calculate the gradient.\n    \n    Arguments:\n    x -- A scalar or numpy array\n\n    Return:\n    ds -- Your computed gradient.\n    \"\"\"\n\n    s = sigmoid(x)\n    ds = s * (1-s)\n\n    return ds\n\ndef softmax(x):\n    \"\"\"Calculates the softmax for each row of the input x.\n\n    Your code should work for a row vector and also for matrices of shape (m,n).\n\n    Argument:\n    x -- A numpy matrix of shape (m,n)\n\n    Returns:\n    s -- A numpy matrix equal to the softmax of x, of shape (m,n)\n    \"\"\"\n    \n    # Apply exp() element-wise to x. Use np.exp(...).\n    x_exp = np.exp(x)\n\n    # Create a vector x_sum that sums each row of x_exp. Use np.sum(..., axis = 1, keepdims = True).\n    x_sum = np.sum(x_exp, axis =1, keepdims= True)\n    \n    # Compute softmax(x) by dividing x_exp by x_sum. It should automatically use numpy broadcasting.\n    s = x_exp/x_sum\n    return s\n\ndef normalizeRows(x):\n    \"\"\"\n    Implement a function that normalizes each row of the matrix x (to have unit length).\n    \n    Argument:\n    x -- A numpy matrix of shape (n, m)\n    \n    Returns:\n    x -- The normalized (by row) numpy matrix. You are allowed to modify x.\n    \"\"\"\n\n    x_norm = np.linalg.norm(x,axis=1,keepdims=True)\n    x = x/x_norm\n    return x\n\ndef L1(yhat, y):\n    \"\"\"\n    Arguments:\n    yhat -- vector of size m (predicted labels)\n    y -- vector of size m (true labels)\n    \n    Returns:\n    loss -- the value of the L1 loss function defined above\n    \"\"\"\n    loss = np.sum(abs(y-yhat))    \n    return loss\n\ndef L2(yhat, y):\n    \"\"\"\n    Arguments:\n    yhat -- vector of size m (predicted labels)\n    y -- vector of size m (true labels)\n    \n    Returns:\n    loss -- the value of the L2 loss function defined above\n    \"\"\"\n    loss = np.sum((y-yhat)**2)\n    return loss\n\n", "meta": {"hexsha": "10a182c07628d3af85c35eefc468cebd465b9e85", "size": 2055, "ext": "py", "lang": "Python", "max_stars_repo_path": "dl/numpy/basics.py", "max_stars_repo_name": "xta0/Python-Playground", "max_stars_repo_head_hexsha": "513ebd2ad7f0a8c69f2f04b4f7524b31e76fa5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dl/numpy/basics.py", "max_issues_repo_name": "xta0/Python-Playground", "max_issues_repo_head_hexsha": "513ebd2ad7f0a8c69f2f04b4f7524b31e76fa5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dl/numpy/basics.py", "max_forks_repo_name": "xta0/Python-Playground", "max_forks_repo_head_hexsha": "513ebd2ad7f0a8c69f2f04b4f7524b31e76fa5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4642857143, "max_line_length": 115, "alphanum_fraction": 0.6165450122, "include": true, "reason": "import numpy", "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551525886193, "lm_q2_score": 0.9241418121440552, "lm_q1q2_score": 0.8916629891697756}}
{"text": "\"\"\"\nidentity\n\nThe identity tool returns an identity array. An identity array is a square matrix with all the main diagonal elements as  and the rest as . The default type of elements is float.\n\nimport numpy\nprint numpy.identity(3) #3 is for  dimension 3 X 3\n\n#Output\n[[ 1.  0.  0.]\n [ 0.  1.  0.]\n [ 0.  0.  1.]]\neye\n\nThe eye tool returns a 2-D array with 's as the diagonal and 's elsewhere. The diagonal can be main, upper or lower depending on the optional parameter . A positive  is for the upper diagonal, a negative  is for the lower, and a   (default) is for the main diagonal.\n\nimport numpy\nprint numpy.eye(8, 7, k = 1)    # 8 X 7 Dimensional array with first upper diagonal 1.\n\n#Output\n[[ 0.  1.  0.  0.  0.  0.  0.]\n [ 0.  0.  1.  0.  0.  0.  0.]\n [ 0.  0.  0.  1.  0.  0.  0.]\n [ 0.  0.  0.  0.  1.  0.  0.]\n [ 0.  0.  0.  0.  0.  1.  0.]\n [ 0.  0.  0.  0.  0.  0.  1.]\n [ 0.  0.  0.  0.  0.  0.  0.]\n [ 0.  0.  0.  0.  0.  0.  0.]]\n\nprint numpy.eye(8, 7, k = -2)   # 8 X 7 Dimensional array with second lower diagonal 1.\nTask\n\nYour task is to print an array of size X with its main diagonal elements as 's and 's everywhere else.\n\nNote\n\nIn order to get alignment correct, please insert the line  below the numpy import.\n\nInput Format\n\nA single line containing the space separated values of  and .\n denotes the rows.\n denotes the columns.\n\nOutput Format\n\nPrint the desired X array.\n\nSample Input\n\n3 3\nSample Output\n\n[[ 1.  0.  0.]\n [ 0.  1.  0.]\n [ 0.  0.  1.]]\n\"\"\"\n\nimport numpy as np\n\nnp.set_printoptions(legacy=\"1.13\")\n\nN, M = list(map(int, input().split()))\nprint(np.eye(N, M, 0))\n", "meta": {"hexsha": "71124d506ac309b1da616b0190815a2a6d064c5e", "size": 1596, "ext": "py", "lang": "Python", "max_stars_repo_path": "Hackerrank_codes/Numpy/numpy_eye_identity.py", "max_stars_repo_name": "Vyshnavmt94/HackerRankTasks", "max_stars_repo_head_hexsha": "634c71ccf0bea7585498bcd7d63e34d0334b4678", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Hackerrank_codes/Numpy/numpy_eye_identity.py", "max_issues_repo_name": "Vyshnavmt94/HackerRankTasks", "max_issues_repo_head_hexsha": "634c71ccf0bea7585498bcd7d63e34d0334b4678", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hackerrank_codes/Numpy/numpy_eye_identity.py", "max_forks_repo_name": "Vyshnavmt94/HackerRankTasks", "max_forks_repo_head_hexsha": "634c71ccf0bea7585498bcd7d63e34d0334b4678", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5538461538, "max_line_length": 266, "alphanum_fraction": 0.6253132832, "include": true, "reason": "import numpy", "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297142, "lm_q2_score": 0.9381240160063031, "lm_q1q2_score": 0.8916033665677107}}
{"text": "import math\nimport numpy as np\n\n\ndef safe_slope(x1: float, y1: float, x2: float, y2: float) -> float:\n    \"\"\"Calulates the slope between two points in a way tha avoids division by zeros.\"\"\"\n    x_diff = (x2 - x1)\n    \n    if x_diff == 0:\n        # Avoid division by zero by return inf.\n        return np.inf\n\n    return (y2 - y1) / x_diff \n\n\ndef z_axis_angle(x1: float, y1: float, x2: float, y2: float) -> float:\n    \"\"\"Calulates that angle in degrees [0, 360] that the slope of the provided points\n    form with rotation about the z axis.\"\"\"\n\n    angle = math.degrees(math.atan2(y2 - y1, x2 - x1))  \n\n    # Wrap angle to bound it between 0 and 360.\n    if angle < 0:\n        angle += 360\n\n    if angle > 360:\n        angle -= 360\n\n    return angle\n\n\ndef euclidean_distance(x1: float, y1: float, x2: float, y2: float) -> float:\n    \"\"\"Calculates the euclidean distance between two points.\"\"\"\n    return math.sqrt(((x1 - x2)**2) + ((y1 - y2)**2))\n\n\ndef wrap_heading(current_heading: float, new_heading: float) -> float:\n    \"\"\"Determines the offset between the current and provided heading to adjust\n    them such that the normal subtraction between them results in an angle less than\n    or equal to 180 degrees.\"\"\"\n    if abs(new_heading - current_heading) > 180:\n      if new_heading > current_heading:\n        new_heading -= 360\n\n      else:\n        new_heading += 360\n\n    return new_heading\n\n\ndef angular_distance(a1: float, a2: float) -> float:\n    \"\"\"Calculates the angular distance between two angles in degrees.\"\"\"\n    phi = abs(a2 - a1) % 360;      \n    distance = 360 - phi if phi > 180 else phi;\n    return distance;\n", "meta": {"hexsha": "6bad6e8308baa0aaec96a0fb32832db466c47fa8", "size": 1629, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils.py", "max_stars_repo_name": "alecmeade/grid_planner", "max_stars_repo_head_hexsha": "7a4c32c3f1a1d8bf798d07766f2d877831de475e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils.py", "max_issues_repo_name": "alecmeade/grid_planner", "max_issues_repo_head_hexsha": "7a4c32c3f1a1d8bf798d07766f2d877831de475e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils.py", "max_forks_repo_name": "alecmeade/grid_planner", "max_forks_repo_head_hexsha": "7a4c32c3f1a1d8bf798d07766f2d877831de475e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0892857143, "max_line_length": 87, "alphanum_fraction": 0.6414978514, "include": true, "reason": "import numpy", "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.973240714486111, "lm_q2_score": 0.9161096193153989, "lm_q1q2_score": 0.891595180450118}}
{"text": "# Ejercicio 1\n\nimport numpy as np\nimport matplotlib.pylab as plt\n\n\n# Use esta funcion que recibe un valor x y retorna un valor f(x) donde f es la forma funcional que debe seguir su distribucion. \ndef mifun(x):\n    x_0 = 3.0\n    a = 0.01\n    return np.exp(-(x**2))/((x-x_0)**2 + a**2)\n\n# Dentro de una funcion que reciba como parametros el numero de pasos y el sigma de la distribucion gausiana que va a usar para calcular el paso de su caminata, implemente el algortimo de Metropolis-Hastings. Finalmente, haga un histograma de los datos obtenidos y grafique en la misma grafica, la funcion de distribucion de probabilidad fx (Ojo, aca debe normalizar). Guarde la grafica sin mostrarla en un pdf. Use plt.savefig(\"histograma_\"+str(sigma)+\"_\"+str(pasos)+\".pdf\"), donde sigma y pasos son los parametros que recibe la funcion. \n\n\ndef metropolis(x,f,N,sigma):\n    datos=np.zeros(N)\n    datos[0]=np.random.random()*max(x)\n    for i in range(1,N):\n        xold=datos[i-1]\n        xnew=np.random.normal(xold,sigma)\n        alpha=f(xnew)/f(xold)\n        if(alpha>1):\n            datos[i]=xnew\n        else:\n            beta=np.random.random()\n            if(beta<alpha):\n                datos[i]=xnew\n            else:\n                datos[i]=xold\n    return datos\n\n# Cuando haya verificado que su codigo funciona, use los siguientes parametros:\n# sigma = 5, pasos =100000 \n# sigma = 0.2, pasos =100000 \n# sigma = 0.01, pasos =100000 \n# sigma = 0.1, pasos =1000 \n# sigma = 0.1, pasos =100000 \n# este puede ser muy demorado dependiendo del computador: sigma = 0.1, pasos =500000\nsigma=[5,0.2,0.01,0.1,0.1,0.1]\npasos=[100000,100000,100000,1000,100000,500000]\n\n\n# Al ejecutar el codigo, este debe generar 6 (o 5) graficas .pdf una para cada vez que se llama a la funcion.\n\nx=np.linspace(-4,4,1000)\ny=mifun(x)/np.sum(mifun(x)*(x[1]-x[0]))\n\nfor i in range(len(pasos)):\n    s=sigma[i]\n    N=pasos[i]\n    MH=metropolis(x,mifun,N,s)\n    \n    plt.figure()\n    plt.hist(MH,bins=100,density=True,label=\"MH\")\n    plt.plot(x,y,label=\"Función\")\n    plt.xlabel(\"x\")\n    plt.ylabel(\"y\")\n    plt.legend()\n    plt.title('Metropolis con $\\sigma$ ='+str(s)+' y '+str(N)+ ' pasos.')\n    plt.savefig(\"histograma_\"+str(s)+\"_\"+str(N)+\".png\")\n    plt.close()\n\n\n", "meta": {"hexsha": "ed59e20d9d72416529c78e490c4a75916457a13b", "size": 2229, "ext": "py", "lang": "Python", "max_stars_repo_path": "S7C2/CendalesLuis_S7C2.py", "max_stars_repo_name": "LuisCendales/M-todos_Computacionales", "max_stars_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "S7C2/CendalesLuis_S7C2.py", "max_issues_repo_name": "LuisCendales/M-todos_Computacionales", "max_issues_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "S7C2/CendalesLuis_S7C2.py", "max_forks_repo_name": "LuisCendales/M-todos_Computacionales", "max_forks_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2923076923, "max_line_length": 539, "alphanum_fraction": 0.6482727681, "include": true, "reason": "import numpy", "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154280587323, "lm_q2_score": 0.9294404082102515, "lm_q1q2_score": 0.8914767460856916}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed(100)\nX = np.arange(1, 51, 1).reshape(50, 1)\nu = np.random.uniform(-1, 1, (50, 1))\nY = u + X\n\nX_temp = np.vstack((np.ones((1, 50)), X.T))\nX_psuedo_inverse = np.matmul(X_temp.T, np.linalg.inv(np.matmul(X_temp, X_temp.T)))\n\nW = np.matmul(Y.reshape(1, 50), X_psuedo_inverse)\n\nf_X = W[0][1]*X[:, 0] + W[0][0]\nplt.plot(X[:, 0], Y[:, 0], 'o')\nplt.plot(X[:, 0], f_X, 'r', label = 'Line to fit data')\nplt.xlabel(\"X-axis\")\nplt.ylabel(\"Y-axis\")\nplt.title(\"Linear Least Squares Fit\")\nplt.legend()\nplt.show()\n\n\nw = np.array([0.15, 0.6])\neta = 0.00001\n\nf_X = w[1]*X[:, 0] + w[0]\nplt.plot(X[:, 0], Y[:, 0], 'o')\nplt.plot(X[:, 0], f_X, 'r', label = 'Line to fit data')\nplt.xlabel(\"X-axis\")\nplt.ylabel(\"Y-axis\")\nplt.title(\"Gradient Descent Fit before training\")\nplt.legend()\nplt.show()\nprint(w, eta)\n\nz = 0\nwhile True:\n    z+=1\n    grad = np.zeros((2,))\n    for i in range(50):\n        grad[0] += (Y[i, 0] - w[0] - w[1]*X[i, 0])\n    grad[0] *= -2\n    \n    for i in range(50):\n        grad[1] += (Y[i, 0] - w[0] - w[1]*X[i, 0])*X[i, 0]\n    grad[1] *= -2\n    \n    delta_w = eta * grad\n    new_w = w - delta_w\n    \n    if np.linalg.norm(w - new_w) < 0.0001:\n        break\n    else:\n        w = new_w\n        wtemp = new_w\n    if z == 1:\n        f_X = w[1]*X[:, 0] + w[0]\n        plt.plot(X[:, 0], Y[:, 0], 'o')\n        plt.plot(X[:, 0], f_X, 'r', label = 'Line to fit data')\n        plt.xlabel(\"X-axis\")\n        plt.ylabel(\"Y-axis\")\n        plt.title(\"Gradient Descent Fit after 1 epoch\")\n        plt.legend()\n        plt.show()\n        \nf_X = w[1]*X[:, 0] + w[0]\nplt.plot(X[:, 0], Y[:, 0], 'o')\nplt.plot(X[:, 0], f_X, 'r', label = 'Line to fit data')\nplt.xlabel(\"X-axis\")\nplt.ylabel(\"Y-axis\")\nplt.title(f\"Gradient Descent Fit after {z} epochs\")\nplt.legend()\nplt.show()\n        \nprint(\"DIFF\", W - w.reshape(1, 2))\n     \n\n\n\n", "meta": {"hexsha": "b622bfc0aba30b90f7f0cc3a5558d28bd65b4850", "size": 1870, "ext": "py", "lang": "Python", "max_stars_repo_path": "linearfit.py", "max_stars_repo_name": "yashchitre03/Linear-Least-Squares-Fit", "max_stars_repo_head_hexsha": "62d1aa57f3df01ff16251a7577dfa3b31818ee4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linearfit.py", "max_issues_repo_name": "yashchitre03/Linear-Least-Squares-Fit", "max_issues_repo_head_hexsha": "62d1aa57f3df01ff16251a7577dfa3b31818ee4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linearfit.py", "max_forks_repo_name": "yashchitre03/Linear-Least-Squares-Fit", "max_forks_repo_head_hexsha": "62d1aa57f3df01ff16251a7577dfa3b31818ee4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0864197531, "max_line_length": 82, "alphanum_fraction": 0.5278074866, "include": true, "reason": "import numpy", "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241974031599, "lm_q2_score": 0.9196425262224018, "lm_q1q2_score": 0.891431753628344}}
{"text": "from math import fabs as fabs\nfrom math import floor as floor\nfrom math import sqrt as sqrt\nfrom scipy.special import erfc as erfc\nfrom scipy.special import gammaincc as gammaincc\n\nclass FrequencyTest:\n\n    @staticmethod\n    def monobit_test(binary_data:str, verbose=False):\n        \"\"\"\n        The focus of the test is the proportion of zeroes and ones for the entire sequence.\n        The purpose of this test is to determine whether the number of ones and zeros in a sequence are approximately\n        the same as would be expected for a truly random sequence. The test assesses the closeness of the fraction of\n        ones to 陆, that is, the number of ones and zeroes in a sequence should be about the same.\n        All subsequent tests depend on the passing of this test.\n\n        if p_value < 0.01, then conclude that the sequence is non-random (return False).\n        Otherwise, conclude that the the sequence is random (return True).\n\n        :param      binary_data         The seuqnce of bit being tested\n        :param      verbose             True to display the debug messgae, False to turn off debug message\n        :return:    (p_value, bool)     A tuple which contain the p_value and result of frequency_test(True or False)\n\n        \"\"\"\n\n        length_of_bit_string = len(binary_data)\n\n        # Variable for S(n)\n        count = 0\n        # Iterate each bit in the string and compute for S(n)\n        for bit in binary_data:\n            if bit == '0':\n                # If bit is 0, then -1 from the S(n)\n                count -= 1\n            elif bit == '1':\n                # If bit is 1, then +1 to the S(n)\n                count += 1\n\n        # Compute the test statistic\n        sObs = count / sqrt(length_of_bit_string)\n\n        # Compute p-Value\n        p_value = erfc(fabs(sObs) / sqrt(2))\n\n        if verbose:\n            print('Frequency Test (Monobit Test) DEBUG BEGIN:')\n            print(\"\\tLength of input:\\t\", length_of_bit_string)\n            print('\\t# of \\'0\\':\\t\\t\\t', binary_data.count('0'))\n            print('\\t# of \\'1\\':\\t\\t\\t', binary_data.count('1'))\n            print('\\tS(n):\\t\\t\\t\\t', count)\n            print('\\tsObs:\\t\\t\\t\\t', sObs)\n            print('\\tf:\\t\\t\\t\\t\\t',fabs(sObs) / sqrt(2))\n            print('\\tP-Value:\\t\\t\\t', p_value)\n            print('DEBUG END.')\n\n        # return a p_value and randomness result\n        return (p_value, (p_value >= 0.01))\n\n    @staticmethod\n    def block_frequency(binary_data:str, block_size=128, verbose=False):\n        \"\"\"\n        The focus of the test is the proportion of ones within M-bit blocks.\n        The purpose of this test is to determine whether the frequency of ones in an M-bit block is approximately M/2,\n        as would be expected under an assumption of randomness.\n        For block size M=1, this test degenerates to test 1, the Frequency (Monobit) test.\n\n        :param      binary_data:        The length of each block\n        :param      block_size:         The seuqnce of bit being tested\n        :param      verbose             True to display the debug messgae, False to turn off debug message\n        :return:    (p_value, bool)     A tuple which contain the p_value and result of frequency_test(True or False)\n        \"\"\"\n\n        length_of_bit_string = len(binary_data)\n\n\n        if length_of_bit_string < block_size:\n            block_size = length_of_bit_string\n\n        # Compute the number of blocks based on the input given.  Discard the remainder\n        number_of_blocks = floor(length_of_bit_string / block_size)\n\n        if number_of_blocks == 1:\n            # For block size M=1, this test degenerates to test 1, the Frequency (Monobit) test.\n            return FrequencyTest.monobit_test(binary_data[0:block_size])\n\n        # Initialized variables\n        block_start = 0\n        block_end = block_size\n        proportion_sum = 0.0\n\n        # Create a for loop to process each block\n        for counter in range(number_of_blocks):\n            # Partition the input sequence and get the data for block\n            block_data = binary_data[block_start:block_end]\n\n            # Determine the proportion 蟺i of ones in each M-bit\n            one_count = 0\n            for bit in block_data:\n                if bit == '1':\n                    one_count += 1\n            # compute π\n            pi = one_count / block_size\n\n            # Compute Σ(πi -½)^2.\n            proportion_sum += pow(pi - 0.5, 2.0)\n\n            # Next Block\n            block_start += block_size\n            block_end += block_size\n\n        # Compute 4M Σ(πi -½)^2.\n        result = 4.0 * block_size * proportion_sum\n\n        # Compute P-Value\n        p_value = gammaincc(number_of_blocks / 2, result / 2)\n\n        if verbose:\n            print('Frequency Test (Block Frequency Test) DEBUG BEGIN:')\n            print(\"\\tLength of input:\\t\", length_of_bit_string)\n            print(\"\\tSize of Block:\\t\\t\", block_size)\n            print('\\tNumber of Blocks:\\t', number_of_blocks)\n            print('\\tCHI Squared:\\t\\t', result)\n            print('\\t1st:\\t\\t\\t\\t', number_of_blocks / 2)\n            print('\\t2nd:\\t\\t\\t\\t', result / 2)\n            print('\\tP-Value:\\t\\t\\t', p_value)\n            print('DEBUG END.')\n\n        return (p_value, (p_value >= 0.01))", "meta": {"hexsha": "c7cbcb99e05b0172a53e491c20ba5a4d7a568115", "size": 5258, "ext": "py", "lang": "Python", "max_stars_repo_path": "nist_randomness_testsuite/FrequencyTest.py", "max_stars_repo_name": "Goluck-Konuko/cellular_automata_prng", "max_stars_repo_head_hexsha": "da8bb374ff4c9f0b508c767e2787754f6de1e56a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2018-05-06T11:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:26:51.000Z", "max_issues_repo_path": "nist_randomness_testsuite/FrequencyTest.py", "max_issues_repo_name": "Goluck-Konuko/cellular_automata_prng", "max_issues_repo_head_hexsha": "da8bb374ff4c9f0b508c767e2787754f6de1e56a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-04-29T13:21:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T07:41:33.000Z", "max_forks_repo_path": "nist_randomness_testsuite/FrequencyTest.py", "max_forks_repo_name": "Goluck-Konuko/cellular_automata_prng", "max_forks_repo_head_hexsha": "da8bb374ff4c9f0b508c767e2787754f6de1e56a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2018-09-07T10:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T15:41:23.000Z", "avg_line_length": 40.7596899225, "max_line_length": 118, "alphanum_fraction": 0.598896919, "include": true, "reason": "from scipy", "num_tokens": 1260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9796676472509722, "lm_q2_score": 0.9099070090919014, "lm_q1q2_score": 0.891406458814232}}
{"text": "from matplotlib import markers\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Langrange Polynomial of n^th Degree - The Degree is Specified by the Data we Use\ndef P(x_data, f_data, pos, x):  # pos is an array with elements the positions of x_data we use\n\n    # n = Degree of the polynomial + 1\n    n = len(pos)\n\n    def L(x_data, pos, x):\n\n        L = np.ones(n)\n\n        # Polynomial that goes through x_data[pos[i]]\n        for i in range(n):\n            for j in range(n):\n                if pos[i] != pos[j]:\n                    L[i] *= (x - x_data[pos[j]]) / (x_data[pos[i]] - x_data[pos[j]])\n        return L\n\n    P = 0.0\n\n    for i in range(n):\n            P += f_data[pos[i]] * L(x_data, pos, x)[i]\n\n    return P\n\n# Function to Generate Points for Graphs\ndef graph(pos, n = 150):\n    x_graph = np.linspace(x_data[np.amin(pos)], x_data[np.amax(pos)], n)\n    y_graph = np.zeros(len(x_graph))\n\n    i = 0\n\n    for x in x_graph:\n        y_graph[i] += [P(x_data, f_data, pos, x)]\n        i += 1\n\n    return x_graph, y_graph\n\nif __name__ == \"__main__\":\n    # Some Data\n    x_data = [-1.6, -1.0, -0.4, 0.2, 0.8, 1.4]\n    f_data = [0.278037, 0.606531, 0.923116, 0.980199, 0.726149, 0.375311]\n\n    print('\\nCompuated with Lagrange Polynomials of 3^rd Degree:')\n    print(f'\\tf(0) = {P(x_data, f_data, [1, 2, 3, 4], 0):.6f}')\n    print(f'\\tf(1) = {P(x_data, f_data, [2, 3, 4, 5], 1):.6f}')\n\n    print('\\nCompuated with Lagrange Polynomials of 4^th Degree:')\n    print(f'\\tf(0) = {P(x_data, f_data, [1, 2, 3, 4, 5], 0):.6f}')\n    print(f'\\tf(1) = {P(x_data, f_data, [1, 2, 3, 4, 5], 1):.6f}')\n\n    # Visualize the Lagrange Polynomials\n    plt.subplot(1, 1, 1)\n    plt.plot(graph([1, 2, 3, 4])[0], graph([1, 2, 3, 4])[1], linewidth = 1, label = 'Third Degree with pos = [1, 2, 3, 4]')\n    plt.plot(graph([2, 3, 4, 5])[0], graph([2, 3, 4, 5])[1], linewidth = 1, label = 'Third Degree with pos = [2, 3, 4, 5]')\n    plt.plot(graph([1, 2, 3, 4, 5])[0], graph([1, 2, 3, 4, 5])[1], linewidth = 1, label = 'Fourth Degree with pos = [1, 2, 3, 4, 5]')\n    plt.scatter(x_data, f_data, color = 'black', marker = \".\", label = 'Sample Points')\n\n    plt.legend(loc = 'lower center', prop = {'size': 10})\n    plt.ylabel('$y$')\n    plt.xlabel('$x$')\n    plt.title('Lagrange Method')\n    plt.show()\n", "meta": {"hexsha": "3a7b3d47c52bc6eb740a289b393dca6c51d18534", "size": 2284, "ext": "py", "lang": "Python", "max_stars_repo_path": "Interpolation/Lagrange-Polynomials.py", "max_stars_repo_name": "AlexTsagas/Computational-Physics", "max_stars_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Interpolation/Lagrange-Polynomials.py", "max_issues_repo_name": "AlexTsagas/Computational-Physics", "max_issues_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Interpolation/Lagrange-Polynomials.py", "max_forks_repo_name": "AlexTsagas/Computational-Physics", "max_forks_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0895522388, "max_line_length": 133, "alphanum_fraction": 0.5582311734, "include": true, "reason": "import numpy", "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307708274402, "lm_q2_score": 0.916109614162018, "lm_q1q2_score": 0.8912196221076647}}
{"text": "def approx_first_derivative(f,x,h):\n    \"\"\"\n    Numerical differentiation by finite differences. Uses central point formula\n    to approximate first derivative of function.\n    Args:\n        f (function): function definition.\n        x (float): point where first derivative will be approximated\n        h (float): step size for central differences. Tipically less than 1\n    Returns:\n        df (float): approximation to first_derivative.\n    \"\"\"\n    df = (f(x+h) - f(x-h))/(2.0*h)\n    return df\n\ndef approx_second_derivative(f,x,h):\n    \"\"\"\n    Numerical differentiation by finite differences. Uses central point formula\n    to approximate second derivative of function.\n    Args:\n        f (function): function definition.\n        x (float): point where second derivative will be approximated\n        h (float): step size for central differences. Tipically less than 1\n    Returns:\n        ddf (float): approximation to second_derivative.\n    \"\"\"\n    ddf =(f(x+h) - 2.0*f(x) + f(x-h))/h**2\n    return ddf\n\ndef main_function():\n    \"\"\"\n    Main execution function\n      args:\n        -\n      returns:\n        -\n    \"\"\"\n    \n    ## Python libraries\n    import numpy as np\n\n    ## Parameters\n    f = np.arctan\n    x = 0.9\n    h = 1e-6\n\n    ## Main code\n    res_first_d = approx_first_derivative(f,x,h)\n    res_second_d = approx_second_derivative(f,x,h)\n\n    print(res_first_d)\n    print(res_second_d)\n\nif __name__ == \"__main__\":\n    main_function()\n", "meta": {"hexsha": "3b67997a65bb4b1e93144590ce6980c40ea17dac", "size": 1448, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ejercicios_clase/1_Calc_diff_int_python/Ejemplo_bloque_main/central_finite_derivative.py", "max_stars_repo_name": "Roberto919/Propedeutico", "max_stars_repo_head_hexsha": "a836cb7a1417efc9ef08802bb049f116125c63cc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ejercicios_clase/1_Calc_diff_int_python/Ejemplo_bloque_main/central_finite_derivative.py", "max_issues_repo_name": "Roberto919/Propedeutico", "max_issues_repo_head_hexsha": "a836cb7a1417efc9ef08802bb049f116125c63cc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ejercicios_clase/1_Calc_diff_int_python/Ejemplo_bloque_main/central_finite_derivative.py", "max_forks_repo_name": "Roberto919/Propedeutico", "max_forks_repo_head_hexsha": "a836cb7a1417efc9ef08802bb049f116125c63cc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3272727273, "max_line_length": 79, "alphanum_fraction": 0.6367403315, "include": true, "reason": "import numpy", "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517475646369, "lm_q2_score": 0.9111797136297299, "lm_q1q2_score": 0.8911809112610027}}
{"text": "# based on https://rpubs.com/andersgs/my_solutions_chapter2_statrethink\n# P(twins|A) = 10%\np_twins_a = 0.1\n# P(single infant|A) = 90%\np_single_a = 0.9\n# P(twins|B) = 20%\np_twins_b = 0.2\n# P(single infant| B) = 80%\np_single_b = 0.8\n# P(A) = P(B) = 0.5\\\np_a, p_b = 0.5, 0.5\n\n# P(twins) = P(twins|A)*P(A) + P(twins|B)*P(B)\np_twins = p_twins_a * p_a + p_twins_b * p_b\n\n# P(A|twins) = P(twins|A)*P(A)/P(twins)\np_a_twins = p_twins_a * p_a / p_twins\n\n# P(B|twins) = P(twins|B)*P(B)/P(twins)\np_b_twins = p_twins_b * p_b / p_twins\n\n#\nresult = p_a_twins * p_twins_a + p_b_twins * p_twins_b\n\nprint('result 2h1 = %f' % (result))\n\n# 2h2 - P(A|twins)\nprint('result 2h2 = %f' % (p_a_twins))\n\n# 2h3\n# P(A | twins, single) = P(twins|A)*P(single|A)*P(A)/P(twins,single)\n# P(twins,single) = P(twins|A)*P(single|A)*P(A) + P(twins|B)*P(single|B)*P(B)\np_twins_single = p_twins_a * p_single_a * p_a + p_twins_b * p_single_b * p_b\np_a_twins_single = p_twins_a * p_single_a * p_a / p_twins_single\nprint('result 2h3=%f' % p_a_twins_single)\n\n# 2h4\np_test_a_a = 0.8\np_test_b_a = 0.2\np_test_b_b = 0.65\np_test_a_b = 0.35\n\n# P(A|testA) = P(testA|A)*P(A)/P(testA)\n# P(testA) = P(testA|A)*P(A)+P(testA|B)*P(B)\np_test_a = p_test_a_a * p_a + p_test_a_b * p_b\np_a_test_a = p_test_a_a * p_a / p_test_a\nprint(\"result 2h4_1=%f\" % p_a_test_a)\n\n# P(A|testA,twins,single) = P(testA|A)*P(twins|A)*P(single|A)*P(A)/P(testA,twins,single)\n# P(testA,twins,single) =\n#   P(testA|A)*P(twins|A)*P(single|A)*P(A) +\n#   P(testA|B)*P(twins|B)*P(single|B)*P(B)\n\np_test_a_twins_single = p_test_a_a * p_twins_a * p_single_a * p_a + p_test_a_b * p_twins_b * p_single_b * p_b\np_a_testa_twins_single = p_test_a_a * p_twins_a * p_single_a * p_a/p_test_a_twins_single\nprint('result 2h4_2=%f'%p_a_testa_twins_single)\n\nprint('---different approach---')\n\n# based on https://github.com/cavaunpeu/statistical-rethinking/blob/master/chapter-2/homework.R\nimport numpy as np\n\nlike = np.array([p_twins_a, p_twins_b])\nprior = np.repeat(1., 2)\npost = like * prior\npost = post / post.sum()\npost_res = post.dot(like)\nprint(\"result 2h1=%f\" % post_res)\nprint(\"result 2h2=%f\" % post[0])\n\nlike = np.array([p_single_a, p_single_b])\n# last posterior is new prior\npost = like * post\npost = post / post.sum()\nprint('result 2h3=%f' % post[0])\n\n#2h4-1\nlike = np.array([p_test_a_a, p_test_a_b])\nprior = np.repeat(1., 2)\npost = like * prior\npost = post / post.sum()\nprint(\"result 2h4_1=%f\" % post[0])\n\n#2h4-2\n# first resolve post from birthing twins\nlike = np.array([p_twins_a, p_twins_b])\nprior = np.repeat(1., 2)\npost = like * prior\npost = post / post.sum()\nlike = np.array([p_single_a, p_single_b])\n# then resolve posterior after birthing also single\npost = like * post\npost = post / post.sum()\n# then after these events, also resolve the event on testing for A\nlike = np.array([p_test_a_a, p_test_a_b])\npost = like * post\npost = post / post.sum()\nprint(\"result 2h4_2=%f\" % post[0])\n\n", "meta": {"hexsha": "cdf3eedd9874d9b93be43fd65ab4343e08e716bb", "size": 2901, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch2/2hard.py", "max_stars_repo_name": "xSakix/bayesian_analyses", "max_stars_repo_head_hexsha": "14042e193507bae6d69caeb4035ac45ef9044176", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch2/2hard.py", "max_issues_repo_name": "xSakix/bayesian_analyses", "max_issues_repo_head_hexsha": "14042e193507bae6d69caeb4035ac45ef9044176", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch2/2hard.py", "max_forks_repo_name": "xSakix/bayesian_analyses", "max_forks_repo_head_hexsha": "14042e193507bae6d69caeb4035ac45ef9044176", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.01, "max_line_length": 109, "alphanum_fraction": 0.6766632196, "include": true, "reason": "import numpy", "num_tokens": 1171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517462851321, "lm_q2_score": 0.9111797088058519, "lm_q1q2_score": 0.8911809053771416}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport numpy as np\n\n\n# Table Utilities\n\ndef is_associative(table):\n    indices = range(len(table))\n    result = True\n    for a in indices:\n        for b in indices:\n            for c in indices:\n                ab = table[a][b]\n                bc = table[b][c]\n                if not (table[ab][c] == table[a][bc]):\n                    result = False\n                    break\n    return result\n\n\ndef is_commutative(table):\n    indices = range(len(table))\n    result = True\n    for a in indices:\n        for b in indices:\n            if table[a][b] != table[b][a]:\n                result = False\n                break\n    return result\n\n\ndef has_left_identity(table):\n    indices = range(len(table))\n    identity = None\n    for x in indices:\n        if all(table[x][y] == y for y in indices):\n            identity = x\n            break\n    return identity\n\n\ndef has_right_identity(table):\n    indices = range(len(table))\n    identity = None\n    for x in indices:\n        if all(table[y][x] == y for y in indices):\n            identity = x\n            break\n    return identity\n\n\ndef has_identity(table):\n    left_id = has_left_identity(table)\n    right_id = has_right_identity(table)\n    if (left_id is not None) and (right_id is not None):\n        return left_id\n    else:\n        return None\n\n\ndef has_inverses(table):\n    return False\n\n\ndef inverse_lookup_dict(table, identity):\n    elements = range(len(table))\n    row_indices, col_indices = np.where(table == identity)\n    return {elements[elem_index]: elements[elem_inv_index]\n            for (elem_index, elem_inv_index)\n            in zip(row_indices, col_indices)}\n\n\nif __name__ == '__main__':\n\n    print(\"\\n=======================================================================\")\n\n    print(\"\\n--------------\")\n    print(\"START OF TESTS\")\n    print(\"--------------\")\n\n    import pprint as pp\n\n    # Table Tests\n\n    print(\"\\nTable Tests:\\n\")\n\n    # not assoc; is comm; no identity -- the RPS magma table, above\n    tbl1 = [[0, 1, 0], [1, 1, 2], [0, 2, 2]]\n\n    # is assoc; not comm; has identity (0) --- the S3 group table\n    tbl2 = [[0, 1, 2, 3, 4, 5], [1, 2, 0, 5, 3, 4], [2, 0, 1, 4, 5, 3],\n            [3, 4, 5, 0, 1, 2], [4, 5, 3, 2, 0, 1], [5, 3, 4, 1, 2, 0]]\n\n    # is assoc; is comm; has identity (0) --- the Z4 group table\n    tbl3 = [[0, 1, 2, 3], [1, 2, 3, 0], [2, 3, 0, 1], [3, 0, 1, 2]]\n\n    # powerset(3) group table\n    tbl4 = [[0, 1, 2, 3, 4, 5, 6, 7], [1, 0, 4, 5, 2, 3, 7, 6], [2, 4, 0, 6, 1, 7, 3, 5],\n            [3, 5, 6, 0, 7, 1, 2, 4], [4, 2, 1, 7, 0, 6, 5, 3], [5, 3, 7, 1, 6, 0, 4, 2],\n            [6, 7, 3, 2, 5, 4, 0, 1], [7, 6, 5, 4, 3, 2, 1, 0]]\n\n    tbl5 = [[0, 3, 0, 3, 0, 3], [1, 4, 1, 4, 1, 4], [2, 5, 2, 5, 2, 5],\n            [3, 0, 3, 0, 3, 0], [4, 1, 4, 1, 4, 1], [5, 2, 5, 2, 5, 2]]\n\n    test_tables = [tbl1, tbl2, tbl3, tbl4, tbl5]\n\n    for tbl in test_tables:\n        pp.pprint(tbl)\n        print()\n\n    print(\"   Table     Associative?  Commutative?   Left Id?   Right Id?  Identity?\")\n    print('-' * 75)\n    for tbl in test_tables:\n        i = test_tables.index(tbl) + 1\n        is_assoc = str(is_associative(tbl))\n        is_comm = str(is_commutative(tbl))\n        lft_id = str(has_left_identity(tbl))\n        rgt_id = str(has_right_identity(tbl))\n        ident = str(has_identity(tbl))\n        print(f\"{i :>{6}} {is_assoc :>{14}} {is_comm :>{12}} {lft_id :>{12}} {rgt_id :>{12}} {ident :>{10}}\")\n\n    print(\"\\n------------\")\n    print(\"END OF TESTS\")\n    print(\"------------\")\n", "meta": {"hexsha": "6168b0ad1ba0f55673f4880dade19b53fa38f780", "size": 3522, "ext": "py", "lang": "Python", "max_stars_repo_path": "trash/table_utils.py", "max_stars_repo_name": "alreich/abstract_algebra", "max_stars_repo_head_hexsha": "9aca57cbc002677aeb117f542a961b7cbdfd4c29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-04T11:23:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T11:23:21.000Z", "max_issues_repo_path": "trash/table_utils.py", "max_issues_repo_name": "alreich/abstract_algebra", "max_issues_repo_head_hexsha": "9aca57cbc002677aeb117f542a961b7cbdfd4c29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trash/table_utils.py", "max_forks_repo_name": "alreich/abstract_algebra", "max_forks_repo_head_hexsha": "9aca57cbc002677aeb117f542a961b7cbdfd4c29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7322834646, "max_line_length": 109, "alphanum_fraction": 0.4988642817, "include": true, "reason": "import numpy", "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214470715363, "lm_q2_score": 0.9241418142333089, "lm_q1q2_score": 0.8911697716007794}}
{"text": "import numpy as np\n\n\nrad = np.pi/2\n\narr_rad = np.array([np.pi/2, np.pi/3, np.pi/4, np.pi/5])\n\n### 1.\n\n# 1.\nprint(np.sin(rad))\nprint(np.sin(arr_rad))\n\n# 2.\nprint(np.cos(rad))\nprint(np.cos(arr_rad))\n\n# 3.\nprint(np.tan(rad))\nprint(np.tan(arr_rad))\n\n\n### 2.\n\n# 1.\nprint(np.rad2deg(rad))\nprint(np.rad2deg(arr_rad))\n\n# 2.\nprint(np.deg2rad(180))\nprint(np.deg2rad([360, 180, 90, 270]))\n\n### 3.\n\n# 1.\nprint(np.arcsin(1.0))\nprint(np.arcsin([1.0, 0.8660254, 0.70710678, 0.58778525]))\n\n# 2. \nprint(np.arccos(6.123233995736766e-17))\nprint(np.arccos([6.12323400e-17, 5.00000000e-01, 7.07106781e-01, 8.09016994e-01]))\n\n# 3.\nprint(np.arctan(1.633123935319537e+16))\nprint(np.arctan([1.63312394e+16, 1.73205081e+00, 1.00000000e+00, 7.26542528e-01]))\n\n###\n\nbase = 5\nperp = 8\n\nprint(np.hypot(base, perp))\n\n", "meta": {"hexsha": "ab73b6c49acc451a746caa0df7b11e94280c1d05", "size": 786, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tutorial/Code/38. NumPy Trigonometric Functions.py", "max_stars_repo_name": "Deve-BlackHeart/Numpy", "max_stars_repo_head_hexsha": "92fac54bc69b0077bd16dbcc9028196c93f0d19f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-23T05:34:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T05:34:45.000Z", "max_issues_repo_path": "Tutorial/Code/38. NumPy Trigonometric Functions.py", "max_issues_repo_name": "Deve-BlackHeart/Numpy", "max_issues_repo_head_hexsha": "92fac54bc69b0077bd16dbcc9028196c93f0d19f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tutorial/Code/38. NumPy Trigonometric Functions.py", "max_forks_repo_name": "Deve-BlackHeart/Numpy", "max_forks_repo_head_hexsha": "92fac54bc69b0077bd16dbcc9028196c93f0d19f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.5555555556, "max_line_length": 82, "alphanum_fraction": 0.6488549618, "include": true, "reason": "import numpy", "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426450627306, "lm_q2_score": 0.9149009607937928, "lm_q1q2_score": 0.8911525518220196}}
{"text": "import numpy\r\nfrom numpy import linalg as LA\r\n\r\n# Input the matrix X\r\nx = numpy.matrix([[5.1, 160, 82000],\r\n                  [5.2, 170, 84000],\r\n                  [5.3, 180, 86000],\r\n                  [5.4, 190, 88000],\r\n                  [5.5, 200, 90000],\r\n                  [5.6, 110, 81000],\r\n                  [5.7, 120, 83000],\r\n                  [5.8, 130, 85000],\r\n                  [5.9, 140, 87000],\r\n                  [6.0, 150, 89000]])\r\n\r\nprint(\"Input Matrix = \\n\", x)\r\n\r\nprint(\"Number of Dimensions = \", x.ndim)\r\n\r\nprint(\"Number of Rows = \", numpy.size(x,0))\r\nprint(\"Number of Columns = \", numpy.size(x,1))\r\n\r\nxtx = x.transpose() * x\r\nprint(\"t(x) * x = \\n\", xtx)\r\n\r\n# Eigenvalue decomposition\r\nevals, evecs = LA.eigh(xtx)\r\nprint(\"Eigenvalues of x = \\n\", evals)\r\nprint(\"Eigenvectors of x = \\n\",evecs)\r\n\r\n# Here is the transformation matrix\r\ndvals = 1.0 / numpy.sqrt(evals)\r\ntransf = evecs * numpy.diagflat(dvals)\r\nprint(\"Transformation Matrix = \\n\", transf)\r\n\r\n# Here is the transformed X\r\ntransf_x = x * transf;\r\nprint(\"The Transformed x = \\n\", transf_x)\r\n\r\n# Check columns of transformed X\r\nxtx = transf_x.transpose() * transf_x;\r\nprint(\"Expect an Identity Matrix = \\n\", xtx)\r\n\r\n# Orthonormalize using the orth function \r\nimport scipy\r\nfrom scipy import linalg as LA2\r\n\r\northx = LA2.orth(x)\r\nprint(\"The orthonormalize x = \\n\", orthx)\r\n\r\n# Check columns of the ORTH function\r\ncheck = orthx.transpose().dot(orthx)\r\nprint(\"Also Expect an Identity Matrix = \\n\", check)", "meta": {"hexsha": "61b855756a5f485badfd964e015eedf767d05031", "size": 1480, "ext": "py", "lang": "Python", "max_stars_repo_path": "Association Rules/Eigenvalue.py", "max_stars_repo_name": "eyobghiday/machine-learning", "max_stars_repo_head_hexsha": "d7165f2b64df6fb780ad30aae55b3b827382bede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-14T20:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T07:06:31.000Z", "max_issues_repo_path": "Association Rules/Eigenvalue.py", "max_issues_repo_name": "eyobghiday/machine-learning", "max_issues_repo_head_hexsha": "d7165f2b64df6fb780ad30aae55b3b827382bede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Association Rules/Eigenvalue.py", "max_forks_repo_name": "eyobghiday/machine-learning", "max_forks_repo_head_hexsha": "d7165f2b64df6fb780ad30aae55b3b827382bede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9245283019, "max_line_length": 51, "alphanum_fraction": 0.577027027, "include": true, "reason": "import numpy,from numpy,import scipy,from scipy", "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426397881663, "lm_q2_score": 0.9149009491921664, "lm_q1q2_score": 0.8911525356958367}}
{"text": "#!/usr/bin/env python3\nimport sys\nimport numpy as np\n\nnp.random.seed(2017)\n\ndef inside_circle(total_count):\n\n    x = np.random.uniform(size=total_count)\n    y = np.random.uniform(size=total_count)\n\n    radii_square = x**2 + y**2\n\n    count = (radii_square<=1.0).sum()\n\n    return count\n\ndef estimate_pi(n_samples):\n\n    return (4.0 * inside_circle(n_samples) / n_samples)\n\nif __name__=='__main__':\n\n    n_samples = 10000\n    if len(sys.argv) > 1:\n        n_samples = int(sys.argv[1])\n\n    my_pi = estimate_pi(n_samples)\n    sizeof = np.dtype(np.float64).itemsize\n\n    print(\"[serial version] required memory {:.3f} MB\".format(n_samples*sizeof*3/(1024*1024)))\n    print(\"[serial version] pi is {} from {} samples\".format(my_pi,n_samples))\n    print(\"[serial version] got {} digits right\".format(int(np.ceil(-np.log10(abs(my_pi - np.pi))))))\n", "meta": {"hexsha": "d4cb9d41e72e660871a711599dc1bb36022fe5c4", "size": 840, "ext": "py", "lang": "Python", "max_stars_repo_path": "4_digits_of_pi/1_serial_digits_of_pi.py", "max_stars_repo_name": "ucsdlib/2017-intro-hpc", "max_stars_repo_head_hexsha": "51562484a70710ac129fee8c5e804fac9c4130ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4_digits_of_pi/1_serial_digits_of_pi.py", "max_issues_repo_name": "ucsdlib/2017-intro-hpc", "max_issues_repo_head_hexsha": "51562484a70710ac129fee8c5e804fac9c4130ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4_digits_of_pi/1_serial_digits_of_pi.py", "max_forks_repo_name": "ucsdlib/2017-intro-hpc", "max_forks_repo_head_hexsha": "51562484a70710ac129fee8c5e804fac9c4130ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7058823529, "max_line_length": 101, "alphanum_fraction": 0.6678571429, "include": true, "reason": "import numpy", "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.9314625031628428, "lm_q1q2_score": 0.8910688865429394}}
{"text": "import numpy as np\n\n'''\nExercise 0 (ungraded).\nOne reason to consider Numpy is that it \"can be much faster,\" as noted above.\nBut how much faster is that? Run the experiment below to see.\n'''\n\nn = 1000000\n\nL = range(n)\n%timeit [i**2 for i in L]\n# 269 ms ± 729 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\nnp.arange(10)  # Moral equivalent to `range`\n\nA = np.arange(n)\n%timeit A**2\n\n#699 µs ± 5.51 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\n'''\nExercise 1 (ungraded). \nThe following code creates an identity matrix in two different ways, which are found to be equal according to the assertion. \nBut in fact there is a subtle difference between the I and I_u matrices created below; can you spot it?\n'''\nn = 3\nI = np.eye(n)\n\nprint(\"==> I = eye(n):\")\nprint(I)\n\nu = [1] * n\nI_u = np.diag(u)\n\nprint(\"\\n==> u:\\n\", u)\nprint(\"==> I_u = diag (u):\\n\", I_u)\n\nassert np.all(I_u == I)\n\n#Difference is between types, eyes is a float-point numbers, while daig is integer.\n\n'''\nExercise 2 (5 points). Consider the following  6×66×6  matrix, which has 4 different subsets highlighted.\nFor each subset illustrated above, write an indexing or slicing expression that extracts the subset. \nStore the result of each slice into Z_green, Z_red, Z_orange, and Z_cyan.\n'''\n\nZ= np.array([[0,1,2,3,4,5],[10,11,12,13,14,15],[20,21,22,23,24,25],[30,31,32,33,34,35],[40,41,42,43,44,45],[50,51,52,53,54,55]])\n\n# Construct `Z_green`, `Z_red`, `Z_orange`, and `Z_cyan`:\nZ_orange = Z[0, 3:5]\nZ_red = Z[:, 2]\nZ_green = Z[2::2, ::2]\nZ_cyan = Z[4:, 4:]\n\n'''\nExercise 3 (1 point). \nGiven the input array, x[:], above, create an array, mask_mult_3[:] such that mask_mult_3[i] is true only if x[i] is a positive multiple of 3.\n'''\n\nmask_mult_3 = (x > 0) & (x % 3 == 0)\n\n'''\nExercise 4 (3 points). Complete the prime number sieve algorithm, which is illustrated below.\n'''\n\nfrom math import sqrt\n\n\ndef sieve(n):\n    \"\"\"\n    Returns the prime number 'sieve' shown above.\n\n    That is, this function returns an array `X[0:n+1]`\n    such that `X[i]` is true if and only if `i` is prime.\n    \"\"\"\n    is_prime = np.empty(n + 1, dtype=bool)  # the \"sieve\"\n\n    # Initial values\n    is_prime[0:2] = False  # {0, 1} are _not_ considered prime\n    is_prime[2:] = True  # All other values might be prime\n\n    # Implement the sieving loop\n\n    for k in range(2, int(sqrt(n)) + 1):\n        is_prime[2 * k::k] = False\n\n\n    return is_prime\n\n\n# Prints your primes\nprint(\"==> Primes through 20:\\n\", np.nonzero(sieve(20))[0])", "meta": {"hexsha": "639e5e2712d0bbe2577e60cd2a3140d433d54988", "size": 2493, "ext": "py", "lang": "Python", "max_stars_repo_path": "EdX/GTx: CSE6040x: FA18 - Computing for Data Analysis/Module 2: The analysis of data/Topic 10: Numerical computing with Numpy-Scipy/Notebook_10.py", "max_stars_repo_name": "helpthx/Path_through_Data_Science-", "max_stars_repo_head_hexsha": "aa22333eae970506f2ce184551c55565b0be89fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-02-06T09:30:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-09T18:24:46.000Z", "max_issues_repo_path": "EdX/GTx: CSE6040x: FA18 - Computing for Data Analysis/Module 2: The analysis of data/Topic 10: Numerical computing with Numpy-Scipy/Notebook_10.py", "max_issues_repo_name": "helpthx/Path_through_Data_Science-", "max_issues_repo_head_hexsha": "aa22333eae970506f2ce184551c55565b0be89fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2019-06-22T00:58:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-27T14:59:21.000Z", "max_forks_repo_path": "EdX/GTx: CSE6040x: FA18 - Computing for Data Analysis/Module 2: The analysis of data/Topic 10: Numerical computing with Numpy-Scipy/Notebook_10.py", "max_forks_repo_name": "helpthx/Path_through_Data_Science-", "max_forks_repo_head_hexsha": "aa22333eae970506f2ce184551c55565b0be89fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-03T21:10:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-03T21:10:43.000Z", "avg_line_length": 26.5212765957, "max_line_length": 142, "alphanum_fraction": 0.6530284797, "include": true, "reason": "import numpy", "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.9489172625012162, "lm_q1q2_score": 0.8910568591750869}}
{"text": "import numpy as np\nimport pandas as pd\nimport scipy\nfrom scipy.stats import norm\n\n\ndef semi_deviation(r):\n    \"\"\"\n    Returns the semi deviation, aka negative semi deviation of r\n    r must be a Series or a DataFrame\n    \"\"\"\n    is_negative = r < 0\n    return r[is_negative].std(ddof=0)\n\n\ndef skewness(r):\n    \"\"\"\n    Alternate to scipy.stats.skew()\n    Computes the skewness of the supplied Series or  DataFrame\n    Returns a float or a series\n    \"\"\"\n    demeaned_r = r - r.mean()\n    sigma_r = r.std(ddof=0)\n    exp = (demeaned_r ** 3).mean()\n    return exp / sigma_r ** 3\n\n\ndef kurtosis(r):\n    \"\"\"\n    Alternate to scipy.stats.kurtosis()\n    Computes the kurtosis of the supplied Series or DataFrame\n    Returns a float or a series\n    \"\"\"\n    demeaned_r = r - r.mean()\n    sigma_r = r.std(ddof=0)\n    exp = (demeaned_r ** 4).mean()\n    return exp / sigma_r ** 4\n\n\ndef is_normal(r, level=0.01):\n    \"\"\"\n    Applies the Jarque-Bera test to determine if a Series is normal or not.\n    Test is applied at 1% level by default\n    Returns True if the hypothesis of normality is accepted, else False.\n    \"\"\"\n    statistic, pvalue = scipy.stats.jarque_bera(r)\n    return pvalue > level\n\n\ndef var_historic(r, levels=5):\n    \"\"\"\n    Returns the historic value at risk at a specified level\n    i.e returns the level such that \"level\" percent of returns\n    fall below that number, and the (100-level) percent are above\n    \"\"\"\n    if isinstance(r, pd.DataFrame):\n        return r.aggregate(var_historic, levels=levels)\n    elif isinstance(r, pd.Series):\n        return -np.percentile(r, levels, axis=0)\n    else:\n        raise TypeError(\"Series or DataFrame expected\")\n\n\ndef var_gaussian(r, levels=5, modified=False):\n    \"\"\"\n    Returns the Parametric Gaussian VaR of a Series or DataFrame\n    If modified is  True, then the modified VaR is returned\n    using Cornish-Fisher modifications\n    \"\"\"\n    # compute the Z score assuming the distribution is Gaussian\n    z = norm.ppf(levels / 100)\n\n    if modified:\n        # calculate the Z score based on kurtosis and skewness\n        s = skewness(r)\n        k = kurtosis(r)\n        z = (z +\n             (z ** 2 + 1) * s / 6 +\n             (z ** 3 - 3 * z) * (k - 3) / 24 +\n             (2 * z ** 3 - 5 * z) * (s ** 2) / 36\n             )\n\n    return -(r.mean() + z * r.std(ddof=0))\n\n\ndef cvar_historic(r, levels=5):\n    \"\"\"\n    Computes the conditional VaR or CVaR of the Series or DataFrame\n    \"\"\"\n    if isinstance(r, pd.Series):\n        is_beyond = r <= -var_historic(r, levels=levels)\n        return -r[is_beyond].mean()\n    elif isinstance(r, pd.DataFrame):\n        return r.aggregate(cvar_historic, levels=levels)\n    else:\n        raise TypeError(\"Expected the input to be DataFrame or Series\")\n", "meta": {"hexsha": "b9821676701093a2e3a78556eda4d5d7f14026b6", "size": 2748, "ext": "py", "lang": "Python", "max_stars_repo_path": "core/operations/statistics.py", "max_stars_repo_name": "francescodisalvo05/portfolio_analysis", "max_stars_repo_head_hexsha": "1145d5b0307acde50a9b1be6be62483b16c70f34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-12-19T21:14:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T09:34:42.000Z", "max_issues_repo_path": "core/operations/statistics.py", "max_issues_repo_name": "francescodisalvo05/portfolio_analysis", "max_issues_repo_head_hexsha": "1145d5b0307acde50a9b1be6be62483b16c70f34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/operations/statistics.py", "max_forks_repo_name": "francescodisalvo05/portfolio_analysis", "max_forks_repo_head_hexsha": "1145d5b0307acde50a9b1be6be62483b16c70f34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-20T11:38:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T11:38:52.000Z", "avg_line_length": 28.3298969072, "max_line_length": 75, "alphanum_fraction": 0.6244541485, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561685659695, "lm_q2_score": 0.9196425394367774, "lm_q1q2_score": 0.8910013472089946}}
{"text": "# Reference: https://stackabuse.com/gradient-descent-in-python-implementation-and-theory/\n\nimport numpy as np\nimport plotly.graph_objects as go\n\n# User defined modules\nfrom test_functions import available_functions\n\n\nclass GradientDescent:\n    def __init__(self, objective_function, initial_point, precision=1e-6, max_iter=10000, rate=0.1, momentum=0.1):\n        self.objective_fn = objective_function\n        self.initial_point = np.array(initial_point)\n        self.precision = precision\n        self.max_iter = max_iter\n        self.learning_rate = rate\n        self.momentum = momentum\n\n        self.step_size = 1\n        self.iters = 0\n        self.points_history = np.array(initial_point)\n        self.fun_history = np.array(objective_function.calculate(initial_point))\n        self.name = \"Gradient Descent\"\n\n    def optimize(self):\n        current_point = self.initial_point\n        delta_pts = np.zeros(current_point.shape)  # change in points\n        print(\"Starting point = \", np.round(self.initial_point, 2))\n        while self.step_size > self.precision and self.iters < self.max_iter:\n            # print(\"Iteration: \", self.iters)\n            delta_pts = -self.learning_rate * self.objective_fn.gradient(current_point) + self.momentum * delta_pts\n            current_point = current_point + delta_pts\n            self.update_history(current_point)\n\n            self.step_size = np.absolute(self.fun_history[-1] - self.fun_history[-2])\n            self.iters += 1\n        return {\"minimum\": self.fun_history[-1], \"position\": current_point, \"path\": self.optimization_path()}\n\n    def update_history(self, new_point):\n        self.points_history = np.vstack((self.points_history, new_point))\n        self.fun_history = np.vstack((self.fun_history, self.objective_fn.calculate(new_point)))\n\n    def print_output(self):\n        minimum = np.round(self.fun_history[-1], 3)\n        position = np.round(self.points_history[-1], 3)\n        print(f'Predicted minimum = {minimum} at {position}')\n\n    def optimization_path(self):\n        return go.Scatter(x=self.points_history[:, 0], y=self.points_history[:, 1], mode=\"lines+markers\")\n\n\ndef available_optimizers():\n    return {\"Gradient Descent\": GradientDescent}\n\n\ndef optimize_function(point, fn_name: str, alg_name: str):\n    test_fns = available_functions()\n    selected_fn = test_fns[fn_name]\n    optimizers = available_optimizers()\n    selected_alg = optimizers[alg_name]\n    optimizer_obj = selected_alg(selected_fn(), point)\n    output = optimizer_obj.optimize()\n    optimizer_obj.print_output()\n    minimum = np.round(output[\"minimum\"], 3)\n    position = np.round(output[\"position\"], 3)\n    return minimum[0], (position[0], position[1]), output[\"path\"]\n\n\nif __name__ == \"__main__\":\n    funs = available_functions()\n    opt_algorithms = available_optimizers()\n    for alg_name, algs in opt_algorithms.items():\n        print(alg_name)\n        for fn_name, test_fn in funs.items():\n            print(fn_name)\n            fun_object = test_fn()\n            opt_obj = algs(fun_object, np.random.uniform(fun_object.lower_limit, fun_object.upper_limit, 2))\n            _ = opt_obj.optimize()\n            opt_obj.print_output()\n", "meta": {"hexsha": "a3f9fd89b43ad481e97fcbc9d5c17b85696e48be", "size": 3184, "ext": "py", "lang": "Python", "max_stars_repo_path": "optimizers.py", "max_stars_repo_name": "febin-varghese/simply-optimize", "max_stars_repo_head_hexsha": "d9933711a4e072c208b66cc22d5ef279690028c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-27T23:29:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T23:29:10.000Z", "max_issues_repo_path": "optimizers.py", "max_issues_repo_name": "febin-varghese/simply-optimize", "max_issues_repo_head_hexsha": "d9933711a4e072c208b66cc22d5ef279690028c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimizers.py", "max_forks_repo_name": "febin-varghese/simply-optimize", "max_forks_repo_head_hexsha": "d9933711a4e072c208b66cc22d5ef279690028c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8, "max_line_length": 115, "alphanum_fraction": 0.6815326633, "include": true, "reason": "import numpy", "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147153749275, "lm_q2_score": 0.9161096055730491, "lm_q1q2_score": 0.8908384613555537}}
{"text": "import numpy as np\n\n\ndef probability_of_sum(total:int, dice1, dice2):\n\n    \"\"\"\n    Brief: \n    Basic probability - Dice cast\n    Suppose a pair of fair 6-sided dice are thrown. \n    What is the probability that the sum of the rolls is 6? (Answer as a simple fraction of integers)\n    reference: https://statweb.stanford.edu/~susan/courses/s60/split/node65.html\n    \"\"\"\n\n    n = dice1.shape[0]\n    m = dice2.shape[0]\n\n    comb = n * m\n    count = 0\n\n    for i in dice1:\n        for j in dice2:\n            sum = int(i + j)\n            if sum == total:\n                count += 1\n    \n    prob = count / comb\n    \n    return print(\"{:.2%}\".format(prob))\n            \n# define the dice as a linear array of 1 to 6, all integers\ndice1 = np.linspace(1,6,6,dtype=int)\n\n# call the function above with the total for which we would like to calculate the probability with 2 dices\nprob = probability_of_sum(6, dice1, dice1)\n\n\n\n\n", "meta": {"hexsha": "a4c959a24f55476956d7d9000d6c3ea81927617c", "size": 917, "ext": "py", "lang": "Python", "max_stars_repo_path": "dices.py", "max_stars_repo_name": "mariamingallonMM/AI-ML-W4-normal-probability-distribution", "max_stars_repo_head_hexsha": "95569929078b22555f870675f27aeca29f8ce487", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-07T12:25:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-07T12:25:20.000Z", "max_issues_repo_path": "dices.py", "max_issues_repo_name": "mariamingallonMM/AI-ML-W4-normal-probability-distribution", "max_issues_repo_head_hexsha": "95569929078b22555f870675f27aeca29f8ce487", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dices.py", "max_forks_repo_name": "mariamingallonMM/AI-ML-W4-normal-probability-distribution", "max_forks_repo_head_hexsha": "95569929078b22555f870675f27aeca29f8ce487", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5128205128, "max_line_length": 106, "alphanum_fraction": 0.6150490731, "include": true, "reason": "import numpy", "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971129093053712, "lm_q2_score": 0.9173026528034425, "lm_q1q2_score": 0.8908192932727711}}
{"text": "import numpy as np\n\n\n# Relu\ndef relu(y) -> np.ndarray:\n    return np.maximum(y, 0)\n\n\ndef relu_prime(y) -> np.ndarray:\n    return y > 0\n\n\n# Leaky relu\ndef leaky_relu(y) -> np.ndarray:\n    return np.where(y > 0, y, y * 0.01)\n\n\ndef leaky_relu_prime(y) -> np.ndarray:\n    return (y >= 0) + (y < 0)*0.01\n\n\n# Linear\ndef linear(y) -> np.ndarray:\n    return y\n\n\ndef linear_prime(y) -> np.ndarray:\n    return 1\n\n\n# Heavyside\ndef heaviside(y) -> np.ndarray:\n    return 1 * (y > 0)\n\n\ndef heaviside_prime(y) -> np.ndarray:\n    return 0\n\n\n# Sigmoid\ndef sigmoid(y) -> np.ndarray:\n    return 1 / (1 + np.exp(-y))\n\n\ndef sigmoid_prime(y) -> np.ndarray:\n    return sigmoid(y) * (1 - sigmoid(y))\n\n\n# Tanh\ndef tanh(y) -> np.ndarray:\n    return np.tanh(y)\n\n\ndef tanh_prime(y) -> np.ndarray:\n    return 1 - tanh(y)**2\n\n\n# Arctan\ndef arctan(y) -> np.ndarray:\n    return np.arctan(y)\n\n\ndef arctan_prime(y) -> np.ndarray:\n    return 1 / (y**2 + 1)\n\n\n# Softmax\ndef softmax(y) -> np.ndarray:\n    e = np.exp(y - np.max(y))\n    return e / e.sum(axis=0)\n\n\n# TODO implement a solution to derive softmax : the result has not the same shape as the input\ndef softmax_prime(y) -> np.ndarray:\n    s = y.reshape(-1, 1)\n    return np.mean(np.diagflat(s) - np.dot(s, s.T))\n\n\ndef listToActivations(activations_list, architecture) -> list:\n    activations_fn = []\n    activations_prime = []\n    for id, _ in enumerate(architecture):\n        if id < len(activations_list):\n\n            if activations_list[id] == 'relu':\n                activations_fn.append(relu)\n                activations_prime.append(relu_prime)\n\n            elif activations_list[id] == 'leaky_relu':\n                activations_fn.append(leaky_relu)\n                activations_prime.append(leaky_relu_prime)\n\n            elif activations_list[id] == 'linear':\n                activations_fn.append(linear)\n                activations_prime.append(linear_prime)\n\n            elif activations_list[id] == 'heaviside':\n                activations_fn.append(heaviside)\n                activations_prime.append(heaviside_prime)\n\n            elif activations_list[id] == 'sigmoid':\n                activations_fn.append(sigmoid)\n                activations_prime.append(sigmoid_prime)\n\n            elif activations_list[id] == 'tanh':\n                activations_fn.append(tanh)\n                activations_prime.append(tanh_prime)\n\n            elif activations_list[id] == 'arctan':\n                activations_fn.append(arctan)\n                activations_prime.append(arctan_prime)\n\n            elif activations_list[id] == 'softmax':\n                print(\n                    'Error : transfert function `', activations_list[id], '` is not fully implemented.', sep='')\n                exit(1)\n                activations_fn.append(softmax)\n                activations_prime.append(softmax_prime)\n\n            else:\n                print(\n                    'Error : transfert function `', activations_list[id], '` does not exist.', sep='')\n                exit(1)\n\n        # If not defined, fallback function is relu\n        else:\n            activations_fn.append(relu)\n            activations_prime.append(relu_prime)\n\n    return activations_fn, activations_prime\n", "meta": {"hexsha": "6d9d6f4c27a54b6e7fb70f13f9a4ee58e9a86256", "size": 3199, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/activations.py", "max_stars_repo_name": "aunetx/loulou", "max_stars_repo_head_hexsha": "ff28c1fe4c2f1c2ac0cc18917954acfd2fa4e5ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-12-01T18:21:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-02T15:30:12.000Z", "max_issues_repo_path": "scripts/activations.py", "max_issues_repo_name": "aunetx/loulou", "max_issues_repo_head_hexsha": "ff28c1fe4c2f1c2ac0cc18917954acfd2fa4e5ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/activations.py", "max_forks_repo_name": "aunetx/loulou", "max_forks_repo_head_hexsha": "ff28c1fe4c2f1c2ac0cc18917954acfd2fa4e5ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4198473282, "max_line_length": 112, "alphanum_fraction": 0.5892466396, "include": true, "reason": "import numpy", "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446463891303, "lm_q2_score": 0.9149009642742805, "lm_q1q2_score": 0.8907884258419061}}
{"text": "import numpy as np\nimport scipy\nimport sympy\nfrom numpy import linalg as lg\nfrom numpy.linalg import solve\nfrom numpy.linalg import eig\nfrom scipy.integrate import quad\n\n\n# Question 1\n'''\nA. Determinant = -21\n\nB. Determinant = -21\n\n'''\n\nm1 = np.array([[3, 0, 3], [2, 3, 3], [0, 4, -1]])\nprint(m1)\n\ndet1 = np.linalg.det(m1)\nprint(det1) # correct\n\n# Question 2\n# Det = -159\n\n# Question 3\n'''\nA. \nReplace row 3 with k times row 3.\n\nB. \nThe determinant is multiplied by k.\n'''\n\n# Question 4\nm2 = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]])\ndet2 = np.linalg.det(m2)\nprint(det2) # correct\n\n# Question 5\n'''\nA.\nFalse, because the determinant of A can be computed by cofactor expansion across any row or down any column. Since the determinant of A is well​ defined, both of these cofactor expansions will be equal.\n\nB.\n\n​False, because the determinant of a triangular matrix is the product of the entries along the main diagonal.\n'''\n\n# Question 6\n'''\nIf two rows of A are interchanged to produce​ B, then det Upper B equals negative det A.\n'''\n\n# Question 7\n'''\nIf a multiple of one row of A is added to another row to produce matrix​ B, then det Upper B equals det Upper A.\n'''\n\n# Question 8\nm3 = sympy.Matrix([[1, 5, -6], [-1, -4, -5], [1, 4, 7]])\nprint(m3)\nrref1 = m3.rref()\nprint(rref1)\n\nm4 = np.array([[1, 5, -6], [-1, -4, -5], [1, 4, 7]])\ndet3 = np.linalg.det(m4)\nprint(det3) # correct, det = 2\n\n# Question 9\n# Switch the rows, det of original matrix = -10, det of changed matrix = 10\n\n# Question 10\nm5 = np.array([[-25, -4, -2], [-5, 12, -4], [0, -20, 6]])\ndet4 = np.linalg.det(m5)\nprint(det4)\n# The matrix is invertible because the determinant of the matrix is not zero.\n\n# Question 11\n# formula\n\n# Question 12\nmat = np.array([[1,1,0], [3, 0, 5], [0, 1, -5]])\nprint(mat)\ndet8 = np.linalg.det(mat)\nprint(det8)\n\n#Cramer's Rule\n# Find A1b by replacing the first column with column b\nmat2 = np.array([[2,1,0], [0, 0, 5], [3, 1, -5]])\nprint(mat2)\ndet9 = np.linalg.det(mat2)\nprint(det9)\nprint(det9/det8)\n\n#Find A2b by replacing the second column with b\nmat3 = np.array([[1, 2, 0], [3, 0, 5], [0, 3, -5]])\nprint(mat3)\ndet10 = np.linalg.det(mat3)\nprint(det10)\nprint(det10/det8)\n\n#Find A3b by replacing the third column with b\nmat4 = np.array([[1, 1, 2], [3, 0, 0], [0, 1, 3]])\nprint(mat4)\ndet11 = np.linalg.det(mat4)\nprint(det11)\nprint(det11/det8)\n\n# Answers above are correct, but try again because I misread the print output\n\nmatr = np.array([[1,1,0], [5, 0, 4], [0, 1, -4]])\nprint(matr)\ndeter = np.linalg.det(matr)\nprint(deter)\n\n# Find A1b by replacing first column with b\nmatr1 = np.array([[5, 1, 0], [0, 0, 4], [6, 1, -4]])\nprint(matr1)\ndeter1 = np.linalg.det(matr1)\nprint(deter1/deter)\n\n# Find A2b by replacing second column with b\nmatr2 = np.array([[1, 5, 0], [5, 0, 4], [0, 6, -4]])\nprint(matr2)\ndeter2 = np.linalg.det(matr2)\nprint(deter2/deter)\n\n# Find A3b by replacing third column with b\nmatr3 = np.array([[1, 1, 5], [5, 0, 0], [0, 1, 6]])\nprint(matr3)\ndeter3 = np.linalg.det(matr3)\nprint(deter3/deter)\n\n# Question 13\n# Compute the adjugate of the given matrix\nmatri = np.matrix([[2, 5, 4], [1, 0, 1], [3, 2, 2]])\nprint(matri)\n# Hermitian transpose (not correct)\nprint(matri.getH())\n# Det of matrix\ndeterm = np.linalg.det(matri)\nprint(determ)\n\nadj_matr = np.array([[-2, -2, 5], [1, -8, 2], [2, 11, -5]])\nprint(adj_matr * 1/determ) # Correct\n\n# Question 14\nm6 = np.array([[3, 7], [6, 2]])\nprint(m6)\ndet5 = np.linalg.det(m6)\nprint(det5) # correct\n# The area of the parellelogram is the absolute value of the det. In this case = 36\n\n# Question 15\n# First find the area of the parellelogram\nm7 = np.array([[-5, -5], [5, 10]])\ndet6 = np.linalg.det(m7)\nprint(det6) # -25\n\n# next find the det of matrix A\nm8 = np.array([[7, -8], [-2, 8]])\nprint(m8)\ndet7 = np.linalg.det(m8)\nprint(det7) # 40\n\n# Finally, multiply the absolute value of the det of the first matrix (area of the parellelogram) by the det of the second matrix \n# Answer = 1000\n", "meta": {"hexsha": "d26193d8f95b87350b91fd8517bcdb1ccfde7d7b", "size": 3936, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ch_5/linear_alg5.py", "max_stars_repo_name": "Skyblueballykid/linalg", "max_stars_repo_head_hexsha": "515eea984856ad39c823314178929876b21f8014", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ch_5/linear_alg5.py", "max_issues_repo_name": "Skyblueballykid/linalg", "max_issues_repo_head_hexsha": "515eea984856ad39c823314178929876b21f8014", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ch_5/linear_alg5.py", "max_forks_repo_name": "Skyblueballykid/linalg", "max_forks_repo_head_hexsha": "515eea984856ad39c823314178929876b21f8014", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1529411765, "max_line_length": 202, "alphanum_fraction": 0.6532012195, "include": true, "reason": "import numpy,from numpy,import scipy,from scipy,import sympy", "num_tokens": 1424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854103128328, "lm_q2_score": 0.9184802496038499, "lm_q1q2_score": 0.8907287457263027}}
{"text": "# --------------\n# Code starts here\n\nimport numpy as np\n\n# Code starts here\n\n# Adjacency matrix\nadj_mat = np.array([[0,0,0,0,0,0,1/3,0],\n                   [1/2,0,1/2,1/3,0,0,0,0],\n                   [1/2,0,0,0,0,0,0,0],\n                   [0,1,0,0,0,0,0,0],\n                  [0,0,1/2,1/3,0,0,1/3,0],\n                   [0,0,0,1/3,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,1,1/3,0]])\n\n# Compute eigenvalues and eigencevectrs\n\neigenvalues , eigencevectors = np.linalg.eig(adj_mat)\n\nprint(eigenvalues)\n\nprint(eigencevectors)\n\n\n\n\n# Eigen vector corresponding to 1\n\neigen_1 = abs(eigencevectors[:,0])\n\nprint(eigen_1)\n\n\neigen_1 = abs(eigencevectors[:,0])/np.linalg.norm(eigencevectors[:,0],1)\n\nprint(eigen_1)\n\n# most important page\n\npage = np.where(np.max(eigen_1)== eigen_1)[0][0] + 1\nprint(page)\n\n\n\n\n# Code ends here\n\n\n# --------------\n# Code starts here\n\nadj_mat\nprint(adj_mat)\n\n\n\n# Initialize stationary vector I\n\ninit_I = np.array([1,0,0,0,0,0,0,0])\nprint(init_I)\n\na= np.dot(adj_mat , init_I)\nprint(a)\n\nb = np.linalg.norm(init_I , 1)\nprint(b)\n\n\nfor i in range(10):\n        init_I = np.dot(adj_mat , init_I)\n        init_I /= np.linalg.norm(init_I , 1)\n\nprint(init_I)\n\n\n\n# Perform iterations for power method\n\npower_page = np.where(np.max(init_I)==init_I)[0][0] +1\nprint(power_page)\n\n\n# Code ends here\n\n\n# --------------\n# Code starts here\n\n# New Adjancency matrix\n# New Adjancency matrix\nnew_adj_mat = np.array([[0,0,0,0,0,0,0,0],\n                   [1/2,0,1/2,1/3,0,0,0,0],\n                  [1/2,0,0,0,0,0,0,0],\n                   [0,1,0,0,0,0,0,0],\n                   [0,0,1/2,1/3,0,0,1/2,0],\n                   [0,0,0,1/3,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,1,1/2,0]])\n\n# Initialize stationary vector I\n\nnew_init_I = np.array([1,0,0,0,0,0,0,0])\n\nprint(new_init_I)\n\n\n# Perform iterations for power method\nfor _ in range(10):\n    new_init_I = np.dot(new_adj_mat, new_init_I)\n    new_init_I /= np.linalg.norm(new_init_I, 1)\n\n\nprint(new_init_I)\n\n\npower_page = np.where(np.max(new_init_I) == new_init_I)[0][0] + 1\nprint(power_page)\n\nprint(new_init_I)\n\n    \n\n\n\n\n# Perform iterations for power method\n\n\n\n\n\n# Code ends here\n\n\n# --------------\n# Alpha value\nalpha = 0.85\n\nnew_adj_mat\nprint(new_adj_mat)\n\n\nlen(new_adj_mat)\n\nnp.ones(new_adj_mat.shape)\n\nG = (alpha*new_adj_mat) + (1-alpha)*(1 / len(new_adj_mat))*np.ones(new_adj_mat.shape)\n\n\n\nprint(G)\n\nfinal_init_I = np.array([1 , 0 , 0,0,0,0,0,0])\nprint(final_init_I)\n\n\n\nfor _ in range(1000):\n    final_init_I = np.dot(G, final_init_I)\n    final_init_I /= np.linalg.norm(final_init_I, 1)\n\n\nprint(final_init_I)\n\n\npower_page = np.where(np.max(final_init_I) == final_init_I)[0][0] + 1\nprint(power_page)\n\nprint(final_init_I)\n\n\n\n\n\n# Code starts here\n\n# Modified adjancency matrix\n\n\n# Initialize stationary vector I\n\n\n# Perform iterations for power method\n\n\n# Code ends here\n\n\n", "meta": {"hexsha": "39d24925d906d3e92777a81a51a6833256833967", "size": 2914, "ext": "py", "lang": "Python", "max_stars_repo_path": "Nitesh_NLP_DL/code.py", "max_stars_repo_name": "Niteshnupur/nlp-dl-prework", "max_stars_repo_head_hexsha": "1a306888de544f9feda512a4ad9b518242e8f3f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Nitesh_NLP_DL/code.py", "max_issues_repo_name": "Niteshnupur/nlp-dl-prework", "max_issues_repo_head_hexsha": "1a306888de544f9feda512a4ad9b518242e8f3f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nitesh_NLP_DL/code.py", "max_forks_repo_name": "Niteshnupur/nlp-dl-prework", "max_forks_repo_head_hexsha": "1a306888de544f9feda512a4ad9b518242e8f3f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.2565445026, "max_line_length": 85, "alphanum_fraction": 0.5881949211, "include": true, "reason": "import numpy", "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969785409439575, "lm_q2_score": 0.9184802462567087, "lm_q1q2_score": 0.8907287416782239}}
{"text": "# https://docs.sympy.org/latest/tutorial/solvers.html\n\nfrom sympy import *\nx, y, z = symbols('x y z')\ninit_printing(use_unicode=False)\nfrom myprint import *\nimport myprint\n\nspprint(Eq(x, y))\n\nspprint(solveset(Eq(x**2, 1), x))\nspprint(solveset(Eq(x**2 - 1, 0), x))\nspprint(solveset(x**2 - 1, x))\n\nspprint(solveset(x**2 - x, x))\nspprint(solveset(x - x, x, domain=S.Reals))\nspprint(solveset(sin(x) - 1, x, domain=S.Reals))\n\nspprint(solveset(exp(x), x))     # No solution exists\nspprint(solveset(cos(x) - x, x))  # Not able to find solution\n\n\nspprint(linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z)))\nspprint(linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z)))\n\nM = Matrix(((1, 1, 1, 1), (1, 1, 2, 3)))\nsystem = A, b = M[:, :-1], M[:, -1]\nspprint(linsolve(system, x, y, z))\n\na, b, c, d = symbols('a, b, c, d', real=True)\nspprint(nonlinsolve([a**2 + a, a - b], [a, b]))\nspprint(nonlinsolve([x*y - 1, x - 2], x, y))\nspprint(nonlinsolve([x**2 + 1, y**2 + 1], [x, y]))\n\nfrom sympy import sqrt\nsystem = [x**2 - 2*y**2 -2, x*y - 2]\nvars = [x, y]\nspprint(nonlinsolve(system, vars))\n\nsystem = [exp(x) - sin(y), 1/y - 3]\nspprint(nonlinsolve(system, vars))\n\nspprint(nonlinsolve([x*y, x*y - x], [x, y]))\n\nsystem = [a**2 + a*c, a - b]\nspprint(nonlinsolve(system, [a, b]))\n\nspprint(solve([x**2 - y**2/exp(x)], [x, y], dict=True))\n\nspprint(solve([sin(x + y), cos(x - y)], [x, y]))\n\nspprint(solveset(x**3 - 6*x**2 + 9*x, x))\n\nspprint(roots(x**3 - 6*x**2 + 9*x, x))\n\nspprint(solve(x*exp(x) - 1, x ))\n\n# diff eq\n\nf, g = symbols('f g', cls=Function)\n\nspprint(f(x))\n\nspprint(f(x).diff(x))\n\ndiffeq = Eq(f(x).diff(x, x) - 2*f(x).diff(x) + f(x), sin(x))\n\nspprint(diffeq)\n\nspprint(dsolve(diffeq, f(x)))\n\nspprint(dsolve(f(x).diff(x)*(1 - sin(f(x))) - 1, f(x)))\n", "meta": {"hexsha": "d237846d400cc675f5253174b2905be4800c21cb", "size": 1746, "ext": "py", "lang": "Python", "max_stars_repo_path": "c11.py", "max_stars_repo_name": "bobbydurrett/sympytutorial", "max_stars_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c11.py", "max_issues_repo_name": "bobbydurrett/sympytutorial", "max_issues_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c11.py", "max_forks_repo_name": "bobbydurrett/sympytutorial", "max_forks_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9178082192, "max_line_length": 66, "alphanum_fraction": 0.5767468499, "include": true, "reason": "from sympy", "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288128, "lm_q2_score": 0.930458253083697, "lm_q1q2_score": 0.8907070363229591}}
{"text": "# numerical differentiation\n\nimport numpy as np\n\ndef numerical_diff(f, x):\n    \"\"\"\n    Returns the derivative of f at x.\n    \"\"\"\n    h = 1e-4  # rule of thumb\n    return (f(x + h) - f(x - h)) / (2 * h)  # central difference\n\n\ndef naive_numerical_diff1(f, x):\n    \"\"\"\n    Simple implementation by mathematical definition.\n    \"\"\"\n    h = 1e-50  # '1e-4 for h is too large. It should be inifinitesimal.'\n    return (f(x + h) - f(x - h)) / (2 * h)  # central difference\n\n\ndef naive_numerical_diff2(f, x):\n    \"\"\"\n    Simple implementation by mathematical definition.\n    \"\"\"\n    h = 1e-4  # rule of thumb\n    return (f(x + h) - f(x)) / h  # 'Central diff is tricky.'\n\n\ndef show(f, x, diff, diff_label, expected):\n    \"\"\"\n    f: function to be differentiated\n    x: calculate the derivative at this point\n    diff: function to get the derivative\n    diff_label: name of `diff`\n    expected: mathematically expected value for f'(x)\n    \"\"\"\n\n    actual = diff(f, x)\n    epsilon = 1e-5\n    message = ''\n    if np.linalg.norm(actual - expected) < epsilon:\n        message = 'correct'\n    else:\n        message = 'wrong'\n\n    print('[{0}] diff at {1} = {2} =====> {3}'.format(\n        diff_label, x, actual, message))\n\n\nif __name__ == '__main__':\n    print('f(x) = x')\n    show(lambda x: x, 0, numerical_diff, 'numerical_diff', 1)\n    show(lambda x: x, 0, naive_numerical_diff1, 'naive_numerical_diff1', 1)\n    show(lambda x: x, 0, naive_numerical_diff2, 'naive_numerical_diff2', 1)\n    print()\n    print('f(x) = x ** 2')\n    show(lambda x: x ** 2, 2, numerical_diff, 'numerical_diff', 4)\n    show(lambda x: x ** 2, 2, naive_numerical_diff1, 'naive_numerical_diff1', 4)\n    show(lambda x: x ** 2, 2, naive_numerical_diff2, 'naive_numerical_diff2', 4)\n    print()\n    print('f(x) = x ** 3')\n    show(lambda x: x ** 3, 5, numerical_diff, 'numerical_diff', 75)\n    show(lambda x: x ** 3, 5, naive_numerical_diff1, 'naive_numerical_diff1', 75)\n    show(lambda x: x ** 3, 5, naive_numerical_diff2, 'naive_numerical_diff2', 75)\n", "meta": {"hexsha": "ec7355ad319eb32d6c2deaa282f7ed07507d9727", "size": 2013, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch04/numerical_diff.py", "max_stars_repo_name": "sankaku/deep-learning-from-scratch-py", "max_stars_repo_head_hexsha": "70ec531578f099136744d2c1ec11959b239c3854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch04/numerical_diff.py", "max_issues_repo_name": "sankaku/deep-learning-from-scratch-py", "max_issues_repo_head_hexsha": "70ec531578f099136744d2c1ec11959b239c3854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch04/numerical_diff.py", "max_forks_repo_name": "sankaku/deep-learning-from-scratch-py", "max_forks_repo_head_hexsha": "70ec531578f099136744d2c1ec11959b239c3854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9692307692, "max_line_length": 81, "alphanum_fraction": 0.6154992548, "include": true, "reason": "import numpy", "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.925229962761739, "lm_q1q2_score": 0.8906940101559842}}
{"text": "# compare various approximations of derivatives\n\nimport math\nimport numpy\nimport pylab\n\ndef func(x):\n    \"\"\" the function to be plotted \"\"\"\n\n    f = numpy.sin(x)\n    return f\n\n\ndef fprime(x):\n    \"\"\" the analytic derivative of func(x) \"\"\"\n    \n    fp = numpy.cos(x)\n    return fp\n\n\ndef d1l(dx, fc, i):\n    \"\"\" first-order, left-sided derivative at index i \"\"\"\n    D = (fc[i] - fc[i-1])/dx\n    return D\n\ndef d1r(dx, fc, i):\n    \"\"\" first-order, right-sided derivative at index i \"\"\"\n    D = (fc[i+1] - fc[i])/dx\n    return D\n\ndef d2(dx, fc, i):\n    \"\"\" second-order centered derivative at index i \"\"\"\n    D = (fc[i+1] - fc[i-1])/(2.0*dx)\n    return D\n\ndef d4(dx, fc, i):\n    \"\"\" fourth-order centered derivative at index i \"\"\"\n    D = -fc[i+2] + 8.0*fc[i+1] - 8.0*fc[i-1] + fc[i-2]\n    D = D/(12.0*dx)\n    return D\n\n\ndef line(x, slope, x0, y0):\n    return y0 + slope*(x - x0)\n\n\nxl = 0.0\nxr = math.pi\n\n# fine grid (to show exact function)\nfine = numpy.linspace(xl, xr, 500)\n\n# coarse grid (for differencing)\ncoarse = numpy.linspace(xl, xr, 10)\n\ndx = coarse[1] - coarse[0]\n\n# plot the fine gridded analytic function\nf = func(fine)\npylab.plot(fine, f, color=\"0.5\", lw=2)\n\n\n\n# plot the discrete data\nc = func(coarse)\npylab.scatter(coarse, c)\n\n\n# get the derivative approximations\nDl = d1l(dx, c, 3)\nDr = d1r(dx, c, 3)\nD2 = d2(dx, c, 3)\nD4 = d4(dx, c, 3)\n\nanalytic = fprime(coarse[3])\n\n# function and point values\nx0 = coarse[3]\ny0 = func(x0)\n\nxplot = numpy.linspace(coarse[1], coarse[5], 50)\n\npylab.plot(xplot, line(xplot, Dl, x0, y0), color=\"r\", label=\"left-sided first-order approx\")\npylab.plot(xplot, line(xplot, Dr, x0, y0), color=\"b\", label=\"right-sided first-order approx\")\npylab.plot(xplot, line(xplot, D2, x0, y0), color=\"g\", label=\"centered second-order approx\")\npylab.plot(xplot, line(xplot, D4, x0, y0), color=\"k\", label=\"centered fourth-order approx\")\n#pylab.plot(xplot, line(xplot, analytic, x0, y0), color=\"0.5\", ls=\":\", label=\"analytic\")\n\nprint \"analytic:          \", analytic\nprint \"left-sided O(dx):  \", Dl\nprint \"right-sided O(dx): \", Dr\nprint \"centered O(dx**2): \", D2\nprint \"centered O(dx**4): \", D4\n\nleg = pylab.legend(loc=2,labelspacing=0.1)\nltext = leg.get_texts()\npylab.setp(ltext, fontsize='small')\nleg.draw_frame(0)\n\n# axes run through 0\n# http://matplotlib.org/examples/pylab_examples/spine_placement_demo.html\nax = pylab.gca()\nax.spines['left'].set_position('zero')\nax.spines['right'].set_color('none')\nax.spines['bottom'].set_position('zero')\nax.spines['top'].set_color('none')\nax.spines['left'].set_smart_bounds(True)\nax.spines['bottom'].set_smart_bounds(True)\nax.xaxis.set_ticks_position('bottom')\nax.yaxis.set_ticks_position('left')\n\npylab.xlim(0,2.0)\n\npylab.savefig(\"fprime.png\")\n\n\n", "meta": {"hexsha": "f918412ea03853b38db6da95ac00934eb0fd283c", "size": 2710, "ext": "py", "lang": "Python", "max_stars_repo_path": "others/differentiation_integration/fprime.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "others/differentiation_integration/fprime.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/differentiation_integration/fprime.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 23.1623931624, "max_line_length": 93, "alphanum_fraction": 0.6472324723, "include": true, "reason": "import numpy", "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543365, "lm_q2_score": 0.9241418126663687, "lm_q1q2_score": 0.8906693426615824}}
{"text": "from numpy import pi\nimport numpy as np\n\narray1 = np.array([2, 3, 4])\n\nprint(array1, array1.shape, array1.dtype)\n\n# The type of the array can also be explicitly specified at creation time\n\ncomplexTypeArray = np.array([[1, 2], [3, 4]], dtype=complex)\nprint(complexTypeArray)\n\n# The function `zeros` creates an array full of zeros,\n# the function `ones` creates an array full of ones,\n# and the function `empty` creates an array whose initial content is random\n# and depends on the state of the memory. By default, the `dtype` of the created array is `float64`.\narrayWithZeros = np.zeros((3, 4))\nprint('Array created with zeros funtion', arrayWithZeros)\n\narrayWithOnes = np.ones((2, 3, 4), dtype=np.int16)\nprint('Array created with ones function', arrayWithOnes)\n\nemptyArray = np.empty((2, 3))\nprint('Array created with empty function', emptyArray)\n\n# To create sequences of numbers, NumPy provides a function analogous to range that returns arrays instead of lists.\n\n# Array from 10 to 30 with a range 5\narrayRange = np.arange(10, 30, 5)\nprint('Array with range', arrayRange)\n# it accepts float arguments\narrayRange1 = np.arange(0, 2, 0.3)\nprint('Array with range floating point numbers', arrayRange1)\n\n# When `arange` is used with floating point arguments, it is generally not possible\n# to predict the number of elements obtained, due to the `finite floating point precision`.\n# For this reason, it is usually better to use the function `linspace` that receives as an argument the `number of elements` that we want,\n# instead of the step\n\n\n# 9 numbers from 0 to 2\narrayRangeWithLineSpace = np.linspace(0, 2, 9)\nprint('Arrange with line space for floating numbers', arrayRangeWithLineSpace)\n\n# useful to evaluate function at lots of points\nx = np.linspace(0, 2*pi, 5)\nf = np.sin(x)\n\n# print(x)\n\n# If an array is too large to be printed, NumPy automatically\n# skips the central part of the array and only prints the corners:\n# print(np.arange(10000).reshape(100, 100))\n\n# To `disable` this behaviour and force NumPy to print the entire array, you can change the printing options using set_printoptions.\n# np.set_printoptions(threshold=10)\n\n# Basic Operations\n\n# Arithmetic operators on arrays apply elementwise. A new array is created and filled with the result\na1 = np.array([20, 30, 40, 50])\nb1 = np.arange(4)\narraySub = a1-b1\n\nprint('Actual array a1', a1)\nprint('Actual array b1', b1)\n\nprint('Subtract an array', arraySub)\n\narrayMultiplied = b1**2\nprint('Multiplied array', arrayMultiplied)\n\narraySinOperation = 10*np.sin(a1)\nprint(arraySinOperation)\n\narrayWithBoolean = a1 < 35\nprint(arrayWithBoolean)\n\n# Unlike in many matrix languages, the product operator `*` operates `elementwise` in NumPy arrays.\n# The matrix product can be performed using the `@` operator (in python >=3.5) or the `dot` function or method\nA = np.array([[1, 1], [0, 1]])\nB = np.array([[2, 0], [3, 4]])\n\nprint(A)\nprint(B)\n# elementwise product\nprint('* operator performs elementwise product', A*B)\n# matrix product\nprint('Matrix multiplication using @', A@B)\n# another matrix product\nprint('Matrix multiplication using dot function', A.dot(B))\n\n# Some operations, such as `+=` and `*=`, act in place to `modify an existing array`\n# rather than create a new one.\na2 = np.ones((2, 3), dtype=int)\nb2 = np.random.random((2, 3))\na2 *= 3\nprint('Mutated array using *=', a2)\n\nb2 += a2\nprint('Mutated array using +=', b2)\n\n# b is not automatically converted to integer type\n# a += b\n\n# Following error is throws\n# Traceback (most recent call last):\n#   ...\n# TypeError: Cannot cast ufunc add output from\n# dtype('float64') to dtype('int64') with casting rule 'same_kind'\n\n# When operating with arrays of different types,\n# the type of the resulting array corresponds to the more general or precise one\n# (a behavior known as upcasting).\n\n# Many unary operations, such as computing the\n#  sum of all the elements in the array, are implemented as methods of the ndarray class.\nrandomArray = np.random.random((2, 3))\nprint('\\nSum of the array:\\n', randomArray.sum())\n\nprint('\\nMinimum element in a array:\\n', randomArray.min())\n\nprint('\\nMaximum element in a array:\\n', randomArray.max())\n\n# By default, these operations apply to the array as though it were a list of numbers,\n# regardless of its shape. However,\n# by specifying the `axis` parameter you can apply an operation along the specified axis of an array\n\nb3 = np.arange(12).reshape(3, 4)\n\nprint('\\n Array used to apply sum, min, cumsum:\\n', b3)\n\n# axis-0 means column, axis-1 means - row\n# sum of each column\nprint('\\nSum of elements in axis-0:\\n', b3.sum(axis=0))\n\n# min of each row\nprint('\\nMimimum of each row:\\n', b3.min(axis=1))\n\n# cumulative sum along each row\nprint('\\nCumilative sum along each row:\\n',  b3.cumsum(axis=0))\n\n# Indexing, Slicing and Iterating\n# One-dimensional arrays can be indexed, sliced and iterated over, much like lists and other Python sequences.\na3 = np.arange(10)**3\nprint('\\nArray a3:\\n', a3)\n\nprint('\\nAccessing Array with index:\\n', a3[2])\nprint('\\nArray slicinng:\\n', a3[2:5])\n# equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000\na3[:6:2] = -1000\n\nprint('\\nAfter manipulating a3:\\n', a3)\n\nprint('\\nReversed a3:\\n', a3[::-1])\n\n# Multidimensional arrays can have 'one index per axis'. These indices are given in a tuple separated by commas\n\n\ndef funtion1(x, y):\n    return 10*x+y\n\n\nb4 = np.fromfunction(funtion1, (5, 4), dtype=int)\nprint('\\nArray generated using fromfuntion:\\n', b4)\n\nprint('\\nAccessing multidimensional array with index:\\n', b4[2, 3])\n\n# each row in the second column\nprint('\\nEach row in the second column', b4[0:5, 1])\n# b[ : ,1] # equivalent to the previous example\n\n# each column in the second and third row\nprint('\\nEach column in the second and third row:\\n', b4[1:3, :])\n\n# a 3D array (two stacked 2D arrays)\nc1 = np.array([[[0,  1,  2],\n                [10, 12, 13]],\n               [[100, 101, 102],\n                [110, 112, 113]]])\n\nprint('\\nShape of a 3D array:\\n', c1.shape)\n\n# The dots (...) represent as many colons as needed to produce a complete indexing tuple\n# same as c[1,:,:] or c[1]), first row\nprint('\\nSlicing 3D array using (...):\\n', c1[1, ...])\n\n# same as c[:,:,2]), second column\nprint('\\nSlicing 3D array using (...):\\n', c1[..., 2])\n\n# Iterating over multidimensional arrays is done with respect to the first axis\nprint('\\nIterating over multidimensional arrays is done with respect to the first axis:\\n')\nfor row in b4:\n    print(row)\n\n# However, if one wants to perform an 'operation on each element' in the array,\n# one can use the 'flat' attribute which is an iterator over all the elements of the array\n# print('\\nPrinting the array elements using flat attribute:\\n')\n# for element in b4.flat:\n    # print(element)\n\n\n# Shape manipulation\na4 = np.floor(10*np.random.random((3, 4)))\nprint('\\nArray before manipulation:\\n', a4)\n\n# Note that the following three commands all return a modified array, but do not change the original array\n\n# returns the array, flattened\nprint('\\nFlattened array using ravel():\\n', a4.ravel())\n\nprint('\\nArray with modified shape:\\n', a4.reshape(6, 2))\n\nprint('\\nTransposed array:\\n', a4.T)\n\n# `ndarray.resize()` method modifies the array itself, If a dimension is given as `-1` in a reshaping operation,\n# the other dimensions are automatically calculated\n\n# Stacking together different arrays\na5 = np.floor(10*np.random.random((2, 2)))\n\nprint('\\nArray-1 to stack:\\n', a5)\n\nb5 = np.floor(10*np.random.random((2, 2)))\nprint('\\nArray-2 to stack:\\n', b5)\n\nprint('\\nVertical stack array-1 over array-2:\\n', np.vstack((a5, b5)))\n\nprint('\\nHorizontal stack array-1 before array-2:\\n', np.hstack((a5, b5)))\n", "meta": {"hexsha": "e6f3bbc25f099355a5490e438946e141e1de3938", "size": 7690, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy-sample.py", "max_stars_repo_name": "kpunith8/python_samples", "max_stars_repo_head_hexsha": "f72433c2d98da5b272f557c0aafcc78dc1e307fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy-sample.py", "max_issues_repo_name": "kpunith8/python_samples", "max_issues_repo_head_hexsha": "f72433c2d98da5b272f557c0aafcc78dc1e307fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy-sample.py", "max_forks_repo_name": "kpunith8/python_samples", "max_forks_repo_head_hexsha": "f72433c2d98da5b272f557c0aafcc78dc1e307fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4347826087, "max_line_length": 138, "alphanum_fraction": 0.7122236671, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556619, "lm_q2_score": 0.9425067276593031, "lm_q1q2_score": 0.8906638748459353}}
{"text": "# identity\n# The identity tool returns an identity array. An identity array is a square matrix with all the main diagonal elements as 1\n# and the rest as 0. The default type of elements is float.\n\n# import numpy\n# print numpy.identity(3) #3 is for  dimension 3 X 3\n\n# #Output\n# [[ 1.  0.  0.]\n#  [ 0.  1.  0.]\n#  [ 0.  0.  1.]]\n\n# eye\n# The eye tool returns a 2-D array with 1's as the diagonal and 0's elsewhere. The diagonal can be main, upper or lower depending on the\n# optional parameter k. A positive k is for the upper diagonal, a negative k is for the lower, and a 0 k(default) is for the main diagonal.\n\n# import numpy\n# print numpy.eye(8, 7, k = 1)    # 8 X 7 Dimensional array with first upper diagonal 1.\n\n# #Output\n# [[ 0.  1.  0.  0.  0.  0.  0.]\n#  [ 0.  0.  1.  0.  0.  0.  0.]\n#  [ 0.  0.  0.  1.  0.  0.  0.]\n#  [ 0.  0.  0.  0.  1.  0.  0.]\n#  [ 0.  0.  0.  0.  0.  1.  0.]\n#  [ 0.  0.  0.  0.  0.  0.  1.]\n#  [ 0.  0.  0.  0.  0.  0.  0.]\n#  [ 0.  0.  0.  0.  0.  0.  0.]]\n\n# print numpy.eye(8, 7, k = -2)   # 8 X 7 Dimensional array with second lower diagonal 1.\n\n# Task\n# Your task is to print an array of size N X M with its main diagonal elements as 1's and 0's everywhere else.\n\n# Input Format\n# A single line containing the space separated values of N and M.\n# N denotes the rows.\n# M denotes the columns.\n\n# Output Format\n# Print the desired N X M array.\n\n# Sample Input\n# 3 3\n\n# Sample Output\n\n# [[ 1.  0.  0.]\n#  [ 0.  1.  0.]\n#  [ 0.  0.  1.]]\n\nimport numpy as np\n\nN, M = tuple(map(int, input().split()))\nprint(str(np.eye(N, M)).replace(\"0\", \" 0\").replace(\"1\", \" 1\"))\n", "meta": {"hexsha": "0ff121760a47c2e04ea98fdeea250f38156da560", "size": 1598, "ext": "py", "lang": "Python", "max_stars_repo_path": "NEW_PRAC/HackerRank/Python/NumpEyeAndIdentity.py", "max_stars_repo_name": "side-projects-42/INTERVIEW-PREP-COMPLETE", "max_stars_repo_head_hexsha": "627a3315cee4bbc38a0e81c256f27f928eac2d63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-03-11T00:25:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T00:19:23.000Z", "max_issues_repo_path": "NEW_PRAC/HackerRank/Python/NumpEyeAndIdentity.py", "max_issues_repo_name": "side-projects-42/INTERVIEW-PREP-COMPLETE", "max_issues_repo_head_hexsha": "627a3315cee4bbc38a0e81c256f27f928eac2d63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 160, "max_issues_repo_issues_event_min_datetime": "2021-04-26T19:04:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T20:18:37.000Z", "max_forks_repo_path": "NEW_PRAC/HackerRank/Python/NumpEyeAndIdentity.py", "max_forks_repo_name": "side-projects-42/INTERVIEW-PREP-COMPLETE", "max_forks_repo_head_hexsha": "627a3315cee4bbc38a0e81c256f27f928eac2d63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-04-26T19:43:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T08:36:29.000Z", "avg_line_length": 28.5357142857, "max_line_length": 139, "alphanum_fraction": 0.5888610763, "include": true, "reason": "import numpy", "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.9465966668104392, "lm_q1q2_score": 0.890548442389192}}
{"text": "#!/usr/bin/python\n\n'''\nLearning Machines\nTaught by Patrick Hebron at NYU ITP\n\nActivation function implementations.\n'''\n\nimport numpy as np\n\ndef sigmoid(x):\n\t'''sigmoid function'''\n\treturn 1.0 / ( 1.0 + np.exp( -x ) )\n\ndef dsigmoid(x):\n\t'''sigmoid derivative function'''\n\ty = sigmoid( x )\n\treturn y * ( 1.0 - y )\n\ndef tanh(x):\n\t'''tanh function'''\n\treturn np.sinh( x ) / np.cosh( x )\n\ndef dtanh(x):\n\t'''tanh derivative function'''\n\treturn 1.0 - np.power( tanh( x ), 2.0 )\n", "meta": {"hexsha": "1139c87d1c7b9c333d09cb558aaaaa340406680c", "size": 471, "ext": "py", "lang": "Python", "max_stars_repo_path": "restricted_boltzmann_machine/Activation.py", "max_stars_repo_name": "dodiku/learning_machines_class", "max_stars_repo_head_hexsha": "d261a3647f678784bd15641e39fbd03de59dc144", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "restricted_boltzmann_machine/Activation.py", "max_issues_repo_name": "dodiku/learning_machines_class", "max_issues_repo_head_hexsha": "d261a3647f678784bd15641e39fbd03de59dc144", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "restricted_boltzmann_machine/Activation.py", "max_forks_repo_name": "dodiku/learning_machines_class", "max_forks_repo_head_hexsha": "d261a3647f678784bd15641e39fbd03de59dc144", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-29T12:47:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-29T12:47:32.000Z", "avg_line_length": 16.8214285714, "max_line_length": 40, "alphanum_fraction": 0.6284501062, "include": true, "reason": "import numpy", "num_tokens": 143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9759464499040092, "lm_q2_score": 0.9124361557147438, "lm_q1q2_score": 0.890488826933866}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nRoutines for numerical integration\r\n\r\n@author: Nicolas Guarin-Zapata\r\n\"\"\"\r\nfrom __future__ import division, print_function \r\nimport numpy as np\r\n# Gauss points and weights\r\nfrom scipy.special import roots_legendre\r\n\r\n\r\ndef trapz(fun, x0, x1, n):\r\n    \"\"\"Trapezoidal rule for integration\r\n\r\n    Parameters\r\n    ----------\r\n    fun : callable\r\n        Function to integrate.\r\n    x0 : float\r\n        Initial point for the integration interval.\r\n    x1 : float\r\n        End point for the integration interval.\r\n    n : int\r\n        Number of points to take in the interval.\r\n\r\n    Returns\r\n    -------\r\n    inte : float\r\n        Approximation of the integral\r\n\r\n    \"\"\"\r\n    x = np.linspace(x0, x1, n)\r\n    y = fun(x)\r\n    dx = x[1] - x[0]\r\n    inte = 0.5*dx*(y[0] + y[-1])\r\n    for cont in range(1, n - 1):\r\n        inte = inte + dx*y[cont]\r\n    return inte\r\n\r\n\r\ndef simps(fun, x0, x1, n):\r\n    \"\"\"Simpson's rule for integration\r\n\r\n    Parameters\r\n    ----------\r\n    fun : callable\r\n        Function to integrate.\r\n    x0 : float\r\n        Initial point for the integration interval.\r\n    x1 : float\r\n        End point for the integration interval.\r\n    n : int\r\n        Number of points to take in the interval.\r\n\r\n    Returns\r\n    -------\r\n    inte : float\r\n        Approximation of the integral\r\n\r\n    \"\"\"\r\n    # We need an odd number of points\r\n    # in case of having an even one\r\n    # we add one point more\r\n    if n%2 == 0:\r\n        n = n + 1\r\n    x = np.linspace(x0, x1, n)\r\n    y = fun(x)\r\n    dx = x[1] - x[0]\r\n    inte = 0\r\n    for cont in range(1, n//2 + 1):\r\n        inte = inte + dx/3 * (y[2*cont - 2] + 4*y[2*cont - 1] + y[2*cont])\r\n    return inte\r\n\r\n\r\ndef gauss1d(fun, x0, x1, n):\r\n    \"\"\"Gauss quadrature in 1D\r\n\r\n    Parameters\r\n    ----------\r\n    fun : callable\r\n        Function to integrate.\r\n    x0 : float\r\n        Initial point for the integration interval.\r\n    x1 : float\r\n        End point for the integration interval.\r\n    n : int\r\n        Number of points to take in the interval.\r\n\r\n    Returns\r\n    -------\r\n    inte : float\r\n        Approximation of the integral\r\n\r\n    \"\"\"\r\n    xi, wi = roots_legendre(n)\r\n    inte = 0\r\n    h = 0.5 * (x1 - x0)\r\n    xm = 0.5 * (x0 + x1)\r\n    for cont in range(n):\r\n        inte = inte + h * fun(h * xi[cont] + xm) * wi[cont]\r\n    return inte\r\n\r\n\r\ndef gauss2d(fun, x0, x1, y0, y1, nx, ny):\r\n    \"\"\"Gauss quadrature for a rectangle in 2D\r\n\r\n    Parameters\r\n    ----------\r\n    fun : callable\r\n        Function to integrate.\r\n    x0 : float\r\n        Initial point for the integration interval in x.\r\n    x1 : float\r\n        End point for the integration interval in x.\r\n    y0 : float\r\n        Initial point for the integration interval in y.\r\n    y1 : float\r\n        End point for the integration interval in y.\r\n    nx : int\r\n        Number of points to take in the interval in x.\r\n    ny : int\r\n        Number of points to take in the interval in y.\r\n\r\n    Returns\r\n    -------\r\n    inte : float\r\n        Approximation of the integral\r\n\r\n    \"\"\"\r\n    xi, wi = roots_legendre(nx)\r\n    yj, wj = roots_legendre(ny)\r\n    inte = 0\r\n    hx = 0.5 * (x1 - x0)\r\n    hy = 0.5 * (y1 - y0)\r\n    xm = 0.5 * (x0 + x1)\r\n    ym = 0.5 * (y0 + y1)\r\n    for cont_x in range(nx):\r\n        for cont_y in range(ny):\r\n            f = fun(hx * xi[cont_x] + xm, hy * yj[cont_y] + ym)\r\n            inte = inte + hx* hy * f * wi[cont_x] * wj[cont_y]\r\n    return inte\r\n", "meta": {"hexsha": "925e06bfb51b101727fe40cc2138547d0f0feeff", "size": 3439, "ext": "py", "lang": "Python", "max_stars_repo_path": "codigo/metodos_numericos/integracion/integrate.py", "max_stars_repo_name": "AppliedMechanics-EAFIT/Mod_Temporal", "max_stars_repo_head_hexsha": "6a0506d906ed42b143b773777e8dc0da5af763eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-02-20T18:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-19T22:44:44.000Z", "max_issues_repo_path": "codigo/metodos_numericos/integracion/integrate.py", "max_issues_repo_name": "AppliedMechanics-EAFIT/Mod_Temporal", "max_issues_repo_head_hexsha": "6a0506d906ed42b143b773777e8dc0da5af763eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-04-15T00:22:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-04T17:03:54.000Z", "max_forks_repo_path": "codigo/metodos_numericos/integracion/integrate.py", "max_forks_repo_name": "AppliedMechanics-EAFIT/Mod_Temporal", "max_forks_repo_head_hexsha": "6a0506d906ed42b143b773777e8dc0da5af763eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-14T18:17:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-27T06:37:05.000Z", "avg_line_length": 24.048951049, "max_line_length": 75, "alphanum_fraction": 0.5324222158, "include": true, "reason": "import numpy,from scipy", "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542817548989, "lm_q2_score": 0.9284087970889806, "lm_q1q2_score": 0.8904872729468108}}
{"text": "#1. Write a NumPy program to sort a given array of shape 2 along the first axis, last axis and on flattened array.\nimport numpy as np\na = np.array([[10,40],[30,20]])\nprint(\"Original array:\")\nprint(a)\nprint(\"Sort the array along the first axis:\")\nprint(np.sort(a, axis=0))\nprint(\"Sort the array along the last axis:\")\nprint(np.sort(a))\nprint(\"Sort the flattened array:\")\nprint(np.sort(a, axis=None))\n#2. Write a NumPy program to create a structured array from given student name, height, class and their data types. Now sort the array on height.\nimport numpy as np\ndata_type = [('name', 'S15'), ('class', int), ('height', float)]\nstudents_details = [('James', 5, 48.5), ('Nail', 6, 52.5),('Paul', 5, 42.10), ('Pit', 5, 40.11)]\n# create a structured array\nstudents = np.array(students_details, dtype=data_type)\nprint(\"Original array:\")\nprint(students)\nprint(\"Sort by height\")\nprint(np.sort(students, order='height'))\n#3. Write a NumPy program to create a structured array from given student name, height, class and their data types. Now sort by class, then height if class are equal\nimport numpy as np\ndata_type = [('name', 'S15'), ('class', int), ('height', float)]\nstudents_details = [('James', 5, 48.5), ('Nail', 6, 52.5),('Paul', 5, 42.10), ('Pit', 5, 40.11)]\n# create a structured array\nstudents = np.array(students_details, dtype=data_type)\nprint(\"Original array:\")\nprint(students)\nprint(\"Sort by class, then height if class are equal:\")\nprint(np.sort(students, order=['class', 'height']))\n#4. Write a NumPy program to sort the student id with increasing height of the students from given students id and height. Print the integer indices that describes the sort order by multiple columns and the sorted data.\nimport numpy as np\nstudent_id = np.array([1023, 5202, 6230, 1671, 1682, 5241, 4532])\nstudent_height = np.array([40., 42., 45., 41., 38., 40., 42.0])\n#Sort by studen_id then by student_height\nindices = np.lexsort((student_id, student_height))\nprint(\"Sorted indices:\")\nprint(indices)\nprint(\"Sorted data:\")\nfor n in indices:\n  print(student_id[n], student_height[n])\n#5. Write a NumPy program to get the indices of the sorted elements of a given array.\nimport numpy as np\nstudent_id = np.array([1023, 5202, 6230, 1671, 1682, 5241, 4532])\nprint(\"Original array:\")\nprint(student_id)\ni = np.argsort(student_id)\nprint(\"Indices of the sorted elements of a given array:\")\nprint(i)\n#6. Write a NumPy program to sort a given complex array using the real part first, then the imaginary part\nimport numpy as np\ncomplex_num = [1 + 2j, 3 - 1j, 3 - 2j, 4 - 3j, 3 + 5j]\nprint(\"Original array:\")\nprint(complex_num)\nprint(\"\\nSorted a given complex array using the real part first, then the imaginary part.\")\nprint(np.sort_complex(complex_num))\n#7. Write a NumPy program to partition a given array in a specified position and move all the smaller elements values to the left of the partition, and the remaining values to the right, in arbitrary order (based on random choice).\n\nimport numpy as np\nnums = np.array([70, 50, 20, 30, -11, 60, 50, 40])\nprint(\"Original array:\")\nprint(nums)\nprint(\"\\nAfter partitioning on 4 the position:\")\nprint(np.partition(nums, 4))\n#8. Write a NumPy program to sort the specified number of elements from beginning of a given array.\nimport numpy as np\nnums =  np.random.rand(10)\nprint(\"Original array:\")\nprint(nums)\nprint(\"\\nSorted first 5 elements:\")\nprint(nums[np.argpartition(nums,range(5))])\n", "meta": {"hexsha": "d6c1f527daf650bfe1fe5266b72ee44e606d7fdf", "size": 3420, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumPy: Sorting and Searching Exercises & solutions.py", "max_stars_repo_name": "AmalChandru/numpy-recipes", "max_stars_repo_head_hexsha": "e80b7695e0d6fd696682027e64220c63e90c8825", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-14T14:25:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T03:14:20.000Z", "max_issues_repo_path": "NumPy: Sorting and Searching Exercises & solutions.py", "max_issues_repo_name": "AmalChandru/numpy-recipes", "max_issues_repo_head_hexsha": "e80b7695e0d6fd696682027e64220c63e90c8825", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumPy: Sorting and Searching Exercises & solutions.py", "max_forks_repo_name": "AmalChandru/numpy-recipes", "max_forks_repo_head_hexsha": "e80b7695e0d6fd696682027e64220c63e90c8825", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.8493150685, "max_line_length": 231, "alphanum_fraction": 0.7263157895, "include": true, "reason": "import numpy", "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666345, "lm_q2_score": 0.939913352771458, "lm_q1q2_score": 0.8904560945146995}}
{"text": "\n# coding: utf-8\n\n# In[2]:\n\n# numpy and scipy are pretty awesome python libraries for scientific computing\n# Let's quickly do a round up of what these 2 libraries can help us do\n\n# Python lists are amazing, but many times you'll want to put your data into grids\n# and perform mathematical operations with them. A numpy array is a way to put your data\n# in a matrix (grid). \n# Numpy then has a number of cool functions to manipulate this data\nimport numpy as np\nimport scipy\n# An array can have any number of dimensions \n# A 1-d array is like a list (The number of dimensions is also known as rank)\narray1d=np.array([0,2,4,6,8])\nprint(array1d)\n\n\n# In[3]:\n\n# A 2-d array is like a 2-d grid. Create it using a list of lists\narray2d=np.array([[1,2,3],[4,5,6]])\n\nprint(array2d)\n\n\n# In[4]:\n\nprint(type(array1d))\n\n\n# In[5]:\n\n# shape is a tuple which contains the size of the array ie (the number of rows, the number of \n# columns)\nprint(array1d.shape)\n\n\n# In[6]:\n\nprint(array2d.shape)\n\n\n# In[7]:\n\n# You can index elements of an array pretty much like you do with lists\n# Like with lists, the indexing starts from 0\nprint(array1d[0])\n\n# With a 2d array the syntax is slightly different. If you had a list of lists, and you \n# wanted the element in the ith row and the jth column you would index it by saying \n# listOfLists[i][j]\n# In a numpy array, you can index the element in the ith row and jth column as \n# arrayNumpy[i,j]\n\nprint(array2d[1,2])\n# this will print the element in the second row and third column of array2d (indexing starts from\n# 0)\n\n\n# In[8]:\n\n# Just like with lists, you can use : to specify \"from the beginning\" or \"till the end\"\nprint(array1d[1:])\n\n\n# In[9]:\n\nprint(array2d[1,:1]) # This will print the elements in the second row , from the first element in \n# the second row, till the second element (not including the second element)\n\n\n# In[10]:\n\nprint(array2d[1,1:]) # The elements in the second row, from the second element onwards\n\n\n# In[11]:\n\n# In all the cases above, the result of the indexing is a numpy array which is a subset\n# of the original array \nsubarray2d=array2d[1,1:]\nprint(type(subarray2d))\n\n\n# In[12]:\n\n# There are other cool ways to index numpy arrays \nnew2dArray=np.array([[1,2,4,5,9],[3,4,6,6,10],[15,3,2,14,7]])\n\n# Let's say you want the elements with indices [1,2], [0,4], [2,3]\n\nnewSubArray=new2dArray[[1,0,2],[2,4,3]] # Arrays of integers to specify the indices\nprint(newSubArray)\n\n\n# In[13]:\n\n# You can also use boolean indexing, ie subset the array to all the values which satisfy\n# a certain condition \nnew2dArray[new2dArray>10]\n\n\n# In[14]:\n\n# new2dArray>10 will return an array with the same size and shape as the original array \n# Each element of that array will be a boolean which says whether the corresponding element \n# of the original array satisfies the given condition \nnew2dArray>10\n\n\n# In[15]:\n\n# You can create some standard kinds of arrays using built-in functions in numpy. \n# Ex: Arrays with all 0s, constant arrays, random numbers etc\n\narrayOfZeros=np.zeros((2,2),dtype='int64') # Creates an array with all zeros. dtype is an optional\n# argument, its default value is float\narrayOfOnes=np.ones((1,2)) # note how the size of the array is passed in as a tuple\narraywithConstantValue = np.full(new2dArray.shape,7) # Creates an array with the same\n# size and shape as new2dArray, fills it with value 7 for all elements\n\nidentityMatrix = np.eye(2)\n# Creates a 2x2 identity matrix ie a square grid of numbers with 2 rows and 2 columns\n# All the diagonal elements will be 1s and all the non-diagonal elements will be 0s\n\nprint(arrayOfZeros,\"\\n\",arrayOfOnes,\"\\n\",arraywithConstantValue,\"\\n\",identityMatrix)\n\n\n# In[16]:\n\n# YOu can also fill an array with random numbers \narrayOfRandomNumbers = np.random.random((2,2)) \n# This will create a 2x2 array with random numbers between the values 0 and 1. \n# To generate random numbers with a specific distribution, check out the \n# numpy documentation\nprint(arrayOfRandomNumbers)\n\n\n# In[17]:\n\n# You can change the size and shape of your array \ntransposeArray=np.transpose(new2dArray)\n\nprint(new2dArray.shape, transposeArray.shape)\n\n\n# In[18]:\n\n# You can reshape array into any shape as long as the total number of elements remains \n# the same\nreshapedArray=np.reshape(new2dArray,[1,15])\nprint(reshapedArray)\n\n\n# In[19]:\n\nreshapedArray=np.reshape(new2dArray,[15,1])\nprint(reshapedArray)\n\n\n# In[20]:\n\n# Normal mathematical operators like +,-,/,* can be used to perform element wise \n# operations. Both arrays have to be of the same dimension \n\narray1=np.array([[1,2,3],[4,5,6]])\narray2=np.array([[7,8,9],[3,2,1]])\n\n\n# In[21]:\n\narray1+array2\n\n\n# In[22]:\n\n# instead of the math operators you can use functions equivalent to the operators\n# +,-,/,* are equivalent to add, subtract, divide,multiply\nnp.subtract(array1,array2)\n\n\n# In[23]:\n\n# Broadcasting is a way in which you can add matrices or arrays of different dimensions\narray3=[[1,4,7]]\n\narray1+array3 # This will add array3 to each row of array1\n\n\n# In[24]:\n\n# The rule of thumb for broadcasting is that the arrays need to be able to align \n# along at least 1 dimension. For more details check the documentation\n\n\n# In[25]:\n\n# One important operation you'll need is to perform an inner product of 2 arrays \n# or multiply 2 matrices. Matrix multiplication is equivalent to taking inner products\n# of every row of the first matrix with every column of the second matrix \n# To multiply 2 matrices, you will need the number of columns of the left array\n# to be equal to the number of rows of the right array \n\nnp.dot(array1,array2)# wont work because we have both 2x3 arrays\n\n\n# In[26]:\n\nnp.dot(array1,array2.T) # .T is shorthand for using np.transpose()\n\n\n# In[27]:\n\n# You can add or multiply all the elements along 1 dimension (or axis), This is \n# like compressing the array along that axis\nnp.sum(array1,axis=0)\n\n\n# In[28]:\n\nnp.sum(array2,axis=1)\n\n\n# In[29]:\n\n# stack arrays together using vstack or hstack. These functions take in a list/tuple/\n# array of arrays and then stack them vertically or horizontally to make a new array\nnp.vstack((array1,array2))\n\n\n# In[30]:\n\nnp.hstack((array2,array1))\n\n\n# In[31]:\n\n# Scipy has many modules that help us compute mathematical functions \n# one example is the spatial module, given 2 points represented by \n# np arrays, scipy can help you find the distance between those points\n# The distance metric could be any one of a number of options ex: euclidean\n# cosine, correlation, hamming etc \n# pdist will compute pairwise distances between the rows in a numpy array \n\nfrom scipy.spatial.distance import correlation, cosine, pdist, squareform \n\narray1=np.array([0,1,0])\narray2=np.array([1,0,0])\n\ncorrelation(array1,array2)\n\n\n# In[33]:\n\nallPoints=np.vstack([array1,array2])\nd=squareform(pdist(allPoints, 'euclidean'))\n# The distance metric can be changed to cosine, correlation or any other distance\n# the complete list of options is available in scipy documentation \n# This will compute the pairwise distance between all rows of allPoints\n# d will be a square matrix with d[i,j] being the Euclidean distance between\n# allPoints[i,:] and allPoints[j,:]\nprint(d)\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n", "meta": {"hexsha": "fa0cbd572d994c365a4d1382fd8a1553fde681ce", "size": 7239, "ext": "py", "lang": "Python", "max_stars_repo_path": "Section 14/Numpy-Python3.py", "max_stars_repo_name": "PacktPublishing/From-0-to-1-Machine-Learning-NLP-Python-Cut-to-the-Chase", "max_stars_repo_head_hexsha": "68d459dd6a1fc50c0edb16d56f130c1d6018a1da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-05-06T17:15:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T16:40:01.000Z", "max_issues_repo_path": "Section 14/Numpy-Python3.py", "max_issues_repo_name": "PacktPublishing/From-0-to-1-Machine-Learning-NLP-Python-Cut-to-the-Chase", "max_issues_repo_head_hexsha": "68d459dd6a1fc50c0edb16d56f130c1d6018a1da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Section 14/Numpy-Python3.py", "max_forks_repo_name": "PacktPublishing/From-0-to-1-Machine-Learning-NLP-Python-Cut-to-the-Chase", "max_forks_repo_head_hexsha": "68d459dd6a1fc50c0edb16d56f130c1d6018a1da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-06-18T10:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T02:31:54.000Z", "avg_line_length": 23.9701986755, "max_line_length": 98, "alphanum_fraction": 0.728415527, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542284, "lm_q2_score": 0.948154531702086, "lm_q1q2_score": 0.8903406424974015}}
{"text": "from __future__ import division\nfrom scipy import*\nfrom scipy import linalg\nimport pylab\nimport sys\nsys.path.append(\"/home/ludger/lib/python2.6/site-packages/\")\nimport statistics\n\n#Task 1: Evaluate the density of a bivariate distribution at a single point\ndef density(x,mu,sigma):\n        inv_sigma=linalg.inv(sigma)\n        x_minus_mu=x-mu\n        return exp(-0.5*dot(dot(transpose(x_minus_mu),inv_sigma),x_minus_mu))/(2*pi*sqrt(\nlinalg.det(sigma) ) )\n\nmu=array([0,0])\nsigma=array([[4,1],[1,4]])\n\n#Task 2: Metropolis Hastings\n\n#Set the standard deviation of the proposal\nsigma_prop=2.5\n#Set the desired sample size\nn=1000\n#Set the starting values\nx=array([0,0])\naccepted_n=0\nf=density(x,mu,sigma)\nX1=[x[0]]\nX2=[x[1]]\n\nfor i in xrange(1,n):\n        x_0=x[0]+random.normal(0,sigma_prop)\n        x_1=x[1]+random.normal(0,sigma_prop)\n        new_x=array([x_0,x_1])\n        new_f=density(new_x,mu,sigma)\n        if (random.random()<(new_f/f)):\n                accepted_n+=1\n                x=new_x\n                f=new_f\n        X1.append(x[0])\n        X2.append(x[1])\n\n#Proportion of accepted values\nprint \"The proportion of accepted values is\", accepted_n/n\n\n#Task 3: Diagnostics\n\n#Sample plots for both values\npylab.figure(0)\npylab.plot(X1,'b')\npylab.title(\"Sample path of X_1\")\npylab.figure(1)\npylab.plot(X2,'r')\npylab.title(\"Sample path of X_2\")\n\n#Cumulative averages\nX1_cummean = cumsum( X1 ) / ( 1 + arange( len( X1 )))\nX2_cummean = cumsum( X2 ) / ( 1 + arange( len( X1 )))\npylab.figure( 2 )\npylab.plot( X1_cummean,\"b\" )\npylab.title(\"Empirical mean of X_1\")\n\npylab.figure( 3 )\npylab.plot( X2_cummean,\"r\" )\npylab.title(\"Empirical mean of X_2\")\npylab.show()        \n\n#Autocorrelation\nX1_sd = sqrt( var( X1 ) )\nX2_sd = sqrt( var( X2 ) )\nX1_autocorr = statistics.correlation( X1[1: ], X1[:-1])\nX2_autocorr = statistics.correlation( X2[1: ], X2[:-1])\nprint \"The autocorrelation of X_1 is\", X1_autocorr\nprint \"The autocorrelation of X_2 is\", X2_autocorr\n\n#Effective sample size\nX1_ess = n * ( 1 - X1_autocorr ) / ( 1 + X1_autocorr )\nX2_ess = n * ( 1 - X2_autocorr ) / ( 1 + X2_autocorr )\nprint \"The effective sample size of X_1 is\", X1_ess\nprint \"The effective sample size of X_2 is\", X2_ess\n\n#Task 4: Repeat with sigma_prop = 0.1, sigma_prop = 10\n\n#Task 5: Repeat with sigma = array([[4,2.8],[2.8,4]])\n", "meta": {"hexsha": "22e7fabdc60f922083959a8d602e5547104e3f06", "size": 2301, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/MH/reference/implementation_code_ref/cp5sol.py", "max_stars_repo_name": "lzhbrian/MCMC", "max_stars_repo_head_hexsha": "0dd3aadd1ed2833aff76bd7af4b014282739984b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-09-10T04:42:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-21T16:07:29.000Z", "max_issues_repo_path": "src/MH/reference/implementation_code_ref/cp5sol.py", "max_issues_repo_name": "lzhbrian/MCMC", "max_issues_repo_head_hexsha": "0dd3aadd1ed2833aff76bd7af4b014282739984b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MH/reference/implementation_code_ref/cp5sol.py", "max_forks_repo_name": "lzhbrian/MCMC", "max_forks_repo_head_hexsha": "0dd3aadd1ed2833aff76bd7af4b014282739984b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-03-03T17:34:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-24T10:54:53.000Z", "avg_line_length": 26.7558139535, "max_line_length": 89, "alphanum_fraction": 0.6714471969, "include": true, "reason": "from scipy", "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828602, "lm_q2_score": 0.9294404101647158, "lm_q1q2_score": 0.89032237395118}}
{"text": "# Generic import\nimport numpy as np\n\n\ndef central_difference(f, x, *args):\n    \"\"\"\n    Description:\n    It returns the numerical derivative of input function \"f\"\n    at the point \"x\", i.e. df(x)/dx, by using the central\n    difference formula.\n\n    Args:\n        - f: function handle.\n        - x: point to evaluate the derivative.\n        - *args: additional input parameters of the function.\n\n    Output:\n        - df(x)/dx\n    \"\"\"\n    # The optimal step when using the CDF should scale\n    # with respect to the cubic root of \"eps\".\n    cbrt_eps = (np.finfo(float).eps) ** (1.0 / 3.0)\n\n    # Number of input parameters.\n    D = x.size\n\n    # Preallocate for efficiency.\n    df = np.zeros(D)\n\n    # Auxilliary vector.\n    e = np.zeros(D)\n\n    # Check all 'D' directions (coordinates of x).\n    for i in range(D):\n        # Switch ON i-th direction.\n        e[i] = 1.0\n\n        # Step size (for the i-th variable).\n        h = cbrt_eps if (x[i] == 0.0) else x[i] * cbrt_eps\n\n        # Move a small way in the i-th direction of x+h.\n        fplus = f(x + h * e, *args)\n\n        # Move a small way in the i-th direction of x-h.\n        fminus = f(x - h * e, *args)\n\n        # Central difference formula for approximation.\n        df[i] = (fplus - fminus) / (2.0 * h)\n\n        # Switch OFF i-th direction.\n        e[i] = 0.0\n    # _end_if_\n\n    return df\n\n\n# _end_def_\n\ndef forward_difference(f, x, *args):\n    \"\"\"\n    Description:\n    It returns the numerical derivative of input function \"f\"\n    at the point \"x\", i.e. df(x)/dx, by using the forward\n    difference formula.\n\n    Args:\n        - f: function handle.\n        - x: point to evaluate the derivative.\n        - *args: additional input parameters of the function.\n\n    Output:\n        - df(x)/dx\n    \"\"\"\n    # Step size.\n    h = 1.0E-6\n\n    # Number of input parameters.\n    D = x.size\n\n    # Preallocate for efficiency.\n    df = np.zeros(D)\n\n    # Auxilliary vector.\n    e = np.zeros(D)\n\n    # Compute the f(x) only once.\n    fx = f(x, *args)\n\n    # Check all 'D' directions (coordinates of x).\n    for i in range(D):\n        # Switch ON i-th direction.\n        e[i] = 1.0\n\n        # Move a small way in the i-th direction of x+h.\n        fplus = f(x + h * e, *args)\n\n        # Central difference formula for approximation.\n        df[i] = (fplus - fx) / h\n\n        # Switch OFF i-th direction.\n        e[i] = 0.0\n    # _end_if_\n\n    return df\n\n\n# _end_def_\n\ndef backward_difference(f, x, *args):\n    \"\"\"\n    Description:\n    It returns the numerical derivative of input function \"f\"\n    at the point \"x\", i.e. df(x)/dx, by using the backward\n    difference formula.\n\n    Args:\n        - f: function handle.\n        - x: point to evaluate the derivative.\n        - *args: additional input parameters of the function.\n\n    Output:\n        - df(x)/dx\n    \"\"\"\n    # Step size.\n    h = 1.0E-6\n\n    # Number of input parameters.\n    D = x.size\n\n    # Preallocate for efficiency.\n    df = np.zeros(D)\n\n    # Auxilliary vector.\n    e = np.zeros(D)\n\n    # Compute the f(x) only once.\n    fx = f(x, *args)\n\n    # Check all 'D' directions (coordinates of x).\n    for i in range(D):\n        # Switch ON i-th direction.\n        e[i] = 1.0\n\n        # Move a small way in the i-th direction of x+h.\n        fminus = f(x - h * e, *args)\n\n        # Central difference formula for approximation.\n        df[i] = (fx - fminus) / h\n\n        # Switch OFF i-th direction.\n        e[i] = 0.0\n    # _end_if_\n\n    return df\n\n\n# _end_def_\n\ndef numerical_derivative(f, x, method='cdf', *args):\n    \"\"\"\n    Description:\n    It returns the numerical derivative of input function \"f\"\n    at the point \"x\", i.e. df(x)/dx, by calling the relevant\n    numerical method to compute the derivative.\n\n    Args:\n        - f: function handle.\n        - x: point to evaluate the derivative.\n        - method: numerical integration (default = 'cdf')\n        - args: additional input parameters of the function.\n\n    Raises:\n        - ValueError: If the input method is not recognized.\n    \"\"\"\n\n    # Call the right method or throw an error.\n    if method == \"cdf\":\n        return central_difference(f, x, *args)\n    elif method == \"fwd\":\n        return forward_difference(f, x, *args)\n    elif method == \"bwd\":\n        return backward_difference(f, x, *args)\n    else:\n        raise ValueError(\" Unknown method of differentiation.\")\n\n\n# _end_def_\n\ndef flat_list(x=None):\n    \"\"\"\n    Description:\n    It returns a list that contains all the elements form the input list of lists.\n    It should work for any number of levels.\n\n    Example:\n        >>> x = flat_list([1, 'k', [], 3, [4, 5, 6], [[7, 8]], [[[9]]]])\n        >>> x\n        >>> [1, 'k', 3, 4, 5, 6, 7, 8, 9]\n\n    Args:\n        - x (list): List of lists of objects.\n\n    Raises:\n        - TypeError: If the input is not a list object.\n    \"\"\"\n\n    # Check for empty input.\n    if x is None:\n        return []\n    # _end_if_\n\n    # Input 'x' should be a list.\n    if not isinstance(x, list):\n        raise TypeError(\" Input should be a list.\")\n    # _end_if_\n\n    # Define the return list.\n    flat_x = []\n\n    # Go through all the list elements.\n    for item_x in x:\n        # Check for embedded lists.\n        if isinstance(item_x, list):\n            # Check for empty entries.\n            if not item_x:\n                continue\n            # _end_if_\n\n            # Note the recursive call in \"flat_list\".\n            for ix in flat_list(item_x):\n                flat_x.append(ix)\n            # _end_for_\n        else:\n            # If the item is not a list.\n            flat_x.append(item_x)\n        # _end_if_\n    # _end_for_\n\n    # Return the flatten list.\n    return flat_x\n\n\n# _end_def_\n\ndef split_dataset_at_feature(data, axis=0):\n    \"\"\"\n    Description:\n    Splits the input data set at the requested feature, given by the index number 'idx'.\n\n    Args:\n        - data: (list of lists) input data-set.\n        - axis: feature index to split the data-set.\n\n    Note:\n        Default index is '0' (i.e. the first feature of the data set).\n\n    Raises:\n        ValueError if the index is out of bounds.\n    \"\"\"\n\n    # Data must be a list.\n    if not isinstance(data, list):\n        raise TypeError(\" Input data should be a list.\")\n    # _end_if_\n\n    # Index must be integer.\n    if not isinstance(axis, int):\n        raise TypeError(\" Axis value should be integer.\")\n    # _end_if_\n\n    # Get the number of features.\n    # Note:  The last column is assumed to contain the class label,\n    # therefore it should never be included for splitting the data.\n    n_features = len(data[0]) - 1\n\n    # If there is only one feature, there is nothing to split.\n    if n_features == 1:\n        return data\n    # _end_if_\n\n    # Sanity check.\n    if axis < 0 or axis >= n_features:\n        raise ValueError(\" Feature index is out of bounds.\")\n    # _end_if_\n\n    # Every entry in the dictionary will contain a sub-set of the\n    # original data-set, split at a value of the feature.\n    partition_data = {}\n\n    # Split the data-set into sub-sets.\n    for record in data:\n        # First part of the record.\n        part_1 = record[:axis]\n\n        # Second part of the record.\n        part_2 = record[axis + 1:]\n\n        # Combine the two parts in one record.\n        part_1.extend(part_2)\n\n        # Construct a key (string) entry.\n        key = \"chID_{0}:{1}\".format(idx, record[axis])\n\n        # Check if this key has been seen.\n        if key not in node_dict.keys():\n            # If not then add it to the dictionary.\n            partition_data[key] = []\n        # _end_if_\n\n        # Add the record on the dictionary.\n        partition_data[key].append(part_1)\n    # _end_for_\n\n    return partition_data\n\n# _end_def_\n", "meta": {"hexsha": "b57ac17e90dca639380cf7a60eab19fb9b43e898", "size": 7701, "ext": "py", "lang": "Python", "max_stars_repo_path": "Utilities/ml_util.py", "max_stars_repo_name": "vrettasm/MLforFun", "max_stars_repo_head_hexsha": "e8d58070d70f17c339a10a3d0fb655cb8e4b1c51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Utilities/ml_util.py", "max_issues_repo_name": "vrettasm/MLforFun", "max_issues_repo_head_hexsha": "e8d58070d70f17c339a10a3d0fb655cb8e4b1c51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Utilities/ml_util.py", "max_forks_repo_name": "vrettasm/MLforFun", "max_forks_repo_head_hexsha": "e8d58070d70f17c339a10a3d0fb655cb8e4b1c51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2933753943, "max_line_length": 88, "alphanum_fraction": 0.5752499675, "include": true, "reason": "import numpy", "num_tokens": 2019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843811, "lm_q2_score": 0.9294403999037784, "lm_q1q2_score": 0.8903223652388441}}
{"text": "import numpy as np\n\nA = np.array([[n+m*10 for n in range(5)] for m in range(5)])\nnp.dot(A, A)\n\"\"\"\narray([[ 300,  310,  320,  330,  340],\n       [1300, 1360, 1420, 1480, 1540],\n       [2300, 2410, 2520, 2630, 2740],\n       [3300, 3460, 3620, 3780, 3940],\n       [4300, 4510, 4720, 4930, 5140]])\n\"\"\"\n\nv1 = np.arange(0, 5)\nnp.dot(A, v1)   # array([ 30, 130, 230, 330, 430])\nnp.dot(v1, v1)  # 30\n\n# También podemos hacer casting al tipo matrix. Eso cambia el comportamiento de los operadores +, -, * para usar álgebra matricial\nM = np.matrix(A)\nv = np.matrix(v1).T # vector columna\nv\n\"\"\"\nmatrix([[0],\n        [1],\n        [2],\n        [3],\n        [4]])\n\"\"\"\nM * M\n\"\"\"matrix([[ 300,  310,  320,  330,  340],\n        [1300, 1360, 1420, 1480, 1540],\n        [2300, 2410, 2520, 2630, 2740],\n        [3300, 3460, 3620, 3780, 3940],\n        [4300, 4510, 4720, 4930, 5140]])\n\"\"\"\n\nM * v\n\"\"\"\nmatrix([[ 30],\n        [130],\n        [230],\n        [330],\n        [430]])\n\"\"\"\n\nv.T * v # matrix([[30]])\n\nv + M*v\n\"\"\"\nmatrix([[ 30],\n    [131],\n    [232],\n    [333],\n    [434]])\n\"\"\"\n\n# Si intentamos operar entre elementos con dimensiones no compatibles, nos da error\nv = np.matrix([1,2,3,4,5,6]).T\nv\n\"\"\"\nmatrix([[1],\n        [2],\n        [3],\n        [4],\n        [5],\n        [6]])\n\n\"\"\"\n\nM * v   # Error: ValueError: shapes (5,5) and (6,1) not aligned: 5 (dim 1) != 6 (dim 0)", "meta": {"hexsha": "21c5a83e2334cff2efb4837485d2d005dbcb7082", "size": 1356, "ext": "py", "lang": "Python", "max_stars_repo_path": "sources/t10/t10ej18.py", "max_stars_repo_name": "workready/pythonbasic", "max_stars_repo_head_hexsha": "59bd82caf99244f5e711124e1f6f4dec8de22141", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sources/t10/t10ej18.py", "max_issues_repo_name": "workready/pythonbasic", "max_issues_repo_head_hexsha": "59bd82caf99244f5e711124e1f6f4dec8de22141", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sources/t10/t10ej18.py", "max_forks_repo_name": "workready/pythonbasic", "max_forks_repo_head_hexsha": "59bd82caf99244f5e711124e1f6f4dec8de22141", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.652173913, "max_line_length": 130, "alphanum_fraction": 0.4896755162, "include": true, "reason": "import numpy", "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242018339897, "lm_q2_score": 0.9184802456988518, "lm_q1q2_score": 0.8903051310623262}}
{"text": "    #!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time     : 2018/10/16 19:48\n# @Author   : Iydon\n# @File     : course4.4.py\n\n\nimport numpy as np\n\n\n# Composite Numerical Integration\ndef trapezoidal_rule(xs:list, fxs:list) -> float:\n    \"\"\"\n    Trapezoidal Rule:\n    /int_{x_0}^{x_1}f(x)dx = (h/2)[f(x_0)+f(x_1)] - E(f)\n    E(f) = (h^3/12)f''(/xi)\n    \"\"\"\n    return (xs[-1]-xs[0]) / 2 * sum(fxs)\n\ndef simpson_rule(xs:list, fxs:list) -> float:\n    \"\"\"\n    Simpson's Rule:\n    /int_{x_0}^{x_2}f(x)dx = (h/3)[f(x_0)+4f(x_1)+f(x_2)] - E(f)\n    E(f) = (h^5/90)f^{(4)}(/xi)\n    \"\"\"\n    return (xs[-1]-xs[0]) / 6 * (fxs[0]+4*fxs[1]+fxs[2])\n\ndef midpoint_rule(xs:list, fxs:list) -> float:\n    return (xs[-1]-xs[0]) * fxs[1]\n\ndef composite_trapezoidal_rule(xs:list, fxs:list) -> float:\n    result = 0\n    for i in range(len(xs)-1):\n        result += trapezoidal_rule(xs[i:i+2], fxs[i:i+2])\n    return result\n\ndef composite_simpson_rule(xs:list, fxs:list) -> float:\n    result = 0\n    for i in range(len(xs)//2):\n        result += simpson_rule(xs[2*i:2*i+3], fxs[2*i:2*i+3])\n    return result\n\ndef composite_midpoint_rule(xs:list, fxs:list) -> float:\n    result = 0\n    for i in range(len(xs)//2):\n        result += midpoint_rule(xs[2*i:2*i+3], fxs[2*i:2*i+3])\n    return result\n\n\n\n\nf  = np.exp\nxs = [i/2 for i in range(9)]\nprint(composite_simpson_rule(xs, [f(x) for x in xs]))\nprint(composite_trapezoidal_rule(xs, [f(x) for x in xs]))\nprint(composite_midpoint_rule(xs, [f(x) for x in xs]))\n\npi = np.pi\nf  = np.sin\nxs = [i*pi/359 for i in range(360)]\nprint(composite_midpoint_rule(xs, [f(x) for x in xs]))\n\npi = np.pi\nf  = np.sin\nxs = [i*pi/20 for i in range(21)]\nprint(composite_simpson_rule(xs, [f(x) for x in xs]))\nprint(composite_trapezoidal_rule(xs, [f(x) for x in xs]))\nprint(composite_midpoint_rule(xs, [f(x) for x in xs]))\n\nf  = lambda x: x**3*np.exp(x)\nxs = [-2, -1, 0, 1, 2]\nprint(composite_trapezoidal_rule(xs, [f(x) for x in xs]))\nxs = [i/2 for i in range(-4,5)]\nprint(composite_simpson_rule(xs, [f(x) for x in xs]))\n\nf  = lambda x: np.exp(2*x)*np.sin(3*x)\nxs = [2*i/2169 for i in range(2170)]\nprint(composite_trapezoidal_rule(xs, [f(x) for x in xs]))\nxs = [2*i/54 for i in range(55)]\nprint(composite_simpson_rule(xs, [f(x) for x in xs]))\n \nprint(-14.213977129862521)\n", "meta": {"hexsha": "1b0585908fa407bbc2ecc17114d6f885ac32b4a7", "size": 2273, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/Python/course4.4.py", "max_stars_repo_name": "Iydon/NumericalAnalysisNotes", "max_stars_repo_head_hexsha": "ef1e37b97522fce9837142d242676fdd16e74712", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-11-08T15:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-02T10:07:33.000Z", "max_issues_repo_path": "Code/Python/course4.4.py", "max_issues_repo_name": "iydon/NumericalAnalysisNotes", "max_issues_repo_head_hexsha": "ef1e37b97522fce9837142d242676fdd16e74712", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Python/course4.4.py", "max_forks_repo_name": "iydon/NumericalAnalysisNotes", "max_forks_repo_head_hexsha": "ef1e37b97522fce9837142d242676fdd16e74712", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3855421687, "max_line_length": 64, "alphanum_fraction": 0.6080070392, "include": true, "reason": "import numpy", "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9854964224384745, "lm_q2_score": 0.9032942008463507, "lm_q1q2_score": 0.8901932033434994}}
{"text": "import matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\nimport torch\nimport torch.optim as optim\nimport utils\n\nprint('通过实际例子查看梯度下降的问题')\neta = 0.4\n\n\ndef f_2d(x1, x2):\n    return 0.1 * x1 ** 2 + 2 * x2 ** 2\n\n\ndef gd_2d(x1, x2, s1, s2):\n    return (x1 - eta * 0.2 * x1, x2 - eta * 4 * x2, 0, 0)\n\n\nprint('竖直方向波动较大')\nutils.show_trace_2d(f_2d, utils.train_2d(gd_2d))\nprint('在竖直方向越过最优解并发散')\neta = 0.6\nutils.show_trace_2d(f_2d, utils.train_2d(gd_2d))\n\nprint('使用动量法进行改进')\neta, gamma = 0.4, 0.5\n\n\ndef momentum_2d(x1, x2, v1, v2):\n    v1 = gamma * v1 + eta * 0.2 * x1\n    v2 = gamma * v2 + eta * 4 * x2\n    return x1 - v1, x2 - v2, v1, v2\n\n\nutils.show_trace_2d(f_2d, utils.train_2d(momentum_2d))\nprint('用更大的学习率，也不会发散')\neta = 0.6\nutils.show_trace_2d(f_2d, utils.train_2d(momentum_2d))\n\nprint('自行实现动量法优化')\nfeatures, labels = utils.get_nasa_data()\n\n\ndef init_momentum_states():\n    v_w = torch.zeros((features.shape[1], 1), dtype=torch.float32)\n    v_b = torch.zeros(1, dtype=torch.float32)\n    return (v_w, v_b)\n\n\ndef sgd_momentum(params, states, hyperparams):\n    for p, v in zip(params, states):\n        v.data = hyperparams['momentum'] * v.data + hyperparams['lr'] * p.grad.data\n        p.data -= v.data\n\n\nprint('momentum = 0.02, lr = 0.02')\nutils.train_opt(sgd_momentum, init_momentum_states(), {'lr': 0.02, 'momentum': 0.5}, features, labels)\nprint('momentum = 0.9, lr = 0.02')\nutils.train_opt(sgd_momentum, init_momentum_states(), {'lr': 0.02, 'momentum': 0.9}, features, labels)\nprint('momentum = 0.9, lr = 0.004')\nutils.train_opt(sgd_momentum, init_momentum_states(), {'lr': 0.004, 'momentum': 0.9}, features, labels)\n\nprint('框架实现')\nutils.train_opt_pytorch(optim.SGD, {'lr': 0.004, 'momentum': 0.9}, features, labels)\n", "meta": {"hexsha": "f4e87d64bee738c88a7dbdb4478c3f41d3978e5a", "size": 1764, "ext": "py", "lang": "Python", "max_stars_repo_path": "d2l/41_momentum.py", "max_stars_repo_name": "wdxtub/deep-learning-note", "max_stars_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2019-03-27T20:17:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T23:20:31.000Z", "max_issues_repo_path": "d2l/41_momentum.py", "max_issues_repo_name": "wdxtub/deep-learning-note", "max_issues_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "d2l/41_momentum.py", "max_forks_repo_name": "wdxtub/deep-learning-note", "max_forks_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-03-31T10:28:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:25:40.000Z", "avg_line_length": 25.9411764706, "max_line_length": 103, "alphanum_fraction": 0.6729024943, "include": true, "reason": "import numpy", "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474246069458, "lm_q2_score": 0.9324533046369553, "lm_q1q2_score": 0.8901641458379053}}
{"text": "from sympy import *\nx, y, z = symbols('x y z')\ninit_printing(use_unicode=False)\n\n# simplify - not specific type of simplification\n\npprint(simplify(sin(x)**2 + cos(x)**2))\n\npprint(simplify((x**3 + x**2 - x - 1)/(x**2 + 2*x + 1)))\n\npprint(simplify(gamma(x)/gamma(x - 2)))\n\npprint(simplify(x**2 + 2*x + 1))\n\n# expand - expand polynomial to canonical form ax^2+bx+c etc.\n\npprint(expand((x + 1)**2))\n\npprint(expand((x + 2)*(x - 3)))\n\npprint(expand((x + 1)*(x - 2) - (x - 1)*x))\n\n# factor - factors a polynomial\n\npprint(factor(x**3 - x**2 + x - 1))\n\npprint(factor(x**2*z + 4*x*y*z + 4*y**2*z))\n\n# returns list of factors\n\npprint(factor_list(x**2*z + 4*x*y*z + 4*y**2*z))\n\n# non-polynomials\n\npprint(expand((cos(x) + sin(x))**2))\n\npprint(factor(cos(x)**2 + 2*cos(x)*sin(x) + sin(x)**2))\n\n# collect - based on a variable (i.e. x)\n# gather the coefficients into a term\n# multiplied by a power of x.\n\nexpr = x*y + x - 3 + 2*x**2 - z*x**2 + x**3\npprint(expr)\n\ncollected_expr = collect(expr, x)\npprint(collected_expr)\n\n# coeff gives coefficient of the given\n# power of x - x^2 in this example\n\npprint(collected_expr.coeff(x, 2))\n\n# cancel - arrange as fraction?\n\npprint(cancel((x**2 + 2*x + 1)/(x**2 + x)))\n\nexpr = 1/x + (3*x/2 - 2)/(x - 4)\npprint(expr)\n\npprint(cancel(expr))\n\nexpr = (x*y**2 - 2*x*y*z + x*z**2 + y**2 - 2*y*z + z**2)/(x**2 - 1)\npprint(expr)\n\npprint(cancel(expr))\n\n# factors numerator in this example\n\npprint(factor(expr))\n\n# apart - seems to split into multiple fractional terms\n# opposite of cancel kind of?\n\nexpr = (4*x**3 + 21*x**2 + 10*x + 12)/(x**4 + 5*x**3 + 5*x**2 + 4*x)\n\npprint(expr)\nprint(' ')\n\npprint(apart(expr))\nprint(' ')\n\npprint(cancel(apart(expr)))\nprint(' ')\n\n# trig simp - like simplify for general\n# there are specific simps later\n\npprint(acos(x))\nprint(' ')\npprint(cos(acos(x)))\nprint(' ')\npprint(asin(1))\nprint(' ')\n\npprint(trigsimp(sin(x)**2 + cos(x)**2))\nprint(' ')\npprint(trigsimp(sin(x)**4 - 2*cos(x)**2*sin(x)**2 + cos(x)**4))\nprint(' ')\npprint(trigsimp(sin(x)*tan(x)/sec(x)))\nprint(' ')\n\npprint(trigsimp(cosh(x)**2 + sinh(x)**2))\nprint(' ')\npprint(trigsimp(sinh(x)/tanh(x)))\nprint(' ')\n\n# expand_trig kind of like expand\n\ndef spprint(o):\n    pprint(o)\n    print(' ')\n\nspprint(expand_trig(sin(x + y)))\nspprint(expand_trig(tan(2*x)))\n\n# trigsimp opposite of expand_trig kinda\n\nspprint(trigsimp(expand_trig(sin(x + y))))\n\n# powers - can state things about the numbers\n# real, positive, or by default complex\n\nx, y = symbols('x y', positive=True)\na, b = symbols('a b', real=True)\nz, t, c = symbols('z t c')\n\nspprint(powsimp(x**a*x**b))\n\nspprint(powsimp(x**a*y**a))\n\n# z, t, c might be complex\n\nspprint(powsimp(t**c*z**c))\n\n# force simp\n\nspprint(powsimp(t**c*z**c, force=True))\n\nspprint((z*t)**2)\n\nspprint(sqrt(x*y))\n\n# simp doesn't work because of automatic splitting\n\nspprint(powsimp(z**2*t**2))\nspprint(powsimp(sqrt(x)*sqrt(y)))\n\n# expanding the base or exponent\n\nspprint(expand_power_exp(x**(a + b)))\n\nspprint(expand_power_base((x*y)**a))\n\n# same doesn't work with complex but can force\n\nspprint(expand_power_base((z*t)**c))\n\nspprint(expand_power_base((z*t)**c, force=True))\n\n# doesn't work with number powers like above\n\nspprint(x**2*x**3)\nspprint(expand_power_exp(x**5))\n\n# simplified nested powers \n# can force when not appropriate\n\nspprint(powdenest((x**a)**b))\nspprint(powdenest((z**a)**b))\nspprint(powdenest((z**a)**b, force=True))\n\n# exponentials and logs\n\n# log(x) = ln(x) log base e of x I think\n\nspprint(ln(x))\n\nx, y = symbols('x y', positive=True)\nn = symbols('n', real=True)\n\nspprint(expand_log(log(x*y)))\nspprint(expand_log(log(x/y)))\nspprint(expand_log(log(x**2)))\nspprint(expand_log(log(x**n)))\nspprint(expand_log(log(z*t)))\n\n\n# force\n\nspprint(expand_log(log(z**2)))\nspprint(expand_log(log(z**2), force=True))\n\n# logcombine kind of revers of expand_log\n\nspprint(logcombine(log(x) + log(y)))\nspprint(logcombine(n*log(x)))\nspprint(logcombine(n*log(z)))\nspprint(logcombine(n*log(z), force=True))\n\n\n# \"special\" functions\n\nx, y, z = symbols('x y z')\nk, m, n = symbols('k m n')\n\nspprint(factorial(n))\n\nspprint(binomial(n, k))\n\nspprint(binomial(5, 2))\n\nspprint(gamma(z))\n\nspprint(hyper([1, 2], [3], z))\n\n# rewrite an expression in terms of a function\n\nspprint(tan(x).rewrite(sin))\nspprint(factorial(x).rewrite(gamma))\n\n# get rid of hyper\n\nspprint(hyperexpand(hyper([1, 1], [2], z)))\n\nexpr = meijerg([[1],[1]], [[1],[]], -z)\nspprint(expr)\nspprint(hyperexpand(expr))\n\n# simplifiy combinatorials - binomial, etc.\n\nn, k = symbols('n k', integer = True)\nspprint(combsimp(factorial(n)/factorial(n - 3)))\nspprint(combsimp(binomial(n+1, k+1)/binomial(n, k)))\n\n# simplify gamma whatever that is. :)\n\nspprint(gammasimp(gamma(x)*gamma(1 - x)))\n\n# continued fraction example\n# i think this is an example of using sympy and simplification\n\ndef list_to_frac(l):\n    expr = Integer(0)\n    for i in reversed(l[1:]):\n        expr += i\n        expr = 1/expr\n    return l[0] + expr\n    \nspprint(list_to_frac([x, y, z]))\n\n# result is sympy fraction\n\nspprint(list_to_frac([1, 2, 3, 4]))\n\n# get continued fraction\n\nsyms = symbols('a0:5')\nspprint(syms)\na0, a1, a2, a3, a4 = syms\nfrac = list_to_frac(syms)\nspprint(frac)\n\n# put into standard form\n\nfrac = cancel(frac)\nspprint(frac)\n\n# put back into original form\n\nl = []\nfrac = apart(frac, a0)\nspprint(frac)\nl.append(a0)\nfrac = 1/(frac - a0)\nspprint(frac)\n\nfrac = apart(frac, a1)\nspprint(frac)\nl.append(a1)\nfrac = 1/(frac - a1)\nfrac = apart(frac, a2)\nspprint(frac)\nl.append(a2)\nfrac = 1/(frac - a2)\nfrac = apart(frac, a3)\nspprint(frac)\nl.append(a3)\nfrac = 1/(frac - a3)\nfrac = apart(frac, a4)\nspprint(frac)\nl.append(a4)\nspprint(list_to_frac(l))\n\n\n\n\n", "meta": {"hexsha": "951ffe689d588060d0644f5f19bd83cc6f093944", "size": 5612, "ext": "py", "lang": "Python", "max_stars_repo_path": "c8.py", "max_stars_repo_name": "bobbydurrett/sympytutorial", "max_stars_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c8.py", "max_issues_repo_name": "bobbydurrett/sympytutorial", "max_issues_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c8.py", "max_forks_repo_name": "bobbydurrett/sympytutorial", "max_forks_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8322147651, "max_line_length": 68, "alphanum_fraction": 0.6493228795, "include": true, "reason": "from sympy", "num_tokens": 1922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741295151718, "lm_q2_score": 0.9343951661947455, "lm_q1q2_score": 0.890080662061144}}
{"text": "import numpy as np\nfrom numpy import linalg as LA\nimport matplotlib.pyplot as plt\n\n\nA = np.array([[1 , 2],[4 , 3]]) \nlamda, v = LA.eig(A)\nprint(f\"eigenvalues\\n{lamda}\")\nprint(f\"eigenvectors\\n{v}\")\nv1 = v[:,0]\nv2 = v[:,1]\nprint(f\"v1\\n{v1}\")\nprint(f\"v2\\n{v2}\")\n\nplt.title('eigenvector v1 : blue , eigenvector v2 : green')\nplt.plot([0,v1[0]],[0,v1[1]],'blue')\nplt.plot([0,v2[0]],[0,v2[1]],'green')\nplt.xlim((-1,1))\nplt.ylim((-1,1))\nplt.grid()\nplt.show()\n\nequation1 = np.dot(A,v1) - lamda[0]*v1 # should be 0\nprint(equation1)\nequation2 = np.dot(A,v2) - lamda[1]*v2 # should be 0\nprint(equation2)\n\n", "meta": {"hexsha": "0a75e4fe835dabbf8729fe86dd1c78f18f0a5c4c", "size": 593, "ext": "py", "lang": "Python", "max_stars_repo_path": "eigenvalues_and_eigrnvector.py", "max_stars_repo_name": "NathanKr/ml-math-background-playground", "max_stars_repo_head_hexsha": "69c3c10f3e9fc348a40166b4b20af8d43507944c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eigenvalues_and_eigrnvector.py", "max_issues_repo_name": "NathanKr/ml-math-background-playground", "max_issues_repo_head_hexsha": "69c3c10f3e9fc348a40166b4b20af8d43507944c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigenvalues_and_eigrnvector.py", "max_forks_repo_name": "NathanKr/ml-math-background-playground", "max_forks_repo_head_hexsha": "69c3c10f3e9fc348a40166b4b20af8d43507944c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1785714286, "max_line_length": 59, "alphanum_fraction": 0.6306913997, "include": true, "reason": "import numpy,from numpy", "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.982287698703999, "lm_q2_score": 0.905989829267587, "lm_q1q2_score": 0.889942664440487}}
{"text": "'''\nThe numerical simulation calculates the approximation of the original curves from the SIR differential equations\nusing Euler's method\nCode is adapted from:\nhttps://scipython.com/book/chapter-8-scipy/additional-examples/the-sir-epidemic-model/\n'''\nimport numpy as np #numpy is used \nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\n# Total population, N.\nN = 1000000\n# Initial number of infected and recovered individuals, I0 and R0.\nI0, R0 = 305, 0\n# Everyone else, S0, is susceptible to infection initially.\nS0 = N - I0 - R0 #Susceptible is equal to the population less the infected and removed\n# Contact rate, beta, and mean recovery rate, gamma, (in 1/days).\nbeta, gamma = 0.3552, 0.1 #Infectiousness and recovery rates\n# A grid of time points (in days)\nt = np.linspace(0, 200, 200) #length of time in days\n\n# The SIR model differential equations.\ndef deriv(y, t, N, beta, gamma):\n    S, I, R = y\n    dSdt = -beta * S * I / N #derivative of susceptible equation\n    dIdt = beta * S * I / N - gamma * I #derivative of infected equation\n    dRdt = gamma * I #derivative of removed equation\n    return dSdt, dIdt, dRdt #return the value of the derivatives\n\n# Initial conditions vector\ny0 = S0, I0, R0\n# Integrate the SIR equations over the time grid, t.\nret = odeint(deriv, y0, t, args=(N, beta, gamma))\nS, I, R = ret.T\n\n# Plot the data on three separate curves for S(t), I(t) and R(t)\nfig = plt.figure(facecolor='w')\nax = fig.add_subplot(111, axisbelow=True)\nax.plot(t, S/1000000, 'b', alpha=0.5, lw=2, label='Susceptible') #Plot the susceptible line as blue\nax.plot(t, I/1000000, 'r', alpha=0.5, lw=2, label='Infected') #plot the infected line as red\nax.plot(t, R/1000000, 'g', alpha=0.5, lw=2, label='Recovered with immunity') #plot the removed line as green\nax.set_xlabel('Time /days') #Set the label as time in days\nax.set_ylabel('Number (1000000s)') #population number is expressed in millions\nax.set_ylim(0,1.2) #the y-axis is limited to a maximum of 1.2\nax.yaxis.set_tick_params(length=0) \nax.xaxis.set_tick_params(length=0)\nax.grid(b=True, which='major', c='w', lw=2, ls='-')\nplt.title('SIR model for the Ebola Outbreak in Liberia, 2014')\nlegend = ax.legend()\nlegend.get_frame().set_alpha(0.5)\nfor spine in ('top', 'right', 'bottom', 'left'):\n    ax.spines[spine].set_visible(False)\nplt.show() #Display the graph", "meta": {"hexsha": "f06b4996329877f0a7872cabbde05b778f4a49d6", "size": 2344, "ext": "py", "lang": "Python", "max_stars_repo_path": "SIR_Numerical_Model/sir.py", "max_stars_repo_name": "markgacoka/micro-projects", "max_stars_repo_head_hexsha": "e8115c8270a115282e7dfda6e24620b3333f8c6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SIR_Numerical_Model/sir.py", "max_issues_repo_name": "markgacoka/micro-projects", "max_issues_repo_head_hexsha": "e8115c8270a115282e7dfda6e24620b3333f8c6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SIR_Numerical_Model/sir.py", "max_forks_repo_name": "markgacoka/micro-projects", "max_forks_repo_head_hexsha": "e8115c8270a115282e7dfda6e24620b3333f8c6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2264150943, "max_line_length": 112, "alphanum_fraction": 0.7175767918, "include": true, "reason": "import numpy,from scipy", "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517469248845, "lm_q2_score": 0.9099070029841949, "lm_q1q2_score": 0.889936133807878}}
{"text": "import numpy as np\n\ndef calcAngle_py(v1,v2):\n    \n    v1 = v1/np.linalg.norm(v1)\n    v2 = v2/np.linalg.norm(v2)\n    \n    return np.arccos(np.dot(v1,v2).clip(-1,1))\n\ndef calcRodriguesMtx_py(theta,k):\n    \"\"\"\n    Get Rodrigues' rotation matrix for \n    theta rad rotation (counter clockwise) w.r.t. a unit vector k\n    \n    see:\n    https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula\n    \n    \"\"\"\n    \n#     assert k.size == 3 and not np.allclose(k,np.zeros(3))\n    \n    # Ensure that k is a unit vector\n    k = k/np.linalg.norm(k)\n    \n    # Cross-product matrix\n    K = np.array([\n            [    0,-k[2], k[1]],\n            [ k[2],    0,-k[0]],\n            [-k[1], k[0],   0]])\n    \n    return np.eye(3)+ K*np.sin(theta) + (K@K*(1-np.cos(theta)))\n\ndef calcAreaPoly_py(verts):\n    \"\"\"\n    ref: http://geomalgorithms.com/a01-_area.html\n    \"\"\"\n\n    L = verts.shape[0]\n    assert L > 2, 'length of verts must be at least 3'\n\n    # Get sequence of index\n    idx1 = np.arange(L)\n    idx2 = np.arange(1,L+1)\n    idx2[-1] = 0\n\n    # Get the unit normar vector\n    n = np.cross(verts[1]-verts[0],verts[2]-verts[0])\n    n /= np.linalg.norm(n)\n\n    return abs(np.dot(np.sum(np.cross(verts[idx1],verts[idx2]),axis=0),n)/2)\n\n    # assert L == 4, \"Currently handle 4 vertices\"\n\n    # # Get the unit normar vector\n    # n = np.cross(verts[1]-verts[0],verts[2]-verts[0])\n    # n /= np.linalg.norm(n)\n\n    # return abs(np.dot(np.cross(verts[2]-verts[0],verts[3]-verts[1]),n)/2)\n\ndef checkBlockage(plane1,plane2,planeB,nargout=1):\n    \"\"\"\n    Check wheter plane1 and plane2 are blocked by planeB.\n\n    plane1, plane2, planeB are simple planes defined in the \n    rectplane class.\n\n\n    \"\"\"\n\n    from owcsimpy.geoutils.cutils import calcArea3DPoly\n\n    # Unpack the tuples\n    _,ctrPoint1,_,_ = plane1\n    _,ctrPoint2,_,_ = plane2\n    normalVectB,ctrPointB,vertsB,areaB = planeB\n\n    # Check intersection\n    # see http://geomalgorithms.com/a05-_intersect-1.html\n    u = ctrPoint2-ctrPoint1\n    w = ctrPoint1-ctrPointB\n\n    # print(np.dot(normalVectB,u))\n\n    if np.allclose(np.dot(normalVectB,u),0):\n        # Line segment and the planeB is parallel\n        isBlocked = False \n        intersectingPoint = None\n    else:\n\n        # Parametric value of the intersecting point\n        ti = -np.dot(normalVectB,w)/np.dot(normalVectB,u)\n        \n        # The intersecting point\n        intersectingPoint = ctrPoint1+ti*u\n\n        # insert V[0] as V[n], see\n        # http://geomalgorithms.com/a01-_area.html\n        verts = np.append(vertsB,vertsB[0]).reshape(-1,3) # num of col is 3\n\n        listTriangleVerts = [np.array([intersectingPoint.tolist(),verts[idx].tolist(),\n                      verts[idx+1].tolist(),intersectingPoint.tolist()]) \n                     for idx in range(4)] \n\n        totalarea = sum([calcArea3DPoly(3,triVerts[:,0],\n            triVerts[:,1],triVerts[:,2],normalVectB) \n        for triVerts in listTriangleVerts])\n\n        if np.allclose(areaB,totalarea):\n            isBlocked = True\n        else:\n            isBlocked = False\n\n    if nargout == 1:\n        return isBlocked\n    elif nargout == 2:\n        return isBlocked,intersectingPoint\n    elif nargout == 3:\n        return isBlocked,intersectingPoint,totalarea\n\ndef checkBlockageQHull(plane1,plane2,planeB,nargout=1):\n    \"\"\"\n    Using ConvexHull.\n\n    This is slower, but worth having as it's more intuitive.\n    We can use this to have a third opinion.\n\n    Check wheter plane1 and plane2 are blocked by planeB.\n\n    plane1, plane2, planeB are simple planes defined in the \n    rectplane class.\n\n\n    \"\"\"\n\n    from scipy.spatial import Delaunay\n\n    # Unpack the tuples\n    _,ctrPoint1,_,_ = plane1\n    _,ctrPoint2,_,_ = plane2\n    normalVectB,ctrPointB,vertsB,areaB = planeB\n\n    # Check intersection\n    # see http://geomalgorithms.com/a05-_intersect-1.html\n    u = ctrPoint2-ctrPoint1\n    w = ctrPoint1-ctrPointB\n\n    if np.allclose(np.dot(normalVectB,u),0):\n        # Line segment and the planeB is parallel\n        isBlocked = False \n        intersectingPoint = None\n    else:\n\n        # Parametric value of the intersecting point\n        ti = -np.dot(normalVectB,w)/np.dot(normalVectB,u)\n        \n        # The intersecting point\n        intersectingPoint = ctrPoint1+ti*u\n\n        verts = vertsB\n        epsilon = 1e-3\n        # for vert in vertsB:\n        #     verts = np.append(verts,vert+normalVectB*epsilon)\n        verts = np.append(verts,verts+normalVectB*epsilon)\n        \n        verts = verts.reshape(-1,3)\n\n        delaunay = Delaunay(verts)\n        isBlocked = delaunay.find_simplex(intersectingPoint)>=0 \n\n    if nargout == 1:\n        return isBlocked\n    elif nargout == 2:\n        return isBlocked,intersectingPoint\n\n\n\n    ", "meta": {"hexsha": "ee50e1947d5699c9ddf2aff2089aeaa196607c0b", "size": 4725, "ext": "py", "lang": "Python", "max_stars_repo_path": "owcsimpy/geoutils/pyutils.py", "max_stars_repo_name": "ardimasp/owcsimpy", "max_stars_repo_head_hexsha": "155b0f26dd5e247cef9a84265256b0d70ba0b139", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "owcsimpy/geoutils/pyutils.py", "max_issues_repo_name": "ardimasp/owcsimpy", "max_issues_repo_head_hexsha": "155b0f26dd5e247cef9a84265256b0d70ba0b139", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "owcsimpy/geoutils/pyutils.py", "max_forks_repo_name": "ardimasp/owcsimpy", "max_forks_repo_head_hexsha": "155b0f26dd5e247cef9a84265256b0d70ba0b139", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6949152542, "max_line_length": 86, "alphanum_fraction": 0.6114285714, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104962847374, "lm_q2_score": 0.9207896753475597, "lm_q1q2_score": 0.8898608071264974}}
{"text": "import math\nimport numpy as np\n\n\nclass PurityFuncs:\n\n    @staticmethod\n    def entropy(labels):\n        \"\"\" Calculate label entropy\n\n        Arguments:\n            labels {np.ndarray} -- A single dimensional array that we wish to calculate the entropy of\n        Returns:\n            {int} -- The entropy of the labels\n        \"\"\"\n\n        total = len(labels)\n        unique_labels, counts = np.unique(labels, return_counts=True)\n        label_counts = dict(zip(unique_labels, counts))\n\n        entropy = 0\n        for label in unique_labels:\n            prob = label_counts[label] / total\n            entropy -= prob * math.log2(prob)\n        return entropy\n\n    @staticmethod\n    def gini(labels):\n        \"\"\" Calculates gini impurity of a given node's labels\n\n        Arguments:\n            labels {np.ndarray} -- A single dimensional array that we wish to calculate the entropy of\n        Returns:\n            {int} -- The gini impurity of the node\n                For J classes, an impurity of (J-1)/J indicates an even distribution\n                e.g. gini(['a','a','b','b','c','c') = 2 / 3 = 0.66667\n        \"\"\"\n\n        total = len(labels)\n        _, counts = np.unique(labels, return_counts=True)\n        return 1 - np.sum(list(map(lambda p: (p / total) ** 2, counts)))\n", "meta": {"hexsha": "0af897647b3efabeaf6dcd8739a6b27e81de1bb3", "size": 1280, "ext": "py", "lang": "Python", "max_stars_repo_path": "statsml/decisionclassifier/purity.py", "max_stars_repo_name": "GiovanniPasserello/StatsML", "max_stars_repo_head_hexsha": "f6d33da05df765496469df8dd2691cb865755ddb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-13T14:37:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T21:28:14.000Z", "max_issues_repo_path": "statsml/decisionclassifier/purity.py", "max_issues_repo_name": "GiovanniPasserello/StatsML", "max_issues_repo_head_hexsha": "f6d33da05df765496469df8dd2691cb865755ddb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "statsml/decisionclassifier/purity.py", "max_forks_repo_name": "GiovanniPasserello/StatsML", "max_forks_repo_head_hexsha": "f6d33da05df765496469df8dd2691cb865755ddb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4761904762, "max_line_length": 102, "alphanum_fraction": 0.578125, "include": true, "reason": "import numpy", "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9793540644400345, "lm_q2_score": 0.9086179031191509, "lm_q1q2_score": 0.8898586364427219}}
{"text": "import pandas as pd\nfrom sympy import Symbol, diff, factorial\nfrom sympy.core.add import Add\nfrom sympy.core.mul import Mul\nfrom typing import Union\n\n\ndef n_diff(f: Union[Add, Mul], variable: Symbol, n: int):\n\tfor _ in range(n):\n\t\tf = f.diff(variable)\n\treturn f\n\n\ndef taylor(f: Union[Add, Mul], variable: Symbol, x0: float = 0.0, n: int = 10):\n\tfn = n_diff(f, variable, n)\n\tif n > 0:\n\t\treturn ((fn.subs({variable: x0}) / factorial(n)) * (variable - x0) ** n) + taylor(f, variable, x0, n - 1)\n\telse:\n\t\treturn (fn.subs({variable: x0}) / factorial(n)) * (variable - x0) ** n\n\n\ndef function(x: float):\n\treturn x ** 2 - 4\n\n\ndef bisection(f: function, a: float, b: float, tol=0.001, iterations=100, history: pd.DataFrame = None):\n\tp = (a + b) / 2\n\tif history is None: history = pd.DataFrame(columns=[\"a\", \"b\", \"p\", \"f(p)\"])\n\n\tif f(a) * f(b) > 0: Exception(\"No root exists between {} and {}\".format(a, b))\n\n\thistory = history.append({\n\t\t\"a\": a,\n\t\t\"b\": b,\n\t\t\"p\": p,\n\t\t\"f(p)\": f(p)\n\t}, ignore_index=True)\n\n\tif abs(f(p)) > tol and iterations > 0:\n\t\tif f(a) * f(p) > 0:\n\t\t\ta = p\n\t\telse:\n\t\t\tb = p\n\t\treturn bisection(f, a, b, tol, iterations - 1, history)\n\telse:\n\t\treturn p, history\n\n\ndef does_converges(g: Union[Add, Mul], variable: Symbol, x0):\n\treturn abs(g.diff(variable).subs({variable: x0}).simplify()) < 1\n\n\ndef direct_iteration(f: Union[Add, Mul], variable: Symbol, variable_start: float = 0.0, iterations: int = 100):\n\tif does_converges(f, variable, variable_start):\n\t\tif iterations > 0:\n\t\t\tprint(variable_start)\n\t\t\tvariable_start = f.subs({variable: variable_start}).simplify()\n\t\t\tprint(variable_start.evalf())\n\t\t\tprint()\n\t\t\treturn direct_iteration(f, variable, variable_start, iterations - 1)\n\t\telse:\n\t\t\tprint(variable_start.evalf())\n\t\t\treturn variable_start\n\telse:\n\t\tprint(\"Does not converge at starting point given\")\n\n\ndef newtons_method(f: Union[Add, Mul], variable: Symbol, x0: float = 0.0, tol: float = 0.001, iterations: int = 100):\n\tf_ = f.diff(variable)\n\tfor i in range(iterations):\n\t\tnumerator = f.subs({variable: x0})\n\t\tdenominator = f_.subs({variable: x0})\n\t\tx1 = x0 - numerator / denominator\n\t\tprint(x1)\n\t\tif abs(x0 - x1) > tol:\n\t\t\treturn x1\n\t\telse:\n\t\t\tx0 = x1\n\treturn x0\n\n", "meta": {"hexsha": "d3f7346602bba6435ae0c8ae2d12ffe6ead631a2", "size": 2183, "ext": "py", "lang": "Python", "max_stars_repo_path": "roots.py", "max_stars_repo_name": "StoneHe1/Calculus", "max_stars_repo_head_hexsha": "46d0b8a0bde6fe11246c65d6897961ed92613646", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "roots.py", "max_issues_repo_name": "StoneHe1/Calculus", "max_issues_repo_head_hexsha": "46d0b8a0bde6fe11246c65d6897961ed92613646", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "roots.py", "max_forks_repo_name": "StoneHe1/Calculus", "max_forks_repo_head_hexsha": "46d0b8a0bde6fe11246c65d6897961ed92613646", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-16T06:01:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T06:01:32.000Z", "avg_line_length": 26.950617284, "max_line_length": 117, "alphanum_fraction": 0.6481905634, "include": true, "reason": "from sympy", "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9835969665221771, "lm_q2_score": 0.9046505395995927, "lm_q1q2_score": 0.88981152651281}}
{"text": "\"\"\"\n...This file implements methods for matrix manipulation, including:\n\n    1. matrix_power() ->\n        divide-and-conquer strategies for\n        finding a matrix exponential.\n        This function makes use of Strassen's algorithm to optimize its runtime.\n\n    2. matrix_multiply() ->\n        an implementation of Strassen's O(n^log_2(7))\n        algorithm for matrix faster matrix multiplication by substituting\n        brute-force multiplication with strategic multiplications and additions.\n\n    3. matrix_sum() ->\n        Given two matrices, find their sum using brute-force methods.\n\n    4. matrix_difference() ->\n        Given two matrices A, B in order, find A - B using brute_force methods.\n\n    5. matrix_get() ->\n        A helper function that, given an n x n matrix such that n % 2 = 0\n        and a position 0 <= x <= 3, returns the subset of the matrix.\n\n    6. matrix_compile() ->\n        A helper function that, given a larger matrix A and a smaller matrix B\n        such that dim(A) = 2 * dim(B), saves the values in B into a\n        specified subset of A.\n\n    7. matrix_identity() ->\n        A function that, given a dimension n, returns the (n x n) identity matrix.\n\n    8. matrix_transpose() ->\n        Given an (m x n) matrix, returns the (n x m) transpose of the matrix.\n        \n    IMPORTANT NOTE:\n        It is usual to represent matrices as an array of arrays, wherein each sub-array\n        represents either a column or row of the matrix. \n        \n        In this implementation, each sub-array is interpreted to be a column of the matrix.\n        It's important that the caller create/implement matrices with similar\n        semantics, or the calculations are not guaranteed to be correct.\n\n    (c) Amittai J. Wekesa (github: @siavava), May 2021.\n...\n\"\"\"\n\nfrom timeit import timeit\nimport numpy as np\nfrom numpy.random import randint\nfrom mpl_toolkits import mplot3d\nfrom matplotlib import pyplot as plt\nfrom math import log, log2, ceil\n\n\ndef matrix_power(matrix: list, exponential: int) -> list:\n    \"\"\"\n    Compute the power of a matrix.\n    \"\"\"\n    if exponential == 0:\n        return matrix_identity(len(matrix))\n    elif exponential == 1:\n        return matrix\n    else:\n        half_power: list = matrix_power(matrix, exponential // 2)\n        power: list = matrix_multiply(half_power, half_power)\n        if (exponential % 2) == 0:\n            return power\n        else:\n            return matrix_multiply(matrix, power)\n\n\ndef matrix_identity(n: int) -> list:\n    \"\"\"\n    Generate the n-sized identity matrix.\n    \"\"\"\n    if n == 0:\n        return [0]\n    identity: list = []\n    for col in range(n):\n        column: list = []\n        for row in range(n):\n            if col == row:\n                column.append(1)\n            else:\n                column.append(0)\n        identity.append(column)\n    return identity\n\n\ndef matrix_generate(n: int, maximum=10**4) -> list:\n    \"\"\"\n    Generate a random square matrix of given size\n    Maximum size of element\n    \"\"\"\n    if n == 0:\n        return [0]\n    m: list = []\n    for col in range(n):\n        column: list = []\n        for row in range(n):\n            column.append(randint(maximum))\n        m.append(column)\n    return m\n\n\ndef matrix_transpose(matrix: list) -> list:\n    \"\"\"\n    Compute the transpose of a matrix\n    \"\"\"\n    transpose: list = []\n    for row in range(len(matrix[1])):\n        column = []\n        for col in range(len(matrix)):\n            column.append(matrix[col][row])\n        transpose.append(column)\n    return transpose\n\n\ndef matrix_multiply(mat_a: list, mat_b: list):\n    \"\"\"\n    Multiply rwo matrices.\n    \"\"\"\n    n: int = len(mat_a)\n    if n != len(mat_b):\n        print(\"ERROR: Cannot multiply non-square matrices using Strassen. Stop.\")\n        return None\n    elif n % 2 != 0:\n        print(\"ERROR: Cannot work on matrices whose dimensions are not a factor of two.\")\n        print(\"An update will be coming soon!\")\n        return None\n\n    if n > 2:\n        mode = \"matrix\"\n    else:\n        mode = \"nums\"\n\n    # sub-nums\n    if mode == \"nums\":\n        # Step 1: compute sums\n        s1 = mat_b[1][0] - mat_b[1][1]\n        s2 = mat_a[0][0] + mat_a[1][0]\n        s3 = mat_a[0][1] + mat_a[1][1]\n        s4 = mat_b[0][1] - mat_b[0][0]\n        s5 = mat_a[0][0] + mat_a[1][1]\n        s6 = mat_b[0][0] + mat_b[1][1]\n        s7 = mat_a[1][0] - mat_a[1][1]\n        s8 = mat_b[0][1] + mat_b[1][1]\n        s9 = mat_a[0][0] - mat_a[0][1]\n        s10 = mat_b[0][0] + mat_b[1][0]\n\n        # Step 2: compute products\n        p1 = mat_a[0][0] * s1\n        p2 = mat_b[1][1] * s2\n        p3 = mat_b[0][0] * s3\n        p4 = mat_a[1][1] * s4\n        p5 = s5 * s6\n        p6 = s7 * s8\n        p7 = s9 * s10\n\n        # Step 3: compile results\n        results = [[0, 0], [0, 0]]\n        results[0][0] = p5 + p4 - p2 + p6\n        results[1][0] = p1 + p2\n        results[0][1] = p3 + p4\n        results[1][1] = p5 + p1 - p3 - p7\n\n        return results\n\n    # sub-matrices\n    elif mode == \"matrix\":\n        # compute matrix sums\n        s1 = matrix_difference(matrix_get(mat_b, 1), matrix_get(mat_b, 3))\n        s2 = matrix_sum(matrix_get(mat_a, 0), matrix_get(mat_a, 1))\n        s3 = matrix_sum(matrix_get(mat_a, 2), matrix_get(mat_a, 3))\n        s4 = matrix_difference(matrix_get(mat_b, 2), matrix_get(mat_b, 0))\n        s5 = matrix_sum(matrix_get(mat_a, 0), matrix_get(mat_a, 3))\n        s6 = matrix_sum(matrix_get(mat_b, 0), matrix_get(mat_b, 3))\n        s7 = matrix_difference(matrix_get(mat_a, 1), matrix_get(mat_a, 3))\n        s8 = matrix_sum(matrix_get(mat_b, 2), matrix_get(mat_b, 3))\n        s9 = matrix_difference(matrix_get(mat_a, 0), matrix_get(mat_a, 2))\n        s10 = matrix_sum(matrix_get(mat_b, 0), matrix_get(mat_b, 1))\n\n        # Step 2: compute matrix products\n        p1 = matrix_multiply(matrix_get(mat_a, 0), s1)\n        p2 = matrix_multiply(s2, matrix_get(mat_b, 3))\n        p3 = matrix_multiply(s3, matrix_get(mat_b, 0))\n        p4 = matrix_multiply(matrix_get(mat_a, 3), s4)\n        p5 = matrix_multiply(s5, s6)\n        p6 = matrix_multiply(s7, s8)\n        p7 = matrix_multiply(s9, s10)\n\n        # Step 3: compile results\n        results = [[0] * n] * n\n        results = matrix_compile(results, matrix_sum(matrix_sum(p5, p4), matrix_difference(p6, p2)), 0)\n        results = matrix_compile(results, matrix_sum(p1, p2), 1)\n        results = matrix_compile(results, matrix_sum(p3, p4), 2)\n        results = matrix_compile(results, matrix_difference(matrix_sum(p5, p1), matrix_sum(p3, p7)), 3)\n\n        # return compiled results\n        return results\n\n\ndef matrix_sum(mat_a: list, mat_b: list):\n    \"\"\"\n    Compute the sum of two compatible matrices.\n    \"\"\"\n    n: int = len(mat_a)\n    if n != len(mat_b):\n        print(\"ERROR: cannot add incompatible matrices. Stop.\")\n        return None\n    results = []\n    for col in range(n):\n        column = []\n        for row in range(n):\n            column.append(mat_a[col][row] + mat_b[col][row])\n        results.append(column)\n    return results\n\n\ndef matrix_difference(mat_a: list, mat_b: list):\n    \"\"\"\n    Compute the difference of two matrices.\n    \"\"\"\n    n: int = len(mat_a)\n    if n != len(mat_b):\n        print(\"ERROR: cannot subtract incompatible matrices. Stop.\")\n        return None\n    results = []\n    for col in range(n):\n        column = []\n        for row in range(n):\n            column.append(mat_a[col][row] - mat_b[col][row])\n        results.append(column)\n    return results\n\n\ndef matrix_compile(main: list, sub: list, pos: int):\n    \"\"\"\n    Compile sub-matrices into a main matrix.\n    \"\"\"\n    n = len(sub)\n    total = len(main)\n    if len(main) != 2 * n:\n        print(\"ERROR: Cannot merge matrices of incompatible dimension. Stop.\")\n        return None\n\n    results = []\n\n    if pos == 0:\n        for col in range(total):\n            column = []\n            for row in range(total):\n                if col in range(n) and row in range(n):\n                    column.append(sub[col][row])\n                else:\n                    column.append(main[col][row])\n            results.append(column)\n        return results\n\n    elif pos == 1:\n        for col in range(total):\n            column = []\n            for row in range(total):\n                if col in range(n, total) and row in range(n):\n                    column.append(sub[col - n][row])\n                else:\n                    column.append(main[col][row])\n            results.append(column)\n        return results\n\n    elif pos == 2:\n        for col in range(total):\n            column = []\n            for row in range(total):\n                if col in range(n) and row in range(n, total):\n                    column.append(sub[col][row - n])\n                else:\n                    column.append(main[col][row])\n            results.append(column)\n        return results\n\n    elif pos == 3:\n        for col in range(total):\n            column = []\n            for row in range(total):\n                if col in range(n, total) and row in range(n, total):\n                    column.append(sub[col - n][row - n])\n                else:\n                    column.append(main[col][row])\n            results.append(column)\n        return results\n\n\ndef matrix_get(main: list, pos: int):\n    \"\"\"\n    Get a subset of a matrix.\n    \"\"\"\n    n = len(main)\n    if n % 2 != 0:\n        print(\"ERROR: Cannot split matrix with odd num of cols/rows. Stop.\")\n        return None\n\n    mid = n // 2\n    sub = []\n\n    if pos == 0:\n        for col in range(mid):\n            column = []\n            for row in range(mid):\n                column.append(main[col][row])\n            sub.append(column)\n        return sub\n\n    elif pos == 1:\n        for col in range(mid):\n            column = []\n            for row in range(mid):\n                column.append(main[mid + col][row])\n            sub.append(column)\n        return sub\n\n    elif pos == 2:\n        for col in range(mid):\n            column = []\n            for row in range(mid):\n                column.append(main[col][mid + row])\n            sub.append(column)\n        return sub\n\n    elif pos == 3:\n        for col in range(mid):\n            column = []\n            for row in range(mid):\n                column.append(main[mid + col][mid + row])\n            sub.append(column)\n        return sub\n\n\nif __name__ == '__main__':\n    a = [[1, 1], [1, 0]]\n    b = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]\n    d = [[1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 5, 6], [0, 0, 7, 8]]\n    c = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]\n\n    h = [[1, 2], [3, 4]]\n    print(matrix_multiply(d, d))\n    print(matrix_power(d, 5))\n    print(matrix_multiply(c, d))\n    print(matrix_identity(4))\n    print(matrix_transpose(b))\n    print(matrix_power(b, 113))\n    print(f\"random matrix: {matrix_generate(8)}\")\n\n    # Add code to do the rest of this problem\n    sizes: list = []\n    runtimes: list = []\n    data = []\n    ns = [2 ** t for t in range(1, 7)]\n\n    titles = {'family': 'serif', 'color': 'blue', 'size': 20}\n    axes = {'family': 'serif', 'color': 'darkred', 'size': 15}\n    power = 4\n    for n in ns:\n        print(f\"Computing with size = {n}, power = {power}\")\n        matrix = matrix_generate(n, 10)\n        sizes.append(n)\n        data.append(timeit(\"matrix_power(matrix, 4)\",\n                                       number=10, globals=globals()))\n\n    # Generate plots\n    plt.subplot(121)\n    plt.grid(True, which=\"both\")\n    plt.title(\"exponential = 4\", fontdict=titles)\n    plt.xlabel(\"size\", fontdict=axes)\n    plt.ylabel(\"runtime\", fontdict=axes)\n    plt.plot(sizes, data, \"--ro\")\n\n    plt.subplot(122)\n    plt.title(\"size = 2\", fontdict=titles)\n    plt.xlabel(\"exponential\", fontdict=axes)\n    plt.ylabel(\"runtime\", fontdict=axes)\n    size = 2\n    maxInt = 10\n    matrix = matrix_generate(size, maxInt)\n    powers = []\n    static_runtimes = []\n    for power in range(600):\n        print(f\"Computing size = 2, power = {power}.\")\n        powers.append(power)\n        static_runtimes.append(timeit(\"matrix_power(matrix, power)\",\n                                       number=10, globals=globals()))\n    plt.plot(powers, static_runtimes, \"--b+\")\n    plt.savefig('./output/matrix-powers.png', dpi=300, transparent=False)\n    plt.show()\n    print(\"FINISHED!\")\n", "meta": {"hexsha": "b59444e7f68e547e91559eef85f8b20b45be1360", "size": 12290, "ext": "py", "lang": "Python", "max_stars_repo_path": "Matrix/matrix.py", "max_stars_repo_name": "siavava/algorithms", "max_stars_repo_head_hexsha": "885a1a622d6d7d6ac185da92a81da7a4133cdb1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Matrix/matrix.py", "max_issues_repo_name": "siavava/algorithms", "max_issues_repo_head_hexsha": "885a1a622d6d7d6ac185da92a81da7a4133cdb1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Matrix/matrix.py", "max_forks_repo_name": "siavava/algorithms", "max_forks_repo_head_hexsha": "885a1a622d6d7d6ac185da92a81da7a4133cdb1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0353535354, "max_line_length": 103, "alphanum_fraction": 0.5541090317, "include": true, "reason": "import numpy,from numpy", "num_tokens": 3290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018448494248, "lm_q2_score": 0.9124361604769413, "lm_q1q2_score": 0.889809427004439}}
{"text": "#For Python 3\n#System of Ordinary Differential Equations: SIR epidemiology model\n\nimport numpy as np\nimport scipy.integrate\nimport matplotlib.pyplot as plt\n\n\"\"\"\nThe system of ODEs that we will solve is (SIR model):\n    S'(t) = -b*S(t)*I(t)/N\n    I'(t) = b*S(t)*I(t)/N - g*I(t)\n    R'(t) = g*I(t)\n    Constants: b, N, g\nInitial Conditions:\n    S(0) = 999\n    I(0) = 1\n    R(0) = 0\nInterval:\n    0 <= t <= 200\n\"\"\"\n\ndef SIR(y,t,b,N,g):\n    S, I, R = y\n    #S = number of susceptible\n    #I = number of infections\n    #R = number of recovered or deceased\n    #N is the total population, b is the average number of contacts per person per time\n    #g is transition (recovery) rate\n    #https://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology#The_SIR_model\n    \n    dydt = [-1*b*S*I/N,\n            b*S*I/N - g*I,\n            g*I]\n    return dydt\n\ndef SIRD(y,t,b,N,g,m):\n    S, I, R, D = y\n    #S = number of susceptible\n    #I = number of infections\n    #R = number of recovered\n    #D = number of deaths\n    #N is the total population, b is the average number of contacts per person per time\n    #g is recovery rate, m is the mortality rate\n    #https://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology#The_SIRD_model\n    \n    dydt = [-1*b*S*I/N,\n            b*S*I/N - g*I - m*I,\n            g*I,\n            m*I]\n    return dydt\n\ndef solve_SIRmodel(b,N,g,ti,tf,y0_SIR,solve_SIR=True,m=0,y0_SIRD=[]):\n    \"\"\"\n    INPUT:\n    b, N, g, ti, tf, y0_SIRD        #see SIR function\n    OPTIONAL INPUT:\n    ::boolean:: solve_SIR           #whether or not to solve SIR, default True; if False, solve for SIRD system\n    m, y0_SIRD                      #see SIRD function\n    \"\"\"\n    t = np.linspace(ti, tf, 5000)\n    if solve_SIR == True:\n        #https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html\n        #SIR model:\n        sol_SIR = scipy.integrate.odeint(SIR, y0_SIR, t, args=(b, N, g))\n        plt.title('SIR Model')\n        plt.plot(t, sol_SIR[:,0], 'y', label='S(t)')\n        plt.plot(t, sol_SIR[:,1], 'r', label='I(t)')\n        plt.plot(t, sol_SIR[:,2], 'b', label='R(t)')\n        plt.legend(loc='best')\n        plt.xlabel('t')\n        plt.grid()\n        plt.show()\n    else:\n        #SIRD model (includes death rate):\n        sol_SIRD = sol_SIR = scipy.integrate.odeint(SIRD, y0_SIRD, t, args=(b, N, g, m))\n        plt.title('SIRD Model')\n        plt.plot(t, sol_SIRD[:,0], 'y', label='S(t)')\n        plt.plot(t, sol_SIRD[:,1], 'r', label='I(t)')\n        plt.plot(t, sol_SIRD[:,2], 'b', label='R(t)')\n        plt.plot(t, sol_SIRD[:,3], 'black', label='D(t)')\n        plt.legend(loc='best')\n        plt.xlabel('t')\n        plt.grid()\n        plt.show()\n\ndef main():\n    b = 0.2\n    N = 1000\n    g = 0.1 \n    \n    y0_SIR = [999,1,0] #Initial Conditions for SIR model\n    \n    m = 0.02\n    y0_SIRD = [999,1,0,0] #Initial Conditions for SIRD model\n    \n    #set of b and g values to plot\n    b_set = [0.2,0.5,0.12,0.4]\n    g_set = [0.1,0.1,0.07,0.3]\n    try:\n        assert(len(b_set) == len(g_set)) #check if both lists are same length\n    except AssertionError:\n        print(\"ERROR: Lists not the same length\")\n        return False\n    \n    #Interval\n    ti = 0\n    tf = 200\n    \n    for i in range(0,len(b_set),1):\n        solve_SIRmodel(b_set[i],N,g_set[i],ti,tf,y0_SIR)\n\n    solve_SIRmodel(b,N,g,ti,tf,y0_SIR,False,m,y0_SIRD)\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "7208cc95883f49f7d58aae2ae1067e2cd8a0ad9f", "size": 3413, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment2_2020/question2_SIR.py", "max_stars_repo_name": "mattleung10/CTA200", "max_stars_repo_head_hexsha": "a88e0a60f35143cbefa4ec9fc10b091664ef06f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment2_2020/question2_SIR.py", "max_issues_repo_name": "mattleung10/CTA200", "max_issues_repo_head_hexsha": "a88e0a60f35143cbefa4ec9fc10b091664ef06f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment2_2020/question2_SIR.py", "max_forks_repo_name": "mattleung10/CTA200", "max_forks_repo_head_hexsha": "a88e0a60f35143cbefa4ec9fc10b091664ef06f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4224137931, "max_line_length": 111, "alphanum_fraction": 0.5681218869, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290938892911, "lm_q2_score": 0.9161096050004511, "lm_q1q2_score": 0.8896606906073645}}
{"text": "import numpy as np\n\n\ndef QRDecomposition(A):\n\tn = np.shape(A)[0] #pegando o tamanho das linhas de A\n\tm = np.shape(A)[1] #pegando o tamanho das colunas de A\n\tQ = np.zeros((n,m)) #declarando a matriz Q\n\tR = np.zeros((m,m)) #declarando a matriz R\n\t\n\tfor j in range(0, m):\n\t\tA_column = A[:, j] #pegando as colunas da matriz A\n\t\tV = np.zeros(n) #declarando o vetor V\n\t\tV = A_column #V igual a coluna j de A\n\t\tfor i in range (0, j):\n\t\t\tR[i,j] = Q[:,i].dot(A_column) #fazendo o calculo do R[i,j] = coluna i de Q * coluna j de A ( i != j)\n\t\t\tV -= (Q[:,i].dot(A_column))*Q[:,i] #fazendo o calculo de V \t\t\t\n\t\tR[j,j] = np.linalg.norm(V) # R[j,j] = norma da coluna j de A (i == j)\t\n\t\tQ[:,j] = V/np.linalg.norm(V) #normalizando V e atribuindo a coluna j de Q\n\t\t\n\treturn Q, R\t\t\t\n\n\ndef QRDecompositionModificada(A):\n\tn = np.shape(A)[0] #pegando o tamanho das linhas de A\n\tm = np.shape(A)[1] #pegando o tamanho das colunas de A\n\tQ = np.zeros((n,m)) #declarando a matriz Q\n\tR = np.zeros((m,m)) #declarando a matriz R\n\tV = np.copy(A) #copiando A para V\n\n\tfor j in range(0, m):\n\t\tfor i in range (0, j):\n\t\t\tR[i,j] = Q[:,i].dot(V[:,j]) #fazendo o calculo do R[i,j] = coluna i de Q * coluna j de V ( i != j)\n\t\t\tV[:,j] -= (Q[:,i].dot(V[:,j]))*Q[:,i] #fazendo o calculo de V \t\t\t\n\t\tR[j,j] = np.linalg.norm(V[:,j]) # R[j,j] = norma da coluna j de V (i == j)\t\n\t\tQ[:,j] = V[:,j]/np.linalg.norm(V[:,j]) #normalizando V e atribuindo a coluna j de Q\n\t\t\n\treturn Q, R\t\t\t\n\n\n\n\nA = np.array([[1,2],[1,3],[-2,0]], dtype='double')\nB = np.array([[3,1], [4,-1]], dtype = 'double')\n\nprint('Decomposicao QR classica\\n')\n\n(Q, R) = QRDecomposition(A)\nprint('{}\\n\\n{}\\n\\n{}'.format(Q, R, Q.dot(R)))\nprint('\\n')\n(Q, R) = QRDecomposition(B)\nprint('{}\\n\\n{}\\n\\n{}'.format(Q, R, Q.dot(R)))\n\nprint('\\n\\n')\n\nA = np.array([[1,2],[1,3],[-2,0]], dtype='double')\nB = np.array([[3,1], [4,-1]], dtype = 'double')\n\nprint('Decomposicao QR do Python\\n')\n\n(Q_python,R_python) = np.linalg.qr(A)\nprint('{}\\n\\n{}\\n\\n{}'.format(Q_python, R_python, Q_python.dot(R_python)))\nprint('\\n')\n(Q_python,R_python) = np.linalg.qr(B)\nprint('{}\\n\\n{}\\n\\n{}'.format(Q_python, R_python, Q_python.dot(R_python)))\n\nprint('\\n\\n')\n\nA = np.array([[1,2],[1,3],[-2,0]], dtype='double')\nB = np.array([[3,1], [4,-1]], dtype = 'double')\n\nprint('Decomposicao QR modificada\\n')\n\n(Q, R) = QRDecompositionModificada(A)\nprint('{}\\n\\n{}'.format(Q, R))\nprint('\\n')\n(Q, R) = QRDecomposition(B)\nprint('{}\\n\\n{}'.format(Q, R))\n\n\n\n", "meta": {"hexsha": "e6b56d914513e4b3037f8049b84067c644cd368e", "size": 2431, "ext": "py", "lang": "Python", "max_stars_repo_path": "QRDecomposition.py", "max_stars_repo_name": "igortakeo/Calculo-Numerico", "max_stars_repo_head_hexsha": "96ed1892c3d2ba80039f2f2ce7de4ca834aa6283", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QRDecomposition.py", "max_issues_repo_name": "igortakeo/Calculo-Numerico", "max_issues_repo_head_hexsha": "96ed1892c3d2ba80039f2f2ce7de4ca834aa6283", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QRDecomposition.py", "max_forks_repo_name": "igortakeo/Calculo-Numerico", "max_forks_repo_head_hexsha": "96ed1892c3d2ba80039f2f2ce7de4ca834aa6283", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.012345679, "max_line_length": 103, "alphanum_fraction": 0.5874125874, "include": true, "reason": "import numpy", "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350252, "lm_q2_score": 0.9230391605990603, "lm_q1q2_score": 0.889606630636603}}
{"text": "import numpy as np\nfrom math import log2\n\ndef mean(X):\n    \"\"\" Average value of a series of data \"\"\"\n    X = np.array(X)\n    return (np.sum(X) / len(X))\n\n\ndef softmax(X):\n    exps = np.exp(X - np.max(X))\n    return exps / np.sum(exps)\n\ndef softmax_grad(softmax):\n    # Reshape the 1-d softmax to 2-d so that np.dot will do the matrix multiplication\n    s = softmax.reshape(-1,1)\n    return np.diagflat(s) - np.dot(s, s.T)\n\ndef stablesoftmax(x):\n    \"\"\"Compute the softmax of vector x in a numerically stable way.\"\"\"\n    shiftx = x - np.max(x)\n    exps = np.exp(shiftx)\n    return exps / np.sum(exps)\n\ndef cross_entropy(y_hat, y):\n    eps = 1e-15\n    y = np.squeeze(y)\n    c = sum((y * np.log(y_hat + eps)) + ((1 - y) * np.log(1 - y_hat + eps))) / -len(y)\n    return c\n\ndef sigmoid(X):\n    \"\"\" Sigmoid Function \"\"\"\n    return (1 / (1 + np.exp(-X)))\n\n\ndef relu(X):\n    if (isinstance(X, np.ndarray)):\n        return np.array([max(n, 0) for n in X])\n    else:\n        return max(X, 0)\n\n\ndef delta_cross_entropy(X,y):\n    \"\"\"\n    X is the output from fully connected layer (num_examples x num_classes)\n    y is labels (num_examples x 1)\n    \tNote that y is not one-hot encoded vector. \n    \tIt can be computed as y.argmax(axis=1) from one-hot encoded vectors of labels if required.\n    \"\"\"\n    m = y.shape[0]\n    grad = softmax(X)\n    grad[range(m),y] -= 1\n    grad = grad/m\n    return grad\n\ndef softmax_crossentropy_with_logits(logits, reference_answers):\n    logits_for_answers = logits[np.arange(len(logits)), reference_answers]\n    xentropy = - logits_for_answers + np.log(np.sum(np.exp(logits) + 1e-14, axis=-1))\n    return xentropy\n\n\ndef grad_softmax_crossentropy_with_logits(logits, reference_answers):\n    ones_for_answers = np.zeros_like(logits)\n    ones_for_answers[np.arange(len(logits)), reference_answers] = 1\n\n    softmax = np.exp(logits) / np.exp(logits).sum(axis=-1, keepdims=True)\n\n    return (- ones_for_answers + softmax) / logits.shape[0]\n\n\nif __name__ == '__main__':\n    X = np.array([1, 2, 3, 4, 5])\n    z = [1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0]\n    print(sigmoid(X))\n    print(softmax(z))\n    y = np.array([0.1, 0.3])\n    ypred = np.array([0.5, 0.6])\n\n    print()\n    print(cross_entropy(y, ypred))\n    x2 = np.array([-1, -2.8, -0, 1.4, 1])\n    print(relu(x2))\n", "meta": {"hexsha": "dd0530d6f9c85f77dd45f9d4ec5b1c94e3b3354b", "size": 2278, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/ft_math.py", "max_stars_repo_name": "d-r-e/multilayer-perceptron", "max_stars_repo_head_hexsha": "6e5f751d4c2332267ffa9d9a1104cc6299f125c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ft_math.py", "max_issues_repo_name": "d-r-e/multilayer-perceptron", "max_issues_repo_head_hexsha": "6e5f751d4c2332267ffa9d9a1104cc6299f125c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ft_math.py", "max_forks_repo_name": "d-r-e/multilayer-perceptron", "max_forks_repo_head_hexsha": "6e5f751d4c2332267ffa9d9a1104cc6299f125c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4457831325, "max_line_length": 95, "alphanum_fraction": 0.6211589113, "include": true, "reason": "import numpy", "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446494481299, "lm_q2_score": 0.913676521650809, "lm_q1q2_score": 0.8895962566316886}}
{"text": "#ZADANIE 2\n#Wykorzystaj metode eliminacji Gaussa do znalezienia\n#rozwiazan ukladow rownan a) – d). Wykonaj obliczenia przy\n#uzyciu udostepnionej funkcji i programu napisanego w Python.\n#Przeanalizuj i opisz w sprawozdaniu dzialanie funkcji realizującej\n#metodę eliminacji Gaussa.\n\nimport numpy as np\n\ndef gaussElimin(a,b):\n    n = len(b)\n    #procedura eliminacji\n    for k in range(0, n-1):\n        for i in range(k+1, n):\n            if a[i, k] != 0.0:\n                lam = a[i, k] / float(a[k, k])\n                a[i, k+1:n] = a[i, k+1:n] - lam * a[k, k+1:n]\n                b[i] = b[i] - lam * b[k]\n    #procedura wyliczania rozwiazania i zapisu do macierzy b\n    for k in range(n-1, -1, -1):\n        b[k] = (b[k] - np.dot(a[k, k+1:n], b[k+1:n])) / float(a[k, k])\n    return b\n    \ndef testA():\n    #macierze jako float\n    a = np.array([[3.0, 1.0, -1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 5.0]])\n    b = np.array([181.05, 108.35, 142.55])\n    print('Rozwiazanie(np.linalg.solve):')\n    print(np.linalg.solve(a, b))\n    Iout = gaussElimin(a,b)\n    print('Rozwiazanie(gaussElimin):')\n    print(Iout)\n    \ndef testB():\n    #macierze jako float\n    a = np.array([[1.0, -1.0, 2.0], [3.0, 2.0, 1.0], [2.0, -3.0, -2.0]])\n    b = np.array([5.0, 10.0, -10.0])\n    print('Rozwiazanie(np.linalg.solve):')\n    print(np.linalg.solve(a, b))\n    Iout = gaussElimin(a,b)\n    print('Rozwiazanie(gaussElimin):')\n    print(Iout)\n    \ndef testC():\n    #macierze jako float\n    a = np.array([[5.0, 1.0, 1.0, 1.0], [2.0, -1.0, -1.0, 1.0], [3.0, -1.0, 2.0, -2.0], [5.0, -4.0, 3.0, -2.0]])\n    b = np.array([685.0, 165.0, 256.0, 361.0])\n    print('Rozwiazanie(np.linalg.solve):')\n    print(np.linalg.solve(a, b))\n    Iout = gaussElimin(a,b)\n    print('Rozwiazanie(gaussElimin):')\n    print(Iout) \n    \ndef testD():\n    #macierze jako float\n    a = np.array([[1.0, 3.0, 5.0], [2.0, 5.0, 1.0], [2.0, 3.0, 8.0]])\n    b = np.array([10.0, 8.0, 3.0])\n    print('Rozwiazanie(np.linalg.solve):')\n    print(np.linalg.solve(a, b))\n    Iout = gaussElimin(a,b)\n    print('Rozwiazanie(gaussElimin):')\n    print(Iout)\n\nif __name__ == \"__main__\":\n    print(30 * '-')\n    print(\"Funkcja A\")\n    testA()\n    print(30 * '-')\n    \n    print(30 * '-')\n    print(\"Funkcja B\")\n    testB()\n    print(30 * '-')\n    \n    print(30 * '-')\n    print(\"Funkcja C\")\n    testC()\n    print(30 * '-')\n    \n    print(30 * '-')\n    print(\"Funkcja D\")\n    testD()\n    print(30 * '-')\n    \n#Funkcja napisana samodzielnie w Python zwraca identyczne wyniki\n#jak funkcja biblioteczna numpy.linalg.solve().\n#Metoda eliminacji Gaussa wykorzystuje dwie fazy obliczen.\n#Pierwsza faza jest faza eliminacji, ktora sprowadza problem obliczeniowy do Ux = c.\n#Druga faza jest faza wstecznego podstawienia, ktora polega na podstawianiu\n#uzyskanych rozwiazan za niewiadome.\n#Wystepujaca w programie funkcja sklada sie z dwoch algorytmow.\n#Pierwszy algorytm realizuje faze eliminacji.\n#Drugi algorytm odpowiada za wyliczenie rozwiazan i ich zapis do macierzy b.", "meta": {"hexsha": "f8395460ff79475c107bd4789e13c109550b99b7", "size": 2986, "ext": "py", "lang": "Python", "max_stars_repo_path": "MN_lab_11/MN_lab11_zad_2.py", "max_stars_repo_name": "matbocz/kurs-mn-python-pwsz-elblag", "max_stars_repo_head_hexsha": "629d778be7c5d3b6cc217b7ba48e2e0d55ccdf36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MN_lab_11/MN_lab11_zad_2.py", "max_issues_repo_name": "matbocz/kurs-mn-python-pwsz-elblag", "max_issues_repo_head_hexsha": "629d778be7c5d3b6cc217b7ba48e2e0d55ccdf36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MN_lab_11/MN_lab11_zad_2.py", "max_forks_repo_name": "matbocz/kurs-mn-python-pwsz-elblag", "max_forks_repo_head_hexsha": "629d778be7c5d3b6cc217b7ba48e2e0d55ccdf36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1075268817, "max_line_length": 112, "alphanum_fraction": 0.5931011386, "include": true, "reason": "import numpy", "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854103128329, "lm_q2_score": 0.9173026584553408, "lm_q1q2_score": 0.8895867350111651}}
{"text": "#gradient descent learning\n#steven 29/02/2020 Initial\n#11/03/2020  add plotSeekPoint to plot the seek process\n#import random\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom plotCommon import plotSub\n\ndef difference_derivative(f,x,h=0.00001): #one parameter fuction derivate\n    return (f(x+h)-f(x))/h\n\ndef question_linearFuc(x):\n    a = 6.5   #must a > 0\n    b = 1.88 #the final optimum x\n    c = -8.8  #the final minimum value\n    return a*(x - b)**2 + c\n\ndef question_linearFucMin():\n    \"\"\"seek x, make f(x) = ax^2 + bx + c (a>0)  minimize\n    this fuction is always as the simplest(one feature data) cost fuction in machine learning\n    \"\"\"\n\n    #tolerance = 0.0000000001  #1.0e-15\n    #max_iter = 10000\n    iter = 0\n    alpha = 0.001 #0.01 #learning rate\n    seekList=[]\n\n    x = -10  #random.random()\n    stepInter = 0\n    while True:\n        gradient = difference_derivative(question_linearFuc,x,h=0.0001)\n\n        x_next = x - alpha * gradient\n\n        if iter % 20 == 0:\n            print(iter,\" :\",x,gradient,x_next,question_linearFuc(x),stepInter)\n            seekList.append(x)\n\n        #stepInter = (question_linearFuc(x) - question_linearFuc(x_next))**2\n        stepInter = abs(question_linearFuc(x) - question_linearFuc(x_next))\n        #if (stepInter < tolerance) or (iter > max_iter) :\n        #if (stepInter - tolerance == 0) or (iter > max_iter) :\n        #if (stepInter == 0) or (iter > max_iter) or (x - x_next == 0):\n        if (stepInter == 0) or (x - x_next == 0):\n            break\n\n        x = x_next\n        iter += 1\n\n    print (iter,'result: x=',x, 'minValue:',question_linearFuc(x))\n\n    plotSeekPoint(seekList)\n\ndef plotSeekPoint(seekList):\n    _, ax = plt.subplots()\n\n    x = np.linspace(-10,10,20)\n    y = question_linearFuc(x)\n    ax.plot(x,y) #plot function curve\n\n    print(len(seekList))\n    x = np.array(seekList)\n    y = question_linearFuc(x)\n    ax.scatter(x, y, s=10, color='r', alpha=0.75) #plot seekpoint in the seeking process\n    plt.show()\n\ndef question_CurvePeakAndValley():\n    \"\"\"seek x, findout all curve's peak and valleys, that is where the derivative equal to 0\"\"\"\n    def func(x):\n        #return x**4\n        #return  (x**3 + 3*x**2-6*x-8)/4\n        return x**5 + 2*x**4 + 3*x**3 + 8*x**2 + 10*x\n\n    x = np.linspace(-1.25,-0.65, 100)\n    z0=[]\n    for i, _ in enumerate(x):\n        if i>=len(x)-1:\n            break\n        d1 = difference_derivative(func,x[i])\n        d2 = difference_derivative(func,x[i+1])\n        if d1*d2<=0:\n            print('x = ',x[i])\n            z0.append(x[i])\n        #print('d1,d2,* = ',d1,d2,d1*d2)\n\n    ax = plt.subplot(1,1,1)\n    plotSub(x, func(x), ax, label='func',color='b')\n    for k in z0:\n        plt.vlines(k, np.min(func(x)), func(x[-1]),linestyles='dotted', color='r')\n    #plt.axis('square')\n    plt.legend()\n    plt.grid()\n    plt.show()\n\ndef main():\n    #question_linearFucMin()\n    question_CurvePeakAndValley()\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "3bdaf70d97d2ff01dfa68fa93a6df64999b28517", "size": 2962, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/gradientTest.py", "max_stars_repo_name": "StevenHuang2020/ML", "max_stars_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gradientTest.py", "max_issues_repo_name": "StevenHuang2020/ML", "max_issues_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gradientTest.py", "max_forks_repo_name": "StevenHuang2020/ML", "max_forks_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0392156863, "max_line_length": 95, "alphanum_fraction": 0.5945307225, "include": true, "reason": "import numpy", "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551566309689, "lm_q2_score": 0.9219218428996602, "lm_q1q2_score": 0.8895210441324631}}
{"text": "import numpy as np\nimport decimal\nimport matplotlib.pyplot as plt\n\ndef trapezoid(f, a, b, pieces, graph=False):\n    \"\"\"Find the integral of the function f between a and b using pieces trapezoids\n    Args:\n        f: function to integrate\n        a: lower bound of integral\n        b: upper bound of integral\n        pieces: number of pieces to chop [a,b] into\n        \n    Returns:\n        estimate of integral\n    \"\"\"\n    integral = 0\n    h = b - a\n    if (graph):\n        x = np.linspace(a,b,100)\n        plt.plot(x,f(x),label=\"f(x)\")\n        ax = plt.subplot(111)\n    #initialize the left function evaluation\n    fa = f(a)\n    for i in range(pieces):\n        #evaluate the function at the left end of the piece\n        fb = f(a+(i+1)*h/pieces)\n        integral += 0.5*h/pieces*(fa + fb)\n        if (graph):\n            verts = [(a+i*h/pieces,0),(a+i*h/pieces,fa), (a+(i+1)*h/pieces,fb),(a+(i+1)*h/pieces,0)]\n            poly = Polygon(verts, facecolor='0.8', edgecolor='k')\n            ax.add_patch(poly)\n        #now make the left function evaluation the right for the next step\n        fa = fb\n        \n    if (graph):\n        ax.set_xticks((a,b))\n        ax.set_xticklabels(('a','b'))\n        plt.xlabel(\"x\")\n        plt.ylabel(\"f(x)\")\n        if (pieces > 1):\n            plt.title(\"Trapezoid Rule with \" + str(pieces) + \" pieces\")\n        else:\n            plt.title(\"Trapezoid Rule with \" + str(pieces) + \" piece\")\n        plt.show()\n    return integral\n\ndef trapezoid_rec(f, a, b, epsilon = 1.0e-6, old = -1.0e16, depth=0, graph=False):\n    \"\"\"Find the integral of the function f between a and b using pieces trapezoids\n    Args:\n        f: function to integrate\n        a: lower bound of integral\n        b: upper bound of integral\n        old: keeps track of how much the estimate changes from recursion to level\n        depth: how many levels of recursion do we have, python only allows so many\n        \n    Returns:\n        estimate of integral\n    \"\"\"\n    h = b - a\n    #break interval into two pieces and do trapezoid on each\n    if (graph) and (depth == 0):\n        x = np.linspace(a,b,100)\n        plt.plot(x,f(x),label=\"f(x)\")\n        \n    new_estimate_left = 0.25*h*(f(a) + f(a+0.5*h))\n    new_estimate_right = 0.25*h*(f(a+0.5*h) + f(b))\n\n    \n    \n    #check to see if the sum of the two pieces is close to the old guess\n    if (np.fabs(new_estimate_left + new_estimate_right - old) > epsilon) and (depth < 100):\n        #if not, then call trapezoid_rec again on each half-interval\n        integral = (trapezoid_rec(f,a,a+0.5*h,epsilon=epsilon, old=new_estimate_left,depth=depth+1,graph=graph) + \n                    trapezoid_rec(f,a+0.5*h,b,epsilon=epsilon,old=new_estimate_right,depth=depth+1,graph=graph))\n\n        return integral\n    else:\n        #halving the interval didn't change much so we can stop\n            \n        if (graph):\n            ax = plt.subplot(111)\n            verts = [(a,0),(a,f(a)), (a+0.5*h,f(a+0.5*h)),(a+0.5*h,0)]\n            poly = Polygon(verts, facecolor='0.8', edgecolor='k')\n            ax.add_patch(poly)\n            verts = [(a+0.5*h,0),(a+0.5*h,f(a+0.5*h)), (b,f(b)),(b,0)]\n            poly = Polygon(verts, facecolor='0.8', edgecolor='k')\n            ax.add_patch(poly)\n            \n        if (graph) and (depth == 0):\n            ax.set_xticks((a,b))\n            ax.set_xticklabels(('a','b'))\n            plt.xlabel(\"x\")\n            plt.ylabel(\"f(x)\")\n            plt.title(\"Trapezoid Rule with recursion\")\n            plt.show()\n        return new_estimate_left + new_estimate_right\n\ndef quadratic_interp(a,f,x):\n    \"\"\"Compute at quadratic interpolant\n    Args:\n        a: array of the 3 points\n        f: array of the value of f(a) at the 3 points\n    Returns:\n        The value of the linear interpolant at x\n    \"\"\"\n    answer = (x-a[1])*(x-a[2])/(a[0]-a[1])/(a[0]-a[2])*f[0] \n    answer += (x-a[0])*(x-a[2])/(a[1]-a[0])/(a[1]-a[2])*f[1] \n    answer += (x-a[0])*(x-a[1])/(a[2]-a[0])/(a[2]-a[1])*f[2] \n    return answer\n\ndef simpsons(f, a, b, pieces, graph=False):\n    \"\"\"Find the integral of the function f between a and b using Simpson's rule\n    Args:\n        f: function to integrate\n        a: lower bound of integral\n        b: upper bound of integral\n        pieces: number of pieces to chop [a,b] into\n        \n    Returns:\n        estimate of integral\n    \"\"\"\n    integral = 0\n    h = b - a\n    one_sixth = 1.0/6.0\n    if (graph):\n        x = np.linspace(a,b,100)\n        plt.plot(x,f(x),label=\"f(x)\")\n        ax = plt.subplot(111)\n    \n    #initialize the left function evaluation\n    fa = f(a)\n    for i in range(pieces):\n        #evaluate the function at the left end of the piece\n        fb = f(a+(i+1)*h/pieces)\n        fmid = f(0.5*(a+(i+1)*h/pieces+ a+i*h/pieces))\n        integral += one_sixth*h/pieces*(fa + 4*fmid + fb)\n        if (graph):\n            ix = np.arange(a+i*h/pieces, a+(i+1)*h/pieces, 0.001)\n            iy = quadratic_interp(np.array([a+i*h/pieces,0.5*(a+(i+1)*h/pieces+ a+i*h/pieces),a+(i+1)*h/pieces]),\n                                  np.array([fa,fmid,fb]),ix)\n            verts = [(a+i*h/pieces,0)] + list(zip(ix,iy)) + [(a+(i+1)*h/pieces,0)]\n            poly = plt.Polygon(verts, facecolor='0.8', edgecolor='k')\n            ax.add_patch(poly)\n        #now make the left function evaluation the right for the next step\n        fa = fb\n        \n    if (graph):\n        ax.set_xticks((a,b))\n        ax.set_xticklabels(('a','b'))\n        plt.xlabel(\"x\")\n        plt.ylabel(\"f(x)\")\n        plt.title(\"Simpsons Rule with \" + str(pieces) + \" pieces\")\n        plt.show()\n    return integral\n\ndef RichardsonExtrapolation(fh, fhn, n, k):\n    \"\"\"Compute the Richardson extrapolation based on two approximations of order k\n    where the finite difference parameter h is used in fh and h/n in fhn.\n    Inputs:\n    fh:  Approximation using h\n    fhn: Approximation using h/n\n    n:   divisor of h\n    k:   original order of approximation\n    \n    Returns:\n    Richardson estimate of order k+1\"\"\"\n    n = decimal.Decimal(n)\n    k = decimal.Decimal(k)\n    numerator = decimal.Decimal(n**k * decimal.Decimal(fhn) - decimal.Decimal(fh))\n    denominator = decimal.Decimal(n**k - decimal.Decimal(1.0))\n    return float(numerator/denominator)\n\ndef Romberg(f, a, b, MaxLevels = 10, epsilon = 1.0e-6, PrintMatrix = False):\n    \"\"\"Compute the Romberg integral of f from a to b\n    Inputs:\n    f:  integrand function\n    a: left edge of integral\n    b: right edge of integral\n    MaxLevels: Number of levels to take the integration to\n    \n    Returns:\n    Romberg integral estimate\"\"\"\n    \n    estimate = np.zeros((MaxLevels,MaxLevels))\n    \n    estimate[0,0] = trapezoid(f,a,b,pieces=1)\n    count = 1\n    converged = 0\n    while not(converged):\n        estimate[count,0] = trapezoid(f,a,b,pieces=2**count)\n        for extrap in range(count):\n            estimate[count,1+extrap] = RichardsonExtrapolation(estimate[count-1,extrap],\n                                                               estimate[count,extrap],2,2**(extrap+1))\n        \n        converged = np.fabs(estimate[count,count] - estimate[count-1,count-1]) < epsilon\n        if (count == MaxLevels-1): converged = 1\n        count += 1\n    if (PrintMatrix):\n        print(estimate[0:count,0:count])\n    return estimate[count-1, count-1]\n\ndef RombergSimpson(f, a, b, MaxLevels = 10, epsilon = 1.0e-6, PrintMatrix = False):\n    \"\"\"Compute the Romberg integral of f from a to b\n    Inputs:\n    f:  integrand function\n    a: left edge of integral\n    b: right edge of integral\n    MaxLevels: Number of levels to take the integration to\n    \n    Returns:\n    Romberg integral estimate\"\"\"\n    \n    estimate = np.zeros((MaxLevels,MaxLevels))\n    \n    estimate[0,0] = simpsons(f,a,b,pieces=1)\n    count = 1\n    converged = 0\n    while not(converged):\n        estimate[count,0] = simpsons(f,a,b,pieces=2**count)\n        for extrap in range(count):\n            estimate[count,1+extrap] = RichardsonExtrapolation(estimate[count-1,extrap],\n                                                               estimate[count,extrap],n=2,k=2+2.0**(extrap+1))\n        \n        converged = np.fabs(estimate[count,count] - estimate[count-1,count-1]) < epsilon\n        if (count == MaxLevels-1): converged = 1\n        count += 1\n    if (PrintMatrix):\n        print(estimate[0:count,0:count])\n    return estimate[count-1, count-1]", "meta": {"hexsha": "27dbd3b992f87d7155f613a8935106d6d33f3f11", "size": 8356, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch15.py", "max_stars_repo_name": "DrRyanMc/CompNucEng", "max_stars_repo_head_hexsha": "55d36abea64c9298092dee0b539bfaccae3f49a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-09-29T19:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T20:08:08.000Z", "max_issues_repo_path": "ch15.py", "max_issues_repo_name": "AllSafeCyberSecur1ty/Nuclear-Engineering", "max_issues_repo_head_hexsha": "302d6dcc7c0a85a9191098366b076cf9cb5a9f6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-04-07T02:26:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-18T23:04:31.000Z", "max_forks_repo_path": "ch15.py", "max_forks_repo_name": "DrRyanMc/CompNucEng", "max_forks_repo_head_hexsha": "55d36abea64c9298092dee0b539bfaccae3f49a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-03T17:34:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T03:48:45.000Z", "avg_line_length": 36.4890829694, "max_line_length": 114, "alphanum_fraction": 0.5719243657, "include": true, "reason": "import numpy", "num_tokens": 2401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551515780319, "lm_q2_score": 0.9219218407544306, "lm_q1q2_score": 0.8895210374042144}}
{"text": "# 面试题9：斐波那契数列题目一：写一个函数，输入n，\n# 求斐波那契（Fibonacci）数列的第n项。斐波那契数列的定义如下：\nimport numpy as np\ndef fib(n):\n    if n <= 2:\n        return 1 \n    \n    return fib(n-1)+fib(n-2)\n\nmemo = {}\ndef fib_memo(n):\n    if n <= 2:\n        return 1 \n    if n in memo:\n        return memo[n]\n    \n    memo[n] = fib(n-1)+fib(n-2)\n    \n    return memo[n]\n\n\ndef fib_iter(n):\n    \n    a,b = 1,1 \n    \n    if n <= 2:\n        return 1 \n    \n    for _ in range(n-2):\n        a,b = b,a+b\n    \n    return b \n\n\ndef matrixMulti(A,B):\n    length = len(A)\n    width = len(B[0])\n    res = [[0]*width for _ in range(length)]\n    print(res)\n    for i in range(length):\n        for j in range(width):\n            for k in range(len(B)):\n                # print(\"i:{},j:{},k:{}\".format(i,j,k))\n                # print(\"\".format(i,k,A[i][k],k,j,B[k][j]))\n                # print(\"res[{}][{}]:{}\".format(i,j,res[i][j]))\n                res[i][j] += A[i][k] * B[k][j]\n                # print(\"A[{}][{}]:{}*B[{}][{}]:{}=res[{}][{}]:{}\".format(i,k,A[i][k],k,j,B[k][j],i,j,res[i][j]))\n    return res \n\ndef fibLog(matrix,n):\n    \n    res = [[1,0],[0,1]]\n    \n    tmp = matrix \n    \n    while n > 0:\n        \n        if n & 1 != 0:\n            res = np.dot(res,tmp)\n        \n        tmp = np.dot(tmp,tmp)\n        \n        n >>= 1 \n    return res\n    \n    \n    # if n == 0:\n    #     return [[1,0],[0,1]]\n\n    # if n == 1:\n    #     return matrix\n    \n    # res = fibLog(matrix,n>>1)\n    \n    # res = np.dot(res,res)\n    \n    # if n & 0x1 == 1:\n    #     res = np.dot(matrix,res)\n\n    \n    return res\n\n    \n    \n            \n               \n\n\nif __name__ == \"__main__\":\n    # print(fib(5))\n    # print(fib(10))\n    # print(fib_memo(10))\n    # print(fib_iter(10))\n    \n    # A = [[1,2,3],[4,5,6]]\n    # B = [[1,2],[3,4],[5,6]]\n    # print(matrixMulti(A,B))\n    # print(matrixMulti([[1,1],[1,0]],[[1,1],[1,0]]))\n    print(fibLog([[1,1],[1,0]],3))\n    # print(np.dot([[1,1],[1,0]],[[1,1],[1,0]]))", "meta": {"hexsha": "42bc6612078a2ebe7d7c4c0835ec33c9e9333a4e", "size": 1940, "ext": "py", "lang": "Python", "max_stars_repo_path": "题源分类/剑指offer/python/面试题9：斐波那契数列.py", "max_stars_repo_name": "ZhengyangXu/Algorithm-Daily-Practice", "max_stars_repo_head_hexsha": "3017a3d476fc9a857026190ea4fae2911058df59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "题源分类/剑指offer/python/面试题9：斐波那契数列.py", "max_issues_repo_name": "ZhengyangXu/Algorithm-Daily-Practice", "max_issues_repo_head_hexsha": "3017a3d476fc9a857026190ea4fae2911058df59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "题源分类/剑指offer/python/面试题9：斐波那契数列.py", "max_forks_repo_name": "ZhengyangXu/Algorithm-Daily-Practice", "max_forks_repo_head_hexsha": "3017a3d476fc9a857026190ea4fae2911058df59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4, "max_line_length": 113, "alphanum_fraction": 0.4072164948, "include": true, "reason": "import numpy", "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813488829418, "lm_q2_score": 0.9304582521195071, "lm_q1q2_score": 0.8895007349404708}}
{"text": "#########################################################################\n#            SIMPSON'S RULES                    \n#                                  \n# This module (based on Mike Zingale's code)\n#    1) calculates the integral of f(x) = sin (pi x) over the \n#     interval [0,1], using N = 3,7,15 and 31 slabs/intervals, for odd Ns.\n#    2) Plots the absolute error vs delta = (b-a)/N.\n#\n#    (Marina von Steinkirch, spring 2013)\n#########################################################################\n\nimport math\nimport numpy\nimport pylab\n\n\n\n\"\"\" Functions \"\"\"\n\ndef func(x):\n    \"\"\" function to integrate\"\"\"\n    fx = numpy.sin(math.pi*x)\n    return fx\n\n\ndef exact_int(a,b):\n    \"\"\" analytic value of the integral \"\"\"\n    I = (numpy.cos(math.pi*a) - numpy.cos(math.pi*b ))/math.pi\n    return I\n\n\ndef simpson_int_odd(a,b,f,N): \n    \"\"\" calculates remaining odd slabs \"\"\"\n    xedge = numpy.linspace(a,b,N+1)\n    delta = xedge[1] - xedge[0]\n    Is_odd = (delta/12.0)*(-f(xedge[N-2]) + 8.0*f(xedge[N-1]) + 5.0*f(xedge[N]))\n    return Is_odd\n\n\ndef simpson_int(a,b,f,N):\n    \"\"\"\"do a Simpson's integration by breaking up the domain [a,b] into N, considering N is even.\"\"\"\n    # MZ -- you were passing in the wrong N, so the xedge was wrong\n    xedge = numpy.linspace(a,b,N+1)\n    delta = xedge[1] - xedge[0]\n    Is = 0.0\n    n = 0\n    # MZ: with the proper N, this loop executed too many times\n    while n < N-1:\n        Is += (delta/3.0)*(f(xedge[n]) + 4.0*f(xedge[n+1]) + f(xedge[n+2]))\n        n += 2\n\n    return Is\n\n\ndef printing(slab, I, Is, ea):\n    \"\"\" print output \"\"\"\n    print \"\\nNumber of slabs to be Integrated: \", slab\n    print \"Simpson's Integral value: \", Is\n    print \"Analytic Integral value: \", I\n    print \"Absolute error: \", ea\n    return 0\n\n\n\n\n\"\"\" Variables \"\"\"\nCONST_A = 0.0\nCONST_B = 1.0\nCONST_N_SLABS = [3, 7, 15, 31]\n\nea_array = []\ndelta_array = []\n\n\n\n\"\"\" Main Function\"\"\" \n\"\"\" Since the intervals are odd, we need to do extra calculations in the edges \"\"\"\nfor i in range (len(CONST_N_SLABS)):\n    slab = CONST_N_SLABS[i]\n    \n    if not slab%2 == 0:\n        Is_odd = simpson_int_odd(CONST_A, CONST_B, func, slab)\n        edge = slab - 1\n        \n    else:\n        edge = slab \n        Is_odd = 0.0\n\n    # MZ: you don't call this with edge -- your linspace needs to know the\n    # correct N (not N-1) to get the right xedge values, so you call\n    # with slab\n    Is = simpson_int(CONST_A, CONST_B, func, slab) \n    Is = Is + Is_odd    \n    I = exact_int(CONST_A, CONST_B)\n\n    ea =   abs(Is - I)\n    delta = abs(CONST_B -CONST_A)/slab\n    \n    printing(slab, I, Is, ea)\n    \n    ea_array.append(ea)\n    delta_array.append(delta)\n\n    \n    \n\n\n\"\"\" Plotting ea vs delta\"\"\"\npylab.loglog(delta_array, ea_array,  'bo')\npylab.xlabel('$\\delta$ = (b-a)/N')\npylab.ylabel('Absolute Error')\npylab.grid(True)\npylab.savefig(\"simp.png\")\n\n\n\"\"\" Plotting ea vs N\"\"\"\npylab.clf()\npylab.cla()\npylab.loglog(CONST_N_SLABS, ea_array,  'go')\npylab.xlabel('N')\npylab.ylabel('Absolute Error')\npylab.grid(True)\npylab.savefig(\"simp2.png\")\n\n\n\n\n\n\nprint \"\\n\\nDone!\"\n", "meta": {"hexsha": "4efa55c19e7f71d3b6462941e7eb649427554624", "size": 3066, "ext": "py", "lang": "Python", "max_stars_repo_path": "homework1_integration_differentiation/Q3/comp_simpsons_rule.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "homework1_integration_differentiation/Q3/comp_simpsons_rule.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework1_integration_differentiation/Q3/comp_simpsons_rule.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 23.4045801527, "max_line_length": 100, "alphanum_fraction": 0.5636007828, "include": true, "reason": "import numpy", "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.9273632896242074, "lm_q1q2_score": 0.8894844753992017}}
{"text": "## Import the packages\r\nimport numpy as np\r\nfrom scipy import stats\r\n\r\n\r\n## Define 2 random distributions\r\n#Sample Size\r\nN = 10\r\n#Gaussian distributed data with mean = 2 and var = 1\r\na = np.random.randn(N) + 2\r\n#Gaussian distributed data with with mean = 0 and var = 1\r\nb = np.random.randn(N)\r\n\r\n\r\n## Calculate the Standard Deviation\r\n#Calculate the variance to get the standard deviation\r\n\r\n#For unbiased max likelihood estimate we have to divide the var by N-1, and therefore the parameter ddof = 1\r\nvar_a = a.var(ddof=1)\r\nvar_b = b.var(ddof=1)\r\n\r\n#std deviation\r\ns = np.sqrt((var_a + var_b)/2)\r\ns\r\n\r\n\r\n\r\n## Calculate the t-statistics\r\nt = (a.mean() - b.mean())/(s*np.sqrt(2/N))\r\n\r\n\r\n\r\n## Compare with the critical t-value\r\n#Degrees of freedom\r\ndf = 2*N - 2\r\n\r\n#p-value after comparison with the t \r\np = 1 - stats.t.cdf(t,df=df)\r\n\r\n\r\nprint(\"t = \" + str(t))\r\nprint(\"p = \" + str(2*p))\r\n### You can see that after comparing the t statistic with the critical t value (computed internally) we get a good p value of 0.0005 and thus we reject the null hypothesis and thus it proves that the mean of the two distributions are different and statistically significant.\r\n\r\n\r\n## Cross Checking with the internal scipy function\r\nt2, p2 = stats.ttest_ind(a,b)\r\nprint(\"t = \" + str(t2))\r\nprint(\"p = \" + str(p2))\r\n\r\n\r\nprint(\"ACRL test!\")\r\na =  np.array([0.92,0.93,0.93,0.96,0.90])\r\nb =  np.array([0.87,0.00,0.76,0.91,0.87])\r\nc =  np.array([0.87,0.76,0.91,0.87])\r\nb[1] = c.mean()\r\nt2, p2 = stats.ttest_ind(a,b)\r\nprint(\"improve: \" + str(a.mean()-b.mean()))\r\nprint(\"t = \" + str(t2))\r\nprint(\"p = \" + str(p2))\r\n\r\nprint(\"Time test!\")\r\na =  np.array([102, 105, 98])\r\nb =  np.array([1.08, 1.25, 1.15, 1.24, 1.15])\r\nt2, p2 = stats.ttest_ind(a,b)\r\nprint(\"improve: \" + str(a.mean()/b.mean()))\r\nprint(\"t = \" + str(t2))\r\nprint(\"p = \" + str(p2))", "meta": {"hexsha": "f8ef3e7b765688ef60750fa666e5aab4f018f2c9", "size": 1816, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/p-value.py", "max_stars_repo_name": "liuruoze/Thought-SC2", "max_stars_repo_head_hexsha": "b3cfbeffbfa09b952c596805d2006af24613db2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-05T15:28:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T02:16:35.000Z", "max_issues_repo_path": "test/p-value.py", "max_issues_repo_name": "liuruoze/Thought-SC2", "max_issues_repo_head_hexsha": "b3cfbeffbfa09b952c596805d2006af24613db2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-10T13:38:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-10T13:38:19.000Z", "max_forks_repo_path": "test/p-value.py", "max_forks_repo_name": "liuruoze/Thought-SC2", "max_forks_repo_head_hexsha": "b3cfbeffbfa09b952c596805d2006af24613db2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-12T01:48:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T01:48:08.000Z", "avg_line_length": 26.7058823529, "max_line_length": 275, "alphanum_fraction": 0.6360132159, "include": true, "reason": "import numpy,from scipy", "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924818279466, "lm_q2_score": 0.914900963114118, "lm_q1q2_score": 0.8892768577640702}}
{"text": "import numpy as np\nimport pandas as pd \n\n\ndef asset_over_time_apy(P:int, r:float, n:int, t:float) -> pd.DataFrame:\n    \"\"\"\n    Compute the ending value of some investment after a certain amount of time with compound interest. \n    \n    Parameters\n    ---------\n    P: int\n        Initial investment\n    r: float\n        Annual Interest Rate\n    n: int\n        Number of compounding periods per year\n    t: int\n        Number of years\n\n    Returns\n    ---------\n    amount: pd.DataFrame\n        Final amount\n\n    Examples\n    ---------\n\n    >>> # Suppose we invest $5,000 into an investment that compounds at 6% annually.\n    >>> # Calculate the ending value of this investment after 10 years:\n    >>> P, r, n, t = 5000, .06, 1, 10\n    >>> df = asset_over_time_apy(P=5000, r=.06, n=1, t=10)\n    >>> # Expected df[-1] = 8954.238483\n           \n    \"\"\"\n\n    df = pd.DataFrame(data={'time': np.linspace(start=1, stop=t, num=t)})\n    df['value']= df.applymap(lambda t: P*(pow((1+r/n), n*t)))\n\n    return df\n\n\n\n\nif __name__ == \"__main__\":  \n   \"\"\"\n   Run for testing only and store example\n   \"\"\"\n\n   \"\"\"\n   https://www.statology.org/compound-interest-in-python/\n   Example 1: Compound Interest Formula with ANNUAL Compounding\n   Suppose we invest $5,000 into an investment that compounds at 6% annually.\n   Calculate the ending value of this investment after 10 years:\n   \"\"\"\n\n   df = asset_over_time_apy(P=5000, r=.06, n=1, t=10)\n   print(df)\n   # Expected df[-1] = 8954.238483\n\n   \"\"\"\n   Example 2: Compound Interest Formula with MONTHLY Compounding\n   Suppose we invest $1,000 into an investment that compounds at 6% annually \n   and is compounded on a monthly basis (12 times per year).\n   Calculate the ending value of this investment after 5 years:\n   \"\"\"\n\n   df = asset_over_time_apy(P=1000, r=.06, n=12, t=2)\n   print(df)\n", "meta": {"hexsha": "3ab19d0d2ab068982b12a756cf19a456179e6fad", "size": 1825, "ext": "py", "lang": "Python", "max_stars_repo_path": "scr/logic.py", "max_stars_repo_name": "G-Licitra/apy-calculator", "max_stars_repo_head_hexsha": "e47f274aeae84623c917e6e26d8eaced8a5d1d3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scr/logic.py", "max_issues_repo_name": "G-Licitra/apy-calculator", "max_issues_repo_head_hexsha": "e47f274aeae84623c917e6e26d8eaced8a5d1d3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scr/logic.py", "max_forks_repo_name": "G-Licitra/apy-calculator", "max_forks_repo_head_hexsha": "e47f274aeae84623c917e6e26d8eaced8a5d1d3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4492753623, "max_line_length": 103, "alphanum_fraction": 0.6290410959, "include": true, "reason": "import numpy", "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924810166349, "lm_q2_score": 0.9149009584734676, "lm_q1q2_score": 0.8892768525111231}}
{"text": "import numpy as np\n\ndef cross_product_matrix(in_vector):\n    \"\"\"\n    Return the cross product matrix of a 3d vector\n\n    For more information, see:\n    https://en.wikipedia.org/wiki/Cross_product#Conversion_to_matrix_multiplication\n\n    Parameters\n    ----------\n    in_vector : 3 x 1 numpy matrix\n        Input vector\n    Returns\n    -------\n    out_mat = 3 x 3 numpy array\n        The cross product matrix of in_vector\n\n    \"\"\"\n    # Alternate implementation for curiosity\n    # I = np.identity(3)\n    # out_mat = np.zeros((3,3))\n    # for row in I:\n    #     cross = np.cross(in_vector,row)\n    #     outer = np.outer(cross,row)\n    #     out_mat += outer\n    out_mat = np.array([[0.,-in_vector[2],in_vector[1]],\n                        [in_vector[2],0,-in_vector[0]],\n                        [-in_vector[1],in_vector[0],0.]])\n    return out_mat\n\n\ndef rotation_matrix(axis_vector, angle, degrees = True):\n    \"\"\"\n    Return the rotation matrix corresponding to a rotation axis and angle\n\n    For more information, see:\n    https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle\n\n    Parameters\n    ----------\n    axis_vector : 3 x 1 numpy array\n        A unit vector of the axis of rotation\n    angle : float\n        Angle of rotation in degrees unless otherwise specified\n    degrees : bool (optional)\n        Choose between units of degrees of radians. Default True so degrees\n    Returns\n    -------\n    rot_mat : 3 x 3 numpy array\n        Rotation matrix\n\n    \"\"\"\n    ang = angle\n    if degrees:\n        ang = np.radians(ang)\n    # the matrix the sum of 3 terms\n    cos_id = np.cos(ang) * np.identity(3)\n    sin_cross = np.sin(ang) * cross_product_matrix(axis_vector)\n    cos_tens = (1-np.cos(ang)) * np.outer(axis_vector,axis_vector)\n    # total\n    rot_mat = cos_id + sin_cross + cos_tens\n\n    return rot_mat\n", "meta": {"hexsha": "99c4c20d8800ee4ad3cbaf07089de000ca332558", "size": 1845, "ext": "py", "lang": "Python", "max_stars_repo_path": "fromage/utils/array_operations/_matrix.py", "max_stars_repo_name": "Yulin832/fromage", "max_stars_repo_head_hexsha": "f6c84d5684ca5abfcc979540bb97cc8f105f963d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-11-19T09:36:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-12T13:46:20.000Z", "max_issues_repo_path": "fromage/utils/array_operations/_matrix.py", "max_issues_repo_name": "Yulin832/fromage", "max_issues_repo_head_hexsha": "f6c84d5684ca5abfcc979540bb97cc8f105f963d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-01-22T17:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-21T14:23:52.000Z", "max_forks_repo_path": "fromage/utils/array_operations/_matrix.py", "max_forks_repo_name": "Yulin832/fromage", "max_forks_repo_head_hexsha": "f6c84d5684ca5abfcc979540bb97cc8f105f963d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-04-22T14:56:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T13:30:58.000Z", "avg_line_length": 28.3846153846, "max_line_length": 85, "alphanum_fraction": 0.6265582656, "include": true, "reason": "import numpy", "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.973240718366854, "lm_q2_score": 0.9136765169496872, "lm_q1q2_score": 0.8892271897110386}}
{"text": "# mean\n\n# The mean tool computes the arithmetic mean along the specified axis.\n# import numpy\n# my_array = numpy.array([ [1, 2], [3, 4] ])\n# print numpy.mean(my_array, axis = 0)        #Output : [ 2.  3.]\n# print numpy.mean(my_array, axis = 1)        #Output : [ 1.5  3.5]\n# print numpy.mean(my_array, axis = None)     #Output : 2.5\n# print numpy.mean(my_array)                  #Output : 2.5\n\n# var\n# The var tool computes the arithmetic variance along the specified axis.\n# import numpy\n# my_array = numpy.array([ [1, 2], [3, 4] ])\n# print numpy.var(my_array, axis = 0)         #Output : [ 1.  1.]\n# print numpy.var(my_array, axis = 1)         #Output : [ 0.25  0.25]\n# print numpy.var(my_array, axis = None)      #Output : 1.25\n# print numpy.var(my_array)                   #Output : 1.25\n\n# By default, the axis is None. Therefore, it computes the variance of the flattened array.\n\n# std\n# The std tool computes the arithmetic standard deviation along the specified axis.\n# import numpy\n# my_array = numpy.array([ [1, 2], [3, 4] ])\n# print numpy.std(my_array, axis = 0)         #Output : [ 1.  1.]\n# print numpy.std(my_array, axis = 1)         #Output : [ 0.5  0.5]\n# print numpy.std(my_array, axis = None)      #Output : 1.11803398875\n# print numpy.std(my_array)                   #Output : 1.11803398875\n\n# By default, the axis is None. Therefore, it computes the standard deviation of the flattened array.\n\n# Problem Statement:\n\n# You are given a 2-D array of size X.\n# Your task is to find:\n# The mean along axis\n# The var along axis\n# The std along axis\n\nimport numpy as np\n\nnp.set_printoptions(legacy=\"1.13\")\nrow, cols = map(int, raw_input().split())\n\nl = []\nfor i in range(row):\n    arr = list(map(float, raw_input().split()))\n    l.append(arr)\nl = np.array(l).reshape(row, cols)\nprint(np.array(np.mean(l, axis=1)))\nprint(np.array(np.var(l, axis=0)))\na = np.array(np.std(l, axis=None))\nprint(a)\n\n# Input :\n\n# 2 2\n# 1 2\n# 3 4\n\n# Output :\n\n# [ 1.5  3.5]\n# [ 1.  1.]\n# 1.11803398875\n", "meta": {"hexsha": "74a8304795e10691693ceedb728d6e0300b43774", "size": 1991, "ext": "py", "lang": "Python", "max_stars_repo_path": "NEW_PRAC/HackerRank/Python/MeanVarAndStd.py", "max_stars_repo_name": "side-projects-42/INTERVIEW-PREP-COMPLETE", "max_stars_repo_head_hexsha": "627a3315cee4bbc38a0e81c256f27f928eac2d63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-03-11T00:25:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T00:19:23.000Z", "max_issues_repo_path": "NEW_PRAC/HackerRank/Python/MeanVarAndStd.py", "max_issues_repo_name": "side-projects-42/INTERVIEW-PREP-COMPLETE", "max_issues_repo_head_hexsha": "627a3315cee4bbc38a0e81c256f27f928eac2d63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 160, "max_issues_repo_issues_event_min_datetime": "2021-04-26T19:04:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T20:18:37.000Z", "max_forks_repo_path": "NEW_PRAC/HackerRank/Python/MeanVarAndStd.py", "max_forks_repo_name": "side-projects-42/INTERVIEW-PREP-COMPLETE", "max_forks_repo_head_hexsha": "627a3315cee4bbc38a0e81c256f27f928eac2d63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-04-26T19:43:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T08:36:29.000Z", "avg_line_length": 29.7164179104, "max_line_length": 101, "alphanum_fraction": 0.6238071321, "include": true, "reason": "import numpy", "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.9294403979493139, "lm_q1q2_score": 0.8891344749870359}}
{"text": "# the code is the demonstration of the linear regression\n# TODO - Implement LARS and proximal gradient descent methods for LASSO\n\n# import the required python libraries\nimport numpy as np\nimport numpy.linalg as la\nfrom sklearn import preprocessing\n\nclass LinearRegression:\n\n    def fit(self, key, X_train, Y_train, regularization_param=0, num_epochs=10):\n\n        # fit the algorithm provided the training data\n        params = [];\n        if(key == 'ls'):\n            params = self.fit_ls(X_train, Y_train);\n        elif(key == 'rr'):\n            params = self.fit_rr(X_train, Y_train, regularization_param);\n        elif(key == 'lasso'):\n            params = self.fit_lasso(X_train, Y_train, regularization_param, num_epochs);\n        else:\n            raise ValueError('Please provide the correct value of the ley argument');\n\n        return params;\n\n    \n    def fit_ls(self, X_train, Y_train):\n\n        print('------------Using Linear regression with Least squares model-------------------');\n        print('Model training data shape:', X_train.shape);\n        print('Model training data shape:', Y_train.shape);\n\n        # determine the paramters of the model using linear regression least sqaures\n        dd_correlation = np.matmul(np.transpose(X_train), X_train);\n        dl_correlation = np.matmul(np.transpose(X_train), Y_train);\n        params = np.matmul(la.inv(dd_correlation), dl_correlation);\n\n        return params;\n\n    def fit_rr(self, X_train, Y_train, lambda_param):\n\n        print('----------Using Linear regression with L2 regularization----------------------');\n        print('Model training data shape:', X_train.shape);\n        print('Model training data shape:', Y_train.shape);\n\n        # determine the paramters of the model using linear regression with L2 regularization\n        # note that a close form solution exists for this type of regression.\n\n        tmp = np.matmul(np.transpose(X_train), X_train);\n        dd_correlation = np.add(tmp, lambda_param* np.identity(tmp.shape[0]));\n\n        dl_correlation = np.matmul(np.transpose(X_train), Y_train);\n        params = np.matmul(la.inv(dd_correlation), dl_correlation);\n\n        return params;\n\n\n    def fit_lasso(self, X_train, Y_train, lambda_param, num_epochs):\n\n        print('----------Using Linear regression with L1 regularization----------------------');\n        print('Model training data shape:', X_train.shape);\n        print('Model training data shape:', Y_train.shape);\n\n        learning_rate = 0.00001;\n        print('Learning rate:', learning_rate);\n\n        # determine the paramters of the model using linear regression with L1 regularization\n        # note that a close form solution does not exists for this type of regression.\n        # use the vanilla gradient descent method. Using the vanilla gradient descent gives only\n        # approximate sparse solutions(not completely zero)\n\n        X_train = preprocessing.scale(X_train);\n        Y_train = preprocessing.scale(Y_train);\n\n        params = np.ones(X_train.shape[1]);\n\n        num_samples = X_train.shape[1];\n\n        for i in range(num_epochs):\n\n            # compuet the loss on the prediction\n            rss_loss = Y_train - np.matmul(X_train, params);\n            mse = la.norm(rss_loss, ord=2) + lambda_param * la.norm(params, ord=1);\n            # print mse;\n            # compute the gradient\n            # notice the subgradient used in the computation of the gradient of L1 norm\n            gradient = (-np.dot(np.transpose(X_train), rss_loss) + \\\n                        lambda_param * np.sign(params))/num_samples;\n\n            # update the parameters\n            params = params - learning_rate * gradient;\n\n        # print params;\n        return params;", "meta": {"hexsha": "fa2b5b36140b4f3d74103a722450ecf1fc111c57", "size": 3727, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear_regression/linear_regression.py", "max_stars_repo_name": "kpandey008/ElementaryMLAlgorithms", "max_stars_repo_head_hexsha": "1c121b014c159839ec5f8607f4fec1fb6697401f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Linear_regression/linear_regression.py", "max_issues_repo_name": "kpandey008/ElementaryMLAlgorithms", "max_issues_repo_head_hexsha": "1c121b014c159839ec5f8607f4fec1fb6697401f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear_regression/linear_regression.py", "max_forks_repo_name": "kpandey008/ElementaryMLAlgorithms", "max_forks_repo_head_hexsha": "1c121b014c159839ec5f8607f4fec1fb6697401f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6489361702, "max_line_length": 97, "alphanum_fraction": 0.6401931849, "include": true, "reason": "import numpy", "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.974434792016126, "lm_q2_score": 0.9124361521430956, "lm_q1q2_score": 0.8891095321415516}}
{"text": "import numpy as np\n\n\"\"\" Determinant of upper triangle or diagnal matrix is product of diagnal element \"\"\"\na = np.array([(2, 3, 4), (0, 2, 5), (0, 0, 2)])\n# array([[2, 3, 4],\n#        [0, 2, 5],\n#        [0, 0, 2]])\n\nprint(np.linalg.det(a))\n# 7.999999999999998\n\n\"\"\" Determinant of row exhanged matrix will change the sign \"\"\"\na = np.array([(2, 3, 4), (0, 0, 2), (0, 2, 5)])\nprint(np.linalg.det(a))\n# - 7.999999999999998\n\n\"\"\" Determinant of identiy matrix is 1 \"\"\"\na = np.array([(1, 0, 0), (0, 1, 0), (0, 0, 1)])\nprint(np.linalg.det(a))\n# 1\n\n\"\"\" Determinant of zero row contain matrix is 0 \"\"\"\na = np.array([(2, 3, 4), (0, 0, 0), (9, 2, 5)])\nprint(np.linalg.det(a))\n# 0\n\n\"\"\" Determinant of singular (dependent column) matrix is 0 \"\"\"\na = np.array([( 2, 6,  4 ),\n              ( 6, 18, 12), \n              ( 9, 27, 5 )])\nprint(np.linalg.det(a))\n# 0\n\n\"\"\" Determinant of non-singular (independent column) matrix is non zero \"\"\"\na = np.array([(2, 6, 4), (6, 7, 12), (9, 9, 5)])\nprint(np.linalg.det(a))\n# 285.99999999999994\n", "meta": {"hexsha": "70e90fcb123c5d69d362b2fa93de42af390168b7", "size": 1017, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numpy/determinant.py", "max_stars_repo_name": "rrsalian/Machine-Learning", "max_stars_repo_head_hexsha": "deb2ddc0228f6ffcf67213a4b98c7bb57c9379a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numpy/determinant.py", "max_issues_repo_name": "rrsalian/Machine-Learning", "max_issues_repo_head_hexsha": "deb2ddc0228f6ffcf67213a4b98c7bb57c9379a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numpy/determinant.py", "max_forks_repo_name": "rrsalian/Machine-Learning", "max_forks_repo_head_hexsha": "deb2ddc0228f6ffcf67213a4b98c7bb57c9379a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7631578947, "max_line_length": 85, "alphanum_fraction": 0.5585054081, "include": true, "reason": "import numpy", "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517106286378, "lm_q2_score": 0.925229956061184, "lm_q1q2_score": 0.8891013090018541}}
{"text": "# Question 4 Lab 03\n# AB Satyaprakash (180123062)\n\n# imports ----------------------------------------------------------------------\nfrom math import factorial\nimport numpy as np\nimport sympy as sp\n# ------------------------------------------------------------------------------\n# functions --------------------------------------------------------------------\n\n\ndef forwardDiff(fArray):\n    sz = len(fArray)\n    fdArray = [fArray]\n    for i in range(1, sz):\n        temp = []\n        for j in range(sz-i):\n            temp.append(fdArray[i-1][j+1]-fdArray[i-1][j])\n        fdArray.append(temp)\n    return fdArray\n\n\ndef newtonFDPoly(fArray, xArray):\n    x0, x1 = xArray[0], xArray[1]\n    h = x1-x0\n    u = np.array([1/h, -x0/h])\n    fdArray = forwardDiff(fArray)\n    sz = len(fArray)\n    px = np.array([0])\n\n    for i in range(sz):\n        term = np.array([1])\n        for j in range(i):\n            term = np.polymul(term, np.polyadd(u, np.array([-j])))\n            term = term/(j+1)\n        term = term*fdArray[i][0]\n        px = np.polyadd(px, term)\n    return px\n\n\n# ------------------------------------------------------------------------------\n# g(x) = sin(x)/(x^2). Calculate g(0.25)\n# (a) By direct interpolation\nX = [0.1, 0.2, 0.3, 0.4, 0.5]\nG = [9.9833, 4.9667, 3.2836, 2.4339, 1.9177]\n\n# Construct a degree 3 polynomial to appproximate g(0.25)\npx = newtonFDPoly(G[:4], X[:4])\nprint('Thus, the approximation of g(0.25) using direct interpolation = P(0.25) = {}'.format(np.polyval(px, 0.25)))\n# ((x−0.1)(x−0.2)(x−0.3)(x−0.4)*Δ_4(f0))/4!(0.1)^4 is used to find the error!\nΔ4_f0 = forwardDiff(G)[4][0]\nx = sp.Symbol('x')\nerrorExpression = ((x-0.1)*(x-0.2)*(x-0.3)*(x-0.4)*Δ4_f0)/(factorial(4)*(0.1**4))\nerrorValue = abs(errorExpression.subs(x, 0.25))\nprint('The error term is at x = 0.25 is', errorValue)\n\n# (b) By first tabulating xg(x) and then forward difference interpolating in that table\nfor i in range(5):\n    G[i] *= X[i]\npx = newtonFDPoly(G[:4], X[:4])\nprint('\\n\\nThus, the approximation of g(0.25) using interpolation on xg(x) table = P(0.25) = {}'.format(\n    np.polyval(px, 0.25)*4))\nΔ4_f0 = forwardDiff(G)[4][0]\nx = sp.Symbol('x')\nerrorExpression = ((x-0.1)*(x-0.2)*(x-0.3)*(x-0.4)*Δ4_f0)/(factorial(4)*(0.1**4))\nerrorValue = abs(errorExpression.subs(x, 0.25)*4)\nprint('The error term is at x = 0.25 is', errorValue)\n\n# (c) Explain the difference between the results in (i) and (ii) respectively.\nprint('\\nSince the differences in (i) are oscillating and are not decreasing fast, the resulting error in interpolation would be large.')\nprint('However, the differences in (ii) tend to become smaller in magnitude, we expect more accurate results in this case.')\n\n# Question 4 ends --------------------------------------------------------------\n", "meta": {"hexsha": "5a870629226cc4f7b9977f44ba0407ef209cfe96", "size": 2760, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 3/Code/q4.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 3/Code/q4.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 3/Code/q4.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 37.2972972973, "max_line_length": 137, "alphanum_fraction": 0.543115942, "include": true, "reason": "import numpy,import sympy", "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.9416541536574629, "lm_q1q2_score": 0.8890880565004274}}
{"text": "# 数值微分求导数， 数值微分就是用数值方法近似的求解函数的导数的过程\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# f = function, x为input\n\ndef numerical_diff(f, x):\n    h = 1e-4\n    return (f(x + h) - f(x - h)) / (2 * h)\n\n# example 1: f = 0.01x^2 + 0.1x\ndef function1(x):\n    return 0.01 * (x ** 2) + 0.1 * x\n\n# 此函数用于利用数值微分的值作为斜率，重新画出与对应函数的斜线\ndef tangent_line(f, x):\n    d = numerical_diff(f, x) # 计算导数\n    print(d)\n    y = f(x) - d*x # f(x)与直线的截距\n    return lambda t: d*t + y # 类似返回一个直线函数 y = k * x + b\n\ndef function(x):\n    return 0.02 * x + 0.1\n\n# define 二元函数f(x0, x1) = x0^2 + x1^2\ndef function2(x):\n    return np.sum(x ** 2)\n\n# 当x0 = 3， x1 = 4时， 求funciton2对x0的偏微分\ndef function2_x0(x0):\n    return x0**2 + 4.0 ** 2.0\nprint('当x0 = 3， x1 = 4时， 求funciton2对x0的偏微分: ', numerical_diff(function2_x0, 3.0))\n\n# 当x0 = 3， x1 = 4时， 求funciton2对x1的偏微分\ndef function2_x1(x1):\n    return 3.0 ** 2.0 + x1 ** 2\nprint('当x0 = 3， x1 = 4时， 求funciton2对x1的偏微分: ', numerical_diff(function2_x1, 4.0))\n\n\nx = np.arange(0.0, 20.0, 0.1)\ny = function1(x)\ntf = tangent_line(function1, 5)\ny1 = tf(x)\ny2 = function(x)\nplt.xlabel(\"x\")\nplt.ylabel(\"f(x)\")\nplt.plot(x, y)\nplt.plot(x, y1)\nplt.plot(x, y2)\nplt.show()\n\n# 如果通过我们自己计算导数f(x)的导数为0.02*x + 0.1\n# 当x in 5： 0.02 * 5 + 0.1 = 0.2\n# 当x in 10：0.02 * 10 + 0.1 = 0.3\n# compare to this result, discover similarly\nprint('x in 5的导数：', numerical_diff(function1, 5))\n\nprint('x in 10的导数: ', numerical_diff(function1, 10))", "meta": {"hexsha": "0f4bf64e833bdd744510c43b824ef139268a6a58", "size": 1403, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch04/Numerical_differentation.py", "max_stars_repo_name": "Lyli724/Book_Introduce_Deep-Learning", "max_stars_repo_head_hexsha": "b24ecc76548794c7e4afaf01142a7e68764744d1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-20T05:34:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T05:34:15.000Z", "max_issues_repo_path": "ch04/Numerical_differentation.py", "max_issues_repo_name": "Lyli724/Book_Introduce_Deep-Learning", "max_issues_repo_head_hexsha": "b24ecc76548794c7e4afaf01142a7e68764744d1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch04/Numerical_differentation.py", "max_forks_repo_name": "Lyli724/Book_Introduce_Deep-Learning", "max_forks_repo_head_hexsha": "b24ecc76548794c7e4afaf01142a7e68764744d1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1896551724, "max_line_length": 81, "alphanum_fraction": 0.6193870278, "include": true, "reason": "import numpy", "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992942089575, "lm_q2_score": 0.9184802406781397, "lm_q1q2_score": 0.8889963766972449}}
{"text": "#Program to find the eigen values and eigen vectors.\r\n#Developed by: SRIJITH R\r\n#RegisterNumber: 21004191\r\nimport numpy as np\r\nA = np.array([[2,-3,0],[2,-5,0],[0,0,3]])\r\nvalues,vectors=np.linalg.eig(A)\r\nprint(\"Eigen values are {} and Eigen Vectors are {}\".format(values,vectors))", "meta": {"hexsha": "02605e0775d19ec01f792afc692d07e5da3b258c", "size": 279, "ext": "py", "lang": "Python", "max_stars_repo_path": "eigen values and vector.py", "max_stars_repo_name": "srijithmass/EIGENVALUES-AND-EIGENVECTORS", "max_stars_repo_head_hexsha": "a6a633ca5c9f8477767f8c83417521c5491dc133", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eigen values and vector.py", "max_issues_repo_name": "srijithmass/EIGENVALUES-AND-EIGENVECTORS", "max_issues_repo_head_hexsha": "a6a633ca5c9f8477767f8c83417521c5491dc133", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigen values and vector.py", "max_forks_repo_name": "srijithmass/EIGENVALUES-AND-EIGENVECTORS", "max_forks_repo_head_hexsha": "a6a633ca5c9f8477767f8c83417521c5491dc133", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8571428571, "max_line_length": 76, "alphanum_fraction": 0.7025089606, "include": true, "reason": "import numpy", "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. Yes\n2. Yes", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.935346510742652, "lm_q1q2_score": 0.8889635911234006}}
{"text": "import numpy as np\n\n\n\n#TODO add doc + add multiple root finding\ndef newton(function, derivative, x0, max_depth=10,  eps=1e-10):\n    x=x0\n    i=0\n    while i < max_depth: \n        if (derivative(x)==0):\n            print(\"Singularity at x={}\".format(x))\n        if np.abs(function(x))<=eps:\n            return x\n        x=x-function(x)/derivative(x)\n        i=i+1\n    return x\n\n\n\n# Find the third root of 27\nf = lambda x : 1/3*np.log(27)-np.log(x)\nDf = lambda x : -1/x\nx = newton(f, Df, 2, 5)\nprint(\"The third root of 27 is : {}\".format(x))\n\n# Find the the golden ratio\nf = lambda x : x**2-x-1\nDf = lambda x : 2*x -1\nx = newton(f, Df, 4, 6)\nprint(\"The golden ratio is : {}\".format(x))\n\n# Find the the super golden ratio\nf = lambda x : x**3-x**2-1\nDf = lambda x : 3*x**2-2*x\nx = newton(f, Df, 4, 6)\nprint(\"The super golden ratio is : {}\".format(x))\n\n# Unprecise function choice\n# Find the the value of pi\nf = lambda x : np.cos(x)\nDf = lambda x : -np.sin(x)\nx = newton(f, Df, 1.55, 1000, 1e-10)\nprint(\"The value of pi is : {}\".format(2*x))\n", "meta": {"hexsha": "3f23b424b5849cf9db1dfb456e18e653ed676037", "size": 1037, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/newton.py", "max_stars_repo_name": "ParadiseLab/Numerical_Methods", "max_stars_repo_head_hexsha": "5f6c86503ded6b77c36ee2103eee683deea63d3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/newton.py", "max_issues_repo_name": "ParadiseLab/Numerical_Methods", "max_issues_repo_head_hexsha": "5f6c86503ded6b77c36ee2103eee683deea63d3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/newton.py", "max_forks_repo_name": "ParadiseLab/Numerical_Methods", "max_forks_repo_head_hexsha": "5f6c86503ded6b77c36ee2103eee683deea63d3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5681818182, "max_line_length": 63, "alphanum_fraction": 0.5882352941, "include": true, "reason": "import numpy", "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9825575173068325, "lm_q2_score": 0.9046505421702797, "lm_q1q2_score": 0.88887119074511}}
{"text": "import pandas as pd\nimport numpy as np\nimport scipy.stats as st\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n#Calculating covariance and correlation coeffecient using hand\nad = pd.DataFrame({'watched':[5,4,4,6,8], 'bought':[8,9,10,13,15]})\nprint(ad)\n\nprint(ad.describe())\n\nprint(ad.corr())\n\n_ = sns.lmplot('watched', 'bought', data=ad)\nplt.show()\n\n# cross-product deviations: multiply the deviations of one variable by the corresponding deviations of a second variable\n# for above examples Cross Product Deviations\nwatched_diff, bought_diff = [], []\nfor index, row in ad.iterrows():\n    watched_diff.append(5.4-row['watched'])\n    bought_diff.append(11-row['bought'])\n\n\nprint(watched_diff, bought_diff)\n\n\n\nCross_Product_Deviations = sum(np.multiply(watched_diff, bought_diff))\nprint(Cross_Product_Deviations)\n\n\n# Covariance (we got it from cross product deviations)\n# covariance = Cross_Product_Deviations/(N-1)\nCovariance = Cross_Product_Deviations/(5-1)\nprint(Covariance)\n\n# now\nwatched_diff_standarized = np.array(watched_diff)/(ad['watched'].std())\nbought_diff_standarized = np.array(bought_diff)/(ad['bought'].std())\n\n\nCross_Product_Deviatiions_standarized = sum(np.multiply(watched_diff_standarized, bought_diff_standarized))\nprint(Cross_Product_Deviatiions_standarized)\n\n\n# R, correlation coefficient is standarized covariance\n\nCovariance_standarized = Cross_Product_Deviatiions_standarized/(5-1)\nprint(Covariance_standarized)\n\n# also , we can get it by R = Covariance/(s1*s2)\nprint(Covariance/(ad['watched'].std() * ad['bought'].std()))\n\n\n# Correlations\n\ndata = pd.read_csv('/home/atrides/Desktop/R/statistics_with_Python/06_Correlation/Data_Files/Exam Anxiety.dat', sep='\\t')\n\nprint(data.head())\n\ndata.set_index('Code', inplace=True, drop=True)\n\n\n# pearson\nprint(data.corr())\n\n\n# kendall\nprint(data.corr(method='kendall'))\n\n\n# using scipy.stats, only does one pair of variables at a time\n\nprint(st.pearsonr(data['Revise'], data['Exam']))\n\n\nprint(st.spearmanr(data['Revise'], data['Exam']))\n\n\n\nprint(st.kendalltau(data['Revise'], data['Exam']))\n\n\nprint(st.pearsonr(data['Anxiety'], data['Exam']))\n\n\n# Note:\n# \n# use pearson r for parametric\n# \n# use spearman rho for non-parametric\n# \n# use tendall tau for non-parametric and small datasets\n\n# seeing the relation with lmplot\n_ = sns.lmplot('Revise', 'Exam', data=data)\nplt.show()\n\n\n# R^2 : measure of the amount of variability in one variable that is shared by the other\n\n\nprint((data.corr())**2)\n\n\n\n\n", "meta": {"hexsha": "2751b79ed73c45eae23dda123b8a60b88acef182", "size": 2500, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/statistics_with_Python/06_Correlation/Script_Files/01_correlations.py", "max_stars_repo_name": "snehilk1312/AppliedStatistics", "max_stars_repo_head_hexsha": "0e2b9ca45b004f38f796fa6506270382ca3c95a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/statistics_with_Python/06_Correlation/Script_Files/01_correlations.py", "max_issues_repo_name": "snehilk1312/AppliedStatistics", "max_issues_repo_head_hexsha": "0e2b9ca45b004f38f796fa6506270382ca3c95a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/statistics_with_Python/06_Correlation/Script_Files/01_correlations.py", "max_forks_repo_name": "snehilk1312/AppliedStatistics", "max_forks_repo_head_hexsha": "0e2b9ca45b004f38f796fa6506270382ca3c95a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3214285714, "max_line_length": 121, "alphanum_fraction": 0.7468, "include": true, "reason": "import numpy,import scipy,import statsmodels", "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307684643189, "lm_q2_score": 0.9136765263519308, "lm_q1q2_score": 0.8888526372587583}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 16 10:03:34 2019\n\n@author: BSWOOD9321\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.arange(-2*np.pi,2*np.pi,np.pi/20)\nsin = np.sin(x)\nderivative = np.cos(x)\nfdiff = ((np.sin(x+np.pi/20))-np.sin(x))/((x+np.pi/20)-x)\nplt.plot(x,fdiff,label='Forward Difference Function')\nplt.plot(x,derivative,'r--',label='Derivative[Cos(x)]')\nplt.title(\"Forward Difference Equation and Cosine function\")\nplt.xlabel(\"x\")\nplt.legend(loc=(1.04,0))\nplt.show()\n\ngrad = np.gradient(sin,np.pi/20)\nplt.plot(x,grad,label='Gradient command')\nplt.plot(x,fdiff,'r--',label='Forward Difference Function')\nplt.plot(x,derivative,'b-',label='Derivative[Cos(x)]')\nplt.xlabel(\"x\")\nplt.title(\"ForDiff and Cos(x) and Gradient command\")\nplt.legend(loc=(1.04,0))\nplt.show()\n\nErrorf = np.absolute(fdiff-derivative)/derivative\n\nErrorg = np.absolute(grad-derivative)/derivative \n\nplt.plot(x,Errorf,label='Forward Differential Error')\nplt.legend(loc=(1.04,0))\nplt.show()\nplt.plot(x,Errorg,label='Gradient Error')\nplt.legend(loc=(1.04,0))\nplt.show()\n\nprint(\"So there is a small difference between the two different ways to find the derivative.\")\nprint(\"The errors of each, while at similar locations (it looks to be at the points where the derivative=0), have different values.\")\nprint(\"This is probably due to how the functions calculate the values really close to zero.\")\n\nx1 = np.arange(-2*np.pi,2*np.pi,np.pi/20)\nsin1 = np.sin(x1+.25)\nderivative1 = np.cos(x1+.25)\nfdiff1 = ((np.sin(x1+np.pi/20+.25))-np.sin(x1+.25))/((x1+np.pi/20)-x1)\nplt.plot(x1,fdiff1,label='Forward Difference Function')\nplt.plot(x1,derivative1,'r--',label='Derivative[Cos(x)]')\nplt.title(\"Challenge Plot 1\")\nplt.xlabel(\"x\")\nplt.legend(loc=(1.04,0))\nplt.show()\n\ngrad1 = np.gradient(sin1,np.pi/20)\nplt.plot(x1,grad1,label='Gradient command')\nplt.plot(x1,fdiff1,'r--',label='Forward Difference Function')\nplt.plot(x1,derivative1,'b-',label='Derivative[Cos(x)]')\nplt.xlabel(\"x\")\nplt.title(\"Challenge Plot 2\")\nplt.legend(loc=(1.04,0))\nplt.show()\n\nErrorf1 = np.absolute(fdiff1-derivative1)/derivative1\n\nErrorg1 = np.absolute(grad1-derivative1)/derivative1 \n\nplt.plot(x1,Errorf1,label='Forward Differential Error')\nplt.legend(loc=(1.04,0))\nplt.title(\"Challenge Error 1\")\nplt.show()\nplt.plot(x1,Errorg1,label='Gradient Error')\nplt.legend(loc=(1.04,0))\nplt.title(\"Challenge Error 2\")\nplt.show()\n\n\nx2 = np.arange(1,10,.20)\nfunc = (x2**3)/3\nderivative2 = x2**2\nfdiff2 = (((x2+.20)**3)/3-((x2**3)/3)/.20)\nplt.plot(x2,fdiff2,label='Forward Difference Function')\nplt.plot(x2,derivative2,'r--',label='Derivative[x^2]')\nplt.title(\"Bonus Plot 1\")\nplt.xlabel(\"x\")\nplt.legend(loc=(1.04,0))\nplt.show()\n\ngrad2 = np.gradient(func,np.pi/20)\nplt.plot(x2,grad2,label='Gradient command')\nplt.plot(x2,fdiff2,'r--',label='Forward Difference Function')\nplt.plot(x2,derivative2,'b-',label='Derivative[Cos(x)]')\nplt.xlabel(\"x\")\nplt.title(\"Bonus Plot 2\")\nplt.legend(loc=(1.04,0))\nplt.show()\n\nErrorf2 = np.absolute(fdiff2-derivative2)/derivative2\n\nErrorg2 = np.absolute(grad2-derivative2)/derivative2 \n\nplt.plot(x2,Errorf2,label='Forward Differential Error')\nplt.legend(loc=(1.04,0))\nplt.title(\"Bonus Error 1\")\nplt.show()\nplt.plot(x2,Errorg2,label='Gradient Error')\nplt.legend(loc=(1.04,0))\nplt.title(\"Bonus Error 2\")\nplt.show()\n", "meta": {"hexsha": "7a8aa997aa68e0d6b2ab97c73771e22ee8ab6ee8", "size": 3291, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week 05/Exercise08_BSW.py", "max_stars_repo_name": "bswood9321/PHYS-3210", "max_stars_repo_head_hexsha": "d780cac166688338ce91099cba4a4f6628430647", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week 05/Exercise08_BSW.py", "max_issues_repo_name": "bswood9321/PHYS-3210", "max_issues_repo_head_hexsha": "d780cac166688338ce91099cba4a4f6628430647", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week 05/Exercise08_BSW.py", "max_forks_repo_name": "bswood9321/PHYS-3210", "max_forks_repo_head_hexsha": "d780cac166688338ce91099cba4a4f6628430647", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3839285714, "max_line_length": 133, "alphanum_fraction": 0.711030082, "include": true, "reason": "import numpy", "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399034724605, "lm_q2_score": 0.9161096227509861, "lm_q1q2_score": 0.8888461119481089}}
{"text": "import numpy as np\nfrom scipy.special import gamma\nimport matplotlib.pyplot as plt\n\ndef plot_beta_distribution(a,b,name,points=100):\n    '''\n    This function will plot the beta distribution give the parameters a & b\n    '''\n    #Getting the normalixation constant\n    constant=gamma(a+b)/(gamma(a)*gamma(b))\n\n    #Sampling the points uniformly\n    delta_x=1.0/points\n    x=np.arange(0,1+delta_x,delta_x)\n\n    #Now calculating the pdf on these points\n    beta=constant*(x**(a-1))*((1-x)**(b-1))\n\n    #Plotting the pdf\n    plt.plot(x,beta)\n    plt.xlabel('mu (u)')\n    plt.ylabel('probability_density')\n    plt.title('Probability Density Function : P(u|a,b)')\n    #plt.show()\n    plt.savefig(name)\n    plt.clf()\n\n\ndef iterative_learning(prior_a,prior_b,toss_sample,plot_control=10):\n    #Getting the metadata\n    N=toss_sample.shape[0]\n\n    #Plotting the initial prior distribution\n    plot_beta_distribution(prior_a,prior_b,name='prior.png')\n    #Now going iteratively and plotting the beta distribution\n    for i in range(N):\n        #Calculating the new posteror based on the current evidence of the data\n        posterior_a = prior_a+toss_sample[i]\n        posterior_b = prior_b+(1-toss_sample[i])\n\n        #Plotting the new distribution\n        if(i%plot_control==0):\n            plot_beta_distribution(posterior_a,posterior_b,name=str(i)+'.png')\n\n        #Updating the current posterir as prior for next iteration\n        prior_a=posterior_a\n        prior_b=posterior_b\n\n\ndef one_shot_learning(prior_a,prior_b,toss_sample):\n    '''\n    This function will give the final posterior distribution by seeing the\n    whole data at once.\n    '''\n    #Getting the metadata\n    N=toss_sample.shape[0]\n    correction_m=np.sum(toss_sample)\n    correction_l=N-correction_m\n\n    #Getting the posteror parameters of the distribution\n    posterior_a = prior_a+correction_m\n    posterior_b = prior_b+correction_l\n\n    #Plotting the final distribution\n    plot_beta_distribution(posterior_a,posterior_b,name='one_shot.png')\n\n\nif __name__=='__main__':\n    ############ CONTROL VARIABLES ##############\n    dataset_size=150\n    #Parameters for the prior\n    a=2\n    b=int((0.6/0.4)*a)\n\n    ########### MAIN CODE ######################\n    #Sampling the dastaset randomly\n    toss_sample=np.random.randint(0,2,size=dataset_size)\n\n    #Plotting the distibution iteratively\n    print \"Plotting the Iterative solution\"\n    iterative_learning(a,b,toss_sample,plot_control=1)\n\n    #Plotting the distribution for the one-shot learning\n    print \"Printing the One-Shot Solution\"\n    one_shot_learning(a,b,toss_sample)\n", "meta": {"hexsha": "060edf7871b27163d108c1b3c26984f2e68d6d88", "size": 2596, "ext": "py", "lang": "Python", "max_stars_repo_path": "CoinToss/CoinToss.py", "max_stars_repo_name": "Robo-Sapien/Monte-Carlo_Bayesian-Learning", "max_stars_repo_head_hexsha": "02009c5bf08c857bdcc0b30ea1f3468c963b1213", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CoinToss/CoinToss.py", "max_issues_repo_name": "Robo-Sapien/Monte-Carlo_Bayesian-Learning", "max_issues_repo_head_hexsha": "02009c5bf08c857bdcc0b30ea1f3468c963b1213", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoinToss/CoinToss.py", "max_forks_repo_name": "Robo-Sapien/Monte-Carlo_Bayesian-Learning", "max_forks_repo_head_hexsha": "02009c5bf08c857bdcc0b30ea1f3468c963b1213", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1860465116, "max_line_length": 79, "alphanum_fraction": 0.6902927581, "include": true, "reason": "import numpy,from scipy", "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778048911612, "lm_q2_score": 0.9284088074883807, "lm_q1q2_score": 0.8887451452740978}}
{"text": "\"\"\"\n@file:          least_square.py\n@description:   answer to problems in exercises 6.5\n@author:        Hiu-kong Dan\n@date:          June 1, 2021\n\"\"\"\n\nfrom sympy import Matrix\n\ndef problem26():\n    A = Matrix([[0, .7, 1],\n                [-.7,0,.7],\n                [-1,-.7,0],\n                [-.7,-1,-.7],\n                [0,-.7,-1],\n                [.7,0,-.7],\n                [1,.7,0],\n                [.7,1,.7],\n                [0,-.7,1],\n                [.7,0,-.7],\n                [-1,.7,0],\n                [.7,-1,.7],\n                [0,.7,-1],\n                [-.7,0,.7],\n                [1,-.7,0],\n                [-.7,1,-.7]])\n    b = Matrix([.7,\n                0,\n                -.7,\n                -1,\n                -.7,\n                0,\n                .7,\n                1,\n                0,\n                0,\n                0,\n                0,\n                0,\n                0,\n                0,\n                0])\n    \n    assert A.shape == (16,3)\n    assert b.shape == (16,1)\n    \n    M = (A.T * A).col_insert(4, A.T * b)\n    \n    assert M.shape == (3, 4)\n    \n    x = Matrix.rref(M)[0].col(3)\n    \n    print(\"Using row reduction:\")\n    print(x)\n    print(\"-\"*20)\n    \n    # using another mathod\n    print(\"Using inverse matrix:\")\n    x = (A.T * A).inv() * A.T * b\n    print(x)\n    \n\nif __name__ == \"__main__\":\n    problem26()", "meta": {"hexsha": "ed0a845bfe762d31ef14ac2e6b39e9b7470309ec", "size": 1364, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_algebra/least_square.py", "max_stars_repo_name": "hiukongDan/pywork", "max_stars_repo_head_hexsha": "5ee6e6176cd63fa049d142e0f04c8416f668ba06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_algebra/least_square.py", "max_issues_repo_name": "hiukongDan/pywork", "max_issues_repo_head_hexsha": "5ee6e6176cd63fa049d142e0f04c8416f668ba06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_algebra/least_square.py", "max_forks_repo_name": "hiukongDan/pywork", "max_forks_repo_head_hexsha": "5ee6e6176cd63fa049d142e0f04c8416f668ba06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3125, "max_line_length": 51, "alphanum_fraction": 0.2903225806, "include": true, "reason": "from sympy", "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777975782054, "lm_q2_score": 0.9284088079835904, "lm_q1q2_score": 0.8887451389587384}}
{"text": "import sympy\r\nfrom sympy import *\r\nimport random\r\n\r\ndef choose_modulus(k,l,m):\r\n\tp1 = find_prime(k,l)\r\n\tp2 = find_prime(k,l)\r\n\t#while not (log(p1,2) + m < log(p2, 2)):\r\n\t#\tp1 = find_prime(k,l)\r\n\t#\tp2 = find_prime(k,l)\r\n\t#\tprint(p1, p2)\r\n\t#print(log(p1,2)+m < log(p2,2))\r\n\tprint(\"prime 1: \", p1)\r\n\tprint(\"prime 2: \", p2)\r\n\treturn p1,p2\r\n\r\ndef choose_encryption_key_old(m):\r\n\te = random.randrange(2,m)\r\n\twhile not gcd(e, totient(m)) == 1:\r\n\t\te = random.randrange(2,m)\r\n\treturn e\r\n\r\ndef choose_encryption_key(p1,p2):\r\n\tm = p1*p2\r\n\te = random.randrange(2, p1*p2)\r\n\twhile not gcd(e, (p1-1)*(p2-1)) == 1:\r\n\t\te = random.randrange(2, p1*p2)\r\n\treturn e\r\n\r\ndef compute_decryption_key(e, p1, p2):\r\n\t# d = e inverse mod phi(m) m = p1*p2\r\n\t#phi(m) = (p1-1)*(p2-1)\r\n\td = inv_mod(e, (p1-1)*(p2-1))\r\n\treturn d\r\n\r\ndef RSA_encrypt(P, e, m):\r\n\treturn power_mod(P,e,m)\r\n\r\ndef RSA_decrypt(C, d, m):\r\n\treturn power_mod(C,d,m)\r\n\r\ndef RSA_crack(C, e, m):\r\n\treturn power_mod(C, inv_mod(e,totient(m)), m)\r\n\r\ndef power_mod(a, b, m):\r\n\t#replace with better version for large numbers\r\n\t#return ((a%m)**(b%m))%m\r\n\treturn pow(a,b,m)\r\n\r\ndef string_to_int(s):\r\n\treturn int.from_bytes(s.encode(),'big')\r\n\r\ndef int_to_string(n):\r\n\treturn n.to_bytes((n.bit_length()+7)//8,'big').decode()\r\n\r\ndef find_prime(k, l):\r\n\tx = random.randrange(2**k+2, 2**l-1)\r\n\twhile (not isprime(x)):\r\n\t\tx = random.randrange(2**k+2, 2**l-1)\r\n\treturn x\r\n\r\ndef mod_inv_old(a,m):\r\n\t#replace with euclid's algorithm - will be using large numbers\r\n\tfor i in range(0,m):\r\n\t\tif (i*a)%m == 1:\r\n\t\t\treturn i\r\n\treturn -1\r\n\r\ndef xgcd(b, n):\r\n    \"\"\" Return g, x0, y0\r\n        such that x0*b + y0*n = g\r\n        and g is the gcd of (b,n)\"\"\"\r\n    x0, x1, y0, y1 = 1, 0, 0, 1\r\n    while n != 0:\r\n        q, b, n = b // n, n, b % n\r\n        x0, x1 = x1, x0 - q * x1\r\n        y0, y1 = y1, y0 - q * y1\r\n    return b, x0, y0\r\n\r\ndef inv_mod(b, n):\r\n    \"\"\" Return the modular inverse of b mod n\r\n     or None if gcd(b,n) > 1 \"\"\"\r\n    g, x, _ = xgcd(b, n)\r\n    if g == 1:\r\n        return x % n\r\n\r\ndef unit_test1(kv, lv, dv, textv):\r\n\t(p1, p2) = choose_modulus(kv, lv, dv)\r\n\tm = p1 * p2\r\n\te = choose_encryption_key(p1, p2)\r\n\td = compute_decryption_key(e, p1, p2)\r\n\tplaintext = textv\r\n\tP = string_to_int(plaintext)\r\n\tprint(\"Plaintext in bits = \", P)\r\n\tC = RSA_encrypt(P, e, m)\r\n\tprint(\"Plaintext: \", plaintext)\r\n\tprint(\"Text Len: \", 8*len(plaintext), \"bits\")\r\n\tprint(\"Modulus len: \",  int(log(m)/log(2)), \"bits\")\r\n\tprint(\"Ciphertext in bit format = \", C)\r\n\tD = RSA_decrypt(C, d, m)\r\n\tprint(\"D (Decrypted text in bit format) = \", D)\r\n\tdecoded_text = int_to_string(D)\r\n\tprint(\"Decoded Text: \", decoded_text, \"\\n\\n--------------\\n\")\r\n\r\ndef unit_test2(kv, lv, dv, textv):\r\n\t(p1, p2) = choose_modulus(kv, lv, dv)\r\n\tm = p1 * p2\r\n\te = choose_encryption_key(p1, p2)\r\n\td = compute_decryption_key(e, p1, p2)\r\n\tplaintext = textv\r\n\tP = string_to_int(plaintext)\r\n\tprint(\"Plaintext in bits = \", P)\r\n\tC = RSA_encrypt(P, e, m)\r\n\tprint(\"Plaintext: \", plaintext)\r\n\tprint(\"Text Len: \", 8*len(plaintext), \"bits\")\r\n\tprint(\"Modulus len: \",  int(log(m)/log(2)), \"bits\")\r\n\tprint(\"C (Ciphertext in bit format) = \", C)\r\n\tD = RSA_crack(C, e, m)\r\n\tprint(\"D (decrypted text in bit format) = \", D)\r\n\tdecoded_text = int_to_string(D)\r\n\tprint(\"Decoded Text: \", decoded_text, \"\\n\\n--------------\\n\")\r\n\r\nunit_test1(10, 12, 1, \"Hi\")\r\nunit_test1(200,201,50,\"I've got the best RSA. Tremendous!\")\r\nunit_test2(10, 12, 5, \"Hi\")", "meta": {"hexsha": "7510448b615f3692339d912bef24060ea4462885", "size": 3404, "ext": "py", "lang": "Python", "max_stars_repo_path": "Cryptography/4.RSA Encryption/isabelleRSA.py", "max_stars_repo_name": "swethapraba/SeniorYearCSElectives", "max_stars_repo_head_hexsha": "67b989ffecd5cf7508258783b0ec26468cdf94fc", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cryptography/4.RSA Encryption/isabelleRSA.py", "max_issues_repo_name": "swethapraba/SeniorYearCSElectives", "max_issues_repo_head_hexsha": "67b989ffecd5cf7508258783b0ec26468cdf94fc", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cryptography/4.RSA Encryption/isabelleRSA.py", "max_forks_repo_name": "swethapraba/SeniorYearCSElectives", "max_forks_repo_head_hexsha": "67b989ffecd5cf7508258783b0ec26468cdf94fc", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.232, "max_line_length": 64, "alphanum_fraction": 0.5875440658, "include": true, "reason": "import sympy,from sympy", "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9867771766922545, "lm_q2_score": 0.9005297774417915, "lm_q1q2_score": 0.8886222313113153}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time     : 2018/12/06 12:41\n# @Author   : Iydon\n# @File     : 9.3.py\n\nimport numpy as np\nimport scipy as sp\n\n\ndef gersgorin_circle(A, numpy):\n    r\"\"\"\n    |z-a_{ii}|<=\\sum_{j!=i}|a_{ij}|\n    \"\"\"\n    shape = A.shape\n    if shape[0] != shape[-1]:\n        raise Exception(\"Dimensions do not match.\")\n    result = [[] for i in range(shape[0])]\n    for i in range(shape[0]):\n        summation = numpy.sum(numpy.abs(A[i,])) - numpy.abs(A[i,i])\n        result[i] = [A[i,i], summation]\n    return result\n\n\ndef power_method(A, numpy, x0, judge=None, eps=1e-6, max_loop=64, disply=False, p=0):\n    r\"\"\"\n    Numpy\n    B = A - pI.\n    \"\"\"\n    if judge==None: judge = lambda x,y: numpy.linalg.norm(x-y, float(\"inf\"))\n    A_    = A.copy() - p*numpy.eye(A.__len__())\n    count = 0\n    mu    = numpy.max(numpy.abs(x0))\n    x0    = x0 / mu\n    last  = x0\n    while count<max_loop:\n        count += 1\n        uv = numpy.matmul(A_, x0)\n        mu = numpy.max(numpy.abs(uv)) \n        x0 = uv / mu\n        if disply:\n            print(\"%%%dd: %%s\"%(len(str(max_loop)))%(count, mu))\n        if judge(last,x0)<eps:\n            break\n        last = x0\n    return mu + p\n\n\ndef inverse_power_method(A, scipy, x0, judge=None, eps=1e-6, max_loop=64, disply=False, p=0):\n    r\"\"\"\n    Scipy\n    pass\n    \"\"\"\n    from scipy import linalg\n    if judge==None:\n        norm  = lambda x: scipy.linalg.norm(x, float(\"inf\"))\n        judge = lambda x,y: abs(norm(x-y))\n    A_    = A.copy() - p*scipy.eye(len(A))\n    LU    = linalg.lu_factor(A_)\n    count = 0\n    mu    = max(abs(x0))\n    x0    = x0 / mu\n    last  = x0\n    while count<max_loop:\n        count += 1\n        uv = linalg.lu_solve(LU, x0)\n        mu = max(abs(x0))[0]\n        x0 = uv / mu\n        if disply:\n            print(\"%%%dd: %%s\"%(len(str(max_loop)))%(count, p+1/mu))\n        if judge(last,x0)<eps:\n            break\n        last = x0\n    return p + 1/mu\n\n\n    \n\nA  = np.matrix([[1,1,1],[1,1,0],[1,0,1]])\nx0 = np.matrix([-1,0,1]).T\nresult = power_method(A, np, x0=x0, judge=None, eps=1e-6, max_loop=64, disply=True, p=0)\nprint(result)\n\nresult = inverse_power_method(A, np, x0=x0, judge=None, eps=1e-6, max_loop=64, disply=True, p=0)\nprint(result)\n\nprint(np.max(np.linalg.eigvals(A)))\nprint(np.min(np.linalg.eigvals(A)))\n\n\n\nA  = np.matrix([[2,1,1],[1,2,1],[1,1,2]])\nx0 = np.matrix([1,-1,2]).T\nresult = power_method(A, np, x0=x0, judge=None, eps=1e-6, max_loop=64, disply=True, p=0)\nprint(result)\nresult = inverse_power_method(A, np, x0=x0, judge=None, eps=1e-6, max_loop=64, disply=True, p=0)\nprint(result)\n\nprint(np.max(np.linalg.eigvals(A)))\nprint(np.min(np.linalg.eigvals(A)))\n\nprint(\"\\n\"*10)\n\nA = np.matrix([[0,0,2,4],[1/2,0,0,0],[0,1/4,0,0],[0,0,1/8,0]])\nx0 = np.matrix([[1],[1],[1],[1]])\nresult = power_method(A, np, x0=x0, judge=None, eps=1e-6, max_loop=128, disply=True, p=0)\nprint(result)\nprint(np.max(np.linalg.eigvals(A)))\n\nprint(\"\\n\"*10)\n\nM = 11\na = 3/4\nA = np.diag([(1+2*a) for i in range(M-1)]) - np.diag([a for i in range(M-2)],1) - np.diag([a for i in range(M-2)],-1)\nx0 = np.ones((M-1,1))\nresult = inverse_power_method(A, np, x0=x0, judge=None, eps=1e-6, max_loop=128, disply=True, p=0)\n\nprint(result)\nprint(np.min(np.linalg.eigvals(A)))\n\nprint(\"\\n\"*10)\n\nM = 11\na = 3/4\nA = np.diag([(1+a) for i in range(M-1)]) - np.diag([-a/2 for i in range(M-2)],1) - np.diag([-a/2 for i in range(M-2)],-1)\nB = np.diag([(1+a) for i in range(M-1)]) - np.diag([a/2 for i in range(M-2)],1) - np.diag([a/2 for i in range(M-2)],-1)\nC = np.matmul( np.linalg.inv(A), B )\nx0 = np.ones((M-1,1))\nresult = power_method(C, np, x0=x0, judge=None, eps=1e-6, max_loop=1024, disply=True, p=0)\n\nprint(result)\nprint(np.max(np.linalg.eigvals(C)))\n", "meta": {"hexsha": "d2189fa0015696b3f8471f2e0c101fc139385341", "size": 3711, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/HW/9.3.py", "max_stars_repo_name": "Iydon/NumericalAnalysisNotes", "max_stars_repo_head_hexsha": "ef1e37b97522fce9837142d242676fdd16e74712", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-10-20T08:18:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-11T12:14:56.000Z", "max_issues_repo_path": "MA305/9.3.py", "max_issues_repo_name": "AllenYZB/homework", "max_issues_repo_head_hexsha": "65bd3372df197bec5e152a37cdc1f6f5432b7f3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-13T03:04:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:49:10.000Z", "max_forks_repo_path": "MA305/9.3.py", "max_forks_repo_name": "AllenYZB/homework", "max_forks_repo_head_hexsha": "65bd3372df197bec5e152a37cdc1f6f5432b7f3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-02T05:46:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T23:11:28.000Z", "avg_line_length": 27.9022556391, "max_line_length": 121, "alphanum_fraction": 0.5650767987, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.9314625045897805, "lm_q1q2_score": 0.8885836505649426}}
{"text": "import numpy as np\ndef minkowski_distances(vector_x, vector_z, p=2):\n    \"\"\" Calculates the Minkowski distance for a choosen value p between two vectors.\n    \n    -----------\n    Parameters:\n    \n    vector_x / vector_z : numpy array\n            Both are expected to have the same size and conntain float values\n    \n    p : int or +/- np.inf\n            The value to  raise and then take the root in the minkowski distance formula\n    \n    Using +/- np.inf for representing a infinity, they are preprocessed to their max/min representation.\n    Be careful since very large values of p may take a some time to process, even though we use a vectorized approach\n    \"\"\"\n    if p == np.inf:\n        return max(np.abs(vector_x - vector_z))\n    elif p == - np.inf:\n        return min(np.abs(vector_x - vector_z))\n    \n    if not isinstance(p, int):\n        raise TypeError(\"p is {type(p)}, not a integer!\")\n    elif p <= 0:\n        raise ValueError(\"p must be a non negative, non zero integer!\")\n        \n    return np.sum(np.abs(vector_x-vector_z)**p) ** (1/p)\n\n\ndef hamming_distance(vector_x, vector_z):\n    \"\"\" Returns the Hamming distance (amount of different elements) between two vectors\n    We divide by the length of the vector to follow sklean's convention\n    \n    Usefull as a distance metric for categorical data\n    ----------\n    Parameters\n    vector_x / vector_z : numpy array or pd.Series\n    \"\"\"\n\n    # If you want, you can check scipy's hamming distance, but it still gives\n    #   different results to sklearn\n    #from scipy.spatial.distance import hamming\n    #return hamming(vector_x, vector_z)\n    return np.sum(~(vector_x == vector_z)) / len(vector_x)\n\n", "meta": {"hexsha": "1a7115e78d185697d0cff862d15b2e773e8542ac", "size": 1673, "ext": "py", "lang": "Python", "max_stars_repo_path": "useful/distances.py", "max_stars_repo_name": "BrunoGomesCoelho/small-bang", "max_stars_repo_head_hexsha": "f5eadd276c26c47dd2465868bb774786d2751b1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "useful/distances.py", "max_issues_repo_name": "BrunoGomesCoelho/small-bang", "max_issues_repo_head_hexsha": "f5eadd276c26c47dd2465868bb774786d2751b1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "useful/distances.py", "max_forks_repo_name": "BrunoGomesCoelho/small-bang", "max_forks_repo_head_hexsha": "f5eadd276c26c47dd2465868bb774786d2751b1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3695652174, "max_line_length": 117, "alphanum_fraction": 0.6586969516, "include": true, "reason": "import numpy,from scipy", "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9793540674530015, "lm_q2_score": 0.9073122201074847, "lm_q1q2_score": 0.8885799132120781}}
{"text": "# IMPORTS\nimport numpy as np\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\nimport matplotlib.style as style\nfrom IPython.core.display import HTML\n\n# PLOTTING CONFIG\n%matplotlib inline\nstyle.use('fivethirtyeight')\nplt.rcParams[\"figure.figsize\"] = (14, 7)\nHTML(\"\"\"\n<style>\n.output_png {\n    display: table-cell;\n    text-align: center;\n    vertical-align: center;\n}\n</style>\n\"\"\")\nplt.figure(dpi=100)\n\n# PDF P = .2\nplt.scatter(np.arange(21),\n            (stats.binom.pmf(np.arange(21), p=.2, n=20)),\n            alpha=0.75,\n            s=100\n       )\nplt.plot(np.arange(21),\n         (stats.binom.pmf(np.arange(21), p=.2, n=20)),\n         alpha=0.75,\n        )\n\n# PDF P = .5\nplt.scatter(np.arange(21),\n            (stats.binom.pmf(np.arange(21), p=.5, n=20)),\n            alpha=0.75,\n            s=100\n       )\nplt.plot(np.arange(21),\n         (stats.binom.pmf(np.arange(21), p=.5, n=20)),\n         alpha=0.75,\n        )\n\n# PDF P = .9\nplt.scatter(np.arange(21),\n            (stats.binom.pmf(np.arange(21), p=.9, n=20)),\n            alpha=0.75,\n            s=100\n       )\nplt.plot(np.arange(21),\n         (stats.binom.pmf(np.arange(21), p=.9, n=20)),\n         alpha=0.75,\n        )\n\n# LEGEND\nplt.text(x=3.5, y=.075, s=\"$p = 0.2$\", alpha=.75, weight=\"bold\", color=\"#008fd5\")\nplt.text(x=9.5, y=.075, s=\"$p = 0.5$\", alpha=.75, weight=\"bold\", color=\"#fc4f30\")\nplt.text(x=17.5, y=.075, s=\"$p = 0.9$\", alpha=.75, weight=\"bold\", color=\"#e5ae38\")\n\n# TICKS\nplt.xticks(range(21)[::2])\nplt.tick_params(axis = 'both', which = 'major', labelsize = 18)\nplt.axhline(y = 0, color = 'black', linewidth = 1.3, alpha = .7)\n\n# TITLE, SUBTITLE & FOOTER\nplt.text(x = -2.5, y = .37, s = \"Binomial Distribution - $p$\",\n               fontsize = 26, weight = 'bold', alpha = .75)\nplt.text(x = -2.5, y = .32, \n         s = 'Depicted below are three Binomial distributed random variables with varying $p $. As one can see\\nthe parameter $p$ shifts and skews the distribution.',\n         fontsize = 19, alpha = .85)\nplt.text(x = -2.5,y = -0.065,\n         s = '   ©Joshua Görner                                                                                                                                                 github.com/jgoerner   ',\n         fontsize = 14, color = '#f0f0f0', backgroundcolor = 'grey');", "meta": {"hexsha": "0a63f85ed3be518a1ee680f1633ea95785851b11", "size": 2298, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/binomial/02_p.py", "max_stars_repo_name": "jgoerner/distribution-cheatsheet", "max_stars_repo_head_hexsha": "b96887fb3f53abc315ce1527a73829843bad41b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2018-01-02T15:28:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T22:43:44.000Z", "max_issues_repo_path": "src/binomial/02_p.py", "max_issues_repo_name": "Kengstar/distribution-cheatsheet", "max_issues_repo_head_hexsha": "b96887fb3f53abc315ce1527a73829843bad41b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-01-04T10:23:47.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-04T18:26:48.000Z", "max_forks_repo_path": "src/binomial/02_p.py", "max_forks_repo_name": "Kengstar/distribution-cheatsheet", "max_forks_repo_head_hexsha": "b96887fb3f53abc315ce1527a73829843bad41b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2018-01-10T17:31:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T10:39:19.000Z", "avg_line_length": 31.0540540541, "max_line_length": 200, "alphanum_fraction": 0.5317667537, "include": true, "reason": "import numpy,import scipy", "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361157495521, "lm_q2_score": 0.9252299617308843, "lm_q1q2_score": 0.8885549169974086}}
{"text": "\"\"\"\nFunctions that return a NumPy array containing a wave such as\na sine wave or square wave.\n\nParameters\n----------\n  frequency: int or float\n     wave frequency in Hertz (1/second)\n  max_amplitude: float\n     The maximum amplitude of the wave\n  phase_shift: float\n     Initial phase of the wave\n  sample_rate: int or float\n     Number of samples per second of the waveform\n  time_duration: int or float\n     The time, in seconds, of the output wave.\n\nVariables\n---------\n    num_samples is the size of the output array\n    time_sequence is an array [0, v, 2*v, .... num_samples*v] where\n        (num_samples + 1)*v == time_duration.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef generate_trignometric_wave(\n        func, frequency, max_amplitude,\n        phase_shift, sample_rate, time_duration):\n    num_samples = int(time_duration * sample_rate)\n    time_sequence = np.linspace(0, time_duration, num_samples, endpoint=False)\n    return max_amplitude*func(2*np.pi*frequency*time_sequence + phase_shift)\n\ndef generate_sine_wave(\n        frequency, max_amplitude, phase_shift,\n        sample_rate, time_duration):\n    return generate_trignometric_wave(\n        np.sin, frequency, max_amplitude, phase_shift,\n        sample_rate, time_duration)\n\ndef generate_cosine_wave(\n        frequency, max_amplitude, phase_shift,\n        sample_rate, time_duration):\n    return generate_trignometric_wave(\n        np.cos, frequency, max_amplitude, phase_shift,\n        sample_rate, time_duration)\n\ndef generate_square_wave(\n        frequency, max_amplitude,\n        phase_shift, sample_rate, time_duration):\n    num_samples = time_duration * sample_rate\n    time_sequence = np.linspace(0, time_duration, num_samples, endpoint=False)\n    def func(v):\n        return - np.sign((v - v.astype(int)) - 0.45)\n    return max_amplitude*func(frequency*time_sequence + phase_shift)\n\n\ndef plot_signal(signal, time_duration, sample_rate):\n    plt.figure(1)\n    plt.clf()\n    num_samples = time_duration * sample_rate\n    time_sequence = np.linspace(0, time_duration, num_samples, endpoint=False)\n    plt.plot(time_sequence, signal)\n    plt.show()\n    return\n\n# TESTS\n\ndef test():\n    # Plot\n    frequency = 1.0\n    max_amplitude = 1.0\n    phase_shift = 0.0\n    sample_rate = 100\n    time_duration = 2\n\n\n    signal = generate_square_wave(frequency, max_amplitude, phase_shift, sample_rate, time_duration)\n    plot_signal(signal, time_duration, sample_rate)\n\n    phase_shift = np.pi/2.0 # 90 degrees \n    signal = generate_sine_wave(frequency, max_amplitude, phase_shift, sample_rate, time_duration)\n    plot_signal(signal, time_duration, sample_rate)\n\n    signal = generate_cosine_wave(frequency, max_amplitude, phase_shift, sample_rate, time_duration)\n    plot_signal(signal, time_duration, sample_rate)\n\nif __name__ == '__main__':\n    test()\n", "meta": {"hexsha": "83de1a5e79ec3856e65ac96e2e50e3f0e680ff3d", "size": 2834, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/signal_processing_examples/generate_waves.py", "max_stars_repo_name": "AssembleSoftware/IoTPy", "max_stars_repo_head_hexsha": "d4b7b516ef95a45cff69827003d5e2d205f2ba55", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2017-12-19T20:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T09:44:03.000Z", "max_issues_repo_path": "examples/signal_processing_examples/generate_waves.py", "max_issues_repo_name": "AssembleSoftware/IoTPy", "max_issues_repo_head_hexsha": "d4b7b516ef95a45cff69827003d5e2d205f2ba55", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-05-30T20:21:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T20:49:31.000Z", "max_forks_repo_path": "examples/signal_processing_examples/generate_waves.py", "max_forks_repo_name": "sdeepaknarayanan/IoTPy", "max_forks_repo_head_hexsha": "ba022c3d6696527b834a865b9cf403d90665145b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2017-05-21T15:37:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-16T13:45:11.000Z", "avg_line_length": 31.4888888889, "max_line_length": 100, "alphanum_fraction": 0.7187720536, "include": true, "reason": "import numpy", "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611574955211, "lm_q2_score": 0.9252299514223379, "lm_q1q2_score": 0.8885549070974812}}
{"text": "import pandas as pd\nimport numpy as np\nimport scipy.stats as stat\nimport matplotlib as mat\n\"\"\"\nProblem 1:  Generate a random 20x20 grid of two digit natural numbers. Find the largest product of four \n            diagonally adjacent numbers.\n\"\"\"\na = np.random.randint(10, 99, (20, 20))\n\ndef largest_product(a):\n    prd = 0\n    d = dict()\n    l = []\n    for row in np.arange(0,a.shape[0]-3):\n        for col in np.arange(0,a.shape[0]-3):\n            temp_down = a[row, col]*a[row+1, col+1]*a[row+2, col+2]*a[row+3, col+3]\n            temp_up = a[row+3, col]*a[row+2, col+1]*a[row+1, col+2]*a[row, col+3]\n            if temp_up > temp_down:\n                temp = temp_up\n                address = f\"Up Diag {(row+3, col),(row+2,col+1),(row+1,col+2),(row,col+3)}\"\n            else:\n                temp = temp_down\n                address = f\"Down Diag {(row, col),(row+1,col+1),(row+2,col+2),(row+3,col+3)}\"\n            l.append([temp,temp_up,temp_down])\n            if temp > prd:\n                prd = temp\n                d = {\"product\": prd,\n                  \"address\": address}\n    return d\n\nprint(f\"Maximum Product: {largest_product(a)['product']} \\nAddress: {largest_product(a)['address']}\")\n\n\"\"\"\nProbelm 2:  The Social Security administration has this neat data by year of what names are most popular \n            by gender for born that year in the USA. The popular name list for the year 1990 is given in the \n            website <url>. Write a python program to identify the names that appear in the list of popular\n            names of both genders. \n\"\"\"\n\ndata = pd.read_csv(\"popular_names.csv\")\n\ndef popular_name(data):\n\n    males = set(data['Male name'])\n    females = set(data['Female name'])\n    common = males.intersection(females)\n    d = dict()\n    for name in common:\n        combined_rank = int(data['Rank'][data['Male name']== name] ) + int(data['Rank'][data['Female name']== name])\n        d.update({combined_rank:name})\n        #print(f\"Name: {name},\\t Rank: {combined_rank}\")\n\n    name = d[min(d.keys())]\n\n    return name\n\nprint(f\"Most Popular name {popular_name(data)}\")\n\n\"\"\"\nProblem 3: Invert matrix using first principle\n\"\"\"\n\n#b = np.random.randint(10, 99, (3, 3))\n\ndef matrix_invert_first_principles(b):\n\n    if b.shape[0] != b.shape[1]:\n        return print(\"Please input a square matrix\")\n\n    b = b.astype(\"float\")\n    c = b.copy()\n    I = np.eye(b.shape[0], b.shape[1])\n\n    for i in np.arange(0, b.shape[0]):\n        I[i] = I[i, :] / b[i, i]\n        b[i] = b[i, :] / b[i, i]\n        for j in np.arange(0, b.shape[0]):\n            if j == i:\n                pass\n            else:\n                I[j] = I[j] - b[j, i] * I[i]\n                b[j] = b[j] - b[j, i] * b[i]\n\n    def check_result(result, actual):\n\n        res = np.matmul(result, actual).astype(\"int\")\n        #print(res)\n        if (np.eye(result.shape[0], result.shape[1]) == res).all():\n            ok = True\n            d_res = None\n        else:\n            ok = False\n            d_res = {\"input\": actual}\n\n        return ok, d_res\n\n    if not check_result(I, c)[0]:\n        return (f\"Something not ok. Input {check_result(I, c)[1]['input']}\")\n\n    return I\n\n\n# b = np.array(  [[35, 40, 82],\n#                 [68, 86, 29],\n#                 [38, 53, 13]])\n\nprint(f\"Result Problem 3: {matrix_invert_first_principles(b)}\")\n\n\"\"\"\nProblem 5:  Numerical Integration using Monte Carlo simulation.\n\n\"\"\"\n\ndef integrate_func_monte_carlo(func,a,b,N=1000):\n    x = np.random.uniform(a, b, N)\n    res = func(x)\n    return ((b-a)/N)*sum(res)\n\ndef func0(x):\n    return x\n\ndef func_a(x):\n    return np.exp(-x**2)\n\ndef func_b(x):\n    return 1/(1 + x**2)\n\ndef func_c(x):\n    return np.sqrt(x**4 + 1)\n\ndef confidence_interval(arr, p = 0.95):\n\n    u = arr.mean()\n    sd = arr.std()\n    z = stat.norm.ppf(1-(1-p)/2)\n\n    ci = z*(sd/np.sqrt(len(arr)))\n    d = {\"mean\": u,\n         \"interval\":ci}\n    return d\n\ndef compute_value(func,a,b,theo_vaule,N=1000):\n    print(N)\n    r = []\n    for _ in np.arange(0,100):\n        r.append(integrate_func_monte_carlo(func, a, b, N))\n\n    result = np.array(r)\n    diff_arr = result - theo_vaule\n    result_dict = {\"result\":result}\n    result_dict.update(confidence_interval(diff_arr))\n\n    return result_dict\n\nl_N = [10, 50, 100, 500, 1000, 5000, 10000, 50000, 1000000]\n#solutions :\n\nsolution_a = [compute_value(func_a, 0, 1, 0.5, N) for N in l_N]\nsolution_b = [compute_value(func_b, 1, 2, 0.5, N) for N in l_N]\nsolution_c = [compute_value(func_c, 0, 1, 0.5, N) for N in l_N]\n\n\n", "meta": {"hexsha": "e46406798a8426540185b67a7cb745333cc5d0b0", "size": 4496, "ext": "py", "lang": "Python", "max_stars_repo_path": "IISc Training Assignment/PythonPractice.py", "max_stars_repo_name": "Abhi1588/PricingToolBox", "max_stars_repo_head_hexsha": "2c0bded1a6374c481113c972c819101df043d9f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IISc Training Assignment/PythonPractice.py", "max_issues_repo_name": "Abhi1588/PricingToolBox", "max_issues_repo_head_hexsha": "2c0bded1a6374c481113c972c819101df043d9f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IISc Training Assignment/PythonPractice.py", "max_forks_repo_name": "Abhi1588/PricingToolBox", "max_forks_repo_head_hexsha": "2c0bded1a6374c481113c972c819101df043d9f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4146341463, "max_line_length": 116, "alphanum_fraction": 0.5642793594, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361156361018, "lm_q2_score": 0.9252299519377652, "lm_q1q2_score": 0.8885549065428013}}
{"text": "import scipy as sp\nimport scipy.linalg as la\n\n\ndef Problem2(Q,b,x0,tol=1e-10):\n    \"\"\"Use conjugate gradient method to minimize Ax-b\"\"\"\n    \n    x = x0.copy()\n    g = Q.dot(x)-b\n    d = -g\n    \n    ndim = x.size\n    \n    for iter in range(ndim):\n        if la.norm(g)<tol:\n            break\n        a = -1.0*(g.T.dot(d))/(d.T.dot(Q).dot(d))\n        x += a*d\n        g = Q.dot(x)-b\n        beta = (g.T.dot(Q).dot(d))/(d.T.dot(Q).dot(d))\n        d = -g+beta*d\n        \n    return x\n\ndef Problem1(A,b,x0,tol=1e-7,maxiter=5000):\n    \"\"\"Find the minimum of a function\"\"\"\n    \n    x = x0.copy()\n    Q = A.T.dot(A)\n    niter = maxiter\n    while la.norm(A.dot(x)-b)>tol and maxiter>0:\n        grad_f = 2.0*A.T.dot(A.dot(x)-b)\n        alpha_f = (grad_f.T.dot(grad_f))/(4.0*grad_f.T.dot(Q.dot(grad_f)))\n        x = x + -1.0*alpha_f*grad_f\n        niter -= 1\n        \n    return x, maxiter-niter\n    \n\"\"\"    \nExplanations:\n    We found that 4.0*denominator of alpha_f converged faster than just having the denominator.\n    \n    I wasn't able to get the eigenvector of A.T.dot(A) to converge in 1 iteration.  The lowest convergence happened in 236 iterations\n    \n\"\"\"", "meta": {"hexsha": "a9a9fe2dead8ffddf13385e316cf031a26f9a0af", "size": 1155, "ext": "py", "lang": "Python", "max_stars_repo_path": "Solutions/Algorithms/gradient.py", "max_stars_repo_name": "abefrandsen/numerical_computing", "max_stars_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Solutions/Algorithms/gradient.py", "max_issues_repo_name": "abefrandsen/numerical_computing", "max_issues_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/Algorithms/gradient.py", "max_forks_repo_name": "abefrandsen/numerical_computing", "max_forks_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-21T23:06:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T23:06:27.000Z", "avg_line_length": 25.6666666667, "max_line_length": 133, "alphanum_fraction": 0.5489177489, "include": true, "reason": "import scipy", "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102542943773, "lm_q2_score": 0.918480249045993, "lm_q1q2_score": 0.8885472112939471}}
{"text": "import numpy as np\na = np.array([1, 2, 3])\nprint(a)\nprint(a.shape) # tuple of ndim elements\nprint(a.dtype) # data types\nprint(a.ndim) # number of dimensions\nprint(a.size) # total number of elements\nprint(a.itemsize) # return size of each elements in bytes\n\nb = a * np.array([2, 0, 2]) # element wise multiplication\nc = a + np.array([4, 2, 3]) # element wise summation\nprint(b)\n\nprint(type(b))\n\n# dot product\nl1 = np.array([1, 2, 3])\nl2 = np.array([4, 5, 6])\ndot = np.dot(l1, l2) # dot = l1 @ l2\nprint(dot)\n\n# boolean indexing\nbool_arr = a > 1\nprint(bool_arr, a[bool_arr]) # a[bool_arr] will have rank 1\nb = np.where(a > 1, a, -1)\nprint(b)\n\n# fancy indexing\na = np.array([10, 19, 30, 41, 50, 61])\nidx = [1, 3, 5]\nprint(a[idx])\n\neven_idx = np.argwhere(a % 2 == 0).flatten()\nprint(a[even_idx])\n\na = np.arange(1, 7)\nprint(a, a.shape)\nb = a[:, np.newaxis]\nprint(b)\nb = a[np.newaxis, :]\nprint(b)\n\n# concatenation\nprint('Concatenation')\na = np.array([[1, 2], [3, 4]])\nb = np.array([[5, 6]])\nc = np.concatenate((a, b))\nprint(c)\nc = np.concatenate((a, b), axis = 0)\nprint(c)\nc = np.concatenate((a, b), axis = None)\nprint(c)\n\n# hstack, vstack to concatenate horizontaly or verticaly.\n\n# generate arrays\na = np.zeros((2, 3)) # deefault data types float64\na = np.ones((2, 3))\na = np.eye(3)\na = np.full((2, 3), 5.0)\nprint(a)\na = np.linspace(0, 10, 5)\nprint(a)\na = np.random.random((3, 2)) # unifor distribution\nprint(a)\na = np.random.randn(2, 3) # gaussian or normal distribution, mean = 0, var = 1\n\na = np.random.randint(2, 10, size = (2, 2))\na = np.random.choice([-2, -1, 5], size = 5)\nprint(a)\n\n# linalg\na = np.array([[1, 2], [3, 4]])\neigenvalues, eigenvectors = np.linalg.eig(a)\nprint(eigenvalues)\nprint(eigenvectors) #column vector\n# e_vec * e_val = A * e_vec\nb = eigenvectors[:, 0] * eigenvalues[0]\nc = a @ eigenvectors[:, 0]\nprint(b == c)\nprint(np.allclose(b, c))", "meta": {"hexsha": "ad722ae6fe03be9e8598eda55314620f5374f469", "size": 1857, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine_learning/numpy/basics.py", "max_stars_repo_name": "shaft49/tools-ref", "max_stars_repo_head_hexsha": "b819338151d3a57f82fd03d4655da85d08ebfeea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "machine_learning/numpy/basics.py", "max_issues_repo_name": "shaft49/tools-ref", "max_issues_repo_head_hexsha": "b819338151d3a57f82fd03d4655da85d08ebfeea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-09-26T06:23:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-04T15:24:20.000Z", "max_forks_repo_path": "machine_learning/numpy/basics.py", "max_forks_repo_name": "shaft49/tools-ref", "max_forks_repo_head_hexsha": "b819338151d3a57f82fd03d4655da85d08ebfeea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9259259259, "max_line_length": 78, "alphanum_fraction": 0.6322024771, "include": true, "reason": "import numpy", "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102571131692, "lm_q2_score": 0.9184802456988518, "lm_q1q2_score": 0.8885472106448931}}
{"text": "# Program the function distance(p1, p2) which returns the distance between the points p1 and p2 in\n# n-dimensional space. p1 and p2 will be given as arrays.\n#\n# Your program should work for all lengths of arrays, and should return -1 if the arrays aren't of\n# the same length or if both arrays are empty sets.\n#\n# If you don't know how to measure the distance between two points,\n# go here: http://mathworld.wolfram.com/Distance.html\nimport numpy as np\n\n\ndef distance(p1, p2):\n    p1 = np.asarray(p1)\n    p2 = np.asarray(p2)\n\n    # compare if both arrays are of same shape, and neither one of them of size zero\n    if p1.shape == p2.shape and (np.size(p1) != 0 or np.size(p2) != 0):\n        return np.linalg.norm(p1 - p2)\n    else:\n        return -1\n\n\nprint(distance([2, 2], [1, 1]))\nprint(distance([1], [1, 1, 1, 1, 1, 1, 1, 1, 1]))\n# test.describe(\"Normal cases\")\n# test.assertEqual(distance([2,2],[1,1]), 2**0.5)\n# test.assertEqual(distance([4],[1]), 3)\n# test.assertEqual(distance([1,1,1],[0,0,0]), 3**0.5)\n# test.assertEqual(distance([2,1,3,1],[2,0,2,-1]), 6**0.5)\n# test.assertEqual(distance([3,2,3],[0,1,1]), 14**0.5)\n\n# test.describe(\"Bad input/edge cases\")\n# test.assertEqual(distance([],[]), -1)\n# test.assertEqual(distance([1],[1,1,1,1,1,1,1,1,1]), -1)\n", "meta": {"hexsha": "bc52edefa612802b6db61f3907d0edaa8549ca1a", "size": 1264, "ext": "py", "lang": "Python", "max_stars_repo_path": "codewars/distance_between_two_points.py", "max_stars_repo_name": "stephanosterburg/coding_challenges", "max_stars_repo_head_hexsha": "601cf1360a7fdf068487106ba995955407365983", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "codewars/distance_between_two_points.py", "max_issues_repo_name": "stephanosterburg/coding_challenges", "max_issues_repo_head_hexsha": "601cf1360a7fdf068487106ba995955407365983", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codewars/distance_between_two_points.py", "max_forks_repo_name": "stephanosterburg/coding_challenges", "max_forks_repo_head_hexsha": "601cf1360a7fdf068487106ba995955407365983", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-08T00:49:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T00:49:14.000Z", "avg_line_length": 36.1142857143, "max_line_length": 98, "alphanum_fraction": 0.6518987342, "include": true, "reason": "import numpy", "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350253, "lm_q2_score": 0.9219218278830521, "lm_q1q2_score": 0.8885297677739884}}
{"text": "import numpy as np\r\nimport math\r\nfrom sklearn import metrics\r\n\r\ndef NMI(A,B):\r\n    # len(A) should be equal to len(B)\r\n    total = len(A)\r\n    A_ids = set(A)\r\n    B_ids = set(B)\r\n\r\n    #Mutual information\r\n    MI = 0\r\n    eps = 1.4e-45\r\n    for idA in A_ids:\r\n        for idB in B_ids:\r\n            idAOccur = np.where(A==idA)\r\n            idBOccur = np.where(B==idB)\r\n            idABOccur = np.intersect1d(idAOccur,idBOccur)\r\n            px = len(idAOccur[0]) / total\r\n            py = len(idBOccur[0]) / total\r\n            pxy = len(idABOccur) / total\r\n            MI = MI + pxy * math.log(pxy / (px * py) + eps)\r\n    # Normalized Mutual information\r\n    Hx = 0\r\n    for idA in A_ids:\r\n        idAOccurCount = 1.0*len(np.where(A==idA)[0])\r\n        Hx = Hx - (idAOccurCount/total)*math.log(idAOccurCount/total+eps)\r\n    Hy = 0\r\n    for idB in B_ids:\r\n        idBOccurCount = 1.0*len(np.where(B==idB)[0])\r\n        Hy = Hy - (idBOccurCount/total)*math.log(idBOccurCount/total+eps)\r\n    MIhat = 2.0*MI/(Hx+Hy)\r\n    return MIhat\r\n\r\ndef H(x : np.ndarray):\r\n    where = x > 0.0001\r\n    entropy = x[where] * np.log(x[where])\r\n    return - np.sum(entropy)\r\n\r\ndef my_NMI(A, B):\r\n    length = len(A)\r\n    set_A = set(A)\r\n    set_B = set(B)\r\n\r\n    p_a = np.array([np.sum(A == i) / length for i in set_A])\r\n    p_b = np.array([np.sum(B == i) / length for i in set_B])\r\n\r\n    H_a = H(p_a)\r\n    H_b = H(p_b)\r\n\r\n    eps = 1e-10\r\n    MI = 0\r\n    for i, x in enumerate(set_A):\r\n        a_equals_x = np.where(A == x)\r\n        for j, y in enumerate(set_B):\r\n            \r\n            b_equals_y = np.where(B == y)\r\n\r\n            joint = np.intersect1d(a_equals_x, b_equals_y)\r\n            joint_p = len(joint) / length\r\n            MI += joint_p * math.log(joint_p / (p_a[i] * p_b[j]) + eps)\r\n    \r\n    NMI = 2 * MI / (H_a + H_b)\r\n    return NMI\r\n\r\n\r\nif __name__ == '__main__':\r\n    A = np.array([1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3])\r\n    B = np.array([1,2,1,1,1,1,1,2,2,2,2,3,1,1,3,3,3])\r\n    \r\n    # print(metrics.normalized_mutual_info_score(A, B))\r\n    print(my_NMI(A, B))\r\n    # print(NMI(A, B))", "meta": {"hexsha": "731e4b611e9f094158998aea97349dc04711e5b6", "size": 2082, "ext": "py", "lang": "Python", "max_stars_repo_path": "NMI.py", "max_stars_repo_name": "ClayLiu/Cross-Entropy-Clustering-with-SSA", "max_stars_repo_head_hexsha": "16448c6690624e9a99d1833cfd739b41ea9b34a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-24T17:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-24T17:54:11.000Z", "max_issues_repo_path": "NMI.py", "max_issues_repo_name": "ClayLiu/Cross-Entropy-Clustering-with-SSA", "max_issues_repo_head_hexsha": "16448c6690624e9a99d1833cfd739b41ea9b34a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NMI.py", "max_forks_repo_name": "ClayLiu/Cross-Entropy-Clustering-with-SSA", "max_forks_repo_head_hexsha": "16448c6690624e9a99d1833cfd739b41ea9b34a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-02T08:22:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-02T08:22:28.000Z", "avg_line_length": 28.5205479452, "max_line_length": 74, "alphanum_fraction": 0.5220941402, "include": true, "reason": "import numpy", "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290955604489, "lm_q2_score": 0.9149009561531425, "lm_q1q2_score": 0.8884869380763912}}
{"text": "from scipy import stats\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport jax.scipy.stats as jstats\nfrom jax import grad\n\n# various beta distribution shapes\nx = np.linspace(0.0, 1.0, 100)\nplt.plot(x, stats.beta.pdf(x, a=0.5, b=0.5), label=f'a={0.5}, b={0.5}')\nplt.plot(x, stats.beta.pdf(x, a=1.0, b=1.0), label=f'a={1.0}, b={1.0}')\nplt.plot(x, stats.beta.pdf(x, a=10.0, b=10.0), label=f'a={10.0}, b={10.0}')\nplt.plot(x, stats.beta.pdf(x, a=5.0, b=20.0), label=f'a={5.0}, b={20.0}')\nplt.plot(x, stats.beta.pdf(x, a=20.0, b=5.0), label=f'a={20.0}, b={5.0}')\nplt.ylabel('Beta PDF')\nplt.xlabel('Action')\nplt.legend()\nplt.show()\n\n# action distribution\nplt.plot(x, stats.beta.pdf(x, a=2.0, b=2.0), label=f'a={2.0}, b={2.0}')\nplt.axvline(0.1, color='red')\nplt.legend()\nplt.xlabel('Action')\nplt.ylabel('Beta PDF')\nplt.show()\n\n# beta distribution at x=0.1 for varying values of a\na = np.linspace(0.1, 2.0, 100)\npdf_at_x = [stats.beta.pdf(x=0.1, a=a, b=2.0) for a in a]\nplt.plot(a, pdf_at_x)\nplt.xlabel('a')\nplt.ylabel('Beta PDF @ x=0.1, b=2.0')\nplt.xlim((0.1, 2.0))\nplt.show()\n\n# modified beta distribution to increase the density at x=0.1\nplt.plot(x, stats.beta.pdf(x, a=2.0, b=2.0), label=f'a={2.0}, b={2.0}')\nplt.plot(x, stats.beta.pdf(x, a=0.6, b=2.0), label=f'a={0.6}, b={2.0}')\nplt.axvline(0.1, color='red')\nplt.legend()\nplt.xlabel('Action')\nplt.ylabel('Beta PDF')\nplt.show()\n\n\n# 1. Define the function for which we want a gradient.\ndef jax_beta_pdf(\n        x: float,\n        a: float,\n        b: float\n):\n    return jstats.beta.pdf(x=x, a=a, b=b, loc=0.0, scale=1.0)\n\n\n# 2. Ask JAX for the gradient with respect to the second argument (shape parameter a).\njax_beta_pdf_grad = grad(jax_beta_pdf, argnums=1)\n\n# 3. Calculate the gradient that we want.\nprint(f'{jax_beta_pdf_grad(0.1, 2.0, b=2.0)}')\n", "meta": {"hexsha": "c84def31c528690088e36b9785163f1df8d22acc", "size": 1803, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/case_studies/mountain-car-continuous-figs/beta-dist.py", "max_stars_repo_name": "MatthewGerber/rlai", "max_stars_repo_head_hexsha": "f390433c3adc285e1e9cc113deed7009b2e6dd5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-05-09T22:30:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:42:56.000Z", "max_issues_repo_path": "docs/case_studies/mountain-car-continuous-figs/beta-dist.py", "max_issues_repo_name": "MatthewGerber/rlai", "max_issues_repo_head_hexsha": "f390433c3adc285e1e9cc113deed7009b2e6dd5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2020-11-18T03:30:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-12T04:19:16.000Z", "max_forks_repo_path": "docs/case_studies/mountain-car-continuous-figs/beta-dist.py", "max_forks_repo_name": "MatthewGerber/rlai", "max_forks_repo_head_hexsha": "f390433c3adc285e1e9cc113deed7009b2e6dd5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-24T16:48:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-24T16:48:59.000Z", "avg_line_length": 30.05, "max_line_length": 86, "alphanum_fraction": 0.6428175263, "include": true, "reason": "import numpy,from scipy,import jax,from jax", "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147201714923, "lm_q2_score": 0.9136765198878883, "lm_q1q2_score": 0.8884724974140439}}
{"text": "\"\"\"Bracketing Methods\"\"\"\r\nimport math as m\r\n\r\n\"\"\"Bisection Method with error\"\"\" \"\"\"ROOT FINDING\"\"\"\r\n\r\ndef f(x):\r\n    return x**3 - 4*(x*2) + 10\r\n\r\nx_lower = 200\r\nx_upper = -300\r\ncounter = 0\r\nerror = 0.000001\r\nwhile True:\r\n    counter +=1\r\n    x_mid = (x_lower+x_upper)/2\r\n    if f(x_lower)*f(x_upper)>0:\r\n        print('The upper and lower limits have not been proper')\r\n        break\r\n    if f(x_lower)*f(x_mid)<0:\r\n        x_upper = x_mid\r\n    if f(x_lower)*f(x_mid)>0:\r\n        x_lower = x_mid\r\n    if -error <= f(x_lower)*f(x_mid) <= error:\r\n        print(f'We have found the root at x = {x_mid} after {counter} iterations')\r\n        break\r\n    \r\n    \r\n\"\"\"False Position Method\"\"\" \"\"\"ROOT FINDING\"\"\" \"\"\"Similar Triangle method for finding the roots\"\"\"\r\nMAX_ITER = 1000000 \r\na = 200\r\nb = -300\r\n\r\n# The function is x^3 - x^2 + 2 \r\ndef func(x): \r\n    return (x**3 - 4*(x*2) + 10) \r\n# Prints root of func(x) in interval [a, b] \r\ndef regulaFalsi(a,b): \r\n    if func(a) * func(b) >= 0: \r\n        print(\"You have not assumed right a and b\") \r\n        return -1\r\n    c = a \r\n    # Initialize result \r\n    for i in range(MAX_ITER): \r\n        # Find the point that touches x axis \r\n        c = (a * func(b) - b * func(a))/ (func(b) - func(a)) \r\n        # Check if the above found point is root \r\n        if func(c) == 0: \r\n            break \r\n        # Decide the side to repeat the steps \r\n        elif func(c) * func(a) < 0: \r\n            b = c \r\n        else: \r\n            a = c \r\n    print(\"The value of root is : \" , '%.4f' %c) \r\n    return\r\nregulaFalsi(a,b)\r\n\r\n\"\"\"Modified false Position Method\"\"\" \"\"\"ROOT FINDING\"\"\"\r\n\r\ndef modregulaFalsi(a,b): \r\n    if func(a) * func(b) >= 0: \r\n        print(\"You have not assumed right a and b\") \r\n        return -1\r\n    c = a \r\n   # Initialize result \r\n    for i in range(MAX_ITER): \r\n    # Find the point that touches x axis \r\n        c1 = (a * 0.5*func(b) - b * func(a))/(0.5*func(b) - func(a))\r\n        c2 = (a * func(b) - b * 0.5* func(a))/(func(b) - 0.5* func(a))\r\n        if func(c1) < func(c2): \r\n            c = c1\r\n        else: \r\n            c = c2\r\n        # Check if the above found point is root \r\n        if func(c) == 0: \r\n            break \r\n        elif func(c) * func(a) < 0: \r\n            b = c \r\n        else: \r\n            a = c \r\n            print(\"The value of root is : \" , '%.4f' %c) \r\n            break\r\n        \r\nmodregulaFalsi(a,b)\r\n\r\n\"\"\"Incremental Search Techniques for finding loads of roots\"\"\" \"\"\"ROOT FINDING\"\"\"\r\n\r\ndef naive_root(f, x_guess, tolerance, step_size):\r\n    steps_taken = 0\r\n    while abs(f(x_guess)) > tolerance:\r\n        if f(x_guess) > 0:\r\n            x_guess -= step_size\r\n        elif f(x_guess) < 0:\r\n            x_guess += step_size\r\n        else:\r\n            return x_guess\r\n        steps_taken += 1\r\n    return x_guess, steps_taken\r\n\r\nf = lambda x: x**2 - 20\r\nroot, steps = naive_root(f, x_guess=4.5, tolerance=.01, step_size=.001)\r\nprint (\"root is:\", root)\r\nprint (\"steps taken:\", steps)\r\n\r\n\"\"\"Open Root Finding Methods\"\"\" \"\"\"ROOT FINDING\"\"\"\r\n\r\ndef f(x):\r\n    return x*x*x + x*x -1\r\n# Re-writing f(x)=0 to x = g(x)\r\ndef g(x):\r\n    return 1/m.sqrt(1+x)\r\n# Implementing Fixed Point Iteration Method\r\ndef fixedPointIteration(x0, e, N): \r\n    print('\\n\\n*** FIXED POINT ITERATION ***')\r\n    step = 1\r\n    flag = 1\r\n    condition = True\r\n    while condition:\r\n        x1 = g(x0)\r\n        print('Iteration-%d, x1 = %0.6f and f(x1) = %0.6f' % (step, x1, f(x1)))\r\n        x0 = x1\r\n        step = step + 1 \r\n        if step > N:\r\n            flag=0\r\n            break \r\n        condition = abs(f(x1)) > e\r\n        if flag==1:\r\n            print('\\nRequired root is: %0.8f' % x1)\r\n        else:\r\n            print('\\nNot Convergent.')\r\n            \r\n# Input Section\r\nx0 = 1\r\ne = 0.01\r\nN = 1000\r\n\r\nfixedPointIteration(x0, e, N)    \r\n        \r\n\"\"\"Newton Raphson\"\"\" \"\"\"ROOT FINDING\"\"\" \"\"\"BEST TO USE BUT HAS PROBLEMS WITH DERIVATIVE IF EQUATION IS DIFFICULT\"\"\"\r\n\r\ndef newton(f,Df,x0,epsilon,max_iter):\r\n    \"\"\"Solution of f(x)=0 by Newton's method.\r\n    Parameters\r\n    ----------\r\n    f : function for which we are searching for a solution \r\n    f(x)=0.\r\n    Df : Derivative of f(x).\r\n    x0 : Initial guess for a solution f(x)=0.\r\n    epsilon : number\r\n    Stopping criteria is abs(f(x)) < epsilon.\r\n    max_iter : integer\r\n    Maximum number of iterations\r\n    Examples\r\n    --------\r\n    >>> f = lambda x: x**2 - x - 1\r\n    >>> Df = lambda x: 2*x - 1\r\n    >>> newton(f,Df,1,1e-8,10)\r\n    Found solution after 5 iterations.\r\n    1.618033988749989  \"\"\"       \r\n    xn = x0\r\n    for n in range(0,max_iter):\r\n        fxn = f(xn)\r\n    if abs(fxn) < epsilon:\r\n        print('Found solution after',n,'iterations.')\r\n    return xn\r\n    Dfxn = Df(xn)\r\n    if Dfxn == 0:\r\n        print('Zero derivative. No solution found.')\r\n    return None\r\n    xn = xn - fxn/Dfxn\r\n    print('Exceeded maximum iterations. No solution found.')\r\n    return None\r\n\r\nf = lambda x: x**4 - x - 1\r\ndf= lambda x: 4*x**3 - 1\r\nx0=1\r\nepsilon=0.001\r\nmax_iter=100\r\nsolution = newton(f,df,x0,epsilon,max_iter)\r\nprint(f'solution {solution}')\r\n      \r\n\"\"\"Secant Technique\"\"\"\r\n\r\ndef secant(f,a,b,N): \r\n    if f(a)*f(b) >= 0: \r\n        print(\"Secant method fails.\") \r\n        return None\r\n    a_n = a\r\n    b_n = b \r\n    for n in range(1,N+1): \r\n        m_n = a_n - f(a_n)*(b_n -a_n)/(f(b_n) - f(a_n)) \r\n        f_m_n = f(m_n) \r\n    if f(a_n)*f_m_n < 0: \r\n        a_n = a_n\r\n        b_n = m_n\r\n    elif f(b_n)*f_m_n < 0: \r\n        a_n = m_n\r\n        b_n = b_n\r\n    elif f_m_n == 0: \r\n        print(\"Found exact solution.\") \r\n        return m_n\r\n    else:\r\n        print(\"Secant method fails.\") \r\n        return None\r\n    return a_n - f(a_n)*(b_n - a_n)/(f(b_n) - f(a_n))        \r\n            \r\nf = lambda x: x**4 - x - 1\r\nsolution = secant(f,1,2,25)\r\nprint(f'Secant Method solutions: {solution}')\r\n\r\n\"\"\"Modified Secant Technique\"\"\"        \r\n        \r\ndef secant_method(func, x0, alpha=1.0, tol=1E-9, maxit=200):\r\n    \"\"\"\r\n    Uses the secant method to find f(x)=0. \r\n    INPUTS\r\n    * f : function f(x)\r\n    * x0 : initial guess for x\r\n    * alpha : relaxation coefficient: \r\n    modifies Secant step size\r\n    * tol : convergence tolerance\r\n    * maxit : maximum number of iteration, default=200 \r\n    \"\"\"\r\n    x, xprev = x0, 1.001*x0\r\n    f, fprev = x**4 - x - 1, xprev**4 - xprev - 1\r\n    rel_step = 2.0 *tol\r\n    k = 0\r\n    rel_step = abs(x-xprev)/abs(x)\r\n    # Full secant step\r\n    dx = -f/(f - fprev)*(x - xprev)\r\n    while (abs(f) > tol) and (rel_step) > tol and (k<maxit): \r\n        if x == 0:\r\n            x = 1\r\n        rel_step = abs(x-xprev)/abs(x)\r\n    # Full secant step\r\n        dx = -f/(f - fprev)*(x - xprev)\r\n    # Update `xprev` and `x` simultaneously\r\n        xprev, x = x, x + alpha*dx\r\n    # Update `fprev` and `f`:\r\n        fprev, f = f, func(x)\r\n        k += 1\r\n        # print('{0:10d} {1:12.5f} {2:12.5f}{3:12.5f} {4:12.5f}'\\.format(k, xprev, fprev, rel_step, alpha*dx))\r\n    return x\r\nfuncT = lambda x: x**4 - x - 1\r\nsolution = secant_method(funcT,1,alpha=1.0,tol=1E-9,maxit=200)\r\nprint(f'Modified Secant Method solutions: {solution}')\r\n\r\n\r\n\"\"\"Inverse Quadratic Interpolation\"\"\"\r\n\r\ndef inverse_quadratic_interpolation(f, x0, x1, x2, max_iter=20, \r\n    tolerance=1e-5):\r\n    steps_taken = 0\r\n    while steps_taken < max_iter and abs(x1-x0) > tolerance: # last guess and new guess are v close\r\n        fx0 = f(x0)\r\n        fx1 = f(x1)\r\n        fx2 = f(x2)\r\n        L0 = (x0 * fx1 * fx2) / ((fx0 - fx1) * (fx0 - fx2))\r\n        L1 = (x1 * fx0 * fx2) / ((fx1 - fx0) * (fx1 - fx2))\r\n        L2 = (x2 * fx1 * fx0) / ((fx2 - fx0) * (fx2 - fx1))\r\n        new = L0 + L1 + L2\r\n        x0, x1, x2 = new, x0, x1\r\n        steps_taken += 1\r\n    return x0, steps_taken\r\nf = lambda x: x**2 - 20\r\nroot, steps = inverse_quadratic_interpolation(f, 4.3, 4.4, 4.5)\r\nprint (\"Inverse Quadratic Interpolation root is:\", root)\r\nprint (\"steps taken:\", steps)\r\n\r\n\"\"\"Brent Method\"\"\"\r\ndef f_01 ( x ):\r\n  import numpy as np\r\n  value = np.sin ( x ) - 0.5 * x\r\n  return value\r\n\r\n\r\ndef zero ( a, b, machep, t, f ):\r\n\r\n#*****************************************************************************80\r\n#\r\n## ZERO seeks the root of a function F(X) in an interval [A,B].\r\n#\r\n#  Discussion:\r\n#\r\n#    The interval [A,B] must be a change of sign interval for F.\r\n#    That is, F(A) and F(B) must be of opposite signs.  Then\r\n#    assuming that F is continuous implies the existence of at least\r\n#    one value C between A and B for which F(C) = 0.\r\n#\r\n#    The location of the zero is determined to within an accuracy\r\n#    of 6 * MACHEPS * abs ( C ) + 2 * T.\r\n#\r\n#    Thanks to Thomas Secretin for pointing out a transcription error in the\r\n#    setting of the value of P, 11 February 2013.\r\n#\r\n#  Licensing:\r\n#\r\n#    This code is distributed under the GNU LGPL license.\r\n#\r\n#  Modified:\r\n#\r\n#    03 December 2016\r\n#\r\n#  Author:\r\n#\r\n#    Original FORTRAN77 version by Richard Brent\r\n#    Python version by John Burkardt\r\n#\r\n#  Reference:\r\n#\r\n#    Richard Brent,\r\n#    Algorithms for Minimization Without Derivatives,\r\n#    Dover, 2002,\r\n#    ISBN: 0-486-41998-3,\r\n#    LC: QA402.5.B74.\r\n#\r\n#  Parameters:\r\n#\r\n#    Input, real A, B, the endpoints of the change of sign interval.\r\n#\r\n#    Input, real MACHEP, an estimate for the relative machine\r\n#    precision.\r\n#\r\n#    Input, real T, a positive error tolerance.\r\n#\r\n#    Input, real value = F ( x ), the name of a user-supplied\r\n#    function which evaluates the function whose zero is being sought.\r\n#\r\n#    Output, real VALUE, the estimated value of a zero of\r\n#    the function F.\r\n#\r\n\r\n#\r\n#  Make local copies of A and B.\r\n#\r\n  sa = a\r\n  sb = b\r\n  fa = f ( sa )\r\n  fb = f ( sb )\r\n\r\n  c = sa\r\n  fc = fa\r\n  e = sb - sa\r\n  d = e\r\n\r\n  while ( True ):\r\n    if ( abs ( fc ) < abs ( fb ) ):\r\n      sa = sb\r\n      sb = c\r\n      c = sa\r\n      fa = fb\r\n      fb = fc\r\n      fc = fa\r\n    tol = 2.0 * machep * abs ( sb ) + t\r\n    m = 0.5 * ( c - sb )\r\n    if ( abs ( m ) <= tol or fb == 0.0 ):\r\n      break\r\n    if ( abs ( e ) < tol or abs ( fa ) <= abs ( fb ) ):\r\n      e = m\r\n      d = e\r\n    else:\r\n      s = fb / fa\r\n      if ( sa == c ):\r\n        p = 2.0 * m * s\r\n        q = 1.0 - s\r\n      else:\r\n        q = fa / fc\r\n        r = fb / fc\r\n        p = s * ( 2.0 * m * q * ( q - r ) - ( sb - sa ) * ( r - 1.0 ) )\r\n        q = ( q - 1.0 ) * ( r - 1.0 ) * ( s - 1.0 )\r\n      if ( 0.0 < p ):\r\n        q = - q\r\n      else:\r\n        p = - p\r\n      s = e\r\n      e = d\r\n      if ( 2.0 * p < 3.0 * m * q - abs ( tol * q ) and p < abs ( 0.5 * s * q ) ):\r\n        d = p / q\r\n      else:\r\n        e = m\r\n        d = e\r\n    sa = sb\r\n    fa = fb\r\n    if ( tol < abs ( d ) ):\r\n      sb = sb + d\r\n    elif ( 0.0 < m ):\r\n      sb = sb + tol\r\n    else:\r\n      sb = sb - tol\r\n    fb = f ( sb )\r\n    if ( ( 0.0 < fb and 0.0 < fc ) or ( fb <= 0.0 and fc <= 0.0 ) ):\r\n      c = sa\r\n      fc = fa\r\n      e = sb - sa\r\n      d = e\r\n  value = sb\r\n  return value\r\n\r\ndef zero_test ( ):\r\n\r\n#*****************************************************************************80\r\n#\r\n## ZERO_TEST tests the Brent zero finding routine on all test functions.\r\n#\r\n#  Licensing:\r\n#\r\n#    This code is distributed under the GNU LGPL license.\r\n#\r\n#  Modified:\r\n#\r\n#    03 December 2016\r\n#\r\n#  Author:\r\n#\r\n#    John Burkardt\r\n#\r\n  import numpy as np\r\n\r\n  print ( '' )\r\n  print ( 'ZERO_TEST' )\r\n  print ( '  ZERO seeks a root X of a function F()' )\r\n  print ( '  in an interval [A,B].' )\r\n\r\n  eps = 2.220446049250313E-016\r\n  machep = np.sqrt ( eps )\r\n  t = 10.0 * np.sqrt ( eps )\r\n  a = 1.0\r\n  b = 2.0\r\n  x = zero ( a, b, machep, t, f_01 )\r\n  print ( '' )\r\n  print ( '  f_01(x) = sin ( x ) - x / 2' )\r\n  print ( '  f_01(%g) = %g' % ( x, f_01 ( x ) ) )\r\n\r\ndef timestamp ( ):\r\n\r\n#*****************************************************************************80\r\n#\r\n## TIMESTAMP prints the date as a timestamp.\r\n#\r\n#  Licensing:\r\n#\r\n#    This code is distributed under the GNU LGPL license. \r\n#\r\n#  Modified:\r\n#\r\n#    06 April 2013\r\n#\r\n#  Author:\r\n#\r\n#    John Burkardt\r\n#\r\n#  Parameters:\r\n#\r\n#    None\r\n#\r\n  import time\r\n\r\n  t = time.time ( )\r\n  print ( time.ctime ( t ) )\r\n\r\n  return None\r\n\r\ndef timestamp_test ( ):\r\n\r\n#*****************************************************************************80\r\n\r\n  import platform\r\n\r\n  print ( '' )\r\n  print ( 'TIMESTAMP_TEST:' )\r\n  print ( '  Python version: %s' % ( platform.python_version ( ) ) )\r\n  print ( '  TIMESTAMP prints a timestamp of the current date and time.' )\r\n  print ( '' )\r\n\r\n  timestamp ( )\r\n#\r\n#  Terminate.\r\n#\r\n  print ( '' )\r\n  print ( 'TIMESTAMP_TEST:' )\r\n  print ( '  Normal end of execution.' )\r\n  return\r\n\r\nif ( __name__ == '__main__' ):\r\n  timestamp ( )\r\n  zero_test ( )\r\n  timestamp ( )\r\n  \r\n\"\"\"Ralston - Rabinowitz for Multiple Roots\"\"\"\r\n\r\nfunction = lambda x: (x-3)*(x-1)*(x-1)\r\nderivative = lambda x: 3*x**2-10*x+7\r\nsecond_derivative = lambda x: 6*x -10\r\n\r\ndef u(x):\r\n    return function(x)/derivative(x)\r\n\r\ndef derivative_u(x):\r\n    return (derivative(x)**2-function(x)*second_derivative(x))/(derivative(x)**2)\r\n\r\n\r\ndef Rolston_Rabinowitz(f,Df,x0,epsilon,max_iter):\r\n    \"\"\"Solution of f(x)=0 by Newton's method.\r\n    Parameters\r\n    ----------\r\n    f : function for which we are searching for a solution \r\n    f(x)=0.\r\n    Df : Derivative of f(x).\r\n    x0 : Initial guess for a solution f(x)=0.\r\n    epsilon : number\r\n    Stopping criteria is abs(f(x)) < epsilon.\r\n    max_iter : integer\r\n    Maximum number of iterations\r\n    Examples\r\n    --------\r\n    >>> f = lambda x: x**2 - x - 1\r\n    >>> Df = lambda x: 2*x - 1\r\n    >>> newton(f,Df,1,1e-8,10)\r\n    Found solution after 5 iterations.\r\n    1.618033988749989  \"\"\"       \r\n    xn = x0\r\n    for n in range(0,max_iter):\r\n        fxn = f(xn)\r\n    if abs(fxn) < epsilon:\r\n        print('Found solution after',n,'iterations.')\r\n        return xn\r\n    Dfxn = Df(xn)\r\n    if Dfxn == 0:\r\n        print('Zero derivative. No solution found.')\r\n        return None\r\n    xn = xn - u(xn)/(derivative_u(xn))\r\n    print('Exceeded maximum iterations. No solution found.')\r\n    return None\r\n\r\n\r\nx0=1\r\nepsilon=0.01\r\nmax_iter=100\r\nsolution = newton(function,derivative,x0,epsilon,max_iter)\r\nprint(f'The solution of Rolstion using derivatives is: {solution}')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "b814e84da929d512d310070182acf3afc3b8faac", "size": 14233, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lecture_5_Tasks.py", "max_stars_repo_name": "oliver779/Computational_Methods_Course", "max_stars_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lecture_5_Tasks.py", "max_issues_repo_name": "oliver779/Computational_Methods_Course", "max_issues_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lecture_5_Tasks.py", "max_forks_repo_name": "oliver779/Computational_Methods_Course", "max_forks_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4615384615, "max_line_length": 116, "alphanum_fraction": 0.509168833, "include": true, "reason": "import numpy", "num_tokens": 4461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551515780319, "lm_q2_score": 0.9207896704568164, "lm_q1q2_score": 0.8884286570600977}}
{"text": "\"\"\"Binomial pricing of options\"\"\"\nimport numpy as np\n# pylint: disable=invalid-name\n\n\ndef call_option(S, K):\n    return max(S - K, 0)\n\n\ndef put_option(S, K):\n    return max(K - S, 0)\n\n\ndef risk_neutral_prob(r, U, D, d_t=0):\n    return (np.exp(r * d_t) - D) / (U - D)\n\n\ndef option_price(p, C_u, C_d, r, d_t):\n    return (p * C_u + (1 - p) * C_d) * np.exp(-r * d_t)\n\n\ndef main():\n    S0 = 100\n    K = 105\n    r = 0.03\n    U = 1.07\n    D = 1 / U\n    d_t = 1 / 12.0\n    M = 6\n    p = risk_neutral_prob(r, U, D, d_t)\n    print(f'p={p}')\n    C_u = put_option(S0*U, K)\n    C_d = put_option(S0*D, K)\n    C0 = option_price(p, C_u, C_d, r, d_t)\n\n    # Stock price lattice\n    S = []\n    for i in range(M, 0, -1):\n        Ss = []\n        for j in range(i + 1):\n            Ss.append(S0 * U ** (i - j) * D ** j)\n        print(Ss)\n        S.append(Ss)\n    print([S0])\n    S.append([S0])\n\n    # EUR option lattice\n    C = []\n    C.append(put_option(S0 * U ** (M - j) * D ** j, K) for j in range(M))\n    for i in range(M, 0, -1):\n        Cs = []\n        for j in range(i + 1):\n            C0 = put_option(S0 * U ** (i - j) * D ** j, K)\n            C1 = option_price(\n                p,\n                C[-1][j],\n                C[-1][j],\n                r, (M - i) * d_t)\n            Cs.append(C0)\n        print(Cs)\n        C.append(Cs)\n    print([option_price(p, put_option(U * S0, K), put_option(D * S0, K), r, M * d_t)])\n\n\nif __name__ == '__main__':\n    main()\n\n\"\"\"\n# init vars\nr = 0.02\nd_t = 1.0 / 12\nS0 = 10.0\nK = 9.0\nU = 13 / S0\nD = 7.5 / S0\np = risk_neutral_prob(r, U, D, d_t)\nMODE = 'call'\n\n\nif MODE == 'call':\n    # Call option\n    C_u = call_option(13, K)\n    C_d = call_option(7.5, K)\nelif MODE == 'put':\n    # Put option\n    C_u = put_option(13, K)\n    C_d = put_option(7.5, K)\nelse:\n    raise ValueError(f'Unknown MODE {MODE}')\n\nC0 = (p * C_u + (1 - p) * C_d) * np.exp(-r * d_t)\nprint(f'U={U}')\nprint(f'D={D}')\nprint(f'p={p}')\nprint(f'C0={C0}')\n\"\"\"\n", "meta": {"hexsha": "beade253f74b7de99e96e0f4daec875716311d39", "size": 1947, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/option_pricing/binomial_pricing.py", "max_stars_repo_name": "TechnicalConsultant123/financial-maths", "max_stars_repo_head_hexsha": "b29d6cd4c0afdc89d69c4db9d11adb2ff64089e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-05-02T19:18:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-08T15:56:23.000Z", "max_issues_repo_path": "Python/option_pricing/binomial_pricing.py", "max_issues_repo_name": "qrana/financial-maths", "max_issues_repo_head_hexsha": "b29d6cd4c0afdc89d69c4db9d11adb2ff64089e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/option_pricing/binomial_pricing.py", "max_forks_repo_name": "qrana/financial-maths", "max_forks_repo_head_hexsha": "b29d6cd4c0afdc89d69c4db9d11adb2ff64089e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-15T14:51:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T23:52:38.000Z", "avg_line_length": 20.0721649485, "max_line_length": 86, "alphanum_fraction": 0.4761171032, "include": true, "reason": "import numpy", "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446509776295, "lm_q2_score": 0.9124361527383703, "lm_q1q2_score": 0.8883885794723216}}
{"text": "from math import sqrt\nfrom itertools import izip\nfrom numpy import mean\n\nfrom py_variance_std import t_percentile\n\ndef calc_slope(r, sdy, sdx): return r * (float(sdy)/sdx)\n\ndef line_fitting(x_arr, y_arr):\n    \"\"\"\n    using straight line y = mx + c;\n    m(of a sample data points) = Covariance(X,Y)/Covariance(X,X) =\n    E[(X - E(X))(Y - E(Y))]/E[(X - E(X))^2]\n    Another way: Look at calc_slope given STD Y and STD X and r\n    \"\"\"\n    xbar = mean(x_arr)\n    ybar = mean(y_arr)\n    xsqr_bar = mean([i**2 for i in x_arr])\n    xybar = mean([i*j for i,j in izip(x_arr, y_arr)])\n    #calcuate the slope m\n    m = (xbar*ybar - xybar)/(xbar**2 - xsqr_bar)\n    #calculate the y intercept\n    c = ybar - m*xbar\n    return ybar,m,xbar,c\n\ndef trace_line(x_arr, y_arr, x_start = 0):\n    y, m, x, c = line_fitting(x_arr, y_arr)\n    return [(i, (m*i)+c) for i in [x_start]+list(x_arr)]\n\ndef line_error(**params):\n    \"\"\"\n    The least squares estimates represent the minimum value;\n    http://www.pmean.com/10/LeastSquares.html\n    params: x_arr, y_arr, m,c\n    \"\"\"\n    if 'x_arr' in params and 'y_arr' in params:\n        if ('m' in params and 'c' in params):\n            m,c = params['m'], params['c']\n        else:\n            y, m, x, c = line_fitting(params['x_arr'], params['y_arr'])\n        #return difference magnitude between y,actual - y,calculated/predicted\n        return [(yi - ((m*xi)+c))**2 for yi,xi in izip(params['y_arr'], params['x_arr'])]\n\n\ndef std_error_y_estimate(n, y_line_error_var):\n    \"\"\"\n    To construct a confidence interval for the slope of the regression line, we need to know the standard error of the sampling distribution of the slope;\n\n    n: total samples in x or y;\n    y_line_error_var: sum(line_error(**params))\n\n    df = n-2 since two variables while calculating linear regression.\n    #calculate \\summ(yi - y_cap)^2 variance\n    line_error_var = line_error(**params)\n    \"\"\"\n    return sqrt(float(y_line_error_var)/(n-2))\n\ndef x_line_std(x_arr):\n    xbar = mean(x_arr)\n    return sqrt(sum([(xi - xbar)**2 for xi in x_arr]))\n\ndef std_error_linear(se_y, x_line_std):\n    \"\"\"\n    se_y: from std_error_y_estimate(n, y_line_error_var)\n    #calculate x - xbar variance and then STD\n    xbar = mean(x_arr)\n    x_line_std: x_line_std(x_arr, xbar)\n    \"\"\"\n    return se_y/x_line_std\n\ndef find_std_err_linear(x_arr, y_arr, n_sample):\n    #Find SE of SEy/SEx\n    #find descriptive params\n    ybar,m,xbar,c = line_fitting(x_arr, y_arr)\n    #find error in x\n    se_x = x_line_std(x_arr)\n    #find error in y\n    y_line_error = sum(line_error(**dict(x_arr=x_arr, y_arr=y_arr, m=m, c=c)))\n    se_y = std_error_y_estimate(n_sample, y_line_error)\n    #return standard error\n    return std_error_linear(se_y, se_x)\n\ndef r_squared(x_arr, y_arr):\n    \"\"\"\n    Literally Trying to do sqrt() of scipy.stats import pearsonr val\n    using functions in this module: linear_regression.py.\n\n    Also called Coefficient of Determination.\n    It simply means total_variation_line: How much the best fit line is\n    \"fit\" Or Away from the scattered points. High value means good fit.\n    How much % is explained by the Fitted Line.\n    High R^2 = good model, probably profitable,\n    Low R^2 = bad model, probably dangerous\n    \"\"\"\n    y, m, x, c = line_fitting(x_arr, y_arr)\n    total_var_y = ([(i-y)**2 for i in y_arr])  #(y-ybar)^2\n    #print sum(total_var_y)\n    #\\summ(yi - mxi * c)^2/\\summ(yi - ybar)^2\n    variation_not_by_line = float(sum(line_error(x_arr=x_arr, y_arr=y_arr, m=m, c=c)))/sum(total_var_y)\n    #R sqaured\n    return 1 - variation_not_by_line #total variation in x, variation in line\n\ndef calc_tscore_from_r(r2,n):\n    \"\"\"\n    Hypothesis Testing if relationship is due to sampling error.\n    r: coefficient of determination\n    n: number of elements in a sample\n    Returns: t score\n    For looking at critical t val and comparing the t score,\n    df = n-2 since there are 2 variables for correlation under test.\n    \"\"\"\n    return sqrt(r2*float(n-2)/(1 - r2))\n\ndef calc_p_from_tval_from_r(r,n, one_tailed= 0 ):\n    return t_percentile(calc_tscore_from_r(r,n), n-2, one_tailed= one_tailed)\n\ndef margin_error_linear(tscore, se): return tscore * se\n\ndef ci_linear(slope, tscore, se):\n    margin_error = margin_error_linear(tscore, se)\n    return (slope - margin_error, slope + margin_error)\n", "meta": {"hexsha": "f726a8242f8fd6b97a2dbc1d66d1b2ffa30955db", "size": 4308, "ext": "py", "lang": "Python", "max_stars_repo_path": "probability_combinatorics/linear_regression.py", "max_stars_repo_name": "codecakes/random_games", "max_stars_repo_head_hexsha": "1e670021ec97a196726e937e658878dc63ba9d34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "probability_combinatorics/linear_regression.py", "max_issues_repo_name": "codecakes/random_games", "max_issues_repo_head_hexsha": "1e670021ec97a196726e937e658878dc63ba9d34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "probability_combinatorics/linear_regression.py", "max_forks_repo_name": "codecakes/random_games", "max_forks_repo_head_hexsha": "1e670021ec97a196726e937e658878dc63ba9d34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3114754098, "max_line_length": 154, "alphanum_fraction": 0.669452182, "include": true, "reason": "from numpy", "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138177076645, "lm_q2_score": 0.9086178994073576, "lm_q1q2_score": 0.8883682752670863}}
{"text": "# Question 3 Lab Assignment 2\n# AB Satyaprakash - 180123062\n\n# imports ----------------------------------------------------------------------\nfrom math import exp, factorial\nimport numpy as np\nfrom sympy import *\n\n# functions --------------------------------------------------------------------\n\n\ndef f(x):\n    return exp(-(x**2))\n\n\ndef makePoly(x0, x1):\n    return np.array([x0, x1])\n\n\ndef secondLagrange(x0, x1, x2):\n    # The given function here is exp(-x^2)\n    f0, f1, f2 = f(x0), f(x1), f(x2)\n\n    # Represents the numerator polynomial part in the form of an np array\n    nl0 = np.polymul(makePoly(1, -x1), makePoly(1, -x2))\n    nl1 = np.polymul(makePoly(1, -x0), makePoly(1, -x2))\n    nl2 = np.polymul(makePoly(1, -x0), makePoly(1, -x1))\n\n    # Constant portion to be multiplied with the polynomial\n    cl0 = f0/((x0-x1)*(x0-x2))\n    cl1 = f1/((x1-x0)*(x1-x2))\n    cl2 = f2/((x2-x0)*(x2-x1))\n\n    # multiplying the constants\n    nl0 = nl0*cl0\n    nl1 = nl1*cl1\n    nl2 = nl2*cl2\n\n    px = nl0+nl1+nl2\n    return px\n\n\ndef derivative(x0, n):\n    x = symbols('x')\n    f = exp(-x*x)\n    fn = f.diff(x, n)\n    fn = lambdify(x, fn)\n    return fn(x0)\n\n\ndef maxError(nodes, x):\n    err = 1\n    for n in nodes:\n        err *= (x-n)\n    err /= factorial(len(nodes))\n    a = min(nodes)\n    b = max(nodes)\n    l = np.linspace(a, b, 250)\n    ret = 0\n    for z in l:\n        der = derivative(z, len(nodes))\n        ret = max(ret, abs(err*der))\n    return ret\n\n\n# ------------------------------------------------------------------------------\n# Lagrange form of interpolating polynomial P2(x) at the nodes x0 = −1, x1 = 0 and x2 = 1\nx0, x1, x2 = -1, 0, 1\npx = secondLagrange(x0, x1, x2)\nprint('The Lagrange form of interpolating polynomial P2(x) is: \\n {}\\n'.format(np.poly1d(px)))\n\n# The value of P2(0.9)\nval = 0.9\nprint('The value of P2(0.9) is {}'.format(np.polyval(px, val)))\nprint('The value of P2(0.9) rounded to 6 decimal places is {}'.format(round(np.polyval(px, val), 6)))\n\n# The true value of f(0.9)\nprint('The true value of f(0.9) is {}'.format(f(0.9)))\n\n# The max error in this calculation\nprint('The max error in this calculation is {}'.format(maxError([x0, x1, x2], val)))\n", "meta": {"hexsha": "34b1b9f6977b95943af5964c07b218f96cc96fa6", "size": 2179, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 2/Code/q3.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 2/Code/q3.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 2/Code/q3.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 26.5731707317, "max_line_length": 101, "alphanum_fraction": 0.5433685177, "include": true, "reason": "import numpy,from sympy", "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995703612219, "lm_q2_score": 0.9196425339307879, "lm_q1q2_score": 0.8882823284096534}}
{"text": "import numpy as np\nimport matplotlib.pyplot as mp\n\n# Interpolates the function f using the left rectangle method on the range [a, b] with a precision of epsilon\n# Returns the integral of f on the range [a, b], if track_efficiency = False\n# Returns the integral of f on the range [a, b] and the dictionnary containing the value of each step, otherwise\ndef rectangle(f, a, b, epsilon, track_efficiency = False):\n\tn = 1\n\t# Initial integral for n = 1\n\tcurIntegration = (b-a) * f(a)\n\n\tif track_efficiency:\n\t\tinteralArray = {}\n\t\tinteralArray[1] = curIntegration\n\n\twhile n == 1 or np.abs(lastIntegration - curIntegration) > epsilon:\n\t\tlastIntegration = curIntegration # Save the previous value\n\n\t\tn *= 2\n\t\th = (b-a)/n\n\n\t\t# Compute the new integral value\n\t\tsum = 0\n\t\tfor i in range(1, n, 2):\n\t\t\tsum += f(a + h*i)\n\n\t\tcurIntegration = h * sum + lastIntegration / 2\n\n\t\tif track_efficiency:\n\t\t\tinteralArray[n] = curIntegration\n\n\tif track_efficiency:\n\t\treturn curIntegration, interalArray\n\telse:\n\t\treturn curIntegration\n\n# Interpolates the function f using the midpoint rectangle method on the range [a, b] with a precision of epsilon\n# Returns the integral of f on the range [a, b], if track_efficiency = False\n# Returns the integral of f on the range [a, b] and the dictionnary containing the value of each step, otherwise\ndef midpoint(f, a, b, epsilon, track_efficiency = False):\n\tn = 1\n\t# Initial integral for n = 1\n\tcurIntegration = (b-a) * f((a+b)/2)\n\n\tif track_efficiency:\n\t\tinteralArray = {}\n\t\tinteralArray[1] = curIntegration\n\n\twhile n == 1 or np.abs(lastIntegration - curIntegration) > epsilon:\n\t\tlastIntegration = curIntegration # Save the previous value\n\n\t\tn *= 3\n\t\th = (b-a)/n\n\n\t\t# Compute the new integral value\n\t\tsum = 0\n\t\tfor i in range(0, n, 3):\n\t\t\tsum += f(a + h*i + h/2) + f(a + h*(i + 2) + h/2)\n\n\t\tcurIntegration = h * sum + lastIntegration / 3\n\n\t\tif track_efficiency:\n\t\t\tinteralArray[n] = curIntegration\n\n\tif track_efficiency:\n\t\treturn curIntegration, interalArray\n\telse:\n\t\treturn curIntegration\n\n# Interpolates the function f using the given method on the range [a, b] with a precision of epsilon\n# Returns the integral of f on the range [a, b], if track_efficiency = False\n# Returns the integral of f on the range [a, b] and the dictionnary containing the value of each step, otherwise\ndef integrate(method, f, a, b, epsilon, track_efficiency = False):\n\treturn method(f, a,  b, epsilon, track_efficiency)\n\ndef test_integral():\n\t# f(x) = x² + 2\n\tf = lambda x: x*x + 2\n\ta = 0\n\tb = 1\n\tepsilon = 1e-4\n\texpected = 7/3\n\tprint(\"f(x) = x² + 2\")\n\tprint(\"Expected:\", expected)\n\n\tintegralLeft, interalLeftArray = integrate(rectangle, f, a, b, epsilon, True)\n\tprint(\"--Left rectangle method--\")\n\tprint(\"Computed integral:\", integralLeft)\n\tprint(\"Relative error:\", np.abs(expected - integralLeft) / expected)\n\n\tintegralMid, interalMidArray = integrate(midpoint, f, a, b, epsilon, True)\n\tprint(\"--Middle rectangle method--\")\n\tprint(\"Computed integral:\", integralMid)\n\tprint(\"Relative error:\", np.abs(expected - integralMid) / expected)\n\n\n\tmp.plot(list(interalLeftArray.keys()), np.abs([expected] * len(interalLeftArray) - np.array(list(interalLeftArray.values()))), label = \"Left rectangle\", marker='.', linewidth = 1.0)\n\tmp.plot(list(interalMidArray.keys()), np.abs([expected] * len(interalMidArray) - np.array(list(interalMidArray.values()))), label = \"Middle rectangle\", marker='.', linewidth = 1.0)\n\tmp.xscale('log')\n\tmp.yscale('log')\n\tmp.legend()\n\tmp.title(\"Absolute error of the left rectangle and the midpoint methods\\non the function $f(x) = x^2 + 2$ on the range [0, 1] with epsilon = $10^{-4}$\")\n\tmp.xlabel(\"n, the number of calls of f\")\n\tmp.ylabel(\"Absolute error of the computed integral value\")\n\tmp.show()\n\n\nif __name__ == \"__main__\":\n\ttest_integral()", "meta": {"hexsha": "8d8818285035a8ee90c033869f44a96e68260998", "size": 3760, "ext": "py", "lang": "Python", "max_stars_repo_path": "integration.py", "max_stars_repo_name": "ImadProjects/Interpolation-and-integration-methods", "max_stars_repo_head_hexsha": "f5807c7fafb721f82f3368983946d5c1aab9ad62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "integration.py", "max_issues_repo_name": "ImadProjects/Interpolation-and-integration-methods", "max_issues_repo_head_hexsha": "f5807c7fafb721f82f3368983946d5c1aab9ad62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "integration.py", "max_forks_repo_name": "ImadProjects/Interpolation-and-integration-methods", "max_forks_repo_head_hexsha": "f5807c7fafb721f82f3368983946d5c1aab9ad62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.495412844, "max_line_length": 182, "alphanum_fraction": 0.7031914894, "include": true, "reason": "import numpy", "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760639, "lm_q2_score": 0.9324533093296392, "lm_q1q2_score": 0.8882308956819428}}
{"text": "# import modules\r\nimport numpy as np\r\n\r\n'''\r\n# Description.\r\ndetermine the area of a simple polygon whose vertices are described by \r\nordered pairs in the plane based on Gauss's area formula.\r\n\r\n# Input(s).\r\n1xn vector with x-coordinates of the polygon (xCoord).\r\n\r\n1xn vector with y-coordinates of the polygon (yCoord).\r\n\r\n# Output(s):\r\npolygon area (area)\r\n\r\n# Example1: by giving next values\r\nxCoord = np.arange(1,10)\r\nyCoord = xCoord**2\r\n\r\nis obtained: area = 84.0\r\n\r\n---\r\n area = polyarea(xCoord, yCoord)\r\n'''\r\ndef polyarea(xCoord, yCoord):\r\n    area = 0.5*np.abs(np.dot(xCoord, np.roll(yCoord, 1))-\\\r\n        np.dot(yCoord, np.roll(xCoord, 1)))\r\n    return area\r\n'''\r\nBSD 2 license.\r\n\r\nCopyright (c) 2016, Universidad Nacional de Colombia, Ludger O.\r\n   Suarez-Burgoa and Exneyder Andrés Montoya Araque.\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without\r\nmodification, are permitted provided that the following conditions are\r\nmet:  \r\n\r\n1. Redistributions of source code must retain the above copyright notice,\r\nthis list of conditions and the following disclaimer. \r\n\r\n2. Redistributions in binary form must reproduce the above copyright\r\nnotice, this list of conditions and the following disclaimer in the\r\ndocumentation and/or other materials provided with the distribution.  \r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\r\nIS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\r\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r\nPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\r\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n'''\r\n", "meta": {"hexsha": "4d26f5bb156633b087f5c2670502833e4fedf42a", "size": 2103, "ext": "py", "lang": "Python", "max_stars_repo_path": "functions/polyarea.py", "max_stars_repo_name": "eamontoyaa/CSS-pyProgram", "max_stars_repo_head_hexsha": "beb28a18cba4e4b2e6d8be556296aa6f8025defa", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2016-05-12T14:54:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T09:29:08.000Z", "max_issues_repo_path": "functions/polyarea.py", "max_issues_repo_name": "eamontoyaa/CSS-pyProgram", "max_issues_repo_head_hexsha": "beb28a18cba4e4b2e6d8be556296aa6f8025defa", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-02-27T17:34:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-17T08:44:26.000Z", "max_forks_repo_path": "functions/polyarea.py", "max_forks_repo_name": "eamontoyaa/CSS-pyProgram", "max_forks_repo_head_hexsha": "beb28a18cba4e4b2e6d8be556296aa6f8025defa", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-06-21T04:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T02:25:19.000Z", "avg_line_length": 35.05, "max_line_length": 74, "alphanum_fraction": 0.7508321446, "include": true, "reason": "import numpy", "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971992484261881, "lm_q2_score": 0.9136765204755286, "lm_q1q2_score": 0.8880867109487605}}
{"text": "# Graphical Solutions \n## Introduction to Linear Programming\n\n#Import some required packages. \nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nGraphical solution is limited to linear programming models containing only two decision variables (can be used with three variables but only with great difficulty).\n\nGraphical methods provide a picture of how a solution for a linear programming problem is obtained.\n\n\n## Product mix problem - Beaver Creek Pottery Company\nHow many bowls and mugs should be produced to maximize profits given labor and materials constraints?\n\nProduct resource requirements and unit profit:\n\nDecision Variables:\n\n$x_{1}$ = number of bowls to produce per day\n\n$x_{2}$ = number of mugs to produce per day\n\n\nProfit (Z)  Mazimization\n\nZ = 40$x_{1}$ + 50$x_{2}$\n\nLabor Constraint Check\n\n1$x_{1}$ + 2$x_{2}$ <= 40\n\nClay (Physicial Resource) Constraint Check\n\n4$x_{1}$ + 3$x_{2}$ <= 120\n\nNegative Production Constaint Check\n\n$x_{1}$ > 0\n\n$x_{2}$ > 0\n\n\n\n#Create an Array X2 from 0 to 60, and it should have a length of 61.\nx2 = np.linspace(0, 60, 61) \n\n#This is the same as starting your Excel Spreadsheet with incrementing X2\nx2\n\n#Labor Constraint Check\n# 1x1 + 2x2 <= 40\n#x1 = 40 - 2*x2\nc1 =  40 - 2*x2\nc1\n\n#Clay (Physicial Resource) Constraint Check\n#4x1 + 3x2 <= 120\n#x1 = (120 - 3*x2)/4\nc2  = (120 - 3*x2)/4\nc2\n\n#Calculate the minimum of X1 you can make per the 2 different constraints.\nct = np.minimum(c1,c2)\nct\n\n#remove those valuese that don't follow non-negativity constraint.\nct= ct[0:21]\nx2= x2[0:21] #Shape of array must be the same.\nct\n\n#Calculate the profit from the constrained \nprofit = 40*ct+50*x2 \nprofit\n\n# Make plot for the labor constraint\nplt.plot(c1, x2, label=r'1$x_{1}$ + 2$x_{2}$ <= 40')\nplt.xlim((0, 60))\nplt.ylim((0, 60))\nplt.xlabel(r'$x_{1}$') #Latex way of writing X subscript 1 (See Markdown)\nplt.ylabel(r'$x_{2}$') #Latex way of writing X subscript 1 (See Markdown)\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\nplt.fill_between(c1, x2, color='grey', alpha=0.5)\n\n\n#Graph Resource Constraint\nplt.plot(c2, x2, label=r'4$x_{1}$ + 3$x_{2}$ <= 120')\nplt.xlim((0, 60))\nplt.ylim((0, 60))\nplt.xlabel(r'$x_{1}$') #Latex way of writing X subscript 1 (See Markdown)\nplt.ylabel(r'$x_{2}$') #Latex way of writing X subscript 1 (See Markdown)\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\nplt.fill_between(c2, x2, color='grey', alpha=0.5)\n\n# Make plot for the combined constraints.\nplt.plot(c1, x2, label=r'1$x_{1}$ + 2$x_{2}$ <= 40')\nplt.plot(c2, x2, label=r'4$x_{1}$ + 3$x_{2}$ <= 120')\n#plt.plot(ct, x2, label=r'min(x$x_{1}$)')\nplt.xlim((0, 60))\nplt.ylim((0, 60))\nplt.xlabel(r'$x_{1}$') #Latex way of writing X subscript 1 (See Markdown)\nplt.ylabel(r'$x_{2}$') #Latex way of writing X subscript 1 (See Markdown)\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\nplt.fill_between(ct, x2,  color='grey', alpha=0.5)\n\nOur solution must be in in lies somewhere in the grey feasible region in the graph above. However, according to the fundamental theorum of Linear programming we know it is at a vertex. \n\n\"In mathematical optimization, the fundamental theorem of linear programming states, in a weak formulation, that the maxima and minima of a linear function over a convex polygonal region occur at the region's corners. Further, if an extreme value occurs at two corners, then it must also occur everywhere on the line segment between them.\"\n\n- [Wikipedia](https://en.wikipedia.org/wiki/Fundamental_theorem_of_linear_programming)\n\n#This returns the index position of the maximum value\nmax_value = np.argmax(profit)\nmax_value\n\n#Calculate The max Profit that is made. \nprofit_answer=profit[max_value]\nprofit_answer\n\n# Verify all constraints are integers\nx2_answer = x2[max_value]\nx2_answer\n\n# Verify all constraints are integers\nct_answer = ct[max_value]\nct_answer\n\n## Q1 Challenge\n\nWhat if the profit function is:\n\nZ = 70$x_{1}$ + 20$x_{2}$       \n\nFind the optimal solution using Python. Assign the answers to: \n\nq1_profit_answer\nq1_x1_answer\nq1_x2_answer\n\n\n", "meta": {"hexsha": "21d82b74010233b372a2cd1d03e018b073cf7585", "size": 4061, "ext": "py", "lang": "Python", "max_stars_repo_path": "site/_build/jupyter_execute/notebooks/graphical-max.py", "max_stars_repo_name": "rpi-techfundamentals/website_fall_2020_qm", "max_stars_repo_head_hexsha": "517b24801286140af5f1e10ee9099cf5d0a28b7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "site/_build/jupyter_execute/notebooks/graphical-max.py", "max_issues_repo_name": "rpi-techfundamentals/website_fall_2020_qm", "max_issues_repo_head_hexsha": "517b24801286140af5f1e10ee9099cf5d0a28b7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "site/_build/jupyter_execute/notebooks/graphical-max.py", "max_forks_repo_name": "rpi-techfundamentals/website_fall_2020_qm", "max_forks_repo_head_hexsha": "517b24801286140af5f1e10ee9099cf5d0a28b7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5985915493, "max_line_length": 339, "alphanum_fraction": 0.7261758188, "include": true, "reason": "import numpy", "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.9343951588871157, "lm_q1q2_score": 0.8880594119395905}}
{"text": "import numpy as np\n\n\ndef L2Loss(y_predicted, y_ground_truth, reduction=\"None\"):\n    \"\"\"returns l2 loss between two arrays\n\n    :param y_predicted: array of predicted values\n    :type y_predicted: ndarray\n    :param y_ground_truth: array of ground truth values\n    :type y_ground_truth: ndarray\n    :param reduction: reduction mode, defaults to \"mean\"\n    :type reduction: str, optional\n    :return: l2-loss\n    :rtype: scalar if reduction is sum or mean, else ndarray\n    \"\"\"\n    # Calculate the difference array\n    difference = y_predicted - y_ground_truth\n    # Raise every difference value to the power of 2\n    squared_difference = np.multiply(difference, difference)\n    # L2 distance is the reduced form of the squared difference array\n    if reduction == \"sum\":\n        # Reduction can be done by summing up all the values in the difference array (this is known as \"L2-Loss\")\n        l2_distance = np.sum(squared_difference)\n        return l2_distance\n    elif reduction == \"mean\":\n        # Reduction can also be done by taking the mean (this is known as \"Mean Squared Error\")\n        mean_squared_error = np.mean(squared_difference)\n        return mean_squared_error\n    elif reduction == \"None\":\n        return squared_difference\n    else:\n        print('ValueError: reduction should be \"sum\" / \"mean\" / \"None\"')\n\n\ndef main():\n    print(\"Initializing predicted and ground truth arrays:\\n\")\n    print('(NOTE: Enter the values in a space-separated format. Ex: \"5.36 1.02 2.03\")')\n    y_predicted = [\n        float(item) for item in input(\"Enter the predicted values: \").split()\n    ]\n    y_ground_truth = [\n        float(item)\n        for item in input(\"Enter the corresponding ground truth values: \").split()\n    ]\n    assert len(y_predicted) == len(\n        y_ground_truth\n    ), \"Number of predicted values {} and ground truth {} values should match\".format(\n        len(y_predicted), len(y_ground_truth)\n    )\n    y_predicted = np.array(y_predicted)\n    y_ground_truth = np.array(y_ground_truth)\n    reduction = str(input('Enter the reduction mode: \"sum\" / \"mean\" / \"None\": '))\n    loss = L2Loss(y_predicted, y_ground_truth, reduction=reduction)\n    print(\"L2-Loss with {}-reduction: {}\".format(reduction, loss))\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "202ebe786bba0d11378ef1a1d0e3a9c6f98dc116", "size": 2266, "ext": "py", "lang": "Python", "max_stars_repo_path": "losses/l2/L2.py", "max_stars_repo_name": "harshikaninawe/Machine-Learning-concepts", "max_stars_repo_head_hexsha": "b1f22003939ac4440b406c08d53da6b6ba358348", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-10-14T07:48:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T11:40:01.000Z", "max_issues_repo_path": "losses/l2/L2.py", "max_issues_repo_name": "harshikaninawe/Machine-Learning-concepts", "max_issues_repo_head_hexsha": "b1f22003939ac4440b406c08d53da6b6ba358348", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-10-14T15:19:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-29T13:47:30.000Z", "max_forks_repo_path": "losses/l2/L2.py", "max_forks_repo_name": "harshikaninawe/Machine-Learning-concepts", "max_forks_repo_head_hexsha": "b1f22003939ac4440b406c08d53da6b6ba358348", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-03T14:57:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-24T16:55:43.000Z", "avg_line_length": 38.406779661, "max_line_length": 113, "alphanum_fraction": 0.6774051192, "include": true, "reason": "import numpy", "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.9241418184118163, "lm_q1q2_score": 0.8880556560990108}}
{"text": "import numpy as np\n\nfrom scipy.optimize import linprog\n\n\ndef ex1():\n    c = np.array([-2, -3])\n    A = np.array([[1, 1], [1, 2], [-1, 1]])\n    b = np.array([3, 4, 1])\n\n    x1_bounds = (0, None)\n    x2_bounds = (0, None)\n\n    res = linprog(c, A, b, bounds=(x1_bounds, x2_bounds), method='simplex')\n    print(\"Ex1\")\n    print(res)\n\ndef ex4():\n    A = np.array([[1, -1], [-4, 1]])\n    b = np.array([1, 4])\n    \n    c_a = np.array([1, 0])\n    c_b = np.array([-2, 1])\n    c_c = np.array([8, -2])\n\n    x1_bounds = (0, None)\n    x2_bounds = (0, None)\n\n    res_a = linprog(c_a, A, b, bounds=(x1_bounds, x2_bounds), method='simplex')\n    res_b = linprog(c_b, A, b, bounds=(x1_bounds, x2_bounds), method='simplex')\n    res_c = linprog(c_c, A, b, bounds=(x1_bounds, x2_bounds), method='simplex')\n    \n    print(\"Ex4a\")\n    print(res_a)\n    print(\"Ex4b\")\n    print(res_b)\n    print(\"Ex4c\")\n    print(res_c)\n\n\ndef ex5():\n    c = np.array([1, 1, 4])\n    A = np.array([[1, -1, -1], [2, -3, -3]])\n    b = np.array([1, 2])\n\n    x1_bounds = (0, None)\n    x2_bounds = (0, None)\n    x3_bounds = (0, None)\n\n    res = linprog(c, A_eq=A, b_eq=b, bounds=(x1_bounds, x2_bounds, x3_bounds), method='simplex')\n    print(\"Ex5\")\n    print(res)\n\ndef ex6():\n    c = np.array([1, 2])\n\n    A_eq= np.array([[2, -5]])\n    b_eq = np.array([4])\n\n    x1_bounds = (0, None)\n    x2_bounds = (0, None)\n    \n    A = np.array([[-1, 2]])\n    b = np.array([-6])\n\n    res = linprog(c, A_ub=A, b_ub=b, A_eq=A_eq, b_eq=b_eq, bounds=(x1_bounds, x2_bounds), method='simplex')\n    print(\"Ex6 a = 2\")\n    print(res)\n\n    A = np.array([[-1, 3]])\n    b = np.array([-6])\n\n    res = linprog(c, A_ub=A, b_ub=b, A_eq=A_eq, b_eq=b_eq, bounds=(x1_bounds, x2_bounds), method='simplex')\n    print(\"Ex6 a = 3\")\n    print(res)\n\nex1()\nex4()\nex5()\nex6()\n", "meta": {"hexsha": "3f92822785f679aa136470efec06805987e27118", "size": 1788, "ext": "py", "lang": "Python", "max_stars_repo_path": "LAB6/ej1.py", "max_stars_repo_name": "codersUP/MO-Labs", "max_stars_repo_head_hexsha": "1df2639e762893a6c5c64fdeece1940b8f0b24e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LAB6/ej1.py", "max_issues_repo_name": "codersUP/MO-Labs", "max_issues_repo_head_hexsha": "1df2639e762893a6c5c64fdeece1940b8f0b24e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LAB6/ej1.py", "max_forks_repo_name": "codersUP/MO-Labs", "max_forks_repo_head_hexsha": "1df2639e762893a6c5c64fdeece1940b8f0b24e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0740740741, "max_line_length": 107, "alphanum_fraction": 0.5369127517, "include": true, "reason": "import numpy,from scipy", "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9787126438601956, "lm_q2_score": 0.9073122150949273, "lm_q1q2_score": 0.8879979368422068}}
{"text": "import timeit\nfrom typing import Dict, Tuple\nimport numpy as np\n\n# Generic functions\n\n\ndef trapezoidal(func, n: int, left: float, right: float) -> float:\n    res = (func(left) + func(right)) / 2\n    delta = (right - left) / n\n    for x in np.arange(left + delta, right, delta):\n        res += func(x)\n    return delta * res\n\n\ndef simpson_1_3(func, n: int, left: float, right: float) -> float:\n    res = func(left) + func(right)\n    delta = (right - left) / n\n    for i, x in enumerate(np.arange(left + delta, right, delta)):\n        res += func(x) * (4 if i % 2 == 0 else 2)\n    return delta * res / 3\n\n\ndef simpson_3_8(func, n: int, left: float, right: float) -> float:\n    res = func(left) + func(right)\n    delta = (right - left) / n\n    for i, x in enumerate(np.arange(left + delta, right, delta)):\n        res += func(x) * (2 if (i + 1) % 3 == 0 else 3)\n    return delta * res * 3 / 8\n\n\nclass Romberg:\n    def __init__(self, func, left: float, right: float) -> None:\n        self._func = func\n        self._left = left\n        self._right = right\n        self._cache: Dict[Tuple[int, int], float] = dict()\n\n    def calculate(self, j: int, k: int) -> float:\n        if k <= 0:\n            if (0, 0) in self._cache:\n                return self._cache[(0, 0)]\n            self._cache[(0, 0)] = trapezoidal(self._func, 2 ** j, self._left, self._right)\n            return self._cache[(0, 0)]\n        res = self._cache.get((j, k))\n        if res is not None:\n            return res\n        res = (4 ** k * self.calculate(j, k - 1) - self.calculate(j - 1, k - 1)) / (4 ** k - 1)\n        self._cache[(j, k)] = res\n        return res\n\n\ndef numeric_function(x: float) -> float:\n    return x * x * x * 5 - 8\n\n\ndef run_test(test_name: str, func_name: str, num_section: int) -> None:\n    setup_str = 'from integration import {0}, numeric_function'.format(func_name)\n    code_str = '{0}(numeric_function, {1}, 0.0, 5.0)'.format(func_name, num_section)\n    num_iter = 1000\n    duration_ns = timeit.timeit(code_str, setup=setup_str, number=num_iter) / num_iter * 1e+9\n    print('{0} {1}: {2:.2f}ns'.format(test_name, num_section, duration_ns))\n\n\nif __name__ == '__main__':\n    num_sections = (1, 2, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)\n    test_dict = {\n        'Trapezoidal': 'trapezoidal',\n        'Simpson 1/3': 'simpson_1_3',\n        'Simpson 3/8': 'simpson_3_8'\n    }\n    for name, f_name in test_dict.items():\n        for n in num_sections:\n            run_test(name, f_name, n)\n", "meta": {"hexsha": "677dcadb65dd9931fe47779e66eb72a80e98a2e5", "size": 2481, "ext": "py", "lang": "Python", "max_stars_repo_path": "numerical_integration_python/integration.py", "max_stars_repo_name": "shuyangsun/cisc_601_final_project", "max_stars_repo_head_hexsha": "9948a05575b7b568b605124f362357639a509b93", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numerical_integration_python/integration.py", "max_issues_repo_name": "shuyangsun/cisc_601_final_project", "max_issues_repo_head_hexsha": "9948a05575b7b568b605124f362357639a509b93", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical_integration_python/integration.py", "max_forks_repo_name": "shuyangsun/cisc_601_final_project", "max_forks_repo_head_hexsha": "9948a05575b7b568b605124f362357639a509b93", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.08, "max_line_length": 95, "alphanum_fraction": 0.5763804917, "include": true, "reason": "import numpy", "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.974434792016126, "lm_q2_score": 0.9111797057909279, "lm_q1q2_score": 0.8878852071016977}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\na = np.array([0.3, 2.9, 4.0])\nexp_a = np.exp(a)  # exponential function\nprint(exp_a)\n\nsum_exp_a = np.sum(exp_a)  # sum of the exponential functions\nprint(sum_exp_a)\n\ny = exp_a / sum_exp_a\nprint(y)\nprint(\"\")\n\na = np.array([1010, 1000, 990])\n# np.exp(a) / np.sum(np.exp(a)) #calculation of softmax func\n\nc = np.max(a)  # maximum of the components of a : 1010\nd = a - c\nprint(d)\n\nans = np.exp(a - c) / np.sum(np.exp(a - c))\nprint(ans)\n\n\ndef softmax(a):\n    c = np.max(a)\n    exp_a = np.exp(a - c)  # subtract c in case of overflow when components of a is large\n    sum_exp_a = np.sum(exp_a)\n    y = exp_a / sum_exp_a\n    return y\n", "meta": {"hexsha": "d5ba4b1e7e621b4ef98523278cbfbcdf0224ccbb", "size": 679, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapt3/3.5.1_softmaxFunc.py", "max_stars_repo_name": "KTD-prototype/DLfromZERO", "max_stars_repo_head_hexsha": "4d77224b381e449694860debe4a29c84fb175874", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapt3/3.5.1_softmaxFunc.py", "max_issues_repo_name": "KTD-prototype/DLfromZERO", "max_issues_repo_head_hexsha": "4d77224b381e449694860debe4a29c84fb175874", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapt3/3.5.1_softmaxFunc.py", "max_forks_repo_name": "KTD-prototype/DLfromZERO", "max_forks_repo_head_hexsha": "4d77224b381e449694860debe4a29c84fb175874", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.21875, "max_line_length": 89, "alphanum_fraction": 0.6450662739, "include": true, "reason": "import numpy", "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347838494567, "lm_q2_score": 0.9111797118207757, "lm_q1q2_score": 0.8878852055360879}}
{"text": "\"\"\"\nBasic mathematical functions operate element-wise on arrays. They are available both as operator overloads and as functions in the NumPy module.\n\nimport numpy\n\na = numpy.array([1,2,3,4], float)\nb = numpy.array([5,6,7,8], float)\n\nprint a + b                     #[  6.   8.  10.  12.]\nprint numpy.add(a, b)           #[  6.   8.  10.  12.]\n\nprint a - b                     #[-4. -4. -4. -4.]\nprint numpy.subtract(a, b)      #[-4. -4. -4. -4.]\n\nprint a * b                     #[  5.  12.  21.  32.]\nprint numpy.multiply(a, b)      #[  5.  12.  21.  32.]\n\nprint a / b                     #[ 0.2         0.33333333  0.42857143  0.5       ]\nprint numpy.divide(a, b)        #[ 0.2         0.33333333  0.42857143  0.5       ]\n\nprint a % b                     #[ 1.  2.  3.  4.]\nprint numpy.mod(a, b)           #[ 1.  2.  3.  4.]\n\nprint a**b                      #[  1.00000000e+00   6.40000000e+01   2.18700000e+03   6.55360000e+04]\nprint numpy.power(a, b)         #[  1.00000000e+00   6.40000000e+01   2.18700000e+03   6.55360000e+04]\n\nTask\n\nYou are given two integer arrays,\nand of dimensions X\n\n.\nYour task is to perform the following operations:\n\n    Add (\n\n+\n)\nSubtract (\n-\n)\nMultiply (\n*\n)\nInteger Division (\n/\n)\nMod (\n%\n)\nPower (\n**\n\n    )\n\nInput Format\n\nThe first line contains two space separated integers,\nand .\nThe next lines contains space separated integers of array .\nThe following lines contains space separated integers of array\n\n.\n\nOutput Format\n\nPrint the result of each operation in the given order under Task.\n\nSample Input\n\n1 4\n1 2 3 4\n5 6 7 8\n\nSample Output\n\n[[ 6  8 10 12]]\n[[-4 -4 -4 -4]]\n[[ 5 12 21 32]]\n[[0 0 0 0]]\n[[1 2 3 4]]\n[[    1    64  2187 65536]]\n\nUse // for division in Python 3.\n\n\n\"\"\"\n\nimport numpy as np\nn, m = map(int, input().split())\na, b = (np.array([input().split() for _ in range(n)], dtype=int) for _ in range(2))\nprint(a+b, a-b, a*b, a//b, a%b, a**b, sep='\\n')\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "fd6876fb6940a1c507d9f29170cdc16654f13d65", "size": 1912, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numpy/Array_Mathematics.py", "max_stars_repo_name": "NikolayVaklinov10/Python_Challenges", "max_stars_repo_head_hexsha": "a1052e1d527004bbb6072a3cbc802065469f66ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-01T23:57:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-01T23:58:16.000Z", "max_issues_repo_path": "Numpy/Array_Mathematics.py", "max_issues_repo_name": "NikolayVaklinov10/Python_Challenges", "max_issues_repo_head_hexsha": "a1052e1d527004bbb6072a3cbc802065469f66ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numpy/Array_Mathematics.py", "max_forks_repo_name": "NikolayVaklinov10/Python_Challenges", "max_forks_repo_head_hexsha": "a1052e1d527004bbb6072a3cbc802065469f66ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9306930693, "max_line_length": 144, "alphanum_fraction": 0.5523012552, "include": true, "reason": "import numpy", "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811581728098, "lm_q2_score": 0.9196425361331837, "lm_q1q2_score": 0.8878055766372329}}
{"text": "import numpy as np\n\n# Function\ndef f(x):\n    y = 1 / np.sqrt(2 * np.pi) * np.exp(-x ** 2 / 2)\n    return y\n\n# General Simpson Method\ndef Simpson(a, b, tol):\n    # Integral Cimputations With Simpson Method\n    def S(n):\n        h = (b-a)/(2*n)\n        I = h/3*(f(a) + f(b))\n\n        for i in range(1, 2*n):\n            x_i = a + h*i\n            if i % 2 == 0:\n                I += 2*h/3 * f(x_i)\n            else:\n                I += 4*h/3 * f(x_i)\n\n        return I\n\n    # Integral Error\n    def dS(n):\n\n        dI = (np.abs(S(2*n) - S(n))) / 15\n\n        return dI\n\n    # min{n} = 3 in General Simpson Method\n    n = 3 \n    d = dS(n)/S(n)\n\n    while d > tol:\n        n += 1\n        d = dS(n)/S(n)\n\n    return S(n), dS(n), d\n\nif __name__ == \"__main__\":\n    print('\\nComputated with General Simpson Method:')\n    print(f\"\\tI ± δI = {Simpson(-5, 5, 0.001)[0]:.8f} ± {Simpson(-5, 5, 0.001)[1]:.8f}\")\n    print(f'\\tThe Relative error is η = {Simpson(-5, 5, 0.001)[2]:.4f} < 0.1 %')", "meta": {"hexsha": "af8633bf7948943e5a3d133174a49bfd7d03b8f7", "size": 977, "ext": "py", "lang": "Python", "max_stars_repo_path": "Integration/General-Simpson-Method.py", "max_stars_repo_name": "AlexTsagas/Computational-Physics", "max_stars_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Integration/General-Simpson-Method.py", "max_issues_repo_name": "AlexTsagas/Computational-Physics", "max_issues_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Integration/General-Simpson-Method.py", "max_forks_repo_name": "AlexTsagas/Computational-Physics", "max_forks_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2045454545, "max_line_length": 88, "alphanum_fraction": 0.4564994882, "include": true, "reason": "import numpy", "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.975576914916509, "lm_q2_score": 0.9099070072595894, "lm_q1q2_score": 0.8876842710032238}}
{"text": "# Import important libraries\nimport numpy as np\nimport pylab as plt\nimport pandas as pd\nfrom sklearn import datasets\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\n\nload_iris = datasets.load_iris()\niris_df = pd.DataFrame(load_iris.data, columns=[load_iris.feature_names])\n\nprint(iris_df.head())\n\nprint(load_iris.data.shape)\n\nstandardized_x = StandardScaler().fit_transform(load_iris.data)\nprint(standardized_x[:2])\n\nprint(standardized_x.T)\n\ncovariance_matrix_x = np.cov(standardized_x.T)\nprint(covariance_matrix_x)\n\neigenvalues, eigenvectors = np.linalg.eig(covariance_matrix_x)\n\nprint(eigenvalues)\n\nprint(eigenvectors)\n\ntotal_of_eigenvalues = sum(eigenvalues)\nvarariance = [(i / total_of_eigenvalues)*100 for i in sorted(eigenvalues, reverse=True)]\n\nprint(varariance)\n\neigenpairs = [(np.abs(eigenvalues[i]), eigenvectors[:,i]) for i in range(len(eigenvalues))]\n\n# Sorting from Higher values to lower value\neigenpairs.sort(key=lambda x: x[0], reverse=True)\nprint(eigenpairs)\n\nmatrix_weighing = np.hstack((eigenpairs[0][1].reshape(4,1),\n                      eigenpairs[1][1].reshape(4,1)))\nprint(matrix_weighing)\n\nY = standardized_x.dot(matrix_weighing)\nprint(Y)\n\nplt.figure()\ntarget_names = load_iris.target_names\ny = load_iris.target\nfor c, i, target_name in zip(\"rgb\", [0, 1, 2], target_names):\n    plt.scatter(Y[y==i,0], Y[y==i,1], c=c, label=target_name)\n\nplt.xlabel('PCA 1')\nplt.ylabel('PCA 2')\nplt.legend()\nplt.title('PCA')\nplt.show()\n\n", "meta": {"hexsha": "28fe1a3b87b4d9de98c4667ab99a252a8ba0007b", "size": 1477, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear-algebra-for-ml-and-deep-learning/pca_with_python.py", "max_stars_repo_name": "fimoziq/tutorials", "max_stars_repo_head_hexsha": "f47f1b59bf3c9e9f79d530c6fc8ca36c0d9ea93b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 670, "max_stars_repo_stars_event_min_datetime": "2020-07-23T11:33:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:38:11.000Z", "max_issues_repo_path": "linear-algebra-for-ml-and-deep-learning/pca_with_python.py", "max_issues_repo_name": "terragord7/tutorials", "max_issues_repo_head_hexsha": "a5c3f1fed6c5c4d23f59a41c024f7499055c8d81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-01-03T16:36:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T06:05:43.000Z", "max_forks_repo_path": "linear-algebra-for-ml-and-deep-learning/pca_with_python.py", "max_forks_repo_name": "terragord7/tutorials", "max_forks_repo_head_hexsha": "a5c3f1fed6c5c4d23f59a41c024f7499055c8d81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 281, "max_forks_repo_forks_event_min_datetime": "2020-07-23T06:37:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:33:48.000Z", "avg_line_length": 24.6166666667, "max_line_length": 91, "alphanum_fraction": 0.7542315504, "include": true, "reason": "import numpy", "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769092358048, "lm_q2_score": 0.9099070090919014, "lm_q1q2_score": 0.8876842676218725}}
{"text": "import pandas as _pd\nimport numpy as _np\nimport math as _math\n\ndef nth_prime_number(n):\n    if n==1:\n        return 2\n    count = 1\n    num = 1\n    while(count < n):\n        num +=2 #optimization\n        if is_prime(num):\n            count +=1\n    return num\n\ndef is_prime(num):\n    # TODO: might be faster to use _math.gcd?\n    factor = 2\n    while (factor * factor <= num):\n        if num % factor == 0:\n             return False\n        factor +=1\n    return True\n\ndef chebyshev_theta_upto(n):\n    '''\n    Returns a pandas series with all the values of chebyshev's theta function\n    up to n.\n\n    TODO: change range steps to vary with size of n to stop it from loading \n    forever for big n.\n    '''\n    df=_pd.DataFrame(index=range(0, n, 1))\n    df['is_prime']=df.index.map(lambda n: n if is_prime(n) else 0)\n    df['log']=df.is_prime.map(lambda n: _np.log(n) if n!=0 else 0)\n    df['chebyshev_theta']=df.log.cumsum()\n    return df['chebyshev_theta']\n\ndef modulo_mult_table(n, returns_neg=False):\n    df=_pd.DataFrame(index=range(0, n, 1))\n    if returns_neg:\n        R=range(0,-n, -1)\n    else:\n        R=range(0, n, 1)\n    for i in R:\n        df[str(i)]=df.index.map(lambda x: (x*i)%n)\n    return df\n\ndef modulo_sum_table(n, returns_neg=False):\n    df=_pd.DataFrame(index=range(0, n, 1))\n    if returns_neg:\n        R=range(0,-n, -1)\n    else:\n        R=range(0, n, 1)\n    for i in R:\n        df[str(i)]=df.index.map(lambda x: (x+i)%n)\n    return df\n\ndef primes_less_than(n):\n    # TODO: there's probably a better way to do this lol\n    primes=[]\n    for i in range(1, n):\n        if is_prime(i):\n            primes.append(i)\n    return primes\n\ndef coprimes_less_than(n):\n    coprimes=[]\n    for i in range(1, n):\n        if _math.gcd(i, n)==1:\n            coprimes.append(i)\n    return coprimes", "meta": {"hexsha": "04de07ec3009cebc3a32a33b822b6755a8d460ef", "size": 1803, "ext": "py", "lang": "Python", "max_stars_repo_path": "ant/main.py", "max_stars_repo_name": "vvveracruz/ant", "max_stars_repo_head_hexsha": "615fabb16ff56cb832595224d5e19a6123d5521b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ant/main.py", "max_issues_repo_name": "vvveracruz/ant", "max_issues_repo_head_hexsha": "615fabb16ff56cb832595224d5e19a6123d5521b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ant/main.py", "max_forks_repo_name": "vvveracruz/ant", "max_forks_repo_head_hexsha": "615fabb16ff56cb832595224d5e19a6123d5521b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0416666667, "max_line_length": 77, "alphanum_fraction": 0.5867997781, "include": true, "reason": "import numpy", "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970239907775086, "lm_q2_score": 0.9149009567332237, "lm_q1q2_score": 0.8876734198841808}}
{"text": "\"\"\"\nCreated on May 12 22:47:36 2022\n\"\"\"\n\nimport numpy as np\n\n\ndef spherical2cartesian(spherical_coordinates, deg_rad: str = 'rad'):\n    \"\"\"\n    Converts spherical coordinates to Cartesian/rectangular coordinates.\n\n    Parameters\n    ----------\n    spherical_coordinates:\n        A tuple containing spherical coordinates.\n    deg_rad: str, optional\n        Indication whether the input coordinates are in degrees or radians. The default\n        is 'rad'.\n\n    Returns\n    -------\n    list:\n        Cartesian coordinates of the input spherical coordinates.\n\n    \"\"\"\n\n    # convert from degrees to radians (only theta and phi parameters)\n\n    if deg_rad == 'deg':\n        cs__ = np.deg2rad(spherical_coordinates[1:])\n        cs_ = np.append(spherical_coordinates[0], cs__)\n    else:\n        cs_ = np.array(spherical_coordinates)\n\n    # reinitialize the coordinates\n    rho, theta, phi = cs_.flatten()\n\n    # calculate the Cartesian coordinates\n    x = rho * np.sin(phi) * np.cos(theta)\n    y = rho * np.sin(phi) * np.sin(theta)\n    z = rho * np.cos(phi)\n\n    return x, y, z\n", "meta": {"hexsha": "64ff2d2766ace662ed1bcd3bf8437face4e29239", "size": 1071, "ext": "py", "lang": "Python", "max_stars_repo_path": "004__cartesian_coordinate_system/spherical2cartesian.py", "max_stars_repo_name": "AstrophysicsAndPython/astrophysicsandpython__main", "max_stars_repo_head_hexsha": "b8f8d38ee38865eea8c742c1964aeabec1c510bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "004__cartesian_coordinate_system/spherical2cartesian.py", "max_issues_repo_name": "AstrophysicsAndPython/astrophysicsandpython__main", "max_issues_repo_head_hexsha": "b8f8d38ee38865eea8c742c1964aeabec1c510bb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-02-10T08:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T19:43:04.000Z", "max_forks_repo_path": "004__cartesian_coordinate_system/spherical2cartesian.py", "max_forks_repo_name": "AstrophysicsAndPython/astrophysicsandpython__main", "max_forks_repo_head_hexsha": "b8f8d38ee38865eea8c742c1964aeabec1c510bb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3409090909, "max_line_length": 87, "alphanum_fraction": 0.6433239963, "include": true, "reason": "import numpy", "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399060540357, "lm_q2_score": 0.9149009555730612, "lm_q1q2_score": 0.8876734171839543}}
{"text": "'''\nWas 2015 anomalous?\n100xp\n\n1990 and 2015 featured the most no-hitters of any season of baseball (there were seven).\nGiven that there are on average 251/115 no-hitters per season, what is the probability of\nhaving seven or more in a season?\n\nInstructions\n-Draw 10000 samples from a Poisson distribution with a mean of 251/115 and assign to n_nohitters.\n-Determine how many of your samples had a result greater than or equal to 7 and assign to n_large.\n-Compute the probability, p_large, of having 7 or more no-hitters by dividing n_large by the total\nnumber of samples (10000).\n-Hit 'Submit Answer' to print the probability that you calculated.\n'''\nimport numpy as np\n\n# Seed random number generator\nnp.random.seed(42)\n\n# Draw 10,000 samples out of Poisson distribution: n_nohitters\nn_nohitters = np.random.poisson((251 / 115), size=10000)\n\n# Compute number of samples that are seven or greater: n_large\nn_large = np.sum(n_nohitters >= 7)\n\n# Compute probability of getting seven or more: p_large\np_large = n_large / 10000\n\n# Print the result\nprint('Probability of seven or more no-hitters:', p_large)\n", "meta": {"hexsha": "930f074b9cef4b3c57ce0db2321e2995354b592c", "size": 1104, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/3-thinking-probabilistically--discrete-variables/was-2015-anomalous_.py", "max_stars_repo_name": "aimanahmedmoin1997/DataCamp", "max_stars_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-12T04:49:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T00:40:28.000Z", "max_issues_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/3-thinking-probabilistically--discrete-variables/was-2015-anomalous_.py", "max_issues_repo_name": "aimanahmedmoin1997/DataCamp", "max_issues_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/3-thinking-probabilistically--discrete-variables/was-2015-anomalous_.py", "max_forks_repo_name": "aimanahmedmoin1997/DataCamp", "max_forks_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-11-06T17:43:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T21:08:16.000Z", "avg_line_length": 34.5, "max_line_length": 98, "alphanum_fraction": 0.7726449275, "include": true, "reason": "import numpy", "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668673560624, "lm_q2_score": 0.9046505267461572, "lm_q1q2_score": 0.8876131233795388}}
{"text": "\n# coding: utf-8\n\n# In[ ]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# In[ ]:\n\n\n# Logistic function implementation\ndef logistic_eq(r,x):\n    return r*x*(1-x)\n\n\n# In[ ]:\n\n\n# Show the logistic function\nx = np.linspace(0, 1)\nplt.plot(x, logistic_eq(2, x), 'k')\nplt.show()\n\n# logistic_eq(4.0009, 0.75)\n\n\n# In[ ]:\n\n\n# Iterate the function for a given r\ndef logistic_equation_orbit(seed, r, n_iter, n_skip=0):\n    print('Orbit for seed {0}, growth rate of {1}, plotting {2} iterations after skipping {3}'.format(seed, r, n_iter, n_skip))\n    X_t=[]\n    T=[]\n    t=0\n    x = seed;\n    # Iterate the logistic equation, printing only if n_skip steps have been skipped\n    for i in range(n_iter + n_skip):\n        if i >= n_skip:\n            X_t.append(x)\n            T.append(t)\n            t+=1\n        x = logistic_eq(r,x);\n    # Configure and decorate the plot\n    plt.plot(T, X_t)\n    plt.ylim(0, 1)\n    plt.xlim(0, T[-1])\n    plt.xlabel('Time t')\n    plt.ylabel('X_t')\n    plt.show()\n\n\n# In[ ]:\n\n\nlogistic_equation_orbit(0.1, 3.05, 100)\nlogistic_equation_orbit(0.1, 3.9, 100)\nlogistic_equation_orbit(0.1, 3.9, 100, 1000)\n\n\n# In[ ]:\n\n\n# Create the bifurcation diagram\ndef bifurcation_diagram(seed, n_skip, n_iter, step=0.0001, r_min=0):\n    print(\"Starting with x0 seed {0}, skip plotting first {1} iterations, then plot next {2} iterations.\".format(seed, n_skip, n_iter));\n    # Array of r values, the x axis of the bifurcation plot\n    R = []\n    # Array of x_t values, the y axis of the bifurcation plot\n    X = []\n    \n    # Create the r values to loop. For each r value we will plot n_iter points\n    r_range = np.linspace(r_min, 4, int(1/step))\n\n    for r in r_range:\n        x = seed;\n        # For each r, iterate the logistic function and collect datapoint if n_skip iterations have occurred\n        for i in range(n_iter+n_skip+1):\n            if i >= n_skip:\n                R.append(r)\n                X.append(x)\n                \n            x = logistic_eq(r,x);\n    # Plot the data    \n    plt.plot(R, X, ls='', marker=',')\n    plt.ylim(0, 1)\n    plt.xlim(r_min, 4)\n    plt.xlabel('r')\n    plt.ylabel('X')\n    plt.show()\n\n\n# In[ ]:\n\n\nbifurcation_diagram(0.2, 100, 5)\nbifurcation_diagram(0.2, 100, 10)\nbifurcation_diagram(0.2, 100, 10, r_min=2.8)\n\n", "meta": {"hexsha": "bc300cfcacb061e188a13195fcc79b0ab928d1f2", "size": 2270, "ext": "py", "lang": "Python", "max_stars_repo_path": "Bifurcation diagram.py", "max_stars_repo_name": "JOSEPH-PIOUS-K/fictional-octo-disco", "max_stars_repo_head_hexsha": "89617287fbbea27baafb803207bd6e2d42f42dae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-11-26T10:45:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T04:29:37.000Z", "max_issues_repo_path": "Bifurcation diagram.py", "max_issues_repo_name": "JOSEPH-PIOUS-K/fictional-octo-disco", "max_issues_repo_head_hexsha": "89617287fbbea27baafb803207bd6e2d42f42dae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bifurcation diagram.py", "max_forks_repo_name": "JOSEPH-PIOUS-K/fictional-octo-disco", "max_forks_repo_head_hexsha": "89617287fbbea27baafb803207bd6e2d42f42dae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-07-23T23:07:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T13:37:46.000Z", "avg_line_length": 22.0388349515, "max_line_length": 136, "alphanum_fraction": 0.6039647577, "include": true, "reason": "import numpy", "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561703644736, "lm_q2_score": 0.9161096044278532, "lm_q1q2_score": 0.8875784429800826}}
{"text": "import numpy as np\n\n# ndarray with shape 3x4 with zeros\n\nx = np.zeros((3,4))\nprint(x)\n\nx = np.zeros((3,4), dtype = int)\nprint(x)\n\n# ndarray full of ones\n\nx = np.ones((3,4))\nprint(x)\n\nx = np.ones((3,4),dtype = int)\nprint(x)\n\n# ndarray full of any numbers\n\nx = np.full((3,4), 5)\nprint(x)\n\n# Identity matrix ,  An Identity matrix is a square matrix that has only 1s in its main diagonal and zeros everywhere else\n\nx = np.eye(5, dtype=int)\nprint(x)\n\n# Diagonal Matrix, square matrix that only has values in its main diagonal\n\nx = np.diag([10,20,30,50])\nprint(x)\n\n# ndarrays that have evenly spaced values within a given interval\n\nx = np.arange(10)\nprint(x)\n\nx = np.arange(1, 11, 3)\nprint(x)\n\n# arange when used for non integer result can be mallicious\n\n# In the cases where non-integer steps are required, it is usually better to use the function np.linspace()\n\nx = np.linspace(0,25, 10)\nprint(x)\n\nx = np.linspace(0,25, 10, endpoint = False)\nprint(x)\n\n# Using arange and linespace for > 1 rank array\n\n# Use reshape() to comine to create rank 2 ndarrays\n\nx = np.arange(20)\nprint(x)\n\nx = np.reshape(x, (4,5))\n\nprint(x)\n\n# Can call as a method\nx = np.arange(20).reshape((4,5))\n\nprint(x)\n\nx = np.linspace(0,50,10, endpoint=False).reshape(5,2)\nprint(x)\n\n# Random ndarray float type\n\nx = np.random.random((3,3))\nprint(x)\n\n# Random ndarray int type\nx = np.random.randint(4,15, size=(3,2))\nprint(x)\n\n# For example, you may want the random numbers in the ndarray to have an average of 0. \n# NumPy allows you create random ndarrays with numbers drawn from various probability \n# distributions. The function np.random.normal(mean, standard deviation, size=shape),\n# for example, creates an ndarray with the given shape that contains random numbers \n# picked from a normal (Gaussian) distribution with the given mean and standard deviation.\n\nx = np.random.normal(0, 0.1, size=(1000, 1000))\nprint(x)\n\nx = np.arange(2, 34, 2, dtype = int).reshape((4,4))\nprint(x)", "meta": {"hexsha": "3f6629de97bd228b547d9485597569172671f10f", "size": 1944, "ext": "py", "lang": "Python", "max_stars_repo_path": "python-programming/numPy/ndarray_create_using_built_in_function.py", "max_stars_repo_name": "geekmj/fml", "max_stars_repo_head_hexsha": "ead2c16be7865eda03183b5e11622f64bf81cab7", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python-programming/numPy/ndarray_create_using_built_in_function.py", "max_issues_repo_name": "geekmj/fml", "max_issues_repo_head_hexsha": "ead2c16be7865eda03183b5e11622f64bf81cab7", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python-programming/numPy/ndarray_create_using_built_in_function.py", "max_forks_repo_name": "geekmj/fml", "max_forks_repo_head_hexsha": "ead2c16be7865eda03183b5e11622f64bf81cab7", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6, "max_line_length": 122, "alphanum_fraction": 0.7031893004, "include": true, "reason": "import numpy", "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.9284087970889806, "lm_q1q2_score": 0.8875414953202416}}
{"text": "'''\r\nshape\r\n\r\nThe shape tool gives a tuple of array dimensions and can be used to change the dimensions of an array.\r\n\r\n(a). Using shape to get array dimensions\r\n\r\nimport numpy\r\n\r\nmy__1D_array = numpy.array([1, 2, 3, 4, 5])\r\nprint my_1D_array.shape     #(5,) -> 5 rows and 0 columns\r\n\r\nmy__2D_array = numpy.array([[1, 2],[3, 4],[6,5]])\r\nprint my_2D_array.shape     #(3, 2) -> 3 rows and 2 columns \r\n(b). Using shape to change array dimensions\r\n\r\nimport numpy\r\n\r\nchange_array = numpy.array([1,2,3,4,5,6])\r\nchange_array.shape = (3, 2)\r\nprint change_array      \r\n\r\n#Output\r\n[[1 2]\r\n[3 4]\r\n[5 6]]\r\nreshape\r\n\r\nThe reshape tool gives a new shape to an array without changing its data. It creates a new array and does not modify the original array itself.\r\n\r\nimport numpy\r\n\r\nmy_array = numpy.array([1,2,3,4,5,6])\r\nprint numpy.reshape(my_array,(3,2))\r\n\r\n#Output\r\n[[1 2]\r\n[3 4]\r\n[5 6]]\r\nTask\r\n\r\nYou are given a space separated list of nine integers. Your task is to convert this list into a X NumPy array.\r\n\r\nInput Format\r\n\r\nA single line of input containing  space separated integers.\r\n\r\nOutput Format\r\n\r\nPrint the X NumPy array.\r\n\r\nSample Input\r\n\r\n1 2 3 4 5 6 7 8 9\r\nSample Output\r\n\r\n[[1 2 3]\r\n [4 5 6]\r\n [7 8 9]]\r\n'''\r\n\r\nimport numpy as np\r\n\r\nip = input().strip().split(' ')\r\nx = np.array(ip)\r\nx = x.astype(np.int32)\r\nx = x.reshape(3,3)\r\nprint(x)\r\n\r\n#print(ip)\r\n\r\n\r\n", "meta": {"hexsha": "d343c4a70a61da926b8ea4ca167e2e39445da567", "size": 1360, "ext": "py", "lang": "Python", "max_stars_repo_path": "Hackerrank Practice/Shape and Reshape.py", "max_stars_repo_name": "falconcode16/pythonprogramming", "max_stars_repo_head_hexsha": "fc53a879be473ebceb1d7da061b0e8fc2a20706c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-11T14:15:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-12T09:57:29.000Z", "max_issues_repo_path": "Hackerrank Practice/Shape and Reshape.py", "max_issues_repo_name": "falconcode16/pythonprogramming", "max_issues_repo_head_hexsha": "fc53a879be473ebceb1d7da061b0e8fc2a20706c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hackerrank Practice/Shape and Reshape.py", "max_forks_repo_name": "falconcode16/pythonprogramming", "max_forks_repo_head_hexsha": "fc53a879be473ebceb1d7da061b0e8fc2a20706c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-10T02:13:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T02:13:42.000Z", "avg_line_length": 18.6301369863, "max_line_length": 144, "alphanum_fraction": 0.6492647059, "include": true, "reason": "import numpy", "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885303, "lm_q2_score": 0.9230391669503405, "lm_q1q2_score": 0.887533368166351}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as sp\nfrom scipy import stats\nimport pandas as pd\n\n###############################################################################################################    \n###############################################################################################################\ndef reg_corr_plot():    \n    class LinearRegression: \n        def __init__(self, beta1, beta2, error_scale, data_size):\n            self.beta1 = beta1\n            self.beta2 = beta2\n            self.error_scale = error_scale\n            self.x = np.random.randint(1, data_size, data_size)\n            self.y = self.beta1 + self.beta2*self.x + self.error_scale*np.random.randn(data_size)\n\n        def x_y_cor(self):\n            return np.corrcoef(self.x, self.y)[0, 1]\n\n    fig, ax = plt.subplots(nrows = 2, ncols = 4,figsize=(24, 12))\n\n    beta1, beta2, error_scale,data_size =  2, .05, 1, 100\n    lrg1 = LinearRegression(beta1, beta2, error_scale, data_size)\n    ax[0, 0].scatter(lrg1.x, lrg1.y)\n    ax[0, 0].plot(lrg1.x, beta1 + beta2*lrg1.x, color = '#FA954D', alpha = .7)\n    ax[0, 0].set_title(r'$Y={}+{}X+{}u$'.format(beta1, beta2, error_scale))\n    ax[0, 0].annotate(r'$\\rho={:.4}$'.format(lrg1.x_y_cor()), xy=(0.1, 0.9), xycoords='axes fraction')\n\n    beta1, beta2, error_scale,data_size =  2, -.6, 1, 100\n    lrg2 = LinearRegression(beta1, beta2, error_scale, data_size)\n    ax[0, 1].scatter(lrg2.x, lrg2.y)\n    ax[0, 1].plot(lrg2.x, 2 - .6*lrg2.x, color = '#FA954D', alpha = .7)\n    ax[0, 1].set_title(r'$Y={}+{}X+{}u$'.format(beta1, beta2, error_scale))\n    ax[0, 1].annotate(r'$\\rho={:.4}$'.format(lrg2.x_y_cor()), xy=(0.1, 0.9), xycoords='axes fraction')\n\n    beta1, beta2, error_scale,data_size =  2, 1, 1, 100\n    lrg3 = LinearRegression(beta1, beta2, error_scale, data_size)\n    ax[0, 2].scatter(lrg3.x, lrg3.y)\n    ax[0, 2].plot(lrg3.x, beta1 + beta2 * lrg3.x, color = '#FA954D', alpha = .7)\n    ax[0, 2].set_title(r'$Y={}+{}X+{}u$'.format(beta1, beta2, error_scale))\n    ax[0, 2].annotate(r'$\\rho={:.4}$'.format(lrg3.x_y_cor()), xy=(0.1, 0.9), xycoords='axes fraction')\n\n    beta1, beta2, error_scale,data_size =  2, 3, 1, 100\n    lrg4 = LinearRegression(beta1, beta2, error_scale, data_size)\n    ax[0, 3].scatter(lrg4.x, lrg4.y)\n    ax[0, 3].plot(lrg4.x, beta1 + beta2 * lrg4.x, color = '#FA954D', alpha = .7)\n    ax[0, 3].set_title(r'$Y={}+{}X+{}u$'.format(beta1, beta2, error_scale))\n    ax[0, 3].annotate(r'$\\rho={:.4}$'.format(lrg4.x_y_cor()), xy=(0.1, 0.9), xycoords='axes fraction')\n\n    beta1, beta2, error_scale,data_size =  2, 3, 3, 100\n    lrg5 = LinearRegression(beta1, beta2, error_scale, data_size)\n    ax[1, 0].scatter(lrg5.x, lrg5.y)\n    ax[1, 0].plot(lrg5.x, beta1 + beta2 * lrg5.x, color = '#FA954D', alpha = .7)\n    ax[1, 0].set_title(r'$Y={}+{}X+{}u$'.format(beta1, beta2, error_scale))\n    ax[1, 0].annotate(r'$\\rho={:.4}$'.format(lrg5.x_y_cor()), xy=(0.1, 0.9), xycoords='axes fraction')\n\n    beta1, beta2, error_scale,data_size =  2, 3, 10, 100\n    lrg6 = LinearRegression(beta1, beta2, error_scale, data_size)\n    ax[1, 1].scatter(lrg6.x, lrg6.y)\n    ax[1, 1].plot(lrg6.x, beta1 + beta2 * lrg6.x, color = '#FA954D', alpha = .7)\n    ax[1, 1].set_title(r'$Y={}+{}X+{}u$'.format(beta1, beta2, error_scale))\n    ax[1, 1].annotate(r'$\\rho={:.4}$'.format(lrg6.x_y_cor()), xy=(0.1, 0.9), xycoords='axes fraction')\n\n    beta1, beta2, error_scale,data_size =  2, 3, 20, 100\n    lrg7 = LinearRegression(beta1, beta2, error_scale, data_size)\n    ax[1, 2].scatter(lrg7.x, lrg7.y)\n    ax[1, 2].plot(lrg7.x, beta1 + beta2 * lrg7.x, color = '#FA954D', alpha = .7)\n    ax[1, 2].set_title(r'$Y={}+{}X+{}u$'.format(beta1, beta2, error_scale))\n    ax[1, 2].annotate(r'$\\rho={:.4}$'.format(lrg7.x_y_cor()), xy=(0.1, 0.9), xycoords='axes fraction')\n\n\n    beta1, beta2, error_scale,data_size =  2, 3, 50, 100\n    lrg8 = LinearRegression(beta1, beta2, error_scale, data_size)\n    ax[1, 3].scatter(lrg8.x, lrg8.y)\n    ax[1, 3].plot(lrg3.x, beta1 + beta2 * lrg3.x, color = '#FA954D', alpha = .7)\n    ax[1, 3].set_title(r'$Y={}+{}X+{}u$'.format(beta1, beta2, error_scale))\n    ax[1, 3].annotate(r'$\\rho={:.4}$'.format(lrg8.x_y_cor()), xy=(0.1, 0.9), xycoords='axes fraction')\n    \n###############################################################################################################    \n###############################################################################################################\n\ndef central_limit_theorem_plot():    \n    fig, ax = plt.subplots(4, 3, figsize = (20, 20))\n\n    ########################################################################################\n    x = np.linspace(2, 8, 100)\n    a = 2 # range of uniform distribution\n    b = 8\n    unif_pdf = np.ones(len(x)) * 1/(b-a)\n\n    ax[0, 0].plot(x, unif_pdf, lw = 3, color = 'r')\n    ax[0, 0].plot([x[0],x[0]],[0, 1/(b-a)], lw = 3, color = 'r', alpha = .9) # vertical line\n    ax[0, 0].plot([x[-1],x[-1]],[0, 1/(b-a)], lw = 3, color = 'r', alpha = .9)\n    ax[0, 0].fill_between(x, 1/(b-a), 0, alpha = .5, color = 'r')\n\n    ax[0, 0].set_xlim([1, 9])\n    ax[0, 0].set_ylim([0, .4])\n    ax[0, 0].set_title('Uniform Distribution', size = 18)\n    ax[0, 0].set_ylabel('Population Distribution', size = 12)\n\n    ########################################################################################\n    ss = 2 #sample size\n    unif_sample_mean = np.zeros(1000)\n    for i in range(1000):\n        unif_sample = np.random.rand(ss)\n        unif_sample_mean[i] = np.mean(unif_sample)\n    ax[1, 0].hist(unif_sample_mean, bins = 20, color = 'r', alpha = .5)\n    ax[1, 0].set_ylabel('Sample Distribution， $n = 2$', size = 12)\n    ########################################################################################\n    ss = 10 #sample size\n    unif_sample_mean = np.zeros(1000)\n    for i in range(1000):\n        unif_sample = np.random.rand(ss)\n        unif_sample_mean[i] = np.mean(unif_sample)\n    ax[2, 0].hist(unif_sample_mean, bins = 30, color = 'r', alpha = .5)\n    ax[2, 0].set_ylabel('Sample Distribution, $n = 10$', size = 12)\n\n    ########################################################################################\n    ss = 1000 #sample size\n    unif_sample_mean = np.zeros(1000)\n    for i in range(1000):\n        unif_sample = np.random.rand(ss)\n        unif_sample_mean[i] = np.mean(unif_sample)\n    ax[3, 0].hist(unif_sample_mean, bins = 40, color = 'r', alpha = .5)\n    ax[3, 0].set_ylabel('Sample Distribution, $n = 1000$', size = 12)\n\n    ########################################################################################\n    a = 6\n    b = 2\n    x = np.linspace(0, 1, 100)\n    beta_pdf = sp.stats.beta.pdf(x, a, b)\n    ax[0, 1].plot(x, beta_pdf, lw = 3, color = 'g')\n    ax[0, 1].set_ylim([0, 6])\n    ax[0, 1].fill_between(x, beta_pdf, 0, alpha = .5, color = 'g')\n    ax[0, 1].set_title('Beta Distribution', size = 18)\n    ########################################################################################\n\n    ss = 2 #sample size\n    beta_sample_mean = np.zeros(1000)\n    for i in range(1000):\n        beta_sample = sp.stats.beta.rvs(a, b, size = ss)\n        beta_sample_mean[i] = np.mean(beta_sample)\n    ax[1, 1].hist(beta_sample_mean, color = 'g', alpha = .5)\n\n    ########################################################################################\n\n    ss = 10 #sample size\n    beta_sample_mean = np.zeros(1000)\n    for i in range(1000):\n        beta_sample = sp.stats.beta.rvs(a, b, size = ss)\n        beta_sample_mean[i] = np.mean(beta_sample)\n    ax[2, 1].hist(beta_sample_mean, color = 'g', bins = 20, alpha = .5)\n\n\n    ########################################################################################\n\n    ss = 100000 #sample size\n    beta_sample_mean = np.zeros(1000)\n    for i in range(1000):\n        beta_sample = sp.stats.beta.rvs(a, b, size = ss)\n        beta_sample_mean[i] = np.mean(beta_sample)\n    ax[3, 1].hist(beta_sample_mean, color = 'g', bins = 30, alpha = .5)\n\n    ########################################################################################\n    a = 6\n    x = np.linspace(0, 25, 100)\n\n    gamma_pdf = sp.stats.gamma.pdf(x, a)\n    ax[0, 2].plot(x, gamma_pdf, lw = 3, color = 'b')\n    ax[0, 2].set_ylim([0, 0.34])\n    ax[0, 2].fill_between(x, gamma_pdf, 0, alpha = .5, color = 'b')\n    ax[0, 2].set_title('Gamma Distribution', size = 18)\n\n    ########################################################################################\n    ss = 2 #sample size\n    gamma_sample_mean = np.zeros(1000)\n    for i in range(1000):\n        gamma_sample = sp.stats.gamma.rvs(a, size = ss)\n        gamma_sample_mean[i] = np.mean(gamma_sample)\n    ax[1, 2].hist(gamma_sample_mean, color = 'b', alpha = .5)\n\n    ########################################################################################\n    ss = 10 #sample size\n    gamma_sample_mean = np.zeros(1000)\n    for i in range(1000):\n        gamma_sample = sp.stats.gamma.rvs(a, size = ss)\n        gamma_sample_mean[i] = np.mean(gamma_sample)\n    ax[2, 2].hist(gamma_sample_mean, bins = 20, color = 'b', alpha = .5)\n    ########################################################################################\n    ss = 1000 #sample size\n    gamma_sample_mean = np.zeros(1000)\n    for i in range(1000):\n        gamma_sample = sp.stats.gamma.rvs(a, size = ss)\n        gamma_sample_mean[i] = np.mean(gamma_sample)\n    ax[3, 2].hist(gamma_sample_mean, bins = 30, color = 'b', alpha = .5)\n    ########################################################################################\n    plt.show()\n    \n##########################################################################################################\n##########################################################################################################\ndef type12_error():\n    x = np.linspace(-6, 9, 200)\n    null_loc, alter_loc = 0, 3\n    y_null = sp.stats.norm.pdf(x, loc = null_loc)\n    y_alter =  sp.stats.norm.pdf(x, loc = alter_loc)\n    fig, ax = plt.subplots(figsize = (18, 6))\n    ax.plot(x, y_null, x, y_alter)\n    ax.annotate('Null', (null_loc-.2, max(y_null)/2), size = 15)\n    ax.annotate('Alternative', (alter_loc-.6, max(y_alter)/2), size = 15)\n    ax.annotate('Type I Error', (2, max(y_alter)/30), size = 15)\n    ax.annotate('Type II Error', (0, max(y_alter)/30), size = 15)\n    ax.fill_between(x[-98:], y_null[-98:])\n    ax.fill_between(x[:103], y_alter[:103])\n    ax.set_ylim([0, .5])\n    plt.show()\n    \n##########################################################################################################\n##########################################################################################################   \n# def reject_region(): \n#     data = pd.read_csv('500_Person_Gender_Height_Weight_Index.csv')\n    \n#     male_mean = data[data['Gender']=='Male']['Height'].mean()\n#     male_std = data[data['Gender']=='Male']['Height'].std(ddof=1)\n#     male_std_error = male_std/np.sqrt(len(data[data['Gender']=='Male']))\n#     male_null = 172\n    \n#     df = len(data[data['Gender']=='Male'])-1\n#     t_975 = sp.stats.t.ppf(.975, df=df)\n#     t_025 = sp.stats.t.ppf(.025, df=df)\n\n#     x = np.linspace(male_null-5, male_null+5, 200)\n#     df = len(data[data['Gender']=='Male'])-1\n#     y_t = sp.stats.t.pdf(x, df = df, loc = male_null)\n\n#     fig, ax = plt.subplots(2, 1, figsize = (18,8))\n\n#     ax[0].plot(x, y_t, color = 'tomato', lw = 3)\n\n#     rejection_lower = male_null - t_975*male_std_error\n#     x_rej_lower = np.linspace(rejection_lower-3, rejection_lower, 30)\n#     y_rej_lower = sp.stats.t.pdf(x_rej_lower, df = df, loc = male_null)\n#     ax[0].fill_between(x_rej_lower, y_rej_lower, color = 'tomato', alpha = .7)\n\n#     rejection_upper = male_null + t_975*male_std_error\n#     x_rej_upper = np.linspace(rejection_upper, rejection_upper+3, 30)\n#     y_rej_upper = sp.stats.t.pdf(x_rej_upper, df = df, loc = male_null)\n#     ax[0].fill_between(x_rej_upper, y_rej_upper, color = 'tomato', alpha = .7)\n\n#     ax[0].set_ylim([0, .45])\n\n#     x = np.linspace(-5, 5, 200)\n#     y_t = sp.stats.t.pdf(x, df = df, loc = 0)\n\n#     ax[1].plot(x, y_t, color = 'tomato', lw = 3)\n\n#     x_rej_lower = np.linspace(t_025-3, t_025, 30)\n#     y_rej_lower = sp.stats.t.pdf(x_rej_lower, df = df)\n#     ax[1].fill_between(x_rej_lower, y_rej_lower, color = 'tomato', alpha = .7)\n\n#     x_rej_lower = np.linspace(t_975+3, t_975, 30)\n#     y_rej_lower = sp.stats.t.pdf(x_rej_lower, df = df)\n#     ax[1].fill_between(x_rej_lower, y_rej_lower, color = 'tomato', alpha = .7)\n\n#     ax[1].set_ylim([0, .45])\n\n#     plt.show()\n    \n##########################################################################################################\n# ##########################################################################################################\n# def draw_something():\n#     x = np.linspace(0, 10, 100)\n#     y = np.sin(x)\n#     plt.plot(x, y)\n\n##########################################################################################################\n##########################################################################################################\ndef anova_plot():\n    def gen_3samples(loc1, loc2, loc3, scale1, scale2, scale3, size1, size2, size3):\n        F_statistic, p_value = [], []\n        for i in range(1000):\n            a = sp.stats.norm.rvs(loc1, scale1, size1)\n            b = sp.stats.norm.rvs(loc2, scale2, size3)\n            c = sp.stats.norm.rvs(loc3, scale3, size3)\n            F, p = sp.stats.f_oneway(a,b,c)\n            F_statistic.append(F)\n            p_value.append(p)\n        return F_statistic, p_value\n\n    fig, ax = plt.subplots(nrows = 6, ncols = 3, figsize = (17, 34))\n\n    mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3 = [3, 6, 9, 6, 6, 6, 10, 20, 30]\n    params = [mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3]\n    F_statistic, p_value = gen_3samples(*params)\n    n, bins, patches = ax[0,0].hist(F_statistic, bins = 50)\n    F_critical = sp.stats.f.ppf(.95, 2, size1+size2+size3-3)\n    textstr = '\\n'.join((\n        '$\\mu_1, \\mu_2, \\mu_3 = {}, {}, {}$'.format(mu1, mu2, mu3),\n        '$\\sigma_1, \\sigma_2, \\sigma_3 = {}, {}, {}$'.format(sig1, sig2, sig3),\n        '$n_1, n_2, n_3 = {}, {}, {}$'.format(size1, size2, size3),\n        r'$F_c = {:.4f}$'.format(F_critical)))\n    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n    ax[0,0].text(max(bins)/2, max(n)/2, textstr, fontsize=10,\n            verticalalignment='top', bbox=props)\n    ax[0,0].set_title('Simulation 1')\n    ax[0,0].vlines(F_critical, 0, max(n)*1.1, color = 'r')\n    ax[1,0].hist(p_value,bins = 50)\n\n    mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3 = [3, 3.1, 2.9, 6, 6, 6, 10, 20, 30]\n    params = [mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3]\n    F_statistic, p_value = gen_3samples(*params)\n    n, bins, patches = ax[0,1].hist(F_statistic, bins = 50)\n    F_critical = sp.stats.f.ppf(.95, 2, size1+size2+size3-3)\n    textstr = '\\n'.join((\n        '$\\mu_1, \\mu_2, \\mu_3 = {}, {}, {}$'.format(mu1, mu2, mu3),\n        '$\\sigma_1, \\sigma_2, \\sigma_3 = {}, {}, {}$'.format(sig1, sig2, sig3),\n        '$n_1, n_2, n_3 = {}, {}, {}$'.format(size1, size2, size3),\n        r'$F_c = {:.4f}$'.format(F_critical)))\n    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n    ax[0,1].text(max(bins)/2, max(n)/2, textstr, fontsize=10,\n            verticalalignment='top', bbox=props)\n    ax[0,1].vlines(F_critical, 0, max(n)*1.1, color = 'r')\n    ax[1,1].hist(p_value,bins = 50)\n    ax[0,1].set_title('Simulation 2')\n\n\n    mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3 = [3, 3.1, 2.9, 6, 12, 18, 10, 20, 30]\n    params = [mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3]\n    F_statistic, p_value = gen_3samples(*params)\n    n, bins, patches = ax[0,2].hist(F_statistic, bins = 50)\n    F_critical = sp.stats.f.ppf(.95, 2, size1+size2+size3-3)\n    textstr = '\\n'.join((\n        '$\\mu_1, \\mu_2, \\mu_3 = {}, {}, {}$'.format(mu1, mu2, mu3),\n        '$\\sigma_1, \\sigma_2, \\sigma_3 = {}, {}, {}$'.format(sig1, sig2, sig3),\n        '$n_1, n_2, n_3 = {}, {}, {}$'.format(size1, size2, size3),\n        r'$F_c = {:.4f}$'.format(F_critical)))\n    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n    ax[0,2].text(max(bins)/2, max(n)/2, textstr, fontsize=10,\n            verticalalignment='top', bbox=props)\n    ax[0,2].vlines(F_critical, 0, max(n)*1.1, color = 'r')\n    ax[1,2].hist(p_value,bins = 50)\n    ax[0,2].set_title('Simulation 3')\n\n\n    mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3 =  [3, 6, 9, 10, 10, 10, 10, 20, 30]\n    params = [mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3]\n    F_statistic, p_value = gen_3samples(*params)\n    n, bins, patches = ax[2,0].hist(F_statistic, bins = 50)\n    F_critical = sp.stats.f.ppf(.95, 2, size1+size2+size3-3)\n    textstr = '\\n'.join((\n        '$\\mu_1, \\mu_2, \\mu_3 = {}, {}, {}$'.format(mu1, mu2, mu3),\n        '$\\sigma_1, \\sigma_2, \\sigma_3 = {}, {}, {}$'.format(sig1, sig2, sig3),\n        '$n_1, n_2, n_3 = {}, {}, {}$'.format(size1, size2, size3),\n        r'$F_c = {:.4f}$'.format(F_critical)))\n    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n    ax[2,0].text(max(bins)/2, max(n)/2, textstr, fontsize=10,\n            verticalalignment='top', bbox=props)\n    ax[2,0].vlines(F_critical, 0, max(n)*1.1, color = 'r')\n    ax[3,0].hist(p_value,bins = 50)\n    ax[2,0].set_title('Simulation 4')\n\n\n    mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3 =  [3, 5, 6, 10, 10, 10, 10, 10, 10]\n    params = [mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3]\n    F_statistic, p_value = gen_3samples(*params)\n    n, bins, patches = ax[2,1].hist(F_statistic, bins = 50)\n    F_critical = sp.stats.f.ppf(.95, 2, size1+size2+size3-3)\n    textstr = '\\n'.join((\n        '$\\mu_1, \\mu_2, \\mu_3 = {}, {}, {}$'.format(mu1, mu2, mu3),\n        '$\\sigma_1, \\sigma_2, \\sigma_3 = {}, {}, {}$'.format(sig1, sig2, sig3),\n        '$n_1, n_2, n_3 = {}, {}, {}$'.format(size1, size2, size3),\n        r'$F_c = {:.4f}$'.format(F_critical)))\n    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n    ax[2,1].text(max(bins)/2, max(n)/2, textstr, fontsize=10,\n            verticalalignment='top', bbox=props)\n    ax[2,1].vlines(F_critical, 0, max(n)*1.1, color = 'r')\n    ax[3,1].hist(p_value,bins = 50)\n    ax[2,1].set_title('Simulation 5')\n\n\n    mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3 = [3, 5, 6, 10, 10, 10, 5000, 5000, 5000]\n    params = [mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3]\n    F_statistic, p_value = gen_3samples(*params)\n    n, bins, patches = ax[2,2].hist(F_statistic, bins = 50)\n    F_critical = sp.stats.f.ppf(.95, 2, size1+size2+size3-3)\n    textstr = '\\n'.join((\n        '$\\mu_1, \\mu_2, \\mu_3 = {}, {}, {}$'.format(mu1, mu2, mu3),\n        '$\\sigma_1, \\sigma_2, \\sigma_3 = {}, {}, {}$'.format(sig1, sig2, sig3),\n        '$n_1, n_2, n_3 = {}, {}, {}$'.format(size1, size2, size3),\n        r'$F_c = {:.4f}$'.format(F_critical)))\n    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n    ax[2,2].text(max(bins)/2, max(n)/2, textstr, fontsize=10,\n            verticalalignment='top', bbox=props)\n    ax[2,2].vlines(F_critical, 0, max(n)*1.1, color = 'r')\n    ax[3,2].hist(p_value,bins = 50)\n    ax[2,2].set_title('Simulation 6')\n\n\n    mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3 = [3, 3, 3, 100, 100, 100, 10, 10, 10]\n    params = [mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3]\n    F_statistic, p_value = gen_3samples(*params)\n    n, bins, patches = ax[4,0].hist(F_statistic, bins = 50)\n    F_critical = sp.stats.f.ppf(.95, 2, size1+size2+size3-3)\n    textstr = '\\n'.join((\n        '$\\mu_1, \\mu_2, \\mu_3 = {}, {}, {}$'.format(mu1, mu2, mu3),\n        '$\\sigma_1, \\sigma_2, \\sigma_3 = {}, {}, {}$'.format(sig1, sig2, sig3),\n        '$n_1, n_2, n_3 = {}, {}, {}$'.format(size1, size2, size3),\n        r'$F_c = {:.4f}$'.format(F_critical)))\n    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n    ax[4,0].text(max(bins)/2, max(n)/2, textstr, fontsize=10,\n            verticalalignment='top', bbox=props)\n    ax[4,0].vlines(F_critical, 0, max(n)*1.1, color = 'r')\n    ax[5,0].hist(p_value,bins = 50)\n    ax[4,0].set_title('Simulation 7')\n\n\n    mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3 = [3, 3, 3, 1, 1, 2, 10, 20, 30]\n    params = [mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3]\n    F_statistic, p_value = gen_3samples(*params)\n    n, bins, patches = ax[4,1].hist(F_statistic, bins = 50)\n    F_critical = sp.stats.f.ppf(.95, 2, size1+size2+size3-3)\n    textstr = '\\n'.join((\n        '$\\mu_1, \\mu_2, \\mu_3 = {}, {}, {}$'.format(mu1, mu2, mu3),\n        '$\\sigma_1, \\sigma_2, \\sigma_3 = {}, {}, {}$'.format(sig1, sig2, sig3),\n        '$n_1, n_2, n_3 = {}, {}, {}$'.format(size1, size2, size3),\n        r'$F_c = {:.4f}$'.format(F_critical)))\n    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n    ax[4,1].text(max(bins)/2, max(n)/2, textstr, fontsize=10,\n            verticalalignment='top', bbox=props)\n    ax[4,1].vlines(F_critical, 0, max(n)*1.1, color = 'r')\n    ax[5,1].hist(p_value,bins = 50)\n    ax[4,1].set_title('Simulation 8')\n\n\n\n    params = [3, 3.1, 2.9, .01, .01, .01, 10, 20, 30]\n    mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3 = [3, 3, 3, 1, 1, 2, 10, 20, 30]\n    params = [mu1, mu2, mu3, sig1, sig2, sig3, size1, size2, size3]\n    F_statistic, p_value = gen_3samples(*params)\n    n, bins, patches = ax[4,2].hist(F_statistic, bins = 50)\n    F_critical = sp.stats.f.ppf(.95, 2, size1+size2+size3-3)\n    textstr = '\\n'.join((\n        '$\\mu_1, \\mu_2, \\mu_3 = {}, {}, {}$'.format(mu1, mu2, mu3),\n        '$\\sigma_1, \\sigma_2, \\sigma_3 = {}, {}, {}$'.format(sig1, sig2, sig3),\n        '$n_1, n_2, n_3 = {}, {}, {}$'.format(size1, size2, size3),\n        r'$F_c = {:.4f}$'.format(F_critical)))\n    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n    ax[4,2].text(max(bins)/2, max(n)/2, textstr, fontsize=10,\n            verticalalignment='top', bbox=props)\n    ax[4,2].vlines(F_critical, 0, max(n)*1.1, color = 'r')\n    ax[5,2].hist(p_value,bins = 50)\n    ax[4,2].set_title('Simulation 9')\n\n    #######################||Rectangle||##########################\n    ##############################################################\n\n    rect = plt.Rectangle(\n        # (lower-left corner), width, height\n        (0.10, 0.633), 0.2645, 0.258, fill=False, color=\"k\", lw=2, \n        zorder=1000, transform=fig.transFigure, figure=fig\n    )\n    fig.patches.extend([rect])\n\n\n    rect = plt.Rectangle(\n        # (lower-left corner), width, height\n        (0.3755, 0.633), 0.2645, 0.258, fill=False, color=\"k\", lw=2, \n        zorder=1000, transform=fig.transFigure, figure=fig\n    )\n    fig.patches.extend([rect])\n\n\n    rect = plt.Rectangle(\n        # (lower-left corner), width, height\n        (0.650, 0.633), 0.2645, 0.258, fill=False, color=\"k\", lw=2, \n        zorder=1000, transform=fig.transFigure, figure=fig\n    )\n    fig.patches.extend([rect])\n\n\n    rect = plt.Rectangle(\n        # (lower-left corner), width, height\n        (0.10, 0.37), 0.2645, 0.258, fill=False, color=\"k\", lw=2, \n        zorder=1000, transform=fig.transFigure, figure=fig\n    )\n    fig.patches.extend([rect])\n\n\n    rect = plt.Rectangle(\n        # (lower-left corner), width, height\n        (0.3755, 0.37), 0.2645, 0.258, fill=False, color=\"k\", lw=2, \n        zorder=1000, transform=fig.transFigure, figure=fig\n    )\n    fig.patches.extend([rect])\n\n    rect = plt.Rectangle(\n        # (lower-left corner), width, height\n        (0.650, 0.37), 0.2645, 0.258, fill=False, color=\"k\", lw=2, \n        zorder=1000, transform=fig.transFigure, figure=fig\n    )\n    fig.patches.extend([rect])\n\n    rect = plt.Rectangle(\n        # (lower-left corner), width, height\n        (0.650, 0.108), 0.2645, 0.258, fill=False, color=\"k\", lw=2, \n        zorder=1000, transform=fig.transFigure, figure=fig\n    )\n    fig.patches.extend([rect])\n\n    rect = plt.Rectangle(\n        # (lower-left corner), width, height\n        (0.3755, 0.108), 0.2645, 0.258, fill=False, color=\"k\", lw=2, \n        zorder=1000, transform=fig.transFigure, figure=fig\n    )\n    fig.patches.extend([rect])\n\n    rect = plt.Rectangle(\n        # (lower-left corner), width, height\n        (0.1, 0.108), 0.2645, 0.258, fill=False, color=\"k\", lw=2, \n        zorder=1000, transform=fig.transFigure, figure=fig\n    )\n    fig.patches.extend([rect])\n    ####################################################################\n\n    plt.show()\n###############################################################################################\n###############################################################################################\ndef two_tail_rej_region_demo():\n    data = pd.read_csv('500_Person_Gender_Height_Weight_Index.csv')\n    \n    df = len(data[data['Gender']=='Male'])-1\n    t_975 = sp.stats.t.ppf(.975, df=df)\n    t_025 = sp.stats.t.ppf(.025, df=df)\n    \n    male_mean = data[data['Gender']=='Male']['Height'].mean()\n    male_std = data[data['Gender']=='Male']['Height'].std(ddof=1)\n    male_std_error = male_std/np.sqrt(len(data[data['Gender']=='Male']))\n    male_null = 172\n    \n    x = np.linspace(male_null-5, male_null+5, 200)\n    \n    \n    y_t = sp.stats.t.pdf(x, df = df, loc = male_null)\n\n    fig, ax = plt.subplots(2, 1, figsize = (18,8))\n\n    ax[0].plot(x, y_t, color = 'tomato', lw = 3)\n\n    rejection_lower = male_null - t_975*male_std_error\n    x_rej_lower = np.linspace(rejection_lower-3, rejection_lower, 30)\n    y_rej_lower = sp.stats.t.pdf(x_rej_lower, df = df, loc = male_null)\n    ax[0].fill_between(x_rej_lower, y_rej_lower, color = 'tomato', alpha = .7)\n\n    rejection_upper = male_null + t_975*male_std_error\n    x_rej_upper = np.linspace(rejection_upper, rejection_upper+3, 30)\n    y_rej_upper = sp.stats.t.pdf(x_rej_upper, df = df, loc = male_null)\n    ax[0].fill_between(x_rej_upper, y_rej_upper, color = 'tomato', alpha = .7)\n    ax[0].set_ylim([0, .45])\n    ax[0].set_title('Rejection Region of Original Unit (cm)')\n\n    x = np.linspace(-5, 5, 200)\n    y_t = sp.stats.t.pdf(x, df = df, loc = 0)\n\n    ax[1].plot(x, y_t, color = 'tomato', lw = 3)\n\n    x_rej_lower = np.linspace(t_025-3, t_025, 30)\n    y_rej_lower = sp.stats.t.pdf(x_rej_lower, df = df)\n    ax[1].fill_between(x_rej_lower, y_rej_lower, color = 'tomato', alpha = .7)\n\n    x_rej_lower = np.linspace(t_975+3, t_975, 30)\n    y_rej_lower = sp.stats.t.pdf(x_rej_lower, df = df)\n    ax[1].fill_between(x_rej_lower, y_rej_lower, color = 'tomato', alpha = .7)\n    ax[1].set_ylim([0, .45])\n    ax[1].set_title('Rejection Region of t-statistic')\n\n    plt.show()\n###############################################################################################\n###############################################################################################\ndef one_tail_rej_region_demo():\n    fig, ax = plt.subplots(2, 1, figsize = (18,8))\n    x = np.linspace(-5, 5, 200)\n    y_t = sp.stats.t.pdf(x, df = len(x), loc = 0)\n    ax[0].plot(x, y_t, color = 'tomato')\n\n    ax[0].annotate('$H_0: \\mu = \\mu_0$\\n$H_1: \\mu < \\mu_0$', (-5, .35), size = 16)\n    t_05 = sp.stats.t.ppf(.05, df = len(x))\n    x_rej_lower = np.linspace(t_05, t_05-3, 30)\n    y_rej_lower = sp.stats.t.pdf(x_rej_lower, df = len(x))\n    ax[0].fill_between(x_rej_lower, y_rej_lower, color = 'tomato', alpha = .7)\n    ax[0].set_ylim([0, .45])\n\n    x = np.linspace(-5, 5, 200)\n    y_t = sp.stats.t.pdf(x, df = len(x), loc = 0)\n    ax[1].plot(x, y_t, color = 'tomato')\n\n    ax[1].annotate('$H_0: \\mu = \\mu_0$\\n$H_1: \\mu > \\mu_0$', (4, .35), size = 16)\n    t_95 = sp.stats.t.ppf(.95, df = len(x))\n    x_rej_lower = np.linspace(t_95, t_95+3, 30)\n    y_rej_lower = sp.stats.t.pdf(x_rej_lower, df = len(x))\n    ax[1].fill_between(x_rej_lower, y_rej_lower, color = 'tomato', alpha = .7)\n    ax[1].set_ylim([0, .45])\n\n    plt.show()", "meta": {"hexsha": "ce08e0c78af889eb88d3df2f15b6950ac102ee9d", "size": 27772, "ext": "py", "lang": "Python", "max_stars_repo_path": "Mathematics/Statistics/0.0 Basic_Statistics_With_Python/plot_material.py", "max_stars_repo_name": "okara83/Becoming-a-Data-Scientist", "max_stars_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2021-07-03T04:22:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T04:56:41.000Z", "max_issues_repo_path": "Mathematics/Statistics/0.0 Basic_Statistics_With_Python/plot_material.py", "max_issues_repo_name": "okara83/Becoming-a-Data-Scientist", "max_issues_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mathematics/Statistics/0.0 Basic_Statistics_With_Python/plot_material.py", "max_forks_repo_name": "okara83/Becoming-a-Data-Scientist", "max_forks_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-07-08T19:46:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T20:48:47.000Z", "avg_line_length": 46.056384743, "max_line_length": 115, "alphanum_fraction": 0.5223246435, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 9422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426458162397, "lm_q2_score": 0.9111797069968974, "lm_q1q2_score": 0.887527892617324}}
{"text": "import numpy as np\n\n\n'''\nExercise 1: NumPy: Create an array with values ranging from 12 to 38\n'''\n\narray_range = np.arange(12, 38)\nprint(array_range)\n\n'''\nExercise 2: Add a border around an existing array\n'''\n\narray_ones = np.ones((3, 3))\nprint(array_ones)\narray_ones_border = np.pad(array_ones, pad_width=1)\nprint(array_ones_border)\n\n'''\nExercise 3: Convert a list and tuple into arrays\n'''\nmy_list = [1, 2, 3, 4, 5, 6, 7, 8]\nprint(my_list)\nprint(\"List to array: \")\nprint(np.asarray(my_list))\n\nmy_tuple = ([8, 4, 6], [1, 2, 3])\nprint(\"Tuple to array: \")\nprint(np.asarray(my_tuple))\n\n'''\nExercise 4: Convert the values of Centigrade degrees into Fahrenheit degrees\n'''\nval_in_fahrenheit = np.array([0., 12., 45.21, 34., 99.91])\nprint(val_in_fahrenheit)\n\nval_in_celcius = (val_in_fahrenheit - 32) / 1.8\nprint(val_in_celcius)\n\n\n'''\nExercise 5: Write a NumPy program \nto find the number of elements of an array, \nlength of one array element in bytes and total bytes consumed by the elements.\n'''\n\narray_range = np.arange(12, 38)\nprint(f\"Number of elements of an array {array_range.size}\")\nprint(f\"length of one array element in bytes {array_range.itemsize}\")\nprint(f\"total bytes consumed by the elements {array_range.nbytes}\")\nprint(f\"total bytes consumed by the elements {array_range.dtype}\")\n\n\n'''\nExercise 6: Get the unique elements of an array\n'''\n\nx = np.array([10, 10, 20, 20, 30, 30])\nprint(np.unique(x))\n\nx = np.array([[1, 1], [2, 3]])\nprint(np.unique(x))\n\n\n'''\nExercise 7: Change the dimension of an array\n'''\n\noriginal_array = np.array([1,2,3,4,5,6,7,8,9])\nprint(original_array)\n\nnew_array_shape = original_array.reshape(3,3)\nprint(new_array_shape)\n\n\n'''\nExercise 8: Create a 1-D array of 30 evenly spaced elements between 2.5. and 6.5, inclusive\n'''\n\nevenly_array_1d_30 = np.linspace(2.5, 6.5, 30)\nprint(evenly_array_1d_30)\n\n'''\nExercise 9: Convert 1-D arrays as columns into a 2-D array\n'''\n\na = np.array((10,20,30))\nb = np.array((40,50,60))\n\nc = np.column_stack((a, b))\nprint(c)\n\nd = np.row_stack((a,b))\nprint(d)\n\n'''\nExercise 10: Create a 5x5 matrix with row values ranging from 0 to 4\n'''\nx = np.zeros((5,5))\n\n#x += np.arange(5)\n\nx[::] = [0,1,2,3,4]\n\nprint(x)\n\n\n'''\nExercise 11: Sum of all the multiples of 3 or 5 below 100\n'''\n\nx = np.arange(1,100)\nprint(x)\n\nn = x [(x%3==0) | (x%5 == 0)]\nprint(n.sum())\n\n\n\n'''\nExercise 12: Combine a one and a two dimensional array together and display their elements\n'''\n\nx = np.arange(4)\nprint(\"One dimensional array:\")\nprint(x)\ny = np.arange(8).reshape(2,4)\nprint(\"Two dimensional array:\")\nprint(y)\nfor a, b in np.nditer([x,y]):\n    print(f\"{a}:{b}\")\n\n'''\nExercise 13: Write a NumPy program to replace all elements of NumPy array that are greater than specified array.\n'''\nx = np.array([[ 0.42436315, 0.48558583, 0.32924763], [ 0.7439979,0.58220701,0.38213418], [ 0.5097581,0.34528799,0.1563123 ]])\nprint(\"Original array:\")\nprint(x)\nprint(\"Replace all elements of the said array with .5 which are greater than .5\")\nx[x > .5] = .5\nprint(x)\n\n'''\nExercise 14: Add a new row to an empty numpy array\n'''\n\narr = np.empty((0,3), int)\nprint(\"Empty array:\")\nprint(arr)\narr = np.append(arr, np.array([[10,20,30]]), axis=0)\narr = np.append(arr, np.array([[40,50,60]]), axis=0)\nprint(\"After adding two new arrays:\")\nprint(arr)\n\n\n'''\nExercise 15: Write a NumPy program to join a sequence of arrays along a new axis.\n'''\n\nx = np.array([1, 2, 3])\ny = np.array([2, 3, 4])\nprint(\"Original arrays:\")\nprint(x)\nprint(y)\nprint(\"Sequence of arrays along a new axis:\")\nprint(np.vstack((x, y)))\nx = np.array([[1], [2], [3]])\ny = np.array([[2], [3], [4]])\nprint(\"\\nOriginal arrays:\")\nprint(x)\nprint()\nprint(y)\nprint(\"Sequence of arrays along a new axis:\")\nprint(np.vstack((x, y)))", "meta": {"hexsha": "535cd6e8d1dce4ece7de029f6995c1cb3aea78af", "size": 3705, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercisenumpy.py", "max_stars_repo_name": "prabhurd/DataScientistPython", "max_stars_repo_head_hexsha": "1fe1b27bcac489d2a963e06153875a4639b08e13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercisenumpy.py", "max_issues_repo_name": "prabhurd/DataScientistPython", "max_issues_repo_head_hexsha": "1fe1b27bcac489d2a963e06153875a4639b08e13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercisenumpy.py", "max_forks_repo_name": "prabhurd/DataScientistPython", "max_forks_repo_head_hexsha": "1fe1b27bcac489d2a963e06153875a4639b08e13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1714285714, "max_line_length": 125, "alphanum_fraction": 0.6744939271, "include": true, "reason": "import numpy", "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.9425067147399245, "lm_q1q2_score": 0.8875153681862697}}
{"text": "import numpy as np\n\nmatrix_basic_1 = np.array([10,20,30])\nmatrix_basic_2 = np.array([15,40,90])\n\n# Concept of vectoriztion\nprint(matrix_basic_1/2,\"\\n\")\nprint(matrix_basic_1 - 2 , \"\\n\")\nprint(matrix_basic_1 + 2 , \"\\n\")\n\n# Comapring two matrices\nprint(matrix_basic_1 < matrix_basic_2)\n\n# Elementary operations on matrices\nprint(matrix_basic_1 - matrix_basic_2)\nprint(matrix_basic_1 + matrix_basic_2)\nprint(matrix_basic_1 * matrix_basic_2)\nprint(matrix_basic_1 / matrix_basic_2)\n\n# Accessing and slicing array\n# Similar to the python list slicing\narr = np.arange(1,11)\nprint(arr[-5:])\nprint(arr[::-1])\n\n# Creating shallow and deep copy\n# Shallow copy\nshallow_arr = arr\n\n# Deep copy\ndeep_arr = arr.copy()\n\n# Changing shape of array\n# Giving meaning shape\nreshaped_array = arr.reshape(2,5)\nprint(reshaped_array)", "meta": {"hexsha": "629c1124620b56522758a9ebaba7136d60002668", "size": 806, "ext": "py", "lang": "Python", "max_stars_repo_path": "vectorization.py", "max_stars_repo_name": "njanirudh/LinearAlgebra", "max_stars_repo_head_hexsha": "fbedfc633551903e855193458e63456c4c873240", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vectorization.py", "max_issues_repo_name": "njanirudh/LinearAlgebra", "max_issues_repo_head_hexsha": "fbedfc633551903e855193458e63456c4c873240", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-23T04:26:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-23T04:26:16.000Z", "max_forks_repo_path": "vectorization.py", "max_forks_repo_name": "njanirudh/LinearAlgebra", "max_forks_repo_head_hexsha": "fbedfc633551903e855193458e63456c4c873240", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3888888889, "max_line_length": 38, "alphanum_fraction": 0.7568238213, "include": true, "reason": "import numpy", "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611654370414, "lm_q2_score": 0.9241418267688303, "lm_q1q2_score": 0.8875099217848302}}
{"text": "# Check README.md for instruction to run\n\nimport numpy as np \nimport argparse\n\n'''\nFunction to calculate exp(x) for the given x passed as an argument\nTaylor Series expansion of exp(x) is such that: \nT_i = x^i/i! where i = 0, 1, 2, 3 ...\nSo, T_i/T_{i-1} = x/i \n\nSo, the algorithm for evaluation exp(x) starts with the first term 1 and subsequently finds each term by multiplying by x/i.\nAll theses terms are summed and the loop continues until the subsequent term becomes NaN, inf or zero.\n\nI also find the number of terms that were summed to get the function value.\n'''\ndef exp(x = 10):\n\n\tnum_terms = 0\n\tsum_terms = 0\n\ti = 1\n\tterm = 1\n\twhile (term != float(\"inf\") and term != float(\"nan\") and term != 0):\n\t\tsum_terms += term\n\t\tterm *= x/i\n\t\tnum_terms += 1\n\t\ti += 1\n\n\treturn sum_terms, num_terms\n\n\n'''\nA parser is created to accept command line argument\nThis code can accept one command line arguments - \n1. x: Value whose exp(x) is required to be calculated\n\nIf no command line argumennt is passed, default value of x is -5.\n'''\nif __name__ == '__main__':\n\t\n\tparser = argparse.ArgumentParser(description='x for which exp(x) is to be computed')\n\tparser.add_argument(\"-x\", type = float, default = -5, help='x for which exp(x) is to be computed')\n\targs = parser.parse_args()\n\n\tanswer, num_terms = exp(args.x)\n\texact_value = np.exp(args.x) # Exact Answer is found using the in-built function in numpy\n\terror = 100*abs(answer - exact_value)/exact_value # Error is evaluated in percentage by comparing with the exact_value\n\n\tprint(\"x = \", args.x)\n\tprint(\"Obtained Value: \", answer) \n\tprint(\"Exact Value:\", exact_value)\n\tprint(\"Error (%) : \", error )\n\tprint(\"Number of terms: \", num_terms, \"\\n\")\n", "meta": {"hexsha": "cf05914b1e5e75cbec4b4a6ed3ecbe6540229ba5", "size": 1689, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW1/exp.py", "max_stars_repo_name": "krishnaw14/CFD-codes", "max_stars_repo_head_hexsha": "beaeb75da0a98c2b89cef82b68a866955b9133f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-27T08:25:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T17:41:30.000Z", "max_issues_repo_path": "HW1/exp.py", "max_issues_repo_name": "krishnaw14/CFD-codes", "max_issues_repo_head_hexsha": "beaeb75da0a98c2b89cef82b68a866955b9133f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW1/exp.py", "max_forks_repo_name": "krishnaw14/CFD-codes", "max_forks_repo_head_hexsha": "beaeb75da0a98c2b89cef82b68a866955b9133f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2777777778, "max_line_length": 124, "alphanum_fraction": 0.7027827117, "include": true, "reason": "import numpy", "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102552339747, "lm_q2_score": 0.9173026567597713, "lm_q1q2_score": 0.8874079973027734}}
{"text": "import numpy as np\n\n\ndef euler_convert_to_rotation_matrix(yaw, pitch, roll):\n    # ZXY rotation, called rpy. problem: Gimbal Lock.\n    Rx = np.array([\n        [1, 0, 0],\n        [0, np.cos(roll), -np.sin(roll)],\n        [0, np.sin(roll), np.cos(roll)]\n    ])\n\n    Ry = np.array([\n        [np.cos(pitch), 0, np.sin(pitch)],\n        [0, 1, 0],\n        [-np.sin(pitch), 0, np.cos(pitch)]\n    ])\n\n    Rz = np.array([\n        [np.cos(yaw), -np.sin(yaw), 0],\n        [np.sin(yaw), np.cos(yaw), 0],\n        [0, 0, 1]\n    ])\n    # ZYX\n    return Rx @ Ry @ Rz\n\n\ndef rotation_matrix_to_euler(R):\n    roll = np.arctan(- R[1, 2] / R[2, 2])\n    pitch = np.arcsin(R[0, 2])\n    yaw = np.arctan(-R[0, 1] / R[0, 0])\n    return roll, pitch, yaw\n\nR = np.array([\n    [np.sqrt(2) / 2, -np.sqrt(2) / 2, 0.],\n    [np.sqrt(2) / 2, np.sqrt(2) / 2, 0.],\n    [0., 0., 1.]]\n)\n\nprint('get euler angle from rotation matrix:')\nroll, pitch, yaw = rotation_matrix_to_euler(R)\nprint(f'roll={np.rad2deg(roll)}, pitch={np.rad2deg(pitch)}, yaw={np.rad2deg(yaw)}')\nprint('convert euler angle to rotation matrix:')\nR_ = euler_convert_to_rotation_matrix(yaw, pitch, roll)\nprint(R_)", "meta": {"hexsha": "2190865817312dea0ea906491d58bef496f8f5e1", "size": 1141, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapter 3/Euler_angle.py", "max_stars_repo_name": "GracefulMan/slam14_python", "max_stars_repo_head_hexsha": "6c4c6b3bd81b88c23b708b084bdbb95ebc9745dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter 3/Euler_angle.py", "max_issues_repo_name": "GracefulMan/slam14_python", "max_issues_repo_head_hexsha": "6c4c6b3bd81b88c23b708b084bdbb95ebc9745dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter 3/Euler_angle.py", "max_forks_repo_name": "GracefulMan/slam14_python", "max_forks_repo_head_hexsha": "6c4c6b3bd81b88c23b708b084bdbb95ebc9745dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9318181818, "max_line_length": 83, "alphanum_fraction": 0.5495179667, "include": true, "reason": "import numpy", "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.975201841245846, "lm_q2_score": 0.9099070139780661, "lm_q1q2_score": 0.8873429953939197}}
{"text": "import numpy\nfrom matplotlib import pyplot\n\ndef simpsons(f, a, b, N):\n    x, dx = numpy.linspace(a, b, N+1, retstep=True)\n    fx = f(x)\n    return dx/3 * ( (fx[0] + fx[-1]) + \\\n        2*numpy.sum(fx[2:-1:2]) + 4*numpy.sum(fx[1:-1:2]) )\n        \ndef simpson_one_interval(f, a, b, h, points, fpoints, tol):\n    # Simpson on one interval with three points\n    I_2h = 2 * h / 3 * (fpoints[0] + fpoints[2] + 4*fpoints[1])\n    # Add new points (and integrand evaluations) for error check\n    new_points = [points[0], points[0]+h, points[1], points[1]+h, points[2]]\n    f_new_points = [fpoints[0], f(new_points[1]), fpoints[1], f(new_points[3]), fpoints[2]]\n    # Simpson over two subintervals\n    I_h = h / 3 * (fpoints[0] + fpoints[2] + 2 * fpoints[1] + \\\n                    4 * (f_new_points[1] + f_new_points[3]))\n    # Computable error estimate\n    error = abs(I_2h - I_h) / (2**4 - 1)\n    # If error on subinterval too big, and interval width not too small,\n    # subdivide this subinterval\n    if error > tol * (points[2] - points[0]) / (b - a) and (points[2] - points[0])/(b-a) > 1e-3:\n        left_I, left_points = simpson_one_interval(f, a, b, h/2, new_points[:3], f_new_points[:3], tol)\n        right_I, right_points = simpson_one_interval(f, a, b, h/2, new_points[2:], f_new_points[2:], tol)\n        return left_I + right_I, left_points + right_points[1:]\n    else:\n        return I_h, new_points\n\ndef adaptive_quad(f, a, b, tol=1e-6):\n    h = (b - a) / 2\n    points = [a, a+h, b]\n    fpoints = f(numpy.array(points))\n    return simpson_one_interval(f, a, b, h/2, points, fpoints, tol)\n    \ndef gauss_legendre(f, a, b, degree):\n    nodes, weights = numpy.polynomial.legendre.leggauss(degree)\n    x = (b - a) * (nodes + 1) / 2 + a\n    fx = f(x)\n    return numpy.sum(fx * weights) * (b - a) / 2\n    \nif __name__==\"__main__\":\n    print(\"Simpson's rule\")\n    print(simpsons(numpy.sin, 0, numpy.pi/2, 2))\n    print(simpsons(numpy.sin, 0, numpy.pi/2, 4))\n    Npoints = 2**numpy.arange(1,20)\n    dx_all = numpy.pi/2/Npoints\n    errors = numpy.zeros_like(dx_all)\n    for i, N in enumerate(Npoints):\n        I = simpsons(numpy.sin, 0, numpy.pi/2, N)\n        errors[i] = abs(I - 1)\n    pyplot.loglog(dx_all, errors, 'kx')\n    pyplot.loglog(dx_all, errors[0]*(dx_all/dx_all[0])**4, 'b-',\n                  label=r\"$\\propto \\Delta x^4$\")\n    pyplot.legend(loc='upper left')\n    pyplot.xlabel(r\"$\\Delta x$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.show()\n    \n    print(\"Adaptive quadrature\")\n    I, points = adaptive_quad(numpy.sin, 0, numpy.pi/2)\n    print(I, len(points))\n    x = numpy.linspace(0, numpy.pi/2, 1000)\n    pyplot.plot(x, numpy.sin(x), 'b-')\n    pyplot.plot(points, numpy.sin(points), 'kx')\n    pyplot.show()\n    \n    def g(x):\n        return numpy.where(numpy.pi > x, numpy.ones_like(x), numpy.zeros_like(x))\n    I, points = adaptive_quad(g, 0, 5)\n    x = numpy.linspace(0, 5, 1000)\n    pyplot.plot(x, g(x), 'b-')\n    pyplot.plot(points, g(numpy.array(points)), 'kx')\n    pyplot.ylim(-0.1, 1.1)\n    pyplot.show()\n    \n    \n    print(\"Gauss-Legendre\")\n    print(gauss_legendre(numpy.sin, 0, numpy.pi/2, 2))\n    print(gauss_legendre(numpy.sin, 0, numpy.pi/2, 4))\n    Npoints = numpy.arange(2,10)\n    dx_all = numpy.pi/2/Npoints\n    errors = numpy.zeros_like(dx_all)\n    for i, N in enumerate(Npoints):\n        I = gauss_legendre(numpy.sin, 0, numpy.pi/2, N)\n        errors[i] = abs(I - 1)\n    pyplot.semilogy(Npoints, errors, 'kx')\n    pyplot.xlabel(r\"$N$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.show()\n    \n    ", "meta": {"hexsha": "37aa595edbdf97fc3d8bc2e730d572b0aabe61ff", "size": 3519, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/tex/codes/lecture13.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Lectures/tex/codes/lecture13.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Lectures/tex/codes/lecture13.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 38.25, "max_line_length": 105, "alphanum_fraction": 0.5967604433, "include": true, "reason": "import numpy", "num_tokens": 1170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957912273285902, "lm_q2_score": 0.9263037353800999, "lm_q1q2_score": 0.8873177169111741}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 11 21:33:39 2019\nThis is the test of the numpy\n@author: yujijun\n\"\"\"\nimport numpy as np \n# a simple example of numpy \na = np.arange(15).reshape(3,5)\na.shape\na.ndim\na.dtype.name\na.itemsize\na.size\ntype(a)\n\n#array create \na = np.array([1,2,3])\nb =np.array((1,2,3))\nnp.zeros((3,4))\nnp.ones((3,4,5))\nnp.empty((2,3))\nnp.arange(10,20,5)\nnp.arange(1,3,0.3)\nnp.linspace(2,4,20)\nnp.random.random((2,3))\nx =np.linspace(0,2*np.pi,100)\ny = np.sin(x)\n\n#basic operations\na = np.array([10,20,30,40])\nb = np.arange(4)\nc = a -b \nb**2\nb*np.sin(a)\na < 35\n\nA = np.arange(4).reshape(2,2)\nB = np.arange(2,6).reshape(2,2)\nA*B\nA@B\nA.dot(B)\n\na = np.random.random((2,3))\na.sum()\na.min()\na.max()\n\nb = np.arange(12).reshape(3,4)\nb.sum(axis=0)\nb.min(axis=1)\nb.cumsum(axis=1)\n\n#universal function \nB = np.arange(3)\nnp.exp(B)\nnp.sqrt(B)\n\n\n\n#reshape\na.ravel()\na.reshape(3,4)\na.resize(3,4)\n\n\n#stacking together different arrays\na = np.floor(10*np.random.random((2,2)))\nb = np.floor(10*np.random.random((2,2)))\nc = np.floor(10*np.random.random((2,2)))\nnp.vstack((a,b,c))\nnp.hstack((a,b,c))\nnp.r_[1:4,3,4]\nnp.c_[1:4,3:6]\n\n\n#hsplit\na = np.floor(10*np.random.random((2,12)))\nnp.hsplit(a,3)\nnp.hsplit(a,(3,5))\n\n\n#copy and view \n# no copy at all (always the same)\na = np.arange(12)\nb = a  #a and b are two names for the same ndarray object\nb is a \nb.shape = 3,4\na.shape\n\n#view and shallow copy (just data is the same)\n#shape could change but two dataset still the same\nc = a.view()\nc is a \nc.base is a #True\nc.shape = 2,6\na.shape\nc[0,4] = 1234\na\n#slicing an array returns a view of it :\ns = a[:,1:3]\ns[:] = 10 #Note the difference between s=10 and s[:]=10\na\n \n#Deep copy (all isn't same)\nd = a.copy() #a new array object with new data is created\nd is a\nd.base is a  #d doesn't share anything with a\n\n#Sometimes copy should be called after slicing if the original array is not required anymore. For example, suppose a is a huge intermediate result and the final result b only contains a small fraction of a, a deep copy should be made when constructing b with slicing:\na = np.arange(int(1e8))\nb = a[:100].copy()\ndel a  # the memory of ``a`` can be released.\n#If b = a[:100] is used instead, a is referenced by b and will persist in memory even if del a is executed.\n\na = np.arange(12).reshape(3,4)\nb1 = np.array([0,1,1])\nb2 = np.array([False,True,True])\na[b1,:]\na[b2,:]\n\n\n#fancy indexing and index tricks\n\n#(1)\n#arrays can be indexed by arrays of integers and arrays of booleans\n#indexing, slicing  and interating\na = np.arange(10)**3\na[2]\na[2:5]\na[::-1]\na[:6:2] = -1000\na = np.arange(12)**2\ni = np.array([1,1,2,8,5])\na[i]\nj = np.array([[3,4],[9,7]]) # a bidimensional array of indices\na[j] # the same shape as j \n\n#for example \npalette = np.array( [ [0,0,0],                # black\n                      [255,0,0],              # red\n                      [0,255,0],              # green\n                      [0,0,255],              # blue\n                      [255,255,255] ] )   \n\nimage = np.array([[0,1,2,0],[0,3,4,0]])\npalette[image]\n\n#(2)\na = np.arange(12).reshape(3,4)\na\ni = np.array([[0,1],\n              [1,2]])\nj = np.array([[2,1],\n              [3,3]])\na[i,j] \nl = [i,j]\na[l]\na[i,2] #broad\na[:,j] #: same as 1,2,3\n\n#(3)\na = np.arange(5)\na[[1,3,4]] = 0\na\n\na = np.arange(5)\na[[0,0,2]] = [1,2,3] #when the list of indices contains repetitions, the assignment is done several times, leaving \n#behind the last value\na\n\n\n#(4)\n#indexing with boolean arrays\na = np.arange(12).reshape(3,4)\nb = a > 4 \na[b] #1d array with the selected elements\na[b] = 0 #all elements of \"a\" higher than 4 become 0\na\n\n#(5) \na = np.arange(12).reshape(3,4)\nb1 = np.array([False, True,True])\nb2 = np.array([True,False,True,False])\na[b1,:]\na[b1]\na[:,b2]\na[b1,b2]\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n# Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2\nmu, sigma = 2, 0.5\nv = np.random.normal(mu,sigma,10000)\n# Plot a normalized histogram with 50 bins\nplt.hist(v, bins=50, density=1)       # matplotlib version (plot)\nplt.show()\n\n# Compute the histogram with numpy and then plot it\n(n, bins) = np.histogram(v, bins=50, density=True)  # NumPy version (no plot)\nplt.plot(.5*(bins[1:]+bins[:-1]), n)\nplt.show()\n", "meta": {"hexsha": "485a169c0a0770b4b4a6fba8d485bf6ccc8d4b54", "size": 4252, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_test.py", "max_stars_repo_name": "yujijun/matplotlib", "max_stars_repo_head_hexsha": "e3cc7c884a7756a6b07f78a885a1e8f9430a72e0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy_test.py", "max_issues_repo_name": "yujijun/matplotlib", "max_issues_repo_head_hexsha": "e3cc7c884a7756a6b07f78a885a1e8f9430a72e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy_test.py", "max_forks_repo_name": "yujijun/matplotlib", "max_forks_repo_head_hexsha": "e3cc7c884a7756a6b07f78a885a1e8f9430a72e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8431372549, "max_line_length": 267, "alphanum_fraction": 0.6222953904, "include": true, "reason": "import numpy", "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360067, "lm_q2_score": 0.9294404043013231, "lm_q1q2_score": 0.8872878846940894}}
{"text": "import math\nimport random\n\nfrom numpy import arange\n\n\n# def get_i():\n#     return math.e ** 1 - math.e ** 0\n\n\ndef method_of_rectangles(func, mim_lim, max_lim, delta):\n    def integrate(func, mim_lim, max_lim, n):\n        integral = 0.0\n        step = (max_lim - mim_lim) / n\n        for x in arange(mim_lim, max_lim - step, step):\n            integral += step * func(x + step / 2)\n        return integral\n\n    d, n = 1, 1\n    while math.fabs(d) > delta:\n        d = (integrate(func, mim_lim, max_lim, n * 2) - integrate(func, mim_lim, max_lim, n)) / 3\n        n *= 2\n\n    a = math.fabs(integrate(func, mim_lim, max_lim, n))\n    b = math.fabs(integrate(func, mim_lim, max_lim, n)) + d\n    if a > b:\n        a, b = b, a\n    print('Rectangles:')\n    print('\\t%s\\t%s\\t%s' % (n, a, b))\n\n\ndef trapezium_method(func, mim_lim, max_lim, delta):\n    def integrate(func, mim_lim, max_lim, n):\n        integral = 0.0\n        step = (max_lim - mim_lim) / n\n        for x in arange(mim_lim, max_lim - step, step):\n            integral += step * (func(x) + func(x + step)) / 2\n        return integral\n\n    d, n = 1, 1\n    while math.fabs(d) > delta:\n        d = (integrate(func, mim_lim, max_lim, n * 2) - integrate(func, mim_lim, max_lim, n)) / 3\n        n *= 2\n\n    a = math.fabs(integrate(func, mim_lim, max_lim, n))\n    b = math.fabs(integrate(func, mim_lim, max_lim, n)) + d\n    if a > b:\n        a, b = b, a\n    print('Trapezium:')\n    print('\\t%s\\t%s\\t%s' % (n, a, b))\n\n\ndef simpson_method(func, mim_lim, max_lim, delta):\n    def integrate(func, mim_lim, max_lim, n):\n        integral = 0.0\n        step = (max_lim - mim_lim) / n\n        for x in arange(mim_lim + step / 2, max_lim - step / 2, step):\n            integral += step / 6 * (func(x - step / 2) + 4 * func(x) + func(x + step / 2))\n        return integral\n\n    d, n = 1, 1\n    while math.fabs(d) > delta:\n        d = (integrate(func, mim_lim, max_lim, n * 2) - integrate(func, mim_lim, max_lim, n)) / 15\n        n *= 2\n\n    a = math.fabs(integrate(func, mim_lim, max_lim, n))\n    b = math.fabs(integrate(func, mim_lim, max_lim, n)) + d\n    if a > b:\n        a, b = b, a\n    print('Simpson:')\n    print('\\t%s\\t%s\\t%s' % (n, a, b))\n\n\ndef monte_karlo_method(func, n):\n    in_d, out_d = 0., 0.\n    for i in range(n):\n        x, y = random.uniform(0, 1), random.uniform(0, 3)\n        if y < func(x):\n            in_d += 1\n\n    print('M-K:')\n    print('\\t%s\\t%s' % (n, math.fabs(in_d / n * 3)))\n\n\nprint('as')\nmethod_of_rectangles(lambda x: 4 * (x ** 3) - 2 * x, 0.0, 1.0, 0.001)\ntrapezium_method(lambda x: 4 * (x ** 3) - 2 * x, 0.0, 1.0, 0.001)\nsimpson_method(lambda x: 4 * (x ** 3) - 2 * x, 0.0, 1.0, 0.001)\n# monte_karlo_method(lambda x: math.e ** x, 100)\n# print('True value:\\n\\t%s' % get_i())\n", "meta": {"hexsha": "840fddd43bc993cade5cf54b30a4a75443aa85ae", "size": 2743, "ext": "py", "lang": "Python", "max_stars_repo_path": "4/test.py", "max_stars_repo_name": "slfdstrctd/num_methods", "max_stars_repo_head_hexsha": "1bc709947d072808bdbc24618fcf1ddfa65bca76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4/test.py", "max_issues_repo_name": "slfdstrctd/num_methods", "max_issues_repo_head_hexsha": "1bc709947d072808bdbc24618fcf1ddfa65bca76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4/test.py", "max_forks_repo_name": "slfdstrctd/num_methods", "max_forks_repo_head_hexsha": "1bc709947d072808bdbc24618fcf1ddfa65bca76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1428571429, "max_line_length": 98, "alphanum_fraction": 0.5461173897, "include": true, "reason": "from numpy", "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147153749275, "lm_q2_score": 0.9124361533336451, "lm_q1q2_score": 0.8872663423417303}}
{"text": "\nfrom scipy.special import factorial\n\nclass TaylorSerApprox(object):\n    \"\"\"\n    A simple python representation of the Taylor Series Approximation.\n    Taylor Series Approximations are often useful in representing non-linear \n    equations as a linear summation of terms relating to those non-linear equations.\n    \n    This allows the user to perform an approximation of arbitrary order, \n    as long as the function and the derivatives of that function are provided. \n    \"\"\"\n    def __init__(self, functions):\n        \"\"\"\n        The `functions` argument should be an iterator containing in the first\n        position the actual function to be evaluated. The remaining items should \n        be the derivatives of the function to be evaluated ascendingly ranked\n        based on their order.\n        e.g. functions = [function, prime1, prime2, ..., primeN]\n        Where function is what should be evaluated, prime# are the derivatives of \n        function, and the numbers on prime# correspond to their rank.\n        \n        Arguments:\n            functions {iterable} -- container of evaluation function and its derivatives\n        \"\"\"\n        self.functions = list(functions)\n        self.order = len(functions)\n        \n    \n    def approximate(self, x, a):\n        \"\"\"\n        Use this method to approximate the function supplied as the first\n        item in the `functions` argument when instantiating the class at the \n        value of `x` (f(x)). Choose `a` such that it can easily be calculated by the \n        the function of interest. \n\n        The basic form of the equation is as follows:\n        f(x) ~ f(a) + f'(a)(x-a)/1! + f\"(a)((x-a)^2)/2! + f'''(a)((x-a)^3)/3! ... etc\n        \n        Arguments:\n            x {float} -- desired value for function evaluation\n            a {float} -- variable used in the approximation to prevent difficult evaluations of your function\n        \n        Returns:\n            float -- Taylor Series Approximation of f(x)\n        \"\"\"\n        fun = self.functions[0]\n        initial = fun(a)\n        for i, fun in enumerate(self.functions[1:]):\n            coef = fun(a)/factorial(i+1)\n            right = (x-a)**(i+1)\n            initial += coef*right\n        return initial\n    \n    def __str__(self):\n        return f\"Taylor Series Approximation of order {self.order} for {self.functions[0].__name__}\"\n\ndef example(x, a):\n    def function(x):\n        return 5*x**3 + 6*x**2 - 4*x + 7\n\n    def prime1(x):\n        return 15*x**2 + 12*x - 4\n\n    def prime2(x):\n        return 30*x + 12\n\n    def prime3(x):\n        return 30\n\n    O1 = [function]\n    O2 = [function, prime1]\n    O3 = [function, prime1, prime2]\n    O4 = [function, prime1, prime2, prime3]\n\n    orders = [(\"O1\", O1), (\"O2\", O2), (\"O3\", O3), (\"O4\", O4)]\n    actual = function(x)\n    for name, funcs in orders:\n        tsa = TaylorSerApprox(funcs)\n        answer = tsa.approximate(x, a)\n        print(tsa)\n        print(f\"Order {name}: Actual Value = {actual}; Approximation = {answer}\")\n        \n\nif __name__ == \"__main__\":\n    x = 0.05\n    a = 1\n    example(x, a)\n", "meta": {"hexsha": "d0870e6bdf80dd053641e10e2cd64248bc538a60", "size": 3079, "ext": "py", "lang": "Python", "max_stars_repo_path": "taylor_series_approximation/taylor_series.py", "max_stars_repo_name": "lcford2/537_guest_lecture", "max_stars_repo_head_hexsha": "b0a744c87473b13ed693518ed0daedcd2bc27f9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-25T14:36:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-25T14:36:33.000Z", "max_issues_repo_path": "taylor_series_approximation/taylor_series.py", "max_issues_repo_name": "lcford2/537_guest_lecture", "max_issues_repo_head_hexsha": "b0a744c87473b13ed693518ed0daedcd2bc27f9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "taylor_series_approximation/taylor_series.py", "max_forks_repo_name": "lcford2/537_guest_lecture", "max_forks_repo_head_hexsha": "b0a744c87473b13ed693518ed0daedcd2bc27f9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.595505618, "max_line_length": 109, "alphanum_fraction": 0.6024683339, "include": true, "reason": "from scipy", "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244552, "lm_q2_score": 0.9184802356574272, "lm_q1q2_score": 0.8871596668099738}}
{"text": "import numpy as np\n\n\ndef f(x, normalize=False):\n    '''\n    Function proportional to target distribution, a sum of Gaussians.\n    For testing, set normalize to True, to get target distribution exactly.\n    '''\n    # Gaussian heights, width parameters, and mean positions respectively:\n    a = np.array([10., 3., 1.]).reshape(3, 1)\n    b = np.array([ 4., 0.2, 2.]).reshape(3, 1)\n    xs = np.array([-4., -1., 5.]).reshape(3, 1)\n\n    if normalize:\n        norm = (np.sqrt(np.pi) * (a / np.sqrt(b))).sum()\n        a /= norm\n\n    return (a * np.exp(-b * (x - xs)**2)).sum(axis=0)\n\ndef g():\n    '''Random step vector.'''\n    return np.random.uniform(-1,1)\n\ndef metropolis_step(x, f=f, g=g):\n    '''Perform one full iteration and return new position.'''\n    \n    x_proposed = x + g()\n    a = min(1, (f(x_proposed) / f(x)).item())\n    \n    x_new = np.random.choice([x_proposed, x], p=[a, 1-a])\n        \n    return x_new\n\ndef metropolis_iterate(x0, num_steps):\n    '''Iterate metropolis algorithm for num_steps using iniital position x_0'''\n    \n    for n in range(num_steps):\n        if n == 0:\n            x = x0\n        else:\n            x = metropolis_step(x)\n        yield x\n    \n\ndef test_metropolis_iterate(num_steps, xmin, xmax, x0):\n    '''\n    Calculate error in normalized density histogram of data  \n    generated by metropolis_iterate() by using \n    normalized-root-mean-square-deviation metric. \n    '''\n    \n    bin_width = 0.25\n    bins = np.arange(xmin, xmax + bin_width/2, bin_width)\n    centers = np.arange(xmin + bin_width/2, xmax, bin_width)\n    \n    true_values = f(centers, normalize=True)\n    mean_value = np.mean(true_values - min(true_values))\n\n    x_dat = list(metropolis_iterate(x0, num_steps))\n    heights, _ = np.histogram(x_dat, bins=bins, density=True)\n                    \n    nmsd = np.average((heights - true_values)**2 / mean_value)\n    nrmsd = np.sqrt(nmsd)\n\n    return nrmsd\n\n        \n \nif __name__ == \"__main__\":\n    xmin, xmax = -10, 10\n    x0 = np.random.uniform(xmin, xmax)\n\n    num_steps = 50_000\n\n    x_dat = list(metropolis_iterate(x0, 50_000))\n        \n    # Write data to file\n    output_string = \"\\n\".join(str(x) for x in x_dat)\n    \n    with open(\"output.dat\", \"w\") as out:\n        out.write(output_string)\n        out.write(\"\\n\")\n        \n    \n    # Testing\n    print(f\"Testing with x0 = {x0:5.2f}\")\n    print(f\"{'num_steps':>10s} {'NRMSD':10s}\")\n    for num_steps in (500, 5_000, 50_000):\n        nrmsd = test_metropolis_iterate(num_steps, xmin, xmax, x0)\n        print(f\"{num_steps:10d} {nrmsd:5.1%}\")\n", "meta": {"hexsha": "a4fc29794d3328c4e1430d9a609bff1ad0c49785", "size": 2546, "ext": "py", "lang": "Python", "max_stars_repo_path": "contents/metropolis/code/python/metropolis.py", "max_stars_repo_name": "alzawad26/algorithm-archive", "max_stars_repo_head_hexsha": "98ca4ab8115dd9013e6a5267cb757d61f0350ad7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-09-12T18:58:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-12T18:58:58.000Z", "max_issues_repo_path": "contents/metropolis/code/python/metropolis.py", "max_issues_repo_name": "alzawad26/algorithm-archive", "max_issues_repo_head_hexsha": "98ca4ab8115dd9013e6a5267cb757d61f0350ad7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-08-09T18:36:48.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-09T18:36:48.000Z", "max_forks_repo_path": "contents/metropolis/code/python/metropolis.py", "max_forks_repo_name": "alzawad26/algorithm-archive", "max_forks_repo_head_hexsha": "98ca4ab8115dd9013e6a5267cb757d61f0350ad7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.978021978, "max_line_length": 79, "alphanum_fraction": 0.5950510605, "include": true, "reason": "import numpy", "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951703918909, "lm_q2_score": 0.9230391558355999, "lm_q1q2_score": 0.8869960495840912}}
{"text": "\"\"\"\nCopyright 2013 Steven Diamond\n\nThis file is part of CVXPY.\n\nCVXPY is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nCVXPY is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with CVXPY.  If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\n\n#!/usr/bin/env python3\n# @author: R. Gowers, S. Al-Izzi, T. Pollington, R. Hill & K. Briggs\n# Boyd and Vandenberghe, Convex Optimization, exercise 4.57 page 207\n\nimport cvxpy as cvx\nimport numpy as np\n\n'''\nInput parameters\n  P: channel transition matrix P_ij(t) = P(output|input) at time t\n  n: size of input\n  m: size of output\n'''\n\ndef channel_capacity(n,m,sum_x=1):\n  '''\nBoyd and Vandenberghe, Convex Optimization, exercise 4.57 page 207\nCapacity of a communication channel.\n  \nWe consider a communication channel, with input x(t)∈{1,..,n} and\noutput Y(t)∈{1,...,m}, for t=1,2,... .The relation between the\ninput and output is given statistically:\np_(i,j) = ℙ(Y(t)=i|X(t)=j), i=1,..,m  j=1,...,m\nThe matrix P ∈ ℝ^(m*n) is called the channel transition matrix, and\nthe channel is called a discrete memoryless channel. Assuming X has a\nprobability distribution denoted x ∈ ℝ^n, i.e.,\nx_j = ℙ(X=j), j=1,...,n\nThe mutual information between X and Y is given by\n∑(∑(x_j p_(i,j)log_2(p_(i,j)/∑(x_k p_(i,k)))))\nThen channel capacity C is given by\nC = sup I(X;Y).\nWith a variable change of y = Px this becomes\nI(X;Y)=  c^T x - ∑(y_i log_2 y_i)\nwhere c_j = ∑(p_(i,j)log_2(p_(i,j)))\n  '''\n  # n is the number of different input values\n  # m is the number of different output values\n  if n*m == 0:\n    print('The range of both input and output values must be greater than zero')\n    return 'failed',np.nan,np.nan\n  # P is the channel transition matrix\n  P = np.ones((m,n))\n  # x is probability distribution of the input signal X(t)\n  x = cvx.Variable(rows=n,cols=1)\n  # y is the probability distribution of the output signal Y(t)\n  y = P*x\n  # I is the mutual information between x and y\n  c = np.sum(P*np.log2(P),axis=0)\n  I = c*x + cvx.sum(cvx.entr(y))\n  # Channel capacity maximised by maximising the mutual information\n  obj = cvx.Minimize(-I)\n  constraints = [cvx.sum(x) == sum_x,x >= 0]\n  # Form and solve problem\n  prob = cvx.Problem(obj,constraints)\n  prob.solve()\n  if prob.status=='optimal':\n    return prob.status,prob.value,x.value\n  else:\n    return prob.status,np.nan,np.nan\n\n# as an example, let's optimise the channel capacity for two different possible input and output values\nif __name__ == '__main__':\n  print(channel_capacity.__doc__)\n  # print all arrays to have 3 significant figures after the decimal place\n  np.set_printoptions(precision=3)\n  n = 2\n  m = 2\n  print('Number of input values=%s'%n)\n  print('Number of outputs=%s'%m)\n  stat,C,x=channel_capacity(n,m)\n  print('Problem status ',stat)\n  print('Optimal value of C = %.4g'%(C))\n  print('Optimal variable x = \\n', x)\n", "meta": {"hexsha": "fe4f29e7776b6e9862102fbe3a942df3f5d017fa", "size": 3251, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/communications/Channel_capacity_BV4.57.py", "max_stars_repo_name": "NunoEdgarGFlowHub/cvxpy", "max_stars_repo_head_hexsha": "43270fcc8af8fc4742f1b3519800b0074f2e6693", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/communications/Channel_capacity_BV4.57.py", "max_issues_repo_name": "NunoEdgarGFlowHub/cvxpy", "max_issues_repo_head_hexsha": "43270fcc8af8fc4742f1b3519800b0074f2e6693", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/communications/Channel_capacity_BV4.57.py", "max_forks_repo_name": "NunoEdgarGFlowHub/cvxpy", "max_forks_repo_head_hexsha": "43270fcc8af8fc4742f1b3519800b0074f2e6693", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9569892473, "max_line_length": 103, "alphanum_fraction": 0.7059366349, "include": true, "reason": "import numpy,import cvxpy", "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075711974104, "lm_q2_score": 0.9219218396818157, "lm_q1q2_score": 0.8869879820101201}}
{"text": "import numpy as np\r\nimport time\r\n\r\n##------------ exact value of the integration -----------\r\n\r\n\r\n### _--------------Simpson's 3/8 rule -----------------\r\nstartTime = time.time()\r\nx = float(input(\"Enter the value of initial point(try 0.1): \"))\r\ny = float(input(\"Enter the value of final point(try 1.3): \"))\r\nn = int(input(\"number of intervals: \"))\r\n\r\n\r\ndef simpson_third(x, y, n):\r\n    h = (y - x) / n\r\n\r\n    def fun(x):\r\n        return 5 * x * np.exp(-2 * x)\r\n\r\n    i = 0\r\n    sum = 0\r\n    # sum=fun(x)+fun(y)\r\n    while i <= n:\r\n        if i == 0:\r\n            sum = sum + fun(x)\r\n        elif i == n:\r\n            sum = sum + fun(y)\r\n        elif i % 3 == 0:\r\n            sum = sum + 2 * fun(x + h * i)\r\n        else:\r\n            sum += 3 * fun(x + h * i)\r\n        i += 1\r\n    #print(\"Number of iterations: \", n)\r\n    return (3 * h / 8) * sum\r\n\r\n\r\nfrom scipy.integrate import quad\r\n\r\n\r\ndef integrate(p):\r\n    return 5 * p * np.exp(-2 * p)\r\n\r\n\r\nexact_value = quad(integrate, 0.1, 1.3)\r\nprint(\" The true value of integration is \", \"%.5f\" %exact_value[0])\r\n\r\nsimpson = simpson_third(x, y, n)\r\n# abs_error = (result-exact_value)\r\n#\r\n# while n>np.log((y-x)/abs_error)/np.log(2)-1:\r\n# print(n)\r\nprint(\" The value of integration is \", \"%.5f\" % simpson)\r\nabs_err = ( simpson - exact_value[0])\r\n# print(\" Error is: \" , \"%.5f\"% abs_err)\r\nprint(\" error is: \",abs_err)\r\n# print(abs_error)\r\nendTime = time.time()\r\ntotalTime = endTime - startTime\r\n\r\nprint(\"Total time taken to execute code is= \", totalTime)", "meta": {"hexsha": "fd3a4e95219e3521f62d41ab5cb9a198038a24a9", "size": 1497, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numerical_Methods_Physics/Simpson's_2nd_Rule.py", "max_stars_repo_name": "Simba2805/Computational_Physics_Python", "max_stars_repo_head_hexsha": "be687939c16a1d08066939830ac31ba666a3e1bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numerical_Methods_Physics/Simpson's_2nd_Rule.py", "max_issues_repo_name": "Simba2805/Computational_Physics_Python", "max_issues_repo_head_hexsha": "be687939c16a1d08066939830ac31ba666a3e1bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numerical_Methods_Physics/Simpson's_2nd_Rule.py", "max_forks_repo_name": "Simba2805/Computational_Physics_Python", "max_forks_repo_head_hexsha": "be687939c16a1d08066939830ac31ba666a3e1bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.95, "max_line_length": 68, "alphanum_fraction": 0.5197060788, "include": true, "reason": "import numpy,from scipy", "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305360354471, "lm_q2_score": 0.9207896764343916, "lm_q1q2_score": 0.8869327336078049}}
{"text": "import numpy as np\n\n#  Function\ndef f(x):\n    y = 1 /np.sqrt(2 * np.pi) * np.exp(-x ** 2 / 2)\n    return y\n\n# General Gauss method with three points\ndef GaussQuad3(a, b, tol):\n    # Compute Integral with 3 Point Gauss Method\n    def GaussQuad(a, b):\n        t = [-pow(3/5, 0.5), 0, pow(3/5, 0.5)]\n        x = [0.5*((b-a)*t[0] + b+a), 0.5*((b-a)*t[1] + b+a),\n             0.5*((b-a)*t[2] + b+a)]\n        I = 0.5 * (b - a) * (f(x[0])/1.8 + f(x[1])/1.125 + f(x[2])/1.8)\n        return I\n\n    # We compute the Integral in N Intervals Using Gauss Method so as to Compute the Error\n    def GaussQuadn(n):\n        h = (b-a)/n\n        I = 0.0\n\n        for i in range(n):\n            x0 = a + i*h\n            x1 = x0 + h\n            I += GaussQuad(x0, x1)\n\n        return I\n\n    # We compute the error using analytic computations\n    def dGaussQuadn(n):\n        h = (b-a)/(2*n)\n        I2 = 0.0\n\n        for i in range(2*n):\n            x0 = a + i*h\n            x1 = x0 + h\n            I2 += GaussQuad(x0, x1)\n\n        dI = 32/31 * abs(I2-GaussQuadn(n))\n\n        return dI\n\n    # Min Value\n    n = 2\n    # General Error\n    η = dGaussQuadn(n)/GaussQuadn(n)\n\n    while η > tol:\n        n += 1\n        η = dGaussQuadn(n)/GaussQuadn(n)\n\n    return GaussQuadn(n), dGaussQuadn(n), η\n\nif __name__ == \"__main__\":\n    print('\\nComputed with 3 Point Gauss Method:')\n    print(f\"\\tI ± δI = {'%.8f'%GaussQuad3(-5, 5, 0.001)[0]} ± {GaussQuad3(-5, 5, 0.001)[1]:.8f}\")\n    print(f'\\tThe General Error is η = {GaussQuad3(-5, 5, 0.001)[2]:.5f} < 0.1 %')", "meta": {"hexsha": "2077c42938d28e672a2aa176f3c834991571a651", "size": 1528, "ext": "py", "lang": "Python", "max_stars_repo_path": "Integration/Gauss-Quadrature-Three-Points.py", "max_stars_repo_name": "AlexTsagas/Computational-Physics", "max_stars_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Integration/Gauss-Quadrature-Three-Points.py", "max_issues_repo_name": "AlexTsagas/Computational-Physics", "max_issues_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Integration/Gauss-Quadrature-Three-Points.py", "max_forks_repo_name": "AlexTsagas/Computational-Physics", "max_forks_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3448275862, "max_line_length": 97, "alphanum_fraction": 0.4921465969, "include": true, "reason": "import numpy", "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924802053234, "lm_q2_score": 0.9124361682155117, "lm_q1q2_score": 0.8868810941728368}}
{"text": "import numpy as np\n\n# Create the time axis (seconds)\nnum_samples = 1001\nsamples_per_second = 1000\nfreq_Hz = 0.5\nt = np.linspace(0.0, ((num_samples - 1) / samples_per_second), num_samples)\n# Create a sine wave, a(t), with a frequency of 1 Hz\na = np.sin((2.0 * np.pi) * freq_Hz * t)\n# Create b(t), a (pi / 2.0) phase-shifted replica of a(t)\nb_shift = (np.pi / 2.0)\nb = np.sin((2.0 * np.pi) * freq_Hz * t + b_shift)\n\n# Cross-correlate the signals, a(t) & b(t)\nab_corr = np.correlate(a, b, \"full\")\ndt = np.linspace(-t[-1], t[-1], (2 * num_samples) - 1)\n# Calculate time & phase shifts\nt_shift_alt = (1.0 / samples_per_second) * ab_corr.argmax() - t[-1]\nt_shift = dt[ab_corr.argmax()]\n# Limit phase_shift to [-pi, pi]\nphase_shift = ((2.0 * np.pi) * ((t_shift / (1.0 / freq_Hz)) % 1.0)) - np.pi\n\nmanual_t_shift = (b_shift / (2.0 * np.pi)) / freq_Hz\n\n# Print out applied & calculated shifts\nprint(\"Manual time shift: {}\".format(manual_t_shift))\nprint(\"Alternate calculated time shift: {}\".format(t_shift_alt))\nprint(\"Calculated time shift: {}\".format(t_shift))                    \nprint(\"Manual phase shift: {}\".format(b_shift))                           \nprint(\"Calculated phase shift: {}\".format(phase_shift)) \n\nimport matplotlib.pyplot as plt\n\nplt.figure()\nplt.plot(dt, ab_corr)\n# plt.plot(t, a)\n# plt.plot(t, b)\nplt.show()", "meta": {"hexsha": "0b78fa8fd1721bba0d7304be7215e166c8b5c0e8", "size": 1319, "ext": "py", "lang": "Python", "max_stars_repo_path": "Development/Random Testing/cross_correlation_testing/test2.py", "max_stars_repo_name": "AdityaSavara/Frhodo", "max_stars_repo_head_hexsha": "90ad23b8f238bd2b4dd9b94eea757fa658e92499", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-05-20T19:33:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T17:22:52.000Z", "max_issues_repo_path": "Development/Random Testing/cross_correlation_testing/test2.py", "max_issues_repo_name": "AdityaSavara/Frhodo", "max_issues_repo_head_hexsha": "90ad23b8f238bd2b4dd9b94eea757fa658e92499", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-27T06:07:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-27T06:07:56.000Z", "max_forks_repo_path": "Development/Random Testing/cross_correlation_testing/test2.py", "max_forks_repo_name": "AdityaSavara/Frhodo", "max_forks_repo_head_hexsha": "90ad23b8f238bd2b4dd9b94eea757fa658e92499", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-05-13T21:56:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T01:48:42.000Z", "avg_line_length": 34.7105263158, "max_line_length": 75, "alphanum_fraction": 0.6444275967, "include": true, "reason": "import numpy", "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924802053235, "lm_q2_score": 0.9124361634533147, "lm_q1q2_score": 0.8868810895440172}}
{"text": "# Reference Book: Python Data Science Handbook (page:(63-69))\n# Date(13 April, 2019) Day-3, Time = 3:25 PM\n\n# Broadcasting is simply a set of rules for applying binary ufuncs(addition,\n# subtraction, multiplication, etc.) onarrays of different sizes.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nprint('\\nIntroducing Broadcasting:')\na = np.array([0, 1, 2])\nb = np.array([5, 5, 5])\n\nprint(a + b)  # [5,6,7]\nprint(a + 5)  # [5,6,7]\n\nmatrix = np.ones((3, 3))\nprint(matrix + a)\n'''\n[[1. 2. 3.]\n [1. 2. 3.]\n [1. 2. 3.]]\n'''\na = np.arange(3)\nb = np.arange(3)[:, np.newaxis]\n\nprint(a + b)\n'''\n[[0 1 2]\n [1 2 3]\n [2 3 4]]\n'''\n\n# @@@@@@@@@@ Broadcasting example 1 @@@@@@@@@@@@@@@@\nprint('\\nBroadcasting Example -1:')\na = np.ones((2, 3))\nb = np.arange(3)\n\nprint(a.shape, ' ', b.shape)\n\n'''\nWe see by rule 1 that the array a has fewer dimensions, so we pad it on the left with\nones:\nM.shape -> (2, 3)\na.shape -> (1, 3)\nBy rule 2, we now see that the first dimension disagrees, so we stretch this dimension\nto match:\nM.shape -> (2, 3)\na.shape -> (2, 3)\nThe shapes match, and we see that the final shape will be (2, 3) :\n'''\nprint(a + b)\n\nprint('\\nBroadcasting example - 2:')\na = np.arange(3).reshape((3, 1))\nb = np.arange(3)\n# Again, we’ll start by writing out the shape of the arrays:\n# a.shape = (3, 1)\n# b.shape = (3,)\n\n'''\nRule 1 says we must pad the shape of b with ones:\na.shape -> (3, 1)\nb.shape -> (1, 3)\nAnd rule 2 tells us that we upgrade each of these ones to match the corresponding\nsize of the other array:\na.shape -> (3, 3)\nb.shape -> (3, 3)\nBecause the result matches, these shapes are compatible. We can see this here:\n'''\n\nprint(a + b)\n\nprint('\\nBroadcasting example - 3:')\na = np.ones((3,2))\nb = np.arange(3)\n\n#print(a + b)\n#ValueError: operands could not be broadcast together with shapes (3,2) (3,)\n\n#to bypass this value error we can use np.newaxis method\nb = b[:,np.newaxis]\n\nprint(a + b)\n\nprint('\\nBroadcasting in Practice: ')\n#Centering an array\n\na = np.random.random((5,3))\nprint(a)\n\naMean = a.mean(0)\nprint(aMean)\n\naCentered = a - aMean\nprint(a)\nprint(aCentered)\nprint(aCentered.mean(0))\n\n'''\nBroadcasting in Practice: \n[[0.83862929 0.14317788 0.80506902]\n [0.46464661 0.26061009 0.72977281]\n [0.18953245 0.98315161 0.41065711]\n [0.30367627 0.72104366 0.67134196]\n [0.12079467 0.89210426 0.70943855]]\n\n[0.38345586 0.6000175  0.66525589]\n\n[[0.83862929 0.14317788 0.80506902]\n [0.46464661 0.26061009 0.72977281]\n [0.18953245 0.98315161 0.41065711]\n [0.30367627 0.72104366 0.67134196]\n [0.12079467 0.89210426 0.70943855]]\n\n[[ 0.45517343 -0.45683962  0.13981313]\n [ 0.08119075 -0.33940741  0.06451692]\n [-0.19392341  0.38313411 -0.25459878]\n [-0.07977959  0.12102616  0.00608607]\n [-0.26266118  0.29208676  0.04418266]]\n\n[2.22044605e-17 2.22044605e-17 0.00000000e+00]\n'''\n\n#Plotting a two-dimensional function\na = np.linspace(0,5,50)\nb = np.linspace(0,5,50)[:, np.newaxis]\n\nz = np.sin(a) ** 10 + np.cos(10 + b * a) * np.cos(a)\n\nfig = plt.figure()\n\nplt.imshow(z, origin='lower', extent=[0,5,0,5],cmap='viridis')\nplt.colorbar()\nfig.savefig('Plotting a two dimensional function')\nprint(plt.show())", "meta": {"hexsha": "e6bc982bd43b64740369eb39fcfea51b66c266d6", "size": 3112, "ext": "py", "lang": "Python", "max_stars_repo_path": "python3/numpy/ComputationOnArraysBroadcasting.py", "max_stars_repo_name": "Nahid-Hassan/code-snippets", "max_stars_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-29T04:09:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-18T13:33:36.000Z", "max_issues_repo_path": "python3/numpy/ComputationOnArraysBroadcasting.py", "max_issues_repo_name": "Nahid-Hassan/code-snippets", "max_issues_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python3/numpy/ComputationOnArraysBroadcasting.py", "max_forks_repo_name": "Nahid-Hassan/code-snippets", "max_forks_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-26T04:55:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T04:55:55.000Z", "avg_line_length": 22.8823529412, "max_line_length": 86, "alphanum_fraction": 0.6584190231, "include": true, "reason": "import numpy", "num_tokens": 1151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545392102522, "lm_q2_score": 0.9353465165999585, "lm_q1q2_score": 0.8868530454487481}}
{"text": "from sympy import Range\n\n\ndef SieveOfEratosthenes(number: int) -> None:\n    \"\"\"\n    SieveOfEratosthenes:\n    Primes smaller than or equal to n using Sieve of Eratosthenes.\n    Create a boolean array \"prime[0..n]\" and initialize all entries it as true.\n    A value in prime[i] will finally be false if i is not a prime, else true.\n    Args:\n        number (int): The limit till which the function will find primes.\n    \"\"\"\n\n    prime: list[bool] = [True for _ in Range(number + 1)]\n    prime_candidate: int = 2\n    while (prime_candidate * prime_candidate <= number):\n\n        # If prime[prime_candidate] is not\n        # changed, then it is a prime\n        if (prime[prime_candidate] is True):\n\n            # Update all multiples of prime_candidate\n            for i in Range(prime_candidate ** 2, number + 1, prime_candidate):\n                prime[i] = False\n        prime_candidate += 1\n\n    # Print all prime numbers.\n    for prime_candidate in Range(2, number + 1):\n        if prime[prime_candidate]:\n            print(prime_candidate)\n\n\nif __name__ == '__main__':\n    NUMBER = int(input(\"Enter a limit: \"))\n    print(\"Following are the prime numbers smaller than or equal to\", NUMBER)\n    SieveOfEratosthenes(NUMBER)\n", "meta": {"hexsha": "195be6a7590f600cea2a5ea42d698cbd1a8e6974", "size": 1223, "ext": "py", "lang": "Python", "max_stars_repo_path": "Codes/Math/sieve_erasthosthenes.py", "max_stars_repo_name": "datta-agni/python-codes", "max_stars_repo_head_hexsha": "d902d0aaf23d2ea4b60ed7ecab0d593e3334c23b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Codes/Math/sieve_erasthosthenes.py", "max_issues_repo_name": "datta-agni/python-codes", "max_issues_repo_head_hexsha": "d902d0aaf23d2ea4b60ed7ecab0d593e3334c23b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Codes/Math/sieve_erasthosthenes.py", "max_forks_repo_name": "datta-agni/python-codes", "max_forks_repo_head_hexsha": "d902d0aaf23d2ea4b60ed7ecab0d593e3334c23b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0540540541, "max_line_length": 79, "alphanum_fraction": 0.6492232216, "include": true, "reason": "from sympy", "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241982893259, "lm_q2_score": 0.9149009613738741, "lm_q1q2_score": 0.886835640897864}}
{"text": "import numpy as np\nimport numpy.linalg as la\nfrom io import StringIO\n\ndef print_mat(mat):\n\n    stream = StringIO()\n    np.savetxt(stream, mat, fmt=\"%.3f\")\n    print( stream.getvalue() )\n\n# -----------------------------------\n\n# transition matrix L\nL = np.array([\n    [0,   1/2, 1/3, 0, 0,   0   ],\n    [1/3, 0,   0,   0, 1/2, 0   ],\n    [1/3, 1/2, 0,   1, 0,   1/2 ],\n    [1/3, 0,   1/3, 0, 1/2, 1/2 ],\n    [0,   0,   0,   0, 0,   0   ],\n    [0,   0,   1/3, 0, 0,   0   ]\n])\n\n\n# initial vector for r\nr = ( np.ones(6) / 6 ) * 100.0\n\n# ------------------------------------\n# for r_1\n\nr_1 = np.matmul(L, r)\nprint_mat(r_1)\n\n# ------------------------------------\n# for r_11\n\nr_next = r_1\nfor _ in range(10):\n    r_next = np.matmul(L, r_next)\n\nr_11 = r_next\nprint_mat(r_11)\n\n# ------------------------------------\n# for r_convergence under diff < 0.01\n\n\nr_cur = r\nthreshold = 0.01\nwhile True:\n\n    r_next = np.matmul(L, r_cur)\n\n    if la.norm(r_next - r_cur) < threshold:\n        # check convergence condition is met or not\n        break\n\n    r_cur = r_next\n\nprint_mat(r_cur)\n", "meta": {"hexsha": "a1f25c81972694fb85e62aa3c0adc7ad5a0fe7fd", "size": 1071, "ext": "py", "lang": "Python", "max_stars_repo_path": "PageRank/Page Rank_stage_2.py", "max_stars_repo_name": "brianchiang-tw/Hyperskill", "max_stars_repo_head_hexsha": "4bb70b19ba4909562e2494a0e9c9660a89bc1139", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-19T20:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-19T20:10:42.000Z", "max_issues_repo_path": "PageRank/Page Rank_stage_2.py", "max_issues_repo_name": "brianchiang-tw/Hyperskill", "max_issues_repo_head_hexsha": "4bb70b19ba4909562e2494a0e9c9660a89bc1139", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PageRank/Page Rank_stage_2.py", "max_forks_repo_name": "brianchiang-tw/Hyperskill", "max_forks_repo_head_hexsha": "4bb70b19ba4909562e2494a0e9c9660a89bc1139", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.85, "max_line_length": 51, "alphanum_fraction": 0.4687208217, "include": true, "reason": "import numpy", "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773708039218115, "lm_q2_score": 0.9073122244934722, "lm_q1q2_score": 0.886780478261272}}
{"text": "# Assignement on Poisson Distribution\n\nimport numpy as np\nfrom scipy.stats import poisson\n\n'''\n1.Find the probability that atmost 5 defective fuses will be found in a box of 200 fuses if experience shows that 2 per cent of such fuses are defective.\n'''\nprint(\"Assignment 1\")\nprint(\"Probability of atmost 5 Defective\",poisson.cdf(k=5,mu=200*0.02))\nprint(\"\\n\")\n\n'''\n2.The number of accidents in a year attributed to taxi drivers in a city follows a Poisson distribution with mean equal to 3. Out of 1,000 taxi drivers, find approximately the number of drivers with\na)No accidents in a year\nb)More than 3 accidents in a year\n'''\nprint(\"Assignment 2\")\n\nprint(\"No of drivers with no accidents in a year\",\n        poisson.pmf(k=0,mu=3)*1000)\nprint(\"No of drivers with more than 3 accidents in a year\",\n        (1-poisson.cdf(k=3,mu=3))*1000)\n\nprint(\"\\n\")\n'''\n\n3.From the records of 10 Indian Army corps kept over 20 years the following data were obtained showing the number of deaths caused by the horse. Calculate the theoretical Poisson frequencies\nNo of Deaths:\t\t0\t1\t2\t3\t4\tTotal\nFrequency:\t\t109\t65\t22\t3\t1\t200\n'''\nprint(\"Assignment 3\")\nmean_value=(0*109 + 1*65 + 2*22 + 3*3 + 4*1)/200\nprint(\"Frequencies of Deaths\")\nfor k in np.arange(4+1):\n    print(\"No of Deaths={}, Frequency={}\"\\\n            .format(k,poisson.pmf(k=k,mu=mean_value)*200))\n\nprint(\"\\n\")", "meta": {"hexsha": "9dca8f1ba3e948a5bbbae04f6ae86306d819c353", "size": 1351, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/simplePrograms/poisson.py", "max_stars_repo_name": "BharathC15/NielitChennai", "max_stars_repo_head_hexsha": "c817aaf63b741eb7a8e4c1df16b5038a0b4f0df7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/simplePrograms/poisson.py", "max_issues_repo_name": "BharathC15/NielitChennai", "max_issues_repo_head_hexsha": "c817aaf63b741eb7a8e4c1df16b5038a0b4f0df7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/simplePrograms/poisson.py", "max_forks_repo_name": "BharathC15/NielitChennai", "max_forks_repo_head_hexsha": "c817aaf63b741eb7a8e4c1df16b5038a0b4f0df7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-11T08:04:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-11T08:04:43.000Z", "avg_line_length": 34.641025641, "max_line_length": 198, "alphanum_fraction": 0.7165062916, "include": true, "reason": "import numpy,from scipy", "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992942089574, "lm_q2_score": 0.9161096107264305, "lm_q1q2_score": 0.8867018456401548}}
{"text": "import numpy as np                     # Import numpy for array manipulation\nimport matplotlib.pyplot as plt        # Import matplotlib for charts\nfrom utils_nb import plot_vectors      # Function to plot vectors (arrows)\n# Create a 2 x 2 matrix\nR = np.array([[2, 0],\n              [0, -2]])\nx = np.array([[1, 1]]) # Create a 1 x 2 matrix\ny = np.dot(x, R) # Apply the dot product between x and R\ny\nplot_vectors([x], axes=[4, 4], fname='transform_x.svg')\nplot_vectors([x, y], axes=[4, 4], fname='transformx_and_y.svg')\n\nangle = 100 * (np.pi / 180) #convert degrees to radians\n\nRo = np.array([[np.cos(angle), -np.sin(angle)],\n              [np.sin(angle), np.cos(angle)]])\n\nx2 = np.array([2, 2]).reshape(1, -1) # make it a row vector\ny2 = np.dot(x2, Ro)\n\nprint('Rotation matrix')\nprint(Ro)\nprint('\\nRotated vector')\nprint(y2)\n\nprint('\\n x2 norm', np.linalg.norm(x2))\nprint('\\n y2 norm', np.linalg.norm(y2))\nprint('\\n Rotation matrix norm', np.linalg.norm(Ro))\n\nplot_vectors([x2, y2], fname='transform_02.svg')\n\nA = np.array([[2, 2],\n              [2, 2]])\nA_squared = np.square(A)\nA_squared\n\nA_Frobenius = np.sqrt(np.sum(A_squared))\nA_Frobenius\n\nprint('Frobenius norm of the Rotation matrix')\nprint(np.sqrt(np.sum(Ro * Ro)), '== ', np.linalg.norm(Ro))\n", "meta": {"hexsha": "d0ce045553790cdba509e99e7d8fa16bbafd98ee", "size": 1250, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine_translation/vector_manipulation.py", "max_stars_repo_name": "junyaogz/pp4nlp", "max_stars_repo_head_hexsha": "9f403352dcce1874d32ba775a02cbacda0904966", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "machine_translation/vector_manipulation.py", "max_issues_repo_name": "junyaogz/pp4nlp", "max_issues_repo_head_hexsha": "9f403352dcce1874d32ba775a02cbacda0904966", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "machine_translation/vector_manipulation.py", "max_forks_repo_name": "junyaogz/pp4nlp", "max_forks_repo_head_hexsha": "9f403352dcce1874d32ba775a02cbacda0904966", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7619047619, "max_line_length": 76, "alphanum_fraction": 0.6352, "include": true, "reason": "import numpy", "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347875615795, "lm_q2_score": 0.9099070097026719, "lm_q1q2_score": 0.8866450437004152}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Diffie–Hellman Key Exchange Algorithm\n\n# ## About \n# Diffie–Hellman key exchange is a method of securely exchanging cryptographic keys over a public channel and was one of the first public-key protocols as conceived by Ralph Merkle and named after Whitfield Diffie and Martin Hellman. Diffie–Hellman is one of the earliest practical examples of public key exchange implemented within the field of cryptography.\n# \n# Diffie-Hellman, uses Asymetric Key cryptography to communicate the Key securely through the media.\n\n# ## Algorithm\n# \n# 1. Select a random prime number, **q**\n# 2. Calculate $\\alpha$, such that, $\\alpha$ is the **Primitive Root of q** and $\\alpha$ > q\n# 3. **For User A:**\n#     1. Select **Private Key** , **pvtKey<sub>a</sub>**, such that pvtKey<sub>a</sub> < q\n#     2. Calculate **Public Key**, **pubKey<sub>a</sub> = $\\alpha$<sup>pvtKey<sub>a</sub></sup> mod q**\n# 4. **For User B:**\n#     1. Select **Private Key** , **pvtKey<sub>b</sub>**, such that pvtKey<sub>b</sub> < q\n#     2. Calculate **Public Key**, **pubKey<sub>b</sub> = $\\alpha$<sup>pvtKey<sub>b</sub></sup> mod q**\n# \n# After the above steps we get a **pair of Private and Public Keys** for each User. These are to be **used** for generating the final **Key**.\n# \n# \n# **User A :** { Private Key of A , Public Key of A } = { **pvtKey<sub>a</sub>** , **pubKey<sub>a</sub>**  }\n# \n# **User B :** { Private Key of B , Public Key of B } = { **pvtKey<sub>b</sub>** , **pubKey<sub>b</sub>**  }\n# \n# Generate **Key**, **K<sub>a</sub> & K<sub>b</sub>**  at both users' end. ***If keys generated***, **match**, the Key Exchange process is **Successful**.\n# \n# ***Note:*** The Private Key of a user is known only to that user and no other user has the access to it. While the Public Key of all the users are known to all the users in the network.\n# \n# ![total.jpg](attachment:total.jpg)\n\n# ## Key Generation\n# \n# For User A, **K<sub>a</sub> = pubKey<sub>b</sub> <sup>pvtKey <sub>a</sub> </sup> mod q**\n# \n# \n# For User B, **K<sub>b</sub> = pubKey<sub>a</sub> <sup>pvtKey <sub>b</sub> </sup> mod q**\n# \n# \n# If **K<sub>a</sub> = K<sub>b</sub>** then the **Key Exchange** is **Successful**. And The final secret key is ***K = K<sub>a</sub> = K<sub>b</sub>***\n# \n# ![keyGen.jpg](attachment:keyGen.jpg)\n\n# In[13]:\n\n\nfrom sympy import *\nfrom termcolor import colored\nimport random\n\n# ------ Generate q ------ #\n\nq = randprime(0, 250)\n\n# ------ Funtion to Generate ------ #\n\ndef generateKey(pubKey, pvtKey):\n    return (pubKey**pvtKey)%q\n\n# ------ Funtion to Generate Public Key ------ #\n\ndef publicKey(key, pr):\n    return (pr**key)%q\n\n\n# ------ Funtion to Determine primitive roots ------ #\n\ndef primitiveRoot(q):\n    setOfPR = []\n    a = 1\n    while a<q:\n        rootSet= set()\n        reqSet = set()\n        for i in range(1, q):\n            rootSet.add(int((a**i)%q))\n        #print(rootSet)\n        for j in range(1, q):\n            reqSet.add(j)\n        if rootSet == reqSet:\n            setOfPR.append(a)\n            a += 1\n            #break\n        else:\n            a += 1\n    print(\"Primitive Roots of q = \", setOfPR, end=\"\\n\\n\")\n    return random.choice(setOfPR)\n\n\nprint(\"q = \", q, end=\"\\n\\n\")\n\n\n# -------------- Primitive root of q -------------- #\n\nprimRoot = primitiveRoot(q)\n\n\nprint(\"Selected (at random) Primitive Root of q = \", primRoot, end=\"\\n\\n\")  \n\n\n# -------------- Name of user A and B -------------- #\n\na , b = input(\"Enter the Names of the two users communicating: \").split(\" \") \n\n\n# ------------------ User A Operations ------------------ #\n\n# Private Key of user A\nprivateKeyOfA = int(input(\"\\nSelect {}'s Private Key (less than q): \".format(a)))\n\n\n# Public Key of user A\npublicKeyOfA = publicKey(privateKeyOfA, primRoot)\n\n\n# Print Public Key of A\nprint(\"Keys of User {}\".format(a))\nprint(\"--- Private Key : \", privateKeyOfA)\nprint(\"--- Public  Key : \", publicKeyOfA)\n\n\n# ------------------ User B Operations ------------------ #\n\n# Private Key of user B\nprivateKeyOfB = int(input(\"\\nSelect {}'s Private Key (less than q): \".format(b)))\n\n\n# Public Key of user B\npublicKeyOfB = publicKey(privateKeyOfB, primRoot)\n\n\n# Print Public Key of B\nprint(\"Keys of User {}\".format(b))\nprint(\"--- Private Key : \", privateKeyOfB)\nprint(\"--- Public  Key : \", publicKeyOfB)\n\n# ------------------ Key Generation ------------------ #\n\nprint(\"\\nKey Generation\")\n\n\n# Key Generation for A\nprint(\"\\nGenerate Key for {}\".format(a))\nkeyA = generateKey(publicKeyOfB, int(input(\"--- Enter {}'s Private Key: \".format(a))))\nprint(\"--- Key generated for {} is {}\".format(a, keyA))\n\n\n# Key Generation for B\nprint(\"\\nGenerate Key for {}\".format(b))\nkeyB = generateKey(publicKeyOfA, int(input(\"--- Enter {}'s Private Key: \".format(b))))\nprint(\"--- Key generated for {} is {}\".format(b, keyB))\n\n\n# ------------------- Key Exchange Verification ------------------- #\n\nif keyA == keyB :\n    print(colored(\"\\nKey Exchange Successful!\", 'green'))\n    print(colored(\"--- Your Key is {}\".format(keyA) , 'green'))\nelse:\n    print(colored(\"\\nKey Exchange Failed!\", 'red'))\n\n\n# #### Tanmoy Sen Gupta\n# [tanmoysg.com](http://tanmoysg.com) | +91 9864809029 | tanmoysps@gmail.com\n", "meta": {"hexsha": "c75cf9459f89fccbe0544efbc67d2c3879232f12", "size": 5176, "ext": "py", "lang": "Python", "max_stars_repo_path": "Diffie-Hellman Key Exchange/Diffie-Hellman Key Exchange.py", "max_stars_repo_name": "TanmoySG/RSA-Algorithm", "max_stars_repo_head_hexsha": "cba1b4ba8e96c6eb1bd67097e47ed7763185fb63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-05-05T11:07:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T13:19:05.000Z", "max_issues_repo_path": "Diffie-Hellman Key Exchange/Diffie-Hellman Key Exchange.py", "max_issues_repo_name": "TanmoySG/RSA-Algorithm", "max_issues_repo_head_hexsha": "cba1b4ba8e96c6eb1bd67097e47ed7763185fb63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-12T18:13:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T18:13:12.000Z", "max_forks_repo_path": "Diffie-Hellman Key Exchange/Diffie-Hellman Key Exchange.py", "max_forks_repo_name": "TanmoySG/RSA-Algorithm", "max_forks_repo_head_hexsha": "cba1b4ba8e96c6eb1bd67097e47ed7763185fb63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-01T01:19:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T01:19:39.000Z", "avg_line_length": 30.994011976, "max_line_length": 359, "alphanum_fraction": 0.5964064915, "include": true, "reason": "from sympy", "num_tokens": 1482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488964, "lm_q2_score": 0.9314625036384887, "lm_q1q2_score": 0.8866249075690563}}
{"text": "import numpy as np\n\n\ndef inverse_power_method(A, tol=1e-9, Max_iter=100):\n    \"\"\" Calculate the minimum eigenvalue and the corresponding eigenvector by inverse power method.\n\n    Args:\n        A: ndarray, the matrix to be solved\n        tol: double, iteration accuracy\n        Max_iter: int, maximum iteration number\n\n    Retruns:\n        k: int, interation number\n        eig: double. minimum eigenvalue of the matrix A\n        eigv: ndarray, corresponding eigenvector\n    \"\"\"\n    # initialization\n    # iteration number\n    k = 0\n    # initial eigenvalue\n    eig = 0\n    # initial eigenvector\n    eigv = np.ones(A.shape[0])\n\n    # iteration\n    while k < Max_iter and np.linalg.norm(A @ eigv - eig * eigv) >= tol:\n        k += 1\n        x = np.linalg.solve(A, eigv)\n        eig = 1 / x[np.argmax(x)]\n        eigv = x * eig\n\n    return k, eig, eigv\n\n\ndef acceleration_inverse_power(A, alpha, tol=1e-9, Max_iter=100):\n    \"\"\" Calculate the eigenvalue around alpha and corresponding eigenvector by inverse power method.\n\n    Args:\n        A: ndarray, the matrix to be solved\n        alpha: double, acceleration number\n        tol: double, iteration accuracy\n        Max_iter: int, maximum iteration number\n\n    Returns:\n        k: int, iteration number\n        eig: double, eigenvalue around alpha of the matrix A\n        eigv: ndarray, corresponding eigenvector\n    \"\"\"\n    # initialization\n    B = A - alpha * np.eye(A.shape[0])\n\n    # inverse power method\n    k, eig, eigv = inverse_power_method(B, tol, Max_iter)\n\n    eig += alpha\n\n    return k, eig, eigv\n\n\nif __name__ == '__main__':\n    A = np.array([[4, -1, 1], [-1, 3, -2], [1, -2, 3]])\n    n, eig, eigv = inverse_power_method(A, 1e-6)\n    print(f\"The eigenvalue is {eig:.7f}, and corresponding eigenvector is {eigv}.\")\n    print(f\"Iteration number is {n}.\")\n    n, eig, eigv = acceleration_inverse_power(A, 2.5, 1e-6)\n    print(f\"The eigenvalue around 2.5 is {eig:.7f}, and corresponding eigenvector is {eigv}.\")\n    print(f\"Iteration number is {n}.\")\n\n", "meta": {"hexsha": "43f7aaa6e5290f71e1106e5662fbe6d13ca90d02", "size": 2011, "ext": "py", "lang": "Python", "max_stars_repo_path": "EigenvaluesandEigenvectors/inverse_power_method.py", "max_stars_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_stars_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EigenvaluesandEigenvectors/inverse_power_method.py", "max_issues_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_issues_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EigenvaluesandEigenvectors/inverse_power_method.py", "max_forks_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_forks_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1449275362, "max_line_length": 100, "alphanum_fraction": 0.6315266037, "include": true, "reason": "import numpy", "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.9273632956467158, "lm_q1q2_score": 0.8865420154398951}}
{"text": "import numpy as np\n\n# Basic demo of\n# 1. Given a secuence, compute and apply a Hann Window\n# 2. Compute DFT using the decimation in time algorithm => FFT\n\nx = np.array([1, 1, 2, 0, 0, 2, 1, 1])\nL = len(x)\nN = L - 1\n\n# Hanning window\nw = 0.5 * (1 - np.cos(2*np.pi*np.arange(L)/N))\n\n# Windowed signal\nxw = x * w\n\n# Wkn\nWkn = np.exp(-1j * 2*np.pi * np.arange(4)/L)\n# Patch: Wkn[2] is super ugly!\nWkn[2] = -1j\n\n# Step 1: combine first with second half of the sequence\nX1 = np.zeros(L)\nX1[0:4] = xw[0:4] + xw[4:]\nX1[4:8] = xw[0:4] - xw[4:]\n\nprint('Pass 1a', X1)\n# Multiply second half by Wkn\nX1 = X1 * np.hstack((np.ones_like(Wkn), Wkn))\nprint('Pass 1b', X1)\n\n# Step 2: 4 elements combos\nX2 = np.zeros(L)\nX2 = X2 + 1j * 0  # Trick to convert X2 to complex\nX2[0:2] = X1[0:2] + X1[2:4]\nX2[2:4] = X1[0:2] - X1[2:4]\nX2[4:6] = X1[4:6] + X1[6:8]\nX2[6:8] = X1[4:6] - X1[6:8]\n\nprint('Pass 2a', X2)\n# Multiply by Wkn factors\nX2 = X2 * np.array([1, 1, Wkn[0], Wkn[2], 1, 1, Wkn[0], Wkn[2]])\nprint('Pass 2b', X2)\n\n# Step 3: 2 elements combos\nX3 = np.zeros_like(X2)  # This directly creates a complex array\nX3[0] = X2[0] + X2[1]\nX3[1] = X2[0] - X2[1]\nX3[2] = X2[2] + X2[3]\nX3[3] = X2[2] - X2[3]\nX3[4] = X2[4] + X2[5]\nX3[5] = X2[4] - X2[5]\nX3[6] = X2[6] + X2[7]\nX3[7] = X2[6] - X2[7]\n\n# Bit reverse\n# binary_repr(...)[::-1] returns the binary number reversed\n# int(..., base=2) converts back to decimal\nbr = [int(np.binary_repr(x, width=3)[::-1], base=2) for x in range(8)]\nX3 = X3[br]\n\n# Check result\nprint('FFT      ', X3)\nprint('FFT numpy', np.fft.fft(xw))\n", "meta": {"hexsha": "0900e632841b29760b7c56cdf7cfc3e92d9ae9f4", "size": 1542, "ext": "py", "lang": "Python", "max_stars_repo_path": "fft_decimation_in_time.py", "max_stars_repo_name": "Jordi-/git-tutorial", "max_stars_repo_head_hexsha": "60e9dbd15ee94b9204ce18dcba9dff1784657e18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fft_decimation_in_time.py", "max_issues_repo_name": "Jordi-/git-tutorial", "max_issues_repo_head_hexsha": "60e9dbd15ee94b9204ce18dcba9dff1784657e18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fft_decimation_in_time.py", "max_forks_repo_name": "Jordi-/git-tutorial", "max_forks_repo_head_hexsha": "60e9dbd15ee94b9204ce18dcba9dff1784657e18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7230769231, "max_line_length": 70, "alphanum_fraction": 0.5849546044, "include": true, "reason": "import numpy", "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104924150546, "lm_q2_score": 0.9173026522382527, "lm_q1q2_score": 0.8864909078432054}}
{"text": "import scipy as sp\n\ndef hilbert(n):\n    \"\"\"Calculate an nxn Hilbert matrix\"\"\"\n\n    H = sp.zeros((n,n))\n\n    for i in range(n):\n        for j in range(n):\n            H[i][j] = 1.0/(i+j+1)\n\n    return H\n\ndef cond(matrix):\n    \"\"\"Calculate the condition number of matrix\"\"\"\n\n    return sp.linalg.norm(matrix)*sp.linalg.norm(sp.linalg.pinv(matrix))\n\n", "meta": {"hexsha": "44df54895ad1a295c5d1b4c9f09b3f93a1c7683e", "size": 347, "ext": "py", "lang": "Python", "max_stars_repo_path": "Source/hilbert.py", "max_stars_repo_name": "abefrandsen/numerical_computing", "max_stars_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/hilbert.py", "max_issues_repo_name": "abefrandsen/numerical_computing", "max_issues_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/hilbert.py", "max_forks_repo_name": "abefrandsen/numerical_computing", "max_forks_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-21T23:06:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T23:06:27.000Z", "avg_line_length": 18.2631578947, "max_line_length": 72, "alphanum_fraction": 0.5878962536, "include": true, "reason": "import scipy", "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9702399094961359, "lm_q2_score": 0.9136765251766503, "lm_q1q2_score": 0.8864854290961371}}
{"text": "import sympy as smp\nfrom sympy import *\n\ndef prgrm_iter():\n    x, k, n, h = smp.symbols ('x k n h')\n    f = smp.sin(x)\n\n    print (\" \")\n    print (\"This program comes from the GitHub repository\")\n    print (\"AndreiMurashev/pos.int_diff_formula\")\n    print (\" \")\n    print (\"The purpose of this program is to check if the formula\")\n    print (\"for the derivative of a certain positive integer order holds\")\n    print (\" \")\n\n    print (\"For which positive integer case would you like to check\")\n    n = int(input(\"if the formula works?: \"))\n\n    d = diff(f, x, n)\n    D = smp.limit((smp.Sum(((-1)**k)*(smp.binomial(n,k))*(f.subs(x,x+(n-k)*h)), (k, 0, n)).doit())/(h**n), h, 0)\n    print(d,\" ?=? \", D)\n    print (\" \")\n\n    if d == D:\n        print (d,\" = \", D)\n        print (\"[VALID]: The formula holds for the derivative of order\", n)\n\n    if d != D:\n        print (d,\" =/= \", D)\n        print (\"[INVALID]: The formula fails for the derivative of order\", n)\n        print (\"Please screenshot this and email the creator of the GitHub repository\")\n\n\ndef prgrm():\n    while True:\n        prgrm_iter()\n        ans = input(\"Repeat? (y/n): \")\n        if ans != \"y\":\n            break\n\n\nif __name__ == '__main__':\n    try:\n        prgrm()\n    finally:\n        input(\"Done. Press any key to exit: \")\n", "meta": {"hexsha": "f7a6c8ae56f9254fcd937f96f7dec79be7e1cd54", "size": 1291, "ext": "py", "lang": "Python", "max_stars_repo_path": "formula-verif-case.py", "max_stars_repo_name": "AndreiMurashev/pos.int_diff_formula", "max_stars_repo_head_hexsha": "a641e1e4193d188b51612bfb0cd9fac43437092a", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-02-04T07:33:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T08:12:33.000Z", "max_issues_repo_path": "formula-verif-case.py", "max_issues_repo_name": "AndreiMurashev/pos.int_diff_formula", "max_issues_repo_head_hexsha": "a641e1e4193d188b51612bfb0cd9fac43437092a", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "formula-verif-case.py", "max_forks_repo_name": "AndreiMurashev/pos.int_diff_formula", "max_forks_repo_head_hexsha": "a641e1e4193d188b51612bfb0cd9fac43437092a", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4680851064, "max_line_length": 112, "alphanum_fraction": 0.5569326104, "include": true, "reason": "import sympy,from sympy", "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9770226334351969, "lm_q2_score": 0.9073122201074847, "lm_q1q2_score": 0.8864645746373497}}
{"text": "# This script uses the Montecarlo method to find the\r\n# [approximated] area under a curve (definite integral)\r\n\r\nimport math\r\nimport random\r\nimport time\r\n\r\nimport numpy as np\r\nimport scipy.integrate as integrate\r\nimport matplotlib.pyplot as plt\r\n\r\ndef montecarlo_iterative_integration(fun, a, b, num_puntos=1000):\r\n    # To keep track of time\r\n    tic = time.time()\r\n\r\n    #HALLAMOS M\r\n    M = 0\r\n    for i in np.arange(a, b, (b-a)/num_puntos):\r\n        aux = fun(i)\r\n        if aux > M :\r\n            M = aux\r\n    print(\"\\n__Integral (iterative)__\")\r\n    print(\"Máximum: \", M)\r\n\r\n    #QUEDA DEFINIDO EL CUADRADO ENTRE A-B Y 0-M\r\n    #LANZAMOS PUNTOS ALEATORIOS DENTRO DEL CUADRADO\r\n\r\n    nDebajo = 0\r\n\r\n    for i in range(num_puntos):\r\n        x = random.uniform(a, b)\r\n        y = random.uniform(0, M)\r\n\r\n        if fun(x)>y :\r\n            nDebajo+=1\r\n\r\n    print(\"Points under curve: \", nDebajo)\r\n    print(\"Total points: \", num_puntos)\r\n\r\n    I = (nDebajo/num_puntos)*(b-a)*M\r\n    print (\"Montecarlo integral: \", I)\r\n\r\n    toc = time.time()\r\n    print(\"time: \", 1000*(toc - tic))\r\n\r\n    return 1000*(toc - tic)\r\n\r\ndef montecarlo_vectorized_integration(fun, a, b, num_puntos=1000):\r\n    # To keep track of time\r\n    tic = time.time()\r\n\r\n    # Vectors with uniformly distributed points\r\n    vectorX = np.random.uniform(low = a, high = b, size =(num_puntos))\r\n\r\n    vectorizedFun = np.vectorize(fun)\r\n    funResults = vectorizedFun(vectorX)\r\n    M = funResults.max()\r\n    vectorY = np.random.uniform(low = 0, high = M, size =(num_puntos))\r\n\r\n    print(\"\\n__Integral (vectorized)__\")\r\n    print(\"Máximum: \", M)\r\n\r\n    # Points under the curve\r\n    nDebajo = np.greater(funResults, vectorY).sum()\r\n\r\n    print(\"Points under curve: \", nDebajo)\r\n    print(\"Total points: \", num_puntos)\r\n\r\n    # Value of the integral (Montecarlo approximation)\r\n    I = (nDebajo/num_puntos)*(b-a)*M\r\n    print (\"Montecarlo integral: \", I)\r\n\r\n    toc = time.time()\r\n    print(\"Time: \", 1000*(toc - tic))\r\n\r\n    return 1000*(toc - tic)\r\n\r\n\r\niterativeArray = []\r\nvectorizedArray = []\r\niValues = []\r\n\r\n# Compare both methods (iterative and vectorized) performance when using\r\n# increasingly larger number of points\r\nfor i in range(1, 1000000, 100000):\r\n    iterativeArray.append(montecarlo_iterative_integration(math.sin, 0, math.pi, i))\r\n    vectorizedArray.append(montecarlo_vectorized_integration(math.sin, 0, math.pi, i))\r\n    iValues.append(i)\r\n\r\n# Show and save the results\r\nplt.figure()\r\nplt.scatter(iValues, iterativeArray, color='red', label=\"Iterative\")\r\nplt.scatter(iValues, vectorizedArray, color='blue', label=\"Vectorized\")\r\nplt.ylabel('Time comparison')\r\nplt.legend()\r\nplt.savefig(\"time_comparison.png\")\r\nplt.show()\r\n\r\nprint(\"\\nReal integral value: \", integrate.quad(math.sin, 0, math.pi)[0], \"\\n\")\r\n", "meta": {"hexsha": "44db5b21bb68956ca56d9e4398f7c1fabd96eb82", "size": 2790, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/montecarlo/montecarlo.py", "max_stars_repo_name": "dimart10/machine-learning", "max_stars_repo_head_hexsha": "0f33bef65a9335c0f7fed680f1112419bae8fabc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/montecarlo/montecarlo.py", "max_issues_repo_name": "dimart10/machine-learning", "max_issues_repo_head_hexsha": "0f33bef65a9335c0f7fed680f1112419bae8fabc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/montecarlo/montecarlo.py", "max_forks_repo_name": "dimart10/machine-learning", "max_forks_repo_head_hexsha": "0f33bef65a9335c0f7fed680f1112419bae8fabc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9, "max_line_length": 87, "alphanum_fraction": 0.6405017921, "include": true, "reason": "import numpy,import scipy", "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731169394882, "lm_q2_score": 0.920789673717312, "lm_q1q2_score": 0.8864194652431391}}
{"text": "#!python\n# -*- coding: utf-8 -*-#\n\"\"\"\n:Title: Univariate Linear Regression.\n\n@author: Bhishan Poudel\n\n@date: Sep 22, 2017\n\n@email: bhishanpdl@gmail.com\n\nThe cost function is given by\n\n.. math::\n\n  J(w) = \\\\frac{1}{2N} \\sum_{n=1}^N (h(x_n,w) - t_n)^2\n\nMinimizing the cost function w.r.t. w gives two system of liner equations:\n\n.. math::\n\n    w_0N + w_1 \\sum_{n=1}^N x_n = \\sum_{n=1}^N t_n \\\\\\\\\\\\\\\\\n    w_0 \\sum_{n=1}^N x_n + w_1 \\sum_{n=1}^N x_n^2 = \\sum_{n=1}^N t_nx_n\n\nWe solve these normal equations and find the values w0 and w1.\n\"\"\"\n# Imports\nimport argparse\nimport sys\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport numpy.polynomial.polynomial as poly\n\n# checking\n# import statsmodels.api as sm # sm 0.8.0 gives FutureWarning\n\n\n\n\ndef read_data(infile):\n    X,t = np.loadtxt(infile,unpack=True)\n    return X,t\n\n\n#\ndef train(X, t):\n    \"\"\"Implement univariate linear regression to compute w = [w0, w1].\n\n    I solve system of linear equations from lecture 01\n\n    w0 N      + w1 sum_x  = sum_t\n\n    w0 sum_x  + w1 sum_xx = sum_tx\n\n    \"\"\"\n\n    # Use system of equations\n    N = len(t)\n    sum_x = sum(X)\n    sum_t = sum(t)\n\n    sum_xsp = sum(X*X)\n    sum_tx = sum(X*t)\n\n    w1 = (sum_t * sum_x - N * sum_tx) / (sum_x * sum_x - N * sum_xsp)\n    w0 = (sum_t - w1 * sum_x) / N\n\n    w = np.array([w0, w1])\n\n\n    # checking values using statsmodel library\n    # w = sm.OLS(t,sm.add_constant(X)).fit().params\n    # [-15682.27021631    115.41845202]\n\n    # params w\n    # print('y-intercept bias term w0 = {:.2f}'.format(w[0][0]))\n    # print('weight term           w1 = {:.2f}'.format(w[1][0]))\n\n    # plt.scatter(X,t)\n    # plt.plot(X, X*w[1] + w[0])\n    # plt.show()\n\n\n    return w\n\n\ndef compute_rmse(X,t,w):\n    \"\"\"Compute RMSE on dataset (X, t).\n\n    Note: cost function J is 1/2 of mean squared error.\n    RMSE is square root of mean squared error.\n\n    \"\"\"\n    h = X*w[1] + w[0]\n    rmse = np.sqrt(np.mean(( h - t )**2) )\n\n    # debug\n    # print('w[0] =', w[0])\n    # print('w[1] =', w[1])\n\n\n    # rmse = np.sqrt(((np.dot(X,w.T)- t)**2).mean())\n\n    return rmse\n\n\n#\ndef compute_cost(X, t, w):\n    \"\"\"Compute objective function on dataset (X, t).\"\"\"\n    h = X*w[1] + w[0]\n    J = 1/2 *  np.mean(( h - t )**2)\n    return J\n\ndef univariate_reg(fh_train, fh_test):\n    # Read the training and test data.\n    Xtrain, ttrain = read_data(fh_train)\n    Xtest, ttest = read_data(fh_test)\n\n\n    # Train model on training examples.\n    w = train(Xtrain, ttrain)\n\n    # train\n    E_rms_train_uni = compute_rmse(Xtrain, ttrain, w)\n    J_train_uni = compute_cost(Xtrain, ttrain, w)\n\n    # test\n    E_rms_test_uni = compute_rmse(Xtest, ttest, w)\n    J_test_uni = compute_cost(Xtest, ttest, w)\n\n    return E_rms_train_uni, J_train_uni, E_rms_test_uni, J_test_uni\n\n\ndef myplot(fh_train,fh_test,w):\n    # matplotlib customization\n    plt.style.use('ggplot')\n    fig, ax = plt.subplots()\n\n    # data\n    Xtrain, ttrain = read_data(fh_train)\n    Xtest, ttest = read_data(fh_test)\n    Xhyptest = Xtest * w[1] + w[0]\n\n\n    # plot with label, title\n    ax.scatter(Xtrain,ttrain,color='b',marker='o', label='Univariate Train')\n    ax.scatter(Xtest,ttest,c='limegreen', marker='^', label='Univariate Test')\n    ax.plot(Xtest,Xhyptest,'r--',label='Best Fit')\n\n    # set xlabel and ylabel to AxisObject\n    ax.set_xlabel('Floor Size (Square Feet)')\n    ax.set_ylabel('House Price (Dollar)')\n    ax.set_title('Univariate Regression')\n    ax.legend()\n    ax.grid(True)\n    plt.tight_layout()\n    plt.savefig('images/Univariate.png')\n    plt.show()\n\n##=======================================================================\n## Main Program\n##=======================================================================\ndef main():\n    \"\"\"Run main function.\"\"\"\n    parser = argparse.ArgumentParser('Univariate Exercise.')\n    parser.add_argument('-i', '--input_data_dir',\n                        type=str,\n                        default='../data/univariate',\n                        help='Directory for the univariate houses dataset.')\n    FLAGS, unparsed = parser.parse_known_args()\n\n    # Data file paths\n    fh_train = FLAGS.input_data_dir + \"/train.txt\"\n    fh_test  = FLAGS.input_data_dir + \"/test.txt\"\n\n    # Print weight vector\n    Xtrain, ttrain = read_data(fh_train)\n    w = train(Xtrain, ttrain)\n    print('Params Univariate: ', w, '\\n')\n\n    # Print RMSE and Cost\n    E_rms_train_uni, J_train_uni, E_rms_test_uni, J_test_uni = univariate_reg(fh_train, fh_test)\n\n    print(\"#\"*50)\n    print(\"Univariate Regression\")\n\n    # Print cost and RMSE on training data.\n    print('E_rms_train Univariate: %0.2e' % E_rms_train_uni)\n    print('J_train Univariate: %0.2e' % J_train_uni)\n\n    # Print cost and RMSE on test data.\n    print(\"\\n\")\n    print('E_rms_test Univariate: %0.2e' % E_rms_test_uni)\n    print('J_test Univariate: %0.2e' % J_test_uni)\n\n\n    # Plotting\n    myplot(fh_train, fh_test,w)\n\n\n\n\nif __name__ == \"__main__\":\n   import time\n\n   # Beginning time\n   program_begin_time = time.time()\n   begin_ctime        = time.ctime()\n\n   #  Run the main program\n   main()\n\n\n   # Print the time taken\n   program_end_time = time.time()\n   end_ctime        = time.ctime()\n   seconds          = program_end_time - program_begin_time\n   m, s             = divmod(seconds, 60)\n   h, m             = divmod(m, 60)\n   d, h             = divmod(h, 24)\n   print(\"\\n\\nBegin time: \", begin_ctime)\n   print(\"End   time: \", end_ctime, \"\\n\")\n   print(\"Time taken: {0: .0f} days, {1: .0f} hours, \\\n     {2: .0f} minutes, {3: f} seconds.\".format(d, h, m, s))\n", "meta": {"hexsha": "d12ea0e610374573c75a01415fc6103cfd966ed3", "size": 5535, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/univariate.py", "max_stars_repo_name": "bhishanpdl/sphinxdoc-test", "max_stars_repo_head_hexsha": "29d305964a7c5244a59115602274188902813256", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/univariate.py", "max_issues_repo_name": "bhishanpdl/sphinxdoc-test", "max_issues_repo_head_hexsha": "29d305964a7c5244a59115602274188902813256", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/univariate.py", "max_forks_repo_name": "bhishanpdl/sphinxdoc-test", "max_forks_repo_head_hexsha": "29d305964a7c5244a59115602274188902813256", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6, "max_line_length": 96, "alphanum_fraction": 0.593495935, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 1692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876287, "lm_q2_score": 0.9372107931567176, "lm_q1q2_score": 0.8864151643181643}}
{"text": "import numpy as np \n\n\nprint(\"\")\nprint(\"array0\")\nprint(\"____\")\narray0 = np.array(5)\nprint(array0.shape) # ()\nprint(array0.ndim) # 0\t\n\nprint(\"\")\nprint(\"array1\")\nprint(\"____\")\narray1 = np.array([1,2,3,4])\nprint(array1.shape) # (4, )\nprint(array1.ndim) # 1\t\n\n\nprint(\"\")\nprint(\"array2\")\nprint(\"____\")\narray2 = np.array([[1,2,3,4],[5, 6, 7, 8]])\nprint(array2.shape) # (2,4)\nprint(array2.ndim) # 2\n\nprint(array2[1,3]) # 8\n\n\n\nprint(\"\")\nprint(\"array5\")\nprint(\"____\")\narray5 = np.array([5, 6, 7, 8], ndmin = 5)\nprint(array5) # [[[[[5 6 7 8]]]]]\nprint(array5.shape) # (1,1,1,1,4)\nprint(array5.ndim) # 5\nprint(array5[0,0,0,0,2]) # 7\n\n\n\n\n\n\n\n\nprint(\"________________\")\nprint(\"________________\")\nprint(\"________________\")\nprint(\"________________\")\nprint(\"________________\")\nprint(\"---RESHAPING----\")\nprint(\"________________\")\nprint(\"________________\")\nprint(\"________________\")\nprint(\"________________\")\nprint(\"________________\")\n\n\n\n\n\narray = np.array([1,2,3,4,5,6,7,8,9,10,11,12])\n\n\nnewarr1 = array.reshape(4,3)\n\nprint(array)\n# [ 1  2  3  4  5  6  7  8  9 10 11 12]\nprint(newarr1)\n\"\"\"[[ 1  2  3]\n [ 4  5  6]\n [ 7  8  9]\n [10 11 12]]\n\n\"\"\"\nprint(newarr1.base) # It is a view\n# [ 1  2  3  4  5  6  7  8  9 10 11 12]\n\n\nnewarr2 = array.reshape(3,2,2)\n\nprint(newarr2)\n\"\"\"\n[[[ 1  2]\n  [ 3  4]]\n\n [[ 5  6]\n  [ 7  8]]\n\n [[ 9 10]\n  [11 12]]]\n\"\"\"\n\n\n\n\n\n\ntry:\n\tarray.reshape(8)\nexcept Exception as e:\n\tprint(\"Can not reshape it to 8 dim\")\n\n\n\n\n\nprint(\"________________\")\nprint(\"________________\")\nprint(\"Falttening Arrays\")\nprint(\"________________\")\nprint(\"________________\")\n\narray = np.array([[1,2,3,4],[5,6,7,8]])\n\nnewarr1 = array.reshape(-1)\n\nprint(newarr1)\n# [1 2 3 4 5 6 7 8]\n\n\n\n\n", "meta": {"hexsha": "950a974c241fe1ad437fd3965d25987f7b7bab69", "size": 1658, "ext": "py", "lang": "Python", "max_stars_repo_path": "learning/A)Intro/07_shape_and_reshape.py", "max_stars_repo_name": "OmarThinks/numpy-project", "max_stars_repo_head_hexsha": "c32da7767114081028b6ee5cab6c2fef5b392659", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "learning/A)Intro/07_shape_and_reshape.py", "max_issues_repo_name": "OmarThinks/numpy-project", "max_issues_repo_head_hexsha": "c32da7767114081028b6ee5cab6c2fef5b392659", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "learning/A)Intro/07_shape_and_reshape.py", "max_forks_repo_name": "OmarThinks/numpy-project", "max_forks_repo_head_hexsha": "c32da7767114081028b6ee5cab6c2fef5b392659", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.3709677419, "max_line_length": 46, "alphanum_fraction": 0.6091676719, "include": true, "reason": "import numpy", "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012640659995, "lm_q2_score": 0.9372107914029487, "lm_q1q2_score": 0.8864151512052046}}
{"text": "import numpy as np\n\n\ndef f(x):\n    return np.exp(-1*x**2)\n\n\ndef g(x):\n    return np.sin(x) / x\n\n\ndef romberg_algorithm(inte, func, tol, Max_iter=10):\n    \"\"\" Calculate the integral by Romberg Algorithm\n\n    Args:\n        inte: ndarray, the integrand interval\n        func: function boject, the integrand function\n        tol: double, the interation accurancy\n        Max_iter: int, the maximum number of iterations\n\n    Returns:\n        (T[-1], m):\n            T[-1]: double, the integral value by Romberg algorithm\n            m: the number of iterations\n    \"\"\"\n    # initial values \n    m = 0\n    T = [(inte[1] - inte[0]) * np.sum(func(inte)) / 2]\n    for i in range(1, Max_iter+1):\n        x_list = np.linspace(inte[0], inte[1], 2**i+1)\n        T.append(T[i-1]/2 + (x_list[1] - x_list[0]) * np.sum(func(x_list[1::2])))\n    T = np.array(T)\n\n    # iteration\n    m += 1\n    S = (4 * T[1:] - T[:-1]) / (4 - 1)\n    \n    # mark whether getting the given iteration accurancy\n    flag = 1\n    while np.fabs(S[-1] - T[-1] >= tol):\n        if m == Max_iter:\n            flag = 0\n            break\n        else:\n            m += 1\n            T = S\n            S = (4**m * T[1:] - T[:-1]) / (4**m - 1)\n    \n    if flag:\n        return (T[-1], m)\n    else:\n        reutnr (nan, Max_iter)\n\n\nif __name__ == '__main__':\n    # interval\n    inte = np.array([1e-32, 1])\n    # the first integral\n    value, n = romberg_algorithm(inte, f, 1e-6)\n    print(f\"The first integral's value is {value:.6f} by Romberg algorithm after {n} iterations\")\n    # the second integral\n    value, n = romberg_algorithm(inte, g, 1e-6)\n    print(f\"The second integral's value is {value:.6f} by Romberg algorithm after {n} iterations\")\n\n", "meta": {"hexsha": "fab15f030f5192cf762ca76d9fed38953047ddc8", "size": 1701, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumericalIntegral/Romberg_algorithm.py", "max_stars_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_stars_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NumericalIntegral/Romberg_algorithm.py", "max_issues_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_issues_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumericalIntegral/Romberg_algorithm.py", "max_forks_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_forks_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1692307692, "max_line_length": 98, "alphanum_fraction": 0.5467372134, "include": true, "reason": "import numpy", "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.9241418272911436, "lm_q1q2_score": 0.8863945959901249}}
{"text": "import numpy as np\n\n\ndef tanh(value, derivative=False):\n    \"\"\"\n    Tanh(x) function / derivative\n    :param value: ndarray -> value to activate\n    :param derivative: bool -> compute derivative\n    :return: ndarray -> activated ndarray\n    \"\"\"\n    if derivative:\n        return 1.0 - (value ** 2.0)\n    return np.tanh(value)\n\n\ndef sigmoid(value, derivative=False):\n    \"\"\"\n    Sigmoid(x) function / derivative\n    :param value: ndarray -> value to activate\n    :param derivative: bool -> compute derivative\n    :return: ndarray -> activated ndarray\n    \"\"\"\n    if derivative:\n        return value * (1.0 - value)\n    return 1.0 / (1.0 + np.exp(-value))\n\n\ndef softplus(value, derivative=False):\n    \"\"\"\n    Softplus(x) function / derivative\n    :param value: ndarray -> value to activate\n    :param derivative: bool -> compute derivative\n    :return: ndarray -> activated ndarray\n    \"\"\"\n    if derivative:\n        return 1.0 / (1.0 + np.exp(-value))\n    return np.log(1.0 + np.exp(value))\n\n\ndef softmax(value, derivative=False):\n    \"\"\"\n    Softmax(x) function / derivative\n    :param value: ndarray -> value to activate\n    :param derivative: bool -> compute derivative\n    :return: ndarray -> activated ndarray\n    \"\"\"\n    if derivative:\n        s = value.reshape(-1, 1)\n        return np.diagflat(s) - np.dot(s, s.T)\n    return np.exp(value) / np.sum(np.exp(value))\n\n\ndef stable_softmax(value, derivative=False):\n    \"\"\"\n    Softmax(x) function / derivative (softmax - except compute value in a numerically stable way)\n    :param value: ndarray -> value to activate\n    :param derivative: bool -> compute derivative\n    :return: ndarray -> activated ndarray\n    \"\"\"\n    if derivative:\n        s = value.reshape(-1, 1)\n        return np.diagflat(s) - np.dot(s, s.T)\n    shift_x = value - np.max(value)\n    return np.exp(shift_x)/np.sum(np.exp(shift_x))\n", "meta": {"hexsha": "a643245b6ad59e1b5705737019b8da15c88ca0dd", "size": 1856, "ext": "py", "lang": "Python", "max_stars_repo_path": "SciGen/Utils/ActivationFunctions.py", "max_stars_repo_name": "SamuelSchmidgall/SciGen", "max_stars_repo_head_hexsha": "d030b71ab87a034f9d59c5a53f501e96411dc0b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-07T12:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-07T12:54:25.000Z", "max_issues_repo_path": "SciGen/Utils/ActivationFunctions.py", "max_issues_repo_name": "SamuelSchmidgall/SciGen", "max_issues_repo_head_hexsha": "d030b71ab87a034f9d59c5a53f501e96411dc0b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SciGen/Utils/ActivationFunctions.py", "max_forks_repo_name": "SamuelSchmidgall/SciGen", "max_forks_repo_head_hexsha": "d030b71ab87a034f9d59c5a53f501e96411dc0b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5538461538, "max_line_length": 97, "alphanum_fraction": 0.6314655172, "include": true, "reason": "import numpy", "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799410139921, "lm_q2_score": 0.9196425229188077, "lm_q1q2_score": 0.8863330164926473}}
{"text": "'''\r\n    This script tries to use a random number generator\r\n    that samples a value from a uniform distribution \r\n    between (0,1) to estimate the value of pi.\r\n    \r\n    The intuition behind the function created is that the\r\n    ratio of the areas of a circle and a square having a \r\n    length equal to the circles diameter is pi/4.\r\n    \r\n    So if we are able to estimate the number of times a point in \r\n    2D space falls within a circle versus outside the circle bounded \r\n    by a square out of a number of trials, we will be able to estimate pi\r\n'''\r\n\r\nimport numpy as np\r\n\r\n\r\ndef estimate_pi(n_trials):\r\n    #counter variable to estimate the probability\r\n    ctr = 0\r\n    for i in range(n_trials):\r\n        #sample a 2d coordinate\r\n        x = np.random.random()\r\n        y = np.random.random()\r\n        #count the number of times the coordinate falls within the circle radius\r\n        if (x**2+y**2) < 1:\r\n           ctr+=1\r\n    #multiply by 4 to get pi since the probability is equal to pi/4           \r\n    return 4*(ctr/n_trials)\r\n\r\n\r\n", "meta": {"hexsha": "b0e626dddff0d35b42ef3fb13a99f43465b8f891", "size": 1052, "ext": "py", "lang": "Python", "max_stars_repo_path": "estimate_pi_using_random_function.py", "max_stars_repo_name": "vishwanathprudhivi/interview_solutions", "max_stars_repo_head_hexsha": "cb1ed7d1dd2cb091394a549f48774cac5ebc4e09", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "estimate_pi_using_random_function.py", "max_issues_repo_name": "vishwanathprudhivi/interview_solutions", "max_issues_repo_head_hexsha": "cb1ed7d1dd2cb091394a549f48774cac5ebc4e09", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "estimate_pi_using_random_function.py", "max_forks_repo_name": "vishwanathprudhivi/interview_solutions", "max_forks_repo_head_hexsha": "cb1ed7d1dd2cb091394a549f48774cac5ebc4e09", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.875, "max_line_length": 81, "alphanum_fraction": 0.6425855513, "include": true, "reason": "import numpy", "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668679067631, "lm_q2_score": 0.9032942158155877, "lm_q1q2_score": 0.8862823565300759}}
{"text": "import numpy as np\n\n# Write a function that takes as input two lists Y, P,\n# and returns the float corresponding to their cross-entropy.\n\n\ndef cross_entropy(Y, P):\n    Y = np.float_(Y)\n    P = np.float_(P)\n    return -1 * np.sum(Y * np.log(P) + (1 - Y) * np.log(1 - P))\n\n\nY = [1, 1, 0]\nP = [0.8, 0.7, 0.1]\nresult = cross_entropy(Y, P)\n\nprint(\n    \"The result of the above Y[1,1,0] and P[0.8, 0.7, 0.1] should be 0.69, and the calculated was \"+str(result))\n\nY = [0, 0, 1]\nP = [0.8, 0.7, 0.1]\nresult = cross_entropy(Y, P)\n\nprint(\n    \"The result of the above Y[0, 0, 1] and P[0.8, 0.7, 0.1] should be 5.12, and the calculated was \"+str(result))\n", "meta": {"hexsha": "285d282ab4da4edc013415591d500f5898a0fcaa", "size": 643, "ext": "py", "lang": "Python", "max_stars_repo_path": "lesson2-20/solution2_20.py", "max_stars_repo_name": "nmpegetis/udacity-facebook-pytorch", "max_stars_repo_head_hexsha": "36a9de03c71892836e184e58695143960c6a7d2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lesson2-20/solution2_20.py", "max_issues_repo_name": "nmpegetis/udacity-facebook-pytorch", "max_issues_repo_head_hexsha": "36a9de03c71892836e184e58695143960c6a7d2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lesson2-20/solution2_20.py", "max_forks_repo_name": "nmpegetis/udacity-facebook-pytorch", "max_forks_repo_head_hexsha": "36a9de03c71892836e184e58695143960c6a7d2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7307692308, "max_line_length": 114, "alphanum_fraction": 0.6049766719, "include": true, "reason": "import numpy", "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.972414716174355, "lm_q2_score": 0.9111797100118214, "lm_q1q2_score": 0.8860445590949765}}
{"text": "import sympy as sym\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# For all printing methods from Sympy\nsym.init_printing()\n\n\ndef show_example_number(index):\n    print(\"\\n\".join((\"\\n********\", f\"Example {index}\", \"********\\n\")))\n\n\n# %%\n#\n# Ex 1 : dy/dt = -5 y(t) with y(0) = 1\n# Plot solution from 0 to 20 with a step of 0.4\n#\nshow_example_number(1)\n\n# Variables\nt = sym.symbols(\"t\")\ny = sym.Function(\"y\")\n\n# Initial conditions\nics = {y(0): 1}\n\n# Build equation\nleft_hand = sym.Derivative(y(t), t)\nright_hand = -5 * y(t)\neq = sym.Eq(left_hand, right_hand)\nprint(\"Diff equation :\", sym.pretty(eq), sep=\"\\n\")\n\n# Solve equation dsolve(eq, func)\nsol = sym.dsolve(eq, y(t), ics=ics)\nprint(\"\\nSolution :\", sym.pretty(sol), sep=\"\\n\")\n\n# Lambdify : Transform into function, from string to numpy function\nfun_y = sym.lambdify(t, sol.rhs, modules=[\"numpy\"])\n\na = 0\nb = 20\nh = 0.4\nt = np.arange(a, b + h, h)\ny = fun_y(t)\n\n# Plot(y, t)\nplt.plot(t, y, color=\"b\")\nplt.xlim(a, b)\nplt.show()\n\n\n# %%\n#\n# Ex 2 : f'(x) = x + (f(x) / 5) with f(0) = -3\n#\nshow_example_number(2)\n\nx = sym.var(\"x\")\nf = sym.Function(\"f\")\n\n# Equation, then solving\neq2 = sym.Eq(sym.Derivative(f(x), x), x + f(x) / 5)\nics = {f(0): -3}\nsol2 = sym.dsolve(eq2, f(x), ics=ics).rhs\nprint(\"Solution :\", sym.pretty(sym.simplify(sol2)), sep=\"\\n\")\n\n\n# %%\n#\n# Ex 3 : f'(x) - f(x) = 0 with f(0) = A\n#\nshow_example_number(3)\n\n# Variables and initial condition\nf_3 = sym.Function(\"f_3\")\nx_3 = sym.var(\"x_3\")\nA = sym.var(\"A\")\nics = {f_3(0): A}\n\n# Not using sym.Eq, simply using an expression, assumed to be equal to 0\nsol3 = sym.dsolve(f_3(x_3).diff(x_3) - f_3(x_3), f_3(x_3), ics=ics)\n\nprint(\"Solution :\", sym.pretty(sol3), sep=\"\\n\")\n", "meta": {"hexsha": "f89b255281e0cbdcfb015d012a027ded28370e22", "size": 1684, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/sympy_snippets/ode_solving.py", "max_stars_repo_name": "IamPhytan/Cookbook", "max_stars_repo_head_hexsha": "a903f9098b0d2ddccdf343f740858731242bde97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/sympy_snippets/ode_solving.py", "max_issues_repo_name": "IamPhytan/Cookbook", "max_issues_repo_head_hexsha": "a903f9098b0d2ddccdf343f740858731242bde97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/sympy_snippets/ode_solving.py", "max_forks_repo_name": "IamPhytan/Cookbook", "max_forks_repo_head_hexsha": "a903f9098b0d2ddccdf343f740858731242bde97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0476190476, "max_line_length": 72, "alphanum_fraction": 0.6169833729, "include": true, "reason": "import numpy,import sympy", "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995733060719, "lm_q2_score": 0.9173026556293917, "lm_q1q2_score": 0.8860222436649561}}
{"text": "#Solutions to Policy Function Iteration Lab\n\nimport numpy as np\nimport scipy as sp\nfrom scipy import sparse\nfrom scipy.sparse import linalg\nimport math\nfrom matplotlib import pyplot as plt\nfrom scipy import linalg as la\n\n\ndef u(x):\n    return np.sqrt(x).flatten()\n    \ndef policyIter(beta, N, Wmax=1.):\n    \"\"\"\n    Solve the infinite horizon cake eating problem using policy function iteration.\n    Inputs:\n        beta -- float, the discount factor\n        N -- integer, size of discrete approximation of cake\n        Wmax -- total amount of cake available\n    Returns:\n        values -- converged value function (Numpy array of length N)\n        psi -- converged policy function (Numpy array of length N)\n    \"\"\"\n    W = np.linspace(0,Wmax,N) #state space vector\n    I = sparse.identity(N, format='csr')\n    \n    #precompute u(W-W') for all possible inputs\n    actions = np.tile(W, N).reshape((N,N)).T\n    actions = actions - actions.T\n    actions[actions<0] = 0\n    rewards = np.sqrt(actions)\n    rewards[np.triu_indices(N, k=1)] = -1e10 #pre-computed reward function\n    \n    psi_ind = np.arange(N)\n    rows = np.arange(0,N)\n    tol = 1.\n    while tol >= 1e-9:\n        columns = psi_ind\n        data = np.ones(N)\n        Q = sparse.coo_matrix((data,(rows,columns)),shape=(N,N))\n        Q = Q.tocsr()\n        values = linalg.spsolve(I-beta*Q, u(W-W[psi_ind])).reshape(1,N)\n        psi_ind1 = np.argmax(rewards + beta*values, axis=1)\n        tol = math.sqrt(((W[psi_ind] - W[psi_ind1])**2).sum())\n        psi_ind = psi_ind1\n    return values.flatten(), W[psi_ind]\n\ndef modPolicyIter(beta, N, Wmax=1., m=15):\n    \"\"\"\n    Solve the infinite horizon cake eating problem using modified policy function iteration.\n    Inputs:\n        beta -- float, the discount factor\n        N -- integer, size of discrete approximation of cake\n        Wmax -- total amount of cake available\n    Returns:\n        values -- converged value function (Numpy array of length N)\n        psi -- converged policy function (Numpy array of length N)\n    \"\"\"\n    W = np.linspace(0,Wmax,N) #state space vector\n    \n    #precompute u(W-W') for all possible inputs\n    actions = np.tile(W, N).reshape((N,N)).T\n    actions = actions - actions.T\n    actions[actions<0] = 0\n    rewards = np.sqrt(actions)\n    rewards[np.triu_indices(N, k=1)] = -1e10 #pre-computed reward function\n    \n    psi_ind = np.arange(N)\n    values = np.zeros(N)\n    tol = 1.\n    while tol >= 1e-9:\n        for i in xrange(m):\n            values = u(W - W[psi_ind]) + beta*values[psi_ind]\n        psi_ind1 = np.argmax(rewards + beta*values.reshape(1,N), axis=1)\n        tol = math.sqrt(((W[psi_ind] - W[psi_ind1])**2).sum())\n        psi_ind = psi_ind1\n    return values.flatten(), W[psi_ind]\n\n", "meta": {"hexsha": "f373f170f7b6ef88a0c7f2d402d77c96448b85ae", "size": 2733, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/PolicyFunctionIteration/policy_solutions.py", "max_stars_repo_name": "jessicaleete/numerical_computing", "max_stars_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-10-18T19:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:12:38.000Z", "max_issues_repo_path": "Labs/PolicyFunctionIteration/policy_solutions.py", "max_issues_repo_name": "jessicaleete/numerical_computing", "max_issues_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/PolicyFunctionIteration/policy_solutions.py", "max_forks_repo_name": "jessicaleete/numerical_computing", "max_forks_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-14T16:07:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-20T09:05:06.000Z", "avg_line_length": 33.7407407407, "max_line_length": 92, "alphanum_fraction": 0.6289791438, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.9294403979493139, "lm_q1q2_score": 0.8860123362772794}}
{"text": "import math\nimport numpy as np\n\nfrom hybridimages.convolution import convolve\n\ndef createHybridImage(lowImage: np.ndarray, lowSigma: float, highImage: np.ndarray, highSigma:float) -> np.ndarray:\n    \"\"\"\n    Create hybrid images by combining a low-pass and high-pass filtered pair.\n\n    :param lowImage: the image to low-pass filter (either greyscale shape=(rows, cols) or colour shape=(rows,cols,channels))\n    :type numpy.ndarray\n\n    :param lowSigma: the standard deviation of the Gaussian used for low-pass filtering lowImage\n    :type numpy.ndarray\n\n    :param highSigma: the standard deviation of the Gaussian used for low-pass filtering highImage before subtraction to create the high-pass filtered image\n    :type float\n\n    :returns returns the hybrid image created\n        by low-pass filtering lowImage with a Gaussian of s.d. lowSigma and combining it with a high-pass image created by subtracting highImage from highImage\n        convolved with a Gaussian of s.d. highSigma. The resultant image has the same size as the input images.\n    :rtype numpy.ndarray\n    \"\"\"\n    print(f'Attempting to merge {lowImage.shape} low frequency image with {highImage.shape} high frequency image')\n\n    low_sigma_kernel = makeGaussianKernel(lowSigma)\n    print(f'Applying convolution...')\n    low_pass_image = convolve(lowImage, low_sigma_kernel)\n    print(f'Low-pass filter successfully applied')\n    high_sigma_kernel = makeGaussianKernel(highSigma)\n    print(f'Applying convolution...')\n    low_pass_of_highimage = convolve(highImage, high_sigma_kernel)\n\n    print(f'Acquiring High-pass filtered image...')\n    high_pass_img = highImage - low_pass_of_highimage\n\n    # visualise high_pass image by adding 128 as high freq image is 0 mean with negative values\n    # show_image(high_pass_img + 128, grey=False)\n\n    hybrid_img = low_pass_image + high_pass_img\n    print(f'Hybrid image computed successfully')\n\n    return hybrid_img\n\ndef makeGaussianKernel(sigma: float) -> np.ndarray:\n    \"\"\"\n    Use this function to create a 2D Gaussian kernel with standard deviation sigma.\n    The kernel values should sum to 1.0, and the size should be floor(8*sigma+1) or \n    floor(8*sigma+1)+1 (whichever is odd).\n    \"\"\"\n    print('Initiating Gaussian kernel with sigma:', sigma)\n    size = np.floor(8 * sigma + 1).astype(int)\n    \n    # ensure size remains odd\n    if size % 2 == 0:\n        size += 1\n    print(f'Gaussian kernel dimensions: {size} x {size}')\n\n    # create range between -1 and +1\n    ax = np.linspace( -(size-1) / 2, (size-1) / 2, size)\n    # fill a size x size grid with above range\n    x, y = np.meshgrid(ax,ax)\n    \n    # construct kernel using Gauss\n    K = (1/(2 * math.pi * sigma**2)) * np.exp(-((x**2 + y**2)/(2 * sigma**2)))\n    return K", "meta": {"hexsha": "d4184620a2e1e54a89ffe84e153d5c916f2a4ccd", "size": 2751, "ext": "py", "lang": "Python", "max_stars_repo_path": "hybridimages/hybrid_image.py", "max_stars_repo_name": "samisnotinsane/HybridImages", "max_stars_repo_head_hexsha": "f41cdb5f5b7319c9b2b1375c626de0206e3d86e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hybridimages/hybrid_image.py", "max_issues_repo_name": "samisnotinsane/HybridImages", "max_issues_repo_head_hexsha": "f41cdb5f5b7319c9b2b1375c626de0206e3d86e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hybridimages/hybrid_image.py", "max_forks_repo_name": "samisnotinsane/HybridImages", "max_forks_repo_head_hexsha": "f41cdb5f5b7319c9b2b1375c626de0206e3d86e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6818181818, "max_line_length": 159, "alphanum_fraction": 0.7102871683, "include": true, "reason": "import numpy", "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812354689082, "lm_q2_score": 0.914900957313305, "lm_q1q2_score": 0.8859729193747451}}
{"text": "# import linear matrix equation solving method or function\nfrom numpy.linalg import solve\nfrom numpy import array\nfrom numpy import allclose\nfrom numpy import dot\n\n\"\"\"\n    Solve(a, b): Take two arguments a = Co-efficient matrix\n                                    b = dependent variable values\n\n    Return: Solution of the system ax = b, returned shape is \n            identical to b\n\n    Raises: LinAlgError: if a is a singular or not square \n\n    ** Broadcasting rules apply.\n    ** a must be square and of full-rank, i.e., all rows (or, equivalently, columns) must be           linearly independent; if either is not true, use lstsq for the least-squares best “solution”    of the system/equation.\n\"\"\"\n\n# Solve the system of equations 3 * x0 + x1 = 9 and x0 + 2 * x1 = 8\na = array([[3, 1], [1, 2]])\nb = array([9, 8])\n\nx = solve(a, b)\n\nprint(x)\n\n# Check the solution is okay or not!!!!!\nflag = allclose(dot(a, x), b)\n\nif flag:\n    print(\"Solution is correct.\")\nelse:\n    print(\"Solution is not correct.\")\n\n\n\n# Ref: https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.solve.html\n", "meta": {"hexsha": "43d3686a5f64bd3bcfd35a930b99327987d6c7e6", "size": 1094, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear-algebra/solution-of-linear-equation.py", "max_stars_repo_name": "Nahid-Hassan/code-snippets", "max_stars_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-29T04:09:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-18T13:33:36.000Z", "max_issues_repo_path": "linear-algebra/solution-of-linear-equation.py", "max_issues_repo_name": "Nahid-Hassan/code-snippets", "max_issues_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear-algebra/solution-of-linear-equation.py", "max_forks_repo_name": "Nahid-Hassan/code-snippets", "max_forks_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-26T04:55:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T04:55:55.000Z", "avg_line_length": 28.0512820513, "max_line_length": 222, "alphanum_fraction": 0.6535648995, "include": true, "reason": "from numpy", "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812345563904, "lm_q2_score": 0.9149009555730612, "lm_q1q2_score": 0.8859729168546622}}
{"text": "'''\nThe sum of the squares of the first ten natural numbers is,\n1**2 + 2**2 + ... + 10**2 == 385\n\nThe square of the sum of the first ten natural numbers is,\n(1 + 2 + ... + 10)**2 == 3025\n\nHence the difference between the sum of the squares of the \nfirst ten natural numbers and the square of the sum is:\n3025 - 385 = 2640\n\nFind the difference between the sum of the squares of the \nfirst one hundred natural numbers and the square of the sum.\n'''\n\nimport numpy as np\n\n# brute force\ndef sum_square_difference(n):\n  first_n = np.arange(1, n+1)\n  sum_square = np.dot(first_n, first_n)\n  square_sum = np.sum(first_n) ** 2\n  return square_sum - sum_square\n\n%timeit sum_square_difference(100)\n\n# using euler and pyramidal numbers\ndef sum_square_difference_2(n):\n  square_sum = ((n+1) * n / 2)**2\n  sum_square = n * (n+1) * (2*n+1) / 6\n  return square_sum - sum_square\n\n%timeit sum_square_difference_2(100)", "meta": {"hexsha": "834c8833e407ee9bdcb6764f5ac6294ef46c9ae4", "size": 899, "ext": "py", "lang": "Python", "max_stars_repo_path": "project-euler/python/06_sum-square-difference.py", "max_stars_repo_name": "jydiw/assorted-algorithms", "max_stars_repo_head_hexsha": "7af26520055104dcaf1ff21d94ece27d81c97918", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project-euler/python/06_sum-square-difference.py", "max_issues_repo_name": "jydiw/assorted-algorithms", "max_issues_repo_head_hexsha": "7af26520055104dcaf1ff21d94ece27d81c97918", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project-euler/python/06_sum-square-difference.py", "max_forks_repo_name": "jydiw/assorted-algorithms", "max_forks_repo_head_hexsha": "7af26520055104dcaf1ff21d94ece27d81c97918", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2424242424, "max_line_length": 60, "alphanum_fraction": 0.7041156841, "include": true, "reason": "import numpy", "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620619801095, "lm_q2_score": 0.9230391685381605, "lm_q1q2_score": 0.8858979756845907}}
{"text": "'''\nQ: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.\nFind the sum of all the primes below two million.\n'''\n\n'''\nfinal answer: 142913828922\n'''\n\nimport numpy as np\n\n# init constants\nupper_bound = 2000000\n\n\ndef list_of_primes(n):\n    # https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Pseudocode\n    numbers = [True for i in range(n)]\n    numbers[0] = numbers[1] = False\n\n    for p in range(1, int(n ** 0.5) + 1):\n        if (numbers[p] == True):\n            for i in range(p ** 2, n, p):\n                numbers[i] = False\n\n    primes = []\n    for p in range(len(numbers)):\n        if numbers[p]:\n            primes.append(p)\n\n    return np.array(primes,\n                    dtype=object)  # sum is too large so need to set as object (https://stackoverflow.com/a/22664510)\n\n\nif __name__ == '__main__':\n    print(\"The sum of all the primes below two million is \" + str(list_of_primes(upper_bound).sum()))\n", "meta": {"hexsha": "a9b4d98c08d0c50e8a02f8ceaec33c3c27447a35", "size": 914, "ext": "py", "lang": "Python", "max_stars_repo_path": "P0010-Summation_of_Primes/summation_of_primes.py", "max_stars_repo_name": "kabhari/Project_Euler", "max_stars_repo_head_hexsha": "e9aba54ae1e03aaf5311fdc615e85cf4c91b25e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "P0010-Summation_of_Primes/summation_of_primes.py", "max_issues_repo_name": "kabhari/Project_Euler", "max_issues_repo_head_hexsha": "e9aba54ae1e03aaf5311fdc615e85cf4c91b25e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P0010-Summation_of_Primes/summation_of_primes.py", "max_forks_repo_name": "kabhari/Project_Euler", "max_forks_repo_head_hexsha": "e9aba54ae1e03aaf5311fdc615e85cf4c91b25e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7027027027, "max_line_length": 117, "alphanum_fraction": 0.6028446389, "include": true, "reason": "import numpy", "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305297023093, "lm_q2_score": 0.9196425366837827, "lm_q1q2_score": 0.8858277677466954}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"HILL_CIPHER.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/drive/14sYOs_tSma_mGwx3ulAB48srtODas8DD\n\"\"\"\n\nimport numpy as np\nimport sympy\nimport string\nimport random\n\n# Define variables\ndimension = 3 # Your N\nkey = np.matrix([[17,17,5], [21,18,21], [2,2,19]]) # Your key\nmessage = 'paymoremoney' # Your message\n\nprint(\"Plain Text: \"+message)\nprint(\"Key Matrix: \")\nprint(key)\n# Generate the alphabet\nalphabet = string.ascii_lowercase\n\n# Encrypted message\nencryptedMessage = \"\"\n\n# Group message in vectors and generate crypted message\nfor index, i in enumerate(message): #PAYMOREMONEY \n    values = []\n    # Make bloc of N values\n    if index % dimension == 0:\n        for j in range(0, dimension):\n            if(index + j < len(message)):\n                values.append([alphabet.index(message[index + j])])\n                # print(f'if:{values}')\n            else:\n                values.append([random.randint(0,25)])\n                # print(f'else:{values}')\n        # Generate vectors and work with them\n        vector = np.matrix(values)\n        vector = key * vector\n        vector %= 26\n        for j in range(0, dimension):\n            encryptedMessage += alphabet[vector.item(j)]\n\n# Show the result\nprint(\"Encrypted message is: \"+ encryptedMessage.upper())\n\n#DECRYPTION\n\ndef modulo_multiplicative_inverse(A, M):\n\n    # This will iterate from 0 to M-1\n    for i in range(0, M):\n        # If we have our multiplicative inverse then return it\n        if (A*i) % M == 1:\n            return i\n    # If we didn't find the multiplicative inverse in the loop above\n    # then it doesn't exist for A under M\n    return -1\n\n\nmatrix= sympy.Matrix([[17,17,5], [21,18,21], [2,2,19]])\nadj=(matrix.adjugate()%26) #TO FIND ADJOINT OF KEY MATRIX\n\nmat=np.matrix([[17,17,5], [21,18,21], [2,2,19]])\n\ndet=(round(np.linalg.det(mat))%26) #TO FIND DETERMINENT\n\n# print(det)\n# print(adj)\n\nmult_inverse=modulo_multiplicative_inverse(det, 26)\n\n# print(mult_inverse)\n\ninv_m=(mult_inverse*adj)%26\nprint(\"inverse of Key Matrix: \")\nprint(inv_m)\n\ndecryptedMessage=\"\"\n\nfor index, i in enumerate(encryptedMessage): \n    values = []\n    if index % dimension == 0:\n        for j in range(0, dimension):\n            if(index + j < len(encryptedMessage)):\n                values.append([alphabet.index(encryptedMessage[index + j])])\n            else:\n                values.append([random.randint(0,25)])\n        vector = np.matrix(values)\n        vector = inv_m * vector\n        vector %= 26\n        for j in range(0, dimension):\n            decryptedMessage += alphabet[vector[j]]\n\n# Show the result\nprint(\"Decrypted Message: \"+ decryptedMessage)", "meta": {"hexsha": "b929fe6ee1a53771d2dbe51faff6782d74780af5", "size": 2711, "ext": "py", "lang": "Python", "max_stars_repo_path": "hill_cipher.py", "max_stars_repo_name": "singhvishvendra700/Hill_Cipher-Encryption_and_Decryption", "max_stars_repo_head_hexsha": "2704e46532b03ffa0c6489f8c1f3510210e39512", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T14:52:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T14:52:19.000Z", "max_issues_repo_path": "hill_cipher.py", "max_issues_repo_name": "singhvishvendra700/Hill_Cipher-Encryption_and_Decryption", "max_issues_repo_head_hexsha": "2704e46532b03ffa0c6489f8c1f3510210e39512", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hill_cipher.py", "max_forks_repo_name": "singhvishvendra700/Hill_Cipher-Encryption_and_Decryption", "max_forks_repo_head_hexsha": "2704e46532b03ffa0c6489f8c1f3510210e39512", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.11, "max_line_length": 77, "alphanum_fraction": 0.6322390262, "include": true, "reason": "import numpy,import sympy", "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305328688784, "lm_q2_score": 0.9196425273236, "lm_q1q2_score": 0.8858277616427932}}
{"text": "# GRADED FUNCTION\nimport numpy as np\nimport numpy.linalg as la\n\nverySmallNumber = 1e-14 # That's 1×10⁻¹⁴ = 0.00000000000001\n\n# Our first function will perform the Gram-Schmidt procedure for 4 basis vectors.\n# We'll take this list of vectors as the columns of a matrix, A.\n# We'll then go through the vectors one at a time and set them to be orthogonal\n# to all the vectors that came before it. Before normalising.\n# Follow the instructions inside the function at each comment.\n# You will be told where to add code to complete the function.\ndef gsBasis4(A) :\n    B = np.array(A, dtype=np.float_) # Make B as a copy of A, since we're going to alter it's values.\n    # The zeroth column is easy, since it has no other vectors to make it normal to.\n    # All that needs to be done is to normalise it. I.e. divide by its modulus, or norm.\n    B[:, 0] = B[:, 0] / la.norm(B[:, 0])\n    # For the first column, we need to subtract any overlap with our new zeroth vector.\n    B[:, 1] = B[:, 1] - B[:, 1] @ B[:, 0] * B[:, 0]\n    # If there's anything left after that subtraction, then B[:, 1] is linearly independant of B[:, 0]\n    # If this is the case, we can normalise it. Otherwise we'll set that vector to zero.\n    if la.norm(B[:, 1]) > verySmallNumber :\n        B[:, 1] = B[:, 1] / la.norm(B[:, 1])\n    else :\n        B[:, 1] = np.zeros_like(B[:, 1])\n    B[:,2] = B[:,2] - B[:, 2] @ B[:, 0] * B[:, 0]\n    B[:,2] = B[:,2] - B[:, 2] @ B[:, 1] * B[:, 1]\n    if la.norm(B[:,2]) > verySmallNumber :\n        B[:, 2] = B[:, 2] / la.norm(B[:, 2])\n    else :\n        B[:, 2] = np.zeros_like(B[:, 2])\n    B[:,3] = B[:,3] - B[:, 3] @ B[:, 0] * B[:, 0]\n    B[:,3] = B[:,3] - B[:, 3] @ B[:, 1] * B[:, 1]\n    B[:,3] = B[:,3] - B[:, 3] @ B[:, 2] * B[:, 2]\n    if la.norm(B[:,3]) > verySmallNumber :\n        B[:, 3] = B[:, 3] / la.norm(B[:, 3])  \n    else :\n        B[:, 3] = np.zeros_like(B[:, 3])\n    \n    \n        \n    # Now we need to repeat the process for column 2.\n    # Insert two lines of code, the first to subtract the overlap with the zeroth vector,\n    # and the second to subtract the overlap with the first.\n    \n    \n    # Again we'll need to normalise our new vector.\n    # Copy and adapt the normalisation fragment from above to column 2.\n    \n    \n    \n    \n    # Finally, column three:\n    # Insert code to subtract the overlap with the first three vectors.\n    \n    \n    \n    # Now normalise if possible\n    \n    \n    \n    \n    # Finally, we return the result:\n    return B\n\n# The second part of this exercise will generalise the procedure.\n# Previously, we could only have four vectors, and there was a lot of repeating in the code.\n# We'll use a for-loop here to iterate the process for each vector.\ndef gsBasis(A) :\n    B = np.array(A, dtype=np.float_) # Make B as a copy of A, since we're going to alter it's values.\n    # Loop over all vectors, starting with zero, label them with i\n    for i in range(B.shape[1]) :\n        # Inside that loop, loop over all previous vectors, j, to subtract.\n        for j in range(i) :\n            # Complete the code to subtract the overlap with previous vectors.\n            # you'll need the current vector B[:, i] and a previous vector B[:, j]\n            B[:, i] = B[:,i] - B[:,i] @ B[:,j] * B[:,j]\n        # Next insert code to do the normalisation test for B[:, i]\n        if la.norm(B[:, i]) > verySmallNumber :\n            B[:, i] = B[:, i] / la.norm(B[:, i])  \n        else :\n            B[:, i] = np.zeros_like(B[:, i])\n            \n            \n            \n        \n            \n    # Finally, we return the result:\n    return B\n\n# This function uses the Gram-schmidt process to calculate the dimension\n# spanned by a list of vectors.\n# Since each vector is normalised to one, or is zero,\n# the sum of all the norms will be the dimension.\ndef dimensions(A) :\n    return np.sum(la.norm(gsBasis(A), axis=0))\n\n", "meta": {"hexsha": "6b44bba63eedc057f471313dbb42bb72c792734c", "size": 3861, "ext": "py", "lang": "Python", "max_stars_repo_path": "gramschmidtprocess.py", "max_stars_repo_name": "MichelML/Mathematics-for-Machine-Learning-Linear-Algebra", "max_stars_repo_head_hexsha": "c0deedb024ffb0360328fa15473c989db317c9b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2018-04-29T10:27:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T15:15:44.000Z", "max_issues_repo_path": "gramschmidtprocess.py", "max_issues_repo_name": "MichelML/Mathematics-for-Machine-Learning-Linear-Algebra", "max_issues_repo_head_hexsha": "c0deedb024ffb0360328fa15473c989db317c9b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-15T12:16:54.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-15T12:16:54.000Z", "max_forks_repo_path": "gramschmidtprocess.py", "max_forks_repo_name": "MichelML/Mathematics-for-Machine-Learning-Linear-Algebra", "max_forks_repo_head_hexsha": "c0deedb024ffb0360328fa15473c989db317c9b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2018-07-21T15:42:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T14:34:04.000Z", "avg_line_length": 39.3979591837, "max_line_length": 102, "alphanum_fraction": 0.5824915825, "include": true, "reason": "import numpy", "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885904, "lm_q2_score": 0.9241418246795768, "lm_q1q2_score": 0.8858248043206925}}
{"text": "# Graphical Solutions \n## Introduction to Linear Programming\n\n#Import some required packages. \nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nGraphical solution is limited to linear programming models containing only two decision variables (can be used with three variables but only with great difficulty).\n\nGraphical methods provide a picture of how a solution for a linear programming problem is obtained.\n\n\n## Product mix problem - Farmers Fields\nProblem: How much of each brand to purchase to minimize total cost of fertilizer given following data ?\n\nProduct resource requirements and unit profit:\nTwo brands of fertilizer available – Super-gro, Crop-quick.\nField requires at least 16 pounds of nitrogen and 24 pounds of phosphate.\nSuper-gro costs $6 per bag, Crop-quick $3 per bag.\n\n\nDecision Variables:\n\n$x_{1}$ = number of bags of Super-gro\n\n$x_{2}$ = number of bags of Crop-quick\n\n\nCost (Z) minimization \n\nZ = 6$x_{1}$ + 3$x_{2}$\n\n\nNitrogen Constraint\n\n2$x_{1}$ + 4$x_{2}$ >= 16\n\nPhosphate Constraint Check\n\n4$x_{1}$ + 3$x_{2}$ >= 24\n\nNon-negativitiy Constraint\n\n$x_{1}$ > 0\n\n$x_{2}$ > 0\n\n\n\n#Create an Array X2 from 0 to 60, and it should have a length of 61.\nx2 = np.linspace(0, 14, 15) \n\n#This is the same as starting your Excel Spreadsheet with incrementing X2\nx2\n\n#Nitrogen Constraint\n# 2x1  + 4x2  >= 16\n# x1= 8-2x2\nc1 =  8 - 2*x2\nc1\n\n#Clay (Physicial Resource) Constraint Check\n#4x1 + 3x2 <= 120\n#4x1  + 3 x2  >= 24\nc2  = (24 - 3*x2)/4\nc2\n\n#Calculate the maximim value of X1 you can make per the 2 different constraints.\n\nct = np.maximum(c1,c2)\nct\n\nct=ct[0:9] #removes negative values\nct\n\n#Calculate the minimum cost from ct\n#Z = 6 x1  + 3 x2\ncost = 6*ct+3*x2[0:9]#Shape of array must be the same.\ncost\n\n# Make plot for the Nitrogen Constraint\n\nplt.plot(c1, x2, label=r'2$x_{1}$ + 4$x_{2}$ >= 16')\nplt.xlim((0, 14))\nplt.ylim((0, 14))\nplt.xlabel(r'$x_{1}$') #Latex way of writing X subscript 1 (See Markdown)\nplt.ylabel(r'$x_{2}$') #Latex way of writing X subscript 1 (See Markdown)\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n#plt.fill_between(x2,c1, color='grey', alpha=0.5)\n\n\n#Graph Phosphate Constraint Check\n\n\nplt.plot(c2, x2, label=r'4$x_{1}$ + 3$x_{2}$ >= 24')\nplt.xlim((0, 14))\nplt.ylim((0, 14))\nplt.xlabel(r'$x_{1}$') #Latex way of writing X subscript 1 (See Markdown)\nplt.ylabel(r'$x_{2}$') #Latex way of writing X subscript 1 (See Markdown)\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n#plt.fill_between(c2, x2, color='grey', alpha=0.5)\n\n# Make plot for the combined constraints.\nplt.plot(c1, x2, label=r'2$x_{1}$ + 4$x_{2}$ >= 16')\nplt.plot(c2, x2, label=r'4$x_{1}$ + 3$x_{2}$ >= 24')\n#plt.plot(ct, x2, label=r'min(x$x_{1}$)')\nplt.xlim((0, 14))\nplt.ylim((0, 14))\nplt.xlabel(r'$x_{1}$') #Latex way of writing X subscript 1 (See Markdown)\nplt.ylabel(r'$x_{2}$') #Latex way of writing X subscript 1 (See Markdown)\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n#plt.fill_between(ct, x2,  color='grey', alpha=0.5)\n\nOur solution must be in in lies somewhere in the grey feasible region in the graph above. However, according to the fundamental theorum of Linear programming we know it is at a vertex. \n\n\"In mathematical optimization, the fundamental theorem of linear programming states, in a weak formulation, that the maxima and minima of a linear function over a convex polygonal region occur at the region's corners. Further, if an extreme value occurs at two corners, then it must also occur everywhere on the line segment between them.\"\n\n- [Wikipedia](https://en.wikipedia.org/wiki/Fundamental_theorem_of_linear_programming)\n\n#This returns the index position of the maximum value\nmin_value = np.argmin(cost)\nmin_value\n\n#Calculate The min cost that is made. \nprofit_answer=cost[min_value]\nprofit_answer\n\n# Verify all constraints are integers\nx2_answer = x2[min_value]\nx2_answer\n\n# Verify all constraints are integers\nct_answer = ct[min_value]\nct_answer\n\n", "meta": {"hexsha": "7a354a1e616fd002e502d49d2790dd949722f83f", "size": 3953, "ext": "py", "lang": "Python", "max_stars_repo_path": "site/_build/jupyter_execute/notebooks/graphical-min.py", "max_stars_repo_name": "rpi-techfundamentals/website_fall_2020_qm", "max_stars_repo_head_hexsha": "517b24801286140af5f1e10ee9099cf5d0a28b7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "site/_build/jupyter_execute/notebooks/graphical-min.py", "max_issues_repo_name": "rpi-techfundamentals/website_fall_2020_qm", "max_issues_repo_head_hexsha": "517b24801286140af5f1e10ee9099cf5d0a28b7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "site/_build/jupyter_execute/notebooks/graphical-min.py", "max_forks_repo_name": "rpi-techfundamentals/website_fall_2020_qm", "max_forks_repo_head_hexsha": "517b24801286140af5f1e10ee9099cf5d0a28b7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8540145985, "max_line_length": 339, "alphanum_fraction": 0.7229951935, "include": true, "reason": "import numpy", "num_tokens": 1193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321806, "lm_q2_score": 0.9334308050109897, "lm_q1q2_score": 0.8857486074279027}}
{"text": "from typing import Union, Dict, Callable, Tuple\n\nimport numpy as np\n\n\ndef sigmoid(X: Union[float, np.array]) -> Union[float, np.array]:\n    \"\"\"\n    Sigmoid activation function σ(X) = 1 / /1 + e^(-x))\n    :param X: A scalar or numpy array of any size.\n    :return: σ(X) = 1 / (1 + e^(-x))\n    \"\"\"\n    return 1 / (1 + np.exp(-X))\n\n\ndef sigmoid_prime(X: Union[float, np.array]):\n    \"\"\"\n    Derivative of the sigmoid function σ'(X) = σ(X) * (1 - σ(X))\n    :param X: A scalar or numpy array of any size\n    :return: σ'(X) = σ(X) * (1 - σ(X))\n    \"\"\"\n    s = sigmoid(X)\n    sigma_prime = s * (1 - s)\n    return sigma_prime\n\n\ndef relu(x: Union[float, np.array]) -> Union[float, np.array]:\n    \"\"\"\n    ReLU activation function implementation relu(X) = max(0, X)\n    :param x: A scalar or numpy array of any size\n    :return: relu(X) = max(0, x)\n    \"\"\"\n    return np.maximum(0, x)\n\n\ndef relu_prime(X: Union[float, np.array]):\n    \"\"\"\n    Derivative of the relu function relu'(X) = 0 if x <= 0, 1 if x > 0\n    :param X: A scalar or numpy array of any size\n    :return: σ'(X) = σ(X) * (1 - σ(X))\n    \"\"\"\n    relu_prime = X > 0\n    return relu_prime\n\n\ndef tanh(X: Union[float, np.array]) -> Union[float, np.array]:\n    \"\"\"\n    tanh activation function tanh(X) = (e^x - e^(-x)) / (e^x + e^(-x))\n    :param X: A scalar or numpy array of any size\n    :return: tanh(X) = (e^X - e^(-X)) / (e^X + e^(-X))\n    \"\"\"\n    e_x = np.exp(X)\n    e_minus_x = np.exp(-X)\n    return (e_x - e_minus_x) / (e_x + e_minus_x)\n\n\ndef tanh_prime(X: Union[float, np.array]):\n    \"\"\"\n    Derivative of the tanh function tanh'(X) = 1 - (tanh(X))^2\n    :param X: A scalar or numpy array of any size\n    :return: tanh'(X) = 1 - (tanh(X))^2\n    \"\"\"\n    t = tanh(X)\n    tanh_prime = 1 - t * t\n    return tanh_prime\n\n\n# The dictionary of activation functions, to be able to retrieve them by name\nactivation_functions: Dict[str, Tuple[Callable, Callable]] = {\n    sigmoid.__name__: (sigmoid, sigmoid_prime),\n    relu.__name__: (relu, relu_prime),\n    tanh.__name__: (tanh, tanh_prime)\n}\n\n\nclass UnknownActivationFunctionName(Exception):\n    def __init__(self, activation_function_name: str):\n        message = \"Unknown activation function name {}\".format(activation_function_name)\n        super().__init__(message)\n\n\ndef get_activation_function(activation_function_name: str):\n    \"\"\"\n    Given the name of an activation function, retrieve the corresponding function and its derivative\n    :param cost_function_name: the name of the cost function\n    :return: the corresponding activation function and its derivative\n    \"\"\"\n    try:\n        return activation_functions[activation_function_name]\n    except KeyError:\n        raise UnknownActivationFunctionName(activation_function_name)\n", "meta": {"hexsha": "fbd3a2f82763aa6b960d65c69cfc5715ebbede50", "size": 2742, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/docknet/function/activation_function.py", "max_stars_repo_name": "Accenture/Docknet", "max_stars_repo_head_hexsha": "e81eb0c5aefd080ebeebf369d41f8d3fa85ab917", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-29T08:58:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T11:38:18.000Z", "max_issues_repo_path": "src/docknet/function/activation_function.py", "max_issues_repo_name": "jeekim/Docknet", "max_issues_repo_head_hexsha": "eb3cad13701471a7aaeea1d573bc5608855bab52", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-07T17:58:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T17:58:59.000Z", "max_forks_repo_path": "src/docknet/function/activation_function.py", "max_forks_repo_name": "jeekim/Docknet", "max_forks_repo_head_hexsha": "eb3cad13701471a7aaeea1d573bc5608855bab52", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-06-29T08:58:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-22T11:23:11.000Z", "avg_line_length": 30.1318681319, "max_line_length": 100, "alphanum_fraction": 0.6280087527, "include": true, "reason": "import numpy", "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211561049158, "lm_q2_score": 0.9086178895092415, "lm_q1q2_score": 0.8857399415090075}}
{"text": "# inner\n# The inner tool returns the inner product of two arrays.\n\n# import numpy\n# A = numpy.array([0, 1])\n# B = numpy.array([3, 4])\n# print numpy.inner(A, B)     #Output : 4\n\n# outer\n# The outer tool returns the outer product of two arrays.\n\n# import numpy\n# A = numpy.array([0, 1])\n# B = numpy.array([3, 4])\n# print numpy.outer(A, B)     #Output : [[0 0]\n#                             #          [3 4]]\n\n# Task :\n# You are given two arrays:\n# and .\n# Your task is to compute their inner and outer product.\n\nimport numpy as np\n\na = list(map(int, raw_input().split()))\nb = list(map(int, raw_input().split()))\na = np.array(a)\nb = np.array(b)\n\nprint(np.inner(a, b))\nprint(np.outer(a, b))\n\n# Sample Input\n# 0 1\n# 2 3\n\n# Sample Output\n# 3\n# [[0 0]\n#  [2 3]]\n", "meta": {"hexsha": "6409ae890b3afa95072bf9f6c3b4de778403ae1c", "size": 755, "ext": "py", "lang": "Python", "max_stars_repo_path": "NEW_PRAC/HackerRank/Python/InnerAndOuter.py", "max_stars_repo_name": "side-projects-42/INTERVIEW-PREP-COMPLETE", "max_stars_repo_head_hexsha": "627a3315cee4bbc38a0e81c256f27f928eac2d63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-03-11T00:25:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T00:19:23.000Z", "max_issues_repo_path": "NEW_PRAC/HackerRank/Python/InnerAndOuter.py", "max_issues_repo_name": "side-projects-42/INTERVIEW-PREP-COMPLETE", "max_issues_repo_head_hexsha": "627a3315cee4bbc38a0e81c256f27f928eac2d63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 160, "max_issues_repo_issues_event_min_datetime": "2021-04-26T19:04:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T20:18:37.000Z", "max_forks_repo_path": "NEW_PRAC/HackerRank/Python/InnerAndOuter.py", "max_forks_repo_name": "side-projects-42/INTERVIEW-PREP-COMPLETE", "max_forks_repo_head_hexsha": "627a3315cee4bbc38a0e81c256f27f928eac2d63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-04-26T19:43:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T08:36:29.000Z", "avg_line_length": 18.4146341463, "max_line_length": 57, "alphanum_fraction": 0.5814569536, "include": true, "reason": "import numpy", "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288128, "lm_q2_score": 0.925229957607466, "lm_q1q2_score": 0.8857021050934055}}
{"text": "from __future__ import annotations\n\nfrom typing import Iterable, Union\n\nimport numpy as np\n\nVector = Union[Iterable[float], Iterable[int], np.ndarray]\nVectorOut = Union[np.float64, int, float]\n\n\ndef euclidean_distance(vector_1: Vector, vector_2: Vector) -> VectorOut:\n    \"\"\"\n    Calculate the distance between the two endpoints of two vectors.\n    A vector is defined as a list, tuple, or numpy 1D array.\n    >>> euclidean_distance((0, 0), (2, 2))\n    2.8284271247461903\n    >>> euclidean_distance(np.array([0, 0, 0]), np.array([2, 2, 2]))\n    3.4641016151377544\n    >>> euclidean_distance(np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8]))\n    8.0\n    >>> euclidean_distance([1, 2, 3, 4], [5, 6, 7, 8])\n    8.0\n    \"\"\"\n    return np.sqrt(np.sum((np.asarray(vector_1) - np.asarray(vector_2)) ** 2))\n\n\ndef euclidean_distance_no_np(vector_1: Vector, vector_2: Vector) -> VectorOut:\n    \"\"\"\n    Calculate the distance between the two endpoints of two vectors without numpy.\n    A vector is defined as a list, tuple, or numpy 1D array.\n    >>> euclidean_distance_no_np((0, 0), (2, 2))\n    2.8284271247461903\n    >>> euclidean_distance_no_np([1, 2, 3, 4], [5, 6, 7, 8])\n    8.0\n    \"\"\"\n    return sum((v1 - v2) ** 2 for v1, v2 in zip(vector_1, vector_2)) ** (1 / 2)\n\n\nif __name__ == \"__main__\":\n\n    def benchmark() -> None:\n        \"\"\"\n        Benchmarks\n        \"\"\"\n        from timeit import timeit\n\n        print(\"Without Numpy\")\n        print(\n            timeit(\n                \"euclidean_distance_no_np([1, 2, 3], [4, 5, 6])\",\n                number=10000,\n                globals=globals(),\n            )\n        )\n        print(\"With Numpy\")\n        print(\n            timeit(\n                \"euclidean_distance([1, 2, 3], [4, 5, 6])\",\n                number=10000,\n                globals=globals(),\n            )\n        )\n\n    benchmark()\n", "meta": {"hexsha": "a2078161374b88db2c186b918b6a74c48124433e", "size": 1846, "ext": "py", "lang": "Python", "max_stars_repo_path": "maths/euclidean_distance.py", "max_stars_repo_name": "NavpreetDevpuri/Python", "max_stars_repo_head_hexsha": "7ef5ae66d777e8ed702993c6aa9270e0669cb0c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 145614, "max_stars_repo_stars_event_min_datetime": "2016-07-21T05:40:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:17:22.000Z", "max_issues_repo_path": "maths/euclidean_distance.py", "max_issues_repo_name": "NavpreetDevpuri/Python", "max_issues_repo_head_hexsha": "7ef5ae66d777e8ed702993c6aa9270e0669cb0c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3987, "max_issues_repo_issues_event_min_datetime": "2016-07-28T17:31:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:07:46.000Z", "max_forks_repo_path": "maths/euclidean_distance.py", "max_forks_repo_name": "NavpreetDevpuri/Python", "max_forks_repo_head_hexsha": "7ef5ae66d777e8ed702993c6aa9270e0669cb0c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 40014, "max_forks_repo_forks_event_min_datetime": "2016-07-26T15:14:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T22:23:03.000Z", "avg_line_length": 28.4, "max_line_length": 82, "alphanum_fraction": 0.5671722644, "include": true, "reason": "import numpy", "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.9252299607000298, "lm_q1q2_score": 0.8857021001599886}}
{"text": "import numpy as np\n\ndef pseudo(A):\n    # Check if matrix A is injective.\n    if np.linalg.det(A.T @ A) < 1e-9:\n        print(\"the given matrix is not injective.\")\n        return\n\n    # Return pseudo-inverse (See lecture notes page 155)\n    print(\"the given matrix is injective.\")\n    return np.linalg.inv(A.T @ A) @ A.T\n\n# A = np.array([[1, 2, 0], [2, 4, 0], [1, 0, 3]]) # not injective\nA = np.array([[1, 2, 0], [1, 4, 2], [1, 0, 3]]) # injective\nprint(pseudo(A))\n\nA = np.array([[1, 0], [2, 1], [0, 2]])\nb = np.array([1, 0, 1]).reshape((3, 1))\nx = pseudo(A) @ b\nprint(\"\\nOwn implementation:\")\nprint(x)\n\nprint(\"\\nNumpy implementation:\")\nprint(np.linalg.lstsq(a = A, b = b, rcond=None)[0])", "meta": {"hexsha": "08fff40a243e18b2db022a1eb7a1f3ab13e2b039", "size": 687, "ext": "py", "lang": "Python", "max_stars_repo_path": "ue/ue_05/problem_6.py", "max_stars_repo_name": "VoxelPi/compm", "max_stars_repo_head_hexsha": "745019d4e0d156910f19ed9168949f150356a349", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ue/ue_05/problem_6.py", "max_issues_repo_name": "VoxelPi/compm", "max_issues_repo_head_hexsha": "745019d4e0d156910f19ed9168949f150356a349", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-03-09T22:54:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:33:49.000Z", "max_forks_repo_path": "ue/ue_05/problem_6.py", "max_forks_repo_name": "VoxelPi/compm", "max_forks_repo_head_hexsha": "745019d4e0d156910f19ed9168949f150356a349", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.625, "max_line_length": 65, "alphanum_fraction": 0.577874818, "include": true, "reason": "import numpy", "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357628519819, "lm_q2_score": 0.9046505402422644, "lm_q1q2_score": 0.8856852317805429}}
{"text": "import numpy as np\nimport sys\n\ntry:\n    n=int(sys.argv[1])\nexcept IndexError:\n    n=100\nexcept ValueError:\n    try:\n        n=int(sys.argv[2])\n    except IndexError:\n        n=100\n\nsilent=\"-s\" in sys.argv\n\nN=4\n\nbase=list(range(N))\n\ndef init():\n    '''\n    Function that initializes monty hall problem simulation.\n\n    returns a list with randomly ordered door's content.\n    '''\n    l=[]\n    for i in range(N-1):\n        l.append(\"goat\")\n    l.append(\"car\")\n    return np.random.permutation(l)\n\ndef first_choice():\n    '''\n    Emulates the initial choice.\n    '''\n    return np.random.choice(base)\n\ndef reveal_goat(doors_list,initial_choice):\n    '''\n    In answer to the initial choice, the machine reveals a door (index of) where is a goat, randomly.\n    '''\n    possible_indexes=[]\n    for i in base:\n        if( i!=initial_choice and doors_list[i]==\"goat\" ):\n            # It is not fair to reveal the first goat. Here are considered all scenarios.\n            possible_indexes.append(i)\n    return np.random.choice(possible_indexes)\n\n\ndef second_choice(change,initial_choice,goat_index):\n    '''\n    Emulates the second choice, according to the rules of the game.\n    '''\n    if(change):\n        choices=[]\n        for i in base:\n            if( i!=goat_index and i!=initial_choice ):\n                choices.append(i)\n        return np.random.choice(choices)\n    else:\n        return initial_choice\n\ndef MontyHall(change_arg):\n    '''\n    Simulates a Monty Hall game, with the changing choice given by the boolean \"change\".\n\n    Returns True if win the car, False if win a goat.\n    '''\n    doors=init()\n    n1=first_choice()\n    goat=reveal_goat(doors,n1)\n    n2=second_choice(change_arg,n1,goat)\n    if doors[n2]==\"goat\":\n        return False\n    if doors[n2]==\"car\":\n        return True\n\n# Set up of several simulations\n\n# Change option, n games\n\nCH_win=0\nCH_lose=0\n\nfor i in range(n):\n    result=MontyHall(True)\n    if(result):\n        CH_win+=1\n    else:\n        CH_lose+=1\n\n# Non-change option, n games\n\nN_win=0\nN_lose=0\n\nfor i in range(n):\n    result=MontyHall(False)\n    if(result):\n        N_win+=1\n    else:\n        N_lose+=1\n\n# Print the results:\n\nif silent:\n    print(round(N_win/n*100,3),round(CH_win/n*100,3))\nelse:\n    print(\"There was a \",round(N_win/n*100,3),\"%  of probabilities to win if one chooses not to change the selected door\")\n    print(\"There was a \",round(CH_win/n*100,3),\"%  of probabilities to win if one chooses to change the selected door\")\n", "meta": {"hexsha": "6823646e7329ff8796e6496522fd4a8864024a98", "size": 2479, "ext": "py", "lang": "Python", "max_stars_repo_path": "SantiagoHenao_MontyHall.py", "max_stars_repo_name": "santiagohenao/SantiagoHenao_hw13", "max_stars_repo_head_hexsha": "8c493f73540ef4216d4a3bf11b5af65bfd5a6614", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SantiagoHenao_MontyHall.py", "max_issues_repo_name": "santiagohenao/SantiagoHenao_hw13", "max_issues_repo_head_hexsha": "8c493f73540ef4216d4a3bf11b5af65bfd5a6614", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SantiagoHenao_MontyHall.py", "max_forks_repo_name": "santiagohenao/SantiagoHenao_hw13", "max_forks_repo_head_hexsha": "8c493f73540ef4216d4a3bf11b5af65bfd5a6614", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3333333333, "max_line_length": 122, "alphanum_fraction": 0.6317063332, "include": true, "reason": "import numpy", "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660923657093, "lm_q2_score": 0.9284087936225136, "lm_q1q2_score": 0.8856705089700315}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 17 02:09:53 2021\n\n@author: Mahfuz_Shazol\n\"\"\"\n\nimport numpy as np\nimport torch as th\n\nA=np.array([[25,2],\n            [5,4]])\n\nA_trace=np.trace(A)\nprint(A_trace)\n\n# Tr(A)=Tr(A.T)\nresult1=np.trace(A)\nprint(result1)\nresult2=np.trace(A.T)\nprint(result2)\nprint('Tr(A)=Tr(A.T)   Ans:',result1==result2)\n\n\n#Calculate Frobenius norm AF=(Tr(A A.T))**(1/2)\nA_p=th.tensor([\n    [-1,2],\n    [3,-2],\n    [5,7],\n    ])\n\n\ncalculated_frobenius_norm=(th.trace(th.matmul(th.as_tensor(A),th.as_tensor(A.T))))**(1/2)\nprint('calculated_frobenius_norm  Ans:',calculated_frobenius_norm)\n\nnorm_result=np.linalg.norm(A)\nprint(norm_result)\n\n\n\n\n\n\n\n\n\n    \n\n\n", "meta": {"hexsha": "1c37b8c017e046ed568dd6da235c0bc53fc0dd6a", "size": 677, "ext": "py", "lang": "Python", "max_stars_repo_path": "trace_operator.py", "max_stars_repo_name": "6895mahfuzgit/Linear_Algebra_for_Machine_Learning", "max_stars_repo_head_hexsha": "3f266391491d9ab99e53a3547900c6b1bd657af1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trace_operator.py", "max_issues_repo_name": "6895mahfuzgit/Linear_Algebra_for_Machine_Learning", "max_issues_repo_head_hexsha": "3f266391491d9ab99e53a3547900c6b1bd657af1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trace_operator.py", "max_forks_repo_name": "6895mahfuzgit/Linear_Algebra_for_Machine_Learning", "max_forks_repo_head_hexsha": "3f266391491d9ab99e53a3547900c6b1bd657af1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.54, "max_line_length": 89, "alphanum_fraction": 0.635155096, "include": true, "reason": "import numpy", "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632329799585, "lm_q2_score": 0.9304582607972163, "lm_q1q2_score": 0.8856690082753477}}
{"text": "#!/usr/bin/python\n\nimport os\nimport numpy as np\nimport math\n\nprint \"This script solves the excercises propossed in the Linear Algebra & 2D Geometry Lectures\"\n\n# --------------------------------------------------------------------------------------------------\n# Length and Normalized Vector\nv = np.array([4, 8, -4])\nlen_v = math.sqrt(pow(v[0], 2) + pow(v[1], 2) + pow(v[2], 2))\nprint \"Length of v=\" + str(v) + \" is = \" + str(len_v)\n\nv_norm = v / len_v\n\nprint \"Normalized vector\" + str(v_norm) + \",length of normalized v =\" + str(np.linalg.norm(v_norm))\n\n# --------------------------------------------------------------------------------------------------\n# Scalar and cross product\n\nx1 = np.array([2, -4, 1])\nx2 = np.array([2, 1, -2])\ndot_product = x1[0] * x2[0] + x1[1] * x2[1] + x1[2] * x2[2]\nprint \"The scalar product of x1= \" + str(x1) + \",and x2= \" + str(x2) + \" ,is =  \" + str(dot_product)\n\ndot_product = np.dot(x1, x2)\nprint \"The scalar product of x1= \" + str(x1) + \",and x2= \" + str(x2) + \" ,is =  \" + str(dot_product)\n\ncross_product = np.cross(x1, x2)\nprint \"The cross product of x1= \" + str(x1) + \",and x2= \" + str(x2) + \" ,is =  \" + str(cross_product)\n\n# --------------------------------------------------------------------------------------------------\n# Matrix Algebra\nM1 = np.matrix([[1, 2], [3, 4]])\nM2 = np.matrix([[5, 4], [3, 2]])\nprint \"M1= \" + str(M1)\nprint \" + M2= \" + str(M2)\nprint \"=\" + str(M1 + M2)\n\nM1 = np.matrix([[-1, 0], [0, 1]])\nM2 = np.matrix([[-2, 1], [-1, 2]])\nprint \"M1= \" + str(M1)\nprint \" - M2= \" + str(M2)\nprint \"=\" + str(M1 - M2)\n\n# --------------------------------------------------------------------------------------------------\n# Scalar Matrix Multiplication\nM1 = np.matrix([[1, -2], [2, -1]])\nprint \"2.5 * M1= \" + str(2.5 * M1)\n\n# --------------------------------------------------------------------------------------------------\n# Matrix Vector Multiplication\nM1 = np.matrix([[1, 0], [0, 1]])\nx1 = np.array([1, 2])\nprint \"x1 * M1= \" + str(M1.dot(x1))\n\nM1 = np.matrix([[1, -1], [-1, 1]])\nx1 = np.array([5, 6])\nprint \"x1 * M1= \" + str(M1.dot(x1))\n\n# --------------------------------------------------------------------------------------------------\n# Matrix Multiplication\nM1 = np.matrix([[1, 0], [0, -1]])\nM2 = np.matrix([[1, -2], [2, -1]])\nprint \"M1 * M2= \" + str(M1 * M2)\n\nM1 = np.matrix([[1, 2], [3, 4]])\nM2 = np.matrix([[4, 3], [2, 1]])\nprint \"M1 * M2= \" + str(M1 * M2)\n", "meta": {"hexsha": "66a9ada59ae9387621736f47f3aa6521000cc257", "size": 2415, "ext": "py", "lang": "Python", "max_stars_repo_path": "Algebra_Geometry/2d_homework.py", "max_stars_repo_name": "IgnacioVizz0/AUTONAVx", "max_stars_repo_head_hexsha": "1295fbce90938390724a5ac5ad96e49d968214b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-17T11:55:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-17T11:55:18.000Z", "max_issues_repo_path": "Algebra_Geometry/2d_homework.py", "max_issues_repo_name": "nachovizzo/AUTONAVx", "max_issues_repo_head_hexsha": "1295fbce90938390724a5ac5ad96e49d968214b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Algebra_Geometry/2d_homework.py", "max_forks_repo_name": "nachovizzo/AUTONAVx", "max_forks_repo_head_hexsha": "1295fbce90938390724a5ac5ad96e49d968214b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.014084507, "max_line_length": 101, "alphanum_fraction": 0.4169772257, "include": true, "reason": "import numpy", "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9865717440735735, "lm_q2_score": 0.8976952845805989, "lm_q1q2_score": 0.8856408025553043}}
{"text": "import read_data as RD\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nX = RD.read_data()\nprint('X = ',X.shape)\nX_mean = np.reshape(np.sum(X,1)/X.shape[1],[ X.shape[0],1])\nX = X-X_mean\nprint('X_centerred = ',X.shape)\n[U,S,V] = np.linalg.svd(X, full_matrices=False)\nprint('U = ',U.shape)\nprint('S = ',S.shape)\nprint('V = ',V.shape)\n\nN = 12#number of eigen images\nEig_im = U[:,0:N]\nplt.figure(figsize=(10,10))\nfor i in range(0,N):\n\tplt.subplot(int(np.sqrt(N)),int(np.ceil(N/int(np.sqrt(N)))),i+1)\n\tim = np.reshape(Eig_im[:,i],[64,64])\n\tplt.imshow(im,cmap=plt.cm.gray, interpolation='none')\n\tplt.title('Eigen Image = '+str(i+1))\n\nplt.savefig('Eigen_Images.png')\nplt.savefig('Eigen_Images.tif')\n\nY = np.matmul(np.transpose(U),X)\nprint('Y = ',Y.shape)\nplt.figure(figsize=(10,10))\nNp = 10#Number of projection coefficients to plot\nNi = 4#Number of images\nimages = ['a','b','c','d']\nfor i in range(0,Ni):\n\tplt.plot(np.arange(1,Np+1),Y[0:Np,i],label='Image = '+images[i])\nplt.xlabel('Eigenvectors',fontsize=20)\nplt.xticks(weight = 'bold',fontsize=15)\nplt.ylabel('Magnitude of the projection coefficient',fontsize=20)\nplt.yticks(weight = 'bold',fontsize=15)\nplt.legend(fontsize=20)\nplt.savefig('Projection_Coefficients.png')\nplt.savefig('Projection_Coefficients.tif')\n\n#Image synthesis\nind = 0#index of the image to synthesize\nm = [1, 5, 10, 15, 20, 30]\nplt.figure(figsize=(10,15))\nfor i in range(0,len(m)):\n\tX_hat = np.reshape(np.matmul(U[:,0:m[i]],Y[0:m[i],ind]),[X.shape[0],1])\n\tprint(X_hat.shape)\n\tprint(X_mean.shape)\n\tX_hat += X_mean\n\tplt.subplot(3,2,i+1)\n\tim = np.reshape(X_hat,[64,64])\n\tplt.imshow(im,cmap=plt.cm.gray, interpolation='none')\n\tplt.title('m = '+str(m[i]),fontsize=20)\n\tplt.xticks(weight = 'bold',fontsize=15)\n\tplt.yticks(weight = 'bold',fontsize=15)\n\t#img_out = Image.fromarray(im.astype(np.uint8))\n\t#img_out.save('Im_reconstruction_'+str(m[i])+'.tif')\nplt.savefig('Im_reconstruction.png')\nplt.savefig('Im_reconstruction.tif')\n", "meta": {"hexsha": "481b7b847a5b07aac335adc738e6043d2c120dd3", "size": 1965, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab_5_Eigen_Decomposition/eigen_images.py", "max_stars_repo_name": "NahianHasan/ECE63700-Digital_Image_Processing", "max_stars_repo_head_hexsha": "ef1f1df93ffa16a4c76ddc8cc5ed6bc303dea96b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab_5_Eigen_Decomposition/eigen_images.py", "max_issues_repo_name": "NahianHasan/ECE63700-Digital_Image_Processing", "max_issues_repo_head_hexsha": "ef1f1df93ffa16a4c76ddc8cc5ed6bc303dea96b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab_5_Eigen_Decomposition/eigen_images.py", "max_forks_repo_name": "NahianHasan/ECE63700-Digital_Image_Processing", "max_forks_repo_head_hexsha": "ef1f1df93ffa16a4c76ddc8cc5ed6bc303dea96b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1904761905, "max_line_length": 72, "alphanum_fraction": 0.6900763359, "include": true, "reason": "import numpy", "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347816221828, "lm_q2_score": 0.9086178950769319, "lm_q1q2_score": 0.8853888801672976}}
{"text": "from __future__ import print_function, division\n\nimport numpy as np\nimport scipy.linalg as la\n\ndef simple_lu(A):\n    R = A.copy()\n    L = np.eye(A.shape[0])\n    for i in range(A.shape[0] - 1):\n        factors = R[i + 1:, i] / R[i, i]\n        R[i+1:, :] -= factors[:, None] * R[i, :]\n        L[i+1:, i] = factors\n    return L, R\n\nA = np.array([[1.1, 2.1, 3.1],\n              [2.2, 3.2, 1.2],\n              [3.3, 1.3, 2.3]])\n\nprint(\"Simple LR without pivotisierung\")\nL, R = simple_lu(A)\nprint(\"A:\\n\", A)\nprint(\"L:\\n\", L)\nprint(\"R:\\n\", R)\nprint(\"L*R:\\n\", L.dot(R))\n\n\ndef lu(A):\n    R = A.copy()\n    L = np.eye(A.shape[0])\n    p_rows = np.arange(A.shape[0])\n    for i in range(A.shape[0] - 1):\n        # pivot wahl\n        pivot_row = i + np.argmax(np.abs(R[i:, i]))\n        p_rows[i], p_rows[pivot_row] = p_rows[pivot_row], p_rows[i]\n        R[i, :], R[pivot_row, :] = R[pivot_row, :], R[i, :].copy()\n        # eliminate\n        factors = R[i + 1:, i] / R[i, i]\n        R[i + 1:, :] -= factors[:, None] * R[i, :]\n        L[i + 1:, i] = factors\n    P = np.zeros(A.shape)\n    for i, p in enumerate(p_rows):\n        P[i, p] = 1\n    return P, L, R\n\nprint(\"Simple LR with pivotisierung\")\nP, L, R = lu(A)\nprint(\"A:\\n\", A)\nprint(\"L:\\n\", L)\nprint(\"R:\\n\", R)\nprint(\"P:\\n\", P)\nprint(\"L*R - P*A:\\n\", L.dot(R) - P.dot(A))\n\ndef backsubstitution(upper_triangular_matrix, rhs):\n    sol = np.zeros(rhs.shape[0])\n    for i in range(rhs.shape[0] - 1, -1, -1):\n        sol[i] = (rhs[i] - np.sum(upper_triangular_matrix[i, i + 1:]*sol[i + 1:]))/upper_triangular_matrix[i, i]\n    return sol\n\ndef forwardsubstituition(lower_triangular_matrix, rhs):\n    sol = np.zeros(rhs.shape[0])\n    for i in range(rhs.shape[0]):\n        sol[i] = (rhs[i] - np.sum(lower_triangular_matrix[i, :i]*sol[:i]))/lower_triangular_matrix[i, i]\n    return sol\n\ndef lu_solve(P, L, R, b):\n    # Ax = b\n    # PA = LR\n    # P^-1*L*Rx = b\n    # LRx = Pb\n    # y = Rx\n    # Ly = Pb\n    # Rx = y\n    y = forwardsubstituition(L, P.dot(b))\n    x = backsubstitution(R, y)\n    return x\n\nb = np.array([1,2,3])\nx = lu_solve(P, L, R, b)\nprint(\"b:\\n\", b)\nprint(\"x with Ax = b:\\n\", x)\nprint(\"Ax - b:\\n\", A.dot(x) - b)\n", "meta": {"hexsha": "87d4bd6e5060fdb561a77d3095a662d60214ae5d", "size": 2153, "ext": "py", "lang": "Python", "max_stars_repo_path": "lu.py", "max_stars_repo_name": "cosmo-jana/numerics-physics-stuff", "max_stars_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-16T16:35:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T16:35:35.000Z", "max_issues_repo_path": "lu.py", "max_issues_repo_name": "cosmo-jana/numerics-physics-stuff", "max_issues_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lu.py", "max_forks_repo_name": "cosmo-jana/numerics-physics-stuff", "max_forks_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.256097561, "max_line_length": 112, "alphanum_fraction": 0.5257779842, "include": true, "reason": "import numpy,import scipy", "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793908, "lm_q2_score": 0.9207896802383028, "lm_q1q2_score": 0.8853704065747923}}
{"text": "import numpy as cp\n\nclass Sigmoid():\n    \n    '''\n    \n    A Sigmoid function is a mathematical function which has a characteristic S-shaped curve.\n    Normally used to refer specifically to the logistic function, also called the logistic\n    sigmoid function.sigmoid functions have the property that they map the entire number line \n    into a small range such as between 0 and 1,so one use of a sigmoid function is to convert \n    a real value into one that can be interpreted as a probability.\n    \n    The logistic sigmoid function is defined as follows:\n        \n        S(x) =   _____1_______ where exp is exponential\n                ( 1 + exp(-x))\n                \n     With the help of Sigmoid activation function, we are able to reduce the loss during\n     the time of training because it eliminates the gradient problem in machine learning \n     model while training.   \n     \n    Parameters\n    ----------\n    x : cp.array\n        Array of ouputs of deeplearning layer.\n\n    Returns\n    -------\n    cp.array\n        Array after sigmoid function applied .\n            \n    '''\n\t\n    def __call__(self, x: cp.array) -> cp.array:\n        \n        return 1 / (1 + cp.exp(-x))\n\n    def gradient(self, x: cp.array) -> cp.array:\n        '''\n        \n        Parameters\n        ----------\n        x : cp.array\n             Array of ouputs of deeplearning layer..\n\n        Returns\n        -------\n        cp.array\n            Array after derivatives of sigmoid applied .\n\n        '''        \n        return self.__call__(x) * (1 - self.__call__(x))\n\n", "meta": {"hexsha": "137da3d49f3ac75e68a2a741563da938eaea8942", "size": 1552, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorial/7. Deep Learning/Activation Function/Sigmoid.py", "max_stars_repo_name": "rjnp2/Data-Science", "max_stars_repo_head_hexsha": "4ea830983d064c1da082e18282a1d746eda8d96f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-06-03T10:26:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T18:42:27.000Z", "max_issues_repo_path": "tutorial/7. Deep Learning/Activation Function/Sigmoid.py", "max_issues_repo_name": "sanjipun/Data-Science", "max_issues_repo_head_hexsha": "4ea830983d064c1da082e18282a1d746eda8d96f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial/7. Deep Learning/Activation Function/Sigmoid.py", "max_forks_repo_name": "sanjipun/Data-Science", "max_forks_repo_head_hexsha": "4ea830983d064c1da082e18282a1d746eda8d96f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-03T10:26:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-03T10:26:55.000Z", "avg_line_length": 28.7407407407, "max_line_length": 94, "alphanum_fraction": 0.5908505155, "include": true, "reason": "import numpy", "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399060540359, "lm_q2_score": 0.9124361688107863, "lm_q1q2_score": 0.8852819827072816}}
{"text": "'''\n    Vector length formula for three-dimensional vector\n    --------------------------------------------------\n    In the case of the spatial problem the length of the vector a = {ax ; ay ; az} \n    can be found using the   following formula:\n\n    |a| = √ax2 + ay2 + az2\n\n    Examples of plane tasks\n    Example 1. Find the length of the vector a = {2; 4}.\n    Solution: |a| = √2^2 + 4^2 = √4 + 16 = √20 = 2√5.\n\n    Example 2. Find the length of the vector a = {3; -4}.\n    Solution: |a| = √3^2 + (-4)^2 = √9 + 16 = √25 = 5.\n\n    Examples of spatial tasks\n    Example 3. Find the length of the vector a = {2; 4; 4}.\n    Solution: |a| = √2^2 + 4^2 + 4^2 = √4 + 16 + 16 = √36 = 6.\n\n    Example 4. Find the length of the vector a = {-1; 0; -3}.\n    Solution: |a| = √(-1)^2 + 0^2 + (-3)^2 = √1 + 0 + 9 = √10.\n'''\n\nimport numpy as np\n\na = np.array([2,4,4]) # 3 dimension\n\ntotal = 0\n\nfor i in range(len(a)):\n    total += a[i] ** 2\n\nprint(np.sqrt(total))\n# or\nprint(np.linalg.norm(a))\n\na = np.array([-1, 0, -3, -4, 10])\n\ntotal = 0\n\nfor i in range(len(a)):\n    total += a[i] ** 2\n\nprint(np.sqrt(total))\n#or\nprint(np.linalg.norm(a))", "meta": {"hexsha": "0abaca24f5e19cb19dda518995db70d43f2c1683", "size": 1126, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear-algebra/lenght-of-vector.py", "max_stars_repo_name": "Nahid-Hassan/code-snippets", "max_stars_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-29T04:09:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-18T13:33:36.000Z", "max_issues_repo_path": "linear-algebra/lenght-of-vector.py", "max_issues_repo_name": "Nahid-Hassan/code-snippets", "max_issues_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear-algebra/lenght-of-vector.py", "max_forks_repo_name": "Nahid-Hassan/code-snippets", "max_forks_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-26T04:55:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T04:55:55.000Z", "avg_line_length": 24.4782608696, "max_line_length": 83, "alphanum_fraction": 0.5230905861, "include": true, "reason": "import numpy", "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971563970248593, "lm_q2_score": 0.9111797154386843, "lm_q1q2_score": 0.8852693819415912}}
{"text": "# Least square method of univariate linear regression.\n# Solution/weight coeffecients: y = mx + c -> m = sum((Mean-deviation of Xi) * (Mean-deviation of Yi)) / sum((Mean-deviation of Xi) ** 2)\n#                                             c = Mean-Y - m * Mean-X\n# https://www.amherst.edu/system/files/media/1287/SLR_Leastsquares.pdf\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass LinearRegression:\n    def __init__(self):\n        self._X = None\n        self._y = None\n        self._beta0 = 0.\n        self._beta1 = 0.\n        self._correlation = 0.\n\n    def _mean(self, arr):\n        return np.mean(arr)\n\n    def _diff(self, arr, num):\n        return np.subtract(arr, num)\n\n    def fit(self, X, y):\n        self._X = X\n        self._y = y\n        self._compute_correlation()\n\n        mean_x = self._mean(self._X)\n        mean_y = self._mean(self._y)\n        mean_deviation_x = self._diff(self._X, mean_x)\n        mean_deviation_y = self._diff(self._y, mean_y)\n\n        self._beta1 = np.sum(np.multiply(mean_deviation_x, mean_deviation_y)) / np.sum(mean_deviation_x ** 2)\n        self._beta0 = mean_y - self._beta1 * mean_x\n\n        train_pred = self.predict(X)\n        return self._rmse_error(y, train_pred)\n\n    def _rmse_error(self, y, y_pred):\n        return np.sqrt(np.mean(np.subtract(y, y_pred) ** 2))\n\n    def predict(self, input):\n        return np.add(self._beta0, np.dot(self._beta1, input))\n\n    def weight_coefficients(self, decimal=4):\n        return round(self._beta0, decimal), round(self._beta1, decimal)\n\n    def _compute_correlation(self):\n        sum_x = np.sum(self._X)\n        sum_y = np.sum(self._y)\n        sum_xy = np.sum(np.multiply(self._X, self._y))\n        sum_xsquare = np.sum(np.multiply(self._X, self._X))\n        sum_ysquare = np.sum(np.multiply(self._y, self._y))\n        n = len(self._X)\n        self._correlation = (n * sum_xy - sum_x * sum_y) / np.sqrt(((n * sum_xsquare - sum_x ** 2) * (n * sum_ysquare - sum_y ** 2)))\n\n    def correlation(self, decimal=4):\n        return round(self._correlation, decimal)\n\n    def plot_regression(self, X, y):\n        plt.scatter(X, y, color=\"red\", marker=\"x\", s=20)\n\n        y_pred = self._beta0 + np.multiply(self._beta1, X)\n\n        plt.plot(X, y_pred, color=\"green\")\n\n        plt.xlabel('X')\n        plt.ylabel('y')\n\n        plt.show()\n\n\ndef main():\n    linear_reg = LinearRegression()\n    X = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n    y = [6, 8, 9, 11, 13, 16, 17, 19, 20, 24]\n\n    rmse_error = linear_reg.fit(X, y)\n    weights = linear_reg.weight_coefficients()\n    print 'Weight coefficients for y = mx + c: m = {}, c = {}\\n'.format(weights[1], weights[0])\n    print 'Correlation between X and y: {}\\n'.format(linear_reg.correlation())\n    print 'Root mean-squared error for training: {}\\n'.format(rmse_error)\n\n    test_y = [3, 5, 10]\n    print 'Prediction of {}: {}'.format(test_y, (linear_reg.predict(test_y)))\n    linear_reg.plot_regression(X, y)\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "8f11cf7c4947221b9763d121c817194305747644", "size": 2976, "ext": "py", "lang": "Python", "max_stars_repo_path": "code_module/least_square/linear_regression_univariate.py", "max_stars_repo_name": "krayush07/linear-regression", "max_stars_repo_head_hexsha": "fa3ce58e60fcad8d67216f548d4c69fc311fa9ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code_module/least_square/linear_regression_univariate.py", "max_issues_repo_name": "krayush07/linear-regression", "max_issues_repo_head_hexsha": "fa3ce58e60fcad8d67216f548d4c69fc311fa9ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code_module/least_square/linear_regression_univariate.py", "max_forks_repo_name": "krayush07/linear-regression", "max_forks_repo_head_hexsha": "fa3ce58e60fcad8d67216f548d4c69fc311fa9ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.347826087, "max_line_length": 137, "alphanum_fraction": 0.6045026882, "include": true, "reason": "import numpy", "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639653084244, "lm_q2_score": 0.9111797142327147, "lm_q1q2_score": 0.8852693762685333}}
{"text": "# ***Question (1)***\n# \n# Part (a)\n# \n# Simultaneous equations for the loops:\n# 80*i1-50*i2-30*i3 = 240\n# 50*i1-100*i2-10*i3-25*i4 = 0\n# -30*i1-10*i2+65*i3-20*i4 = 0\n# -25*i2-20*i3-100*i4 = 0\n\n\n# Part (b)\n\nimport scipy as sp\nimport numpy as np\nimport gaussElimin as gE\n\nA = sp.array([[80.0,-50.0,-30.0,0.0],[-50.0,100.0,-10.0,-25.0],[-30.0,-10.0,65.0,-20.0],[0.0,-25.0,-20.0,100.0]]) # array of coefficients in simultaneous equations\nb = sp.array([240.0,0.0,0.0,0.0]) # results for all the simultaneous equations\n\n\n\nprint \"For the first array, plug in all of the coefficients of the simultaneous equations derived from the circuit diagrams. This array, A:\"\nprint A\n\nprint \"For the second array, plug in all the results of the simultaneous equations derived from the circuit diagram. This array, b:\"\nprint b \n\n\nx = gE.gaussElimin(A,b)\n\nprint \"Using the Gaussian elimination module, we can solve:\"\nprint x \n\n# Part (c)\n\nfrom scipy import linalg\n\nP, L, U = linalg.lu(A) # computes LU factorisation explicitly where P is the permutation matrix, L is the lower triangular matrix, and U is the upper triangular matrix\n\nprint \"We can use an LU (Lower-Upper) decomposition to decompose our resultant matrix into an upper part and a lower part. The lower part:\"\nprint L\n\nprint \"And the upper part:\"\nprint U\n\n# Part (d)\n\nprint \"Next, use the LU decomposition to solve Ax = b\"\n\ny1 = gE.gaussElimin(L,b) # lower triangular matrix and b\n\nx1 = gE.gaussElimin(U,y1) # upper triangular matrix and the gE of lower and b\nprint x1\n\nprint \"Now we want to use our LU decomposition to prove that we can go the other direction and get an answer from it too.\" \nprint \"Using a new array where the voltage across is 120 V instead of 240 V (as the range is 0 V to +120 V instead of -120 V to +120 V:\"\n\nc = sp.array([240.0,0.0,0.0,0.0]) # new b array where the -120 V is = 0 V\n\ny2 = gE.gaussElimin(L,c) # same process as with y1 and x1\n\nx2 = gE.gaussElimin(U,y2)\n\n\nprint x2\n\n\n\n", "meta": {"hexsha": "0c1f464c81704cecd9933f396819ebbd463b06bf", "size": 1949, "ext": "py", "lang": "Python", "max_stars_repo_path": "ExamPrep/Shit Comp/SciComp Exam 2016/Assignments 15-16/A1Q1 LU decomp Gauss Elim.py", "max_stars_repo_name": "FHomewood/ScientificComputing", "max_stars_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_stars_repo_licenses": ["IJG"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ExamPrep/Shit Comp/SciComp Exam 2016/Assignments 15-16/A1Q1 LU decomp Gauss Elim.py", "max_issues_repo_name": "FHomewood/ScientificComputing", "max_issues_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_issues_repo_licenses": ["IJG"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ExamPrep/Shit Comp/SciComp Exam 2016/Assignments 15-16/A1Q1 LU decomp Gauss Elim.py", "max_forks_repo_name": "FHomewood/ScientificComputing", "max_forks_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_forks_repo_licenses": ["IJG"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8428571429, "max_line_length": 167, "alphanum_fraction": 0.7024114931, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122768904644, "lm_q2_score": 0.9241418158002492, "lm_q1q2_score": 0.8852467909429049}}
{"text": "\"\"\"\nCreated on Aug  30 \n\n@author: tsquire\n\nDescription: Solving the knapsack problem (see below) using dynamic programming\n\nmax 3x1 + x2 + 6x3\ns.t 4x1 + 5x2 + 10x3 <= 20\n\"\"\"\n\nimport numpy as np\n\nc = np.array([3,1,6])\na= np.array([4,5,10])\nd= 20\nn= c.size\n\n\ndef KnapSackSolve(costs,weights,cap,varNum):\n    valMat = np.zeros([varNum,cap+1])\n    decMat = np.zeros([varNum,cap+1])\n    for i in range(varNum-1,-1,-1):\n        for j in range(cap+1):\n            range2Check = int(j/weights[i])\n            maxVal = 0\n            maxPos = -1\n            for k in range(range2Check+1):\n                if i == varNum-1:\n                    val = k*costs[i]\n                else:\n                    val = k*costs[i]+valMat[i+1,j-k*weights[i]]\n                if val >= maxVal:\n                    maxVal = val\n                    maxPos = k\n            valMat[i,j] = maxVal\n            decMat[i,j] = maxPos\n    return valMat,decMat\n\ndef EvalSolu(valMat,decMat,costs,weights,cap,varNum):\n    x = np.zeros(varNum)\n    currentCap = cap\n    totalCost = 0\n    for i in range(varNum):\n        x[i] = decMat[i,currentCap]\n        totalCost += x[i]*costs[i]\n        currentCap -= int(x[i]*weights[i])\n    return x,totalCost\n\nvalMat,decMat = KnapSackSolve(c,a,d,n)\nsolu,totalCost = EvalSolu(valMat,decMat,c,a,d,n)\n", "meta": {"hexsha": "5f29851bd207a7298a5cb30f6278c429d9463253", "size": 1298, "ext": "py", "lang": "Python", "max_stars_repo_path": "knapSackSolve.py", "max_stars_repo_name": "trevorsquires9/iefinal", "max_stars_repo_head_hexsha": "1953b144dc0cc4cae6984af9fd95bb2c3f3ba891", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "knapSackSolve.py", "max_issues_repo_name": "trevorsquires9/iefinal", "max_issues_repo_head_hexsha": "1953b144dc0cc4cae6984af9fd95bb2c3f3ba891", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "knapSackSolve.py", "max_forks_repo_name": "trevorsquires9/iefinal", "max_forks_repo_head_hexsha": "1953b144dc0cc4cae6984af9fd95bb2c3f3ba891", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9615384615, "max_line_length": 79, "alphanum_fraction": 0.5454545455, "include": true, "reason": "import numpy", "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769085257164, "lm_q2_score": 0.9073122251200418, "lm_q1q2_score": 0.8851528556501993}}
{"text": "\"\"\"Halton low discrepancy sequence.\n\nThis snippet implements the Halton sequence following the generalization of\na sequence of *Van der Corput* in n-dimensions.\n\n---------------------------\n\nMIT License\n\nCopyright (c) 2017 Pamphile Tupui ROY\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\n\n\ndef primes_from_2_to(n):\n\n\tsieve = np.ones(n // 3 + (n % 6 == 2), dtype=np.bool)\n\tfor i in range(1, int(n ** 0.5) // 3 + 1):\n\t\tif sieve[i]:\n\t\t\tk = 3 * i + 1 | 1\n\t\t\tsieve[k * k // 3::2 * k] = False\n\t\t\tsieve[k * (k - 2 * (i & 1) + 4) // 3::2 * k] = False\n\treturn np.r_[2, 3, ((3 * np.nonzero(sieve)[0][1:] + 1) | 1)]\n\n\ndef van_der_corput(n_sample, base=2):\n\n\tsequence = []\n\tfor i in range(n_sample):\n\t\tn_th_number, denom = 0., 1.\n\t\twhile i > 0:\n\t\t\ti, remainder = divmod(i, base)\n\t\t\tdenom *= base\n\t\t\tn_th_number += remainder / denom\n\t\tsequence.append(n_th_number)\n\n\treturn sequence\n\n\ndef halton(dim, n_sample):\n\n\tbig_number = 10\n\twhile 'Not enought primes':\n\t\tbase = primes_from_2_to(big_number)[:dim]\n\t\tif len(base) == dim:\n\t\t\tbreak\n\t\tbig_number += 1000\n\n\tsample = [van_der_corput(n_sample + 1, dim) for dim in base]\n\tsample = np.stack(sample, axis=-1)[1:]\n\n\treturn sample\n\n\ndef halton_batch(batch_size, dim, n_sample, extent=1.5, z_offset=0.):\n\n\tif z_offset == 0:\n\t\treturn tf.cast(tf.constant([halton(dim, n_sample) for _ in range(batch_size)]), tf.float32) * (extent / 0.5)\n\telse:\n\t\tarr = np.array([halton(dim, n_sample) for _ in range(batch_size)], dtype=np.float32) * (extent / 0.5)\n\t\tarr[:, :, 2] = z_offset\n\t\tarr[:, :, :2] = arr[:, :, :2] - np.mean(arr[:, :, :2], axis=1).reshape(arr.shape[0], -1, 2)\n\t\treturn tf.constant(arr)\n", "meta": {"hexsha": "bd70ecd0feda56c4dc0123241757f5119a661704", "size": 2647, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/halton.py", "max_stars_repo_name": "dgriffiths3/finding-your-center", "max_stars_repo_head_hexsha": "6eea1ed5d1bbd9064828133111e96f3395a3afcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2020-05-22T02:24:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T09:13:40.000Z", "max_issues_repo_path": "utils/halton.py", "max_issues_repo_name": "dgriffiths3/finding-your-center", "max_issues_repo_head_hexsha": "6eea1ed5d1bbd9064828133111e96f3395a3afcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-10-12T23:06:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:40:17.000Z", "max_forks_repo_path": "utils/halton.py", "max_forks_repo_name": "dgriffiths3/finding-your-center", "max_forks_repo_head_hexsha": "6eea1ed5d1bbd9064828133111e96f3395a3afcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-09T23:32:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-25T11:37:27.000Z", "avg_line_length": 31.5119047619, "max_line_length": 110, "alphanum_fraction": 0.6939931998, "include": true, "reason": "import numpy", "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997376, "lm_q2_score": 0.925229951422338, "lm_q1q2_score": 0.8851066143947044}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom tictoc import *\r\nfrom plot import plot\r\n#from RFA import secant\r\n\r\ndef secant(f,x0,x1,TOL,NMAX):\r\n    #INPUT : f , x0 , x1 , TOL , NMAX\r\n    # f : function / polynomial\r\n    # x0 : first initial point/guess\r\n    # x1 : second initial point/guess\r\n    # TOL : tolerance value\r\n    # NMAX : maximum number of iterations\r\n\r\n    #Approximates root using Secant Method\r\n\r\n    #Print Header\r\n    print('--------------------------------------------------------------------------')\r\n    print(\"iter \\t\\t\\t x2 \\t\\t\\t\\t f(x2)\")\r\n    print('--------------------------------------------------------------------------')\r\n    \r\n    for i in range(NMAX):\r\n        if f(x0) == f(x1):\r\n            print('DIVIDE BY ZERO ENCOUNTERED!')\r\n            exit()\r\n        #improved guess\r\n        x2 = x0 - (x1-x0)*f(x0)/(f(x1)-f(x0))\r\n        N.append(1+i)\r\n        f_x.append(f(x2))\r\n        #print values after each iteration step\r\n        print(\"%d \\t\\t %15.12f \\t\\t %15.12f\" %(1+i,x2,f(x2)))\r\n        x0 = x1\r\n        x1 = x2\r\n\r\n        #executing the required precision\r\n        if abs(f(x2)) < TOL:\r\n            print('--------------------------------------------------------------------------')\r\n            print('Root Found : ',x2)\r\n            break\r\n    #limiting number of iterations\r\n    if i == NMAX -1:\r\n        print(\"MAX NUMBER OF ITERATIONS REACHED!\")\r\n        print('Approximaiton to the Root after max iterations is : '+str(c))        \r\n        exit()\r\n\r\n\r\n\r\n\r\n\r\n\r\nf1 = lambda x: x**3 - 3*(x**2) - x + 9\r\nf2 = lambda x: np.exp(x)*(x**3 - 3*(x**2) - x + 9)\r\nx0 = -2\r\nx1 = 5\r\n\r\n\r\n\r\n\r\nN=[]\r\nf_x=[]\r\ntic()\r\nsecant(f1,x0,x1,1.e-10,1000)\r\ntoc()\r\nplot(N,f_x,'b',1)\r\n\r\nN=[]\r\nf_x=[]\r\ntic()\r\nsecant(f1,x0-0.5,x1+0.5,1.e-10,1000)\r\ntoc()\r\nplot(N,f_x,'r',1)\r\nplt.legend(['(x0,x1)=(-2,2)','(x0,x1)=(-2.5,5.5)'])\r\nplt.show()\r\n\r\nN=[]\r\nf_x=[]\r\ntic()\r\nsecant(f2,x0,x1,1.e-10,1000)\r\ntoc()\r\nplot(N,f_x,'b',2)\r\n\r\nN=[]\r\nf_x=[]\r\ntic()\r\nsecant(f2,x0-0.5,x1+0.5,1.e-10,1000)\r\ntoc()\r\nplot(N,f_x,'r',2)\r\nplt.legend(['(x0,x1)=(-2,2)','(x0,x1)=(-2.5,5.5)'])\r\nplt.show()\r\n\r\n", "meta": {"hexsha": "da56adf8640c837417ed822126149cd066d52748", "size": 2098, "ext": "py", "lang": "Python", "max_stars_repo_path": "Secant.py", "max_stars_repo_name": "YashIITM/Root-Finding-Algorithms", "max_stars_repo_head_hexsha": "a7ccc58cd5064f7910af538de00a3fe7cdd57cd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Secant.py", "max_issues_repo_name": "YashIITM/Root-Finding-Algorithms", "max_issues_repo_head_hexsha": "a7ccc58cd5064f7910af538de00a3fe7cdd57cd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Secant.py", "max_forks_repo_name": "YashIITM/Root-Finding-Algorithms", "max_forks_repo_head_hexsha": "a7ccc58cd5064f7910af538de00a3fe7cdd57cd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0549450549, "max_line_length": 96, "alphanum_fraction": 0.4556720686, "include": true, "reason": "import numpy", "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.9252299488452012, "lm_q1q2_score": 0.8851066096415009}}
{"text": "# import packages\nimport numpy as np\nimport matplotlib.pyplot as plt\n#from scipy.stats import linregress\nfrom scipy.integrate import simps\n#from matplotlib.patches import Polygon\n\n# input data\nx = np.array([1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5,9, 9.5, 10])\ny = np.array([3.43, 4.94, 6.45, 9.22, 6.32, 6.11, 4.63, 8.95, 7.8, 8.35, 11.45, 14.71, 11.97, 12.46, 17.42, 17.0, 15.45, 19.15, 20.86])\n\n# 1: fit linear\nl_co = np.polyfit(x, y, 1)\nl_fit = np.poly1d(l_co)\n\n# 2: fit cubic\nc_co = np.polyfit(x, y, 3)\nc_fit = np.poly1d(c_co)\n\n# 3: Find the area underneath the cubic curve\nt = np.linspace(1, 10, 200)\narea = simps(c_fit(t),t)\nprint(\"Area under cubic line = \",area)\n\n# 4 & 5: Plot the data, the linear fit, and the cubic fit; Put the area on the plot\n\nplt.scatter(x,y, label = 'Data')\nplt.plot(x,l_fit(x),'r', label = 'Linear Fit')\nplt.plot(t,c_fit(t),'g', label = 'Cubic Fit')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Fitting the data')\nplt.legend()\nplt.text(0.8,16,'Area under cubic line = '+str(area))\nplt.savefig('ylu_data_fitting.pdf')\n\n# 6: Justify preferable model (linear or cubic) by BIC\ndef BIC(y, yhat, k, weight = 1):\n    err = y - yhat\n    sigma = np.std(np.real(err))\n    n = len(y)\n    B = n*np.log(sigma**2) + weight*k*np.log(n)\n    return B\nlinear = BIC(y,l_fit(x),len(l_co)) # k = number of coefficients\ncubic = BIC(y,c_fit(x),len(c_co))\nprint('BIC(linear):',linear)\nprint('BIC(cubic):',cubic)\nif linear <= cubic:\n    print('linear model is preferable')\nelse:\n    print('cubic model is preferable')    ", "meta": {"hexsha": "a3480784008e1b1c7ccd9b9019682420f2268c97", "size": 1549, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week02/ylu_HW2_Problem1-6.py", "max_stars_repo_name": "stnma7e/SkillsWorkshop2018", "max_stars_repo_head_hexsha": "f18d6fd265d1400f4a8f0eefa0d9d4a6fedf01f0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-18T03:30:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-18T03:30:46.000Z", "max_issues_repo_path": "Week02/ylu_HW2_Problem1-6.py", "max_issues_repo_name": "stnma7e/SkillsWorkshop2018", "max_issues_repo_head_hexsha": "f18d6fd265d1400f4a8f0eefa0d9d4a6fedf01f0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2018-07-12T19:12:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-10T13:52:45.000Z", "max_forks_repo_path": "Week02/ylu_HW2_Problem1-6.py", "max_forks_repo_name": "stnma7e/SkillsWorkshop2018", "max_forks_repo_head_hexsha": "f18d6fd265d1400f4a8f0eefa0d9d4a6fedf01f0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 60, "max_forks_repo_forks_event_min_datetime": "2018-05-08T16:59:20.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-01T14:28:28.000Z", "avg_line_length": 30.3725490196, "max_line_length": 135, "alphanum_fraction": 0.6455777921, "include": true, "reason": "import numpy,from scipy", "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102589923635, "lm_q2_score": 0.9149009544128984, "lm_q1q2_score": 0.8850845692609427}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n# # CAPM - Capital Asset Pricing Model\n# Watch the video for the full overview.\n# Portfolio Returns:\n# ## $r_p(t) = \\sum\\limits_{i}^{n}w_i r_i(t)$\n# Market Weights:\n# ## $ w_i = \\frac{MarketCap_i}{\\sum_{j}^{n}{MarketCap_j}} $\n# ### CAPM of a portfolio\n# ## $ r_p(t) = \\beta_pr_m(t) + \\sum\\limits_{i}^{n}w_i \\alpha_i(t)$\n# Model CAPM as a simple linear regression\nfrom scipy import stats\nimport pandas as pd\nimport pandas_datareader as web\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nhelp(stats.linregress)\nspy_etf = web.DataReader('SPY', 'yahoo')\n# In[21]:\nspy_etf.info()\n# In[22]:\nspy_etf.head()\n# In[18]:\nstart = pd.to_datetime('2010-01-04')\nend = pd.to_datetime('2017-07-18')\naapl = web.DataReader('AAPL', 'yahoo', start, end)\naapl.head()\n# In[28]:\n#get_ipython().run_line_magic('matplotlib', 'inline')\naapl['Close'].plot(label='AAPL', figsize=(10, 8))\nspy_etf['Close'].plot(label='SPY Index')\nplt.legend()\n# ## Compare Cumulative Return\naapl['Cumulative'] = aapl['Close'] / aapl['Close'].iloc[0]\nspy_etf['Cumulative'] = spy_etf['Close'] / spy_etf['Close'].iloc[0]\naapl['Cumulative'].plot(label='AAPL', figsize=(10, 8))\nspy_etf['Cumulative'].plot(label='SPY Index')\nplt.legend()\nplt.title('Cumulative Return')\n# ## Get Daily Return\naapl['Daily Return'] = aapl['Close'].pct_change(1)\nspy_etf['Daily Return'] = spy_etf['Close'].pct_change(1)\nplt.scatter(aapl['Daily Return'], spy_etf['Daily Return'], alpha=0.3)\n# In[46]:\naapl['Daily Return'].hist_df(bins=100)\nspy_etf['Daily Return'].hist_df(bins=100)\nbeta, alpha, r_value, p_value, std_err = stats.linregress(aapl['Daily Return'].iloc[1:],\n                                                          spy_etf['Daily Return'].iloc[1:])\nbeta\n# In[39]:\nalpha\n# In[40]:\nr_value\n# ## What if our stock was completely related to SP500?\nspy_etf['Daily Return'].head()\nnoise = np.random.normal(0, 0.001, len(spy_etf['Daily Return'].iloc[1:]))\nnoise\n# In[65]:\nspy_etf['Daily Return'].iloc[1:] + noise\n# In[66]:\nbeta, alpha, r_value, p_value, std_err = stats.linregress(spy_etf['Daily Return'].iloc[1:] + noise,\n                                                          spy_etf['Daily Return'].iloc[1:])\nbeta\n# In[68]:\nalpha\n# Looks like our understanding is correct!\n", "meta": {"hexsha": "328376568ea9459f50368b8a8756979332d6c24d", "size": 2254, "ext": "py", "lang": "Python", "max_stars_repo_path": "FinanceAnalysisAlgoTrading/09-Python-Finance-Fundamentals_03-CAPM-Capital-Asset-Pricing-Model.py", "max_stars_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_stars_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-04T11:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-10T15:36:42.000Z", "max_issues_repo_path": "FinanceAnalysisAlgoTrading/09-Python-Finance-Fundamentals_03-CAPM-Capital-Asset-Pricing-Model.py", "max_issues_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_issues_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-03-30T16:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:37:21.000Z", "max_forks_repo_path": "FinanceAnalysisAlgoTrading/09-Python-Finance-Fundamentals_03-CAPM-Capital-Asset-Pricing-Model.py", "max_forks_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_forks_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T11:26:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T11:26:16.000Z", "avg_line_length": 33.1470588235, "max_line_length": 99, "alphanum_fraction": 0.6548358474, "include": true, "reason": "import numpy,from scipy", "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102571131692, "lm_q2_score": 0.9149009515124917, "lm_q1q2_score": 0.8850845647357828}}
{"text": "import numpy as np\nfrom numpy.linalg import svd\nfrom scipy.io import loadmat\nimport matplotlib.pyplot as plt\n\n\ndef featureNormalize(X):\n    \"\"\"\n    Normalize the dataset X\n\n    :param X:\n    :return:\n    \"\"\"\n\n    mu = np.mean(X, axis=0)\n    sigma = np.std(X, axis=0)\n\n    X_normalized = (X - mu) / sigma\n\n    return X_normalized, mu, sigma\n\n\ndef pca(X):\n    \"\"\"\n    Compute eigenvectors of the covariance matrix X\n\n    :param X:\n    :return:\n    \"\"\"\n\n    number_of_examples = X.shape[0]\n    sigma = (1/number_of_examples) * np.dot(X.T, X)\n    U, S, V = svd(sigma)\n\n    return U, S, V\n\n\ndef projectData(X, U, K):\n    \"\"\"\n    Computes the reduced data representation when projecting only onto\n    the top K eigenvectors\n\n    :param X: Dataset\n    :param U: Principal components\n    :param K: The desired number of dimensions to reduce\n    :return:\n    \"\"\"\n\n    number_of_examples = X.shape[0]\n    U_reduced = U[:, :K]\n\n    Reduced_representation = np.zeros((number_of_examples, K))\n\n    for i in range(number_of_examples):\n        for j in range(K):\n            Reduced_representation[i, j] = np.dot(X[i, :], U_reduced[:, j])\n\n    return Reduced_representation\n\n\ndef recoverData(Z, U, K):\n    \"\"\"\n    Recovers an approximation of the original data when using the projected data\n\n    :param Z: Reduced representation\n    :param U: Principal components\n    :param K: The desired number of dimensions to reduce\n    :return:\n    \"\"\"\n\n    number_of_examples = Z.shape[0]\n    number_of_features = U.shape[0]\n\n    X_recovered = np.zeros((number_of_examples, number_of_features))\n    U_reduced = U[:, :K]\n\n    for i in range(number_of_examples):\n        X_recovered[i, :] = np.dot(Z[i, :], U_reduced.T)\n\n    return X_recovered\n\n\n'''\nStep 0: Load the dataset.\n'''\n\ndataset = loadmat(\"./data/lab9data2.mat\")\nprint(dataset.keys(), '\\n')\n\nX = dataset[\"X\"]\n\n\n'''\nStep 1: Normalize the dataset X\n'''\n\nX_normalized, mu, std = featureNormalize(X)\nprint(\"Values of the first 3 normalized dataset X: \\n{}\\n\".format(X_normalized[:3]))\n\n\n'''\nStep 2: Compute the principal components and the diagonal matrix\n'''\n\nU, S, _ = pca(X_normalized)\n\nprint(\"The principal components: \\n{}\\n\".format(U))\nprint(\"The diagonal matrix: \\n{}\\n\".format(S))\n\n\n'''\nStep 3: Project the data onto 1 dimension\n'''\n\nreduced_representation = projectData(X_normalized, U, 1)\nprint(\"Projection of the first example: {}\\n\".format(reduced_representation[0][0]))\n\n\n'''\nStep 4: Reconstruct an approximation of the data (which was reduced to 1 dimension)\n'''\n\nX_recovered = recoverData(reduced_representation, U, 1)\nprint(\"Approximation of the first example: {}\\n\".format(X_recovered[0, :]))\n\n\n'''\nStep 5: Visualizing the projections\n'''\n\nplt.scatter(X_normalized[:, 0], X_normalized[:, 1], marker=\"o\", label=\"Original\", facecolors=\"none\", edgecolors=\"b\", s=15)\nplt.scatter(X_recovered[:, 0], X_recovered[:, 1], marker=\"o\", label=\"Approximation\", facecolors=\"none\", edgecolors=\"r\", s=15)\nplt.title(\"The Normalized and Projected Data after PCA\")\nplt.legend()\n\n", "meta": {"hexsha": "9114206a434ca6d3e053dd4c981a9e593284a7d7", "size": 3006, "ext": "py", "lang": "Python", "max_stars_repo_path": "day10/lab-guide-ans/lab9-problem3-3.py", "max_stars_repo_name": "WhatTheFar/practical-ai-bootcamp", "max_stars_repo_head_hexsha": "e2fe013390c00df0a5486795a737d7b777266f35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day10/lab-guide-ans/lab9-problem3-3.py", "max_issues_repo_name": "WhatTheFar/practical-ai-bootcamp", "max_issues_repo_head_hexsha": "e2fe013390c00df0a5486795a737d7b777266f35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day10/lab-guide-ans/lab9-problem3-3.py", "max_forks_repo_name": "WhatTheFar/practical-ai-bootcamp", "max_forks_repo_head_hexsha": "e2fe013390c00df0a5486795a737d7b777266f35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1029411765, "max_line_length": 125, "alphanum_fraction": 0.6650033267, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426450627306, "lm_q2_score": 0.9086179006446221, "lm_q1q2_score": 0.8850325832952332}}
{"text": "import matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport numpy as np\nfrom numpy import linalg as LA\n\n\nfig = plt.figure()\nax = fig.add_subplot(321, aspect='equal')\n# Parallelogram\nxy = np.array([[0,0], [7,2], [12,11],[5,9]])\nmean = np.mean(xy, axis=0)\nprint('Mean', mean)\ncov = np.cov(xy.T)\nprint('Cov::')\nprint(cov)\neigenvalues, eigenvectors = LA.eig(cov)\nprint('Eigen values', eigenvalues)\nprint('Eigen vectors', eigenvectors)\nax.add_patch(patches.Polygon(xy, fill=False))\nplt.quiver(mean[0],mean[1],eigenvectors[0,0],eigenvectors[0,1], color=['r'],scale=5, label=\"eigen vector[0]\")\nplt.quiver(mean[0],mean[1],eigenvectors[1,0],eigenvectors[1,1], color=['g'],scale=5, label=\"eigen vector[1]\")\n\nax1 = fig.add_subplot(322, aspect='equal')\n# Parallelogram : Square\nxy1 = np.array([[0,0], [0,3], [3,3],[3,0]])\nmean1 = np.mean(xy1, axis=0)\nprint('Mean', mean1)\ncov1 = np.cov(xy1.T)\nprint('Cov::')\nprint(cov1)\neigenvalues1, eigenvectors1 = LA.eig(cov1)\nprint('Eigen values', eigenvalues1)\nprint('Eigen vectors', eigenvectors1)\nax1.add_patch(patches.Polygon(xy1, fill=False))\nax1.quiver(mean1[0],mean1[1],eigenvectors1[0,0],eigenvectors1[0,1], color=['r'],scale=5, label=\"eigen vector[0]\")\nax1.quiver(mean1[0],mean1[1],eigenvectors1[1,0],eigenvectors1[1,1], color=['g'],scale=5, label=\"eigen vector[1]\")\n\n\nax2 = fig.add_subplot(323, aspect='equal')\n# Parallelogram : Rectangle\nxy2 = np.array([[0,0], [0,2], [4,2],[4,0]])\nmean2 = np.mean(xy2, axis=0)\nprint('Mean', mean2)\ncov2 = np.cov(xy2.T)\nprint('Cov::')\nprint(cov2)\neigenvalues2, eigenvectors2 = LA.eig(cov2)\nprint('Eigen values', eigenvalues2)\nprint('Eigen vectors', eigenvectors2)\nax2.add_patch(patches.Polygon(xy2, fill=False))\nax2.quiver(mean2[0],mean2[1],eigenvectors2[0,0],eigenvectors2[0,1], color=['r'],scale=5, label=\"eigen vector[0]\")\nax2.quiver(mean2[0],mean2[1],eigenvectors2[1,0],eigenvectors2[1,1], color=['g'],scale=5, label=\"eigen vector[1]\")\n\n\nax3 = fig.add_subplot(324, aspect='equal')\n# Parallelogram : Rectangle\nxy3 = np.array([[0,0], [-1,3], [4,3],[5,0]])\nmean3 = np.mean(xy3, axis=0)\nprint('Mean', mean3)\ncov3 = np.cov(xy3.T)\nprint('Cov::')\nprint(cov3)\neigenvalues3, eigenvectors3 = LA.eig(cov3)\nprint('Eigen values', eigenvalues3)\nprint('Eigen vectors', eigenvectors3)\nax3.add_patch(patches.Polygon(xy3, fill=False))\nax3.quiver(mean3[0],mean3[1],eigenvectors3[0,0],eigenvectors3[0,1], color=['r'],scale=5, label=\"eigen vector[0]\")\nax3.quiver(mean3[0],mean3[1],eigenvectors3[1,0],eigenvectors3[1,1], color=['g'],scale=5, label=\"eigen vector[1]\")\n\n\nax4 = fig.add_subplot(325, aspect='equal')\n# Parallelogram \nxy4 = np.array([[0,0], [1,3], [5,3],[4,0]])\nmean4 = np.mean(xy4, axis=0)\nprint('Mean', mean4)\ncov4 = np.cov(xy4.T)\nprint('Cov::')\nprint(cov4)\neigenvalues4, eigenvectors4 = LA.eig(cov4)\nprint('Eigen values', eigenvalues4)\nprint('Eigen vectors', eigenvectors4)\nax4.add_patch(patches.Polygon(xy4, fill=False))\nax4.quiver(mean4[0],mean4[1],eigenvectors4[0,0],eigenvectors4[0,1], color=['r'],scale=5, label=\"eigen vector[0]\")\nax4.quiver(mean4[0],mean4[1],eigenvectors4[1,0],eigenvectors4[1,1], color=['g'],scale=5, label=\"eigen vector[1]\")\nplt.show() \n", "meta": {"hexsha": "c5f75b5aed2894b89abce872228d84b2bee5e263", "size": 3143, "ext": "py", "lang": "Python", "max_stars_repo_path": "Supervised Learning/SMAI HWS/8/3.py", "max_stars_repo_name": "shailymishra/Machine-Learning-Advanced", "max_stars_repo_head_hexsha": "048e7c816f8c673c7b73ffb7555ebdfee6f0dc5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Supervised Learning/SMAI HWS/8/3.py", "max_issues_repo_name": "shailymishra/Machine-Learning-Advanced", "max_issues_repo_head_hexsha": "048e7c816f8c673c7b73ffb7555ebdfee6f0dc5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Supervised Learning/SMAI HWS/8/3.py", "max_forks_repo_name": "shailymishra/Machine-Learning-Advanced", "max_forks_repo_head_hexsha": "048e7c816f8c673c7b73ffb7555ebdfee6f0dc5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5465116279, "max_line_length": 113, "alphanum_fraction": 0.6986955138, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668734137681, "lm_q2_score": 0.9019206804839998, "lm_q1q2_score": 0.8849346941377042}}
{"text": "'''\nThe NumPy ndarray: A Multidimensional Array Object\n\nOne of the key features of NumPy is its N-dimensional array object, or ndarray,\nwhich is a fast, flexible container for large datasets in Python. \nArrays enable you to perform mathematical operations on whole blocks of data using similar syntax to the \nequivalent operations between scalar elements.\n'''\n\n'''\nProblem 2) \nGenerating random data using ndarray\n'''\n\nimport numpy as np\n\ndata1 = np.random.randn(3) # returns a random sample\nprint(data1) # run the program in python terminal to see the result --- row-vector with 3 elements is produced\n\ndata2 = np.random.randn(2,4) # returns a random array with 2 rows and 4 columns each\nprint(data2) # run the program in python terminal to see the result --- array with 2 rows and 4 columns is produced\n\n# performing mathematical operations on the ndarray\ndata3 = data2 * 5 # multiply each element by 5\nprint(data3)\n\n# produces a new array wherein each \"cell\" of data2 is added to each other\ndata4 = data2 + data2\nprint(data4)\n\n\n'''\nProblem 3)\nTo find size of each dimension of data4 produced above and also finding the data type of the array\n'''\n# to get the size of each dimension of data4 we use the shape method that returns the tuple\nprint(data4.shape) # prints a tuple (2, 4) indicating that there are 2 dimensions with size 4 each\n\n# to get the data type of the array we use the object dtype\nprint(data4.dtype) # prints float64 indicating each cell value is a floating-point value occupying 64 bits in memory\n", "meta": {"hexsha": "159658908ea042fb913286401396e56ad1d42817", "size": 1518, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy/numpy2.py", "max_stars_repo_name": "hegde10122/python_training", "max_stars_repo_head_hexsha": "cf7d375650aa918c822bfadfae92e0f50afaab7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy/numpy2.py", "max_issues_repo_name": "hegde10122/python_training", "max_issues_repo_head_hexsha": "cf7d375650aa918c822bfadfae92e0f50afaab7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy/numpy2.py", "max_forks_repo_name": "hegde10122/python_training", "max_forks_repo_head_hexsha": "cf7d375650aa918c822bfadfae92e0f50afaab7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0243902439, "max_line_length": 116, "alphanum_fraction": 0.7654808959, "include": true, "reason": "import numpy", "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069627, "lm_q2_score": 0.93721079754114, "lm_q1q2_score": 0.8848927498614364}}
{"text": "# strassens_algorithm.py\r\n\r\n# A demonstration of Strassen's subcubic runtime matrix multiplication \r\n# algorithm on square matrices using the divide and conquer model.\r\n\r\nimport numpy as np\r\n\r\ndef main():\r\n    m1 = np.array([[1,2],[3,4]])\r\n    m2 = np.array([[5,6],[7,8]])\r\n\r\n    print(\"The first square matrix is: \")\r\n    print(m1)\r\n    print(\"The second square matrix is: \")\r\n    print(m2)\r\n\r\n    output_matrix = strassens_algorithm(m1, m2)\r\n    expected_matrix = np.matmul(m1, m2)\r\n\r\n    print(\"When taking the dot product of m1 and m2 we expected an \\\r\noutput matrix of:\")\r\n    print(expected_matrix)\r\n    print(\"Using Strassen's subcubic runtime matrix multiplication \\\r\nalgorithm we got:\")\r\n    print(output_matrix)\r\n\r\ndef strassens_algorithm(m1, m2):\r\n    # Base case: A matrix of shape 1x1 is solved by default\r\n    if np.shape(m1) == (1, 1):\r\n        return np.asscalar(m1 * m2)\r\n\r\n    # Pre-calculate the n/2 value. We'll be using it a lot and it's the same \r\n    # for matrix 1 and matrix 2 since they have equivalent square dimensions.\r\n    n_over_2 = len(m1)//2\r\n\r\n    # Divide\r\n    # Create submatrix blocks from quadrants of m1\r\n    # |A B|\r\n    # |C D|\r\n    A = m1[0:n_over_2, 0:n_over_2]\r\n    B = m1[0:n_over_2, n_over_2:]\r\n    C = m1[n_over_2:, 0:n_over_2]\r\n    D = m1[n_over_2:, n_over_2:]\r\n\r\n    # Create submatrix blocks from quadrants of m2\r\n    # |E F|\r\n    # |G H|\r\n    E = m2[0:n_over_2, 0:n_over_2]\r\n    F = m2[0:n_over_2, n_over_2:]\r\n    G = m2[n_over_2:, 0:n_over_2]\r\n    H = m2[n_over_2:, n_over_2:]\r\n\r\n    # Conquer\r\n    # Calculate the 7 products: (elements matrix 1) * (elements matrix 2)\r\n    p1 = strassens_algorithm(A, F-H)        # p1 = A * (F - H)\r\n    p2 = strassens_algorithm(A+B, H)        # p2 = (A + B) * H\r\n    p3 = strassens_algorithm(C+D, E)        # p3 = (C + D) * E\r\n    p4 = strassens_algorithm(D, G-E)        # p4 = D * (G - E)\r\n    p5 = strassens_algorithm(A+D, E+H)      # p5 = (A + D) * (E + H)\r\n    p6 = strassens_algorithm(B-D, G+H)      # p6 = (B - D) * (G + H)\r\n    p7 = strassens_algorithm(A-C, E+F)      # p7 = (A - C) * (E + F)\r\n\r\n    # Combine\r\n    return np.array([[p5+p4-p2+p6, p1+p2],[p3+p4, p1+p5-p3-p7]])\r\n\r\nif __name__ == \"__main__\":\r\n    main()", "meta": {"hexsha": "a59c1ec4875830401a38c2564d02d4e60051d5da", "size": 2211, "ext": "py", "lang": "Python", "max_stars_repo_path": "Stanford/03_DivideAndConquerModel/3B_StrassensSubcubicMatrixMultiplication/strassens_algorithm.py", "max_stars_repo_name": "jeffvswanson/DataStructuresAndAlgorithms", "max_stars_repo_head_hexsha": "82605a1dea4e52480f006956645e812fe2cb02dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-07-10T21:51:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T01:52:53.000Z", "max_issues_repo_path": "Stanford/03_DivideAndConquerModel/3B_StrassensSubcubicMatrixMultiplication/strassens_algorithm.py", "max_issues_repo_name": "jeffvswanson/DataStructuresAndAlgorithms", "max_issues_repo_head_hexsha": "82605a1dea4e52480f006956645e812fe2cb02dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Stanford/03_DivideAndConquerModel/3B_StrassensSubcubicMatrixMultiplication/strassens_algorithm.py", "max_forks_repo_name": "jeffvswanson/DataStructuresAndAlgorithms", "max_forks_repo_head_hexsha": "82605a1dea4e52480f006956645e812fe2cb02dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0, "max_line_length": 78, "alphanum_fraction": 0.5848032564, "include": true, "reason": "import numpy", "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995752693049, "lm_q2_score": 0.916109614162018, "lm_q1q2_score": 0.88486988721922}}
{"text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n## jupyter console\n\nimport numpy as np\n\n##\ndata = [[1,2,3,4],[5,6,7,8]]\narr1 = np.array(data)\ntype(arr1)\narr1.ndim\narr1.shape\nnp.zeros((3,2))\nnp.empty((3,2,2))\nnp.arange(10)\n\n##\narr1 * arr1\narr1 * 0\narr1 + 1\n\n##\narr2 = np.arange(10)\narr2[2]\narr3 = np.array([[1,2,3],[4,5,6]])\narr3[0]\narr3[0][1]\n\n##\narr2[:3]\narr2[:-3]\narr3[1:, :2]\n\n##\narr3 < 5\narr3[arr3 < 5]\n\n##\narr4 = np.empty((8,4))\nfor i in range(8):\n    arr4[i] = i\narr4\n\n##\narr5 = np.arange(32).reshape((8,4))\narr5\n\n##\narr5.shape\narr6 = arr5.T\narr6.shape\n\n##\narr7 = np.random.randn(6, 3)\narr7\nnp.dot(arr7.T, arr7)\n\n##\narr8 = np.arange(16).reshape((2,2,4))\narr8\narr8.transpose((2, 1, 0))\n\n##\narr9 = np.arange(1, 17)\narr9\nnp.sqrt(arr9)\nnp.exp(arr9)\n\n## 用数组表达式代替循环: 矢量化\narr10 = np.arange(-5, 5, 0.01)\nxs, ys = np.meshgrid(arr10, arr10)\nys\nz = np.sqrt(xs ** 2 + ys ** 2)\nz\n\n## broadcast\narr11 = np.arange(12).reshape((3,4))\narr11\narr11[0]\narr11 - arr11[0]\n", "meta": {"hexsha": "126d8cfe04b573811e026200be1eec5689146024", "size": 952, "ext": "py", "lang": "Python", "max_stars_repo_path": "ML/learn/Python_For_Data_Analysis/base_numpy.py", "max_stars_repo_name": "qrsforever/workspace", "max_stars_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-06-07T03:20:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-07T09:14:26.000Z", "max_issues_repo_path": "ML/learn/Python_For_Data_Analysis/base_numpy.py", "max_issues_repo_name": "qrsforever/workspace", "max_issues_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ML/learn/Python_For_Data_Analysis/base_numpy.py", "max_forks_repo_name": "qrsforever/workspace", "max_forks_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.6097560976, "max_line_length": 37, "alphanum_fraction": 0.5903361345, "include": true, "reason": "import numpy", "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854138058637, "lm_q2_score": 0.9124361586911173, "lm_q1q2_score": 0.8848672777276979}}
{"text": "import numpy as np\nimport pandas as pd\nimport numpy as np\nfrom scipy.constants import G\nimport random\n\nrandom.seed(0)\n\n\ndef newton_equation(m1=1, m2=1, r=1, G=G):\n    \"\"\"\n    Newton´s Equation\n    :param m1: Mass first body in kg\n    :param m2: Mass second body in kg\n    :param r: Distance between m1 and m2 in meters\n    :param G: Gravitational constant\n    :return: Newtons equation in the Internation System of Units\n    \"\"\"\n    return G * m1 * m2 * (1 / r ** 2)\n\n\ndef movement_equation(x0=1, v=1, a=1, t=1):\n    return x0 + v * t + 0.5 * a * t * t\n\n\ndef make_newton(\n    samples=100,\n    m1_min=0.001,\n    m1_max=1,\n    m2_min=0.001,\n    m2_max=1,\n    r_min=1,\n    r_max=10,\n    G=G,\n    dataframe=True,\n):\n    \"\"\"\n    Creates a sample of data of the Newton Equation\n    :param samples: Number of samples\n    :param m1_min: Minimum value in the range of the mass of the first body\n    :param m1_max: Maximum value in the range of the mass of the first body\n    :param m2_min: Minimum value in the range of the mass of the second body\n    :param m2_max: Maximum value in the range of the mass of the second body\n    :param r_min: Minimum value of the distance between the bodies\n    :param r_max: Maximum value of the distance between the bodies\n    :param dataframe: wether it returns a dataframe or an array\n    :return: data sample\n    \"\"\"\n    data = []\n    for n in range(samples):\n        m1 = (m1_max - m1_min) * np.random.random() + m1_min\n        m2 = (m2_max - m2_min) * np.random.random() + m2_min\n        r = (r_max - r_min) * np.random.random() + r_min\n\n        data.append([m1, m2, r, newton_equation(m1=m1, m2=m2, r=r, G=G)])\n    if dataframe:\n        return pd.DataFrame(data=data, columns=[\"m1\", \"m2\", \"r\", \"f\"])\n    else:\n        return data\n\n\ndef make_movement_data(\n    samples=100,\n    x0_min=1,\n    x0_max=2,\n    v_min=1,\n    v_max=2,\n    a_min=1,\n    a_max=2,\n    t_min=1,\n    t_max=2,\n    dataframe=True,\n):\n    data = []\n    for n in range(samples):\n        x0 = (x0_max - x0_min) * np.random.random() + x0_min\n        v = (v_max - v_min) * np.random.random() + v_min\n        a = (a_max - a_min) * np.random.random() + a_min\n        t = (t_max - t_min) * np.random.random() + t_min\n\n        data.append([x0, v, a, t, movement_equation(x0=x0, v=v, a=a, t=t)])\n    if dataframe:\n        return pd.DataFrame(data=data, columns=[\"x0\", \"v\", \"a\", \"t\", \"pos\"])\n    else:\n        return data\n", "meta": {"hexsha": "cd46e5f7c4d30fc2cedba582dcee50952a8e30b0", "size": 2412, "ext": "py", "lang": "Python", "max_stars_repo_path": "make_data.py", "max_stars_repo_name": "cmougan/Newton-xAI", "max_stars_repo_head_hexsha": "e9afa4f81d140fc7e2b37c7168e16d5d7b74f703", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "make_data.py", "max_issues_repo_name": "cmougan/Newton-xAI", "max_issues_repo_head_hexsha": "e9afa4f81d140fc7e2b37c7168e16d5d7b74f703", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "make_data.py", "max_forks_repo_name": "cmougan/Newton-xAI", "max_forks_repo_head_hexsha": "e9afa4f81d140fc7e2b37c7168e16d5d7b74f703", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0465116279, "max_line_length": 76, "alphanum_fraction": 0.6106965174, "include": true, "reason": "import numpy,from scipy", "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692298333416, "lm_q2_score": 0.905989819748845, "lm_q1q2_score": 0.8848523794909524}}
{"text": "import numpy as np\n\n'''\n    This python code calculates the Min-Max Normalization\n\n    Min-max normalization is one of the most common ways to normalize data. \n    For every feature, the minimum value of that feature gets transformed into a 0, \n    the maximum value gets transformed into a 1, and every other value \n    gets transformed into a decimal between 0 and 1.\n\n    norm = [(x - X.min)/(X.max - X.min)]*(new_max - new_min) + new_min\n\n'''\n\ndef minmax_norm(X, npmin, diff, nmax, nmin):\n    return ( (X - npmin) / (diff) ) * (nmax-nmin) + nmin\n\n# Input the data array\ndata = [ 13, 15, 16, 16, 19, 20, 20, 21, 22, 22,\n         25, 25, 25, 25, 30, 33, 33, 35, 35, 35,\n         35, 36, 40, 45, 46, 52, 70]\n\n# Setting the new min and new max\nnmin = 0\nnmax = 1\n\n# Putting the data in new numpy array\nnparray = np.array(data)\n\n#------------- Normalizing the data --------------------------#\n# Difference between max nparray value and min nparray value\ndiff = nparray.max() - nparray.min()\nnpmin = nparray.min()\n\nndata = minmax_norm(nparray, npmin, diff, nmax, nmin)\n\nprint(ndata)\n\n# Getting the norm of 35\nnvalue = minmax_norm(35, npmin, diff, nmax, nmin)\nprint(np.round(nvalue, 2))\n", "meta": {"hexsha": "1f74a59ff226ccb72b6f3e6a99226155aac95efc", "size": 1183, "ext": "py", "lang": "Python", "max_stars_repo_path": "Normalization/minmax_edad.py", "max_stars_repo_name": "TheWorstOne/numpy-formulas", "max_stars_repo_head_hexsha": "093657d4a23dfe82685595254aae50e0c6e46afb", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-04-21T00:41:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T06:57:00.000Z", "max_issues_repo_path": "Normalization/minmax_edad.py", "max_issues_repo_name": "magabydelgado/numpy-formulas", "max_issues_repo_head_hexsha": "093657d4a23dfe82685595254aae50e0c6e46afb", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Normalization/minmax_edad.py", "max_forks_repo_name": "magabydelgado/numpy-formulas", "max_forks_repo_head_hexsha": "093657d4a23dfe82685595254aae50e0c6e46afb", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-22T03:04:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T18:59:33.000Z", "avg_line_length": 28.1666666667, "max_line_length": 84, "alphanum_fraction": 0.6432797971, "include": true, "reason": "import numpy", "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018383629826, "lm_q2_score": 0.9073122269997507, "lm_q1q2_score": 0.8848125517393686}}
{"text": "# -*- coding: utf-8 -*-\r\n\r\n'''\r\nUn-documented code (booo!) for trial documentation-sprint. \r\n'''\r\n\r\nimport numpy as np\r\n\r\n\r\n\r\n\r\ndef quadratic_formula(a,b,c):\r\n        \"\"\"Calculates the real roots for ax^2+bx+c=0\r\n\r\n        :param a: quadratic coefficient\r\n        :type a: float, optional\r\n        :param b: linear coefficient\r\n        :type b: float, optional\r\n        :param c: linear coefficient\r\n        :type c: float, optional\r\n        \r\n        :raises: raises ValueError if the discriminant is less than zero\r\n        :return: List of quadratic polynomial roots\r\n        :rtype: list\r\n        \"\"\"\r\n        d = b**2-4*a*c # discriminant\r\n\r\n        if d < 0:\r\n            raise ValueError(\"This equation has no real solution\")\r\n        elif d == 0:\r\n            x = (-b+np.sqrt(b**2-4*a*c))/2*a\r\n            sol = [x]\r\n            return sol\r\n        else:\r\n            x1 = (-b+np.sqrt(b**2-4*a*c))/2*a\r\n            x2 = (-b-np.sqrt(b**2-4*a*c))/2*a\r\n            sol = [x1, x2]\r\n            return sol\r\n\r\n\r\n# simple numerical integration of f(x) over an interval x: [x_lower, x_upper] using composite trapezoid rule.\r\n\r\ndef simple_integrate(f, x):\r\n    \"\"\"Computes the definite integral of a function from the lower to the upper limit using composite trapezoid rule.\r\n\r\n    :param f: function to be integrated.\r\n    :param x:  [x_lower, x_upper] lower limit of integration upper limit of integration\r\n    :raises: raises ValueError if the discriminant is less than zero\r\n    :return: integral value\r\n    :rtype: float\r\n    \"\"\"\r\n    int_sum = 0\r\n\r\n    for i in range(x.size-1):\r\n        int_sum += 0.5*(x[i+1] - x[i])*(f[i] + f[i+1])\r\n    \r\n    return int_sum\r\n\r\n\r\n# function for nth Fibonacci number \r\n  \r\ndef fibonacci(n): \r\n    \"\"\"Computes the nth fibonacci number, starting at 0.\r\n\r\n    :param n: the index of the Fibonacci number to be computed\r\n    :raises: raises ValueError if n is less than 1\r\n    :return: nth fibonacci number\r\n    :rtype: int\r\n    \"\"\"\r\n    if n<=0: \r\n        raise ValueError(\"Input cannot be less than 1\") \r\n    elif n==1: \r\n        return 0\r\n    elif n==2: \r\n        return 1\r\n    else: \r\n        return fibonacci(n-1)+fibonacci(n-2)  \r\n\r\n\r\n\r\n# convert time in seconds to hours, minutes and seconds\r\n\r\ndef get_hms(t_sec):\r\n    \"\"\"Converts time in seconds to hours, minutes, and seconds.\r\n\r\n    :param t_sec: time in seconds\r\n    :return: time in hours, minutes, and seconds\r\n    :rtype: list\r\n    \"\"\"\r\n\r\n    h = t_sec//3600\r\n\r\n    m = (t_sec - h*3600)//60\r\n\r\n    s = t_sec%60\r\n\r\n    return h,m,s #question: does it return a list? Or maybe not?\r\n\r\n", "meta": {"hexsha": "12754b8053754a01611701eeac935c143bbe13aa", "size": 2583, "ext": "py", "lang": "Python", "max_stars_repo_path": "Sprint 1 code.py", "max_stars_repo_name": "kathkryu/Sprint1", "max_stars_repo_head_hexsha": "d99c77c7c30483b80b6da127304640e8debc87b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sprint 1 code.py", "max_issues_repo_name": "kathkryu/Sprint1", "max_issues_repo_head_hexsha": "d99c77c7c30483b80b6da127304640e8debc87b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sprint 1 code.py", "max_forks_repo_name": "kathkryu/Sprint1", "max_forks_repo_head_hexsha": "d99c77c7c30483b80b6da127304640e8debc87b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0909090909, "max_line_length": 118, "alphanum_fraction": 0.5710414247, "include": true, "reason": "import numpy", "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075711974104, "lm_q2_score": 0.9196425328295899, "lm_q1q2_score": 0.8847950436305114}}
{"text": "import numpy as np\n\n\ndef R(theta):\n    \"\"\"\n        Returns the rotation matrix for rotating an object\n        centered around the origin with a given angle\n\n        Arguments:\n            theta: angle in degrees\n\n        Returns:\n            R: 2x2 np.ndarray with rotation matrix\n    \"\"\"\n    theta = np.radians(theta)\n    return np.array(\n        [[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]\n    )\n\n\ndef M(axis=\"x\"):\n    \"\"\"\n        Returns a matrix to mirror an object against a given axis\n\n        Arguments:\n            axis: str. 'x', 'y', 'origin' or 'xy'\n\n        Returns:\n            M: mirror matrix\n    \"\"\"\n    if axis == \"x\":\n        return np.array([[1, 0], [0, -1]])\n    elif axis == \"y\":\n        return np.array([[-1, 0], [0, 1]])\n    elif axis == \"origin\":\n        return np.array([[-1, 0], [0, -1]])\n    elif axis == \"xy\":\n        return np.array([[0, 1], [1, 0]])\n    else:\n        raise NotImplementedError(\n            f\"Could not recognize axis of mirroring: {axis}\"\n        )\n\n\ndef cart2pol(x, y):\n    \"\"\"\n        Cartesian to polar coordinates\n\n        angles in degrees\n    \"\"\"\n    rho = np.hypot(x, y)\n    phi = np.degrees(np.arctan2(y, x))\n    return rho, phi\n\n\ndef pol2cart(rho, phi):\n    \"\"\"\n        Polar to cartesian coordinates\n\n        angles in degrees\n    \"\"\"\n    x = rho * np.cos(np.radians(phi))\n    y = rho * np.sin(np.radians(phi))\n    return x, y\n", "meta": {"hexsha": "f76668ec76c9119ef8a15021e0295d7ef71c2030", "size": 1406, "ext": "py", "lang": "Python", "max_stars_repo_path": "fcutils/maths/coordinates.py", "max_stars_repo_name": "FedeClaudi/fedes_utils", "max_stars_repo_head_hexsha": "2ef6f037303fc426d5c5b2851d2c99f17efa4002", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-19T23:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:41:33.000Z", "max_issues_repo_path": "fcutils/maths/coordinates.py", "max_issues_repo_name": "FedeClaudi/fedes_utils", "max_issues_repo_head_hexsha": "2ef6f037303fc426d5c5b2851d2c99f17efa4002", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-21T13:09:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T10:50:14.000Z", "max_forks_repo_path": "fcutils/maths/coordinates.py", "max_forks_repo_name": "FedeClaudi/fedes_utils", "max_forks_repo_head_hexsha": "2ef6f037303fc426d5c5b2851d2c99f17efa4002", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6307692308, "max_line_length": 73, "alphanum_fraction": 0.5199146515, "include": true, "reason": "import numpy", "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446425653806, "lm_q2_score": 0.9086179000259899, "lm_q1q2_score": 0.8846709504993117}}
{"text": "\"\"\"\nauthor: Fabian Schaipp\n\"\"\"\n\nimport numpy as np\n\nclass f_rosenbrock:\n    \"\"\"\n    Nonsmooth Rosenbrock function (see 5.1 in Curtis, Overton \"SQP FOR NONSMOOTH CONSTRAINED OPTIMIZATION\")\n    \n    x -> w|x_1^2 − x_2| + (1 − x_1)^2\n    \"\"\"\n    def __init__(self, w = 8):\n        self.name = 'rosenbrock'\n        self.dim = 2\n        self.dimOut = 1\n        self.w = w\n        \n    def eval(self, x):    \n        return self.w*np.abs(x[0]**2-x[1]) + (1-x[0])**2\n    \n    def differentiable(self, x):\n        return np.abs(x[0]**2 - x[1]) > 1e-10\n    \n    def grad(self, x):\n        a = np.array([-2+x[0], 0])    \n        sign = np.sign(x[0]**2 -x[1])\n    \n        if sign == 1:\n            b = np.array([2*x[0], -1])\n        elif sign == -1:\n            b = np.array([-2*x[0], 1])\n        else:\n            b = np.array([-2*x[0], 1])\n         \n        #b = np.sign(x[0]**2 -x[1]) * np.array([2*x[0], -1])       \n        return a + b\n    \nclass g_max:\n    \"\"\"\n    maximum function (see 5.1 in Curtis, Overton \"SQP FOR NONSMOOTH CONSTRAINED OPTIMIZATION\")\n    \n    x -> max(c1*x_1, c2*x_2) - 1\n    \"\"\"\n    def __init__(self, c1 = np.sqrt(2), c2 = 2.):\n        self.name = 'max'        \n        self.c1 = c1\n        self.c2 = c2\n        self.dimOut = 1\n        return\n    \n    def eval(self, x):\n        return np.maximum(self.c1*x[0], self.c2*x[1]) - 1\n    \n    def differentiable(self, x):\n        return np.abs(self.c1*x[0] -self.c2*x[1]) > 1e-10\n    \n    def grad(self, x):\n        \n        sign = np.sign(self.c1*x[0] - self.c2*x[1])\n        if sign == 1:\n            g = np.array([self.c1, 0])\n        elif sign == -1:\n            g = np.array([0, self.c2])\n        else:\n            g = np.array([0, self.c2])\n        return g\n\nclass g_linear:\n    \"\"\"\n    linear constraint:\n    \n    x -> Ax - b\n    \"\"\"\n    def __init__(self, A, b):\n        self.name = 'linear' \n        self.A = A\n        self.b = b\n        self.dim = A.shape[0]\n        self.dimOut = A.shape[1]\n        return\n    \n    def eval(self, x):\n        return self.A @ x - self.b\n    \n    def differentiable(self, x):\n        return True\n    \n    def grad(self, x):\n        return self.A\n    \n\n", "meta": {"hexsha": "7aea4066d04ca875d7669e6db9b800a9b848453a", "size": 2159, "ext": "py", "lang": "Python", "max_stars_repo_path": "ncopt/funs.py", "max_stars_repo_name": "fabian-sp/ncOPT", "max_stars_repo_head_hexsha": "742c126da755558900837c868de77ba0083d41ad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-11-19T03:32:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T05:35:16.000Z", "max_issues_repo_path": "ncopt/funs.py", "max_issues_repo_name": "fabian-sp/ncOPT", "max_issues_repo_head_hexsha": "742c126da755558900837c868de77ba0083d41ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ncopt/funs.py", "max_forks_repo_name": "fabian-sp/ncOPT", "max_forks_repo_head_hexsha": "742c126da755558900837c868de77ba0083d41ad", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2150537634, "max_line_length": 107, "alphanum_fraction": 0.4576192682, "include": true, "reason": "import numpy", "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446502128797, "lm_q2_score": 0.9086178882719769, "lm_q1q2_score": 0.8846709460037343}}
{"text": "import numpy as np\r\ndef LM(f,a,b,n):\r\n    # Carries out the numerical integration using the Left Hand Rule\r\n    # INPUT: f , a , b , n\r\n    # f : function which is the integrand\r\n    # a : lower limit of the interval\r\n    # b : upper limit of the interval\r\n    # n : number of sub-intervals\r\n\r\n    # makes sure the input format is correct\r\n    if (b < a) :\r\n        print('Input Error: Lower limit(a) must be < Upper limit(b)')\r\n        exit()\r\n    # limits the maximum number of iterations to 1 million\r\n    if (n > 1000000) :\r\n        print('Input Error: No more than 1 million divisions are allowed!')\r\n        exit()\r\n    # calculate the step size or length of each sub-interval\r\n    h = (b - a)/n\r\n    #step.append(h)\r\n    # calculates the numerical integration using Left Hand Rule\r\n    area = 0\r\n    for i in range(n):\r\n        x = a + float(i*h)\r\n        area = area + f(x)*h\r\n    # calculates error\r\n    err = 1 - area\r\n    rel_err = np.abs(err)*100\r\n    #abs_err.append(np.abs(err))\r\n    print('---------------------------------------------------')\r\n    print('NUMERICAL QUADRATURE RESULTS : LEFT-ENDPOINT METHOD')\r\n    print('---------------------------------------------------')\r\n    print('Integrating from %8.2f    to %8.2f   in %5d steps' %(a,b,n))\r\n    print('Area           = %10.4f units\\u00b2'%(area))\r\n    print('Error          = %10.4f'%err)\r\n    print('Absolute Error = %10.4f '%(np.abs(err)))\r\n    print('Relative Error = %10.4f'%rel_err)\r\n    print('---------------------------------------------------')\r\n    return h,np.abs(err)\r\ndef RM(f,a,b,n):\r\n    # Carries out the numerical integration using the Right Hand Rule\r\n    # INPUT: f , a , b , n\r\n    # f : function which is the integrand\r\n    # a : lower limit of the interval\r\n    # b : upper limit of the interval\r\n    # n : number of sub-intervals\r\n\r\n    # makes sure the input format is correct\r\n    if (b < a) :\r\n        print('Input Error: Lower limit(a) must be < Upper limit(b)')\r\n        exit()\r\n    # limits the maximum number of iterations to 1 million\r\n    if (n > 1000000) :\r\n        print('Input Error: No more than 1 million divisions are allowed!')\r\n        exit()\r\n    # calculate the step size or length of each sub-interval\r\n    h = (b - a)/n\r\n    #step.append(h)\r\n    # calculates the numerical integration using Right Hand Rule\r\n    area = 0\r\n    for i in range(1,n+1):\r\n        x = a + float(i*h)\r\n        area = area + f(x)*h\r\n    # calculates error\r\n    err = 1 - area\r\n    rel_err = np.abs(err)*100\r\n    #abs_err.append(np.abs(err))\r\n    print('---------------------------------------------------')\r\n    print('NUMERICAL QUADRATURE RESULTS : RIGHT-ENDPOINT METHOD')\r\n    print('---------------------------------------------------')\r\n    print('Integrating from %8.2f    to %8.2f   in %5d steps' %(a,b,n))\r\n    print('Area           = %10.4f units\\u00b2'%(area))\r\n    print('Error          = %10.4f'%err)\r\n    print('Absolute Error = %10.4f '%(np.abs(err)))\r\n    print('Relative Error = %10.4f'%rel_err)\r\n    print('---------------------------------------------------')\r\n    return h,np.abs(err)\r\ndef MpM(f,a,b,n):\r\n    # Carries out the numerical integration using the Midpoint Rule\r\n    # INPUT: f , a , b , n\r\n    # f : function which is the integrand\r\n    # a : lower limit of the interval\r\n    # b : upper limit of the interval\r\n    # n : number of sub-intervals\r\n\r\n    # makes sure the input format is correct\r\n    if (b < a) :\r\n        print('Input Error: Lower limit(a) must be < Upper limit(b)')\r\n        exit()\r\n    # limits the maximum number of iterations to 1 million\r\n    if (n > 1000000) :\r\n        print('Input Error: No more than 1 million divisions are allowed!')\r\n        exit()\r\n    # calculate the step size or length of each sub-interval\r\n    h = (b - a)/n\r\n    #step.append(h)\r\n    # calculates the numerical integration using Midpoint Rule\r\n    area = 0\r\n    for i in range(n):\r\n        x = a + float((i+0.5)*h)\r\n        area = area + f(x)*h\r\n    # calculates error\r\n    err = 1 - area\r\n    rel_err = np.abs(err)*100\r\n    #abs_err.append(np.abs(err))\r\n    print('---------------------------------------------------')\r\n    print('NUMERICAL QUADRATURE RESULTS : MIDPOINT METHOD')\r\n    print('---------------------------------------------------')\r\n    print('Integrating from %8.2f    to %8.2f   in %5d steps' %(a,b,n))\r\n    print('Area           = %10.4f units\\u00b2'%(area))\r\n    print('Error          = %10.4f'%err)\r\n    print('Absolute Error = %10.4f '%(np.abs(err)))\r\n    print('Relative Error = %10.4f'%rel_err)\r\n    print('---------------------------------------------------')\r\n    return h,np.abs(err)\r\ndef TM(f,a,b,n):\r\n    # Carries out the numerical integration using the Trapezoidal Rule\r\n    # INPUT: f , a , b , n\r\n    # f : function which is the integrand\r\n    # a : lower limit of the interval\r\n    # b : upper limit of the interval\r\n    # n : number of sub-intervals\r\n\r\n    # makes sure the input format is correct\r\n    if (b < a) :\r\n        print('Input Error: Lower limit(a) must be < Upper limit(b)')\r\n        exit()\r\n    # limits the maximum number of iterations to 1 million\r\n    if (n > 1000000) :\r\n        print('Input Error: No more than 1 million divisions are allowed!')\r\n        exit()\r\n    # calculate the step size or length of each sub-interval\r\n    h = (b - a)/n\r\n    #step.append(h)\r\n    # calculates the numerical integration using Trapezoidal Rule\r\n    area = f(float(a))*h/2\r\n    for i in range(1,n):\r\n        x = a + float(i*h)\r\n        area = area + f(x)*h\r\n    area = area + f(float(b))*h/2\r\n    # calculates error\r\n    err = 1 - area\r\n    rel_err = np.abs(err)*100\r\n    #abs_err.append(np.abs(err))\r\n    print('---------------------------------------------------')\r\n    print('NUMERICAL QUADRATURE RESULTS : TRAPEZOID METHOD')\r\n    print('---------------------------------------------------')\r\n    print('Integrating from %8.2f    to %8.2f   in %5d steps' %(a,b,n))\r\n    print('Area           = %10.4f units\\u00b2'%(area))\r\n    print('Error          = %10.4f'%err)\r\n    print('Absolute Error = %10.4f '%(np.abs(err)))\r\n    print('Relative Error = %10.4f'%rel_err)\r\n    print('---------------------------------------------------')\r\n    return h,np.abs(err)\r\n", "meta": {"hexsha": "598d68e1d7629ca33b4d1b2bdb04f1995d7acf87", "size": 6218, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numerical_Quadrature.py", "max_stars_repo_name": "YashIITM/Numerical-Quadrature", "max_stars_repo_head_hexsha": "628d72f3397c104a1309dc30444a629a49945573", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numerical_Quadrature.py", "max_issues_repo_name": "YashIITM/Numerical-Quadrature", "max_issues_repo_head_hexsha": "628d72f3397c104a1309dc30444a629a49945573", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numerical_Quadrature.py", "max_forks_repo_name": "YashIITM/Numerical-Quadrature", "max_forks_repo_head_hexsha": "628d72f3397c104a1309dc30444a629a49945573", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1161290323, "max_line_length": 76, "alphanum_fraction": 0.5172081055, "include": true, "reason": "import numpy", "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914017797636, "lm_q2_score": 0.9149009584734676, "lm_q1q2_score": 0.8846305616444887}}
{"text": "from sympy import *\n\nx, y, a, b = symbols('x y a b')\nall_symbols = [a,b]\n\ntarget_value = y\nmodel_function = a*x + b\nobs_eq = Matrix([target_value - model_function]).vec()\nobs_eq_jacobian = obs_eq.jacobian(all_symbols)\n\nprint(model_function)\nprint(obs_eq)\nprint(obs_eq_jacobian)\nprint(latex(model_function))\nprint(latex(obs_eq_jacobian))\n\nwith open(\"example_func_ax_plus_b_eq_y_jacobian.h\",'w') as f_cpp:  \n    f_cpp.write(\"inline void example_func_ax_plus_b(double &y, double x, double a, double b)\\n\")\n    f_cpp.write(\"{\")\n    f_cpp.write(\"y = %s;\\n\"%(ccode(model_function)))\n    f_cpp.write(\"}\")\n    f_cpp.write(\"\\n\")\n    f_cpp.write(\"inline void observation_equation_example_func_ax_plus_b_eq_y(double &delta, double x, double y, double a, double b)\\n\")\n    f_cpp.write(\"{\")\n    f_cpp.write(\"delta = %s;\\n\"%(ccode(obs_eq[0,0])))\n    f_cpp.write(\"}\")\n    f_cpp.write(\"\\n\")\n    f_cpp.write(\"inline void observation_equation_example_func_ax_plus_b_eq_y_jacobian(Eigen::Matrix<double, 1, 2> &j, double x, double y, double a, double b)\\n\")\n    f_cpp.write(\"{\")\n    for i in range (1):\n        for j in range (2):\n            f_cpp.write(\"j.coeffRef(%d,%d) = %s;\\n\"%(i,j, ccode(obs_eq_jacobian[i,j])))\n    f_cpp.write(\"}\")\n  \n\n\n  \n\n", "meta": {"hexsha": "ddf72c2d7548553fc91d59b4d2014b6e8a4ee936", "size": 1229, "ext": "py", "lang": "Python", "max_stars_repo_path": "codes/python-scripts/example_func/example_func_ax_plus_b_eq_y_jacobian.py", "max_stars_repo_name": "JanuszBedkowski/observation_equations", "max_stars_repo_head_hexsha": "ab241f571a655aebc89870f54e01cb7347382aa9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-11T13:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T22:04:00.000Z", "max_issues_repo_path": "codes/python-scripts/example_func/example_func_ax_plus_b_eq_y_jacobian.py", "max_issues_repo_name": "JanuszBedkowski/observation_equations", "max_issues_repo_head_hexsha": "ab241f571a655aebc89870f54e01cb7347382aa9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/python-scripts/example_func/example_func_ax_plus_b_eq_y_jacobian.py", "max_forks_repo_name": "JanuszBedkowski/observation_equations", "max_forks_repo_head_hexsha": "ab241f571a655aebc89870f54e01cb7347382aa9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-30T22:33:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T18:21:21.000Z", "avg_line_length": 31.5128205128, "max_line_length": 162, "alphanum_fraction": 0.672091131, "include": true, "reason": "from sympy", "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214480969029, "lm_q2_score": 0.9173026658028078, "lm_q1q2_score": 0.884574635030113}}
{"text": "# solutions.py\n\"\"\"Volume I: Monte Carlo Integration\nSolutions file. Written by Tanner Christensen, Jan 2016\nEdited by Jessica Morrise, May 2016\n\"\"\"\n\nimport numpy as np\nimport scipy.stats as stats\nfrom matplotlib import pyplot as plt\n    \ndef prob1(N=10000):\n    \"\"\"Return an estimate of the volume of the unit sphere using Monte\n    Carlo Integration.\n\n    Input:\n        N (int, optional) - The number of points to sample. Defaults\n            to 10000.\n    \n    \"\"\"\n    points = np.random.rand(3, N)\n    points = points*2 - 1\n    radii = np.linalg.norm(points,axis=0)\n    numInSphere = np.count_nonzero(radii <= 1)\n    return 8.*numInSphere/N\n    \ndef prob2(f, a, b, N=10000):\n    \"\"\"Use Monte-Carlo integration to approximate the integral of \n    1-D function f on the interval [a,b].\n    \n    Inputs:\n        f (function) - Function to integrate. Should take scalar input.\n        a (float) - Left-hand side of interval.\n        b (float) - Right-hand side of interval.\n        N (int, optional) - The number of points to sample in \n            the Monte-Carlo method. Defaults to 10000.\n        \n    Returns:\n        estimate (float) - The result of the Monte-Carlo algorithm.\n                \n    Example:\n        >>> f = lambda x: x**2\n        >>> # Integral from 0 to 1. True value is 1/3.\n        >>> prob2(f, 0, 1)\n        0.3333057231764805\n    \"\"\"\n    points = np.random.rand(1,N)\n    V = b-a\n    points = V*points + a\n    fPoints = np.apply_along_axis(f,0,points)\n    return V*np.sum(fPoints)/float(N)\n    \ndef prob3(f, mins, maxs, N=10000):\n    \"\"\"Use Monte-Carlo integration to approximate the integral of f\n    on the box defined by mins and maxs.\n    \n    Inputs:\n        f (function) - The function to integrate. This function should \n            accept a 1-D NumPy array as input.\n        mins (1-D np.ndarray) - Minimum bounds on integration.\n        maxs (1-D np.ndarray) - Maximum bounds on integration.\n        N (int, optional) - The number of points to sample in \n            the Monte-Carlo method. Defaults to 10000.\n        \n    Returns:\n        estimate (float) - The result of the Monte-Carlo algorithm.\n                \n    Example:\n        >>> f = lambda x: np.hypot(x[0], x[1]) <= 1\n        >>> # Integral over the square [-1,1] x [-1,1]. True value is pi.\n        >>> mc_int(f, np.array([-1,-1]), np.array([1,1]))\n        3.1290400000000007\n    \"\"\"\n    if len(mins) != len(maxs):\n        raise ValueError(\"Dimension of mins and maxs must be the same\")\n    \n    # create points\n    dim = len(mins)\n    side_lengths = maxs-mins\n    points = np.random.rand(N,dim)\n    points = side_lengths*points + mins\n\n    # calculate Volume\n    V = 1\n    for i in xrange(dim):\n        V *= maxs[i] - mins[i]\n\n    # apply the function f along axis=1 and sum all the results\n    estimate = V*np.sum(np.apply_along_axis(f,1,points))/float(N)\n    \n    return estimate\n    \ndef prob4():\n    \n    #define the joint normal distribution\n    joint_normal = lambda x: 1/(2*np.pi)**(len(x)/2.)*np.exp(-x.T.dot(x)/2.)    \n    \n    mins = np.array([-1.5,0,0,0])\n    maxs = np.array([0.75,1,0.5,1])\n    means = np.zeros(4)\n    covs = np.eye(4)\n    \n    my_value = prob3(joint_normal,mins,maxs,50000)  \n    scipy_value, inform = stats.mvn.mvnun(mins, maxs, means, covs)\n    err = np.abs(my_value - scipy_value)/abs(scipy_value) # relative error\n    return my_value, scipy_value, err  \n    \ndef prob5(numEstimates=50):\n    \"\"\"Plot the error of Monte Carlo Integration.\n    \"\"\"\n\n    # actual volume of the unit sphere\n    actual = 4.1887902047863905\n    \n    # construct an array of values of N\n    # use closer-spaced values near 50\n    N = [i*1000 for i in xrange(1,51)]\n    N = [50,100,500] + N\n    errors = []    \n    \n    for n in N:\n        meanErr = 0.\n        for i in xrange(numEstimates):\n            I = prob1(n) # estimate the integral\n            err = np.abs(I - actual)/actual # compute the relative error\n            meanErr += err\n        errors.append(meanErr/float(numEstimates))\n    \n    # create the plot\n    plt.plot(N,errors,label='Error')\n    plt.plot(N,[1./n**0.5 for n in N],'r--',label=r'$1/\\sqrt{N}$')\n    plt.ylim([0,max(errors)])\n    plt.xlim([0,max(N)])\n    plt.xlabel(r'$N$')\n    plt.ylabel('Relative error')\n    plt.title('Sphere volume error vs. number of points used')\n    plt.legend()\n    plt.show()\n    \nif __name__ == \"__main__\":\n    print prob1()\n", "meta": {"hexsha": "348115abc502f7b17a14bc95d04f554b8b88188e", "size": 4387, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol1B/MonteCarlo1-Integration/solutions.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vol1B/MonteCarlo1-Integration/solutions.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vol1B/MonteCarlo1-Integration/solutions.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 31.1134751773, "max_line_length": 80, "alphanum_fraction": 0.5965352177, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.9465966747198242, "lm_q1q2_score": 0.8844953571942237}}
{"text": "import numpy as np\na = np.array([0, 0.5, 1.0, 1.5, 2.0])\ntype(a)\na[:2]  # Slicing works as for lists\n\n# Built in methods\na.sum()\na.std()\na.cumsum()\na.max()\na.argmax()\n\n# Careful with np.max!\nnp.max(2, 0)\nnp.max(-2, 0)  # silent fail :) second argument is the axis\nnp.max(0, 2)  # fail\nnp.maximum(-2, 0)\n\n# Vectorized operations: operations are applied to each element\na*2\na**2\nnp.sqrt(a)\nnp.log2(a+1)\n\nb = np.array([a, a*2])\nb\n\nb.sum(axis=0)  # sum along axis 0 ==> columns\nb.sum()\nb.sum(axis=1)\n\n\neye = np.identity(4)\neye\n\nnp.ones_like(eye)\nnp.ones((2,3))\n\nzeros = np.zeros((2,3,4))\nzeros.shape\nzeros[1]\n\n\n# Optimized for speed!\nimport time\nstart = time.time()\nacc = 0\nfor i in range(1000):\n    for j in range(1000):\n        acc += np.random.standard_normal()\nend = time.time()\nprint(\"It took (ms): \", (end-start)*1000)\n\n# Numpy outsources the loops to underlying C code for performance\n# %timeit test = np.random.standard_normal((1000,1000)).sum()\n\n# CODE VECTORIZATION\nr = np.random.standard_normal((4,3))\ns = np.random.standard_normal((4,3))\nr+s\n\n# Broadcasting\n2*r+3 # same as 2*r+3*np.ones_like(r)\n\n########################################\n########################################\n######## MOVE TO BROWSER HERE\n########################################\n########################################\n\n# Functions are applied element-wise.\ndef f(x):\n    return 3*x+5\n\nf(3)\nf(r)\n\nimport math\nmath.sin(math.pi)\nmath.sin(r)  # Error: this function only takes real numbers!\nnp.sin(r)\ntype(np.sin)  # ufunc: universal function (works with arrays too)\n", "meta": {"hexsha": "32d866ad9b2e3295fbd612d83c997f1bcade9299", "size": 1544, "ext": "py", "lang": "Python", "max_stars_repo_path": "02 Code vectorization and numpy.py", "max_stars_repo_name": "jpmaldonado/python4finance", "max_stars_repo_head_hexsha": "d21f772e79f9b1b10ecc71c69d088c69c3bea1fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "02 Code vectorization and numpy.py", "max_issues_repo_name": "jpmaldonado/python4finance", "max_issues_repo_head_hexsha": "d21f772e79f9b1b10ecc71c69d088c69c3bea1fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02 Code vectorization and numpy.py", "max_forks_repo_name": "jpmaldonado/python4finance", "max_forks_repo_head_hexsha": "d21f772e79f9b1b10ecc71c69d088c69c3bea1fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6024096386, "max_line_length": 65, "alphanum_fraction": 0.5900259067, "include": true, "reason": "import numpy", "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924777713886, "lm_q2_score": 0.909906999319571, "lm_q1q2_score": 0.8844227588101591}}
{"text": "import numpy as np\n\nfrom utils_2nd_version import inc_index, dec_index, \\\n                              constraint_inequalities_funcs_generator\n\ndef gradient_approximation(f,x,h=1e-8):\n    '''\n    Numerical approximation of gradient for function f using forward differences.\n    Args:\n        f (lambda expression): definition of function f.\n        x (array): numpy array that holds values where gradient will be computed.\n        h (float): step size for forward differences, tipically h=1e-8\n    Returns:\n        gf (array): numerical approximation to gradient of f.\n    '''\n    n = x.size\n    gf = np.zeros(n)\n    f_x = f(x)\n    for i in np.arange(n):\n        inc_index(x,i,h)\n        gf[i] = f(x) - f_x\n        dec_index(x,i,h)\n    return gf/h\ndef Hessian_approximation(f,x,h=1e-6):\n    '''\n    Numerical approximation of Hessian for function f using forward differences.\n    Args:\n        f (lambda expression): definition of function f.\n        x (array): numpy array that holds values where Hessian will be computed.\n        h (float): step size for forward differences, tipically h=1e-6\n    Returns:\n        Hf (array): numerical approximation to Hessian of f.\n    '''\n    n = x.size\n    Hf = np.zeros((n,n))\n    f_x = f(x)\n    for i in np.arange(n):\n        inc_index(x,i,h)\n        f_x_inc_in_i = f(x)\n        for j in np.arange(i,n):\n            inc_index(x,j,h)\n            f_x_inc_in_i_j = f(x)\n            dec_index(x,i,h)\n            f_x_inc_in_j = f(x)\n            dif = f_x_inc_in_i_j-f_x_inc_in_i-f_x_inc_in_j+f_x\n            Hf[i,j] = dif\n            if j != i:\n                Hf[j,i] = dif\n            dec_index(x,j,h)\n            inc_index(x,i,h)\n        dec_index(x,i,h)\n    return Hf/h**2\ndef numerical_differentiation_of_logarithmic_barrier(f, x, t_path, constraint_inequalities,\n                                                     infeasible = None):\n    '''\n    First and second derivative of logarithmic barrier function approximation\n    via finite differences\n    '''\n    sum_gf_const = 0\n    sum_Hf_const = 0\n    for const in constraint_inequalities_funcs_generator(constraint_inequalities):\n        const_eval = const(x)\n        gf_const_eval = gradient_approximation(const, x)\n        Hf_const_eval = Hessian_approximation(const, x)\n        sum_gf_const += gf_const_eval/(-const_eval) if not infeasible else \\\n                        gf_const_eval/(infeasible - const_eval)\n        if not infeasible:\n            sum_Hf_const += np.outer(gf_const_eval,gf_const_eval)/const_eval**2 - Hf_const_eval/const_eval\n        else:\n            sum_Hf_const += np.outer(gf_const_eval,gf_const_eval)/(infeasible - const_eval)**2 + \\\n                            Hf_const_eval/(infeasible - const_eval)\n    gf_eval = gradient_approximation(f,x)\n    Hf_eval = Hessian_approximation(f,x)\n    return {'gradient': t_path*gf_eval + sum_gf_const,\n            'Hessian': t_path*Hf_eval + sum_Hf_const\n           }", "meta": {"hexsha": "463564b0b5f9402b92d7f37202680a1106bb2d3d", "size": 2927, "ext": "py", "lang": "Python", "max_stars_repo_path": "temas/IV.optimizacion_convexa_y_machine_learning/algoritmos/Python/numerical_differentiation_2nd_version.py", "max_stars_repo_name": "Danahirmt/analisis-numerico-computo-cientifico", "max_stars_repo_head_hexsha": "ec42457dc8f707ce8d481cb62441d29fc0a9ab52", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "temas/IV.optimizacion_convexa_y_machine_learning/algoritmos/Python/numerical_differentiation_2nd_version.py", "max_issues_repo_name": "Danahirmt/analisis-numerico-computo-cientifico", "max_issues_repo_head_hexsha": "ec42457dc8f707ce8d481cb62441d29fc0a9ab52", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "temas/IV.optimizacion_convexa_y_machine_learning/algoritmos/Python/numerical_differentiation_2nd_version.py", "max_forks_repo_name": "Danahirmt/analisis-numerico-computo-cientifico", "max_forks_repo_head_hexsha": "ec42457dc8f707ce8d481cb62441d29fc0a9ab52", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5131578947, "max_line_length": 106, "alphanum_fraction": 0.6132558934, "include": true, "reason": "import numpy", "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741322079103, "lm_q2_score": 0.9284087965937711, "lm_q1q2_score": 0.8843782037495018}}
{"text": "import sympy\nfrom typing import Tuple\n\ndef sym_skew(vec: sympy.Matrix) -> sympy.Matrix:\n    vec = vec.reshape(1, 3)\n    return sympy.Matrix([\n        [0, -vec[2], vec[1]],\n        [vec[2], 0, -vec[0]],\n        [-vec[1], vec[0], 0]\n    ])\n\ndef sym_vex(skewmat: sympy.Matrix) -> sympy.Matrix:\n    return sympy.Matrix([skewmat[2, 1], skewmat[0, 2], skewmat[1, 0]])\n\ndef sym_no_rot() -> sympy.Matrix:\n    return sympy.Matrix([\n        [1, 0, 0],\n        [0, 1, 0],\n        [0, 0, 1]\n    ])\n\ndef sym_hom_no_rot() -> sympy.Matrix:\n    return sympy.Matrix([\n        [1, 0, 0, 0],\n        [0, 1, 0, 0],\n        [0, 0, 1, 0],\n        [0, 0, 0, 1]\n    ])\n\ndef sym_rot(axis: sympy.Matrix, angle: sympy.NumberSymbol) -> sympy.Matrix:\n    if axis.shape != (1, 3) and axis.shape != (3, 1):\n        return sympy.Matrix([\n        [1, 0, 0],\n        [0, 1, 0],\n        [0, 0, 1]\n    ])\n    axis = axis.reshape(3, 1)\n    axis = sympy.simplify(axis.normalized())\n    c = sympy.cos(angle)\n    s = sympy.sin(angle)\n    axis2 = sympy.simplify(axis * axis.T)\n    axis = axis.reshape(1, 3)\n    skewaxis = sympy.Matrix([\n        [0, -axis[2], axis[1]],\n        [axis[2], 0, -axis[0]],\n        [-axis[1], axis[0], 0]\n    ])\n    return sympy.simplify(axis2 + (sympy.Matrix([\n        [1, 0, 0],\n        [0, 1, 0],\n        [0, 0, 1]\n    ]) - axis2) * c + skewaxis * s)\n\ndef sym_rotx(angle: sympy.NumberSymbol) -> sympy.Matrix:\n    c = sympy.cos(angle)\n    s = sympy.sin(angle)\n    return sympy.Matrix([\n        [1, 0, 0],\n        [0, c, -s],\n        [0, s, c]\n    ])\n\ndef sym_roty(angle: sympy.NumberSymbol) -> sympy.Matrix:\n    c = sympy.cos(angle)\n    s = sympy.sin(angle)\n    return sympy.Matrix([\n        [c, 0, s],\n        [0, 1, 0],\n        [-s, 0, c]\n    ])\n\ndef sym_rotz(angle: sympy.NumberSymbol) -> sympy.Matrix:\n    c = sympy.cos(angle)\n    s = sympy.sin(angle)\n    return sympy.Matrix([\n        [c, -s, 0],\n        [s, c, 0],\n        [0, 0, 1]\n    ])\n\ndef sym_rot_eulzxz(anglez: sympy.NumberSymbol, anglex: sympy.NumberSymbol, anglez1: sympy.NumberSymbol) \\\n    -> sympy.Matrix:\n    cz = sympy.cos(anglez)\n    sz = sympy.sin(anglez)\n    cx = sympy.cos(anglex)\n    sx = sympy.sin(anglex)\n    cz1 = sympy.cos(anglez1)\n    sz1 = sympy.sin(anglez1)\n    rotzmat = sympy.Matrix([\n        [cz, -sz, 0],\n        [sz, cz, 0],\n        [0, 0, 1]\n    ])\n    rotxmat = sympy.Matrix([\n        [1, 0, 0],\n        [0, cx, -sx],\n        [0, sx, cx]\n    ])\n    rotz1mat = sympy.Matrix([\n        [cz1, -sz1, 0],\n        [sz1, cz1, 0],\n        [0, 0, 1]\n    ])\n    return sympy.simplify(rotzmat * rotxmat * rotz1mat)\n\ndef sym_rot_rpyxyz(anglex: sympy.NumberSymbol, angley: sympy.NumberSymbol, anglez: sympy.NumberSymbol) \\\n    -> sympy.Matrix:\n    cx = sympy.cos(anglex)\n    sx = sympy.sin(anglex)\n    cy = sympy.cos(angley)\n    sy = sympy.sin(angley)\n    cz = sympy.cos(anglez)\n    sz = sympy.sin(anglez)\n    rotxmat = sympy.Matrix([\n        [1, 0, 0],\n        [0, cx, -sx],\n        [0, sx, cx]\n    ])\n    rotymat = sympy.Matrix([\n        [cy, 0, sy],\n        [0, 1, 0],\n        [-sy, 0, cy]\n    ])\n    rotzmat = sympy.Matrix([\n        [cz, -sz, 0],\n        [sz, cz, 0],\n        [0, 0, 1]\n    ])\n    return sympy.simplify(rotzmat * rotymat * rotxmat)\n\ndef sym_rot_inv(rotmat: sympy.Matrix) -> sympy.Matrix:\n    return sympy.transpose(rotmat)\n\ndef sym_hom_rotx(angle: sympy.NumberSymbol) -> sympy.Matrix:\n    c = sympy.cos(angle)\n    s = sympy.sin(angle)\n    return sympy.Matrix([\n        [1, 0, 0, 0],\n        [0, c, -s, 0],\n        [0, s, c, 0],\n        [0, 0, 0, 1]\n    ])\n\ndef sym_hom_roty(angle: sympy.NumberSymbol) -> sympy.Matrix:\n    c = sympy.cos(angle)\n    s = sympy.sin(angle)\n    return sympy.Matrix([\n        [c, 0, s, 0],\n        [0, 1, 0, 0],\n        [-s, 0, c, 0],\n        [0, 0, 0, 1]\n    ])\n\ndef sym_hom_rotz(angle: sympy.NumberSymbol) -> sympy.Matrix:\n    c = sympy.cos(angle)\n    s = sympy.sin(angle)\n    return sympy.Matrix([\n        [c, -s, 0, 0],\n        [s, c, 0, 0],\n        [0, 0, 1, 0],\n        [0, 0, 0, 1]\n    ])\n\ndef sym_hom_rot_inv(homrotmat: sympy.Matrix) -> sympy.Matrix:\n    rot_inv_mat = sympy.transpose(homrotmat[0:3, 0:3])\n    return sympy.Matrix([\n        [rot_inv_mat[0, 0], rot_inv_mat[0, 1], rot_inv_mat[0, 2], 0],\n        [rot_inv_mat[1, 0], rot_inv_mat[1, 1], rot_inv_mat[1, 2], 0],\n        [rot_inv_mat[2, 0], rot_inv_mat[2, 1], rot_inv_mat[2, 2], 0],\n        [0, 0, 0, 1]\n    ])\n\ndef sym_no_transl() -> sympy.Matrix:\n    return sympy.Matrix([[0, 0, 0]])\n\ndef sym_transl(tx: sympy.NumberSymbol, ty: sympy.NumberSymbol, tz: sympy.NumberSymbol) -> sympy.Matrix:\n    return sympy.Matrix([[tx, ty, tz]])\n\ndef sym_no_coltransl() -> sympy.Matrix:\n    return sympy.Matrix([0, 0, 0])\n\ndef sym_coltransl(tx: sympy.NumberSymbol, ty: sympy.NumberSymbol, tz: sympy.NumberSymbol) -> sympy.Matrix:\n    return sympy.Matrix([tx, ty, tz])\n\ndef sym_transl_inv(translvec: sympy.Matrix) -> sympy.Matrix:\n    return -translvec\n\ndef sym_hom_transl(tx: sympy.NumberSymbol, ty: sympy.NumberSymbol, tz: sympy.NumberSymbol) -> sympy.Matrix:\n    return sympy.Matrix([\n        [1, 0, 0, tx],\n        [0, 1, 0, ty],\n        [0, 0, 1, tz],\n        [0, 0, 0, 1]\n    ])\n\ndef sym_hom_transl_inv(homtranslmat: sympy.Matrix) -> sympy.Matrix:\n    transl_inv_vec = -homtranslmat[0:3, 3:4]\n    return sympy.Matrix([\n        [1, 0, 0, transl_inv_vec[0, 0]],\n        [0, 1, 0, transl_inv_vec[1, 0]],\n        [0, 0, 1, transl_inv_vec[2, 0]],\n        [0, 0, 0, 1]\n    ])\n\ndef sym_DH_transformation(alpha: sympy.NumberSymbol, a: sympy.NumberSymbol,\n                          d: sympy.NumberSymbol, theta: sympy.NumberSymbol) -> sympy.Matrix:\n    calpha = sympy.cos(alpha)\n    salpha = sympy.sin(alpha)\n    ctheta = sympy.cos(theta)\n    stheta = sympy.sin(theta)\n    transf1 = sympy.Matrix([\n        [ctheta, -stheta, 0, 0],\n        [stheta, ctheta, 0, 0],\n        [0, 0, 1, d],\n        [0, 0, 0, 1]\n    ])\n    transf2 = sympy.Matrix([\n        [1, 0, 0, a],\n        [0, calpha, -salpha, 0],\n        [0, salpha, calpha, 0],\n        [0, 0, 0, 1]\n    ])\n    return sympy.simplify(transf1 * transf2)\n\ndef sym_hom(rotmat: sympy.Matrix, translvec: sympy.Matrix) -> sympy.Matrix:\n    translvec = translvec.reshape(3, 1)\n    return sympy.Matrix([\n        [rotmat[0, 0], rotmat[0, 1], rotmat[0, 2], translvec[0, 0]],\n        [rotmat[1, 0], rotmat[1, 1], rotmat[1, 2], translvec[1, 0]],\n        [rotmat[2, 0], rotmat[2, 1], rotmat[2, 2], translvec[2, 0]],\n        [0, 0, 0, 1]\n    ])\n\ndef sym_hom_inv(hommat: sympy.Matrix) -> sympy.Matrix:\n    rot_inv_mat = sympy.transpose(hommat[0:3, 0:3])\n    transl_inv_vec = sympy.simplify(-rot_inv_mat * hommat[0:3, 3:4])\n    return sympy.Matrix([\n        [rot_inv_mat[0, 0], rot_inv_mat[0, 1], rot_inv_mat[0, 2], transl_inv_vec[0, 0]],\n        [rot_inv_mat[1, 0], rot_inv_mat[1, 1], rot_inv_mat[1, 2], transl_inv_vec[1, 0]],\n        [rot_inv_mat[2, 0], rot_inv_mat[2, 1], rot_inv_mat[2, 2], transl_inv_vec[2, 0]],\n        [0, 0, 0, 1]\n    ])\n\ndef dehom(hommat: sympy.Matrix) -> Tuple[sympy.Matrix, sympy.Matrix]:\n    rotmat = sympy.Matrix([\n        [hommat[0, 0], hommat[0, 1], hommat[0, 2]],\n        [hommat[1, 0], hommat[1, 1], hommat[1, 2]],\n        [hommat[2, 0], hommat[2, 1], hommat[2, 2]]\n    ])\n    translvec = sympy.Matrix([[hommat[0, 3], hommat[1, 3], hommat[2, 3]]])\n    return rotmat, translvec\n", "meta": {"hexsha": "9cf53280d64b37dbd53f1cfc7d80a3eb35d0f54c", "size": 7300, "ext": "py", "lang": "Python", "max_stars_repo_path": "rob/math/sym_transforms3d.py", "max_stars_repo_name": "lorenzo-di-luccio/rob", "max_stars_repo_head_hexsha": "531559292ec7b8219931f7a25581bff51c0dd5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rob/math/sym_transforms3d.py", "max_issues_repo_name": "lorenzo-di-luccio/rob", "max_issues_repo_head_hexsha": "531559292ec7b8219931f7a25581bff51c0dd5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rob/math/sym_transforms3d.py", "max_forks_repo_name": "lorenzo-di-luccio/rob", "max_forks_repo_head_hexsha": "531559292ec7b8219931f7a25581bff51c0dd5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9682539683, "max_line_length": 107, "alphanum_fraction": 0.5421917808, "include": true, "reason": "import sympy", "num_tokens": 2716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9820137884587394, "lm_q2_score": 0.9005297821135385, "lm_q1q2_score": 0.8843326629532391}}
{"text": "# Introdução à Computação Simbólica com _sympy_\n\n## Motivação\n\nNeste ponto do curso, você já aprendeu a realizar operações matemáticas elementares com Python. Por exemplo, se lhe for dado o valor do raio $R$, você consegue facilmente computar a área $\\pi R^2$ de um círculo. Todavia, o valor de $\\pi$ que você obtém é finito. As instruções abaixo verificam isto.   \n\n```python\nfrom math import pi\nprint(pi)\n3.141592653589793\n```\n\nPense, no entanto, se você pudesse realizar o cálculo desta área de maneira \"exata\". Matematicamente falando, é impossível fazer isto pois $\\pi$ é um número irracional – o imbróglio desta constante é longo na história da Matemática. Porém, a computação simbólica permite que operemos com $\\pi$ como se fosse simplesmente um símbolo com precisão infinita. Embora 15 casas decimais, como o valor exemplificado acima, sejam suficientes para a maioria dos cálculos do mundo real, a computação simbólica permite que trabalhemos com modelos abstratos que servem a uma diversidade de propósitos. \n\nAliás, quando se diz que 3.141592653589793 é um valor razoavelmente aceitável, isto é verdade até mesmo para cálculos em escala astronômica. A equipe de engenharia da NASA explica que, usando este valor para calcular o perímetro de uma circunferência com diâmetro igual a 25 bilhões de milhas, o erro de cálculo é próximo de 1,5 polegada [[NASA]](https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/). Até aí, nada mal para uma aproximação!\n\n## O que é Computação Simbólica e para que serve? \n\n*Computação Simbólica* (CS) é uma subárea de estudo da matemática e da ciência da computação que se preocupa em resolver problemas usando objetos simbólicos representáveis em um computador. Esses problemas surgem em muitas aplicações em ciências naturais, pesquisa básica, na indústria e principalmente no desenvolvimento de softwares para computação avançada denominados _sistemas de computação algébrica_ (SCAs). \n\nA CS existente em um SCA é aplicada em álgebra computacional, projetos assistidos por computação (CAD), raciocínio automatizado, gestão do conhecimento, lógica computacional e sistemas formais de verificação. O desenvolvimento da CS depende da integração de basicamente três campos: *softwares matemáticos*, *álgebra computacional* e *lógica computacional* [[RISC/JKU]](https://risc.jku.at/studying-symbolic-computation/). Em casos mais avançados, a CS é útil para solucionar equações da macroeconomia, manipular números para a finalidade de criptografia e criar modelos probabilísticos [[Kotzé]](https://kevinkotze.github.io/mm-tut1-symbolic/), [[Cohen]](https://www.ukma.edu.ua/~yubod/teach/compalgebra/%5BJoel_S._Cohen%5D_Computer_algebra_and_symbolic_comp(BookFi.org).pdf). \n\n## Principais SCAs \n\nAlguns SCAs são populares de longa data, tais como Maple, Mathematica e MuPad. Entretanto, são comerciais e costumam ter licenças custosas, embora ofereçam versões com desconto para estudantes. Algumas alternativas robustas de uso livre são Scilab, Sagemath, Octave e o próprio módulo *sympy*. Uma lista completa de SCAs está disponível na [[Wikipedia]](https://en.wikipedia.org/wiki/Computer_algebra_system).\n\n## Por que *sympy*? \n\nO objetivo principal do *sympy* é ser uma biblioteca de manipulação simbólica para Python. Ele começou a ser desenvolvido em 2006 e atualmente está na versão 1.5.1, lançada em dezembro de 2019 na página oficial [[sympy.org]](https://www.sympy.org/pt/index.html). As principais características do módulo são as seguintes: \n\n- é gratuito;\n\n- é baseado inteiramente em Python;\n\n- é leve e independente.\n\n## Objetos numéricos x objetos simbólicos\n\nImportaremos os módulos `math` e `sympy` para ver algumas  diferenças entre objetos numéricos e simbólicos.\n\nimport math as mt\nimport sympy as sy\nsy.init_printing(pretty_print=True) # melhor impressão de símbolos\n\nmt.pi # numérico\n\nsy.pi # simbólico\n\nVerifiquemos com `type`.\n\ntype(mt.pi)\n\ntype(sy.pi) # é um objeto simbólico\n\nVejamos mais um exemplo:\n\nmt.sqrt(2)\n\nsy.sqrt(2)\n\ntype(mt.sqrt(2))\n\ntype(sy.sqrt(2)) # é um objeto simbólico\n\n### Função x método \n\nNa aula anterior destacamos que `print` e `type` são \"funções\" similares àquelas do tipo $y = f(x)$ em Matemática. Em Python, essas \"funções\" recebem o nome de *função* mesmo.\n\nPorém, há módulos que possuem *métodos*, que para seu entendimento, podem ser vistos como \"funções\" também. Porém, *função* e *método* são conceitos levemenete distintos. \n\nPara aplicarmos funções usamos parênteses envolvendo um ou mais *parâmetros*. \n\nNo caso acima, `mt.sqrt(2)` mostra que `sqrt` age como uma função e o número 2 é seu único parâmetro. Note, além disso, que o sympy também possui a sua própria função `sqrt`, que é de uma natureza distinta. Ela é um objeto `sympy.core.power.Pow`. Não precisamos entender isso agora, mas basta saber que ela pertence a um submódulo do *sympy*.\n\nPor outro lado, também aprendemos que o conjugado de um número complexo `z` (tipo `complex`) pode ser obtido como `z.conjugate()`. Esta forma \"sem parâmetros\" indica que `conjugate` é um método do objeto `z`.\n\nA partir deste ponto, poderemos ver situações como as seguintes:\n\n- `f(x)`: a função `f` é aplicada ao parâmetro `x`\n\n- `a.f()`: `f` é um método sem parâmetro do objeto `a`\n\n- `a.f(x)`: `f` é um método com parâmetro `x` do objeto `a`\n\nA partir do último exemplo, podemos dizer que um método é, na verdade, uma função que pertence a um objeto.\n\n### Atribuições com símbolos\n\nPodemos atribuir símbolos a variáveis usando a função `symbols`.\n\nx = sy.symbols('x')\ny = sy.symbols('y')\n\n`x` e `y` são símbolos sem valor definido.\n\nx\n\ny\n\nPodemos operar aritmeticamente com símbolos e obter uma expressão simbólica como resultado.\n\nz = sy.symbols('z')\nx*y + z**2/3 + sy.sqrt(x*y - z)\n\n**Exemplo**: escreva o produto notável $(x - y)^2$ como uma expressão simbólica.\n\nx**2 - 2*x*y + y**2\n\nNote que o nome da variável não tem a ver com o nome do símbolo. Poderíamos fazer o seguinte:\n\ny = sy.symbols('x') # y é variável; x é símbolo\ny\n\n### Atribuição por desempacotamento \n\nTambém poderíamos realizar as atribuições anteriores da seguinte forma: \n\nx, y, z = sy.symbols('x y z')\n\n### Alfabeto de símbolos \n\nO *sympy* dispõe de um submódulo chamado `abc` do qual podemos importar símbolos para letras latinas (maiúsculas e minúsculas) e gregas (minúsculas).\n\nfrom sympy.abc import a,b,c,alpha,beta,gamma\n(a + 2*b - 3*c)*(alpha/3 + beta/2 - gamma) # símbolico\n\nfrom sympy.abc import D,G,psi,theta\nD**a * G**b * psi**c * theta**2 # símbolico\n\n**Nota**: algumas letras já são usadas como símbolos especiais, tais como `O`, que indica \"ordem\" e `I`, que é o complexo $i$. Neste caso, cuidado deve ser tomado com nomes de variáveis\n\nsy.I # imaginário simbólico\n\ntype(sy.I)\n\n### Símbolos com nomes genéricos\n\nPara criar símbolos genéricos, temos de usar `symbols` ou `Symbol`.\n\nsem_nocao = sy.symbols('nada')\nsem_nocao\n\nmuito_louco = sy.Symbol('massa')\nmuito_louco\n\n### Variáveis e símbolos\n\nsem_medo = sem_nocao + 2\nsem_medo \n\nsoma = muito_louco + 2\nmuito_louco = 3 # 'muito_louco' aqui não é o simbólico\nsoma\n\n## Substituição\n\nA operação de *substituição* permite que: \n\n1. substituamos variáveis por valores numéricos para avaliar uma expressão ou calcular valores de uma função em um dado ponto.\n2. substituamos uma subexpressão por outra.\n\nPara tanto, procedemos da seguinte forma: \n\n```python\nexpressao.subs(variavel,valor)\n```\n\n\n**Exemplo**: considere o polinômio $P(x) = 2x^3 - 4x -6$. Calcule o valor de $P(-1)$, $P(e/3)$, $P(\\sqrt{3.2})$.\n\nfrom sympy.abc import x \nP = 2*x**3 - 4*x - 6\nP1 = P.subs(x,-1)\nPe3 = P.subs(x,mt.e/3)\nP32 = P.subs(x,mt.sqrt(3.2))\nprint(P1, Pe3, P32)\n\n**Exemplo:** sejam $f(x) = 4^x$ e $g(x) = 2x - 1$. Compute o valor da função composta $f(g(x))$ em $x = 3$. \n\nf = 4**x\nfg = f.subs(x,2*x - 1)\n\nfg.subs(x,3)\n\nPoderíamos também fazer isso com um estilo \"Pythônico\":\n\nfg = 4**x.subs(x,2*x - 1).subs(x,3)\nfg\n\n**Exemplo:** se $a(x) = 2^x$, $b(x) = 6^x$ e $c(x) = \\cos(x)$, compute o valor de $a(x)b(c(x))$ em $x = 4$\n\na = 2**x\nb = 6**x\nc = sy.cos(x)\n(a * b.subs(x,c)).subs(x,4)\n\nOu, de modo direto:\n\nvalor = ( 2**x * ( 6**x.subs(x,sy.cos(x))) ).subs(x,4)\nvalor\n\n### Avaliação de expressão em ponto flutuante\n\nNote que a expressão anterior não foi computada em valor numérico. Para obter seu valor numérico, podemos usar o método `evalf`.\n\nvalor.evalf()\n\n#### Precisão arbitrária \n\n`evalf` permite que escolhamos a precisão do cálculo impondo o número de dígitos de precisão. Por exemplo, a última expressão com 20 dígitos de precisão seria:\n\nvalor.evalf(20)\n\nCom 55, seria:\n\nvalor.evalf(55)\n\nE com 90 seria:\n\nvalor.evalf(90)\n\n**Exemplo**: calcule o valor de $e$ com 200 dígitos de precisão.\n\nsy.exp(1).evalf(200)\n\n## Funções predefinidas x funções regulares\n\nVamos apresentar aqui três grupos de funções que podem ser criadas em Python para nos auxiliar ao longo do curso sem, no entanto, nos aprofundaremos nos detalhes de cada um. \n\nComo dissemos em um momento anterior, a linguagem Python possui um *core* que contém um conjunto de funções já prontas que podemos usar, como é o caso de `print()`, `type()` e até mesmo `int()` e `float()` para operações de *casting*. Essas funções podem ser chamadas de **predefinidas** (*built-in functions*). Ou seja, são aquelas funções \"já existentes\". Exemplos adicionais seriam as funções do módulo `math`.\n\nSuponhamos, porém, que você vasculhe módulos e mais módulos atrás de uma função que faça exatamente o que você quer, mas não a encontra. O que você faz? Você a cria! Podemos fazer isto de uma maneira usando uma \"palavra-chave\" (*keyword*) chamada `def` da seguinte forma:\n\n```python\ndef f(x):\n    (...)\n    return y\n```\nA instrução acima permite que você crie uma *função* chamada `f` da qual `x` é um *argumento* e `y` é um *valor de retorno*, indicado por uma segunda \"palavra-chave\", *return*. Funções definidas por você dessa maneira são chamadas de **regulares**, *normais* – pelo fato de serem programadas de um modo regular, seguindo a \"normalidade\" da linguagem –, ou ainda *definidas pelo usuário* (do inglês *user-defined functions*, ou simplesmente *UDF*). Por conveniência, vamos nos referir a elas por este acrônimo elegante: UDF. \n\nUma UDF permite que você abstraia seu pensamento para criar basicamente o que quiser dentro dos limites da linguagem Python. Cabe, apesar disso, fazermos as seguintes ressalvas: \n\n- uma UDF **pode ter zero ou mais argumentos**, tantos quantos se queira;\n- uma UDF **pode ou não ter valor de retorno**;\n\nVamos entender as UDFs com exemplos.\n\n**Exemplo:** Suponha que você é um(a) analista de dados do mercado imobiliário e está estudando o impacto do repasse de comissões pagas a corretores mediante vendas de imóveis. Você, então, começa a raciocinar e cria um modelo matemático bastante simples que, antes de tudo, precisa calcular o valor do repasse a partir do preço de venda. \n\nSe $c$ for o percentual de comissão, $V$ o valor da venda do imóvel e $r$ o valor a ser repassado para o corretor, então, a função a ser definida é \n\n$$r(V) = c\\, V,$$ \n\nassumindo que $c$ seja um valor fixo. \n\nDigamos que $c$ corresponda a 1.03% do valor da venda do imóvel. Neste caso podemos criar uma UDF para calcular $r$ para nós da seguinte forma:\n\ndef repasse(V): \n    r = 0.0103*V  \n    return r\n\nPara $V = \\, R\\$ \\, 332.130,00$:\n\nrepasse(332130)\n\nO que é necessário observar:\n\n- `def` vem seguido pelo *nome* da função (`repasse`) após um espaço;\n- o nome precede os argumentos, enclausurados por parênteses `(V)`. Neste caso, temos apenas um *argumento*, que é `V`;\n- após o nome, os dois-pontos (`:`) são obrigatórios e significam mais ou menos \"o que esta função faz será definido da seguinte maneira\"\n- a instrução `r = 0.0103*V` é o *escopo* da função, que deve ser escrito em uma ou mais linhas indentadas (pressione `TAB` para isso, ou use 4 espaços)\n- o valor de retorno, se houver, é posto na última linha do escopo.\n\nPodemos atribuir os valores do argumento e resultado a variáveis:\n\nV = 332130\nrep = repasse(V)\nrep\n\nNomes iguais de variável e função são permissíveis.\n\nrepasse = repasse(V) # 'repasse' à esquerda é uma variável; à direita, função\nprint(repasse)\n\nTodavia, isto pode ser confuso e é bom evitar.\n\nO estilo \"Pythônico\" de escrever permite que o valor de retorno não seja explicitamente declarado. No escopo\n\n```python\n...\n    r = 0.0103*V  \n    return r\n```\n a variável `r` não é necessária.\n \nPython é inteligente para permitir o seguinte:\n\ndef repasse(V): \n    return 0.0103*V\n\n# note que aqui não indentamos a linha. \n# Logo esta instrução NÃO pertence ao escopo da função.\nrepasse(V)\n\nPodemos criar uma função para diferentes valores de `c` e `V` usando *dois* argumentos:\n\ndef repasse_c(c,V): # esta função tem outro nome\n    return c*V\n\nc = 0.0234 # equivaleria a uma taxa de repasse de 2.34%\nV = 197432 # o valor do imóvel agora é R$ 197.432,00\nrepasse_c(c,V)\n\nA ordem dos argumentos importa:\n\nV = 0.0234 # este deveria ser o valor de c\nc = 197432 # este deveria ser o valor de V\nrepasse_c(c,V)\n\nPor que o valor resultante é o mesmo? Porque a operação no escopo da função é uma multiplicação, `c*V`, que é comutativa independentemente do valor das variáveis. Porém, digamos que um segundo modelo tenha uma forma de cálculo distinta para a comissão dada por\n\n$$r_2(V) = c^{3/5} \\, V$$\n\nNeste caso:\n\ndef repasse_2(c,V):\n    return c**(3/5)*V\n\nV = 197432\nc = 0.0234\n\nrepasse_2(c,V)\n\nPorém, se trocarmos o valor das variáveis, a função `repasse_2` calculará um valor distinto. Embora exista um produto também comutativo, o expoente `3/4` modifica apenas o valor de `c`.\n\n# variáveis com valores trocados\nc = 197432\nV = 0.0234\n\nrepasse_2(c,V)\n\nA ordem com que escrevemos os argumentos tem importância relativa aos valores que passamos e ao que definimos: \n\n# variáveis com valores corretos\nV = 197432\nc = 0.0234\n\ndef repasse_2_trocada(V,c): # V vem antes de c\n    return c**(3/5)*V\n    \nrepasse_2_trocada(V,c)\n\nMas,\n\n# os valores das variáveis estão corretos, \n# mas foram passados para a função na ordem errada\nrepasse_2_trocada(c,V) \n\ne \n\n# a ordem dos argumentos está de acordo com a que foi definida\n# mas os valores das variáveis foram trocados\nV = 197432\nc = 0.0234\nrepasse_2_trocada(c,V) \n\n## Modelos matemáticos simbólicos\n\nA partir do que aprendemos, podemos definir modelos matemáticos completamente simbólicos.\n\nfrom sympy.abc import c,V\n\ndef repasse_2_simbolica(c,V):\n    return c**(3/5)*V\n\nSe chamarmos esta função, ela será um objeto simbólico.\n\nrepasse_2_simbolica(c,V)\n\nAtribuindo em variável:\n\nrep_simb = repasse_2_simbolica(c,V)\n\ntype(rep_simb) # é um objeto simbólico\n\n**Exemplo:** Suponha, agora, que seu modelo matemático de repasse deva considerar não apenas um percentual $c$ pré-estabelecido, mas também um valor de \"bônus\" adicional concedido como prêmio pela venda do imóvel. Considere, então, que o valor deste bônus seja $b$. Diante disso, nosso novo modelo teria uma fórmula como a seguinte: \n\n$$r_3(V) = c\\,V + b$$\n\nSimbolicamente:\n\n# importaremos apenas o símbolo b, \n# uma vez que c e V já foram importados \n# como símbolos anteriormente\nfrom sympy.abc import b \n\ndef r3(V):\n    return c*V + b\n\nrep_3 = r3(V)\nrep_3\n\n### Substituindo valores\n\nPodemos usar a função `subs` para atribuir quaisquer valores para o modelo.\n\n**Exemplo:** $c = 0.119$\n\nrep_3.subs(c,0.119) # substituindo para c\n\n**Exemplo:** $c = 0.222$\n\nrep_3.subs(c,0.222) # substituindo para c\n\n**Exemplo:** $c = 0.222$ e $b = 12.0$\n\nrep_3.subs(c,0.222).subs(b,12.0) # substituindo para c, depois para b\n\n### Substituição múltipla\n\nO modo anterior de substituição não é \"Pythônico\". Para substituirmos mais de uma variável de uma vez, devemos usar *pares ordenados* separados por vírgula sequenciados entre colchetes como uma *lista*. Mais tarde, aprenderemos sobre pares ordenados e listas.\n\n**Exemplo:** Modifique o modelo $r_3$ para que $c = 0.043$ e $b = 54.0$\n\n# espaços foram adicionados para dar legibilidade\nrep_3.subs( [ (c,0.043), (b,54.0) ] )\n\n#### Pares ordenados\n\nEm matemática, o conceito de par ordenado pode ser definido pelo conjunto: \n\n$$ X \\times Y = \\{ (x,y) ; x \\in X \\text{ e } y \\in Y \\},$$\n\nonde $X$ e $Y$ são conjuntos quaisquer e $x$ e $y$ são as *coordenadas*. Por exemplo, se $X = Y = \\mathbb{R}$, o conjunto acima contém elementos do tipo $(3,2)$, $(-1,3)$, $(\\pi,2.18)$ etc. Na verdade, eles formam o conjunto $\\mathbb{R} \\times \\mathbb{R} = \\mathbb{R}^2$, que é exatamente o *plano cartesiano*.\n\nLogo, a substituição múltipla com `subs` ocorre da seguinte forma; \n\n- a primeira coordenada é o *símbolo*;\n\n- a segunda coordenada é o *valor* que você quer dar para o símbolo.\n\n**Exemplo:** Calcule $r_3(V)$ considerando $c = 0.021$, $b = 34.0$ e $V = 432.000$.\n\n# armazenaremos o valor na variável 'valor'\nvalor = r3(V)\n\n# subsituição \nvalor.subs( [ (c,0.021), (b,54.0) ] )\n\nCom o estilo \"Pythônico\":\n\nvalor = r3(V).subs( [ (c,0.021), (b,54.0) ] ) # \nvalor\n\nPodemos seguir esta regra de pares para substituir todos os valores de um modelo simbólico genérico não necessariamente definido através de uma função. Veja o exemplo aplicado a seguir.\n\n## Exemplo de aplicação: o índice de caminhabilidade\n\nEstudos empíricos nos EUA mostraram que a *caminhabilidade* de uma vizinhança impacta substancialmente os preços das casas. A caminhabilidade está relacionada à distância da moradia a locais de amenidades, tais como restaurantes, bares, bibliotecas, mercearias etc.\n\nO *índice de caminhabilidade* $W$ para uma vizinhança de casas é uma medida matemática que assume valores no intervalo $[0,1]$. A fórmula é definida por: \n\n$$W(d) = e^{-5 \\left( \\dfrac{d}{M} \\right)^5},$$\n\nonde $d$ é a distância medida entre a vizinhança (0 metro) e um dado ponto de referência, e $M$ é a distância máxima de avaliação considerada a partir da qual a caminhabilidade é assumida como nula. Ou seja, \n\n- quando estamos na vizinhança, $d = 0$, $W = 1$ e a caminhabilidade é considerada ótima.\n\n- à medida que nos afastamos da vizinhança em direção ao local da amenidade, $d$ aumenta e o valor $W$ decai vertiginosamente até atingir o valor limite $M$ a partir do qual $W = 0$ e a caminhabilidade é considerada \"péssima\". \n\nO índice de caminhabilidade é, portanto, calculado com relação a um ponto de destino definido e a distância deve levar em consideração as vias de circulação (ruas, rodovias etc) e não a distância mais curta (raio do perímetro). Por exemplo, se a distância máxima a ser considerada para a caminhabilidade for $M = 500 \\, m$ , um bar localizado a 100 metros da vizinhança teria um índice de caminhabilidade maior do que o de uma farmácia localizada a 300 m e muito maior do que o de um shopping localizado a 800 m, ainda que muito famoso. Aliás, neste caso, o valor de $W$ para o shopping seria zero, já que 800 m está além do limite $M$ estabelecido.\n\nFonte: *De Nadai, M. and Lepri, B. [[The economic value of neighborhoods: Predicting real estate prices from the urban environment]](https://arxiv.org/pdf/1808.02547.pdf)*. \n\n### Modelo simbólico\n\nPodemos modelar $W$ simbolicamente e calcular seu valor para diferentes valores de $d$ e $M$ usando a substituição múltipla.\n\nfrom sympy.abc import d,M,W \n\nW = sy.exp(-5*(d/M)**5) # função exponencial simbólica\nW\n\n**Exemplo:** A nossa corretora de imóveis gostaria de entender a relação de preços de imóveis para o Condomínio Pedras de Marfim. Considerando $M = 1 km$, calcule:\n        \n- o índice de caminhabilidade $W_1$ em relação à farmácia Dose Certa, localizada a 222 m do condomínio.\n\n- o índice de caminhabilidade $W_2$ em relação ao restaurante Sabor da Arte, localizada a 628 m do condomínio.\n\n- o índice de caminhabilidade $W_3$ em relação ao Centro Esportivo Physicalidade, localizada a 998 m do condomínio.\n\n- o índice de caminhabilidade $W_4$ em relação à Padaria Dolce Panini, localizada a 1,5 km do condomínio.\n\n# note que 1 km = 1000 m\nW1 = W.subs([ (d,222), (M,1000) ]) \nW2 = W.subs([ (d,628), (M,1000) ]) \nW3 = W.subs([ (d,998), (M,1000) ]) \nW4 = W.subs([ (d,1500), (M,1000) ])\n\nPerceba, entretanto, que os valores calculados ainda não são numéricos, como esperado.\n\nW1\n\nW2\n\nW3\n\nW4\n\nLembre-se que podemos usar `evalf` para calcular esses valores. Faremos isso considerando 3 casas decimais.\n\n# reatribuindo todos os valores\nW1n = W1.evalf(3)\nW2n = W2.evalf(3)\nW3n = W3.evalf(3)\nW4n = W4.evalf(3)\n\nprint('W1 =', W1n, '; ' \\\n      'W2 =', W2n, '; ' \\\n      'W3 =', W3n, '; ' \\\n      'W4 =', W4n)       \n\nComo era de se esperar, os valores decaem de 0.997 a 3.24e-17, que é um valor considerado nulo em termos de aproximação numérica.\n\n#### Quebrando instruções com `\\`\n\nA contra-barra `\\` pode ser usada para quebrar instruções e continuá-las nas próximas linhas, porém não poderá haver nenhum caracter após ela, nem mesmo espaços. Caso contrário, um erro será lançado.\n\nprint('Continuando' \\\n      'na linha abaixo')\n\n# neste exemplo, há um caracter de espaço após \\\nprint('Continuando' \\ \n      'na linha abaixo')\n\n### O tipo `bool`\n\nEm Python, temos mais um tipo de dado bastante útil, o `bool`, que é uma redução de \"booleano\". Objetos `bool`, que têm sua raiz na chamada Álgebra de Boole, são baseados nos conceitos *true* (verdadeiro) e *false*, ou *0* e *1* e são estudados em algumas disciplinas, tais como Circuitos Lógicos, Matemática Discreta, Lógica Aplicada, entre outras. \n\nAprenderemos sobre operadores lógicos mais à frente. Por enquanto, cabe mencionar as entidades fundamentais `True` e `False`. \n\nTrue\n\nFalse\n\ntype(True)\n\ntype(False)\n\nPodemos realizar testes lógicos para concluir verdades ou falsidades quando temos dúvidas sobre objetos e relações entre eles. Por exemplo, retomemos os seguintes valores:\n\nW1\n\nW2\n\nA princípio, é difícil determinar qual dos dois é o maior. Porém, podemos realizar \"perguntas\" lógicas para o interpretador Python com operadores lógicos. Mostraremos apenas dois exemplos com `>` e `<`.\n\nW1 > W2 # isto quer dizer: \"W1 é maior do que W2?\"\n\nO valor `True` confirma que o valor de `W1` é maior do que `W2`. \n\nW4 < 0\n\nNote que, de acordo com nosso modelo de caminhabilidade, este valor deveria ser zero. Porém, numericamente, ele é uma aproximação para zero. Embora muito pequeno, não é exatamente zero! Por que isso ocorre? Porque o computador lida com uma matemática inexata e aproximada, mas com precisão satisfatória.\n\n## Operadores lógicos\n\nVimos que `True` e `False` são os dois valores atribuíves a um objeto de tipo `bool`. Eles são úteis para testar condições, realizar verificações e comparar quantidades. Vamos estudar *operadores de comparação*, *operadores de pertencimento* e *operadores de identidade*.\n\n### Operadores de comparação\n\nA tabela abaixo resume os operadores de comparação utilizados em Python.\n\n| operador | significado | símbolo matemático | \n|---|---|---| \n| `<` | menor do que | $<$ |\n| `<=` | menor ou igual a | $\\leq$ |\n| `>` | maior do que | $>$ |\n| `>=` | maior ou igual a | $\\geq$ |\n| `==` | igual a | $=$ |\n| `!=` | diferente de | $\\neq$ |\n\nPodemos usá-los para comparar objetos. \n\n**Nota:** `==` está relacionado à igualdade, ao passo que `=` é uma atribuição. São conceitos operadores com finalidade distinta. \n\n2 < 3 # o resultado é um 'bool'\n\n5 < 2 # isto é falso\n\n2 <= 2 # isto é verdadeiro\n\n4 >= 3 # isto é verdadeiro\n\n6 != -2 \n\n4 == 4 # isto não é uma atribuição! \n\nPodemos realizar comparações aninhadas:\n\nx = 2\n1 < x < 3\n\n3 > x > 4\n\n2 == x > 3 \n\nAs comparações aninhadas acima são resolvidas da esquerda para a direita e em partes. Isso nos leva a introduzir os seguintes operadores.\n\n| operador | símbolo matemático | significado | uso relacionado a |\n|---|---|---|---|\n| `or` | $\\vee$ | \"ou\" booleano | união, disjunção |\n| `and` | $\\wedge$ | \"e\" booleano | interseção, conjunção |\n| `not` | $\\neg$ | \"não\" booleano | exclusão, negação |\n\n# parênteses não são necessários aqui\n(2 == x) and (x > 3) # 1a. comparação: 'True'; 2a.: 'False'. Portanto, ambas: 'False'\n\n# parênteses não são necessários aqui\n(x < 1) or (x < 2) # nenhuma das duas é True. Portanto, \n\nnot (x == 2) # nega o \"valor-verdade\" que é 'True'\n\nnot x + 1 > 3 # estude a precedência deste exemplo. Por que é 'True'?\n\nnot (x + 1 > 3) # estude a precedência deste exemplo. Por que também é 'True'?\n\n### Operadores de pertencimento\n\nA tabela abaixo resume os operadores de pertencimento. \n\n| operador | significado | símbolo matemático\n|---|---|---|\n| `in` | pertence a | $\\in$ |\n| `not in` | não pertence a | $\\notin$ |\n\nEles terão mais utilidade quando falarmos sobre sequências, listas. Neste momento, vejamos exemplos com objetos `str`.\n\n'2' in '2 4 6 8 10' # o caracter '2' pertence à string\n\nfrase_teste = 'maior do que' \n'maior' in frase_teste\n\n'menor' in frase_teste # a palavra 'menor' está na frase\n\n1 in 2 # 'in' e 'not in' não são aplicáveis aqui\n\n### Operadores de identidade\n\nA tabela abaixo resume os operadores de identidade. \n\n| operador | significado \n|---|---|\n| `is` | \"aponta para o mesmo objeto\" \n| `is not` | \"não aponta para o mesmo objeto\" |\n\nEsses operadores são úteis para verificar se duas variáveis se referem ao mesmo objeto. Exemplo: \n\n```python\na is b\na is not b\n```\n\n- `is` é `True` se `a` e `b` se referem ao mesmo objeto; `False`, caso contrário.\n- `is not` é `False` se `a` e `b` se referem ao mesmo objeto; `True`, caso contrário.\n\na = 2\nb = 3\na is b # valores distintos\n\na = 2\nb = a\na is b # mesmos valores\n\na = 2\nb = 3\na is not b # de fato, valores não são distintos\n\na = 2\nb = a\na is not b # de fato, valores são distintos\n\n## Equações simbólicas\n\nEquações simbólicas podem ser formadas por meio de `Eq` e não com `=` ou `==`.\n\n# importação\nfrom sympy.abc import a,b\nimport sympy as sy \nsy.init_printing(pretty_print=True)\n\nsy.Eq(a,b) # equação simbólica\n\nsy.Eq(sy.cos(a), b**3) # os objetos da equação são simbólicos\n\n### Resolução de equações algébricas simbólicas\n\nPodemos resolver equações algébricas da seguinte forma:\n\n```python\nsolveset(equação,variável,domínio)\n```\n\n**Exemplo:** resolva $x^2 = 1$ no conjunto $\\mathbb{R}$.\n\nfrom sympy.abc import x\nsy.solveset( sy.Eq( x**2, 1), x,domain=sy.Reals)\n\nPodemos reescrever a equação como: $x^2 - 1 = 0$.\n\nsy.solveset( sy.Eq( x**2 - 1, 0), x,domain=sy.Reals)\n\nCom `solveset`, não precisamos de `Eq`. Logo, a equação é passada diretamente.\n\nsy.solveset( x**2 - 1, x,domain=sy.Reals)\n\n**Exemplo:** resolva $x^2 + 1 = 0$ no conjunto $\\mathbb{R}$.\n\nsy.solveset( x**2 + 1, x,domain=sy.Reals) # não possui solução real\n\n**Exemplo:** resolva $x^2 + 1 = 0$ no conjunto $\\mathbb{C}$.\n\nsy.solveset( x**2 + 1, x,domain=sy.Complexes) # possui soluções complexas\n\n**Exemplo:** resolva $\\textrm{sen}(2x) = 3 + x$ no conjunto $\\mathbb{R}$.\n\nsy.solveset( sy.sin(2*x) - x - 3,x,sy.Reals) # a palavra 'domain' também pode ser omitida.\n\nO conjunto acima indica que nenhuma solução foi encontrada.\n\n**Exemplo:** resolva $\\textrm{sen}(2x) = 1$ no conjunto $\\mathbb{R}$.\n\nsy.solveset( sy.sin(2*x) - 1,x,sy.Reals)\n\n## Expansão, simplificação e fatoração de polinômios\n\nVejamos exemplos de polinômios em uma variável. \n\na0, a1, a2, a3 = sy.symbols('a0 a1 a2 a3') # coeficientes\nP3x = a0 + a1*x + a2*x**2 + a3*x**3 # polinômio de 3o. grau em x\nP3x\n\nb0, b1, b2, b3 = sy.symbols('b0 b1 b2 b3') # coeficientes\nQ3x = b0 + b1*x + b2*x**2 + b3*x**3 # polinômio de 3o. grau em x\nQ3x\n\nR3x = P3x*Q3x # produto polinomial\nR3x\n\nR3x_e = sy.expand(R3x) # expande o produto\nR3x_e\n\nsy.simplify(R3x_e) # simplify às vezes não funciona como esperado\n\nsy.factor(R3x_e) # 'factor' pode funcionar melhor\n\n# simplify funciona para casos mais gerais \nident_trig = sy.sin(x)**2 + sy.cos(x)**2\nident_trig\n\nsy.simplify(ident_trig)\n\n## Identidades trigonométricas \n\nPodemos usar `expand_trig` para expandir funções trigonométricas. \n\nsy.expand_trig( sy.sin(a + b) ) # sin(a+b)\n\nsy.expand_trig( sy.cos(a + b) ) # cos(a+b)\n\nsy.expand_trig( sy.sec(a - b) ) # sec(a-b)\n\n## Propriedades de logaritmo\n\n\nCom `expand_log`, podemos aplicar propriedades válidas de logaritmo.\n\nsy.expand_log( sy.log(a*b) )\n\nA identidade não foi validada pois `a` e `b` são símbolos irrestritos.\n\na,b = sy.symbols('a b',positive=True) # impomos que a,b > 0\n\nsy.expand_log( sy.log(a*b) ) # identidade validada\n\nsy.expand_log( sy.log(a/b) )\n\nm = sy.symbols('m', real = True) # impomos que m seja um no. real\nsy.expand_log( sy.log(a**m) )\n\nCom `logcombine`, compactamos as propriedades.\n\nsy.logcombine( sy.log(a) + sy.log(b) ) # identidade recombinada\n\n## Fatorial \n\nA função `factorial(n)` pode ser usada para calcular o fatorial de um número.\n\nsy.factorial(m)\n\nsy.factorial(m).subs(m,10) # 10! \n\nsy.factorial(10) # diretamente\n\n**Exemplo:** Sejam $m,n,x$ inteiros positivos. Se $f(m) = 2m!$, $g(n) = \\frac{(n + 1)!}{n^2!}$ e $h(x) = f(x)g(x)$, qual é o valor de $h(2)$? \n\nfrom sympy.abc import m,n,x\n\nf = 2*sy.factorial(m)\ng = sy.factorial(n + 1)/sy.factorial(n**2)\n\nh = (f.subs(m,x)*g.subs(n,x)).subs(x,4)\nh\n\n## Funções anônimas \n\nA terceira classe de funções que iremos aprender é a de *funções anônimas*. Uma **função anônima** em Python consiste em uma função cujo nome não é explicitamente definido e que pode ser criada em apenas uma linha de código para executar uma tarefa específica.\n\nFunções anônimas são baseadas na palavra-chave `lambda`. Este nome tem inspiração em uma área da ciência da computação chamada de cálculo-$\\lambda$.\n\nUma função anônima tem a seguinte forma: \n\n```python\nlambda lista_de_parâmetros: expressão\n```\n\nFunções anônimas podem são bastante úteis para tornar um código mais conciso. \n\nPor exemplo, na aula anterior, definimos a função\n\n```python\ndef repasse(V): \n    return 0.0103*V\n```\n\npara calcular o repasse financeiro ao corretor imobiliário. \n\nCom uma função anônima, a mesma função seria escrita como:\n\nrepasse = lambda V: 0.0103*V\n\nNão necessariamente temos que atribui-la a uma variável. Neste caso, teríamos:\n\nlambda V: 0.0103*V\n\nPara usar a função, passamos um valor:\n\nrepasse(100000) # repasse sobre R$ 100.000,00\n\nO modelo completo com \"bonificação\" seria escrito como:\n\nr3 = lambda c,V,b: c*V + b # aqui há 3 parâmetros necessários\n\nRedefinamos objetos simbólicos:\n\nfrom sympy.abc import b,c,V\nr3(b,c,V)\n\nO resultado anterior continua sendo um objeto simbólico, mas obtido de uma maneira mais direta. Podemos usar funções anônimas para tarefas de menor complexidade.\n\n## \"Lambdificação\" simbólica\n\nUsando `lambdify`, podemos converter uma expressão simbólica do *sympy* para uma expressão que pode ser numericamente avaliada em outra biblioteca. Essa função desempenha papel similar a uma função *lambda* (anônima).\n\nexpressao = sy.sin(x) + sy.sqrt(x) # expressão simbólica\nf = sy.lambdify(x,expressao,\"math\") # lambdificação para o módulo math\nf(0.2) # avalia\n\nPara avaliações simples como a anterior, podemos usar `evalf` e `subs`. A lambdificação será útil quando quisermos avaliar uma função em vários pontos, por exemplo. Na próxima aula, introduziremos sequencias e listas. Para mostrar um exemplo de lambdificação melhor veja o seguinte exemplo.\n\nfrom numpy import arange # importação de função do módulo numpy\n\nX = arange(40) # gera 40 valores de 0 a 39\n\nX\n\nf = sy.lambdify(x,expressao,\"numpy\")(X) # avalia 'expressao' em X\nf", "meta": {"hexsha": "11eada0508baeb3e2e77b2922fc1b97060549e7d", "size": 31056, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/ipynb/02a-computacao-simbolica.py", "max_stars_repo_name": "gcpeixoto/FMECD", "max_stars_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/jupyter_execute/ipynb/02a-computacao-simbolica.py", "max_issues_repo_name": "gcpeixoto/FMECD", "max_issues_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/ipynb/02a-computacao-simbolica.py", "max_forks_repo_name": "gcpeixoto/FMECD", "max_forks_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3712984055, "max_line_length": 778, "alphanum_fraction": 0.7227266873, "include": true, "reason": "from numpy,import sympy,from sympy", "num_tokens": 10252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582506732222, "lm_q2_score": 0.9504109771915411, "lm_q1q2_score": 0.884317735258269}}
{"text": "# importing Python library \nimport numpy as np \n  \n# define Unit Step Function \ndef unitStep(v): \n    if v >= 0: \n        return 1\n    else: \n        return 0\n  \n# design Perceptron Model \ndef perceptronModel(x, w, b): \n    v = np.dot(w, x) + b \n    y = unitStep(v) \n    return y \n  \n# NOT Logic Function \n# wNOT = -1, bNOT = 0.5 \ndef NOT_logicFunction(x): \n    wNOT = -1\n    bNOT = 0.5\n    return perceptronModel(x, wNOT, bNOT) \n  \n# AND Logic Function \n# w1 = 1, w2 = 1, bAND = -1.5 \ndef AND_logicFunction(x): \n    w = np.array([1, 1]) \n    bAND = -1.5\n    return perceptronModel(x, w, bAND) \n  \n# NAND Logic Function \n# with AND and NOT   \n# function calls in sequence \ndef NAND_logicFunction(x): \n    output_AND = AND_logicFunction(x) \n    output_NOT = NOT_logicFunction(output_AND) \n    return output_NOT \n  \n# testing the Perceptron Model \ntest1 = np.array([0, 1]) \ntest2 = np.array([1, 1]) \ntest3 = np.array([0, 0]) \ntest4 = np.array([1, 0]) \n  \nprint(\"NAND({}, {}) = {}\".format(0, 1, NAND_logicFunction(test1))) \nprint(\"NAND({}, {}) = {}\".format(1, 1, NAND_logicFunction(test2))) \nprint(\"NAND({}, {}) = {}\".format(0, 0, NAND_logicFunction(test3))) \nprint(\"NAND({}, {}) = {}\".format(1, 0, NAND_logicFunction(test4)))\n\n'''\nOUTPUT\nNAND(0, 1) = 1\nNAND(1, 1) = 0\nNAND(0, 0) = 1\nNAND(1, 0) = 1\n'''", "meta": {"hexsha": "ba0b2816f914ab98e8324356f55aa108208d3e67", "size": 1299, "ext": "py", "lang": "Python", "max_stars_repo_path": "ml/Perceptrons/Perceptron as NAND operator.py", "max_stars_repo_name": "SounakMandal/AlgoBook", "max_stars_repo_head_hexsha": "3952cb49ef12f1c00e97e0cf25810170f8585748", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 191, "max_stars_repo_stars_event_min_datetime": "2020-09-28T10:00:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T14:36:55.000Z", "max_issues_repo_path": "ml/Perceptrons/Perceptron as NAND operator.py", "max_issues_repo_name": "SounakMandal/AlgoBook", "max_issues_repo_head_hexsha": "3952cb49ef12f1c00e97e0cf25810170f8585748", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 210, "max_issues_repo_issues_event_min_datetime": "2020-09-28T10:06:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T03:44:24.000Z", "max_forks_repo_path": "ml/Perceptrons/Perceptron as NAND operator.py", "max_forks_repo_name": "SounakMandal/AlgoBook", "max_forks_repo_head_hexsha": "3952cb49ef12f1c00e97e0cf25810170f8585748", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 320, "max_forks_repo_forks_event_min_datetime": "2020-09-28T09:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T16:45:57.000Z", "avg_line_length": 23.1964285714, "max_line_length": 67, "alphanum_fraction": 0.5950731332, "include": true, "reason": "import numpy", "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407191430024, "lm_q2_score": 0.9086179012632543, "lm_q1q2_score": 0.8843039396516551}}
{"text": "import numpy as np\n\ndef detA_2x2(a, b, c, d):\n    return a*d-b*c\n\ndef inv(A):\n\n    if len(A.shape) == 1:\n        return ValueError('Matix must have at least 2 dimensions!')\n    if A.shape[1] not in [2, 3]:\n        return ValueError('Matrix must be either 2x2 or 3x3!')\n\n    elif len(A.shape) == 2:\n        if A.shape[0] == 2:       # 2x2\n            detA = detA_2x2(A[0, 0], A[0,1], A[1,0], A[1,1])\n            cofactor = np.array([[A[1,1], -A[0,1]],\n                                [-A[1,0], A[0,0]]])\n            Ainv = cofactor/detA\n        else:                     # 3x3\n            detA = A[0,0]*detA_2x2(A[1,1],A[1,2],A[2,1],A[2,2]) + \\\n                    -A[0,1]*detA_2x2(A[1,0],A[1,2],A[2,0],A[2,2]) + \\\n                    +A[0,2]*detA_2x2(A[1,0],A[1,1],A[2,0],A[2,1])\n\n            cf00 = detA_2x2(A[1,1],A[1,2],A[2,1],A[2,2])\n            cf01 = detA_2x2(A[0,2],A[0,1],A[2,2],A[2,1])\n            cf02 = detA_2x2(A[0,1],A[0,2],A[1,1],A[1,2])\n            cf10 = detA_2x2(A[1,2],A[1,0],A[2,2],A[2,0])\n            cf11 = detA_2x2(A[0,0],A[0,2],A[2,0],A[2,2])\n            cf12 = detA_2x2(A[0,2],A[0,0],A[1,2],A[1,0])\n            cf20 = detA_2x2(A[1,0],A[1,1],A[2,0],A[2,1])\n            cf21 = detA_2x2(A[0,1],A[0,0],A[2,1],A[2,0])\n            cf22 = detA_2x2(A[0,0],A[0,1],A[1,0],A[1,1])\n\n            Ainv = np.array([[cf00, cf01, cf02],\n                            [cf10, cf11, cf12],\n                            [cf20, cf21, cf22]])/detA\n\n    elif len(A.shape) == 3:\n        Ainv = np.zeros_like(A)\n\n        if A.shape[1] == 2:       # 2x2\n            detA = detA_2x2(A[:,0, 0], A[:,0,1], A[:,1,0], A[:,1,1])\n\n            cf00 = A[:,1,1]\n            cf01 = -A[:,0,1]\n            cf10 = -A[:,1,0]\n            cf11 = A[:,0,0]\n\n            Ainv[:,0,0] = cf00\n            Ainv[:,0,1] = cf01\n            Ainv[:,1,0] = cf10\n            Ainv[:,1,1] = cf11\n\n            Ainv = Ainv/detA[:,None,None]\n        else:                     # 3x3\n            detA = A[:,0,0]*detA_2x2(A[:,1,1],A[:,1,2],A[:,2,1],A[:,2,2]) + \\\n                    -A[:,0,1]*detA_2x2(A[:,1,0],A[:,1,2],A[:,2,0],A[:,2,2]) + \\\n                    +A[:,0,2]*detA_2x2(A[:,1,0],A[:,1,1],A[:,2,0],A[:,2,1])\n\n            cf00 = detA_2x2(A[:,1,1],A[:,1,2],A[:,2,1],A[:,2,2])\n            cf01 = detA_2x2(A[:,0,2],A[:,0,1],A[:,2,2],A[:,2,1])\n            cf02 = detA_2x2(A[:,0,1],A[:,0,2],A[:,1,1],A[:,1,2])\n            cf10 = detA_2x2(A[:,1,2],A[:,1,0],A[:,2,2],A[:,2,0])\n            cf11 = detA_2x2(A[:,0,0],A[:,0,2],A[:,2,0],A[:,2,2])\n            cf12 = detA_2x2(A[:,0,2],A[:,0,0],A[:,1,2],A[:,1,0])\n            cf20 = detA_2x2(A[:,1,0],A[:,1,1],A[:,2,0],A[:,2,1])\n            cf21 = detA_2x2(A[:,0,1],A[:,0,0],A[:,2,1],A[:,2,0])\n            cf22 = detA_2x2(A[:,0,0],A[:,0,1],A[:,1,0],A[:,1,1])\n\n            Ainv[:,0,0] = cf00\n            Ainv[:,0,1] = cf01\n            Ainv[:,0,2] = cf02\n            Ainv[:,1,0] = cf10\n            Ainv[:,1,1] = cf11\n            Ainv[:,1,2] = cf12\n            Ainv[:,2,0] = cf20\n            Ainv[:,2,1] = cf21\n            Ainv[:,2,2] = cf22\n\n            Ainv = Ainv/detA[:,None,None]\n\n    return Ainv, detA\n\nif __name__ == '__main__':\n    A_2x2 = np.random.rand(2,2)\n    A_3x3 = np.random.rand(3,3)\n\n\n    print(np.linalg.norm((np.linalg.inv(A_2x2) - inv(A_2x2))))\n    print(np.linalg.norm((np.linalg.inv(A_3x3) - inv(A_3x3))))\n\n    a = np.array([[[4, 8, 2],\n                    [5, 0, 2],\n                    [1, 1, 3]],\n                    \n                    [[7, 0, 8],\n                    [9, 5, 4],\n                    [3, 4, 2]]])\n\n    b = np.array([[[4, 8],\n                    [5, 0]],\n                    \n                    [[7, 0],\n                    [9, 5]]])\n\n    #2x2\n    i = np.zeros_like(a, dtype=float)\n    i[0,:,:] = np.linalg.inv(a[0,:,:])\n    i[1,:,:] = np.linalg.inv(a[1,:,:])\n\n    i_custom = inv(a)\n\n    print(np.linalg.norm(i-i_custom))\n\n    #3x3\n    i = np.zeros_like(b, dtype=float)\n    i[0,:,:] = np.linalg.inv(b[0,:,:])\n    i[1,:,:] = np.linalg.inv(b[1,:,:])\n\n    i_custom = inv(b)\n\n    print(np.linalg.norm(i-i_custom))\n", "meta": {"hexsha": "920c92de2c05dc04ea07db71e7a8467dfc178b9f", "size": 4050, "ext": "py", "lang": "Python", "max_stars_repo_path": "util/math_helper_fcns.py", "max_stars_repo_name": "saustinp/3D-CG", "max_stars_repo_head_hexsha": "8d3e161674273649af1f23b2a0e1d5100971477a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util/math_helper_fcns.py", "max_issues_repo_name": "saustinp/3D-CG", "max_issues_repo_head_hexsha": "8d3e161674273649af1f23b2a0e1d5100971477a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/math_helper_fcns.py", "max_forks_repo_name": "saustinp/3D-CG", "max_forks_repo_head_hexsha": "8d3e161674273649af1f23b2a0e1d5100971477a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9268292683, "max_line_length": 79, "alphanum_fraction": 0.382962963, "include": true, "reason": "import numpy", "num_tokens": 1726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407168145568, "lm_q2_score": 0.9086178969328286, "lm_q1q2_score": 0.8843039333214412}}
{"text": "\"\"\"\ntest_numpy.fft_example_01.py\n\nThis is an example code for numpy.fft.fft\nhttps://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fft.html#numpy.fft.fft\n\nMore in general, Discrete Fourier Transform (numpy.fft)\nhttps://docs.scipy.org/doc/numpy/reference/routines.fft.html\n\n>>> np.arange(8)\narray([0, 1, 2, 3, 4, 5, 6, 7])\n\nwhen x=0, a=1,\n        ...\n     x=8, e^2(pi)j\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.arange(8)\na = np.exp( 2j*np.pi * x/8 )\nplt.plot( a )\nnp.fft.fft( a )\n\nt = np.arange(256)\n#array([0, 1, 2, ... , 254, 255])\nsp = np.fft.fft( np.sin(t) )\nfreq = np.fft.fftfreq( t.shape[-1] )\nplt.plot( freq, sp.real, freq, sp.imag )\nplt.show()\n\n\"\"\"\nIn this example, real input has an FFT which is Hermitian,\ni.e., symmetric in the real part and anti-symmetric in the imaginary part,\nas described in the numpy.fft documentation:\n\"\"\"\n\nplt.figure()\n\nplt.subplot(211)\nplt.title(\"Real part\")\nplt.plot( freq, sp.real )\nplt.grid(True)\nplt.axis([-0.5,0.5,-100,100])\nplt.ylabel(\"?\")\n\nplt.subplot(212)\nplt.title(\"Imagenary part\")\nplt.plot( freq, sp.imag )\nplt.grid(True)\n\nplt.axis([-0.5,0.5,-100,100])\nplt.xlabel(\"?\")\nplt.ylabel(\"?\")\n\n#plt.title(\"Spectrum of r'$e^(2\\pij*x/8)$'\")\n\n", "meta": {"hexsha": "143fb1b9dc5d82c19fe688981638fd86fcbbae01", "size": 1209, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/en/_numpy/organize_this/test_numpy.fft_example_01.py", "max_stars_repo_name": "aimldl/coding", "max_stars_repo_head_hexsha": "70ddbfaa454ab92fd072ee8dc614ecc330b34a70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/en/_numpy/organize_this/test_numpy.fft_example_01.py", "max_issues_repo_name": "aimldl/coding", "max_issues_repo_head_hexsha": "70ddbfaa454ab92fd072ee8dc614ecc330b34a70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/en/_numpy/organize_this/test_numpy.fft_example_01.py", "max_forks_repo_name": "aimldl/coding", "max_forks_repo_head_hexsha": "70ddbfaa454ab92fd072ee8dc614ecc330b34a70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4915254237, "max_line_length": 85, "alphanum_fraction": 0.6592224979, "include": true, "reason": "import numpy", "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360066, "lm_q2_score": 0.926303724699188, "lm_q1q2_score": 0.8842934616022358}}
{"text": "#!/usr/bin/env python\n\n#\tSigular Value Decomposition (SVD)\n#\t\tTrucco, Appendix A.6\n#\n#\tdefinition\n#\n#\t\t\tA = U*D*transpose(V)\n#\n#\t\tA any real m x n matrix\n#\t\tU is m x n matrix that columns are eigenvectors of A*transpose(A)\n#\t\t\tA*transpose(A) = U * D * transpose(V) * V * D * transpose(U) = U * D^2 * transpose(U)\n#\t\tV is n x n matrix that columns are eivenvectors of transpose(A)*A \n#\t\t\ttranspose(A)*A = V * D * transpose(U) * U * D * transpose(V) = V * D^2 * transpose(V)\n#\t\tD is n x n diagonal matrix (non-negative real values called sigular values)\n# \n#\tcomputing the inverse of a matrix using SVD\n#\t\t\n#\t\tinverse(A) = V*inverse(D)*transpose(U)\n#\t\t\twhere inverse(D) are 1/singular values\t\n#\n\n#\n#\t\t|-     -|\n#\t\t| 1 2 1 |\n#\tA = | 2 3 2 | \n#\t\t| 1 2 1 |\n#\t\t|_\t   _|\n#\n#\t\t\t\t\t\t\t\t\t\t\t   |-\t     -|\n#\t\t\t\t\t\t\t\t\t\t\t   | 6  10 6  |\n#\tA * transpose( A ) = transpose( A ) * A =  | 10 17 10 |\n#\t\t\t\t\t\t\t\t\t\t\t   | 6  10 6  |\n#\t\t\t\t\t\t\t\t\t\t\t   |_\t     _|\n\nimport numpy as np\n\nEpsilon = 1e-12\n\n\na = np.array( [ [ 1, 2, 1 ],\n\t\t\t\t[ 2, 3, 2 ],\n\t\t\t\t[ 1, 2, 1 ],\n\t\t\t] )\nprint( '  matrix A = {}'.format( a ) )\n\n#\tbasic inverse matrix\nprint( '###################################################' )\nprint( 'basic method inverse matrix...............' )\n\n#\ttry to inverse using basic method 1/det(a) * adj(a)\ntry:\n\tinverseA = np.linalg.inv( a )\n\tprint( '  matrix inverse( A ) = {}'.format( inverseA ) )\nexcept np.linalg.linalg.LinAlgError as e:\n\tprint( 'ERROR!!! Cannot inverse matrix : {}'.format( e ) )\n\nprint( '###################################################' )\nprint( 'SVD method inverse matrix...............' )\n\n#\tconstruct A * transpose( A )\naMultiplyTransposeA = np.array( [ [ 6, 10, 6 ],\n\t\t\t\t\t\t\t\t\t[ 10, 17, 10 ],\n\t\t\t\t\t\t\t\t\t[ 6, 10, 6 ],\n\t\t\t\t\t\t\t\t] )\nprint( '  matrix A * trasnpose( A ) = {}'.format( aMultiplyTransposeA ) )\n\n#\tcalculate eigenvalues and eigenvectors\nprint( '      calculating eigen values/vectors' )\neigenvalues, eigenvectors = np.linalg.eig( aMultiplyTransposeA )\nprint( '      eigenvalues of matrix A * trasnpose( A ) = {}'.format( eigenvalues ) )\nprint( '      eigenvectors of matrix A * trasnpose( A ) = {}'.format( eigenvectors ) )\n\n#\tconstruct the D matrix from eigenvalues\nd = np.array( [ [ eigenvalues[0], 0, 0 ],\n\t\t\t\t[ 0, eigenvalues[1], 0 ],\n\t\t\t\t[ 0, 0, eigenvalues[2] ] \n\t\t\t] )\nprint( '\\n    d matrix = {}'.format( d ) )\n\t\t\t\n#\tconstruct the U and V matrix from eigenvectors\nu = np.array( eigenvectors )\nprint( '    u matrix = {}'.format( u ) )\n\n#\tconstruct transpose v\nvt = np.array( [ [ eigenvectors[0][0], eigenvectors[1][0], eigenvectors[2][0] ], \n\t\t\t\t\t[ eigenvectors[0][1], eigenvectors[1][1], eigenvectors[2][1] ],\n\t\t\t\t\t[ eigenvectors[0][2], eigenvectors[1][2], eigenvectors[2][2] ],\n\t\t\t\t ] )\nprint( '    vt matrix = {}'.format( vt ) )\n\nprint( '    testing by calculate A from U*D*transpose(V)..............' )\nresult = np.matmul( u, d )\nresult = np.matmul( result, vt )\nprint( '         result from reconstruct A from SVD = {}'.format( result ) )\nassert( ( a[0][0] - result[0][0] < Epsilon ) and ( a[0][1] - result[0][1] < Epsilon ) and ( a[0][2] - result[0][2] < Epsilon )\n\t\tand ( a[1][0] - result[1][0] < Epsilon ) and ( a[1][1] - result[1][1] < Epsilon ) and ( a[1][2] - result[1][2] < Epsilon )\n\t\tand ( a[2][0] - result[2][0] < Epsilon ) and ( a[2][1] - result[2][1] < Epsilon ) and ( a[2][2] - result[2][2] < Epsilon ) )\n\nprint( '..........................................' )\nprint( '\\n\\n    preparing data to do a inverse matrix from V*inverse(D)*transpose(U)..............' )\n\n#\tcalculate inverse of D\ninverseD = np.array( [ [ 1./eigenvalues[0] if eigenvalues[0] > Epsilon else 0, 0, 0 ],\n\t\t\t\t\t\t[ 0, 1./eigenvalues[1] if eigenvalues[1] > Epsilon else 0, 0 ],\n\t\t\t\t\t\t[ 0, 0, 1./eigenvalues[2] if eigenvalues[2] > Epsilon else 0 ] \n\t\t\t\t\t] )\nprint( '\\n    inverse(D) matrix = {}'.format( inverseD ) )\n\n#\tconstruct v from eigenvectors\nv = np.array( eigenvectors )\nprint( '    v matrix = {}'.format( v ) )\n\n#\tconstruct transpose u\nut = np.array( [ [ eigenvectors[0][0], eigenvectors[1][0], eigenvectors[2][0] ], \n\t\t\t\t\t[ eigenvectors[0][1], eigenvectors[1][1], eigenvectors[2][1] ],\n\t\t\t\t\t[ eigenvectors[0][2], eigenvectors[1][2], eigenvectors[2][2] ],\n\t\t\t\t ] )\nprint( '    ut matrix = {}'.format( ut ) )\n\nprint( '\\n\\n    testing by calculate inverse( A ) from V*inverse(D)*transpose(U)..............' )\ninverseA = np.matmul( v, inverseD )\ninverseA = np.matmul( result, ut )\nprint( '         result from reconstruct inverse of A from SVD = {}'.format( inverseA ) )\n\n#\tchecking the inverse matrix\naMultiplyInverseA = np.matmul( a, inverseA )\nprint( '         checking the inverse of A by A * inverse(A) = {}'.format( aMultiplyInverseA ) )\n\n\n\n\t\t\t\n\n", "meta": {"hexsha": "56fa505deb7c2aa43720b96473de96580ccb9449", "size": 4656, "ext": "py", "lang": "Python", "max_stars_repo_path": "understanding_svd_and_pseudoinverse/understanding_svd_and_pseudoinverse.py", "max_stars_repo_name": "wiphoo/experimental-numpy", "max_stars_repo_head_hexsha": "ba13444c44cb514c2df61953c1f024766ab512eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "understanding_svd_and_pseudoinverse/understanding_svd_and_pseudoinverse.py", "max_issues_repo_name": "wiphoo/experimental-numpy", "max_issues_repo_head_hexsha": "ba13444c44cb514c2df61953c1f024766ab512eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "understanding_svd_and_pseudoinverse/understanding_svd_and_pseudoinverse.py", "max_forks_repo_name": "wiphoo/experimental-numpy", "max_forks_repo_head_hexsha": "ba13444c44cb514c2df61953c1f024766ab512eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7462686567, "max_line_length": 126, "alphanum_fraction": 0.5573453608, "include": true, "reason": "import numpy", "num_tokens": 1567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611643025387, "lm_q2_score": 0.9207896845856297, "lm_q1q2_score": 0.8842906535664227}}
{"text": "'''\r\n------------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\nAuthor:B.Ajay\r\nLicence:Apache 2.0\r\n------------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n'''\r\n\r\nimport random as r\r\nimport math\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nlx,ly=[],[]\r\ndef compute_pi(sample_points):\r\n    inside_point_ctr=0\r\n    for i in range(sample_points):\r\n        x=r.random()\r\n        y=r.random()\r\n        lx.append(x)\r\n        ly.append(y)\r\n        if(math.sqrt(x**2+y**2)<=1):inside_point_ctr+=1\r\n    return 4*inside_point_ctr/sample_points        \r\ndef draw():\r\n    x_axis=np.linspace(0,1.0,150)\r\n    y_axis=np.linspace(0,1.0,150)\r\n    a,b=np.meshgrid(x_axis,y_axis)\r\n    circle_equation=a**2+b**2-1.0\r\n    _,axis=plt.subplots()\r\n    axis.contour(a,b,circle_equation,[0])\r\n    plt.scatter(lx,ly,s=0.001)\r\n    axis.set_aspect(1)\r\n    plt.title(\"Scatter Plot of Points sampled\")\r\n    plt.show()\r\nsample_point=int(input(\"Enter the number of sample points to compute pi->Enter a large value 10000<x<10000000\"))\r\nflag='y'\r\nif sample_point>10000000:\r\n    flag=input(\"This value is much above the limit .Allowing this process may hog your memory .Do you still want to proceed?[y/n]\")\r\nif flag=='y':    \r\n    print(\"The Computation may take seconds to compute Please wait\")\r\n    print(\"Value of Pi (approximated): \",compute_pi(sample_point))\r\n    draw()\r\nelse:\r\n    exit()\r\n", "meta": {"hexsha": "a114e02ebefbc4d53e848ca0120678eee04ddfef", "size": 1593, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/picalc.py", "max_stars_repo_name": "AjayBadrinath/Compute_pi", "max_stars_repo_head_hexsha": "a0c1e6b29c722ad29ba7b217da9e6673c2b79766", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/picalc.py", "max_issues_repo_name": "AjayBadrinath/Compute_pi", "max_issues_repo_head_hexsha": "a0c1e6b29c722ad29ba7b217da9e6673c2b79766", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/picalc.py", "max_forks_repo_name": "AjayBadrinath/Compute_pi", "max_forks_repo_head_hexsha": "a0c1e6b29c722ad29ba7b217da9e6673c2b79766", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0465116279, "max_line_length": 169, "alphanum_fraction": 0.5109855618, "include": true, "reason": "import numpy", "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862454, "lm_q2_score": 0.9196425399873764, "lm_q1q2_score": 0.8842673954834186}}
{"text": "import csv\nimport math\nimport random\nimport os.path\nimport operator\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom copy import deepcopy\nfrom functools import reduce\n\n\n\"\"\"\n    FURB - Bacharelado em Ciências da Computação\n    Inteligência Artificial\n    Trabalho 03 - Fase 03 - Regressão Polinomial - Overfitting\n    Equipe: Adriner Maranho de Andrade, Fábio Luiz Fischer, Felipe Anselmo dos Santos, Jorge Guilherme Kohn\n\n    Faça um script demo_regressaop que faz o seguinte:\n        a) Baixe o arquivo data_preg.mat ou data_preg.svg. A primeira coluna representa os valores de x e a segunda coluna representa os valores de y.\n        b) Faça o Gráfico de dispersão dos dados.\n        c) Use a função polyfit para gerar a linha de regressão para N = 1 e trace-o no gráfico de dispersão na cor vermelha (plot (x, y, 'r')).\n        (observe que nesta função a numeração coeficiente é invertida! β0=βN, β1=βN−1, β2=βN−2 , ...βN=β0)\n        d) Trace a linha de regressão para N = 2 no gráfico na cor verde.\n        e) Trace a linha de regressão para N = 3 no gráfico na cor preta.\n        f) Trace a linha de regressão para N = 8 no gráfico na cor amarela.\n        g) Calcule o Erro Quadrático Médio (EQM) para cada linha de regressão. Qual é o mais preciso?\n            Resposta: A linha de regressão para N=8 é mais precisa para esse cenário pois obteve o menor erro quadrático médio: 0.05870934697363511\n        h) Para evitar o overfitting, divida os dados aleatoriamente em Dados de Treinamento e Dados de Teste. Use os primeiros 10% dos dados como conjunto de teste, e o resto como de treinamento.\n        i) Repita os passos de c - f, mas agora use apenas os dados de treinamento para ajustar a linha de regressão.\n        J) Repita o passo g, mas agora utilize somente os dados de Teste para calcular o erro.\n        k) Que método é o mais preciso neste caso?\n            Resposta: Apesar de cada regressão poder se sobressair de acordo com os dados selecionados para o treinamento,\n                nas execuções realizadas a regressão N=2 teve o melhor resultado em 5 execuções consecutivas de 5000 iterações.\n                Em média, a regressão N=2 se saiu melhor em 50% das iterações da execução.\n\n                Execução 1 - 5000 iterações\n                    N1 teve o melhor EQM 14 vezes\n                    N2 teve o melhor EQM 2779 vezes\n                    N3 teve o melhor EQM 1104 vezes\n                    N8 teve o melhor EQM 1103 vezes\n\n                Execução 2 - 5000 iterações\n                    N1 teve o melhor EQM 27 vezes\n                    N2 teve o melhor EQM 2721 vezes\n                    N3 teve o melhor EQM 1112 vezes\n                    N8 teve o melhor EQM 1140 vezes\n\n                Execução 3 - 5000 iterações\n                    N1 teve o melhor EQM 25 vezes\n                    N2 teve o melhor EQM 2718 vezes\n                    N3 teve o melhor EQM 1137 vezes\n                    N8 teve o melhor EQM 1120 vezes\n\n                Execução 4 - 5000 iterações\n                    N1 teve o melhor EQM 23 vezes\n                    N2 teve o melhor EQM 2708 vezes\n                    N3 teve o melhor EQM 1133 vezes\n                    N8 teve o melhor EQM 1136 vezes\n\n                Execução 5 - 5000 iterações\n                    N1 teve o melhor EQM 14 vezes\n                    N2 teve o melhor EQM 2725 vezes\n                    N3 teve o melhor EQM 1108 vezes\n                    N8 teve o melhor v 1153 vezes\n\"\"\"\n\n\ndef strnum(x):\n    return round(x, 2)\n\n\nclass DataSet:\n    def __init__(self, x, y):\n        self.x = np.array(x)\n        self.y = np.array(y)\n        self.lenght = len(self.x)\n\nclass RegressaoPolinomial:\n    def __init__(self, dataset):\n        self.dataset = dataset\n\n    def regressaop(self, n, outro=None):\n        # Chama a função polyfit e inverte seu resultado, pois sua numeração coeficiente é invertida\n        b = np.polyfit(self.dataset.x, self.dataset.y, n)[::-1]\n\n        def somatoriap(b, x):\n            resultado = 0\n            for i in range(n+1):\n                resultado += b[i] * x ** i\n            return np.array(resultado)\n        # Quando outro objeto for passado como parâmetro o valor do polyfit será compartilhado entre o calculo de ambos\n        if outro is None:\n            return somatoriap(b, self.dataset.x)\n        return somatoriap(b, self.dataset.x), somatoriap(b, outro.dataset.x)\n\n    @staticmethod\n    def eqm(y1, y2):\n        # Se o tamanho dos vetores de entrada for diferente, deve ser feito um broadcasting do maior para o menor,\n        # de forma que os elementos faltantes no array menor sejam iguais aos do array maior\n        if len(y1) != len(y2):\n            y1y = y1 if len(y1) > len(y2) else np.array([y1[i] if i < len(y1) else y2[i] for i in range(len(y2))])\n            y2y = y2 if len(y2) > len(y1) else np.array([y2[i] if i < len(y2) else y1[i] for i in range(len(y1))])\n            return reduce(operator.add, (y1y - y2y) ** 2) / len(y2y)\n        return reduce(operator.add, (y1 - y2) ** 2) / len(y2)\n\n\n# Realiza leitura do arquivo e parsing dos valores para float\nwith open(os.path.join(os.path.abspath(os.path.dirname(__file__)), \"data_preg.csv\")) as file:\n    raw_data = csv.reader(file, delimiter=',')\n    data = [[float(elem) for elem in row] for row in raw_data]\n\nif data is not None:\n    ds = DataSet([elem[0] for elem in data], [elem[1] for elem in data])\n    rp = RegressaoPolinomial(ds)\n\n    # Cria diagrama de disperção dos pontos do dataset\n    fig = plt.figure('Gráfico de disperção')\n    plt.title('Vermelho: N1  Verde: N2  Preto: N3  Amarelo: N8')\n    plt.grid(True)\n    plt.scatter(ds.x, ds.y)\n\n    # Gera a linha de regressão polinomial para N1 em vermelho\n    y1 = rp.regressaop(1)\n    plt.plot(ds.x, y1, 'r')\n    # Gera a linha de regressão polinomial para N2 em verde\n    y2 = rp.regressaop(2)\n    plt.plot(ds.x, y2, 'g')\n    # Gera a linha de regressão polinomial para N3 em preto\n    y3 = rp.regressaop(3)\n    plt.plot(ds.x, y3, 'k')\n    # Gera a linha de regressão polinomial para N8 em amarelo\n    y4 = rp.regressaop(8)\n    plt.plot(ds.x, y4, 'y')\n\n    # Calcula o erro quadratico médio EQM para cada uma das regressões\n    eqm = [[y, RegressaoPolinomial.eqm(y[1], ds.y)] for y in [('N1', y1), ('N2', y2), ('N3', y3), ('N8', y4)]]\n    for i in range(len(eqm)):\n        print('EQM da regressão de %s' % eqm[i][0][0], eqm[i][1])\n    plt.show()\n\n    resultados = []\n    # Treinamento para evitar underfitting e overfitting\n    # Número de iterações para o treinamento\n    iteracoes = 5000\n    # 'True' para exibir as regressões, 'False' para exeibir apenas o resultado final\n    exibeDiagramaTreinamento = False\n\n    print('\\nIniciando treinamento para evitar underfitting e overfitting...')\n    print('Utilizando', iteracoes, 'iterações\\n')\n\n    for i in range(iteracoes):\n        # Cria uma cópia dos dados do dataset e randomiza o endereçamento deles na matriz\n        datai = deepcopy(data)\n        random.shuffle(datai)\n\n        # Seleciona 10% dos dados aleatórios como dados para teste e os outros 90% para dados de treinamento\n        # Ordena os valores para melhor qualidade na exibição do gráfico\n        index = round((ds.lenght * 10) / 100)\n        data_tes = datai[0:index]\n        data_tre = datai[index:ds.lenght]\n        data_tre.sort()\n\n        ds_tes = DataSet([elem[0] for elem in data_tes], [elem[1] for elem in data_tes])\n        ds_tre = DataSet([elem[0] for elem in data_tre], [elem[1] for elem in data_tre])\n        rp_tes = RegressaoPolinomial(ds_tes)\n        rp_tre = RegressaoPolinomial(ds_tre)\n\n        if exibeDiagramaTreinamento:\n            fig = plt.figure('Treinamento de Regressão Polinominial')\n            plt.grid(True)\n            plt.scatter(ds_tes.x, ds_tes.y)\n            plt.scatter(ds_tre.x, ds_tre.y, c='b')\n\n        # Calcula a regressão polinomial dos datasets de treino e de teste com o mesmo polyfit\n        y1_tre, y1_tes = rp_tre.regressaop(1, rp_tes)\n        y2_tre, y2_tes = rp_tre.regressaop(2, rp_tes)\n        y3_tre, y3_tes = rp_tre.regressaop(3, rp_tes)\n        y4_tre, y4_tes = rp_tre.regressaop(8, rp_tes)\n\n        if exibeDiagramaTreinamento:\n            plt.plot(ds_tre.x, y1_tre, 'r')\n            plt.plot(ds_tre.x, y2_tre, 'g')\n            plt.plot(ds_tre.x, y3_tre, 'k')\n            plt.plot(ds_tre.x, y4_tre, 'y')\n\n        # Calcula o erro quadratico médio EQM para cada uma das regressões\n        eqm_tre = [('N1', y1_tre, y1_tes), ('N2', y2_tre, y2_tes), ('N3', y3_tre, y3_tes), ('N8', y4_tre, y4_tes)]\n        eqm = [[y, RegressaoPolinomial.eqm(y[1], y[2])] for y in eqm_tre]\n\n        # Salva o melhor resultado  na lista de resultados\n        melhor = None\n        for res in eqm:\n            melhor = res if melhor is None or res[1] < melhor[1] else melhor\n        resultados.append(melhor)\n\n    if exibeDiagramaTreinamento:\n        plt.show()\n    # Sumariza o resultado do treinamento atravéz da iterações\n    # Informa a qunatidade vezes que cada valor de N teve o melhor resultado\n    for tre in ['N1', 'N2', 'N3', 'N8']:\n        aux = list(filter(lambda res: res[0][0] == tre, resultados))\n        print('%s teve o melhor EQM %s vezes' % (tre, len(aux)))\n\nelse:\n    print('Erro ao ler arquivo')\n\n\n", "meta": {"hexsha": "acbfa3907f709f523e0112c4926e8a824b81b55d", "size": 9224, "ext": "py", "lang": "Python", "max_stars_repo_path": "trabalhos/trab-03-correlacao_regressao/fase-03/demo_regressaop.py", "max_stars_repo_name": "FabioFischer/furb-ia", "max_stars_repo_head_hexsha": "f45edb90515e4e2291b0f34ca2ac7766fe352d1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trabalhos/trab-03-correlacao_regressao/fase-03/demo_regressaop.py", "max_issues_repo_name": "FabioFischer/furb-ia", "max_issues_repo_head_hexsha": "f45edb90515e4e2291b0f34ca2ac7766fe352d1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trabalhos/trab-03-correlacao_regressao/fase-03/demo_regressaop.py", "max_forks_repo_name": "FabioFischer/furb-ia", "max_forks_repo_head_hexsha": "f45edb90515e4e2291b0f34ca2ac7766fe352d1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3461538462, "max_line_length": 196, "alphanum_fraction": 0.6283607979, "include": true, "reason": "import numpy", "num_tokens": 2767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338057771058, "lm_q2_score": 0.9196425223682085, "lm_q1q2_score": 0.8842673744871606}}
{"text": "\r\n# NumPy is often used along with packages like SciPy (Scientific Python) and Mat−plotlib (plotting library). This combination is widely used as a replacement for MatLab\r\n# ndarray - an N-dimensional array; collection of items of the same type; items can be accessed using a zero-based index\r\n# Each element in ndarray is an object of data-type object (called dtype)\r\n\r\nimport numpy as np \r\na = np.array([1,2,3])  # [1, 2, 3]\r\na = np.array([[1, 2], [3, 4]]) \r\n'''\r\n[[1, 2] \r\n [3, 4]]\r\n'''\r\n\r\n# ndarray.shape - this array attribute returns a tuple consisting of array dimensions\r\na = np.array([[1,2,3],[4,5,6]]) \r\nprint(a.shape) # (2, 3)\r\n\r\n# It can also be used to resize the array\r\na.shape=(3,2)\r\n'''\r\n[[1, 2] \r\n [3, 4] \r\n [5, 6]]\r\n'''\r\n\r\n# NumPy also provides a reshape function to resize an array\r\na.reshape(3,2) \r\n\r\na.ndim # 2 dimentional array\r\n\r\n# numpy.linspace - this function is similar to arange() function. \r\n# In this function, instead of step size, the number of evenly spaced values between the interval is specified\r\n# numpy.linspace(start, stop, num, endpoint, retstep, dtype)\r\nx = np.linspace(10,20,5)  # [10.   12.5   15.   17.5  20.]\r\n\r\n# numpy.logspace - this function returns an ndarray object that contains the numbers that are evenly spaced on a log scale. \r\n# Start and stop endpoints of the scale are indices of the base, usually 10.\r\n# numpy.logspace(start, stop, num, endpoint, base, dtype)\r\n# default base is 10 \r\na = np.logspace(1.0, 2.0, num = 10) \r\n'''\r\n[ 10.           12.91549665     16.68100537      21.5443469  27.82559402      \r\n  35.93813664   46.41588834     59.94842503      77.42636827    100.    ]\r\n'''\r\na = np.logspace(1,10,num = 10, base = 2) \r\n# [ 2.     4.     8.    16.    32.    64.   128.   256.    512.   1024.] \r\n\r\n\r\n# arange funciton produces a list of numbers based on specifications\r\n# numpy.arange(start, stop, step, dtype)\r\na=np.arange(8) # array([0, 1, 2, 3, 4, 5, 6, 7])\r\n# now reshape it \r\nb = a.reshape(2,2,2) \r\nprint(b) # b has three dimensions\r\n\r\nb.dtype # its int32\r\nb.itemsize\r\n\r\n# specify data type\r\nx = np.array([1,2,3,4,5], dtype = np.float32) \r\n\r\n'''\r\ndifferent data types\r\nbool_ Boolean (True or False) stored as a byte\r\nint_ Default integer type (same as C long; normally either int64 or int32)\r\nintc Identical to C int (normally int32 or int64)\r\nintp Integer used for indexing (same as C ssize_t; normally either int32 or int64)\r\nint8 Byte (-128 to 127)\r\nint16 Integer (-32768 to 32767)\r\nint32 Integer (-2147483648 to 2147483647)\r\nint64 Integer (-9223372036854775808 to 9223372036854775807)\r\nuint8 Unsigned integer (0 to 255)\r\nuint16 Unsigned integer (0 to 65535)\r\nuint32 Unsigned integer (0 to 4294967295)\r\nuint64 Unsigned integer (0 to 18446744073709551615)\r\nfloat_ Shorthand for float64\r\nfloat16 Half precision float: sign bit, 5 bits exponent, 10 bits mantissa\r\nfloat32 Single precision float: sign bit, 8 bits exponent, 23 bits mantissa\r\nfloat64 Double precision float: sign bit, 11 bits exponent, 52 bits mantissa\r\ncomplex_ Shorthand for complex128\r\ncomplex64 Complex number, represented by two 32-bit floats (real and imaginary components)\r\ncomplex128 Complex number, represented by two 64-bit floats (real and imaginary components)\r\n'''\r\n\r\n\r\n# numpy.empty creates an uninitialized array of specified shape and dtype\r\nx = np.empty([3,2], dtype = int) \r\nprint(x)\r\n'''\r\n[[ -572458896         495]\r\n [          0           0]\r\n [          1 -2147483648]]\r\nNote − The elements in an array show random values as they are not initialized\r\n'''\r\n\r\n# numpy.zeros returns a new array of specified size, filled with zeros\r\nx = np.zeros(5)  # array([0., 0., 0., 0., 0.])\r\nx = np.zeros((5,), dtype = np.int)  # array([0, 0, 0, 0, 0])\r\nx = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')])  \r\n'''\r\narray([[(0, 0), (0, 0)],\r\n       [(0, 0), (0, 0)]], dtype=[('x', '<i4'), ('y', '<i4')])\r\n'''\r\n\r\n# numpy.ones returns a new array of specified size and type, filled with ones\r\nx = np.ones(5)  # array([1., 1., 1., 1., 1.])\r\nx = np.ones([2,2], dtype = int) \r\n'''\r\narray([[1, 1],\r\n       [1, 1]])\r\n'''\r\n\r\n\r\n# numpy.asarray - this function is similar to numpy.array \r\n# # except for the fact that it has fewer parameters. \r\n# # This routine is useful for converting Python sequence into ndarray.\r\n\r\n# convert list to ndarray\r\nx = [1,2,3] \r\na = np.asarray(x)\r\n\r\n# dtype is set \r\nx = [1,2,3]\r\na = np.asarray(x, dtype = float) \r\n\r\n# ndarray from tuple \r\nx = (1,2,3) \r\na = np.asarray(x) \r\n\r\n# ndarray from list of tuples \r\nx = [(1,2,3),(4,5)] \r\na = np.asarray(x) \r\n\r\n\r\n# numpy.frombuffer - this function interprets a buffer as one-dimensional array. \r\n# Any object that exposes the buffer interface is used as parameter to return an ndarray.\r\ns = 'Hello World' \r\na = np.frombuffer(s, dtype = 'S1') \r\n\r\n\r\n# numpy.fromiter\r\n# This function builds an ndarray object from any iterable object.\r\n# A new one-dimensional array is returned by this function.\r\nlist = range(5) \r\nit = iter(list)   # obtain iterator object from list \r\nx = np.fromiter(it, dtype = float)   # use iterator to create ndarray \r\n\r\n\r\n# Slicing one dim array [start:stop:step<one-by-default>]\r\na = np.arange(10) \r\nslice(2,7,2)  # [2  4  6]\r\na[2:7:2]  # array([2, 4, 6])\r\na[2:7] # array([2, 3, 4, 5, 6])\r\na[5]  # 5 - this is just an individual int not an array\r\na[7:]  # array([7, 8, 9])\r\n\r\n# Slicing two dim array\r\na = np.arange(9) \r\na.shape=(3,3)\r\n'''\r\narray([[0, 1, 2],\r\n       [3, 4, 5],\r\n       [6, 7, 8]])\r\n'''\r\na[2,2] # 8\r\na[1,:]  # array([3, 4, 5]) - we can skip specifying :\r\na[:,1] # array([1, 4, 7]) - we cant skip specifying :\r\na[1:,:] # all columns of row 2 and 3 \r\n'''\r\narray([[3, 4, 5],\r\n       [6, 7, 8]])\r\n'''\r\n\r\n\r\n# NaN (Not a Number) elements can be omitted by using ~ (complement operator)\r\na = np.array([np.nan, 1,2,np.nan,3,4,5]) \r\nprint(a[~np.isnan(a)]) # [1. 2. 3. 4. 5.]\r\n\r\n# filter out the non-complex elements from an array\r\na = np.array([1, 2+6j, 5, 3.5+5j]) \r\nprint(a[np.iscomplex(a)]) # [2. +6.j 3.5+5.j]\r\n\r\n'''\r\nBroadcasting \r\n-Ability of NumPy to treat arrays of different shapes during arithmetic operations. \r\n-Arithmetic operations on arrays are usually done on corresponding elements. \r\n-If two arrays are of exactly the same shape, then these operations are smoothly performed.\r\n\r\nBroadcasting is possible if the following rules are satisfied −\r\n-Array with smaller ndim than the other is prepended with '1' in its shape.\r\n-Size in each dimension of the output shape is maximum of the input sizes in that dimension.\r\n-An input can be used in calculation, if its size in a particular dimension matches the output size or its value is exactly 1.\r\n-If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension.\r\n\r\nA set of arrays is said to be broadcastable if the above rules produce a valid result and one of the following is true −\r\n-Arrays have exactly the same shape.\r\n-Arrays have the same number of dimensions and the length of each dimension is either a common length or 1.\r\n-Array having too few dimensions can have its shape prepended with a dimension of length 1, so that the above stated property is true.\r\n'''\r\na = np.array([[0.0,0.0,0.0],[10.0,10.0,10.0],[20.0,20.0,20.0],[30.0,30.0,30.0]]) \r\nb = np.array([1.0,2.0,3.0])  \r\n'''\r\nFirst array:\r\n[[ 0. 0. 0.]\r\n [ 10. 10. 10.]\r\n [ 20. 20. 20.]\r\n [ 30. 30. 30.]]\r\n\r\nSecond array:\r\n[ 1. 2. 3.]\r\n\r\nFirst Array + Second Array\r\n[[ 1. 2. 3.]\r\n [ 11. 12. 13.]\r\n [ 21. 22. 23.]\r\n [ 31. 32. 33.]]\r\n'''\r\n\r\n# Iterating Over Array using numpy.nditer\r\na = np.arange(0,60,5)\r\na = a.reshape(3,4)\r\nfor x in np.nditer(a): # order of iteration is chosen to match the memory layout of the array (so transpose the array wont help, instead we can change the memory layout)\r\n   print (x) # output 1\r\n\r\nb = a.copy(order = 'F')  # we can change the memory layout of the array using order \r\nfor x in np.nditer(b): \r\n   print (x) # output 2\r\n\r\nfor x in np.nditer(a, order = 'F'):  # or we can force nditer object to use a specific order by explicitly mentioning it\r\n   print (x) # output 3\r\n'''\r\nOriginal array is:\r\n[[ 0 5 10 15]\r\n [20 25 30 35]\r\n [40 45 50 55]]\r\n\r\nOutput 1:\r\n0 5 10 15 20 25 30 35 40 45 50 55\r\n\r\nOutput 2:\r\n0 20 40 5 25 45 10 30 50 15 35 55\r\n\r\nOutput 3:\r\n0 20 40 5 25 45 10 30 50 15 35 55\r\n'''\r\n\r\n\r\n# Transposing an array\r\na=np.arange(9)\r\na.shape=(3,3)\r\na.T\r\n\r\n\r\n# Modifying Array Values usinf op_flags parameter \r\na = np.arange(0,60,5)\r\na = a.reshape(3,4)\r\nprint (a) # output 1\r\nfor x in np.nditer(a, op_flags = ['readwrite']):\r\n   x[...] = 2*x\r\nprint(a) # output 2\r\n'''\r\nOutput 1:\r\n[[ 0  5 10 15]\r\n [20 25 30 35]\r\n [40 45 50 55]]\r\n\r\nOutput 2:\r\n[[  0  10  20  30]\r\n [ 40  50  60  70]\r\n [ 80  90 100 110]]\r\n'''\r\n\r\n\r\n# extracting one-dimensional arrays corresponding to each column\r\na = np.arange(0,60,5) \r\na = a.reshape(3,4) \r\nprint(a)\r\nfor x in np.nditer(a, flags = ['external_loop'], order = 'F'):\r\n   print(x)\r\n'''\r\noutput 1:\r\n[[ 0  5 10 15]\r\n [20 25 30 35]\r\n [40 45 50 55]]\r\n\r\noutput 2:\r\n[ 0 20 40]\r\n[ 5 25 45]\r\n[10 30 50]\r\n[15 35 55]\r\n'''\r\n\r\n# Broadcasting Iteration\r\na = np.arange(0,60,5) \r\na = a.reshape(3,4)\r\nprint(a) # output 1\r\nb = np.array([1, 2, 3, 4], dtype = int) \r\nprint(b) # output  2\r\nfor x,y in np.nditer([a,b]): \r\n   print(x+y) # output 3\r\n'''\r\noutput 1:\r\n[[ 0  5 10 15]\r\n [20 25 30 35]\r\n [40 45 50 55]]\r\n\r\noutput 2:\r\n[1 2 3 4]\r\n\r\noutput 3:\r\n1 7 13 19 21 27 33 39 41 47 53 59\r\n'''\r\n\r\n# Array Manipulation\r\n# Changing Shape\r\na = np.arange(8).reshape(2,4)  # reshape a 1x8 (1 row, 8 cols) array into a 2x4 array\r\na.flat[5] # 5 ; 1-D iterator over the array\r\na.flatten(order = 'F') # returns a copy of an array collapsed into one dimension\r\na.ravel(order = 'F') # Returns a contiguous flattened array / copy is made only if needed\r\n\r\n# Transpose Operations\r\nnp.transpose(a) # same as a.T\r\na.T\r\n\r\n# Changing Dimensions\r\na = np.arange(4).reshape(1,4)  # [0  1  2  3] \r\nnp.broadcast_to(a,(4,4))\r\n'''\r\n[[0  1  2  3] \r\n [0  1  2  3] \r\n [0  1  2  3] \r\n [0  1  2  3]]\r\n'''\r\n\r\n# Joining Arrays\r\na = np.array([[1,2],[3,4]]) \r\n'''First array:\r\n[[1 2]\r\n [3 4]]'''\r\nb = np.array([[5,6],[7,8]]) \r\n'''Second array:\r\n[[5 6]\r\n [7 8]]'''\r\n\r\n# concatenate joins a sequence of arrays along an existing axis\r\nnp.concatenate((a,b)) # by default it joins on axis=0, stacks horizontally - this is same as np.vstack((a,b)) \r\n'''Joining the two arrays along axis 0:\r\n[[1 2]\r\n [3 4]\r\n [5 6]\r\n [7 8]]'''\r\nnp.concatenate((a,b),axis = 1) # this is same as np.hstack((a,b))\r\n'''Joining the two arrays along axis 1:\r\n[[1 2 5 6]\r\n [3 4 7 8]]'''\r\n\r\n# stack joins a sequence of arrays along a new axis\r\nnp.stack((a,b),0)\r\n'''Stack the two arrays along axis 0:\r\n[[[1 2]\r\n [3 4]]\r\n [[5 6]\r\n [7 8]]]'''\r\nnp.stack((a,b),1)\r\n'''Stack the two arrays along axis 1:\r\n[[[1 2]\r\n [5 6]]\r\n [[3 4]\r\n [7 8]]]''' \r\n\r\n# Splitting Arrays\r\na = np.arange(9) \r\n# [0 1 2 3 4 5 6 7 8]\r\nnp.split(a,3) # Split the array in 3 equal-sized subarrays:\r\n# [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]\r\nnp.split(a,[4,7]) # Split the array at positions indicated in 1-D array:\r\n# [array([0, 1, 2, 3]), array([4, 5, 6]), array([7, 8])]\r\n\r\na = np.arange(16).reshape(4,4)\r\n'''\r\n[[ 0 1 2 3]\r\n [ 4 5 6 7]\r\n [ 8 9 10 11]\r\n [12 13 14 15]]'''\r\nnp.hsplit(a,2) # Horizontal splitting                                                        \r\n'''[array([[ 0,  1],                                                             \r\n       [ 4,  5],                                                              \r\n       [ 8,  9],                                                              \r\n       [12, 13]]), array([[ 2,  3],                                           \r\n       [ 6,  7],                                                              \r\n       [10, 11],                                                              \r\n       [14, 15]])]'''\r\nnp.vsplit(a,2) # Vertical splitting                                                         \r\n'''[array([[0, 1, 2, 3],                                                         \r\n       [4, 5, 6, 7]]), array([[ 8,  9, 10, 11],                               \r\n       [12, 13, 14, 15]])]''' \r\n\r\n# Adding / Removing Elements\r\na = np.array([[1,2,3],[4,5,6]]) \r\n'''[[1 2 3]\r\n [4 5 6]]'''\r\nnp.resize(a,(3,3)) \r\n'''[[1 2 3]\r\n [4 5 6]\r\n [1 2 3]]''' # Observe that first row of a is repeated in b since size is bigger \r\n\r\n\r\na = np.array([[1,2,3],[4,5,6]])\r\n'''[[1 2 3]\r\n [4 5 6]]'''\r\nnp.append(a, [7,8,9])  # Append elements to array - Axis parameter not passed. The input array is flattened before append\r\n# [1 2 3 4 5 6 7 8 9]\r\nnp.append(a, [[7,8,9]],axis = 0)  # Append elements along axis 0\r\n'''[[1 2 3]\r\n [4 5 6]\r\n [7 8 9]]'''\r\nnp.append(a, [[5,5,5],[7,8,9]],axis = 1) # Append elements along axis 1\r\n'''[[1 2 3 5 5 5]\r\n [4 5 6 7 8 9]]'''\r\n\r\n\r\na = np.array([[1,2],[3,4],[5,6]]) \r\n'''[[1 2]\r\n [3 4]\r\n [5 6]]'''\r\nnp.insert(a,3,[11,12])  # Axis parameter not passed. The input array is flattened before insertion.\r\n# [ 1 2 3 11 12 4 5 6]\r\nnp.insert(a,1,[11],axis = 0)  # Broadcast along axis 0:\r\n'''[[ 1 2]\r\n [11 11]\r\n [ 3 4]\r\n [ 5 6]]'''\r\nnp.insert(a,1,11,axis = 1) # Broadcast along axis 1:\r\n'''[[ 1 11 2]\r\n [ 3 11 4]\r\n [ 5 11 6]]'''\r\n\r\na = np.arange(12).reshape(3,4) \r\n'''[[ 0 1 2 3]\r\n [ 4 5 6 7]\r\n [ 8 9 10 11]]'''\r\nnp.delete(a,5)  # no axis specified, so array flattened before delete operation as axis not used\r\n[ 0 1 2 3 4 6 7 8 9 10 11]\r\nnp.delete(a,1,axis = 1) # Column 2 deleted\r\n'''[[ 0 2 3]\r\n [ 4 6 7]\r\n [ 8 10 11]]'''\r\nnp.delete(a, np.s_[::2]) # A slice containing alternate values from array deleted:\r\n# [ 2 4 6 8 10]\r\n\r\n# unique function returns an array of unique elements in the input array\r\na = np.array([5,2,6,2,7,5,6,8,2,9]) \r\nnp.unique(a)  # Unique values of first array\r\nu,indices = np.unique(a, return_index = True) # Unique array and Indices array\r\nu[indices]  # Reconstruct the original array using indices\r\nu,cnt = np.unique(a,return_counts = True) # Return the count of repetitions of unique elements\r\n\r\n\r\n# Mathematical/statistical funcitons\r\na = np.array([1.0,5.55, 123, 0.567, 25.532])  \r\nnp.around(a)  # Default is 0. If negative, the integer is rounded to position to the left of the decimal point\r\nnp.around(a, decimals = 1)  # [   1.    5.6  123.    0.6  25.5] \r\nnp.around(a, decimals = -1) # [   0.    10.  120.    0.   30. ]\r\n\r\na = np.array([-1.7, 1.5, -0.2, 0.6, 10]) \r\nnp.floor(a) # [ -2.   1.  -1.   0.  10.]\r\nnp.ceil(a)  # [ -1.   2.  -0.   1.  10.]\r\n\r\n# Arithmetic functions\r\na = np.arange(9, dtype = np.float_).reshape(3,3) \r\n'''[[ 0. 1. 2.]\r\n [ 3. 4. 5.]\r\n [ 6. 7. 8.]]'''\r\nb = np.array([10,10,10])\r\n# [10 10 10]\r\nnp.add(a,b) # Add the two arrays\r\n[[ 10. 11. 12.]\r\n [ 13. 14. 15.]\r\n [ 16. 17. 18.]]\r\nnp.subtract(a,b) # Subtract the two arrays\r\n[[-10. -9. -8.]\r\n [ -7. -6. -5.]\r\n [ -4. -3. -2.]]\r\nnp.multiply(a,b)  # Multiply the two arrays\r\n[[ 0. 10. 20.]\r\n [ 30. 40. 50.]\r\n [ 60. 70. 80.]]\r\nnp.divide(a,b) # Divide the two arrays\r\n[[ 0. 0.1 0.2]\r\n [ 0.3 0.4 0.5]\r\n [ 0.6 0.7 0.8]]\r\n\r\n# Dot product\r\n# For 2-D vectors, it is the equivalent to matrix multiplication. \r\n# For 1-D arrays, it is the inner product of the vectors. \r\n# For N-dimensional arrays, it is a sum product over the last axis of a and the second-last axis of b.\r\nnp.dot(a,b)\r\nnp.dot(b,a) == np.dot(a.T,b)\r\n\r\n\r\na=[1,2,3]\r\nb=[2,3,1]\r\nnp.power(a,2) # array([1, 4, 9], dtype=int32)\r\nnp.power(a,b) # array([1, 8, 3], dtype=int32)\r\n\r\na = np.array([10,20,30]) \r\nb = np.array([3,5,7]) \r\nnp.mod(a,b)  # same as np.remainder(a,b) \r\n# array([1, 0, 2], dtype=int32)\r\n\r\na = np.array([[3,7,5],[8,4,3],[2,4,9]]) \r\nnp.amin(a,1)  # array of min in each row\r\nnp.amin(a,0)  # array of min in each col\r\nnp.amin(a)    # overall min element\r\n\r\n# ptp function returns the range (maximum-minimum) of values along an axis\r\na = np.array([[3,7,5],[8,4,3],[2,4,9]]) \r\nnp.ptp(a)  \r\nnp.ptp(a, axis = 1) \r\nnp.ptp(a, axis = 0) \r\n\r\n# Percentile (or a centile) is a measure used in statistics indicating the value below which a given percentage of observations in a group of observations fall\r\na = np.array([[30,40,70],[80,20,10],[50,90,60]]) \r\nnp.percentile(a,50) \r\n# 50.0\r\nnp.percentile(a,50, axis = 1)  # 1 is rows\r\n# [ 40. 20. 60.]  \r\nnp.percentile(a,50, axis = 0)  # 0 is columns\r\n# [ 50. 40. 60.]\r\n\r\n# Median is defined as the value separating the higher half of a data sample from the lower half\r\na = np.array([[30,65,70],[80,95,10],[50,90,60]]) \r\nnp.median(a) # 65.0\r\nnp.median(a, axis = 0)  # [ 50. 90. 60.]\r\nnp.median(a, axis = 1) # [ 65. 80. 60.]\r\n\r\n# np.mean - syntax similar to np.median\r\n# np.average function can be used to calculate weighted average if weights are specified, if they are not specified then this function is same as mean function\r\n# In a multi-dimensional array, the axis for computation can be specified.\r\na = np.array([1,2,3,4]) \r\nnp.average(a)\r\nwts = np.array([4,3,2,1]) \r\nnp.average(a,weights = wts) \r\n\r\n# Standard deviation is the square root of the average of squared deviations from mean\r\n# std = sqrt(mean(abs(x - x.mean())**2))\r\nnp.std([1,2,3,4])\r\n\r\n# Variance is the average of squared deviations - mean(abs(x - x.mean())**2)\r\n# In other words, the standard deviation is the square root of variance\r\nnp.var([1,2,3,4])\r\n\r\n# sorting\r\n# sort() function returns a sorted copy of the input array\r\na = np.array([[3,7],[9,1]]) \r\n'''[[3 7]\r\n [9 1]]'''\r\nnp.sort(a) \r\n'''[[3 7]\r\n [1 9]]'''\r\n\r\n# # Order parameter in sort function \r\ndt = np.dtype([('name', 'S10'),('age', int)]) \r\na = np.array([(\"raju\",21),(\"anil\",25),(\"ravi\", 17), (\"amar\",27)], dtype = dt) \r\n# [('raju', 21) ('anil', 25) ('ravi', 17) ('amar', 27)]\r\nnp.sort(a, order = 'name')\r\n# [('amar', 27) ('anil', 25) ('raju', 21) ('ravi', 17)]\r\n\r\n# numpy.argsort returns the array of indices of sorted array\r\n# this indices array is used to construct the sorted array\r\nx = np.array([3, 1, 2]) \r\ny = np.argsort(x)\r\nx[y]  # Reconstruct original array in sorted order\r\n\r\n# numpy.argmax() and numpy.argmin()\r\n# return the indices of maximum and minimum elements along the given axis\r\n\r\n# numpy.nonzero() function returns the indices of non-zero elements in the input array\r\n# numpy.where(condition) function returns the indices of elements in an input array where the given condition is satisfied\r\n# numpy.extract(condition) function returns the elements satisfying any condition\r\n\r\n# id() returns a universal identifier of Python object, similar to the pointer in C\r\n# While executing the functions, some of them return a copy of the input array, while some return the view\r\na\r\nb=a # b.shape will also change the shape of a\r\n# view - a different view of the same memory content \r\nb=a.view() # b.shape will not change the shape of a, even though both a and b have same id()\r\n# copy - When the contents are physically stored in another location\r\nb=a.copy() # b.shape will not change the shape of a, as a and b have different id()\r\n\r\n# MATRIX\r\n# matrix is always two-dimensional, whereas ndarray is an n-dimensional array. Both the objects are inter-convertible.\r\ni = np.matrix('1,2;3,4') \r\n'''[[1  2] \r\n [3  4]]'''\r\nj = np.asarray(i) \r\n'''[[1  2] \r\n [3  4]]'''\r\nk = np.asmatrix (j) \r\n'''[[1  2] \r\n [3  4]]'''\r\n\r\n# Matrix functions\r\nnp.matlib.empty((2,2)) # returns a new matrix without initializing the entries (it will be filled with random data)\r\nnp.matlib.zeros((2,2)) # returns the matrix filled with zeros\r\nnp.matlib.ones((2,2))\r\nnp.matlib.eye(n = 3, M = 4, k = 0, dtype = float) # returns a matrix with 1 along the diagonal elements and the zeros elsewhere\r\nnp.matlib.identity(5, dtype = float) # returns the Identity matrix of the given size. An identity matrix is a square matrix with all diagonal elements as 1\r\nnp.matlib.rand(3,3) # returns a matrix of the given size filled with random values\r\n\r\n\r\n\r\n", "meta": {"hexsha": "7fcaabee106575515dc7770265d60894d07d3205", "size": 19634, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python-Programming/04-numpy arrays and matrices.py", "max_stars_repo_name": "vivekparasharr/Learn-Programming", "max_stars_repo_head_hexsha": "1ae07ef5143bff3c504978e1d375698820f59af0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python-Programming/04-numpy arrays and matrices.py", "max_issues_repo_name": "vivekparasharr/Learn-Programming", "max_issues_repo_head_hexsha": "1ae07ef5143bff3c504978e1d375698820f59af0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python-Programming/04-numpy arrays and matrices.py", "max_forks_repo_name": "vivekparasharr/Learn-Programming", "max_forks_repo_head_hexsha": "1ae07ef5143bff3c504978e1d375698820f59af0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0293637847, "max_line_length": 170, "alphanum_fraction": 0.6002342875, "include": true, "reason": "import numpy", "num_tokens": 6639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.9381240138438709, "lm_q1q2_score": 0.8841881868516107}}
{"text": "\"\"\"\nGiven the coordinates of four points in 2D space, return whether the four points could construct a square.\n\nThe coordinate (x,y) of a point is represented by an integer array with two integers.\n\nExample:\nInput: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]\nOutput: True\nNote:\n\nAll the input integers are in the range [-10000, 10000].\nA valid square has four equal sides with positive length and four equal angles (90-degree angles).\nInput points have no order.\n\"\"\"\nimport numpy as np\nimport math\nclass Solution:\n    def euclid(self,t1,t2):\n        return math.sqrt(math.pow(t1[0]-t2[0],2)+math.pow(t1[1]-t2[1],2))\n    def validSquare(self, p1, p2, p3, p4):\n        \"\"\"\n        :type p1: List[int]\n        :type p2: List[int]\n        :type p3: List[int]\n        :type p4: List[int]\n        :rtype: bool\n        \"\"\"\n        dist = list()\n        dist.append(self.euclid(p1,p2))\n        dist.append(self.euclid(p1,p3))\n        dist.append(self.euclid(p1,p4))\n        dist.append(self.euclid(p2,p3))\n        dist.append(self.euclid(p2,p4))\n        dist.append(self.euclid(p3,p4))\n        set_temp = set(dist)\n        if(len(set_temp)!=2):\n            return False\n        else:\n            temp = list()\n            for nums in set_temp:\n                temp.append(nums)\n            temp.sort()\n            if round(math.sqrt(2)*temp[0],2) == round(temp[1],2):\n                return True\n            else:\n                return False\n", "meta": {"hexsha": "de0c0bc5466e4e1d989e96d38e1543b05f4a3fbc", "size": 1438, "ext": "py", "lang": "Python", "max_stars_repo_path": "593. Valid Square.py", "max_stars_repo_name": "sanjaymanickam/LeetCode-Problems", "max_stars_repo_head_hexsha": "0e5c7ff21e5c0ccd2a4e4521b0dfe40402687199", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "593. Valid Square.py", "max_issues_repo_name": "sanjaymanickam/LeetCode-Problems", "max_issues_repo_head_hexsha": "0e5c7ff21e5c0ccd2a4e4521b0dfe40402687199", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "593. Valid Square.py", "max_forks_repo_name": "sanjaymanickam/LeetCode-Problems", "max_forks_repo_head_hexsha": "0e5c7ff21e5c0ccd2a4e4521b0dfe40402687199", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5957446809, "max_line_length": 106, "alphanum_fraction": 0.5730180807, "include": true, "reason": "import numpy", "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347860767304, "lm_q2_score": 0.9073122132152183, "lm_q1q2_score": 0.884116582389176}}
{"text": "from sympy import *\r\n\r\n#define sympy symbols for \r\nx , t , z , nu = symbols ('x t z nu')\r\n\r\n#for pretty printing:\r\ninit_printing ( use_unicode=True)\r\n\r\n#take a derivative of  [ sin (x) e ^ x ]\r\nprint (\" Diffrentiating sin (x) e ^ x \") \r\nprint ( diff ( sin ( x ) * exp (x), x))\r\n\r\n#integration:\r\nprint ( \"\\n Integrating the result:\")\r\nprint (  integrate ( exp(x) * sin (x) + exp(x)*cos(x) , x) )\r\n\r\nprint(\"\\n Integrating with limits   -oo to + oo \")\r\nprint ( integrate( sin(x**2) , ( x, -oo , oo ) ) )\r\n\r\nprint (\"\\n Finding the limit as x -> 0 \" )\r\nprint ( limit (sin(x)/x, x, 0 ) )\r\n\r\nprint (\"\\n Solving an equation:\")\r\nprint ( solve ( x ** 2 - 2, x) )\r\n\r\nprint (\"\\n Solving a diffrentaial equation:\")\r\ny = Function ( 'y' )\r\nprint ( dsolve( Eq( y(t).diff(t,t) - y(t), exp(t) ), y(t) ) )\r\n\r\nprint(\"\\n Finding EigenValues:\")\r\nprint ( Matrix( [ [1,2],[2,2] ] ).eigenvals() )\r\n\r\n#to check mathematical equality, between two expressions say a and b\r\n# if simplify(a-b) evaluates to 0 => a = b\r\nx = symbols('x')\r\na = (x+1)**2\r\nb = x**2 + 2*x + 1\r\nprint ( simplify (a-b) )\r\n", "meta": {"hexsha": "8967e17c2b719b250094aa362ace32622a48bc56", "size": 1067, "ext": "py", "lang": "Python", "max_stars_repo_path": "00 Calculus Operations in SymPy.py", "max_stars_repo_name": "Verma314/Experiments-in-Symbolic-Computation", "max_stars_repo_head_hexsha": "baf800c5ff69cc125df8c84ab93c4f40a7aba725", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "00 Calculus Operations in SymPy.py", "max_issues_repo_name": "Verma314/Experiments-in-Symbolic-Computation", "max_issues_repo_head_hexsha": "baf800c5ff69cc125df8c84ab93c4f40a7aba725", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "00 Calculus Operations in SymPy.py", "max_forks_repo_name": "Verma314/Experiments-in-Symbolic-Computation", "max_forks_repo_head_hexsha": "baf800c5ff69cc125df8c84ab93c4f40a7aba725", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.358974359, "max_line_length": 69, "alphanum_fraction": 0.5670103093, "include": true, "reason": "from sympy", "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9817357248544007, "lm_q2_score": 0.900529795461386, "lm_q1q2_score": 0.8840822715002691}}
{"text": "# GenerateCurve.py\n\nimport numpy as np\nimport sys\n\ndef getCurveNames() :\n    return (\"line\",\"circle\",\"ellipse\",\"clover\",\"heart\",\"lissajous\",\"figureight\")\n\ndef generateCurve(argv) :\n    nargs = len(argv)\n    if nargs==1 :\n        print('argument must be one of: ',getCurveNames())\n        exit()\n    if nargs<2 : raise Exception('must specify curve name')\n    name = sys.argv[1]\n    if name==str(\"line\") :\n         npts = 1000\n         x = np.arange(npts,dtype=\"float64\")\n         y = np.arange(npts,dtype=\"float64\")\n         return {\"x\":x,\"y\":y,\"name\":name}\n    if name==str(\"circle\") :\n         min = 0.0\n         max = 1.0\n         npts = 2000\n         inc = (max-min)/npts\n         t = np.arange(min, max, inc)\n         x = np.cos(2*np.pi*t)\n         y = np.sin(2*np.pi*t)\n         return {\"x\":x,\"y\":y,\"name\":name}\n    if name==str(\"ellipse\") :\n         min = 0.0\n         max = 1.0\n         npts = 2000\n         inc = (max-min)/npts\n         t = np.arange(min, max, inc)\n         a = 3.0\n         if nargs>=3 : a = float(sys.argv[2])\n         b = 2.0\n         if nargs>=4 : b = float(sys.argv[3])\n         x = a*np.cos(2*np.pi*t)\n         y = b*np.sin(2*np.pi*t)\n         return {\"x\":x,\"y\":y,\"name\":name}\n    if name==str(\"clover\") :\n         min = 0.0\n         max = 1.0\n         npts = 2000\n         inc = (max-min)/npts\n         nloops = 3\n         if nargs>=3 : nloops = float(sys.argv[2])\n         print('nloops=',nloops)\n         t = np.arange(min, max, inc)\n         x = np.sin(nloops*2*np.pi*t)*np.cos(2*np.pi*t)\n         y = np.sin(nloops*2*np.pi*t)*np.sin(2*np.pi*t)\n         return {\"x\":x,\"y\":y,\"name\":name}\n    if name==str(\"heart\") :\n         min = 0.0\n         max = 1.0\n         npts = 2000\n         inc = (max-min)/npts\n         t = np.arange(min, max, inc)\n         x = (1.0 - np.cos(2*np.pi*t)*np.cos(2*np.pi*t))*np.sin(2*np.pi*t)\n         y = (1.0 - np.cos(2*np.pi*t)*np.cos(2*np.pi*t)*np.cos(2*np.pi*t))*np.cos(2*np.pi*t)\n         return {\"x\":x,\"y\":y,\"name\":name}\n    if name==str(\"lissajous\") :\n         min = 0.0\n         max = 1.0\n         npts = 4000\n         inc = (max-min)/npts\n         t = np.arange(min, max, inc)\n         m = 3\n         if nargs>=3 : m = float(sys.argv[2])\n         n = 1\n         if nargs>=4 : n = float(sys.argv[3])\n         x = np.sin(n*2*np.pi*t)\n         y = np.cos(m*2*np.pi*t)\n         return {\"x\":x,\"y\":y,\"name\":name}\n    if name==str(\"figureight\") :\n         min = 0.0\n         max = 1.0\n         npts = 2000\n         inc = (max-min)/npts\n         a = 1\n         if nargs>=3 : a = float(sys.argv[2])\n         print('a=',a)\n         t = np.arange(min, max, inc)\n         x = a*np.sin(2*np.pi*t)*np.cos(2*np.pi*t)\n         y = a*np.sin(2*np.pi*t)\n         return {\"x\":x,\"y\":y,\"name\":name}\n    raise Exception(name + ' not implemented')\n\nif __name__ == '__main__':\n    curveData = generateCurve(sys.argv)\n    print('name=',curveData[\"name\"],' len(x)=',len(curveData[\"x\"]),' len(y)=',len(curveData[\"y\"]))\n\n\n", "meta": {"hexsha": "2cb6bdc9dec00619536287741daf79916459eb92", "size": 2963, "ext": "py", "lang": "Python", "max_stars_repo_path": "plot2dcurve/GenerateCurve.py", "max_stars_repo_name": "mrkraimer/testPvaPy", "max_stars_repo_head_hexsha": "7d09095bc76bf0a86d8d664c85757ab8369485c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plot2dcurve/GenerateCurve.py", "max_issues_repo_name": "mrkraimer/testPvaPy", "max_issues_repo_head_hexsha": "7d09095bc76bf0a86d8d664c85757ab8369485c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-18T19:50:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-19T09:58:16.000Z", "max_forks_repo_path": "plot2dcurve/GenerateCurve.py", "max_forks_repo_name": "mrkraimer/testPvaPy", "max_forks_repo_head_hexsha": "7d09095bc76bf0a86d8d664c85757ab8369485c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-18T18:06:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T06:40:34.000Z", "avg_line_length": 30.8645833333, "max_line_length": 98, "alphanum_fraction": 0.4724940938, "include": true, "reason": "import numpy", "num_tokens": 994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399086356109, "lm_q2_score": 0.91117971362973, "lm_q1q2_score": 0.8840629221027314}}
{"text": "import numpy as np\r\nfrom numpy.core.records import array\r\n\r\n# Request the matrix from the user\r\nA = [float(a) for a in input(\"Please, Enter the matrix row by row: \").split(\" \")]\r\nA_shape = [int(i) for i in input(\"Please, Enter the dimension of the previous matrix: \").split(\" \")]\r\nA = np.array(A).reshape(A_shape)\r\n\r\n# Request the starting vector from the user\r\nX = [float(a) for a in input(\"Please, Enter the starting vector: \").split(\" \")]\r\nX_shape = [int(i) for i in input(\"Please, Enter the dimension of the previous vector: \").split(\" \")]\r\nX = np.array(X).reshape(X_shape)\r\n\r\ndef PowerMethod(A, X, tolerance, ndigits, counter = np.inf):\r\n    print('#' * 50, \"The Power Method\", '#' * 50)\r\n    i = 1\r\n    B = list()\r\n    print(\"Iteration No.\", 0)\r\n    print(X.T, \"---\")\r\n    print(\"Iteraion No.\", 1)\r\n    B.append(np.dot(A, X))\r\n    print(B[0].T, \"---\")\r\n    print(\"Iteration No.\", 2)\r\n    # min = np.amax([abs(b) for b in B[0]])\r\n    # B[0] = np.array([b / min for b in B[0]])\r\n    B.append(np.dot(A, B[0]))\r\n    dominant_eigenvalue = round(np.amax([abs(b) for b in abs(B[1])]) / np.amax([abs(b) for b in abs(B[0])]), ndigits)\r\n    print(B[1].T, dominant_eigenvalue)\r\n    # min = np.amax([abs(b) for b in B[1]])\r\n    # B[1] = np.array([b / min for b in B[1]])\r\n    previous = -1\r\n    while((abs(dominant_eigenvalue - previous) > tolerance or (dominant_eigenvalue == previous)) and i <= counter-2):\r\n        B.append(np.dot(A, B[i]))\r\n        previous = dominant_eigenvalue\r\n        i += 1\r\n        # min = np.amax([abs(b) for b in B[i]])\r\n        # B[i] = np.array([b / min for b in B[i]])\r\n        dominant_eigenvalue = round(np.amax([abs(b) for b in abs(B[i])]) / np.amax([abs(b) for b in abs(B[i - 1])]),ndigits)\r\n        print(\"Iteration No.\", i+1)\r\n        print(B[i].T, dominant_eigenvalue)\r\n\r\n    print('#' * 120)\r\n    dominant_eignevector = np.round([(b / np.amin([abs(b) for b in abs(B[i])])) for b in B[i]],ndigits)\r\n    \r\n    return [dominant_eignevector, dominant_eigenvalue, i+1]\r\n\r\n# Example 1: 2 1 1 1 2 1 1 1 2\r\n# Example: 1 -1 0 -2 4 -2 0 -1 2\r\n# PowerMethod(A, X, 0.0001, 5)\r\n[dominant_eignevector, dominant_eigenvalue, i] = PowerMethod(A, X, 0.0001, 5)\r\nprint(\"The Dominant Eigenvalue =\", dominant_eigenvalue)\r\nprint(\"The Dominant Eigenvector =\", dominant_eignevector.T)\r\nprint(\"Total Number of iterations =\", i)", "meta": {"hexsha": "98f33b0fe6b78f3ef8578cf22d355f9a6e86bb62", "size": 2336, "ext": "py", "lang": "Python", "max_stars_repo_path": "Eigenvalue Approximation/Power Method with visualization.py", "max_stars_repo_name": "AhmedAlaa2024/Numerical-Methods", "max_stars_repo_head_hexsha": "6b4afe1a1610bf9c8311ab993b06bd026b41c61e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Eigenvalue Approximation/Power Method with visualization.py", "max_issues_repo_name": "AhmedAlaa2024/Numerical-Methods", "max_issues_repo_head_hexsha": "6b4afe1a1610bf9c8311ab993b06bd026b41c61e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Eigenvalue Approximation/Power Method with visualization.py", "max_forks_repo_name": "AhmedAlaa2024/Numerical-Methods", "max_forks_repo_head_hexsha": "6b4afe1a1610bf9c8311ab993b06bd026b41c61e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0754716981, "max_line_length": 125, "alphanum_fraction": 0.5980308219, "include": true, "reason": "import numpy,from numpy", "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422269175633, "lm_q2_score": 0.9294404057671714, "lm_q1q2_score": 0.884030017328551}}
{"text": "# skewness python\n# https://www.google.com/search?q=skewness+python&oq=Skewness+python&aqs=chrome.0.0l4j0i22i30l6.3988j0j4&sourceid=chrome&ie=UTF-8\n# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skew.html\n# https://www.geeksforgeeks.org/scipy-stats-skew-python/\n\n''' Statistical functions\nIn simple words, skewness is the measure of how much the\nprobability distribution of a random variable deviates\nfrom the normal distribution.\n# https://www.investopedia.com/terms/s/skewness.asp\n\nskewness = 0 : normally distributed.\nskewness > 0 : more weight in the left tail of the distribution.\nskewness < 0 : more weight in the right tail of the distribution.\n\n'''\n# part 1 ----------------------------------\nimport numpy as np\nfrom scipy.stats import skew\nimport pandas as pd\n\narr = np.random.randint(1, 10, 10)\narr = list(arr)\n# print(arr)\n# # more weight in the right when skew>0,\n# # determine skew close enough to zero\n# print(skew(arr))\n# print(skew([1, 2, 3, 4, 5]))\n\n# part 2 ----------------------------------\n# df = pd.read_csv('Data/nba.csv')\ndf = pd.read_csv('Data/XAUNZD_Daily.csv')\n\n# print(df.tail())\n\n# skewness along the index axis\nprint(df.skew(axis=0, skipna=True))\n\n# skewness of the data over the column axis\n# print(df.skew(axis=1, skipna=True))\n", "meta": {"hexsha": "0fa5ad98efc704cdbbb569fd5290f21eaeacc0df", "size": 1280, "ext": "py", "lang": "Python", "max_stars_repo_path": "davidgoliath/project/modelling/17_skewness.py", "max_stars_repo_name": "spideynolove/Other-repo", "max_stars_repo_head_hexsha": "34066f177994415d031183ab9dd219d787e6e13a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "davidgoliath/project/modelling/17_skewness.py", "max_issues_repo_name": "spideynolove/Other-repo", "max_issues_repo_head_hexsha": "34066f177994415d031183ab9dd219d787e6e13a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "davidgoliath/project/modelling/17_skewness.py", "max_forks_repo_name": "spideynolove/Other-repo", "max_forks_repo_head_hexsha": "34066f177994415d031183ab9dd219d787e6e13a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2195121951, "max_line_length": 129, "alphanum_fraction": 0.69921875, "include": true, "reason": "import numpy,from scipy", "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422269175636, "lm_q2_score": 0.9294403969720817, "lm_q1q2_score": 0.8840300089631701}}
{"text": "import numpy as np\nimport pandas as pd\nfrom IPython.display import display\nimport matplotlib.pyplot as plt\n\nn = 1000\nmean = (-1, 2)\ncov = [[10, 1], [1, 0.5]]\nX = np.random.multivariate_normal(mean, cov, n)\n\ndf = pd.DataFrame(X)\n# Pandas does the centering for us\ndf = df -df.mean()\nprint(\"Centered covariance with Pandas\")\ncovarianceX = df.cov()\n\nprint(covarianceX)\n\n# we center it ourselves\nX_centered = X - X.mean(axis=0)\nprint(\"Centered covariance using numpy\")\nprint(np.cov(X_centered.T))\n# extract the relevant columns from the centered design matrix\nx = X_centered[:,0]\ny = X_centered[:,1]\nCov = np.zeros((2,2))\nCov[0,1] = np.sum(x.T@y)/(n-1.0)\nCov[0,0] = np.sum(x.T@x)/(n-1.0)\nCov[1,1] = np.sum(y.T@y)/(n-1.0)\nCov[1,0]= Cov[0,1]\nprint(\"Centered covariance using own code\")\nprint(Cov)\n\nplt.plot(x, y, 'x')\nplt.axis('equal')\nplt.show()\n\n# diagonalize and obtain eigenvalues, not necessarily sorted\nEigValues, EigVectors = np.linalg.eig(Cov)\n# sort eigenvectors and eigenvalues\n#permute = EigValues.argsort()\n#EigValues = EigValues[permute]\n#EigVectors = EigVectors[:,permute]\nprint(\"Eigenvalues of Covariance matrix\")\nfor i in range(2):\n    print(EigValues[i])\nFirstEigvector = EigVectors[:,0]\nSecondEigvector = EigVectors[:,1]\nprint(\"First eigenvector\")\nprint(FirstEigvector)\nprint(\"Second eigenvector\")\nprint(SecondEigvector)\n#thereafter we do a PCA with Scikit-learn\nfrom sklearn.decomposition import PCA\npca = PCA(n_components = 2)\nX2Dsl = pca.fit_transform(X)\nprint(\"Eigenvector of largest eigenvalue\")\nprint(pca.components_.T[:, 0])\n\n\n\n", "meta": {"hexsha": "4f06292dddec6fa75d596a2124eddad0f0fe3d2f", "size": 1547, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/src/DimRed/Programs/PCAsimple.py", "max_stars_repo_name": "esleon97/MachineLearningECT", "max_stars_repo_head_hexsha": "97a218c9742b43a53e033a888f8a0b1074a2c48b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 59, "max_stars_repo_stars_event_min_datetime": "2019-12-06T09:24:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T03:27:28.000Z", "max_issues_repo_path": "doc/src/DimRed/Programs/PCAsimple.py", "max_issues_repo_name": "esleon97/MachineLearningECT", "max_issues_repo_head_hexsha": "97a218c9742b43a53e033a888f8a0b1074a2c48b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-06-16T18:24:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-08T21:13:56.000Z", "max_forks_repo_path": "doc/src/DimRed/Programs/PCAsimple.py", "max_forks_repo_name": "esleon97/MachineLearningECT", "max_forks_repo_head_hexsha": "97a218c9742b43a53e033a888f8a0b1074a2c48b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2019-11-30T00:37:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T21:30:09.000Z", "avg_line_length": 24.9516129032, "max_line_length": 62, "alphanum_fraction": 0.723335488, "include": true, "reason": "import numpy", "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102524151826, "lm_q2_score": 0.9136765322283324, "lm_q1q2_score": 0.8839000446688399}}
{"text": "### Computation on NumPy Arrays: Universal Functions\n# Using NP arrays in the traditional iterative manner is slow\n# Vectorized operations are preferred - generally implemented in ufuncs\n\n# here's a traditional loop-based approach to operating on arr values to demonstrate\nimport numpy as np\nnp.random.seed(0)\n\ndef compute_reciprocals(values):\n    output = np.empty(len(values))\n    for i in range(len(values)):\n        output[i] = 1.0 / values[i]\n    return output\n\nvalues = np.random.randint(1, 10, size=5)\n# %timeit compute_reciprocals(values)\n\n# now, consider a case with a much bigger array of values:\nbig_arr = np.random.randint(1, 100, size=1000000)\n# %timeit compute_reciprocals(big_array)\n\n# note that both ops are way slower than they should be\n\n##############################\n### UFuncs introduction\n# Interface for statically typed, compiled routines are known as vectorized operations\n# can be achieved by performing an operation on the array, which then is applied to each el\n# Advantage of vectorized approach is it pushes loop into the compiled layer, rather than being interpreted piecewise\n\n# sample 1: ufunc operation b/w Scalar type and Array\ncompute_reciprocals(big_arr)\n1.0 / big_arr\n# %timeit (1.0 / big_array)\n\n# sample 2: ufunc operation b/w Array type and Array\nnp.arange(5) / np.arange(1, 6)\n\n# sample 3: ufunc operation on Multi-dimensional array\nx = np.arange(9).reshape((3,3))\n2 ** x\n\n# the Pythonic way :: replace loops with vectorized expressions like the above when possible\n\n\n##############################\n### Exploring additional UFuncs \n# Two types, Unary ufuncs and Binary ufuncs\n\n## Array Arithmetic\n# NumPy ufuncs use simple arithmetic operators\nx = np.arange(4)\nx\nx + 5\nx - 5\nx * 2\nx / 2\nx // 2  # floor division \n-x\nx ** 2\nx % 2\n\n# can also string together operations, standard operations order respected\n-(0.5*x + 1) ** 2\n\n# Arithmetic operators in this context are wrappers for specific NP funcs. I.e. + evaluates to add()\nnp.add(x, 2)    # long form\nx + 2           # wrapper equivalent\n\n\n# We also have Boolean and Bitwise operators translated to NP ufuncs. Covered in \"2.6-boolMasking.py\"\n\n\n## Absolute Value\n# np plays nice with python standard library absolute val function abs()\nx = np.array([-2, -1, 0, 1, 2])\nabs(x)\n# np has its own ufunc np.absolute() --- also callable as np.abs()\nnp.absolute(x)\nnp.abs(x)\n\nx = np.array([3 - 4j, 4 - 3j, 2 + 0j, 0 + 1j])  # complex nums example\nabs(x)\nnp.abs(x)\n\n\n## Trigonometric ufuncs\n# we can start by defining an array of angles\ntheta = np.linspace(0, np.pi, 3)\ntheta\nnp.sin(theta)\nnp.cos(theta)\nnp.tan(theta)\n# and inverse trig funcs\nx = [-1, 0, 1]\nnp.arcsin(x)\nnp.arccos(x)\nnp.arctan(x)\n\n# side-note: recall that doubles get 15 decimal digits of precision.\n#            to get less messy output, must round.\n#            NON-Ufunc:  np.round(np.sin(theta), decimals=15) # rounds to 15th (dec precision limit)\n#                ufunc:  np.rint( np.sin(theta))              # rounds to 0 th decimal\n\n\n## Exponents and logarithms\nimport math;\nx = np.array([1, 2, 3])\n\nmath.e ** x\nnp.exp(x)\n\n2 ** x\nnp.exp2(x)\n\n3 ** x\nnp.power(3, x)\n\nx = [1, 2, 4, 10]           # NOTE: x is a list --> cannot use ufunc operators like ** or +\n\nnp.log(x)                   # natural logarithm\nnp.log2(x)                  # base 2 logarithm\nnp.log10(x)                 # base 10 logarithm\n\n# related exp/log funcs, good for precision on small input vals\nx = [0, .001, .01, .1]\nnp.exp(x)\nnp.expm1(x)             # Calculates ``exp(x) - 1``  \nnp.log1p(x)             # Calculates ``log(1 + x)``\n\n## Specialized ufuncs\n# some additional examples: hyperbolic trig funcs, bitwise arithmetic, comparison operators,\n# radian > degree conversions, rounding/remainders, etc. See NumPy ufunc docs\n\n# another source of ufuncs :: scipy.special \nfrom scipy import special\n\n# Gamma functions (generalized factorials) & related funcs\nx = [1, 5, 10]\nspecial.gamma(x)    # gamma\nspecial.gammaln(x)  # ln|gamma\nspecial.beta(x, 2)  # beta\n\n# Error function (integral of Gaussian), complement, and inverse\nx = np.array([0, 0.3, 0.7, 1.0])\nspecial.erf(x)\nspecial.erfc(x)\nspecial.erfinv(x)\n\n###################################\n### Advanced UFunc Features\n# 3 topics: Out, Aggregates, Outer Products\n\n## Specifying output: using \"out\"\n# We can directly specify mem location to store result of a calculation using \"out\". Imperative style -> huge efficiency gain\nx = np.arange(5)\ny = np.empty(5)\nnp.multiply(x, 10, out=y)\n\n# Can also utilize this with array views\ny = np.zeros(10);   y = np.power(2, x, out=y[::2])  # y[::2] is a size=5 View of y. Save result into that view.\ny = np.zeros(10);   y = 2 ** x                      # Requires additional temp array + full copy\n\n\n## Aggregates\n# With reduce() method, we can repeatedly execute a given operation to all elements of the array\n# returning a single scalar value\nx = np.arange(1, 6)\nnp.add.reduce(x)\nnp.multiply.reduce(x)\n\n# with accumulate() method, we reduce() while storing all intermediate outputs in array\nnp.add.accumulate(x)\nnp.multiply.accumulate(x)\n\n# note that there are dedicated NumPy funcs for these particular cases\n# np.sum, np.prod, np.cumsum, np.cumprod - respectively\n\n\n## Outer products (generalized cross product)\n# Any ufunc can compute the output of all pairs of two different inputs with outer()\nx = np.arange(1, 6)\nnp.multiply.outer(x, x)\n\n# ufunc.at() and ufunc.reduceat() will be covered later in Fancy Indexing, and build on this idea\n\n# additional ufuncs available in the NumPy/SciPy docs", "meta": {"hexsha": "0ab8d5721153f3c01d4741c101c61d6713047816", "size": 5518, "ext": "py", "lang": "Python", "max_stars_repo_path": "2.3-npUFuncs.py", "max_stars_repo_name": "pgiardiniere/notes-PythonDataScienceHandbook", "max_stars_repo_head_hexsha": "ddb6662d2fbeedd5b6b09ce4d8ddee55813ec589", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-05-01T02:23:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-04T03:26:39.000Z", "max_issues_repo_path": "2.3-npUFuncs.py", "max_issues_repo_name": "pgiardiniere/notes-PythonDataScienceHandbook", "max_issues_repo_head_hexsha": "ddb6662d2fbeedd5b6b09ce4d8ddee55813ec589", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2.3-npUFuncs.py", "max_forks_repo_name": "pgiardiniere/notes-PythonDataScienceHandbook", "max_forks_repo_head_hexsha": "ddb6662d2fbeedd5b6b09ce4d8ddee55813ec589", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6666666667, "max_line_length": 125, "alphanum_fraction": 0.6805001812, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.9353465161493965, "lm_q1q2_score": 0.8838975084764004}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Part A: Numerical Differentiation Closure\ndef numerical_diff(f,h):\n    def inner(x):\n        return (f(x+h) - f(x))/h\n    return inner\n\n# Part B:\nf = np.log\nx = np.linspace(0.2, 0.4, 500)\nh = [1e-1, 1e-7, 1e-15]\ny_analytical = 1/x\nresult = {}\n\n\nfor i in h:\n    y = numerical_diff(f,i)(x)\n    result[i] = y\n\n# Plotting\nplt.figure(figsize = (8,5))\nplt.plot(x, y_analytical, 'x-', label='Analytical Derivative')\nfor i in h:\n    plt.plot(x, result[i], label='Estimated derivative h = '+str(i))\nplt.xlabel(\"X value\")\nplt.ylabel(\"Derivative Value at X\")\nplt.title(\"Differentiation Value at X on various h value\")\nplt.legend()\n\n\n# Part C:\nprint(\"Answer to Q-a: When h value is 1e-7, it most closely approximates the true derivative. \\n\",\n      \"When h value is too small: The approximation is jumping around stepwise and not displaying a smooth curve approximation, it amplifies floating point errors in numerical operation such as rounding and division\\n\",\n      \"When h value is too large: The approximation is lower than the true value, it doesn't provide a good approximation to the derivative\\n\")\nprint(\"Answer to Q-b: Automatic differentiation avoids the problem of not choosing a good h value. \\n\"\n      \"The finite difference approach is quick and easy but suffers from accuracy and stability problems.\\n\"\n      \"Symbolic derivatives can be evaluated to machine precision, but can be costly to evaluate.\\n\"\n      \"Automatic differentiation (AD) overcomes both of these deficiencies. It is less costly than symbolic differentiation while evaluating derivatives to machine precision.\\n\"\n      \"AD uses forward or backward modes to differentiate, via Computational Graph, chain rule and evaluation trace.\")\n\n# Show plot\nplt.show()\n# plt.savefig('P1_fig.png')\n\n", "meta": {"hexsha": "f73081bcbbb55a3e2f6093ea3985232180c04f1a", "size": 1812, "ext": "py", "lang": "Python", "max_stars_repo_path": "homework/HW4/HW4-final/P1.py", "max_stars_repo_name": "TangJiahui/cs107_system_devlopment", "max_stars_repo_head_hexsha": "c46d7769683d9be0c31973e3b0666e3fe2a4099b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework/HW4/HW4-final/P1.py", "max_issues_repo_name": "TangJiahui/cs107_system_devlopment", "max_issues_repo_head_hexsha": "c46d7769683d9be0c31973e3b0666e3fe2a4099b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework/HW4/HW4-final/P1.py", "max_forks_repo_name": "TangJiahui/cs107_system_devlopment", "max_forks_repo_head_hexsha": "c46d7769683d9be0c31973e3b0666e3fe2a4099b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-21T16:28:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T16:28:51.000Z", "avg_line_length": 38.5531914894, "max_line_length": 219, "alphanum_fraction": 0.7246136865, "include": true, "reason": "import numpy", "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885904, "lm_q2_score": 0.9219218337824341, "lm_q1q2_score": 0.883696859291544}}
{"text": "#!/usr/bin/env python3\n# coding: utf-8\n\nimport numpy as np\nimport mimetypes\nimport argparse\nimport matplotlib.pyplot as plt\nimport csv\n\n\ndef check_file_ext(filename):\n    \"\"\"\n    Check file extension\n    \"\"\"\n    if mimetypes.guess_type(filename)[0] != 'text/csv':\n        raise argparse.ArgumentTypeError('wrong filetype or path')\n    return filename\n\n\ndef normalize(x, min, max):\n    \"\"\"\n    Data min-max normalization:\n    \"\"\"\n    return (x - min) / (max - min)\n\n\ndef denormalize(x, min, max):\n    \"\"\"\n    Data min-max denormalization:\n    \"\"\"\n    return x * (max - min) + min\n\n\ndef estimate_price(mileage, theta0, theta1):\n    \"\"\"\n    Estimate price function: \n    \"\"\"\n    return theta0 + theta1 * mileage\n\n\ndef gradient_descent(X, Y, curr_t0, curr_t1, lr):\n    \"\"\"\n    Gradient descent and its derivate\n    \"\"\"\n    M = len(X)\n    deriv_theta0 = 0\n    deriv_theta1 = 0\n    for i in range(M):\n        deriv_theta0 += (1 / M) * ((curr_t0 + (curr_t1 * X[i])) - Y[i])\n        deriv_theta1 += (1 / M) * (((curr_t0 + (curr_t1 * X[i])) - Y[i]) * X[i])\n    tmp_theta0 = curr_t0 - lr * deriv_theta0\n    tmp_theta1 = curr_t1 - lr * deriv_theta1\n    return tmp_theta0, tmp_theta1\n\n\ndef cost_function(X, Y, theta0, theta1):\n    \"\"\"\n    Evaluate the loss\n    \"\"\"\n    M = len(X)\n    err = 0.0\n    for i in range(M):\n        err += (Y[i] - estimate_price(X[i], theta0, theta1)) ** 2\n    return err / M\n\n\ndef linear_regression(X, Y, lr, epochs):\n    \"\"\"\n    The linear regression function to train the model\n    \"\"\"\n    theta0 = 0\n    theta1 = 0\n    loss = []\n    for _ in range(epochs):\n        theta0, theta1 = gradient_descent(X, Y, theta0, theta1, lr)\n        loss.append(cost_function(X, Y, theta0, theta1))\n    return theta0, theta1, loss\n\n\ndef plot(x, y, t0, t1, loss):\n    line_x = [0, 1]\n    line_y = [(t1 * i) + t0 for i in line_x]\n    # plt.figure(1)\n    plt.subplot(211)\n    plt.plot(loss)\n    plt.xlabel('epochs')\n    plt.ylabel('loss')\n    plt.title('Loss')\n    plt.grid(True)\n    plt.subplot(212)\n    plt.plot(line_x, line_y)\n    plt.scatter(x, y, None, 'orange')\n    plt.title('Mileage vs. Price')\n    plt.xlabel('mileage')\n    plt.ylabel('price')\n    plt.grid(True)\n    plt.subplots_adjust(top=0.92, bottom=0.10, left=0.10, right=0.95, hspace=0.5, wspace=0.35)\n    plt.show()\n\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"filename\", type=check_file_ext, help=\"CSV file path\")\n    args = parser.parse_args()\n    data = np.genfromtxt(args.filename, delimiter=',', skip_header=1)\n    X = data[:, 0]\n    Y = data[:, 1]\n    xmin = np.min(X)\n    xmax = np.max(X)\n    ymin = np.min(Y)\n    ymax = np.max(Y)\n    normalized_X = [normalize(x, xmin, xmax) for x in X]\n    normalized_Y = [normalize(y, ymin, ymax) for y in Y]\n    learning_rate = 0.01\n    epochs = 10000\n    theta0, theta1, loss = linear_regression(normalized_X, normalized_Y, learning_rate, epochs)\n    plot(normalized_X, normalized_Y, theta0, theta1, loss)\n    print('Final loss = ', loss[-1])\n    with open('out.csv', mode='w') as out:\n        out_writer = csv.writer(out, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n        out_writer.writerow(['theta0', 'theta1', 'xmin', 'xmax', 'ymin', 'ymax'])\n        out_writer.writerow([theta0, theta1, xmin, xmax, ymin, ymax])\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "5e82b76b51ab2d52ff3ac820ee66f32c2244e5ab", "size": 3314, "ext": "py", "lang": "Python", "max_stars_repo_path": "train.py", "max_stars_repo_name": "zneel/ft_linear_regression", "max_stars_repo_head_hexsha": "7c16b7eb50f1a282f0c172ff4baf166cc113f734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "train.py", "max_issues_repo_name": "zneel/ft_linear_regression", "max_issues_repo_head_hexsha": "7c16b7eb50f1a282f0c172ff4baf166cc113f734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "train.py", "max_forks_repo_name": "zneel/ft_linear_regression", "max_forks_repo_head_hexsha": "7c16b7eb50f1a282f0c172ff4baf166cc113f734", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.094488189, "max_line_length": 95, "alphanum_fraction": 0.6074230537, "include": true, "reason": "import numpy", "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812354689083, "lm_q2_score": 0.9124361580958427, "lm_q1q2_score": 0.8835860540633562}}
{"text": "from sympy import Symbol, symbols\nfrom sympy import simplify\nfrom sympy import sin, cos, atan\nfrom sympy.matrices import Matrix\nfrom sympy import pprint\nfrom sympy import factor,expand,diff\nfrom sympy import sqrt\nfrom sympy import latex\nfrom sympy.vector import CoordSys3D\n\n\na,b,x,y,r,t,Vrr,Vrt,Vtt = symbols('a,b,x,y,r,t,V_rr,V_rt,V_tt', real=True)\ns11,s12,s13,s14,s15,s21,s22,s23,s24,s25,s31,s32,s33,s34,s35,s41,s4,s43,s44,s45,s51,s52,s53,s54,s55 = symbols('s1:6(1:6)', real=True)\nVxx, Vxy, Vxz, Vyx, Vyy, Vyz, Vzx, Vzy, Vzz = symbols('V_x:z(x:z)', real=True)\nx11, x12, x21, x22 = symbols('x_1:3(1:3)')\ny11, y12, y21, y22 = symbols('y_1:3(1:3)')\n(x1, x2) = symbols('x_1:3')\n(y1, y2) = symbols('y_1:3')\n(Vr1r1, Vr1r2, Vr2r1, Vr2r2) = symbols('V_r1:3(1:3)')\n(Vt1t1, Vt1t2, Vt2t1, Vt2t2) = symbols('V_t1:3(1:3)')\n(Vr1t1, Vr1t2, Vr2t1, Vr2t2) = symbols('V_r1:3t1:3')\n(Vt1r1, Vt1r2, Vt2r1, Vt2r2) = symbols('V_t1:3r1:3')\n(r1,r2) = symbols('r_1:3')\n\nPRINT_LATEX = 1\n\ndef printCentral(expression):\n  if PRINT_LATEX:\n    pprint(latex(expression, mode='equation', mat_str='smallmatrix'))\n  else:\n    pprint(expression)\n\n\nif PRINT_LATEX:\n    print(\"\\\\documentclass[8pt]{article}\")\n    print(\"\\\\usepackage{amsmath}\")\n    print(\"\\\\usepackage[landscape]{geometry}\")\n    print(\"\\\\begin{document}\")\n\n# Let's study the simple case u = a*x + b*y, with Cov(x,y)\n# Jacobian = [df/dx, df/dy] = [a, b]\n# Hence the Cov(u) = J * Cov(x,y) * JT\n\nJ = Matrix([[diff(a*x+b*y, x), diff(a*x+b*y, y)]])\nCov_xy = Matrix([[Vxx, Vxy], [Vxy, Vyy]])\nprint(\"\\nFor the case u = a*x + b*y we have a Cov(u):\")\nprintCentral(expand(J * Cov_xy * J.T))\n\n\n\n\n\n# Case of cartesian to polar transformation\n# x = r cos(t) = f1\n# y = r sin(t) = f2\n# Rotation matrix R = [[cos(t), -sin(t)], [sin(t), cos(t)]]\n\nV_xy = Matrix([[Vxx, Vxy], [Vxy, Vyy]])\nJ = Matrix([[cos(t), -sin(t)], [sin(t), cos(t)]])\n\nprint(\"\\nFor the case of going from x,y to r,theta(t), using a Rotation\")\nprintCentral(V_xy)\n\nprint(\"\\nRotation Matrix:\")\nprintCentral(J)\n\nprint(\"\\nFinal(destination) covariance Matrix:\")\nprintCentral(expand(J * V_xy * J.T))\n\n\n\n\n\n# Case of cartesian to polar transformation\n# x = r cos(t) = f1\n# y = r sin(t) = f2\n# Jacobian = [[df1/dr, df1/dt], [df2/dr, df2/dt]] = [[cos(t), -r*sin(t)], [sin(t), r*cos(t)]]\n\nprint(\"\\n\\n\\nCase of cartesian to polar transformation\")\nVar_xy = Matrix([[Vxx, Vxy], [Vxy, Vyy]])\nprint(\"\\nCartesian Variance:\")\nprintCentral(Var_xy)\n\nJacobian_cart_to_polar = Matrix([[diff(r*cos(t),r) , diff(r*cos(t), t)], [diff(r*sin(t), r), diff(r*sin(t), t)]])\nprint(\"\\nJacobian-cart-to-polar:\")\nprintCentral(Jacobian_cart_to_polar)\n\nprint(\"\\nPolar Variance:\")\nprintCentral(expand(Jacobian_cart_to_polar * Var_xy * Jacobian_cart_to_polar))\n\n\n# Case of polar coordinates to cartesian transtormation\n# r = sqrt(x^2+y^2) = f1\n# t = atan(y/x) = f2\n# Jacobian = [[df1/dx, df1/dy], [df2/dx, df2/dy]] = [[x/r, y/r], [-y/r^2, x/r^2]]\n\nprint(\"\\n\\n\\nCase of polar to cartesian transformation\")\nVar_rt = Matrix([[Vrr, Vrt], [Vrt, Vtt]])\nprint(\"\\nPolar Variance:\")\nprintCentral(Var_rt)\n\nf1 = sqrt(x**2+y**2)\nf2 = atan(y/x)\nJacobian_rad_to_cart = Matrix([[f1.diff(x).subs(x**2+y**2,r**2), f1.diff(y).subs(x**2+y**2,r**2)],\n                               [factor(f2.diff(x)).subs(x**2+y**2,r**2), factor(f2.diff(y)).subs(x**2+y**2,r**2)]])\nprint(\"\\nJacobian-rad-to-cart:\")\nprintCentral(Jacobian_rad_to_cart)\n\nprint(\"\\nCartesian Variance:\")\nprintCentral(expand(Jacobian_rad_to_cart * Var_rt * Jacobian_rad_to_cart.T))\n\n\n\n\n\n# Case of polar to cartesian coordinates, with several points using a block matrix.\n# Input Cov is: [[Vr1r1, Vr1r2, Vr1t1, Vr1t2],\n#                [Vr1r2, Vr2r2, Vr2t1, Vr2t2],\n#                [Vt1r1, Vt1r2, Vt1t1, Vt1t2],\n#                [Vt2r1, Vt2r2, Vt2t1, Vt2t2]]\n#\n# Also the Jacobian becomes block-ed\n#\n# Jacobian_block = [[x1/r1, 0, y1/r1, 0],\n#                   [0, x2/r2, 0, y2/r2],\n#                   [-y1/r1**2, 0, x1/r1**2, 0],\n#                   [0, -y2/r2**2, 0, x2/r2**2]]\n\nprint(\"\\n\\n\\nPolar to Cartesian transformation, using multiple points with block matrices.\")\n\nprint(\"\\nInput Covariance block matrix:\")\nVar_block = Matrix([[Vr1r1, Vr1r2, Vr1t1, Vr1t2],\n                    [Vr1r2, Vr2r2, Vr2t1, Vr2t2],\n                    [Vt1r1, Vt1r2, Vt1t1, Vt1t2],\n                    [Vt2r1, Vt2r2, Vt1t2, Vt2t2]])\nprintCentral(Var_block)\n\nprint(\"\\nJacobian block matrix:\")\nJacobian_block = Matrix([[x1/r1, 0, y1/r1, 0],\n                         [0, x2/r2, 0, y2/r2],\n                         [-y1/r1**2, 0, x1/r1**2, 0],\n                         [0, -y2/r2**2, 0, x2/r2**2]])\nprintCentral(Jacobian_block)\n\nprint(\"\\nCartesian Covariance block matrix:\")\nprintCentral(expand(Jacobian_block * Var_block * Jacobian_block.T))\n\n\n\n# Now we compute the Jacobian for the s variable for the  line fit.\n\nx0,y0,xi,yi,q,R = symbols('X_0, Y_0 x_i, y_i q R')\nN = CoordSys3D('N')\no = x0*N.i + y0*N.j\ntmp = xi*N.i + yi*N.j\na = -o\nb = tmp - o\n\nprint(\"\\n\\n\\nInput values:\")\nprint(\"\\na:\")\nprintCentral(a)\nprint(\"\\nb:\")\nprintCentral(b)\n\nc_ = expand((a ^ b) & N.k)\nd_ = expand(a & b)\nc2_d2 = factor(c_**2+d_**2)\nk = -q*R/c2_d2\n\nprint(\"\\ncross:\")\nprintCentral(c_)\n\nprint(\"\\ndot:\")\nprintCentral(d_)\n\nc2_d2 = factor(c_**2+d_**2)\n\nkm = k*(x0**2+y0**2)\nprint(\"\\nkm:\")\nprintCentral(km)\n\nprint(\"\\nk:\")\nprintCentral(k)\nprint(\"\\nk also as:\")\nprintCentral(k.subs(c2_d2, 'dot**2+cross**2'))\nprint(\"\\ni.e. k:\")\nprintCentral(k.subs(km,'km'))\n\ns = -q * R * atan(c_/d_)\nprint(\"\\ns:\")\nprintCentral(s.subs(d_,'dot').subs(c_,'cross'))\n\n# compute the Jacobian\n\nJacobian_s = Matrix([\n    factor(diff(s,x0)).subs(k, 'k'),\n    factor(diff(s,y0)).subs(k, 'k'),\n    simplify(factor(diff(s,R))).subs(d_,'dot').subs(c_,'cross'),\n    factor(diff(s,xi)).subs(km, 'km'),\n    factor(diff(s,yi)).subs(-km, '-km')\n    ])\n\n\nprint(\"\\nJacobian [x0, y0, R, xi, yi]:\")\nprintCentral(Jacobian_s)\n\nprint(\"\\nNote that -(b_y - a_y)*dot + (b_x + a_x)*cross is:\")\nprintCentral(factor(-(b.components[N.j] - a.components[N.j])*d_ + (b.components[N.i] + a.components[N.i])*c_))\n\nprint(\"\\nNote that (b_x - a_x)*dot - (-a_y - b_y)*cross is:\")\nprintCentral(factor((b.components[N.i] - a.components[N.i])*d_ - (-a.components[N.j] - b.components[N.j])*c_))\n\nprint(\"\\nNote that -a_y*dot - a_x*cross is:\")\nprintCentral(factor(-a.components[N.j]*d_ - a.components[N.i]*c_))\n\nprint(\"\\nNote that a_x*dot-a_y*cross is:\")\nprintCentral(factor(a.components[N.i]*d_ - a.components[N.j]*c_))\n\n\nif PRINT_LATEX:\n    print(\"\\\\end{document}\")\n", "meta": {"hexsha": "cc76c6279aadec7fa760267e96188c32f3fd070e", "size": 6446, "ext": "py", "lang": "Python", "max_stars_repo_path": "RiemannFitJacobians.py", "max_stars_repo_name": "rovere/utilities", "max_stars_repo_head_hexsha": "fe864dbe45f688ef9070deb5eb6e9cbd4fb359a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RiemannFitJacobians.py", "max_issues_repo_name": "rovere/utilities", "max_issues_repo_head_hexsha": "fe864dbe45f688ef9070deb5eb6e9cbd4fb359a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RiemannFitJacobians.py", "max_forks_repo_name": "rovere/utilities", "max_forks_repo_head_hexsha": "fe864dbe45f688ef9070deb5eb6e9cbd4fb359a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.036036036, "max_line_length": 132, "alphanum_fraction": 0.6208501396, "include": true, "reason": "from sympy", "num_tokens": 2374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.9334308040850653, "lm_q1q2_score": 0.8835824910091955}}
{"text": "# Cross entropy is one out of many possible loss functions (another\n# popular one is SVM hinge loss). These loss functions are typically\n# written as J(theta) and can be used within gradient descent, which\n# is an iterative algorithm to move the parameters (or coefficients)\n# towards the optimum values.\n\n# For multi-class problem\n\n# our y needs to be one-hot encoded\n# apply softmax\n\n# Average the losses over the entire test set, and you get the cross entropy loss.\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\n# squashes output from 0 to 1\ndef softmax(x):\n    return np.exp(x) / np.sum(np.exp(x), axis = 0)\n\nx = np.array([2.0, 1.0, 0.1])\noutput = softmax(x)\nprint('softmax numpy:', output)\n\nx = torch.tensor([2.0, 1.0, 0.1])\noutput = torch.softmax(x, dim=0)\nprint(output)\n\n# a lot of times softmax is used with cross entropy\n# loss increases as predicted probabiliy diverges from true\n# high cross entropy for very wrong prediction\n\ndef cross_entropy(actual, predicted):\n    loss = -np.sum(actual * np.log(predicted))\n    return loss\n\nY = np.array([1, 0, 0])\n\nY_pred_good = np.array([.7, .2, .1])\nY_pred_bad = np.array([.1, .3, .6])\nl1 = cross_entropy(Y, Y_pred_good)\nl2 = cross_entropy(Y, Y_pred_bad)\nprint(f'Loss1 numpy: {l1:.4f}')\nprint(f'Loss2 numpy: {l2:.4f}')\n", "meta": {"hexsha": "7edfe2360fbbcba88af820a1a86d25b0ef268c6a", "size": 1280, "ext": "py", "lang": "Python", "max_stars_repo_path": "11_softmax_cross_entropy.py", "max_stars_repo_name": "LilySu/neural-networks-pytorch", "max_stars_repo_head_hexsha": "6e6c67f9fdd49e21579085ededcb8c266b9508dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "11_softmax_cross_entropy.py", "max_issues_repo_name": "LilySu/neural-networks-pytorch", "max_issues_repo_head_hexsha": "6e6c67f9fdd49e21579085ededcb8c266b9508dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "11_softmax_cross_entropy.py", "max_forks_repo_name": "LilySu/neural-networks-pytorch", "max_forks_repo_head_hexsha": "6e6c67f9fdd49e21579085ededcb8c266b9508dc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4444444444, "max_line_length": 82, "alphanum_fraction": 0.71171875, "include": true, "reason": "import numpy", "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147201714923, "lm_q2_score": 0.9086179031191509, "lm_q1q2_score": 0.8835534240044173}}
{"text": "# Import the necessary modules.\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# This script will demonstrate the usefulness of using the taylor expansion\n# to approximate the local shape of a curve. We will look at a simple function,\n# y = cos(x), but it may be useful for you to try more complicated functions.\n\n# To start, we'll make an array of x values at which we will evaluate cos(x).\nx = np.linspace(-4 * np.pi, 4 * np.pi, 500)\ny = np.cos(x)\n\n# Let's evaluat eh first handful of orders.\norder_0  = np.ones_like(x)\norder_2 = 1 - x**2 / np.math.factorial(2)\norder_4 = order_2 + x**4 / np.math.factorial(4)\norder_6 = order_4 - x**6 / np.math.factorial(6)\n\n# Now let's plot all of them together.\nplt.figure()\nplt.plot(x, y, label='cos(x)')\nplt.plot(x, order_0, label='0th order')\nplt.plot(x, order_2, label='2nd order')\nplt.plot(x, order_4, label='4th order')\nplt.plot(x, order_6, label='6th order')\n\n# Add the legend and labels.\nplt.legend()\nplt.xlabel('x')\nplt.ylabel('y')\n\n# Change the yrange so it's easier to see.\nplt.ylim([-1.5, 1])\nplt.show()\n\n# With this, we can see that even the first few expansions are a great\n# approximation of the actual behavior.\n", "meta": {"hexsha": "aada4d39286dd25c226f71f647694d13a0a0bd18", "size": 1193, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/taylor_expansion.py", "max_stars_repo_name": "RPGroup-PBoC/gist_pboc_2017", "max_stars_repo_head_hexsha": "2c2f5134e221cf174c92a933ab1e5f71b2eb8b17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/taylor_expansion.py", "max_issues_repo_name": "RPGroup-PBoC/gist_pboc_2017", "max_issues_repo_head_hexsha": "2c2f5134e221cf174c92a933ab1e5f71b2eb8b17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/taylor_expansion.py", "max_forks_repo_name": "RPGroup-PBoC/gist_pboc_2017", "max_forks_repo_head_hexsha": "2c2f5134e221cf174c92a933ab1e5f71b2eb8b17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-08T00:48:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-08T00:48:28.000Z", "avg_line_length": 30.5897435897, "max_line_length": 79, "alphanum_fraction": 0.7082984074, "include": true, "reason": "import numpy", "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.972414716174355, "lm_q2_score": 0.9086178987887253, "lm_q1q2_score": 0.8835534161615772}}
{"text": "import numpy as np\nfrom scipy import stats\nimport math\n\nx = np.array([25,35,10,40,85,75,60,45,50])\ny = np.array([63,68,72,62,65,46,51,60,55])\nn = x.size\n\nmean_x = np.mean(x)\nmean_y = np.mean(y)\nprint(\"mean x : \",mean_x)\nprint(\"mean y : \",mean_y)\n\nx_i= x - mean_x\ny_i = y - mean_y\nprint(\"\\nxi : \",x_i)\nprint(\"yi : \",y_i)\n\nx_i_square = np.square(x_i)\ny_i_square = np.square(y_i)\nxi_yi = x_i * y_i\nprint(\"\\nxi**2 : \",x_i_square)\nprint(\"yi**2 : \",y_i_square)\nprint(\"xi*yi : \",xi_yi)\n\nsum_x_i = np.sum(x_i)\nsum_y_i = np.sum(y_i)\nsum_xi_square = np.sum(x_i_square)\nsum_yi_square = np.sum(y_i_square)\nsum_xi_yi = np.sum(xi_yi)\n\nprint(\"\\nsum_x_i : \",sum_x_i)\nprint(\"sum_y_i : \",sum_y_i)\nprint(\"sum_xi_square : \",sum_xi_square)\nprint(\"sum_yi_square : \",sum_yi_square)\nprint(\"sum_xi_yi : \",sum_xi_yi)\n\ncoeff_numerator  = ((n*sum_xi_yi) - (sum_x_i*sum_y_i))\ncoeff_denominator_1 = math.sqrt((n*sum_xi_square) - math.pow(sum_x_i,2))\ncoeff_denominator_2 = math.sqrt((n*sum_yi_square) - math.pow(sum_y_i,2))\n\ncoeff = coeff_numerator/(coeff_denominator_1*coeff_denominator_2)\nprint(\"\\n coefficent of corelation : \",coeff)", "meta": {"hexsha": "ec4f7aa5d828b4c19165edded2796fb744ccfa1f", "size": 1105, "ext": "py", "lang": "Python", "max_stars_repo_path": "Statistics/coefficent_of_corelation.py", "max_stars_repo_name": "Dheer08/Algorithms", "max_stars_repo_head_hexsha": "6731a5896ab338b6123280275fab5f36bdd52b4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Statistics/coefficent_of_corelation.py", "max_issues_repo_name": "Dheer08/Algorithms", "max_issues_repo_head_hexsha": "6731a5896ab338b6123280275fab5f36bdd52b4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/coefficent_of_corelation.py", "max_forks_repo_name": "Dheer08/Algorithms", "max_forks_repo_head_hexsha": "6731a5896ab338b6123280275fab5f36bdd52b4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6976744186, "max_line_length": 72, "alphanum_fraction": 0.7031674208, "include": true, "reason": "import numpy,from scipy", "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018383629827, "lm_q2_score": 0.9059898305367525, "lm_q1q2_score": 0.8835229482776082}}
{"text": "\"\"\"\nProblem 7:\n\nWhat is the 10001st prime number?\n\"\"\"\n\nimport numpy as np\n\n# We will solve this using the sieve of Eratosthenes\n# The pseudocode can be found at https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Pseudocode\n\nn = 200000\nsieve = np.array([True for _ in range(n)])\nsieve[0:2] = False\nupper_bound = int(np.sqrt(n))\n\nfor i in range(2, upper_bound+1):\n    if sieve[i]:\n        j = i * i\n        counter = 0\n        while j < n:\n            sieve[j] = False\n            j = (i * i) + (counter * i)\n            counter += 1\n\nprimes = np.where(sieve == True)[0]\n\n# The solution is at index 10000 since we start at index 0\nsolution = primes[10000]\nprint('solution: ', solution)\n\n", "meta": {"hexsha": "807f94440936b364e2a9c7556324c6a5cacecd49", "size": 686, "ext": "py", "lang": "Python", "max_stars_repo_path": "problem007.py", "max_stars_repo_name": "gboluwaga/ProjectEuler", "max_stars_repo_head_hexsha": "079496db04f1c3b6d2e421f8dd4db46b3f76b465", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-07-25T08:58:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-13T05:48:22.000Z", "max_issues_repo_path": "problem007.py", "max_issues_repo_name": "gboluwaga/ProjectEuler", "max_issues_repo_head_hexsha": "079496db04f1c3b6d2e421f8dd4db46b3f76b465", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem007.py", "max_forks_repo_name": "gboluwaga/ProjectEuler", "max_forks_repo_head_hexsha": "079496db04f1c3b6d2e421f8dd4db46b3f76b465", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2018-08-11T10:05:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-09T14:50:56.000Z", "avg_line_length": 21.4375, "max_line_length": 95, "alphanum_fraction": 0.6224489796, "include": true, "reason": "import numpy", "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9840936106207203, "lm_q2_score": 0.8976952880018481, "lm_q1q2_score": 0.8834161972069461}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 17 15:05:05 2022\n\n@author: bobrokerson\n\n\"\"\"\n\n# Рассмотрим все ту же функцию из задания по линейной алгебре: \n# f(x) = sin(x / 5) * exp(x / 10) + 5 * exp(-x / 2), но теперь уже на промежутке [1, 30]\n# В первом задании будем искать минимум этой функции на заданном промежутке с помощью scipy.optimize. \n# Разумеется, в дальнейшем вы будете использовать методы оптимизации для более сложных функций,\n# а f(x) мы рассмотрим как удобный учебный пример.\n# Напишите на Питоне функцию, вычисляющую значение f(x) по известному x. \n# Будьте внимательны: не забывайте про то, что по умолчанию в питоне целые числа делятся нацело, и о том, \n# что функции sin и exp нужно импортировать из модуля math.\n\n\nfrom math import sin, exp\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef func(x):\n    return sin(x / 5.) * exp(x / 10.) + 5. * exp(-x/ 2.)\n\n\nxarr = np.arange(1., 31.)\nprint(xarr)\nprint(\"x:\", xarr.shape)\nyarr = np.array([func(x) for x in xarr])\nprint(yarr)\nprint(\"y:\", yarr.shape)\n\nplt.plot(xarr, yarr)\nplt.grid(True)\nplt.axis([0, 30, -15, 5])\nplt.show()\n\n\n# Изучите примеры использования  scipy.optimize.minimize в документации Scipy (см. \"Материалы\")\n# Попробуйте найти минимум, используя стандартные параметры в функции  scipy.optimize.minimize \n# (т.е. задав только функцию и начальное приближение). Попробуйте менять начальное приближение и изучить, меняется ли результат. \n# Укажите в scipy.optimize.minimize в качестве метода BFGS (один из самых точных в большинстве случаев градиентных методов оптимизации),\n# запустите из начального приближения x=2. Градиент функции при этом указывать не нужно – он будет оценен численно. \n# Полученное значение функции в точке минимума - ваш первый ответ по заданию 1, его надо записать с точностью до 2 знака после запятой.\n\nfrom scipy.optimize import minimize\n\nminFuncVal = minimize(func, 5)\nprint(\"Min f(x): \", round(minFuncVal.fun,2), \"x = \", minFuncVal.x)\nprint(\"Number: \", minFuncVal.nit)\n\n\nminFuncVal2 = minimize(func, 2, method = 'BFGS')\nprint(\"Min f(x) BFGS: \", round(minFuncVal2.fun, 2), \"for x = \", minFuncVal2.x)\nprint(\"Number: \", minFuncVal2.nit)\n\nminValR1 = np.zeros((2))\nminValR1[0] = round(minFuncVal2.fun, 2)\nprint(minValR1)\n\n# Теперь измените начальное приближение на x=30. Значение функции в точке минимума - ваш второй ответ по заданию 1, \n# его надо записать через пробел после первого, с точностью до 2 знака после запятой.\n\nminFuncVal3 = minimize(func, 30, method = 'BFGS')\nprint(\"Min f(x) BFGS method: \", minFuncVal3, \"for x = \", minFuncVal3.x)\nprint(\"Number: \", minFuncVal3)\n\nminValR1[1] = round(minFuncVal3.fun, 2)\nprint(minValR1)\n\nminValR1[1] = round(minFuncVal3.fun, 2)\nprint(minValR1)\n\n\nwith open(\"docvalue.txt\", \"w\") as file:\n    for item in minValR1:\n        file.write(str(item) + ' ')\n", "meta": {"hexsha": "5b8250eb30901c370630ca2f7947a82093192012", "size": 2832, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment/min_smooth_fun.py", "max_stars_repo_name": "bobrokerson/libraries", "max_stars_repo_head_hexsha": "996509d341af7108a24053eb88431ec6afbb0f25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment/min_smooth_fun.py", "max_issues_repo_name": "bobrokerson/libraries", "max_issues_repo_head_hexsha": "996509d341af7108a24053eb88431ec6afbb0f25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment/min_smooth_fun.py", "max_forks_repo_name": "bobrokerson/libraries", "max_forks_repo_head_hexsha": "996509d341af7108a24053eb88431ec6afbb0f25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.962962963, "max_line_length": 136, "alphanum_fraction": 0.7235169492, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.937210785703199, "lm_q1q2_score": 0.8833274677330815}}
{"text": "import numpy\n\ndef tridiag(a, b, c, d):\n    \"\"\" solve the linear system Ax = d where A has the form:\n\n          a_i x_{i-1} + b_i x_i + c_i x_{i+1} = d_i\n\n        for i = 0, n-1 with a_0 = 0 and c_{n-1} = 0\n\n        In matrix form, b is the main diagonal, a is the subdiagonal and\n        c is the superdiagonal. \"\"\"\n\n    N = len(a)\n    if not (len(b) == len(c) == len(d) == N):\n        print \"ERROR: vectors not the right size\"\n        return None\n\n    # forward elimination\n    cprime = numpy.zeros((N), dtype=a.dtype)\n    dprime = numpy.zeros((N), dtype=a.dtype)\n    \n    cprime[0] = c[0]/b[0]\n    dprime[0] = d[0]/b[0]\n\n    for i in range(1,N-1):\n        cprime[i] = c[i]/(b[i] - cprime[i-1]*a[i])\n        dprime[i] = (d[i] - dprime[i-1]*a[i])/(b[i] - cprime[i-1]*a[i])\n        \n    dprime[N-1] = (d[N-1] - dprime[N-2]*a[N-1])/(b[N-1] - cprime[N-2]*a[N-1])\n\n    # back substitution\n    x = numpy.zeros((N), dtype=a.dtype)\n\n    x[N-1] = dprime[N-1]\n    for i in reversed(range(0,N-1)):\n        x[i] = dprime[i] - cprime[i]*x[i+1]\n\n    return x\n\n\ndef triMultAx(a, b, c, x):\n    \"\"\" multiply the tridiagonal matrix A by vector x and return the\n        product vector d \"\"\"\n\n    N = len(a)\n    if not (len(b) == len(c) == len(x) == N):\n        print \"ERROR: vectors not the right size\"\n        return None\n\n    \n    d = numpy.zeros((N), dtype=a.dtype)\n\n    d[0] = b[0]*x[0] + c[0]*x[1]\n    for i in range(1,N-1):\n        d[i] = a[i]*x[i-1] + b[i]*x[i] + c[i]*x[i+1]\n    \n    d[N-1] = a[N-1]*x[N-2] + b[N-1]*x[N-1]\n\n    return d\n\n\n    \n    \n", "meta": {"hexsha": "432895ad5f7fcbe9ac4ba392baeed22ed114e02d", "size": 1539, "ext": "py", "lang": "Python", "max_stars_repo_path": "others/lin_algebra/tridiag.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "others/lin_algebra/tridiag.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/lin_algebra/tridiag.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 24.046875, "max_line_length": 77, "alphanum_fraction": 0.5003248863, "include": true, "reason": "import numpy", "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474142844409, "lm_q2_score": 0.9252299648234481, "lm_q1q2_score": 0.8832683935371889}}
{"text": "import numpy as np\nfrom math import *\nfrom sympy import *\nfrom scipy import interpolate\nfrom scipy.misc import comb\nfrom matplotlib import pyplot as plt\n\n\ndef bernstein_poly(i, n, t):\n    \"\"\"\n     The Bernstein polynomial of n, i as a function of t\n    \"\"\"\n\n    return comb(n, i) * ( t**(n-i) ) * (1 - t)**i\n\n\ndef bezier_curve(points, nTimes=1000):\n    \"\"\"\n       Given a set of control points, return the\n       bezier curve defined by the control points.\n\n       points should be a list of lists, or list of tuples\n       such as [ [1,1],\n                 [2,3],\n                 [4,5], ..[Xn, Yn] ]\n        However, we aware that the function takes in input as they come. So, if the points\n        are not ordered correctly, you will get incorrect results. \n        Should be: [ [x1,y1],\n                     [x2,y2],\n                     ........[xn,yn] ]\n        nTimes is the number of time steps, defaults to 1000\n\n    \"\"\"\n\n    nPoints = len(points)\n    xPoints = np.array([p[0] for p in points])\n    yPoints = np.array([p[1] for p in points])\n\n\n\n    t = np.linspace(0.0, 1.0, nTimes)\n\n    polynomial_array = np.array([ bernstein_poly(i, nPoints-1, t) for i in range(0, nPoints)   ])\n\n    xvals = np.dot(xPoints, polynomial_array)\n    yvals = np.dot(yPoints, polynomial_array)\n\n    return xvals, yvals, xPoints, yPoints\n\ndef bezier_spline(xPoints, yPoints, numPoints):\n    t = symbols('t')\n    if numPoints <= 3:\n        print(\"Enter atleast two control point and one pass through point!\\n\")\n    elif numPoints == 4:\n        bx = 3 * (xPoints[1] - xPoints[0])\n        cx = 3 * (xPoints[2] - xPoints[1]) - bx\n        dx = xPoints[3]-xPoints[0]-bx-cx\n        by = 3 * (yPoints[1] - yPoints[0])\n        cy = 3 * (yPoints[2] - yPoints[1]) - by\n        dy = (yPoints[3]-yPoints[0])-by-cy\n        print('x(t) = ' + latex(xPoints[0] + bx * t + cx * t ** 2 + dx * t ** 3))\n        print('y(t) = ' + latex(xPoints[0]+by*t+cy*t**2+dy*t**3))\n    else:\n        print(\"This is an invalid entry. Sorry, please try again.\\n\")\n\n\n# understand  you must enter 4 points.\n# if you do not enter 4 points the function will\n# reject. If you have equations to enter, please enter the points\n# in the form\ndef bezier(user_input, n):\n    point = '(';\n    foundPoint = False;\n    userString = str(user_input);\n    try:\n        if userString.find(point) != -1:\n            foundPoint = True;\n        if(foundPoint):\n            points = np.array(user_input)\n            xvals, yvals, xPoints, yPoints = bezier_curve(user_input, nTimes=1000)\n            bezier_spline(xPoints, yPoints, n)\n            plt.plot(xvals, yvals)\n            plt.plot(xPoints, yPoints, \"ro\")\n            for nr in range( len(user_input)):\n                plt.text(xPoints[nr], yPoints[nr], nr)\n\n            plt.show()\n        else:\n            length = len(user_input)\n            xPoints = np.array(user_input[0])\n            yPoints = np.array(user_input[1])\n            if length == 3:\n                zPoints = np.array(user_input[2])\n                x1,y1,z1 = xPoints[0],yPoints[0],zPoints[0]\n                bx = xPoints[1]\n                x2 = eval('(bx+3*x1)/3')\n                cx = xPoints[2]\n                x3 = eval('(cx+3*x2+bx)/3')\n                dx = xPoints[3]\n                x4 = eval('dx+x1+bx+cx')\n                by = yPoints[1]\n                y2 = eval('(by+3*y1)/3')\n                cy = yPoints[2]\n                y3 = eval('(cy+3*y2+by)/3')\n                dy = yPoints[3]\n                y4 = eval('dy+y1+by+cy')\n                bz = zPoints[1]\n                z2 = eval('(bz+3*z1)/3')\n                cz = zPoints[2]\n                z3 = eval('(cz+3*z2+bz)/3')\n                dz = zPoints[3]\n                z4 = eval('dz+z1+bz+cz')\n                print('Knots: (' + str(x1) + ',' + str(y1) + ',' + str(z1) + ')'+','\\\n                '(' + str(x4) + ',' + str(y4) + ',' + str(z4) + ')')\n                print('Control Points: (' + str(x2) + ',' + str(y2) + ',' + str(z2) + ')'+','\\\n                '(' + str(x4) + ',' + str(y3) + ',' + str(z3) + ')')\n            elif length == 2:\n                x1, y1 = xPoints[0], yPoints[0]\n                bx = xPoints[1]\n                x2 = eval('(bx+3*x1)/3')\n                cx = xPoints[2]\n                x3 = eval('(cx+3*x2+bx)/3')\n                dx = xPoints[3]\n                x4 = eval('dx+x1+bx+cx')\n                by = yPoints[1]\n                y2 = eval('(by+3*y1)/3')\n                cy = yPoints[2]\n                y3 = eval('(cy+3*y2+by)/3')\n                dy = yPoints[3]\n                y4 = eval('dy+y1+by+cy')\n                print('Knots: (' + str(x1) + ',' + str(y1) + ')' + ',' + '(' + str(x4) + ',' +\n                str(y4) + ')')\n                print('Control Points: (' + str(x2) + ',' + str(y2) +')' + ','+ '(' + str(x4) + ',' + str(\n                    y3) + ')')\n            else:\n                print(\"Sorry, you can only use a maximum of 3 equations\\n\")\n\n    except:\n        e = sys.exc_info()[0]\n        write_to_page(\"<p>Error: %s</p>\" % e)\n        print('Sorry, you have not entered correct input\\n')\n        return -1\n\n\ndef main():\n    # nPoints = 4\n    # points = np.random.rand(nPoints,2)*200\n    nPoints = 4\n    points = [[1,0,6,2],[1,-1,0,1],[1,1,6,0]]\n    bezier(points,nPoints)\n\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "581b7cfde7821e8980c389a8733c655629bb77bb", "size": 5294, "ext": "py", "lang": "Python", "max_stars_repo_path": "sample.py", "max_stars_repo_name": "nguyenvu2589/Numerical", "max_stars_repo_head_hexsha": "23eee7d31a8871d5d53871ebc9950866cf11ad23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sample.py", "max_issues_repo_name": "nguyenvu2589/Numerical", "max_issues_repo_head_hexsha": "23eee7d31a8871d5d53871ebc9950866cf11ad23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sample.py", "max_forks_repo_name": "nguyenvu2589/Numerical", "max_forks_repo_head_hexsha": "23eee7d31a8871d5d53871ebc9950866cf11ad23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9358974359, "max_line_length": 106, "alphanum_fraction": 0.4756327918, "include": true, "reason": "import numpy,from scipy,from sympy", "num_tokens": 1576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877692486438, "lm_q2_score": 0.9099070084811307, "lm_q1q2_score": 0.8832356042862556}}
{"text": "import numpy\nimport scipy.linalg\nimport matplotlib.pyplot as plt\n\ndef cspline(x, y, x_interp, B0, Bk):\n    # h_i, v_i, d_i, i = 0, 1, ..., k - 1:\n    h = x[1:] - x[:-1]\n    v = y[1:] - y[:-1]\n    d = v / h\n\n    # 1 / h_i, i = 0, 1, ..., k - 1:\n    off_diag = 1.0/h\n    # 2 * ( 1 / h_i + 1 / h_{i + 1} ), i = 0, 1, ..., k - 2\n    diag = 2.0*(off_diag[1:] + off_diag[:-1])\n    # 1 / h_i, i = 1, 2, ..., k - 2:\n    off_diag = off_diag[1:-1]\n\n    # Compact tridiagonal hermitian matrix:\n    A = numpy.zeros((2, diag.size))\n    A[0,1:] = off_diag[:]\n    A[1,:] = diag\n\n    # Right-hand side:\n    z = d/h\n    b = 3.0 * (z[:-1] + z[1:])\n    b[0] = b[0] - B0/h[0]\n    b[-1] = b[-1] - Bk/h[-1]\n\n    # B-coefficients:\n    B = numpy.zeros( (b.size + 2, ))\n    B[1:-1] = scipy.linalg.solve_banded(A, b)\n    B[0] = B0\n    B[-1] = Bk\n\n    # C-coefficients:\n    C = (3.0*d - 2.0*B[:-1] - B[1:])/h\n    # D-coefficients:\n    D = (B[:-1] + B[1:] - 2.0*d)/(h**2)\n\n    # Interpolate:\n    y_interp = numpy.zeros(x_interp.shape)\n    k = 0\n    for i in range( x_interp.size ):\n        # Find appropriate segment:\n        while k < C.size and x_interp[i] > x[k + 1]:\n            k = k + 1\n        # Compute cubic polinomial:\n        h_x = x_interp[i] - x[k]\n        y_interp[i] = y[k] + B[k]*h_x + C[k]*(h_x**2) + D[k]*(h_x**3)\n\n    return y_interp\n\ndef runge(x):\n    return 1.0/(1.0 + 25.0 * x**2)\n\n\n# 1-) splines naturais: s'(x0) = B0 = 0 e s'(xk) = Bk = 0\n\nB0 = 0\nBk = 0\n\nek = []\nfor k in range(1,15):\n    x_interp = numpy.linspace(-1.1,1.1,100)\n   \n    x = numpy.zeros(k+1)\n    for i in range(k+1):\n        x[i] = -1 + 2*i/k  \n\n    sk = cspline( x, runge(x), x_interp, B0 , Bk )\n    plt.plot(x_interp, runge(x_interp), 'r')\n    plt.plot(x_interp, sk, 'b')\n    plt.plot(x, runge(x), 'ko')\n    plt.show()\n\n    ek.append(numpy.amax(numpy.absolute(numpy.subtract(runge(x_interp), sk))))\n\n", "meta": {"hexsha": "ec500424cdfc40b49b6b9553e13d121800b40e2d", "size": 1864, "ext": "py", "lang": "Python", "max_stars_repo_path": "splines.py", "max_stars_repo_name": "isabelamatos/interpolation", "max_stars_repo_head_hexsha": "e898cf962f1ed04abbaad3f9829916d7b6155e0a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "splines.py", "max_issues_repo_name": "isabelamatos/interpolation", "max_issues_repo_head_hexsha": "e898cf962f1ed04abbaad3f9829916d7b6155e0a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "splines.py", "max_forks_repo_name": "isabelamatos/interpolation", "max_forks_repo_head_hexsha": "e898cf962f1ed04abbaad3f9829916d7b6155e0a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8974358974, "max_line_length": 78, "alphanum_fraction": 0.4833690987, "include": true, "reason": "import numpy,import scipy", "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811611608242, "lm_q2_score": 0.9149009625340367, "lm_q1q2_score": 0.8832281535582641}}
{"text": "'''\nLibrary of quantized and non-quantized activation functions.\n'''\n\nimport numpy as np\n\ndef tanh_activation(x):\n    '''Tanh activation function.\n\n    Parameters\n    ----------\n    x : float\n        Value of the input pre-activation.\n\n    Returns\n    -------\n    float\n        The corresponding Tanh(x) value.\n\n    '''\n    return np.tanh(x)\n\ndef sigmoid_activation(x):\n    r'''Sigmoid activation function defined as:\n    \n    .. math::\n        y = \\frac{1}{1+e^{-x}}\n\n    Parameters\n    ----------\n    x : float\n        Value of the input pre-activation.\n\n    Returns\n    -------\n    float\n        The result of the Sigmoid function.\n    '''\n    return 1 / (1 + np.exp(-x))\n\ndef sigmoid_tanh_activation(x):\n    r'''A Sigmoid activation defined as:\n    \n    .. math::\n        y = \\frac{\\tanh\\left(\\frac{x}{2}+1\\right)}{2}\n\n    Parameters\n    ----------\n    x : float\n        Value of the input pre-activation.\n\n    Returns\n    -------\n    float\n        The result of the Sigmoid function.\n    '''\n    return (np.tanh(x / 2) + 1) / 2\n\ndef fast_sigmoid_activation(x):\n    r'''Fast Sigmoid activation function defined as:\n    \n    .. math::\n        y = \\frac{x}{1+\\lvert x \\rvert}\n    \n    It can be used to reduce the amount of hardware resources needed\n    to implement a Sigmoid function.\n\n    Parameters\n    ----------\n    x : float\n        Value of the input pre-activation.\n\n    Returns\n    -------\n    float\n        The result of the fast Sigmoid.\n    '''\n    return x / (1 + np.abs(x))\n\ndef relu_activation(x):\n    '''Rectifier Linear Unit activation function.\n\n    Parameters\n    ----------\n    x : float\n        Value of the input pre-activation.\n\n    Returns\n    -------\n    float\n        Returns ``x`` if ``x`` is larger or equal to 0. Otherwise 0 is returned.\n    '''\n    return x * (x > 0)\n\ndef approximate_sigmoid_activation(x, alpha=0.001):\n    r'''Approximate version of the Fast Sigmoid activation function defined as:\n    \n    .. math::\n        y = 0.5 \\frac{x \\cdot \\alpha}{1+\\lvert x \\cdot \\alpha \\rvert} + 0.5\n\n    Parameters\n    ----------\n    x : float\n        Value of the input pre-activation\n    alpha : float, optional\n        Noise factor, defaults to 0.001\n\n    Returns\n    -------\n    float\n        The result of the approximate Sigmoid.\n    '''\n    return 0.5 * (x * alpha / (1 + np.abs(x * alpha))) + 0.5\n\ndef ramp_activation(x, bound=1):\n    '''A modified ReLU activation where the maximum (minimum) value\n    for the input is capped at a specified value.\n\n    Parameters\n    ----------\n    x : numpy.ndarray\n        The input tensor\n    bound : int, optional\n        Upper bound of the activation, by default 1\n\n    Returns\n    -------\n    numpy.ndarray\n        A tensor having the same shape of the input tensor, where\n        values are the result of the ramp activation.\n    '''\n    return np.maximum(-bound, np.minimum(bound, x))\n", "meta": {"hexsha": "df4377402f2d08eb643f99c100d4373aec2f1b67", "size": 2866, "ext": "py", "lang": "Python", "max_stars_repo_path": "darwin/activations.py", "max_stars_repo_name": "lnis-uofu/darwin", "max_stars_repo_head_hexsha": "e76d3a1cd5f93b85a6f32e6c6c3e7cadf32441a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "darwin/activations.py", "max_issues_repo_name": "lnis-uofu/darwin", "max_issues_repo_head_hexsha": "e76d3a1cd5f93b85a6f32e6c6c3e7cadf32441a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "darwin/activations.py", "max_forks_repo_name": "lnis-uofu/darwin", "max_forks_repo_head_hexsha": "e76d3a1cd5f93b85a6f32e6c6c3e7cadf32441a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5488721805, "max_line_length": 80, "alphanum_fraction": 0.5704815073, "include": true, "reason": "import numpy", "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688146, "lm_q2_score": 0.914900957313305, "lm_q1q2_score": 0.8832281466957765}}
{"text": "# https://docs.sympy.org/latest/tutorial/matrices.html\n\nfrom sympy import *\ninit_printing(use_unicode=False)\nfrom myprint import spprint\n\nspprint(Matrix([[1, -1], [3, 4], [0, 2]]))\n\nspprint(Matrix([1, 2, 3]))\n\nM = Matrix([[1, 2, 3], [3, 2, 1]])\nN = Matrix([0, 1, 1])\n\nspprint(M)\nspprint(N)\nspprint(M*N)\n\n# shape\n\nM = Matrix([[1, 2, 3], [-2, 0, 4]])\nspprint(M)\n\n# cannot find shape - is it in sympy-1.8\nspprint(shape(M))\n\n# rows and columns\n\nspprint(M.row(0))\nspprint(M.col(-1))\n\nM.col_del(0)\nspprint(M)\n\nM.row_del(1)\nspprint(M)\n\nM = M.row_insert(1, Matrix([[0, 4]]))\nspprint(M)\n\nM = M.col_insert(0, Matrix([1, -2]))\nspprint(M)\n\n# math et al\n\nM = Matrix([[1, 3], [-2, 3]])\nN = Matrix([[0, 3], [0, 7]])\nspprint(M + N)\nspprint(M*N)\nspprint(3*M)\nspprint(M**2)\nspprint(M**-1)\n\n# this gets error:\n# sympy.matrices.common.NonInvertibleMatrixError: Matrix det == 0; not invertible.\n#spprint(N**-1)\n\n# transpose\n\nM = Matrix([[1, 2, 3], [4, 5, 6]])\nspprint(M)\n\nspprint(M.T)\n\n# constructors\n\nspprint(eye(3))\n\nspprint(eye(4))\n\nspprint(zeros(2, 3))\n\nspprint(ones(3, 2))\n\nspprint(diag(1, 2, 3))\n\nspprint(diag(-1, ones(2, 2), Matrix([5, 7, 5])))\n\n# advanced\n\nM = Matrix([[1, 0, 1], [2, -1, 3], [4, 3, 2]])\nspprint(M)\n\nspprint(M.det())\n\nM = Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]])\nspprint(M)\n\nspprint(M.rref())\n\nM = Matrix([[1, 2, 3, 0, 0], [4, 10, 0, 0, 1]])\n\nspprint(M)\n\nspprint(M.nullspace())\n\nM = Matrix([[1, 1, 2], [2 ,1 , 3], [3 , 1, 4]])\n\nspprint(M)\n\nspprint(M.columnspace())\n\nM = Matrix([[3, -2,  4, -2], [5,  3, -3, -2], [5, -2,  2, -2], [5, -2, -3,  3]])\n\nspprint(M)\n\nspprint(M.eigenvals())\n\nspprint(M.eigenvects())\n\n# diagonalize\n\nspprint(M)\n\nP, D = M.diagonalize()\n\nspprint(P)\n\nspprint(D)\n\nspprint(P*D*P**-1)\n\nprint(P*D*P**-1 == M)\n\nlamda = symbols('lamda')\n\np = M.charpoly(lamda)\n\nspprint(p)\n\nspprint(factor(p.as_expr()))\n\n# zero testing\n\nfrom sympy import *\nq = Symbol(\"q\", positive = True)\nm = Matrix([\n[-2*cosh(q/3),      exp(-q),            1],\n[      exp(q), -2*cosh(q/3),            1],\n[           1,            1, -2*cosh(q/3)]])\n\nspprint(m.nullspace())\n\n\nimport warnings\ndef my_iszero(x):\n    try:\n        result = x.is_zero\n    except AttributeError:\n        result = None\n\n    # Warnings if evaluated into None\n    if result is None:\n        warnings.warn(\"Zero testing of {} evaluated into None\".format(x))\n    return result\n\nspprint(m.nullspace(iszerofunc=my_iszero))\n\ndef my_iszero(x):\n    try:\n        result = x.rewrite(exp).simplify().is_zero\n    except AttributeError:\n        result = None\n\n    # Warnings if evaluated into None\n    if result is None:\n        warnings.warn(\"Zero testing of {} evaluated into None\".format(x))\n    return result\n\nspprint(m.nullspace(iszerofunc=my_iszero))\n\n\n\n", "meta": {"hexsha": "5f6665d2c31a53d6ff8032f21092b3a2947c89a9", "size": 2722, "ext": "py", "lang": "Python", "max_stars_repo_path": "c12.py", "max_stars_repo_name": "bobbydurrett/sympytutorial", "max_stars_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c12.py", "max_issues_repo_name": "bobbydurrett/sympytutorial", "max_issues_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c12.py", "max_forks_repo_name": "bobbydurrett/sympytutorial", "max_forks_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.7341040462, "max_line_length": 82, "alphanum_fraction": 0.5844966936, "include": true, "reason": "from sympy", "num_tokens": 1053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811571768048, "lm_q2_score": 0.9149009515124917, "lm_q1q2_score": 0.8832281392732891}}
{"text": "from typing import List\n\nimport numpy as np\n\nfrom Common.Primes import sieve_of_atkin\n\n\ndef divisors(number: int) -> List[int]:\n    \"\"\"\n    This function calculates and returns a list of all divisors that a given number has, e.g.\n    f(number=24) -> [1, 2, 3, 4, 6, 8, 12, 24]\n    :param number: The number whose divisors are to be calculated\n    :return: A list of integer divisors\n    \"\"\"\n    if number < 1:\n        raise ValueError(f\"The input number must be greater than one ({number} !> 1).\")\n    if number == 1:\n        return [1]\n\n    divisor_list = set()\n    sqrt_ceil = int(np.floor(np.sqrt(number)) + 1)\n    for i in range(1, sqrt_ceil):\n        if number % i == 0:\n            divisor_list.add(i)\n            divisor_list.add(int(number/i))\n\n    return sorted(list(divisor_list))\n\n\ndef prime_factorization(number: int) -> List[int]:\n    \"\"\"\n    This function calculates and returns the prime factorization of an input number. This algorithm doesn't condense\n    factor multiples, e.g.\n    f(number=24) -> [2, 2, 2, 3] (and not [2, 3])\n    :param number: The number whose prime factors are to be calculated\n    :return: A list of integer prime factors\n    \"\"\"\n    if number <= 1:\n        return [number]\n\n    factors_list = []\n    primes_list = sieve_of_atkin(number)\n\n    for prime in primes_list:\n        while number % prime == 0:\n            factors_list += [prime]\n            number /= prime\n\n    if int(number) != 1:\n        raise ArithmeticError(f\"The prime factorization for the {number}; the number, {number} != 1\")\n    else:\n        return factors_list\n", "meta": {"hexsha": "c8b088543ab8dea17574c0dc2ffcfa7b0c1f7723", "size": 1574, "ext": "py", "lang": "Python", "max_stars_repo_path": "Common/Numbers.py", "max_stars_repo_name": "SigfriedHache/euler-project", "max_stars_repo_head_hexsha": "7c38deee65a793a441830a6d0916da61e86b8cf7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Common/Numbers.py", "max_issues_repo_name": "SigfriedHache/euler-project", "max_issues_repo_head_hexsha": "7c38deee65a793a441830a6d0916da61e86b8cf7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Common/Numbers.py", "max_forks_repo_name": "SigfriedHache/euler-project", "max_forks_repo_head_hexsha": "7c38deee65a793a441830a6d0916da61e86b8cf7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6981132075, "max_line_length": 116, "alphanum_fraction": 0.626429479, "include": true, "reason": "import numpy", "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211619568681, "lm_q2_score": 0.9059898159413479, "lm_q1q2_score": 0.8831780450970338}}
{"text": "'''\r\nObjective \r\nIn this challenge, we practice calculating the mean, median, and mode. Check out the Tutorial tab for learning materials and an instructional video!\r\n\r\nTask \r\nGiven an array, , of  integers, calculate and print the respective mean, median, and mode on separate lines. If your array contains more than one modal value, choose the numerically smallest one.\r\n\r\nNote: Other than the modal value (which will always be an integer), your answers should be in decimal form, rounded to a scale of  decimal place (i.e., ,  format).\r\n\r\nInput Format\r\n\r\nThe first line contains an integer, , denoting the number of elements in the array. \r\nThe second line contains  space-separated integers describing the array's elements.\r\n\r\nConstraints\r\n\r\n, where  is the  element of the array.\r\nOutput Format\r\n\r\nPrint  lines of output in the following order:\r\n\r\nPrint the mean on a new line, to a scale of  decimal place (i.e., , ).\r\nPrint the median on a new line, to a scale of  decimal place (i.e., , ).\r\nPrint the mode on a new line; if more than one such value exists, print the numerically smallest one.\r\nSample Input\r\n\r\n10\r\n64630 11735 14216 99233 14470 4978 73429 38120 51135 67060\r\nSample Output\r\n\r\n43900.6\r\n44627.5\r\n4978\r\nExplanation\r\n\r\nMean: \r\nWe sum all  elements in the array, divide the sum by , and print our result on a new line.\r\n\r\nMedian: \r\nTo calculate the median, we need the elements of the array to be sorted in either non-increasing or non-decreasing order. The sorted array . We then average the two middle elements:\r\n\r\nand print our result on a new line.\r\nMode: \r\nWe can find the number of occurrences of all the elements in the array:\r\n\r\n 4978 : 1\r\n11735 : 1\r\n14216 : 1\r\n14470 : 1\r\n38120 : 1\r\n51135 : 1\r\n64630 : 1\r\n67060 : 1\r\n73429 : 1\r\n99233 : 1\r\nEvery number occurs once, making  the maximum number of occurrences for any number in . Because we have multiple values to choose from, we want to select the smallest one, , and print it on a new line.\r\n'''\r\n\r\n# Enter your code here. Read input from STDIN. Print output to STDOUT\r\nimport numpy as np\r\nfrom scipy import stats\r\n\r\nn = int(input())\r\nx = list(map(int, input().split()))\r\n\r\nx = np.array(x)\r\n\r\nprint(round(np.mean(x),1))\r\nprint(round(np.median(x),1))\r\nprint(int(stats.mode(x)[0]))", "meta": {"hexsha": "2bbd5b700f22ee9955c2cb900a590152e73289bf", "size": 2255, "ext": "py", "lang": "Python", "max_stars_repo_path": "10 Days of Statistics/Day 0/Mean-Median-Mode.py", "max_stars_repo_name": "falconcode16/pythonprogramming", "max_stars_repo_head_hexsha": "fc53a879be473ebceb1d7da061b0e8fc2a20706c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-11T14:15:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-12T09:57:29.000Z", "max_issues_repo_path": "10 Days of Statistics/Day 0/Mean-Median-Mode.py", "max_issues_repo_name": "falconcode16/pythonprogramming", "max_issues_repo_head_hexsha": "fc53a879be473ebceb1d7da061b0e8fc2a20706c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "10 Days of Statistics/Day 0/Mean-Median-Mode.py", "max_forks_repo_name": "falconcode16/pythonprogramming", "max_forks_repo_head_hexsha": "fc53a879be473ebceb1d7da061b0e8fc2a20706c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-10T02:13:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T02:13:42.000Z", "avg_line_length": 32.2142857143, "max_line_length": 202, "alphanum_fraction": 0.7228381375, "include": true, "reason": "import numpy,from scipy", "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.9314625098218848, "lm_q1q2_score": 0.8831703986041938}}
{"text": "# %% [markdown]\n# # Least squares\n# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/YoniChechik/AI_is_Math/blob/master/c_04a_curve_fitting/least_squares.ipynb)\n# ## Linear LS\n# Let's generate some noisy data\n# %%\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfigsize = (10, 10)\n\nnp.random.seed(123)\n\n# %%\nx_max = 10\nx_step = 0.01\nx = np.arange(0, x_max, x_step)\ny = 3 * x - 3\n\n# add noise to data\nstd = 1\ny = y + np.random.normal(scale=std, size=x.shape)\n\nplt.figure(figsize=figsize)\nplt.plot(x, y, \"*\")\nplt.title(\"noisy data\")\nplt.show()\n\n# %% [markdown]\n# ### calc LS matrices and result:\n# $$ Xb = y $$\n# %%\nx_vec = x.reshape(-1, 1)\nX = np.concatenate((x_vec, np.ones(x_vec.shape)), axis=1)\nprint(X.shape)\ny_vec = y.reshape(-1, 1)\n\n# %%\nb = np.linalg.inv(X.T @ X) @ X.T @ y_vec\nprint(b)\n\n# plot fit results\nplt.figure(figsize=figsize)\nplt.plot(x, y, \"*\")\nplt.plot(x, b[0] * x + b[1], \"r\")\nplt.title(\"noisy data + best LS fit. $b^T$=\" + str(b.T))\nplt.show()\n\n# %% [markdown]\n# ## Comparison to np.linalg.lstsq\n# %%\nb_np = np.linalg.lstsq(X, y_vec, rcond=None)[0]\nmse = np.mean((b - b_np) ** 2)\nprint(mse)\n# %% [markdown]\n# ## vertical dataset\n# As mentioned in the lecture, LS is not goog at fitting vertical dataset.\n# Let's generate data:\n# %%\ndata_sz = 100\nx = np.ones(data_sz)\ny = np.arange(data_sz)\n\n# add noise to data\nstd = 0.1\nx = x + np.random.normal(scale=std, size=x.shape)\n\nplt.figure(figsize=figsize)\nplt.plot(x, y, \"*\")\naxes = plt.gca()\naxes.set_xlim([-3, 3])\nplt.title(\"noisy vertical data\")\nplt.show()\n\n# %% [markdown]\n# Calc LS matrices and result\n# %%\nx_vec = x.reshape(-1, 1)\nX = np.concatenate((x_vec, np.ones(x_vec.shape)), axis=1)\ny_vec = y.reshape(-1, 1)\n\n# %%\nb = np.linalg.inv(X.T @ X) @ X.T @ y_vec\nprint(b)\n\n# plot fit results\nplt.figure(figsize=figsize)\nplt.plot(x, y, \"*\")\nx_axis = np.arange(3)\nplt.plot(x_axis, b[0] * x_axis + b[1], \"r\")\nplt.title(\"vertical data + best LS fit. $b^T$=\" + str(b.T))\nplt.show()\n\n\n# %% [markdown]\n# ## TLS\n# Same vertical data, now with total least squares\n# %%\nX = np.concatenate((x.reshape(-1, 1) - np.mean(x), y.reshape(-1, 1) - np.mean(y)), axis=1)\n\n\ndef linear_tls(X):\n    w, v = np.linalg.eig(X.T @ X)\n    return v[:, np.argmin(w)]\n\n\ntls_res = linear_tls(X)\n\na = tls_res[0]\nb = tls_res[1]\n\nc = -a * np.mean(x) - b * np.mean(y)\nx_fit = np.array([x.min(), x.max()])\ny_fit = -a / b * x_fit - c / b\n\nplt.figure(figsize=figsize)\nplt.plot(x, y, \"*\")\nplt.plot(x_fit, y_fit)\naxes = plt.gca()\naxes.set_xlim([-3, 3])\naxes.set_ylim([0, 100])\nplt.title(\"noisy vertical data + linear TLS fit\")\nplt.show()\n\n# %% [markdown]\n# ## Example for non linear LS\n# %%\nx_step = 0.01\nx = np.arange(-10, 10 + x_step, x_step)\n\ny = 0.5 * x ** 2 + 2 * x + 5\n\n# add noise to data\nstd = 5\ny = y + np.random.normal(scale=std, size=y.shape)\n\nplt.figure(figsize=figsize)\nplt.plot(x, y, \"*\")\nplt.title(\"noisy parabola data\")\nplt.show()\n\n# %%\n# calc LS matrices\nx_vec = x.reshape(-1, 1)\nX = np.concatenate((x_vec ** 2, x_vec, np.ones(x_vec.shape)), axis=1)\ny_vec = y.reshape(-1, 1)\n\nb = np.linalg.lstsq(X, y_vec, rcond=None)[0]\nprint(b)\n# %%\nplt.figure(figsize=figsize)\nplt.plot(x, y, \"*\")\nplt.plot(x, b[0] * x ** 2 + b[1] * x + b[2], \"r\")\nplt.title(\"data + best LS fit. $b^T$=\" + str(b.T))\nplt.show()\n\n# %% [markdown]\n# ## Outliers\n# As mentioned, LS has a problem with outliers:\n# %%\nx_max = 10\n\nx = np.arange(10)\ny = 4 * x + 2\n\n# let's change the last data point\ny[-1] -= 20\n\nplt.figure(figsize=figsize)\nplt.plot(x, y, \"*\")\nplt.title(\"data with outlier\")\nplt.show()\n\n# %%\n# calc LS matrices\nx_vec = x.reshape(-1, 1)\nX = np.concatenate((x_vec, np.ones(x_vec.shape)), axis=1)\ny_vec = y.reshape(-1, 1)\n\n# %%\nb = np.linalg.inv(X.T @ X) @ X.T @ y_vec\nprint(b)\n\n# plot fit results\nplt.figure(figsize=figsize)\nplt.plot(x, y, \"*\")\nx_axis = np.arange(x_max)\nplt.plot(x_axis, b[0] * x_axis + b[1], \"r\")\nplt.title(\"data with outlier + best LS fit. $b^T$=\" + str(b.T))\nplt.show()\n\n# %% [markdown]\n# ## RANSAC\n# ### arrange data\n# %%\n\nx = np.arange(0, 10, 0.1)\ny = 3 * x - 3\n\n# add noise to data\nstd = 1\ny = y + np.random.normal(scale=std, size=x.shape)\n\n# add random noise unrelated to noisy line\nnoise_sz = int(x.shape[0] * 1)\nx_noise = np.random.uniform(x.min(), x.max(), size=noise_sz)\ny_noise = np.random.uniform(y.min(), y.max(), size=noise_sz)\n\nplt.figure(figsize=figsize)\nplt.plot(x, y, \"*\")\nplt.plot(x_noise, y_noise, \"*\")\nplt.show()\n\n# %%\nx = np.concatenate((x, x_noise))\ny = np.concatenate((y, y_noise))\n\n# %% [markdown]\n# ### Run RANSAC\n# %%\n\n\ndef basic_ransac(x, TH):\n    # ====== choose 2 random inds\n    rand_indices = np.random.choice(x.shape[0], size=2)\n\n    # ====== build LS data:\n    x_vec = x[rand_indices].reshape(-1, 1)\n    X = np.concatenate((x_vec, np.ones(x_vec.shape)), axis=1)\n    y_vec = y[rand_indices].reshape(-1, 1)\n\n    b = np.linalg.lstsq(X, y_vec, rcond=None)[0].flatten()\n\n    # ====== build fitted line\n    line_p1 = np.array([x.min(), b[0] * x.min() + b[1]])\n    line_p2 = np.array([x.max(), b[0] * x.max() + b[1]])\n    inliers_ind = []\n\n    # ====== distance of fit line from each sample to determine inliers\n    for j in range(x.shape[0]):\n        p_j = np.array([x[j], y[j]])\n\n        # https://en.wikipedia.org/wiki/Cross_product#Geometric_meaning\n        # |a X b| = |a||b|sin(t) -> |a X b|/|b| = |a|sin(t)\n        d_j = np.linalg.norm(np.cross(line_p1 - p_j, line_p2 - line_p1)) / np.linalg.norm(line_p2 - line_p1)\n        if d_j <= TH:\n            inliers_ind.append(j)\n\n    inliers_ind = np.array(inliers_ind)\n    return b, inliers_ind\n\n\n# %%\nTH = 1\nnum_cycles = 10\n\nnum_best_inliers = 0\nbest_cycle_ind = -1\ninliers_ind_list = []\nb_list = []\n\nfor i in range(num_cycles):\n    b, inliers_ind = basic_ransac(x, TH)\n    inliers_ind_list.append(inliers_ind)\n    b_list.append(b)\n\n    # ====== save best model\n    if num_best_inliers < inliers_ind.shape[0]:\n        num_best_inliers = inliers_ind.shape[0]\n        best_cycle_ind = i\n# %%\n# plot best fit\nplt.rcParams[\"figure.figsize\"] = [20, 20]\n\nfor i in range(num_cycles):\n    plt.subplot(int(num_cycles / 2), 2, i + 1)\n    ax = plt.gca()\n    x_axis = np.arange(11)\n    ax.plot(x_axis, b_list[i][0] * x_axis + b_list[i][1], \"r\")\n    ax.plot(x, y, \"*\")\n    ax.plot(x[inliers_ind_list[i]], y[inliers_ind_list[i]], \"*k\")\n    ax.set_xlim([0, 10])\n    ax.set_ylim([0, 25])\n    if i == best_cycle_ind:\n        plt.title(\"!!! BEST FIT !!! num inliers: \" + str(inliers_ind_list[i].shape[0]))\n    else:\n        plt.title(\"num inliers: \" + str(inliers_ind_list[i].shape[0]))\nplt.show()\n\n# %% [markdown]\n# ### Test RANSAC with sklearn package (a known machine learning package in python)\n# Code taken from: https://scikit-learn.org/stable/auto_examples/linear_model/plot_ransac.html\n# %%\nfrom sklearn import linear_model\n\nX = x.reshape(-1, 1)\n\n\nlr = linear_model.LinearRegression()\nlr.fit(X, y)\n\n# Robustly fit linear model with RANSAC algorithm\nransac = linear_model.RANSACRegressor()\nransac.fit(X, y)\ninlier_mask = ransac.inlier_mask_\noutlier_mask = np.logical_not(inlier_mask)\n\n# Predict data of estimated models\nline_X = np.arange(X.min(), X.max())[:, np.newaxis]\nline_y = lr.predict(line_X)\nline_y_ransac = ransac.predict(line_X)\n\nplt.figure()\nplt.scatter(X[inlier_mask], y[inlier_mask], color=\"yellowgreen\", marker=\".\", label=\"Inliers\")\nplt.scatter(X[outlier_mask], y[outlier_mask], color=\"red\", marker=\".\", label=\"Outliers\")\nplt.plot(line_X, line_y, color=\"navy\", linewidth=2, label=\"Linear regressor\")\nplt.plot(line_X, line_y_ransac, color=\"cornflowerblue\", linewidth=2, label=\"RANSAC regressor\")\nplt.legend(loc=\"lower right\")\nplt.title(\"RANSAC using sklearn package\")\nplt.show()\n# %%\n", "meta": {"hexsha": "82cc9f6657b1fd0a224211bb6c29c570b22b10f5", "size": 7672, "ext": "py", "lang": "Python", "max_stars_repo_path": "c_04a_curve_fitting/least_squares.py", "max_stars_repo_name": "YoniChechik/test_site", "max_stars_repo_head_hexsha": "6e06de9629fefc4a0a005786ecde600c7462f124", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2019-08-28T17:13:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T03:36:07.000Z", "max_issues_repo_path": "c_04a_curve_fitting/least_squares.py", "max_issues_repo_name": "YoniChechik/test_site", "max_issues_repo_head_hexsha": "6e06de9629fefc4a0a005786ecde600c7462f124", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-03T19:40:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-03T19:43:02.000Z", "max_forks_repo_path": "c_04a_curve_fitting/least_squares.py", "max_forks_repo_name": "YoniChechik/test_site", "max_forks_repo_head_hexsha": "6e06de9629fefc4a0a005786ecde600c7462f124", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-12-16T01:09:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T22:39:53.000Z", "avg_line_length": 23.8260869565, "max_line_length": 195, "alphanum_fraction": 0.6317778936, "include": true, "reason": "import numpy", "num_tokens": 2507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924818279465, "lm_q2_score": 0.9086179055936797, "lm_q1q2_score": 0.8831697730913115}}
{"text": "import numpy as np\nimport numpy.linalg as la\n\nsmall_number= 1e-14 \n\ndef gram_schmidt_basis(A):\n\n    # set B as a copy of A, since its values are going to be altered\n    B = np.array(A, dtype=np.float_) \n\n    # looping over the vectors, starting with zero, label them with i\n    for i in range(B.shape[1]) :\n\n        # Inside the above loop, looping all previous j vectors to substract\n        for j in range(i):\n\n            # Substracting the overlap with previous vectors using the corresponding dot product\n            # current vector is B[:, i], previous vector is B[:, j]\n            B[:, i] = B[:,i] - B[:,i] @ B[:,j] * B[:,j]\n\n        # normalisation test for B[:, i]\n        if la.norm(B[:, i]) > small_number:\n            B[:, i] = B[:, i] / la.norm(B[:, i])  \n        else :\n            B[:, i] = np.zeros_like(B[:, i])      \n            \n    # returning the result\n    return B\n\n# using the Gram-schmidt process to calculate the dimension spanned by a list of vectors\n# the sum of all the norms will be the final number of dimensions (since each vector is normalized to 1 or 0)\ndef calc_dimensions(A):\n    return np.sum(la.norm(gram_schmidt_basis(A), axis=0))\n\n# test the function\nvector_v = np.array([[1,0,2,6],\n                    [0,1,8,2],\n                    [2,8,3,1],\n                    [1,-6,2,3]], dtype=np.float_)\n\ngram_schmidt_basis(vector_v)\n\n# find number of dimensions of \"vector_v\"\ncalc_dimensions(vector_v)", "meta": {"hexsha": "65ade89a4888c43ba20ad2ca9ef73029851d3a14", "size": 1435, "ext": "py", "lang": "Python", "max_stars_repo_path": "Maths - Statistics/Mathematics_for_ML/gram_schmidt.py", "max_stars_repo_name": "dimi-fn/Various-Data-Science-Scripts", "max_stars_repo_head_hexsha": "82ec30178ce4b7e2fedd9552e05cfc99e92ed52a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-04-02T18:50:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T13:23:03.000Z", "max_issues_repo_path": "Maths - Statistics/Mathematics_for_ML/gram_schmidt.py", "max_issues_repo_name": "dimi-fn/Various-Data-Science-Scripts", "max_issues_repo_head_hexsha": "82ec30178ce4b7e2fedd9552e05cfc99e92ed52a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-03T21:17:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-07T14:07:41.000Z", "max_forks_repo_path": "Maths - Statistics/Mathematics_for_ML/gram_schmidt.py", "max_forks_repo_name": "dimi-fn/Various-Data-Science-Scripts", "max_forks_repo_head_hexsha": "82ec30178ce4b7e2fedd9552e05cfc99e92ed52a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-07T12:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T10:34:02.000Z", "avg_line_length": 32.6136363636, "max_line_length": 109, "alphanum_fraction": 0.5944250871, "include": true, "reason": "import numpy", "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924793940119, "lm_q2_score": 0.9086179049750475, "lm_q1q2_score": 0.8831697702784891}}
{"text": "\"\"\"\nGeneral mathematical transformations and statistical methods.\n\n\"\"\"\n\nimport numpy as np\nfrom scipy.stats import zscore\n\n\ndef modified_zscore(x: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Modified z-score transformation.\n\n    The modified z score might be more robust than the standard z-score because\n    it relies on the median for calculating the z-score. It is less influenced\n    by outliers when compared to the standard z-score.\n\n    Parameters\n    ----------\n    x: (N,) np.ndarray\n        numbers\n\n    Returns\n    -------\n    z: (N,) np.ndarray\n        z-scored numbers computed using modified z-score\n\n    \"\"\"\n    med = np.median(x)\n    med_abs_dev = np.median(np.abs(x - med))\n    return (x - med) / (1.486 * med_abs_dev)\n\n\ndef find_outliers(scores: np.ndarray,\n                  threshold: float = 3.0,\n                  max_iter: int = 5,\n                  tail: int = 0) -> np.ndarray:\n    \"\"\"\n    Find outliers via iterated z-scoring.\n\n    This procedure compares absolute z-scores against the threshold.\n    After excluding outliers, the comparison is repeated until no\n    outliers are present.\n\n    Parameters\n    ----------\n    scores : (N,) np.ndarray\n        The scores for which to find outliers.\n    threshold : float, optional\n        The value above which a feature is classified as outlier.\n    max_iter : int, optional\n        The maximum number of iterations.\n    tail : one of {0, 1, -1}, optional\n        Whether to search for outliers on both extremes of the z-scores (0),\n        or on just the positive (1) or negative (-1) side.\n\n    Returns\n    -------\n    bad_idx : (M,) np.ndarray[int]\n        The indices of outliers found in `scores`.\n\n    Notes\n    -----\n    This code adapted from mne.preprocessing.bads._find_outliers\n\n    \"\"\"\n    bad_idx = list()\n    remaining_idx = list(range(len(scores)))\n\n    for _ in range(max_iter):\n        x = scores[remaining_idx]\n        if tail == 0:\n            this_z = np.abs(zscore(x))\n        elif tail == 1:\n            this_z = zscore(x)\n        elif tail == -1:\n            this_z = -zscore(x)\n        else:\n            raise ValueError(\"Tail parameter %s not recognised.\" % tail)\n\n        local_bad = this_z > threshold\n        if not np.any(local_bad):\n            break\n\n        ix_to_remove = [remaining_idx[i] for i in np.where(local_bad)[0]]\n        for ix in ix_to_remove:\n            bad_idx.append(ix)\n            remaining_idx.remove(ix)\n\n    return np.array(bad_idx, dtype=int)\n\n\ndef rms(x: np.ndarray) -> float:\n    \"\"\" Compute root-mean-square. \"\"\"\n    return np.sqrt(np.mean(np.power(x, 2)))\n\n\ndef logistic4(x: np.ndarray, a: float, b: float, c: float, d: float) -> np.ndarray:\n    \"\"\"\n    4PL logistic equation.\n\n    Parameters\n    ----------\n    x: (N,) np.ndarray\n        scalar array, eg logarithmic concentration of a drug\n    a: float\n        response as x -> 0\n    b: float\n        slope\n    c: float\n        inflection point, eg EC50\n    d: float\n        response as x -> inf\n\n    Returns\n    -------\n    (N,) np.ndarray\n        transformation of `x`\n\n    \"\"\"\n    return d + ((a - d) / (1.0 + ((-x / c) ** b)))\n", "meta": {"hexsha": "7d78ef787cbdf614d9d770185ddd486f9cd33d62", "size": 3110, "ext": "py", "lang": "Python", "max_stars_repo_path": "jburt/math.py", "max_stars_repo_name": "jbburt/jburt", "max_stars_repo_head_hexsha": "7745491214ef2b665ca8d1fc526bc802a36985ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jburt/math.py", "max_issues_repo_name": "jbburt/jburt", "max_issues_repo_head_hexsha": "7745491214ef2b665ca8d1fc526bc802a36985ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jburt/math.py", "max_forks_repo_name": "jbburt/jburt", "max_forks_repo_head_hexsha": "7745491214ef2b665ca8d1fc526bc802a36985ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4918032787, "max_line_length": 83, "alphanum_fraction": 0.5848874598, "include": true, "reason": "import numpy,from scipy", "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924818279465, "lm_q2_score": 0.9086178876533445, "lm_q1q2_score": 0.8831697556534406}}
{"text": "#!/usr/bin/env python\n\nfrom sympy import sieve\nimport time\n\n\ndef primality_test_simple(n):\n    \"\"\"素数判定（単純な実装）\"\"\"\n    \n    n = int(n)\n    if n < 2:\n        return False\n    elif n == 2:\n        return True\n    else:\n        for i in range(2, n, 1):\n            if n % i == 0:\n                return False\n    return True\n\ndef do_2(start, end, test_func=primality_test_simple):\n    \"\"\"素直な実装\"\"\"\n    print(\"\\n単純なforループ\")\n    #t1 = time.time()\n    start = int(start)\n    end = int(end)\n    prime_list = []\n    print(\"start ...\")\n    \n    for n in range(start, end+1, 1):\n        if test_func(n):\n            prime_list.append(n)\n\n    #print('prime number is ...')\n    #print(prime_list)\n    print(start, \"から\", end, \"に素数は\", len(prime_list), \"個ある\")\n    #print(\"time = \", time.time() - t1)\n    return prime_list\n\n\ndef primality_test_using_sieve(n):\n    \"\"\"素数判定（sieve使用）\n    \"\"\"\n    \n    n = int(n)\n    if n in sieve:\n        return True\n    else:\n        return False\n\n\ndef do_2_using_sieve(start, end):\n    \"\"\"sieve使用\"\"\"\n    \n    print(\"\\nsieve使用\")\n    #t1 = time.time()\n    start = int(start)\n    end = int(end)\n    print(\"start ...\")\n    \n    prime_list = [i for i in sieve.primerange(start, end+1)]\n\n    #print('prime number is ...')\n    #print(prime_list)\n    print(start, \"から\", end, \"に素数は\")\n    print(\"Total = \", len(prime_list), \"個ある\")\n    #print(\"time = \", time.time() - t1)\n    return prime_list\n\n\n\nif __name__ == '__main__':\n    start = time.time()\n    #print(primality_test_simple(999961))  # 100万以下で最大の素数\n    do_2(1, 100000)\n    #do_2_using_sieve(2, 100000)\n    print(\"実行時間 = \", time.time() - start, \" [秒]\\n\")\n", "meta": {"hexsha": "2ddecd01251adb0099b57c21b74ca01f446a30a5", "size": 1614, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercise_py/exercise_0.py", "max_stars_repo_name": "YoshimitsuMatsutaIe/ans_2021", "max_stars_repo_head_hexsha": "a04cd9b9541583aaa8a6dc5ece323ae1cf706c3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercise_py/exercise_0.py", "max_issues_repo_name": "YoshimitsuMatsutaIe/ans_2021", "max_issues_repo_head_hexsha": "a04cd9b9541583aaa8a6dc5ece323ae1cf706c3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise_py/exercise_0.py", "max_forks_repo_name": "YoshimitsuMatsutaIe/ans_2021", "max_forks_repo_head_hexsha": "a04cd9b9541583aaa8a6dc5ece323ae1cf706c3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6923076923, "max_line_length": 60, "alphanum_fraction": 0.5489467162, "include": true, "reason": "from sympy", "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122672782973, "lm_q2_score": 0.9219218364639713, "lm_q1q2_score": 0.8831202366205744}}
{"text": "import math\n\nfrom pathlib import Path\nfrom numpy import array\nimport numpy as np\n\nfrom manim import *\n\nANGLE_IN_DEGREES = -90\nangle = math.radians(ANGLE_IN_DEGREES)\n\nTRANSFORMATION_MATRIX = np.array([\n    [math.cos(angle), math.sin(angle)],\n    [-math.sin(angle), math.cos(angle)]\n])\n\nFONT_SIZE = 75\n\ndef convert_to_3d(vect):\n    return np.array([*list(vect), 0])\n\n\ndef get_transform_matrix_text(matrix_2d):\n    return MathTex(\n        f\"\\\\begin{{bmatrix}}{round(matrix_2d[0][0])} && {round(matrix_2d[0][1])} \\\\\\\\ {round(matrix_2d[1][0])} && {round(matrix_2d[1][1])}\\\\end{{bmatrix}}\", font_size=FONT_SIZE)\n\n\nclass TransformationMatrix(Scene):\n    def construct(self):\n        VECT1 = np.array([3, 2])\n        VECT1_COLOR = \"#b9b28b\"\n\n        TRANS_VEC = TRANSFORMATION_MATRIX @ VECT1\n        VECT2_COLOR = \"#b98b99\"\n\n        VECT3_COLOR = \"#8ba7b9\"\n\n        vect1 = Line(start=ORIGIN, end=convert_to_3d(VECT1), stroke_color=VECT1_COLOR).add_tip()\n\n        vect1_name = MathTex(r\"\\begin{bmatrix}a \\\\ b\\end{bmatrix}\").next_to(vect1.get_end(), UP + RIGHT * 2, buff=0.1).set_color(VECT1_COLOR)\n\n        trans_vect1 = Line(start=ORIGIN, end=convert_to_3d(TRANS_VEC), stroke_color=VECT1_COLOR, stroke_width=10).add_tip().set_color(VECT2_COLOR)\n\n        # self.camera.frame_center = np.array([0, 1, 0])\n\n        numberplane = NumberPlane(\n            background_line_style={\n                \"stroke_opacity\": 0.4\n            }\n        )\n\n        matrix_text = get_transform_matrix_text(TRANSFORMATION_MATRIX)\n        matrix_text.set_color(\"#222\")\n\n        vector_part = MathTex(f\"\\\\begin{{bmatrix}}{VECT1[0]} \\\\\\\\ {VECT1[1]}\\end{{bmatrix}}\", font_size=FONT_SIZE).set_color(VECT1_COLOR)\n        equals_part = MathTex(\" = \", font_size=FONT_SIZE).set_color(\"#222\")\n        trans_vect_part = MathTex(f'\\\\begin{{bmatrix}}{round(TRANS_VEC[0], 2)} \\\\\\\\ {round(TRANS_VEC[1], 2)}\\\\end{{bmatrix}}', font_size=FONT_SIZE).set_color(VECT2_COLOR)\n\n        group = VGroup(matrix_text, vector_part, equals_part, trans_vect_part).arrange()\n        group.move_to(ORIGIN)\n        group.shift(DOWN * 2)\n\n        self.add(vect1, trans_vect1, numberplane, group)\n\n\nif __name__ == '__main__':\n    # Generate animated gif.\n    config.background_color = WHITE\n\n    config.frame_height = 8\n    config.frame_width = 8\n\n    config.pixel_width = 300\n    config.pixel_height = 300\n\n    config.output_file = Path(__file__).resolve().parent.parent.parent / Path('notes/_media/transformation-matrix-cover')\n    config.save_last_frame = True\n\n    scene = TransformationMatrix()\n    scene.render()\n", "meta": {"hexsha": "5c031831ac6a768e770122a520fcddf5c2a53e58", "size": 2556, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/manim/transformation_matrix_cover.py", "max_stars_repo_name": "aav789/study-notes", "max_stars_repo_head_hexsha": "34eca00cd48869ba7a79c0ea7d8948ee9bde72b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 43, "max_stars_repo_stars_event_min_datetime": "2015-06-10T14:48:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-29T16:22:28.000Z", "max_issues_repo_path": "code/manim/transformation_matrix_cover.py", "max_issues_repo_name": "aav789/study-notes", "max_issues_repo_head_hexsha": "34eca00cd48869ba7a79c0ea7d8948ee9bde72b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-01T12:01:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-01T12:01:44.000Z", "max_forks_repo_path": "code/manim/transformation_matrix_cover.py", "max_forks_repo_name": "lextoumbourou/notes", "max_forks_repo_head_hexsha": "5f94c59a467eb3eb387542bdce398abc0365e6a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 40, "max_forks_repo_forks_event_min_datetime": "2015-03-02T10:33:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T12:17:05.000Z", "avg_line_length": 31.5555555556, "max_line_length": 177, "alphanum_fraction": 0.6658841941, "include": true, "reason": "import numpy,from numpy", "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731115849662, "lm_q2_score": 0.9173026641072386, "lm_q1q2_score": 0.8830626099212945}}
{"text": "import math\nfrom scipy.fftpack import fft, ifft\n\ndef conv(signal1, signal2):\n    \"\"\"Discrete convolution by definition\"\"\"\n\n    n = len(signal1) + len(signal2) - 1\n    out = []\n    \n    for i in range(n):\n        s = 0\n        \n        for j in range(i + 1):\n            if j < len(signal1) and i - j  < len(signal2):\n                s += signal1[j] * signal2[i - j]\n                \n        out.append(s)\n\n    return out\n\n\ndef conv_fft(signal1, signal2):\n    \"\"\"Convolution using fft and convolutional theorem\"\"\"\n\n    signal1 = signal1.copy()\n    signal2 = signal2.copy()\n\n    # pad signals to same len\n    max_len = max(len(signal1), len(signal2))\n    \n    for i in range(max_len - len(signal1)):\n        signal1.append(0)\n    for i in range(max_len - len(signal2)):\n        signal2.append(0)\n    \n    fft_s1 = fft(signal1)\n    fft_s2 = fft(signal2)\n    out = []\n\n    for i in range(len(signal1)):\n        out.append(fft_s1[i] * fft_s2[i])\n\n    return list(ifft(out))\n\n\ndef main():\n    # Example convolution with sin and cos\n    s1 = [math.sin(x) for x in range(5)]\n    s2 = [math.cos(x) for x in range(5)]\n\n    print(\"Discrete Convolution\")\n    print(conv(s1, s2))\n\n    print(\"FFT Convolution\")\n    print(conv_fft(s1, s2))\n\n\nif __name__ == \"__main__\":\n    main()\n\n", "meta": {"hexsha": "f8c8f48fcb2d3f82ef99f444733e5324a61af4cc", "size": 1266, "ext": "py", "lang": "Python", "max_stars_repo_path": "contents/convolutions/code/python/conv.py", "max_stars_repo_name": "atocil/algorithm-archive", "max_stars_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-30T09:58:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T12:49:47.000Z", "max_issues_repo_path": "contents/convolutions/code/python/conv.py", "max_issues_repo_name": "atocil/algorithm-archive", "max_issues_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-03T20:52:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-03T20:52:20.000Z", "max_forks_repo_path": "contents/convolutions/code/python/conv.py", "max_forks_repo_name": "atocil/algorithm-archive", "max_forks_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-17T09:17:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T09:17:56.000Z", "avg_line_length": 20.7540983607, "max_line_length": 58, "alphanum_fraction": 0.5663507109, "include": true, "reason": "from scipy", "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140616, "lm_q2_score": 0.9173026646724284, "lm_q1q2_score": 0.8830626094830438}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\n\r\n\r\ndef demo_simple():\r\n    # ref: http://mathworld.wolfram.com/HeartCurve.html\r\n    t = np.linspace(0, 2 * np.pi, 180)\r\n    x = 16 * np.sin(t) ** 3\r\n    y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)\r\n    plt.plot(x, y)\r\n    plt.show()\r\n\r\n\r\ndef demo_ani():\r\n    def update_line(num):\r\n        chart.set_data(data[..., :num])\r\n        return chart,\r\n\r\n    # ref: http://mathworld.wolfram.com/HeartCurve.html\r\n    t = np.linspace(0, 2 * np.pi, 180)\r\n    x = 16 * np.sin(t) ** 3\r\n    y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)\r\n    data = np.vstack((x, y))  # 2 x 180\r\n    fig = plt.figure()\r\n    padding = 1.1\r\n    plt.xlim(np.min(x) * padding, np.max(x) * padding)\r\n    plt.ylim(np.min(y) * padding, np.max(y) * padding)\r\n    chart, = plt.plot([], [], color=\"pink\", linewidth=5)\r\n    ani = animation.FuncAnimation(fig, update_line, interval=10, frames=x.size,\r\n                                  repeat=False)\r\n    # required ffmpeg\r\n    ani.save(\"ani_demo2.mp4\")\r\n    plt.show()\r\n\r\n\r\ndef demo1():\r\n    # heart\r\n    # t = np.linspace(0, 2 * np.pi, 180)\r\n    # x = 16 * np.sin(t) ** 3\r\n    # y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)\r\n\r\n    # butterfly: https://en.wikipedia.org/wiki/Butterfly_curve_(transcendental)\r\n    t = np.linspace(0, 5 * np.pi, 180 * 5)\r\n    x = np.sin(t) * (np.exp(np.cos(t)) - 2 * np.cos(4 * t) - np.sin(t / 12) ** 5)\r\n    y = np.cos(t) * (np.exp(np.cos(t)) - 2 * np.cos(4 * t) - np.sin(t / 12) ** 5)\r\n    plot_ani(x, y, lw=3, interval=10)\r\n\r\n\r\ndef plot_ani(x, y, color=\"green\", interval=20, lw=2):\r\n    def update_line(num):\r\n        chart.set_data(data[..., :num])\r\n        return chart,\r\n\r\n    # ref: http://mathworld.wolfram.com/HeartCurve.html\r\n    data = np.vstack((x, y))  # 2 x 180\r\n    fig = plt.figure()\r\n    padding = 1.1\r\n    plt.xlim(np.min(x) * padding, np.max(x) * padding)\r\n    plt.ylim(np.min(y) * padding, np.max(y) * padding)\r\n    chart, = plt.plot([], [], color=color, linewidth=lw)\r\n    ani = animation.FuncAnimation(fig, update_line, interval=interval, frames=x.size,\r\n                                  repeat=False)\r\n    # required ffmpeg\r\n    # ani.save(\"ani_demo2.mp4\")\r\n    plt.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n    # demo_simple()\r\n    # demo_ani()\r\n    demo1()\r\n", "meta": {"hexsha": "f182f4a4f303d2a1411eb6397c0c3d6f5cb5efab", "size": 2408, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/plot_ani.py", "max_stars_repo_name": "prasertcbs/matplotlib", "max_stars_repo_head_hexsha": "e38e5ee3360b7c18ea944b9dcfd8b6b4d4029568", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/plot_ani.py", "max_issues_repo_name": "prasertcbs/matplotlib", "max_issues_repo_head_hexsha": "e38e5ee3360b7c18ea944b9dcfd8b6b4d4029568", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plot_ani.py", "max_forks_repo_name": "prasertcbs/matplotlib", "max_forks_repo_head_hexsha": "e38e5ee3360b7c18ea944b9dcfd8b6b4d4029568", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9863013699, "max_line_length": 86, "alphanum_fraction": 0.5365448505, "include": true, "reason": "import numpy", "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750466836961, "lm_q2_score": 0.9263037308025663, "lm_q1q2_score": 0.8830222322240983}}
{"text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nimport numpy as np\n\n# Classfication losses\n\n\n## prepare the data\n\n# we simulate 3 class classification problem, our model retunrs from last layer this output\nnp_output1 = np.array([[0.5, 0.1, 0.4 ]], dtype=np.float32)\nnp_output2 = np.array([[0.1, 0.5, 0.3 ]], dtype=np.float32)\noutput1 = torch.from_numpy(np_output1)\noutput2 = torch.from_numpy(np_output2)\ntarget1 = 0\ntarget2 = 1 \nprint(f'output1={output1} target={target1}')\nprint(f'output1={output2} target={target2}')\n\n# but we know our target class, encoded as one hot encoding\nnp_target = np.array([[1, 0, 0 ]], dtype=np.float32)\ncls_target = torch.from_numpy(np_target)\n\n# L1 loss\nprint(\"L1\")\nloss = nn.L1Loss()\nloss_value = loss(output1, cls_target)\nprint(loss_value) # (|0.5-1| + |0.1-0| + |0.4-0|)/3 = (0.5+0.1+0.4)/3 = 1.0/3 = 0.333\n\n# for second wrong output the loss should be higher\nloss_value = loss(output2, cls_target)\nprint(loss_value) # (|0.1-1| + |0.5-0| + |0.3-0|)/3 = (0.9+0.5+0.3)/3 = 1.7/3 = 0.5667\n\n\n\n\n\n# CrossEntropy - This criterion combines nn.LogSoftmax() and nn.NLLLoss() in one single class.\n# It is useful when training a classification problem with C classes.\n\nprint(\"CrossEntropyLoss\")\nloss = nn.CrossEntropyLoss()\n\nclass_number =torch.tensor([target1], dtype=torch.long)\nloss_value = loss(output1, class_number)\nprint(loss_value) # =\n\nclass_number =torch.tensor([target2], dtype=torch.long)\nloss_value = loss(output2, class_number)\nprint(loss_value) # =\n\n\n# CrossEntropy for mini batch of size 2\nprint(\"CrossEntropyLoss - batch\")\nloss = nn.CrossEntropyLoss(reduction='none')\n# input = torch.randn(3, 5)\n# target = torch.empty(3, dtype=torch.long).random_(5)\n\n# now we have 3 output classes and 2 examples in mini-batch\n#batch_output = torch.stack([output1, output2])\nbatch_output = torch.cat([output1, output2])\n# target for each mini-batch exmaple, should be from [0,2] - \nbatch_target = torch.tensor( [target1, target2], dtype= torch.int64)\nloss_value = loss(batch_output, batch_target)\nprint(loss_value) # =\n\n\n# regression problem \n\n\n# we simulate 3 variable regression problem, our model returns from last layer this output\nnp_output1 = np.array([-0.9, 3.3, 4.5 ], dtype=np.float32)\nnp_output2 = np.array([5., -1, 3. ], dtype=np.float32)\n# but we know our target is\nnp_target = np.array([-1., 3., 4. ], dtype=np.float32)\n\n# make tensors\noutput1 = torch.from_numpy(np_output1)\noutput2 = torch.from_numpy(np_output2)\nreg_target = torch.from_numpy(np_target)\n\n\n# L2 loss - MSE - mean square error\nprint(\"MSE Loss\")\nprint(f'output1={output1}')\nprint(f'output2={output2}')\nprint(f'target={reg_target}')\n\n\nloss = nn.MSELoss()\nloss_value = loss(output1, reg_target)\nprint(f'loss(output1, target)={loss_value}') # ((-0.9- -1)^2 + (3.3-3)^2 + (4.5-4)^2)/3 = 0.1167\n\n# for second wrong output the loss should be higher\nloss_value = loss(output2, reg_target)\nprint(f'loss(output2, target)={loss_value}')  # = 17.666\n\nprint(\"MSEs - without reduction\")\nloss = nn.MSELoss(reduction='none')\nloss_value = loss(output1, reg_target)\nprint(f'loss(output1, target)={loss_value}') # [(-0.9- -1)^2 ,  (3.3-3)^2,  (4.5-4)^2 ] = [ 0.01, 0.09, 0.25]\n\n\n# Multi-label\n\n# BCE loss\n\n# we have batch_size=3 (one example in a row), multi label problem \n# this should be returned in the last layer of our model\n# data shouldbe numbers from [0,1]\nnp_output1 = np.array([[0.1, 0.9], [0.6, 0.8], [0.8, 1.]], dtype=np.float32)\nnp_output2 = np.array([[0.4, 0.5], [0.1, 0.9], [0.1, 0.9]], dtype=np.float32)\n# but we know our target is\nnp_target = np.array([[0., 1.],[1., 0.],[1., 1.]], dtype=np.float32)\n\n# make tensors\noutput1 = torch.from_numpy(np_output1)\noutput2 = torch.from_numpy(np_output2)\ntarget = torch.from_numpy(np_target)\n\n# Binary Cross Entropy\nprint(\"BCELoss\")\nprint(f'output1={output1}')\nprint(f'output2={output2}')\nprint(f'target={target}')\n\n\nloss = nn.BCELoss()\n\n# L= sum_i { l_i = -1*[ y_i * log(x_i) + (1-y_i)*log(1-x_i) ]}\nloss_value = loss(output1, target)\nprint(f'loss(output1, target)={loss_value}') # \n\n# for second wrong output the loss should be higher\nloss_value = loss(output2, target)\nprint(f'loss(output2, target)={loss_value}')  # = \n\nprint(\"BCELoss - without reduction\")\nloss = nn.BCELoss(reduction='none')\nloss_value = loss(output1, target)\nprint(f'loss(output1, target)={loss_value}') # =\n\nprint(\"BCELoss - reduction sum\")\nloss = nn.BCELoss(reduction='sum')\nloss_value = loss(output1, target)\nprint(f'loss(output1, target)={loss_value}') # =\n\nlst = []\nx = output1.numpy()\ny = target.numpy()\nfor i in range(len(x)):\n    lst.append(-np.log(x[i])*y[i] + -np.log(1-x[i])*(1-y[i]))\nprint(lst, np.mean(lst))", "meta": {"hexsha": "94b40da2ebc0f6bed2e3367390f607f45618715d", "size": 4682, "ext": "py", "lang": "Python", "max_stars_repo_path": "loss_functions.py", "max_stars_repo_name": "ksopyla/pytorch_tut", "max_stars_repo_head_hexsha": "3a6cd119d5d75214c34f8ea2ccfb0dc0d3c0afd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-07-09T09:49:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-09T09:49:40.000Z", "max_issues_repo_path": "loss_functions.py", "max_issues_repo_name": "ksopyla/pytorch_tut", "max_issues_repo_head_hexsha": "3a6cd119d5d75214c34f8ea2ccfb0dc0d3c0afd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "loss_functions.py", "max_forks_repo_name": "ksopyla/pytorch_tut", "max_forks_repo_head_hexsha": "3a6cd119d5d75214c34f8ea2ccfb0dc0d3c0afd7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0128205128, "max_line_length": 109, "alphanum_fraction": 0.6956428877, "include": true, "reason": "import numpy", "num_tokens": 1502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.9263037297853367, "lm_q1q2_score": 0.8830222287951602}}
{"text": "import math\nimport numpy as np\n\n\ndef euclidian_distance(first: \"List[float]\", second: \"List[float]\") -> float:\n    \"\"\"\n    Given two vectors, returns the euclidian distance between them\n    Requires that they are the same dimension\n\n    :param first: a vector\n    :param second: a vector\n\n    :return: the distance as a float\n    \"\"\"\n    if len(first) != len(second):\n        raise Exception(\"These vectors must be the same size\")\n    return math.sqrt(sum([pow(x - y, 2) for x, y in zip(first, second)]))\n\n\ndef minkowski_distance(\n    first: \"List[float]\", second: \"List[float]\", order: int\n) -> float:\n    \"\"\"\n    Given two vectors, returns the Minkowski distance between them\n    Requires that they are the same dimension\n\n    :param first: a vector\n    :param second: a vector\n    :param order: int\n\n    :return: the distance as a float\n    \"\"\"\n    if len(first) != len(second):\n        raise Exception(\"These vectors must be the same size\")\n    return pow(\n        sum([pow(np.abs(x - y), order) for x, y in zip(first, second)]), 1 / order\n    )\n\n\ndef manhatten_distance(first: \"List[float]\", second: \"List[float]\") -> float:\n    \"\"\"\n    Given two vectors, returns the manhatten distance between them\n    Requires that they are the same dimension\n\n    :param first: a vector\n    :param second: a vector\n\n    :return: the distance as a float\n    \"\"\"\n    if len(first) != len(second):\n        raise Exception(\"These vectors must be the same size\")\n\n    return sum([abs(x - y) for x, y in zip(first, second)])\n\n\ndef cosine_similarity(first: \"List[float]\", second: \"List[float]\") -> float:\n    \"\"\"\n    Given two vectors, returns the cosine similarity between them\n    Requires that they are the same dimension\n\n    :param first: a vector\n    :param second: a vector\n\n    :return: the similarity as a float\n    \"\"\"\n    if len(first) != len(second):\n        raise Exception(\"These vectors must be the same size\")\n    numerator = sum(x * y for x, y in zip(first, second))\n    denominator = math.sqrt(sum(pow(x, 2) for x in first)) * math.sqrt(\n        sum(pow(y, 2) for y in second)\n    )\n    if denominator == 0:\n        return 0\n    return numerator / denominator\n\n\ndef jaccard_similarity(first: \"Set[object]\", second: \"Set[object]\") -> float:\n    \"\"\"\n    Given two sets, returns the jaccard similarity between them\n\n    :param first: a set\n    :param second: a set\n\n    :return: the similarity as a float\n    \"\"\"\n    return len(first & second) / len(first | second)\n", "meta": {"hexsha": "441a625da7c38f4d7d131a5e808cfc9d596d8d42", "size": 2466, "ext": "py", "lang": "Python", "max_stars_repo_path": "pepperonai/unsupervised/distance.py", "max_stars_repo_name": "JonWiggins/pepperon.ai", "max_stars_repo_head_hexsha": "7162479dabb072cc125e707dc93785dff47dcb5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-09-30T03:41:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T22:18:17.000Z", "max_issues_repo_path": "pepperonai/unsupervised/distance.py", "max_issues_repo_name": "JonWiggins/pepperon.ai", "max_issues_repo_head_hexsha": "7162479dabb072cc125e707dc93785dff47dcb5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pepperonai/unsupervised/distance.py", "max_forks_repo_name": "JonWiggins/pepperon.ai", "max_forks_repo_head_hexsha": "7162479dabb072cc125e707dc93785dff47dcb5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-13T16:12:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-13T16:12:43.000Z", "avg_line_length": 28.3448275862, "max_line_length": 82, "alphanum_fraction": 0.6415247364, "include": true, "reason": "import numpy", "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357549000773, "lm_q2_score": 0.9019206811430764, "lm_q1q2_score": 0.8830125949229037}}
{"text": "#!/usr/bin/env python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy.linalg import inv\nfrom numpy.linalg import norm\nfrom math import isnan\n\n\ndef jacobian_1(x):\n    \"\"\"Jacobiano do sistema 5.7.2 da pagina 175 do livro \n    Numerical Methods in Economics, de Keneth Judd.\"\"\"\n    return np.array([[.2 * x[0] ** (-.8), .2 * x[1] ** (-.8)],\n                     [.1 * x[0] ** (-.9), .4 * x[1] ** (-.6)]])\n\n\ndef jacobian_2(x):\n    \"\"\"Jacobiano do sistema 5.7.3 da pagina 175 do livro \n    Numerical Methods in Economics, de Keneth Judd.\"\"\"\n    return np.array([[5. * (x[0] ** .2 + x[1] ** .2) ** 4. * .2 * x[0] ** (-.8),\n                      5. * (x[0] ** .2 + x[1] ** .2) ** 4. * .2 * x[1] ** (-.8)],\n                     [4. * (x[0] ** .1 + x[1] ** .4) ** 3. * .1 * x[0] ** (-.9),\n                      4. * (x[0] ** .1 + x[1] ** .4) ** 3. * .4 * x[1] ** (-.6)]])\n\n\ndef function_1(x):\n    \"\"\"Sistema 5.7.2 da pagina 175 do livro \n    Numerical Methods in Economics, de Keneth Judd.\"\"\"\n    return np.array([x[0] ** .2 + x[1] ** .2 - 2.,\n                     x[0] ** .1 + x[1] ** .4 - 2.])\n\n\ndef function_2(x):\n    \"\"\"Sistema 5.7.2 da pagina 175 do livro \n    Numerical Methods in Economics, de Keneth Judd.\"\"\"\n    return np.array([(x[0] ** .2 + x[1] ** .2) ** 5. - 32.,\n                     (x[0] ** .1 + x[1] ** .4) ** 4. - 16.])\n\n\ndef newton(function, jacobian, initial, e=0.00001, d=0.00001, print_iter=True,\n           plot_iter = False):\n    \"\"\"Funcao que aplica o metodo de Newton-Raphson a funcao 'function' com\n    jacobiano 'jacobian' inseridos como funcoes do Python. 'initial' e o ponto\n    inicial para as iteracoes. 'e' e o nivel de precisao desejado e d e a\n    precisao desejada em relacao ao resultado. 'print_iter' escolhe se quer\n    que imprima os pontos intermediarios das iteracoes e 'plot_iter' escolhe\n    se quer imprimir estes pontos num grafico.\"\"\"\n    x = initial\n    iter = 0\n    while True:\n        try:\n            if print_iter:\n                print(x)\n            if plot_iter:\n                plt.scatter(x[0], x[1])\n            s = np.dot(-inv(jacobian(x)), function(x)) # Equacao do metodo\n            x_ante = x\n            x = x + s\n            iter += 1\n            if norm(x_ante - x) <= e * (1 + norm(x)) or isnan(x[0]) or\\\n               isnan(x[1]): # Verifica criterio de convergencia\n                break\n        except:\n            print(\"Erro\")\n            break\n    if norm(function(x)) <= d: # Verifica se a solucao atende criterio\n        print(\"Convergiu em \" + str(iter) + \" iterações iniciando em \" +\\\n              str(np.round(initial, 2)))\n        return x\n    else:\n        print(\"Método não convergiu iniciando em \" + str(np.round(initial, 2)))\n\n# O loop abaixo roda o metodo no retangulo [0,2]**2 para function_1\nfor i in (np.array(range(20))+1.)/10:\n    for j in (np.array(range(20))+1.)/10:\n        newton(function_1, jacobian_1, [i, j], print_iter=False)\n\n# O loop abaixo roda o metodo no retangulo [0,2]**2 para function_2\nfor i in (np.array(range(20))+1.)/10:\n    for j in (np.array(range(20))+1.)/10:\n        newton(function_2, jacobian_2, [i, j], print_iter=False)\n\n###############################################################################\n# Note que os loops acima mostram que a transformacao da function_2 tornou    #\n# a convergencia mais rapida, exigindo em media uma iteracao a menos no       #\n# dominio testado                                                             #\n###############################################################################\n\n# O comando abaixo imprime um grafico com os pontos da iteracao da function_1\nnewton(function_1, jacobian_1, [2, 2], plot_iter=True)\n\n# O comando abaixo imprime um grafico com os pontos da iteracao da function_2\nnewton(function_2, jacobian_2, [2, 2], plot_iter=True)\n", "meta": {"hexsha": "7ac43d8d76d24181cc34848ee19d888ce89c4bfb", "size": 3814, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/depreciated/test-newton-auto.py", "max_stars_repo_name": "codinginbrazil/GA018", "max_stars_repo_head_hexsha": "714fcfca0144536ce17481793b100058fb07b928", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-24T12:52:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T12:52:12.000Z", "max_issues_repo_path": "src/depreciated/test-newton-auto.py", "max_issues_repo_name": "codinginbrazil/GA018", "max_issues_repo_head_hexsha": "714fcfca0144536ce17481793b100058fb07b928", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/depreciated/test-newton-auto.py", "max_forks_repo_name": "codinginbrazil/GA018", "max_forks_repo_head_hexsha": "714fcfca0144536ce17481793b100058fb07b928", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5744680851, "max_line_length": 82, "alphanum_fraction": 0.5301520713, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342049451596, "lm_q2_score": 0.9230391674796138, "lm_q1q2_score": 0.8830108401151023}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"aula_python_4.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/drive/10JwswxJwA6xL3sSl9tIH0HMp3-ZLC5gH\n\n# Revisão\n\ndef inicia a definição de uma função\n\"\"\"\n\n\ndef parabola(x, a, b, c):\n    y = a * x ** 2 + b * x + c\n    return y\n\n\nparabola(1, 5, 2, 4)\n\n\"\"\"Funções com argumentos com valor padrão:\"\"\"\n\n\ndef parabola_2(x, a=5, b=2, c=4):\n    y = a * x ** 2 + b * x + c\n    return y\n\n\nparabola_2(1, 6, 7, 8)\n\n\"\"\"Funções anônimas podem ser criadas com a palavra-chave lambda. As funções lambdas são restritas a uma única (em geral pequena) expressão. \"\"\"\n\nf2 = lambda x: x ** 2\n\nf2(5)\n\nf_soma = lambda a, b: a + b\nf_soma(5, 9)\n\n\"\"\"# Estrutura de dados\n\nVeja a seguir mais métodos de objetos do tipo lista:\n\"\"\"\n\nl = [5, 18, 43, 77, 91, 18, 77]\n\n\"\"\"Adicionar um elemento ao final da lista\"\"\"\n\nl.append(100)\nprint(l)\n\n\"\"\"Inserir um elemento em uma dada posição. Nesse caso insere o elemento 9 na posição de índice 1. \"\"\"\n\nl.insert(1, 9)\nprint(l)\n\n\"\"\"Remover o primeiro elemento da lista que tem valor igual ao argumento (nesse caso remove o elemento 18)\"\"\"\n\nl.remove(18)\nprint(l)\n\n\"\"\"Contar o número de vezes que um elemento aparece na lista\"\"\"\n\nl.count(77)\n\nprint(l)\n\n\"\"\"Remover o elemento em uma dada posição. Esse método remove o elemento e o retorna. \n\nNesse caso remove o elemento de índice 1.\n\"\"\"\n\nl.pop(1)\n\nprint(l)\n\n\"\"\"Devolver o índice do primeiro elemento cujo valor é igual ao argumento (nesse caso 91)\n\n\"\"\"\n\nl.index(91)\n\nl.index(77)\n\nl.index(53)\n\n\"\"\"Ordenar os elementos da lista\"\"\"\n\nprint(\"lista:\", l)\nl.sort()\nprint(\"lista ordenada:\", l)\n\n\"\"\"Ordenar em ordem reversa\"\"\"\n\nl = [5, 43, 77, 91, 18, 77, 100]  # definindo novamente a lista l\nl.sort(reverse=True)\nprint(l)\n\n\"\"\"Inverter a ordem dos elementos\"\"\"\n\nl = [5, 43, 77, 91, 18, 77, 100]  # definindo novamente a lista l\nl.reverse()\nprint(l)\n\n\"\"\"Copiar os elementos da lista\"\"\"\n\nl_c = l.copy()\nprint(l_c)\n\n\"\"\"Para iterar sobre uma lista, a posição e o valor podem ser obtidos simultaneamente com a função enumerate()\"\"\"\n\nfor i, v in enumerate(l_c):\n    print(i, v)\n\n\"\"\"Para percorrer duas ou mais listas ao mesmo tempo, as entradas podem ser pareadas com a função zip()\"\"\"\n\nl1 = [2.5, 3.9, 8.7]  # definindo lista l1\nl2 = [8.7, 23.4, 12.5]  # definindo lista l2\nfor a, b in zip(l1, l2):\n    print(a, b)\n\n\"\"\"Uma lista pode ser percorrida na ordem inversa com a função reversed()\"\"\"\n\nfor z in reversed(range(10)):\n    print(z)\n\n\"\"\"**Compreensões de listas**\n\nCompreensões de listas são uma maneira concisa de criar uma lista. Uma aplicação comum é criar uma nova lista onde cada elemento é resultante da avaliação de uma expressão no contexto das cláusulas for e if. \n\nPor exemplo, podemos criar uma lista com os quadrados desta forma:\n\n\"\"\"\n\nquadrados = []  # cria uma lista vazia e armazena na variável quadrados\nfor x in range(10):\n    quadrados.append(x ** 2)\n\nprint(quadrados)\n\n\"\"\"Alternativamente, podemos fazer:\"\"\"\n\nquadrados2 = [x ** 2 for x in range(10)]\nprint(quadrados2)\n\nquadrados3 = list(map(lambda x: x ** 2, range(10)))\nprint(quadrados3)\n\n\"\"\"**Tuplas**\n\nUma tupla consiste em uma sequência de valores separados por vírgulas. Na sua criação os valores de uma tupla podem ser envolvidos ou não por parênteses. Na saída do console tuplas são sempre envolvidas por parênteses. Apesar de serem similares às listas, as tuplas são frequentemente utilizadas em situações e com propósitos distintos. O principal motivo é que tuplas são imutáveis, enquanto listas são mutáveis. \n\"\"\"\n\nt = 5, 87, 'bla'\nprint(t)\n\n\"\"\"Tuplas podem ser indexadas\n\n\"\"\"\n\nprint(t[2])\n\n\"\"\"É possível criar uma tupla contendo outras tuplas\n\n\"\"\"\n\nu = t, (56, 89, 346)\nprint(u[0][0])\n\n\"\"\"Tuplas são **imutáveis**!\"\"\"\n\nt[0] = 65\n\nv = (27.6, 45.9)  # 'empacotamento' de dois valores em uma tupla\nvx, vy = v  # processo inverso de 'desempacotamento' também é possível\nprint(vx)\n\n\"\"\"\n**Dicionários** \n\nUma estrutura de dados muito útil é o dicionário. Eles são indexados por palavras-chaves (keys), que podem ser de qualquer tipo imutável. Os dicionários são delimitados por {} e contém uma lista de pares chave:valor separados por vírgulas. O dicionário vazio é {}. Os dicionários são utilizados para armazenar e recuperar valores a partir das palavras-chaves. É possivel substituir uma valor de uma chave por um novo valor. \"\"\"\n\nramais = {'Cristina': 6473, 'Ana': 6486, 'Marina': 7256, 'Allan': 7257, 'Gustavo': 7257}\nprint(ramais['Marina'])\n\n\"\"\"Remover um par chave:valor\"\"\"\n\ndel (ramais['Allan'])\nprint(ramais)\n\n\"\"\"Incluir novo par chave:valor\"\"\"\n\nramais['Charles'] = 6486\nprint(ramais)\n\n\"\"\"Alterar o valor de uma chave\"\"\"\n\nramais['Cristina'] = 6478\nprint(ramais)\n\n\"\"\"Listar todas as chaves presentes no dicionário \"\"\"\n\nlist(ramais)\n\n\"\"\"Verificar se uma palavra-chave está ou não no dicionário\"\"\"\n\n'Cristina' in ramais\n\n'Sandra' in ramais\n\n\"\"\"O construtor dict cria um dicionário a partir de sequências de pares chave,valor\"\"\"\n\ndict([('Cristina', 6473), ('Ana', 6486), ('Marina', 7256)])\n\ndict(Allan=7257, Charles=6486)\n\n\"\"\"As compreensões de dicionário também podem ser usadas para criar dicionários a partir de expressões\"\"\"\n\ndici = {x: x ** 2 for x in range(10)}\nprint(dici)\n\n\"\"\"Ao iterar sobre dicionários, a chave e o valor podem ser obtidos simultaneamente usando o método items()\"\"\"\n\nfor nome, fone in ramais.items():\n    print(nome, fone)\n\n\"\"\"# Módulos\n\nUma boa prática ao escrever códigos maiores é dividí-lo em arquivos menores, o que pode facilitar a manutenção. \n\nUm módulo é um arquivo contendo definições e instruções Python. O nome do arquivo é o nome do módulo acrescido do sufixo .py.\n\nUm módulo também pode ser muito útil para escrever funções que são usadas em vários programas diferentes. É preferível usar um arquivo separado para uma função do que copiá-la para dentro de vários programas. \n\nPor exemplo, usando um editor de texto, foi criado um arquivo chamado fibonacci.py, contendo as funções fib e fib_lista, apresentadas na última aula. Ao importar um módulo, as funções definidas no arquivo são colocadas diretamente na tabelas de símbolos atual e poderão ser chamadas e executadas.\n\"\"\"\n\nimport fibonacci\n\nfibonacci.fib(20)\n\nfibonacci.fib_lista(50)\n\n\"\"\"Módulos podem importar outros módulos. É costume colocar todos os comandos de import no início do módulo ou de um programa. \n\nOutras maneiras de importar as definições de um módulo são:\n\"\"\"\n\nfrom fibonacci import fib, fib_lista\n\nfrom fibonacci import *\n# Importa todos os nomes definidos em um módulo\n# Nem sempre aconselhado, pois introduz um conjunto desconhecido de nomes no ambiente,\n# podendo levar a conflitos com outros nomes previamente definidos\n\nimport fibonacci as fibo\n\nfibo.fib(10)\n\nfrom fibonacci import fib_lista as f_l\n\nf_l(30)\n\n\"\"\"O Python guarda versões compiladas de cada módulo no diretório \\__ pycache__ com o nome modulo.versão.pyc para acelerar o carregamento de módulos.\n\n# Pacotes\n\nOs pacotes são uma maneira de estruturar o “espaço de nomes” (namespace) dos módulos Python. Eles são uma coleção de módulos. Nos referimos a um módulo dentro de um pacote como nomedopacote.nomedomodulo. \n\nOs arquivos \\__ init__.py são necessários para que o Python trate diretórios contendo o arquivo como pacotes. \\__ init__.py pode ser apenas um arquivo vazio.\n\nO pacote **math** contém todas as funções matemáticas padrão (sqrt,log, log10, exp, funções trigonométricas).\n\"\"\"\n\nfrom math import log\n\nx = log(3)\nprint(x)\n\nfrom math import pi\n\nprint(pi)\n\nfrom math import exp\nfrom math import sin, cos\n\nfrom math import *\n\n# Algoritmo para converter a posição de um ponto dada em coordenadas polares (r,theta) para coordenadas\n# Cartesianas (x,y)\n\nfrom math import sin, cos, pi\n\nr = float(input('Entre o valor de r: '))\nd = float(input('Entre o valor de theta em graus: '))\n\ntheta = d * pi / 180.  # conversão de graus para radianos\nx = r * cos(theta)\ny = r * sin(theta)\n\nprint('x=', x, 'y=', y)\n\n\"\"\"O pacote **numpy** é fundamental para computação científica com Python. Ele oferece funções matemáticas, geradores de números aleatórios, rotinas de álgebra linear, transformada de Fourier e muito mais. Mas o seu poder está em permitir cálculos em arrays multidimensionais. \n\nO numpy executa facilmente cálculos numéricos que são muito utilizados em problemas de machine learning (aprendizado de máquina) e de processamento de imagem (imagens no computador são representadas como arrays multidimensionais de números). Além disso, o numpy oferece várias outras tarefas matemáticas.\n\nPara mais informações, consulte https://numpy.org/.\n\n# Arrays\n\nUm array é um conjunto ordenado de valores. Mas há diferenças importantes entre listas e arrays:\n* O número de elementos de um array é fixo e não é possível adicionar ou remover elementos de um array após criá-lo;\n* Os elementos de um array devem ser todos de um mesmo tipo, como float ou inteiros.\n\nAs principais vantagens de usar arrays em vez de listas são:\n* Arrays podem ter qualquer número de dimensões. Arrays unidimensionais e bidimensionais são, respectivamente, como vetores e matrizes em álgebra linear. Listas são sempre unidimensionais. \n* Como se comportam como vetores ou matrizes, podemos fazer qualquer aritmética com eles, ao contrário de listas.\n* Arrays funcionam mais rápido que listas em Python.\n\nCada dimensão de um array é chamada axis. O número de axes é chamada de rank do array. A indexação dos arrays também começa em 0, com um número para cada axis do array.\n\"\"\"\n\nfrom numpy import array\n\na = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n\nprint(a)\n\n# Minha recomendação\nimport numpy as np\n\na = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n\nprint(a)\n\ntype(a)  # checar que o tipo é um numpy array\n\na.dtype  # fornece o tipo dos elementos do array\n\na.shape  # dimensões do array\n\na.ndim  # número de dimensões\n\na.size  # número de elementos\n\n\"\"\"Indexação de um array: o índice da linha vem primeiro e depois o da coluna\"\"\"\n\nprint(a)\n\nprint(a[2, 1])\n\na[1, 0:2]\n\n\"\"\"Iterando sobre um array\n\n\"\"\"\n\nb = np.array([0, 2, 5, 8], dtype=int)\nprint(b)\n\nfor z in b:\n    print(z)\n\nfor i in range(len(b)):\n    print(b[i])\n\n\"\"\"Outras formas de criar arrays\n\n\"\"\"\n\na0 = np.zeros(5)\nprint(a0)\n\na0_2 = np.zeros([3, 4])\nprint(a0_2)\n\na1 = np.ones(7)\nprint(a1)\n\na1_2 = np.ones([2, 3])\nprint(a1_2)\n\na1_3 = np.ones([2, 3, 4])\nprint(a1_3)\n\n\"\"\"A função arange retorna valores espaçados igualmente em um certo intervalo. \nO espaçamento é definido pelo passo (terceiro argumento da função).\n\nnumpy.arange(início,fim,passo)\n\"\"\"\n\na2 = np.arange(1., 4., 0.5)\nprint(a2)\n\n\"\"\"A função linspace também retorna n valores espaçados igualmente em um certo intervalo. \n\nnumpy.linspace(início,fim,n) \n\"\"\"\n\na3 = np.linspace(1., 10., 3)\nprint(a3)\n\n\"\"\"É possível criar arrays com números aleatórios (entre 0 e 1)\n\n\"\"\"\n\na5 = np.random.rand(3, 4, 2)\nprint(a5)\n\n\"\"\"**Operações com arrays**\n\nO poder do numpy vem da possibilidade de realizar operações com arrays.\n\"\"\"\n\nc = np.array([1, 2])\nd = np.array([3, 4])\n\nprint(c + d)\n\nprint(c * d)\n\nprint(c ** d)\n\ne = a1_2 + 6.5\nprint(e)\n\n# Produto escalar de dois array é feito pela função dot\nprod_esc = np.dot(c, d)\nprint(prod_esc)\n\nlog10_c = np.log10(a5)\nprint(log10_c)\nprint(log10_c[1, 0, 0])\n\n\"\"\"Cuidado ao fazer cópias de arrays\"\"\"\n\na = np.array([1, 1])\nb = a\na[0] = 2\nprint(a)\nprint(b)\n\na = np.array([1, 1])\nb = np.copy(a)\na[0] = 2\nprint(a)\nprint(b)", "meta": {"hexsha": "80cea74cc3f43e75c123b53a7784d66cf8ad5545", "size": 11329, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ark.MetCompA/Aula-py3/aula3.py", "max_stars_repo_name": "Artur-UF/MetCompA", "max_stars_repo_head_hexsha": "1198f861f4e5190f7435314bf476c594471e79fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ark.MetCompA/Aula-py3/aula3.py", "max_issues_repo_name": "Artur-UF/MetCompA", "max_issues_repo_head_hexsha": "1198f861f4e5190f7435314bf476c594471e79fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ark.MetCompA/Aula-py3/aula3.py", "max_forks_repo_name": "Artur-UF/MetCompA", "max_forks_repo_head_hexsha": "1198f861f4e5190f7435314bf476c594471e79fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2879464286, "max_line_length": 427, "alphanum_fraction": 0.717362521, "include": true, "reason": "import numpy,from numpy", "num_tokens": 3493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.9343951602572964, "lm_q1q2_score": 0.8829984879823084}}
{"text": "import numpy as np\r\nimport time\r\nimport pandas as pd\r\n\r\n\r\ndef main():\r\n    # initi conditions---------------------------------------------------------\r\n    A=2\r\n    B=0.01\r\n    t0=0.0\r\n    t_end=5\r\n    #--------------------------------------------------------------------------\r\n\r\n    # Analytic solution\r\n    analytic = lambda t_ini, y_ini, t, a, b: 1/(b/a+(1/y_ini-b/a)*np.exp(-a*(t-t_ini)))\r\n    #--------------------------------------------------------------------------\r\n    # ODE\r\n    f = lambda y: A*y-B*y*y\r\n    #--------------------------------------------------------------------------\r\n    # initial valuse\r\n    y0_list = np.array([8, 10, 12])\r\n    #y0_list = np.array([100, 190, 250])\r\n    #--------------------------------------------------------------------------\r\n\r\n    timesteps = np.array([0.05, 0.025, 0.0125, 0.00625, 0.003125])\r\n\r\n    # maps of 6th order for different time steps (A=2, B=0.01)\r\n    # M(0,:) is map for dt=0.05     (N=100)\r\n    # M(1,:) is map for dt=0.025    (N=200)\r\n    # M(2,:) is map for dt=0.0125   (N=400)\r\n    # M(3,:) is map for dt=0.00625  (N=800)\r\n    # M(4,:) is map for dt=0.003125 (N=1600)\r\n    Maps = np.array([[-2.20674242163663e-17,7.2859273622565e-14,-1.57090670168903e-10,3.0491292885473e-7,-0.000581078444935817,1.10516564125989,0.000148534476733103],\r\n                    [-8.20209311569985e-19,4.34779284638878e-15,-1.76489909946068e-11,6.90754305025356e-8,-0.000269497671189628,1.05127100148724,2.69139400711076e-6],\r\n                    [-2.79644218719739e-20,2.60080775407912e-16,-2.07823660780399e-12,1.6426765170331e-8,-0.000129779855270288,1.02531511893295,4.53070556313535e-8],\r\n                    [-9.12880385587037e-22,1.57930196254673e-17,-2.51879120712609e-13,4.00518610053792e-9,-6.3683344531535e-5,1.01257845151487,7.34983595234415e-10],\r\n                    [-2.91577138323977e-23,9.70954867859659e-19,-3.09980538706333e-14,9.88849311608068e-10,-3.15443976782067e-5,1.00626957200335,1.16379709756459e-11]\r\n                    ])\r\n\r\n    #--------------------------------------------------------------------------\r\n    # resulting table\r\n    # result(:, 0) is N\r\n    # result(:, 1) is err_RK4\r\n    # result(:, 2) is err_TM6\r\n    # result(:, 3) is time_RK4\r\n    # result(:, 4) is time_TM6\r\n    # result(:, 5) is time_ratio = time_RK4/time_TM6\r\n    result = np.zeros((len(timesteps), 6))\r\n\r\n\r\n    for k, dt in enumerate(timesteps):  # for each time stemp dt\r\n        M = Maps[k, :]                 # get TM for this dt\r\n        N = int((t_end-t0)/dt)\r\n        t = np.arange(t0, t_end, dt)\r\n\r\n        result[k, 0] = N\r\n\r\n        for y0 in y0_list: # for each y0\r\n            # analytic solution------------------------------------------------\r\n            y_sol = analytic(t0, y0, t, A, B)\r\n            #------------------------------------------------------------------\r\n\r\n            # RK4 integration--------------------------------------------------\r\n            y_rk4 = np.zeros(N)\r\n\r\n            y_rk4[0]=y0\r\n            tic = time.time()\r\n            for i in range(N-1):\r\n                y = y_rk4[i]\r\n                k1 = f(y)\r\n                k2 = f(y+dt*k1/2)\r\n                k3 = f(y+dt*k2/2)\r\n                k4 = f(y+dt*k3)\r\n                y_rk4[i+1] = y + dt*(k1+2*k2+2*k3+k4)/6\r\n\r\n            elapsed_time = time.time()-tic\r\n            result[k, 3] += elapsed_time # time_RK4\r\n            #------------------------------------------------------------------\r\n\r\n            # Mapping----------------------------------------------------------\r\n            y_map = np.zeros(N)\r\n            y_map[0] = y0\r\n            tic = time.time()\r\n            for i in range(N-1):\r\n                y=y_map[i]\r\n                y2 = y*y\r\n                y3 = y2*y\r\n                y_map[i+1] = (y3*(M[0]*y3 + M[3]) +\r\n                            y2*(M[1]*y3 + M[4]) +\r\n                            y *(M[2]*y3 + M[5]) +\r\n                            M[6])\r\n\r\n            elapsed_time = time.time()-tic\r\n            result[k, 4] += elapsed_time # time_RK4\r\n            #------------------------------------------------------------------\r\n            result[k, 1] += np.abs(y_rk4 - y_sol).max() # err_RK4\r\n            result[k, 2] += np.abs(y_map - y_sol).max() # err_TM6\r\n\r\n    result[:, 1:] /= len(y0_list) # get average results\r\n    result[:, 5] = result[:, 3]/result[:, 4] # get time_ratio\r\n\r\n\r\n    result = pd.DataFrame(data=result[:,1:], index=result[:,0], columns=np.array(['err_RK4', 'err_TM6', 'time_RK4', 'time_TM6', 'time_ratio']))\r\n    return result\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    print(main())", "meta": {"hexsha": "38935621457c29db2f11a51bc62ef6d9e02fa08b", "size": 4577, "ext": "py", "lang": "Python", "max_stars_repo_path": "TM6.py", "max_stars_repo_name": "andiva/PopulationEquation", "max_stars_repo_head_hexsha": "3d6b4edc4ae72f3664214d7776278edf733690ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TM6.py", "max_issues_repo_name": "andiva/PopulationEquation", "max_issues_repo_head_hexsha": "3d6b4edc4ae72f3664214d7776278edf733690ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TM6.py", "max_forks_repo_name": "andiva/PopulationEquation", "max_forks_repo_head_hexsha": "3d6b4edc4ae72f3664214d7776278edf733690ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3796296296, "max_line_length": 167, "alphanum_fraction": 0.4199257155, "include": true, "reason": "import numpy", "num_tokens": 1372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104914476339, "lm_q2_score": 0.9136765198878883, "lm_q1q2_score": 0.8829865746090181}}
{"text": "import numpy as np\nfrom math import sqrt\n\ndef cubic_spline_interpolation(x0, x, y):\n\nx = np.asfarray(x)\ny = np.asfarray(y)\nsize = len(x)\nxdiff = np.diff(x)\nydiff = np.diff(y)\nLi = np.empty(size)\nLi_1 = np.empty(size-1)\nz = np.empty(size)\nLi[0] = sqrt(2*xdiff[0])\nLi_1[0] = 0\nB0 = 0\nz[0] = B0 / Li[0]\n\nfor i in range(1, size-1, 1):\nLi_1[i] = xdiff[i-1] / Li[i-1]\nLi[i] = sqrt(2*(xdiff[i-1]+xdiff[i]) - Li_1[i-1] * Li_1[i-1])\nBi = 6*(ydiff[i]/xdiff[i] - ydiff[i-1]/xdiff[i-1])\nz[i] = (Bi - Li_1[i-1]*z[i-1])/Li[i]\ni = size - 1\nLi_1[i-1] = xdiff[-1] / Li[i-1]\nLi[i] = sqrt(2*xdiff[-1] - Li_1[i-1] * Li_1[i-1])\nBi = 0\nz[i] = (Bi - Li_1[i-1]*z[i-1])/Li[i]\ni = size-1\nz[i] = z[i] / Li[i]\n\nfor i in range(size-2, -1, -1):\nz[i] = (z[i] - Li_1[i-1]*z[i+1])/Li[i]\nindex = x.searchsorted(x0)\nnp.clip(index, 1, size-1, index)\nxi1, xi0 = x[index], x[index-1]\nyi1, yi0 = y[index], y[index-1]\nzi1, zi0 = z[index], z[index-1]\nhi1 = xi1 - xi0\nf0 = zi0/(6*hi1)*(xi1-x0)**3 + \\\nzi1/(6*hi1)*(x0-xi0)**3 + \\\n(yi1/hi1 - zi1*hi1/6)*(x0-xi0) + \\\n(yi0/hi1 - zi0*hi1/6)*(xi1-x0)\nreturn f0\n\nif __name__ == '__main__':\nimport matplotlib.pyplot as plt\nx = np.linspace(0.9, 13.3, num=21)\ny = np.array([1.3, 1.5, 1.85, 2.1, 2.6, 2.7, 2.4, 2.15, 2.05, 2.1, 2.25, 2.3, 2.25, 1.95,\n1.4, 0.9, 0.7, 0.6, 0.5, 0.4, 0.25])\nplt.scatter(x, y, color = 'red')\nx_new = np.linspace(0.9, 13.3, num=50)\nplt.plot(x_new, cubic_spline_interpolation(x_new, x, y), 'k--')\nplt.ylim(-1,5)\nplt.title('Cubic Spline Interpolation')\nplt.xlabel('x')\nplt.ylabel('f(x)')\nplt.ylim(-1,5)\nplt.show()\n", "meta": {"hexsha": "ddf4e4acf5c55f47476e0a791c053e2183de0e56", "size": 1537, "ext": "py", "lang": "Python", "max_stars_repo_path": "cubic_spline_interpolation.py", "max_stars_repo_name": "orujmusa/cubic_spline_interpolation", "max_stars_repo_head_hexsha": "638be23c9348112f05c62f5950fa7c0f3e575744", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cubic_spline_interpolation.py", "max_issues_repo_name": "orujmusa/cubic_spline_interpolation", "max_issues_repo_head_hexsha": "638be23c9348112f05c62f5950fa7c0f3e575744", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cubic_spline_interpolation.py", "max_forks_repo_name": "orujmusa/cubic_spline_interpolation", "max_forks_repo_head_hexsha": "638be23c9348112f05c62f5950fa7c0f3e575744", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6166666667, "max_line_length": 89, "alphanum_fraction": 0.5797007157, "include": true, "reason": "import numpy", "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9835969684454967, "lm_q2_score": 0.8976952845805989, "lm_q1q2_score": 0.8829703605012945}}
{"text": "import numpy as np\nimport numpy.linalg as la\n\nverySmallNumber = 1e-14 # 1×10⁻¹⁴ = 0.00000000000001\n\n\ndef gsBasis4(A) :\n    B = np.array(A, dtype=np.float_)\n    B[:, 0] = B[:, 0] / la.norm(B[:, 0])\n    B[:, 1] = B[:, 1] - B[:, 1] @ B[:, 0] * B[:, 0]\n    if la.norm(B[:, 1]) > verySmallNumber :\n        B[:, 1] = B[:, 1] / la.norm(B[:, 1])\n    else :\n        B[:, 1] = np.zeros_like(B[:, 1])\n    B[:, 2] = B[:, 2] - B[:, 2] @ B[:, 0] * B[:, 0]\n    B[:, 2] = B[:, 2] - B[:, 2] @ B[:, 1] * B[:, 1]\n    if la.norm(B[:, 2]) > verySmallNumber :\n        B[:, 2] = B[:, 2] / la.norm(B[:, 2])\n    else :\n        B[:, 2] = np.zeros_like(B[:, 2])\n    B[:, 3] = B[:, 3] - B[:, 3] @ B[:, 0] * B[:, 0]\n    B[:, 3] = B[:, 3] - B[:, 3] @ B[:, 1] * B[:, 1]\n    B[:, 3] = B[:, 3] - B[:, 3] @ B[:, 2] * B[:, 2]\n    if la.norm(B[:, 3]) > verySmallNumber :\n        B[:, 3] = B[:, 3] / la.norm(B[:, 3])\n    else :\n        B[:, 3] = np.zeros_like(B[:, 3])\n    return B\n\ndef gsBasis(A) :\n    B = np.array(A, dtype=np.float_)\n    for i in range(B.shape[1]) :\n        for j in range(i) :\n            B[:, i] = B[:,i] - B[:,i] @ B[:,j] * B[:,j]\n        if la.norm(B[:, i]) > verySmallNumber :\n            B[:, i] = B[:, i] / la.norm(B[:, i])\n        else :\n            B[:, i] = np.zeros_like(B[:, i])\n    return B\n\ndef dimensions(A) :\n    return np.sum(la.norm(gsBasis(A), axis=0))\n\n\n# Tests\n\nV = np.array([[1,0,2,6],\n              [0,1,8,2],\n              [2,8,3,1],\n              [1,-6,2,3]], dtype=np.float_)\ngsBasis4(V)\n\nU = gsBasis4(V)\ngsBasis4(U)\n\ngsBasis(V)\n\nA = np.array([[3,2,3],\n              [2,5,-1],\n              [2,4,8],\n              [12,2,1]], dtype=np.float_)\ngsBasis(A)\n\ndimensions(A)\n\nB = np.array([[6,2,1,7,5],\n              [2,8,5,-4,1],\n              [1,-6,3,2,8]], dtype=np.float_)\ngsBasis(B)\n\ndimensions(B)\n\nC = np.array([[1,0,2],\n              [0,1,-3],\n              [1,0,2]], dtype=np.float_)\ngsBasis(C)\n\ndimensions(C)", "meta": {"hexsha": "faede7c830561e58b24bc39478ea9ba3a30e285a", "size": 1919, "ext": "py", "lang": "Python", "max_stars_repo_path": "gram-schmidt.py", "max_stars_repo_name": "ecdedios/gram-schmidt", "max_stars_repo_head_hexsha": "482e572f5f40d99bb67dd9120514370024f57111", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-23T18:52:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-23T18:52:46.000Z", "max_issues_repo_path": "gram-schmidt.py", "max_issues_repo_name": "ecdedios/gram-schmidt", "max_issues_repo_head_hexsha": "482e572f5f40d99bb67dd9120514370024f57111", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gram-schmidt.py", "max_forks_repo_name": "ecdedios/gram-schmidt", "max_forks_repo_head_hexsha": "482e572f5f40d99bb67dd9120514370024f57111", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6025641026, "max_line_length": 55, "alphanum_fraction": 0.4038561751, "include": true, "reason": "import numpy", "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9820137931962462, "lm_q2_score": 0.8991213738910259, "lm_q1q2_score": 0.8829495909185466}}
{"text": "###_________________________ Lotka-Volterra Model __________________________###\n###                         Prey - Predator Model                           ###\n# Las ecuaciones de Lotka-Volterra son un modelo biomatemático que pretende responder \n# a estas cuestiones prediciendo la dinámica de las poblaciones de presa y depredador \n# bajo una serie de hipótesis:\n    # * El ecosistema está aislado: no hay migración, no hay otras especies presentes, \n    #   no hay plagas...\n    # * La población de presas en ausencia de depredadores crece de manera exponencial: \n    #   la velocidad de reproducción es proporcional al número de individuos. \n    #   Las presas sólo mueren cuando son cazadas por el depredador.\n    # * La población de depredadores en ausencia de presas decrece de manera exponencial.\n    # * La población de depredadores afecta a la de presas haciéndola decrecer de \n    #   forma proporcional al número de presas y depredadores (esto es como decir \n    #   de forma proporcional al número de posibles encuentros entre presa y depredador).\n    # * La población de presas afecta a la de depredadores también de manera \n    #   proporcional al número de encuentros, pero con distinta constante de \n    #   proporcionalidad (dependerá de cuanto sacien su hambre los depredadores \n    #   al encontrar una presa).\n\n# Se trata de un sistema de dos ecuaciones diferenciales de primer orden, acopladas, \n# autónomas y no lineales:\n    \n    # $$ \\frac{dx}{dt} = \\alpha x - \\beta x y $$\n    # $$ \\frac{dy}{dt} = -\\gamma y + \\delta y x $$\n    \n# donde x es el número de presas e y es el número de depredadores. \n# Los parámetros son constantes positivas que representan:\n    # * $\\alpha$: tasa de crecimiento de las presas.\n    # * $\\beta$: éxito en la caza del depredador.\n    # * $\\gamma$: tasa de decrecimiento de los depredadores.\n    # * $\\delta$: éxito en la caza y cuánto alimenta cazar una presa al depredador.\n#_____________________________________________________________________________#\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import odeint\n\n# System of 1st order ODEs \ndef df_dt(x, t, a, b, c, d):\n    \n    dx = a * x[0] - b * x[0] * x[1]\n    dy = - c * x[1] + d * x[0] * x[1]\n    \n    return np.array([dx, dy])\n\n# Parameters\na = 0.1\nb = 0.02\nc = 0.3\nd = 0.01\n\n# Initial Conditions\nx0 = 40\ny0 = 9\nconds_iniciales = np.array([x0, y0])\n\n# Conditions for integration\ntf = 200\nN = 800\nt = np.linspace(0, tf, N)\n\n# Solve the equation\nsolucion = odeint(df_dt, conds_iniciales, t, args=(a, b, c, d))\n\n# Plot population in terms of time\nplt.style.use('seaborn-talk')\n\nplt.figure(\"Temporal Evolution\", figsize=(8,5))\nplt.title(\"Temporal Evolution\")\nplt.plot(t, solucion[:, 0], label='Prey')\nplt.plot(t, solucion[:, 1], label='Predator')\nplt.xlabel('Time')\nplt.ylabel('Population')\nplt.grid()\nplt.legend()\nplt.show()\n\n# Plot Prey pop. in terms of Predator pop.\nplt.figure(\"Preys vs Predators\", figsize=(8,5))\nplt.plot(solucion[:, 0], solucion[:, 1], 'r')\nplt.xlabel('Prey')\nplt.ylabel('Predator')\nplt.grid()\nplt.show()\n\n# Plot phase map and direction field\n\n# Podemos pintar el campo de direcciones de nuestras ecuaciones usando la función \n# quiver. El tamaño de las flechas se ha normalizado para que todas tengan la misma \n# longitud y se ha usado un colormap para representar el módulo.\nx_max = np.max(solucion[:,0]) * 1.05\ny_max = np.max(solucion[:,1]) * 1.05\n\nx = np.linspace(0, x_max, 25)\ny = np.linspace(0, y_max, 25)\n\nxx, yy = np.meshgrid(x, y)\nuu, vv = df_dt((xx, yy), 0, a, b, c, d)\nnorm = np.sqrt(uu**2 + vv**2)\nuu = uu / norm\nvv = vv / norm\n\nplt.figure(\"Direction field\", figsize=(8,5))\nplt.quiver(xx, yy, uu, vv, norm, cmap=plt.cm.gray)\nplt.plot(solucion[:, 0], solucion[:, 1], 'r')\nplt.xlim(0, x_max)\nplt.ylim(0, y_max)\nplt.xlabel('Preys')\nplt.ylabel('Predators')\nplt.grid()\nplt.show()\n\n# Plot direction field + Pop vs time\nn_max = np.max(solucion) * 1.10\n\nfig, ax = plt.subplots(1,2)\n\nfig.set_size_inches(12,5)\n\nax[0].quiver(xx, yy, uu, vv, norm, cmap=plt.cm.gray)\nax[0].plot(solucion[:, 0], solucion[:, 1], lw=2, alpha=0.8)\nax[0].set_xlim(0, x_max)\nax[0].set_ylim(0, y_max)\nax[0].set_xlabel('Preys')\nax[0].set_ylabel('Predators')\n\nax[1].plot(t, solucion[:, 0], label='Preys')\nax[1].plot(t, solucion[:, 1], label='Predators')\nax[1].legend()\nax[1].set_xlabel('Time')\nax[1].set_ylabel('Population')\nplt.show()\n\n##_______________________ Effect of initial conditions ______________________##\n# Se puede demostrar que a lo largo de las líneas del mapa de fases, como la que \n# hemos pintado antes, se conserva la cantidad:\n    # $$ C = \\alpha \\ln{y} - \\beta y + \\gamma \\ln{x} -\\delta x $$\n# Por tanto, pintando un `contour` de esta cantidad podemos obtener la solución \n# para distintos valores iniciales del problema.\n\ndef C(x, y, a, b, c, d):\n    return a * np.log(y) - b * y + c * np.log(x) - d * x\n\nx = np.linspace(0, x_max, 100)\ny = np.linspace(0, y_max, 100)\nxx, yy = np.meshgrid(x, y)\nconstant = C(xx, yy, a, b, c, d)\n\nplt.figure('Various solutions', figsize=(8,5))\nplt.contour(xx, yy, constant, 50, cmap=plt.cm.Blues)\nplt.xlabel('Preys')\nplt.ylabel('Predators')\nplt.grid()\nplt.show()\n\n# Vemos que estas curvas se van haciendo cada vez más y más pequeñas, hasta que, \n# en nuestro caso, colapsarían en un punto en torno a $(30,5)$. Se trata de un \n# punto de equilibrio o punto crítico; si el sistema lo alcanzase, no evolucionaría \n# y el número de cebras y leones sería constante en el tiempo. El otro punto crítico \n# de nuestro sistema es el $(0,0)$. Analizándolos matemáticamente se obtiene que:\n\n# El punto crítico situado en $(0,0)$ es un punto de silla. Al tratarse de un punto \n# de equilibrio inestable la extinción de cualquiera de las dos especies en el \n# modelo sólo puede conseguirse imponiendo la condición inicial nula.\n\n# El punto crítico situado en $(gamma/delta,alpha/beta)$ es un centro (en este \n# caso los autovalores de la matriz del sistema linealizado son ambos imaginarios\n# puros, por lo que a priori no se conoce su estabilidad).\n\nfig, ax = plt.subplots(1,2)\n\nfig.set_size_inches(12,5)\n\nax[0].plot(solucion[:, 0], solucion[:, 1], lw=2, alpha=0.8)\nax[0].scatter(c/d, a/b)\nlevels = (0.5, 0.6, 0.7, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.775, 0.78, 0.781)\nax[0].contour(xx, yy, constant, levels, colors='blue', alpha=0.3)\nax[0].set_xlim(0, x_max)\nax[0].set_ylim(0, y_max)\nax[0].set_xlabel('presas')\nax[0].set_ylabel('depredadores')\n\nax[1].plot(t, solucion[:, 0], label='presa')\nax[1].plot(t, solucion[:, 1], label='depredador')\nax[1].legend()\nax[1].set_xlabel('tiempo')\nax[1].set_ylabel('población')\nplt.show()\n\n##___________________________ Improving the model ___________________________##\n# Como se puede observar, este modelo tiene algunas deficiencias propias de su \n# simplicidad y derivadas de las hipótesis bajo las que se ha formulado. Una \n# modificación razonable es cambiar el modelo de crecimiento de las presas en \n# ausencia de depredadores, suponiendo que en vez de aumentar de forma exponencial, \n# lo hacen según una [función logística](http://es.wikipedia.org/wiki/Funci%C3%B3n_log%C3%ADstica). \n# Esta curva crece de forma similar a una exponencial al principio, moderándose\n# después y estabilizándose asintóticamente en un valor:\n\ndef logistic_curve(t, a=1, m=0, n=1, tau=1):\n    e = np.exp(-t / tau)\n    return a * (1 + m * e) / (1 + n * e) \n\nx_ = np.linspace(0,10)\nplt.figure('función logística', figsize=(8,5))\nplt.plot(x_, logistic_curve(x_, 1, m=10, n=100, tau=1))\nplt.grid()\nplt.plot()\n\n# Podemos observar como esta curva crece de forma similar a una exponencial al \n# principio, moderándose después y estabilizándose asintóticamente en un valor. \n# Este modelo de crecimiento representa mejor las limitaciones en el número de \n# presas debidas al medio (falta de alimento, territorio...). Llevando este modelo \n# de crecimiento a las ecuaciones originales se tiene un nuevo sistema en el que \n# interviene un parámetro más:\n    # $$ \\frac{dx}{dt} = (\\alpha x - r x^2) - \\beta x y $$\n    # $$ \\frac{dy}{dt} = -\\gamma y + \\delta y x $$\n\ndef df_dt_logistic(x, t, a, b, c, d, r):\n    \n    dx = a * x[0] - r * x[0]**2 - b * x[0] * x[1]\n    dy = - c * x[1] + d * x[0] * x[1]\n    \n    return np.array([dx, dy])\n\n# Parámetros\na = 0.1\nb = 0.02\nc = 0.3\nd = 0.01\nr = 0.001\n\n# Condiciones iniciales\nx0 = 40\ny0 = 9\nconds_iniciales = np.array([x0, y0])\n\n# Condiciones para integración\ntf = 200\nN = 800\nt = np.linspace(0, tf, N)\n\n# Solution\nsolucion_logistic = odeint(df_dt_logistic, conds_iniciales, t, args=(a, b, c, d, r))\n\nn_max = np.max(solucion) * 1.10\n\nfig, ax = plt.subplots(1,2)\n\nfig.set_size_inches(12,5)\n\nx_max = np.max(solucion_logistic[:,0]) * 1.05\ny_max = np.max(solucion_logistic[:,1]) * 1.05\n\nx = np.linspace(0, x_max, 25)\ny = np.linspace(0, y_max, 25)\n\nxx, yy = np.meshgrid(x, y)\nuu, vv = df_dt_logistic((xx, yy), 0, a, b, c, d, r)\nnorm = np.sqrt(uu**2 + vv**2)\nuu = uu / norm\nvv = vv / norm\n\nax[0].quiver(xx, yy, uu, vv, norm, cmap=plt.cm.gray)\nax[0].plot(solucion_logistic[:, 0], solucion_logistic[:, 1], lw=2, alpha=0.8)\nax[0].set_xlim(0, x_max)\nax[0].set_ylim(0, y_max)\nax[0].set_xlabel('presas')\nax[0].set_ylabel('depredadores')\n\nax[1].plot(t, solucion_logistic[:, 0], label='presa')\nax[1].plot(t, solucion_logistic[:, 1], label='depredador')\nax[1].legend()\nax[1].set_xlabel('tiempo')\nax[1].set_ylabel('población')\nplt.grid()\nplt.show()\n\n# En este caso se puede observar como el comportamiento deja de ser periódico. \n# El punto crítico que antes era un centro, se convierte en un atractor y la \n# solución tiende a estabilizarse en un número fijo de presas y depredadores.\n", "meta": {"hexsha": "2ebb713004d081d6f0f059395982d921a06e6882", "size": 9600, "ext": "py", "lang": "Python", "max_stars_repo_path": "MyScripts/091-Examples-Lotka-Volterra.py", "max_stars_repo_name": "diegoomataix/Curso_AeroPython", "max_stars_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MyScripts/091-Examples-Lotka-Volterra.py", "max_issues_repo_name": "diegoomataix/Curso_AeroPython", "max_issues_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MyScripts/091-Examples-Lotka-Volterra.py", "max_forks_repo_name": "diegoomataix/Curso_AeroPython", "max_forks_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2857142857, "max_line_length": 100, "alphanum_fraction": 0.6857291667, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399060540358, "lm_q2_score": 0.9099070121457543, "lm_q1q2_score": 0.8828280939822051}}
{"text": "\"\"\"\nThe prime module makes available several functions for prime operations.\nIncluded are prime tests, prime lists, and prime factorization.\n\"\"\"\n\ndef isprime(n):\n    \"\"\"Returns True if n is prime. O(sqrt(n))\"\"\"\n    if n < 2:\n        return False\n    if n == 2 or n == 3:\n        return True\n    if n % 2 == 0 or n % 3 == 0:\n        return False\n    i = 5\n    w = 2\n    while i * i <= n:\n        if n % i == 0:\n            return False\n        i += w\n        w = 6 - w\n    return True\n\ndef primes_up_to(n):\n    \"\"\"\n    Return a numpy.ndarray of bools of all primes <= n.\n    Uses Sieve of Eratosthenes, O(n log log n).\n    \"\"\"\n    import numpy as np\n    if n < 2:\n        return np.zeros(n+1, dtype=bool)\n\n    A = np.ones(n+1, dtype=bool)\n    A[0] = A[1] = False\n    for i in range(2, int(np.sqrt(n))+1):\n        if A[i]:\n            for j in range(i**2, n+1, i):\n                A[j] = False\n    return np.where(A)[0]\n\ndef primes_dict(n):\n    \"\"\"\n    Return a dictionary with the prime factorization of n.\n    Format of (key, value) is (prime, multiplicity)\n    \"\"\"\n    primfac = {}\n    d = 2\n    while d*d <= n:\n        while n % d == 0:\n            if d in primfac:\n                primfac[d] += 1\n            else:\n                primfac[d] = 1\n            n /= d\n        d += 1\n    if n > 1:\n        primfac[n] = 1\n    return primfac\n\ndef primes_list(n):\n    \"Return a list with the prime factorization of n.\"\n    primfac = []\n    d = 2\n    while d*d <= n:\n        while n % d == 0:\n            primfac.append(d)\n            n /= d\n        d += 1\n    if n > 1:\n        primfac.append(n)\n    return primfac\n\ndef prime_stream():\n    \"An indefinite stream of primes, starting from 2. O(n log log n).\"\n    import itertools\n    yield from (2, 3, 5, 7)\n    D = {}\n    ps = prime_stream()\n    next(ps)\n    p = next(ps)\n    assert p == 3\n    psq = p*p\n    for i in itertools.count(9, 2):\n        if i in D:      # composite\n            step = D.pop(i)\n        elif i < psq:   # prime\n            yield i\n            continue\n        else:           # composite, = p*p\n            assert i == psq\n            step = 2*p\n            p = next(ps)\n            psq = p*p\n        i += step\n        while i in D:\n            i += step\n        D[i] = step\n", "meta": {"hexsha": "4f2139c6d556d5188d86d3f33616b0bc4d56b3ae", "size": 2245, "ext": "py", "lang": "Python", "max_stars_repo_path": "projecteuler/prime.py", "max_stars_repo_name": "bsamseth/project-euler", "max_stars_repo_head_hexsha": "60d70b117960f37411935bc18eab5bb2fca220e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projecteuler/prime.py", "max_issues_repo_name": "bsamseth/project-euler", "max_issues_repo_head_hexsha": "60d70b117960f37411935bc18eab5bb2fca220e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projecteuler/prime.py", "max_forks_repo_name": "bsamseth/project-euler", "max_forks_repo_head_hexsha": "60d70b117960f37411935bc18eab5bb2fca220e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1443298969, "max_line_length": 72, "alphanum_fraction": 0.4699331849, "include": true, "reason": "import numpy", "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347860767305, "lm_q2_score": 0.905989819748845, "lm_q1q2_score": 0.8828279961946613}}
{"text": "import plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport numpy as np\nfrom scipy.fftpack import fft, ifft, fftfreq\n\n\n# Changing K plot\n# Create figure\nfig_k = make_subplots(\n    rows=1, cols=2,\n    shared_xaxes=False,\n    horizontal_spacing=0.02,\n    specs=[[{'type': 'scatter3d'}, {'type': 'scatter3d'}]])\n\n\n# Add traces, one for each slider step\nk= np.linspace(-10, 10, 21)\nphi_0 = 0\nsig = 0.5\nx=np.arange(-20, 20.01, 0.01)\n\nfor k_i in np.arange(-10, 11, 1):\n    psi = np.multiply(np.exp(1j*k_i*x), np.sqrt(np.exp(-np.power(x-phi_0, 2)/(2*sig**2))/(sig*np.sqrt(2*np.pi))))\n    fig_k.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"black\", width=2),\n            name=\"wavefunction\",\n            x=x,\n            y=np.imag(psi), \n            z=np.real(psi),\n            mode=\"lines\"), row=1, col=1)\n    fig_k.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"red\", width=1),\n            name=\"real part\",\n            x=x,\n            y=-2*np.ones(psi.shape),\n            z=np.real(psi),  \n            mode=\"lines\"), row=1, col=1)\n    fig_k.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"orange\", width=1),\n            name=\"imaginary part\",\n            x= x,\n            y= np.imag(psi), \n            z= -2*np.ones(psi.shape), \n            mode=\"lines\"), row=1, col=1)\n    fig_k.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"black\", width=1),\n            name=\"imaginary part\",\n            x= x,\n            y= -2*np.ones(psi.shape), \n            z= np.abs(psi), \n            mode=\"lines\"), row=1, col=1)\n\nfor k_i in np.arange(-10, 11, 1):\n    psi_fft = fft(np.multiply(np.exp(1j*k_i*x), np.sqrt(np.exp(-np.power(x-phi_0, 2)/(2*sig**2))/(sig*np.sqrt(2*np.pi)))))\n    xf = fftfreq(len(x), x[1] - x[0])\n    fig_k.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"black\", width=2),\n            name=\"wavefunction\",\n            x=np.concatenate((xf[len(xf)//2+1:], [xf[0]], xf[1:len(xf)//2])),\n            y=np.imag(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))), \n            z=np.real(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))),\n            mode=\"lines\"), row=1, col=2)\n    fig_k.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"red\", width=1),\n            name=\"real part\",\n            #x=xf,\n            x=np.concatenate((xf[len(xf)//2+1:], [xf[0]], xf[1:len(xf)//2])),\n            y=-10*np.ones(psi_fft.shape),\n            #z=np.real(psi_fft),\n            z=np.real(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))),  \n            mode=\"lines\"), row=1, col=2)\n    fig_k.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"orange\", width=1),\n            name=\"imaginary part\",\n            x=np.concatenate((xf[len(xf)//2+1:], [xf[0]], xf[1:len(xf)//2])),\n            #x= xf,\n            #y= np.imag(psi_fft), \n            y=np.imag(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))),\n            z= -200*np.ones(psi_fft.shape), \n            mode=\"lines\"), row=1, col=2)\n    fig_k.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"black\", width=1),\n            name=\"imaginary part\",\n            x=np.concatenate((xf[len(xf)//2+1:], [xf[0]], xf[1:len(xf)//2])),\n            #x= xf,\n            y= -10*np.ones(psi_fft.shape), \n            z= np.abs(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))), \n            mode=\"lines\"), row=1, col=2)\n\nfig_k.data[40].visible = True\nfig_k.data[41].visible = True\nfig_k.data[42].visible = True\nfig_k.data[43].visible = True\n\nfig_k.data[(len(fig_k.data))//2+40].visible = True\nfig_k.data[(len(fig_k.data))//2+41].visible = True\nfig_k.data[(len(fig_k.data))//2+42].visible = True\nfig_k.data[(len(fig_k.data))//2+43].visible = True\n\n# Create and add slider\nsteps = []\nfor i in range(0, (len(fig_k.data))//2, 4):\n    step = dict(\n        method=\"update\",\n        args=[{\"visible\": [False] * len(fig_k.data)}],  # layout attribute\n        label=str(k[i//4])\n    )\n    step[\"args\"][0][\"visible\"][i] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][i+1] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][i+2] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][i+3] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][(len(fig_k.data))//2+i] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][(len(fig_k.data))//2+i+1] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][(len(fig_k.data))//2+i+2] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][(len(fig_k.data))//2+i+3] = True  # Toggle i'th trace to \"visible\"\n    #step[\"args\"][0][\"visible\"][-1] = True \n    #step[\"args\"][0][\"visible\"][-2] = True \n    steps.append(step)\n\nsliders = [dict(\n    active=10,\n    currentvalue={\"prefix\": \"Wave number: \"},\n    pad={\"t\": 33},\n    steps=steps\n)]\n\nfig_k.update_layout(\n    sliders=sliders\n)\n\nfig_k.update_layout(\n    scene = dict(\n        xaxis = dict(nticks=10, range=[-5,5],),\n        yaxis = dict(nticks=4, range=[-2,2],),\n        zaxis = dict(nticks=4, range=[-2,2],),\n        xaxis_title='Phi',\n        yaxis_title='Imaginary', \n        zaxis_title='Real',))\n    #width=1000,\n    #margin=dict(r=20, l=10, b=10, t=10))\nfig_k.update_layout(\n    scene2 = dict(\n        xaxis = dict(nticks=10, range=[-3, 3]),\n        yaxis = dict(nticks=4, range=[-10,10]),\n        zaxis = dict(nticks=4, range=[-200, 200]),\n        xaxis_title='Q',\n        yaxis_title='Imaginary', \n        zaxis_title='Real',))\nfig_k.update_layout(scene_aspectmode='manual',\n                  scene_aspectratio=dict(x=2, y=1, z=1), \n                  scene2_aspectmode='manual',\n                  scene2_aspectratio=dict(x=2, y=1, z=1), \n                  showlegend=False,\n                  margin=dict(l=10, r=10, t=5, b=5), \n                  scene_camera=dict(eye=dict(x=1, y=2.4, z=0.4)),\n                  scene2_camera=dict(eye=dict(x=1, y=2.4, z=0.4)))\n\nfig_k.show(config = {'displayModeBar': False, 'displaylogo': False, 'scrollZoom': False})\nfig_k.write_html(\"wavefunction_changing_k_with_fft.html\", config={'displayModeBar': False, 'displaylogo': False, 'scrollZoom': False})\n\n# Changing sig plot\n# Create figure\nfig_sig = make_subplots(\n    rows=1, cols=2,\n    shared_xaxes=True,\n    horizontal_spacing=0.02,\n    specs=[[{'type': 'scatter3d'}, {'type': 'scatter3d'}]])\n\n# Add traces, one for each slider step\nk = 3\nsig_arr = np.logspace(-0.8, 0.5, 4)\nphi_0 = 0\nsig = 1\nx=np.arange(-20, 20.01, 0.01)\n\nfor sig_i in sig_arr:\n    psi = np.multiply(np.exp(1j*k*x), np.sqrt(np.exp(-np.power(x-phi_0, 2)/(2*sig_i**2))/(sig_i*np.sqrt(2*np.pi))))\n    fig_sig.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"black\", width=2),\n            name=\"wavefunction\",\n            x=x,\n            y=np.imag(psi),\n            z=np.real(psi), \n            mode=\"lines\"), row=1, col=1)\n    fig_sig.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"red\", width=1),\n            name=\"real part\",\n            x=x,\n            y=-2*np.ones(psi.shape),\n            z=np.real(psi),  \n            mode=\"lines\"), row=1, col=1)\n    fig_sig.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"orange\", width=1),\n            name=\"imaginary part\",\n            x= x,\n            y= np.imag(psi), \n            z= -2*np.ones(psi.shape), \n            mode=\"lines\"), row=1, col=1)\n    fig_sig.add_trace(\n        go.Scatter3d(\n            visible=False, \n            x=x, \n            y= -2*np.ones(psi.shape), \n            z=np.abs(psi), \n            name=\"prob amplitude\", mode=\"lines\", line=dict(color='black', width=2)), row=1, col=1)\n\nfor sig_i in sig_arr:\n    psi_fft = fft(np.multiply(np.exp(1j*k*x), np.sqrt(np.exp(-np.power(x-phi_0, 2)/(2*sig_i**2))/(sig_i*np.sqrt(2*np.pi)))))\n    xf = fftfreq(len(x), x[1] - x[0])\n    fig_sig.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"black\", width=2),\n            name=\"wavefunction\",\n            x=np.concatenate((xf[len(xf)//2+1:], [xf[0]], xf[1:len(xf)//2])),\n            y=np.imag(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))),\n            z=np.real(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))), \n            mode=\"lines\"), row=1, col=2)\n    fig_sig.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"red\", width=1),\n            name=\"real part\",\n            x=np.concatenate((xf[len(xf)//2+1:], [xf[0]], xf[1:len(xf)//2])),\n            y=-9*np.ones(psi_fft.shape),\n            z=np.real(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))),  \n            mode=\"lines\"), row=1, col=2)\n    fig_sig.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"orange\", width=1),\n            name=\"imaginary part\",\n            x= np.concatenate((xf[len(xf)//2+1:], [xf[0]], xf[1:len(xf)//2])),\n            y= np.imag(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))), \n            z= -320*np.ones(psi_fft.shape), \n            mode=\"lines\"), row=1, col=2)\n    fig_sig.add_trace(\n        go.Scatter3d(\n            visible=False, \n            x=np.concatenate((xf[len(xf)//2+1:], [xf[0]], xf[1:len(xf)//2])), \n            y= -9*np.ones(psi_fft.shape), \n            z=np.abs(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))), \n            name=\"prob amplitude\", mode=\"lines\", line=dict(color='black', width=2)), row=1, col=2)\n\n\n# Make 10th trace visible\nfig_sig.data[4].visible = True\nfig_sig.data[5].visible = True\nfig_sig.data[6].visible = True\nfig_sig.data[7].visible = True\nfig_sig.data[len(fig_sig.data)//2+4].visible = True\nfig_sig.data[len(fig_sig.data)//2+5].visible = True\nfig_sig.data[len(fig_sig.data)//2+6].visible = True\nfig_sig.data[len(fig_sig.data)//2+7].visible = True\n\n# Create and add slider\nsteps = []\nfor i in range(0, len(fig_sig.data)//2, 4):\n    step = dict(\n        method=\"update\",\n        args=[{\"visible\": [False] * len(fig_sig.data)}],  # layout attribute\n        label=str(round(sig_arr[i//4],2))\n    )\n    step[\"args\"][0][\"visible\"][i] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][i+1] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][i+2] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][i+3] = True \n    step[\"args\"][0][\"visible\"][len(fig_sig.data)//2+i] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][len(fig_sig.data)//2+i+1] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][len(fig_sig.data)//2+i+2] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][len(fig_sig.data)//2+i+3] = True \n    steps.append(step)\n\nsliders = [dict(\n    active=1,\n    currentvalue={\"prefix\": \"Standard diviation: \"},\n    pad={\"t\": 33},\n    steps=steps\n)]\n\nfig_sig.update_layout(\n    sliders=sliders\n)\n\nfig_sig.update_layout(\n    scene = dict(\n        xaxis = dict(nticks=10, range=[-5,5],),\n        yaxis = dict(nticks=4, range=[-2,2],),\n        zaxis = dict(nticks=4, range=[-2,2],),\n        xaxis_title='Phi',\n        yaxis_title='Imaginary', \n        zaxis_title='Real',))\n    #margin=dict(r=20, l=10, b=10, t=10))\nfig_sig.update_layout(\n    scene2 = dict(\n        xaxis = dict(nticks=10, range=[-5,5],),\n        yaxis = dict(nticks=4, range=[-9, 9],),\n        zaxis = dict(nticks=4, range=[-320, 320],),\n        xaxis_title='Q',\n        yaxis_title='Imaginary', \n        zaxis_title='Real',))\nfig_sig.update_layout(scene_aspectmode='manual',\n    scene_aspectratio=dict(x=2, y=1, z=1), \n                  scene2_aspectmode='manual',\n                  scene2_aspectratio=dict(x=2, y=1, z=1), \n                  showlegend=False, \n                  margin=dict(l=10, r=10, t=5, b=5),\n                  scene_camera=dict(eye=dict(x=1, y=2.4, z=0.4)), \n                  scene2_camera=dict(eye=dict(x=1, y=2.4, z=0.4))\n                  #width=1000\n                  )\n\n\nfig_sig.show(config={'displayModeBar': False, 'displaylogo': False, 'scrollZoom': False})\nfig_sig.write_html(\"wavefunction_changing_sig_with_fft.html\", config={'displayModeBar': False, 'displaylogo': False, 'scrollZoom': False})\n\n# Changing sig plot\n# Create figure\nfig_mean = make_subplots(\n    rows=1, cols=2,\n    shared_xaxes=True,\n    horizontal_spacing=0.02,\n    specs=[[{'type': 'scatter3d'}, {'type': 'scatter3d'}]])\n\n# Add traces, one for each slider step\nk = 3\nsig = 1\nphi_0 = np.arange(-3, 3.5, 0.5)\nsig = 1\nx=np.arange(-20, 20.01, 0.01)\n\n\nfor phi_0_i in phi_0:\n    psi = np.multiply(np.exp(1j*k*x), np.sqrt(np.exp(-np.power(x-phi_0_i, 2)/(2*sig**2))/(sig*np.sqrt(2*np.pi))))\n    fig_mean.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"black\", width=2),\n            name=\"wavefunction\",\n            x=x,\n            y=np.imag(psi), \n            z=np.real(psi), \n            mode=\"lines\"), row=1, col=1)\n    fig_mean.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"red\", width=1),\n            name=\"real part\",\n            x=x,\n            y=-np.ones(psi.shape), \n            z=np.real(psi), \n            mode=\"lines\"), row=1, col=1)\n    fig_mean.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"orange\", width=1),\n            name=\"imaginary part\",\n            x= x,\n            y= np.imag(psi), \n            z= -np.ones(psi.shape), \n            mode=\"lines\"), row=1, col=1)\n    fig_mean.add_trace(\n        go.Scatter3d(\n            visible=False, \n            x=x, \n            y= -np.ones(psi.shape), \n            z=np.abs(psi), \n            name=\"prob amplitude\", mode=\"lines\", line=dict(color='black', width=2)), row=1, col=1)\n\nfor phi_0_i in phi_0:\n    psi_fft = fft(np.multiply(np.exp(1j*k*x), np.sqrt(np.exp(-np.power(x-phi_0_i, 2)/(2*sig**2))/(sig*np.sqrt(2*np.pi)))))\n    xf = fftfreq(len(x), x[1] - x[0])\n    fig_mean.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"black\", width=2),\n            name=\"wavefunction\",\n            x=np.concatenate((xf[len(xf)//2+1:], [xf[0]], xf[1:len(xf)//2])),\n            y=np.imag(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))), \n            z=np.real(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))), \n            mode=\"lines\"), row=1, col=2)\n    fig_mean.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"red\", width=1),\n            name=\"real part\",\n            x=np.concatenate((xf[len(xf)//2+1:], [xf[0]], xf[1:len(xf)//2])),\n            y=-290*np.ones(psi_fft.shape), \n            z=np.real(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))), \n            mode=\"lines\"), row=1, col=2)\n    fig_mean.add_trace(\n        go.Scatter3d(\n            visible=False,\n            line=dict(color=\"orange\", width=1),\n            name=\"imaginary part\",\n            x= np.concatenate((xf[len(xf)//2+1:], [xf[0]], xf[1:len(xf)//2])),\n            y= np.imag(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))), \n            z= -410*np.ones(psi_fft.shape), \n            mode=\"lines\"), row=1, col=2)\n    fig_mean.add_trace(\n        go.Scatter3d(\n            visible=False, \n            x=np.concatenate((xf[len(xf)//2+1:], [xf[0]], xf[1:len(xf)//2])), \n            y= -290*np.ones(psi_fft.shape), \n            z=np.abs(np.concatenate((psi_fft[len(xf)//2+1:],[psi_fft[0]], psi_fft[1:len(xf)//2]))), \n            name=\"prob amplitude\", mode=\"lines\", line=dict(color='black', width=2)), row=1, col=2)\n\n\n\n# Make 10th trace visible\nfig_mean.data[24].visible = True\nfig_mean.data[25].visible = True\nfig_mean.data[26].visible = True\nfig_mean.data[27].visible = True\nfig_mean.data[len(fig_mean.data)//2+24].visible = True\nfig_mean.data[len(fig_mean.data)//2+25].visible = True\nfig_mean.data[len(fig_mean.data)//2+26].visible = True\nfig_mean.data[len(fig_mean.data)//2+27].visible = True\n\n# Create and add slider\nsteps = []\nfor i in range(0, len(fig_mean.data)//2, 4):\n    step = dict(\n        method=\"update\",\n        args=[{\"visible\": [False] * len(fig_mean.data)}],  # layout attribute\n        label=str(phi_0[i//4])\n    )\n    step[\"args\"][0][\"visible\"][i] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][i+1] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][i+2] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][i+3] = True \n    step[\"args\"][0][\"visible\"][len(fig_mean.data)//2+i] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][len(fig_mean.data)//2+i+1] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][len(fig_mean.data)//2+i+2] = True  # Toggle i'th trace to \"visible\"\n    step[\"args\"][0][\"visible\"][len(fig_mean.data)//2+i+3] = True \n    steps.append(step)\n\nsliders = [dict(\n    active=6,\n    currentvalue={\"prefix\": \"Mean: \"},\n    pad={\"t\": 33},\n    steps=steps\n)]\n\nfig_mean.update_layout(\n    sliders=sliders\n)\n\nfig_mean.update_layout(\n    scene = dict(\n        xaxis = dict(nticks=10, range=[-5,5],),\n        yaxis = dict(nticks=4, range=[-2,2],),\n        zaxis = dict(nticks=4, range=[-2,2],),\n               xaxis_title='Phi',\n        yaxis_title='Imaginary', \n        zaxis_title='Real',))\n    #margin=dict(r=20, l=10, b=10, t=10))\nfig_mean.update_layout(\n    scene2 = dict(\n        xaxis = dict(nticks=10, range=[-3,3],),\n        yaxis = dict(nticks=4, range=[-290, 290],),\n        zaxis = dict(nticks=4, range=[-430, 430],),\n        xaxis_title='Q',\n        yaxis_title='Imaginary', \n        zaxis_title='Real',))\nfig_mean.update_layout(scene_aspectmode='manual',\n    scene_aspectratio=dict(x=2, y=1, z=1), \n                  scene2_aspectmode='manual',\n                  scene2_aspectratio=dict(x=2, y=1, z=1), \n                  showlegend=False, \n                  margin=dict(l=10, r=10, t=5, b=5), \n                  scene_camera=dict(eye=dict(x=1, y=2.4, z=0.4)),\n                  scene2_camera=dict(eye=dict(x=1, y=2.4, z=0.4))\n                  #width=1000\n                  )\n\nfig_mean.show(config={'displayModeBar': False, 'displaylogo': False, 'scrollZoom': False})\nfig_mean.write_html(\"wavefunction_changing_mu_with_fft.html\", config={'displayModeBar': False, 'displaylogo': False, 'scrollZoom': False})", "meta": {"hexsha": "37ea574218d864356980c40ffc38e6fb4c988894", "size": 18855, "ext": "py", "lang": "Python", "max_stars_repo_path": "web_app/main/utils/plotly_with_fft.py", "max_stars_repo_name": "karlberggren/QuantumCircuitsClass", "max_stars_repo_head_hexsha": "ea0c7599c53a481ee854a0f8496cd91444311d16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-11T05:48:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T04:28:59.000Z", "max_issues_repo_path": "web_app/main/utils/plotly_with_fft.py", "max_issues_repo_name": "karlberggren/QuantumCircuitsClass", "max_issues_repo_head_hexsha": "ea0c7599c53a481ee854a0f8496cd91444311d16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "web_app/main/utils/plotly_with_fft.py", "max_forks_repo_name": "karlberggren/QuantumCircuitsClass", "max_forks_repo_head_hexsha": "ea0c7599c53a481ee854a0f8496cd91444311d16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.71, "max_line_length": 138, "alphanum_fraction": 0.5447891806, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347860767304, "lm_q2_score": 0.9059898146721821, "lm_q1q2_score": 0.8828279912477843}}
{"text": "import numpy as np\n\n\ndef compint(P, r, n, t) -> float:\n    \"\"\"\n    Compute the compounding interest\n    P: principal\n    r: interest rate\n    n: number of times interest compounds in period\n    t: Number of time periods\n\n    A = P (1 + r / n) ^ (n * t)\n    \"\"\"\n    A = P * np.power(1 + r / n, n * t)\n    return A\n\ndef payment_amount(balance, payment):\n    \"\"\"\n    The amount of a payment given a balance is which ever is less\n    \"\"\"\n    curr_payment = min(balance, payment)\n    return curr_payment\n\ndef single_payment(payment, P, r, n=365, t=1/12):\n    \"\"\"\n    Make a single payment on a loan after accruing interest for the provided pay period\n    :param payment: Payment amount per period\n    :param P: principal\n    :param r: interest rate\n    :param n: number of times interest compounds in period\n    :param t: payment frequency\n    :return: (new principal, amount paid)\n    \"\"\"\n    # Calculate new principal at end of period\n    P = compint(P, r, n, t)\n    ## Subtract payment\n    # Pay payment amount until principal is zero\n    curr_pay = payment_amount(P, payment)\n    P -= curr_pay\n\n    # Round\n    curr_pay = round(curr_pay, 2)\n    P = round(P, 2)\n    return P, curr_pay\n\ndef pay_loan(payment, P, r, n=365, t=1/12, stop=1e6) -> tuple:\n    \"\"\"\n    Pay a compound interest loan to extinction\n    Default parameters for daily compounding with monthly payments\n    :param payment: Payment amount per period\n    :param P: principal\n    :param r: interest rate\n    :param n: number of times interest compounds in period\n    :param t: payment frequency\n    :param stop: Stop criteria to avoid infinite calculation (default 1 million)\n    :return: (balances, payments)\n    | balances: balances for each period\n    | payments: payments for each period\n    \"\"\"\n    # Keep track of balances after each payment\n    balances = []\n    payments = []\n    while P > 0:\n        P, curr_pay = single_payment(payment, P, r, n, t)\n        assert P <= stop, f'Payments of {money_amount(payment)} have led the balance to reach stopping criteria of' \\\n                          f' {money_amount(stop)}.'\n        balances.append(P)\n        payments.append(curr_pay)\n    return balances, payments\n\ndef money_amount(x: float) -> str:\n    \"\"\"\n    Convert a float to a string dollar amount with commas\n    Ex. 1000.235 -> $1,000.24\n    \"\"\"\n    # Round to hundreds\n    rounded = '%.2f' % x\n    # Split into dollars and cents\n    dollars, cents = rounded.split('.')\n\n    # Add commas every three digits to dollars\n    rev_dollars = ''\n    count = 0\n    for i in dollars[::-1]:\n        rev_dollars += i\n        count += 1\n        # Add comma\n        if count == 3:\n            rev_dollars += ','\n            count = 0\n\n    # Flip reversed representation\n    ref_dollars = rev_dollars.rstrip(',')[::-1]\n\n    # Final format\n    ref_amt = f'${ref_dollars}.{cents}'\n    return ref_amt\n\n", "meta": {"hexsha": "e0967fe27bf445379bc95128a9e226a64f76b8a8", "size": 2862, "ext": "py", "lang": "Python", "max_stars_repo_path": "multiloan/utils.py", "max_stars_repo_name": "michaelsilverstein/Loans", "max_stars_repo_head_hexsha": "017465a996dda6629842ecd9ab6aa183a5fcb9dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-16T03:17:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-23T02:18:10.000Z", "max_issues_repo_path": "multiloan/utils.py", "max_issues_repo_name": "michaelsilverstein/Loans", "max_issues_repo_head_hexsha": "017465a996dda6629842ecd9ab6aa183a5fcb9dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multiloan/utils.py", "max_forks_repo_name": "michaelsilverstein/Loans", "max_forks_repo_head_hexsha": "017465a996dda6629842ecd9ab6aa183a5fcb9dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9090909091, "max_line_length": 117, "alphanum_fraction": 0.6226415094, "include": true, "reason": "import numpy", "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639677785088, "lm_q2_score": 0.9086179049750476, "lm_q1q2_score": 0.8827804169521534}}
{"text": "import numpy as np\r\nimport math\r\nfrom mpl_toolkits import mplot3d\r\nimport matplotlib.pyplot as plt\r\nimport sympy\r\n\r\n\r\n\r\n\r\n\r\n# Дано:\r\nalpha = 1\r\nf = lambda x, y: alpha * (x**2 - y)**2 + (x - 1)**2\r\n\r\nX0 = np.array([-1, -2])\r\neps = 1e-3\r\n\r\nGrad_f = lambda x, y: np.array([4*alpha*x*(x**2 - y) + 2*x - 2, alpha*(-2*x**2 + 2*y)])\r\n\r\n# Параметры методов:\r\nkappa0 = 1\r\nnu = 0.95\r\nomega = 0.5\r\n\r\n\r\n\r\ndef MethodGoldenRatio(f, b, a = 0, e = eps * 1e-1):\r\n    tau = (math.sqrt(5) + 1) / 2\r\n    Ak, Bk = a, b\r\n    lk = Bk - Ak\r\n    Xk1 = Bk - (Bk - Ak) / tau\r\n    Xk2 = Ak + (Bk - Ak) / tau\r\n    y1, y2 = f(Xk1), f(Xk2)\r\n    while lk >= e:\r\n        if y1 >= y2:\r\n            Ak = Xk1\r\n            Xk1 = Xk2\r\n            Xk2 = Ak + Bk - Xk1\r\n            y1 = y2\r\n            y2 = f(Xk2)\r\n        else:\r\n            Bk = Xk2\r\n            Xk2 = Xk1\r\n            Xk1 = Ak + Bk - Xk2\r\n            y2 = y1\r\n            y1 = f(Xk1)\r\n        lk = Bk - Ak\r\n    return (Ak + Bk) / 2\r\n\r\ndef MethodsGradientDescent(flag):\r\n    fun = lambda X: f(X[0], X[1])\r\n    w = lambda X: -Grad_f(X[0], X[1])\r\n    X = X0\r\n    kappa_k = kappa0\r\n    NormW = []\r\n    Xk = []\r\n    while True:\r\n        Xk.append(X)\r\n        Wk = w(X)\r\n        NormW.append(np.linalg.norm(Wk))\r\n        if NormW[-1] <= eps:\r\n            break\r\n        fk = fun(X)\r\n        if flag == 0:\r\n            phi = lambda kappa: fun(X + kappa * Wk)\r\n            kappa_k = MethodGoldenRatio(phi, 2.5)\r\n            X = X + kappa_k * Wk\r\n        elif flag == 1:\r\n            Xcurr = X + kappa_k * Wk\r\n            while fk - fun(Xcurr) <= omega * kappa_k * NormW[-1]**2:\r\n                kappa_k *= nu\r\n                Xcurr = X + kappa_k * Wk\r\n            X = Xcurr\r\n    return X, Xk, NormW\r\n\r\n\r\n\r\nprint()\r\nprint('Методы градиентного спуска')\r\nprint('Дано:')\r\nprint('Целевая функция:        f(x, y) =', f(sympy.Symbol('x'), sympy.Symbol('y')))\r\nprint('Начальное приближение:  X0 =', X0)\r\nprint('Точность вычисления:    Eps =', eps)\r\n\r\nfor i in range(2):\r\n    print()\r\n    print('_' * 100)\r\n    if i == 0:\r\n        print('*' * 30, ' Метод наискорейщего спуска ', '*' * 30)\r\n    elif i == 1:\r\n        print('*' * 20, ' Метод градиентного спуска с дроблением шага ', '*' * 20)\r\n    X, Xk, NormW = MethodsGradientDescent(i)\r\n    print('Точка минимума функции:             Xmin =', X)\r\n    print('Значение функции в точке минимума:  f(Xmin) =', f(X[0], X[1]))\r\n    print('Количество итераций:                k =', len(NormW)-1)", "meta": {"hexsha": "a042bcc7e2700b0929a259f0d90903d9af46613b", "size": 2452, "ext": "py", "lang": "Python", "max_stars_repo_path": "methods/Lab2_gradient_descent.py", "max_stars_repo_name": "v-mk-s/optimization-methods", "max_stars_repo_head_hexsha": "41be917aedb80e2f04d059f0ca31efce1dc1b742", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "methods/Lab2_gradient_descent.py", "max_issues_repo_name": "v-mk-s/optimization-methods", "max_issues_repo_head_hexsha": "41be917aedb80e2f04d059f0ca31efce1dc1b742", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "methods/Lab2_gradient_descent.py", "max_forks_repo_name": "v-mk-s/optimization-methods", "max_forks_repo_head_hexsha": "41be917aedb80e2f04d059f0ca31efce1dc1b742", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8105263158, "max_line_length": 88, "alphanum_fraction": 0.4645187602, "include": true, "reason": "import numpy,import sympy", "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639669551474, "lm_q2_score": 0.9086179049750476, "lm_q1q2_score": 0.8827804162040324}}
{"text": "'''\nrotations.py rotates cartesian points about x,y,z axis and/or specified vector.\nSee rotationsVid.py for a more extensive example with outputted graphics with rotations.py at work\n'''\n#Data array format: [[x1,y1,z1],[x2,y2,z2],[x3,y3,z3],...[xn,yn,zn]]\n#Specified vector array: [vx,vy,vz]\n#Output array format: [[xr1, yr1, zr1],[xr2,yr2,zr2],[xr3,yr3,zr3],...[xrn,yrn,zrn]]\n#Theta (angle) input in degrees\n\nimport numpy as np #only requirement\n\n#Rotation definitions\ndef xrotate(positions, theta): # rotation about the x-axis\n    theta = np.deg2rad(theta)\n    xr = np.array([[1,0,0],[0,np.cos(theta),-np.sin(theta)],[0,np.sin(theta),np.cos(theta)]])\n    return np.dot(positions, xr)\n\ndef yrotate(positions, theta): # rotation about the y-axis\n    theta = np.deg2rad(theta)\n    yr = np.array([[np.cos(theta),0,np.sin(theta)],[0,1,0],[-np.sin(theta),0,np.cos(theta)]])\n    return np.dot(positions, yr)\n\ndef zrotate(positions, theta): # rotation about the z-axis\n    theta = np.deg2rad(theta)\n    zr = np.array([[np.cos(theta),-np.sin(theta),0],[np.sin(theta),np.cos(theta),0],[0,0,1]])\n    return np.dot(positions, zr)\n\ndef vrotate(positions, theta, vec): # rotation about specified vector\n    vec = normalize(vec)\n    theta = np.deg2rad(theta)\n    ux = vec[0]\n    uy = vec[1]\n    uz = vec[2]\n    #Utilize known rotation matrix\n    rot = np.array([[np.cos(theta) + ux*ux*(1-np.cos(theta)), ux*uy*(1-np.cos(theta))-uz*np.sin(theta), ux*uz*(1-np.cos(theta))+uy*np.sin(theta)],\n                    [uy*ux*(1-np.cos(theta))+uz*np.sin(theta), np.cos(theta) + uy*uy*(1-np.cos(theta)), uy*uz*(1-np.cos(theta))-ux*np.sin(theta)],\n                   [uz*ux*(1-np.cos(theta))-uy*np.sin(theta), uz*uy*(1-np.cos(theta))+ux*np.sin(theta), np.cos(theta)+uz*uz*(1-np.cos(theta))]])\n    return np.dot(positions, rot)\n\ndef normalize(vec): #normalize function used in vrotate\n    norm = np.linalg.norm(vec)\n    return vec/norm\n\ndef main():\n    #Example code of how to run\n    print(\"Example of 4 points\")\n    a = np.random.randint(10,size=(4,3))\n    print(\"Array = \\n {}\".format(a))\n    theta = 45\n    print(\"Theta = {} deg\".format(theta))\n    xrot = xrotate(a, theta)\n    yrot = yrotate(a,theta)\n    zrot = zrotate(a, theta)\n    vec = [1,1,1]\n    vrot = vrotate(a, theta, vec)\n    print(\"x-rotation array = \\n{}\".format(xrot))\n    print(\"y-rotation array = \\n{}\".format(yrot))\n    print(\"z-rotation array = \\n{}\".format(zrot))\n    print(\"v-rotation about vector [1,1,1] array = \\n{}\".format(vrot))\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "394472bf06d69dae10603d11cb4ca78eeba1edac", "size": 2521, "ext": "py", "lang": "Python", "max_stars_repo_path": "main/rotations.py", "max_stars_repo_name": "bkopchick/rotations", "max_stars_repo_head_hexsha": "d5738d96974dcd0119004f50b2bcefeb3d4ac491", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-03-31T14:23:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T17:50:47.000Z", "max_issues_repo_path": "main/rotations.py", "max_issues_repo_name": "bkopchick/rotations", "max_issues_repo_head_hexsha": "d5738d96974dcd0119004f50b2bcefeb3d4ac491", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main/rotations.py", "max_forks_repo_name": "bkopchick/rotations", "max_forks_repo_head_hexsha": "d5738d96974dcd0119004f50b2bcefeb3d4ac491", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-14T03:17:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-14T03:17:54.000Z", "avg_line_length": 40.0158730159, "max_line_length": 146, "alphanum_fraction": 0.6322887743, "include": true, "reason": "import numpy", "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639653084245, "lm_q2_score": 0.9086179049750475, "lm_q1q2_score": 0.8827804147077903}}
{"text": "import numpy as np\n\n\ndef calc_mean_squared_error(y_N, yhat_N):\n    ''' Compute the mean squared error given true and predicted values\n\n    Args\n    ----\n    y_N : 1D array, shape (N,)\n        Each entry represents 'ground truth' numeric response for an example\n    yhat_N : 1D array, shape (N,)\n        Each entry representes predicted numeric response for an example\n\n    Returns\n    -------\n    mse : scalar float\n        Mean squared error performance metric\n        .. math:\n            mse(y, \\hat{y}) = \\frac{1}{N} \\sum_{n=1}^N (y_n - \\hat{y}_n)^2\n\n    Examples\n    --------\n    >>> y_N = np.asarray([-2, 0, 2], dtype=np.float64)\n    >>> yhat_N = np.asarray([-4, 0, 2], dtype=np.float64)\n    >>> calc_mean_squared_error(y_N, yhat_N)\n    1.3333333333333333\n    '''\n\n    if yhat_N.shape[0] == 0:\n        return 0\n    return np.sum((yhat_N - y_N)**2)/yhat_N.shape[0]\n\n# y_N = np.asarray([-2, 0, 2], dtype=np.float64)\n# yhat_N = np.asarray([-4, 0, 2], dtype=np.float64)\n# print(calc_mean_squared_error(y_N, yhat_N))\n\ndef calc_mean_absolute_error(y_N, yhat_N):\n    ''' Compute the mean absolute error given true and predicted values\n\n    Args\n    ----\n    y_N : 1D array, shape (N,)\n        Each entry represents 'ground truth' numeric response for an example\n    yhat_N : 1D array, shape (N,)\n        Each entry representes predicted numeric response for an example\n\n    Returns\n    -------\n    mae : scalar float\n        Mean absolute error performance metric\n        .. math:\n            mae(y, \\hat{y}) = \\frac{1}{N} \\sum_{n=1}^N | y_n - \\hat{y}_n |\n\n    Examples\n    --------\n    >>> y_N = np.asarray([-2, 0, 2], dtype=np.float64)\n    >>> yhat_N = np.asarray([-4, 0, 2], dtype=np.float64)\n    >>> calc_mean_absolute_error(y_N, yhat_N)\n    0.6666666666666666\n    '''\n    if yhat_N.shape[0] == 0:\n        return 0\n    return np.sum(abs(yhat_N - y_N))/yhat_N.shape[0]\n\n# y_N = np.asarray([-2, 0, 2], dtype=np.float64)\n# yhat_N = np.asarray([-4, 0, 2], dtype=np.float64)\n# print(calc_mean_absolute_error(y_N, yhat_N))\n", "meta": {"hexsha": "555d8ce24d6c1180d85b34c70799ad0c7a382306", "size": 2020, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw1/performance_metrics.py", "max_stars_repo_name": "brawnerquan/comp135-20f-assignments", "max_stars_repo_head_hexsha": "9570c17b872b7334b0e5b86160d868e3b854c71a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw1/performance_metrics.py", "max_issues_repo_name": "brawnerquan/comp135-20f-assignments", "max_issues_repo_head_hexsha": "9570c17b872b7334b0e5b86160d868e3b854c71a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw1/performance_metrics.py", "max_forks_repo_name": "brawnerquan/comp135-20f-assignments", "max_forks_repo_head_hexsha": "9570c17b872b7334b0e5b86160d868e3b854c71a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7058823529, "max_line_length": 76, "alphanum_fraction": 0.6044554455, "include": true, "reason": "import numpy", "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639653084245, "lm_q2_score": 0.9086178975514608, "lm_q1q2_score": 0.8827804074953011}}
{"text": "\"\"\"Implementation of the Logistic sigmoid function\n    Reference: https://en.wikipedia.org/wiki/Logistic_function\n    \n    Logistic functions are often used in neural networks to introduce \n    nonlinearity in the model or to clamp signals to within a specified \n    range. A popular neural net element computes a linear combination of \n    its input signals, and applies a bounded sigmoid function to the result; \n    this model can be seen as a \"smoothed\" variant of the classical threshold\n    neuron.\n\n\n\"\"\"    \n    \nfrom .activation_function import ActivationFunction\nimport numpy as np\n\nclass Sigmoid(ActivationFunction):\n    \n    def __init__(self):\n        super().__init__()\n    \n    @classmethod\n    def eval(cls, x: np.float) -> np.float:\n        \"\"\"Evaluates the sigmoid function for a given x value\n           Reference: https://en.wikipedia.org/wiki/Logistic_function#Derivative\n        \"\"\"\n        return 1 / (1 + np.exp(-x))\n    \n    @classmethod\n    def derivative(cls, x: np.float) -> np.float:\n        \"\"\"Evaluates the derivative of the logitistic function for a given x value\n           Reference: https://en.wikipedia.org/wiki/Logistic_function#Derivative\n        \"\"\"\n        return cls.eval(x) * (1 - cls.eval(x))    \n", "meta": {"hexsha": "d22525167108d86da30ad00caa3830dda5df3187", "size": 1239, "ext": "py", "lang": "Python", "max_stars_repo_path": "flypy/neural_networks/activation_functions/sigmoid.py", "max_stars_repo_name": "bobbyscharmann/flypy", "max_stars_repo_head_hexsha": "39dce7decd9633e7d90bb4c77472c8c40aeda61c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "flypy/neural_networks/activation_functions/sigmoid.py", "max_issues_repo_name": "bobbyscharmann/flypy", "max_issues_repo_head_hexsha": "39dce7decd9633e7d90bb4c77472c8c40aeda61c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "flypy/neural_networks/activation_functions/sigmoid.py", "max_forks_repo_name": "bobbyscharmann/flypy", "max_forks_repo_head_hexsha": "39dce7decd9633e7d90bb4c77472c8c40aeda61c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4, "max_line_length": 82, "alphanum_fraction": 0.6771589992, "include": true, "reason": "import numpy", "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639677785087, "lm_q2_score": 0.908617893221035, "lm_q1q2_score": 0.8827804055323781}}
{"text": "#Function to apply circle intersection\n    #Inputs:\n        #point 1, distance 1, point 2, distance 2\n        #np.a, float, np.a, float\n\n#Standard imports\nimport math\nimport numpy as np\n        \ndef circleIntersection(point_1,dist_1,point_2,dist_2): #*1\n\n    x_0 = point_1[0]\n    y_0 = point_1[1]\n    r_0 = dist_1\n    \n    x_1 = point_2[0]\n    y_1 = point_2[1]\n    r_1 = dist_2\n    \n    d = math.sqrt((x_1-x_0)**2 +(y_1-y_0)**2)\n    a = (r_0**2 - r_1**2 + d**2)/(2*d)\n    h = np.sqrt(r_0**2 - a**2)\n    \n    x_2 = x_0+a*(x_1-x_0)/d   \n    y_2 = y_0+a*(y_1-y_0)/d\n    \n    x_31=x_2 + h*(y_1-y_0)/d\n    y_31=y_2 - h*(x_1-x_0)/d\n    \n    x_32=x_2 - h*(y_1-y_0)/d\n    y_32=y_2 + h*(x_1-x_0)/d\n    \n    \n    return (x_31,y_31),(x_32,y_32)\n\n#NOTES: Does not test for irregular conditions, which really shouldn't happen.\n    #It should be mathmatically impossible\n    #But they keep hapending, so it is critical to do so\n\n#SOURCES: https://stackoverflow.com/questions/3349125/circle-circle-intersection-points *1\n\n    ", "meta": {"hexsha": "6e0ea156e92b6e9928f675763e485085080f42e4", "size": 1011, "ext": "py", "lang": "Python", "max_stars_repo_path": "LightLockClean/a1_Program-Files/b4_Generation3/s5/a_ApplyCircleIntersection.py", "max_stars_repo_name": "Team766/LightLock", "max_stars_repo_head_hexsha": "b73250f084546749e25eb6446892641eab315725", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LightLockClean/a1_Program-Files/b4_Generation3/s5/a_ApplyCircleIntersection.py", "max_issues_repo_name": "Team766/LightLock", "max_issues_repo_head_hexsha": "b73250f084546749e25eb6446892641eab315725", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LightLockClean/a1_Program-Files/b4_Generation3/s5/a_ApplyCircleIntersection.py", "max_forks_repo_name": "Team766/LightLock", "max_forks_repo_head_hexsha": "b73250f084546749e25eb6446892641eab315725", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0714285714, "max_line_length": 90, "alphanum_fraction": 0.5984174085, "include": true, "reason": "import numpy", "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9833429619433692, "lm_q2_score": 0.8976952845805989, "lm_q1q2_score": 0.8827423400620819}}
{"text": "import numpy as np\n\n\n# Pearson's correlation coefficient\n# r = summation[(x - x_mean)(y - y_mean)] / sqrt[summation((x - x_mean)^2) * summation((y - y_mean)^2)]\n# http://www.datasciencemadesimple.com/wp-content/uploads/2017/07/CORRELATION-COEFFICIENT-FORMULA.png\ndef pearson_correlation(feature_1, feature_2, generate_sd=False):\n    feature_1_mean = np.mean(feature_1, axis=0)\n    feature_2_mean = np.mean(feature_2, axis=0)\n    feature_1_minus_mean = feature_1 - feature_1_mean\n    feature_2_minus_mean = feature_2 - feature_2_mean\n    feature_1_minus_mean_squared = np.square(feature_1_minus_mean)\n    feature_2_minus_mean_squared = np.square(feature_2_minus_mean)\n    features_diff_product = np.multiply(feature_1_minus_mean, feature_2_minus_mean)\n    coefficient = (np.sum(features_diff_product, axis=0) /\n                   np.sqrt(np.multiply(np.sum(feature_1_minus_mean_squared, axis=0),\n                                       np.sum(feature_2_minus_mean_squared, axis=0))))\n    if generate_sd:\n        feature_1_sd = np.sqrt(np.sum(feature_1_minus_mean_squared)/(np.size(feature_1_minus_mean_squared) - 1))\n        feature_2_sd = np.sqrt(np.sum(feature_2_minus_mean_squared)/(np.size(feature_2_minus_mean_squared) - 1))\n        return coefficient, feature_1_sd, feature_2_sd\n    return coefficient\n\n\n# outcome/dependent feature residual (error) function\ndef residual_error(actual_y_matrix, predicted_y_matrix):\n    return np.subtract(actual_y_matrix, predicted_y_matrix)\n\n\n# Sum of squared residuals\ndef rss(residual_vector):\n    return np.sum(np.square(residual_vector), axis=0)\n\n\ndef l2_norm(vector):\n    return np.sqrt(np.sum(np.square(vector)))\n\n\n# sigmoid / logistic function\ndef sigmoid(x):\n    return 1.0 / (1.0 + np.exp(-x))\n\n\n# softmax function (returns probability of a class)\n# input is most commonly product of parameters (theta) and variables (values)\ndef softmax(x):\n    return np.exp(x)/np.sum(np.exp(x), axis=0)\n", "meta": {"hexsha": "332c227fdb7e502d6cb1b0f26b887959e7eca8ad", "size": 1936, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/formulae.py", "max_stars_repo_name": "limjiaxiang/panpy-ml", "max_stars_repo_head_hexsha": "add1ccd0197d188c00b86f34b09b42e3e977e302", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/formulae.py", "max_issues_repo_name": "limjiaxiang/panpy-ml", "max_issues_repo_head_hexsha": "add1ccd0197d188c00b86f34b09b42e3e977e302", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/formulae.py", "max_forks_repo_name": "limjiaxiang/panpy-ml", "max_forks_repo_head_hexsha": "add1ccd0197d188c00b86f34b09b42e3e977e302", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3333333333, "max_line_length": 112, "alphanum_fraction": 0.7355371901, "include": true, "reason": "import numpy", "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102552339747, "lm_q2_score": 0.9124361622627654, "lm_q1q2_score": 0.8827001006193302}}
{"text": "# calculate_pi.py\n# MIT License\n# github.com/viktor40/HammerBotPython\n\n\"\"\"\nCalculate the value of π using the Leibniz formula for pi: https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80.\nThis is a rather slow way to calculate π since the series converges slowly. This was mostly a personal exercise.\n\nITERATIONS will determine the number of iterations to perform to calculate the value of pi.\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nITERATIONS = 50\nPLOT = True\nx, y = [], []\n\n\ndef calculate_pi(iterations: int):\n    \"\"\"\n    Use leibniz series to calculate pi.\n    :param iterations: sets the number of iterations to be executed. After this has been reach the program will stop\n    :param plot: set if you want to plot the values\n    :yield: the function will yield the nth iteration of the leibniz series, together with n.\n    \"\"\"\n    pi_ = 0\n    for n_ in range(0, iterations):\n        pi_ += 4 * ((-1) ** n_) / (2 * n_ + 1)\n        yield pi_, n_\n\n\npi_iterator = calculate_pi(ITERATIONS)\nfor value in pi_iterator:\n    pi, n = value\n    print(\"After {} iteration{}, the value of π equals {}\".format(n + 1, \"s\" if n else \"\", pi))\n\n    if PLOT:\n        x.append(n)\n        y.append(pi)\n\nif PLOT:\n    plt.plot(x, y, color='blue')\n    plt.plot([0, ITERATIONS], [np.pi, np.pi], color='red')\n    plt.xlabel('Number of iterations n')\n    plt.ylabel('Value of pi')\n    plt.show()\n", "meta": {"hexsha": "fc1583e7ec5818fd63a2a4185294843cac648c2b", "size": 1394, "ext": "py", "lang": "Python", "max_stars_repo_path": "calculate_pi.py", "max_stars_repo_name": "viktor40/pi_leibniz", "max_stars_repo_head_hexsha": "5fc15c569c89af6f7323587616de15c14acb710c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "calculate_pi.py", "max_issues_repo_name": "viktor40/pi_leibniz", "max_issues_repo_head_hexsha": "5fc15c569c89af6f7323587616de15c14acb710c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calculate_pi.py", "max_forks_repo_name": "viktor40/pi_leibniz", "max_forks_repo_head_hexsha": "5fc15c569c89af6f7323587616de15c14acb710c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0416666667, "max_line_length": 116, "alphanum_fraction": 0.6700143472, "include": true, "reason": "import numpy", "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102524151826, "lm_q2_score": 0.9124361610722159, "lm_q1q2_score": 0.8827000968956127}}
{"text": "# Python script of the basic operations numpy\n# Author: Sandeep Mewara\n# Location: Learn By Insight\n# Github: https://github.com/samewara/python-examples/blob/master/numpy-basic.py\n# #####################################\n# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %% [markdown]\n# ## Numpy (Numerical python)\n# \n# Packages for numerical computation designed for efficiency to work on large data sets\n# %% [markdown]\n# *** Initalizing Matrix - via LIST ***\n\n# %%\nimport numpy as np\n\n\n# %%\n#mat = np.array([1, 2, 3, 4, 5])\n\nlst = [1,2,3,4,5]\nmat = np.array(lst)\nmat\n\n\n# %%\nprint(\"mat.shape:\", mat.shape)\nprint(\"mat[2]:\", mat[2])\nprint(\"mat.flatten():\", mat.flatten())\n\n# %% [markdown]\n# *** Initializing Matrix - via NULL MATRIX (ZEROS) ***\n\n# %%\n# 5x4 numpy array where the ith row and jth col has the entry i+j\nx,y=5,4\nmatij = np.zeros((x,y))\nmatij\n\n\n# %%\nfor i in range(x):\n    for j in range(y):\n        matij[i][j] = i+j\n\nmatij\n\n# %% [markdown]\n# *** Initializing Matrix - via IDENTITY MATRX ***\n\n# %%\nsize=3\nmat_i = np.identity(size)\nmat_i\n\n# %% [markdown]\n# *** Initializing Matrix - via ONES MATRIX ***\n\n# %%\nm,n=3,2\nmat_1=np.ones((m,n))\nmat_1\n\n# %% [markdown]\n# *** Transpose ***\n\n# %%\nmat_1=np.ones((m,n))\nmat_1_transpose = mat_1.T\nmat_1_transpose\n\n# %% [markdown]\n# *** Reshape ***\n\n# %%\nmat_1=np.ones((m,n))\nmat_1_reshape = mat_1.reshape(1,6) #size is still the same 3*2 = 1*6\nmat_1_reshape\n\n# %% [markdown]\n# *** Indexing ***\n\n# %%\n# An array of grand slam information\nPlayers = ['Roger Federer', 'Margaret Court', 'Rafael Nadal', 'Maria Sharapova', 'Pete Sampras', 'Steffi Graf', 'Novak Djokovic']\nTitles = [20, 24, 17, 23, 15, 22, 14]\nFinals = [30, 29, 25, 29, 24, 31, 19]\n\ngrand_slam=np.array([Players,Titles,Finals])\ngrand_slam\n\n\n# %%\n# select all players from the matrix\ngrand_slam[0,::1] #0th row & all column, then the indexing of list :: matrix[row, column], row, column are list so start:stop:step\n\n\n# %%\n# select alternate players with data and ten transpose for easy reading\n\ngrand_slam[:,::2].T #all of row and all of columns but step jump 2\n\n# %% [markdown]\n# *** Simulation #1 *** \n# Simulate the process of rolling a 6 faced die 100 times and find the probability of getting a number that is divisible by 3. \n\n# %%\n\ntrials = 100\ndraws = np.random.randint(1,7,trials) # Generate 10 random integers in the range 1-6\ndraws\n\n\n# %%\ndraws[draws%3==0] #masking - give all the values back that satisfy the mask in the list\n\n\n# %%\nprobab_3 = len(draws[draws%3==0])/trials # or can use .size of the list instead of using len\nprint(\"probability for numbers divisble by 3:\", probab_3) \n\n\n# %%\n# simulation with multiple counts\ntrials_multiple = 100,1000,10000,100000\nfor i in range(len(trials_multiple)):\n    draws = np.random.randint(1,7,trials_multiple[i])\n    probab_3 = len(draws[draws%3==0])/trials_multiple[i] # or can use .size of the list instead of using len\n    print(\"probability for numbers divisble by 3 in {0} trials:{1}\".format(trials_multiple[i], probab_3)) \n\n# %% [markdown]\n# *** Simulation #2 ***\n# Two six-faced dice are rolled. Find the probability that their faces sum to 4.\n\n# %%\ntrials_multiple = 100,1000,10000,100000\nfor i in range(len(trials_multiple)):\n    draws1, draws2 = np.random.randint(1,7,trials_multiple[i]), np.random.randint(1,7,trials_multiple[i])\n    probab_sum4 = len(draws1[draws1+draws2 == 4])/trials_multiple[i] #filter the values\n    print(\"probability for sum be 4 in {0} trials:{1}\".format(trials_multiple[i], probab_sum4)) \n\n# %% [markdown]\n# *** Reading CSV Files ***\n# \n# data-file: economy_data.CSV\n# \n# sample data on a quarterly basis on Indian economy sampled from RBI database containing Gross Value added, Forex, Borrowings for the period 2016 - Q1 2018. Find the correlation among different indicators\n\n# %%\nf=open('./data-files/numpy/economy_data.csv')\ndata = f.read().split('\\n')\ndata\n\n\n# %%\n# For better data read\nfor content in data[:-1]:\n    print(\"{0:>9s}  {1:9s} {2:7s} {3:10s} {4:4s}\".format(*(content.split(','))))\n\n\n# %%\n#read data into numpy array\n#skip the header and 1st column\ndata_np = np.genfromtxt('./data-files/numpy/economy_data.csv',delimiter=\",\",skip_header=1,usecols=[1,2,3,4],dtype=\"float32\")\nprint(\"Data shape:\",data_np.shape, \", Data size:\",data_np.size, \", Data type:\",data_np.dtype)\nprint(data_np)\n\n\n# %%\n# Correlation between Forex & Borrowing\n\ngva = data_np[:,0] #select all rows from 1st column\nforex = data_np[:,1]\nborrowing = data_np[:,2]\ncpi = data_np[:,3]\n\nprint(\"Corrleation coefficients forex,borrowing\\n\",np.corrcoef(forex,borrowing))\n\n\n# %%\n# Forex Data in Q2 (17-18)\n\ndata_np[5,:]\n\n\n# %%\n# rows where cpi is less than 3\n\ndata_np[data_np[:,-1] < 3]\n\n\n# %%\n# average cpi for all the years\n\nnp.round(np.mean(cpi),2)\n\n# %% [markdown]\n# *** Broadcasting ***\n# \n# When two arrays are of different shapes this describes how the arithmetic works between them.\n# \n# Arrays are compatible for broadcasting when the trailing dimension match or either of them is of length 1, then the broadcasting is done over the missing dimension or length 1 dimension\n\n# %%\n#When trailing dimension match\na=np.array([[1,2,3],[3,4,5]])\nb=np.array([8,9,10])\nprint(\"shape of a\",a.shape,\" shape of b\",b.shape)\na+b #broadcasting on row\n\n\n# %%\n#trailing dimension is 1\nb=np.array([[10],[12]])\nprint(\"shape of a\",a.shape,\" shape of b\",b.shape)\na+b #broadcasting on column\n\n\n# %%\n#vertical/horizontal stacking\na = np.identity(3)\nb = np.array([[ 1, 2, 3],\n[ 4, 5, 6],\n[ 7, 8, 9]])\nprint(\"vertical:\\n\",np.vstack((a,b)))\nprint(\"horizontal:\\n\",np.hstack((a,b)))\n\n\n# %%\nnp.concatenate([a,b],axis=0) #same as vstack \n\n# %% [markdown]\n# *** Image Processing ***\n\n# %%\n# show an image using matpotlib\nimport matplotlib.image as mimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nget_ipython().run_line_magic('matplotlib', 'inline')\nimg = mimg.imread('./data-files/numpy/hulk.png') # read an image\n\noriginal_image_pixels = np.array(img,dtype='float32')  # make an numpy array\nprint (original_image_pixels) # Note the values are between 0 and 1\nplt.imshow(original_image_pixels,cmap='gray'); # use a gray scale color map\n\n\n# %%\n# increase contrast pixel by pixel\ncontrast_enhanced_pixels = original_image_pixels*3 #increase the contrast; but some values may now be more than 1\ncontrast_enhanced_pixels[contrast_enhanced_pixels > 1] = 1 #clamp the values to max 1\nplt.imshow(contrast_enhanced_pixels,cmap='gray')\n\n\n# %%\n\n\n\n", "meta": {"hexsha": "bf6b7d4a9937709bbe3c9869a746532bed988f65", "size": 6438, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy-basic.py", "max_stars_repo_name": "samewara/python-examples", "max_stars_repo_head_hexsha": "088c40adfe7b6433ca89d7f1f76b17f43d2acbc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy-basic.py", "max_issues_repo_name": "samewara/python-examples", "max_issues_repo_head_hexsha": "088c40adfe7b6433ca89d7f1f76b17f43d2acbc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy-basic.py", "max_forks_repo_name": "samewara/python-examples", "max_forks_repo_head_hexsha": "088c40adfe7b6433ca89d7f1f76b17f43d2acbc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-26T09:48:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-26T09:48:07.000Z", "avg_line_length": 24.7615384615, "max_line_length": 205, "alphanum_fraction": 0.678471575, "include": true, "reason": "import numpy", "num_tokens": 1945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.9465966705768132, "lm_q1q2_score": 0.8826571994123914}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 24 22:44:03 2019\n\n@author: alankar\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import fftpack\n\ndow = np.loadtxt('dow2.txt')\nN = len(dow)\nt = np.arange(0,N,1)\n\nsampling = 1/(t[1]-t[0])\nf = np.linspace(0,sampling,N//2+1)\ndow_fft = np.fft.rfft(dow)\nplt.figure(figsize=(13,10))\nplt.semilogy(f,np.abs(dow_fft)**2)\nplt.grid()\nplt.xlabel(r'f',size=18)\nplt.ylabel(r'Power Spectrum $P(f)$',size=20)\nplt.title(r'FFT[DOW]', size=21)\nplt.tick_params(axis='both', which='major', labelsize=15)\nplt.tick_params(axis='both', which='minor', labelsize=12)\nplt.savefig('5_1.png')\nplt.show()\n\n\nplt.figure(figsize=(13,10))\nplt.plot(t,dow,label='Original Data')\nplt.grid()\nplt.xlabel(r'Days',size=18)\nplt.ylabel(r'DOW',size=20)\nplt.title(r'DOW Industrial Average', size=21)\nplt.tick_params(axis='both', which='major', labelsize=15)\nplt.tick_params(axis='both', which='minor', labelsize=12)\nplt.savefig('5_2.png')\n\ncompress = lambda data,freq,percent_acc: np.piecewise(data,[(freq-freq[0])<=\\\n                                                       (percent_acc/100)*(freq[-1]-freq[0])],[lambda data: data,0.])\n\ndow_fft2 = compress(dow_fft,f,2)\ndow2 = np.fft.irfft(dow_fft2)\nplt.plot(t,dow2,label=r'%d percent Fourier modes Accepted'%2)\nplt.legend(loc='best', prop={'size': 16})\nplt.show()\n\n#---------------------------------------------------------------------------------\n\nf = np.linspace(0,sampling,N)\nn = np.arange(0,N,1)\nplt.figure(figsize=(13,10))\nplt.plot(t,dow,label='Original Data')\nplt.grid()\nplt.xlabel(r'Days',size=18)\nplt.ylabel(r'DOW',size=20)\nplt.title(r'DOW Industrial Average', size=21)\nplt.tick_params(axis='both', which='major', labelsize=15)\nplt.tick_params(axis='both', which='minor', labelsize=12)\ndow_dct = fftpack.dct(dow, norm='ortho')\ndow_dct2 = compress(dow_dct,f,2)\ndow2 = fftpack.idct(dow_dct2, norm='ortho')\nplt.plot(t,dow2,label=r'%d percent Cosine Transform modes Accepted'%2)\nplt.legend(loc='best', prop={'size': 16})\nplt.savefig('5_3.png')\nplt.show()", "meta": {"hexsha": "5f7dc22881eccdaa30ba7301393960049822feea", "size": 2053, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw4/05/5.py", "max_stars_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_stars_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:47:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:05:39.000Z", "max_issues_repo_path": "hw4/05/5.py", "max_issues_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_issues_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw4/05/5.py", "max_forks_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_forks_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-21T17:33:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T02:58:56.000Z", "avg_line_length": 29.7536231884, "max_line_length": 116, "alphanum_fraction": 0.6551388212, "include": true, "reason": "import numpy,from scipy", "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951703918909, "lm_q2_score": 0.9184802445831379, "lm_q1q2_score": 0.8826151560480228}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy.random import sample\nimport seaborn as sns\n\nfrom multiple_linear_and_polynomial_regression.polynomial_LR import polynomial_linear_regression\n\nsns.set()\n\ndef make_polynomial(X, degrees):\n    number_of_inputs = len(X)\n    polynomial_data = [np.ones(number_of_inputs)]\n    for degree in range(degrees):\n        polynomial_data.append(np.power(X, degree+1))\n\n    return np.vstack(polynomial_data).T\n\ndef fit_and_display(X, y, sample_number, degrees):\n    number_of_inputs = len(X)\n    train_samples_indeces = np.random.choice(number_of_inputs, sample_number)\n    X_train = X[train_samples_indeces]\n    y_train = y[train_samples_indeces]\n\n    plt.figure()\n    plt.scatter(X_train, y_train)\n    plt.show()\n\n    X_train_polynomial = make_polynomial(X_train, degrees)\n    w, _ = polynomial_linear_regression(X_train_polynomial, y_train)\n\n    X_polynomial = make_polynomial(X, degrees)\n    y_hat = X_polynomial.dot(w)\n\n    plt.figure()\n    plt.plot(X,y, label='original data')\n    plt.plot(X,y_hat, label='predicted data')\n    plt.plot(X_train, y_train, 'r*', label='train data')\n    plt.title(\"Degree = %d\" %degrees)\n    plt.legend()\n    plt.show()\n\ndef mse(x, y):\n    d = x - y\n    return d.dot(d) / len(d)\n\ndef plot_train_vs_test_curves(X, y, sample_number=20, max_degrees=20):\n    number_of_inputs = len(X)\n    train_samples_indeces = np.random.choice(number_of_inputs, sample_number)\n    X_train = X[train_samples_indeces]\n    y_train = y[train_samples_indeces]\n\n    test_indeces = [index for index in range(number_of_inputs) if index not in train_samples_indeces]\n    X_test = X[test_indeces]\n    y_test = y[test_indeces]\n\n    MSEs_train = []\n    MSEs_test = []\n\n    for degree in range(max_degrees+1):\n        X_train_polynomial = make_polynomial(X_train, degree)\n        w, y_hat_train = polynomial_linear_regression(X_train_polynomial, y_train)\n        mse_train = mse(y_train, y_hat_train)\n\n        MSEs_train.append(mse_train)\n\n        X_test_polynomial = make_polynomial(X_test, degree)\n        y_hat_test = X_test_polynomial.dot(w)\n        mse_test = mse(y_test, y_hat_test)\n\n        MSEs_test.append(mse_test)\n\n    plt.figure()\n    plt.plot(MSEs_train, label='Train MSEs')\n    plt.plot(MSEs_test, label='Test MSEs')\n    plt.ylabel('MSEs')\n    plt.xlabel('Polynomial Degrees')\n    plt.legend()\n    plt.show()\n\nif __name__ == '__main__':\n\n    number_of_points = 100\n    X = np.linspace(0, 6 * np.pi, number_of_points)\n    y = np.sin(X)\n\n    plt.figure()\n    plt.plot(X,y)\n    plt.show()\n\n    for degrees in (5, 6, 7, 8, 9):\n        fit_and_display(X, y, sample_number=10, degrees=degrees)\n\n    plot_train_vs_test_curves(X, y)\n\n", "meta": {"hexsha": "2453369ef06a05add25a16dd50323513dbebe974", "size": 2692, "ext": "py", "lang": "Python", "max_stars_repo_path": "practical_machine_learning_issues/generalization_and_overfitting.py", "max_stars_repo_name": "AndreiRoibu/LinearRegression", "max_stars_repo_head_hexsha": "fffb7b555e717836e9e449bcca68ef8d3d8c7918", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-28T12:49:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T12:49:40.000Z", "max_issues_repo_path": "practical_machine_learning_issues/generalization_and_overfitting.py", "max_issues_repo_name": "AndreiRoibu/LinearRegression", "max_issues_repo_head_hexsha": "fffb7b555e717836e9e449bcca68ef8d3d8c7918", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practical_machine_learning_issues/generalization_and_overfitting.py", "max_forks_repo_name": "AndreiRoibu/LinearRegression", "max_forks_repo_head_hexsha": "fffb7b555e717836e9e449bcca68ef8d3d8c7918", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3368421053, "max_line_length": 101, "alphanum_fraction": 0.6968796434, "include": true, "reason": "import numpy,from numpy", "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737735, "lm_q2_score": 0.9184802406781396, "lm_q1q2_score": 0.8826151553768847}}
{"text": "import numpy as np\n\ndef calculate_distance(rA, rB):\n    \"\"\"\n    This function calculates the distance between two points\n\n    Parameters\n    ----------\n    rA, rB : np.ndarray\n        The coordinates of each point.\n\n    Returns\n    -------\n    distance : float\n        The distance between two vectors.\n\n    Examples\n    --------\n    >>> r1 = np.array([0,0,0])\n    >>> r2 = np.array([3.0,0,0,])\n    >>> calculate_distance(r1_r2)\n    3.0\n    \"\"\"\n    \n    dist_vec = (rA-rB)\n    distance = np.linalg.norm(dist_vec)\n    return distance\n\ndef calculate_angle(rA, rB, rC, degrees=False):\n    # Calculate the angle between three points. Answer is given in radians by default, but can be given in degrees\n    # by setting degrees=True\n    ab_diff = rA - rB\n    bc_diff = rB - rC\n    theta = np.arccos(np.dot(ab_diff, bc_diff)/(np.linalg.norm(ab_diff)*np.linalg.norm(bc_diff)))\n\n    if degrees:\n        return np.degrees(theta)\n    else:\n        return theta\n", "meta": {"hexsha": "e5bdcba8ef834d02244b3cef0b9d16c496266771", "size": 950, "ext": "py", "lang": "Python", "max_stars_repo_path": "molecool/measure.py", "max_stars_repo_name": "hansence1/MoleCOOL", "max_stars_repo_head_hexsha": "80d0f7dca09d78f1e410b7a794884779f7a89e34", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "molecool/measure.py", "max_issues_repo_name": "hansence1/MoleCOOL", "max_issues_repo_head_hexsha": "80d0f7dca09d78f1e410b7a794884779f7a89e34", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "molecool/measure.py", "max_forks_repo_name": "hansence1/MoleCOOL", "max_forks_repo_head_hexsha": "80d0f7dca09d78f1e410b7a794884779f7a89e34", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.75, "max_line_length": 114, "alphanum_fraction": 0.6073684211, "include": true, "reason": "import numpy", "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769142064209, "lm_q2_score": 0.9046505434556231, "lm_q1q2_score": 0.8825561856195985}}
{"text": "import numpy as np\n\nfrom utils import inc_index, dec_index\n\ndef gradient_approximation(f,x,h=1e-8):\n    '''\n    Numerical approximation of gradient for function f using forward differences.\n    Args:\n        f (lambda expression): definition of function f.\n        x (array): numpy array that holds values where gradient will be computed.\n        h (float): step size for forward differences, tipically h=1e-8\n    Returns:\n        gf (array): numerical approximation to gradient of f.\n    '''\n    n = x.size\n    gf = np.zeros(n)\n    f_x = f(x)\n    for i in np.arange(n):\n        inc_index(x,i,h)\n        gf[i] = f(x) - f_x\n        dec_index(x,i,h)\n    return gf/h\ndef Hessian_approximation(f,x,h=1e-6):\n    '''\n    Numerical approximation of Hessian for function f using forward differences.\n    Args:\n        f (lambda expression): definition of function f.\n        x (array): numpy array that holds values where Hessian will be computed.\n        h (float): step size for forward differences, tipically h=1e-6\n    Returns:\n        Hf (array): numerical approximation to Hessian of f.\n    '''\n    n = x.size\n    Hf = np.zeros((n,n))\n    f_x = f(x)\n    for i in np.arange(n):\n        inc_index(x,i,h)\n        f_x_inc_in_i = f(x)\n        for j in np.arange(i,n):\n            inc_index(x,j,h)\n            f_x_inc_in_i_j = f(x)\n            dec_index(x,i,h)\n            f_x_inc_in_j = f(x)\n            dif = f_x_inc_in_i_j-f_x_inc_in_i-f_x_inc_in_j+f_x\n            Hf[i,j] = dif\n            if j != i:\n                Hf[j,i] = dif\n            dec_index(x,j,h)\n            inc_index(x,i,h)\n        dec_index(x,i,h)\n    return Hf/h**2", "meta": {"hexsha": "49e15a24e19e3b023ae71b9678ca8bc96b43ddaf", "size": 1628, "ext": "py", "lang": "Python", "max_stars_repo_path": "temas/IV.optimizacion_convexa_y_machine_learning/algoritmos/Python/numerical_differentiation.py", "max_stars_repo_name": "dapivei/analisis-numerico-computo-cientifico", "max_stars_repo_head_hexsha": "3d4ee4eb9e7610135adf77133912fe513178aa8a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "temas/IV.optimizacion_convexa_y_machine_learning/algoritmos/Python/numerical_differentiation.py", "max_issues_repo_name": "dapivei/analisis-numerico-computo-cientifico", "max_issues_repo_head_hexsha": "3d4ee4eb9e7610135adf77133912fe513178aa8a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "temas/IV.optimizacion_convexa_y_machine_learning/algoritmos/Python/numerical_differentiation.py", "max_forks_repo_name": "dapivei/analisis-numerico-computo-cientifico", "max_forks_repo_head_hexsha": "3d4ee4eb9e7610135adf77133912fe513178aa8a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9215686275, "max_line_length": 81, "alphanum_fraction": 0.5847665848, "include": true, "reason": "import numpy", "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.975576914916509, "lm_q2_score": 0.9046505357435622, "lm_q1q2_score": 0.8825561787382715}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef sigmoid(z):\n    return 1.0 / (1.0 + np.exp(-z))\n\ndef plot_sigmoid():\n\tz = np.arange(-7, 7, 0.1)\n\tphi_z = sigmoid(z)\n\n\tplt.plot(z, phi_z)\n\tplt.axvline(0.0, color='k')\n\tplt.ylim(-0.1, 1.1)\n\tplt.xlabel('z')\n\tplt.ylabel('$\\phi (z)$')\n\n\t# y axis ticks and gridline\n\tplt.yticks([0.0, 0.5, 1.0])\n\tax = plt.gca()\n\tax.yaxis.grid(True)\n\n\tplt.tight_layout()\n\t# plt.savefig('./figures/sigmoid.png', dpi=300)\n\tplt.show()\n\ndef cost_1(z):\n    return - np.log(sigmoid(z))\n\ndef cost_0(z):\n    return - np.log(1 - sigmoid(z))\n\ndef plot_cost():\n\tz = np.arange(-10, 10, 0.1)\n\tphi_z = sigmoid(z)\n\n\tc1 = [cost_1(x) for x in z]\n\tplt.plot(phi_z, c1, label='J(w) if y=1')\n\n\tc0 = [cost_0(x) for x in z]\n\tplt.plot(phi_z, c0, linestyle='--', label='J(w) if y=0')\n\n\tplt.ylim(0.0, 5.1)\n\tplt.xlim([0, 1])\n\tplt.xlabel('$\\phi$(z)')\n\tplt.ylabel('J(w)')\n\tplt.legend(loc='best')\n\tplt.tight_layout()\n\t# plt.savefig('./figures/log_cost.png', dpi=300)\n\tplt.show()\n\ndef main():\n\tplot_sigmoid()\n\tplot_cost()\n\nif __name__ == '__main__':\n    main()\n\n", "meta": {"hexsha": "e09129d22af4500568bf435bd16f2bfb24b85797", "size": 1064, "ext": "py", "lang": "Python", "max_stars_repo_path": "books/python-machine-learning-book/code/ch02/sigmoid.py", "max_stars_repo_name": "tuanvu216/machine-learning-ipython-notebooks", "max_stars_repo_head_hexsha": "efc45b02420e5b6853b7f82ff37481ee971abde7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-02-21T06:56:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T02:19:14.000Z", "max_issues_repo_path": "books/python-machine-learning-book/code/ch02/sigmoid.py", "max_issues_repo_name": "tuanvu216/machine-learning-ipython-notebooks", "max_issues_repo_head_hexsha": "efc45b02420e5b6853b7f82ff37481ee971abde7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "books/python-machine-learning-book/code/ch02/sigmoid.py", "max_forks_repo_name": "tuanvu216/machine-learning-ipython-notebooks", "max_forks_repo_head_hexsha": "efc45b02420e5b6853b7f82ff37481ee971abde7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-06-19T18:41:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T02:19:16.000Z", "avg_line_length": 18.0338983051, "max_line_length": 57, "alphanum_fraction": 0.6062030075, "include": true, "reason": "import numpy", "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075777163566, "lm_q2_score": 0.9173026601509101, "lm_q1q2_score": 0.8825438403905623}}
{"text": "#!/usr/bin/env python\n\n#This script will introduce us to Scipy, a library useful for scientific computation\n#Adapted from https://docs.scipy.org/doc/scipy/reference/tutorial/integrate.html\n\n#Integration\n\n#Using known function\nprint(\"Integration:\")\nfrom scipy.integrate import quad\ndef integrand(x, a, b):\n    return a*x**2 + b\n\na = 2\nb = 1\nI = quad(integrand, 0, 1, args=(a,b))\nprint(\"Integral of 2x^2 + 1 from x=0..1: {}\".format(I[0]))\n\n#Using arbitrarily spaced samples\nimport numpy as np\ndef f1(x):\n   return x**2\n\nx = np.array([1,3,4])\ny1 = f1(x)\nfrom scipy.integrate import simps\nI1 = simps(y1, x)\nprint(\"Integral of x^2 evaluated at {}: {}\".format(x.tolist(), I1))\n\n#Optimization\nprint(\"\\nOptimization:\")\nimport numpy as np\nfrom scipy.optimize import minimize\ndef rosen(x):\n    \"\"\"The Rosenbrock function\"\"\"\n    return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)\n\nx0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])\nprint(\"Nelder-Mead simplex method:\")\nres = minimize(rosen, x0, method='nelder-mead', options={'xtol': 1e-8, 'disp': True})\n\ndef rosen_der(x):\n    xm = x[1:-1]\n    xm_m1 = x[:-2]\n    xm_p1 = x[2:]\n    der = np.zeros_like(x)\n    der[1:-1] = 200*(xm-xm_m1**2) - 400*(xm_p1 - xm**2)*xm - 2*(1-xm)\n    der[0] = -400*x[0]*(x[1]-x[0]**2) - 2*(1-x[0])\n    der[-1] = 200*(x[-1]-x[-2]**2)\n    return der\n\nprint(\"Broyden-Fletcher-Goldfarb-Shanno method:\")\nres1 = minimize(rosen, x0, method='BFGS', jac=rosen_der, options={'disp': True})\n\n#Linear Algebra\n\nprint(\"\\nLinear algebra:\")\n\n#inverse:\nimport numpy as np\nA = np.array([[1,3,5],[2,5,1],[2,3,8]])\nprint(\"A:\\n{}\\n\".format(A))\nprint(\"A^(-1):\\n{}\\n\".format(np.linalg.inv(A)))\n\n#Systems solution\nA = np.array([[1, 2], [3, 4]])\nb = np.array([[5], [6]])\nprint(\"A:\\n{}\\n\".format(A))\nprint(\"b:\\n{}\\n\".format(b))\nprint(\"A^(-1) b:\\n{}\\n\".format(np.linalg.solve(A, b)))\nprint(\"det(A): {}\".format(np.linalg.det(A)))\nprint(\"||A||_inf: {}\".format(np.linalg.norm(A, np.inf)))\n", "meta": {"hexsha": "c26d031640cbf7abd50ca0dccf07477ccbe70351", "size": 1926, "ext": "py", "lang": "Python", "max_stars_repo_path": "section1/code/scipy_script.py", "max_stars_repo_name": "brandonfranz13/aa274-sections", "max_stars_repo_head_hexsha": "191fb0d249240969117eb3bd95b1b6ee370d276f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-09-30T06:49:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-07T23:32:38.000Z", "max_issues_repo_path": "section1/code/scipy_script.py", "max_issues_repo_name": "brandonfranz13/aa274-sections", "max_issues_repo_head_hexsha": "191fb0d249240969117eb3bd95b1b6ee370d276f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "section1/code/scipy_script.py", "max_forks_repo_name": "brandonfranz13/aa274-sections", "max_forks_repo_head_hexsha": "191fb0d249240969117eb3bd95b1b6ee370d276f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-09-21T22:07:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-29T23:21:44.000Z", "avg_line_length": 26.3835616438, "max_line_length": 85, "alphanum_fraction": 0.6168224299, "include": true, "reason": "import numpy,from scipy", "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9830850882200038, "lm_q2_score": 0.8976952852648488, "lm_q1q2_score": 0.8825108487092753}}
{"text": "#\n# statistics.py\n#\n\nimport copy\nimport math\nimport numpy\nimport quicksort\n\ndef mean(data):\n\n    return sum(data)/len(data)\n\ndef median(data):\n\n    index = len(data)//2\n    is_odd = len(data) % 2 > 0\n    data = quicksort.sort(copy.deepcopy(data))\n\n    return data[index] if is_odd else (data[index]+data[index-1])/2\n\ndef mode(data):\n\n    lookup = {}\n\n    for n in data: lookup[n] = 0\n    for n in data: lookup[n] += 1\n\n    return sorted(lookup, key=lookup.__getitem__)[-1]\n\ndef standard_deviation(data=[], is_sample=False):\n\n    dmean = mean(data)\n    diffs = [math.pow(n-dmean, 2) for n in data]\n    divisor = len(data)-1 if is_sample else len(data)\n\n    return math.sqrt(sum(diffs)/divisor)\n\ndef variance(data, is_sample=False):\n\n    return math.pow(standard_deviation(data, is_sample), 2)\n\ndef covariance(x=[], y=[], is_sample=False):\n\n    xmean = mean(x)\n    ymean = mean(y)\n\n    xvect = [(n-xmean) for n in x]\n    yvect = [(n-ymean) for n in y]\n\n    divisor = len(x)-1 if is_sample else len(x)\n    result = numpy.dot(xvect, yvect) / divisor\n\n    return result\n\ndef correlation(x=[], y=[], is_sample=False):\n\n    xstd = standard_deviation(x, is_sample)\n    ystd = standard_deviation(y, is_sample)\n\n    return covariance(x, y, is_sample) / xstd / ystd\n", "meta": {"hexsha": "5c2749b0ea11e5239679a076f3f8026fe5e2fb06", "size": 1255, "ext": "py", "lang": "Python", "max_stars_repo_path": "conveniences/statistics.py", "max_stars_repo_name": "mateusnbm/ai-conveniences", "max_stars_repo_head_hexsha": "4a0cd0d761f1d534149f9f0ab03f5f94e4290580", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "conveniences/statistics.py", "max_issues_repo_name": "mateusnbm/ai-conveniences", "max_issues_repo_head_hexsha": "4a0cd0d761f1d534149f9f0ab03f5f94e4290580", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conveniences/statistics.py", "max_forks_repo_name": "mateusnbm/ai-conveniences", "max_forks_repo_head_hexsha": "4a0cd0d761f1d534149f9f0ab03f5f94e4290580", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2419354839, "max_line_length": 67, "alphanum_fraction": 0.6462151394, "include": true, "reason": "import numpy", "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426435557124, "lm_q2_score": 0.905989826094673, "lm_q1q2_score": 0.8824727252438355}}
{"text": "import numpy as np\n\ndef bisection(f,a,b,epsilon=1.0e-6):\n\t\"\"\"Find the root of the function f via bisection where the root lies within [a,b]\n\tArgs:\n\t\tf: function to find root of\n\t\ta: left-side of interval\n\t\tb: right-side of interval\n\t\tepsilon: tolerance\n\tReturns:\n\t\testimate of root\n\t\"\"\"\n\n\tassert (b>a)\n\tassert (f(a)*f(b) < 0)\n\tdelta = b - a\n\tprint(\"We expect\",int(np.ceil(np.log(delta/epsilon)/np.log(2))),\"iterations\")\n\titerations = 0\n\twhile (delta > epsilon):\n\t\tc = (a+b)*0.5\n\t\tif (f(a)*f(c) < 0):\n\t\t\tb = c\n\t\telif (f(b)*f(c) < 0):\n\t\t\ta=c\n\t\telse:\n\t\t\treturn c\n\t\tdelta = b-a\n\t\titerations += 1\n\tprint(\"It took\",iterations,\"iterations\")\n\treturn c #return midpoint of interval\n\ndef false_position(f,a,b,epsilon=1.0e-6):\n\t\"\"\"Find the root of the function f via false position where the root lies within [a,b]\n\tArgs:\n\t\tf: function to find root of\n\t\ta: left-side of interval\n\t\tb: right-side of interval\n\t\tepsilon: tolerance\n\tReturns:\n\t\testimate of root\n\t\"\"\"\n\tassert (b>a)\n\tassert (f(a)*f(b) < 0)\n\tdelta = b - a\n\titerations = 0\n\tresidual = 1.0\n\twhile (np.fabs(residual) > epsilon):\n\t\tm = (f(b)-f(a))/(b-a)\n\t\tc = a - f(a)/m\n\t\tif (f(a)*f(c) < 0):\n\t\t\tb=c\n\t\telif (f(b)*f(c) < 0):\n\t\t\ta=c\n\t\telse:\n\t\t\tprint(\"It took\",iterations,\"iterations\")\n\t\t\treturn c\n\t\tresidual = f(c)\n\t\titerations += 1\n\tprint(\"It took\",iterations,\"iterations\")\n\treturn c #return c\n\ndef ridder(f,a,b,epsilon=1.0e-6):\n\t\"\"\"Find the root of the function f via Ridder's Method where the root lies within [a,b]\n\tArgs:\n\t\tf: function to find root of\n\t\ta: left-side of interval\n\t\tb: right-side of interval\n\t\tepsilon: tolerance\n\tReturns:\n\t\testimate of root\n\t\"\"\"\n\tassert (b>a)\n\tassert (f(a)*f(b) < 0)\n\tdelta = b - a\n\titerations = 0\n\tresidual = 1.0\n\twhile (np.fabs(residual) > epsilon):\n\t\tc = 0.5*(b+a)\n\t\td = 0.0\n\t\tif (f(a) - f(b) > 0):\n\t\t\td = c + (c-a)*f(c)/np.sqrt(f(c)**2-f(a)*f(b))\n\t\telse:\n\t\t\td = c - (c-a)*f(c)/np.sqrt(f(c)**2-f(a)*f(b))\n\t\t#now see which part of interval root is in\n\t\tif (f(a)*f(d) < 0):\n\t\t\tb=d\n\t\telif (f(b)*f(d) < 0):\n\t\t\ta=d\n\t\tresidual = f(d)\n\t\titerations += 1\n\tprint(\"It took\",iterations,\"iterations\")\n\treturn d #return c", "meta": {"hexsha": "943e915f2899181e9c864497ba3f2999508348e5", "size": 2089, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch12.py", "max_stars_repo_name": "DrRyanMc/CompNucEng", "max_stars_repo_head_hexsha": "55d36abea64c9298092dee0b539bfaccae3f49a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-09-29T19:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T20:08:08.000Z", "max_issues_repo_path": "ch12.py", "max_issues_repo_name": "AllSafeCyberSecur1ty/Nuclear-Engineering", "max_issues_repo_head_hexsha": "302d6dcc7c0a85a9191098366b076cf9cb5a9f6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-04-07T02:26:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-18T23:04:31.000Z", "max_forks_repo_path": "ch12.py", "max_forks_repo_name": "DrRyanMc/CompNucEng", "max_forks_repo_head_hexsha": "55d36abea64c9298092dee0b539bfaccae3f49a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-03T17:34:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T03:48:45.000Z", "avg_line_length": 22.7065217391, "max_line_length": 88, "alphanum_fraction": 0.6108185735, "include": true, "reason": "import numpy", "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.931462514578343, "lm_q1q2_score": 0.8824499361300875}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as st\n\ndata = np.loadtxt(\"dataset.txt\")\nplt.hist(data)\nplt.show()\n\n#Centrality can be defined by average\n\"\"\"def get_mean(x_input):\n  sum = 0\n  for x in x_input:\n    sum += x\n  return sum / len(x_input)\n#print(get_mean([2,4,6,8]))\n\"\"\"\nmean = np.mean(data)\nprint(\"mean     data.mean()     np.average(data)\")\nprint(mean,data.mean(),np.average(data))\n\n#invoke data.mean() when working with pandas dataframe/ numpy array but not\n#on list\n#np.average(data) identical to mean but we can also pass in weights\nprint()\nprint()\n#Median - sort from small to largest and then middle number\n#If even no's then average of central two numbers (n/2 + n+1/2)\n\n\"\"\"\ndef get_median(x_inp):\n    mid = len(x_inp)//2\n    if len(x_inp) %2 == 1:\n        return sorted(x_inp)[mid]\n    else:\n        return 0.5 * np.sum(sorted(x_inp)[mid-1:mid+1])\nprint(get_median([5,4,2,1,2]))\n\"\"\"\n\nmedian = np.median(data)\nprint(\"Median\")\nprint(median)\nprint()\nprint()\n#MEANS ARE SENSETIVE TO OUTLIERS BUT MEDIANS ARE NOT\n\noutlier = np.insert(data,0,5000)\nplt.hist(data,label=\"Data\")\nplt.axvline(np.mean(data),ls=\"--\",label=\"Mean Data\")\nplt.axvline(np.median(data),ls=\":\",label=\"Median Data\")\nplt.axvline(np.mean(outlier),c='r',ls=\"--\",label=\"Mean Outlier\",alpha=0.7)\nplt.axvline(np.median(outlier),c='r',ls=\":\",label=\"Median Outlier\",alpha=0.7)\nplt.legend()\nplt.xlim(0,20)\nplt.show()\n\n\n#Mode are the most common data in dataset\n#If continuous, then bin the data\n\n\"\"\"\ndef get_mode(x):\n    values,counts = np.unique(x,return_counts=True)\n    max_count_index = np.argmax(counts)\n    return values[max_count_index]\n\nprint(get_mode[1,7,5,6,3,1,1,2])\n\"\"\"\nprint()\nmode = st.mode(data)\nprint(\"Mode\")\nprint(mode)\nprint()\nprint()\n#get bins for more numbers\n\nhist,edges = np.histogram(data,bins=100)\nedge_centers = 0.5 * (edges[1:] + edges[:-1]) #first to last\nmode = edge_centers[hist.argmax()]  #get the index of highest value in histogram\n#then get bin center for that and that is mode\nprint(\"Mode using KDE\")\nprint(mode)\n\n#if you increase bins amount then mode changes\n#to correct above problem - smooth data using scipy in kde\n\nkde = st.gaussian_kde(data)\nxvals = np.linspace(data.min(),data.max(),1000)\nyval = kde(xvals)\nmode = xvals[yval.argmax()]\nplt.hist(data,bins=100,density=True,label=\"Data hist\",histtype=\"step\")\nplt.plot(xvals,yval,label=\"KDE\")\nplt.axvline(mode,label=\"Mode\")\nplt.legend()\nplt.show()\n\n#with GAUSSIAN Smoothening, now when we change the bin value the kde remains\n#same\n\n#TOTAL COMPARISON OF CENTRAL TENDENCY\n\nplt.hist(data,bins=100,label=\"Data\",alpha=0.5)\nplt.axvline(mean,label=\"Mean\",ls=\"--\",c='r')\nplt.axvline(median,label=\"Median\",ls=\":\",c='b')\nplt.axvline(mode,label=\"Mode\",ls=\"-\",c='g')\nplt.legend()\nplt.show()\n#data is skewed, is the inference\n", "meta": {"hexsha": "e3135bf9a0e49f479ab4389f7c2018fc47afcdbc", "size": 2798, "ext": "py", "lang": "Python", "max_stars_repo_path": "characterising_1d.py", "max_stars_repo_name": "WestHamster/Feature_engg", "max_stars_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "characterising_1d.py", "max_issues_repo_name": "WestHamster/Feature_engg", "max_issues_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "characterising_1d.py", "max_forks_repo_name": "WestHamster/Feature_engg", "max_forks_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9074074074, "max_line_length": 80, "alphanum_fraction": 0.6979985704, "include": true, "reason": "import numpy,import scipy", "num_tokens": 825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846722794541, "lm_q2_score": 0.9019206857566127, "lm_q1q2_score": 0.882425374556044}}
{"text": "\"\"\"\nContaining an example for obtaining the gradients through the implicit relation\ngiven by a linear system.\n\nAx = b\n\nwith\nJ = 0.5 * (x_r - x)^T(x_r - x)\n\nwhereas x_r is a reference solution.\n\"\"\"\n\nimport numpy as np\nimport time\n\nif __name__ == \"__main__\":\n\n    A = np.array([\n        [10, 2, 1],\n        [2, 5, 1],\n        [1, 1, 3]\n    ])\n\n    ##### Creating a reference solution\n\n    b_true = np.array([5, 4, 3])\n    x_ref = np.linalg.solve(A, b_true)\n\n    #### [A] Solve the classical system\n    b_guess = np.ones(3)\n\n    x = np.linalg.solve(A, b_guess)\n\n    # Evaluate the loss function\n    J = 0.5 * (x - x_ref).T @ (x - x_ref)\n\n    #### [B] Obtaining gradients\n\n    ### [3] Adjoint Sensitivities\n\n    time_adjoint = time.time_ns()\n\n    del_J__del_theta = np.zeros((1, 3))\n    del_J__del_x = (x - x_ref).T\n    d_b__d_theta = np.eye(3)\n\n    # Solve adjoint system\n    adjoint_variable = np.linalg.solve(A.T, del_J__del_x.T)\n\n    # Plug in\n    d_J__d_theta__adjoint = del_J__del_theta + adjoint_variable.T @ d_b__d_theta\n\n    time_adjoint = time.time_ns() - time_adjoint\n\n    ### [2] Forward Sensitivities\n\n    time_forward = time.time_ns()\n\n    del_J__del_theta = np.zeros((1, 3))\n    del_J__del_x = (x - x_ref).T\n    d_b__d_theta = np.eye(3)\n\n    # Solve forward system\n    d_x__d_theta = np.linalg.solve(A, d_b__d_theta)\n\n    # Plug in\n    d_J__d_theta__forward = del_J__del_theta + del_J__del_x @ d_x__d_theta\n\n    time_forward = time.time_ns() - time_forward\n\n    ### [1] Finite differences\n\n    time_finite_differences = time.time_ns()\n\n    eps = 1.0e-6\n\n    d_J__d_theta__finite_difference = np.empty((1, 3))\n\n    for i in range(3):\n        b_augmented = b_guess.copy()\n        b_augmented[i] += eps\n\n        x_augmented = np.linalg.solve(A, b_augmented)\n        J_augmented = 0.5 * (x_augmented - x_ref).T @ (x_augmented - x_ref)\n\n        d_J__d_theta__finite_difference[0, i] = (J_augmented - J) / eps\n    \n    time_finite_differences = time.time_ns() - time_finite_differences\n    \n    #### Reporting the Results\n\n    print(\"The loss function\")\n    print(J)\n\n    print()\n\n    np.set_printoptions(precision=16)\n    print(\"Sensitivities by the Adjoint Method\")\n    print(d_J__d_theta__adjoint)\n    print(\"Sensitivities by the Forward Method\")\n    print(d_J__d_theta__forward)\n    print(\"Sensitivities by Finite Differences\")\n    print(d_J__d_theta__finite_difference)\n\n    print()\n\n    print(\"Time of the approaches [ns] - lower is better\")\n    print(\"Sensitivities by the Adjoint Method\")\n    print(time_adjoint)\n    print(\"Sensitivities by the Forward Method\")\n    print(time_forward)\n    print(\"Sensitivities by Finite Differences\")\n    print(time_finite_differences)\n\n", "meta": {"hexsha": "0426e278eec722bf447ee94a99d2267682070ba5", "size": 2684, "ext": "py", "lang": "Python", "max_stars_repo_path": "english/adjoints_sensitivities_automatic_differentiation/adjoint_linear_system_example.py", "max_stars_repo_name": "bartdavids/machine-learning-and-simulation", "max_stars_repo_head_hexsha": "4a4ca74e2252fa8311112e38b46ed46da3c105e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 110, "max_stars_repo_stars_event_min_datetime": "2021-05-20T12:38:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:00:14.000Z", "max_issues_repo_path": "english/adjoints_sensitivities_automatic_differentiation/adjoint_linear_system_example.py", "max_issues_repo_name": "uarsln/machine-learning-and-simulation", "max_issues_repo_head_hexsha": "942c75e74de44cf17ee247449a1490ec7e802a46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-20T16:50:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T19:44:47.000Z", "max_forks_repo_path": "english/adjoints_sensitivities_automatic_differentiation/adjoint_linear_system_example.py", "max_forks_repo_name": "uarsln/machine-learning-and-simulation", "max_forks_repo_head_hexsha": "942c75e74de44cf17ee247449a1490ec7e802a46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 40, "max_forks_repo_forks_event_min_datetime": "2021-05-20T12:56:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T20:54:37.000Z", "avg_line_length": 23.3391304348, "max_line_length": 80, "alphanum_fraction": 0.6516393443, "include": true, "reason": "import numpy", "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305349799242, "lm_q2_score": 0.916109614162018, "lm_q1q2_score": 0.8824247537495324}}
{"text": "import numpy as np\nimport numpy.random as np_random\n\nclass Solution:\n\tdef monteCarloPiEstimate(self, num_samples=1_000_000):\n\t\t\"\"\"\n\t\tWe can estimate pi by randomly picking points in the square\n\t\t(0, 0) <= (x, y) <= (1, 1)\n\t\tand computing their distance. If their distance is <= 1 then they are\n\t\tinside the unit circle. The ratio of the number of points inside the\n\t\tunit circle to the number of points picked approximates the ratio of\n\t\tthe quarter circle and square areas, (pi / 4) : 1. Multiplying the ratio\n\t\tby 4 yields an estimate for pi. Ensuring 3 decimal places of accuracy,\n\t\trequires at least 1,000,000 points as error is preportional to\n\t\t1/(sqrt(num_points))\n\t\t\"\"\"\n\t\tx_samples = np_random.sample(num_samples)\n\t\ty_samples = np_random.sample(num_samples)\n\t\tsamples_within_unit_circle = (x_samples**2 + y_samples**2) <= 1\n\t\treturn round(\n\t\t\t4 * np.count_nonzero(samples_within_unit_circle) / num_samples, 3\n\t\t)\n\nsoln = Solution()\nprint(soln.monteCarloPiEstimate())\nprint(soln.monteCarloPiEstimate())\nprint(soln.monteCarloPiEstimate())\nprint(soln.monteCarloPiEstimate())\nprint(soln.monteCarloPiEstimate())\n", "meta": {"hexsha": "53580362f71edb036b7f982f1706623d1c87b583", "size": 1115, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/daily_coding_problems/mailing_list/problem_14.py", "max_stars_repo_name": "kylecbrodie/daily_coding_problems", "max_stars_repo_head_hexsha": "87c0ce48c5546017c7df3fce56cd791cc0f2b53e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/daily_coding_problems/mailing_list/problem_14.py", "max_issues_repo_name": "kylecbrodie/daily_coding_problems", "max_issues_repo_head_hexsha": "87c0ce48c5546017c7df3fce56cd791cc0f2b53e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/daily_coding_problems/mailing_list/problem_14.py", "max_forks_repo_name": "kylecbrodie/daily_coding_problems", "max_forks_repo_head_hexsha": "87c0ce48c5546017c7df3fce56cd791cc0f2b53e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1666666667, "max_line_length": 74, "alphanum_fraction": 0.7515695067, "include": true, "reason": "import numpy", "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969785415552379, "lm_q2_score": 0.9099070042057362, "lm_q1q2_score": 0.8824145421876801}}
{"text": "# Import functions and libraries\r\nimport cv2\r\nimport os\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.fft import dct, idct\r\n\r\n# set image file to ../data/00.bmp\r\n# you are free to point to any other image files\r\nIMG_FILE = os.path.join(\"..\", \"data\", \"zelda.bmp\")\r\n\r\n# read image file, img is a gray scale image\r\nimg_gray = cv2.imread(IMG_FILE, cv2.IMREAD_GRAYSCALE)\r\nprint(f\"Reading {IMG_FILE}, img size(width,height): {img_gray.shape}\")\r\n\r\n\r\ndef dct2(a):\r\n    # 2D dct conversion\r\n    # convert image a from spatial domain to frequency domain\r\n    return dct(dct(a.T, norm='ortho').T, norm='ortho')\r\n\r\n\r\ndef idct2(a):\r\n    # 2D idct converstion\r\n    # convert image from freuqency domain back to spatial domain\r\n    return idct(idct(a.T, norm='ortho').T, norm='ortho')\r\n\r\n\r\n# create a variable to hold dct coefficients\r\nimF = dct2(img_gray)\r\nim_reconstructed = idct2(imF)\r\n\r\n# plot original and reconstructed images with matplotlib.pylab\r\nplt.gray()\r\nplt.subplot(121)\r\nplt.imshow(img_gray)\r\nplt.title('original image')\r\nplt.subplot(122)\r\nplt.imshow(im_reconstructed)\r\nplt.title('reconstructed image (DCT+IDCT)')\r\nplt.show()\r\n\r\n#compare the pixel value side by side\r\nh, v = 10, 10\r\norig_pix = img_gray[h, v]\r\nrecon_pix = im_reconstructed[h, v]\r\nprint(f\"pos {h},{v} orig:{orig_pix}, reconstructed:{recon_pix}\")\r\n\r\n# Question 1:\r\n# think about how to do DCT in a 8x8 block level\r\n# here is how to index an element in numpy\r\n# https://numpy.org/doc/stable/user/basics.indexing.html\r\n\r\n# Solution:\r\n'''\r\nimg_size = img_gray.shape\r\n# for forward 2d DCT on 8x8 block\r\ndct_8x8 = np.zeros(img_size)\r\nfor i in np.r_[:img_size[0]:8]:\r\n    for j in np.r_[:img_size[1]:8]:\r\n        # Apply DCT to the image every 8x8 block of it.\r\n        dct_8x8[i:(i+8), j:(j+8)] = dct(img_gray[i:(i+8), j:(j+8)])\r\n\r\n# now inverse 2d DCT on 8x8 block\r\ndct_8x8_reconstructed = np.zeros(img_size)\r\nfor i in np.r_[:img_size[0]:8]:\r\n    for j in np.r_[:img_size[1]:8]:\r\n        # Apply inverse DCT to the DCT results every 8x8 block of it.\r\n        dct_8x8_reconstructed[i:(i+8), j:(j+8)\r\n                              ] = idct(dct_8x8[i:(i+8), j:(j+8)])\r\nplt.gray()\r\nplt.subplot(131)\r\nplt.imshow(img_gray)\r\nplt.title('original image')\r\nplt.subplot(132)\r\nplt.imshow(dct_8x8_reconstructed)\r\nplt.title('reconstructed image (DCT+IDCT) 8x8 block')\r\nplt.subplot(133)\r\nplt.imshow(im_reconstructed)\r\nplt.title('reconstructed image (DCT+IDCT)')\r\nplt.show()\r\n'''\r\n", "meta": {"hexsha": "bd90debca81c90f2e67b35a5d1923bc9c3818fdf", "size": 2443, "ext": "py", "lang": "Python", "max_stars_repo_path": "L02/Q1_dct.py", "max_stars_repo_name": "lxpwj/mtd207_lab", "max_stars_repo_head_hexsha": "eb9154b3ae1e2ccd6efc327be33f1b8d6e7a46a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "L02/Q1_dct.py", "max_issues_repo_name": "lxpwj/mtd207_lab", "max_issues_repo_head_hexsha": "eb9154b3ae1e2ccd6efc327be33f1b8d6e7a46a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "L02/Q1_dct.py", "max_forks_repo_name": "lxpwj/mtd207_lab", "max_forks_repo_head_hexsha": "eb9154b3ae1e2ccd6efc327be33f1b8d6e7a46a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4337349398, "max_line_length": 71, "alphanum_fraction": 0.6745804339, "include": true, "reason": "import numpy,from scipy", "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854120593483, "lm_q2_score": 0.909907002984195, "lm_q1q2_score": 0.8824145378247142}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom math import sqrt\n\ndef func(x):\n    return x**2 - 2*x - 3\n\ndef fprime(x):\n    return 2*x - 2\n\n\ndef Func(x0):\n    x = np.linspace(-5, 7, 100)\n    plt.plot(x, func(x))\n    plt.plot(x0, func(x0), 'ro')\n    plt.xlabel('$x$')\n    plt.ylabel('$f(x)$')\n    plt.title('Objective Function')\n\ndef Path(xs, ys, x0):\n    Func(x0)\n    plt.plot(xs, ys, linestyle='--', marker='o', color='orange')\n    plt.plot(xs[-1], ys[-1], 'ro')\n    plt.show()\n\n\ndef GradientDescentSimple(func, fprime, x0, alpha, tol=1e-5, max_iter=1000):\n    # initialize x, f(x), and -f'(x)\n    xk = x0\n    fk = func(xk)\n    pk = -fprime(xk)\n    # initialize number of steps, save x and f(x)\n    num_iter = 0\n    curve_x = [xk]\n    curve_y = [fk]\n    # take steps\n    while abs(pk) > tol and num_iter < max_iter:\n        # calculate new x, f(x), and -f'(x)\n        xk = xk + alpha * pk\n        fk = func(xk)\n        pk = -fprime(xk)\n        # increase number of steps by 1, save new x and f(x)\n        num_iter += 1\n        curve_x.append(xk)\n        curve_y.append(fk)\n    # print results\n    if num_iter == max_iter:\n        print('Gradient descent does not converge.')\n    else:\n        print('Solution found:\\n  y = {:.4f}\\n  x = {:.4f}'.format(fk, xk))\n    \n    return curve_x, curve_y\n\nxs, ys = GradientDescentSimple(func, fprime, -4, alpha=0.8) # Earlier used alpha = 0.1\nPath(xs, ys, -4)\n\n# Solution found:\n#   y = -4.0000  \n#   x = 1.0000", "meta": {"hexsha": "3ff0cb91b3d6c2ade3040941089f52f11c978323", "size": 1460, "ext": "py", "lang": "Python", "max_stars_repo_path": "Gradient_Descent/GD.py", "max_stars_repo_name": "divyanshugit/Machine-Learning-Lab-EC792B", "max_stars_repo_head_hexsha": "2c0ceeef67dcbf9dd1135d0b4616d9f94205fd66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-12-17T05:44:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T08:24:10.000Z", "max_issues_repo_path": "Gradient_Descent/GD.py", "max_issues_repo_name": "divyanshugit/Machine-Learning-Lab-EC792B", "max_issues_repo_head_hexsha": "2c0ceeef67dcbf9dd1135d0b4616d9f94205fd66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gradient_Descent/GD.py", "max_forks_repo_name": "divyanshugit/Machine-Learning-Lab-EC792B", "max_forks_repo_head_hexsha": "2c0ceeef67dcbf9dd1135d0b4616d9f94205fd66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7457627119, "max_line_length": 86, "alphanum_fraction": 0.5636986301, "include": true, "reason": "import numpy", "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813451206063, "lm_q2_score": 0.9230391568941467, "lm_q1q2_score": 0.8824082148066568}}
{"text": "import numpy as np\nfrom numpy.linalg import inv\n\ndef setupLHS():\n    G1= 3.\n    G2= 5.\n    a = np.array([[G1+G2, -G2], [-G2, G2]])  \n    return a\n\ndef setupRHS():\n    I1= 2.\n    I2= 7.    \n    RHS= np.array([I1, I2])\n    return RHS\n\ndef checkInverse(a, ainv):\n    inverseOK= True\n    if not np.allclose(np.dot(a, ainv), np.eye(2)):\n        inverseOK= False\n    if not np.allclose(np.dot(ainv, a), np.eye(2)):\n        inverseOK= False\n    if inverseOK:\n        print \"OK 1 - matrix inverse self-check\"\n    else:\n        print \"Not OK 1\"\n\nif __name__ == \"__main__\":\n    a= setupLHS()\n    RHS= setupRHS()\n    \n    ainv = inv(a) \n    checkInverse(a, ainv)\n    \n    therm= ainv * RHS\n    V= np.dot(ainv, RHS)\n    \n    HeatSinkPerf= np.array([therm[0][0], therm[1][1]])\n    \n    V1RiseDueToI2= therm[0][1]\n    V2RiseDueToI1= therm[1][0]\n    \n    print HeatSinkPerf[0], V1RiseDueToI2, V[0]\n    print HeatSinkPerf[1], V2RiseDueToI1, V[1]  \n    \n    exactInverse= np.array([[1./3., 1./3.],[1./3., 8./15.]])\n    \n    if np.allclose(exactInverse, ainv):\n        print \"OK 2 - matrix inverse expected value\"\n    else:\n        print \"Not OK 2 - matrix inverse expected value\"\n    ", "meta": {"hexsha": "5db3ca394c834b53a3f7b96ecd4ceb93e15e83cd", "size": 1167, "ext": "py", "lang": "Python", "max_stars_repo_path": "matrixInvTest2x2.py", "max_stars_repo_name": "tomacorp/thermapythia", "max_stars_repo_head_hexsha": "d6392a9e9eb9a5123ae3031812a0b4f8324d7211", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-09-16T17:41:19.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-03T00:39:26.000Z", "max_issues_repo_path": "matrixInvTest2x2.py", "max_issues_repo_name": "tomacorp/thermapythia", "max_issues_repo_head_hexsha": "d6392a9e9eb9a5123ae3031812a0b4f8324d7211", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matrixInvTest2x2.py", "max_forks_repo_name": "tomacorp/thermapythia", "max_forks_repo_head_hexsha": "d6392a9e9eb9a5123ae3031812a0b4f8324d7211", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8823529412, "max_line_length": 60, "alphanum_fraction": 0.5638389032, "include": true, "reason": "import numpy,from numpy", "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290905469752, "lm_q2_score": 0.9086179068309441, "lm_q1q2_score": 0.8823852815154309}}
{"text": "# ipython --pylab\n\nfrom scipy.integrate import odeint\n\ndef Lorenz(state,t):\n  # unpack the state vector\n  x = state[0]\n  y = state[1]\n  z = state[2]\n  \n  # these are our constants\n  sigma = 10.0\n  rho = 28.0\n  beta = 8.0/3.0\n\n  # compute state derivatives\n  xd = sigma * (y-x)\n  yd = (rho-z)*x - y\n  zd = x*y - beta*z\n  \n  # return the state derivatives\n  return [xd, yd, zd]\n\nt = arange(0.0, 30, 0.01)\n\n# original initial conditions\nstate1_0 = [2.0, 3.0, 4.0]\nstate1 = odeint(Lorenz, state1_0, t)\n\n# rerun with very small change in initial conditions\ndelta = 0.0001\nstate2_0 = [2.0+delta, 3.0, 4.0]\nstate2 = odeint(Lorenz, state2_0, t)\n\n# animation\nfigure()\npb, = plot(state1[:,0],state1[:,1],'b-',alpha=0.2)\nxlabel('x')\nylabel('y')\np, = plot(state1[0:10,0],state1[0:10,1],'b-')\npp, = plot(state1[10,0],state1[10,1],'b.',markersize=10)\np2, = plot(state2[0:10,0],state2[0:10,1],'r-')\npp2, = plot(state2[10,0],state2[10,1],'r.',markersize=10)\ntt = title(\"%4.2f sec\" % 0.00)\n# animate\nstep = 3\nfor i in xrange(1,shape(state1)[0]-10,step):\n  p.set_xdata(state1[10+i:20+i,0])\n  p.set_ydata(state1[10+i:20+i,1])\n  pp.set_xdata(state1[19+i,0])\n  pp.set_ydata(state1[19+i,1])\n  p2.set_xdata(state2[10+i:20+i,0])\n  p2.set_ydata(state2[10+i:20+i,1])\n  pp2.set_xdata(state2[19+i,0])\n  pp2.set_ydata(state2[19+i,1])\n  tt.set_text(\"%4.2f sec\" % (i*0.01))\n  draw()\n\ni = 1939          # the two simulations really diverge here!\ns1 = state1[i,:]\ns2 = state2[i,:]\nd12 = norm(s1-s2) # distance\nprint (\"distance = %f for a %f different in initial condition\") % (d12, delta)\n\n", "meta": {"hexsha": "362d006ca3a7bbe9c8c6ec2e21ce7878463b7051", "size": 1557, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/lorenz2.py", "max_stars_repo_name": "paulgribble/CompNeuro", "max_stars_repo_head_hexsha": "f586944c0c3254976203d29f096ecf80e175bff4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2015-10-08T21:38:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T16:55:16.000Z", "max_issues_repo_path": "code/lorenz2.py", "max_issues_repo_name": "paulgribble/CompNeuro", "max_issues_repo_head_hexsha": "f586944c0c3254976203d29f096ecf80e175bff4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/lorenz2.py", "max_forks_repo_name": "paulgribble/CompNeuro", "max_forks_repo_head_hexsha": "f586944c0c3254976203d29f096ecf80e175bff4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2015-06-29T20:50:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-16T08:59:56.000Z", "avg_line_length": 23.9538461538, "max_line_length": 78, "alphanum_fraction": 0.631342325, "include": true, "reason": "from scipy", "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741322079104, "lm_q2_score": 0.9263037308025663, "lm_q1q2_score": 0.8823729725302045}}
{"text": "from typing import Union, Sequence\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.interpolate as spinter\n\nNum = Union[int, float]\n\n\ndef piecewise_linear(x_data: Sequence[Num], y_data: Sequence[Num], x_to_find: Num) -> float:\n    \"\"\"\n    Shows plot for piece-wise linear with given data and the estimated y-value for the given x value.\n    Prints the lowest y-value and its corresponding x-value.\n    Will also interpolate and return the y-value for a given x-value.\n    \"\"\"\n\n    plt.plot(x_data, y_data)\n\n    # This does the piece wise interopolation\n    for i, x in enumerate(x_data):\n        if x_data[i] <= x_to_find < x_data[i+1]:\n            y_found = y_data[i] + (y_data[i+1] - y_data[i])/(x_data[i+1] - x_data[i])*(x_to_find - x_data[i])\n\n    plt.plot(x_to_find, y_found, 'r+')\n    plt.title(\"Piece-Wise Interpolation\")\n    plt.show()\n\n    print(f\"Minimum y-value: {min(y_data)}\")\n    print(f\"Corresponding x-value: {x_data[y_data.index(min(y_data))]}\")\n\n    return y_found\n\n\ndef exact_data_fit_polynomial(x_data: Sequence[Num], y_data: Sequence[Num], x_to_find: Num, polynomial_order: int) -> Union[float, None]:\n    \"\"\"\n    Given: x_data, y_data, and x-value to interpolate, and the polynomial order\n    this function will print the coefficients for the specified order interpolation polynomial.\n    Polynomial will fit all data points and return the interpolated y-value from the given x-value.\n    It will print the minimum y-value and the corresponding x-value for the interpolation function.\n\n    This function returns the interpolated y-value from the given x-value.\n\n    The polynomial order (rank) must be square with the data, otherwise a value of None will be returned.\n    \"\"\"\n    if len(x_data) != polynomial_order + 1:  # Checking if the rank is square and we can get an exact solution\n        return None\n\n    plt.plot(x_data, y_data, 'r+')\n\n    # We create the polynomial array we need to solve to get the coefficients array\n    a_array = []\n    for x in x_data:\n        inner_temp_array = []\n        for exponent in range(polynomial_order+1):\n            inner_temp_array.append(x**exponent)\n        a_array.append(inner_temp_array)\n\n    coefficients = np.linalg.solve(a_array, y_data)\n    print(f\"Coefficients: {coefficients}\")\n\n    # Doing the interpolation\n    y_found = 0\n    for i, coeff in enumerate(coefficients):\n        y_found += coeff*x_to_find**i\n\n    # It's time for some plotting!\n    x_vals = np.linspace(-1, 1, 1000)\n    y_vals = []\n    for x in x_vals:\n        y_temp = 0\n        for i, coeff in enumerate(coefficients):\n            y_temp += coeff*x**i\n        y_vals.append(y_temp)\n    plt.plot(x_vals, y_vals)\n    plt.plot(x_to_find, y_found, 'g*')\n    plt.title(f\"{polynomial_order}-Order Polynomial Interpolation Passing Through All Data Points\")\n    plt.show()\n\n    # Finding the lowest y-value min using a fine grid mesh\n    y_min = min(y_vals)\n    x_min = x_vals[y_vals.index(min(y_vals))]\n    print(f\"Minimum y-value found was: {y_min}, corresponding x-value was: {x_min}\")\n\n    return y_found\n\n\ndef least_squares_polynomial(x_data: Sequence[Num], y_data: Sequence[Num], x_to_find: Num, polynomial_order: int) -> float:\n    \"\"\"\n    Given x-data, y-data, an x-value to interpolate, and a polynomial solution order\n    this function will find the least-squares polynomial solution\n    and return the interpolated y-value for the given x-value.\n\n    It will print the coefficients for the resulting polynomial.\n    It will provide a plot of the polynomial, with the original data points, and the interpolated value.\n    Additionally it will print the lowest y-value and its corresponding x-value.\n    \"\"\"\n    plt.plot(x_data, y_data, 'r+')\n\n    # Solving for the polynomial coefficients\n    a_array = []\n    for x in x_data:\n        inner_temp_array = []\n        for exponent in range(polynomial_order+1):\n            inner_temp_array.append(x**exponent)\n        a_array.append(inner_temp_array)\n    a_array = np.array(a_array)\n    a_array_trans = np.matrix.transpose(a_array)\n    coefficients = np.linalg.solve(a_array_trans.dot(a_array), a_array_trans.dot(y_data))\n    print(f\"Coefficients: {coefficients}\")\n\n    # Let's find the interpolated y-value\n    y_found = 0\n    for i, coeff in enumerate(coefficients):\n        y_found += coeff*x_to_find**i\n    print(y_found)\n\n    # Iterating through the polynomial to provide a plot\n    x_vals = np.linspace(-1, 1, 1000)\n    y_vals = []\n    for x in x_vals:\n        y_temp = 0\n        for i, coeff in enumerate(coefficients):\n            y_temp += coeff*x**i\n        y_vals.append(y_temp)\n    plt.plot(x_vals, y_vals)\n    plt.plot(x_to_find, y_found, 'g*')\n    plt.title(f\"Least-Squares {polynomial_order}-Order Polynomial Interpolation\")\n    plt.show()\n\n    # Printing y_min and corresponding x_min\n    y_min = min(y_vals)\n    x_min = x_vals[y_vals.index(min(y_vals))]\n    print(f\"Minimum y-value found was: {y_min}, corresponding x-value was: {x_min}\")\n\n    return y_found\n\n\ndef cubic_spline(x_data: Sequence[Num], y_data: Sequence[Num], x_to_find: Num) -> float:\n    \"\"\"\n    Given x_data, y_data, and an x-value to find, this function will return the\n    corresponding y-value using SciPy's cubic spline interpolation.\n    It will display a graph showing the data points, interpolation, and the interpolated value.\n    It will also print the minimum y-value for the interpolation and its corresponding x-value.\n    \"\"\"\n    plt.plot(x_data, y_data)\n    x_vals = np.linspace(-1, 1, 1000)\n    y_vals = []\n\n    cs = spinter.CubicSpline(x_data, y_data)\n    for x in x_vals:\n        y_vals.append(cs(x))\n    plt.plot(x_vals, y_vals)\n\n    # Let's find the interpolated data point\n    y_found = cs(x_to_find)\n    plt.plot(x_to_find, y_found, 'g*')\n    plt.title(\"Cubic Spline Interpolation\")\n    plt.show()\n\n    y_min = min(y_vals)\n    x_min = x_vals[y_vals.index(min(y_vals))]\n    print(f\"Minimum y-value found was: {y_min}, corresponding x-value was: {x_min}\")\n\n    return y_found\n", "meta": {"hexsha": "830a17a8f33ae1530976c8f705b207e07b5dd60e", "size": 5989, "ext": "py", "lang": "Python", "max_stars_repo_path": "interpolation.py", "max_stars_repo_name": "janine9vn/NumericalMethods", "max_stars_repo_head_hexsha": "1299bcb96cab2648203e8a9956d0a2caef407782", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "interpolation.py", "max_issues_repo_name": "janine9vn/NumericalMethods", "max_issues_repo_head_hexsha": "1299bcb96cab2648203e8a9956d0a2caef407782", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interpolation.py", "max_forks_repo_name": "janine9vn/NumericalMethods", "max_forks_repo_head_hexsha": "1299bcb96cab2648203e8a9956d0a2caef407782", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-26T17:26:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-28T08:47:21.000Z", "avg_line_length": 36.296969697, "max_line_length": 137, "alphanum_fraction": 0.6844214393, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.9284087985746093, "lm_q1q2_score": 0.8823699172355944}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 25 13:53:40 2017\n\n@author: ratnadeepb\n@License: MIT\n\"\"\"\n\n# System Imports\nimport numpy as np\nimport sys\n\n# Local imports\nfrom InnerProductSpaces.dot import dot\nfrom InnerProductSpaces.norm import norm\n\ndef angle(u, v, op=\"radians\"):\n    n_u = norm(u)\n    n_v = norm(v)\n    \n    if op not in (\"radians\", \"degrees\"):\n        sys.exit(\"At this time we only handle radians and degrees\")\n    \n    # The angle does not exist if one of them is a zero vector\n    if n_u == 0 or n_v == 0:\n        return np.NaN\n    \n    a = np.arccos(dot(u, v) / (norm(u) * norm(v)))\n    \n    if op == \"radians\":\n        return a\n    else:\n        return a * (180 / np.pi)\n\nif __name__ == \"__main__\":\n    # u = [6, 2]\n    u = (-3, 3)\n    # v = [1, 4]\n    v = (5, 5)\n    a_r = angle(u, v)\n    if np.isnan(a_r):\n        print(\"The angle does not exist\")\n    else:\n        a_d = angle(u, v, \"degrees\")\n        print(\"The angle between u and v is {} radians\".format(np.round(a_r, \n              decimals=4)))\n        print(\"This is the same as {} degrees\".format(np.round(a_d, \n              decimals=4)))", "meta": {"hexsha": "ca156a7f7f630742d9c3a8b6180d77547a2550bb", "size": 1145, "ext": "py", "lang": "Python", "max_stars_repo_path": "InnerProductSpaces/angle_between_vectors.py", "max_stars_repo_name": "ratnadeepb/LinearAlgebra", "max_stars_repo_head_hexsha": "0f4399c15ba12a3e7c0e2a796c77efa66520e462", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "InnerProductSpaces/angle_between_vectors.py", "max_issues_repo_name": "ratnadeepb/LinearAlgebra", "max_issues_repo_head_hexsha": "0f4399c15ba12a3e7c0e2a796c77efa66520e462", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "InnerProductSpaces/angle_between_vectors.py", "max_forks_repo_name": "ratnadeepb/LinearAlgebra", "max_forks_repo_head_hexsha": "0f4399c15ba12a3e7c0e2a796c77efa66520e462", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3673469388, "max_line_length": 77, "alphanum_fraction": 0.5572052402, "include": true, "reason": "import numpy", "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.9284087946129328, "lm_q1q2_score": 0.8823699121663474}}
{"text": "# Tools - NumPy\n\n*NumPy is the fundamental library for scientific computing with Python. NumPy is centered around a powerful N-dimensional array object, and it also contains useful linear algebra, Fourier transform, and random number functions.*\n\n## Creating arrays\n\nNow let's import `numpy`. Most people import it as `np`:\n\nimport numpy as np\n\n## `np.zeros`\n\nThe `zeros` function creates an array containing any number of zeros:\n\nnp.zeros(5)\n\nIt's just as easy to create a 2D array (ie. a matrix) by providing a tuple with the desired number of rows and columns. For example, here's a 3x4 matrix:\n\nnp.zeros((3,4))\n\n## Some vocabulary\n\n* In NumPy, each dimension is called an **axis**.\n* The number of axes is called the **rank**.\n    * For example, the above 3x4 matrix is an array of rank 2 (it is 2-dimensional).\n    * The first axis has length 3, the second has length 4.\n* An array's list of axis lengths is called the **shape** of the array.\n    * For example, the above matrix's shape is `(3, 4)`.\n    * The rank is equal to the shape's length.\n* The **size** of an array is the total number of elements, which is the product of all axis lengths (eg. 3*4=12)\n\na = np.zeros((3,4))\na\n\na.shape\n\na.ndim  # equal to len(a.shape)\n\na.size\n\n## N-dimensional arrays\nYou can also create an N-dimensional array of arbitrary rank. For example, here's a 3D array (rank=3), with shape `(2,3,4)`:\n\nnp.zeros((2,3,4))\n\n## Array type\nNumPy arrays have the type `ndarray`s:\n\ntype(np.zeros((3,4)))\n\n## `np.ones`\nMany other NumPy functions create `ndarrays`.\n\nHere's a 3x4 matrix full of ones:\n\nnp.ones((3,4))\n\n## `np.full`\nCreates an array of the given shape initialized with the given value. Here's a 3x4 matrix full of `π`.\n\nnp.full((3,4), np.pi)\n\n## `np.empty`\nAn uninitialized 2x3 array (its content is not predictable, as it is whatever is in memory at that point):\n\nnp.empty((2,3))\n\n## np.array\nOf course you can initialize an `ndarray` using a regular python array. Just call the `array` function:\n\nnp.array([[1,2,3,4], [10, 20, 30, 40]])\n\n## `np.arange`\nYou can create an `ndarray` using NumPy's `arange` function, which is similar to python's built-in `range` function:\n\nnp.arange(1, 5)\n\nIt also works with floats:\n\nnp.arange(1.0, 5.0)\n\nOf course you can provide a step parameter:\n\nnp.arange(1, 5, 0.5)\n\nHowever, when dealing with floats, the exact number of elements in the array is not always predictible. For example, consider this:\n\nprint(np.arange(0, 5/3, 1/3)) # depending on floating point errors, the max value is 4/3 or 5/3.\nprint(np.arange(0, 5/3, 0.333333333))\nprint(np.arange(0, 5/3, 0.333333334))\n\n\n## `np.linspace`\nFor this reason, it is generally preferable to use the `linspace` function instead of `arange` when working with floats. The `linspace` function returns an array containing a specific number of points evenly distributed between two values (note that the maximum value is *included*, contrary to `arange`):\n\nprint(np.linspace(0, 5/3, 6))\n\n## `np.rand` and `np.randn`\nA number of functions are available in NumPy's `random` module to create `ndarray`s initialized with random values.\nFor example, here is a 3x4 matrix initialized with random floats between 0 and 1 (uniform distribution):\n\nnp.random.rand(3,4)\n\nHere's a 3x4 matrix containing random floats sampled from a univariate [normal distribution](https://en.wikipedia.org/wiki/Normal_distribution) (Gaussian distribution) of mean 0 and variance 1:\n\nnp.random.randn(3,4)\n\nTo give you a feel of what these distributions look like, let's use matplotlib (see the [matplotlib tutorial](tools_matplotlib.ipynb) for more details):\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\nplt.hist(np.random.rand(100000), density=True, bins=100, histtype=\"step\", color=\"blue\", label=\"rand\")\nplt.hist(np.random.randn(100000), density=True, bins=100, histtype=\"step\", color=\"red\", label=\"randn\")\nplt.axis([-2.5, 2.5, 0, 1.1])\nplt.legend(loc = \"upper left\")\nplt.title(\"Random distributions\")\nplt.xlabel(\"Value\")\nplt.ylabel(\"Density\")\nplt.show()\n\n## np.fromfunction\nYou can also initialize an `ndarray` using a function:\n\ndef my_function(z, y, x):\n    return x * y + z\n\nnp.fromfunction(my_function, (3, 2, 10))\n\nNumPy first creates three `ndarrays` (one per dimension), each of shape `(2, 10)`. Each array has values equal to the coordinate along a specific axis. For example, all elements in the `z` array are equal to their z-coordinate:\n\n    [[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]\n      [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]\n    \n     [[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]\n      [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]]\n    \n     [[ 2.  2.  2.  2.  2.  2.  2.  2.  2.  2.]\n      [ 2.  2.  2.  2.  2.  2.  2.  2.  2.  2.]]]\n\nSo the terms x, y and z in the expression `x * y + z` above are in fact `ndarray`s (we will discuss arithmetic operations on arrays below).  The point is that the function `my_function` is only called *once*, instead of once per element. This makes initialization very efficient.\n\n## Array data\n## `dtype`\nNumPy's `ndarray`s are also efficient in part because all their elements must have the same type (usually numbers).\nYou can check what the data type is by looking at the `dtype` attribute:\n\nc = np.arange(1, 5)\nprint(c.dtype, c)\n\nc = np.arange(1.0, 5.0)\nprint(c.dtype, c)\n\nInstead of letting NumPy guess what data type to use, you can set it explicitly when creating an array by setting the `dtype` parameter:\n\nd = np.arange(1, 5, dtype=np.complex64)\nprint(d.dtype, d)\n\nAvailable data types include `int8`, `int16`, `int32`, `int64`, `uint8`|`16`|`32`|`64`, `float16`|`32`|`64` and `complex64`|`128`. Check out [the documentation](http://docs.scipy.org/doc/numpy-1.10.1/user/basics.types.html) for the full list.\n\n## `itemsize`\nThe `itemsize` attribute returns the size (in bytes) of each item:\n\ne = np.arange(1, 5, dtype=np.complex64)\ne.itemsize\n\n## `data` buffer\nAn array's data is actually stored in memory as a flat (one dimensional) byte buffer. It is available *via* the `data` attribute (you will rarely need it, though).\n\nf = np.array([[1,2],[1000, 2000]], dtype=np.int32)\nf.data\n\nIn python 2, `f.data` is a buffer. In python 3, it is a memoryview.\n\nif (hasattr(f.data, \"tobytes\")):\n    data_bytes = f.data.tobytes() # python 3\nelse:\n    data_bytes = memoryview(f.data).tobytes() # python 2\n\ndata_bytes\n\nSeveral `ndarrays` can share the same data buffer, meaning that modifying one will also modify the others. We will see an example in a minute.\n\n## Reshaping an array\n## In place\nChanging the shape of an `ndarray` is as simple as setting its `shape` attribute. However, the array's size must remain the same.\n\ng = np.arange(24)\nprint(g)\nprint(\"Rank:\", g.ndim)\n\ng.shape = (6, 4)\nprint(g)\nprint(\"Rank:\", g.ndim)\n\ng.shape = (2, 3, 4)\nprint(g)\nprint(\"Rank:\", g.ndim)\n\n## `reshape`\nThe `reshape` function returns a new `ndarray` object pointing at the *same* data. This means that modifying one array will also modify the other.\n\ng2 = g.reshape(4,6)\nprint(g2)\nprint(\"Rank:\", g2.ndim)\n\nSet item at row 1, col 2 to 999 (more about indexing below).\n\ng2[1, 2] = 999\ng2\n\nThe corresponding element in `g` has been modified.\n\ng\n\n## `ravel`\nFinally, the `ravel` function returns a new one-dimensional `ndarray` that also points to the same data:\n\ng.ravel()\n\n## Arithmetic operations\nAll the usual arithmetic operators (`+`, `-`, `*`, `/`, `//`, `**`, etc.) can be used with `ndarray`s. They apply *elementwise*:\n\na = np.array([14, 23, 32, 41])\nb = np.array([5,  4,  3,  2])\nprint(\"a + b  =\", a + b)\nprint(\"a - b  =\", a - b)\nprint(\"a * b  =\", a * b)\nprint(\"a / b  =\", a / b)\nprint(\"a // b  =\", a // b)\nprint(\"a % b  =\", a % b)\nprint(\"a ** b =\", a ** b)\n\nNote that the multiplication is *not* a matrix multiplication. We will discuss matrix operations below.\n\nThe arrays must have the same shape. If they do not, NumPy will apply the *broadcasting rules*.\n\n## Broadcasting\n\nIn general, when NumPy expects arrays of the same shape but finds that this is not the case, it applies the so-called *broadcasting* rules:\n\n## First rule\n*If the arrays do not have the same rank, then a 1 will be prepended to the smaller ranking arrays until their ranks match.*\n\nh = np.arange(5).reshape(1, 1, 5)\nh\n\nNow let's try to add a 1D array of shape `(5,)` to this 3D array of shape `(1,1,5)`. Applying the first rule of broadcasting!\n\nh + [10, 20, 30, 40, 50]  # same as: h + [[[10, 20, 30, 40, 50]]]\n\n## Second rule\n*Arrays with a 1 along a particular dimension act as if they had the size of the array with the largest shape along that dimension. The value of the array element is repeated along that dimension.*\n\nk = np.arange(6).reshape(2, 3)\nk\n\nLet's try to add a 2D array of shape `(2,1)` to this 2D `ndarray` of shape `(2, 3)`. NumPy will apply the second rule of broadcasting:\n\nk + [[100], [200]]  # same as: k + [[100, 100, 100], [200, 200, 200]]\n\nCombining rules 1 & 2, we can do this:\n\nk + [100, 200, 300]  # after rule 1: [[100, 200, 300]], and after rule 2: [[100, 200, 300], [100, 200, 300]]\n\nAnd also, very simply:\n\nk + 1000  # same as: k + [[1000, 1000, 1000], [1000, 1000, 1000]]\n\n## Third rule\n*After rules 1 & 2, the sizes of all arrays must match.*\n\ntry:\n    k + [33, 44]\nexcept ValueError as e:\n    print(e)\n\nBroadcasting rules are used in many NumPy operations, not just arithmetic operations, as we will see below.\nFor more details about broadcasting, check out [the documentation](https://docs.scipy.org/doc/numpy-dev/user/basics.broadcasting.html).\n\n## Upcasting\nWhen trying to combine arrays with different `dtype`s, NumPy will *upcast* to a type capable of handling all possible values (regardless of what the *actual* values are).\n\nk1 = np.arange(0, 5, dtype=np.uint8)\nprint(k1.dtype, k1)\n\nk2 = k1 + np.array([5, 6, 7, 8, 9], dtype=np.int8)\nprint(k2.dtype, k2)\n\nNote that `int16` is required to represent all *possible* `int8` and `uint8` values (from -128 to 255), even though in this case a uint8 would have sufficed.\n\nk3 = k1 + 1.5\nprint(k3.dtype, k3)\n\n## Conditional operators\n\nThe conditional operators also apply elementwise:\n\nm = np.array([20, -5, 30, 40])\nm < [15, 16, 35, 36]\n\nAnd using broadcasting:\n\nm < 25  # equivalent to m < [25, 25, 25, 25]\n\nThis is most useful in conjunction with boolean indexing (discussed below).\n\nm[m < 25]\n\n##Mathematical and statistical functions\n\nMany mathematical and statistical functions are available for `ndarray`s.\n\n## `ndarray` methods\nSome functions are simply `ndarray` methods, for example:\n\na = np.array([[-2.5, 3.1, 7], [10, 11, 12]])\nprint(a)\nprint(\"mean =\", a.mean())\n\nNote that this computes the mean of all elements in the `ndarray`, regardless of its shape.\n\nHere are a few more useful `ndarray` methods:\n\nfor func in (a.min, a.max, a.sum, a.prod, a.std, a.var):\n    print(func.__name__, \"=\", func())\n\nThese functions accept an optional argument `axis` which lets you ask for the operation to be performed on elements along the given axis. For example:\n\nc=np.arange(24).reshape(2,3,4)\nc\n\nc.sum(axis=0)  # sum across matrices\n\nc.sum(axis=1)  # sum across rows\n\nYou can also sum over multiple axes:\n\nc.sum(axis=(0,2))  # sum across matrices and columns\n\n0+1+2+3 + 12+13+14+15, 4+5+6+7 + 16+17+18+19, 8+9+10+11 + 20+21+22+23\n\n## Universal functions\nNumPy also provides fast elementwise functions called *universal functions*, or **ufunc**. They are vectorized wrappers of simple functions. For example `square` returns a new `ndarray` which is a copy of the original `ndarray` except that each element is squared:\n\na = np.array([[-2.5, 3.1, 7], [10, 11, 12]])\nnp.square(a)\n\nHere are a few more useful unary ufuncs:\n\nprint(\"Original ndarray\")\nprint(a)\nfor func in (np.abs, np.sqrt, np.exp, np.log, np.sign, np.ceil, np.modf, np.isnan, np.cos):\n    print(\"\\n\", func.__name__)\n    print(func(a))\n\n## Binary ufuncs\nThere are also many binary ufuncs, that apply elementwise on two `ndarray`s.  Broadcasting rules are applied if the arrays do not have the same shape:\n\na = np.array([1, -2, 3, 4])\nb = np.array([2, 8, -1, 7])\nnp.add(a, b)  # equivalent to a + b\n\nnp.greater(a, b)  # equivalent to a > b\n\nnp.maximum(a, b)\n\nnp.copysign(a, b)\n\n## Array indexing\n## One-dimensional arrays\nOne-dimensional NumPy arrays can be accessed more or less like regular python arrays:\n\na = np.array([1, 5, 3, 19, 13, 7, 3])\na[3]\n\na[2:5]\n\na[2:-1]\n\na[:2]\n\na[2::2]\n\na[::-1]\n\nOf course, you can modify elements:\n\na[3]=999\na\n\nYou can also modify an `ndarray` slice:\n\na[2:5] = [997, 998, 999]\na\n\n## Differences with regular python arrays\nContrary to regular python arrays, if you assign a single value to an `ndarray` slice, it is copied across the whole slice, thanks to broadcasting rules discussed above.\n\na[2:5] = -1\na\n\nAlso, you cannot grow or shrink `ndarray`s this way:\n\ntry:\n    a[2:5] = [1,2,3,4,5,6]  # too long\nexcept ValueError as e:\n    print(e)\n\nYou cannot delete elements either:\n\ntry:\n    del a[2:5]\nexcept ValueError as e:\n    print(e)\n\nLast but not least, `ndarray` **slices are actually *views*** on the same data buffer. This means that if you create a slice and modify it, you are actually going to modify the original `ndarray` as well!\n\na_slice = a[2:6]\na_slice[1] = 1000\na  # the original array was modified!\n\na[3] = 2000\na_slice  # similarly, modifying the original array modifies the slice!\n\nIf you want a copy of the data, you need to use the `copy` method:\n\nanother_slice = a[2:6].copy()\nanother_slice[1] = 3000\na  # the original array is untouched\n\na[3] = 4000\nanother_slice  # similary, modifying the original array does not affect the slice copy\n\n## Multi-dimensional arrays\nMulti-dimensional arrays can be accessed in a similar way by providing an index or slice for each axis, separated by commas:\n\nb = np.arange(48).reshape(4, 12)\nb\n\nb[1, 2]  # row 1, col 2\n\nb[1, :]  # row 1, all columns\n\nb[:, 1]  # all rows, column 1\n\n**Caution**: note the subtle difference between these two expressions: \n\nb[1, :]\n\nb[1:2, :]\n\nThe first expression returns row 1 as a 1D array of shape `(12,)`, while the second returns that same row as a 2D array of shape `(1, 12)`.\n\n## Fancy indexing\nYou may also specify a list of indices that you are interested in. This is referred to as *fancy indexing*.\n\nb[(0,2), 2:5]  # rows 0 and 2, columns 2 to 4 (5-1)\n\nb[:, (-1, 2, -1)]  # all rows, columns -1 (last), 2 and -1 (again, and in this order)\n\nIf you provide multiple index arrays, you get a 1D `ndarray` containing the values of the elements at the specified coordinates.\n\nb[(-1, 2, -1, 2), (5, 9, 1, 9)]  # returns a 1D array with b[-1, 5], b[2, 9], b[-1, 1] and b[2, 9] (again)\n\n## Higher dimensions\nEverything works just as well with higher dimensional arrays, but it's useful to look at a few examples:\n\nc = b.reshape(4,2,6)\nc\n\nc[2, 1, 4]  # matrix 2, row 1, col 4\n\nc[2, :, 3]  # matrix 2, all rows, col 3\n\nIf you omit coordinates for some axes, then all elements in these axes are returned:\n\nc[2, 1]  # Return matrix 2, row 1, all columns.  This is equivalent to c[2, 1, :]\n\n## Ellipsis (`...`)\nYou may also write an ellipsis (`...`) to ask that all non-specified axes be entirely included.\n\nc[2, ...]  #  matrix 2, all rows, all columns.  This is equivalent to c[2, :, :]\n\nc[2, 1, ...]  # matrix 2, row 1, all columns.  This is equivalent to c[2, 1, :]\n\nc[2, ..., 3]  # matrix 2, all rows, column 3.  This is equivalent to c[2, :, 3]\n\nc[..., 3]  # all matrices, all rows, column 3.  This is equivalent to c[:, :, 3]\n\n## Boolean indexing\nYou can also provide an `ndarray` of boolean values on one axis to specify the indices that you want to access.\n\nb = np.arange(48).reshape(4, 12)\nb\n\nrows_on = np.array([True, False, True, False])\nb[rows_on, :]  # Rows 0 and 2, all columns. Equivalent to b[(0, 2), :]\n\ncols_on = np.array([False, True, False] * 4)\nb[:, cols_on]  # All rows, columns 1, 4, 7 and 10\n\n## `np.ix_`\nYou cannot use boolean indexing this way on multiple axes, but you can work around this by using the `ix_` function:\n\nb[np.ix_(rows_on, cols_on)]\n\nnp.ix_(rows_on, cols_on)\n\nIf you use a boolean array that has the same shape as the `ndarray`, then you get in return a 1D array containing all the values that have `True` at their coordinate. This is generally used along with conditional operators:\n\nb[b % 3 == 1]\n\n## Iterating\nIterating over `ndarray`s is very similar to iterating over regular python arrays. Note that iterating over multidimensional arrays is done with respect to the first axis.\n\nc = np.arange(24).reshape(2, 3, 4)  # A 3D array (composed of two 3x4 matrices)\nc\n\nfor m in c:\n    print(\"Item:\")\n    print(m)\n\nfor i in range(len(c)):  # Note that len(c) == c.shape[0]\n    print(\"Item:\")\n    print(c[i])\n\nIf you want to iterate on *all* elements in the `ndarray`, simply iterate over the `flat` attribute:\n\nfor i in c.flat:\n    print(\"Item:\", i)\n\n##Stacking arrays\nIt is often useful to stack together different arrays. NumPy offers several functions to do just that. Let's start by creating a few arrays.\n\nq1 = np.full((3,4), 1.0)\nq1\n\nq2 = np.full((4,4), 2.0)\nq2\n\nq3 = np.full((3,4), 3.0)\nq3\n\n## `vstack`\nNow let's stack them vertically using `vstack`:\n\nq4 = np.vstack((q1, q2, q3))\nq4\n\nq4.shape\n\nThis was possible because q1, q2 and q3 all have the same shape (except for the vertical axis, but that's ok since we are stacking on that axis).\n\n## `hstack`\nWe can also stack arrays horizontally using `hstack`:\n\nq5 = np.hstack((q1, q3))\nq5\n\nq5.shape\n\nThis is possible because q1 and q3 both have 3 rows. But since q2 has 4 rows, it cannot be stacked horizontally with q1 and q3:\n\ntry:\n    q5 = np.hstack((q1, q2, q3))\nexcept ValueError as e:\n    print(e)\n\n## `concatenate`\nThe `concatenate` function stacks arrays along any given existing axis.\n\nq7 = np.concatenate((q1, q2, q3), axis=0)  # Equivalent to vstack\nq7\n\nq7.shape\n\nAs you might guess, `hstack` is equivalent to calling `concatenate` with `axis=1`.\n\n## `stack`\nThe `stack` function stacks arrays along a new axis. All arrays have to have the same shape.\n\nq8 = np.stack((q1, q3))\nq8\n\nq8.shape\n\n##Splitting arrays\nSplitting is the opposite of stacking. For example, let's use the `vsplit` function to split a matrix vertically.\n\nFirst let's create a 6x4 matrix:\n\nr = np.arange(24).reshape(6,4)\nr\n\nNow let's split it in three equal parts, vertically:\n\nr1, r2, r3 = np.vsplit(r, 3)\nr1\n\nr2\n\nr3\n\nThere is also a `split` function which splits an array along any given axis. Calling `vsplit` is equivalent to calling `split` with `axis=0`. There is also an `hsplit` function, equivalent to calling `split` with `axis=1`:\n\nr4, r5 = np.hsplit(r, 2)\nr4\n\nr5\n\n##Transposing arrays\nThe `transpose` method creates a new view on an `ndarray`'s data, with axes permuted in the given order.\n\nFor example, let's create a 3D array:\n\nt = np.arange(24).reshape(4,2,3)\nt\n\nNow let's create an `ndarray` such that the axes `0, 1, 2` (depth, height, width) are re-ordered to `1, 2, 0` (depth→width, height→depth, width→height):\n\nt1 = t.transpose((1,2,0))\nt1\n\nt1.shape\n\nBy default, `transpose` reverses the order of the dimensions:\n\nt2 = t.transpose()  # equivalent to t.transpose((2, 1, 0))\nt2\n\nt2.shape\n\nNumPy provides a convenience function `swapaxes` to swap two axes. For example, let's create a new view of `t` with depth and height swapped:\n\nt3 = t.swapaxes(0,1)  # equivalent to t.transpose((1, 0, 2))\nt3\n\nt3.shape\n\n## Linear algebra\nNumPy 2D arrays can be used to represent matrices efficiently in python. We will just quickly go through some of the main matrix operations available. For more details about Linear Algebra, vectors and matrics, go through the [Linear Algebra tutorial](math_linear_algebra.ipynb).\n\n## Matrix transpose\nThe `T` attribute is equivalent to calling `transpose()` when the rank is ≥2:\n\nm1 = np.arange(10).reshape(2,5)\nm1\n\nm1.T\n\nThe `T` attribute has no effect on rank 0 (empty) or rank 1 arrays:\n\nm2 = np.arange(5)\nm2\n\nm2.T\n\nWe can get the desired transposition by first reshaping the 1D array to a single-row matrix (2D):\n\nm2r = m2.reshape(1,5)\nm2r\n\nm2r.T\n\n## Matrix multiplication\nLet's create two matrices and execute a [matrix multiplication](https://en.wikipedia.org/wiki/Matrix_multiplication) using the `dot()` method.\n\nn1 = np.arange(10).reshape(2, 5)\nn1\n\nn2 = np.arange(15).reshape(5,3)\nn2\n\nn1.dot(n2)\n\n**Caution**: as mentionned previously, `n1*n2` is *not* a matric multiplication, it is an elementwise product (also called a [Hadamard product](https://en.wikipedia.org/wiki/Hadamard_product_(matrices))).\n\n## Matrix inverse and pseudo-inverse\nMany of the linear algebra functions are available in the `numpy.linalg` module, in particular the `inv` function to compute a square matrix's inverse:\n\nimport numpy.linalg as linalg\n\nm3 = np.array([[1,2,3],[5,7,11],[21,29,31]])\nm3\n\nlinalg.inv(m3)\n\nYou can also compute the [pseudoinverse](https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse) using `pinv`:\n\nlinalg.pinv(m3)\n\n## Identity matrix\nThe product of a matrix by its inverse returns the identiy matrix (with small floating point errors):\n\nm3.dot(linalg.inv(m3))\n\nYou can create an identity matrix of size NxN by calling `eye`:\n\nnp.eye(3)\n\n## QR decomposition\nThe `qr` function computes the [QR decomposition](https://en.wikipedia.org/wiki/QR_decomposition) of a matrix:\n\nq, r = linalg.qr(m3)\nq\n\nr\n\nq.dot(r)  # q.r equals m3\n\n## Determinant\nThe `det` function computes the [matrix determinant](https://en.wikipedia.org/wiki/Determinant):\n\nlinalg.det(m3)  # Computes the matrix determinant\n\n## Eigenvalues and eigenvectors\nThe `eig` function computes the [eigenvalues and eigenvectors](https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors) of a square matrix:\n\neigenvalues, eigenvectors = linalg.eig(m3)\neigenvalues # λ\n\neigenvectors # v\n\nm3.dot(eigenvectors) - eigenvalues * eigenvectors  # m3.v - λ*v = 0\n\n## Singular Value Decomposition\nThe `svd` function takes a matrix and returns its [singular value decomposition](https://en.wikipedia.org/wiki/Singular_value_decomposition):\n\nm4 = np.array([[1,0,0,0,2], [0,0,3,0,0], [0,0,0,0,0], [0,2,0,0,0]])\nm4\n\nU, S_diag, V = linalg.svd(m4)\nU\n\nS_diag\n\nThe `svd` function just returns the values in the diagonal of Σ, but we want the full Σ matrix, so let's create it:\n\nS = np.zeros((4, 5))\nS[np.diag_indices(4)] = S_diag\nS  # Σ\n\nV\n\nU.dot(S).dot(V) # U.Σ.V == m4\n\n## Diagonal and trace\n\nnp.diag(m3)  # the values in the diagonal of m3 (top left to bottom right)\n\nnp.trace(m3)  # equivalent to np.diag(m3).sum()\n\n## Solving a system of linear scalar equations\n\nThe `solve` function solves a system of linear scalar equations, such as:\n\n* $2x + 6y = 6$\n* $5x + 3y = -9$\n\ncoeffs  = np.array([[2, 6], [5, 3]])\ndepvars = np.array([6, -9])\nsolution = linalg.solve(coeffs, depvars)\nsolution\n\nLet's check the solution:\n\ncoeffs.dot(solution), depvars  # yep, it's the same\n\nLooks good! Another way to check the solution:\n\nnp.allclose(coeffs.dot(solution), depvars)\n\n## Vectorization\nInstead of executing operations on individual array items, one at a time, your code is much more efficient if you try to stick to array operations. This is called *vectorization*. This way, you can benefit from NumPy's many optimizations.\n\nFor example, let's say we want to generate a 768x1024 array based on the formula $sin(xy/40.5)$. A **bad** option would be to do the math in python using nested loops:\n\nimport math\ndata = np.empty((768, 1024))\nfor y in range(768):\n    for x in range(1024):\n        data[y, x] = math.sin(x*y/40.5)  # BAD! Very inefficient.\n\nSure, this works, but it's terribly inefficient since the loops are taking place in pure python. Let's vectorize this algorithm. First, we will use NumPy's `meshgrid` function which generates coordinate matrices from coordinate vectors.\n\nx_coords = np.arange(0, 1024)  # [0, 1, 2, ..., 1023]\ny_coords = np.arange(0, 768)   # [0, 1, 2, ..., 767]\nX, Y = np.meshgrid(x_coords, y_coords)\nX\n\nY\n\nAs you can see, both `X` and `Y` are 768x1024 arrays, and all values in `X` correspond to the horizontal coordinate, while all values in `Y` correspond to the the vertical coordinate.\n\nNow we can simply compute the result using array operations:\n\ndata = np.sin(X*Y/40.5)\n\nNow we can plot this data using matplotlib's `imshow` function (see the [matplotlib tutorial](tools_matplotlib.ipynb)).\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfig = plt.figure(1, figsize=(7, 6))\nplt.imshow(data, cmap=cm.hot, interpolation=\"bicubic\")\nplt.show()\n\n## Saving and loading\nNumPy makes it easy to save and load `ndarray`s in binary or text format.\n\n## Binary `.npy` format\nLet's create a random array and save it.\n\na = np.random.rand(2,3)\na\n\nnp.save(\"my_array\", a)\n\nDone! Since the file name contains no file extension was provided, NumPy automatically added `.npy`. Let's take a peek at the file content:\n\nwith open(\"my_array.npy\", \"rb\") as f:\n    content = f.read()\n\ncontent\n\nTo load this file into a NumPy array, simply call `load`:\n\na_loaded = np.load(\"my_array.npy\")\na_loaded\n\n## Text format\nLet's try saving the array in text format:\n\nnp.savetxt(\"my_array.csv\", a)\n\nNow let's look at the file content:\n\nwith open(\"my_array.csv\", \"rt\") as f:\n    print(f.read())\n\nThis is a CSV file with tabs as delimiters. You can set a different delimiter:\n\nnp.savetxt(\"my_array.csv\", a, delimiter=\",\")\n\nTo load this file, just use `loadtxt`:\n\na_loaded = np.loadtxt(\"my_array.csv\", delimiter=\",\")\na_loaded\n\n## Zipped `.npz` format\nIt is also possible to save multiple arrays in one zipped file:\n\nb = np.arange(24, dtype=np.uint8).reshape(2, 3, 4)\nb\n\nnp.savez(\"my_arrays\", my_a=a, my_b=b)\n\nAgain, let's take a peek at the file content. Note that the `.npz` file extension was automatically added.\n\nwith open(\"my_arrays.npz\", \"rb\") as f:\n    content = f.read()\n\nrepr(content)[:180] + \"[...]\"\n\nYou then load this file like so:\n\nmy_arrays = np.load(\"my_arrays.npz\")\nmy_arrays\n\nThis is a dict-like object which loads the arrays lazily:\n\nmy_arrays.keys()\n\nmy_arrays[\"my_a\"]\n\n## What next?\nNow you know all the fundamentals of NumPy, but there are many more options available. The best way to learn more is to experiment with NumPy, and go through the excellent [reference documentation](http://docs.scipy.org/doc/numpy/reference/index.html) to find more functions and features you may be interested in.\n\n", "meta": {"hexsha": "9aebb93b09e50fc0f3a4bea1406389ce60050863", "size": 26158, "ext": "py", "lang": "Python", "max_stars_repo_path": "site/_build/jupyter_execute/notebooks/book/tools_numpy.py", "max_stars_repo_name": "rpi-techfundamentals/website_fall_2020", "max_stars_repo_head_hexsha": "b85e5c297954bcaae565a8d25a18d2904d40f543", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-18T23:05:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T08:09:11.000Z", "max_issues_repo_path": "site/_build/jupyter_execute/notebooks/book/tools_numpy.py", "max_issues_repo_name": "rpi-techfundamentals/website_fall_2020", "max_issues_repo_head_hexsha": "b85e5c297954bcaae565a8d25a18d2904d40f543", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-31T14:33:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-31T14:38:26.000Z", "max_forks_repo_path": "site/_build/jupyter_execute/notebooks/book/tools_numpy.py", "max_forks_repo_name": "rpi-techfundamentals/website_fall_2020", "max_forks_repo_head_hexsha": "b85e5c297954bcaae565a8d25a18d2904d40f543", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-08-31T21:58:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-30T02:55:08.000Z", "avg_line_length": 29.7588168373, "max_line_length": 313, "alphanum_fraction": 0.6993653949, "include": true, "reason": "import numpy", "num_tokens": 7937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.9504109775426864, "lm_q1q2_score": 0.8823699119299151}}
{"text": "# Undergraduate Student: Arturo Burgos\n# Professor: João Rodrigo Andrade\n# Federal University of Uberlândia - UFU, Fluid Mechanics Laboratory - MFLab, Block 5P, Uberlândia, MG, Brazil\n\n\n# Fourth exercise: Solving a Linear System --> ax = b\n\n# Here I first set conditions\n\nimport numpy as np\nfrom numpy import linalg as lin\nnp.seterr(divide='ignore', invalid='ignore')\n\na = np.array([\n    [-4, 1, 0, 1, 0, 0, 0, 0, 0],\n    [1, -4, 1, 0, 1, 0, 0, 0, 0], \n    [0, 1, -4, 0, 0, 1, 0, 0, 0], \n    [1, 0, 0, -4, 1, 0, 1, 0, 0], \n    [0, 1, 0, 1, -4, 1, 0, 1, 0], \n    [0, 0, 1, 0, 1, -4, 0, 0, 1], \n    [0, 0, 0, 1, 0, 0, -4, 1, 0], \n    [0, 0, 0, 0, 1, 0, 1, -4, 1], \n    [0, 0, 0, 0, 0, 1, 0, 1, -4] \n    ])\n\nprint('The coefficient Matrix is:')\nprint(a)\nprint('\\n')\n\nb = np.array([-50, -50, -150, 0, 0, -100, -50, -50, -150])\n\nprint('The result Matrix is:')\nprint(b)\nprint('\\n')\n\nx_k = np.zeros(9)\nx_k1 = np.ones(9)\n\n\n\n\n# Here I set the tolerance\n\ntolerance = 0.0000000001\n\n\n# Here I set the iterations\n\nite = 0\n  \n\n\n# Here I set the error based in the relative error -> error array \n\nerro = np.ones(9)\nerro = (x_k1 - x_k)/x_k1 # the relative error is not normalized so I must use .any() in order to compare with the tolerance\n\nwhile (erro>tolerance).any() : # use this condition (erro.all()>tolerance) and you will see that the error array is wrong and also\n    # the iteration counter gets a way bigger value\n    for i in range(0,9):\n        \n        x_k1[i] = b[i]\n\n        for j in range(0,9):\n\n            if j!=i:\n\n                x_k1[i] =  x_k1[i] - a[i,j]*x_k[j]\n\n\n    \n        x_k1[i] =  x_k1[i]/ a[i,i]\n\n    erro = (x_k1 - x_k)/x_k1\n    x_k = x_k1.copy()\n    ite = ite + 1\n\n\nprint('The number of iterations is: ')\nprint(ite)\nprint('\\n')\n\nprint('The solution is:')\nprint(x_k1)\nprint('\\n')\n\nprint('The error array is given by:')\nprint(erro)\nprint('\\n')\n\n\nprint(np.max(erro))", "meta": {"hexsha": "dad358e5696a98c447d9c883945adb9501626a2a", "size": 1879, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear System/Python/relative_error_test.py", "max_stars_repo_name": "arturofburgos/Comparing-Languages", "max_stars_repo_head_hexsha": "a20dc24699c762252c94c26e32c7053c04793d9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-03-17T18:40:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T11:51:12.000Z", "max_issues_repo_path": "Linear System/Python/relative_error_test.py", "max_issues_repo_name": "arturofburgos/Assessment-of-Programming-Languages-for-Computational-Numerical-Dynamics", "max_issues_repo_head_hexsha": "eefdc8800b424bbfb34286f4f507297300122a4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear System/Python/relative_error_test.py", "max_forks_repo_name": "arturofburgos/Assessment-of-Programming-Languages-for-Computational-Numerical-Dynamics", "max_forks_repo_head_hexsha": "eefdc8800b424bbfb34286f4f507297300122a4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-11T01:20:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T01:20:01.000Z", "avg_line_length": 20.4239130435, "max_line_length": 130, "alphanum_fraction": 0.570516232, "include": true, "reason": "import numpy,from numpy", "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.9343951588871157, "lm_q1q2_score": 0.8822342845893225}}
{"text": "import numpy as np\nfrom numpy import linalg as LA\nfrom sympy import *\n\nprint(\"1. Padalinkite intervalą nuo -1.3 iki 2.5 tolygiai į 64 dalis:\")\nprint(np.linspace(-1.3, 2.5, 64))\n\nprint(\"2. Sugeneruokite masyvą dydžio 3n ir užpildykite jį cikliniu šablonu [1, 2, 3]:\")\nn = 10\nprint(np.tile(np.array([1, 2, 3]), n))\n\nprint(\"3. Sukurkite masyvą iš pirmųjų 10 nelyginių sveikųjų skaičių:\")\nn = 10\nprint(np.arange(1, 2 * n, 2))\n\nprint(\"4. Sukurkite masyvą dydžio 10 x 10 iš nulių ir \\\"įrėminkite\\\" jį vienetais:\")\nn = 10\nmatrix = np.zeros((n ,n))\nmatrix[0] = 1\nmatrix[::, 0:n:n-1] = 1\nmatrix[n-1] = 1\nprint(matrix)\n\nprint(\"5. Sukurkite masyvą dydžio 8 x 8, kur 1 ir 0 išdėlioti šachmatine tvarka (panaudokite slicing+striding metodą):\")\nn = 8\nmatrix = np.zeros((n ,n))\nmatrix[::2, 1::2] = 1\nmatrix[1::2, ::2] = 1\nprint(matrix)\n\nprint(\"6. Sukurkite masyvą dydžio n×n , kurio (i,j)-oji pozicija lygi i+j:\")\nn = 10\nmatrix = np.fromfunction(lambda i, j: i + j, (10, 10), dtype=int)\nprint(matrix)\n\n\n\nprint(\"7. kurkite atsitiktinį masyvą dydžio 3×5 naudodami np.random.rand(3, 5) funkciją ir suskaičiuokite: sumą, eilučių sumą, stulpelių sumą:\")\nmatrix = np.random.rand(3, 5)\nprint(matrix)\nprint(\"Suma: \", matrix.sum())\nprint(\"Eilučių suma: \", matrix.sum(axis=0))\nprint(\"Stulpelių suma: \", matrix.sum(axis=1))\n\nprint(\"8. Sukurkite atsitiktinį masyvą dydžio 5×5 naudodami np.random.rand(5, 5). Surūšiuokite eilutes pagal antrąjį stulpelį. Tam pamėginkite apjungti masyvo slicing + argsort + indexing metodus:\")\nmatrix = np.random.rand(5, 5)\nprint(\"Sukurta matrica: \")\nprint(matrix)\nprint(\"Eilučių rūšiavimo tvarka pagal stulpelius: \")\nprint(np.argsort(matrix[::, 1], axis=0))\nprint(\"Surūšiuota matrica: \")\nprint(matrix[np.argsort(matrix[::, 1], axis=0), ::])\n\nprint(\"9. Atvirkštinę matricą:\")\nmatrix = np.random.rand(5, 5)\nprint(\"Sukurta matrica: \")\nprint(matrix)\nprint(\"Atvirkštinė matrica: \")\nprint(np.linalg.inv(matrix))\n\nprint(\"10. Apskaičiuokite matricos tikrines reikšmes ir tikrinį vektorių:\")\n# Teorija: https://mathworld.wolfram.com/Eigenvalue.html\n# API: https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html\nmatrix = np.random.rand(2, 2)\nprint(\"Sukurta matrica: \")\nprint(matrix)\neigvalue, eigvector = LA.eig(matrix)\nprint(\"Tikrinė reikšmė:\")\nprint(eigvalue)\nprint(\"Tikrinis vektorius:\")\nprint(eigvector)\n\nprint(\"11. Pasirinktos funkcijos išvestinę:\")\nx = Symbol('x')\nf = 4*x**3+3\nf_derivative = f.diff(x)\nprint(\"Funkcija: \", f)\nprint(\"Funkcijos išvestinė: \", f_derivative)\nf_derivative = lambdify(x, f_derivative)\nprint(\"Funkcijos išvestinės reikšmė, kai x = 0: \", f_derivative(0))\n\nprint(\"12. Pasirinktos funkcijos apibrėžtinį ir neapibrėžtinį integralus:\")\nx = Symbol('x')\nf = 4*x**3+3\nf_integral = f.integrate(x)\nprint(\"Funkcija: \", f)\nprint(\"Neapibrėžtas integralas: \", f_integral)\na = 0\nb = 1\nprint(\"Apibrėžtas integralas \", f_integral,  \" (funkcijos\", f, \") nuo \", a, \" iki \", b, \":\", f.integrate((x, a, b)))\n", "meta": {"hexsha": "0ee1a016e60ba06a4c64e47bf615a38219de902f", "size": 2934, "ext": "py", "lang": "Python", "max_stars_repo_path": "1 assignment/main.py", "max_stars_repo_name": "nastae/programavimas_python", "max_stars_repo_head_hexsha": "7e65ad834c5f52e146fb5fcd0408b344545dc30e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1 assignment/main.py", "max_issues_repo_name": "nastae/programavimas_python", "max_issues_repo_head_hexsha": "7e65ad834c5f52e146fb5fcd0408b344545dc30e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1 assignment/main.py", "max_forks_repo_name": "nastae/programavimas_python", "max_forks_repo_head_hexsha": "7e65ad834c5f52e146fb5fcd0408b344545dc30e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2417582418, "max_line_length": 198, "alphanum_fraction": 0.7062031357, "include": true, "reason": "import numpy,from numpy,from sympy", "num_tokens": 1217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018416062039, "lm_q2_score": 0.9046505286741727, "lm_q1q2_score": 0.8822168615730792}}
{"text": "import pandas as pd\nimport numpy as np\nimport math\nimport pdb\nimport random\nfrom math import sqrt\n\n\n\ndef average(series):\n\n    y = len(series)\n    x = sum(series)\n\n    av = x/y\n    return(av)\n    \n\ndef standard_deviation(series):\n\n    r = 0\n    aver = average(series)\n\n    for x in range (len(series)):\n        k = abs( series[x] - aver)**2\n        r = r + k\n    \n    \n    ss = r/(len(series)-1)\n    if ss>0 :\n        return (sqrt(ss))\n    else:\n        return(n/a)\n    \"\"\"\n    implements the sample standard deviation of a series from scratch\n    you may need a for loop and your average function\n    also the function math.sqrt\n    you should get the same result as calling .std() on your data\n    https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.std.html\n    See numpy documenation for implementation details:\n    https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html\n    \"\"\"\n\n\ndef median(series):\n\n    l=sorted(series)\n    t= len(l)\n\n    if t<1:\n        return None\n    if t % 2 == 0:\n        return (l[int(t/2)] + l[int(t/2)-1]) / 2\n    else:\n        return l[int((t-1)/2)]\n    \n\n    \"\"\"\n    finds the median of the series from scratch\n    you may need to sort your values and use\n    modular division\n    this number should be the same as calling .median() on your data\n    See numpy documenation for implementation details:\n    https://docs.scipy.org/doc/numpy/reference/generated/numpy.median.html\n    https://pandas.pydata.org/pandas-docs/version/0.23.0/generated/pandas.Series.median.html\n    \"\"\"", "meta": {"hexsha": "0458da7273920e4b26c5eb5f078c131d8bb192c7", "size": 1544, "ext": "py", "lang": "Python", "max_stars_repo_path": "KonstantinosTzo/code.py", "max_stars_repo_name": "botasakhi/applied_ds", "max_stars_repo_head_hexsha": "b70cf83b2fbaf78664950d990555a22e3e286f0d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-03T00:15:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-14T17:32:45.000Z", "max_issues_repo_path": "KonstantinosTzo/code.py", "max_issues_repo_name": "botasakhi/applied_ds", "max_issues_repo_head_hexsha": "b70cf83b2fbaf78664950d990555a22e3e286f0d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2019-03-11T00:32:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-12T01:26:05.000Z", "max_forks_repo_path": "KonstantinosTzo/code.py", "max_forks_repo_name": "botasakhi/applied_ds", "max_forks_repo_head_hexsha": "b70cf83b2fbaf78664950d990555a22e3e286f0d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 54, "max_forks_repo_forks_event_min_datetime": "2019-03-01T00:02:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-09T22:31:58.000Z", "avg_line_length": 23.3939393939, "max_line_length": 92, "alphanum_fraction": 0.6366580311, "include": true, "reason": "import numpy", "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018419665618, "lm_q2_score": 0.9046505254608135, "lm_q1q2_score": 0.8822168587654033}}
{"text": "#Program used to compute least squared fitting of a set of data X,Y\n# Y=A+BX\n################\n## Conventions\n##X: List where data are stored\n## SS:sum of x or y squared\n## S:sum of x or y\n## SXY:sum of xi*yi\n## n:number of data\n## A:intercept\n## B:slope\n\nimport numpy as np\ndef S(X):\n\tX=np.array(X)\n\treturn np.sum(X)\ndef SS(X):\n\tX=np.array(X)\n\treturn np.sum(X**2)\ndef SXY(X,Y):\n\tX=np.array(X)\n\tY=np.array(Y)\n\treturn np.sum(X*Y)\ndef delta(X):\n\tX=np.array(X)\n\treturn len(X)*SS(X)-(S(X))**2\ndef A(X,Y):\n\treturn (SS(X)*S(Y)-S(X)*SXY(X,Y))/delta(X)\ndef B(X,Y):\n\treturn (len(X)*SXY(X,Y)-S(X)*S(Y))/delta(X)\ndef sigma_y(X,Y):\n\ta=A(X,Y)\n\tb=B(X,Y)\n\tX=np.array(X)\n\tY=np.array(Y)\n\treturn np.sqrt(SS(Y-a-b*X)/(len(X)-2))\ndef sigma_A(X,Y):\n\treturn  sigma_y(X,Y)*np.sqrt(SS(X))/delta(X)\ndef sigma_B(X,Y):\n\treturn  sigma_y(X,Y)*len(X)/delta(X)\ndef fit(X,Y):\n    return \"y={:.4f}+{}x\".format(A(X,Y),B(X,Y))\n#f\"y={A(X,Y)}+{B(X,Y)}x\"\n#\"y={:.4f}+{:.4f}x\".format(A(X,Y),B(X,Y))\n\t#return \"$\\sin \\\\theta_t=({:.2f}\\pm{:.2f})\\\\\\\\+({:.2f}\\pm{:.2f})\\sin \\\\theta_i$\".format(A(X,Y),sigma_A(X,Y),B(X,Y),sigma_B(X,Y))\ndef y_pred(x,X,Y):\n\ta=A(X,Y)\n\tb=B(X,Y)\n\tx=np.array(x)\n\treturn a+b*x\n", "meta": {"hexsha": "f879b71a6362706709adf47af405cdd4a8cda47a", "size": 1156, "ext": "py", "lang": "Python", "max_stars_repo_path": "Actividad_7/linear_fitting.py", "max_stars_repo_name": "jerck1/MetodosComputacionales1", "max_stars_repo_head_hexsha": "a0002ea81902e6649ae05983faf59ac1bcb3f2ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-18T00:17:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T00:17:30.000Z", "max_issues_repo_path": "Actividad_7/linear_fitting.py", "max_issues_repo_name": "jerck1/MetodosComputacionales1", "max_issues_repo_head_hexsha": "a0002ea81902e6649ae05983faf59ac1bcb3f2ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Actividad_7/linear_fitting.py", "max_forks_repo_name": "jerck1/MetodosComputacionales1", "max_forks_repo_head_hexsha": "a0002ea81902e6649ae05983faf59ac1bcb3f2ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2022-03-08T22:11:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T00:17:31.000Z", "avg_line_length": 22.6666666667, "max_line_length": 129, "alphanum_fraction": 0.5761245675, "include": true, "reason": "import numpy", "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517437261225, "lm_q2_score": 0.9019206837793828, "lm_q1q2_score": 0.8821250974730821}}
{"text": "import numpy as np\n\n# Constants\nSCARA_X_OFFSET = 1.035 # meters, indexed from bottom left corner\nSCARA_Y_OFFSET = 0.097 # meters, indexed from bottom left corner\n\nr1 = 0.5 # meters, length of the first arm\nr2 = 0.5 # meters, length of the second arm\n\n# Positional definitions for SCARA:\n#\n# Angles of theta_1, theta_2 defined WRT horizontal. \n#\n# SCARA (0, 0)\n#  |\n#  v\n# theta_1----(r1)------theta_2------(r2)----tip\n\n\ndef fkin(theta_1, theta_2):\n    '''\n    Returns (x, y) position as a function of the joint angles q0, q1\n    '''\n    return np.array([\n        SCARA_X_OFFSET +r1*np.cos(theta_1) + r2*np.cos(-theta_2),\n        SCARA_Y_OFFSET +r1*np.sin(theta_1) + r2*np.sin(-theta_2)])\n\n\ndef ikin(x, y):\n    '''\n    Returns array of [(theta_1_1, theta_1_2), (theta_2_1, theta_2_2)] as a\n    function of the (x, y) position given. Returns\n    None if (x, y) is out of bounds or out of reach.\n    '''\n\n    # Else, compute the branches\n    x = x - SCARA_X_OFFSET\n    y = y - SCARA_Y_OFFSET\n\n    # Check if out of reach\n    if (np.sqrt((x)**2 + (y)**2) > r1 + r2):\n        return None\n    # Check if out of bounds\n    if (y < 0):\n        return None\n\n    # angle from base to desired point\n    theta_t = np.arctan2(y, x)\n    \n    # calculate the angle at the elbow using law  of cosines\n    theta_1_2 = np.arccos((x**2 + y**2 - r1**2 -r2**2)/(2*r1*r2))   \n\n    # difference between angles \n    theta_1_1 = theta_t - np.arctan2((r1*np.sin(theta_1_2)), (r1 + r2 * np.cos(theta_1_2)))\n\n    # calculate the second set of angles\n    theta_2_2 = -1 * theta_1_2\n\n    theta_2_1 = theta_t + (theta_t - theta_1_1)\n\n    return np.array(\n        [[theta_1_1, -(theta_1_1+theta_1_2)],\n         [theta_2_1, -(theta_2_1+theta_2_2)]])\n\n\ndef jacobian(thetas):\n    return np.array(\n        [[-r1*np.sin(thetas[0]), -r2*np.sin(thetas[1])],\n         [r1*np.cos(thetas[0]), r2*np.cos(thetas[1])]])\n\n", "meta": {"hexsha": "d741dc064cdcbe1b41daca15acf1133500034d0e", "size": 1876, "ext": "py", "lang": "Python", "max_stars_repo_path": "hockbot/src/hockbot/scara_kinematics.py", "max_stars_repo_name": "wwerst/EE134", "max_stars_repo_head_hexsha": "ca558e4e6dc874a7b91885a786fd5eae8492afca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hockbot/src/hockbot/scara_kinematics.py", "max_issues_repo_name": "wwerst/EE134", "max_issues_repo_head_hexsha": "ca558e4e6dc874a7b91885a786fd5eae8492afca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hockbot/src/hockbot/scara_kinematics.py", "max_forks_repo_name": "wwerst/EE134", "max_forks_repo_head_hexsha": "ca558e4e6dc874a7b91885a786fd5eae8492afca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4225352113, "max_line_length": 91, "alphanum_fraction": 0.6108742004, "include": true, "reason": "import numpy", "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517501236461, "lm_q2_score": 0.9019206692796966, "lm_q1q2_score": 0.8821250890616975}}
{"text": "from math import sqrt\nfrom numpy import linspace as ls\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatch\n\n\nclass Quadratic(object):\n    \"\"\"\n    This is a Quadratic function class that takes a quadratic equation in standard form\n    and returns anything that you might want.\n\n    X and Y intercepts, vertex of graph, factored form of equation, vertex form of equation,\n    graph of function as a vector or raster image (png, or pdf).\n\n    USAGE EXAMPLES:\n    >>> q = Quadratic(5, 25, 30)\n    >>> print(q)\n    f(x) = 5x^2 + 25x + 30\n    >>> q.vertex()\n    (-2.5, -1.25)\n    >>> q.factored_form()\n    f(x) = 5(x+2)(x+3)\n    \"\"\"\n\n    def __init__(self, a, b, c):\n        self.a = float(a)\n        self.b = float(b)\n        self.c = float(c)\n        self.y_int = (0, self.c)\n        self.discriminant = self.b ** 2 - (4 * self.a * self.c)\n\n    def __repr__(self, encode=True):\n        \"\"\"\n        Python2 doesn't have default unicode support so I\n        have added the encode method but matplotlib doesn't need the encode method\n        so I made a default parameter and enter False when I'm using this for matplotlib\n        \"\"\"\n        if self.b == 0 and self.c == 0:\n            if encode:\n                return u'f(x) = %dx\\u00b2'.encode('UTF-8') % self.a\n            else:\n                return u'f(x) = %dx\\u00b2' % self.a\n        elif self.a == 0:\n            if encode:\n                return u'f(x) = %dx%+d'.encode('UTF-8') % (self.b, self.c)\n            else:\n                return u'f(x) = %dx%+d' % (self.b, self.c)\n        elif self.b == 0:\n            if encode:\n                return u'f(x) = %dx\\u00b2%+d'.encode('UTF-8') % (self.a, self.c)\n            else:\n                return u'f(x) = %dx\\u00b2%+d' % (self.a, self.c)\n        elif self.c == 0:\n            if encode:\n                return u'f(x) = %dx\\u00b2%+dx'.encode('UTF-8') % (self.a, self.b)\n            else:\n                return u'f(x) = %dx\\u00b2%+dx' % (self.a, self.b)\n        else:\n            if encode:\n                return u'f(x) = %dx\\u00b2%+dx%+d'.encode('UTF-8') % (self.a, self.b, self.c)\n            else:\n                return u'f(x) = %dx\\u00b2%+dx%+d' % (self.a, self.b, self.c)\n\n    @staticmethod\n    def __is_square(num):\n        \"\"\"\n        Checks if number is a perfect square.\n        I'm adding 0.5 to root because you can never rely on exact comparisons\n        when dealing with float numbers.\n        Maybe sqrt(49) evaluates to 6.99999 or 7.00001\n        so taking the square of the int right off isn't going to work.\n        we add 0.5 and then take int() to ensure we have what we want.\n        \"\"\"\n        root = sqrt(num)\n        if int(root + 0.5) ** 2 == num:\n            return True\n        else:\n            return False\n\n    def has_x_intercept(self):\n        \"\"\"\n        According to a mathematical rule:\n        1. If the discriminant of a quadratic function is greater than 0,\n        the vertex is below x axis, therefore the graph has 2 x-intercepts.\n        2. If the discriminant of a quadratic function is equal to 0,\n        the vertex is on x axis, therefore the graph has 1 x-intercept.\n        3. If the discriminant of a quadratic function is less than 0,\n        the vertex is above x axis, therefore the graph doesn't have x-intercepts.\n        \"\"\"\n        if self.discriminant > 0:\n            return 2\n        elif self.discriminant == 0:\n            return 1\n        else:\n            return 0\n\n    def x_intercepts(self):\n        \"\"\"\n        If graph has 0 x-intercepts, return None.\n        If graph has 1 x-intercept, return vertex.\n        If graph has 2 x-intercepts, use quadratic formula to get x-intercepts.\n        \"\"\"\n        if self.has_x_intercept() == 0:\n            return None\n        elif self.has_x_intercept() == 1:\n            return (self.vertex()[0],)\n        else:\n            x1 = (-self.b + sqrt(self.discriminant)) / (2 * self.a)\n            x2 = (-self.b - sqrt(self.discriminant)) / (2 * self.a)\n            return round(x1, 3), round(x2, 3)\n\n    def is_factorable(self):\n        \"\"\"\n        According to a mathematical rule:\n        If the discriminant of a quadratic function is a perfect square,\n        the equation is factorable.\n        \"\"\"\n        if self.discriminant < 0:\n            return False\n        if self.__is_square(self.discriminant):\n            return True\n        return False\n\n    def factored_form(self):\n        \"\"\"\n        In order to find the factored form, we need to find the value\n        of a, which is the vertical stretch coefficient. We can do that\n        by evaluating an x point at a certain distance from the vertex,\n        then we divide it by the value it would have in an x^2 graph.\n        The other factors are easily obtained from the x intercepts.\n        EXAMPLE:\n        f(x) = 2x^2 + 4x + 2\n        vertex = (-1, 0)\n \n        evaluate f(0) = 2\n        k) x distance from vertex-x = 1\n        k) y distance from vertex-y = 2\n \n        f(1) in an x^2 graph = 1\n        h) x distance from vertex-x = 1\n        h) y distance from vertex-y = 1\n \n        a = k)dist-y / h)dist-y = 2 / 1 = 2\n \n        Remaining factors:\n        (x + (-x_int 1)) * (x + (-x_int 2))\n        \"\"\"\n        if self.is_factorable():\n            x_ints = self.x_intercepts()\n            vertex = self.vertex()\n            if len(x_ints) == 1:\n                a = self.evaluate(0) / ((0 - x_ints[0]) ** 2)\n                return u'f(x) = %d(x%+d)\\u00b2'.encode('UTF-8') % (a, -x_ints[0])\n            a = self.evaluate(max(x_ints)) - vertex[1] / ((max(x_ints) - vertex[0]) ** 2)\n            return u'f(x) = %d(x%+d)(x%+d)'.encode('UTF-8') % (a, -x_ints[0], -x_ints[1])\n        else:\n            return None\n\n    def vertex(self):\n        \"\"\"\n        Using a shortened method of completing the square, I get the x and y of the vertex\n        for any given graph f(x) = ax^2 + bx + c\n        the vertex form is f(x) = a(x - h)^2 + k\n        we can convert using this method:\n        EXAMPLE. f(x) = -4x^2 - 32x + 6\n        1. factor the coefficients\n            f(x) = -4(x^2 + 8x) + 6\n\n        2. create a perfect square trinomial\n            f(x) = -4(x^2 + 8x + 16 - 16) + 6\n\n        in the second step we are taking half of the second coefficient in the bracket and squaring it.\n        but since we can't change the value of our graph we also subtract the same value.\n\n        3. take the subtracted value out of the bracket (multiply by a).\n            f(x) = -4(x^2 + 8x + 16) + 6 + 64\n\n        4. now we can factor the bracket into a binomial.\n            f(x) = -4(x + 4)^2 + 70\n\n        From this final equation we can get the vertex which is (-4, 70)\n        To only get the vertex, we don't need to go through all of the steps.\n        We only need half of the second coefficient for the x of the vertex.\n        The y of the vertex is half of the second coefficient squared times a, subtracted from c.\n        \"\"\"\n        x = (self.b / self.a) / 2\n        x = -x if not x == 0 else 0\n        y = self.c - (x ** 2 * self.a)\n        return round(x, 3), round(y, 3)\n\n    def vertex_form(self):\n        \"\"\"\n        This function gets the vertex and goes the extra step of printing\n        the function in proper vertex form.\n        \"\"\"\n        if self.b == 0 and self.c == 0:\n            return u'f(x) = %dx\\u00b2'.encode('UTF-8') % self.a\n        x = (self.b / self.a) / 2\n        y = self.c - (x ** 2 * self.a)\n        return u'f(x) = %.2f(x%+.2f)\\u00b2%+.2f'.encode('UTF-8') % (self.a, round(x, 3), round(y, 3))\n\n    def evaluate(self, x):\n        \"\"\"\n        Returns y value for any given x\n        \"\"\"\n        return self.a * (x**2) + self.b * x + self.c\n\n    def graph(self, x_range=None, vector=False):\n        \"\"\"\n        This function uses matplotlib to graph the function.\n        If no range is given, it takes the x of the vertex and\n        graphs in a range of 5 on both sides.\n\n        I'm using numpy linspace to create 1000 evenly spaced points within the range.\n        So the graph is always smooth no matter how small the range.\n\n        The function loops through the array of x and simply plugs it into the function\n        and plots each point.\n\n        It also adds the equation, the x and y intercepts and the vertex as labels.\n\n        It saves the graph as \"graph.png\" into the same directory by default.\n        If the vector option is on, it saves as a vector image \"graph.pdf\".\n        \"\"\"\n        vertex = self.vertex()\n        if x_range:\n            x = ls(x_range[0], x_range[1], 1000)\n        else:\n            x = ls(vertex[0] - 5, vertex[0] + 5)\n        y = [((self.a * (i ** 2)) + (self.b * i) + self.c) for i in x]\n        plt.plot(x, y)\n        x_ints = self.x_intercepts() if self.has_x_intercept() else None\n\n        patches = [mpatch.Patch(color='black', label=self.__repr__(False)),\n                   mpatch.Patch(color='red', label=\"Vertex \" + str(vertex)),\n                   mpatch.Patch(color='blue', label=\"Y Intercept \" + str(self.y_int))]\n        if x_ints is not None:\n            patches.append(mpatch.Patch(color='orange', label=\"X Intercept(s) \" + str(x_ints)))\n\n        plt.grid()\n        plt.legend(handles=patches)\n        if vector:\n            plt.savefig('graph.pdf', bbox_inches='tight')\n        else:\n            plt.savefig('graph.png', bbox_inches='tight')\n", "meta": {"hexsha": "3b45b663d7112868e850cdc79a46a7fe579debef", "size": 9332, "ext": "py", "lang": "Python", "max_stars_repo_path": "Quad.py", "max_stars_repo_name": "CodeMaker33/PyQuad", "max_stars_repo_head_hexsha": "7db1e1da89f313fd3186f82074dc835b0e43b755", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-21T17:10:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-21T17:10:53.000Z", "max_issues_repo_path": "Quad.py", "max_issues_repo_name": "Khachig/PyQuad", "max_issues_repo_head_hexsha": "7db1e1da89f313fd3186f82074dc835b0e43b755", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Quad.py", "max_forks_repo_name": "Khachig/PyQuad", "max_forks_repo_head_hexsha": "7db1e1da89f313fd3186f82074dc835b0e43b755", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7813765182, "max_line_length": 103, "alphanum_fraction": 0.5480068581, "include": true, "reason": "from numpy", "num_tokens": 2601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97805174308637, "lm_q2_score": 0.90192067257508, "lm_q1q2_score": 0.8821250859376882}}
{"text": "import numpy as np\n\nclass BinomialTree:\n  def __init__(self, S0, r, d, sigma, T):\n    self.S0 = S0\n    self.r = r\n    self.d = d\n    self.sigma = sigma\n    self.T = T\n\n  def generate_tree(self, N, model = 'crr'):\n    '''\n    generate an upper triangular matrix recording all possible price paths \n    by using up and down moves only S0, sigma, T and N.\n\n    inputs: \n    N: number of levels of node\n    mode: up and down multipliers are decided by either crr or GBM model\n\n    Outputs:\n    dt: T / N\n    up: up-move multiplier\n    down: down-move multiplier\n    price_tree: numpy array containing prices\n\n    '''\n\n    dt = self.T / N\n\n    # Construct a price tree using numpy array\n    # Given N periods, there are (N+1) nodes in total \n    # Period starts from 0 (current price)\n    price_tree = np.zeros((N+1,N+1))\n\n    if model == 'crr':\n      # Cox, Ross & Rubinstein (CRR) formulas are\n      # $$up = e^{\\sigma\\sqrt{\\Delta t}} \\quad \\text{and} \\quad down = e^{-\\sigma\\sqrt{\\Delta  t}} =\\frac{1}{up}.$$\n      # Note that ud = 1 \n      up = np.exp(self.sigma * np.sqrt(dt))\n      down = 1 / up \n\n    elif model == 'gbm':\n      # Geometric Brownian Motion (GBM) formulas are\n      # $$up = e^{ (r - d - 0.5 \\sigma^2) \\Delta t + \\sigma\\sqrt{\\Delta t}} \\quad \\text{and} \\quad down = e^{ (r - d - 0.5 \\sigma^2) \\Delta t - \\sigma\\sqrt{\\Delta t}}.$$\n      # Note that ud \\neq 1 \n      # Simplifying the discrete GBM gives\n      # S_{j\\Delta t} = S_{(j-1)\\Delta t} exp( ( r - 0.5 \\sigma^2)\\Delta t + \\sigma \\sqrt{\\Delta t}Z_j)\n\n      det_comp = (self.r - self.d - 0.5 * self.sigma ** 2) * dt\n      stoc_comp = self.sigma * np.sqrt(dt)\n\n      up = np.exp(det_comp + stoc_comp)\n      down = np.exp(det_comp - stoc_comp)\n\n    # concepts: at [i,j]-th entry of the tree, \n    # number of up + number of down = j (col)\n    # number of down = i (row)\n    # So, number of up = j - i\n    # Hence, [i,j]-th entry = S0 x up^{j-i} x down^i\n\n    size = (N+1, N+1)\n    f = lambda i,j : up**(j-i) * down**i if i <= j else 0\n    price_tree = self.S0 * np.fromfunction(np.vectorize(f), size)\n\n    return dt, up, down, price_tree\n\n  def option_price(self, num_sim, payoff, model = 'crr', exercise_style = 'European'):\n    '''\n    inputs:\n    num_sim: number of simulations \n    payoff: (lambda function) option's payoff function at maturity\n    model: either crr or gbm\n    exercise_style: either European or American\n\n    output:\n    list of (should converge) prices\n    '''\n    prices = [0] * num_sim\n\n    for a in range(1, num_sim + 1):\n      N = 2 ** a\n      dt, up, down, price_tree = self.generate_tree(N, model = model) \n\n      # price option\n      if model == 'crr':\n        # To ensure no-arbitrage, we must have \n        # 0 <= p_tilde <= 1, that is, d <= e^{r\\delta t} <= u, that is, \n        # e^{-sigma \\sqrt{\\Delta t}} <= e^{r\\delta t} <= e^{sigma \\sqrt{\\Delta t}}, that is, \n        # -sigma <= r \\sqrt{T/N} <= sigma\n        # Since the LHS is always true, so we just need to check r \\sqrt{T/N} <= sigma\n        assert self.r * np.sqrt(self.T/N) <= self.sigma, ' r \\sqrt{T/N} <= sigma is not fulfilled, leading to arbitrage'\n      \n      p_tilde = (np.exp( (self.r - self.d) * dt ) - down) / (up - down)\n      cash_flows = np.zeros((N+1,N+1))\n      cash_flows[:, -1] =  payoff(price_tree[:, -1])\n\n      if exercise_style == 'European':\n        for j in range(N-1, -1, -1):\n          for i in range(j+1):\n            cash_flows[i,j] = np.exp(-self.r * dt) * (p_tilde * cash_flows[i,j+1] + (1-p_tilde) * cash_flows[i+1,j+1] )\n\n      elif exercise_style == 'American':\n        exercise_value = payoff(price_tree)\n        for j in range(N-1, -1, -1):\n          for i in range(j+1):\n            cash_flows[i,j] = np.maximum(exercise_value[i,j], np.exp(-self.r * dt) * (p_tilde * cash_flows[i,j+1] + (1-p_tilde) * cash_flows[i+1,j+1] ))\n\n      prices[a - 1] = cash_flows[0,0]\n\n    return prices", "meta": {"hexsha": "60d10c000a8630cda6b5195ea30b5b5d5426bdba", "size": 3881, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/Binomial_tree.py", "max_stars_repo_name": "manityagi/Option_pricing", "max_stars_repo_head_hexsha": "129345146cb4b657eda4497561c4a2bc119e077c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/Binomial_tree.py", "max_issues_repo_name": "manityagi/Option_pricing", "max_issues_repo_head_hexsha": "129345146cb4b657eda4497561c4a2bc119e077c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/Binomial_tree.py", "max_forks_repo_name": "manityagi/Option_pricing", "max_forks_repo_head_hexsha": "129345146cb4b657eda4497561c4a2bc119e077c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2818181818, "max_line_length": 169, "alphanum_fraction": 0.5717598557, "include": true, "reason": "import numpy", "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446471538802, "lm_q2_score": 0.9059898305367525, "lm_q1q2_score": 0.8821121488779602}}
{"text": "#!/usr/local/bin/python3.9\n'''\nModule for significance testing\n\nChange Log\n==========\n0.0.1 (2021-04-11)\n0.0.2 (2021-07-07)\n----------\nimplemented loop option for multiple variables in dataframe\n'''\nimport numpy as np\nfrom scipy import stats\n\nnp.random.seed(7654567)  # fix seed to get the same result\n\n'''\nOne-sample t-test\ntwo-sided test for the null hypothesis that the expected value (mean) of a \nsample of independent observations a is equal to the given population mean, popmean\n'''\nrvs = stats.norm.rvs(loc=5, scale=10, size=(50))\nstat, p = stats.ttest_1samp(rvs,5.0)\nprint(stat)\nprint(p)\n\n'''\nIndependent-samples t-test\ntwo-sided test for the null hypothesis that 2 independent samples have identical average \n(expected) values. This test assumes that the populations have identical variances by default.\n\nPerform check for homogeneity of variance prior to running\ni.e., Levene Test\n'''\nrvs1 = stats.norm.rvs(loc=5,scale=10,size=500)\nrvs2 = stats.norm.rvs(loc=5,scale=10,size=500)\nrvs3 = stats.norm.rvs(loc=5,scale=30,size=500)\n\n#Equal variance\nfrom scipy.stats import levene\nlevene(rvs1, rvs2)\n\nstat, p = stats.ttest_ind(rvs1, rvs2, equal_var=True, alternative='two-sided')\nprint(stat, p)\n\n# Unequal variance\nlevene(rvs1, rvs3)\n\nstat, p = stats.ttest_ind(rvs1, rvs3, equal_var=False)\nprint(stat, p)\n\n\n# Mann-Whitney U-test\nn = 10000\nstart = 0\nwidth = 20\n\na = 0\ndata_normal = skewnorm.rvs(size=n, a=a,loc = start, scale=width)\n\na = 3\ndata_skew = skewnorm.rvs(size=n, a=a,loc = start, scale=width)\n\nf, (ax1, ax2) = plt.subplots(1, 2)\nax1.hist(data_normal, bins='auto')\nax1.set_title('probability density (random)')\nax2.hist(data_skew, bins='auto')\nax2.set_title('Skewed data')\nplt.tight_layout()\n\nstat, p = stats.mannwhitneyu(data_normal, data_skew, alternative='two-sided')\nprint(stat)\nprint('%.5f' % p)\nresults = stats.mannwhitneyu(data_normal, data_skew, alternative='two-sided')\n\n'''\nPaired samples t-test\ntwo-sided test for the null hypothesis that 2 related \nor repeated samples have identical average (expected) values\n'''\nnp.random.seed(12345678)\nrvs1 = stats.norm.rvs(loc=5,scale=10,size=500)\nrvs2 = (stats.norm.rvs(loc=5,scale=10,size=500) + stats.norm.rvs(scale=0.2,size=500))\nstats.ttest_rel(rvs1,rvs2, alternative='two-sided')\n\n'''\nWilcox signed-rank test\nTests the null hypothesis that two related paired samples come from the same distribution. \nIn particular, it tests whether the distribution of the differences x - y is symmetric about zero. \nIt is a non-parametric version of the paired T-test\n'''\nfrom numpy.random import randn\nfrom scipy.stats import wilcoxon\ndata1 = 5 * randn(100) + 50\ndata2 = 5 * randn(100) + 51\nstat, p = wilcoxon(data1, data2)\nprint('Statistic=%.3f, p=%.3f' % (stat, p))\n\n\n# Code for interpretation\nalpha = 0.05\nif p > alpha:\n\tprint('Fail to reject H0')\nelse:\n\tprint('Reject H0')\n\n\n\n'''\nLoop through columns in dataframe\nInterpret Hypothesis\nFDR correction for multiple p-values\n\n2 options:\n1. parametric (normallly distributed) variables - run t-test\n2. non-parametric (not normally distributed variables) - run Wilcox test\n'''\n# One-sample t-test (for parametric data)\ncol_names_par = ['', '', '']\ntrue_mu = 0\n\npvals_par = []\nfor i in col_names_par:\n\tprint('\\n')\n\tw, p = stats.ttest_1samp(df[i], true_mu)\n\tprint(i)\n\tprint(w, p)\n\tpvals_par.append(p)\n\talpha = 0.05\n\tif p > alpha:\n\t\tprint('Fail to reject H0\\nNot statistically different from zero')\n\telse:\n\t\tprint('Reject H0\\n*****Statistically different from zero*****')\n\n# FDR correction for parametric p-values\nmulti.multipletests(pvals_par, alpha=0.05, method='fdr_bh',\n\t\t\t\t\tis_sorted=False, returnsorted=False)\n\n# Wilcox test (for non-parametric data)\n# col_names_npar\ncol_names_npar = ['', '', '']\n\npvals_npar = []\nfor i in col_names_npar:\n\tprint('\\n')\n\tw, p = wilcoxon(df[i])\n\tprint(i)\n\tprint(w, p)\n\tpvals_npar.append(p)\n\talpha = 0.05\n\tif p > alpha:\n\t\tprint('Fail to reject H0\\nNot statistically different from zero')\n\telse:\n\t\tprint('Reject H0\\n*****Statistically different from zero*****')\n\n# FDR correction for non-parametric p-values\nmulti.multipletests(pvals_npar, alpha=0.05, method='fdr_bh',\n\t\t\t\t\tis_sorted=False, returnsorted=False)", "meta": {"hexsha": "66d0f571dec12753cfc94392d4cf97bc5315cccc", "size": 4145, "ext": "py", "lang": "Python", "max_stars_repo_path": "significance_testing.py", "max_stars_repo_name": "jessedesimone/python_stats", "max_stars_repo_head_hexsha": "fab60291a909efa14bea6dd97cd59c27bb53f65e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "significance_testing.py", "max_issues_repo_name": "jessedesimone/python_stats", "max_issues_repo_head_hexsha": "fab60291a909efa14bea6dd97cd59c27bb53f65e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "significance_testing.py", "max_forks_repo_name": "jessedesimone/python_stats", "max_forks_repo_head_hexsha": "fab60291a909efa14bea6dd97cd59c27bb53f65e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2341772152, "max_line_length": 99, "alphanum_fraction": 0.7249698432, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 1216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.9334308138072713, "lm_q1q2_score": 0.882087185683794}}
{"text": "# coding: utf-8\n\n__author__ = 'Mário Antunes'\n__version__ = '0.1'\n__email__ = 'mariolpantunes@gmail.com'\n__status__ = 'Development'\n\n\nimport math\nimport numpy as np\n\n\ndef lagrange_derivative(x: float, x0: float, x1: float, x2: float, y0: float, y1: float, y2: float) -> float:\n    \"\"\"\n    Three point lagrange derivative.\n\n    It computes the derivative of \\\\(x\\\\) based on three points:\n    \\\\([(x_0, y_0), (x_1, y_1), (x_2, y_2)]\\\\)\n    Depending od the value of \\\\(x\\\\), we can compute the forward,\n    backward or central derivative.\n\n\n    Args:\n        x (float): the value where the derivative will be computed\n        x0 (float): first x value\n        x1 (float): second x value\n        x2 (float): third x value\n        y0 (float): first y value\n        y1 (float): second y value\n        y2 (float): third y value\n    \n    Returns:\n        float: the first derivative for \\\\(x\\\\) value\n\n    \"\"\"\n    p0 = y0 * (2*x-x1-x2) / ((x0-x1)*(x0-x2))\n    p1 = y1 * (2*x-x0-x2) / ((x1-x0)*(x1-x2))\n    p2 = y2 * (2*x-x0-x1) / ((x2-x0)*(x2-x1))\n    return p0+p1+p2\n\n\ndef cfd(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Computes the central first order derivative for uneven space sequences.\n\n    This method uses the three point lagrange derivative to compute the\n    derivative in uneven time series.\n    The first and last elements are computed beased on the forward and \n    backward definition of the first derivative.\n\n    Args:\n        x (np.ndarray): the value of the points in the x axis coordinates\n        y (np.ndarray): the value of the points in the y axis coordinates\n\n    Returns:\n        np.ndarray: the first order derivative\n    \"\"\"\n    d1 = []\n\n    # compute the first point with the forward definition\n    y0, y1, y2 = y[0:3]\n    x0, x1, x2 = x[0:3]\n    d = lagrange_derivative(x0, x0, x1, x2, y0, y1, y2)\n    d1.append(d)\n\n    # compute n-2 points with the central definition\n    for i in range(1, len(x) - 1):\n        y0, y1, y2 = y[i-1:i+2]\n        x0, x1, x2 = x[i-1:i+2]\n        d = lagrange_derivative(x1, x0, x1, x2, y0, y1, y2)\n        d1.append(d)\n\n    # compute the last point with the backwards definition\n    y0, y1, y2 = y[-3:len(y)+1]\n    x0, x1, x2 = x[-3:len(x)+1]\n    d = lagrange_derivative(x2, x0, x1, x2, y0, y1, y2)\n    d1.append(d)\n\n    return np.array(d1)\n\n\ndef csd(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Computes the central second order derivative for uneven space sequences.\n\n    The computation is based on the second order polynomial fitting.\n\n    Args:\n        x (np.ndarray): the value of the points in the x axis coordinates\n        y (np.ndarray): the value of the points in the y axis coordinates\n\n    Returns:\n        np.ndarray: the second order derivative\n    \"\"\"\n    d2 = []\n\n    # compute the first point with the forward definition\n    y0, y1, y2 = y[0:3]\n    x0, x1, x2 = x[0:3]\n    d = 2.0 * ((x1-x0)*y2 - (x2-x0)*y1 + (x2-x1)*y0) / ((x1-x0)*(x2-x1)*(x2-x0))\n    d2.append(d)\n\n    # compute n-2 points with the central definition\n    for i in range(1, len(x) - 1):\n        y1, y2, y3 = y[i-1:i+2]\n        x1, x2, x3 = x[i-1:i+2]\n        d = (2*y1/((x2-x1)*(x3-x1))) - (2*y2/((x3-x2)*(x2-x1)))+(2*y3/((x3-x2)*(x3-x1)))\n        d2.append(d)\n\n    # compute the last point with the backwards definition\n    y2, y1, y0 = y[-3:len(y)+1]\n    x2, x1, x0 = x[-3:len(x)+1]\n    d = 2.0 * ((x1-x2)*y0 - (x0-x2)*y1 + (x0-x1)*y2) / ((x1-x2)*(x0-x1)*(x0-x2))\n    d2.append(d)\n\n    return np.array(d2)\n", "meta": {"hexsha": "d9df45bab04306a4ef1d6fa2d696757c7f8c27d9", "size": 3475, "ext": "py", "lang": "Python", "max_stars_repo_path": "uts/gradient.py", "max_stars_repo_name": "mariolpantunes/uts", "max_stars_repo_head_hexsha": "e6fd176464f953186f6b7aebedbec717838f5ee5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-09T15:37:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T15:37:58.000Z", "max_issues_repo_path": "uts/gradient.py", "max_issues_repo_name": "mariolpantunes/uts", "max_issues_repo_head_hexsha": "e6fd176464f953186f6b7aebedbec717838f5ee5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-20T22:22:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-20T22:23:04.000Z", "max_forks_repo_path": "uts/gradient.py", "max_forks_repo_name": "mariolpantunes/uts", "max_forks_repo_head_hexsha": "e6fd176464f953186f6b7aebedbec717838f5ee5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-29T20:13:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-29T20:13:18.000Z", "avg_line_length": 29.7008547009, "max_line_length": 109, "alphanum_fraction": 0.5890647482, "include": true, "reason": "import numpy", "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.9196425234694067, "lm_q1q2_score": 0.8820790694383234}}
{"text": "\"\"\"\n[2015-05-11] Challenge #214 [Easy] Calculating the standard deviation\nhttp://www.reddit.com/r/dailyprogrammer/comments/35l5eo/20150511_challenge_214_easy_calculating_the/\n\nDescription\n\nStandard deviation is one of the most basic measurments in statistics. For some collection of values (known as a \"population\" in statistics), it measures how dispersed those values are. If the standard deviation is high, it means that the values in the population are very spread out; if it's low, it means that the values are tightly clustered around the mean value.\nFor today's challenge, you will get a list of numbers as input which will serve as your statistical population, and you are then going to calculate the standard deviation of that population. There are statistical packages for many programming languages that can do this for you, but you are highly encouraged not to use them: the spirit of today's challenge is to implement the standard deviation function yourself.\nThe following steps describe how to calculate standard deviation for a collection of numbers. For this example, we will use the following values:\n5 6 11 13 19 20 25 26 28 37\nFirst, calculate the average (or mean) of all your values, which is defined as the sum of all the values divided by the total number of values in the population. For our example, the sum of the values is 190 and since there are 10 different values, the mean value is 190/10 = 19\nNext, for each value in the population, calculate the difference between it and the mean value, and square that difference. So, in our example, the first value is 5 and the mean 19, so you calculate (5 - 19)2 which is equal to 196. For the second value (which is 6), you calculate (6 - 19)2 which is equal to 169, and so on.\nCalculate the sum of all the values from the previous step. For our example, it will be equal to 196 + 169 + 64 + ... = 956.\nDivide that sum by the number of values in your population. The result is known as the variance of the population, and is equal to the square of the standard deviation. For our example, the number of values in the population is 10, so the variance is equal to 956/10 = 95.6.\nFinally, to get standard deviation, take the square root of the variance. For our example, sqrt(95.6) ≈ 9.7775.\nFormal inputs & outputs\n\nInput\n\nThe input will consist of a single line of numbers separated by spaces. The numbers will all be positive integers.\nOutput\n\nYour output should consist of a single line with the standard deviation rounded off to at most 4 digits after the decimal point.\nSample inputs & outputs\n\nInput 1\n\n5 6 11 13 19 20 25 26 28 37\nOutput 1\n\n9.7775\nInput 2\n\n37 81 86 91 97 108 109 112 112 114 115 117 121 123 141\nOutput 2\n\n23.2908\nChallenge inputs\n\nChallenge input 1\n\n266 344 375 399 409 433 436 440 449 476 502 504 530 584 587\nChallenge input 2\n\n809 816 833 849 851 961 976 1009 1069 1125 1161 1172 1178 1187 1208 1215 1229 1241 1260 1373\nNotes\n\nFor you statistics nerds out there, note that this is the population standard deviation, not the sample standard deviation. We are, after all, given the entire population and not just a sample.\nIf you have a suggestion for a future problem, head on over to /r/dailyprogrammer_ideas and let us know about it!\n\"\"\"\n\n# 1st implementation: clear, short, matches the problem definition\ndef standard_deviation_1(input_str):\n    list = [int(s) for s in input_str.split()]\n    count = len(list)\n    avg = sum(list) / count\n    variance = sum((n - avg)**2 for n in list) / count\n    return variance**0.5\n\n# 2nd implementation: 1 pass, O(1) memory usage\ndef standard_deviation(input_str):\n    n_sum, n2_sum, count = 0, 0, 0\n    for s in input_str.split():\n        n = int(s)\n        n_sum += n\n        n2_sum += n*n\n        count += 1\n    if count == 0:\n        return None\n    avg = n_sum / count\n    return (n2_sum/count - n_sum*n_sum/(count*count))**0.5\n\n    \ndef tests():\n    assert math.trunc(standard_deviation('5 6 11 13 19 20 25 26 28 37') * 10000.0) == 97775, 'Test 1'\n    assert math.trunc(standard_deviation('37 81 86 91 97 108 109 112 112 114 115 117 121 123 141') * 10000.0) == 232908, 'Test 2'\n    assert math.trunc(standard_deviation('266 344 375 399 409 433 436 440 449 476 502 504 530 584 587') * 10000.0) == 836615, 'Test 3'\n    assert math.trunc(standard_deviation('809 816 833 849 851 961 976 1009 1069 1125 1161 1172 1178 1187 1208 1215 1229 1241 1260 1373') * 10000.0) == 1701272, 'Test 4'\n    print('All tests passed')\n\nif __name__ == '__main__':\n    tests()\n\n# Python 3.4 => import statistics; statistics.pstdev(list)\n# Others => import numpy; numpy.std()\n\n", "meta": {"hexsha": "47dda74373b140674078e8054dc5df31e6788bf0", "size": 4594, "ext": "py", "lang": "Python", "max_stars_repo_path": "E214_StandardDeviation.py", "max_stars_repo_name": "feliposz/daily-programmer-solutions", "max_stars_repo_head_hexsha": "85114b13118384895a1fe37fe041fb06ed074353", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "E214_StandardDeviation.py", "max_issues_repo_name": "feliposz/daily-programmer-solutions", "max_issues_repo_head_hexsha": "85114b13118384895a1fe37fe041fb06ed074353", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "E214_StandardDeviation.py", "max_forks_repo_name": "feliposz/daily-programmer-solutions", "max_forks_repo_head_hexsha": "85114b13118384895a1fe37fe041fb06ed074353", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.8045977011, "max_line_length": 415, "alphanum_fraction": 0.7418371789, "include": true, "reason": "import numpy", "num_tokens": 1330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611643025387, "lm_q2_score": 0.9184802473724224, "lm_q1q2_score": 0.8820727597554633}}
{"text": "\"\"\"Use Newton's method to solve systems of nonlinear algebraic equations.\"\"\"\nimport numpy as np\n\ndef Newton_system(F, J, x, eps):\n    \"\"\"\n    Solve nonlinear system F=0 by Newton's method.\n    J is the Jacobian of F. Both F and J must be functions of x.\n    At input, x holds the start value. The iteration continues\n    until ||F|| < eps.\n    \"\"\"\n    F_value = F(x)\n    F_norm = np.linalg.norm(F_value, ord=2)     # l2 norm of vector\n    iteration_counter = 0\n    while abs(F_norm) > eps and iteration_counter < 100:\n        delta = np.linalg.solve(J(x), -F_value)\n        x = x + delta\n        F_value = F(x)\n        F_norm = np.linalg.norm(F_value, ord=2)\n        iteration_counter = iteration_counter + 1\n\n    # Here, either a solution is found, or too many iterations\n    if abs(F_norm) > eps:\n        iteration_counter = -1\n    return x, iteration_counter\n\ndef test_Newton_system1():\n    from numpy import cos, sin, pi, exp\n\n    def F(x):\n        return np.array(\n            [x[0]**2 - x[1] + x[0]*cos(pi*x[0]),\n             x[0]*x[1] + exp(-x[1]) - x[0]**(-1.)])\n\n    def J(x):\n        return np.array(\n            [[2*x[0] + cos(pi*x[0]) - pi*x[0]*sin(pi*x[0]), -1],\n             [x[1] + x[0]**(-2.), x[0] - exp(-x[1])]])\n\n    expected = np.array([1, 0])\n    tol = 1e-4\n    x, n = Newton_system(F, J, x=np.array([2, -1]), eps=0.0001)\n    print(n, x)\n    error_norm = np.linalg.norm(expected - x, ord=2)\n    assert error_norm < tol, 'norm of error ={:g}'.format(error_norm)\n    print('norm of error ={:g}'.format(error_norm))\n\ndef test_Newton_system2():\n\n    def F(x):\n        return np.array(\n            [x[0]**2 - x[1] + x[0] - 2,\n             x[1]*x[0] + x[1]**2 + x[0] - 1])\n\n    def J(x):\n        return np.array(\n            [[2*x[0] + 1, -1],\n             [x[1] + 1, x[0] + 2*x[1]]])\n\n    expected = np.array([1, 0])\n    tol = 1e-4\n    x, n = Newton_system(F, J, x=np.array([2, -0.5]), eps=0.0001)\n    print(n, x)\n    error_norm = np.linalg.norm(expected - x, ord=2)\n    assert error_norm < tol, 'norm of error ={:g}'.format(error_norm)\n    print('norm of error ={:g}'.format(error_norm))\n\nif __name__ == '__main__':\n    test_Newton_system1()\n    test_Newton_system2()\n\n", "meta": {"hexsha": "62b6b424c5309d6fef2e5d98fb7b31b4c489593e", "size": 2186, "ext": "py", "lang": "Python", "max_stars_repo_path": "Prog4comp-SL-HPL-Extra/src/Newton_system.py", "max_stars_repo_name": "computational-medicine/BMED360-2021", "max_stars_repo_head_hexsha": "2c6052b9affedf1fee23c89d23941bf08eb2614c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-19T23:22:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T14:04:58.000Z", "max_issues_repo_path": "Prog4comp-SL-HPL-Extra/src/Newton_system.py", "max_issues_repo_name": "computational-medicine/BMED360-2021", "max_issues_repo_head_hexsha": "2c6052b9affedf1fee23c89d23941bf08eb2614c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Prog4comp-SL-HPL-Extra/src/Newton_system.py", "max_forks_repo_name": "computational-medicine/BMED360-2021", "max_forks_repo_head_hexsha": "2c6052b9affedf1fee23c89d23941bf08eb2614c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-26T17:15:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T08:10:06.000Z", "avg_line_length": 30.7887323944, "max_line_length": 76, "alphanum_fraction": 0.5494053065, "include": true, "reason": "import numpy,from numpy", "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.9273632916317102, "lm_q1q2_score": 0.882054379942499}}
{"text": "import numpy as np\r\nfrom scipy.stats import beta\nfrom matplotlib import pyplot as plt\r\n\r\nvisitors_to_A = 1300\nvisitors_to_B = 1275\nconversions_from_A = 120\nconversions_from_B = 125\n\nalpha_prior = 1\nbeta_prior = 1\n\nposterior_A = beta(alpha_prior + conversions_from_A,\n                   beta_prior + visitors_to_A - conversions_from_A)\nposterior_B = beta(alpha_prior + conversions_from_B,\n                   beta_prior + visitors_to_B - conversions_from_B)\n\nsamples = 20000 # We want this to be large to get a better approximation.\n\nsamples_posterior_A = posterior_A.rvs(samples)\nsamples_posterior_B = posterior_B.rvs(samples)\n\nprint((samples_posterior_A > samples_posterior_B).mean())\n\nx = np.linspace(0,1, 500)\nplt.plot(x, posterior_A.pdf(x), label='posterior of A')\nplt.plot(x, posterior_B.pdf(x), label='posterior of B')\nplt.xlabel('Value')\nplt.ylabel('Density')\nplt.title(\"Posterior distributions of the conversion rates of Web pages $A$ and $B$\")\nplt.legend()\nplt.show()\n\nplt.plot(x, posterior_A.pdf(x), label='posterior of A')\nplt.plot(x, posterior_B.pdf(x), label='posterior of B')\nplt.xlim(0.05, 0.15)\nplt.xlabel('Value')\nplt.ylabel('Density')\nplt.title(\"Zoomed-in posterior distributions of the conversion rates of Web pages $A$ and $B$\")\nplt.legend()\n\nplt.show()\n", "meta": {"hexsha": "63ed39b1f5d5e67530e4d02b6947d263ddcd19bd", "size": 1273, "ext": "py", "lang": "Python", "max_stars_repo_path": "1.3.BayesianInference/exercises/srcs/9/AB_2.py", "max_stars_repo_name": "mihaighidoveanu/machine-learning-examples", "max_stars_repo_head_hexsha": "e5a7ab71e52ae2809115eb7d7c943b46ebf394f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1.3.BayesianInference/exercises/srcs/9/AB_2.py", "max_issues_repo_name": "mihaighidoveanu/machine-learning-examples", "max_issues_repo_head_hexsha": "e5a7ab71e52ae2809115eb7d7c943b46ebf394f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1.3.BayesianInference/exercises/srcs/9/AB_2.py", "max_forks_repo_name": "mihaighidoveanu/machine-learning-examples", "max_forks_repo_head_hexsha": "e5a7ab71e52ae2809115eb7d7c943b46ebf394f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-02T13:12:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-02T13:12:21.000Z", "avg_line_length": 29.6046511628, "max_line_length": 95, "alphanum_fraction": 0.7391987431, "include": true, "reason": "import numpy,from scipy", "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9825575147530351, "lm_q2_score": 0.8976952934758465, "lm_q1q2_score": 0.8820372565631243}}
{"text": "import numpy as np\nimport xlsxwriter as xl\nimport time\n\n# Função utilizada: f(x) = 3 * cos(x) - e^x/3 // Intervalo: [-5; 2]// h: 0.75 // Precisão: 10^-5\n# f'(x) = -3sen(x) - 1/3 * e^x\n\n\ntempo_inicial = time.time()\n\n# Utilizando o método de Newton para o intervalo [1; 1.75]:\n\n# Xo é um chute inicial de qualquer valor entre o intervalo I.\n\n\ndef test(x):\n    resultado = 3 * np.cos(x) - (np.exp(x)/3)\n    return resultado\n\n\ndef derivada(x):\n    resultado = - 3 * np.sin(x) - (1/3) * (np.exp(x)/3)\n    return resultado\n\ndef newton():\n    c = 0\n    x_barra = [1.375]  # O Xo é um chute inicial de qualquer valor no I. Nesse caso, o valor do meio\n    x_aplicado = []\n    while True:\n        x_aplicado_atual = test(x_barra[-1])\n        if x_aplicado_atual < 0:\n            modulo_x_aplicado_atual = x_aplicado_atual * (-1)\n        else:\n            modulo_x_aplicado_atual = x_aplicado_atual\n        if modulo_x_aplicado_atual < 10 ** -5:\n            x_aplicado.append(x_aplicado_atual)\n            break\n        else:\n            derivada_x_barra = derivada(x_barra[-1])\n            x_aplicado.append(x_aplicado_atual)\n            x_barra_atual = x_barra[-1] - (x_aplicado[-1] / derivada_x_barra)\n            x_barra.append(x_barra_atual)\n            c += 1\n    return x_barra[-1], x_barra, x_aplicado, c\n\n\nraiz_aproximada = newton()[0]\nlista_x_barra = newton()[1]\nlista_x_aplicado = newton()[2]\niteracoes = newton()[3]\n\nprint('Questao teste, intervalo [1; 1.75]:')\nprint(f'A raiz aproximada é: {raiz_aproximada}')\nprint(f'Para encontrar essa raiz, foram necessárias {iteracoes} iterações.')\nprint(lista_x_barra)\nprint(lista_x_aplicado)\n\n\"\"\"# Criando a tabela com os valores obtidos\n# Criando o arquivo\noutWorkbook = xl.Workbook(\"Questao_03_3o_intervalo_newton.xlsx\")\noutSheet = outWorkbook.add_worksheet()\n\n# Declarando os títulos\n\n# Escrevendo os dados no arquivo\noutSheet.write(\"A1\", \"x_barra\")\noutSheet.write(\"B1\", \"f(x_barra)\")\n\nfor number, item in enumerate(lista_x_barra):\n    outSheet.write(number + 1, 0, item)\nfor number, item in enumerate(lista_x_aplicado):\n    outSheet.write(number + 1, 1, item)\noutWorkbook.close()\"\"\"\n\ntempo_final = time.time()\ntempo_gasto = tempo_final - tempo_inicial\nprint(f'Foram gastos {tempo_gasto}s.')\n\n", "meta": {"hexsha": "1657974f2cad5bd66204d68f3b7c2c84de423537", "size": 2238, "ext": "py", "lang": "Python", "max_stars_repo_path": "Questao_03/Questao_03_newton/Questao_03_3o_intervalo_newton.py", "max_stars_repo_name": "VictorBenoiston/Primeiro_trabalho_calculo_numerico", "max_stars_repo_head_hexsha": "80213b362f9b527339eaf3d0b0a3f7ae77c26eee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Questao_03/Questao_03_newton/Questao_03_3o_intervalo_newton.py", "max_issues_repo_name": "VictorBenoiston/Primeiro_trabalho_calculo_numerico", "max_issues_repo_head_hexsha": "80213b362f9b527339eaf3d0b0a3f7ae77c26eee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Questao_03/Questao_03_newton/Questao_03_3o_intervalo_newton.py", "max_forks_repo_name": "VictorBenoiston/Primeiro_trabalho_calculo_numerico", "max_forks_repo_head_hexsha": "80213b362f9b527339eaf3d0b0a3f7ae77c26eee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3291139241, "max_line_length": 100, "alphanum_fraction": 0.663538874, "include": true, "reason": "import numpy", "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828602, "lm_q2_score": 0.9207896807817186, "lm_q1q2_score": 0.8820357341231201}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits import mplot3d\n\n\ndef circle_2D():\n\t# CIRCLE APPROXIMATION FUNCTION\n\n\tplt.figure(1,figsize=(13,12))\n\tfor count in range(1,8):\n\t\thit=0\n\t\tN=10**count\n\t\tplt.subplot(3,3,count)\n\t\trandomx = np.random.uniform(-1,1,size=N)\n\t\trandomy = np.random.uniform(-1,1,size=N)\n\t\tplt.axis([-1,1,-1,1])\n\t\tpowersum = np.power(randomx,2)+np.power(randomy,2) #condition for any point to be inside the circle\n\t\thit=np.count_nonzero(powersum<=1) #Number of points inside the circle\n\t\tpi = 4.0*hit/N #Estimating pi by equating area probabilty with empirical probabilty\n\t\tprint('for n = %i, approx pi = %f' %(N,pi))\n\n\t\t#Points inside the circle\n\t\tcirclex = randomx[np.nonzero(powersum<=1)]\n\t\tcircley = randomy[np.nonzero(powersum<=1)]\n\n\t\t#Points outside the circle\n\t\toutx = randomx[np.nonzero(powersum>1)]\n\t\touty = randomy[np.nonzero(powersum>1)]\n\n\t\tplt.plot(circlex,circley,'bo')\n\t\tplt.plot(outx,outy,'ro')\t\n\t\t\n\t\tplt.title(r'N: $10^%i$ pi : %f' %(count,pi))\n\t\t\n\t#plt.show()\n\n\ndef sphere_3D():\n\t#SPHERE APPROXIMATION FUNCTION\n\n\t\n\tfor count in range(1,8):\n\t\tplt.figure(count+1)\n\t\thit=0\n\t\tN=10**count\n\t\tax=plt.axes(projection='3d')\n\t\trandomx = np.random.uniform(-1,1,size=N)\n\t\trandomy = np.random.uniform(-1,1,size=N)\n\t\trandomz = np.random.uniform(-1,1,size=N)\n\t\t\n\t\tpowersum = np.power(randomx,2)+np.power(randomy,2)+np.power(randomz,2) #condition for any point to be inside the sphere\n\t\thit=np.count_nonzero(powersum<=1) #Number of points inside the sphere\n\t\tpi = 6.0*hit/N #Estimating pi by equating volume probabilty with empirical probabilty\n\t\tprint('for n = %i, approx pi = %f' %(N,pi))\n\n\t\t#Points inside the sphere\n\t\tspherex = randomx[np.nonzero(powersum<=1)]\n\t\tspherey = randomy[np.nonzero(powersum<=1)]\n\t\tspherez = randomz[np.nonzero(powersum<=1)]\n\t\t\n\t\t#Points outside the sphere\n\t\toutx = randomx[np.nonzero(powersum>1)]\n\t\touty = randomy[np.nonzero(powersum>1)]\n\t\toutz = randomz[np.nonzero(powersum>1)]\n\t\tax.scatter3D(spherex,spherey,spherez,c='b',marker='o')\n\t\tax.scatter3D(outx,outy,outz,c='r',marker='o')\n\t\t\n\t\tplt.title(r'N: $10^%i$ pi : %f' %(count,pi))\n\t\t\n\t\t\n\tplt.show()\n\n\nif __name__=='__main__':\n\t# MAIN FUNCTION\n\n\tprint('\\n')\n\tprint('Printing pi values for Part A: Circle (2D)')\n\tcircle_2D()\n\n\tprint('\\n')\n\tprint('Printing pi values for Part B: Sphere (3D)')\n\tsphere_3D()\n\n\n", "meta": {"hexsha": "00180da6f5b5e7da19f57bef180652fe6adaf04d", "size": 2329, "ext": "py", "lang": "Python", "max_stars_repo_path": "MonteCarlo/montecarlo.py", "max_stars_repo_name": "Robo-Sapien/Monte-Carlo_Bayesian-Learning", "max_stars_repo_head_hexsha": "02009c5bf08c857bdcc0b30ea1f3468c963b1213", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MonteCarlo/montecarlo.py", "max_issues_repo_name": "Robo-Sapien/Monte-Carlo_Bayesian-Learning", "max_issues_repo_head_hexsha": "02009c5bf08c857bdcc0b30ea1f3468c963b1213", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MonteCarlo/montecarlo.py", "max_forks_repo_name": "Robo-Sapien/Monte-Carlo_Bayesian-Learning", "max_forks_repo_head_hexsha": "02009c5bf08c857bdcc0b30ea1f3468c963b1213", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0813953488, "max_line_length": 121, "alphanum_fraction": 0.6852726492, "include": true, "reason": "import numpy", "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122672782973, "lm_q2_score": 0.9207896818685504, "lm_q1q2_score": 0.8820357318451651}}
{"text": "import numpy as np\n\ndef euclidian_distance(a, b):\n    \"\"\"\n    Compute Euclidian distance between two 1-D arrays.\n\n    Parameters\n    ----------\n    a: array_like\n        Input array.\n    b: array_like\n        Input array.\n\n    Returns\n    -------\n    Euclidian distance between two vectors.\n    \"\"\"\n    distance = 0.0\n\n    for i in range(len(a)):\n        distance += (a[i] - b[i])**2\n\n    return np.sqrt(distance)\n", "meta": {"hexsha": "9c21096023783afe862cbef099c2b5320152a7c4", "size": 414, "ext": "py", "lang": "Python", "max_stars_repo_path": "zero2ml/utils/distance_metrics.py", "max_stars_repo_name": "bekzatalish/zero2ml", "max_stars_repo_head_hexsha": "c2baa747e3a02893c58590de52f049184fb4b167", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "zero2ml/utils/distance_metrics.py", "max_issues_repo_name": "bekzatalish/zero2ml", "max_issues_repo_head_hexsha": "c2baa747e3a02893c58590de52f049184fb4b167", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "zero2ml/utils/distance_metrics.py", "max_forks_repo_name": "bekzatalish/zero2ml", "max_forks_repo_head_hexsha": "c2baa747e3a02893c58590de52f049184fb4b167", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.25, "max_line_length": 54, "alphanum_fraction": 0.5579710145, "include": true, "reason": "import numpy", "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241982893259, "lm_q2_score": 0.909907002984195, "lm_q1q2_score": 0.8819948761854981}}
{"text": "import scipy\nimport scipy.special\nimport scipy.integrate\nfrom numpy import exp,cos,sin\n\n# A basic 1D integral:\nscipy.integrate.quad(exp, 0, 1)\n# (1.7182818284590453, 1.9076760487502457e-14)\nscipy.integrate.quad(sin, -0.5, 0.5)\n# (0.0, 2.707864644566304e-15)\nscipy.integrate.quad(cos, -0.5, 0.5)\n# (0.9588510772084061, 1.0645385431034061e-14)\n\nf = lambda x : exp(-x**2)\nscipy.integrate.quad(f, 0, 1)\n# (0.7468241328124271, 8.291413475940725e-15)\n\nscipy.integrate.quad(lambda x : exp(-x**2), 0, 1)\n# (0.7468241328124271, 8.291413475940725e-15)\n\nscipy.integrate.quad(lambda x : exp(-x**2), 0, inf)\n# (0.8862269254527579, 7.101318390472462e-09)\n\nscipy.integrate.quad(lambda x : exp(-x**2), -inf, 1)\n# (1.6330510582651852, 3.669607414547701e-11)\n\nscipy.integrate.quad(lambda x: scipy.special.jn(1,x),0,5)\n# (1.177596771314338, 1.8083362065765924e-14)\n\n#### Integrating Polynomials\n\np = np.poly1d([2, 5, 1])\np(1), p(2), p(3.5)\n\nP = polyint(p)\nq=P(5)-P(1)\n\n\n#### Basic computations in linear algebra\nimport scipy.linalg\n\na = array([[-2, 3], [4, 5]])\nscipy.linalg.det(a)\n\nb = scipy.linalg.inv(a)\ndot(a,b)\n\n#### Solving systems of linear equations¶\nimport scipy.linalg\n\nA = array([[2, 4, 6], [1, -3, -9], [8, 5, -7]])\nb = array([4, -11, 2])\n\nsol1 = scipy.linalg.solve(A,b)\n\nAinv = scipy.linalg.inv(A)\nsol2 = dot(Ainv, b)\nsol1==sol2\n", "meta": {"hexsha": "a228a82243a7ce31f3dc6f66c0399c693bc6355b", "size": 1323, "ext": "py", "lang": "Python", "max_stars_repo_path": "MyTools/ODE/scipy_linalg_tutorial_diego.py", "max_stars_repo_name": "fovtran/PyGame_samples", "max_stars_repo_head_hexsha": "5364181136a0b56eb6e57db5998f49913b596b61", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MyTools/ODE/scipy_linalg_tutorial_diego.py", "max_issues_repo_name": "fovtran/PyGame_samples", "max_issues_repo_head_hexsha": "5364181136a0b56eb6e57db5998f49913b596b61", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MyTools/ODE/scipy_linalg_tutorial_diego.py", "max_forks_repo_name": "fovtran/PyGame_samples", "max_forks_repo_head_hexsha": "5364181136a0b56eb6e57db5998f49913b596b61", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-09T23:31:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-09T23:31:28.000Z", "avg_line_length": 22.4237288136, "max_line_length": 57, "alphanum_fraction": 0.678760393, "include": true, "reason": "from numpy,import scipy", "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877692486436, "lm_q2_score": 0.9086179055936797, "lm_q1q2_score": 0.8819842878801036}}
{"text": "import numpy as np\n\n\ndef gaussianKernel(x1, x2, sigma):\n    \"\"\"returns a gaussian kernel between x1 and x2\n    and returns the value in sim\n    \"\"\"\n\n# Ensure that x1 and x2 are column vectors\n#     x1 = x1.ravel()\n#     x2 = x2.ravel()\n\n# You need to return the following variables correctly.\n    sim = 0\n\n# ====================== YOUR CODE HERE ======================\n# Instructions: Fill in this function to return the similarity between x1\n#               and x2 computed using a Gaussian kernel with bandwidth\n#               sigma\n#\n#\n    sim = np.exp(-np.sum(np.power((x1 - x2), 2)) / float(2 * (sigma**2)))    \n    return sim\n# =============================================================", "meta": {"hexsha": "8618538ab4fc5e0ab726a6fcd3bdb825f5fb4b8b", "size": 696, "ext": "py", "lang": "Python", "max_stars_repo_path": "ex6/gaussianKernel.py", "max_stars_repo_name": "SkyAndCloud/Coursera-AndrewNG-ML-Python", "max_stars_repo_head_hexsha": "586edffdcc3e0811ac186a00b78897b0a75a07d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-10-22T13:18:03.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-26T11:46:20.000Z", "max_issues_repo_path": "ex6/gaussianKernel.py", "max_issues_repo_name": "SkyAndCloud/Coursera-AndrewNG-ML-Python", "max_issues_repo_head_hexsha": "586edffdcc3e0811ac186a00b78897b0a75a07d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex6/gaussianKernel.py", "max_forks_repo_name": "SkyAndCloud/Coursera-AndrewNG-ML-Python", "max_forks_repo_head_hexsha": "586edffdcc3e0811ac186a00b78897b0a75a07d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-16T01:50:45.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-16T01:50:45.000Z", "avg_line_length": 29.0, "max_line_length": 77, "alphanum_fraction": 0.5301724138, "include": true, "reason": "import numpy", "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877700966098, "lm_q2_score": 0.9086179000259899, "lm_q1q2_score": 0.8819842832460925}}
{"text": "\"\"\"\nUnsupervised learning\n=====================\nA category of learning algorithms is able to discover inherent groups that may exist in a set of data.\n\nK-means algorithm\n-----------------\nThe k-means algorithm uses the mean points in a given dataset to cluster and discover groups within the dataset.\nK is the number of clusters that we want and are hoping to discover. After the k-means algorithm has generated the\ngroupings, we can pass it additional but unknown data for it to predict to which group it will belong.\n\nNote that in this kind of algorithm, only the raw uncategorized data is fed to the algorithm.\nIt is up to the algorithm to find out if the data has inherent groups within it.\n\nE.g. 100 data points consisting of x and y values. We will feed these values to the learning algorithm and expect that\nthe algorithm will cluster the data into two sets. We will color the two sets so that the clusters are visible.\n\nEach data point in original_set will belong to a cluster after our k-means algorithm has finished its training.\nThe k-mean algorithm represents the two clusters it discovers as 1s and 0s. If we had asked the algorithm to cluster\nthe data into four, the internal representation of these clusters would have been 0, 1, 2, and 3.\n\n\nThe algorithm discovers two distinct clusters in our sample data.\nThe two mean points of the two clusters are denoted with the red star symbol.\n\nPrediction\n---------\nWith the two clusters that we have obtained, we can predict the group that a new set of data might belong to.\n\nAt the barest minimum, we can expect the two test datasets to belong to different clusters. Prove: right when the print\nstatement prints 1 and 0, thus confirming that our test data does indeed fall under two different clusters.\n\"\"\"\n\n# K-means algorithm\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\n\n# Let's create a sample data of 100 records of x and y pairs\noriginal_set = -2 * np.random.rand(100, 2)\nsecond_set = 1 + 2 * np.random.rand(50, 2)\n# The last 50 numbers in original_set will be replaced\noriginal_set[50:100, :] = second_set\n# =>  we created two subsets of data, one set has numbers in the negative while the other in the positive.\n# print(original_set)\n# print(second_set)\n\n# makes the algorithm cluster all its data under only two groups.\nk_mean = KMeans(n_clusters=2)\nk_mean.fit(original_set)\n\n# The clusters generated by the algorithm will revolve around a certain mean point.\n# => get the points that define these two mean points:\nprint(k_mean.cluster_centers_)\n# to print out the various clusters that each dataset belongs:\nprint(k_mean.labels_)\n\n# There are 100 1s and 0s. Each shows the cluster that each data point falls under.\n# To chart the points of each group and color it appropriately to show the clusters:\nfor i in set(k_mean.labels_):\n    # select all points that correspond to the group i\n    # When i=0, all points belonging to the group 0 are returned to index\n    index = k_mean.labels_ == i\n    # plots these data points using o as the character for drawing each point.\n    plt.plot(original_set[index, 0], original_set[index, 1], 'o')\n\n# plot the centroids or mean values around which the clusters have formed:\nplt.plot(k_mean.cluster_centers_[0][0], k_mean.cluster_centers_[0][1], '*', c='r', ms=10)\nplt.plot(k_mean.cluster_centers_[1][0], k_mean.cluster_centers_[1][1], '*', c='r', ms=10)\n\n\n# show the whole graph with the two means illustrated by a star:\nplt.show()\n\n\n# Prediction\n# With the two clusters that we have obtained, we can predict the group that a new set of data might belong to.\nsample = np.array([[-1.4, -1.4]])\nprint(k_mean.predict(sample))\n\nanother_sample = np.array(([[2.5, 2.5]]))\nprint(k_mean.predict(another_sample))\n\n", "meta": {"hexsha": "01375d53a2fba2f1421dcce845190dafd7dd775a", "size": 3755, "ext": "py", "lang": "Python", "max_stars_repo_path": "my_work/ch11_implems_apps_tools/ml_unsupervised_learning.py", "max_stars_repo_name": "gabrielavirna/PythonDataStructuresAndAlgorithms", "max_stars_repo_head_hexsha": "d406dc247a8ff2f39ee5aac2a398027298ffbf69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-22T04:59:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-22T04:59:02.000Z", "max_issues_repo_path": "my_work/ch11_implems_apps_tools/ml_unsupervised_learning.py", "max_issues_repo_name": "gabrielavirna/python_data_structures_and_algorithms", "max_issues_repo_head_hexsha": "d406dc247a8ff2f39ee5aac2a398027298ffbf69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "my_work/ch11_implems_apps_tools/ml_unsupervised_learning.py", "max_forks_repo_name": "gabrielavirna/python_data_structures_and_algorithms", "max_forks_repo_head_hexsha": "d406dc247a8ff2f39ee5aac2a398027298ffbf69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6627906977, "max_line_length": 119, "alphanum_fraction": 0.7547270306, "include": true, "reason": "import numpy", "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877692486438, "lm_q2_score": 0.9086178969328287, "lm_q1q2_score": 0.8819842794731215}}
{"text": "import numpy as np\r\n\r\ndef l21shrink(epsilon, x):\r\n    output = x.copy()\r\n    norm = np.linalg.norm(x, ord=2, axis=0)\r\n    for i in range(x.shape[1]):\r\n        if norm[i] > epsilon:\r\n            for j in range(x.shape[0]):\r\n                output[j,i] = x[j,i] - epsilon * x[j,i] / norm[i]\r\n        elif norm[i] < -epsilon:\r\n            for j in range(x.shape[0]):\r\n                output[j,i] = x[j,i] + epsilon * x[j,i] / norm[i]\r\n        else:\r\n            output[:,i] = 0.\r\n    return output", "meta": {"hexsha": "c3f587b0728f7b4166b6cdfb3cffa4af894dcb99", "size": 494, "ext": "py", "lang": "Python", "max_stars_repo_path": "resources/l21shrink.py", "max_stars_repo_name": "sebalp1987/anomaly_detection_answers", "max_stars_repo_head_hexsha": "fee2eb08302c1e340acd910d1777016625c25def", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "resources/l21shrink.py", "max_issues_repo_name": "sebalp1987/anomaly_detection_answers", "max_issues_repo_head_hexsha": "fee2eb08302c1e340acd910d1777016625c25def", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "resources/l21shrink.py", "max_forks_repo_name": "sebalp1987/anomaly_detection_answers", "max_forks_repo_head_hexsha": "fee2eb08302c1e340acd910d1777016625c25def", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9333333333, "max_line_length": 66, "alphanum_fraction": 0.4696356275, "include": true, "reason": "import numpy", "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. Yes\n2. Yes", "lm_q1_score": 0.956634196290671, "lm_q2_score": 0.921921838609201, "lm_q1q2_score": 0.8819419571207306}}
{"text": "# %%\n\nfrom typing import Sequence\nfrom numba import njit\n# %%\n\n\ndef fib(n: int):\n    if(n <= 2):\n        return 1\n    return fib(n-1) + fib(n-2)\n\n\n# print(fib(3))\n# print(fib(5))\n# print(fib(8))\n\ndef fib_memo(n: int, memo={1: 1, 2: 1}):\n    if n >= 1:\n        if (n in memo):\n            return memo[n]\n        memo[n] = fib_memo(n-1, memo) + fib_memo(n-2, memo)\n        return memo[n]\n\n    else:\n        print(\"Provide Positive int\")\n\n# %%\n\n# print(fib_memo(100))\n\n\n# @njit(fastmath=True, cache=True)\ndef grid_traveller(x: int, y: int, memo={}) -> int:\n    if (x, y) in memo.keys():\n        return memo[(x, y)]\n    if x*y == 0:\n        return 0\n    if x*y == 1:\n        return 1\n\n    res = grid_traveller(x-1, y, memo) + grid_traveller(x, y-1, memo)\n    memo[(x, y)] = res\n    return res\n\n\nprint(grid_traveller(1, 1))\nprint(grid_traveller(3, 3))\nprint(grid_traveller(10, 10))\n\n# %%\n\n\ndef can_sum(target: int, arr: Sequence[int]) -> bool:\n    pass\n# %%\n\n\ndef how_sum(target: int, arr: Sequence[int]) -> Sequence[int]:\n    pass\n# %%\n\n\ndef can_sum(target: int, arr: Sequence[int]):\n    pass\n", "meta": {"hexsha": "3214c236cfd76b69da9dac32ba29aab399bc631d", "size": 1089, "ext": "py", "lang": "Python", "max_stars_repo_path": "Prep/ProgrammingPrac/temp.py", "max_stars_repo_name": "talk2sunil83/UpgradLearning", "max_stars_repo_head_hexsha": "70c4f993c68ce5030e9df0edd15004bbb9fc71e7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Prep/ProgrammingPrac/temp.py", "max_issues_repo_name": "talk2sunil83/UpgradLearning", "max_issues_repo_head_hexsha": "70c4f993c68ce5030e9df0edd15004bbb9fc71e7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Prep/ProgrammingPrac/temp.py", "max_forks_repo_name": "talk2sunil83/UpgradLearning", "max_forks_repo_head_hexsha": "70c4f993c68ce5030e9df0edd15004bbb9fc71e7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.5, "max_line_length": 69, "alphanum_fraction": 0.5528007346, "include": true, "reason": "from numba", "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.9219218294919745, "lm_q1q2_score": 0.8819419495387033}}
{"text": "import numpy\nfrom matplotlib import pyplot\n\ndef euler(f, x_end, y0, N):\n    x, dx = numpy.linspace(0, x_end, N+1, retstep=True)\n    y = numpy.zeros((len(y0),N+1))\n    y[:,0] = y0\n    for n in range(N):\n        y[:,n+1] = y[:,n] + dx * f(x[n], y[:,n])\n    return x, dx, y\n\ndef euler_pc(f, x_end, y0, N):\n    x, dx = numpy.linspace(0, x_end, N+1, retstep=True)\n    y = numpy.zeros((len(y0),N+1))\n    y[:,0] = y0\n    for n in range(N):\n        fn = f(x[n], y[:,n])\n        yp = y[:,n] + dx * fn\n        y[:,n+1] = y[:,n] + dx / 2 * (fn + f(x[n+1], yp))\n    return x, dx, y\n\ndef rk4(f, x_end, y0, N):\n    x, dx = numpy.linspace(0, x_end, N+1, retstep=True)\n    y = numpy.zeros((len(y0),N+1))\n    y[:,0] = y0\n    for n in range(N):\n        k1 = dx * f(x[n]         , y[:,n]         )\n        k2 = dx * f(x[n] + dx / 2, y[:,n] + k1 / 2)\n        k3 = dx * f(x[n] + dx / 2, y[:,n] + k2 / 2)\n        k4 = dx * f(x[n] + dx    , y[:,n] + k3    )\n        y[:,n+1] = y[:,n] + (k1 + 2 * (k2 + k3) + k4) / 6\n    return x, dx, y\n\nif __name__==\"__main__\":\n\n    def f_sin(x, y):\n        return -numpy.sin(x)\n    print(\"Euler Predictor-Corrector\")\n    x, dx, y = euler_pc(f_sin, 0.5, [1], 5)\n    print(\"dx=\", dx, \"y(0.5)=\", y[0,-1])\n    x, dx, y = euler_pc(f_sin, 0.5, [1], 50)\n    print(\"dx=\", dx, \"y(0.5)=\", y[0,-1])\n    Npoints = 5*2**numpy.arange(1,10)\n    dx_all = 0.5/Npoints\n    errors = numpy.zeros_like(dx_all)\n    for i, N in enumerate(Npoints):\n        x, dx, y = euler_pc(f_sin, 0.5, [1], N)\n        errors[i] = abs(y[0,-1] - numpy.cos(0.5))\n        dx_all[i] = dx\n    pyplot.figure(figsize=(12,6))\n    pyplot.loglog(dx_all, errors, 'kx')\n    pyplot.loglog(dx_all, errors[0]*(dx_all/dx_all[0])**2, 'b-',\n                  label=r\"$\\propto \\Delta x^2$\")\n    pyplot.legend(loc='upper left')\n    pyplot.xlabel(r\"$\\Delta x$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.show()\n    \n    def f_circle(x, y):\n        dydx = numpy.zeros_like(y)\n        dydx[0] = -y[1]\n        dydx[1] = y[0]\n        return dydx\n    y0 = numpy.array([1, 0])\n    x, dx, y = euler_pc(f_circle, 50, y0, 500)\n    pyplot.figure(figsize=(8,8))\n    pyplot.plot(y[0,:], y[1,:])\n    pyplot.show()\n    \n    print(\"RK4\")\n    x, dx, y = rk4(f_sin, 0.5, [1], 5)\n    print(\"dx=\", dx, \"y(0.5)=\", y[0,-1])\n    x, dx, y = rk4(f_sin, 0.5, [1], 50)\n    print(\"dx=\", dx, \"y(0.5)=\", y[0,-1])\n    Npoints = 5*2**numpy.arange(1,10)\n    dx_all = 0.5/Npoints\n    errors = numpy.zeros_like(dx_all)\n    for i, N in enumerate(Npoints):\n        x, dx, y = rk4(f_sin, 0.5, [1], N)\n        errors[i] = abs(y[0,-1] - numpy.cos(0.5))\n        dx_all[i] = dx\n    pyplot.figure(figsize=(12,6))\n    pyplot.loglog(dx_all, errors, 'kx')\n    pyplot.loglog(dx_all, errors[0]*(dx_all/dx_all[0])**4, 'b-',\n                  label=r\"$\\propto \\Delta x^4$\")\n    pyplot.legend(loc='upper left')\n    pyplot.xlabel(r\"$\\Delta x$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.show()\n    \n    y0 = numpy.array([1, 0])\n    x, dx, y = rk4(f_circle, 50, y0, 500)\n    pyplot.figure(figsize=(8,8))\n    pyplot.plot(y[0,:], y[1,:])\n    pyplot.show()", "meta": {"hexsha": "e9937b9df8fff616e5f6243cc2ea412f0f3c998d", "size": 3046, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/tex/codes/lecture15.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Lectures/tex/codes/lecture15.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Lectures/tex/codes/lecture15.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 32.0631578947, "max_line_length": 64, "alphanum_fraction": 0.49441891, "include": true, "reason": "import numpy", "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211612253742, "lm_q2_score": 0.9046505267461572, "lm_q1q2_score": 0.8818724769858354}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov 24 17:10:18 2021\r\n\r\n@author: pvghd\r\n\"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom datetime import date\r\nimport pandas_datareader as pdr\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n# How does the portfolio.cov() function work?\r\n\r\nportfolio = pd.DataFrame( [(1,3), (2,5), (3,7), (4,2), (5,4), (6,1)], \r\n                         columns=['a', 'b'] )\r\n\r\ncovariance = portfolio.cov()\r\nprint( covariance )\r\n\r\n# Now let us recreate the function:\r\n\r\na = [1,2,3,4,5,6]\r\nb = [3,5,7,2,4,1]\r\n\r\n\"\"\"\r\nTo calculate the pairwise covariance. You take the mean value of the array\r\nand subtract it from each of the components. Then you multiply both arrays\r\ncomponent by component and sum them. You divide everything by the number\r\nof components of the arrays (which must have the same dimension) minus one.\r\nThe minus one comes from the Bessel correction.\r\nJust like in http://nambis.bplaced.net/nambis/SMDV/SMDV_Kapitel7.pdf p.7\r\n(with corrections)\r\n\"\"\"\r\n\r\ndef covariance_func(a,b):\r\n    a_2 = a - np.mean(a)\r\n    b_2 = b - np.mean(b)\r\n    return np.sum( a_2 * b_2 ) /  (len(a)-1)\r\n\r\nprint()\r\nprint('variance a =', covariance_func(a, a) )\r\nprint('covariance ab =', covariance_func(a, b) )\r\nprint('covariance ab =', covariance_func(b, a) )\r\nprint('variance b =', covariance_func(b, b) )\r\n\r\na_2 = a - np.mean(a)\r\nb_2 = b - np.mean(b)\r\n", "meta": {"hexsha": "2b3b1abff6f1306f970055dd880c613da1221b55", "size": 1364, "ext": "py", "lang": "Python", "max_stars_repo_path": "recreate_covariance_function.py", "max_stars_repo_name": "pvhprjct/OptPo", "max_stars_repo_head_hexsha": "0f153297e5b048c2b757997a4104102207f0973d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "recreate_covariance_function.py", "max_issues_repo_name": "pvhprjct/OptPo", "max_issues_repo_head_hexsha": "0f153297e5b048c2b757997a4104102207f0973d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "recreate_covariance_function.py", "max_forks_repo_name": "pvhprjct/OptPo", "max_forks_repo_head_hexsha": "0f153297e5b048c2b757997a4104102207f0973d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.28, "max_line_length": 76, "alphanum_fraction": 0.6480938416, "include": true, "reason": "import numpy", "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715435, "lm_q2_score": 0.9230391632454271, "lm_q1q2_score": 0.881796972484273}}
{"text": "import numpy as np\r\nimport matplotlib.pylab as plt\r\n\r\ndef function_1(x):\r\n    return 0.01*x**2 + 0.1*x\r\n\r\nx = np.arange(0.0, 20.0, 0.1) # 0에서 20까지 0.1 간격의 배열 x를 만든다.\r\ny = function_1(x)\r\n\r\n# plt.xlabel(\"x\")\r\n# plt.ylabel(\"f(x)\")\r\n# plt.plot(x,y)\r\n# plt.show()\r\n\r\ndef numerical_diff(f, x):\r\n    h = 1e-4 # 0.0001\r\n    return (f(x+h) - f(x-h)) / (2*h)\r\n\r\n# print(numerical_diff(function_1, 5))\r\n#\r\n# print(numerical_diff(function_1, 10))\r\n\r\n# 편미분\r\ndef function_2(x):\r\n    return x[0]**2 + x[1]**2\r\n\r\ndef function_tmp1(x0):\r\n    return x0*x0 + 4.0**2.0\r\n\r\n# print(numerical_diff(function_tmp1, 3.0))\r\n\r\ndef function_tmp2(x1):\r\n    return 3.0**2.0 + x1*x1\r\n\r\n# print(numerical_diff(function_tmp2, 4.0))\r\n\r\n# 기울기\r\ndef numerical_gradient(f, x):\r\n    h = 1e-4  # 0.0001\r\n    grad = np.zeros_like(x)  # x와 형상이 같은 배열을 생성\r\n\r\n    for idx in range(x.size):\r\n        tmp_val = x[idx]\r\n\r\n        # f(x+h) 계산\r\n        x[idx] = float(tmp_val) + h\r\n        fxh1 = f(x)\r\n\r\n        # f(x-h) 계산\r\n        x[idx] = tmp_val - h\r\n        fxh2 = f(x)\r\n\r\n        grad[idx] = (fxh1 - fxh2) / (2 * h)\r\n        x[idx] = tmp_val  # 값 복원\r\n\r\n    return grad\r\n\r\n# print(_numerical_gradient_no_batch(function_2, np.array([3.0, 4.0])))\r\n# print(_numerical_gradient_no_batch(function_2, np.array([0.0, 2.0])))\r\n\r\n# 경사 하강법\r\ndef gradient_descent(f, init_x, lr=0.01, step_num=100):\r\n    x = init_x\r\n\r\n    for i in range(step_num):\r\n        grad = numerical_gradient(f,x)\r\n        x -= lr *grad\r\n    return x\r\n\r\ninit_x = np.array([-3.0, 4.0])\r\nprint(gradient_descent(function_2, init_x=init_x, lr=0.1, step_num=100))\r\n\r\n# 학습률이 너무 큰 예 : lr=10.0\r\ninit_x = np.array([-3.0, 4.0])\r\nprint(gradient_descent(function_2, init_x=init_x, lr=10.0, step_num=100))\r\n\r\n# 학습률이 너무 작은 예 : lr=1e-10\r\ninit_x = np.array([-3.0, 4.0])\r\nprint(gradient_descent(function_2, init_x=init_x, lr=1e-10, step_num=100))", "meta": {"hexsha": "cb0b388d784c317f4c6eb10463f613cd4534fd08", "size": 1846, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch04/prac.py", "max_stars_repo_name": "jihyunis/-", "max_stars_repo_head_hexsha": "8575e74ced7842bc8ebf1af1b683a4976941cec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch04/prac.py", "max_issues_repo_name": "jihyunis/-", "max_issues_repo_head_hexsha": "8575e74ced7842bc8ebf1af1b683a4976941cec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch04/prac.py", "max_forks_repo_name": "jihyunis/-", "max_forks_repo_head_hexsha": "8575e74ced7842bc8ebf1af1b683a4976941cec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3670886076, "max_line_length": 74, "alphanum_fraction": 0.5834236186, "include": true, "reason": "import numpy", "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191348157373, "lm_q2_score": 0.9230391574234201, "lm_q1q2_score": 0.8817969692707889}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef complexiter(max_iter, x, y):\n    \"\"\"Finds whether or not a point on the complex xy plane remains bounded \n    in the absolute value of z squared after iterating the equation z = z*z +c \n    or runs off to infinity within the maximum number of interations\n    \n    Parameters:\n    max_iter - Integer\n    x - numeric sequence of form np.linspace(start, end, number of breakpoints)\n    y - numeric sequence of form np.linspace(start, end, number of breakpoints)\n    \n    Returns:\n    True if iterations at that point remain bounded, False otherwise\n    \"\"\"\n    \n    c = x[:,np.newaxis] + y[np.newaxis,:]*1j\n    #start from 0\n    z = 0\n    \n    for i in range(max_iter):\n        z = z*z + c\n    c_set = (abs(z) < 2)\n    return(c_set)\n\n#complex plane from -2 to 2\nx = np.linspace(-2, 2, 500)\ny = np.linspace(-2, 2, 500)\n#determining which points in the complex plane remain bounded within 200 iterations\nc_set = complexiter(200, x, y)\n\n#plotting the image\nplt.imshow(c_set.T, extent=[-2, 2, -2, 2])\nplt.title(\"Mandelbrot Set\")\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.gray()\nplt.show()\n\n###now zooming into a portion of the image and trying again\n#complex plane from -1 to 0\nx = np.linspace(-1, 0, 500)\ny = np.linspace(-1, 0, 500)\n#determining which points in the complex plane remain bounded within 200 iterations\nc_set = complexiter(200, x, y)\n\n#plotting the image\nplt.imshow(c_set.T, extent=[-1, 0, -1, 0])\nplt.title(\"Zoomed In Madelbrot Set\")\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.gray()\nplt.show()\n\n", "meta": {"hexsha": "0ad1da99b9801d0c7efd07fb3ce70c3e56521b4e", "size": 1548, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment_2/question1.py", "max_stars_repo_name": "jpas3/CTA200", "max_stars_repo_head_hexsha": "231b22c476638be63da945d24d0de8ddaaaf702f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment_2/question1.py", "max_issues_repo_name": "jpas3/CTA200", "max_issues_repo_head_hexsha": "231b22c476638be63da945d24d0de8ddaaaf702f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment_2/question1.py", "max_forks_repo_name": "jpas3/CTA200", "max_forks_repo_head_hexsha": "231b22c476638be63da945d24d0de8ddaaaf702f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6428571429, "max_line_length": 83, "alphanum_fraction": 0.6776485788, "include": true, "reason": "import numpy", "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104914476338, "lm_q2_score": 0.9124361688107863, "lm_q1q2_score": 0.8817878863150281}}
{"text": "import numpy as np\nimport skimage\nimport utils\nimport pathlib\n\n\ndef otsu_thresholding(im: np.ndarray) -> int:\n    \"\"\"\n        Otsu's thresholding algorithm that segments an image into 1 or 0 (True or False)\n        The function takes in a grayscale image and outputs a boolean image\n\n        args:\n            im: np.ndarray of shape (H, W) in the range [0, 255] (dtype=np.uint8)\n        return:\n            (int) the computed thresholding value\n    \"\"\"\n    assert im.dtype == np.uint8\n    ### START YOUR CODE HERE ### (You can change anything inside this block)\n    # You can also define other helper functions\n\n    # Number of intensity levels\n    L = 256\n\n    # Compute normalized histogram\n    p, _ = np.histogram(im, bins=L, density=True)\n\n    # Compute the cumulative sums P_1(k) for k = 0, 1, 2,.., L-1, the cumulative means m_k for k = 0, 1, 2,.., L-1 and the global mean m_g\n    P_1 = np.zeros(L)\n    m = np.zeros(L)\n    m_g = 0\n\n    for k in range(L):\n        # Computes the global mean\n        m_g += (k * p[k])\n\n        for i in range(k + 1):\n            # Computes the cumulative sums\n            P_1[k] += p[i]\n\n            # Computes the cumulative means\n            m[k] += (i * p[i])\n\n    var = np.zeros(L)\n    threshold = 128\n    max_var = 0\n\n    # Compute the between-class variance o^2 = (m_g * P_1 - m_k)^2/(P_1 * (1 - P_1)) for k = 0, 1, 2,.., L-1 and find the k value for the max variance\n    for k in range(L):\n        var[k] = ((m_g * P_1[k] - m[k])**2)/(P_1[k]*(1-P_1[k]))\n        if (var[k] > max_var):\n            max_var = var[k]\n            threshold = k\n\n    return threshold\n    ### END YOUR CODE HERE ###\n\n\nif __name__ == \"__main__\":\n    # DO NOT CHANGE\n    impaths_to_segment = [\n        pathlib.Path(\"thumbprint.png\"),\n        pathlib.Path(\"polymercell.png\")\n    ]\n    for impath in impaths_to_segment:\n        im = utils.read_image(impath)\n        threshold = otsu_thresholding(im)\n        print(\"Found optimal threshold:\", threshold)\n\n        # Segment the image by threshold\n        segmented_image = (im >= threshold)\n        assert im.shape == segmented_image.shape, \\\n            \"Expected image shape ({}) to be same as thresholded image shape ({})\".format(\n                im.shape, segmented_image.shape)\n        assert segmented_image.dtype == np.bool, \\\n            \"Expected thresholded image dtype to be np.bool. Was: {}\".format(\n                segmented_image.dtype)\n\n        segmented_image = utils.to_uint8(segmented_image)\n\n        save_path = \"{}-segmented.png\".format(impath.stem)\n        utils.save_im(save_path, segmented_image)\n", "meta": {"hexsha": "83ac89e4fde3496aab74ca9c29e7674556b4bded", "size": 2586, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment3/task2a.py", "max_stars_repo_name": "anastalind/TDT4195-StarterCode", "max_stars_repo_head_hexsha": "b2c351e4bce53961af02ffad81bd472b23cb4137", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment3/task2a.py", "max_issues_repo_name": "anastalind/TDT4195-StarterCode", "max_issues_repo_head_hexsha": "b2c351e4bce53961af02ffad81bd472b23cb4137", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment3/task2a.py", "max_forks_repo_name": "anastalind/TDT4195-StarterCode", "max_forks_repo_head_hexsha": "b2c351e4bce53961af02ffad81bd472b23cb4137", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5365853659, "max_line_length": 150, "alphanum_fraction": 0.5893271462, "include": true, "reason": "import numpy", "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543366, "lm_q2_score": 0.9149009549929797, "lm_q1q2_score": 0.8817631893885912}}
{"text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\nfrom sal_timer import timer\n\n\ndef get_data():\n    df = pd.read_csv(DATA_PATH)\n    print(df.head(5))\n\n    return df\n\ndef scatter_training_data(df):\n    plt.plot('exam1', 'exam2', '*', c='r', data=df[df.y == 0])\n    plt.plot('exam1', 'exam2', '+', c='b', data=df[df.y == 1])\n    plt.legend(['Not Admitted', 'Admitted'])\n    plt.xlabel('Exam 1 score')\n    plt.ylabel('Exam 2 score')\n    plt.title('Scatter plot of training data')\n    plt.show()\n\n\ndef sigmoid(X: np.ndarray) -> np.ndarray:\n    '''\n    For large positive values of x, the sigmoid should be close to 1, while for large negative values, the sigmoid should be close to 0. \n    Evaluating sigmoid(0) should give you exactly 0.5.\n\n    this method work with vectors and matrices. For a matrix, method perform the sigmoid function on every element.\n\n    Sigmoid function formula\n    Math :\n        g(z) = (1) / (1 + e^(-z))\n\n    LaTex :\n        g(z) = \\frac{1}{1 + e^{-z}}\n    '''\n    return 1.0 / ( 1.0 + np.exp(-X))\n\ndef hypothesis(X: np.ndarray, theta: np.ndarray) -> np.ndarray:\n    '''\n    calculate the cost for given X and y, the following shows and example of a single dimensional X\n    theta   = Vector of theta;\n    X       = Row of X's np.zeros((m, j));\n\n    where:\n        m number of samples;\n        j is the no. of features;\n\n    Return ...........    \n    \n\n    logistic regression hypothesis formula\n    Math :\n        1. h(x) = g(theta^T * x); g is sigmoid function.\n        2. g(z) = (1) / (1 + e^(-z))\n\n    LaTex :\n        1. h_{\\theta} (x) = g( \\theta^{T} x)\n        2. g(z) = \\frac{1}{1 + e^{-z}}\n    '''\n\n    # https://www.youtube.com/watch?v=okpqeEUdEkY\n    # np.dot(theta.T, X)\n\n    return sigmoid(np.dot(X, theta))\n\ndef cost_function(theta: np.ndarray, X: np.ndarray, y: np.ndarray) -> np.ndarray:\n    '''\n    calculate the cost for given X and y, the following shows and example of a single dimensional X\n    theta   = Vector of theta;\n    X       = Row of X's np.zeros((m, j));\n    y       = Actual of y's np.zeros((m, 1));\n\n    where:\n        m number of samples;\n        j is the no. of features;\n    \n    Return ...........    \n        \n    Cost function formula\n    Math :\n        J = (1 / m) * sum(-y .* log(h) - (1 - y) .* log(1 - h))\n    LaTex:\n        J(\\theta) = \\frac{1}{m} \\sum_{i=1}^{m} [-y^{(i)}log(h_{\\theta}(x^{(i)})) - (1 - y^{(i)})log(1 - h_{\\theta}(x^{(i)}))]\n    '''\n\n    try:\n        m = len(y)\n        h = hypothesis(X, theta)\n        \n        # print('y : ', y.shape)\n        # print('h : ', h.shape)\n        # print('log(h) : ', np.log(h))\n        # print(\n        #     np.multiply(\n        #         -y,\n        #         np.log(h)\n        #         ).shape\n        #     )\n\n        return (1. / m) * np.sum( np.multiply(-y, np.log(h ) - np.multiply(1 - y, np.log(1 - h)) ))\n    except Exception as err:\n        print('cost_function(...)  ==>  {err}.'.format(err=err))\n        return 0.\n\ndef gradient_function(theta: np.ndarray, X: np.ndarray, y: np.ndarray) -> np.ndarray:\n    '''\n    X    = Matrix of X with added bias units;\n    y    = Vector of Y;\n    theta=Vector of thetas np.random.randn(j,1);\n\n    Return ...........    \n\n    Math:\n        grad = (1 / m) * sum((h - y) .* X)\n\n    LaTex:\n        \\frac{\\partial J(\\theta)}{\\partial \\theta_{j}} = \\frac{1}{m} \\sum_{i=1}^{m} (h_{\\theta}(x^{(i)}) - y^{(i)})x_{j}^{(i)}\n    '''\n    try:\n        m = len(y)\n        h = hypothesis(X, theta)\n        return (1. / m) * np.sum(np.multiply(h - y, X), axis=0)\n    except Exception as err:\n        print('gradient_function(...)  ==>  {err}.'.format(err=err))\n        return np.zeros(theta.shape)\n\n\n# TODO ... https://www.youtube.com/watch?v=QOne3o-7_DQ\ndef gradient_descent(theta: np.ndarray, X: np.ndarray, y: np.ndarray, alpha: int, num_iterations: int) -> np.ndarray:\n    '''\n    X    = Matrix of X with added bias units;\n    y    = Vector of Y;\n    theta=Vector of thetas np.random.randn(j,1);\n    learning_rate;\n    iterations = no of iterations;\n    \n    Returns the final theta vector and array of cost history over no of iterations\n    '''\n    m = len(y)\n    h = hypothesis(X, theta)\n    theta = theta - alpha / m * np.dot((h - y), X)\n\n    ####\n    # cost_history = [] # plot\n    # theta = theta + alpha * gradient\n\n\n    ####\n    # https://gist.github.com/sagarmainkar/41d135a04d7d3bc4098f0664fe20cf3c\n\n    # m = len(y)\n    # cost_history = np.zeros(iterations)\n    # theta_history = np.zeros((iterations,2))\n    # for it in range(iterations):\n        \n    #     prediction = np.dot(X,theta)\n        \n    #     theta = theta -(1/m)*learning_rate*( X.T.dot((prediction - y)))\n    #     theta_history[it,:] =theta.T\n    #     cost_history[it]  = cal_cost(theta,X,y)\n        \n    # return theta, cost_history, theta_history\n\n\n\ndef sigmoid_test():\n    x = np.array([\n        99999,\n        100,\n        10,\n        4,\n        2,\n\n        0.01,\n        0.1,\n        0,\n        -0.1,\n        -0.01,\n\n        \n        -2,\n        -4,\n        -10,\n        -100,\n        -99999,\n    ])\n\n    print(pd.DataFrame({\n        'x': x,\n        'sig': sigmoid(x),\n        'real': np.array([1.00,1.00,0.99,0.98,0.88,0.50,0.52,0.50,0.47,0.49,0.11,0.17,0.45,0.37,0.00])\n    }))\n\n    x = 4\n    z = sigmoid(x)\n    print(z)\n\ndef hypothesis_test():\n    X = np.array([34.62365962451697, 78.0246928153624])\n    theta = np.array([1, 1])\n    y = np.array([0])\n    # yy = hypothesis(X, theta)\n    # print(yy)\n\n    # ...\n    X = np.array([7, 2])\n    theta = np.array([3, 4])\n    y = hypothesis(X, theta)\n    print('X : ', X.shape)\n    print('theta : ', theta.shape)\n    print('y : ', y.shape)\n    print(y)\n\n    # ...\n    X = np.array([1, 2])\n    theta = np.array([3, 4]).T\n    y = hypothesis(X, theta)\n    print('X : ', X.shape)\n    print('theta : ', theta.shape)\n    print('y : ', y.shape)\n    print(y)\n\n    # ...\n    X = np.array([1, 2]).T\n    theta = np.array([3, 4])\n    y = hypothesis(X, theta)\n    print('X : ', X.shape)\n    print('theta : ', theta.shape)\n    print('y : ', y.shape)\n    print(y)\n\n    # ...\n    X = np.array([[1, 2], [1, 2], [1, 2]])\n    theta = np.array([3, 4])\n    y = hypothesis(X, theta)\n    print('X : ', X.shape)\n    print('theta : ', theta.shape)\n    print('y : ', y.shape)\n    print(y)\n\n    # ... ERROR\n    # X = np.array([[1, 2], [1, 2], [1, 2]]).T\n    # theta = np.array([3, 4])\n    # y = hypothesis(X, theta)\n    # print('X : ', X.shape)\n    # print('theta : ', theta.shape)\n    print('y : ', y.shape)\n    # print(y)\n\n    # ...\n    X = np.array([[1, 2], [1, 2], [1, 2]])\n    theta = np.array([3, 4]).T\n    y = hypothesis(X, theta)\n    print('X : ', X.shape)\n    print('theta : ', theta.shape)\n    print('y : ', y.shape)\n    print(y)\n\n    # ...\n    X = np.array([[1, 2], [1, 2], [1, 2]]).T\n    theta = np.array([3, 4]).T\n    y = hypothesis(theta, X)  # <<===== replace in space !!!\n    print('X : ', X.shape)\n    print('theta : ', theta.shape)\n    print('y : ', y.shape)\n    print(y)\n\ndef cost_function_test():\n    # ...\n    X = np.array([[1, 2], [1, 2], [1, 2]])\n    m, n = X.shape\n    theta = np.array([[3], [4]])\n    # y = np.array([1., 1., 0.])\n    y = np.array([[1.], [1.], [0.]])\n\n    # ...\n    J = cost_function(theta, X, y)\n    print(J)\n\ndef gradient_function_test():\n    # ...\n    X = np.array([[1, 2], [1, 2], [1, 2]])\n    theta = np.array([[3], [4]])\n    # y = np.array([1., 1., 0.])\n    y = np.array([[1.], [1.], [0.]])\n\n    # ...\n    grad = gradient_function(theta, X, y)\n    print(grad)\n\n\ndef test_1():\n    # ...\n    df = get_data()\n    X, y = df.iloc[:, :-1].values, df.iloc[:, -1].values\n    m, n = X.shape\n    X = np.hstack([np.ones([m, 1]), X])\n    initial_theta = np.zeros([n + 1, 1])\n    y = np.resize(y, (len(y), 1))\n    # y = y.reshape((len(y), 1))\n\n    # ...\n    print('X : ', X.shape)\n    print('Theta : ', initial_theta.shape)\n    print('y : ', y.shape)\n\n    # ...\n    cost = cost_function(initial_theta, X, y)\n    print('\\n'*2)\n    print('Cost at initial theta (zeros): ', cost)\n    print('Expected cost (approx): 0.693')\n\n    grad = gradient_function(initial_theta, X, y)\n    print('Gradient at initial theta:\\t\\t', grad)\n    print('Expected gradients (approx):\\t\\t[-0.1000 -12.0092 -11.2628]')\n\n\n    test_theta = np.array([[-24], [0.2], [0.2]])\n\n    cost = cost_function(test_theta, X, y)\n    print('\\n'*2)\n    print('Cost at test theta: ', cost)\n    print('Expected cost (approx): 0.218')\n\n    grad = gradient_function(test_theta, X, y)\n    print('Gradient at test theta:\\t\\t', grad)\n    print('Expected gradients (approx): \\t\\t[0.043 2.566 2.647]')\n\n\n\n\n\n@timer\ndef main():\n    df = get_data()\n    # scatter_training_data(df)\n\n\n\n    \n    # X, y = df.iloc[:, :-1].values, df.iloc[-1].values\n    # print(X[:3])\n    # print(y[:3])\n\n\n@timer\ndef test():\n    # sigmoid_test()\n    # hypothesis_test()\n    # cost_function_test()\n    # gradient_function_test()\n    test_1()\n\n\n\nDATA_PATH = './data/ex2data1.csv'\n\nif __name__ == '__main__':\n    print('========================================== START ==========================================')\n    #...\n    test()\n    # main()\n    print('========================================== END ============================================')", "meta": {"hexsha": "00a395f6687246f3a2e6f79868bb9be1ef1caa5f", "size": 9185, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignment/python/ex2/main.py", "max_stars_repo_name": "SalAlba/coursera-machine-learning", "max_stars_repo_head_hexsha": "4ca4cde05dd3ab96ee5176861a095513e9e381dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment/python/ex2/main.py", "max_issues_repo_name": "SalAlba/coursera-machine-learning", "max_issues_repo_head_hexsha": "4ca4cde05dd3ab96ee5176861a095513e9e381dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment/python/ex2/main.py", "max_forks_repo_name": "SalAlba/coursera-machine-learning", "max_forks_repo_head_hexsha": "4ca4cde05dd3ab96ee5176861a095513e9e381dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0956284153, "max_line_length": 137, "alphanum_fraction": 0.5017964072, "include": true, "reason": "import numpy", "num_tokens": 2870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799430946808, "lm_q2_score": 0.9149009480320036, "lm_q1q2_score": 0.881763183631554}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\n# Soluciones a los ejercicios de la seccion 6.2.5 \n# del libro A Survey of Computational Physics Introductory Computational Science\n# de Landau, Paez, Bordeianu (Python Multimodal eTextBook Beta4.0)\n\n#1. Write a double-precision program to integrate an arbitrary function numerically \n# using the trapezoid rule, the Simpson rule, and Gaussian quadrature.\ndef integral(f, a, b, n_points=10, metodo=\"trapecio\"):\n    # Genera siempre un numero impar de puntos\n    if n_points%2 == 0:\n        n_points = n_points + 1\n\n    if metodo==\"trapecio\":\n        x = np.linspace(a, b, n_points)\n        h = x[1] - x[0]\n        w = np.ones(n_points) * h\n        w[0] = h/2\n        w[-1] = h/2\n    elif metodo==\"simpson\":\n        x = np.linspace(a, b, n_points)\n        h = x[1] - x[0]\n        w = np.ones(n_points) \n        ii = np.arange(n_points)\n        w[ii%2!=0] = 4.0*h/3.0\n        w[ii%2==0] = 2.0*h/3.0\n        w[0] = h/3\n        w[-1] = h/3\n    elif metodo==\"cuadratura\":\n        y, wprime = np.polynomial.legendre.leggauss(n_points)\n        x = 0.5*(b+a) + 0.5*(b-a)*y\n        w = 0.5*(b-a)*wprime\n    else:\n        print('metodo no implementado')\n        x = np.zeros(n_points)\n        y = np.zeros(n_points)\n\n    return np.sum(f(x)*w)\n\ndef func(x):\n    return np.cos(x)\n\ndef error(x):\n    return np.abs(1-x)\n\n# 2 Compute the relative error (epsilon=abs(numerical-exact)/exact) in each case. \n# Present your data in tabular form for N=2,10,20,40,80,160\n\ndef integra():\n    N = [2,10,20,40,80,160]\n    print(\"Primera Parte\")\n    out = open(\"/tmp/tabla_resultados.dat\", \"w\")\n    print(\"# N\\t e_T\\t e_S \\t e_G\")\n    for n_points in N:\n        a = integral(func, 0, np.pi/2, n_points=n_points, metodo=\"trapecio\")\n        b = integral(func, 0, np.pi/2, n_points=n_points, metodo=\"simpson\")\n        c = integral(func, 0, np.pi/2, n_points=n_points, metodo=\"cuadratura\")\n        print(\"{:d}\\t {:.1e} {:.1e} {:.1e}\".format(n_points, error(a), error(b), error(c)))\n        out.write(\"{:d}\\t {:.1e} {:.1e} {:.1e}\\n\".format(n_points, error(a), error(b), error(c)))\n    out.close()\n    print(\"\")\n\n    # 3 Make a log-log plot of relative error versus N\n    data = np.loadtxt(\"/tmp/tabla_resultados.dat\")\n    plt.figure()\n    plt.plot(data[:,0], data[:,1], label=\"Trapecio\")\n    plt.plot(data[:,0], data[:,2], label=\"Simpson\")\n    plt.plot(data[:,0], data[:,3], label=\"Cuadratura\")\n\n    plt.xlabel('N')\n    plt.ylabel('|error|')\n    plt.loglog()\n    plt.legend()\n    plt.savefig(\"error_loglogplot.png\")\n\n\n    # 4. Use your plot or table to estimate the power-law dependence of the error on N and\n# to determine the nuber of decimal places of precision.\n\n    for i,m in zip([1,2,3],[\"Trapecio\", \"Simpson\", \"Cuadratura\"]):\n        power_law = (np.log(data[2,i]) - np.log(data[0,i]))/(np.log(data[2,0]) - np.log(data[0,0]))\n        decimal_places = -np.log10(data[-1,i])\n        print(\"Metodo {}\".format(m))    \n        print(\"\\t Power Law: {:.1f}\".format(power_law))\n        print(\"\\t Decimal Places: {:d}\".format(int(decimal_places)))\n\n", "meta": {"hexsha": "0029caae435390d28118eff205e8ff9e2e2e2303", "size": 3071, "ext": "py", "lang": "Python", "max_stars_repo_path": "Metodos Computacionales Uniandes/Code/ejercicio_21.py", "max_stars_repo_name": "aess14/Cursos-Uniandes", "max_stars_repo_head_hexsha": "be016b25f2f49788235fbe91ec577fd16b9ad613", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Metodos Computacionales Uniandes/Code/ejercicio_21.py", "max_issues_repo_name": "aess14/Cursos-Uniandes", "max_issues_repo_head_hexsha": "be016b25f2f49788235fbe91ec577fd16b9ad613", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Metodos Computacionales Uniandes/Code/ejercicio_21.py", "max_forks_repo_name": "aess14/Cursos-Uniandes", "max_forks_repo_head_hexsha": "be016b25f2f49788235fbe91ec577fd16b9ad613", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5056179775, "max_line_length": 99, "alphanum_fraction": 0.5952458483, "include": true, "reason": "import numpy", "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.9372107979795822, "lm_q1q2_score": 0.881718314745536}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport ipywidgets as widgets\n\ndef solow_equation(k,alpha,delta,s):\n\n    saving = s*k**alpha\n    depreciation = delta*k\n    k_plus = k + saving - depreciation    \n    return k_plus, saving, depreciation  \n              \ndef simulate_solow_model(k0,alpha,delta,s,T):\n\n    k_path = [k0]    \n    saving_path = []\n    depreciation_path = []\n    \n    for t in range(1,T):\n\n        k_plus,saving,depreciation = solow_equation(k_path[t-1],alpha,delta,s)    \n\n        k_path.append(k_plus)\n        saving_path.append(saving)\n        depreciation_path.append(depreciation)\n        \n    return k_path,saving_path,depreciation_path\n\n\ndef simulate(k_max=10,T=150):\n\n   widgets.interact(simulate_,        \n                    k0=widgets.FloatSlider(description='$k_0$',min=0, max=k_max, step=0.05, value=2), \n                    alpha=widgets.FloatSlider(description='$\\\\alpha$',min=0.01, max=0.99, step=0.01, value=0.3), \n                    delta=widgets.FloatSlider(description='$\\\\delta$',min=0.01, max=0.50, step=0.01, value=0.1), \n                    s=widgets.FloatSlider(description='$s$',min=0.01, max=0.99, step=0.01, value=0.3), \n                    T=widgets.fixed(T), \n                    k_max=widgets.fixed(k_max)) \n\ndef simulate_(k0,alpha,delta,s,T,k_max):\n\n    k_path,saving_path,depreciation_path = simulate_solow_model(k0,alpha,delta,s,T*5)\n\n    fig = plt.figure(figsize=(16,6),dpi=100)\n    ax1 = fig.add_subplot(1,2,1)\n\n    ax1.plot(k_path[:T],lw=2)\n    ax1.grid(ls='--',lw=1)\n    ax1.set_title('Capital ($k_t$)')\n    ax1.set_xlim([0,T])\n    ax1.set_ylim([0,k_max])\n\n    k_path = np.array(k_path)\n    I = np.abs(np.log(k_path) - np.log(k_path[-1])) < 0.01\n    t_converge = T*5 - k_path[I].size\n    ax1.plot([t_converge,t_converge],[0,k_max],ls='--',color='black',label='$|\\\\log(k_t)-\\\\log(k^\\\\ast)| < 0.01$')\n\n    legend = ax1.legend(loc='lower right', shadow=True)\n    frame = legend.get_frame()\n    frame.set_facecolor('0.90')\n\n    ax2 = fig.add_subplot(1,2,2)\n    ax2.plot(saving_path[:T],label='saving')\n    ax2.plot(depreciation_path[:T],label='depreciation')\n    ax2.grid(ls='--',lw=1)\n    ax2.set_title('Saving ($sk^\\\\alpha$) and depreciation ($\\\\delta k_t$)')\n    ax2.set_xlim([0,T])\n    ax2.set_ylim([0,0.5*k_max])\n\n    legend = ax2.legend(loc='upper left', shadow=True)\n    frame = legend.get_frame()\n    frame.set_facecolor('0.90')\n", "meta": {"hexsha": "41994fd6fe3ba3c48d64024ce9ac934d305d32ac", "size": 2400, "ext": "py", "lang": "Python", "max_stars_repo_path": "numecon/course_macro1/solow.py", "max_stars_repo_name": "minjiedeng/NumEcon", "max_stars_repo_head_hexsha": "ff021e765344db93eed7ff0002dbdf3e50e528e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-03T12:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T12:23:34.000Z", "max_issues_repo_path": "numecon/course_macro1/solow.py", "max_issues_repo_name": "minjiedeng/NumEcon", "max_issues_repo_head_hexsha": "ff021e765344db93eed7ff0002dbdf3e50e528e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numecon/course_macro1/solow.py", "max_forks_repo_name": "minjiedeng/NumEcon", "max_forks_repo_head_hexsha": "ff021e765344db93eed7ff0002dbdf3e50e528e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3333333333, "max_line_length": 114, "alphanum_fraction": 0.61625, "include": true, "reason": "import numpy", "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693731004241, "lm_q2_score": 0.928408793127304, "lm_q1q2_score": 0.8816813965501281}}
{"text": "import numpy as np\nimport copy\nfrom copy import deepcopy\n\n#normalize the list into range [-1,1]\ndef linear_normalization(data):\n    normalization = deepcopy(data)\n    for index, datai in enumerate(normalization):\n        datai = float(datai)\n        normalization[index] = datai\n    max = np.max(normalization)\n    min = np.min(normalization)\n    for index, datai in enumerate(data):\n        datai = 2*(datai-min)/(max-min)-1\n        normalization[index] = datai\n    return normalization\n\n#normalize the list by substracting mean and divided by standard deviation (zscore)\ndef z_score(data):\n    normalization = deepcopy(data)\n    average = np.mean(normalization)\n    std = np.std(normalization)\n    for index, datai in enumerate(normalization):\n        datai = (datai-average)/std\n        normalization[index] = datai\n    return normalization\n\n\nsamplelist = [1, 2, 3, 4, 5]\nlinearsample = linear_normalization(samplelist)\nzscoresample = z_score(samplelist)\n", "meta": {"hexsha": "025bc76d6c6e9fadaf1c0bfcc6654dfd1e469aa6", "size": 958, "ext": "py", "lang": "Python", "max_stars_repo_path": "build/lib/rqalpha/data/dtsk_python_interface/utility/normalization.py", "max_stars_repo_name": "kinglogxzl/rqalpha", "max_stars_repo_head_hexsha": "6203803e0fb130fbb5a280ee8e1b902a8c0fd731", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/lib/rqalpha/data/dtsk_python_interface/utility/normalization.py", "max_issues_repo_name": "kinglogxzl/rqalpha", "max_issues_repo_head_hexsha": "6203803e0fb130fbb5a280ee8e1b902a8c0fd731", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/lib/rqalpha/data/dtsk_python_interface/utility/normalization.py", "max_forks_repo_name": "kinglogxzl/rqalpha", "max_forks_repo_head_hexsha": "6203803e0fb130fbb5a280ee8e1b902a8c0fd731", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9375, "max_line_length": 83, "alphanum_fraction": 0.7035490605, "include": true, "reason": "import numpy", "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561685659695, "lm_q2_score": 0.9099070042057363, "lm_q1q2_score": 0.8815690138461092}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef fowardDif(func,x,h):\n    return (func(x+h)-func(x))/h\n\ndef backwardDif(func,x,h):\n    return (func(x)-func(x-h))/h\n\ndef centralDif(func,x,h):\n    return (func(x+h)-func(x-h))/(2*h)\n\ndef getError(approx,truth):\n    return np.abs(truth-approx)/np.abs(truth)\n\ndef partOne(f,dT,h,x):\n    # Setup\n   \n\n    # Part 1\n    # fowardErr = []\n    # backErr = []\n    centralErr = []\n    for i in h:\n        # fowardErr.append(getError(fowardDif(f,x,i),dT))\n        # backErr.append(getError(backwardDif(f,x,i),dT))\n        centralErr.append(getError(centralDif(f,x,i),dT))\n    \n    # plt.loglog(h, fowardErr, 'ro-')\n    # plt.grid()\n    # plt.xlabel('h')\n    # plt.ylabel(\"Relative Error\")\n    # plt.title(\"Forward Difference Error\")\n    # plt.show()\n\n    # plt.loglog(h, backErr, 'ro-')\n    # plt.xlabel('h')\n    # plt.grid()\n    # plt.ylabel(\"Relative Error\")\n    # plt.title(\"Backward Difference Error\")\n    # plt.show()\n\n    plt.loglog(h, centralErr, 'ro-')\n    plt.xlabel('h')\n    plt.grid()\n    plt.ylabel(\"Relative Error\")\n    plt.title(\"Central Difference Error\")\n    plt.show()\n\ndef partTwo(f,x,h,dT):\n    approxDerivErr = []\n    for i in h:\n        approxDerivErr.append(getError(approxDeriv(f,x,i),dT))\n\n    plt.loglog(h, approxDerivErr, 'ro-')\n    plt.xlabel('h')\n    plt.grid()\n    plt.ylabel(\"Relative Error\")\n    plt.title(\"Relative Error for an Approximated Derivative\")\n    plt.show()\n\n\ndef helper():\n    xT = 0.2\n    deriFunc = lambda x: np.cos(4.8*np.pi*x)*4.8*np.pi\n    deriTruth = deriFunc(xT)\n    h = [np.power(2.,-i) for i in range(5,31)]\n    h.reverse()\n    func = lambda x: np.sin(4.8*np.pi*x)\n    arrErr = []\n    for i in h:\n        # arrErr.append(getError(centralDif(func,xT,i),deriTruth))\n        arrErr.append(getError(approxDeriv(func,xT,i),deriTruth))\n    temp = np.log(arrErr[16])-np.log(arrErr[len(arrErr)-2])\n    temp2 = np.log(h[16])-np.log(h[len(arrErr)-2])\n    print(temp/temp2)\n\ndef approxDeriv(func,x,h):\n    return (2*func(x+h) + 3*func(x) - 6*func(x-h) + func(x-2*h))/(6*h)\n\ndef main():\n    xT = 0.2\n    h = [np.power(2.,-i) for i in range(5,31)]\n    h.reverse()\n    func = lambda x: np.sin(4.8*np.pi*x)\n    deriFunc = lambda x: np.cos(4.8*np.pi*x)*4.8*np.pi\n    deriTruth = deriFunc(xT)\n\n    partOne(func,deriTruth,h,xT)\n    # partTwo(func,xT,h,deriTruth)\n    \nhelper()\n# main()", "meta": {"hexsha": "d13c201f4f0dbbbc72b9a1ccd3c32a0b30537298", "size": 2365, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW10/homeworkScript.py", "max_stars_repo_name": "kai-handelman/NumericalAnalysisHomework", "max_stars_repo_head_hexsha": "2153dc39405168cabbf5c33c1238e64ceb96adf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW10/homeworkScript.py", "max_issues_repo_name": "kai-handelman/NumericalAnalysisHomework", "max_issues_repo_head_hexsha": "2153dc39405168cabbf5c33c1238e64ceb96adf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW10/homeworkScript.py", "max_forks_repo_name": "kai-handelman/NumericalAnalysisHomework", "max_forks_repo_head_hexsha": "2153dc39405168cabbf5c33c1238e64ceb96adf1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1595744681, "max_line_length": 70, "alphanum_fraction": 0.5949260042, "include": true, "reason": "import numpy", "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551546097941, "lm_q2_score": 0.9136765328159726, "lm_q1q2_score": 0.8815655123334959}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# generate an array of floats between 0 and 1\nnumber_of_features = 10\nx = np.random.uniform(low=0, high=1, size=(number_of_features,))  # Write your code here\ny = 1 + 2 * x\n# plot data\n# plt.plot(x,y,'b')\n# plt.show()\n\n# # Step 2: Generate noisy data\n# generate random values using normal distribution with mean = 0 and standard deviation = 0.1\nmu, sigma = 0, 0.1\nnoise = np.random.normal(mu, sigma, number_of_features)  # Write your code here\ny_noise = y + noise\n#\nplt.plot(x, y, 'b', x, y_noise, 'rx')\nplt.show()\n\n#\n## Step 3: Find parameters\n# Here you have to use the provided formulas to calculate the parameters theta_0 ($\\theta_0$) and theta_1 ($\\theta_1$)\ndef get_theta_1(x1, y):\n    X = np.stack((x1, y), axis=0)\n    cov = np.cov(X)[0][1]\n    var = np.var(x1)\n    return cov / var\n\n\ndef get_theta_2(x1, y, theta_1):\n    return np.mean(y) - theta_1 * np.mean(x1)\n\n\n# Write your code below\ntheta_1 = get_theta_1(x, y_noise)\ntheta_0 = get_theta_2(x, y_noise, theta_1)\n#\nz = theta_0 + theta_1 * x\n#\n# plot the original line and the fitting linear line here on the same graph\nplt.xlabel('x')\nplt.ylabel('y')\nplt.plot(x,y,'b',x,y_noise,'rx',x,z,'g')\nplt.legend(('Original Data', 'Noisy Data', 'Linear Fit'), loc='lower right')\nplt.show()\n#\n## Step 4: Fit multiple lines\nplt.subplot(111)\nnum_sigma = 6\ny_noise = np.zeros((num_sigma,len(x)))\nz = np.zeros((num_sigma,len(x)))\nfor indx,sigma in enumerate(np.linspace(0,1,num=num_sigma)):\n    # generate the noise\n    noise = np.random.normal(mu, sigma, number_of_features)\n    y_noise[indx,:] = noise + y\n    # calculate theta_1 and theta_0\n    theta_1 = get_theta_1(x, y_noise[indx,:])\n    theta_0 = get_theta_2(x,y_noise[indx,:],theta_1)\n    z[indx,:] = theta_0 + theta_1*x\n    # plot the fitting line\n    plt.plot(x,z[indx,:])\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend(('0.0','0.2','0.4','0.6','0.8','1.0'), loc='lower right')\n#\n# reset the color cycle, so that the same color will be used for dots\nplt.gca().set_prop_cycle(None)\n# plot dots in the same figure\nfor indx in range(num_sigma):\n    plt.plot(x,y_noise[indx,:],'.')\nplt.show()\n#\n## Step 5: Explore the statistical properties of simple linear regression\nmu = 0\nsigma = 0.1\nn = 1000\nparams = np.zeros((n,2))\nfor i in range(n):\n    # genrate the noise\n    noise = np.random.normal(mu, sigma, number_of_features)\n    y_noise = y + noise\n    # your code goes here\n    theta_1 = get_theta_1(x, y_noise)\n    theta_0 = get_theta_2(x,y_noise,theta_1)\n    params[i,0] = theta_0\n    params[i,1] = theta_1\ntheta_bar = np.mean(params,axis=0)\ntheta_sd = np.std(params,axis=0)\nprint(\"Mean Theta 0: \",theta_bar[0])\nprint(\"Mean Theta 1: \",theta_bar[1])\nprint(\"STD 0: \",theta_sd[0])\nprint(\"STD 1: \",theta_sd[1])\nf, axarr = plt.subplots(2, sharex=True)\naxarr[0].hist(params[:,0],bins=30)\naxarr[0].set_title('Theta 0')\naxarr[1].hist(params[:,1],bins=30)\naxarr[1].set_title('Theta 1')\nplt.show()\n", "meta": {"hexsha": "95b96b9b4999a3bfd2b79e58566c587e09a984c9", "size": 2941, "ext": "py", "lang": "Python", "max_stars_repo_path": "1.- simple linear regression/solution/simple_linear_regression.py", "max_stars_repo_name": "nik1168/data-representation-reduction-exercises", "max_stars_repo_head_hexsha": "6b39940ae2c9f5a0eb5a3ce4ed57a32e1d2ac166", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1.- simple linear regression/solution/simple_linear_regression.py", "max_issues_repo_name": "nik1168/data-representation-reduction-exercises", "max_issues_repo_head_hexsha": "6b39940ae2c9f5a0eb5a3ce4ed57a32e1d2ac166", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1.- simple linear regression/solution/simple_linear_regression.py", "max_forks_repo_name": "nik1168/data-representation-reduction-exercises", "max_forks_repo_head_hexsha": "6b39940ae2c9f5a0eb5a3ce4ed57a32e1d2ac166", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.41, "max_line_length": 118, "alphanum_fraction": 0.6732403944, "include": true, "reason": "import numpy", "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102524151826, "lm_q2_score": 0.9111797124237605, "lm_q1q2_score": 0.8814845955914636}}
{"text": "# #from numpy import array, zeros\r\n# from array import *\r\nimport numpy as np\r\n#from numpy import fabs\r\n\r\n'''\r\na=np.array([[25,5,1],\r\n        [64,8,1],\r\n        [144,12,1]],float)\r\nb=[106.8,177,279.2]\r\nn= len(b)\r\nx= np.zeros(n,float)\r\n\r\n# Elimination\r\nfor k in range(n - 1):\r\n    for i in range(k + 1, n):\r\n        if a[i, k] == 0:\r\n            continue\r\n        factor = a[k, k] / a[i, k]\r\n        for j in range(k, n):\r\n            a[i, j] = a[k, j] - a[i, j] * factor\r\n        b[i] = b[k] - b[i] * factor\r\nprint(a)\r\n\r\nprint(b)\r\n\r\n# Back-Substitution\r\nx[n - 1] = b[n - 1] / a[n - 1, n - 1]\r\nfor i in range(n - 2, -1, -1):\r\n    sum_ax = 0\r\n    for j in range(i + 1, n):\r\n        sum_ax += a[i, j] * x[j]\r\n    x[i] = (b[i] - sum_ax) / a[i, i]\r\n\r\nprint(x)\r\n'''\r\n\r\n### Gauss Elimination Method with Partial Pivoting\r\n##3 defining array\r\n## Coefficient Matrix\r\n'''\r\na= np.array([[0,7,-1,3,1],\r\n             [0,3,4,1,7],\r\n             [6,2,0,2,-1],\r\n             [2,1,2,0,2],\r\n             [3,4,1,-2,1]],float)\r\n## Constant vector\r\nb = np.array([5,7,2,3,4],float)\r\n'''\r\n'''\r\na=np.array([[25,5,1],\r\n        [64,8,1],\r\n        [144,12,1]],float)\r\nb=np.array([106.8,177,279.2],float)\r\n'''\r\na=np.array([[20,15,10],\r\n            [-3,-2.249,7],\r\n            [5,1,3]],float)\r\nb=np.array([45,1.751,9],float)\r\n\r\n## length of the vector\r\nn= len(b)\r\n# defining zeros to fill the entries of x\r\nx= np.zeros(n,float)\r\n##\r\n\r\n## --------------Partial Pivoting---------------\r\n## if there is zero on the main diagonal the we have to interchange the row with another row which has greater value then zero\r\nfor k in range(n-1):\r\n    if abs(a[k,k])<1.0e-10:\r\n        for i in range(k+1, n):  ### I have to check here what if i take n instead of (n-1), can we interchange the pivot row with the last row.\r\n            if abs(a[i,k])> abs(a[k,k]): #we can also write (1.0e-10) instead of a([k,k])### it doesn't matter whether we take n or n-1in the previous range.\r\n                a[[i,k]]=a[[k,i]]\r\n                b[[k,i]]=b[[i,k]]\r\n                break\r\n\r\n\r\n    # Elimination---->\r\n\r\n    #for k in range(n-1):\r\n    for i in range(k+1,n):\r\n        if a[i,k]==0:\r\n            continue\r\n        factor= a[k,k]/a[i,k]\r\n        for j in range(k,n):\r\n            a[i,j]= a[k,j]- a[i,j]*factor\r\n        b[i]=b[k]-b[i]*factor\r\nprint(\"the upper triangular matrix \")\r\nU=a\r\nprint(np.round(U,1))\r\n## back-Substitution---->\r\n\r\nx[n-1]= b[n-1]/a[n-1,n-1]\r\nfor i in range(n-2,-1,-1):\r\n    sum_ax=0\r\n    for j in range(i+1,n):\r\n        sum_ax+=a[i,j]*x[j]\r\n    x[i]= (b[i]-sum_ax)/a[i,i]\r\n\r\nprint(\"The solution vector is: \")\r\nprint(np.round(x,1))\r\n", "meta": {"hexsha": "1a719fa160b85a30de322ea98735f1a3f74e533d", "size": 2609, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numerical_Methods_Physics/Gauss_Elimination.py", "max_stars_repo_name": "Simba2805/Computational_Physics_Python", "max_stars_repo_head_hexsha": "be687939c16a1d08066939830ac31ba666a3e1bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numerical_Methods_Physics/Gauss_Elimination.py", "max_issues_repo_name": "Simba2805/Computational_Physics_Python", "max_issues_repo_head_hexsha": "be687939c16a1d08066939830ac31ba666a3e1bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numerical_Methods_Physics/Gauss_Elimination.py", "max_forks_repo_name": "Simba2805/Computational_Physics_Python", "max_forks_repo_head_hexsha": "be687939c16a1d08066939830ac31ba666a3e1bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5784313725, "max_line_length": 158, "alphanum_fraction": 0.4871598314, "include": true, "reason": "import numpy,from numpy", "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102561735719, "lm_q2_score": 0.9111797063939127, "lm_q1q2_score": 0.8814845931826951}}
{"text": "def cells():\n    # setup SymPy\n    from sympy import *\n    init_printing()\n    x, y, z, t = symbols('x y z t')\n    alpha, beta = symbols('alpha beta')\n\n    '''\n    '''\n\n    '''\n    # Linearity\n    '''\n\n    '''\n    '''\n\n    b, m = symbols('b m')\n    \n    def f(x):\n        return m*x\n\n    '''\n    '''\n\n    f(1)\n\n    '''\n    '''\n\n    f(2)\n\n    '''\n    '''\n\n    f(1+2)\n\n    '''\n    '''\n\n    f(1) + f(2)\n\n    '''\n    '''\n\n    expand(f(x+y)) ==  f(x) + f(y)\n\n    '''\n    '''\n\n    '''\n    ## What about vector inputs?\n    '''\n\n    '''\n    '''\n\n    m_1, m_2 = symbols('m_1 m_2')\n    \n    def T(vec):\n        \"\"\"A function that takes a 2D vector and returns a number.\"\"\"\n        return m_1*vec[0] + m_2*vec[1]\n\n    '''\n    '''\n\n    u_1, u_2 = symbols('u_1 u_2')\n    u = Matrix([u_1,u_2])\n    v_1, v_2 = symbols('v_1 v_2')\n    v = Matrix([v_1,v_2])\n\n    '''\n    '''\n\n    T(u)\n\n    '''\n    '''\n\n    T(v)\n\n    '''\n    '''\n\n    T(u) + T(v)\n\n    '''\n    '''\n\n    expand( T(u+v) )\n\n    '''\n    '''\n\n    simplify( T(alpha*u + beta*v) - alpha*T(u) - beta*T(v) )\n\n    '''\n    '''\n\n    '''\n    # Linear transformations\n    '''\n\n    '''\n    '''\n\n    '''\n    A linear transformation is function that takes vectors as inputs, and produces vectors as outputs:\n    \n    $$\n       T: \\mathbb{R}^n \\to \\mathbb{R}^m.\n    $$\n    \n    see page 116 in book\n    '''\n\n    '''\n    '''\n\n    m_11, m_12, m_21, m_22 = symbols('m_11 m_12 m_21 m_22')\n    \n    def T(vec):\n        \"\"\"A linear transformations R^2 --> R^2.\"\"\"\n        out_1 = m_11*vec[0] + m_12*vec[1]\n        out_2 = m_21*vec[0] + m_22*vec[1]\n        return Matrix([out_1, out_2])\n\n    '''\n    '''\n\n    T(u)\n\n    '''\n    '''\n\n    T(v)\n\n    '''\n    '''\n\n    T(u+v)\n\n    '''\n    '''\n\n    '''\n    ## Linear transformations as matrix-vector products \n    '''\n\n    '''\n    '''\n\n    '''\n    see page 113\n    '''\n\n    '''\n    '''\n\n    def T_impl(vec):\n        \"\"\"A linear transformations implemented as matrix-vector product.\"\"\"\n        M_T = Matrix([[m_11, m_12], \n                      [m_21, m_22]])\n        return M_T*vec\n\n    '''\n    '''\n\n    T_impl(u)\n\n    '''\n    '''\n\n\n    '''\n    '''\n\n", "meta": {"hexsha": "a88f373d1f074179d3a78ae2db76f8f76be67d8f", "size": 2115, "ext": "py", "lang": "Python", "max_stars_repo_path": "aspynb/chapter02_linearity_intuition.py", "max_stars_repo_name": "ChidinmaKO/noBSLAnotebooks", "max_stars_repo_head_hexsha": "c0102473f1e6625fa5fb62768d4545059959fa26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aspynb/chapter02_linearity_intuition.py", "max_issues_repo_name": "ChidinmaKO/noBSLAnotebooks", "max_issues_repo_head_hexsha": "c0102473f1e6625fa5fb62768d4545059959fa26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aspynb/chapter02_linearity_intuition.py", "max_forks_repo_name": "ChidinmaKO/noBSLAnotebooks", "max_forks_repo_head_hexsha": "c0102473f1e6625fa5fb62768d4545059959fa26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.8820224719, "max_line_length": 102, "alphanum_fraction": 0.3839243499, "include": true, "reason": "from sympy", "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102542943773, "lm_q2_score": 0.9111797051879431, "lm_q1q2_score": 0.8814845903037438}}
{"text": "# make a cobweb plot\nimport numpy as np\n#from numpy import cos\nimport matplotlib.pyplot as plt\n\n# here is the function we want to iterate\n# mu is a possible parameter\ndef func(x,mu,c4):\n\treturn x*(2*np.pi/mu) + c4#mu*np.sin(x*(1.0*np.pi)) #mu*x*(1-x)\n\n# return f^n(x)\ndef func_n(x,mu,c4,n):\n\tfor i in range(-n,n):\n\t\tx = func(x,mu,c4)\n\n\treturn x\n# here is \"plotting graphical\" or \"cobweb\" for an interated map\n# connect up (x, f^1(x)), (f^1(x),f^1(x)), (f^1(x), f^2(x)), (f^2(x),f^2(x))\n#  ... (f^i(x), f^(i+1)(x)),(f^(i+1),f^(i+1)) to i=n\n# initial x0, mu is a parameter to pass to function\n# connect up points n times, this is 2n pairs of points\ndef plot_graphical(x0,mu,c4, n):\n\txv = np.linspace(0.0,1.0,2*n)  # create array for points xvalue \n\tyv = np.linspace(0.0,1.0,2*n)  # create array for points yvalue \n\tx =x0\n\tfor i in range(0,n):  #iterate\n\t\txv[2*i] = x  # first point is (x,f(x))\n\t\tx = func(x,mu,c4)\n\t\tyv[2*i] = x\n\t\txv[2*i+1] = x #second point is (f(x),f(x))\n\t\tyv[2*i+1] = x\n\tplt.plot(xv,yv,'b')  # connect up all these points blue\n\nplt.figure()\nplt.xlabel('r')\nplt.ylabel('P(r)')\nplt.xticks([-np.pi, -.5*np.pi,0., .5*np.pi, np.pi,],[r\"$-\\pi$\",r\"$\\frac{-1}{2}\\pi$\",\"$0$\", r\"$\\frac{1}{2}\\pi$\",\n                     r\"$\\pi$\"])\n\nfac=1.01\nxmax = np.pi\nxmin =-np.pi\n#ymax = 1.01\n#ymin =0.01\n#plt.axis([xmin*fac,xmax*fac,ymin*fac,ymax*fac])\nxcon = np.arange(xmin, xmax, 0.01)   # to plot function \nplt.plot(xcon,xcon, 'g',label=r'P(r) = r')             #y=x plotted green\n\nmu=10\nc4= .5\nycon = func(xcon,mu,c4)                 # function computed\nplt.plot(xcon,ycon, 'r', label=\"P(r)\")             # function plotted red\nplot_graphical(xmin,mu,c4,10)            # cobweb plot, 0.3 is initial condition\nplot_graphical(xmax,mu,c4,10)            # cobweb plot, 0.3 is initial condition\nplt.title('Strogatz Figure 8.7.3')\nplt.grid()\nplt.legend()\nplt.show()", "meta": {"hexsha": "ba183131f8aba8ee988eaaf8a00b2ab20a79f49a", "size": 1857, "ext": "py", "lang": "Python", "max_stars_repo_path": "Strogatz/CobwebPlot.py", "max_stars_repo_name": "yuchiaol/Non-linear-dynamics-Strogatz", "max_stars_repo_head_hexsha": "79e1171d4a88193d3da67c15f41212a96e6854dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 64, "max_stars_repo_stars_event_min_datetime": "2017-11-21T12:47:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:23:29.000Z", "max_issues_repo_path": "Strogatz/CobwebPlot.py", "max_issues_repo_name": "Llewelyn62/Non-linear-dynamics-Strogatz", "max_issues_repo_head_hexsha": "79e1171d4a88193d3da67c15f41212a96e6854dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Strogatz/CobwebPlot.py", "max_forks_repo_name": "Llewelyn62/Non-linear-dynamics-Strogatz", "max_forks_repo_head_hexsha": "79e1171d4a88193d3da67c15f41212a96e6854dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2017-11-21T20:11:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T00:00:30.000Z", "avg_line_length": 32.0172413793, "max_line_length": 111, "alphanum_fraction": 0.5982767905, "include": true, "reason": "import numpy,from numpy", "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102514755852, "lm_q2_score": 0.9111797057909279, "lm_q1q2_score": 0.8814845883186513}}
{"text": "from package import redact_ex\n\nfrom package import \\\n    euler_differentiate, \\\n    range_kutta_differentiate\n\nimport numpy as np\n\n\nEXERCISE_02i = \"\"\"\\\nMake a program that is able to graphically solve the equation\nd\\u00B2x/dt\\u00B2 + b dx/dt + \\u03C9_0\\u00B2 x = 0 using the Euler method.\\\n\"\"\"\n\nredact_ex(EXERCISE_02i, '2i')\n\n\n# dx/dt = y\n# dy/dt = -b*y - omega\n\nb = 1/2; omega_0 = 2\n\ndef inct(dt, *o):\n    return dt\n\ndef incx(dt, t, x, y):\n    return dt * y\n\ndef incy(dt, t, x, y, b = b, omega_0 = omega_0):\n    return dt * (-b*y - omega_0**2*x)\n\nprint(\"Computing Euler method...\", end='\\n\\n')\neuler_differentiate([inct, incx, incy], bounds = [0, 1, -1],\n    delta = 1e-2, itern = 1e4, graph = [1, 2],\n    title = r\"Euler method for function\"\n        + r\"$\\:\\:\\frac{d^2x}{dt^2} + b \\frac{dx}{dt} + \\omega_0^2 x = 0$\")\n\n\nEXERCISE_02 = \"\"\"\\\nMake a program that is able to graphically solve the equation\nd\\u00B2x/dt\\u00B2 + b dx/dt + \\u03C9_0\\u00B2 x = F cos(x) using:\n+ the Euler method\n+ the Range-Kutta method of order 2\n+ the Range-Kutta method of order 4\nComment on the effects of \\u0394t over the obtained solutions\n(analyze the methods' stability with regards to the \\u0394t used).\\\n\"\"\"\n\nredact_ex(EXERCISE_02, 2)\n\n\n# dx/dt = y\n# dy/dt = -b*y - omega_0**2*x + f*np.cos(omega*t)\n\nb = 1/2; omega_0 = 4; f = 1; omega = 2\n\ndef inct(dt, *o):\n    return dt\n\ndef incx(dt, t, x, y):\n    return dt * y\n\ndef incy(dt, t, x, y, b = b, omega_0 = omega_0, f = f, omega = omega):\n    return dt * (-b*y - omega_0**2*x + f*np.cos(omega*t))\n\nprint(\"Computing Euler method...\", end='\\n\\n')\neuler_differentiate([inct, incx, incy], bounds = [0, 0, 1],\n    delta = 1e-2, itern = 1e4, graph = [1, 2],\n    title = r\"Euler method for function\"\n        + r\"$\\:\\:\\frac{d^2x}{dt^2} + b \\frac{dx}{dt} + \\omega_0^2 x = F \\cos(\\omega t)$\")\n\nprint(\"Computing Range-Kutta method of order 2...\", end='\\n\\n')\nrange_kutta_differentiate([inct, incx, incy], bounds = [0, 0, 1],\n    delta = 1e-2, order = 2, itern = 1e4, graph = [1, 2],\n    title = r\"Range-Kutta method of order 2 for function\"\n        + r\"$\\:\\:\\frac{d^2x}{dt^2} + b \\frac{dx}{dt} + \\omega_0^2 x = F \\cos(\\omega t)$\")\n\nprint(\"Computing Range-Kutta method of order 4...\", end='\\n\\n')\nrange_kutta_differentiate([inct, incx, incy], bounds = [0, 0, 1],\n    delta = 1e-2, order = 4, itern = 1e4, graph = [1, 2],\n    title = r\"Range-Kutta method of order 4 for function\"\n        + r\"$\\:\\:\\frac{d^2x}{dt^2} + b \\frac{dx}{dt} + \\omega_0^2 x = F \\cos(\\omega t)$\")\n\nomega = omega_0\ndef incy(dt, t, x, y, b = b, omega_0 = omega_0, f = f, omega = omega):\n    return dt * (-b*y - omega_0**2*x + f*np.cos(omega*t))\n\neuler_differentiate([inct, incx, incy], bounds = [0, 0, 1],\n    delta = 1e-2, itern = 1e4, graph = [1, 2],\n    title = r\"Euler method for function\"\n        + r\"$\\:\\:\\frac{d^2x}{dt^2} + b \\frac{dx}{dt} + \\omega_0^2 x = F \\cos(\\omega_0 t)$\")\n\n# When omega_0 == omega, movement is a single sinusoidal wave since the start\n# rather than a combination of two, as we can see in the early stages\n# of the plots where omega_0 != omega.", "meta": {"hexsha": "a5294d6eeccbd1de63977121ac38fd3d442347f3", "size": 3062, "ext": "py", "lang": "Python", "max_stars_repo_path": "T07/ex02.py", "max_stars_repo_name": "mariogarcc/comphy", "max_stars_repo_head_hexsha": "3ab05a07dfa2eb8a1165fca1bdfd9bda6c8e27d3", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "T07/ex02.py", "max_issues_repo_name": "mariogarcc/comphy", "max_issues_repo_head_hexsha": "3ab05a07dfa2eb8a1165fca1bdfd9bda6c8e27d3", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "T07/ex02.py", "max_forks_repo_name": "mariogarcc/comphy", "max_forks_repo_head_hexsha": "3ab05a07dfa2eb8a1165fca1bdfd9bda6c8e27d3", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2315789474, "max_line_length": 91, "alphanum_fraction": 0.6113651208, "include": true, "reason": "import numpy", "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920617, "lm_q2_score": 0.9173026561945815, "lm_q1q2_score": 0.8814835545827591}}
{"text": "import math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass fakeRule:\n    f = None\n    xl = 0\n    xu = 0\n    mini = 0\n    maxi = 0\n    table = [[\"i\",\"xl\",\"xu\",\"xi\",\"f(xl)\",\"f(xu)\",\"f(xi)\"]]\n\n    def __init__(self, f, mini=0, maxi= 0):\n        self.f = f\n        self.maxi = maxi\n        self.mini = mini\n\n    def display(self):\n        xvalues = np.arange(self.mini,self.maxi,.1)\n        plt.plot(xvalues ,[self.f(x) for x in xvalues])\n        plt.plot([self.mini,self.maxi],[0,0],\"b\")\n        plt.plot([0,0],[self.f(self.mini),self.f(self.maxi)],\"b\")\n        plt.xlabel(\"x\")\n        plt.ylabel(\"f(x)\")\n        plt.show()\n        \n    def getXi(self, xl, xu):\n        a = xu*(self.f(xl)) - xl*(self.f(xu))\n        b = self.f(xl) - self.f(xu)\n        return a/b\n    \n    def isInside(self,error,xi):\n        return abs(self.f(xi)) < error\n    \n    def findRoot(self, xl,xu, error):\n        self.table = [[\"i\",\"xl\",\"xu\",\"xi\",\"f(xl)\",\"f(xu)\",\"f(xi)\"]]\n        xi = self.getXi(xl,xu)\n        it = 0\n        \n        while not self.isInside(error,xi):\n            self.table.append([it,xl,xu,xi,self.f(xl),self.f(xu),self.f(xi)])\n            xu = {True:xi, False:xu}[self.f(xi)*self.f(xu)>0]\n            xl = {True:xi, False:xl}[self.f(xi)*self.f(xl)>0]\n            xi = self.getXi(xl,xu)\n            it += 1\n        self.table.append([it,xl,xu,xi,self.f(xl),self.f(xu),self.f(xi)])\n        print('\\n'.join(['\\t'.join([str(cell) for cell in row]) for row in self.table]))\n        return (xi)\n\n# How to use it\n# We need to define a function, the one that we need to solve\nfun = lambda x : math.sqrt(x) - (2*math.cos(math.radians(x+1)))\n#we create an object that receives the function and the range that it needs to be graphed\nroot_fun = fakeRule(fun, 0,50)\n#the display method allows us to see the function graphically \nroot_fun.display()\n#seeing this graph, we can find points in the function where the f(x) changes it's sign\n#the closer we get to these points the faster we will find a solution\n#Solve uses tree arguments, the lower limit, the higher limit and a degree of error that we will allow\nprint(\"The value x | f(x) -> 0 is: \" + str(root_fun.findRoot(0,10,.0001)))", "meta": {"hexsha": "3dc607bd847a1d0c2700b5115266caeaff4a5f77", "size": 2178, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/fakeRuler.py", "max_stars_repo_name": "antoniosalinasolivares/numericalMethods", "max_stars_repo_head_hexsha": "8f404ac4ea581e22cc4a46be3f76416999e85bf6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fakeRuler.py", "max_issues_repo_name": "antoniosalinasolivares/numericalMethods", "max_issues_repo_head_hexsha": "8f404ac4ea581e22cc4a46be3f76416999e85bf6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fakeRuler.py", "max_forks_repo_name": "antoniosalinasolivares/numericalMethods", "max_forks_repo_head_hexsha": "8f404ac4ea581e22cc4a46be3f76416999e85bf6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3, "max_line_length": 102, "alphanum_fraction": 0.5766758494, "include": true, "reason": "import numpy", "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517095103498, "lm_q2_score": 0.917302654499012, "lm_q1q2_score": 0.8814835539792074}}
{"text": "import numpy as np\n\ndef angular_dist(a1, d1, a2, d2):\n  a1 = np.radians(a1)\n  d1 = np.radians(d1)\n  a2 = np.radians(a2)\n  d2 = np.radians(d2)\n  \n  p1 = np.sin(abs(d1-d2)/2)**2\n  p2 = np.cos(d1)*np.cos(d2)*np.sin(abs(a1-a2)/2)**2\n  p3 = 2*np.arcsin(np.sqrt(p1+p2))\n  return np.degrees(p3)\n\n# You can use this to test your function.\n# Any code inside this `if` statement will be ignored by the automarker.\nif __name__ == '__main__':\n  # Run your function with the first example in the question.\n  print(angular_dist(21.07, 0.1, 21.15, 8.2))\n\n  # Run your function with the second example in the question\n  print(angular_dist(10.3, -3, 24.3, -29))\n\n", "meta": {"hexsha": "6799e1d8e2d09df7208bad3e57f2eb30c6419c64", "size": 646, "ext": "py", "lang": "Python", "max_stars_repo_path": "wk2/angular_distance.py", "max_stars_repo_name": "lokijota/datadrivenastronomymooc", "max_stars_repo_head_hexsha": "175655e5c6450c091534299da6bce6f10a1a3627", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-12-09T18:10:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T16:38:58.000Z", "max_issues_repo_path": "wk2/angular_distance.py", "max_issues_repo_name": "lokijota/datadrivenastronomymooc", "max_issues_repo_head_hexsha": "175655e5c6450c091534299da6bce6f10a1a3627", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wk2/angular_distance.py", "max_forks_repo_name": "lokijota/datadrivenastronomymooc", "max_forks_repo_head_hexsha": "175655e5c6450c091534299da6bce6f10a1a3627", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-11-09T16:57:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-15T09:11:33.000Z", "avg_line_length": 28.0869565217, "max_line_length": 72, "alphanum_fraction": 0.6640866873, "include": true, "reason": "import numpy", "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951711746926, "lm_q2_score": 0.917302651107873, "lm_q1q2_score": 0.8814835527721038}}
{"text": "# example of calculating the js divergence between two mass functions\n# forked from https://machinelearningmastery.com/divergence-between-probability-distributions/#:~:text=KL%20divergence%20can%20be%20calculated,of%20the%20event%20in%20P.&text=The%20value%20within%20the%20sum%20is%20the%20divergence%20for%20a%20given%20event.\n#HINT:\n# # calculate the jensen-shannon distance metric\n# from scipy.spatial.distance import jensenshannon\n# from numpy import asarray\n# # define distributions\n# p = asarray([0.10, 0.40, 0.50])\n# q = asarray([0.80, 0.15, 0.05])\n# # calculate JS(P || Q)\n# js_pq = jensenshannon(p, q, base=2)\n# print('JS(P || Q) Distance: %.3f' % js_pq)\n# # calculate JS(Q || P)\n# js_qp = jensenshannon(q, p, base=2)\n# print('JS(Q || P) Distance: %.3f' % js_qp)\n#\n#\nfrom math import log2\nfrom math import sqrt\nfrom numpy import asarray\n\n# calculate the kl divergence\ndef kl_divergence(p, q):\n\treturn sum(p[i] * log2(p[i]/q[i]) for i in range(len(p)))\n\n# calculate the js divergence\ndef js_divergence(p, q):\n\tm = 0.5 * (p + q)\n\treturn 0.5 * kl_divergence(p, m) + 0.5 * kl_divergence(q, m)\n\nif __name__ is \"__main__\":\n\t# define distributions\n\tp = asarray([0.10, 0.40, 0.50])\n\tq = asarray([0.80, 0.15, 0.05])\n\t# calculate JS(P || Q)\n\tjs_pq = js_divergence(p, q)\n\tprint('JS(P || Q) divergence: %.3f bits' % js_pq)\n\tprint('JS(P || Q) distance: %.3f' % sqrt(js_pq))\n\t# calculate JS(Q || P)\n\tjs_qp = js_divergence(q, p)\n\tprint('JS(Q || P) divergence: %.3f bits' % js_qp)\n\tprint('JS(Q || P) distance: %.3f' % sqrt(js_qp))\n\n\t# calculate the jensen-shannon distance metric\n\tfrom scipy.spatial.distance import jensenshannon\n\tfrom numpy import asarray\n\t# define distributions\n\tp = asarray([0.10, 0.40, 0.50])\n\tq = asarray([0.80, 0.15, 0.05])\n\t# calculate JS(P || Q)\n\tjs_pq = jensenshannon(p, q, base=2)\n\tprint('JS(P || Q) Distance: %.3f' % js_pq)\n\t# calculate JS(Q || P)\n\tjs_qp = jensenshannon(q, p, base=2)\n\tprint('JS(Q || P) Distance: %.3f' % js_qp)\n", "meta": {"hexsha": "d2e39945f2cde40a3e1353826d455a3aeb13a14d", "size": 1951, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/lib/model/divergences.py", "max_stars_repo_name": "timtyree/bgmc", "max_stars_repo_head_hexsha": "891e003a9594be9e40c53822879421c2b8c44eed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/lib/model/divergences.py", "max_issues_repo_name": "timtyree/bgmc", "max_issues_repo_head_hexsha": "891e003a9594be9e40c53822879421c2b8c44eed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/lib/model/divergences.py", "max_forks_repo_name": "timtyree/bgmc", "max_forks_repo_head_hexsha": "891e003a9594be9e40c53822879421c2b8c44eed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8392857143, "max_line_length": 258, "alphanum_fraction": 0.6745258842, "include": true, "reason": "from numpy,from scipy", "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517039189089, "lm_q2_score": 0.917302657890151, "lm_q1q2_score": 0.8814835521088846}}
{"text": "\"\"\"\nAuthor: phunc20\n\nhaar1D and haar2D are slightly modified version of the functions carrying the same names in the notebook.\n\n\n\"\"\"\nimport math\nimport numpy as np\n\ndef haar1D(n, SIZE):\n    # check power of two\n    if math.floor(math.log(SIZE) / math.log(2)) != math.log(SIZE) / math.log(2):\n        print(\"Haar defined only for lengths that are a power of two\")\n        return None\n    if n >= SIZE or n < 0:\n        print(\"invalid Haar index\")\n        return None\n    \n    # zero basis vector\n    if n == 0:\n        return np.ones(SIZE)\n    \n    # express n >= 1 as 2^p + q with p as large as possible;\n    # then k = SIZE/2^p is the length of the support\n    # and s = qk is the shift\n    p = math.floor(math.log(n) / math.log(2))\n    pp = int(pow(2, p))\n    k = SIZE / pp\n    s = (n - pp) * k\n    \n    h = np.zeros(SIZE)\n    h[int(s):int(s+k/2)] = 1\n    h[int(s+k/2):int(s+k)] = -1\n    # these are not normalized\n    return h\n\n\ndef haar2D(n, SIZE=8):\n    # get horizontal and vertical indices\n    hr = haar1D(n % SIZE, SIZE)\n    hv = haar1D(int(n / SIZE), SIZE)\n    # 2D Haar basis matrix is separable, so we can\n    # just take the column-row product\n    H = np.outer(hr, hv)\n    H = H / math.sqrt(np.sum(H * H))\n    # the previous line just divides H by its Frobenius norm\n    # so that the returned value of haar2D() has norm 1.\n    return H\n\n\ndef decomposition_step(array):\n    h = len(array)\n    exponent = math.log(h, 2)\n    if math.floor(exponent) != exponent:\n        print(\"Haar defined only for lengths that are a power of two\")\n        return None\n    # =============================================\n    #  Implementation 01:\n    #  Same as in the paper, only diff being\n    #  1-based to 0-based.\n    # =============================================\n    #array2 = np.empty_like(array)\n    array2 = [0]*h\n    for i in range(h//2):\n        array2[i] = (array[2*i] + array[2*i+1]) / math.sqrt(2)\n        array2[h//2 + i] = (array[2*i] - array[2*i+1]) / math.sqrt(2)\n    # =============================================\n    #  Implementation 02:\n    #  Try to code using matrix operation instead\n    # =============================================\n    #if not isinstance(array):\n    #    array = np.array(array)\n    return array2\n\n\nif __name__ == \"__main__\":\n    print(f\"decomposition_step([9,7,3,5]) = {decomposition_step([9,7,3,5])}\")\n", "meta": {"hexsha": "f9bac95e46652a944a0c02a32a6103dd69ae29ee", "size": 2347, "ext": "py", "lang": "Python", "max_stars_repo_path": "epfl/2020/hw-ipynb/HaarBasis/haar.py", "max_stars_repo_name": "phunc20/dsp", "max_stars_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-12T18:32:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T18:32:06.000Z", "max_issues_repo_path": "epfl/2020/hw-ipynb/HaarBasis/haar.py", "max_issues_repo_name": "phunc20/dsp", "max_issues_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "epfl/2020/hw-ipynb/HaarBasis/haar.py", "max_forks_repo_name": "phunc20/dsp", "max_forks_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7088607595, "max_line_length": 105, "alphanum_fraction": 0.5432466979, "include": true, "reason": "import numpy", "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778048911611, "lm_q2_score": 0.9207896758909756, "lm_q1q2_score": 0.8814515197033568}}
{"text": "# Question: https://projecteuler.net/problem=158\n# General idea:\n#     - Pick an decreasing sequence S, e.g. (n,n-1,...,1). There are C(26, n) ways of choosing S.\n#     - Assume the sequence we're going to construct consists of the left seq and the right seq, which is a partition of S.\n#     - Let the \"pivot\" be the character that comes lexicographically after its neighbour on the left, i.e. the first character of the right seq.\n#     - For each possible length k of the left seq,\n#         * There are C(n, k) ways of choosing the left seq.\n#         * However, among those C(n,k) seqs, there is always one seq such that all characters on the right seq are lexicographically after all characters on the left. In other words, left = (n, n-1, ..., n-k+1), right = (n-k, n-k-1, ..., 1).\n#         * For each of the C(n,k)-1 seqs on the left, there is always only one possible of choosing the right seq. This is because the right seq must be a decreasing seq.\n#     - So, p(n) = C(26, n) * sum_{k=1}^(k=n}[C(n, k) - 1]\n#     - We have that sum_{k=0}^{k=n}[C(n,k)]   = 2^n,\n#                 so sum_{k=1}^{k=n}[C(n,k)]   = 2^n - 1,\n#                 so sum_{k=1)^{k=n}[C(n,k)-1] = 2^n - 1 - n\n#     - So, p(n) = C(26, n) * (2^n - n - 1)\n\nfrom scipy.special import comb # comb(n,k) = n choose k\n\nM = 26 # number of characters in the alphabet\n\ndef C(n,k):\n    return comb(n, k, exact = True)\n\ndef sum_from_a_to_b(a, b):\n    return (b-a+1)*(a+b)//2\n\ndef p(n):\n    return C(26, n) * (2**n - n - 1)\nif __name__ == \"__main__\":\n    ans = 0\n\n    for n in range(1, M+1):\n        p_n = p(n)\n        ans = max(ans, p_n)\n\n    print(ans)\n", "meta": {"hexsha": "91878b43d4301aa02fb82c0e8000c0a029d5bee3", "size": 1625, "ext": "py", "lang": "Python", "max_stars_repo_path": "2nd_100/problem158.py", "max_stars_repo_name": "takekoputa/project-euler", "max_stars_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2nd_100/problem158.py", "max_issues_repo_name": "takekoputa/project-euler", "max_issues_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2nd_100/problem158.py", "max_forks_repo_name": "takekoputa/project-euler", "max_forks_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-02T12:08:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T12:08:46.000Z", "avg_line_length": 45.1388888889, "max_line_length": 242, "alphanum_fraction": 0.5889230769, "include": true, "reason": "from scipy", "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298657, "lm_q2_score": 0.9161096170250074, "lm_q1q2_score": 0.8813960035632442}}
{"text": "import pandas as pd\nfrom datascience import *\nfrom sympy import *\nimport matplotlib.pyplot as plt\nimport numpy as np \nimport plotly.graph_objs as go\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\nfrom ipywidgets import interact, interactive, fixed, interact_manual\nfrom IPython.display import display, HTML\n\ndef cobb_douglas(A, K, L, alpha, beta = None):\n    if beta is None:\n        return A * K ** alpha * L ** (1 - alpha)\n    else:\n        return A * K ** alpha * L ** (beta)\n        \ndef cobb_douglas_plotter_K(A, L_bar, alpha, y):\n    plt.plot(np.arange(0, 1.01, 0.01), y)\n    plt.title(fr\"Cobb-Douglas with $\\bar L$ = {L_bar}, $A$ = {A} and $\\alpha$ = {alpha}\", size=16)\n    plt.xlabel(\"Capital Stock\", size=16)\n    plt.ylabel(\"Output\", size=16);\n    \ndef cobb_douglas_plotter_L(A, K_bar, alpha):\n    L_s = np.arange(0, 1.01, 0.01)\n    V_3 = cobb_douglas(A, K_bar, L_s, alpha)\n    plt.plot(L_s, V_3)\n    plt.title(fr\"Cobb-Douglas with $\\bar K$ = {K_bar}, $A$ = {A} and $\\alpha$ = {alpha}\", size=16)\n    plt.xlabel(\"Labor Force\", size=16)\n    plt.ylabel(\"Output\", size=16);\n    \ndef plot_cobb_douglas(V, orig_V, t0label=\"trace 0\", t1label=\"trace 1\", filename=None):\n    data = [go.Surface(z = V, contours = go.surface.Contours(z = go.surface.contours.Z(show = False, project = dict(z = True))),\n                      colorscale = \"Electric\", showscale = False, name=t0label),\n           go.Surface(z = orig_V, contours = go.surface.Contours(z = go.surface.contours.Z(show = False, project = dict(z = True))),\n                     colorscale = \"Viridis\", showscale = False, name=t1label)]\n    layout = go.Layout(title = \"Cobb-Douglas Production Function\", autosize=False, width=500, height=500, margin = dict(l = 65, r = 50, b = 65, t = 90),\n                       scene = dict(xaxis = dict(title = 'K'), yaxis = dict(title = 'L'), zaxis = dict(title = 'Y')))\n    fig = go.Figure(data = data, layout = layout)\n    if filename:\n        plot(fig, filename=filename, auto_open=False, include_mathjax='cdn')\n    else:\n        iplot(fig)\n    \ndef orig_cobb_douglas():\n    L_s = np.arange(0, 10.11, 0.1)\n    K_s = np.arange(0, 10.11, 0.1)\n    A = 1\n    alpha = 0.5\n    xx, yy = np.meshgrid(K_s, L_s)\n    curr_V = cobb_douglas(A, xx, yy, alpha)\n    return curr_V\n\ndef change_A(A, filename=None):\n    L_s = np.arange(0, 10.11, 0.1)\n    K_s = np.arange(0, 10.11, 0.1)\n    alpha = 0.5\n    xx, yy = np.meshgrid(K_s, L_s)\n    curr_V = cobb_douglas(A, xx, yy, alpha)\n    plot_cobb_douglas(curr_V, orig_cobb_douglas(), fr\"A = {A}\", r\"A = 1\", filename=filename)\n    \ndef change_alpha(alpha, filename=None):\n    L_s = np.arange(0, 10.11, 0.1)\n    K_s = np.arange(0, 10.11, 0.1)\n    A = 1\n    xx, yy = np.meshgrid(K_s, L_s)\n    curr_V = cobb_douglas(A, xx, yy, alpha)\n    plot_cobb_douglas(curr_V, orig_cobb_douglas(), fr\"alpha = {alpha}\", f\"alpha = 0.5\", filename=filename)\n\ndef change_alpha_beta(alpha_beta_sum, filename=None):\n    L_s = np.arange(0, 10.11, 0.1)\n    K_s = np.arange(0, 10.11, 0.1)\n    A = 1\n    alpha = alpha_beta_sum / 2\n    beta = alpha_beta_sum / 2\n    xx, yy = np.meshgrid(K_s, L_s)\n    curr_V = cobb_douglas(A, xx, yy, alpha, beta)\n    plot_cobb_douglas(curr_V, orig_cobb_douglas(), f\"alpha + beta = {alpha_beta_sum}\", f\"alpha + beta = 1\", filename=filename)\n\ndef MPK(A, K, L, alpha):\n    return A * alpha * (K ** (alpha - 1)) * (L ** (1 - alpha))\n\ndef MPL(A, K, L, alpha):\n    return A * (1 - alpha) * (K / L) ** alpha", "meta": {"hexsha": "3e9f5d8ca1e5eb8ead4bb056a365a3b8c379554f", "size": 3461, "ext": "py", "lang": "Python", "max_stars_repo_path": "content/04-production/textbook_utils.py", "max_stars_repo_name": "d8a-88/econ-models-textbook", "max_stars_repo_head_hexsha": "b0b34afaf1f182fe6cdb8968c3045dc0692452d1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-06T17:30:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-06T17:30:11.000Z", "max_issues_repo_path": "content/04-production/textbook_utils.py", "max_issues_repo_name": "ds-connectors/econ-models-textbook", "max_issues_repo_head_hexsha": "2314ad7aac8ff621d50d2499659562bdf5f5b3fe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "content/04-production/textbook_utils.py", "max_forks_repo_name": "ds-connectors/econ-models-textbook", "max_forks_repo_head_hexsha": "2314ad7aac8ff621d50d2499659562bdf5f5b3fe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-06T17:30:12.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-06T17:30:12.000Z", "avg_line_length": 41.6987951807, "max_line_length": 152, "alphanum_fraction": 0.6194741404, "include": true, "reason": "import numpy,from sympy", "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307684643189, "lm_q2_score": 0.9059898184796792, "lm_q1q2_score": 0.8813747713324351}}
{"text": "import math\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom scipy import optimize\r\nfrom methods import *\r\nfrom pprint import pprint\r\n\r\n\r\n\r\n\r\n#-------F(x)--------------\r\ndef F(x):\r\n    n = len(x)\r\n    \r\n    piatoria = 1\r\n    exp_power = 0\r\n    \r\n    for el in x:\r\n        piatoria*= (math.cos(el))\r\n        exp_power-= (el-math.pi)**2\r\n    \r\n    return -1  *  ((-1)**n) * (piatoria) * math.exp(exp_power)   \r\n\r\n#--------For x_i <= 500 restrictions-------------\r\ndef g_i_1(x_i : float):\r\n    return x_i - 2*math.pi\r\n\r\ndef g_i_1_plus(x_i : float):\r\n    return max(0,x_i -2* math.pi)\r\n#------For x_i>= -500 restrictions---------------\r\ndef g_i_2(x_i : float):\r\n    return -x_i-2*math.pi\r\n\r\ndef g_i_2_plus(x_i : float):\r\n    return max(0,-x_i-2*math.pi)\r\n\r\n#------Q(x,c)-for penalization method----------------\r\n\r\ndef Q(c):\r\n    def Q_call(x):\r\n        f_x_eval = F(x)\r\n    \r\n        g_i_1_sum = 0\r\n        for variable in x:\r\n            g_i_1_sum +=g_i_1_plus(variable)\r\n        \r\n        g_i_2_sum = 0\r\n        for variable in x:\r\n            g_i_2_sum +=g_i_2_plus(variable)\r\n        \r\n        return f_x_eval + c * g_i_1_sum + c * g_i_2_sum\r\n    \r\n    return Q_call\r\n\r\n#------R(x,miu)- for barrier method-------------------\r\ndef R(miu):\r\n    def R_call(x):\r\n        f_x_eval = F(x)\r\n        \r\n        g_i_1_sum = 0\r\n        for variable in x:\r\n            g_i_1_sum -=1/g_i_1(variable)\r\n        \r\n        g_i_2_sum = 0\r\n        for variable in x:\r\n            g_i_2_sum -=1/g_i_2(variable)\r\n        \r\n        return f_x_eval + miu * g_i_1_sum + miu * g_i_2_sum\r\n    \r\n    return R_call\r\n\r\n#------Omega( chequear si un vector x cumple con las restricciones)-------\r\ndef omega(x):\r\n    # print(x)\r\n    for element in x:\r\n        # print(element)\r\n        if element<-2*math.pi or element>2*math.pi:\r\n            return False\r\n    return True\r\n\r\ndef Bounds(n):\r\n    return [(-2 * math.pi, 2 * math.pi) for _ in range(n)]\r\n\r\n\r\ndef plot():\r\n    x = np.arange(-2 * math.pi, 2 * math.pi, 0.1)\r\n    y = [F([i]) for i in x]\r\n\r\n    plt.plot(x, y)\r\n    plt.show()\r\n\r\n\r\n\r\n#testing-------------------\r\nif __name__ == '__main__':\r\n    # plot()\r\n    \r\n    # print(\"Penalization Method\")\r\n    # answer = Penalization_method(\"BFGS\", Q, omega, x0=np.array([2, 2]), c0=1, alpha=1.5, epsilon=0.001, k_max=500)\r\n    # pprint(answer)\r\n    # print(F(answer[\"1.Result\"]))\r\n    # print()\r\n    print(\"Barrier Method\")\r\n    answer = Barrier_method(\"BFGS\", R, x0=np.array([2,2]), miu_0=1, alpha=0.5, epsilon=0.001, k_max=500)\r\n    pprint(answer)\r\n    print(F(answer[\"1.Result\"]))\r\n    # print()\r\n    # print(\"SQP Method\")\r\n    # print(SQP_method(F, np.array([3,3]), Bounds(2), k_max=500))", "meta": {"hexsha": "b988cc91fc10c3c4f0db18dbf9344ebccbd413c3", "size": 2676, "ext": "py", "lang": "Python", "max_stars_repo_path": "LAB4/ej_6.py", "max_stars_repo_name": "codersUP/MO-Labs", "max_stars_repo_head_hexsha": "1df2639e762893a6c5c64fdeece1940b8f0b24e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LAB4/ej_6.py", "max_issues_repo_name": "codersUP/MO-Labs", "max_issues_repo_head_hexsha": "1df2639e762893a6c5c64fdeece1940b8f0b24e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LAB4/ej_6.py", "max_forks_repo_name": "codersUP/MO-Labs", "max_forks_repo_head_hexsha": "1df2639e762893a6c5c64fdeece1940b8f0b24e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5504587156, "max_line_length": 117, "alphanum_fraction": 0.5168161435, "include": true, "reason": "import numpy,from scipy", "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9833429599907709, "lm_q2_score": 0.8962513786759491, "lm_q1q2_score": 0.881322483603017}}
{"text": "# Question 05, Lab 07\n# AB Satyapraksh, 180123062\n\n# imports\nimport numpy as np\nimport pandas as pd\n\n# functions\n\n\ndef f(t, y):\n    return y - t**2 + 1\n\n\ndef F(t):\n    return (t+1)**2 - 0.5*np.exp(t)\n\n\ndef AdamsBashforth(t, y, h):\n    return y[-1] + h*(55*f(t[-1], y[-1]) - 59*f(t[-2], y[-2]) + 37*f(t[-3], y[-3]) - 9*f(t[-4], y[-4]))/24\n\n\ndef AdasmMoulton(t, y, h):\n    t1 = t[-1]+h\n    y1 = AdamsBashforth(t, y, h)\n    return y[-1] + h*(9*f(t1, y1) + 19*f(t[-1], y[-1]) - 5*f(t[-2], y[-2]) + f(t[-3], y[-3]))/24\n\n\n# program body\n# part (a)\nt, y1, h = [0], [0.5], 0.2\nfor i in range(3):\n    t.append(round(t[-1]+h, 1))\n    y1.append(F(t[-1]))\n\nwhile t[-1] < 2:\n    t.append(round(t[-1]+h, 1))\n    y1.append(AdamsBashforth(t, y1, h))\n\n# part (b)\nt, y2, h = [0], [0.5], 0.2\nfor i in range(3):\n    t.append(round(t[-1]+h, 1))\n    y2.append(F(t[-1]))\n\nwhile t[-1] < 2:\n    t.append(round(t[-1]+h, 1))\n    y2.append(AdasmMoulton(t, y2, h))\n\ny3 = []\nfor T in t:\n    y3.append(F(T))\n\n#  tabulate and print the results\ndf = pd.DataFrame()\ndf['Adams-Bashforth'] = pd.Series(y1)\ndf['Adams-Moulton'] = pd.Series(y2)\ndf['Actual Value'] = pd.Series(y3)\ndf.set_index(pd.Series(t), inplace=True)\nprint(df)\n", "meta": {"hexsha": "d9dd29482933814718a2d3ad451278b729bdb0b6", "size": 1192, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 7/Code/q5.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 7/Code/q5.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 7/Code/q5.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 19.5409836066, "max_line_length": 106, "alphanum_fraction": 0.5377516779, "include": true, "reason": "import numpy", "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545318852121, "lm_q2_score": 0.9294404013696267, "lm_q1q2_score": 0.8812531286758221}}
{"text": "import matplotlib.pyplot as plt\r\nimport matplotlib.image as mpimg\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\nimport numpy as np\r\nfrom numpy.linalg import svd\r\nimport scipy.io as sio\r\nimport itertools\r\n\r\nfrom common_functions import feature_normalize, matrix_args, matrix_args_array_only\r\nfrom ex7 import kmeans_init_centroids, run_kmeans\r\n\r\n@matrix_args\r\ndef pca(X):\r\n    m = len(X)\r\n\r\n    u, s, v = svd(X.T*X/m)\r\n\r\n    return u, s\r\n\r\n@matrix_args_array_only\r\ndef project_data(X, U, K):\r\n    return X*U[:, :K]\r\n\r\n@matrix_args_array_only\r\ndef recover_data(Z, U, K):\r\n    return (Z*(U[:, :K]).T).A\r\n\r\ndef display_data(X, title):\r\n    fig = plt.figure(figsize=(8, 8))  # figure size in inches\r\n    fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)\r\n    plt.suptitle(title, fontsize=18, color='r')\r\n\r\n    for i, x in enumerate(X):\r\n        ax = fig.add_subplot(10, 10, i + 1, xticks=[], yticks=[])\r\n        ax.imshow(x.reshape(32, 32).T, cmap=plt.cm.Greys_r, interpolation='nearest')\r\n\r\n    plt.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n    data = sio.loadmat('ex7data1.mat')\r\n    X = data['X']\r\n    x1, x2 = X.T\r\n\r\n    plt.plot(x1, x2, 'bo')\r\n    plt.show()\r\n\r\n    mu, sigma, X_norm = feature_normalize(X)\r\n\r\n    U, S = pca(X_norm)\r\n\r\n    print('Top eigenvector: ');\r\n    print(' U[:,0] = %s' % U[:, 0])\r\n    print('(you should expect to see -0.707107 -0.707107)')\r\n\r\n    K = 1\r\n    Z = project_data(X_norm, U, K)\r\n    print('Projection of the first example: %s' % Z[0])\r\n    print('(this value should be about 1.49631261)')\r\n\r\n    X_rec = recover_data(Z, U, K)\r\n    print('Approximation of the first example: %s' % X_rec[0])\r\n    print('(this value should be about  -1.05805279 -1.05805279)')\r\n\r\n    x1, x2 = X_norm.T\r\n    plt.plot(x1, x2, 'bo')\r\n    x1, x2 = X_rec.T\r\n    plt.plot(x1, x2, 'ro')\r\n    plt.axis('equal')\r\n\r\n    for x_rec, x_norm in zip(X_rec, X_norm):\r\n        plt.plot((x_rec[0], x_norm[0]), (x_rec[1], x_norm[1]), 'k-')\r\n    plt.show()\r\n\r\n    #PCA on Face Data: Eigenfaces\r\n    data = sio.loadmat('ex7faces.mat')\r\n    X = data['X']\r\n\r\n    display_data(X[:100, :], 'Faces dataset')\r\n\r\n    mu, sigma, X_norm = feature_normalize(X)\r\n\r\n    U, S = pca(X_norm)\r\n\r\n    display_data(U[:, :36].T, 'Principal components on the face dataset')\r\n\r\n    K = 100\r\n    Z = project_data(X_norm, U, K)\r\n    X_rec = recover_data(Z, U, K)\r\n\r\n    display_data(X_norm[:100, :], 'Original images of faces')\r\n    display_data(X_rec[:100, :], 'Reconstructed from only the top 100 principal components')\r\n\r\n    #PCA for Visualization\r\n    img=mpimg.imread('bird_small.png')\r\n    img_size = img.shape\r\n\r\n    X = img.reshape(img_size[0]*img_size[1], 3)\r\n\r\n    K = 16\r\n    max_iters = 10\r\n    initial_centroids = kmeans_init_centroids(X, K)\r\n    idx, centroids = run_kmeans(X, initial_centroids, max_iters)\r\n\r\n    to_plot = range(len(X))\r\n    np.random.shuffle(to_plot)\r\n    to_plot = to_plot[:1000]\r\n\r\n    X_plot = X[to_plot, :]\r\n    idx_plot = idx[to_plot]\r\n    fig = plt.figure()\r\n    ax = fig.add_subplot(111, projection='3d')\r\n    for k, color in zip(xrange(K), itertools.cycle(['r', 'b', 'g', 'k', 'm'])):\r\n\r\n        x, y, z = X_plot[idx_plot == k, :].T\r\n        ax.scatter(x, y, z, c=color)\r\n    plt.title('Pixel dataset plotted in 3D. Color shows centroid memberships')\r\n    plt.show()\r\n\r\n    mu, sigma, X_norm = feature_normalize(X)\r\n    U, S = pca(X_norm)\r\n    Z = project_data(X_norm, U, 2)\r\n\r\n    Z_plot = Z[to_plot, :]\r\n    for k, color in zip(xrange(K), itertools.cycle(['r', 'b', 'g', 'k', 'm'])):\r\n\r\n        x1, x2 = Z_plot[idx_plot == k, :].T\r\n        plt.plot(x1, x2, color+'o')\r\n    plt.title('Pixel dataset plotted in 2D, using PCA for dimensionality reduction')\r\n    plt.show()\r\n", "meta": {"hexsha": "1d52dc3f7ae6cee5a9f40fd971c9c50623a5d9fa", "size": 3716, "ext": "py", "lang": "Python", "max_stars_repo_path": "ex7/ex7_pca.py", "max_stars_repo_name": "mlyundin/Machine-Learning", "max_stars_repo_head_hexsha": "108d2c5cbfdd93b26e4045bfcf34bcad501f92dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2016-02-02T10:28:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T15:58:54.000Z", "max_issues_repo_path": "ex7/ex7_pca.py", "max_issues_repo_name": "mlyundin/Machine-Learning", "max_issues_repo_head_hexsha": "108d2c5cbfdd93b26e4045bfcf34bcad501f92dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex7/ex7_pca.py", "max_forks_repo_name": "mlyundin/Machine-Learning", "max_forks_repo_head_hexsha": "108d2c5cbfdd93b26e4045bfcf34bcad501f92dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-03-08T23:51:39.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-29T20:45:11.000Z", "avg_line_length": 27.9398496241, "max_line_length": 93, "alphanum_fraction": 0.6003767492, "include": true, "reason": "import numpy,from numpy,import scipy", "num_tokens": 1133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854146791214, "lm_q2_score": 0.9086179012632543, "lm_q1q2_score": 0.881164388161458}}
{"text": "from sympy import ( symbols, solve, diff, integrate, exp, sqrt, lambdify, pprint, Integral, simplify )\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = symbols( 'x' )\n\n# A construction company has an expenditure rate of\ndE = exp( 0.12 * x )\nE = integrate( dE, x )\n\n#  dollars per day on a particular paving job and an income rate\ndI = 120.8 - exp( 0.12 * x )\nI = integrate( dI, x )\n\n# dollars per day on the same​ job, where x is the number of days from the start of the job. \n\n# The​ company's profit on that job will equal total income less total expenditures. \n# \n# Profit will be maximized if the job ends at the optimum​ time, which is the point where the two curves meet.\n\nP = I - E\n\n# What is the graph doing?\ng_xlim = [ 1, 40 ]\n\nlam_e = lambdify( x, dE, np )\nx_vals = np.linspace( g_xlim[0], g_xlim[1], 1000, endpoint=True )\ny_vals = lam_e( x_vals )\nplt.plot( x_vals, y_vals, label = \"Expense\" )\n\nlam_i = lambdify( x, dI, np )\nx_vals = np.linspace( g_xlim[0], g_xlim[1], 1000, endpoint=True )\ny_vals = lam_i( x_vals )\nplt.plot( x_vals, y_vals, label = \"Income\" )\n\ndays = solve( dI - dE, x )[ 0 ]\n\nlam_p = lambdify( x, P, np )\nx_vals = np.linspace( g_xlim[0], g_xlim[1], 1000, endpoint=True )\ny_vals = lam_p( x_vals )\nplt.plot( x_vals, y_vals, label = \"Profit\" )\n\nplt.vlines( x = days, ymin = 0, ymax = P.subs( { x: days } ), color = 'Red', zorder = 1 )\n\nincome = round( I.subs( { x: days } ), 2 )\nexpenses = round( E.subs( { x: days } ), 2 )\nmax_profit = round( P.subs( { x: days } ), 2 )\n\ndays = round( days )\n\nplt.title( 'Max Profit at {0} days, ${1}'.format( days, max_profit ) )\nplt.show()\n\nif __name__ == '__main__':\n\tprint( 'Optimal Days: {0}'.format( days ) )\n\tprint( 'Total Income: {0}'.format( income ) )\n\tprint( 'Total Expenditures: {0}'.format( expenses ) )\n\tprint( 'Max Profit: {0}'.format( max_profit ) )", "meta": {"hexsha": "efc4b67ad3b89d070f76a14b2a60a9e76d7d6ce0", "size": 1832, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Quiz/IV/05.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Quiz/IV/05.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Quiz/IV/05.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5862068966, "max_line_length": 110, "alphanum_fraction": 0.6517467249, "include": true, "reason": "import numpy,from sympy", "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290930537122, "lm_q2_score": 0.9073122301325985, "lm_q1q2_score": 0.8811173031652114}}
{"text": "from sympy import *\n\n# The average monthly rent for a​ 1000-sq-ft apartment in a major metropolitan area from \n# 1998 through 2005 can be approximated by the function below where t is the time in years since \n# the beginning of 1998. Find the value of t when rents were increasing most rapidly. \n# Approximately when did this​ occur?\n\nt = symbols( 't', positive = True ) # 0 <= x\nC = 1.6434 * t**4 - 21.052 * t**3 + 62.98 * t**2 + 6.1157 * t + 1005\n\n# The rents were increasing most rapidly when \ndC = diff( C, t, 1 )\nddC = diff( dC, t, 1 )\n\ncritical_values = solve( ddC )\n\ncv_1 = dC.subs( { t : critical_values[ 0 ] } )\ncv_2 = dC.subs( { t : critical_values[ 1 ] } )\n\nif cv_1 > cv_2:\n\tcv = critical_values[ 0 ]\n\tprint( 'Critical Value {0} is higher [ {1} ]'.format( round( cv, 3 ), cv_1 ) )\nelse:\n\tcv = critical_values[ 1 ]\n\tprint( 'Critical Value {0} is higher [ {1} ]'.format( round( cv, 3 ), cv_2 ) )\n\nprint( 'Year: {0}'.format( round( 1998 + cv ) ) )", "meta": {"hexsha": "5aa57f1cdfaab51371f6e28e8e5edffd2784380f", "size": 955, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Quiz/III/13.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Quiz/III/13.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Quiz/III/13.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3703703704, "max_line_length": 97, "alphanum_fraction": 0.6439790576, "include": true, "reason": "from sympy", "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846672373524, "lm_q2_score": 0.9005297821135385, "lm_q1q2_score": 0.8810645312104799}}
{"text": "# Adding vectors using Python\nimport numpy as np   \n\nvector1 = np.array([[10],[3],[21]])\nvector2 = np.array([[3],[2],[4]])\n\noutput = vector1 + vector2\nprint(output)\n\n\"\"\"\n\ngives a result:\n\n[[13]\n [ 5]\n [25]]\n\nwhich is the component-wise sum of the elements of each vector\n\n\"\"\"", "meta": {"hexsha": "bca7b6fa5238b41a70f3bd8429964a5df7c79264", "size": 275, "ext": "py", "lang": "Python", "max_stars_repo_path": "VectorMaths/VectorAddition.py", "max_stars_repo_name": "MikeDurrant/DSMWP", "max_stars_repo_head_hexsha": "41a74121b7b17d88f4365ec330eeed3ce4e921f9", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VectorMaths/VectorAddition.py", "max_issues_repo_name": "MikeDurrant/DSMWP", "max_issues_repo_head_hexsha": "41a74121b7b17d88f4365ec330eeed3ce4e921f9", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VectorMaths/VectorAddition.py", "max_forks_repo_name": "MikeDurrant/DSMWP", "max_forks_repo_head_hexsha": "41a74121b7b17d88f4365ec330eeed3ce4e921f9", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.75, "max_line_length": 62, "alphanum_fraction": 0.6327272727, "include": true, "reason": "import numpy", "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9669140206578809, "lm_q2_score": 0.9111797112177908, "lm_q1q2_score": 0.8810324381154809}}
{"text": "import numpy as np\n\n\ndef mse(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n    \"\"\"\n    Mean squared error\n\n    Args:\n        y_true (np.ndarray): ground-truth values\n        y_pred (np.ndarray): y_predicted values\n    Returns:\n        float: metric value\n\n    \"\"\"\n    result = np.mean((y_true - y_pred) ** 2)\n\n    return result\n\n\ndef rmse(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n    \"\"\"\n    Root mean squared error\n\n    Args:\n        y_true (np.ndarray): ground-truth values\n        y_pred (np.ndarray): y_predicted values\n    Returns:\n        float: metric value\n\n    \"\"\"\n    result = np.sqrt(np.mean((y_true - y_pred) ** 2))\n\n    return result\n\n\ndef r2(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n    \"\"\"\n    Coefficient of determination\n\n    Args:\n        y_true (np.ndarray): ground-truth values\n        y_pred (np.ndarray): y_predicted values\n    Returns:\n        float: metric value\n\n    \"\"\"\n    result = 1 - np.sum((y_true - y_pred) ** 2) / np.sum((y_true - np.mean(y_true)) ** 2) # noqa\n\n    return result\n", "meta": {"hexsha": "076d29a3248b6f10f5547032ff4853ff3ada0fe7", "size": 1034, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/metrics/regression.py", "max_stars_repo_name": "dankiy/mm-ml-2021", "max_stars_repo_head_hexsha": "cd49a1be79d4cbdbb3a7b207162d15fc850f34fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/metrics/regression.py", "max_issues_repo_name": "dankiy/mm-ml-2021", "max_issues_repo_head_hexsha": "cd49a1be79d4cbdbb3a7b207162d15fc850f34fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/metrics/regression.py", "max_forks_repo_name": "dankiy/mm-ml-2021", "max_forks_repo_head_hexsha": "cd49a1be79d4cbdbb3a7b207162d15fc850f34fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.68, "max_line_length": 96, "alphanum_fraction": 0.5976789168, "include": true, "reason": "import numpy", "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147153749275, "lm_q2_score": 0.9059898286330041, "lm_q1q2_score": 0.8809978413427421}}
{"text": "#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n# Python 3.7\n\n#\n# @Author: Jxtopher\n# @License: CC-BY-NC-SA\n# @Date: 2019-04\n# @Version: 1\n# @Purpose: approximation de pi par la méthode de Monte-Carlo\n#           see https://fr.wikipedia.org/wiki/Méthode_de_Monte-Carlo#Détermination_de_la_valeur_de_π\n#\n\nimport numpy as np\n\nfrom itertools import cycle\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nlines = [\"-\"]#,\"--\",\"-.\",\":\"]\nmarkers = [\"o\", \"v\", \"^\", \"^\", \">\", \"1\", \"2\", \"3\", \"4\", \"8\", \"s\", \"p\", \"*\", \"h\", \"H\", \"+\", \"<\", \"D\"]\ncolors = [\"black\", \"blue\", \"green\", \"red\", \"brown\", \"magenta\", \"silver\", \"pink\"]\nlinecycler = cycle(lines)\nmarkercycler = cycle(markers)\ncolorcycler = cycle(colors)\n\n\ndef approximationPI():\n    result_x = []\n    result_y = []\n\n    inTheCircle = 0\n    outsideTheCircle = 0\n    step = 0\n    while (step < 5010):\n\n        if (np.sqrt(pow(np.random.uniform(), 2) + pow(np.random.uniform(), 2))  <= 1):\n            inTheCircle += 1\n        else:\n            outsideTheCircle += 1\n\n        x = inTheCircle / float(inTheCircle + outsideTheCircle)\n        step +=1\n        result_x += [step]\n        result_y += [x*4]\n    return result_x, result_y\n\nif __name__ == '__main__':\n    x, y = approximationPI()\n\n    plt.plot(x,\n            [3.141592653589793]*len(x), \n            linestyle=next(linecycler), \n            marker=None, \n            label=ur\"π\", \n            linewidth=1, \n            markersize=2, \n            markeredgewidth=1,\n            color=next(colorcycler))\n\n    plt.plot(x,\n            y, \n            linestyle=next(linecycler), \n            marker=None,#next(markercycler), \n            label=ur\"Approximation of π\", \n            linewidth=1, \n            markersize=2, \n            markeredgewidth=1,\n            color=next(colorcycler))\n\n\n\n    size = 10\n    plt.xticks(np.arange(0, np.max(x), step=500))\n    plt.grid(True)\n    plt.ylabel(\"Value\", fontsize=size)\n    plt.xlabel(\"Steps\", fontsize=size)\n    plt.legend(loc=4, bbox_to_anchor=(1, 0.2),prop={'size':size}, fancybox=False) #(loc='upper center', ncol=3, fancybox=True)\n    plt.savefig(\"approximation-of-PI.pdf\", bbox_inches='tight')\n    plt.savefig(\"approximation-of-PI.svg\", bbox_inches='tight')\n", "meta": {"hexsha": "4fbdfbe33ed3c6e7ad5717c01e1deb71b7679bfb", "size": 2226, "ext": "py", "lang": "Python", "max_stars_repo_path": "Approximation of PI/approximation-de-pi.py", "max_stars_repo_name": "Jxtopher/Results", "max_stars_repo_head_hexsha": "8e86c47dae4d68e8e881a80148b4d384bc1e0ecc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Approximation of PI/approximation-de-pi.py", "max_issues_repo_name": "Jxtopher/Results", "max_issues_repo_head_hexsha": "8e86c47dae4d68e8e881a80148b4d384bc1e0ecc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Approximation of PI/approximation-de-pi.py", "max_forks_repo_name": "Jxtopher/Results", "max_forks_repo_head_hexsha": "8e86c47dae4d68e8e881a80148b4d384bc1e0ecc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1463414634, "max_line_length": 126, "alphanum_fraction": 0.5705300988, "include": true, "reason": "import numpy", "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154282922475, "lm_q2_score": 0.9184802512774205, "lm_q1q2_score": 0.8809642667924489}}
{"text": "import math\nimport matplotlib\nimport numpy as np\n\ndef dist(x1, y1, x2, y2):\n    return math.sqrt((x2-x1)**2 + (y2-y1)**2)\n\ndef intersect(x1, y1, x2, y2, x3, y3, x4, y4):\n    # unchecked implementation that appears to work\n    # I can implement my own using the cross product vector based approach\n    # where p * tr = q * us\n    def ccw(x1, y1, x2, y2, x3, y3):\n        return (y3-y1) * (x2-x1) > (y2-y1) * (x3-x1)\n    return (ccw(x1,y1, x3,y3, x4,y4) != ccw(x2,y2, x3,y3, x4,y4) and\n           ccw(x1,y1, x2,y2, x3,y3) != ccw(x1,y1, x2,y2, x4,y4))\n\ndef my_intersect(x1, y1, x2, y2, x3, y3, x4, y4):\n    # based on https://stackoverflow.com/a/565282\n    p = (x1, y1)\n    r = (x2-x1, y2-y1)\n    q = (x3, y3)\n    s = (x4-x3, y4-y3)\n    def calc(q, p, s, r):\n        t = (q[0]-p[0], q[1]-p[1])\n        t = (t[0]*s[1]) - (t[1]*s[0])\n        t /= (r[0]*s[1]) - (r[1]*s[0])\n        return t\n    rs = (r[0]*s[1]) - (r[1]*s[0])\n    if rs == 0:\n        return False\n    t = calc(q,p,s,r)\n    u = calc(p,q,r,s)\n    # print(\"t: {}\".format(p[0]+ r[0]*t, p[1]+r[1]*t))\n    # print(\"u: {}\".format(q[0]+ s[0]*u, q[1]+s[1]*u))\n    if t >= 0 and t <= 1 and u >= 0 and u <= 1:\n        return (p[0]+ r[0]*t, p[1]+r[1]*t)\n\ndef has_intersection(polygon1, polygon2):\n    # Check if there is any intersection between pairs of edges of polygons\n    for i in range(len(polygon1)-1):\n        x1, y1 = polygon1[i]\n        x2, y2 = polygon1[i+1]\n        for j in range(len(polygon2)-1):\n            x3, y3 = polygon2[j]\n            x4, y4 = polygon2[j+1]\n            if intersect(x1, y1, x2, y2, x3, y3, x4, y4):\n                return True\n    return False\n\ndef point_inside_polygon(x, y, polygon):\n    # source: https://stackoverflow.com/a/23453678\n    test_polygon = [point for point in polygon]\n    bb_path = matplotlib.path.Path(np.array(test_polygon))\n    return bb_path.contains_point((x, y))\n\ndef is_inside(polygon1, polygon2):\n    #print(\"Checking if poylgon1: \\n {}\".format(polygon1))\n    #print(\"is inside polygon2: \\n {}\".format(polygon2))\n    if has_intersection(polygon1, polygon2):\n        return False\n\n    # If no intersection is found, we just need to check that\n    # at least 1 point of pol1 is within pol2\n    for x, y in polygon1:\n        if point_inside_polygon(x, y, polygon2):\n            return True\n\n    return False\n\ndef get_boundingbox(polygon):\n    x, y = polygon[0]\n    min_x, min_y, max_x, max_y = x, y, x, y\n    for x, y in polygon:\n        min_x = x if x < min_x else min_x\n        min_y = y if y < min_y else min_y\n        max_x = x if x > max_x else max_x\n        max_y = y if y > max_y else max_y\n    return min_x, min_y, max_x, max_y\n\ndef get_parallel_points(x1, y1, x2, y2, u, v, d):\n    return x1 + d*u, y1 + d*v, x2 + d*u, y2 + d*v\n\ndef get_unit_vector(a, b):\n    import math\n    l = 1 / math.sqrt(a**2 + b**2)\n    u = l * a\n    v = l * b\n    return u, v\n\ndef get_line_equation(x1, y1, x2, y2):\n    a = y1 - y2\n    b = x2 - x1\n    c = (-(y1 - y2))*x1 + (x1 - x2)*y1\n    return a, b, c\n\ndef get_pont_in_line(x1,y1,x2,y2,dist):\n    d = math.sqrt((x2-x1)**2 + (y2-y1)**2)\n    x3 = (dist*(x2-x1))/d + x1\n    y3 = (dist*(y2-y1))/d + y1\n    return x3, y3\n\ndef extend_line(x1,y1,x2,y2,ext=0.1):\n    len_p1_p2 = dist(x1,y1,x2,y2)\n    x3 = x2 + (x2 - x1) / len_p1_p2 * (ext*len_p1_p2)\n    y3 = y2 + (y2 - y1) / len_p1_p2 * (ext*len_p1_p2)\n    return x3, y3\n\ndef get_angle(lat1, long1, lat2, long2):\n    import math\n    dLon = (long2 - long1)\n\n    y = math.sin(dLon) * math.cos(lat2)\n    x = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(dLon)\n\n    brng = math.atan2(y, x)\n\n    brng = math.degrees(brng)\n    brng = (brng + 360) % 360\n    brng = 360 - brng # count degrees clockwise - remove to make counter-clockwise\n\n    return brng\n\n# playing and understanding the code\ndef line_manipulation_demo():\n\n    # points in a line\n    x1, y1 = 4, 5\n    x2, y2 = 7, 9\n    print(x1, y1, x2, y2)\n\n    # a, b, c terms that define the line\n    a, b, c = get_line_equation(x1, y1, x2, y2)\n    print(a, b, c)\n\n    # unit vector of a perpendicular vector to the line given by a, b\n    u, v = get_unit_vector(a, b)\n    print(u, v)\n\n    # calculate p3 and p4 given a multiple of the perpendicular unit vector\n    d = 5\n    x3, y3, x4, y4 = get_parallel_points(x1, y1, x2, y2, u, v, d)\n    print(x3, y3, x4, y4)\n\n    d = 1\n    x3, y3, x4, y4 = get_parallel_points(x1, y1, x2, y2, u, v, d)\n    print(x3, y3, x4, y4)\n", "meta": {"hexsha": "0ad30084626d189ac1a29e809f6a76a6b7b903e9", "size": 4433, "ext": "py", "lang": "Python", "max_stars_repo_path": "generator/lib/trigonometry.py", "max_stars_repo_name": "ehauckdo/map_generation", "max_stars_repo_head_hexsha": "df370c8bec2ac2b58fdb89ca4afec99e6dd96e56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "generator/lib/trigonometry.py", "max_issues_repo_name": "ehauckdo/map_generation", "max_issues_repo_head_hexsha": "df370c8bec2ac2b58fdb89ca4afec99e6dd96e56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generator/lib/trigonometry.py", "max_forks_repo_name": "ehauckdo/map_generation", "max_forks_repo_head_hexsha": "df370c8bec2ac2b58fdb89ca4afec99e6dd96e56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.156462585, "max_line_length": 90, "alphanum_fraction": 0.5648545003, "include": true, "reason": "import numpy", "num_tokens": 1728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.9184802395624257, "lm_q1q2_score": 0.8809642598455425}}
{"text": "#!/usr/bin/env python3\nimport sys\nimport numpy as np\n\ndef inside_circle(total_count):\n\n    x = np.random.uniform(size=total_count)\n    y = np.random.uniform(size=total_count)\n\n    radii_square = x**2 + y**2\n\n    count = (radii_square<=1.0).sum()\n\n    return count\n\ndef estimate_pi(n_samples):\n\n    return (4.0 * inside_circle(n_samples) / n_samples)\n\nif __name__=='__main__':\n\n    n_samples = 10000\n    if len(sys.argv) > 1:\n        n_samples = int(sys.argv[1])\n\n    my_pi = estimate_pi(n_samples)\n    sizeof = np.dtype(np.float64).itemsize\n\n    print(\"required memory {:.3f} MB\".format(n_samples*sizeof*3/(1024*1024)))\n    print(\"pi is {} from {} samples\".format(my_pi,n_samples))\n    print(\"error is {:.3e}\".format(abs(my_pi - np.pi)))\n", "meta": {"hexsha": "506ec5e76e626dd430d539029c8add3631aee214", "size": 738, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_hpc/2_digits_of_pi/1_serial_digits_of_pi.py", "max_stars_repo_name": "sdsc-scicomp/2018-11-02-comet-workshop-ucr", "max_stars_repo_head_hexsha": "0189387422135db9e32ff5dfd42c333f4c258962", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-11-08T17:16:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-02T16:48:45.000Z", "max_issues_repo_path": "python_hpc/2_digits_of_pi/1_serial_digits_of_pi.py", "max_issues_repo_name": "sdsc-scicomp/2019-11-08-comet-workshop-ucla", "max_issues_repo_head_hexsha": "c35ac2e8c7f38e20e4aaba2cc67b0bc4651b5912", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python_hpc/2_digits_of_pi/1_serial_digits_of_pi.py", "max_forks_repo_name": "sdsc-scicomp/2019-11-08-comet-workshop-ucla", "max_forks_repo_head_hexsha": "c35ac2e8c7f38e20e4aaba2cc67b0bc4651b5912", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-02T12:15:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-02T12:15:09.000Z", "avg_line_length": 23.0625, "max_line_length": 77, "alphanum_fraction": 0.6571815718, "include": true, "reason": "import numpy", "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122732859021, "lm_q2_score": 0.9196425388861785, "lm_q1q2_score": 0.8809368750348779}}
{"text": "import numpy as np\r\nfrom math import *\r\n\r\n# Global variables\r\nNMAX = 100\r\nTOLERANCE = 0.00001\r\nOP = 1\r\n\r\n\r\ndef fe(a, b, op, f):\r\n    if op == 1:\r\n        return abs(f(a))\r\n    elif op == 2:\r\n        return abs(b - a)\r\n\r\n    elif op == 3:\r\n        return abs(b - a) / b\r\n\r\n\r\ndef bisection(lower_end, upper_end,  test, f):\r\n    a = lower_end\r\n    b = upper_end\r\n    niter = 0\r\n    m = lower_end + (upper_end - lower_end) / 2\r\n\r\n    fa = f(lower_end)\r\n    fb = f(upper_end)\r\n    fm = f(m)\r\n    ERROR = 100\r\n    if not test:\r\n        print(\"# iter\\t\\t a \\t\\t f(a) \\t\\t b \\t\\t f(b) \\t\\t m \\t\\t f(m)  \\t\\t ERROR\")\r\n        print(\r\n            \"{0} \\t\\t {1:6.4f} \\t {2:6.4f} \\t {3:6.4f} \\t {4:6.4f} \\t {5:6.4f} \\t {6:6.4f} \\t {7:6.9f}\".format(\r\n                niter, lower_end, fa, upper_end, fb, m, fm, ERROR\r\n            )\r\n        )\r\n\r\n    while ERROR > TOLERANCE and niter < NMAX:\r\n        m = lower_end + (upper_end - lower_end) / 2\r\n        if np.sign(fa) == np.sign(fm):\r\n            lower_end = m\r\n            fa = f(lower_end)\r\n        else:\r\n            upper_end = m\r\n            fb = f(upper_end)\r\n        m = lower_end + (upper_end - lower_end) / 2\r\n        fm = f(m)\r\n        ERROR = fe(lower_end, upper_end, OP, f)\r\n\r\n        niter += 1\r\n        if not test:\r\n            print(\r\n                \"{0} \\t\\t {1:6.4f} \\t {2:6.4f} \\t {3:6.4f} \\t {4:6.4f} \\t {5:6.4f} \\t {6:6.4f} \\t {7:6.9f}\".format(\r\n                    niter, lower_end, fa, upper_end, fb, m, fm, ERROR\r\n                )\r\n            )\r\n    if not test:\r\n        print(\r\n            \"The root of the function between [{0:6.4f}, {1:6.4f}] is: {2:6.4f}\".format(\r\n                a, b, m\r\n            )\r\n        )\r\n        print(\"The estimated ERROR is: {0:6.8f}\".format(ERROR))\r\n    else:\r\n        return m\r\n\r\n\r\ndef f_test_1(x):\r\n    return (3 * x**3) - (2 * x) - 5\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    lower_end = 0\r\n    upper_end = 2\r\n    bisection(lower_end, upper_end, False, f_test_1)\r\n\r\n\r\n# Tests\r\ndef test_1():\r\n    lower_end = 0\r\n    upper_end = 2\r\n    assert bisection(lower_end, upper_end,\r\n                     True, f_test_1) == 1.3717398643493652\r\n", "meta": {"hexsha": "8e3c40e93b7a00d8d1faa0f3922333d6f26d8439", "size": 2133, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/bisection.py", "max_stars_repo_name": "Youngermaster/ST0256-Numerical-Analysis", "max_stars_repo_head_hexsha": "cc8e53f0df9cceec88b2e0d52a6e534cc25295ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-16T01:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T01:50:36.000Z", "max_issues_repo_path": "Python/bisection.py", "max_issues_repo_name": "Youngermaster/ST0256-Numerical-Analysis", "max_issues_repo_head_hexsha": "cc8e53f0df9cceec88b2e0d52a6e534cc25295ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/bisection.py", "max_forks_repo_name": "Youngermaster/ST0256-Numerical-Analysis", "max_forks_repo_head_hexsha": "cc8e53f0df9cceec88b2e0d52a6e534cc25295ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3928571429, "max_line_length": 116, "alphanum_fraction": 0.4613220816, "include": true, "reason": "import numpy", "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362486, "lm_q2_score": 0.9390248178552368, "lm_q1q2_score": 0.8809217348804038}}
{"text": "# Practicing Dynamic Programming (DP) with the log cutting problem given on the practice midterm.\r\n# this file contains the solution from the given exam solutions.\r\nimport numpy as np\r\n\r\n\r\n################################################################################\r\n# Top Down Algorithm (Solution)\r\n################################################################################\r\n\r\n\r\ndef top_down_woody(d):\r\n    i = 0\r\n    j = len(d) - 1\r\n    c = np.ones([j+1, j+1])*np.inf\r\n    return top_down_woody_aux(i, j, d, c)\r\n\r\n\r\ndef top_down_woody_aux(i, j, d, c):\r\n    if j == i+1:\r\n        return 0\r\n    if c[i, j] == np.inf:\r\n        for k in range(i+1, j):\r\n            c[i, j] = min(c[i, j], d[j] - d[i] + top_down_woody_aux(i, k, d, c) + top_down_woody_aux(k, j, d, c))\r\n    return c[i, j]\r\n\r\n\r\n################################################################################\r\n# Bottom Up Algorithm (solution)\r\n################################################################################\r\n\r\n\r\ndef bottom_up_woody(d):\r\n    n = len(d) - 2\r\n    c = np.zeros([n+2, n+2])\r\n    for m in range(2, n+2):\r\n        for i in range(0, n-m+2):\r\n            j = i + m\r\n            c[i, j] = np.inf\r\n            for k in range(i+1, j+1):\r\n                c[i, j] = min(c[i, j], d[j] - d[i] + c[i, k] + c[k, j])\r\n    return c[0, n+1]\r\n\r\n\r\n################################################################################\r\n# Main\r\n################################################################################\r\nif __name__ == '__main__':\r\n    dist = np.array([0, 3, 8, 10])\r\n    print(\"min cost (top down sol) = $\" + str(top_down_woody(dist)))\r\n    print(\"min cost (bottom up sol) = $\" + str(bottom_up_woody(dist)))\r\n", "meta": {"hexsha": "addac23c30f4e32e51a527b8411ba36f212d9108", "size": 1710, "ext": "py", "lang": "Python", "max_stars_repo_path": "DP/LogCutting/LogCuttingSolution.py", "max_stars_repo_name": "nalyd88/Algorithms", "max_stars_repo_head_hexsha": "63ec18288b3e89f3b96bcbed70080cf33f9a115d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DP/LogCutting/LogCuttingSolution.py", "max_issues_repo_name": "nalyd88/Algorithms", "max_issues_repo_head_hexsha": "63ec18288b3e89f3b96bcbed70080cf33f9a115d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DP/LogCutting/LogCuttingSolution.py", "max_forks_repo_name": "nalyd88/Algorithms", "max_forks_repo_head_hexsha": "63ec18288b3e89f3b96bcbed70080cf33f9a115d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5294117647, "max_line_length": 114, "alphanum_fraction": 0.3736842105, "include": true, "reason": "import numpy", "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338035725358, "lm_q2_score": 0.9161096135894201, "lm_q1q2_score": 0.8808703612440012}}
{"text": "import math\n\nimport numpy as np\n\nfrom typing import Tuple, Callable, Union\n\nINV_PHI = (math.sqrt(5) - 1) / 2\nINV_PHI_SQUARED = (3 - math.sqrt(5)) / 2\n\n\ndef golden_section_search(func: Callable, low: float, up: float, tolerance: float = 1e-5,\n                          return_mean: bool = True) -> Union[Tuple[float, float], float]:\n    \"\"\"Golden Section Search Algorithm - Taken directly from Wikipedia.\n\n    Given a function f with a single local minimum in\n    the interval [a,b], gss returns a subset interval\n    [c,d] that contains the minimum with d-c <= tol.\n\n    This implementation\n    reuses function evaluations, saving 1/2 of the evaluations per\n    iteration, and returns a bounding interval if return_mean=False, else it takes the mean of the\n    upper and lower bound of the interval.\n\n    Example:\n        f = lambda x: (x-2)**2\n        a = 1\n        b = 5\n        tol = 1e-5\n        (c,d) = golden_section_search(f, a, b, tol)\n        print(c, d)\n        1.9999959837979107 2.0000050911830893\n    \"\"\"\n    (low, up) = (min(low, up), max(low, up))\n    h = up - low\n    if h <= tolerance:\n        if return_mean:\n            return float(np.mean([low, up]))\n        else:\n            return low, up\n\n    # Required steps to achieve tolerance\n    n = int(math.ceil(math.log(tolerance / h) / math.log(INV_PHI)))\n\n    c = low + INV_PHI_SQUARED * h\n    d = low + INV_PHI * h\n    yc = func(c)\n    yd = func(d)\n\n    for k in range(n - 1):\n        if yc < yd:\n            up = d\n            d = c\n            yd = yc\n            h = INV_PHI * h\n            c = low + INV_PHI_SQUARED * h\n            yc = func(c)\n        else:\n            low = c\n            c = d\n            yc = yd\n            h = INV_PHI * h\n            d = low + INV_PHI * h\n            yd = func(d)\n\n    if yc < yd:\n        if return_mean:\n            return float(np.mean([low, d]))\n        else:\n            return low, d\n    else:\n        if return_mean:\n            return float(np.mean([c, up]))\n        else:\n            return c, up\n", "meta": {"hexsha": "cb472e56e4f1a6ccc9853615e4c0cc9de40fc49f", "size": 2019, "ext": "py", "lang": "Python", "max_stars_repo_path": "uncertify/algorithms/golden_section_search.py", "max_stars_repo_name": "matthaeusheer/uncertify", "max_stars_repo_head_hexsha": "dfc2df16fb07ee8d7d17906827e0f0c8b2747532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-09T00:06:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T00:06:55.000Z", "max_issues_repo_path": "uncertify/algorithms/golden_section_search.py", "max_issues_repo_name": "matthaeusheer/uncertify", "max_issues_repo_head_hexsha": "dfc2df16fb07ee8d7d17906827e0f0c8b2747532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-29T21:55:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-29T21:55:32.000Z", "max_forks_repo_path": "uncertify/algorithms/golden_section_search.py", "max_forks_repo_name": "matthaeusheer/uncertify", "max_forks_repo_head_hexsha": "dfc2df16fb07ee8d7d17906827e0f0c8b2747532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.92, "max_line_length": 98, "alphanum_fraction": 0.5324418029, "include": true, "reason": "import numpy", "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885302, "lm_q2_score": 0.9161096050004511, "lm_q1q2_score": 0.8808703600541138}}
{"text": "\"\"\"\n9.4-2. The Wirehouse Lumber Company will soon begin logging eight groves of trees in the same general area. Therefore,\nit must develop a system of dirt roads that makes each grove accessible from every other grove. The distance (in\nmiles) between every pair of groves is as follows:\n\n                grove_1   grove_2     grove_3     grove_4     grove_5     grove_6     grove_7     grove_8\n    grove_1     --        1.3         2.1         0.9         0.7         1.8         2.0         1.5\n    grove_2     1.3       --          0.9         1.8         1.2         2.6         2.3         1.1\n    grove_3     2.1       0.9         --          2.6         1.7         2.5         1.9         1.0\n    grove_4     0.9       1.8         2.6         --          0.7         1.6         1.5         0.9\n    grove_5     0.7       1.2         1.7         0.7         --          0.9         1.1         0.8\n    grove_6     1.8       2.6         2.5         1.6         0.9         --          0.6         1.0\n    grove_7     2.0       2.3         1.9         1.5         1.1         0.6         --          0.5\n    grove_8     1.5       1.1         1.0         0.9         0.8         1.0         0.5         --\n\nManagement now wishes to determine between which pairs of groves the roads should be constructed to connect all\ngroves with a minimum total length of road.<br>\n\n(a) Describe how this problem fits the network description of the minimum spanning tree problem.\n(b) Use the algorithm described in Sec. 9.4 to solve the problem.\n\nCopyright @author: S. Lei\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport networkx as nx\nfrom helper_functions.util import export_soln_to_csv\nfrom networkx.algorithms import tree\n\n\n# model name\nm = '9.4-2_v2'\n\n# read in data\ndf = pd.read_csv('data_arc.csv')\ndf = df[df['distance'] != 0]\n\n# create a Graph object\narcs = list((t[1], t[2]) for t in df.itertuples())\ndistance_dict = dict([((t[1], t[2]), t.distance) for t in df.itertuples()])\n\nG = nx.Graph()\n\nfor x in arcs:\n    i = x[0]\n    j = x[1]\n    weight = distance_dict[i,j]\n    G.add_edge(i,j,weight = weight)\n\n# solve for MSP\nmst = tree.minimum_spanning_edges(G, algorithm='prim', data=False)\nedges = list(mst)\nedges\n\n# print results\ndistance_lst = []\nfor x in edges:\n    i = x[0]\n    j = x[1]\n    weight = distance_dict[i,j]\n    distance_lst.append(weight)\ntotal_distance = sum(distance_lst)\nprint(total_distance)\nprint(edges)\n\npos = nx.spring_layout(G)\nnx.draw_networkx_nodes(G, pos, node_size=400)\nnx.draw_networkx_edges(G, pos, edgelist=edges, width=1)\nnx.draw_networkx_labels(G, pos, font_size=15, font_family='sans-serif')\n\nplt.axis('off')\nplt.show()\n\n# export solution to csv\nnode_1 = [i[0] for i in edges]\nnode_2 = [i[1] for i in edges]\n\noutput_df = pd.DataFrame(\n    {'node_1': node_1,\n     'node_2': node_2,\n     'distance': distance_lst\n     })\n\nexport_soln_to_csv(output_df, m)\n", "meta": {"hexsha": "a359574534d06e04cbca312953297169f0e7416a", "size": 2897, "ext": "py", "lang": "Python", "max_stars_repo_path": "9.4 (The Minimum Spanning Tree Problem)/prob_2/mod_v2.py", "max_stars_repo_name": "shellei503/introduction-to-operations-research-7th-ed", "max_stars_repo_head_hexsha": "4ba4003a637a6a8694d2101b11159d4cbbc5d517", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-16T14:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T14:11:23.000Z", "max_issues_repo_path": "9.4 (The Minimum Spanning Tree Problem)/prob_2/mod_v2.py", "max_issues_repo_name": "shellei503/Linear-Programming-Examples", "max_issues_repo_head_hexsha": "4ba4003a637a6a8694d2101b11159d4cbbc5d517", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "9.4 (The Minimum Spanning Tree Problem)/prob_2/mod_v2.py", "max_forks_repo_name": "shellei503/Linear-Programming-Examples", "max_forks_repo_head_hexsha": "4ba4003a637a6a8694d2101b11159d4cbbc5d517", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6860465116, "max_line_length": 118, "alphanum_fraction": 0.5674836037, "include": true, "reason": "import networkx,from networkx", "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.9362850026367633, "lm_q1q2_score": 0.8808473344196808}}
{"text": "from numba import jit\nimport numpy as np\nimport math\nimport time\n\n@jit('f4[:,:](i2,f4[:,:])')\ndef ra_numba(doy, lat):\n    \n    M, N = lat.shape\n    \n    ra = np.zeros_like(lat)\n    Gsc = 0.0820\n    \n    # math.pi doesnt work?\n    # NumbaError: 11:31: Binary operations mul on values typed object_ and object_ not (yet) supported)\n    pi = math.pi\n    #pi = 3.1415926535897932384626433832795\n\n    dr = 1 + 0.033 * math.cos( 2 * pi / 365 * doy)\n    decl = 0.409 * math.sin( 2 * pi / 365 * doy - 1.39 )\n    \n    for i in range(M):\n        for j in range(N):\n            \n            # it crashes without the float() wrapped around the array slicing?!\n            ws = math.acos(-1 * math.tan(float(lat[i,j])) * math.tan(decl))\n            ra[i,j] = 24 * 60 / pi * Gsc * dr * ( ws * math.sin(float(lat[i,j])) * math.sin(decl) + math.cos(float(lat[i,j])) * math.cos(decl) * math.sin(ws)) * 11.6\n\n    \n    return ra\n\n\ndef ra_numpy(doy, lat):\n\n    Gsc = 0.0820\n    \n    pi = math.pi\n    \n    dr = 1 + 0.033 * np.cos( 2 * pi / 365 * doy)\n    decl = 0.409 * np.sin( 2 * pi / 365 * doy - 1.39 )\n    ws = np.arccos(-np.tan(lat) * np.tan(decl))\n    \n    ra = 24 * 60 / pi * Gsc * dr * ( ws * np.sin(lat) * np.sin(decl) + np.cos(lat) * np.cos(decl) * np.sin(ws)) * 11.6\n    \n    return ra\n\nra_python = ra_numba.py_func\n\ndoy = 120 # day of year\n\npy = []\nnump = []\nnumb = []\ndims = []\n\nfor dim in [25,50,100,200,400,800,1600]:\n    \n    dims.append(dim)\n    \n    lat = np.deg2rad(np.ones((dim,dim), dtype=np.float32) * 45.) # array of 45 degrees latitude converted to rad\n    \n    tic = time.clock()\n    ra_nb = ra_numba(doy, lat)\n    numb.append(time.clock() - tic)\n\n    tic = time.clock()\n    ra_np = ra_numpy(doy, lat)\n    nump.append(time.clock() - tic)\n    \n    tic = time.clock()\n    ra_py = ra_python(doy, lat)\n    py.append(time.clock() - tic)\n    \ndims = np.array(dims)**2\npy = np.array(py)\nnumb = np.array(numb)\nnump = np.array(nump)\n", "meta": {"hexsha": "e3759f967cd9668780853e83cea8f53c549e19b3", "size": 1928, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/ra24.py", "max_stars_repo_name": "meawoppl/numba", "max_stars_repo_head_hexsha": "bb8df0aee99133c6d52465ae9f9df2a7996339f3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-01-29T06:52:36.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-29T06:52:36.000Z", "max_issues_repo_path": "examples/ra24.py", "max_issues_repo_name": "meawoppl/numba", "max_issues_repo_head_hexsha": "bb8df0aee99133c6d52465ae9f9df2a7996339f3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ra24.py", "max_forks_repo_name": "meawoppl/numba", "max_forks_repo_head_hexsha": "bb8df0aee99133c6d52465ae9f9df2a7996339f3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7179487179, "max_line_length": 165, "alphanum_fraction": 0.5539419087, "include": true, "reason": "import numpy,from numba", "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446456243805, "lm_q2_score": 0.9046505370289059, "lm_q1q2_score": 0.8808081515394145}}
{"text": "\nimport numpy as np\n\n#training set\n#x: {n features, m samples as n*m array}\n#x =  np.array([ […] ... ])\n#for e.g., a 3 * 4 array for 3 fearures, 4 samples\n\nx = np.array( [ [1,2,4,5], \n                [3,4,1,3],\n                [4,5,3,5] ])\n\n#calculate u (mean) and var (variance)\nu = np.mean(x,axis=1,keepdims=True)\nvar = np.mean((x - u)**2, axis=1, keepdims=True)\n\n#gaussian probability (vectorised implementation)\n# x {n features, m samples as n*m array}\n# u = mean of each feature as n * 1 array\n# var = variance of each feature as n* 1 array\ndef prob_gaussian(x,u,var):\n p1 = 1/np.sqrt(2*np.pi*var)\n p2 = np.exp(- ((x-u)**2) / (2*var))\n return p1*p2\n\n#epsilon - anomaly threshold, to be tuned based on performance on anomalous vs normal samples\nepsilon = 0.02\n\n#flags anomaly if prob_prod<epsilon\n# x_test {n features, m samples as n*m array}\n# u = mean of each feature as n * 1 array\n# var = variance of each feature as n* 1 array\n# epsilon = anomaly threshold\ndef anomaly(x_test, u, var, epsilon):\n probs = prob_gaussian(x_test, u, var)\n prob_prod = np.prod(probs,axis=0)\n return prob_prod, prob_prod<epsilon\n\n#test with some examples\n\nx_test = [[3],\n          [2],\n          [4]]\n\nanomaly(x_test, u, var, epsilon)\n#(array([0.03351253]), array([False]))\n\nx_test = [[0],\n          [5],\n          [6]]\n\n#(array([9.39835262e-05]), array([ True]))\n", "meta": {"hexsha": "ac698b72bc43a4dce6d1fbc18a6284b6e14e4d08", "size": 1350, "ext": "py", "lang": "Python", "max_stars_repo_path": "anomaly.py", "max_stars_repo_name": "mlnoone/anomalydetnumpy", "max_stars_repo_head_hexsha": "036df8b2a4241943d6aab5cf759900d454321a39", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "anomaly.py", "max_issues_repo_name": "mlnoone/anomalydetnumpy", "max_issues_repo_head_hexsha": "036df8b2a4241943d6aab5cf759900d454321a39", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "anomaly.py", "max_forks_repo_name": "mlnoone/anomalydetnumpy", "max_forks_repo_head_hexsha": "036df8b2a4241943d6aab5cf759900d454321a39", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4716981132, "max_line_length": 93, "alphanum_fraction": 0.6237037037, "include": true, "reason": "import numpy", "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668717616667, "lm_q2_score": 0.897695295528596, "lm_q1q2_score": 0.8807888849089575}}
{"text": "# calcuation.py\n# calculate linear regession line and correlation coefficient\n\nimport numpy as np\nimport copy\n\n# funtion to inverse the 2x2 matrix\ndef inverse_matrix(normal_matrix):\n\n    scalar = 1 / ((normal_matrix[0][0] * normal_matrix[1][1]) - (normal_matrix[0][1] * normal_matrix[1][0]))\n    # scalar = np.linalg.det(normal_matrix))    # the code above could be replace by this line, and this is also applicable for different size of matrix\n\n    inversed_matrix = copy.deepcopy(normal_matrix)  # deepcopy the normal_matrixto inversed_matrix to store in another memory\n\n    # inverse the matrix manually\n    inversed_matrix[0][0] = normal_matrix[1][1]\n    inversed_matrix[0][1] = -normal_matrix[1][0]\n    inversed_matrix[1][0] = -normal_matrix[0][1]\n    inversed_matrix[1][1] = normal_matrix[0][0]\n\n    # iterate through rows and columns of the matrix\n    for row in range(len(inversed_matrix)):\n        for column in range(len(inversed_matrix[row])):\n            # replace the value in the inversed_matrix after scalar multplication\n            inversed_matrix[row][column] = inversed_matrix[row][column] * scalar\n\n    return inversed_matrix  # return inversed matrix (a nested list)\n\n# function to find the linear regression line\ndef find_linear_regress(x_values, y_values):\n\n    # create nested array with ones and insert x_values as colomn and update x_values\n    x_values = np.insert(np.ones((x_values.size, 1)), 1, x_values, axis=1)\n    x_T_x = x_values.transpose().dot(x_values)\n    x_T_y = np.dot(x_values.transpose(), y_values)\n\n    x_T_x_inv = np.array(inverse_matrix(x_T_x.tolist()))    # convert x_T_x to list, and call function to find inversed matrix, then convert the return value to numpy array\n\n    b_m = x_T_x_inv.dot(x_T_y)  # multiply both matrix to find A, the values for b and m\n\n    verify_b_m = np.linalg.inv(x_values.transpose().dot(x_values)).dot(x_values.T).dot(y_values)  # the code above could be replace by this one line by using the function from numpy\n\n    return b_m, verify_b_m  # return both variables in numpy array form\n\n# function to find the correlation coefficient\ndef find_corr_coeff(x_values, y_values, b_m):\n\n    e_values = np.array([y_values[i] - (b_m[1] * x_values[i] + b_m[0]) for i in range(len(x_values))])  # find matrix E\n    sse = e_values.transpose().dot(e_values)    # find the sum of squares error\n\n    sst = np.sum((y_values - np.mean(y_values)) ** 2)   # find the sum of squares total\n    ssr = sst - sse # find the sum of squares regression\n    r_2 = ssr / sst # find the r^2 value\n\n    verify_r_2 = (np.corrcoef(x_values, y_values)[0,1])**2  # the code above could be replace by this one line by using the function from numpy\n\n    return r_2, verify_r_2  # return both variables\n", "meta": {"hexsha": "0d7d1384878df3c2b100cd8b905487a5f791f242", "size": 2740, "ext": "py", "lang": "Python", "max_stars_repo_path": "util/calculation.py", "max_stars_repo_name": "AaronCheung430/DurhamISC_LinearRegressionusingLeastSquaresMethod", "max_stars_repo_head_hexsha": "b72b423a5a17540b684f19752f3fac3ffb2e6802", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-25T09:41:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:41:38.000Z", "max_issues_repo_path": "util/calculation.py", "max_issues_repo_name": "AaronCheung430/DurhamISC_LinearRegressionusingLeastSquaresMethod", "max_issues_repo_head_hexsha": "b72b423a5a17540b684f19752f3fac3ffb2e6802", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/calculation.py", "max_forks_repo_name": "AaronCheung430/DurhamISC_LinearRegressionusingLeastSquaresMethod", "max_forks_repo_head_hexsha": "b72b423a5a17540b684f19752f3fac3ffb2e6802", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-28T16:07:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T16:07:42.000Z", "avg_line_length": 47.2413793103, "max_line_length": 181, "alphanum_fraction": 0.7164233577, "include": true, "reason": "import numpy,from numpy", "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.9353465170505205, "lm_q1q2_score": 0.8807729382499999}}
{"text": "# # Big O Notation\n\n# The goal of this lesson is to develop your ability to look at some code and indentify its time complexity, using Big O notation.\n\n# Comparison computacional complexity\nimport matplotlib.pyplot as plt\nfrom scipy.special import gamma\nimport math\nimport numpy as np\nn = np.linspace(1,101,100)\nO1 = gamma(n)\nO2 = 2**n\nO3 = n**2\nO4 = n*np.log(n) / np.log(2)\nO5 = n\nO6 = np.sqrt(n)\nO7 = np.log(n) / np.log(2)\nplt.plot(n, O1, '--k', label='n!') \nplt.plot(n, O2, '--r', label='2^n')  \nplt.plot(n, O3, '--g', label='n^2') \nplt.plot(n, O4, 'y', label='nlog(n)') \nplt.plot(n, O5, 'c', label='n') \nplt.plot(n, O6, '--m', label='sqrt(n)') \nplt.plot(n, O7, 'b', label='log(n)') \naxes = plt.gca()\naxes.set(xlim=(0, 100), ylim=(0, 100))\nleg = axes.legend()\nplt.show()\n\n# O(N!)\n# This is the Heap's algorithm, which is used for generating all possible permutation of n objects\n# Another example could be the Travelling Salesman Problem\ndef Permutation(data, n):\n    if n == 1:\n        print(data)\n        return\n    for i in range(n):\n        Permutation(data, n - 1)\n        if n % 2 == 0:\n            data[i], data[n-1] = data[n-1], data[i]\n        else:\n            data[0], data[n-1] = data[n-1], data[0]\ndata = [1, 2]\nPermutation(data,len(data))\nget_ipython().run_line_magic('time', '')\n\n# O(2^n)\n# Recursive calculation of Fibonacci numbers\ndef fibonacci(n):\n    if n <= 1:\n        return n\n    return fibonacci(n-1) + fibonacci(n-2)\nprint(fibonacci(20))\nget_ipython().run_line_magic('time', '')\n\n# O(N^2)\n# Print pair of numbers in the data\n\ndef Print_Pair(some_list):\n    for i in some_list:\n        for j in some_list:\n\n            print(\"Items: {}, {}\".format(i,j))\nPrint_Pair([1, 2, 3, 4])      \nget_ipython().run_line_magic('time', '')\n\n# O(nlog(n))\n# Mergesort algorithm\ndef Merge_Sort(data):\n    if len(data) <= 1:\n        return\n    \n    mid = len(data) // 2\n    left_data = data[:mid]\n    right_data = data[mid:]\n    \n    Merge_Sort(left_data)\n    Merge_Sort(right_data)\n    \n    left_index = 0\n    right_index = 0\n    data_index = 0\n    \n    while left_index < len(left_data) and right_index < len(right_data):\n        if left_data[left_index] < right_data[right_index]:\n            data[data_index] = left_data[left_index]\n            left_index += 1\n        else:\n            data[data_index] = right_data[right_index]\n            right_index += 1\n        data_index += 1\n    \n    if left_index < len(left_data):\n        del data[data_index:]\n        data += left_data[left_index:]\n    elif right_index < len(right_data):\n        del data[data_index:]\n        data += right_data[right_index:]\n    \ndata = [9, 0, 8, 6, 2, 5, 7, 3, 4, 1]\nMerge_Sort(data)\nprint(data)\nget_ipython().run_line_magic('time', '')\n\n# O(n)\n# Just print some itens\n\ndef Print_Item(data):\n    for i in data:\n        print(i)\n\nPrint_Item([1, 2, 3, 4])\nget_ipython().run_line_magic('time', '')\n\n# Linear search\ndef Linear_Search(data, value):\n    for index in range(len(data)):\n        if value == data[index]:\n            return index\n    raise ValueError('Value not found in the list')\ndata = [1, 3, 7, 4, 5, 9, 0, 11]\nprint(Linear_Search(data,9))\nget_ipython().run_line_magic('time', '')\n\n# O(log(n))\n# This algorithms with logarithmic time complexity are commonly found on binary trees\nfor idx in range(0, len(data), 3):\n    print(data[idx])\nget_ipython().run_line_magic('time', '')\n\n# Binary search\ndef binary_search(data, value):\n    n = len(data)\n    left = 0\n    right = n - 1\n    while left <= right:\n        middle = (left + right) // 2\n        if value < data[middle]:\n            right = middle - 1\n        elif value > data[middle]:\n            left = middle + 1\n        else:\n            return middle\n    raise ValueError('Value is not in the list')\n\ndata = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nprint(binary_search(data, 8))\n\n# O(0n + 1)\n\ndef First_Idx(data):\n    return data[0]\n    \ndata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nprint(First_Idx(data))\nget_ipython().run_line_magic('time', '')\n\n", "meta": {"hexsha": "a7e7fa74c80336504db81f360698c109a3fbe840", "size": 3988, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/efficiency/big_o_efficiency.py", "max_stars_repo_name": "joaomh/Python-Data-Structures-and-Algorithms", "max_stars_repo_head_hexsha": "0a0d9291380752f29edd77683be73b6c2d7a355f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2020-06-28T20:45:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T22:29:18.000Z", "max_issues_repo_path": "src/efficiency/big_o_efficiency.py", "max_issues_repo_name": "joaomh/Python-Data-Structures-and-Algorithms", "max_issues_repo_head_hexsha": "0a0d9291380752f29edd77683be73b6c2d7a355f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/efficiency/big_o_efficiency.py", "max_forks_repo_name": "joaomh/Python-Data-Structures-and-Algorithms", "max_forks_repo_head_hexsha": "0a0d9291380752f29edd77683be73b6c2d7a355f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-09-09T05:56:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T12:52:38.000Z", "avg_line_length": 25.2405063291, "max_line_length": 130, "alphanum_fraction": 0.6018054162, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241974031599, "lm_q2_score": 0.9086179018818865, "lm_q1q2_score": 0.8807453184878027}}
{"text": "# solutions.py\n\"\"\"Volume I: Monte Carlo Integration\nSolutions file. Written by Tanner Christensen\n\"\"\"\n\nimport numpy as np\nimport scipy.stats as stats\n\ndef mc_int(f, mins, maxs, numPoints=500, numIters=100):\n    \"\"\"Use Monte-Carlo integration to approximate the integral of f\n    on the box defined by mins and maxs.\n    \n    Inputs:\n        f (function) - The function to integrate. This function should \n            accept a 1-D NumPy array as input.\n        mins (1-D np.ndarray) - Minimum bounds on integration.\n        maxs (1-D np.ndarray) - Maximum bounds on integration.\n        numPoints (int, optional) - The number of points to sample in \n            the Monte-Carlo method. Defaults to 500.\n        numIters (int, optional) - An integer specifying the number of \n            times to run the Monte Carlo algorithm. Defaults to 100.\n        \n    Returns:\n        estimate (int) - The average of 'numIters' runs of the \n            Monte-Carlo algorithm.\n                \n    Example:\n        >>> f = lambda x: np.hypot(x[0], x[1]) <= 1\n        >>> # Integral over the square [-1,1] x [-1,1]. Should be pi.\n        >>> mc_int(f, np.array([-1,-1]), np.array([1,1]))\n        3.1290400000000007\n    \"\"\"\n    if len(mins) != len(maxs):\n        raise ValueError(\"Dimension of mins and maxs must be the same\")\n    \n    results = []\n    for i in xrange(numIters):\n        # create points\n        dim = len(mins)\n        side_lengths = maxs-mins\n        points = np.random.rand(numPoints,dim)\n        points = side_lengths*points + mins\n\n        # calculate Volume\n        V = 1\n        for i in xrange(dim):\n            V *= maxs[i] - mins[i]\n\n        # apply the function f along axis=1 and sum all the results\n        total = np.sum(np.apply_along_axis(f,1,points))\n        results.append((V/float(numPoints))*total)\n    estimate = np.average(results)\n    return estimate\n\ndef joint_normal(mins, maxs):\n    \"\"\"Caluclate the integral of the joint normal distribution using SciPy and \n    Monte Carlo integration.\n    \n    Inputs:\n        mins (1-D np.ndarray) - Minimum bounds of integration.\n        maxs (1-D np.ndarray) - Maximum bounds of integration.\n    \n    Returns:\n        value (int) - result from intregration using SciPy\n        estimate (1-D np.ndarray) - result of Monte Carlo integration\n            using 'numPoints' = {10,100,1000,10000}\n    \"\"\"\n    # define means and covs\n    means = np.zeros(len(mins))\n    covs = np.eye(len(mins))\n\n    #calculate integral using SciPy\n    value, inform = stats.mvn.mvnun(mins, maxs, means, covs)\n\n    f = lambda x: (1./np.sqrt((2*np.pi)**(len(x))))*np.exp(-x.dot(x)/2)\n    estimates = []\n    for n in xrange(1,5):\n        estimates.append(mc_int(f,mins,maxs,numPoints=10**n))\n    estimates = np.array(estimates)\n    \n    return value, estimates\n", "meta": {"hexsha": "5da21b5765623ad836dd1d33e3e95071a6f43d1c", "size": 2801, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol1B/MonteCarlo1-Integration/old_solutions2.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vol1B/MonteCarlo1-Integration/old_solutions2.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vol1B/MonteCarlo1-Integration/old_solutions2.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 34.1585365854, "max_line_length": 79, "alphanum_fraction": 0.6119243127, "include": true, "reason": "import numpy,import scipy", "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.9219218402181232, "lm_q1q2_score": 0.8807295700738142}}
{"text": "# Dependencies\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.fft import fft,ifft\nfrom module_1 import *\n\n# Sampling\n# Length of the signal\nL = 1\n# Sampling frequency\nsf = 12      \n# Sampling points\nsp = sf*L\n# Time partition \nt_part = np.linspace(0,L,sp,endpoint=False) #[s]\n# Frequency partition\nf_part = np.arange(0,sp/L,1/L)\n\n\n# Sinewave signal parameters\nfreq = 1 # frequency of the signal in Hz (1/period)\nA = 1. # Amplitude of the signal [V]\nphi = 0. # phase shift of the signal [degree]\n# Sinewave signal function\nomega = 2*np.pi*freq \nfunc = A*np.sin(omega*t_part + degree_to_rad(phi))\n\n# fourier transform of func\nft = np.empty(sp, dtype = np.complex_)  \nft = fft(func) # backward normalization (i.e, no normalisation for fft, 1/sp for ifft)\n\n# inverse fourier transform of ft\nift = np.empty(sp, dtype = np.complex_)   # *1/sp\nift = ifft(ft)\n\n\n# modulus and phase spectrum\nmodulus = np.abs(ft[0:int(sp/2)])\nphase = np.arctan2(ft.imag[0:int(sp/2)],ft.real[0:int(sp/2)])\n\n# Index associated with the maximum Fourier's coefficient \nmax_mod = np.max(modulus)\nindex = np.where(modulus==max_mod)\n\n# Amplitute of the signal through maximum fourier coefficient\nA_max = max_mod/(sp/2)\nphase_max = phase[index]\n\n# PRINTING AMPLIUDE AND PHASE OF THE SIN FUNCTION\nprint(\"PRINTING THE VALUES OF THE AMPLITUDE AND THE PHASE OF THE SINEWAVE CALCULATED FROM THE FOURIER'S COEFFICIENTS\")\nprint(\"----------------------------------------------------------------------------------------------------------\")\nprint(\"AMPLITUTE:\")\nprint(\"Expected value = %1.8f\"%A)\nprint(\"Calculated from the maximum Fourier coefficient = %1.8f\"%A_max)\nprint(\"-----------------------------------------------\")\nprint(\"PHASE\")\nprint(\"Expected value = %1.8f\"%phi)\nprint(\"Calculated from the maximum Fourier coefficients = %1.8f\"%(90+rad_to_degree(phase_max)))\n\n# Creating visualization\nfig, ax = plt.subplots(3)\n\n# plotting the sin function and the inverse fourier transform\nax[0].plot(t_part,func,\"-\",color = \"red\",label=r\"$sin(\\omega t)$\")\nax[0].plot(t_part,ift.real,\".\",color = \"blue\",label =r\"$F^{-1}[F[\\nu]]$\")\nax[0].legend()\nax[0].set_xlabel(\"Time (s)\")\nax[0].set_ylabel(\"Signal [a.u]\")\n\n# plotting the modulus of the fourier transform\nax[1].plot(f_part[0:int(sp/2)],modulus[0:int(sp/2)], marker='o',markerfacecolor=\"red\")\nax[1].set_xlabel(\"Frequency [Hz]\")\nax[1].set_ylabel(\"Amplitude [a.u]\")\n\n# plotting the fourier transform (imaginary part)\nax[2].plot(f_part[0:int(sp/2)],rad_to_degree(phase[0:int(sp/2)])+90, marker='o',markerfacecolor=\"red\")\nax[2].set_xlabel(\"Frequency [Hz]\")\nax[2].set_ylabel(\"Phase [degree]\")\n\nplt.show()\n", "meta": {"hexsha": "39ed175f038912ff0f5fa5024996bf3659a3472e", "size": 2617, "ext": "py", "lang": "Python", "max_stars_repo_path": "Codes/Exercise1/ex1.py", "max_stars_repo_name": "jacomore/NanoLab", "max_stars_repo_head_hexsha": "d2e7a7d37899d77431c21a4fe25549713ee02ef1", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Codes/Exercise1/ex1.py", "max_issues_repo_name": "jacomore/NanoLab", "max_issues_repo_head_hexsha": "d2e7a7d37899d77431c21a4fe25549713ee02ef1", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Codes/Exercise1/ex1.py", "max_forks_repo_name": "jacomore/NanoLab", "max_forks_repo_head_hexsha": "d2e7a7d37899d77431c21a4fe25549713ee02ef1", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3086419753, "max_line_length": 118, "alphanum_fraction": 0.6698509744, "include": true, "reason": "import numpy,from scipy", "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110589, "lm_q2_score": 0.921921831100897, "lm_q1q2_score": 0.8807295578456318}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef plotData(x, y):\n    \"\"\" Plots the data points x and y into a new figure;\n        plotData(x, y) plots the data points and gives the figure axes labels of population and profit.\n    \"\"\"\n    plt.figure()\n    plt.plot(X, y, 'rx')\n    plt.xlabel('Profit in $10,000s')\n    plt.ylabel('Population of City in 10,000s')\n\n\n# load comma separated txt file\ndata = np.loadtxt('ex1data1.txt', delimiter=',')\nX = data[:, 0][:, np.newaxis]\ny = data[:, 1][:, np.newaxis]\nplotData(X, y)\n\n\ndef computeCost(X, y, theta):\n    \"\"\" computeCost(X, y, theta) computes the cost of using theta as the\n   parameter for linear regression to fit the data points in X and y\n    \"\"\"\n\n    m = len(y)\n    J = 0.5 / m * np.sum((np.dot(X, theta)-y)**2)\n\n    return J\n\n\ndef gradientDescent(X, y, theta, alpha, num_iters):\n    \"\"\" gradientDescent(X, y, theta, alpha, num_iters) updates theta by\n    taking num_iters gradient steps with learning rate alpha\n    \"\"\"\n    m = len(y)\n    J_history = np.zeros((num_iters, 1))\n    print(J_history.shape)\n\n    for iter in range(num_iters):\n\n        # update theta\n        theta = theta - alpha / m * np.dot(X.T, (np.dot(X, theta)-y))\n        J_history[iter, 0] = computeCost(X, y, theta)\n\n    return theta, J_history\n\n\nm = len(y)\n# X with bias items\nX_wb = np.append(np.ones((m, 1)), X, axis=1)\ntheta0 = np.zeros((2, 1))\n\n# gradient descent settings\niterations = 1500\nalpha = 0.01\n\n# test cost function\nJ = computeCost(X_wb, y, theta0)\nprint('Expected 32.07 here.')\nprint('Actual result is {:.2f}.'.format(J))\n\nJ = computeCost(X_wb, y, np.array([[-1], [2]]))\nprint('Expected 54.24 here.')\nprint('Actual result is {:.2f}.'.format(J))\n\n\n# run gradient descent\ntheta, _ = gradientDescent(X_wb, y, theta0, alpha, iterations)\n\n# test theta\nprint('Expected \\n-3.6303 \\n1.1664\\n')\nprint('Actual result is \\n{:.4f} \\n{:.4f}'.format(theta[0, 0], theta[1, 0]))\n\n# Plot the result\nplotData(X, y)\nplt.plot(X, np.dot(X_wb, theta))\nplt.legend(['Training data', 'Linear regression'])\n\n# Create theta grid\ntheta0_vals = np.linspace(-10, 10, 100)\ntheta1_vals = np.linspace(-1, 4, 100)\n\n# initialize J_vals\nJ_vals = np.zeros((len(theta0_vals), len(theta1_vals)))\n\n# Fill out J_vals\nfor i in range(len(theta0_vals)):\n    for j in range(len(theta1_vals)):\n        t = np.array([[theta0_vals[i]], [theta1_vals[j]]])\n        J_vals[i, j] = computeCost(X_wb, y, t)\n\nJ_valsT = J_vals.T\n\n# # Contour plot\n# plt.contour(theta0_vals, theta1_vals, J_valsT, np.logspace(-2, 3, 20))\n# plt.plot(theta[0], theta[1], 'rx')\n\n# Surface plot\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nXt, Yt = np.meshgrid(theta0_vals, theta1_vals)\nsurf = ax.plot_surface(Xt, Yt, J_valsT)\nax.view_init(30, -125)\n\nplt.show()\n", "meta": {"hexsha": "cb31cf8752d19bd6f51b96f9c796494e29431779", "size": 2792, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment1 linear regression/assign1.py", "max_stars_repo_name": "oeyh/NN", "max_stars_repo_head_hexsha": "f07b6273425df47dab81a451edba04028c303134", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-09-09T05:01:06.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-09T05:01:06.000Z", "max_issues_repo_path": "assignment1 linear regression/assign1.py", "max_issues_repo_name": "oeyh/NN", "max_issues_repo_head_hexsha": "f07b6273425df47dab81a451edba04028c303134", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-08-20T05:14:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-09T04:58:36.000Z", "max_forks_repo_path": "assignment1 linear regression/assign1.py", "max_forks_repo_name": "oeyh/NN", "max_forks_repo_head_hexsha": "f07b6273425df47dab81a451edba04028c303134", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6146788991, "max_line_length": 103, "alphanum_fraction": 0.6540114613, "include": true, "reason": "import numpy", "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992960608886, "lm_q2_score": 0.9099070109242131, "lm_q1q2_score": 0.8806983553544132}}
{"text": "\"\"\"\nAnimated example of Linear Regression with Gradient Descent \n\nMIT License\n\nCopyright (c) 2021 Luiz Gustavo da Rocha Charamba\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt \nfrom matplotlib import animation\n\n# cost function method\ndef chi_square(m, c, X, Y):\n    error = 0\n    n = len(X)\n    for xi, yi in zip(X,Y):\n        error += (yi - (m*xi + c))*(yi - (m*xi + c))\n    \n    return error/n\n\n# partial derivative of chi square for m line parameter\ndef dChi_dm(m, c, X, Y):\n    m_grad = 0\n    n = len(X)\n    for xi, yi in zip(X,Y):\n        m_grad += xi*(yi - (m*xi + c))\n    \n    return (-2.0/n)*m_grad\n\n# partial derivative of chi square for c line parameter\ndef dChi_dc(m, c, X, Y):\n    c_grad = 0\n    n = len(X)\n    for xi, yi in zip(X,Y):\n        c_grad += (yi - (m*xi + c))\n    \n    return (-2.0/n)*c_grad\n\n# gradient descent updates line parameters\ndef grad_descent(m, c, lr, X, Y):\n    m_ = m - lr*dChi_dm(m, c, X, Y)\n    c_ = c - lr*dChi_dc(m, c, X, Y)\n    return m_, c_\n\ndef calc_line(m, c, X):\n    Y = []\n    for xi in X:\n        Y.append(m*xi + c)\n    return Y\n\ndef generate_noisydata(m, c, X):\n    noise = np.random.randint(40, size=(50))\n    noise = noise - 20\n    noise = 0.1*noise\n    Y = calc_line(m, c, X)\n    X_data = X\n    Y_data = Y + noise\n    return X_data, Y_data\n\n\n# original line\nm = 0.0\nc = 0.0\n\nfig = plt.figure()\nax = plt.axes(xlim=(0, 50), ylim=(0, 30))\ndata_points, = ax.plot([],[], 'o', color='orange')\nline_fitted, = ax.plot([],[])\ntext = ax.text(0.5, 0.5, '', fontsize=12)\n\nX_data, Y_data = generate_noisydata(0.5, 10, range(0,50))\nX_line = X_data\niterations = 5000 #10000\nlr = 0.001 # learning rate\n\n# Training\nM, C = [m],[c]\nfor it in range(iterations):\n    m,c = grad_descent(m, c, lr, X_data, Y_data)\n    M.append(m)\n    C.append(c)\n\ndef init_animation():\n    line_fitted.set_data([], [])\n    data_points.set_data(X_data, Y_data)\n    return data_points, line_fitted, text\n\nfont0 = {'family': 'serif',\n        'color':  'black',\n        'weight': 'normal',\n        'size': 16,\n        }\n\nfont1 = {'family': 'serif',\n        'color':  'darkred',\n        'weight': 'normal',\n        'size': 16,\n        }\n\nfont2 = {'family': 'serif',\n        'color':  'blue',\n        'weight': 'normal',\n        'size': 14,\n        }\n\n\ndef animate(i):\n    plt.title('Linear Regression with Gradient Descent optimization in MSE', fontdict=font1)\n    mserror = chi_square(M[i], C[i], X_data, Y_data)\n    text0 = ax.text(0.5, 28, \"Iteration: \" + str(i+1), fontdict=font0)\n    text1 = ax.text(0.5, 26, \"MSE = \" + \"{:.4f}\".format(mserror), fontdict=font1)\n    text2 = ax.text(0.5, 23, \"Line Parameters: \\n\" + \"(m = \" + \"{:.4f}\".format(M[i]) + \", c = \" + \"{:.4f}\".format(C[i]) + \")\", fontdict=font2)\n\n    \n    Y_line = calc_line(M[i], C[i], X_line)\n    line_fitted.set_data(X_line, Y_line)\n    data_points.set_data(X_data, Y_data)\n        \n    return data_points, line_fitted, text0, text1, text2\n\n\nprint(\"Line Parameters:\\n(m = \" + str(m) + \", c = \" + str(c) + \")\")\n\n# Animation\nanim = animation.FuncAnimation(fig, animate, init_func=init_animation,\n                               frames=iterations, interval=2, blit=True, repeat=False)\n\nplt.show()\n", "meta": {"hexsha": "6002d826b717be4a01b22f85f87d04888530a3f3", "size": 4199, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear-regression_animated.py", "max_stars_repo_name": "Charamba/Math-Algorithms-for-Machine-Learning", "max_stars_repo_head_hexsha": "d3701902e8a07764fc250f2fba9d308a614b59a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear-regression_animated.py", "max_issues_repo_name": "Charamba/Math-Algorithms-for-Machine-Learning", "max_issues_repo_head_hexsha": "d3701902e8a07764fc250f2fba9d308a614b59a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear-regression_animated.py", "max_forks_repo_name": "Charamba/Math-Algorithms-for-Machine-Learning", "max_forks_repo_head_hexsha": "d3701902e8a07764fc250f2fba9d308a614b59a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3716216216, "max_line_length": 142, "alphanum_fraction": 0.6325315551, "include": true, "reason": "import numpy", "num_tokens": 1242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.9252299539994747, "lm_q1q2_score": 0.8806923714735474}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n''' polynomial regression using numpy.polynomial.polynomial\nIt is a form of regression analysis in which \nthe relationship between the independent variable x \nand the dependent variable y is modelled as an \nnth degree polynomial in x.\n\ny = c0 * x^0 + c1 * x^1 +\n    c2 * x^2 + c3 * x^3 + ..... + cn * x ^n\nn = degree\n'''\n\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numpy.polynomial.polynomial as poly\n\n''' sample polynomial equation with degree=3'''\n''' t =    24.0 * x^0\n         + 12.0 * x^1\n         -  0.5 * x^2\n         +  9.0 * x^3\n'''\n\nconstant     = 24\nerror_induce = 0.01\n\ndef fx1(x1):\n    res   = (12.0  * x1)\n    error = 0.0\n    error = res * random.uniform(-error_induce, error_induce)\n    return res + error\ndef fx2(x2):\n    res   = (-0.50 * x2 * x2)\n    error = 0.0\n    error = res * random.uniform(-error_induce, error_induce)\n    return res + error\ndef fx3(x3):\n    res   = (09.0 * x3 * x3 * x3)\n    error = 0.0\n    error = res * random.uniform(-error_induce, error_induce)\n    return res + error\n\n''' data preparation '''\nmax_sample_value = 50\ntotal_samples    = 800\ntrain_sample_cnt = int((total_samples * 60.0 / 100.0))\ntest_sample_cnt  = total_samples - train_sample_cnt\ntrain_sample     = np.linspace(1,train_sample_cnt,train_sample_cnt)\ntest_sample      = np.linspace(train_sample_cnt,total_samples,test_sample_cnt)\n\ny1_samples       = fx1(np.arange(total_samples))\ny2_samples       = fx2(np.arange(total_samples))\ny3_samples       = fx3(np.arange(total_samples))\n\nt_samples        = y1_samples + y2_samples + y3_samples\n\nt_samples        = t_samples + constant\n\n''' splitting samples into train data and test data '''\nt_samples_train, t_samples_test   = np.split(\n                                     t_samples, \n                                     [train_sample_cnt,])\n\n''' use numpy.polynomial.polynomial for fitting data'''\ncoefs   = poly.polyfit(np.arange(train_sample_cnt),\n                       t_samples_train,\n                       3)\nffit    = poly.Polynomial(coefs) \n\nprint(\"intercept_ = \", coefs[0])\nprint(\"coef_      = \", coefs[1],coefs[2],coefs[3])\n\n\n#plt.plot(np.arange(test_sample_cnt), ffit(t_samples_test))\n#plt.show()\n\n''' fit a polynomial with above coefficients'''\nffit = np.poly1d(coefs[::-1])\n\nplt.title('Polynomial Regression using numpy.polynomial.polynomial', fontsize=16)\nplt.plot(train_sample,t_samples_train)\nplt.plot(test_sample,ffit(test_sample))\nplt.show()\n\nplt.title('Polynomial Regression using numpy.polynomial.polynomial: Difference between actual and expected', fontsize=16)\nplt.plot(np.linspace(1,test_sample_cnt,test_sample_cnt),\n         (ffit(test_sample) - t_samples_test))\nplt.show()\n         ", "meta": {"hexsha": "ed8c62a648285e60bbb9d29739e092489f57ce52", "size": 2738, "ext": "py", "lang": "Python", "max_stars_repo_path": "prg06_scikitlearn/sklearn06_polynomial_regression.py", "max_stars_repo_name": "imademethink/MachineLearning_related_Python", "max_stars_repo_head_hexsha": "c7fd22d2d878d110e0a7bf679103a226952164e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prg06_scikitlearn/sklearn06_polynomial_regression.py", "max_issues_repo_name": "imademethink/MachineLearning_related_Python", "max_issues_repo_head_hexsha": "c7fd22d2d878d110e0a7bf679103a226952164e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prg06_scikitlearn/sklearn06_polynomial_regression.py", "max_forks_repo_name": "imademethink/MachineLearning_related_Python", "max_forks_repo_head_hexsha": "c7fd22d2d878d110e0a7bf679103a226952164e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7608695652, "max_line_length": 121, "alphanum_fraction": 0.6548575603, "include": true, "reason": "import numpy", "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799462157138, "lm_q2_score": 0.9136765281148512, "lm_q1q2_score": 0.8805831151250915}}
{"text": "import numpy as np\nfrom numpy import log, exp\nfrom scipy import linalg as la\nimport matplotlib.pyplot as plt\nplt.ion() # Turn on interactive mode for plotting\nfrom scipy import stats\n\n# Build two matrices...\n\nA = np.zeros((4,4))\nB = np.zeros((4,4))\n\n# ... and fill in column by column...\n\nA[0,:]=[1,2,3,0]\nA[1,:]=[2,0,2,2]\nA[2,:]=[1,-2,1,3]\nA[3,:]=[5,1,7,8]\n\n# ... or maybe using some pattern...\n\nfor j in np.arange(1,3):\n    B[j,j]=2\n    B[j,j+1]=-1\n    B[j,j-1]=-1\n    \nB[0,:]=[2,-1,0,0]\nB[3,:]=[0,0,-1,2]\n\n# Define a special print function!\n\ndef pr(a,b):\n    # A personalized print function which adds extra spaces for a cleaner presentation\n    print()\n    print(a,b)\n    print()\n\n# Let's test some matrix operations:\n\npr('A = ', A )\npr('B = ', B )\npr('|A| = ', la.det(A) )\npr('AB = ', np.dot(A,B) )\npr('*Element-wise* A*B = ', A*B )\npr('A^T = ', A.T)\npr('A^{-1} = ', la.inv(A) )\npr('A^{-1}A = ', np.dot(la.inv(A),A) )\n\nb=np.ones((4,1))\nx=la.solve(A,b)\nprint('Solution to Ax=[1,1,1,1]^T:')\npr('x = ', x )\npr('Ax = ', np.dot(A,x) )\n\n\n# Now let's time out how long it takes to perform an LU Decomposition as a function of the matrix size.\n\nimport time\nNstart = 200\nNfinal = 1500\nNs = 20\nsizes = np.zeros((int((Nfinal-Nstart)/Ns),))\ntimes = np.zeros((int((Nfinal-Nstart)/Ns),))\n\nstep = 0\nprint('Running...')\nfor N in np.arange(Nstart,Nfinal,Ns):\n    \n    A = np.random.rand(N,N)\n\n    start = time.time()    \n    P,L,U = la.lu(A)\n    end  = time.time()\n\n    sizes[step] = N\n    times[step] = end - start\n    step += 1\nprint('Completed.')\n\nslope, intercept, r_value, p_value, std_err = stats.linregress(log(sizes[-5:]),log(times[-5:]))\npr('slope = ', slope)\n\n# Plotting results\nfig = plt.figure(figsize=(8.5, 8.5))\nplt.plot(sizes,times,'o')\nplt.plot(sizes,exp(intercept + slope*log(sizes)),'r-')\nplt.xlabel('N')\nplt.ylabel('Time [s]')\nplt.savefig('./Random.png')\n\nprint('Figure saved as ./Random.png.')\nprint('Have a nice day.')\n", "meta": {"hexsha": "55f9f9a145ef898591552deb1365789b29b843d7", "size": 1928, "ext": "py", "lang": "Python", "max_stars_repo_path": "514/hwk1/MatrixPlayground.py", "max_stars_repo_name": "DirkyJerky/Uni", "max_stars_repo_head_hexsha": "73ec1a84cdd59af9fc82a7bbb8af931305ec2ad3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "514/hwk1/MatrixPlayground.py", "max_issues_repo_name": "DirkyJerky/Uni", "max_issues_repo_head_hexsha": "73ec1a84cdd59af9fc82a7bbb8af931305ec2ad3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "514/hwk1/MatrixPlayground.py", "max_forks_repo_name": "DirkyJerky/Uni", "max_forks_repo_head_hexsha": "73ec1a84cdd59af9fc82a7bbb8af931305ec2ad3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7311827957, "max_line_length": 103, "alphanum_fraction": 0.5943983402, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104914476338, "lm_q2_score": 0.9111797088058519, "lm_q1q2_score": 0.8805736301841751}}
{"text": "from demos.setup import np, plt\nfrom scipy.integrate import quad\n\n\n\"\"\" Computing Function Inner Products, Norms & Metrics \"\"\"\n\n# Compute Inner Product and Angle\na, b = -1, 1\nf = lambda x: 2 * x**2 - 1\ng = lambda x: 4 * x**3 - 3*x\nfg = quad(lambda x: f(x) * g(x), a, b)[0]\nff = quad(lambda x: f(x) * f(x), a, b)[0]\ngg = quad(lambda x: g(x) * g(x), a, b)[0]\nangle = np.arccos(fg / np.sqrt(ff * gg)) * 180 / np.pi\nprint('\\nCompute inner product and angle')\nprint('\\tfg = {:6.4f},   ff = {:6.4f}, gg = {:6.4f},  angle = {:3.2f}'.format(fg, ff, gg, angle))\n\n# Compute Function Norm\na, b = 0, 2\nf = lambda x: x**2 - 1\np1, p2 = 1, 2\nq1 = quad(lambda x: np.abs(f(x) - g(x)) ** p1, a, b)[0] ** (1 / p1)\nq2 = quad(lambda x: np.abs(f(x) - g(x)) ** p2, a, b)[0] ** (1 / p2)\nprint('\\nCompute function norm')\nprint('\\tnorm 1 = {:6.4f},   norm 2 = {:6.4f}'.format(q1, q2))\n\n\n# Compute Function Metrics\na, b = 0, 2\nf = lambda x: x**3 + x**2 + 1\ng = lambda x: x**3 + 2\np1, p2 = 1, 2\nq1 = quad(lambda x: np.abs(f(x)-g(x)) ** p1, a, b)[0] ** (1 / p1)\nq2 = quad(lambda x: np.abs(f(x)-g(x)) ** p2, a, b)[0] ** (1 / p2)\nprint('\\nCompute function metrics')\nprint('\\tnorm 1 = {:6.4f},   norm 2 = {:6.4f}'.format(q1, q2))\n\n# Illustrate function metrics\nx = np.linspace(a, b, 200)\nplt.figure(figsize=[12, 4])\nplt.subplot(1, 2, 1)\nplt.plot([0, 2], [0, 0], 'k:', linewidth=4)\nplt.plot(x, f(x) - g(x), 'b', linewidth=4, label='f - g')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.xticks([0, 1, 2])\nplt.yticks([-1, 0, 1, 2, 3])\nplt.title('f - g')\n\nplt.subplot(1, 2, 2)\nplt.plot(x, np.abs(f(x) - g(x)), 'b', linewidth=4, label='f - g')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.xticks([0, 1, 2])\nplt.yticks([0, 1, 2, 3])\nplt.title('|f - g|')\n\nplt.show()\n\n# Demonstrate Pythagorean Theorem\na, b = -1, 1\nf = lambda x: 2 * x**2 - 1\ng = lambda x: 4 * x**3 -3*x\nifsq = quad(lambda x: f(x) ** 2, a, b)[0]\nigsq = quad(lambda x: g(x) ** 2, a, b)[0]\nifplusgsq = quad(lambda x: (f(x) + g(x)) ** 2, a, b)[0]\nprint('\\nDemonstrate Pythagorean Theorem')\nprint(r'    $\\int f^2(x) dx$ = {:6.4f}, $\\int g^2(x) dx$ = {:6.4f}'.format(ifsq, igsq))\nprint(r'    $\\int f^2(x) dx + \\int g^2(x) dx$ = {:6.4f}, $\\int (f+g)^2(x) dx$ = {:6.4f}'.format(ifsq + igsq, ifplusgsq))\n\n", "meta": {"hexsha": "a1a7aa1849f1d78592fd286124644310ce7bae30", "size": 2204, "ext": "py", "lang": "Python", "max_stars_repo_path": "compecon/demos/demmath02.py", "max_stars_repo_name": "daniel-schaefer/CompEcon-python", "max_stars_repo_head_hexsha": "d3f66e04a7e02be648fc5a68065806ec7cc6ffd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2016-12-14T13:21:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-23T21:04:34.000Z", "max_issues_repo_path": "compecon/demos/demmath02.py", "max_issues_repo_name": "daniel-schaefer/CompEcon-python", "max_issues_repo_head_hexsha": "d3f66e04a7e02be648fc5a68065806ec7cc6ffd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-09-10T04:48:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-31T01:36:46.000Z", "max_forks_repo_path": "compecon/demos/demmath02.py", "max_forks_repo_name": "daniel-schaefer/CompEcon-python", "max_forks_repo_head_hexsha": "d3f66e04a7e02be648fc5a68065806ec7cc6ffd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-02-25T08:10:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T09:49:16.000Z", "avg_line_length": 31.0422535211, "max_line_length": 120, "alphanum_fraction": 0.5494555354, "include": true, "reason": "from scipy", "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9793540734789343, "lm_q2_score": 0.899121367808974, "lm_q1q2_score": 0.8805581741156698}}
{"text": "import pandas as pd\nimport numpy as np\nimport datetime as dt\nimport matplotlib.pyplot as plt \nimport matplotlib.dates as mdates\nfrom scipy import stats \n\n\nclass Valuation:\n    \n    def time_to_maturity(self, t0, T, y=252):\n        t0 = pd.to_datetime(t0).date()\n        T = pd.to_datetime(T).date()\n        return ( np.busday_count(t0, T) / y )\n\n    \n    def ddm(self, d, r, g):\n        p = d / (r - g)\n        return(p)\n    \n    \n    def dcf(self, r, *cf):\n        n = 1\n        p = 0\n        for c in cf:\n            p += (c / (1+r)**n)\n            n += 1\n        return(p)\n\n\n    def futures_price(self, S, r, d, t0, T):\n        #ttm = np.busday_count(t0, T) / 252\n        ttm = self.time_to_maturity(t0, T)\n        F = S * np.exp((r-d)*ttm)\n        return (F)\n\n    \n    def call_price(self, S, K, ttm, r, sigma):    \n        d1 = ( np.log(S / K) + (r + sigma**2 * 0.5) * ttm ) / ( sigma * np.sqrt(ttm) )\n        d2 = ( np.log(S / K) + (r - sigma**2 * 0.5) * ttm ) / ( sigma * np.sqrt(ttm) )\n        val = ( S * stats.norm.cdf(d1, 0.0, 1.0) ) - K * np.exp( -r * ttm ) * stats.norm.cdf(d2, 0.0, 1.0)\n        return val\n    \n\n    def put_price(self, S, K, ttm, r, sigma):    \n        d1 = ( np.log(S / K) + (r + sigma**2 * 0.5) * ttm ) / ( sigma * np.sqrt(ttm) )\n        d2 = ( np.log(S / K) + (r - sigma**2 * 0.5) * ttm ) / ( sigma * np.sqrt(ttm) )\n        val = K * np.exp( -r * ttm ) * stats.norm.cdf(-d2, 0.0, 1.0) - ( S * stats.norm.cdf(-d1, 0.0, 1.0) ) \n        return val\n    \n    \n    def call_delta(self, S, K, ttm, r, sigma):\n        d1 = ( np.log(S / K) + (r + sigma**2 * 0.5) * ttm ) / ( sigma * np.sqrt(ttm) )\n        val = stats.norm.cdf(d1, 0.0, 1.0)\n        return val\n\n    \n    def put_delta(self, S, K, ttm, r, sigma):\n        d1 = ( np.log(S / K) + (r + sigma**2 * 0.5) * ttm ) / ( sigma * np.sqrt(ttm) )\n        val = stats.norm.cdf(d1, 0.0, 1.0)  - 1\n        return val\n\n    \n    def ndx(self, x):\n        return ( np.exp( -1 * x**2 * 0.5 ) / np.sqrt(2 * np.pi) )\n    \n    \n    def gamma(self, S, K, ttm, r, sigma):\n        d1 = ( np.log(S / K) + (r + sigma**2 * 0.5) * ttm ) / ( sigma * np.sqrt(ttm) )\n        val = ( self.ndx(d1) ) / ( S * sigma * np.sqrt(ttm) )\n        return val\n    \n    \n    def call_theta(self, S, K, ttm, r, sigma):    \n        d1 = ( np.log(S / K) + (r + sigma**2 * 0.5) * ttm ) / ( sigma * np.sqrt(ttm) )\n        d2 = ( np.log(S / K) + (r - sigma**2 * 0.5) * ttm ) / ( sigma * np.sqrt(ttm) )\n        val = -1 * ( ( S * self.ndx(d1) * sigma ) / ( 2 * np.sqrt(ttm)) ) - r * K * np.exp(-r*ttm) * stats.norm.cdf(d2, 0.0, 1.0)\n        return val\n    \n    \n    def put_theta(self, S, K, ttm, r, sigma):    \n        d1 = ( np.log(S / K) + (r + sigma**2 * 0.5) * ttm ) / ( sigma * np.sqrt(ttm) )\n        d2 = ( np.log(S / K) + (r - sigma**2 * 0.5) * ttm ) / ( sigma * np.sqrt(ttm) )\n        val = -1 * ( ( S * self.ndx(d1) * sigma ) / ( 2 * np.sqrt(ttm)) ) + r * K * np.exp(-r*ttm) * stats.norm.cdf(-1*d2, 0.0, 1.0)\n        return val\n    \n    \n    def vega(self, S, K, ttm, r, sigma):    \n        d1 = ( np.log(S / K) + (r + sigma**2 * 0.5) * ttm ) / ( sigma * np.sqrt(ttm) )\n        d2 = ( np.log(S / K) + (r - sigma**2 * 0.5) * ttm ) / ( sigma * np.sqrt(ttm) )\n        val = ( S * np.sqrt(ttm) * self.ndx(d1) )\n        return val\n    \n    def implied_vol_call(self, S, K, ttm, r, sigma, C, repeat=100):\n        for i in range(repeat):\n            sigma = sigma - ( (self.call_price(S, K, ttm, r, sigma) - C) / self.vega(S, K, ttm, r, sigma) )\n        return sigma\n    \n    def implied_vol_put(self, S, K, ttm, r, sigma, P, repeat=100):\n        for i in range(repeat):\n            sigma = sigma - ( (self.put_price(S, K, ttm, r, sigma) - P) / self.vega(S, K, ttm, r, sigma) )\n        return sigma\n    \n    \n\nclass ValueAtExpiry:\n    \n    def stock(self, x, x0):\n        y = x - x0\n        return y\n\n    def x_axis(self, x):\n        return x*0\n    \n    def futures(self, s, k):\n        return s - k\n    \n    def call_option(self, s, k, p):\n        return np.where(s > k, s - k - p, -p)\n    \n    def put_option(self, s, k, p):\n        return np.where(s < k, k - s - p, -p)\n    \n    def ko_put(self, s, k, b, p):\n        return np.where(s > b, np.where(s > k, -p, k - s - p), -p)\n    \n    def ki_call(self, s, k, b, p):\n        return np.where(s > b, np.where(s > k, s - k - p, -p), -p)\n    \n    def synthetic(self, x, **y):\n        s = pd.Series(0 for _ in range(len(x)))\n        for key, value in y.items():\n            s = s + pd.Series(value)\n        return (s)", "meta": {"hexsha": "c4b04cfdd7b9ae14d1f63aab81c5976b651f111d", "size": 4504, "ext": "py", "lang": "Python", "max_stars_repo_path": "w4/finterstellar/valuation.py", "max_stars_repo_name": "finterstellar/lecture", "max_stars_repo_head_hexsha": "fb14fb1c6a842e2ee2f79b0225ac9f4d11c3ca47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-14T05:53:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-29T03:45:59.000Z", "max_issues_repo_path": "w5/finterstellar/valuation.py", "max_issues_repo_name": "finterstellar/lecture", "max_issues_repo_head_hexsha": "fb14fb1c6a842e2ee2f79b0225ac9f4d11c3ca47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "w5/finterstellar/valuation.py", "max_forks_repo_name": "finterstellar/lecture", "max_forks_repo_head_hexsha": "fb14fb1c6a842e2ee2f79b0225ac9f4d11c3ca47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-03-01T13:50:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:47:28.000Z", "avg_line_length": 33.6119402985, "max_line_length": 132, "alphanum_fraction": 0.460035524, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9840936110872273, "lm_q2_score": 0.8947894541786198, "lm_q1q2_score": 0.880556585125407}}
{"text": "# --------------------------------------------------- \n# Statistical Thinking in Python (Part 1) - Quantitative exploratory data analysis\n# 10 fev 2021 \n# VNTBJR \n# --------------------------------------------------- \n#\n\n######################################################################\n# Introduction to summary statistics: The sample mean and median  -------------------------------------------\n######################################################################\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nsns.set()\ndf = sns.load_dataset('iris')\nversicolor_petal_length = df.petal_length[df['species'] == 'versicolor'].values\n\n# Computing means and medians\n# Compute the mean: mean_length_vers\nmean_length_vers = np.mean(versicolor_petal_length)\nmedian_length_vers = np.median(versicolor_petal_length)\n\n# Print the result with some nice formatting\nprint('I. versicolor mean:', mean_length_vers, 'cm')\nprint('I. versicolor median:', median_length_vers, 'cm')\n\n######################################################################\n# Percentiles, outliers, and box plots  -------------------------------------------\n######################################################################\n\n# Computing percentiles\n# Specify array of percentiles: percentiles\npercentiles = np.array([2.5, 25, 50, 75, 97.5])\n\n# Compute percentiles: ptiles_vers\nptiles_vers = np.percentile(versicolor_petal_length, percentiles)\n\n# Print the result\nprint(ptiles_vers)\n\n# Comparing perceentiles to ECDF\n# Plot the ECDF\n_ = plt.plot(x_vers, y_vers, '.')\n_ = plt.xlabel('petal length (cm)')\n_ = plt.ylabel('ECDF')\n\n# Overlay percentiles as red diamonds.\n_ = plt.plot(ptiles_vers, percentiles/100, marker = 'D', color = 'red',\n         linestyle = 'none')\n\n# Show the plot\nplt.show()\nplt.clf()\n\n# Box-and-whisker plot\n# Create box plot with Seaborn's default settings\n_ = sns.boxplot(x = 'species', y = 'petal_length', data = df)\n\n# Label the axes\n_ = plt.xlabel('species')\n_ = plt.ylabel('peltal length (cm)')\n\n# Show the plot\nplt.show()\nplt.clf()\n\n######################################################################\n# Variance and standard deviation  -------------------------------------------\n######################################################################\n# Computing the variance\n# Array of differences to mean: differences\ndifferences = versicolor_petal_length - np.mean(versicolor_petal_length)\n\n# Square the differences: diff_sq\ndiff_sq = differences ** 2\n\n# Compute the mean square difference: variance_explicit\nvariance_explicit = np.mean(diff_sq)\n\n# Compute the variance using NumPy: variance_np\nvariance_np = np.var(versicolor_petal_length)\n\n# Print the results\nprint(variance_explicit, variance_np)\n\n# The standard deviation and the variance\n# Compute the variance: variance\nvariance = np.var(versicolor_petal_length)\n\n# Print the square root of the variance\nprint(np.sqrt(variance))\n\n# Print the standard deviation\nprint(np.std(versicolor_petal_length))\n\n######################################################################\n# Covariance and the Pearason correlation coefficient  -------------------------------------------\n######################################################################\n# Covariance summarize how one variable varies in relation to another\n# It measure how two quantities vary together\n# The covariace is the mean of the product of the difference\n# between observations and their respective means\n# The Pearson correlation coefficient is a dimensionless measure\n# of how two variables depend on each other\n# We divide the covariance by the product of the standard deviation\n# of x and y variables\n# It is the comparison of the variability in the data due to \n# codependence (the covariance) to the variability inherent to \n# each variable indpendently (their standard deviations)\n\n# Scatter plots\nversicolor_petal_width = df.petal_width[df['species'] == 'versicolor'].values\n# Make a scatter plot\n_ = plt.plot(versicolor_petal_length, versicolor_petal_width, marker = '.', linestyle = 'none')\n\n# Label the axes\n_ = plt.xlabel('petal length (cm)')\n_ = plt.ylabel('petal width (cm)')\n\n# Show the result\nplt.show()\nplt.clf()\n\n# Computing the covariance\n# Compute the covariance matrix: covariance_matrix\ncovariance_matrix = np.cov(versicolor_petal_length, versicolor_petal_width)\n\n# Print covariance matrix\nprint(covariance_matrix)\n\n# Extract covariance of length and width of petals: petal_cov\npetal_cov = covariance_matrix[0, 1]\n\n# Print the length/width covariance\nprint(petal_cov)\n\n# Computing the Pearson correlation coefficient\ndef pearson_r(x, y):\n    \"\"\"Compute Pearson correlation coefficient between two arrays.\"\"\"\n    # Compute correlation matrix: corr_mat\n    corr_mat = np.corrcoef(x, y)\n\n    # Return entry [0,1]\n    return corr_mat[0,1]\n\n# Compute Pearson correlation coefficient for I. versicolor: r\nr = pearson_r(versicolor_petal_length, versicolor_petal_width)\n\n# Print the result\nprint(r)\n", "meta": {"hexsha": "912cc49cf3d791808bf2e1e3c06d894e7198c855", "size": 4967, "ext": "py", "lang": "Python", "max_stars_repo_path": "Statistical-Thinking-in-Python-part-1/02-Quantitative-exploratory-data-analysis.py", "max_stars_repo_name": "vntborgesjr/Data-Scientist-with-Python", "max_stars_repo_head_hexsha": "30385c448d696aed98532765c727cc110c587028", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Statistical-Thinking-in-Python-part-1/02-Quantitative-exploratory-data-analysis.py", "max_issues_repo_name": "vntborgesjr/Data-Scientist-with-Python", "max_issues_repo_head_hexsha": "30385c448d696aed98532765c727cc110c587028", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistical-Thinking-in-Python-part-1/02-Quantitative-exploratory-data-analysis.py", "max_forks_repo_name": "vntborgesjr/Data-Scientist-with-Python", "max_forks_repo_head_hexsha": "30385c448d696aed98532765c727cc110c587028", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8940397351, "max_line_length": 109, "alphanum_fraction": 0.6341856251, "include": true, "reason": "import numpy", "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211575679041, "lm_q2_score": 0.9032942112597331, "lm_q1q2_score": 0.8805503086445999}}
{"text": "# MSDS 400 Module 5 Practice 1\n\nimport numpy \nfrom numpy import sin, arange\nimport matplotlib.pyplot \nfrom matplotlib.pyplot import *\n\n# Students can substitute their own functions to observe convergence\n# to limiting values.\n\ndef g(x):\n    g = (sin(x))  #This is where a student's function can be substituted.\n    return g\n\n# An example will be used to show right and left convergence to a value.        \n# Convergence at x=0 will be shown graphically using g(x).\n\nn=5  # This determines the number of values calculated on each side of x=0.\n\npowers=arange(0,n+1)\ndenominator=2.0**powers  # denominator contains exponentiated values of 2.0. \ndelta=2.0           # This is the interval used on either side of the origin.\n\n# The following are values of x and f(x) trending to the limit.\n# Delta is being divided by powers of 2 to reduce the distance from the limit.\n# The letter \"r\" denotes from the right, and \"l\" denotes from the left.\n\nx_r=delta/denominator\ny_r=g(x_r) \nx_l=-x_r   # The negative sign generates a symmetric point on the left.\ny_l=g(x_l)\n\n# The following determines the vertical boundaries of the resulting plot.\n\nymax = max( abs(y_r) ) + 0.5\nymin = -ymax\n\nfigure()\nxlim(-delta-0.5,delta+0.5)\nylim(ymin,ymax)\n\n# Plotting is being done in layers.  First the line plot then the points.\n\nplot(x_r,y_r, color='b')\nplot(x_l,y_l,color='r')\n\n# The black points were computed.  The yellow point marks the limit.\n\nscatter(x_r,y_r,color='k',s=30)\nscatter(x_l,y_l,color='k',s=30)\nscatter(0.0,g(0.0),c='y',s=40)\n\ntitle ('Example of Convergence to a Functional Value')\nxlabel('x-axis')\nylabel('y-axis')\nshow()\n\n# Define a different function.  This one is from Lial Section 11.1 Example 12.\n# As x goes to infinity, f tends to 8/3=2.667 (rounded to 3 digits).\n\ndef f(x):\n    f = (8.0*x)/(3*x-1)\n    return f\n       \n# The next section shows convergence to a limit at infinity.\n# The coding shows list manipulations resulting in a plot.\n# For simplicity, equal intervals between calculated points will be used.\n \nnumber = 210  # This is the number of points calculated (minus the increment).\nincrement =10  # This is the increment between the points.\n \ny = []\nx = []\n\n# The for loop traverses between 10 and 200 in increments of 10.  \n# A range statement is inclusive of the first number and exclusive of the last.\n\nfor k in range(increment, number, increment):\n    w=float(k)\n    x = x + [k]\n    y = y + [f(w)]\n    \nprint ('Final value equals' , y[-1])  #Floating point with 4 decimals.\n    \nfigure()\nxlim(0,number+increment)\nylim(min(y)-0.1, max(y)+0.1)\n\n# The black points were computed.  The yellow point indicates the limit.\n\nplot(x,y, color='r')\nscatter(x,y,color='k',s=30)\nscatter(number,y[-1],c='y',s=40)\n\ntitle ('Example of Convergence to a Limit at Infinity')\nxlabel('x-axis')\nylabel('y-axis')\nshow()  # Plot shows convergence to limit at infinity \n\n# Exercise #1: Refer to Lial Section 11.1 Example 1.  Generalize the code \n# for the function indicated to determine a limit when x=2. Compare the\n# code and the resulting plot to the answer sheet.\n\n# Exercise #2: Generalize the code which was used to determine a limiting\n# value at infinity.  Apply to Lial Section 11.1 Example 11.", "meta": {"hexsha": "d424946a258cbaf64eeb92316bc02c1ff8cda626", "size": 3194, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Module 5/practice/practice_1.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Module 5/practice/practice_1.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Module 5/practice/practice_1.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.419047619, "max_line_length": 80, "alphanum_fraction": 0.7100814026, "include": true, "reason": "import numpy,from numpy", "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235895, "lm_q2_score": 0.9294404038127071, "lm_q1q2_score": 0.8805342253266553}}
{"text": "\n# coding: utf-8\n\n# # Introduction\n# In this assignment, we analyse signals using the Fast Fourier transform, or the FFT for short. The FFT is a fast implementation of the Discrete Fourier transform(DFT). It runs in $\\mathcal{O}(n \\log n)$ time complexity. We find the FFTs of various types of signals using the numpy.fft module. We also attempt to approximate the continuous time fourier transform of a gaussian by windowing and sampling in time domain, and then taking the DFT. We iteratively increase window size and number of samples until we obtain an estimate of required accuracy.\n\n# In[1]:\n\n\nfrom pylab import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# # Spectrum of $\\sin^3(t)$\n\n# Using the following identity:\n# $$\\sin^3(t) = \\frac{3}{4}\\sin(t) - \\frac{1}{4}\\sin(3t)$$\n# \n# We expect two sets of peaks at frequencies of 1 and 3, with heights corresponding to half of $0.75$ and $0.25$.\n\n# In[2]:\n\n\nx = np.linspace(-4*pi,4*pi,513)[:-1]\nw = np.linspace(-64,64,513)[:-1]\ny1 = (np.sin(x))**3\nY1 = fftshift(fft(y1))/512\nfig,ax = plt.subplots(2)\nax[0].plot(w,abs(Y1))\nax[0].set_xlim([-10,10])\nax[0].set_title(r\"Magnitude and Phase plots of DFT of $\\sin^3(t)$ \")\nax[0].set_ylabel(r\"$|Y|$\",size=16)\nax[0].set_xlabel(r\"$\\omega$\",size=16)\nax[0].grid(True)\nii1 = np.where(abs(Y1)<10**-3)\nph = angle(Y1)\nph[ii1] = 0 \nax[1].plot(w,ph,\"ro\")\nax[1].set_xlim([-10,10])\nax[1].grid(True)\nax[1].set_ylabel(r\"Phase of $Y$\",size=16)\nax[1].set_xlabel(r\"$\\omega$\",size=16)\nplt.show()\n\n\n# We observe the peaks in the magnitude at the expected frequencies of 1 and 3, along with the expected amplitudes. The phases of the peaks are also in agreement with what is expected(one is a positive sine while the other is a negative sine).\n\n# # Spectrum of $\\cos^3(t)$\n\n# Using the following identity:\n# $$\\cos^3(t) = \\frac{3}{4}\\cos(t) + \\frac{1}{4}\\cos(3t)$$\n# \n# We expect two sets of peaks at frequencies of 1 and 3, with heights corresponding to half of $0.75$ and $0.25$.\n\n# In[3]:\n\n\nx = np.linspace(-4*pi,4*pi,129)[:-1]\nw = np.linspace(-16,16,129)[:-1]\ny2 = (np.cos(x))**3\nY2 = fftshift(fft(y2))/128\nfig,bx = plt.subplots(2)\nbx[0].plot(w,abs(Y2))\nbx[0].set_xlim([-10,10])\nbx[0].grid(True)\nbx[0].set_ylabel(r\"$|Y|$\",size=16)\nbx[0].set_xlabel(r\"$\\omega$\",size=16)\nbx[0].set_title(r\"Magnitude and Phase plots of DFT of $\\cos^3(t)$ \")\nii2 = np.where(abs(Y2)>10**-3)\nbx[1].plot(w[ii2],angle(Y2[ii2]),\"ro\")\nbx[1].set_xlim([-10,10])\nbx[1].grid(True)\nbx[1].set_ylabel(r\"Phase of $Y$\",size=16)\nbx[1].set_xlabel(r\"$\\omega$\",size=16)\nplt.show()\n\n\n# We observe the peaks in the magnitude at the expected frequencies of 1 and 3, along with the expected amplitudes. The phases of the peaks are also in agreement with what is expected(both are positive cosines).\n\n# # Freq Modulation\n\n# We find the DFT of the following frequency modulated signal:\n# \n# $$ \\cos(20t +5 \\cos(t))$$\n\n# In[4]:\n\n\nx = np.linspace(-4*pi,4*pi,513)[:-1]\nw = np.linspace(-64,64,513)[:-1]\ny1 = cos(20*x + 5*cos(x))\nY1 = fftshift(fft(y1))/512\nfig,ax = plt.subplots(2)\nax[0].plot(w,abs(Y1))\nax[0].set_xlim([-40,40])\nax[0].grid(True)\nax[0].set_ylabel(r\"$|Y|$\",size=16)\nax[0].set_xlabel(r\"$\\omega$\",size=16)\nax[0].set_title(r\"Magnitude and Phase plots of DFT of $ \\cos(20t +5 \\cos(t))$ \")\nii1 = np.where(abs(Y1)<10**-3)\nph = angle(Y1)\nph[ii1] = 0 \nax[1].plot(w,ph,\"ro\")\nax[1].set_xlim([-40,40])\nax[1].grid(True)\nax[1].set_ylabel(r\"Phase of $Y$\",size=16)\nax[1].set_xlabel(r\"$\\omega$\",size=16)\nplt.show()\n\n\n# # Continuous time Fourier Transform of Gaussian\n\n# The fourier transform of a signal $x(t)$ is defined as follows:\n# \n# $$X(\\omega) = \\frac{1}{2 \\pi} \\int_{- \\infty}^{\\infty} x(t) e^{-j \\omega t} dt$$\n# \n# We can approximate this by the fourier transform of the windowed version of the signal $x(t)$, with a sufficiently large window. Let the window be of size $T$. We get:\n# \n# $$X(\\omega) \\approx \\frac{1}{2 \\pi} \\int_{- \\frac{T}{2}}^{\\frac{T}{2}} x(t) e^{-j \\omega t} dt$$\n# \n# We can write the integral approximately as a Reimann sum:\n# \n# $$X(\\omega) \\approx \\frac{\\Delta t}{2 \\pi} \\sum_{n = -\\frac{N}{2}}^{\\frac{N}{2}-1} x(n \\Delta t) e^{-j \\omega n \\Delta t}$$\n# \n# Where we divide the integration domain into $N$ parts (assume $N$ is even), each of width $\\Delta t = \\frac{T}{N}$.\n# \n# Now, we sample our spectrum with a sampling period in the frequency domain of $\\Delta \\omega = \\frac{2 \\pi}{T}$, which makes our continuous time signal periodic with period equal to the window size $T$. Our transform then becomes:\n# \n# $$X(k \\Delta \\omega) \\approx \\frac{\\Delta t}{2 \\pi} \\sum_{n = -\\frac{N}{2}}^{\\frac{N}{2}-1} x(n \\Delta t) e^{-j k n \\Delta \\omega \\Delta t}$$\n# \n# Which simplifies to:\n# \n# $$X(k \\Delta \\omega) \\approx \\frac{\\Delta t}{2 \\pi} \\sum_{n = -\\frac{N}{2}}^{\\frac{N}{2}-1} \n# x(n \\Delta t) e^{-j \\frac{2 \\pi}{N} k n}$$\n# \n# Noticing that the summation is of the form of a DFT, we can finally write:\n# \n# $$X(k \\Delta \\omega) \\approx \\frac{\\Delta t}{2 \\pi} DFT \\{x(n \\Delta t)\\}$$\n# \n# The two approximations we made were:\n# \n# * The fourier transform of the windowed signal is approximately the same as that of the original.\n# * The integral was approximated as a Reimann sum.\n# \n# We can improve these approximations by making the window size $T$ larger, and by decreasing the time domain sampling period or increasing the number of samples $N$. We implement this in an iterative algorithm in the next part.\n# \n# The analytical expression of the fourier transform of the gaussian:\n# \n# $$x(t) = e^{\\frac{-t^2}{2}}$$\n# \n# Was found as:\n# \n# $$X(j \\omega) = \\frac{1}{\\sqrt{2 \\pi}}e^{\\frac{-\\omega^2}{2}}$$\n# \n# We also compare the numerical results with the expected analytical expression.\n\n# In[5]:\n\n\ndef ideal(w):\n    return (1/np.sqrt(2*pi)) * (exp((-1*w*w)/2))\ndef tol(N=128,tol=10**-6):\n    T = 8*pi\n    N = 128\n    error = 10**10\n    yold =0\n    while error>tol:\n        x = np.linspace(-T/2,T/2,N+1)[:-1]\n        w = pi* np.linspace(-N/T,N/T,N+1)[:-1]\n        Y1 = (T/(2*pi*N)) * fftshift(fft(ifftshift(exp(-x*x/2))))\n        error = sum(abs(Y1-ideal(w)))\n        yold = Y1\n        T = T*2\n        N = N*2\n    print(\"max error =\" + str(error))\n    fig,ax = plt.subplots(2)\n    ax[0].plot(w,abs(Y1))\n    ax[0].set_xlim([-10,10])\n    ax[0].grid(True)\n    ax[0].set_ylabel(r\"$|Y|$\",size=16)\n    ax[0].set_xlabel(r\"$\\omega$\",size=16)\n    ax[0].set_title(r\"Magnitude and Phase plots(calculated) of DFT of $ \\exp(-t^{2}/2)$ \")\n    ii1 = np.where(abs(Y1)<10**-3)\n    ph = angle(Y1)\n    ph[ii1] =0\n    ax[1].plot(w,ph,\"r+\")\n    ax[1].set_xlim([-10,10])\n    ax[1].grid(True)\n    ax[1].set_ylabel(r\"Phase of $Y$\",size=16)\n    ax[1].set_xlabel(r\"$\\omega$\",size=16)\n    plt.show()\n    fig2,bx = plt.subplots(2)\n    bx[0].plot(w,abs(ideal(w)))\n    bx[0].set_xlim([-10,10])\n    bx[0].grid(True)\n    bx[0].set_ylabel(r\"$|Y|$\",size=16)\n    bx[0].set_xlabel(r\"$\\omega$\",size=16)\n    bx[0].set_title(r\"Magnitude and Phase plots(ideal) of DFT of $ \\exp(-t^{2}/2)$ \")\n    bx[1].plot(w,angle(ideal(w)),\"r+\")\n    bx[1].set_xlim([-10,10])\n    bx[1].grid(True)\n    bx[1].set_ylabel(r\"Phase of $Y$\",size=16)\n    bx[1].set_xlabel(r\"$\\omega$\",size=16)\n    plt.show()\n\n    \n\n\n# In[6]:\n\n\ntol()\n\n\n# # Conclusions\n# * From the above pairs of plots, it is clear that with a sufficiently large window size and sampling rate, the DFT approximates the CTFT of the gaussian.\n# * This is because the magnitude of the gaussian quickly approaches $0$ for large values of time. This means that there is lesser frequency domain aliasing due to windowing. This can be interpreted as follows: \n# * Windowing in time is equivalent to convolution with a sinc in frequency domain. A large enough window means that the sinc is tall and thin. This tall and thin sinc is approximately equivalent to a delta function for a sufficiently large window. This means that convolution with this sinc does not change the spectrum much.\n# * Sampling after windowing is done so that the DFT can be calculated using the Fast Fourier Transform. This is then a sampled version of the DTFT of the sampled time domain signal. With sufficiently large sampling rates, this approximates the CTFT of the original time domain signal.\n# * This process is done on the gaussian and the results are in agreement with what is expected.\n", "meta": {"hexsha": "b1f7d6af81cd8057172156470149fa026be47b0b", "size": 8246, "ext": "py", "lang": "Python", "max_stars_repo_path": "week8/code8.py", "max_stars_repo_name": "suhas1999/EE2703", "max_stars_repo_head_hexsha": "e508f61d7af0c2445c6b30c465eca3fad455f853", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week8/code8.py", "max_issues_repo_name": "suhas1999/EE2703", "max_issues_repo_head_hexsha": "e508f61d7af0c2445c6b30c465eca3fad455f853", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week8/code8.py", "max_forks_repo_name": "suhas1999/EE2703", "max_forks_repo_head_hexsha": "e508f61d7af0c2445c6b30c465eca3fad455f853", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1441441441, "max_line_length": 552, "alphanum_fraction": 0.6542566093, "include": true, "reason": "import numpy", "num_tokens": 2718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377261041521, "lm_q2_score": 0.918480237330998, "lm_q1q2_score": 0.8803979581628568}}
{"text": "import numpy as np\n\ndef to_polar(x, y):\n\t\"\"\"\n\tTake two numbers or np arrays and return polar representation\n\tof the comblex number(s) x + Iy\n\tReturn:\n\t\ttuple (r, arg)\n\t\"\"\"\n\tr = np.sqrt(x**2 + y**2)\n\targ = np.arctan2(y, x)\n\treturn r, arg\n\ndef to_cartisian(r, theta):\n\t\"\"\"\n\tTake two numbers or np arrays and return cartisian representation\n\tof the comblex number(s) r*exp(i*theta)\n\tReturn:\n\t\ttuple (x, y)\n\t\"\"\"\n\tx = r*np.cos(theta)\n\ty = r*np.sin(theta)\n\treturn (x, y)\n\n######################## FUNCTION DEFINITIONS #################################\n\ndef complex_log(r, theta, polar=True):\n\t\"\"\"\n\treturns complex logarithm as an ordered pair (u, v)\n\tfor a result u + Iv in complex plane.\n\tInput:\n\t\tIf polar is True, then input (r, theta) is represented as\n\t\tr*e^(i*theta) else the complex representation is taken as r + I*theta\n\t\"\"\"\n\tif not polar:\n\t\tr, theta = to_polar(r, theta)\n\tu = np.log(r)\n\tv = theta\n\treturn u, v\n\ndef complex_sqrt(r, theta, polar=True):\n\t\"\"\"\n\treturns complex square root as an ordered pair (u, v)\n\tfor a result u + Iv in complex plane\n\tInput:\n\t\tIf polar is True, then input is (r, theta)\n\t\telse input is (x, y)\n\t\"\"\"\n\tif not polar:\n\t\tr, theta = to_polar(r, theta)\n\tu = np.sqrt(r)*np.cos(theta/2)\n\tv = np.sqrt(r)*np.sin(theta/2)\n\treturn u, v\n\ndef f1(r, theta, polar=True):\n\t\"\"\"\n\tf(z) = sqrt(z**2 + 1)\n\t\"\"\"\n\tif not polar:\n\t\tr, theta = to_polar(r, theta)\n\tx = r**2 * np.cos(2*theta) + 1\n\ty = r**2 * np.sin(2*theta)\n\tu, v = complex_sqrt(x, y, polar=False)\n\treturn u, v\n\n########################## CONTOUR DEFINITIONS #################################\n\ndef contour_circle(x0, y0, r0, theta):\n\t\"\"\"\n\treturns contour as tuple of numpy arrays\n\tthe length of contour is equal to tat of \n\ttheta. theta should be a numpy array\n\tThe contour is a circle centered at (x0, y0) \n\twith radius r0.\n\tReturns: \n\t\tordered pain of cartitian form of complex\n\t\tnumber : (x, y)\n\t\"\"\"\n\tR = np.sqrt(x0**2 + y0**2)\n\tangle = np.arctan2(y0, x0)\n\n\tx = (R*np.cos(angle) + r0*np.cos(theta))\n\ty = (R*np.sin(angle) + r0*np.sin(theta))\n\treturn (x, y)\n\ndef contour_rectangle(x0, y0, l, b, n):\n\t\"\"\"\n\tReturns rectangle contour as (x, y)\n\tInput:\n\t\tx0, y0 : coordinate of upper left corner\n\t\tl, b : length and breadth\n\t\tn : number of samples\n\t\"\"\"\n\t# sharing n over l and b\n\tnl = int(n/2 * l/(l+b))\n\tnb = int(n/2 * b/(l+b)) + 1\n\tl1x = np.linspace(x0, x0+l, nl)\n\tl1y = np.ones(nl)*y0\n\tl2x = l1x[::-1]\n\tl2y = np.ones(nl)*(y0-b)\n\tb1x = np.ones(nb)*(x0+l)\n\tb1y = np.linspace(y0, y0-b, nb)\n\tb2x = np.ones(nb)*x0\n\tb2y = b1y[::-1]\n\tx = np.concatenate([l1x, b1x, l2x, b2x])\n\ty = np.concatenate([l1y, b1y, l2y, b2y])\n\t# x = np.concatenate([b1x[nb//2:0:-1], l1x[::-1], b2x[::-1], l2x[::-1], b1x[-1:nb//2 -15:-1]])\n\t# y = np.concatenate([b1y[nb//2:0:-1], l1y[::-1], b2y[::-1], l2y[::-1], b1y[-1:nb//2 -15:-1]])\n\n\treturn (x, y)\n\n#################################################################################\n", "meta": {"hexsha": "39ebcd0a6ec7fcb4d3816711d09cf8cce2ae5204", "size": 2872, "ext": "py", "lang": "Python", "max_stars_repo_path": "Mathematics/complex_numbers/contour_plot/definitions.py", "max_stars_repo_name": "muhsinibnalazeez/MyPhysics", "max_stars_repo_head_hexsha": "46818eb405c283c563231d1816eab1f60f39b898", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Mathematics/complex_numbers/contour_plot/definitions.py", "max_issues_repo_name": "muhsinibnalazeez/MyPhysics", "max_issues_repo_head_hexsha": "46818eb405c283c563231d1816eab1f60f39b898", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mathematics/complex_numbers/contour_plot/definitions.py", "max_forks_repo_name": "muhsinibnalazeez/MyPhysics", "max_forks_repo_head_hexsha": "46818eb405c283c563231d1816eab1f60f39b898", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4159292035, "max_line_length": 95, "alphanum_fraction": 0.5759052925, "include": true, "reason": "import numpy", "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762057376384, "lm_q2_score": 0.9173026528034426, "lm_q1q2_score": 0.8803922812914469}}
{"text": "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport scipy.linalg as la\nfrom scipy.linalg import svd, norm\n\n\ndef truncated_svd(A,r=None,tol=10**-6):\n    '''\n    Computes the truncated SVD of A. If r is None or equals the number of nonzero singular values, it is the compact SVD.\n    Parameters:\n        A: the matrix\n        r: the number of singular values to use \n        tol: the tolerance for zero\n    Returns:\n        U - the matrix U in the SVD\n        s - the diagonals of Sigma in the SVD\n        Vh - the matrix V^H in the SVD\n    '''\n    #Initialize things\n    m,n = A.shape\n\n    #Find eigenvalues and eigenvectors of A^H A\n    eigs, vr = la.eig(A.conj().T.dot(A)) \n    #Find singular values\n    sigs = np.sqrt(eigs) \n    #Find how many singular values are nonzero\n    mask = sigs > tol \n    num_eigs = np.sum(mask)\n    if (r==None):\n        #Return compact SVD\n        r=num_eigs\n    elif (num_eigs < r):\n        print 'less nonzero eigenvalues than given size'\n        return\n    #Initialize things\n    U = np.empty((m,r))\n    s = np.zeros(r)\n    V = np.empty((n,r))\n    \n    \n    #Sort the singular values and only keep the greatest r\n    sorted_index = np.argsort(sigs)[::-1]\n    sigs = sigs[sorted_index]\n    s[:r] = sigs[:r]\n    #Keep eigenvectors matching the order of the singular values\n    vr = vr[:,sorted_index]\n    \n    #Calculate V\n    #Only keep the first r columns corresponding to the first r singular values\n    V = vr[:,:r]\n\n    #Calculate U\n    #The first r columns are 1/sigma*A V_i where V_i is the ith column of V.\n    #Only use columns that correspond to the first r singular values\n    U = 1./sigs[:r]*A.dot(V[:,:r])\n    \n    return U, s, V.conj().T\n\ndef svd_approx(A, k):\n    '''\n    Calculate the best rank k approximation to A with respect to the induced\n    2-norm. Use the SVD.\n    Inputs:\n        A -- array of shape (m,n)\n        k -- positive integer\n    Returns:\n        Ahat -- best rank k approximation to A obtained via the SVD\n    '''\n    #compute the reduced SVD\n    U,s,Vh = svd(A,full_matrices=False)\n    \n    #keep only the first k singular values\n    S = np.diag(s[:k])\n    \n    #reconstruct the best rank k approximation\n    return U[:,:k].dot(S).dot(Vt[:k,:])\n    \ndef plot_svd():\n\tA = np.array([[3,1],[1,3]])\n\tU, S, V = truncated_svd(A)\n\tS = np.diag(S)\n\t\n\tt = np.linspace(0,2*np.pi,100)\n\tpts = np.array([np.cos(t),np.sin(t)])\n\tv= V.dot(pts)\n\tsv = S.dot(v)\n\ta = U.dot(sv)\n\t\n\tunit_vecs = np.array([[1,0],[0,1]])\n\tvu = V.dot(unit_vecs)\n\tsvu = S.dot(vu)\n\tau = U.dot(svu)\n\t\n\tplt.subplot(221)\n\tplt.plot(pts[0],pts[1],'b')\n\tplt.plot([0,unit_vecs[0,0]],[0,unit_vecs[1,0]],'g')\n\tplt.plot([0,unit_vecs[0,1]],[0,unit_vecs[1,1]],'g')\n\tplt.axis('equal')\n\n\tplt.subplot(222)\n\tplt.plot(v[0],v[1],'b')\n\tplt.plot([0,vu[0,0]],[0,vu[1,0]],'g')\n\tplt.plot([0,vu[0,1]],[0,vu[1,1]],'g')\n\tplt.axis('equal')\n\n\tplt.subplot(223)\n\tplt.plot(sv[0],sv[1],'b')\n\tplt.plot([0,svu[0,0]],[0,svu[1,0]],'g')\n\tplt.plot([0,svu[0,1]],[0,svu[1,1]],'g')\n\tplt.axis('equal')\n\t\n\tplt.subplot(224)\n\tplt.plot(a[0],a[1],'b')\n\tplt.plot([0,au[0,0]],[0,au[1,0]],'g')\n\tplt.plot([0,au[0,1]],[0,au[1,1]],'g')\n\tplt.axis('equal')\n\tplt.show()\n    \ndef lowest_rank_approx(A,e):\n    '''\n    Calculate the lowest rank approximation to A that has error strictly less than e.\n    Inputs:\n        A -- array of shape (m,n)\n        e -- positive floating point number\n    Returns:\n        Ahat -- the best rank s approximation of A constrained to have error less than e, \n                where s is as small as possible.\n    '''\n    #calculate the reduced SVD\n    U,s,Vh = svd(A,full_matrices=False)\n    \n    #find the index of the first singular value less than e\n    k = np.where(s<e)[0][0] \n    \n    #now recreate the rank k approximation\n    S = np.diag(s[:k])\n    return U[:,:k].dot(S).dot(Vt[:k,:])\n    \n\ndef readimg(filename, channel=None):\n    if channel is not None:\n        return sp.misc.imread(filename)[:,:,channel]\n    else:\n        return sp.misc.imread(filename)\n\n\ndef compressSVD(filename, rank, random=False, channel=None):\n    img = readimg(filename, channel)\n\n    try:\n        isize = img[:,:,0].shape\n        colors = [la.svd(img[:,:,i]) for i in range(3)]\n    except IndexError:\n        isize = img.shape\n        plt.gray()\n        colors = la.svd(img)\n\n    plt.ion()\n    imgc = plt.imshow(img)\n    newimg = sp.zeros_like(img)\n\n    rank = range(1,rank+1)\n\n    if random is True:\n        sp.random.shuffle(rank)\n\n    for r in rank:\n        col_res = hat(colors, r-1, r)\n        try:\n            #col_res[0] = sp.where(col_res[0]>255, col_res[0], 255)\n            #col_res[1] = sp.where(col_res[1]>255, col_res[1], 255)\n            #col_res[2] = sp.where(col_res[2]>255, col_res[2], 255)\n\n            #col_res[0] = sp.where(col_res[0]<0, col_res[0], 0)\n            #col_res[1] = sp.where(col_res[1]<0, col_res[1], 0)\n            #col_res[2] = sp.where(col_res[2]<0, col_res[2], 0)\n            \n            newimg[:,:,0] += col_res[0]\n            newimg[:,:,1] += col_res[1]\n            newimg[:,:,2] += col_res[2]\n\n            ## for ch in range(3):\n            ##     newimg[newimg[:,:,ch]<1]=0\n            ##     newimg[newimg[:,:,ch]>254]=255\n                \n        except IndexError:\n            newimg += col_res[0]\n            ## newimg[newimg<1]=0\n            ## newimg[newimg>254]=255\n        \n        imgc.set_data(newimg)\n        plt.draw()\n    plt.ioff()\n    plt.show()\n\n    return newimg\n\n\ndef hat(color_svd, lrank, urank):\n    results = []\n    if len(color_svd) == 3:\n        r = 3\n    else:\n        r = 1\n        \n    for c in range(r):\n        U = color_svd[c][0]\n        S = sp.diag(color_svd[c][1])\n        Vt = color_svd[c][2]\n        results.append(U[:,lrank:urank].dot(S[lrank:urank, lrank:urank]).dot(Vt[lrank:urank,:]))\n        \n    return results\n    \ndef matrix_rank(X):\n    \"\"\"Compute the rank of a matrix using the SVD\"\"\"\n    \n    S = la.svd(X, compute_uv=False)\n    tol = S.max()*sp.finfo(S.dtype).eps\n    return sum(S>tol)\n", "meta": {"hexsha": "2aa472f8875301718518d6d8e64147e9c311c30a", "size": 5986, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/SVD/SVD.py", "max_stars_repo_name": "jessicaleete/numerical_computing", "max_stars_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Labs/SVD/SVD.py", "max_issues_repo_name": "jessicaleete/numerical_computing", "max_issues_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/SVD/SVD.py", "max_forks_repo_name": "jessicaleete/numerical_computing", "max_forks_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 27.0859728507, "max_line_length": 121, "alphanum_fraction": 0.5674908119, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288128, "lm_q2_score": 0.9196425322789908, "lm_q1q2_score": 0.8803533868263493}}
{"text": "import numpy as np\n\nfrom hand_crafted_models.loss_functions import mean_squared_error\nfrom hand_crafted_models.optimization import (\n    gradient_descent, closed_form_linear_algebra, GradientStep, WeightsAndBias,\n)\nfrom hand_crafted_models.utils import forward_pass\n\n\ndef _step(\n        x: np.ndarray,\n        y: np.ndarray,\n        weights: np.ndarray,\n        bias: np.ndarray,\n        one: np.ndarray\n) -> GradientStep:\n    \"\"\"\n    Mean-squared-error: Calculate gradients for a given step.\n    \n    :param x: Input data [Batch, Features]\n    :param y: Label data [Batch, 1]\n    :param weights: Feature parameters [1, Features]\n    :param bias: Bias parameter [1, 1]\n    :param one: (Ignore) Vector of ones\n    :return: step loss, weight gradients, bias gradient\n    \"\"\"\n    # Get predictions\n    y_hat = forward_pass(x=x, weights=weights, bias=bias)\n    # Calculate total loss value for current parameter values (e.g., MSE cost fn)\n    loss = mean_squared_error(y_hat=y_hat, y=y)\n    # Perform back-propagation to parameters\n    # The MSE derivative\n    d_y = 2 * (y - y_hat)  # [B, 1]\n    # The Weights derivative w.r.t. MSE loss fn\n    d_w = d_y.T @ x  # [1, B] @ [B, N] -> [1, N]\n    # The Bias derivative w.r.t. MSE loss fn\n    d_b = d_y.T @ one  # [B, 1] -> [1]\n    return loss, d_w, d_b\n\n\ndef get_beta_sgd(\n        x: np.ndarray,\n        y: np.ndarray,\n        lr: float = 0.001,\n        tol: float = 1e-6,\n        max_grad: float = 10.0,\n        max_loops: int = 10000\n) -> WeightsAndBias:\n    \"\"\"\n    Fit parameters using gradient descent.\n    \n    :param x: Input data [Batch, Features]\n    :param y: Label data [Batch, 1]\n    :param lr: Learning rate (i.e., optimizer step size)\n    :param tol: Tolerance for early-stopping\n    :param max_grad: (Optional) Max size of gradient\n    :param max_loops: Maximum number of steps to take\n    :return: weight gradients, bias gradient\n    \"\"\"\n    return gradient_descent(\n        x=x,\n        y=y,\n        fn=_step,\n        lr=lr,\n        tol=tol,\n        max_grad=max_grad,\n        max_loops=max_loops\n    )\n\n\ndef get_beta_linalg(\n        x: np.ndarray,\n        y: np.ndarray,\n        add_bias: bool = True\n) -> WeightsAndBias:\n    \"\"\"\n    Fit parameters using matrices and linear algebra.\n    \n    :param x: Input data [Batch, Features]\n    :param y: Label data [Batch, 1]\n    :param add_bias: If 'true', append a column of ones to use for the bias\n    :return: weight gradients, bias gradient\n    \"\"\"\n    return closed_form_linear_algebra(\n        x=x,\n        y=y,\n        add_bias=add_bias\n    )\n", "meta": {"hexsha": "899a2e344860705f199771fb8bbd22a0b0178891", "size": 2555, "ext": "py", "lang": "Python", "max_stars_repo_path": "hand_crafted_models/linear_regression.py", "max_stars_repo_name": "sadighian/hand_crafted_models", "max_stars_repo_head_hexsha": "aea75892ea183bc0f7f10781400c5d47de078e5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-08-24T19:03:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T04:17:07.000Z", "max_issues_repo_path": "hand_crafted_models/linear_regression.py", "max_issues_repo_name": "sadighian/hand_crafted_models", "max_issues_repo_head_hexsha": "aea75892ea183bc0f7f10781400c5d47de078e5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hand_crafted_models/linear_regression.py", "max_forks_repo_name": "sadighian/hand_crafted_models", "max_forks_repo_head_hexsha": "aea75892ea183bc0f7f10781400c5d47de078e5e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7078651685, "max_line_length": 81, "alphanum_fraction": 0.6234833659, "include": true, "reason": "import numpy", "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.9161096101538325, "lm_q1q2_score": 0.8803370918782875}}
{"text": "import numpy as np\n\ndef sigmoid(x):\n    return 1/(1 + np.exp(-x))\n\ndef identity_function(x):\n    return x\n\ndef softmax_ng(a):\n    exp_a = np.exp(a)\n    sum_exp_a = np.sum(exp_a)\n    y = exp_a /sum_exp_a\n\n    return y\n\ndef softmax(a):\n    c = np.max(a)\n    exp_a = np.exp(a - c) # prevent overflow\n    sum_exp_a = np.sum(exp_a)\n    y = exp_a / sum_exp_a\n\n    return y\n\ndef mean_squared_error(y, t):\n    return 0.5 * np.sum((y-t)**2)\n\n# def cross_entropy_error(y, t):\n#     delta = 1e-7\n#     return -np.sum(t * np.log(y + delta))\n\ndef cross_entropy_error(y, t):\n    if y.ndim == 1:\n        t = t.reshape(1, t.size)\n        y = y.reshape(1, y.size)\n\n    delta = 1e-7\n    batch_size = y.shape[0]\n    return -np.sum(t * np.log(y + delta)) / batch_size\n\n# def cross_entropy_error(y, t):\n#     if y.ndim == 1:\n#         t = t.reshape(1, t.size)\n#         y = y.reshape(1, y.size)\n#\n#     batch_size = y.shape[0]\n#     return -np.sum(np.log(y[np.arrange(batch_size), t])) / batch_size\n\ndef numerical_diff(f, x):\n    h = 1e-4\n    return (f(x+h) - f(x-h)) / (2*h)\n", "meta": {"hexsha": "0cc4b7fb50766d7ac4698b8eb27e5de1546d49e2", "size": 1055, "ext": "py", "lang": "Python", "max_stars_repo_path": "function.py", "max_stars_repo_name": "karaage0703/zero-deeplearning", "max_stars_repo_head_hexsha": "8b6e4550d14819c2b4f3114405af15e78c700a33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "function.py", "max_issues_repo_name": "karaage0703/zero-deeplearning", "max_issues_repo_head_hexsha": "8b6e4550d14819c2b4f3114405af15e78c700a33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "function.py", "max_forks_repo_name": "karaage0703/zero-deeplearning", "max_forks_repo_head_hexsha": "8b6e4550d14819c2b4f3114405af15e78c700a33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6862745098, "max_line_length": 71, "alphanum_fraction": 0.5658767773, "include": true, "reason": "import numpy", "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561676667174, "lm_q2_score": 0.9086178901278738, "lm_q1q2_score": 0.8803200469027103}}
{"text": "import numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport time\n\ndef dn_sin(n):\n\t'''\n\tCompute the n^th derivative of sin(x) at x=0\n\n\tinput:\n\t\tn - int: the order of the derivative to compute\n\toutput:\n\t\tfloat nth derivative of sin(0)\n\tpurpose:\n\t\tproblem 1) Write a python function dn_sin0(n) to evaluate the  nth  derivate of  sin(0). \n\t\tThis should provide a chance to use the if-elif-else control structure.\n\t'''\n\n\tx = 0\n\tif n%4 == 1: return np.cos(x)\n\telif n%4 == 2: return -np.sin(x)\n\telif n%4 == 3: return -np.cos(x)\n\telse: return np.sin(x)\n\t# pass\n\ndef taylor_sin(x, n):\n\t'''\n\tEvaluate the Taylor series of sin(x) about x=0 neglecting terms of order x^n\n\t\n\tinput:\n\t\tx - float: argument of sin\n\t\tn - int: number of terms of the taylor series to use in approximation\n\toutput:\n\t\tfloat value computed using the taylor series truncated at the nth term\n\t'''\n\ty = 0\n\tfor k in range(n):\n\t\ty += dn_sin(k) * (x**k) / math.factorial(k) \n\treturn y\n\t# pass\n\n\ndef measure_diff(ary1, ary2):\n\t'''\n\tCompute a scalar measure of difference between 2 arrays\n\n\tinput:\n\t\tary1 - numpy array of float values\n\t\tary2 - numpy array of float values\n\toutput:\n\t\ta float scalar quantifying difference between the arrays\n\t'''\n\tdiff = ary1 - ary2\n\treturn np.sum(np.absolute(diff))\n\t# pass\n\n\ndef escape(cx, cy, dist,itrs, x0=0, y0=0):\n\t'''\n\tCompute the number of iterations of the logistic map, \n\tf(x+j*y)=(x+j*y)**2 + cx +j*cy with initial values x0 and y0 \n\twith default values of 0, to escape from a cirle centered at the origin.\n\n\tinputs:\n\t\tcx - float: the real component of the parameter value\n\t\tcy - float: the imag component of the parameter value\n\t\tdist: radius of the circle\n\t\titrs: int max number of iterations to compute\n\t\tx0: initial value of x; default value 0\n\t\ty0: initial value of y; default value 0\n\treturns:\n\t\tan int scalar interation count\n\t'''\n\tx = x0\n\ty = y0\n\tr = 0\n\tfor i in range(itrs):\n\t\tr = math.sqrt(x**2 + y**2)\n\t\tif dist > r:\n\t\t\tx_n = x**2 - y**2 + cx \n\t\t\ty_n = 2*x*y + cy\n\t\t\tx = x_n\n\t\t\ty = y_n\n\t\telse: return i\n\treturn 0\n\t# pass\n\t# \n    # xtemp := x×x - y×y + x0\n    # y := 2×x×y + y0\n    # x := xtemp\n    # iteration := iteration + 1\n\ndef mandelbrot(cx,cy,dist,itrs):\n\t'''\n\tCompute escape iteration counts for an array of parameter values\n\n\tinput:\n\t\tcx - array: 1d array of real part of parameter\n\t\tcy - array: 1d array of imaginary part of parameter\n\t\tdist - float: radius of circle for escape\n\t\titrs - int: maximum number of iterations to compute\n\toutput:\n\t\ta 2d array of iteration count for each parameter value (indexed pair of values cx, cy)\n\t'''\n\t#create a 2D numpy array (init to zero) to store n_ss values at each of the m values of r.\n\t# x = numpy.zeros([m,n_ss])\n\tf = np.zeros([len(cx), len(cy)])\n\tfor i in range(len(cx)):\n\t\tfor j in range(len(cy)):\n\t\t\tf[i][j] = escape(cx[i], cy[j], dist, itrs)\n\treturn f\n\t# pass\n\n\nif __name__ == '__main__':\n\t# problem 1\n\tprint('Problem 1')\n\t# print(dn_sin.__doc__)\n\tprint(dn_sin(1)) # first: 1\n\n\n\t#Problem 2/3\n\tprint('Problem 2/3')\t\n\tx = np.linspace(-2, 2, 100)\n\tfor n in range(2,16,2): #for n in len(range(2,16,2)):\n\t\t#compute taylor series\n\t\ty = []\n\t\tfor i in range(len(x)):\n\t\t\tx_i = x[i]\n\t\t\ty.append(taylor_sin(x_i, n)) #collect list of y in n's row\n\t\t#plot taylor series\t\n\t\tplt.plot(x, y, label = n) # colect plot for n_th terms\n\tplt.plot(x, np.sin(x), label = 'sin(x)')\n\tplt.figure(1)\n\tplt.legend()\n\tplt.xlabel('x')\n\tplt.ylabel('y')\n\tplt.title('Taylor series (n = num of term)')\t\n\tplt.show()\n\t\n\n\t#Problem 4\n\tprint('Problem 4')\t\n\t# diff measure to be less than 1e-2\n\t# use diff fn.\n\t# evaluate your functions at 50 points equally spaced across the interval [0,pi/4]\n\tx = np.linspace(0, np.pi/4, 50)\n\ty0 = np.sin(x)\n\tdiff = 100\n\tn = 0\n\twhile diff > 10**-2:\n\t\tn += 1\t\n\t\ty = []\n\t\tfor i in range(len(x)):\n\t\t\tx_i = x[i]\n\t\t\ty.append(taylor_sin(x_i, n))\n\t\tdiff = measure_diff(y, y0)\n\tprint('current difference = ', diff)\n\tprint('truncation order = ', n)\n\n\n\t# problem 5\n\tprint('Problem 5')\t\n\tnx = 512\n\tny = 512\n\tunit_away = 2.5\n\ti = 256\n\n\tx = np.linspace(-2, 1, nx)\n\ty = np.linspace(-1.5, 1.5, ny)\n\t# print time required to comput 512 x 512\n\tt0 = time.time()\n\tf = mandelbrot(x, y, unit_away, i)\n\tt1 = time.time() - t0\n\tprint('Time took for calcualting mandelbrot (second) = ', t1)\n\tprint(\"1(yellow) part is where it can escape.\")\n\tprint('0(purbpe) part where it cannot escape')\n\n\tfor i in range(len(x)):\n\t\tfor j in range(len(y)):\n\t\t\tif f[i][j] > 0: f[i][j] = 1\n\n\t# plot\n\tplt.figure(2)\n\tplt.imshow(f.T, extent = (-2.5, 2.5, -2.5, 2.5))\n\tplt.xlabel('')\n\tplt.ylabel('')\n\tplt.title('Mandelbrot graph')\t\n\tplt.show()\n\t# plt.colorbar()\n\n\t# A map is a function: it takes an input value (and possibly paramter values) and returns an output value\n\t# rewrite the map\n", "meta": {"hexsha": "cf193c7f58a9c5d7eefc1f570b7db3c2814c27cf", "size": 4709, "ext": "py", "lang": "Python", "max_stars_repo_path": "P1.py", "max_stars_repo_name": "bmaxdk/applied-parallel-computing", "max_stars_repo_head_hexsha": "8140f12476c6e47d651ca632e0210ed7f0c0ef4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-07T04:10:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-07T04:10:29.000Z", "max_issues_repo_path": "P1.py", "max_issues_repo_name": "bmaxdk/applied-parallel-computing", "max_issues_repo_head_hexsha": "8140f12476c6e47d651ca632e0210ed7f0c0ef4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P1.py", "max_forks_repo_name": "bmaxdk/applied-parallel-computing", "max_forks_repo_head_hexsha": "8140f12476c6e47d651ca632e0210ed7f0c0ef4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2731958763, "max_line_length": 106, "alphanum_fraction": 0.6476959015, "include": true, "reason": "import numpy", "num_tokens": 1553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993888, "lm_q2_score": 0.9207896775212233, "lm_q1q2_score": 0.8802577625733207}}
{"text": "# when use t test?\n# two independent group\n# sample not larger than 30\nimport numpy as np\nfrom scipy import stats\n\ndef t_value(X1, X2):\n    \"\"\"\n            (n1-1)*s1_var + (n2-1)*s2_var \n    temp1 = --------------------------------\n                    n1 + n2 - 2\n\n              n1 + n2\n    temp2 = ------------\n              n1 * n2\n\n            X1_bar - X2_bar\n    t = ------------------------\n          sqrt(temp1 * temp2)\n    \"\"\"\n    X1_bar = np.mean(X1)\n    X2_bar = np.mean(X2)\n    s1_var = np.var(X1)\n    s2_var = np.var(X2)\n    n1 = X1.shape[0]\n    n2 = X2.shape[0]\n    temp1 = ((n1 - 1) * s1_var + (n2 - 1) * s2_var) / (n1 + n2 - 2)\n    temp2 = (n1 + n2) / (n1 * n2)\n    t = (X1_bar - X2_bar) / np.sqrt(temp1 * temp2)\n    return t\n\ndef t_value_test():\n    X1 = np.array([\n        7, 5, 5, 3, 4, 7, 3, 6, 1, 2, \n        10, 9, 3, 10, 2, 8, 5, 5, 8, 1, \n        2, 5, 1, 12, 8, 4, 15, 5, 3, 4,\n    ])\n    X2 = np.array([\n        5, 3, 4, 4, 2, 3, 4, 5, 2, 5,\n        4, 7, 5, 4, 6, 7, 6, 2, 8, 7, \n        8, 8, 7, 9, 9, 5, 7, 8, 6, 6,\n    ])\n    t = t_value(X1, X2)\n    print(\"t_58 = %.2f, p > .05\" % t)\n\n    # so t = -0.14\n    # what's the threshold when significant level is 5%?\n    left, right = stats.t.interval(0.95, df=58)\n    print('confident interval [%.3f, %.3f]' % (left, right))\n    if left < t < right:\n        msg = (\"t value live in the confident interval, \"\n            \"accept the original hypothesis\")\n    else:\n        msg = ('t value live out of confident interval, '\n            'reject the original hypothesis')\n    print(msg)\n\n\ndef effect_size(X1, X2):\n    \"\"\"\n               X1_bar - X2_bar\n    ES = ---------------------------\n         sqrt[(X1_var + X2_var) / 2]\n    \"\"\"\n    X1_bar = np.mean(X1)\n    X2_bar = np.mean(X2)\n    X1_var = np.var(X1)\n    X2_var = np.var(X2)\n    ES = (X1_bar - X2_bar) / np.sqrt((X1_var + X2_var) / 2)\n    return ES\n\nif __name__ == '__main__':\n    t_value_test()", "meta": {"hexsha": "6ea42317d59614b0175ebff2511c4904d2825007", "size": 1922, "ext": "py", "lang": "Python", "max_stars_repo_path": "books/master/statistic/t_test_independent.py", "max_stars_repo_name": "Bingwen-Hu/hackaway", "max_stars_repo_head_hexsha": "69727d76fd652390d9660e9ea4354ba5cc76dd5c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "books/master/statistic/t_test_independent.py", "max_issues_repo_name": "Bingwen-Hu/hackaway", "max_issues_repo_head_hexsha": "69727d76fd652390d9660e9ea4354ba5cc76dd5c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "books/master/statistic/t_test_independent.py", "max_forks_repo_name": "Bingwen-Hu/hackaway", "max_forks_repo_head_hexsha": "69727d76fd652390d9660e9ea4354ba5cc76dd5c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3287671233, "max_line_length": 67, "alphanum_fraction": 0.4562955255, "include": true, "reason": "import numpy,from scipy", "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9759464450067471, "lm_q2_score": 0.9019206837793828, "lm_q1q2_score": 0.8802262850125432}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef myf(x):\n    return np.exp(2*x)\n\ndef myf3derivative(x):\n    return 6*np.exp(2*x)\n\ndef delta(f,x,m,h):\n    if m> 1:\n        return (delta(f, x+h/2, m-1, h) - delta(f, x-h/2, m-1, h))/(h)\n    else:\n        return (f(x+(h/2))-f(x-(h/2)))/h\n    \ndef centralDiffErr(f,x,C,h):\n    return ((2*C*np.abs(f(x)))/h) + (1/24)*(h**2)*(np.abs(delta(myf,x,3,h)))\n\ndef optimalError(f,f3,x,C):\n    return ((9/8)*(C**2)*(f(x)**2)*f3(x))**(1/3)\n\n#creating a list of number that increase by a factor of 10\nhRange = [10**i for i in range(-16,1)]\n\n#using delta to find the first derivative approximation at x = 0\n#using central difference method given on the lab 3 document.\n#Then find the absolute difference from known solution, 2.\ndiffFrom2 = [np.abs(delta(myf, 0, 1, i) - 2) for i in hRange]\n\n#graphing part a\nfig1, graph = plt.subplots(figsize=(6, 4), dpi=80)\ngraph.plot(np.arange(-16,1), diffFrom2)\ngraph.set(xlabel=\"Power of h (step size)\", ylabel=\"Absolute difference from 2\",\n       title=\"Absolute error of each \\nderivative over step size\")\ngraph.grid()\nfig1.savefig(\"q3_A.png\")\n\n#constant taken from lab manuel\nC1 = 10**-16\n#calculations for part (a)\nprint(\"centtal difference error calculation from textbook\",[centralDiffErr(myf, 0, C1, i) for i in hRange])\nprint(\"value of h that produced the least difference from 2:\", hRange[diffFrom2.index(np.min(diffFrom2))])\nprint(\"Min difference from our calculation:\", np.min(diffFrom2))\nprint(\"Optimal error from equation 5.101:\", optimalError(myf, myf3derivative, 0, C1))\n\n\n#Part B\ndef cauchy(f,z,m,N):\n    coefficients = (float(np.math.factorial(m)))/N\n    summation = 0\n    for k in range(0, N):\n        zk = np.exp(1j*2*np.pi*k/N)\n        summation += f(zk)*np.exp(-1j*2*np.pi*k*m/N)\n    return (coefficients*summation).real\n\n#Setting up constants and ranges\nN = 10000 #number of summation for Cauchy formula\ncorrectDerivative = np.asarray([2**m for m in range(1,11)]) #list of correct result of m-th derivatives\ncentralDiffResults = np.abs(np.asarray([delta(myf,0,m,0.1) for m in range(1,11)]) - correctDerivative)\ncauchyResults = np.abs(np.asarray([cauchy(myf, 0, m, N) for m in range(1,11)]) - correctDerivative)\n\n#graphing part b\nfig2, graph = plt.subplots(figsize=(6, 4), dpi=80)\ngraph.plot(np.arange(1,11), centralDiffResults)\ngraph.set(xlabel=\"mth derivative (step size)\", ylabel=\"Absolute difference\",\n       title=\"Absolute error of each derivative using\\n Central Difference over step size\")\ngraph.grid()\nfig2.savefig(\"q3_B_1.png\")\n\nfig3, graph = plt.subplots(figsize=(6, 4), dpi=80)\ngraph.plot(np.arange(1,11), cauchyResults)\ngraph.set(xlabel=\"mth derivative (step size)\", ylabel=\"absolute difference\",\n       title=\"Absolute error of each derivative using\\n Cauchy Formula over step size\")\ngraph.grid()\nfig3.savefig(\"q3_B_2.png\")\n", "meta": {"hexsha": "1d94cb232cc1b4262c4cc5e3addbf19a26fafd53", "size": 2835, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab3/Lab3_Q3.py", "max_stars_repo_name": "fancent/PHY407", "max_stars_repo_head_hexsha": "38ce8badb9537060becc255ec64e6de2968ca73c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-20T17:30:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-20T17:30:06.000Z", "max_issues_repo_path": "Lab3/Lab3_Q3.py", "max_issues_repo_name": "fancent/PHY407", "max_issues_repo_head_hexsha": "38ce8badb9537060becc255ec64e6de2968ca73c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab3/Lab3_Q3.py", "max_forks_repo_name": "fancent/PHY407", "max_forks_repo_head_hexsha": "38ce8badb9537060becc255ec64e6de2968ca73c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-12T14:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T14:21:13.000Z", "avg_line_length": 37.3026315789, "max_line_length": 107, "alphanum_fraction": 0.6881834215, "include": true, "reason": "import numpy", "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347845918813, "lm_q2_score": 0.9032942151647514, "lm_q1q2_score": 0.880201303977157}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nx = np.linspace(0,3,100)\r\ny=x**3 -2*x**2 -x + 2\r\n\r\nfig = plt.figure()\r\naxdef = fig.add_subplot(1, 1, 1)\r\naxdef.spines['left'].set_position('center')\r\naxdef.spines['bottom'].set_position('zero')\r\naxdef.spines['right'].set_color('none')\r\naxdef.spines['top'].set_color('none')\r\naxdef.xaxis.set_ticks_position('bottom')\r\naxdef.yaxis.set_ticks_position('left')\r\n\r\nplt.plot(x,y, 'r')\r\nplt.show()\r\n\r\nprint('Value of x at the minimum of the function', x[np.argmin(y)])\r\n\r\nFirstDerivative = lambda x: 3*x**2-4*x -1 \r\nSecondDerivative = lambda x: 6*x-4  \r\n\r\nActualX = 3 \r\nPrecisionValue = 0.000001 \r\nPreviousStepSize = 1 \r\nMaxIteration = 10000 \r\nIterationCounter = 0 \r\n\r\n\r\nwhile PreviousStepSize > PrecisionValue and IterationCounter < MaxIteration:\r\n    PreviousX = ActualX\r\n    ActualX = ActualX - FirstDerivative(PreviousX)/ SecondDerivative(PreviousX)\r\n    PreviousStepSize = abs(ActualX - PreviousX) \r\n    IterationCounter = IterationCounter+1 \r\n    print(\"Number of iterations = \",IterationCounter,\"\\nActual value of x  is = \",ActualX) \r\n    \r\nprint(\"X value of f(x) minimum = \", ActualX)", "meta": {"hexsha": "66340303861cbe45907e4f3706c0568fdb7f3f33", "size": 1139, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter07/Newton-Raphson.py", "max_stars_repo_name": "CiaburroGiuseppe/Hands-On-Simulation-Modeling-with-Python", "max_stars_repo_head_hexsha": "c1cbf02840bb9e634e8f93e653cd8fdabcbcff01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2020-07-29T08:52:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T04:04:56.000Z", "max_issues_repo_path": "Chapter07/Newton-Raphson.py", "max_issues_repo_name": "CiaburroGiuseppe/Hands-On-Simulation-Modeling-with-Python", "max_issues_repo_head_hexsha": "c1cbf02840bb9e634e8f93e653cd8fdabcbcff01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter07/Newton-Raphson.py", "max_forks_repo_name": "CiaburroGiuseppe/Hands-On-Simulation-Modeling-with-Python", "max_forks_repo_head_hexsha": "c1cbf02840bb9e634e8f93e653cd8fdabcbcff01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2020-08-18T16:27:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T03:31:54.000Z", "avg_line_length": 29.9736842105, "max_line_length": 92, "alphanum_fraction": 0.6953467954, "include": true, "reason": "import numpy", "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995762509216, "lm_q2_score": 0.911179716041669, "lm_q1q2_score": 0.8801081016130832}}
{"text": "import numpy as np\n\n### Functions for you to fill in ###\n\n\ndef polynomial_kernel(X, Y, c, p):\n    \"\"\"\n        Compute the polynomial kernel between two matrices X and Y::\n            K(x, y) = (<x, y> + c)^p\n        for each pair of rows x in X and y in Y.\n\n        Args:\n            X - (n, d) NumPy array (n datapoints each with d features)\n            Y - (m, d) NumPy array (m datapoints each with d features)\n            c - a coefficient to trade off high-order and low-order terms (scalar)\n            p - the degree of the polynomial kernel\n\n        Returns:\n            kernel_matrix - (n, m) Numpy array containing the kernel matrix\n    \"\"\"\n    return (np.dot(X, Y.transpose()) + c)**p\n\n\ndef rbf_kernel(X, Y, gamma):\n    \"\"\"\n        Compute the Gaussian RBF kernel between two matrices X and Y::\n            K(x, y) = exp(-gamma ||x-y||^2)\n        for each pair of rows x in X and y in Y.\n\n        Args:\n            X - (n, d) NumPy array (n datapoints each with d features)\n            Y - (m, d) NumPy array (m datapoints each with d features)\n            gamma - the gamma parameter of gaussian function (scalar)\n\n        Returns:\n            kernel_matrix - (n, m) Numpy array containing the kernel matrix\n    \"\"\"\n    # TODO: Work on the pairwise distance\n    # dist = (X.reshape((X.shape[0], X.shape[1], 1)) - Y.transpose()).sum(axis=1)\n\n    # L2 Vectorized distance between matrices\n    dist = -2 * np.dot(X, Y.transpose()) + np.sum(Y**2,\n                                                  axis=1) + np.sum(X**2, axis=1)[:, np.newaxis]\n    return np.exp(-gamma*dist)\n", "meta": {"hexsha": "5bd8fcebf07295e7f19912feea4703cc3f01b1f5", "size": 1582, "ext": "py", "lang": "Python", "max_stars_repo_path": "Projects/Digit Recognition (Project 2-3)/part1/kernel.py", "max_stars_repo_name": "gustavopmachado/MITx6.86x", "max_stars_repo_head_hexsha": "1aaaee49d78f8e540faaf22c71b5de64bbbfb885", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-09-27T02:41:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T14:58:19.000Z", "max_issues_repo_path": "Projects/Digit Recognition (Project 2-3)/part1/kernel.py", "max_issues_repo_name": "gustavopmachado/MITx6.86x", "max_issues_repo_head_hexsha": "1aaaee49d78f8e540faaf22c71b5de64bbbfb885", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Projects/Digit Recognition (Project 2-3)/part1/kernel.py", "max_forks_repo_name": "gustavopmachado/MITx6.86x", "max_forks_repo_head_hexsha": "1aaaee49d78f8e540faaf22c71b5de64bbbfb885", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1555555556, "max_line_length": 95, "alphanum_fraction": 0.5575221239, "include": true, "reason": "import numpy", "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995713428387, "lm_q2_score": 0.9111797166446537, "lm_q1q2_score": 0.8801080977233602}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nEuropean call option by Monte Carlo simulation \n\ntest for vectorized calculation\n\n@author: Minhyun Yoo\n\"\"\"\nimport time\nimport numpy as np\nfrom math import exp, sqrt, log\nfrom scipy import stats\ndef exc_call(S0, E, T, r, sig):\n    d1 = (log(S0/E) + (r + 0.5*sig**2)*T) / (sig*sqrt(T));\n    d2 = d1 - sig * sqrt(T);\n\n    call = ( S0 * stats.norm.cdf(d1, 0.0, 1.0) \n        - E * exp(-r * T) * stats.norm.cdf(d2, 0.0, 1.0) )\n\n    print 'Exact call Price : %.5f\\n' % call\n\ndef mc_call(S0, E, T, r, sig, numSim, numStep):\n\n    dt = T / numStep; # time step\n    accum = 0.0; # accumulated payoff\n    t0 = time.clock();\n    for i in range(numSim): # simulation loop\n        s = S0;\n        for j in range(numStep): # timestep loop\n            z = np.random.normal();\n            # Geometric Brownian motion\n            s = s * exp((r - 0.5*sig**2)*dt + sig*sqrt(dt)*z);\n        payoff = max(s - E, 0); # vanilla call\n        accum = accum + payoff; # accumulate payoff\n    call = exp(-r * T) * (accum / numSim); # expectation\n    t1 = time.clock();\n    \n    print 'version 0' \n    print 'Call Price : %.5f' % call\n    print 'CPU time in Python(sec) : %.4f' % (t1-t0)\n    \ndef mc_call_vec1(S0, E, T, r, sig, numSim, numStep):\n    dt = T / numStep;\n    accum = 0.0;\n    t0 = time.clock();\n    z = np.random.normal(size = [numSim, numStep]);\n    for i in range(numSim):\n        s = S0;\n        for j in range(numStep):\n            s = s * exp((r - 0.5*sig**2)*dt + sig*sqrt(dt)*z[i, j]);\n        payoff = max(s - E, 0);\n        accum = accum + payoff;\n    call = exp(-r * T) * (accum / numSim);\n    t1 = time.clock();\n    \n    print 'version 1' \n    print 'Call Price : %.5f' % call\n    print 'CPU time in Python(sec) : %.4f' % (t1-t0)\n    \ndef mc_call_vec2(S0, E, T, r, sig, numSim, numStep):\n    dt = T / numStep;\n    t0 = time.clock();\n    z = np.random.normal(size = [numStep, numSim]);\n    s = S0 * np.ones([numSim]);\n    for i in range(numStep):\n        s[:] = s[:] * np.exp((r - 0.5*sig**2)*dt + sig*sqrt(dt)*z[i, :]);\n    payoff = np.maximum(s - E, 0);\n    call = exp(-r * T) * np.mean(payoff);\n    t1 = time.clock();\n    \n    print 'version 2' \n    print 'Call Price : %.5f' % call\n    print 'CPU time in Python(sec) : %.4f' % (t1-t0  )\n\nS0 = 100.0; # underlying price\nE = 100.0; # strike price\nT = 1.0; # maturity\nr = 0.03; # riskless interest rate\nsig = 0.3; # volatility\nns = 1000000;  # # of simulations\nnStep = 1; # # of time steps (In this example, nStep does not have to over 1 due to European option pricing.)\n\n# functions call\nexc_call(S0, E, T, r, sig);\nmc_call(S0, E, T, r, sig, ns, nStep);\nmc_call_vec1(S0, E, T, r, sig, ns, nStep);\nmc_call_vec2(S0, E, T, r, sig, ns, nStep);\n\n", "meta": {"hexsha": "8accd8755a3220fb4da36e3a3c1c1ff801783de3", "size": 2716, "ext": "py", "lang": "Python", "max_stars_repo_path": "call/call_vec_test.py", "max_stars_repo_name": "ymh1989/monte_calro_python", "max_stars_repo_head_hexsha": "21cdfb2936626b3e1615d7e3cc72bd6eb31b182a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-01-09T03:40:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T07:47:21.000Z", "max_issues_repo_path": "call/call_vec_test.py", "max_issues_repo_name": "ymh1989/monte_calro_python", "max_issues_repo_head_hexsha": "21cdfb2936626b3e1615d7e3cc72bd6eb31b182a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "call/call_vec_test.py", "max_forks_repo_name": "ymh1989/monte_calro_python", "max_forks_repo_head_hexsha": "21cdfb2936626b3e1615d7e3cc72bd6eb31b182a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-03-31T03:46:01.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-31T03:46:01.000Z", "avg_line_length": 30.5168539326, "max_line_length": 109, "alphanum_fraction": 0.5508100147, "include": true, "reason": "import numpy,from scipy", "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995742876885, "lm_q2_score": 0.9111797045849583, "lm_q1q2_score": 0.880108088758193}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"Convolutions Sidebar.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/Course%201%20-%20Part%206%20-%20Lesson%203%20-%20Notebook.ipynb\n\nLet's explore how convolutions work by creating a basic convolution on a 2D Grey Scale image. First we can load the image by taking the 'ascent' image from scipy. It's a nice, built-in picture with lots of angles and lines.\n\"\"\"\n\nimport cv2\nimport numpy as np\nfrom scipy import misc\ni = misc.ascent()\n\n\"\"\"Next, we can use the pyplot library to draw the image so we know what it looks like.\"\"\"\n\nimport matplotlib.pyplot as plt\nplt.grid(False)\nplt.gray()\nplt.axis('off')\nplt.imshow(i)\nplt.show()\n\n\"\"\"The image is stored as a numpy array, so we can create the transformed image by just copying that array. Let's also get the dimensions of the image so we can loop over it later.\"\"\"\n\ni_transformed = np.copy(i)\nsize_x = i_transformed.shape[0]\nsize_y = i_transformed.shape[1]\n\n\"\"\"Now we can create a filter as a 3x3 array.\"\"\"\n\n# This filter detects edges nicely\n# It creates a convolution that only passes through sharp edges and straight\n# lines.\n\n#Experiment with different values for fun effects.\n#filter = [ [0, 1, 0], [1, -4, 1], [0, 1, 0]]\n\n# A couple more filters to try for fun!\nfilter = [ [-1, -2, -1], [0, 0, 0], [1, 2, 1]]\n#filter = [ [-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]\n\n# If all the digits in the filter don't add up to 0 or 1, you \n# should probably do a weight to get it to do so\n# so, for example, if your weights are 1,1,1 1,2,1 1,1,1\n# They add up to 10, so you would set a weight of .1 if you want to normalize them\nweight  = 1\n\n\"\"\"Now let's create a convolution. We will iterate over the image, leaving a 1 pixel margin, and multiply out each of the neighbors of the current pixel by the value defined in the filter. \n\ni.e. the current pixel's neighbor above it and to the left will be multiplied by the top left item in the filter etc. etc. We'll then multiply the result by the weight, and then ensure the result is in the range 0-255\n\nFinally we'll load the new value into the transformed image.\n\"\"\"\n\nfor x in range(1,size_x-1):\n  for y in range(1,size_y-1):\n      convolution = 0.0\n      convolution = convolution + (i[x - 1, y-1] * filter[0][0])\n      convolution = convolution + (i[x, y-1] * filter[0][1])\n      convolution = convolution + (i[x + 1, y-1] * filter[0][2])\n      convolution = convolution + (i[x-1, y] * filter[1][0])\n      convolution = convolution + (i[x, y] * filter[1][1])\n      convolution = convolution + (i[x+1, y] * filter[1][2])\n      convolution = convolution + (i[x-1, y+1] * filter[2][0])\n      convolution = convolution + (i[x, y+1] * filter[2][1])\n      convolution = convolution + (i[x+1, y+1] * filter[2][2])\n      convolution = convolution * weight\n      if(convolution<0):\n        convolution=0\n      if(convolution>255):\n        convolution=255\n      i_transformed[x, y] = convolution\n\n\"\"\"Now we can plot the image to see the effect of the convolution!\"\"\"\n\n# Plot the image. Note the size of the axes -- they are 512 by 512\nplt.gray()\nplt.grid(False)\nplt.imshow(i_transformed)\n#plt.axis('off')\nplt.show()\n\n\"\"\"This code will show a (2, 2) pooling. The idea here is to iterate over the image, and look at the pixel and it's immediate neighbors to the right, beneath, and right-beneath. Take the largest of them and load it into the new image. Thus the new image will be 1/4 the size of the old -- with the dimensions on X and Y being halved by this process. You'll see that the features get maintained despite this compression!\"\"\"\n\nnew_x = int(size_x/2)\nnew_y = int(size_y/2)\nnewImage = np.zeros((new_x, new_y))\nfor x in range(0, size_x, 2):\n  for y in range(0, size_y, 2):\n    pixels = []\n    pixels.append(i_transformed[x, y])\n    pixels.append(i_transformed[x+1, y])\n    pixels.append(i_transformed[x, y+1])\n    pixels.append(i_transformed[x+1, y+1])\n    newImage[int(x/2),int(y/2)] = max(pixels)\n\n# Plot the image. Note the size of the axes -- now 256 pixels instead of 512\nplt.gray()\nplt.grid(False)\nplt.imshow(newImage)\n#plt.axis('off')\nplt.show()", "meta": {"hexsha": "009d558b7fbe543cab431967611019c3f6dcad91", "size": 4171, "ext": "py", "lang": "Python", "max_stars_repo_path": "introduction-to-tensorflow/examples/convolutions_sidebar.py", "max_stars_repo_name": "macio-matheus/tensorflow-specialization", "max_stars_repo_head_hexsha": "3f21d410299436f1b0922b3bf7c54c29a858f8c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-30T14:03:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-30T14:03:36.000Z", "max_issues_repo_path": "introduction-to-tensorflow/examples/convolutions_sidebar.py", "max_issues_repo_name": "macio-matheus/tensorflow-specialization", "max_issues_repo_head_hexsha": "3f21d410299436f1b0922b3bf7c54c29a858f8c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "introduction-to-tensorflow/examples/convolutions_sidebar.py", "max_forks_repo_name": "macio-matheus/tensorflow-specialization", "max_forks_repo_head_hexsha": "3f21d410299436f1b0922b3bf7c54c29a858f8c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7238095238, "max_line_length": 422, "alphanum_fraction": 0.6866458883, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9632305339244013, "lm_q2_score": 0.9136765298777718, "lm_q1q2_score": 0.8800811317083603}}
{"text": "import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt \n\n\ndef normalize_transformation(points: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Compute a similarity transformation matrix that translate the points such that\n    their center is at the origin & the avg distance from the origin is sqrt(2)\n    :param points: <float: num_points, 2> set of key points on an image\n    :return: (sim_trans <float, 3, 3>)\n    \"\"\"\n    center = np.array([np.mean(points[:,0],axis=0),np.mean(points[:,1],axis=0)])  # TODO: find center of the set of points by computing mean of x & y\n    # dist = np.array([np.sqrt((points[:,0] - center[0])**2 + (points[:,1] - center[1])**2)])  # TODO: matrix of distance from every point to the origin, shape: <num_points, 1>\n    dist = np.linalg.norm(points - center, axis=1)\n    s = np.sqrt(2)/np.mean(dist)  # TODO: scale factor the similarity transformation = sqrt(2) / (mean of dist)\n    sim_trans = np.array([\n        [s,     0,      -s * center[0]],\n        [0,     s,      -s * center[1]],\n        [0,     0,      1]\n    ])\n    return sim_trans\n\n\ndef homogenize(points: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Convert points to homogeneous coordinate\n    :param points: <float: num_points, num_dim>\n    :return: <float: num_points, 3>\n    \"\"\"\n    return np.concatenate((points, np.ones((points.shape[0], 1))), axis=1)\n\n\n# read image & put them in grayscale\nimg1 = cv2.imread('../Materials/chapel00.png', 0)  # queryImage\nimg2 = cv2.imread('../Materials/chapel01.png', 0)  # trainImage\n\n# detect kpts & compute descriptor\norb = cv2.ORB_create()\nkp1, des1 = orb.detectAndCompute(img1, None)\nkp2, des2 = orb.detectAndCompute(img2, None)\n\n# match kpts\nbf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\nmatches = bf.match(des1, des2)\n\n# organize key points into matrix, each row is a point\nquery_kpts = np.array([kp1[m.queryIdx].pt for m in matches]).reshape((-1, 2))  # shape: <num_pts, 2>\ntrain_kpts = np.array([kp2[m.trainIdx].pt for m in matches]).reshape((-1, 2))  # shape: <num_pts, 2>\n\n# normalize kpts\nT_query = normalize_transformation(query_kpts)  # get the similarity transformation for normalizing query kpts\nnormalized_query_kpts = (T_query @ homogenize(query_kpts).T).T # TODO: apply T_query to query_kpts to normalize them\n\nT_train = normalize_transformation(train_kpts)  # get the similarity transformation for normalizing train kpts\nnormalized_train_kpts = (T_train @ homogenize(train_kpts).T).T  # TODO: apply T_train to train_kpts to normalize them\n\nprint(T_query)\nprint(T_train)\n# construct homogeneous linear equation to find fundamental matrix\na1 = (normalized_train_kpts[:,0]*normalized_query_kpts[:,0]).reshape(-1, 1)\na2 = (normalized_train_kpts[:,0]*normalized_query_kpts[:,1]).reshape(-1, 1)\na3 = normalized_train_kpts[:,0].reshape(-1, 1)\na4 = (normalized_train_kpts[:,1]*normalized_query_kpts[:,0]).reshape(-1, 1)\na5 = (normalized_train_kpts[:,1]*normalized_query_kpts[:,1]).reshape(-1, 1)\na6 = normalized_train_kpts[:,1].reshape(-1, 1)\na7 = normalized_query_kpts[:,0].reshape(-1, 1)\na8 = normalized_query_kpts[:,1].reshape(-1, 1)\na9 = np.ones((len(normalized_train_kpts),1))\nA = np.concatenate((a1,a2,a3,a4,a5,a6,a7,a8,a9),axis=1) # TODO: construct A according to Eq.(3) in lab subject\n\n# TODO: find vector f by solving A f = 0 using SVD\n# hint: perform SVD of A using np.linalg.svd to get u, s, vh (vh is the transpose of v)\n# hint: f is the last column of v\nu,s,vh = np.linalg.svd(A)\nf = vh.T[:,-1]  # TODO: find f\n\n# arrange f into 3x3 matrix to get fundamental matrix F\nF = f.reshape(3, 3)\nprint('rank F: ', np.linalg.matrix_rank(F))  # should be = 3\n\n# TODO: force F to have rank 2\n# hint: perform SVD of F using np.linalg.svd to get u, s, vh\n# hint: set the smallest singular value of F to 0\n# hint: reconstruct F from u, new_s, vh\nu,s,vh = np.linalg.svd(F)\nindex = np.where(s == np.amin(s))\ns[-1] = 0\nF = u @ np.diag(s) @ vh\n\nassert np.linalg.matrix_rank(F) == 2, 'Fundamental matrix must have rank 2'\n\n# TODO: de-normlaize F\n# hint: last line of Algorithme 1 in the lab subject\nF = T_train.T @ F @ T_query\nF_gt = np.loadtxt('../Materials/chapel.00.01.F')\n\nFransac, mask= cv2.findFundamentalMat(query_kpts, train_kpts, cv2.FM_RANSAC)\n\nprint('ERROR OF F COMPUTED BY 8-POINT ALGORITHM:')\nprint(F - F_gt)\nprint('*****')\nprint('ERROR OF F COMPUTED BY CV RANSAC:')\nprint(Fransac - F_gt)\n\n## 1.1.1 Practical\n\n# Load F\nF= np.loadtxt('../Materials/chapel.00.01.F')\n\n# Get the real epipole from F\nu,s,vh= np.linalg.svd(F.T)\ne= vh.T[:,-1]\ne /= e[-1]\n\n# Choose two correspondances points\nplt.imshow(img1, cmap='gray')\nx= plt.ginput(2)\nx= np.asarray(x)\n\n# Homogenize the selected points\none= np.ones((1,2))\nx= np.concatenate((x,one.T),axis=1)\n\n# Compute the epipolar lines by l = F x\nl= F @ x.T\n\n# Compute the epipole from the epipolar lines computed\nec= np.cross(l[:,0],l[:,1])\nec /= ec[-1]\n\nprint('****')\nprint('REAL EPIPOLE: ', e)\nprint('COMPUTED EPIPOLE: ', ec)\n\n# Visualize the epipolar lines computed\nx2 = np.array([0, 500])\n\na2, b2, c2 = l[:,0].ravel()\ny2 = -(x2*a2 + c2) / b2\na3, b3, c3 = l[:,1].ravel()\ny3 = -(x2*a3 + c3) / b3\n\nimg2=cv2.imread('../Materials/chapel01.png')\nimage=cv2.line(img2,(x2[0],int(np.around(y2.T[0]))),(x2[-1],int(np.around(y2.T[-1]))),(0,255,0),(1))\nimage=cv2.line(img2,(x2[0],int(np.around(y3.T[0]))),(x2[-1],int(np.around(y3.T[-1]))),(0,255,0),(1))\ncv2.imshow('Epipolar lines',image)\n\n# PRESS A KEY TO FINISH INSTEAD OF CLOSING THE WINDOW\ncv2.waitKey(0)\n", "meta": {"hexsha": "9e4a0f8d2857f053703a8fa6b3e13189978b19e3", "size": 5438, "ext": "py", "lang": "Python", "max_stars_repo_path": "Two-views geometry/Code/lab2_epipolar.py", "max_stars_repo_name": "imstevenpmwork/Advanced_Vision_Geometry-Projects", "max_stars_repo_head_hexsha": "308ff9674eb9d53a1d42ee9caeda784632f2fcf7", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Two-views geometry/Code/lab2_epipolar.py", "max_issues_repo_name": "imstevenpmwork/Advanced_Vision_Geometry-Projects", "max_issues_repo_head_hexsha": "308ff9674eb9d53a1d42ee9caeda784632f2fcf7", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Two-views geometry/Code/lab2_epipolar.py", "max_forks_repo_name": "imstevenpmwork/Advanced_Vision_Geometry-Projects", "max_forks_repo_head_hexsha": "308ff9674eb9d53a1d42ee9caeda784632f2fcf7", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0132450331, "max_line_length": 176, "alphanum_fraction": 0.6778227289, "include": true, "reason": "import numpy", "num_tokens": 1762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305339244012, "lm_q2_score": 0.9136765140114859, "lm_q1q2_score": 0.8800811164254692}}
{"text": "from typing import List, Union\nfrom scipy.optimize import OptimizeResult\nimport numpy as np\nfrom scipy.integrate import solve_ivp\n\n\n# https://www.idmod.org/docs/hiv/model-seir.html\n# https://www.idmod.org/docs/typhoid/model-seir.html\n# The SIR model differential equations. (without vital kinetics)\ndef seir(t: float, y: List[float], N: Union[int, float], beta: float, gamma: float, sigma: float):\n    \"\"\"\n    System of ODE for the Susceptible-Exposed-Infected-Recovered model without vital kinetics\n\n    Parameters\n    ----------\n    t: float\n        Time in days\n    y: List[float, float, float, float]\n        A list with the current values of\n        S: float\n            The susceptible population\n        E: float\n            The exposed population\n        I: float\n            The infected population\n        R: float\n            The removed population\n    N: int\n        The total population\n    beta: float\n        The contact rate of the disease (1/days)\n    gamma: float\n        The recovery rate of the disease (1/days)\n    sigma: float\n        The rate of latent individuals becoming infectious in 1/days (average duration of incubation is 1/sigma)\n\n    Returns\n    -------\n    OptimizeResult:\n        The solution\n    \"\"\"\n    S, E, I, R = y\n    dSdt = -beta * S * I / N\n    dEdt = beta * S * I / N - sigma * E\n    dIdt = sigma * E - gamma * I\n    dRdt = gamma * I\n    return [dSdt, dEdt, dIdt, dRdt]\n\n\ndef seir_model(t: np.ndarray, N: Union[int, float], beta: float, gamma: float, sigma: float,\n               **kwargs):\n    \"\"\"\n    Solves the Susceptible-Exposed-Infected-Removed ODE\n    \n    Parameters\n    ----------\n    t: np.ndarray\n        The time (days)\n    N: int\n        The total population\n    beta: float\n        The contact rate of the disease (1/days)\n    gamma: float\n        The recovery rate of the disease (1/days)\n    sigma: float\n        The rate of latent individuals becoming infectious in 1/days (average duration of incubation is 1/sigma)\n    kwargs: keyword arguments\n        I0: int\n            The initial number of infected individuals\n        R0: int\n            The initial number of recovered individuals\n        E0: float\n            The initial number of exposed individuals\n    \"\"\"\n\n    I0 = kwargs.get('I0', 1)\n    R0 = kwargs.get('R0', 0)\n    E0 = kwargs.get('E0', 1)\n\n    #    # Total population, N.\n    #    N = 1000\n    #    # Initial number of infected and recovered individuals, I0 and R0.\n    #    I0, R0 = 1, 0\n    #    # Everyone else, S0, is susceptible to infection initially.\n    S0 = N - I0 - R0 - E0\n    #    # Contact rate, beta, and mean recovery rate, gamma, (in 1/days).\n    #    beta, gamma = 0.2, 1./10\n    #    # A grid of time points (in days)\n\n    # Initial conditions vector\n    y0 = S0, E0, I0, R0\n    # Integrate the SIR equations over the time grid, t.\n    # ret = odeint(deriv, y0, t, args=(N, beta, gamma))\n    sol = solve_ivp(seir, [np.amin(t), np.amax(t)], y0, t_eval=t,\n                    args=(N, beta, gamma, sigma),\n                    method='DOP853',\n                    dense_output=True)\n\n    return sol\n", "meta": {"hexsha": "af6d392b9011b6da12383afa5b9de645d05bdefc", "size": 3094, "ext": "py", "lang": "Python", "max_stars_repo_path": "epydemics/seir_model.py", "max_stars_repo_name": "erickmartinez/epydemics", "max_stars_repo_head_hexsha": "48100a0b42ac6797a5607a91299f1b4cf27e96bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "epydemics/seir_model.py", "max_issues_repo_name": "erickmartinez/epydemics", "max_issues_repo_head_hexsha": "48100a0b42ac6797a5607a91299f1b4cf27e96bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "epydemics/seir_model.py", "max_forks_repo_name": "erickmartinez/epydemics", "max_forks_repo_head_hexsha": "48100a0b42ac6797a5607a91299f1b4cf27e96bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.94, "max_line_length": 112, "alphanum_fraction": 0.594376212, "include": true, "reason": "import numpy,from scipy", "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307708274402, "lm_q2_score": 0.9046505312448598, "lm_q1q2_score": 0.8800718736403903}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom tictoc import *\r\nfrom plot import plot\r\n#from RFA import bisection\r\n\r\ndef bisection(f,a,b,TOL,NMAX):\r\n    # THIS FUNCTION PRINTS THE a,b,c VALUES FOR EACH ITERATION:\r\n    \r\n    #Approximates root using Bisection Method\r\n    #In an interval[a,b] with a tolerance TOL\r\n    #|f(c)| < TOL, where m is the midpoint\r\n    \r\n\r\n    #INPUT : f , a , b , TOL , NMAX\r\n    # f : function / polynomial\r\n    # a : interval start\r\n    # b : interval end\r\n    # TOL : tolerance value\r\n    # NMAX : maximum number of iterations\r\n\r\n\r\n    #Print Table Header:\r\n    print('--------------------------------------------------------------------------')\r\n    print('iter \\t\\t a \\t\\t b \\t\\t c \\t\\t f(c)        ')\r\n    print('--------------------------------------------------------------------------')\r\n    #satisfy the conditions needed to apply the Bisection Method:\r\n    if np.sign(f(a)) == np.sign(f(b)):\r\n        print(\"No root found in the given interval!\")\r\n        exit()\r\n        \r\n    for i in range(NMAX):\r\n        #Compute Midpoint\r\n        c = (a+b)/2\r\n        #print line for the table:\r\n        N.append(1+i)\r\n        f_x.append(f(c))\r\n        print(str(1+i)+'\\t% 15.12f\\t% 15.12f\\t% 15.12f\\t% 15.12f\\t' %(a, b, c, f(c)))\r\n        #Check stopping condition:\r\n        if np.abs(f(c)) < TOL:\r\n            print('------------------------------------------------------------------------')\r\n            print('Root Found: '+str(c))\r\n            break\r\n        #Implement Recursion:\r\n        elif np.sign(f(a)) == np.sign(f(c)):\r\n            #Improvement on a\r\n            a = c\r\n        elif np.sign(f(b)) == np.sign(f(c)):\r\n            #Improvement on b\r\n            b = c\r\n        \r\n    if i == NMAX -1:\r\n        print(\"MAX NUMBER OF ITERATIONS REACHED!\")\r\n        print('Approximaiton to the Root after max iterations is : '+str(c))        \r\n        exit()\r\nf1 = lambda x: x**3 - 3*(x**2) - x + 9\r\nf2 = lambda x: np.exp(x)*(x**3 - 3*(x**2) - x + 9)\r\na1 = -5\r\nb1 = 0\r\na2 = -2.5\r\nb2 = 1\r\n\r\n\r\nN=[]\r\nf_x=[]\r\ntic()\r\nbisection(f1,a1,b1,1.e-10,1000)\r\ntoc()\r\nplot(N,f_x,'b',1)\r\n    \r\nN=[]\r\nf_x=[]\r\ntic()\r\nbisection(f1,a2,b2,1.e-10,1000)\r\ntoc()\r\nplot(N,f_x,'r',1)\r\nplt.legend(['(a1,b1)=(-5,0)','(a2,b2)=(-2.5,1)'])\r\nplt.show()\r\n\r\nN=[]\r\nf_x=[]\r\ntic()\r\nbisection(f2,a1,b1,1.e-10,1000)\r\ntoc()\r\nplot(N,f_x,'b',2)\r\n    \r\nN=[]\r\nf_x=[]\r\ntic()\r\nbisection(f2,a2,b2,1.e-10,1000)\r\ntoc()\r\nplot(N,f_x,'r',2)\r\nplt.legend(['(a1,b1)=(-5,0)','(a2,b2)=(-2.5,1)'])\r\nplt.show()\r\n", "meta": {"hexsha": "927f5b06dbde1b80e9a392433641057b8b3e65b6", "size": 2495, "ext": "py", "lang": "Python", "max_stars_repo_path": "Bisection.py", "max_stars_repo_name": "YashIITM/Root-Finding-Algorithms", "max_stars_repo_head_hexsha": "a7ccc58cd5064f7910af538de00a3fe7cdd57cd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Bisection.py", "max_issues_repo_name": "YashIITM/Root-Finding-Algorithms", "max_issues_repo_head_hexsha": "a7ccc58cd5064f7910af538de00a3fe7cdd57cd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bisection.py", "max_forks_repo_name": "YashIITM/Root-Finding-Algorithms", "max_forks_repo_head_hexsha": "a7ccc58cd5064f7910af538de00a3fe7cdd57cd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2631578947, "max_line_length": 94, "alphanum_fraction": 0.4653306613, "include": true, "reason": "import numpy", "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.9273633006654725, "lm_q1q2_score": 0.8799910424345851}}
{"text": "\"\"\"\nCost functions of Machine Learning\n\"\"\"\n\nimport numpy as np\n\n\ndef calculate_mse_cost(y_pred: np.ndarray, y: np.ndarray) -> float:\n    \"\"\"Calculate error for regression model with mean squared error\n\n    Args:\n        y_pred (np.ndarray): predicted y value, y^.\n        y (np.ndarray): actual y value. \n\n    Returns:\n        float: mean squared error cost.\n    \"\"\"\n    residual = y_pred - y\n    diff_squared = np.square(residual)\n    mse_cost = np.mean(diff_squared) / 2\n    return float(mse_cost)\n\n\ndef calculate_entropy_cost(y_pred: np.ndarray, y: np.ndarray) -> float:\n    \"\"\"Calculate entropy error for classification model\n\n    Args:\n        y_pred (np.ndarray): predicted y value, y^.\n        y (np.ndarray): actual y value.\n\n    Returns:\n        float: entorpy error cost.\n    \"\"\"\n\n    part_1 = y * np.log(y_pred)\n\n    part_2 = (1 - y) * np.log(1 - y_pred)\n\n    cost = (-1 / y_pred.shape[0]) * np.sum(part_1 + part_2)\n    return cost\n", "meta": {"hexsha": "2ea244c9dcf8eac1a92b14fe0717004d83e2557b", "size": 943, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/mightypy/ml/_error_fxs.py", "max_stars_repo_name": "NishantBaheti/mightypy", "max_stars_repo_head_hexsha": "8219ae5cfc462e02f04bec6bdd7e3751b57d2a25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-03T19:32:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T19:32:45.000Z", "max_issues_repo_path": "src/mightypy/ml/_error_fxs.py", "max_issues_repo_name": "NishantBaheti/mightypy", "max_issues_repo_head_hexsha": "8219ae5cfc462e02f04bec6bdd7e3751b57d2a25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mightypy/ml/_error_fxs.py", "max_forks_repo_name": "NishantBaheti/mightypy", "max_forks_repo_head_hexsha": "8219ae5cfc462e02f04bec6bdd7e3751b57d2a25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0, "max_line_length": 71, "alphanum_fraction": 0.6267232238, "include": true, "reason": "import numpy", "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9787126444811033, "lm_q2_score": 0.8991213799730774, "lm_q1q2_score": 0.8799814635029495}}
{"text": "import numpy as np\r\n\r\ndef gausseidel(A, b, imax=1000, es100=1.0, lamb=1.):\r\n    n = len(A)\r\n    A = np.array(A, dtype=float)\r\n    b = np.array(b, dtype=float)\r\n    x = np.zeros(n)\r\n    for i in range(n):\r\n        pivot = A[i,i]\r\n        A[i,:] /= pivot\r\n        b[i] /= pivot\r\n    for i in range(n):\r\n        sum = b[i]\r\n        for j in range(n):\r\n            if i != j: sum -= A[i,j]*x[j]\r\n        x[i] = sum\r\n    iter = 1\r\n    while True:\r\n        sentinel = 1\r\n        for i in range(n):\r\n            old = x[i]\r\n            sum = b[i]\r\n            for j in range(n):\r\n                if i != j: sum -= A[i,j]*x[j]\r\n            x[i] = lamb*sum + (1 - lamb)*old\r\n            if sentinel and x[i]:\r\n                ea = abs(1 - old/x[i])\r\n                if ea*100 > es100: sentinel = 0\r\n        iter += 1\r\n        if sentinel or iter >= imax:\r\n            break\r\n    return x\r\n\r\nA = ([[-8, 1, -2], [2, -6, -1], [-3, -1, 7]])\r\nb = ([-20, -38, -34])\r\n\r\nprint(\"A = {}\".format(np.array(A)))\r\nprint(\"b = {}\".format(np.array(b)))\r\n\r\nx = gausseidel(A, b, es100=1.0, lamb=1.)\r\nprint(\"(using gauss-seidel(without relaxation)x = {}\".format(x))\r\ny = gausseidel(A, b, es100=0.5, lamb=1.2)\r\nprint(\"(using gauss-seidel(with relaxation)x = {}\".format(y))\r\n", "meta": {"hexsha": "97205102306a0ac5acac6b54d4006506f18affd2", "size": 1244, "ext": "py", "lang": "Python", "max_stars_repo_path": "Gauss-Seidel method.py", "max_stars_repo_name": "J-Chaudhary/sciComp_I", "max_stars_repo_head_hexsha": "e3499746b3ffb8818107db79c84b01b3e0fc0d9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Gauss-Seidel method.py", "max_issues_repo_name": "J-Chaudhary/sciComp_I", "max_issues_repo_head_hexsha": "e3499746b3ffb8818107db79c84b01b3e0fc0d9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gauss-Seidel method.py", "max_forks_repo_name": "J-Chaudhary/sciComp_I", "max_forks_repo_head_hexsha": "e3499746b3ffb8818107db79c84b01b3e0fc0d9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2727272727, "max_line_length": 65, "alphanum_fraction": 0.441318328, "include": true, "reason": "import numpy", "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214470715364, "lm_q2_score": 0.9124361646438639, "lm_q1q2_score": 0.8798817626497735}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ninfo_list = []\r\ndef InverseMethod(A, converge_range):\r\n    \r\n    r, c = A.shape\r\n\r\n    if r != c:\r\n        raise Exception(\"not a square matrix\")\r\n\r\n    #initialize eigenvectors\r\n    vec_list = []\r\n    lambda_list = []\r\n    diff_list = []\r\n\r\n    idx = 0\r\n    vec_init = np.zeros(r)\r\n    vec_init[-1] = 1\r\n    vec_list.append(vec_init)\r\n\r\n    #initialize eigenvalues\r\n    lambda_init = vec_init.dot(A.dot(vec_init))\r\n    lambda_list.append(lambda_init)\r\n    \r\n    diff_init = float(\"inf\")\r\n    diff_list.append(diff_init)\r\n\r\n    while diff_list[idx] > converge_range:\r\n        #solve the Aw = v^(k-1) for w=vec_new\r\n        vec_new = np.linalg.solve(A, vec_list[idx]) \r\n        #normalize the newly found vec_new=w\r\n        vec_new = vec_new / np.linalg.norm(vec_new)\r\n        #add this to the vector list\r\n        vec_list.append(vec_new)\r\n        lambda_new = vec_new.dot(A.dot(vec_new))\r\n        lambda_list.append(lambda_new)\r\n        diff = np.abs(lambda_new - lambda_list[idx])\r\n        diff_list.append(diff)\r\n        idx = idx + 1\r\n        \r\n    print_log(idx, vec_list, lambda_list, diff_list)\r\n\r\n    #plot lambda_list\r\n    x = [i for i in range(idx+1)]\r\n    if len(x) > 20:\r\n        x = x[:21]\r\n        diff_list = diff_list[:21]\r\n\r\n\r\n    plt.plot(x, diff_list)\r\n    plt.show()\r\n    plt.savefig(\"II_difference_list_plot\") \r\n    return vec_list[-1], lambda_list[-1]\r\n\r\ndef print_log(idx, vec_list, lambda_list, diff_list):\r\n    print(\"Inverse Iteration:\")\r\n    print('Number of Iterations:', idx)\r\n    cor_eig_vec = vec_list[idx]\r\n    sm_eig_val = round(lambda_list[idx], 4)\r\n    inv_eig_val = np.reciprocal(sm_eig_val)\r\n    print('Inverse Smallest Eigenvalue:', inv_eig_val) #\r\n    print('Smallest Eigenvalue:', sm_eig_val)\r\n    print('Corresponding Eigenvector:', cor_eig_vec)\r\n    print(diff_list[idx]) #don't really need this, just want to see it \r\n\r\n\r\n#Examples to run on\r\nB = np.array([[1.5, 0.5], [0.5, 1.5]])\r\nC = np.array([[2, 1], [2, 3]]) # eigenval of smallest magnitude of C is 1 \r\nD = np.array([[2, 2, -1], [-5, 9, -3], [-4, 4, 1]]) # eigenvals of D are 3, 4, and 5 \r\nE = np.array([[-4, 1, 1], [0, 3, 1], [-2, 0, 15]]) # eigenvals of E are ~ -3.9095, 3.0243 and 14.8852\r\nF = np.array([[-6, 3], [4, 5]]) #eigenval of smallest magnitude of F is 6 with corresponding eigenvec [1, 4]\r\nG = np.array([[0.8, 0.3], [0.2, 0.7]])\r\nInverseMethod(D, 0.0001)", "meta": {"hexsha": "1a0f94515e254ce86d6ad226ebea6080d566ba25", "size": 2421, "ext": "py", "lang": "Python", "max_stars_repo_path": "efficientEigensolvers/Inverse_Iteration.py", "max_stars_repo_name": "Erica-Liu/icerm_efficient_eigensolver", "max_stars_repo_head_hexsha": "7c933ea0e6500926ca43a26309d80069bcc65a37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "efficientEigensolvers/Inverse_Iteration.py", "max_issues_repo_name": "Erica-Liu/icerm_efficient_eigensolver", "max_issues_repo_head_hexsha": "7c933ea0e6500926ca43a26309d80069bcc65a37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "efficientEigensolvers/Inverse_Iteration.py", "max_forks_repo_name": "Erica-Liu/icerm_efficient_eigensolver", "max_forks_repo_head_hexsha": "7c933ea0e6500926ca43a26309d80069bcc65a37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-02T15:33:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T16:32:40.000Z", "avg_line_length": 32.28, "max_line_length": 109, "alphanum_fraction": 0.6030565882, "include": true, "reason": "import numpy", "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214470715364, "lm_q2_score": 0.912436159286392, "lm_q1q2_score": 0.8798817574834484}}
{"text": "import matplotlib.pyplot as plt \nfrom scipy.special import gamma\nimport numpy as np\n\n# Plots Histogram along side acutal distribution\ndef plotHistogram(sample, a1, a2, N):\n\thist, bins, _ = plt.hist(sample, density=True, bins=100)\n\txAxis = (bins[1:]+bins[:-1])/2\n\tyAxis = []\n\tfor x in xAxis:\n\t\tyAxis.append(fx(x, a1, a2))\n\n\tplt.plot(xAxis, yAxis, label = \"f(x)\")\n\tplt.legend(loc = \"upper right\")\n\tplt.xlabel('x')\n\tplt.ylabel('y')\n\tplt.show()\n\n# Computes f(x)\ndef fx(x, a1, a2):\n\tres = (x**(a1-1))*((1-x)**(a2-1))\n\tres /= beta(a1, a2)\n\treturn res\n\n# Computes B(a1, a2)\ndef beta(a1, a2):\n\tres = (gamma(a1)*gamma(a2))/(gamma(a1+a2))\n\treturn res\n\n# Generates Beta Distribution of N values\ndef generateBeta(a1, a2, c, N):\n\tres = []\n\tfor i in range(N):\n\t\twhile True:\n\t\t\tu1 = np.random.uniform(0.00, 1.00)\n\t\t\tu2 = np.random.uniform(0.00, 1.00)\n\n\t\t\tif fx(u1, a1, a2) >= c*u2:\n\t\t\t\tres.append(u1)\n\t\t\t\tbreak\n\n\treturn res\n\ndef solve(a1, a2):\n\tx = (a1-1)/(a1+a2-2)\n\tprint('*x = {}'.format(x))\n\tc = fx(x, a1, a2)\n\tprint('f(*x) = {}'.format(c))\n\n\tres = generateBeta(a1, a2, c, 100)\n\tplotHistogram(res, a1, a2, 100)\n\t\n\tres = generateBeta(a1, a2, c, 1000)\n\tplotHistogram(res, a1, a2, 1000)\n\t\n\tres = generateBeta(a1, a2, c, 10000)\n\tplotHistogram(res, a1, a2, 10000)\n\t\n\tres = generateBeta(a1, a2, c, 100000)\n\tplotHistogram(res, a1, a2, 100000)\n\t\n\t# res = generateBeta(a1, a2, c, 1000000)\n\t# plotHistogram(res, a1, a2, 1000000)\n\t\n\ndef main():\n\tsolve(1.43, 2.76)\n\t# solve(1.25, 2.0)\n\t# solve(1.25, 2.75)\n\t# solve(1.0, 2.0)\n\t# solve(3.25, 4.75)\n\t# solve(2.25, 1.75)\n\nif __name__ == '__main__':\n\tmain()", "meta": {"hexsha": "8d958747bca4a50dea5616967b4da0273664f926", "size": 1578, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab 04/180123019_Jay_Sabale_q1.py", "max_stars_repo_name": "ElProfesor18/MA-323_Monte_Carlo_Simulation", "max_stars_repo_head_hexsha": "24efd6ba1d50b00100d15ec2ef5d3fc5217f93a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab 04/180123019_Jay_Sabale_q1.py", "max_issues_repo_name": "ElProfesor18/MA-323_Monte_Carlo_Simulation", "max_issues_repo_head_hexsha": "24efd6ba1d50b00100d15ec2ef5d3fc5217f93a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab 04/180123019_Jay_Sabale_q1.py", "max_forks_repo_name": "ElProfesor18/MA-323_Monte_Carlo_Simulation", "max_forks_repo_head_hexsha": "24efd6ba1d50b00100d15ec2ef5d3fc5217f93a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.04, "max_line_length": 57, "alphanum_fraction": 0.6159695817, "include": true, "reason": "import numpy,from scipy", "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576266, "lm_q2_score": 0.9173026601509102, "lm_q1q2_score": 0.8798347773619658}}
{"text": "import idx2numpy\r\nfrom matplotlib import pyplot as plt\r\nimport numpy as np\r\n\r\n# using idx2numpy to import the MNIST dataset\r\ntrain_img = idx2numpy.convert_from_file('train-images.idx3-ubyte')\r\ntrain_lb = idx2numpy.convert_from_file('train-labels.idx1-ubyte')\r\ntest_img = idx2numpy.convert_from_file('t10k-images.idx3-ubyte')\r\ntest_lb = idx2numpy.convert_from_file('t10k-labels.idx1-ubyte')\r\n\r\nprint(train_img.shape)\r\nprint(train_lb.shape)\r\nprint(test_img.shape)\r\nprint(test_lb.shape)\r\n\r\n# set random seed\r\nnp.random.seed(42)\r\ntrainsize = 2000  # number of training images we use, selected randomly\r\nrandtrain = np.random.choice(train_img.shape[0], trainsize, replace=False)\r\ntrain_image, train_label = train_img[randtrain], train_lb[randtrain]\r\n\r\nnp.random.seed(10)\r\ntestsize = 10000  # number of testing images we use, selected randomly\r\nrandtest = np.random.choice(test_img.shape[0], testsize, replace=False)\r\ntest_image, test_label = test_img[randtest], test_lb[randtest]\r\n\r\nprint(train_image.shape, train_label.shape, test_image.shape, test_label.shape)\r\n\r\n\r\ntrainsize = 2000\r\nmatrix = []\r\nfor i in range(0, trainsize):\r\n    matrix.append(train_image[i].flatten())\r\n\r\nmatrix = np.array(matrix).T\r\n\r\nprint(matrix.shape)  # should be (784, trainsize)\r\n\r\n\r\n# print(matrix)\r\n\r\n# take an (x by k) matrix A (where x is the total number of pixels in an image\r\n# and k is the number of training images) and return a vector m of length x\r\n# containing the mean column vector of A and an (x by k) matrix V that\r\n# contains k eigenvectors of the covariance matrix of A\r\n# (after the mean has been subtracted). These should be sorted in descending\r\n# order by eigenvalue (i.e., V(:,1) is the eigenvector with the largest associated\r\n# eigenvalue) and normalized (i.e., norm(V(:,1)) = 1). You can reshape a vector\r\n# and display it as an image.\r\ndef hw1FindEigendigits(Mat):\r\n    mean = np.array(np.mean(Mat, axis=1), ndmin=2).T\r\n\r\n    mean_Matrix = np.broadcast_to(mean, (784, trainsize))\r\n    A = (Mat - mean_Matrix) / np.sqrt(trainsize)  # A should be a (784,trainsize) matrix\r\n\r\n    if trainsize < 784:\r\n        # compute A^tA\r\n        small_Mat = np.matmul(A.T, A)\r\n        # find the eigenvalues and eigenvectors of A^tA\r\n        mu, v = np.linalg.eig(small_Mat)\r\n    else:\r\n        small_Mat = np.matmul(A, A.T)\r\n        mu, v = np.linalg.eig(small_Mat)\r\n\r\n    # print(mu)\r\n    print(v[0].shape)  # should be (trainsize,)\r\n    # print(v[0])\r\n\r\n    # sort by eigenvalues in decreasing order\r\n    ls = []\r\n    for i in range(min(trainsize, 784)):\r\n        ls.append((mu[i], v[i]))\r\n    ls = sorted(ls, key=lambda ls: ls[0], reverse=True)\r\n    # print(ls)\r\n\r\n    # print(np.matmul(A,ls[0][1]).shape)  # should be (784,)\r\n\r\n    V = []\r\n    for i in range(min(trainsize, 784)):\r\n        if trainsize < 784:\r\n            vec = np.matmul(A, ls[i][1])\r\n            norm = np.linalg.norm(vec)\r\n            vec = vec / norm\r\n            # print(np.linalg.norm(vec))  # check the norm, should be 1\r\n            V.append(vec)\r\n        else:\r\n            V.append(ls[i][1])\r\n\r\n    V = np.array(V).T\r\n    print(V.shape)  # should be (784,trainsize)\r\n\r\n    return mean, V\r\n\r\n\r\nmean, V = hw1FindEigendigits(matrix)\r\n# print(mean.shape)  # should be (784,1)\r\n# print(mean)\r\n\r\n# code for displaying the first eight eigendigits\r\n\"\"\"\r\nfor i in range(8):\r\n    plt.subplot(2, 4, i + 1)\r\n    img = (V[:, i]).reshape(28, 28)\r\n    plt.title('#{}'.format(i + 1))\r\n    plt.imshow(img)\r\nplt.show()\r\n\"\"\"\r\n\r\n# print(V.shape)  # should be (784,8)\r\n\r\n# create eigenvector space\r\nOmega = []\r\nfor i in range(trainsize):\r\n    Omega_i = []\r\n    X_i = matrix[:, i] - mean[:, 0]\r\n    for j in range(min(trainsize, 784)):\r\n        Omega_i.append(np.dot(X_i, V[:, j]))\r\n    Omega.append(Omega_i)\r\n\r\nOmega = np.array(Omega)\r\n# print(Omega)  # should be (8,8)\r\n\r\n\r\n# Define our prediction function, which uses KNN to make predictions\r\ndef predict(testsize, k):\r\n    predict_label = []\r\n    for i in range(testsize):\r\n        # Form the eigenvector space of the predicting image\r\n        Omega_test = []\r\n        Y_i = test_image[i].flatten() - mean[:, 0]\r\n        for j in range(min(trainsize, 784)):\r\n            Omega_test.append(np.dot(Y_i, V[:, j]))\r\n        # print(Omega_test)\r\n\r\n        # reconstruct some test images with Matrix V and the Omega_test above\r\n        if i < 3 and trainsize < 600:\r\n            recon_img = np.matmul(V, Omega_test).reshape(28, 28)\r\n            print(recon_img.shape)\r\n            plt.imshow(recon_img)\r\n            plt.show()\r\n\r\n        # Calculate L2-norm distances\r\n        distance = []\r\n        for j in range(trainsize):\r\n            L2 = np.linalg.norm(np.array(Omega_test) - Omega[j, :])\r\n            distance.append((L2, train_label[j]))\r\n        # print(distance)\r\n        # Sort the distance in increasing order\r\n        distance = sorted(distance, key=lambda distance: distance[0])\r\n        # print(distance)\r\n\r\n        # Using KNN to choose the k nearest ones and pick the label that appears the most\r\n        KNN_arr = []\r\n        for i in range(k):\r\n            KNN_arr.append(distance[i][1])\r\n        # print(KNN_arr)  # should only contain the k-nearest labels\r\n\r\n        # create \"bins\" to count the occurrences of different labels and create \"order\"\r\n        # to count the appearing order of them.\r\n        bin = np.zeros((10,), dtype=int)\r\n        order = bin + 10\r\n        count = 0\r\n        for i in range(k):\r\n            bin[KNN_arr[i]] += 1\r\n            if order[KNN_arr[i]] == 10:\r\n                order[KNN_arr[i]] = count\r\n                count += 1\r\n\r\n        # print(bin, order*(-0.1))\r\n\r\n        # We subtract the bin count by 0.1 times the appearing order,\r\n        # so that the digit with highest counts and appears first will have\r\n        # the largest value.\r\n        # We use 0.1 here so that the digits appear n times will always\r\n        # have higher \"rank\" values than those appear (n-1) or fewer times.\r\n        rank = bin - 0.1 * order\r\n        # print(rank)\r\n\r\n        # using argmax to find the index of the largest value, which becomes\r\n        # the digit we predict, and assign it to label\r\n        label = np.argmax(rank)\r\n        predict_label.append(label)\r\n\r\n    return predict_label\r\n\r\n\r\n# set our testsize and k (number of nearest neighbors) to make predictions\r\ntestsize = 10000\r\nk = 4\r\n\r\n# display the first few actual test labels\r\nif trainsize < 600:\r\n    for i in range(3):\r\n        plt.imshow(test_image[i])\r\n        plt.show()\r\n\r\n# generate predicting labels\r\npredict_label = np.array(predict(testsize, k))\r\nprint(\"Our Predictions: {}\".format(predict_label))\r\n\r\n# assign actual labels to test_ans\r\ntest_ans = test_label[0:testsize]\r\nprint(\"Actual Labels:   {}\".format(test_ans))\r\n\r\n# Using \"==\" and sum to compute the number of correct predictions\r\nright_ones = sum(predict_label == test_ans)\r\n# Calculate accuracy\r\naccuracy = right_ones / testsize\r\n# Print accuracy with corresponding trainsize and testsize\r\nprint('Accuracy ({} trainsize, {} testsize): {}'.format(trainsize, testsize, accuracy))\r\n", "meta": {"hexsha": "8a0fc1e4a7f756cdc389d2242333d51e6a713804", "size": 7054, "ext": "py", "lang": "Python", "max_stars_repo_path": "estensions.py", "max_stars_repo_name": "ck44liu/PCA-KNN-for-mnist-classification", "max_stars_repo_head_hexsha": "0066bb8cfb795d4e1033e5494ff542e57db4514c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "estensions.py", "max_issues_repo_name": "ck44liu/PCA-KNN-for-mnist-classification", "max_issues_repo_head_hexsha": "0066bb8cfb795d4e1033e5494ff542e57db4514c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "estensions.py", "max_forks_repo_name": "ck44liu/PCA-KNN-for-mnist-classification", "max_forks_repo_head_hexsha": "0066bb8cfb795d4e1033e5494ff542e57db4514c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4312796209, "max_line_length": 90, "alphanum_fraction": 0.625602495, "include": true, "reason": "import numpy", "num_tokens": 1815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154280587323, "lm_q2_score": 0.9173026499774933, "lm_q1q2_score": 0.8798347633200075}}
{"text": "import numpy as np\n\ndef findAngle(a, b, c):\n    \"\"\"\n    find the angle between three point (return in degrees)\n    \"\"\"\n    ba = a - b\n    bc = c - b\n\n    cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))\n    angle = np.arccos(cosine_angle)\n\n    return np.degrees(angle)\n\ndef determinantBetweenPoint(p1, p2, p3):\n    \"\"\"\n    find the determinant between three point\n    if > 0 then it is left/upper from p1 and p2\n    if = 0 then it is in p1 and p2\n    if < 0 then it is right/below from p1 and p2\n    \"\"\"\n    x1 = p1[0]\n    y1 = p1[1]\n    x2 = p2[0]\n    y2 = p2[1]\n    x3 = p3[0]\n    y3 = p3[1]\n    return x1*y2 + x3*y1 + x2*y3 - x3*y2 - x2*y1 - x1*y3\n\ndef pointDistanceMax(S, P1, Pn):\n    \"\"\"\n    find the furthest point from  a line (P1, pn) to a point from array S\n    if the distance is the same then maximize the angle\n    \"\"\"\n    maxD = 0\n    pointMaxD = []\n    for i in S:\n        d = np.abs(np.cross(Pn-P1, i-P1)/np.linalg.norm(Pn-P1))\n        if (d > maxD):\n            maxD = d\n            pointMaxD = i\n\n        elif (d == maxD):\n            # maximize the angle if distance is the same\n            dAngle = findAngle(P1, i, Pn)\n            maxDAngle = findAngle(P1, pointMaxD, Pn)\n\n            if (dAngle > maxDAngle):\n                maxD = d\n                pointMaxD = i\n\n    return pointMaxD\n\n\ndef splittedConvex(S, P1, Pn, pivot):\n    \"\"\"\n    divide and conquer algorithm using quickHull\n    \"\"\"\n    if (len(S) == 0):\n        # there's no point in S, then P1 and Pn is convexPoint\n        convexPoint.append(\n            [np.array([P1[0], Pn[0]]), np.array([P1[1], Pn[1]])])\n\n    # edge case for only one point in S\n    elif (len(S) == 1):\n        pMax = S[0]\n        convexPoint.append(\n            [np.array([P1[0], pMax[0]]), np.array([P1[1], pMax[1]])])\n        convexPoint.append(\n            [np.array([pMax[0], Pn[0]]), np.array([pMax[1], Pn[1]])])\n\n    else:\n        # find the max distance between point in S to the line between P1 and Pn\n        pointMaxD = pointDistanceMax(S, P1, Pn)\n\n        # define S1 and S2\n        S1 = []\n        S2 = []\n        # split to S1 and S2\n        for i in S:\n            # if pivot is -1 then it is upside down of the original function \n            # multiply with -1 so that the function will work properly\n            if (pivot == -1):\n                dir = -1\n            else:\n                dir = 1\n\n            # check if point outside of the left triangle of P1, pointMaxD, and Pn\n            if (pointMaxD[0] > i[0]):\n                dir *= determinantBetweenPoint(pointMaxD, P1, i)\n\n                if (dir < 0):\n                    S1.append(i)\n\n            # check if point outside of the right triangle of P1, pointMaxD, and Pn\n            elif (pointMaxD[0] < i[0]):\n                dir *= determinantBetweenPoint(Pn, pointMaxD, i)\n\n                if (dir < 0):\n                    S2.append(i)\n\n        splittedConvex(S1, P1, pointMaxD, pivot)\n        splittedConvex(S2, pointMaxD, Pn, pivot)\n\n\ndef convexHull(listOfPoint):\n    \"\"\"\n    main function from convex hull\n    \"\"\"\n    # initialize convexPoint\n    global convexPoint\n    convexPoint = []\n\n    # sort array by the absis\n    listOfPoint = listOfPoint[listOfPoint[:, 1].argsort(kind='mergesort')]\n    listOfPoint = listOfPoint[listOfPoint[:, 0].argsort(kind='mergesort')]\n    # take the minimum of absis as P1\n    P1 = listOfPoint[0]\n    # take the maximum of absis as Pn\n    Pn = listOfPoint[-1]\n\n    # define S1 and S2\n    S1 = []\n    S2 = []\n    # split point by the line of P1 and Pn\n    for i in listOfPoint[1:-1]:\n        dir = determinantBetweenPoint(Pn, P1, i)\n        if (dir < 0):\n            S1.append(i)\n        elif (dir > 0):\n            S2.append(i)\n\n    # divide and conquer for S1 and S2\n    splittedConvex(S1, P1, Pn, 1)\n    splittedConvex(S2, P1, Pn, -1)\n    return convexPoint\n", "meta": {"hexsha": "12f8dee7f36314ba4ac11cc3a744f4143ec15cb8", "size": 3857, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/convexHull.py", "max_stars_repo_name": "apwic/convex-hull-visualizer", "max_stars_repo_head_hexsha": "738c4fc5641bda679fbecb5df2507aeec9233246", "max_stars_repo_licenses": ["FTL", "CNRI-Python"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/convexHull.py", "max_issues_repo_name": "apwic/convex-hull-visualizer", "max_issues_repo_head_hexsha": "738c4fc5641bda679fbecb5df2507aeec9233246", "max_issues_repo_licenses": ["FTL", "CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/convexHull.py", "max_forks_repo_name": "apwic/convex-hull-visualizer", "max_forks_repo_head_hexsha": "738c4fc5641bda679fbecb5df2507aeec9233246", "max_forks_repo_licenses": ["FTL", "CNRI-Python"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1532846715, "max_line_length": 83, "alphanum_fraction": 0.5400570391, "include": true, "reason": "import numpy", "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290963960278, "lm_q2_score": 0.9059898222871762, "lm_q1q2_score": 0.8798330774617432}}
{"text": "import numpy as np\nimport sympy as sp\nfrom sympy.utilities.lambdify import lambdastr\nimport itertools\nimport time\n\n\ndef monte_carlo_integration(integrand, bounds: list, n_sample: int = int(1e6)) -> float:\n    \"\"\"\n    Compute the definite integral with a monte carlo integration algorithm\n    :param integrand: the function to integrate (lambda or func)\n    :param bounds: list of integral bounds ex: [[0, 10], [0, 2], [-10, 10]] (list)\n    :param n_sample: number of sample to use (int)\n    :return: the integral of the integrand (float)\n    \"\"\"\n    np.random.seed(1)\n    count_in_curve: int = 0\n\n    def sampler():\n        while True:\n            yield [np.random.uniform(b0, b1) for [b0, b1] in bounds]\n\n    x_rn0, x_rn1 = next(sampler()), next(sampler())\n    f_min: float = np.min([integrand(*x_rn0), integrand(*x_rn1)])\n    f_max: float = np.max([integrand(*x_rn0), integrand(*x_rn1)])\n\n    for x in itertools.islice(sampler(), n_sample):\n        f: float = integrand(*x)\n\n        # Generate random point\n        f_rn: float = np.random.uniform(f_min, f_max)\n\n        # Increase the counter\n        count_in_curve += 1 if 0 <= f_rn <= f else 0\n\n        # update the domain size\n        f_min = np.min([f_min, f])\n        f_max = np.max([f_max, f])\n\n    # Compute the hyper volume v of the statistical box\n    v: float = np.prod([b1 - b0 for [b0, b1] in bounds]) * (f_max - f_min)\n    return (count_in_curve / n_sample) * v\n\n\nif __name__ == '__main__':\n    bounds_x: list = [0, 9]\n    bounds_y: list = [-10, 7]\n    bounds_z: list = [0, 10]\n\n    bounds: list = [bounds_x, bounds_y, bounds_z]\n\n    def g(x, y, z):\n        return 4*x**3 + y**2 + np.sqrt(z)\n\n    start_time = time.time()\n\n    P: float = monte_carlo_integration(g, bounds, n_sample=int(1e6))\n    print(f\"P = {P:.5e}\")\n    print(f\"--- elapse time: {time.time() - start_time} s ---\")\n\n    x, y, z = sp.symbols(\"x, y, z\")\n    f = 4*x**3 + y**2 + sp.sqrt(z)\n    print(f\"f = {f}\")\n    f_lambdify = sp.lambdify((x, y, z), f)\n    print(f\"f_lambdify -> {lambdastr((x, y, z), f)}\")\n\n    for n in [int(1e1), int(1e3), int(1e6), int(1e8)]:\n        start_time = time.time()\n        P: float = monte_carlo_integration(f_lambdify, bounds, n_sample=n)\n        print(f\"P = {P:.5e} for {n:2e} samples\")\n        print(f\"--- elapse time: {time.time() - start_time} s ---\")\n", "meta": {"hexsha": "0c74af5c4b2328773738ff07a4c75d0864fb444b", "size": 2319, "ext": "py", "lang": "Python", "max_stars_repo_path": "Integral_calculus/MonteCarlo_integration.py", "max_stars_repo_name": "JeremieGince/ProjetPythonPhysique", "max_stars_repo_head_hexsha": "4332eb23dc72fea542b7314d2365d877e0ca51d8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-02-02T02:14:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T23:50:01.000Z", "max_issues_repo_path": "Integral_calculus/MonteCarlo_integration.py", "max_issues_repo_name": "JeremieGince/TutorielPython-Manuel", "max_issues_repo_head_hexsha": "e474f5dcecbf3a1e1c7c776b7630f7c168cfd938", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Integral_calculus/MonteCarlo_integration.py", "max_forks_repo_name": "JeremieGince/TutorielPython-Manuel", "max_forks_repo_head_hexsha": "e474f5dcecbf3a1e1c7c776b7630f7c168cfd938", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2083333333, "max_line_length": 88, "alphanum_fraction": 0.6002587322, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813394, "lm_q2_score": 0.9184802429095672, "lm_q1q2_score": 0.8798234941429715}}
{"text": "import solver.algorithms as alg\nimport numpy as np\n\ndef problem4(t0, tf, NA0, NB0, tauA, tauB, n, returnlist=False):\n    \"\"\"Uses Euler's method to model the solution to a radioactive decay problem where dNA/dt = -NA/tauA and dNB/dt = NA/tauA - NB/tauB.\n\n    Args:\n        t0 (float): Start time\n        tf (float): End time\n        NA0 (int): Initial number of NA nuclei\n        NB0 (int): Initial number of NB nuclei\n        tauA (float): Decay time constant for NA\n        tauB (float): Decay time constant for NB\n        n (int): Number of points to sample at\n        returnlist (bool) = Controls whether the function returns the list of points or not. Defaults to false\n\n    Returns:\n        solution (list): Points on the graph of the approximate solution. Each element in the list has the form (t, array([NA, NB]))\n\n    In the graph, NA is green and NB is blue\n    \"\"\"\n    print(\"Problem 4: ~Radioactive Decay~ dNA/dt = -NA/tauA & dNB/dt = NA/tauA - NB/tauA - NB/tauB\")\n    N0 = np.array([NA0, NB0])\n    A = np.array([[-1/tauA, 0],[1/tauA, -1/tauB]])\n    def dN_dt(t, N):\n        return A @ N\n    h = (tf-t0)/(n-1)\n    print(\"Time step of %f seconds.\" % h)\n    solution = alg.euler(t0, tf, n, N0, dN_dt)\n    if returnlist:\n        return solution\n", "meta": {"hexsha": "9944ed29ef18664f91835683e77f02025e71e44d", "size": 1253, "ext": "py", "lang": "Python", "max_stars_repo_path": "solver/problem4.py", "max_stars_repo_name": "suzannastep/eulers", "max_stars_repo_head_hexsha": "886da24546a490a11bc31ace4fbfa71536b129bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solver/problem4.py", "max_issues_repo_name": "suzannastep/eulers", "max_issues_repo_head_hexsha": "886da24546a490a11bc31ace4fbfa71536b129bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-21T22:07:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-21T22:07:51.000Z", "max_forks_repo_path": "solver/problem4.py", "max_forks_repo_name": "suzannastep/eulers", "max_forks_repo_head_hexsha": "886da24546a490a11bc31ace4fbfa71536b129bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.15625, "max_line_length": 135, "alphanum_fraction": 0.6233040702, "include": true, "reason": "import numpy", "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338090839607, "lm_q2_score": 0.9149009636941993, "lm_q1q2_score": 0.8797082085554698}}
{"text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nnp.set_printoptions(precision=6)\n\n\ndef estimateGaussian(X):\n    \"\"\"This function estimates the parameters of a\n    Gaussian distribution using the data in X\n\n    [mu sigma2] = estimateGaussian(X),\n    The input X is the dataset with each n-dimensional data point in one row\n    The output is an n-dimensional vector mu, the mean of the data set\n    and the variances sigma^2, an n x 1 vector\n    :param X:\n    :return:\n    \"\"\"\n    # Useful variables\n    m, n = X.shape\n\n    mu = X.mean(axis=0)\n    sigma2 = ((X - mu) ** 2).mean(axis=0)\n    return mu, sigma2\n\n\ndef multivariateGaussian(X, mu, Sigma2):\n    \"\"\"Computes the probability density function of the\n    multivariate gaussian distribution.\n\n    p = multivariateGaussian(X, mu, Sigma2) Computes the probability\n    density function of the examples X under the multivariate gaussian\n    distribution with parameters mu and Sigma2. If Sigma2 is a matrix, it is\n    treated as the covariance matrix. If Sigma2 is a vector, it is treated\n    as the \\sigma^2 values of the variances in each dimension (a diagonal\n    covariance matrix)\n    :param X:\n    :param mu:\n    :param Sigma2:\n    :return:\n    \"\"\"\n    k = len(mu)\n\n    if len(Sigma2.shape) == 1:\n        Sigma2 = np.diag(Sigma2)\n\n    X = X - mu.reshape(1, -1)\n    p = (2 * np.pi) ** (- k / 2) * np.linalg.det(Sigma2) ** (-0.5) * np.exp(\n        -0.5 * np.diag(np.matmul(np.matmul(X, np.linalg.pinv(Sigma2)), X.transpose())))\n    return p\n\n\ndef visualizeFit(X, mu, sigma2):\n    \"\"\"Visualize the dataset and its estimated distribution.\n\n    visualizeFit(X, p, mu, sigma2) This visualization shows you the\n    probability density function of the Gaussian distribution. Each example\n    has a location (x1, x2) that depends on its feature values.\n    :param X:\n    :param mu:\n    :param sigma2:\n    :return:\n    \"\"\"\n    X1, X2 = np.meshgrid(np.arange(0, 35.5, 0.5), np.arange(0, 35.5, 0.5))\n    Z = multivariateGaussian(np.column_stack([X1.reshape(-1), X2.reshape(-1)]), mu, sigma2)\n    Z = Z.reshape(X1.shape)\n\n    plt.plot(X[:, 0], X[:, 1], 'bx')\n    # Do not plot if there are infinities\n    if np.sum(np.isinf(Z)) == 0:\n        plt.contour(X1, X2, Z, 10.0 ** np.arange(-20, 1, 3))\n\n\ndef selectThreshold(yval, pval):\n    \"\"\"Find the best threshold (epsilon) to use for selecting outliers\n\n    [bestEpsilon bestF1] = selectThreshold(yval, pval) finds the best\n    threshold to use for selecting outliers based on the results from a\n    validation set (pval) and the ground truth (yval).\n    :param yval:\n    :param pval:\n    :return:\n    \"\"\"\n    bestEpsilon = np.nan\n    bestF1 = 0\n\n    stepsize = (max(pval) - min(pval)) / 1000\n    for epsilon in np.arange(min(pval) + stepsize, max(pval) + stepsize, stepsize):\n        predictions = (pval < epsilon).astype(int)\n        precision = ((predictions == 1) & (yval == 1)).sum() / (predictions == 1).sum()\n        recall = ((predictions == 1) & (yval == 1)).sum() / (yval == 1).sum()\n        F1 = 2 * precision * recall / (precision + recall)\n\n        if F1 > bestF1:\n            bestF1 = F1\n            bestEpsilon = epsilon\n\n    return bestEpsilon, bestF1\n", "meta": {"hexsha": "a17b9c9089646a3bd542517bc97a6322b8dbbe0c", "size": 3167, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine-learning-python/machine-learning-ex8/ex8.py", "max_stars_repo_name": "StevenPZChan/ml_dl_coursera_Andrew_Ng", "max_stars_repo_head_hexsha": "c14f3490007392c16547e429c3028e9c80221013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-01-26T11:17:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T09:26:12.000Z", "max_issues_repo_path": "machine-learning-python/machine-learning-ex8/ex8.py", "max_issues_repo_name": "StevenPZChan/ml_dl_coursera_Andrew_Ng", "max_issues_repo_head_hexsha": "c14f3490007392c16547e429c3028e9c80221013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "machine-learning-python/machine-learning-ex8/ex8.py", "max_forks_repo_name": "StevenPZChan/ml_dl_coursera_Andrew_Ng", "max_forks_repo_head_hexsha": "c14f3490007392c16547e429c3028e9c80221013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-12T10:38:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-02T14:42:12.000Z", "avg_line_length": 32.3163265306, "max_line_length": 91, "alphanum_fraction": 0.634985791, "include": true, "reason": "import numpy", "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748209, "lm_q2_score": 0.9149009625340366, "lm_q1q2_score": 0.879708203406008}}
{"text": "\"\"\"\nProblem 6\n\nFind the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.\n\"\"\"\n\nimport numpy as np\n\ndef sum_of_squares(range_start, range_end):\n    return sum(i**2 for i in range(range_start, range_end))\n\ndef square_of_sum(range_start, range_end):\n    return sum(range(range_start, range_end)) ** 2\n\ndef compute_difference(range_start, range_end):\n    a = sum_of_squares(range_start, range_end)\n    b = square_of_sum(range_start, range_end)\n\n    return np.abs(a - b)\n\nprint(compute_difference(1, 101))\n\n", "meta": {"hexsha": "8541749f382ff22815fcf37806fdd0888fb4be85", "size": 562, "ext": "py", "lang": "Python", "max_stars_repo_path": "problem006.py", "max_stars_repo_name": "gboluwaga/ProjectEuler", "max_stars_repo_head_hexsha": "079496db04f1c3b6d2e421f8dd4db46b3f76b465", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-07-25T08:58:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-13T05:48:22.000Z", "max_issues_repo_path": "problem006.py", "max_issues_repo_name": "gboluwaga/ProjectEuler", "max_issues_repo_head_hexsha": "079496db04f1c3b6d2e421f8dd4db46b3f76b465", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem006.py", "max_forks_repo_name": "gboluwaga/ProjectEuler", "max_forks_repo_head_hexsha": "079496db04f1c3b6d2e421f8dd4db46b3f76b465", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2018-08-11T10:05:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-09T14:50:56.000Z", "avg_line_length": 24.4347826087, "max_line_length": 118, "alphanum_fraction": 0.7455516014, "include": true, "reason": "import numpy", "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.972414716174355, "lm_q2_score": 0.9046505434556231, "lm_q1q2_score": 0.8796955014513758}}
{"text": "import numpy as np\nimport math\n\n'''\nDifferent combination methods using python\n'''\n\n# Using raw mathematics\ndef comb(n, r):\n  num = denom_a = denom_b= 1\n  \n  # n!\n  if n >= 1:\n    for i in range (1,n+1):\n      num=num*i\n\n  if r < n:\n    # r!\n    for i in range (1,r+1):\n      denom_a=denom_a*i\n    \n    # (n-r)!\n    for i in range (1,n-r+1):\n      denom_b=denom_b*i\n  \n  return num/(denom_a*denom_b)\n\n# Using factorial  \ndef comb_fact(n, r):\n  return math.factorial(n)/(math.factorial(r)*math.factorial(n-r))\n\n# Using Stirling Approximation\ndef comb_stir(n,r):\n  def stirling(n):\n      return math.sqrt(2*math.pi*n)*(n/math.e)**n\n  return stirling(n)/(stirling(r)*stirling(n-r))\n\n# Using list\ndef comb_list(n, r):\n  num_list = []\n  denom_a = 1\n  denom_list = []\n\n  if n >= 1:\n    for i in range (1,n+1):\n      num_list.append(i)\n\n  if r < n:\n    for i in range (1,r+1):\n      denom_a=denom_a*i\n    \n    for i in range (1,n-r+1):\n      denom_list.append(i)\n\n  # or just use math.factorial\n  # denom_a = math.factorial(r)\n\n  new_num = [x for x in num_list if x not in denom_list]\n\n  return np.prod(new_num)/denom_a\n\n# Using list (shortened)\ndef comb_list_v2(n, r):\n  num_list = []\n  denom_a = 1\n  denom_list = []\n\n  if r < n:\n    for i in range (1,r+1):\n        denom_a=denom_a*i\n\n  if n >= 1:\n    for i in range (n-r+1,n+1):\n      num_list.append(i)\n\n  # or just use math.factorial\n  # denom_a = math.factorial(r)\n\n  return np.prod(num_list)/denom_a", "meta": {"hexsha": "0894a7f6dd558307ae428176905a3ea084407c72", "size": 1448, "ext": "py", "lang": "Python", "max_stars_repo_path": "permutation_combination/combination.py", "max_stars_repo_name": "ChuinHongYap/permutation-python", "max_stars_repo_head_hexsha": "51efa0d23a086a1520d77f6ed095be10cd7e182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-19T14:50:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T14:50:07.000Z", "max_issues_repo_path": "permutation_combination/combination.py", "max_issues_repo_name": "ChuinHongYap/permutation-python", "max_issues_repo_head_hexsha": "51efa0d23a086a1520d77f6ed095be10cd7e182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "permutation_combination/combination.py", "max_forks_repo_name": "ChuinHongYap/permutation-python", "max_forks_repo_head_hexsha": "51efa0d23a086a1520d77f6ed095be10cd7e182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-08T17:57:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T17:57:35.000Z", "avg_line_length": 18.3291139241, "max_line_length": 66, "alphanum_fraction": 0.601519337, "include": true, "reason": "import numpy", "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846716491915, "lm_q2_score": 0.8991213847035618, "lm_q1q2_score": 0.8796865807459607}}
{"text": "import numpy as np\nfrom numpy.core.function_base import linspace\nimport scipy\nimport scipy.stats\nimport matplotlib.pyplot as plt\nshape = 2\nscale = 3\nrv_gamma = scipy.stats.gamma(shape, scale=scale)\nrv_inv_gamma = scipy.stats.invgamma(shape, scale=scale)\nl = 1000\nsample_gamma = rv_gamma.rvs(size=[l])\nsample_inv_gamma = rv_inv_gamma.rvs(size=[l])\naxes = []\nfig,ax = plt.subplots()\nax.hist(sample_gamma, bins=\"auto\", density=True, color=[1,0.4,0.4,0.4], label=\"gamma distribution\")\naxes.append(ax)\nfor i in range(2):\n    axes.append(ax.twinx())\naxes[1].hist(sample_inv_gamma, bins=\"auto\", density=True, color=[0.4,0.4,1,0.4], label=\"inv-gamma distribution\")\n\nx = np.linspace(1e-8,20)\ndef pdf_gamma(x,shape, scale):\n    return 1/(scipy.special.gamma(shape)*shape**scale) * x**(shape-1) * np.exp(-x/scale)\ndef pdf_inv_gamma(x, shape, scale):\n    return scale**shape /scipy.special.gamma(shape) * x**(-shape-1) * np.exp(-scale/x)\ny_gamma = scipy.stats.gamma.pdf(x, shape, scale=scale)\ny_gamma_m = pdf_gamma(x, shape, scale)\ny_inv_gamma = pdf_inv_gamma(x,shape, scale)\naxes[2].plot(x,y_gamma, color=[1,0.4,0.4,0.9])\naxes[2].plot(x,y_gamma_m, color=[0.4,1,0.4,0.9])\naxes[2].plot(x,y_inv_gamma, color=[0.4,0.4,1,0.9])\nfor ax in axes:\n    ax.set_xlim(0,20)\n    ax.set_ylim(0,1.5)\nplt.savefig(\"./q3_explore_2.png\")\n", "meta": {"hexsha": "a3b8c432a0a450084c551000efc887fac599a037", "size": 1306, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment3/code/q3_explore_2.py", "max_stars_repo_name": "liusida/ds2", "max_stars_repo_head_hexsha": "1a4c6b3e0590d987c1e66d83bda1fb3382bf034e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment3/code/q3_explore_2.py", "max_issues_repo_name": "liusida/ds2", "max_issues_repo_head_hexsha": "1a4c6b3e0590d987c1e66d83bda1fb3382bf034e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment3/code/q3_explore_2.py", "max_forks_repo_name": "liusida/ds2", "max_forks_repo_head_hexsha": "1a4c6b3e0590d987c1e66d83bda1fb3382bf034e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2777777778, "max_line_length": 112, "alphanum_fraction": 0.7082695253, "include": true, "reason": "import numpy,from numpy,import scipy", "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846691281407, "lm_q2_score": 0.8991213826762113, "lm_q1q2_score": 0.8796865764957014}}
{"text": "import streamlit as st\n\nimport math\nimport numpy as np\nfrom  matplotlib import pyplot as plt\nfrom  plotly import graph_objects as go\nfrom typing import List\nimport pandas as pd\n\ninterval = st.sidebar.slider(\n    \"Interval\",\n    min_value=0.000001,\n    max_value=1.0,\n    step=0.00001,\n    value=0.5\n)\nΔt = st.sidebar.number_input(\n    \"Choose Δt for computing derivative:\",\n    min_value=0.00001,\n    max_value=0.1,\n    value=0.001,\n    step=0.05\n)\n\n\ndef _plot_exponentials():\n    base = 1\n\n    t = np.arange(0., 5., interval)\n    fig, ax = plt.subplots()\n\n    fig = go.Figure()\n\n    for b in range(base, base + 4):\n        ax.plot(t, b ** t, label=f\"a = {b}\")\n        fig.add_trace(go.Scatter(x=t, y=b**t, showlegend=True, name=f\"a = {b}\"))\n   \n    fig.update_layout(title=\"Plotting a^t vs t\", xaxis_title=\"t\", yaxis_title=\"a ^ t\")\n    st.plotly_chart(fig, use_container_width=True)\n\n\nst.markdown(\n    f\"\"\"\n    # Exponentials, Derivatives and `e`\n\n    In this article, we will observe some interesting properties of exponential functions and how the magical\n    constant `e` governs all exponential functions and their derivatives.\n\n    ## Exponential Functions\n\n    To refresh your memory, exponential functions are typically expressed as follows.\n    let `f(t)` be an exponential function of `t` that operates on some constant number `a`:\n    \"\"\"\n)\n\nst.latex(\n    r\"\"\"\n    f(t) = a ^ t\n    \"\"\"\n)\n\n\nst.markdown(\n    \"\"\"\n    Let's start out by plotting some familiar exponential values.\n    \"\"\"\n)\n\n\n_plot_exponentials()\n\n\nst.markdown(\"\"\"\n    ## Derivatives of Exponential Functions\n\n    Recall that the expression for computing the derivative of any function `f(t)` is:\n\"\"\")\n\nst.latex(\n    r\"\"\"\n    f'(t) = \\frac{Δf}{Δt} = \\frac{f(t + Δt) - f(t)}{Δt} \\hspace{3 pt} \\left( \\text {where \\Δt is small enough.} \\right)\n    \"\"\"\n)\n\nst.markdown(\"\"\"\n    Without further ado, let's just start plotting `f'(t)` and compare it against `f(t)`.\n\"\"\")\n\ndef _plot_exponential_derivative() -> None:\n\n    t = np.arange(0., 10., interval)\n\n    a = st.slider(\n        \"Choose a value of `a` as the base of the exponential function (example: 2.0):\",\n        min_value=0.01, max_value=10.0, value=2.0, step=0.01\n    )\n\n    fig, ax = plt.subplots()\n    ax.plot(t, a ** t, 'r+', label=\"f(t)\")\n    ax.plot(\n        t, (a ** (t + Δt) - a ** t) / Δt, 'bo', label=\"f'(t)\",\n    )\n    ax.plot(t, ((a ** (t + Δt) - a ** t) / Δt) / (a ** t), label=\"f'(t) / f(t)\" )\n\n    _ = ax.legend()\n    ax.set_xlabel(\"t\")\n    fig.suptitle(f\"Base: {a}, c: {((a ** Δt) - 1) / Δt} where c = f'(t) / f(t)\")\n    st.pyplot(fig, use_container_width=True)\n    # st.plotly_chart(fig, use_container_width=True)\n\n_plot_exponential_derivative()\n\nst.markdown(\"\"\"\n    The most important observation from the above graph is the ratio `f'(t) / f(t)` is a constant\n    value for all values of `t`.  We will see shortly what that is the case, but the key insight\n    from this observation is that **the rate of change of an exponential function at some `t` is\n    proportional to the value of the exponential function at `t`.**  Mathematically speaking:\n    \"\"\")\n\nst.latex(r\"\"\"f(t) = a^t, f'(t) = K a^t\"\"\")\n\nst.markdown(\"\"\"\n    By playing with the slider in the chart above, you can see that the value of `K` is different for\n    different values of `a`.\n\n    **It is worth conteplating at this point if there exists a value of `a` for which `K` is equal to `1`.**\n\n    Without getting entangled in the mathematical expressions, let's just try to figure out the value of\n    `a` for which `K = 1` by tweaking the slider in the above chart.  Give it a try!\n\n    >Hint: If you play with the `a` number for a bit, you will see that the scaling\n    >factor `K` is close to `1.0` when `a` is approximately `2.72`.  Keep this number in mind,\n    >as it will appear once again later in this tutorial.\n    \"\"\"\n)\n\nst.markdown(\"\"\"\n    ## Magical Multiplier to Rule All Exponential Derivatives\n    Now, let's approach the same setup from a different perspective.\n\n    Recall from the earlier sections that `f'(t) = f(t) * c` where:\n\"\"\")\n\nst.latex(r'c = \\left(\\frac{a^{dt} - 1}{dt}\\right) \\text{for some small value of dt.}')\n\nst.markdown(\"\"\"\n    To gain more insight into the behavior of this multiplier, we will observe its values\n    for various values of `a`. For convention, let's rewrite it as a function in `a`:\n\"\"\")\nst.latex(r'g(a) = \\left(\\frac{a^{dt} - 1}{dt}\\right) \\text{for some small value of dt.}')\n\ndef _plot_multiplier_vs_base() -> None:\n    interval = st.slider(\n        \"Interval:\", min_value=0.000001, max_value=1.0, step=0.00001, value=0.5, key='i4'\n    )\n    bases = np.arange(1., 50., interval)\n\n    dt = st.number_input(\n        \"Choose `dt` for computing derivative:\",\n        min_value=0.00001, max_value=0.1, value=0.001, step=0.05, key='dt1'\n    )\n\n    fig, ax = plt.subplots()\n    ax.plot(bases, (bases ** dt - 1) / dt, '+')\n    ax.set_xlabel('a')\n    ax.set_ylabel('g(a)')\n    st.plotly_chart(fig, use_container_width=True)\n\n    g = [\n        [2, (2 ** dt - 1) / dt],\n        [4, (4 ** dt - 1) / dt],\n        [5, (5 ** dt - 1) / dt],\n        [8, (8 ** dt - 1) / dt],\n        [25, (25 ** dt - 1) / dt],\n        [64, (64 ** dt - 1) / dt],\n    ]\n    st.dataframe(pd.DataFrame.from_records(g, columns=['a', 'g(a)']))\n\n_plot_multiplier_vs_base()\n\nst.markdown(\"\"\"\n    Notice the peculiar shape of this chart.\n    To gain more insight in the shape, observe the hand-picked values in the table.\n    \n    From the above table, you can see that:\n\"\"\")\n\nst.latex(r'''\n    g(a^2) = 2 g(a)\n''')\n\nst.markdown(\"\"\"\n    This is a strong hint that `g(a)` is a logarithmic function!\n    But it is not quite the [common logarithm](https://en.wikipedia.org/wiki/Common_logarithm),\n    because we know that `log` of `2` to the base `10` is approximately `0.30103`.\n\n    **So what is really the base of this logarithmic function?**\n\n    ### Finding the Base of of Logarithmic Multiplier\n    Let `x` be the unknown base of the logarithm function represented by `g`:\n\"\"\")\n\nst.latex(r'''\n    g(a) = log_x (a) \\hspace{2 pt} \\text {where x represents the unknown base of this log function.}\n''')\n\nst.write(\"Let's take the specific examples from the table above:\")\nst.latex(r\"\"\"log_x(2) = 0.6931 \\dots\"\"\")\nst.latex(r\"\"\"log_x(4) = 1.3873 \\dots\"\"\")\nst.latex(r\"\"\"log_x(5) = 1.6107 \\dots\"\"\")\nst.latex(r\"\"\"log_x(8) = 2.0816 \\dots\"\"\")\nst.latex(r\"\"\"log_x(16) = 2.7764 \\dots\"\"\")\nst.latex(r\"\"\"log_x(25) = 3.2241 \\dots\"\"\")\nst.latex(r\"\"\"log_x(64) = 4.1675 \\dots\"\"\")\n\nst.markdown(\"\"\"\n    To empirically find `x` in the above expression, let's just plot the expression for\n    various values of `x`.\n\"\"\")\n\ndef _plot_exponents_for_x():\n    interval = st.slider(\n        \"Interval:\", min_value=0.000001, max_value=1.0, step=0.00001, value=0.5, key='i5'\n    )\n    x = np.arange(1., 10., interval)\n    \n    a = st.number_input(\n        \"Choose a value of `a` for the exponential (example: 2.0):\",\n        min_value=0.01, max_value=10.0, value=2.0, step=1.0\n    )\n\n    fig, ax = plt.subplots()\n    ax.plot(x, np.log(a) / np.log(x), '+')\n    ax.set_xlabel('x')\n    ax.set_ylabel('log(a) to the base x')\n    fig.suptitle(f\"a: {a}\")\n    st.plotly_chart(fig, use_container_width=True)\n\n_plot_exponents_for_x()\n\nst.markdown(f\"\"\"\n    In this chart, try varying the value of `a`, and for each value of `a`, try to find\n    the value of `x` that corresponds to a y-axis value that matches `log_x(a)` in the table above.\n\n    For example, if we set `a` to `2.0`, what is the value of `x` that is close to the value\n    `0.6931...` on the y-axis?  The answer is a number between `2.7` and `2.8`, which is\n    suspiciously close to the number we observed earlier.\n\n    As another example, if we set `a` to `5.0`, what is the value of `x` that is close to the value\n    `0.6931...` on the y-axis?  The answer is again a number between `2.7` and `2.8`, which is\n    suspiciously close to the number we observed earlier.\n\n    This in fact is the magical number `e` that is the base of the logarithmic function represented by `g`!\n\"\"\")\n\nst.latex(r\"\"\"g(a) = log_e(a) = ln(a)\"\"\")\n\nst.markdown(\"\"\"\n    >The more precise value of `e` according to the `numpy` package is {np.e}.\n\n    ## Connecting the Dots\n    This magical number `e` underpins the phenomenon where the rate of change of an exponential function `a^t` at\n    a certain value of `t` is proportional to the value `a^t` multiplied by the log of `a` to the base `e`:\n\"\"\")\n\nst.latex(r\"\"\"f(t) = a^t\"\"\")\nst.latex(r\"\"\"\n    f'(t) = a^t log_e(a) = a^t ln(a)\n\"\"\")\n\nst.markdown(\"\"\"\n    The natural extension of this expression is when `a = e`, `f'(t) = f(t)`:\n\"\"\")\n\nst.latex(r\"\"\"f(t) = e^t\"\"\")\nst.latex(r\"\"\"\n    f'(t) = e^t log_e(e) = e^t\n\"\"\")\n\n\nst.markdown(\"\"\"\n    ## References\n\n    This tutorial is basically a watered down version of this mindblowing [YouTube video](https://www.youtube.com/watch?v=m2MIpDrF7Es).\n    \n    I created this tutorial just to convince myself of all the math in the video and also to play with Streamlit open-source library.\n    Do check out the documentation at [https://docs.streamlit.io/](https://docs.streamlit.io/) and follow along interesting discussions\n    at [https://discuss.streamlit.io/](https://discuss.streamlit.io/).\n\n\"\"\")", "meta": {"hexsha": "e52592821b3c2018f81a0b8f1f47c3c3d42f68a5", "size": 9210, "ext": "py", "lang": "Python", "max_stars_repo_path": "what_is_e.py", "max_stars_repo_name": "Amey-D/math-apps", "max_stars_repo_head_hexsha": "b2a475cd6f99f2923b1dc48a0879e2afb4683cef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-17T09:33:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-23T13:21:47.000Z", "max_issues_repo_path": "what_is_e.py", "max_issues_repo_name": "Amey-D/math-apps", "max_issues_repo_head_hexsha": "b2a475cd6f99f2923b1dc48a0879e2afb4683cef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "what_is_e.py", "max_forks_repo_name": "Amey-D/math-apps", "max_forks_repo_head_hexsha": "b2a475cd6f99f2923b1dc48a0879e2afb4683cef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7586206897, "max_line_length": 135, "alphanum_fraction": 0.6300760043, "include": true, "reason": "import numpy", "num_tokens": 2783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.9496693700734142, "lm_q1q2_score": 0.8796822761807831}}
{"text": "import numpy as np\n\n\n\n\ndef float_is_zero(v, eps=1e-6):\n    \"\"\" Test if floating point number is zero. \"\"\"\n    return abs(v) < eps\n\ndef special_div(num, den):\n    \"\"\" Return num/dev with the special rule\n    that 0/0 is 0. \"\"\"\n    if float_is_zero(num) and float_is_zero(den):\n        return 0.0\n    else:\n        return num / den\n\ndef B(j, p, x, knots):\n    \"\"\" Compute B-splines using recursive definition. \"\"\"        \n    if p == 0:\n        if knots[j] <= x < knots[j+1]:\n            return 1.0\n        else:\n            return 0.0\n    else:\n        left = special_div((x-knots[j])*B(j,p-1,x,knots), knots[j+p]-knots[j])\n        right = special_div((knots[j+1+p]-x)*B(j+1,p-1,x,knots), knots[j+1+p]-knots[j+1])\n        return left + right\n\ndef get_mu(x, knots, mu=None):\n    \"\"\"\n    Find the knot interval index (mu) for a given value x\n    This is a prerequisite for alg 2.20 and 2.21.\n    Optional to supply a suggestion to try first.\n    Throws on error.\n    \"\"\"\n    if mu != None:\n        if x >= knots[mu] and x < knots[mu+1]:\n            return mu\n    for mu in range(0, len(knots)-1):\n        if x >= knots[mu] and x < knots[mu+1]:\n            return mu\n    raise RuntimeError(\"Illegal knot vector or x value\")\n\ndef R_mat(k, mu, knots, x):\n    \"\"\"\n    Compute k'th B-spline matrix (k=1...)\n    mu: so that t_{mu} <= x < t_{mu+1}\n    knots: the knot vector\n    x: value to evaluate in\n    \"\"\"\n    res = np.zeros((k,k+1))\n    for row in range(k):\n        common_denom = knots[mu+(row+1)] - knots[mu+(row+1)-k]\n        res[row,row] = special_div(knots[mu+(row+1)] - x, common_denom)\n        res[row,row+1] = special_div(x - knots[mu + (row+1) - k], common_denom)\n    return res\n\ndef alg_220(p, knots, control_points, x, mu=None):\n    \"\"\"\n    Compute the spline function value at x\n    p: degree\n    knots: knots vector\n    control_points:\n    x: value to evaluate at\n    \"\"\"\n    if mu == None:\n        # auto-determine mu\n        mu = get_mu(x, knots)\n    c = np.array(control_points[(mu-p):(mu+1)])\n    assert( len(c) == p+1 )\n    for k in range(p, 0, -1):   # k = p...1\n        c = R_mat(k, mu, knots, x).dot(c)\n    return c    \n\ndef alg_221(p, knots, x):\n    \"\"\"\n    Evaluate all p+1 nonzero B-splines at x\n    p: degree\n    knots: knot vector\n    x: value to evaluate at\n    \"\"\"\n    mu = get_mu(x, knots)\n    B = np.array([1.0])\n    for k in range(1, p+1):\n        B = B.dot(R_mat(k, mu, knots, x))\n    return B\n    \ndef render_spline(p, knots, control_points, ts):\n    \"\"\"\n    Compute points on a spline function using the straightforward\n    implementation of the recurrence relation for the B-splines.\n    \"\"\"\n    \n    ys = []\n    for t in ts:\n        y = 0.0 \n        for j in range(0, len(control_points)):\n            y += B(j, p, t, knots)*control_points[j]\n        ys.append(y)\n    return ys\n\ndef render_spline_alg220(p, knots, control_points, ts):\n    # TODO: verify input data\n    # TODO: reuse get_mu() and alg_220()\n    xs = []\n    mu = None\n    for t in ts:\n        # Try the last mu value first, and then search if needed\n        if mu == None or not (t >= knots[mu] and t < knots[mu+1]):\n            mu = None\n            for i in range(0, len(knots)-1):\n                if t >= knots[i] and t < knots[i+1]:\n                    mu = i\n            if mu == None: raise Exception(\"Unable to determine mu\")\n\n        # Compute the B-spline vector\n        B_vec = np.array([[1]])\n        for k in range(1, p+1):\n            Rk = R_mat(k, mu, knots, t)\n            B_vec = B_vec.dot(Rk)\n\n        # Dot with correct part of control point vector\n        c0 = control_points[(mu-p):(mu+1)]\n        x = B_vec.dot(c0)[0]\n        xs.append(x)\n    return xs\n\ndef uniform_regular_knot_vector(n, p, t0=0.0, t1=1.0):\n    \"\"\"\n    Create a p+1-regular uniform knot vector for\n    a given number of control points\n    Throws if n is too small\n    \"\"\"\n\n    # The minimum length of a p+1-regular knot vector\n    # is 2*(p+1)\n    if n < p+1:\n        raise RuntimeError(\"Too small n for a uniform regular knot vector\")\n\n    # p+1 copies of t0 left and p+1 copies of t1 right\n    # but one of each in linspace\n    return [t0]*p + list(np.linspace(t0, t1, n+1-p)) + [t1]*p\n\ndef control_points(p, knots):\n    \"\"\"\n    Return the control point abscissa for the control polygon\n    of a one-dimensional spline.\n    \"\"\"\n    knots = np.array(knots)\n    abscissas = []\n    for i in range(len(knots)-p-1):\n        part = knots[(i+1):(i+1+p)]\n        abscissas.append(np.mean(part))\n    return abscissas\n\ndef render_tensor_prod_spline(p1, p2, knots1, knots2, control_points, us, vs):\n    \"\"\" Slow ref. impl. \"\"\"\n    res = np.empty((len(us), len(vs)))\n    n1, n2 = control_points.shape\n    assert(n1 == len(knots1) - p1 - 1)\n    assert(n2 == len(knots2) - p2 - 1)\n    for u_i,u in enumerate(us):\n        for v_i,v in enumerate(vs):\n            s = 0.0\n            for i in range(n1):\n                for j in range(n2):\n                    s += control_points[i,j]*B(i, p1, u, knots1)*B(j, p2, v, knots2)\n            res[u_i, v_i] = s\n    return res\n\ndef least_squares_surface_fit(xs, ys, zs, ws1, ws2, p1, p2, knots1, knots2):\n    \"\"\"\n    Data points (xs[i], ys[j], zs[i,j]) (i=1..m1, j=1..m2)\n    ws1[i] weights (i=1..m1)\n    ws2[j] weights (j=1..m2)\n    Spline spaces S1 and S2 implicitly defined by \n    (p1, knots1) and (p2, knots2):\n        n1=len(knots1)-(p1+1)\n        n2=len(knots2)-(p2+1)\n    Returns n1 x n2 matrix of coefficients\n    \"\"\"\n    m1, m2 = zs.shape\n    assert(m1 == len(xs))\n    assert(m2 == len(ys))\n    assert(len(ws1) == m1)\n    assert(len(ws2) == m2)\n    \n    n1 = len(knots1) - (p1+1)\n    n2 = len(knots2) - (p2+1)\n    \n    # Create matrix A\n    A = np.empty((m1, n1))\n    for i in range(m1):\n        for q in range(n1):            \n            A[i, q] = np.sqrt(ws1[i])*B(q, p1, xs[i], knots1)\n\n    # Create matrix _B\n    _B = np.empty((m2, n2))\n    for j in range(m2):\n        for r in range(n2):\n            _B[j, r] = np.sqrt(ws2[j])*B(r, p2, ys[j], knots2)\n    \n    # Create matrix G\n    G = np.empty((m1, m2))\n    for i in range(m1):\n        for j in range(m2):\n            G[i, j] = np.sqrt(ws1[i])*np.sqrt(ws2[j])*zs[i, j]\n\n    # Compute the coefficient matrix from eq. (7.20)\n    A_trans = A.transpose()\n    M1 = np.linalg.inv(A_trans.dot(A))\n    M2 = np.linalg.inv(_B.transpose().dot(_B))\n    C = M1.dot(A_trans).dot(G).dot(_B).dot(M2)\n    \n    return C\n\ndef lsq_spline_fit(xs, ys, knots, p, ws=None):\n    \"\"\"\n    Returns spline coefficients for least-squares\n    fit of function samples (x_i, y_i) on an arbitrary\n    knot vector and degree.\n    \"\"\"\n    if ws == None:\n        ws = np.ones((len(xs),))\n    m = len(xs)\n    n = len(knots) - p - 1  # number of control points in approximation\n    assert(m == len(ys))\n    \n    # Create matrix A\n    A = np.empty((m,n))\n    for row in range(m):\n        for col in range(n):\n            A[row, col] = np.sqrt(ws[row])*B(col, p, xs[row], knots)\n\n    # Create vector b\n    b = np.empty((len(xs),))\n    for i in range(m):\n        b[i] = np.sqrt(ws[i])*ys[i]\n\n    # Compute least-squares coefficients\n    Atrans = A.T\n    c = np.linalg.inv(Atrans.dot(A)).dot(Atrans).dot(b)\n    \n    return c\n\ndef render_tensor_product_surface_alg_221(p1, p2, knots1, knots2, control_points, xs, ys):\n    \"\"\" Evaluate at xs,ys \"\"\"\n    xs = np.array(xs)\n    ys = np.array(ys)\n    res = np.empty((xs.shape[0], ys.shape[0]))\n\n    for x_i,x in enumerate(xs):\n        for y_i, y in enumerate(ys):\n            # Find the knot indices\n            mv = get_mu(x, knots1)\n            mu = get_mu(y, knots2)\n            \n            # Extract the correct part of the control point matrix\n            C = control_points[(mv-p1):(mv+1), (mu-p2):(mu+1)]\n            \n            # Compute the non-zero basis functions\n            Bx = alg_221(p1, knots1, x)\n            By = alg_221(p2, knots2, y)\n            \n            value = Bx.dot(C).dot(By)\n            res[x_i, y_i] = value\n\n    return res\n\ndef B_derivative(j, p, x, knots):\n    \"\"\"\n    Evaluate the derivative of Bj,p(x)\n    p must be greater than or equal to 1\n    Using theorem 3.16 from the book.\n    \"\"\"\n    if p < 1: raise RuntimeError(\"p must be greater than or equal to 1\")\n    left = special_div(B(j, p-1, x, knots), (knots[j+p]-knots[j]) )\n    right = special_div(B(j+1,p-1, x, knots), (knots[j+p+1] - knots[j+1]) )\n    return (left - right)*p\n\ndef general_spline_interpolation(xs, ys, p, knots=None):\n    \"\"\"\n    NOTE: SLOW SINCE IT USES B()\n    xs,ys:  interpolation points\n    p:      degree\n    knots:  If None, use p+1-regular from xs[0] to slightly past x[1]\n    \n    returns cs, knots\n    \"\"\"\n    \n    # number of interpolation points (and also control points)\n    m = len(xs)\n    assert(len(ys) == m)\n\n    # use p+1-regular knot vector with ends equal to first sample and slightly\n    # past last sample\n    if knots == None:\n        knots = uniform_regular_knot_vector(m, p, t0=xs[0], t1=xs[-1]+0.001)\n\n    # create matrix A\n    A = np.zeros((m,m))\n    for row in range(m):\n        for col in range(m):\n            A[row, col] = B(col, p, xs[row], knots)\n    \n    # compute control points\n    cs = np.linalg.inv(A).dot(np.array(ys))\n    return cs, knots\n\ndef alpha(j, p, i, coarse_knots, refined_knots):\n    \"\"\" Compute B-splines using recursive definition. \"\"\"        \n    x = refined_knots[i+p]\n    knots = coarse_knots\n    if p == 0:\n        if knots[j] <= x < knots[j+1]:\n            return 1.0\n        else:\n            return 0.0\n    else:\n        left = special_div((x-knots[j])*alpha(j,p-1,i,coarse_knots, refined_knots), knots[j+p]-knots[j])\n        right = special_div((knots[j+1+p]-x)*alpha(j+1,p-1,i,coarse_knots,refined_knots), knots[j+1+p]-knots[j+1])\n        return left + right\n\ndef oslo_alg1(p, coarse_knots, refined_knots):\n    \"\"\"\n    Compute knot insertion matrix using Oslo-algorithm 1.\n    Returns the m x n knot insertion matrix.\n    \"\"\"\n    n = len(coarse_knots) - p - 1\n    m = len(refined_knots) - p - 1\n    A = np.zeros((m, n,))\n    for i in range(m):\n        mu = get_mu(refined_knots[i], coarse_knots)\n        if p == 0:\n            res = 1\n        else:\n            res = R_mat(1, mu, coarse_knots, refined_knots[i+1])\n            for k in range(2, p+1):\n                res = res.dot(R_mat(k, mu, coarse_knots, refined_knots[i+k]))\n        A[i, mu-p:(mu+1)] = res\n    return A\n\ndef oslo_alg2(p, cs, coarse_knots, refined_knots):\n    \"\"\"\n    Compute control points relative to refined knot vector\n    using Oslo-algorithm 2\n    Returns length-m control point vector.\n    \"\"\"\n    n = len(coarse_knots) - p - 1\n    m = len(refined_knots) - p - 1\n    b = np.zeros((m,))\n    for i in range(m):\n        mu = get_mu(refined_knots[i], coarse_knots)\n        if p == 0:\n            res = cs[mu]\n        else:\n            _cs = cs[(mu-p):(mu+1)]\n            res = R_mat(1, mu, coarse_knots, refined_knots[i+1])\n            for k in range(2, p+1):\n                res = res.dot(R_mat(k, mu, coarse_knots, refined_knots[i+k]))\n            res = res.dot(_cs)\n        b[i] = res\n    return b\n    \ndef test_render_tensor_product_surface_alg_221_1():\n    \"\"\"\n    Compare using algorithm 2.21 with using the recurrence \n    relation.\n    \"\"\"\n    \n    n1 = 10 # x \n    n2 = 10 # y\n    p1 = 3\n    p2 = 3\n    cs = np.random.uniform(low=0.0, high = 10.0, size=(n1, n2))\n    knots1 = uniform_regular_knot_vector(n1, p1)\n    knots2 = uniform_regular_knot_vector(n2, p2)\n    \n    # Where to evaluate\n    xs = np.linspace(knots1[0], knots1[-1]-0.01, 10)\n    ys = np.linspace(knots2[0], knots2[-1]-0.01, 10)\n    for x in xs:\n        for y in ys:\n            f1 = render_tensor_product_surface_alg_221(p1, p2, knots1, knots2, cs, [x], [y])\n            f2 = render_tensor_prod_spline(p1, p2, knots1, knots2, cs, [x], [y])\n            assert(float_is_zero(f1-f2))\n    \n\ndef test_alg_220_1():\n    \"\"\"\n    Verify that alg 2.20 agrees with the direct implementation\n    of algorithm 2.20\n    \"\"\"\n    \n    p = 3\n    n = 10\n    knots = uniform_regular_knot_vector(n, p)\n    cs = range(10)\n    for t in np.linspace(0.0, 0.99, 100):\n        # Evaluate with recurrence relation\n        x1 = render_spline(p, knots, cs, [t])\n        # Evaluate with alg 2.20\n        x2 = alg_220(p, knots, cs, t)\n        assert(float_is_zero(x1-x2))\n\ndef test_get_mu_1():\n    \"\"\"\n    Verify that the knot interval search works\n    on some simple cases\n    \"\"\"\n    assert(get_mu(0.1, [0.0, 1.0]) == 0)\n    assert(get_mu(1.0, [0.0, 1.0, 2.0]) == 1)\n    assert(get_mu(1.0, [0.0, 0.0, 0.0, 0.9, 1.1, 1.1, 1.1]) == 3)\n\ndef test_alg_221_1():\n    \"\"\"\n    Verify that algorithm 2.21 produces the same\n    results as the direct implementation of the\n    recurrence relation.\n    \"\"\"\n    n = 5\n    p = 3\n    knots = uniform_regular_knot_vector(n, p)\n    \n    ts = np.linspace(knots[0], knots[-1]-0.01, 10)\n    \n    for t in ts:\n        # Compute all B-splines at once with alg 2.21\n        B1 = alg_221(p, knots, t)\n        mu = get_mu(t, knots)\n        \n        # Compute one by one with recurrence relation\n        for j in range(p+1):\n            B2 = B(j+mu-p, p, t, knots)\n            assert( float_is_zero(B2 - B1[j]) )\n        \n\ndef test_bspline_derivative():\n    \"\"\"\n    Compare B-spline derivatives with numerical differentiation\n    of the B-splines.\n    \"\"\"\n    import matplotlib.pyplot as plt\n    p = 2\n    knots = [0.0, 0.0, 0.0, 1.0, 1.4, 1.9, 2.1, 2.1, 2.1]\n    ts = np.linspace(knots[0], knots[-1]-0.001, 10000)\n    for j in range(0, len(knots)-p-1):\n        plt.figure(j)\n        xs = map(lambda x: B(j, p, x, knots), ts)\n        xs_der = map(lambda x: B_derivative(j, p, x, knots), ts)\n        plt.subplot(2,1,1)\n        plt.plot(ts, xs_der, label='Analytical')\n        \n        xs_num_der = np.diff(xs)/np.diff(ts)\n        plt.plot(ts[:-1], xs_num_der, label='Numerical')\n        plt.title('Basis function derivative %d' % j)\n        plt.subplot(2,1,2)\n        error = xs_der[:-1]-xs_num_der\n        plt.plot(error)\n        plt.title('Error')\n        \n    plt.show()\n        \n        \n   \n    \nif __name__ == '__main__':\n    test_get_mu_1()\n    test_alg_220_1()\n    test_alg_221_1()\n    test_render_tensor_product_surface_alg_221_1()\n    test_bspline_derivative()\n", "meta": {"hexsha": "d6b6b5a1031408c1fc0288ecd41dbbd739079bdf", "size": 14166, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/bsplines.py", "max_stars_repo_name": "sigurdstorve/supersplines", "max_stars_repo_head_hexsha": "a49cac9f7e166b660fb1da688f9bf5d90f05dcdb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-07T02:40:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T07:09:08.000Z", "max_issues_repo_path": "python/bsplines.py", "max_issues_repo_name": "sigurdstorve/supersplines", "max_issues_repo_head_hexsha": "a49cac9f7e166b660fb1da688f9bf5d90f05dcdb", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/bsplines.py", "max_forks_repo_name": "sigurdstorve/supersplines", "max_forks_repo_head_hexsha": "a49cac9f7e166b660fb1da688f9bf5d90f05dcdb", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8860759494, "max_line_length": 114, "alphanum_fraction": 0.5561908796, "include": true, "reason": "import numpy", "num_tokens": 4502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144273, "lm_q2_score": 0.924141819456443, "lm_q1q2_score": 0.8796566187378465}}
{"text": "import time\n\nimport numpy as np\n\n\ndef jacobi(A, b, max_iter_time=5000, min_iter_time=100, tolerance=1e-10):\n    \"\"\"\n    Jacobi iteration for solving the linear equations with below form:\n        A * u = b\n\n    ---------------\n    :param A: (N, N) array_like\n        Matrix A (n*n size). Square input data.\n    :param b: (N, 1) array_like\n        Vector b (n*1 size). Input data for the right hand side.\n    :param max_iter_time: int, optional\n        Maximal iteration times.\n    :param min_iter_time: int, optional\n        Minimal iteration times\n    :param tolerance: float, optional\n        The difference tolerance for adjacent u solutions.\n    ---------------\n    :return:\n        The solution array u. Or suggestive error message.\n    \"\"\"\n    start = time.clock()\n    end = time.clock()\n\n    A = np.array(A)\n    b = np.array(b)\n    n, m = A.shape\n    if n != m:\n        return \"The row size of matrix 'A' is not equal to its column size.\"\n    if n != b.shape[0]:\n        return \"The row size of matrix 'A' is not equal to the size of vector 'b'.\"\n    b.reshape(n)\n    aii = np.array([A[i, i] for i in range(n)])\n    x_before = np.zeros(n)\n    x_cur = np.zeros(n)\n\n    # iteration\n    for i in range(max_iter_time):\n        for r in range(n):\n            remain = np.dot(A[r, :], x_before[:]) - A[r, r] * x_before[r]\n            x_cur[r] = (b[r] - remain) / aii[r]\n        if max(abs(x_cur - x_before)) < tolerance and i > min_iter_time:\n            print('Jacobi Iteration:', i + 1)\n            print('Time past:', time.clock() - start)\n            return x_cur\n        else:\n            x_cur, x_before = x_before, x_cur\n    print(\"Maximal iteration times reached.\")\n\n    print('Jacobi Iteration:', i + 1)\n    print('Time past:', time.clock() - start)\n    return x_cur\n\n\ndef gauss_seidel(A, b, max_iter_time=5000, min_iter_time=100, tolerance=1e-10):\n    \"\"\"\n    Gauss-Seidel iteration for solving the linear equations with below form:\n        A * u = b\n\n    ---------------\n    :param A: (N, N) array_like\n        Matrix A (n*n size). Square input data.\n    :param b: (N, 1) array_like\n        Vector b (n*1 size). Input data for the right hand side.\n    :param max_iter_time: int, optional\n        Maximal iteration times.\n    :param min_iter_time: int, optional\n        Minimal iteration times\n    :param tolerance: float, optional\n        The difference tolerance for adjacent u solutions.\n    ---------------\n    :return:\n        The solution array u. Or suggestive error message.\n    \"\"\"\n    start = time.clock()\n\n    A = np.array(A)\n    b = np.array(b)\n    n, m = A.shape\n    if n != m:\n        return \"The row size of matrix 'A' is not equal to its column size.\"\n    if n != b.shape[0]:\n        return \"The row size of matrix 'A' is not equal to the size of vector 'b'.\"\n    b.reshape(n)\n    aii = np.array([A[i, i] for i in range(n)])\n    x_before = np.zeros(n)\n    x_cur = np.zeros(n)\n\n    # iteration\n    for i in range(max_iter_time):\n        for r in range(n):\n            remain = np.dot(A[r, :], x_cur[:]) - A[r, r] * x_cur[r]\n            x_cur[r] = (b[r] - remain) / aii[r]\n        if max(abs(x_cur - x_before)) < tolerance and i > min_iter_time:\n            print('Gauss-Seidel Iterations:', i + 1)\n            print('Time past:', time.clock() - start)\n            return x_cur\n\n        x_before = np.copy(x_cur)\n    print(\"Maximal iteration times reached.\")\n    print('Gauss-Seidel Iterations:', i + 1)\n    print('Time past:', time.clock() - start)\n    return x_cur\n\n\n# just for simple test\nif __name__ == '__main__':\n    from scipy.linalg import solve\n\n    A = np.array([[8, -3, 2], [4, 11, -1], [6, 3, 12]])\n    b = np.array([[20], [33], [36]])\n\n    s1 = solve(A, b).reshape(len(b))\n    s2 = jacobi(A, b)\n    s3 = gauss_seidel(A, b)\n\n    print(s1, s2, s3)\n    print(np.array(s1) - np.array(s2))\n", "meta": {"hexsha": "5b9fbc2b61655c83fce7968e844f7cf41eced9f4", "size": 3822, "ext": "py", "lang": "Python", "max_stars_repo_path": "linsolver/linsolver.py", "max_stars_repo_name": "Pengeace/DGP-PDE-FEM", "max_stars_repo_head_hexsha": "64b7f42ca7083b05f05c42baa6cad21084068d8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-06-26T07:25:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T03:40:22.000Z", "max_issues_repo_path": "linsolver/linsolver.py", "max_issues_repo_name": "Pengeace/DGP-PDE-FEM", "max_issues_repo_head_hexsha": "64b7f42ca7083b05f05c42baa6cad21084068d8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linsolver/linsolver.py", "max_forks_repo_name": "Pengeace/DGP-PDE-FEM", "max_forks_repo_head_hexsha": "64b7f42ca7083b05f05c42baa6cad21084068d8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0731707317, "max_line_length": 83, "alphanum_fraction": 0.5716902145, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632275178339, "lm_q2_score": 0.9241418205010699, "lm_q1q2_score": 0.8796566159463551}}
{"text": "'''\r\nWhat is Standard Deviation?\r\n\r\nStandard deviation is a number that describes how spread out the values are.\r\n\r\nA low standard deviation means that most of the numbers are close to the mean (average) value.\r\n\r\nA high standard deviation means that the values are spread out over a wider range.\r\n\r\nExample: This time we have registered the speed of 7 cars:\r\n\r\nspeed = [86,87,88,86,87,85,86]\r\n\r\nThe standard deviation is:\r\n\r\n0.9\r\n\r\nMeaning that most of the values are within the range of 0.9 from the mean value, which is 86.4.\r\n\r\nLet us do the same with a selection of numbers with a wider range:\r\n\r\nspeed = [32,111,138,28,59,77,97]\r\n\r\nThe standard deviation is:\r\n\r\n37.85\r\n\r\nMeaning that most of the values are within the range of 37.85 from the mean value, which is 77.4.\r\n\r\nAs you can see, a higher standard deviation indicates that the values are spread out over a wider range.\r\n\r\nThe NumPy module has a method to calculate the standard deviation:\r\nExample\r\n\r\nUse the NumPy std() method to find the standard deviation:\r\n'''\r\nimport numpy as r \r\nspeed=[86,87,88,86,87,85,86]\r\n\r\no=r.std(speed)\r\nprint(o)\r\n\r\n'''\r\nVariance\r\n\r\nVariance is another number that indicates how spread out the values are.\r\n\r\nIn fact, if you take the square root of the variance, you get the standard deviation!\r\n\r\nOr the other way around, if you multiply the standard deviation by itself, you get the variance!\r\n\r\nTo calculate the variance you have to do as follows:\r\n\r\n1. Find the mean:\r\n\r\n(32+111+138+28+59+77+97) / 7 = 77.4\r\n\r\n2. For each value: find the difference from the mean:\r\n\r\n 32 - 77.4 = -45.4\r\n111 - 77.4 =  33.6\r\n138 - 77.4 =  60.6\r\n 28 - 77.4 = -49.4\r\n 59 - 77.4 = -18.4\r\n 77 - 77.4 = - 0.4\r\n 97 - 77.4 =  19.6\r\n\r\n3. For each difference: find the square value:\r\n\r\n(-45.4)2 = 2061.16\r\n (33.6)2 = 1128.96\r\n (60.6)2 = 3672.36\r\n(-49.4)2 = 2440.36\r\n(-18.4)2 =  338.56\r\n(- 0.4)2 =    0.16\r\n (19.6)2 =  384.16\r\n\r\n4. The variance is the average number of these squared differences:\r\n\r\n(2061.16+1128.96+3672.36+2440.36+338.56+0.16+384.16) / 7 = 1432.2\r\n\r\nLuckily, NumPy has a method to calculate the variance:\r\nExample\r\n\r\nUse the NumPy var() method to find the variance:\r\n'''\r\n\r\nimport numpy as r \r\nspeed=[32,111,138,28,59,77,97]\r\n\r\np=r.var(speed)\r\nprint(p)\r\n\r\n'''Standard Deviation\r\n\r\nAs we have learned, the formula to find the standard deviation is the square root of the variance:\r\n\r\n√1432.25 = 37.85\r\n\r\nOr, as in the example from before, use the NumPy to calculate the standard deviation:\r\nExample\r\n\r\nUse the NumPy std() method to find the standard deviation:\r\nimport numpy\r\n'''\r\nspeed = [32,111,138,28,59,77,97]\r\n\r\nx = r.std(speed)\r\n\r\nprint(x)\r\n", "meta": {"hexsha": "50290f2dc9a526286c54ccb57d2158f886ee6f4a", "size": 2635, "ext": "py", "lang": "Python", "max_stars_repo_path": "codeMania-python-AI-Machine-learning/tut2_standard_deviation.py", "max_stars_repo_name": "JayramMardi/codeMania", "max_stars_repo_head_hexsha": "2327bef1d2a25aacdf4e39dccf2d2e77191a0f35", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "codeMania-python-AI-Machine-learning/tut2_standard_deviation.py", "max_issues_repo_name": "JayramMardi/codeMania", "max_issues_repo_head_hexsha": "2327bef1d2a25aacdf4e39dccf2d2e77191a0f35", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codeMania-python-AI-Machine-learning/tut2_standard_deviation.py", "max_forks_repo_name": "JayramMardi/codeMania", "max_forks_repo_head_hexsha": "2327bef1d2a25aacdf4e39dccf2d2e77191a0f35", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-02T14:58:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T14:58:38.000Z", "avg_line_length": 23.7387387387, "max_line_length": 105, "alphanum_fraction": 0.6834914611, "include": true, "reason": "import numpy", "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.920789679151471, "lm_q1q2_score": 0.8796479949489089}}
{"text": "import numpy as np\nfrom math import *\nimport matplotlib.pyplot as plt\n\n#This file contains two functions which simulate trajectories of the fractional Brownian motion.\n\ndef davies_harte(T, N, H):\n    '''\n    Generates a sample path of fractional Brownian Motion using the Davies Harte method\n    \n    args:\n        T:      length of time (in years)\n        N:      number of time steps within timeframe\n        H:      Hurst parameter\n    '''\n    gamma = lambda k,H: 0.5*(np.abs(k-1)**(2*H) - 2*np.abs(k)**(2*H) + np.abs(k+1)**(2*H))  \n    g = [gamma(k,H) for k in range(0,N)];    r = g + [0] + g[::-1][0:N-1]\n\n    # Step 1 (eigenvalues)\n    j = np.arange(0,2*N);   k = 2*N-1\n    lk = np.fft.fft(r*np.exp(2*np.pi*complex(0,1)*k*j*(1/(2*N))))[::-1]\n\n    # Step 2 (get random variables)\n    Vj = np.zeros((2*N,2), dtype=np.complex); \n    Vj[0,0] = np.random.standard_normal();  Vj[N,0] = np.random.standard_normal()\n    \n    for i in range(1,N):\n        Vj1 = np.random.standard_normal();    Vj2 = np.random.standard_normal()\n        Vj[i][0] = Vj1; Vj[i][1] = Vj2; Vj[2*N-i][0] = Vj1;    Vj[2*N-i][1] = Vj2\n    \n    # Step 3 (compute Z)\n    wk = np.zeros(2*N, dtype=np.complex)   \n    wk[0] = np.sqrt((lk[0]/(2*N)))*Vj[0][0];          \n    wk[1:N] = np.sqrt(lk[1:N]/(4*N))*((Vj[1:N].T[0]) + (complex(0,1)*Vj[1:N].T[1]))       \n    wk[N] = np.sqrt((lk[0]/(2*N)))*Vj[N][0]       \n    wk[N+1:2*N] = np.sqrt(lk[N+1:2*N]/(4*N))*(np.flip(Vj[1:N].T[0]) - (complex(0,1)*np.flip(Vj[1:N].T[1])))\n    \n    Z = np.fft.fft(wk);     fGn = Z[0:N] \n    fBm = np.cumsum(fGn)*(N**(-H))\n    fBm = (T**H)*(fBm)\n    path = np.array([0] + list(fBm))\n    return path\n\ndef fBm(T,N,H,trials):\n      '''\n    Generates multiple sample path of fractional Brownian Motion using the Davies Harte method\n    \n    args:\n        T:      length of time (in years)\n        N:      number of time steps within timeframe\n        H:      Hurst parameter\n        trials: number of paths\n    '''\n    B = np.zeros((N+1,trials))\n    for i in range(trials):\n        B[:,i] = davies_harte(T,N,H)\n    return B  \n", "meta": {"hexsha": "6df4b5e6067347083f26fda8313162affaaefdf8", "size": 2066, "ext": "py", "lang": "Python", "max_stars_repo_path": "fractionalBrownianmotion.py", "max_stars_repo_name": "ElMehdiHaress/estimation-for-SDEs", "max_stars_repo_head_hexsha": "72d50f8317e63db3edf835bfa02255c915f7e947", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-14T14:37:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T14:37:28.000Z", "max_issues_repo_path": "fractionalBrownianmotion.py", "max_issues_repo_name": "ElMehdiHaress/estimation-for-SDEs", "max_issues_repo_head_hexsha": "72d50f8317e63db3edf835bfa02255c915f7e947", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fractionalBrownianmotion.py", "max_forks_repo_name": "ElMehdiHaress/estimation-for-SDEs", "max_forks_repo_head_hexsha": "72d50f8317e63db3edf835bfa02255c915f7e947", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6206896552, "max_line_length": 107, "alphanum_fraction": 0.5387221684, "include": true, "reason": "import numpy", "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688145, "lm_q2_score": 0.9111797015700343, "lm_q1q2_score": 0.8796357165127742}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\ndef rotation(grid_in, pattern = 1):\n    if pattern == 1:\n       return grid_in.T\n    elif pattern == 2:\n       return np.flipud(np.fliplr(grid_in))\n\n\ndef hilbert_space_filling_curve(num = 4, ver_bose = False, ver_bose_contour=False):\n    \n    n_level = np.log2(num)\n    if n_level // 1 != n_level:\n        raise ValueError(\"square grid size not a exponential of 2!\")\n    elif n_level == 1:\n        raise ValueError(\"grid size should be larger or equal than 4!\")\n    \n    n_level = n_level.astype('int')\n\n    # start from 2 * 2 grid\n    grid_1 = np.array([0, 3, 1, 2]).reshape(2, 2)\n    subsize = 4  \n\n    for i in range(2, n_level + 1):\n\n        grid_2 = rotation(grid_1, pattern = 1) + subsize\n\n        grid_3 = rotation(grid_1, pattern = 1) + subsize * 2\n\n        grid_4 = rotation(grid_1, pattern = 2) + subsize * 3      \n\n        grid_1 = np.vstack((np.hstack((grid_1, grid_2)), np.hstack((grid_4, grid_3))))\n\n        grid_1 = rotation(grid_1, pattern = 1)\n\n        subsize *= 4\n\n    if ver_bose:\n        \n        x_coords = np.argsort(grid_1.flatten()) // num \n        y_coords = np.argsort(grid_1.flatten()) % num \n\n        fig, ax = plt.subplots(figsize=(20,20))\n        ax.set_title(\"Hilbert space-filling curve on a %d * %d square grid\" % (num, num), fontsize = 25)\n\n        ax.plot(x_coords, y_coords, color = \"black\")\n\n        plt.show()\n\n    if ver_bose_contour:\n\n        fig, ax = plt.subplots(figsize=(20,20))\n        ax.set_title(\"Hilbert space-filling curve on a %d * %d square grid\" % (num, num), fontsize = 25)\n        xx, yy = np.meshgrid(np.arange(0, num), np.arange(0, num))\n        plot_levels = [i * num // 2 - 0.5 for i in range(1, num * 2 - 1)]\n        plot_levels.insert(0, 0)\n        plot_levels.append(num ** 2)\n\n        cset = plt.contourf(xx, yy, grid_1.T, levels=plot_levels, cmap=None)\n        fig.colorbar(cset, shrink=0.5, aspect=5)\n\n        plt.show()\n       \n    return np.argsort(grid_1.flatten())\n\ndef inverse_ordering(order_index):\n    return np.argsort(order_index)\n\n\n# index_hilbert = hilbert_space_filling_curve(8)\n\n# element64 = np.arange(1, 65) \n\n\n# inverse_map = np.argsort(index_hilbert)\n# inverse_map\n\n# (element64[index_hilbert])[inverse_ordering(index_hilbert)]\n\n# Hilbert_ordering\n\n# Hilbert_ordering[inverse_map]", "meta": {"hexsha": "2471f62b111af4465a81f14bec6f92d7b58a1db0", "size": 2327, "ext": "py", "lang": "Python", "max_stars_repo_path": "simple_hilbert.py", "max_stars_repo_name": "acse-fy120/SFC-CAE-Ready-to-use", "max_stars_repo_head_hexsha": "ff8ae1b40e4849b17963ca26dbe9bdc2a72acb5d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simple_hilbert.py", "max_issues_repo_name": "acse-fy120/SFC-CAE-Ready-to-use", "max_issues_repo_head_hexsha": "ff8ae1b40e4849b17963ca26dbe9bdc2a72acb5d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simple_hilbert.py", "max_forks_repo_name": "acse-fy120/SFC-CAE-Ready-to-use", "max_forks_repo_head_hexsha": "ff8ae1b40e4849b17963ca26dbe9bdc2a72acb5d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7023809524, "max_line_length": 104, "alphanum_fraction": 0.6205414697, "include": true, "reason": "import numpy", "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.9324533032291501, "lm_q1q2_score": 0.8796275591445067}}
{"text": "from sympy import *\r\nfrom sympy.parsing.sympy_parser import parse_expr\r\nimport sys\r\n\r\nf = None\r\nf_prime = None\r\n\r\ndef main():\r\n    x = Symbol('x')\r\n\r\n    # polynomial to evaluate\r\n    global f\r\n    f = parse_expr('x**2-2') #you can also read from terminal using sys.agrv\r\n\r\n    global f_prime\r\n    f_prime = f.diff(x)  # symbolic derivative with respect to x\r\n    \r\n    f = lambdify(x, f)  # pass evaulation f to f\r\n    f_prime = lambdify(x, f_prime)\r\n\r\n    secant(1,2,10**-4,100) #method to use\r\n\r\ndef bisec(a, b, error, N):\r\n    # Initialization\r\n    a = float(a)\r\n    b = float(b)\r\n    error = float(error)  # error tolerance\r\n\r\n    for i in range(0, N):\r\n        print(\"iteration\", i + 1)\r\n        c = (a + b) / 2\r\n\r\n        print(\"a=\", a, \" b=\", b, \"c=\", c)\r\n\r\n        print(\"f(a)=\", f(a), \" f(c)=\", f(c))\r\n\r\n        if(f(c) == 0):\r\n            print(\"the solution is\", c)\r\n            break\r\n        elif(f(a)*f(c)<0):\r\n            print(\"sign negative\")\r\n            b = c\r\n        else:\r\n            print(\"sign positive\")\r\n            a = c\r\n        \r\n        print(\"error=\",abs(b-a))\r\n        print(\"the root is in between\",a ,b)\r\n\r\n        if(abs(b-a)<error):\r\n            print(\"the solution is ~\",c)\r\n            break\r\n        print()\r\n\r\n\r\ndef newton(x0, error, N):\r\n    x0 = float(x0)\r\n    error = float(error)\r\n\r\n    for i in range (0, N):\r\n        print(\"iteration\", i+1)\r\n        print(\"x0=\", x0)\r\n\r\n        x1 = (x0)-f(x0)/f_prime(x0)\r\n        print(\"x1=\", x1)\r\n\r\n        e = abs(x1-x0)\r\n        print(\"|x0-x1|=\", e)\r\n        print(\"f(x)=\", f(x0))\r\n        print(\"f'(x)=\",f_prime(x0))\r\n        x0 = x1\r\n        \r\n        if(e<=error):\r\n            print(\"the solution is ~\", x0)\r\n            break\r\n        print()\r\n\r\n\r\ndef secant(x0, x1, error, N):\r\n    x0 = float(x0)\r\n    error = float(error)\r\n\r\n    for i in range (0, N):\r\n        print(\"iteration\", i+1)\r\n        print(\"x0=\", x0)\r\n        print(\"x1=\", x1)\r\n        \r\n        x2 = x1-(f(x1)*(x1-x0))/(f(x1)-f(x0))\r\n        print(\"f(x0)=\", f(x0))\r\n        print(\"f(x1)=\", f(x1))\r\n        print(\"x2=\", x2)\r\n        \r\n        e = abs(x2-x1)\r\n        print(\"error=\", e)\r\n        print()\r\n        x0 = x1\r\n        x1 = x2\r\n        \r\n        if(e<=error):\r\n            print(\" the solution is ~\", x1)\r\n            break\r\n\r\nmain()", "meta": {"hexsha": "9be72c6a1e47d9608e28db66880ac6edc6d23829", "size": 2296, "ext": "py", "lang": "Python", "max_stars_repo_path": "poly_calc.py", "max_stars_repo_name": "akiraminase/numerical_methods", "max_stars_repo_head_hexsha": "1d1dc856fd398a8e7e5f629c1ec3c3350dda4cd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "poly_calc.py", "max_issues_repo_name": "akiraminase/numerical_methods", "max_issues_repo_head_hexsha": "1d1dc856fd398a8e7e5f629c1ec3c3350dda4cd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "poly_calc.py", "max_forks_repo_name": "akiraminase/numerical_methods", "max_forks_repo_head_hexsha": "1d1dc856fd398a8e7e5f629c1ec3c3350dda4cd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2912621359, "max_line_length": 77, "alphanum_fraction": 0.4359756098, "include": true, "reason": "from sympy", "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558706, "lm_q2_score": 0.913676530465412, "lm_q1q2_score": 0.8795718295437546}}
{"text": "\"\"\"\n黄金比\n\"\"\"\n\ndef golden_ratio(digit: int) -> str:\n\tfrom sympy import N, sqrt\n\treturn str(N(\"(1 + sqrt(5)) / 2\", digit))\n\nif __name__ == \"__main__\":\n\tdigit = 10000\n\tprint(golden_ratio(digit))\n", "meta": {"hexsha": "720d4b72a9539f72cdc9ae9249f07f02b2f6e6fc", "size": 191, "ext": "py", "lang": "Python", "max_stars_repo_path": "extra/golden_ratio.py", "max_stars_repo_name": "Fairy-Phy/Relium", "max_stars_repo_head_hexsha": "70ea037cea176f02e4768bde44dd5ee23af699b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extra/golden_ratio.py", "max_issues_repo_name": "Fairy-Phy/Relium", "max_issues_repo_head_hexsha": "70ea037cea176f02e4768bde44dd5ee23af699b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extra/golden_ratio.py", "max_forks_repo_name": "Fairy-Phy/Relium", "max_forks_repo_head_hexsha": "70ea037cea176f02e4768bde44dd5ee23af699b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.9166666667, "max_line_length": 42, "alphanum_fraction": 0.6335078534, "include": true, "reason": "from sympy", "num_tokens": 65, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140615, "lm_q2_score": 0.9136765245890102, "lm_q1q2_score": 0.8795718219297798}}
{"text": "import numpy as np\nimport os\n\n\ndef gaussian_func(x, a, x0, sigma, c1, c2, c3):\n    \"\"\"\n    Compute Gaussian function with up to quadratic background terms.\n\n    Parameters\n    ----------\n    x : array\n        Array of values at which to evaluate the function.\n    a : float\n        Height of the Gaussian function.\n    x0 : float\n        Location of Gaussian function.\n    sigma : float\n        Width of Gaussian function.\n    c1 : float\n        Zeroth-order background coefficient.\n    c2 : float\n        First-order background coefficient.\n    c3 : float\n        Second-order background coefficient.\n    \n    Returns\n    -------\n    array\n        Gaussian function\n    \"\"\"\n    return a*np.exp(-(x-x0)**2/(2*sigma**2)) + c1 + c2*x + c3*x**2\n\n\ndef smooth(x, window_len=11, window='hanning'):\n    \"\"\"\n    Smooth the data using a window with requested size.\n    \n    This method is based on the convolution of a scaled window with the signal.\n    The signal is prepared by introducing reflected copies of the signal \n    (with the window size) at both ends so that transient parts are minimized\n    in the begining and end part of the output signal.\n\n    Parameters\n    ----------\n    x : array\n        The input signal \n    window_len : int\n        The dimension of the smoothing window; should be an odd integer\n    window : str\n        The type of window from 'flat', 'hanning', 'hamming', 'bartlett', \n        'blackman'. Flat window will produce a moving average smoothing.\n\n    Returns\n    -------\n    array\n        The smoothed signal  \n    \"\"\"\n    if x.ndim != 1:\n        raise ValueError(\"smooth only accepts 1 dimension arrays.\")\n    if x.size < window_len:\n        raise ValueError(\"Input vector needs to be bigger than window size.\")\n    if window_len<3:\n        return x\n    if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:\n        raise ValueError(\"Window is one of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'\")\n    \n    s=np.r_[x[window_len-1:0:-1],x,x[-2:-window_len-1:-1]]\n    \n    if window == 'flat': #moving average\n        w=np.ones(window_len,'d')\n    else:\n        w=eval('np.'+window+'(window_len)')\n\n    y=np.convolve(w/w.sum(),s,mode='valid')\n    \n    return y[window_len//2:-window_len//2+1]\n\ndef closest(arr,val,index=False):\n    \"\"\"\n    Find either the closest value or index of closest value in an array.\n\n    Parameters\n    ----------\n    arr : array\n        Array to find the closest value in.\n    val : float or int\n        Input value to find the closest array value to.\n    index : bool, default: False\n        If True, return the index of the closest value instead of the value.\n\n    Returns\n    -------\n    float or int\n        If `index=False`, this is the closest value\n    int\n        If `index=True`, returns the index of the closest value isntead,\n    \"\"\"\n    idx = np.argmin(np.abs(arr-val))\n    if index:\n        return idx\n    else:\n        return arr[idx]\n", "meta": {"hexsha": "39c899b319b844deaa4d9752c1ea0528bdd08dca", "size": 2933, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/famed/utils.py", "max_stars_repo_name": "darthoctopus/FAMED", "max_stars_repo_head_hexsha": "fa5b0e2fc21da33f2ffb9d874fc86eb5c85d5b98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-16T13:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T13:13:36.000Z", "max_issues_repo_path": "python/famed/utils.py", "max_issues_repo_name": "darthoctopus/FAMED", "max_issues_repo_head_hexsha": "fa5b0e2fc21da33f2ffb9d874fc86eb5c85d5b98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/famed/utils.py", "max_forks_repo_name": "darthoctopus/FAMED", "max_forks_repo_head_hexsha": "fa5b0e2fc21da33f2ffb9d874fc86eb5c85d5b98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-05T13:31:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T13:31:05.000Z", "avg_line_length": 28.4757281553, "max_line_length": 97, "alphanum_fraction": 0.6113194681, "include": true, "reason": "import numpy", "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558706, "lm_q2_score": 0.9136765210631689, "lm_q1q2_score": 0.879571820492468}}
{"text": "import numpy as np\nimport matplotlib.pylab as plt\nimport scipy\nimport scipy.linalg\nimport sys\n\ndef solve_triangular(A, b):\n    n = len(b)\n    x = np.empty_like(b)\n    for i in range(n-1, -1, -1):\n        x[i] = b[i]\n        for j in range(n-1, i, -1):\n            x[i] -= A[i, j] * x[j]\n        x[i] /= A[i, i]\n    return x\n\n\ndef gaussian_elimination(A):\n    m, n = A.shape\n\n    # initialise the pivot row and column\n    h = 0\n    k = 0\n    while h < m and k < n:\n        # Find the k-th pivot:\n        i_max = np.argmax(A[h:, k]) + h\n        if A[i_max, k] == 0:\n            # No pivot in this column, pass to next column\n            k = k+1\n        else:\n            # swap rows\n            A[[h, i_max], :] = A[[i_max, h], :]\n            # Do for all rows below pivot:\n            for i in range(h+1, m):\n                f = A[i, k] / A[h, k]\n                # Fill with zeros the lower part of pivot column:\n                A[i, k] = 0\n                # Do for all remaining elements in current row:\n                for j in range(k + 1, n):\n                    A[i, j] = A[i, j] - A[h, j] * f\n            # Increase pivot row and column\n            h = h + 1\n            k = k + 1\n    return A\n\ndef solve_gaussian_elimination(A, b):\n    augmented_system = np.concatenate((A, b.reshape(-1, 1)), axis=1)\n    gaussian_elimination(augmented_system)\n    return solve_triangular(augmented_system[:, :-1], augmented_system[:, -1])\n\ndef random_matrix(n):\n    R = np.random.rand(n, n)\n    A = np.zeros((n, n))\n    triu = np.triu_indices(n)\n    A[triu] = R[triu]\n    return A\n\ndef random_non_singular_matrix(n):\n    A = np.random.rand(n, n)\n    while np.linalg.cond(A) > 1/sys.float_info.epsilon:\n        A = np.random.rand(n, n)\n    return A\n\nAs = [\n    np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]),\n    random_non_singular_matrix(3),\n    random_non_singular_matrix(4),\n    random_non_singular_matrix(5),\n    random_non_singular_matrix(6),\n]\n\nbs = [\n    np.array([1, 2, 3]),\n    np.random.rand(3),\n    np.random.rand(4),\n    np.random.rand(5),\n    np.random.rand(6),\n]\n\nfor A, b in zip(As, bs):\n    x_scipy = scipy.linalg.solve(A, b)\n    x_mine = solve_gaussian_elimination(A, b)\n    np.testing.assert_almost_equal(x_scipy, x_mine)\n\nA = np.array([\n    [4.5, 3.1],\n    [1.6, 1.1],\n])\nx1 = scipy.linalg.solve(A, np.array([19.249, 6.843]))\nx2 = scipy.linalg.solve(A, np.array([19.25, 6.84]))\nprint('percentage error is ', np.linalg.norm(x2 - x1) / np.linalg.norm(x1) * 100)\nprint('condition number is ', np.linalg.cond(A))\n\n\n", "meta": {"hexsha": "6189ebdeb7dde5452450d0af3b503afe5533b813", "size": 2517, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/unit_1_2.py", "max_stars_repo_name": "tommylees112/scientific-computing", "max_stars_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-02-03T02:10:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T13:21:47.000Z", "max_issues_repo_path": "src/unit_1_2.py", "max_issues_repo_name": "tommylees112/scientific-computing", "max_issues_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-01T16:00:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T17:09:17.000Z", "max_forks_repo_path": "src/unit_1_2.py", "max_forks_repo_name": "tommylees112/scientific-computing", "max_forks_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-02-01T15:45:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T12:20:25.000Z", "avg_line_length": 26.4947368421, "max_line_length": 81, "alphanum_fraction": 0.54390147, "include": true, "reason": "import numpy,import scipy", "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692298333416, "lm_q2_score": 0.9005297834483234, "lm_q1q2_score": 0.8795197300424599}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\n\"\"\"Question-2:: Gradient Decent Method\"\"\"\n\n\ndef cost_function(cf):\n    cf = np.asarray(cf)\n    cf_x = cf[0]\n    cf_y = cf[1]\n    cost = np.log(1 - cf_x - cf_y) - np.log(cf_x) - np.log(cf_y)\n    return cost\n\n\ndef gradient_cost_function(gcf):\n    gcf = np.asarray(gcf)\n    gcf_x = gcf[0]\n    gcf_y = gcf[1]\n    gradient_x = np.divide(1, (1 - gcf_x - gcf_y)) - np.divide(1, gcf_x)\n    gradient_y = np.divide(1, (1 - gcf_x - gcf_y)) - np.divide(1, gcf_y)\n    new_gcf = np.asarray((gradient_x, gradient_y))\n    return new_gcf\n\n\n\"\"\"weights initialization\"\"\"\n\nw_x = np.random.uniform(0, 0.5, 1)\nw_y = np.random.uniform(0, 0.4, 1)\nweights = np.asarray((w_x, w_y))\nprint weights\n\nlearning_rate = 0.0001\nthreshold = 0.00000001\niteration_number = 0\ndomain_miss = 0\nactual_cost = [[0.0]]\nactual_cost = np.asarray(actual_cost, dtype=np.float)\ncost_plot = []\niteration_plot = []\nw0_plot = []\nw1_plot = []\nw0_plot.append(weights[[0]])\nw1_plot.append(weights[[0]])\n\nwhile True:\n    step_update = gradient_cost_function(weights)\n    temp_weights = weights - learning_rate * step_update\n    if ((temp_weights[[0]] + temp_weights[[1]]) < 1) and (temp_weights[[0]] > 0) and (temp_weights[[1]] > 0):\n        weights = temp_weights\n        w0_plot.append(temp_weights[[0]])\n        w1_plot.append(temp_weights[[1]])\n        temp_cost = cost_function(weights)\n        iteration_temp = iteration_number + 1\n        iteration_plot.append(iteration_temp)\n        cost_plot.append(temp_cost)\n    else:\n        w_x = np.random.uniform(0, 0.5, 1)\n        w_y = np.random.uniform(0, 0.4, 1)\n        weights = np.asarray((w_x, w_y))\n        domain_miss = domain_miss + 1\n        print \"number of domain misses:\", domain_miss, \"weights are:\", temp_weights\n        continue\n    iteration_number = iteration_number + 1\n    actual_cost_temp = cost_function(weights)\n    actual_cost = np.append(actual_cost, actual_cost_temp)\n    threshold_cal = np.subtract(actual_cost[iteration_number], actual_cost[iteration_number - 1])\n    print \"iteration number::\", iteration_number, \"cost difference\", threshold_cal, \"cost::\", actual_cost_temp\n    if np.absolute(threshold_cal) < threshold:\n        break\n\nprint \"final weights::\", weights\nprint \"final cost::\", cost_function(weights)\nplt.figure(1)\nplt.xlabel('iteration number')\nplt.ylabel('cost')\nplt.scatter(iteration_plot, cost_plot, color='red', s=4)\nplt.savefig('question2GD.png')\nplt.figure(2)\nplt.scatter(w0_plot, w1_plot, s=2)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.savefig('Q2pointPlotGD.png')\n", "meta": {"hexsha": "6df6ccdf9134a89b181aae04d7ac28e1002fae2b", "size": 2557, "ext": "py", "lang": "Python", "max_stars_repo_path": "gradient-decent.py", "max_stars_repo_name": "SriSaiAnkitBasava/gradient_decent_method", "max_stars_repo_head_hexsha": "4a2adec033ebc3c72ee1262fed6de5dd16a8ccba", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gradient-decent.py", "max_issues_repo_name": "SriSaiAnkitBasava/gradient_decent_method", "max_issues_repo_head_hexsha": "4a2adec033ebc3c72ee1262fed6de5dd16a8ccba", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gradient-decent.py", "max_forks_repo_name": "SriSaiAnkitBasava/gradient_decent_method", "max_forks_repo_head_hexsha": "4a2adec033ebc3c72ee1262fed6de5dd16a8ccba", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8072289157, "max_line_length": 110, "alphanum_fraction": 0.6769651936, "include": true, "reason": "import numpy", "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446463891304, "lm_q2_score": 0.9032941982430048, "lm_q1q2_score": 0.8794875602336635}}
{"text": "import numpy as np\n\n# define a rotation matrix. rotate 45 degree by z axis.\n\nR = np.array([\n    [np.sqrt(2) / 2, -np.sqrt(2) / 2, 0.],\n    [np.sqrt(2) / 2, np.sqrt(2) / 2, 0.],\n    [0., 0., 1.]]\n)\n\n# calculate the axis and angle.\n\ntheta = np.arccos((R.trace() - 1) / 2) # rotation angle\n\n# the rotation axis(column vector) is the eig vector corresponding to the eig value equals 1.\neig_vals, eig_vector = np.linalg.eig(R)\nprint('eig values:\\n', eig_vals.real)\nprint('eig vector:\\n', eig_vector.real)\n\nn = eig_vector[eig_vals == 1].real.T\nprint('rotation angle:theta=', np.rad2deg(theta), 'rotation axis:n=', n.ravel())\nprint('i.e: we can find this R is rotating 45 degree by Z axis.')\n\n# Rodrigue's formula: convert Axis-angle to Rotation matrix.\n\ndef skew_symmetric(a):\n    a = a.ravel()\n    return np.array([\n        [0, -a[2], a[1]],\n        [a[2], 0, -a[0]],\n        [-a[1], a[0], 0]\n    ])\n\nR_ = np.cos(theta) * np.eye(3) + (1 - np.cos(theta)) * n @ n.T + np.sin(theta) * skew_symmetric(n)\nprint('restored rotation matrix:\\n',R_)\nprint('check by mse:', np.linalg.norm(R - R_))", "meta": {"hexsha": "4ab34987f087bc8958d5311a99596997dd6a5927", "size": 1081, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapter 3/axis_angle.py", "max_stars_repo_name": "GracefulMan/slam14_python", "max_stars_repo_head_hexsha": "6c4c6b3bd81b88c23b708b084bdbb95ebc9745dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter 3/axis_angle.py", "max_issues_repo_name": "GracefulMan/slam14_python", "max_issues_repo_head_hexsha": "6c4c6b3bd81b88c23b708b084bdbb95ebc9745dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter 3/axis_angle.py", "max_forks_repo_name": "GracefulMan/slam14_python", "max_forks_repo_head_hexsha": "6c4c6b3bd81b88c23b708b084bdbb95ebc9745dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0277777778, "max_line_length": 98, "alphanum_fraction": 0.6151711378, "include": true, "reason": "import numpy", "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241965169938, "lm_q2_score": 0.9073122288794595, "lm_q1q2_score": 0.8794796972486248}}
{"text": "import numpy as np\n\n#  compute f\ndef f(A,b,x):\n    fx = np.zeros(A.shape[0])\n    for i in range(A.shape[0]):\n        ci = b[i]*np.dot(A[i],x)\n        fx[i] = np.log(1+np.exp(-ci))\n    fx = fx.mean()\n    return fx\n\n# compute gradient\ndef stogradfx(A,b,x, i):\n    di = np.exp(-np.dot(b[i], np.dot(A[i],x)))\n    gradfx = (-b[i] * A[i] * di / (1+di)).T\n    return gradfx\n\ndef gradfx(A,b,x):\n    n = A.shape[0]\n    gradfx = np.zeros(x.shape)\n    for i in range(n):\n        gradfx += stogradfx(A,b,x,i)\n    gradfx = gradfx/n\n\n    return gradfx\n\ndef Oracles(b, A, lbd):\n    \"\"\"\n    FIRST ORDER ORACLE\n    Takes inputs b, A, lbd and returns two anonymous functions, one for\n    the objective evaluation and the other for the gradient.\n    fx(x) computes the objective (l-2 regularized) of input x\n    gradf(x) computes the gradient (l-2 regularized) of input x\n    gradfsto(x,i) computes the stochastic gradient (l-2 regularized) of input x at index i\n    \"\"\"\n    n, p = A.shape\n    fx  = lambda x : 0.5*lbd*np.linalg.norm(x, 2)**2 + f(A,b,x)\n    gradf  = lambda x: lbd*x + gradfx(A,b,x)\n    gradfsto = lambda x, i: lbd * x + stogradfx(A, b, x, i)\n    return fx, gradf, gradfsto\n\n\ndef compute_error(A_test,b_test,x):\n    n, err = A_test.shape[0], 0\n    for i in range(n):\n        if np.dot(b_test[i],np.dot(A_test[i],x)) <= 0:\n           err += 1\n    err = err/float(n)\n    return err\n", "meta": {"hexsha": "f83e69a424773e9751c4d5882e54670a84e78e8f", "size": 1377, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW1/exercise1_code/question2/log_reg/commons.py", "max_stars_repo_name": "3Represents/EE-556_MathsOfData", "max_stars_repo_head_hexsha": "91790e214f2cd2f27a08f343ed89d050bc377d1e", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW1/exercise1_code/question2/log_reg/commons.py", "max_issues_repo_name": "3Represents/EE-556_MathsOfData", "max_issues_repo_head_hexsha": "91790e214f2cd2f27a08f343ed89d050bc377d1e", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW1/exercise1_code/question2/log_reg/commons.py", "max_forks_repo_name": "3Represents/EE-556_MathsOfData", "max_forks_repo_head_hexsha": "91790e214f2cd2f27a08f343ed89d050bc377d1e", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.54, "max_line_length": 90, "alphanum_fraction": 0.5838779956, "include": true, "reason": "import numpy", "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242009478237, "lm_q2_score": 0.9073122144683576, "lm_q1q2_score": 0.8794796872997412}}
{"text": "import autograd.numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import minimize, shgo\nfrom autograd import grad\n\n\ndef convex_function(x):\n    return np.sum(np.array(x)**2, axis=0)\n\ndef rosenbrock(x):\n    a = 1.0\n    b = 100.0\n    return (a-x[0])**2 + b*(x[1]-x[0]**2)**2\n\ndef rastrigin(x):\n    A = 10.0\n    n = len(x)\n    ret = A*n\n    for i in range(n):\n        ret += x[i]**2 - A * np.cos(2*np.pi*x[i])\n    return ret\n\ndef visualise_functions():\n    nx, ny = (100, 100)\n    x = np.linspace(-5, 5, nx)\n    y = np.linspace(-5, 5, ny)\n    xv, yv = np.meshgrid(x, y)\n    eval_convex = convex([xv, yv])\n    eval_rastrigin = rastrigin([xv, yv])\n    eval_rosenbrock = rosenbrock([xv, yv])\n\n    plt.contourf(x, y, eval_convex)\n    plt.colorbar()\n    plt.show()\n    plt.clf()\n    plt.contourf(x, y, eval_rosenbrock)\n    plt.colorbar()\n    plt.show()\n    plt.clf()\n    plt.contourf(x, y, eval_rastrigin)\n    plt.colorbar()\n    plt.show()\n\ndef optimize(function, method, autodiff):\n    eval_points_x = []\n    eval_points_y = []\n    def fill_eval_points(xk):\n        eval_points_x.append(xk[0])\n        eval_points_y.append(xk[1])\n\n    x0 = np.array([2.5, 2.5])\n    if autodiff:\n        jac = grad(function)\n    else:\n        jac = None\n\n    if method == 'shgo':\n        bounds = [(-10, 10), (-10.0, 10.0)]\n        res = shgo(function, bounds, callback=fill_eval_points,\n                    options={'disp': True})\n    else:\n        res = minimize(function, x0, method=method, callback=fill_eval_points,\n                        jac = jac,\n                    options={'disp': True})\n\n    nx, ny = (100, 100)\n    x = np.linspace(-5, 5, nx)\n    y = np.linspace(-5, 5, ny)\n    xv, yv = np.meshgrid(x, y)\n    eval_function = function([xv, yv])\n\n    print(function.__name__)\n    plt.clf()\n    plt.contourf(x, y, eval_function)\n    plt.plot(eval_points_x, eval_points_y, 'x-k')\n    plt.colorbar()\n    neval = res.nfev\n    try:\n        neval += res.njev\n    except:\n        print('no njev')\n    try:\n        neval += res.nhev\n    except:\n        print('no nhev')\n    plt.title('iterations: {} evaluations: {}'.format(res.nit, neval))\n\n    if autodiff:\n        ext = '-auto.pdf'\n    else:\n        ext = '.pdf'\n\n    plt.savefig(function.__name__ + '-' + method + ext)\n\n\nif __name__ == '__main__':\n    for f in [convex_function, rosenbrock, rastrigin]:\n        for m in ['shgo','nelder-mead', 'cg', 'bfgs', 'newton-cg']:\n            for a in [False, True]:\n                if m == 'newton-cg' and a == False:\n                    continue\n                if m == 'shgo' and a == True:\n                    continue\n                optimize(f, m, a)\n", "meta": {"hexsha": "4f88b92eabfa488c456b6e7ce571df87d7950a9b", "size": 2643, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/unit_4_5.py", "max_stars_repo_name": "tommylees112/scientific-computing", "max_stars_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-02-03T02:10:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T13:21:47.000Z", "max_issues_repo_path": "src/unit_4_5.py", "max_issues_repo_name": "tommylees112/scientific-computing", "max_issues_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-01T16:00:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T17:09:17.000Z", "max_forks_repo_path": "src/unit_4_5.py", "max_forks_repo_name": "tommylees112/scientific-computing", "max_forks_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-02-01T15:45:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T12:20:25.000Z", "avg_line_length": 25.1714285714, "max_line_length": 78, "alphanum_fraction": 0.5433219826, "include": true, "reason": "from scipy", "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992960608886, "lm_q2_score": 0.9086178950769319, "lm_q1q2_score": 0.8794506210332887}}
{"text": "\"\"\" transfor data vectors into their Fourier coefficients\n    we will approximate derivaties by taking advantage of FFT\n\n    1st - take a function that we can analytically compute the exact derivative\n    2nd - we are going to compare how accurate FFT is compared to analytic derivative\n    and we also compare with simple finite difference derivative \"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.figsize'] = [12, 12]\nplt.rcParams.update({'font.size': 10})\n\nn = 64\nL = 30                      # the length of our domain is gonna be 30\ndx = L / n\nx = np.arange(-L/2, L/2, dx, dtype ='complex_')\nf = np.cos(x) * np.exp(-np.power(x, 2) / 25)                            # Function\n    # cosine * decaying Gaussian function = Cosine in a Gaussian envelope -- use chain rule to get exact derivative\ndf = -(np.sin(x) * np.exp(-np.power(x, 2) / 25) + (2 / 25) * x * f)     # Derivative\n\n\"\"\" Approximate derivative using Finite Difference -- it is really crude derivative to be honest (fk+1 - fk) / deltax\n    this is not a good approximation of the derivative has error that scales like Delta X order Delta X error\n    better job would be Central Difference or a Higher Order finite difference -- but this is just illustration \"\"\"\ndfFD = np.zeros(len(df), dtype='complex_')\nfor kappa in range(len(df) - 1):\n    dfFD[kappa] = (f[kappa + 1] - f[kappa]) / dx\n\ndfFD[-1] = dfFD[-2]\n\n\"\"\" Derivative using FFT (spectral derivative)        = i * W * fhat = i * K * fhat\n    use kappa when fourier transforming in space      K - spatial frequencies (wave numbers)\n    use omega when fourier transforming in time       W - temporal frequencies\n    fhat is vector of fourier coefficients            and Kappa is a vector of frequencies\n    frequency weighted fourier coefficients * i --- inverse fourier this and recover the derivative of data\n    at those discrete sample points \"\"\"\nfhat = np.fft.fft(f)\nkappa = (2 * np.pi / L) * np.arange(-n/2, n/2)\nkappa = np.fft.fftshift(kappa)                          # re-order fft frequencies\ndfhat = kappa * fhat * (1j)\ndfFFT = np.real(np.fft.ifft(dfhat))\n\n\"\"\" Up shot here: All of these steps is very fast and very accurate:\n    FFT = O(n*log(n))\n    - create kappa vector\n    - compute derivative = i * kappa * f \n    - inverse fourier transform to get the derivative back in spatial units \n    and  because these are complex numbers in fhat when multiply out and inverse fourier transform \n    we might have very very small machine precision imaginary parts that why we are just going to take \n    the real part of this inverse fourier transform -- just being careful \"\"\"\n\n# Plots\nplt.plot(x, df.real, color='k', LineWidth=2, label='True Derivative')\nplt.plot(x, dfFD.real, '--', color='y', LineWidth=1.5, label='Finite Difference')\nplt.plot(x, dfFFT.real, '--', color='r', LineWidth=1.5, label='FFT Derivative')\nplt.legend()\nplt.show()\n\n\"\"\" As you increase the data points(increase n) in signal which is decreasing deltax\n    - Finite Difference Derivative does get more accurate but very slowly \n    whereas our Spectral Derivative (FFT Derivative) gets more accurate very rapidly \"\"\"\n\n\"\"\" Conclusion FFT is great for Spectral Derivatives of smooth functions whose derivatives are continuous\n    or else we will get Gibbs phenomenon \"\"\"", "meta": {"hexsha": "ef2dedb10f8d18a69be2c6ad69e3c412c12e6967", "size": 3297, "ext": "py", "lang": "Python", "max_stars_repo_path": "derivatives-fft/derivatives-fft.py", "max_stars_repo_name": "oguznsari/Fourier-implementation", "max_stars_repo_head_hexsha": "c4e1a57bbb05347d7d938c4096bd9ae56586319a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "derivatives-fft/derivatives-fft.py", "max_issues_repo_name": "oguznsari/Fourier-implementation", "max_issues_repo_head_hexsha": "c4e1a57bbb05347d7d938c4096bd9ae56586319a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "derivatives-fft/derivatives-fft.py", "max_forks_repo_name": "oguznsari/Fourier-implementation", "max_forks_repo_head_hexsha": "c4e1a57bbb05347d7d938c4096bd9ae56586319a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.3333333333, "max_line_length": 117, "alphanum_fraction": 0.6897179254, "include": true, "reason": "import numpy", "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9796676508127574, "lm_q2_score": 0.8976952900545975, "lm_q1q2_score": 0.8794430359534644}}
{"text": "# numpy provides function to perform log at base 2, e and 10.\n# how we can take log for any base by creating a custom ufunc.\n# all of logs function will place -inf or inf in elements if log cannot not be computed.\n# log at base 2 - use log2() function to perform log at base 2\nimport numpy as np\nfrom math import log\n\narr1 = np.arange(1, 10)           # returns array with 1 to 9 numbers\narr2 = np.log2(arr1)              # returns array with 2^? for 1 to 9 numbers\nprint(arr2)\n\narr3 = np.arange(10, 21)\narr4 = np.log10(arr3)             # returns array with 10^? for 10 to 20 numbers\nprint(arr4)\n\n# natural log or log at base e - use log() function to perform log at base e.\narr5 = np.arange(30, 61)\narr6 = np.log(arr5)                     # here base is \"e\" i.e. 2.71828183\nprint(arr6)\n\n# numpy does not provide any function to take log at any base\n# so we can use frompyfunc() function along with inbuilt function math.log() with two input parameters\nnplog = np.frompyfunc(log, 2, 1)     # function to be done = log, 2 is total inputs, 1 is total output\nomk = nplog(100, 15)                 # log 100 with base 15\nprint(\"log at any base\")\nprint(omk)\n", "meta": {"hexsha": "5676e1f5554c1085a0798544321715f34ad08fe8", "size": 1153, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/Numpy/numpy 35 - numpy logs.py", "max_stars_repo_name": "omkarsutar1255/Python-Data", "max_stars_repo_head_hexsha": "169d0c54b23d9dd5a7f1aea41ab385121c3b3c63", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/Numpy/numpy 35 - numpy logs.py", "max_issues_repo_name": "omkarsutar1255/Python-Data", "max_issues_repo_head_hexsha": "169d0c54b23d9dd5a7f1aea41ab385121c3b3c63", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/Numpy/numpy 35 - numpy logs.py", "max_forks_repo_name": "omkarsutar1255/Python-Data", "max_forks_repo_head_hexsha": "169d0c54b23d9dd5a7f1aea41ab385121c3b3c63", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.7037037037, "max_line_length": 102, "alphanum_fraction": 0.671292281, "include": true, "reason": "import numpy", "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877692486438, "lm_q2_score": 0.9059898216525935, "lm_q1q2_score": 0.8794332389419326}}
{"text": "import numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nx0 = 0\r\ny0 = 2\r\nxf = 1\r\nn = 11\r\ndeltax = (xf-x0)/(n-1)\r\nx = np.linspace(x0,xf,n)\r\ndef f(x,y):\r\n\treturn y-x\r\n\r\ny = np.zeros([n])\r\ny[0] = y0\r\nfor i in range(1,n):\r\n\tk1 = deltax*f(x[i-1],y0)\r\n\tk2 = deltax*f(x[i-1]+deltax/2,y0+k1/2)\r\n\tk3 = deltax*f(x[i-1]+deltax/2,y0+k2/2)\r\n\tk4 = deltax*f(x[i-1]+deltax,y0+k3)\r\n\ty[i] =  y0 + (k1 + 2*k2 + 2*k3 + k4)/6\r\n\ty0 = y[i]\r\n\r\nprint(\"x_n\\t    y_n\")\r\nfor i in range(n):\r\n\tprint(x[i],\"\\t\",format(y[i],'6f'))\r\n\r\nplt.plot(x,y,'o')\r\nplt.xlabel(\"Value of x\")\r\nplt.ylabel(\"Value of y\")\r\nplt.title(\"Approximation Solution with Runge-Kutta Method\")\r\nplt.show()\r\n\r\n#table 19.3\r\n", "meta": {"hexsha": "eb6f62da5e3612d892afb3aaa78e8fefcfbcf770", "size": 664, "ext": "py", "lang": "Python", "max_stars_repo_path": "runge-kutta_method.py", "max_stars_repo_name": "EloneSampaio/Numerical-Methods-First_Order_DE", "max_stars_repo_head_hexsha": "454acf91317a7789dea365490af00ed879583c19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-12T18:49:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T06:38:41.000Z", "max_issues_repo_path": "runge-kutta_method.py", "max_issues_repo_name": "sultanki/Numerical-Methods-First_Order_DE", "max_issues_repo_head_hexsha": "454acf91317a7789dea365490af00ed879583c19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "runge-kutta_method.py", "max_forks_repo_name": "sultanki/Numerical-Methods-First_Order_DE", "max_forks_repo_head_hexsha": "454acf91317a7789dea365490af00ed879583c19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-07-27T08:48:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T07:22:05.000Z", "avg_line_length": 19.5294117647, "max_line_length": 60, "alphanum_fraction": 0.5707831325, "include": true, "reason": "import numpy", "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799482964023, "lm_q2_score": 0.9124361616674906, "lm_q1q2_score": 0.879387676715662}}
{"text": "## Week 5: Probability and the Media\n# Birthday Problem\n# https://www.washingtonpost.com/news/wonk/wp/2016/11/02/why-lifes-strangest-coincidences-really-arent-that-strange-at-all/?utm_term=.de47719120dd\n# at what point would it be better than 50/50 that 2 people share a birthday. \n# They found that when there are 23 people, you have 253 potential pairs and >50% chance that one of those pairs is a match.\n# To get 253 = 23! / ((23-2)! * 2!)\n\n# Attempt to replicate in 2 methods\n\nimport numpy as np\nimport scipy.misc as sm\nimport plotly.plotly as py\nimport plotly.graph_objs as go\n\n# number of guests at party\n# n == 0 & n == 1 are not parties!\nn = np.array([range(2,100,1)])\n\n# Attempt 1\ny  = []\ny2 = []\nfor i in range(2,100,1):\n    days = 365\n    prob = 1\n    for j in range(1, (i + 1), 1):\n        days -=1\n        prob *= days/365\n    y.append(prob)\n    y2.append(1 - prob)\n\nmatch = go.Scatter(x = n[0], y = y2)\nno_match = go.Scatter(x = n[0], y = y)\ndata = [match, no_match]\nplot_url = py.plot(data, filename='basic-line')\n\nbetter_than_50 = min(i for i in y2 if i > 0.5)\nprint(\"Party size to have >50% chance of a shared birthday =\",\n      y2.index(better_than_50) + 3)\n# Party size to have >50% chance of a shared birthday = 23\n\n# Attempt 2 - simplify\n# Total possible number of matches\ny = sm.factorial(n) / (sm.factorial(n - 2) * sm.factorial(2))\n\n# Chance of nobody matching\na = (364/365)**y\n# Chance there is a match\nb = 1 - a\n\nmatch    = go.Scatter(x = n[0], y = b[0])\nno_match = go.Scatter(x = n[0], y = a[0])\ndata = [match, no_match]\nplot_url = py.plot(data, filename='basic-line')\n\nbetter_than_50 = min(i for i in b[0] if i > 0.5)\nprint(\"Party size to have >50% chance of a shared birthday =\",\n      int(np.where(b[0] == better_than_50)[0]) + 2)\n#  Party size to have >50% chance of a shared birthday = 23\n", "meta": {"hexsha": "6aaf7d024963997cb5c8d0cc4a5a2a62e8857f62", "size": 1821, "ext": "py", "lang": "Python", "max_stars_repo_path": "predict400/week5.py", "max_stars_repo_name": "TJConnellyContingentMacro/northwestern", "max_stars_repo_head_hexsha": "116301f68e9ce02bc13d5496b3e4cec98154f7d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "predict400/week5.py", "max_issues_repo_name": "TJConnellyContingentMacro/northwestern", "max_issues_repo_head_hexsha": "116301f68e9ce02bc13d5496b3e4cec98154f7d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "predict400/week5.py", "max_forks_repo_name": "TJConnellyContingentMacro/northwestern", "max_forks_repo_head_hexsha": "116301f68e9ce02bc13d5496b3e4cec98154f7d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-02-12T01:15:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T23:08:10.000Z", "avg_line_length": 30.8644067797, "max_line_length": 146, "alphanum_fraction": 0.6578802856, "include": true, "reason": "import numpy,import scipy", "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799430946808, "lm_q2_score": 0.9124361658344131, "lm_q1q2_score": 0.8793876759854194}}
{"text": "from sympy import ( symbols, solve, diff, integrate, exp, sqrt, lambdify, pprint, Integral )\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# The number of​ bachelor's degrees conferred has been increasing steadily in recent decades.\n# The rate of change of the number of​ bachelor's degrees​ (in thousands) can be approximated by the following function where t is the number of years since 1970.\n\nt = symbols( 't' )\ndB = 0.0651 * t**2 - 1.939 *t + 16.31\n\n# Divide by 1000\ny_min = 833300 / 1000\n\nB = Integral( dB, t ).doit() + y_min\n\nB.subs( { t: 0 } ) == y_min # Verify\n\n# Find Upper B(t)​, given that about 819,900 degrees were conferred in 1970 ​(t=​0).\npprint( B )\n\n# Use the formula from part a. to project the number of​ bachelor's degrees that will be conferred in 2010, t = 40\nyear_tofind = 40\n\ndeg_2010 = B.subs( { t: year_tofind } )\ndegrees = round( deg_2010 * 1000 )\ndegrees\n\n# What does the degree distribution look like?\n\ng_xlim = [ 0, 50 ]\n\nlam_p = lambdify( t, B, np )\nx_vals = np.linspace( g_xlim[0], g_xlim[1], 1000, endpoint = True )\ny_vals = lam_p( x_vals )\nplt.plot( x_vals, y_vals )\nx_min, x_max = 0, year_tofind\n\nplt.vlines( x = x_min, ymin = y_min, ymax = B.subs( { t: x_min } ), color = 'Black', zorder = 1 )\nplt.vlines( x = x_max, ymin = y_min, ymax = B.subs( { t: x_max } ), color = 'Red', zorder = 1 )\nplt.text( x = x_max, y= deg_2010, s = str( degrees ) )\n\n\nplt.title( str( B ) )\nplt.show()", "meta": {"hexsha": "398802ef47e096451366dd96d5e241fb3a4ada9a", "size": 1423, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Quiz/IV/01.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Quiz/IV/01.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Quiz/IV/01.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3409090909, "max_line_length": 162, "alphanum_fraction": 0.6725228391, "include": true, "reason": "import numpy,from sympy", "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517469248845, "lm_q2_score": 0.899121373891026, "lm_q1q2_score": 0.8793872304316201}}
{"text": "# Softmax function : normalized exponential function\n# Copyright 2018 Denis Rothman MIT License. See LICENSE.\n\nimport math\nimport numpy as np\n\n# y is the vector of the scores of the lv vector in the warehouse example.\ny = [0.0002, 0.2, 0.9,0.0001,0.4,0.6]\nprint('0.Vector to be normalized',y)\n\n#Version 1 : Explicitly writing the softmax function for this case\ny_exp = [math.exp(i) for i in y]\nprint(\"1\",[i for i in y_exp])\nprint(\"2\",[round(i, 2) for i in y_exp])\nsum_exp_yi = sum(y_exp)\nprint(\"3\",round(sum_exp_yi, 2))\nprint(\"4\",[round(i) for i in y_exp])\nsoftmax = [round(i / sum_exp_yi, 3) for i in y_exp]\nprint(\"5,\",softmax)\n\n#Version 2 : Explicitly but with no comments\ny_exp = [math.exp(i) for i in y]\nsum_exp_yi = sum(y_exp)\nsoftmax = [round(i / sum_exp_yi, 3) for i in y_exp]\nprint(\"6, Normalized vector\",softmax)\n\n#Version 3: Using a function in a 2 line code instead of 3 lines\ndef softmax(x):\n    return np.exp(x) / np.sum(np.exp(x), axis=0)\n\nprint(\"7A Normalized vector\",softmax(y))\nprint(\"7B Sum of the normalize vector\",sum(softmax(y)))\n\nohot=max(softmax(y))\nohotv=softmax(y)\n\nprint(\"7C.Finding the highest value in the normalized y vector : \",ohot)\nprint(\"7D.For One-Hot function, the highest value will be rounded to 1 then set all the other values of the vector to 0: \")\nfor onehot in range(6):\n    if(ohotv[onehot]<ohot):\n        ohotv[onehot]=0\n    if(ohotv[onehot]>=ohot):\n        ohotv[onehot]=1\nprint(\"This is a vector that is an output of a one-hot function on a softmax vector\")\nprint(ohotv)\n", "meta": {"hexsha": "aa48b419da778230b4dbc71c957e77e9b0792382", "size": 1516, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter02/SOFTMAX.py", "max_stars_repo_name": "deadphilosopher/Artificial-Intelligence-By-Example", "max_stars_repo_head_hexsha": "cb7f0347b8b14d22d29b746f39a112269ac61900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2018-05-18T02:35:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T10:39:34.000Z", "max_issues_repo_path": "Chapter02/SOFTMAX.py", "max_issues_repo_name": "gahan9/Artificial-Intelligence-By-Example", "max_issues_repo_head_hexsha": "47bed1a88db2c9577c492f950069f58353375cfe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter02/SOFTMAX.py", "max_forks_repo_name": "gahan9/Artificial-Intelligence-By-Example", "max_forks_repo_head_hexsha": "47bed1a88db2c9577c492f950069f58353375cfe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63, "max_forks_repo_forks_event_min_datetime": "2018-05-12T11:16:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T08:31:42.000Z", "avg_line_length": 32.9565217391, "max_line_length": 123, "alphanum_fraction": 0.7038258575, "include": true, "reason": "import numpy", "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.9252299555457567, "lm_q1q2_score": 0.8793487021159994}}
{"text": "import numpy as np\r\nfrom scipy import optimize,integrate,interpolate\r\nimport matplotlib.pyplot as plt\r\n \r\nA = np.array([[1.,2.],[4.,5.]])\r\nprint('A =\\n',A,'\\n')\r\nprint('norm(A) =',np.linalg.norm(A),'\\n')\r\n\r\nB = np.ones((2,2))\r\nC = np.zeros(B.shape)\r\nD = np.eye(4)\r\nE = np.diag(range(3))\r\nb = B[:,1]\r\n\r\n#solve A*x=b\r\nx0 = np.linalg.inv(A)@b\r\nx1 = np.linalg.pinv(A)@b\r\nx2 = np.linalg.solve(A,b)\r\nx3,residuals,rank,s = np.linalg.lstsq(A,b)\r\n\r\nfor i,x in enumerate([x0,x1,x2,x3]):\r\n    print('x{} = {}'.format(i,x))\r\n\r\nu,s,vh = np.linalg.svd(A)\r\nL = np.linalg.cholesky(D)\r\nw,v = np.linalg.eig(A)\r\nq,r = np.linalg.qr(A)\r\n\r\nsignal = np.sin(np.linspace(0,3*np.pi,100))\r\nout = np.fft.fft(signal)\r\n\r\nplt.subplot(1,2,1)\r\nplt.plot(abs(out))\r\nplt.title('modulo')\r\nplt.subplot(1,2,2)\r\nplt.plot(np.angle(out))\r\nplt.title('fase')\r\n\r\ny,abserr = integrate.quad(lambda x: np.sqrt(1-x**2), -1, 1)\r\n\r\nres = optimize.minimize(lambda x: np.exp(x)+x**2,\r\n                  x0=1,\r\n                  method='BFGS',\r\n                  tol = 0.6)\r\n\r\nx = np.linspace(-np.pi,np.pi,4)\r\ny = np.sin(x)\r\nx_new = np.linspace(-np.pi,np.pi,100)\r\ny_new = interpolate.interp1d(x, y,'cubic')(x_new)\r\nplt.figure()\r\nplt.plot(x, y, 'o',\r\n         x_new, y_new, '-',\r\n         x_new, np.sin(x_new), '--')\r\n\r\nsol = integrate.solve_ivp(fun = lambda t,y: -0.5*y,\r\n                          t_span = [0, 10],\r\n                          y0 = [5,4,2,1,3],\r\n                          method = 'RK45',\r\n                          max_step = 0.1)\r\nplt.figure()\r\nplt.plot(sol.t,sol.y.T)\r\n\r\nplt.figure()\r\nplt.bar(['um','dois','tres'],[4,5,6])\r\n\r\nx = np.arange(0,4,0.1)\r\ny = 2*x+np.random.randn(*x.shape)\r\nplt.figure()\r\nplt.scatter(x,y,marker='*')\r\n\r\n\r\nN = 100\r\nx = np.linspace(-3.0, 3.0, N)\r\ny = np.linspace(-2.0, 2.0, N)\r\nX, Y = np.meshgrid(x, y)\r\nZ1 = np.exp(-X**2 - Y**2)\r\nZ2 = np.exp(-(X - 1)**2 - (Y - 1)**2)\r\nZ = (Z1 - Z2) * 2\r\nplt.figure()\r\nplt.contourf(X,Y,Z)\r\nplt.figure()\r\nplt.contour(X,Y,Z)\r\nplt.figure()\r\nplt.imshow(Z)\r\n\r\nplt.figure()\r\nplt.pie([3,4,2,5])\r\n\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfrom matplotlib import cm\r\nfig = plt.figure()\r\nax = fig.gca(projection='3d')\r\nax.plot_surface(X, Y, Z,cmap=cm.rainbow)\r\n\r\n\r\n\"\"\"\r\nMuitas outras referencias de gráficos em\r\nmatplotlib.org/gallery/index.html\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "12ad88981f2c3ebf01cd88d561349c1b530fe380", "size": 2277, "ext": "py", "lang": "Python", "max_stars_repo_path": "dia_2/matlab.py", "max_stars_repo_name": "mariogen/curso_python", "max_stars_repo_head_hexsha": "767512edd07ee02f72293f539aa61b73e1dfe78d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dia_2/matlab.py", "max_issues_repo_name": "mariogen/curso_python", "max_issues_repo_head_hexsha": "767512edd07ee02f72293f539aa61b73e1dfe78d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dia_2/matlab.py", "max_forks_repo_name": "mariogen/curso_python", "max_forks_repo_head_hexsha": "767512edd07ee02f72293f539aa61b73e1dfe78d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6857142857, "max_line_length": 60, "alphanum_fraction": 0.5472112429, "include": true, "reason": "import numpy,from scipy", "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924810166349, "lm_q2_score": 0.9046505402422644, "lm_q1q2_score": 0.8793135230631177}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import quad\nfrom scipy.integrate import romberg\n\n\n# part a\n\nx = np.linspace(0,5,100)\n \nY1 = (x**(1))*(np.exp(-x)) # a = 2\nY2 = (x**(2))*(np.exp(-x)) # a = 3\nY3 = (x**(3))*(np.exp(-x)) # a = 4\n\nplt.plot(x,Y1,'r--',label='a = 2') # first line where a = 2 is red dashes\nplt.plot(x,Y2,'b--',label='a = 3') # second line where a = 3 is blue dashes\nplt.plot(x,Y3,'g--',label='a = 4') # third line where a = 4 is green dashes\nplt.legend(loc=0) # adding a legend\nplt.title('Gamma function with varying values of a')\nplt.xlabel('x')\nplt.ylabel('Gamma function Y')\nplt.show() \n\n\n# part b\n\n# gamma function integrand (denoted as y for this derivation):\n\n# y = x^(a-1) * e^(-x) where a = real constant\n# y' = dy/dx = d/dx (u*v) \n# when u = x^(a-1) and u' = (a-1)*x^(a-2)\n# and v = e^(-x) and v' = -e^(-x)\n\n# d/dx (u*v) = u'v+uv'\n\n# u'v+uv' = [e^(-x)]*[(a-1)*x^(a-2)]+[x^(a-1)]*[-e^(-x)]\n# = [e^(-x)]*[(a-1)*x^(a-2)]-[x^(a-1)]*[e^(-x)]\n# = [e^(-x)]*[(a-1)*x^(a-2)-x^(a-1)]\n\n# plug in x = a-1\n\n# u'v+uv' = [e^(1-a)]*[(a-1)*(a-1)^(a-2)-(a-1)^(a-1)]\n# u'v+uv' = [e^(1-a)]*[(a-1)^(a-1)-(a-1)^(a-1)] = 0\n\n# derivative of a f(x) equals zero when x = stationary point\n# so, x = a-1 gives stationary point (maximum) \n\n# part c\n\ndef Y(x): # defining gamma quation\n    return (x**(0.5))*(np.exp(-x)) #  here, a = 3/2\n\nprint \"The value of the Gamma function with its error is\",quad(Y, 0, np.inf),\"at a = 3/2 when we use the built in sci.integrate.quad module. This value is supposed to be around 1/2*(sqrt(pi) which is ~0.886 so this value is good.\"\n\nprint \"The value of the Gamma function  is\",romberg(Y,0,1e+1),\"at a = 3/2 when we use the Romberg method. This value is also around the accepted value of ~0.886 so this value is also good.\"", "meta": {"hexsha": "ca529a83c02a63f848b83796a239beaab1a4d623", "size": 1788, "ext": "py", "lang": "Python", "max_stars_repo_path": "ExamPrep/Shit Comp/SciComp Exam 2016/Assignments 15-16/A2Q4 quad romberg scipy integrate.py", "max_stars_repo_name": "FHomewood/ScientificComputing", "max_stars_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_stars_repo_licenses": ["IJG"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ExamPrep/Shit Comp/SciComp Exam 2016/Assignments 15-16/A2Q4 quad romberg scipy integrate.py", "max_issues_repo_name": "FHomewood/ScientificComputing", "max_issues_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_issues_repo_licenses": ["IJG"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ExamPrep/Shit Comp/SciComp Exam 2016/Assignments 15-16/A2Q4 quad romberg scipy integrate.py", "max_forks_repo_name": "FHomewood/ScientificComputing", "max_forks_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_forks_repo_licenses": ["IJG"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5090909091, "max_line_length": 230, "alphanum_fraction": 0.5844519016, "include": true, "reason": "import numpy,from scipy", "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452443, "lm_q2_score": 0.9273632921335859, "lm_q1q2_score": 0.879283713574828}}
{"text": "import numpy as np\n\n# Write a function that takes as input a list of numbers, and returns\n# the list of values given by the softmax function.\n\n# This implementation supports L of any dimensionality\ndef softmax(L): # Let L = [5, 6, 7]\n    # View inputs as arrays with atleast two dimensions\n    y = np.atleast_2d(L) # [[ 5, 6, 7 ]]\n    \n    # Find axis along which to do computation\n    # axis = 0 means do computation row wise\n    # axis = 1 means do computation column wise\n    axis = next(j[0] for j in enumerate(y.shape) if j[1] > 1) # axis = 1\n    \n    # Calculate maximum value in given list, i.e, max(L)\n    y_max = np.max(y, axis = axis) # [7]\n    \n    # Step 1: Calculate exp(Ln - max(L)) which is equivalent to exp(Ln) / exp(max(L))\n    # (i) Ln - max(L)\n    # Expand dimensions of y_max along axis = 1 in our case and subtract from y\n    y = y - np.expand_dims(y_max, axis) # [[5, 6, 7]] - [[7]] = [[-2,-1,0]]\n    # (ii) exp(Ln - max(L))\n    y = np.exp(y) # [[0.13533528 0.36787944 1.        ]]\n    \n    # Step 2: Calculate sum(exp(Ln - max(L))) which is equivalent to sum(exp(Ln)) / exp(max(L))\n    y_sum = np.sum(y, axis = axis) # Add along axis = 1 in our case => [1.50321472]\n    y_sum_expanded = np.expand_dims(y_sum, axis) # [[1.50321472]]\n    \n    # Step 3: Calculate exp(Ln) / sum(exp(Ln)) which can be obtained by dividing result of Step 1 by result of Step 2\n    p = y / y_sum_expanded # [[0.09003057 0.24472847 0.66524096]]\n    \n    return p.flatten() # Return array of copy collapsed to one dimension\n    \n    pass\n", "meta": {"hexsha": "75d65e45d03cf506c4a2e575b0f8d803c7850687", "size": 1537, "ext": "py", "lang": "Python", "max_stars_repo_path": "P2-Softmax Implementation/main.py", "max_stars_repo_name": "MANOJPATRA1991/Deep-Learning-Nanodegree", "max_stars_repo_head_hexsha": "4848df7dbc8ff413ad79f4437a76c4bb212be8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "P2-Softmax Implementation/main.py", "max_issues_repo_name": "MANOJPATRA1991/Deep-Learning-Nanodegree", "max_issues_repo_head_hexsha": "4848df7dbc8ff413ad79f4437a76c4bb212be8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P2-Softmax Implementation/main.py", "max_forks_repo_name": "MANOJPATRA1991/Deep-Learning-Nanodegree", "max_forks_repo_head_hexsha": "4848df7dbc8ff413ad79f4437a76c4bb212be8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6944444444, "max_line_length": 117, "alphanum_fraction": 0.6200390371, "include": true, "reason": "import numpy", "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574668, "lm_q2_score": 0.9173026494123034, "lm_q1q2_score": 0.8792691989764485}}
{"text": "import numpy as np\n\ndef hypothesis(b,m,x):\n\tpredicted_y = (b + (m*x))\n\treturn predicted_y\n\ndef cost(b,m,points):\n\ttotalError = 0\n\tM = (float(len(points)))\n\tfor i in range(len(points)):\n\t\tx = float(points[i,0])\n\t\ty = float(points[i,1])\n\t\ttotalError += (1/(2*M)) * ((hypothesis(b,m,x) - y)**2)\n\treturn totalError\n\ndef gradient_descent(b,m,points,alpha,epochs):\n\tpartial_b=partial_m=0\n\tnew_b = b\n\tnew_m = m\n\tfor convergence in range(epochs):\n\t\tfor i in range(len(points)):\n\t\t\tx = float(points[i,0])\n\t\t\ty = float(points[i,1])\n\t\t\tpartial_b += (1/float(len(points))) * (hypothesis(new_b,new_m,x) - y)\n\t\t\tpartial_m += (1/float(len(points))) * (hypothesis(new_b,new_m,x) - y) * x\n\t\tnew_b = (b - (alpha*partial_b))\n\t\tnew_m = (m - (alpha*partial_m))\n\treturn [new_b, new_m]\n\ndef main():\n\tb=m=0\n\talpha = 0.0008\n\tepochs = 1000\n\tpoints = np.genfromtxt('data.csv', delimiter=',')\n\t[new_b, new_m] = gradient_descent(b, m, np.asarray(points), alpha, epochs)\n\tx = float(input(\"Enter X value to predict : \"))\n\ty = hypothesis(new_b,new_m,x)\n\tprint('Predicted price is : {}'.format(y))\n\n\tprint(\"Cost function's weights are b:{}, m:{}\".format(new_b, new_m))\n\tprint(\"Total cost is : {}\".format(cost(new_b,new_m,np.asarray(points))))\n\t\nif __name__ == '__main__':\n\tmain()\n\t\n", "meta": {"hexsha": "0beefe81ba70e71001c11ca7b96d117d15c6fd84", "size": 1249, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "ankitiiest21/Batch_Gradient_Descent", "max_stars_repo_head_hexsha": "c167b095567c1c09d1f863c00d0540b4c6017ff6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-15T00:40:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T05:18:31.000Z", "max_issues_repo_path": "main.py", "max_issues_repo_name": "TheBlackEyeGuy/Batch_Gradient_Descent", "max_issues_repo_head_hexsha": "3ba8b1323f350276f522d80d13a1bd377da67907", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "TheBlackEyeGuy/Batch_Gradient_Descent", "max_forks_repo_head_hexsha": "3ba8b1323f350276f522d80d13a1bd377da67907", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-11T05:18:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T05:18:19.000Z", "avg_line_length": 27.152173913, "max_line_length": 76, "alphanum_fraction": 0.645316253, "include": true, "reason": "import numpy", "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9763105335255604, "lm_q2_score": 0.9005297927918167, "lm_q1q2_score": 0.8791967224562409}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\nnp.random.seed(0)\n\n#%% https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html\n# Generate the sample\nmu = 170\nsd = 8\nx = norm.rvs(loc=mu, scale=sd, size=100)\n\n#%% Statistics\nprint(x.mean())\nprint(x.var())\nprint(x.std())\n\n#%% Delta Degrees of freedom\nprint(x.var(ddof=1))\nprint(x.std(ddof=1))\n\n#%% Quantile function (inverse of cdf)\nprint(norm.ppf(0.95, loc=mu, scale=sd))\n\n#%% CDF\nprint(norm.cdf(165, loc=mu, scale=sd))\n\n#%% Survival Function = 1 - cdf\nprint(1-norm.cdf(165, loc=mu, scale=sd))\nprint(norm.sf(165, loc=mu, scale=sd))\n", "meta": {"hexsha": "c2bb7d59b2d839ac58d25982ffdaf5a76bedf252", "size": 631, "ext": "py", "lang": "Python", "max_stars_repo_path": "probability/cdf_percentile.py", "max_stars_repo_name": "chinmaykurade/ab-testing-course", "max_stars_repo_head_hexsha": "14a96b5acd711a29010d4bb7a7cdd41a0ae492f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "probability/cdf_percentile.py", "max_issues_repo_name": "chinmaykurade/ab-testing-course", "max_issues_repo_head_hexsha": "14a96b5acd711a29010d4bb7a7cdd41a0ae492f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "probability/cdf_percentile.py", "max_forks_repo_name": "chinmaykurade/ab-testing-course", "max_forks_repo_head_hexsha": "14a96b5acd711a29010d4bb7a7cdd41a0ae492f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0333333333, "max_line_length": 78, "alphanum_fraction": 0.6941362916, "include": true, "reason": "import numpy,from scipy", "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.914900963114118, "lm_q1q2_score": 0.8791756404446855}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nExamples of root finding\r\n\r\n@author: Nicolas Guarin-Zapata\r\n@date: Febr, 2018\r\n\"\"\"\r\nfrom __future__ import division, print_function\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom roots import newton, bisection\r\n\r\n\r\nnpts = 201\r\na = -1.0\r\nb = 10.0\r\nfun = lambda x: x**3 + 4.0*x**2 - 10.0\r\nderiv = lambda x: 3.0*x**2 + 8.0*x\r\n\r\n#%% Plot\r\nx = np.linspace(a, b, npts)\r\ny = fun(x)\r\nplt.plot(x, y)\r\nplt.grid(True)\r\nplt.ylim(-40, 100)\r\nplt.xlabel(\"x\")\r\nplt.ylabel(\"y\")\r\n\r\n#%% Bisection\r\nprint(\"Bisection solution\")\r\nprint(\"=\"*25)\r\nbisection(fun, a, b, verbose=True)\r\n\r\n#%% Newton-Raphson\r\nprint(\"\\n\\n\")\r\nprint(\"Newton-Raphson solution\")\r\nprint(\"=\"*25)\r\nnewton(fun, deriv, 10, verbose=True, ftol=1e-16)\r\n\r\nplt.show()", "meta": {"hexsha": "f147609a4801f9f46d64793fffaaa3ccf862c4d2", "size": 749, "ext": "py", "lang": "Python", "max_stars_repo_path": "codigo/metodos_numericos/raices/example_roots.py", "max_stars_repo_name": "AppliedMechanics-EAFIT/Mod_Temporal", "max_stars_repo_head_hexsha": "6a0506d906ed42b143b773777e8dc0da5af763eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-02-20T18:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-19T22:44:44.000Z", "max_issues_repo_path": "codigo/metodos_numericos/raices/example_roots.py", "max_issues_repo_name": "AppliedMechanics-EAFIT/Mod_Temporal", "max_issues_repo_head_hexsha": "6a0506d906ed42b143b773777e8dc0da5af763eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-04-15T00:22:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-04T17:03:54.000Z", "max_forks_repo_path": "codigo/metodos_numericos/raices/example_roots.py", "max_forks_repo_name": "AppliedMechanics-EAFIT/Mod_Temporal", "max_forks_repo_head_hexsha": "6a0506d906ed42b143b773777e8dc0da5af763eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-14T18:17:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-27T06:37:05.000Z", "avg_line_length": 18.725, "max_line_length": 49, "alphanum_fraction": 0.6275033378, "include": true, "reason": "import numpy", "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9609517072737735, "lm_q2_score": 0.9149009584734678, "lm_q1q2_score": 0.8791756380314907}}
{"text": "#!/bin/env python3\n# coding: utf-8 \n\nimport numpy as np\nimport sys\n\n\ndef linear(x, y, n):\n\tn = len(x)\n\tb = (n*sum(x*y)-sum(x)*sum(y))/(n*sum(x*x)-sum(x)**2)\n\ta = (sum(y)-b*sum(x))/n\n\t\n\treturn a, b\n\n\ndef R2(x, y, n, a, b, c = 0):\n\tyMean = sum(y) / n\n\tyHat = a + b * x + c * x*x\n\n\tsst = sum((y - yMean) ** 2)\n\tsse = sum((yHat - yMean) ** 2)\n\tssr = sum((y - yHat) ** 2)\n\n\tr2 = sse / sst\n\tr2_adj = 1 - (n - 1) / (n - 2) * (1 - r2)\n\n\treturn r2 * 100 , r2_adj * 100\n\n\ndef main():\n\tx = np.array([0.0162, 1.4094, 3.0132, 5.5080, 8.1000, 10.3032, 11.8422])\n\ty = np.array([0.0089, 0.0265, 0.0400, 0.0650, 0.0835, 0.1017, 0.1092])\n\n\tif len(x) != len(y):\n\t\tsys.exit(\"Number of data points for x and y are different!\")\n\n\n\tn = len(x)\n\ta, b = linear(x, y, n)\n\tr2, r2_adj = R2(x, y, n, a, b)\n\n\tprint(\"Linear Regression\")\n\tprint(\"-----------------\")\n\tprint(\"\")\n\tprint(\"y = {:.10f} + {:.10f} x\".format(a, b))\n\tprint(\"\")\n\tprint(\"R² = {:.2f}%\".format(r2))\n\tprint(\"R²_adj = {:.2f}%\".format(r2_adj))\n\n\nif __name__ == '__main__':\n\tmain()", "meta": {"hexsha": "5ec1ea2b94743517846bd2e6e64313d6ead90b0e", "size": 1014, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/linear-regression.py", "max_stars_repo_name": "marvinfriede/projects", "max_stars_repo_head_hexsha": "7050cd76880c8ff0d9de17b8676e82f1929a68e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/linear-regression.py", "max_issues_repo_name": "marvinfriede/projects", "max_issues_repo_head_hexsha": "7050cd76880c8ff0d9de17b8676e82f1929a68e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-04-14T20:15:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-14T20:20:54.000Z", "max_forks_repo_path": "python/linear-regression.py", "max_forks_repo_name": "marvinfriede/projects", "max_forks_repo_head_hexsha": "7050cd76880c8ff0d9de17b8676e82f1929a68e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5, "max_line_length": 73, "alphanum_fraction": 0.5187376726, "include": true, "reason": "import numpy", "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203815, "lm_q2_score": 0.9111797106148062, "lm_q1q2_score": 0.879156441483383}}
{"text": "from lagrangianpoly import LagrangianBasis, LagrangianPoly, Derivative\nimport SymbolicFiniteDifference as fd\nimport SymbolicInterpolation as intp\nimport TaylorExpansion as te\n\n\ndef main():\n    import sympy as sp\n\n    # lagrangian basis\n    x = sp.symbols('x')\n    eq = LagrangianBasis(x, degreeOfPolynomial=5, pointAt=0)\n    print(eq)\n    # (x - x1)*(x - x2)*(x - x3)*(x - x4)*(x - x5)/((x0 - x1)*(x0 - x2)*(x0 - x3)*(x0 - x4)*(x0 - x5))\n\n    x = sp.symbols('x')\n    dx = sp.symbols('dx')\n\n    # 3-point stencil lagrangian polynomial\n    x_set = [-dx, 0, dx]\n    f_set = sp.symbols('f0:{:d}'.format(len(x_set)))\n    eq = LagrangianPoly(x, x_set, f_set)\n    print(eq)\n    # f0*x*(-dx + x)/(2*dx**2) - f1*(-dx + x)*(dx + x)/dx**2 + f2*x*(dx + x)/(2*dx**2)\n\n    # 3-point stencil central difference for 1st derivative on regular grid\n    x_set = [-dx, 0, dx]\n    f_set = sp.symbols('f0:{:d}'.format(len(x_set)))\n    eq = Derivative(LagrangianPoly(x, x_set, f_set), x, orderOfDifference=1)\n    print(eq)\n\n    # 3-point stencil central difference for 2nd derivative on regular grid\n    x_set = [-dx, 0, dx]\n    f_set = sp.symbols('f0:{:d}'.format(len(x_set)))\n    eq = Derivative(LagrangianPoly(x, x_set, f_set), x, orderOfDifference=2)\n    print(eq)\n\n    # 5-point stencil central difference for 1st derivative on regular grid\n    x_set = [-2*dx, -dx, 0, dx, 2*dx]\n    f_set = sp.symbols('f0:{:d}'.format(len(x_set)))\n    eq = Derivative(LagrangianPoly(x, x_set, f_set), x, orderOfDifference=1)\n    print(eq)\n\n    # 3-point stencil right-sided difference for 1st derivative on regular grid\n    x_set = [0, dx, 2*dx]\n    f_set = sp.symbols('f0:{:d}'.format(len(x_set)))\n    eq = Derivative(LagrangianPoly(x, x_set, f_set), x, orderOfDifference=1)\n    print(eq)\n\n    # 4-point stencil right-sided difference for 2nd derivative on regular grid\n    x_set = [0, dx, 2*dx, 3*dx]\n    f_set = sp.symbols('f0:{:d}'.format(len(x_set)))\n    eq = Derivative(LagrangianPoly(x, x_set, f_set), x, orderOfDifference=2)\n    print(eq)\n\n    # 3-point stencil central difference for 1st derivative on staggered grid\n    x_set = [-dx/2, 0, dx/2]\n    f_set = sp.symbols('f0:{:d}'.format(len(x_set)))\n    eq = Derivative(LagrangianPoly(x, x_set, f_set), x, orderOfDifference=1)\n    print(eq)\n\n    # 5-point central difference for 1st derivative with a default interval symbol\n    stencil = [-2, -1, 0, 1, 2]\n    eq = fd.getFiniteDifferenceEquation(\n        stencil, orderOfDifference=1)\n    print(eq)\n\n    # 5-point central difference for 1st derivative with a default interval symbol\n    stencil = [-2, -1, 0, 1, 2]\n    eq = fd.getFiniteDifferenceEquation(\n        stencil, 1, sameSubscriptsAsStencil=True, evaluate=False)\n    print(eq)\n\n    # 5-point central difference for 1sit derivative with an user-defined interval symbol\n    stencil = [-2, -1, 0, 1, 2]\n    eq = fd.getFiniteDifferenceEquation(\n        stencil, orderOfDifference=1, intervalSymbolStr='dx')\n    print(eq)\n\n    # 3-point one-sided difference for 1st derivative with a default interval symbol\n    stencil = [0, 1, 2]\n    eq = fd.getFiniteDifferenceEquation(\n        stencil, orderOfDifference=1)\n    print(eq)\n\n    # 4-point one-sided difference for 2nd derivative with a default interval symbol\n    stencil = [0, 1, 2, 3]\n    eq = fd.getFiniteDifferenceEquation(\n        stencil, orderOfDifference=2)\n    print(eq)\n\n    # 5-point central difference formula for 1st derivative with changing subscripts\n    stencil = [-2, -1, 0, 1, 2]\n    eq = fd.getFiniteDifferenceEquation(\n        stencil, orderOfDifference=1, sameSubscriptsAsStencil=True)\n    print(eq)\n\n    # 5-point central difference formula for 1st derivative with changing subscripts\n    stencil = [-1.5, -0.5, 0, 0.5, 1.5]\n    eq = fd.getFiniteDifferenceEquation(\n        stencil, orderOfDifference=1, sameSubscriptsAsStencil=True)\n    print(eq)\n\n    # coefficients for 5-point central difference for 1st derivative\n    stencil = [-2, -1, 0, 1, 2]\n    coef = fd.getFiniteDifferenceCoefficients(\n        stencil, orderOfDifference=1)\n    print(coef)\n\n    # coefficients for 7-point central difference for 1st derivative\n    stencil = [-3, -2, -1, 0, 1, 2, 3]\n    coef = fd.getFiniteDifferenceCoefficients(\n        stencil, orderOfDifference=1)\n    print(coef)\n\n    # coefficients for 3-point one-sided difference for 1st derivative\n    stencil = [0, 1, 2]\n    coef = fd.getFiniteDifferenceCoefficients(\n        stencil, orderOfDifference=1)\n    print(coef)\n\n    # coefficients for 4-point one-sided difference for 2nd derivative\n    stencil = [0, 1, 2, 3]\n    coef = fd.getFiniteDifferenceCoefficients(\n        stencil, orderOfDifference=2)\n    print(coef)\n\n    # numerator and denominator of coefficients for 5-point central difference for 1st derivative\n    stencil = [-2, -1, 0, 1, 2]\n    numr, denom = fd.getFiniteDifferenceCoefficients(\n        stencil, orderOfDifference=1, as_numr_denom=True)\n    print(numr, denom)\n\n    # numerator and denominator of coefficients for 7-point central difference for 1st derivative\n    stencil = [-3, -2, -1, 0, 1, 2, 3]\n    numr, denom = fd.getFiniteDifferenceCoefficients(\n        stencil, orderOfDifference=1, as_numr_denom=True)\n    print(numr, denom)\n\n    # numerator and denominator of coefficients for 3-point one-sided difference for 1st derivative\n    stencil = [0, 1, 2]\n    numr, denom = fd.getFiniteDifferenceCoefficients(\n        stencil, orderOfDifference=1, as_numr_denom=True)\n    print(numr, denom)\n\n    # numerator and denominator of coefficients for 3-point one-sided difference for 1st derivative on staggered grid\n    stencil = [-0.5, 0, 0.5]\n    numr, denom = fd.getFiniteDifferenceCoefficients(\n        stencil, orderOfDifference=1, as_numr_denom=True)\n    print(numr, denom)\n\n    # Tayloer expansion of f(x+h) around x up to term including 6th order difference\n    h = sp.symbols('h')\n    f1 = te.TaylorExpansion(h, n=6)\n    print(f1)\n\n    # Tayloer expansion of f(x-h) around x up to term including 7th order difference\n    h = sp.symbols('h')\n    f_1 = te.TaylorExpansion(-h, n=7)\n    print(f_1)\n\n    # Tayloer expansion of f(x+2h) around x up to term including 4th order difference\n    h = sp.symbols('h')\n    f2 = te.TaylorExpansion(2*h, n=4)\n    print(f2)\n\n    # truncation error of 3-point central finite difference for 1st derivative\n    stencil = [-1, 0, 1]\n    err = fd.getTruncationError(stencil, 1)\n    print(err)\n\n    # truncation error of 3-point central finite difference for 2nd derivative\n    stencil = [-1, 0, 1]\n    err = fd.getTruncationError(stencil, 2)\n    print(err)\n\n    # truncation error of 5-point central finite difference for 1st derivative\n    stencil = [-2, -1, 0, 1, 2]\n    err = fd.getTruncationError(stencil, 1)\n    print(err)\n\n    # truncation error of 3-point central finite difference for 1st dervative on the staggered grid\n    stencil = [-0.5, 0, 0.5]\n    err = fd.getTruncationError(stencil, 1)\n    print(err)\n\n    # truncation error of 3-point central finite difference for 1st derivative on the staggered grid\n    stencil = [-1.5, -0.5, 0, 0.5, 1.5]\n    err = fd.getTruncationError(stencil, 1)\n    print(err)\n\n    # 2-point central interpolation\n    stencil = [-1, 1]\n    eq = intp.getInterpolationEquation(stencil)\n    print(eq)\n\n    # 4-point central interpolation\n    stencil = [-2, -1, 1, 2]\n    eq = intp.getInterpolationEquation(stencil)\n    print(eq)\n\n    # coefficients for 2-point central interpolation\n    stencil = [-1, 1]\n    coef = intp.getInterpolationCoefficients(stencil)\n    print(coef)\n\n    # coefficients for 4-point central interpolation\n    stencil = [-2, -1, 1, 2]\n    coef = intp.getInterpolationCoefficients(stencil)\n    print(coef)\n\n    # numerator and denominator of coefficients for 2-point central interpolation\n    stencil = [-1, 1]\n    numr, denom = intp.getInterpolationCoefficients(\n        stencil, as_numr_denom=True)\n    print(numr, denom)\n\n    # numerator and denominator of coefficients for 4-point central interpolation\n    stencil = [-2, -1, 1, 2]\n    numr, denom = intp.getInterpolationCoefficients(\n        stencil, as_numr_denom=True)\n    print(numr, denom)\n\n    # truncation error of 2-point central interpolation\n    stencil = [-1, 1]\n    err = intp.getTruncationError(stencil)\n    print(err)\n\n    # truncation error of 4-point central interpolation\n    stencil = [-2, -1, 1, 2]\n    err = intp.getTruncationError(stencil)\n    print(err)\n\n    # linear extrapolation\n    stencil = [1, 2]\n    eq = intp.getInterpolationEquation(stencil)\n    err = intp.getTruncationError(stencil)\n    print(eq)\n    print(err)\n\n    # quadratic extrapolation\n    stencil = [1, 2, 3]\n    eq = intp.getInterpolationEquation(stencil)\n    err = intp.getTruncationError(stencil)\n    print(eq)\n    print(err)\n\n    return\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "a73a3beabbf34f39c76d3a9cf9ea72bc1ee5793c", "size": 8785, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "degawa/Symbolic_Lagrangian_Polynomial_and_Finite_Difference", "max_stars_repo_head_hexsha": "aea5b24a0ecafb8c7223f0db6827527e7c1cb14e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.py", "max_issues_repo_name": "degawa/Symbolic_Lagrangian_Polynomial_and_Finite_Difference", "max_issues_repo_head_hexsha": "aea5b24a0ecafb8c7223f0db6827527e7c1cb14e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "degawa/Symbolic_Lagrangian_Polynomial_and_Finite_Difference", "max_forks_repo_head_hexsha": "aea5b24a0ecafb8c7223f0db6827527e7c1cb14e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7233201581, "max_line_length": 117, "alphanum_fraction": 0.6711439954, "include": true, "reason": "import sympy", "num_tokens": 2636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551525886193, "lm_q2_score": 0.91117969855511, "lm_q1q2_score": 0.8791564270850428}}
{"text": "import numpy as np\n\n\ndef polynomial_interpolation(x, y):\n    \"\"\"\n        Computes c of interpolating polynomial using Newton method.\n\n        Parameters\n        ----------\n        x : ndarray\n            The values of the independent variable\n        y : list\n            The values of f(x) for every x, where x is the independent variable\n\n        Returns\n        -------\n        c : list\n            coefficients of interpolating polynomial\n    \"\"\"\n    v = []\n    [v.append([0 for j in range(len(x))]) for i in range(len(x))]\n    for j in range(len(x)):\n        v[j][0] = y[j]\n\n    for i in range(1, len(x)):\n        for j in range(len(x) - i):\n            v[j][i] = (v[j + 1][i - 1] - v[j][i - 1]) / (x[j + i] - x[j])\n\n    c = []\n    for i in range(len(x)):\n        c.append(v[0][i])\n\n    return c\n\n\ndef calculate_polynomial(degree, x_data, coefficients, x):\n    \"\"\"\n        Computes the value of the interpolating polynomial.\n\n        Parameters\n        ----------\n        degree : int\n            The degree of the interpolating polynomial.\n        x_data : list\n            The values that were used when calculating the c of the interpolating polynomial.\n        coefficients : list\n            The coefficients of the interpolating polynomial, constant term first.\n        x : int\n            The point at which the polynomial will be calculated\n\n        Returns\n        -------\n        value : float\n            The value of the interpolating polynomial at point x.\n    \"\"\"\n    value = 0.0\n    for i in range(degree + 1):\n        temp = coefficients[i]\n        for j in range(i):\n            temp *= (x - x_data[j])\n        value += temp\n\n    return value\n\n\ndef custom_sin(value):\n    \"\"\"\n        Approximates sin curve with degree 9 polynomial.\n\n        Parameters\n        ----------\n        value : float\n            The point at which the sin will be approximated\n\n        Returns\n        -------\n        float\n            The approximation value of the sin curve at point x.\n    \"\"\"\n    x = [0.0, 0.65, 1.3, 1.9500000000000002, 2.6, 3.25, 3.9000000000000004, 4.55, 5.2, 2*np.pi]\n    y = [0.0, 0.6051864057, 0.9635581854, 0.9289597150, 0.5155013718, -0.1081951345, -0.6877661591, -0.9868438585,\n         -0.8834546557, 0]\n    c = polynomial_interpolation(x, y)\n    value = value % (2 * np.pi)\n\n    return calculate_polynomial(len(x) - 1, x, c, value)\n", "meta": {"hexsha": "e16a65f2bee140edd4ec33e1d65629a6f018781a", "size": 2363, "ext": "py", "lang": "Python", "max_stars_repo_path": "Second Project/Exercise5/polynomial.py", "max_stars_repo_name": "TasosOperatingInBinary/Numerical-Analysis-Projects", "max_stars_repo_head_hexsha": "61a8014f2b853a646145cea5a4d3655e100be854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Second Project/Exercise5/polynomial.py", "max_issues_repo_name": "TasosOperatingInBinary/Numerical-Analysis-Projects", "max_issues_repo_head_hexsha": "61a8014f2b853a646145cea5a4d3655e100be854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Second Project/Exercise5/polynomial.py", "max_forks_repo_name": "TasosOperatingInBinary/Numerical-Analysis-Projects", "max_forks_repo_head_hexsha": "61a8014f2b853a646145cea5a4d3655e100be854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1609195402, "max_line_length": 114, "alphanum_fraction": 0.5463393991, "include": true, "reason": "import numpy", "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551505674444, "lm_q2_score": 0.9111797003640646, "lm_q1q2_score": 0.8791564269887684}}
{"text": "# MSDS 400 Module 9 Practice 1\n\nfrom numpy import random, arange, array\nimport matplotlib.pyplot as plt\n\n\n# The random sample size=nsamples and can be specified by the student.\n\nnsamples = 100\nsample = random.random(nsamples)  # This draws a random sample.\n\nnbins = 10  # This defines the number of subintervals for the histogram.\nbns = float(nbins)\n'''\nFor a uniform distribution, the proportions in each subinterval are\nexpected to be the same.  With ten subintervals, this amounts to 0.1 in\neach.  With 20 subintervals it amounts to 0.05.\n'''\nexpected = 1.0 / bns  # This defines the expected subinterval proportion.\n\nind = arange(nbins)  # This sets ind to serve as a range of indices.\nh = [0] * nbins  # This prepares h to serve as a list of the proper length.\nhistogram = {}  # This defines histogram as a void dictionary.\n\nfor k in ind:\n    histogram[k] = 0  # This initializes the dictionary with zero counts.\n'''\nIn the for loop we run v across all randomly generated values and categorize\nthem according to which bin they fall in.  The count for each bin is\naccumulated in the dictionary histogram[] indexed according to ind[].\n'''\nfor v in sample:\n    for k in ind:\n        xk = float(k)\n        if xk / bns <= v < (xk + 1) / bns:\n            histogram[k] += 1\n'''\nThe following for loop converts each count to a proportion and stores the\nproportions in the list h[] and the dictionary histogram[].  The list h[]\nwill be used for plotting and the dictionary histogram[] for computing.\n'''\nfor k in ind:\n    x = histogram[k]\n    x = x / float(nsamples)\n    h[k] = [x]\n    histogram[k] = x\n'''\nMeasuring the degree of convergence of the histogram to the limiting uniform\ndistribution can be done in various ways.  Here we use the sum of absolute\ndifferences between the expected proportion and the observed proportion.\n'''\ntotal = 0.0\nfor k in ind:\n    total = total + abs(expected - histogram[k])\ntotal = format(total, '0.4e')\nprint('Sum of Absolute Differences= {}'.format(total))\n\nh = array(h)\ncell = ind + 0.5  # This will center the bar in the middle of the subinterval.\n\nplt.bar(cell, h, width=0.5, align='center', color='r')\nplt.plot(cell, h)\n\n# The following statements are used to form the title for the plot.\n# Note how computational information is being included in the title.\n\nstring = str(nsamples) + '   Absolute Difference= ' + str(sum)\nplt.title('Histogram   n=' + string)\n\nplt.ylabel('Proportions')\nplt.xlabel('Subintervals')\nplt.show()\n\n# Exercise 1:  Generate a series of plotted histograms using the code.\n# Generate five plots using nsample values increasing by powers of ten:  100,\n# 1000, 10000, 100000, 1000000.  Calculate the sample mean value and absolute\n# difference for each plot.  Evaluate the changes in absoute difference and\n# mean values as the sample size increases.  When computing the sample mean\n# value, use the dictionary histogram[] and the ind array. The ind array needs\n# to be centered within each subinterval. (Hint: add 0.5)\n\n# Exercise 2:  Add code to estimate the sample variance for each random sample.\n# For simplicity, calculate the sum of the following terms:\n# histogram[k]*(ind[k]-mean)**2.  In the limit as nsamples approaches\n# infinity, for sample data grouped in subintervals centered at 0.5, 1.5, ...,\n# 8.5, 9.5, the limiting value is 8.25.  Do you see convergence?\n\n", "meta": {"hexsha": "1ba596cae7c4d0a29a4b72d4f3fa54f34e98d526", "size": 3336, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Module 9/practice/Module 9 Practice 1.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Module 9/practice/Module 9 Practice 1.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Module 9/practice/Module 9 Practice 1.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9090909091, "max_line_length": 79, "alphanum_fraction": 0.721822542, "include": true, "reason": "from numpy", "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.934395164824565, "lm_q1q2_score": 0.8790693974774825}}
{"text": "import numpy as np\r\n\r\n# dot\r\n# For 2-D vectors, it is the equivalent to matrix multiplication.\r\n# For 1-D arrays, it is the inner product of the vectors\r\n# For N-dimensional arrays, it is a sum product over the last axis of a and the second-last axis of b\r\n\r\na = np.array([[1,2],[3,4]]) \r\nb = np.array([[11,12],[13,14]]) \r\nc = np.dot(a,b) # [[1*11+2*13, 1*12+2*14],[3*11+4*13, 3*12+4*14]]\r\nprint(\"dot prod: \", c)\r\n\r\n# vdot\r\na = np.array([[1,2],[3,4]]) \r\nb = np.array([[11,12],[13,14]]) \r\nprint (\"vdot: \", np.vdot(a,b)) # 1*11 + 2*12 + 3*13 + 4*14 = 130\r\n\r\n# inner\r\nprint (\"inner product of 2 1-d vectors: \", inner prodc\"\"np.inner(np.array([1,2,3]),np.array([0,1,0])) \r\n# Equates to 1*0+2*1+3*0\r\n\r\na = np.array([[1,2], [3,4]])\r\nb = np.array([[11, 12], [13, 14]]) \r\nprint(\"inner produc: \", np.inner(a,b)) \r\n# [[1*11+2*12, 1*13+2*14] \r\n# [3*11+4*12, 3*13+4*14]]  \r\n\r\n# matmul\r\na = [[1,0],[0,1]] \r\nb = [[4,1],[2,2]] \r\nprint (\"Matmul: \", np.matmul(a,b))\r\n\r\na = [[1,0],[0,1]] \r\nb = [1,2] \r\nprint (\"matmul array n vector: \", np.matmul(a,b)) \r\nprint (\"matmul vector n array: \", np.matmul(b,a))\r\n\r\na = np.arange(8).reshape(2,2,2) \r\nb = np.arange(4).reshape(2,2) \r\nprint (\"matmul with broadcast: \", np.matmul(a,b))\r\n\r\n# TODO: work on determinant, inv and solve methods in numpy", "meta": {"hexsha": "d4d02a07c2de1a75b26ad7069ef614979f002166", "size": 1267, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpu-tuto/numpy_rev_lin_alg.py", "max_stars_repo_name": "sourabhyadav/100-days-0f-DL-DevOps", "max_stars_repo_head_hexsha": "51bd1636323d117c7e2e11b62941efac5d4f2d74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpu-tuto/numpy_rev_lin_alg.py", "max_issues_repo_name": "sourabhyadav/100-days-0f-DL-DevOps", "max_issues_repo_head_hexsha": "51bd1636323d117c7e2e11b62941efac5d4f2d74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpu-tuto/numpy_rev_lin_alg.py", "max_forks_repo_name": "sourabhyadav/100-days-0f-DL-DevOps", "max_forks_repo_head_hexsha": "51bd1636323d117c7e2e11b62941efac5d4f2d74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1666666667, "max_line_length": 103, "alphanum_fraction": 0.5666929755, "include": true, "reason": "import numpy", "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.9343951625409307, "lm_q1q2_score": 0.8790693844706033}}
{"text": "1 EYE IDENTITY\r\nimport numpy\r\nprint(str(numpy.eye(*map(int,input().split()))).replace('1',' 1').replace('0',' 0'))\r\n\r\n2 ARRAYS\r\nimport numpy\r\ndef arrays(arr):\r\n    # complete this function\r\n    # use numpy.array\r\n    return(numpy.array(arr[::-1], float))\r\n\r\narr = input().strip().split(' ')\r\nresult = arrays(arr)\r\nprint(result)\r\n\r\n3 SHAPE AND RESHAPE\r\nimport numpy\r\na=numpy.array(list(map(int,input().split())))\r\na.shape=(3,3)\r\nprint(a)\r\n\r\n4 TRAMPOSE AND FLATTEN\r\nimport numpy\r\nN, M = map(int, input().split())\r\narray = numpy.array([input().strip().split() for _ in range(N)], int)\r\nprint (array.transpose())\r\nprint (array.flatten())\r\n\r\n5 CONCATENATE\r\nimport numpy\r\n\r\na, b, c = map(int,input().split())\r\narray_1 = numpy.array([input().split() for _ in range(a)],int)\r\narray_2 = numpy.array([input().split() for _ in range(b)],int)\r\nprint(numpy.concatenate((array_1, array_2), axis = 0))\r\n\r\n6 ZERO AND ONES\r\nimport numpy\r\nx= list(map(int,input().split()))\r\nprint(numpy.zeros(x,int), numpy.ones(x,int), sep='\\n')\r\n\r\n7 ARRAY MATH\r\nimport numpy\r\nN, M = map(int, input().split())\r\nA, B = (numpy.array([input().split() for _ in range(N)], dtype=int) for _ in range(2))\r\nprint(A+B, A-B, A*B, A//B, A%B, A**B, sep='\\n')\r\n\r\n8 FLOOR, CEIL AND RINT\r\nimport numpy\r\nnumpy.set_printoptions(sign=' ')\r\nA = numpy.array(input().split(),float)\r\nprint(numpy.floor(A))\r\nprint(numpy.ceil(A))\r\nprint(numpy.rint(A))\r\n\r\n9 SUM AND PROD\r\nimport numpy\r\nN, M = map(int, input().split())\r\nx = numpy.array([input().split() for _ in range(N)],int)\r\nprint(numpy.prod(numpy.sum(x, axis=0), axis=0))\r\n\r\n10 MIN AND MAX\r\nimport numpy\r\nN, M = map(int, input().split())\r\nprint(numpy.array([input().split() for _ in range(int(N))], int).min(1).max())\r\n\r\n11 MEAN, VAR AND STD\r\nimport numpy\r\nN,M = map(int,input().split())\r\nx = []\r\nfor i in range(N):\r\n    y = list(map(int,input().split()))\r\n    x.append(y)\r\n\r\nx= numpy.array(x)\r\nnumpy.set_printoptions(legacy='1.13')\r\nprint (numpy.mean(x, axis = 1))\r\nprint (numpy.var(x, axis = 0))\r\nprint (numpy.std(x))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n12 DOT AND CROSS\r\nimport numpy\r\n\r\nN = int(input())\r\nA = numpy.array([input().split() for _ in range(N)], int)\r\nB = numpy.array([input().split() for _ in range(N)], int)\r\nprint(numpy.dot(A, B))\r\n\r\n13 INNER AND OUTER\r\nimport numpy\r\nA = numpy.array(input().split(), int)\r\nB = numpy.array(input().split(), int)\r\nprint(numpy.inner(A,B), numpy.outer(A,B), sep='\\n')\r\n\r\n14 POLYNOMIALS\r\nimport numpy\r\nP = [float(x) for x in input().split()]\r\nx = float(input())\r\nprint(numpy.polyval(P, x))\r\n\r\n15 LINEAR ALGEBRA\r\nimport numpy\r\nprint(round(numpy.linalg.det(numpy.array([list(map(float,input().split())) for _ in range(int(input()))])),2))\r\n", "meta": {"hexsha": "544e48c0a5b664641430f0cf6fbceb47881626c2", "size": 2674, "ext": "py", "lang": "Python", "max_stars_repo_path": "Problems/NUMPY.py", "max_stars_repo_name": "eleonoraserra/ADM-HW1", "max_stars_repo_head_hexsha": "bd01cc24277815ad40427b59da745d63c4fe3e86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Problems/NUMPY.py", "max_issues_repo_name": "eleonoraserra/ADM-HW1", "max_issues_repo_head_hexsha": "bd01cc24277815ad40427b59da745d63c4fe3e86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Problems/NUMPY.py", "max_forks_repo_name": "eleonoraserra/ADM-HW1", "max_forks_repo_head_hexsha": "bd01cc24277815ad40427b59da745d63c4fe3e86", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6610169492, "max_line_length": 111, "alphanum_fraction": 0.6271503366, "include": true, "reason": "import numpy", "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.9294404003923944, "lm_q1q2_score": 0.8790659140845924}}
{"text": "#https://www.geeksforgeeks.org/python-binomial-distribution/\n#https://www.hackerrank.com/challenges/s10-binomial-distribution-1/tutorial\n\nimport sys\nimport scipy.stats\nimport matplotlib.pyplot as plt\n\n\ndef fact(x,memo={}):\n    # factorial of x! = x * (x-1) * (x-2) * ..... 2 * 1\n    if x in memo:\n        return memo[x]\n    if x <= 1:\n        return 1\n    memo[x] = x*fact(x-1,memo)\n    return memo[x]\n    \ndef bin_coe(n,x):\n    # binomial coefficient = n! / x!(n-x)!\n    return fact(n) / (fact(x) * fact(n-x))\n\ndef pmf(n,x,p):\n    # probability mass function for the binomial distribution\n    return bin_coe(n,x) * (p**x) * ((1-p)**(n-x))\n\nn = 10\nx = list(range(1,11))\np = 0.5\nq = 0.5\n\n# mean = np; variance = np(1-p)\nmean, variance = scipy.stats.binom.stats(n, p)\n\nprint(mean, variance)\n\n# p(x) = nCr (p^x) ((1-p)^n-r)\npx = [scipy.stats.binom.pmf(r, n, p) for r in x]\n\nprint(x)\nprint(px)\n\nplt.bar(x, px)\n\nplt.title('A coin is tossed 10 times')\nplt.xlabel(\"The value of X\")\nplt.ylabel(\"Probability of x\")\n\n\n# plt.hist(px)\nplt.show()\nplt.savefig('binomial.png')\n\n#Two  lines to make our compiler able to draw:\n# plt.savefig(sys.stdout.buffer)\n# sys.stdout.flush()\n\n# print(px[4])\n# print(sum(px[4:]))\n# print(sum(px[:5]))", "meta": {"hexsha": "b59a85e0679ef5e789c65a32dbb7ea8739c59404", "size": 1221, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tutorials/Statistics/Binomial_Distribution2.py", "max_stars_repo_name": "vinayvinu500/Hackerrank", "max_stars_repo_head_hexsha": "e185ae9d3c7dc5cd661761142e436f5df6a3f0f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tutorials/Statistics/Binomial_Distribution2.py", "max_issues_repo_name": "vinayvinu500/Hackerrank", "max_issues_repo_head_hexsha": "e185ae9d3c7dc5cd661761142e436f5df6a3f0f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tutorials/Statistics/Binomial_Distribution2.py", "max_forks_repo_name": "vinayvinu500/Hackerrank", "max_forks_repo_head_hexsha": "e185ae9d3c7dc5cd661761142e436f5df6a3f0f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6949152542, "max_line_length": 75, "alphanum_fraction": 0.6191646192, "include": true, "reason": "import scipy", "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561694652216, "lm_q2_score": 0.9073122219871936, "lm_q1q2_score": 0.8790550439034912}}
{"text": "\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import Slider, Button\nimport matplotlib.patches as patches\n\np = 1\t\t\t\t\t\t\t\t\t\t\t\t\t\t#population\ni = 0.01*p  \t\t\t\t\t\t\t\t\t\t\t\t#infected\ns = p-i\t\t\t\t\t\t\t\t\t\t\t\t\t\t#susceptible\nr = 0\t\t\t\t\t\t\t\t\t\t\t\t\t\t#recovered/removed\n\na = 3.2\t\t\t\t\t\t\t\t\t\t\t\t\t\t#transmission parameter\nb = 0.23\t\t\t\t\t\t\t\t\t\t\t\t\t#recovery parameter\n\ninitialTime = 0\ndeltaTime = 0.001\t\t\t\t\t\t\t\t\t\t\t#smaller the delta, better the approximation to a real derivative\nmaxTime = 10000\t\t\t\t\t\t\t\t\t\t\t\t#more number of points, better is the curve generated\n\ndef sPrime(oldS, oldI, transmissionRate):\t\t\t\t\t#differential equations being expressed as functions to\n\treturn -1*((transmissionRate*oldS*oldI)/p)\t\t\t\t#calculate rate of change between time intervals of the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#different quantities i.e susceptible, infected and recovered/removed\ndef iPrime(oldS, oldI, transmissionRate, recoveryRate):\t\t\t\t\n\treturn (((transmissionRate*oldS)/p)-recoveryRate)*oldI\n\ndef rPrime(oldI, recoveryRate):\n\treturn recoveryRate*oldI\n\nmaxTimeInitial = maxTime\n\ndef genData(transRate, recovRate, maxT):\n\tglobal a, b, maxTimeInitial\n\ta = transRate\n\tb = recovRate\n\tmaxTimeInitial = maxT\n\n\tsInitial = s\n\tiInitial = i\n\trInitial = r\n\n\ttime = np.arange(maxTimeInitial+1)\n\tsVals = np.zeros(maxTimeInitial+1)\n\tiVals = np.zeros(maxTimeInitial+1)\n\trVals = np.zeros(maxTimeInitial+1)\n\n\tfor t in range(initialTime, maxTimeInitial+1):\t\t\t\t#generating the data through a loop\n\t\tsVals[t] = sInitial\n\t\tiVals[t] = iInitial\n\t\trVals[t] = rInitial\n\n\t\tnewDeltas = (sPrime(sInitial, iInitial, transmissionRate=a), iPrime(sInitial, iInitial, transmissionRate=a, recoveryRate=b), rPrime(iInitial, recoveryRate=b))\n\t\tsInitial += newDeltas[0]*deltaTime\n\t\tiInitial += newDeltas[1]*deltaTime\n\t\trInitial += newDeltas[2]*deltaTime\n\n\t\tif sInitial < 0 or iInitial < 0 or rInitial < 0:\t\t#as soon as any of these value become negative, the data generated becomes invalid\n\t\t\tbreak\t\t\t\t\t\t\t\t\t\t\t\t#according to the SIR model, we assume all values of S, I and R are always positive.\n\n\treturn (time, sVals, iVals, rVals)\n\nfig, ax = plt.subplots()\nplt.subplots_adjust(bottom=0.4, top=0.94)\n\nplt.title('SIR epidemiology curves for a disease')\n\nplt.xlim(0, maxTime+1)\nplt.ylim(0, p*1.4)\n\nplt.xlabel('Time (t)')\nplt.ylabel('Population (p)')\n\ninitialData = genData(a, b, maxTimeInitial)\n\nsusceptible, = ax.plot(initialData[0], initialData[1], label='Susceptible', color='b')\ninfected, = ax.plot(initialData[0], initialData[2], label='Infected', color='r')\nrecovered, = ax.plot(initialData[0], initialData[3], label='Recovered/Removed', color='g')\n\nplt.legend()\n\ntransmissionAxes = plt.axes([0.125, 0.25, 0.775, 0.03], facecolor='white')\nrecoveryAxes = plt.axes([0.125, 0.2, 0.775, 0.03], facecolor='white')\ntimeAxes = plt.axes([0.125, 0.15, 0.775, 0.03], facecolor='white')\n\ntransmissionSlider = Slider(transmissionAxes, 'Transmission parameter', 0, 10, valinit=a, valstep=0.01)\nrecoverySlider = Slider(recoveryAxes, 'Recovery parameter', 0, 10, valinit=b, valstep=0.01)\ntimeSlider = Slider(timeAxes, 'Max time', 0, 100000, valinit=maxTime, valstep=1, valfmt=\"%i\")\n\ndef updateTransmission(newVal):\n\tnewData = genData(newVal, b, maxTimeInitial)\n\n\tsusceptible.set_ydata(newData[1])\n\tinfected.set_ydata(newData[2])\n\trecovered.set_ydata(newData[3])\n\n\tr_o.set_text(r'$R_O$={:.2f}'.format(a/b))\n\n\tfig.canvas.draw_idle()\n\ndef updateRecovery(newVal):\n\tnewData = genData(a, newVal, maxTimeInitial)\n\n\tsusceptible.set_ydata(newData[1])\n\tinfected.set_ydata(newData[2])\n\trecovered.set_ydata(newData[3])\n\n\tr_o.set_text(r'$R_O$={:.2f}'.format(a/b))\n\n\tfig.canvas.draw_idle()\n\ndef updateMaxTime(newVal):\n\tglobal susceptible, infected, recovered\n\n\tnewData = genData(a, b, int(newVal.item()))\n\n\tdel ax.lines[:3]\n\n\tsusceptible, = ax.plot(newData[0], newData[1], label='Susceptible', color='b')\n\tinfected, = ax.plot(newData[0], newData[2], label='Infected', color='r')\n\trecovered, = ax.plot(newData[0], newData[3], label='Recovered/Removed', color='g')\n\ntransmissionSlider.on_changed(updateTransmission)\nrecoverySlider.on_changed(updateRecovery)\ntimeSlider.on_changed(updateMaxTime)\n\nresetAxes = plt.axes([0.8, 0.025, 0.1, 0.05])\nresetButton = Button(resetAxes, 'Reset', color='white')\n\nr_o = plt.text(0.1, 1.5, r'$R_O$={:.2f}'.format(a/b), fontsize=12)\n\ndef reset(event):\n    transmissionSlider.reset()\n    recoverySlider.reset()\n    timeSlider.reset()\n\nresetButton.on_clicked(reset)\n\nplt.show()\n", "meta": {"hexsha": "6fe2119ae360a41e07a0b61d0fa33f5d606d8ce9", "size": 4411, "ext": "py", "lang": "Python", "max_stars_repo_path": "SIRmodel_cl_op.py", "max_stars_repo_name": "prithvidiamond1/SIR-model-based-epidemiology-curve-generator-in-Matplotlib", "max_stars_repo_head_hexsha": "8949c7ac058037fae9745ec3572b2d81a8c416c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2020-03-31T14:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-04T21:27:49.000Z", "max_issues_repo_path": "SIRmodel_cl_op.py", "max_issues_repo_name": "prithvidiamond1/SIR-model-based-epidemiology-curve-generator-in-Matplotlib", "max_issues_repo_head_hexsha": "8949c7ac058037fae9745ec3572b2d81a8c416c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SIRmodel_cl_op.py", "max_forks_repo_name": "prithvidiamond1/SIR-model-based-epidemiology-curve-generator-in-Matplotlib", "max_forks_repo_head_hexsha": "8949c7ac058037fae9745ec3572b2d81a8c416c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-03-31T16:24:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-07T01:01:56.000Z", "avg_line_length": 32.197080292, "max_line_length": 160, "alphanum_fraction": 0.7129902516, "include": true, "reason": "import numpy", "num_tokens": 1324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456935, "lm_q2_score": 0.9207896764343916, "lm_q1q2_score": 0.879029488460327}}
{"text": "from __future__ import print_function\nimport numpy as np\n\n\ndef demo_gauss_sedel_method():\n    ITERATION_LIMIT = 1000\n    # initialize the matrix\n    A = np.array([[10., -1., 2., 0.],\n                  [-1., 11., -1., 3.],\n                  [2., -1., 10., -1.],\n                  [0.0, 3., -1., 8.]])\n    # initialize the RHS vector\n    b = np.array([6., 25., -11., 15.])\n\n    # prints the system\n    print(\"System:\")\n    for i in range(A.shape[0]):\n        row = [\"{}*x{}\".format(A[i, j], j + 1) for j in range(A.shape[1])]\n        print(\" + \".join(row), \"=\", b[i])\n    print()\n\n    x = np.zeros_like(b)\n    for it_count in range(ITERATION_LIMIT):\n        print(\"Current solution:\", x)\n        x_new = np.zeros_like(x)\n\n        for i in range(A.shape[0]):\n            s1 = np.dot(A[i, :i], x_new[:i])\n            s2 = np.dot(A[i, i + 1:], x[i + 1:])\n            x_new[i] = (b[i] - s1 - s2) / A[i, i]\n\n        if np.allclose(x, x_new, rtol=1e-8):\n            break\n\n        x = x_new\n\n    print(\"Solution:\")\n    print(x)\n    error = np.dot(A, x) - b\n    print(\"Error:\")\n    print(error)\n\n\ndef demo_jacobi_method():\n    ITERATION_LIMIT = 1000\n    # initialize the matrix\n    A = np.array([[10., -1., 2., 0.],\n                  [-1., 11., -1., 3.],\n                  [2., -1., 10., -1.],\n                  [0.0, 3., -1., 8.]])\n    # initialize the RHS vector\n    b = np.array([6., 25., -11., 15.])\n\n    # prints the system\n    print(\"System:\")\n    for i in range(A.shape[0]):\n        row = [\"{}*x{}\".format(A[i, j], j + 1) for j in range(A.shape[1])]\n        print(\" + \".join(row), \"=\", b[i])\n    print()\n\n    x = np.zeros_like(b)\n    for it_count in range(ITERATION_LIMIT):\n        print(\"Current solution:\", x)\n        x_new = np.zeros_like(x)\n\n        for i in range(A.shape[0]):\n            s1 = np.dot(A[i, :i], x[:i])\n            s2 = np.dot(A[i, i + 1:], x[i + 1:])\n            x_new[i] = (b[i] - s1 - s2) / A[i, i]\n\n        if np.allclose(x, x_new, atol=1e-10):\n            break\n\n        x = x_new\n\n    print(\"Solution:\")\n    print(x)\n\n    error = np.dot(A, x) - b\n    print(\"Error:\")\n    print(error)\n\n\nif __name__ == '__main__':\n    demo_gauss_sedel_method()\n    demo_jacobi_method()\n", "meta": {"hexsha": "a272a3ab9838bf6fb441a1a8076213def0cacbd6", "size": 2192, "ext": "py", "lang": "Python", "max_stars_repo_path": "ref_src/2014-Heat-Kernel/src_python/demo_files/yche_numerical_linear_algebra_exp.py", "max_stars_repo_name": "GraphProcessor/LocalityBasedGraphAlgo", "max_stars_repo_head_hexsha": "de6e48498eb43a106312f14149a3060501b8a49c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ref_src/2014-Heat-Kernel/src_python/demo_files/yche_numerical_linear_algebra_exp.py", "max_issues_repo_name": "GraphProcessor/LocalityBasedGraphAlgo", "max_issues_repo_head_hexsha": "de6e48498eb43a106312f14149a3060501b8a49c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ref_src/2014-Heat-Kernel/src_python/demo_files/yche_numerical_linear_algebra_exp.py", "max_forks_repo_name": "GraphProcessor/LocalityBasedGraphAlgo", "max_forks_repo_head_hexsha": "de6e48498eb43a106312f14149a3060501b8a49c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-06T14:03:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-06T14:03:59.000Z", "avg_line_length": 25.1954022989, "max_line_length": 74, "alphanum_fraction": 0.4671532847, "include": true, "reason": "import numpy", "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102542943773, "lm_q2_score": 0.9086178901278738, "lm_q1q2_score": 0.8790062641450269}}
{"text": "import numpy as np\nfrom scipy.signal import get_window\nfrom scipy.fftpack import fft, fftshift\nimport math\nimport matplotlib.pyplot as plt\neps = np.finfo(float).eps\n\n\"\"\" \nA4-Part-1: Extracting the main lobe of the spectrum of a window\n\nWrite a function that extracts the main lobe of the magnitude spectrum of a window given a window \ntype and its length (M). The function should return the samples corresponding to the main lobe in \ndecibels (dB).\n\nTo compute the spectrum, take the FFT size (N) to be 8 times the window length (N = 8*M) (For this \npart, N need not be a power of 2). \n\nThe input arguments to the function are the window type (window) and the length of the window (M). \nThe function should return a numpy array containing the samples corresponding to the main lobe of \nthe window. \n\nIn the returned numpy array you should include the samples corresponding to both the local minimas\nacross the main lobe. \n\nThe possible window types that you can expect as input are rectangular ('boxcar'), 'hamming' or\n'blackmanharris'.\n\nNOTE: You can approach this question in two ways: 1) You can write code to find the indices of the \nlocal minimas across the main lobe. 2) You can manually note down the indices of these local minimas \nby plotting and a visual inspection of the spectrum of the window. If done manually, the indices \nhave to be obtained for each possible window types separately (as they differ across different \nwindow types).\n\nTip: log10(0) is not well defined, so its a common practice to add a small value such as eps = 1e-16 \nto the magnitude spectrum before computing it in dB. This is optional and will not affect your answers. \nIf you find it difficult to concatenate the two halves of the main lobe, you can first center the \nspectrum using fftshift() and then compute the indexes of the minimas around the main lobe.\n\n\nTest case 1: If you run your code using window = 'blackmanharris' and M = 100, the output numpy \narray should contain 65 samples.\n\nTest case 2: If you run your code using window = 'boxcar' and M = 120, the output numpy array \nshould contain 17 samples.\n\nTest case 3: If you run your code using window = 'hamming' and M = 256, the output numpy array \nshould contain 33 samples.\n\n\"\"\"\ndef extractMainLobe(window, M):\n    \"\"\"\n    Input:\n            window (string): Window type to be used (Either rectangular ('boxcar'), 'hamming' or '\n                blackmanharris')\n            M (integer): length of the window to be used\n    Output:\n            The function should return a numpy array containing the main lobe of the magnitude \n            spectrum of the window in decibels (dB).\n    \"\"\"\n\n    w = get_window(window, M)         # get the window \n    \n    ### Your code here\n    hM1 = int(np.floor((M+1)/2))\n    hM2 = int(np.floor(M/2))\n    N = 8 * M\n    hN1 = int(np.floor((N+1)/2))\n    hN2 = int(np.floor(N/2))\n    fftbuffer = np.zeros(N)\n    fftbuffer[:hM1] = w[hM2:]\n    fftbuffer[N-hM2:] = w[:hM1]\n    W = fft(fftbuffer)\n    mW = np.abs(W)\n    mW[mW < eps] = eps\n    mW = 20 * np.log10(mW)\n    for i in range(1, N):\n        if mW[i] > mW[i-1]:\n            left_local_minimum = i-1\n            break\n\n    right_local_minimum = N - left_local_minimum\n\n    mW_left = mW[right_local_minimum:]\n    mW_right = mW[:left_local_minimum+1]\n\n    mW_lobe = np.append(mW_left, mW_right)\n\n    return mW_lobe\n    \n#mW_lobe = extractMainLobe('blackmanharris', 100)\n#print(mW_lobe.size)\n", "meta": {"hexsha": "c4da8dd6e0c56f026a903665ecbd7efcb669217c", "size": 3426, "ext": "py", "lang": "Python", "max_stars_repo_path": "A4/A4Part1.py", "max_stars_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_stars_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A4/A4Part1.py", "max_issues_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_issues_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A4/A4Part1.py", "max_forks_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_forks_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2391304348, "max_line_length": 104, "alphanum_fraction": 0.700525394, "include": true, "reason": "import numpy,from scipy", "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294984, "lm_q2_score": 0.9416541638911341, "lm_q1q2_score": 0.8789690099102055}}
{"text": "import math\n\nimport numpy as np\nfrom scipy.fftpack import fft, ifft\n\n\ndef my_fft(x):\n    assert x.ndim == 1\n    size = x.shape[0]\n    if size == 1:\n        return x\n    if size % 2 != 0:\n        raise ValueError(\"size of x must be a power of 2\")\n    odd = my_fft(x[1::2])\n    even = my_fft(x[0::2])\n    coe = np.exp(-2j * math.pi * np.arange(size)/size)\n    mid = int(size/2)\n    a = even+coe[:mid]*odd\n    b = even+coe[mid:]*odd\n    return np.concatenate([a,b])\n\ndef my_ifft(x):\n    assert x.ndim == 1\n    size = x.shape[0]\n    if size == 1:\n        return x\n    if size % 2 != 0:\n        raise ValueError(\"size of x must be a power of 2\")\n    odd = my_ifft(x[1::2])\n    even = my_ifft(x[0::2])\n    coe = np.exp(2j * math.pi * np.arange(size)/size)\n    mid = int(size/2)\n    a = even+coe[:mid]*odd\n    b = even+coe[mid:]*odd\n    return np.concatenate([a,b])/2\n\nif __name__ == '__main__':\n    x = np.array([1, 2, 3, 5,6,9,10,11])\n    fft1 = fft(x)\n    ifft1 = ifft(fft1)\n    print(\"fft1\", fft1)\n    print(\"ifft1\", ifft1)\n\n    my_fft1 = my_fft(x)\n    my_ifft1 = my_ifft(my_fft1)\n    print(\"my_fft1\", my_fft1)\n    print(\"my_ifft1\", my_ifft1)\n", "meta": {"hexsha": "b39b37255e9b419ff6ee7dc4a04915ba78b98eeb", "size": 1140, "ext": "py", "lang": "Python", "max_stars_repo_path": "01-dft/fft.py", "max_stars_repo_name": "xiaoxiaoxiang-Wang/05-math", "max_stars_repo_head_hexsha": "286c2df6972d8a331eab70cddbc04df26f42583d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "01-dft/fft.py", "max_issues_repo_name": "xiaoxiaoxiang-Wang/05-math", "max_issues_repo_head_hexsha": "286c2df6972d8a331eab70cddbc04df26f42583d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01-dft/fft.py", "max_forks_repo_name": "xiaoxiaoxiang-Wang/05-math", "max_forks_repo_head_hexsha": "286c2df6972d8a331eab70cddbc04df26f42583d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.75, "max_line_length": 58, "alphanum_fraction": 0.5587719298, "include": true, "reason": "import numpy,from scipy", "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347860767304, "lm_q2_score": 0.9019206771886166, "lm_q1q2_score": 0.8788628821344694}}
{"text": "import numpy as np\n\n\ndef check_invertible_array(X: np.array) -> bool:\n    \"\"\"\n    Check if the input array is invertible based on its rank\n    Parameters\n    ----------\n    X:  np.array with (n_samples, n_features) shape\n\n    Returns\n    -------\n    boolean, True if X is invertible, False if NOT.\n    \"\"\"\n    assert len(X.shape) == 2  # Has to be 2-D array\n    assert np.divide(*X.shape) == 1  # Has to be a square array/matrix\n\n    n_rank_raw, _ = X.shape\n    n_rank_real = np.linalg.matrix_rank(X)\n\n    return True if int(n_rank_raw) == int(n_rank_real) else False\n\ndef feature_norm(X: np.array, axis: int = 0) -> np.array:\n    \"\"\"\n    Feature normalization.\n    X_ = (X - mean(X)) / stdev(X)\n\n    Parameters\n    ----------\n    X:  np.array with (n_samples, n_features) shape\n    axis: int, which axis to perform the normalization too (features' axis).\n\n    Returns\n    -------\n    X_new:  np.array with (n_samples, n_features) shape.\n            The normalized X input based on its feature!\n    \"\"\"\n    X_new = (X - np.mean(X, axis=axis)) / np.std(X, axis=axis)\n    return X_new\n\ndef normal_eq(X: np.array, y: np.array) -> np.array:\n    \"\"\"\n    Calculating normal equation to solve linear regression.\n\n    Parameters\n    ----------\n    X: np.array with (n_samples, n_features) shape\n    y: np.array with (n_samples,) shape\n\n    Returns\n    -------\n    theta:  np.array with (n_features,).\n            The trained parameters for the linear regression.\n    \"\"\"\n    A = np.dot(X.T, X)\n    theta = np.dot(np.linalg.pinv(A), np.dot(X.T, y))  # inv(A) dot X.T dot y\n    return theta\n", "meta": {"hexsha": "d6a00f4c77d24175ad4d1bf9f7e5a0e697e9e16d", "size": 1581, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/linear/_math.py", "max_stars_repo_name": "abrosua/ml-with-numpy", "max_stars_repo_head_hexsha": "0201c4f6a311023add46a67c208e0deb9f25aa50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/linear/_math.py", "max_issues_repo_name": "abrosua/ml-with-numpy", "max_issues_repo_head_hexsha": "0201c4f6a311023add46a67c208e0deb9f25aa50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/linear/_math.py", "max_forks_repo_name": "abrosua/ml-with-numpy", "max_forks_repo_head_hexsha": "0201c4f6a311023add46a67c208e0deb9f25aa50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2586206897, "max_line_length": 77, "alphanum_fraction": 0.6046805819, "include": true, "reason": "import numpy", "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347875615795, "lm_q2_score": 0.9019206686206199, "lm_q1q2_score": 0.8788628751247315}}
{"text": "### LINEAR ALGEBRA ###\nimport numpy as np\n# from numpy.linalg import norm, det\n# help(np.linalg)\n\n# M = np.array([\n#     [1, 2],\n#     [3, 4]\n# ])\n# v = np.array([1, -1])\n\n# # print(v.T) # Calcular transpuesta no funciona al ser vector (matriz 1D)\n\n# u = np.dot(M, v)\n\n# # Para hacer comparaciones entre arrays de punto flotante se puede usar:\n# # np.allclose: comprueba si todos los elementos de los arrays son iguales dentro de una tolerancia, \n# # np.isclose: compara elemento a elemento y devuelve un array de valores True y False\n# # np.allclose(u, v)\n# # np.isclose(0.0, 1e-8, atol=1e-10)\n\n# # u = M @ v # Hace operaciones entre matrices\n# # print(u)\n\n# mat = np.array([[1, 5, 8, 5],\n#                 [0, 6, 4, 2],\n#                 [9, 3, 1, 6]])\n\n# vec1 = np.array([5, 6, 2])\n\n# print(vec1 @ mat)\n\n## Exercise 1 ##\n# Hallar el producto de estas dos matrices y su determinante:\n\n# A = np.array([\n#     [1, 0, 0],\n#     [2, 1, 1],\n#     [-1, 0, 1]\n# ])\n# B = np.array([\n#     [2, 3, -1],\n#     [0, -2, 1],\n#     [0, 0, 3]\n# ])\n\n# C = A @ B\n# determ = det(C)\n\n## Exercise 2 ##\n# 2- Resolver el siguiente sistema:\n\n# $$ \\begin{pmatrix} 2 & 0 & 0 \\\\ -1 & 1 & 0 \\\\ 3 & 2 & -1 \\end{pmatrix} \\begin{pmatrix} 1 & 1 & 1 \\\\ 0 & 1 & 2 \\\\ 0 & 0 & 1 \\end{pmatrix} \\begin{pmatrix} x \\\\ y \\\\ z \\end{pmatrix} = \\begin{pmatrix} -1 \\\\ 3 \\\\ 0 \\end{pmatrix} $$\n# M = (np.array([[2, 0, 0],\n#                         [-1, 1, 0],\n#                         [3, 2, -1]])\n#      @\n#         np.array([[1, 1, 1],\n#                         [0, 1, 2],\n#                         [0, 0, 1]]))\n# res = np.array([-1, 3, 0])\n\n# x = np.linalg.solve(M,res)\n\n# print(np.allclose(M @ x, res))\n\n## Exercise 3 ##\n# 3- Hallar la inversa de la matriz 𝐻 y comprobar que 𝐻𝐻−1=𝐼 (recuerda la función np.eye)\n# A = np.arange(1, 37).reshape(6,6)\n# A[1, 1::2] = 0\n# A[3, ::2] = 1\n# A[4, :] += 30\n# B = (2 ** np.arange(36)).reshape((6,6))\n# H = A + B\n# print(H)\n\n# print(np.linalg.det(H))\n\n# Hinv = np.linalg.inv(H)\n\n# np.isclose(np.dot(Hinv, H), np.eye(6))\n\n# np.set_printoptions(precision=3)\n# print(np.dot(Hinv, H))\n\n#¡No funciona! Y no solo eso sino que los resultados varían de un ordenador a otro.\n\n## Exercise 4 ##\n# print(np.linalg.cond(H))\n# La matriz está mal condicionada\n\n## Exercise 5 ## # Autovalores y autovectores #\nA = np.array([\n    [1, 0, 0],\n    [2, 1, 1],\n    [-1, 0, 1]\n])\n\neigen = np.linalg.eig(A)\n", "meta": {"hexsha": "1aa1a0d1d6e0cf8e1de6f27b0113590d9f960e0e", "size": 2380, "ext": "py", "lang": "Python", "max_stars_repo_path": "MyScripts/014-NumPy.py", "max_stars_repo_name": "diegoomataix/Curso_AeroPython", "max_stars_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MyScripts/014-NumPy.py", "max_issues_repo_name": "diegoomataix/Curso_AeroPython", "max_issues_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MyScripts/014-NumPy.py", "max_forks_repo_name": "diegoomataix/Curso_AeroPython", "max_forks_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8, "max_line_length": 228, "alphanum_fraction": 0.5214285714, "include": true, "reason": "import numpy,from numpy", "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.9219218370002789, "lm_q1q2_score": 0.8788450797575548}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul  8 15:58:48 2021\n\n@author: alessandro\n\"\"\"\n\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sympy as sym\nfrom sympy.utilities.lambdify import lambdify\nfrom scipy.optimize import fsolve\n\ndef f(x): return 2 * math.cos(x) + x * (7 - x) - math.tan((3 / 2) * x)\n\nzero1 = fsolve(f, -1)\nzero2 = fsolve(f, 0)\nzero3 = fsolve(f, 1)\n\nzeri = np.array([zero1, zero2, zero3])\n\nx = sym.symbols('x')\ngx = sym.tan((3 / 2) * x) - 2 * sym.cos(x) - x * (6 - x)\ndgx = sym.diff(gx, x, 1)\n\ng = lambdify(x, gx, np)\ndg = lambdify(x, dgx, np)\n\nxx = np.linspace(-1, 1, 100)\ny = g(xx)\n\nplt.ylim((-3, 3))\nplt.plot(zeri, g(zeri), 'o')\nplt.plot(zeri, dg(zeri), 'o')\nplt.plot(xx, xx, label=\"y = x\")\nplt.plot(xx, y, label=\"g(x)\")\nplt.plot(xx, dg(xx), label=\"g'(x)\")\nplt.legend()\nplt.show()\n\n\n# --------\n\ngx = (sym.tan((3 / 2) * x) - 2 * sym.cos(x)) / (7 - x)\ndgx = sym.diff(gx, x, 1)\n\ng = lambdify(x, gx, np)\ndg = lambdify(x, dgx, np)\n\nxx = np.linspace(-1, 1, 100)\ny = g(xx)\n\nplt.ylim((-3, 3))\nplt.plot(zeri, g(zeri), 'o')\nplt.plot(zeri, dg(zeri), 'o')\nplt.plot(xx, xx, label=\"y = x\")\nplt.plot(xx, y, label=\"g(x)\")\nplt.plot(xx, dg(xx), label=\"g'(x)\")\nplt.legend()\nplt.show()\n\n# c)\ndef puntofisso(g, x0, tol, nmax):\n    x = g(x0)\n    it, xk = 1, [x]\n    while it < nmax and abs(x - x0) >= tol * abs(x):\n        x0 = x\n        x = g(x)\n        xk.append(x)\n        it += 1\n    return x, it, xk\n\n# d)\nx, it, xk = puntofisso(g, 0, 1e-7, 500)\nprint(x)\nplt.plot(np.arange(1, it + 1), xk)\n\n# e)\n\ndef stima_ordine(xk):\n    k = len(xk) - 4\n    n = np.log(np.abs(xk[k + 3] - xk[k + 2]) / np.abs(xk[k + 2] - xk[k + 1]))\n    d = np.log(np.abs(xk[k + 2] - xk[k + 1]) / np.abs(xk[k + 1] - xk[k]))\n    return n / d\n\nordine = stima_ordine(xk)\nprint(ordine)\n    \n    \n", "meta": {"hexsha": "65eec29d785610404529a3ee63446106c7b1ae80", "size": 1809, "ext": "py", "lang": "Python", "max_stars_repo_path": "esercitazioni/luglio_21_2020.py", "max_stars_repo_name": "alemazzo/metodi_numerici", "max_stars_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-07-08T10:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T09:56:37.000Z", "max_issues_repo_path": "esercitazioni/luglio_21_2020.py", "max_issues_repo_name": "alemazzo/metodi_numerici", "max_issues_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "esercitazioni/luglio_21_2020.py", "max_forks_repo_name": "alemazzo/metodi_numerici", "max_forks_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6630434783, "max_line_length": 77, "alphanum_fraction": 0.5450525152, "include": true, "reason": "import numpy,from scipy,import sympy,from sympy", "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846919, "lm_q2_score": 0.9324533055754922, "lm_q1q2_score": 0.8788435062038594}}
{"text": "# author: Krzysztof Sopyła (krzysztofsopyla@gmail.com)\n# Twitter: ksopyla\n# Blog: http://ksopyla.com\n\n# If you want to use this material in your own trainning please let me know.\nimport numpy as np\n\n# We will add the vector v to each row of the matrix x,\n# storing the result in the matrix y\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\nv = np.array([1, 0, 1])\ny = np.empty_like(x)   # Create an empty matrix with the same shape as x\n\n# Add the vector v to each row of the matrix x with an explicit loop\nfor i in range(4):\n    y[i, :] = x[i, :] + v\n\n# Now y is the following\n# [[ 2  2  4]\n#  [ 5  5  7]\n#  [ 8  8 10]\n#  [11 11 13]]\nprint y\n\n\n# We will add the vector v to each row of the matrix x,\n# storing the result in the matrix y\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\nv = np.array([1, 0, 1])\nvv = np.tile(v, (4, 1))  # Stack 4 copies of v on top of each other\nprint vv                 # Prints \"[[1 0 1]\n                         #          [1 0 1]\n                         #          [1 0 1]\n                         #          [1 0 1]]\"\ny = x + vv  # Add x and vv elementwise\nprint y  # Prints \"[[ 2  2  4\n         #          [ 5  5  7]\n         #          [ 8  8 10]\n         #          [11 11 13]]\"\n         \n         \n         \n# We will add the vector v to each row of the matrix x,\n# storing the result in the matrix y\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\nv = np.array([1, 0, 1])\ny = x + v  # Add v to each row of x using broadcasting\nprint y  # Prints \"[[ 2  2  4]\n         #          [ 5  5  7]\n         #          [ 8  8 10]\n         #          [11 11 13]]\"\n         \n\n# Compute outer product of vectors\nv = np.array([1,2,3])  # v has shape (3,)\nw = np.array([4,5])    # w has shape (2,)\n# To compute an outer product, we first reshape v to be a column\n# vector of shape (3, 1); we can then broadcast it against w to yield\n# an output of shape (3, 2), which is the outer product of v and w:\n# [[ 4  5]\n#  [ 8 10]\n#  [12 15]]\nprint np.reshape(v, (3, 1)) * w\n\n# Add a vector to each row of a matrix\nx = np.array([[1,2,3], [4,5,6]])\n# x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),\n# giving the following matrix:\n# [[2 4 6]\n#  [5 7 9]]\nprint x + v\n\n# Add a vector to each column of a matrix\n# x has shape (2, 3) and w has shape (2,).\n# If we transpose x then it has shape (3, 2) and can be broadcast\n# against w to yield a result of shape (3, 2); transposing this result\n# yields the final result of shape (2, 3) which is the matrix x with\n# the vector w added to each column. Gives the following matrix:\n# [[ 5  6  7]\n#  [ 9 10 11]]\nprint (x.T + w).T\n# Another solution is to reshape w to be a row vector of shape (2, 1);\n# we can then broadcast it directly against x to produce the same\n# output.\nprint x + np.reshape(w, (2, 1))\n\n# Multiply a matrix by a constant:\n# x has shape (2, 3). Numpy treats scalars as arrays of shape ();\n# these can be broadcast together to shape (2, 3), producing the\n# following array:\n# [[ 2  4  6]\n#  [ 8 10 12]]\nprint x * 2", "meta": {"hexsha": "77c0fa6ded3f5b5d4fbefaf9f2ab95fa3512be04", "size": 3038, "ext": "py", "lang": "Python", "max_stars_repo_path": "4.Array_broadcasting.py", "max_stars_repo_name": "ksopyla/numpy-tutorial", "max_stars_repo_head_hexsha": "2a38cdba291568f8c837f41f2e12ed086b6ad8bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-07-09T03:07:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T13:11:33.000Z", "max_issues_repo_path": "4.Array_broadcasting.py", "max_issues_repo_name": "ksopyla/numpy-tutorial", "max_issues_repo_head_hexsha": "2a38cdba291568f8c837f41f2e12ed086b6ad8bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4.Array_broadcasting.py", "max_forks_repo_name": "ksopyla/numpy-tutorial", "max_forks_repo_head_hexsha": "2a38cdba291568f8c837f41f2e12ed086b6ad8bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-02-05T14:43:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-04T06:07:12.000Z", "avg_line_length": 32.6666666667, "max_line_length": 76, "alphanum_fraction": 0.5618828176, "include": true, "reason": "import numpy", "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067253, "lm_q2_score": 0.9284087990698189, "lm_q1q2_score": 0.8788286791827284}}
{"text": "#\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Chp003C003(object):\n    def __init__(self):\n        self.name = ''\n\n    def run(self):\n        print('一元高斯分布图像')\n        mu = 3.0\n        sigma = 0.5\n        x = np.linspace(-1.0, 6.0, 100)\n        y = self.gaussian(x, mu, sigma)\n        plt.rcParams['font.sans-serif'] = ['SimHei']\n        plt.rcParams['axes.unicode_minus'] = False\n        plt.title('一元高斯分布图像')\n        plt.plot(x, y, '-b')\n        plt.show()\n\n    def gaussian(self, x, mu, sigma):\n        v1 = 1 / (math.sqrt(2 * math.pi) * sigma)\n        v2 = (x-mu)*(x-mu) / (2 * sigma * sigma)\n        v3 = np.exp(-v2)\n        return v1 * v3\n\n\nif '__main__' == __name__:\n    app = Chp003C003()\n    app.run()", "meta": {"hexsha": "dacfa124f1048f55a31adaf93ac880a7a661ee2f", "size": 735, "ext": "py", "lang": "Python", "max_stars_repo_path": "app/pytorch/book/chp003/chp003_c003.py", "max_stars_repo_name": "yt7589/aqp", "max_stars_repo_head_hexsha": "c9c1c79facdea7ace73e2421e8a5868d87fb58dd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/pytorch/book/chp003/chp003_c003.py", "max_issues_repo_name": "yt7589/aqp", "max_issues_repo_head_hexsha": "c9c1c79facdea7ace73e2421e8a5868d87fb58dd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/pytorch/book/chp003/chp003_c003.py", "max_forks_repo_name": "yt7589/aqp", "max_forks_repo_head_hexsha": "c9c1c79facdea7ace73e2421e8a5868d87fb58dd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7096774194, "max_line_length": 52, "alphanum_fraction": 0.525170068, "include": true, "reason": "import numpy", "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773707979895381, "lm_q2_score": 0.8991213691605412, "lm_q1q2_score": 0.8787749700658842}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 25 16:35:07 2017\n\n@author: ratnadeepb\n@License: MIT\n\"\"\"\n\n'''\nLet c[0, 1] be the space of all continuous real valued functions in the interval\n[0, 1].\n\nLet f(x) = x + 1\nand g(x) = 2 + x^2\n\nInner Product is defined as the definite integral of f(x) * g(x) in the interval\n0 to 1.\n'''\n\nimport sympy\nimport numpy as np\nimport sys\n\n# Function dot product\ndef fn_dot(f, g, upper, lower):\n    try:\n        return sympy.N(sympy.integrate(f*g, (x, lower, upper)))\n    except:\n        sys.exit(\"Problem not formatted correctly\")\n        \n# Function norm\ndef fn_norm(f, upper, lower):\n    return np.sqrt(float(fn_dot(f, f, upper, lower)))\n\n# Angle between two functions\ndef fn_angle(f, g, upper, lower, op=\"radians\"):\n    if op not in [\"radians\", \"degrees\"]:\n        sys.exit(\"At this time we only handle radians and degrees\")\n    return np.arccos(float(fn_dot(f, g, upper, lower) / (fn_norm(f, upper, \n                           lower) * fn_norm(g, upper, lower))))\n\nif __name__ == \"__main__\":\n    upper = 1\n    lower = 0\n    \n    x = sympy.symbols('x')\n    \n    f = x + 1\n    g = x**2 + 2\n    \n    print(\"The inner product of the functions is: \", fn_dot(f, g, upper, lower))\n    print(\"The norm of f is: \", fn_norm(f, upper, lower))\n    print(\"The angle between the functions is: \", fn_angle(f, g, upper, lower))", "meta": {"hexsha": "917bda3b5cf2695e98b9813ce24fdeed809004b0", "size": 1372, "ext": "py", "lang": "Python", "max_stars_repo_path": "InnerProductSpaces/Examples/fnspace.py", "max_stars_repo_name": "ratnadeepb/LinearAlgebra", "max_stars_repo_head_hexsha": "0f4399c15ba12a3e7c0e2a796c77efa66520e462", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "InnerProductSpaces/Examples/fnspace.py", "max_issues_repo_name": "ratnadeepb/LinearAlgebra", "max_issues_repo_head_hexsha": "0f4399c15ba12a3e7c0e2a796c77efa66520e462", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "InnerProductSpaces/Examples/fnspace.py", "max_forks_repo_name": "ratnadeepb/LinearAlgebra", "max_forks_repo_head_hexsha": "0f4399c15ba12a3e7c0e2a796c77efa66520e462", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4074074074, "max_line_length": 80, "alphanum_fraction": 0.6129737609, "include": true, "reason": "import numpy,import sympy", "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122768904644, "lm_q2_score": 0.9173026528034425, "lm_q1q2_score": 0.8786954727446088}}
{"text": "\n## Worksheet 2\n    \nimport numpy as np\nimport scipy.linalg as la\n\n#### Answer Coding Question 1\n\ndef LU_decomposition(A):\n    \"\"\"Perform LU decomposition using the Doolittle factorisation.\"\"\"\n    \n    L = np.zeros_like(A)\n    U = np.zeros_like(A)\n    N = np.size(A, 0)\n    \n    for k in range(N):\n        L[k, k] = 1\n        U[k, k] = (A[k, k] - np.dot(L[k, :k], U[:k, k])) / L[k, k]\n        for j in range(k+1, N):\n            U[k, j] = (A[k, j] - np.dot(L[k, :k], U[:k, j])) / L[k, k]\n        for i in range(k+1, N):\n            L[i, k] = (A[i, k] - np.dot(L[i, :k], U[:k, k])) / U[k, k]\n    \n    return L, U\n\n#### Answer Coding Question 2\n\ndef ThomasAlgorithm(a, b, c, f):\n    \"\"\"Implement the Thomas algorithm to solve A x = f. \n    The vectors a, b, c are the sub-diagonal, diagonal and super-diagonal \n    vectors of the original matrix A.\"\"\"\n    \n    # Make copies of the input\n    aa = a.copy()\n    bb = b.copy()\n    cc = c.copy()\n    \n    x = np.zeros_like(f)\n    d = np.zeros_like(f)\n    d[:] = f[:]\n    N = len(f)\n    for k in range(1, N):\n        m = aa[k-1] / bb[k-1]\n        bb[k] -= m * cc[k-1]\n        d[k] -= m * d[k-1]\n    x[-1] = d[-1] / bb[-1]\n    for k in range(N-2, -1, -1):\n        x[k] = (d[k] - cc[k] * x[k+1]) / bb[k]\n    \n    return x\n\n#### Answer Coding Question 3\n\ndef Jacobi(A, b, tolerance = 1.e-10, MaxSteps = 100):\n    \"\"\"Solve the linear system A x = b using Jacobi's method, \n    starting from the trivial initial guess.\"\"\"\n    \n    x = np.zeros_like(b)\n    \n    Anorm = A.copy()\n    bnorm = b.copy()\n    n = len(b)\n    \n    for i in range(n):\n        bnorm[i] /= A[i, i]\n        Anorm[i, :] /= A[i, i]\n    \n    # Compute the split\n    N = np.eye(n)\n    P = N - Anorm\n    AL = la.tril(P)\n    AU = la.triu(P)\n    \n    # Compute the convergence matrix and check its spectral radius\n    M = np.dot(la.inv(N), P)\n    eigenvalues, eigenvectors = la.eig(M)\n    rho = np.amax(np.absolute(eigenvalues))\n    if (rho > 1):\n        print(\"Jacobi will not converge as the\"\\\n            \" largest eigenvalue of the convergence matrix is {}\".format(rho))\n    \n    for j in range(MaxSteps):\n        x_old = x.copy()\n        x = bnorm + np.dot(AL + AU, x)\n        if (la.norm(x - x_old) < tolerance):\n            print \"Jacobi converged in \", j, \" iterations.\"\n            break\n    \n    return x\n\n#### Answer Coding Question 4\n\ndef GaussSeidel(A, b, tolerance = 1.e-10, MaxSteps = 100):\n    \"\"\"Solve the linear system A x = b using the Gauss-Seidel method, \n    starting from the trivial initial guess.\"\"\"\n    \n    x = np.zeros_like(b)\n    \n    Anorm = A.copy()\n    bnorm = b.copy()\n    n = len(b)\n    \n    for i in range(n):\n        bnorm[i] /= A[i, i]\n        Anorm[i, :] /= A[i, i]\n    \n    # Compute the split\n    D = np.eye(n)\n    AL = la.tril(D - Anorm)\n    AU = la.triu(D - Anorm)\n    N = np.eye(n) - AL\n    P = AU\n    \n    # Compute the convergence matrix and check its spectral radius\n    M = np.dot(la.inv(N), P)\n    eigenvalues, eigenvectors = la.eig(M)\n    rho = np.amax(np.absolute(eigenvalues))\n    if (rho > 1):\n        print(\"Gauss-Seidel will not converge as the\"\\\n              \" largest eigenvalue of the convergence matrix is {}\".format(rho))\n    \n    for j in range(MaxSteps):\n        x_old = x.copy()\n        for i in range(n):\n            x[i] = bnorm[i] + np.dot(AL[i, :], x) + np.dot(AU[i, :], x_old)\n        if (la.norm(x - x_old) < tolerance):\n            print(\"Gauss-Seidel converged in {} iterations.\".format(j))\n            break\n    \n    return x\n\n#### Answer Coding Question 5\n\ndef chord(f, m, x0, tolerance = 1e-10, MaxSteps = 100):\n    \"\"\"Implement the chord method to find the root of the equation f(x) = 0, \n    starting from the initial guess x^{(0)} = x0.\"\"\"\n    \n    x = np.zeros(MaxSteps)\n    x[0] = x0\n    \n    # Set up the map g\n    g = lambda x: x - m * f(x)\n    \n    for i in range(1, MaxSteps):\n        x[i] = g(x[i-1])\n        if (np.absolute(f(x[i])) < tolerance):\n            break\n    return x[:i+1]\n\n", "meta": {"hexsha": "e3b4b20e888869fe3af7f325a60fbc3e6d91af6e", "size": 3972, "ext": "py", "lang": "Python", "max_stars_repo_path": "Worksheets/Worksheet2_Functions.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Worksheets/Worksheet2_Functions.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Worksheets/Worksheet2_Functions.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 26.48, "max_line_length": 80, "alphanum_fraction": 0.5191339376, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122672782973, "lm_q2_score": 0.9173026528034426, "lm_q1q2_score": 0.8786954639273424}}
{"text": "import random\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef graph(x):\n    return 5 * (x ** 4) - 8.7 * (x ** 3) + 33 * (x ** 2) + 21 * (x) + 10.8\n\nxValues = np.linspace(0, 5, 10000)\nyValues = np.array(list(map(graph, xValues)))\n\nplt.figure()\nplt.plot(xValues, yValues, '-b')\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Graph of y = 5(x^4) - 8.7(x^3) + 33(x^2) + 21(x) + 10.8\")\nplt.grid()\nplt.show()\n\n##################################################################################\n\nxLimits = [0, 5]\nyLimits = [0, graph(5)]\nxRange = xLimits[1] - xLimits[0]\nyRange = yLimits[1] - yLimits[0]\n\npointsUnderGraph = []\npointsOverGraph = []\n\ndef calcArea(iterations: int, appendToArray: bool) -> float:\n    countUnder = 0\n\n    for i in range(iterations):\n        point = [random.uniform(xLimits[0], xLimits[1]), random.uniform(yLimits[0], yLimits[1])]\n        isUnderGraph = point[1] < graph(point[0])\n        countUnder += 1 if isUnderGraph else 0\n\n        if appendToArray:\n            if isUnderGraph:\n                pointsUnderGraph.append(point)\n            else:\n                pointsOverGraph.append(point)\n\n    return (countUnder / iterations) * (xRange * yRange)\n\n##################################################################################\n\narea = calcArea(100000, True)\nanalytical = 3457.125\nprint(\"Area after 100,000 iterations: %f\" % area)\nprint(\"Area achieved analytically:    %f\" % analytical)\nprint(\"Percentage error:              %f\" % np.abs(100 * (analytical - area) / analytical))\n\nnp_underGraph = np.array(pointsUnderGraph)\nnp_overGraph = np.array(pointsOverGraph)\n\nplt.figure()\nplt.scatter(np_underGraph[:, 0], np_underGraph[:, 1], c='b', label=\"Under Graph\")\nplt.scatter(np_overGraph[:, 0], np_overGraph[:, 1], c='r', label=\"Over Graph\")\nplt.title(\"Plot of Random Points Under and Over the Graph\")\nplt.legend()\nplt.grid()\nplt.show()\n\n##################################################################################\n\nN_iters = range(10000, 1000001, 10000)\nareaValues = []\nprint()\nfor N_iter in N_iters:\n    areaValues.append(calcArea(N_iter, False))\n    print(\"Area after %d iterations: %f\" % (N_iter, areaValues[-1]))\n\naverageArea = np.mean(areaValues)\nprint()\nprint(\"Average area:                %f\" % averageArea)\nprint(\"Area achieved analytically:  %f\" % analytical)\nprint(\"Percentage error:            %f\" % np.abs(100 * (analytical - averageArea) / analytical))\n\nplt.figure()\nplt.plot(N_iters, areaValues, '-bx')\nplt.plot([N_iters[0], N_iters[-1]], [analytical, analytical], '-r')\nplt.xlabel(\"Number of iterations\")\nplt.ylabel(\"Area\")\nplt.title(\"Plot of Area versus No. of Iterations\")\nplt.grid()\n# plt.show()\n\n##################################################################################\n\nerrorValues = list(map(lambda a: 100 * np.abs(a - analytical) / analytical, areaValues))\n\nplt.figure()\nplt.plot(N_iters, errorValues, '-bx')\nplt.plot([N_iters[0], N_iters[-1]], [1, 1], '-r')\nplt.xlabel(\"Number of iterations\")\nplt.ylabel(\"Percentage Error\")\nplt.title(\"Plot of Percentage Error versus No. of Iterations\")\nplt.grid()\nplt.show()\n\nminimumIter = 0\nfor i in reversed(range(len(errorValues))):  # traverse in reverse\n    if errorValues[i] > 1:\n        minimumIter = N_iters[i+1]  # at i+1 was last for which error was < 1%\n        break\nprint()\nprint(\"Minimum number of iterations: %d\" % minimumIter)\n", "meta": {"hexsha": "0ae2bcfcde707144da062a493f8dd85b09f7d09d", "size": 3345, "ext": "py", "lang": "Python", "max_stars_repo_path": "Implementation/Task3/task3_2.py", "max_stars_repo_name": "migueldingli1997/CCE2501-Modelling-and-Computer-Simulation-Assignment", "max_stars_repo_head_hexsha": "82684a47f63063515351373ccb00d415978b2713", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Implementation/Task3/task3_2.py", "max_issues_repo_name": "migueldingli1997/CCE2501-Modelling-and-Computer-Simulation-Assignment", "max_issues_repo_head_hexsha": "82684a47f63063515351373ccb00d415978b2713", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Implementation/Task3/task3_2.py", "max_forks_repo_name": "migueldingli1997/CCE2501-Modelling-and-Computer-Simulation-Assignment", "max_forks_repo_head_hexsha": "82684a47f63063515351373ccb00d415978b2713", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9722222222, "max_line_length": 96, "alphanum_fraction": 0.5898355755, "include": true, "reason": "import numpy", "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576265, "lm_q2_score": 0.9161096130168221, "lm_q1q2_score": 0.8786904610907909}}
{"text": "\"\"\" Code for the EKF Refactored \"\"\"\n\nimport sympy\nfrom sympy import atan, pi, tan\nfrom sympy import symbols, Matrix\nfrom math import sqrt, tan, cos, sin, atan2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy.random import randn\nfrom filterpy.kalman import ExtendedKalmanFilter as EKF\nfrom numpy import array, sqrt\n\nclass RobotEKF(EKF):\n    def __init__(self, dt, wheelbase, std_vel, std_steer):\n        EKF.__init__(self, 3, 2, 2)\n        self.dt = dt\n        self.wheelbase = wheelbase\n        self.std_vel = std_vel\n        self.std_steer = std_steer\n\n        a, x, y, v, w, theta, time = symbols(\n            'a, x, y, v, w, theta, t')\n        d = v*time\n        beta = (d/w)*sympy.tan(a)\n        r = w/sympy.tan(a)\n    \n        self.fxu = Matrix(\n            [[x-r*sympy.sin(theta)+r*sympy.sin(theta+beta)],\n             [y+r*sympy.cos(theta)-r*sympy.cos(theta+beta)],\n             [theta+beta]])\n\n        self.F_j = self.fxu.jacobian(Matrix([x, y, theta]))\n        self.V_j = self.fxu.jacobian(Matrix([v, a]))\n\n        # save dictionary and it's variables for later use\n        self.subs = {x: 0, y: 0, v:0, a:0, \n                     time:dt, w:wheelbase, theta:0}\n        self.x_x, self.x_y, = x, y \n        self.v, self.a, self.theta = v, a, theta\n\n    def predict(self, u):\n        self.x = self.move(self.x, u, self.dt)\n\n        self.subs[self.theta] = self.x[2, 0]\n        self.subs[self.v] = u[0]\n        self.subs[self.a] = u[1]\n\n        F = array(self.F_j.evalf(subs=self.subs)).astype(float)\n        V = array(self.V_j.evalf(subs=self.subs)).astype(float)\n\n        # covariance of motion noise in control space\n        M = array([[self.std_vel*u[0]**2, 0], \n                   [0, self.std_steer**2]])\n\n        self.P = np.dot(F, self.P).dot(F.T) + np.dot(V, M).dot(V.T)\n\n    def move(self, x, u, dt):\n        hdg = x[2, 0]\n        vel = u[0]\n        steering_angle = u[1]\n        dist = vel * dt\n\n        if abs(steering_angle) > 0.001: # is robot turning?\n            beta = (dist / self.wheelbase) * tan(steering_angle)\n            r = self.wheelbase / tan(steering_angle) # radius\n\n            dx = np.array([[-r*sin(hdg) + r*sin(hdg + beta)], \n                           [r*cos(hdg) - r*cos(hdg + beta)], \n                           [beta]])\n        else: # moving in straight line\n            dx = np.array([[dist*cos(hdg)], \n                           [dist*sin(hdg)], \n                           [0]])\n        return x + dx\n   \n\n   ##MIT license", "meta": {"hexsha": "07f0d5741a273a82f1551dfdf7ff3d1a5b46c4ff", "size": 2482, "ext": "py", "lang": "Python", "max_stars_repo_path": "self driving/controls/kalman/EKF_dynamic.py", "max_stars_repo_name": "Systemx-ai/Pilot-X", "max_stars_repo_head_hexsha": "adabb123917388366b62917db03fa57380b0b456", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-16T05:11:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T05:11:51.000Z", "max_issues_repo_path": "self driving/controls/kalman/EKF_dynamic.py", "max_issues_repo_name": "Systemx-ai/Pilot-X", "max_issues_repo_head_hexsha": "adabb123917388366b62917db03fa57380b0b456", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "self driving/controls/kalman/EKF_dynamic.py", "max_forks_repo_name": "Systemx-ai/Pilot-X", "max_forks_repo_head_hexsha": "adabb123917388366b62917db03fa57380b0b456", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2337662338, "max_line_length": 67, "alphanum_fraction": 0.5273972603, "include": true, "reason": "import numpy,from numpy,import sympy,from sympy", "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.9161096095812347, "lm_q1q2_score": 0.8786904599347871}}
{"text": "# you should fill in the functions in this file,\n# do NOT change the name, input and output of these functions\n\nimport numpy as np\nimport time\nimport matplotlib.pyplot as plt\n\n# first function to fill, compute distance matrix using loops\ndef compute_distance_naive(X):\n    N = X.shape[0]      # num of rows\n    D = X[0].shape[0]   # num of cols\n\n    M = np.zeros([N,N])\n    for i in range(N):\n        for j in range(N):\n            xi = X[i,:]\n            xj = X[j,:]\n            dist = np.linalg.norm(xi-xj)\n            M[i,j] = dist\n\n    return M\n\n# second function to fill, compute distance matrix without loops\ndef compute_distance_smart(X):\n    N = X.shape[0]  # num of rows\n    D = X[0].shape[0]  # num of cols\n    \n    # use X to create M\n    M = np.zeros([N, N])\n\n    sum = np.sum(np.multiply(X,X), axis=1)\n\n    x2 = (sum * np.ones([N,1]))\n    y2 = np.transpose(x2)\n    xy = np.dot(X, X.T)\n\n    M = np.sqrt(abs(x2 - 2 * xy + y2))\n    return M\n\n# third function to fill, compute correlation matrix using loops\ndef compute_correlation_naive(X):\n    N = X.shape[0]  # num of rows\n    D = X[0].shape[0]  # num of cols\n\n    # use X to create M\n    M = np.zeros([D, D])\n\n    for i in range(D):\n        for j in range(D):\n            xi = X[:, i]\n            xj = X[:, j]\n\n            mui = np.sum(xi).astype(float) / N\n            muj = np.sum(xj).astype(float) / N\n            xni = xi - mui\n            xnj = xj - muj\n            sij = (np.dot(xni, xnj)).astype(float) / (N - 1)\n\n            sigmai = np.sqrt(np.dot(xni, xni).astype(float) / (N - 1))\n            sigmaj = np.sqrt(np.dot(xnj, xnj).astype(float) / (N - 1))\n            sigma = sigmai * sigmaj\n\n            cmatrix = sij.astype(float) / sigma\n            M[i, j] = cmatrix\n\n    return M\n\n# fourth function to fill, compute correlation matrix without loops\ndef compute_correlation_smart(X):\n    N = X.shape[0]  # num of rows\n    D = X[0].shape[0]  # num of cols\n\n    # use X to create M\n    M = np.zeros([D, D])\n\n    vectormu = (np.sum(X, axis=0)).astype(float) / N\n    matrixmu = vectormu * np.ones([N, 1])\n    x = X - matrixmu\n    xT = np.transpose(x)\n    covarience = (np.dot(xT, x)).astype(float) / (N - 1)\n    x2 = np.multiply(x, x)\n    varience = (np.sum(x2, axis=0)).astype(float) / (N - 1)\n    sigma = np.sqrt(varience)\n    denmatrix = np.outer(sigma, sigma)\n\n    with np.errstate(divide='ignore', invalid='ignore'):\n        c = np.power(denmatrix,-1)\n        c[c == np.inf] = 0\n        c = np.nan_to_num(c)\n        M = np.multiply(covarience, c)\n\n    return M\n\ndef main():\n    print 'starting comparing distance computation .....'\n    np.random.seed(100)\n    params = range(10,141,10)   # different param setting\n    nparams = len(params)       # number of different parameters\n\n    perf_dist_loop = np.zeros([10,nparams])  # 10 trials = 10 rows, each parameter is a column\n    perf_dist_cool = np.zeros([10,nparams])\n    perf_corr_loop = np.zeros([10,nparams])  # 10 trials = 10 rows, each parameter is a column\n    perf_corr_cool = np.zeros([10,nparams])\n\n    counter = 0\n\n    for ncols in params:\n        nrows = ncols * 10\n\n        print \"matrix dimensions: \", nrows, ncols\n\n        for i in range(10):\n            X = np.random.rand(nrows, ncols)   # random matrix\n\n            # compute distance matrices\n            st = time.time()\n            dist_loop = compute_distance_naive(X)\n            et = time.time()\n            perf_dist_loop[i,counter] = et - st              # time difference\n\n            st = time.time()\n            dist_cool = compute_distance_smart(X)\n            et = time.time()\n            perf_dist_cool[i,counter] = et - st\n\n            assert np.allclose(dist_loop, dist_cool, atol=1e-06) # check if the two computed matrices are identical all the time\n\n            # compute correlation matrices\n            st = time.time()\n            corr_loop = compute_correlation_naive(X)\n            et = time.time()\n            perf_corr_loop[i,counter] = et - st              # time difference\n\n            st = time.time()\n            corr_cool = compute_correlation_smart(X)\n            et = time.time()\n            perf_corr_cool[i,counter] = et - st\n\n            assert np.allclose(corr_loop, corr_cool, atol=1e-06) # check if the two computed matrices are identical all the time\n\n        counter = counter + 1\n\n    mean_dist_loop = np.mean(perf_dist_loop, axis = 0)    # mean time for each parameter setting (over 10 trials)\n    mean_dist_cool = np.mean(perf_dist_cool, axis = 0)\n    std_dist_loop = np.std(perf_dist_loop, axis = 0)      # standard deviation\n    std_dist_cool = np.std(perf_dist_cool, axis = 0)\n\n    plt.figure(1)\n    plt.errorbar(params, mean_dist_loop[0:nparams], yerr=std_dist_loop[0:nparams], color='red',label = 'Loop Solution for Distance Comp')\n    plt.errorbar(params, mean_dist_cool[0:nparams], yerr=std_dist_cool[0:nparams], color='blue', label = 'Matrix Solution for Distance Comp')\n    plt.xlabel('Number of Cols of the Matrix')\n    plt.ylabel('Running Time (Seconds)')\n    plt.title('Comparing Distance Computation Methods')\n    plt.legend()\n    plt.savefig('CompareDistanceCompFig.pdf')\n    # plt.show()    # uncomment this if you want to see it right way\n    print \"result is written to CompareDistanceCompFig.pdf\"\n\n    mean_corr_loop = np.mean(perf_corr_loop, axis = 0)    # mean time for each parameter setting (over 10 trials)\n    mean_corr_cool = np.mean(perf_corr_cool, axis = 0)\n    std_corr_loop = np.std(perf_corr_loop, axis = 0)      # standard deviation\n    std_corr_cool = np.std(perf_corr_cool, axis = 0)\n\n    plt.figure(2)\n    plt.errorbar(params, mean_corr_loop[0:nparams], yerr=std_corr_loop[0:nparams], color='red',label = 'Loop Solution for Correlation Comp')\n    plt.errorbar(params, mean_corr_cool[0:nparams], yerr=std_corr_cool[0:nparams], color='blue', label = 'Matrix Solution for Correlation Comp')\n    plt.xlabel('Number of Cols of the Matrix')\n    plt.ylabel('Running Time (Seconds)')\n    plt.title('Comparing Correlation Computation Methods')\n    plt.legend()\n    plt.savefig('CompareCorrelationCompFig.pdf')\n    # plt.show()    # uncomment this if you want to see it right way\n    print \"result is written to CompareCorrelationCompFig.pdf\"\n\nif __name__ == \"__main__\": main()\n", "meta": {"hexsha": "b1c361e2807fef6888849e858cc7a06ae0c51f9c", "size": 6240, "ext": "py", "lang": "Python", "max_stars_repo_path": "CSCI381_Homework1/ComputeMatrices.py", "max_stars_repo_name": "Shashi717/MachineLearningProjects", "max_stars_repo_head_hexsha": "447d1fb160dc1ceb1530933049c8d696a28b2b71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CSCI381_Homework1/ComputeMatrices.py", "max_issues_repo_name": "Shashi717/MachineLearningProjects", "max_issues_repo_head_hexsha": "447d1fb160dc1ceb1530933049c8d696a28b2b71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CSCI381_Homework1/ComputeMatrices.py", "max_forks_repo_name": "Shashi717/MachineLearningProjects", "max_forks_repo_head_hexsha": "447d1fb160dc1ceb1530933049c8d696a28b2b71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4545454545, "max_line_length": 144, "alphanum_fraction": 0.6116987179, "include": true, "reason": "import numpy", "num_tokens": 1734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.9252299493606285, "lm_q1q2_score": 0.8786625407111767}}
{"text": "# shows how linear regression analysis can be applied to 1-dimensional data\n#\n# notes for this course can be found at:\n# https://deeplearningcourses.com/c/data-science-linear-regression-in-python\n# https://www.udemy.com/data-science-linear-regression-in-python\n\nfrom __future__ import print_function, division\nfrom builtins import range\n# Note: you may need to update your version of future\n# sudo pip install -U future\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# load the data\nX = []\nY = []\nfor line in open('data_1d.csv'):\n    x, y = line.split(',')\n    X.append(float(x))\n    Y.append(float(y))\n\n# let's turn X and Y into numpy arrays since that will be useful later\nX = np.array(X)\nY = np.array(Y)\n\n\n# let's plot the data to see what it looks like\nplt.scatter(X, Y)\nplt.show()\n\n\n# apply the equations we learned to calculate a and b\n\n# denominator is common\n# note: this could be more efficient if\n#       we only computed the sums and means once\ndenominator = X.dot(X) - X.mean() * X.sum()\na = ( X.dot(Y) - Y.mean()*X.sum() ) / denominator\nb = ( Y.mean() * X.dot(X) - X.mean() * X.dot(Y) ) / denominator\n\n# let's calculate the predicted Y\nYhat = a*X + b\n\n# let's plot everything together to make sure it worked\nplt.scatter(X, Y)\nplt.plot(X, Yhat)\nplt.show()\n\n# determine how good the model is by computing the r-squared\nd1 = Y - Yhat\nd2 = Y - Y.mean()\nr2 = 1 - d1.dot(d1) / d2.dot(d2)\nprint(\"the r-squared is:\", r2)\n", "meta": {"hexsha": "499b123eac7bd26f6c5e9396bdafdbae792cfc72", "size": 1433, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear Regression LP/linear_regression_class/lr_1d.py", "max_stars_repo_name": "philtsmith570/Linear-Regression-Lazy-Programmer", "max_stars_repo_head_hexsha": "33c2e35a57359bfcf33746f1acc5c5ed9cf743e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-04T18:36:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T18:36:33.000Z", "max_issues_repo_path": "Machine Learning/linear_regression_class/lr_1d.py", "max_issues_repo_name": "Ashleshk/Machine-Learning-Data-Science-Deep-Learning", "max_issues_repo_head_hexsha": "03357ab98155bf73b8f1d2fd53255cc16bea2333", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Machine Learning/linear_regression_class/lr_1d.py", "max_forks_repo_name": "Ashleshk/Machine-Learning-Data-Science-Deep-Learning", "max_forks_repo_head_hexsha": "03357ab98155bf73b8f1d2fd53255cc16bea2333", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-16T13:11:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-16T13:11:14.000Z", "avg_line_length": 25.5892857143, "max_line_length": 76, "alphanum_fraction": 0.6901605024, "include": true, "reason": "import numpy", "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812309063186, "lm_q2_score": 0.9073122182277757, "lm_q1q2_score": 0.8786241227037558}}
{"text": "# Linear Regression\n\n## Model\n\ngiven a dataset $\\left \\{ (x^{(1)},y^{(1)}),...,(x^{(n)},y^{(n)}) \\right \\} $, where $x^{(i)} \\in \\mathbb{R}^{d},\\ y^{(i)} \\in \\mathbb{R}$.\n\nlinear regression is trying to model $y^{(i)}$ from $x^{(i)}$ by a linear model:\n\n$$h_{\\theta}(x^{(i)}) = \\theta_{0} + \\theta_{1}x_{1}^{(i)} + \\theta_{2}x_{2}^{(i)} + ... + \\theta_{d}x_{d}^{(i)}\\approx y^{(i)}$$\n\nfor the sake of simplicity, we set $x_{0}^{(i)}=1,\\ x^{(i)} = (x_{0}^{(i)},...,x_{d}^{(i)}),\\ \\theta=(\\theta_{0},...,\\theta_{d})$, then:\n\n$$h_{\\theta}(x^{(i)}) = \\sum_{j=0}^{d}\\theta_{j}x_{j}^{(i)} = \\theta^{T}x^{(i)}$$\n\n## Loss Function\n\ngiven $\\hat{y}=(h_{\\theta}^{(1)},...,h_{\\theta}^{(n)}),\\ y=(y^{(1)},...,y^{(n)})$.\n\nwe want to approximate $y$ by $\\hat{y}$, or equivalent to say, we want to minimize the distance between $\\hat{y}$ and $y$.\n\nusing euclidean distance, we derive the loss function for linear regression:\n\n$$J(\\theta) = \\frac{1}{2}\\sum_{i=1}^{n}(h_{\\theta}x^{(i)} - y^{(i)})^2$$\n\n## Gradient Descent\n\nafter defining model and loss function, our goal now is to find the model that minimize the loss function:\n\n$$\\hat{\\theta} = \\underset{\\theta}{argmin}\\ J(\\theta)$$\n\nto minimize the loss function, we can set \n\n$$\\nabla J(\\theta)=0$$\n\nbut to find the analytic solution of this equation is usually impossible.\n\nalternatively, we can init $\\theta$ randomly, then iteratively move $\\theta$ towards the direction that makes $J(\\theta)$ smaller.\n\nremmenber the oposite direction of gradient is the fastest direction that makes functions smaller, we derive gradient descent:\n\n$$\\theta := \\theta - \\alpha\\nabla{J(\\theta )}$$\n\n$\\alpha > 0$ is called the learning rate\n\nappendix: proof of opposite gradient as fastest descent\n\nfor all $l\\in \\mathbb{R}^{d}, \\left \\| l \\right \\| =1$\n\n$$\\lim_{x \\to 0} \\frac{J(\\theta + x l) - J(\\theta ) }{x}=l \\cdot \\nabla{J(\\theta )} >= -\\left \\| l \\right \\|\\left \\|J(\\theta)  \\right \\| = -\\left \\|  J(\\theta )\\right \\|   $$\n\nequality obtained only if $l$ is in the opposite direction of $\\nabla{J(\\theta )}$\n\nimport numpy as np\n\nX = 2 * np.random.rand(100, 1)\ny = 4 + 3 * X + np.random.randn(100, 1)\nX_new = np.array([[0], [2]])\n\n\"\"\"LinearRegression actually uses SVD to get pseudoinverse, based on scipy.linalg.lstsq()\"\"\"\nfrom sklearn.linear_model import LinearRegression\n\nlin_reg = LinearRegression()\nlin_reg.fit(X, y)\nlin_reg.intercept_, lin_reg.coef_\n\ny_predict = lin_reg.predict(X_new)\ny_predict\n\nimport matplotlib.pyplot as plt\n\nplt.plot(X_new, y_predict, \"r-\", linewidth=2, label=\"Predictions\")\nplt.plot(X, y, \"b.\")\nplt.xlabel(\"$x_1$\", fontsize=18)\nplt.ylabel(\"$y$\", rotation=0, fontsize=18)\nplt.legend(loc=\"upper left\", fontsize=14)\nplt.axis([0, 2, 0, 15])\nplt.show()\n\n### stochastic gradient descent\n\nin practice, to update $\\theta$ by gradient descent(concretely batch gradient descent), at each step, we need to calculate all sample's gradient, too slow.\n\nto fix this problem, we can only use one sample's gradient at a time, choose that sample randomly:\n\n$$\\theta := \\theta - \\alpha{l(h_{\\theta}(x^{(i)}), y^{(i)})}$$\n\nfrom sklearn.linear_model import SGDRegressor\n\nsgd_reg = SGDRegressor(max_iter=1000, tol=1e-3, penalty=None, eta0=0.1)\nsgd_reg.fit(X, y.ravel())\n\nsgd_reg.intercept_, sgd_reg.coef_\n\n### mini-batch gradient descent\n\nsgd too random, batch gradient descent too slow, we can use some(not one, not all) samples at a time:\n\n$$\\theta := \\theta - \\alpha\\sum_{i \\in batch}{l(h_{\\theta}(x^{(i)}), y^{(i)})}$$\n\n## update rule of linear regression\n\nfor linear regression, we have:\n\n$$\n\\begin{equation}\n\\begin{split} \n\\frac{\\partial }{\\partial \\theta_{j}}J(\\theta ) &=  \\frac{\\partial }{\\partial \\theta_{j}}\\frac{1}{2}\\sum_{i=1}^{n}(h_{\\theta }(x^{(i)}) - y^{(i)})^2  \\\\ \n&=\\sum_{i=1}^{n}(h_{\\theta }(x^{(i)}) - y^{(i)})\\cdot{}\\frac{\\partial }{\\partial \\theta_{j}}(h_{\\theta }(x^{(i)}) - y^{(i)})\\\\ \n& =\\sum_{i=1}^{n}(h_{\\theta }(x^{(i)}) - y^{(i)})x_{j}^{(i)}\n\\end{split}\n\\end{equation}\n$$\n\nso we have the update rule for linear regression:\n\n$$\\theta_{j}: =\\theta_{j} - \\alpha\\sum_{i=1}^{n} (h_{\\theta }(x^{(i)}) - y^{(i)})x_{j}^{(i)} $$\n\ncombine all dimensions, we have:\n\n$$\\theta: =\\theta - \\alpha\\sum_{i=1}^{n} (h_{\\theta }(x^{(i)}) - y^{(i)})\\cdot x^{(i)} $$\n\n### matrix form\n\ndefine $X = [(x^{(1)})^{T},...,(x^{(n)})^{T}]$, then we can write $J(\\theta)$ in matrix form:\n\n$$\n\\begin{equation}\n\\begin{split}\nJ(\\theta) &= \\frac{1}{2}\\sum_{i=1}^{n}(h_{\\theta}x^{(i)} - y^{(i)})^2 \\\\\n&= \\frac{1}{2}\\sum_{i=1}^{n}(\\theta^{T}x^{(i)} - y^{(i)})^2 \\\\\n&= \\frac{1}{2}(X\\theta - y)^{T}(X\\theta - y)\n\\end{split}\n\\end{equation}\n$$\n\nwe then have:\n\n$$\n\\begin{equation}\n\\begin{split}\n\\nabla{J(\\theta )} &= \\nabla\\frac{1}{2}(X\\theta - y)^{T}(X\\theta - y) \\\\\n&= \\frac{1}{2}\\nabla(\\theta^{T}X^{T}X\\theta - y^{T}(X\\theta) - (X\\theta)^{T}y) \\\\\n&= \\frac{1}{2}\\nabla(\\theta^{T}X^{T}X\\theta - 2(X^{T}y)^{T}\\theta) \\\\\n&= \\frac{1}{2}(2X^{T}X\\theta - 2(X^{T}y)) \\\\\n&= X^{T}X\\theta - X^{T}y\n\\end{split}\n\\end{equation}\n$$\n\nhere we use\n\n1.$a^{T}b=b^{T}a$, obvious.\n\n2.$\\nabla{a^{T}x}=a$, obvious.\n\n3.$\\nabla{x^{T}Ax} = (A + A^{T})x$, proof:\n\n$$\n\\begin{equation}\n\\begin{split}\n\\frac{\\partial}{\\partial x_{i}}x^{T}Ax &= \n\\frac{\\partial}{\\partial x_{i}}{\\sum_{j=1}^{n}}{\\sum_{k=1}^{n}}a_{jk}x_{j}x_{k} \\\\\n&= \\frac{\\partial}{\\partial x_{i}}(\\sum_{j\\ne{i}}a_{ji}x_{j}x_{i} + \\sum_{k\\ne{i}}a_{ik}x_{i}x_{k} + a_{ii}x_{i}^{2}) \\\\\n&= \\sum_{j\\ne{i}}a_{ji}x_{j} + \\sum_{k\\ne{i}}a_{ik}x_{k} + 2a_{ii}x_{ii} \\\\\n&= \\sum_{j=1}^{n}a_{ji}x_{j} + \\sum_{k=1}^{n}a_{ik}x_{k} \\\\\n&= (A^{T}x)_{i} + (Ax)_{i}\n\\end{split}\n\\end{equation}\n$$\n\nfinally, we get the matrix form of the update rule:\n\n$$\\theta: =\\theta - \\alpha X^{T}(X\\theta-\\mathbf{y} ) $$\n\n## analytic solution\n\nfrom above, we have:\n\n$$\\nabla{J(\\theta )} = X^{T}X\\theta - X^{T}y$$\n\nso the equation of zero gradient change to:\n\n$$X^{T}X\\theta - X^{T}y = 0$$\n\nif $X^{T}X$ is invertible:\n\n$$\\theta = (X^{T}X)^{-1}X^{T}y$$\n\nif $X^{T}X$ is not invertible, the equation also have solution. proof:\n\non one hand $X\\theta = 0 \\Rightarrow X^{T}X\\theta=0$<br>\non the other hand $X^{T}X\\theta=0 \\Rightarrow \\theta^{T}X^{T}X\\theta=0 \\Rightarrow (X\\theta)^{T}X\\theta=0 \\Rightarrow X\\theta=0$<br>\nso $X\\theta=0 \\Leftrightarrow X^{T}X\\theta=0$, that is to say $null(X^{T}X)=null(X)$<br>\nwe easily derive from the above that $rank(X^{T}X) = rank(X) = rank(X^{T})$<br>\nbut $range(X^{T}X) \\subseteq  range(X^{T})$, so we must have $range(X^{T}X)=range(X^{T})$<br>\n\nX_b = np.c_[np.ones((100, 1)), X]\ntheta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)\ntheta_best\n\n## geometric interpretation of the linear regression\n\nconsider the linear space $S = span\\left \\{  columns\\ of\\ X \\right \\}$, linear combination of $S$ could be write as $X\\theta$, then:\n\n$X\\theta$ is the projection of $y$ on $S \\Leftrightarrow$ $X\\theta - y$ orthogonal with $S \\Leftrightarrow$ orthogonal with $columns\\ of\\ X \\Leftrightarrow X^{T}(X\\theta - y)=0$\n\nso linear regression could be interpret as finding the projection of $y$ on $S$.\n\n## probabilistic interpretation\n\nassume targets and inputs are related via:\n\n$$y^{(i)} = \\theta^{T}x^{(i)} + \\epsilon^{(i)}$$\n\nwhere $\\epsilon^{(i)}$ is the error term, assume that $\\epsilon^{(i)}$ are distributed IID according to Gaussian with mean 0 and variance $\\sigma^{2}$, i.e the density of $\\epsilon^{(i)}$ is given by:\n\n$$p(\\epsilon^{(i)}) = \\frac{1}{\\sqrt{2\\pi}\\sigma}exp\\left (-\\frac{(\\epsilon^{(i)})^{2}}{2\\sigma^{2}}\\right )$$\n\nthis implies:\n\n$$p(y^{(i)}|x^{(i)}; \\theta) = \\frac{1}{\\sqrt{2\\pi}\\sigma}exp\\left ( -\\frac{(y^{(i)} - \\theta^{T}x^{(i)})^{2}}{2\\sigma^{2}}\\right)$$\n\nwe should denote that $\\theta$ is not a random variable.\n\ngiven $X$ and $\\theta$, what is the probability of $y$? we call it the likelihood function:\n\n$$L(\\theta) = L(\\theta; X,y) = p(y|X; \\theta)$$\n\nfor the above assumptions:\n\n$$\n\\begin{equation}\n\\begin{split}\nL(\\theta) &= \\prod_{i=1}^{n}p(y^{(i)}|x^{(i)}; \\theta) \\\\\n&= \\prod_{i=1}^{n}\\frac{1}{\\sqrt{2\\pi}\\sigma}exp\\left ( -\\frac{(y^{(i)} - \\theta^{T}x^{(i)})^{2}}{2\\sigma^{2}}\\right)\n\\end{split}\n\\end{equation}\n$$\n\nwe should choose $\\theta$ so as to make the data as high probability as possible, i.e we should choose $\\theta$ to maxmize $L(\\theta)$, this is called maximum likelihood. one step further:\n\n$$maximize\\ L(\\theta) \\Leftrightarrow maxmize\\ log(L(\\theta))$$\n\nso we maximize the log likelihood, this is simpler.\n\n$$\n\\begin{equation}\n\\begin{split}\nl(\\theta) &= log(L(\\theta)) \\\\\n&= log\\prod_{i=1}^{n}\\frac{1}{\\sqrt{2\\pi}\\sigma}exp\\left ( -\\frac{(y^{(i)} - \\theta^{T}x^{(i)})^{2}}{2\\sigma^{2}}\\right) \\\\\n&= \\sum_{i=1}^{n}log\\frac{1}{\\sqrt{2\\pi}\\sigma}exp\\left ( -\\frac{(y^{(i)} - \\theta^{T}x^{(i)})^{2}}{2\\sigma^{2}}\\right) \\\\\n&= n\\ log\\frac{1}{\\sqrt{2\\pi}\\sigma} - \\frac{1}{2\\sigma^{2}}\\sum_{i=1}^{n}(y^{(i)} - \\theta^{T}x^{(i)})^{2}\n\\end{split}\n\\end{equation}\n$$\n\nhence, maximizing $l(\\theta)$ gives the same answer as minimizing\n\n$$\\frac{1}{2}\\sum_{i=1}^{n}(y^{(i)} - \\theta^{T}x^{(i)})^{2} = J(\\theta)$$\n\nso linear regression $\\Leftrightarrow $ maximum likelihood given Gaussian error\n\n## regularization\n\nto lower variance $\\Rightarrow $ to limit model's complexity $\\Rightarrow $ to prevent the absolute value of parameters to be too large $\\Rightarrow $ we add punishment term concerning the absolute value of parameters on $J(\\theta)$\n\nchoose $\\lambda{\\left \\| \\theta   \\right \\|}_{2}^{2}$ as the punishment term:\n\n$$J(\\theta) := J(\\theta) + \\lambda{\\left \\| \\theta   \\right \\|}_{2}^{2}$$\n\n$\\lambda$ is the regularization hyperparameter, linear regression with $l_{2}$ loss is ridge regression.\n\notherwise, if we choose $\\lambda{\\left \\| \\theta   \\right \\|}_{1}$ as the punishment term:\n\n$$J(\\theta) := J(\\theta) + \\lambda{\\left \\| \\theta   \\right \\|}_{1}$$\n\nthat is called lasso regression.\n\n## probabilistic interpretation of regularization\n\nas before, we assume:\n\n$$p(y^{(i)}|x^{(i)}; \\theta) = \\frac{1}{\\sqrt{2\\pi}\\sigma}exp\\left ( -\\frac{(y^{(i)} - \\theta^{T}x^{(i)})^{2}}{2\\sigma^{2}}\\right)$$\n\nin bayes perspective, we can also assume $\\theta \\sim N(0, \\sigma_{0})$, that is:\n\n$$p(\\theta) = \\frac{1}{\\sqrt{2\\pi}\\sigma_{0}}exp\\left ( -\\frac{\\left \\| \\theta   \\right \\|_{2}^{2}}{2\\sigma_{0}^{2}}\\right)$$\n\nby bayes rule:\n\n$$P(\\theta|y)=\\frac{P(y|\\theta)P(\\theta)}{P(y)}$$\n\nthus we have maximum a posteriori estimation(MAP):\n\n$$\n\\begin{equation}\n\\begin{split}\n\\hat{\\theta} =&\\underset{\\theta}{argmax}P(\\theta|y)\\\\\n=&\\underset{\\theta}{argmax}P(y|\\theta)P(\\theta) \\\\\n=&\\underset{\\theta}{argmax}\\ logP(y|\\theta)P(\\theta) \\\\\n=&\\underset{\\theta}{argmax}\\ log\\ exp\\left ( \\sum_{i=1}^{n}-\\frac{(y^{(i)} - \\theta^{T}x^{(i)})^{2}}{2\\sigma^{2}}\\right)exp\\left ( -\\frac{\\left \\| \\theta   \\right \\|_{2}^{2}}{2\\sigma_{0}^{2}}\\right)\\\\\n=&\\underset{\\theta}{argmin}\\left(\\sum_{i=1}^{n}\\frac{(y^{(i)} - \\theta^{T}x^{(i)})^{2}}{2\\sigma^{2}} + \\frac{\\left \\| \\theta   \\right \\|_{2}^{2}}{2\\sigma_{0}^{2}}\\right)\\\\\n=&\\underset{\\theta}{argmin}\\left(\\sum_{i=1}^{n}(y^{(i)} - \\theta^{T}x^{(i)})^{2} + \\frac{\\sigma^{2}}{\\sigma_{0}^{2}}\\left \\| \\theta   \\right \\|_{2}^{2}\\right)\n\\end{split}\n\\end{equation}\n$$\n\nthat is exactly minimize:\n\n$$J(\\theta) = \\frac{1}{2}\\sum_{i=1}^{n}(y^{(i)} - \\theta^{T}x^{(i)})^2 + \\lambda{\\left \\| \\theta   \\right \\|}^{2}$$\n\nwith $\\lambda=\\frac{\\sigma^{2}}{2\\sigma_{0}^{2}}$\n\nin one word:\n\n1. linear regression $\\Leftrightarrow $ maximum likelihood estimation(MLE) where noise is guassian.\n2. ridge regression $\\Leftrightarrow $ maximum a posteriori estimation(MAP) where noise and prior are guassian.\n\nfrom sklearn.linear_model import Ridge\n\nridge_reg = Ridge(alpha=1, solver=\"cholesky\", random_state=42)\nridge_reg.fit(X, y)\nridge_reg.predict([[1.5]])\n\n\"\"\"set SGDRegressor penalty=l2\"\"\"\nsgd_reg = SGDRegressor(penalty=\"l2\", max_iter=1000, tol=1e-3, random_state=42)\nsgd_reg.fit(X, y.ravel())\nsgd_reg.predict([[1.5]])\n\n## Lasso\n\n\"\"\"use Lasso or set SGDRegressor penalty=l1\"\"\"\nfrom sklearn.linear_model import Lasso\n\nlasso_reg = Lasso(alpha=0.1)\nlasso_reg.fit(X, y)\nlasso_reg.predict([[1.5]])\n\n\"\"\"combination of ridge and lasso\"\"\"\nfrom sklearn.linear_model import ElasticNet\n\nelastic_net = ElasticNet(alpha=0.1, l1_ratio=0.5)\nelastic_net.fit(X, y)\nelastic_net.predict([[1.5]])\n\n## Polynomial Regression\n\nm = 100\nX = 6 * np.random.rand(m, 1) - 3\ny = 0.5 * X**2 + X + 2 + np.random.randn(m, 1)\n\nplt.plot(X, y, \"b.\")\nplt.xlabel(\"$x_1$\", fontsize=18)\nplt.ylabel(\"$y$\", rotation=0, fontsize=18)\nplt.axis([-3, 3, 0, 10])\nplt.show()\n\nfrom sklearn.preprocessing import PolynomialFeatures\n\npoly_features = PolynomialFeatures(degree=2, include_bias=False)\nX_poly = poly_features.fit_transform(X)\n\nlin_reg = LinearRegression()\nlin_reg.fit(X_poly, y)\nlin_reg.intercept_, lin_reg.coef_\n\nX_new=np.linspace(-3, 3, 100).reshape(100, 1)\nX_new_poly = poly_features.transform(X_new)\ny_new = lin_reg.predict(X_new_poly)\n\nplt.plot(X, y, \"b.\")\nplt.plot(X_new, y_new, \"r-\", linewidth=2, label=\"Predictions\")\nplt.xlabel(\"$x_1$\", fontsize=18)\nplt.ylabel(\"$y$\", rotation=0, fontsize=18)\nplt.legend(loc=\"upper left\", fontsize=14)\nplt.axis([-3, 3, 0, 10])\nplt.show()\n\n\"\"\"using pipeline\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\n\n\ndef polynomial_regression(degree, include_bias=True):\n    return Pipeline([\n        (\"poly_features\", PolynomialFeatures(degree=degree, include_bias=False)),\n        (\"std_scaler\", StandardScaler()),\n        (\"lin_reg\", LinearRegression()),\n    ])\n\npoly_reg = polynomial_regression(degree=2)\npoly_reg.fit(X, y)\n\nX_new = np.linspace(-3, 3, 100).reshape(100, 1)\ny_new = poly_reg.predict(X_new)\n\nplt.plot(X, y, \"b.\")\nplt.plot(X_new, y_new, \"r-\", linewidth=2, label=\"Predictions\")\nplt.xlabel(\"$x_1$\", fontsize=18)\nplt.ylabel(\"$y$\", rotation=0, fontsize=18)\nplt.legend(loc=\"upper left\", fontsize=14)\nplt.axis([-3, 3, 0, 10])\nplt.show()\n\n", "meta": {"hexsha": "a4b3a32ba785ae517291e96f84f346f28d35ac43", "size": 13706, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/02_linear_regression.py", "max_stars_repo_name": "newfacade/machine-learning-notes", "max_stars_repo_head_hexsha": "1e59fe7f9b21e16151654dee888ceccc726274d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/jupyter_execute/02_linear_regression.py", "max_issues_repo_name": "newfacade/machine-learning-notes", "max_issues_repo_head_hexsha": "1e59fe7f9b21e16151654dee888ceccc726274d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/02_linear_regression.py", "max_forks_repo_name": "newfacade/machine-learning-notes", "max_forks_repo_head_hexsha": "1e59fe7f9b21e16151654dee888ceccc726274d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8419753086, "max_line_length": 232, "alphanum_fraction": 0.6270976215, "include": true, "reason": "import numpy", "num_tokens": 4990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854103128328, "lm_q2_score": 0.9059898286330041, "lm_q1q2_score": 0.878615717700111}}
{"text": "import math\nimport numpy as np\n\ndef f(x, y): #objective function\n    return 2*x + y**2 + math.exp(-x-y+1)\n\ndef delta(x, y): #delta = -1 * gradient(f(x_(n)))\n    return np.array([math.exp(-x-y+1) - 2, math.exp(-x-y+1) - 2*y])\n\ndef backtracking(x_n, c, t):\n    global counter\n    counter += 1\n    x_n_new = np.round(x_n + t*delta(x_n[0], x_n[1]), 7) #calculate x_(n + 1)\n    temp = round((-delta(x_n[0], x_n[1])[0])*((x_n_new-x_n)[0]) + (-delta(x_n[0], x_n[1])[1])*((x_n_new-x_n)[1]), 7)\n    if round(f(x_n_new[0], x_n_new[1]), 7) <= round(f(x_n[0], x_n[1]) + c*temp, 7): #condition is true, algorithm stops\n        print('Best approximation of x_n is:', x_n_new)\n        return x_n_new\n    else: #condition is false, algorithm is repeated with x_(n + 1) and t = t/2\n        print('Current x_n is:', x_n_new)\n        backtracking(x_n_new, c, t/2)\n\ncounter = 0\nx_n = np.array([3, 3]) #inital point\nc = 0.8\nt = 1\nprint('Initial x_n is:', x_n)\nbacktracking(x_n, c, t)\nprint('\\nThe steepest descent backtracking algorithm ran', counter, 'times.')\nprint('Total number of steps:', counter*3)\n", "meta": {"hexsha": "17a017dc03754f7181e602678c47b571c4baeef6", "size": 1084, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/steepestDescent.py", "max_stars_repo_name": "michalispap/Optimization-Problem-Backtracking", "max_stars_repo_head_hexsha": "4b80e2cd655d1c361c570bde29aa838873ecc8b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/steepestDescent.py", "max_issues_repo_name": "michalispap/Optimization-Problem-Backtracking", "max_issues_repo_head_hexsha": "4b80e2cd655d1c361c570bde29aa838873ecc8b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/steepestDescent.py", "max_forks_repo_name": "michalispap/Optimization-Problem-Backtracking", "max_forks_repo_head_hexsha": "4b80e2cd655d1c361c570bde29aa838873ecc8b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1333333333, "max_line_length": 119, "alphanum_fraction": 0.6125461255, "include": true, "reason": "import numpy", "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9787126457229185, "lm_q2_score": 0.8976952866333484, "lm_q1q2_score": 0.8785857290339181}}
{"text": "from numpy import cos, cosh, sin, sinh\nimport numpy as np\nimport matplotlib.pyplot as plt\n'''\nTASK 3\n'''\n#Newton's method \ndef newton(f,df,x_0,eps):\n    xn = x_0\n\n    while True:\n        fxn = f(xn)\n        if abs(fxn) < eps:\n            return xn\n        dfxn = df(xn)\n        if dfxn == 0:\n            print('Zero derivative -> no solution')\n            return None\n        xn = xn - fxn/dfxn\n\n#math functions of f & df/dx\ndef f(r):\n    return cos(r)*cosh(r) + 1\n\ndef df(r):\n    return -sin(r)*cosh(r) + cos(r)*sinh(r)\n\n#input parameters for newton's method\neps = 0.001\n\nr1 = newton(f, df, 1.5, eps)          #r1 = 1.87527632324985\nr2 = newton(f, df, 4.25, eps)         #r2 = 4.69409122046058\n\nprint(\"r_1: {:.3f}\".format(r1))\nprint(\"r_2: {:.3f}\".format(r2))\n\ndef phi_1(x):\n    return sin(r1*x) + sinh(r1*x) + ((cos(r1)+cosh(r1))/(sin(r1)+sinh(r1)))*(cos(r1*x)-cosh(r1*x))\n\ndef phi_2(x):\n    return sin(r2*x) + sinh(r2*x) + ((cos(r2)+cosh(r2))/(sin(r2)+sinh(r2)))*(cos(r2*x)-cosh(r2*x))\n\nx = np.arange(-1,2,0.02)    #250 data points\np1 = []                     #y values for phi_1\np2 = []                     #y values for phi_2\n\nfor point in x:\n    p1.append(phi_1(float(point)))\n    p2.append(phi_2(float(point)))\n\np1 = np.array(p1)\np2 = np.array(p2)\n\n#plot phi_1\nplt.plot(x, p1)\nplt.title(\"Plot of phi_1\")\nplt.grid(color='k', linestyle='--', linewidth=0.5)\nplt.show()\n\n#plot phi_2\nplt.plot(x, p2)\nplt.title(\"Plot of phi_2\")\nplt.grid(color='k', linestyle='--', linewidth=0.5)\nplt.ylim(-6, 4)\n#max point of phi_2 (for clarity)\n# xmax = round(x[np.argmax(p2)], 2)\n# ymax = round(p2.max(), 6)\n# def annot_max(x,y, ax=None):\n#     text= \"Max point: x={:.2f}, y={:.6f}\".format(xmax, ymax)\n#     if not ax:\n#         ax=plt.gca()\n#     bbox_props = dict(boxstyle=\"square,pad=0.3\", fc=\"w\", ec=\"k\", lw=0.72)\n#     arrowprops=dict(arrowstyle=\"->\",connectionstyle=\"angle,angleA=0,angleB=60\")\n#     kw = dict(xycoords='data',textcoords=\"axes fraction\",\n#               arrowprops=arrowprops, bbox=bbox_props, ha=\"right\", va=\"top\")\n#     ax.annotate(text, xy=(xmax, ymax), xytext=(0.94,0.96), **kw)\n# annot_max(x,p2)\nplt.show()", "meta": {"hexsha": "44708dabca1ec2f199f9502496e55b8cb451d26e", "size": 2118, "ext": "py", "lang": "Python", "max_stars_repo_path": "tasks/task3.py", "max_stars_repo_name": "paulhinta/Mech-309-final", "max_stars_repo_head_hexsha": "fdf9b91666312311f93a6a52efd1c119851b56c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-21T01:50:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T01:50:43.000Z", "max_issues_repo_path": "tasks/task3.py", "max_issues_repo_name": "paulhinta/Mech-309-final", "max_issues_repo_head_hexsha": "fdf9b91666312311f93a6a52efd1c119851b56c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tasks/task3.py", "max_forks_repo_name": "paulhinta/Mech-309-final", "max_forks_repo_head_hexsha": "fdf9b91666312311f93a6a52efd1c119851b56c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1538461538, "max_line_length": 98, "alphanum_fraction": 0.5764872521, "include": true, "reason": "import numpy,from numpy", "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9802808753491772, "lm_q2_score": 0.8962513648201266, "lm_q1q2_score": 0.8785780724387684}}
{"text": "import math\nimport numpy as np\n\ndef basic_sigmoid(x):\n    \"\"\"\n    Compute sigmoid of x.\n\n    Arguments:\n    x -- A scalar\n\n    Return:\n    s -- sigmoid(x)\n    \"\"\"\n    \n    s = 1 /(1+math.exp(-x))\n    \n    return s\n\nnumber = 1\nprint(\"sigmoid of \"+str(number)+\" is \"+ str(basic_sigmoid(number)))\n\nx = [1, 2, 3]\n# basic_sigmoid(x) \nx = np.array([1, 2, 3])\nprint(np.exp(x))\n\n# example of vector operation\ny= np.array([1, 2, 3])\nprint (y + 3)\n\ndef vectorSigmoid(x):\n    \"\"\"\n    Compute the sigmoid of x\n\n    Arguments:\n    x -- A scalar or numpy array of any size\n\n    Return:\n    s -- sigmoid(x)\n    \"\"\"\n    \n    ### START CODE HERE ### (≈ 1 line of code)\n    s = 1/(1+np.exp(-x))\n    ### END CODE HERE ###\n    return s\n\nx = np.array([1, 2, 3])\nprint(vectorSigmoid(x))\n\n\ndef sigmoid_derivative(x):\n    \"\"\"\n    Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x.\n    You can store the output of the sigmoid function into variables and then use it to calculate the gradient.\n    \n    Arguments:\n    x -- A scalar or numpy array\n\n    Return:\n    ds -- Your computed gradient.\n    \"\"\"\n    \n    ### START CODE HERE ### (≈ 2 lines of code)\n    s = vectorSigmoid(x)\n    ds = s*(1-s)\n    ### END CODE HERE ###\n    print(\"sigmoid is \",s)\n    print(\"sigmoid gradiet is\",ds)\n    return ds\n\nsigmoid_derivative(x)\n\ndef image2vector(image):\n    \"\"\"\n    Argument:\n    image -- a numpy array of shape (length, height, depth)\n    \n    Returns:\n    v -- a vector of shape (length*height*depth, 1)\n    \"\"\"\n    \n    ### START CODE HERE ### (≈ 1 line of code)\n    v = image.reshape(image.shape[0]*image.shape[1]*image.shape[2], 1)\n    ### END CODE HERE ###\n    \n    return v\n\n# This is a 3 by 3 by 2 array, typically images will be (num_px_x, num_px_y,3) where 3 represents the RGB values\nimage = np.array(\n                [\n                  [  \n                    [ 0.67826139,  0.29380381],\n                    [ 0.90714982,  0.52835647],\n                    [ 0.4215251 ,  0.45017551]\n                  ],\n\n                  [\n                    [ 0.92814219,  0.96677647],\n                    [ 0.85304703,  0.52351845],\n                    [ 0.19981397,  0.27417313]\n                  ],\n\n                  [\n                    [ 0.60659855,  0.00533165],\n                    [ 0.10820313,  0.49978937],\n                    [ 0.34144279,  0.94630077]\n                  ]\n                ]\n)\n\nprint (\"image2vector(image) = \" + str(image2vector(image)))\ndef normalizeRows(x):\n    \"\"\"\n    Implement a function that normalizes each row of the matrix x (to have unit length).\n    \n    Argument:\n    x -- A numpy matrix of shape (n, m)\n    \n    Returns:\n    x -- The normalized (by row) numpy matrix. You are allowed to modify x.\n    \"\"\"\n    \n    ### START CODE HERE ### (≈ 2 lines of code)\n    # Compute x_norm as the norm 2 of x. Use np.linalg.norm(..., ord = 2, axis = ..., keepdims = True)\n    x_norm = np.linalg.norm(x, ord = 2, axis = 1, keepdims = True)\n    \n    # Divide x by its norm.\n    print(\"x is \\n\",x,)\n    x = x/x_norm\n    ### END CODE HERE ###\n    print(\"x_norm is \\n\",x_norm)\n    print(x.shape, x_norm.shape)\n\n    return x\n\nrandomArray = np.array(\n                      [\n                        [0, 3, 4],\n                        [1, 6, 4]\n                      ]\n)\n\nprint(\"normalizeRows(randomArray) = \" + str(normalizeRows(randomArray)))\n\ndef softmax(x):\n    \"\"\"Calculates the softmax for each row of the input x.\n\n    Your code should work for a row vector and also for matrices of shape (m,n).\n\n    Argument:\n    x -- A numpy matrix of shape (m,n)\n\n    Returns:\n    s -- A numpy matrix equal to the softmax of x, of shape (m,n)\n    \"\"\"\n    \n    ### START CODE HERE ### (≈ 3 lines of code)\n    # Apply exp() element-wise to x. Use np.exp(...).\n    print(\"x is \\n \",x)\n    x_exp = np.exp(x)\n\n    # Create a vector x_sum that sums each row of x_exp. Use np.sum(..., axis = 1, keepdims = True).\n    print(\"x_exp \\n \", x_exp)\n    x_sum = np.sum(x_exp, axis=1, keepdims=True)\n    print(\"x_sum is \\n \",x_sum)\n    # Compute softmax(x) by dividing x_exp by x_sum. It should automatically use numpy broadcasting.\n    s = x_exp/x_sum\n\n    ### END CODE HERE ###\n    \n    return s\nx = np.array([\n    [9, 2, 5, 0, 0],\n    [7, 5, 0, 0 ,0]])\nprint(\"softmax(x) = \" + str(softmax(x)))\n", "meta": {"hexsha": "2ea07085ce3280cf0849fb4c3b6ebdd4d9ded356", "size": 4328, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpyBasic.py", "max_stars_repo_name": "ismaelsadeeq/dea-learning", "max_stars_repo_head_hexsha": "034303ebef89f15262d9761fbb0c15cbebcbecf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpyBasic.py", "max_issues_repo_name": "ismaelsadeeq/dea-learning", "max_issues_repo_head_hexsha": "034303ebef89f15262d9761fbb0c15cbebcbecf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpyBasic.py", "max_forks_repo_name": "ismaelsadeeq/dea-learning", "max_forks_repo_head_hexsha": "034303ebef89f15262d9761fbb0c15cbebcbecf5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5909090909, "max_line_length": 115, "alphanum_fraction": 0.533271719, "include": true, "reason": "import numpy", "num_tokens": 1242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.947381049809296, "lm_q1q2_score": 0.8785664106825242}}
{"text": "from numpy import array, zeros, sqrt\n\ndef decomposition(A):\n    N = len(A)\n    L = zeros((N,N))    # L = [[0.0] * n for i in xrange(n)]\n    U = zeros((N,N))    # U = [[0.0 for x in range(n)] for y in range(n)]\n\n    for j in range(N):                                      # j = 0 to N-1\n        \n        # Upper Triangular\n        U[j,j] = 1                                          # i = j, Diagonal 1\n\n        for i in range(j):                                  # i = 0 to j-1\n\n            if j == 0: break                                # No value for Ui0  \n            \n            U[i,j] = (A[i,j] - sum(L[i,:i]*U[:i,j]))/L[i,i] # k = 0 to i-1\n\n            # sum(U[k][j] * L[i][k] for k in xrange(i))\n\n        # Lower Triangular\n        for i in range(j, N):                                   # i = j to N-1\n\n            L[i,j] = A[i,j] - sum(L[i,:j]*U[:j,j])              # k = 0 to j-1\n\n            # sum(U[k][j] * L[i][k] for k in xrange(j))\n\n    print('LU Decomposition:')\n    print('[L] =\\n', L, sep='')\n    print('[U] =\\n', U, sep='', end='\\n\\n')\n    return L, U\n\n\ndef solveLU(A, B):\n    L, U = decomposition(A)\n    N = len(L)\n    \n    X = zeros(N)\n    Y = zeros(N)\n\n    # Forward Substitution\n    for i in range(N):                                      # i = 0 to N-1\n        Y[i] = (B[i] - sum(L[i,:i] * Y[:i])) / L[i,i]       # j = 0 to i-1\n\n        # sumj = 0\n        # for j in range(i):\n        #     sumj += L[i,j] * Y[j]\n        # Y[i] = (B[i] - sumj) / L[i,i]\n\n    # Backward Substitution\n    for i in range(N-1, -1, -1):                            # i = N-1 to 0\n        X[i] = (Y[i] - sum(U[i,i+1:] * X[i+1:]))            # j = i+1 to N-1\n\n        # sumj = 0\n        # for j in range(i+1, N):\n        #     sumj += U[i,j] * X[j]\n        # X[i] = (Y[i] - sumj)\n\n    return X\n\n\n# System of Equations\n\nA = array([[3,  -.1, -.2],\n           [.1,  7,  -.3],\n           [.3, -.2, 10]], float)\nB = array([10.3, 33.6, 60.2], float)\n\nN = len(A)\n\n\nX = solveLU(A, B)\n\nprint(\"The Solution of the System:\")\nfor i in range(N):\n    print('X[', i+1, '] = ', round(X[i], 6), sep='')\n\n\n'''\nDecomposition: [A] = [L][U]   # [L][U] ≠ [U][L]    Not commutative\n\n│a11 a12 a13 ... a1n│   │L11  0   0  ...  0 ││U11 U12 U13 ... U1n│\n│a21 a22 a23 ... a2n│   │L21 L22  0  ...  0 ││ 0  U22 U23 ... U2n│\n│a31 a32 a33 ... a3n│ = │L31 L32 L33 ...  0 ││ 0   0  U33 ... U3n│\n│... ... ... ... ...│   │... ... ... ... ...││... ... ... ... ...│\n│an1 an2 an3 ... ann│   │Ln1 Ln2 Ln3 ... Lnn││ 0   0   0  ... Unn│\n\nFor Doolittle: Lii = 1  All elements on main diagonal of [L] are 1\n\n│a11 a12 a13 ... a1n│   │L11  0   0  ...  0 ││ 1  U12 U13 ... U1n│\n│a21 a22 a23 ... a2n│   │L21 L22  0  ...  0 ││ 0   1  U23 ... U2n│\n│a31 a32 a33 ... a3n│ = │L31 L32 L33 ...  0 ││ 0   0   1  ... U3n│\n│... ... ... ... ...│   │... ... ... ... ...││... ... ... ... ...│\n│an1 an2 an3 ... ann│   │Ln1 Ln2 Ln3 ... Lnn││ 0   0   0  ...  1 │\n\n│a11 a12 a13 ... a1n│\n│a21 a22 a23 ... a2n│\n│a31 a32 a33 ... a3n│ =\n│... ... ... ... ...│\n│an1 an2 an3 ... ann│\n\n│L11 L11U12     L11U13            ... L11U1n                      │\n│L21 L21U12+L22 L21U13+L22U23     ... L21U1n+L22U2n               │\n│L31 L31U12+L32 L31U13+L32U23+L33 ... L31U1n+L32U2n+L33U3n        │\n│...      ...             ...     ...             ...             │\n│Ln1 Ln1U12+Ln2 Ln1U13+Ln2U23+Ln3 ... Ln1U1n+Ln2U2n+Ln3U3n+...+Lnn│\n\n Li1 Li1U1j+Li2 Li1U1j+Li2U2j+Li3 ... Li1U1j+Li2U2j+Li3U3j+...+Lnj\n\n where i = 1 to n, j = 1 to n, k = 1 to j\n\n\nL11 = a11   U12 = a12 / L11   U13 =  a13 / L11          ...\nL21 = a21   L22 = a22-L21U12  U23 = (a23-L21U13)/L22    ...\nL31 = a31   L32 = a32-L31U12  L33 =  a33-L31U13-L32U23  ...\nLn1 = an1   Ln2 = an2-Ln1U12  Ln3 =  an3-Ln1U13-Ln2U23  ...\n\nLij = aij   Lij = aij-Li1U1j  Lij =  aij-Li1U1j-Li2U2j\n            Uij = aij / Lii   Uij = (aij-Li1U1j)/Lii\n\nUjj = 1                       j = 1 to n\nUij = (aij - ∑ Lik*Ukj)/Lii   i = 1 to j-1, k = 1 to i-1\nLij =  aij - ∑ Lik*Ukj        i = j to n,   k = 1 to j-1\n\nNo value for Ui1 is implimented by skipping Upper Triangular loop for j == 1 \nFor U1j there is no ∑ and is implimented by k = 1 to 1-1, not entering k loop\nFor Li1 there is no ∑ and is implimented by k = 1 to 1-1, not entering k loop\n\n\nSubstitution: [A]{X}={B}    => [L][U]{X}={B}    => [U]{X}={y} and [L]{y}={B}\n\nForward Substitution: [L]{y}={B}\n\n│L11  0   0  ...  0 ││y1│   │b1│\n│L21 L22  0  ...  0 ││y2│   │b2│\n│L31 L32 L33 ...  0 ││y3│ = │b3│\n│... ... ... ... ...││……│   │……│\n│Ln1 Ln2 Ln3 ... Lnn││yn│   │bn│\n\ny1 =  b1 / L11\ny2 = (b2 - L21y1) / L22\ny3 = (b3 - L31y1 - L32y2) / L33\nyn = (bn - Ln1y1 - Ln2y2 - ... - L[n,n-1]y[n-1]) / Lnn\n\nyi = (bi - ∑ Lij*yj) / Lii , i = 1 to n, j = 1 to i-1\n\nFor y1 there is no ∑ and is implimented by j = 1 to 1-1, not entering j loop\n\nBackward Substitution: [U]{X}={y}\n\n│U11 U12 U13 ... U1n││x1│   │y1│\n│ 0  U22 U23 ... U2n││x2│   │y2│\n│ 0   0  U33 ... U3n││x3│ = │y3│\n│... ... ... ... ...││……│   │……│\n│ 0   0   0  ... Unn││xn│   │yn│\n\nxn =  yn\nx3 = (y3                   - U34*x4)\nx2 = (y2          - U23*x3 - U24*x4)\nx1 = (y1 - U12*x2 - U13*x3 - U14*x4)\nxi = (yi - Uij*xj - Uij*xj - Uij*xj)\n\nxi = (yi - ∑ Uij*xj)       , i = n to 1, j = i+1 to n\n\nFor xn there is no ∑ and is implimented by j = n+1 to n, not entering j loop\n\n'''\n", "meta": {"hexsha": "b9b77a6441927c79bc69a124662172593b66c268", "size": 5243, "ext": "py", "lang": "Python", "max_stars_repo_path": "5. Systems of Linear Equations/5. Crout's (Uii=1) Triangularization (Factorization or LU Decomposition) Method.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5. Systems of Linear Equations/5. Crout's (Uii=1) Triangularization (Factorization or LU Decomposition) Method.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5. Systems of Linear Equations/5. Crout's (Uii=1) Triangularization (Factorization or LU Decomposition) Method.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2083333333, "max_line_length": 80, "alphanum_fraction": 0.4207514782, "include": true, "reason": "from numpy", "num_tokens": 2318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140235181257, "lm_q2_score": 0.908617890746506, "lm_q1q2_score": 0.8785553805822569}}
{"text": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Helper file containing activation functions\n\"\"\"\n\nimport numpy as np\n\n\ndef sigmoid(x):\n    \"\"\"Description: Calculates the sigmoid for each value in the the input array\n    Params:\n        x: Array for which sigmoid is to be calculated\n\n    Returns:\n        ndarray: Sigmoid of the input\n    \"\"\"\n    return 1.0 / (1.0 + np.exp(-x))\n\n\ndef delta_sigmoid(x):\n    \"\"\"Description: Calculates the sigmoid derivative for the input array\n    Params:\n        x: Array for which sigmoid derivative is to be calculated\n\n    Returns:\n        ndarray: Sigmoid derivative of the input\n    \"\"\"\n    return sigmoid(x) * (1 - sigmoid(x))\n\n\ndef softmax(x):\n    \"\"\"Description: Calculates softmax for each set of scores in the input array\n\n    Params:\n        x: Array for which softmax is to be calculated\n            (axis_0 is the feature dimension, axis_1 is the n_samples dim)\n\n    Returns:\n        ndarray: Softmax of the input\n    \"\"\"\n    e_x = np.exp(x - np.max(x, axis=0))\n    return e_x / e_x.sum(axis=0)\n\n\ndef relu(x):\n    \"\"\"Description: Calculates ReLU for each value in the input array\n\n    Params:\n        x: Array for which ReLU is to be calculated\n\n    Returns:\n        ndarray: ReLU of the input\n    \"\"\"\n    return np.maximum(x, 0)\n\n\ndef delta_relu(x):\n    \"\"\"\n\tDescription: Calculates the ReLU derivative for the input array\n\n\tParams:\n\t\t\tx: Array for which ReLU derivative is to be calculated\n\n\tReturns:\n\t\t\tndarray: ReLU derivative of the input\n\t\"\"\"\n    return np.greater(x, 0).astype(np.float32)\n\n\ndef linear(x):\n    \"\"\"\n\tDescription: Calculates the linear activation for the input array\n\n\tParams:\n\t\t\tx: Array for which linear activation is to be calculated\n\n\tReturns:\n\t\t\tndarray: Linear activation of the input\n\t\"\"\"\n    return x\n\n\ndef delta_linear(x):\n    \"\"\"\n\tDescription: Calculates the linear activation derivative for for the input array\n\n\tParams:\n\t\t\tx: Array for which linear activation derivative is to be calculated\n\n\tReturns:\n\t\t\tndarray: Linear activation derivative of the input\n\t\"\"\"\n    return np.ones(x.shape).astype(np.float32)\n\n\ndef activation_function(x, type=\"linear\"):\n    \"\"\"\n\tDescription: Helper function for calculating activation of the input\n\n\tParams:\n\t\t\tout: Array for which activation is to be calculated\n\t\t\ttype: Type of the activation function \n\t\t\t(can be linear, sigmoid, relu, softmax)\n\n\tReturns:\n\t\t\tndarray: Activation of the input\n\t\"\"\"\n    if (type == \"linear\"):\n        return linear(x)\n    elif type == \"sigmoid\":\n        return sigmoid(x)\n    elif type == \"relu\":\n        return relu(x)\n    elif type == \"softmax\":\n        return softmax(x)\n    else:\n        raise ValueError('Invalid activation type entered')\n\n\ndef activation_derivative(x, name=\"linear\"):\n    \"\"\"Description: Helper function for calculating activation derivative of the input\n\n\tParams:\n\t\t\tout: Array for which activation derivative is to be calculated\n\t\t\tname: Type of the activation derivative function\n\t\t\t(can be linear, sigmoid, relu, softmax)\n\n\tReturns:\n\t\t\tndarray: Activation derivative of the input\n\t\"\"\"\n    if (name == \"linear\"):\n        return delta_linear(x)\n    elif (name == \"sigmoid\"):\n        return delta_sigmoid(x)\n    elif (name == \"relu\"):\n        return delta_relu(x)\n    else:\n        raise ValueError('Invalid activation type entered')\n", "meta": {"hexsha": "c322515ca2695cb2c476cf3b840c922a52ecfc8e", "size": 3306, "ext": "py", "lang": "Python", "max_stars_repo_path": "PA1/code/activation.py", "max_stars_repo_name": "badarsh2/EE6132-Deep-Learning-For-Imaging-Assignments", "max_stars_repo_head_hexsha": "f2485bb2f0c17ebddd4acd176a8c6aa8ace6439a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-20T09:36:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-20T09:36:36.000Z", "max_issues_repo_path": "PA1/code/activation.py", "max_issues_repo_name": "badarsh2/EE6132-Deep-Learning-For-Imaging-Assignments", "max_issues_repo_head_hexsha": "f2485bb2f0c17ebddd4acd176a8c6aa8ace6439a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PA1/code/activation.py", "max_forks_repo_name": "badarsh2/EE6132-Deep-Learning-For-Imaging-Assignments", "max_forks_repo_head_hexsha": "f2485bb2f0c17ebddd4acd176a8c6aa8ace6439a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7841726619, "max_line_length": 86, "alphanum_fraction": 0.6657592257, "include": true, "reason": "import numpy", "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273497, "lm_q2_score": 0.9196425273235999, "lm_q1q2_score": 0.8785520988630418}}
{"text": "import math\r\nimport random\r\nfrom matplotlib import pyplot as plt\r\nimport numpy as np\r\n\r\nclass utils:\r\n    def power_mod(self, x, y, p):\r\n        res = 1     \r\n        x = x % p\r\n        while y > 0:\r\n            if y & 1:\r\n                res = (res*x) % p\r\n            y = y>>1\r\n            x = (x*x) % p\r\n        return res\r\n \r\n    def miller_test(self, d, n) -> bool:\r\n        for a in range(2, int(2*math.log(n)**2)): \r\n            x = self.power_mod(a, d, n)\r\n            if x == 1 or x == n-1:\r\n                continue\r\n            c = False\r\n            while d != n-1:\r\n                x = (x * x) % n\r\n                d *= 2\r\n                if x == n-1:\r\n                    c = True\r\n                    break\r\n            if c:\r\n                continue\r\n            return False\r\n        return True\r\n\r\n    def is_prime(self, n) -> bool:\r\n        if n <= 1 or n == 4:\r\n            return False\r\n        if n <= 3:\r\n            return True\r\n        d = n - 1\r\n        while d % 2 == 0:\r\n            d >>= 1\r\n        return self.miller_test(d, n)\r\n\r\n    def primes2n(n):\r\n        \"\"\" Returns  a list of primes < n \"\"\"\r\n        sieve = [True] * n\r\n        for i in range(3,int(n**0.5)+1,2):\r\n            if sieve[i]:\r\n                sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)\r\n        return [2] + [i for i in range(3,n,2) if sieve[i]]\r\n    \r\n    def nprimes(n):\r\n        return len(utils.primes2n(n))\r\n\r\n    def nthprime(n):\r\n        num = 1\r\n        primes = [2]\r\n        if n == 1:\r\n            return 2\r\n        while n > 1 :\r\n            num += 2\r\n            limit = int(math.sqrt(num))+1\r\n            for i in primes:\r\n                if i > limit:\r\n                    primes.append(num)\r\n                    n -= 1\r\n                    break\r\n                if num % i == 0 :\r\n                    break\r\n                \r\n            if i == primes[-1]:\r\n                primes.append(num)\r\n                n -= 1\r\n        return num\r\n\r\n    def prime_factors(n):\r\n        i = 2\r\n        factors = []\r\n        if n % i == 0:\r\n            factors.append(2)\r\n        while n % i == 0:\r\n            n //= i\r\n        i += 1\r\n        while i <= n:\r\n            if n % i == 0:\r\n                factors.append(i)\r\n                n = n // i\r\n                i = 1\r\n            i += 2\r\n        return factors\r\n    \r\n    def nfactors(n):\r\n        return len(utils.prime_factors(n))\r\n\r\n    def nthroot(num, n):\r\n        u, s = num, num+1\r\n        while u < s:\r\n            s = u\r\n            t = (n - 1) * s + num // pow(s, n-1)\r\n            u = t // n\r\n        return s\r\n        if float(s) == num ** (1/n):\r\n            return s\r\n        else:\r\n            return -1\r\n    \r\n    def plot_graph(self, title, x, y, xlabel, ylabel):\r\n        plt.plot(x,y)\r\n        plt.xlabel(xlabel)\r\n        plt.ylabel(ylabel)\r\n        plt.title(title)\r\n        plt.show()\r\n", "meta": {"hexsha": "c89ce2a53bfc673215faf8d073ae32080803f583", "size": 2870, "ext": "py", "lang": "Python", "max_stars_repo_path": "ProjectEuler/Python/utils.py", "max_stars_repo_name": "dfm066/Programming", "max_stars_repo_head_hexsha": "53d28460cd40b966cca1d4695d9dc6792ced4c6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProjectEuler/Python/utils.py", "max_issues_repo_name": "dfm066/Programming", "max_issues_repo_head_hexsha": "53d28460cd40b966cca1d4695d9dc6792ced4c6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProjectEuler/Python/utils.py", "max_forks_repo_name": "dfm066/Programming", "max_forks_repo_head_hexsha": "53d28460cd40b966cca1d4695d9dc6792ced4c6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3982300885, "max_line_length": 61, "alphanum_fraction": 0.3529616725, "include": true, "reason": "import numpy", "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.975576912786245, "lm_q2_score": 0.9005297927918166, "lm_q1q2_score": 0.8785360751238773}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.figsize'] = [16, 12]\nplt.rcParams.update({'font.size' : 18})\n\n# creating a simple signal with 2 frequencies\ndt = 0.001\nt = np.arange(0, 1, dt)\nf = np.sin(2*np.pi*50*t) + np.sin(2*np.pi*120*t)        # sum of 2 frequencies\nf_clean = f                                             # clean 2 tone signal\nf = f + 2.5*np.random.randn(len(t))                     # random noise addition\n\nplt.plot(t, f, color='c', LineWidth='1.5', label='Noisy')\nplt.plot(t, f_clean, color='k', Linewidth='2', label='Clean')\nplt.xlim(t[0], t[-1])\nplt.legend()\nplt.show()\n\n\"\"\" Denoise the noisy signal and try to obtain the clean one \"\"\"\n\nn = len(t)\nfhat = np.fft.fft(f, n)                             # compute fft = (signal, data points)\n                                                    # complex valued(magnitude&phase) fourier coefficients vector\nPSD = fhat * np.conj(fhat) / n                      # Power spectrum (power per frequency) Density\nfreq =(1/(dt*n)) * np.arange(n)                     # create x-axis of frequencies\nL = np.arange(1, np.floor(n/2), dtype='int')        # only plot the first half of\n\nfig, axs = plt.subplots(2, 1)\n\nplt.sca(axs[0])\nplt.plot(t, f, color='c', LineWidth=1.5, label='Noisy')\nplt.plot(t, f_clean, color='k', LineWidth=2, label='Clean')\nplt.xlim(t[0], t[-1])\nplt.legend()\n\nplt.sca(axs[1])\nplt.plot(freq[L], PSD[L], color='c', LineWidth =2, label='Noisy')\nplt.xlim(freq[L[0]], freq[L[-1]])\nplt.ylabel('Power Spectrum')\nplt.xlabel('Hertz')\nplt.legend()\n\nplt.show()\n\n\n\"\"\" Even though the signal is noisy; The Power Spectrum has 2 super-clean peaks(1st at 50Hz. and 2nd at 120Hz.)\n    that means most of the power in noisy signal is in 50Hz and 120Hz \n    and then there is a bunch of noise in noise floor contributing to the jitter on the data(signal) \n    \n    We can filter out; any fourier coefficient that is smaller than 100 -- just zero it out\n    any fourier coefficient larger than 100 -- keep it \n    do Inverse Fourier Transform -- reconstruct denoised signal \"\"\"\n# Use PSD to filter out noise\nindices = PSD > 100                 # frequences larger than 100 --- large vector with a lot of 0s two entries of 1\nPSDclean = PSD * indices            # Zero out all others\nfhat = indices * fhat               # Zero out small fourier coefficients in Y\nffilt = np.fft.ifft(fhat)\n\n# Plots\nfig, axs = plt.subplots(3, 1)\n\nplt.sca(axs[0])\nplt.plot(t, f, color='c', LineWidth=1.5, label='Noisy')\nplt.plot(t, f_clean, color='k', LineWidth='2', label='clean')\nplt.xlim(t[0], t[-1])\nplt.legend()\n\nplt.sca(axs[1])\nplt.plot(t, ffilt, color='k', LineWidth=2, label='Filtered')\nplt.xlim(t[0], t[-1])\nplt.legend()\n\nplt.sca(axs[2])\nplt.plot(freq[L], PSD[L], color='c', LineWidth=2, label='Noisy')\nplt.plot(freq[L], PSDclean[L], color='k', LineWidth=1.5, label='Filtered')\nplt.xlim(freq[L[0]], freq[L[-1]])\nplt.legend()\n\nplt.show()", "meta": {"hexsha": "f8287ff6ccad24096f97895e5470abd0c76100ec", "size": 2909, "ext": "py", "lang": "Python", "max_stars_repo_path": "data denoising FFT/denoise.py", "max_stars_repo_name": "oguznsari/Fourier-implementation", "max_stars_repo_head_hexsha": "c4e1a57bbb05347d7d938c4096bd9ae56586319a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data denoising FFT/denoise.py", "max_issues_repo_name": "oguznsari/Fourier-implementation", "max_issues_repo_head_hexsha": "c4e1a57bbb05347d7d938c4096bd9ae56586319a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data denoising FFT/denoise.py", "max_forks_repo_name": "oguznsari/Fourier-implementation", "max_forks_repo_head_hexsha": "c4e1a57bbb05347d7d938c4096bd9ae56586319a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8227848101, "max_line_length": 115, "alphanum_fraction": 0.6218631832, "include": true, "reason": "import numpy", "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769049752756, "lm_q2_score": 0.9005297907896396, "lm_q1q2_score": 0.8785360661365891}}
{"text": "\"\"\"\nSum square difference\nProblem 6 \nThe sum of the squares of the first ten natural numbers is,\n\n12 + 22 + ... + 102 = 385\nThe square of the sum of the first ten natural numbers is,\n\n(1 + 2 + ... + 10)2 = 552 = 3025\nHence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.\n\nFind the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.\n\"\"\"\n\nimport numpy as np\n\ndef sum_of_squares(range_start, range_end):\n    return sum(i**2 for i in range(range_start, range_end))\n\ndef square_of_sum(range_start, range_end):\n    return sum(range(range_start, range_end)) ** 2\n\ndef compute_difference(range_start, range_end):\n    a = sum_of_squares(range_start, range_end)\n    b = square_of_sum(range_start, range_end)\n\n    return np.abs(a - b)\n\nprint(compute_difference(1, 101))\n\n\"\"\"\n25164150\n\"\"\"\n", "meta": {"hexsha": "ea40482a2a52f96f6faa8f9f3b41b3fc0fdc97c5", "size": 915, "ext": "py", "lang": "Python", "max_stars_repo_path": "006.py", "max_stars_repo_name": "GeraldHaxhillari/ProjectEuler", "max_stars_repo_head_hexsha": "ccbfa90845fba0e44ec12c1137071a8e538fa502", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "006.py", "max_issues_repo_name": "GeraldHaxhillari/ProjectEuler", "max_issues_repo_head_hexsha": "ccbfa90845fba0e44ec12c1137071a8e538fa502", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "006.py", "max_forks_repo_name": "GeraldHaxhillari/ProjectEuler", "max_forks_repo_head_hexsha": "ccbfa90845fba0e44ec12c1137071a8e538fa502", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9117647059, "max_line_length": 132, "alphanum_fraction": 0.7256830601, "include": true, "reason": "import numpy", "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9770226280828406, "lm_q2_score": 0.8991213820004279, "lm_q1q2_score": 0.8784619356075337}}
{"text": "import Utils as u\r\nfrom numpy import ones, append, array\r\nfrom pylab import inv, dot \r\n\r\ndef normal_equation(x,y):\r\n    \"\"\"\r\n    Description:\r\n        Computes the parameters based the training examples and values of the target variables using\r\n        the closed form formula theta = (inverse(X.transpose()*X)*X.transpose())*Y where X.transpose()\r\n        computes the transpose of matrix X and * implies matrix multiplication.\r\n    Parameters:\r\n        x - an array of feature vectors\r\n        y - target variables corresponding to the feature vectors\r\n    Returns:\r\n        theta - an array of parameters corresponding to the feature vectors.\r\n    \"\"\"\r\n\r\n    z = inv(dot(x.transpose(), x))\r\n    theta = dot(dot(z, x.transpose()), y)\r\n    return theta\r\n\r\ndef main():\r\n    \"\"\"\r\n    Description:\r\n        Driver function for the script. Gets the training file from the user, parses it and computes\r\n        the parameters using the normal_equation function.\r\n    Parameters:\r\n        None\r\n    Returns:\r\n        None\r\n    \"\"\"\r\n\r\n    training_file = raw_input(\"Enter the filename in which the training data is present:\")\r\n    n = int(raw_input(\"Enter the number of features:\"))\r\n    m = int(raw_input(\"Enter the number of training examples:\"))\r\n    (x,y) = u.parse_csv(training_file,m,n)\r\n    x = append(ones([m,1]),x,1)\r\n    theta = normal_equation(x,y)\r\n    print \"Parameters Learned from the training set:\\n\",theta\r\n    print \"Enter the new values of feature vector x for which the target value should be predicted\"\r\n    x_new = []\r\n    for i in xrange(n):\r\n        x_new.append(float(raw_input()))\r\n    feature_vector = array(x_new)\r\n    feature_vector = append(ones([1,1]),feature_vector)\r\n    print \"Predicted value of target variable y corresponding to Linear Regression algorithm =\",u.predict(feature_vector,theta)\r\n\r\n# Execute main() only when this script is executed from the command line    \r\nprint __name__\r\nif __name__ == \"__main__\":\r\n    main()", "meta": {"hexsha": "6c32803d85d493263e69eb19aeba6e6ad346a7c2", "size": 1957, "ext": "py", "lang": "Python", "max_stars_repo_path": "aula1_ex1123_normal_equations.py", "max_stars_repo_name": "denstorti/machine-learning", "max_stars_repo_head_hexsha": "473ee030ea6619c2e574756dcbe1c09e81afe3f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aula1_ex1123_normal_equations.py", "max_issues_repo_name": "denstorti/machine-learning", "max_issues_repo_head_hexsha": "473ee030ea6619c2e574756dcbe1c09e81afe3f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aula1_ex1123_normal_equations.py", "max_forks_repo_name": "denstorti/machine-learning", "max_forks_repo_head_hexsha": "473ee030ea6619c2e574756dcbe1c09e81afe3f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3725490196, "max_line_length": 128, "alphanum_fraction": 0.6653040368, "include": true, "reason": "from numpy", "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688145, "lm_q2_score": 0.9099070097026719, "lm_q1q2_score": 0.8784070837625951}}
{"text": "\"\"\"\nMulti-Parameter Bayesian Inference Using Markov Chain Monte Carlo (MCMC)\nSampling and the Metropolis-Hastings Algorithm.\n\nCopyright (c) 2021 Gabriele Gilardi\n\n\nFeatures\n--------\n- Code has been written and tested in Python 3.8.5.\n- Likelihood (pdf) can be defined as an arbitrary function with any number\n  of independent parameters.\n- Prior functions are defined using a list of list, and can be any pdf from\n  function \"prior_dist\" in file \"Metropolis.py\" (other priors can be easily\n  added).\n- Jumps in the Metropolis-Hastings algorithm are proposed using a normal\n  distribution of the parameters.\n- Function \"random_number\" in file \"Metropolis.py\" can be used to generate\n  random numbers from any arbitrary pdf.\n- Results can be verified using the pymc3 library.\n- Usage: python test.py <example>.\n\nMain Parameters\n---------------\nexample = Random, Coin, Normal, Coin_upd\n    Name of the example to run.\nlikelihood\n    Name of the likelihood function.\npar\n    Array with the parameters of the likelihood function.\nn_data >=1\n    Number of data to be sampled from the likelihood function.\ndata\n    Array with the data sampled from the likelihood function.\na0, b0\n    Support interval for the likelihood function.\npriors\n    List with the priors. Each prior is assigned to one of the likelihood\n    parameter following the same order as in <par>.\nsamples > 0\n    Number of jumps to perform in the Metropolis-Hastings algorithm.\npar_init\n    Initial value for the parameters in the Metropolis-Hastings algorithm.\nwidth_prop > 0\n    Standard deviation of the normal distribution used to search the neighboroud\n    of a parameter. A good value should give about 50% of accepted jumps.\ni0 >= 0\n    Index specifying the burn-in/warm-up amount.\nposterior\n    Array containing the jumps (accepted or rejected) of all parameters.\njumps\n    Number of jumps actually accepted.\n\nExamples\n--------\nThere are four examples: Coin, Normal, Coin_upd, and Random (see the code for\nparameters and results).\n\n- Coin: one parameter (theta), Bernoulli distribution as likelihood, beta\n        distribution as prior, admit an analytical solution.\n\n- Normal: two parameters (mean and standard deviation), normal distribution\n          as likelihood, normal distribution as prior for the mean, gamma\n          distribution as prior for the standard deviation, solution also\n          checked with pymc3.\n\n- Coin_upd: one parameter (theta), Bernoulli distribution as likelihood,\n            uniform distribution as initial prior, previous posterior as\n            successive prior.\n\n- Random: generation of random numbers from a generic pdf.\n\nReferences\n----------\n- Metropolis-Hastings algorithm @\n  https://en.wikipedia.org/wiki/Metropolis-Hastings_algorithm\n- Markov chain Monte Carlo @\n  https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo\n- Halls-Moore, 2016, \"Bayesian statistics\", chapter II in \"Advanced Algorithmic\n  Trading\", @ https://www.quantstart.com/advanced-algorithmic-trading-ebook/\n- Probabilistic programming in Python using pymc3 @ https://docs.pymc.io/\n\"\"\"\nif __name__ == '__main__':\n\n    import sys\n    import warnings\n\n    import numpy as np\n    from scipy import stats\n    import matplotlib.pyplot as plt\n    import seaborn as sns\n\n    from Metropolis import metropolis, random_number\n\n    # To avoid the warning about log(0) when one of the probability is zero\n    warnings.filterwarnings(\"ignore\")\n\n    # Read example to run\n    if len(sys.argv) != 2:\n        print(\"Usage: python test.py <example>\")\n        sys.exit(1)\n    example = sys.argv[1]\n\n    # Seed the random generator\n    np.random.seed(123)\n\n    # Coin flip example:\n    # - one parameter (the probability tail comes up)\n    # - Bernoulli distribution as likelihood\n    # - beta distribution as prior\n    # - admit an analytical solution\n    if (example == 'Coin'):\n\n        def pdf_coin(x, par):\n            \"\"\"\n            Bernoulli distribution.\n            \"\"\"\n            theta = par[0]\n            pdf = np.where(x, theta, 1.0-theta)\n\n            return pdf\n\n        # Generate data (0 = tail, 1 = head)\n        likelihood = pdf_coin\n        n_data = 50                 # Number of coin flip\n        par = [0.63]                # Probability tail comes up\n        data = (np.random.uniform(0, 1, size=n_data) > par[0])\n\n        # Priors (coefficients are just arbitrary values used as example)\n        alpha, beta = 4.0, 12.0\n        priors = []\n        priors.append(['beta', alpha, beta])\n\n        # Solve\n        samples = 10000\n        par_init = [0.5]\n        width_prop = 0.1\n        i0 = int(np.floor(0.2 * samples))       # Burn-in period\n        posterior, jumps = metropolis(data, likelihood, priors, samples=samples,\n                                      par_init=par_init, width_prop=width_prop)\n\n        # Results:\n        # - accepted jumps = 52.9%\n        # - <theta> mean and std = 0.289, 0.057\n        print(\"\\nAccepted jumps = {0:.1f}%\".format(100 * jumps / samples))\n        print(\"<theta> mean and std = {0:.3f}, {1:.3f}\"\n              .format(posterior[i0:, 0].mean(), posterior[i0:, 0].std()))\n\n        # Analytical solution\n        # - Bernoulli likelihood with beta prior results in a beta posterior\n        # - posterior (alpha, beta) are converted to equivalent (mu, sigma)\n        #   for comparison purpose\n        # - Results: <theta> mean and std (anal.) = 0.288, 0.055\n        # - Ref.: https://en.wikipedia.org/wiki/Conjugate_prior\n        n_heads = data.sum()\n        alpha_post = alpha + n_heads\n        beta_post = beta + n_data - n_heads\n        a = alpha_post + beta_post\n        mu_post = alpha_post / a\n        sigma_post = np.sqrt(alpha_post * beta_post / (a + 1.0)) / a\n        print(\"\\n<theta> mean and std (anal.) = {0:.3f}, {1:.3f}\"\n              .format(mu_post, sigma_post))\n\n        # Plot posteriors (numerical, analytical, and histogram)\n        plt.subplot(121)\n        sns.kdeplot(posterior[i0:, 0], label='num.', c='b')\n        plt.hist(posterior[i0:, 0], 30, histtype=\"step\", density=True,\n                 color='r', label='hist.')\n        xx = np.linspace(0.0, 0.6, 1000)\n        yy = stats.beta(alpha_post, beta_post).pdf(xx)\n        plt.plot(xx, yy, label='anal.', c='g')\n        plt.xlabel('x')\n        plt.xticks(np.linspace(0.0, 0.6, num=7))\n        plt.xlim(0.0, 0.6)\n        plt.ylabel('$\\Theta$')\n        plt.yticks(np.linspace(0, 8, num=9))\n        plt.ylim(0, 8)\n        plt.grid(b=True)\n        plt.legend()\n\n        # Plot all <theta> values (both accepted and rejected)\n        plt.subplot(122)\n        plt.plot(posterior[:, 0], c='b')\n        plt.xlabel('sample')\n        plt.xticks(np.linspace(0, samples, num=5))\n        plt.xlim(0, samples)\n        plt.ylabel('$\\Theta$')\n        plt.yticks(np.linspace(0.1, 0.5, num=5))\n        plt.ylim(0.1, 0.5)\n        plt.axhline(posterior[i0:, 0].mean(), color='r')\n        plt.grid(b=True)\n\n        plt.show()\n\n    # Example with normally distributed likelihood:\n    # - two parameters (mean and standard deviation)\n    # - Normal distribution as likelihood\n    # - Normal distribution as prior for the mean <mu >and gamma distribution\n    #   as prior for the standard deviation <sigma>\n    # - solution checked with pymc3\n    elif (example == 'Normal'):\n\n        def pdf_normal(x, par):\n            \"\"\"\n            Normal distribution.\n            \"\"\"\n            mu = par[0]\n            sigma = par[1]\n            y = (x - mu) / sigma\n            pdf = np.exp(-y * y / 2.0) / (sigma * np.sqrt(2.0 * np.pi))\n            return pdf\n\n        # Generate data\n        likelihood = pdf_normal\n        n_data = 20\n        par = [-1.3, 1.0]               # Mean and standard deviation\n        a0, b0 = -10.0, +10.0           # Support\n        data = random_number(likelihood, par, a0, b0, size=n_data)\n\n        # Priors (coefficients are just arbitrary values used as example)\n        priors = []\n        priors.append(['norm', 2.0, 1.0])               # Mean\n        priors.append(['gamma', 6.0, 1.0])              # Standard deviation\n\n        # Solve\n        samples = 20000\n        par_init = [2.0, 5.0]\n        width_prop = 0.20\n        i0 = int(np.floor(0.2 * samples))       # Burn-in period\n        posterior, jumps = metropolis(data, likelihood, priors, samples=samples,\n                                      par_init=par_init, width_prop=width_prop)\n\n        # Results:\n        # - accepted jumps = 52.8%\n        # - <mu> mean and std = -1.182, 0.230\n        # - <sigma> mean and std = 0.968, 0.198\n        print(\"\\nAccepted jumps = {0:.1f}%\".format(100 * jumps / samples))\n        print(\"<mu> mean and std = {0:.3f}, {1:.3f}\"\n              .format(posterior[i0:, 0].mean(), posterior[i0:, 0].std()))\n        print(\"<sigma> mean and std = {0:.3f}, {1:.3f}\"\n              .format(posterior[i0:, 1].mean(), posterior[i0:, 1].std()))\n\n        # Solve using pymc3 (set to false if pymc3 not installed)\n        use_pymc3 = True\n        if (use_pymc3):\n\n            print(\"\\n===== Solving using pymc3 =====\")\n\n            import pymc3 as pm\n\n            with pm.Model():\n\n                # Priors\n                mu = pm.Normal('mu', 2.0, 1.0)\n                sigma = pm.Gamma('sigma', 6.0, 1.0)\n\n                # Best starting point\n                start = pm.find_MAP()\n\n                # Likelihood\n                returns = pm.Normal('returns', mu=mu, sd=sigma, observed=data)\n\n                # Algorithm\n                step = pm.Metropolis()\n\n                # Solve\n                trace = pm.sample(samples, step, return_inferencedata=False)\n\n            # Results:\n            # - start point =  {'mu': array(2.0), 'sigma': array(5.0)}\n            # - <mu> mean and std = -1.188, 0.224\n            # - <sigma> mean and std = 0.972, 0.202\n            print(\"Start point = \", start)\n            print(\"<mu> mean and std = {0:.3f}, {1:.3f}\"\n                  .format(trace[i0:]['mu'].mean(), trace[i0:]['mu'].std()))\n            print(\"<sigma> mean and std = {0:.3f}, {1:.3f}\"\n                  .format(trace[i0:]['sigma'].mean(), trace[i0:]['sigma'].std()))\n\n        # Plot <mu> posteriors (numerical, analytical, and histogram)\n        plt.subplot(221)\n        sns.kdeplot(posterior[i0:, 0], label='num.', c='b')\n        plt.hist(posterior[i0:, 0], 50, histtype=\"step\", density=True,\n                 color='r', label='hist.')\n        if (use_pymc3):\n            sns.kdeplot(trace[i0:]['mu'], label='pymc3', c='g')\n        plt.xlabel('x')\n        plt.xticks(np.linspace(-2.50, 0, num=6))\n        plt.xlim(-2.50, 0)\n        plt.ylabel('$\\mu$')\n        plt.yticks(np.linspace(0, 2.5, num=6))\n        plt.ylim(0, 2.5)\n        plt.grid(b=True)\n        plt.legend()\n\n        # Plot <sigma> posteriors (numerical, analytical, and histogram)\n        plt.subplot(222)\n        sns.kdeplot(posterior[i0:, 1], label='num.', c='b')\n        plt.hist(posterior[i0:, 1], 50, histtype=\"step\", density=True,\n                 color='r', label='hist.')\n        if (use_pymc3):\n            sns.kdeplot(trace[i0:]['sigma'], label='pymc3', c='g')\n        plt.xlabel('x')\n        plt.xticks(np.linspace(0.0, 2, num=5))\n        plt.xlim(0.0, 2)\n        plt.ylabel('$\\sigma$')\n        plt.yticks(np.linspace(0, 2.5, num=6))\n        plt.ylim(0, 2.5)\n        plt.grid(b=True)\n        plt.legend()\n\n        # Plot all <mu> values (both accepted and rejected)\n        plt.subplot(223)\n        plt.plot(posterior[:, 0], c='b')\n        plt.xlabel('sample')\n        plt.xticks(np.linspace(0, samples, num=5))\n        plt.xlim(0, samples)\n        plt.ylabel('$\\mu$')\n        plt.yticks(np.linspace(-2, 0, num=5))\n        plt.ylim(-2, 0)\n        plt.axhline(posterior[i0:, 0].mean(), color='r')\n        plt.grid(b=True)\n\n        # Plot all <sigma> values (both accepted and rejected)\n        plt.subplot(224)\n        plt.plot(posterior[:, 1], c='b')\n        plt.xlabel('sample')\n        plt.xticks(np.linspace(0, samples, num=5))\n        plt.xlim(0, samples)\n        plt.ylabel('$\\sigma$')\n        plt.yticks(np.linspace(0.0, 2.50, num=6))\n        plt.ylim(0.0, 2.50)\n        plt.axhline(posterior[i0:, 1].mean(), color='r')\n        plt.grid(b=True)\n\n        plt.show()\n\n    # Coin flip example with updates:\n    # - one parameter (the probability tail comes up)\n    # - Bernoulli distribution as likelihood\n    # - uniform distribution as initial prior\n    # - previous posterior as successive prior\n    elif (example == 'Coin_upd'):\n\n        def pdf_coin_upd(x, par):\n            \"\"\"\n            Bernoulli distribution.\n            \"\"\"\n            theta = par[0]\n            pdf = np.where(x, theta, 1.0-theta)\n\n            return pdf\n\n        # Parameters\n        likelihood = pdf_coin_upd\n        n_data = 50                     # Number of coin flip\n        par = [0.63]                    # Probability tail comes up\n        samples = 5000\n        i0 = int(np.floor(0.2 * samples))       # Burn-in period\n        mu = 0.5\n        width_prop = 0.1\n\n        # Initial prior is uniform\n        XX = np.linspace(0.0, 1.0, 100)\n        YY = np.ones(len(XX))\n        plt.plot(XX, YY, label='init')\n\n        # The mean of the posterior should tend to the probability that head\n        # comes up, i.e. 0.37, while its standard deviation should become\n        # smaller and smaller.\n        #\n        # Results (after 15 steps):\n        # - head freq. = 36.4%\n        # - accepted jumps = 24.0%\n        # - <theta> mean and std = 0.362, 0.020\n        tot_heads = 0\n        tot_data = 0\n        n_steps = 15\n        for step in range(n_steps):\n\n            # Generate data (0 = tail, 1 = head)\n            data = (np.random.uniform(0, 1, size=n_data) > par[0])\n            tot_heads += data.sum()\n            tot_data += len(data)\n\n            # Prior is expressed as generic array\n            priors = []\n            priors.append(['generic', XX, YY])\n\n            # Solve using the previous mean as initial value\n            par_init = [mu]\n            posterior, jumps = metropolis(data, likelihood, priors,\n                                          samples=samples, par_init=par_init,\n                                          width_prop=width_prop)\n            mu = posterior[i0:, 0].mean()\n\n            # Print results for each step\n            print(\"\\nStep\", step+1)\n            print(\"- head freq. = {0:.1f}%\".format(100 * tot_heads / tot_data))\n            print(\"- accepted jumps = {0:.1f}%\".format(100 * jumps / samples))\n            print(\"- <theta> mean and std = {0:.3f}, {1:.3f}\"\n                  .format(mu, posterior[i0:, 0].std()))\n\n            # Use the posterior as new prior (adding 10% tails on the side)\n            x_min, x_max = np.min(posterior[:, 0]), np.max(posterior[:, 0])\n            xx = np.linspace(x_min, x_max, 100)\n            yy = stats.gaussian_kde(posterior[:, 0])(xx)\n            d = x_max - x_min\n            XX = np.concatenate([[xx[0] - 0.1 * d], xx, [xx[-1] + 0.1 * d]])\n            YY = np.concatenate([[0], yy, [0]])\n            if (((step+1) % 3) == 0):\n                plt.plot(XX, YY, label='step ' + str(step+1))\n\n        # Plot interpolated posteriors\n        plt.xlabel('x')\n        plt.xticks(np.linspace(0.2, 0.5, num=7))\n        plt.xlim(0.2, 0.5)\n        plt.ylabel('$\\Theta$')\n        plt.yticks(np.linspace(0, 24, num=7))\n        plt.ylim(0, 24)\n        plt.axvline(1.0 - par[0], c='k', ls='--')\n        plt.grid(b=True)\n        plt.legend()\n        plt.show()\n\n    # Generation of random numbers given the pdf\n    elif (example == 'Random'):\n\n        def pdf_random(x, par):\n            \"\"\"\n            Piece-wise pdf.\n            \"\"\"\n            pdf = np.where((x > 0.0) * (x <= 1.0), 0.3 * x, 0.0)\n            pdf += np.where((x > 1.0) * (x <= 2.0), -0.2 * x + 0.5, 0.0)\n            pdf += np.where((x > 2.0) * (x <= 3.0), 0.1, 0.0)\n            pdf += np.where((x > 3.0) * (x <= 4.0), 0.1 * x - 0.2, 0.0)\n            pdf += np.where((x > 4.0) * (x <= 5.0), 0.2, 0.0)\n            pdf += np.where((x > 5.0) * (x <= 7.0), -0.1 * x + 0.7, 0.0)\n\n            return pdf\n\n        # Parameters\n        par = []\n        a0, b0 = -1.0, +8.0\n\n        # Randomly approximated pdf\n        n_data = 50000\n        data = random_number(pdf_random, par, a0, b0, size=n_data, n=1000)\n\n        # Real pdf\n        xx = np.linspace(a0, b0, 1000)\n        yy = pdf_random(xx, par)\n\n        # Plot\n        plt.plot(xx, yy, label='Real')\n        plt.hist(data, 100, histtype=\"step\", density=True, label='Random')\n        plt.xlabel('x')\n        plt.xticks(np.arange(-1, 9, step=1))\n        plt.xlim(-1, 8)\n        plt.ylabel('pdf')\n        plt.yticks(np.arange(0, 0.4, step=0.05))\n        plt.ylim(0, 0.35)\n        plt.grid(b=True)\n        plt.legend()\n        plt.show()\n\n    else:\n        print(\"\\n\", example)\n        print(\"--> Example not found.\\n\")\n        sys.exit(1)\n", "meta": {"hexsha": "c10f5d63b8ed7070b53f5b0099fc3883ed5a4328", "size": 16779, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code_Python/test.py", "max_stars_repo_name": "gabrielegilardi/BayesianInference", "max_stars_repo_head_hexsha": "8fbdd30267e7bc4e9d6aa2d4589b6a75f6babc57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code_Python/test.py", "max_issues_repo_name": "gabrielegilardi/BayesianInference", "max_issues_repo_head_hexsha": "8fbdd30267e7bc4e9d6aa2d4589b6a75f6babc57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code_Python/test.py", "max_forks_repo_name": "gabrielegilardi/BayesianInference", "max_forks_repo_head_hexsha": "8fbdd30267e7bc4e9d6aa2d4589b6a75f6babc57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7, "max_line_length": 81, "alphanum_fraction": 0.5515823351, "include": true, "reason": "import numpy,from scipy,import pymc3", "num_tokens": 4623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811601648195, "lm_q2_score": 0.9099070054272775, "lm_q1q2_score": 0.8784070805414819}}
{"text": "import numpy as np\nimport scipy.linalg.decomp_lu as dl\n\n# Considera la funzione numpy.random.rand e genera una matrice di numeri random\n# A, di dimensione 7x7.\nn = 7\nA = np.random.rand(n, n)\n\n# {{1}} Quanto vale il numero di condizionamento (con norma 2) della matrice? La\n# matrice è ben o mal condizionata?\nprint('K_A = ', np.linalg.cond(A))\n\n# {{2}} Crea il problema test con soluzione esatta x_true = [1, 1, 1, 1, 1, 1,\n# 1]^T. Riporta gli elementi del vettore b, termine noto del sistema lineare.\nx_true = np.ones(n)\nb = A @ x_true\nprint('b = ', b)\n\n# {{3}} Utilizza le funzioni di scipy.linalg.decomp_lu e fattorizza A con lu(A).\n# Risulta necessario permutare le righe di A? Da cosa si evince?\np, l, u = dl.lu(A)\nprint('Permutation?', not np.array_equal(p, np.eye(n)))\n\n# {{4}} Riporta il valore della norma 'fro' della differenza tra A e la sua\n# fattorizzazione calcolata. A cosa è dovuto questo errore?\nprint('||A - l @ u||_fro = ', np.linalg.norm(A - l @ u, 'fro'))\n\n# {{5}} Usare le funzioni scipy.linalg.solve_triangular e/o scipy.linalg.solve\n# per risolvere il sistema lineare sfruttando la fattorizzazione di A. Riporta\n# la soluzione ottenuta.\nmy_x = dl.lu_solve(dl.lu_factor(A), b)\nprint('my_x = ', my_x)\n\n# {{6}} Calcola la norma 2 della differenza fra la soluzione esatta e la\n# soluzione calcolata.\nprint('||x - my_x||_2 = ', np.linalg.norm(x_true - my_x))\n", "meta": {"hexsha": "fdc1f7b57e984c72d4f9a983503a2b500eef3495", "size": 1378, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/test1.py", "max_stars_repo_name": "FoxySeta/unibo-02023-calcolo-numerico", "max_stars_repo_head_hexsha": "441ede5cc6500751d511ad14aeaafa6e57457bf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-18T08:37:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-18T08:37:22.000Z", "max_issues_repo_path": "test/test1.py", "max_issues_repo_name": "FoxySeta/unibo-02023-calcolo-numerico", "max_issues_repo_head_hexsha": "441ede5cc6500751d511ad14aeaafa6e57457bf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test1.py", "max_forks_repo_name": "FoxySeta/unibo-02023-calcolo-numerico", "max_forks_repo_head_hexsha": "441ede5cc6500751d511ad14aeaafa6e57457bf3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2432432432, "max_line_length": 80, "alphanum_fraction": 0.7002902758, "include": true, "reason": "import numpy,import scipy", "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811631528336, "lm_q2_score": 0.909907001151883, "lm_q1q2_score": 0.8784070791329116}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n#   data\nx = np.array([1.0, 1.0, 2.0, 3.3, 3.3, 4.0, 4.0, 4.0, 4.7, 5.0, 5.6,\n    5.6, 5.6, 6.0, 6.0, 6.5, 6.92])\ny = np.array([10.84, 9.30, 16.35, 22.88, 24.35, 24.56, 25.86, 29.46,\n    24.59, 22.25, 25.90, 27.20, 25.61, 25.45, 26.56, 21.03, 21.46])\n\n#   fit a linear model\nA = np.ones([len(x), 2])\nA[:,1] = x\nbeta, SSe, rank, s = np.linalg.lstsq(A,y)\nxl = np.linspace(min(x),max(x),num=100)\nAl = np.ones([len(xl), 2])\nAl[:,1] = xl\nyl = np.dot(Al,beta)\nyhat = np.dot(A,beta)\n#   plot\nplt.figure()\nplt.plot(x,y,'ok')\nplt.plot(xl,yl,'-b')\nplt.grid(True)\nplt.xlabel('$x$')\nplt.ylabel('$y$')\nplt.show()\n#plt.savefig('dataAndFit.png', ftype='png', dpi=300)\n\n#   compute the sum of squares of pure error\nlevel = np.array([1.0, 2.0, 3.3, 4.0, 4.7, 5.0, 5.6, 6.0, 6.5, 6.92])\nlevelIndex = [y[0:2], y[2], y[3:5], y[5:8], y[8], y[9],\n    y[10:13], y[13:15], y[15], y[16]]\nybarLevels = []\nfor i in levelIndex:\n    ybarLevels.append(np.mean(i))\nSSpe = 0\nfor i, r in enumerate(levelIndex):\n    SSpe += np.sum((r-ybarLevels[i])**2)\n\n#   compute the sum of squares lack of fit\nnl = len(level)\nSSlof = 0\nAlevel = np.ones([nl,2])\nAlevel[:,1] = level\nyhatLevel = np.dot(Alevel,beta)\nfor i, j in enumerate(ybarLevels):\n    ni = np.size(levelIndex[i])\n    SSlof+= ni*((j-yhatLevel[i])**2)\n    \n#   Statistical test for lack of fit\nm = len(ybarLevels)\nn = len(x)\np = len(beta)\nF0 = (SSlof / (m-p)) / (SSpe / (n-m))\n\n#   test for lack of fit\nfrom scipy.stats import f\npValue = 1.0 - f.cdf(F0,m-p,n-m)\n#   since pValue is very small we reject the case \n", "meta": {"hexsha": "703e6c483521dc7fe9ffbd1c52bd235d8ea31d50", "size": 1582, "ext": "py", "lang": "Python", "max_stars_repo_path": "assets/2017-03-18/linExample.py", "max_stars_repo_name": "ChrisLuginbuhl/cjekel.github.io", "max_stars_repo_head_hexsha": "a0bc8edf6ff97437035a13ae476bc04fd2448eef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assets/2017-03-18/linExample.py", "max_issues_repo_name": "ChrisLuginbuhl/cjekel.github.io", "max_issues_repo_head_hexsha": "a0bc8edf6ff97437035a13ae476bc04fd2448eef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assets/2017-03-18/linExample.py", "max_forks_repo_name": "ChrisLuginbuhl/cjekel.github.io", "max_forks_repo_head_hexsha": "a0bc8edf6ff97437035a13ae476bc04fd2448eef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.813559322, "max_line_length": 69, "alphanum_fraction": 0.5916561315, "include": true, "reason": "import numpy,from scipy", "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731158685837, "lm_q2_score": 0.9124361658344132, "lm_q1q2_score": 0.8783777667949983}}
{"text": "\"\"\"\nThis example approximates pi numerically using a Monte Carlo estimator:\nI = (4/N) SUM_{i=1}^{N} h(x^(i), y^(i)) where h() is the indicator \nfunction h(x,y) = {1 if x^2+y^2 <= 1 and 0 otherwise} and the tupels \n(x^(i), y^(i)) are drawn from the uniform distribution U([0,1]x[0,1])\n\"\"\"\nimport numpy as np \nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport math\nfrom math import log10, floor\nfrom matplotlib.ticker import MaxNLocator\n\nrc('font', **{'size':12, 'family':'serif', 'serif':['Computer Modern Roman']})\nrc('text', usetex=True)\n\n# Parameters for simulation\nNUM_RUNS = 10\nNUM_DRAW_STEPS = 5\n\nSTEP_MULTIPLIER = 10\nSTEP_START = 100\n\nPRECISION = 6\n\nPATH_FIG = 'pi_monte_carlo.pdf'\nPATH_DATA = 'pi_monte_carlo.txt'\n\ndef round_sig(x, sig):\n\treturn round(x, sig-int(floor(log10(abs(x))))-1)\n\ndef indicator_function(x, y):\n\tif (np.power(x, 2) + np.power(y, 2)) <= 1:\n\t\treturn 1\n\telse:\n\t\treturn 0\n\ndef approximation(num_draws):\n\t\"\"\"\n\tApproximation of pi with (num_draws) number of draws\n\t\"\"\"\n\tsamples = np.random.uniform(-1, 1, (num_draws, 2))\n\n\tdraws_in_circle = 0\n\n\tfor i in range(0, num_draws):\n\t\tdraws_in_circle += indicator_function(samples[i,0], samples[i,1])\n\n\treturn 4*(draws_in_circle/num_draws)\n\ndef simulation():\n\t\"\"\"\n\tThe approximation is run (NUM_RUNS)x(NUM_DRAW_STEPS)\n\t\"\"\"\n\tpi_approximations = np.zeros((NUM_DRAW_STEPS, NUM_RUNS))\n\n\tnum_draws = STEP_START\n\n\tfor i in range(0, NUM_DRAW_STEPS):\n\t\tfor j in range(0, NUM_RUNS):\n\t\t\tpi_approximations[i,j] = approximation(num_draws)\n\n\t\tnum_draws *= STEP_MULTIPLIER\n\n\treturn pi_approximations\n\ndef visualization(pi_approximations):\n\t\"\"\"\n\tPlotting the expected values of the simulation\n\t\"\"\"\n\tfig, ax = plt.subplots() \n\n\tlabels = [r'$10^2$', r'$10^3$', r'$10^4$', r'$10^5$', r'$10^6$']\n\tx = [0, 1, 2, 3, 4]\n\n\tax.plot([-0.5, NUM_RUNS], [math.pi, math.pi], color='k', linestyle='-', linewidth=1)\n\tax.plot(pi_approximations,'kx',markersize=2)\n\n\tplt.xlabel(r'Number of draws')\n\tplt.ylabel(r'Expected value $I(h)$')\n\tplt.xlim(-0.5, NUM_DRAW_STEPS-0.5)\n\tax.xaxis.set_major_locator(MaxNLocator(integer=True))\n\tplt.xticks(x, labels)\n\n\tplt.savefig(PATH_FIG, bbox_inches='tight')\n\tplt.show()\n\ndef data(pi_approximations):\n\t\"\"\"\n\tSaving the data of the expected values \n\t\"\"\"\n\tdata_file = open(PATH_DATA, 'w')\n\n\tfor i in range(0, NUM_DRAW_STEPS):\n\t\texpecation_sum = 0\n\n\t\tfor j in range(0, NUM_RUNS):\n\t\t\troundend_expactation = round_sig(pi_approximations[i, j], PRECISION)\n\t\t\texpecation_sum += roundend_expactation\n\n\t\t\tdata_file.write(str(roundend_expactation) + ' ')\n\n\t\tmean = round_sig((expecation_sum/NUM_RUNS), PRECISION)\n\n\t\tdata_file.write('\\t' + str(mean))\n\t\tdata_file.write('\\n')\n\ndef main():\n\tapproximation = simulation()\n\tvisualization(approximation)\n\tdata(approximation)\n\t\nif __name__ == \"__main__\":\n\tmain()\n", "meta": {"hexsha": "2d543c68a21796eee118a95fd1728e69eb9ebf27", "size": 2777, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/pi_monte_carlo.py", "max_stars_repo_name": "timudk/introduction_to_mcmc", "max_stars_repo_head_hexsha": "6513f2e49b8d6a4a03c24bb40a6807876e6941b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-30T07:31:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T03:06:18.000Z", "max_issues_repo_path": "code/pi_monte_carlo.py", "max_issues_repo_name": "timudk/introduction_to_mcmc", "max_issues_repo_head_hexsha": "6513f2e49b8d6a4a03c24bb40a6807876e6941b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/pi_monte_carlo.py", "max_forks_repo_name": "timudk/introduction_to_mcmc", "max_forks_repo_head_hexsha": "6513f2e49b8d6a4a03c24bb40a6807876e6941b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.147826087, "max_line_length": 85, "alphanum_fraction": 0.6982355059, "include": true, "reason": "import numpy", "num_tokens": 851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147201714923, "lm_q2_score": 0.9032942008463507, "lm_q1q2_score": 0.8783765775485359}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import interp1d\nfrom scipy.integrate import simps\n\nxs = [0.0,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0,\n    5.5,6.0,6.5,7.0,7.5,8.0,8.5,9.0,9.5,10.0]\nys = [0.2,0.165,0.167,0.166,0.154,0.134,0.117,0.108,0.092,0.06,0.031,0.028,\n    0.048,0.077,0.103,0.119,0.119,0.103,0.074,0.038,0.003]\n\nplt.scatter(xs,ys)\nplt.xlabel(\"x\")\nplt.ylabel(\"Observed PDF\")\nplt.show()\n#This is a continuous distribution\n\n#span x from min to max with these data points\n#interpolating the data\nx = np.linspace(min(xs),max(xs),1000)\ny1 = interp1d(xs,ys)(x)\n#interpolating xs and ys to x line\n\nplt.scatter(xs,ys,s=30,label=\"Data\",c=\"b\")\nplt.plot(x,y1,label=\"Linear(default)\")\nplt.legend()\nplt.show()\n#linear interpolating in our data\n#but if we have sparse data then it is not shown correctly\n#depends on data\n\n#another type of interpolation - nearest\nx = np.linspace(min(xs),max(xs),1000)\ny2 = interp1d(xs,ys,kind=\"nearest\")(x)\n#works as a step function in the graph shown below\n#useful for discrete function but not very useful for\n#smooth changing values\n\nplt.scatter(xs,ys,s=30,label=\"Data\",c=\"b\")\nplt.plot(x,y1,label=\"Linear(default)\")\nplt.plot(x,y2,label=\"Nearest\")\nplt.legend()\nplt.show()\n\n#another type of interpolation - quadratic\nx = np.linspace(min(xs),max(xs),1000)\ny3 = interp1d(xs,ys,kind=\"quadratic\")(x)\n#works as a step function in the graph shown below\n#useful for discrete function but not very useful for\n#smooth changing values\n\nplt.scatter(xs,ys,s=30,label=\"Data\",c=\"b\")\nplt.plot(x,y1,label=\"Linear(default)\")\nplt.plot(x,y2,label=\"Nearest\",alpha=0.3)\nplt.plot(x,y3,label=\"Quadratic\",ls=\"-\")\nplt.legend()\nplt.show()\n#on the changing gradient you can see the difference\n#between the nearest and quadratic\n\n\n#another type of interpolation - cubic\nx = np.linspace(min(xs),max(xs),1000)\ny4 = interp1d(xs,ys,kind=\"cubic\")(x)\n\nplt.scatter(xs,ys,s=30,label=\"Data\",c=\"b\")\nplt.plot(x,y1,label=\"Linear(default)\")\nplt.plot(x,y2,label=\"Nearest\",alpha=0.3)\nplt.plot(x,y3,label=\"Quadratic\",ls=\"-\")\nplt.plot(x,y4,label=\"Cubic\",ls=\"-\")\nplt.legend()\nplt.show()\n#the more complex interpolation,the slower\n#it's(difference in quadratic and cubic) going to be\n\nfrom scipy.interpolate import splev,splrep\n\n#another type of interpolation - splev\nx = np.linspace(min(xs),max(xs),1000)\ny5 = splev(x,splrep(xs,ys))\n#if data changing quickly, using cubic spline\n\nplt.scatter(xs,ys,s=30,label=\"Data\",c=\"b\")\nplt.plot(x,y1,label=\"Linear(default)\")\nplt.plot(x,y2,label=\"Nearest\",alpha=0.3)\nplt.plot(x,y3,label=\"Quadratic\",ls=\"-\")\nplt.plot(x,y4,label=\"Cubic\",ls=\"-\")\nplt.plot(x,y5,label=\"Spline\",ls=\"-\",alpha=0.5,c=\"#0000\")\nplt.legend()\nplt.show()\n\n#the red changes colour as both quadratic and spline are same\n\n\n#Using the interp1d we can find the probability for any x value\n#Using scipy.integrate we can calculate the CDF and probability in two bounds\n\n#scipy.integrate.trapz = low accuracy but high speed - accuracy scales as O(h)\n#scipy.integrate.simps = med accuracy but very high speed - acc scales as O(h^2)\n#scipy.integrate.quad = high accuracy but low speed - arbitary accuracy\n\n\ndef get_prob(xs,ys,a,b): #add another variable here resolution=1000\n  #a,b = bounds\n  #to normalize, use the below\n  x_norm = np.linspace(min(xs),max(xs),1000) #add resolution here instead of no\n  y_norm = interp1d(xs,ys,kind=\"quadratic\")(x_norm)\n  normalisation = simps(y_norm,x=x_norm)\n  x_vals = np.linspace(a,b,1000)#add resolution here instead of number\n  y_vals = interp1d(xs,ys,kind=\"quadratic\")(x_vals) #general solution\n  #could be tweaked to gain more accuracy\n  return simps(y_vals,x=x_vals)/normalisation\n\ndef get_cdf(xs,ys,v):#value of cdf at\n  return get_prob(xs,ys,min(xs),v) #if xs is np array -> xs.min(),upto value v\n\ndef get_sf(xs,ys,v):\n  return 1 - get_cdf(xs,ys,v)#definition of the survival function\n  #OR return get_prob(xs,ys,v,max(xs))\n\nprint(get_prob(xs,ys,0,10)) #simps has some issue & needs to be normalized,\n#check the normalized code above and check without normalized\n#another problem is of numbers added to np.linspace,try changing\n#x_vals = np.linspace(a,b,100), to solve this\n#add a variable to it, use of resolution can solve the problem\n\n\nv1,v2 = 6,9.3\narea = get_prob(xs,ys,v1,v2)\n\nplt.scatter(xs,ys,s=30,label=\"Data\",color=\"w\")\nplt.plot(x,y3,linestyle=\"-\",label=\"Interpolation\")\nplt.fill_between(x,0,y3,where=(x>=v1)&(x<=v2),alpha=0.2) #fill in the values\nplt.annotate(f\"p = {area}.3f\",(7,0.05))\nplt.legend()\nplt.show()\n\n\n#comparing cdf\nx_new = np.linspace(min(xs),max(xs),100)\ncdf_new = [get_cdf(xs,ys,i) for i in x_new] #expensive way of cdf_new\n\ncheap_cdf =y3.cumsum()/y3.sum()\nplt.plot(x_new,cdf_new,label=\"Interpolated CDF\",c=\"r\")\nplt.plot(x,cheap_cdf,label=\"Super cheap CDF for specific cases\",c=\"g\")\nplt.ylabel(\"CDF\")\nplt.xlabel(\"x\")\nplt.legend()\nplt.show()\n#for smooth data you can use the cheap cdf method\n#you can see the interpolated and the cheap cdf coming together\n", "meta": {"hexsha": "119b4085243ca423eb9743b96a787abe6c675b44", "size": 4940, "ext": "py", "lang": "Python", "max_stars_repo_path": "empirical_dist.py", "max_stars_repo_name": "WestHamster/Feature_engg", "max_stars_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "empirical_dist.py", "max_issues_repo_name": "WestHamster/Feature_engg", "max_issues_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "empirical_dist.py", "max_forks_repo_name": "WestHamster/Feature_engg", "max_forks_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7152317881, "max_line_length": 80, "alphanum_fraction": 0.7218623482, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.9362849990810246, "lm_q1q2_score": 0.8783514450840708}}
{"text": "#!/usr/bin/env python\n\"\"\"Program to multiply 2  matrices together. (nxm)*(mxl)\"\"\"\n\nimport numpy as np \nimport timeit\n\nspeed_test = True\n\ndef check_shape(A,B):\n\t\"\"\"Checking if it's possible to multiply these matrices together\"\"\"\n\tshape_A = np.shape(A)\n\tshape_B = np.shape(B)\n\tif shape_A[1] != shape_B[0]:\n\t\traise ValueError(\"shapes {0} and {1} not aligned\".format(shape_A,shape_B))\n\ndef matrix_mult_nested(A,B):\n\t\"\"\"Matrix multiplication using nested for loops\"\"\"\n\tcheck_shape(A,B)\n\trows = np.shape(A)[0]\n\tcols = np.shape(B)[1]\n\tC = np.zeros((rows,cols)) #resultant matrix after multiplication\n\tfor i in range(rows): \n\t\tfor j in range(cols): #loops give [i,j] location in matrix\n\t\t\tfor k in range(cols): #each [i,j] location is a dot-product of a row of X and a column of Y\n\t\t\t\tC[i][j] += A[i][k]*B[k][j]\n\treturn C\n\ndef matrix_mult_list_comp(A,B):\n\t\"\"\"Matrix multiplication using list comprehension\"\"\"\n\tcheck_shape(A,B)\n\trows = np.shape(A)[0]\n\tcols = np.shape(B)[1]\n\tC = [[np.sum([A[i][k]*B[k][j] for k in range(cols)]) for j in range(cols)] for i in range(rows)]\n\treturn C\n\ndef matrix_mult_numpy(A,B):\n\t\"\"\"Matrix multiplication using numpy dot function\"\"\"\n\tC = np.dot(A,B)\n\treturn C\n\ndef time_elasped(function):\n\tstart = timer()\n\tfunction\n\tend = timer()\n\treturn end-start\n\n#Example matrices\nX = np.array([[1,2],[3,4],[5,6]])\nY = np.array([[5,6],[7,8]])\n\nprint(\"Example Matrices\")\nprint(\"X * Y = \\n{0} * \\n{1}\".format(X,Y))\nprint(\"Nested for loop:\\n\", matrix_mult_nested(X,Y))\nprint(\"List comprehension:\\n\", matrix_mult_list_comp(X,Y))\nprint(\"Numpy dot function:\\n\", matrix_mult_numpy(X,Y))\n\n\nif speed_test: #speed test is optional\n\t#Large Matrix\n\tnp.random.seed(1)\n\tlarge_X =  np.random.rand(20,20)\n\tlarge_X_inv = np.linalg.inv(large_X)\n\tprint(\"\\nSpeed test\")\n\n\t#I only made these function because they don't have any arguments so I can use timeit on them easily\n\tdef func1():\n\t\treturn matrix_mult_nested(large_X,large_X_inv)\n\tdef func2():\n\t\treturn matrix_mult_list_comp(X,Y)\n\tdef func3():\n\t\treturn matrix_mult_numpy(X,Y)\n\n\tt_nested = np.min(timeit.repeat(\"func1()\", setup=\"from __main__ import func1\",repeat=5,number= 100))/100\n\tt_list_comp = np.min(timeit.repeat(\"func2()\", setup=\"from __main__ import func2\",repeat=5,number= 100))/100\n\tt_numpy = np.min(timeit.repeat(\"func3()\", setup=\"from __main__ import func3\",repeat=5,number= 100))/100\n\tprint(\"Nested for loop:\")\n\tprint(\"{0:.3e} seconds\".format(t_nested))\n\tprint(\"List comprehension:\")\n\tprint(\"{0:.3e} seconds\".format(t_list_comp))\n\tprint(\"Numpy dot function:\")\n\tprint(\"{0:.3e} seconds\".format(t_numpy))\n\n\n\n\n#Code graveyard\n\t# print(timeit.repeat(\"func2()\", setup=\"from __main__ import func2\"))\n\t# print(timeit.repeat(\"func3()\", setup=\"from __main__ import func3\")\n\t# t_nested = time_elasped(matrix_mult_nested(large_X,large_X_inv))\n\t# t_list_comp = time_elasped(matrix_mult_list_comp(large_X,large_X_inv))\n\t# t_numpy = time_elasped(matrix_mult_numpy(large_X,large_X_inv))\n\t# print(\"Nested for loop:\\n\", t_nested*1e7)\n\t# #np.round(matrix_mult_nested(large_X,large_X_inv)))\n\t# print(\"List comprehension:\\n\", t_list_comp*1e7)\n\t# #np.round(matrix_mult_list_comp(large_X,large_X_inv)))\n\t# print(\"Numpy dot function:\\n\", t_numpy*1e7)\n\t# #np.round(matrix_mult_numpy(large_X,large_X_inv)))\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ca3c1444dbdd47210fdc594c38dc6c7fc4b597b3", "size": 3247, "ext": "py", "lang": "Python", "max_stars_repo_path": "5.3c_matrix_multiplication.py", "max_stars_repo_name": "bayu-wilson/phys218_example", "max_stars_repo_head_hexsha": "f6d624d0747c42b29e9855c34a2ab1af28d97654", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5.3c_matrix_multiplication.py", "max_issues_repo_name": "bayu-wilson/phys218_example", "max_issues_repo_head_hexsha": "f6d624d0747c42b29e9855c34a2ab1af28d97654", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5.3c_matrix_multiplication.py", "max_forks_repo_name": "bayu-wilson/phys218_example", "max_forks_repo_head_hexsha": "f6d624d0747c42b29e9855c34a2ab1af28d97654", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9238095238, "max_line_length": 108, "alphanum_fraction": 0.7064983061, "include": true, "reason": "import numpy", "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159683, "lm_q2_score": 0.9241418236349501, "lm_q1q2_score": 0.8783145335022117}}
{"text": "import numpy\n\n\ndef cos2degree(cos) -> float:\n    \"\"\"\n    Convert cosine to degree. Support float, List[float], numpy.ndarray[float]\n    :param cos:\n    :return:\n    \"\"\"\n    return numpy.arccos(cos) / numpy.pi * 180\n\n\ndef cos_angle(left_side: float, right_side: float, third_side: float) -> float:\n    \"\"\"\n    Calculate cos of angle if give 3 side of triangle\n    \"\"\"\n    return (left_side ** 2 + right_side ** 2 - third_side ** 2) / (2 * left_side * right_side)\n\n\ndef degree_angle(left_side: float, right_side: float, third_side: float) -> float:\n    \"\"\"\n    Calculate degree of angle if give 3 side of triangle\n    \"\"\"\n    return cos2degree(cos_angle(left_side, right_side, third_side))\n\n\ndef cos_triangle(first_side, second_side, third_side):\n    \"\"\"\n    Calculate 3 angles's cos of triangle\n    \"\"\"\n    first_angle = cos_angle(second_side, third_side, first_side)\n    second_angle = cos_angle(first_side, third_side, second_side)\n    third_angle = cos_angle(first_side, second_side, third_side)\n    return first_angle, second_angle, third_angle\n\n\ndef degree_triangle(first_side, second_side, third_side):\n    return cos2degree(cos_triangle(first_side, second_side, third_side))\n", "meta": {"hexsha": "69b4fedcfaac1d0b1081a5d963d4756f9e814054", "size": 1181, "ext": "py", "lang": "Python", "max_stars_repo_path": "dpsutil/triangle/tool.py", "max_stars_repo_name": "connortran216/DPS_Util", "max_stars_repo_head_hexsha": "8e6af59c3cc5d4addf3694ee0dfede08206ec4b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-19T03:14:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T03:14:42.000Z", "max_issues_repo_path": "dpsutil/triangle/tool.py", "max_issues_repo_name": "connortran216/DPS_Util", "max_issues_repo_head_hexsha": "8e6af59c3cc5d4addf3694ee0dfede08206ec4b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-27T09:50:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-27T09:50:33.000Z", "max_forks_repo_path": "dpsutil/triangle/tool.py", "max_forks_repo_name": "connortran216/DPS_Util", "max_forks_repo_head_hexsha": "8e6af59c3cc5d4addf3694ee0dfede08206ec4b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-03-24T02:49:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-26T04:05:06.000Z", "avg_line_length": 30.2820512821, "max_line_length": 94, "alphanum_fraction": 0.7053344623, "include": true, "reason": "import numpy", "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9799765581257485, "lm_q2_score": 0.8962513668985, "lm_q1q2_score": 0.8783053297486895}}
{"text": "#!/usr/bin/python\n\n#############################################################\n# Linear regressions: Polynomial basis functions #\n# Sk. Mashfiqur Rahman #\n#############################################################\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndata = np.loadtxt(\"crash.txt\")\ntraining = data[1::2]\ntest = data[0:-1:2]\ntraining_x = np.array(training[:, 0]).reshape(len(training), 1)\ntraining_t = np.array(training[:, 1]).reshape(len(training), 1)\ntest_x = np.array(test[:, 0]).reshape(len(training), 1)\ntest_t = np.array(test[:, 1]).reshape(len(training), 1)\nErms_training = np.zeros(20)\nErms_test = np.zeros(20)\nErms_reference_training = 1000.\nbest_w_training = 0\nbest_L_training = 0\nErms_reference_test = 1000.\nbest_w_test = 0\nbest_L_test = 0\n\n\nfor L in range(1,21):\n    phi = training_x**range(L)\n    w = np.linalg.solve(phi.T.dot(phi), phi.T.dot(training_t))\n    E_training = 0.5 * np.square(np.linalg.norm(training_t - phi.dot(w)))\n    Erms_training[L-1] = np.sqrt(2. * E_training / len(training))\n    if Erms_training[L-1] < Erms_reference_training:\n        Erms_reference_training = Erms_training[L-1]\n        best_L_training = L\n        best_w_training = w\n\n    phi = test_x**range(L)\n    E_test = 0.5 * np.square(np.linalg.norm(test_t - phi.dot(w)))\n    Erms_test[L-1] = np.sqrt(2. * E_test / len(training))\n    if Erms_test[L-1] < Erms_reference_test:\n        Erms_reference_test = Erms_test[L-1]\n        best_L_test = L\n        best_w_test = w\n\nprint('Maximum likelihood RMS error between the actual data and the models prediction (for Training sets): \\n')\nprint(Erms_training)\nprint('Maximum likelihood RMS error between the actual data and the models prediction (for Test sets): \\n')\nprint(Erms_test)\n\nplt.figure(figsize=(16,12))\nplt.plot(Erms_training, '-o', markerfacecolor='none', color='b', label='Training')\nplt.plot(Erms_test, '-o', markerfacecolor='none', color='r', label='Test')\nplt.suptitle('Maximum likelihood RMS error between the actual data and the models prediction', fontsize=24)\nplt.legend(fontsize=22)\nplt.xlabel(\"M \", fontsize = 22)\nplt.ylabel(\"Erms\", fontsize = 22)\nplt.show()\n\nx = np.linspace(start=np.min(training_x), stop= np.max(training_x), num=100).reshape(100, 1)\nphi = x**range(best_L_training)\ny = phi.dot(best_w_training)\nprint('Lowest RMS L for training data:', best_L_training)\n\nplt.figure(figsize=(16,12))\nplt.plot(training_x, training_t, color='b', label='Training data')\nplt.plot(x, y, color='r', label='Lowest RMS model output')\nplt.suptitle('Best fit on the training set', fontsize=24)\nplt.legend(fontsize=22)\nplt.xlabel(\"time \", fontsize = 22)\nplt.ylabel(\"acceleration\", fontsize = 22)\nplt.show()\n\nx = np.linspace(start=np.min(test_x), stop=np.max(test_x), num=100).reshape(100, 1)\nphi = x**range(best_L_test)\ny = phi.dot(best_w_test)\nprint('Lowest RMS L for test data:', best_L_test)\n\nplt.figure(figsize=(16,12))\nplt.plot(test_x, test_t, color='b', label='Test data')\nplt.plot(x, y, color='r', label='Lowest RMS model output')\nplt.suptitle('Best fit on the test set', fontsize=24)\nplt.legend(fontsize=22)\nplt.xlabel(\"time \", fontsize = 22)\nplt.ylabel(\"acceleration\", fontsize = 22)\nplt.show()\n", "meta": {"hexsha": "fa324aae4afef1cfca6a583651695f820301257c", "size": 3172, "ext": "py", "lang": "Python", "max_stars_repo_path": "prob1.py", "max_stars_repo_name": "mashfiq10/Linear-and-logistic-regression", "max_stars_repo_head_hexsha": "74ba478949d1ea6e9c9fea7deaec5347a28b1d54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prob1.py", "max_issues_repo_name": "mashfiq10/Linear-and-logistic-regression", "max_issues_repo_head_hexsha": "74ba478949d1ea6e9c9fea7deaec5347a28b1d54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prob1.py", "max_forks_repo_name": "mashfiq10/Linear-and-logistic-regression", "max_forks_repo_head_hexsha": "74ba478949d1ea6e9c9fea7deaec5347a28b1d54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0454545455, "max_line_length": 111, "alphanum_fraction": 0.6796973518, "include": true, "reason": "import numpy", "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846678676152, "lm_q2_score": 0.8976952818435994, "lm_q1q2_score": 0.8782913001728753}}
{"text": "import numpy as np\nimport kalman\nimport matplotlib.pyplot as plt\n\n### Part 1 ###\n# Consider a projectile object starting from (0,0) with initial velocity (300,600) m/s.\n# Suppose we have a gravitational acceleration in y of -9.8 m/s. \n# Suppose Q = 0.1*I, and R = 500*I, and delta t = 0.1.\n# Evolve the system forward 1200 steps and keep the states and observations.\n\nFk = np.array([[1.,0.,.1,0.],[0.,1.,0.,.1],[0.,0.,1.,0.],[0.,0.,0.,1.]])\nQ = np.eye(4)*.1\nU = np.array([0.,0.,0.,-.98])\nH = np.array([[1.,0.,0.,0.],[0.,1.,0.,0.]])\nR = np.eye(2)*500\n\nx_initial = np.array([0.,0.,300.,600.])\n\nstates, observations = kalman.generation(Fk,Q,U,H,R,x_initial,1250)\n\n### Part 2 ###\n# Suppose we are only able to see the observations from iteration 200 to 800.\n# Plot these observations as red points and the entire projectile path as a blue curve.\n\nplt.plot(observations[0,200:800],observations[1,200:800],'r.')\ntemp = np.array([x > -50 for x in states[1,:]])\nplt.plot(states[0,temp],states[1,temp],'b')\n\n### Part 3 ###\n# Supposing we only have the given observations, estimate the state of the system at \n# iteration 200, using the average of the measured velocities from iteration 200 to 210.\n# Estimate the position of the projectile given this initial state estimate, using P = 10^6 * Q.\n# Add to the plot the estimated path of the projectile as a green curve.\n\nvel = np.array([np.mean(np.diff(observations[0,200:210])/.1),np.mean(np.diff(observations[1,200:210])/.1)])\nx_est_initial = np.concatenate([observations[:,200],vel])\n\nestimation = kalman.kalmanFilter(Fk,Q,U,H,R,x_est_initial,Q*(10**6),observations[:,200:800])\n\nplt.plot(estimation[0,:],estimation[1,:],'g')\n\n### Part 4 ###\n# Given the final state estimate at iteration 800, iterate forward predictively to find the \n# projectile's point of impact. Plot this with a yellow curve.\n\nprediction = kalman.predict(Fk,U,estimation[:,599],500)\ntemp = np.array([x > -50 for x in prediction[1,:]])\nplt.plot(prediction[0,temp],prediction[1,temp],'y')\n\n### Part 4 ###\n# Given the state estimate at iteration 250, rewind the system to identify the\n# projectile's point of origin. Plot this with a cyan curve, and display the results.\n\nrewound = kalman.rewind(Fk,U,estimation[:,50],300)\ntemp = np.array([x > -50 for x in rewound[1,:]])\nplt.plot(rewound[0,temp],rewound[1,temp],'c')\nplt.ylim([0,20000])\n", "meta": {"hexsha": "f4a894468bed68a4450317de2c4d84ffed2fe7fb", "size": 2348, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/ProjectileTracking/solutions.py", "max_stars_repo_name": "m4webb/numerical_computing", "max_stars_repo_head_hexsha": "d26e5ace9dbb91cd87440d84f0bd05d4a46e6781", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Labs/ProjectileTracking/solutions.py", "max_issues_repo_name": "m4webb/numerical_computing", "max_issues_repo_head_hexsha": "d26e5ace9dbb91cd87440d84f0bd05d4a46e6781", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/ProjectileTracking/solutions.py", "max_forks_repo_name": "m4webb/numerical_computing", "max_forks_repo_head_hexsha": "d26e5ace9dbb91cd87440d84f0bd05d4a46e6781", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-08T01:19:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T01:19:23.000Z", "avg_line_length": 40.4827586207, "max_line_length": 107, "alphanum_fraction": 0.6925042589, "include": true, "reason": "import numpy", "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241956308277, "lm_q2_score": 0.9059898216525933, "lm_q1q2_score": 0.8781978551231171}}
{"text": "import numpy as np\n\nfrom lazylog import LazyLog\n\n\nclass PCA(LazyLog):\n    def __init__(self, dataset: np.ndarray):\n        \"\"\"\n        :param dataset: A dataset, which is a matrix with the shape of (N x M), where:\n                - N: number of samples\n                - M: number of features\n        \"\"\"\n        # Get the shape of the input data\n        super().__init__()\n        assert len(dataset.shape) == 2\n        self._n_samples, self._n_features = dataset.shape\n        self.logger.info({\n            'msg': 'Shape of input data',\n            'value': dataset.shape\n        })\n\n        # Change mean to zero\n        self._mean = np.mean(dataset, axis=0)\n        self._dataset = dataset - self._mean\n\n        # Calculate covariance matrix of features\n        self._covariance_matrix = (1 / (self._n_samples - 1)) * np.matmul(dataset.transpose(), self._dataset)\n        assert self._covariance_matrix.shape == (self._n_features, self._n_features)\n        self.logger.debug({\n            'msg': 'Covariance matrix',\n            'shape': self._covariance_matrix.shape,\n            'matrix': self._covariance_matrix.tolist()\n        })\n\n        # Find eigenvectors and eigenvalues of the covariance matrix (which are the candidates of principal components)\n        # Notes: technically in this context, eigenvectors are column vectors\n        self._eigenvalues, self._eigenvectors = np.linalg.eig(self._covariance_matrix)\n        self._component_indices = np.flip(np.argsort(self._eigenvalues))\n        self._eigenvalues = self._eigenvalues[self._component_indices]\n        self._eigenvectors = self._eigenvectors[:, self._component_indices]\n        for i in range(self._n_features):\n            self.logger.debug({\n                'msg': '{}-th component'.format(i),\n                'value': self._eigenvalues[i],\n                'vector': self._eigenvectors[:, i].tolist()\n            })\n        self.logger.debug({\n            'msg': 'Assert orthogonal characteristics',\n            'basis': np.matmul(self._eigenvectors, self._eigenvectors.transpose()).tolist()\n        })\n\n    def project(self, vectors: np.ndarray, n_reduced_features: int) -> np.ndarray:\n        \"\"\"\n        :param vectors: A dataset, which is a matrix with the shape of (N x M), where:\n                - N: number of samples\n                - M: number of features\n        :param n_reduced_features: An integer, which is number of features to be reduced\n        \"\"\"\n        # Assert shape of vectors\n        assert len(vectors.shape) == 2\n        assert vectors.shape[1] == self._n_features\n        assert n_reduced_features < len(self._eigenvalues)\n        return np.matmul(vectors - self._mean, self._eigenvectors[:, :n_reduced_features])\n\n    def project_and_restore(self, vectors: np.ndarray, n_reduced_features: int) -> np.ndarray:\n        \"\"\"\n        :param vectors: A dataset, which is a matrix with the shape of (N x M), where:\n                - N: number of samples\n                - M: number of features\n        :param n_reduced_features: An integer, which is number of features to be reduced\n        \"\"\"\n        projected = self.project(vectors, n_reduced_features)\n        return np.matmul(projected, self._eigenvectors[:, :n_reduced_features].transpose()) + self._mean\n", "meta": {"hexsha": "e2ddbaa96d229231b6e436c2316ccfa74b70a3b5", "size": 3261, "ext": "py", "lang": "Python", "max_stars_repo_path": "pca.py", "max_stars_repo_name": "huy-quoc-nguyen/DIP-PCA", "max_stars_repo_head_hexsha": "e7e619628881d7098a21bcebe3cc21712e171bba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pca.py", "max_issues_repo_name": "huy-quoc-nguyen/DIP-PCA", "max_issues_repo_head_hexsha": "e7e619628881d7098a21bcebe3cc21712e171bba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pca.py", "max_forks_repo_name": "huy-quoc-nguyen/DIP-PCA", "max_forks_repo_head_hexsha": "e7e619628881d7098a21bcebe3cc21712e171bba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0675675676, "max_line_length": 119, "alphanum_fraction": 0.6191352346, "include": true, "reason": "import numpy", "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350252, "lm_q2_score": 0.9111797009670495, "lm_q1q2_score": 0.8781767212949919}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nExample solutions for Worksheet 1\n\nIan Hawke\n\"\"\"\n\ndef MatrixConditionCheck(A):\n    import numpy as np\n\n    MaxConditionNumber = 10 # This is absurdly low    \n    ConditionNumber = np.linalg.cond(A)\n    if ConditionNumber > MaxConditionNumber:\n        print \"Condition number of matrix\\n\", A, \"\\ntoo large (bigger than\", MaxConditionNumber, \").\\n\"\n    \n\nimport numpy as np\n\nprint \"\\nQuestion 1\\n\"\n\nA1 = np.array([[1,2],[3,4]])\nA1T = np.transpose(A1)\nA1I = np.linalg.inv(A1)\nprint \"The matrix\\n\", A1, \"\\nhas transpose\\n\", A1T, \"\\nand inverse\\n\", A1I\n\nA2 = np.array([[-3,2],[3,6]])\nA2T = np.transpose(A2)\nA2I = np.linalg.inv(A2)\nprint \"The matrix\\n\", A2, \"\\nhas transpose\\n\", A2T, \"\\nand inverse\\n\", A2I\n\nprint \"\\nQuestion 2\\n\"\n\nv1 = np.array([1,3,-1])\nv2 = np.array([1,-2])\nv3 = np.array([1,6,-3,1])\n\nprint \"The vector\\n\", v1, \"\\nhas norms\", np.linalg.norm(v1,1), np.linalg.norm(v1,2), np.linalg.norm(v1,np.inf)\nprint \"The vector\\n\", v2, \"\\nhas norms\", np.linalg.norm(v2,1), np.linalg.norm(v2,2), np.linalg.norm(v2,np.inf)\nprint \"The vector\\n\", v3, \"\\nhas norms\", np.linalg.norm(v3,1), np.linalg.norm(v3,2), np.linalg.norm(v3,np.inf)\n\nprint \"The matrix\\n\", A1, \"\\nhas norms\", np.linalg.norm(A1,1), np.linalg.norm(A1,np.inf)\nprint \"The matrix\\n\", A2, \"\\nhas norms\", np.linalg.norm(A2,1), np.linalg.norm(A2,np.inf)\n\nprint \"\\nQuestion 3\\n\"\n\nMatrixConditionCheck(A1)\nMatrixConditionCheck(A2)\n\nprint \"\\nQuestion 4\\n\"\n\n# Bisection algorithm\n\ntolerance = 1e-15\n# Define the function\nf = lambda x: np.tan(x) - np.exp(-x)\n# Define the interval\nx_min = 0.0\nx_max = 1.0\n# Values at the ends of the domain\nf_min = f(x_min)\nf_max = f(x_max)\nassert(f_min * f_max < 0.0)\n# The loop\nx_c = (x_min + x_max) / 2.0\nf_c = f(x_c)\niteration = 0\nwhile ((x_max - x_min > tolerance) and (np.abs(f_c) > tolerance) and (iteration < 100)):\n    iteration = iteration+1    \n    if f_min * f_c < 0.0:\n        x_max = x_c\n        f_max = f_c\n    else:\n        x_min = x_c\n        f_min = f_c\n    x_c = (x_min + x_max) / 2.0\n    f_c = f(x_c)\n#    print \"Iteration \", iteration, \" x \", x_c, \" f \", f_c\n\nprint \"The root is approximately \", x_c, \" where f is \", f_c\n", "meta": {"hexsha": "cb951dbfcc7e325885f53eaa1d20b07acf69916d", "size": 2155, "ext": "py", "lang": "Python", "max_stars_repo_path": "Worksheets/Worksheet1_Answers.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Worksheets/Worksheet1_Answers.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Worksheets/Worksheet1_Answers.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 26.9375, "max_line_length": 110, "alphanum_fraction": 0.6357308585, "include": true, "reason": "import numpy", "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.9334308110294983, "lm_q1q2_score": 0.8781621402084073}}
{"text": "import math\nimport numpy as np\n\ndef R_x(theta):\n    '''\n    rotate about x-axis\n    '''\n    return np.array([[1, 0, 0],\n                     [0, np.cos(theta), -np.sin(theta)],\n                     [0, np.sin(theta), np.cos(theta)]])\n\n\ndef R_y(theta):\n    '''\n    rotate about y-axis\n    '''\n    return np.array([[np.cos(theta), 0, np.sin(theta)],\n                     [0, 1, 0],\n                     [-np.sin(theta), 0, np.cos(theta)]])\n\n\ndef R_z(theta):\n    '''\n    rotate about z-axis\n    '''\n    return np.array([[np.cos(theta), -np.sin(theta), 0],\n                     [np.sin(theta), np.cos(theta), 0],\n                     [0, 0, 1]])\n\n\ndef normalize_array(arr):\n    '''\n    normalize a 1D array of values so the largest value is 1\n    '''\n\n    arr_nrm = (1/np.amax(arr))*arr\n\n    return arr_nrm\n\n\ndef print_matrix_as_latex(mat, n_digs=3):\n    '''\n    print a matrix in latex form\n    inputs:\n        mat: matrix, n_digs: number of digits in largest value\n    '''\n    n_rows, n_cols = mat.shape\n    mat_max = np.amax(mat) # max value in matrix\n    max_pow = int(np.floor(np.log10(mat_max))) # max value power of 10\n    # power of 10 to divide matrix by so largest element is in range [100,999]\n    scl_pow = max_pow - (n_digs - 1)\n    scl = 10**scl_pow # value to divide matrix by\n    mat_scl = mat/scl\n\n    # print in latex form\n    print('10^{' + str(scl_pow) + '} \\\\times')\n    print(r'\\begin{bmatrix}')\n    for i in range(n_cols):\n        for j in range(n_rows):\n            if j < n_rows - 1:\n                print('%.0f' %  mat_scl[i, j], '& ', end='')\n            else: # last row\n                if i < n_rows - 1:\n                    print('%.0f' %  mat_scl[i, j], '\\\\\\ ')\n                else: # last column and last row\n                    print('%.0f' %  mat_scl[i, j])\n    print(r'\\end{bmatrix}')\n", "meta": {"hexsha": "3ff53891817e29b50b74c0bfe0684002d4b3933f", "size": 1817, "ext": "py", "lang": "Python", "max_stars_repo_path": "pose_estimation/tools/math.py", "max_stars_repo_name": "uwaa-ndcl/ACC_2019_Avant", "max_stars_repo_head_hexsha": "d03e3715a030e52135baa9bf4e6a4d7a8b2c0881", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pose_estimation/tools/math.py", "max_issues_repo_name": "uwaa-ndcl/ACC_2019_Avant", "max_issues_repo_head_hexsha": "d03e3715a030e52135baa9bf4e6a4d7a8b2c0881", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pose_estimation/tools/math.py", "max_forks_repo_name": "uwaa-ndcl/ACC_2019_Avant", "max_forks_repo_head_hexsha": "d03e3715a030e52135baa9bf4e6a4d7a8b2c0881", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7205882353, "max_line_length": 78, "alphanum_fraction": 0.5063291139, "include": true, "reason": "import numpy", "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692366242304, "lm_q2_score": 0.8991213833519949, "lm_q1q2_score": 0.8781441951109149}}
{"text": "import numpy as np\n\n# CRIAÇÃO DE DOIS ARRAYS X E Y\nprint(\"\\nCRIAÇÃO DE DOIS ARRAYS X E Y!!\\n\")\nx = np.ones((2, 2))\ny = np.eye(2)\nprint(\"x : \\n\", x)\nprint('y: \\n', y)\n\n# multiplicações\nprint('\\n***MULTIPLICAÇÕES***\\n')\nprint('multiplicação de dois arrays: \\n ', x * y)\nprint(\"multiplicação com float/int:\\n\", x * 2) #broadcasting\n\n# multiplicação matricial\nprint('\\n*** MULTIPLICAÇÃO MATRICIAL***\\n')\nprint('multiplicação matricial (np.dot): \\n', np.dot(x, y))\nprint('multiplicação matricial (@): \\n', x @ y)\nprint('multiplicação matricial (.dot): \\n', x.dot(y))\nprint('\\n\\n')\n'''\nExemplo:\n\nSolução de um sistema de equações:\n    a + 2*b = 7\n    3*a - 2*b = -11\n\n    solução analitica: (a,b) = (-1, 4)\n\nMatricialmente, este problema te a seguinte forma:\n    Ax =c, onde: \n    - x = [a, b]\n    - A = [[1, 2], [3, 2]]\n    - c = [7, -11]\n    solução numérica: x = inv(A) @ c, \n\n\n'''\n# Defição do problema\n\nprint('Definição do Problema!')\nA = np.array ([[1, 2], [3, -2]])\nc = np.array([[7], [-11]])\nprint('A: \\n', A)\nprint(\"c: \\n\", c)\n\n# solução\nx = np.dot(np.linalg.inv(A), c)\n# x = np.linalg.inv(A) @ c\nprint('(a, b):', x.ravel())\n", "meta": {"hexsha": "c2844d575d6b97155b61bd328c309f0401c6c84f", "size": 1128, "ext": "py", "lang": "Python", "max_stars_repo_path": "mod2OparitMulteleWiseeMatricial.py", "max_stars_repo_name": "leonarddepaula/Projetos", "max_stars_repo_head_hexsha": "6908f875a181e42e554f46171d946713ba88ef58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mod2OparitMulteleWiseeMatricial.py", "max_issues_repo_name": "leonarddepaula/Projetos", "max_issues_repo_head_hexsha": "6908f875a181e42e554f46171d946713ba88ef58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mod2OparitMulteleWiseeMatricial.py", "max_forks_repo_name": "leonarddepaula/Projetos", "max_forks_repo_head_hexsha": "6908f875a181e42e554f46171d946713ba88ef58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1176470588, "max_line_length": 60, "alphanum_fraction": 0.579787234, "include": true, "reason": "import numpy", "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877684006774, "lm_q2_score": 0.9046505428129514, "lm_q1q2_score": 0.8781332165855653}}
{"text": "from numpy.linalg import matrix_rank\r\nimport numpy as np\r\n\r\nfrom toolbox.centerCols import *\r\n\r\n\r\ndef pcaPmtk(X, K=None, method=None):\r\n    n, d = X.shape\r\n    if method is None:\r\n        cost = np.array([d**3, n**3, min(n*d**2, d*n**2)])\r\n        method = np.argmin(cost) + 1\r\n    methodNames = ['eig(Xt X)', 'eig(X Xt)', 'SVD(X)']\r\n    print(\"Using method %s\" % methodNames[method - 1])\r\n    XCenter, mu = centerCols(X)\r\n    if K is None:\r\n        K = matrix_rank(XCenter)\r\n    if method == 1:\r\n        cov_matrix = np.cov(XCenter, rowvar=False, bias=True)\r\n        evals, evec = np.linalg.eig(cov_matrix)\r\n        sorted_idx = np.argsort(-evals)\r\n        evals = evals[sorted_idx]\r\n        evec = evec[:, sorted_idx]\r\n        B = evec[:, 0:K]\r\n    elif method == 2:\r\n        w = np.dot(XCenter, XCenter.T)\r\n        evals, evec = np.linalg.eig(w)\r\n        sorted_idx = np.argsort(-evals)\r\n        evals = evals[sorted_idx]\r\n        evec = evec[:, sorted_idx]\r\n        B = np.dot(np.dot(X.T, evec), np.diag(1. / np.sqrt(evals)))\r\n        B = B[:, 0:K]\r\n        evals = evals / n\r\n        r = np.linalg.matrix_rank(XCenter)\r\n        evals[r:] = 0\r\n    elif method == 3:\r\n        if n > d:\r\n            full_matrices = False\r\n        else:\r\n            full_matrices = True\r\n        u, s, vh = np.linalg.svd(XCenter, full_matrices=full_matrices)\r\n        B = vh.T[:, 0:K]\r\n        evals = 1/n * np.square(s)\r\n    Z = np.dot(XCenter, B)\r\n    Xrecon = np.dot(Z, B.T) + mu\r\n    return B, Z, evals, Xrecon, mu\r\n\r\n\r\nif __name__ == '__main__':\r\n    # octave\r\n    # X = [[2, 8, 3, 4, 9]; [6, 3, 5, 8, 2]; [1, 4, 5, 9, 3]; [5, 5, 1, 2, 7]]\r\n    # [B, Z, evals, Xrecon, mu] = pcaPmtk(X, 2, 1)\r\n    # -0.025365  - 0.78857\r\n    # 0.35044    0.36752\r\n    # -0.3313    0.23639\r\n    # -0.60956    0.36123\r\n    # 0.62866    0.23814\r\n    X = np.array([[2, 8, 3, 4, 9], [6, 3, 5, 8, 2], [1, 4, 5, 9, 3], [5, 5, 1, 2, 7]])\r\n    B, Z, evals, Xrecon, mu = pcaPmtk(X, 2, 3)\r\n    print(B, Z)", "meta": {"hexsha": "1231ab89d77e4fc0112f5766c4235d9ab914ab73", "size": 1968, "ext": "py", "lang": "Python", "max_stars_repo_path": "practice/toolbox/pcaPmtk.py", "max_stars_repo_name": "colinzuo/MLAPP_Solution", "max_stars_repo_head_hexsha": "6d4bab23455169310547462fe2fc2cb71a915ef0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-07-22T18:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T18:07:49.000Z", "max_issues_repo_path": "practice/toolbox/pcaPmtk.py", "max_issues_repo_name": "colinzuo/MLAPP_Solution", "max_issues_repo_head_hexsha": "6d4bab23455169310547462fe2fc2cb71a915ef0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practice/toolbox/pcaPmtk.py", "max_forks_repo_name": "colinzuo/MLAPP_Solution", "max_forks_repo_head_hexsha": "6d4bab23455169310547462fe2fc2cb71a915ef0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3559322034, "max_line_length": 87, "alphanum_fraction": 0.5020325203, "include": true, "reason": "import numpy,from numpy", "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574668, "lm_q2_score": 0.9161096067182449, "lm_q1q2_score": 0.8781256225411013}}
{"text": "import numpy as np\n\n#勾配を求める関数\ndef numerical_gradient(f, x):\n    h = 1e-4\n    grad = np.zeros_like(x)\n    \n    for i in range(x.size):\n        v = x[i]\n        \n        x[i] = v + h\n        f1 = f(x)\n        \n        x[i] = v - h\n        f2 = f(x)\n        \n        grad[i] = (f1 - f2) / (2 * h)\n        x[i] = v\n    \n    return grad\n\ndef function_2(x):\n    return np.sum(x**2)\n\nprint(numerical_gradient(function_2, np.array([3.0, 4.0])))\nprint(numerical_gradient(function_2, np.array([0.0, 2.0])))\nprint(numerical_gradient(function_2, np.array([3.0, 0.0])))\n\n#勾配降下法\ndef gradient_descent(f, init_x, lr=0.01, step_num=100):\n    x = init_x\n    \n    for i in range(step_num):\n        x -= lr * numerical_gradient(f, x)\n    \n    return x\n\ninit_x = np.array([-3.0, 4.0])\nprint(gradient_descent(function_2, init_x, lr=0.1, step_num=100))\nprint(gradient_descent(function_2, init_x, lr=10, step_num=100))\nprint(gradient_descent(function_2, init_x, lr=1e-10, step_num=100))\n\n#重要なのは微分の特性を思い出すこと\n#ほんのちょっとだけxを動かしたらyがどれだけ変化するか\n#傾き\n#微分の数学的典型的解(x^2 > 2x, x > 1, e^x > e^x)\n", "meta": {"hexsha": "0fbd7d4944d7d171e9de9eab4078069dd4db2875", "size": 1056, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/src/zero/gradient_descent.py", "max_stars_repo_name": "d-ikeda-sakurasoft/deep-learning", "max_stars_repo_head_hexsha": "e253d11bafa34bb0260bb655268054534cc8cff6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/src/zero/gradient_descent.py", "max_issues_repo_name": "d-ikeda-sakurasoft/deep-learning", "max_issues_repo_head_hexsha": "e253d11bafa34bb0260bb655268054534cc8cff6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/src/zero/gradient_descent.py", "max_forks_repo_name": "d-ikeda-sakurasoft/deep-learning", "max_forks_repo_head_hexsha": "e253d11bafa34bb0260bb655268054534cc8cff6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4680851064, "max_line_length": 67, "alphanum_fraction": 0.5956439394, "include": true, "reason": "import numpy", "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377261041521, "lm_q2_score": 0.9161096055730491, "lm_q1q2_score": 0.8781256181881621}}
{"text": "import numpy as np\n\n\ndef Heaviside(z):\n    ''' Heaviside function.\n        @params:\n            z : float values  -- required\n        @return:\n            1 if z is greater or equal to 0 and 0 in other case'''\n    return 1 * (z >= 0)\n\ndef d_Heaviside(z):\n    return 0\n\n\ndef sgn(z):\n    '''Sign function\n        @params:\n            z : float values -- required\n        @return:\n            1 if z is greater or equal to 0 and -1 in other case'''\n    return 2 * Heaviside(z) - 1\n\ndef d_sgn(z):\n    return 0\n\n\ndef saturation_function(z):\n    ''' Saturation function:\n        @params:\n            z : float values -- required\n        @return:\n            1 if z is greater than 1, z if z is lower or equal than 1 and greater\n             or equal than -1 and -1 in other case'''\n    x = 1 * (z > 1)\n    y = -1 * (z < -1)\n    w = (abs(z) <= 1) * z\n    return x + y + w\n\ndef d_saturation_function(z):\n    return 1\n\ndef logistic(z, s=1):\n    ''' Logistic function:\n        @params:\n            z : float values -- required\n            s : weight  -- float values -- required\n        @return:\n            return the logistic function values '''\n    return 1. / (1. + np.exp(-s * z))\n\n\ndef sigmoid(z, s=1):\n    ''' Sigmoid function:\n        @params:\n            z : float values -- required\n            s : weight -- float values -- required\n        @return:\n            return thte sigmoid values'''\n    return s * logistic(z, s) * (1 - logistic(z, s))\n\n\ndef tanh(z):\n    ''' Hiperbolic tangent function:\n        @params:\n            z : float values -- required\n        @return:\n            return the tanh values'''\n    return 2 * logistic(z, 2) - 1\n\ndef d_tanh(z):\n    return 1 - tanh(z) * tanh(z)\n\n\ndef relu(z, smoothed=False):\n    ''' REctified Linear Units:\n        It's a no lineal activation function that is defined like:\n                           [ z  if z >= 0\n                    f(z) = |\n                           [ 0  if z < 0\n\n        @params:\n            z : float values -- required\n        @return:\n            return the tanh values\n        '''\n    if smoothed:\n        return np.log(1 + np.exp(z))\n    else:\n        return (z > 0) * z\n\ndef d_relu(z, smoothed=False):\n    if smoothed:\n        return z * np.exp(z) / (1 + relu(z, smoothed))\n    else:\n        return (z > 0) * 1\n\n\nact_func = {\n            'heaviside': Heaviside,\n            'sgn': sgn,\n            'saturation_function': saturation_function,\n            'sigmoid': logistic,\n            'tanh': tanh,\n            'relu': relu\n}\n\nder_act_func = {\n            'heaviside': d_Heaviside,\n            'sgn': d_sgn,\n            'saturation_function': d_saturation_function,\n            'sigmoid': sigmoid,\n            'tanh': d_tanh,\n            'relu': d_relu\n}", "meta": {"hexsha": "ee5117afc70c981721c7d171a8add0f79bfeab15", "size": 2736, "ext": "py", "lang": "Python", "max_stars_repo_path": "number_recognition/activation_function/functions.py", "max_stars_repo_name": "Limman89/neural_networks", "max_stars_repo_head_hexsha": "8cf427302841c613f4de41f86c9580a24b8fb88f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "number_recognition/activation_function/functions.py", "max_issues_repo_name": "Limman89/neural_networks", "max_issues_repo_head_hexsha": "8cf427302841c613f4de41f86c9580a24b8fb88f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "number_recognition/activation_function/functions.py", "max_forks_repo_name": "Limman89/neural_networks", "max_forks_repo_head_hexsha": "8cf427302841c613f4de41f86c9580a24b8fb88f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7913043478, "max_line_length": 81, "alphanum_fraction": 0.4956140351, "include": true, "reason": "import numpy", "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288128, "lm_q2_score": 0.9173026505426832, "lm_q1q2_score": 0.8781134699684081}}
{"text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef make_default_q_curve(Snom, Qmin, Qmax, n=3):\n    \"\"\"\n    Compute the generator capability curve\n    :param Snom: Nominal power\n    :param Qmin: Minimum reactive power\n    :param Qmax: Maximum reactive power\n    :param n: number of points, at least 3\n    :return: Array of points [(P1, Qmin1, Qmax1), (P2, Qmin2, Qmax2), ...]\n    \"\"\"\n    assert(n > 2)\n\n    pts = np.zeros((n, 3))\n    s2 = Snom * Snom\n\n    # Compute the intersections of the Qlimits with the natural curve\n    p0_max = np.sqrt(s2 - Qmax * Qmax)\n    p0_min = np.sqrt(s2 - Qmin * Qmin)\n    p0 = min(p0_max, p0_min)  # pick the lower limit as the starting point for sampling\n\n    pts[1:, 0] = np.linspace(p0, Snom, n - 1)\n    pts[0, 0] = 0\n    pts[0, 1] = Qmin\n    pts[0, 2] = Qmax\n\n    for i in range(1, n):\n        p2 = pts[i, 0] * pts[i, 0]  # P^2\n        q = np.sqrt(s2 - p2)  # point that naturally matches Q = sqrt(S^2 - P^2)\n\n        # assign the natural point if it does not violates the limits imposes, else set the limit\n        qmin = -q if -q > Qmin else Qmin\n        qmax = q if q < Qmax else Qmax\n\n        # Enforce that Qmax > Qmin\n        if qmax < qmin:\n            qmax = qmin\n        if qmin > qmax:\n            qmin = qmax\n\n        # Assign the points\n        pts[i, 1] = qmin\n        pts[i, 2] = qmax\n\n    return pts\n\n\ndef get_q_limits(q_points, p):\n    \"\"\"\n    Get the reactive power limits\n    :param q_points: Array of points [(P1, Qmin1, Qmax1), (P2, Qmin2, Qmax2), ...]\n    :param p: active power value (or array)\n    :return:\n    \"\"\"\n    all_p = q_points[:, 0]\n    all_qmin = q_points[:, 1]\n    all_qmax = q_points[:, 2]\n\n    qmin = np.interp(p, all_p, all_qmin)\n    qmax = np.interp(p, all_p, all_qmax)\n\n    return qmin, qmax\n\n\nSnom = 650\npoints = make_default_q_curve(Snom=Snom, Qmin=-100, Qmax=300)\n\n# plot the capability curve\np = points[:, 0]\nqmin = points[:, 1]\nqmax = points[:, 2]\nplt.plot(qmax, p, 'x-')\nplt.plot(qmin, p, 'x-')\n\n# generate random points and interpolate the curve to get the reactive power limits\np2 = np.random.random(10) * Snom\nqmin2, qmax2 = get_q_limits(q_points=points, p=p2)\nplt.plot(qmax2, p2, 'o')\nplt.plot(qmin2, p2, 'o')\n\nplt.show()\n", "meta": {"hexsha": "33722a8c4916323fa3b434757683a8fbc9d77a53", "size": 2218, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/research/generator/reactive_power_curve.py", "max_stars_repo_name": "mzy2240/GridCal", "max_stars_repo_head_hexsha": "0352f0e9ce09a9c037722bf2f2afc0a31ccd2880", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 284, "max_stars_repo_stars_event_min_datetime": "2016-01-31T03:20:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T21:16:52.000Z", "max_issues_repo_path": "src/research/generator/reactive_power_curve.py", "max_issues_repo_name": "mzy2240/GridCal", "max_issues_repo_head_hexsha": "0352f0e9ce09a9c037722bf2f2afc0a31ccd2880", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 94, "max_issues_repo_issues_event_min_datetime": "2016-01-14T13:37:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T03:13:56.000Z", "max_forks_repo_path": "src/research/generator/reactive_power_curve.py", "max_forks_repo_name": "mzy2240/GridCal", "max_forks_repo_head_hexsha": "0352f0e9ce09a9c037722bf2f2afc0a31ccd2880", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 84, "max_forks_repo_forks_event_min_datetime": "2016-03-29T10:43:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T16:26:55.000Z", "avg_line_length": 26.4047619048, "max_line_length": 97, "alphanum_fraction": 0.6009918846, "include": true, "reason": "import numpy", "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104933824754, "lm_q2_score": 0.9086179025005187, "lm_q1q2_score": 0.8780978754516762}}
{"text": "import numpy as np\n\n# matrix_size = n x n\ndef build_magic_squares(matrix_size):\n\tmagic_square = np.zeros((matrix_size, matrix_size), dtype=int)\n\n\tn = 1\n\ti = 0\n\tj = matrix_size // 2\n\n\twhile n <= matrix_size * matrix_size:\n\t\tmagic_square[i, j] = n\n\n\t\tn += 1\n\t\tii = (i - 1) % matrix_size\n\t\tjj = (j + 1) % matrix_size\n\n\t\tif magic_square[ii, jj]:\n\t\t\ti += 1\n\t\telse:\n\t\t\ti, j = ii, jj\n\n\treturn magic_square\n\tprint(\"\\n\")\n\n\n\n# Square formatting here:\ndef format_magic_square(magic_square):\n\tnice_list = [[\"%3s\" % str(str(j) + \" \") for j in i] for i in magic_square]\n\tfor line in nice_list:\n\t\tprint(\" \".join(map(str, line)))\n\n# Verification/test matrix\ndef magic_square_test(matrix):\n\tiSize = len(matrix[0])\n\tsum_list = []\n\n\t#Horizontal Part:\n\tsum_list.extend([sum(lines) for lines in matrix])\n\n\t#Vertical Part:\n\tfor col in range(iSize):\n\t\tsum_list.append(sum(row[col] for row in matrix))\n\n\t#Diagonals Part\n\tresult1 = 0\n\tfor i in range(0, iSize):\n\t\tresult1 += matrix[i][i]\n\tsum_list.append(result1)\n\n\tresult2 = 0\n\tfor i in range(iSize - 1, -1, -1):\n\t\tresult2 += matrix[i][i]\n\tsum_list.append(result2)\n\n\tif len(set(sum_list)) > 1:\n\t\treturn \"incorrect\"\n\treturn \"correct\"\n\n\ndef main(matrix_size):\n\tprint(\"\\n\")\n\tmagic_square = build_magic_squares(matrix_size)\n\tprint(\"\\n\")\n\tformat_magic_square(magic_square)\n\tprint(\"\\n\")\n\tprint(magic_square_test(magic_square))\n\n\nif __name__ == \"__main__\":\n\twhile True:\n\t\ttry:\n\t\t\tnum = int(input(\"Please enter a positive odd integer:  \"))\n\t\texcept ValueError:\n\t\t\tprint(\"Sorry, enter valid number\")\n\t\t\tcontinue\n\t\tif (num < 0) or (num % 2) == 0:\n\t\t\tprint(\"Sorry, your response must be positive odd number.\")\n\t\t\tcontinue\n\t\telse:\n\t\t\tbreak\n\nif (num % 2) == 1:\n\tmain(num)\n", "meta": {"hexsha": "b6e91a0e391aed50189fdb2a23d33087b7941bda", "size": 1684, "ext": "py", "lang": "Python", "max_stars_repo_path": "script.py", "max_stars_repo_name": "Anuoluwa/Magic_Squares_Builder", "max_stars_repo_head_hexsha": "7b631352af099dcd30df099e5cfdadb1ebd1b2ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script.py", "max_issues_repo_name": "Anuoluwa/Magic_Squares_Builder", "max_issues_repo_head_hexsha": "7b631352af099dcd30df099e5cfdadb1ebd1b2ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script.py", "max_forks_repo_name": "Anuoluwa/Magic_Squares_Builder", "max_forks_repo_head_hexsha": "7b631352af099dcd30df099e5cfdadb1ebd1b2ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5813953488, "max_line_length": 75, "alphanum_fraction": 0.6627078385, "include": true, "reason": "import numpy", "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.9284088045171237, "lm_q1q2_score": 0.8780902265556335}}
{"text": "# Question 1, Lab 6\n# AB Satyaprakash, 180123062\n\n# imports \nfrom sympy.abc import t,y\nimport numpy as np\nimport sympy as sp\nimport pandas as pd\n\n# functions \ndef getEulerApproximation(f,X,Y,h):\n    for i in range(1,Y.shape[0]):\n        Y[i]=Y[i-1] + (f.subs({t:X[i-1], y:Y[i-1]})*h)\n\ndef getActualValues(g,X):\n    for i in range(X.shape[0]):\n        Z[i]=g.subs(t,X[i])\n\n# program body\n# t belongs to [0,3] and y(0)=0, with h = 0.5\na, b, h = 0, 3, 0.5\nX = np.arange(a,b+h/2,h)\nY = np.zeros(X.shape[0])\nZ = np.zeros(X.shape[0])\nY[0] = 0\n\nf = -20*y + sp.cos(t) + 20*sp.sin(t) # from question\ng = sp.sin(t)\n\ngetEulerApproximation(f,X,Y,h)\ngetActualValues(g,X)\nprint('Approximate value of y({}) = {}'.format(3,Y[-1]))\nprint('The actual value of y({}) = {}'.format(3, Z[-1]))\nprint('The error in this case = {}'.format(abs(Y[-1]-Z[-1])))\n\n# Error bound is nh^2Y, where Y = 1/2(max|y\"(x)|) for x in {x0,x1..xn}\nfunc = sp.sin(t)\nfunc = sp.diff(sp.diff(func,t),t)\nn = X.shape[0]-1\nmaxi = 0\nfor x in X:\n    maxi=max(maxi,abs(func.subs(t,x)))\nK = maxi/2\nerrorBound = n*(h**2)*K\nprint('The error bound in this case = {}'.format(errorBound))\nprint('Clearly, absolute error with h = 0.5 greatly exceeds the error bound computed using (I) in Q4\\n')\n\n\nprint('If we reduce h by 10 times, i.e make it 0.05 we observe that:')\na, b, h = 0, 3, 0.05\nX = np.arange(a,b+h/2,h)\nY = np.zeros(X.shape[0])\nZ = np.zeros(X.shape[0])\nY[0] = 0\ngetEulerApproximation(f,X,Y,h)\ngetActualValues(g,X)\nprint('Approximate value of y({}) = {}'.format(3,Y[-1]))\nprint('The actual value of y({}) = {}'.format(3, Z[-1]))\nprint('The error in this case = {}'.format(abs(Y[-1]-Z[-1])))\n", "meta": {"hexsha": "34def9f13b2c7e3d6516a7320f68e4020898e6ef", "size": 1642, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 6/Code/q5.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 6/Code/q5.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 6/Code/q5.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 27.3666666667, "max_line_length": 104, "alphanum_fraction": 0.6132764921, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.9284087970889807, "lm_q1q2_score": 0.8780902195300864}}
{"text": "\"\"\"\nhttps://projecteuler.net/problem=12\nThe sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be\n1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:\n\n1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...\n\nLet us list the factors of the first seven triangle numbers:\n\n 1: 1\n 3: 1,3\n 6: 1,2,3,6\n10: 1,2,5,10\n15: 1,3,5,15\n21: 1,3,7,21\n28: 1,2,4,7,14,28\nWe can see that 28 is the first triangle number to have over five divisors.\n\nWhat is the value of the first triangle number to have over five hundred divisors?\n\"\"\"\nimport numpy as np\n\nfrom Common.Logger import get_logger, init_logger\nfrom Common.Utilities import performance_run\nfrom Common.Numbers import divisors\n\nPERFORMANCE_RUNS = 10\nDIVISOR_COUNT = 500\n\n# def fastest(...) -> ...:\n#     \"\"\"\n#     :return: ...\n#     \"\"\"\n#     return ...\n\n\ndef generative(divisor_count: int = DIVISOR_COUNT) -> int:\n    \"\"\"\n    This method starts from the beginning and performs a full search of triangular numbers to find the first one that\n    satisfies the minimum number of required divisors\n    :param divisor_count: This is the minimum number of divisors criteria that the solution has to find\n    :return: This is the number that satisfies the minimum number of divisors criteria\n    \"\"\"\n    divisor_list = []\n    i = 0\n    number = 0\n    while len(divisor_list) < divisor_count:\n        i += 1\n        number += i\n        divisor_list = divisors(number)\n    return number\n\n\ndef predictive(divisor_count: int = DIVISOR_COUNT) -> int:\n    \"\"\"\n    This method jumps ahead to a triangular number that could viable contain the number of divisors that are being\n    sought in the answer.\n    :param divisor_count: This is the minimum number of divisors criteria that the solution has to find\n    :return: This is the number that satisfies the minimum number of divisors criteria\n    \"\"\"\n    n = int((1 + np.sqrt(8*divisor_count + 1)) / 2)\n    n -= 1  # This primes the algorithm to start at the correct value\n    triangular_number = 0\n    divisor_list = []\n\n    while len(divisor_list) < divisor_count:\n        n += 1\n        triangular_number = int(n*(n+1)/2)\n        divisor_list = divisors(triangular_number)\n\n    return triangular_number\n\n\nif __name__ == \"__main__\":\n    # Log stuff\n    init_logger()\n    logger = get_logger()\n\n    # Performance run for fastest\n    performance_run(generative, iterations=PERFORMANCE_RUNS)()\n    performance_run(predictive, iterations=PERFORMANCE_RUNS)()\n", "meta": {"hexsha": "6f6d437c5556ff671f606009d76f147214955cc7", "size": 2484, "ext": "py", "lang": "Python", "max_stars_repo_path": "Solutions/Q0012_Highly_Divisible_Triangular_Number.py", "max_stars_repo_name": "SigfriedHache/euler-project", "max_stars_repo_head_hexsha": "7c38deee65a793a441830a6d0916da61e86b8cf7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Solutions/Q0012_Highly_Divisible_Triangular_Number.py", "max_issues_repo_name": "SigfriedHache/euler-project", "max_issues_repo_head_hexsha": "7c38deee65a793a441830a6d0916da61e86b8cf7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/Q0012_Highly_Divisible_Triangular_Number.py", "max_forks_repo_name": "SigfriedHache/euler-project", "max_forks_repo_head_hexsha": "7c38deee65a793a441830a6d0916da61e86b8cf7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2926829268, "max_line_length": 117, "alphanum_fraction": 0.6896135266, "include": true, "reason": "import numpy", "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541528387691, "lm_q2_score": 0.9324533149608596, "lm_q1q2_score": 0.8780485363611702}}
{"text": "#Central Limit Theorem states that dist. of sample mean is normally dist.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import expon,skewnorm\n\ndef get_data(n):\n    data = np.concatenate((expon.rvs(scale=1,size=n//2),skewnorm.rvs(5,loc=3,size=n//2)))\n    #getting exp dist data\n    #now shuffle the data\n    np.random.shuffle(data)\n    return data\n\nplt.hist(get_data(2000))    #not a gaussian,normal dist\nplt.show()\n\nd10 = get_data(10)\nprint(d10.mean())   #gives mean of 10 random numbers\n\nmeans = [get_data(10).mean() for i in range(10000)]\nplt.hist(means)\nplt.show()\nprint(\"Std. Dev.=\",np.std(means))\n\nmeans = [get_data(100).mean() for i in range(10000)]\nplt.hist(means)\nplt.show()  #this gives better result than before\nprint(\"Std. Dev. for 100 data point mean=\",np.std(means))\n\nnum_sample = [10,50,100,500,1000,5000,10000]\nstds=[]\nfor n in num_sample:\n    stds.append(np.std([get_data(n).mean() for i in range(1000)]))\nplt.plot(num_sample,stds,'o',label='Obs Scatter')\nplt.plot(num_sample,1/np.sqrt(num_sample),label='Random function',alpha=0.5)\n#standard deviation is related to inverse number of samples\nplt.legend()\nplt.show()\n\nplt.hist([get_data(100).mean() for i in range(100)])\nplt.show()\n#by changing the range to power of 10, you can observe that it reaches normal dist.\n#width depends on samples went into number(10,100,1000)\n\nn = 1000\ndata = get_data(n)\nsample_mean = np.mean(data)\nuncertainity_mean = np.std(data)/np.sqrt(n)\nprint(f\"We have determined the mean of population to be {sample_mean:0.2f} +- {uncertainity_mean:.2f}\")\n#1 sigma = 1 standard deviation away from mean, represented by +-\n\nfrom scipy.stats import norm\n\nxs = np.linspace(sample_mean -0.2,sample_mean+0.2,100)\nys = norm.pdf(xs,sample_mean,uncertainity_mean)\nplt.plot(xs,ys)\nplt.xlabel(\"population mean\")\nplt.ylabel(\"Probability\")\nplt.show()\n#normal distribution is always formed when sample size increases\n#using CLT, to provide uncertainity, is the most way it's used\n", "meta": {"hexsha": "be7817780a67c94d21ab8ccedd97347d2229f23a", "size": 1977, "ext": "py", "lang": "Python", "max_stars_repo_path": "central_limit.py", "max_stars_repo_name": "WestHamster/Feature_engg", "max_stars_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "central_limit.py", "max_issues_repo_name": "WestHamster/Feature_engg", "max_issues_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "central_limit.py", "max_forks_repo_name": "WestHamster/Feature_engg", "max_forks_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8870967742, "max_line_length": 103, "alphanum_fraction": 0.731917046, "include": true, "reason": "import numpy,from scipy", "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517061554855, "lm_q2_score": 0.9136765292901317, "lm_q1q2_score": 0.8779990196955745}}
{"text": "## NUMERICS ASSIGNMENT 4\n# ADVECTION\n\"\"\" Solving du/dt + du/dx = 0 \"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pylan as pn\n\n## set up the grid\ndx = .5\nxend = 30\nx = np.arange(0,xend+dx,dx)\nnx = len(x)\n\ntend = 10\n## analytical solution\ndef ua(t):\n    return (((x-t) >= 1.5) * ((x-t) <= 6.5))*1\n\n## set up LEFT-DERIVATIVE, CENTRED DERIVATIVE\nGl = (np.eye(nx) + np.diag(-np.ones(nx-1),-1))/dx\nGc = (np.diag(np.ones(nx-1),1) + np.diag(-np.ones(nx-1),-1))/2/dx\n\n#Gl[0,-1] = -1\n#Gc[0,-1] = -1\n#Gc[-1,0] = 1\n\n## forward in time, centred in space\ndef FTUP(nt,dt):\n    u = np.zeros((nt,nx))\n    u[0,:] = ((x >= 1.5) * (x <= 6.5))*1 #initial conditions\n    \n    for i in range(nt-1):\n        u[i+1,:] = u[i,:] - dt*Gl.dot(u[i,:])\n    \n    return u\n\n## leap frog in time, centered in space    \ndef LFCS(nt,dt):\n    u = np.zeros((nt,nx))\n    u[:2,:] = FTUP(2,dt) #use forward in time for n = 1\n    \n    for i in range(1,nt-1):\n        u[i+1,:] = u[i-1,:] - 2*dt*Gc.dot(u[i,:])\n    \n    return u\n\n## plotting\ndtlist = np.array([.1,.5,1])\n\nfig,axs = plt.subplots(2,3,sharex=True,sharey=True,figsize=(11,6))\nfor i in range(3):\n    \n    n = int(tend/dtlist[i])+1\n    u = FTUP(n,dtlist[i])\n    u2 = LFCS(n,dtlist[i])\n    \n    axs[0,i].plot(x,u[int(n/2),:],label='FT+UP')\n    axs[0,i].plot(x,u2[int(n/2),:],label='LF+CS')\n    axs[0,i].plot(x,ua(5.),'--',label='analytic',lw=2)\n    \n    axs[1,i].plot(x,u[-1,:])\n    axs[1,i].plot(x,u2[-1,:])\n    axs[1,i].plot(x,ua(10.),'--',lw=2)\n\n    if i == 0:\n        axs[0,i].legend()\n        axs[0,i].set_ylabel(r'$u$')\n        axs[1,i].set_ylabel(r'$u$')\n    \n    axs[1,i].set_xlabel(r'$x$')\n    axs[0,i].set_title(r'$t = %i, \\Delta t = %.1f$' % (int(tend/2),dtlist[i]))\n    axs[1,i].set_title(r'$t = %i, \\Delta t = %.1f$' % (int(tend),dtlist[i]))\n    \n\naxs[0,0].set_ylim(-.5,1.5)\n\nplt.tight_layout()\nplt.show()", "meta": {"hexsha": "925b8dce55c3115f21a339bd1ea94a1d948d3924", "size": 1851, "ext": "py", "lang": "Python", "max_stars_repo_path": "num/adv.py", "max_stars_repo_name": "milankl/misc", "max_stars_repo_head_hexsha": "40c74d927e6d18b44a6edb51bffda85cafb347e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-04T11:43:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-04T11:43:34.000Z", "max_issues_repo_path": "num/adv.py", "max_issues_repo_name": "milankl/misc", "max_issues_repo_head_hexsha": "40c74d927e6d18b44a6edb51bffda85cafb347e1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "num/adv.py", "max_forks_repo_name": "milankl/misc", "max_forks_repo_head_hexsha": "40c74d927e6d18b44a6edb51bffda85cafb347e1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-05-04T11:43:47.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-04T11:43:47.000Z", "avg_line_length": 23.4303797468, "max_line_length": 78, "alphanum_fraction": 0.5240410589, "include": true, "reason": "import numpy", "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920617, "lm_q2_score": 0.9136765222384493, "lm_q1q2_score": 0.8779990149627553}}
{"text": "import numpy as np\nimport sympy\n\ndef decompLU(A):\n\tL = np.eye(np.shape(A)[0]) #matriz L com a dimensao de A com a diagonal principla igual a 1\n\tU = np.zeros(np.shape(A)) #matriz U full zero\n\tlim = np.shape(A)[1] #pegando o tamanho da coluna de A (matriz quadrada)\t\n\tsum = 0\t\n\n\tfor i in range(0, lim):\n\t\tfor j in range(0, lim):\n\t\t\tsum = 0\n\t\t\t#Parte do somatorio de U que vai de 0 a i-1 e acumula L[i][k]*U[k][j] sendo k a variavel iteradora\n\t\t\tfor k in range (0, i):\n\t\t\t\tsum += L[i,k]*U[k,j]\n\t\t\tU[i,j] = A[i,j] - sum #atribuindo o valor de U[i][j]\n\t\n\t\tfor j in range (0, lim):\n\t\t\tsum = 0\n\t\t\t#Parte do somatorio de L que vai de 0 a i-1 e acumula L[j][k]*U[k][i] sendo k a variavel iteradora\n\t\t\tfor k in range (0, i):\n\t\t\t\tsum+= L[j,k]*U[k,i]\n\t\t\tL[j,i] = (A[j,i] - sum)/U[i,i] #atribuindo o valor L[i][j]\n\t\n\treturn L, U #retornando o resultado\n\ndef solveLU(L, U, b):\n\t#Resolvendo o sistema A*x = b\n\t#Como A = L*U, entao (L*U)*x = b\n\t#Vamos fazer L*(U*x) = b e U*x=y, portanto L*y=b\n\t#Logo, para encontrarmos o resultado resolvemos o sistema U*x = y \n\n\ty = np.zeros(np.shape(b)) #matriz coluna y com a mesma dimensao de b \n\tx = np.zeros(np.shape(b)) #matriz coluna x (resultado do sistema) com a mesma dimensao de b\t\t\n\t\n\tfor i in range (0, np.shape(b)[0]): #resolvendo o sistema  L*y=b\n\t\tfor j in range (0,i):\n\t\t\ty[i] -= y[j]*L[i,j]\n\t\ty[i]+=b[i]\t\t\t\t\t\n\n\tfor i in range (np.shape(b)[0]-1, -1, -1): #resolvendo o sistema U*x=b\n\t\tfor j in range (np.shape(b)[0]-1, i, -1):\n\t\t\tx[i] -= x[j]*U[i,j]\n\t\tx[i]+=y[i]\n\t\tx[i]/=U[i,i]\n\n\treturn x #retornando o resultado\t\t\t\t\n\n\nA = np.array([[1, 2,0], [1, 3,1],[-2, 0,1]])\nb = np.array([3,5,-1])\n(L, U) = decompLU(A)\nx = solveLU(L, U, b)\nprint('Matriz L:\\n{}'.format(L))\nprint('Matriz U:\\n{}'.format(U))\nprint('Solve LU:{}'.format(x))\n\nA = sympy.Matrix([[1, 2,0], [1, 3,1],[-2, 0,1]])\nb = sympy.Matrix([3, 5,-1])\nL, U, _ = A.LUdecomposition()\nx = A.solve(b)\n\nprint('Matriz L funcao do python:\\n{}'.format(L))\nprint('Matriz U funcao do python:\\n{}'.format(U))\nprint('Solve LU: {}'.format(x))\n", "meta": {"hexsha": "4f94c7f1bce3111a90d827aec1d1b610b4a195db", "size": 2018, "ext": "py", "lang": "Python", "max_stars_repo_path": "LUDecomposition.py", "max_stars_repo_name": "igortakeo/Calculo-Numerico", "max_stars_repo_head_hexsha": "96ed1892c3d2ba80039f2f2ce7de4ca834aa6283", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LUDecomposition.py", "max_issues_repo_name": "igortakeo/Calculo-Numerico", "max_issues_repo_head_hexsha": "96ed1892c3d2ba80039f2f2ce7de4ca834aa6283", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LUDecomposition.py", "max_forks_repo_name": "igortakeo/Calculo-Numerico", "max_forks_repo_head_hexsha": "96ed1892c3d2ba80039f2f2ce7de4ca834aa6283", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5757575758, "max_line_length": 101, "alphanum_fraction": 0.5921704658, "include": true, "reason": "import numpy,import sympy", "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.9230391558356, "lm_q1q2_score": 0.8779415169352317}}
{"text": "def main():\n\n    from copy import deepcopy\n    import numpy as np\n    import pandas as pd\n    from matplotlib import pyplot as plt\n    plt.rcParams['figure.figsize'] = (16, 9)\n    plt.style.use('ggplot')\n\n    # Importing the dataset\n    data = pd.read_csv('xclara.csv')\n    print(\"Input Data and Shape\")\n    print(data.shape)\n    data.head()\n\n    # Getting the values and plotting it\n    f1 = data['V1'].values\n    f2 = data['V2'].values\n    X = np.array(list(zip(f1, f2)))\n    plt.scatter(f1, f2, c='black', s=7)\n\n    # Euclidean Distance Caculator\n    def dist(a, b, ax=1):\n        return np.linalg.norm(a - b, axis=ax)\n\n    # Number of clusters\n    k = 3\n    # X coordinates of random centroids\n    C_x = np.random.randint(0, np.max(X)-20, size=k)\n    # Y coordinates of random centroids\n    C_y = np.random.randint(0, np.max(X)-20, size=k)\n    C = np.array(list(zip(C_x, C_y)), dtype=np.float32)\n    print(\"Initial Centroids\")\n    print(C)\n\n    # Plotting along with the Centroids\n    plt.scatter(f1, f2, c='#050505', s=7)\n    plt.scatter(C_x, C_y, marker='*', s=200, c='g')\n\n    # To store the value of centroids when it updates\n    C_old = np.zeros(C.shape)\n    # Cluster Lables(0, 1, 2)\n    clusters = np.zeros(len(X))\n    # Error func. - Distance between new centroids and old centroids\n    error = dist(C, C_old, None)\n    # Loop will run till the error becomes zero\n    while error != 0:\n        # Assigning each value to its closest cluster\n        for i in range(len(X)):\n            distances = dist(X[i], C)\n            cluster = np.argmin(distances)\n            clusters[i] = cluster\n        # Storing the old centroid values\n        C_old = deepcopy(C)\n        # Finding the new centroids by taking the average value\n        for i in range(k):\n            points = [X[j] for j in range(len(X)) if clusters[j] == i]\n            C[i] = np.mean(points, axis=0)\n        error = dist(C, C_old, None)\n\n    colors = ['r', 'g', 'b', 'y', 'c', 'm']\n    fig, ax = plt.subplots()\n    for i in range(k):\n            points = np.array([X[j] for j in range(len(X)) if clusters[j] == i])\n            ax.scatter(points[:, 0], points[:, 1], s=7, c=colors[i])\n    ax.scatter(C[:, 0], C[:, 1], marker='*', s=200, c='#050505')\n\n\n\n    '''\n    ==========================================================\n    scikit-learn\n    ==========================================================\n    '''\n\n    from sklearn.cluster import KMeans\n\n    # Number of clusters\n    kmeans = KMeans(n_clusters=3)\n    # Fitting the input data\n    kmeans = kmeans.fit(X)\n    # Getting the cluster labels\n    labels = kmeans.predict(X)\n    # Centroid values\n    centroids = kmeans.cluster_centers_\n\n    # Comparing with scikit-learn centroids\n    print(\"Centroid values\")\n    print(\"Scratch\")\n    print(C) # From Scratch\n    print(\"sklearn\")\n    print(centroids) # From sci-kit learn", "meta": {"hexsha": "467ccbbbce8324d70259c5f4fb471c5a8d30c27d", "size": 2852, "ext": "py", "lang": "Python", "max_stars_repo_path": "threads/kmeans.py", "max_stars_repo_name": "Siddhant-Ray/Space-Exploration-Bot", "max_stars_repo_head_hexsha": "6436af1cff0101ea796e2bbef512bf4ba1b44d9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "threads/kmeans.py", "max_issues_repo_name": "Siddhant-Ray/Space-Exploration-Bot", "max_issues_repo_head_hexsha": "6436af1cff0101ea796e2bbef512bf4ba1b44d9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "threads/kmeans.py", "max_forks_repo_name": "Siddhant-Ray/Space-Exploration-Bot", "max_forks_repo_head_hexsha": "6436af1cff0101ea796e2bbef512bf4ba1b44d9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0, "max_line_length": 80, "alphanum_fraction": 0.5683730715, "include": true, "reason": "import numpy", "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203814, "lm_q2_score": 0.9099070011518829, "lm_q1q2_score": 0.8779284611964746}}
{"text": "import numpy as np\n\ndef correlation(X, Y):\n    '''\n    Correlation function\n    '''\n    N = X.size\n    mu_X = X.sum()/N\n    mu_Y = Y.sum()/N\n    cov = ((X - mu_X)*(Y - mu_Y)).sum()/N\n    sigma_X = X.std()\n    sigma_Y = Y.std()\n    return cov/(sigma_X*sigma_Y)\n\n######################\n### Synthetic Data ###\n######################\n\ndef synthData1():\n    '''\n    Returns synthetic data for linear regression simple\n    '''\n    np.random.seed(sum([ord(c) for c in 'Regression']))\n    N = 20\n    x = np.linspace(0, 1, N)\n    yA = x\n    yB = x + (np.random.random(N)*2 - 1)*0.15\n    yC = x + (np.random.random(N)*2 - 1)*0.5\n    yD = np.random.random(N)\n    return [x, yA, yB, yC, yD]\n\ndef synthData2(M):\n    '''\n    Returns synthetic data for linear regression multiple\n    '''\n    np.random.seed(sum([ord(c) for c in 'Regression']))\n    N = complex(0, M)\n    s, t = np.mgrid[-1:1:N, -1:1:N]\n    x1 = s.reshape(1, -1)[0]\n    x2 = t.reshape(1, -1)[0]\n    y = (x1 + x2)*0.5 + (np.random.random(int(N.imag**2))*2 - 1)*0.75\n    return [s, t, x1, x2, y]\n\ndef synthData3():\n    '''\n    Returns synthetic data for linear regression gradient descent\n    '''\n    np.random.seed(sum([ord(c) for c in 'Regression']))\n    N = 20\n    x = np.linspace(0, 1, N)\n    x_ = np.linspace(-5, 5, N)\n    y = x + (np.random.random(N)*2 - 1)*0.25\n    return [x, x_, y]\n\ndef synthData4():\n    '''\n    Returns synthetic data for linear regression non-linear analysis\n    Anscombes quartet\n    '''\n    x1 = [10,   8,    13,   9,    11,   14,   6,    4,    12,   7,    5]\n    y1 = [8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84,4.82, 5.68]\n    x2 = [10,   8,    13,   9,    11,   14,   6,    4,    12,   7,    5]\n    y2 = [9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74]\n    x3 = [10,   8,    13,   9,    11,   14,   6,    4,    12,   7,    5]\n    y3 = [7.46, 6.77, 12.74,7.11, 7.81, 8.84, 6.08, 5.39, 8.15, 6.42, 5.73]\n    x4 = [8,    8,    8,    8,    8,    8,    8,    19,   8,    8,    8]\n    y4 = [6.58, 5.76, 7.71, 8.84, 8.47, 7.04, 5.25, 12.50,5.56, 7.91, 6.89]\n    return np.array([x1, y1, x2, y2, x3, y3, x4, y4])\n\ndef synthData5():\n    '''\n    Returns synthetic data for logistic regression\n    '''\n    np.random.seed(sum([ord(c) for c in 'Regression']))\n    N = 512\n    x1 = np.random.normal(1, 0.3, N//2)\n    x1 = np.concatenate([x1, np.random.normal(2, 0.3, N//2)])\n    x2 = np.random.normal(0, 0.3, N//2)\n    x2 = np.concatenate([x2, np.random.normal(0.25, 0.3, N//2)])\n    y = np.zeros(N//2, np.int8)\n    y = np.concatenate([y, np.ones(N//2, np.int8)])\n    return [x1, x2, y]\n\ndef synthData6():\n    '''\n    Returns synthetic data for polynomial regression\n    '''\n    np.random.seed(sum([ord(c) for c in 'Regression']))\n    N = 21\n    x = np.random.uniform(-3, 3, N)\n    y = x**3 - 3*x**2 + x + 1 + np.random.uniform(-3, 3, N)\n    return [x, y]", "meta": {"hexsha": "22c98774f7c168df2ac817bfacea261006c8bc8a", "size": 2851, "ext": "py", "lang": "Python", "max_stars_repo_path": "Machine-Learning-Fundamentals/regression__utils.py", "max_stars_repo_name": "XGBTrain5/07.ml_diegoinacio", "max_stars_repo_head_hexsha": "6fb927b953e476cb07c19496e51ffb500ad10fcb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2020-01-20T15:23:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T00:00:07.000Z", "max_issues_repo_path": "Machine-Learning-Fundamentals/regression__utils.py", "max_issues_repo_name": "XGBTrain5/07.ml_diegoinacio", "max_issues_repo_head_hexsha": "6fb927b953e476cb07c19496e51ffb500ad10fcb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-12-09T13:45:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T22:19:13.000Z", "max_forks_repo_path": "Machine-Learning-Fundamentals/regression__utils.py", "max_forks_repo_name": "XGBTrain5/07.ml_diegoinacio", "max_forks_repo_head_hexsha": "6fb927b953e476cb07c19496e51ffb500ad10fcb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-02-07T18:07:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-26T23:24:02.000Z", "avg_line_length": 30.9891304348, "max_line_length": 75, "alphanum_fraction": 0.5040336724, "include": true, "reason": "import numpy", "num_tokens": 1191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075722839015, "lm_q2_score": 0.9124361652391385, "lm_q1q2_score": 0.8778617438022603}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 17 16:26:48 2017\n\n@author: lamahamadeh\n\"\"\"\n\n#First: Python-based implementation \n#------------------------------------\n'''\nsource:\n-------\nVideo 2.4.2: Examples Involving Randomness\nWeek 2 Overview/Python Libraries and Concepts Used in Research\nUsing python for research\nHarvard\nonline course provided by edx.org\nurl: https://courses.edx.org/courses/course-v1:HarvardX+PH526x+3T2016/courseware/317ce880d7644d35840b1f734be76b06/391063d8f58242e892efafc9903b36e8/\n'''\n#roll a dice 100 times and plot a histogram of the outcomes\n#meaning: a histogram that shows how frequent the numbers from 1 to 6 appeared in the 100 samples\n\nimport numpy as np\nimport random \nimport matplotlib.pyplot as plt\nimport time\n\nrandom.choice([1,2,3,4,5,6]) #this line throws the dice one time \n\nrolls = []              \n              \nfor k in range(100):#we can try 1000, 10000000 times. We can notice that the histogram gets more flat when the number of rolling times increases.\n    rolls.append(random.choice([1,2,3,4,5,6]))#in this case, after using for loop, we wre rolling the dice 100 times    \n        \nprint(len(rolls))\n\n\n#draw a histogram\n\nplt.figure()\nplt.hist(rolls, bins = np.linspace(0.5,6.5,7));\nplt.show()\n\nstart_time = time.clock()\n#This time we will roll 10 dice not jsut one\nys = []\nfor rep in range(100000):#By increasing the number of dice rolls for each dice the distrbution follows the central limit theorem\n#The central limit theorem (CLT) states that the sum of a large number of random variables regardless of their distribution will\n#approximately follow a normal distribution (or Gaussian distribution).\n    y = 0\n    for k in range (10):\n        x = random.choice([1,2,3,4,5,6])\n        y = y + x\n    ys.append(y)\n\nend_time = time.clock()\n\nspeed1 = end_time - start_time\nprint(speed1)#1.19823723963\n   \nprint(len(ys)) #100\nprint(min(ys)) \nprint(max(ys)) \n\nplt.figure()\nplt.hist(ys); #the semicolon suppresses the output \nplt.show()\n\n#------------------------------------------------------------------\n\n#Second: NumPy random module implementation\n#------------------------------------------\n'''\nsource:\n-------\nVideo 2.4.3: using the NumPy Random Module\nWeek 2 Overview/Python Libraries and Concepts Used in Research\nUsing python for research\nHarvard\nonline course provided by edx.org\nurl: https://courses.edx.org/courses/course-v1:HarvardX+PH526x+3T2016/courseware/317ce880d7644d35840b1f734be76b06/391063d8f58242e892efafc9903b36e8/\n'''\n# We will repeate the previous example, but this time we will use Numpy\n\n\nstart_time = time.clock()\n\nX= np.random.randint(1,7,(100000,10)) #generate random numbers between 1 and 6 in a 2D matrix where we have 100 rows and 10 columns\nY = np.sum(X, axis=1) #sum over all the columns (the length of Y =100)\n#if you sum over all the columns, the length of the resulting list = the length of your rows\n#if you sum over all the rows, the length of the resulting list = the length of your columns\n\nend_time = time.clock()\nspeed2 = end_time - start_time\nprint(speed2)#0.0248949445651\n\n\nplt.hist(Y) #It can be seen from the histogram that its shape tends to have a normal distribution shape as we go higher in the \n#number of rows.\n\n#Generally using numpy is much faster than using standard python implementation. This is very important in scientific research.\n#we can prove that by calculating the value of:\n#speed1/speed2=1.19823723963/0.0248949445651=49.9(approximately 50 times faster)\n#and it is obviously can be seen taht using numpy is not only uses a less code but also much faster than the python-based\n#implementation (with approximately 50 times faster in our case).\n#ususally the coding speed value depends on your computer speed, so it doesn't have to hold the same value for everyone.\n#You might get a different value\n#------------------------------------------------------------------\n\n\n", "meta": {"hexsha": "48f0988b94bf31c808a04d98a2790e9310acf0e1", "size": 3903, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week2-Python-Libraries-and-Concepts-Used-in-Research/Dice_Probability.py", "max_stars_repo_name": "Lamanova/Harvard-PH526x-Lab", "max_stars_repo_head_hexsha": "168e4c16fa067905142bb6be106277f228d591c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-08-13T03:03:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T17:08:12.000Z", "max_issues_repo_path": "Week2-Python-Libraries-and-Concepts-Used-in-Research/Dice_Probability.py", "max_issues_repo_name": "Lamanova/Harvard-PH526x-Lab", "max_issues_repo_head_hexsha": "168e4c16fa067905142bb6be106277f228d591c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week2-Python-Libraries-and-Concepts-Used-in-Research/Dice_Probability.py", "max_forks_repo_name": "Lamanova/Harvard-PH526x-Lab", "max_forks_repo_head_hexsha": "168e4c16fa067905142bb6be106277f228d591c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2017-09-29T08:22:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T22:51:59.000Z", "avg_line_length": 34.8482142857, "max_line_length": 147, "alphanum_fraction": 0.7058672816, "include": true, "reason": "import numpy", "num_tokens": 1024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.9465966688819449, "lm_q1q2_score": 0.8778390103031541}}
{"text": "import numpy as np\nimport matplotlib.pyplot as mplt\n\ndef twoDGradient(vals, dx, dy):\n\n    n = len(vals); j = len(vals[0])\n\n    gradX =  [ [0.0] * n for _ in range(j) ]\n    gradY = [ [0.0] * n for _ in range(j) ]\n    \n    for i in range(1, n - 1):\n        for k in range(1, j - 1):\n\n            gradX[i][k] = (vals[i + 1][k] - vals[i - 1][k]) / (2.0 * dx)\n            gradY[i][k] = (vals[i][k + 1] - vals[i][k - 1]) / (2.0 * dy)\n\n    return gradX, gradY\n\n#grid information\nLx = 10; Ly = 10\nNx = 51; Ny = 51; Nt = 500\ndx = Lx/(Nx - 1); dy = Ly/(Ny - 1)\nrho = 1; cp = 1\nc = 1; C = 0.05; dt = C*dx/c\n\n#initialize mats to correct sizes\nTc = [ [0.0] * Ny for _ in range(Nx) ]\nTn = [ [0.0] * Ny for _ in range(Nx) ]\nk = [ [1.0] * Ny for _ in range(Nx) ]\n\n#place initial source\nfor i in range(20, 25):\n    for j in range( 30, 35):\n        k[i][j] = 0.0001 #square hole - thermal conductivity is very low\n\n#Source Term / Location of Source\nSx = round(7.0*Nx/Lx); Sy = round(3.0*Ny/Ly)\n\nt = 0; \nfor n in range( 0, Nt ):\n    \n    Tc = Tn #copy old temps for new time step\n    \n    for i in range( 1, Nx - 1 ):\n        for j in range( 1, Ny - 1 ):\n            #five point stencil with forcing function that includes the source\n            Tn[j][i] = Tc[j][i] + dt * (k[j][i]/rho/cp) * ((Tc[j][i+1] + Tc[j+1][i] - 4.0*Tc[j][i] + Tc[j][i-1] + Tc[j-1][i])/dx/dx)\n    \n    t = t + dt #inc time\n\n    if(t < 1):\n        #the source turns off at t == 1\n        Tn[Sy][Sx] = Tn[Sy][Sx] + dt*100/rho/cp; \n\n    #mixed boundary conditions\n    for i in range(Nx): \n        Tn[0][i] = 0.0\n        Tn[Ny - 1][i] = 0.0\n        Tn[i][0] = 0\n        Tn[i][Ny - 1] = Tn[i][Ny - 2]; \n\ntwoDGradX, twoDGradY = twoDGradient(Tn, dx, dy)\nsanityCheck = np.gradient(Tn, dx, dy)\n\nfig, (ax1, ax2) = mplt.subplots(2)\nax1.plot(sanityCheck[0], label = 'numpy implementation')\nax2.plot(twoDGradX, label = 'my implementation')\nmplt.show()", "meta": {"hexsha": "c7911ae270ba0b29dde398987d21a9f2eb7053eb", "size": 1893, "ext": "py", "lang": "Python", "max_stars_repo_path": "simplePhysics/DiscreteGradient/2D/2DGradient.py", "max_stars_repo_name": "shmillo/SimplePythonExamples", "max_stars_repo_head_hexsha": "1ed23af998220448c510cebc03af5ccdbd37a131", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simplePhysics/DiscreteGradient/2D/2DGradient.py", "max_issues_repo_name": "shmillo/SimplePythonExamples", "max_issues_repo_head_hexsha": "1ed23af998220448c510cebc03af5ccdbd37a131", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simplePhysics/DiscreteGradient/2D/2DGradient.py", "max_forks_repo_name": "shmillo/SimplePythonExamples", "max_forks_repo_head_hexsha": "1ed23af998220448c510cebc03af5ccdbd37a131", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8382352941, "max_line_length": 132, "alphanum_fraction": 0.5250924459, "include": true, "reason": "import numpy", "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407191430025, "lm_q2_score": 0.9019206679615432, "lm_q1q2_score": 0.8777859194968295}}
{"text": "import numpy as np\n\n\ndef compute_mse(theta_0, theta_1, data):\n    acum_error = 0.0\n    for k in range(len(data)):\n        acum_error += (first_order_pol(theta_0, theta_1, data[k][0]) - data[k][1])**2\n    return acum_error / len(data)\n\n\ndef first_order_pol(theta_0, theta_1, x):\n    return theta_0 + theta_1 * x\n\n\ndef step_gradient(theta_0, theta_1, data, alpha):\n    df_dtheta_0 = 0\n    df_dtheta_1 = 0\n    for k in range(len(data)):\n        e = first_order_pol(theta_0, theta_1, data[k][0]) - data[k][1]\n        df_dtheta_0 += e\n        df_dtheta_1 += e * data[k][0]\n    df_dtheta_0 *= 2/len(data)\n    df_dtheta_1 *= 2/len(data)\n    return (theta_0-alpha*df_dtheta_0, theta_1-alpha*df_dtheta_1)\n\n\ndef fit(data, theta_0, theta_1, alpha, num_iterations):\n    theta_0_record = [theta_0]\n    theta_1_record = [theta_1]\n    t0 = theta_0\n    t1 = theta_1\n    for i in range(num_iterations):\n        t0, t1 = step_gradient(t0, t1, data, alpha)\n        theta_0_record.append(t0)\n        theta_1_record.append(t1)\n    return theta_0_record, theta_1_record\n", "meta": {"hexsha": "ec27ddeca1b00db2fb8672443eb71ab60164a58d", "size": 1048, "ext": "py", "lang": "Python", "max_stars_repo_path": "alegrete.py", "max_stars_repo_name": "GarrenSouza/INF01048-T-3", "max_stars_repo_head_hexsha": "190349b12429ecd5a617e6bc61c9e73d353fb925", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "alegrete.py", "max_issues_repo_name": "GarrenSouza/INF01048-T-3", "max_issues_repo_head_hexsha": "190349b12429ecd5a617e6bc61c9e73d353fb925", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "alegrete.py", "max_forks_repo_name": "GarrenSouza/INF01048-T-3", "max_forks_repo_head_hexsha": "190349b12429ecd5a617e6bc61c9e73d353fb925", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3243243243, "max_line_length": 85, "alphanum_fraction": 0.6536259542, "include": true, "reason": "import numpy", "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561676667172, "lm_q2_score": 0.9059898191142621, "lm_q1q2_score": 0.8777738240921064}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n#step1\ndef initialize_parameters(lenw):\n    w=np.random.randn(1,lenw)\n    #w=np.zeroes((1,lenw))\n    b=0\n    return w,b\n\ndef sigmoid(x):\n    return 1/(1+np.exp(-x))\n\n#step2\ndef forward_prop(X,w,b): #w-->1xn , X-->nxm\n    z = sigmoid(np.dot(w,X)+b)\n    return z\n\n#    ln  = len(X.shape[1])\n#   for i in range(0,ln):\n#        if z[0,i]>0.5:\n#            z[0,i]=1\n#        else:\n#            z[0,i]=0\n#    z = z.astype(int)\n    \n\n\n#step 3\ndef cost_function(z,y):\n    #cost = -1/m * np.sum(Y * np.log(A) + (1-Y) * (np.log(1-A)))\n    cost = ((-y * np.log(z))-((1-y)* np.log(1-z))).mean()\n    return cost\n\n#step4\ndef back_prop(X,y,z):\n    m=y.shape[1]\n    dz = (1/m)*(z-y)\n    dw = np.dot(dz,X.T) #dw --> 1xn\n    db = np.sum(dz)\n    return dw,db\n    \n    \n#step5\ndef gradient_descent_update(w,b,dw,db,learning_rate):\n    w=w-learning_rate*dw\n    b=b-learning_rate*db\n    return w,b\n\n#step6\ndef logistic_regression_model(X_train,y_train,X_val,y_val,learning_rate,epochs,threshold):\n    \n    lenw = X_train.shape[0]\n    w,b= initialize_parameters(lenw) #step1\n    th=threshold\n    iteration=2\n    \n    costs_train = []\n    costs_val   = []\n    m_train     = y_train.shape[1]\n    m_val       = y_val.shape[1]\n    \n    for i in range(1,epochs+1):\n        z_train    = forward_prop(X_train,w,b) #step2\n        cost_train = cost_function(z_train,y_train) #step3\n        dw,db      = back_prop(X_train,y_train,z_train) #step4\n        w,b        = gradient_descent_update(w,b,dw,db,learning_rate) #step5\n        \n        count=i\n        #store trining cost in a list for plotting purpose\n        #if i%10==0:\n        costs_train.append(cost_train)\n            \n        #MAE_train\n        MAE_train = (1/m_train)*np.sum(np.abs(z_train-y_train))\n        \n        #cost_val,MAE val\n        z_val    = forward_prop(X_val,w,b)\n        cost_val = cost_function(z_val,y_val)\n        MAE_val  = (1/m_val)*np.sum(np.abs(z_val-y_val))\n        #if i%10==0:\n        costs_val.append(cost_val)\n        \n        \n        if count>1:\n            diff = (costs_train[-2]-costs_train[-1])\n            iteration=iteration+1\n            if diff <th:                \n                break\n            else:\n                continue\n\n    return costs_train,costs_val,w,iteration\n        ", "meta": {"hexsha": "c038ae232b30d793f9a853f8b1e9633bcd3a4921", "size": 2304, "ext": "py", "lang": "Python", "max_stars_repo_path": "LogisticRegression_5.py", "max_stars_repo_name": "Kaminibokefode/lLinear-Logistic-Regression--Gradient-Descent", "max_stars_repo_head_hexsha": "29746873aad132e2d91ae40830dff2ce198d9de0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LogisticRegression_5.py", "max_issues_repo_name": "Kaminibokefode/lLinear-Logistic-Regression--Gradient-Descent", "max_issues_repo_head_hexsha": "29746873aad132e2d91ae40830dff2ce198d9de0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LogisticRegression_5.py", "max_forks_repo_name": "Kaminibokefode/lLinear-Logistic-Regression--Gradient-Descent", "max_forks_repo_head_hexsha": "29746873aad132e2d91ae40830dff2ce198d9de0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5106382979, "max_line_length": 90, "alphanum_fraction": 0.5503472222, "include": true, "reason": "import numpy", "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305381464928, "lm_q2_score": 0.9111797009670494, "lm_q1q2_score": 0.8776761137106514}}
{"text": "import numpy as np\n\n\n# Zeros Matrix\nprint(np.zeros((3, 3)), '\\n')\n\n# Identity Matrix\nprint(np.identity(3), '\\n')\n\nA = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\nC = np.array([[2, 4, 6], [8, 10, 12], [14, 16, 18]])\n\n# Matrix Copy\nAC = A.copy()\nprint(AC, '\\n')\n\n# Transpose a matrix\nAT = np.transpose(A)\nprint(AT, '\\n')\n\n# Add and Subtract\nSumAC = A + C\nprint(SumAC, '\\n')\n\nDifCA = C - A\nprint(DifCA, '\\n')\n\n# Matrix Multiply\nProdAC = np.matmul(A, C)\nprint(ProdAC, '\\n')\n\n# Multiply a List of Matrices\narr = [A, C, A, C, A, C]\nProd = np.matmul(A, C)\nnum = len(arr)\nfor i in range(2, num):\n    Prod = np.matmul(Prod, arr[i])\nprint(Prod, '\\n')\n\nChkP = np.matmul(\n            np.matmul(\n                np.matmul(\n                    np.matmul(\n                        np.matmul(arr[0], arr[1]),\n                        arr[2]), arr[3]), arr[4]), arr[5])\nprint(ChkP, '\\n')\n\n# Check Equality of Matrices\nprint(Prod == ChkP, '\\n')\n# https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html\nprint(np.allclose(Prod, ChkP), '\\n')\n\n# Dot Product (follows the same rules as matrix multiplication)\n# https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html\nv1 = np.array([[2, 4, 6]])\nv2 = np.array([[1], [2], [3]])\nans1 = np.dot(v1, v2)\nans2 = np.dot(v1, v2)[0, 0]\nprint(f'ans1 = {ans1}, ans2 = {ans2}\\n')\n\n# Unitize an array\nmag1 = (1*1 + 2*2 + 3*3) ** 0.5\nmag2 = np.linalg.norm(v2)\nnorm1 = v2 / mag1\nnorm2 = v2 / mag2\nprint(f'mag1 = {mag1}, mag2 = {mag2}, they are equal: {mag1 == mag2}\\n')\nprint(norm1, '\\n')\nprint(norm2, '\\n')\nprint(norm1 == norm2)\n", "meta": {"hexsha": "ab9a33f65f6abed73730363e803c5e70c029dff9", "size": 1568, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumpyToolsPractice.py", "max_stars_repo_name": "ThomIves/BasicLinearAlgebraToolsPurePy", "max_stars_repo_head_hexsha": "533263e946b83ee49f1dc48fd4b606e2b37c408e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2019-10-03T11:26:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T00:06:00.000Z", "max_issues_repo_path": "NumpyToolsPractice.py", "max_issues_repo_name": "ThomIves/BasicLinearAlgebraToolsPurePy", "max_issues_repo_head_hexsha": "533263e946b83ee49f1dc48fd4b606e2b37c408e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-07-05T08:18:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-28T12:56:02.000Z", "max_forks_repo_path": "NumpyToolsPractice.py", "max_forks_repo_name": "ThomIves/BasicLinearAlgebraToolsPurePy", "max_forks_repo_head_hexsha": "533263e946b83ee49f1dc48fd4b606e2b37c408e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-07-29T19:34:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-04T01:31:00.000Z", "avg_line_length": 22.4, "max_line_length": 74, "alphanum_fraction": 0.568877551, "include": true, "reason": "import numpy", "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639686018702, "lm_q2_score": 0.9032942054022056, "lm_q1q2_score": 0.8776081030156399}}
{"text": "# trapezoidal rule\n#\n# M. Zingale (2013-02-13)\n\nimport math\nimport numpy\n\n# function we wish to integrate\ndef fun(x):\n    return numpy.exp(-x)\n\n\n# analytic value of the integral\ndef I_exact(a,b):\n    return -math.exp(-b) + math.exp(-a)\n\n\n# do a trapezoid integration by breaking up the domain [a,b] into N\n# slabs\ndef trap(a,b,f,N):\n\n    xedge = numpy.linspace(a,b,N+1)\n\n    integral = 0.0\n\n    n = 0\n    while n < N:\n        integral += 0.5*(xedge[n+1] - xedge[n])*(f(xedge[n]) + f(xedge[n+1]))\n        n += 1\n\n    return integral\n\n\nN = 3\na = 0.0\nb = 1.0\n\nN = 2\nwhile (N <= 128):\n    t = trap(a,b,fun,N)\n    e = t - I_exact(a,b)\n    print N, t, e\n\n    N *= 2\n\n\n \n", "meta": {"hexsha": "e6e89283e3db9e0576066e39e811b6382a3a1a25", "size": 664, "ext": "py", "lang": "Python", "max_stars_repo_path": "others/differentiation_integration/trap.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "others/differentiation_integration/trap.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/differentiation_integration/trap.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 13.8333333333, "max_line_length": 77, "alphanum_fraction": 0.5602409639, "include": true, "reason": "import numpy", "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639677785088, "lm_q2_score": 0.9032941975921684, "lm_q1q2_score": 0.8776080946839515}}
{"text": "import numpy as np \nimport matplotlib.pyplot as plt\n\n##### Sigmoid\nsigmoid = lambda x: 1 / (1 + np.exp(-x))\n\nx=np.linspace(-10,10,10)\n\ny=np.linspace(-10,10,100)\n\nfig = plt.figure()\nplt.plot(y,sigmoid(y),'b', label='linspace(-10,10,100)')\n\nplt.grid(linestyle='--')\n\nplt.xlabel('X Axis')\n\nplt.ylabel('Y Axis')\n\nplt.title('Sigmoid Function')\n\nplt.xticks([-4, -3, -2, -1, 0, 1, 2, 3, 4])\nplt.yticks([-2, -1, 0, 1, 2])\n\nplt.ylim(-2, 2)\nplt.xlim(-4, 4)\n\nplt.show()\n#plt.savefig('sigmoid.png')\n\nfig = plt.figure()\n\n##### TanH\ntanh = lambda x: 2*sigmoid(2*x)-1\n\nx=np.linspace(-10,10,10)\n\ny=np.linspace(-10,10,100)\n\nplt.plot(y,tanh(y),'b', label='linspace(-10,10,100)')\n\nplt.grid(linestyle='--')\n\nplt.xlabel('X Axis')\n\nplt.ylabel('Y Axis')\n\nplt.title('TanH Function')\n\nplt.xticks([-4, -3, -2, -1, 0, 1, 2, 3, 4])\nplt.yticks([-4, -3, -2, -1, 0, 1, 2, 3, 4])\n\nplt.ylim(-4, 4)\nplt.xlim(-4, 4)\n\nplt.show()\n#plt.savefig('tanh.png')\n\nfig = plt.figure()\n\n##### ReLU\nrelu = lambda x: np.where(x>=0, x, 0)\n\nx=np.linspace(-10,10,10)\n\ny=np.linspace(-10,10,1000)\n\nplt.plot(y,relu(y),'b', label='linspace(-10,10,100)')\n\nplt.grid(linestyle='--')\n\nplt.xlabel('X Axis')\n\nplt.ylabel('Y Axis')\n\nplt.title('ReLU')\n\nplt.xticks([-4, -3, -2, -1, 0, 1, 2, 3, 4])\nplt.yticks([-4, -3, -2, -1, 0, 1, 2, 3, 4])\n\nplt.ylim(-4, 4)\nplt.xlim(-4, 4)\n\nplt.show()\n#plt.savefig('relu.png')\n\nfig = plt.figure()\n\n##### Leaky ReLU\nleakyrelu = lambda x: np.where(x>=0, x, 0.1*x)\n\nx=np.linspace(-10,10,10)\n\ny=np.linspace(-10,10,1000)\n\nplt.plot(y,leakyrelu(y),'b', label='linspace(-10,10,100)')\n\nplt.grid(linestyle='--')\n\nplt.xlabel('X Axis')\n\nplt.ylabel('Y Axis')\n\nplt.title('Leaky ReLU')\n\nplt.xticks([-4, -3, -2, -1, 0, 1, 2, 3, 4])\nplt.yticks([-4, -3, -2, -1, 0, 1, 2, 3, 4])\n\nplt.ylim(-4, 4)\nplt.xlim(-4, 4)\n\nplt.show()\n#plt.savefig('lrelu.png')\n\nfig = plt.figure()\n\n\n##### Binary Step\nbstep = lambda x: np.where(x>=0, 1, 0)\n\nx=np.linspace(-10,10,10)\n\ny=np.linspace(-10,10,1000)\n\nplt.plot(y,bstep(y),'b', label='linspace(-10,10,100)')\n\nplt.grid(linestyle='--')\n\nplt.xlabel('X Axis')\n\nplt.ylabel('Y Axis')\n\nplt.title('Step Function')\n\nplt.xticks([-4, -3, -2, -1, 0, 1, 2, 3, 4])\nplt.yticks([-2, -1, 0, 1, 2])\n\nplt.ylim(-2, 2)\nplt.xlim(-4, 4)\n\nplt.show()\n#plt.savefig('step.png')\n\nprint('done')", "meta": {"hexsha": "8892e010e011dd6b5b322158ed8b366482f2c440", "size": 2245, "ext": "py", "lang": "Python", "max_stars_repo_path": "12_plot_activations.py", "max_stars_repo_name": "tansenkhan1990/pytorch_python_engineer", "max_stars_repo_head_hexsha": "c4e8120c95ac419e978afc344b4a592c6ba0f417", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "12_plot_activations.py", "max_issues_repo_name": "tansenkhan1990/pytorch_python_engineer", "max_issues_repo_head_hexsha": "c4e8120c95ac419e978afc344b4a592c6ba0f417", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "12_plot_activations.py", "max_forks_repo_name": "tansenkhan1990/pytorch_python_engineer", "max_forks_repo_head_hexsha": "c4e8120c95ac419e978afc344b4a592c6ba0f417", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.5902777778, "max_line_length": 58, "alphanum_fraction": 0.5870824053, "include": true, "reason": "import numpy", "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639669551474, "lm_q2_score": 0.9032941982430049, "lm_q1q2_score": 0.8776080945725432}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nnp.set_printoptions(threshold=np.nan)\nnp.set_printoptions(precision=16)\n\nres = np.zeros((2,20))\nfor m in [10,20]:\n    h = 1/m\n    h2 = h/2\n    \n    x = np.linspace(0,1,m+1)\n    f = 2*(3*x[1:]**2-2*x[1:]+1) # start at x[1] since we evaluate for j=1,2,...\n    \n    f[0] -= (1+(x[1]-h2)**2)/h**2\n    \n    A = np.zeros((m,m))\n    A[0,0:2] = [-2*(1+x[2]**2+h2**2),(1+(x[2]+h2)**2)]\n    for j in range(2,m):\n        A[j-1,j-2:j+1] = [(1+(x[j]-h2)**2),-2*(1+x[j]**2+h2**2),(1+(x[j]+h2)**2)]\n    A[m-1,m-2:m] = [2*(1+x[j]**2+h2**2),-2*(1+x[j]**2+h2**2)]\n\n    u = np.linalg.solve(A/h**2,f)\n    res[int(m/10-1),0:m] = u\n    print(h,np.sqrt(h)*np.linalg.norm(u-(1-x[1:])**2))\n\n#<startTeX>\n# richardson extrapolation\nm = 10\nh = 1/m\nx = np.linspace(0,1,m+1)\nrichardson = (4*res[1,1::2] - res[0,0:10])/3\n\nplt.scatter(x[1:],((1-x[1:])**2)) #actual solution\nplt.scatter(x[1:],richardson) # numerical solution\nprint(\"m=10:\",np.sqrt(h)*np.linalg.norm(res[0,0:10]-(1-x[1:])**2))\nprint(\"m=20 (subsampled):\",np.sqrt(h)*np.linalg.norm(res[1,1::2]-(1-x[1:])**2))\nprint(\"richardson:\",np.sqrt(h)*np.linalg.norm(richardson-(1-x[1:])**2))\n#<endTeX>", "meta": {"hexsha": "de241816501786c98413a1db7652f77133fdd5d5", "size": 1172, "ext": "py", "lang": "Python", "max_stars_repo_path": "amath585/hw3/hw3_3.py", "max_stars_repo_name": "interesting-courses/UW_coursework", "max_stars_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-19T01:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T12:32:59.000Z", "max_issues_repo_path": "amath585/hw3/hw3_3.py", "max_issues_repo_name": "interesting-courses/UW_coursework", "max_issues_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "amath585/hw3/hw3_3.py", "max_forks_repo_name": "interesting-courses/UW_coursework", "max_forks_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-31T22:23:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T22:13:01.000Z", "avg_line_length": 30.8421052632, "max_line_length": 81, "alphanum_fraction": 0.5409556314, "include": true, "reason": "import numpy", "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.9149009515124917, "lm_q1q2_score": 0.8775311671612701}}
{"text": "from numpy import *\r\nfrom tqdm import trange # for a fancy looking progress bar while running the algorithm (use with for loop) \r\n\r\ndef mean_sq_error(b, m, data):\r\n    squared_error = 0\r\n\r\n    # calculate squared_error\r\n    for i in range(len(data)):\r\n        x = data[i, 0]\r\n        y = data[i, 1]\r\n        squared_error += (y - (m * x + b))**2  #this will calculate squared error\r\n\r\n    # for mean squared error, divide squared error by number of data points or len(data)\r\n    return squared_error / float(len(data)) #float bc we want error to be precise\r\n\r\ndef gradient_descent(b_init, m_init, data, learning_rate):\r\n    gradient_wrt_b = 0 #gradient wrt b_init\r\n    gradient_wrt_m = 0 #gradient wrt m_init\r\n    N = float(len(data))\r\n\r\n    # compute gradients wrt b_init and m_init\r\n    for i in range(len(data)):\r\n        x = data[i, 0]\r\n        y = data[i, 1]\r\n        gradient_wrt_b += -(2/N) * (y - ((m_init * x) + b_init))\r\n        gradient_wrt_m += -(2/N) * x * (y - ((m_init * x) + b_init))\r\n\r\n    #update and return b_init and m_init to b_new and m_new respectively\r\n    b_new = b_init - (learning_rate * gradient_wrt_b)\r\n    m_new = m_init - (learning_rate * gradient_wrt_m)\r\n    return (b_new, m_new)\r\n\r\ndef run_gradient_descent(b_init, m_init, data, learning_rate, num_of_iterations):\r\n    # b and m before running gradient descent\r\n    b_final = b_init\r\n    m_final = m_init\r\n\r\n    # run gradient descent for the given number of iterations\r\n    for i in trange(num_of_iterations):\r\n        (b_final, m_final) = gradient_descent(b_final, m_final, array(data), learning_rate)\r\n\r\n\r\n    # return the final values of b and m\r\n    return (b_final, m_final)\r\n\r\ndef run_linear_regression():\r\n  # load data\r\n  dataset = genfromtxt('data.csv', delimiter= ',')\r\n\r\n  # define hyperparameters\r\n  learning_rate = 0.0001\r\n  b_init = 0 # y-intercept\r\n  m_init = 0 # slope of regression line\r\n  num_of_iterations = 100000\r\n  \r\n  # start gradient descent\r\n  print(\"\\n Starting gradient descent at b =\", b_init, \", m =\", m_init, \", error =\", mean_sq_error(b_init, m_init, dataset))\r\n  print(\"Running...\")\r\n  (b_init, m_init) = run_gradient_descent(b_init, m_init, dataset, learning_rate, num_of_iterations)\r\n  \r\n  #print final results\r\n  print(\"Gradient descent successful...\")\r\n  print(\"After\", num_of_iterations,  \"iterations, b =\", b_init, \", m =\", m_init, \"error =\", mean_sq_error(b_init, m_init, dataset))\r\n\r\n\r\nif __name__ == '__main__':\r\n  run_linear_regression()\r\n", "meta": {"hexsha": "7b6adbfa6e17f46eb269040d101a8a045dfacb8f", "size": 2466, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_regression.py", "max_stars_repo_name": "sarvasvX/Linear-Regression-Using-Gradient-Descent", "max_stars_repo_head_hexsha": "29be77284cf1cebc1bdcf26f14084703f3d8b32a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_regression.py", "max_issues_repo_name": "sarvasvX/Linear-Regression-Using-Gradient-Descent", "max_issues_repo_head_hexsha": "29be77284cf1cebc1bdcf26f14084703f3d8b32a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_regression.py", "max_forks_repo_name": "sarvasvX/Linear-Regression-Using-Gradient-Descent", "max_forks_repo_head_hexsha": "29be77284cf1cebc1bdcf26f14084703f3d8b32a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2647058824, "max_line_length": 132, "alphanum_fraction": 0.6577453366, "include": true, "reason": "from numpy", "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.9173026516730629, "lm_q1q2_score": 0.8775230883408986}}
{"text": "# Python script of the samples of numpy\n# Author: Sandeep Mewara\n# Location: Learn By Insight\n# Github: https://github.com/samewara/python-examples/blob/master/numpy-basic.py\n# #####################################\n# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %% [markdown]\n# ## NUMPY SAMPLES ##\n\n# %%\nimport numpy as np\n\n# %% [markdown]\n# *** Random Walk simulation ***\n# \n# 1000-step random walk exercise where a person starting from 0 takes one step to the right(+1) or to the left(-1) with equal probability. To get 'd' being the max distance reached from the origin during the walk. \n# \n# Simulate it (N trials) and find the mean of the max distance of all trails.\n\n# %%\n# unit\nsteps = 1000\nrw_seq = np.random.choice([-1,1],steps) #random sequence of steps\nnet_d = rw_seq.cumsum() #total distance = cumulative sum of all steps\nmax_d_from_origin = np.max(np.abs(net_d))\n\nprint('Max distance from origin: ',max_d_from_origin)\n\n\n# %%\n# for simulation\n\ndef simulate_d():\n    steps = 1000\n    rw_seq = np.random.choice([-1,1],steps) #random sequence of steps\n    net_d = rw_seq.cumsum() #total distance = cumulative sum of all steps\n    max_d_from_origin = np.max(np.abs(net_d))\n    return max_d_from_origin\n\nsimulation_count = 100,1000,10000,100000\nfor i in range(len(simulation_count)):\n    max_d_all = [simulate_d() for x in range(simulation_count[i])] # list comprehension - all max_d in a list\n    mean_d = np.mean(max_d_all)\n    print('Mean distance for {0} simulation is: {1}'.format(simulation_count[i], mean_d))\n    \n# based on the results, seems the max distance far from origin is around 40\n\n# %% [markdown]\n# *** Triangle simulation ***\n# With a unit length stick - break into 3 sticks randomly. Carry out N trails and see the probability of finding the right pieces that can form the sides of the triangle using these 3 broken pieces\n# \n\n# %%\n# unit validation\n\nstick_l = 1\n# this would be incorrect logically as fixed unit length is there\n# pieces_length = np.random.rand(2) #2 random numbers between 0 & 1 \n\n#x = pieces_length[0]\n#y = pieces_length[1]\n\nx = np.random.uniform(0,1)\ny = np.random.uniform(0,1-x)\n\nz = 1 - (x+y)\nprint ('x:{0},y:{1},z:{2}'.format(x,y,z))\n\n# for triangle to be valid any two side sum should always be greater than third\nif(x+y>z and y+z>x and z+x>y):\n    print('We got a traingle!')\nelse:\n    print('SORRY! No triangle')\n\n\n# %%\n# for simulation\nstick_l = 1\n\ndef getxyz():\n    x = np.random.uniform(0,stick_l)\n    y = np.random.uniform(0,stick_l-x)\n    z = stick_l - (x+y)\n    return x,y,z\n\ndef istriangle(x,y,z):\n    if (x+y>z and y+z>x and z+x>y):\n        return 1\n    else:\n        return 0\n\n\nsimulation_count = 100,1000,10000,100000\nfor i in range(len(simulation_count)):\n    triangle_all = [istriangle(*(getxyz())) for x in range(simulation_count[i])] # list comprehension - all true/false in a list\n    probability = np.sum(triangle_all)/simulation_count[i]\n    print('Probablity for {0} simulation is: {1}'.format(simulation_count[i], probability))\n    \n    \n# based on the results, seems the probablility f formaing triangle from pieces would be just under 20%\n\n# %% [markdown]\n# *** Random Number ***\n# \n# Generate 10 random numbers in the interval 0,1 and obtain an array X\n# \n# Generate another array Y such that $Y[i]$=1 if $X[i]$≥0.5 and 0 otherwise. \n\n# %%\nX = np.random.rand(10)\n\n# Generate the array Y == Random Number\nY = np.where(X>=0.5,1,0)\nY\n\n# %% [markdown]\n# *** Pearson's correlation coefficient ***\n# \n# Given two arrays $X,Y$, correlation is a measure of linear dependence of values of one array on the other. For example, heights and weights of a group of people are correlated. Validate the below formula for correlation and verify the result using numpy's corrcoef method.\n# \n# This is given by $\\frac{\\sum(X-X_{mean})(Y-Y_{mean})}{\\sqrt{\\sum(X-X_{mean})^2\\sum(Y-Y_{mean})^2}}$  . \n# \n\n# %%\nX = np.random.randint(0,10,20)\nY = X + np.random.randint(20)\n\nX_mean = np.mean(X)\nY_mean = np.mean(Y)\n\nexp = np.sum((X-X_mean)*(Y-Y_mean))\nstd = np.sqrt(np.sum((X-X_mean)**2) * np.sum((Y-Y_mean)**2))\ncoeff_corr = exp/std\nprint('PCC via fomula: ',coeff_corr)\nprint('PCC via Numpy: ',np.corrcoef(X,Y))\n\n# %% [markdown]\n# *** Mean & Variance of crude oil prices ***\n# \n# data-file: crude_oil.csv\n# Find the mean & the standard deviation of the two types of crude oil. \n# \n# Handle:\n# 1. Header\n# 2. Missing/Unknown data (should not be part of calcs)\n\n# %%\ndata = np.genfromtxt('./data-files/numpy/crude_oil.csv',delimiter=\";\")\n# data\n# Row1 & Column1 look like not a number here so\ndata=data[1:,1:]\ndata\n\n\n# %%\ndata = np.genfromtxt('./data-files/numpy/crude_oil.csv',delimiter=\";\",skip_header=1, encoding=None)\ndata=data[:,1:]\ndata\n\n\n# %%\ncrude_data = np.nan_to_num(data)\ncrude_data\n\n\n# %%\ncrude1_data = crude_data[~np.isnan(data[:,0])][:,0] #all rows but not nan, 0th column => using masking \ncrude2_data = crude_data[~np.isnan(data[:,1])][:,1] #all rows but not nan, 1st column \n\n\n# %%\nprint('crude1_mean:{0},crude2_mean:{1}'.format(np.mean(crude1_data),np.mean(crude2_data)))\nprint('crude1_sd:{0},crude2_sd:{1}'.format(np.std(crude1_data),np.std(crude2_data)))", "meta": {"hexsha": "4a7d7259efe6d7b26e9d6eb64c2a82724cd67a89", "size": 5163, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy-samples.py", "max_stars_repo_name": "samewara/python-examples", "max_stars_repo_head_hexsha": "088c40adfe7b6433ca89d7f1f76b17f43d2acbc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy-samples.py", "max_issues_repo_name": "samewara/python-examples", "max_issues_repo_head_hexsha": "088c40adfe7b6433ca89d7f1f76b17f43d2acbc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy-samples.py", "max_forks_repo_name": "samewara/python-examples", "max_forks_repo_head_hexsha": "088c40adfe7b6433ca89d7f1f76b17f43d2acbc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-26T09:48:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-26T09:48:07.000Z", "avg_line_length": 29.6724137931, "max_line_length": 274, "alphanum_fraction": 0.6788688747, "include": true, "reason": "import numpy", "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.937210788772295, "lm_q1q2_score": 0.8774964037540733}}
{"text": "from pprint import pprint\nimport time\nimport numpy\nimport math\nfrom uniform_generator import uniform_generator\n\ndef normal_generator():\n    \"\"\" \n    Samples two independent random variables from standard Gaussian distribution.\n    Uses Box-Muller Transform to generate random variables.\n    Equation for Box-Muller Transform is\n            Z_1 = -2log(U_1)^(1/2)*cos(2*pi*U_2)\n            Z_2 = -2log(U_1)^(1/2)*sin(2*pi*U_2)\n    where U_1 and U_2 are two independent random variables generated from uniform\n    distribution.\n    \"\"\"\n    uni_gen = uniform_generator()\n    while True:\n        u1 = next(uni_gen)\n        u2 = next(uni_gen)\n        if u1 == 0 or u2 == 0:\n            continue\n        random_number_1 = ((-2 * math.log(u1)) ** (1/2)) * math.cos(2 * math.pi * u2)\n        random_number_2 = ((-2 * math.log(u1)) ** (1/2)) * math.sin(2 * math.pi * u2)  \n        yield random_number_1, random_number_2\n\n\nlimit = 10001\nif __name__ == '__main__':\n    output_list = []\n    print(\"Generating 10000 random numbers from standard normal distribution.\")\n    start = time.time()\n    norm_gen = normal_generator()\n    for i in range(10000):\n       op1, op2 = next(norm_gen)\n       output_list.append(op1)\n       output_list.append(op2)\n    end = time.time()\n    print(\"Time taken \" + str(end - start))\n    print(\"Mean is: \" + str(numpy.mean(output_list)))\n    print(\"Standard Deviation: \" + str(numpy.std(output_list)))\n\n", "meta": {"hexsha": "a447f6866471dd45d391c2aa0224a0a22c62e046", "size": 1420, "ext": "py", "lang": "Python", "max_stars_repo_path": "normal_generator.py", "max_stars_repo_name": "Prakash2403/data-generators", "max_stars_repo_head_hexsha": "16d844aeb90022a68c8f48f297787eec4cce9434", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-17T19:13:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-17T19:13:26.000Z", "max_issues_repo_path": "normal_generator.py", "max_issues_repo_name": "Prakash2403/data-generators", "max_issues_repo_head_hexsha": "16d844aeb90022a68c8f48f297787eec4cce9434", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "normal_generator.py", "max_forks_repo_name": "Prakash2403/data-generators", "max_forks_repo_head_hexsha": "16d844aeb90022a68c8f48f297787eec4cce9434", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.023255814, "max_line_length": 87, "alphanum_fraction": 0.6387323944, "include": true, "reason": "import numpy", "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9822877012965885, "lm_q2_score": 0.8933094159957173, "lm_q1q2_score": 0.8774868527850311}}
{"text": "from __future__ import division\r\nimport numpy as np\r\nfrom numpy import linalg\r\n\r\n\r\ndef jacobi(A, b, x0, tol, N):\r\n    # preliminares\r\n    A, b, x0 = A.astype(\"double\"), b.astype(\"double\"), x0.astype(\"double\")\r\n\r\n    n = np.shape(A)[0]\r\n    x = np.zeros(n)\r\n    it = 0\r\n    # iteracoes\r\n    while it < N:\r\n        it = it + 1\r\n        # iteracao de Jacobi\r\n        for i in np.arange(n):\r\n            x[i] = b[i]\r\n            for j in np.concatenate((np.arange(0, i), np.arange(i + 1, n))):\r\n                x[i] -= A[i, j] * x0[j]\r\n            x[i] /= A[i, i]\r\n        # tolerancia\r\n        if np.linalg.norm(x - x0, np.inf) < tol:\r\n            return x\r\n        # prepara nova iteracao\r\n        x0 = np.copy(x)\r\n    raise NameError(\"num. max. de iteracoes excedido.\")\r\n\r\n\r\ndef gauss_seidel(A, b, x0, tol, N):\r\n    # preliminares\r\n    A, b, x0 = A.astype(\"double\"), b.astype(\"double\"), x0.astype(\"double\")\r\n\r\n    n = np.shape(A)[0]\r\n    x = np.copy(x0)\r\n    it = 0\r\n    # iteracoes\r\n    while it < N:\r\n        it = +1\r\n        # iteracao de Jacobi\r\n        for i in np.arange(n):\r\n            x[i] = b[i]\r\n            for j in np.concatenate((np.arange(0, i), np.arange(i + 1, n))):\r\n                x[i] -= A[i, j] * x[j]\r\n            x[i] /= A[i, i]\r\n        # tolerancia\r\n        if np.linalg.norm(x - x0, np.inf) < tol:\r\n            return x\r\n        # prepara nova iteracao\r\n        x0 = np.copy(x)\r\n    raise NameError(\"num. max. de iteracoes excedido.\")\r\n\r\n\r\nA = np.matrix(\r\n    [\r\n        [1, -1, 0, 0, 0],\r\n        [-1, 2, -1, 0, 0],\r\n        [0, -1, (2 + 10 ** -3), -1, 0],\r\n        [0, 0, -1, 2, -1],\r\n        [0, 0, 0, 1, 2],\r\n    ]\r\n)\r\nb = np.matrix([[1], [1], [1], [1], [1]])\r\nx0 = np.matrix([[0], [0], [0], [0], [0]])\r\n\r\nprint(\"Metodo Eliminacao de Gauss\")\r\nA_inversa = np.linalg.inv(A)\r\nx = np.dot(A_inversa, b)\r\nfor i in range(5):\r\n    print(\"x{} = {}\".format(i + 1, x[i, 0]))\r\nprint\r\n\r\nprint(\"Metodo Jacobi\")\r\nx = jacobi(A, b, x0, 10 ** -2, 100)  # utilizando 100 iteracoes\r\nfor i in range(5):\r\n    print(\"x{} = {}\".format(i + 1, x[i]))\r\nprint\r\n\r\nprint(\"Metodo Gauss-Seidel\")\r\nx = gauss_seidel(A, b, x0, 10 ** -2, 100)  # utilizando 100 iteracoes\r\nfor i in range(5):\r\n    print(\"x{} = {}\".format(i + 1, x[i, 0]))\r\n", "meta": {"hexsha": "6181d8d84484b7519f9035734504099bb0212137", "size": 2232, "ext": "py", "lang": "Python", "max_stars_repo_path": "ANN/past_works/sistemas_lineares.py", "max_stars_repo_name": "joao-frohlich/BCC", "max_stars_repo_head_hexsha": "9ed74eb6d921d1280f48680677a2140c5383368d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-12-08T20:18:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-07T20:00:07.000Z", "max_issues_repo_path": "ANN/past_works/sistemas_lineares.py", "max_issues_repo_name": "joao-frohlich/BCC", "max_issues_repo_head_hexsha": "9ed74eb6d921d1280f48680677a2140c5383368d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-28T03:42:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T16:53:13.000Z", "max_forks_repo_path": "ANN/past_works/sistemas_lineares.py", "max_forks_repo_name": "joao-frohlich/BCC", "max_forks_repo_head_hexsha": "9ed74eb6d921d1280f48680677a2140c5383368d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-14T19:59:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T11:53:21.000Z", "avg_line_length": 26.8915662651, "max_line_length": 77, "alphanum_fraction": 0.4681899642, "include": true, "reason": "import numpy,from numpy", "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.935346505335907, "lm_q1q2_score": 0.8774710183250833}}
{"text": "import numpy as np\nimport math\nimport time\n\n\n\ndef timeit(func):\n\tdef timed(*args, **kwargs):\n\t\tt1 = time.time()\n\t\tres = func(*args, **kwargs)\n\t\tt2 = time.time()\n\t\treturn (t2-t1, res)\n\treturn timed\n\n\ndef powerIntegrate(p, a, b):\n\t'''Integrate x^p over (a,b)'''\n\tp += 1\n\treturn (b**p - a**p)/p\n\n\n\n@timeit\ndef gaussIntegrate(\n\t# Interval\n\ta,b,\n\t# Function\n\tf,\n\t# Weight function alpha, where w(x) = x^p,\n\tp,\n\t# Number of intervals\n\tn=1\n):\n\t'''Composite Gauss 1-point rule over n subintervals of (a,b), for callable f(x).\n\tUses weight function w(x) = x**p\n\t'''\n\t# Divide into subintervals\n\tintervals = np.linspace(a,b,n+1)\n\t\n\t# Bounds of intervals, as lists\n\tai = intervals[:-1]\n\tbi = intervals[1:]\n\t\n\t# The evaluated points, according to p\n\t# This only works explicitly for linear w(x), otherwise\n\t# We would need lagrange solver or something\n\tpg = powerIntegrate(p+1, ai, bi) / \\\n\t\tpowerIntegrate(p, ai, bi)\n\t\n\t# Compute the weight at each xi\n\t# Weight is just the integral of w(x) on subinterval\n\twg = powerIntegrate(p, ai, bi)\n\n\t# Evaluate f(xi) for each xi\n\tfpg = list(map(f, pg))\n\t\n\t# Sum wi*f(xi)\n\treturn wg.T @ fpg\n\n\n\n\ncases = [\n\t(\n\t\t'x',\n\t\t[(2, 5),]\n\t),\n\t\n\t(\n\t\t'x**0.5',\n\t\t[ (-0.5, 4), (-0.5, 40) ],\n\t),\n\t(\n\t\t'(1-math.sin(x))**2',\n\t\t[(-0.5, 5), (-0.5, 50), (-0.5, 100)]\n\t),\n\t(\n\t\t'(x/math.sin(x/2))**0.5',\n\t\t[(-0.5, 2), (-0.5, 10)]\n\t)\n]\n\n\n\n\nif __name__ == '__main__':\n\n\tfor i, z in enumerate(cases):\n\n\t\t# This is case #i, with function 'name'\n\t\tname, other = z\n\t\tf = lambda x: eval(name)\n\t\t\n\t\tprint('Case #{0}, f(x) = {1}'.format (i, name))\n\n\t\t# Now run over each of the p's and n's\n\t\tfor p, n in other:\n\t\t\t\n\t\t\telapsed, integral = gaussIntegrate(\n\t\t\t\t0,1,\n\t\t\t\tf,\n\t\t\t\tp=p,\n\t\t\t\tn=n\n\t\t\t)\n\n\t\t\tprint('\\t(n={0})\\t===>\\t{1:.5f} ({2:.3f} ms)'.format(n,integral, elapsed * 1000))\n\n\t\tprint()\n\n\n", "meta": {"hexsha": "537067e804d30f79ed9033615862a44160fd1af8", "size": 1788, "ext": "py", "lang": "Python", "max_stars_repo_path": "numerical_eqs/quad/gauss/run.py", "max_stars_repo_name": "alienbrett/numerical-eqs-collection", "max_stars_repo_head_hexsha": "23619bf379d53ce0facb63be08ee6a3902d404d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numerical_eqs/quad/gauss/run.py", "max_issues_repo_name": "alienbrett/numerical-eqs-collection", "max_issues_repo_head_hexsha": "23619bf379d53ce0facb63be08ee6a3902d404d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical_eqs/quad/gauss/run.py", "max_forks_repo_name": "alienbrett/numerical-eqs-collection", "max_forks_repo_head_hexsha": "23619bf379d53ce0facb63be08ee6a3902d404d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.1081081081, "max_line_length": 84, "alphanum_fraction": 0.5738255034, "include": true, "reason": "import numpy", "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273499, "lm_q2_score": 0.9184802512774205, "lm_q1q2_score": 0.877441754322103}}
{"text": "import numpy as np\n\n\ndef jacobi_iteration(A, b, tol=1e-9, Max_iter=5000):\n    \"\"\" Solve linear equations by Jacobi iteration method.\n\n    Args:\n        A: ndarray, coefficients matrix\n        b: ndarray, constant vector\n        tol: double, iteration accuracy\n        Max_iter: int, maximum iteration number\n\n    Returns:\n        y: ndarray, solution of the linear equations\n        k: int, iteration number\n    \"\"\"\n    # decompose coefficients matrix\n    D = np.diag(np.diag(A))\n    L_plus_U = D - A\n\n    # construct iterative coefficients matrix\n    B = np.linalg.inv(D).dot(L_plus_U)\n    f = np.linalg.inv(D).dot(b)\n\n    # initial solution vector\n    x = np.ones_like(b)\n    # first iteration\n    k = 1\n    y = B.dot(x) + f\n\n    # iteration\n    while np.max(np.abs(y - x)) >= tol and k < Max_iter:\n        k += 1\n        x = y\n        y = B.dot(x) + f\n\n    return (y, k)\n\n\nif __name__ == '__main__':\n    # cofficients matrix\n    A = np.array([[5, 2, 1], [2, 8, -3], [1, -3, -6]])\n    # constant vector\n    b = np.array([8, 21, 1])\n    # Jacobi iteration method\n    x, n = jacobi_iteration(A, b, 1e-5)\n\n    print(\"The solution of the linear euqations is:\")\n    for i in range(len(x)):\n        print(f'x_{i+1} = {x[i]}')\n    print(f\"The iteration number is {n}.\")\n\n", "meta": {"hexsha": "b82db8415ba4e1f3b841084b4d5b2ae160e736a4", "size": 1266, "ext": "py", "lang": "Python", "max_stars_repo_path": "LinearEquations2/jacobi_iteration_method.py", "max_stars_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_stars_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LinearEquations2/jacobi_iteration_method.py", "max_issues_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_issues_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LinearEquations2/jacobi_iteration_method.py", "max_forks_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_forks_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8867924528, "max_line_length": 58, "alphanum_fraction": 0.5758293839, "include": true, "reason": "import numpy", "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715436, "lm_q2_score": 0.9184802473724224, "lm_q1q2_score": 0.8774417529283753}}
{"text": "import numpy as np\n    \ndef ref(A):\n    for j in xrange(A.shape[0]-1):\n        for i in xrange(j+1, A.shape[0]):\n            A[i,j:] -= A[i,j] * A[j,j:] / A[j,j]\n\ndef ref2(A):\n    # This is an alternate version\n    # It is faster but less intuitive.\n    for i in xrange(A.shape[0]):\n        A[i+1:,i:] -= np.outer(A[i+1:,i]/A[i,i], A[i,i:])\n\ndef LU(A):\n    U = A.copy()\n    L = np.eye(A.shape[0])\n    for j in xrange(A.shape[0]-1):\n        for i in xrange(j+1, A.shape[0]):\n            # operation corresponding to left mult by\n            # the elementary matrix desired\n            L[i,j] = U[i,j] / U[j,j]\n            # now we apply the change to U\n            U[i,j:] -= L[i,j] * U[j,j:]\n    return L, U\n\ndef LU2(A):\n    # This is an alternate similar to ref2.\n    U = A.copy()\n    L = np.eye(A.shape[0])\n    for i in xrange(A.shape[0]-1):\n        L[i+1:,i] = U[i+1:,i] / U[i,i]\n        U[i+1:,i:] -= np.outer(L[i+1:,i], U[i,i:])\n    return L, U\n\ndef LU_inplace(A):\n    for j in xrange(A.shape[0]-1):\n        for i in xrange(j+1, A.shape[0]):\n\t\t\t# change to L\n            A[i,j] /= A[j,j]\n            # change to U\n            A[i,j+1:] -= A[i,j] * A[j,j+1:]\n\ndef LU_solve(A,B):\n    for j in xrange(A.shape[0]-1):\n        for i in xrange(j+1, A.shape[0]):\n            B[i] -= A[i,j] * B[j]\n    for j in xrange(A.shape[0]-1, -1, -1):\n        B[j] /= A[j,j]\n        for i in xrange(j):\n            B[i] -= A[i,j] * B[j]\n\ndef LU_det(A):\n    B = A.copy()\n    ref(B)\n    # now extract diagonal and take product\n    return np.prod(B.diagonal())\n\ndef cholesky(A):\n    L = np.zeros_like(A)\n    for i in xrange(A.shape[0]):\n        for j in xrange(i):\n            L[i,j]=(A[i,j] - np.inner(L[i,:j], L[j,:j])) / L[j,j]\n        sl = L[i,:i]\n        L[i,i] = sqrt(A[i,i] - np.inner(sl, sl))\n    return L\n\ndef cholesky_inplace(A):\n    for i in xrange(A.shape[0]):\n        A[i,i+1:] = 0.\n        for j in range(i):\n            A[i,j] = (A[i,j] - np.inner(A[i,:j],A[j,:j])) / A[j,j]\n        sl = A[i,:i]\n        A[i,i] = sqrt(A[i,i] - np.inner(sl, sl))\n\ndef cholesky_solve(A, B):\n    for j in xrange(A.shape[0]):\n        B[j] /= A[j,j]\n        for i in xrange(j+1, A.shape[0]):\n            B[i] -= A[i,j] * B[j]\n    for j in xrange(A.shape[0]-1, -1, -1):\n        B[j] /= A[j,j]\n        for i in xrange(j):\n            B[i] -= A[j,i] * B[j]\n", "meta": {"hexsha": "d3d5d590e3a4f2c99de16738ee35b82f3b0065f9", "size": 2329, "ext": "py", "lang": "Python", "max_stars_repo_path": "Algorithms/LUdecomposition/LUdecomposition.py", "max_stars_repo_name": "abefrandsen/numerical_computing", "max_stars_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Algorithms/LUdecomposition/LUdecomposition.py", "max_issues_repo_name": "abefrandsen/numerical_computing", "max_issues_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Algorithms/LUdecomposition/LUdecomposition.py", "max_forks_repo_name": "abefrandsen/numerical_computing", "max_forks_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7261904762, "max_line_length": 66, "alphanum_fraction": 0.4577071705, "include": true, "reason": "import numpy", "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191246389617, "lm_q2_score": 0.9184802440252811, "lm_q1q2_score": 0.8774417427204114}}
{"text": "\"\"\"\nCalculating standard deviation and normality of a user defined random set of integers\n\"\"\"\n\ndef summary_stats(n=\"Enter integer here\"):\n    \n    \"\"\"\n    Calculate STD and normality of a random set of integers\n    % function ex = summary_stats(n)\n    %- INPUT:\n    % 1) One whole integer that defines how many random numbers to generate in the data set.\n    %- OUTPUT:\n    % 1) How many values are within +/- 1 std.\n    % 2) How many values are not within +/- 1 std.\n    % 3) The percent of values that fall within +/- 1 std.\n    % 4) Is the data set normally distributed?\n    % 5) Graph of ther data set\n    \"\"\"\n    \n    import numpy as np\n    import matplotlib.pyplot as plt\n    data = np.random.randint(low=1,high=100,size=n).astype(np.float)\n    summation=0.0\n    counter=0\n    mean=0\n    sumsq=0.0\n    var=0.0\n    sqsum=0.0\n    std_list=[]\n    for i in range(len(data)):\n        summation+=data[i]\n        counter+=1\n    mean=(summation/counter)\n    for i in range(len(data)):\n        sumsq=((data[i]-mean)**2)\n        std_list.append(sumsq)\n    for i in range(len(std_list)):\n        sqsum+=std_list[i]\n    var=(sqsum/counter)\n    std=(var**0.5)\n    print('The average(mu) of this data list is: '+ str(mean) + ' and the standard deviation (sigma) is: ' + str(std))\n    lower=(mean-std)\n    upper=(mean+std)\n    yes=0.0\n    no=0.0\n    for i in data:\n        if i < (upper) and i > (lower):\n            yes+=1\n        else:\n            no+=1\n    print(\"These are how many values are within +/- 1 std: \" + str(yes))\n    print(\"These are how many values are not within +/- 1 std: \" + str(no))\n    # A normal distribution will have approx. 68% of the values within this range.  \n    print(\"The percent of values that fall within +/- 1 std are: \" + str((yes/counter)*100) + \"%\")\n    # Based on this criteria is the list normally distributed?\n    if ((yes/counter)) >= .68:\n        print(\"This is normally distributed\")\n    else:\n        print(\"This is not normally distributed\")\n    #Make a figure object\n    fig = plt.figure()\n    # make histogram plot with 10 bins\n    plt.hist(data, bins=10)\n    #Label x-axis\n    plt.xlabel(\"Integers in [data]\")\n    #Label y-axis\n    plt.ylabel(\"Count of intergers\")\n    #Label title\n    plt.title('Histrogram of numbers');\n    #Save the figure\n    fig.savefig(\"normality_testing.png\")\n    print('Image save complete')\n", "meta": {"hexsha": "9bd5e1c674a334185ec94d94ae9a4b1f44678886", "size": 2358, "ext": "py", "lang": "Python", "max_stars_repo_path": "norm_testing/normality_testing.py", "max_stars_repo_name": "madmolecularman/basic_stats", "max_stars_repo_head_hexsha": "95883df76335474e6e22983a6a9a12294bda77eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "norm_testing/normality_testing.py", "max_issues_repo_name": "madmolecularman/basic_stats", "max_issues_repo_head_hexsha": "95883df76335474e6e22983a6a9a12294bda77eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "norm_testing/normality_testing.py", "max_forks_repo_name": "madmolecularman/basic_stats", "max_forks_repo_head_hexsha": "95883df76335474e6e22983a6a9a12294bda77eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.301369863, "max_line_length": 118, "alphanum_fraction": 0.6123833757, "include": true, "reason": "import numpy", "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307661011975, "lm_q2_score": 0.9019206857566127, "lm_q1q2_score": 0.8774161916871228}}
{"text": "from math import sqrt, acos\nimport numpy as np\n\n\n# parte 1, operacoes aritmeticas com vetores\ndef norma(vetor):\n    return sqrt(sum(i ** 2 for i in vetor))\n\n\ndef mult_escalar(vetor, escalar):\n    return [escalar * i for i in vetor]\n\n\ndef add_vetores(v1, v2):\n    # implementacao para v1 e v2 de mesmo tamanho\n    return [i + j for i, j in zip(v1, v2)]\n\n\ndef prod_escalar(v1, v2):\n    # implementacao para v1 e v2 de mesmo tamanho\n    return [i * j for i, j in zip(v1, v2)]\n\n\ndef prod_vetorial(a, b):\n    # implementacao para v1 (a) e v2 (b) no espaço R3\n    resultado = []\n    resultado.append( a[1]  * b[2] - b[1] * a[2])\n    resultado.append(-a[0]  * b[2] + b[0] * a[2])\n    resultado.append( a[0]  * b[1] - b[0] * a[1])\n    return resultado\n\n\ndef angulo_entre_vetores(v1, v2):\n    return acos(sum(prod_escalar(v1, v2)) / (norma(v1) * norma(v2)))\n\n\n# parte 2, operacoes com matrizes\ndef transposicao(matriz):\n    return [list(x) for x in zip(*matriz)]\n\n\ndef mult_escalar_matriz(matriz, escalar):\n    return [mult_escalar(linha, escalar) for linha in matriz]\n\n\ndef add_matrizes(m1, m2):\n    return [add_vetores(l1, l2) for l1, l2 in zip(m1, m2)]\n\n\ndef mult_matrizes(m1, m2):\n    # return [prod_escalar(l1, l2) for l1, l2 in zip(m1, m2)]\n    np_m1 = np.matrix(m1)\n    np_m2 = np.matrix(m2)\n    return np_m1 * np_m2\n\n\ndef determinante(matriz):\n    # por sarrus e somente para matriz 3x3\n    aei = matriz[0][0] * matriz[1][1] * matriz[2][2]\n    bfg = matriz[0][1] * matriz[1][2] * matriz[2][0]\n    cdh = matriz[0][2] * matriz[1][0] * matriz[2][1]\n    ceg = matriz[0][2] * matriz[1][1] * matriz[2][0]\n    afh = matriz[0][0] * matriz[1][2] * matriz[2][1]\n    bdi = matriz[0][1] * matriz[1][0] * matriz[2][2]\n    return (aei + bfg + cdh) - (ceg + afh + bdi)\n\n\ndef inversa(matriz):\n    # Uma matriz quadrada, cujo determinante e diferente de zero e dita\n    # inversıvel e o produto de uma matriz pela sua inversa e a matriz\n    # identidade\n    # 1. Achar a matriz de determinantes menores;\n    # 2. Achar a matriz de cofatores;\n    # 3. Achar a matriz adjunta;\n    # 4. Inversa = 1/det × adjunta.\n    pass\n", "meta": {"hexsha": "6162104873b7a2e75d775759547d82c8f8c2d0ad", "size": 2102, "ext": "py", "lang": "Python", "max_stars_repo_path": "functional/reports/rel08_python.py", "max_stars_repo_name": "lucasjoao/programming_paradigms", "max_stars_repo_head_hexsha": "db90246d5bb271029122ff4c4e27a29513232872", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functional/reports/rel08_python.py", "max_issues_repo_name": "lucasjoao/programming_paradigms", "max_issues_repo_head_hexsha": "db90246d5bb271029122ff4c4e27a29513232872", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functional/reports/rel08_python.py", "max_forks_repo_name": "lucasjoao/programming_paradigms", "max_forks_repo_head_hexsha": "db90246d5bb271029122ff4c4e27a29513232872", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2987012987, "max_line_length": 71, "alphanum_fraction": 0.6265461465, "include": true, "reason": "import numpy", "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9805806506825456, "lm_q2_score": 0.8947894569842487, "lm_q1q2_score": 0.8774132279534963}}
{"text": "import numpy as np\nfrom numpy import ndarray\n\n\ndef mae(pred: ndarray, label: ndarray) -> ndarray:\n    \"\"\"Returns the mean absolute error between the predicted values and the\n    actual values.\n\n    Args:\n        pred (ndarray): the array of predicted values.\n        label (ndarray): the array of ground truths.\n    Returns:\n        (ndarray): mean absolute errors.\n    \"\"\"\n    return np.mean(np.abs(label - pred))\n\n\ndef sse(pred: ndarray, label: ndarray) -> ndarray:\n    \"\"\"Returns the residual sum of squared errors between the predicted \n    values and the actual values.\n\n    Args:\n        pred (ndarray): the array of predicted values.\n        label (ndarray): the array of ground truths.\n    Returns:\n        (ndarray): residual sum of squared errors.\n    \"\"\"\n    return np.sum(np.power((label - pred), 2))\n\n\ndef mse(pred: ndarray, label: ndarray) -> ndarray:\n    \"\"\"Returns the mean squared errors between the predicted \n    values and the actual values.\n\n    Args:\n        pred (ndarray): the array of predicted values.\n        label (ndarray): the array of ground truths.\n    Returns:\n        (ndarray): mean squared errors.\n    \"\"\"\n   return np.mean(np.power((label - pred), 2))\n\n\ndef rmse(pred: ndarray, label: ndarray) -> ndarray:\n    \"\"\"Returns the root mean squared error between the predicted values\n    and the actual values.\n\n    Args:\n        pred (ndarray): the array of predicted values.\n        label (ndarray): the array of ground truths.\n    Returns:\n        (ndarray): root mean squared errors.\n    \"\"\"\n  return np.sqrt(np.mean(np.power((label - pred), 2)))\n", "meta": {"hexsha": "2593c2ac95de0ce4600ad3963fb08124ac918580", "size": 1582, "ext": "py", "lang": "Python", "max_stars_repo_path": "regresspy/loss.py", "max_stars_repo_name": "anikatabassum-diuse1999-july-16-cancer/regresspy", "max_stars_repo_head_hexsha": "000537732d3691ccad438888dda34b291290fa9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "regresspy/loss.py", "max_issues_repo_name": "anikatabassum-diuse1999-july-16-cancer/regresspy", "max_issues_repo_head_hexsha": "000537732d3691ccad438888dda34b291290fa9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "regresspy/loss.py", "max_forks_repo_name": "anikatabassum-diuse1999-july-16-cancer/regresspy", "max_forks_repo_head_hexsha": "000537732d3691ccad438888dda34b291290fa9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-23T12:36:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T12:36:00.000Z", "avg_line_length": 28.7636363636, "max_line_length": 75, "alphanum_fraction": 0.6485461441, "include": true, "reason": "import numpy,from numpy", "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97737079469383, "lm_q2_score": 0.8976953016868439, "lm_q1q2_score": 0.8773811704025881}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\nx = np.arange(0, np.pi*2, 0.1)\n\ny = np.sin(x)\nyHalf = y/2\n\ndef rms(array):\n\n  sumOfSquares = 0.0\n\n  for val in array:\n    sumOfSquares += val**2.0\n  \n  meanSquare = sumOfSquares / array.size\n\n  return meanSquare ** 0.5\n\ncombinedRMS = ((rms(y)**2.0 + rms(yHalf)**2.0)/2.0)**0.5\ncombinedRMS2 = rms(np.concatenate((y, yHalf), axis=None))\n\nprint(f\"\\n RMS of y: {rms(y)}\")\nprint(f\"RMS of yHalf: {rms(yHalf)}\")\nprint(f\"Twice RMS of yHalf: {rms(yHalf) * 2.0}\")\nprint(f\"Combined RMS: {combinedRMS}\")\nprint(f\"Combined RMS2: {combinedRMS2} \\n\")\n\n# plt.plot(x, y)\n# plt.plot(x, yHalf)\n# plt.show()\n\n", "meta": {"hexsha": "070bd2a190f0978606b301c7e46dcf1cf53036f8", "size": 652, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/rmsEval.py", "max_stars_repo_name": "spensbot/crispy", "max_stars_repo_head_hexsha": "21a9377abc7b74d95cc43ae6dab57681d167983f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-07-03T23:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T18:26:26.000Z", "max_issues_repo_path": "Python/rmsEval.py", "max_issues_repo_name": "spensbot/crispy", "max_issues_repo_head_hexsha": "21a9377abc7b74d95cc43ae6dab57681d167983f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-30T00:32:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-30T00:32:03.000Z", "max_forks_repo_path": "Python/rmsEval.py", "max_forks_repo_name": "spensbot/crispy", "max_forks_repo_head_hexsha": "21a9377abc7b74d95cc43ae6dab57681d167983f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-08T18:50:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T18:50:01.000Z", "avg_line_length": 19.1764705882, "max_line_length": 57, "alphanum_fraction": 0.6441717791, "include": true, "reason": "import numpy", "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773707979895381, "lm_q2_score": 0.8976952968970956, "lm_q1q2_score": 0.8773811686797697}}
{"text": "#####Gradient Methods Example\n#####Muhammad Umer\n#####GIT_ROOT\n#####Import different packages\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sympy as sp\nfrom scipy.misc import derivative\n\n\n#####Define function and its derivatives in symbolic form\nx= sp.symbols('x')\ndef f(x):\n    return ((x**2)/10 - 2*sp.sin(x))\ndef d(x):\n    return derivative(f,x)\ndef df(x):\n    return x/5 - 2*sp.cos(x)\ndef ddf(x):\n    return 1/5 + 2*sp.sin(x)\n\n\n#####Simple Gradient Descent Function with fixed step size\ndef GD(x0, alpha, eps,max_iter):\n    iter = 0\n    y = x0\n    y_new = np.zeros((max_iter,1))\n    y_new[iter,] = y\n    iter += 1\n    y = y - alpha * df(y)\n    y_new[iter,] = y\n    while (np.abs(y_new[iter,] - y_new[iter-1,]) > eps and iter < max_iter):\n        iter += 1\n        if (iter == max_iter):\n            break\n        y = y - alpha* df(y)\n        y_new[iter,] = y\n    return y,iter,y_new\n\n#####Steepest Gradient Descent Function with adaptive step size\ndef SGD(x0, alpha, eps,max_iter,gamma):\n    iter = 0\n    y = x0\n    y_new = np.zeros((max_iter,1))\n    y_new[iter,] = y\n    iter += 1\n    alpha = gamma * alpha\n    y = y - alpha * df(y)\n    y_new[iter,] = y\n    while(np.abs(y_new[iter,] - y_new[iter-1,]) > eps and iter < max_iter) :\n        iter += 1\n        if(iter == max_iter):\n            break\n        y = y - alpha* df(y)\n        y_new[iter,] = y\n        alpha = gamma * alpha\n    return y,iter,y_new\n\n#####Steepest Gradient Descent Function with proposed adaptive step size\ndef SGD_proposed(x0, alpha, eps,max_iter,gamma):\n    iter = 0\n    y = x0\n    y_new = np.zeros((max_iter,1))\n    y_new[iter,] = y\n    iter += 1\n    alpha = (gamma**(iter)) * alpha\n    y = y - alpha * df(y)\n    y_new[iter,] = y\n    while(np.abs(y_new[iter,] - y_new[iter-1,]) > eps and iter < max_iter) :\n        iter += 1\n        if(iter == max_iter):\n            break\n        y = y - alpha* df(y)\n        y_new[iter,] = y\n        alpha = (gamma**(iter)) * alpha\n    return y,iter,y_new\n\n#####Steepest Gradient Descent Function with Armijo rule reduction step size\ndef SGD_w_armijo(x0, s, sig, beta, max_iter):\n    iter = 0\n    y = x0\n    alpha = s\n    y_new = np.zeros((max_iter,1))\n    y_new[iter,] = y\n    for i in range(1,max_iter):\n        alpha = s * (beta ** (i))\n        y = y - alpha * df(y)\n        print(y)\n        y_new[i,] = y\n        if ((f(y_new[i-1,]) - f(y_new[i,])) <= (1*sig *s *(beta ** (i)) * (df(y_new[i-1,]))**2)):\n            break\n    return y, i, y_new\n\n#####Newton Method\ndef NM(x0, eps, max_iter):\n        iter = 0\n        y = x0\n        y_new = np.zeros((max_iter, 1))\n        y_new[iter,] = y\n        iter += 1\n        y = y - df(y)/ddf(y)\n        y_new[iter,] = y\n        while (np.abs(y_new[iter,] - y_new[iter - 1,]) > eps and iter < max_iter):\n            iter += 1\n            if (iter == max_iter):\n                break\n            y = y - df(y)/ddf(y)\n            y_new[iter,] = y\n        return y, iter, y_new\n\n#####Call Gradient Descent with fixed step size\nres,iter,y_new = GD(x0=0.5,alpha=1,eps=1e-5,max_iter  = 1000)\n#####Call Gradient Descent with adaptive step size\nres_sgd,iter_sgd,y_new_sgd = SGD(x0=0.5,alpha=1,eps=1e-5,max_iter  = 1000, gamma = 0.5)\n#####Call Gradient Descent with proposed adaptive step size\nres_sgd_p,iter_sgd_p,y_new_sgd_p = SGD_proposed(x0=0.5,alpha=1,eps=1e-5,max_iter  = 1000, gamma = 0.95)\n#####Call Gradient Descent with armijo rule reduced step size\nres_sgd_w_armijo,iter_sgd_w_armijo,y_new_sgd_w_armijo = SGD_w_armijo(x0=0.5,s=1, sig=1e-5, beta = 0.9, max_iter = 1000)\n#####Call Newton Method\nres_NM,iter_NM,y_new_NM = NM(x0=-6,eps=1e-5,max_iter  = 1000)\n\n#####Print Results for Gradient Descent Method with fixed step size\nprint(res)\nprint(iter)\nprint(y_new[0:iter,])\n\n#####Print Results for Gradient Descent Method with adaptive step size\nprint(res_sgd)\nprint(iter_sgd)\nprint(y_new_sgd[0:iter_sgd,])\n\n#####Print Results for Gradient Descent Method with proposed step size\nprint(res_sgd_p)\nprint(iter_sgd_p)\nprint(y_new_sgd_p[0:iter_sgd_p,])\n\n#####Print Results for Gradient Descent Method with Armijo Rule\nprint(res_sgd_w_armijo)\nprint(iter_sgd_w_armijo)\nprint(y_new_sgd_w_armijo[0:iter_sgd_w_armijo,])\n\n#####Print Results for Newton Method\nprint(res_NM)\nprint(iter_NM)\nprint(y_new_NM[0:iter_NM,])\n\n\n#####Plotting Results\n\ny = np.linspace(-10,10)\nf_orig = (np.power(y, 2))/10 - 2*np.sin(y)\nplt.plot(y,f_orig)\nf1 = (np.power(y_new[0:iter,], 2))/10 - 2*np.sin(y_new[0:iter,])\nplt.plot(y_new[0:iter,],f1,'k--o')\nplt.title('steepest descent with x0=0.5 and alpha=1')\nplt.show()\nplt.figure()\nplt.plot(y,f_orig)\nf1_sgd = (np.power(y_new_sgd[0:iter_sgd,], 2))/10 - 2*np.sin(y_new_sgd[0:iter_sgd,])\nplt.plot(y_new_sgd[0:iter_sgd,],f1_sgd,'k--o')\nplt.title('steepest descent with a forgetting factor rule x0=0.5, gamma = 0.5, and alpha=1')\nplt.show()\nplt.figure()\nplt.plot(y,f_orig)\nf1_sgd_p = (np.power(y_new_sgd_p[0:iter_sgd_p,], 2))/10 - 2*np.sin(y_new_sgd_p[0:iter_sgd_p,])\nplt.plot(y_new_sgd_p[0:iter_sgd_p,],f1_sgd_p,'k--o')\nplt.title('steepest descent with a proposed forgetting factor rule x0=0.5, gamma = 0.95, and alpha=1')\nplt.show()\nplt.figure()\nplt.plot(y,f_orig)\nf1_sgd_w_armijo = (np.power(y_new_sgd_w_armijo[0:iter_sgd_w_armijo,], 2))/10 - 2*np.sin(y_new_sgd_w_armijo[0:iter_sgd_w_armijo,])\nplt.plot(y_new_sgd_w_armijo[0:iter_sgd_w_armijo,],f1_sgd_w_armijo,'k--o')\nplt.show()\nplt.figure()\nplt.plot(y,f_orig)\nf1_NM = (np.power(y_new_NM[0:iter_NM,], 2))/10 - 2*np.sin(y_new_NM[0:iter_NM,])\nplt.plot(y_new_NM[0:iter_NM,],f1_NM,'k--o')\nplt.title('Newton Method with x0=-6')\nplt.show()", "meta": {"hexsha": "92f20fb393d39fb318963403a8665ec638d1fbba", "size": 5561, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/HW#3.py", "max_stars_repo_name": "umerm5/Gradient_methods", "max_stars_repo_head_hexsha": "50b80a7df5c195f1035fe9c1b160b3b244d8ca8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/HW#3.py", "max_issues_repo_name": "umerm5/Gradient_methods", "max_issues_repo_head_hexsha": "50b80a7df5c195f1035fe9c1b160b3b244d8ca8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/HW#3.py", "max_forks_repo_name": "umerm5/Gradient_methods", "max_forks_repo_head_hexsha": "50b80a7df5c195f1035fe9c1b160b3b244d8ca8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0670391061, "max_line_length": 129, "alphanum_fraction": 0.6277647905, "include": true, "reason": "import numpy,from scipy,import sympy", "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812345563904, "lm_q2_score": 0.9059898267292559, "lm_q1q2_score": 0.8773435469036069}}
{"text": "#*************************************************************************************************************\n#Chapter 2.1 Two Dimensional Data set\n#*************************************************************************************************************\n#The numpy package transfer lists into arrays\nimport numpy as np\nmath = [91, 56, 72, 87, 99, 73, 44, 63, 21, 95]\nnp_math = np.array(math)\ngpa = [3.8, 2.1, 2.8, 3.1, 4.0, 2.5, 2.9, 2.9, 0.8, 3.9]\nnp_gpa = np.array(gpa)\n\nprint(np_math[8])\n\n#*************************************************************************************************************\n# What is the difference between list and nparray?\n# Good answer: http://stackoverflow.com/questions/176011/python-list-vs-array-when-to-use\n# But, let's try our example\n#*************************************************************************************************************\n\nlist1 = [1, 2, 3]\nlist2 = [3, 4, 5]\nnp_array1 = np.array([1, 2, 3])\nnp_array2 = np.array([3, 4, 5])\nprint(list1+list2)\nprint(np_array1 + np_array2)\n\n#*************************************************************************************************************\n# Exercise 2.1: Based on the reading above, what is the difference between array of NumPy and list? Why in\n# data science we use array?\n#*************************************************************************************************************\n\n\n# Now, let's create a real 2-dimensional data, by combining the math score and gpa together\nnp_score = np.array([[91, 3.8],\n                     [56, 2.1],\n                     [72, 2.8],\n                     [87, 3.1],\n                     [99, 4.0],\n                     [73, 2.5],\n                     [44, 2.9],\n                     [63, 2.9],\n                     [21, 0.8],\n                     [95, 3.9]])\nprint (np_score.shape)\nprint (np_score[1])\n#*************************************************************************************************************\n# Exercise 2.2 What does the output of np_score.shape described? Using np_score and bracket \"[]\" to find the GPA\n# of the exact student with the 73 math exam score (which is a 2.5 GPA). (Hint: you may use more than one bracket).\n#*************************************************************************************************************\n\n\n# Print mean height (first column)\navg = np.mean(np_score[:, 0])\nprint(\"The Average of math exam grades is \" + str(avg))\n\n# Print median height. Replace 'None'\nmed = np.median(np_score[:, 0])\nprint(\"The Median of math exam grades is \" + str(med))\n\n# Print out the standard deviation on height. Replace 'None'\nstddev = np.std(np_score[:, 0])\nprint(\"The Standard Deviation of math exam grades is: \" + str(stddev))\n\n# Print out correlation between first and second column. Replace 'None'\ncorr = np.corrcoef(np_score[:, 0], np_score[:, 1])\nprint(\"Correlation of math exam grades and overall GPA is: \" + str(corr))\n\n#*************************************************************************************************************\n# Exercise 2.3 Calculate the median of GPA for the array np.score. Print the results (followed my example above).\n#*************************************************************************************************************\n\n\n", "meta": {"hexsha": "eb0cdd2063c8b81c24299171e076a3a5f034a798", "size": 3258, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter2/Chapter2-1.py", "max_stars_repo_name": "biggyd/Python_for_Little_Piggy", "max_stars_repo_head_hexsha": "74f668ddfbaa5a5cee0d92212bad2d5640b98298", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-26T03:37:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-26T03:37:54.000Z", "max_issues_repo_path": "Chapter2/Chapter2-1.py", "max_issues_repo_name": "zdong1/Python_Scientific_Computing", "max_issues_repo_head_hexsha": "74f668ddfbaa5a5cee0d92212bad2d5640b98298", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-01-09T23:22:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-11T23:43:55.000Z", "max_forks_repo_path": "Chapter2/Chapter2-1.py", "max_forks_repo_name": "biggyd/Python_for_Little_Piggy", "max_forks_repo_head_hexsha": "74f668ddfbaa5a5cee0d92212bad2d5640b98298", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-06T07:44:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-06T07:44:50.000Z", "avg_line_length": 45.25, "max_line_length": 115, "alphanum_fraction": 0.4140577041, "include": true, "reason": "import numpy", "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812309063186, "lm_q2_score": 0.905989822921759, "lm_q1q2_score": 0.8773435399095706}}
{"text": "'''\n@author Suraj Dakua. \nNumpy IS A PACKAGE FOR MULTI-DIMENSIONAL ARRAY.\nDesigned for scientific computation.\nNumpy is array oriented computing.\nNumpy is memory efficient and provides extremely fast numerical computation.\n'''\nimport numpy as np \n'''\nBelow shown the 1-D array.\n1-D array is called a scalar\n'''\nnparr = np.array([100,101,102,103,104])\n#length returns the size of the rows in the array\nprint(len(nparr))\nprint(nparr.ndim)\n\n'''\nconvert 1-D array to 2-D array using function newaxis.\n'''\nnparr1 = nparr[:, np.newaxis]\nprint(nparr1)\n\n'''\nConvert 2-D array to 1-D array using ravel function.\nThis is also called flattening. \nSimilarly we can use rehape function to reshape the matrix.\n'''\nprint(nparr1.ravel())\n\n'''\nshape returns the size of the matrix i.e. mxn\nremember shape always return a tuple.\n'''\nprint(nparr.shape) \nprint(nparr1.shape)  \n\n'''\nBelow shown the 2-D array.\nNote the 2-D array should be list inside list.\n2-D array is called as a matrix.\n'''\n\nnparr = np.array([[100,101,102,103,104], [107, 202, 233, 124,435]])\nprint(len(nparr))\nprint(nparr.ndim)\nprint(nparr.shape)   \n\n''' \nBelow shown the 3-D array.\nNote the 3-D array should be list inside list inside list.\nSimilary we can create N-dimensional array. \nNote the N-dimensional array is called as a TENSOR.\n3-D means it has 3 matrices with shape mxn ex: 3x3x2\n'''\nnparr = np.array([[[1,2,3,4],[5,6,7,8]], [[1,2,3,4],[6,7,8,9]]])\nprint(len(nparr))\nprint(nparr.shape)\nprint(nparr.ndim)\n\n'''\nCreate np array using stepsize\nStart, Stop and Stepsize is the arguments written inside the parenthesis.\n'''\nnparr = np.arange(1,10,3)\nprint(nparr)\n\n'''\nNumpy array using linspace.\nStart Number, Stop Number, Third argument is divide the start stop in parts that we provide.\nLets see the below example.  \n'''\nnparr = np.linspace(1,2,5) #range 1 to 2 will be divided into 5 parts.\nprint(nparr)\n\n'''\nPrint zeros and ones using np.zeros and np.ones \n'''\narr = np.zeros((4,4))\nprint(arr)\narr = np.ones((4,4))\nprint(arr)\n\n'''\ncreate identity matrix where the diagonal elements of the matrix are one.\n using np.eye function. \n'''\narr = np.eye(4) #identity matrix of 4 row 4 column.\nprint(arr)\narr = np.eye(4,2)  #identity matrix of 4 rows and 2 columns.\nprint(arr)\n\n'''\nPrint diagonal matrix using np.diag\nNote diagonal matrix is a 2-D matrix.\n'''\narr = np.diag([1,2,3,4,5])\nprint(arr) #prints diagonal matrix of 5rows and 5columns with diagonal elements 1,2,3,4,5. \n#to see the diagonal elements of the matrix\nprint(np.diag(arr))\n\n'''\ngenerate random number usinng np.random.rand() \nrand() gives random number which are uniformly distributed meaning having values between 0 and 1.\n'''\narr = np.random.rand(5) \nprint(arr)  #print any 5 random numbers.\narr = np.random.randn(4)  #randn - random normal.\nprint(arr)\n\n'''\nassign a custom value to matrix.\n'''\narr1 = np.diag([1,2,3])\narr1[2,1] = 10 #assign value 10 to third row first column of matrix arr.\nprint(arr1)\n\n'''\nSlicing the numpy array\n'''\narr = np.arange(10)\n#start index stop index and step size.\nprint(arr[0:9:3]) \n\n'''\nChange the value of array \n'''\narr[5:] = 8 #change the value of array from index 5 to the last index.\nprint(arr)\n\n'''\nReverse a array\n'''\na = arr[::-1] #-1 indicates the inde of last element of the array.\nprint(a)\n    \n'''\nPerform scalar addition and squaring each element of the array.\n'''\narr = np.array([1,2,3,4])\nprint(arr+1) #this is known as scalar addition. Adding 1 to each element fof the numpy array.\nprint(arr**2) #square each element of the array. Also known as exponent operator.\n\n'''\nPerform subtraction, multiplication of two array.\n'''\na = np.ones(4) + 1\nprint(a)\nprint(a - arr)\nprint(arr*a)\n\n'''\nMatrix-Matrix multiplication\n'''\na = np.diag([1,2,3])\nb = np.diag([5,6,7])\nprint(a*b)\n\n'''\nCompare element-wise comparison and it returns a boolean.\n'''\na = np.array([1,2,3,4])\nb = np.array([5,6,7,8])\nprint(a==b)\nprint(b>a)\n\n'''\nArray-wise comparisions using array_equal function.\n'''\nprint(np.array_equal(a,b))\n\n'''\nArray using mathematical function sin, log, exponentaion(base of natural log.)\n'''\nprint(np.sin(a))  #returns sin value of elements in a array.\nprint(np.log(b))  #returns logarithmic values of array.\nprint(np.exp(a))  #returns exponent values of an array.\nprint(np.cos(a))  #return cos values of an array.\n\n'''\nFind the sum of all the elements in an array.\nwhen axis = 0 it does the column wise sum\nwhen axis = 1/-1 it does the row wise sum\n'''\n# print(arr.sum(axis=0))\n# print(arr.sum(axis=1))\n\n'''\nFind the min and max of the array.\n'''\nprint(a.min())\nprint(b.max())\nprint(b.argmax())  #argmax return the index of the maximum value of the array.\nprint(a.argmin())\n\n'''\nany,all, median, std, transponse of an array.\n'''\nprint(np.any(a==2))\nprint(np.all(a==b))\nprint(np.median(a))\nc = np.transpose(arr1)\nprint(c)\n\n\n", "meta": {"hexsha": "c15a7d34bd700758552657fee828ccf27e539664", "size": 4789, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numpy.py", "max_stars_repo_name": "surajdakua/Numpy", "max_stars_repo_head_hexsha": "01bff351cb21a41a81b6740a677a8f197f6eebf4", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-05T10:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-05T10:39:13.000Z", "max_issues_repo_path": "Numpy.py", "max_issues_repo_name": "surajdakua/Numpy", "max_issues_repo_head_hexsha": "01bff351cb21a41a81b6740a677a8f197f6eebf4", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numpy.py", "max_forks_repo_name": "surajdakua/Numpy", "max_forks_repo_head_hexsha": "01bff351cb21a41a81b6740a677a8f197f6eebf4", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2475728155, "max_line_length": 97, "alphanum_fraction": 0.700563792, "include": true, "reason": "import numpy", "num_tokens": 1343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.928408800060238, "lm_q1q2_score": 0.8773414077969576}}
{"text": "# logistic_distribution\r\n# used to describe growth\r\n# used extensively in machine learning in logistic regression, neural networks etc.\r\n# It has three parameters.\r\n# loc = mena, where the peak is, Default 0.\r\n# scale = standard deviation, the flatness of distribution. Default 1.\r\n# size = The shape of the returned array.\r\n\r\n# Draw 2x3 samples from a logistic distribution with mean at 1 and stddev 2.0\r\n\r\nfrom numpy import random\r\n\r\nx = random.logistic(loc = 1, scale = 2, size = (2,3))\r\n\r\nprint(x)\r\n\r\n# visualization of logistic distribution\r\n\r\n# from numpy import random\r\nimport matplotlib.pyplot as plt \r\nimport seaborn as sns \r\n\r\nsns.distplot(random.logistic(size = (1000)), hist = False)\r\nplt.show()\r\n\r\n# Difference between logistic and normal distribution\r\n\"\"\"\r\nBoth distributions are near identical, but logistic distribution\r\nhas more area under the tails. i.e. It representage more possibility\r\nof occurence of an event further away from mean.  For higher value of scale\r\n(standard deviation) the normal and logistic distributions are near identical\r\napart from the peak\r\n\"\"\"\r\n\r\n# from numpy import random\r\n# import matplotlib.pyplot as plt\r\n# import seaborn as sns \r\n\r\nsns.distplot(random.normal(scale = 2, size = 1000), hist = False, label = 'Normal')\r\nsns.distplot(random.logistic(size = 1000), hist = False, label = 'Logistic')\r\n\r\nplt.show()", "meta": {"hexsha": "f651b307a06f68867e46737668f7b2359b809487", "size": 1357, "ext": "py", "lang": "Python", "max_stars_repo_path": "logistic_distribution.py", "max_stars_repo_name": "khinthandarkyaw98/Python_Practice", "max_stars_repo_head_hexsha": "9b431129c79315a57dae81048a22bf85c4b5132c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "logistic_distribution.py", "max_issues_repo_name": "khinthandarkyaw98/Python_Practice", "max_issues_repo_head_hexsha": "9b431129c79315a57dae81048a22bf85c4b5132c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logistic_distribution.py", "max_forks_repo_name": "khinthandarkyaw98/Python_Practice", "max_forks_repo_head_hexsha": "9b431129c79315a57dae81048a22bf85c4b5132c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3095238095, "max_line_length": 84, "alphanum_fraction": 0.7347089167, "include": true, "reason": "from numpy", "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885303, "lm_q2_score": 0.9124361610722159, "lm_q1q2_score": 0.8773382195132431}}
{"text": "# -*- coding: utf-8 -*-\n\nimport math\nimport numpy\n\nPI2 = math.pi * 2\n\n\ndef dft(nums):\n    \"\"\"\n    离散傅里叶变换\n    \"\"\"\n    N = len(nums)\n    x = [0 + 0j for i in range(N)]\n    for n in range(N):\n        xn = nums[n]\n        for k in range(N):\n            re = xn * math.cos(n * PI2 * k / N)   # 实部\n            im = -xn * math.sin(n * PI2 * k / N)  # 虚部\n            x[k] += complex(re, im)\n    return x\n\ndef dft2(nums):\n    N = len(nums)\n    x = [0 + 0j for i in range(N)]\n    for k in range(N):\n        for n in range(N):\n            xn = nums[n]\n            re = xn * math.cos(n * PI2 * k / N)\n            im = -xn * math.sin(n * PI2 * k / N)\n            x[k] += complex(re, im)\n    return x\n\n\ndef idft(nums):\n    \"\"\" 逆傅里叶变换\n    args:\n        nums: 复数，傅里叶变换的结果\n    \"\"\"\n    N = len(nums)\n    x = [0 + 0j for i in range(N)]\n\n    for n in range(N):\n        for k in range(N):\n            re = nums[k].real * math.cos(PI2 * n * k / N) - nums[k].imag * math.sin(PI2 * n * k / N)\n            im = nums[k].real * math.sin(PI2 * n * k / N) + nums[k].imag * math.cos(PI2 * n * k / N)\n            re /= N\n            im /= N\n            x[n] += complex(re, im)\n\n    return x\n\ndef idft2(nums):\n    N = len(nums)\n    x = [0 + 0j for i in range(N)]\n\n    for k in range(N):\n        for n in range(N):\n            re = nums[k].real * math.cos(PI2 * n * k / N) - nums[k].imag * math.sin(PI2 * n * k / N)\n            im = nums[k].real * math.sin(PI2 * n * k / N) + nums[k].imag * math.cos(PI2 * n * k / N)\n            re /= N\n            im /= N\n            x[n] += complex(re, im)\n\n    return x\n\n\nif __name__ == '__main__':\n    N = 1024 * 8\n    nums = [i for i in range(N)]\n    np_result = numpy.fft.fft(nums)\n    dft_result = dft2(nums)\n\n    inp_result = numpy.fft.ifft(dft_result)\n    ix = idft2(dft_result)\n\n    # print(\"------nums--------\")\n    # print(nums)\n\n    # print(\"------numpy fft--------\")\n    # print(np_result)\n    # print(\"------dft--------\")\n    # print(dft_result)\n\n    # print(\"------numpy ifft--------\")\n    # print(inp_result)\n\n    # print(\"------idft--------\")\n    # print(ix)\n\n    success = True\n    for i in range(N):\n        if math.fabs(nums[i].real - ix[i].real) > 1e-05:\n            print(\"[%d]: %f != %f\" % (i, nums[i], ix[i]))\n            success = False\n    print(\"success: %s\\n\" % str(success))\n", "meta": {"hexsha": "b5d54f43751f6b01a3b54819ebe2f742dbc0a030", "size": 2307, "ext": "py", "lang": "Python", "max_stars_repo_path": "DFT/python/dft.py", "max_stars_repo_name": "QuantumLiu/algorithms-cuda", "max_stars_repo_head_hexsha": "0999b244c08dc9d92cbcdfb15215b10849df2840", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 55, "max_stars_repo_stars_event_min_datetime": "2016-12-29T08:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T10:41:59.000Z", "max_issues_repo_path": "DFT/python/dft.py", "max_issues_repo_name": "kevinyu1949/algorithms-cuda", "max_issues_repo_head_hexsha": "bdef6b744f2338348a08bd26a48969bb1d4fa316", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-02-25T01:46:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-23T05:16:06.000Z", "max_forks_repo_path": "DFT/python/dft.py", "max_forks_repo_name": "kevinyu1949/algorithms-cuda", "max_forks_repo_head_hexsha": "bdef6b744f2338348a08bd26a48969bb1d4fa316", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 40, "max_forks_repo_forks_event_min_datetime": "2017-01-10T06:53:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T13:47:41.000Z", "avg_line_length": 23.7835051546, "max_line_length": 100, "alphanum_fraction": 0.4425661032, "include": true, "reason": "import numpy", "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854146791214, "lm_q2_score": 0.9046505440982949, "lm_q1q2_score": 0.8773169030480578}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\ndef geo_brownian_paths(S, T, r, q, sigma, steps, N):\n    '''\n    S = Stock price\n    T = time to maturity\n    r = risk free\n    q = dividend rate\n    steps = time increments\n    N = Number of trials\n\n    returns:\n    matrix of price paths\n    '''\n\n    dt = T/steps\n\n    # ito integral\n    ST = np.log(S) + np.cumsum(((r - q - sigma**2/2)*dt +\\\n\n    sigma*np.sqrt(dt) * \\\n\n    np.random.normal(size=(steps,N))),axis=0)\n\n    return np.exp(ST)\n\ndef prob_over(value, S, T, r, q, sigma, steps, N, show_plot=True):\n    '''\n    value: value you want to check S_T is above p(value < S_T)\n    '''\n    paths = geo_brownian_paths(S,T, r, q, sigma, steps, N)\n    ST = paths[-1]\n    over = len(ST[ST>value])\n    # print(f\"probability of stock being above {value} is {round(over/len(ST)*100,3)}%\")\n\n    if show_plot:\n        _ = plt.hist(paths[-1],bins=200)\n        plt.axvline(value, color='black', linestyle='dashed', linewidth=2)\n        plt.show()\n\n    return over/len(ST)\n\n\n\ndef prob_under(value, S, T, r, q, sigma, steps, N, show_plot=True):\n    '''\n    value: this refers to the value you want to check p(S_T < value)\n    returns: probability in %\n    '''\n    paths = geo_brownian_paths(S,T, r, q, sigma, steps, N)\n    ST = paths[-1]\n    under = len(ST[ST<value])\n    \n    # print(f\"probability of stock being below {value} is {round(under/len(ST)*100,3)}%\")\n\n    if show_plot:\n        _ = plt.hist(paths[-1],bins=200,color='blue')\n        plt.axvline(value, color='black', linestyle='dashed', linewidth=2) \n        plt.show()   \n\n    return under/len(ST)\n\n# if __name__ == \"__main__\":\n    \n    # #example of geo brownian paths\n    # paths = geo_brownian_paths(100, 1, 0.05, 0.02, 0.20, 100, 100)\n\n    # #show distribution of final values\n    # _ = plt.hist(paths[-1],bins=200)\n\n    # #show geometric brownian paths\n    # _ = plt.plot(paths)\n    # plt.show()\n\n    #example\n    # S = 121 #price today\n    # value = 116\n    # T = 1 # one year , for one month 1/12, 2months = 2/12 etc\n    # r = 0.01 # riskfree rate: https://www.treasury.gov/resource-center/data-chart-center/interest-rates/pages/TextView.aspx?data=billrates\n    # q = 0.007 # dividend rate\n    # sigma = 0.4 # annualized volatility\n    # steps = 1 # no need to have more than 1 for non-path dependent security\n    # N = 1000000 # larger the better\n\n    # # probability of over value\n    # # Params: value, S, T, r, q, sigma, steps, N, \n    # # prob_over(value, S, T, r, q, sigma, steps, N, show_plot=True)\n\n    # # #probability of less than value , Not showing hist\n    # prob_under(value, S, T, r, q, sigma, steps, N, show_plot=True)", "meta": {"hexsha": "e9e866fdd5c58e5dfdc1db6a51688c897496ef14", "size": 2673, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/gbm.py", "max_stars_repo_name": "peppermanvince/tos_options_dashboard", "max_stars_repo_head_hexsha": "ddf77966d12f401b16783916b1769a9417d3838d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2021-06-24T05:46:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T15:08:13.000Z", "max_issues_repo_path": "src/gbm.py", "max_issues_repo_name": "peppermanvince/tos_options_dashboard", "max_issues_repo_head_hexsha": "ddf77966d12f401b16783916b1769a9417d3838d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gbm.py", "max_forks_repo_name": "peppermanvince/tos_options_dashboard", "max_forks_repo_head_hexsha": "ddf77966d12f401b16783916b1769a9417d3838d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-07-15T06:02:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T11:48:08.000Z", "avg_line_length": 29.0543478261, "max_line_length": 140, "alphanum_fraction": 0.6064347175, "include": true, "reason": "import numpy,from scipy", "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854138058637, "lm_q2_score": 0.9046505383142494, "lm_q1q2_score": 0.8773168966487817}}
{"text": "\"\"\"Randomized LU decomposition.\"\"\"\nimport numpy as np\nimport scipy.linalg as la\nfrom typing import Tuple\n\nPQLU = Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]\n\n\ndef randomized_lu(A: np.ndarray, k: int, l: int, seed: int = 0) -> PQLU:\n    \"\"\"Performs a randomized rank-k LU decomposition of A.\n    \n    Adapted from Shabat et al. 2013, Algorithm 4.1.\n\n    Args:\n        A: An mXn matrix to decompose.\n        k: Rank of the decomposition.\n        l: Number of columns to use in the random matrix.\n        seed: Random seed.\n\n    Returns:\n        A 4-tuple containing P, Q, L, U.\"\"\"\n    rand = np.random.RandomState(seed)\n    # (Algorithm notes copied verbatim from paper.)\n    # 1. Create a matrix G of size n × l whose entries are i.i.d. Gaussian\n    # random variables with zero mean and unit standard deviation.\n    assert l >= k\n    m, n = A.shape\n    G = rand.randn(n, l)\n\n    # 2. Y ← AG.\n    Y = A @ G\n    assert Y.shape == (m, l)\n\n    # 3. Apply RRLU decomposition (Theorem 3.1) to Y such that P Y Qy = LyUy.\n    #\n    # Remark 4.2. In practice, it is sufficient to perform step 3 in Algorithm\n    # 4.1 using standard LU decomposition with partial pivoting instead of\n    # applying RRLU. The cases where U grows exponentially are extremely rare...\n    P, L_y, U_y = la.lu(Y)\n    P = P.T\n    Q_y = np.identity(l)  # TODO: replace with RRLU\n    assert P.shape == (m, m)\n    assert L_y.shape == (m, l)\n    assert U_y.shape == (l, l)\n    #assert np.allclose(P @ Y, L_y @ U_y)\n    #assert np.allclose(P @ Y @ Q_y, L_y @ U_y)\n\n    # 4. Truncate Ly and Uy by choosing the first k columns and the first k rows,\n    # respectively, such that Ly ← Ly(:, 1 : k) and Uy ← Uy(1 : k, :).\n    L_y = L_y[:, :k]\n    U_y = U_y[:k, :]\n    assert L_y.shape == (m, k)\n    assert U_y.shape == (k, l)\n\n    # 5. B ← (L_y †) PA\n    L_y_pseudoinverse = la.pinv(L_y)\n    assert L_y_pseudoinverse.shape == (k, m)\n    B = L_y_pseudoinverse @ P @ A\n    assert B.shape == (k, n)\n\n    # 6. Apply LU decomposition to B with column pivoting BQ = L_b U_b.\n    Q, U_b, L_b = la.lu(B.T)\n    #Q = Q.T\n    L_b = L_b.T\n    U_b = U_b.T\n    assert Q.shape == (n, n)\n    assert L_b.shape == (k, k)\n    assert U_b.shape == (k, n)\n    #assert np.allclose(B @ Q, L_b @ U_b)\n\n    # 7. L ← L_y L_b.\n    L = L_y @ L_b\n    assert L.shape == (m, k)\n\n    return P, Q, L, U_b\n", "meta": {"hexsha": "1d065f1a5b01dcca6c7a7a8f8392fd06df430cc0", "size": 2340, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/randomized_lu.py", "max_stars_repo_name": "pjrule/math126-final-project", "max_stars_repo_head_hexsha": "93c9953366fd684289ba97297ab16651f8c92d39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/randomized_lu.py", "max_issues_repo_name": "pjrule/math126-final-project", "max_issues_repo_head_hexsha": "93c9953366fd684289ba97297ab16651f8c92d39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/randomized_lu.py", "max_forks_repo_name": "pjrule/math126-final-project", "max_forks_repo_head_hexsha": "93c9953366fd684289ba97297ab16651f8c92d39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7894736842, "max_line_length": 81, "alphanum_fraction": 0.5948717949, "include": true, "reason": "import numpy,import scipy", "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969785415552379, "lm_q2_score": 0.9046505318875316, "lm_q1q2_score": 0.8773168919962305}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n#The feature of activation function-Nonlinear function->if activation function is linear, then it means  just updating of weight(it's called by projection layer or linear layer)\n\n#Sigmoid Function\ndef sigmoid(x):\n    return 1/(1+np.exp(-x))\n\nx=np.arange(-5.0,5.0,0.1)\ny=sigmoid(x)\n\nplt.plot(x,y)\nplt.plot([0,0],[1.0,0.0],':')\nplt.title('Sigmoid Function')\nplt.show()\n\n#that's why we don't use Sigmoid. because of Vanishing Gradient. not update forward weight\n\n#Hyperbolic tangent function\nx=np.arange(-5.0,5.0,0.1)\ny=np.tanh(x)\n\nplt.plot(x,y)\nplt.plot([0,0],[-1.0,1.0],':')\nplt.axhline(y=0,color='orange',linestyle='--')\nplt.title('Tanh Function')\nplt.show()\n#Hyperbolic tangent is well used than Sigmoid function because of low Vanishing Gradient than Sigmoid\n\n#ReLU Function\ndef relu(x):\n    return np.maximum(0,x)\n\nx=np.arange(-5.0,5.0,0.1)\ny=relu(x)\n\nplt.plot(x,y)\nplt.plot([0,0],[5.0,0.0],':')\nplt.title('Relu Function')\nplt.show()\n#problem->if input is - then weight is 0 too. it calls dying ReLU\n\n#Leaky ReLU\na=0.1#(Leaky rate)\ndef leaky_relu(x):\n    return np.maximum(a*x,x)\n\nx=np.arange(-5.0,5.0,0.1)\ny=leaky_relu(x)\n\nplt.plot(x,y)\nplt.plot([0,0],[5.0,0.0],':')\nplt.title('Leaky ReLU Function')\nplt.show()\n\n#Softmax Function\nx=np.arange(-5.0,5.0,0.1)\ny=np.exp(x)/np.sum(np.exp(x))\n\nplt.plot(x,y)\nplt.title('Softmax Function')\nplt.show()\n#Sigmoid Function is well used at Binary Classification, Softmax function is well used at MultiClass Classification\n\n#Theory\n#Binary Classification->Sigmoid_active F, nn.BCELoss()_cost F\n#MultiClass Classificationi->Softmax_active F, nn.CrossEntropyLoss()_cost F (p.s)nn.CrossEntropyLoss has already Softmax Function\n#Regressive->none, MSE_cost F\n", "meta": {"hexsha": "a134ed53dd0dd067011482bc22d28e1698c4adb8", "size": 1745, "ext": "py", "lang": "Python", "max_stars_repo_path": "6. Aritificial Neural Network/6-6) Activation function.py", "max_stars_repo_name": "choijiwoong/-ROKA-torch-tutorial-files", "max_stars_repo_head_hexsha": "c298fdf911cd64757895c3ab9f71ae7c3467c545", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "6. Aritificial Neural Network/6-6) Activation function.py", "max_issues_repo_name": "choijiwoong/-ROKA-torch-tutorial-files", "max_issues_repo_head_hexsha": "c298fdf911cd64757895c3ab9f71ae7c3467c545", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6. Aritificial Neural Network/6-6) Activation function.py", "max_forks_repo_name": "choijiwoong/-ROKA-torch-tutorial-files", "max_forks_repo_head_hexsha": "c298fdf911cd64757895c3ab9f71ae7c3467c545", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9285714286, "max_line_length": 177, "alphanum_fraction": 0.71747851, "include": true, "reason": "import numpy", "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969785409439575, "lm_q2_score": 0.9046505312448598, "lm_q1q2_score": 0.8773168858430255}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\nJ_value = []\n\n\ndef normalization(X):\n    shape = X.shape\n    means = np.zeros((shape[1], 1))\n    stds = np.zeros((shape[1], 1))\n    for col in range(shape[1]):\n        means[col] = np.mean(X[:, col])\n        stds[col] = np.std(X[:, col])\n        X[:, col] = (X[:, col] - means[col]) / stds[col]\n    \n    return X, means.T, stds.T\n\n\ndef cost_function(X, y, theta, m):\n    a = np.dot(X, theta) # h(X)\n    b = a - y[:][np.newaxis].T\n    return np.dot(b.T, b)[0][0] / 2 / m\n\n\ndef gradient_descent(X, y, iteration=1500, alpha=0.01):\n    shape = X.shape\n    m = shape[0] # num of samples\n    theta = np.zeros((1, shape[1]+1)).T # initiate theta\n\n    X = np.concatenate((np.ones((m, 1)), X), axis=1) # add a colum of one to X\n\n    J_value.append(cost_function(X, y, theta, m))\n    print(shape[1] + 1)\n    for i in range(iteration):\n        theta_temp = theta\n        a = np.dot(X, theta_temp) # h(X)\n        b = a - y[:][np.newaxis].T\n\n        for col in range(shape[1] + 1):\n            theta[col] = theta_temp[col] - alpha * np.dot(b.T, X[:, col]) / m\n\n        J_value.append(cost_function(X, y, theta, m))\n\n    return theta.T[0]\n\n\ndef normal_equations(X,y):\n    shape = X.shape\n    m = shape[0] # num of samples\n\n    X = np.concatenate((np.ones((m, 1)), X), axis=1) # add a colum of one to X\n\n    a = np.dot(X.T, X)\n    b = np.linalg.pinv(a)\n    c = np.dot(b, X.T)\n\n    return np.dot(c, y)\n        \n\n\ndef main():\n    data = np.loadtxt('./ex1/ex1/ex1data2.txt', delimiter=',')\n    X = data[:, :-1]\n    y = data[:, -1]\n    \n    theta_1 = normal_equations(X,y) # solve by normal equation\n\n    X, means, stds = normalization(X) # normalize before gradient descent\n    theta_2 = gradient_descent(X, y, iteration=500)\n\n    print('Theta solved by normal equation is: ', theta_1)\n    print('Theta solved by gradient descent is: ', theta_2)\n\n    x = np.array([1., 1650, 3])\n    print('Price of the 1650-square-foot house with 3 bedrooms is (normal equation): ', np.dot(x, theta_1.T))\n    x[1:] = (x[1:] - means) / stds\n    print('Price of the 1650-square-foot house with 3 bedrooms is (gradient descent): ', np.dot(x, theta_2.T))\n\n    # plot J\n    plt.plot(J_value)\n    plt.xlabel('Number of iterations')\n    plt.ylabel('Cost J')\n    plt.show()\n\n\n\nif __name__ == '__main__':\n    main()\n    \n\n", "meta": {"hexsha": "05cdd8d1f9ce32e8f726400b5e66927b706af340", "size": 2332, "ext": "py", "lang": "Python", "max_stars_repo_path": "ex1/ex1/Linear-regression-with-multiple-variables.py", "max_stars_repo_name": "LixiangHan/cs229-assignments", "max_stars_repo_head_hexsha": "3ed75e9c95b60e8c58a86c5adce3bd7cd4ea74a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex1/ex1/Linear-regression-with-multiple-variables.py", "max_issues_repo_name": "LixiangHan/cs229-assignments", "max_issues_repo_head_hexsha": "3ed75e9c95b60e8c58a86c5adce3bd7cd4ea74a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex1/ex1/Linear-regression-with-multiple-variables.py", "max_forks_repo_name": "LixiangHan/cs229-assignments", "max_forks_repo_head_hexsha": "3ed75e9c95b60e8c58a86c5adce3bd7cd4ea74a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.347826087, "max_line_length": 110, "alphanum_fraction": 0.5728987993, "include": true, "reason": "import numpy", "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182844, "lm_q2_score": 0.9196425383355795, "lm_q1q2_score": 0.8773078058908369}}
{"text": "\"\"\"\nNewton\n\nA package to solve non-linear equations.\n\nCopyright (c) 2020 Felipe Markson dos Santos Monteiro <fmarkson@gmail.com>\nMIT License.\n\"\"\"\n\nfrom numpy.linalg import solve as default_solver\nfrom numpy import ndarray\nfrom typing import Tuple, Callable, Union\n\n\ndef solve(\n    func: Callable[[ndarray], ndarray],\n    jacobian: Callable[[ndarray], ndarray],\n    x0: ndarray,\n    *,\n    tol: Union[int, float, ndarray] = 0.001,\n    maxiter: int = 100,\n    solver: Callable[[ndarray, ndarray], ndarray] = default_solver,\n    verbose: bool = True,\n) -> Tuple[bool, ndarray, ndarray]:\n    \"\"\"\n    A Newton–Raphson method implementation for finding roots . See (https://en.wikipedia.org/wiki/Newton%27s_method)\n        Ex:\n            import newton\n            import numpy as np\n\n            (converged, error, solution) = newton.solve(\n            lambda x: np.array([x ** 2]),\n            lambda x: np.array([2 * x]),\n            x0=np.array([1.2]),\n            tol=0.001,\n            maxiter=100,\n            verbose=False,\n            )\n\n            print(solution)            \n            >>> [0.01875]\n    Args:\n        func : The func is a F, where F: ℝᵏ → ℝᵏ and k is the number of dimensions.\n        jacobian : The Jacobian Matrix of func. See (https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant).\n        x0 : The intial guess, where x0 ∈ ℝᵏ.\n        tol : The tolerance. If ndarray, the tolerance for each dimension must be specified.\n        maxiter : The maximum number of iterations.\n        solver : A linear matrix equation solver. If not specified, the numpy.linalg.solve is used. See (https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html)\n        verbose :  If True, prints the iteration and the absolute maximum error. \n    Returns:\n        If converged, the mismatch vectors, and the current solution.\n\n    \"\"\"  # noqa\n\n    Fx = func(x0)\n    for indx in range(0, maxiter):\n        Jx = jacobian(x0)\n        deltaX = solver(-Jx, Fx)\n        x0 = x0 + deltaX\n        Fx = func(x0)\n        Fxabs = abs(Fx)\n        if verbose:\n            print(f\"## Iteration {indx}. Absolute maximum error: {Fxabs.max()}\")\n\n        if all(Fxabs <= tol):\n            return (True, Fx, x0)\n\n    return (False, Fx, x0)\n", "meta": {"hexsha": "1599bbddef1200074e5e590087974483a1a77681", "size": 2248, "ext": "py", "lang": "Python", "max_stars_repo_path": "newtonpy/__init__.py", "max_stars_repo_name": "felipemarkson/newtonpy", "max_stars_repo_head_hexsha": "7ee009e8791e0e5dda0a53a2cf57931a5a99ff81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "newtonpy/__init__.py", "max_issues_repo_name": "felipemarkson/newtonpy", "max_issues_repo_head_hexsha": "7ee009e8791e0e5dda0a53a2cf57931a5a99ff81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "newtonpy/__init__.py", "max_forks_repo_name": "felipemarkson/newtonpy", "max_forks_repo_head_hexsha": "7ee009e8791e0e5dda0a53a2cf57931a5a99ff81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5797101449, "max_line_length": 178, "alphanum_fraction": 0.6045373665, "include": true, "reason": "import numpy,from numpy", "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832345, "lm_q2_score": 0.9196425344813868, "lm_q1q2_score": 0.8773077973996931}}
{"text": "import os\nfrom scipy.special import comb\n\n\ndef bagging_proba(n, acc=0.8):\n    ''' n independent estimators with accuracy 'acc', then what is estimated\n    accuracy of bagging estimator with majority voting ?\n    Note, 6 or more out of 10 is called a majority. \n    '''\n    if n == 1:\n        return acc\n    error = 0\n    for i in range(n // 2 + 1):\n        # only i estimator makes correct guess\n        error += comb(n, i, exact=False) * \\\n            ((1 - acc) ** (n - i)) * ((acc) ** i)\n    return 1 - error\n\n\nfor i in range(1, 10):\n    n = i * 10\n    print(n, bagging_proba(n))\n\n'''\n10 0.9672065024000001\n20 0.997405172599326\n30 0.9997687743883322\n40 0.9999783081068737\n50 0.9999979051451444\n60 0.9999997938783113\n70 0.999999979452253\n80 0.999999997931789\n90 0.9999999997902754\n'''\n", "meta": {"hexsha": "045eba1d128e56a561c913a6b1cb79ea20be3436", "size": 787, "ext": "py", "lang": "Python", "max_stars_repo_path": "ipynb/probability/codes/bagging_probability.py", "max_stars_repo_name": "NilLau/NilLau.github.io", "max_stars_repo_head_hexsha": "e55768be0be4d6549b24c702554c11e64958d4c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ipynb/probability/codes/bagging_probability.py", "max_issues_repo_name": "NilLau/NilLau.github.io", "max_issues_repo_head_hexsha": "e55768be0be4d6549b24c702554c11e64958d4c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-06-20T10:05:10.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-08T04:53:01.000Z", "max_forks_repo_path": "ipynb/probability/codes/bagging_probability.py", "max_forks_repo_name": "117ami/117ami.github.io", "max_forks_repo_head_hexsha": "e55768be0be4d6549b24c702554c11e64958d4c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4857142857, "max_line_length": 76, "alphanum_fraction": 0.6404066074, "include": true, "reason": "from scipy", "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9888419700672151, "lm_q2_score": 0.8872045937171068, "lm_q1q2_score": 0.877305138303907}}
{"text": "from numpy import array, full, empty\n\n# System of Equations\nA = array([[4, 1, 2, -1],\n           [3, 6, -1, 2],\n           [2, -1, 5, -3],\n           [4, 1, -3, -8]], float)\nB = array([2, -1, 3, 2], float)\n\nN = len(B)\n\nX = full(N, 1.0, float) # Initial Gusses array([1.0, 1.0, 1.0, 1.0], float)]\n\nXnew = empty(N, float)  # Creates empty array of size n\n\nfor iterations in range(100):\n    for i in range(N):\n\n        s = 0\n        for j in range(N):\n            if j == i: continue\n            s += A[i,j]*X[j]\n\n        Xnew[i] = - 1/A[i,i] * (s - B[i])\n\n\n    if (abs(Xnew - X) < 1e-6).all():\n        break\n    else:\n        X = Xnew.copy() # X = Xnew would cause errors by binding memory address\n\nelse:\n    raise OverflowError(\"The System does not have Diagonal Dominance\")\n\n\nprint(\"The Solution of the System:\")\nfor i in range(N):\n    print('X[', i+1, '] = ', round(X[i], 6), sep='')\nprint('The Number of Iterations: %d' % (iterations+1))\n\n\n'''\n4x1 +  x2 + 2x3 -  x4 = 2\n3x1 + 6x2 -  x3 + 2x4 = -1\n2x1 -  x2 + 5x3 - 3x4 = 3\n4x1 +  x2 - 3x3 - 8x4 = 2\n\nx1 = - 1/4 ( x2 + 2x3 -  x4 - 2)\nx2 = - 1/6 (3x1 -  x3 + 2x4 + 1)\nx1 = - 1/5 (2x1 -  x2 - 3x4 - 3)\nx2 =   1/8 (4x1 +  x2 - 3x3 - 2)\n\nxnew[i] = - 1/aii (∑ aij*xj - bi)   where i = 1 to n, j = 1 to n and j ≠ i\n\n'''\n", "meta": {"hexsha": "244ebd981b9bf46bb4133dd1c898b60fc60cf5dc", "size": 1265, "ext": "py", "lang": "Python", "max_stars_repo_path": "5. Systems of Linear Equations/7. Jacobi's (Iteration) Method.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5. Systems of Linear Equations/7. Jacobi's (Iteration) Method.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5. Systems of Linear Equations/7. Jacobi's (Iteration) Method.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5892857143, "max_line_length": 79, "alphanum_fraction": 0.4909090909, "include": true, "reason": "from numpy", "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140206578809, "lm_q2_score": 0.9073122201074847, "lm_q1q2_score": 0.8772929067361562}}
{"text": "'''\nPlotting the ECDF\n100xp\n\nYou will now use your ecdf() function to compute the ECDF for the petal lengths of\nAnderson's Iris versicolor flowers. You will then plot the ECDF. Recall that your ecdf()\nfunction returns two arrays so you will need to unpack them. An example of such unpacking\nis x, y = foo(data), for some function foo().\n\nInstructions\n-Use ecdf() to compute the ECDF of versicolor_petal_length. Unpack the output into x_vers and y_vers.\n-Plot the ECDF as dots. Remember to include marker = '.' and linestyle = 'none' in addition to x_vers and y_vers as arguments inside plt.plot().\n-Set the margins of the plot with plt.margins() so that no data points are cut off. Use a 2% margin.\n-Label the axes. You can label the y-axis 'ECDF'.\n-Show your plot.\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nversicolor_petal_length = np.array([ 4.7,  4.5,  4.9,  4. ,  4.6,  4.5,  4.7,  3.3,  4.6,  3.9,  3.5,\n        4.2,  4. ,  4.7,  3.6,  4.4,  4.5,  4.1,  4.5,  3.9,  4.8,  4. ,\n        4.9,  4.7,  4.3,  4.4,  4.8,  5. ,  4.5,  3.5,  3.8,  3.7,  3.9,\n        5.1,  4.5,  4.5,  4.7,  4.4,  4.1,  4. ,  4.4,  4.6,  4. ,  3.3,\n        4.2,  4.2,  4.2,  4.3,  3. ,  4.1])\ndef ecdf(data):\n    \"\"\"Compute ECDF for a one-dimensional array of measurements.\"\"\"\n\n    # Number of data points: n\n    n = len(data)\n\n    # x-data for the ECDF: x\n    x = np.sort(data)\n\n    # y-data for the ECDF: y\n    y = np.arange(1, n+1) / n\n\n    return x, y\n\n# Compute ECDF for versicolor data: x_vers, y_vers\nx_vers, y_vers = ecdf(versicolor_petal_length)\n\n# Generate plot\n_ = plt.plot(x_vers, y_vers, marker = '.', linestyle = 'none')\n\n# Make the margins nice\nplt.margins(0.02)\n\n# Label the axes\n_ = plt.xlabel('length')\n_ = plt.ylabel('ECDF')\n\n\n# Display the plot\nplt.show()\n", "meta": {"hexsha": "9d987a9e4cb4626f756382c7e9dce27e70744fc0", "size": 1770, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/1-graphical-exploratory-data-analysis/plotting-the-ecdf.py", "max_stars_repo_name": "aimanahmedmoin1997/DataCamp", "max_stars_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-12T04:49:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T00:40:28.000Z", "max_issues_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/1-graphical-exploratory-data-analysis/plotting-the-ecdf.py", "max_issues_repo_name": "aimanahmedmoin1997/DataCamp", "max_issues_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/1-graphical-exploratory-data-analysis/plotting-the-ecdf.py", "max_forks_repo_name": "aimanahmedmoin1997/DataCamp", "max_forks_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-11-06T17:43:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T21:08:16.000Z", "avg_line_length": 32.1818181818, "max_line_length": 144, "alphanum_fraction": 0.6316384181, "include": true, "reason": "import numpy", "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741281688026, "lm_q2_score": 0.9207896764343916, "lm_q1q2_score": 0.8771204232563244}}
{"text": "# Question 05, Lab 04\n# AB Satyaprakash - 180123062\n\n# imports ----------------------------------------------------------------------------\nfrom sympy.abc import t\nfrom sympy import evalf, integrate\nfrom math import ceil, sqrt\nimport numpy as np\n\n# functions --------------------------------------------------------------------------\n\n\ndef f(x):\n    return 1/(x+4)\n\n\ndef errorCompositeTrapezoidal(a, b):\n    err = 10**(-5)\n    d2fmax = 1/32\n    val = (1/err)*(b-a)*(b-a)*(b-a)*(1/12)*d2fmax\n    n = ceil(sqrt(val))\n    print(\"Constraints :\", \"h <=\", (b-a)/sqrt(val), \"and n >=\", n)\n    return n\n\n\ndef errCompositeSimpson(a, b):\n    err = 10**(-5)\n    d4fmax = 24/(4**5)\n    val = (1/err)*pow(b-a, 5)*(1/180)*d4fmax\n    n = ceil(sqrt(sqrt(val)))\n    if n % 2 == 0:\n        print(\"Constraints :\", \"h <=\", (b-a) /\n              sqrt(sqrt(val)), \"and n >=\", n)\n        return n\n    else:\n        print(\"Constraints :\", \"h <=\", (b-a) /\n              sqrt(sqrt(val)), \"and n >=\", n+1)\n        return n+1\n\n\ndef errCompositeMidpoint(a, b):\n    err = 10**(-5)\n    d2fmax = 1/32\n    val = (1/err)*(b-a)*(b-a)*(b-a)*(1/6)*d2fmax\n    n = ceil(sqrt(val))\n    if n % 2 == 0:\n        print(\"Constraints :\", \"h <=\", (b-a)/sqrt(val), \"and n >=\", n)\n        return n\n    else:\n        print(\"Constraints :\", \"h <=\", (b-a)/sqrt(val), \"and n >=\", n+1)\n        return n+1\n\n\ndef compositeTrapezoidalRule(X):\n    sum = 0\n    a, b = X[0], X[-1]\n    n = X.shape[0]\n    h = (b-a)/(n-1)\n    for i in range(n):\n        x = X[i]\n        if(i == 0 or i == n-1):\n            sum += f(x)/2\n        else:\n            sum += f(x)\n    return (h*sum)\n\n\ndef compositeSimpsonRule(X):\n    sum = 0\n    a, b = X[0], X[-1]\n    n = X.shape[0]\n    h = (b-a)/(n-1)\n    for i in range(n):\n        x = X[i]\n        if(i == 0 or i == n-1):\n            sum += f(x)\n        else:\n            if(i % 2 == 0):\n                sum += 2*f(x)\n            else:\n                sum += 4*f(x)\n    return (h*sum)/3\n\n\ndef compositeMidpointRule(X):\n    a, b = X[0], X[-1]\n    n = X.shape[0]-1\n    h = (b-a)/(n)\n    sum = 0\n    for i in range(n):\n        xi = a+i*h\n        xi_nex = a+(i+1)*h\n        pt = (xi+xi_nex)/2\n        sum += f(pt)\n    return h*sum\n\n\n# program body\nfunc = 1/(t+4)\na, b = 0, 2\n\n\nI = integrate(func, (t, a, b)).evalf()\nprint('Actual value of integral is', I)\n\nprint(\"\\nFor part a: (Trapezoidal Rule)\")\nn = errorCompositeTrapezoidal(a, b)\nh = (b-a)/n\nX = np.arange(a, b+h/2, h)\nestimatedIntegral = compositeTrapezoidalRule(X)\nprint('Required tuple (n,h) with error < 0.00001 is ({}, {})'.format(n, h))\nprint('Estimated value of integral is', estimatedIntegral)\nprint('Error in this case is', abs(estimatedIntegral-I))\n\nprint(\"\\nFor part b: (Simpson Rule)\")\nn = errCompositeSimpson(a, b)\nh = (b-a)/n\nX = np.arange(a, b+h/2, h)\nestimatedIntegral = compositeSimpsonRule(X)\nprint('Required tuple (n,h) with error < 0.00001 is ({}, {})'.format(n, h))\nprint('Estimated value of integral is', estimatedIntegral)\nprint('Error in this case is', abs(estimatedIntegral-I))\n\nprint(\"\\nFor part c: (Midpoint Rule)\")\nn = errCompositeMidpoint(a, b)\nh = (b-a)/n\nX = np.arange(a, b+h/2, h)\nestimatedIntegral = compositeMidpointRule(X)\nprint('Required tuple (n,h) with error < 0.00001 is ({}, {})'.format(n, h))\nprint('Estimated value of integral is', estimatedIntegral)\nprint('Error in this case is', abs(estimatedIntegral-I))\n", "meta": {"hexsha": "797574bf0545d52910bee7baacfde42053db8668", "size": 3371, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 4/Code/q5.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 4/Code/q5.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 4/Code/q5.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 25.5378787879, "max_line_length": 86, "alphanum_fraction": 0.5117175912, "include": true, "reason": "import numpy,from sympy", "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741227833249, "lm_q2_score": 0.9207896688265684, "lm_q1q2_score": 0.8771204110504166}}
{"text": "import numpy as np\nfrom typing import Union\nfrom matplotlib.axes import Axes\nfrom matplotlib.image import AxesImage\nfrom matplotlib.colors import Colormap, LogNorm\n\n\ndef pascal_triangle(size: int) -> np.ndarray:\n    \"\"\"Creates an array representation of pascal's triangle (right-angled)\n\n    Args:\n        size: width and height of the triangle\n\n    Returns:\n        A 2D numpy array containing the triangle. The triangle is\n        right-angled and the elements where the triangle is not defined\n        are filled with zeros.\n        \n        Example: Triangle of size 5\n        [[1, 0, 0, 0, 0],\n         [1, 1, 0, 0, 0],\n         [1, 2, 1, 0, 0],\n         [1, 3, 3, 1, 0],\n         [1, 4, 6, 4, 1]]\n    \"\"\"\n    grid = np.zeros((size, size), dtype=np.uint64)\n    grid[:, 0] = 1\n    for i in range(1, size):\n        for j in range(1, size):\n            grid[i, j] = grid[i - 1, j - 1] + grid[i - 1, j]\n    return grid\n\n\ndef draw_pascal_triangle(ax: Axes, size: int, fontsize: int = 10,\n                         normalize: bool = True) -> None:\n    \"\"\"Plots pascal's triangle with the given size on ax\n\n    Args:\n        ax: matplotlib axes object\n        size: width and height of the triangle\n        fontsize: font size of the numbers\n        normalize: whether or not to normalize the coordinates\n            and the axes' limits to make the triangle equilateral\n    \"\"\"\n    grid = pascal_triangle(size)\n    hor = 1\n    if normalize:\n        ver = 3**0.5 / 2 * hor\n    else:\n        ver = hor\n\n    for i in range(size):\n        for j in range(i + 1):\n            ax.text((size - i + 2 * j) * hor,\n                    (2 * (size - 1 - i) + 1) * ver,\n                    str(int(grid[i][j])), fontsize=fontsize,\n                    ha=\"center\", va=\"center\")\n\n    if normalize:\n        ax.set_xlim(0, 2 * hor * (size - 1))\n        ax.set_ylim(0, 2 * ver * (size - 1))\n\n\ndef draw_pascal_fractal(ax: Axes, size: int,\n                        draw_numbers: bool = True, fontsize: float = 10,\n                        cmap: Union[Colormap, str]=\"rainbow\") -> AxesImage:\n    \"\"\"Draws the serpinski triangle inside pascal's triangle\n\n    This is achieved by connecting the odd numbers in pascal's triangle\n\n    Args:\n        ax: matplotlib axes object\n        size: width and height of the triangle\n        draw_numbers: wheter or not to draw pascal's triangle\n            on top of the fractal\n        fontsize: font size of the numbers\n        cmap: The colormap used for coloring the points. The points are\n            colored according to the ratio of their number to the maximum\n            number in the triangle. Logarithmic normalization is applied\n            for better distinction.\n\n    Returns:\n        output of imshow\n    \"\"\"\n    grid = pascal_fractal(size)\n\n    image = ax.imshow(np.flip(grid, axis=0), origin=\"lower\",\n                      extent=(0, 2 * size, 0, 2 * size),\n                      norm=LogNorm(), cmap=cmap)\n    if draw_numbers:\n        draw_pascal_triangle(ax, size, fontsize, False)\n\n    ax.set_aspect('auto')\n    return image\n\n\ndef pascal_fractal(size: int) -> np.ndarray:\n    \"\"\"Masked array representation of pascal's triangle serpinski fractal\n\n    Suitable for use with imshow\n\n    Args:\n        size: width and height of the triangle\n\n    Returns:\n        Masked numpy array containing the serpinski triangle inside\n        pascal's triangle. The numbers are repeated four times in squares\n        and the squares are centered. Even numbers are masked.\n\n        Example: Triangle of size 5\n        [[- - - - 1 1 - - - -]\n         [- - - - 1 1 - - - -]\n         [- - - 1 1 1 1 - - -]  \n         [- - - 1 1 1 1 - - -]  \n         [- - 1 1 - - 1 1 - -]  \n         [- - 1 1 - - 1 1 - -]\n         [- 1 1 3 3 3 3 1 1 -]\n         [- 1 1 3 3 3 3 1 1 -]\n         [1 1 - - - - - - 1 1]\n         [1 1 - - - - - - 1 1]]\n    \"\"\"\n    grid = _pascal_triangle_map(size)\n    return np.ma.masked_where(grid % 2 == 0, grid)\n\n\ndef _pascal_triangle_map(size: int) -> np.ndarray:\n    \"\"\"Array representation of pascal's triangle, centered\n\n    Args:\n        size (int): width and height of the triangle\n\n    Returns:\n        Numpy array containing centered pascal's triangle. The numbers\n        are repeated four times in squares and the squares are centered.\n        Elements where the triangle is not defined are filled with zeros.\n\n        Example: Triangle of size 5\n        [[0 0 0 0 1 1 0 0 0 0]\n         [0 0 0 0 1 1 0 0 0 0]\n         [0 0 0 1 1 1 1 0 0 0]\n         [0 0 0 1 1 1 1 0 0 0]\n         [0 0 1 1 2 2 1 1 0 0]\n         [0 0 1 1 2 2 1 1 0 0]\n         [0 1 1 3 3 3 3 1 1 0]\n         [0 1 1 3 3 3 3 1 1 0]\n         [1 1 4 4 6 6 4 4 1 1]\n         [1 1 4 4 6 6 4 4 1 1]]\n    \"\"\"\n    grid = pascal_triangle(size)\n    grid = grid.repeat(2, axis=0)\n    grid = grid.repeat(2, axis=1)\n\n    shifts = np.linspace(size - 1, 0, size).astype(int)\n    shifts = shifts.repeat(2)\n    return _apply_shifts(grid, shifts)\n\n\ndef _apply_shifts(array: np.ndarray, shifts: np.ndarray) -> np.ndarray:\n    \"\"\"Applies different shifts to diffrent rows of a numpy array\n\n    Args:\n        array: the numpy array\n        shifts: shift amounts as a numpy array\n\n    Returns:\n        the numpy array with shifted rows\n    \"\"\"\n    row, col = np.ogrid[:array.shape[0], :array.shape[1]]\n    col = col - shifts[:, np.newaxis]\n    return array[row, col]\n", "meta": {"hexsha": "f56c73a03df96d0389984c15860eee006224a0be", "size": 5345, "ext": "py", "lang": "Python", "max_stars_repo_path": "ps1-fractals/p4-pascal-fractal/pascal.py", "max_stars_repo_name": "slhshamloo/comp-phys", "max_stars_repo_head_hexsha": "04d6759e0eb9d7e16e2781417d389bc15e22b01b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ps1-fractals/p4-pascal-fractal/pascal.py", "max_issues_repo_name": "slhshamloo/comp-phys", "max_issues_repo_head_hexsha": "04d6759e0eb9d7e16e2781417d389bc15e22b01b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ps1-fractals/p4-pascal-fractal/pascal.py", "max_forks_repo_name": "slhshamloo/comp-phys", "max_forks_repo_head_hexsha": "04d6759e0eb9d7e16e2781417d389bc15e22b01b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2573099415, "max_line_length": 75, "alphanum_fraction": 0.5631431244, "include": true, "reason": "import numpy", "num_tokens": 1588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.9273632861110772, "lm_q1q2_score": 0.87710137816941}}
{"text": "# we are going to solve -u''(x) + 16*u(x)^p = 0\n# intial condition of u(0) = 0 and u(1) = 2\n# using Newton's method with an initial guess of 2x\n# build a mesh on the domain of [0,1]\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nleft_point = 0.0\nright_endpoint = 1.0\n\np = 3.0  # the power on the u(x) term, the problem is nonlinear when p != 1\nn = 80.0  # number of sub intervals\nh = 1.0 / n  # sub interval length\n\nx = np.arange(left_point, right_endpoint + h, h)\n\nu = 2.0 * x\nprint \"This is u\", u\n# when n = 4, then u = [ 0.   0.5  1.   1.5  2. ]\n\n# now we need to create our Jacobian matrix.\n# recall that Python is 0 based indexing and MATLAB has 1 based indexing!!!\n\n\n# Jacobian has -1 on both sides of the main diagonal\ndiagonals = -1.0*np.ones(n-2)\n\nprint diagonals\n\n# storage space\nmain_diagonal = np.zeros(n-1)\n\nfor iteration in np.arange(0, 100):\n\n\n    for j in np.arange(n-1):\n        # print x[i]\n        main_diagonal[j] = 2.0 + 16.0 * p * np.power(h, 2.0) * np.power(u[j+1], p - 1.0)\n        # print main_diagonal\n\n    jacobian = np.diag(diagonals, -1) + np.diag(diagonals, 1) + np.diag(main_diagonal)\n\n    # print jacobian\n\n\n    F = np.zeros(n-1)\n\n    for k in np.arange(1, n):\n        F[k-1] = -u[k-1] + 2.0*u[k] - u[k+1] + 16.0 * np.power(h, 2.0) * np.power(u[k], p)\n\n\n    # print \"this is F\", F\n\n    # now we want to solve the system for delta u\n    delta_u = np.linalg.solve(jacobian, -F)\n\n    # print \"this is u\", u\n    # print \"this is delta u\", delta_u\n\n    print \"Iteration: {} and delta u:{}:\".format(iteration, np.linalg.norm(delta_u))\n\n    for i in np.arange(1, n):\n        u[i] += delta_u[i-1]\n\n\n\n    # print \"this is u\", u\n\n    if np.linalg.norm(delta_u) < 10e-15:\n        print \"It took this many iterations\", iteration\n        break\n\n\ndef hyperbolic_sin(x):\n    return 2.0 * np.sinh(4.0*x) / np.sinh(4)\n\n\ny = hyperbolic_sin(x)\n# print \"this is y\", y\n# print \"this is y\", y\nplt.title(\"p={0}\".format(p))\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.plot(x, u)\n# plt.plot(x, y)\nplt.show()\n", "meta": {"hexsha": "7fe102fbd9e45470acd7cda9040ea824d5f85e19", "size": 2013, "ext": "py", "lang": "Python", "max_stars_repo_path": "watkins_math448/assignment7_c.py", "max_stars_repo_name": "johnnydevriese/wsu_courses", "max_stars_repo_head_hexsha": "b55efd501c2d8f0651891f422a486e32533f5aa0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "watkins_math448/assignment7_c.py", "max_issues_repo_name": "johnnydevriese/wsu_courses", "max_issues_repo_head_hexsha": "b55efd501c2d8f0651891f422a486e32533f5aa0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "watkins_math448/assignment7_c.py", "max_forks_repo_name": "johnnydevriese/wsu_courses", "max_forks_repo_head_hexsha": "b55efd501c2d8f0651891f422a486e32533f5aa0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.875, "max_line_length": 90, "alphanum_fraction": 0.6050670641, "include": true, "reason": "import numpy", "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799472560582, "lm_q2_score": 0.9099070145888367, "lm_q1q2_score": 0.8769501345283465}}
{"text": "'''\nIntroduction to NumPy Library.\nThis script introduces how to create NumPy arrays and how to operate with them.\nFor more details: https://numpy.org/devdocs/user/quickstart.html\n'''\n\nimport numpy as npy\n\n## 1. CREATING NumPy ARRAYS ##\n\n# Casting lists to arrays:\nlist = [1,2,3,4,5]\n\narray1 = npy.array(list)\nprint('The array1 is: ', array1)\n\n# Using NumPy built-in functions:\n\n# .zeros() creates an array of 0s with user-defined dimensions.\narray2 = npy.zeros((1,5)) # the input is a tuple.\nprint('\\n The array2 is: ', array2)\n\n# .ones() creates an array of 1s with user-defined dimensions.\narray3 = npy.ones((2,3))\nprint('\\n The array3 is: \\n', array3)\n\n# .eye() creates an identity matrix with user-defined dimensions.\narray4 = npy.eye(5)\nprint('\\n The array4 is: \\n', array4)\n\n# .arange() creates an array of evenly spaced values within the user-specified interval.\narray5 = npy.arange(1,11)\nprint('\\n The array5 is: \\n', array5)\n\narray6 = npy.arange(1,100, 10) # Starts from 1 and iterates by adding 10 until it reaches to the upper limit 100.\nprint('\\n The array6 is: \\n', array6)\n\n# .linspace() creates an array of evenly spaced values.\narray7 = npy.linspace(1,100, 10) # divides the interval 1 to 100 into 10 equivalent pieces.\nprint('\\n The array7 is: \\n', array7)\n\n# .random.rand() can create an array with random number entries with user-defined dimension\narray8 = npy.random.rand(2,3) # by default, the generated numbers are between 0 to 1.\nprint('\\n The array8 is: \\n', array8)\n\n# similarly:\narray9 = npy.random.randn(2,3) # the entries of the array are coming from Standard Normal Distribution.\nprint('\\n The array9 is: \\n', array9)\n\narray10 = npy.random.randint(1,10, 15) # generates random integers within a given interval.\nprint('\\n The array10 is: \\n', array10)\n\n# Reshaping the array:\nnewArray10 = array10.reshape(3,5) # make sure d1xd2 = initial length. In this example 3x5 = 15 matches array10 length\nprint('\\n The newArray10 is: \\n', newArray10)\n\n\n## 2. BUILT-IN ARRAY ATTRIBUTES ##\n\n# Generate an array with random integer values between 1 and 100:\narray = npy.random.randint(1,100,10)\nprint('\\n The array is: \\n', array)\n\n# Finding the maximum entry of the array\narrMax = array.max()\nprint('\\n The maximum entry of array is: ', arrMax, '\\n')\n\n# Finding the minimum entry of the array\narrMin = array.min()\nprint('\\n The minimum entry of array is: ', arrMin, '\\n')\n\n# Fining the index of the maximum and minimum entries:\narrMinInd = array.argmin()\nprint('\\n The index of the minimum entry of array is: ', arrMinInd, '\\n') # Remember, indexing starts from 0!\n\narrMaxInd = array.argmax()\nprint('\\n The index of the maximum entry of array is: ', arrMaxInd, '\\n')\n\n# Finding length the array\nlenArray = len(array)\nprint('\\n The length of the array is: ', lenArray, '\\n')\n\n# Finding dimensions of an array\ndimArray = array8.shape\nprint('\\n The dimensions of the array8 is: ', dimArray, '\\n')\n\n## 3. ARRAY INDEXING AND ENTRY SELECTION ##\n\n# Create a new array:\narray = npy.arange(1,21).reshape(4,5)\nprint('\\n The new array is: \\n', array)\n\n# Picking a single entry from the array:\nanEntry = array[1, 3] # retrieving entry 9\nprint('\\n The picked entry is: ', anEntry, '\\n')\n\n# Picking an entire row of the array:\naRow = array[1, :] # retrieving the 2nd row\nprint('\\n The picked row is: ', aRow, '\\n')\n\n# Picking an entire column of the array:\naColumn = array[:, 4] # retrieving the 5th column\nprint('\\n The picked column is: ', aColumn, '\\n')\n\n# Picking multiple rows and columns of the array:\nmultiRowColumn = array[0:2, 2:4] # retrieving the 1st and 2nd row, and 3rd,4th columns\nprint('\\n The picked multiRowColumn are: \\n', multiRowColumn, '\\n')\n\n# Picking rows irregularly:\nirregRows = array[[1,3]] # retrieving the 1st and 3rd rows\nprint('\\n The picked irregRows are: \\n', irregRows, '\\n')\n\n## 4. ARRAY OPERATIONS ##\n\n# Adding arrays\narrAdd = array + array\nprint('\\n The arrAdd is: \\n', arrAdd, '\\n')\n\n# Substituting arrays\narrSubs = array - array\nprint('\\n The arrSubs is: \\n', arrSubs, '\\n')\n\n# Multiplying arrays\narrMult = array * array\nprint('\\n The arrMult is: \\n', arrMult, '\\n')\n\n# Dividing arrays\narrDiv = array / array\nprint('\\n The arrDiv is: \\n', arrDiv, '\\n')\n\n# Power of arrays\narrPow = array**4\nprint('\\n The arrPow is: \\n', arrPow, '\\n')\n\n# Square root of entries of array\narrSqrt = npy.sqrt(array)\nprint('\\n The arrSqrt is: \\n', arrSqrt, '\\n')\n\n# Sine of entries of array\narrSin = npy.sin(array)\nprint('\\n The arrSin is: \\n', arrSin, '\\n')\n\n# Exponention of entries of array\narrExp = npy.exp(array)\nprint('\\n The arrExp is: \\n', arrExp, '\\n')\n\n# Logarithm of entries of array\narrLog = npy.log(array)\nprint('\\n The arrLog is: \\n', arrLog, '\\n')", "meta": {"hexsha": "018f2d2a911b39172592f7742fb3aa0304a8fca3", "size": 4680, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumPy Library/NumPy_Basics.py", "max_stars_repo_name": "mustafaozen/python-libraries", "max_stars_repo_head_hexsha": "92e3ac06f02cc5f0bdcaddfd00b71ed2478f5d79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-02T18:10:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-02T18:10:47.000Z", "max_issues_repo_path": "NumPy Library/NumPy_Basics.py", "max_issues_repo_name": "mustafaozen/python-libraries", "max_issues_repo_head_hexsha": "92e3ac06f02cc5f0bdcaddfd00b71ed2478f5d79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumPy Library/NumPy_Basics.py", "max_forks_repo_name": "mustafaozen/python-libraries", "max_forks_repo_head_hexsha": "92e3ac06f02cc5f0bdcaddfd00b71ed2478f5d79", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-02T12:35:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-02T12:35:09.000Z", "avg_line_length": 31.4093959732, "max_line_length": 117, "alphanum_fraction": 0.6972222222, "include": true, "reason": "import numpy", "num_tokens": 1412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983308, "lm_q2_score": 0.9241418189341296, "lm_q1q2_score": 0.8769341241514748}}
{"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nrotation.py\nRotation is a module designed to organize the three basic\nrotation matrices in three dimensions, according to \nhttps://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations.\nIt is based on numpy arrays.\nContext examples:\nThe unit vector in the direction of the x axis\nof a three dimensional Cartesian coordinate system\nis written as np.array([1, 0, 0]).\nThe identity amtrix of size 3 is written as\nnp.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\nRotation example:\n# TODO \nRotate hat(i) to get hat(k).\n\"\"\"\n\nimport numpy as np\n\n# Basic rotation\n\ndef R_x(angle):\n    \"\"\"Rotation matrix by given angle in radians about x-axis.\"\"\"\n    cos = np.cos(angle)\n    sin = np.sin(angle)\n    R_x_angle = np.array(\n        [\n            [1, 0, 0],\n            [0, cos, -sin],\n            [0, sin, cos]\n        ]\n    )\n    return R_x_angle\n\ndef R_y(angle):\n    \"\"\"Rotation matrix by given angle in radians about y-axis.\"\"\"\n    cos = np.cos(angle)\n    sin = np.sin(angle)\n    R_y_angle = np.array(\n        [\n            [cos, 0, sin],\n            [0, 1, 0],\n            [-sin, 0, cos]\n        ]\n    )\n    return R_y_angle\n\ndef R_z(angle):\n    \"\"\"Rotation matrix by given angle in radians about z-axis.\"\"\"\n    cos = np.cos(angle)\n    sin = np.sin(angle)\n    R_z_angle = np.array(\n        [\n            [cos, -sin, 0],\n            [sin, cos, 0],\n            [0, 0, 1]\n        ]\n    )\n    return R_z_angle\n\n# General rotation\n\ndef cartesian_rotation(vector, x_angle, y_angle, z_angle):\n    \"\"\"\n    Rotate a given vector in a three dimensional Cartesian coordinate system\n    by given angles in radians about each axis.\n    \"\"\"\n    R_vector = np.matmul(\n        R_z(z_angle), np.matmul(\n            R_y(y_angle), np.matmul(\n                R_x(x_angle), vector\n            )\n        )\n    )\n    return R_vector\n\ndef normalize(vector):\n    norm = np.linalg.norm(vector, ord = 2)\n    return vector / norm\n\ndef axis_rotation(vector, angle, axis):\n    \"\"\"\n    Rotate a given vector by given angle in radians about given axis.\n    The axis is defined by a unit vector.\n    \"\"\"\n\n    unit_vector = normalize(axis)\n\n    cos = np.cos(angle)\n    sin = np.sin(angle)\n\n    ux,uy,uz = unit_vector\n\n    R = np.array(\n        [\n            [cos+(1-cos)*ux**2, ux*uy*(1-cos)-uz*sin, ux*uz*(1-cos)+uy*sin],\n            [uy*ux*(1-cos)+uz*sin, cos+(1-cos)*uy**2, uy*uz*(1-cos)-ux*sin],\n            [uz*ux*(1-cos)-uy*sin, uz*uy*(1-cos)+ux*sin, cos+(1-cos)*uz**2]\n        ]\n    )\n\n    R_vector = np.matmul(\n        R, vector\n    )\n    return R_vector\n\ndef orthographic_projection(vector3D, z):\n    \"\"\"\n    Project 3D vector into 2D vector\n    It is perspective_projection with FOV = np.pi/2\n    \"\"\"\n    projection_matrix = np.array(\n        [\n            [z, 0, 0],\n            [0, z, 0]\n        ]\n    )\n    vector2D = np.matmul(\n        projection_matrix, vector3D\n    )\n    return vector2D\n\ndef perspective_projection(vector, near, far, FOV = 2*np.pi/3, AR = 1):\n    \"\"\"\n    Project 3D into 2D with perspective.\n    \n    Parameters\n    ----------\n    vector : array_like\n        Input vector array.\n    near : float\n        Distance to the near clipping plane along the z-axis.\n    far : float\n        Distance to the far clipping plane along the z-axis.\n    FOV : float\n        Field of view.\n        The angle between the upper and lower sides of the viewing frustum.\n    AR : float\n        The aspect ratio of the viewing window (width/height).\n    Returns\n    -------\n    projected_vector : array_like\n        Output vector array.\n    \"\"\"\n\n    # perspective_matrix = np.array(\n    #     [\n    #         [1, 0, 0, 0],\n    #         [0, 1, 0, 0],\n    #         [0, 0, 1, 0],\n    #         [0, 0, -1, 0]\n    #     ]\n    # )\n\n    perspective_matrix = np.array(\n        [\n            [1/(AR*np.tan(FOV/2)), 0, 0, 0],\n            [0, 1/np.tan(FOV/2), 0, 0],\n            [0, 0, (near+far)/(near-far), 2*(near+far)/(near-far)],\n            [0, 0, -1, 0]\n        ]\n    )\n\n    aux_vector = np.matmul(\n        perspective_matrix, vector\n    )\n\n    w = aux_vector[2] / near\n\n    projected_vector = aux_vector / w\n\n    projected_vector = projected_vector[:2]\n\n    return projected_vector", "meta": {"hexsha": "18dfbdcd893cc891dce6de45e9b2354ce24cec58", "size": 4193, "ext": "py", "lang": "Python", "max_stars_repo_path": "data/rotation.py", "max_stars_repo_name": "camilo-nb/Dongui-Pong", "max_stars_repo_head_hexsha": "68f521ca5e731ea8cf060a9335fcdcfad6eb3ad8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data/rotation.py", "max_issues_repo_name": "camilo-nb/Dongui-Pong", "max_issues_repo_head_hexsha": "68f521ca5e731ea8cf060a9335fcdcfad6eb3ad8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/rotation.py", "max_forks_repo_name": "camilo-nb/Dongui-Pong", "max_forks_repo_head_hexsha": "68f521ca5e731ea8cf060a9335fcdcfad6eb3ad8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6892655367, "max_line_length": 76, "alphanum_fraction": 0.550918197, "include": true, "reason": "import numpy", "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992942089575, "lm_q2_score": 0.9059898273638387, "lm_q1q2_score": 0.8769069144659547}}
{"text": "from typing import Tuple\n\nimport numpy as np\nfrom numpy.linalg import norm, eig\n\n\ndef eigenvalue(A, v):\n    return np.dot(v, np.dot(A, v)) / np.dot(v, v)\n\n\ndef eigendecomp(A: np.ndarray,\n                eps: float = 0.01) \\\n        -> Tuple[np.ndarray, np.ndarray]:\n    \"\"\"\n    Calculates the eigendecomposition of matrix A using power method.\n\n    :param A: matrix of shape (n, n)\n    :param eps: precision of iterations\n    :return: tuple vector, matrix - (eigenvalues, eigenvectors)\n    \"\"\"\n    n = A.shape[0]\n\n    eigvals = np.zeros(n)\n    eigvecs = np.zeros(A.shape)\n\n    for i in range(n):\n        eig_vec = np.random.rand(n)\n        eig_val = eigenvalue(A, eig_vec)\n\n        while True:\n            Av = A.dot(eig_vec)\n\n            eig_vec_new = Av / np.linalg.norm(Av)\n            eig_val_new = eigenvalue(A, eig_vec_new)\n\n            if np.abs(eig_val - eig_val_new) < eps:\n                break\n\n            eig_vec = eig_vec_new\n            eig_val = eig_val_new\n\n        eigvals[i] = eig_val_new\n        eigvecs[i] = eig_vec_new\n\n        A = A - eig_val_new * eig_vec_new * eig_vec_new[:, np.newaxis]\n\n    return eigvals, eigvecs.T\n\n\nif __name__ == '__main__':\n    A = np.array([[2, -1, 0],\n                  [-1, 2, -1],\n                  [0, -1, 2]])\n\n    eig_vals, eig_vecs = eig(A)\n    print(\"Library:\")\n    print(eig_vals)\n    print(eig_vecs)\n    print()\n\n    eig_vals, eig_vecs = eigendecomp(A)\n    print(\"My:\")\n    print(eig_vals)\n    print(eig_vecs)\n    print()\n", "meta": {"hexsha": "9c309b2559f3fc00373931f6ade369ccbccf1900", "size": 1482, "ext": "py", "lang": "Python", "max_stars_repo_path": "eigendecomposition.py", "max_stars_repo_name": "j-adamczyk/Matrix_algorithms", "max_stars_repo_head_hexsha": "2b06b4cfd741919724b2e88eb17da35909341ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-13T13:06:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-13T13:06:32.000Z", "max_issues_repo_path": "eigendecomposition.py", "max_issues_repo_name": "j-adamczyk/Matrix_algorithms", "max_issues_repo_head_hexsha": "2b06b4cfd741919724b2e88eb17da35909341ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigendecomposition.py", "max_forks_repo_name": "j-adamczyk/Matrix_algorithms", "max_forks_repo_head_hexsha": "2b06b4cfd741919724b2e88eb17da35909341ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-10T17:33:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T17:33:49.000Z", "avg_line_length": 22.4545454545, "max_line_length": 70, "alphanum_fraction": 0.5620782726, "include": true, "reason": "import numpy,from numpy", "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992923570261, "lm_q2_score": 0.905989826094673, "lm_q1q2_score": 0.8769069115596991}}
{"text": "\"\"\"\nNormalization also called as norms have three types\n    - L2 Norms   (also called as Euclidean Norm)\n    - L1 Norms\n    - Frobenius Norms (used for matrix normalization)\n\nNormalization is nothing but calculating the magnitude of the given vector/matrix\n\n\"\"\"\nimport numpy as np\n\n# define a array\nA = np.arange(9) - 3\n\n# reshape array into 3x3 matrix\nB = A.reshape((3, 3))\n\n# Euclidean (L2) Norm - Default\nprint(np.linalg.norm(A))\nprint(np.linalg.norm(B))\n\"\"\"\nOutput:\n8.306623862918075\n8.306623862918075\n\"\"\"\n\n# The Frobenius norm is the L2 norm for a Matrix\nprint(np.linalg.norm(B, 'fro'))\n\"\"\"\nOutput:\n8.306623862918075\n\"\"\"\n\n# the L1 norm\nprint(np.linalg.norm(A, 1))\nprint(np.linalg.norm(B, 1))\n\"\"\"\nOutput:\n21.0\n8.0\n\"\"\"\n\n# the max norm (P = infinity)\nprint(np.linalg.norm(A, np.inf))\nprint(np.linalg.norm(B, np.inf))\n\"\"\"\nOutput:\n5.0\n12.0\n\"\"\"\n\n\"\"\"\nVector Normalization\n\"\"\"\n\n# normalization to produce unit vector\nnorm = np.linalg.norm(A, 2)\nA_unit = A / norm\n\"\"\"\nOutput:\n[-0.36115756 -0.24077171 -0.12038585  0.          0.12038585  0.24077171\n  0.36115756  0.48154341  0.60192927]\n\"\"\"\n\n# the magnitude of a unit vector is equal to 1\nprint(np.linalg.norm(A_unit))\n\"\"\"\nOutput:\n1.0\n\"\"\"", "meta": {"hexsha": "a6f459e665a4f6ced884ac307e1728220d65b5cf", "size": 1184, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_algebra/vector_normalization.py", "max_stars_repo_name": "amoljagadambe/machine-Learning_Tutorials", "max_stars_repo_head_hexsha": "7e9dc49d269bad93d3c6377f05865307c77d35df", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_algebra/vector_normalization.py", "max_issues_repo_name": "amoljagadambe/machine-Learning_Tutorials", "max_issues_repo_head_hexsha": "7e9dc49d269bad93d3c6377f05865307c77d35df", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_algebra/vector_normalization.py", "max_forks_repo_name": "amoljagadambe/machine-Learning_Tutorials", "max_forks_repo_head_hexsha": "7e9dc49d269bad93d3c6377f05865307c77d35df", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.9142857143, "max_line_length": 81, "alphanum_fraction": 0.6773648649, "include": true, "reason": "import numpy", "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992960608886, "lm_q2_score": 0.9059898172105135, "lm_q1q2_score": 0.8769069063163892}}
{"text": "import numpy as np\nimport math\n\n\n\n# Compute the intersection distance between histograms x and y\n# Return 1 - hist_intersection, so smaller values correspond to more similar histograms\n# Check that the distance range in [0,1]\n\ndef dist_intersect(x,y):\n    \n    zipped = list(map(min, list(zip(x,y))))\n    dist = 1 - (0.5*((np.sum(zipped)/np.sum(x)) + (np.sum(zipped)/np.sum(y))))\n    assert 0 <= dist <= 1, \"not in [0,1]\"\n    return dist\n\n\n# Compute the L2 distance between x and y histograms\n# Check that the distance range in [0,sqrt(2)]\n\ndef dist_l2(x,y):\n    \n    dist = np.sum((x - y)**2)\n    assert 0 <= dist <= np.sqrt(2), \"not in [0, sqrt(2)]\"\n    return dist\n\n\n# Compute chi2 distance between x and y\n# Check that the distance range in [0,Inf]\n# Add a minimum score to each cell of the histograms (e.g. 1) to avoid division by 0\n\ndef dist_chi2(x,y):\n    \n    x += 0.5\n    y += 0.5\n    dist = np.sum(((x - y)**2)/((x) + (y)))\n    assert 0 <= dist <= np.inf, \"not in [0, inf]\"\n    return dist\n\n\n\ndef get_dist_by_name(x, y, dist_name):\n  if dist_name == 'chi2':\n    return dist_chi2(x,y)\n  elif dist_name == 'intersect':\n    return dist_intersect(x,y)\n  elif dist_name == 'l2':\n    return dist_l2(x,y)\n  else:\n    assert False, 'unknown distance: %s'%dist_name\n  \n\n\n\n\n", "meta": {"hexsha": "f1f599027d7d522e9df37f2f73f75de472cfa0d4", "size": 1274, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignment/Identification/dist_module.py", "max_stars_repo_name": "EgonFerri/AML-lab1", "max_stars_repo_head_hexsha": "080f8735461fa82b4f847f070aed6dedb0f1e174", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment/Identification/dist_module.py", "max_issues_repo_name": "EgonFerri/AML-lab1", "max_issues_repo_head_hexsha": "080f8735461fa82b4f847f070aed6dedb0f1e174", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment/Identification/dist_module.py", "max_forks_repo_name": "EgonFerri/AML-lab1", "max_forks_repo_head_hexsha": "080f8735461fa82b4f847f070aed6dedb0f1e174", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.75, "max_line_length": 87, "alphanum_fraction": 0.6271585557, "include": true, "reason": "import numpy", "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846634557752, "lm_q2_score": 0.8962513668985002, "lm_q1q2_score": 0.8768785919747676}}
{"text": "# This code shows how a linear regression analysis can be applied to a 1-dimensional data\n# Implementation here is based on the theory described in the jupyter notebook.\n\n# Code Flow:\n    # 1. Import all relevant libraries.\n    # 2. Generate sample data & save it as a csv file (Stored as a csv file just to use pandas).\n    # 3. Load the dataset using pandas (X - input/feature, Y - output/target).\n    # 4. Plot the generated data understand the trend.\n    # 5. Calculate weights (parameters - a & b) using the equation from the theory lecture.\n    # 6. Calculate Yhat from the weights above. Yhat = a*X + b.\n    # 7. Plot actual vs. predicted to visualize the fit.\n    # 8. Calculate R-squared using the equation from the theory lecture to validate the model.\n    # 9. How is the fit? Good? Bad? Ok?\n\n# 1.Imports:\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# 2.Generate sample data:\nN = 100\nwith open('data_1d.csv', 'w') as f:\n    X = np.random.uniform(low=0, high=100, size=N)\n    Y = 2*X + 1 + np.random.normal(scale=5, size=N)\n    for i in range(N):\n        f.write(\"%s,%s\\n\" % (X[i], Y[i]))\n        \n# 3.Load the data:\ndf = pd.read_csv('data_1D.csv',header = None)\nX = df[0].values\nY = df[1].values\n\n# 4.Plot the data:\nplt.figure(1)\nplt.scatter(X,Y,c = 'red')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.title('Sample Data Scatter Plot')\n\n\n# 5.Model: Y = a*X + B\n# Apply the equations from the jupyter notebook to calculate a & b:\n# Denominator is same for both a & b\ndenominator = X.dot(X) - X.mean() * X.sum()\na = (X.dot(Y) - Y.mean()*X.sum())/denominator\nb = (Y.mean()*X.dot(X) - X.mean() * X.dot(Y))/denominator\n\n# 6.Predict Y:\nYhat = a*X + b\n\n# 7.Plot predicted vs actual:\nplt.figure(2)\nplt.scatter(X,Y,c = 'red',label = 'Actual Data')\nplt.plot(X,Yhat,c = 'black',label = 'Predicted Data')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.title('Actual vs. Model')\nplt.legend()\n\n\n# 8 & 9.R-squared:\nd1 = Y - Yhat\nd2 = Y - Y.mean()\nr2 = 1 - d1.dot(d1)/d2.dot(d2)\nprint('the r-squared is {} & hence the model is good'.format(r2))\n", "meta": {"hexsha": "3894c637c162f5c329e24752458135ce17db454b", "size": 2048, "ext": "py", "lang": "Python", "max_stars_repo_path": "1.Linear Regression/1.Code - Using Theory/0.1D - Regression.py", "max_stars_repo_name": "ananth-repos/machine-learning", "max_stars_repo_head_hexsha": "a510dcf81fab9137c33f568e73d65262667b3973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1.Linear Regression/1.Code - Using Theory/0.1D - Regression.py", "max_issues_repo_name": "ananth-repos/machine-learning", "max_issues_repo_head_hexsha": "a510dcf81fab9137c33f568e73d65262667b3973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1.Linear Regression/1.Code - Using Theory/0.1D - Regression.py", "max_forks_repo_name": "ananth-repos/machine-learning", "max_forks_repo_head_hexsha": "a510dcf81fab9137c33f568e73d65262667b3973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0303030303, "max_line_length": 96, "alphanum_fraction": 0.6528320312, "include": true, "reason": "import numpy", "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018455701406, "lm_q2_score": 0.8991213799730774, "lm_q1q2_score": 0.8768248291413167}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom numba import njit\nimport streamlit as st\n\n\n@njit\ndef fourier(x, coeffs):\n    a = coeffs[0:-1:2]\n    b = coeffs[1:-1:2]\n    y = a[0]/2*np.ones_like(x)\n    for i, (ai, bi) in enumerate(zip(a, b)):\n        y += ai*np.cos(2*np.pi*(i+1)*x) + bi*np.sin(2*np.pi*(i+1)*x)\n    return y\n\n\n@njit\ndef integral(coeffs):\n    a = coeffs[0:-1:2]\n    b = coeffs[1:-1:2]\n    y = a[0] / 2\n    for i, (ai, bi) in enumerate(zip(a, b)):\n        k = np.pi*(i+1)\n        y += np.sin(k)/k * (ai*np.cos(k)+bi*np.sin(k))\n    return y\n\n\nst.title(\"Random Fourier Functions\")\nst.markdown(\"This application creates random functions of the following type:\")\nst.latex(\n    r'''f_{coeffs}(x) = a_0/2 +\n    \\sum_{i=1}^N {a_i}\\, \\cos(2\\pi \\, i \\, x)+b_i\\, \\sin(2\\pi \\, i \\, x)''')\nst.markdown(\"The coefficients $a_i$ and $b_i$ are of order $O(i^{-smoothness})$. \")\nst.markdown(\"More precisely, $a_i = r_i \\cdot i^{-smoothness}$ for a random number $r_i$.\")\n\nsmoothness = st.sidebar.slider('Smoothness', 0.0, 10.0, 2.0, 0.1)\nnpoints = st.sidebar.slider('Number of points in plot', 100, 10000, 1000, 100)\nfixorder = st.sidebar.checkbox('Fix expansion order?', 10)\nfixordervalue = st.sidebar.slider('Expansion order value', 1, 1000, 100, 1)\nnsamples = st.sidebar.slider(\"Number of samples\", 1, 200, 3, 1)\nsampling = st.sidebar.selectbox(\n    'Which random nunber generator?',\n    ('rand', 'randn'))\nfixrandomseed = st.sidebar.checkbox('Fix random seed?', True)\nrandomseed = st.sidebar.text_input(\"Random seed value\", 1)\nnormalizezero = st.sidebar.checkbox('Fix integral to be zero?', True)\n\nif fixorder:\n    order = fixordervalue\nelse:\n    order = int((10**-8)**(-1/smoothness))\n\nif fixrandomseed:\n    rng = np.random.RandomState(int(randomseed))\nelse:\n    rng = np.random.RandomState(np.random.randint(2**32-1))\n\nn = 2*order+1\nx = np.linspace(0, 1, npoints)\n\nplt.style.use(\"https://raw.githubusercontent.com/camminady/kitstyle/master/kitishnotex.mplstyle\")\nfig, axs = plt.subplots(2, 1, figsize=(8, 6))\n\n\ndatastorage = {}\nfor sampleid in range(nsamples):\n    if sampling == \"rand\":\n        coeffs = rng.uniform(-1, 1, n)\n    else:\n        coeffs = rng.normal(0, 1, n)\n    for i in range(1, n, 2):\n        coeffs[i] *= i**(-smoothness)\n        coeffs[i+1] *= i**(-smoothness)\n    if normalizezero:\n        y = integral(coeffs)\n        coeffs[0] -= 2*y  # integral now has value 0\n    y = fourier(x, coeffs)\n    axs[0].plot(x, y, lw=1, alpha=0.7)\n    if order > 1:\n        axs[1].loglog(np.arange(order), np.abs(coeffs[0:-1:2]), '.', markersize=3, alpha=0.7)\n\n    infos = {\"order\": order,\n             \"x\": list(x),\n             \"y\": list(y),\n             \"coeffs\": list(coeffs),\n             }\n    datastorage[f\"sample_{sampleid}\"] = infos\n\naxs[0].set_ylim([-2, 2])\naxs[0].set_xlabel(\"$x$\")\naxs[0].set_ylabel(\"$f_{coeffs}(x)$\", rotation=90, labelpad=0)\naxs[1].set_ylim([10**-8, 10**1])\naxs[1].set_ylabel(\"$|coeffs|$\", rotation=90, labelpad=0)\naxs[1].set_xlabel(\"$n$\")\n\n\nst.pyplot(fig)\n\ntoshow = st.checkbox(\"Show function values and coefficients in JSON format?\", False)\nst.markdown(\"(Maybe only choose few samples and few points in plot and recreate the function values with the script below.)\")\nst.markdown(\"\"\"\n```\ndef fourier(x, coeffs):\n    a = coeffs[0:-1:2]\n    b = coeffs[1:-1:2]\n    y = a[0]/2*np.ones_like(x)\n    for i, (ai, bi) in enumerate(zip(a, b)):\n        y += ai*np.cos(2*np.pi*(i+1)*x) + bi*np.sin(2*np.pi*(i+1)*x)\n    return y\n```\n\"\"\")\nif toshow:\n    st.json(datastorage)\n", "meta": {"hexsha": "d737d1ad58762b91116735c36b53e8a201a49326", "size": 3507, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "camminady/RandomFourierFunctions", "max_stars_repo_head_hexsha": "4972b64b44d07b1fcb1336c557607b3686668888", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-25T09:34:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T09:34:43.000Z", "max_issues_repo_path": "main.py", "max_issues_repo_name": "camminady/RandomFourierFunctions", "max_issues_repo_head_hexsha": "4972b64b44d07b1fcb1336c557607b3686668888", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "camminady/RandomFourierFunctions", "max_forks_repo_head_hexsha": "4972b64b44d07b1fcb1336c557607b3686668888", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7631578947, "max_line_length": 125, "alphanum_fraction": 0.6130595951, "include": true, "reason": "import numpy,from numba", "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650673, "lm_q2_score": 0.9184802468145655, "lm_q1q2_score": 0.8768247950631144}}
{"text": "\"\"\" Fourier Series --> Approximate periodic functions using an infinite sum of cosines and sine waves\n    Gibbs Phenomenon happens while computing Fourier Series of a Discontinuous Function:\n     Top-hat function discontinuous at edges of unit step \"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.figsize'] = [8, 8]\nplt.rcParams.update({'font.size': 18})\n\ndx = 0.01                                                                       # 0.001\nL = 2 * np.pi\nx = np.arange(0, L+dx, dx)\nn = len(x)\nnquart = int(np.floor(n/4))\n\nf = np.zeros_like(x)\nf[nquart:3*nquart] = 1\n\nA0 = np.sum(f * np.ones_like(x)) * dx * 2 / L\nfFs = A0/2 * np.ones_like(f)\n\nfor k in range(1, 101):                                                         # 1001\n    Ak = np.sum(f * np.cos(2 * np.pi * k * x / L)) * dx * 2 / L\n    Bk = np.sum(f * np.sin(2 * np.pi * k * x / L)) * dx * 2 / L\n    fFs = fFs + Ak * np.cos(2 * k * np.pi * x / L ) + Bk * np.sin(2 * k * np.pi * x / L)\n\nplt.plot(x, f, color='k', LineWidth=2)\nplt.plot(x, fFs, '-', color='r', LineWidth=1.5)\nplt.show()\n\n\n\"\"\" Fourier Series aprroximation with first 100 sines and cosines Gibbs Phenomenon at the corners where discontinuous\n    Ringing behavior at the points of discontinuity \n    !! Reminder !! = If we added up all infinitely many sines and cosines of all frequencies we would have \n                     perfect approximation of discontinuous top-hat function \n                     \n    !!! we have discontinuous function but sines and cosines are still continuous no sharp corners or jumps \n        these corners and sharps requires all fourier frequences to be able to approximate \n\n    Gibbs Phenomenon: happens while approximating discontinuous function using a finite truncated Fourier Series \n    \n    If we use the Fourier Series to approximate the derivative of triangular hat function - which is a top hat function\n     then the derivative is gonna have Gibbs Phenomenon \"\"\"", "meta": {"hexsha": "cfc0e7aa5a47c9a200e74a5f92bac06a33199095", "size": 1959, "ext": "py", "lang": "Python", "max_stars_repo_path": "Fourier_Gibbs_Phenomena/fourierS-gibbs.py", "max_stars_repo_name": "oguznsari/Fourier-implementation", "max_stars_repo_head_hexsha": "c4e1a57bbb05347d7d938c4096bd9ae56586319a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Fourier_Gibbs_Phenomena/fourierS-gibbs.py", "max_issues_repo_name": "oguznsari/Fourier-implementation", "max_issues_repo_head_hexsha": "c4e1a57bbb05347d7d938c4096bd9ae56586319a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fourier_Gibbs_Phenomena/fourierS-gibbs.py", "max_forks_repo_name": "oguznsari/Fourier-implementation", "max_forks_repo_head_hexsha": "c4e1a57bbb05347d7d938c4096bd9ae56586319a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5581395349, "max_line_length": 119, "alphanum_fraction": 0.6294027565, "include": true, "reason": "import numpy", "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.9124361688107863, "lm_q1q2_score": 0.876807092156333}}
{"text": "# Question 2, Lab 6\n# AB Satyaprakash, 180123062\n\n# imports \nfrom sympy.abc import t,y\nimport numpy as np\nimport sympy as sp\n\n# functions \ndef getEulerApproximation(f,X,Y,h):\n    for i in range(1,Y.shape[0]):\n        Y[i]=Y[i-1] + f.subs({t:X[i-1], y:Y[i-1]})*h\n\ndef getActualValues(g,X):\n    for i in range(X.shape[0]):\n        Z[i]=g.subs(t,X[i])\n\n\n# program body\n# Case (A):\n# t belongs to [0,1] and y(0)=1, with h = 0.5\na, b, h = 0, 1, 0.5\nX = np.arange(a,b+h/2,h)\nY = np.zeros(X.shape[0])\nZ = np.zeros(X.shape[0])\nY[0] = 1\n\nf = sp.exp(t-y) # from question\ng = sp.log(sp.exp(t)+sp.exp(1)-1)\n\ngetEulerApproximation(f,X,Y,h)\ngetActualValues(g,X)\nprint('(a)')\nprint('Approx Sol: {}'.format(Y))\nprint('Exact Sol: {}'.format(Z))\nfor i in range(X.shape[0]):\n    print('Error for y({}) = {}'.format(X[i],abs(Y[i]-Z[i])))\n\n\n\n# Case (B):\n# t belongs to [1,2] and y(1)=2, with h = 0.5\na, b, h = 1, 2, 0.5\nX = np.arange(a,b+h/2,h)\nY = np.zeros(X.shape[0])\nZ = np.zeros(X.shape[0])\nY[0] = 2\n\nf = (1+t)/(1+y) # from question\ng = sp.sqrt(t*t + 2*t +6)-1\n\ngetEulerApproximation(f,X,Y,h)\ngetActualValues(g,X)\n\nprint('(b)')\nprint('Approx Sol: {}'.format(Y))\nprint('Exact Sol: {}'.format(Z))\nfor i in range(X.shape[0]):\n    print('Error for y({}) = {}'.format(X[i],abs(Y[i]-Z[i])))\n\n\n\n# Case (C):\n# t belongs to [2,3] and y(2)=2, with h = 0.25\na, b, h = 2, 3, 0.25\nX = np.arange(a,b+h/2,h)\nY = np.zeros(X.shape[0])\nZ = np.zeros(X.shape[0])\nY[0] = 2\n\nf = -y+(t*sp.sqrt(y)) # from question\ng = (t-2+(sp.sqrt(2)*sp.exp(1)*sp.exp(-t/2)))**2\n\ngetEulerApproximation(f,X,Y,h)\ngetActualValues(g,X)\n\nprint('(c)')\nprint('Approx Sol: {}'.format(Y))\nprint('Exact Sol: {}'.format(Z))\nfor i in range(X.shape[0]):\n    print('Error for y({}) = {}'.format(X[i],abs(Y[i]-Z[i])))\n\n\n\n# Case (D):\n# t belongs to [1,2] and y(1)=2, with h = 0.25\na, b, h = 1, 2, 0.25\nX = np.arange(a,b+h/2,h)\nY = np.zeros(X.shape[0])\nZ = np.zeros(X.shape[0])\nY[0] = 2\n\nf = (sp.sin(2*t)-(2*t*y))/(t*t) # from question\ng = (4+sp.cos(2)-sp.cos(2*t))/(2*(t**2))\n\ngetEulerApproximation(f,X,Y,h)\ngetActualValues(g,X)\n\nprint('(d)')\nprint('Approx Sol: {}'.format(Y))\nprint('Exact Sol: {}'.format(Z))\nfor i in range(X.shape[0]):\n    print('Error for y({}) = {}'.format(X[i],abs(Y[i]-Z[i])))\n", "meta": {"hexsha": "fa69df0eaa8013531956c9face4ad82cb1cba3f1", "size": 2228, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 6/Code/q2.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 6/Code/q2.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 6/Code/q2.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 21.4230769231, "max_line_length": 61, "alphanum_fraction": 0.5695691203, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9814534316905262, "lm_q2_score": 0.8933094039240554, "lm_q1q2_score": 0.8767415800426827}}
{"text": "import numpy as np\nimport scipy as sp\nimport sys\nimport os\nfrom sklearn.decomposition import PCA\n\ndef analyze(m):\n    #d=np.linalg.det(m)\n    r=np.linalg.matrix_rank(m)\n    c=np.linalg.cond(m)\n    #cd=np.linalg.cholesky(m)\n    svd=np.linalg.svd(m)\n    print('--------------------')\n    print(m)\n    print('--------------------')\n    print('rank=',r,'condition number=',c)\n    #print(cd)\n    print('--------------------')\n    print('singular value decomposition')\n    u = svd[0]\n    s = np.zeros(m.shape)#np.diag(svd[1])\n    s[0,0]=svd[1][0]\n    s[1,1]=svd[1][1]\n    v = svd[2]\n    print('u')\n    print(u)\n    print('sigma')\n    print(s)\n    print('v transpose')\n    print(v)\n    print('--------------------')\n    print('reconstruct m from svd m = U*S*V.T')\n    m1 = np.dot(np.dot(u, s), v)\n    print(m1)\n    print('--------------------')\n    print('show u is orthognoal matrix')\n    u0 = u[:,0]\n    u1 = u[:,1]\n    print(\"u0=\",u0)\n    print(\"u1=\",u1)\n    print('dot product of u0 dot u1 = 0')\n    print(np.dot(u0,u1))\n    print('u*u.T is the idenity')\n    print(np.dot(u,u.T))\n    print('--------------------')\n    print('show v is orthognoal matrix')\n    v0T = v[0,:]\n    v1T = v[1,:]\n    print(\"v0.T=\",v0T)\n    print(\"v1.T=\",v1T)\n    print(np.dot(v0T,v1T))\n    print('u*u.T is the idenity')\n    print(np.dot(u,u.T))\n    print('v*v.T is the idenity')\n    print(np.dot(v,v.T))\n    print('--------------------')\n    print('recreate A matrix from indivudual components')\n    print('a1 = s1 * u1 * v1.T')\n    ur,uc = u.shape\n    vr,vc = v.shape\n    a1=s[0,0]*np.dot(np.reshape(u0,(ur,1)),np.reshape(v0T,(1,vc)))\n    print(a1)\n    print('a2 = s2 * u2 * v2.T')\n    a2=s[1,1]*np.dot(np.reshape(u1,(ur,1)),np.reshape(v1T,(1,vc)))\n    print(a2)\n    print('A = a1 + a2')\n    m2 = a1 + a2\n    print(m2)\n    print('--------------------')\n    print('norms')\n    A=m\n    print('------------------------')\n    print('norms(A)')\n    print('A l1',np.linalg.norm(A, 1))\n    print('A l2',np.linalg.norm(A, 2))\n    print('A fro',np.linalg.norm(A, 'fro'))\n    print('A inf',np.linalg.norm(A, np.inf))\n\n    print('------------------------')\n    print('norm(a1)')\n    print('a1 rank', np.linalg.matrix_rank(a1))\n    print('l1',np.linalg.norm(a1, 1))\n    print('l2',np.linalg.norm(a1, 2))\n    print('fro',np.linalg.norm(a1, 'fro'))\n    print('inf',np.linalg.norm(a1, np.inf))\n\n    dx = m-a1\n    print('------------------------')\n    print('norm(A-a1)')\n    print('||A-a1|| l1',np.linalg.norm(dx, 1))\n    print('||A-a1|| l2',np.linalg.norm(dx, 2))\n    print('||A-a1|| fro',np.linalg.norm(dx, 'fro'))\n    print('||A-a1|| inf',np.linalg.norm(dx, np.inf))\n\n    # pca\n    print('------------------------')\n    print('pca')\n    pca = PCA(n_components=2)\n    pca.fit(m)  \n    print(pca.explained_variance_ratio_) \n    print(pca.singular_values_) \n    z = pca.fit_transform(m)\n    print(z)\n    iv = pca.inverse_transform(z)\n    print(iv)\n    print('------------------------')\n    print('recreate pca from svd')\n    print('s0=',s[0,0])\n    print('s1=',s[1,1])\n    # step 1 center the data around means\n    mu = np.mean(m, axis=0)\n    print('mu-',mu)\n    A0 = A - mu\n    print(A0)\n    # step 2 compute covar matrix\n    cov = np.dot(A0.T, A0) / (len(mu)-1)\n    print('covar matrix')\n    print(cov)\n    sv_cov = np.linalg.svd(cov)\n    print(\"svd u\", sv_cov[0])\n    print(\"svd s\", sv_cov[1])\n    print(\"svd v\", sv_cov[2]) \n    eig=np.linalg.eig(cov)\n    tot = sum(sv_cov[1])\n    print(sv_cov[1][0]/tot)\n    print(np.sqrt(sv_cov[1]))\n    print(np.sqrt(sv_cov[1])/sum(np.sqrt(sv_cov[1])))\n    print(np.dot(A0, sv_cov[2]))\n    \ndef pca_test(data):\n    Mean = np.mean(data, axis = 0)\n    print(Mean)\n    V = data - Mean\n    print(V)\n    C = np.dot(V.T, V)/(len(data) - 1)\n    Csv = np.linalg.svd(C)\n    Diag = Csv[1]\n    U = Csv[0]\n    print(U)\n    print(Diag/np.sum(Diag))\n    Proj = np.dot(V, U[0]).reshape((len(data),1))\n    print(Proj) # \n    #Back = np.dot(U[0],Proj)\n    #print(Back)\n    \n    \ndef main():\n    print(\"start\")\n    m = np.array([[3, 1], [1, 2], [4, 1], [5,2],[11,3],[18,4]])\n    #analyze(m)\n    pca_test(m)\n\n\nif __name__ == '__main__' :\n    main()\n", "meta": {"hexsha": "1ba33d13828311a1cb6943b2ad88abcbfae2ffd0", "size": 4128, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/python/linalg.py", "max_stars_repo_name": "jrrpanix/cexchange", "max_stars_repo_head_hexsha": "1cf075dc1168d9fb6e44b31fc00c44d91d5cd2f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-21T00:19:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T16:21:36.000Z", "max_issues_repo_path": "src/python/linalg.py", "max_issues_repo_name": "jrrpanix/cexchange", "max_issues_repo_head_hexsha": "1cf075dc1168d9fb6e44b31fc00c44d91d5cd2f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-18T23:44:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-18T23:44:48.000Z", "max_forks_repo_path": "src/python/linalg.py", "max_forks_repo_name": "jrrpanix/cexchange", "max_forks_repo_head_hexsha": "1cf075dc1168d9fb6e44b31fc00c44d91d5cd2f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-09T22:05:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T22:05:48.000Z", "avg_line_length": 26.4615384615, "max_line_length": 66, "alphanum_fraction": 0.5055717054, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551495568569, "lm_q2_score": 0.9086179055936797, "lm_q1q2_score": 0.8766846651916279}}
{"text": "import math\nimport numpy as np\nimport numpy.linalg as la\n\n\ndef point_from_angle(x, y, angle, length):\n    \"\"\"return the endpoint of a line starting in x,y using the given angle and length\"\"\"\n    x = x + length * math.cos(angle)\n    y = y + length * math.sin(angle)\n    return x, y\n\n\ndef distance(point_1, point_2):\n    \"\"\"Distance between the 2 points\"\"\"\n    return math.sqrt((point_1[0] - point_2[0]) ** 2 + (point_1[1] - point_2[1]) ** 2)\n\n\ndef get_line_angle(point_1, point_2):\n    \"\"\"Returns the angle of a line that goes from point_1 to point_2\"\"\"\n    return ((math.atan2((point_1[1] - point_2[1]), (point_1[0] - point_2[0])) * 180.0 / math.pi) + 360) % 360\n\n\ndef py_ang(v1, v2):\n    \"\"\" Returns the angle in radians between vectors 'v1' and 'v2'    \"\"\"\n    cosang = np.dot(v1, v2)\n    sinang = la.norm(np.cross(v1, v2))\n    return np.arctan2(sinang, cosang)\n\n\ndef check_periodicity(angle):\n    # Reset degrees after 2 PI radians\n    if angle >= 2 * math.pi:\n        angle = angle - 2 * math.pi\n    elif angle <= -2 * math.pi:\n        angle = angle + 2 * math.pi\n    return angle\n\n\ndef get_point_from_angle(point, angle, lenght):\n    \"\"\"\n    Return a point given a starting point, the angle that it has to form with respect to X-axis and how far from that\n    point it has to be.\n    :param point: Initial point\n    :param angle: angle with respect to X-axis\n    :param lenght: How far from the initial point the final point must be\n    :return: array with [x, y]\n    \"\"\"\n    return [point[0] + lenght * math.cos(angle), point[1] + lenght * math.sin(angle)]\n", "meta": {"hexsha": "2b046c56f6a59e3326f5301c7daa463785e48fee", "size": 1563, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/helper.py", "max_stars_repo_name": "Brechard/Robot-Simulator", "max_stars_repo_head_hexsha": "201256fdae6d6d1bd7221832ed4646afbe0779aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/helper.py", "max_issues_repo_name": "Brechard/Robot-Simulator", "max_issues_repo_head_hexsha": "201256fdae6d6d1bd7221832ed4646afbe0779aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/helper.py", "max_forks_repo_name": "Brechard/Robot-Simulator", "max_forks_repo_head_hexsha": "201256fdae6d6d1bd7221832ed4646afbe0779aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8979591837, "max_line_length": 117, "alphanum_fraction": 0.6423544466, "include": true, "reason": "import numpy", "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924785827002, "lm_q2_score": 0.9019206699387733, "lm_q1q2_score": 0.8766601074587578}}
{"text": "import numpy as np\nfrom sympy import *\n\n\"\"\"\n\nThe transfer function is defined as\n\nY(s)/U(s) = G(s)\n\nThe state space equations is defined as\nx' = Ax + Bu\ny  = Cx + du\n\nTake the laplace transform of the state space equation and get\nsX(s) - x(0) = AX(s) + BU(s)\nY(s)         = CX(s) + DU(s)\n\nThe Laplace Transform assumes the initial conditions to be 0 so x(0) = 0\nsX(s) - AX(s) = BU(s)\n\nFactor X(s) out\n(sI - A)X(s) = B*U(s)\n\nSolve for X(s)\nX(s) = (sI - A)^-1BU(s)\n\nSubstitute X(s)\nY(s) = CX(s) + DU(s)\nY(s) = (C(sI - A)^-1B + D)U(s)\n\nWe can see that the equation\nG(s) = C(sI - A)^-1B + D\n\n\"\"\"\n\ndef st2tf(A, B, C, D):\n    s = Symbol('s')\n    I = eye(A.shape[0])\n    G = C*(s*I - A)**-1*B + D\n    G = simplify(G)\n    \n    print('Converting State Space Matrix to Transfer Function')\n    print('\\nA\\n\\n')\n    pprint(A)\n    print('\\nB\\n\\n')\n    pprint(B)\n    print('\\nC\\n\\n')\n    pprint(C)\n    print('\\nD\\n\\n')\n    pprint(D)\n    print('\\nG\\n\\n')\n    pprint(G)\n    print('\\n\\n')\n\nb = Symbol('b')\nk = Symbol('k')\nm = Symbol('m')\nKp = Symbol('kp')\ntaup = Symbol('taup')\ntau = Symbol('tau')\nzeta = Symbol('zeta')\n\nA = Matrix([[0, 1], [-k/m, -b/m]])\nB = Matrix([[0], [1/m]])\nC = Matrix([[1, 0]])\nD = Matrix([0])\nst2tf(A, B, C, D)\n\nA = Matrix([[-14, -56, -160], [1, 0, 0], [0, 1, 0]])\nB = Matrix([[1], [0], [0]])\nC = Matrix([[0, 1, 0]])\nD = Matrix([0])\nst2tf(A, B, C, D)\n\nA = Matrix([-1/taup])\nB = Matrix([Kp/taup])\nC = Matrix([1])\nD = Matrix([0])\nst2tf(A, B, C, D)\n\nA = Matrix([[0,1],[-1/tau**2,-2*zeta/tau]])\nB = Matrix([[0],[Kp/tau**2]])\nC = Matrix([[1, 0]])\nD = Matrix([0])\nst2tf(A, B, C, D)\n\nA = Matrix([[0, 1], [0, -10/100]])\nB = Matrix([[0], [1/100]])\nC = Matrix([[1, 0]])\nD = Matrix([0])\nK = Matrix([[30, 70]])\nst2tf(A, B, C, D)\nst2tf(A - np.dot(B, K), B, C, D)\n", "meta": {"hexsha": "ee230b61d0a2ac08d34200ce618e3ececee9b195", "size": 1758, "ext": "py", "lang": "Python", "max_stars_repo_path": "math/controls/state-space-to-transfer-function.py", "max_stars_repo_name": "qeedquan/misc_utilities", "max_stars_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-10-17T18:17:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:02:53.000Z", "max_issues_repo_path": "math/controls/state-space-to-transfer-function.py", "max_issues_repo_name": "qeedquan/misc_utilities", "max_issues_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/controls/state-space-to-transfer-function.py", "max_forks_repo_name": "qeedquan/misc_utilities", "max_forks_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:52:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:10:59.000Z", "avg_line_length": 18.7021276596, "max_line_length": 72, "alphanum_fraction": 0.5136518771, "include": true, "reason": "import numpy,from sympy", "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971992481016635, "lm_q2_score": 0.9019206673024666, "lm_q1q2_score": 0.8766601070915035}}
{"text": "import numpy as np\nfrom numpy.linalg import inv\n\n'''\nStandard matrix formula for solving a system of equations. A is an nxn matrix.\n\nAx = b\nAi A x = Ai b\nI x = Ai b\nx = Ai b\n'''\n\n# Test matrix. An underdetermined example is commented out to test exception handling.\nA = np.array([[1.0, 2.0, 3.0],[10.0, 7.0, 3.0],[3.0, 1.0, 11.0]])\n# A = np.array([[1.0, 2.0, 3.0],[1.0, 2.0, 3.0],[3.0, 1.0, 11.0]])\n\n# Get the inverse of A.\ntry:\n    Ai = inv(A)\nexcept np.linalg.LinAlgError:\n    print(\"Matrix is singular\")\n    quit()\n\nprint(\"\\nStandard method for solving Ax = b using an inverse\")\nprint(\"A\")\nprint(A)\nprint(\"Matrix A rank: \", np.linalg.matrix_rank(A))\nprint(\"Ai\")\nprint(Ai)\nprint(\"Ai A = I\")\nprint(np.dot(Ai, A))\n\n# Calculate b from some test x values.\nxtest = np.array([10.0, 11.0, 12.0])\nb = np.dot(A, xtest)\nprint(\"b\")\nprint(b)\n\n# Now solve for x and show that they match.\nx = np.dot(Ai, b)\nprint(\"xtest and x calculated\")\nprint (xtest, x)\n\n'''\nSVD way - this is a least squares fit for use when there is error in the system.\nhttps://en.wikipedia.org/wiki/Singular_value_decomposition\nhttps://austingwalters.com/using-svd-to-obtain-regression-lines/\nSee PDFs in this repo, too.\n\nFor:\n\nAx = b\n\nA can be decomposed by SVD as follows:\n\nA = U S Vt      \n\nU and V are orthogonal matrices for n x n systems, so transpose == inverse. Transpose == inverse\nfor these matrices on m x n systems (m > n), too. S is diagonal matrix containing the singular values. \nIf A is overdetermined (more rows than columns), S must have zeroed rows added in order to calc x.\nThe svd() function just returns the vector of values in S as the s vector. \n\nU S Vt x = b\n\nx = V Si Ut b\n\nSi = is a pseudo-inverse in which the non-zero elements on the diagonal are inverted.\n'''\n\n# Reusing A, b, and xtest from above.\n\n# SVD\n# Note: catch LinAlgError to see if the calculation doesn't converge. I test this above.\nU, s, Vt = np.linalg.svd(A)\n\n# Create a diagonal matrix for S and it's pseudo-inverse\nS = np.diag(s)\nsi = 1/s\nSi = np.diag(si)\n\nprint(\"\\nSVD method of solving Ax = b\")\nprint(\"A = U S Vt\")\nprint(\"U \", U.shape)\nprint(U)\nprint(\"S\", S.shape)\nprint(S)\nprint(\"s \", s.shape)\nprint(s)\nprint(\"Si\", Si.shape)\nprint(Si)\nprint(\"si \", si.shape)\nprint(si)\nprint(\"Vt \", Vt.shape)\nprint(Vt)\n\nprint(\"\\nNow let's check the decomposition\")\nprint(\"A\")\nprint(A)\n\n# element-wise multiply works for s because s is a 1D vector (??)\n# Acheck = np.dot(U * s, Vt)  \n# print(\"A = U s Vt\")\n# print(Acheck)\n\n# Check the decomposition.\nAcheck2 = np.dot(U, np.dot(S, Vt))\nprint(\"A = U S Vt\")\nprint(Acheck2)\n\nprint(\"\\nNow let's solve for x\")\n\n# Solve for x. This just uses the si vector instad of the Si matrix. \nxnew = np.dot(Vt.T * si, np.dot(U.T, b))\nprint(\"x = V si Ut b\")\nprint(xnew)\n\n# Solve for x again using the Si matrix. I prefer this notation better.\n# Note: there are lots of ways to write this matrix multiplication. multi_dot is the clearest to me.\n# Also note that technically this should be Si.T as below. For a square matrix, it doesn't matter.\n# xnew = np.dot(np.dot(Vt.T, Si), np.dot(U.T, b))\n# xnew = Vt.T.dot(Si).dot(U.T).dot(b)\nxnew = np.linalg.multi_dot([Vt.T, Si, U.T, b])\nprint(\"x = V Si Ut b\")\nprint(xnew)\nprint(\"\\n\")\n\n'''\nSVD again, but with an overdetermined system of equations, i.e. more rows than columns.\n\nAlso adding some error into the system to show an \"almost correct\" answer.\n'''\n\nprint(\"\\n SVD again with a non-square matrix B\")\n\n# Test matrix\nB = np.array([[1.0, 2.0, 3.0],[10.0, 7.0, 3.0],[3.0, 1.0, 11.0],[15.0, 9.0, 5.0]])\nprint(\"B\")\nprint(B)\nprint(\"Matrix B rank: \", np.linalg.matrix_rank(B))\n\n# Put in some x values to calculate b\nxtest2 = np.array([10.0, 11.0, 12.0])\nb = np.dot(B, xtest2)\nprint(\"xtest\")\nprint(xtest2)\nprint(\"b\")\nprint(b)\n\n# Add some error to B to show least-squares convergence.\nprint(\"\\nLet's add some error to B\")\nerror = np.random.rand(4,3)\nerror /= 100.0\nprint(error)\nB += error\nprint(\"\\nB with error\")\nprint(B)\n\n# SVD\nU, s, Vt = np.linalg.svd(B)\n\n# Create a diagonal matrix for S and it's pseudo-inverse\nS = np.diag(s)\nsi = 1/s\nSi = np.diag(si)\n\n# Addd a row to S since we're over-determined by one row. (TODO: fix to work with any m x n.)\nS = np.append(S, [[0, 0, 0]], axis=0)\nSi = np.append(Si, [[0, 0, 0]], axis=0)\n\nprint(\"\\nSVD method of solving Bx = b\")\nprint(\"B = U S Vt\")\nprint(\"U \", U.shape)\nprint(U)\nprint(\"S\", S.shape)\nprint(S)\nprint(\"s \", s.shape)\nprint(s)\nprint(\"Si\", Si.shape)\nprint(Si)\nprint(\"Si.T\", Si.T.shape)\nprint(Si.T)\nprint(\"si \", si.shape)\nprint(si)\nprint(\"Vt \", Vt.shape)\nprint(Vt)\n\nprint(\"\\nNow let's check the decomposition\")\nprint(\"B\")\nprint(B)\n\n# Check the decomposition\nBcheck2 = np.linalg.multi_dot([U, S, Vt])\nprint(\"B = U S Vt\")\nprint(Bcheck2)\n\n# Solve for x\n# Note that Si has to be transposed to make it 3x4. The diagonal values don't change on the transpose.\n# The zero row just becomes a zero column.\nxnew2 = np.linalg.multi_dot([Vt.T, Si.T, U.T, b])\nprint(\"x = V Si Ut b\")\nprint(xnew2)\nprint(\"\\n\")\n", "meta": {"hexsha": "a54219ea1aa77faf6cf0bb0c4e6b8e1248d41d74", "size": 4954, "ext": "py", "lang": "Python", "max_stars_repo_path": "svdexample.py", "max_stars_repo_name": "dgaff/linearalgebra", "max_stars_repo_head_hexsha": "c2de722f6ab6b8656a7f888c7a7717c99ec2b156", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "svdexample.py", "max_issues_repo_name": "dgaff/linearalgebra", "max_issues_repo_head_hexsha": "c2de722f6ab6b8656a7f888c7a7717c99ec2b156", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "svdexample.py", "max_forks_repo_name": "dgaff/linearalgebra", "max_forks_repo_head_hexsha": "c2de722f6ab6b8656a7f888c7a7717c99ec2b156", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4039408867, "max_line_length": 103, "alphanum_fraction": 0.6655228099, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.9111797106148062, "lm_q1q2_score": 0.8766528973139818}}
{"text": "#!/usr/bin/env python3\n\nimport numpy as np\nimport operator as op\nfrom functools import reduce\n\n#Maximum path sum II\n#Problem 67\n#By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.\n\n#3\n#7 4\n#2 4 6\n#8 5 9 3\n\n#That is, 3 + 7 + 4 + 9 = 23.\n\n#Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows.\n\n#NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)\n\n\n\nfilename = 'p067_triangle.txt'\nrawfile = open(filename).read()\n\n\n# split by line\nlines = rawfile.splitlines()\n\n\n# create matrix to hold data\ngrid_n = np.zeros(shape=(len(lines),len(lines)))\n\n\n# convert to integers\nfor i in range(len(lines)):\n  num_str = lines[i]\n  nums = np.asarray(num_str.split(' '))\n  grid_n[i,:len(nums)] = nums\n\n\nprint(grid_n[0:3,:])\n#print(grid_n[0:3,:])\n\ndef walk_sum(grid,row,col):\n  if row==0: return grid[0,0]\n  if (row>0):\n    if(col>0):\n      temp1=grid[row-1,col]\n      temp2=grid[row-1,col-1]\n      if temp1>temp2:\n        return(grid[row,col]+walk_sum(grid,row-1,col))\n      return(grid[row,col]+walk_sum(grid,row-1,col-1))\n    return(grid[row,col]+walk_sum(grid,row-1,col))\n\n\ncount = 0\n#print(grid_n.shape)\n#for i in range(grid_n.shape[1]):\n#  temp = walk_sum(grid_n,grid_n.shape[0]-1,i)\n#  if temp > count: count = temp\n\n#print(count)\n\n# idea 2 - optimal substructure!\n# start from top, and calculate max sum for each element\n# at the bottom, take the max\n\ndef max_sum(grid):\n  grid_sum = np.zeros(shape=(grid.shape[0],grid.shape[1]))\n  \n  for row in range(0,grid.shape[0]):\n    for col in range(0,row+1):\n      #print(row,col, grid[row,col])\n      grid_sum[row,col] = grid[row,col]\n      if row==0: \n        if col==0: grid_sum[0,0] = grid[0,0]      \n        else: grid_sum[row,col] += grid_sum[row-1,col]\n        #print(\"row 0,\", row,grid[row-1,col],grid_sum[row,col])\n      elif col==row:\n        grid_sum[row,col] += grid_sum[row-1,col-1]\n        #print(\"col=row,\", row,grid[row-1,col-1],grid_sum[row,col])\n      else: \n        grid_sum[row,col] += max([grid_sum[row-1,col-1],grid_sum[row-1,col]])\n  return(grid_sum)\n\n\ntemp = max_sum(grid_n)\nprint(temp[-1,:],max(temp[-1,:]))\n\n# 7273 YAY\n\n\n\n\n\n", "meta": {"hexsha": "2b4e3d369cee24de452d688ef6f042c9a09359c4", "size": 2540, "ext": "py", "lang": "Python", "max_stars_repo_path": "question67.py", "max_stars_repo_name": "larkaa/project_euler", "max_stars_repo_head_hexsha": "a3d980b0436cfaac0dd0b3c9fb6025b5713f8397", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "question67.py", "max_issues_repo_name": "larkaa/project_euler", "max_issues_repo_head_hexsha": "a3d980b0436cfaac0dd0b3c9fb6025b5713f8397", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "question67.py", "max_forks_repo_name": "larkaa/project_euler", "max_forks_repo_head_hexsha": "a3d980b0436cfaac0dd0b3c9fb6025b5713f8397", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9183673469, "max_line_length": 316, "alphanum_fraction": 0.6622047244, "include": true, "reason": "import numpy", "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.935346511193214, "lm_q1q2_score": 0.876616843991379}}
{"text": "#!/usr/bin/env python\n\"\"\"\n    Copyright 2019 by Michael Wild (alohawild)\n    \n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n        http://www.apache.org/licenses/LICENSE-2.0\n        \n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n============================================================================================================\nThis is a pi calculation process using Monte Carlo or simple random process.\n\nImagine a circle in a box. The edges just touch the box. Lets make it a circle of radius 1.\n\nThus any point on or within the cirlce are 1 unit or less from the center.\n\nIt should be possible to randomly select points in the box and determine if the point is in the circle or not.\nThe ratio of points in the box over the number of randomly selected should be 1/4*Pi\n\nWe are using the numpy library to get some more exact results. Also numpy is not slow.ArithmeticError\n\nWe also added the mpmath library to use 50 digits of floating point accuracy. The calls to mpf force the results into \n50 digits of floating point accuracy.\n\n\"\"\"\n__author__ = 'michaelwild'\n__copyright__ = \"Copyright (C) 2018 Michael Wild\"\n__license__ = \"Apache License, Version 2.0\"\n__version__ = \"0.0.1\"\n__credits__ = [\"Michael Wild\"]\n__maintainer__ = \"Michael Wild\"\n__email__ = \"alohawild@mac.com\"\n__status__ = \"Initial\"\n\nfrom mpmath import mp,mpf  # This is the floating point accuracy set to 50 for this example\nmp.dps = 50\n\nimport sys\nimport numpy as np\nimport math\n\nfrom time import process_time\n\ndef howFar(x,y):\n\n# The distance is always from the center at 0,0 and thus we can dispense with the subtractions of points.\n    \n    distance = mpf((x * x) + (y * y))  # Orginally I used an exponent as this more appealing to me, but it was less accurate!\n    return mpf(np.sqrt(distance))  # From what I have read this is more accurate and faster version\n\ndef runtime(start):\n\n# I use this a lot so I have a routine.\n\n    return process_time() - start\n\n# =============================================================\n\nprogram = \"Pi Calc\"\n\npiLoop = 10000\ninCircle = 0\n\nbegin_time = process_time()\n\n# =============================================================\n# Main program begins here\n\nprint(program)\nprint(\"Version \", __version__, \" \", __copyright__, \" \", __license__)\nprint(\"Running on \", sys.version)\n\nfor i in range(1, piLoop):\n    x = mpf(np.random.uniform()* 2) -1\n    y = mpf(np.random.uniform() * 2) -1\n\n    if (howFar(x,y)<1.0) :\n        inCircle = inCircle + 1\npiGuess = mpf(4.0* mpf(inCircle / piLoop))\n\npiError = math.pi - piGuess\n\nprint(\"Loops:\", piLoop)\nprint(\"Calculated value: \",piGuess, \"Error: \", piError)\n\nfinish = runtime(begin_time)\nprint(\"Run time:\", finish)\n", "meta": {"hexsha": "6e6084222b3835044a0d1706cc510acba8aab08f", "size": 3089, "ext": "py", "lang": "Python", "max_stars_repo_path": "pi_calc_50.py", "max_stars_repo_name": "alohawild/python_class", "max_stars_repo_head_hexsha": "99d676d177220c36a808b05e44464f9e96641bac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-04T17:19:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-04T17:19:01.000Z", "max_issues_repo_path": "pi_calc_50.py", "max_issues_repo_name": "alohawild/python_class", "max_issues_repo_head_hexsha": "99d676d177220c36a808b05e44464f9e96641bac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pi_calc_50.py", "max_forks_repo_name": "alohawild/python_class", "max_forks_repo_head_hexsha": "99d676d177220c36a808b05e44464f9e96641bac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8617021277, "max_line_length": 125, "alphanum_fraction": 0.6672062156, "include": true, "reason": "import numpy,from mpmath", "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.933430810103574, "lm_q1q2_score": 0.8765147008181863}}
{"text": "import numpy as np\nimport scipy as sc\n\n\ndef Normalize(adjmat, tele_const = 0.2):\n    \"\"\"\n    This method will try and normalize the adjacency matrix, so that it will be suitable for the PageRank algorithm. Using the teleporting constant it will remove the effect of deadends in the PageRank algorithm.\n\n    Parameters\n    ----------\n    adjmat: numpy array\n            a square adjacency matrix\n    tele_const: float\n                teleporting constant for the PageRank algorithm (P' = (1-alpha)*P + alpha*v)\n\n    Returns\n    -------\n    mat: numpy array\n         an square matrix of size equal to the adjmat matrix and normalized\n    \"\"\"\n\n    mat = np.zeros(adjmat.shape)\n    cols = adjmat.shape[0]\n    deadend_const = 1.0 / cols\n    for i in range(cols):\n        s = np.sum(adjmat[i,:])\n        if s == 0:\n            mat[i,:] = deadend_const\n        else:\n            mat[i,:] = adjmat[i,:] / s\n        mat[i,:] = mat[i,:] * (1 - tele_const) + deadend_const * tele_const\n    return mat\n\ndef PageRankScores(norm_mat):\n    \"\"\"\n    Calculates the PageRank score vector for norm_mat normalized adjacency matrix\n\n    Parameters\n    ----------\n    norm_mat: numpy array\n              the normalized adjacency matrix, such that each row sums up to one.\n\n    Returns\n    -------\n    sv: numpy array\n        the PageRank score vector\n    \"\"\"\n    sw, sv = sc.sparse.linalg.eigs(norm_mat.T, k=1, which='LR')\n    sv = sv.T[0]\n    sv = np.abs(sv)\n    sv /= np.sum(sv)\n    return sv\n", "meta": {"hexsha": "3dfae242caf483fafa36a5e268e2e4ffe2c5e3e6", "size": 1473, "ext": "py", "lang": "Python", "max_stars_repo_path": "PageRank.py", "max_stars_repo_name": "erfannoury/GoodSearcher", "max_stars_repo_head_hexsha": "102141e9398cf52b94a59f22b4e0031d9b7c3bea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2015-01-25T21:12:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T01:06:19.000Z", "max_issues_repo_path": "PageRank.py", "max_issues_repo_name": "erfannoury/GoodSearcher", "max_issues_repo_head_hexsha": "102141e9398cf52b94a59f22b4e0031d9b7c3bea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-10-15T20:08:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-07T06:47:13.000Z", "max_forks_repo_path": "PageRank.py", "max_forks_repo_name": "erfannoury/GoodSearcher", "max_forks_repo_head_hexsha": "102141e9398cf52b94a59f22b4e0031d9b7c3bea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-10-15T19:11:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-27T10:47:56.000Z", "avg_line_length": 27.7924528302, "max_line_length": 212, "alphanum_fraction": 0.6014935506, "include": true, "reason": "import numpy,import scipy", "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668695588649, "lm_q2_score": 0.8933093982432729, "lm_q1q2_score": 0.8764855858218654}}
{"text": "import numpy as np # for math\n\n# Collection of activation functions\n# References: \n# https://en.wikipedia.org/wiki/Activation_function\n# https://miro.medium.com/proxy/1*RD0lIYqB5L2LrI2VTIZqGw.png\n# https://deepai.org/machine-learning-glossary-and-terms/sigmoid-function\n# σ(x) = 1 / 1+e(−xb)\n# x = cosh(a) = e(a)+e(−a)/2​   &    y = sinh(a) = e(a)−e(−a)/2\n# https://brilliant.org/wiki/hyperbolic-trigonometric-functions/\n\nclass Sigmoid():\n    def __call__(self, x, bias=0):\n        return 1 / (1 + np.exp(-x + bias))\n    \n    def gradient(self, x, bias=0, out=None):\n        if out is None:\n            out = self.__call__(x, bias)\n        return out * (1 - out)\n\nclass TanH():\n    def __call__(self, x):\n        return 2 / (1 + np.exp(-2 * x)) - 1\n\n    def gradient(self, x):\n        return 1 - (self.__call__(x) ** 2)\n\nclass ReLU():\n    def __call__(self, x):\n        return np.where(x >= 0, x, 0)\n\n    def gradient(self, x):\n        return np.where(x >= 0, 1, 0)\n\nclass SoftPlus():\n    def __call__(self, x):\n        return np.log(1 + np.exp(x))\n    \n    def gradient(self, x):\n        return 1 / (1 + np.exp(-x))\n\nclass LeakyReLU():\n    def __init__(self, alpha=0.2):\n        self.alpha = alpha\n\n    def __call__(self, x):\n        return np.where(x >= 0, x, self.alpha * x)\n\n    def gradient(self, x):\n        return np.where(x >= 0, 1, self.alpha)\n\nclass ELU():\n    def __init__(self, alpha=0.2):\n        self.alpha = alpha\n\n    def __call__(self, x):\n        return np.where(x >= 0.0, x, self.alpha * (np.exp(x) - 1))\n\n    def gradient(self, x):\n        return np.where(x >= 0.0, 1, self.__call__(x) + self.alpha)\n\nclass SELU():\n    def __init__(self):\n        self.alpha = 1.6732632423543772848170429916717\n        self.scale = 1.0507009873554804934193349852946 \n\n    def __call__(self, x):\n        return self.scale * np.where(x >= 0.0, x, self.alpha*(np.exp(x) - 1))\n    \n    def gradient(self, x):\n        return self.scale * np.where(x >= 0.0, 1, self.alpha * np.exp(x))\n\nclass Softmax:\n    def __call__(self, x):\n        e_x = np.exp(x - np.max(x))\n        return e_x / np.sum(e_x)\n    \n    def gradient(self, x):\n        p = self.__call__(x)\n        return p * (1 - p)\n\nclass Softmax_V2():\n    def __call__(self, x):\n        exponential = np.exp(x - np.max(x, axis=-1, keepdims=True))\n        return exponential / np.sum(exponential , axis=-1, keepdims=True)\n    \n    def gradient(self, x):\n        p = self.__call__(x)\n        return p * (1 - p)\n\nact_functions = {\n    \"sigmoid\"   : Sigmoid,\n    \"tanh\"      : TanH,\n    \"relu\"      : ReLU,\n    \"softplus\"  : SoftPlus,\n    \"leakyrelu\" : LeakyReLU,\n    \"elu\"       : ELU,\n    \"selu\"      : SELU,\n    \"softmax\"   : Softmax,\n    \"softmax_v2\"   : Softmax_V2\n}\n", "meta": {"hexsha": "69f240b06e936c3ed347b92db59fcdb5dcc7ca4e", "size": 2719, "ext": "py", "lang": "Python", "max_stars_repo_path": "deep_learning/_network/algorithms/activation_functions.py", "max_stars_repo_name": "niektuytel/Machine_Learning", "max_stars_repo_head_hexsha": "0cd5656ca8076c383fd81c5e32a49969a20ad042", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-07-05T15:51:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T15:17:37.000Z", "max_issues_repo_path": "deep_learning/_network/algorithms/activation_functions.py", "max_issues_repo_name": "niektuytel/Machine_Learning", "max_issues_repo_head_hexsha": "0cd5656ca8076c383fd81c5e32a49969a20ad042", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deep_learning/_network/algorithms/activation_functions.py", "max_forks_repo_name": "niektuytel/Machine_Learning", "max_forks_repo_head_hexsha": "0cd5656ca8076c383fd81c5e32a49969a20ad042", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6568627451, "max_line_length": 77, "alphanum_fraction": 0.5645457889, "include": true, "reason": "import numpy", "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211582993982, "lm_q2_score": 0.8991213847035617, "lm_q1q2_score": 0.8764825496884848}}
{"text": "import numpy as np\n\nfrom utils import get_input, ints\n\n\ndef main():\n    \"\"\"\n    Goal: develop an analytical solution for the problem.\n    First, describe the recurrence relation. Note that:\n\n    a0,n = a1,n-1\n    a1,n = a2,n-1\n    ...\n    a6,n = a7,n-1 + a0,n-1\n    a7,n = a8,n-1\n    a8,n = a0,n-1\n\n    Where ai,j := the number of fish at time i, with lifetime j\n    Then, define yn := a0,n\n    The above system can then be reduced down to the following single recurrence relation:\n\n    yn = yn-7 + yn-9\n\n    The solution to this is the equation:\n\n    yn = c1r1^n + c2r2^n + ... + c9r9^n\n    where c1, ... c9 are some arbitrary coefficients\n          r1, ... rn are the roots of the polynomial x^9 - x^2 - 1 = 0\n\n    These roots are then computed numerically, and then we need to solve for the coefficients.\n    In order to do that, we need the first y1, ... y9 values, which can be inferred from the input data\n    Then we solve the matrix equation:\n\n    [ r1^1 ... r9^1 ] [ c1 ]   [ y1 ]\n    [ ...      ...  ] [ .. ] = [ .. ]\n    [ r1^n ... r9^n ] [ c9 ]   [ y9 ]\n\n    This gives us the values of c1, ... c9.\n    Now, with an explicit formula for yn, we can define Kn = the sum of a0,n + ... + a8,n\n    Using the definition of yn, this becomes:\n\n    Kn = yn+5 + ... + yn + 2*yn-1 + yn-2 + yn-3\n\n    The solution is then rounded to the nearest complex integer, and the real part is now our answer.\n    \"\"\"\n\n    values = ints(get_input())\n\n    ys = np.array([values.count(n % 7) for n in range(9)])\n    rs = np.roots((1, 0, 0, 0, 0, 0, 0, -1, 0, -1))  # x^9 - x^2 - 1 = 0\n    A = np.array([[pow(r, n) for r in rs] for n in range(9)])\n    cs = np.linalg.solve(A, ys)  # Ax = b\n\n    # Note that both rs is constant (across all inputs), and cs is constant (across any specific input).\n    # So solving any value of n can be done just with those precomputed values.\n\n    print('Part 1:', solve(80, rs, cs))\n    print('Part 2:', solve(256, rs, cs))\n\ndef solve(n: int, rs, cs) -> int:\n    return round(sum((2 if j == -1 else 1) * sum(c * pow(r, n + j) for r, c in zip(rs, cs)) for j in range(-3, 6)).real)\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "b37018f8a7db6fb508fcbe1bce50f2f20c28769d", "size": 2140, "ext": "py", "lang": "Python", "max_stars_repo_path": "day06/day06_analytical.py", "max_stars_repo_name": "alcatrazEscapee/AdventOfCode2021", "max_stars_repo_head_hexsha": "a473b01b8931791b4a1fd03bf05b286ed0ac9f85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-12-07T22:25:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T18:15:25.000Z", "max_issues_repo_path": "day06/day06_analytical.py", "max_issues_repo_name": "alcatrazEscapee/AdventOfCode2021", "max_issues_repo_head_hexsha": "a473b01b8931791b4a1fd03bf05b286ed0ac9f85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day06/day06_analytical.py", "max_forks_repo_name": "alcatrazEscapee/AdventOfCode2021", "max_forks_repo_head_hexsha": "a473b01b8931791b4a1fd03bf05b286ed0ac9f85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-17T00:47:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:26.000Z", "avg_line_length": 32.4242424242, "max_line_length": 120, "alphanum_fraction": 0.5859813084, "include": true, "reason": "import numpy", "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211561049159, "lm_q2_score": 0.8991213691605412, "lm_q1q2_score": 0.8764825325637137}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport imageio\n\n# Number of observations\nt = np.arange(0, 1, 0.001)\nprint(\"Number of observations: \", t.shape[0])\n\n# Sine\nmysine = np.sin(2 * np.pi * t)\n\n# Sine * 4\nmysine4 = np.sin(2 * np.pi * t * 4)\n\n# Cosine * 4\nmycos4 = np.cos(2 * np.pi * t * 4)\n\n# Cosine * 18\nmycos18 = np.cos(2 * np.pi * t * 18)\n\n# Combining all the functions\nmyfun = mysine + mysine4 + mycos4 + mycos18\nplt.figure(figsize=(10, 4))\nplt.plot(t, myfun)\nplt.savefig('myfun.png')\n\n# Match sines and cosines with 4Hz (part of the signal)\nOmega = 4\nmatch_sin_4 = myfun * np.sin(Omega * (2 * np.pi) * t)\nmatch_cos_4 = myfun * np.cos(Omega * (2 * np.pi) * t)\nprint('Sum of matching sines at 4Hz = %.2f' % np.sum(match_sin_4))\nprint('Sum of matching cosines at 4Hz = %.2f' % np.sum(match_cos_4))\n\n# Match sines and cosines with 3Hz (not part of the signal)\nOmega = 3\nmatch_sin_3 = myfun * np.sin(Omega * (2 * np.pi) * t)\nmatch_cos_3 = myfun * np.cos(Omega * (2 * np.pi) * t)\nprint('Sum of matching sines at 3Hz = %.4f' % np.sum(match_sin_3))\nprint('Sum of matching cosines at 3Hz = %.4f' % np.sum(match_cos_3))\n\n# This procedure is able to detect that our function has 4Hz patterns while 3Hz\n# is absent\n\n# Plot the point-wise multiplication to observe this effect\n\nplt.figure(figsize=(10, 4))\nplt.plot(t, myfun, '-k')\nplt.plot(t, match_sin_3, '--r')\nplt.savefig('match_sin_3.png')\n\nplt.figure(figsize=(10, 4))\nplt.plot(t, myfun, '-k')\nplt.plot(t, match_sin_4, '--r')\nplt.savefig('match_sin_4.png')\n\ndef match_freqs(f, t, maxfreq):\n  print(\"Coefficients of sine and cosine matching\")\n  for Omega in np.arange(0, maxfreq):\n    match_sin = np.sum(f * np.sin(Omega * 2 * np.pi * t))\n    match_cos = np.sum(f * np.cos(Omega * 2 * np.pi * t))\n    print(\"%d\\t%.1f\\t%.1f\" % (Omega, match_sin, match_cos))\n\nmatch_freqs(myfun, t, 22)\n", "meta": {"hexsha": "e3ab342133d7f879a174fe3ca7b5b498349632f0", "size": 1840, "ext": "py", "lang": "Python", "max_stars_repo_path": "other-exercises/fourier/fourier_analysis.py", "max_stars_repo_name": "brenov/ip-usp", "max_stars_repo_head_hexsha": "06f9f16229a4587e38a3ae89fbe3394d5f1572fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "other-exercises/fourier/fourier_analysis.py", "max_issues_repo_name": "brenov/ip-usp", "max_issues_repo_head_hexsha": "06f9f16229a4587e38a3ae89fbe3394d5f1572fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "other-exercises/fourier/fourier_analysis.py", "max_forks_repo_name": "brenov/ip-usp", "max_forks_repo_head_hexsha": "06f9f16229a4587e38a3ae89fbe3394d5f1572fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.75, "max_line_length": 79, "alphanum_fraction": 0.6630434783, "include": true, "reason": "import numpy", "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561667674653, "lm_q2_score": 0.9046505421702796, "lm_q1q2_score": 0.8764762565512063}}
{"text": "import numpy as np\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_iris\nfrom sklearn import decomposition\nfrom scipy import linalg as la\n\ndef kmeans(data,n_clusters,init='random',max_iter=300,normalize=False):\n    n,m = data.shape\n    norms = np.zeros((n,n_clusters))\n    if init=='random':\n        means = data.mean(axis=0)+np.random.randn(n_clusters,m)*data.std()\n    else:\n        means=init\n    if normalize:\n        means /= np.linalg.norm(means,axis=1)[:,np.newaxis]\n    for i in xrange(n_clusters):\n        norms[:,i] = ((data-means[i,:])**2).sum(axis=1)\n    labels = np.argmin(norms,axis=1)\n    it =0\n    for j in xrange(max_iter):\n        it += 1\n        means = np.array([data[labels==i].mean(axis=0) for i in xrange(n_clusters)])\n        if normalize:\n            means /= np.linalg.norm(means,axis=1)[:,np.newaxis]\n        for i in xrange(n_clusters):\n            norms[:,i] = ((data-means[i,:])**2).sum(axis=1)\n        new_labels = np.argmin(norms,axis=1)\n        if not np.allclose(labels,new_labels):\n            labels=new_labels\n        else:\n            break\n\n    inertia = 0\n    for i in xrange(n_clusters):\n        inertia += ((data[labels==i]-means[i,:])**2).sum()\n    return means,labels,inertia\n\ndef clusterIris():    \n    iris = load_iris()\n    \n    X = iris.data\n    # pre-process\n    Y = X - X.mean(axis=0)\n    # get SVD\n    U,S,VT = la.svd(Y,full_matrices=False)\n    # project onto the first two principal components\n    Yhat = U[:,:2].dot(np.diag(S[:2]))\n    \n    # cluster 10 times, retaining the best\n    means = None\n    labs = None\n    inertia=np.inf\n    \n    for j in xrange(10):\n        m,l,i = kmeans(Yhat,3)\n        if i < inertia:\n            inertia=i\n            means=m\n            labs=l\n    \n    setosa = iris.target==0\n    versicolor = iris.target==1\n    virginica = iris.target==2\n    p1, p2 = Yhat[:,0], Yhat[:,1]\n    mrkr = []\n    for flower, m,n in zip([setosa,versicolor,virginica],['*','.','^'],['Setosa','Versicolor','Virginica']):\n        mr = plt.scatter([],[],color='k',marker=m,label=n)\n        mrkr.append(mr)\n        for i,c in enumerate(['cyan','red','green']):\n            msk = np.where(labs[flower]==i)[0]\n            if msk.any():\n                plt.scatter(p1[flower][msk],p2[flower][msk], marker=m, color=c)\n    mrkr.append(plt.scatter(means[:,0],means[:,1],marker='+',s=100,linewidths=2,label=\"Means\"))\n    \n    plt.legend(handles=mrkr, loc=2)\n    plt.ylim([-4,5])\n    plt.xlim([-4,4])\n    plt.xlabel(\"First Principal Component\")\n    plt.ylabel(\"Second Principal Component\")\n    plt.show()\n\ndef loadEarthquakes(path):\n    latitudes = []\n    longitudes = []\n    for i in xrange(1,7):\n        with open(path.format(i),'r') as f:\n            for line in f:\n                la = float(line[20:25])/1000\n                s = line[25]=='S'\n                lo = float(line[26:32])/1000\n                w = line[32]=='W'\n                latitudes.append(la*(-1)**s)\n                longitudes.append(lo*(-1)**w)\n    latitudes=np.array(latitudes)\n    longitudes = np.array(longitudes)\n    return latitudes,longitudes\n\ndef sphericalToEuclidean(r, theta, phi):\n    \"\"\"\n    theta and phi must be in radians!!\n    \"\"\"\n    eucl = np.zeros((len(theta),3))\n    eucl[:,0] = np.sin(phi)*np.cos(theta)\n    eucl[:,1] = np.sin(phi)*np.sin(theta)\n    eucl[:,2] = np.cos(phi)\n    return r*eucl\ndef euclideanToSpherical(pts):\n    \"\"\"\n    returns answers in radians.\n    \"\"\"\n    x = pts[:,0]\n    y = pts[:,1]\n    z = pts[:,2]\n    phi=np.arccos(z)\n    theta=np.arctan2(y,x)\n    return phi, theta\n    \ndef clusterEarthquakes(path):\n    # load in the data\n    latitudes, longitudes = loadEarthquakes(path)\n    # convert to euclidean coordinates\n    eucl = sphericalToEuclidean(1.,longitudes*np.pi/180,(90-latitudes)*np.pi/180)\n    # cluster 10 times, retaining best\n    best_i = np.inf\n    best_m = None\n    best_l = None\n    for j in xrange(10):\n        m,l,i = kmeans(eucl,15,normalize=True)\n        if i < best_i:\n            best_i=i\n            best_m = m\n            best_l = l\n    # get means back into latitude and longitude coordinates\n    m_phi, m_longitude = euclideanToSpherical(best_m)\n    m_latitude = np.pi/2-m_phi\n    return latitudes, longitudes, m_latitude, m_longitude, best_l\n    \ndef plotClusters(lats, longs, m_lats, m_longs, labs):\n    for i in xrange(15):\n        msk=labs==i\n        c=np.random.rand(3)\n        plt.scatter(longs[msk],lats[msk],marker='.',\n                    color=c)\n    plt.scatter(m_longs*180/np.pi,m_lats*180/np.pi,marker='+',s=100,linewidths=2,color='k')    \n    plt.show()\n", "meta": {"hexsha": "a35e7923fb6af6f3743f0d5a3829567739ff5f6d", "size": 4611, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/KMeans/solutions.py", "max_stars_repo_name": "jessicaleete/numerical_computing", "max_stars_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-10-18T19:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:12:38.000Z", "max_issues_repo_path": "Labs/KMeans/solutions.py", "max_issues_repo_name": "jessicaleete/numerical_computing", "max_issues_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/KMeans/solutions.py", "max_forks_repo_name": "jessicaleete/numerical_computing", "max_forks_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-14T16:07:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-20T09:05:06.000Z", "avg_line_length": 31.3673469388, "max_line_length": 108, "alphanum_fraction": 0.5788332249, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102580527664, "lm_q2_score": 0.9059898108646849, "lm_q1q2_score": 0.8764638367217819}}
{"text": "import numpy as np\nfrom numpy import linalg as LA\nfrom scipy import optimize\n\na = np.array([[1, 0], [0, 2]])\nb = np.array([1, -1])\n\ndef f(x):\n    return (lambda x : np.matmul(np.matmul(np.dot(0.5, x.transpose()), a), x) - np.matmul(x.transpose(), b) + 7)(x)\n\ndef g(x):\n    return (lambda x : np.matmul(a, x) - b)(x)\n\n# only pass np values - no internal checking\ndef quad_alpha(x, d):\n    return np.matmul(np.dot(-1, g(x)), d) / np.matmul(np.matmul(d.transpose(), a), d)\n\n# rank one correction formula\ndef rank_one(x0, max, tol):\n    # step 1\n    k = 0\n    x0 = np.array(x0)\n    H = np.array([[1, 0], [0, 1]])\n\n    while k < max: \n        # step 2\n        print(LA.norm(g(x0)))\n        if LA.norm(g(x0)) < tol:\n            return x0\n        else:\n            d = np.matmul(np.dot(-1, H), g(x0))\n\n        # step 3\n        alpha = quad_alpha(x0, d)\n        delta_x = np.dot(alpha, d)\n        x1 = x0 + delta_x\n        \n        # step 4\n        delta_x = np.dot(alpha, d)\n        delta_g = g(x1) - g(x0)\n\n        num = np.matmul((delta_x - np.matmul(H, delta_g)), (delta_x - np.matmul(H, delta_g)).transpose())\n        denom = np.matmul(delta_g.transpose(), (delta_x - np.matmul(H, delta_g)))\n    \n        H1 = H + (num / denom)\n        # loop back\n        H = H1\n        x0 = x1\n        k = k + 1\n\n# # SciPy offers BFGS as part of its library\n# print(optimize.fmin_bfgs(f, np.array([0, 0])), g)\n\n# # NOTE: x must be entered as a 2-D array\n# # there is a ZeroDivisionError increasing the error range\n# print(rank_one([0, 0], 10, 0.5)) ", "meta": {"hexsha": "dc2257924a84fe342bbfb6168a1d828e827d9570", "size": 1531, "ext": "py", "lang": "Python", "max_stars_repo_path": "optimization/rank_one.py", "max_stars_repo_name": "ahujaradhika/optimization", "max_stars_repo_head_hexsha": "c24ac4984117dcce2612e1270b2d645a9939f213", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optimization/rank_one.py", "max_issues_repo_name": "ahujaradhika/optimization", "max_issues_repo_head_hexsha": "c24ac4984117dcce2612e1270b2d645a9939f213", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimization/rank_one.py", "max_forks_repo_name": "ahujaradhika/optimization", "max_forks_repo_head_hexsha": "c24ac4984117dcce2612e1270b2d645a9939f213", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3392857143, "max_line_length": 115, "alphanum_fraction": 0.5427824951, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305381464927, "lm_q2_score": 0.9099070103134425, "lm_q1q2_score": 0.8764502192074834}}
{"text": "import numpy as np\n\n# Funciton\ndef f(x):\n    y = 1 / np.sqrt(2 * np.pi) * np.exp(-x ** 2 / 2)\n    return y\n\n# Adaptable Simpson Method\ndef adSimpson(a, b, tol):\n\n    # Simpson Rule for 2 intervals\n    def S(n, m):\n        value = (m-n)/6 * (f(n) + f(m) + 4*f(0.5*(n + m)))\n        return value\n\n    # Compute Integral with Simpson Rule in left half and right hald interval\n    Il, Ir = S(a, 0.5*(a+b)), S(0.5*(a+b), b)\n    # Compute Integral wth Simpson Rule\n    I = S(a, b)\n\n    # Integral Error\n    dI = np.abs((I - (Il+Ir)))/15\n\n    # Check If We Get the Desired Tolerance\n    if dI < tol:\n        I = Il + Ir\n    # If we Don't get it Reiterate\n    else:\n        Il = adSimpson(a, 0.5*(a+b), 0.5*tol)\n        Ir = adSimpson(0.5*(a+b), b, 0.5*tol)\n\n    I = Il + Ir\n\n    return I\n\nif __name__ == \"__main__\":\n    print('\\nComputed with Adaptable Simpson Method:')\n    print(f'\\tI = {adSimpson(-5, 5, 0.001):.8f}')", "meta": {"hexsha": "2f0b0445bf5c87c7a54302609deacc8270705b91", "size": 913, "ext": "py", "lang": "Python", "max_stars_repo_path": "Integration/Adaptable-Simpson-Method.py", "max_stars_repo_name": "AlexTsagas/Computational-Physics", "max_stars_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Integration/Adaptable-Simpson-Method.py", "max_issues_repo_name": "AlexTsagas/Computational-Physics", "max_issues_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Integration/Adaptable-Simpson-Method.py", "max_forks_repo_name": "AlexTsagas/Computational-Physics", "max_forks_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0263157895, "max_line_length": 77, "alphanum_fraction": 0.543263965, "include": true, "reason": "import numpy", "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407168145568, "lm_q2_score": 0.9005297961287784, "lm_q1q2_score": 0.876432264297239}}
{"text": "\"\"\"\r\nCourse: ME/MF F342 Computer Aided Design\r\nAuthor: Bhavya Bhatia\r\n\r\nTopic: Bsplines\r\n\r\nDescription:\r\n-------------\r\nThe Bspline functions can take the degree and control vectors to return a set of coordinates which plot the actual bspline curve.\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport scipy.interpolate as si\r\n\r\ncv = np.array([[ 50.,  25.],\r\n   [ 59.,  12.],\r\n   [ 50.,  10.],\r\n   [ 57.,   2.],\r\n   [ 40.,   4.],\r\n   [ 40.,   14.]])\r\n\r\ndef bspline(cv, n=100, degree=3, periodic=False):\r\n    \"\"\" \r\n    Parameters :\r\n    ------------\r\n    cv : Array ov control vertices\r\n    n  : Number of samples to return\r\n    degree: Curve degree\r\n    periodic: True - Curve is closed\r\n              False - Curve is open\r\n    Returns :\r\n    ---------\r\n    Returns array of x,y coordinates of the spline, which can be used to plot bspline graphs usin Matplotlib\r\n\r\n    \"\"\"\r\n\r\n    # If periodic, extend the point array by count+degree+1\r\n    cv = np.asarray(cv)\r\n    count = len(cv)\r\n\r\n    if periodic:\r\n        factor, fraction = divmod(count+degree+1, count)\r\n        cv = np.concatenate((cv,) * factor + (cv[:fraction],))\r\n        count = len(cv)\r\n        degree = np.clip(degree,1,degree)\r\n\r\n    # If opened, prevent degree from exceeding count-1\r\n    else:\r\n        degree = np.clip(degree,1,count-1)\r\n\r\n\r\n    # Calculate knot vector\r\n    kv = None\r\n    if periodic:\r\n        kv = np.arange(0-degree,count+degree+degree-1,dtype='int')\r\n    else:\r\n        kv = np.concatenate(([0]*degree, np.arange(count-degree+1), [count-degree]*degree))\r\n\r\n\r\n    # Calculate query range\r\n    u = np.linspace(periodic,(count-degree),n)\r\n\r\n    #print(u)\r\n\r\n    # Calculate result\r\n    return np.array(si.splev(u, (kv,cv.T,degree))).T\r\n\r\n'''\r\nExample :\r\n---------\r\n\r\nfrom gbot.bsplines import bspline\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\ncolors = ('b', 'g', 'r', 'c', 'm', 'y', 'k')\r\n\r\ncv = np.array([[ 50.,  25.],\r\n   [ 59.,  12.],\r\n   [ 50.,  10.],\r\n   [ 57.,   2.],\r\n   [ 40.,   4.],\r\n   [ 40.,   14.]])\r\n\r\nplt.plot(cv[:,0],cv[:,1], 'o-', label='Control Points')\r\n\r\nd = 4\r\np = bspline(cv,n=100,degree=4,periodic=False)\r\nx,y = p.T\r\nplt.plot(x,y,'k-',label='Degree %s'%d,color=colors[d%len(colors)])\r\n\r\nplt.minorticks_on()\r\nplt.legend()\r\nplt.xlabel('x')\r\nplt.ylabel('y')\r\nplt.xlim(35, 70)\r\nplt.ylim(0, 30)\r\nplt.gca().set_aspect('equal', adjustable='box')\r\nplt.show()\r\n\r\n\r\nOut : Matplotlib figure \r\n'''\r\n\r\n########################################################################\r\n########################################################################\r\n# End of File", "meta": {"hexsha": "adaa2ebd06a696637ca24217676d65de9e8099d5", "size": 2557, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/bsplines.py", "max_stars_repo_name": "bhvya2603/Geometric-Boolean-Operations-and-Transformations", "max_stars_repo_head_hexsha": "f747f7462cdf3bc51be47ae78029a1d6e1fedfa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-31T11:54:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T11:54:26.000Z", "max_issues_repo_path": "tests/bsplines.py", "max_issues_repo_name": "bhvya2603/Geometric-Boolean-Operations-and-Transformations", "max_issues_repo_head_hexsha": "f747f7462cdf3bc51be47ae78029a1d6e1fedfa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/bsplines.py", "max_forks_repo_name": "bhvya2603/Geometric-Boolean-Operations-and-Transformations", "max_forks_repo_head_hexsha": "f747f7462cdf3bc51be47ae78029a1d6e1fedfa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8971962617, "max_line_length": 130, "alphanum_fraction": 0.5342197888, "include": true, "reason": "import numpy,import scipy", "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889437, "lm_q2_score": 0.914900963114118, "lm_q1q2_score": 0.876394863606651}}
{"text": "# Behnam Asadi \n# http://ros-developer.com\n# To see the function that we are working on visit:\n# http://ros-developer.com/2017/05/07/gradient-descent-method-for-finding-the-minimum/\n# or simply put the following latex code in a latex doc:\n# $$ z= -( 4 \\times e^{- ( (x-4)^2 +(y-4)^2 ) }+ 2 \\times e^{- ( (x-2)^2 +(y-2)^2 ) } )$$\n\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n\ndef objective_function(x,y):\n    z=-( 4*np.exp(-(x-4)**2 - (y-4)**2)+2*np.exp(-(x-2)**2 - (y-2)**2) )\n    return z\n\n\ndef f_prim(x,y):\n    f_x=-( (-2)*(x-4)*4*np.exp(-(x-4)**2 - (y-4)**2)    +   (-2)*(x-2)*2*np.exp(-(x-2)**2 - (y-2)**2) )\n    f_y=-( (-2)*(y-4)*4*np.exp(-(x-4)**2 - (y-4)**2)    +   (-2)*(y-2)*2*np.exp(-(x-2)**2 - (y-2)**2) )\n    return [f_x,f_y]\n\n \nx = np.linspace(-2,10,200)\ny = np.linspace(-2,10,200)\n\nX, Y = np.meshgrid(x,y)\n\nZ=objective_function(X,Y)\n\n\n#Make a 3D plot\nfig = plt.figure()\nax = fig.gca(projection='3d')\nax.plot_surface(X, Y, Z,linewidth=0,cmap='coolwarm')\n\nax.set_xlabel('X axis')\nax.set_ylabel('Y axis')\nax.set_zlabel('Z axis')\n\n\nX_old=-2\nY_old=0\n\n\n# The starts point for the algorithm:\nX_new=4\nY_new=2.2\n\n# step size\nepsilon=0.1\n\n# stop criteria\nprecision = 0.00001\n\n\n\nx_path_to_max=[]\ny_path_to_max=[]\nz_path_to_max=[]\n\n\n\nwhile np.sqrt( (X_new-X_old)**2 + (Y_new-Y_old)**2 ) > precision:\n    X_old=X_new\n    Y_old=Y_new\n    \n    #[X_new,Y_new]=f_prim(X_new,Y_new)\n    #print f_prim(X_new,Y_new)\n    x_path_to_max.append(X_new )\n    y_path_to_max.append(Y_new )\n    z=objective_function(X_new,Y_new)\n    z_path_to_max.append(z)\n    \n    ret_val=f_prim(X_old,Y_old)\n    X_new=X_old-epsilon*ret_val[0]\n    Y_new=Y_old-epsilon*ret_val[1]\n#    print X_new\n#    print Y_new\n    \n    \n\nline1=plt.plot(x_path_to_max,y_path_to_max,z_path_to_max)\nplt.setp(line1,color='g',linewidth=0.5)\n\n\n#print X_new\n#print Y_new\nplt.show()\n\n\n", "meta": {"hexsha": "3e4e896c3c8ef72f39d95b767c5c9331a14f92d5", "size": 1881, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/gradient_descent.py", "max_stars_repo_name": "behnamasadi/gradient_descent", "max_stars_repo_head_hexsha": "a420a85e00664c2bc130053d75e21b87bee2d164", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gradient_descent.py", "max_issues_repo_name": "behnamasadi/gradient_descent", "max_issues_repo_head_hexsha": "a420a85e00664c2bc130053d75e21b87bee2d164", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gradient_descent.py", "max_forks_repo_name": "behnamasadi/gradient_descent", "max_forks_repo_head_hexsha": "a420a85e00664c2bc130053d75e21b87bee2d164", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2258064516, "max_line_length": 103, "alphanum_fraction": 0.6236044657, "include": true, "reason": "import numpy", "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.9161096198879968, "lm_q1q2_score": 0.8763817933336177}}
{"text": "import math\nimport sympy as sp\nfrom sympy.abc import x\n\n\ndef lagrange_interpolation(t, y):\n    \"\"\" Lagrange Interpolation Polinomial\n\n    Args:\n        t: list/ndarray, the interpolation points\n        y: list/ndarray, the values of the function at every t\n\n    Returns:\n        L: symbol object, Lagrange interpolation Polinomial \n    \"\"\"\n    # the number of the points\n    n = len(t)\n\n    # Lagrange interpolation polinomial \n    L = 0\n    for i in range(n):\n        # the base function of Lagrange interpolation polinomial\n        l = y[i]\n        for j in range(n):\n            if i == j:\n                continue\n            else:\n                l *= (x - t[j])/(t[i] - t[j])\n        L += l\n\n    return sp.simplify(L)\n\n\nif __name__ == '__main__':\n    # the interpolation points(degrees)\n    t = [11, 12, 13]\n    # the interpolation points(radians)\n    t = list(map(math.radians, t))\n    y = [0.190809, 0.207912, 0.224951] \n    L = lagrange_interpolation(t, y)\n    print(f\"The Lagrange interpolation polinomial is L = {L}\")\n    # calculate the value of sin11.5 by Lagrange interpolation\n    x0_deg = 11.5\n    x0_rad = math.radians(x0_deg)\n    true_value = math.sin(x0_rad)\n    pre_value = L.subs(x, x0_rad)\n    print(f\"The predict value of sin{x0_deg} is {pre_value:.7f}\")\n    print(f\"The true value of sin{x0_deg} is {true_value:.7f}\")\n    print(f\"The error is {math.fabs(true_value - pre_value):.7f}\")\n\n", "meta": {"hexsha": "99a0b34ab6438902425464b06e172537d4028f7a", "size": 1410, "ext": "py", "lang": "Python", "max_stars_repo_path": "InterpolationAndFitting/lagrange_interpolation.py", "max_stars_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_stars_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "InterpolationAndFitting/lagrange_interpolation.py", "max_issues_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_issues_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "InterpolationAndFitting/lagrange_interpolation.py", "max_forks_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_forks_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6470588235, "max_line_length": 66, "alphanum_fraction": 0.609929078, "include": true, "reason": "import sympy,from sympy", "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724487, "lm_q2_score": 0.9161096112990285, "lm_q1q2_score": 0.876381787382391}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef logistic_map(r, x_0, n):\n    final_x = x_0\n\n    for step in range(n):\n        final_x = (4 * r) * final_x * (1 - final_x)\n\n    return final_x\n\n\ndef bifurcation_diagram(r_start, r_end, r_samples, sample_numbers, max_n):\n    r_s = np.linspace(r_start, r_end, r_samples)\n    x_0_s = np.random.rand(sample_numbers)\n    x_r_s = np.zeros((r_samples, sample_numbers))\n\n    for r_index, r in enumerate(r_s):\n        x_r_s[r_index] = logistic_map(r, x_0_s, max_n)\n\n    data = {\n        'r_start': r_start,\n        'r_end': r_end,\n        'r_samples': r_samples,\n        'sample_numbers': sample_numbers,\n        'max_n': max_n,\n        'x_r_s': x_r_s\n    }\n    file_name = f'data/q4_{r_start}_{r_end}_{r_samples}_{sample_numbers}_{max_n}.npy'\n    np.save(file_name, data)\n\n    return file_name\n\n\ndef show(file_name, fig_width = 10, fig_height=5, r_lim=None, x_lim=None, show_x_m=False, save=True):\n    data = np.load('data/' + file_name, allow_pickle=True).tolist()\n    r_start = data['r_start']\n    r_end = data['r_end']\n    r_samples = data['r_samples']\n    sample_numbers = data['sample_numbers']\n    max_n = data['max_n']\n    x_r_s = data['x_r_s']\n\n    r_lim_start = r_start if r_lim is None else r_lim[0]\n    r_lim_end = r_end if r_lim is None else r_lim[1]\n    r_lim_ratio = (r_lim_end - r_lim_start) / 1\n\n    r_s = np.linspace(r_start, r_end, r_samples)\n    ones = 4 * np.ones(sample_numbers)\n\n    plt.figure(figsize=(fig_width, fig_height))\n    for r_index, r in enumerate(r_s):\n        plt.plot(r * ones, x_r_s[r_index], linestyle='', marker='.', color='black',\n                 markersize=133 * fig_width / r_samples * r_lim_ratio)\n\n    if show_x_m:\n        plt.axhline(0.5)\n    if r_lim is not None:\n        plt.xlim(r_lim)\n    if x_lim is not None:\n        plt.ylim(x_lim)\n    plt.xlabel(r'$r$')\n    plt.ylabel(r'$x$')\n    if save:\n        plt.savefig(f'images/q4_{r_lim_start}_{r_lim_end}_{r_samples}_{sample_numbers}_{max_n}.jpg')\n    plt.show()\n\n\nif __name__ == \"__main__\":\n    file_name = bifurcation_diagram(0, 1, 10000, 100, 10000)\n    show(file_name=file_name, fig_height=5, fig_width=10)\n", "meta": {"hexsha": "d7c1b35e7307f934ca74c769be3b0371433a5d0c", "size": 2156, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW8/q4.py", "max_stars_repo_name": "sina-moammar/2020-Fall-Computational-Physics", "max_stars_repo_head_hexsha": "f03e95b0a97022b628175fd06c301aecfdcf60af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW8/q4.py", "max_issues_repo_name": "sina-moammar/2020-Fall-Computational-Physics", "max_issues_repo_head_hexsha": "f03e95b0a97022b628175fd06c301aecfdcf60af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW8/q4.py", "max_forks_repo_name": "sina-moammar/2020-Fall-Computational-Physics", "max_forks_repo_head_hexsha": "f03e95b0a97022b628175fd06c301aecfdcf60af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5342465753, "max_line_length": 101, "alphanum_fraction": 0.6433209647, "include": true, "reason": "import numpy", "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.9161096067182449, "lm_q1q2_score": 0.8763817841328939}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Primera parte\n\n# Soluciones a los ejercicios de la seccion 6.2.5 \n# del libro A Survey of Computational Physics Introductory Computational Science\n# de Landau, Paez, Bordeianu (Python Multimodal eTextBook Beta4.0)\n\n#1. Write a double-precision program to integrate an arbitrary function numerically \n# using the trapezoid rule, the Simpson rule, and Gaussian quadrature.\ndef integra(f, a, b, n_points=10, metodo=\"trapecio\"):\n    # Genera siempre un numero impar de puntos\n    if n_points%2 == 0:\n        n_points = n_points + 1\n\n    if metodo==\"trapecio\":\n        x = np.linspace(a, b, n_points)\n        h = x[1] - x[0]\n        w = np.ones(n_points) * h\n        w[0] = h/2\n        w[-1] = h/2\n    elif metodo==\"simpson\":\n        x = np.linspace(a, b, n_points)\n        h = x[1] - x[0]\n        w = np.ones(n_points) \n        ii = np.arange(n_points)\n        w[ii%2!=0] = 4.0*h/3.0\n        w[ii%2==0] = 2.0*h/3.0\n        w[0] = h/3\n        w[-1] = h/3\n    elif metodo==\"cuadratura\":\n        y, wprime = np.polynomial.legendre.leggauss(n_points)\n        x = 0.5*(b+a) + 0.5*(b-a)*y\n        w = 0.5*(b-a)*wprime\n    else:\n        print('metodo no implementado')\n        x = np.zeros(n_points)\n        y = np.zeros(n_points)\n\n    return np.sum(f(x)*w)\n\ndef func(x):\n    return np.sin(x)\n\ndef error(x):\n    return np.abs(2-x)/2\n\n# 2 Compute the relative error (epsilon=abs(numerical-exact)/exact) in each case. \n# Present your data in tabular form for N=2,10,20,40,80,160\n\nN = [2,10,20,40,80,160]\nprint(\"Primera Parte\")\nout = open(\"tabla_resultados.dat\", \"w\")\nprint(\"# N\\t e_T\\t e_S \\t e_G\")\nfor n_points in N:\n    a = integra(func, 0, np.pi, n_points=n_points, metodo=\"trapecio\")\n    b = integra(func, 0, np.pi, n_points=n_points, metodo=\"simpson\")\n    c = integra(func, 0, np.pi, n_points=n_points, metodo=\"cuadratura\")\n    print(\"{:d}\\t {:.1e} {:.1e} {:.1e}\".format(n_points, error(a), error(b), error(c)))\n    out.write(\"{:d}\\t {:.1e} {:.1e} {:.1e}\\n\".format(n_points, error(a), error(b), error(c)))\nout.close()\nprint(\"\")\n\n# 3 Make a log-log plot of relative error versus N\ndata = np.loadtxt(\"tabla_resultados.dat\")\nplt.figure()\nplt.plot(data[:,0], data[:,1], label=\"Trapecio\")\nplt.plot(data[:,0], data[:,2], label=\"Simpson\")\nplt.plot(data[:,0], data[:,3], label=\"Cuadratura\")\n\nplt.xlabel('N')\nplt.ylabel('|error|')\nplt.loglog()\nplt.legend()\nplt.savefig(\"loglogplot.png\")\n\n\n# 4. Use your plot or table to estimate the power-law dependence of the error on N and\n# to determine the nuber of decimal places of precision.\n\nfor i,m in zip([1,2,3],[\"Trapecio\", \"Simpson\", \"Cuadratura\"]):\n    power_law = (np.log(data[2,i]) - np.log(data[0,i]))/(np.log(data[2,0]) - np.log(data[0,0]))\n    decimal_places = -np.log10(data[-1,i])\n    print(\"Metodo {}\".format(m))    \n    print(\"\\t Power Law: {:.1f}\".format(power_law))\n    print(\"\\t Decimal Places: {:d}\".format(int(decimal_places)))\n\nprint(\"\")\n\n# Segunda parte.\n# Calcule la integral de la función Gamma (https://en.wikipedia.org/wiki/Gamma_function) para z>1. Imprima los resultados Gamma(2), Gamma(3) y Gamma(4). \n\ndef gamma(z, n_points=20):\n    def fun(z, x):\n        return x**(z-1) * np.exp(-x)\n    # Usando la formula de transformacion (6.36) del libro.\n    y, wprime = np.polynomial.legendre.leggauss(n_points)\n    x = (1+y)/(1-y)\n    w = wprime * 2/(1-y)**2\n    return np.sum(fun(z,x)*w)\nprint(\"Segunda Parte\")\nprint(\"Gamma(2): {}\\nGamma(3): {}\\nGamma(4): {}\\t\".format(gamma(2), gamma(3), gamma(4)))\n\n\ndef gamma2(z, n_points=20):\n    # Usando el cambio de variable u = exp(-x)\n    def fun(z,u):\n        return (-np.log(u))**(z-1)    # diverge para u=0\n    a = 0.0\n    b = 1.0\n    y, wprime = np.polynomial.legendre.leggauss(n_points)\n    x = 0.5*(b+a) + 0.5*(b-a)*y\n    w = 0.5*(b-a)*wprime\n    return np.sum(fun(z,x)*w)\nprint(\"Segunda Parte\")\nprint(\"Gamma(2): {}\\nGamma(3): {}\\nGamma(4): {}\\t\".format(gamma2(2), gamma2(3), gamma2(4)))\n\n", "meta": {"hexsha": "159f359c81326b24e2f90c684b518c4fb6d361ea", "size": 3939, "ext": "py", "lang": "Python", "max_stars_repo_path": "ejercicios/09/JaimeForero_Solucion9.py", "max_stars_repo_name": "oscarochoa1/FISI2028-201910", "max_stars_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-03T04:27:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T18:50:41.000Z", "max_issues_repo_path": "ejercicios/09/JaimeForero_Solucion9.py", "max_issues_repo_name": "oscarochoa1/FISI2028-201910", "max_issues_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ejercicios/09/JaimeForero_Solucion9.py", "max_forks_repo_name": "oscarochoa1/FISI2028-201910", "max_forks_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-01-23T10:44:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-04T00:05:40.000Z", "avg_line_length": 33.1008403361, "max_line_length": 153, "alphanum_fraction": 0.6123381569, "include": true, "reason": "import numpy", "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542794197471, "lm_q2_score": 0.9136765298777718, "lm_q1q2_score": 0.8763567536376492}}
{"text": "#!/usr/bin/env python3\n\"\"\"\nClustering Module\n\"\"\"\nimport numpy as np\nkmeans = __import__('1-kmeans').kmeans\nvariance = __import__('2-variance').variance\n\n\ndef optimum_k(X, kmin=1, kmax=None, iterations=1000):\n    \"\"\"\n    Tests for the optimum number of clusters by variance:\n\n    X is a numpy.ndarray of shape (n, d) containing the data set\n    kmin is a positive integer containing the minimum number of clusters to\n    check for (inclusive)\n    kmax is a positive integer containing the maximum number of clusters to\n    check for (inclusive)\n    iterations is a positive integer containing the maximum number of\n    iterations for K-means\n    This function should analyze at least 2 different cluster sizes\n    You may use at most 2 loops\n\n    Returns: results, d_vars, or None, None on failure\n        results is a list containing the outputs of K-means for each cluster\n        size\n        d_vars is a list containing the difference in variance from the\n        smallest cluster size for each cluster size\n    \"\"\"\n    if type(X) is not np.ndarray or len(X.shape) != 2:\n        return (None, None)\n    if type(kmin) is not int:\n        return (None, None)\n    if type(iterations) is not int:\n        return (None, None)\n    if kmax is not None and type(kmax) is not int:\n        return (None, None)\n    n, _ = X.shape\n    if kmax is None:\n        kmax = n\n    if kmin <= 0 or kmax <= 0 or iterations <= 0:\n        return (None, None)\n    if kmin >= kmax:\n        return (None, None)\n\n    d_vars = []\n    results = []\n    for i in range(kmin, kmax + 1):\n        center, klss = kmeans(X, i, iterations)\n        results.append((center, klss))\n        if i == kmin:\n            kmin_var = variance(X, center)\n        cvar = variance(X, center)\n        d_vars.append(kmin_var - cvar)\n    return (results, d_vars)\n", "meta": {"hexsha": "97bf2f4b75139d55d1b5d2acbcb2db79fa91e8ea", "size": 1812, "ext": "py", "lang": "Python", "max_stars_repo_path": "unsupervised_learning/0x01-clustering/3-optimum.py", "max_stars_repo_name": "kyeeh/holbertonschool-machine_learning", "max_stars_repo_head_hexsha": "8e4894c2b036ec7f4750de5bf99b95aee5b94449", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unsupervised_learning/0x01-clustering/3-optimum.py", "max_issues_repo_name": "kyeeh/holbertonschool-machine_learning", "max_issues_repo_head_hexsha": "8e4894c2b036ec7f4750de5bf99b95aee5b94449", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unsupervised_learning/0x01-clustering/3-optimum.py", "max_forks_repo_name": "kyeeh/holbertonschool-machine_learning", "max_forks_repo_head_hexsha": "8e4894c2b036ec7f4750de5bf99b95aee5b94449", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3571428571, "max_line_length": 76, "alphanum_fraction": 0.642384106, "include": true, "reason": "import numpy", "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.927363299661721, "lm_q1q2_score": 0.8763534097012791}}
{"text": "from fractions import Fraction\nimport numpy as np\n\n# These functions are written based on the exercises in \n# Xanadu Quantum Codebook nodes S.3 and S.4\n# https://codebook.xanadu.ai\n\ndef fractional_binary_to_float(sample):\n    \"\"\"Convert an n-bit sample [k1, k2, ..., kn] to a floating point \n    value using fractional binary representation,\n    \n        k = (k1 / 2) + (k2 / 2 ** 2) + ... + (kn / 2 ** n)\n        \n    Args:\n        sample (list[int] or array[int]): A list or array of bits, e.g.,\n            the sample output of quantum circuit.\n            \n    Returns:\n        float: The floating point value corresponding computed from the\n        fractional binary representation.\n    \"\"\"\n    return np.sum(\n        [int(sample[bit]) / 2 ** (bit + 1) for bit in range(len(sample))]\n    )\n\n\n\ndef phase_to_order(phase, max_denominator):\n    \"\"\"Estimating which integer values divide to produce a float.\n    \n    Given some floating-point phase, estimate integers s, r such\n    that s / r = phase, where r is no greater than some specified value.\n    \n    Args:\n        phase (float): Some fractional value (here, will be the output\n            of running QPE).\n        max_denominator (int): The largest r to be considered when looking\n            for s, r such that s / r = phase.\n            \n    Returns:\n        int: The estimated value of r.\n    \"\"\"\n    s_over_r = Fraction(phase)\n    return s_over_r.limit_denominator(max_denominator).denominator\n\n\ndef get_U_Na(N, a):\n    \"\"\"Computes the unitary matrix U_(N, a) used in the order-finding\n    portion of Shor's algorithm.\n    \n    U_(N, a) multiples a computational basis state by a modulo N, i.e.,\n        U_(N, a) |k> = |ak mod N>\n        \n    In Shor's algorithm, we try to find its order, i.e., the smallest\n    m such that \n        U_(N, a)^m |k> = |k mod N> = |k>\n    \n    Args:\n        N (int): The modulus. In Shor's algorithm, this is the number \n            we are trying to find the prime factors of.\n        a (int): The candidate value a which we are testing to try and\n            find a non-trivial square root (which will then allow us to\n            recover the prime factors of N).\n            \n    Returns:\n        array[int]: The matrix representation U_(N, a).\n    \"\"\"    \n    # Compute size of the matrix; we need at least log2(N) qubits\n    # because we are looking at computational basis states modulo N\n    n_qubits = int(np.ceil(np.log2(N)))\n    \n    U_Na = np.zeros([2 ** n_qubits, 2 ** n_qubits])\n    \n    # U_Na is a permutation matrix; for each k < N, need to compute\n    # |l> = |a k mod N>, and then set the value of U_Na[l, k] = 1\n    for k in range(N):\n        U_Na[(k * a) % N, k] = 1\n\n    # We might have more basis states than we need, if N < 2 ** n_qubits\n    # so we set the remaining rows to identity rows\n    for extra in range(N, 2 ** n_qubits):\n        U_Na[extra, extra] = 1\n        \n    return U_Na", "meta": {"hexsha": "0181d6b96150256b3da4a62175de49fb52fb378f", "size": 2904, "ext": "py", "lang": "Python", "max_stars_repo_path": "demos/lecture12_helpers.py", "max_stars_repo_name": "annabellegrimes/CPEN-400Q", "max_stars_repo_head_hexsha": "044d521f8109567ec004a9c882898f9e2eb5a19e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2022-01-12T22:57:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T21:20:59.000Z", "max_issues_repo_path": "demos/lecture12_helpers.py", "max_issues_repo_name": "annabellegrimes/CPEN-400Q", "max_issues_repo_head_hexsha": "044d521f8109567ec004a9c882898f9e2eb5a19e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demos/lecture12_helpers.py", "max_forks_repo_name": "annabellegrimes/CPEN-400Q", "max_forks_repo_head_hexsha": "044d521f8109567ec004a9c882898f9e2eb5a19e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-02-04T07:48:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T21:40:06.000Z", "avg_line_length": 34.5714285714, "max_line_length": 74, "alphanum_fraction": 0.6074380165, "include": true, "reason": "import numpy", "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611631680358, "lm_q2_score": 0.9124361563100186, "lm_q1q2_score": 0.8762682483904611}}
{"text": "# -*- coding: UTF-8 -*-\nfrom __future__ import division\n\nimport numpy as np\n\nx = np.array([1, 2, 3])\ny = np.array([4, 5, 6])\n\nprint(x + y)  # elementwise addition     [1 2 3] + [4 5 6] = [5  7  9]\nprint(x - y)  # elementwise subtraction  [1 2 3] - [4 5 6] = [-3 -3 -3]\nprint(x * y)  # elementwise multiplication  [1 2 3] * [4 5 6] = [4  10  18]\nprint(x / y)  # elementwise divison         [1 2 3] / [4 5 6] = [0.25  0.4  0.5]\nprint(x ** 2)  # elementwise power  [1 2 3] ^2 =  [1 4 9]\n\n#  Dot Product\nprint(x.dot(y))  # dot product  1*4 + 2*5 + 3*6 = 32\n\n# T\nz = np.array([y, y ** 2])\nprint(len(z))  # number of rows of array # 2\nprint(z)\n# [[ 4  5  6]\n#  [16 25 36]]\nprint(z.shape)  # (2L, 3L)\nprint(z.T)\n# [[ 4 16]\n#  [ 5 25]\n#  [ 6 36]]\nprint(z.T.shape)  # (3L, 2L)\n\n# dtype\nprint(z.dtype)  # int32\n# convert data type to float\nz = z.astype('f')\nprint(z.dtype)  # float32\n", "meta": {"hexsha": "0fe37745f42e4f7004e29503b67e277d0c0f637f", "size": 874, "ext": "py", "lang": "Python", "max_stars_repo_path": "1_introduction/w1_python_fundamentals/3_numpy/2_numpy_operation.py", "max_stars_repo_name": "shijiansu/coursera-applied-data-science-with-python", "max_stars_repo_head_hexsha": "a0f2bbd0b9201805f26d18b73a25183cf0b3a0e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1_introduction/w1_python_fundamentals/3_numpy/2_numpy_operation.py", "max_issues_repo_name": "shijiansu/coursera-applied-data-science-with-python", "max_issues_repo_head_hexsha": "a0f2bbd0b9201805f26d18b73a25183cf0b3a0e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1_introduction/w1_python_fundamentals/3_numpy/2_numpy_operation.py", "max_forks_repo_name": "shijiansu/coursera-applied-data-science-with-python", "max_forks_repo_head_hexsha": "a0f2bbd0b9201805f26d18b73a25183cf0b3a0e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2777777778, "max_line_length": 80, "alphanum_fraction": 0.5377574371, "include": true, "reason": "import numpy", "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214480969029, "lm_q2_score": 0.9086178888906091, "lm_q1q2_score": 0.876199718381743}}
{"text": "import random\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nphi = lambda vec: np.sin(np.product(vec))\nh = lambda x: np.sqrt(1 + np.sin(np.product(x)) ** 2)\n\n\n# Section 1.1.5 - Analytical Evaluation\n\n# SubSection 1\ndef gradient_phi(vec: np.matrix):\n    grad_vec = np.matrix(np.array([[vec[1] * vec[2]], [vec[0] * vec[2]], [vec[0] * vec[1]]]), dtype=np.float128)\n    grad_vec = grad_vec.transpose()\n    return np.cos(np.product(vec)) * grad_vec\n\n\ndef hessian_phi(mat: np.matrix, vec: np.matrix):\n    nabla = np.zeros((3, 3))\n    nabla[0, 0] = (-((vec[1] * vec[2]) ** 2) * np.sin(np.product(vec)))\n    nabla[0, 1] = vec[2] * np.cos(np.product(vec)) - np.product(vec) * vec[2] * np.sin(np.product(vec))\n    nabla[0, 2] = vec[1] * np.cos(np.product(vec)) - np.product(vec) * vec[1] * np.sin(np.product(vec))\n    nabla[1, 0] = vec[2] * np.cos(np.product(vec)) - np.product(vec) * vec[2] * np.sin(np.product(vec))\n    nabla[1, 1] = (-((vec[0] * vec[2]) ** 2) * np.sin(np.product(vec)))\n    nabla[1, 2] = vec[0] * np.cos(np.product(vec)) - np.product(vec) * vec[0] * np.sin(np.product(vec))\n    nabla[2, 0] = vec[1] * np.cos(np.product(vec)) - np.product(vec) * vec[1] * np.sin(np.product(vec))\n    nabla[2, 1] = vec[0] * np.cos(np.product(vec)) - np.product(vec) * vec[0] * np.sin(np.product(vec))\n    nabla[2, 2] = (-((vec[0] * vec[1]) ** 2) * np.sin(np.product(vec)))\n    return mat.transpose() * nabla * mat\n\n\n# SubSection 2\ndef gradient_h(vec: np.matrix):\n    return 0.5 * phi(vec) / ((1 + (phi(vec) ** 2)) ** 0.5) \\\n           * gradient_phi(vec)\n\n\ndef hessian_h(vec: np.matrix):\n    # Calculating the 2nd derivative of h of phi\n    derivative = (np.cos(np.product(vec)) ** 2 -\n                  (1 + np.sin(np.product(vec)) ** 2) * np.sin(np.product(vec)) ** 2) / \\\n                 (1 + np.sin(np.product(vec)) ** 2) ** 1.5\n\n    return derivative * hessian_phi(np.matrix(np.identity(3)), vec)\n\n\n# Section 1.2.1 - Numerical Differentiation\n\ndef numerical_diff_gradient(func, vector: np.matrix, epsilon):\n    vec_len = vector.shape[0]\n    assert vector.shape[1] == 1\n    assert vec_len > 0\n    gradient = np.matrix(np.zeros((vec_len, 1)), dtype=np.float128)\n    for i in range(vec_len):\n        base_vector = np.matrix(np.zeros((vec_len, 1)), dtype=np.float128)\n        base_vector[i, 0] = 1\n        func_plus = func(vector + (epsilon * base_vector))\n        func_minus = func(vector - (epsilon * base_vector))\n        gradient[i, 0] = ((func_plus - func_minus) / (2 * epsilon))\n    return gradient\n\n\ndef numerical_diff_hessian(vec: np.matrix, epsilon, hess_phi=False, hess_h=False,):\n    vec_len = vec.shape[0]\n    assert vec.shape[1] == 1\n    assert vec_len > 0\n    hessian = np.matrix(np.zeros((vec_len, vec_len)), dtype=np.float128)\n    for i in range(vec_len):\n        base_vector = np.matrix(np.zeros((vec_len, 1)))\n        base_vector[i, 0] = 1\n        if hess_phi is True:\n            v1 = gradient_phi(vec + epsilon * base_vector)\n            v2 = gradient_phi(vec - epsilon * base_vector)\n        elif hess_h is True:\n            v1 = gradient_h(vec + epsilon * base_vector)\n            v2 = gradient_h(vec - epsilon * base_vector)\n        else:\n            return None\n        value = (v1 - v2)\n        hessian[0:vec_len, i] = value / (2 * epsilon)\n    return hessian\n\n\n# Section 1.3 - Comparison plot\ndef compare_grad():\n    vec = np.matrix(np.random.rand(3), dtype=np.float128).transpose()\n    A = np.matrix(np.random.rand(3, 3), dtype=np.float128)\n    epsilon = []\n    values = []\n    for i in range(61):\n        epsilon.append(2 ** -i)\n\n    # Comparison for f1 gradient\n    analytical_grad = gradient_phi(A * vec)\n    for i in range(61):\n        numerical_grad = numerical_diff_gradient(phi, A * vec, epsilon[i])\n        x = np.abs(analytical_grad - numerical_grad)\n        values.append(np.linalg.norm(x, np.inf))\n    show_plot(\"f1 gradient\", values)\n\n    # Comparison for f1 hessian\n    analytical_hessian = hessian_phi(A, vec)\n    values = []\n    for i in range(61):\n        numerical_hessian = numerical_diff_hessian(A * vec, epsilon[i], hess_phi=True)\n        x = np.abs(analytical_hessian - numerical_hessian)\n        values.append(np.linalg.norm(x, np.inf))\n    show_plot(\"f1 hessian\", values)\n\n    # Comparison for f2\n    analytical_grad = gradient_h(vec)\n    values = []\n    for i in range(61):\n        numerical_grad = numerical_diff_gradient(h, vec, epsilon[i])\n        x = np.abs(analytical_grad - numerical_grad)\n        y = max(x).item()\n        values.append(y)\n    show_plot(\"f2 gradient\", values)\n\n\ndef show_plot(str, y_axis):\n    fig = plt.figure()\n    ax = fig.add_subplot()\n    fig.subplots_adjust(top=0.85)\n    fig.suptitle(str, fontsize=14, fontweight='bold')\n    ax.set_xlabel('epsilon')\n    ax.set_ylabel('differentiation')\n    plt.plot(list(range(61)), y_axis)\n    plt.xscale(\"linear\")\n    plt.yscale(\"log\")\n    plt.show()\n\n\ncompare_grad()\n", "meta": {"hexsha": "1221825b2f1692a913f8b8f46e8d3ff261d4bf84", "size": 4885, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW1/HW1_Optimization.py", "max_stars_repo_name": "weaver20/NumericalOptimization", "max_stars_repo_head_hexsha": "1672745a34a588603e3f4249c4ae1d4b3c91fb53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW1/HW1_Optimization.py", "max_issues_repo_name": "weaver20/NumericalOptimization", "max_issues_repo_head_hexsha": "1672745a34a588603e3f4249c4ae1d4b3c91fb53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW1/HW1_Optimization.py", "max_forks_repo_name": "weaver20/NumericalOptimization", "max_forks_repo_head_hexsha": "1672745a34a588603e3f4249c4ae1d4b3c91fb53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9191176471, "max_line_length": 112, "alphanum_fraction": 0.611258956, "include": true, "reason": "import numpy", "num_tokens": 1440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347823646076, "lm_q2_score": 0.899121379297294, "lm_q1q2_score": 0.8761351455549244}}
{"text": "\"\"\"\ndemo_constrained_optimization_nonlinear_equality_constraints.py\n\nMinimize a (quadratic) function of two variables:\nMinimize f(X), where X = [x0, x1].T;\nX* is MIN;\n\nm = number of equality constraints;\nn = number of parameters;\n\nObjective function:\n    Minimize a (quadratic) function of two variables: f(X);\n    X = [x1, ..., xn].T is vector of variables;\n\nBox constraints:\n    X_lower = [x1_lower, ..., xn_lower].T; lower bounds for X;\n    X_upper = [x1_upper, ..., xn_upper].T; upper bounds for X;\n    \n(Non)linear equality constraints:\n    Subject to (non)linear equality constraints: h(X);\n    h(X) = [h1(X), ..., hn(X)].T is vector of constraints;\n    m < n;\n\nFirst order Lagrange algorithm\n\nLagrangian function:\nl(X, Lambda) = f(X) + Lambda.T @ h(X);\nLambda = [lambda1, ..., lambdan].T is vector of langrange multipliers;\n\nUpdate equation for X:\n    X = X_old + alpha * d;\n    alpha is step size (<<1);\n    d is direction:\n        d = - (Df(X_old) + Dh(X_old).T @ Lambda);\n        \nUpdate equation for Lambda:\n    Lambda = Lambda_old + beta * d;\n    beta is step size (<<1);\n    d is direction:\n        d = h(X_old);\n\nIf alpha and beta are small enough, the algorithm will converge to a fixed point, which satisfies the Lagrange condition.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom first_order_lagrangian_algorithm import first_order_lagrangian_algorithm\nfrom print_report import print_report\nfrom plot_progress_y import plot_progress_y\nfrom plot_progress_x import plot_progress_x\nimport time\n\nreg_coeff =10; # regularization coefficient\n# Minimize the following objective function:\n# X = [x0, x1].T;\n# f(X) = 1 / 2 * X.T @ Q @ X + X.T @ B + C + reg_coeff * X.T @ X;\nQ = np.array([[8, 2 * np.sqrt(2)], [2 * np.sqrt(2), 10]]);\nB = np.array([[3], [6]]);\nC = 24;\nfunc = lambda X : 1 / 2 * X.T @ Q @ X + X.T @ B + C + reg_coeff * X.T @ X; \nDy = lambda X : Q @ X + B + 2 * reg_coeff * X;\n\n# Box constraints:\nX_lower = np.array([[-20], [-20]]); # X lower bound   \nX_upper = np.array([[20], [20]]); # X upper bound \n\n# (Non)linear equality constraints:\n# h(X) = x1 * x2 - 20 = 0\nh = lambda X : X[0] * X[1] - 20; \nDh = lambda X : np.array([X[1], X[0]]);\n# Initial guess (subject to the equality constraints):\nX0 = np.array([[-50], [-0.4]]);   \nLambda0 = np.array([[0]]);\n\nfig = plt.figure();\nX_data = np.arange(-100, 100, 5);\nY_data = np.arange(-100, 100, 5);\nZ_data = np.zeros(shape = (X_data.size,Y_data.size));\nfor iX in range (X_data.size):\n    for iY in range (Y_data.size):\n        Z_data[iX][iY] = func(np.array([X_data[iX], Y_data[iY]]));\nX_data, Y_data = np.meshgrid(X_data, Y_data);\n\n# Plot the surface\nax = fig.add_subplot(1, 2, 1, projection ='3d')\nsurf = ax.plot_surface(X_data, Y_data, Z_data, cmap = cm.coolwarm,\n                       linewidth = 0, antialiased = False)\nax.set_xlabel('X')\nax.set_xlim(-100, 100)\nax.set_ylabel('Y')\nax.set_ylim(-100, 100)\nplt.title('Objective function: surface plot')\n\n# Plot the contour\nax = fig.add_subplot(1, 2, 2)\ncset = ax.contour(X_data, Y_data, Z_data, 50, cmap = cm.coolwarm);\nax.set_xlabel('X')\nax.set_xlim(-100, 100)\nax.set_ylabel('Y')\nax.set_ylim(-100, 100)\nplt.title('Objective function: contour plot');\nplt.show();\n\n# First order Lagrangian algorithm\nprint('***********************************************************************');\nprint('First order Lagrangian algorithm');\nN_iter_max = 10000;\ntolerance_x = 10e-6;\ntolerance_y = 10e-6;\noptions = {'tolerance_x' : tolerance_x, 'tolerance_y' : tolerance_y, 'N_iter_max' : N_iter_max, 'x_lower' : X_lower, 'x_upper' : X_upper};\nstart = time.time();\nX, report = first_order_lagrangian_algorithm(X0, Lambda0, func, Dy, Dh, h, options);\nend = time.time();\nprint_report(func, report);\n# Plot path to X* for Y\nalgorithm_name = 'First order Lagrangian algorithm';\nplot_progress_y(algorithm_name, report);\n# Plot path to X* for X\nplot_progress_x(X_data, Y_data, Z_data, algorithm_name, report);\nprint('Elapsed time [s]: %0.5f' % (end - start));\nprint('***********************************************************************\\n');", "meta": {"hexsha": "40dcfeed90842951874379326ba43caf3f7dc2b9", "size": 4182, "ext": "py", "lang": "Python", "max_stars_repo_path": "constrained_optimization_nonlinear_equality_constraints/demo_constrained_optimization_nonlinear_equality_constraints.py", "max_stars_repo_name": "almostdutch/numerical-optimization-algorithms", "max_stars_repo_head_hexsha": "cd6c1306cb04eccce62a74420323bda83058c1d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "constrained_optimization_nonlinear_equality_constraints/demo_constrained_optimization_nonlinear_equality_constraints.py", "max_issues_repo_name": "almostdutch/numerical-optimization-algorithms", "max_issues_repo_head_hexsha": "cd6c1306cb04eccce62a74420323bda83058c1d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-02T10:07:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-03T10:23:46.000Z", "max_forks_repo_path": "constrained_optimization_nonlinear_equality_constraints/demo_constrained_optimization_nonlinear_equality_constraints.py", "max_forks_repo_name": "almostdutch/numerical-optimization-algorithms", "max_forks_repo_head_hexsha": "cd6c1306cb04eccce62a74420323bda83058c1d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7258064516, "max_line_length": 138, "alphanum_fraction": 0.6480153037, "include": true, "reason": "import numpy", "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338123908151, "lm_q2_score": 0.9111797100118214, "lm_q1q2_score": 0.8761301003408241}}
{"text": "# -*- coding: utf-8 -*-\n#\n#  Activate Function Model\n#\n#  @auth whuang022ai\n#\n\nimport math\nimport numpy as np\nfrom abc import ABCMeta, abstractmethod\nimport matplotlib.pyplot as plt\nfrom enum import Enum\n\n\nclass Activate_Function_Type(Enum):\n\n    sigmoid = 'sigmoid'\n    tanh = 'tanh'\n    relu = 'relu'\n    leaky_relu = 'leaky-relu'\n    identity = 'identity'\n\n\nclass Activate_Function(metaclass=ABCMeta):\n\n    @abstractmethod\n    def f(self, x):\n        pass\n\n    @abstractmethod\n    def df(self, y):\n        pass\n\n    def plot_fx_dfx(self, min, max, inter, title):\n\n        x = np.arange(min, max, inter)\n        f_vect = np.vectorize(self.f)\n        df_vect = np.vectorize(self.df)\n        plt.figure(title)\n        plt.subplot(211)\n        plt.ylabel('f(x)')\n        plt.plot(x, f_vect(x))\n        plt.grid(True)\n        plt.subplot(212)\n        plt.ylabel('d f(x)')\n        plt.plot(x, df_vect(f_vect(x)), color='red',\n                 linewidth=1.0, linestyle='--')\n        plt.grid(True)\n        plt.show()\n\n    @abstractmethod\n    def show_plot(self):\n        pass\n\n\nclass Activate_Function_Sigmoid(Activate_Function):\n    # ref: https://timvieira.github.io/blog/post/2014/02/11/exp-normalize-trick/\n    def f(self,x):\n\n        if x >= 0:\n            z = np.exp(-x)\n            return 1 / (1 + z)\n        else:\n            z = np.exp(x)\n            return z / (1 + z)\n\n    def df(self, y):\n        return y*(1-y)\n\n    def show_plot(self):\n        self.plot_fx_dfx(-5.0, 5.0, 0.1, 'The Sigmoid Function')\n\n\nclass Activate_Function_Tanh(Activate_Function):\n\n    def f(self, x):\n        return np.tanh(x)\n\n    def df(self, y):\n        return 1-y**2\n\n    def show_plot(self):\n        self.plot_fx_dfx(-5.0, 5.0, 0.1, 'The Tanh Function')\n\n\nclass Activate_Function_Relu(Activate_Function):\n\n    def __init__(self):\n        self.lrelu = Activate_Function_LeakyRelu()\n        self.lrelu.alpha = 0.0\n\n    def f(self, x):\n        return self.lrelu.f(x)\n\n    def df(self, y):\n        return self.lrelu.df(y)\n\n    def show_plot(self):\n        self.plot_fx_dfx(-5.0, 5.0, 0.01, 'The ReLU Function')\n\n\nclass Activate_Function_LeakyRelu(Activate_Function):\n\n    def __init__(self):\n        self.alpha = 0.1\n\n    def f(self, x):\n        if x > 0:\n            return x\n        else:\n            return (self.alpha*x)\n\n    def df(self, y):\n        if y > 0:\n            return 1.0\n        else:\n            return self.alpha\n\n    def show_plot(self):\n        self.plot_fx_dfx(-5.0, 5.0, 0.01, 'The Leaky ReLU Function')\n\n\nclass Activate_Function_Identity(Activate_Function):\n\n    def f(self, x):\n        return x\n\n    def df(self, y):\n        return 1.0\n\n    def show_plot(self):\n        self.plot_fx_dfx(-5.0, 5.0, 0.01, 'The Identity Function')\n\nclass Activate_Function_Generator():\n\n    def __init__(self, name):\n\n        if isinstance(name, Activate_Function_Type):\n            name = str(name.value)\n            self.__genfromname(name)\n        else:\n            self.__genfromname(name)\n\n    def __genfromname(self, name):\n\n        if name == 'sigmoid':\n            self.get = Activate_Function_Sigmoid()\n        elif name == 'tanh':\n            self.get = Activate_Function_Tanh()\n        elif name == 'relu':\n            self.get = Activate_Function_Relu()\n        elif name == 'leaky-relu':\n            self.get = Activate_Function_LeakyRelu()\n        elif name == 'identity':\n            self.get = Activate_Function_Identity()", "meta": {"hexsha": "a6bb83d4c12b386eec7bd2731a84c0a7c064507c", "size": 3427, "ext": "py", "lang": "Python", "max_stars_repo_path": "actf.py", "max_stars_repo_name": "whuang022ai/AI-Tutorial-Multilayer-Perceptron-Numpy-Batch-Version", "max_stars_repo_head_hexsha": "dd74088f21a0d2ff29f1893f9c14b5000a5e1ba0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-10T21:25:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-10T21:25:52.000Z", "max_issues_repo_path": "actf.py", "max_issues_repo_name": "whuang022ai/AI-Tutorial-Multilayer-Perceptron-Numpy-Batch-Version", "max_issues_repo_head_hexsha": "dd74088f21a0d2ff29f1893f9c14b5000a5e1ba0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "actf.py", "max_forks_repo_name": "whuang022ai/AI-Tutorial-Multilayer-Perceptron-Numpy-Batch-Version", "max_forks_repo_head_hexsha": "dd74088f21a0d2ff29f1893f9c14b5000a5e1ba0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1096774194, "max_line_length": 80, "alphanum_fraction": 0.574263204, "include": true, "reason": "import numpy", "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338090839607, "lm_q2_score": 0.9111797033789887, "lm_q1q2_score": 0.8761300909499924}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n#\n# test the fourier transform and inverse transform in the numpy.fft library\n# define a simple function, compute and plot its fft,\n# then compute and plot the inverse fft of the fft\n# this is a good way to test the fft normalization\n#\npathout1='/Users/riser/Desktop/ocean.569A/fft.test.out.jpg'\npathout2='/Users/riser/Desktop/ocean.569A/inverse.fft.test.out.jpg'\n#\n# set the number of points and number of frequencies\n#\nnn=1000\nmm=int(nn/2+1)\n#\n# define the arrays\n#\ntt0=np.zeros(nn)\ntt1=np.zeros(nn)\nyy0=np.zeros(nn)\nyy1=np.zeros(nn)\nzz=np.zeros(mm)\nfreq_rad=np.zeros(mm)\nfreq=np.zeros(mm)\n#\n# define some constants\n#\npi=np.pi\namp=1.0\nn_fac=50.\nomega0=2.*pi/nn\n#\n# set the time and amplitude coordinates\n# \nfor i in range(0,nn):\n    tt0[i]=i # t\n    yy0[i]=amp*np.sin(2.*pi*tt0[i]/n_fac)    #y_sin\n#\n# set the frequency values\n#\nfor i in range(0,mm):\n    freq_rad[i]=i*omega0\n    freq[i]=freq_rad[i]/(2.*pi)\n#\n# carry out the fourier transform\n# convert from real-imaginary parts to amplitude and phase\n#\nzz=np.fft.rfft(yy0,n=nn)/nn\nzz_real=zz.real\nzz_imag=zz.imag\nzz_mag=np.sqrt(zz_real**2+zz_imag**2)\nzz_phase=np.arctan(zz_imag/zz_real)\n#\n# plot the magnitude of the transform as a function of frequency\n#\nsz=15\nfig=plt.figure(figsize=(10,5))\nplt.xlim([0,0.5])\nplt.ylim([0,1])\nplt.plot(freq_rad,zz_mag,color='firebrick')\nplt.plot([0,pi],[0.5,0.5],'--k')\nplt.plot([0.12566,0.12566],[0,1],'--k')\nplt.xlabel('$\\omega$ (cycles)  (continues to $\\pi$)',fontsize=sz)\nplt.ylabel('Fourier coefficient magnitude (FFT/$\\it{n}$)',fontsize=0.85*sz)\nplt.text(0.132,0.55,'$\\omega$=0.12566, $\\it{f}$=0.02')\nplt.grid(color='blue')\nplt.title('FFT of sin(2$\\pi$$\\it{t}$/50)')\n#plt.savefig(pathout1)\nplt.show()\n#\n# now test the inverse transform\n#\nyy1=nn*np.fft.irfft(zz,n=nn)\n#\nfig=plt.figure(figsize=(10,5))\nplt.xlim([0,1000])\nplt.ylim([-1,1])\nplt.plot(yy1)\nplt.plot([0,1000],[0,0],'--m')\nper=50.\nplt.plot([per,per],[-1,1],'--k')\nplt.xlabel('Time',fontsize=sz)\nplt.ylabel('Amplitude',fontsize=sz)\nplt.text(35,-1.12,'50',fontsize=15)\nplt.title('Inverse FFT of [FFT of sin(2$\\pi$$\\it{t}$/50)]')\n#plt.savefig(pathout2)\nplt.show()", "meta": {"hexsha": "c6fb770bae2ef305f4146b44d07a348249a86fff", "size": 2163, "ext": "py", "lang": "Python", "max_stars_repo_path": "test_fft.py", "max_stars_repo_name": "jade-sauve/data_analysis_tech", "max_stars_repo_head_hexsha": "cfd831bc164f621f9003fa35aeebd1b4f6234c9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_fft.py", "max_issues_repo_name": "jade-sauve/data_analysis_tech", "max_issues_repo_head_hexsha": "cfd831bc164f621f9003fa35aeebd1b4f6234c9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_fft.py", "max_forks_repo_name": "jade-sauve/data_analysis_tech", "max_forks_repo_head_hexsha": "cfd831bc164f621f9003fa35aeebd1b4f6234c9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5795454545, "max_line_length": 75, "alphanum_fraction": 0.6911696718, "include": true, "reason": "import numpy", "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9759464492044004, "lm_q2_score": 0.8976952914230971, "lm_q1q2_score": 0.876102532131881}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n# Exercise 1\r\n\r\nA = np.array([[0.3,0.6,0.1],[0.5,0.2,0.3],[0.4,0.1,0.5]])\r\nv = np.array([1/3,1/3,1/3])\r\n\r\nv_dist = []\r\nv_next = v\r\nfor i in range(1,25):\r\n    v_current = v_next\r\n    v_next = v_next*A\r\n    v_dist.append(np.linalg.norm(v_next-v_current))\r\n\r\nplt.plot(v_dist)\r\nplt.show\r\n\r\n\r\n# Exercise 2\r\n\r\nN = 1000\r\nYs = np.random.randn(10000,N)\r\nYsum = np.sum(Ys, axis=1)\r\nplt.hist(Ysum, bins=100)\r\nplt.show()\r\n\r\nYsum.mean()\r\nYsum.var()\r\n\r\n\r\n# Exercise 3\r\n\r\ndf = pd.read_csv(\"train.csv\")\r\n\r\ndigit = 7\r\nD = df[df['label'] == digit]\r\nD_mean = D.mean().values\r\nim = D_mean[1:]\r\nim = im.reshape(28,28)\r\nplt.imshow(im, cmap=\"gray\")\r\nplt.show()\r\n\r\n# Exercise 4\r\n\r\nim90 = np.rot90(im,3)\r\nplt.imshow(im90, cmap=\"gray\")\r\nplt.show()\r\n\r\n# Exercise 5\r\n\r\ndef is_symmetric(M):\r\n    return np.abs(M-M.T).sum() == 0\r\n\r\nM1 = np.array([[1,2],[3,4]])\r\nM2 = np.array([[1,2],[2,1]])\r\n\r\nis_symmetric(M1)\r\nis_symmetric(M2)\r\n\r\n# Exercise 6\r\n\r\nXOR = np.random.random((5000,2))*2-1\r\nz = (np.sign(XOR[:,0]*XOR[:,1])+1)/2\r\nz = np.expand_dims(z, axis=0).T\r\nXOR = np.append(XOR, z, axis=1)\r\nplt.scatter(XOR[:,0], XOR[:,1], c=XOR[:,2], cmap=plt.cm.RdBu, alpha=0.5)\r\nplt.axis('equal')\r\nplt.show()\r\n\r\n# Exercise 7\r\n\r\nN = 2000\r\nC = np.random.random((N,2))\r\ns = np.sign(C[:,1]-0.5)\r\nr0 = np.random.randn(N)\r\nr = (s-3)/2*10+r0\r\nx = np.cos(C[:,0]*2*np.pi)*r\r\ny = np.sin(C[:,0]*2*np.pi)*r\r\nplt.scatter(x, y, c=s, cmap=plt.cm.RdBu, alpha=0.5)\r\nplt.axis('equal')\r\nplt.show()\r\n\r\n# Exercise 8\r\n\r\nN = 2000\r\nt6 = np.random.randint(6, size=N)\r\ns = np.mod(t6,2)\r\nt = 0.5+np.random.random(N)*2+np.random.randn(N)*0.1\r\nr = t\r\na = (t+t6)*np.pi/3\r\nr0 = r+np.random.randn(N)*0.1\r\nx = np.cos(a)*r0\r\ny = np.sin(a)*r0\r\nplt.scatter(x, y, c=s, cmap=plt.cm.RdBu, alpha=0.5)\r\nplt.axis('equal')\r\nplt.show()\r\n\r\ndf = pd.DataFrame(data={'x1': x, 'x2': y, 'y': s})\r\ndf.to_csv('spiral.csv', index=False)\r\n", "meta": {"hexsha": "cde5e20df4a9d647e0d892a80f07e93a2b9e9731", "size": 1916, "ext": "py", "lang": "Python", "max_stars_repo_path": "udemy/lazyprogrammer/numpy-stack/exercises.py", "max_stars_repo_name": "balazssimon/ml-playground", "max_stars_repo_head_hexsha": "c2eba497bebc53e5a03807bdd8873c55f0ec73e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "udemy/lazyprogrammer/numpy-stack/exercises.py", "max_issues_repo_name": "balazssimon/ml-playground", "max_issues_repo_head_hexsha": "c2eba497bebc53e5a03807bdd8873c55f0ec73e1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "udemy/lazyprogrammer/numpy-stack/exercises.py", "max_forks_repo_name": "balazssimon/ml-playground", "max_forks_repo_head_hexsha": "c2eba497bebc53e5a03807bdd8873c55f0ec73e1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7843137255, "max_line_length": 73, "alphanum_fraction": 0.5798538622, "include": true, "reason": "import numpy", "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599253, "lm_q2_score": 0.9263037348714851, "lm_q1q2_score": 0.8760992532563304}}
{"text": "import math\nimport itertools\nimport numpy as np\nimport pandas as pd\nfrom typing import Dict\nfrom IPython.display import display\n\ndef cg_coefficient(\n    j1, j2,\n    m1, m2,\n    j, m\n):\n    '''\n    Compute the Clebsch-Gordan coefficient :math:`\\langle j_1, j_2; m_1, m_2 | j_1, j_2; j, m \\rangle`.\n    References: \n        - Section 3.8 of J. J. Sakurai and Jim Napolitano, \"Quantum Mechanics\", 2nd ed., Cambridge, 2017\n        - https://en.wikipedia.org/wiki/Table_of_Clebsch–Gordan_coefficients\n    '''\n\n    if m != m1 + m2:\n        return 0\n    if j < abs(j1 - j2):\n        return 0\n    if j > j1 + j2:\n        return 0\n\n    # coefficient outside of the summation\n    numerator = 2 * j + 1\n    try:\n        numerator *= math.factorial(j + j1 - j2)\n        numerator *= math.factorial(j - j1 + j2)\n        numerator *= math.factorial(j1 + j2 - j)\n        numerator *= math.factorial(j + m)\n        numerator *= math.factorial(j - m)\n        numerator *= math.factorial(j1 - m1)\n        numerator *= math.factorial(j1 + m1)\n        numerator *= math.factorial(j2 - m2)\n        numerator *= math.factorial(j2 + m2)\n    except ValueError:  # invalid j1, j2, m1, m2, j, or m -> 0\n        return 0\n\n    denominator = math.factorial(j1 + j2 + j + 1)\n\n    c = math.sqrt(numerator / denominator)\n\n    # summation\n    summation = 0\n    # ranges of k\n    k_min = max(0, -(j - j2 + m1), -(j - j1 - m2))\n    k_max = min(j1 + j2 - j, j1 - m1, j2 + m2)\n    k_max = max(0, k_max)  # avoid negative k's\n    k_list = np.linspace(k_min, k_max, int(k_max - k_min + 1))\n\n    for k in k_list:\n        numerator = (-1) ** k\n\n        denominator = math.factorial(k)\n        denominator *= math.factorial(j1 + j2 - j - k)\n        denominator *= math.factorial(j1 - m1 - k)\n        denominator *= math.factorial(j2 + m2 - k)\n        denominator *= math.factorial(j - j2 + m1 + k)\n        denominator *= math.factorial(j - j1 - m2 + k)\n\n        summation += numerator / denominator\n\n    return c * summation\n\n\ndef cg_table(j1, j2, m) -> pd.DataFrame:\n    '''\n    Returns the Clebsch-Gordan table given :math:`j_1, j_2, m`.\n    '''\n    table = dict()\n    m1_list = np.linspace(-j1, j1, int(2*j1 + 1))\n    m2_list = np.linspace(-j2, j2, int(2*j2 + 1))\n    j_list = list(set(\n        abs(m1 + m2)\n        for m1, m2 in list(itertools.product(m1_list, m2_list))\n        if abs(m1 + m2) >= abs(m)  # constraints\n    ))\n\n    for m1, m2 in list(itertools.product(m1_list, m2_list)):\n        if m1 + m2 != m:\n            continue\n        key = (m1, m2)\n        value = []\n        for j in j_list:\n            coefficient = cg_coefficient(\n                j1=j1, j2=j2,\n                m=m1+m2,\n                j=j,\n                m1=m1, m2=m2,\n            )\n            value.append(coefficient)\n        table[key] = value\n\n    df = pd.DataFrame.from_dict(table, orient='index', columns=j_list)\n    df.index.name = '(m1, m2)'\n    df.columns.name = 'j'\n    return df\n\n\ndef cg_matrix(j1, j2, m, return_indices=False):\n    '''\n    Returns the Clebsch-Gordan matrix given :math:`j_1, j_2, m` in matrix form.\n    Returns row indices (`m1, m2`) and column indices (`j`) if `return_indices` is `True`.\n    '''\n    table = cg_table(j1, j2, m)\n\n    if return_indices:\n        return table.to_numpy(), table.index.to_numpy(), table.columns.to_numpy()\n\n    return table.to_numpy()\n\n\ndef cg_tables_all_m(j1, j2, display_tables=False) -> Dict:\n    '''\n    Returns a dictionary of CClebsch-Gordan table given :math:`j_1, j_2`\n    with all possible :math:`m`.\n    '''\n    tables = dict()\n    m_max = j1 + j2\n    m_min = - m_max\n    m_list = np.linspace(m_min, m_max, int((m_max - m_min) + 1))\n\n    for m in m_list:\n        tables[m] = cg_table(j1, j2, m)\n\n    if display_tables:\n        print(f'{j1 = }, {j2 = }')\n        for m, table in tables.items():\n            print(f'{m = }:')\n            display(table)\n\n    return tables\n", "meta": {"hexsha": "a9e73559875c76752c5337619c2ef283accaed5a", "size": 3883, "ext": "py", "lang": "Python", "max_stars_repo_path": "cg/methods.py", "max_stars_repo_name": "zichunhao/WignerD", "max_stars_repo_head_hexsha": "b2ae9a512b12215c6080e068e9e092b10dbf55d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-11T19:50:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T19:50:33.000Z", "max_issues_repo_path": "cg/methods.py", "max_issues_repo_name": "zichunhao/WignerD", "max_issues_repo_head_hexsha": "b2ae9a512b12215c6080e068e9e092b10dbf55d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cg/methods.py", "max_forks_repo_name": "zichunhao/WignerD", "max_forks_repo_head_hexsha": "b2ae9a512b12215c6080e068e9e092b10dbf55d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5514705882, "max_line_length": 104, "alphanum_fraction": 0.5627092454, "include": true, "reason": "import numpy", "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.9263037297853367, "lm_q1q2_score": 0.8760992399551393}}
{"text": "# Problem: https://projecteuler.net/problem=323\n\nimport numpy as np\n\n\"\"\"\n    T: transistion matrix where,\n        T[i][j] is the probability of (a state where i bits are set) transition to (a state where j bits are set).\n        We have:\n            T[i][j] = C(N-i, j-i) * 2^i / 2^N\n        Why?\n            Assume S' = S | y, where S has i bits set, while S' has j bits set.\n            For a state S where i bits are set, there are (N-i) are not set.\n            To transition to S' where 2^j bits are set, we need to pick (j-i) bits from (N-i) bits.\n            There are C(N-i, j-i) ways to pick (j-i) bits from (N-i) bits.\n            Also, y might have bits that are already set in S, and there are 2^i ways to choose those bits.\n            Therefore, there are C(N-i, j-i) * 2^i ways to choose y.\n            Also, there are 2^N different N-bit numbers.\n            Therefore, T[i][j] = C(N-i, j-i) * 2^i / 2^N.\n    S: state vector where,\n        S[i] means the probability of the current number has i bits set.\n\n    Apply Markov chain, we can figure out the probability of having 2^N bits set after applying bitwise-OR k times as follows,\n        S_{k} = S * T^k\n    To calculate the expected value of N, and due to linearity of expectations, we can follow the following formula to calculate E(N):\n        E(N) = sum_{i = 1 to inf} (S[N] - prev_S[N]) * i\n    We expect this series to converge, so we calculate the sum for each K as in sum_{i = 1 to K} (S[N] - prev_S[N]) * i until it converges.\n\"\"\"\n\nN = 32\n\nfactorials = [1]\nfor i in range(1, N+1):\n    factorials.append(factorials[-1] * i)\n\ndef C(n, k):\n    return factorials[n] / factorials[k] / factorials[n-k]\n\nT = np.zeros((N+1, N+1), dtype = np.float)\n\nfor alpha in range(N+1):\n    for beta in range(alpha, N+1):\n        T[alpha][beta] = 1.0 * C(N - alpha, beta - alpha) / (2**(N - alpha))\n\nS = np.zeros((N+1), dtype = np.float)\nS[0] = 1.0\n\nans = 0\nprev_ans = -1\nstop_threshold = 10\nstop_counter = 0\ntol = 10**-12\n\nprev_SN = 0.0\nn_trials = 0\nwhile True:\n    n_trials = n_trials + 1\n    S = S.dot(T)\n    ans = ans + (S[N]-prev_SN) * n_trials\n    prev_SN = S[N]\n    if abs(ans - prev_ans) < tol:\n        stop_counter = stop_counter + 1\n        if stop_counter == stop_threshold:\n            break\n    else:\n        stop_counter = 0\n    prev_ans = ans\n\nprint(ans)\n", "meta": {"hexsha": "9e7c7c338129ff457e5ff4391b648dde9e3fe4ad", "size": 2327, "ext": "py", "lang": "Python", "max_stars_repo_path": "4th_100/problem323.py", "max_stars_repo_name": "takekoputa/project-euler", "max_stars_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4th_100/problem323.py", "max_issues_repo_name": "takekoputa/project-euler", "max_issues_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4th_100/problem323.py", "max_forks_repo_name": "takekoputa/project-euler", "max_forks_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-02T12:08:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T12:08:46.000Z", "avg_line_length": 33.7246376812, "max_line_length": 139, "alphanum_fraction": 0.595186936, "include": true, "reason": "import numpy", "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140177976359, "lm_q2_score": 0.905989826094673, "lm_q1q2_score": 0.8760142628329817}}
{"text": "# import modules\r\nimport numpy as np\r\n\r\n'''\r\n# Description.\r\nObtains the unit vector of an input vector.\r\n\r\n# Input(s).\r\nArray nx1 with size different to unit (vector)\r\n\r\n# Example\r\nvector = np.random.rand(2)\r\n\r\n---\r\nuVector = unitvector(vector)\r\n'''\r\ndef unitvector(vector):\r\n    \r\n    vecDist = np.sqrt(np.dot(vector,vector))\r\n    uVector = vector/vecDist\r\n    \r\n    return uVector\r\n'''\r\nBSD 2 license.\r\n\r\nCopyright (c) 2016, Universidad Nacional de Colombia, Ludger O.\r\n   Suarez-Burgoa and Exneyder Andrés Montoya Araque.\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without\r\nmodification, are permitted provided that the following conditions are\r\nmet:  \r\n\r\n1. Redistributions of source code must retain the above copyright notice,\r\nthis list of conditions and the following disclaimer. \r\n\r\n2. Redistributions in binary form must reproduce the above copyright\r\nnotice, this list of conditions and the following disclaimer in the\r\ndocumentation and/or other materials provided with the distribution.  \r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\r\nIS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\r\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r\nPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\r\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n'''\r\n", "meta": {"hexsha": "5c40748c390809454da2e1102ee82ec37ad4282a", "size": 1819, "ext": "py", "lang": "Python", "max_stars_repo_path": "functions/unitvector.py", "max_stars_repo_name": "eamontoyaa/CSS-pyProgram", "max_stars_repo_head_hexsha": "beb28a18cba4e4b2e6d8be556296aa6f8025defa", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2016-05-12T14:54:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T09:29:08.000Z", "max_issues_repo_path": "functions/unitvector.py", "max_issues_repo_name": "eamontoyaa/CSS-pyProgram", "max_issues_repo_head_hexsha": "beb28a18cba4e4b2e6d8be556296aa6f8025defa", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-02-27T17:34:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-17T08:44:26.000Z", "max_forks_repo_path": "functions/unitvector.py", "max_forks_repo_name": "eamontoyaa/CSS-pyProgram", "max_forks_repo_head_hexsha": "beb28a18cba4e4b2e6d8be556296aa6f8025defa", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-06-21T04:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T02:25:19.000Z", "avg_line_length": 34.320754717, "max_line_length": 74, "alphanum_fraction": 0.7586586036, "include": true, "reason": "import numpy", "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914017797636, "lm_q2_score": 0.9059898153067649, "lm_q1q2_score": 0.8760142524020023}}
{"text": "#   A quick guide to sympy\r\nfrom sympy import *\r\n\r\n#   INITIALIZE\r\nx,y,z = symbols('x y z')\r\nf = x**3 + exp(x) + cos(3*x) + log(sin(x))\r\nprint('function: '); print(f)\r\n\r\n    #initialize with string:\r\nexpression = \"x**3 + exp(x) + cos(3*x) + log(sin(x))\"\r\nf = sympify(expression)\r\n\r\nprint()\r\n#   VALUE\r\nvalue = f.subs(x,3)\r\nprint('symbolic f(3): '); print(value)\r\n\r\nvalue = N(value)    # or evalf()\r\nprint('numeric f(3): '); print(value)\r\n\r\nvalue = value.evalf(100)    # up to 1e-100 precision ?!\r\nprint('numagic f(3): '); print(value)\r\n\r\nprint('1/6: ') # don't test 1/7 \r\nvalue = (x/6).subs(x,1); print(value.evalf(100))\r\n\r\n    #multivariable\r\nf1 = x*y*z\r\nprint('with x=2, y=4, z=3 then f1 = x*y*z = ')\r\nvalue = f.subs( [(x,2),(y,4),(z,3)] )\r\nprint(value)\r\n\r\nprint()\r\n#   DERIVATIVE\r\ndf = diff(f,x)\r\nprint('first order derivative: '); print(df)\r\n\r\ndf = diff(f,x,2)    # or diff(f, x, x)\r\nprint('second order derivative: '); print(df)\r\n\r\n    #multivariable\r\ndf = diff(x*y*z + x**y, x, y)   #derivative with respect to x then y\r\nprint(df)\r\n\r\nprint(value)\r\n\r\nprint()\r\n#   INTEGRAL\r\n\r\nprint()\r\n#   MATRIX\r\n\r\nprint()\r\n#   SOLVER  f(x) = 0\r\nfx = x**2 - 5\r\nsolution = solveset(fx, x, domain=S.Reals)\r\nprint(solution)\r\n\r\nfx = sin(x) - 1\r\nsolution = solveset(fx, x, domain=S.Reals)\r\nprint(solution)\r\n\r\n#", "meta": {"hexsha": "f84feba68c094c6e02bf16fab4bd23611fd20002", "size": 1294, "ext": "py", "lang": "Python", "max_stars_repo_path": "SympyGuide.py", "max_stars_repo_name": "dthanhqhtt/MI3040-Numerical-Analysis", "max_stars_repo_head_hexsha": "cf38ea7e6dc834b19e7cffef8b867a02ba472eae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-11-23T17:00:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T06:28:40.000Z", "max_issues_repo_path": "SympyGuide.py", "max_issues_repo_name": "dthanhqhtt/MI3040-Numerical-Analysis", "max_issues_repo_head_hexsha": "cf38ea7e6dc834b19e7cffef8b867a02ba472eae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-22T17:08:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-20T12:00:59.000Z", "max_forks_repo_path": "SympyGuide.py", "max_forks_repo_name": "dthanhqhtt/MI3040-Numerical-Analysis", "max_forks_repo_head_hexsha": "cf38ea7e6dc834b19e7cffef8b867a02ba472eae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-12-03T05:11:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T03:33:35.000Z", "avg_line_length": 20.5396825397, "max_line_length": 69, "alphanum_fraction": 0.5726429675, "include": true, "reason": "from sympy", "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969785409439575, "lm_q2_score": 0.9032942151647513, "lm_q1q2_score": 0.8760015502979479}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport calculus.integ as numint\nimport scipy.integrate as spint\nfrom interpolation.lagrange import lagrangepoly\n#Real value 7.32473\ndef f(x):\n\treturn -x**5 + 5*x**4 - 7*x**3 + x**2 + 4*x + 0.5\n\nx = np.linspace(-5,5, 150)\ny = f(x)\na = 0.5\nb = 2.6\nx2 = np.linspace(a, b)\nfig, ax = plt.subplots()\nax.plot(x, y)\nax.set_xlim(-3, 5)\nax.set_ylim(-4, 7)\nax.axhline(0, color='black')\nax.legend(['f(x)'])\nax.fill_between(x2, 0, f(x2), color = 'g', alpha=0.3)\nplt.title('Integral of f(x)')\n\n#Trap rule\nfig, ax = plt.subplots()\nax.plot(x, y)\nax.set_xlim(-3, 5)\nax.set_ylim(-4, 7)\nax.axhline(0, color='black')\nax.legend(['f(x)'])\n\nh = b-a\n\ny2 = f(a) + (f(b) - f(a))/(b - a) * (x2 - a)\nax.plot(x2, y2, '-g')\nax.fill_between(x2, 0, y2, color = 'g', alpha=0.3)\nax.grid(True)\ntextstr = str(numint.trap(h, f(a), f(b)))\nprops = dict(boxstyle='round', facecolor='white')\n# place a text box in upper left in axes coords\nax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=12,\n        verticalalignment='top', bbox=props)\n\nplt.title('Trapezoid Rule')\n\n#Trap rule with multiple segs\nfig, ax = plt.subplots()\nax.plot(x, y)\nnumpts = 5\nn = 5-1\nax.set_xlim(-3, 5)\nax.set_ylim(-4, 7)\nax.axhline(0, color='black')\nax.legend(['f(x)'])\nx3 = np.linspace(a, b, numpts)\nx4 = np.linspace(a, b, numpts)\nx3 = x3[1:]\nlastx = a\nfor i in x3:\n\txn = np.linspace(lastx, i, 15)\n\tyn = f(lastx) + (f(i) - f(lastx))/(i - lastx) * (xn - lastx)\n\tax.plot(xn, yn, '-g')\n\tax.fill_between(xn, 0, yn, color='g', alpha=0.3)\n\tlastx = i\n\t\ntextstr = str(numint.trapm(h/n, f(x4)))\nprops = dict(boxstyle='round', facecolor='white')\n# place a text box in upper left in axes coords\nax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=12,\n        verticalalignment='top', bbox=props)\nax.grid(True)\nplt.title('Trapezoid Rule w/ Multiple Segments')\n\n#Simps 1/3 rule\nfig, ax = plt.subplots()\nax.plot(x, y)\nax.set_xlim(-3, 5)\nax.set_ylim(-4, 7)\nax.axhline(0, color='black')\nax.legend(['f(x)'])\na = 0.5\nb = 2.6\nh = b-a\nxx = np.linspace(a, b, 3)\nx2 = np.linspace(a, b)\ny2 = lagrangepoly(xx, f(xx), x2)\nax.plot(x2, y2, '-g')\nax.fill_between(x2, 0, y2, color = 'g', alpha=0.3)\nax.grid(True)\ntextstr = str(numint.simp13(h, f(xx[0]), f(xx[1]), f(xx[2])))\nprops = dict(boxstyle='round', facecolor='white')\n# place a text box in upper left in axes coords\nax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=12,\n        verticalalignment='top', bbox=props)\n\nplt.title('Simpson 1/3 Rule')\n\n#Simps 1/3 rule with multiple segs\nfig, ax = plt.subplots()\nax.plot(x, y)\nnumpts = 5\nn = 5-1\nax.set_xlim(-3, 5)\nax.set_ylim(-4, 7)\nax.axhline(0, color='black')\nax.legend(['f(x)'])\nx3 = np.linspace(a, b, numpts)\nx4 = np.linspace(a, b, numpts)\nx3 = x3[1:]\nlastx = a\nfor i in x3:\n\txn = np.linspace(lastx, i, 15)\n\txx2 = np.linspace(lastx, i, 3)\n\tyn = lagrangepoly(xx2, f(xx2), xn)\n\tax.plot(xn, yn, '-g')\n\tax.fill_between(xn, 0, yn, color='g', alpha=0.3)\n\tlastx = i\n\t\ntextstr = str(numint.simp13m(h/n, f(x4)))\nprops = dict(boxstyle='round', facecolor='white')\n# place a text box in upper left in axes coords\nax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=12,\n        verticalalignment='top', bbox=props)\nax.grid(True)\nplt.title('Simpson Rule 1/3 w/ Multiple Segments')\nplt.show()\n", "meta": {"hexsha": "22444a7c6880e25f3c2f9ddc420bc456d1482a31", "size": 3284, "ext": "py", "lang": "Python", "max_stars_repo_path": "gen_calc_graphs.py", "max_stars_repo_name": "Seek/LaTechNumeric", "max_stars_repo_head_hexsha": "dabef2040e84bf25cabab07fe20a6434ce52197b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gen_calc_graphs.py", "max_issues_repo_name": "Seek/LaTechNumeric", "max_issues_repo_head_hexsha": "dabef2040e84bf25cabab07fe20a6434ce52197b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gen_calc_graphs.py", "max_forks_repo_name": "Seek/LaTechNumeric", "max_forks_repo_head_hexsha": "dabef2040e84bf25cabab07fe20a6434ce52197b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8582677165, "max_line_length": 65, "alphanum_fraction": 0.6452496955, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854120593482, "lm_q2_score": 0.9032942112597331, "lm_q1q2_score": 0.8760015488773442}}
{"text": "from numba import njit\nimport numpy as np\n\ndef py_l2_diff(f1, f2):\n    \"\"\"\n    Computes the l2-norm of the difference\n    between a function f1 and a function f2\n\n    Parameters\n    ----------\n    f1 : array of floats\n        function 1\n    f2 : array of floats\n        function 2\n\n    Returns\n    -------\n    diff : float\n        The l2-norm of the difference.\n    \"\"\"\n    l2_diff = np.sqrt(np.sum((f1 - f2)**2))/f1.size\n\n    return l2_diff\n\n@njit\ndef l2_diff(f1, f2):\n    \"\"\"\n    Computes the l2-norm of the difference\n    between a function f1 and a function f2\n\n    Parameters\n    ----------\n    f1 : array of floats\n        function 1\n    f2 : array of floats\n        function 2\n\n    Returns\n    -------\n    diff : float\n        The l2-norm of the difference.\n    \"\"\"\n    l2_diff = np.sqrt(np.sum((f1 - f2)**2)) / f1.size\n\n    return l2_diff\n", "meta": {"hexsha": "2a854030b13ba45ccbba308d1a307694e171352c", "size": 847, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/modules/norms.py", "max_stars_repo_name": "acalikto/letsgo", "max_stars_repo_head_hexsha": "bdd29980f9d6fe6933b185b47701586579d1971f", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2020-09-14T15:55:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T21:32:54.000Z", "max_issues_repo_path": "notebooks/modules/norms.py", "max_issues_repo_name": "acalikto/letsgo", "max_issues_repo_head_hexsha": "bdd29980f9d6fe6933b185b47701586579d1971f", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-09-14T15:49:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-18T10:40:52.000Z", "max_forks_repo_path": "notebooks/modules/norms.py", "max_forks_repo_name": "acalikto/letsgo", "max_forks_repo_head_hexsha": "bdd29980f9d6fe6933b185b47701586579d1971f", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2020-09-15T12:57:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T08:51:38.000Z", "avg_line_length": 18.4130434783, "max_line_length": 53, "alphanum_fraction": 0.5631641086, "include": true, "reason": "import numpy,from numba", "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773708026035287, "lm_q2_score": 0.8962513696696647, "lm_q1q2_score": 0.875969920508552}}
{"text": "from __future__ import division\nimport numpy\nimport matplotlib.pyplot as pyplot\n\nUSER = 'Maciej Grabias'\nUSER_ID = 'njgh39'\n\n# constants used\nT_HALF = 20.8 #half-time\nTAU = T_HALF / numpy.log(2) # average lifetime\n\n\ndef f(n):\n    return -n / TAU\n\ndef analytic(N0, ts):\n    return N0 * numpy.exp(-ts / TAU)\n\ndef solve_euler(N0, dt, n_panels):\n\n    #initial parameters\n    n, t = N0, 0\n\n    # array for iteration\n    n_t = numpy.zeros((n_panels,))\n\n    for i in range(n_panels):\n        n_t[i] = n\n        t = i * dt\n        n = n + f(n) * dt\n    return n_t\n\n\ndef solve_heun(N0, dt, n_panels):\n\n    # initial parameters\n    n, t = N0, 0\n\n    # array for iteration\n    n_t = numpy.zeros((n_panels,))\n\n    for i in range(n_panels):\n        n_t[i] = n\n        k0 = f(n)\n        k1 = f(n + k0 * dt)\n        n = n + (k0 + k1) * dt /2\n    return n_t\n\n\n# constants for plots\nT1 = 60 # time range\nN_PANELS = 15 # number of panels\nN0 = 1500 # initial numbe of nuclei\n\n\ndt = T1 / N_PANELS\nts = numpy.arange(0, T1, dt)\n\n# functions for plots\n\nn_analytic  = analytic(N0, ts)\nn_euler     = solve_euler(N0, dt, N_PANELS)\nn_heun      = solve_heun(N0, dt, N_PANELS)\n\n\n#plot\n\npyplot.figure()\npyplot.subplot(211) # count VS time for methods\npyplot.plot(ts, n_euler, label='Euler Method', color ='red')\npyplot.plot(ts, n_heun, label='Heun Method', color = 'blue', linestyle = '--')\npyplot.plot(ts, n_analytic, label='Analytic', color = 'grey')\npyplot.xlabel(\"Time, h\")\npyplot.ylabel(\"Number of nuclei\")\npyplot.title(\"Number of nuclei for different methods used VS time\")\npyplot.legend()\n\n\npyplot.subplot(212) # error VS time for numerics\npyplot.semilogy()\nerr_euler = abs(n_euler - n_analytic) / n_analytic\nerr_heun = abs(n_heun - n_analytic) / n_analytic\npyplot.plot(ts, err_euler, color=\"red\", label =\" Euler\")\npyplot.plot(ts, err_heun, color =\"blue\", linestyle=\"--\", label=\"Heun\")\npyplot.xlabel(\"Time, h\")\npyplot.ylabel(\"Error\")\npyplot.title(\"Error between methods used and the analytically determined solution\")\npyplot.legend()\n\npyplot.show()\n\nANSWER1 = \"\"\"Heun's method is more accurate than Euler's method because it integrates a differential\nequation over trapeziums rather than rectangles\"\"\"", "meta": {"hexsha": "d9001758aebf53d546aaf7c45bb614c8a645260b", "size": 2178, "ext": "py", "lang": "Python", "max_stars_repo_path": "cp_3.py", "max_stars_repo_name": "M-Grabias/uni_codes", "max_stars_repo_head_hexsha": "ff117894c7d49ec13470c551ef6929782a154d68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cp_3.py", "max_issues_repo_name": "M-Grabias/uni_codes", "max_issues_repo_head_hexsha": "ff117894c7d49ec13470c551ef6929782a154d68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cp_3.py", "max_forks_repo_name": "M-Grabias/uni_codes", "max_forks_repo_head_hexsha": "ff117894c7d49ec13470c551ef6929782a154d68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4193548387, "max_line_length": 100, "alphanum_fraction": 0.665748393, "include": true, "reason": "import numpy", "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731169394882, "lm_q2_score": 0.9099070066488187, "lm_q1q2_score": 0.875943014215698}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.integrate import quad\n\n\ndef smooth_product(u, v, domain=(0, 1)):\n    approx, _ = quad(lambda x: u(x)*v(x), *domain)  # Discard error\n    return approx\n\n\ndef least_squares(func, basis, inner, **kwargs):\n    # Take the inner product of each pair of basis\n    lhs = np.array([\n        [inner(p, q, **kwargs) for p in basis]\n        for q in basis\n    ])\n\n    # The the inner product of the function with each basis\n    rhs = np.array([\n        inner(p, func, **kwargs) for p in basis\n    ])\n\n    # Create the approximation\n    return np.linalg.solve(lhs, rhs)\n\n\ndef Q1():\n    legendre = ('1', '2*x - 1', '6*x**2 - 6*x + 1')\n    basis    = [  # Generate the functions based off strings\n        np.vectorize(eval('lambda x:' + poly))\n        for poly in legendre\n    ]\n\n    coeffs = least_squares(\n        np.exp, basis, smooth_product, domain=(0, 1))\n\n    domain = np.linspace(0, 1)\n    approx = coeffs @ [p(domain) for p in basis]\n\n    fig, ax = plt.subplots()\n    ax.plot(domain, np.exp(domain), label='Exact')\n    ax.plot(domain, approx, label='Approx')\n\n\ndef Q2():\n    basis_funcs = [  # Generate the functions based off strings\n        np.vectorize(eval('lambda x:' + poly))\n        for poly in ('1', 'x', 'x**2')\n    ]\n\n    x_data, y_data = np.loadtxt('data_points.txt', unpack=True)\n    basis_data = [p(x_data) for p in basis_funcs]\n\n    coeffs = least_squares(\n        y_data, basis_data, np.inner)\n\n    domain = np.linspace(x_data.min(), x_data.max())\n    approx = coeffs @ [p(domain) for p in basis_funcs]\n\n    fig, ax = plt.subplots()\n    ax.scatter(x_data, y_data, label='Exact')\n    ax.plot(domain, approx, 'k-', label='Approx')\n\n\ndef Q3():\n    basis = [  # Generate the functions based off strings\n        eval('lambda x:' + func)\n        for func in ('np.sin(x)', 'np.sin(2*x)', 'np.sin(3*x)')\n    ]\n\n    def function(x):\n        return x*(np.pi-x)\n\n    coeffs = least_squares(\n        function, basis,\n        smooth_product, domain=(0, np.pi)\n    )\n\n    for coeff, exact in zip(coeffs, (8/np.pi, 0, 8/(27*np.pi))):\n        print(f'Coefficient error: {abs(coeff-exact):.3e}')\n\n    domain = np.linspace(0, np.pi)\n    approx = coeffs @ [p(domain) for p in basis]\n\n    fig, ax = plt.subplots()\n    ax.plot(domain, function(domain), label='Exact')\n    ax.plot(domain, approx, label='Approx')\n\n\nif __name__ == '__main__':\n    questions = (Q1, Q2, Q3)\n    for question in questions:\n        input(f'Press `Enter` to run {question.__name__} ')\n\n        plt.close('all')        # <- Close all existing figures\n        question()\n        plt.show(block=False)   # <- Allow code execution to continue\n\n    input('Press `Enter` to quit the program.')\n", "meta": {"hexsha": "40b3842080af100b37930f14a5a42678df3703b1", "size": 2714, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week 3/advanced.py", "max_stars_repo_name": "Schalk-Laubscher/2020-Tutorials", "max_stars_repo_head_hexsha": "d720994d80d255da7958bd0e4d3fa4ca69aae9d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-08-03T01:40:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T12:07:28.000Z", "max_issues_repo_path": "Week 3/advanced.py", "max_issues_repo_name": "Schalk-Laubscher/2020-Tutorials", "max_issues_repo_head_hexsha": "d720994d80d255da7958bd0e4d3fa4ca69aae9d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week 3/advanced.py", "max_forks_repo_name": "Schalk-Laubscher/2020-Tutorials", "max_forks_repo_head_hexsha": "d720994d80d255da7958bd0e4d3fa4ca69aae9d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-08-03T02:48:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T06:47:11.000Z", "avg_line_length": 27.14, "max_line_length": 69, "alphanum_fraction": 0.5972733972, "include": true, "reason": "import numpy,from scipy", "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.9099070066488187, "lm_q1q2_score": 0.8759430103180043}}
{"text": "import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\n\t\n'''\nComputeCost computes the cost function\n'''\ndef computeCost(X, y, theta):\n\t#computeCost Compute cost for linear regression\n\t#   J = computeCost(X, y, theta) computes the cost of using theta as the\n\t#   parameter for linear regression to fit the data points in X and y\n\n\t# Initialize some useful values\n\tm = len(y); # number of training examples\n\n\t# You need to return the following variables correctly \n\tJ = 0;\n\n\t# ====================== YOUR CODE HERE ======================\n\t# Instructions: Compute the cost of a particular choice of theta\n\t# =========================================================================\n\t# You should set J to the cost.\n\t\n\tX_product \t= np.matmul(X,theta) \t\t# X*theta\n\tX_diff\t  \t= np.subtract(X_product, y)\t# X*theta - y\n\tX_square\t= np.square(X_diff)\t\t\t# Square each element of the matrix computed above\n\tX_sum\t\t= np.sum(X_square)\t\t\t# Sum all the elements\n\tJ \t\t\t= (1.0/(2.0*m))*X_sum\t\t# Cost Function\n\t\n\treturn J\n\n'''\ngradientDescent function iterates till it finds a minima\n'''\ndef gradientDescent(X, y, theta, alpha, num_iters):\n\t#function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)\n\t#GRADIENTDESCENT Performs gradient descent to learn theta\n\t#   theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by \n\t#   taking num_iters gradient steps with learning rate alpha\n\n\t# Initialize some useful values\n\tm = len(y); # number of training examples\n\tJ_history = np.zeros((num_iters, 1));\n\n\tfor iter in range(num_iters):\n\n\t\t# ====================== YOUR CODE HERE ======================\n\t\t# Instructions: Perform a single gradient step on the parameter vector\n\t\t#               theta. \n\t\t#\n\t\t# Hint: While debugging, it can be useful to print out the values\n\t\t#       of the cost function (computeCost) and gradient here.\n\t\t#\n\t\tX_0 \t\t\t= X[:,0].reshape((m,1));\n\t\tX_1 \t\t\t= X[:,1].reshape((m,1));\n\t\tX_0_tr\t\t\t= np.transpose(X_0)\n\t\tX_1_tr\t\t\t= np.transpose(X_1)\n\t\tX_theta_prod\t= (np.matmul(X,theta)).reshape((m,1))\n\t\tX_theta_y_diff\t= np.subtract(X_theta_prod,y)\n\t\ttheta_0 = theta.item(0) - (float(alpha)/float(m))*(np.matmul(X_0_tr, X_theta_y_diff)).item(0)\n\t\ttheta_1 = theta.item(1) - (float(alpha)/float(m))*(np.matmul(X_1_tr, X_theta_y_diff)).item(0)\n\t\t#print X_0.shape, X_0_tr.shape, theta.shape, X.shape, X_theta_prod.shape, y.shape, X_theta_y_diff.shape\n\t\ttheta = np.array([theta_0, theta_1]).reshape((2,1))\n\t\t\n\t\t# Plot the linear fit\n\t\tif(iter%200==0):\n\t\t\tplt.scatter(X_data, y_data, marker='o',  color='g', label='orig') \n\t\t\ty_data_predicted = np.matmul(X,theta)\n\t\t\tplt.plot(X_data, y_data_predicted, marker='*', linestyle='-', color='b', label='pred')\n\t\t\tplt.legend(loc='lower right')\n\t\t\tplt.show(block=False)\n\t\t\ttime.sleep(3)\n\t\t\tplt.close()\n\n\n\n\n\t\t# ============================================================\n\n\t\t# Save the cost J in every iteration    \n\t\tJ_history[iter] = computeCost(X, y, theta)\n\t\tprint \"Cost @ iteration: \",iter, \" = \", J_history[iter]\n\treturn theta\n\n\ndata \t= pd.read_csv('ex1data1.txt', header =  None, names = ['Population', 'Profits'])\ny_data \t= data.iloc[:,1]\nX_data \t= data.iloc[:,0]\n\nm \t\t= len(y_data)\t\t\t\t\t\t  #Number of training samples\ny \t\t= np.array(y_data).reshape(m,1)\t\t\nX \t\t= np.c_[np.ones(m), np.array(X_data)] # Add a column of ones to x\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.set_title('Population - Profit Scatter Plot')\nax.set_xlabel('Population in 10000s')\nax.set_ylabel('Profit in 10000$')\n\ntheta \t= np.zeros((2, 1)).reshape((2,1)) # initialize fitting parameters\ntheta \t= np.array([40,40]).reshape((2,1))# Try initializing from a different point. The convergence will be seen easily\n\nprint \"Cost Function Value is:\", computeCost(X, y, theta)\n\n# Some gradient descent settings\niterations = 1500;\nalpha = 0.01;\n\n# run gradient descent\ntheta = gradientDescent(X, y, theta, alpha, iterations);\n\n# print theta to screen\nprint 'Theta found by gradient descent: ', theta.item(0), theta.item(1)\n\n# Plot the linear fit\nplt.scatter(X_data, y_data, marker='o',  color='g', label='orig') \ny_data_predicted = np.matmul(X,theta)\nplt.plot(X_data, y_data_predicted, marker='*', linestyle='-', color='b', label='pred')\nplt.legend(loc='lower right')\n\n# Predict values for population sizes of 35,000 and 70,000\n#predict1 = [1, 3.5] *theta;\n#fprintf('For population = 35,000, we predict a profit of %f\\n',...\n#    predict1*10000);\n#predict2 = [1, 7] * theta;\n#fprintf('For population = 70,000, we predict a profit of %f\\n',...\n#   predict2*10000);\n\n", "meta": {"hexsha": "7910613f106fbae62b1f5f126cd2a246485ff2ff", "size": 4537, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear_Regression/ex1.py", "max_stars_repo_name": "rishisidhu/MachineLearning", "max_stars_repo_head_hexsha": "a5a95de25ce5ff6bed5e51f3c5325c8dc54253f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Linear_Regression/ex1.py", "max_issues_repo_name": "rishisidhu/MachineLearning", "max_issues_repo_head_hexsha": "a5a95de25ce5ff6bed5e51f3c5325c8dc54253f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear_Regression/ex1.py", "max_forks_repo_name": "rishisidhu/MachineLearning", "max_forks_repo_head_hexsha": "a5a95de25ce5ff6bed5e51f3c5325c8dc54253f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9, "max_line_length": 119, "alphanum_fraction": 0.652854309, "include": true, "reason": "import numpy", "num_tokens": 1299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811571768048, "lm_q2_score": 0.9073122288794594, "lm_q1q2_score": 0.8759021294363185}}
{"text": "#!/usr/bin/python\n\"\"\" Calculation of Pi via Monte-Carlo \"\"\"\n\nimport random\nimport numpy as np\nfrom time import process_time\nMAX_STEPS = 1000000\nREPEATS = 100\n\n\ndef method_1() -> float:\n    \"\"\"\n    Generate two random numbers between 0 and 1 (as x and y coordinates).\n    If x*x + y*y < 1, that is (x, y) inside the unit circle (segment).\n    Pi is calculated by the fraction of points in the circle vs total number.\n    \"\"\"\n    for i in range(REPEATS):\n        step = 0\n        sum = 0\n        while step < MAX_STEPS:\n            x = random.random()\n            y = random.random()\n            if x*x + y*y < 1.0:\n                sum += 1\n            step += 1\n        estimate = 4.0 * sum / MAX_STEPS\n    return estimate\n\n\ndef method_2() -> float:\n    \"\"\"\n    Generates one random number [0, 1) as x and calculates the corresponding\n    y value to put (x, y) on the unit circle.\n    \"\"\"\n    for i in range(REPEATS):\n        step = 0\n        sum = 0.0\n        while step < MAX_STEPS:\n            x = random.random()\n            y = (1.0 - x*x) ** 0.5\n            sum = sum + y\n            step += 1\n        estimate = 4.0 * sum / MAX_STEPS\n    return estimate\n\n\ndef method_3() -> float:\n    \"\"\"\n    Generates a periodic x-grid and generates the corresponding y values to form a unit circle.\n    \"\"\"\n    step = 1.0 / MAX_STEPS\n    for i in range(REPEATS):\n        sum = 0.0\n        x = 0.0\n        while x <= 1.0:\n            y = (1.0 - x*x) ** 0.5\n            sum = sum + y\n            x += step\n        estimate = 4.0 * sum / MAX_STEPS\n    return estimate\n\n\ndef method_4() -> float:\n    \"\"\"\n    Basically the same as method3, but utiliting the numpy module.\n    \"\"\"\n    x_dom = np.linspace(0, 1, MAX_STEPS)\n    for i in range(REPEATS):\n        y     = np.sqrt(1-np.power(x_dom, 2))\n        estimate    = 4.0 * y.sum() / MAX_STEPS\n    return estimate\n\n\nif __name__ == '__main__':\n    lst_methods = [\n        method_1,\n        method_2,\n        method_3,\n        method_4,\n        ]\n    for method in lst_methods:\n        t1 = process_time()\n        pi = method()\n        t2 = process_time()\n        print(\"Pi was approximated to {} using {} steps and {} repeats in {} seconds.\".format(pi, MAX_STEPS, REPEATS, round(t2-t1, 5)))\n", "meta": {"hexsha": "05d0e8cfea37ce963c0f9004733064bfaf5359d4", "size": 2227, "ext": "py", "lang": "Python", "max_stars_repo_path": "ApproxPi/python/compute_pi.py", "max_stars_repo_name": "LauKr/funny_maths", "max_stars_repo_head_hexsha": "ceb7ea68ff6b1606a7482a73a0117c742bc95f94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ApproxPi/python/compute_pi.py", "max_issues_repo_name": "LauKr/funny_maths", "max_issues_repo_head_hexsha": "ceb7ea68ff6b1606a7482a73a0117c742bc95f94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ApproxPi/python/compute_pi.py", "max_forks_repo_name": "LauKr/funny_maths", "max_forks_repo_head_hexsha": "ceb7ea68ff6b1606a7482a73a0117c742bc95f94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8953488372, "max_line_length": 135, "alphanum_fraction": 0.5383924562, "include": true, "reason": "import numpy", "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811601648193, "lm_q2_score": 0.907312221360624, "lm_q1q2_score": 0.8759021248888386}}
{"text": "# Polynomial Regression\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('Position_Salaries.csv')\nX = dataset.iloc[:, 1:-1].values\nY = dataset.iloc[:, -1].values\n\n## Splitting the dataset into the training set and test set\n# Only 10 observations, thus doesn't make sense to split dataset\n\"\"\"from sklearn.cross_validation import train_test_split\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size= 0.2, random_state= 0)\"\"\"\n\n\"\"\"# Feature scaling\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\"\"\"\n\n# Fit linear regression to dataset\nfrom sklearn.linear_model import LinearRegression\nLinReg = LinearRegression()\nLinReg.fit(X,Y)\n\n# Fit polynomial regression to dataset\nfrom sklearn.preprocessing import PolynomialFeatures\nDegree = 3\nPolyReg = PolynomialFeatures(degree = Degree)\nX_poly = PolyReg.fit_transform(X)\nLinReg2 = LinearRegression()\nLinReg2.fit(X_poly, Y)\n\n# Calculate R^2 and adjusted R^2\ndef calculateRSquared(y_orig, y_pred, X):\n    Resid = sum((y_orig - y_pred)**2)\n    Total = sum((y_orig - np.mean(y_orig))**2)\n    R_squared = 1 - (float(Resid))/Total\n    R_squared_adjusted = 1 - (1-R_squared)*(len(y_orig)-1)/(len(y_orig)-X.shape[1]-1)\n    return R_squared, R_squared_adjusted\n\n# Visualize regression fits\n# Visualize linear fit\nY_Lin = LinReg.predict(X)\n[R, R_adjust] = calculateRSquared(Y,Y_Lin,X)\nplt.scatter(X, Y, color = 'red')\nplt.plot(X,Y_Lin, color = 'blue')\nplt.title('Salary vs Position (Linear Regression)')\nplt.text(0.05, 0.85, '$R^2$ = {}'.format(round(R,2))+'\\n$R^2$ adjusted = {}'.format(round(R_adjust,2)), transform=plt.gca().transAxes)\nplt.xlabel('Position grade')\nplt.ylabel('Salary ($)')\n\nX_grid = np.arange(min(X), max(X), 0.1)\nX_grid = X_grid.reshape(len(X_grid), 1)\nY_Poly = LinReg2.predict(PolyReg.fit_transform(X_grid))\n[R, R_adjust] = calculateRSquared(Y,LinReg2.predict(PolyReg.fit_transform(X)),X)\nplt.figure()\nplt.scatter(X, Y, color = 'red')\nplt.plot(X_grid, Y_Poly, color = 'blue')\nplt.title('Salary vs Position (Polynomial Regression, D = ' + str(Degree) + ')')\nplt.text(0.05, 0.85, '$R^2$ = {}'.format(round(R,2))+'\\n$R^2$ adjusted = {}'.format(round(R_adjust,2)), transform=plt.gca().transAxes)\nplt.xlabel('Position grade')\nplt.ylabel('Salary ($)')\nplt.show()\n\n# Predicting a new result with linear regression\nprint(LinReg.predict(6.5))\n\n# Predicting a new result with polynomial regression\nprint(LinReg2.predict(PolyReg.fit_transform(6.5)))", "meta": {"hexsha": "c1b967a4cd801c9a9fba50434e5c2ba03e1ba170", "size": 2596, "ext": "py", "lang": "Python", "max_stars_repo_path": "Regression/polynomial_regression.py", "max_stars_repo_name": "BigMani/Machine-learning-projects", "max_stars_repo_head_hexsha": "94574de4d039d67b5699481144023c029104ee1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Regression/polynomial_regression.py", "max_issues_repo_name": "BigMani/Machine-learning-projects", "max_issues_repo_head_hexsha": "94574de4d039d67b5699481144023c029104ee1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Regression/polynomial_regression.py", "max_forks_repo_name": "BigMani/Machine-learning-projects", "max_forks_repo_head_hexsha": "94574de4d039d67b5699481144023c029104ee1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5616438356, "max_line_length": 134, "alphanum_fraction": 0.7307395994, "include": true, "reason": "import numpy", "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811641488385, "lm_q2_score": 0.9073122163480667, "lm_q1q2_score": 0.8759021236645594}}
{"text": "import numpy as np\n\n#############################\n# SINGLE DIMENSIONAL ARRAYS #\n#############################\n\n# This creates our array\nnp_array = np.array([5, 10, 15, 20, 25, 30])\nprint(\"--0--\")\n\n# Gets the unique values\nprint(np.unique(np_array))\nprint(\"--1--\")\n\n# Calculates the standard deviation\nprint(np.std(np_array))\nprint(\"--2--\")\n\n# Calculates the maximum\nprint(np_array.max())\nprint(\"--3--\")\n\n# Squares each value in the array\nprint(np_array ** 2)\nprint(\"--4--\")\n\n# Adds the arrays together element wise\nprint(np_array + np_array)\nprint(\"--5--\")\n\n# The sum of the squares of the elements\nprint(np.sum(np_array ** 2))\nprint(\"--6--\")\n\n# Gives you the shape: (rows, columns)\nprint(np_array.shape)\n\n##########################\n# TWO DIMENSIONAL ARRAYS #\n##########################\n# Create 2d array\nprint(\"--0--\")\nnp_2d_array = np.array([[1,2,3], \n                        [4,5,6]])\nprint(np_2d_array)\n\n# Calculate the transpose, which is when you swap the columns and rows.\nprint(\"--1--\")\nnp_2d_array_T = np_2d_array.T\nprint(np_2d_array_T)\n\n# Print the shape of the array as (number of rows, number of columns)\nprint(\"--3--\")\nprint(np_2d_array.shape)\n\n# Access elements in the 2d array by index. \n# First index is the row number\n# Second index is the column number\n# Index numbers start from 0\nprint(\"--4--\")\nprint(np_2d_array[1,1])\nprint(np_2d_array[0,2])\n\n###########################\n# CALCULATING DOT PRODUCT #\n###########################\nnp_array = np.array([5, 10, 15, 20, 25, 30])\ndot_product = np.dot(np_array, np_array)\nprint(dot_product)\n\n############################\n# GENERATING RANDOM VALUES #\n############################\n# Generage a single random number in range [0,1)\nprint(\"--0--\")\nprint(np.random.rand())\n\n# Generate a matrix of random numbers in range [0,1) with shape (3,2)\nprint(\"--1--\")\nprint(np.random.rand(3,2))\n\n# Low=5, High=15, Size=2. Generate 2 values between 5 and 15 (exclusive)\nprint(\"--0--\")\nprint(np.random.randint(5, 15, 2))\n\n# Low=5, High=15, Size=(3,2). Generate a matrix of shape (3,2) with values between 5 and 15 (exclusive)\nprint(\"--1--\")\nprint(np.random.randint(5, 15, (3,2)))\n\n#####################\n# SAMPLING THE DATA #\n#####################\narray = np.array([1,2,3,4,5])\n\n# Sample 10 data points with replacement. \nprint(\"--0--\")\nprint(np.random.choice(array, 10, replace=True))\n\n# Sample 3 data points without replacement. \n# Sampling without replacement means the same value can’t be sampled more than once\nprint(\"--1--\")\nprint(np.random.choice(array, 3, replace=False))\n\n#############################\n# RANDOMLY SHUFFLING VALUES #\n#############################\nx = [1,2,3,4,5]  # Create a list of 5 elements\nnp.random.shuffle(x)  # Randomly shuffle the order of the elements in the list\n\nprint(x)\n\n# if you want the random selections to be the same every time, you need to set a seed\nnp.random.seed(42)", "meta": {"hexsha": "90e7d7e90808ca89f0e052c37c9ef75f987fd2d6", "size": 2856, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python Basics/numpy_basics.py", "max_stars_repo_name": "python-sonchau/python-visualization", "max_stars_repo_head_hexsha": "eb139aaabbff858663a96f8e19e30f1418e4330c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python Basics/numpy_basics.py", "max_issues_repo_name": "python-sonchau/python-visualization", "max_issues_repo_head_hexsha": "eb139aaabbff858663a96f8e19e30f1418e4330c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python Basics/numpy_basics.py", "max_forks_repo_name": "python-sonchau/python-visualization", "max_forks_repo_head_hexsha": "eb139aaabbff858663a96f8e19e30f1418e4330c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2743362832, "max_line_length": 103, "alphanum_fraction": 0.6078431373, "include": true, "reason": "import numpy", "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811611608242, "lm_q2_score": 0.9073122169746364, "lm_q1q2_score": 0.8759021215583761}}
{"text": "\n# TheoIV\n# 1. Exercise Sheet\n#  -> 4. Shooting Pi\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\n# num_shoots is N from the exercise sheet.\ndef shoot_pi(num_shoots = 10, verbose = True):\n\n    if verbose:\n        print('Shooting PI with ' + str(num_shoots) + ' samples...')\n    \n    # shoot randomly (uniform) at 1x1 area and count hits on inner quarter circle.\n    num_hits = 0\n    for _ in range(num_shoots):\n        point = np.random.rand(2)\n        if (np.linalg.norm(point) < 1):\n            num_hits += 1\n    \n    # compute pi as ratio of hits to all samples\n    # (factor 4 necessary, since we're only shooting at a quarter circle)\n    pi = (num_hits / num_shoots) * 4 \n\n    if verbose:\n        print('PI is approximately ', str(pi), '!', sep='')\n    \n    return pi\n\n\n# num_samples is M from the exercise sheet.\ndef sample_pi_shoots(num_samples = 500, num_shoots_per_sample = 10, verbose = True):\n\n    # shoot pi M times and compute mean + std of results\n    pi_samples = []\n    for _ in range(num_samples):\n        pi_samples.append(shoot_pi(num_shoots_per_sample, False))\n    pi_mean = np.mean(pi_samples, axis=0)\n    pi_std = np.std(pi_samples, axis=0)\n    pi_var = pi_std**2\n\n    if verbose:\n        print('Mean:', round(pi_mean, 3))\n        print('Std: ', round(pi_std, 3))\n        print('Var: ', round(pi_var, 3))\n\n    return (pi_mean, pi_std, pi_var)\n\n\n# show proportionality between standard deviation and 1/sqrt(N)\ndef show_dependency():\n\n    M = 500\n    Ns = []\n    stds = []\n\n    t = time.time()\n\n    for N in range(500, 8_001, 500):\n        (_, std, _) = sample_pi_shoots(M, N, False)\n        Ns.append(N)\n        stds.append(std)\n\n    print('Runtime:', time.time()-t, 'seconds')\n        \n    fig, axs = plt.subplots(3)\n    fig.canvas.set_window_title('Homework 1')\n    fig.suptitle(r'Showing: $\\Delta x \\sim \\frac{1}{\\sqrt{N}}$, M=' + str(M))\n    axs[0].set_xlabel('N', fontsize=15)\n    axs[0].set_ylabel(r'$\\Delta x$', rotation=0, fontsize=15)\n    axs[0].plot(Ns, np.array(stds))\n    axs[1].set_xlabel(r'$log(N)$', fontsize=15)\n    axs[1].set_ylabel(r'$log(\\Delta x)$', rotation=0, fontsize=15)\n    axs[1].plot(np.log(np.array(Ns)), np.log(np.array(stds)))\n    axs[2].set_xlabel(r'$\\frac{1}{\\sqrt{N}}$', fontsize=15)\n    axs[2].set_ylabel(r'$\\Delta x$', rotation=0, fontsize=15)\n    axs[2].plot(1/np.sqrt(np.array(Ns)), np.array(stds))\n    plt.show()\n\nif __name__ == '__main__':\n    # 4a):\n    # shoot_pi(10_000)\n    \n    # 4b):\n    show_dependency()\n", "meta": {"hexsha": "c06fa326b887d6a2c9e55c322e1f46760639d9ac", "size": 2490, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw1.4_shooting-pi/submission.py", "max_stars_repo_name": "tobiaskempe/physics-homework", "max_stars_repo_head_hexsha": "fbb9b270afed4e12d358754ba538c0927979899f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw1.4_shooting-pi/submission.py", "max_issues_repo_name": "tobiaskempe/physics-homework", "max_issues_repo_head_hexsha": "fbb9b270afed4e12d358754ba538c0927979899f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw1.4_shooting-pi/submission.py", "max_forks_repo_name": "tobiaskempe/physics-homework", "max_forks_repo_head_hexsha": "fbb9b270afed4e12d358754ba538c0927979899f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2954545455, "max_line_length": 84, "alphanum_fraction": 0.6120481928, "include": true, "reason": "import numpy", "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377284730286, "lm_q2_score": 0.9136765245890102, "lm_q1q2_score": 0.8757934204386811}}
{"text": "#!/usr/bin/env python3\nimport sys\nimport numpy as np\n\nnp.random.seed(2017)\n\ndef inside_circle(total_count):\n\n    x = np.float32(np.random.uniform(size=total_count))\n    y = np.float32(np.random.uniform(size=total_count))\n\n    radii = np.sqrt(x*x + y*y)\n\n    count = len(radii[np.where(radii<=1.0)])\n\n    return count\n\ndef estimate_pi(n_samples):\n\n    return (4.0 * inside_circle(n_samples) / n_samples)\n\nif __name__=='__main__':\n\n    n_samples = 10000\n    if len(sys.argv) > 1:\n        n_samples = int(sys.argv[1])\n\n    my_pi = estimate_pi(n_samples)\n    sizeof = np.dtype(np.float32).itemsize\n\n    print(\"[serial version] required memory %.3f MB\" % (n_samples*sizeof*3/(1024*1024)))\n    print(\"[serial version] pi is %f from %i samples\" % (my_pi,n_samples))\n", "meta": {"hexsha": "fb4ea59ae54e1669b34f0b2f9174b31668f92f0f", "size": 759, "ext": "py", "lang": "Python", "max_stars_repo_path": "_episodes/code/03_parallel_jobs/serial_numpi.py", "max_stars_repo_name": "elenavataga/HighPer_2018", "max_stars_repo_head_hexsha": "5a8aa02fe8685ea60b90ec5820409df7e0a5f6ad", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_episodes/code/03_parallel_jobs/serial_numpi.py", "max_issues_repo_name": "elenavataga/HighPer_2018", "max_issues_repo_head_hexsha": "5a8aa02fe8685ea60b90ec5820409df7e0a5f6ad", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_episodes/code/03_parallel_jobs/serial_numpi.py", "max_forks_repo_name": "elenavataga/HighPer_2018", "max_forks_repo_head_hexsha": "5a8aa02fe8685ea60b90ec5820409df7e0a5f6ad", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0, "max_line_length": 88, "alphanum_fraction": 0.6679841897, "include": true, "reason": "import numpy", "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.9136765204755286, "lm_q1q2_score": 0.8757934154135604}}
{"text": "\"\"\"\nOne of the central problems in statistics is to make estimations — and quantify\nhow good these estimations are — of the distribution of an entire population\ngiven only a small (random) sample. A classic example is to estimate the average\nheight of all the people in a country when measuring the height of a randomly\nselected sample of people. These kinds of problems are particularly interesting\nwhen the true population distribution, by which we usually mean the mean of the\nwhole population, cannot feasibly be measured. In this case, we must rely on our\nknowledge of statistics and a (usually much smaller) randomly selected sample to\nestimate the true population mean and standard deviation, and also quantify how\ngood our estimations are. It is the latter that is the source of confusion,\nmisunderstanding, and misrepresentation of statistics in the wider world.\n\nThis module illustrates how to estimate the population mean and give a\nconfidence interval fo these estimates.\n\"\"\"\nimport math\nimport pandas as pd\n\nfrom scipy import stats\n\nsample_data = pd.Series([\n    172.3, 171.3, 164.7, 162.9, 172.5, 176.3, 174.8, 171.9,\n    176.8, 167.8, 164.5, 179.7, 157.8, 170.6, 189.9, 185. ,\n    172.7, 165.5, 174.5, 171.5])\n\nsample_mean = sample_data.mean()\nsample_std = sample_data.std()\n\nprint(f\"Mean: {sample_mean}, st. dev: {sample_std}\")\n# Mean: 172.15, st. dev: 7.473778724383846\n\nN = sample_data.count()\nstd_err = sample_std/math.sqrt(N)\n\ncv_95, cv_99 = stats.t.ppf([0.975, 0.995], df=N-1)\n\npm_95 = cv_95 * std_err\npm_99 = cv_99 * std_err\nconf_interval_95 = [sample_mean - pm_95, sample_mean + pm_95] \nconf_interval_99 = [sample_mean - pm_99, sample_mean + pm_99]\n\nprint(f\"95% confidence: {conf_interval_95}\")\nprint(f\"99% confidence: {conf_interval_99}\")\n# 95% confidence: [168.65216388659374, 175.64783611340627]\n# 99% confidence: [167.36884119608774, 176.93115880391227]\n", "meta": {"hexsha": "f70391cad5dd31becb556ae04a51819ce17fe64b", "size": 1881, "ext": "py", "lang": "Python", "max_stars_repo_path": "data-and-statistics/understanding-a-population-using-sampling.py", "max_stars_repo_name": "jeantardelli/math-with-python", "max_stars_repo_head_hexsha": "119bbbc62329c0d834d965232239bd3b39116cc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-16T21:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-16T21:42:42.000Z", "max_issues_repo_path": "data-and-statistics/understanding-a-population-using-sampling.py", "max_issues_repo_name": "jeantardelli/math-with-python", "max_issues_repo_head_hexsha": "119bbbc62329c0d834d965232239bd3b39116cc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data-and-statistics/understanding-a-population-using-sampling.py", "max_forks_repo_name": "jeantardelli/math-with-python", "max_forks_repo_head_hexsha": "119bbbc62329c0d834d965232239bd3b39116cc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0212765957, "max_line_length": 80, "alphanum_fraction": 0.7581073897, "include": true, "reason": "from scipy", "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769049752756, "lm_q2_score": 0.8976952962128457, "lm_q1q2_score": 0.8757707986901913}}
{"text": "import numpy as np\n\n\ndef softmax_numpy(x):\n    \"\"\"\n    :param x:  numpy array of shape (n_samples, n_features)\n    :return: numpy array of shape (n_samples, n_features)\n    Things that are important in this code:\n    1. delegate looping into numpy and don't use for loops in python\n    2. Use broadcasting to to operations on vectors/matrices with different shapes\n    a good article on broadcasting can be found here:\n    http://eli.thegreenplace.net/2015/broadcasting-arrays-in-numpy/\n    3. Direct computation of exp(x) can lead to overflow, use the property:\n        softmax(x) = softmax(x+c) for any constant c\n    \"\"\"\n    x_max = np.max(x, axis=1)\n    x_exp = np.exp((x.transpose() - x_max).transpose())\n    x_exp_sum = np.sum(x_exp, axis=1)\n    return x_exp / x_exp_sum[:, None]\n\n\ndef test_softmax_numpy():\n    \"\"\"\n     Warning: these are not exhaustive.\n    \"\"\"\n    print \"Running basic tests...\"\n    test1 = softmax_numpy(np.array([[1001, 1002], [3, 4]]))\n    assert np.amax(np.fabs(test1 - np.array(\n        [0.26894142, 0.73105858]))) <= 1e-6\n    test2 = softmax_numpy(np.array([[-1001, -1002]]))\n    assert np.amax(np.fabs(test2 - np.array(\n        [0.73105858, 0.26894142]))) <= 1e-6\n    print \"softmax tests pass\\n\"\n\n\nif __name__ == \"__main__\":\n    test_softmax_numpy()\n", "meta": {"hexsha": "52ffb28dae477a8c482d53a634df4e861e28f8c4", "size": 1284, "ext": "py", "lang": "Python", "max_stars_repo_path": "basic-algorithms/softmax_numpy.py", "max_stars_repo_name": "gvenkataraman/machine-learning-tools", "max_stars_repo_head_hexsha": "4e44054e8a3ce2358cb23e706c6ce5144ddb414e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "basic-algorithms/softmax_numpy.py", "max_issues_repo_name": "gvenkataraman/machine-learning-tools", "max_issues_repo_head_hexsha": "4e44054e8a3ce2358cb23e706c6ce5144ddb414e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "basic-algorithms/softmax_numpy.py", "max_forks_repo_name": "gvenkataraman/machine-learning-tools", "max_forks_repo_head_hexsha": "4e44054e8a3ce2358cb23e706c6ce5144ddb414e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7894736842, "max_line_length": 82, "alphanum_fraction": 0.6549844237, "include": true, "reason": "import numpy", "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769085257167, "lm_q2_score": 0.8976952886860978, "lm_q1q2_score": 0.875770794534484}}
{"text": "Vamos continuar nossa trilha em computação simbólica estendendo o conhecimento sobre o tipo `bool`, expressões e testes lógicos.\n\n## Operadores lógicos\n\nVimos que `True` e `False` são os dois valores atribuíves a um objeto de tipo `bool`. Eles são úteis para testar condições, realizar verificações e comparar quantidades. Vamos estudar *operadores de comparação*, *operadores de pertencimento* e *operadores de identidade*.\n\n### Operadores de comparação\n\nA tabela abaixo resume os operadores de comparação utilizados em Python.\n\n| operador | significado | símbolo matemático | \n|---|---|---| \n| `<` | menor do que | $<$ |\n| `<=` | menor ou igual a | $\\leq$ |\n| `>` | maior do que | $>$ |\n| `>=` | maior ou igual a | $\\geq$ |\n| `==` | igual a | $=$ |\n| `!=` | diferente de | $\\neq$ |\n\nPodemos usá-los para comparar objetos. \n\n**Nota:** `==` está relacionado à igualdade, ao passo que `=` é uma atribuição. São conceitos operadores com finalidade distinta. \n\n2 < 3 # o resultado é um 'bool'\n\n5 < 2 # isto é falso\n\n2 <= 2 # isto é verdadeiro\n\n4 >= 3 # isto é verdadeiro\n\n6 != -2 \n\n4 == 4 # isto não é uma atribuição! \n\nPodemos realizar comparações aninhadas:\n\nx = 2\n1 < x < 3\n\n3 > x > 4\n\n2 == x > 3 \n\nAs comparações aninhadas acima são resolvidas da esquerda para a direita e em partes. Isso nos leva a introduzir os seguintes operadores.\n\n| operador | símbolo matemático | significado | uso relacionado a |\n|---|---|---|---|\n| `or` | $\\vee$ | \"ou\" booleano | união, disjunção |\n| `and` | $\\wedge$ | \"e\" booleano | interseção, conjunção |\n| `not` | $\\neg$ | \"não\" booleano | exclusão, negação |\n\n# parênteses não são necessários aqui\n(2 == x) and (x > 3) # 1a. comparação: 'True'; 2a.: 'False'. Portanto, ambas: 'False'\n\n# parênteses não são necessários aqui\n(x < 1) or (x < 2) # nenhuma das duas é True. Portanto, \n\nnot (x == 2) # nega o \"valor-verdade\" que é 'True'\n\nnot x + 1 > 3 # estude a precedência deste exemplo. Por que é 'True'?\n\nnot (x + 1 > 3) # estude a precedência deste exemplo. Por que também é 'True'?\n\n### Operadores de pertencimento\n\nA tabela abaixo resume os operadores de pertencimento. \n\n| operador | significado | símbolo matemático\n|---|---|---|\n| `in` | pertence a | $\\in$ |\n| `not in` | não pertence a | $\\notin$ |\n\nEles terão mais utilidade quando falarmos sobre sequências, listas. Neste momento, vejamos exemplos com objetos `str`.\n\n'2' in '2 4 6 8 10' # o caracter '2' pertence à string\n\nfrase_teste = 'maior do que' \n'maior' in frase_teste\n\n'menor' in frase_teste # a palavra 'menor' está na frase\n\n1 in 2 # 'in' e 'not in' não são aplicáveis aqui\n\n### Operadores de identidade\n\nA tabela abaixo resume os operadores de identidade. \n\n| operador | significado \n|---|---|\n| `is` | \"aponta para o mesmo objeto\" \n| `is not` | \"não aponta para o mesmo objeto\" |\n\nEsses operadores são úteis para verificar se duas variáveis se referem ao mesmo objeto. Exemplo: \n\n```python\na is b\na is not b\n```\n\n- `is` é `True` se `a` e `b` se referem ao mesmo objeto; `False`, caso contrário.\n- `is not` é `False` se `a` e `b` se referem ao mesmo objeto; `True`, caso contrário.\n\na = 2\nb = 3\na is b # valores distintos\n\na = 2\nb = a\na is b # mesmos valores\n\na = 2\nb = 3\na is not b # de fato, valores não são distintos\n\na = 2\nb = a\na is not b # de fato, valores são distintos\n\n## Equações simbólicas\n\nEquações simbólicas podem ser formadas por meio de `Eq` e não com `=` ou `==`.\n\n# importação\nfrom sympy.abc import a,b\nimport sympy as sy \nsy.init_printing(pretty_print=True)\n\nsy.Eq(a,b) # equação simbólica\n\nsy.Eq(sy.cos(a), b**3) # os objetos da equação são simbólicos\n\n### Resolução de equações algébricas simbólicas\n\nPodemos resolver equações algébricas da seguinte forma:\n\n```python\nsolveset(equação,variável,domínio)\n```\n\n**Exemplo:** resolva $x^2 = 1$ no conjunto $\\mathbb{R}$.\n\nfrom sympy.abc import x\nsy.solveset( sy.Eq( x**2, 1), x,domain=sy.Reals)\n\nPodemos reescrever a equação como: $x^2 - 1 = 0$.\n\nsy.solveset( sy.Eq( x**2 - 1, 0), x,domain=sy.Reals)\n\nCom `solveset`, não precisamos de `Eq`. Logo, a equação é passada diretamente.\n\nsy.solveset( x**2 - 1, x,domain=sy.Reals)\n\n**Exemplo:** resolva $x^2 + 1 = 0$ no conjunto $\\mathbb{R}$.\n\nsy.solveset( x**2 + 1, x,domain=sy.Reals) # não possui solução real\n\n**Exemplo:** resolva $x^2 + 1 = 0$ no conjunto $\\mathbb{C}$.\n\nsy.solveset( x**2 + 1, x,domain=sy.Complexes) # possui soluções complexas\n\n**Exemplo:** resolva $\\textrm{sen}(2x) = 3 + x$ no conjunto $\\mathbb{R}$.\n\nsy.solveset( sy.sin(2*x) - x - 3,x,sy.Reals) # a palavra 'domain' também pode ser omitida.\n\nO conjunto acima indica que nenhuma solução foi encontrada.\n\n**Exemplo:** resolva $\\textrm{sen}(2x) = 1$ no conjunto $\\mathbb{R}$.\n\nsy.solveset( sy.sin(2*x) - 1,x,sy.Reals)\n\n## Expansão, simplificação e fatoração de polinômios\n\nVejamos exemplos de polinômios em uma variável. \n\na0, a1, a2, a3 = sy.symbols('a0 a1 a2 a3') # coeficientes\nP3x = a0 + a1*x + a2*x**2 + a3*x**3 # polinômio de 3o. grau em x\nP3x\n\nb0, b1, b2, b3 = sy.symbols('b0 b1 b2 b3') # coeficientes\nQ3x = b0 + b1*x + b2*x**2 + b3*x**3 # polinômio de 3o. grau em x\nQ3x\n\nR3x = P3x*Q3x # produto polinomial\nR3x\n\nR3x_e = sy.expand(R3x) # expande o produto\nR3x_e\n\nsy.simplify(R3x_e) # simplify às vezes não funciona como esperado\n\nsy.factor(R3x_e) # 'factor' pode funcionar melhor\n\n# simplify funciona para casos mais gerais \nident_trig = sy.sin(x)**2 + sy.cos(x)**2\nident_trig\n\nsy.simplify(ident_trig)\n\n## Identidades trigonométricas \n\nPodemos usar `expand_trig` para expandir funções trigonométricas. \n\nsy.expand_trig( sy.sin(a + b) ) # sin(a+b)\n\nsy.expand_trig( sy.cos(a + b) ) # cos(a+b)\n\nsy.expand_trig( sy.sec(a - b) ) # sec(a-b)\n\n## Propriedades de logaritmo\n\n\nCom `expand_log`, podemos aplicar propriedades válidas de logaritmo.\n\nsy.expand_log( sy.log(a*b) )\n\nA identidade não foi validada pois `a` e `b` são símbolos irrestritos.\n\na,b = sy.symbols('a b',positive=True) # impomos que a,b > 0\n\nsy.expand_log( sy.log(a*b) ) # identidade validada\n\nsy.expand_log( sy.log(a/b) )\n\nm = sy.symbols('m', real = True) # impomos que m seja um no. real\nsy.expand_log( sy.log(a**m) )\n\nCom `logcombine`, compactamos as propriedades.\n\nsy.logcombine( sy.log(a) + sy.log(b) ) # identidade recombinada\n\n## Fatorial \n\nA função `factorial(n)` pode ser usada para calcular o fatorial de um número.\n\nsy.factorial(m)\n\nsy.factorial(m).subs(m,10) # 10! \n\nsy.factorial(10) # diretamente\n\n**Exemplo:** Sejam $m,n,x$ inteiros positivos. Se $f(m) = 2m!$, $g(n) = \\frac{(n + 1)!}{n^2!}$ e $h(x) = f(x)g(x)$, qual é o valor de $h(2)$? \n\nfrom sympy.abc import m,n,x\n\nf = 2*sy.factorial(m)\ng = sy.factorial(n + 1)/sy.factorial(n**2)\n\nh = (f.subs(m,x)*g.subs(n,x)).subs(x,4)\nh\n\n## Funções anônimas \n\nA terceira classe de funções que iremos aprender é a de *funções anônimas*. Uma **função anônima** em Python consiste em uma função cujo nome não é explicitamente definido e que pode ser criada em apenas uma linha de código para executar uma tarefa específica.\n\nFunções anônimas são baseadas na palavra-chave `lambda`. Este nome tem inspiração em uma área da ciência da computação chamada de cálculo-$\\lambda$.\n\nUma função anônima tem a seguinte forma: \n\n```python\nlambda lista_de_parâmetros: expressão\n```\n\nFunções anônimas podem são bastante úteis para tornar um código mais conciso. \n\nPor exemplo, na aula anterior, definimos a função\n\n```python\ndef repasse(V): \n    return 0.0103*V\n```\n\npara calcular o repasse financeiro ao corretor imobiliário. \n\nCom uma função anônima, a mesma função seria escrita como:\n\nrepasse = lambda V: 0.0103*V\n\nNão necessariamente temos que atribui-la a uma variável. Neste caso, teríamos:\n\nlambda V: 0.0103*V\n\nPara usar a função, passamos um valor:\n\nrepasse(100000) # repasse sobre R$ 100.000,00\n\nO modelo completo com \"bonificação\" seria escrito como:\n\nr3 = lambda c,V,b: c*V + b # aqui há 3 parâmetros necessários\n\nRedefinamos objetos simbólicos:\n\nfrom sympy.abc import b,c,V\nr3(b,c,V)\n\nO resultado anterior continua sendo um objeto simbólico, mas obtido de uma maneira mais direta. Podemos usar funções anônimas para tarefas de menor complexidade.\n\n## \"Lambdificação\" simbólica\n\nUsando `lambdify`, podemos converter uma expressão simbólica do *sympy* para uma expressão que pode ser numericamente avaliada em outra biblioteca. Essa função desempenha papel similar a uma função *lambda* (anônima).\n\nexpressao = sy.sin(x) + sy.sqrt(x) # expressão simbólica\nf = sy.lambdify(x,expressao,\"math\") # lambdificação para o módulo math\nf(0.2) # avalia\n\nPara avaliações simples como a anterior, podemos usar `evalf` e `subs`. A lambdificação será útil quando quisermos avaliar uma função em vários pontos, por exemplo. Na próxima aula, introduziremos sequencias e listas. Para mostrar um exemplo de lambdificação melhor veja o seguinte exemplo.\n\nfrom numpy import arange # importação de função do módulo numpy\n\nX = arange(40) # gera 40 valores de 0 a 39\n\nX\n\nf = sy.lambdify(x,expressao,\"numpy\")(X) # avalia 'expressao' em X\nf", "meta": {"hexsha": "64344ea11680044f5a90fa4f942a1065a2c12eb3", "size": 8912, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/ipynb/02b-computacao-simbolica.py", "max_stars_repo_name": "gcpeixoto/FMECD", "max_stars_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/jupyter_execute/ipynb/02b-computacao-simbolica.py", "max_issues_repo_name": "gcpeixoto/FMECD", "max_issues_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/ipynb/02b-computacao-simbolica.py", "max_forks_repo_name": "gcpeixoto/FMECD", "max_forks_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2920634921, "max_line_length": 290, "alphanum_fraction": 0.6958034111, "include": true, "reason": "from numpy,import sympy,from sympy", "num_tokens": 3062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701655, "lm_q2_score": 0.9353465175010824, "lm_q1q2_score": 0.8757509178519814}}
{"text": "################################################################## clase ######################################################################################\n# Ejercicio 1:\n\nimport numpy as np\nfrom numpy.linalg import inv\nfrom numpy.linalg import solve\n# 1a.) Tiene un sistema de 3 ecuaciones lineales Ax=B, donde:\n\nA=np.matrix([[8.,2.,1.],[1.,-2.,-3.],[-1.,1.,2,]])\nprint(A)\n\nB=np.array([-8.,0.,3.])\n\n\n# Implemente el algoritmo de eliminacion gaussiana para resolver este sistema de ecuaciones. IMPRIMA la matriz aumentada paso a paso. IMPRIMA su vector solucion\ndef GJ(A,B):\n    NA=len(A)\n    paso=0\n    for c in range(NA):\n        for r in range(NA):\n            if(r==c):\n                B[r]=B[r]/A[r,c]\n                A[r,:]=A[r,:]/A[r,c]\n                paso+=1\n                print('Paso',paso)\n                print(A)\n            if(r>c):\n                B[r]=B[r]-(B[c]*A[r,c])\n                A[r,:]=A[r,:]-(A[c,:]*A[r,c])\n                paso+=1\n                print('Paso',paso)\n                print(A)\n            \n    for c in range(NA):\n        for r in range(NA):\n            if(r<c):\n                B[r]=B[r]-(B[c]*A[r,c])\n                A[r,:]=A[r,:]-(A[c,:]*A[r,c])\n                paso+=1\n                print('Paso',paso)\n                print(A)\n    print('El vector solución es:',B)\n    \nGJ(A,B)\n            \n\n\n# IMPRIMA la solucion encontrada usando los paquetes de numpy\nprint('Usando los paquetes de numpy la solución da:',solve(A,B))\n\n\n# 1b). Repita lo anterior para un sistema de ecuaciones mas general: Imprimiendo los pasos intermedios.\n#Escriba aca un codigo GENERAL de eliminacion Gaussiana para resolver el sistema Ax=B.\n\nprint('')\nprint('PUNTO 1B')\nprint('')\n\nN=np.random.randint(3 , 8)\nprint ('Matriz de tamaño:',N,'x',N)\nArreglo=(np.random.random((N,N))*10.0)-5.0\nB=(np.random.random((N,1))*10.0)-5.0\n\nprint ('Matriz A =')\nprint (Arreglo)\nprint ('B =')\nprint (B)\nprint('')\nprint('Solución')\nGJ(Arreglo,B)\n\n# IMPRIMA la solucion encontrada usando los paquetes de numpy \n\nprint('Usando los paquetes de numpy la solución da:',solve(Arreglo,B))\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "d51cb4afb1206b279d338a7cd8c82aa3acf5fef3", "size": 2103, "ext": "py", "lang": "Python", "max_stars_repo_path": "S3C1/CendalesLuis_S3C1.py", "max_stars_repo_name": "LuisCendales/M-todos_Computacionales", "max_stars_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "S3C1/CendalesLuis_S3C1.py", "max_issues_repo_name": "LuisCendales/M-todos_Computacionales", "max_issues_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "S3C1/CendalesLuis_S3C1.py", "max_forks_repo_name": "LuisCendales/M-todos_Computacionales", "max_forks_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6292134831, "max_line_length": 160, "alphanum_fraction": 0.504041845, "include": true, "reason": "import numpy,from numpy", "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762060829178, "lm_q2_score": 0.9124361670249624, "lm_q1q2_score": 0.875721616038954}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nN = 101\nL = 2.0\nmesh = np.linspace(-L,L,N)\n\n# Plot quadratic loss for comparison\nPLOT_QUADRATIC = True\n\n# Plot sequence of hyperparameter values\nPLOT_SEQ = True\n\nnormal_loss = lambda x, s:  np.power(x,2)/(2*np.power(s,2)) + 0.5*np.log(2*np.pi*np.power(s,2))\nlaplace_loss = lambda x, b:  np.abs(x)/b + np.log(2*b)\ncauchy_loss = lambda x, g: np.log( np.pi*g*(1.0 + np.power(x,2)/np.power(g,2)) )\nquadratic_loss = lambda x: x*x\n\ntheta = 0.5\nnormal_vals = np.array([normal_loss(x,theta) for x in mesh])\nlaplace_vals = np.array([laplace_loss(2*x,theta) for x in mesh])\ncauchy_vals = np.array([cauchy_loss(2*x,theta) for x in mesh])\nquadratic_vals = np.array([quadratic_loss(x) for x in mesh])\n\n\nfig = plt.figure()\nax = fig.gca()\nplt.plot(mesh, normal_vals, c='C0', label=\"Normal\")\nplt.plot(mesh, laplace_vals, c='C1', label=\"Laplace\")\nplt.plot(mesh, cauchy_vals, c='C2', label=\"Cauchy\")\nif PLOT_QUADRATIC:\n    plt.plot(mesh, quadratic_vals, c='C3', label=\"Quadratic\")\nax.legend(fontsize=24)\nplt.show()\n\nif PLOT_SEQ:\n    \n    normal_vals = np.array([normal_loss(x,theta) for x in mesh])\n    laplace_vals = np.array([laplace_loss(2*x,theta) for x in mesh])\n    cauchy_vals = np.array([cauchy_loss(2*x,theta) for x in mesh])\n\n    for rate, title in [[0.9,\"Decreasing\"],[1.1,\"Increasing\"]]:\n        for loss, label, color in [[normal_loss, \"Normal\", \"C0\"],[laplace_loss, \"Laplace\", \"C1\"],[cauchy_loss, \"Cauchy\", \"C2\"]]:\n            if label == \"Normal\":\n                theta = 1.0\n            elif label == \"Laplace\":\n                theta = 0.5\n            else:\n                theta = 0.5\n            vals = np.array([loss(x,theta) for x in mesh])\n            plt.plot(mesh, vals, c=color, label=label, linewidth=3.0)\n            plt.plot(mesh, quadratic_vals, c='C3', label=\"Quadratic\")\n\n            for k in range(1,11):\n                theta = theta*rate\n                vals = np.array([loss(x,theta) for x in mesh])\n                plt.plot(mesh, vals, c=color, linestyle=\"dashed\", label=None)\n            plt.title(title + \" \" + label + \" Paramater\", fontsize=24)\n            plt.show()\n", "meta": {"hexsha": "22bdef276df697d6c375510e35e9b01124e0b683", "size": 2140, "ext": "py", "lang": "Python", "max_stars_repo_path": "Poisson_Varying_Domain/Evaluation/Loss_Functions/plot_loss_functions.py", "max_stars_repo_name": "nw2190/ConvPDE", "max_stars_repo_head_hexsha": "86f3fa67d64a6c56f3dff4d32999fe70db30795e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2019-05-21T16:35:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T06:27:48.000Z", "max_issues_repo_path": "Poisson_Varying_Domain/Evaluation/Loss_Functions/plot_loss_functions.py", "max_issues_repo_name": "nw2190/ConvPDE", "max_issues_repo_head_hexsha": "86f3fa67d64a6c56f3dff4d32999fe70db30795e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Poisson_Varying_Domain/Evaluation/Loss_Functions/plot_loss_functions.py", "max_forks_repo_name": "nw2190/ConvPDE", "max_forks_repo_head_hexsha": "86f3fa67d64a6c56f3dff4d32999fe70db30795e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-05-22T05:19:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T07:20:21.000Z", "avg_line_length": 35.6666666667, "max_line_length": 128, "alphanum_fraction": 0.6130841121, "include": true, "reason": "import numpy", "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762057376384, "lm_q2_score": 0.9124361563100186, "lm_q1q2_score": 0.8757216026047033}}
{"text": "import numpy as np\nfrom scipy import signal\n\n# source: https://stackoverflow.com/questions/40703751/using-fourier-transforms-to-do-convolution?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa\n\nx = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 3, 0], [0, 0, 0, 1]]\nx = np.array(x)\ny = [[4, 5], [3, 4]]\ny = np.array(y)\n\nstandard_conv = signal.convolve2d(x, y, 'full')\n\nprint(\"conv:\", standard_conv)\n\ns1 = np.array(x.shape)\ns2 = np.array(y.shape)\nprint(\"s1: \", s1)\nprint(\"s2: \", s2)\n\nsize = s1 + s2 - 1\nprint(\"size: \", size)\n\nfsize = 2 ** np.ceil(np.log2(size)).astype(int)\nfslice = tuple([slice(0, int(sz)) for sz in size])\nprint(\"fslice: \", fslice)\n\n# Along each axis, if the given shape (fsize) is smaller than that of the input, the input is cropped.\n# If it is larger, the input is padded with zeros. if s is not given, the shape of the input along the axes\n# specified by axes is used.\nnew_x = np.fft.fft2(x, fsize)\n\nnew_y = np.fft.fft2(y, fsize)\nresult = np.fft.ifft2(new_x * new_y)\nprint(\"first result: \", result)\n\nresult = np.fft.ifft2(new_x * new_y)[fslice].copy()\nresult_int = np.array(result.real, np.int32)\n\nmy_result = np.array(result, np.double)\nprint(\"my_result (doubles): \", my_result)\n\nprint(\"fft for my method (ints):\", result_int)\nprint(\"is my method correct (for ints): \", np.array_equal(result_int, standard_conv))\nprint(\"fft for my method (doubles):\", result)\n\nprint(\"fft with int32 output:\", np.array(signal.fftconvolve(x, y), np.int32))\nlib_result = np.array(signal.fftconvolve(x, y), np.double)\nprint(\"fft with double output:\", np.allclose(my_result, lib_result, atol=1e-12))\n\n# the correct way is to take the amplitude:  the abs of a complex number gives us its amplitude/mangnitude\nlib_magnitude = np.abs(signal.fftconvolve(x, y))\nprint(\"lib_magnitude: \", lib_magnitude)\nmy_magnitude = np.abs(result)\nprint(\"is the magnitude correct: \", np.allclose(my_magnitude, lib_magnitude, atol=1e-12))\n", "meta": {"hexsha": "9b416da8134adb025da81d1a2ab23ef76125b524", "size": 1931, "ext": "py", "lang": "Python", "max_stars_repo_path": "cnns/nnlib/test/ConvDirectFFTsimple.py", "max_stars_repo_name": "adam-dziedzic/time-series-ml", "max_stars_repo_head_hexsha": "81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-25T13:19:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-25T13:19:46.000Z", "max_issues_repo_path": "cnns/nnlib/test/ConvDirectFFTsimple.py", "max_issues_repo_name": "adam-dziedzic/time-series-ml", "max_issues_repo_head_hexsha": "81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cnns/nnlib/test/ConvDirectFFTsimple.py", "max_forks_repo_name": "adam-dziedzic/time-series-ml", "max_forks_repo_head_hexsha": "81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1090909091, "max_line_length": 170, "alphanum_fraction": 0.7058518902, "include": true, "reason": "import numpy,from scipy", "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762057376384, "lm_q2_score": 0.9124361539289197, "lm_q1q2_score": 0.875721600319415}}
{"text": "import numpy as np\nfrom sympy import simplify, integrate, zeros, S, Matrix, symbols, pi, cos, sin\nfrom .funcs_aproximacion import producto_asecas\n\n\ndef producto_escalar_trigono(f, g, var=symbols('x'), a=-pi, b=pi, I=None, numeric=False):\n    \"\"\"Aplica el producto escalar <f,g> = 1/(2pi) ∫_[-pi]^[pi] f.g\n\n    Args:\n        f (funcion): f\n        g (funcion): g\n        var (variable): variable de integración\n        a (int, optional): limite inferior de integracion. Defaults to 0.\n        b (int, optional): limite superior de integracion. Defaults to 1.\n        I (list, optional): Si no es None, lista de valores sobre los que hacer un sumatorio discreto. Defaults to None.\n        numeric (bool, optional): si True, realiza una aproximación numérica de la integral usando un método de sympy.\n\n    Returns:\n        funcion, float: Valor del producto escalar. Se devuelve como funcion si tiene variables.\n    \"\"\"\n    prod = producto_asecas(f, g, var, a, b, I, numeric)\n    return simplify(prod / (2 * pi))\n\n\ndef coefs_fourier(f, var=symbols('x'), I=[0, 1], n_coefs=2):\n    \"\"\"Genera los coeficientes de la serie de fourier. Esta es la versión continua, donde los coeficientes se calculan usando la expresión de la integral.\n\n    Args:\n        f (funcion): Función a aproximar\n        var (variable, optional): Variable de la función. Defaults to symbols('x').\n        I (list, optional): Intervalo de aproximación de la función. Defaults to [0, 1].\n        n_coefs (int, optional): Número de coeficientes de la serie a generar. Defaults to 2.\n\n    Returns:\n        dict_coefs: {a_0, a_1, b_1, a_2, b_2, ...}\n    \"\"\"\n    dict_coefs = {}\n    dict_coefs['a0'] = simplify(1 / pi * integrate(f, (var, I[0], I[1])))\n    for i in range(1, n_coefs):\n        dict_coefs[f'a{i}'] = simplify(1 / pi * integrate(f * cos(i * var), (var, I[0], I[1])))\n        dict_coefs[f'b{i}'] = simplify(1 / pi * integrate(f * sin(i * var), (var, I[0], I[1])))\n\n    return dict_coefs\n\n\ndef coefs_fourier_discr(f, var=symbols('x'), I=[0, 1], n_coefs=2, m=10):\n    \"\"\"Genera los coeficientes de la serie de fourier. Esta es la versión donde la integral se aproxima como un sumatorio discreto de m términos sobre I.\n\n    Args:\n        f (funcion): Función a aproximar\n        var (variable, optional): Variable de la función. Defaults to symbols('x').\n        I (list, optional): Intervalo de aproximación de la función. Defaults to [0, 1].\n        n_coefs (int, optional): Número de coeficientes de la serie a generar. Defaults to 2.\n        m (int, optional): Número de elementos en los que dividir I para el sumatorio.\n\n    Returns:\n        dict_coefs: {a_0, a_1, b_1, a_2, b_2, ...}\n    \"\"\"\n    dict_coefs = {}\n    lista_xk = np.linspace(I[0], I[1], 2 * m)\n\n    dict_coefs['a0'] = np.sum([f.subs(var, xk) * cos(0 * xk) for xk in lista_xk]) / m\n    for i in range(1, n_coefs):\n        dict_coefs[f'a{i}'] = np.sum([f.evalf(subs={var: S(xk)}) * cos(S(i) * xk) for xk in lista_xk]) / m\n        dict_coefs[f'b{i}'] = np.sum([f.evalf(subs={var: S(xk)}) * sin(S(i) * xk) for xk in lista_xk]) / m\n\n    return dict_coefs\n\n\ndef serie_fourier(f, var=symbols('x'), I=[0, 1], n_coefs=3, discreto=False, m=10):\n    \"\"\"Genera la serie de Fourier para la función f sobre un intervalo.\n\n    Args:\n        f (funcion): Función a aproximar\n        var (variable, optional): Variable de la función. Defaults to symbols('x').\n        I (list, optional): Intervalo de aproximación de la función. Defaults to [0, 1].\n        n_coefs (int, optional): Número de coeficientes de la serie a generar. Defaults to 2.\n        discreto (bool, optional): Si True, genera una aproximación discreta de los coeficientes empleando m términos.\n        m (int, optional): Número de elementos en los que dividir I para el sumatorio.\n\n    Returns:\n        funcion: Función polinómica con la serie de Fourier.\n    \"\"\"\n    if discreto:\n        dict_coefs = coefs_fourier_discr(f, var, I, n_coefs, m)\n    else:\n        dict_coefs = coefs_fourier(f, var, I, n_coefs)\n\n    serie_fourier = dict_coefs['a0'] / 2\n    for i in range(1, n_coefs):\n        serie_fourier += dict_coefs[f'a{i}'] * cos(i * var) + dict_coefs[f'b{i}'] * sin(i * var)\n\n    return simplify(serie_fourier)\n", "meta": {"hexsha": "42e38f4d85b57b32753e64a3a1d40c312cc99c58", "size": 4209, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/anmi/T4/funcs_fourier.py", "max_stars_repo_name": "alexmascension/ANMI", "max_stars_repo_head_hexsha": "9c51a497a5fa2650f1429f847c7f9df69271168b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-30T23:30:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T23:30:45.000Z", "max_issues_repo_path": "src/anmi/T4/funcs_fourier.py", "max_issues_repo_name": "alexmascension/ANMI", "max_issues_repo_head_hexsha": "9c51a497a5fa2650f1429f847c7f9df69271168b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-04-11T20:39:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-13T17:45:43.000Z", "max_forks_repo_path": "src/anmi/T4/funcs_fourier.py", "max_forks_repo_name": "alexmascension/ANMI", "max_forks_repo_head_hexsha": "9c51a497a5fa2650f1429f847c7f9df69271168b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-30T23:31:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T23:31:11.000Z", "avg_line_length": 44.7765957447, "max_line_length": 154, "alphanum_fraction": 0.6402946068, "include": true, "reason": "import numpy,from sympy", "num_tokens": 1286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745211, "lm_q2_score": 0.9124361521430956, "lm_q1q2_score": 0.8757215965051458}}
{"text": "import matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\nimport torch\nimport torch.optim as optim\nimport utils\nimport math\n\n\nprint('定义 adagrad')\neta = 0.4\n\n\ndef adagrad_2d(x1, x2, s1, s2):\n    g1, g2, eps = 0.2 * x1, 4 * x2, 1e-6\n    s1 += g1 ** 2\n    s2 += g2 ** 2\n    x1 -= eta / math.sqrt(s1 + eps) * g1\n    x2 -= eta / math.sqrt(s2 + eps) * g2\n    return x1, x2, s1, s2\n\n\ndef f_2d(x1, x2):\n    return 0.1 * x1 ** 2 + 2 * x2 ** 2\n\n\nprint('lr= 0.4 的轨迹')\nutils.show_trace_2d(f_2d, utils.train_2d(adagrad_2d))\nprint('lr= 2.0 的轨迹，更快逼近最优解')\neta = 2.0\nutils.show_trace_2d(f_2d, utils.train_2d(adagrad_2d))\n\nprint('自行实现 Adagrad')\n\n\nfeatures, labels = utils.get_nasa_data()\n\n\ndef init_adagrad_states():\n    s_w = torch.zeros((features.shape[1], 1), dtype=torch.float32)\n    s_b = torch.zeros(1, dtype=torch.float32)\n    return (s_w, s_b)\n\n\ndef adagrad(params, states, hyperparams):\n    eps = 1e-6\n    for p, s in zip(params, states):\n        s.data += (p.grad.data ** 2)\n        p.data -= hyperparams['lr'] * p.grad.data / torch.sqrt(s + eps)\n\n\nprint('Adagrad 进行优化')\nutils.train_opt(adagrad, init_adagrad_states(), {'lr': 0.1}, features, labels)\n\nprint('简洁实现')\nutils.train_opt_pytorch(optim.Adagrad, {'lr': 0.1}, features, labels)\n", "meta": {"hexsha": "ebf6df93fc197ac6d42d211e63ac996ed421fd1f", "size": 1276, "ext": "py", "lang": "Python", "max_stars_repo_path": "d2l/42_adagrad.py", "max_stars_repo_name": "wdxtub/deep-learning-note", "max_stars_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2019-03-27T20:17:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T23:20:31.000Z", "max_issues_repo_path": "d2l/42_adagrad.py", "max_issues_repo_name": "wdxtub/deep-learning-note", "max_issues_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "d2l/42_adagrad.py", "max_forks_repo_name": "wdxtub/deep-learning-note", "max_forks_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-03-31T10:28:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:25:40.000Z", "avg_line_length": 21.6271186441, "max_line_length": 78, "alphanum_fraction": 0.6465517241, "include": true, "reason": "import numpy", "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799462157138, "lm_q2_score": 0.9086179037377831, "lm_q1q2_score": 0.8757077143950353}}
{"text": "\"\"\"\nEvaluate the integral of x * exp(-a * x) with a = 2 on [0,1].\n    Determine the relative error as a function of step size N and\n    find N such that the approximate integral isaccurate to\n    five significant digits\n\nSolution to Problem Set 2, Problem 1\n\nTo run:\n    python trap_rule_2_1.py\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#original trapezoidal rule; loop from 1 to n - 1\ndef trapezoidalRule(func, a, b, n, *P):\n        h = (b - a) / n\n        Int_part1 = func(a, *P) + func(b, *P)\n        Int_part2 = 0\n        for i in range(1, n):\n            x = a + i * h\n            Int_part2 += func(x, *P)\n        I = (h / 2) * (Int_part1 + 2 * Int_part2)\n        return I\n#for part 4 of problem 1: modify step d to loop from 0 to n\ndef trapezoidalRule_modified(func, a, b, n, *P):\n        h = (b - a) / n\n        Int_part1 = func(a, *P) + func(b, *P)\n        Int_part2 = 0\n        for i in range(0, n+1):\n            x = a + i * h\n            Int_part2 += func(x, *P)\n        I = (h / 2) * (Int_part1 + 2 * Int_part2)\n        return I\n\n#the function to be integrated\ndef integrand(x,alpha):\n    return x*np.exp(-alpha*x)\n#the indefinite integral\ndef int_indef(x,alpha):\n    return ((-x/alpha) - (1./alpha**2)) * np.exp(-alpha*x)\n\nalpha = 2.0\n#integral boundaries\nxmax = 1.0\nxmin = 0.0\n\n#analytic result\nint_analytic = int_indef(xmax,alpha)-int_indef(xmin,alpha)\n#build the n vs relErr arrays\nN = np.array([50, 100, 200, 400])\nrel_err = np.zeros(4)\nfor i in range(N.shape[0]):\n    int_trap = trapezoidalRule(integrand, xmin, xmax, N[i], alpha)\n    rel_err[i] = np.abs(int_trap - int_analytic) / int_analytic\n\n\n#fit a line to log(N), log(rel_err) to get slope/convergence rate\nm, b = np.polyfit(np.log(N), np.log(rel_err), 1)\nprint(\"convergence rate regular trapezoidal rule %.3f\" % m)\nplt.xlabel(\"log(number of steps)\")\nplt.ylabel(\"log(relative Error)\")\nplt.yscale('log')\nplt.xscale('log')\n#plot relative error\nplt.plot(N, rel_err, marker ='x',label='Regular Trapezoidal Rule',color ='b')\n# and best fit\nplt.plot(N,np.exp(np.log(N)*m+b),linestyle = \"--\",color ='b')\n\n#recalcuate the n and relErr arrays, but with the modified step d\nrel_err_mod = np.zeros(4)\nfor i in range(N.shape[0]):\n    int_trap = trapezoidalRule_modified(integrand, xmin, xmax, N[i], alpha)\n    rel_err_mod[i] = np.abs(int_trap - int_analytic) / int_analytic\n\n\n#fit a line to log(N), log(rel_err) to get slope/convergence rate\nm, b = np.polyfit(np.log(N), np.log(rel_err_mod), 1)\nprint(\"convergence rate modified trapezoidal rule %.3f\" % m)\n\n#plot results\nplt.plot(N, rel_err_mod, marker ='o',label='Modified Trapezoidal Rule',color ='r')\n# and best fit\nplt.plot(N,np.exp(np.log(N)*m+b),linestyle = \"--\",color ='r')\nplt.legend()\nplt.show()\n\n#find an n accurate to at least five significant digits\nN_5 = 10\nint_trap = trapezoidalRule(integrand, xmin, xmax, N_5, alpha)\nprint(\"finding N_5...\")\nwhile np.abs(int_trap - int_analytic) / int_analytic >= 5.e-6:\n    N_5 += 1\n    int_trap = trapezoidalRule(integrand, xmin, xmax, N_5, alpha)\n#    print(\"\\tN=%d\\t I=%.7e\\taccuracy=%.6e\"%(N_5,int_trap,np.abs(int_trap - int_analytic) / int_analytic))\n#print the results\nprint(\"Integration with N = %d has relative error %e\\naccurate to at least 5 digits!\"%(N_5,np.abs(int_trap - int_analytic) / int_analytic))\n", "meta": {"hexsha": "5e2a7f581b4f1916cd82611d8f07dc077740b47f", "size": 3293, "ext": "py", "lang": "Python", "max_stars_repo_path": "Problem Sets/Problem Set 2/Solutions/trap1D_ps2_1.py", "max_stars_repo_name": "astroarshn2000/PHYS305S20", "max_stars_repo_head_hexsha": "18f4ebf0a51ba62fba34672cf76bd119d1db6f1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-10T06:45:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T13:50:11.000Z", "max_issues_repo_path": "Problem Sets/Problem Set 2/Solutions/trap1D_ps2_1.py", "max_issues_repo_name": "astroarshn2000/PHYS305S20", "max_issues_repo_head_hexsha": "18f4ebf0a51ba62fba34672cf76bd119d1db6f1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Problem Sets/Problem Set 2/Solutions/trap1D_ps2_1.py", "max_forks_repo_name": "astroarshn2000/PHYS305S20", "max_forks_repo_head_hexsha": "18f4ebf0a51ba62fba34672cf76bd119d1db6f1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.93, "max_line_length": 139, "alphanum_fraction": 0.6538111145, "include": true, "reason": "import numpy", "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474142844409, "lm_q2_score": 0.917302651107873, "lm_q1q2_score": 0.8757006039963936}}
{"text": "import numpy as np\n\ndef multivariate_gaussian_pdf(X : np.array, mu : np.array, cov : np.array) -> float:\n    \"\"\"\n    Computes the likelihood of a vector w.r.t. the multivariate gaussian PDF.\n\n    Parameters\n    ==========\n    X: numpy.array.\n        The input array.\n    mu: numpy.array.\n        The mean array.\n    cov: numpy.array.\n        The covariance array.\n    Returns\n    ===========\n    p: float.\n        The likelihood of X given the mean mu and covariance cov.\n    \"\"\"\n    diff = X.reshape(-1,1) - mu.reshape(-1,1)\n    exp_factor = float( - 0.5 * np.dot( np.dot ( diff.T, np.linalg.inv(cov) ), diff ) )\n    norm_factor = float ( np.linalg.det(2 * np.pi * cov) ** (-0.5) )\n    p = norm_factor * np.exp( exp_factor )\n    return p", "meta": {"hexsha": "cc82c51039eee89b5c9a97e9e5a47ad59b7ee32e", "size": 738, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/modules/pdf.py", "max_stars_repo_name": "cabraile/DMLAV", "max_stars_repo_head_hexsha": "fd5bea5a97a7012da6260fffd402db799a442e4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/modules/pdf.py", "max_issues_repo_name": "cabraile/DMLAV", "max_issues_repo_head_hexsha": "fd5bea5a97a7012da6260fffd402db799a442e4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/modules/pdf.py", "max_forks_repo_name": "cabraile/DMLAV", "max_forks_repo_head_hexsha": "fd5bea5a97a7012da6260fffd402db799a442e4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.75, "max_line_length": 87, "alphanum_fraction": 0.5799457995, "include": true, "reason": "import numpy", "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9835969703688158, "lm_q2_score": 0.8902942333990421, "lm_q1q2_score": 0.8756907107081252}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Oct 13 10:15:04 2020\r\n\r\n#https://xavierbourretsicotte.github.io/Intro_optimization.html\r\n\"\"\"\r\n\r\n#matplotlib inline\r\nimport matplotlib.pyplot as plt\r\nplt.style.use('seaborn-white')\r\nimport numpy as np\r\nfrom mpl_toolkits import mplot3d\r\n\r\ndef Rosenbrock(x,y):\r\n    return 100*(y-x**2)**2 + (1-x)**2\r\n\r\ndef Grad_Rosenbrock(x,y):\r\n    g1 = 2*x + 2 - 400*x*y+400*x**3\r\n    g2 = 200*y-200*x**2\r\n    return np.array([g1,g2])\r\n\r\ndef Hessian_Rosenbrock(x,y):\r\n    h11 = -400*y + 1200*x**2 + 2\r\n    h12 = -400 * x\r\n    h21 = -400 * x\r\n    h22 = 200\r\n    return np.array([[h11,h12],[h21,h22]])\r\n\r\ndef Gradient_Descent(Grad,x,y, gamma = 0.00125, epsilon=0.0001, nMax = 10000 ):\r\n    #Initialization\r\n    i = 0\r\n    iter_x, iter_y, iter_count = np.empty(0),np.empty(0), np.empty(0)\r\n    error = 10\r\n    X = np.array([x,y])\r\n    \r\n    #Looping as long as error is greater than epsilon\r\n    while np.linalg.norm(error) > epsilon and i < nMax:\r\n        i +=1\r\n        iter_x = np.append(iter_x,x)\r\n        iter_y = np.append(iter_y,y)\r\n        iter_count = np.append(iter_count ,i)   \r\n        #print(X) \r\n        \r\n        X_prev = X\r\n        X = X - gamma * Grad(x,y)\r\n        error = X - X_prev\r\n        x,y = X[0], X[1]\r\n          \r\n    print(X)\r\n    return X, iter_x,iter_y, iter_count\r\n\r\n\r\nroot,iter_x,iter_y, iter_count = Gradient_Descent(Grad_Rosenbrock,-2,2)\r\n\r\n#PLOTTING THE SOLUTION\r\n\r\nx = np.linspace(-2,2,250)\r\ny = np.linspace(-1,3,250)\r\nX, Y = np.meshgrid(x, y)\r\nZ = Rosenbrock(X, Y)\r\n\r\n#Angles needed for quiver plot\r\nanglesx = iter_x[1:] - iter_x[:-1]\r\nanglesy = iter_y[1:] - iter_y[:-1]\r\n\r\n\r\n#matplotlib inline\r\nfig = plt.figure(figsize = (16,8))\r\n\r\n#Surface plot\r\nax = fig.add_subplot(1, 2, 1, projection='3d')\r\nax.plot_surface(X,Y,Z,rstride = 5, cstride = 5, cmap = 'jet', alpha = .4, edgecolor = 'none' )\r\nax.plot(iter_x,iter_y, Rosenbrock(iter_x,iter_y),color = 'r', marker = '*', alpha = .4)\r\n\r\nax.view_init(45, 280)\r\nax.set_xlabel('x')\r\nax.set_ylabel('y')\r\n\r\n\r\n#Contour plot\r\nax = fig.add_subplot(1, 2, 2)\r\nax.contour(X,Y,Z, 50, cmap = 'jet')\r\n#Plotting the iterations and intermediate values\r\nax.scatter(iter_x,iter_y,color = 'r', marker = '*')\r\nax.quiver(iter_x[:-1], iter_y[:-1], anglesx, anglesy, scale_units = 'xy', angles = 'xy', scale = 1, color = 'r', alpha = .3)\r\nax.set_title('Gradient Descent with {} iterations'.format(len(iter_count)))\r\n\r\n\r\nplt.show()\r\n\r\n#Newton's Method (Multi-Dimensional)\r\n\r\ndef Newton_Raphson_Optimize(Grad, Hess, x,y, epsilon=0.000001, nMax = 200):\r\n    #Initialization\r\n    i = 0\r\n    iter_x, iter_y, iter_count = np.empty(0),np.empty(0), np.empty(0)\r\n    error = 10\r\n    X = np.array([x,y])\r\n    \r\n    #Looping as long as error is greater than epsilon\r\n    while np.linalg.norm(error) > epsilon and i < nMax:\r\n        i +=1\r\n        iter_x = np.append(iter_x,x)\r\n        iter_y = np.append(iter_y,y)\r\n        iter_count = np.append(iter_count ,i)   \r\n        print(X) \r\n        \r\n        X_prev = X\r\n        X = X - np.linalg.inv(Hess(x,y)) @ Grad(x,y)\r\n        error = X - X_prev\r\n        x,y = X[0], X[1]\r\n          \r\n    return X, iter_x,iter_y, iter_count\r\n\r\n\r\nroot,iter_x,iter_y, iter_count = Newton_Raphson_Optimize(Grad_Rosenbrock,Hessian_Rosenbrock,-2,2)\r\n\r\nx = np.linspace(-3,3,250)\r\ny = np.linspace(-9,8,350)\r\nX, Y = np.meshgrid(x, y)\r\nZ = Rosenbrock(X, Y)\r\n\r\n#Angles needed for quiver plot\r\nanglesx = iter_x[1:] - iter_x[:-1]\r\nanglesy = iter_y[1:] - iter_y[:-1]\r\n\r\n#matplotlib inline\r\nfig = plt.figure(figsize = (16,8))\r\n\r\n#Surface plot\r\nax = fig.add_subplot(1, 2, 1, projection='3d')\r\nax.plot_surface(X,Y,Z,rstride = 5, cstride = 5, cmap = 'jet', alpha = .4, edgecolor = 'none' )\r\nax.plot(iter_x,iter_y, Rosenbrock(iter_x,iter_y),color = 'r', marker = '*', alpha = .4)\r\n\r\n#Rotate the initialization to help viewing the graph\r\nax.view_init(45, 280)\r\nax.set_xlabel('x')\r\nax.set_ylabel('y')\r\n\r\n#Contour plot\r\nax = fig.add_subplot(1, 2, 2)\r\nax.contour(X,Y,Z, 60, cmap = 'jet')\r\n#Plotting the iterations and intermediate values\r\nax.scatter(iter_x,iter_y,color = 'r', marker = '*')\r\nax.quiver(iter_x[:-1], iter_y[:-1], anglesx, anglesy, scale_units = 'xy', angles = 'xy', scale = 1, color = 'r', alpha = .3)\r\nax.set_title('Newton method with {} iterations'.format(len(iter_count)))\r\n\r\nplt.show()\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "d4d06c8272fcee1b55e06c9e1225e9274c185e57", "size": 4300, "ext": "py", "lang": "Python", "max_stars_repo_path": "week 8 tutorial, Multivariate optimization.py", "max_stars_repo_name": "oliver779/Computational_Methods_Course", "max_stars_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week 8 tutorial, Multivariate optimization.py", "max_issues_repo_name": "oliver779/Computational_Methods_Course", "max_issues_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week 8 tutorial, Multivariate optimization.py", "max_forks_repo_name": "oliver779/Computational_Methods_Course", "max_forks_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1045751634, "max_line_length": 125, "alphanum_fraction": 0.6069767442, "include": true, "reason": "import numpy", "num_tokens": 1384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147209709197, "lm_q2_score": 0.9005297854505006, "lm_q1q2_score": 0.8756884200448507}}
{"text": "import numpy as np\nfrom math import pi as PI\n\ndef estimate_pi(sims):\n    \"\"\"\n    takes the number of simulations as input to estimate pi\n    \"\"\"\n    \n    # counter to hold points lying inside the circle\n    in_circle = 0\n    \n    for s in range(0,sims):\n        \n        x = np.random.rand()\n        y = np.random.rand()\n        \n        if (x**2 + y**2) <= 1:\n            in_circle += 1\n        \n    # The ratio of pts. inside the circle and the total pts. will be same as the ratio\n    # of the area of circle to the area of the square, inside which the circle is inscribed\n    # Area of circle = PI * R * R\n    # Area of square = (2R) * (2R)\n    \n    pi_estimated = 4.0 * in_circle / sims\n    \n    print(\"Simulations ran: \", sims)\n    print(\"Estimated pi\", pi_estimated)\n    print(\"Error\", PI - pi_estimated)\n\npow = 0\ninput_sims = 100\nwhile pow <= 8:\n    estimate_pi(sims=input_sims)\n    pow += 1\n    input_sims *= 10\n\n", "meta": {"hexsha": "3a08e4c7465cf94babc22b64648b326bade9ebd4", "size": 922, "ext": "py", "lang": "Python", "max_stars_repo_path": "estimate_pi.py", "max_stars_repo_name": "deepak5998/Py", "max_stars_repo_head_hexsha": "5ae3bd9e8dcf3104a8ca7512911a1607f6c9ae20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 726, "max_stars_repo_stars_event_min_datetime": "2019-06-04T04:46:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:54:00.000Z", "max_issues_repo_path": "estimate_pi.py", "max_issues_repo_name": "Ishajj/Python-Interview-Problems-for-Practice", "max_issues_repo_head_hexsha": "12ece68be497757e2aad8a07c29399856de782da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2019-06-05T14:21:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-17T05:11:01.000Z", "max_forks_repo_path": "estimate_pi.py", "max_forks_repo_name": "Ishajj/Python-Interview-Problems-for-Practice", "max_forks_repo_head_hexsha": "12ece68be497757e2aad8a07c29399856de782da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 118, "max_forks_repo_forks_event_min_datetime": "2019-06-04T10:25:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T22:31:12.000Z", "avg_line_length": 24.2631578947, "max_line_length": 91, "alphanum_fraction": 0.5835140998, "include": true, "reason": "import numpy", "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147193720649, "lm_q2_score": 0.9005297867852854, "lm_q1q2_score": 0.8756884199029987}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n@author: Alex Muirhead\n\"\"\"\n\nimport numpy as np\nfrom numpy.core.numeric import ones_like\n\n\ndef fact(n):\n    \"\"\"Calculate the value of n factorial.\"\"\"\n    # n! = n*(n-1)*...*2*1\n    product = 1\n    for i in range(1, n+1):\n        product *= i\n    return product\n\n\ndef exptaylor(n, x):\n    \"\"\"Taylor series expansion of e^x\n\n    NOTE:\n        This will fail with x as a np.ndarray when\n        n > 21, due to a quirk with division by\n        large numbers (21! = 51090942171709440000).\n        Just another reason to avoid this implemenation!\n    \"\"\"\n    output = 0\n    for i in range(n):\n        output += x**i / fact(i)\n    return output\n\n\ndef better_exptaylor(n, x):\n    \"\"\"\n    Better Taylor series expansion of e^x\n\n    term 0: 1\n    term 1: x**1 / 1! == (term 0) * x\n    term 2: x**2 / 2! == (term 1) * x / 2\n    term 3: x**3 / 3! == (term 2) * x / 3\n    \"\"\"\n    term = ones_like(x)\n    output = term\n    for i in range(1, n):\n        term   *= x / i\n        output += term\n    return output\n\n\ndef lntaylor(n, x):\n    \"\"\"\n    Efficient Taylor series expansion of ln(x+1) at x=1\n\n    term 0: -1 {not included}\n    term 1:   (x-1)**1 / (2**1 * 1)\n    term 2: - (x-1)**2 / (2**2 * 2)\n    term 3:   (x-1)**3 / (2**3 * 3)\n    term 4: - (x-1)**4 / (2**4 * 4)\n    \"\"\"\n    term = -1\n    output = np.log(2.)  # <- 0th term\n    for i in range(1, n):\n        term *= (1-x) / 2\n        output += term / i\n    return output\n\n\nif __name__ == '__main__':\n\n    approx = better_exptaylor(100, 2)\n    exact  = np.exp(2)\n    error  = np.abs(exact - approx)\n    print(f'The error for 100 terms was {error:.2e}')\n", "meta": {"hexsha": "ed7d39aaa2d65039bf7809a5da75e6230a231618", "size": 1623, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week_02/efficient_calculations.py", "max_stars_repo_name": "MECH3750/2021-Tutorials", "max_stars_repo_head_hexsha": "e813f2a97d9b71ad0e304a35e8c66d21ed63ee0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-08-03T01:40:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T12:07:28.000Z", "max_issues_repo_path": "Week_02/efficient_calculations.py", "max_issues_repo_name": "MECH3750/2021-Tutorials", "max_issues_repo_head_hexsha": "e813f2a97d9b71ad0e304a35e8c66d21ed63ee0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week_02/efficient_calculations.py", "max_forks_repo_name": "MECH3750/2021-Tutorials", "max_forks_repo_head_hexsha": "e813f2a97d9b71ad0e304a35e8c66d21ed63ee0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-08-03T02:48:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T06:47:11.000Z", "avg_line_length": 21.64, "max_line_length": 56, "alphanum_fraction": 0.5212569316, "include": true, "reason": "import numpy,from numpy", "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.9324533036984186, "lm_q1q2_score": 0.875596798039546}}
{"text": "\"\"\"\nJacobi Iteration Method - https://en.wikipedia.org/wiki/Jacobi_method\n\"\"\"\nfrom __future__ import annotations\n\nimport numpy as np\n\n\n# Method to find solution of system of linear equations\ndef jacobi_iteration_method(\n    coefficient_matrix: np.ndarray,\n    constant_matrix: np.ndarray,\n    init_val: list,\n    iterations: int,\n) -> list[float]:\n    \"\"\"\n    Jacobi Iteration Method:\n    An iterative algorithm to determine the solutions of strictly diagonally dominant\n    system of linear equations\n\n    4x1 +  x2 +  x3 =  2\n     x1 + 5x2 + 2x3 = -6\n     x1 + 2x2 + 4x3 = -4\n\n    x_init = [0.5, -0.5 , -0.5]\n\n    Examples:\n\n    >>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])\n    >>> constant = np.array([[2], [-6], [-4]])\n    >>> init_val = [0.5, -0.5, -0.5]\n    >>> iterations = 3\n    >>> jacobi_iteration_method(coefficient, constant, init_val, iterations)\n    [0.909375, -1.14375, -0.7484375]\n\n\n    >>> coefficient = np.array([[4, 1, 1], [1, 5, 2]])\n    >>> constant = np.array([[2], [-6], [-4]])\n    >>> init_val = [0.5, -0.5, -0.5]\n    >>> iterations = 3\n    >>> jacobi_iteration_method(coefficient, constant, init_val, iterations)\n    Traceback (most recent call last):\n    ...\n    ValueError: Coefficient matrix dimensions must be nxn but received 2x3\n\n    >>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])\n    >>> constant = np.array([[2], [-6]])\n    >>> init_val = [0.5, -0.5, -0.5]\n    >>> iterations = 3\n    >>> jacobi_iteration_method(coefficient, constant, init_val, iterations)\n    Traceback (most recent call last):\n    ...\n    ValueError: Coefficient and constant matrices dimensions must be nxn and nx1 but\n                received 3x3 and 2x1\n\n    >>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])\n    >>> constant = np.array([[2], [-6], [-4]])\n    >>> init_val = [0.5, -0.5]\n    >>> iterations = 3\n    >>> jacobi_iteration_method(coefficient, constant, init_val, iterations)\n    Traceback (most recent call last):\n    ...\n    ValueError: Number of initial values must be equal to number of rows in coefficient\n                matrix but received 2 and 3\n\n    >>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])\n    >>> constant = np.array([[2], [-6], [-4]])\n    >>> init_val = [0.5, -0.5, -0.5]\n    >>> iterations = 0\n    >>> jacobi_iteration_method(coefficient, constant, init_val, iterations)\n    Traceback (most recent call last):\n    ...\n    ValueError: Iterations must be at least 1\n    \"\"\"\n\n    rows1, cols1 = coefficient_matrix.shape\n    rows2, cols2 = constant_matrix.shape\n\n    if rows1 != cols1:\n        raise ValueError(\n            f\"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}\"\n        )\n\n    if cols2 != 1:\n        raise ValueError(f\"Constant matrix must be nx1 but received {rows2}x{cols2}\")\n\n    if rows1 != rows2:\n        raise ValueError(\n            f\"\"\"Coefficient and constant matrices dimensions must be nxn and nx1 but\n            received {rows1}x{cols1} and {rows2}x{cols2}\"\"\"\n        )\n\n    if len(init_val) != rows1:\n        raise ValueError(\n            f\"\"\"Number of initial values must be equal to number of rows in coefficient\n            matrix but received {len(init_val)} and {rows1}\"\"\"\n        )\n\n    if iterations <= 0:\n        raise ValueError(\"Iterations must be at least 1\")\n\n    table = np.concatenate((coefficient_matrix, constant_matrix), axis=1)\n\n    rows, cols = table.shape\n\n    strictly_diagonally_dominant(table)\n\n    # Iterates the whole matrix for given number of times\n    for i in range(iterations):\n        new_val = []\n        for row in range(rows):\n            temp = 0\n            for col in range(cols):\n                if col == row:\n                    denom = table[row][col]\n                elif col == cols - 1:\n                    val = table[row][col]\n                else:\n                    temp += (-1) * table[row][col] * init_val[col]\n            temp = (temp + val) / denom\n            new_val.append(temp)\n        init_val = new_val\n\n    return [float(i) for i in new_val]\n\n\n# Checks if the given matrix is strictly diagonally dominant\ndef strictly_diagonally_dominant(table: np.ndarray) -> bool:\n    \"\"\"\n    >>> table = np.array([[4, 1, 1, 2], [1, 5, 2, -6], [1, 2, 4, -4]])\n    >>> strictly_diagonally_dominant(table)\n    True\n\n    >>> table = np.array([[4, 1, 1, 2], [1, 5, 2, -6], [1, 2, 3, -4]])\n    >>> strictly_diagonally_dominant(table)\n    Traceback (most recent call last):\n    ...\n    ValueError: Coefficient matrix is not strictly diagonally dominant\n    \"\"\"\n\n    rows, cols = table.shape\n\n    is_diagonally_dominant = True\n\n    for i in range(0, rows):\n        sum = 0\n        for j in range(0, cols - 1):\n            if i == j:\n                continue\n            else:\n                sum += table[i][j]\n\n        if table[i][i] <= sum:\n            raise ValueError(\"Coefficient matrix is not strictly diagonally dominant\")\n\n    return is_diagonally_dominant\n\n\n# Test Cases\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n", "meta": {"hexsha": "9c30fd84bb03435c6147a89f9e0d495d559a639a", "size": 5028, "ext": "py", "lang": "Python", "max_stars_repo_path": "arithmetic_analysis/jacobi_iteration_method.py", "max_stars_repo_name": "egagraha/python-algorithm", "max_stars_repo_head_hexsha": "07a6a745b4ebddc93ab7c10b205c75b2427ac1fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "arithmetic_analysis/jacobi_iteration_method.py", "max_issues_repo_name": "egagraha/python-algorithm", "max_issues_repo_head_hexsha": "07a6a745b4ebddc93ab7c10b205c75b2427ac1fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arithmetic_analysis/jacobi_iteration_method.py", "max_forks_repo_name": "egagraha/python-algorithm", "max_forks_repo_head_hexsha": "07a6a745b4ebddc93ab7c10b205c75b2427ac1fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6585365854, "max_line_length": 87, "alphanum_fraction": 0.5803500398, "include": true, "reason": "import numpy", "num_tokens": 1437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361741, "lm_q2_score": 0.9273632996617212, "lm_q1q2_score": 0.8755949687583348}}
{"text": "import numpy as np\r\n\r\ndef BFGSAlgo(f,g,xd,epsilon=1e-6):\r\n    \"\"\"\r\n       quasi-Newton method, use BFGS algorithm\r\n       :param f:target function, it's a method having a float parameter.\r\n       :param g:the derivative of the target function, it's a method having a float parameter.\r\n       :param xd: the dimension of the vector\r\n       :param epsilon: precision\r\n       :return: the optimization point\r\n    \"\"\"\r\n    #x=np.random.rand(xd)\r\n    x=np.zeros(xd)\r\n    B=np.eye(xd)\r\n    gk=g(x)\r\n    if np.linalg.norm(gk)<epsilon:\r\n        return x\r\n    while True:\r\n        pk = np.linalg.solve(B, -1 * gk)\r\n        #pk=solveEquation(B,-1*gk)\r\n\r\n        abs=np.abs(gk)\r\n        # print(\"grad\",np.max(abs),np.argmax(abs))\r\n        # print(\"function\",f(x))\r\n        # print(\"w\",np.max(x),np.argmax(x),np.median(x),np.mean(x))\r\n        # print()\r\n        stepLength=calLambdaByArmijoRule(x,f(x),gk,pk,f)\r\n        #stepLength=0.01\r\n        xPre=x\r\n        gkPre=gk\r\n\r\n        x=x+stepLength*pk\r\n        gk=g(x)\r\n        if np.linalg.norm(gk)<epsilon:\r\n            return x\r\n\r\n        #update B\r\n        yk=gk-gkPre\r\n        deltaK=x-xPre\r\n        deltaMatrix=np.matmul(deltaK.reshape(-1,1),deltaK.reshape(1,-1))\r\n        B=B+(np.matmul(yk.reshape(-1,1),yk.reshape(1,-1))/np.sum(yk*deltaK))- \\\r\n          (np.matmul(np.matmul(B,deltaMatrix),B)/np.matmul(np.matmul(deltaK.reshape(1,-1),B),deltaK.reshape(-1,1)))\r\n\r\n\r\ndef calLambdaByArmijoRule(xCurr, fCurr, gCurr, pkCurr,f, c=1.e-4, v=0.5):\r\n    \"\"\"\r\n    refer to https://www.cnblogs.com/xxhbdk/p/11785365.html\r\n    to calculate lambda\r\n    \"\"\"\r\n    i = 0\r\n    alpha = v ** i\r\n    xNext = xCurr + alpha * pkCurr\r\n    fNext = f(xNext)\r\n\r\n    while True:\r\n        if fNext <= fCurr + c * alpha * np.sum(pkCurr*gCurr):\r\n            break\r\n        i += 1\r\n        alpha = v ** i\r\n        xNext = xCurr + alpha * pkCurr\r\n        fNext = f(xNext)\r\n\r\n    return alpha\r\n\r\n\r\n#PALU decomposition\r\ndef PALU_Factorization(A: np.array):\r\n    U = A.copy()\r\n    P = np.eye(U.shape[0])\r\n    L = np.zeros(U.shape)\r\n    for index in range(U.shape[1]):\r\n        maxIndex = index + np.argmax(U[index:, index])\r\n        # exchange 2 rows\r\n        #print(U[[index, maxIndex], :])\r\n        P[[index, maxIndex], :] = P[[maxIndex, index], :]\r\n        U[[index, maxIndex], :] = U[[maxIndex, index], :]\r\n        L[[index, maxIndex], :] = L[[maxIndex, index], :]\r\n        # eliminate non-zero elements\r\n        for rIndex in range(index + 1, U.shape[0]):\r\n            # try:\r\n            #     assert U[index, index]!=0\r\n            # except:\r\n            #     print(index)\r\n            #     print(U)\r\n            multiFactor = U[rIndex, index] / U[index, index]\r\n            U[rIndex, :] -= U[index, :] * multiFactor\r\n            L[rIndex, index] = multiFactor\r\n\r\n        # 给L加上对角线的1\r\n    for i in range(U.shape[0]):\r\n        L[i, i] = 1.0\r\n    return P, L, U\r\n\r\n\r\n# 使用PA=LU分解解方程\r\ndef solveEquation(A: np.array, b: np.array):\r\n    P, L, U = PALU_Factorization(A)\r\n    Pb = np.matmul(P, b.reshape(-1,1))\r\n    # 此时方程为：LUx=Pb\r\n    # 先解Lc=Pb\r\n    c = np.zeros([L.shape[0], 1])\r\n    for i in range(L.shape[0]):\r\n        c[i, 0] = Pb[i, 0]\r\n        for j in range(i):\r\n            c[i, 0] -= L[i, j] * c[j, 0]\r\n\r\n    # 再解Ux=c\r\n    x = np.zeros([U.shape[0], 1])\r\n    for i in range(U.shape[0] - 1, -1, -1):\r\n        x[i, 0] = c[i, 0]\r\n        for j in range(U.shape[1] - 1, i, -1):\r\n            x[i, 0] -= U[i, j] * x[j, 0]\r\n        x[i, 0] /= U[i, i]\r\n\r\n    return x.reshape(-1,)\r\n\r\nif __name__ == '__main__':\r\n    f=lambda x:5*x[0]*x[0]+2*x[1]*x[1]+3*x[0]-10*x[1]+4\r\n    g=lambda x:np.array([10*x[0]+3,4*x[1]-10])\r\n    print(BFGSAlgo(f,g,2))\r\n    #print(solveEquation(np.eye(50),np.array([i for i in range(50)])))", "meta": {"hexsha": "ff3a3427fc235e6ed8d8ff32620c35bc446ebb8d", "size": 3725, "ext": "py", "lang": "Python", "max_stars_repo_path": "utilities/numericalComputation.py", "max_stars_repo_name": "RockeyCoss/machineLearningImplementation", "max_stars_repo_head_hexsha": "92442f9a9703de57df6308881c4a87bbf0f9163c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-21T15:08:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T15:08:39.000Z", "max_issues_repo_path": "utilities/numericalComputation.py", "max_issues_repo_name": "RockeyCoss/machineLearningImplementation", "max_issues_repo_head_hexsha": "92442f9a9703de57df6308881c4a87bbf0f9163c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utilities/numericalComputation.py", "max_forks_repo_name": "RockeyCoss/machineLearningImplementation", "max_forks_repo_head_hexsha": "92442f9a9703de57df6308881c4a87bbf0f9163c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7851239669, "max_line_length": 116, "alphanum_fraction": 0.5111409396, "include": true, "reason": "import numpy", "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241982893259, "lm_q2_score": 0.9032942132122422, "lm_q1q2_score": 0.8755849390413442}}
{"text": "from itertools import ifilter\nimport numpy as np\n\ndef sieve(n):\n    '''Recursive Sieve of Eratosthenes'''\n    acc = []\n    def aux(numList):\n        try:\n            k = numList[0]\n            acc.append(k)\n            aux(filter(lambda x: x % k, numList))\n        except IndexError:\n            pass\n    aux(xrange(2,n))\n    return acc\n\ndef sieve2(n):\n    '''Iterative Sieve of Eratosthenes'''\n    acc = []\n    numList = xrange(2,n)\n    while numList:\n        k = numList[0]\n        acc.append(k)\n        numList = filter(lambda x: x % k, numList)\n    return acc\n\ndef sieve3(n):\n    '''Iterative Sieve of Eratosthenes using iterator'''\n    acc = [] \n    numList = iter(xrange(2,n))\n    try:\n        while True:\n            k = numList.next()\n            acc.append(k)\n            numList = ifilter(lambda x: # all(x % np.array(acc))\n                reduce(lambda acc,a: acc and (x % a), acc, True)\n                , numList)\n    except StopIteration:\n        pass\n    return acc\n\ndef sieve4(n):\n    '''Sieve of Eratosthenes in memory'''\n    acc = []\n    sieve_array = np.arange(2,n)\n    next_index = 0\n    for (i,k) in enumerate(sieve_array):\n        if k != 0:\n          sieve_array[sieve_array % k == 0] = 0\n          sieve_array[i] = k # Store the prime back into the array \n    return sieve_array[sieve_array != 0]\n\nif __name__ == '__main__':\n    import sys\n    if len(sys.argv) > 1:\n        n = int(sys.argv[1])\n    else:\n        n =100\n    print 'There are {0} primes less than {1}'.format(len(sieve2(n)), n)\n", "meta": {"hexsha": "9cc81f7b4fcaad458820f6bf44ddccd26ff7d0ea", "size": 1516, "ext": "py", "lang": "Python", "max_stars_repo_path": "Sieve/sieve.py", "max_stars_repo_name": "mattmcd/PySnippets", "max_stars_repo_head_hexsha": "0ee40ff04b383b8c5c9b92caa4c8baa520d03543", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sieve/sieve.py", "max_issues_repo_name": "mattmcd/PySnippets", "max_issues_repo_head_hexsha": "0ee40ff04b383b8c5c9b92caa4c8baa520d03543", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sieve/sieve.py", "max_forks_repo_name": "mattmcd/PySnippets", "max_forks_repo_head_hexsha": "0ee40ff04b383b8c5c9b92caa4c8baa520d03543", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2666666667, "max_line_length": 72, "alphanum_fraction": 0.5428759894, "include": true, "reason": "import numpy", "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693688269984, "lm_q2_score": 0.9219218332461268, "lm_q1q2_score": 0.8755209254866785}}
{"text": "\"\"\"\nFile: yx_ODE.py\nCopyright (c) 2016 Andrew Malfavon\nLicense: MIT\nExercise C.3\nDescription: Solve an ODE using the Forward Euler method.\n\"\"\"\n\nimport numpy as np\nimport sympy as sp\nimport matplotlib.pyplot as plt\n\n#ode to be solved\ndef y_prime(y, x):\n    return 1 / (2 * (y - 1))\n\n#forward euler method based on code from book\ndef Forward_Euler(prime, a, b, dx, eps = 1e-3):\n    n = int((b - a) / (dx))\n    x = np.zeros(n + 1)\n    y = np.zeros(n + 1)\n    y[0] = 1 + np.sqrt(eps)\n    x[0] = 0\n    for i in range(n):\n        x[i + 1] = x[i] + dx\n        y[i + 1] = y[i] + dx * prime(y[i], x[i])\n    return y, x\n\n#solves the ode using sympy\n#does not take into account initial condition\ndef sympy_solution():\n    x = sp.Symbol('x')\n    f = sp.Function('f')\n    eq = 1 / (2 * (f(x) - 1))\n    return sp.dsolve(sp.Eq(sp.diff(f(x)), eq))[1]#solves ode. first solution is negative so we use the second solution\n\n#plot approximations with three step sizes and plots analytical solution\ndef plot(eps = 1e-3):\n    x_exact = np.linspace(0, 4, 1001)\n    y_exact = 1 + np.sqrt(x_exact + eps)\n    x1 = Forward_Euler(y_prime, 0, 4, 1)[1]\n    y1 = Forward_Euler(y_prime, 0, 4, 1)[0]\n    x2 = Forward_Euler(y_prime, 0, 4, 0.25)[1]\n    y2 = Forward_Euler(y_prime, 0, 4, 0.25)[0]\n    x3 = Forward_Euler(y_prime, 0, 4, 0.01)[1]\n    y3 = Forward_Euler(y_prime, 0, 4, 0.01)[0]\n    plt.plot(x_exact, y_exact, label = 'Exact Solution')#labels are for the key in the graph\n    plt.plot(x1, y1, label = 'step size = 1')\n    plt.plot(x2, y2, label = 'step size = 0.25')\n    plt.plot(x3, y3, label = 'step size = 0.01')\n    plt.title('Approximations and exact solution of ODE')\n    plt.xlabel('x')\n    plt.ylabel('y')\n    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)#creates key for graph\n\n#test the most accurate approximation with the analytical solution\ndef test():\n    eps = 1e-3\n    exact = 1 + np.sqrt(4 + eps)\n    assert (Forward_Euler(y_prime, 0, 4, 0.01)[0][-1]) - (exact) < 0.01", "meta": {"hexsha": "5014fbe51c0489738d0fc6e69fb016911496ee0a", "size": 1977, "ext": "py", "lang": "Python", "max_stars_repo_path": "yx_ODE.py", "max_stars_repo_name": "chapman-phys227-2016s/hw-6-malfa100", "max_stars_repo_head_hexsha": "b905f77acc9fc6ad76964347e6ceff2917882641", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "yx_ODE.py", "max_issues_repo_name": "chapman-phys227-2016s/hw-6-malfa100", "max_issues_repo_head_hexsha": "b905f77acc9fc6ad76964347e6ceff2917882641", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "yx_ODE.py", "max_forks_repo_name": "chapman-phys227-2016s/hw-6-malfa100", "max_forks_repo_head_hexsha": "b905f77acc9fc6ad76964347e6ceff2917882641", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.95, "max_line_length": 118, "alphanum_fraction": 0.6216489631, "include": true, "reason": "import numpy,import sympy", "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.924141814233309, "lm_q1q2_score": 0.8755144364775892}}
{"text": "# Importing required libraries\n \nimport numpy as np\nimport scipy.stats\nimport math\nfrom scipy.stats import multivariate_normal\n\n\ndef normal_dist(x , mean , var):\n\n    \"\"\"\n    Calculates a normal distribution in a variate x,\n    with mean mu (mean) and variance sigma^2 (sd)\n    as a statistic distribution with probability density function.\n    source: https://mathworld.wolfram.com/NormalDistribution.html\n\n    note that variance is std^2, e.g. a distribution with variance equal to 36, has a std dev of 6 (36 = 6^2).\n\n    sigma^2 = sd, standard deviation\n    sigma = variance\n    \"\"\"\n    \n    prob_density = (1/((2*np.pi*var)**(1/2))) * (np.exp(-0.5*((x-mean)**2/var)))\n\n    return prob_density\n \n\ndef stackoverflow_normpdf(x, mean, sd):\n\n    \"\"\"\n    Another alternative from: https://stackoverflow.com/a/12413491\n    This uses the formula found here: http://en.wikipedia.org/wiki/Normal_distribution#Probability_density_function\n    \"\"\"\n    var = float(sd)**2\n    denom = (2*math.pi*var)**.5\n    num = math.exp(-(float(x)-float(mean))**2/(2*var))\n    return num/denom\n\n\ndef scipy_norm_pdf(x, mean, sd):\n\n    #Using scipy library for calculating the normal probability distribution\n    # loc being the mean, varies for probability of 'yes' vs 'no'\n    # scale being the sd (not variance), varies for probability of 'yes' vs 'no'\n    # use cdf to indicate the value at which we would like to calculate the probability; e.g. x = 4 in this particular scenario\n\n    prob = scipy.stats.norm(mean, sd).pdf(x)\n    prob_dist = scipy.stats.norm(mean, sd)\n\n    return prob, prob_dist\n \n\nx = 4\nmean_yes = 10\nmean_no = 0\nvar = 36\nsd = var**(1/2)\n\n\n#using the function we have created\n\nour_prob_dist_yes = normal_dist(x, mean_yes, var)\nour_prob_dist_no = normal_dist(x, mean_no, var)\n\nprint(f\"Using the function we have created, for \\n X = {x} \\n mean_yes = {mean_yes} \\n mean_no= {mean_no} n var = {var} \\n the probability for Yes is {our_prob_dist_yes} \\n and the probability for No is {our_prob_dist_no}\")\n\n\n#using the alternative method from stackoverflow and wikipedia formulation; note you are passing on here sd and not variance (e.g. passing on sd and not var = sd^(2)\nalt_prob_dist_yes = stackoverflow_normpdf(x, mean_yes, sd)\nalt_prob_dist_no = stackoverflow_normpdf(x, mean_no, sd)\n\nprint(f\"Using the alternative method from stackoverflow and wikipedia formulation, for \\n X = {x} \\n mean_yes = {mean_yes} \\n mean_no = {mean_no} \\n var = {var} the probability for Yes is {alt_prob_dist_yes} \\n and the probability for No is {alt_prob_dist_no}\")\n\n\n#using scipy library to compare/validate above function\nscipy_prob_yes, scipy_prob_dist_yes = scipy_norm_pdf(x, mean_yes, sd)\nscipy_prob_no, scipy_prob_dist_no = scipy_norm_pdf(x, mean_no, sd)\n\nprint(f\"Using scipy library to compare/validate above function, for \\n X = {x} \\n mean_yes = {mean_yes} \\n mean_no = {mean_no} \\n var = {var} the probability for Yes is {scipy_prob_yes} \\n and the probability for No is {scipy_prob_no}\")", "meta": {"hexsha": "032d7648e8dd82cb3b770c3eaad2f97f6e0b09b2", "size": 2977, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "mariamingallonMM/AI-ML-W4-normal-probability-distribution", "max_stars_repo_head_hexsha": "95569929078b22555f870675f27aeca29f8ce487", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-07T12:25:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-07T12:25:20.000Z", "max_issues_repo_path": "main.py", "max_issues_repo_name": "mariamingallonMM/AI-ML-W4-normal-probability-distribution", "max_issues_repo_head_hexsha": "95569929078b22555f870675f27aeca29f8ce487", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "mariamingallonMM/AI-ML-W4-normal-probability-distribution", "max_forks_repo_head_hexsha": "95569929078b22555f870675f27aeca29f8ce487", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6835443038, "max_line_length": 261, "alphanum_fraction": 0.7178367484, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877717925422, "lm_q2_score": 0.9019206844384594, "lm_q1q2_score": 0.8754833795111727}}
{"text": "from sympy import *\n\n\nt, a, Q, w = symbols('t a A w', positive=True, real=True)\nu = Q*exp(-a*t)*sin(w*t)\ndudt = diff(u, t)\ndudt\nfactor(dudt)\nsimplify(dudt)\n# Alternative, manually derived expression\nphi = atan(-a/w)\nA = Q*sqrt(a**2 + w**2)\ndudt2 = exp(-a*t)*A*cos(w*t - phi)\n\nsimplify(expand_trig(dudt2))\nsimplify(expand_trig(dudt2 - dudt))  # are they equal?\ns = solve(dudt2, t)\ns\n", "meta": {"hexsha": "7b8b4177dff4a22a785396ae2971b0e2b501ae56", "size": 382, "ext": "py", "lang": "Python", "max_stars_repo_path": "fdm-devito-notebooks/A_formulas/src-formulas/sympy_sin_wphase.py", "max_stars_repo_name": "devitocodes/devito_book", "max_stars_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-07-17T13:19:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-27T05:21:09.000Z", "max_issues_repo_path": "fdm-devito-notebooks/A_formulas/src-formulas/sympy_sin_wphase.py", "max_issues_repo_name": "devitocodes/devito_book", "max_issues_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 73, "max_issues_repo_issues_event_min_datetime": "2020-07-14T15:38:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-25T11:54:59.000Z", "max_forks_repo_path": "fdm-devito-notebooks/A_formulas/src-formulas/sympy_sin_wphase.py", "max_forks_repo_name": "devitocodes/devito_book", "max_forks_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-27T05:21:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T05:21:14.000Z", "avg_line_length": 20.1052631579, "max_line_length": 57, "alphanum_fraction": 0.6518324607, "include": true, "reason": "from sympy", "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018376422668, "lm_q2_score": 0.8976952832120991, "lm_q1q2_score": 0.8754340898312342}}
{"text": "\n'''\nPrint the series:\nx + x**2 + x**3 ... + x**n\n'''\n\nfrom sympy import Symbol, pprint, init_printing\n\ndef print_series( n, x_value ):\n\n\t# Initialize printing system with reverse order\n\tinit_printing( order = 'rev-lex' )\n\n\tx = Symbol( 'x' )\n\n\tseries = x\n\tfor i in range( 2, n + 1 ):\n\t\tseries = series + ( x ** i ) / i\n\tpprint( series )\n\n\tseries_value = series.subs( { x: x_value } )\n\n\tprint( 'Value of the series at {0}: {1}'.format( x_value, series_value ) )\n\nif __name__ == '__main__':\n\tn = input( 'Enter the number of terms you want in the series: ' )\n\tx_value = input( 'Enter the value of x at which you want to evaluate the series: ' )\n\n\tprint_series( int( n ), float( x_value ) )\n", "meta": {"hexsha": "d500a34e3697c190a7d3cd82016ee65aa7ee4f02", "size": 687, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/DoingMathInPython/ch_04/simple_series.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DoingMathInPython/ch_04/simple_series.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DoingMathInPython/ch_04/simple_series.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9, "max_line_length": 85, "alphanum_fraction": 0.634643377, "include": true, "reason": "from sympy", "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075777163566, "lm_q2_score": 0.9099070158103778, "lm_q1q2_score": 0.8754284349284411}}
{"text": "#NAME:\n#  K_ARR\n#PURPOSE:\n#  Generate an array of wavenumber values (by default, in units of cycles per \n#  sample interval), arranged corresponding to the FFT of an N-element array.\n#CALLING SEQUENCE:\n#  k = k_arr(N [, dx=dx] [,/radians])\n#OUTPUT:\n#  k = N-element array of positive and negative wavenumbers, where the maximum\n#     (Nyquist) frequency has a value of pi radians per sample interval. The\n#     dx and cycles keywords can be used to modify the units of k.\n#INPUTS:\n#  N = Number of elements. The program has been verified for both odd and\n#     even N.\n#OPTIONAL KEYWORD INPUTS:\n#  dx = sample interval. Default=1. If included, then k will be converted into units\n#     of cycles (or radians, if that keyword is set) per unit distance (or time),\n#     corresponding to the units of dx.\n#  radians = if set, then let k be in radians (rather than cycles).\n#HISTORY:\n#  2013-Jun-25 C. Kankelborg\n#  2019 Jun 21  JTE Translated into Python 3\n\nimport numpy as np\n\ndef k_arr(N,\n          dx = 1.0,\n          radians = False):\n    \n    dk = np.power(N * dx, -1.0)  #frequency interval equals the fundamental frequency\n       #of one cycle per N samples, or one cycle per total distance N*dx.\n    \n    k = dk * [ np.arange(np.floor_divide(N, 2.0) + 1), -np.arange(np.ceil(0.5 * N - 1))[::-1] + 1  ]\n    #        [  positive frequencies,        negative frequencies              ]\n    \n    if radians:\n        \n        k *= 2.0 * np.pi #convert from cycles to radians.\n    \n    return k\n", "meta": {"hexsha": "eff00c9bcdd03778e1f06f3714709404312930ac", "size": 1494, "ext": "py", "lang": "Python", "max_stars_repo_path": "k_arr.py", "max_stars_repo_name": "Jon-Eckberg/ffopy", "max_stars_repo_head_hexsha": "caeed54bf805b8d7895fff288655e698aab0284e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "k_arr.py", "max_issues_repo_name": "Jon-Eckberg/ffopy", "max_issues_repo_head_hexsha": "caeed54bf805b8d7895fff288655e698aab0284e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "k_arr.py", "max_forks_repo_name": "Jon-Eckberg/ffopy", "max_forks_repo_head_hexsha": "caeed54bf805b8d7895fff288655e698aab0284e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4390243902, "max_line_length": 100, "alphanum_fraction": 0.6459170013, "include": true, "reason": "import numpy", "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075722839015, "lm_q2_score": 0.9099070145888367, "lm_q1q2_score": 0.8754284288101583}}
{"text": "import numpy as np\r\nitr_limit = 20\r\nconv_crit = 0.0000001\r\n\r\n\r\ndef stop_cond(A, b, x):\r\n\r\n\tn = len(b)\r\n\tres = (A@x - b)\r\n\tmagnitude = (res@res)**0.5\r\n\t\r\n\tif magnitude < conv_crit:\r\n\t\treturn True\r\n\telse:\r\n\t\treturn False \r\n\r\n\r\ndef jacobi(A, b, N = -1, x_old = None):\r\n\r\n\tn = len(b)\r\n\titr = 0\r\n\tconverged = False\r\n\tx_new = np.empty(n)\r\n\tif x_old == None:\r\n\t\tx_old = np.zeros(n)\r\n\r\n\twhile not converged and itr < itr_limit and itr != N:\r\n\r\n\t\tfor i in range (n):\r\n\t\t\tdot = 0\r\n\t\t\tfor j in range(n):\r\n\t\t\t\tif(i!=j):\r\n\t\t\t\t\tdot += A[i,j]*x_old[j]\r\n\r\n\t\t\tx_new[i] = (b[i] - dot)/A[i,i]\r\n\r\n\t\titr += 1\r\n\t\tconverged = stop_cond(A,b,x_new)\r\n\t\tx_old = x_new.copy()\r\n\t\t\r\n\tif not converged:\r\n\t\tprint(\"Iteration limit reached without convergence.\")\t\r\n\r\n\treturn x_new\t\r\n\t\r\nM = np.array([[4,1],[1,4]],dtype=float)\r\nx = np.array([5,5],dtype=float)\r\nprint(jacobi(M,x))", "meta": {"hexsha": "9c3642ccdd401930428a924b979ec7698ed932ec", "size": 844, "ext": "py", "lang": "Python", "max_stars_repo_path": "Jacobi.py", "max_stars_repo_name": "krutikdesai/Lid-Driven-Cavity-with-FVM", "max_stars_repo_head_hexsha": "15d0703decd74e900466a71433fa63030a8bd1ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-09T00:51:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-09T00:51:31.000Z", "max_issues_repo_path": "Jacobi.py", "max_issues_repo_name": "krutikdesai/Lid-Driven-Cavity-with-FVM", "max_issues_repo_head_hexsha": "15d0703decd74e900466a71433fa63030a8bd1ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Jacobi.py", "max_forks_repo_name": "krutikdesai/Lid-Driven-Cavity-with-FVM", "max_forks_repo_head_hexsha": "15d0703decd74e900466a71433fa63030a8bd1ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5833333333, "max_line_length": 57, "alphanum_fraction": 0.5651658768, "include": true, "reason": "import numpy", "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075733703927, "lm_q2_score": 0.9099070115349837, "lm_q1q2_score": 0.875428426860629}}
{"text": "import numpy as np\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nfrom numpy.fft import fft2, fftshift, ifft2\n\n# %% read images\nimg_raw = np.asarray(Image.open('Q5_1.tif'))\nrow, col = img_raw.shape\n\n# %% spatial filtering\nsobel_filter = np.array([[-1, 0, 1],\n                         [-2, 0, 2],\n                         [-1, 0, 1]])\n\nimg_pad = np.pad(img_raw, 1)\nimg_spatial = np.asarray([(img_pad[i:i + 3, j:j + 3] * sobel_filter).sum()\n                          for i in range(row)\n                          for j in range(col)]).reshape(row, col)\n\nplt.subplot(121)\nplt.imshow(img_raw, cmap='gray')\nplt.title('Raw Q5_1.tif')\n\nplt.subplot(122)\nplt.imshow(img_spatial, cmap='gray')\nplt.title('Sobel filtered Q5_1.tif\\n(in spatial domain)')\n# plt.savefig('Q5_1_1.png')\nplt.show()\n\n# %% freq domain filtering\nimg_fourier = fftshift(fft2(np.pad(img_raw, ((0, row), (0, col)))))\nfilter_fourier = fftshift(fft2(np.pad(sobel_filter, ((0, 2 * row - 3), (0, 2 * col - 3)))))\n\nimg_view = np.log10(np.abs(img_fourier) + 1).astype(np.uint8)\nfilter_view = np.abs(filter_fourier).astype(np.uint8)\n\nplt.subplot(121)\nplt.imshow(img_view, cmap='gray')\nplt.title('Fourier transform of Q5_1.tif\\n(Shifted and log transformed)')\n\nplt.subplot(122)\nplt.imshow(filter_view, cmap='gray')\nplt.title('Fourier transform of Sobel Filter\\n(Shifted and log transformed)')\nplt.savefig('Q5_1_2.png')\nplt.show()\n\nimg_freq = np.real(ifft2(fftshift(img_fourier * filter_fourier)))[0:row, 0:col]\n\nplt.subplot(121)\nplt.imshow(img_raw, cmap='gray')\nplt.title('Raw Q5_1.tif')\n\nplt.subplot(122)\nplt.imshow(img_freq, cmap='gray')\nplt.title('Sobel Filtered Q5_1.tif\\n(in frequency domain)')\nplt.savefig('Q5_1_3.png')\nplt.show()\n\n# %% no fft shift\nimg_fourier_no_shift = fft2(np.pad(img_raw, ((0, row), (0, col))))\nimg_view_no_shift = np.log10(np.abs(img_fourier_no_shift) + 1).astype(np.uint8)\nimg_freq_no_shift = np.real(ifft2(img_fourier * filter_fourier))[0:row, 0:col]\n\nplt.subplot(121)\nplt.imshow(img_view_no_shift, cmap='gray')\nplt.title('Fourier transform of Q5_1.tif\\n(Not shifted, log transformed)')\n\nplt.subplot(122)\nplt.imshow(img_freq_no_shift, cmap='gray')\nplt.title('Sobel Filtered Q5_1.tif\\n(in frequency domain, not shifted)')\nplt.savefig('Q5_1_4.png')\nplt.show()\n", "meta": {"hexsha": "802a15d2a24d46b0e4bde7ff434a93b754a813d7", "size": 2252, "ext": "py", "lang": "Python", "max_stars_repo_path": "lab5/sobel.py", "max_stars_repo_name": "kommunium/dip-lab", "max_stars_repo_head_hexsha": "2c8e08a994fb34b87da55da48a7b72b7c13d9c81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab5/sobel.py", "max_issues_repo_name": "kommunium/dip-lab", "max_issues_repo_head_hexsha": "2c8e08a994fb34b87da55da48a7b72b7c13d9c81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab5/sobel.py", "max_forks_repo_name": "kommunium/dip-lab", "max_forks_repo_head_hexsha": "2c8e08a994fb34b87da55da48a7b72b7c13d9c81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8493150685, "max_line_length": 91, "alphanum_fraction": 0.6860568384, "include": true, "reason": "import numpy,from numpy", "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551546097942, "lm_q2_score": 0.9073122251200417, "lm_q1q2_score": 0.8754248772475542}}
{"text": "\nimport pandas as pd\n\n\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\n\n#https://datahub.io/core/s-and-p-500\ndat = pd.read_csv(\"c:/users/jliv/downloads/data_csv.csv\")\n\ndat['year']=dat['Date'].apply(lambda x: x[:4])\ndat['year']=dat['year'].astype(int)\n\ni = dat.index.values/max(dat.index)\n\nprint(\"Has the SP500 grown strictly exponentially? It can be shown that an exponential model a second exponential model on the exponent can well describe the historical growth of the sp500.\")\nplt.plot(dat['SP500'])\nplt.title(\"monthly s&p 500: big exponential growth\")\nplt.xlabel(\"month since 1871\")\nplt.show()\n\nprint(\"If growth is exponential, evaluating log(sp500) can render growth linear. It is observable that the log-trend still grows more in recent history than in early history.\")\nplt.plot(np.log(dat['SP500']))\nplt.title(\"monthly log s&p 500: growing faster and faster, but linear in part\")\nplt.xlabel(\"month since 1871\")\nplt.show()\n\nprint(\"Using a homomorphism on i (normalized month since 1871), functionally a**i for some a, 'a' can be chosen to map the normalized month to a new value in space a**i, such that small i are mapped to a closer proximity to each other than large i.\")\na=6\nplt.scatter(i,a**i)\nplt.title(\"i (month since 1871, normalized), maps to a**i \\n stretching high i and compressing low i\")\nplt.xlabel(\"i = month since 1871 normalized\")\nplt.ylabel(\"a**i\")\nplt.show()\n\nprint(\"Initial guess of a is \"+str(a)+\", such that plot log_a(sp500) against a**i is as linear as possible.\")\nplt.plot(a**i,np.log(dat['SP500'])/np.log(a))\nplt.title(\"warping x axis: a**x; a=\"+str(a)+\", compressing low x \\n stretching high x, even more linear\")\nplt.xlabel(\"a**i\")\nplt.ylabel(\"log_a(sp500)\")\nplt.show()\n\n\nprint(\"With initial a = \"+str(a)+\", fitting linear model X=[a**i,1] to log_a(sp500) for inital guess of beta.  log_a(sp500)=b1*i'+b0 where i'=a**i\")\nX = np.column_stack([a**i,np.ones(len(i))])\nY=np.log(dat['SP500'])/np.log(a)\nbeta = np.linalg.inv(X.T@X)@(X.T@Y)\n\nYhat=X@beta\n\nplt.plot(a**i,Y)\nplt.plot(a**i,Yhat)\nplt.title(\"Fitting a linear model this can be abstracted into an exponential curve \\n with respect to a power-warped axis\")\nplt.xlabel(\"a**i\")\nplt.ylabel(\"log_a(sp500)\")\nplt.show()\n\n\nprint(\"Plotting log_a(Y) over unmorphed i scale, exponential growth is observable. Here log_5(sp500)=b1*a**i+b0\")\nplt.plot(i,Y)\nplt.plot(i,Yhat)\nplt.ylabel(\"i\")\nplt.title(\"This growth is well behaved with respect to a**i, and thus, i\")\nplt.show()\n\nprint(\"Plotting Y over unmorphed i scale, growth is exponential, and the exponent grows exponentially. Here sp500=a**(b1*a**i+b0). The shape is largely correct, but parameters a, b1 and b0 can be tuned with gradient descent.\")\nplt.plot(i,a**Y)\nplt.plot(i,a**Yhat)\nplt.ylabel(\"i\")\nplt.title(\"This growth is well behaved with respect to a**i, and thus, i\")\nplt.show()\n\n\nprint(\"Setting Y to be sp500, x is i (normalized month since 1870).\")\nprint(\"Model is Y=a**(b1*a**i+b0), from visual analysis above, initial a guessed \"+str(a)+\", and model fit given a=\"+str(a)+\" yielded beta vector \"+ str(beta)+\".\")\n\nprint(\"Derivative of SSE cost function is evaluated using each of a, b1 and b0.\")\nprint(\"In terms of a: (a**(b1*a**X+b0)-Y)@(a**(b1*a**X+b0-1)*(b1*a**X+b0+b1*X*np.log(a)*a**X))\")\nprint(\"In terms of b1: (a**(b1*a**X+b0)-Y)@(np.log(a)*a**(b1*a**X+b0+X))\")\nprint(\"In terms of b0: (a**(b1*a**X+b0)-Y)@(np.log(a)*a**(b1*a**X+b0))\\n\")\n\nY=dat['SP500']\nX = i\n\nl=.00000000001\ntol=1e-8\na,b1,b0=a,beta[0],beta[1]\ne1=1e5\nfor c in range(15000):\n    err = (a**(b1*a**X+b0)-Y)\n    \n    e2=np.mean(abs(err))\n    \n    if e1-e2<tol:\n        break\n    else:\n        e1=e2\n    grad_mod_a = a**(b1*a**X+b0-1)*(b1*a**X+b0+b1*X*np.log(a)*a**X)\n    grad_mod_b1=np.log(a)*a**(b1*a**X+b0+X)\n    grad_mod_b0 = np.log(a)*a**(b1*a**X+b0)\n    \n    grad_a=err@grad_mod_a\n    grad_b1=err@grad_mod_b1\n    grad_b0=err@grad_mod_b0\n    \n    a,b1,b0=a-l*grad_a,b1-l*grad_b1,b0-l*grad_b0\n    \n\nprint(np.mean(abs(err)))\nprint(\"After gradient descent, new a, b1 and b0 are:\",a,b1,b0)\nyhat=a**(b1*a**X+b0)\n\nprint(\"With learned a, b1 and b0, model well-defines historical growth of the market.\")\nplt.plot(Y)\nplt.plot(yhat)\nplt.show()\n\n", "meta": {"hexsha": "a5b785ae0eb1eabc016d7b94c5d8d82588e3ebeb", "size": 4152, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/sp500_ts_warping.py", "max_stars_repo_name": "JLivingston01/py_research", "max_stars_repo_head_hexsha": "928f74287039a933d27c5a5dc3df8db4cb79c152", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-21T00:47:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T00:47:41.000Z", "max_issues_repo_path": "scripts/sp500_ts_warping.py", "max_issues_repo_name": "JLivingston01/py_research", "max_issues_repo_head_hexsha": "928f74287039a933d27c5a5dc3df8db4cb79c152", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/sp500_ts_warping.py", "max_forks_repo_name": "JLivingston01/py_research", "max_forks_repo_head_hexsha": "928f74287039a933d27c5a5dc3df8db4cb79c152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6, "max_line_length": 250, "alphanum_fraction": 0.6791907514, "include": true, "reason": "import numpy", "num_tokens": 1320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551515780319, "lm_q2_score": 0.9073122238669026, "lm_q1q2_score": 0.8754248732877015}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\n\"\"\"\nA2-Part-1: Generate a sinusoid\n\nWrite a function to generate a real sinusoid (use np.cos()) given its amplitude A, frequency f (Hz), initial phase phi (radians), \nsampling rate fs (Hz) and duration t (seconds). \n\nAll the input arguments to this function (A, f, phi, fs and t) are real numbers such that A, t and fs are \npositive, and fs > 2*f to avoid aliasing. The function should return a numpy array x of the generated \nsinusoid.\n\nEXAMPLE: If you run your code using A=1.0, f = 10.0, phi = 1.0, fs = 50.0 and t = 0.1, the output numpy \narray should be: array([ 0.54030231, -0.63332387, -0.93171798,  0.05749049,  0.96724906])\n\"\"\"\ndef genSine(A, f, phi, fs, t):\n    \"\"\"\n    Inputs:\n        A (float) =  amplitude of the sinusoid\n        f (float) = frequency of the sinusoid in Hz\n        phi (float) = initial phase of the sinusoid in radians\n        fs (float) = sampling frequency of the sinusoid in Hz\n        t (float) =  duration of the sinusoid (is second)\n    Output:\n        The function should return a numpy array\n        x (numpy array) = The generated sinusoid (use np.cos())\n    \"\"\"\n    Xs = []\n    Tn = np.arange(0.0, t, 1.0/fs)\n    lenTn = int(t*fs)\n    for i in range(lenTn):\n        Xs.append(A*np.cos(2*np.pi*f*Tn[i] + phi))\n    x = np.array(Xs)\n    return(x)\n\nsinA = genSine(0.5, 2.0, 0.0, 1000.0, 2.0)\nsinB = genSine(0.5, 2.0, 0.0, 1000.0, 2.0)\nsinSum = sinA + sinB\nplt.plot(sinA)\nplt.plot(sinB)\nplt.plot(sinSum)\n", "meta": {"hexsha": "0a5dbce89522621d5f58480fbf846bf497f7e931", "size": 1493, "ext": "py", "lang": "Python", "max_stars_repo_path": "assets/genSine.py", "max_stars_repo_name": "larzeitlin/larzeitlin.github.io", "max_stars_repo_head_hexsha": "25f99dbff8bbad38886548a6470f284c73e1bbfe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-07-25T05:54:18.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-25T05:54:18.000Z", "max_issues_repo_path": "assets/genSine.py", "max_issues_repo_name": "larzeitlin/larzeitlin.github.io", "max_issues_repo_head_hexsha": "25f99dbff8bbad38886548a6470f284c73e1bbfe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assets/genSine.py", "max_forks_repo_name": "larzeitlin/larzeitlin.github.io", "max_forks_repo_head_hexsha": "25f99dbff8bbad38886548a6470f284c73e1bbfe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9318181818, "max_line_length": 130, "alphanum_fraction": 0.6409912927, "include": true, "reason": "import numpy", "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551495568569, "lm_q2_score": 0.9073122257466114, "lm_q1q2_score": 0.8754248732675115}}
{"text": "import random\nimport time\nimport numpy as np\n\n\n# Check if a number is a power of 2 using bit manipulations\ndef pow_of_2_check(n: int) -> bool:\n    assert n > 0, f\"The number for power-of-2-check should be a POSITIVE integer. Here n = {n}.\"\n    return n & (n - 1) == 0  # &: bit-wise and\n\n\n# O(n**log_2^7) sub-cubic time complexity\ndef strassen_mat_mult(m1: np.ndarray, m2: np.ndarray) -> np.ndarray:\n    assert pow_of_2_check(m1.shape[0]) and m1.shape[0] == m1.shape[1] == m2.shape[0] == m2.shape[1], \\\n        f\"Both mat should be of shape 2^n*2^n with the same n. Here the shapes are {m1.shape}, {m2.shape}.\"\n\n    n = m1.shape[0]\n    if n <= 2:  # Base case\n        return m1 @ m2\n    else:\n        # Split m1 and m2 evenly into 4 sub-matrices each\n        half_n = n//2\n        a, b, c, d = m1[:half_n, :half_n], m1[:half_n, half_n:], m1[half_n:, :half_n], m1[half_n:, half_n:]\n        e, f, g, h = m2[:half_n, :half_n], m2[:half_n, half_n:], m2[half_n:, :half_n], m2[half_n:, half_n:]\n        # Compute the 7 products\n        p1 = strassen_mat_mult(a, f-h)\n        p2 = strassen_mat_mult(a+b, h)\n        p3 = strassen_mat_mult(c+d, e)\n        p4 = strassen_mat_mult(d, g-e)\n        p5 = strassen_mat_mult(a+d, e+h)\n        p6 = strassen_mat_mult(b-d, g+h)\n        p7 = strassen_mat_mult(a-c, e+f)\n        # Combine the results\n        output_1 = p5 + p4 - p2 + p6\n        output_2 = p1 + p2\n        output_3 = p3 + p4\n        output_4 = p1 + p5 - p3 - p7\n    return np.concatenate((np.concatenate((output_1, output_2), axis=1), np.concatenate((output_3, output_4), axis=1)),\n                          axis=0)\n\n\nif __name__ == '__main__':\n    # Test function \"pow_of_2_check\"\n    test = 1483948\n    print(f\"The number is a power of 2: {pow_of_2_check(test)}\")\n    test = 2 ** 10\n    print(f\"The number is a power of 2: {pow_of_2_check(test)}\")\n\n    # Test Strassen matrix multiplication algorithm\n    mat_size = 2**6\n    mat_1 = random.randint(1, 100)*np.random.rand(mat_size, mat_size)\n    mat_2 = random.randint(1, 100)*np.random.rand(mat_size, mat_size)\n    ans = strassen_mat_mult(mat_1, mat_2)\n    # print(f\"Product = {ans}\")\n    print(f\"Normalized Fresenius norm of (ans - np mat mult result): {np.linalg.norm(ans - mat_1@mat_2)/mat_size}\")\n\n    repetition = int(1e2)\n    start = time.time()\n    for _ in range(repetition):\n        strassen_mat_mult(mat_1, mat_2)\n    print(f\"Strassen matrix multiplication average time = {(time.time() - start)/repetition}s\")\n", "meta": {"hexsha": "267957a3551d720319effce9540513c3209cad31", "size": 2469, "ext": "py", "lang": "Python", "max_stars_repo_path": "StrassenMatMult.py", "max_stars_repo_name": "fxie520/Coursera-Algo-Specialization", "max_stars_repo_head_hexsha": "4ae744ec2a578ac19465305077427eb0fa44a7e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "StrassenMatMult.py", "max_issues_repo_name": "fxie520/Coursera-Algo-Specialization", "max_issues_repo_head_hexsha": "4ae744ec2a578ac19465305077427eb0fa44a7e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "StrassenMatMult.py", "max_forks_repo_name": "fxie520/Coursera-Algo-Specialization", "max_forks_repo_head_hexsha": "4ae744ec2a578ac19465305077427eb0fa44a7e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8225806452, "max_line_length": 119, "alphanum_fraction": 0.6164439044, "include": true, "reason": "import numpy", "num_tokens": 818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551505674445, "lm_q2_score": 0.9073122244934722, "lm_q1q2_score": 0.8754248729753321}}
{"text": "from math import sqrt, pi, exp\nimport numpy as np\n\ndef distance(x1, y1, x2, y2):\n    \"\"\"\n    Distance between two points (x1, y1), (x2, y2).\n    \"\"\"\n    return sqrt((x1-x2)**2 + (y1-y2)**2)\n\ndef array_dist(p1, p2):\n    \"\"\"\n    Distance between two points represented by arrays.\n    \"\"\"\n    return distance(p1[0], p1[1], p2[0], p2[1])\n\ndef direction(p1, p2):\n    \"\"\"\n    Direction between two points p1 and p2.\n    \"\"\"\n    return (p2-p1)/distance(p1[0], p1[1], p2[0], p2[1])\n\ndef theta(v1, v2):\n    \"\"\"\n    Computes angle between two vectors\n    \"\"\"\n    val = v1.dot(v2)/(np.linalg.norm(v1)*np.linalg.norm(v2))\n    if val > 1:\n        print(val, v1, v2)\n        return np.arccos(1)\n    elif val < -1:\n        print(val, v1, v2)\n        return np.arccos(-1)\n    return np.arccos(val)\n\ndef proj(v1, v2):\n    \"\"\"\n    Computes projection of v1 onto v2\n    \"\"\"\n    return np.dot(v1, v2)/np.linalg.norm(v2)\n\ndef t1_force(t):\n    M = 0.01\n    N = 15\n    s1 = 2\n    s2 = 0.3\n    sig_square = s1**2 + s2**2\n\n    s = s1**2 + s2**2\n    A = -(M * N) / sqrt(2*pi*s)\n    return A * exp(-(t**2) / (2*s)) * (-t/s)\n    #return (M*N*t/(ss*sqrt(2*pi*ss))) * exp(-(t**2)/(2*ss))\n    #return ((M*N)/(sqrt(2*pi*sig_square))) * ((2*t*exp((-t**2)/(2*sig_square)))/(2*sig_square))\n\ndef t2_force(p, orig):\n    return 0.005*array_dist(p, orig)\n\ndef ccw(A, B, C):\n    \"\"\"\n    Check if a point C is counter-clockwise to AB.\n    \"\"\"\n    return (C[1] - A[1])*(B[0]-A[0]) > (B[1]-A[1])*(C[0]-A[0])\n\ndef is_intersect(A, B, C, D):\n    \"\"\"\n    Check if two line segments AB and CD intersect.\n    \"\"\"\n    return ccw(A, C, D) != ccw(B, C, D) and ccw(A, B, C) != ccw(A, B, D)\n\ndef line_line_segment_intersect(p, d, p1, p2):\n    \"\"\"\n    Check if a line defined by point p and direction d intersects\n    a segment p1p2.\n    \"\"\"\n\n    extend1 = [p[0] + 500000*d[0], p[1] + 500000*d[1]]\n    extend2 = [p[0] - 500000*d[0], p[1] - 500000*d[1]]\n\n    return is_intersect(p, extend1, p1, p2) or is_intersect(p, extend2, p1, p2)\n\ndef minDistance(A, B, E) :\n    \"\"\"\n    Minimum distance from a point E to line segment AB. Adapted from GeeksforGeeks.\n    \"\"\"\n\n    # vector AB\n    AB = [None, None]\n    AB[0] = B[0] - A[0]\n    AB[1] = B[1] - A[1]\n\n    # vector BP\n    BE = [None, None]\n    BE[0] = E[0] - B[0]\n    BE[1] = E[1] - B[1]\n\n    # vector AP\n    AE = [None, None]\n    AE[0] = E[0] - A[0]\n    AE[1] = E[1] - A[1]\n\n    # Variables to store dot product\n\n    # Calculating the dot product\n    AB_BE = AB[0] * BE[0] + AB[1] * BE[1]\n    AB_AE = AB[0] * AE[0] + AB[1] * AE[1]\n\n    # Minimum distance from\n    # point E to the line segment\n    reqAns = 0\n\n    # Case 1\n    if (AB_BE > 0) :\n\n        # Finding the magnitude\n        y = E[1] - B[1]\n        x = E[0] - B[0]\n        reqAns = sqrt(x * x + y * y)\n\n    # Case 2\n    elif (AB_AE < 0) :\n        y = E[1] - A[1]\n        x = E[0] - A[0]\n        reqAns = sqrt(x * x + y * y)\n\n    # Case 3\n    else:\n\n        # Finding the perpendicular distance\n        x1 = AB[0]\n        y1 = AB[1]\n        x2 = AE[0]\n        y2 = AE[1]\n        mod = sqrt(x1 * x1 + y1 * y1)\n        reqAns = abs(x1 * y2 - y1 * x2) / mod\n\n    return reqAns\n", "meta": {"hexsha": "7ae457554a6c9cabbf43411ce110fa2ffb9f1780", "size": 3127, "ext": "py", "lang": "Python", "max_stars_repo_path": "graphgen/data/utils.py", "max_stars_repo_name": "bhaveshk658/graphgen", "max_stars_repo_head_hexsha": "4a988ccd6a03a12a0ea900d8f2ea7204e61104cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-30T22:31:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-30T22:31:00.000Z", "max_issues_repo_path": "graphgen/data/utils.py", "max_issues_repo_name": "bhaveshk658/graphgen", "max_issues_repo_head_hexsha": "4a988ccd6a03a12a0ea900d8f2ea7204e61104cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphgen/data/utils.py", "max_forks_repo_name": "bhaveshk658/graphgen", "max_forks_repo_head_hexsha": "4a988ccd6a03a12a0ea900d8f2ea7204e61104cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9926470588, "max_line_length": 96, "alphanum_fraction": 0.5059162136, "include": true, "reason": "import numpy", "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446471538802, "lm_q2_score": 0.8991213799730774, "lm_q1q2_score": 0.8754247187523968}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n# ## Monte Carlo - Euler Discretization - Part II\n# *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).*\n# *Euler Discretization – continued.*\n# In[1]:\nimport numpy as np  \nimport pandas as pd  \nfrom pandas_datareader import data as web  \nfrom scipy.stats import norm \nimport matplotlib.pyplot as plt  \nget_ipython().run_line_magic('matplotlib', 'inline')\nticker = 'MSFT'  \ndata = pd.DataFrame()\ndata[ticker] = web.DataReader(ticker, data_source='yahoo', start='2000-1-1')['Adj Close']\nlog_returns = np.log(1 + data.pct_change())\nstdev = log_returns.std() * 250 ** 0.5\nstdev = stdev.values\nr = 0.025\nT = 1.0 \nt_intervals = 250 \ndelta_t = T / t_intervals  \niterations = 10000  \nZ = np.random.standard_normal((t_intervals + 1, iterations))  \nS = np.zeros_like(Z) \nS0 = data.iloc[-1]  \nS[0] = S0 \nfor t in range(1, t_intervals + 1):\n    S[t] = S[t-1] * np.exp((r - 0.5 * stdev ** 2) * delta_t + stdev * delta_t ** 0.5 * Z[t])\nplt.figure(figsize=(10, 6))\nplt.plot(S[:, :10]);\n# ******\n# Use numpy.maximum to create a vector with as many elements as there are columns in the S matrix.\n# In[2]:\np = np.maximum(S[-1] - 110, 0)\n# In[3]:\np\n# In[4]:\np.shape\n# Use the following formula to forecast the price of a stock option.\n# $$\n# C = \\frac{exp(-r \\cdot T) \\cdot \\sum{p_i}}{iterations}\n# $$\n# In[5]:\nnp.sum(p)\n# In[6]:\nC = np.exp(-r * T) * np.sum(p) / iterations\nC  \n# Because this pricing model is based on random iterations, you will obtain a different result every time you re-run the code in this document. Expand the “Kernel” list from the Jupyter menu and click on “Restart and run all”/”Restart & run all cells” to verify this is true.\n", "meta": {"hexsha": "f6897398897e6711749ce1ffc67105e5e17e397b", "size": 1712, "ext": "py", "lang": "Python", "max_stars_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_110-MC-EulerDiscretization-PartII-Solution_Yahoo_Py3.py", "max_stars_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_stars_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-04T11:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-10T15:36:42.000Z", "max_issues_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_110-MC-EulerDiscretization-PartII-Solution_Yahoo_Py3.py", "max_issues_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_issues_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-03-30T16:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:37:21.000Z", "max_forks_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_110-MC-EulerDiscretization-PartII-Solution_Yahoo_Py3.py", "max_forks_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_forks_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T11:26:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T11:26:16.000Z", "avg_line_length": 34.24, "max_line_length": 275, "alphanum_fraction": 0.6752336449, "include": true, "reason": "import numpy,from scipy", "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454896, "lm_q2_score": 0.9196425284247979, "lm_q1q2_score": 0.875373911548092}}
{"text": "#!usr/bin/python\n\"\"\"\nauthor  : Bhekimpilo Ndhlela\nauthor  : 18998712\nmodule  : Applied Mathematics(Numerical Methods) TW324\ntask    : computer assignment 04 question 4\nsince   : Friday-23-03-2018\n\"\"\"\ndef trapezium(exact_I, H, x0=0., debug=True):\n    apprx_I = array([h/2. * (exp(x0) + exp(h)) for h in H])\n    return array([abs(apI - exI) for apI, exI in zip(apprx_I, exact_I)])\n\ndef midpoint(exact_I, H, x0=0., debug=True):\n    W = array([x0 + (h / 2.0) for h in H])\n    apprx_I = array([h * exp(w) for h, w in zip(H, W)])\n    return array([abs(apI - exI) for apI, exI in zip(apprx_I, exact_I)])\n\ndef simpson(exact_I, H, x0=0., debug=True):\n    apprx_I = array([h/6.*(exp(x0)+(4.*exp(h/2.))+exp(h)) for h in H])\n    return array([abs(apI - exI) for apI, exI in zip(apprx_I, exact_I)])\n\ndef debug(abs_err_s, abs_err_m, abs_err_t, debug=True):\n    if debug is True:\n        print \"DEBUG MODE: [ON] [Question 4 Simpson's method]\"\n        print \"SIMPSONS METHOD\\t\\tMIDPOINT METHOD\\t\\tTRAPEZIUM METHOD\"\n        for s, m, t in zip(abs_err_s, abs_err_m, abs_err_t):\n            print \"{:.20f}\".format(s),\"{:.20f}\".format(m),\"{:.20f}\".format(t)\n    else:\n        print \"DEBUG MODE: [OFF] [Question 4 Simpson's method]\"\n\ndef plot_abs_errs(abs_err_t, abs_err_m, abs_err_s):\n    #loglog plot to display the error as function of the step size\n    plt.title(\"|xc-x| of: The Midpoint, Simpson & Trapezium Methods against h\")\n    plt.ylabel(\"Midpoint vs Simpson vs Trapezium\")\n    plt.xlabel(\"h\")\n    plt.yscale('log'); plt.xscale('log')\n    plt.plot([1., .1, .01], abs_err_t, \"k-\", label=\"Trapezium\")\n    plt.plot([1., .1, .01], abs_err_m, \"r-\", label=\"Midpoint\")\n    plt.plot([1., .1, .01], abs_err_s, \"g-\", label=\"Simpson\")\n    plt.legend(bbox_to_anchor=(.65, .9))\n    plt.show()\n\nif __name__ == \"__main__\":\n    from numpy import (exp, abs, array)\n    import matplotlib.pyplot as plt\n\n    H         = array([1., .1, .01])\n    exact_I   = array([exp(h) - 1 for h in H])\n\n    abs_err_t = trapezium(exact_I, H)\n    abs_err_m = midpoint(exact_I, H)\n    abs_err_s = simpson(exact_I, H)\n\n    debug(abs_err_s, abs_err_m, abs_err_t)\n    plot_abs_errs(abs_err_t, abs_err_m, abs_err_s)\nelse:\n    from sys import exit\n    exit(\"USAGE: python q5.py\")\n", "meta": {"hexsha": "7dce889adbd58925b65b579b48f1735d40b95f19", "size": 2228, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment_04/src/q4.py", "max_stars_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_stars_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-28T18:36:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-28T18:36:55.000Z", "max_issues_repo_path": "assignment_04/src/q4.py", "max_issues_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_issues_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment_04/src/q4.py", "max_forks_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_forks_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-16T04:26:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-16T04:26:44.000Z", "avg_line_length": 37.7627118644, "max_line_length": 79, "alphanum_fraction": 0.631508079, "include": true, "reason": "from numpy", "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.9263037226647284, "lm_q1q2_score": 0.8753521222221589}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Give the parameters.\nH0 = 7.16e-11 # [yr^-1]\nomega_0 = 1\n\n# Define a and time-derivative of a.\na = lambda t: ((3/2)*H0*t)**(2/3)\na_dot = lambda t: H0*((3/2)*H0*t)**(-1/3)\n\n# Define the function to be solved.\ndef ode(t, y):\n\n    \"\"\"\n    y ... A vector function containing D and dD/dt\n    t ... time to integrate over\n\n    \"\"\"\n\n    # Define the initial conditions. Will assign values later.\n    D , dD_dt = y[0], y[1]\n\n    d2D_dt2 = -2*(a_dot(t)/a(t))*dD_dt + (3/2)*omega_0*(H0**2)*(D/(a(t)**3))\n\n    return np.array([dD_dt, d2D_dt2])\n\n# define the solver method.\ndef rk4(ode,y,t,h):\n\n    \"\"\"\n    ode ... ordinary differential equation to solve\n    y   ... A vector fucntion containing D and dD/dt\n    t   ... time to integrate over\n    h   ... integration step\n\n    Method using here is the classic Runge-Kutta (4-th order), acquired L10.\n\n    \"\"\"\n\n    k1 = h * ode(t, y)\n    k2 = h * ode(t+h/2., y+k1/2.)\n    k3 = h * ode(t+h/2., y+k2/2.)\n    k4 = h * ode(t+h, y+k3)\n\n    return k1/6. + k2/3. + k3/3. + k4/6.\n\n# Define the ode solver.\ndef ode_solver(init, lower, upper, N):\n\n    # Define the integration step.\n    h = (upper-lower)/N\n\n    # Define initial conditions and assign values.\n    y, t_values, D_values = init, [], []\n\n    # Solve the ode using rk4.\n    for i in np.arange(lower, upper, h):\n        t_values.append(i)\n        D_values.append(y[0])\n        y += rk4(ode,y,i,h)\n\n    return t_values, D_values\n\n\n# Define the time range and number of data points.\nt_init, t_final, t_step = 1., 1000., 10\nN = (t_final-t_init)*t_step\n\n# Plot given the initial conditions.\nplt.figure()\n\ncase1, case2, case3 = [3,2], [10,-10], [5,0]\nall_cases = [[case1,'case1'], [case2,'case2'], [case3,'case3']]\n\nfor i in range(len(all_cases)):\n    t_values, D_values = ode_solver(all_cases[i][0], t_init, t_final, N)\n    plt.loglog(t_values, D_values, label=all_cases[i][1])\n\nplt.xlabel('t', fontsize=14)\nplt.ylabel('D(t)', fontsize=14)\nplt.legend()\n\nplt.savefig('./plots/handin2_p3.png')\nplt.close()\n", "meta": {"hexsha": "827d43ae5bcacbe20d28868ea9d3bbc86157f1e4", "size": 2042, "ext": "py", "lang": "Python", "max_stars_repo_path": "Hand_in_exercise_2/handin2_p3.py", "max_stars_repo_name": "rywjhzd/Numerical-Recipes-In-Astrophysics", "max_stars_repo_head_hexsha": "1f4bf40c504cd5f0117a9986c2756dcfd5bfc5c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Hand_in_exercise_2/handin2_p3.py", "max_issues_repo_name": "rywjhzd/Numerical-Recipes-In-Astrophysics", "max_issues_repo_head_hexsha": "1f4bf40c504cd5f0117a9986c2756dcfd5bfc5c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hand_in_exercise_2/handin2_p3.py", "max_forks_repo_name": "rywjhzd/Numerical-Recipes-In-Astrophysics", "max_forks_repo_head_hexsha": "1f4bf40c504cd5f0117a9986c2756dcfd5bfc5c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7441860465, "max_line_length": 76, "alphanum_fraction": 0.6087169442, "include": true, "reason": "import numpy", "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924777713886, "lm_q2_score": 0.9005297921244243, "lm_q1q2_score": 0.8753081839539727}}
{"text": "import math\nimport numpy as np\n\ndef evenParity(n):\n\t\"\"\"Determines if n is an even parity.\n\n\tCalculates the number of 1 bits in the binary representation of the given \n\tinteger, n. An even parity is true if the number of 1 bits in the\n\trepresentation is even.\n\n\tArgs:\n\t\tn: integer to check for even parity.\n\n\tReturns:\n\t\tA 0 if n is an even parity, else a 1.\n\t\"\"\"\n\tbinary =  \"{0:b}\".format(n)\n\treturn binary.count('1') % 2\n\ndef oddParity(n):\n\t\"\"\"Determines if n is an odd parity.\n\n\tCalculates the number of 1 bits in the binary representation of the given \n\tinteger, n. If the number is odd,  outputs a 0. If the number is even, \n\toutputs a 1.\n\n\tArgs:\n\t\tn: integer to check for odd parity.\n\n\tReturns:\n\t\tA 0 if n is an odd parity, else a 1.\n\t\"\"\"\n\tbinary = \"{0:b}\".format(n)\n\treturn (binary.count('1') + 1) % 2\n\ndef adder(n):\n\t\"\"\"Adds 42 to a given number.\n\n\tArgs:\n\t\tn: integer to add to.\n\n\tReturns:\n\t\tThe value of n added by 42.\n\t\"\"\"\n\treturn n + 42\n\ndef addThem(n, m):\n\t\"\"\"Calculates the sum of n and m.\n\n\tArgs:\n\t\tn: an integer to add.\n\t\tm: an integer to add.\n\tReturns:\n\t\tThe sum of n and m.\n\t\"\"\"\n\treturn n + m\n\ndef multiply(n, m):\n\t\"\"\"Returns n multiplied by m.\n\n\tArgs:\n\t\tn: integer to be multiplied by\n\t\tm: integer to be multiplied by\n\n\tReturns:\n\t\tThe product of n and m.\n\t\"\"\"\n\treturn n * m\n\ndef multiplyAndAdd(n, m):\n\t\"\"\"Adds 5 to n, adds 7 to m, and returns the product of the two.\n\n\tf(n, m) = (n + 5) * (m + 7)\n\n\tArgs:\n\t\tn: integer as an input to the function\n\t\tm: integer as an input to the function\n\n\tReturns:\n\t\tThe output of the function given n and m.\n\t\"\"\"\n\treturn (n + 5) * (m + 7)\n\ndef makePalindrome(s):\n\t\"\"\"Makes a palindrome from a given string.\n\n\tReverses and appends s to the end of s. This guarantees the return \n\tstatement is a palindrome.\n\n\tArgs:\n\t\ts: a string\n\n\tReturns:\n\t\tA palindrome formed by appending s reversed to the end of s.\n\t\"\"\"\n\treturn s + s[::-1]\n\ndef isPalindrome(s):\n\t\"\"\"Validates whether the input is a palindrome.\n\n\tArgs:\n\t\ts: a string\n\n\tReturns:\n\t\tTrue if the input is a valid palindrome, else False.\n\t\"\"\"\n\treturn all(s[i] == s[-i - 1] for i in range(len(s) >> 1))\n\ndef sine(x):\n\t\"\"\"Returns the sin of x radians.\n\n\tArgs:\n\t\tx: number of radians\n\n\tReturns:\n\t\tThe sine of x radians.\n\t\"\"\"\n\treturn math.sin(x)\n\ndef expansionTerms(x):\n\toutput = np.zeros(9, dtype='float32')\n\tn = 1\n\tfor i in range(9):\n\t\tif i % 2 == 0:\n\t\t\toutput[i] = float((x ** n) / math.factorial(n))\n\t\telse:\n\t\t\toutput[i] = float(-(x ** n) / math.factorial(n))\n\t\tn += 2\n\treturn output\n\ndef fib(n):\n\t\"\"\"Approximates the nth Fibonacci number.\n\n\tSince this uses Binet's formula, it is only exactly accurate from 1 to 70.\n\tPast n values of 70, it is only an approximation.\n\n\tBinet's formula is defined as:\n\tF(n) = ((Phi ^ n) - ((- Phi) ^ -n)) / sqrt(5)\n\t\t\t = (((1 + sqrt(5)) / 2) ^ n) - ((1 - sqrt(5)) / 2) ^ n)) / sqrt(5))\n\n\tArgs:\n\t\tn: integer for the nth number in the Fibonacci sequence\n\n\tReturns:\n\t\tThe output of Binet's forumula with input n, an approximation of the nth\n\t\tnumber in the Fibonacci sequence.\n\t\"\"\"\n\treturn round(((((1 + math.sqrt(5)) / 2) ** n)\n\t\t\t\t- (((1 - math.sqrt(5)) / 2) ** n))\n\t\t\t\t/ math.sqrt(5))\n\ndef testFibAccuracy():\n\t\"\"\"Calculates when the function fib(n) becomes inaccurate.\n\n\tExactly up to 70.\n\t71 - 72 are off by 1.\n\t73 and on are off by more than 1.\n\n\tReturns:\n\t\tfn: the last Fibonacci number found by using the recursive function.\n\t\tcount: the number of Fibonacci numbers calculated.\n\t\tfib(count): an approximation for the last Fibonacci number.\n\t\"\"\"\n\tfn = f1 = f2 = 1\n\tcount = 2\n\twhile (fn == fib(count)) | (fn == fib(count) + 1) | (fn == fib(count) - 1):\n\t\tfn = f1 + f2\n\t\tf2, f1 = f1, fn\n\t\tcount+=1\n\treturn fn, count, fib(count)\n\ndef determinant(m):\n\t\"\"\"Calculates the determinant of a matrix.\n\n\tArgs:\n\t\tm: array of arrays that represents a matrix.\n\n\tReturns:\n\t\tThe determinant of a matrix.\n\t\"\"\"\n\treturn np.linalg.det(m)\n\ndef main():\n\tprint(\"evenParity(2) ->\", evenParity(2))\n\tprint(\"evenParity(3) ->\", evenParity(3))\n\tprint(\"evenParity(10) ->\", evenParity(10))\n\tprint(\"oddParity(2) ->\", oddParity(2))\n\tprint(\"oddParity(3) ->\", oddParity(3))\n\tprint(\"oddParity(10) ->\", oddParity(10))\n\tprint(\"oddParity(1243) + evenParity(1243) == 1 ->\", \n\t\t   oddParity(1243) + evenParity(1243) == 1)\n\tprint(\"adder(1) ->\", adder(1))\n\tprint(\"adder(5) ->\", adder(5))\n\tprint(\"multiply(3, 7) ->\", multiply(3, 7))\n\tprint(\"multiplyAndAdd(3, 7) ->\", multiplyAndAdd(3, 7))\n\tprint(\"isPalindrome('abc') ->\", isPalindrome('abc'))\n\tprint(\"isPalindrome('yootnooy') ->\", isPalindrome('yootnooy'))\n\tprint(\"makePalindrome('This is the final countdown!') ->\",\n\t\tmakePalindrome('This is the final countdown!'))\n\tprint(\"isPalindrome(makePalindrome('This is the final countdown!')) ->\", \n\t\tisPalindrome(makePalindrome('This is the final countdown!')))\n\tprint(\"sine(math.pi) ->\", sine(math.pi))\n\tprint(\"sine(math.pi / 2) ->\", sine(math.pi / 2))\n\tprint(\"fib(2) ->\", fib(2))\n\tprint(\"fib(3) ->\", fib(3))\n\tprint(\"fib(4) ->\", fib(4))\n\tprint(\"fib(5) ->\", fib(5))\n\tprint(\"fib(6) ->\", fib(6))\n\tfn, count, approx = testFibAccuracy()\n\tprint(\"Actual\", count, \"number in fib sequence =\", fn, \n\t\t\"Approximation =\", approx)\n\nif __name__ == \"__main__\":\n    main()", "meta": {"hexsha": "2ac507764fc1a0441cbe7de158d8c13f428c8a46", "size": 5140, "ext": "py", "lang": "Python", "max_stars_repo_path": "trainingFunctions.py", "max_stars_repo_name": "derrowap/MA490-MachineLearning-FinalProject", "max_stars_repo_head_hexsha": "2f6003edd985cefdddfba8f64c2c0effdd51a92e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trainingFunctions.py", "max_issues_repo_name": "derrowap/MA490-MachineLearning-FinalProject", "max_issues_repo_head_hexsha": "2f6003edd985cefdddfba8f64c2c0effdd51a92e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trainingFunctions.py", "max_forks_repo_name": "derrowap/MA490-MachineLearning-FinalProject", "max_forks_repo_head_hexsha": "2f6003edd985cefdddfba8f64c2c0effdd51a92e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0186915888, "max_line_length": 76, "alphanum_fraction": 0.6392996109, "include": true, "reason": "import numpy", "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828601, "lm_q2_score": 0.9136765169496872, "lm_q1q2_score": 0.8752219472036169}}
{"text": "\"\"\"\nThis script plots the analytic solution to the differential equation in \nexercise 2.2.3 of the book `Nonlinear Dynamics and Chaos` by Steven H. Strogatz. \n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef get_velocities(times, x0: float):\n    # Fix the integration constant using the initial condition\n    c = 1.0 / (x0 ** 2) - 1.0\n    if x0 < 0.0:\n        return -1.0 / np.sqrt(1.0 + c * np.exp(-2.0 * times))\n    else:\n        return +1.0 / np.sqrt(1.0 + c * np.exp(-2.0 * times))\n\n\nif __name__ == \"__main__\":\n    # The set of initial conditions that we use.\n    initial_conditions = [2.0, 0.7, 0.5, 0.3, -0.3, -0.5, -0.7, -2.0]\n\n    # The time steps we use\n    time_steps = np.linspace(0, 3, 100)\n\n    fig, ax = plt.subplots()\n\n    plt.title(r\"$\\dot{x}=x-x^3$\")\n    plt.xlabel(\"t\")\n    plt.ylabel(\"x\")\n    for counter, ic in enumerate(initial_conditions):\n        velocities = get_velocities(time_steps, ic)\n        ax.plot(time_steps, velocities, color=f\"C{counter}\")\n\n    # Add the fixed points\n    plt.plot(time_steps, np.zeros(len(time_steps)), color=\"gray\", linestyle=\"-.\")\n    plt.plot(time_steps, np.ones(len(time_steps)), color=\"gray\", linestyle=\"--\")\n    plt.plot(time_steps, -np.ones(len(time_steps)), color=\"gray\", linestyle=\"--\")\n\n    # Draw the plot\n    # plt.savefig('ex_2_2_3.pdf')\n    plt.show()\n", "meta": {"hexsha": "2db97fa46684e7cee118779560a7eef248f9a3d5", "size": 1330, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch2/ex2_2_3.py", "max_stars_repo_name": "FractalArt/chaos_exercises", "max_stars_repo_head_hexsha": "ce86858ceb887560a30f6fd313d920a18f2da5c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-17T18:28:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T18:28:50.000Z", "max_issues_repo_path": "ch2/ex2_2_3.py", "max_issues_repo_name": "FractalArt/chaos_exercises", "max_issues_repo_head_hexsha": "ce86858ceb887560a30f6fd313d920a18f2da5c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch2/ex2_2_3.py", "max_forks_repo_name": "FractalArt/chaos_exercises", "max_forks_repo_head_hexsha": "ce86858ceb887560a30f6fd313d920a18f2da5c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6666666667, "max_line_length": 81, "alphanum_fraction": 0.6278195489, "include": true, "reason": "import numpy", "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305360354471, "lm_q2_score": 0.9086178975514608, "lm_q1q2_score": 0.8752085045098945}}
{"text": "import numpy as np\nimport skimage\nimport utils\nimport pathlib\nimport matplotlib.pyplot as plt\nimport functools as ft\n\n'''\n[1.0 points] Implement a function in task2a.py/task2a.ipynb that implements Otsu’s algorithm for thresholding, and returns a single threshold value.\nSegment the images thumbprint.png and polymercell.png, and include the results in your report.\n'''\ndef sum_to_threshhold(arr: np.ndarray, threshold: int):\n    sum = 0\n    for i, el in enumerate(arr):\n        if(i < threshold):\n            sum+=el\n\n    return sum\n\ndef mean_to_threshhold(arr: np.ndarray, threshold: int, less_than: bool):\n    numerator_sum = 0\n    divisor_sum = 0\n\n    if(less_than):\n        for i, el in enumerate(arr):\n            if(i < threshold):\n                numerator_sum += i * el\n                divisor_sum += el\n    else:\n        for i, el in enumerate(arr):\n            if(i >= threshold):\n                numerator_sum += i * el\n                divisor_sum += el\n\n    return numerator_sum/divisor_sum\n\ndef otsu_thresholding(im: np.ndarray) -> int:\n    \"\"\"\n        Otsu's thresholding algorithm that segments an image into 1 or 0 (True or False)\n        The function takes in a grayscale image and outputs a boolean image\n\n        args:\n            im: np.ndarray of shape (H, W) in the range [0, 255] (dtype=np.uint8)\n        return:\n            (int) the computed thresholding value\n    \"\"\"\n    assert im.dtype == np.uint8\n    # START YOUR CODE HERE ### (You can change anything inside this block)\n    # You can also define other helper functions\n\n    # Compute normalized histogram\n    intensity_count = np.zeros(256)\n    for i in range(len(im)):\n        for j in range(len(im[i])):\n            intensity_count[im[i][j]] += 1\n\n    #test = [9,6,4,5,8,4]\n    num_pixels = im.shape[0]*im.shape[1]\n    best_between_class_variance = -100\n    best_threshold = -1\n    # Check for each threshold if it produces a better between class variance\n    for threshold in range(1,256):\n        background_percentage = sum_to_threshhold(intensity_count, threshold)/num_pixels\n        foreground_percentage = 1-background_percentage\n\n        background_mean = mean_to_threshhold(intensity_count, threshold, True)\n        foreground_mean = mean_to_threshhold(intensity_count, threshold, False)\n\n        between_class_variance = background_percentage*foreground_percentage*(background_mean-foreground_mean)**2\n        if(best_between_class_variance < between_class_variance):\n            best_between_class_variance = between_class_variance\n            best_threshold = threshold\n    \n    threshold = best_threshold\n    '''\n    plt.imshow(im, cmap=\"gray\")\n    plt.show()\n    '''\n    # Plot intensity distribution\n    intensity_levels = list(range(0,256))\n    plt.bar(intensity_levels, intensity_count)\n    plt.show()\n    \n    return threshold\n    ### END YOUR CODE HERE ###\n\n\nif __name__ == \"__main__\":\n    # DO NOT CHANGE\n    impaths_to_segment = [\n        pathlib.Path(\"thumbprint.png\"),\n        pathlib.Path(\"polymercell.png\"),\n        pathlib.Path(\"defective-weld.png\")\n    ]\n    for impath in impaths_to_segment:\n        im = utils.read_image(impath)\n        threshold = otsu_thresholding(im)\n        print(\"Found optimal threshold:\", threshold)\n\n        # Segment the image by threshold\n        segmented_image = (im >= threshold)\n        assert im.shape == segmented_image.shape, \"Expected image shape ({}) to be same as thresholded image shape ({})\".format(\n            im.shape, segmented_image.shape)\n        assert segmented_image.dtype == np.bool, \"Expected thresholded image dtype to be np.bool. Was: {}\".format(\n            segmented_image.dtype)\n\n        segmented_image = utils.to_uint8(segmented_image)\n\n        save_path = \"{}-segmented.png\".format(impath.stem)\n        utils.save_im(save_path, segmented_image)\n", "meta": {"hexsha": "2511828da78da4dac41b705329448102a96502c8", "size": 3815, "ext": "py", "lang": "Python", "max_stars_repo_path": "TDT4195/image_processing/A3/task2a.py", "max_stars_repo_name": "jorgstei/Datateknologi", "max_stars_repo_head_hexsha": "6fea7bf2c557cd93981c6996c7f4cca02f343d9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TDT4195/image_processing/A3/task2a.py", "max_issues_repo_name": "jorgstei/Datateknologi", "max_issues_repo_head_hexsha": "6fea7bf2c557cd93981c6996c7f4cca02f343d9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TDT4195/image_processing/A3/task2a.py", "max_forks_repo_name": "jorgstei/Datateknologi", "max_forks_repo_head_hexsha": "6fea7bf2c557cd93981c6996c7f4cca02f343d9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3693693694, "max_line_length": 148, "alphanum_fraction": 0.6587155963, "include": true, "reason": "import numpy", "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715435, "lm_q2_score": 0.916109614162018, "lm_q1q2_score": 0.8751770416668776}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 23 22:36:14 2019\r\n\r\nINSTITUTO FEDERAL DE EDUCAÇÃO, CIÊNCIA E TECNOLOGIA DO PÁRA - IFPA ANANINDEUA\r\n\r\n@author: \r\n        Prof. Dr. Denis C. L. Costa\r\n        \r\n        Discentes:\r\n            Heictor Alves de Oliveira Costa\r\n            Lucas Pompeu Neves\r\n        \r\nGrupo de Pesquisa: \r\n                 Gradiente de Modelagem Matemática e\r\n                 Simulação Computacional - GM²SC\r\n                 \r\nAssunto: \r\n        Derivadas Parciais\r\n        \r\nNome do sript: derivadas_parciais\r\n\r\nDisponível em: \r\n    https://github.com/GM2SC/DEVELOPMENT-OF-MATHEMATICAL-METHODS-IN-\r\n    COMPUTATIONAL-ENVIRONMENT/blob/master/SINEPEM_2019/derivadas_parciais.py\r\n    \r\n\"\"\"\r\n\r\n# Bibliotecas\r\n\r\n# Cálculo Diferencial e Integral: sympy\r\nimport sympy as sy\r\n\r\n# Variáveis simbólicas\r\nx,y = sy.symbols('x,y')\r\n\r\nprint('')\r\n\r\n# Função de várias Variáveis: f(x,y)\r\ndef f(x,y):\r\n    return 3*x**2*y**3\r\n\r\n# (f(x,y), x, 1) --> (Função, variável, ordem da derivada) \r\n# Derivada em função de x: dfx(x,y)\r\ndef dfx(x,y):\r\n    return sy.diff(f(x,y), x, 1) \r\n# Derivada em função de y: dfy(x,y)\r\ndef dfy(x,y):\r\n    return sy.diff(f(x,y), y, 1) \r\nprint('')\r\nprint('=======================================================')\r\nprint('Função Analisada: f(x,y) =', f(x,y))\r\n\r\nprint('Derivada Parcial em função de x: dfx(x,y) =', dfx(x,y))\r\n\r\nprint('Derivada Parcial em função de y: dfy(x,y) =', dfy(x,y))\r\n\r\nprint('=======================================================')\r\nprint('')\r\n# Valor Numérico das Derivadas Parciais\r\nprint('Valor Numérico da Derivada Parcial dfx')\r\nx1 = 2; y1 = -1\r\nprint('nos pontos x1 e y1 -->', (x1,y1))\r\n\r\nVN_dfx= dfx(x,y).subs(x,x1).subs(y,y1)\r\nprint('VN_dfx =', VN_dfx)\r\n\r\nprint('')\r\nprint('Valor Numérico da Derivada Parcial dfy')\r\nx2 = 1; y2 = 3\r\nprint('nos pontos x2 e y2 -->', (x2,y2))\r\nVN_dfy= dfy(x,y).subs(x,x2).subs(y,y2)\r\nprint('VN_dfy =', VN_dfy)\r\n\r\nprint('')\r\nprint('---> Fim do Programa derivadas_parciais <---')\r\n\r\n\r\n", "meta": {"hexsha": "927afeb6e35507e9fa5a9839d0923ba96ffff72b", "size": 1989, "ext": "py", "lang": "Python", "max_stars_repo_path": "derivadas_parciais.py", "max_stars_repo_name": "lucaspompeun/metodos-matematicos-aplicados-nas-engenharias-via-sistemas-computacionais", "max_stars_repo_head_hexsha": "008d397f76a935af1aba530cc0134b9dd326d3ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-09-27T03:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T18:43:45.000Z", "max_issues_repo_path": "primeira-edicao/derivadas_parciais.py", "max_issues_repo_name": "gm2sc-ifpa/metodos-matematicos-aplicados-nas-engenharias-via-sistemas-computacionais-master", "max_issues_repo_head_hexsha": "f435c366e08dc14b0557f2172ad3b841ddb7ef2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "primeira-edicao/derivadas_parciais.py", "max_forks_repo_name": "gm2sc-ifpa/metodos-matematicos-aplicados-nas-engenharias-via-sistemas-computacionais-master", "max_forks_repo_head_hexsha": "f435c366e08dc14b0557f2172ad3b841ddb7ef2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-09-13T20:00:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-19T03:04:00.000Z", "avg_line_length": 25.1772151899, "max_line_length": 78, "alphanum_fraction": 0.5676219206, "include": true, "reason": "import sympy", "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191309994468, "lm_q2_score": 0.9161096095812347, "lm_q1q2_score": 0.8751770361253876}}
{"text": "import numpy\nfrom matplotlib import pyplot\n\ndef forward_difference(f, x0, h):\n    return (f(x0+h) - f(x0)) / h\ndef backward_difference(f, x0, h):\n    return (f(x0) - f(x0-h)) / h\ndef central_difference(f, x0, h):\n    return (f(x0+h) - f(x0-h)) / (2*h)\n\ndef euler(f, x_end, y0, N):\n    x, dx = numpy.linspace(0, x_end, N+1, retstep=True)\n    y = numpy.zeros((len(y0),N+1))\n    y[:,0] = y0\n    for n in range(N):\n        y[:,n+1] = y[:,n] + dx * f(x[n], y[:,n])\n    return x, dx, y\n\nif __name__==\"__main__\":\n    h = 0.5\n    print(\"Forward difference, h=\",h, \"y'=\", \n          forward_difference(numpy.exp, 0, h))\n    print(\"Backward difference, h=\",h, \"y'=\", \n          backward_difference(numpy.exp, 0, h))\n    print(\"Central difference, h=\",h, \"y'=\", \n          central_difference(numpy.exp, 0, h))\n    h = 0.05\n    print(\"Forward difference, h=\",h, \"y'=\", \n          forward_difference(numpy.exp, 0, h))\n    print(\"Backward difference, h=\",h, \"y'=\", \n          backward_difference(numpy.exp, 0, h))\n    print(\"Central difference, h=\",h, \"y'=\", \n          central_difference(numpy.exp, 0, h))\n    h_all = 0.5/2**numpy.arange(1,10)\n    errors_forward = numpy.zeros_like(h_all)\n    errors_backward = numpy.zeros_like(h_all)\n    errors_central = numpy.zeros_like(h_all)\n    for i, h in enumerate(h_all):\n        errors_forward[i] = abs(1 - forward_difference(numpy.exp, 0, h))\n        errors_backward[i] = abs(1 - backward_difference(numpy.exp, 0, h))\n        errors_central[i] = abs(1 - central_difference(numpy.exp, 0, h))\n    pyplot.figure(figsize=(12,6))\n    pyplot.loglog(h_all, errors_forward, 'kx', label=\"Forward\")\n    pyplot.loglog(h_all, errors_backward, 'bo', label=\"Backward\")\n    pyplot.loglog(h_all, errors_central, 'r^', label=\"Central\")\n    pyplot.loglog(h_all, h_all/h_all[0]*errors_forward[0], 'b-',\n                  label=r\"$\\propto h$\")\n    pyplot.loglog(h_all, (h_all/h_all[0])**2*errors_central[0], 'g-',\n                  label=r\"$\\propto h^2$\")\n    pyplot.xlabel(r\"$h$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.legend(loc=\"upper left\")\n    pyplot.show()\n    \n\n    def f_sin(x, y):\n        return -numpy.sin(x)\n    print(\"Euler's Method\")\n    x, dx, y = euler(f_sin, 0.5, [1], 5)\n    print(\"dx=\", dx, \"y(0.5)=\", y[0,-1])\n    x, dx, y = euler(f_sin, 0.5, [1], 50)\n    print(\"dx=\", dx, \"y(0.5)=\", y[0,-1])\n    Npoints = 5*2**numpy.arange(1,10)\n    dx_all = 0.5/Npoints\n    errors = numpy.zeros_like(dx_all)\n    for i, N in enumerate(Npoints):\n        x, dx, y = euler(f_sin, 0.5, [1], N)\n        errors[i] = abs(y[0,-1] - numpy.cos(0.5))\n        dx_all[i] = dx\n    pyplot.figure(figsize=(12,6))\n    pyplot.loglog(dx_all, errors, 'kx')\n    pyplot.loglog(dx_all, errors[0]*(dx_all/dx_all[0])**1, 'b-',\n                  label=r\"$\\propto \\Delta x$\")\n    pyplot.legend(loc='upper left')\n    pyplot.xlabel(r\"$\\Delta x$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.show()\n    \n    def f_circle(x, y):\n        dydx = numpy.zeros_like(y)\n        dydx[0] = -y[1]\n        dydx[1] = y[0]\n        return dydx\n    y0 = numpy.array([1, 0])\n    x, dx, y = euler(f_circle, 50, y0, 500)\n    pyplot.figure(figsize=(8,8))\n    pyplot.plot(y[0,:], y[1,:])\n    pyplot.show()\n    x, dx, y = euler(f_circle, 50, y0, 5000)\n    pyplot.figure(figsize=(8,8))\n    pyplot.plot(y[0,:], y[1,:])\n    pyplot.show()", "meta": {"hexsha": "8442e5821fd29c6b9e8dc6bc7b97d76dce4bcf1a", "size": 3292, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/tex/codes/lecture14.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Lectures/tex/codes/lecture14.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Lectures/tex/codes/lecture14.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 35.7826086957, "max_line_length": 74, "alphanum_fraction": 0.5689550425, "include": true, "reason": "import numpy", "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102524151827, "lm_q2_score": 0.904650527388829, "lm_q1q2_score": 0.8751681950487553}}
{"text": "import os\nimport time\nimport json\nimport math\nimport pandas as pd\nfrom scipy import stats\nfrom prettytable import PrettyTable\n\nos.chdir('..')\npath = os.getcwd()\n\ndef simpleLinear(filename):\n\n    with open(filename, newline='') as csvFile:\n        start = time.time()\n        df = pd.read_csv(csvFile)\n        elapsed = time.time() - start\n        print(\"Read Time ->\", round(elapsed, 4), \"seconds.\")\n        start = time.time()\n        x = df['X']\n        y = df['Y']\n        avg_x = x.mean()\n        avg_y = y.mean()\n        diff_x = []\n        diff_y = []\n        for index, row in df.iterrows():\n            diff_x.append(row['X'] - avg_x)\n            diff_y.append(row['Y'] - avg_y)\n        b1_numerator = sum([i * j for i, j in zip(diff_x, diff_y)])\n        b1_denominator = sum([i ** 2 for i in diff_x])\n        b1 = b1_numerator/b1_denominator\n        b0 = avg_y - (b1 * avg_x)\n        yhat = []\n        residuals = []\n        for index, row in df.iterrows():\n            yhat.append(b0 + b1*row['X'])\n            residuals.append(row['Y'] - (b0 + b1*row['X']))\n        tss = sum([i ** 2 for i in diff_y])\n        rss = sum([i ** 2 for i in residuals])\n        rse = math.sqrt(rss/(df.shape[0] - 2))\n        stdErrB0 = math.sqrt((rse ** 2) * (1/df.shape[0] + (avg_x ** 2)/b1_denominator))\n        stdErrB1 = math.sqrt((rse ** 2)/b1_denominator)\n        b0CI = [round(b0 - 2*stdErrB0, 4), round(b0 + 2*stdErrB0, 4)]\n        b1CI = [round(b1 - 2*stdErrB1, 4), round(b1 + 2*stdErrB1, 4)]\n        b0Tstat = b0/stdErrB0\n        b1Tstat = b1/stdErrB1\n        b0pval = stats.t.sf(abs(b0Tstat), df.shape[0] - 2)*2\n        b1pval = stats.t.sf(abs(b1Tstat), df.shape[0] - 2)*2\n        Rsquared = 1 - rss/tss\n        adjRsquared = 1 - ((1 - Rsquared) * (df.shape[0] - 1))/(df.shape[0] - 2)\n        fStat = (tss - rss)/(rss/(df.shape[0] - 2))\n        elapsed = time.time() - start\n        results = {\n            \"intercept\" : {\n                \"b0\" : round(b0, 4),\n                \"std_error\" : round(stdErrB0, 4),\n                \"confidence_interval\" : b0CI,\n                \"t_value\" : round(b0Tstat, 4),\n                \"p_value\" : round(b0pval, 6)\n                },\n            \"slope\" : {\n                \"b1\" : round(b1, 4),\n                \"std_error\" : round(stdErrB1, 4),\n                \"confidence_interval\" : b1CI,\n                \"t_value\" : round(b1Tstat, 4),\n                \"p_value\" : round(b1pval, 6)\n                },\n            \"equation\" : \"y = \" + str(round(b0, 4)) + \" + \" + str(round(b1, 4)) + \" * x\",\n            \"rss\" : round(rss, 4),\n            \"tss\" : round(tss, 4),\n            \"rse\" : round(rse, 4),\n            \"R_squared\" : round(Rsquared, 4),\n            \"adjRsquared\" : round(adjRsquared, 4),\n            \"f_statistic\": round(fStat, 2),\n            \"degrees_of_freedom\" : df.shape[0] - 2,\n            \"predicted_y\" : yhat,\n            \"residuals\" : residuals\n            }\n        print(\"Computation Time ->\", round(elapsed, 4), \"seconds.\")\n        df['yhat'] = pd.Series(yhat).values\n        df['residuals'] = pd.Series(residuals).values\n        t = PrettyTable(['X', 'Y', 'Yhat', 'residuals'])\n        for index, row in df.iterrows():\n            t.add_row(row)\n        print(t)\n        return results\n\ndef main():\n    filename = path + '\\\\data\\\\autoInsur.csv'\n    print(\"+----------+\")\n    print(\"Model Output\")\n    print(\"+----------+\")\n    results = simpleLinear(filename)\n    with open(path + '\\\\src\\\\simpleLinearModel.json', 'w') as outfile:\n        json.dump(results, outfile)\n    print(\"+-----------------+\")\n    print(\"Model File Written.\")\n    print(\"+-----------------+\")\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "c74cfed328fc7ae6533ea63286f22f47cd11aa05", "size": 3658, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/simpleLinear.py", "max_stars_repo_name": "NeilBardhan/linear-regression", "max_stars_repo_head_hexsha": "08e04f97bdedb1f8a3e951f28c50fb46f46f99f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simpleLinear.py", "max_issues_repo_name": "NeilBardhan/linear-regression", "max_issues_repo_head_hexsha": "08e04f97bdedb1f8a3e951f28c50fb46f46f99f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simpleLinear.py", "max_forks_repo_name": "NeilBardhan/linear-regression", "max_forks_repo_head_hexsha": "08e04f97bdedb1f8a3e951f28c50fb46f46f99f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.862745098, "max_line_length": 89, "alphanum_fraction": 0.4917987972, "include": true, "reason": "from scipy", "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561721629777, "lm_q2_score": 0.9032942119105696, "lm_q1q2_score": 0.875162172488648}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nclass InterpolatingFunction(object):\n    def __init__(self):\n        print('initializing interpolating function class')\n        plt.rcParams[\"figure.figsize\"] = [20, 7]\n        \n    def calculateNodes(self,nNodes,plot=False):\n        \"\"\"Calculates Chebyshev points of the second kind (aka Gauss-Lobatto grid points)\n\n        Parameters:\n        nNodes (int): number of grid points\n\n        Returns:\n        ndarray: array containing all grind points\n        \"\"\"\n        j = np.arange(nNodes)\n        nodes = -np.cos(j*np.pi/(nNodes-1))\n        \n        if plot:\n            plt.grid(True)\n            plt.plot(nodes,np.zeros(nNodes),'x')\n            plt.show()\n        \n        return(nodes)\n    \n    def calculateWeights(self,nodes,plot=False):\n        \"\"\"Calculates according weights for barycentric interpolation if provided\n        nodes are Chebyshev points of second kind \n\n        Parameters:\n        nodes (ndarray): nodes\n\n        Returns:\n        ndarray: weights\n        \"\"\"\n        \n        weights = np.ones(len(nodes))*np.power((-1),np.arange(len(nodes)))\n        weights[0]/=2\n        weights[-1]/=2\n        \n        if plot:\n            plt.grid(True)\n            plt.plot(nodes,weights,'x')\n            plt.show()\n        \n        return(weights)\n    \n    def calculateBasisFunctions(self,nodes,weights,n,plot=False):\n        \"\"\"Calculates the basis functions l_j(s) for n equidistant points s\n        \n        Parameters:\n        nodes (ndarray[nNodes]): Gaus-Lobatto nodes\n        weights (ndarray[nNodes]): barycentric weights for Gaus-Lobatto nodes\n\n        Returns:\n        ndarray[nNodes,n] : values of basis functions on n equidistant points s\n        \"\"\"\n        l = np.empty((len(nodes),n))\n        s = np.linspace(-1,1,n)\n        \n        # [sum_{k=0}^{n} w_k/(s-s_k)]^-1\n        temp2 = 1/np.sum(np.repeat(np.reshape(weights,[len(weights),1]),len(s),axis=1)/\n                         (np.repeat(np.reshape(s,[1,len(s)]),len(nodes),axis=0)-\n                          np.repeat(np.reshape(nodes,[len(nodes),1]),len(s),axis=1)),axis=0)\n        for j in range(len(nodes)):\n            # w_j/(s-s_j):\n            temp1 = weights[j]/(s-nodes[j])\n            l[j,:]=temp1*temp2\n            if plot:\n                plt.plot(s,l[j,:])\n        if plot:\n            plt.plot(nodes,np.zeros(len(nodes))+1,'x')\n            plt.grid(True)\n            #plt.yscale(\"Log\")\n            plt.show()\n        return l\n    \n    def interpolateFunction(self,values,basis,plot=False,nodes=None):\n        \"\"\"Calculates a Lagrange interpolation function for given values at the nodes\n        with the given basis functions\n        \n        Parameters:\n        values (ndarray[nNodes]): values at sampling points\n        basis (ndarray[nNodes,n]): the basis functions as calculatet with\n        corresponding functiong\n\n        Returns:\n        ndarray[n] : the interpolation function at n equidistant points\n        \"\"\"\n        nNodes = len(values)\n        nPoints = len(basis[0])\n        p = np.sum(np.repeat(np.reshape(values,(nNodes,1)),nPoints,axis=1)*basis,axis=0)\n        if plot:\n            plt.plot(np.linspace(-1,1,1000),p)\n            plt.plot(nodes,values,'x')\n            plt.grid(True)\n            plt.show()\n        return(p)\n    \n    def derivative(self,values,matrix):\n        \"\"\"Calculates the m-th derivateive of a function at barycentric nodes\n        given by parameter values at barycentric nodes by means of a differentiation matrix\n        \n        Parameters:\n        values (ndarray[nNodes]): values at sampling points\n        matrix (ndarray[nNodes,nNodes]): m-th differentiation matrix \n\n        Returns:\n        ndarray[nNoes] : values of the derivative function at the sampling points\n        \"\"\"\n        \n        \n        #p'(s_i)=Sum_{j=0}^n l'_j(s_i)f_j\n        p = np.dot(matrix,values)        \n        return p\n    \n    def differentiationMatrix(self,m,nodes,weights,plot=False):\n        \"\"\"Calculates the m-th differentiation matrix for a function given at barycentric nodes \n        \n        Parameters:\n        m (int): m-th derivative of the given function\n        nodes (ndarray[nNodes]): Gaus-Lobatto nodes\n        weights (ndarray[nNodes]): barycentric weights for Gaus-Lobatto nodes\n\n        Returns:\n        ndarray[nNoes,nNodes] : m-th differentiation matrix\n        \"\"\"\n        \n        nNodes=len(nodes)\n        #calculate some matrices frequenty used in the following calculation\n        temp1=np.repeat(np.reshape(weights,(nNodes,1)),nNodes,axis=1)\n        temp2=np.transpose(temp1)\n        tempW = temp2/temp1 #w_j / w_i\n        temp3=np.repeat(np.reshape(nodes,(nNodes,1)),nNodes,axis=1)\n        temp4=np.transpose(temp3)\n        tempS = temp3-temp4 #s_i - s_j\n\n        #calculate matrix of first derivative\n        temp5=tempW/tempS\n        temp5[temp5==np.inf]=0\n        temp6=-np.sum(temp5,axis=1)\n        row,col = np.diag_indices(temp5.shape[0])\n        temp5[row,col] = temp6\n\n        if m==1:\n            D = temp5\n        elif m>1:\n            for i in range(2,m+1):\n                temp7 = np.repeat(np.reshape(np.diag(temp5),(nNodes,1)),nNodes,axis=1)\n                temp5 = np.nan_to_num(i/tempS*(tempW*temp7-temp5))\n                temp6=-np.sum(temp5,axis=1)\n                row,col = np.diag_indices(temp5.shape[0])\n                temp5[row,col] = temp6\n            D = temp5\n        else:\n            raise Exception('degree of derivative not supported')\n        \n        if plot:\n            plt.matshow(D)\n            plt.colorbar()\n            plt.show()\n        \n        return D", "meta": {"hexsha": "4060a06e479f2189b78a931f7c21cc4e454d6d2a", "size": 5605, "ext": "py", "lang": "Python", "max_stars_repo_path": "barycentricLagrangeInterpolation/barycentricLagrangeInterpolation.py", "max_stars_repo_name": "LaGuer/barycentricLagrangeInterpolation", "max_stars_repo_head_hexsha": "c1514bc60971583ba0be19eff3d26a9a69cb6f0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "barycentricLagrangeInterpolation/barycentricLagrangeInterpolation.py", "max_issues_repo_name": "LaGuer/barycentricLagrangeInterpolation", "max_issues_repo_head_hexsha": "c1514bc60971583ba0be19eff3d26a9a69cb6f0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "barycentricLagrangeInterpolation/barycentricLagrangeInterpolation.py", "max_forks_repo_name": "LaGuer/barycentricLagrangeInterpolation", "max_forks_repo_head_hexsha": "c1514bc60971583ba0be19eff3d26a9a69cb6f0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-16T18:49:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-16T18:49:49.000Z", "avg_line_length": 33.9696969697, "max_line_length": 96, "alphanum_fraction": 0.5650312221, "include": true, "reason": "import numpy", "num_tokens": 1339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561685659693, "lm_q2_score": 0.9032942106088967, "lm_q1q2_score": 0.8751621679783574}}
{"text": "# Decorrelating your data and dimension reduction\n# Dimension reduction summarizes a dataset using its common occuring patterns. In this chapter, you'll learn about the most fundamental of dimension reduction techniques, \"Principal Component Analysis\" (\"PCA\"). PCA is often used before supervised learning to improve model performance and generalization. It can also be useful for unsupervised learning. For example, you'll employ a variant of PCA will allow you to cluster Wikipedia articles by their content!\n\n# Correlated data in nature\n# You are given an array grains giving the width and length of samples of grain. You suspect that width and length will be correlated. To confirm this, make a scatter plot of width vs length and measure their Pearson correlation.\n\n\n# Perform the necessary imports\nimport matplotlib.pyplot as plt\nfrom scipy.stats import pearsonr\n\n# Assign the 0th column of grains: width\nwidth = grains[:,0]\n\n# Assign the 1st column of grains: length\nlength = grains[:,1]\n\n# Scatter plot width vs length\nplt.scatter(width, length)\nplt.axis('equal')\nplt.show()\n\n# Calculate the Pearson correlation\ncorrelation, pvalue = pearsonr(width,length)\n\n# Display the correlation\nprint(correlation)\n\n\n\n# Decorrelating the grain measurements with PCA\n# You observed in the previous exercise that the width and length measurements of the grain are correlated. Now, you'll use PCA to decorrelate these measurements, then plot the decorrelated points and measure their Pearson correlation.\n\n\n# Import PCA\nfrom sklearn.decomposition import PCA\n\n# Create PCA instance: model\nmodel = PCA()\n\n# Apply the fit_transform method of model to grains: pca_features\npca_features = model.fit_transform(grains)\n\n# Assign 0th column of pca_features: xs\nxs = pca_features[:,0]\n\n# Assign 1st column of pca_features: ys\nys = pca_features[:,1]\n\n# Scatter plot xs vs ys\nplt.scatter(xs, ys)\nplt.axis('equal')\nplt.show()\n\n# Calculate the Pearson correlation of xs and ys\ncorrelation, pvalue = pearsonr(xs, ys)\n\n# Display the correlation\nprint(correlation)\n\n\n\n# The first principal component\n# The first principal component of the data is the direction in which the data varies the most. In this exercise, your job is to use PCA to find the first principal component of the length and width measurements of the grain samples, and represent it as an arrow on the scatter plot.\n\n# The array grains gives the length and width of the grain samples. PyPlot (plt) and PCA have already been imported for you.\n\n\n# Make a scatter plot of the untransformed points\nplt.scatter(grains[:,0], grains[:,1])\n\n# Create a PCA instance: model\nmodel = PCA()\n\n# Fit model to points\nmodel.fit(grains)\n\n# Get the mean of the grain samples: mean\nmean = model.mean_\n\n# Get the first principal component: first_pc\nfirst_pc = model.components_[0,:]\n\n# Plot first_pc as an arrow, starting at mean\nplt.arrow(mean[0], mean[1], first_pc[0], first_pc[1], color='red', width=0.01)\n\n# Keep axes on same scale\nplt.axis('equal')\nplt.show()\n\n\n# Variance of the PCA features\n# The fish dataset is 6-dimensional. But what is its intrinsic dimension? Make a plot of the variances of the PCA features to find out. As before, samples is a 2D array, where each row represents a fish. You'll need to standardize the features first.\n\n\n\n# Perform the necessary imports\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import make_pipeline\nimport matplotlib.pyplot as plt\n\n# Create scaler: scaler\nscaler = StandardScaler()\n\n# Create a PCA instance: pca\npca = PCA()\n\n# Create pipeline: pipeline\npipeline = make_pipeline(scaler,pca)\n\n# Fit the pipeline to 'samples'\npipeline.fit(samples)\n\n# Plot the explained variances\nfeatures = range(pca.n_components_)\nplt.bar(features, pca.explained_variance_)\nplt.xlabel('PCA feature')\nplt.ylabel('variance')\nplt.xticks(features)\nplt.show()\n\n\n\n# Dimension reduction of the fish measurements\n# In a previous exercise, you saw that 2 was a reasonable choice for the \"intrinsic dimension\" of the fish measurements. Now use PCA for dimensionality reduction of the fish measurements, retaining only the 2 most important components.\n\n# The fish measurements have already been scaled for you, and are available as scaled_samples.\n\n\n\n# Import PCA\nfrom sklearn.decomposition import PCA\n\n# Create a PCA model with 2 components: pca\npca = PCA(n_components =2)\n\n# Fit the PCA instance to the scaled samples\npca.fit(scaled_samples)\n\n# Transform the scaled samples: pca_features\npca_features = pca.transform(scaled_samples)\n\n# Print the shape of pca_features\nprint(pca_features.shape)\n\n\n\n\n# A tf-idf word-frequency array\n# In this exercise, you'll create a tf-idf word frequency array for a toy collection of documents. For this, use the TfidfVectorizer from sklearn. It transforms a list of documents into a word frequency array, which it outputs as a csr_matrix. It has fit() and transform() methods like other sklearn objects.\n\n# You are given a list documents of toy documents about pets. Its contents have been printed in the IPython Shell.\n\n\n# Import TfidfVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n# Create a TfidfVectorizer: tfidf\ntfidf = TfidfVectorizer()\n\n# Apply fit_transform to document: csr_mat\ncsr_mat = tfidf.fit_transform(documents)\n\n# Print result of toarray() method\nprint(csr_mat.toarray())\n\n# Get the words: words\nwords = tfidf.get_feature_names()\n\n# Print words\nprint(words)\n\n\n\n# Clustering Wikipedia part I\n# You saw in the video that TruncatedSVD is able to perform PCA on sparse arrays in csr_matrix format, such as word-frequency arrays. Combine your knowledge of TruncatedSVD and k-means to cluster some popular pages from Wikipedia. In this exercise, build the pipeline. In the next exercise, you'll apply it to the word-frequency array of some Wikipedia articles.\n\n# Create a Pipeline object consisting of a TruncatedSVD followed by KMeans. (This time, we've precomputed the word-frequency matrix for you, so there's no need for a TfidfVectorizer).\n\n# The Wikipedia dataset you will be working with was obtained from here.\n\n\n# Perform the necessary imports\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.cluster import KMeans\nfrom sklearn.pipeline import make_pipeline\n\n# Create a TruncatedSVD instance: svd\nsvd = TruncatedSVD(n_components= 50)\n\n# Create a KMeans instance: kmeans\nkmeans = KMeans(n_clusters=6)\n\n# Create a pipeline: pipeline\npipeline = make_pipeline(svd,kmeans)\n\n\n\n# Clustering Wikipedia part II\n# It is now time to put your pipeline from the previous exercise to work! You are given an array articles of tf-idf word-frequencies of some popular Wikipedia articles, and a list titles of their titles. Use your pipeline to cluster the Wikipedia articles.\n\n# A solution to the previous exercise has been pre-loaded for you, so a Pipeline pipeline chaining TruncatedSVD with KMeans is available.\n\n\n# Import pandas\nimport pandas as pd\n\n# Fit the pipeline to articles\npipeline.fit(articles)\n\n# Calculate the cluster labels: labels\nlabels = pipeline.predict(articles)\n\n# Create a DataFrame aligning labels and titles: df\ndf = pd.DataFrame({'label': labels, 'article': titles})\n\n# Display df sorted by cluster label\nprint(df.sort_values('label'))\n\n\n\n", "meta": {"hexsha": "1a008ccc57bb030f1f478a00a5cce119589d4418", "size": 7251, "ext": "py", "lang": "Python", "max_stars_repo_path": "Unsupervised Learning in Python/Decorrelating_your_data_and_dimension_reduction.py", "max_stars_repo_name": "shreejitverma/Data-Scientist", "max_stars_repo_head_hexsha": "03c06936e957f93182bb18362b01383e5775ffb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-12T04:53:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T12:39:21.000Z", "max_issues_repo_path": "Unsupervised Learning in Python/Decorrelating_your_data_and_dimension_reduction.py", "max_issues_repo_name": "shivaniverma1/Data-Scientist", "max_issues_repo_head_hexsha": "f82939a411484311171465591455880c8e354750", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Unsupervised Learning in Python/Decorrelating_your_data_and_dimension_reduction.py", "max_forks_repo_name": "shivaniverma1/Data-Scientist", "max_forks_repo_head_hexsha": "f82939a411484311171465591455880c8e354750", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-03-12T04:52:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T12:45:32.000Z", "avg_line_length": 32.5156950673, "max_line_length": 460, "alphanum_fraction": 0.7815473728, "include": true, "reason": "from scipy", "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109826342959, "lm_q2_score": 0.9207896775212233, "lm_q1q2_score": 0.8751286222124623}}
{"text": "import numpy as np\n\ndef sigmoid(x: np.ndarray) -> np.ndarray: # x:input / return output of sigmoid func\n  \"\"\"\n  ref:\n    http://www.kamishima.net/mlmpyja/lr/sigmoid.html\n  \"\"\"\n  sigmoid_range = 34.538776394910684\n  x = np.clip(x, -sigmoid_range, sigmoid_range)\n\n  return 1.0 / (1.0 + np.exp(-x))\n\n\ndef softmax(x: np.ndarray) -> np.ndarray: # x:input / return output of softmax func\n  \"\"\"\n  ref:\n    https://qiita.com/shohei-ojs/items/d66783bcead3eb7efd82\n    \"axis = -1, keepdims = True\" is 2dim and 1dim to share process\n  \"\"\"\n  c = np.max(x, axis=-1, keepdims=True)\n  exp_x = np.exp(x - c) # for overflow\n  sum_exp_x = np.sum(exp_x, axis=-1, keepdims=True)\n  y = exp_x / sum_exp_x\n\n  return y\n\n\ndef cross_entropy_error(y: np.ndarray, t: np.ndarray) -> float: # y:output of NN, t:correct label / return value of cross entropy error\n  if y.ndim == 1:\n    t = t.reshape(1, t.size)\n    y = y.reshape(1, y.size)\n\n  delta = 1e-7 # to prevent log(0)\n  err = -np.sum(t * np.log(y + delta))\n  batch_size = y.shape[0] # to normalize\n  return err / batch_size\n\n\ndef sigmoid_grad(x: np.ndarray) -> np.ndarray: # fast ver / x:input / return output of sigmoid func\n  return (1.0 - sigmoid(x)) * sigmoid(x)\n", "meta": {"hexsha": "2a286b08eb1d4e5efa60ba3ec9695d4b9da5de56", "size": 1194, "ext": "py", "lang": "Python", "max_stars_repo_path": "5/func.py", "max_stars_repo_name": "Terfno/learn_DL", "max_stars_repo_head_hexsha": "0e1f3049c2c342915e1b7237506029a42539029e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5/func.py", "max_issues_repo_name": "Terfno/learn_DL", "max_issues_repo_head_hexsha": "0e1f3049c2c342915e1b7237506029a42539029e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5/func.py", "max_forks_repo_name": "Terfno/learn_DL", "max_forks_repo_head_hexsha": "0e1f3049c2c342915e1b7237506029a42539029e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1219512195, "max_line_length": 135, "alphanum_fraction": 0.6524288107, "include": true, "reason": "import numpy", "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899577232538, "lm_q2_score": 0.9059898203834277, "lm_q1q2_score": 0.8750951844853359}}
{"text": "import numpy as np\n\n\ndef sigmoid(z):\n    return 1.0 / (1 + np.exp(-(z)))\n\n\ndef tanh(z):\n    return np.tanh(z)\n\n\ndef sin(z):\n    return np.sin(z)\n\n\ndef relu(z):\n    return np.maximum(0.001, z) \n\n\ndef softmax(Z):\n    return np.exp(Z) / np.sum(np.exp(Z))\n\n\ndef der_sigmoid(z):\n    #return sigmoid(z)*(1 - sigmoid(z))\n    return  (1.0 / (1 + np.exp(-(z))))*(1 -  1.0 / (1 + np.exp(-(z))))\n\ndef der_tanh(z):\n    return 1 - np.tanh(z) ** 2\n\ndef der_relu(z):\n    return (z>0)*1 + (z<0)*0.001 \n", "meta": {"hexsha": "7c732b7214121d2d2bf2123040c01c84e6b8a5ea", "size": 486, "ext": "py", "lang": "Python", "max_stars_repo_path": "Utils/Numpy/activation.py", "max_stars_repo_name": "RahulSundar/ANNS_ODES_PDES", "max_stars_repo_head_hexsha": "a73be1895f0a6b7de53718d5081783db4fa4d8be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-20T15:33:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T07:45:43.000Z", "max_issues_repo_path": "Utils/Numpy/activation.py", "max_issues_repo_name": "RahulSundar/ANNS_ODES_PDES", "max_issues_repo_head_hexsha": "a73be1895f0a6b7de53718d5081783db4fa4d8be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Utils/Numpy/activation.py", "max_forks_repo_name": "RahulSundar/ANNS_ODES_PDES", "max_forks_repo_head_hexsha": "a73be1895f0a6b7de53718d5081783db4fa4d8be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.7272727273, "max_line_length": 70, "alphanum_fraction": 0.5349794239, "include": true, "reason": "import numpy", "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899575269305, "lm_q2_score": 0.9059898146721821, "lm_q1q2_score": 0.875095177190177}}
{"text": "import numpy as np\nfrom scipy.stats import chi2, multivariate_normal\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\n\ndef get_error_ellipse_parameters(cov, confidence=None, sigma=None):\n    \"\"\"Returns parameters of an ellipse which contains a specified\n    amount of normally-distributed 2D data, where the data is\n    characterised by its covariance matrix.\n    \n    Parameters\n    ----------\n    cov : array_like\n        Input covariance matrix of shape (2,2)\n    confidence : float\n        Fraction of data points within ellipse. 0 < confidence < 1.\n        If confidence is not given, it is calculated according to sigma.\n    sigma : float\n        Length of axes of the ellipse in standard deviations. If \n        confidence is also given, sigma is ignored.\n    \n    Returns\n    -------\n    semi_major : float\n        Length of major semiaxis of ellipse.\n    semi_minor : float\n        Length of minor semiaxis of ellipse.\n    angle : float\n        Rotation angle of ellipse in radian.\n    confidence : float\n        Fraction of data expected to lie within the ellipse.\n    sigma : float\n        Length of major and minor semiaxes in standard deviations.\n    \"\"\"\n    cov = np.array(cov)\n    if(cov.shape != (2,2)):\n        raise ValueError(\"The covariance matrix needs to be of shape (2,2)\")\n    if(confidence == None and sigma == None):\n        raise RuntimeError(\"One of confidence and sigma is needed as input argument\")\n    if(confidence and sigma):\n        print(\"Argument sigma is ignored as confidence is also provided!\")\n    \n    if(confidence == None):\n        if(sigma < 0):\n            raise ValueError(\"Sigma needs to be positive\")\n        scaling = np.square(sigma)\n        confidence = chi2.cdf(scaling, 2)\n    if(sigma == None):\n        if(confidence > 1 or confidence < 0):\n            raise ValueError(\"Ensure that confidence lies between 0 and 1\")\n        scaling = chi2.ppf(confidence, 2)\n        sigma = np.sqrt(scaling)\n    eigenvalues, eigenvectors = np.linalg.eig(cov)\n    \n    maxindex = np.argmax(eigenvalues)\n    vx, vy = eigenvectors[:, maxindex]\n    angle = np.arctan2(vy, vx)\n    semi_minor, semi_major = np.sqrt(np.sort(eigenvalues) * scaling)\n    print(\"With sigma = {:.2f}, {:.1f}% of data points lie within ellipse.\".format(sigma, confidence * 100))\n\n    return semi_major, semi_minor, angle, confidence, sigma\n\n\n##################\n## Example usage \n##################\nif(__name__ == \"__main__\"):\n    mean_x, mean_y = 5, -2\n    covariance = [[1, -2.04], [-2.04, 5.16]]\n\n    rv = multivariate_normal([mean_x, mean_y], covariance)\n    data_points = rv.rvs(size = 500)\n\n    fig = plt.figure()\n    ax = fig.gca()\n    plt.scatter(data_points[:,0], data_points[:,1], alpha = .5)\n\n    confidence = 0.95\n    semi_major, semi_minor, angle, confidence, sigma\\\n        = get_error_ellipse_parameters(covariance, confidence = confidence)\n    ax.add_patch(Ellipse((mean_x, mean_y), 2*semi_major, 2*semi_minor, 180*angle/np.pi,\\\n            facecolor = 'none', edgecolor = 'red',\\\n            label = 'Confidence = {:.0f}% (sigma = {:.2f})'.format(confidence * 100, sigma)))\n\n    sigma = 1\n    semi_major, semi_minor, angle, confidence, sigma,\\\n        = get_error_ellipse_parameters(covariance, sigma = sigma)\n    ax.add_patch(Ellipse((mean_x, mean_y), 2*semi_major, 2*semi_minor, 180*angle/np.pi,\\\n            facecolor = 'none', edgecolor = 'yellow',\\\n            label = 'Sigma = {:.0f} (confidence = {:.1f}%)'.format(sigma, confidence * 100)))\n    ax.legend()\n    fig.savefig('plot.png')\n    plt.show()\n", "meta": {"hexsha": "f61a7c8c08a718bdf298a568135107395db7637a", "size": 3554, "ext": "py", "lang": "Python", "max_stars_repo_path": "error_ellipse.py", "max_stars_repo_name": "dstei/error-ellipse", "max_stars_repo_head_hexsha": "ee015c9896805706837480a303627e1b1503eba1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "error_ellipse.py", "max_issues_repo_name": "dstei/error-ellipse", "max_issues_repo_head_hexsha": "ee015c9896805706837480a303627e1b1503eba1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "error_ellipse.py", "max_forks_repo_name": "dstei/error-ellipse", "max_forks_repo_head_hexsha": "ee015c9896805706837480a303627e1b1503eba1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8085106383, "max_line_length": 108, "alphanum_fraction": 0.6392796849, "include": true, "reason": "import numpy,from scipy", "num_tokens": 893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970239908635611, "lm_q2_score": 0.90192067455231, "lm_q1q2_score": 0.8750794328742019}}
{"text": "#usr/bin/env/python\n'''\nAuthor  : Bhekimpilo Ndhlela\nAuthor  : 18998712\nmodule  : TW244 Applied Mathematics\ntask    : Assignment 01 problem2\nsince   : Saturday-28-07-2018\n'''\n\nfrom numpy import (exp, linspace, array, abs, zeros, shape)\nimport matplotlib.pyplot as plt\nfrom sys import exit\n\ndef eulers_method(f, I, y0=1.0,(a,b)=(0.0,4.0), h=1.0):\n    X = array([0.0, 1.0, 2.0, 3.0, 4.0])\n    W = array([y0, 0.0, 0.0, 0.0, 0.0])\n\n    for i in xrange(int(a), int(b)):\n        W[i+1] = W[i] + h * f(X[i], W[i])\n    absolute_error(W, X, 'Euler\\'s Method')\n\ndef modified_eulers_method(f, I, y0=1.0,(a,b)=(0.0,4.0), h=1.0):\n    X = array([0.0, 1.0, 2.0, 3.0, 4.0])\n    W = array([y0, 0.0, 0.0, 0.0, 0.0])\n\n    for i in xrange(int(a), int(b)):\n        temp = W[i] + h*f(X[i], W[i])\n        W[i+1] = W[i] + (h/2.0)*(f(X[i], W[i]) + f(X[i+1], temp))\n    absolute_error(W, X, 'Improved Euler\\'s Method')\n\ndef absolute_error(W, X, label, debug=True):\n    Y = array([ I(n) for n in xrange(len(W))])\n    abs_err = array([abs(ya - yc) for ya, yc in zip(Y, W)])\n    if debug is True:\n        print(label)\n        for i , (err, w) in enumerate(zip(abs_err, W)):\n            print 'x = ', i, '\\t\\tw = {:.10f} \\ty = {:.10f}\\terr = {:.10f}'.format(w, Y[i], abs_err[i])\n    plot_comparison_func(Y, W, X, label)\n\ndef plot_comparison_func(Y, W, x, lbl):\n    plt.title('Analytical vs. ' + lbl)\n    plt.xlabel('x')\n    plt.ylabel('y = f(x)')\n    plt.plot(x, Y, '-k', linewidth=2, label='Analytical Solution')\n    plt.plot(x, W, '--r', linewidth=2, label='Numerical Solution')\n    plt.legend(bbox_to_anchor=(.4, .4))\n    plt.show()\n\ndef plot_analytical_solution():\n    X = linspace(0, 4, 1000)\n    y = array([ exp(1 - exp(-x)) for x in X])\n    plt.title('Plot of function f(x) = exp(1 - exp(-x))')\n    plt.xlabel('x = linspace(0, 4, 1000)')\n    plt.ylabel('f(x) = exp(1 - exp(-x))')\n    plt.plot(X, y, '-k', linewidth=4)\n    plt.show()\n\nif __name__ == '__main__':\n    f = lambda x, y: exp(-x) * y    # f(x, y) = y DE\n    I = lambda x: exp(1 - exp(-x))  # Exact Solution\n    plot_analytical_solution()\n    eulers_method(f, I)\n    modified_eulers_method(f, I)\nelse:\n    exit('USAGE: python problem2.py')\n", "meta": {"hexsha": "b078e2ece54d70835c07d4955e29346344ae2a7d", "size": 2176, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignment01/src/problem2.py", "max_stars_repo_name": "BhekimpiloNdhlela/AppliedDifferentialEquations", "max_stars_repo_head_hexsha": "0db3e3136d0beb4e5af89c3ff6e2af1939b504a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment01/src/problem2.py", "max_issues_repo_name": "BhekimpiloNdhlela/AppliedDifferentialEquations", "max_issues_repo_head_hexsha": "0db3e3136d0beb4e5af89c3ff6e2af1939b504a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment01/src/problem2.py", "max_forks_repo_name": "BhekimpiloNdhlela/AppliedDifferentialEquations", "max_forks_repo_head_hexsha": "0db3e3136d0beb4e5af89c3ff6e2af1939b504a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9696969697, "max_line_length": 103, "alphanum_fraction": 0.5629595588, "include": true, "reason": "from numpy", "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.9284087970889806, "lm_q1q2_score": 0.8750315267792885}}
{"text": "import math\r\nimport numpy as np\r\n\r\n#define data\r\ndata = [6.224, 6.665, 6.241, 5.302, 5.073, 5.127, 4.994, 5.012, 5.108, 5.377, 5.510, 6.372]\r\nm = len(data)\r\nb = np.reshape(data,(m,1))\r\ntime = [0.0, 1/12, 2/12, 3/12, 4/12, 5/12, 6/12, 7/12, 8/12, 9/12, 10/12, 11/12]\r\n\r\n#Create the A matrix from the time\r\nAmatrix = []\r\nn = 0\r\nwhile n < m:\r\n    Amatrix.append([1.0, round(math.cos(2*math.pi*time[n]), 12), round(math.sin(2*math.pi*time[n]), 12),])\r\n    n = n + 1\r\n    pass\r\nAmatrix = np.array(Amatrix)\r\nprint(Amatrix)\r\n\r\n#Create and use Transpose\r\nTransposeMatrix = Amatrix.transpose()\r\nprint(TransposeMatrix)\r\nCmatrix = np.matmul(TransposeMatrix, Amatrix)\r\nprint(Cmatrix)\r\n\r\n#Fix error when ATranspose times A has a 0 on the diagonal, may cause problems if not careful\r\nf = 0\r\nwhile f < 3:\r\n    if Cmatrix[f,f] == 0:\r\n        Cmatrix[f,f] = .0000000000000001\r\n        pass\r\n    f = f + 1\r\n    pass\r\n\r\nTransposeTimesb = np.matmul(TransposeMatrix, b)\r\nprint(TransposeTimesb)\r\nC = np.linalg.solve(Cmatrix,TransposeTimesb)\r\nprint(C)\r\n\r\n#Calculate Error\r\nr = np.subtract(b, np.matmul(Amatrix, C))\r\nk = 0\r\nSE = 0\r\nwhile k < m:\r\n    SE = SE + (r.item(k))**2\r\n\r\n    k = k + 1\r\n    pass\r\nRMSE = math.sqrt(SE/m)\r\n\r\nprint(\"F3(t) = \", C.item(0), \" + \", C.item(1), \"* cos(2(pi)t) + \", C.item(2), \"* sin(2(pi)t)\")\r\nprint(\"RMSE = \", RMSE)\r\n", "meta": {"hexsha": "3ba049e5802d038c435168325ead96f62d4a46d1", "size": 1325, "ext": "py", "lang": "Python", "max_stars_repo_path": "LeastSquaresMethodForPeriodicData.py", "max_stars_repo_name": "ericthered1138/NumericalAnalysis", "max_stars_repo_head_hexsha": "2b389bdb5cd1d81fa70bd7a98168d441120313db", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LeastSquaresMethodForPeriodicData.py", "max_issues_repo_name": "ericthered1138/NumericalAnalysis", "max_issues_repo_head_hexsha": "2b389bdb5cd1d81fa70bd7a98168d441120313db", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LeastSquaresMethodForPeriodicData.py", "max_forks_repo_name": "ericthered1138/NumericalAnalysis", "max_forks_repo_head_hexsha": "2b389bdb5cd1d81fa70bd7a98168d441120313db", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0, "max_line_length": 107, "alphanum_fraction": 0.6, "include": true, "reason": "import numpy", "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.976310530768455, "lm_q2_score": 0.8962513745192024, "lm_q1q2_score": 0.8750196551587999}}
{"text": "import numpy as np\nfrom typing import Tuple\n\n\ndef R(theta: float) -> np.ndarray:\n    \"\"\"\n        Returns the rotation matrix for rotating an object\n        centered around the origin with a given angle\n\n        Arguments:\n            theta: angle in degrees\n\n        Returns:\n            R: 2x2 np.ndarray with rotation matrix\n    \"\"\"\n    theta = np.radians(theta)\n    return np.array(\n        [[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]\n    )\n\n\ndef cart2pol(x: float, y: float) -> Tuple[float, float]:\n    \"\"\"\n        Cartesian to polar coordinates\n\n        angles in degrees\n    \"\"\"\n    rho = np.hypot(x, y)\n    phi = np.degrees(np.arctan2(y, x))\n    return rho, phi\n\n\ndef pol2cart(rho: float, phi: float) -> Tuple[float, float]:\n    \"\"\"\n        Polar to cartesian coordinates\n\n        angles in degrees\n    \"\"\"\n    x = rho * np.cos(np.radians(phi))\n    y = rho * np.sin(np.radians(phi))\n    return x, y\n", "meta": {"hexsha": "2fa8c4951cc0c0b7755fefee2d0d57ef9fd5fea0", "size": 928, "ext": "py", "lang": "Python", "max_stars_repo_path": "kino/geometry/coordinates.py", "max_stars_repo_name": "BrancoLab/Kino", "max_stars_repo_head_hexsha": "0e914e3d65fdf76e4efa95b9848cb30da3653f3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-09T09:19:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T09:19:25.000Z", "max_issues_repo_path": "kino/geometry/coordinates.py", "max_issues_repo_name": "BrancoLab/Kino", "max_issues_repo_head_hexsha": "0e914e3d65fdf76e4efa95b9848cb30da3653f3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kino/geometry/coordinates.py", "max_forks_repo_name": "BrancoLab/Kino", "max_forks_repo_head_hexsha": "0e914e3d65fdf76e4efa95b9848cb30da3653f3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0952380952, "max_line_length": 73, "alphanum_fraction": 0.5808189655, "include": true, "reason": "import numpy", "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668684574637, "lm_q2_score": 0.8918110425624792, "lm_q1q2_score": 0.8750154478868136}}
{"text": "import numpy as np\nimport matplotlib.pyplot as mpl\nfrom scipy import interpolate\nimport time\n\n# -------------------------------------|Declaração de funções|-------------------------------------#\ndef f0(x):\n    return np.e ** np.cos(np.pi * x)\n\n\ndef d2f0(x):\n    return np.pi ** 2 * (np.sin(np.pi * x) ** 2 - np.cos(np.pi * x)) * np.e ** (np.cos(np.pi * x))\n\n\ndef d4f0(x):\n    return (\n        np.pi ** 4\n        * (\n            np.sin(np.pi * x) ** 4\n            - 6 * np.sin(np.pi * x) ** 2 * np.cos(np.pi * x)\n            - 4 * np.sin(np.pi * x) ** 2\n            + 3 * np.cos(np.pi * x) ** 2\n            + np.cos(np.pi * x)\n        )\n        * np.e ** (np.cos(np.pi * x))\n    )\n\n\ndef f1(x):\n    return np.sin(np.pi * x ** 2)\n\n\ndef d2f1(x):\n    return 2 * np.pi * (-2 * np.pi * x ** 2 * np.sin(np.pi * x ** 2) + np.cos(np.pi * x ** 2))\n\n\ndef d4f1(x):\n    return (\n        4\n        * np.pi ** 2\n        * (\n            4 * np.pi ** 2 * x ** 4 * np.sin(np.pi * x ** 2)\n            - 12 * np.pi * x ** 2 * np.cos(np.pi * x ** 2)\n            - 3 * np.sin(np.pi * x ** 2)\n        )\n    )\n\n\ndef f2(x):\n    return 1 / (1 + x ** 5)\n\n\ndef d2f2(x):\n    return 10 * x ** 3 * (5 * x ** 5 / (x ** 5 + 1) - 2) / (x ** 5 + 1) ** 2\n\n\ndef d4f2(x):\n    return (\n        120\n        * x\n        * (125 * x ** 15 / (x ** 5 + 1) ** 3 - 150 * x ** 10 / (x ** 5 + 1) ** 2 + 40 * x ** 5 / (x ** 5 + 1) - 1)\n        / (x ** 5 + 1) ** 2\n    )\n\n\ndef f2_g(x):\n    if x != -1:\n        return 1 / (1 + x ** 5)\n\n\ndef f3(x):\n    return np.cos(np.e ** np.cos(np.pi * x))\n\n\ndef d2f3(x):\n    return (\n        np.pi ** 2\n        * (\n            -np.e ** (np.cos(np.pi * x)) * np.sin(np.pi * x) ** 2 * np.cos(np.e ** (np.cos(np.pi * x)))\n            - np.sin(np.pi * x) ** 2 * np.sin(np.e ** (np.cos(np.pi * x)))\n            + np.sin(np.e ** (np.cos(np.pi * x))) * np.cos(np.pi * x)\n        )\n        * np.e ** (np.cos(np.pi * x))\n    )\n\n\ndef d4f3(x):\n    return (\n        np.pi ** 4\n        * (\n            np.e ** (3 * np.cos(np.pi * x)) * np.sin(np.pi * x) ** 4 * np.cos(np.e ** (np.cos(np.pi * x)))\n            + 6 * np.e ** (2 * np.cos(np.pi * x)) * np.sin(np.pi * x) ** 4 * np.sin(np.e ** (np.cos(np.pi * x)))\n            - 6\n            * np.e ** (2 * np.cos(np.pi * x))\n            * np.sin(np.pi * x) ** 2\n            * np.sin(np.e ** (np.cos(np.pi * x)))\n            * np.cos(np.pi * x)\n            - 7 * np.e ** (np.cos(np.pi * x)) * np.sin(np.pi * x) ** 4 * np.cos(np.e ** (np.cos(np.pi * x)))\n            + 18\n            * np.e ** (np.cos(np.pi * x))\n            * np.sin(np.pi * x) ** 2\n            * np.cos(np.pi * x)\n            * np.cos(np.e ** (np.cos(np.pi * x)))\n            + 4 * np.e ** (np.cos(np.pi * x)) * np.sin(np.pi * x) ** 2 * np.cos(np.e ** (np.cos(np.pi * x)))\n            - 3 * np.e ** (np.cos(np.pi * x)) * np.cos(np.pi * x) ** 2 * np.cos(np.e ** (np.cos(np.pi * x)))\n            - np.sin(np.pi * x) ** 4 * np.sin(np.e ** (np.cos(np.pi * x)))\n            + 6 * np.sin(np.pi * x) ** 2 * np.sin(np.e ** (np.cos(np.pi * x))) * np.cos(np.pi * x)\n            + 4 * np.sin(np.pi * x) ** 2 * np.sin(np.e ** (np.cos(np.pi * x)))\n            - 3 * np.sin(np.e ** (np.cos(np.pi * x))) * np.cos(np.pi * x) ** 2\n            - np.sin(np.e ** (np.cos(np.pi * x))) * np.cos(np.pi * x)\n        )\n        * np.e ** (np.cos(np.pi * x))\n    )\n\n\ndef trapezio(f, df, x, fx, n, a, b):\n\n    inicio = time.time()\n\n    v = np.linspace(a, b, num=n)\n    h = abs(v[1] - v[0])\n\n    x.append(v[0])\n    fx.append(f(v[0]))\n\n    res = np.zeros((3))\n\n    for i in range(1, n):\n\n        x.append(v[i])\n        fx.append(f(v[i]))\n\n        res[0] += (h / 2) * (fx[i - 1] + fx[i])\n\n    res[1] = erro(df, n, a, b, h, \"T\")\n\n    fim = time.time()\n\n    res[2] = fim - inicio\n\n    print(\"Regra dos Trapezios:\")\n    print(\"\\t-> Resultado:\", res[0])\n    print(\"\\t-> Erro:\", res[1])\n    print(\"\\t-> Tempo:\", res[2], end=\"\\n\\n\")\n\n    return res\n\n\ndef simpson(f, df, x, fx, n, a, b):\n\n    inicio = time.time()\n\n    v = np.linspace(a, b, num=n)\n    h = abs(v[1] - v[0])\n\n    x.append(v[0])\n    fx.append(f(v[0]))\n\n    res = np.zeros((3))\n\n    for i in range(2, n, 2):\n\n        x.append(v[i - 1])\n        x.append(v[i])\n        fx.append(f(v[i - 1]))\n        fx.append(f(v[i]))\n\n        res[0] += (h / 3) * (fx[i - 2] + 4 * fx[i - 1] + fx[i])\n\n    res[1] = erro(df, n, a, b, h, \"S\")\n\n    fim = time.time()\n\n    res[2] = fim - inicio\n\n    print(\"Regra de Simpson:\")\n    print(\"\\t-> Resultado:\", res[0])\n    print(\"\\t-> Erro:\", res[1])\n    print(\"\\t-> Tempo:\", res[2], end=\"\\n\\n\")\n\n    return res\n\n\ndef erro(df, n, a, b, h, tipo):\n\n    x0 = np.linspace(a, b, num=1000)\n\n    if tipo == \"t\" or tipo == \"T\":\n        return (n * (h ** 3) / 12) * np.max(np.abs(df(x0)))\n\n    elif tipo == \"s\" or tipo == \"S\":\n        return (n * (h ** 5) / 180) * np.max(np.abs(df(x0)))\n\n\ndef f_de_x(f, fx, x, a, b):\n\n    for i in range(int(a * 50), int(b * 50 + 1)):\n        i /= 50\n\n        x.append(i)\n        fx.append(f(i))\n\n\ndef grafico_trapezio(f, xf, t, xt, funcao):\n\n    mpl.figure()\n    mpl.plot(xf, f, label=funcao, color=\"k\")\n    mpl.stem(\n        xt,\n        t,\n        basefmt=\"b\",\n        use_line_collection=True,\n        linefmt=\"blue\",\n        markerfmt=\"blue\",\n        label=\"integração numérica pela Regra dos Trapézios\",\n    )\n    mpl.fill_between(xt, t, 0, facecolor=\"#8112ff\", alpha=0.3)\n    mpl.xlabel(\"x\")\n    mpl.ylabel(\"f(x)\")\n    mpl.legend()\n    mpl.grid(True)\n\n\ndef grafico_simpson(f, xf, fxs, xs, funcao):\n\n    mpl.figure()\n    mpl.plot(xf, f, label=funcao, color=\"k\")\n    mpl.stem(\n        xs,\n        fxs,\n        basefmt=\"r\",\n        use_line_collection=True,\n        linefmt=\"red\",\n        markerfmt=\" \",\n        label=\"integração numérica pela Regra de Simpson\",\n    )\n\n    for i in range(2, n, 2):\n        fxp = []\n        xp = []\n        fx = interpolate.interp1d(xs[i - 2 : i + 1], fxs[i - 2 : i + 1], kind=\"quadratic\")\n        xp = np.linspace(xs[i - 2], xs[i], 50)\n        fxp = fx(xp)\n\n        mpl.plot(xp, fxp, color=\"r\")\n        mpl.fill_between(xp, fxp, 0, facecolor=\"#f2600c\", alpha=0.3)\n\n    mpl.xlabel(\"x\")\n    mpl.ylabel(\"f(x)\")\n    mpl.legend()\n    mpl.grid(True)\n\n\n# -------------------------------------------------------------------------------------------------#\n\n# -------------------------------------|Variáveis de controle|-------------------------------------#\n\n# Número de pontos (impar)\nn = 1000001\n\na = 0  # Intervalo inicial\nb = 1  # Intervalo final\n\nfuncao0 = False\nfuncao1 = False\nfuncao2 = False\nfuncao3 = True\n\ngraficos = False\n# -------------------------------------------------------------------------------------------------#\n\n# ------------------------------------|Declaração de variáveis|------------------------------------#\nf = [f0, f1, [f2, f2_g], f3]\ndf = [[d2f0, d4f0], [d2f1, d4f1], [d2f2, d4f2], [d2f3, d4f3]]\nxt = [[], [], [], []]\nfxt = [[], [], [], []]\nxs = [[], [], [], []]\nfxs = [[], [], [], []]\nx = [[], [], [], []]\nfx = [[], [], [], []]\n# -------------------------------------------------------------------------------------------------#\n\n\n# Caso n seja par, incrementa-se 1, pois n precisa de ser ímpar\nif n % 2 == 0:\n    n += 1\n\n# --|Calculando e printando as integrais numéricas com seus respectivos erros e tempo de execução|--#\nif funcao0 == True:\n    print(\"\\nÁrea de e^cos(pi*x) entre\", a, \"e\", b, \"com\", n, \"pontos\", end=\"\\n\\n\")\n    trapezio(f[0], df[0][0], xt[0], fxt[0], n, a, b)\n    simpson(f[0], df[0][1], xs[0], fxs[0], n, a, b)\n\nif funcao1 == True:\n    print(\"\\nÁrea de sen(pi*x^2) entre\", a, \"e\", b, \"com\", n, \"pontos\", end=\"\\n\\n\")\n    trapezio(f[1], df[1][0], xt[1], fxt[1], n, a, b)\n    simpson(f[1], df[1][1], xs[1], fxs[1], n, a, b)\n\nif funcao2 == True:\n    print(\"\\nÁrea de 1/(1 + x^5) entre\", a, \"e\", b, \"com\", n, \"pontos\", end=\"\\n\\n\")\n    trapezio(f[2][0], df[2][0], xt[2], fxt[2], n, a, b)\n    simpson(f[2][1], df[2][1], xs[2], fxs[2], n, a, b)\n\nif funcao3 == True:\n    print(\"\\nÁrea de cos(e^cos(pi*x)) entre\", a, \"e\", b, \"com\", n, \"pontos\", end=\"\\n\\n\")\n    trapezio(f[3], df[3][0], xt[3], fxt[3], n, a, b)\n    simpson(f[3], df[3][1], xs[3], fxs[3], n, a, b)\n# -------------------------------------------------------------------------------------------------#\n\n# --------------------------------------|Plotando os gráficos|-------------------------------------#\nif graficos == True:\n\n    if funcao0 == True:\n        f_de_x(f[0], fx[0], x[0], -2, 2)\n        grafico_trapezio(fx[0], x[0], fxt[0], xt[0], \"e^cos(pi*x)\")\n        grafico_simpson(fx[0], x[0], fxs[0], xs[0], \"e^cos(pi*x)\")\n\n    if funcao1 == True:\n        f_de_x(f[1], fx[1], x[1], -2, 2)\n        grafico_trapezio(fx[1], x[1], fxt[1], xt[1], \"sen(pi*x^2)\")\n        grafico_simpson(fx[1], x[1], fxs[1], xs[1], \"sen(pi*x^2)\")\n\n    if funcao2 == True:\n        f_de_x(f[2][1], fx[2], x[2], -2, 2)\n        grafico_trapezio(fx[2], x[2], fxt[2], xt[2], \"1/(1 + x^5)\")\n        grafico_simpson(fx[2], x[2], fxs[2], xs[2], \"1/(1 + x^5)\")\n\n    if funcao3 == True:\n        f_de_x(f[3], fx[3], x[3], -2, 2)\n        grafico_trapezio(fx[3], x[3], fxt[3], xt[3], \"cos(e^cos(pi*x))\")\n        grafico_simpson(fx[3], x[3], fxs[3], xs[3], \"cos(e^cos(pi*x))\")\n\n    mpl.show()\n# -------------------------------------------------------------------------------------------------#\n", "meta": {"hexsha": "e7a9c92a152c0cdb9580b4b922c93c0dc1e6ccf7", "size": 9249, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lista-implementacao-3/2 - Integracao Numerica/integracao numerica.py", "max_stars_repo_name": "henrique-tavares/IFB-Calculo-Numerico", "max_stars_repo_head_hexsha": "2c1a9de3b3c3ff7d9ed82771fe12bccfa7a05aab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lista-implementacao-3/2 - Integracao Numerica/integracao numerica.py", "max_issues_repo_name": "henrique-tavares/IFB-Calculo-Numerico", "max_issues_repo_head_hexsha": "2c1a9de3b3c3ff7d9ed82771fe12bccfa7a05aab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lista-implementacao-3/2 - Integracao Numerica/integracao numerica.py", "max_forks_repo_name": "henrique-tavares/IFB-Calculo-Numerico", "max_forks_repo_head_hexsha": "2c1a9de3b3c3ff7d9ed82771fe12bccfa7a05aab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6089552239, "max_line_length": 114, "alphanum_fraction": 0.404800519, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214480969029, "lm_q2_score": 0.907312213841788, "lm_q1q2_score": 0.8749406279279198}}
{"text": "# The Fibonacci numbers, commonly denoted F(n) form a sequence, \n# called the Fibonacci sequence, such that each number is the sum of the two preceding ones, \n# starting from 0 and 1. That is,\n# F(0) = 0,   F(1) = 1\n# F(N) = F(N - 1) + F(N - 2), for N > 1.\n# Given N, calculate F(N).\n\n# Example 1:\n# Input: 2\n# Output: 1\n# Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.\n\n# Example 2:\n# Input: 3\n# Output: 2\n# Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.\n\n# Example 3:\n# Input: 4\n# Output: 3\n# Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.\n \n# Note:\n# 0 ≤ N ≤ 30.\n\nclass Solution(object):\n    def fib(self, N):\n        \"\"\"\n        :type N: int\n        :rtype: int\n        \"\"\"\n        # M1. 原始递归 \n        # 时间复杂度: O(2^n) 递归树分析\n        # 空间复杂度: O(n) 栈帧分析\n\n        # if N == 0:\n        #     return 0\n        # if N < 3:\n        #     return 1\n        # return self.fib(N-2) + self.fib(N-1)\n\n        # M2. 尾递归\n        # 时间复杂度: O(n) 尾递归过程分析\n        # 空间复杂度: O(n) 栈帧分析\n\n        # def helper(first, second, N):\n        #     if N == 0:\n        #         return 0\n        #     if N < 3:\n        #         return 1\n        #     if N == 3:\n        #         return first + second\n        #     return helper(second, first+second, N-1)\n        # return helper(1, 1, N)\n\n        # M3. DP循环\n        # 时间复杂度: O(n) \n        # 空间复杂度: O(n) \n\n        # import numpy as np\n        # if N == 0:\n        #     return 0\n        # tmp = np.zeros(N+1, dtype=int)\n        # tmp[0] = 0\n        # tmp[1] = 1\n        # for i in range(2, N+1):\n        #     tmp[i] = tmp[i-1] + tmp[i-2]\n        # return tmp[N]\n\n\n        # M4. DP循环 空间优化\n        # 时间复杂度: O(n) \n        # 空间复杂度: O(1)\n\n        if N == 0:\n            return 0\n        if N < 3:\n            return 1\n        first, second = 0, 1\n        res = 0\n        for i in range(2, N+1):\n            res = first + second\n            first = second\n            second = res \n        return res", "meta": {"hexsha": "a65b2b47e59fe40c26067c77999423a51562e3e4", "size": 1913, "ext": "py", "lang": "Python", "max_stars_repo_path": "LeetCode/Python3/Math/509. Fibonacci Number.py", "max_stars_repo_name": "WatsonWangZh/CodingPractice", "max_stars_repo_head_hexsha": "dc057dd6ea2fc2034e14fd73e07e73e6364be2ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-09-01T22:36:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T08:57:20.000Z", "max_issues_repo_path": "LeetCode/Python3/Math/509. Fibonacci Number.py", "max_issues_repo_name": "WatsonWangZh/LeetCodePractice", "max_issues_repo_head_hexsha": "dc057dd6ea2fc2034e14fd73e07e73e6364be2ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LeetCode/Python3/Math/509. Fibonacci Number.py", "max_forks_repo_name": "WatsonWangZh/LeetCodePractice", "max_forks_repo_head_hexsha": "dc057dd6ea2fc2034e14fd73e07e73e6364be2ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-27T14:58:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-27T15:04:17.000Z", "avg_line_length": 22.5058823529, "max_line_length": 93, "alphanum_fraction": 0.4223732358, "include": true, "reason": "import numpy", "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.9184802507195636, "lm_q1q2_score": 0.8749205203596104}}
{"text": "import numpy as np\n\ndef householder(_A):\n\tA = _A.copy()\n\tn = A.shape[1]\n\tv = np.zeros_like(A)\n\tfor k in range(n):\n\t\tsigma = np.sign(A[k, k]) * np.sqrt((A[k:, k] ** 2).sum())\n\t\tif (A[k:, k] ** 2).sum() < 1e-10:\n\t\t\tcontinue\n\t\tv[k, k] += sigma\n\t\tv[k:, k] += A[k:, k]\n\t\tbeta = v[:, k].dot(v[:, k])\n\t\tfor j in range(k, n):\n\t\t\tA[:, j] -= 2 * (v[:, k].dot(A[:, j]) / beta) * v[:, k]\n\treturn A, v\n\ndef QR(A):\n\tr, _ = householder(A)\n\t# A=QR, Q=AR^{-1}\n\tq = A.dot(np.linalg.inv(r))\n\t# q, r = np.linalg.qr(A)\n\treturn q, r\n\ndef check(A):\n\tfor i in range(1, A.shape[0]):\n\t\tif abs(A[i, :i-1]).sum() > 1e-3:\n\t\t\treturn False\n\treturn True\n\ndef solve(A):\n\tcnt = 0\n\twhile check(A) == False and cnt <= 1000:\n\t\tq, r = QR(A)\n\t\tA = r.dot(q)\n\t\tcnt += 1\n\tif cnt >= 1000:\n\t\tprint('Cannot solve A!')\n\t\treturn None\n\treturn A.diagonal()\n\ndef gen53():\n\tprint('t53 result'.center(30, '-'))\n\t# A = np.array([[4,0,0],[4,5,5],[2,5,5.]])\n\t# A = np.array([[1,0,0], [0,1,0], [0,0,1], [-1,1,0],[-1,0,1], [0,-1,1.]])\n\t# print(QR(A))\n\t# exit()\n\t# A = np.array([\n\t# \t[2.9766, 0.3945, 0.4198, 1.1159],\n\t# \t[0.3945, 2.7328, -0.3097, 0.1129],\n\t# \t[0.4198, -0.3097, 2.5675, 0.6079],\n\t# \t[1.1159, 0.1129, 0.6079, 1.7231],\n\t# \t])\n\tA = np.array([\n\t\t[.5, .5, .5, .5],\n\t\t[.5, .5, -.5, -.5],\n\t\t[.5, -.5, .5, -.5],\n\t\t[.5, -.5, -.5, .5]\n\t\t])\n\tprint(solve(A))\n\tprint('end t53'.center(30, '-')+'\\n')\n\nif __name__ == '__main__':\n\tgen53()\n", "meta": {"hexsha": "d9984c56bcb7d651c8b4c2b21636e0e0efa1a0ae", "size": 1382, "ext": "py", "lang": "Python", "max_stars_repo_path": "数值分析/t53.py", "max_stars_repo_name": "jasnzhuang/Personal-Homework", "max_stars_repo_head_hexsha": "edf633ce94f22a646786b85e133797339cf9fc3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 463, "max_stars_repo_stars_event_min_datetime": "2019-10-25T04:28:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:03:44.000Z", "max_issues_repo_path": "数值分析/t53.py", "max_issues_repo_name": "1002753959/Undergraduate", "max_issues_repo_head_hexsha": "95e6e95a98f53e350d628edacad0042382c6a464", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-28T08:05:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-28T08:26:34.000Z", "max_forks_repo_path": "数值分析/t53.py", "max_forks_repo_name": "1002753959/Undergraduate", "max_forks_repo_head_hexsha": "95e6e95a98f53e350d628edacad0042382c6a464", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 201, "max_forks_repo_forks_event_min_datetime": "2019-04-10T07:17:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-15T09:46:30.000Z", "avg_line_length": 21.2615384615, "max_line_length": 74, "alphanum_fraction": 0.482633864, "include": true, "reason": "import numpy", "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741214369554, "lm_q2_score": 0.9184802451409948, "lm_q1q2_score": 0.8749205125723826}}
{"text": "import numpy as np\n\n\"\"\"\nmeshgrid的结果，\n第一个是横坐标轴的数据的集合\n第二个是纵坐标轴数据的集合\n两者合起来构成一个网格点的集合\n\nx[0]与y[0] 逐个元素组合，是四个点的坐标，这些点构成一条横线。纵坐标是y[i], 横坐标是x[i]\n\"\"\"\ngrid_x, grid_y = np.meshgrid(np.linspace(-3, 3, 4), np.linspace(-3, 3, 4))\nprint(grid_x)\nprint(\"-----------------\")\nprint(grid_y)", "meta": {"hexsha": "69bc8a02eff2232f5f672f8bbc06117de43ffbd4", "size": 270, "ext": "py", "lang": "Python", "max_stars_repo_path": "test_matplotlib/meshgrid.py", "max_stars_repo_name": "baijianhua/pymath", "max_stars_repo_head_hexsha": "a96ebbd8c8ac646c436d8bf33cb01764a948255d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_matplotlib/meshgrid.py", "max_issues_repo_name": "baijianhua/pymath", "max_issues_repo_head_hexsha": "a96ebbd8c8ac646c436d8bf33cb01764a948255d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_matplotlib/meshgrid.py", "max_forks_repo_name": "baijianhua/pymath", "max_forks_repo_head_hexsha": "a96ebbd8c8ac646c436d8bf33cb01764a948255d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2857142857, "max_line_length": 74, "alphanum_fraction": 0.6740740741, "include": true, "reason": "import numpy", "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338090839607, "lm_q2_score": 0.9099069980980297, "lm_q1q2_score": 0.8749063417933506}}
{"text": "import numpy as np\n\n#solve (x_1)+4*(x_2)=2,-2*(x_1)+x_2=14\nA=np.array([[1,4]\n           ,[-2,1]])\n\nprint(\"det(A)=\",np.linalg.det(A))\n#det(A)= 9.000000000000002\n#the reason that 2 appear here:\n#the decimal calcuation error\n#det(A)!=0 -> not singular matrix\n# -> has unique solution\n\nb=np.array([2,14])\nx=np.linalg.solve(A,b)\nprint(x)\n#[-6.  2.]\n\nclass Uniqueness_of_solution:\n    def __init__(self):\n        pass\n    def judge_solution(self,A,b):\n        #to avoid the decimal error\n        #determine by the value of the det(A)by a small float number\n        if abs(np.linalg.det(A))<0.0000001:\n            print(\"doesn't have a unique solution\")\n        else:\n            print(\"has a unique solution:\")\n            print(np.linalg.solve(A,b))\n            return np.linalg.solve(A,b)\n\n\n#solve:\n#x-4y+6z=3\n#-2x+8y-12z=-6\n#2x-y+3z=1\n\nC=np.array([[1,-4,6]\n           ,[-2,8,-12]\n           ,[2,-1,3]])\n\nD=np.array([3,-6,1])\n\nsol=Uniqueness_of_solution()\nsol.judge_solution(A,b)\n#[-6.  2.]\nsol.judge_solution(C,D)\n#doesn't have a unique solution\n\n#What if doesn't have a unique solution and using linalg.solve?\n# ans=np.linalg.solve(C,D)\n# print(ans)\n#terminal:\n#numpy.linalg.LinAlgError: Singular matrix\n\n\n#solve for the traffic flows\n# (x_1)-(x_2)=160\n# (x_2)-(x_3)=-40\n# (x_3)-(x_4)=210\n# (x_4)-(x_1)=-330\n\nE=np.array([[1,-1,0,0]\n           ,[0,1,-1,0]\n           ,[0,0,1,-1]\n           ,[-1,0,0,1]])\n\nF=np.array([160,-40,210,-330])\n\nprint(\"det(E)=\",np.linalg.det(E))\nif np.linalg.det(E)!=0:\n    print(\"non-singular matrix\")\nelse:\n    print(\"singular matrix\")\n# det(E)= 0.0\n# singular matrix\n\n#solve for the traffic flows (if (x_4)=100)\n\nG=np.array([[1,0,0]\n           ,[1,-1,0]\n           ,[0,0,1]])\n\nH=np.array([430,160,310])\n\nprint(\"det(G)=\",np.linalg.det(G))\nif np.linalg.det(G)!=0:\n    print(\"non-singular matrix\")\n    print(\"the solution is:\")\n    print(np.linalg.solve(G,H))\nelse:\n    print(\"singular matrix\")\n\n# det(G)= -1.0\n# non-singular matrix\n# the solution is:\n# [430. 270. 310.]", "meta": {"hexsha": "22019f5694fafe833b63dd03b74dbb6f41bb0ade", "size": 1992, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_algebra/exercise2.py", "max_stars_repo_name": "coherent17/physics_calculation", "max_stars_repo_head_hexsha": "cf94813778984f62b2c65174fb44bebb2e9c0d05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-30T01:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T01:11:30.000Z", "max_issues_repo_path": "linear_algebra/exercise2.py", "max_issues_repo_name": "coherent17/physics_calculation", "max_issues_repo_head_hexsha": "cf94813778984f62b2c65174fb44bebb2e9c0d05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_algebra/exercise2.py", "max_forks_repo_name": "coherent17/physics_calculation", "max_forks_repo_head_hexsha": "cf94813778984f62b2c65174fb44bebb2e9c0d05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5360824742, "max_line_length": 68, "alphanum_fraction": 0.5868473896, "include": true, "reason": "import numpy", "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9843363499098282, "lm_q2_score": 0.888758798648752, "lm_q1q2_score": 0.8748375918121565}}
{"text": "\"\"\"Test functions. Functions to be minimized.\"\"\"\nimport numpy as np\n\ndef function_sphere(vector):\n    \"\"\"Return the value of the sphere function for the given vector.\n    :param vector: n-dimensional array.\n    :return value: value of the function at this point in the n-dimensional space.\n    \"\"\"\n    return sum([x*x for x in vector])\n\ndef function_ackley(vector):\n    \"\"\"Implementations of the Ackley function.\n    :param vector: n-dimensional array of floats.\n    :return value: value of the Ackley function for the given point in the space.\n    \"\"\"\n    n = len(vector)               # dimension of the vector\n    sv = function_sphere(vector)  # value of the sphere function\n\n    a = -0.2 * np.sqrt( 1/n * sv)\n    b = 1/n * sum([np.cos( 2 * np.pi * x) for x in vector])\n    value = -20 * np.exp(a) - np.exp(b) + 20 + np.e\n\n    return value\n\ndef function_himmelblau(vector):\n    \"\"\"Compute the value of the Himmelblau's function for a given 2d point in R^2.\n    :param vector: 2D array of floats.\n    :return value: value of the function at the given point.\n    \"\"\"\n    value = np.power(np.power(vector[0], 2) + vector[1] - 11, 2)\n    value += np.power(vector[0] + np.power(vector[1], 2) - 7, 2)\n\n    return value\n\ndef function_rastrigin(vector):\n    \"\"\"Computes the rastrigin function.\n    :param vector: n-dimensional array of floats, vector of dimension n.\n    :return value: value of the function at that point.\n    \"\"\"\n    A = 10\n    An = A * len(vector) # A * n, where n is the dimension of the space\n    v = sum([np.power(x, 2) - A * np.cos(2 * np.pi * x) for x in vector])\n\n    value = An + v\n    return value \n", "meta": {"hexsha": "02d16230860f8ee59e47c11d6e287a8dda8b1b08", "size": 1621, "ext": "py", "lang": "Python", "max_stars_repo_path": "Evolutive_Strategies/EE-(1+1)/test_functions.py", "max_stars_repo_name": "MGijon/Posts", "max_stars_repo_head_hexsha": "53f382516970b95156895966a683a56d883054a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Evolutive_Strategies/EE-(1+1)/test_functions.py", "max_issues_repo_name": "MGijon/Posts", "max_issues_repo_head_hexsha": "53f382516970b95156895966a683a56d883054a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Evolutive_Strategies/EE-(1+1)/test_functions.py", "max_forks_repo_name": "MGijon/Posts", "max_forks_repo_head_hexsha": "53f382516970b95156895966a683a56d883054a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2391304348, "max_line_length": 82, "alphanum_fraction": 0.6409623689, "include": true, "reason": "import numpy", "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812327313545, "lm_q2_score": 0.9032942021480235, "lm_q1q2_score": 0.8747331529951883}}
{"text": "'''\r\nY is the dependant variable and X is the independant variable\r\nWe are going to fit a line\r\n        Y = a0 + a1*x\r\nusing Gradient Descent minimizing the SSE.\r\nThis code will work for any variable with single attribute, i.e.\r\nit is Linear Regression in 1 variable.\r\n'''\r\nimport random\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n#Sum of Squares Error\r\ndef sse(n,a0,a1,x,y):\r\n    \"\"\"\n    Compute the sse sse sse.\n\n    Args:\n        n: (array): write your description\n        a0: (array): write your description\n        a1: (array): write your description\n        x: (array): write your description\n        y: (array): write your description\n    \"\"\"\n    s=0\r\n    mean=np.mean(y)\r\n    for i in range(n):\r\n        s+=(a0+a1*x[i]-mean)**2\r\n    return s/(2*n)\r\n\r\n#Calculate the cost function\r\ndef cost(n,a0,a1,x,y,ch,p=2):\r\n    \"\"\"\n    Calculate the cost between two points.\n\n    Args:\n        n: (todo): write your description\n        a0: (todo): write your description\n        a1: (todo): write your description\n        x: (todo): write your description\n        y: (todo): write your description\n        ch: (todo): write your description\n        p: (todo): write your description\n    \"\"\"\n    s=0;\r\n    if ch=='sum-of-squares':\r\n        for i in range(n):\r\n            s+=(a0+a1*x[i]-y[i])**2\r\n        return s/(2*n)\r\n    if ch=='l-p norm':\r\n        for i in range(n):\r\n            s+=abs(a0+a1*x[i]-y[i])**p\r\n        return s**(1/p)\r\n\r\n#Partial Differential with respect to a0\r\ndef dela0(n,a0,a1,x,y):\r\n    \"\"\"\n    Dela0 dela0.\n\n    Args:\n        n: (array): write your description\n        a0: (array): write your description\n        a1: (array): write your description\n        x: (array): write your description\n        y: (array): write your description\n    \"\"\"\n    s=0;\r\n    for i in range(n):\r\n        s+=(a0+a1*x[i]-y[i])\r\n    return s/n\r\n\r\n#Partial Differential with respect to a1\r\ndef dela1(n,a0,a1,x,y):\r\n    \"\"\"\n    Dela1 dela1 dela1 dela\n\n    Args:\n        n: (array): write your description\n        a0: (array): write your description\n        a1: (array): write your description\n        x: (array): write your description\n        y: (array): write your description\n    \"\"\"\n    s=0;\r\n    for i in range(n):\r\n        s+=(a0+a1*x[i]-y[i])*x[i]\r\n    return s/n\r\n\r\ndef predict(x, y, alphas=np.linspace(0.001,1,10), it=1000):\r\n    \"\"\"\n    Predict the predicted )\n\n    Args:\n        x: (array): write your description\n        y: (array): write your description\n        alphas: (array): write your description\n        np: (array): write your description\n        linspace: (array): write your description\n        it: (array): write your description\n    \"\"\"\n    mx=max(x)\r\n    my=max(y)\r\n    \r\n    # Normalize values in the range 0-1\r\n    for i in range(len(x)):\r\n        x[i]/=mx\r\n        y[i]/=my\r\n    coeff, r2, cos = grad_desc(x, y, alphas, it)\r\n    coeff, x, y = rescale(x, y, coeff, mx, my)\r\n    r2_alpha(r2, alphas)\r\n    plot_predict(x, y, coeff, r2, cos, it)\r\n    # Store all predictions for which R^2 is maximum in an array\r\n    a0=coeff[r2.index(max(r2))][0]\r\n    a1=coeff[r2.index(max(r2))][1]\r\n    pred=a0+x*a1\r\n    return pred\r\n    \r\ndef grad_desc(x, y, alphas, it):\r\n    \"\"\"\n    Describe the objective function.\n\n    Args:\n        x: (todo): write your description\n        y: (todo): write your description\n        alphas: (todo): write your description\n        it: (todo): write your description\n    \"\"\"\n    r2=[]# Array to store calculated R^2 values\r\n    coeff=[] #Array to store Predicted Coefficients for Linear Regression\r\n    \r\n    for alpha in alphas:\r\n        cos=[]\r\n        #Initialize random weights\r\n        a0=random.random()\r\n        a1=random.random()\r\n        for i in range(it):\r\n            # Reduce the coefficient by alpha times partial differential\r\n            temp0=a0-alpha*dela0(len(x),a0,a1,x,y)\r\n            temp1=a1-alpha*dela1(len(x),a0,a1,x,y)\r\n            a0=temp0\r\n            a1=temp1\r\n            #Add the cost for each iteration\r\n            cos.append(cost(len(x),a0,a1,x,y,ch='sum-of-squares'))\r\n        # Calculate and store the R^2 value for a particular learning rate alpha\r\n        r2.append(1-(cos[-1]/(cos[-1]+sse(len(x),a0,a1,x,y))))\r\n        #Store the predicted coefficients for regression\r\n        coeff.append([a0,a1])\r\n    return coeff, r2, cos\r\n    \r\ndef r2_alpha(r2, alphas):\r\n    \"\"\"\n    Plot r2 alpha\n\n    Args:\n        r2: (todo): write your description\n        alphas: (array): write your description\n    \"\"\"\n    #Plot for R^2 vs alpha\r\n    plt.plot(alphas, r2)\r\n    plt.title('R^2 vs. Learning Rate')\r\n   \r\n    #Max. value of R^2 over all values of alpha\r\n    print(max(r2))\r\n    #Value of alpha for maximum R^2\r\n    print(np.linspace(0.001,1,10)[r2.index(max(r2))])\r\n   \r\ndef rescale(x, y, coeff, mx, my):\r\n    \"\"\"\n    Rescale x y - axis.\n\n    Args:\n        x: (todo): write your description\n        y: (todo): write your description\n        coeff: (todo): write your description\n        mx: (todo): write your description\n        my: (todo): write your description\n    \"\"\"\n    # Bring the data back to scale\r\n    for i in range(len(coeff)):\r\n        coeff[i][0]*=my\r\n        coeff[i][1]*=my/mx\r\n    for i in range(len(x)):\r\n        x[i]*=mx\r\n        y[i]*=my\r\n    return coeff, x, y\r\n\r\ndef plot_predict(x, y, coeff, r2, cos, it):        \r\n    \"\"\"\n    Plots the r2d plot\n\n    Args:\n        x: (array): write your description\n        y: (array): write your description\n        coeff: (array): write your description\n        r2: (array): write your description\n        cos: (array): write your description\n        it: (array): write your description\n    \"\"\"\n    # Plot the training data, cost function and Predicted vs Actual values\r\n    fig1,ax=plt.subplots(1,2,figsize=(14,4))\r\n    ax[0].plot([x for x in range(it)],cos)\r\n    ax[0].set_title('Cost Function')\r\n    ax[0].set_xlabel('No. of Iterations')\r\n    ax[1].scatter(x,y,marker='x',color='r',label=\"Training Data\")\r\n    ax[1].plot(np.arange(1,12),[coeff[r2.index(max(r2))][0]+coeff[r2.index(max(r2))][1]*x for x in np.arange(1,12)],label=\"Linear Regression\")\r\n    plt.legend()\r\n    ax[1].set_title('Predicted vs Actual')\r\n    plt.xlabel(\"Experience in Years\")\r\n    plt.ylabel(\"Salary\")\r\n    plt.show()\r\n", "meta": {"hexsha": "50fc3b3118630709d121b0b4b2efddaf91b0d235", "size": 6242, "ext": "py", "lang": "Python", "max_stars_repo_path": "Machine Learning & AI/Linear_Regression_with_Gradient_Descent.py", "max_stars_repo_name": "Gregor-Davies/Awesome-Scripts-1", "max_stars_repo_head_hexsha": "b2f7fe99b7e9780b91cdd2f4f94e63795146e9c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 141, "max_stars_repo_stars_event_min_datetime": "2018-10-04T10:02:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T08:47:01.000Z", "max_issues_repo_path": "Machine Learning & AI/Linear_Regression_with_Gradient_Descent.py", "max_issues_repo_name": "Gregor-Davies/Awesome-Scripts-1", "max_issues_repo_head_hexsha": "b2f7fe99b7e9780b91cdd2f4f94e63795146e9c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2018-10-04T08:28:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-02T09:36:02.000Z", "max_forks_repo_path": "Machine Learning & AI/Linear_Regression_with_Gradient_Descent.py", "max_forks_repo_name": "Gregor-Davies/Awesome-Scripts-1", "max_forks_repo_head_hexsha": "b2f7fe99b7e9780b91cdd2f4f94e63795146e9c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 110, "max_forks_repo_forks_event_min_datetime": "2018-10-04T04:28:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T05:49:02.000Z", "avg_line_length": 29.5829383886, "max_line_length": 143, "alphanum_fraction": 0.5722524832, "include": true, "reason": "import numpy", "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812318188366, "lm_q2_score": 0.903294196941332, "lm_q1q2_score": 0.8747331471288539}}
{"text": "from scipy.fftpack import fft\nimport numpy as np\n\n\ndef get_fft(t,x):\n\n    \"\"\"\n    This function returns fast-fourier transform. fftpack in scipy is used for this purpose, however, \n    numpy.fft.fft can also be used in similar manner.\n\n    t:       time\n    x:       signal\n\n    fr:      frequency axis\n    X_fr:    amplitude complex number\n    amp:     amplitude\n    angle:   phase angle\n    \"\"\"\n\n    # Sampling Frequency\n    Fs = 1 / (t[1] - t[0])\n    \n    # Generate Frequency Axis\n    n = np.size(t)\n    n_half = int(n / 2)\n    fr = (Fs / 2) * np.linspace(0, 1, n_half)\n    \n    # Compute FFT\n    X     = fft(x)\n    X_fr  = (1 / n_half) * X[0:n_half]\n    amp   = np.absolute(X_fr)\n    angle = np.angle(X_fr)\n    \n    return fr, X_fr, amp, angle\n\ndef get_ifft(X):\n\n    \"\"\"\n    X:            amplitude complex number\n    \"\"\"\n    return np.fft.ifft(X).real * np.size(X) / 2\n\n\n\ndef fft_comps_cutoff(t, x, cutoff = 0.01):\n    \n    fr, X_fr, amp, angle = get_fft(t, x)\n    \n    # filter\n    amp_norm = amp / amp.max()\n    mask = amp_norm > cutoff\n\n    return fr[mask], X_fr[mask], amp[mask], angle[mask]\n\ndef construct_time_signal_from_comps(t_vec, freq, amplitude, angle):\n\n    y_vec = np.zeros_like(t_vec)\n    for fr, amp, a in zip(freq, amplitude, angle):\n        # y_vec += amp * np.sin(2 * np.pi * fr * t_vec + a)\n        y_vec += amp * np.sin(2 * np.pi * fr * t_vec) # + a)\n\n    return y_vec\n", "meta": {"hexsha": "dfd451116e4ab06fa067508f70bbdd7d1d2b3000", "size": 1396, "ext": "py", "lang": "Python", "max_stars_repo_path": "signal_processing.py", "max_stars_repo_name": "bmotevalli/pyscripts-common", "max_stars_repo_head_hexsha": "2a2549d2549205e96eccde4c2be7b70827f5c192", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "signal_processing.py", "max_issues_repo_name": "bmotevalli/pyscripts-common", "max_issues_repo_head_hexsha": "2a2549d2549205e96eccde4c2be7b70827f5c192", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "signal_processing.py", "max_forks_repo_name": "bmotevalli/pyscripts-common", "max_forks_repo_head_hexsha": "2a2549d2549205e96eccde4c2be7b70827f5c192", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1587301587, "max_line_length": 102, "alphanum_fraction": 0.5680515759, "include": true, "reason": "import numpy,from scipy", "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140244715406, "lm_q2_score": 0.9046505395995927, "lm_q1q2_score": 0.874719293984593}}
{"text": "import numpy as np\n\nimport matplotlib.pyplot as plt\n#%matplotlib inline\n\n#import matplotlib.image as img\n#import PIL.Image as Image \nfrom PIL import Image\nimport math\nimport cmath\n\nimport time\n\nimport csv\n\nfrom numpy import binary_repr\n\nfrom fractions import gcd\n\nclass Haar(object):\n    \"\"\"\n    This class Haar implements all the procedures for transforming a given 2D digital image\n    into its corresponding frequency-domain image (Haar Transform)\n    \"\"\"\n    \n    def __init__():\n        pass\n        \n    #Compute the Haar kernel.\n    @classmethod\n    def computeKernel(self, N):\n        \"\"\"\n        Computes/generates the haar kernel function.\n\n        Parameters\n        ----------\n        N : int\n            Size of the kernel to be generated.\n\n        Returns\n        -------\n        kernel : ndarray\n            The generated kernel as a matrix.\n        \"\"\"\n        \n        i = 0\n        kernel = np.zeros([N, N])\n        n = int(math.log(N, 2))\n\n        #Fill for the first row of the kernel\n        for j in xrange(N):\n            kernel[i, j] = 1.0/math.sqrt(N)\n\n\n        # For the other rows of the kernel....\n        i += 1\n        for r in xrange(n):\n             for m in xrange(1, (2**r)+1):\n                j=0\n                for x in np.arange(0, 1, 1.0/N):\n                    if (x >= (m-1.0)/(2**r)) and (x < (m-0.5)/(2**r)):\n                        kernel[i, j] = (2.0**(r/2.0))/math.sqrt(N)\n                    elif (x >= (m-0.5)/(2**r)) and (x < m/(2.0**r)):\n                        kernel[i, j] = -(2.0**(r/2.0))/math.sqrt(N)\n                    else:\n                        kernel[i, j] = 0\n                    j += 1\n                i += 1\n        return kernel\n\n    @classmethod\n    def computeForwardHaar(self, imge):\n        \"\"\"\n        Computes/generates the 2D Haar transform.\n\n        Parameters\n        ----------\n        imge : ndarray\n            The input image to be transformed.\n\n        Returns\n        -------\n        final2DHaar : ndarray\n            The transformed image.\n        \"\"\"\n        \n        N = imge.shape[0]\n        kernel = Haar.computeKernel(N)\n\n        imge1DHaar = np.dot(kernel, imge) \n        \n        #Transpose the kernel as it is not symmetric\n        final2DHaar = np.dot(imge1DHaar, kernel.T)\n\n        return final2DHaar/N\n    \n    @classmethod\n    def computeInverseHaar(self, imgeHaar):\n        \"\"\"\n        Computes/generates the inverse of 2D Haar transform.\n\n        Parameters\n        ----------\n        imgeHaar : ndarray\n            The Haar transformed image.\n\n        Returns\n        -------\n        imgeInverse : ndarray\n            The inverse of the transformed image.\n        \"\"\"\n        \n        N = imgeHaar.shape[0]\n        kernel = Haar.computeKernel(N)\n\n        imge1DInverse = np.dot(kernel.T, imgeHaar)        \n        imgeInverse = np.dot(imge1DInverse, kernel)\n\n        return imgeInverse/N\n        ", "meta": {"hexsha": "826b245efc4f7196d2f3872280abbcf2f53219b1", "size": 2893, "ext": "py", "lang": "Python", "max_stars_repo_path": "Notebooks_Teoricos/Image-Processing-Operations/CommonClasses/haar.py", "max_stars_repo_name": "lucas-althoff/PDI-UnB", "max_stars_repo_head_hexsha": "eae5de886739807bd7f66d5cb9dbe7b541efa4ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Notebooks_Teoricos/Image-Processing-Operations/CommonClasses/haar.py", "max_issues_repo_name": "lucas-althoff/PDI-UnB", "max_issues_repo_head_hexsha": "eae5de886739807bd7f66d5cb9dbe7b541efa4ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notebooks_Teoricos/Image-Processing-Operations/CommonClasses/haar.py", "max_forks_repo_name": "lucas-althoff/PDI-UnB", "max_forks_repo_head_hexsha": "eae5de886739807bd7f66d5cb9dbe7b541efa4ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1083333333, "max_line_length": 91, "alphanum_fraction": 0.5032837885, "include": true, "reason": "import numpy,from numpy", "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140206578809, "lm_q2_score": 0.904650538956921, "lm_q1q2_score": 0.8747192899131554}}
{"text": "#!/usr/bin/env python\n# GET TRANSFORMATION MATRIX FROM FIXED-ANGLES ROTATIONS AND A TRANSLATION\n# SANTIAGO GARCIA AND ELKIN GUERRA\n\nimport numpy as np\nimport math\n\n\nclass Transformation:\n    \"\"\"\n    Get transformation matrix from fixed-angles rotations and a translation.\n\n    :returns: transformation matrix size(4, 4)\n    :param angle_x: rotation of {B} with respect of {A} in \"x\" axis.\n    :param angle_y: rotation of {B} with respect of {A} in \"y\" axis.\n    :param angle_z: rotation of {B} with respect of {A} in \"z\" axis.\n    :param vector_AB: vector from origin of {A} to origin of {B}.\n    \"\"\"\n\n    def __init__(self, angle_x, angle_y, angle_z, vector_AB):\n        # Add extra \"1\" to vector_AB\n        vector_AB.append(1)\n        self.vector_AB = np.transpose([vector_AB])\n\n        # Initialize rotation matrices in zero\n        self.RX = np.eye(3)\n        self.RY = np.eye(3)\n        self.RZ = np.eye(3)\n\n        # Change the rotation matrices based on inputs\n        self.create_rotation_matrix(\"x\", angle_x)\n        self.create_rotation_matrix(\"y\", angle_y)\n        self.create_rotation_matrix(\"z\", angle_z)\n\n        # Create homogeneous transformation matrix\n        self.create_transformation_matriz()\n\n    def create_rotation_matrix(self, axis, angle):\n\n        if axis == \"x\":\n            self.RX = np.array([\n                [1, 0, 0],\n                [0, math.cos(angle), -math.sin(angle)],\n                [0, math.sin(angle), math.cos(angle)]\n            ])\n\n        if axis == \"y\":\n            self.RY = np.array([\n                [math.cos(angle), 0, math.sin(angle)],\n                [0, 1, 0],\n                [-math.sin(angle), 0, math.cos(angle)]\n            ])\n\n        if axis == \"z\":\n            self.RZ = np.array([\n                [math.cos(angle), -math.sin(angle), 0],\n                [math.sin(angle), math.cos(angle), 0],\n                [0, 0, 1]\n            ])\n    \n    def create_transformation_matriz(self):\n        # Get rotation matrix with fixed angles approach (Rxyz = Rz.Ry.Rx)\n        R_ZYX = np.dot(np.dot(self.RZ, self.RY), self.RX)\n\n        extra_zeros_perspective = np.array([[0, 0, 0]])\n        self.TM = np.concatenate((R_ZYX, extra_zeros_perspective))\n        self.TM = np.concatenate((self.TM, self.vector_AB), axis=1)\n\n\n# TESTS\nif __name__ == \"__main__\":\n    test = Transformation(0, 0, math.radians(30), [10, 5, 0])\n    print(\"\\nRX:\\n\", test.RX)\n    print(\"\\nRY:\\n\", test.RY)\n    print(\"\\nRZ:\\n\", test.RZ)\n    print(\"\\nTM:\\n\", test.TM)\n\n    test = Transformation(0, 0, math.radians(90), [1, 2, 3])\n    print(\"\\nRX:\\n\", test.RX)\n    print(\"\\nRY:\\n\", test.RY)\n    print(\"\\nRZ:\\n\", test.RZ)\n    print(\"\\nTM:\\n\", test.TM)\n", "meta": {"hexsha": "7b15305a6e0c7938ae63c53c5f53d1f25ccefa72", "size": 2671, "ext": "py", "lang": "Python", "max_stars_repo_path": "PROJECTS/CHALLENGE_BAXTER_PY/transformation.py", "max_stars_repo_name": "san99tiago/MY_ROBOTICS", "max_stars_repo_head_hexsha": "871ddbedd0b3fb4292facfa7a0cdf190a6df7f88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-26T16:39:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T16:39:15.000Z", "max_issues_repo_path": "PROJECTS/CHALLENGE_BAXTER_PY/transformation.py", "max_issues_repo_name": "san99tiago/MY_ROBOTICS", "max_issues_repo_head_hexsha": "871ddbedd0b3fb4292facfa7a0cdf190a6df7f88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-21T22:32:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-21T22:32:12.000Z", "max_forks_repo_path": "PROJECTS/CHALLENGE_BAXTER_PY/transformation.py", "max_forks_repo_name": "san99tiago/MY_ROBOTICS", "max_forks_repo_head_hexsha": "871ddbedd0b3fb4292facfa7a0cdf190a6df7f88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1807228916, "max_line_length": 76, "alphanum_fraction": 0.5709472108, "include": true, "reason": "import numpy", "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.9086179062123119, "lm_q1q2_score": 0.8747020270152231}}
{"text": "\"\"\"\n    A/B split test calculator\n    ----------\n        \n    This module implements the statistical calculation of the A/B test split significance. The \n    implementation was taken from https://www.periscopedata.com/blog/ab-testing-in-redshift.html\n    which contains the code to do the statistical analysis using the normal approximation method \n    in redshift with scipy. This was translated to python using scipy too.\n\"\"\"\n\nfrom scipy.stats import norm\n\n\ndef standard_error(sample_size, successes):\n    \"\"\"\n    Calculates the standard error of a sample proportion.\n    \n    Formula: σp = sqrt [ p(1 - p) / n ]. \n    with:\n    p = proportion of successes in sample (successes / sample size)    \n    \n    :param sample_size: the size of the sample \n    :param successes: the number of successes on the given sample. \n    :return: the standard error on the sample proportion -> σp\n    \"\"\"\n    p = successes / sample_size\n    return (p * (1 - p) / sample_size) ** 0.5\n\n\ndef significance(size_a, successes_a, size_b, successes_b):\n    \"\"\"\n    Calculates the significance for an A/B test.\n    \n    :param size_a: Sample size of the experiment A\n    :param successes_a: Successes of the experiment A\n    :param size_b: Sample size fo the experiment B\n    :param successes_b: Successes of the experiment b\n    :return: The significance of the test.\n    \"\"\"\n    # Raising an error if the condition of size_sample > successes is not met.\n    if size_a < successes_a or size_b < successes_b:\n        raise ValueError('The size numbers must be greater than the number of successes for an '\n                         'experiment')\n\n    p_a = successes_a / size_a\n    p_b = successes_b / size_b\n    se_a = standard_error(size_a, successes_a)\n    se_b = standard_error(size_b, successes_b)\n\n    numerator = (p_b - p_a)\n    denominator = (se_a ** 2 + se_b ** 2) ** 0.5\n\n    return norm.sf(abs(numerator / denominator))\n", "meta": {"hexsha": "040f8989e3786e0e105fddd8ccee100e8bfe4a7a", "size": 1907, "ext": "py", "lang": "Python", "max_stars_repo_path": "calculator/ab_calculator.py", "max_stars_repo_name": "Julioocz/A-B-test-split-calculator", "max_stars_repo_head_hexsha": "b5af0d860b7b2aa6040764519a019d0a67ab419a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-04-25T10:47:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:23:53.000Z", "max_issues_repo_path": "calculator/ab_calculator.py", "max_issues_repo_name": "Julioocz/A-B-test-split-calculator", "max_issues_repo_head_hexsha": "b5af0d860b7b2aa6040764519a019d0a67ab419a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calculator/ab_calculator.py", "max_forks_repo_name": "Julioocz/A-B-test-split-calculator", "max_forks_repo_head_hexsha": "b5af0d860b7b2aa6040764519a019d0a67ab419a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-16T06:23:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T06:23:59.000Z", "avg_line_length": 35.3148148148, "max_line_length": 97, "alphanum_fraction": 0.6759307813, "include": true, "reason": "from scipy", "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97594644290792, "lm_q2_score": 0.8962513821399045, "lm_q1q2_score": 0.8746933483507467}}
{"text": "import numpy as np\n\n# We create a 5 x 5 ndarray that contains integers from 0 to 24\nX = np.arange(25).reshape(5, 5)\n\n# We print X\nprint()\nprint('Original X = \\n', X)\nprint()\n\n# We use Boolean indexing to select elements in X:\nprint('The elements in X that are greater than 10:', X[X > 10])\nprint('The elements in X that less than or equal to 7:', X[X <= 7])\nprint('The elements in X that are between 10 and 17:', X[(X > 10) & (X < 17)])\n\n# We use Boolean indexing to assign the elements that are between 10 and 17 the value of -1\nX[(X > 10) & (X < 17)] = -1\n\n# We print X\nprint()\nprint('X = \\n', X)\nprint()\n\n## Set Operations\n\n# We create a rank 1 ndarray\nx = np.array([1,2,3,4,5])\n\n# We create a rank 1 ndarray\ny = np.array([6,7,2,8,4])\n\n# We print x\nprint()\nprint('x = ', x)\n\n# We print y\nprint()\nprint('y = ', y)\n\n# We use set operations to compare x and y:\nprint()\nprint('The elements that are both in x and y:', np.intersect1d(x,y))\nprint('The elements that are in x that are not in y:', np.setdiff1d(x,y))\nprint('All the elements of x and y:',np.union1d(x,y))\n\n## Sorting\n\n# We create an unsorted rank 1 ndarray\nx = np.random.randint(1,11,size=(10,))\n\n# We print x\nprint()\nprint('Original x = ', x)\n\n# We sort x and print the sorted array using sort as a function.\nprint()\nprint('Sorted x (out of place):', np.sort(x))\n\n# When we sort out of place the original array remains intact. To see this we print x again\nprint()\nprint('x after sorting:', x)\n\n# We sort x but only keep the unique elements in x\nprint(np.sort(np.unique(x)))\n\n## Sorting in place\n\n# We create an unsorted rank 1 ndarray\nx = np.random.randint(1,11,size=(10,))\n\n# We print x\nprint()\nprint('Original x = ', x)\n\n# We sort x and print the sorted array using sort as a method.\nx.sort()\n\n# When we sort in place the original array is changed to the sorted array. To see this we print x again\nprint()\nprint('x after sorting:', x)\n\n# When sorting rank 2 ndarrays, we need to specify to the np.sort() function whether we are sorting by rows or columns. \n# This is done by using the axis keyword.\n\n# We create an unsorted rank 2 ndarray\nX = np.random.randint(1,11,size=(5,5))\n\n# We print X\nprint()\nprint('Original X = \\n', X)\nprint()\n\n# We sort the columns of X and print the sorted array\nprint()\nprint('X with sorted columns :\\n', np.sort(X, axis = 0))\n\n# We sort the rows of X and print the sorted array\nprint()\nprint('X with sorted rows :\\n', np.sort(X, axis = 1))\n\n## Quiz question\nX = np.arange(1, 26).reshape(5, 5)\nprint(X)\nprint(X[X%2 == 1])\n", "meta": {"hexsha": "6ba71c0e6538812b4e9bf6b7fa79d61d78f9fe5f", "size": 2515, "ext": "py", "lang": "Python", "max_stars_repo_path": "python-programming/numPy/boolean_indexing_set_operations_sorting_ndarray.py", "max_stars_repo_name": "geekmj/fml", "max_stars_repo_head_hexsha": "ead2c16be7865eda03183b5e11622f64bf81cab7", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python-programming/numPy/boolean_indexing_set_operations_sorting_ndarray.py", "max_issues_repo_name": "geekmj/fml", "max_issues_repo_head_hexsha": "ead2c16be7865eda03183b5e11622f64bf81cab7", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python-programming/numPy/boolean_indexing_set_operations_sorting_ndarray.py", "max_forks_repo_name": "geekmj/fml", "max_forks_repo_head_hexsha": "ead2c16be7865eda03183b5e11622f64bf81cab7", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9523809524, "max_line_length": 120, "alphanum_fraction": 0.6711729622, "include": true, "reason": "import numpy", "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939024825960626, "lm_q2_score": 0.931462502687197, "lm_q1q2_score": 0.8746664144746943}}
{"text": "import numpy as np\nimport matplotlib.pyplot as pyplot\n\ndef step_func(x) :\n    '''\n    안쓴다. \n    '''\n    return np.array(x>0, dtype=np.int)\n\ndef sigmoid_func(x) :\n    '''\n    안쓴다. \n    '''\n    return 1/(1+np.exp(-x))\n\ndef ReLU_func(x):\n    '''\n    쓴다. \n    '''\n    return np.maximum(0, x)\n\ndef parametric_ReLU_func(x):\n    '''\n    쓴다 \n    '''\n    a=0.2\n    return np.where(x>0, x, a*x)\n\ndef identity_func(x):\n    '''\n    출력층의 활성함수\n     항등함수. 출력=입력\n     회귀문제에서 사용\n    '''\n    return x\n\ndef softmax_func_overflow(x):\n    '''\n    출력층 활성함수\n     신경망의 출력값으로 확률벡터를 얻는다. (해석 용이)\n     분류문제에서 사용\n     신경망의 출력값을 0~1 로 제한. 모든 출력값의 합은 1.\n    '''\n    expX=np.exp(x)\n    sumX=np.sum(expX)\n    return expX/sumX\n\ndef softmax_func(x):\n    '''\n    출력층 활성함수\n     신경망의 출력값으로 확률벡터를 얻는다. (해석 용이)\n     분류문제에서 사용\n     신경망의 출력값을 0~1 로 제한. 모든 출력값의 합은 1.\n     이전 버전에서 오버플로우가 발생하므로 x 에서 x 의 최대값을 빼서 오버플로우를 막는다.\n    '''\n    maxX=np.max(x)\n    expX=np.exp(x-maxX)\n    sumX=np.sum(expX)\n    return expX/sumX\n\nif __name__ == '__main__' :\n    print('activation function')\n    x=np.arange(-5, 5, 0.1)\n    y_step=step_func(x)\n    y_sig=sigmoid_func(x)\n    y_ReLU=ReLU_func(x)\n    y_para_ReLU=parametric_ReLU_func(x)\n\n    pyplot.plot(x,y_step, '--')\n    pyplot.plot(x,y_sig, '-.')\n    pyplot.plot(x,y_ReLU,':')\n    pyplot.plot(x,y_para_ReLU, ',')\n    pyplot.show()\n\n    print('\\nsoftmax function')\n    x=np.array([2.3, -0.9, 3.6])\n    y=softmax_func_overflow(x)\n    print(y, np.sum(y))\n\n    # x1 = np.array([900, 1000, -1000]) # 입력이 너무 큰 경우 overflow\n    # y1 = softmax_func_overflow(x1)\n    # print(y1, np.sum(y1))\n\n    print('\\n개선된 softmax function') # overflow 가 해결됨\n    x2=np.array([900, 1000, 1000])\n    y2=softmax_func(x2)\n    print(y2, np.sum(y2))\n\n", "meta": {"hexsha": "b65f58eb6ab0939b55c7ad6a92ee94c749d7fc90", "size": 1717, "ext": "py", "lang": "Python", "max_stars_repo_path": "DeepLearning/DeepLearning/09_Deep_SongJW/garbageCan/activationFunctions.py", "max_stars_repo_name": "ghost9023/DeepLearningPythonStudy", "max_stars_repo_head_hexsha": "4d319c8729472cc5f490935854441a2d4b4e8818", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-27T04:05:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T04:05:59.000Z", "max_issues_repo_path": "DeepLearning/DeepLearning/09_Deep_SongJW/garbageCan/activationFunctions.py", "max_issues_repo_name": "ghost9023/DeepLearningPythonStudy", "max_issues_repo_head_hexsha": "4d319c8729472cc5f490935854441a2d4b4e8818", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DeepLearning/DeepLearning/09_Deep_SongJW/garbageCan/activationFunctions.py", "max_forks_repo_name": "ghost9023/DeepLearningPythonStudy", "max_forks_repo_head_hexsha": "4d319c8729472cc5f490935854441a2d4b4e8818", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2921348315, "max_line_length": 62, "alphanum_fraction": 0.5690157251, "include": true, "reason": "import numpy", "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377237352755, "lm_q2_score": 0.9124361688107864, "lm_q1q2_score": 0.8746044883056268}}
{"text": "import numpy as np\nimport inspect\n\n# 1) Stwórz wektor zer o rozmiarze 10\n\nv = np.zeros((10,), dtype=int)\n\nassert v.sum() == 0\nassert v.shape == (10,)\n\n# ---------------------------------------------------\n# 2) Napisz funkcję zwracającą ilość danych jaką zajmuje tablica numpy\n\ndef memof(a):\n    return a.nbytes\n\nassert memof(np.zeros((12,10),dtype=np.int32))==480\n\n# ---------------------------------------------------\n# 3) Napisz funkcję tworzącą wektor zer o rozmiarze n z jedynką na piątym miejscu\n\ndef make_v(n):\n\n    # Tworzenie wektora z 10 zerami\n    v = np.zeros((n,), dtype=int)\n\n    # Ustawienie jedynki na piątym miejscu\n    v[4] = 1\n    return v\n\nassert make_v(14)[4] == 1\nnp.testing.assert_array_equal( make_v(14)[:4] , 0)\nnp.testing.assert_array_equal( make_v(14)[5:] , 0)\n\n# ---------------------------------------------------\n# 4) Utwórz wektor z wartościami od 10 do 49 włącznie\n\ndef make10_49():\n    v = np.array(range(10, 50))\n    return v\n\nassert make10_49()[7] == 17\n\n# ---------------------------------------------------\n# 5) Odwóć kolejność elementów wektora\n\ndef reverse(v):\n    v = v[::-1]\n    return v\n\nnp.testing.assert_equal(reverse(np.array([1,2,3])), np.array([3,2,1]))\n\n# ---------------------------------------------------\n# 6) Stwórz macierz jednostkową o rozmiarze n x n\n\ndef identity_matrix(n):\n    v = np.eye(n)\n    return v\n\nnp.testing.assert_equal(identity_matrix(2), np.array([[1, 0],  [0, 1]]))\n\n# ---------------------------------------------------\n# 7) Utwórz macierz n×n z wartościami od 1 do n**2\n\n# Tak by każdy rząd zawierał wartości rosnące o 1\ndef n2_col(n):\n    # Inicjalizacja talicy z wartościami od 1 do n**2,\n    # a następnie zmienienie jej kształtu na macierz n x n\n    v = np.arange(1, n ** 2 + 1).reshape(n, n)\n    return v\n\nnp.testing.assert_equal( n2_col(2), np.array([[1, 2],  [3, 4]]) )\n\n# Tak by każda kolumna zawierała wartości rosnące o 1\ndef n2_row(n):\n    # Zamiana kolumn z wierszami tak aby wartości nie roszły w\n    # wierszach tylko w kolumnach\n    v = n2_col(n).transpose()\n    return v\n\nnp.testing.assert_equal( n2_row(2), np.array([[1, 3],  [2, 4]]) )\n\n# ---------------------------------------------------\n# 8) Utwórz macierz n×m z losowymi wartościami\n\n# Z przedziału [0,1)\ndef rand1(n, m):\n    v = np.random.uniform(0,1,size=(n,m))\n    return v\n\nassert np.min(rand1(n=10, m=11)) >= 0\nassert np.max(rand1(n=10, m=10)) < 1\nassert np.shape(rand1(n=10, m=15)) == (10, 15)\n\n# Z przedziału [a,b)\ndef rand2(n, m, a, b):\n    v = np.random.uniform(a, b, size=(n, m))\n    return v\n\nassert np.min(rand2(n=10, m=12, a=3, b=7)) >= 3\nassert np.max(rand2(n=10, m=12, a=3, b=7)) < 7\nassert np.shape(rand2(n=10, m=12, a=3, b=7)) == (10, 12)\n\n# ---------------------------------------------------\n# 9) Znajdź wskaźniki dla których wartości wektora są równe zero\n\ndef is_zero(x):\n    return np.where(x == 0)[0]\n\nx = np.array([1,2,0,1,0,11])\nnp.testing.assert_equal(is_zero(x), np.array([2,4]))\n\n\n# ---------------------------------------------------\n# 10) Oblicz dla zadanego wektora jego wartość najmniejszą, największą oraz średnią.\n\ndef mystats(x):\n    return np.min(x), np.max(x), np.average(x)\n\nx = np.array([1,2,0,1,0,11])\nassert  mystats(x) == (0, 11, 2.5)\n\n# ---------------------------------------------------\n# 11) Stwórz dwuwymiarową tablicę z zerami w środku i jedynkami na zewnątrz.\ndef zeros_padded(n):\n\n    # Stworzenie macierzy n x n wypełnionej zerami\n    matrix = np.zeros((n, n))\n\n    # Zastępienie krańcowych wartości jedynkami\n    matrix = np.pad(matrix[1:-1, 1:-1], 1, 'constant', constant_values=1)\n\n    return matrix\n\npadded_array = np.array([[ 1.,  1.,  1.,  1.],\n                         [ 1.,  0.,  0.,  1.],\n                         [ 1.,  0.,  0.,  1.],\n                         [ 1.,  1.,  1.,  1.]])\n\nnp.testing.assert_equal(zeros_padded(n=4),\n                        padded_array)\n\n# ---------------------------------------------------\n# 12) Używając `np.pad` dodaj do tablicy otoczenie z wartością 3\n\ndef pad3(x):\n\n    # Do całej macierzy dodajemy obramowanie o szerokości 1 elementu\n    # Obramowanie będzie wypełnione 3\n    matrix = np.pad(x, 1, 'constant', constant_values=3)\n    return matrix\n\nx = np.ones((2,3))\nx_pad3 = np.array([[ 3.,  3.,  3.,  3.,  3.],\n                   [ 3.,  1.,  1.,  1.,  3.],\n                   [ 3.,  1.,  1.,  1.,  3.],\n                   [ 3.,  3.,  3.,  3.,  3.]])\nnp.testing.assert_equal(pad3(x), x_pad3)\n\n# ---------------------------------------------------\n# 13) Dla danej tablicy zastąp maksymalne wartości zerami.\n\ndef maxto0(x):\n    # Wyznaczenie maksimum w danym macierzu\n    maximium = np.max(x)\n\n    # Zamienienie maksymalnych wartości na zera\n    x[np.where(x == maximium)] = 0\n\n    return x\n\nx_expected = np.array([[1, 0, 1, 2],\n                       [0, 2, 1, 0],\n                       [2, 0, 2, 1]])\n\nx = np.array([[1, 3, 1, 2],\n              [3, 2, 1, 3],\n              [2, 0, 2, 1]])\n\nnp.testing.assert_equal(maxto0(x),x_expected)\n\n# ---------------------------------------------------\n# 14) Niech będzie dana tablica k parametrów zmierzonych w n pomiarach:\n#       xij:  j-ty parametr w i-tym pomiarze\n\n# Stwórz funkcję nie zawierającą pętli, która obliczy:\n# - średnią po pomiarach dla wszyskich zmiennych\n# - odchylenie od wartości średniej dla każdej zmiennej we wszystkich pomiarach\n# - odchylenie średniokwadratowe dla każdej zmiennej\n\ndef data_stats(x):\n\n    # Liczba wierszy w danym macierzu\n    n = x.shape[0]\n\n    # Suma wszystkich pomiarów (suma danej kolumny) podzielona przez n pomiarów (liczba wierszy)\n    x_avg = 1 / n * np.sum(x, axis=0)\n\n    # Od każdego wiersza w macierzy odejmujemy średnie wartości poszczególnych kolumn\n    x_delta = x - x_avg\n\n    # Odchylenie średniokwadratowe dla każdej zmiennej (dla każdej kolumny)\n    x_sigma = 1 / n * np.sum((x - x_avg) ** 2, axis=0)\n\n    return x_avg, x_delta, x_sigma\n\n\nexample_matrix = np.array([[3, 4, 2, 3],\n                           [3, 4, 3, 4],\n                           [4, 3, 2, 2],\n                           [3, 2, 1, 2],\n                           [3, 2, 3, 1]])\n\naverage, delta, sigma = data_stats(example_matrix)\nexpected_average = np.array([ 3.2, 3. ,  2.2,  2.4])\nexpected_delta = np.array([[-0.2,  1. , -0.2,  0.6],\n                           [-0.2,  1. ,  0.8,  1.6],\n                           [ 0.8,  0. , -0.2, -0.4],\n                           [-0.2, -1. , -1.2, -0.4],\n                           [-0.2, -1. ,  0.8, -1.4]])\nexpected_sigma = np.array([0.16, 0.8 , 0.56, 1.04])\n\nnp.testing.assert_allclose(average,\n                           expected_average)\n\nnp.testing.assert_allclose(delta,\n                           expected_delta)\n\nnp.testing.assert_allclose(sigma,\n                           expected_sigma)\n\nblacklist = [\".mean\",\".average\",\"for\",\"while\",\"std\"]\nassert all([ not keyword  in inspect.getsource(data_stats) for keyword in blacklist])\n\nprint(\"All tests were successful.\")", "meta": {"hexsha": "6b49ad906a5ad7c5e3178fdb293b8e32fde6763f", "size": 6924, "ext": "py", "lang": "Python", "max_stars_repo_path": "short_tasks/exercises.py", "max_stars_repo_name": "danielwardega141196/introduction-to-numpy", "max_stars_repo_head_hexsha": "978f48b4fc47d56bce8839ebfd0f6ec801add860", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "short_tasks/exercises.py", "max_issues_repo_name": "danielwardega141196/introduction-to-numpy", "max_issues_repo_head_hexsha": "978f48b4fc47d56bce8839ebfd0f6ec801add860", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "short_tasks/exercises.py", "max_forks_repo_name": "danielwardega141196/introduction-to-numpy", "max_forks_repo_head_hexsha": "978f48b4fc47d56bce8839ebfd0f6ec801add860", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4638297872, "max_line_length": 96, "alphanum_fraction": 0.5306181398, "include": true, "reason": "import numpy", "num_tokens": 2350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.926303728768107, "lm_q1q2_score": 0.8745945420735106}}
{"text": "import numpy as np\n#Evaluate the linear regression\ndef compute_cost(X, y, theta):\n    '''\n    Comput cost for linear regression\n    '''\n    #Number of training samples\n    m = y.size\n\n    predictions = X.dot(theta).flatten()\n\n    sqErrors = (predictions - y) ** 2\n\n    J = (1.0 / (2 * m)) * sqErrors.sum()\n\n    return J\n\n\ndef gradient_descent(X, y, theta, alpha, num_iters):\n    '''\n    Performs gradient descent to learn theta\n    by taking num_items gradient steps with learning\n    rate alpha\n    '''\n    m = y.size\n    J_history = np.zeros(shape=(num_iters, 1))\n\n    for i in range(num_iters):\n\n        predictions = X.dot(theta).flatten()\n\n        errors_x1 = (predictions - y) * X[:, 0]\n        errors_x2 = (predictions - y) * X[:, 1]\n\n        theta[0][0] = theta[0][0] - alpha * (1.0 / m) * errors_x1.sum()\n        theta[1][0] = theta[1][0] - alpha * (1.0 / m) * errors_x2.sum()\n\n        J_history[i, 0] = compute_cost(X, y, theta)\n\n    return theta, J_history", "meta": {"hexsha": "275648de118a4847838a110ca7ff12572c6bb92e", "size": 967, "ext": "py", "lang": "Python", "max_stars_repo_path": "ut_engine/LR/linregr.py", "max_stars_repo_name": "justpic/ut_ali", "max_stars_repo_head_hexsha": "5173011c735cdbd4b1cb9becad3b69675993225a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-08T01:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T01:30:07.000Z", "max_issues_repo_path": "ut_engine/LR/linregr.py", "max_issues_repo_name": "justpic/ut_ali", "max_issues_repo_head_hexsha": "5173011c735cdbd4b1cb9becad3b69675993225a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ut_engine/LR/linregr.py", "max_forks_repo_name": "justpic/ut_ali", "max_forks_repo_head_hexsha": "5173011c735cdbd4b1cb9becad3b69675993225a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.175, "max_line_length": 71, "alphanum_fraction": 0.5863495346, "include": true, "reason": "import numpy", "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357604052423, "lm_q2_score": 0.893309416705815, "lm_q1q2_score": 0.8745818640617411}}
{"text": "import numpy as np\n\ndef power_method(A, error_tol):\n\tlim = 10000 #Numero maximo de iteracoes\n\terror = np.inf #atribuicao de infinito para o erro\n\tn = A.shape[1] #pegando a dimensao da matriz A quadrada\n\ty0 = np.zeros(n)  \n\ty0[0] = 1 #chute inicial normalizado\n\n\tfor k in range (0, lim):\t\n\t\txk = A.dot(y0) #produto de matrizes (x^k) = A * y^(k-1) \n\t\tyk = xk/np.linalg.norm(xk) #normalizando xk\t\n\t\terror = np.abs(np.abs(y0.dot(yk))-1) #teste de alinhamento, calculando o erro\n\t\tif error <= error_tol: # se o erro for menor que a tolerancia recebida como parametro, pode parar a iteracao\n\t\t\tbreak\n\t\ty0 = yk #atribuindo o novo y0\n \t\t\n\n\tlambda_1 = y0.dot(A.dot(y0)) #calculando o lambda_1 = y^k * (A * y^k)\n\t\n\treturn lambda_1, y0 #retornando o autovalor e seu autovetor associado\n\n\nA = np.array([[12, 2, 3],  \n              [ 2, 3, 5],\n              [ 3, 5,-2]], dtype='double')\n\n(D,V) = np.linalg.eig(A) #usando uma funcao pronta para calcular todos os autovalores\nprint('Método do Python: {0:.15f}'.format(np.max(abs(D))))\n(autovalor, autovetor) = power_method(A, 0.000000001) #usando o metodo da potencia implementado com erro em torno de 10^-9\nprint('Método Implementado: {0:.15f}'.format(autovalor))\n", "meta": {"hexsha": "bc533499f719f2caf46b1b681685740b4461afb1", "size": 1200, "ext": "py", "lang": "Python", "max_stars_repo_path": "PowerIteration.py", "max_stars_repo_name": "igortakeo/Calculo-Numerico", "max_stars_repo_head_hexsha": "96ed1892c3d2ba80039f2f2ce7de4ca834aa6283", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PowerIteration.py", "max_issues_repo_name": "igortakeo/Calculo-Numerico", "max_issues_repo_head_hexsha": "96ed1892c3d2ba80039f2f2ce7de4ca834aa6283", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PowerIteration.py", "max_forks_repo_name": "igortakeo/Calculo-Numerico", "max_forks_repo_head_hexsha": "96ed1892c3d2ba80039f2f2ce7de4ca834aa6283", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5, "max_line_length": 122, "alphanum_fraction": 0.6683333333, "include": true, "reason": "import numpy", "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360067, "lm_q2_score": 0.9161096187428011, "lm_q1q2_score": 0.8745616846442615}}
{"text": "import numpy as np\n\ndef forward_euler(f,y0,Delta_t,numsteps):\n    \"\"\"Perform numsteps of the forward euler method starting at y0\n    of the ODE y'(t) = f(y,t)\n    Args:\n        f: function to integrate takes arguments y,t\n        y0: initial condition\n        Delta_t: time step size\n        numsteps: number of time steps\n        \n    Returns:\n        a numpy array of the times and a numpy\n        array of the solution at those times\n    \"\"\"\n    numsteps = int(numsteps)\n    y = np.zeros(numsteps+1)\n    t = np.arange(numsteps+1)*Delta_t\n    y[0] = y0\n    for n in range(1,numsteps+1):\n        y[n] = y[n-1] + Delta_t * f(y[n-1], t[n-1])\n    return t, y\n\ndef inexact_newton(f,x0,delta = 1.0e-7, epsilon=1.0e-6, LOUD=False):\n    \"\"\"Find the root of the function f via Newton-Raphson method\n    Args:\n        f: function to find root of\n        x0: initial guess\n        delta: finite difference parameter\n        epsilon: tolerance\n        \n    Returns:\n        estimate of root\n    \"\"\"\n    x = x0\n    if (LOUD):\n        print(\"x0 =\",x0)\n    iterations = 0\n    while (np.fabs(f(x)) > epsilon):\n        fx = f(x)\n        fxdelta = f(x+delta)\n        slope = (fxdelta - fx)/delta\n        if (LOUD):\n            print(\"x_\",iterations+1,\"=\",x,\"-\",fx,\"/\",slope,\"=\",x - fx/slope)\n        x = x - fx/slope\n        iterations += 1\n    #print(\"It took\",iterations,\"iterations\")\n    return x #return estimate of root\n\ndef backward_euler(f,y0,Delta_t,numsteps):\n    \"\"\"Perform numsteps of the backward euler method starting at y0\n    of the ODE y'(t) = f(y,t)\n    Args:\n        f: function to integrate takes arguments y,t\n        y0: initial condition\n        Delta_t: time step size\n        numsteps: number of time steps\n        \n    Returns:\n        a numpy array of the times and a numpy\n        array of the solution at those times\n    \"\"\"\n    numsteps = int(numsteps)\n    y = np.zeros(numsteps+1)\n    t = np.arange(numsteps+1)*Delta_t\n    y[0] = y0\n    for n in range(1,numsteps+1):\n        solve_func = lambda u: u-y[n-1] - Delta_t*f(u,t[n])\n        y[n] = inexact_newton(solve_func,y[n-1])\n    return t, y\n\ndef inexact_newton(f,x0,delta = 1.0e-7, epsilon=1.0e-6, LOUD=False):\n    \"\"\"Find the root of the function f via Newton-Raphson method\n    Args:\n        f: function to find root of\n        x0: initial guess\n        delta: finite difference parameter\n        epsilon: tolerance\n        \n    Returns:\n        estimate of root\n    \"\"\"\n    x = x0\n    if (LOUD):\n        print(\"x0 =\",x0)\n    iterations = 0\n    while (np.fabs(f(x)) > epsilon):\n        fx = f(x)\n        fxdelta = f(x+delta)\n        slope = (fxdelta - fx)/delta\n        if (LOUD):\n            print(\"x_\",iterations+1,\"=\",x,\"-\",fx,\"/\",slope,\"=\",x - fx/slope)\n        x = x - fx/slope\n        iterations += 1\n    #print(\"It took\",iterations,\"iterations\")\n    return x #return estimate of root\n\ndef backward_euler(f,y0,Delta_t,numsteps):\n    \"\"\"Perform numsteps of the backward euler method starting at y0\n    of the ODE y'(t) = f(y,t)\n    Args:\n        f: function to integrate takes arguments y,t\n        y0: initial condition\n        Delta_t: time step size\n        numsteps: number of time steps\n        \n    Returns:\n        a numpy array of the times and a numpy\n        array of the solution at those times\n    \"\"\"\n    numsteps = int(numsteps)\n    y = np.zeros(numsteps+1)\n    t = np.arange(numsteps+1)*Delta_t\n    y[0] = y0\n    for n in range(1,numsteps+1):\n        solve_func = lambda u: u-y[n-1] - Delta_t*f(u,t[n])\n        y[n] = inexact_newton(solve_func,y[n-1])\n    return t, y\n\ndef RK4(f,y0,Delta_t,numsteps):\n    \"\"\"Perform numsteps of the 4th order Runge-Kutta method starting at y0\n    of the ODE y'(t) = f(y,t)\n    Args:\n        f: function to integrate takes arguments y,t\n        y0: initial condition\n        Delta_t: time step size\n        numsteps: number of time steps\n        \n    Returns:\n        a numpy array of the times and a numpy\n        array of the solution at those times\n    \"\"\"\n    numsteps = int(numsteps)\n    y = np.zeros(numsteps+1)\n    t = np.arange(numsteps+1)*Delta_t\n    y[0] = y0\n    for n in range(1,numsteps+1):\n        dy1 = Delta_t * f(y[n-1], t[n-1])\n        dy2 = Delta_t * f(y[n-1] + 0.5*dy1, t[n-1] + 0.5*Delta_t)\n        dy3 = Delta_t * f(y[n-1] + 0.5*dy2, t[n-1] + 0.5*Delta_t)\n        dy4 = Delta_t * f(y[n-1] + dy3, t[n-1] + Delta_t)\n        y[n] = y[n-1] + 1.0/6.0*(dy1 + 2.0*dy2 + 2.0*dy3 + dy4)\n    return t, y\n\ndef forward_euler_system(Afunc,c,y0,Delta_t,numsteps):\n    \"\"\"Perform numsteps of the forward euler method starting at y0\n    of the ODE y'(t) = A(t) y(t) + c(t)\n    Args:\n        Afunc: function to compute A matrix\n        c: nonlinear function of time\n        Delta_t: time step size\n        numsteps: number of time steps\n        \n    Returns:\n        a numpy array of the times and a numpy\n        array of the solution at those times\n    \"\"\"\n    numsteps = int(numsteps)\n    unknowns = y0.size\n    y = np.zeros((unknowns,numsteps+1))\n    t = np.arange(numsteps+1)*Delta_t\n    y[0:unknowns,0] = y0\n    for n in range(1,numsteps+1):\n        yold = y[0:unknowns,n-1]\n        A = Afunc(t[n-1])\n        y[0:unknowns,n] = yold + Delta_t * (np.dot(A,yold) + c(t[n-1]))\n    return t, y\n\ndef swap_rows(A, a, b):\n    \"\"\"Rows two rows in a matrix, switch row a with row b\n    \n    args:\n        A: matrix to perform row swaps on\n        a: row index of matrix\n        b: row index of matrix\n        \n    returns: nothing\n    \n    side effects:\n    changes A to rows a and b swapped\n    \"\"\"\n    assert (a>=0) and (b>=0)\n    N = A.shape[0] #number of rows\n    assert (a<N) and (b<N) #less than because 0-based indexing\n    temp = A[a,:].copy()\n    A[a,:] = A[b,:].copy()\n    A[b,:] = temp.copy()\ndef BackSub(aug_matrix,x):\n    \"\"\"back substitute a N by N system after Gaussian elimination\n    \n    Args:\n        aug_matrix: augmented matrix with zeros below the diagonal\n        x: length N vector to hold solution\n    Returns:\n        nothing\n    Side Effect:\n    x now contains solution\n    \"\"\"\n    N = x.size\n    for row in range(N-1,-1,-1):\n        RHS = aug_matrix[row,N]\n        for column in range(row+1,N):\n            RHS -= x[column]*aug_matrix[row,column]\n        x[row] = RHS/aug_matrix[row,row]\n    return\ndef GaussElimPivotSolve(A,b,LOUD=0):\n    \"\"\"create a Gaussian elimination with pivoting matrix for a system\n    \n    Args:\n        A: N by N array\n        b: array of length N\n    Returns:\n        solution vector in the original order\n    \"\"\"\n    [Nrow, Ncol] = A.shape\n    assert Nrow == Ncol\n    N = Nrow\n    #create augmented matrix\n    aug_matrix = np.zeros((N,N+1))\n    aug_matrix[0:N,0:N] = A\n    aug_matrix[:,N] = b\n    #augmented matrix is created\n    \n    #create scale factors\n    s = np.zeros(N)\n    count = 0\n    for row in aug_matrix[:,0:N]: #don't include b\n        s[count] = np.max(np.fabs(row))\n        count += 1\n    if LOUD:\n        print(\"s =\",s)\n    if LOUD:\n        print(\"Original Augmented Matrix is\\n\",aug_matrix)\n    #perform elimination\n    for column in range(0,N):\n        \n        #swap rows if needed\n        largest_pos = np.argmax(np.fabs(aug_matrix[column:N,column]/s[column])) + column\n        if (largest_pos != column):\n            if (LOUD):\n                print(\"Swapping row\",column,\"with row\",largest_pos)\n                print(\"Pre swap\\n\",aug_matrix)\n            swap_rows(aug_matrix,column,largest_pos)\n            #re-order s\n            tmp = s[column]\n            s[column] = s[largest_pos]\n            s[largest_pos] = tmp\n            if (LOUD):\n                print(\"A =\\n\",aug_matrix)\n        #finish off the row\n        for row in range(column+1,N):\n            mod_row = aug_matrix[row,:]\n            mod_row = mod_row - mod_row[column]/aug_matrix[column,column]*aug_matrix[column,:]\n            aug_matrix[row] = mod_row\n    #now back solve\n    x = b.copy()\n    if LOUD:\n        print(\"Final aug_matrix is\\n\",aug_matrix)\n    BackSub(aug_matrix,x)\n    return x\n\ndef backward_euler_system(Afunc,c,y0,Delta_t,numsteps):\n    \"\"\"Perform numsteps of the forward euler method starting at y0\n    of the ODE y'(t) = A(t) y(t) + c(t)\n    Args:\n        Afunc: function to compute A matrix\n        c: nonlinear function of time\n        y0: initial condition\n        Delta_t: time step size\n        numsteps: number of time steps\n        \n    Returns:\n        a numpy array of the times and a numpy\n        array of the solution at those times\n    \"\"\"\n    numsteps = int(numsteps)\n    unknowns = y0.size\n    y = np.zeros((unknowns,numsteps+1))\n    t = np.arange(numsteps+1)*Delta_t\n    y[0:unknowns,0] = y0\n    for n in range(1,numsteps+1):\n        yold = y[0:unknowns,n-1]\n        A = Afunc(t[n])\n        LHS = np.identity(unknowns) - Delta_t * A\n        RHS = yold + c(t[n])*Delta_t\n        y[0:unknowns,n] = GaussElimPivotSolve(LHS,RHS)\n    return t, y\n\ndef cn_system(Afunc,c,y0,Delta_t,numsteps):\n    \"\"\"Perform numsteps of the forward euler method starting at y0\n    of the ODE y'(t) = A(t) y(t) + c(t)\n    Args:\n        Afunc: function to compute A matrix\n        c: nonlinear function of time\n        y0: initial condition\n        Delta_t: time step size\n        numsteps: number of time steps\n        \n    Returns:\n        a numpy array of the times and a numpy\n        array of the solution at those times\n    \"\"\"\n    numsteps = int(numsteps)\n    unknowns = y0.size\n    y = np.zeros((unknowns,numsteps+1))\n    t = np.arange(numsteps+1)*Delta_t\n    y[0:unknowns,0] = y0\n    for n in range(1,numsteps+1):\n        yold = y[0:unknowns,n-1]\n        A = Afunc(t[n])\n        LHS = np.identity(unknowns) - 0.5*Delta_t * A\n        A = Afunc(t[n-1])\n        RHS = yold + 0.5*Delta_t * np.dot(A,yold) + 0.5*(c(t[n-1]) + c(t[n]))*Delta_t\n        y[0:unknowns,n] = GaussElimPivotSolve(LHS,RHS)\n    return t, y\n\ndef RK4_system(Afunc,c,y0,Delta_t,numsteps):\n    \"\"\"Perform numsteps of the forward euler method starting at y0\n    of the ODE y'(t) = f(y,t)\n    Args:\n        f: function to integrate takes arguments y,t\n        y0: initial condition\n        Delta_t: time step size\n        numsteps: number of time steps\n        \n    Returns:\n        a numpy array of the times and a numpy\n        array of the solution at those times\n    \"\"\"\n    numsteps = int(numsteps)\n    unknowns = y0.size\n    y = np.zeros((unknowns,numsteps+1))\n    t = np.arange(numsteps+1)*Delta_t\n    y[0:unknowns,0] = y0\n    for n in range(1,numsteps+1):\n        yold = y[0:unknowns,n-1]\n        A = Afunc(t[n-1])\n        dy1 = Delta_t * (np.dot(A,yold) + c(t[n-1])) \n        A = Afunc(t[n-1] + 0.5*Delta_t)\n        dy2 = Delta_t * (np.dot(A,y[0:unknowns,n-1] + 0.5*dy1) \n                         + c(t[n-1] + 0.5*Delta_t))\n        dy3 = Delta_t * (np.dot(A,y[0:unknowns,n-1] + 0.5*dy2) \n                         + c(t[n-1] + 0.5*Delta_t))\n        A = Afunc(t[n] + Delta_t)\n        dy4 = Delta_t * (np.dot(A,y[0:unknowns,n-1] + dy3) + c(t[n]))\n        y[0:unknowns,n] = y[0:unknowns,n-1] + 1.0/6.0*(dy1 + 2.0*dy2 + 2.0*dy3 + dy4)\n    return t, y\n\ndef new2(f,y0,Delta_t,numsteps):\n    \"\"\"Perform numsteps of the backward euler method starting at y0\n    of the ODE y'(t) = f(y,t)\n    Args:\n        f: function to integrate takes arguments y,t\n        y0: initial condition\n        Delta_t: time step size\n        numsteps: number of time steps\n        \n    Returns:\n        a numpy array of the times and a numpy\n        array of the solution at those times\n    \"\"\"\n    numsteps = int(numsteps)\n    y = np.zeros(numsteps+1)\n    t = np.arange(numsteps+1)*Delta_t\n    y[0] = y0\n    for n in range(1,numsteps+1):\n        tcur = t[n-1]\n        fshift = lambda u,t: f(u,t+tcur)\n        tmp,y1 = backward_euler(fshift,y[n-1],Delta_t*0.5,1)\n        tmp,y2 = backward_euler(fshift,y[n-1],Delta_t,1)\n        y[n] = y[n-1] + Delta_t*(1.0/(1.0+Delta_t) * f(y1[1],t[n-1]+0.5*Delta_t) + \n                                 Delta_t/(1.0+Delta_t) * f(y2[1],t[n]))\n    return t, y\n\ndef new2_system(Afunc,c,y0,Delta_t,numsteps):\n    \"\"\"Perform numsteps of the forward euler method starting at y0\n    of the ODE y'(t) = A(t) y(t) + c(t)\n    Args:\n        Afunc: function to compute A matrix\n        c: nonlinear function of time\n        y0: initial condition\n        Delta_t: time step size\n        numsteps: number of time steps\n        \n    Returns:\n        a numpy array of the times and a numpy\n        array of the solution at those times\n    \"\"\"\n    numsteps = int(numsteps)\n    unknowns = y0.size\n    y = np.zeros((unknowns,numsteps+1))\n    t = np.arange(numsteps+1)*Delta_t\n    y[0:unknowns,0] = y0\n    for n in range(1,numsteps+1):\n        tcur = t[n-1]\n        Af = lambda t: Afunc(t+tcur)\n        cf = lambda t: c(t+tcur)\n        tmp,y1 = backward_euler_system(Af,cf,y[0:unknowns,n-1],Delta_t*0.5,1)\n        tmp,y2 = backward_euler_system(Af,cf,y[0:unknowns,n-1],Delta_t,1)\n        y1 = y1[0:unknowns,1]\n        y2 = y2[0:unknowns,1]\n        th = t[n-1] + 0.5*Delta_t\n        Ah = Afunc(th)\n        A = Afunc(t[n])\n        y[0:unknowns,n] = y[0:unknowns,n-1] + Delta_t*(1.0/(1.0+Delta_t) * (np.dot(Ah,y1) + c(th)) + \n                                 Delta_t/(1.0+Delta_t) * (np.dot(A,y2) + c(t[n])) )\n    return t, y\n\ndef crank_nicolson(f,y0,Delta_t,numsteps):\n    \"\"\"Perform numsteps of the backward euler method starting at y0\n    of the ODE y'(t) = f(y,t)\n    Args:\n        f: function to integrate takes arguments y,t\n        y0: initial condition\n        Delta_t: time step size\n        numsteps: number of time steps\n        \n    Returns:\n        a numpy array of the times and a numpy\n        array of the solution at those times\n    \"\"\"\n    numsteps = int(numsteps)\n    y = np.zeros(numsteps+1)\n    t = np.arange(numsteps+1)*Delta_t\n    y[0] = y0\n    for n in range(1,numsteps+1):\n        solve_func = lambda u: u-y[n-1] - 0.5*Delta_t*(f(u,t[n])\n                                                       + f(y[n-1],t[n-1]))\n        y[n] = inexact_newton(solve_func,y[n-1])\n    return t, y", "meta": {"hexsha": "2c17674910b9429dd192dbf8593de742d37f527c", "size": 13940, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch17.py", "max_stars_repo_name": "DrRyanMc/CompNucEng", "max_stars_repo_head_hexsha": "55d36abea64c9298092dee0b539bfaccae3f49a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-09-29T19:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T20:08:08.000Z", "max_issues_repo_path": "ch17.py", "max_issues_repo_name": "AllSafeCyberSecur1ty/Nuclear-Engineering", "max_issues_repo_head_hexsha": "302d6dcc7c0a85a9191098366b076cf9cb5a9f6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-04-07T02:26:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-18T23:04:31.000Z", "max_forks_repo_path": "ch17.py", "max_forks_repo_name": "DrRyanMc/CompNucEng", "max_forks_repo_head_hexsha": "55d36abea64c9298092dee0b539bfaccae3f49a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-03T17:34:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T03:48:45.000Z", "avg_line_length": 32.4186046512, "max_line_length": 101, "alphanum_fraction": 0.5684361549, "include": true, "reason": "import numpy", "num_tokens": 4281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474181553805, "lm_q2_score": 0.9161096193153989, "lm_q1q2_score": 0.8745616828267541}}
{"text": "\"\"\"\r\n@author = mbilkhu\r\nCode for Logistic Regression\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\ndef load_dataset():\r\n    X = np.array([[0,0],[0,1],[1,0],[1,1]])\r\n    y = np.array([0,1,1,0])\r\n    W = np.random.randn(1,2)\r\n    b = np.ones(1)\r\n    x = X.T\r\n    y = y.T\r\n    print(\"X Shape:- \" +  str(x.shape))\r\n    print(\"Y Shape:- \" +  str(y.shape))\r\n    return x,y,W,b\r\n\r\ndef sigmoid(z):\r\n    return 1.0/(1.0 + np.exp(-z))\r\n\r\ndef sigmoid_gradient(x):\r\n    return x * (1-x)\r\n\r\ndef forward_propagate(W, x, b):\r\n    z = np.dot(W, x) + b\r\n    a = sigmoid(z)\r\n    return a\r\n\r\ndef compute_loss(y, a):\r\n    x = np.multiply(y, np.log(a)) + np.multiply((1-y), np.log(1-a))\r\n    cost = np.sum(x, dtype=np.float32)\r\n    return -np.squeeze(cost)\r\n\r\ndef gradient_descent(y, a, x):\r\n    dz = (a-y) * sigmoid_gradient(a)\r\n    dw = np.dot(dz, x.T)\r\n    db = dz\r\n    return dw, db\r\n\r\ndef main():\r\n    x,y,W,b = load_dataset()\r\n    loss = []\r\n    n_epochs = 60000\r\n    learning_rate = 0.01\r\n    for i in range(n_epochs):\r\n        a = forward_propagate(W, x, b)\r\n        cost = compute_loss(y, a)\r\n        loss.append(cost)\r\n        dw, db = gradient_descent(y, a, x)\r\n        W = W - learning_rate * dw\r\n        b = b - learning_rate * db\r\n        if i%250 == 0:\r\n            print(\"Loss after epoch %d = %f \" % (i, cost))\r\n    print(a)\r\n\r\nif __name__=='__main__':\r\n    main()\r\n", "meta": {"hexsha": "8b9536158a8188c0589fe32cfb56c96c696e4fe3", "size": 1346, "ext": "py", "lang": "Python", "max_stars_repo_path": "logistic_regression_with_xor.py", "max_stars_repo_name": "manjotms10/ML_Exercises", "max_stars_repo_head_hexsha": "d4879c43ee828bc68db00a1fbe825db855bf14bd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "logistic_regression_with_xor.py", "max_issues_repo_name": "manjotms10/ML_Exercises", "max_issues_repo_head_hexsha": "d4879c43ee828bc68db00a1fbe825db855bf14bd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logistic_regression_with_xor.py", "max_forks_repo_name": "manjotms10/ML_Exercises", "max_forks_repo_head_hexsha": "d4879c43ee828bc68db00a1fbe825db855bf14bd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.813559322, "max_line_length": 68, "alphanum_fraction": 0.5133729569, "include": true, "reason": "import numpy", "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. Yes\n2. Yes", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.9399133502467731, "lm_q1q2_score": 0.874550139811315}}
{"text": "import math\nfrom cmath import pi\n\nimport numpy as np\n\n\ndef cylinder_area(r:float,h:float):\n    \"\"\"Obliczenie pola powierzchni walca. \n    Szczegółowy opis w zadaniu 1.\n    \n    Parameters:\n    r (float): promień podstawy walca \n    h (float): wysokosć walca\n    \n    Returns:\n    float: pole powierzchni walca \n    \"\"\"\n    if r > 0 and h > 0:\n        return 2 * pi * r * h + pi * r * r * 2\n    else:\n        return math.nan\n\n\n\ndef fib(n:int):\n    \"\"\"Obliczenie pierwszych n wyrazów ciągu Fibonnaciego. \n    Szczegółowy opis w zadaniu 3.\n    \n    Parameters:\n    n (int): liczba określająca ilość wyrazów ciągu do obliczenia \n    \n    Returns:\n    np.ndarray: wektor n pierwszych wyrazów ciągu Fibonnaciego.\n    \"\"\"\n    if n > 0 and isinstance(n, int):\n        result = np.ndarray(shape=(1, n), dtype=int)\n        result[0][0] = 1  # jak zaczynam od 0 to testy nie przechodzą\n        if n == 1:  # dostaje dosyć sprzeczne odpowiedzi od testów więc dorzucam ten warunek\n            return result[0]\n        if n >= 2:\n            result[0][1] = 1\n        if n >= 3:\n            i = 2\n            while n > i:\n                result[0][i] = result[0][i - 1] + result[0][i - 2]\n                i += 1\n        return result\n\n    else:\n        return None\n\n\n\ndef matrix_calculations(a:float):\n    \"\"\"Funkcja zwraca wartości obliczeń na macierzy stworzonej \n    na podstawie parametru a.  \n    Szczegółowy opis w zadaniu 4.\n    \n    Parameters:\n    a (float): wartość liczbowa \n    \n    Returns:\n    touple: krotka zawierająca wyniki obliczeń \n    (Minv, Mt, Mdet) - opis parametrów w zadaniu 4.\n    \"\"\"\n    M = np.array([[a, 1, -a], [0, 1, 1], [-a, a, 1]])\n    try:\n        Minv = np.linalg.inv(M)\n    except np.linalg.LinAlgError:\n        Minv = math.nan\n    Mt = M.T\n    Mdet = np.linalg.det(M)\n    return Minv, Mt, Mdet\n\n\n\n\ndef custom_matrix(m:int, n:int):\n    \"\"\"Funkcja zwraca macierz o wymiarze mxn zgodnie \n    z opisem zadania 7.  \n    \n    Parameters:\n    m (int): ilość wierszy macierzy\n    n (int): ilość kolumn macierzy  \n    \n    Returns:\n    np.ndarray: macierz zgodna z opisem z zadania 7.\n    \"\"\"\n    if n >= 0 and m >= 0 and isinstance(n, int) and isinstance(m, int):\n        result = np.ndarray([m, n])\n        for i, row in enumerate(result):\n            for j, _ in enumerate(row):\n                if i > j:\n                    result[i][j] = i\n                else:\n                    result[i][j] = j\n        return result\n    else:\n        return None\n\n\n\n\n\n", "meta": {"hexsha": "91b469ea17159d951782b6a25acbf77272a89d5c", "size": 2475, "ext": "py", "lang": "Python", "max_stars_repo_path": "Metody numeryczne 2021/Laboratorium 1/main.py", "max_stars_repo_name": "jakub-sacha/public_lectures", "max_stars_repo_head_hexsha": "fbd1360e0a0f4655985e49ef53fcecfd5e99367f", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Metody numeryczne 2021/Laboratorium 1/main.py", "max_issues_repo_name": "jakub-sacha/public_lectures", "max_issues_repo_head_hexsha": "fbd1360e0a0f4655985e49ef53fcecfd5e99367f", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Metody numeryczne 2021/Laboratorium 1/main.py", "max_forks_repo_name": "jakub-sacha/public_lectures", "max_forks_repo_head_hexsha": "fbd1360e0a0f4655985e49ef53fcecfd5e99367f", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5714285714, "max_line_length": 92, "alphanum_fraction": 0.5551515152, "include": true, "reason": "import numpy", "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799462157138, "lm_q2_score": 0.9073122182277756, "lm_q1q2_score": 0.8744493208844256}}
{"text": "# Author: Martin Konečnik\n# Contact: martin.konecnik@gmail.com\n# Licenced under MIT\n\n# 1-Vzorčenje\n# Predlagan IDE PyCharm Community Edition (na voljo za Windows, macOS in Linux)\n# https://www.jetbrains.com/pycharm/download\n# Navodila za pridobitev potrebnih knjižnic:\n# https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html\n# Kratka navodila. Znotraj GUI knjižnice dodamo prek File->Settings->Project: Name->Project Interpreter.\n# V tem oknu na desni strani kliknemo na plus in vpišemo ime knjižnice.\n# Privzeta bližnjica za zagon izbora je Alt+Shift+E\n\nimport numpy as np\nimport scipy.signal\nfrom matplotlib import cm  # color mapping\nimport pylab as pylab\nimport matplotlib.pyplot as plt\nimport sounddevice as sd\nfrom pathlib import Path\nfrom PIL import Image\nfrom mpl_toolkits.mplot3d import axes3d\nfrom mpl_toolkits.mplot3d import art3d\n\n# ----------------------------------------------------------------------------------------\n# Vzorčenje in Nyquistov teorem;\nFvz = 100  # Frekvenca vzorčenja (v Hz)\nT = 1  # dolžina signala (v s)\ni = np.arange(float(T) * Fvz) / Fvz  # vektor časovnih indeksov\nf1 = 5  # frekvenca sinusoide\nA1 = 1  # amplituda sinusoide\nfaza1 = 0.0  # faza sinusoide\n\n# ukazi.m:10 -- NOTE: Enak rezultat kot v Matlab 2017b\n# izris sinuside pri razlicnih fazah\nplt.figure()  # Ta vrstica ni nujna, če odpremo le eno okno.\nfor faza1 in np.arange(0, 6.1, 0.1):\n    plt.cla()\n    # pri množenju z matriko je potrebno uporabiti numpy.np.dot(...)\n    s = np.dot(A1, np.sin(np.dot(2 * np.pi * f1, i) + faza1 * np.pi))\n    plt.plot(i, s)\n    setattr(plt.gca, 'YLim', [-1, 1])\n    plt.title('Fvz = {0} Hz, Frekvenca = {1} Hz, faza = {2} $\\pi$'.format(Fvz, f1, round(faza1, 1)))\n    plt.xlabel('Čas (s)')\n    plt.ylabel('Amplituda (dB)')\n    plt.tight_layout()\n    plt.waitforbuttonpress()\n\n# ukazi.m:23 -- NOTE: Preverjeno z Matlab\n# izris sinusid pri različnih frekvencah\nfaza1 = 0.0\nplt.figure()\nfor f1 in np.arange(Fvz + 1):\n    plt.cla()  # počistimo graf za naslednjo iteracijo\n    s = np.dot(A1, np.sin(np.dot(2 * np.pi * f1, i) + faza1 * np.pi))\n    plt.plot(i, s)\n    plt.ylim(-1, 1)\n    plt.title('Fvz = {0} Hz, Frekvenca = {1} Hz, faza = {2} $\\pi$'.format(Fvz, f1, faza1))\n    plt.xlabel('Čas (s)')\n    plt.ylabel('Amplituda (dB)')\n    plt.pause(0.025)\n\n# ukazi.m:37 -- NOTE: Preverjeno z Matlab\n# izris sinusoid s frekvenco f1 in Fvz-f1\nf1 = 1\ns1 = np.sin(np.dot(2 * np.pi * f1, i) + faza1 * np.pi)\nplt.figure()\nplt.plot(i, s1, 'b')\nf2 = Fvz - f1\ns2 = np.sin(np.dot(np.dot(np.dot(2, np.pi), f2), i) + np.dot(faza1, np.pi))\nplt.plot(i, s2, 'r')\nplt.xlabel('Čas (s)')\nplt.ylabel('Amplituda')\nplt.title('Fvz = {0} Hz, Frekvenca1 = {1} Hz, Frekvenca2 = {2} Hz, faza = {3} $\\pi$'.format(Fvz, f1, f2, faza1))\nplt.tight_layout()\n# ----------------------------------------------------------------------------------------\n\n# glej tudi primera v Mathematici: (WheelIllusion.nbp in SamplingTheorem.nbp)\n\n# V Z O R Č E N J E    Z V O K A\n# -----------------------------------------------------------------------------------------\n# ukazi.m:56 -- NOTE: Primerljiv rezultat v Matlab\n# vzorčenje zvoka\nFs = 44100  # vzorčevalna frekvenca\nbits = 16  # bitna ločljivost\nnchans = 1  # 1 (mono), 2 (stereo).\nposnetek = sd.rec(5 * Fs, Fs, nchans, blocking=True)\n\nplt.figure()\nplt.plot(posnetek)\n\nsd.play(posnetek, 44100)\nsd.play(posnetek, 44100 / 2)\nsd.play(posnetek, 2 * 44100)\n\n# -----------------------------------------------------------------------------------------\n# ukazi.m:73 -- NOTE: Primerljiv rezultat v Matlab\n# ali zaznate fazne spremembe? Spreminjajte faza1 med 0 in 2.0 in poženite ta demo...\nFvz = 44100  # vzorčevalna frekvenca\nT = 3  # čas v sekundah\ni = np.arange(0.0, T * Fvz, 1) / Fvz  # vektor časovnih indeksov\nf1 = 500  # frekvenca sinusoide\nA1 = 0.3  # amplituda sinusoide\nfaza1 = 1.0  # faza sinusoide\n\ns = np.dot(A1, np.sin(np.dot(2 * np.pi * f1, i) + faza1 * np.pi))  # tvorjenje sinusoide\ns2 = np.dot(A1, np.sin(np.dot(2 * np.pi * f1, i) + 0 * np.pi))  # tvorjenje sinusoide\n\nsd.play(np.concatenate((s, s2)), Fvz)  # pozor, dvojni oklepaji pri concatenate, ker sta s1 in s2 en parameter!\n# \"navadna\" polja združiš z s+s2, v numpy.array pa to sešteje istoležne elemente\n\n\n# -----------------------------------------------------------------------------------------\n# ukazi.m:88 -- NOTE: Primerljiv rezultat v Matlab\n# trije poskusi: 1. f1 = 50;\n#                2. f1 = 450;\n#                3. f1 = 1450;\n#                4. f1 = 2450;\n\nFvz = 44100  # vzorčevalna frekvenca\nT = 3  # čas v sekundah\ni = np.arange(T * Fvz) / Fvz  # vektor časovnih indeksov\nf1 = 50  # frekvenca sinusoide\nA1 = 5.5  # amplituda sinusoide\nfaza1 = 0.0  # faza sinusoide\nf2 = f1 + 1  # frekvenca druge sinusoide\n\ns1 = np.dot(A1, np.sin(np.dot(2 * np.pi * f1, i) + faza1 * np.pi))  # tvorjenje prve sinusoide\ns2 = np.dot(A1, np.sin(np.dot(2 * np.pi * f2, i) + faza1 * np.pi))  # tvorjenje druge sinusoide\nsd.play(np.concatenate((s1, s2)), Fvz)\n\n# -----------------------------------------------------------------------------------------\n# ukazi.m:106 -- NOTE: Primerljiv rezultat v Matlab\n# ali zaznate zvok netopirja pri 90000 Hz? Nyquist?\nFvz = 44100  # vzorčevalna frekvenca\nT = 3\ni = np.arange(T * Fvz) / Fvz  # vektor časovnih indeksov\nfnetopir = 140000  # frekvenca sinusoide\nA1 = 5.5  # amplituda sinusoide\nfaza1 = 1.0  # faza sinusoide\n\ns = np.dot(A1, np.sin(np.dot(2 * np.pi * fnetopir, i) + faza1 * np.pi))  # tvorjenje sinusoide\nsd.play(s, Fvz)\n\n# ukazi.m:118 -- NOTE: Preverjeno z Matlab\n# izris sinuside pri razlicnih fazah (verzija 2)\nFvz = 100\nT = 1\ni = np.arange(T * Fvz) / Fvz\nf1 = 5\nA1 = 5\nfaza1 = 0.0\n\n# spremninjanje frekvence...\nplt.close('all')\nfig, ax = plt.subplots(2)  # create a figure with 2 subplots\nfig.tight_layout(rect=[0, 0.03, 1, 0.95])\n\nfor f1 in np.arange(0, Fvz+1):\n    ax[0].clear()\n    ax[1].clear()\n\n    s = np.sin(np.dot(2 * np.pi * f1, i) + faza1 * np.pi)\n    ax[0].plot(s)\n    ax[0].set_ylim(-1, 1)\n    ax[0].set_title('Časovna domena: Fvz = {0} Hz, Frekvenca = {1} Hz, faza = {2} $\\pi$'.format(Fvz, f1, faza1))\n\n    ax[1].plot(abs(np.fft.fft(s)), 'r')\n    ax[1].set_ylim(-1, 1)\n    ax[1].set_title('Frekvenčna domena (abs): Fvz = {0} Hz, Frekvenca = {1} Hz, faza = {2} $\\pi$'.format(Fvz, f1, faza1))\n\n    plt.waitforbuttonpress()\n\n\n# in faze... (več o tem na naslednjih vajah)\nf1 = 5\nA1 = 5\nfaza1 = 0.0\nplt.close('all')\nfig, ax = plt.subplots(2)\nfig.tight_layout(rect=[0, 0.03, 1, 0.95])\n\nfor faza1 in np.arange(0, 2.1, 0.1):\n    ax[0].clear()\n    ax[1].clear()\n\n    s = np.sin(np.dot(2 * np.pi * f1, i) + faza1 * np.pi)\n    ax[0].plot(s)\n    ax[0].set_ylim(-1, 1)\n    ax[0].set_title('Časovna domena: Fvz = {0} Hz, Frekvenca = {1} Hz, faza = {2} $\\pi$'.format(Fvz, f1, round(faza1, 1)))\n\n    ax[1].plot(abs(np.fft.fft(s)), 'r')\n    ax[1].set_ylim(-1, 1)\n    ax[1].set_title('Frekvenčna domena (abs): Fvz = {0} Hz, Frekvenca = {1} Hz, faza = {2} $\\pi$'.format(Fvz, f1, round(faza1, 1)))\n\n    plt.waitforbuttonpress()\n\n# S L I K E\n# -----------------------------------------------------------------------------------------\n# ukazi.m:181 -- NOTE: Preverjetno v Matlabu. Del ne deluje pravilno (označeno)\n# vzorčenje slik in Moire\n# Če datoteke ne najde, preverite pod \"Settings -> Project: Name -> Project Structure\" kje je root.\nA = pylab.array(Image.open(Path('./1-Vzorcenje/Moire.jpg')))\nplt.figure(figsize=(10, 10))\nplt.axis('off')\nplt.imshow(A)\nplt.title('originalna slika')\n\npvz = 3\nplt.figure()\nplt.axis('off')\nplt.imshow(A[::pvz, ::pvz])\nplt.title('podvzorčena slika: faktor podvzorčenja {0}'.format(pvz))\n\n# Celotna slika bistveno svetlejša kot v matlabu. Pri bitni ločljivosti 2, sta namesto sivin rumena in modra barva.\n# Podatki?\nst_bit = 2\nkvant = 2 ** (9 - st_bit)\nplt.figure(figsize=(10, 10))\nplt.axis('off')\nplt.imshow(np.dot(np.round(A[:, :, :] / kvant), kvant))\nplt.title('slika pri bitni ločljivosti {0}'.format(st_bit))\n\nfig, ax = plt.subplots(2, 2)\nfig.tight_layout()\n\nax[0, 0].imshow(np.dot(np.round(A[:, :, :] / kvant), kvant))\nax[0, 0].set_title('slika pri bitni ločljivosti {0}'.format(st_bit))\nax[0, 0].set_xticklabels([])\nax[0, 0].set_yticklabels([])\n\nax[0, 1].imshow(np.dot(np.round(A[:, :, 0] / kvant), kvant))\nax[0, 1].set_title('ravnina R pri bitni ločljivosti {0}'.format(st_bit))\nax[0, 1].set_xticklabels([])\nax[0, 1].set_yticklabels([])\n\nax[1, 0].imshow(np.dot(np.round(A[:, :, 1] / kvant), kvant))\nax[1, 0].set_title('ravnina G pri bitni ločljivosti {0}'.format(st_bit))\nax[1, 0].set_xticklabels([])\nax[1, 0].set_yticklabels([])\n\nax[1, 1].imshow(np.dot(np.round(A[:, :, 2] / kvant), kvant))\nax[1, 1].set_title('ravnina B pri bitni ločljivosti {0}'.format(st_bit))\nax[1, 1].set_xticklabels([])\nax[1, 1].set_yticklabels([])\n\n# -----------------------------------------------------------------------------------------\n# ukazi.m:215 -- Note: Plotting not working properly yet. Data shown in 2D.\n# spekter slik, Moire in Diskretna Fourierova transformacija (fft2)\nA = pylab.array(Image.open(Path('./1-Vzorcenje/Moire.jpg')))\nplt.figure().set_size_inches(10, 10)\nplt.imshow(A)\nplt.title('originalna slika')\nplt.axis('off')\n\nplt.close('all')\n\n# ukazi.m:224\nB = np.double(A[:, :, 0])\n\nfig = plt.figure()\nfig.set_size_inches(7, 7)\nax = fig.add_subplot(111, projection='3d')\nX = Y = np.array([np.arange(100), ]*100)  # Creates a 100 * 100 array\nZ = abs(np.fft.fft2(B - np.mean(np.ravel(B)), s=(100, 100)))\nwire = ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)\n\n# Retrive data from internal storage of plot_wireframe, then delete it\nnx, ny, _ = np.shape(wire._segments3d)\nwire_x = np.array(wire._segments3d)[:, :, 0].ravel()\nwire_y = np.array(wire._segments3d)[:, :, 1].ravel()\nwire_z = np.array(wire._segments3d)[:, :, 2].ravel()\nwire.remove()\n\n# create data for a LineCollection\nwire_x1 = np.vstack([wire_x, np.roll(wire_x, 1)])\nwire_y1 = np.vstack([wire_y, np.roll(wire_y, 1)])\nwire_z1 = np.vstack([wire_z, np.roll(wire_z, 1)])\nto_delete = np.arange(0, nx*ny, ny)\nwire_x1 = np.delete(wire_x1, to_delete, axis=1)\nwire_y1 = np.delete(wire_y1, to_delete, axis=1)\nwire_z1 = np.delete(wire_z1, to_delete, axis=1)\nscalars = np.delete(wire_z, to_delete)\n\nsegs = [list(zip(xl, yl, zl)) for xl, yl, zl in \\\n                 zip(wire_x1.T, wire_y1.T, wire_z1.T)]\n\n# Plots the wireframe by a  a line3DCollection\nmy_wire = art3d.Line3DCollection(segs, cmap=\"hsv\")\nmy_wire.set_array(scalars)\nax.add_collection(my_wire)\n\nplt.colorbar(my_wire)\nplt.show()\n\n\n# ukazi.m:226 -- Note: Not implemented. Same chart as previous section.\nB = np.double(A[:, :, 1])\nX, Y = np.meshgrid(np.arange(100), np.arange(100))\nZ = abs(np.fft.fft2(B - np.mean(np.ravel(B)))[0:100, 0:100])\ncolors = cm.Blues(Z)\nrcount, ccount, _ = colors.shape\n\n\nfig = plt.figure()\nfig.set_size_inches(7, 7)\nax = fig.gca(projection='3d')\nsurf = ax.plot_surface(X, Y, Z, rcount=rcount, ccount=ccount, facecolors=colors, shade=False)\nsurf.set_facecolor((0, 0, 0, 0))\nplt.title('G ravnina')\nplt.show()\n\n# ukazi.m:228 -- Note: Not implemented. Same chart as previous section.\nB = np.double(A[:, :, 2])\nX, Y = np.meshgrid(np.arange(100), np.arange(100))\nZ = abs(np.fft.fft2(B - np.mean(np.ravel(B)))[0:100, 0:100])\ncolors = cm.Blues(Z)\nrcount, ccount, _ = colors.shape\n\nfig = plt.figure()\nfig.set_size_inches(7, 7)\nax = fig.gca(projection='3d')\nsurf = ax.plot_surface(X, Y, Z, rcount=rcount, ccount=ccount, facecolors=colors, shade=False)\nsurf.set_facecolor((0, 0, 0, 0))\nplt.title('B ravnina')\nplt.show()\n\n# ukazi.m:231 -- Note: Not implemented. Same chart as previous section.\n# prevzorčena slika..................................\npvz = 4\nB = np.double(A[0::pvz, 0::pvz, 1])\nX, Y = np.meshgrid(np.arange(100), np.arange(100))\nZ = abs(np.fft.fft2(B - np.mean(np.ravel(B)))[0:100, 0:100])\ncolors = cm.Blues(Z)\nrcount, ccount, _ = colors.shape\n\nfig = plt.figure()\nfig.set_size_inches(7, 7)\nax = fig.gca(projection='3d')\nsurf = ax.plot_surface(X, Y, Z, rcount=rcount, ccount=ccount, facecolors=colors, shade=False)\nsurf.set_facecolor((0, 0, 0, 0))\nplt.title('R ravnina, po podvzorenju s faktorjem {0}'.format(pvz))\nplt.show()\n\n# ukazi.m:235\nB = np.double(A[0::pvz, 0::pvz, 2])\nX, Y = np.meshgrid(np.arange(100), np.arange(100))\nZ = abs(np.fft.fft2(B - np.mean(np.ravel(B)))[0:100, 0:100])\ncolors = cm.Blues(Z)\nrcount, ccount, _ = colors.shape\n\nfig = plt.figure()\nfig.set_size_inches(7, 7)\nax = fig.gca(projection='3d')\nsurf = ax.plot_surface(X, Y, Z, rcount=rcount, ccount=ccount, facecolors=colors, shade=False)\nsurf.set_facecolor((0, 0, 0, 0))\nplt.title('G ravnina, po podvzorenju s faktorjem {0}'.format(pvz))\nplt.show()\n\n# ukazi.m:237 -- Note: Not implemented. Same chart as previous section.\nB = np.double(A[0::pvz, 0::pvz, 3])\nX, Y = np.meshgrid(np.arange(100), np.arange(100))\nZ = abs(np.fft.fft2(B - np.mean(np.ravel(B)))[0:100, 0:100])\ncolors = cm.Blues(Z)\nrcount, ccount, _ = colors.shape\n\nfig = plt.figure()\nfig.set_size_inches(7, 7)\nax = fig.gca(projection='3d')\nsurf = ax.plot_surface(X, Y, Z, rcount=rcount, ccount=ccount, facecolors=colors, shade=False)\nsurf.set_facecolor((0, 0, 0, 0))\nplt.title('B ravnina, po podvzorenju s faktorjem {0}'.format(pvz))\nplt.show()\n\n# -----------------------------------------------------------------------------------------\n# ukazi.m:241\n# podvzorčenje slik in operator povprečenja\n\nA = pylab.array(Image.open(Path('./1-Vzorcenje/Moire.jpg')))\nplt.figure().set_size_inches(10, 10)\nplt.imshow(A)\nplt.title('originalna slika')\nplt.axis('off')\n\npvz = 3  # faktor podvzorčenja\nplt.figure()\nplt.imshow(A[0::pvz, 0::pvz, :])\nplt.title('podvzorčena slika: faktor podvzorčenja {0}'.format(pvz))\n\n# ukazi.m:253 -- Note: Mislim, da je ok, čeprav rezultat različen kot v Matlab (poglej spodaj).\n# operator povprečenja (verzija 1)\n# Zglajena slika v Matlabu ima pri meni moder odtenek. Nisem prepričan, če tako mora biti (tukaj odtenka ni).\nD = 3  # premer lokalne okolice piksla, na kateri se izračuna povprečna vrednost\nB = np.ndarray((A.shape[0] - D + 1, A.shape[1] - D + 1, D))\nfor r in np.arange(0, A.shape[0] - D).reshape(-1):\n    for c in np.arange(0, A.shape[1] - D).reshape(-1):\n        C = A[r + np.arange(0, D - 1), c + np.arange(0, D - 1), 0]\n        B[r, c, 0] = np.mean(np.ravel(C))\n        C = A[r + np.arange(0, D - 1), c + np.arange(0, D - 1), 1]\n        B[r, c, 1] = np.mean(np.ravel(C))\n        C = A[r + np.arange(0, D - 1), c + np.arange(0, D - 1), 2]\n        B[r, c, 2] = np.mean(np.ravel(C))\n\nplt.figure()\nplt.imshow(np.uint8(B))\nplt.title('zglajena slika')\n\n# ukazi.m:270 -- Note: Naslovi se prekrivajo.\n# operator povpreenja (verzija 2)\n# isti operator povprečenja kot zgoraj, implementiran nekoliko drugače (veliko hitreja izvedba)\nD = 3\nB = np.ndarray((A.shape[0] + D - 1, A.shape[1] + D - 1, D))\nB[:, :, 0] = scipy.signal.convolve2d(np.double(A[:, :, 0]), np.ones((D, D), np.float) / D ** 2)\nB[:, :, 1] = scipy.signal.convolve2d(np.double(A[:, :, 1]), np.ones((D, D), np.float) / D ** 2)\nB[:, :, 2] = scipy.signal.convolve2d(np.double(A[:, :, 2]), np.ones((D, D), np.float) / D ** 2)\nB = np.uint8(B)\nplt.figure()\nplt.imshow(B)\nplt.title('zglajena slika')\n\n# prikaz\npvz = 3  # faktor podvzorčenja\nplt.figure()\nplt.subplot(1, 2, 1)\nplt.imshow(A[0::pvz, 0::pvz, :])\nplt.title('podvzorčena slika: faktor podvzorčenja {0}'.format(pvz))\nplt.subplot(1, 2, 2)\nplt.imshow(B[1::pvz, 1::pvz, :])\nplt.title('zglajena podvzorena slika: faktor podvzorenja {0}'.format(pvz))\n", "meta": {"hexsha": "1c7d5badda32d6bbfd9a869ac3902a48cbdf6cd5", "size": 15384, "ext": "py", "lang": "Python", "max_stars_repo_path": "1-Vzorcenje/ukazi.py", "max_stars_repo_name": "LoremasterLH/MatlabToPython", "max_stars_repo_head_hexsha": "bdfd827d7fc143332e3945fc980e915c6324eb6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-05T12:55:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-20T11:00:43.000Z", "max_issues_repo_path": "1-Vzorcenje/ukazi.py", "max_issues_repo_name": "LoremasterLH/MatlabToPython", "max_issues_repo_head_hexsha": "bdfd827d7fc143332e3945fc980e915c6324eb6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1-Vzorcenje/ukazi.py", "max_forks_repo_name": "LoremasterLH/MatlabToPython", "max_forks_repo_head_hexsha": "bdfd827d7fc143332e3945fc980e915c6324eb6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-20T13:15:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-20T13:15:09.000Z", "avg_line_length": 35.776744186, "max_line_length": 131, "alphanum_fraction": 0.6224648986, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759489, "lm_q2_score": 0.920789679151471, "lm_q1q2_score": 0.874445756045476}}
{"text": "from sympy import *\nfrom rodrigues_R_utils import *\n\nksi_0, eta_0, c = symbols('ksi_0 eta_0 c');\npx, py, pz = symbols('px py pz')\nsx, sy, sz = symbols('sx sy sz')\ntie_px, tie_py, tie_pz = symbols('tie_px tie_py tie_pz'); \nksi_kp, eta_kp = symbols('ksi_kp eta_kp')\n\nposition_symbols = [px, py, pz]\nrodrigues_symbols = [sx, sy, sz]\ntie_point_symbols = [tie_px, tie_py, tie_pz]\nall_symbols = position_symbols + rodrigues_symbols + tie_point_symbols\n\nRT_wc = matrix44FromRodrigues(px, py, pz, sx, sy, sz)\nr=RT_wc[:-1,:-1]\nt=Matrix([px, py, pz]).vec()\n\ndenom=r[0,2]*(tie_px-t[0]) + r[1,2]*(tie_py-t[1]) + r[2,2]*(tie_pz-t[2])\nksi=ksi_0 - c * ( r[0,0]*(tie_px-t[0]) + r[1,0]*(tie_py-t[1]) + r[2,0]*(tie_pz-t[2]) ) /denom\neta=eta_0 - c * ( r[0,1]*(tie_px-t[0]) + r[1,1]*(tie_py-t[1]) + r[2,1]*(tie_pz-t[2]) ) /denom\n\nksi_delta = ksi_kp - ksi;\neta_delta = eta_kp - eta;\n\nobs_eq = Matrix([ksi_delta, eta_delta]).vec()\nobs_eq_jacobian = obs_eq.jacobian(all_symbols)\n\nprint(obs_eq)\nprint(obs_eq_jacobian)\n\nwith open(\"metric_camera_colinearity_rodrigues_wc_jacobian.h\",'w') as f_cpp:  \n    f_cpp.write(\"inline void observation_equation_metric_camera_colinearity_rodrigues_wc(Eigen::Matrix<double, 2, 1> &delta, double ksi_0, double eta_0, double c, double px, double py, double pz, double sx, double sy, double sz, double tie_px, double tie_py, double tie_pz, double ksi_kp, double eta_kp)\\n\")\n    f_cpp.write(\"{\")\n    f_cpp.write(\"delta.coeffRef(0,0) = %s;\\n\"%(ccode(obs_eq[0,0])))\n    f_cpp.write(\"delta.coeffRef(1,0) = %s;\\n\"%(ccode(obs_eq[1,0])))\n    f_cpp.write(\"}\")\n    f_cpp.write(\"\\n\")\n    f_cpp.write(\"inline void observation_equation_metric_camera_colinearity_rodrigues_wc_jacobian(Eigen::Matrix<double, 2, 9, Eigen::RowMajor> &j, double ksi_0, double eta_0, double c, double px, double py, double pz, double sx, double sy, double sz, double tie_px, double tie_py, double tie_pz, double ksi_kp, double eta_kp)\\n\")\n    f_cpp.write(\"{\")\n    for i in range (2):\n        for j in range (9):\n            f_cpp.write(\"j.coeffRef(%d,%d) = %s;\\n\"%(i,j, ccode(obs_eq_jacobian[i,j])))\n    f_cpp.write(\"}\")\n\n\n\n\n\n\n", "meta": {"hexsha": "428051de6d4ff36e8cc6dc65a31c3d6561c0fcdf", "size": 2100, "ext": "py", "lang": "Python", "max_stars_repo_path": "codes/metric_camera_colinearity_rodrigues_wc_jacobian.py", "max_stars_repo_name": "michalpelka/observation_equations", "max_stars_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "codes/metric_camera_colinearity_rodrigues_wc_jacobian.py", "max_issues_repo_name": "michalpelka/observation_equations", "max_issues_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/metric_camera_colinearity_rodrigues_wc_jacobian.py", "max_forks_repo_name": "michalpelka/observation_equations", "max_forks_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1764705882, "max_line_length": 329, "alphanum_fraction": 0.6780952381, "include": true, "reason": "from sympy", "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739075, "lm_q2_score": 0.9173026607161, "lm_q1q2_score": 0.8744417318465356}}
{"text": "import math\nimport numpy as np\n#-------------------------------------------------------------------------\n'''\n    Problem 2: User-based recommender systems\n    In this problem, you will implement a version of the recommender system using user-based method.\n    You could test the correctness of your code by typing `nosetests test2.py` in the terminal.\n'''\n\n#--------------------------\ndef cosine_similarity(RA, RB):\n    '''\n        compute the cosine similarity between user A and user B. \n        The similarity values between users are measured by observing all the items which have been rated by BOTH users. \n        If an item is only rated by one user, the item will not be involved in the similarity computation. \n        You need to first remove all the items that are not rated by both users from RA and RB. \n        If the two users don't share any item in their ratings, return 0. as the similarity.\n        Then the cosine similarity is < RA, RB> / (|RA|* |RB|). \n        Here <RA, RB> denotes the dot product of the two vectors (see here https://en.wikipedia.org/wiki/Dot_product). \n        |RA| denotes the L-2 norm of the vector RA (see here for example: http://mathworld.wolfram.com/L2-Norm.html). \n        For more details, see here https://en.wikipedia.org/wiki/Cosine_similarity.\n        Input:\n            RA: the ratings of user A, a float python vector of length m (the number of movies). \n                If the rating is unknown, the number is 0. For example the vector can be like [0., 0., 2.0, 3.0, 0., 5.0]\n            RB: the ratings of user B, a float python vector\n                If the rating is unknown, the number is 0. For example the vector can be like [0., 0., 2.0, 3.0, 0., 5.0]\n        Output:\n            S: the cosine similarity between users A and B, a float scalar value between -1 and 1.\n        Hint: you could use math.sqrt() to compute the square root of a number\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n    # assuming cosine(RA, RB) = P/(sqrt(NA)*sqrt(NB))\n\n    # loop through two lists\n\n        # if both users rated the item \n\n\n\n\n    # if the two user share no item in their ratings\n\n\n\n        # compute cosine similarity on the shared items \n\n    #########################################\n    return S \n\n\n#--------------------------\ndef find_users(R, i):\n    '''\n        find the all users who have rated the i-th movie.  \n        Input:\n            R: the rating matrix, a float numpy matrix of shape m by n. Here m is the number of movies, n is the number of users.\n                If a rating is unknown, the number is 0. \n            i: the index of the i-th movie, an integer python scalar (Note: the index starts from 0)\n        Output:\n            idx: the indices of the users, a python list of integer values \n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n    #########################################\n    return idx\n\n#--------------------------\ndef user_similarity(R, j, idx):\n    '''\n        compute the cosine similarity between a collection of users in idx list and the j-th user.  \n        Input:\n            R: the rating matrix, a float numpy matrix of shape m by n. Here m is the number of movies, n is the number of users.\n                If a rating is unknown, the number is 0. \n            j: the index of the j-th user, an integer python scalar (Note: the index starts from 0)\n            idx: a list of user indices, a python list of integer values \n        Output:\n            sim: the similarity between any user in idx list and user j, a python list of float values. It has the same length as idx.\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n\n\n\n\n\n    #########################################\n    return sim \n\n\n#--------------------------\ndef user_based_prediction(R, i_movie, j_user, K=5):\n    '''\n        Compute a prediction of the rating of the j-th user on the i-th movie using user-based approach.  \n        First we take all the users who have rated the i-th movie, and compute their similarities to the target user j. \n        If there is no user who has rated the i-th movie, predict 3.0 as the default rating.\n        From these users, we pick top K similar users. \n        If there are less than K users who has rated the i-th movie, use all these users.\n        We weight the user's ratings on i-th movie by the similarity between that user and the target user. \n        Finally, we rescale the prediction by the sum of similarities to get a reasonable value for the predicted rating.\n        Input:\n            R: the rating matrix, a float numpy matrix of shape m by n. Here m is the number of movies, n is the number of users.\n                If the rating is unknown, the number is 0. \n            i_movie: the index of the i-th movie, an integer python scalar\n            j_user: the index of the j-th user, an integer python scalar\n            K: the number of similar users to compute the weighted average rating.\n        Output:\n            p: the predicted rating of user j on movie i, a float scalar value between 1. and 5.\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n    # find all other users who have rated movie i.\n\n\n    # if there are less than K users who have rated the movie, change K to the number of users\n\n\n    # compute the similarity between all of these users with user j\n\n\n    # compute the weighted average of the top K similar users to user j\n\n\n\n\n\n\n\n\n\n\n\n\n\n    #########################################\n    return p \n\n\n#--------------------------\ndef compute_RMSE(ratings_pred, ratings_real):\n    '''\n        Compute the root of mean square error of the rating prediction.\n        Input:\n            ratings_pred: predicted ratings, a float python list\n            ratings_real: real ratings, a float python list\n        Output:\n            RMSE: the root of mean squared error of the predicted rating, a float scalar.\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n\n\n\n\n    #########################################\n    return RMSE\n\n\n\n#--------------------------\ndef load_rating_matrix(filename = 'movielens_train.csv'):\n    '''\n        Load the rating matrix from a CSV file.  In the CSV file, each line represents (user id, movie id, rating).\n        Note the ids start from 1 in this dataset.\n        Input:\n            filename: the file name of a CSV file, a string\n        Output:\n            R: the rating matrix, a float numpy array of shape m by n. Here m is the number of movies, n is the number of users.\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n\n\n\n\n\n\n\n\n    #########################################\n    return R\n\n\n#--------------------------\ndef load_test_data(filename = 'movielens_test.csv'):\n    '''\n        Load the test data from a CSV file.  In the CSV file, each line represents (user id, movie id, rating).\n        Note the ids in the CSV file start from 1. But the indices in u_ids and m_ids start from 0.\n        Input:\n            filename: the file name of a CSV file, a string\n        Output:\n            m_ids: the list of movie ids, an integer python list of length n. Here n is the number of lines in the test file. (Note indice should start from 0)\n            u_ids: the list of user ids, an integer python list of length n. \n            ratings: the list of ratings, a float python list of length n. \n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n\n\n\n    #########################################\n    return m_ids, u_ids, ratings\n\n\n#--------------------------\ndef movielens_user_based(train_file='movielens_train.csv', test_file ='movielens_test.csv', K = 5):\n    '''\n        Compute movie ratings in movielens dataset. Based upon the training ratings, predict all values in test pairs (movie-user pair).\n        In the training file, each line represents (user id, movie id, rating).\n        Note the ids start from 1 in this dataset.\n        Input:\n            train_file: the train file of the dataset, a string.\n            test_file: the test file of the dataset, a string.\n            K: the number of similar users to compute the weighted average rating.\n        Output:\n            RMSE: the root of mean squared error of the predicted rating, a float scalar.\n    Note: this function may take 1-5 minutes to run.\n    '''\n   \n    # load training set\n    R = load_rating_matrix(train_file)\n\n    # load test set\n    m_ids, u_ids,ratings_real = load_test_data(test_file)\n\n    # predict on test set\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n\n\n\n\n    #########################################\n    # compute RMSE \n    RMSE = compute_RMSE(ratings_pred,ratings_real)\n    return  RMSE \n\n\n", "meta": {"hexsha": "a5e1a1a7b4ca4c5f637efc5807f5d081484101c3", "size": 8844, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW3/problem2.py", "max_stars_repo_name": "aefernandez/DS501", "max_stars_repo_head_hexsha": "15799c8690c2f934d8e710db060e2b9e1b6afc8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW3/problem2.py", "max_issues_repo_name": "aefernandez/DS501", "max_issues_repo_head_hexsha": "15799c8690c2f934d8e710db060e2b9e1b6afc8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW3/problem2.py", "max_forks_repo_name": "aefernandez/DS501", "max_forks_repo_head_hexsha": "15799c8690c2f934d8e710db060e2b9e1b6afc8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8056680162, "max_line_length": 159, "alphanum_fraction": 0.5736092266, "include": true, "reason": "import numpy", "num_tokens": 1929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.975576914206421, "lm_q2_score": 0.8962513668985, "lm_q1q2_score": 0.8743621428721255}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# https://www.mathportal.org/calculators/statistics-calculator/standard-deviation-calculator.php\n\nimport numpy as np \n\ndef print_this_matrix(given_matrix):\n  for i in range(len(given_matrix)):\n   for j in range(len(given_matrix[i])):\n    print (given_matrix[i][j],\" \",end=\"\")\n   print()\n  print(\"\\n\")\n\narr_extreme = np.array([[ 4,   5,  6,   7],\n                        [ 3,  -1, -2,  -3],\n                        [ 8,   9,  10,  11],\n                        [12,   13, 14,  15]])\nprint(\"np.ptp() -- difference between max and min\")\nprint(\"np.ptp(arr_extreme)                     --->\",np.ptp(arr_extreme))\nprint(\"np.ptp(arr_extreme, axis=0)--vertical   --->\",np.ptp(arr_extreme, axis=0))\nprint(\"np.ptp(arr_extreme, axis=1)--horizontal --->\",np.ptp(arr_extreme, axis=1))\n\nprint(\"np.percentile() -- percentitle of sum of given range of values\")\nprint(\"np.percentile(arr_extreme)                     --->\",np.percentile(arr_extreme,10))        # 10% of the total values \nprint(\"np.percentile(arr_extreme, axis=0)--vertical   --->\",np.percentile(arr_extreme,10,axis=0)) # 10% of the total values\nprint(\"np.percentile(arr_extreme, axis=1)--horizontal --->\",np.percentile(arr_extreme,10,axis=1)) # 10% of the total values\n\nprint(\"np.mean() -- mean = 50% percentile\")\nprint(\"np.mean(arr_extreme)                     --->\",np.mean(arr_extreme))\nprint(\"np.mean(arr_extreme, axis=0)--vertical   --->\",np.mean(arr_extreme, axis=0))\nprint(\"np.mean(arr_extreme, axis=1)--horizontal --->\",np.mean(arr_extreme, axis=1))\n\nprint(\"np.median() -- middle number or avg of the middle 2 numbers\")\nprint(\"np.median(arr_extreme)                     --->\",np.median(arr_extreme))\nprint(\"np.median(arr_extreme, axis=0)--vertical   --->\",np.median(arr_extreme, axis=0))\nprint(\"np.median(arr_extreme, axis=1)--horizontal --->\",np.median(arr_extreme, axis=1))\n\nprint(\"np.average(arr_extreme)                     --->\",np.average(arr_extreme))\nprint(\"np.std(arr_extreme)    standard deviation   --->\",np.std(arr_extreme))\nprint(\"np.var(arr_extreme)    variance             --->\",np.var(arr_extreme))\nprint(\"\\n\")\n\narr_extreme = np.array([[ 4,   5,  6,   7],\n                        [ 3,  -1, -2,  -3],\n                        [ 8,   9,  10,  11],\n                        [12,   13, 14,  15]])\nprint_this_matrix(arr_extreme)\nprint(\"np.amin(arr_extreme)                    --->\",np.amin(arr_extreme))\nprint(\"np.amin(arr_extreme, axis=0)--vertical  --->\",np.amin(arr_extreme, axis=0))\nprint(\"np.amin(arr_extreme, axis=1)--horizontal--->\",np.amin(arr_extreme, axis=1))\nprint(\"just index of sorted element\")\narr_extreme.flatten()\nprint(\"np.argmin(arr_extreme, axis=1)--horizontal--->\",np.argmin(arr_extreme, axis=1))\n\n\nfrom scipy import stats\n\narr_extreme = np.array([[ 4,   5,  6,   7],\n                        [ 3,  -1, -2,  -3],\n                        [ 8,   9,  10,  11],\n                        [12,   13, 14,  15]])\n\nstats.describe(arr_extreme)\n", "meta": {"hexsha": "691c5506add195cea2df9184b8f6cf662a9f05fc", "size": 2965, "ext": "py", "lang": "Python", "max_stars_repo_path": "prg02_basic_statisticks/basic_statistics01.py", "max_stars_repo_name": "imademethink/MachineLearning_related_Python", "max_stars_repo_head_hexsha": "c7fd22d2d878d110e0a7bf679103a226952164e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prg02_basic_statisticks/basic_statistics01.py", "max_issues_repo_name": "imademethink/MachineLearning_related_Python", "max_issues_repo_head_hexsha": "c7fd22d2d878d110e0a7bf679103a226952164e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prg02_basic_statisticks/basic_statistics01.py", "max_forks_repo_name": "imademethink/MachineLearning_related_Python", "max_forks_repo_head_hexsha": "c7fd22d2d878d110e0a7bf679103a226952164e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6153846154, "max_line_length": 124, "alphanum_fraction": 0.5851602024, "include": true, "reason": "import numpy,from scipy", "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992942089574, "lm_q2_score": 0.9032942151647513, "lm_q1q2_score": 0.8742978333209969}}
{"text": "import numpy as np\n\n\ndef riemann_sum(f, a, b, N: int, method='midpoint'):\n    '''\n    Compute the Riemann sum of f(x) over the interval [a,b].\n\n    Parameters\n    ----------\n    f : function\n        Vectorized function of one variable\n    a , b : numbers\n        Endpoints of the interval [a,b]\n    N : integer\n        Number of subintervals of equal length in the partition of [a,b]\n    method : string\n        Determines the kind of Riemann sum:\n        right : Riemann sum using right endpoints\n        left : Riemann sum using left endpoints\n        midpoint (default) : Riemann sum using midpoints\n\n    Returns\n    -------\n    float\n        Approximation of the integral given by the Riemann sum.\n    '''\n    dx = (b - a)/N\n    x = np.linspace(a, b, N+1)\n\n    # left riemann sum\n    if method == 'left':\n        x_left = x[:-1]\n        return np.sum(f(x_left)*dx)\n\n    # right reimann sum\n    elif method == 'right':\n        x_right = x[1:]\n        return np.sum(f(x_right)*dx)\n\n    # midpoint reimann sum\n    elif method == 'midpoint':\n        x_mid = (x[:-1] + x[1:])/2\n        return np.sum(f(x_mid)*dx)\n    else:\n        raise ValueError(\"Method must be 'left', 'right' or 'midpoint'.\")\n\n\n# example problems\n\n# 1\nf = np.sin\nr_sum = riemann_sum(f, 0, np.pi/2, 100)\nright_r_sum = riemann_sum(f, 0, np.pi/2, 100, 'right')\nleft_r_sum = riemann_sum(f, 0, np.pi/2, 100, 'left')\nprint(f\"\"\"Sin(x) in the interval [0,pi/2] partition with 100 sub-intervals\nLeft Riemann Sum: {left_r_sum}\nMidpoint Riemann Sum: {r_sum}\nRight Riemann Sum: {right_r_sum}\"\"\")\n\n\n# 2\nf = lambda x : 1 / (1 + x**2)\nr_sum = riemann_sum(f, 0, 5, 10)\nright_r_sum = riemann_sum(f, 0, 5, 10, 'right')\nleft_r_sum = riemann_sum(f, 0, 5, 10, 'left')\nprint(f\"\"\"\n1/(1+x^2) in the interval [0,5] partition with 10 sub-intervals\nLeft Riemann Sum: {left_r_sum}\nMidpoint Riemann Sum: {r_sum}\nRight Riemann Sum: {right_r_sum}\"\"\")\n", "meta": {"hexsha": "c9e0f4b85564266b0f0b24fdc9b3a402f38785b4", "size": 1890, "ext": "py", "lang": "Python", "max_stars_repo_path": "Maths_And_Stats/Calculus/Riemann_Sum/riemann_sum.py", "max_stars_repo_name": "arslantalib3/algo_ds_101", "max_stars_repo_head_hexsha": "a1293f407e00b8346f93e8770727f769e7add00e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 182, "max_stars_repo_stars_event_min_datetime": "2020-10-01T17:16:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T17:52:49.000Z", "max_issues_repo_path": "Maths_And_Stats/Calculus/Riemann_Sum/riemann_sum.py", "max_issues_repo_name": "arslantalib3/algo_ds_101", "max_issues_repo_head_hexsha": "a1293f407e00b8346f93e8770727f769e7add00e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 759, "max_issues_repo_issues_event_min_datetime": "2020-10-01T00:12:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T19:35:11.000Z", "max_forks_repo_path": "Maths_And_Stats/Calculus/Riemann_Sum/riemann_sum.py", "max_forks_repo_name": "arslantalib3/algo_ds_101", "max_forks_repo_head_hexsha": "a1293f407e00b8346f93e8770727f769e7add00e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1176, "max_forks_repo_forks_event_min_datetime": "2020-10-01T16:02:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T19:20:19.000Z", "avg_line_length": 26.6197183099, "max_line_length": 74, "alphanum_fraction": 0.6111111111, "include": true, "reason": "import numpy", "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992932829917, "lm_q2_score": 0.9032942119105695, "lm_q1q2_score": 0.8742978293348571}}
{"text": "import numpy as np\nimport math\n\n\ndef poisson_lambda_mle(d):\n    \"\"\"\n    Computes the Maximum Likelihood Estimate for a given 1D training\n    dataset from a Poisson distribution.\n    \n    \"\"\"\n    return sum(d) / len(d)\n\ndef likelihood_poisson(x, lam):\n    \"\"\"\n    Computes the class-conditional probability for an univariate\n    Poisson distribution\n    \n    \"\"\"\n    if x // 1 != x:\n        likelihood = 0\n    else:\n        likelihood = math.e**(-lam) * lam**(x) / math.factorial(x)\n    return likelihood\n\n\nif __name__ == \"__main__\":\n\n    # Plot Probability Density Function\n    from matplotlib import pyplot as plt\n\n    training_data = [0, 1, 1, 3, 1, 0, 1, 2, 1, 2, 2, 1, 2, 0, 1, 4]\n    mle_poiss =  poisson_lambda_mle(training_data)\n    true_param = 1.0\n\n    x_range = np.arange(0, 5, 0.1)\n    y_true = [likelihood_poisson(x, true_param) for x in x_range]\n    y_mle = [likelihood_poisson(x, mle_poiss) for x in x_range]\n\n    plt.figure(figsize=(10,8))\n    plt.plot(x_range, y_true, lw=2, alpha=0.5, linestyle='--', label='true parameter ($\\lambda={}$)'.format(true_param))\n    plt.plot(x_range, y_mle, lw=2, alpha=0.5, label='MLE ($\\lambda={}$)'.format(mle_poiss))\n    plt.title('Poisson probability density function for the true and estimated parameters')\n    plt.ylabel('p(x|theta)')\n    plt.xlim([-1,5])\n    plt.xlabel('random variable x')\n    plt.legend()\n\n    plt.show()\n", "meta": {"hexsha": "30d3ae4c70af131df7d52adb69f67024302cbdf9", "size": 1379, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_reference/useful_scripts/univariate_poisson_pdf.py", "max_stars_repo_name": "gopala-kr/ds-notebooks", "max_stars_repo_head_hexsha": "bc35430ecdd851f2ceab8f2437eec4d77cb59423", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-10T09:16:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-10T09:16:23.000Z", "max_issues_repo_path": "python_reference/useful_scripts/univariate_poisson_pdf.py", "max_issues_repo_name": "gopala-kr/ds-notebooks", "max_issues_repo_head_hexsha": "bc35430ecdd851f2ceab8f2437eec4d77cb59423", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python_reference/useful_scripts/univariate_poisson_pdf.py", "max_forks_repo_name": "gopala-kr/ds-notebooks", "max_forks_repo_head_hexsha": "bc35430ecdd851f2ceab8f2437eec4d77cb59423", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-14T07:30:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T07:30:18.000Z", "avg_line_length": 28.1428571429, "max_line_length": 120, "alphanum_fraction": 0.6403190718, "include": true, "reason": "import numpy", "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.967899289579129, "lm_q2_score": 0.903294212561406, "lm_q1q2_score": 0.8742978266191236}}
{"text": "import numpy as np\nimport math\nfrom math import sqrt\n#float_percision = '{:.4f}'.format\n#np.set_printoptions(formatter={'float_kind':float_percision})\n\ndef decomp_cholesky(A):\n\n    n = len(A)\n    L = np.zeros((n, n))\n\n    for i in range(n):\n\n        for j in range(i+1):\n\n            L[i][j] = A[i][j]\n\n            for k in range(j):\n\n                L[i][j] -= L[i][k]*L[j][k]\n\n            if(i == j):\n\n                L[i][j] = sqrt(L[j][j])\n\n            else:\n\n                L[i][j] /= L[j][j]\n\n    return L\n\n\ndef solve_lower(L, b):\n\n    n = len(L)\n    y = np.copy(b)\n\n    y[0] = b[0] / L[0][0]\n\n    for i in range(1, n):\n\n        for j in range(i):\n\n            y[i] -= L[i][j]*y[j]\n\n        y[i] /= L[i][i]\n\n    return y\n         \n\ndef solve_upper(U, y):\n\n    n = len(U)\n    x = np.copy(y)\n\n    for i in range(n-1, -1, -1):\n\n        for j in range(i+1, n):\n\n            x[i] -= U[j][i]*x[j]\n\n        x[i] /= U[i][i]\n\n    return x\n    \n\ndef solve_cholesky(L,b):\n\n    y = solve_lower(L,b)\n    x = solve_upper(L,y)\n\n    return x\n\n\nif __name__ == '__main__':\n\n\tN = 1000\n\tprint('N = ', N)\n\n\t#Filling N*N array to initialize it\n\tA1 = np.zeros((N,N), float)\n\tA2 = np.zeros((N,N), float)\n\n\tb1 = np.zeros(N, float)\n\tb2 = np.ones(N, float) \n\n\t#Fill arrays with the correspondant values\n\tnp.fill_diagonal(A1, 6)\n\tnp.fill_diagonal(A1[1:], -4)\n\tnp.fill_diagonal(A1[:, 1:], -4)\n\tnp.fill_diagonal(A1[2:], 1)\n\tnp.fill_diagonal(A1[:, 2:], 1)\n\n\tnp.fill_diagonal(A2, 7)\n\tnp.fill_diagonal(A2[1:], -4)\n\tnp.fill_diagonal(A2[:, 1:], -4)\n\tnp.fill_diagonal(A2[2:], 1)\n\tnp.fill_diagonal(A2[:, 2:], 1)\n\n\tb1[0] = 3\n\tb1[1] = -1\n\tb1[-2] = -1\n\tb1[-1] = 3\n\n\tb2[0] = 4\n\tb2[1] = 0\n\tb2[-2] = 0\n\tb2[-1] = 4\n\n\tL = decomp_cholesky(A1)\n\tx = solve_cholesky(L, b1)\n\n\tprint('A1 x = b1 \\n Ten median x are:')\n\n\tml = len(x) // 2 - 5\n\tmu = len(x) // 2 + 5\n\n\tprint(x[ml : mu])\n\n\tL = decomp_cholesky(A2)\n\tx = solve_cholesky(L, b2)\n\n\tprint('A2 x = b2 \\n Ten median x are:')\n\n\tml = len(x) // 2 - 5\n\tmu = len(x) // 2 + 5\n\n\tprint(x[ml : mu])\n", "meta": {"hexsha": "aa3d49f10158f29c6271b4c5b41ef7536a8c92bf", "size": 1998, "ext": "py", "lang": "Python", "max_stars_repo_path": "cholesky.py", "max_stars_repo_name": "ioannapap/cholesky", "max_stars_repo_head_hexsha": "0f4054fe0577aff5e5b76ad05bd14541138a650f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cholesky.py", "max_issues_repo_name": "ioannapap/cholesky", "max_issues_repo_head_hexsha": "0f4054fe0577aff5e5b76ad05bd14541138a650f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cholesky.py", "max_forks_repo_name": "ioannapap/cholesky", "max_forks_repo_head_hexsha": "0f4054fe0577aff5e5b76ad05bd14541138a650f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.488372093, "max_line_length": 62, "alphanum_fraction": 0.496996997, "include": true, "reason": "import numpy", "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075733703927, "lm_q2_score": 0.9086179018818865, "lm_q1q2_score": 0.8741881647004793}}
{"text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np\nimport csv\nfrom numpy import cov\nfrom numpy.linalg import eig\nimport matplotlib.pyplot as plt\n\ndef PCA(filename = \"\",topk = 0, graph=True):\n\n\tif len(filename) == 0:\n\t\tprint(\"Error: File not provided!\")\n\t\treturn\n\n\tdata = []\n\tlabel = []\n\twith open(filename) as datafile:\n\t\treader = csv.reader(datafile,delimiter=\",\")\n\t\tnext(reader)\n\t\tfor row in reader:\n\t\t\t\n\t\t\t# data.append(list(map(float,row[2:])))\n\t\t\tfloat_row = []\n\t\t\tfor value in row[2:]:\n\t\t\t\ttry:\n\t\t\t\t\tvalue = float(value)\n\t\t\t\t\tfloat_row.append(value)\n\n\t\t\t\texcept ValueError:\n\t\t\t\t\tfloat_row.append(0.0)\t\t\t\t\t\n\t\t\tdata.append(float_row)\n\t\t\tlabel.append(row[1])\n\n\tdata_mat = np.asarray(data)\n\n\ttotalDims = data_mat.shape[-1]\n\n\tif topk > totalDims or topk < 0:\n\t\tprint(\"Invalid value for topk!\")\n\t\treturn\n\n\t\n\tcentered_mat = data_mat - np.mean(data_mat.T, axis=1)\n\t\n\tvalues, vectors = eig(cov(centered_mat.T))\n\tindices = np.argpartition(values, -topk)[-topk:]\n\n\tmax_variance_vectors = []\n\tfor index in indices:\n\t\tmax_variance_vectors.append(vectors[index])\n\n\tmax_variance_vectors = np.asarray(max_variance_vectors)\n\tprojected_mat = max_variance_vectors.dot(centered_mat.T)\n\n\tif graph:\n\t\tfig = plt.figure()\n\t\tfig.suptitle('PCA on '+filename, fontsize=14, fontweight='bold')\n\t\tax = fig.add_subplot(111)\n\t\tax.set_xlabel(\"PC1\")\n\t\tax.set_ylabel(\"PC2\")\n\t\tax.scatter(projected_mat[0],projected_mat[1])\n\t\t# for i, txt in enumerate(label):\n\t\t# \tax.annotate(txt, (projected_mat[0], projected_mat[1]))\t\t\n\t\tplt.show()\n\n\treturn projected_mat.T\n", "meta": {"hexsha": "c691437e1dc8668ead4185333831d700d037af39", "size": 1647, "ext": "py", "lang": "Python", "max_stars_repo_path": "pcapkg.py", "max_stars_repo_name": "sharababy/pca_pkg", "max_stars_repo_head_hexsha": "7cd7d8b8625aa03675bb2fd6704884f739966653", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcapkg.py", "max_issues_repo_name": "sharababy/pca_pkg", "max_issues_repo_head_hexsha": "7cd7d8b8625aa03675bb2fd6704884f739966653", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcapkg.py", "max_forks_repo_name": "sharababy/pca_pkg", "max_forks_repo_head_hexsha": "7cd7d8b8625aa03675bb2fd6704884f739966653", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5285714286, "max_line_length": 66, "alphanum_fraction": 0.7067395264, "include": true, "reason": "import numpy,from numpy", "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075744568837, "lm_q2_score": 0.908617890746506, "lm_q1q2_score": 0.8741881549742506}}
{"text": "import numpy as np \nfrom scipy.stats import multivariate_normal\nimport pdb\n\n\nclass MultivariateGaussianData:\n    \"\"\" Class for generating data from a multivariate Gaussian distibution \n    (Z, X) ~ N(mu, Sigma), where Z is considered the latent variable and X the observation, \n    such that Z ~ N(0, I) and X|Z=z ~ N(Wz + b, Sigma_x)\n    ------------------\n    Parameters:\n              dim_x : dimension of X\n              dim_z : dimension of Z\n    ------------------\n    Methods:\n            create_dataset : generate n_samples observations X ~ N(mu_x, Sigma_x)\n            compute_posterior : return p(Z|X=x), mean and covariance of Z|X=x\n            compute_log_likelihood : return mean(log(p(x))) across the given dataset\n    \"\"\"\n\n    def __init__(self, dim_x, dim_z):\n        np.random.seed(0)\n        self.n_x = dim_x\n        self.n_z = dim_z\n        \n        # z ~ N(0, I):\n        self.sigma_z = np.eye(dim_z)\n        self.mu_z = np.zeros(dim_z)\n\n        # X|Z=z ~ N(Wz+b, Sigma_x_z)\n        self.W = np.random.normal(0, 1, size=(dim_x, dim_z))\n        self.b = np.random.normal(0, 1, dim_x)\n        aux_sigma = np.random.normal(0, 1, size=(dim_x, dim_x))\n        self.sigma_x_z = np.dot(aux_sigma, aux_sigma.T) + 0.5 * np.eye(dim_x)\n        \n        # Cholesky factor of the covariance of the observed variable X (needed for sampling)\n        self.chol_sigma_x_z = np.linalg.cholesky(self.sigma_x_z)\n\n        # X + N(b, W*W^T + Sigma_x, z)\n        self.sigma_x = np.dot(self.W, self.W.T) + self.sigma_x_z\n   \n\n    def create_dataset(self, n_samples):\n        \"\"\" Sample n_samples from X ~ N(mu_x, Sigma_x), generated by first sampling from Z\n        \"\"\"\n        z = np.random.normal(0, 1, size=(n_samples, self.n_z))\n        eps = np.random.normal(0, 1, size=(n_samples, self.n_x))\n        data = np.dot(z, self.W.T) + self.b + np.dot(eps, self.chol_sigma_x_z)\n        return data \n\n\n    def compute_posterior(self, x, z):\n        \"\"\" Compute the posterior and its parameters: p(z|x), mu_z_x, sigma_z_x\n        \"\"\"\n        solver = np.linalg.solve(self.sigma_x, x - self.b)\n        mu_z_x = self.mu_z + np.dot(self.W.T, solver)\n        sigma_z_x = self.sigma_z - np.dot(self.W.T, np.dot(np.linalg.inv(self.sigma_x), self.W))\n        pdf = multivariate_normal.pdf(z, mu_z_x, sigma_z_x)\n        return pdf, mu_z_x, sigma_z_x\n \n\n    def compute_log_likelihood(self, x):\n        \"\"\" True log likelihood of the data\n        \"\"\"\n        p_x = multivariate_normal.pdf(x, self.b, self.sigma_x)\n        return np.mean(np.log(p_x))\n\n\ndef load(n_x, n_z, n_samples_train, n_samples_test):\n    data = {}\n    multivarGaussData = MultivariateGaussianData(n_x, n_z)\n    generatedX = multivarGaussData.create_dataset(n_samples_train + n_samples_test)\n    data[\"gaussian_class\"] = multivarGaussData\n    data[\"train_set_x\"] = generatedX[:n_samples_train]\n    data[\"test_set_x\"] = generatedX[n_samples_train:]\n    data[\"n_samples_train\"] = n_samples_train\n    data[\"n_samples_test\"] = n_samples_test\n    data[\"input_size\"] = n_x\n    data[\"binary\"] = 0\n    return data\n\n\nif __name__=='__main__':\n    opts = {\"n_x\": 10,\n            \"n_z\": 2,\n            \"n_train\": 500,\n            \"n_test\" : 50,\n            \"n_samples\": 5,\n            \"n_samples_is\": 10,\n            \"n_epochs\": 100,\n            \"period\" : 10,\n            \"alpha\": 0.9,\n            \"learning_rate\": 0.0001}\n\n    data = load(opts[\"n_x\"], opts[\"n_z\"], opts[\"n_train\"], opts[\"n_test\"])\n    # pdb.set_trace()\n", "meta": {"hexsha": "8166cc0962db00a1eb5b0ee717a8bb601afddd72", "size": 3464, "ext": "py", "lang": "Python", "max_stars_repo_path": "datasets/syn_multivar_gaussian.py", "max_stars_repo_name": "rist-ro/argo", "max_stars_repo_head_hexsha": "a10c33346803239db8a64c104db7f22ec4e05bef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-07T19:13:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T18:52:18.000Z", "max_issues_repo_path": "datasets/syn_multivar_gaussian.py", "max_issues_repo_name": "rist-ro/argo", "max_issues_repo_head_hexsha": "a10c33346803239db8a64c104db7f22ec4e05bef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-09-25T22:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:46:34.000Z", "max_forks_repo_path": "datasets/syn_multivar_gaussian.py", "max_forks_repo_name": "rist-ro/argo", "max_forks_repo_head_hexsha": "a10c33346803239db8a64c104db7f22ec4e05bef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-02T18:31:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-02T21:56:43.000Z", "avg_line_length": 35.7113402062, "max_line_length": 96, "alphanum_fraction": 0.5964203233, "include": true, "reason": "import numpy,from scipy", "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075733703927, "lm_q2_score": 0.9086178888906091, "lm_q1q2_score": 0.8741881522014731}}
{"text": "import numpy as np\n\ndef sigmoid(z):\n    return 1.0/(1.0 + np.exp(-z))\n\ndef sigmoid_prime(z):\n    return sigmoid(z)*(1-sigmoid(z))\n\ndef tanh(z):\n    return ((2 / (1 + np.exp(-2*z))) + 1)\n\ndef tanh_prime(z):\n    return 1 - tanh(z)**2\n\ndef relu(z):\n    def comp(x):\n        if (x > 0):\n            return x\n        else:\n            return 0\n    return np.array([comp(i) for i in z])\n\ndef relu_prime(z):\n    def comp(x):\n        if (x <= 0):\n             return 0\n        elif (x > 0):\n            return 1\n\n    return np.array([comp(i) for i in z])\n\ndef leaky_relu(z):\n    def comp(x):\n        if (x < 0):\n            return 0.1*x\n        elif (x >= 0):\n            return x\n    return np.array([comp(i) for i in z])\n\ndef leaky_relu_prime(z):\n    def comp(x):\n        if (x < 0):\n            return 0.1\n        elif (x >= 0):\n            return 1\n    return np.array([comp(i) for i in z])\n\ndef elu(z):\n    alpha = 1\n    def comp(x):\n        if (x > 0):\n            return x\n        elif (x <= 0):\n            return alpha*(np.exp(x) - 1)\n    return np.array([comp(i) for i in z])\n\ndef elu_prime(z):\n    alpha = 1\n    def comp(x):\n        if (x > 0):\n            return 1\n        elif (x <= 0):\n            return alpha*np.exp(x)\n    return np.array([comp(i) for i in z])\n\ndef softmax(z):\n    return np.exp(z)/sum(np.exp(z))\n\ndef softmax_prime(z):\n    #this is the diagonal of the jacobian.\n    return softmax(z)*(1-softmax(z))\n\ndef softmax_input_change(z):\n    dz_da = np.zeros((z.shape[0], z.shape[0]))\n    for i in range(len(z)):\n        tmp = []\n        if (z[i] == 0):\n            for j in z:\n                if (j == 0):\n                    tmp.append(0)\n                else:\n                    tmp.append(-1)\n        else:\n            for j in range(len(z)):\n                if (i == j):\n                    tmp.append(1)\n                else:\n                    tmp.append(0)\n\n        dz_da[:,i] += np.array(tmp)\n\n    return dz_da.diagonal()\n\ndef func_dict(order):\n    if (order == 0):\n        dict = {\n            \"sigmoid\": sigmoid,\n            \"relu\": relu,\n            \"l_relu\": leaky_relu,\n            \"tanh\": tanh,\n            \"elu\": elu,\n        }\n    elif (order == 1):\n        dict = {\n            \"sigmoid\": sigmoid_prime,\n            \"relu\": relu_prime,\n            \"l_relu\": leaky_relu_prime,\n            \"tanh\": tanh_prime,\n            \"elu\": elu_prime,\n            \"softmax\": softmax_prime,\n        }\n    return dict\n", "meta": {"hexsha": "6e6f3f6485ab94ad16427f38c8277a00e95f7b34", "size": 2439, "ext": "py", "lang": "Python", "max_stars_repo_path": "perceptron/activation_functions.py", "max_stars_repo_name": "lstefanello/perceptron", "max_stars_repo_head_hexsha": "4d411e69972da0c39249cce7bd191f84555ce550", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "perceptron/activation_functions.py", "max_issues_repo_name": "lstefanello/perceptron", "max_issues_repo_head_hexsha": "4d411e69972da0c39249cce7bd191f84555ce550", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "perceptron/activation_functions.py", "max_forks_repo_name": "lstefanello/perceptron", "max_forks_repo_head_hexsha": "4d411e69972da0c39249cce7bd191f84555ce550", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5840707965, "max_line_length": 46, "alphanum_fraction": 0.4444444444, "include": true, "reason": "import numpy", "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551505674444, "lm_q2_score": 0.9059898140375993, "lm_q1q2_score": 0.8741489384358188}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep  5 22:11:24 2018\n\n@author: chen jin\n\nNon-Linear Least-Squares Fitting: solve a curve fitting problem using robust \nloss function to take care of outliers in the data. Define the model function \nas y = a + b * exp(c * x), where t is a predictor variable, y is an observation\nand a, b, c are parameters to estimate.\nPut all coefficients in beta, this could be write as:\n    y = beta[0] + beta[1] * exp(beta[2] * x)\n    \nInput:\n    target function: y = a + b * np.exp(x * c)\n    x_train linspace generated\n    y_train generated with noise and outliers\n    par: parameters (a, b, c) of target function\n    loss_fun: loss or residual function (simple f(x) - y used here) \n    beta: initial guess of parameters (a, b, c)\n    \nOutput:\n    res_lsq: standard least-squares solution with beta = [*res_lsq.x]\n    res_soft_l1: robust soft_11 solution with beta = [*res_soft_l1.x]\n    res_log: robust cauchy solution with beta = [*res_log.x]\n\"\"\"\n\nimport numpy as np\nfrom scipy.optimize import least_squares\nimport matplotlib.pyplot as plt\n\n# First, define the function which generates the data with noise and outliers, \n# define the model parameters with default setting in par\n\ndef gen_data(x, par = [0.5, 2, -1], noise=0, n_outliers=0, random_state=0):\n    \n    a, b, c = par[0], par[1], par[2]\n    y = a + b * np.exp(x * c)\n\n    rnd = np.random.RandomState(random_state)\n    error = noise * rnd.randn(x.size)\n    outliers = rnd.randint(0, x.size, n_outliers)\n    error[outliers] *= 10\n\n    return y + error\n\n# generate data\nx_train = np.linspace(0, 10, 15)\npar = [0.5, 2, -1]\ny_train = gen_data(x_train, par, noise=0.1, n_outliers=3)\n\n# Define function for computing Loss (residuals)\ndef loss_fun(beta, x, y):\n    return beta[0] + beta[1] * np.exp(beta[2] * x) - y\n\n# initial estimate of parameters\nbeta = np.array([1.0, 1.0, 0.0])\n\n# Compute a standard least-squares solution\nres_lsq = least_squares(loss_fun, beta, args=(x_train, y_train))\n\n# compute two solutions with two different robust loss functions. \n# The parameter f_scale is set to 0.1, meaning that inlier residuals \n# should not significantly exceed 0.1 (the noise level used)\n\nres_soft_l1 = least_squares(loss_fun, beta, loss='soft_l1', f_scale=0.1,\n                            args=(x_train, y_train))\nres_log = least_squares(loss_fun, beta, loss='cauchy', f_scale=0.1,\n                        args=(x_train, y_train))\n\n# plot all curves\nx_test = np.linspace(0, 10, 15 * 10)\ny_true = gen_data(x_test, par)\ny_lsq = gen_data(x_test, [*res_lsq.x])\ny_soft_l1 = gen_data(x_test, [*res_soft_l1.x])\ny_log = gen_data(x_test, [*res_log.x])\n\nplt.plot(x_train, y_train, 'o')\nplt.plot(x_test, y_true, 'k', linewidth=2, label='true')\nplt.plot(x_test, y_lsq, label='linear loss')\nplt.plot(x_test, y_soft_l1, label='soft_l1 loss')\nplt.plot(x_test, y_log, label='cauchy loss')\nplt.xlabel(\"t\")\nplt.ylabel(\"y\")\nplt.legend()\nplt.show()", "meta": {"hexsha": "9666dc9ebebc0de701ecd1617ba3bfd679fd381e", "size": 2919, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/NonLinearLeastSquaresFitting.py", "max_stars_repo_name": "nifex007/Numerical-Analysis-Examples", "max_stars_repo_head_hexsha": "18e7fda49e6138a90a8dc9d0af56aa039b05d69f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 389, "max_stars_repo_stars_event_min_datetime": "2016-03-03T19:47:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T13:48:35.000Z", "max_issues_repo_path": "Python/NonLinearLeastSquaresFitting.py", "max_issues_repo_name": "nifex007/Numerical-Analysis-Examples", "max_issues_repo_head_hexsha": "18e7fda49e6138a90a8dc9d0af56aa039b05d69f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2016-05-15T20:52:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-01T01:46:25.000Z", "max_forks_repo_path": "Python/NonLinearLeastSquaresFitting.py", "max_forks_repo_name": "nifex007/Numerical-Analysis-Examples", "max_forks_repo_head_hexsha": "18e7fda49e6138a90a8dc9d0af56aa039b05d69f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 84, "max_forks_repo_forks_event_min_datetime": "2016-03-03T19:51:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T07:54:26.000Z", "avg_line_length": 33.9418604651, "max_line_length": 79, "alphanum_fraction": 0.6834532374, "include": true, "reason": "import numpy,from scipy", "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970687770944576, "lm_q2_score": 0.9005297961287783, "lm_q1q2_score": 0.8741332604734172}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Realisation of Multivariate Linear Regression powered by pure Numpy.\nInspired by Machine Learning class from Andrew Ng at Coursera.\n@see https://www.coursera.org/learn/machine-learning\n\nFAQ:\n- Linear Regression model looks like: y = theta0 + theta1*x1 + theta2*x2 ... thetan*xn\n- We try to find theta parameters\n- We use Gradient Descent for that\n- It is very handful do np.seterr(all='raise') before using this module, to stop on any errors and avoid further\ncalculations that already wrong\n\"\"\"\nimport numpy as np\n\n\ndef compute_cost(x: np.ndarray, y: np.ndarray, theta: np.ndarray) -> float:\n    \"\"\"Calculate and return cost function value (float scalar), based on given training set x, expected outcomes y and\n    theta\n\n    If x.shape = (m, n), then y.shape must be (m, 1) and theta.shape must be (1, n)\n\n    :param x: set of features\n    :param y: set of training examples\n    :param theta: parameters of linear regression function\n    \"\"\"\n    m = len(y)  # number of training examples\n    return np.ndarray.item(sum(np.square(x @ theta - y)) / (2 * m))\n\n\ndef gradient_descent(x: np.ndarray, y: np.ndarray, theta: np.ndarray, alpha: float, num_iters: int) \\\n        -> (np.ndarray, np.ndarray):\n    \"\"\"Straitforward (unoptimized) version of Gradient Descent. Applies num_iters iterations with learning rate alpha\n    and returns tuple (theta, J_history) with finded theta and history of values of the cost function J_history\n\n    If x.shape = (m, n), then y.shape must be (m, 1) and theta.shape must be (1, n)\n\n    :param x: set of features\n    :param y: set of training examples\n    :param theta: parameters of linear regression function\n    :param alpha: learning rate alpha (size of the one step of gradient descent)\n    :param num_iters: number of iterations for gradient descent\n    :return: a tuple (theta, J_historu), where theta is sought-for parameter of Linear Regression Model,\n        J_history - is an array of cost function values over iterations\n    \"\"\"\n    m = len(y)  # number of training examples\n    n = x.shape[1]  # number of features\n    j_history = np.zeros(shape=(num_iters, 1))\n    for i in range(num_iters):\n        for j in range(n):\n            # np.multiply is the element-wise multiplication\n            theta[j, 0] = theta[j, 0] - alpha * sum(np.multiply(x @ theta - y, x[:, j].reshape(m, 1))) / m\n        j_history[i] = compute_cost(x, y, theta)\n    return theta, j_history\n\n\ndef gd(x: np.ndarray, y: np.ndarray, theta: np.ndarray, alpha: float, num_iters: int) \\\n        -> (np.ndarray, np.ndarray):\n    \"\"\"Optimized version of gradient_descent function. Parameters and return is equal with gradient_descent()\"\"\"\n    m = len(y)  # number of training examples\n    n = x.shape[1]  # number of features\n    alpha_m = alpha / m  # constant formula part, calculate outside of loops\n    j_history = np.zeros(shape=(num_iters, 1))\n    for i in range(num_iters):\n        difference = x @ theta - y\n        for j in range(n):\n            # np.multiply is the element-wise multiplication\n            theta[j, 0] = theta[j, 0] - alpha_m * sum(np.multiply(difference, x[:, j].reshape(m, 1)))\n        j_history[i] = np.ndarray.item(sum(np.square(difference)) / (2 * m))  # use precalculated difference\n    return theta, j_history\n", "meta": {"hexsha": "ebbd3e816e2e62eb493a913bf8c73921ae3fc875", "size": 3303, "ext": "py", "lang": "Python", "max_stars_repo_path": "aiml/lr.py", "max_stars_repo_name": "andyceo/pylibs", "max_stars_repo_head_hexsha": "df2eec6f9903e27ab02a82688378207eedb1b419", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-28T08:56:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-28T08:56:41.000Z", "max_issues_repo_path": "aiml/lr.py", "max_issues_repo_name": "andyceo/pylibs", "max_issues_repo_head_hexsha": "df2eec6f9903e27ab02a82688378207eedb1b419", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aiml/lr.py", "max_forks_repo_name": "andyceo/pylibs", "max_forks_repo_head_hexsha": "df2eec6f9903e27ab02a82688378207eedb1b419", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5211267606, "max_line_length": 118, "alphanum_fraction": 0.6775658492, "include": true, "reason": "import numpy", "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877684006775, "lm_q2_score": 0.9005297821135385, "lm_q1q2_score": 0.874133244578139}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport imageio\nimport matplotlib.pyplot as plt\nimport timeit\n\n\n#%%\n#<start:svd>\ndef compress_image(A,k):\n    u,s,vt = np.linalg.svd(A, full_matrices=False)\n    \n    return (u[:,:k]*s[:k])@vt[:k]\n#<end:svd>\n#%%\n#<start:approx_svd>\ndef col_sample_compress_image(A,k,eps):\n    m,n = np.shape(A)\n    \n    column_norms = np.linalg.norm(A,axis=0)\n    \n    column_probs = column_norms**2\n    column_probs /= np.sum(column_probs)\n    \n    s = int(k/eps**2)\n    \n    indices = np.random.choice(np.arange(n), size=s, p=column_probs)\n    \n    X = A[:,indices]\n    \n    u,s,vt = np.linalg.svd(X, full_matrices=False)\n    \n    return u[:,:k]@(u[:,:k].T@A)\n#<end:approx_svd>\n\n#%%\n#<start:approx_qr>\ndef gaus_sample_compress_image(A,k):\n    m,n = np.shape(A)\n    \n    X = A@np.random.randn(n,k)\n    u,s,vt = np.linalg.svd(X, full_matrices=False)\n    \n    return u[:,:k]@(u[:,:k].T@A)\n#<end:approx_qr>\n\n#%%\nA = imageio.imread('einstein.jpg')[:,:,0]\nK = np.logspace(0,2.7,8,dtype='int')\nfor i,k in enumerate(K):\n    A_k = compress_image(A,k)\n    plt.imsave('img/'+str(k)+'.png', A_k[::6,::6], format='png')\n    \n    A_k_col = col_sample_compress_image(A,k,1)\n    plt.imsave('img/'+str(k)+'_fast.png', A_k_col[::6,::6], format='png')\n    \n    A_k_gaus = gaus_sample_compress_image(A,k)\n    plt.imsave('img/'+str(k)+'_faster.png', A_k_gaus[::6,::6], format='png')\n\n#%%\n    \nN = 1\n\nK = np.logspace(0,2.7,8,dtype='int')\nsetup = 'from __main__ import A, compress_image'\nsetup_col = 'from __main__ import A, col_sample_compress_image'\nsetup_gaus = 'from __main__ import A, gaus_sample_compress_image'\n\nt = np.zeros(len(K))\nt_col = np.zeros(len(K))\nt_gaus = np.zeros(len(K))\n\nfor i,k in enumerate(K):\n    t[i] = timeit.timeit('compress_image(A,'+str(k)+')', number=N, setup=setup)/N\n    t_col[i] = timeit.timeit('col_sample_compress_image(A,'+str(k)+',1)', number=N, setup=setup_col)/N\n    t_gaus[i] = timeit.timeit('gaus_sample_compress_image(A,'+str(k)+')', number=N, setup=setup_gaus)/N\n\n#%%\nplt.figure(figsize=(10,6))\nplt.scatter(K,t,label='exact')\nplt.scatter(K,t_col,label='column sampling')\nplt.scatter(K,t_gaus,label='gaussian sampling')\n\nplt.xlabel('$k$')\nplt.ylabel('time (s)')\nplt.legend()\n\nplt.xscale('log')\nplt.yscale('log')\nplt.savefig('img/times.pdf')\n\n\n", "meta": {"hexsha": "dfb375a530a1b59f7d8ecf5711fe8e2c8db55fcc", "size": 2312, "ext": "py", "lang": "Python", "max_stars_repo_path": "cse521/hw3/approx_svd.py", "max_stars_repo_name": "interesting-courses/UW_coursework", "max_stars_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-19T01:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T12:32:59.000Z", "max_issues_repo_path": "cse521/hw3/approx_svd.py", "max_issues_repo_name": "interesting-courses/UW_coursework", "max_issues_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cse521/hw3/approx_svd.py", "max_forks_repo_name": "interesting-courses/UW_coursework", "max_forks_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-31T22:23:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T22:13:01.000Z", "avg_line_length": 24.3368421053, "max_line_length": 103, "alphanum_fraction": 0.634083045, "include": true, "reason": "import numpy", "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502202, "lm_q2_score": 0.9219218278830521, "lm_q1q2_score": 0.8741243605018373}}
{"text": "\"\"\"\nfloor\nThe tool floor returns the floor of the input element-wise.\nThe floor of  is the largest integer  where .\n\nimport numpy\n\nmy_array = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\nprint numpy.floor(my_array)         #[ 1.  2.  3.  4.  5.  6.  7.  8.  9.]\nceil\nThe tool ceil returns the ceiling of the input element-wise.\nThe ceiling of  is the smallest integer  where .\n\nimport numpy\n\nmy_array = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\nprint numpy.ceil(my_array)          #[  2.   3.   4.   5.   6.   7.   8.   9.  10.]\nrint\nThe rint tool rounds to the nearest integer of input element-wise.\n\nimport numpy\n\nmy_array = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\nprint numpy.rint(my_array)          #[  1.   2.   3.   4.   6.   7.   8.   9.  10.]\nTask\nYou are given a 1-D array, . Your task is to print the ,  and  of all the elements of .\n\nNote\nIn order to get the correct output format, add the line  below the numpy import.\n\nInput Format\n\nA single line of input containing the space separated elements of array .\n\nOutput Format\n\nOn the first line, print the  of A.\nOn the second line, print the  of A.\nOn the third line, print the  of A.\n\nSample Input\n\n1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9\nSample Output\n\n[ 1.  2.  3.  4.  5.  6.  7.  8.  9.]\n[  2.   3.   4.   5.   6.   7.   8.   9.  10.]\n[  1.   2.   3.   4.   6.   7.   8.   9.  10.]\n\"\"\"\n\nimport numpy as np\n\nnp.set_printoptions(legacy=\"1.13\")\n\narr = np.array(list(map(float, input().split())), float)\nprint(np.floor(arr))\nprint(np.ceil(arr))\nprint(np.rint(arr))\n", "meta": {"hexsha": "edbc196014441553123c30aff3c18fd446f43ce2", "size": 1572, "ext": "py", "lang": "Python", "max_stars_repo_path": "Hackerrank_codes/Numpy/numpy_floor_ceil_rint.py", "max_stars_repo_name": "Vyshnavmt94/HackerRankTasks", "max_stars_repo_head_hexsha": "634c71ccf0bea7585498bcd7d63e34d0334b4678", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Hackerrank_codes/Numpy/numpy_floor_ceil_rint.py", "max_issues_repo_name": "Vyshnavmt94/HackerRankTasks", "max_issues_repo_head_hexsha": "634c71ccf0bea7585498bcd7d63e34d0334b4678", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hackerrank_codes/Numpy/numpy_floor_ceil_rint.py", "max_forks_repo_name": "Vyshnavmt94/HackerRankTasks", "max_forks_repo_head_hexsha": "634c71ccf0bea7585498bcd7d63e34d0334b4678", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6440677966, "max_line_length": 87, "alphanum_fraction": 0.606870229, "include": true, "reason": "import numpy", "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068041, "lm_q2_score": 0.9196425377849806, "lm_q1q2_score": 0.8740383602582411}}
{"text": "# IMport the necessary modules\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# In this short script, we will see how Stirling's approximation can be\n# useful for approximating very large numbers. For example, computing 200! is\n# very difficult because that is beyond the basic precision of a 64-bit\n# computer. We can do better by converting the numbers to something called\n# 'arbitrary precision', but it is often sufficient to perform approximations\n# by hand.\n\n# As a reminder, Stirling's approximation is\n#\n#     log(n!) = n * log(n) - n\n#\n# We'll show this by computing the log of the factorial for large numbers\n# and show it along with the approximation.\n\n# We'll first set upa range of n to compute.\nn_array = np.arange(0, 150, 1)\n\n# Now we'll compute the factorial and store the log.\nlog_factorial = []\nfor n in n_array:\n    n_factorial = float(np.math.factorial(n))   # Converts to a float for precision\n    log_factorial.append(np.log(n_factorial))\n\n# Now we can compute our approximation.\nstirlings_approx = n_array * np.log(n_array) - n_array\n\n# Now let's plot the log factorial and our approximation together.\nplt.figure()\nplt.plot(n_array, log_factorial, label='factorial')\nplt.plot(n_array, stirlings_approx, label='approximation')\nplt.xlabel('$n$')\nplt.ylabel('$n!$')\nplt.legend()\nplt.show()\n\n# We see that as n becomes larger and larger, our approximation gets even\n# better.\n", "meta": {"hexsha": "e37e4ed0f1a2115264417b499a8039cf459fd6f2", "size": 1422, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/stirling_appx.py", "max_stars_repo_name": "RPGroup-PBoC/gist_pboc_2017", "max_stars_repo_head_hexsha": "2c2f5134e221cf174c92a933ab1e5f71b2eb8b17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/stirling_appx.py", "max_issues_repo_name": "RPGroup-PBoC/gist_pboc_2017", "max_issues_repo_head_hexsha": "2c2f5134e221cf174c92a933ab1e5f71b2eb8b17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/stirling_appx.py", "max_forks_repo_name": "RPGroup-PBoC/gist_pboc_2017", "max_forks_repo_head_hexsha": "2c2f5134e221cf174c92a933ab1e5f71b2eb8b17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-08T00:48:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-08T00:48:28.000Z", "avg_line_length": 33.0697674419, "max_line_length": 83, "alphanum_fraction": 0.7475386779, "include": true, "reason": "import numpy", "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446494481298, "lm_q2_score": 0.8976952832120991, "lm_q1q2_score": 0.8740362093342838}}
{"text": "\"\"\"\n  Name     : c12_10_simulate_pi.py\n  Book     : Python for Finance (2nd ed.)\n  Publisher: Packt Publishing Ltd. \n  Author   : Yuxing Yan\n  Date     : 6/6/2017\n  email    : yany@canisius.edu\n             paulyxy@hotmail.com\n\"\"\"\n\nimport scipy as sp \nn=100000\nx=sp.random.uniform(low=0,high=1,size=n) \ny=sp.random.uniform(low=0,high=1,size=n) \ndist=sp.sqrt(x**2+y**2) \nin_circle=dist[dist<=1] \nour_pi=len(in_circle)*4./n\nprint ('pi=',our_pi)\nprint('error (%)=', (our_pi-sp.pi)/sp.pi)\n", "meta": {"hexsha": "a98b050d93300fc4352657e2959cf0abd45ee343", "size": 485, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter12/c12_10_simulate_pi.py", "max_stars_repo_name": "John-ye666/Python-for-Finance-Second-Edition", "max_stars_repo_head_hexsha": "dabef09bcdd7b0ec2934774741bd0a7e1950de73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 236, "max_stars_repo_stars_event_min_datetime": "2017-07-02T03:06:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:15:33.000Z", "max_issues_repo_path": "Chapter12/c12_10_simulate_pi.py", "max_issues_repo_name": "John-ye666/Python-for-Finance-Second-Edition", "max_issues_repo_head_hexsha": "dabef09bcdd7b0ec2934774741bd0a7e1950de73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter12/c12_10_simulate_pi.py", "max_forks_repo_name": "John-ye666/Python-for-Finance-Second-Edition", "max_forks_repo_head_hexsha": "dabef09bcdd7b0ec2934774741bd0a7e1950de73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 139, "max_forks_repo_forks_event_min_datetime": "2017-06-30T10:28:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T19:43:34.000Z", "avg_line_length": 24.25, "max_line_length": 41, "alphanum_fraction": 0.6371134021, "include": true, "reason": "import scipy", "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9579122684798184, "lm_q2_score": 0.9124361616674908, "lm_q1q2_score": 0.8740337934659244}}
{"text": "import numpy as np\nimport pandas as pd\nimport time, gc\n \npi = np.pi \ncos = np.cos \nsin = np.sin\nacos = np.arccos\ndegrees = np.degrees\nradians = np.radians\n\ndef angularDistance(row, col_names):\n    '''\n    Computes the angular distance (in degrees) between two points on the celestial \n    sphere with a given right-ascension and declination values\n    \n    <Formula> - http://spiff.rit.edu/classes/phys373/lectures/radec/radec.html\n    \n    Parameters\n    ----------\n    row : pd.Dataframe - series\n        Input right-ascension in (hrs) and declination in (degrees) format\n        \n    col_names: list of strings\n        The names of the columns on which the function will be applied \n        ### SHOULD FOLLOW THIS CONVENTION\n        c1 = right-ascension_1; c2 = right-ascension_2\n        c3 = declination_1; c4 = declination_2\n          \n    Returns\n    -------\n    y : pd.Dataframe - series\n        The corresponding angular distance in degree value.\n    '''\n    # Unpack column names\n    c1, c2, c3, c4 = col_names\n    # Assert datatypes\n    assert type(c1) == str and type(c2) == str and type(c3) == str and type(c4) == str, 'TypeError: input should be str'\n      \n    \n    # Units of right-ascension is in (hours) format\n    alpha1, alpha2 = radians(15*row[c1]), radians(15*row[c2])\n    \n    # Units of declination is in (degrees) format\n    delta1, delta2 = radians(row[c3]), radians(row[c4])\n    \n    # Given Formula\n    temp = cos(pi/2 - delta1)*cos(pi/2 - delta2) + sin(pi/2 - delta1)*sin(pi/2 - delta2)*cos(alpha1 - alpha2) \n    \n    return np.degrees(acos(temp))\n\n\ndef genRefCatalogue(CATALOGUE, mag_limit, no_iter = -1,  gen_csv = True):\n    '''\n    Generates the reference star catalogue for Geometric Voting Algorithm where each row\n    of the table has two unique stars and the corresponding angular distance in degrees,\n    for all pairs of stars with a specified upper magnitude limit\n    \n    Parameters\n    ----------\n    CATALOGUE : pd.Dataframe\n        The 'master' star catalogue on which the function works\n\n    mag_limit : floating-point number\n        The upper magnitude limit of stars that are required in the reference catalogue\n        \n    no_iter : integer, default = -1\n        Specifies the number of iterations, thereby allowing it to be reduced\n        Default value = -1, allows for the completion of the entire catalogue\n       \n    gen_csv : boolean, default = True\n          If True generates csv files of the reference catalogues\n          \n    Returns\n    -------\n    OB_CATALOGUE : pd.Dataframe\n        The corresponding angular distance in degree value.\n    '''\n    \n    # Start clock-1\n    start1 = time.time()\n    \n    # Generate restricted catalogue based on upper magnitude limit\n    temp0 = CATALOGUE[CATALOGUE.Mag <= mag_limit]\n    \n    # Number of rows in the resticted catalogue\n    rows = temp0.shape[0]\n    # Resets the index of <temp0>\n    temp0.index = list(range(rows))\n    \n    # Prints total number of stars in <temp0> and the (n)C(2) - combinations\n    print('Number of stars - ', rows)\n    print('Number of unique combinations = ', (rows-1)*rows/2)\n    \n    # Initialize the number of iterations to take place\n    no_iter = (rows-1) if no_iter == -1 else no_iter\n    \n    for i in range(no_iter):\n        # Throws error if an iteration runs beyond number of available rows in <temp0>\n        assert i<(rows-1), 'IndexError: iterating beyond available number of rows'\n        \n        # The final iteration is reduntant, as <temp2> will be zero rows\n        '''\n        if (rows-1-i)==0:\n            continue\n        '''\n        \n        # Generates <temp1> dataframe which has the (i - th) star of <temp0>\n        # repetated (rows-1-i) times \n        temp1 = pd.DataFrame(columns = ['Star_ID1','RA_1', 'Dec_1', 'Mag_1'])\n        s1, ra, dec, mag = temp0.iloc[i]\n        temp1.loc[0] = [s1] + [ra] + [dec] + [mag]\n        temp1 = pd.concat([temp1]*(rows-1-i), ignore_index=True)\n        \n        # Generates <temp2> dataframe by copying values of <temp0> and dropping the first\n        # (i + 1) number of stars\n        temp2 = temp0\n        temp2 = temp2.drop(list(range(i+1)), axis = 0)\n        # Resets the index \n        temp2.index = list(range(0, rows-1-i))\n        \n        # Concatenates <temp1> & <temp2> side-by-side such that resulting <temp3> has (8) columns altogether\n        temp3 = pd.concat([temp1, temp2], axis=1)\n        \n        # Initializes <temp4> in the first iteratation\n        if i == 0:\n            temp4 = temp3\n            \n        # Append subsequent <temp4> with <temp3> after first iteration\n        else:\n            temp4 = pd.concat([temp4, temp3], axis = 0, ignore_index=True)\n        \n        # Releases memory back to OS\n        if i%40 == 0:\n            gc.collect()\n    \n    gc.collect()      \n    # Rename columns\n    temp4.columns = ['Star_ID1','RA_1', 'Dec_1', 'Mag_1', 'Star_ID2', 'RA_2', 'Dec_2', 'Mag_2']\n    \n    if gen_csv == True:\n        #Generates CSV of <temp4>\n        temp4.to_csv('Processed_Catalogue1.csv', index = False)\n        \n    # Stop clock-1   \n    end1 = time.time() - start1\n    \n    # Print time taken\n    print('Process 1 - ', end1)\n    \n    # Start clock-2\n    start2 = time.time()\n    \n    # Initialize <OB_CATALOGUE>\n    OB_CATALOGUE = temp4\n    \n    # Calculate angular distance between the two stars present in every row\n    cols = ['RA_1', 'RA_2', 'Dec_1', 'Dec_2']\n    OB_CATALOGUE['Ang_Distance'] = OB_CATALOGUE.apply(angularDistance, axis = 1, col_names = cols)\n    \n    if gen_csv == True:\n        # Generates CSV of <OB_CATALOGUE>\n        OB_CATALOGUE.to_csv('Processed_Catalogue2.csv', index = False)\n        \n    # Stop clock-2\n    end2 = time.time() - start2\n    \n    # Print time taken\n    print('Process 2 - ', end2)\n    print('Total Process ', end1+ end2)\n        \n    return OB_CATALOGUE\n\n\n\ndef main():\n    '''\n    main function\n    '''\n    # Reads 'Master' star catalogue\n    CATALOGUE = pd.read_csv(r\"F:\\IIT Bombay\\SatLab\\Star Tracker\\Programs\\Catalogues\\Modified Star Catalogue.csv\")\n    # StarID: The database primary key from a larger \"master database\" of stars\n    # Mag: The star's apparent visual magnitude\n    # RA, Dec: The star's right ascension and declination, for epoch 2000.0 (Unit: RA - hrs; Dec - degrees)\n    \n    # Sorts <CATALOGUE>\n    CATALOGUE.sort_values('Mag', inplace=True)\n    \n    # Run function\n    REF_DF = genRefCatalogue(CATALOGUE, mag_limit=1, no_iter=-1, gen_csv=False)\n    \n    # Sort <REF_DF>\n    REF_DF.sort_values('Ang_Distance', inplace=False)\n    \n    \n    # Generates CSV of <REF_DF>\n    REF_DF.to_csv('Processed_Catalogue3.csv', index = False)\n    print('Done')\n    \nif __name__ == '__main__':\n    main()", "meta": {"hexsha": "76c08f706e665e5da58268bfa58cc5609a793bd4", "size": 6694, "ext": "py", "lang": "Python", "max_stars_repo_path": "GV_Catalogue_Gen.py", "max_stars_repo_name": "Jamun-Fanatic-Foreva/STADS---Star-Matching", "max_stars_repo_head_hexsha": "0a96885a168b8de86eb4f51ba401980969023452", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-29T13:13:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-29T13:13:48.000Z", "max_issues_repo_path": "GV_Catalogue_Gen.py", "max_issues_repo_name": "Jamun-Fanatic-Foreva/STADS---Star-Matching", "max_issues_repo_head_hexsha": "0a96885a168b8de86eb4f51ba401980969023452", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GV_Catalogue_Gen.py", "max_forks_repo_name": "Jamun-Fanatic-Foreva/STADS---Star-Matching", "max_forks_repo_head_hexsha": "0a96885a168b8de86eb4f51ba401980969023452", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-09T17:28:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-09T17:28:18.000Z", "avg_line_length": 33.3034825871, "max_line_length": 120, "alphanum_fraction": 0.6171198088, "include": true, "reason": "import numpy", "num_tokens": 1803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018434079933, "lm_q2_score": 0.896251366205709, "lm_q1q2_score": 0.8740259844807399}}
{"text": "# A function to find out all the primes till the number n\n#\n# @Author : Subhendu Ranjan Mishra\n#\n# @Input : a positive intiger\n# @Output : An array of intigers\n\nfrom time import time\nfrom numba import jit\nimport numpy as np\n\n\n@jit\ndef getPrimes(n):\n    q, r = divmod(n, 2)\n    r = q + r\n    seive = np.ones(r, dtype=bool)\n    seive[0] = 0\n\n    lim = int(n**0.5 / 2) + 1\n\n    for i in range(1, lim + 1):\n        p = 2 * i + 1\n        if seive[i]:\n            sp = 2 * i * (i + 1)\n            seive[sp:r:p] = False\n\n    def_prime = np.asarray([2])\n    seived_primes = np.asarray(np.nonzero(seive)).flatten() * 2 + 1\n    primes = np.concatenate((def_prime, seived_primes))\n    return primes\n\n\n@jit\ndef getPrimes2(n):\n    arr = np.ones(n + 1, dtype=bool)\n    arr[0], arr[1] = 0, 0\n    for i in range(2, n + 1):\n        if arr[i]:\n            arr[i * i:n + 1:i] = False\n    return arr.nonzero()[0]\n\n\nif __name__ == '__main__':\n    # Test Cases\n    print(\"Testing the getPrimes function.\")\n    print(\"getPrimes2(18) : \", getPrimes2(18))\n    print(\"getPrimes2(7) : \", getPrimes2(7))\n    print(\"getPrimes2(25) : \", getPrimes2(25))\n    print(\"getPrimes2(31) : \", getPrimes2(31))\n    print()\n    print(\"Now testing the getPrimes function for higher powers of 10\")\n    for power in range(1, 9):\n        n = 10**power\n        t0 = time()\n        primes = getPrimes(n)\n        print(\n            \"1 - Computed for {:10d} ({}th power of 10), in {:03.5f} secs. number of primes : {:,}\".\n            format(n, power, time() - t0, len(primes)))\n\n        # second function\n        t0 = time()\n        primes2 = getPrimes2(n)\n        print(\n            \"2 - Computed for {:10d} ({}th power of 10), in {:03.5f} secs. number of primes : {:,}\".\n            format(n, power, time() - t0, len(primes2)))\n        # print(primes)\n", "meta": {"hexsha": "458b906db2089265116805793c1833e17adc3a58", "size": 1804, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/myutils/prime.py", "max_stars_repo_name": "lord483/Project-Euler-Solutions", "max_stars_repo_head_hexsha": "ba9e9451460d631774dfa75d61cedc1918a462c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/myutils/prime.py", "max_issues_repo_name": "lord483/Project-Euler-Solutions", "max_issues_repo_head_hexsha": "ba9e9451460d631774dfa75d61cedc1918a462c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/myutils/prime.py", "max_forks_repo_name": "lord483/Project-Euler-Solutions", "max_forks_repo_head_hexsha": "ba9e9451460d631774dfa75d61cedc1918a462c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5294117647, "max_line_length": 100, "alphanum_fraction": 0.5476718404, "include": true, "reason": "import numpy,from numba", "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542805873231, "lm_q2_score": 0.9111797027760039, "lm_q1q2_score": 0.8739619123018889}}
{"text": "#IIR Analog and Digital Butterworth BPF filter design\r\nfrom scipy import signal\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom pylab import clf\r\n#Analog Band pass butterworth filter, order =3, fc1=100Hz, fc2=300Hz\r\n#b = numerator coefficients, a = denominator coefficients\r\n#w = frequency variable, h= frequency response\r\n\r\nb,a = signal.iirfilter(3,[100,300],btype ='bandpass',analog=True, ftype ='butter')\r\nw,h = signal.freqs(b,a,1000)\r\n\r\nfig1 = plt.figure(1)\r\nax = fig1.add_subplot(1,1,1)\r\nax.semilogx(w,20*np.log10(np.maximum(abs(h),1e-5)))\r\nax.set_title('Butterworth IIR Analog BPF frequency response')\r\nax.set_xlabel('Frequency in Hz---->')\r\nax.set_ylabel('Amplitude in dB----->')\r\n#ax.axis((10,1000,-100,10))\r\nax.grid(which='both',axis='both')\r\nplt.show()\r\n\r\n\r\n#Digital Band pass butterworth filter, order =3, fc1=100Hz, fc2=300Hz\r\nfs =1000\r\nsos = signal.iirfilter(3,[100/fs,300/fs],btype ='bandpass',analog=False, ftype ='butter',output='sos')\r\nw,h = signal.sosfreqz(sos,1000)\r\n\r\n\r\nfig2 = plt.figure(2)\r\nclf()\r\nax = fig2.add_subplot(1,1,1)\r\nax.plot(w/np.pi,20*np.log10(np.maximum(abs(h),1e-5)))\r\nax.set_title('Butterworth IIR Digital BPF frequency response')\r\nax.set_xlabel('Normalized Digital Frequency ---->')\r\nax.set_ylabel('Amplitude in dB----->')\r\n#ax.axis((10,1000,-100,10))\r\nax.grid(which='both',axis='both')\r\nplt.show()\r\n\r\n#Result\r\n##>>> b\r\n##array([8000000.,       0.,       0.,       0.])\r\n##>>> a\r\n##array([1.0e+00, 4.0e+02, 1.7e+05, 3.2e+07, 5.1e+09, 3.6e+11, 2.7e+13])\r\n##>>> sos\r\n##array([[ 0.01809893,  0.03619787,  0.01809893,  1.        , -1.28407904,\r\n##         0.50952545],\r\n##       [ 1.        ,  0.        , -1.        ,  1.        , -1.0263941 ,\r\n##         0.65079467],\r\n##       [ 1.        , -2.        ,  1.        ,  1.        , -1.73866033,\r\n##         0.83854915]])\r\n", "meta": {"hexsha": "b6455ed911aff77808b708d7b3b1832f3a6f0728", "size": 1817, "ext": "py", "lang": "Python", "max_stars_repo_path": "20_IIR_BPF_Butterworth.py", "max_stars_repo_name": "senthilkumarIRTT/Python-for-Digital-Signal-Processing", "max_stars_repo_head_hexsha": "684b36a035cacd229dc7a1984d401d18a2b19670", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-19T05:40:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T03:52:03.000Z", "max_issues_repo_path": "20_IIR_BPF_Butterworth.py", "max_issues_repo_name": "senthilkumarIRTT/Python-for-Digital-Signal-Processing", "max_issues_repo_head_hexsha": "684b36a035cacd229dc7a1984d401d18a2b19670", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "20_IIR_BPF_Butterworth.py", "max_forks_repo_name": "senthilkumarIRTT/Python-for-Digital-Signal-Processing", "max_forks_repo_head_hexsha": "684b36a035cacd229dc7a1984d401d18a2b19670", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-09T06:46:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-09T06:46:50.000Z", "avg_line_length": 34.2830188679, "max_line_length": 103, "alphanum_fraction": 0.6092460099, "include": true, "reason": "import numpy,from scipy", "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542805873231, "lm_q2_score": 0.9111797003640646, "lm_q1q2_score": 0.873961909988467}}
{"text": "import numpy as np\n\ndef l1Norm(x):\n    \"\"\"\n        Computes the l1 norm of x\n    \"\"\"\n    return np.sum(np.abs(x))\n\ndef l2Norm(x):\n    \"\"\"\n        Computes the l2 norm of x\n    \"\"\"\n    return np.sqrt(np.sum(x**2))\n\ndef r2Compute(u, v, x):\n    \"\"\"\n        Computes the r square score of the data\n        x in the projection defined by u and v\n        :param u: Vector of size x\n        :param v: Vector of size x\n        :param x: Matrix of size N * x\n        :return r2: r square score of the N points projected in (u,v)\n    \"\"\"\n    xProj = np.dot(x, u.T).flatten()\n    yProj = np.dot(x, v.T).flatten()\n    projectedPoints = np.array([xProj,yProj]).T\n    SSRes = np.sum((projectedPoints[:, 1] - projectedPoints[:, 0])**2)\n    SSTot = np.sum((projectedPoints[:, 1] - np.mean(projectedPoints[:, 1]))**2)\n    \n    return 1 - SSRes/(SSTot + 10**(-5)) # Add epsilon to avoid nan\n", "meta": {"hexsha": "423e942ccbb96af0e764db3549e5f0549069e879", "size": 873, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/utils.py", "max_stars_repo_name": "Jeanselme/CanonicalAutocorrelationAnalysis", "max_stars_repo_head_hexsha": "640543b197f9cb1dac1bd27d0805d61f1837091d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-18T01:43:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-18T01:43:32.000Z", "max_issues_repo_path": "model/utils.py", "max_issues_repo_name": "Jeanselme/CanonicalAutocorrelationAnalysis", "max_issues_repo_head_hexsha": "640543b197f9cb1dac1bd27d0805d61f1837091d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/utils.py", "max_forks_repo_name": "Jeanselme/CanonicalAutocorrelationAnalysis", "max_forks_repo_head_hexsha": "640543b197f9cb1dac1bd27d0805d61f1837091d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-24T23:37:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-24T23:37:47.000Z", "avg_line_length": 28.1612903226, "max_line_length": 79, "alphanum_fraction": 0.5681557847, "include": true, "reason": "import numpy", "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305328688783, "lm_q2_score": 0.9073122201074847, "lm_q1q2_score": 0.8739508332525775}}
{"text": "\n\"\"\"\n\nThis program will find the closest pair of points in a set of n points.\nTwo algorithms will be implemented here:\n    1) A brute force approach determines the distance between\n       every pair of points first and then find the points\n       with the closest distance.\n    2) An enhanced algorithm\n       - Sorts all points according to coordinates;\n       - Divides all points in two halves;\n       - Recursively finds the smallest distances in both subarrays;\n       - Take the minimum of two smallest distances;\n       - Create an array strip[] that stores all points which are at\n         most d distance away from the middle line dividing the two sets;\n       - Find the smallest distance in strip[];\n       - Find the points with the closest distance.\n\n The time complexity of brute force algorithm is O(n^2).\n The time complexity of enhanced algorithm algorithm is O(n * log(n)).\n\n @author RabbitCaesar\n\n\"\"\"\n\nimport numpy as np\nimport timeit\n\n# Input random generator\n# Use this to create different testing inputs\ndef input_random_generator(n):\n    arrP = []\n    for i in range (n):\n        temp = []\n        for j in range (2):\n            temp.append(np.random.randint(1,50))\n        arrP.append(temp)\n    return arrP\n\n# Calculate Euclidean distance between 2 points\ndef get_distance(point1, point2):\n    return np.round(np.sqrt((point1[0] - point2[0]) ** 2\n                            + (point1[1] - point2[1]) ** 2), 2)\n\n# Brute force O(n^2)\ndef brute_force(arr, n):\n    min_dist, pair = float('inf'), []\n    # Iterate through all the possible pairs\n    # Calculate distance and compare to find min\n    for i in range(n - 1):\n        for j in range(i + 1, len(arr)):\n            dist = get_distance(arr[i], arr[j])\n            if min_dist > dist:\n                min_dist = dist\n                pair = [arr[i], arr[j]]\n    return [min_dist, pair]\n\n\n# Sort points vertically or horizontally. For example, points\n# (4,3), (6,2), (1,7) will be sorted to (6,2), (4,3), (1,7) vertically\ndef sort_points(array, index=0):\n    return sorted(array, key=lambda x: x[index])\n\n\n# Find the closest pair of points in the strip.\n# Return the min distance between the closest pair.\ndef get_strip_min_dist(points, n, min_dist=float('inf')):\n    # it's proven that the max iteration of this loop is 6\n    for i in range(min(6, n - 1), n):\n        for j in range(max(0, i - 6), i):\n            dist = get_distance(points[i], points[j])\n            if min_dist > dist: min_dist = dist\n    return min_dist\n\n\n# Recursively find the distance between the closest pair\ndef closest_pair_raw(points_h_sorted, points_v_sorted, n):\n    # Base case: if there are only 2 or 3 points, then use brute force\n    if n <= 3:\n        return brute_force(points_h_sorted, n)[0]\n\n    # Recursion part\n    mid = n // 2\n    # Left section\n    dist_left = closest_pair_raw(points_h_sorted\n                                 , points_v_sorted[:mid], mid)\n    # Right section\n    dist_right = closest_pair_raw(points_v_sorted\n                                  , points_v_sorted[mid:], n - mid)\n    min_dist = min(dist_left, dist_right)\n\n    # Points in the strip\n    strip = []\n    for point in points_h_sorted:\n        if abs(point[0] - points_h_sorted[mid][0]) < min_dist:\n            strip.append(point)\n\n    # Get the distance between closest pair in strip\n    min_dist_strip = get_strip_min_dist(strip, len(strip), min_dist)\n\n    return min(min_dist, min_dist_strip)\n\n# Return final distance between closest pair\ndef closest_pair_of_points(points, n):\n    points_h_sorted = sort_points(points, index=0)\n    points_v_sorted = sort_points(points, index=1)\n\n    return (closest_pair_raw(points_h_sorted, points_v_sorted, n))\n\n\n\"\"\"\nDriver executes DTM\n\"\"\"\nif __name__ == '__main__':\n\n    # Manual Test case 1:\n    #points = [(32, 24), (34, 70), (77, 61), (37, 99), (26, 47), (16, 53)]\n\n    # Manual Test case 2:\n    # points = [[82, 31], [67, 11], [80, 7], [25, 22], [84, 23]\n    #         , [21, 2], [24, 74], [21, 53], [28, 85], [12, 7]]\n\n    # Manual Test case 3:\n    # points  =[[94, 38], [35, 48], [18, 59], [33, 95], [57, 80]\n    #         , [34, 5], [71, 42], [42, 41], [75, 40], [81, 52]\n    #         , [99, 21], [74, 59], [83, 70], [17, 72], [22, 50]\n    #         , [51, 16], [12, 80], [57, 96], [7, 14], [5, 2]]\n\n    # Random generator can be used to initialize input points\n    points = input_random_generator(100)\n\n    \"\"\"\n    Brute Force Approach O(n^2)\n    Set timmer to log the runtime \n    \"\"\"\n    start = timeit.default_timer()\n\n    brute_force_result = brute_force(points, len(points))\n\n    stop = timeit.default_timer()\n    time_b = stop - start\n\n    \"\"\"\n    Enhanced Approach O(nlog(n))\n    Set timmer to log the runtime \n    \"\"\"\n    start = timeit.default_timer()\n\n    nlogn_result = closest_pair_of_points(points, len(points))\n\n    stop = timeit.default_timer()\n    time_e = stop - start\n\n    \"\"\"\n    Display final results\n    \"\"\"\n    comp = np.round(time_b/time_e ,2)\n    pointA = str(brute_force_result[1][0])\n    pointB = str(brute_force_result[1][1])\n\n    print('\\nInputs:\\n' + str(points))\n    print('\\nClosest Pair Is: ' + pointA + ' and ' + pointB)\n\n    print('\\nBrute Force Approach O(n^2):\\nMin Distance: '\n          + str(brute_force_result[0]) + '\\nRuntime: '\n          , time_b)\n    print('\\nEnhanced Approach O(nlog(n)):\\nMin Distabce: '\n          + str(nlogn_result) + '\\nRuntime: '\n          , time_e)\n    print('\\nRuntime Comparison:\\nEnhanced Approach is'\n          , comp, 'times faster than Brute Force.')\n", "meta": {"hexsha": "af789477e6cca3fa0ba8d0b11eee86740b87e84f", "size": 5519, "ext": "py", "lang": "Python", "max_stars_repo_path": "ClosestPairs.py", "max_stars_repo_name": "RabbitCaesar/Algorithms-Implementations-Closest-Pairs", "max_stars_repo_head_hexsha": "e5960712e8fbeba27d16063a9d120badbd1fd08a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ClosestPairs.py", "max_issues_repo_name": "RabbitCaesar/Algorithms-Implementations-Closest-Pairs", "max_issues_repo_head_hexsha": "e5960712e8fbeba27d16063a9d120badbd1fd08a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ClosestPairs.py", "max_forks_repo_name": "RabbitCaesar/Algorithms-Implementations-Closest-Pairs", "max_forks_repo_head_hexsha": "e5960712e8fbeba27d16063a9d120badbd1fd08a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0872093023, "max_line_length": 74, "alphanum_fraction": 0.6156912484, "include": true, "reason": "import numpy", "num_tokens": 1514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96323053709097, "lm_q2_score": 0.907312213841788, "lm_q1q2_score": 0.8739508310480224}}
{"text": "# Simpson's rule\n#\n# M. Zingale (2013-02-13)\n\nimport math\nimport numpy\nimport sys\n\n# function we wish to integrate\ndef fun(x):\n    return numpy.exp(-x)\n\n\n# analytic value of the integral\ndef I_exact(a,b):\n    return -math.exp(-b) + math.exp(-a)\n\n\n# do a Simpson's integration by breaking up the domain [a,b] into N\n# slabs.  Note: N must be even, because we do a pair at a time\ndef simp(a,b,f,N):\n\n    xedge = numpy.linspace(a,b,N+1)\n\n    integral = 0.0\n\n    if not N%2 == 0:\n        sys.exit(\"ERROR: N must be even\")\n\n    delta = (xedge[1] - xedge[0])\n\n    n = 0\n    while n < N:\n        integral += (1.0/3.0)*delta*(f(xedge[n]) + \n                                     4.0*f(xedge[n+1]) + \n                                     f(xedge[n+2]))\n        n += 2\n\n    return integral\n\n\na = 0.0\nb = 1.0\n\nN = 2\nwhile (N <= 128):\n    t = simp(a,b,fun,N)\n    e = t - I_exact(a,b)\n    print N, t, e\n\n    N *= 2\n\n\n \n", "meta": {"hexsha": "f036805fea2dc5cbb5677a2a8f5fee7ccd61b7fb", "size": 905, "ext": "py", "lang": "Python", "max_stars_repo_path": "others/differentiation_integration/simp.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "others/differentiation_integration/simp.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/differentiation_integration/simp.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 16.4545454545, "max_line_length": 67, "alphanum_fraction": 0.5138121547, "include": true, "reason": "import numpy", "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924785827003, "lm_q2_score": 0.8991213725394589, "lm_q1q2_score": 0.8739392114413082}}
{"text": "import numpy as np\n\n\n# 均方误差\ndef mean_squared_error(y, t):\n    return 0.5 * np.sum((y-t)**2)\n\n\n# 交叉熵误差\n# 支持单个和 batch\ndef cross_entropy_error(y, t):\n    if y.ndim == 1:\n        t = t.reshape(1, t.size)\n        y = y.reshape(1, y.size)\n    batch_size = y.shape[0]\n    delta = 1e-7\n    return -np.sum(t * np.log(y + delta))\n\n\n# 假设 第三个位置是正确的\nt = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]\nprint('第三个位置的概率最高情况')\ny = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0]\nprint('均方误差', mean_squared_error(np.array(y), np.array(t)))\nprint('交叉熵误差', cross_entropy_error(np.array(y), np.array(t)))\n\nprint('第八个位置的概率最高的情况')\ny = [0.1, 0.05, 0.1, 0.0, 0.05, 0.1, 0.0, 0.6, 0.0, 0.0]\nprint('均方误差', mean_squared_error(np.array(y), np.array(t)))\nprint('交叉熵误差', cross_entropy_error(np.array(y), np.array(t)))\n\n\n# 数值微分\ndef numerical_diff(f, x):\n    h = 1e-4\n    return (f(x+h) - f(x-h)) / (2 * h)\n\n\n# 梯度计算\ndef numerical_gradient(f, x):\n    h = 1e-4\n    grad = np.zeros_like(x)\n\n    for idx in range(x.size):\n        tmp_val = x[idx]\n        # f(x+h) 的计算\n        x[idx] = tmp_val + h\n        fxh1 = f(x)\n        # f(x-h) 的计算\n        x[idx] = tmp_val - h\n        fxh2 = f(x)\n\n        grad[idx] = (fxh1 - fxh2) / (2 * h)\n        x[idx] = tmp_val\n\n    return grad\n\n\n# 梯度下降\ndef gradient_descent(f, init_x, lr=0.01, step_num=100):\n    x = init_x\n    for i in range(step_num):\n        grad = numerical_gradient(f, x)\n        x -= lr * grad\n\n    return x\n\n\ndef function_2(x):\n    return x[0]**2 + x[1]**2\n\n\nprint('用梯度下降计算函数 function_2 的最小值')\ninit_x = np.array([-3.0, 4.0])\nresult = gradient_descent(function_2, init_x=init_x, lr=0.1, step_num=100)\nprint(result)\n\n", "meta": {"hexsha": "5fe183360dc57d5a653ad1bc73db91e4dc8c9c2d", "size": 1621, "ext": "py", "lang": "Python", "max_stars_repo_path": "deep_learning_from_scratch/7_gradient.py", "max_stars_repo_name": "wdxtub/deep-learning-note", "max_stars_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2019-03-27T20:17:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T23:20:31.000Z", "max_issues_repo_path": "deep_learning_from_scratch/7_gradient.py", "max_issues_repo_name": "wdxtub/deep-learning-note", "max_issues_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deep_learning_from_scratch/7_gradient.py", "max_forks_repo_name": "wdxtub/deep-learning-note", "max_forks_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-03-31T10:28:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:25:40.000Z", "avg_line_length": 20.7820512821, "max_line_length": 74, "alphanum_fraction": 0.5657001851, "include": true, "reason": "import numpy", "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660962919971, "lm_q2_score": 0.9161096112990285, "lm_q1q2_score": 0.8739375096665131}}
{"text": "from sympy import Symbol, Derivative\nfrom sympy.solvers import solve\n\nx = Symbol('x')\ny = Symbol('y')\nh = Symbol('h')\n\n#f = 2*x**2 - y + 3*x*y\n#values = (2,3)\n\nf = 3*x**2 - 2*y + x*y\nvalues = (2,1)\n\n\ndef printline(): print('---------------------------------------------------------------------------------------')\n\ndef steep_step(f, values, x, y, h):\n    (xi, yi) = values\n    dfdx = Derivative(f,x).doit().evalf(subs = {x:xi, y:yi})\n    dfdy = Derivative(f,y).doit().evalf(subs = {x:xi, y:yi})\n    xnew = xi + dfdx*h\n    ynew = yi + dfdy*h\n    g = f.subs(x, xnew)\n    g = g.subs(y,ynew)\n    dgdh = Derivative(g,h).doit()\n    H = solve(dgdh, h)[0]\n    xnew = xi + dfdx*H\n    ynew = yi + dfdy*H\n    return (xnew, ynew)\n\ndef steep_step_verbose(f, values, x, y, h):\n    (xi, yi) = values\n    dfdx = Derivative(f,x).doit()\n    print('df/dx: ' + str(dfdx))\n    dfdx = dfdx.evalf(subs = {x:xi, y:yi})\n    print('df/dx @ ' + str(values) + ': ' + str(dfdx))\n    dfdy = Derivative(f,y).doit()\n    print('df/dy: ' + str(dfdy))\n    dfdy = dfdy.evalf(subs = {x:xi, y:yi})\n    print('df/dy @ ' + str(values) + ': ' + str(dfdy))\n    xnew = xi + dfdx*h\n    print('x = ' + str(xnew))\n    ynew = yi + dfdy*h\n    print('y = ' + str(ynew))\n    g = f.subs(x, xnew)\n    g = g.subs(y,ynew)\n    print('g(h) = ' + str(g))\n    dgdh = Derivative(g,h).doit()\n    print(\"g'(h) = \" + str(dgdh))\n    H = solve(dgdh, h)\n    print('Solutions of h: ' + str(len(H)))\n    H = H[0]\n    print('h* = ' + str(H))\n    xnew = xi + dfdx*H\n    ynew = yi + dfdy*H\n    print('(x,y) = ' + str((xnew, ynew)))\n    return (xnew, ynew)\n\nprintline()\nprint('Iteration 1: ')\nvalues = steep_step_verbose(f, values, x, y, h)\nprintline()\nprint('Iteration 2: ')\nvalues = steep_step_verbose(f, values, x, y, h)\n(xi, yi) = values\nY = f.evalf(subs = {x:xi, y:yi})\nprint('Height on the mountain: ' + str(Y))\nprintline()", "meta": {"hexsha": "4e79bfe9d2a34ce06db1bd4a6a5b4759113f8308", "size": 1858, "ext": "py", "lang": "Python", "max_stars_repo_path": "problem solutions/steepAsc.py", "max_stars_repo_name": "suhailnajeeb/numerical-methods", "max_stars_repo_head_hexsha": "b5f6189e5072407004e97d37edc83356e43449e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problem solutions/steepAsc.py", "max_issues_repo_name": "suhailnajeeb/numerical-methods", "max_issues_repo_head_hexsha": "b5f6189e5072407004e97d37edc83356e43449e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem solutions/steepAsc.py", "max_forks_repo_name": "suhailnajeeb/numerical-methods", "max_forks_repo_head_hexsha": "b5f6189e5072407004e97d37edc83356e43449e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-12T09:12:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-12T09:12:50.000Z", "avg_line_length": 27.3235294118, "max_line_length": 113, "alphanum_fraction": 0.512378902, "include": true, "reason": "from sympy", "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102524151826, "lm_q2_score": 0.9032942021480236, "lm_q1q2_score": 0.8738560721051905}}
{"text": "import numpy as np\n\ndef Build(type_str=\"sigmoid\"):\n    \"\"\"\n    Factory method that builds the specified activation function.\n    \"\"\"\n    if (type_str == \"sigmoid\"):\n        return SigmoidAF()\n    elif (type_str == \"arctan\"):\n        return ArctanAF()\n    else:\n        raise NotImplementedError(\"Unsupported activation function: '%s'\" % (type_str))\n\nclass ActivationFunctionBaseClass:\n    \"\"\"\n    Base class that defines the interfaces of all activation functions.\n    \"\"\"\n    def __init__(self):\n        pass\n\n    def GetValue(self, x):\n        raise NotImplementedError(\"Must implement GetValue().\")\n\n    def GetDerivative(self, x):\n        raise NotImplementedError(\"Must implement GetDerivative().\")\n\nclass SigmoidAF(ActivationFunctionBaseClass):\n    def __init__(self):\n        pass\n\n    def GetValue(self, x):\n        return 1.0 / (1.0 + np.exp(-x))\n\n    def GetDerivative(self, x):\n        v = self.GetValue(x)\n        #return np.multiply(v, (1.0 - v))\n        return v * (1.0 - v)\n\nclass ArctanAF(ActivationFunctionBaseClass):\n    def __init__(self):\n        pass\n\n    def GetValue(self, x):\n        return np.arctan(x);\n\n    def GetDerivative(self, x):\n        return 1.0 / (1.0 + np.multiply(x, x))\n", "meta": {"hexsha": "264ce27ab5b29b659014610cd226298e25a08a8e", "size": 1209, "ext": "py", "lang": "Python", "max_stars_repo_path": "legacy/activation_function.py", "max_stars_repo_name": "lonelycorn/machine-learning", "max_stars_repo_head_hexsha": "812b4d4f214dc28463cb87bada4e88d0d0cf4184", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "legacy/activation_function.py", "max_issues_repo_name": "lonelycorn/machine-learning", "max_issues_repo_head_hexsha": "812b4d4f214dc28463cb87bada4e88d0d0cf4184", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "legacy/activation_function.py", "max_forks_repo_name": "lonelycorn/machine-learning", "max_forks_repo_head_hexsha": "812b4d4f214dc28463cb87bada4e88d0d0cf4184", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1875, "max_line_length": 87, "alphanum_fraction": 0.6211745244, "include": true, "reason": "import numpy", "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102524151826, "lm_q2_score": 0.9032941975921684, "lm_q1q2_score": 0.8738560676978095}}
{"text": "import numpy as np\n\ndef median_bins(values, B):\n  #main variables (returns)\n  mean = np.mean(values)\n  stdev = np.std(values)\n  bin_counts = np.zeros((B,)) # init with zeroes - , dtype=np.int\n  n_smaller = 0\n  \n  #aux variables\n  width = 2*stdev / B\n  minval = mean-stdev\n   \n  for value in values: # for all the values in the array\n    binmax = minval\n    \n    if value < minval : #skip this value\n      n_smaller += 1\n    else: # fit into a bin\n      for index in range(B):\n        binmax += width\n        if value < binmax: #values > maxval -> ignored\n          bin_counts[index] += 1\n          break\n  return (mean, stdev, n_smaller, bin_counts)\n\n\ndef median_approx(values, B):\n  median_bins_result = median_bins(values, B)\n  \n  #resuts of bin calculation\n  mean = median_bins_result[0]\n  stdev = median_bins_result[1]\n  n_smaller = median_bins_result[2]\n  bins = median_bins_result[3]\n    \n  #other aux calculations\n  minval = mean - stdev\n  target_total = (len(values)+1)/2\n  width = 2*stdev / B\n  running_total = n_smaller\n  \n  #print(\"minval:\", minval, \"width:\", width, \", running_total/n_smaller: \", running_total)\n  \n  for index in range(len(bins)): #go over every bin\n     running_total += bins[index]\n     #print(\"idx: \", index, \"rt: \", running_total, \", target_total: \", target_total)\n     if running_total >= target_total: \n        return minval + width/2 + index*width\n  return minval + width/2 + index*width\n\n# You can use this to test your functions.\n# Any code inside this `if` statement will be ignored by the automarker.\nif __name__ == '__main__':\n  # Run your functions with the first example in the question.\n  print(median_bins([1, 1, 3, 2, 2, 6], 3))\n  print(median_approx([1, 1, 3, 2, 2, 6], 3)) #2.5\n  \n  # Run your functions with the second example in the question.\n  print(median_bins([1, 5, 7, 7, 3, 6, 1, 1], 4))\n  print(median_approx([1, 5, 7, 7, 3, 6, 1, 1], 4)) #4.50544503131\n  \n  #3rd case\n  print(median_bins([0, 1], 5))\n  print(median_approx([0, 1], 5)) #0.9\n\n  # Pathological case\n  print(median_bins([1, 1, 1000], 5))\n  print(median_approx([1, 1, 1000], 5)) #-42.7464930162\n\n\n", "meta": {"hexsha": "32c52167fdb0603d1c925c91090506e79f15dd04", "size": 2115, "ext": "py", "lang": "Python", "max_stars_repo_path": "wk1/binaprox.py", "max_stars_repo_name": "lokijota/datadrivenastronomymooc", "max_stars_repo_head_hexsha": "175655e5c6450c091534299da6bce6f10a1a3627", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-12-09T18:10:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T16:38:58.000Z", "max_issues_repo_path": "wk1/binaprox.py", "max_issues_repo_name": "lokijota/datadrivenastronomymooc", "max_issues_repo_head_hexsha": "175655e5c6450c091534299da6bce6f10a1a3627", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wk1/binaprox.py", "max_forks_repo_name": "lokijota/datadrivenastronomymooc", "max_forks_repo_head_hexsha": "175655e5c6450c091534299da6bce6f10a1a3627", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-11-09T16:57:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-15T09:11:33.000Z", "avg_line_length": 29.375, "max_line_length": 90, "alphanum_fraction": 0.6453900709, "include": true, "reason": "import numpy", "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138559, "lm_q2_score": 0.9263037252078029, "lm_q1q2_score": 0.873826368176933}}
{"text": "def bsm_call_value(S0, K, T, r, sigma):\n  #Valuation of European call option in BSM model.\n  #Analytical formula.\n  \n  from math import log, sqrt, exp\n  from scipy import stats\n  S0 = float(S0)\n  d1 = (log(S0 / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))\n  d2 = (log(S0 / K) + (r - 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))\n  value = (S0 * stats.norm.cdf(d1, 0.0, 1.0) - K * exp(-r * T) * stats.norm.cdf(d2, 0.0, 1.0))\n  # stats.norm.cdf --> cumulative distribution function\n  # for normal distribution\n  return value\n\nbsm_call_value(S0=10,K=10,T=3./12,r=0.01,sigma=0.1)\n\n# Vega function\ndef bsm_vega(S0, K, T, r, sigma):\n  # Vega of European option in BSM model.\n  from math import log, sqrt\n  from scipy import stats\n  S0 = float(S0)\n  d1 = (log(S0 / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))\n  vega = S0 * stats.norm.cdf(d1, 0.0, 1.0) * sqrt(T)\n  return vega\n\nbsm_vega(10,10,3./12,0.01,0.1)\n\n# Implied volatility function\ndef bsm_call_imp_vol(S0, K, T, r, C0, sigma_est, it=100):\n  for i in range(it):\n    sigma_est -= ((bsm_call_value(S0, K, T, r, sigma_est) - C0)\n    / bsm_vega(S0, K, T, r, sigma_est))\n  return sigma_est\n\nbsm_call_imp_vol(S0=10,K=10,T=3./12,r=0.01,C0=0.3,sigma_est=0.05,it=1000)\n\nimport pandas as pd\nimport os\nos.getcwd()\n\nfilename = 'vstoxx_data_31032014.h5'\n\nwith pd.HDFStore(filename,  mode='r') as h5:\n  futures_data = h5.select('futures_data')\n\nwith pd.HDFStore(filename,  mode='r') as h5:\n  options_data = h5.select('options_data')\n\n#==============================================================================\n# futures_data = pd.read_hdf(filename, 'futures_data')\n# options_data= pd.read_hdf(filename, 'options_data')\n# \n# h5 = pd.HDFStore('vstoxx_data_31032014.h5', 'r')\n# futures_data = h5['futures_data'] # VSTOXX futures data\n# options_data = h5['options_data'] # VSTOXX call option data\n# \n#==============================================================================\n\nh5.close()\n\noptions_data.info()\noptions_data.head()\nfutures_data.head()\noptions_data[['DATE', 'MATURITY', 'TTM', 'STRIKE', 'PRICE']].head()\n\noptions_data['IMP_VOL'] = 0.0\n\nV0 = 17.6639\nr = 0.01\ntol = 0.5 # tolerance level for moneyness\n\nfor option in options_data.index:\n  # iterating over all option quotes\n  forward = futures_data[futures_data['MATURITY'] == \\\n            options_data.loc[option]['MATURITY']]['PRICE'].values[0]\n  # picking the right futures value\n  if (forward * (1 - tol) < options_data.loc[option]['STRIKE'] < forward * (1 + tol)):\n      # only for options with moneyness within tolerance\n      imp_vol = bsm_call_imp_vol(V0, # VSTOXX value\n                                 options_data.loc[option]['STRIKE'],\n                                 options_data.loc[option]['TTM'],\n                                 r, # short rate\n                                 options_data.loc[option]['PRICE'],\n                                 sigma_est=2., # estimate for implied volatility\n                                 it=100)\n      options_data['IMP_VOL'].loc[option] = imp_vol\n\n\nfutures_data['MATURITY']\noptions_data.loc[46170]\noptions_data.loc[46170]['STRIKE']\n\nmaturities = sorted(set(options_data['MATURITY']))\nmaturities\n\nplot_data = options_data[options_data['IMP_VOL'] > 0]\n\n#iterates over all maturities and does the plotting\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nplt.figure(figsize=(16, 12))\nfor maturity in maturities:\n  data = plot_data[options_data.MATURITY == maturity]\n  # select data for this maturity\n  plt.plot(data['STRIKE'], data['IMP_VOL'],label=maturity.date(), lw=1.5)\n  plt.plot(data['STRIKE'], data['IMP_VOL'], 'r.')\n\nplt.grid(True)\nplt.xlabel('strike')\nplt.ylabel('implied volatility of VSTOXX')\nplt.legend()\nplt.show()\n\nkeep = ['PRICE', 'IMP_VOL']\ngroup_data = plot_data.groupby(['MATURITY', 'STRIKE'])[keep]\ngroup_data\n\n# any aggregation since one element in every group\ngroup_data = group_data.sum()\ngroup_data.head(20)\n# check attributes and methods of unknown objects\ndir(group_data)\n#unique MATURITY and STRIKE\ngroup_data.index.levels\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "2f57b6b506a784d93e168f34d2fb50f399dc1b4d", "size": 4033, "ext": "py", "lang": "Python", "max_stars_repo_path": "wordpress-py-scripts/implied vol.py", "max_stars_repo_name": "QuantFinEcon/py-learn", "max_stars_repo_head_hexsha": "7151f01df9f7f096312e43434fe8026d1d7d7828", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T17:13:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T08:55:17.000Z", "max_issues_repo_path": "wordpress-py-scripts/implied vol.py", "max_issues_repo_name": "QuantFinEcon/py-learn", "max_issues_repo_head_hexsha": "7151f01df9f7f096312e43434fe8026d1d7d7828", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-10T20:17:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-10T20:17:55.000Z", "max_forks_repo_path": "wordpress-py-scripts/implied vol.py", "max_forks_repo_name": "QuantFinEcon/py-learn", "max_forks_repo_head_hexsha": "7151f01df9f7f096312e43434fe8026d1d7d7828", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4379562044, "max_line_length": 94, "alphanum_fraction": 0.6260848004, "include": true, "reason": "from scipy", "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224331, "lm_q2_score": 0.9173026601509101, "lm_q1q2_score": 0.8737987805251484}}
{"text": "\"\"\"\nContains various functions for computing statistics over 3D volumes\n\"\"\"\nimport numpy as np\n\ndef Dice3d(a, b):\n    \"\"\"\n    This will compute the Dice Similarity coefficient for two 3-dimensional volumes\n    Volumes are expected to be of the same size. We are expecting binary masks -\n    0's are treated as background and anything else is counted as data\n\n    Arguments:\n        a {Numpy array} -- 3D array with first volume\n        b {Numpy array} -- 3D array with second volume\n\n    Returns:\n        float\n    \"\"\"\n    if len(a.shape) != 3 or len(b.shape) != 3:\n        raise Exception(f\"Expecting 3 dimensional inputs, got {a.shape} and {b.shape}\")\n\n    if a.shape != b.shape:\n        raise Exception(f\"Expecting inputs of the same shape, got {a.shape} and {b.shape}\")\n\n    # TASK: Write implementation of Dice3D. If you completed exercises in the lessons\n    # you should already have it.\n    \n    # From slides (and exericse)\n    # Dice = 2 * intersection(x, y) / sum(x, y)\n    # Where \n    # Intersection = np.sum(a*b)\n    # Note additional logic for scenario where denominator == 0\n    \n    # Convert to binary: here, we're not going to make a distinction between classes beyond \"0\" and \"not 0\"\n    a, b = np.where(a > 0, 1, 0), np.where(b > 0, 1, 0)\n    \n    if (np.sum(a) + np.sum(b)) == 0:\n        return -1\n\n    return (np.sum(a * b) * 2.0) / (np.sum(a) + np.sum(b))\n    \n\ndef Jaccard3d(a, b):\n    \"\"\"\n    This will compute the Jaccard Similarity coefficient for two 3-dimensional volumes\n    Volumes are expected to be of the same size. We are expecting binary masks - \n    0's are treated as background and anything else is counted as data\n\n    Arguments:\n        a {Numpy array} -- 3D array with first volume\n        b {Numpy array} -- 3D array with second volume\n\n    Returns:\n        float\n    \"\"\"\n    if len(a.shape) != 3 or len(b.shape) != 3:\n        raise Exception(f\"Expecting 3 dimensional inputs, got {a.shape} and {b.shape}\")\n\n    if a.shape != b.shape:\n        raise Exception(f\"Expecting inputs of the same shape, got {a.shape} and {b.shape}\")\n\n    # TASK: Write implementation of Jaccard similarity coefficient. Please do not use \n    # the Dice3D function from above to do the computation ;)\n    # <YOUR CODE GOES HERE>\n    \n    # From slides (and exericse)\n    # Jaccard = intersection(x, y) / union(x, y)\n    # Where\n    # Union = sum - intersection\n    # TODO remove Similar logic for denominator == 0  \n    a, b = np.where(a > 0, 1, 0), np.where(b > 0, 1, 0)\n    \n    if ((np.sum(a) + np.sum(b)) - np.sum(a * b)) == 0:\n        return -1\n    \n    return  np.sum(a * b) / ((np.sum(a) + np.sum(b)) - np.sum(a * b))", "meta": {"hexsha": "f25d95b206b604cbabd2eb86f4559c905b5c359e", "size": 2644, "ext": "py", "lang": "Python", "max_stars_repo_path": "section3/src/utils/volume_stats.py", "max_stars_repo_name": "JaredBBowden/nd320-c3-3d-imaging-starter", "max_stars_repo_head_hexsha": "0cddd4a93fe841a4d9762145fbff491907801a3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "section3/src/utils/volume_stats.py", "max_issues_repo_name": "JaredBBowden/nd320-c3-3d-imaging-starter", "max_issues_repo_head_hexsha": "0cddd4a93fe841a4d9762145fbff491907801a3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "section3/src/utils/volume_stats.py", "max_forks_repo_name": "JaredBBowden/nd320-c3-3d-imaging-starter", "max_forks_repo_head_hexsha": "0cddd4a93fe841a4d9762145fbff491907801a3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7894736842, "max_line_length": 107, "alphanum_fraction": 0.6198940998, "include": true, "reason": "import numpy", "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321806, "lm_q2_score": 0.9207896715436483, "lm_q1q2_score": 0.8737532176197894}}
{"text": "### Univariate batch (standard) gradient descent algorithm\n\n### author: Dr. Marko Mitic\n### year 2015\n### contact: miticm@gmail.com\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass BatchGD: #Main class for Univariate Batch Gradient Descent\n      \n    def __init__(self, data):\n        ### data is given in two-column format, first column is input, second column is output\n        self.x=data[:,0]\n        self.y=data[:,1]\n        self.m=len(data[:,0])          \n        \n    def plotdata(self):        \n        ### \n        plt.figure()\n        plt.plot(self.x, self.y, 'ro')                \n        plt.show()\n    \n    def hypothesis(self, theta0, theta1):\n        \"Return univariate hypothesis\"\n        self.t0=theta0\n        self.t1=theta1\n        self.hy=self.t0+self.t1*self.x ##current hypothesis\n        return self.hy\n        \n    def cost_function(self):\n        \"Return Cost function for hypothesis hy(of input x) and output y\"\n        self.J=(1./(2.*self.m))*sum((self.hy-self.y)**2)\n        return self.J\n           \n    def gradientdescent(self,alpha):\n        \"Perform gradient descent algorithm\"\n        self.a=alpha #leaarning rate\n                     \n        temptheta0=self.t0-self.a*(1./self.m)*sum((self.hy-self.y))\n        temptheta1=self.t1-self.a*(1./self.m)*sum(((self.hy-self.y)*self.x))\n        \n        self.t0=temptheta0\n        self.t1=temptheta1\n        return self.t0, self.t1\n        \n    def plothyp(self,col,title):        \n        \"Plot current hypothesis\"\n        plt.figure()\n        plt.plot(self.x, self.y, 'ro')\n        plt.plot(self.x, self.hy, col)\n        #plt.gca().set_xlim(left=0)\n        #plt.gca().set_ylim(bottom=0)\n        plt.title(title)\n        plt.show()\n\n## END CLASS\n\n################################################################################\n\n#import data\ndata = np.loadtxt(\"data_GD.txt\", comments=\"#\", delimiter=\",\", unpack=False)\n\ngd=BatchGD(data)\n## visualize the data\n\ngd.plotdata()\n##starting values for hupothesis hy=theta0+theta1*x\ngd.t0=1.5\ngd.t1=-0.7\n\n#test and plot the starting hypothesis\ngd.hy=gd.hypothesis(gd.t0,gd.t1)\ngd.plothyp('b','Initial hypothesis')\n\n#calculate initial gradient\ngd.J=gd.cost_function()\n\n#define error tolerance:\ntol=5\n\nwhile (gd.J>tol): # of course, you can do this with FOR also :)\n                  #for i in range (0,1000):\n    gd.hy=gd.hypothesis(gd.t0,gd.t1)\n    gd.J=gd.cost_function()   \n    [gd.t0,gd.t1]=gd.gradientdescent(0.002) ##learning rate==0.002    ## interesting results with 0.2 ;)\n\n    print \"Current cost is\", gd.J\n    print 'Parameters Theta0 and Theta1 are {} and {}, respectively' .format(gd.t0, gd.t1)\n    \nprint 'Final parameters Theta0 and Theta1 found by GD are {} and {}, respectively' .format(gd.t0, gd.t1)\ngd.plothyp('k', 'Final hypothesis')\n\n##END", "meta": {"hexsha": "0749c5f1be9f4e2e694e452325bb3fc973aa7b74", "size": 2790, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear_Regression/BatchGradientDescent.py", "max_stars_repo_name": "mmitic/Machine-Learning-algorithms-Python-", "max_stars_repo_head_hexsha": "2f228a88d64b7c2748dfafbe41c0984dcf8923b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-08-09T21:12:51.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-09T21:12:51.000Z", "max_issues_repo_path": "Linear_Regression/BatchGradientDescent.py", "max_issues_repo_name": "mmitic/Machine-Learning-algorithms-Python-", "max_issues_repo_head_hexsha": "2f228a88d64b7c2748dfafbe41c0984dcf8923b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear_Regression/BatchGradientDescent.py", "max_forks_repo_name": "mmitic/Machine-Learning-algorithms-Python-", "max_forks_repo_head_hexsha": "2f228a88d64b7c2748dfafbe41c0984dcf8923b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2015-12-29T13:11:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-12-29T13:11:43.000Z", "avg_line_length": 29.6808510638, "max_line_length": 104, "alphanum_fraction": 0.5860215054, "include": true, "reason": "import numpy", "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.9230391669503405, "lm_q1q2_score": 0.8737457991183278}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Sep  8 17:22:01 2017\r\n\r\n@author: Alan\r\n\"\"\"\r\n\r\n#Black Scholes Model\r\n###############\r\nS = float(input(\"Please enter the stock price :\"))\r\n\r\nK = float(input(\"Please enter the strike price :\"))\r\n\r\nr = float(input(\"Please enter the risk-free rate :\"))\r\n\r\nT = float(input(\"Please enter the maturing time in year :\"))\r\n\r\nt = float(input(\"Please enter the starting time in year :\"))\r\n\r\nD = float(input(\"Please enter the annual dividend yield :\"))\r\n\r\nsigma = float(input(\"Please enter the annualized volatility :\"))\r\n\r\ndef BS_Call_Value():\r\n    \r\n    from math import exp,log,sqrt \r\n    from scipy import stats\r\n\r\n    d1 = (log(S/K ,exp(1)) + ((r - D + (0.5*(sigma**2)))*(T-t))) / (sigma*sqrt(T-t))\r\n    print(\"d1 =\",d1)\r\n    d2 = d1 - (sigma*sqrt(T-t))\r\n    print(\"d2 =\",d2)\r\n    \r\n    Nd1 = stats.norm.cdf(d1, 0.0 ,1.0)\r\n    print(\"N(d1) =\",Nd1)\r\n    \r\n    Nd2 = stats.norm.cdf(d2, 0.0 ,1.0)\r\n    print(\"N(d2) =\",Nd2)\r\n    \r\n    call_value = float((S*exp(-D*(T-t))*Nd1)- (K*exp(-r*(T-t))*Nd2))\r\n    return call_value \r\n\r\nEuropean_Call_Option = BS_Call_Value()\r\nprint(\"European_Call_Option =\",European_Call_Option)\r\n\r\ndef BS_Put_Value():\r\n    \r\n    from math import exp,log,sqrt \r\n    from scipy import stats\r\n   \r\n    d1 = (log(S/K ,exp(1)) + ((r - D + (0.5*(sigma**2)))*(T-t))) / (sigma*sqrt(T-t))\r\n    print(\"d1 =\",d1)\r\n    \r\n    d2 = d1 - (sigma*sqrt(T-t))\r\n    print(\"d2 =\",d2)\r\n    \r\n    N_d1 = stats.norm.cdf(-d1, 0.0 ,1.0)\r\n    print(\"N(-d1) =\",N_d1)\r\n    \r\n    N_d2 = stats.norm.cdf(-d2, 0.0 ,1.0)\r\n    print(\"N(-d2) =\",N_d2)\r\n    \r\n    Put_value = float((K*exp(-r*(T-t))*N_d2)-(S*exp(-D*(T-t))*N_d1))\r\n    return Put_value\r\n\r\nEuropean_Put_Option = BS_Put_Value()\r\nprint(\"European_Put_Option =\",European_Put_Option)\r\n\r\n###################\r\n#Put Call Parity in Black Scholes Model\r\n################### \r\nPut_Call_Parity = round(European_Call_Option - European_Put_Option,2)\r\nprint(\"Put Call Parity =\",Put_Call_Parity)\r\n\r\ndef P_C_Parity():\r\n    \r\n     from math import exp\r\n     \r\n     PV_S = S*exp(-D*(T-t))\r\n     print(\"Present Value of Stock Price =\",PV_S)\r\n     PV_K = K*exp(-r*(T-t))\r\n     print(\"Present Value of Strike Price in Dollar =\",PV_K)\r\n     P_C = round(PV_S - PV_K , 2)\r\n     return P_C\r\n \r\nPut_Call_Parity = P_C_Parity()\r\nprint(\"Put Call Parity =\", Put_Call_Parity)\r\n", "meta": {"hexsha": "9b2b15ea9d89fbe6ca7efcdfcad46f87a3ba04b3", "size": 2329, "ext": "py", "lang": "Python", "max_stars_repo_path": "Black Scholes Model european call and put .py", "max_stars_repo_name": "ALANHENG/Robot", "max_stars_repo_head_hexsha": "34f9aaeeb87ef53556442e7a04d6ba3ee387deb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Black Scholes Model european call and put .py", "max_issues_repo_name": "ALANHENG/Robot", "max_issues_repo_head_hexsha": "34f9aaeeb87ef53556442e7a04d6ba3ee387deb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Black Scholes Model european call and put .py", "max_forks_repo_name": "ALANHENG/Robot", "max_forks_repo_head_hexsha": "34f9aaeeb87ef53556442e7a04d6ba3ee387deb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-18T15:51:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T15:51:23.000Z", "avg_line_length": 26.4659090909, "max_line_length": 85, "alphanum_fraction": 0.5689136969, "include": true, "reason": "from scipy", "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399086356109, "lm_q2_score": 0.9005297887874625, "lm_q1q2_score": 0.8737299399967936}}
{"text": "import math\nimport numpy as np\n\n__DEBUG__ = False\n\n\ndef compute_entropy(values):\n    \"\"\"\n    Given values for a random variable, calculate its entropy.\n    :param values: RV\n    :return: entropy of random variable with values outcome\n    \"\"\"\n    counts = {}\n    for val in values:\n        try:\n            counts[val] += 1\n        except KeyError:\n            counts[val] = 1\n    entropy = 0\n    for key, value in counts.items():\n        prob = counts[key] / len(values)\n        entropy += -1 * prob * math.log(prob, 2)\n    return entropy\n\n\ndef compute_expected_info(data, feature, target):\n    \"\"\"\n    Compute expected info for a feature given the observation data\n    :param data: training data\n    :param feature: feature name to process\n    :param target: target variable\n    :return: expected info\n    \"\"\"\n    data_size = data.shape[0]\n    expected_info = 0\n    for attr_value in data[feature].unique():\n        values = data.loc[data[feature] == attr_value][target].values\n        expected_info += compute_entropy(values) * len(values) / data_size\n    return expected_info\n\n\ndef get_best_feature(data, target):\n    \"\"\"\n    Get best feature that gives the purest node!\n    :param data: training data\n    :param target: target variable\n    :return: feature name\n    \"\"\"\n    features = list(set(data.columns) - set([target]))\n    exp_info_values = []\n    for feature in features:\n        exp_info = compute_expected_info(data, feature, target)\n        exp_info_values.append(exp_info)\n        if __DEBUG__:\n            print(\"feature: {} --> info: {}\".format(feature, exp_info))\n    best_fet_inx = np.argmin(np.array(exp_info_values))\n    if __DEBUG__:\n        print(\"feature: {} --> info: {}\".format(features[best_fet_inx], min(exp_info_values)))\n    return features[best_fet_inx]\n", "meta": {"hexsha": "d285acb09bccdeccd1a62766570dc759f4f7b1bf", "size": 1785, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/utilities.py", "max_stars_repo_name": "kjahan/decision-trees", "max_stars_repo_head_hexsha": "c7cc585a13ff7cb94b9ea8f74bb5679504a41cdb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utilities.py", "max_issues_repo_name": "kjahan/decision-trees", "max_issues_repo_head_hexsha": "c7cc585a13ff7cb94b9ea8f74bb5679504a41cdb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities.py", "max_forks_repo_name": "kjahan/decision-trees", "max_forks_repo_head_hexsha": "c7cc585a13ff7cb94b9ea8f74bb5679504a41cdb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.75, "max_line_length": 94, "alphanum_fraction": 0.6442577031, "include": true, "reason": "import numpy", "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214511730025, "lm_q2_score": 0.9059898172105135, "lm_q1q2_score": 0.8736654152804056}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\nN = int(input(\"Pick a number: \"))\n\nn, a, sum1, m, b, sum2 = 1, 0, 0, N, 0, 0\n\n\nwhile (n<=N):\n    a = 1/n\n    sum1+=a\n    n = n+1\n    \nwhile (m>=1):\n    b = 1/m\n    sum2+=b\n    m = m-1\n    \nerror = (sum1 - sum2)/(np.absolute(sum1)+np.absolute(sum2))\nprint(\"For N = :\",N,\", the error is: \",error)\n\nN1=1\nNs=[]\nErrors=[]\n\nwhile N1<=N:\n\n    n1, a1, sum11, m1, b1, sum21 = 1, 0, 0, N1, 0, 0\n\n\n    while (n1<=N1):\n        a1 = 1/n1\n        sum11+=a1\n        n1 = n1+1\n    while (m1>=1):\n        b1 = 1/m1\n        sum21+=b1\n        m1 = m1-1\n\n    Ns.append(N1)\n    error1 = (sum11 - sum21)/(np.absolute(sum11)+np.absolute(sum21))\n    Errors.append(error1)\n    N1=N1+1\n    \nplt.plot(Ns,Errors,'r-')\nplt.xlabel(\"N\")\nplt.ylabel(\"Error(x10^-16)\")\nplt.title(\"N vs. Error\")\nplt.show()    \n    \nprint(\"The down summation is more precise because the error of the number is proportional to the number you are summing, therefore as the number decreases, there is less error, versus starting with a small number, and adding more error for every summation.\")\n    ", "meta": {"hexsha": "d0361d8b9d5a81ac3dd44054fea2bb9ded116ac4", "size": 1177, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week 02/summationerror_BSW.py", "max_stars_repo_name": "bswood9321/PHYS-3210", "max_stars_repo_head_hexsha": "d780cac166688338ce91099cba4a4f6628430647", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week 02/summationerror_BSW.py", "max_issues_repo_name": "bswood9321/PHYS-3210", "max_issues_repo_head_hexsha": "d780cac166688338ce91099cba4a4f6628430647", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week 02/summationerror_BSW.py", "max_forks_repo_name": "bswood9321/PHYS-3210", "max_forks_repo_head_hexsha": "d780cac166688338ce91099cba4a4f6628430647", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6166666667, "max_line_length": 258, "alphanum_fraction": 0.577740017, "include": true, "reason": "import numpy", "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.9399133502467731, "lm_q1q2_score": 0.8735934364542064}}
{"text": "import numpy as np\n# Q. 11. Get the common items between a and b\na = np.array([1,2,3,2,3,4,3,4,5,6])\nb = np.array([7,2,10,2,7,4,9,4,9,8])\nc = np.intersect1d(a,b)\n# print(c)\n# 12. How to remove from one array those items that exist in another?\na = np.array([1,2,3,4,5])\nb = np.array([5,6,7,8,9])\nc = np.setdiff1d(a,b)\n# print(c)\n# 13. How to get the positions where elements of two arrays match?\na = np.array([1,2,3,2,3,4,3,4,5,6])\nb = np.array([7,2,10,2,7,4,9,4,9,8])\n# print(np.where(a==b))\n# 14. How to extract all numbers between a given range from a numpy array?\n# Q. Get all items between 5 and 10 from a\na = np.array([2, 6, 1, 9, 10, 3, 27])\n# method 1\nprint(a[(a >= 5) & (a <= 10)])\n# method 2\nmask = np.where((a>=5) & (a<=10))\nprint(a[mask])\n# method 3\ntruthy_mask = np.logical_and(a>=5, a<=10)\nindex_mask = np.where(truthy_mask)\nprint(a[index_mask])\n# 15. How to make a python function that handles scalars to work on numpy arrays?\n# Q. Convert the function maxx that works on two scalars, to work on two arrays.\na = np.array([5, 7, 9, 8, 6, 4, 5])\nb = np.array([6, 3, 4, 8, 9, 7, 1])\ndef pair_max(arr_a, arr_b):\n    res = np.empty_like(arr_a)\n    for i, (a, b) in enumerate(zip(arr_a, arr_b)):\n        if a >= b:\n            res[i] = a\n        else:\n            res[i] = b\n    return res\nprint(pair_max(a, b))\n# using the vectorize method\ndef maxx(x, y):\n    \"\"\"Get the maximum of two items\"\"\"\n    if x >= y:\n        return x\n    else:\n        return y\npair_max = np.vectorize(maxx, otypes=[int])\nprint(pair_max(a, b))\n# 16. How to swap two columns in a 2d numpy array?\n# Q. Swap columns 1 and 2 in the array arr.\narr = np.arange(9).reshape(3,3)\nprint(arr)\nswapped_arr = np.empty_like(arr)\nswapped_arr[:,0] = arr[:,0]\nswapped_arr[:,1] = arr[:,2]\nswapped_arr[:,2] = arr[:,1]\nprint(swapped_arr)\n# better method\nswapped_arr = arr[:, [0,2,1]]\nprint(swapped_arr)\n# 17. How to swap two rows in a 2d numpy array?\n# Q. Swap rows 1 and 2 in the array arr:\narr = np.arange(9).reshape(3,3)\nswapped_arr = arr[[0,2,1],:]\nprint(swapped_arr)\n# 18. How to reverse the rows of a 2D array?\n# Q. Reverse the rows of a 2D array arr.\n# Input\narr = np.arange(9).reshape(3,3)\nprint(arr)\nreversed_rows_arr = arr[[2,1,0],:]\nprint(reversed_rows_arr)\n# better method, using arr[start:stop:step]\narr = np.arange(9).reshape(3,3)\nreversed_rows_arr = arr[::-1]\nprint(reversed_rows_arr)\n# 20. How to create a 2D array containing random floats between 5 and 10?\n# Q. Create a 2D array of shape 5x3 to contain random decimal numbers between 5 and 10.\n\narr = np.random.uniform(low=5, high=11, size=(5,3))\nprint(arr) \nprint(arr)\n\n\n# 21. How to print only 3 decimal places in python numpy array?\n# Q. Print or show only 3 decimal places of the numpy array rand_arr.\n\nrand_arr = np.random.random((5,3))\n\n# solution, use: numpy.set_printoptions(precision=None...) \n# #from https://het.as.utexas.edu/HET/Software/Numpy/reference/generated/numpy.set_printoptions.html\n\nnp.set_printoptions(precision=3)\nprint(rand_arr)\n\n# 22. How to pretty print a numpy array by suppressing the scientific notation (like 1e10)?\n# Q. Pretty print rand_arr by suppressing the scientific notation (like 1e10)\n\n# Create the random array\nnp.random.seed(100)\nrand_arr = np.random.random([3,3])/1e3\n\n# Desired Output (similar to):\n#> array([[ 0.000543,  0.000278,  0.000425],\n#>        [ 0.000845,  0.000005,  0.000122],\n#>        [ 0.000671,  0.000826,  0.000137]])\nDefine branch protection rules to disable force pushing, prevent branches from being deleted, and optionally require status checks before merging. New to branch protection rules? Learn more.\nnp.set_printoptions(suppress=True)\nprint(rand_arr)\n\n# 23. How to limit the number of items printed in output of numpy array?\n# Q. Limit the number of items printed in python numpy array a to a maximum of 6 elements.\n\na = np.arange(15)\n#> array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])\n# Desired Output:\n#> array([ 0,  1,  2, ..., 12, 13, 14])\n\nnp.set_printoptions(threshold=6)\nprint(a)\n\n# 24. How to print the full numpy array without truncating\n# Q. Print the full numpy array a without truncating.\n\n# Input:\n\n\na = np.arange(15)\nnp.set_printoptions(threshold=sys.maxsize)\nprint(a)\n#> array([ 0,  1,  2, ..., 12, 13, 14])\n\n\n# 25. How to import a dataset with numbers and texts keeping the text intact in python numpy?\n# Q. Import the iris dataset keeping the text intact.\n\nimport requests\nimport io\n\nlink = \"https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\"\n\nresponse = requests.get(link, verify=False)\nresponse.raise_for_status()\ndata = np.load(io.BytesIO(response.content))  # Works!\n\n# data = np.loadtxt(link)\n\nprint(data)\n# Not sure if this one is working because I can't run it on ONS work machine\n\n# LOOKS LIKE np.genfromtxt() would have been a better solution\n\n# 26. How to extract a particular column from 1D array of tuples?\n# Q. Extract the text column species from the 1D iris imported in previous question.\n\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris_1d = np.genfromtxt(url, delimiter=',', dtype=None)\n\ntext_col = np.array([row[4] for row in iris_1d])\n\n# 27. How to convert a 1d array of tuples to a 2d numpy array?\n# Q. Convert the 1D iris to 2D array iris_2d by omitting the species text field.\n\n# running iris_1d.dtype.names gives us the col names\n# The names can be used to access items in the np.void (like a tuple)\n\n# HACKY AS HELL solution using nested list comprehension and unpacking the list of voids\niris_2d = np.array([[*void[['f0', 'f1', 'f2', 'f3']]] for void in iris_1d])\n\n# Given solution using .tolist() method on the np.voids\n\niris_2d = np.array([row.tolist()[:4] for row in iris_1d])", "meta": {"hexsha": "ebe06ea435ff71db621662cbcb71acff3be66348", "size": 5705, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_flex.py", "max_stars_repo_name": "james-westwood/numpy_flex", "max_stars_repo_head_hexsha": "d1e12e96ace53a05276dc29bbe37af60fb8572c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy_flex.py", "max_issues_repo_name": "james-westwood/numpy_flex", "max_issues_repo_head_hexsha": "d1e12e96ace53a05276dc29bbe37af60fb8572c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy_flex.py", "max_forks_repo_name": "james-westwood/numpy_flex", "max_forks_repo_head_hexsha": "d1e12e96ace53a05276dc29bbe37af60fb8572c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9768786127, "max_line_length": 190, "alphanum_fraction": 0.6878177038, "include": true, "reason": "import numpy", "num_tokens": 1857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.9441768647558424, "lm_q1q2_score": 0.8735807142254889}}
{"text": "import numpy as np\nfrom numpy.linalg import inv\nimport matplotlib.pyplot as plt\n\n# Load data\nx_train = np.load('x_train.npy')\ny_train = np.load('y_train.npy')\nx_test = np.load('x_test.npy')\ny_test = np.load('y_test.npy')\n\n\ndef trace_for_all_data(x_train, y_train, vector_like=True):\n    if vector_like:\n        for i in range(len(x_train)):\n            yield (x_train[i]).reshape(2, 1), y_train[i]\n    else:\n        for i in range(len(x_train)):\n            yield x_train[i], y_train[i]\n\n# 1. Compute the mean vectors mi, (i=1,2) of each 2 classes\n\n\ndef get_mi(x_train, y_train):\n    n_1 = 0\n    # sum_1 = np.zeros(2)\n    # sum_2 = np.zeros(2)\n    # for i, e in enumerate(y_train):\n    #     print(f'dot: ({x_train[i][0]}, {x_train[i][1]}) -> {y_train[i]}')\n    #     if e == 0:\n    #         sum_1 += x_train[i]\n    #         n_1 += 1\n    #     else:\n    #         sum_2 += x_train[i]\n    #     print(f'update sum: s1= {sum_1}, s2= {sum_2}')\n    # return sum_1/ n_1, sum_2/ (len(x_train) - n_1)\n\n    sum_ = np.zeros((2, 2, 1))\n    for data in trace_for_all_data(x_train, y_train):\n        sum_[data[1]] += data[0]\n        n_1 += data[1] == 0\n        # print(f'data: {data}')\n        # print(f'update sum: s1= {sum_[0]}, s2= {sum_[1]}')\n        # print(f'n_1: {n_1}')\n    return sum_[0] / n_1, sum_[1] / (len(x_train) - n_1)\n    # training data:\n    # mean vector of class 1: [ 1.3559426  -1.34746216]\n    # mean vector of class 2: [-1.29735587  1.29096203]\n\nm1, m2 = get_mi(x_train, y_train)\nprint(f\"mean vector of class 1:\\n{m1}\\nmean vector of class 2:\\n{m2}\\n\")\n# =================================================================\n\n# 2. Compute the Within-class scatter matrix SW\n\n\ndef get_SW(x_train, y_train, m=None):\n    '''\n    m: [ m1: 2x1 vector, m2: 2x1 vector ]\n    '''\n    if m is None:\n        m = get_mi(x_train, y_train)\n\n    # Si = sum( (xi - m)(xi - m)T )\n    # 2x2 matrix, if xi is 2-D data\n    S = np.zeros((2, 2, 2))\n    for data in trace_for_all_data(x_train, y_train):\n        sub = data[0] - m[data[1]]\n        S[data[1]] += sub @ sub.T\n        # print(f'   X: {data[0]}')\n        # print(f'mean: {m[data[1]]}')\n        # print(f' sub: {sub}')\n        # print(f'sub @ subT: {sub@sub.T}')\n        # print(f'S[{data[1]}]: {S[data[1]]}')\n    return S[0] + S[1]\n\nsw = get_SW(x_train, y_train, (m1, m2))\nassert sw.shape == (2, 2)\nprint(f\"Within-class scatter matrix SW:\\n{sw}\\n\")\n# =================================================================\n\n# 3. Compute the Between-class scatter matrix SB\n\n\ndef get_SB(m1, m2):\n    sub = m2 - m1\n    return sub @ sub.T\n\nsb = get_SB(m1, m2)\nassert sb.shape == (2, 2)\nprint(f\"Between-class scatter matrix SB:\\n{sb}\\n\")\n# =================================================================\n\n# 4. Compute the Fisher’s linear discriminant\n\n\ndef get_W(SW, m1, m2):\n    w = inv(SW) @ (m2 - m1)\n    # |w| = sqrt( wTw )\n    # print(f'origin w: {w}')\n    w = w / (w.T @ w)**(1/2)\n    # print(f' after w: {w}')\n    return w\n\nw = get_W(sw, m1, m2)\nassert w.shape == (2, 1)\nprint(f\" Fisher’s linear discriminant:\\n{w}\\n\")\n# =================================================================\n\n# 5. Project the test data by linear discriminant\n#    to get the class prediction by nearest-neighbor rule\n#    and calculate the accuracy score\n\n\ndef predict(x_train, y_train, w, x_test):\n    '''\n    x_test: [\n        [x0, x1],\n        [x0, x1],\n        ...\n    ]\n    y_test: [\n        1, 0, 0, 1, 1, ...\n    ]\n    w: [\n        [w0],\n        [w1]\n    ]\n    return [\n        1, 0, 0, 1, 1\n    ]\n    x_train 投影到 w 上的長度(正負)差異\n    x_train @ w = [\n        [1.342],\n        [-0.023],\n        ...\n    ]\n    '''\n    x_train_project = x_train @ w\n    x_test_project = x_test @ w\n\n    check_table = np.append(x_train_project,\n                            y_train.reshape((-1, 1)),\n                            axis=1)\n    # check table:\n    # [[project val, catgory],\n    #  [project val, catgory]]\n    # print(check_table)\n\n    # sort by [proj val, ]\n    check_table = check_table[np.argsort(check_table[:, 0])]\n    # find no. of x_test( by project val to w )\n    search_result = np.searchsorted(check_table[:, 0], x_test_project)\n    # [1 3 5], 2 -> place in pos \"1\" -> check distance to \"0\" and \"1\"\n    # print(f'check:\\n{check_table}')\n    # print(f'resul:\\n{search_result}')\n\n    y_pred = []\n    for i, e in enumerate(search_result):\n        e = e[0]  # U 夠麻煩...\n        # x_test[i] between check table [e-1] to [e]\n        # print(f'{x_test_project[i][0]} - {check_table[e-1][0]} vs.')\n        # print(f'{check_table[e][0]} - {x_test_project[i][0]}')\n        if x_test_project[i][0] - check_table[e-1][0] < \\\n           check_table[e][0] - x_test_project[i][0]:\n            # if distance to e-1 is closer than\n            #    distance to e\n            y_pred += [check_table[e-1][1]]\n        else:\n            y_pred += [check_table[e][1]]\n    return np.array(y_pred)\n\ny_pred = predict(x_train, y_train, w, x_test)\n\n\ndef accuracy_score(y_test, y_pred):\n    '''\n    y_test: [1, 0, 0, ...]\n    y_pred: [1, 1, 0, ...]\n\n    correct / all\n    (y_test == y_pred) / all\n\n    not correct: abs(y_test - y_pred)\n    (all-abs(y_test-y_pred)) / all\n    '''\n    n = len(y_test)\n    return (n-sum(abs(y_test-y_pred))) / n\n\nacc = accuracy_score(y_test, y_pred)\nprint(f\"Accuracy of test-set {acc}\")\n# =================================================================\n\n# 6. Plot the\n# 1) best projection line on the training data and show the slope\n#    and intercept on the title\n#    (you can choose any value of intercept for better visualization)\n# 2) colorize the data with each class\n# 3) project all data points on your projection line.\n# Your result should look like this image\n\n\ndef partition(x_train, y_train):\n    '''\n    return [\n        [x0, x1],\n        [x0, x1],\n        ...\n        [x0, x1]\n    ]\n    '''\n    collect_0 = []\n    collect_1 = []\n    for x, y in trace_for_all_data(x_train, y_train, vector_like=False):\n        if y == 0:\n            # plt.plot([x[0]], [x[1]], 'b.')\n            collect_0 += [x]\n        else:\n            # plt.plot([x[0]], [x[1]], 'r.')\n            collect_1 += [x]\n    collect_0 = np.array(collect_0)\n    collect_1 = np.array(collect_1)\n    return collect_0, collect_1\n\n\ndef Plot_point(x_train, y_train):\n    collect_0, collect_1 = partition(x_train, y_train)\n    # plt.plot(collect_0[0][0], collect_0[0][1], 'b.')\n    plt.plot(collect_0.T[0], collect_0.T[1], 'bo')\n    plt.plot(collect_1.T[0], collect_1.T[1], 'ro')\n\n\ndef Plot_line(w, b, from_x, to_x):\n    # y_dist / x_dist\n    a = w[1][0] / w[0][0]\n    # y = a x + b\n    plt.title(f'ProjectionLine: w={a}, b={b}')\n    plt.plot(\n        [from_x, to_x],\n        [a * from_x + b, a * to_x + b],\n        'k-'\n    )\n\n\ndef Plot_point_on_line(x_train, y_train, w, b, from_x, to_x):\n    collect_0, collect_1 = partition(x_train, y_train)\n    # x0, x1 = collect_0[0]\n    # project = (x0*w[0][0] + (x1-b)*w[1][0]) * w\n    # point = [project[0][0], project[1][0] + b]\n    # plt.plot(*point, 'b.')\n\n    # plt.plot([x0, point[0]], [x1, point[1]], 'b--')\n    # # a = (x1-x0)*w[0] + (point[1] - point[0])*w[1]\n    # print()\n\n    # ================================================\n\n    c_0 = []\n    c_1 = []\n    pairs = []\n    for x0, x1 in collect_0:\n        # project = np.array([[x0], [x1-b]]).dot(w) * w\n        project = (x0*w[0][0] + (x1-b)*w[1][0]) * w\n        point = [project[0][0], project[1][0] + b]\n        c_0 += [point]\n        pairs += [[[x0, x1], point]]\n    for x0, x1 in collect_1:\n        # project = np.array([[x0], [x1-b]]).dot(w) * w\n        project = (x0*w[0][0] + (x1-b)*w[1][0]) * w\n        point = [project[0][0], project[1][0] + b]\n        c_1 += [point]\n        pairs += [[[x0, x1], point]]\n\n    c_0 = np.array(c_0)\n    c_1 = np.array(c_1)\n    pairs = np.array(pairs)\n\n    plt.plot(c_0.T[0], c_0.T[1], 'bo')\n    plt.plot(c_1.T[0], c_1.T[1], 'ro')\n    for p1, p2 in pairs:\n        plt.plot([p1[0], p2[0]], [p1[1], p2[1]], 'c:')\n\n\ndef Plot_all(x_train, y_train, w, b, from_x, to_x):\n    # set x, y size\n    plt.figure(figsize=(8, 8), dpi=80)\n    plt.xlim(-6, 4)\n    plt.ylim(-5, 5)\n\n    Plot_point(x_test, y_test)\n    Plot_line(**line_information)\n    Plot_point_on_line(x_test, y_test, **line_information)\n    plt.show()\n\nline_information = {\n    'w': w,\n    'b': -3.5,\n    'from_x': -6,\n    'to_x': 4\n}\n\nPlot_all(x_train, y_train, **line_information)\n", "meta": {"hexsha": "7218f1dcd0143872d20e951b2410fd5a7294dcbd", "size": 8380, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW2/309553018_HW 2.py", "max_stars_repo_name": "clashroyaleisgood/Course_PatternRecognition", "max_stars_repo_head_hexsha": "1bc9eee50ca167012f3bd4c5cd6d9a2fb9a26aa9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW2/309553018_HW 2.py", "max_issues_repo_name": "clashroyaleisgood/Course_PatternRecognition", "max_issues_repo_head_hexsha": "1bc9eee50ca167012f3bd4c5cd6d9a2fb9a26aa9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW2/309553018_HW 2.py", "max_forks_repo_name": "clashroyaleisgood/Course_PatternRecognition", "max_forks_repo_head_hexsha": "1bc9eee50ca167012f3bd4c5cd6d9a2fb9a26aa9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7483443709, "max_line_length": 75, "alphanum_fraction": 0.512052506, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639669551474, "lm_q2_score": 0.8991213684847577, "lm_q1q2_score": 0.8735539235391919}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 23 11:20:19 2020\n\n@author: Ruben Andre Barreiro\n\"\"\"\n\n# Import NumPy Python's Library\nimport numpy as np\n\n# Import Matplotlib Python's Library\nimport matplotlib.pyplot as plt\n\n\n# Load the Matrix with the Polynomial Data\nmat = np.loadtxt('../files/polydata.csv',delimiter=';')\n\n\n# Set the X values, from the Polynomial Data\nx = mat[:,0]\n\n# Set the Y values, from the Polynomial Data\ny = mat[:,1]\n\n\n# Set the Coefficients, of Degree 3\ncoefs_3 = np.polyfit(x,y,3)\n\n# Set the Coefficients, of Degree 15\ncoefs_15 = np.polyfit(x,y,15)\n\n\n# Set the Pixels, for the Linear Space\npxs = np.linspace(0,max(x),100)\n\n\n# Fit a 3rd Degree Polynomial function\npoly_3 = np.polyval(coefs_3,pxs)\n\n# Fit a 15th Degree Polynomial function\npoly_15 = np.polyval(coefs_15,pxs)\n\n\n# Create a Figure for Plotting\nplt.figure(figsize=(12, 8))\n\n# Plot the points of the Polynomial data\nplt.plot(x,y,'or')\n\n\n# Plot the Fitted 3rd Degree Polynomial Function\nplt.plot(pxs,poly_3,'-')\n\n# Plot the Fitted 15th Degree Polynomial Function\nplt.plot(pxs,poly_15,'-')\n\n\n# Set the Axis for the Plotting Chart\nplt.axis([0,max(x),-1.5,1.5])\n\n\n# Set the Title for the Plotting Chart\n#plt.title('Degree: 3')\n#plt.title('Degree: 15')\nplt.title('Degree: 3 and 15')\n\n# Save a figure for the Plotting of the Polynomial data points\n# NOTE: This needs to be done always after the plot function\n#       and before the close function\n#plt.savefig('../files/imgs/1.6-exercise-2-coef-3.png')\n#plt.savefig('../files/imgs/1.6-exercise-2-coef-15.png')\nplt.savefig('../files/imgs/1.6-exercise-2-coefs-3-and-15.png')\n\n\n# Close the Figure for Plotting\nplt.close()\n\n\n\n# Print the Coefficients of the 3rd Degree Polynomial Function\nprint('\\n')\nprint('The Coefficients of the 3rd Degree Polynomial Function:')\nprint(coefs_3)\n\n\n# Print the Coefficients of the 15th Degree Polynomial Function\nprint('\\n')\nprint('The Coefficients of the 15th Degree Polynomial Function:')\nprint(coefs_15)\n\n\n\n# Exercise 1.6.1: \n# Q: What is the hypothesis class you are using in each case\n#    (degree 3 and degree 15)?\n# A: Degree 3: A polynomial curve of degree 3\n#    Degree 15: A polynomial curve of degree 15\n    \n\n# Exercise 1.6.2: \n# Q: What is the corresponding model for each hypothesis class?\n# A: Degree 3: y = θ_{1}x^{3} + θ_{2}x^{2} + θ_{3}x + θ_{4}\n#    Degree 15: y = θ_{1}x^{15} + θ_{2}x^{14} + θ_{3}x^{13} + θ_{4}x^{12} +\n#                 + θ_{5}x^{11} + θ_{6}x^{10} + θ_{7}x^{9} + θ_{8}x^{8} + \n#                 + θ_{9}x^{7} + θ_{10}x^{6} + θ_{11}x^{5} + θ_{12}x^{4} + \n#                 + θ_{13}x^{3} + θ_{14}x^{2} + θ_{15}x + θ_{16}\n    \n\n# Exercise 1.6.3: \n# Q: What is the hypothesis in each case?\n# A: Degree 3:  [ θ_{1} = 0.12831139 ; θ_{2} = -1.24583487 ;\n#                 θ_{3} = 3.01638739 ; θ_{4} = -1.10432872 ]\n#    Degree 15: [ θ_{1} = -1.16565156e-03 ; θ_{2} = 5.94797587e-02 ;\n#                 θ_{3} = -1.39485584e+00 ; θ_{4} = 1.99433035e+01 ;\n#                 θ_{5} = -1.94455094e+02 ; θ_{6} = 1.36991372e+03 ;\n#                 θ_{7} = -7.20494944e+03 ; θ_{8} = 2.88096907e+04 ;\n#                 θ_{9} = -8.82893589e+04 ; θ_{10} = 2.07259302e+05 ;\n#                 θ_{11} = -3.69289141e+05 ; θ_{12} = 4.89713241e+05 ;\n#                 θ_{13} = -4.66923307e+05 ; θ_{14} = 3.01463118e+05 ;\n#                 θ_{15} = -1.17541384e+05 ; θ_{16} = 2.08092837e+04 ]\n\n\n# Exercise 1.6.4: \n# Q: How was each hypothesis chosen?\n# A: Instantiating the parameters' vector (theta), representing the vector of\n#    all theta_{1}; ... ; theta_{n} parameters.\n#    The probability of the data given the hypothesis is\n#    the likelihood of the hypothesis.\n#    The best hypothesis is the one with the best (or maximum) likelihood\n#    However, in some cases, increasing too much the degree of\n#    a Polynomial Curve, can lead to not a good prediction of future values,\n#    because the range of Polynomial Curve is very stricted to the data used\n#    So, a good idea is to separate the global set in two subsets:\n#    1) Training Set: The subset for training the Model;\n#    2) Test Set: The subset for test the Model and predict the future values;", "meta": {"hexsha": "c3d7fc6f77db5a4c049bd534b71cfc716361ad33", "size": 4136, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/tutorial-1/1.6-exercise-2/exercise-2.py", "max_stars_repo_name": "rubenandrebarreiro/fct-nova-machine-learning-labs", "max_stars_repo_head_hexsha": "3ad34c4f49d7acfef04c757dc3317da6c717c8c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-06-29T14:19:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T18:30:03.000Z", "max_issues_repo_path": "tutorials/tutorial-1/1.6-exercise-2/exercise-2.py", "max_issues_repo_name": "rubenandrebarreiro/fct-nova-machine-learning-labs", "max_issues_repo_head_hexsha": "3ad34c4f49d7acfef04c757dc3317da6c717c8c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/tutorial-1/1.6-exercise-2/exercise-2.py", "max_forks_repo_name": "rubenandrebarreiro/fct-nova-machine-learning-labs", "max_forks_repo_head_hexsha": "3ad34c4f49d7acfef04c757dc3317da6c717c8c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.637037037, "max_line_length": 78, "alphanum_fraction": 0.6416827853, "include": true, "reason": "import numpy", "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813476288299, "lm_q2_score": 0.9136765145991261, "lm_q1q2_score": 0.8734577057232848}}
{"text": "## 3. Bikesharing distribution ##\n\nimport pandas\nbikes = pandas.read_csv(\"bike_rental_day.csv\")\nprob_over_5000 = bikes[bikes[\"cnt\"] > 5000].shape[0] / bikes.shape[0]\n\n## 4. Computing the distribution ##\n\nimport math\n\n# Each item in this list represents one k, starting from 0 and going up to and including 30.\noutcome_counts = list(range(31))\ndef find_probability(N, k, p, q):\n    # Find the probability of any single combination.\n    term_1 = p ** k\n    term_2 = q ** (N-k)\n    combo_prob = term_1 * term_2\n    \n    # Find the number of combinations.\n    numerator = math.factorial(N)\n    denominator = math.factorial(k) * math.factorial(N - k)\n    combo_count = numerator / denominator\n    \n    return combo_prob * combo_count\n\noutcome_probs = [find_probability(30, i, .39, .61) for i in outcome_counts]\n\n## 5. Plotting the distribution ##\n\nimport matplotlib.pyplot as plt\n\n# The most likely number of days is between 10 and 15.\nplt.bar(outcome_counts, outcome_probs)\nplt.show()\n\n## 6. Simplifying the computation ##\n\nimport scipy\nfrom scipy import linspace\nfrom scipy.stats import binom\n\n# Create a range of numbers from 0 to 30, with 31 elements (each number has one entry).\noutcome_counts = linspace(0,30,31)\ndist = binom.pmf(outcome_counts,30,0.39)\nplt.bar(outcome_counts, dist)\nplt.show()\n\n## 8. Computing the mean of a probability distribution ##\n\ndist_mean = None\ndist_mean = 30 * .39\n\n## 9. Computing the standard deviation ##\n\ndist_stdev = None\ndist_stdev = (30*0.39*0.61)** (1/2)\n\n## 10. A different plot ##\n\n# Enter your answer here.\nimport scipy\nfrom scipy import linspace\nfrom scipy.stats import binom\noutcome_counts = linspace(0,10,11)\ndist = binom.pmf(outcome_counts,10,0.39)\nplt.bar(outcome_counts,dist)\nplt.show()\noutcome_counts = linspace(0,100,101)\ndist = binom.pmf(outcome_counts,100,0.39)\nplt.bar(outcome_counts,dist)\nplt.show()\n\n\n## 11. The normal distribution ##\n\n# Create a range of numbers from 0 to 100, with 101 elements (each number has one entry).\noutcome_counts = scipy.linspace(0,100,101)\n\n# Create a probability mass function along the outcome_counts.\noutcome_probs = binom.pmf(outcome_counts,100,0.39)\n\n# Plot a line, not a bar chart.\nplt.plot(outcome_counts, outcome_probs)\nplt.show()\n\n## 12. Cumulative density function ##\n\noutcome_counts = linspace(0,30,31)\noutcome_probs = binom.cdf(outcome_counts,30,0.39)\nplt.plot(outcome_counts, outcome_probs)\nplt.show()\n\n## 14. Faster way to calculate likelihood ##\n\nleft_16 = None\nright_16 = None\n\nleft_16 = binom.cdf(16,30,0.39)\nright_16 = 1 - left_16", "meta": {"hexsha": "ae438125a5fb1ad0a5b24ac0c6c24b408606df96", "size": 2530, "ext": "py", "lang": "Python", "max_stars_repo_path": "Probability Statistics Intermediate/Probability distributions-135.py", "max_stars_repo_name": "vipmunot/Data-Analysis-using-Python", "max_stars_repo_head_hexsha": "34586d8cbbc336508c4a7a68abe14944f1096252", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Probability Statistics Intermediate/Probability distributions-135.py", "max_issues_repo_name": "vipmunot/Data-Analysis-using-Python", "max_issues_repo_head_hexsha": "34586d8cbbc336508c4a7a68abe14944f1096252", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Probability Statistics Intermediate/Probability distributions-135.py", "max_forks_repo_name": "vipmunot/Data-Analysis-using-Python", "max_forks_repo_head_hexsha": "34586d8cbbc336508c4a7a68abe14944f1096252", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5555555556, "max_line_length": 92, "alphanum_fraction": 0.7288537549, "include": true, "reason": "import scipy,from scipy", "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558706, "lm_q2_score": 0.9073122288794594, "lm_q1q2_score": 0.8734450875261249}}
{"text": "import numpy as np\n\n\nclass linearSys:\n    def __init__(self, A, b):\n        self.A = A\n        self.b = b\n        self.n = A.shape[0]\n        self.L = np.eye(self.n)\n        self.U = np.eye(self.n)\n        self.x = np.zeros([self.n, 1])\n        self.y = np.zeros([self.n, 1])\n    \n    def LU_Decompose(self):\n        if self.A[0, 0] != 0:\n            self.L[0, 0] = self.A[0, 0]\n            self.U[0, 1:] = self.A[0, 1:] / self.L[0, 0]\n            self.L[1:, 0] = self.A[1:, 0] / self.U[0, 0]\n            for i in range(1, self.n - 1):\n                self.L[i, i] = self.A[i, i] - np.dot(self.L[i, 0:i], self.U[0:i, i])\n                if self.L[i, i] != 0:\n                    self.U[i, i+1:] = (self.A[i, i+1:] - np.dot(self.L[i, 0:i], self.U[0:i, i+1:])) / self.L[i, i]\n                    self.L[i+1:, i] = (self.A[i+1:, i] - np.dot(self.L[i+1:, 0:i], self.U[0:i, i])) / self.U[i, i]\n                else:\n                    return 'Factorization impossible at l{0}{0}'.format(i+1)\n            \n            self.L[-1, -1] = self.A[-1, -1] - np.dot(self.L[-1, 0:-1], self.U[0:-1, -1])\n            if self.L[-1, -1] == 0:\n                print('A is singular')\n            \n            self.y[0] = self.b[0] / self.L[0, 0]\n            for i in range(1, self.n):\n                self.y[i, 0] = (self.b[i] - np.dot(self.L[i, 0:i], self.y[0:i, 0])) / self.L[i, i]\n            \n            self.x[-1] = self.y[-1] / self.U[-1, -1]\n            for i in range(self.n - 2, -1, -1):\n                self.x[i, 0] = (self.y[i, 0] - np.dot(self.U[i, i+1:], self.x[i+1:, 0])) / self.U[i, i]\n            \n            return self.x, self.L, self.U\n        else:\n            return 'Factorization impossible at a11'\n\n    def LLt_Decompose(self):\n        self.L[0, 0] = np.sqrt(self.A[0, 0])\n        self.L[1:, 0] = self.A[1:, 0] / self.L[0, 0]\n        for i in range(1, self.n - 1):\n            self.L[i, i] = np.sqrt(self.A[i, i] - np.sum(self.L[i, 0:i] ** 2))\n            self.L[i+1:, i] = (self.A[i+1:, i] - np.sum(self.L[i+1:, 0:i] * self.L[i, 0:i], axis=1)) / self.L[i, i]\n        self.L[-1, -1] = np.sqrt(self.A[-1, -1] - np.sum(self.L[-1, 0:-1] ** 2))\n        self.y[0] = self.b[0] / self.L[0, 0]\n        for i in range(1, self.n):\n            self.y[i, 0] = (self.b[i] - np.dot(self.L[i, 0:i], self.y[0:i, 0])) / self.L[i, i]\n        \n        self.x[-1] = self.y[-1] / self.L[-1, -1]\n        for i in range(self.n - 2, -1, -1):\n            self.x[i, 0] = (self.y[i, 0] - np.dot(self.L[i+1:, i], self.x[i+1:, 0])) / self.L[i, i]\n        \n        return self.x\n\n\ndef array2latex(arr):\n    s = ''\n    for k in range(len(arr)):\n        row = arr[k]\n        if k < len(arr) - 1:\n            s += ' & '.join(map(str, row)) + ' \\\\\\\\\\n'\n        else:\n            s += ' & '.join(map(str, row))\n    return s\n\n\nif __name__ == '__main__':\n    # A = np.array([[1,1,0,3], [2,1,-1,1], [3,-1,-1,2], [-1,2,3,-1]])\n    # b = np.array([1, 1, -3, 4])\n    A = np.array([[1,1,0,3], [2,1,-1,1], [3,-1,-1,2], [-1,2,3,-1]])\n    b = np.array([8, 7, 14, -7])\n    sol = linearSys(A, b)\n    try:\n        # x, L, U = sol.LU_Decompose()\n        x, L, U = sol.LLt_Decompose()\n        print('Solution:', x.T)\n        print('L=\\n', array2latex(L))\n        print('U=\\n', array2latex(U))\n    except ValueError:\n        print(sol.LU_Decompose())\n", "meta": {"hexsha": "7beb3b00151baa6ab97c8084a092df1b6d21d1a9", "size": 3307, "ext": "py", "lang": "Python", "max_stars_repo_path": "numerical_analysis/report5_codes.py", "max_stars_repo_name": "chaosWsF/Financial-Mathematics", "max_stars_repo_head_hexsha": "e8eebb7edd24eb71f6161fb6bf5fea4bb8a2961a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-13T11:57:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T11:57:56.000Z", "max_issues_repo_path": "numerical_analysis/report5_codes.py", "max_issues_repo_name": "chaosWsF/Financial-Mathematics", "max_issues_repo_head_hexsha": "e8eebb7edd24eb71f6161fb6bf5fea4bb8a2961a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical_analysis/report5_codes.py", "max_forks_repo_name": "chaosWsF/Financial-Mathematics", "max_forks_repo_head_hexsha": "e8eebb7edd24eb71f6161fb6bf5fea4bb8a2961a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4534883721, "max_line_length": 115, "alphanum_fraction": 0.4197157545, "include": true, "reason": "import numpy", "num_tokens": 1236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140616, "lm_q2_score": 0.907312226373181, "lm_q1q2_score": 0.8734450831701085}}
{"text": "from typing import Optional\n\nimport numpy as np\n\nfrom mygrad import Tensor\nfrom mygrad.operation_base import Operation\nfrom mygrad.typing import ArrayLike, Real\n\n__all__ = [\"selu\"]\n\n\n_ALPHA = 1.6732632423543772848170429916717\n_SCALE = 1.0507009873554804934193349852946\n\n\nclass SELU(Operation):\n    \"\"\"Returns the scaled exponential linear activation (SELU) elementwise along x. The SELU is\n    given by  λɑ(exp(x) - 1) for x < 0 and λx for x ≥ 0.\n\n    Notes\n    -----\n    The SELU activation was proposed in the paper\n        Self-Normalizing Neural Networks\n        Günter Klambauer, Thomas Unterthiner, Andreas Mayr, Sepp Hochreiter\n    at https://arxiv.org/abs/1706.02515\n    \"\"\"\n\n    def __call__(self, x):\n        \"\"\"\n        Parameters\n        ----------\n        x : mygrad.Tensor\n            Input data.\n\n        Returns\n        -------\n        numpy.ndarray\n            The SELU function applied to `x` elementwise.\n        \"\"\"\n        self.variables = (x,)\n\n        x = x.data\n        self.exp = _ALPHA * (np.exp(x) - 1)\n        return _SCALE * np.where(x < 0, self.exp, x)\n\n    def backward_var(self, grad, index, **kwargs):\n        x = self.variables[index]\n        return grad * _SCALE * np.where(x.data < 0, self.exp + _ALPHA, 1)\n\n\ndef selu(x: ArrayLike, *, constant: Optional[bool] = None) -> Tensor:\n    \"\"\"Returns the scaled exponential linear activation (SELU) elementwise along x.\n\n    The SELU is given by  λɑ(exp(x) - 1) for x < 0 and λx for x ≥ 0.\n\n    Parameters\n    ----------\n    x : ArrayLike\n        Input data.\n\n    constant : Optional[bool]\n        If ``True``, the returned tensor is a constant (it\n        does not back-propagate a gradient)\n\n    Returns\n    -------\n    mygrad.Tensor\n        The SELU function applied to `x` elementwise.\n\n    References\n    ----------\n    .. [1] Günter Klambauer, Thomas Unterthiner, Andreas Mayr, Sepp Hochreiter\n       Self-Normalizing Neural Networks\n       https://arxiv.org/abs/1706.02515\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> from mygrad.nnet.activations import selu\n    >>> x = mg.arange(-5, 6)\n    >>> x\n    Tensor([-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5])\n    >>> y = selu(x, alpha=0.1); y\n    Tensor([-1.74625336, -1.72589863, -1.67056873, -1.52016647, -1.11133074,\n         0.        ,  1.05070099,  2.10140197,  3.15210296,  4.20280395,\n         5.25350494])\n\n    .. plot::\n\n       >>> import mygrad as mg\n       >>> from mygrad.nnet.activations import selu\n       >>> import matplotlib.pyplot as plt\n       >>> x = mg.linspace(-2, 2, 100)\n       >>> y = selu(x)\n       >>> plt.title(\"selu(x)\")\n       >>> y.backward()\n       >>> plt.plot(x, x.grad, label=\"df/dx\")\n       >>> plt.plot(x, y, label=\"f(x)\")\n       >>> plt.legend()\n       >>> plt.grid()\n       >>> plt.show()\n    \"\"\"\n    return Tensor._op(SELU, x, constant=constant)\n", "meta": {"hexsha": "8be1c6fc9297f4382b4b1dc2d31a5a2bcb2a1a95", "size": 2837, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/mygrad/nnet/activations/selu.py", "max_stars_repo_name": "kw-0/MyGrad", "max_stars_repo_head_hexsha": "307f1bb5f2391e7f4df49fe43a7acf9d1e8ea141", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 147, "max_stars_repo_stars_event_min_datetime": "2018-07-14T01:37:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:37:58.000Z", "max_issues_repo_path": "src/mygrad/nnet/activations/selu.py", "max_issues_repo_name": "kw-0/MyGrad", "max_issues_repo_head_hexsha": "307f1bb5f2391e7f4df49fe43a7acf9d1e8ea141", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 223, "max_issues_repo_issues_event_min_datetime": "2018-05-31T14:13:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T18:53:49.000Z", "max_forks_repo_path": "src/mygrad/nnet/activations/selu.py", "max_forks_repo_name": "kw-0/MyGrad", "max_forks_repo_head_hexsha": "307f1bb5f2391e7f4df49fe43a7acf9d1e8ea141", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2018-06-17T14:42:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T00:21:09.000Z", "avg_line_length": 27.2788461538, "max_line_length": 95, "alphanum_fraction": 0.5738456116, "include": true, "reason": "import numpy", "num_tokens": 846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650673, "lm_q2_score": 0.9149009625340367, "lm_q1q2_score": 0.8734078405704818}}
{"text": "\r\nimport numpy as np\r\nimport ast\r\nimport json\r\ndef jacobi(A, b, x, norm, tol, iteMax):\r\n    A = ast.literal_eval(A)\r\n    b = ast.literal_eval(b)\r\n    x = ast.literal_eval(x)\r\n    result = {}\r\n    iters = []\r\n    D = np.diag(np.diag(A))\r\n    L = (-1 * np.tril(A))+D\r\n    U = (-1 * np.triu(A))+D\r\n    if(0 in np.diag(A)): return {\"status\" : \"diagonal has 0\", \"error\" : True}\r\n    ite = 0\r\n    #Change here for Jacobi, Sor and Gauss seidel\r\n    T = np.dot(np.linalg.inv(D), (L+U))\r\n    C = np.dot(np.linalg.inv(D),b)\r\n    #End changes\r\n    spectRad = np.max(np.absolute(np.linalg.eigvals(T)))\r\n    if(spectRad > 1): return {\"status\" : \"spectral radious > 1\", \"error\" : True}\r\n    #Saving into result dict\r\n    result['tmatrix'] = json.dumps(T.tolist())\r\n    result['cmatrix'] = json.dumps(C.tolist())\r\n    result['spectrad'] = spectRad\r\n\r\n    iters.append({ \"iter\" : ite, \"E\" : \"n/a\", \"x\" : x})\r\n    #End savings\r\n    while(norm > tol and ite < iteMax):\r\n        xold = x\r\n        x = np.dot(T,xold)+C\r\n        norm = np.linalg.norm(xold-x)\r\n        ite += 1\r\n        #Saving into iters\r\n        iters.append({ \"iter\" : ite,  \"E\" : float(norm),  \"x\" : x.tolist()})\r\n        #End saving\r\n    result['iters'] = iters\r\n    result['error'] = False\r\n    return result\r\n", "meta": {"hexsha": "0710a7c4010c1f97e97eddc045beb687e7959613", "size": 1261, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/jacobi.py", "max_stars_repo_name": "eechava6/NumericalAnalysisMethods", "max_stars_repo_head_hexsha": "3eeb06bdb20d97f13a09fd0ed71bce045173ffef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/jacobi.py", "max_issues_repo_name": "eechava6/NumericalAnalysisMethods", "max_issues_repo_head_hexsha": "3eeb06bdb20d97f13a09fd0ed71bce045173ffef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/jacobi.py", "max_forks_repo_name": "eechava6/NumericalAnalysisMethods", "max_forks_repo_head_hexsha": "3eeb06bdb20d97f13a09fd0ed71bce045173ffef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.525, "max_line_length": 81, "alphanum_fraction": 0.5384615385, "include": true, "reason": "import numpy", "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140254249553, "lm_q2_score": 0.9032942054022056, "lm_q1q2_score": 0.8734078362884831}}
{"text": "import numpy as np\nimport settings as globalv\n\ndef centerData(data):\n\tprint('\\nCentering data...')\n\tmean_vector = np.mean(data, axis = 1).reshape(data.shape[0], 1)\n\tcentered_data = data - mean_vector\n\n\tif (globalv.print_results):\n\t\tprint('Mean vector: \\n', mean_vector)\n\t\tprint('Centered data: \\n', centered_data)\n\treturn centered_data, mean_vector\n\ndef correlationMatrix(centered_data):\n\tprint('\\nComputing correlation matrix...')\n\tD = globalv.D\n\tN = globalv.N\n\n\tcorrelation_matrix = np.zeros((D, D))\n\tfor i in range(N):\n\t\tcorrelation_matrix += (centered_data[:,i].reshape(D,1)).dot(centered_data[:,i].reshape(D,1).T)\n\tcorrelation_matrix = correlation_matrix/N\n\n\tif (globalv.print_results):\n\t\tprint(correlation_matrix)\n\t\n\treturn correlation_matrix\n\ndef eigenDecomposition(corr):\n\tprint('\\nEigendecomposition of correlation matrix...')\n\tD = globalv.D\n\tN = globalv.N\n\n\teigvals, eigvecs = np.linalg.eig(corr)\n\n\tfor i in range(len(eigvals)):\n\t\teigv = eigvecs[:,i].reshape(1,D).T\n\t\tnp.testing.assert_array_almost_equal(corr.dot(eigv), eigvals[i] * eigv, decimal=6, err_msg='', verbose=True)\n\n\tif (globalv.print_results):\t\n\t\tprint('Eigenvalues: \\n', eigvals)\n\t\tprint('Eigenvectors: \\n', eigvecs)\n\t\n\treturn eigvals, eigvecs\n\ndef readUserNumComponents(msg):\t\n\tD = globalv.D\n\tN = globalv.N\n\n\t# numComponents = raw_input(msg)\n\tnumComponents = 4\n\t# try:\n\t\t# Try to convert the user input to an integer\n\t    # numComponents = int(numComponents)\n\t\t# if numComponents > D or numComponents < 0:\n\t\t# \tprint 'Invalid number of components'\n\t\t# \tsys.exit(-3)\n\t# except ValueError:\n\t# \tCatch the exception if the input was not a number\n\t\t# numComponents = 1\n\t# print 'Using %d components' %numComponents\n\treturn numComponents\n\ndef computeProjectionMatrix(eigvals, eigvecs, r):\n\tprint('\\nComputing the projection matrix...')\n\tD = globalv.D\n\tN = globalv.N\n\n\t# List of (eigenvalue, eigenvector) tuples\n\teig_pairs = [(np.abs(eigvals[i]), eigvecs[:,i]) for i in range(len(eigvals))]\n\n\t# Sort the (eigenvalue, eigenvector) tuples from high to low (reverse=True)\n\teig_pairs.sort(key=lambda tup: tup[0], reverse=True)\n\n\t# Projection matrix\n\tproj_matrix = np.zeros((D,r))\n\tfor i in range(r):\n\t\tproj_matrix[:,i] = eig_pairs[i][1].reshape(1, D)\n\n\tif (globalv.print_results):\n\t\tprint('Projection matrix: \\n', proj_matrix)\n\t\n\treturn proj_matrix\n\ndef computePrincipalComponents(centered_data, proj_matrix):\n\tprint('\\nComputing principal components...')\n\tp = (proj_matrix.T).dot(centered_data)\n\n\tif (globalv.print_results):\t\n\t\tprint('Principal components: \\n', p)\n\t\n\treturn p\n\ndef reconstructData(princ_comps, proj_matrix, mean_vector):\n\tprint('\\nReconstructing the data...')\n\treconstructed_data = (proj_matrix).dot(princ_comps) + mean_vector\n\t\n\tif (globalv.print_results):\n\t\tprint('Reconstructed data: \\n', reconstructed_data)\n\t\n\treturn reconstructed_data\n\ndef computeRecError(data, reconstructed_data):\n\tprint('\\nComputing reconstruction error...')\n\tD = globalv.D\n\tN = globalv.N\n\n\terror = data - reconstructed_data\n\terror_var = 0\n\tfor i in range(N):\n\t\terror_var += np.linalg.norm(error[:, i])**2\n\terror_var = error_var/N\n\n\tif (globalv.print_results):\n\t\tprint('Error: \\n', error)\n\tprint('Error variance: ', error_var)\n\t\n\treturn error", "meta": {"hexsha": "54544dabb1d09e9aae0310f482a6e24f1124fc7e", "size": 3200, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw3/references/simple-PCA/pca_utils.py", "max_stars_repo_name": "ardihikaru/mlsp", "max_stars_repo_head_hexsha": "db38972bcceac7b95808132457c4de9170546c9d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw3/references/simple-PCA/pca_utils.py", "max_issues_repo_name": "ardihikaru/mlsp", "max_issues_repo_head_hexsha": "db38972bcceac7b95808132457c4de9170546c9d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw3/references/simple-PCA/pca_utils.py", "max_forks_repo_name": "ardihikaru/mlsp", "max_forks_repo_head_hexsha": "db38972bcceac7b95808132457c4de9170546c9d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-07T14:25:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-07T14:25:54.000Z", "avg_line_length": 27.1186440678, "max_line_length": 110, "alphanum_fraction": 0.7215625, "include": true, "reason": "import numpy", "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140206578809, "lm_q2_score": 0.9032942054022056, "lm_q1q2_score": 0.8734078319824123}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef least_square_algorithm(t, y, n):\n    \"\"\" Least square algorithm\n\n    Args:\n        t: list/ndarray, the list of points\n        y: list/ndarray, the list of function value\n        n: int, the order of the fitting curve\n\n    Returns:\n        c: ndarray, the cofficients of the fitting curve\n    \"\"\"\n    # the number of the points\n    leng = len(t)\n    # the cofficient matrix\n    A = np.ones(leng)\n    for i in range(n):\n        A = np.c_[A, t**(i+1)]\n    # the solution of the normal equations\n    c = np.linalg.solve(A.T.dot(A), A.T.dot(y))\n    \n    return c\n\n\ndef calculate_square_error(y, func):\n    \"\"\" Calculate the square error\n\n    Args:\n        y: ndarray, the list of prediction value\n        func: ndarray, the list of original value\n\n    Returns:\n        sq_err: double, the square error\n    \"\"\"\n    return np.sum(np.square(y - func))\n\n\ndef draw_curve(x, y, func, file_name):\n    \"\"\" Draw the fitting curve\n\n    Args:\n        x: ndarray, the data of independent variable\n        y: ndarray, the original value\n        func: ndarray, the prediction function\n        file_name: string, the name of the saved figure file\n\n    \"\"\"\n    fig = plt.figure(figsize=(6, 6))\n    plt.plot(x, y, 'ro', label='data set')\n    t = np.arange(x[0], x[-1], 0.1)\n    plt.plot(t, func(t), 'g-', label='fitting curve')\n    plt.title('Least Square Algorithm')\n    plt.legend()\n    plt.savefig(file_name)    \n\n\ndef linear_fitting():\n    \"\"\" Fitting experiment 1\n\n    \"\"\"\n    # data\n    x = np.array([1, 2, 3, 4, 5])\n    y = np.array([4, 4.5, 6, 8, 8.5])\n    # get the cofficients\n    a, b = least_square_algorithm(x, y, 1)\n    # define the fitting curve using the cofficients\n    f = lambda x: a + b * x\n    # get the square error\n    print(f\"The linear fitting's square error is {calculate_square_error(f(x), y)}\")\n    # visualization\n    draw_curve(x, y, f, 'linear_fitting.png')\n\n\ndef non_linear_fitting():\n    \"\"\" two order polinomial fitting\n\n    \"\"\"\n    # data\n    x = np.array([2, 3, 4, 7, 8, 10, 11, 14, 16, 18, 19])\n    y = np.array([106.42, 108.2, 109.5, 110, 109.93, 110.49, 110.59, 110.6, 110.76, 111, 111.2])\n    # get the cofficients\n    a, b, c = least_square_algorithm(x, y, 2)\n    # define the fitting curve\n    f = lambda x: a + b * x + c * x**2\n    # get the square error\n    print(f\"The 2-order polinomial fitting's square error is {calculate_square_error(f(x), y)}\")\n    # visualization\n    draw_curve(x, y, f, 'polinomial_fitting.png')\n\n    \"\"\" exponential fitting\n\n    \"\"\"\n    # data preprocessing\n    t = 1 / x\n    z = np.log(y)\n    # get the cofficients\n    a0, b0 = least_square_algorithm(t, z, 1)\n    a1, b1 = np.exp(a0), b0\n    # define the fitting curve\n    g = lambda x: a1 * np.exp(b1 / x)\n    print(f\"The exponential fitting's square error is {calculate_square_error(g(x), y)}\")\n    # visualization\n    draw_curve(x, y, g, 'exponential_fitting.png')\n\n\nif __name__ == '__main__':\n    linear_fitting() \n    non_linear_fitting()\n\n", "meta": {"hexsha": "0509e78af2205a459f1e9df61dd76bc503165806", "size": 3002, "ext": "py", "lang": "Python", "max_stars_repo_path": "InterpolationAndFitting/least_square_algorithm.py", "max_stars_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_stars_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "InterpolationAndFitting/least_square_algorithm.py", "max_issues_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_issues_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "InterpolationAndFitting/least_square_algorithm.py", "max_forks_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_forks_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5663716814, "max_line_length": 96, "alphanum_fraction": 0.6055962692, "include": true, "reason": "import numpy", "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812299938005, "lm_q2_score": 0.9019206752113866, "lm_q1q2_score": 0.8734030528180416}}
{"text": "#!/usr/bin/env python\r\n\"\"\"Module providing functionality surrounding gaussian function.\r\n\"\"\"\r\nSVN_REVISION = '$LastChangedRevision: 16541 $'\r\n\r\nimport sys\r\nimport numpy\r\n\r\ndef gaussian2(size, sigma):\r\n    \"\"\"Returns a normalized circularly symmetric 2D gauss kernel array\r\n    \r\n    f(x,y) = A.e^{-(x^2/2*sigma^2 + y^2/2*sigma^2)} where\r\n    \r\n    A = 1/(2*pi*sigma^2)\r\n    \r\n    as define by Wolfram Mathworld \r\n    http://mathworld.wolfram.com/GaussianFunction.html\r\n    \"\"\"\r\n    A = 1/(2.0*numpy.pi*sigma**2)\r\n    x, y = numpy.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1]\r\n    g = A*numpy.exp(-((x**2/(2.0*sigma**2))+(y**2/(2.0*sigma**2))))\r\n    return g\r\n\r\ndef fspecial_gauss(size, sigma):\r\n    \"\"\"Function to mimic the 'fspecial' gaussian MATLAB function\r\n    \"\"\"\r\n    x, y = numpy.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1]\r\n    g = numpy.exp(-((x**2 + y**2)/(2.0*sigma**2)))\r\n    return g/g.sum()\r\n\r\ndef main():\r\n    \"\"\"Show simple use cases for functionality provided by this module.\"\"\"\r\n    from mpl_toolkits.mplot3d.axes3d import Axes3D\r\n    import pylab\r\n    argv = sys.argv\r\n    if len(argv) != 3:\r\n        print >>sys.stderr, 'usage: python -m pim.sp.gauss size sigma'\r\n        sys.exit(2)\r\n    size = int(argv[1])\r\n    sigma = float(argv[2])\r\n    x, y = numpy.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1]\r\n\r\n    fig = pylab.figure()\r\n    fig.suptitle('Some 2-D Gauss Functions')\r\n    ax = fig.add_subplot(2, 1, 1, projection='3d')\r\n    ax.plot_surface(x, y, fspecial_gauss(size, sigma), rstride=1, cstride=1, \r\n                    linewidth=0, antialiased=False, cmap=pylab.jet())\r\n    ax = fig.add_subplot(2, 1, 2, projection='3d')\r\n    ax.plot_surface(x, y, gaussian2(size, sigma), rstride=1, cstride=1, \r\n                    linewidth=0, antialiased=False, cmap=pylab.jet())\r\n    pylab.show()\r\n    return 0\r\n\r\nif __name__ == '__main__':\r\n    sys.exit(main())", "meta": {"hexsha": "120be0940c7ca0d5c1a5441d305e405d8765c01f", "size": 1916, "ext": "py", "lang": "Python", "max_stars_repo_path": "gauss.py", "max_stars_repo_name": "lidongliang666/EraseNet", "max_stars_repo_head_hexsha": "fba8ad76c7cae55b5f624d4a000928fee8c69983", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 104, "max_stars_repo_stars_event_min_datetime": "2021-05-19T16:17:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:46:09.000Z", "max_issues_repo_path": "gauss.py", "max_issues_repo_name": "lidongliang666/EraseNet", "max_issues_repo_head_hexsha": "fba8ad76c7cae55b5f624d4a000928fee8c69983", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-10-15T06:21:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T05:46:47.000Z", "max_forks_repo_path": "gauss.py", "max_forks_repo_name": "lidongliang666/EraseNet", "max_forks_repo_head_hexsha": "fba8ad76c7cae55b5f624d4a000928fee8c69983", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2021-05-20T00:42:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:36:16.000Z", "avg_line_length": 34.8363636364, "max_line_length": 78, "alphanum_fraction": 0.5871607516, "include": true, "reason": "import numpy", "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812345563904, "lm_q2_score": 0.9019206692796966, "lm_q1q2_score": 0.8734030511889984}}
{"text": "# Project Euler Problem 5 Solution\n#\n# Problem statement:\n# 2520 is the smallest number that can be divided by each of\n# the numbers from 1 to 10 without any remainder.\n# What is the smallest positive number that is evenly divisible\n# by all of the numbers from 1 to 20?\n#\n# Solution description:\n# This script is a brute-force solution of the above problem,\n# followed by a faster solution exploiting prime number factorization.\n#\n# Author: Daniel Schuette, Philipp Schuette\n# Date: 2019/02/09\n# License: MIT (see ../LICENSE.md)\nimport time\n\nimport numpy as np\n\n\ndef evenly_divisible(limit):\n    \"\"\"\n    Doc string\n    \"\"\"\n    current_num = limit  # represents the currently tested number\n    divisible = True  # whether `current_num' is still divisible\n\n    while True:\n        for divisor in range(1, limit+1):\n            if not (current_num % divisor) == 0:\n                divisible = False\n                break  # break out of for loop\n\n        if not divisible:\n            current_num += limit\n            divisible = True\n        else:\n            return current_num\n\n\ndef check_prime(x):\n    \"\"\"\n    checks, whether or not x is a prime number\n    \"\"\"\n    prime = True\n    for i in range(2, x):\n        if (x % i) == 0:\n            prime = False\n            break\n    return prime\n\n\ndef prime_list(n):\n    \"\"\"\n    outputs a list of all prime numbers between 1 and n > 1\n    \"\"\"\n    prime_list = []\n    for i in range(2, n + 1):\n        if check_prime(i):\n            prime_list.append(i)\n    return prime_list\n\n\ndef lcm(n):\n    \"\"\"\n    outputs the least common multiple for the numbers from 1 to 20\n    \"\"\"\n    primes = prime_list(n)\n    lcm = 1\n    for p in primes:\n        e_p = 1\n        while pow(p, e_p + 1) <= n:\n            e_p += 1\n        lcm *= pow(p, e_p)\n    return lcm\n\n\nif __name__ == \"__main__\":\n    # calculate the solution with the 'slow' variant\n    start1 = time.time()\n    solution1 = evenly_divisible(20)\n    end1 = time.time()\n    # calculate the solution with the 'fast' variant\n    start2 = time.time()\n    solution2 = lcm(30)\n    end2 = time.time()\n\n    # print both solutions\n    print(\"slow solution expired: {}s, solution: {}\".format(\n        np.round(end1 - start1, 5), solution1))\n    print(\"fast solution expired: {}s, solution {}\". format(\n        np.round(end2 - start2, 5), solution2))\n", "meta": {"hexsha": "496765075d7819bbc820790b747f6888f16f0d26", "size": 2331, "ext": "py", "lang": "Python", "max_stars_repo_path": "py_src/problem005.py", "max_stars_repo_name": "PhilippSchuette/projecteuler", "max_stars_repo_head_hexsha": "b74f76e8f27769d5cfc4227ccfb272d0a83ef587", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-09-24T14:14:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T01:57:12.000Z", "max_issues_repo_path": "py_src/problem005.py", "max_issues_repo_name": "PhilippSchuette/projecteuler", "max_issues_repo_head_hexsha": "b74f76e8f27769d5cfc4227ccfb272d0a83ef587", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2018-09-24T14:18:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-08T07:03:31.000Z", "max_forks_repo_path": "py_src/problem005.py", "max_forks_repo_name": "PhilippSchuette/projecteuler", "max_forks_repo_head_hexsha": "b74f76e8f27769d5cfc4227ccfb272d0a83ef587", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-03-01T14:22:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T01:57:53.000Z", "avg_line_length": 25.064516129, "max_line_length": 70, "alphanum_fraction": 0.6053196053, "include": true, "reason": "import numpy", "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.949669364375513, "lm_q1q2_score": 0.8733563380363025}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct  7 10:11:19 2019\n\n@author: amandaash\n\"\"\"\n\nimport numpy as np\nimport scipy.optimize as opt\nimport matplotlib.pyplot as plt\n\n\nE_b = np.arange(0,10,0.001)\nf_Eb = (((10-E_b)**(0.5))*np.tan((10-E_b)**(0.5))) - E_b**(0.5)\n\nplt.plot(E_b, f_Eb)\nplt.ylim(-10,10)\nplt.grid()\nplt.axvline(x = 8.592785275230653, color = 'k', linestyle = 'dashed')\n#plt.yscale('log')\nplt.savefig('binding_func_10_even.pdf')\nplt.show()\n\ndef binding_energy(Eb):\n    f = (((10-Eb)**(0.5))*np.tan((10-Eb)**(0.5))) - Eb**(0.5)\n    return f\n\nE_b_bisect = opt.bisect(binding_energy,8,9.5)\n\nE_b_newton = opt.newton(binding_energy, 8.5)\n\nE_b_brents = opt.brentq(binding_energy, 8.5, 9.5)\n\nprint('root even function: bisection method = {0}, precision = {1}'.format(E_b_bisect, binding_energy(E_b_bisect)))\nprint('root even function: Newton method = {0}, precision = {1}'.format(E_b_newton, binding_energy(E_b_newton)))\nprint('root even function: brents method = {0}, precision = {1}'.format(E_b_brents, binding_energy(E_b_brents)))\ndef binding_energy_beta(Eb):\n    f = (np.sqrt(Eb)*(np.tan(np.sqrt(10-Eb))**-1))-np.sqrt(10-Eb)\n    return(f)\n\n    \nenergies = np.arange(0,10,0.001)\nfE = binding_energy_beta(energies)\n\nplt.plot(energies, fE)\nplt.ylim(-20,10)\nplt.axvline(x = 8.592785275230653, color = 'k', linestyle = 'dashed')\nplt.grid()\nplt.savefig('binding_func_10_odd.pdf')\nplt.show()\n\nEb_bisect_beta = opt.bisect(binding_energy_beta,8,9.5)\nprint(\"root odd function: bisection method = {0}\".format(Eb_bisect_beta))\nE_b_newton_beta = opt.newton(binding_energy_beta, 8.5)\nprint(\"root odd function: Newton method = {0}\".format(E_b_newton_beta))\n\ndef binding_energy_gamma(E, A):\n    f = (((A-E)**(0.5))*np.tan((A-E)**(0.5))) - E**(0.5)\n    return f\n\nenergy_gamma1 = np.arange(0,10,0.001)\nenergy_gamma2 = np.arange(0,20,0.001)\nenergy_gamma3 = np.arange(0,30,0.001)\n\nplt.plot(energy_gamma1, binding_energy_gamma(energy_gamma1, 10))\nplt.ylim(-10,10)\nplt.grid()\nplt.show()\nplt.title('Binding energy = 20')\nplt.plot(energy_gamma2, binding_energy_gamma(energy_gamma2, 20))\nplt.ylim(-20,20)\nplt.grid()\nplt.savefig('binding_func_20_even.pdf')\nplt.show()\ndef binding_energy_gamma20(E):\n    f = (((20-E)**(0.5))*np.tan((20-E)**(0.5))) - E**(0.5)\n    return f\nEb_bisect_gamma20_root1 = opt.bisect(binding_energy_gamma20,5,7.5)\nEb_bisect_gamma20_root2 = opt.bisect(binding_energy_gamma20,17.7,19)\n\nprint(Eb_bisect_gamma20_root1, binding_energy_gamma20(Eb_bisect_gamma20_root1))\nprint(Eb_bisect_gamma20_root2, binding_energy_gamma20(Eb_bisect_gamma20_root2))\nplt.title('Binding energy = 30')\nplt.plot(energy_gamma3, binding_energy_gamma(energy_gamma3, 30))\nplt.ylim(-30,30)\nplt.grid()\nplt.savefig('binding_func_30_even.pdf')\nplt.show()\ndef binding_energy_gamma30(E):\n    f = (((30-E)**(0.5))*np.tan((30-E)**(0.5))) - E**(0.5)\n    return f\nEb_bisect_gamma30_root1 = opt.bisect(binding_energy_gamma30,14,16)\nEb_bisect_gamma30_root2 = opt.bisect(binding_energy_gamma30,28,29.5)\n\nprint(Eb_bisect_gamma30_root1, binding_energy_gamma30(Eb_bisect_gamma30_root1))\nprint(Eb_bisect_gamma30_root2, binding_energy_gamma30(Eb_bisect_gamma30_root2))\n\n", "meta": {"hexsha": "bee673cfbb77e4a20f1c3b364f9dfebf22a2415c", "size": 3152, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week 08/E15.py", "max_stars_repo_name": "aash7871/PHYS-3210", "max_stars_repo_head_hexsha": "7820e85259b5fbc2845feaa1068ef12afc13db77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week 08/E15.py", "max_issues_repo_name": "aash7871/PHYS-3210", "max_issues_repo_head_hexsha": "7820e85259b5fbc2845feaa1068ef12afc13db77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week 08/E15.py", "max_forks_repo_name": "aash7871/PHYS-3210", "max_forks_repo_head_hexsha": "7820e85259b5fbc2845feaa1068ef12afc13db77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-17T01:58:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T01:58:14.000Z", "avg_line_length": 31.8383838384, "max_line_length": 115, "alphanum_fraction": 0.7220812183, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688146, "lm_q2_score": 0.9046505447409666, "lm_q1q2_score": 0.873332591524734}}
{"text": "from helper import load_times, str_time_to_num_time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\n\n\n# Load in 5k times and VDOT scores\ndf = load_times()\ndf = df[['VDOT', '5k']]\ndf['5k Time'] = df['5k'].apply(lambda x: str_time_to_num_time(x))\n\n\n# Create a plot of 5k times against VDOT\ndf.plot(y='VDOT',\n        x='5k Time',\n        kind='scatter',\n        grid=True,\n        title='5k Times Against VDOT')\nplt.xticks(ticks=[900, 1200, 1500, 1800],\n           labels=['15:00', '20:00', '25:00', '30:00'])\nplt.savefig('../generated-notes/5k-models/regular-plot.png')\n\n####################\n# We will create a linear regression model and plot results\n\n# Plot a linear regression\nmodel = LinearRegression().fit(df[['5k Time']], df['VDOT'])\nprint(model.coef_)\nprint(model.intercept_)\nprint(model.score(df[['5k Time']], df['VDOT']))\n\n# Get presumed VDOTs from model\nplot_space = np.linspace(700, 1900, num=50)\nvdots = model.intercept_ + (plot_space * model.coef_[0])\n\n# Plot true, and model predictions\ndf.plot(y='VDOT',\n        x='5k Time',\n        kind='scatter',\n        grid=True,\n        title='5k Times Against VDOT (with Linear Regression Model)')\nplt.xticks(ticks=[900, 1200, 1500, 1800],\n           labels=['15:00', '20:00', '25:00', '30:00'])\nplt.plot(plot_space, vdots)\nplt.savefig('../generated-notes/5k-models/linear-plot.png')\n\n####################\n# We will create multiple regression models and plot results\n\n# Create multiple regression models\ndf['5k_1'] = df['5k Time']\ndf['5k_2'] = df['5k_1'] * df['5k_1']\ndf['5k_3'] = df['5k_2'] * df['5k_1']\ndf['5k_4'] = df['5k_3'] * df['5k_1']\nmodel_1 = LinearRegression().fit(df[['5k_1']], df['VDOT'])\nmodel_2 = LinearRegression().fit(df[['5k_1', '5k_2']], df['VDOT'])\nmodel_3 = LinearRegression().fit(df[['5k_1', '5k_2', '5k_3']], df['VDOT'])\nmodel_4 = LinearRegression().fit(df[['5k_1', '5k_2', '5k_3', '5k_4']], df['VDOT'])\n\n# Get model predictions\nplot_space = np.linspace(700, 1900, num=50)\nvdots_1 = model_1.intercept_ + (plot_space * model_1.coef_[0])\nvdots_2 = model_2.intercept_ + (plot_space * model_2.coef_[0]) + ((plot_space**2)*model_2.coef_[1])\nvdots_3 = model_3.intercept_ + (plot_space * model_3.coef_[0]) + ((plot_space**2)*model_3.coef_[1]) + ((plot_space**3)*model_3.coef_[2])\nvdots_4 = model_4.intercept_ + (plot_space * model_4.coef_[0]) + ((plot_space**2)*model_4.coef_[1]) + ((plot_space**3)*model_4.coef_[2]) + ((plot_space**4)*model_4.coef_[3])\n\n# Plot true, and model predictions\ndf.plot(y='VDOT',\n        x='5k Time',\n        kind='scatter',\n        grid=True,\n        title='5k Times Against VDOT (with Multiple Regression Models)')\nplt.xticks(ticks=[900, 1200, 1500, 1800],\n           labels=['15:00', '20:00', '25:00', '30:00'])\nplt.plot(plot_space, vdots_1, label='Power 1')\nplt.plot(plot_space, vdots_2, label='Power 2')\nplt.plot(plot_space, vdots_3, label='Power 3')\nplt.plot(plot_space, vdots_4, label='Power 4')\nplt.legend()\nplt.savefig('../generated-notes/5k-models/multi-plot.png')\n\n# Output scores for each model\nprint()\nprint('Model 1:', model_1.score(df[['5k_1']], df['VDOT']))\nprint('Model 2:', model_2.score(df[['5k_1', '5k_2']], df['VDOT']))\nprint('Model 3:', model_3.score(df[['5k_1', '5k_2', '5k_3']], df['VDOT']))\nprint('Model 4:', model_4.score(df[['5k_1', '5k_2', '5k_3', '5k_4']], df['VDOT']))\n\n# Print coefs and intercept for model 4\nprint()\nprint('Model 4')\nprint('Coefs:    ', model_4.coef_)\nprint('Intercept:', model_4.intercept_)\n\n####################\n# These are helper functions created from the power 4 model\n\ndef fivek_time_to_vdot(time):\n    c = 320.21840994212795\n    m = [-5.85338453e-01,4.99386989e-04,-2.05665011e-07,3.29250289e-11]\n    \n    secs = str_time_to_num_time(time)\n    vdot = c + (secs*m[0]) + ((secs**2)*m[1]) + ((secs**3)*m[2]) + ((secs**4)*m[3])\n    return vdot\n\nprint()\nprint('20:00 to ', fivek_time_to_vdot('20:00'))\nprint('22:00 to ', fivek_time_to_vdot('22:00'))\nprint('24:00 to ', fivek_time_to_vdot('24:00'))\nprint('26:00 to ', fivek_time_to_vdot('26:00'))", "meta": {"hexsha": "c71a660015fa819246bf3ed67aca6c4e0b089380", "size": 4045, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/5k-time-plotting.py", "max_stars_repo_name": "CurtisThompson/VDOT-Calculator", "max_stars_repo_head_hexsha": "a4a8f7e0fa7ee3d9588fd8f111fc6b39a5f0f529", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/5k-time-plotting.py", "max_issues_repo_name": "CurtisThompson/VDOT-Calculator", "max_issues_repo_head_hexsha": "a4a8f7e0fa7ee3d9588fd8f111fc6b39a5f0f529", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/5k-time-plotting.py", "max_forks_repo_name": "CurtisThompson/VDOT-Calculator", "max_forks_repo_head_hexsha": "a4a8f7e0fa7ee3d9588fd8f111fc6b39a5f0f529", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4414414414, "max_line_length": 173, "alphanum_fraction": 0.6474660074, "include": true, "reason": "import numpy", "num_tokens": 1380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811581728097, "lm_q2_score": 0.9046505402422644, "lm_q1q2_score": 0.8733325862807352}}
{"text": "import numpy as np\nimport pymc3\nfrom scipy.stats import binom, beta\n\n#3M1\ngrid = np.linspace(0.0, 1.0, 1000)\nprior = np.ones(1000)\n\nlikelihood = binom.pmf(8, 15, p=grid)\n\nposterior = likelihood * prior\nposterior /= np.sum(posterior)\n\n#3M2\nnp.random.seed(100)\nsamples = np.random.choice(grid, size=10000, replace=True, p=posterior)\n\nprint('2')\nprint(pymc3.stats.hpd(samples, 0.9))\n\n#3M3\ndummyData = binom.rvs(15, samples, size=samples.shape[0])\nprint('\\n3')\nprint(np.mean(dummyData == 8))\n\n\n#3M4\ndummyData = binom.rvs(9, samples, size=samples.shape[0])\nprint('\\n4')\nprint(np.mean(dummyData == 6))\n\n#3M5\nprior[grid < 0.5] = 0\n\nposterior = likelihood * prior\nposterior /= np.sum(posterior)\n\nsamples = np.random.choice(grid, size=10000, replace=True, p=posterior)\nprint('\\n5')\nprint(pymc3.stats.hpd(samples, 0.9))\n\ndummyData = binom.rvs(15, samples, size=samples.shape[0])\nprint(np.mean(dummyData == 8))\n\n\ndummyData = binom.rvs(9, samples, size=samples.shape[0])\nprint(np.mean(dummyData == 6))\n\n#3M6\n\nN = 2500\ns = int(np.round(8 * N / 15))\nlikelihood = binom.pmf(s, N, p=grid)\n\nposterior = likelihood * prior\nposterior /= np.sum(posterior)\n\nsamples = np.random.choice(grid, size=10000, replace=True, p=posterior)\n\ninterval = pymc3.stats.hpd(samples, 0.99)\nprint('\\n6')\nprint('%d: %f' % (N, interval[1] - interval[0]))\n\n\n", "meta": {"hexsha": "e512ae02c74acab46f230f341a92b2842a587444", "size": 1316, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapter-3/medium.py", "max_stars_repo_name": "stamakro/statistical-rethinking-python", "max_stars_repo_head_hexsha": "2de598a384677a5c931f10c193becdfa5c796031", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-10-02T09:38:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T21:42:00.000Z", "max_issues_repo_path": "chapter-3/medium.py", "max_issues_repo_name": "stamakro/statistical-rethinking-python", "max_issues_repo_head_hexsha": "2de598a384677a5c931f10c193becdfa5c796031", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter-3/medium.py", "max_forks_repo_name": "stamakro/statistical-rethinking-python", "max_forks_repo_head_hexsha": "2de598a384677a5c931f10c193becdfa5c796031", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2461538462, "max_line_length": 71, "alphanum_fraction": 0.693768997, "include": true, "reason": "import numpy,from scipy,import pymc3", "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854103128328, "lm_q2_score": 0.9005297821135385, "lm_q1q2_score": 0.8733206442459039}}
{"text": "from pylab import *\r\nfrom scipy.integrate import quad;\r\nfrom scipy.interpolate import interp1d\r\n\r\nclose('all')\r\n\r\n# PDF of the standard normal distribution.\r\np = lambda t : exp(-t**2/2.0)/sqrt(2*pi);\r\n# CDF of the standard normal distribution. \r\nF = lambda x : (quad(p,-inf,x))[0];\r\n\r\n\r\n# Take discrete points (x,F(x))\r\nNs = 40;\r\nx = linspace(-7,7,Ns);\r\ny = zeros(Ns)\r\nfor i in xrange(Ns):\r\n\ty[i] = F(x[i]);\r\n\r\nplot(x,y,'r*')\r\n\r\n# Interpolate F\r\nFint = interp1d(x,y);\r\n\r\nplot(x,Fint(x),'g--')\r\nlegend(['(x,F(x))','Interpolation'],loc=0);\r\n\r\nfigure()\r\n\r\nFinv = interp1d(y,x);\r\nplot(x,Finv(Fint(x)),'b--',x,x,'r*-')\r\nlegend(['Finv(Fint(x))','y=x'],loc=0)\r\n\r\n# Now let's sample from F!\r\n\r\n# First, we need N samples from U[0,1]\r\nN = 1e+6;\r\nu = rand(N)\r\n\r\n# Now, we need to calculate Finv(u), which will\r\n# gives us the samples we want.\r\nx = Finv(u);\r\n\r\nprint \"Mean of samples : \", mean(x)\r\nprint \"Variance of samples :\", var(x)\r\n\r\n# Let's make a histogram of what we got. \r\n\r\nfigure()\r\nhist(x,normed=True)\r\n\r\n# We need to compare with samples from the Standard Normal distribution. \r\nun = randn(N);\r\nhist(un,normed=True,color='red',alpha=0.6)\r\n\r\nlegend(['Samples with our method','\"Real\" samples'],loc=0)\r\n\r\nshow()\r\n\r\n", "meta": {"hexsha": "feb9af2c9ea5f06c7145f6a5be926362e5fb4272", "size": 1215, "ext": "py", "lang": "Python", "max_stars_repo_path": "pythonCode/sample_with_interpolation.py", "max_stars_repo_name": "kgourgou/blog", "max_stars_repo_head_hexsha": "c9da56dc87a2b349efe06972a59706bfb181b197", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-12-02T06:18:58.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-07T20:21:04.000Z", "max_issues_repo_path": "pythonCode/sample_with_interpolation.py", "max_issues_repo_name": "kgourgou/blog", "max_issues_repo_head_hexsha": "c9da56dc87a2b349efe06972a59706bfb181b197", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pythonCode/sample_with_interpolation.py", "max_forks_repo_name": "kgourgou/blog", "max_forks_repo_head_hexsha": "c9da56dc87a2b349efe06972a59706bfb181b197", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.25, "max_line_length": 74, "alphanum_fraction": 0.6139917695, "include": true, "reason": "from scipy", "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854111860905, "lm_q2_score": 0.9005297787765764, "lm_q1q2_score": 0.8733206417961612}}
{"text": "\n# coding: utf-8\n\n# ## Exercises\n# \n# This will be a notebook for you to work through the exercises during the workshop. Feel free to work on these at whatever pace you feel works for you, but I encourage you to work together! Edit the title of this notebook with your name because I will ask you to upload your final notebook to our shared github repository at the end of this workshop.\n# \n# Feel free to google the documentation for numpy, matplotlib, etc.\n# \n# Don't forget to start by importing any libraries you need.\n\n# In[2]:\n\n\n# import your libraries here\nimport numpy as np\nimport pylab as plt\n\n\n# ### Day 1\n# \n# #### Exercise 1\n# \n#    A. Create an array with 10 evenly spaced values in logspace ranging from 0.1 to 10,000.\n# \n#    B. Print the following values: The first value in the array, the final value in the array, and the range of 5th-8th values.\n# \n#    C. Append the numbers 10,001 and 10,002 (as floats) to the array. Make sure you define this!\n# \n#    D. Divide your new array by 2.\n# \n#    E. Reshape your array to be 3 x 4. \n# \n#    F. Multiply your array by itself.\n#     \n#    G.  Print out the number of dimensions and the maximum value.\n\n# In[5]:\n\n\n# your solution here\n\nprint('A')\nlog_arr = np.logspace(-1, 4, 10)\nprint(log_arr)\nprint()\n\nprint('B')\nprint(log_arr[0], log_arr[-1], log_arr[4:8])\n\nprint()\n\nprint('C')\nx = np.array([10001. , 10002. ])\n\nnew_log_arr = np.append(log_arr, x)\nprint(new_log_arr)\nprint()\n\nprint('D')\ndivide_by_2 = new_log_arr/2\nprint(divide_by_2)\nprint()\n\nprint('E')\nreshaped_arr = divide_by_2.reshape((3,4))\n\nprint(reshaped_arr)\nprint()\n\nprint('F')\nmult = reshaped_arr * reshaped_arr\nprint(mult)\nprint()\n\nprint('G')\nprint(mult.ndim, np.amax(mult))\n\n\n# ### Day 2\n\n# #### Exercise 1\n# \n#    A. Create an array containing the values 4, 0, 6, 5, 11, 14, 12, 14, 5, 16.\n#    B. Create a 10x2 array of zeros.\n#    C. Write a for loop that checks if each of the numbers in the first array squared is less than 100. If the statement is true, change that row of your zeros array to equal the number and its square. Hint: you can change the value of an array by stating \"zerosarray[i] = [a number, a number squared]\". \n#    D. Print out the final version of your zeros array.\n#     \n# Hint: should you loop over the elements of the array or the indices of the array?\n\n# In[7]:\n\n\n# your solutions here\n\n#making my array\narr = np.array([4, 0, 6, 5, 11, 14, 12, 14, 5, 16])\n\n#making my 10X2 array of zeros\nzero_arr = np.zeros((10,2))\n\n#going through the loop and finding the square values < 100\nfor i, val in enumerate(arr):\n    \n    if val**2 < 100:\n        zero_arr[i] = [val, val**2]\n        \n        \nprint(zero_arr)        \n\n\n# #### Exercise 2\n#     \n#    A. Write a function that takes an array of numbers and spits out the Gaussian distribution. Yes, there is a function for this in Python, but it's good to do this from scratch! This is the equation:\n#     \n# $$ f(x) = \\frac{1}{\\sigma \\sqrt{2\\pi}} \\exp{\\frac{-(x - \\mu)^2}{2\\sigma^2}} $$\n# \n#     (Pi is built into numpy, so call it as np.pi.)\n# \n#    B. Call the function a few different times for different values of mu and sigma, between -10 < x < 10.\n#     \n#    C. Plot each version, making sure they are differentiated with different colors and/or linestyles and include a legend. Btw, here's a list of the customizations available in matplotlib:\n#     \n#     https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.plot.html\n#     \n#     https://matplotlib.org/gallery/color/named_colors.html\n#     \n#    D. Save your figure.\n#     \n# If you have multiple lines with plt.plot(), Python will plot all of them together, unless you write plt.show() after each one. I want these all on one plot.\n\n# In[24]:\n\n\n# your solutions here\ndef Gauss(x, mu, sigma):\n    '''\n    This function calculates the Guassian distribution given x, mu, sigma\n    \n    Parameters\n    -------------\n    x: the range of x values you are interested in finding the Gaussian distribution\n    mu: the average of the given distribution\n    sigma: the standard deviation of the distribution\n    \n    Output:\n    Gaussian distribution given the x, mu, and sigma you passed in\n    \n    '''\n    #making a prefactor variable\n    prefactor = 1/(sigma* np.sqrt(2*np.pi))\n    #making the exponential part into its own variable\n    exp = np.exp(-(x-mu)**2/(2*sigma**2))\n    \n    #returning the Gaussian\n    return prefactor * exp\n\n\n#making my x array\nx = np.linspace(-10, 10, 500)\n\ny1 = Gauss(x, 1, 1)\ny2 = Gauss(x, 3, .5)\ny3 = Gauss(x, -2, 4)\ny4 = Gauss(x, 1.2, .3)\ny5 = Gauss(x, -3.2, 2)  \n    \nplt.figure(figsize = (14, 8))\nplt.title('Gaussian Function', fontsize = 16)\nplt.xlabel('x values', fontsize = 16)\nplt.ylabel('y-values of Gaussian', fontsize = 16)\n\n#yaxis goes from 0 to 1 since it sproperly normalized by the prefactor\nplt.axis([x[0], x[-1], 0, 1])\nplt.plot(x, y1, 'r-', label = r'$\\mu$ = 1, $\\sigma$ = 1')\nplt.plot(x, y2, 'b--', label = r'$\\mu$ = 3, $\\sigma$ = .5')\nplt.plot(x, y3, 'k*', label = r'$\\mu$ = -2, $\\sigma$ = 4')\nplt.plot(x, y4, 'gs', label = r'$\\mu$ = 1.2, $\\sigma$ = 8')\nplt.plot(x, y5, 'yo', label = r'$\\mu$ = -3.2, $\\sigma$ = 6.75')\nplt.legend(loc = 'best')\nplt.savefig('Gaussian_Plots.pdf')\nplt.show()\n\n\n# ### Day 3\n# \n# #### Exercise 1\n# \n# There is a file in this directory called \"histogram_exercise.dat\" which consists of of randomly generated samples from a Gaussian distribution with an unknown $\\mu$ and $\\sigma$. Using what you've learned about fitting data, load up this file using np.genfromtxt, fit a Gaussian curve to the data and plot both the curve and the histogram of the data. As always, label everything, play with the colors, and choose a judicious bin size. \n# \n# Hint: if you attempt to call a function from a library or package that hasn't been imported, you will get an error.\n\n# In[5]:\n\n\nfrom scipy.stats import norm\n\n\n# In[6]:\n\n\n# your solution here\ngauss_data = np.loadtxt('histogram_exercise.dat')\n\n\n# In[8]:\n\n\nmu, sigma = norm.fit(gauss_data)\n\nx = np.linspace(np.min(gauss_data), np.max(gauss_data), 1000)\n\ngauss = norm.pdf(x, mu, sigma)\n\n\n# In[21]:\n\n\nplt.figure(figsize =(12, 12))\nplt.title('Gauss and Gaussian Fit')\nplt.plot(x, gauss, 'k', linewidth = 2, label= 'Gauss Fit')\nplt.hist(gauss_data, color= 'yellow', normed=True, hatch='//', label='Gaussian Data')\nplt.legend(loc='best')\nplt.show()\n\n\n# #### Exercise 2\n# \n# Create a 1D interpolation along these arrays. Plot both the data (as points) and the interpolation (as a dotted line). Also plot the value of the interpolated function at x=325. What does the function look like to you?\n\n# In[22]:\n\n\nfrom scipy.interpolate import interp1d\n\n\n# In[24]:\n\n\nx = np.array([0., 50., 100., 150., 200., 250., 300., 350., 400., 450., 500])\ny = np.array([0., 7.071, 10., 12.247, 14.142, 15.811, 17.321, 18.708, 20., 21.213, 22.361])\n\n# solution here\n\nf = interp1d(x, y)\n\n\n# In[34]:\n\n\nxnew = np.linspace(0, 500, 1000)\nplt.figure(figsize = (10,10))\nplt.plot(x, y, 'ko', label = 'Data')\nplt.plot(xnew, f(xnew), 'r--', label = 'Interpolation')\nplt.plot(325, f(325), 'b*', label = 'x = 325', markersize = 15)\nplt.legend(loc = 'best', frameon=False)\nplt.show()\n\n\n# In[1]:\n\n\nfrom astropy import constants as const\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy.io import fits\nimport aplpy\n\n\n# ### Day 4\n# \n# #### Exercise 1\n# \n# Let's practice some more plotting skills, now incorporating units. \n# \n# A. Write a function that takes an array of frequencies and spits out the Planck distribution. That's this equation:\n# \n# $$ B(\\nu, T) = \\frac{2h\\nu^3/c^2}{e^{\\frac{h\\nu}{k_B T}} - 1} $$\n# \n# This requires you to use the Planck constant, the Boltzmann constant, and the speed of light from astropy. Make sure they are all in cgs. \n#     \n# B. Plot your function in log-log space for T = 25, 50, and 300 K. The most sensible frequency range is about 10^5 to 10^15 Hz. Hint: if your units are correct, your peak values of B(T) should be on the order of 10^-10. Make sure everything is labelled. \n\n# In[4]:\n\n\nh = const.h.cgs\nk = const.k_B.cgs\nc = const.c.cgs.value\nprint(h)\nprint(k)\nprint(c)\n\n\n# In[8]:\n\n\nh = const.h.cgs.value\nk = const.k_B.cgs.value\nc = const.c.cgs.value\n\n# solution here\ndef blackbody(nu, T):\n    \n    \n    numerator = (2 * h * nu**3)/c**2\n    denom = np.exp((h * nu)/(k * T)) - 1\n    \n    return numerator/denom\n\nnu = np.linspace(1e5, 1e15, 1e5)\nT = [25, 50, 300]\n\nplt.figure(figsize = (10,10))\nplt.xlabel('Frequency [Hz]', fontsize = 16)\nplt.ylabel('Specific Intensity', fontsize = 16)\nplt.title('Planck Distribution', fontsize = 16)\n\nfor i in T:\n    plt.loglog(nu, blackbody(nu, i), label = str(i) + ' K')\n\nplt.legend(loc='best', fontsize = 14, frameon=False)\nplt.show()    \n\n\n# #### Exercise 2\n# \n# Let's put everything together now! Here's a link to the full documentation for FITSFigure, which will tell you all of the customizable options: http://aplpy.readthedocs.io/en/stable/api/aplpy.FITSFigure.html. Let's create a nice plot of M51 with a background optical image and X-ray contours overplotted.\n# \n# The data came from here if you're interested: http://chandra.harvard.edu/photo/openFITS/multiwavelength_data.html\n# \n# A. Using astropy, open the X-RAY data (m51_xray.fits). Flatten the data array and find its standard deviation, and call it sigma.\n# \n# B. Using aplpy, plot a colorscale image of the OPTICAL data. Choose a colormap that is visually appealing (list of them here: https://matplotlib.org/2.0.2/examples/color/colormaps_reference.html). Show the colorbar. \n# \n# C. Plot the X-ray data as contours above the optical image. Make the contours spring green with 80% opacity and dotted lines. Make the levels go from 2$\\sigma$ to 10$\\sigma$ in steps of 2$\\sigma$. (It might be easier to define the levels array before show_contours, and set levels=levels.)\n\n# In[20]:\n\n\n# solution here\ndata = fits.getdata('m51_xray.fits')\n\nflat_data = data.flatten()\n\nsigma = np.std(flat_data)\n\n\n# In[35]:\n\n\ngalaxy = aplpy.FITSFigure('m51_optical_B.fits')\ngalaxy.show_colorscale(cmap='cubehelix')\ngalaxy.show_colorbar()\n\nplt.show()\n\n\n# In[21]:\n\n\n2*sigma\n\n\n# In[29]:\n\n\nlevels = np.linspace(2*sigma, 10*sigma, num = 5)\nlevels[1]-levels[0]\n\n\n# In[36]:\n\n\nlevels = np.linspace(2*sigma, 10*sigma, num = ((8*sigma)/(2*sigma)))\n\ngalaxy = aplpy.FITSFigure('m51_optical_B.fits')\ngalaxy.show_colorscale(cmap='cubehelix')\ngalaxy.show_contour('m51_xray.fits', linestyle= 'dotted', colors = 'springgreen', alpha = .8, levels = levels)\n#galaxy.show_colorbar()\n\nplt.show()\n\n", "meta": {"hexsha": "ab3940b4f68ec781362438bf1a3f9a9744ee8b6e", "size": 10463, "ext": "py", "lang": "Python", "max_stars_repo_path": "Oscar_Chavez.py", "max_stars_repo_name": "UTAustinTAURUS/day-1-exercises-chavezoscar009", "max_stars_repo_head_hexsha": "282ebf78782d21cb4a085846f9cbf21f36f835db", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Oscar_Chavez.py", "max_issues_repo_name": "UTAustinTAURUS/day-1-exercises-chavezoscar009", "max_issues_repo_head_hexsha": "282ebf78782d21cb4a085846f9cbf21f36f835db", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Oscar_Chavez.py", "max_forks_repo_name": "UTAustinTAURUS/day-1-exercises-chavezoscar009", "max_forks_repo_head_hexsha": "282ebf78782d21cb4a085846f9cbf21f36f835db", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2473958333, "max_line_length": 438, "alphanum_fraction": 0.6735161999, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 3148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.924141826246517, "lm_q2_score": 0.9449947120938248, "lm_q1q2_score": 0.8733091390276888}}
{"text": "import numpy as np\nfrom numpy import array\nfrom numpy import mean\nfrom numpy.linalg import eig\n\nC_1 = array([[1, 2], [2, 3], [3, 3], [4, 5], [5, 5]])\nC_2 = array([[1, 0], [2, 1], [3, 1], [3, 2], [5, 3], [6, 5]])\nprint(\"We have the data:\")\nprint(\"Class C1:\\n\", C_1)\nprint(\"Class C1:\\n\", C_2)\nM_1 = mean(C_1.T, axis=1)\nM_2 = mean(C_2.T, axis=1)\nprint(\"Step1: Let's compute the mean for each class:\")\nprint(\"Mean of class C1: mu1 = \\n\", M_1)\nprint(\"Mean of class C2: mu2 = \\n\", M_2)\nS_1 = (len(C_1) - 1) * np.cov(C_1.T)\nS_2 = (len(C_2) - 1) * np.cov(C_2.T)\nprint(\"Step2: Let's compute the scatter matrices for each class:\")\nprint(\"Scatter matrix of class C1: S1 = \\n\", S_1)\nprint(\"Scatter matrix of class C2: S2 = \\n\", S_2)\nS_W = S_1 + S_2\nprint(\"Step3: Within the class scatter S_W = S_1 + S_2\")\nprint(\"S_W = \\n\", S_W)\nS_W_I = np.linalg.inv(S_W)\nprint(\"Step4: Let's compute the inverse of S_W\")\nprint(\"S_W_I = \\n\", S_W_I)\nV = np.matmul(S_W_I, (M_1 - M_2))\nprint(\"Step5: The optimal line direction v = S_W_I(mu1-mu2)\")\nprint(\"v = \\n\", V)\n", "meta": {"hexsha": "e0e915e6c74e64321432d1b6bed437d17494a947", "size": 1035, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/models/ul/LDA.py", "max_stars_repo_name": "sanatanonline/ml", "max_stars_repo_head_hexsha": "bed8c45913f8b85af35f0c6f1ea6099e744a78f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/models/ul/LDA.py", "max_issues_repo_name": "sanatanonline/ml", "max_issues_repo_head_hexsha": "bed8c45913f8b85af35f0c6f1ea6099e744a78f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/ul/LDA.py", "max_forks_repo_name": "sanatanonline/ml", "max_forks_repo_head_hexsha": "bed8c45913f8b85af35f0c6f1ea6099e744a78f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5, "max_line_length": 66, "alphanum_fraction": 0.6260869565, "include": true, "reason": "import numpy,from numpy", "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307676766119, "lm_q2_score": 0.8976952907388474, "lm_q1q2_score": 0.8733055988291522}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n########\n#Name: Conner Carnahan\n#ID: 1614309\n#Email: carna104@mail.chapman.edu\n#Class: PHYS220\n#Date: Oct 16, 2018\n########\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n@np.vectorize\ndef Sn(T,t,n):\n    \"\"\"Sn(float T,float t,int n): Returns a value computed by a sum of sin functions in accordance with the Fourier series expansion of sign(x)\"\"\"\n    if (abs(t) > T/2):\n        print(\"t should be within the range -T/2, T/2\")\n        pass\n    K = np.arange(1,n+1)\n    K = np.divide(4,np.pi*(2*K-1))\n    SinPeriods = np.divide(2*np.pi*(2*np.arange(1,n+1)-1),T)\n    value = np.sum(K*np.sin(SinPeriods*t))\n    return value\n\n@np.vectorize\ndef f(T,t):\n    \"\"\"f(float T, float t): Returns a value that is the sign of the value inputed\n       if t < 0 sign(t) = -1\n       if t > 0 sign(t) = 1\n       if t = 0 sign(t) = 0\"\"\"\n    if (abs(t) > T/2):\n        print(\"t should be between T/2\")\n        pass\n    return np.sign(t)\n\ndef Snarray(T,n,K = 300):\n    \"\"\"Snarray(T float, n int, K = 300 int): returns numpy array, Generates an array of values for K values of t in [-T/2,T/2] of the summed sines which approximate sign(x)\"\"\"\n    Time = np.linspace(-T/2,T/2,K)\n    return Sn(T,Time,n)\n\ndef farray(T,K = 300):\n    \"\"\"farray(T float, K = 300 int): returns numpy array of values evaluated by sign(x) for equally spaced K values of x in [-T/2,T/2]\"\"\"\n    Time = np.linspace(-T/2,T/2,K)\n    return f(T,Time)\n\ndef timespace(T,K = 300):\n    \"\"\"timespace(T float, K = 300 int), returns numpy array of K equally spaced values in [-T/2,T/2]\"\"\"\n    return np.linspace(-T/2,T/2,K)\n\n### DO NOT USE (OUT OF ORDER)\ndef buildallplots(alpha):\n    \"\"\"DON'T DO IT ONLY A PROTOTYPE\n    args: alpha (float),\n       returns null\n       This is a helper function that takes in a float, alpha,\n       and generates a sequence of partial Fourier Sums that approximate the sign function\"\"\"\n    T = alpha*2*np.pi\n    F1Array = ss.Snarray(T,1)\n    F3Array = ss.Snarray(T,3)\n    F5Array = ss.Snarray(T,5)\n    F10Array = ss.Snarray(T,10)\n    F30Array = ss.Snarray(T,30)\n    F100Array = ss.Snarray(T,100)\n    FuncArray = ss.farray(T)\n    Time = ss.timespace(T)\n###", "meta": {"hexsha": "1cd62ec9915afd3bab2a92f67eff792d28b15b8b", "size": 2200, "ext": "py", "lang": "Python", "max_stars_repo_path": "sinesum.py", "max_stars_repo_name": "chapman-phys220-2018f/cw08-forced-collaboration", "max_stars_repo_head_hexsha": "f21237668cc18bff47fbe506357848a47717fdb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sinesum.py", "max_issues_repo_name": "chapman-phys220-2018f/cw08-forced-collaboration", "max_issues_repo_head_hexsha": "f21237668cc18bff47fbe506357848a47717fdb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sinesum.py", "max_forks_repo_name": "chapman-phys220-2018f/cw08-forced-collaboration", "max_forks_repo_head_hexsha": "f21237668cc18bff47fbe506357848a47717fdb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.884057971, "max_line_length": 175, "alphanum_fraction": 0.6186363636, "include": true, "reason": "import numpy", "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288018, "lm_q2_score": 0.9161096170250075, "lm_q1q2_score": 0.8733044355047228}}
{"text": "from numpy.linalg import norm\nfrom math import sin, cos, asin, acos, atan2, pi, degrees\n\n\nclass Finesse:\n    @staticmethod\n    def forward_pack(lengths, angles):\n        \"\"\"\n        Computes the forward kinematics for the legs of DOG.\n        :param lengths: An array of lengths (l1, l2).\n        :param angles: An array of angles (theta1, theta2, theta3).\n        :return: (x3, y3, z3)\n        \"\"\"\n\n        l1, l2 = lengths\n        theta1, theta2, theta3 = angles\n\n        x1, y1, z1 = 0, 0, 0\n\n        x2 = -l1 * sin(theta1) * cos(theta2)\n        y2 = l1 * sin(theta2)\n        z2 = -l1 * cos(theta1) * cos(theta2)\n\n        x3 = x2 - l2 * cos(theta1) * sin(theta3) - l2 * cos(theta2) * cos(theta3) * sin(theta1)\n        y3 = y2 + l2 * cos(theta3) * sin(theta2)\n        z3 = z2 + l2 * sin(theta1) * sin(theta3) - l2 * cos(theta1) * cos(theta2) * cos(theta3)\n\n        return x3, y3, z3\n\n    @staticmethod\n    def inverse_pack(lengths, target, a2=False, a3=False, deg=True):\n        \"\"\"\n        Computes the inverse kinematics for the legs of DOG and Alpha\n        For the back legs of Alpha, pass 0 for y.\n        :param lengths: An array of lengths (l1, l2).\n        :param target: The coordinate of the target (x, y, z).\n        :param a2: Returns an alternate solution for theta2.\n        :param a3: Returns an alternate solution for theta3.\n        :param deg: Return the result in degrees if True and radians otherwise.\n        :return: (theta1, theta2, theta3)\n        \"\"\"\n\n        if lengths is None or target is None:\n            raise ValueError\n\n        l1, l2 = lengths\n        x, y, z = target\n        dist = norm(target)\n\n        if dist > sum(lengths):\n            raise ValueError\n\n        # theta3 *= -1\n        # Returns [0, 180]. +/- expands solution to [-180, 180].\n        theta3 = (l1 ** 2 + l2 ** 2 - dist ** 2) / (2 * l1 * l2)\n        theta3 = round(theta3, 13)\n        theta3 = acos(theta3) - pi\n        if a3:\n            theta3 *= -1\n\n        # theta2 = (pi - theta2)\n        # Returns [-90, 90]. (pi - theta2) expands solution to [-180, 180].\n        theta2 = y / (l1 + l2 * cos(theta3))\n        theta2 = round(theta2, 13)\n        theta2 = asin(theta2)\n        if a2:\n            theta2 = pi - theta2\n\n        # theta1 -= 2 * pi\n        # Sometimes (theta1 - 2 * pi). Doesn't matter. Either is cool.\n        theta1 = atan2(z, -x) + atan2((l1 + l2 * cos(theta3)) * cos(theta2), l2 * sin(theta3))\n\n        if deg:\n            return degrees(theta1), degrees(theta2), degrees(theta3)\n        else:\n            return theta1, theta2, theta3\n\n", "meta": {"hexsha": "a6f7c42007eef5cb6393898722eb547c87e16d24", "size": 2564, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/finesse/eclipse.py", "max_stars_repo_name": "bobbyluig/eclipse", "max_stars_repo_head_hexsha": "ed2d3ed40b878eaddaf8997749fde5a11428964e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-12-11T19:09:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T00:28:40.000Z", "max_issues_repo_path": "src/finesse/eclipse.py", "max_issues_repo_name": "bobbyluig/Eclipse", "max_issues_repo_head_hexsha": "ed2d3ed40b878eaddaf8997749fde5a11428964e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/finesse/eclipse.py", "max_forks_repo_name": "bobbyluig/Eclipse", "max_forks_repo_head_hexsha": "ed2d3ed40b878eaddaf8997749fde5a11428964e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-10T07:20:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-10T07:20:04.000Z", "avg_line_length": 32.8717948718, "max_line_length": 95, "alphanum_fraction": 0.5456318253, "include": true, "reason": "from numpy", "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9759464478051827, "lm_q2_score": 0.8947894527758052, "lm_q1q2_score": 0.8732665879700904}}
{"text": "'''\r\n    Recursive multiplication algorithms.\r\n'''\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport timeit\r\n\r\n\r\ndef pad_inputs_(x, y):\r\n    '''Left 0-pad inputs to have equal number of digits.'''\r\n    if len(x) > len(y):\r\n        y = '0' * (len(x) - len(y)) + y\r\n    elif len(y) > len(x):\r\n        x = '0' * (len(y) - len(x)) + x\r\n    return x, y\r\n\r\n\r\ndef split_input_(s):\r\n    '''Splits input digits in half.'''\r\n    split_point = len(s) // 2\r\n    return s[:split_point], s[split_point:] \r\n\r\n\r\ndef rec_int_mult_(x, y):\r\n    '''Multiply two integers using a recrusive approach.'''\r\n    # Pad inputs to be the same length\r\n    x, y = pad_inputs_(x, y)\r\n    \r\n    # Check for base case\r\n    n = len(x)\r\n    if n == 1:\r\n        return int(x) * int(y)\r\n    \r\n    # Split inputs\r\n    a, b = split_input_(x)\r\n    c, d = split_input_(y)\r\n    \r\n    # Recursively compute pair products\r\n    ac = rec_int_mult_(a, c)\r\n    ad = rec_int_mult_(a, d)\r\n    bc = rec_int_mult_(b, c)\r\n    bd = rec_int_mult_(b, d)\r\n    \r\n    # Combine results\r\n    if n % 2 == 1: # Handle odd-length strings\r\n        n += 1\r\n    return ac*10**(n) + (ad + bc)*10**(n//2) + bd\r\n\r\n\r\ndef rec_int_mult(x, y):\r\n    '''Multiply two integers using a recursive approach.\r\n    \r\n    Parameters\r\n    ----------\r\n    x : int\r\n        The left operand for integer multiplication.\r\n    y : int\r\n        The right operand for integer multiplication.\r\n    Returns\r\n    -------\r\n    int\r\n        The result of multiplying x and y.\r\n        \r\n    Based off pseudocode from Algorithms Illuminated Part 1.\r\n    '''\r\n    # This is a wrapper to cast the inputs to strings for the first call\r\n    x = str(x)\r\n    y = str(y)\r\n    return rec_int_mult_(x, y)\r\n\r\n\r\ndef karatsuba_(x, y):\r\n    '''Multiply two integers using Karatsuba multiplication.'''\r\n    # Pad inputs to be the same length\r\n    x, y = pad_inputs_(x, y)\r\n    \r\n    # Check for base case\r\n    n = len(x)\r\n    if n == 1:\r\n        return int(x) * int(y)\r\n    \r\n    # Split inputs\r\n    a, b = split_input_(x)\r\n    c, d = split_input_(y)\r\n    \r\n    # Compute p and q\r\n    p = str(int(a) + int(b))\r\n    q = str(int(c) + int(d))\r\n    \r\n    # Recursively compute pair products\r\n    ac = karatsuba_(a, c)\r\n    bd = karatsuba_(b, d)\r\n    pq = karatsuba_(p, q)\r\n    \r\n    # Combine results\r\n    adbc = pq - ac - bd\r\n    if n % 2 == 1: # Handle odd-length strings\r\n        n += 1\r\n    return ac*10**(n) + (adbc)*10**(n//2) + bd    \r\n\r\n\r\ndef karatsuba(x, y):\r\n    '''Multiply two integers using Karatsuba multiplication.\r\n    \r\n    Parameters\r\n    ----------\r\n    x : int\r\n        The left operand for integer multiplication.\r\n    y : int\r\n        The right operand for integer multiplication.\r\n    Returns\r\n    -------\r\n    int\r\n        The result of multiplying x and y.\r\n        \r\n    Based off pseudocode from Algorithms Illuminated Part 1.\r\n    '''\r\n    # This is a wrapper to cast the inputs to strings for the first call\r\n    x = str(x)\r\n    y = str(y)\r\n    return karatsuba_(x, y)\r\n\r\n\r\ndef built_in_multiply(x, y):\r\n    '''Applies the built-in multiplication operator '''\r\n    return x * y\r\n\r\n\r\ndef get_random_input(n):\r\n    '''Returns random integer with specified number of digits.'''\r\n    return int(''.join([str(digit) for digit in np.random.randint(0,10,n)]))\r\n\r\n\r\ndef get_setup(algorithm_name, n):\r\n    s = f\"from __main__ import {algorithm_name}; import numpy as np;\"\r\n    s += f\"x = int(''.join([str(digit) for digit in np.random.randint(0,10,{n})]));\"\r\n    s += f\"y = int(''.join([str(digit) for digit in np.random.randint(0,10,{n})]));\"\r\n    return s \r\n\r\n\r\nif __name__ == '__main__':\r\n    # First, correctness tests involving varying length combinations\r\n    algorithms = {'rec_int_mult': rec_int_mult, 'karatsuba': karatsuba} \r\n    digit_range = (1,20) # Range of number of digits to test\r\n    for algorithm_name, algorithm in algorithms.items():\r\n        print(f'\\nRunning correctness tests for {algorithm_name} with number of digits from {digit_range[0]} to {digit_range[1]}...')\r\n        num_tested = 0\r\n        num_passed = 0\r\n        failed_inputs = []\r\n        # Tests all permutations of digit ranges with built-in operator as reference\r\n        for x_digits in range(min_digits, max_digits):\r\n            for y_digits in range(min_digits, max_digits):\r\n                x, y = get_random_input(x_digits), get_random_input(y_digits)\r\n                result = algorithm(x, y)\r\n                if result == x * y:\r\n                    num_passed += 1\r\n                else:\r\n                    failed_inputs.append((x, y))\r\n                num_tested += 1\r\n        print(f'Results: {num_passed} passed out of {num_tested} tests.')\r\n        if num_tested > num_passed:\r\n            print(f'Failed input sets:')\r\n            for inputs in failed_inputs:\r\n                print(inputs)\r\n\r\n    # Second, timing tests for various input sizes\r\n    algorithms['built_in_multiply'] = built_in_multiply\r\n    results = pd.DataFrame(data={'n':[40, 80, 160, 320]})\r\n    for algorithm_name, algorithm in algorithms.items():\r\n        print(f'\\nRunning timing tests for {algorithm_name}...')\r\n        temp_results = []\r\n        for n in results['n'].values:\r\n            n = int(n)\r\n            temp_results.append(np.round(timeit.timeit(f'{algorithm_name}(x, y)', setup=get_setup(algorithm_name, n), number=1), 4))\r\n        results[algorithm_name] = temp_results\r\n    print('Timing tests complete.')\r\n    print(results.head(results.shape[0]))", "meta": {"hexsha": "4d2e224b255d5f918c9803b0e541f8ebf0d7ed1f", "size": 5448, "ext": "py", "lang": "Python", "max_stars_repo_path": "algorithms_illuminated/part_1/chapter_1/multiply.py", "max_stars_repo_name": "andrewdoss/algorithms_practice", "max_stars_repo_head_hexsha": "671ae4a4ec05b6cf87ee44faf092456444ed3cf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-25T08:05:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T16:15:25.000Z", "max_issues_repo_path": "algorithms_illuminated/part_1/chapter_1/multiply.py", "max_issues_repo_name": "andrewdoss/algorithms_illuminated", "max_issues_repo_head_hexsha": "671ae4a4ec05b6cf87ee44faf092456444ed3cf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorithms_illuminated/part_1/chapter_1/multiply.py", "max_forks_repo_name": "andrewdoss/algorithms_illuminated", "max_forks_repo_head_hexsha": "671ae4a4ec05b6cf87ee44faf092456444ed3cf0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.606741573, "max_line_length": 134, "alphanum_fraction": 0.5737885463, "include": true, "reason": "import numpy", "num_tokens": 1423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.927363286612953, "lm_q1q2_score": 0.8732554991400147}}
{"text": "# Load modules\nfrom __future__ import print_function\nimport os\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# read the data from into a pandas.DataFrame\nwisc_emp = pd.read_csv(\"datasets/wisconsin-employment-time-series.csv\")\n\n# Let's find out the shape of the DataFrame\nprint(\"Shape of the DataFrame:\", wisc_emp.shape)\n\n# Let's see first 10 rows of it\nwisc_emp.head()\n\n# plot the wisconsin employment dataset\nwisc_emp.plot()\n\n# Capture seasonality component\ndef initialize_T(x, seasonLength):\n    total = 0.0\n    for i in range(seasonLength):\n        total += float(x[i + seasonLength] - x[i]) / seasonLength\n    return total\n\n\ninitialize_T(wisc_emp[\"Employment\"], 12)\n\n# Initialize seasonal trend\ndef initialize_seasonalilty(x, seasonLength):\n    seasons = {}\n    seasonsMean = []\n    num_season = int(len(x) / seasonLength)\n    # Compute season average\n    for i in range(num_season):\n        seasonsMean.append(\n            sum(x[seasonLength * i : seasonLength * i + seasonLength])\n            / float(seasonLength)\n        )\n\n    # compute season intial values\n    for i in range(seasonLength):\n        tot = 0.0\n        for j in range(num_season):\n            tot += x[seasonLength * j + i] - seasonsMean[j]\n        seasons[i] = tot / num_season\n    return seasons\n\n\ninitialize_seasonalilty(wisc_emp[\"Employment\"], 12)\n\n\n# Triple Exponential Smoothing Forecast\ndef triple_exp_smoothing(x, seasonLength, alpha, beta, gamma, h):\n    yhat = []\n    S = initialize_seasonalilty(x, seasonLength)\n    for i in range(len(x) + h):\n        if i == 0:\n            F = x[0]\n            T = initialize_T(x, seasonLength)\n            yhat.append(x[0])\n            continue\n        if i >= len(x):\n            m = i - len(x) + 1\n            yhat.append((F + m * T) + S[i % seasonLength])\n        else:\n            obsval = x[i]\n            F_last, F = (\n                F,\n                alpha * (obsval - S[i % seasonLength]) + (1 - alpha) * (F + T),\n            )\n            T = beta * (F - F_last) + (1 - beta) * T\n            S[i % seasonLength] = (\n                gamma * (obsval - F) + (1 - gamma) * S[i % seasonLength]\n            )\n            yhat.append(F + T + S[i % seasonLength])\n    return yhat\n\n\n# Triple exponential smoothing\nwisc_emp[\"TES\"] = triple_exp_smoothing(wisc_emp[\"Employment\"], 12, 0.4, 0.6, 0.2, 0)\n\n### Plot Single Exponential Smoothing forecasted value\nfig = plt.figure(figsize=(5.5, 5.5))\nax = fig.add_subplot(2, 1, 1)\nwisc_emp[\"Employment\"].plot(ax=ax)\nax.set_title(\"Beer Production\")\nax = fig.add_subplot(2, 1, 2)\nwisc_emp[\"TES\"].plot(ax=ax, color=\"r\")\nax.set_title(\"Triple Smoothing Forecast\")\nplt.savefig(\"plots/ch2/B07887_03_14.png\", format=\"png\", dpi=300)\n", "meta": {"hexsha": "35aaa79cc824bb9bc9efa1ef2b92094ef627020a", "size": 2719, "ext": "py", "lang": "Python", "max_stars_repo_path": "time series regression/autocorelation, mov avg etc/tripleExponentialSmoothing.py", "max_stars_repo_name": "Diyago/ML-DL-scripts", "max_stars_repo_head_hexsha": "40718a9d4318d6d6531bcea5998c0a18afcd9cb3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 142, "max_stars_repo_stars_event_min_datetime": "2018-09-02T08:59:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:08:24.000Z", "max_issues_repo_path": "time series regression/autocorelation, mov avg etc/tripleExponentialSmoothing.py", "max_issues_repo_name": "jerinka/ML-DL-scripts", "max_issues_repo_head_hexsha": "eeb5c3c7c5841eb4cdb272690e14d6718f3685b2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-09-08T07:27:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-19T05:50:24.000Z", "max_forks_repo_path": "time series regression/autocorelation, mov avg etc/tripleExponentialSmoothing.py", "max_forks_repo_name": "jerinka/ML-DL-scripts", "max_forks_repo_head_hexsha": "eeb5c3c7c5841eb4cdb272690e14d6718f3685b2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 75, "max_forks_repo_forks_event_min_datetime": "2018-10-04T17:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T18:50:52.000Z", "avg_line_length": 29.2365591398, "max_line_length": 84, "alphanum_fraction": 0.6130930489, "include": true, "reason": "import numpy", "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543366, "lm_q2_score": 0.905989826094673, "lm_q1q2_score": 0.8731748220953425}}
{"text": "# find the inverse of a matrix using Gaussian elimination\n\nimport numpy\n\ndef inverse(AInput):\n    \"\"\" return the inverse of AInput \"\"\"\n\n    A = AInput.copy()\n\n    N = len(A[:,0])\n\n    # A is square, with each dimension of length N\n    if not (A.shape[0] == A.shape[1]):\n        print \"ERROR: A should be square\"\n        return None\n\n    # create an identity matrix\n    I = numpy.identity(N)\n\n    # allocation for the inverse\n    Ainv = numpy.zeros((N,N), dtype=A.dtype)\n\n    # find the scale factors for each row -- this is used when pivoting\n    scales = numpy.max(numpy.abs(A), 1)\n\n    # keep track of the number of times we swapped rows\n    numRowSwap = 0\n\n    # we are essentially doing Gaussian elimination, but with A Ainv = I\n    # each column of I represents a separate righthand side to an Ax = b\n    # linear system\n\n    # main loop over rows\n    for k in range(N):\n        \n        # find the pivot row based on the size of column k -- only consider\n        # the rows beyond the current row\n        rowMax = numpy.argmax(A[k:, k]/scales[k:]) \n        if (k > 0): rowMax += k  # we sliced A from k:, correct for total rows\n\n        # swap the row with the largest scaled element in the current column\n        # with the current row (pivot) -- do this with b too!\n        if not rowMax == k:\n            A[[k, rowMax],:] = A[[rowMax, k],:]\n            I[[k, rowMax],:] = I[[rowMax, k],:]\n            numRowSwap += 1\n\n        # do the forward-elimination for all rows below the current\n        for i in range(k+1, N):\n            coeff = A[i,k]/A[k,k]\n\n            for j in range(k+1, N):\n                A[i,j] += -A[k,j]*coeff\n\n            A[i,k] = 0.0\n            I[i,:] += -coeff*I[k,:]\n    \n    \n\n    # back-substitution -- once for each column in the I matrix\n    \n    for c in range(N):\n\n        # last solution is easy\n        Ainv[N-1,c] = I[N-1,c]/A[N-1,N-1]\n\n        for i in reversed(range(N-1)):\n            sum = I[i,c]\n            for j in range(i+1,N):\n                sum += -A[i,j]*Ainv[j,c]\n            Ainv[i,c] = sum/A[i,i]\n\n\n    # determinant\n    det = numpy.prod(numpy.diagonal(A))*(-1.0)**numRowSwap\n    \n    return Ainv\n\n\n# output: numpy.savetxt(\"test.out\", a, fmt=\"%5.2f\", delimiter=\"  \")\n# convert -font Courier-New-Regular -pointsize 20 text:test.out test.png\n\n\nA = numpy.array([ [4, 3, 4, 10], [2, -7, 3, 0], [-2, 11, 1, 3], [3, -4, 0, 2] ], dtype=numpy.float64)\nAinv = inverse(A)\nprint \"A . Ainv = \\n\", numpy.dot(A, Ainv)\nprint\" Ainv = \\n\", Ainv\n\nprint \" \"\n\nA = numpy.array([ [0, 1, 1], [1, 1, 0], [1, 0, 1] ], dtype=numpy.float64)\nAinv = inverse(A)\nprint \"A . Ainv = \\n\", numpy.dot(A, Ainv)\n\nprint \" \"\n\nA = numpy.array([ [0, 0, 0, 4], \n                  [0, 0, 3, 0], \n                  [5, 6, 7, 8],\n                  [0, 4, 3, 2] ], dtype=numpy.float64)\nAinv = inverse(A)\nprint \"A . Ainv = \\n\", numpy.dot(A, Ainv)\n\n\n\n", "meta": {"hexsha": "f4039a7a9e298f6c36c08688bdd98423522841f7", "size": 2859, "ext": "py", "lang": "Python", "max_stars_repo_path": "others/lin_algebra/inverse.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "others/lin_algebra/inverse.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/lin_algebra/inverse.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 26.9716981132, "max_line_length": 101, "alphanum_fraction": 0.5383001049, "include": true, "reason": "import numpy", "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799430946808, "lm_q2_score": 0.9059898241909247, "lm_q1q2_score": 0.8731748212030893}}
{"text": "\"\"\"\n3D version of approx2D.py.\nNumerical integration only.\n\"\"\"\nimport sympy as sym\nimport numpy as np\nimport scipy.integrate\n\ndef least_squares(f, psi, Omega):\n    \"\"\"\n    Given a function f(x,y,z) on a rectangular domain\n    Omega=[[xmin,xmax],[ymin,ymax],[zmin,zmax]],\n    return the best approximation to f in the space V\n    spanned by the functions in the list psi.\n    f and psi are symbolic (sympy) expressions, but will\n    be converted to numeric functions for faster integration.\n    \"\"\"\n    N = len(psi) - 1\n    A = np.zeros((N+1, N+1))\n    b = np.zeros(N+1)\n    x, y, z = sym.symbols('x y z')\n    f = sym.lambdify([x, y, z], f, modules='numpy')\n    psi_sym = psi[:]  # take a copy, needed for forming u later\n    psi = [sym.lambdify([x, y, z], psi[i]) for i in range(len(psi))]\n\n    print('...evaluating matrix...')\n    for i in range(N+1):\n        for j in range(i, N+1):\n            print(('(%d,%d)' % (i, j)))\n\n            integrand = lambda x, y, z: psi[i](x,y,z)*psi[j](x,y,z)\n            I, err = scipy.integrate.nquad(\n                integrand,\n                [[Omega[0][0], Omega[0][1]],\n                 [Omega[1][0], Omega[1][1]],\n                 [Omega[2][0], Omega[2][1]]])\n            A[i,j] = A[j,i] = I\n        integrand = lambda x, y, z: psi[i](x,y,z)*f(x,y,z)\n        I, err = scipy.integrate.nquad(\n            integrand,\n            [[Omega[0][0], Omega[0][1]],\n             [Omega[1][0], Omega[1][1]],\n             [Omega[2][0], Omega[2][1]]])\n        b[i] = I\n    print()\n    c = np.linalg.solve(A, b)\n    if N <= 10:\n        print(('A:\\n', A, '\\nb:\\n', b))\n        print(('coeff:', c))\n    u = sum(c[i]*psi_sym[i] for i in range(len(psi_sym)))\n    print(('approximation:', u))\n    return u, c\n\ndef sine_basis(Nx, Ny, Nz):\n    \"\"\"\n    Compute basis sin((p+1)*pi*x)*sin((q+1)*pi*y)*sin((r+1)*pi*z),\n    p=0,...,Nx, q=0,...,Ny, r=0,...,Nz.\n    \"\"\"\n    x, y, z = sym.symbols('x y z')\n    psi = []\n    for r in range(0, Nz+1):\n        for q in range(0, Ny+1):\n            for p in range(0, Nx+1):\n                s = sym.sin((p+1)*sym.pi*x)*\\\n                    sym.sin((q+1)*sym.pi*y)*sym.sin((r+1)*sym.pi*z)\n                psi.append(s)\n    return psi\n\ndef test_least_squares():\n    # Use sine functions\n    x, y, z = sym.symbols('x y z')\n    N = 1  # (N+1)**3 = 8 basis functions\n    psi = sine_basis(N, N, N)\n    f_coeff = [0]*len(psi)\n    f_coeff[3] = 2\n    f_coeff[4] = 3\n    f = sum(f_coeff[i]*psi[i] for i in range(len(psi)))\n    # Check that u exactly reproduces f\n    u, c = least_squares(f, psi, Omega=[[0,1], [0,1], [0,1]])\n    diff = np.abs(np.array(c) - np.array(f_coeff)).max()\n    print(('diff:', diff))\n    tol = 1E-15\n    assert diff < tol\n\nif __name__ == '__main__':\n    import time\n    t0 = time.clock()\n    test_least_squares()\n", "meta": {"hexsha": "3d51a2133cdb045c58ec9bfe834dfe1a5f50ca7a", "size": 2783, "ext": "py", "lang": "Python", "max_stars_repo_path": "exer/approx3D.py", "max_stars_repo_name": "mbarzegary/finite-element-intro", "max_stars_repo_head_hexsha": "47ef0a3592b823ae71a874ee35850114f16b6d8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-01-26T13:18:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T15:20:11.000Z", "max_issues_repo_path": "exer/approx3D.py", "max_issues_repo_name": "mbarzegary/finite-element-intro", "max_issues_repo_head_hexsha": "47ef0a3592b823ae71a874ee35850114f16b6d8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exer/approx3D.py", "max_forks_repo_name": "mbarzegary/finite-element-intro", "max_forks_repo_head_hexsha": "47ef0a3592b823ae71a874ee35850114f16b6d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-05T23:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T10:22:29.000Z", "avg_line_length": 31.2696629213, "max_line_length": 68, "alphanum_fraction": 0.5102407474, "include": true, "reason": "import numpy,import scipy,import sympy", "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920617, "lm_q2_score": 0.9086179025005187, "lm_q1q2_score": 0.8731379256834851}}
{"text": "import numpy as np;\n\nar=np.array([1,2,3])\n\nar=np.array([(1,2,3),(3,4,5)],dtype=float)\n# print(ar)\n\nar = np.array([(1, 2, 3), (3, 4, 5),(6,7,8)], dtype=float)\n\n# print(ar)\n\n#Creating Zero\nprint(np.zeros((2,3)))\n\nprint(np.ones((3,3),dtype=np.int16))\n\nprint(np.arange(2,10,2))\n\nprint(np.linspace(1,10,10))\n\nprint(ar.T) #Transpose\n\narT=ar.T\n\n#Dot mul\nprint(ar.dot(arT))\n\n\"\"\" Determinant of upper triangle or diagnal matrix is product of diagnal element \"\"\"\n\na = np.array([(2, 3, 4), (0, 2, 5), (0, 0, 2)])\n# a\n# array([[2, 3, 4],\n#        [0, 2, 5],\n#        [0, 0, 2]])\nprint(np.linalg.det(a))\n# 7.999999999999998\n\n\"\"\" Determinant of row exhanged matrix will change the sign \"\"\"\n\na=np.array([(2, 3, 4), (0, 0, 2), (0, 2, 5)])\nprint(np.linalg.det(a))\n# - 7.999999999999998\n\n\"\"\" Determinant of identiy matrix is 1 \"\"\"\na = np.array([(1,0,0), (0, 1, 0), (0, 0,1)])\nprint(np.linalg.det(a))\n# 1\n", "meta": {"hexsha": "7ce828c456d4edece9e40d661d98929e078b3880", "size": 886, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numpy/Numpy_1.py", "max_stars_repo_name": "rrsalian/Machine-Learning", "max_stars_repo_head_hexsha": "deb2ddc0228f6ffcf67213a4b98c7bb57c9379a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numpy/Numpy_1.py", "max_issues_repo_name": "rrsalian/Machine-Learning", "max_issues_repo_head_hexsha": "deb2ddc0228f6ffcf67213a4b98c7bb57c9379a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numpy/Numpy_1.py", "max_forks_repo_name": "rrsalian/Machine-Learning", "max_forks_repo_head_hexsha": "deb2ddc0228f6ffcf67213a4b98c7bb57c9379a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.4583333333, "max_line_length": 85, "alphanum_fraction": 0.5823927765, "include": true, "reason": "import numpy", "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517106286379, "lm_q2_score": 0.9086178913651383, "lm_q1q2_score": 0.8731379170151156}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.style.use('ggplot')\n\n########## Função degrau\ndef step():\n    z = np.arange(-5, 5, .001)\n    step_fn = np.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)\n    step = step_fn(z)\n    return z, step, \"Função degrau\"\n\ndef step_d():\n    z = np.arange(-5, 5, .02)\n    return z, [0]*len(z), \"Derivada da função degrau\"\n\n\n########## Função logística\ndef logistic():\n    z = np.arange(-10, 10, .1)\n    sigma_fn = np.vectorize(lambda z: 1/(1+np.exp(-z)))\n    sigma = sigma_fn(z)\n    return z, sigma, \"Função logística\"\n\ndef logistic_d():\n    z = np.arange(-10, 10, .1)\n    sigma_fn = np.vectorize(lambda z: np.exp(-z)/((np.exp(-z) + 1)**2))\n    sigma = sigma_fn(z)\n    return z, sigma, \"Derivada da função logística\"\n\n\n########## Função ReLU\ndef relu():\n    z = np.arange(-2, 2, .01)\n    zero = np.zeros(len(z))\n    y = np.max([zero, z], axis=0)\n    return z, y, \"Função ReLU\"\n\ndef relu_d():\n    z = np.arange(-2, 2, .01)\n    y = [1 if x > 0 else 0 for x in z]\n    return z, y, \"Derivada da função ReLU\"\n\n\n########## Função LeakyReLU\ndef lrelu(alpha=.2):\n    z = np.arange(-2, 2, .01)\n    y = [x if x > 0 else alpha*x for x in z]\n    return z, y, \"Função LeakyReLU (α = 0.2)\"\n\ndef lrelu_d(alpha=.2):\n    z = np.arange(-2, 2, .01)\n    y = [1 if x > 0 else alpha for x in z]\n    return z, y, \"Derivada da função LeakyReLU (α = 0.2)\"\n\n\n########## Função tangente hiperbólica\ndef tanh():\n    z = np.arange(-5, 5, .1)\n    t = np.tanh(z)\n    return z, t, \"Função tangente hiperbólica\"\n\ndef tanh_d():\n    z = np.arange(-5, 5, .1)\n    # sech(z) = 1 / cosh(z)\n    t = 1/np.cosh(z)\n    return z, t, \"Derivada da função tangente hiperbólica\"\n\n########## Função tangente hiperbólica\ndef mish():\n    z = np.arange(-5, 5, .1)\n    t = z * np.tanh(np.log(1 + np.exp(z)))\n    return z, t, \"Função Mish\"\n\ndef mish_d():\n    z = np.arange(-5, 5, .1)\n    t = ((2*np.exp(z)*z*(1+np.exp(z)))/((1+np.exp(z))**2+1)) - \\\n            (2*np.exp(z)*z*((1+np.exp(z))**2 - 1)*(1+np.exp(z)))/((1+np.exp(z))**2 + 1)**2 + \\\n                ((1+np.exp(z))**2 - 1)/((1+np.exp(z))**2 + 1)\n    return z, t, \"Derivada da função Mish\"\n\n########## Função APL\ndef apl_func(x,a,b):\n    return max(0, x) + sum([a[i]*max(0, -x + b[i]) for i in range(len(a))])\n\ndef apl(a=[.2], b=[0]):\n    z = np.arange(-5, 5, .01)\n    t = [apl_func(x,a,b) for x in z]\n    return z, t, \"Função APL (a = \" + a + \"; b = \" + b + \")\"\n\ndef apl_d_a02_b0():\n    z = np.arange(-5, 5, .01)\n    t = [1 if x > 0 else -0.2 for x in z]\n    return z, t, \"Derivada da função APL (a = 0.2; b = 0)\"\n\n########## Função SHReLU\ndef shrelu(tau=0.2):\n    z = np.arange(-5, 5, .01)\n    t = [0.5*(x + np.sqrt(x**2 + tau**2)) for x in z]\n    return z, t, \"Função SHReLU (τ = %.2f)\" % (tau)\n\ndef shrelu_d(tau=0.2):\n    z = np.arange(-5, 5, .01)\n    t = [0.5*((x/(np.sqrt(x**2 + tau**2))) + 1) for x in z]\n    return z, t, \"Derivada da função SHReLU (τ = %.2f)\" % (tau)\n\n########## Função BHSA\ndef h1_bhsa(l, tau, z):\n    return np.sqrt( (l**2) * (z + (1/(2*l)))**2 + tau**2)\n\ndef h2_bhsa(l, tau, z):\n    return np.sqrt( (l**2) * (z - (1/(2*l)))**2 + tau**2)\n\ndef bhsa(l=1, tau=0, z = None):\n    # h1 = torch.sqrt( ((self.l**2) * (x + (1/(2*self.l)))**2) + self.t1**2 )\n    # h2 = torch.sqrt( ((self.l**2) * (x - (1/(2*self.l)))**2) + self.t2**2 )\n    if z is None: z = np.arange(-5, 5, .01)\n    t = h1_bhsa(l, tau, z) - h2_bhsa(l, tau, z)\n    return z, t, \"Função BHSA (λ = %.2f; τ = %.2f)\" % (l, tau)\n\ndef bhsa_d(l=1, tau=0):\n    z = np.arange(-5, 5, .01)\n    t = (l * (1 - 2 * l * z))/np.sqrt(4 * tau**2 + (1 - 2 * l * z)**2) + (l * (1 + 2 * l * z))/np.sqrt(4 * tau**2 + (1 + 2 * l * z)**2)\n    return z, t, \"Derivada da função BHSA (λ = %.2f; τ = %.2f)\" % (l, tau)\n\n########## Função BHAA\ndef bhaa(l=1, tau1=0, tau2=0):\n    z = np.arange(-5, 5, .01)\n    t = np.sqrt((l**2) * (z+(1/(2*l)))**2 + (tau1**2)) - np.sqrt((l**2) * (z-(1/(2*l)))**2 + (tau2**2))\n    return z, t, \"Função BHAA (λ = %.2f; τ1 = %.2f; τ2 = %.2f)\" % (l, tau1, tau2)\n\ndef bhaa_d(l=1, tau1=0, tau2=0):\n    z = np.arange(-5, 5, .01)\n    t = (l * (1 - 2 * l * z))/np.sqrt((1 - 2 * l * z)**2 + 4 * tau2**2) + (l * (2 * l * z + 1))/np.sqrt((2 * l * z + 1)**2 + 4 * tau1**2)\n    return z, t, \"Derivada da função BHAA (λ = %.2f; τ1 = %.2f; τ2 = %.2f)\" % (l, tau1, tau2)\n\ndef bhata(l=1,tau1=0,tau2=0):\n    z, t, _ = bhaa(l, tau1, tau2)\n    t[t > 1] = 1\n    t[t < -1] = -1\n    return z, t, \"Função BHAA truncada (λ = %.2f; τ1 = %.2f; τ2 = %.2f)\" % (l, tau1, tau2)\n\ndef func_bh_derivative_equal_to_zero(tau1, tau2, l):\n    return [(tau1 - tau2)/(2*l*(tau1 + tau2)), (tau1 + tau2)/(2*l*(tau1 - tau2))]\n\ndef raw_func_bh_derivative(x, tau1, tau2, l):\n    return (l * (1 - 2 * l * x))/np.sqrt(4 * tau2**2 + (1 - 2 * l * x)**2) + (l * (1 + 2 * l * x))/np.sqrt(4 * tau1**2 + (1 + 2 * l * x)**2)\n\ndef raw_func_bh(x, tau1, tau2, l):\n    return (np.sqrt((l**2) * (x+(1/(2*l)))**2 + (tau1**2)) - np.sqrt((l**2) * (x-(1/(2*l)))**2 + (tau2**2)))\n\ndef bhana(l=1,tau1=0,tau2=0):\n    z = np.arange(-5, 5, .001)\n    result = raw_func_bh(z, tau1, tau2, l)\n    func_points_edge_value = func_bh_derivative_equal_to_zero(tau1, tau2, l)\n    func_points_edge_value = max(func_points_edge_value) if abs(tau1) > abs(tau2) else min(func_points_edge_value)\n    func_edge_value = raw_func_bh(func_points_edge_value, tau1, tau2, l)\n\n    if(abs(tau1) > abs(tau2)):\n        result = (result - (-1))/(func_edge_value + 0.001 - (-1))\n    elif(abs(tau2) > abs(tau1)):\n        result = (result - func_edge_value)/(1 + 0.001 - func_edge_value)\n\n    result = (result - 0.5) * 2\n\n    return z, result, \"Função BHANA (λ = %.2f; τ1 = %.2f; τ2 = %.2f)\" % (l, tau1, tau2)\n\n########## Função MiDA\ndef raw_softmax(x):\n    return np.log(1 + np.exp(x))\n\ndef mida(l=1, tau=1):\n    z = np.arange(-5, 5, .01)\n    t = z * bhsa(l,tau,raw_softmax(z))[1]\n    return z, t, \"Função MiDA (λ = %.2f; τ = %.2f)\" % (l, tau)\n\ndef mida_d(l=1, tau=1):\n    z = np.arange(-5, 5, .01)\n    delta = (l*np.exp(z)*z)/(2*(1+np.exp(z)))\n    t = bhsa(l, tau, raw_softmax(z))[1] + delta * (((1 + 2*l*raw_softmax(z))/h1_bhsa(l, tau, raw_softmax(z))) + ((1-2*l*raw_softmax(z))/(h2_bhsa(l, tau, raw_softmax(z)))))\n    return z, t, \"Derivada da função MiDA (λ = %.2f; τ = %.2f)\" % (l, tau)\n\n#############################################################\ndef conf(ax, xlim=2, ylim=None, offsetx=0, offsety=0):\n    if ylim is None: ylim = xlim\n    ax.set_ylim([-ylim + offsety, ylim + offsety])\n    ax.set_xlim([-xlim + offsetx, xlim + offsetx])\n    ax.set_xlabel('x')\n    ax.set_ylabel('y')\n    ax.grid(True)\n    ax.legend()\n\n#############################################################\ndef step_and_derivative():\n    fig, (ax) = plt.subplots(1, 1, figsize=(6,6))\n    data, data_d = [step(), step_d()]\n    ax.plot(data[0], data[1], label=data[2])\n    ax.plot(data_d[0], data_d[1], ls='dashed', lw=1, label=data_d[2])\n    conf(ax,xlim=1,offsety=.5)\n    # fig.suptitle('Funções de ativação sigmoidais tradicionais')\n    plt.show()\n\ndef logistic_and_derivative():\n    fig, (ax) = plt.subplots(1, 1, figsize=(6,6))\n    data, data_d = [logistic(), logistic_d()]\n    ax.plot(data[0], data[1], label=data[2])\n    ax.plot(data_d[0], data_d[1], ls='dashed', lw=1, label=data_d[2])\n    conf(ax, xlim=4,ylim=1,offsety=.5)\n    plt.show()\n\ndef tanh_and_derivative():\n    fig, (ax) = plt.subplots(1, 1, figsize=(6,6))\n    data, data_d = [tanh(), tanh_d()]\n    ax.plot(data[0], data[1], label=data[2])\n    ax.plot(data_d[0], data_d[1], ls='dashed', lw=1, label=data_d[2])\n    conf(ax,ylim=1.5,offsety=.3)\n    plt.show()\n\ndef mish_and_derivative():\n    fig, (ax) = plt.subplots(1, 1, figsize=(6,6))\n    data, data_d = [mish(), mish_d()]\n    ax.plot(data[0], data[1], label=data[2])\n    ax.plot(data_d[0], data_d[1], ls='dashed', lw=1, label=data_d[2])\n    conf(ax,xlim=4,offsety=1.5)\n    plt.show()\n\ndef relu_and_derivative():\n    fig, (ax) = plt.subplots(1, 1, figsize=(6,6))\n    data, data_d = [relu(), relu_d()]\n    ax.plot(data[0], data[1], label=data[2])\n    ax.plot(data_d[0], data_d[1], ls='dashed', lw=1, label=data_d[2])\n    conf(ax, offsety=1,xlim=1.5)\n    plt.show()\n\ndef lrelu_and_derivative():\n    fig, (ax) = plt.subplots(1, 1, figsize=(6,6))\n    data, data_d = [lrelu(), lrelu_d()]\n    ax.plot(data[0], data[1], label=data[2])\n    ax.plot(data_d[0], data_d[1], ls='dashed', lw=1, label=data_d[2])\n    conf(ax, offsety=1,xlim=1.5)\n    plt.show()\n\ndef apl_and_derivative():\n    fig, (ax) = plt.subplots(1, 1, figsize=(6,6))\n    data, data_d = [apl(), apl_d_a02_b0()]\n    ax.plot(data[0], data[1], label=data[2])\n    ax.plot(data_d[0], data_d[1], ls='dashed', lw=1, label=data_d[2])\n    conf(ax,offsety=1)\n    plt.show()\n\ndef shrelu_and_derivative():\n    fig, (ax) = plt.subplots(1, 1, figsize=(6,6))\n    for tau in [0.05, 0.25, 1]:\n        data, data_d = [shrelu(tau), shrelu_d(tau)]\n        ax.plot(data[0], data[1], label=data[2])\n        ax.plot(data_d[0], data_d[1], ls='dashed', lw=1, label=data_d[2])\n    conf(ax, offsety=1,xlim=1.5)\n    plt.show()\n\ndef bhsa_and_derivative():\n    fig, (ax) = plt.subplots(1, 1, figsize=(6,6))\n    for l, tau in [(1, 1), (.5, 1), (1, .5)]:\n        data, data_d = [bhsa(l, tau), bhsa_d(l, tau)]\n        ax.plot(data[0], data[1], label=data[2])\n        ax.plot(data_d[0], data_d[1], ls='dashed', lw=1, label=data_d[2])\n    conf(ax)\n    plt.show()\n\ndef bhaa_and_derivative():\n    fig, (ax) = plt.subplots(1, 1, figsize=(6,6))\n    for l, tau1, tau2 in [(1, .5, .5), (1, .5, .1), (1, .1, .5)]:\n        data, data_d = [bhaa(l, tau1, tau2), bhaa_d(l, tau1, tau2)]\n        ax.plot(data[0], data[1], label=data[2])\n        ax.plot(data_d[0], data_d[1], ls='dashed', lw=1, label=data_d[2])\n    conf(ax)\n    plt.show()\n\ndef mida_and_derivative():\n    fig, (ax) = plt.subplots(1, 1, figsize=(6,6))\n    for l, tau in [(1, 1), (.5, 1), (1, .5)]:\n        data, data_d = [mida(l, tau), mida_d(l, tau)]\n        ax.plot(data[0], data[1], label=data[2])\n        ax.plot(data_d[0], data_d[1], ls='dashed', lw=1.25, label=data_d[2])\n    conf(ax,xlim=3,offsety=1.5)\n    plt.show()\n\ndef bhata_only():\n    fig, (ax) = plt.subplots(1, 1, figsize=(6,6))\n    for l, tau1, tau2 in [(1, .5, .1), (1, .1, .5)]:\n        data = bhata(l, tau1, tau2)\n        ax.plot(data[0], data[1], label=data[2])\n    conf(ax)\n    plt.show()\n\ndef bhana_only():\n    fig, (ax) = plt.subplots(1, 1, figsize=(6,6))\n    for l, tau1, tau2 in [(1, .75, .1), (1, .1, .75)]:\n        data = bhana(l, tau1, tau2)\n        ax.plot(data[0], data[1], label=data[2])\n    conf(ax)\n    plt.show()\n\n# step_and_derivative()\n# logistic_and_derivative()\n# tanh_and_derivative()\n# mish_and_derivative()\n# relu_and_derivative()\n# lrelu_and_derivative()\n# apl_and_derivative()\n# shrelu_and_derivative()\n# bhsa_and_derivative()\n# bhaa_and_derivative()\n# mida_and_derivative()\n# bhata_only()\nbhana_only()\n", "meta": {"hexsha": "46169a2a5c94b7e23c04dc9d3e5eeddc3eb92918", "size": 10806, "ext": "py", "lang": "Python", "max_stars_repo_path": "activation_visualization/f/activation_functions.py", "max_stars_repo_name": "chriiscardozo/msc_aafgan", "max_stars_repo_head_hexsha": "d5312a80c5ee56e89edb6a927661377731debbd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "activation_visualization/f/activation_functions.py", "max_issues_repo_name": "chriiscardozo/msc_aafgan", "max_issues_repo_head_hexsha": "d5312a80c5ee56e89edb6a927661377731debbd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "activation_visualization/f/activation_functions.py", "max_forks_repo_name": "chriiscardozo/msc_aafgan", "max_forks_repo_head_hexsha": "d5312a80c5ee56e89edb6a927661377731debbd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1962025316, "max_line_length": 171, "alphanum_fraction": 0.5388672959, "include": true, "reason": "import numpy", "num_tokens": 4219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.9086178882719769, "lm_q1q2_score": 0.8731379089622539}}
{"text": "import numpy as np\n\n\ndef simpson(f, a, b, n):\n    \"\"\"Approximates the definite integral of f from a to b by\n    the composite Simpson's rule, using n subintervals.\n    From http://en.wikipedia.org/wiki/Simpson's_rule\n    \n    Args:\n    f   : function to integrate\n    a,b : boundaries\n    n   : number of subintervals\n    \n    Return: integral\n    \"\"\"\n    h = (b - a) / n\n    i = np.arange(0,n)\n    s = f(a) + f(b) \n    s += 4 * np.sum( f( a + i[1::2] * h ) )\n    s += 2 * np.sum( f( a + i[2:-1:2] * h ) )\n    sum = s * h / 3\n    return sum\n\ndef trapezoid(f, a, b, n):\n    \"\"\"Approximates the definite integral of f from a to b by\n    the composite trapezoidal rule, using n subintervals.\n    From http://en.wikipedia.org/wiki/Trapezoidal_rule\n        \n    Args:\n    f   : function to integrate\n    a,b : boundaries\n    n   : number of subintervals\n    \n    Return: integral\n    \"\"\"\n    h = (b - a) / n\n    s = f(a) + f(b)\n    i = np.arange(0,n)\n    s += 2 * np.sum( f(a + i[1:] * h) )\n    return s * h / 2\n\n\ndef adaptive_trapezoid(f, a, b, acc, output=False):\n    \"\"\"\n    Uses the adaptive trapezoidal method to compute the definite integral\n    of f from a to b to desired accuracy acc. \n        \n    Args:\n    f      : function to integrate\n    a,b    : boundaries\n    acc    : desired accurarcy\n    output : prints individual steps, default is False\n    \n    Return: integral\n    \"\"\"\n    old_s = np.inf\n    h = b - a\n    n = 1\n    s = (f(a) + f(b)) * 0.5\n    if output == True : \n        print (\"N = \" + str(n+1) + \",  Integral = \" + str( h*s ))\n    while abs(h * (old_s - s*0.5)) > acc :\n        old_s = s\n        for i in np.arange(n) :\n            s += f(a + (i + 0.5) * h)\n        n *= 2.\n        h *= 0.5\n        if output == True :\n            print (\"N = \" + str(n) + \",  Integral = \" + str( h*s ))\n    return h * s\n", "meta": {"hexsha": "f47f9138a2d607000d2dd16c10aba9095a3207cc", "size": 1827, "ext": "py", "lang": "Python", "max_stars_repo_path": "UtilityFunctions/integrals.py", "max_stars_repo_name": "shopnochari/CP1_Calculus", "max_stars_repo_head_hexsha": "d5d3b0ba40bc1930d3a27c8977d4903b6d9a4855", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "UtilityFunctions/integrals.py", "max_issues_repo_name": "shopnochari/CP1_Calculus", "max_issues_repo_head_hexsha": "d5d3b0ba40bc1930d3a27c8977d4903b6d9a4855", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UtilityFunctions/integrals.py", "max_forks_repo_name": "shopnochari/CP1_Calculus", "max_forks_repo_head_hexsha": "d5d3b0ba40bc1930d3a27c8977d4903b6d9a4855", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7323943662, "max_line_length": 73, "alphanum_fraction": 0.5139573071, "include": true, "reason": "import numpy", "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202038, "lm_q2_score": 0.9207896715436482, "lm_q1q2_score": 0.8730508986382415}}
{"text": "import numpy as np\n\n\ndef coding_problem_32(exchange_matrix):\n    \"\"\"\n    Suppose you are given a table of currency exchange rates, represented as a 2D array. Determine whether there is a\n    possible arbitrage: that is, whether there is some sequence of trades you can make, starting with some amount A of\n    any currency, so that you can end up with some amount greater than A of that currency.\n    There are no transaction costs and you can trade fractional quantities.\n\n    >>> em = [[1, 2, 3], [1./2, 1, 3./2], [1./3, 2./3, 1]]\n    >>> coding_problem_32(em)\n    True\n\n    >>> em[0][2] = 2.98\n    >>> coding_problem_32(em)\n    False\n\n    Note: idea is that given a single row in the currency exchange matrix, it is possible to generate the entire 2D\n    array. Any difference between the given currency exchange matrix and the computed one implies the possibility of\n    arbitration.\n\n    For example, for five currencies and given the exchange rates from the first to the other 4 [b, c, d, e]:\n\n      |  A   B   C   D   E\n    --+------------------\n    A |  1   b   c   d   e\n    B | 1/b  1  c/b d/b e/b\n    C | 1/c b/c  1  d/b e/c\n    D | 1/d b/d c/d  1  e/d\n    E | 1/e b/e c/e d/e  1\n\n    Since floating point quantities are involved, we need to test for approximate equality.\n    \"\"\"\n    em = np.array(exchange_matrix)  # ideally, we should test if the exchange_matrix is well-formed\n    cem = np.vstack(tuple(em[0, :] / em[0, n] for n in range(len(em))))  # computed exchange_matrix\n    return np.allclose(em, cem)\n\n\nif __name__ == '__main__':\n\n    import doctest\n    doctest.testmod(verbose=True)\n", "meta": {"hexsha": "426889c7b40a590999f35d02db3714dac17fa586", "size": 1607, "ext": "py", "lang": "Python", "max_stars_repo_path": "problems/32/solution_32.py", "max_stars_repo_name": "r1cc4rdo/daily_coding_problem", "max_stars_repo_head_hexsha": "6ac85309fad2f64231ac7ab94aa4158e18bdec40", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 158, "max_stars_repo_stars_event_min_datetime": "2018-01-25T06:33:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T23:18:05.000Z", "max_issues_repo_path": "problems/32/solution_32.py", "max_issues_repo_name": "r1cc4rdo/daily_coding_problem", "max_issues_repo_head_hexsha": "6ac85309fad2f64231ac7ab94aa4158e18bdec40", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2018-07-04T00:31:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-16T21:02:30.000Z", "max_forks_repo_path": "problems/32/solution_32.py", "max_forks_repo_name": "r1cc4rdo/daily_coding_problem", "max_forks_repo_head_hexsha": "6ac85309fad2f64231ac7ab94aa4158e18bdec40", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 50, "max_forks_repo_forks_event_min_datetime": "2018-06-22T16:48:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T16:45:48.000Z", "avg_line_length": 36.5227272727, "max_line_length": 118, "alphanum_fraction": 0.6484131923, "include": true, "reason": "import numpy", "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.926303724699188, "lm_q1q2_score": 0.8730474849053131}}
{"text": "'''\nContent under Creative Commons Attribution license CC-BY 4.0, \ncode under MIT license (c)2018 Sergio Rojas (srojas@usb.ve) \n\nhttp://en.wikipedia.org/wiki/MIT_License\nhttp://creativecommons.org/licenses/by/4.0/\n\nCreated on march, 2018\nLast Modified on: may 15, 2018\n'''\n\nTheValues = [336.1, 346.67, 354.54, 359.9, 338.61, 348.16, 355.2, 360.,\n339.32, 349.31, 355.36, 363.13, 350.56, 355.76, 342.62, 351.88,\n356.85, 342.88, 351.99, 358.16, 343.44, 352.12, 358.3, 344.32,\n352.47, 359.18, 345.03, 353.21, 359.56, 346.5]\n\nTheValues.sort()\nNumberOfValues = len(TheValues)\n\nif NumberOfValues == 0:\n   print(' List of values in empty ')\nelif NumberOfValues == 1:\n   TheMedian = TheValues[ 0 ]     # The only element in the list\nelif (NumberOfValues % 2) == 1:   # Check if the number of values is odd\n   temp = NumberOfValues//2\n   TheMedian = TheValues[ temp ]\nelse:\n   temp = NumberOfValues//2\n   TheMedian = (TheValues[ temp ] + TheValues[ temp - 1 ])/2\n\nprint('The median = {0}'.format(TheMedian))\nIn [8]: import numpy as np\n\nIn [9]: np.median(TheValues)\nOut[9]: 352.05500000000001\n\n\n\n", "meta": {"hexsha": "43c6b74cea51b049c9a43a4ec712a24be19068ba", "size": 1085, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter_03/chap03_prog_05_median_ex2.py", "max_stars_repo_name": "rojassergio/Prealgebra-via-Python-Programming", "max_stars_repo_head_hexsha": "8d1cdf103af2a39f6ae7bba76e9a6a0182eb39d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-19T11:54:15.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-19T11:54:15.000Z", "max_issues_repo_path": "Chapter_03/chap03_prog_05_median_ex2.py", "max_issues_repo_name": "rojassergio/Prealgebra-via-Python-Programming", "max_issues_repo_head_hexsha": "8d1cdf103af2a39f6ae7bba76e9a6a0182eb39d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter_03/chap03_prog_05_median_ex2.py", "max_forks_repo_name": "rojassergio/Prealgebra-via-Python-Programming", "max_forks_repo_head_hexsha": "8d1cdf103af2a39f6ae7bba76e9a6a0182eb39d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-03-02T22:31:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T05:06:39.000Z", "avg_line_length": 27.8205128205, "max_line_length": 72, "alphanum_fraction": 0.6792626728, "include": true, "reason": "import numpy", "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.9230391664210672, "lm_q1q2_score": 0.8730116174341236}}
{"text": "#coding=utf-8\n# 计算图像文件 '正方形面积占比计算.JPG'中粉红色区域占总正方形面积的比例\n\n# 思路：蒙特卡洛算方法：\n# 假设正方形边长为1\n# 以正方形的左下角定点为直角坐标系圆点，记圆点为A（0，0）\n# 正方形右下角的点为B（1，0）\n# 正方形左上角的点为C（0，1）\n# 正方形上面的那条边的中点为D（0.5,1）\n# 记AD与BC两线的交点，即为粉红色三角形的定点为P\n# 直线AD的方程式为 y = 2*x\n# 直线BC的方程为   y = 1-x\n# 粉红的区域的可行域为满足 y < 2*x 且 y < 1-x 且 y >0，其中x的范围为 0～1\n# 正方形区域的可行域为 0<x<1;0<y<1\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef meng_num(n):\n    col_X=[]; col_y=[]\n    z=np.zeros(n)\n    sum=0                       # 程序刚开始的时候，没有点落入粉红色区域的可行域\n    for i in range(n):\n        x=np.random.rand()      # 随机生成一个值为0～1的数即记为x坐标\n        y=np.random.rand()      # 随机生成一个值为0～1的数即记为y坐标\n        col_X.append(x)         # 收集生成的x，留着作图用\n        col_y.append(y)         # 收集生成的y，留着作图用\n        if y<2*x and y < 1-x:   # 若坐标（x，y）落入粉红区域,则进行计数\n            sum +=1\n            z[i]=1\n    area_rate=sum/len(range(n+1))   # 则粉红色区域所占正方形的概率为落入粉红色区域的点数除以总生成的随机数n\n    print('当随机生成 %i 个点的时候，面积占比为： %f ' %(n,area_rate))\n\n    #以下是可视化输出，只是把生成的点投影到区域中\n    x1 = np.linspace(0, 1 / 3, 1000)\n    x2 = np.linspace(1 / 3, 1, 1000)\n    x3 = np.linspace(0, 1, 1000)\n    y1 = 2 * x1\n    y2 = 1 - x2\n    y3 = 0 * x1\n    plt.plot(x1, y1, x2, y2, x3, y3)\n    plt.xlim(0, 1)\n    plt.ylim(0, 1)\n    plt.scatter(col_X,col_y,c=z,cmap='rainbow')\n    plt.title('when create %i random point' %n)\n    plt.show()\n\n\nfor n in list([10,100,1000,10000,100000]):\n    meng_num(n)\n", "meta": {"hexsha": "d2f55a5c79e4bb1843d7fa387f54cba5b850c585", "size": 1367, "ext": "py", "lang": "Python", "max_stars_repo_path": "area_calculate.py", "max_stars_repo_name": "Aplicity/MonteCarlomethod_cal_area", "max_stars_repo_head_hexsha": "b0a1ed7fd46f54cb4e21ee539693f663bd8b0e52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-02-07T04:26:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T01:48:42.000Z", "max_issues_repo_path": "area_calculate.py", "max_issues_repo_name": "Aplicity/MonteCarlomethod_cal_area", "max_issues_repo_head_hexsha": "b0a1ed7fd46f54cb4e21ee539693f663bd8b0e52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "area_calculate.py", "max_forks_repo_name": "Aplicity/MonteCarlomethod_cal_area", "max_forks_repo_head_hexsha": "b0a1ed7fd46f54cb4e21ee539693f663bd8b0e52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8039215686, "max_line_length": 73, "alphanum_fraction": 0.587417703, "include": true, "reason": "import numpy", "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104962847373, "lm_q2_score": 0.9032942008463507, "lm_q1q2_score": 0.872952996931047}}
{"text": "import sys\n\nimport numpy as np\n\ndef bayes_theorem(P_B_A, P_A, P_B_nA):\n    \"\"\"An implementation of Bayes theorem.\n    Evaluate the probability of event $A$ given that $B$ is true.\n\n    Parameters\n    ----------\n    P_B_A : array_like\n        the likelihood of event $B$ occurring given that $A$ is true.\n    P_A : array_like\n        the likelihood of observing $A$.\n    P_B_nA : array_like\n        the likelihood of observing $B$ given $A$ is false.\n\n    Returns\n    -------\n    P_A_B : float\n        probability of event $A$ given that $B$ is true.\n    \n    Notes\n    -----\n    From wikipedia:\n    [Bayes Theorem](https://en.wikipedia.org/wiki/Bayes%27_theorem)\n    is described as in (1.):\n\n    1. $$P(A|B) = \\frac{P(B|A)P(A)}{P(B)} $$\n\n    Where `A` and `B` are [events](https://en.wikipedia.org/wiki/Event_(probability_theory)) \n    and $P(B) \\\\neq 0$.\n\n    - $P(A|B)$ is a [conditional probability](https://en.wikipedia.org/wiki/Conditional_probability):\n      the likelihood of event $A$ occurring _given that_ $B$ is true.\n    - $P(B|A)$ is also a conditional probability: the likelihood of event $B$ occurring\n      given that $A$ is true.\n    - $P(A)$ and $P(B)$ are the probabilities of observing $A$ and $B$ respectively;\n      they are known as the [marginal probability](https://en.wikipedia.org/wiki/Marginal_distribution).\n    - $A$ and $B$ must be different events.\n\n    However it strikes me as obfuscating to only show the denominator as $P(B)$ as it must \n    be developed in order to actually evaluate this equation, as follows in (2.):\n\n    2. $$ P(B) = P(B|A)P(A) + P(B|¬A)P(¬A) $$\n\n    Where:\n    - $P(B|¬A)$ is a conditional probability; \n        the likelihood of event $B$ occurring given that $A$ is false.\n    - $P(¬A)$ is the probablity of not observing $A$.\n\n    So we need a minimum of 3 numeric inputs to run this calculation:\n\n    1. $P(B|A)$ the likelihood\n    2. $P(A)$ the normalizing constant\n    3. $P(B|¬A)$\n\n    Example\n    -------\n    Retrieving a Special Publication of the GeolSoc (SPGS) from my bookshelf:\n    Getting a SPGS book is the test (A);\n    I have 11 SPGS books on my bookshelf and a total of 44 books on that shelf\n    so:\n    \n    P(A) = 11 / 44 = 0.25\n    P(B|A) = 1 - P(A) = 0.75\n    P(B|¬A) = 1\n\n    >>> python bayes_theorem.py 0.75 0.25 1\n    P(A|B) = 0.200\n\n    \"\"\"\n    P_B_A, P_A, P_B_nA = np.array(P_B_A), np.array(P_A), np.array(P_B_nA)\n    return (P_B_A * P_A) / ((P_B_A * P_A) + P_B_nA * (1 - P_A))\n\nif __name__ == \"__main__\":\n    try:\n        P_B_A_str, P_A_str, P_B_nA_str = sys.argv[1:]\n        P_B_A, P_A, P_B_nA = float(P_B_A_str), float(P_A_str), float(P_B_nA_str)\n        print(f'P(A|B) = {bayes_theorem(P_B_A, P_A, P_B_nA):.3f}')\n    except ValueError:\n        num_vals = int((len(sys.argv) - 1) / 3)\n        vals = [float(val.strip('[],')) for val in sys.argv[1:]]\n        P_B_A = vals[:num_vals]\n        P_A = vals[num_vals:-num_vals]\n        P_B_nA = vals[-num_vals:]\n        print(f'P(A|B) = {bayes_theorem(P_B_A, P_A, P_B_nA)}')", "meta": {"hexsha": "2641cc4adf616f7906265a68be14e7645af977d9", "size": 3007, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/demos/bayes_theorem.py", "max_stars_repo_name": "Zabamund/misc", "max_stars_repo_head_hexsha": "e1a2bec1b8e36b039807ec02c53ee3970bb4e255", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-02-18T18:38:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T06:34:31.000Z", "max_issues_repo_path": "scripts/demos/bayes_theorem.py", "max_issues_repo_name": "Zabamund/misc", "max_issues_repo_head_hexsha": "e1a2bec1b8e36b039807ec02c53ee3970bb4e255", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-04-01T20:22:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-13T02:18:12.000Z", "max_forks_repo_path": "scripts/demos/bayes_theorem.py", "max_forks_repo_name": "Zabamund/misc", "max_forks_repo_head_hexsha": "e1a2bec1b8e36b039807ec02c53ee3970bb4e255", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-03T08:57:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-03T08:57:23.000Z", "avg_line_length": 34.5632183908, "max_line_length": 104, "alphanum_fraction": 0.6099102095, "include": true, "reason": "import numpy", "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769120761569, "lm_q2_score": 0.8947894738180211, "lm_q1q2_score": 0.8729359518256343}}
{"text": "# %% codecell\n# create some x and y date\nfrom matplotlib import pyplot as plt\nx_list = [-4.0, -2.0, 3.0, 4.0, 5.0, 6.0]\ny_list = list()\nm = 2\nb = 4\n\n\nfor x in x_list:\n    y = (m*x) + b\n    y_list.append(y)\n\nplt.plot(x_list, y_list)\n\n# %% codecell\ndef lin_model_single_ele(m, x, b):\n    \"\"\" Returns a single y for a given x using a line \"\"\"\n    return (m*x) + b\n\nx_list = [1, 2, 3, 4, 5, 6]\ny_observed = [2.11, 3.87, 6.01, 7.93, 9.99, 12.12]\n\ny_predicted = []\nm = 2\nb = 4\n\nfor x in x_list:\n    y = lin_model_single_ele(m, x, b)\n    y_predicted.append(y)\n\nprint(y_predicted[0])\n# %% codecell\ndef calculate_residual(y_pred, y_obs):\n    \"\"\" Returns the residual of either a point or array \"\"\"\n    return y_pred-y_obs\n\nresiduals = []\nfor i in range(0, len(y_predicted)):\n    residual = calculate_residual(y_predicted[i], y_observed[i])\n    residuals.append(residual)\n\nprint(residuals)\n# %% codecell\nfrom statistics import mean\n\ndef calculate_ssr(y_pred, y_obs, deci=4):\n    \"\"\"  Calculates the Sum of Squared Residuals using the observed and predicted y\"\"\"\n    res = [calculate_residual(a_i, b_i) for a_i, b_i in zip(y_pred, y_obs)]\n    return round(sum([d * d for d in res]), deci)\n\n\ndef calculate_tss(y_obs, deci=4):\n\ty_mean = mean(y_obs)\n\tdelta = [y - y_mean for y in y_obs]\n\treturn round(sum([d * d for d in delta]), deci)\n\n\ndef calculate_rsquared(ssr, tss, deci=4):\n\treturn round(1-(ssr/tss), 4)\n# %% codecell\ntss = calculate_tss(y_observed)\nssr = calculate_ssr(y_observed, y_predicted)\nr2 = calculate_rsquared(ssr, tss)\n\nprint('SSE: %s' % ssr)\nprint('R^2: %s' % r2)\n# %% codecell\ndef fit_line(x_input, y_observed, m_max=5, c_max=5, print_output=True):\n\n\tbest_model = {\n\t\t'm': None,\n\t\t'c': None,\n\t\t'SSR': None,\n\t\t'R^2': None\n\t}\n\tassert len(x_input) == len(y_observed), 'Input vectors have differing lengths'\n\n\ttss = calculate_tss(y_observed)\n\n\tfor m in range(1, m_max):\n\t\tfor c in range(0, c_max):\n\t\t\ty_model = list()\n\t\t\tfor x_i in x_input:\n\t\t\t\ty_model.append(lin_model_single_ele(m, x_i, c))\n\n\t\t\tssr = calculate_ssr(y_observed, y_model)\n\t\t\tr2 = calculate_rsquared(ssr, tss)\n\t\t\tif print_output:\n\t\t\t\tprint('#####')\n\t\t\t\tprint('using: m=%s and c=%s' % (m, c))\n\t\t\t\tprint('actual: %s' % y_observed)\n\t\t\t\tprint('model: %s' % y_model)\n\t\t\t\tprint('SSR: %s' % ssr)\n\t\t\t\tprint('R^2: %s' % r2)\n\t\t\t\tprint('#####')\n\n\t\t\tif best_model['SSR'] is None or best_model['SSR'] > ssr:\n\t\t\t\tbest_model['m'] = m\n\t\t\t\tbest_model['c'] = c\n\t\t\t\tbest_model['SSR'] = ssr\n\t\t\t\tbest_model['R^2'] = r2\n\n\treturn best_model\n\n# %% codecell\nmy_model = fit_line(x_list, y_observed, print_output=False)\nprint('best model: %s' % my_model)\n# %% codecell\nfrom sklearn import linear_model\nimport numpy as np\n\nlm = linear_model.LinearRegression()\nX = np.array(x_list).reshape(-1, 1)\nY = np.array(y_observed).reshape(-1, 1)\nmodel = lm.fit(X, Y)\nprint(model.coef_)\nprint(model.intercept_)\nprint(model.score(X, Y))\n\n\n\n\n# %% codecell\n\n# %% codecell\ntss = calculate_tss(y_observed)\nssr = calculate_ssr(y_observed, y_predicted)\nr2 = calculate_rsquared(ssr, tss)\n\nprint('SSE: %s' % ssr)\nprint('R^2: %s' % r2)\n# %% codecell\ndef fit_line(x_input, y_observed, m_max=5, c_max=5, print_output=True):\n\n\tbest_model = {\n\t\t'm': None,\n\t\t'c': None,\n\t\t'SSE': None,\n\t\t'R^2': None\n\t}\n\tassert len(x_input) == len(y_observed), 'Input vectors have differing lengths'\n\n\ttss = calculate_tss(y_observed)\n\n\tfor m in range(1, m_max):\n\t\tfor c in range(0, c_max):\n\t\t\ty_model = list()\n\t\t\tfor x_i in x_input:\n\t\t\t\ty_i = (m*x_i) + c\n\t\t\t\ty_model.append(y_i)\n\n\t\t\tssr = calculate_ssr(y_observed, y_model)\n\t\t\tr2 = calculate_rsquared(ssr, tss)\n\t\t\tif print_output:\n\t\t\t\tprint('#####')\n\t\t\t\tprint('using: m=%s and c=%s' % (m, c))\n\t\t\t\tprint('actual: %s' % y_observed)\n\t\t\t\tprint('model: %s' % y_model)\n\t\t\t\tprint('SSE: %s' % ssr)\n\t\t\t\tprint('R^2: %s' % r2)\n\t\t\t\tprint('#####')\n\n\t\t\tif best_model['SSE'] is None or best_model['SSE'] > ssr:\n\t\t\t\tbest_model['m'] = m\n\t\t\t\tbest_model['c'] = c\n\t\t\t\tbest_model['SSE'] = ssr\n\t\t\t\tbest_model['R^2'] = r2\n\n\treturn best_model\n\n# %% codecell\nmy_model = fit_line(x_list, y_observed, print_output=False)\nprint('best model: %s' % my_model)\n# %% codecell\nfrom sklearn import linear_model\nimport numpy as np\n\nlm = linear_model.LinearRegression()\nX = np.array(x).reshape(-1, 1)\nY = np.array(y).reshape(-1, 1)\nmodel = lm.fit(X, Y)\nprint(lm.score(X, Y))\n", "meta": {"hexsha": "8a45f9bce9cee36dd27c6504e6ed7aebd1e80e98", "size": 4281, "ext": "py", "lang": "Python", "max_stars_repo_path": "hydrogen/hydrogen_ch6-regression.py", "max_stars_repo_name": "ewhitling/datascience-cc", "max_stars_repo_head_hexsha": "21fc9186741860a62c4d1ccf403fca7c0e12009d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hydrogen/hydrogen_ch6-regression.py", "max_issues_repo_name": "ewhitling/datascience-cc", "max_issues_repo_head_hexsha": "21fc9186741860a62c4d1ccf403fca7c0e12009d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hydrogen/hydrogen_ch6-regression.py", "max_forks_repo_name": "ewhitling/datascience-cc", "max_forks_repo_head_hexsha": "21fc9186741860a62c4d1ccf403fca7c0e12009d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2663043478, "max_line_length": 86, "alphanum_fraction": 0.643774819, "include": true, "reason": "import numpy", "num_tokens": 1461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410982634296, "lm_q2_score": 0.918480237330998, "lm_q1q2_score": 0.8729337048919352}}
{"text": "import sympy\n\n##################################################################\n# Function : factorize(a, n, factor_matrix)\n# This function recursively divides a by n to get the largest\n# multiple of n that is a divisor of a. It also checks if n is\n# a prime factor because we only wanna account for prime factors\n#\n# In other words, repeatedly integer divides a by n, increasing\n# the count of n as displayed in factor_matrix[n-1][1] by every\n# time. The greatest divisor of a that is a multiple of only n\n# is given by n ^ (factor_matrix[n-1][1])\n#\n# params : a - The number to be factored (int)\n#        : n - The factor (int)\n#        : factor_matrix - 2D matrix that holds the prime factors\n#                          of a and the gcd of a that is a power\n#                          of n.\n#\n# returns: nothing\n#################################################################\ndef factorizer(a, n, factor_matrix):\n    if a % n == 0 and sympy.isprime(n):  # replace with own isprime function\n        factor_matrix[n-1][1] += 1\n        factorizer(a//n, n, factor_matrix)\n    return\n\n##################################################################\n# Function : gcd(x,y)\n# Calculates the Greatest Common Divisor of x and y\n#\n# How the algorithm works:\n# Find all the prime factors of x and y and their powers.\n# GCD is set to 1 initially\n# If any of x an y have common prime factors, multiply the GCD\n# by the lower of the powers of the common prime factors.\n#\n# params : x - (int)\n#        : y - (int)\n#\n# returns: (int) Greatest common divisor of x and y\n#################################################################\ndef gcd(x, y):\n    greatest_common_divisor = 1\n\n########## Edge Case testing# #############\n    if x == 0:\n        raise ValueError(\"x cannot be 0\")\n    if y == 0:\n        raise ValueError(\"y cannot be 0\")\n\n    if x < 0:\n        x = abs(x)\n    if y < 0:\n        y = abs(y)\n\n    if not isinstance(x, int):\n        raise TypeError(\"x has to be an integer\")\n    if not isinstance(y, int):\n        raise TypeError(\"y has to be an integer\")\n\n\n    # 1 is always a divisor of both x and y\n    factor_matrix_x = [[1, 1]]     # matrix that contains the prime factors of x\n    factor_matrix_y = [[1, 1]]     # matrix that contains the prime factors of y\n\n    for i in range(2, x + 1):\n        factor_matrix_x.append([i, 0])\n        factorizer(x, i, factor_matrix_x)\n\n    i = 2\n    for i in range(2, y + 1):\n        factor_matrix_y.append([i, 0])\n        factorizer(y, i, factor_matrix_y)\n\n    for i in range(0, len(factor_matrix_x) if len(factor_matrix_x) <= len(factor_matrix_y) else len(factor_matrix_y)):\n        if factor_matrix_x[i][1] == 0 or factor_matrix_y[i][1] == 0:\n            continue\n        elif factor_matrix_x[i][1] <= factor_matrix_y[i][1]:\n            greatest_common_divisor *= pow(factor_matrix_x[i][0], factor_matrix_x[i][1])\n        else:\n            greatest_common_divisor *= pow(factor_matrix_y[i][0], factor_matrix_y[i][1])\n\n    return greatest_common_divisor\n\n\n\n", "meta": {"hexsha": "a82d83befe0e0e069e6ca47a828a7bfaf23baef0", "size": 3007, "ext": "py", "lang": "Python", "max_stars_repo_path": "Number_Theory/gcd.py", "max_stars_repo_name": "SherwynBraganza31/csc514-crypto", "max_stars_repo_head_hexsha": "b4b9641c37041e465e652f5d84398101746d518b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Number_Theory/gcd.py", "max_issues_repo_name": "SherwynBraganza31/csc514-crypto", "max_issues_repo_head_hexsha": "b4b9641c37041e465e652f5d84398101746d518b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Number_Theory/gcd.py", "max_forks_repo_name": "SherwynBraganza31/csc514-crypto", "max_forks_repo_head_hexsha": "b4b9641c37041e465e652f5d84398101746d518b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1704545455, "max_line_length": 118, "alphanum_fraction": 0.5703358829, "include": true, "reason": "import sympy", "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147201714923, "lm_q2_score": 0.8976952900545975, "lm_q1q2_score": 0.872932114277708}}
{"text": "import numpy as np\nfrom Exercise5.util import matrix_mult, transpose, matrix_vector_mult\nfrom Exercise5.lu_decomposition import lu\n\n\ndef least_squares_fit(x, y, degree=10):\n    \"\"\"\n        Computes the coefficients of the <b>degree</b> degree polynomial of the least squares fit. <br>Constant term\n        first.</br>\n\n        Parameters\n        ----------\n        x : list\n            The values of the independent variable.\n        y : list\n            The values of f(x) for every x, where x is the independent variable\n        degree : int\n            The degree of the polynomial model fitting the data.\n\n        Returns\n        -------\n        c : list\n            coefficients of interpolating polynomial\n    \"\"\"\n    # construct A\n    a = []\n    for row in range(len(x)):\n        a.append([])\n        for column in range(degree):\n            a[row].append(x[row]**column)\n    # construct A^T * A\n    a_transpose = transpose(a)\n    a_transpose_a = matrix_mult(a_transpose, a)\n\n    # solve (A^T * A) * x = A^T * y\n    return lu(a_transpose_a, matrix_vector_mult(a_transpose, y))\n\n\ndef calculate_polynomial(c, x, degree=10):\n    \"\"\"\n        Computes the value of the <b>degree</b> degree least squares fit polynomial.\n\n        Parameters\n        ----------\n        c : list\n            The coefficients of the <b>degree</b> degree polynomial. <b>Constant term first.</br>\n        x : int\n            The point at which the polynomial will be calculated\n        degree : int\n            The degree of the polynomial model that was used when fitting the data.\n\n        Returns\n        -------\n        return_value : float\n            The value of the interpolating polynomial at point x.\n    \"\"\"\n    return_value = 0.0\n    for i in range(degree):\n        return_value += c[i] * (x ** i)\n    return return_value\n\n\ndef custom_sin(value, d=10):\n    \"\"\"\n        Approximates sin curve with least squares using <b>d</b> degree polynomial model.\n\n        Parameters\n        ----------\n        value : float\n            The point at which the sin will be approximated\n        d : int\n            The degree of the polynomial model fitting the data.\n\n        Returns\n        -------\n        float\n            The approximation value of the sin curve at point x.\n    \"\"\"\n    x = [0.0, 0.65, 1.3, 1.9500000000000002, 2.6, 3.25, 3.9000000000000004, 4.55, 5.2, 2*np.pi]\n    y = [0.0, 0.6051864057, 0.9635581854, 0.9289597150, 0.5155013718, -0.1081951345, -0.6877661591, -0.9868438585,\n         -0.8834546557, 0]\n    c = least_squares_fit(x, y, degree=d)\n\n    value = value % (2*np.pi)\n    return calculate_polynomial(c, value, degree=d)\n", "meta": {"hexsha": "b3a119dbc44efb234b9993745d843f32ee0b20bb", "size": 2627, "ext": "py", "lang": "Python", "max_stars_repo_path": "Second Project/Exercise5/leastSquares.py", "max_stars_repo_name": "TasosOperatingInBinary/Numerical-Analysis-Projects", "max_stars_repo_head_hexsha": "61a8014f2b853a646145cea5a4d3655e100be854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Second Project/Exercise5/leastSquares.py", "max_issues_repo_name": "TasosOperatingInBinary/Numerical-Analysis-Projects", "max_issues_repo_head_hexsha": "61a8014f2b853a646145cea5a4d3655e100be854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Second Project/Exercise5/leastSquares.py", "max_forks_repo_name": "TasosOperatingInBinary/Numerical-Analysis-Projects", "max_forks_repo_head_hexsha": "61a8014f2b853a646145cea5a4d3655e100be854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5465116279, "max_line_length": 116, "alphanum_fraction": 0.5888846593, "include": true, "reason": "import numpy", "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075733703927, "lm_q2_score": 0.9073122269997506, "lm_q1q2_score": 0.8729319650080168}}
{"text": "def extgcd(a, b):\n    \"\"\" 拡張ユークリッド互除法\n    ax + by = gcd(a,b) の最小整数解 (gcd(a,b), x, y) を返す\n    Args:\n        a (int):\n        b (int):\n    Returns:\n        Tuple[int, int, int]\n    \"\"\"\n    u = y = 1\n    v = x = 0\n    while a:\n        q = b // a\n        x, u = u, x-q*u\n        y, v = v, y-q*v\n        b, a = a, b-q*a\n    return b, x, y\n\n    # 再帰版\n    # if a == 0:\n    #     return b, 0, 1\n    # else:\n    #     g, y, x = extgcd(b % a, a)\n    #     return g, x - (b // a) * y, y\n\ndef chinese_reminder_theorem(q1, m1, q2, m2):\n    \"\"\"中国剰余定理 (CRT)\n\n    x ≡ m1 (mod q1) ∧ x ≡ m2 (mod q2)\n    <=> x ≡ m (mod q)\n    となる (m. q) を返す\n    解無しのとき (0, -1) を返す\n\n    verify:\n        https://atcoder.jp/contests/abc193/submissions/20558893\n\n    Args:\n        q1 (int): 除数\n        m1 (int): あまり\n        q2 (int): 除数\n        m2 (int): あまり\n\n    Returns:\n        Tuple[int, int]: 除数、あまり\n    \"\"\"\n    gcd_, p, q = extgcd(q1, q2)\n    if (m2 - m1) % gcd_ != 0:\n        return 0, -1\n    q = q1 * (q2 // gcd_)  # q = lcm(q1, q2)\n    tmp = (m2 - m1) // gcd_ * p % (q2 // gcd_)\n    m = (m1 + q1 * tmp) % q\n    return m, q\n\ndef modinv(a, mod=10**9+7):\n    return pow(a, mod-2, mod)\n\ndef combination(n, r, mod=10**9+7):\n    # nCr mod m\n    # rがn/2に近いと非常に重くなる\n    n1, r = n+1, min(r, n-r)\n    numer = denom = 1\n    for i in range(1, r+1):\n        numer = numer * (n1-i) % mod\n        denom = denom * i % mod\n    return numer * pow(denom, mod-2, mod) % mod\n\ndef H(n, r, mod=10**9+7):\n    # nHr mod m\n    return combination(n+r-1, r, mod)\n\ndef combination_list(n, mod=10**9+7):\n    # nCrをすべてのr(0<=r<=n)について求める\n    # nC0, nC1, nC2, ... , nCn を求める\n    lst = [1]\n    for i in range(1, n+1):\n        lst.append(lst[-1] * (n+1-i) % mod * pow(i, mod-2, mod) % mod)\n    return lst\n\ndef make_modinv_list(n, mod=10**9+7):\n    # 0 から n までの mod 逆元のリストを返す O(n)\n    modinv = [0, 1]\n    for i in range(2, n+1):\n        modinv.append(mod - mod//i * modinv[mod%i] % mod)\n    return modinv\n\nclass Combination:\n    def __init__(self, n_max, mod=10**9+7):\n        # O(n_max + log(mod))\n        self.mod = mod\n        f = 1\n        self.fac = fac = [f]\n        for i in range(1, n_max+1):\n            f = f * i % mod\n            fac.append(f)\n        f = pow(f, mod-2, mod)\n        self.facinv = facinv = [f]\n        for i in range(n_max, 0, -1):\n            f = f * i % mod\n            facinv.append(f)\n        facinv.reverse()\n\n    def __call__(self, n, r):\n        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod\n\n    def C(self, n, r):\n        if not 0 <= r <= n: return 0\n        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod\n\n    def P(self, n, r):\n        if not 0 <= r <= n: return 0\n        return self.fac[n] * self.facinv[n-r] % self.mod\n\n    def H(self, n, r):\n        if (n == 0 and r > 0) or r < 0: return 0\n        return self.fac[n+r-1] * self.facinv[r] % self.mod * self.facinv[n-1] % self.mod\n\n    # \"n 要素\" は区別できる n 要素\n    # \"k グループ\" はちょうど k グループ\n\n    def rising_factorial(self, n, r):  # 上昇階乗冪 n * (n+1) * ... * (n+r-1)\n        return self.fac[n+r-1] * self.facinv[n-1] % self.mod\n\n    def stirling_first(self, n, k):  # 第 1 種スターリング数  lru_cache を使うと O(nk)  # n 要素を k 個の巡回列に分割する場合の数\n        if n == k: return 1\n        if k == 0: return 0\n        return (self.stirling_first(n-1, k-1) + (n-1)*self.stirling_first(n-1, k)) % self.mod\n\n    def stirling_second(self, n, k):  # 第 2 種スターリング数 O(k + log(n))  # n 要素を区別のない k グループに分割する場合の数\n        if n == k: return 1  # n==k==0 のときのため\n        return self.facinv[k] * sum((-1)**(k-m) * self.C(k, m) * pow(m, n, self.mod) for m in range(1, k+1)) % self.mod\n\n    def balls_and_boxes_3(self, n, k):  # n 要素を区別のある k グループに分割する場合の数  O(k + log(n))\n        return sum((-1)**(k-m) * self.C(k, m) * pow(m, n, self.mod) for m in range(1, k+1)) % self.mod\n\n    def bernoulli(self, n):  # ベルヌーイ数  lru_cache を使うと O(n**2 * log(mod))\n        if n == 0: return 1\n        if n % 2 and n >= 3: return 0  # 高速化\n        return (- pow(n+1, self.mod-2, self.mod) * sum(self.C(n+1, k) * self.bernoulli(k) % self.mod for k in range(n))) % self.mod\n\n    def faulhaber(self, k, n):  # べき乗和 0^k + 1^k + ... + (n-1)^k\n        # bernoulli に lru_cache を使うと O(k**2 * log(mod))  bernoulli が計算済みなら O(k * log(mod))\n        return pow(k+1, self.mod-2, self.mod) * sum(self.C(k+1, j) * self.bernoulli(j) % self.mod * pow(n, k-j+1, self.mod) % self.mod for j in range(k+1)) % self.mod\n\n    def lah(self, n, k):  # n 要素を k 個の空でない順序付き集合に分割する場合の数  O(1)\n        return self.C(n-1, k-1) * self.fac[n] % self.mod * self.facinv[k] % self.mod\n\n    def bell(self, n, k):  # n 要素を k グループ以下に分割する場合の数  O(k**2 + k*log(mod))\n        return sum(self.stirling_second(n, j) for j in range(1, k+1)) % self.mod\n\ndef make_prime_checker(n):\n    # n までの自然数が素数かどうかを表すリストを返す  O(nloglogn)\n    is_prime = [False, True, False, False, False, True] * (n//6+1)\n    del is_prime[n+1:]\n    is_prime[1:4] = False, True, True\n    for i in range(5, int(n**0.5)+1):\n        if is_prime[i]:\n            is_prime[i*i::i] = [False] * (n//i-i+1)\n    return is_prime\n\ndef prime_factorization(n):\n    # 素因数分解\n    i = 2\n    table = []\n    while i * i <= n:\n        while n % i == 0:\n            n //= i\n            table.append(i)\n        i += 1\n    if n > 1:\n        table.append(n)\n    return table\n\ndef fast_prime_factorization(n):\n    # 素因数分解（ロー法）  O(n^(1/4) polylog(n))\n    from subprocess import Popen, PIPE\n    return list(map(int, Popen([\"factor\", str(n)], stdout=PIPE).communicate()[0].split()[1:]))\n\ndef fast_prime_factorization_many(lst):\n    # 素因数分解（ロー法、複数）\n    from subprocess import Popen, PIPE\n    res = Popen([\"factor\"] + list(map(str, lst)), stdout=PIPE).communicate()[0].split(b\"\\n\")[:-1]\n    return [list(map(int, r.split()[1:])) for r in res]\n\ndef miller_rabin(n):\n    # 確率的素数判定（ミラーラビン素数判定法）\n    # 素数なら確実に True を返す、合成数なら確率的に False を返す\n    # True が返ったなら恐らく素数で、False が返ったなら確実に合成数である\n    # 参考: http://tjkendev.github.io/procon-library/python/prime/probabilistic.html\n    # 検証: https://yukicoder.me/submissions/381948\n    primes = [2, 325, 9375, 28178, 450775, 9780504, 1795265022]  # 32bit: [2, 7, 61]\n    if n==2: return True\n    if n<=1 or n&1==0: return False\n    d = m1 = n-1\n    d //= d & -d\n    for a in primes:\n        if a >= n: return True\n        t, y = d, pow(a, d, n)\n        while t!=m1 and y!=1 and y!=m1:\n            y = y * y % n\n            t <<= 1\n        if y!=m1 and t&1==0: return False\n    return True\n\n\nclass Bit:\n    # Binary Indexed Tree\n    def __init__(self, n):\n        self.size = n\n        self.tree = [0]*(n+1)\n\n    def __iter__(self):\n        psum = 0\n        for i in range(self.size):\n            csum = self.sum(i+1)\n            yield csum - psum\n            psum = csum\n        raise StopIteration()\n\n    def __str__(self):  # O(nlogn)\n        return str(list(self))\n\n    def sum(self, i):\n        # [0, i) の要素の総和を返す\n        if not (0 <= i <= self.size): raise ValueError(\"error!\")\n        s = 0\n        while i>0:\n            s += self.tree[i]\n            i -= i & -i\n        return s\n\n    def add(self, i, x):\n        if not (0 <= i < self.size): raise ValueError(\"error!\")\n        i += 1\n        while i <= self.size:\n            self.tree[i] += x\n            i += i & -i\n\n    def __getitem__(self, key):\n        if not (0 <= key < self.size): raise IndexError(\"error!\")\n        return self.sum(key+1) - self.sum(key)\n\n    def __setitem__(self, key, value):\n        # 足し算と引き算にはaddを使うべき\n        if not (0 <= key < self.size): raise IndexError(\"error!\")\n        self.add(key, value - self[key])\n\nclass BitImos:\n    \"\"\"\n    ・範囲すべての要素に加算\n    ・ひとつの値を取得\n    の2種類のクエリをO(logn)で処理\n    \"\"\"\n    def __init__(self, n):\n        self.bit = Bit(n+1)\n\n    def add(self, s, t, x):\n        # [s, t)にxを加算\n        self.bit.add(s, x)\n        self.bit.add(t, -x)\n\n    def get(self, i):\n        return self[i]\n\n    def __getitem__(self, key):\n        # 位置iの値を取得\n        return self.bit.sum(key+1)\n\n\"\"\"\n# BITで転倒数を求められる\nA = [3, 10, 1, 8, 5, 5, 1]\nbit = Bit(max(A)+1)\nans = 0\nfor i, a in enumerate(A):\n    ans += i - bit.sum(a+1)\n    bit.add(a, 1)\nprint(ans)\n\"\"\"\n\n# 未検証\nclass Bit2:\n    def __init__(self, n):\n        self.bit0 = Bit(n)\n        self.bit1 = Bit(n)\n\n    def add(self, l, r, x):\n        # [l, r) に x を足す\n        self.bit0.add(l, -x * (l-1))\n        self.bit1.add(l, x)\n        self.bit0.add(r, x * (r-1))\n        self.bit1.add(r, -x)\n\n    def sum(self, l, r):\n        res = 0\n        res += self.bit0.sum(r) + self.bit1.sum(r) * (r-1)\n        res -= self.bit0.sum(l) + self.bit1.sum(l) * (l-1)\n        return res\n\n\ndef dijkstra(G, start):\n    # ダイクストラ法\n    from heapq import heappush, heappop\n    N = len(G)\n    inf = 1 << 62\n    distances = [inf] * N\n    distances[start] = 0\n    q = [(0, start)]\n    while q:\n        dv, v = heappop(q)\n        if distances[v] != dv:\n            continue\n        for u, cost in G[v]:\n            du = dv + cost\n            if du < distances[u]:\n                distances[u] = du\n                heappush(q, (du, u))\n    return distances\n\ndef shortest_path_faster_algorithm(E, start):\n    # ベルマンフォードの更新があるところだけ更新する感じのやつ\n    # O(VE) だが実用上高速\n    # E は隣接リスト\n    # 検証: http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=4005805#1\n    # deque 版 (コーナーケースに強い？): http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=4005813\n    inf = float(\"inf\")  # 10**18 は良くない\n    N = len(E)\n    q = [start]\n    distance = [inf] * N;  distance[start] = 0\n    in_q = [0] * N;        in_q[start] = True\n    times = [0] * N;       times[start] = 1\n    while q:\n        v = q.pop()\n        in_q[v] = False\n        dist_v = distance[v]\n        for u, cost in E[v]:\n            new_dist_u = dist_v + cost\n            if distance[u] > new_dist_u:\n                times[u] += 1\n                if times[u] >= N:  # 負閉路検出\n                    distance[u] = -inf\n                else:\n                    distance[u] = new_dist_u\n                if not in_q[u]:\n                    in_q[u] = True\n                    q.append(u)\n    return distance\n\n\nclass UnionFind:\n    # 検証: https://atcoder.jp/contests/practice2/submissions/17594179\n    def __init__(self, N):\n        self.p = list(range(N))\n        self.size = [1] * N\n\n    def root(self, x):\n        p = self.p\n        while x != p[x]:\n            x = p[x]\n        return x\n\n    def same(self, x, y):\n        return self.root(x) == self.root(y)\n\n    def unite(self, x, y):\n        u = self.root(x)\n        v = self.root(y)\n        if u == v:\n            return\n        size = self.size\n        if size[u] < size[v]:\n            self.p[u] = v\n            size[v] += size[u]\n            size[u] = 0\n        else:\n            self.p[v] = u\n            size[u] += size[v]\n            size[v] = 0\n\n    def count(self, x):\n        return self.size[self.root(x)]\n\n\ndef fast_zeta_transform_superset(arr):\n    # 上位集合の高速ゼータ変換  O(nlog(n))\n    # fast_zeta_transform_superset([1]*8) => [8, 4, 4, 2, 4, 2, 2, 1]\n    # 添字 and での畳み込みに使う\n    n = len(arr)\n    assert n & -n == n  # n は 2 冪\n    for i in range(n.bit_length()-1):\n        for s in range(n):\n            if s>>i&1 == 0:\n                arr[s] -= arr[s|1<<i]  # -= にすると逆変換\n    return arr\n\ndef fast_zeta_transform_subset(arr):\n    # 下位集合の高速ゼータ変換  O(nlog(n))\n    # fast_zeta_transform_subset([1]*8) => [1, 2, 2, 4, 2, 4, 4, 8]\n    # 添字 or での畳み込みに使う\n    n = len(arr)\n    assert n & -n == n  # n は 2 冪\n    for i in range(n.bit_length()-1):\n        for s in range(n):\n            if s>>i&1:\n                arr[s] += arr[s^1<<i]  # -= にすると逆変換\n    return arr\n\n# 倍数集合の高速ゼータ変換: https://atcoder.jp/contests/agc038/submissions/7671865\n\n\nclass SegmentTree(object):\n    # 検証: https://atcoder.jp/contests/nikkei2019-2-qual/submissions/8434117\n    # 参考: https://atcoder.jp/contests/abc014/submissions/3935971\n    __slots__ = [\"elem_size\", \"tree\", \"default\", \"op\", \"real_size\"]\n\n    def __init__(self, a, default, op):\n        self.default = default\n        self.op = op\n        if hasattr(a, \"__iter__\"):\n            self.real_size = len(a)\n            self.elem_size = elem_size = 1 << (self.real_size-1).bit_length()\n            self.tree = tree = [default] * (elem_size * 2)\n            tree[elem_size:elem_size + self.real_size] = a\n            for i in range(elem_size - 1, 0, -1):\n                tree[i] = op(tree[i << 1], tree[(i << 1) + 1])\n        elif isinstance(a, int):\n            self.real_size = a\n            self.elem_size = elem_size = 1 << (self.real_size-1).bit_length()\n            self.tree = [default] * (elem_size * 2)\n\n    def get_value(self, x: int, y: int) -> int:  # 半開区間\n        l, r = x + self.elem_size, y + self.elem_size\n        tree, result, op = self.tree, self.default, self.op\n        while l < r:\n            if l & 1:\n                result = op(tree[l], result)\n                l += 1\n            if r & 1:\n                r -= 1\n                result = op(tree[r], result)\n            l, r = l >> 1, r >> 1\n        return result\n\n    def set_value(self, i: int, value: int) -> None:\n        k = self.elem_size + i\n        op, tree = self.op, self.tree\n        tree[k] = value\n        while k > 1:\n            k >>= 1\n            tree[k] = op(tree[k << 1], tree[(k << 1) + 1])\n\n    def get_one_value(self, i):\n        return self.tree[i+self.elem_size]\n\n    def debug(self):\n        print(self.tree[self.elem_size:self.elem_size+self.real_size])\n\n\ndef manacher(S):\n    # 最長回文 O(n)\n    # R[i] := i 文字目を中心とする最長の回文の半径（自身を含む）\n    # 偶数長の回文を検出するには \"$a$b$a$a$b$\" のようにダミーを挟む\n    # 検証: https://atcoder.jp/contests/wupc2019/submissions/8665857\n    # 左右で違う条件: https://atcoder.jp/contests/code-thanks-festival-2014-a-open/submissions/12911822\n    c, r, n = 0, 0, len(S)  # center, radius, length\n    R = [0]*n\n    while c < n:\n        while c-r >= 0 and c+r < n and S[c-r] == S[c+r]:\n            r += 1\n        R[c] = r\n        d = 1  # distance from center\n        while c-d >= 0 and c+d < n and d+R[c-d] < r:\n            R[c+d] = R[c-d]\n            d += 1\n        c += d\n        r -= d\n    return R\n\ndef z_algorithm(S):\n    # Z アルゴリズム  O(n)\n    # Z[i] := S と S[i:] で prefix が何文字一致しているか\n    # 検証: https://atcoder.jp/contests/arc055/submissions/14179788\n    i, j, n = 1, 0, len(S)\n    Z = [0] * n\n    Z[0] = n\n    while i < n:\n        while i+j < n and S[j] == S[i+j]:\n            j += 1\n        if j == 0:\n            i += 1\n            continue\n        Z[i] = j\n        d = 1\n        while i+d < n and d+Z[d] < j:\n            Z[i+d] = Z[d]\n            d += 1\n        i += d\n        j -= d\n    return Z\n\n\n# 最大流問題\nfrom collections import deque\nINF = float(\"inf\")\nTO = 0;  CAP = 1;  REV = 2\nclass Dinic:\n    def __init__(self, N):\n        self.N = N\n        self.V = [[] for _ in range(N)]  # to, cap, rev\n        # 辺 e = V[n][m] の逆辺は V[e[TO]][e[REV]]\n        self.level = [0] * N\n\n    def add_edge(self, u, v, cap):\n        self.V[u].append([v, cap, len(self.V[v])])\n        self.V[v].append([u, 0, len(self.V[u])-1])\n\n    def add_edge_undirected(self, u, v, cap):  # 未検証\n        self.V[u].append([v, cap, len(self.V[v])])\n        self.V[v].append([u, cap, len(self.V[u])-1])\n\n    def bfs(self, s: int) -> bool:\n        self.level = [-1] * self.N\n        self.level[s] = 0\n        q = deque()\n        q.append(s)\n        while len(q) != 0:\n            v = q.popleft()\n            for e in self.V[v]:\n                if e[CAP] > 0 and self.level[e[TO]] == -1:  # capが1以上で未探索の辺\n                    self.level[e[TO]] = self.level[v] + 1\n                    q.append(e[TO])\n        return True if self.level[self.g] != -1 else False  # 到達可能\n\n    def dfs(self, v: int, f) -> int:\n        if v == self.g:\n            return f\n        for i in range(self.ite[v], len(self.V[v])):\n            self.ite[v] = i\n            e = self.V[v][i]\n            if e[CAP] > 0 and self.level[v] < self.level[e[TO]]:\n                d = self.dfs(e[TO], min(f, e[CAP]))\n                if d > 0:  # 増加路\n                    e[CAP] -= d  # cap を減らす\n                    self.V[e[TO]][e[REV]][CAP] += d  # 反対方向の cap を増やす\n                    return d\n        return 0\n\n    def solve(self, s, g):\n        self.g = g\n        flow = 0\n        while self.bfs(s):  # 到達可能な間\n            self.ite = [0] * self.N\n            f = self.dfs(s, INF)\n            while f > 0:\n                flow += f\n                f = self.dfs(s, INF)\n        return flow\n\n\ndef lis(A: list):  # 最長増加部分列\n    # original author: ikatakos\n    # https://ikatakos.com/pot/programming_algorithm/dynamic_programming/longest_common_subsequence\n    from bisect import bisect_left\n    L = [A[0]]\n    for a in A[1:]:\n        if a > L[-1]:\n            # Lの末尾よりaが大きければ増加部分列を延長できる\n            L.append(a)\n        else:\n            # そうでなければ、「aより小さい最大要素の次」をaにする\n            # 該当位置は、二分探索で特定できる\n            L[bisect_left(L, a)] = a\n    return len(L)\n\n\nclass NewtonInterpolation:\n    # ニュートン補間  O(n^2)  n は次元\n    # 具体的な係数は保持しない\n    def __init__(self, X=(), Y=(), mod=10**9+7):\n        self.mod = mod\n        self.X = []\n        self.C = []\n        for x, y in zip(X, Y):\n            self.add_constraint(x, y)\n\n    def add_constraint(self, x, y):  # O(n)\n        mod, X, C = self.mod, self.X, self.C\n        numer, denom = y, 1\n        for c, x_ in zip(C, X):\n            numer -= denom * c\n            denom = denom * (x - x_) % mod\n        X.append(x)\n        C.append(numer * pow(denom, mod-2, mod) % mod)\n\n    def calc(self, x):\n        mod, X, C = self.mod, self.X, self.C\n        y = 0\n        for c, x_ in zip(C[::-1], X[::-1]):\n            y = (y * (x - x_) + c) % mod\n        return y\n\ndef fast_lagrange_interpolation(Y, x, mod=10**9+7):\n    # X = [0, 1, 2, ... , n] のラグランジュ補間  O(nlog(mod))  # n==len(Y)-1\n    if 0 <= x < len(Y):\n        return Y[x] % mod\n    factorial, f, numer = [1], 1, x\n    for x_ in range(1, len(Y)):\n        f = f * x_ % mod\n        factorial.append(f)\n        numer = numer * (x - x_) % mod\n    y = 0\n    for x_, (y_, denom1, denom2) in enumerate(zip(Y, factorial, factorial[::-1])):\n        y = (y_ * numer * pow((x-x_)*denom1*denom2, mod-2, mod) - y) % mod\n    return y\n\ndef faulhaber(k, n, mod=10**9+7):  # べき乗和 0^k + 1^k + ... + (n-1)^k\n    # n に関する k+1 次式になるので最初の k+2 項を求めれば多項式補間できる  O(k log(mod))\n    s, Y = 0, [0]  # 第 0 項は 0\n    for x in range(k+1):\n        s += pow(x, k, mod)\n        Y.append(s)\n    return fast_lagrange_interpolation(Y, n, mod)\n\n\nclass RollingHash:\n    # 未検証\n    # 参考1:  http://tjkendev.github.io/procon-library/python/string/rolling_hash.html\n    # 参考2:  https://ei1333.github.io/algorithm/rolling-hash.html\n    BASE = 1000\n    MOD = 1111111111111111111  # ≒10**18 素数  # 10**9くらいの素数2つ使うのとどちらが速い？\n    def __init__(self, s):\n        self.s = s\n        self.n = n = len(s)\n        BASE = RollingHash.BASE\n        MOD = RollingHash.MOD\n        self.h = h = [0]*(n+1)\n        for i in range(n):\n            h[i+1] = (h[i] * BASE + ord(s[i])) % MOD\n\n    def get(self, l, r):  # [l, r)\n        MOD = RollingHash.MOD\n        return (self.h[r] - self.h[l]*pow(RollingHash.BASE, r-l, MOD)) % MOD\n\n    @classmethod\n    def connect(cls, h1, h2, h2len):\n        return (h1 * pow(cls.BASE, h2len, cls.MOD) + h2) % cls.MOD\n\n    def lcp(self, h2, l1, r1, l2, r2):  # 最長共通接頭辞\n        # 区間の長さ N に対して O(logN)  # h2 は RollingHash オブジェクト\n        # 自身の [l1, r1) と h2 の [l2, r2) の最長共通接頭辞の長さを返す\n        length = min(r1-l1, r2-l2)\n        ok, ng = 0, length+1\n        while ng - ok > 1:\n            c = ok + ng >> 1\n            if self.get(l1, l1+c) == h2.get(l2, l2+c):\n                ok = c\n            else:\n                ng = c\n        return ok\n\n\ndef convolve(A, B):\n    # 畳み込み (Numpy)  # 要素は整数\n    # 3 つ以上の場合は一度にやった方がいい\n    import numpy as np\n    dtype = np.int64  # np.float128 は windows では動かない？\n    fft, ifft = np.fft.rfft, np.fft.irfft\n    a, b = len(A), len(B)\n    if a==b==1:\n        return np.array([A[0]*B[0]])\n    n = a + b - 1  # 返り値のリストの長さ\n    k = 1 << (n-1).bit_length()  # n 以上の最小の 2 冪\n    AB = np.zeros((2, k), dtype=dtype)\n    AB[0, :a] = A\n    AB[1, :b] = B\n    return np.rint(ifft(fft(AB[0]) * fft(AB[1]))).astype(np.int64)[:n]\n\ndef garner(A, M, mod):\n    # Garner のアルゴリズム (NumPy)\n    # 参考: https://math314.hateblo.jp/entry/2015/05/07/014908\n    M.append(mod)\n    coffs = [1] * len(M)\n    constants = np.zeros((len(M),)+A[0].shape, dtype=np.int64)\n    for i, (a, m) in enumerate(zip(A, M[:-1])):\n        v = (a - constants[i]) * pow(coffs[i], m-2, m) % m\n        for j, mm in enumerate(M[i+1:], i+1):\n            constants[j] = (constants[j] + coffs[j] * v) % mm\n            coffs[j] = coffs[j] * m % mm\n    return constants[-1]\n\ndef convolve_mod(A, B, mod=10**9+7):\n    # 任意 mod 畳み込み (NumPy)\n    # 検証1: 注文の多い高橋商店 (TLE): https://atcoder.jp/contests/arc028/submissions/7467522\n    # 検証2: [yosupo] Convolution (mod 1,000,000,007): https://judge.yosupo.jp/submission/12504\n    \n    #mods = [1000003, 1000033, 1000037, 1000039]  # 要素数が 10**3 以下の場合（誤差 6*2+3=15<16  復元 6*4=24>21=9*2+3）\n    #mods = [100003, 100019, 100043, 100049, 100057]  # 要素数が10**5 以下の場合（誤差 5*2+5=15<16  復元 5*5=25>23=9*2+5）\n    mods = [63097, 63103, 63113, 63127, 63131]  # 要素数が 5*10**5 以下の場合（誤差 4.8*2+5.7=15.3<16  復元 4.8*5=24>23.7=9*2+5.7  10**4.8=63096  10**5.7=501187）\n    \n    mods_np = np.array(mods, dtype=np.int32)\n    fft, ifft = np.fft.rfft, np.fft.irfft\n    a, b = len(A), len(B)\n    if a == b == 1:\n        return np.array([A[0] * B[0]]) % mod\n    n = a + b - 1  # 畳み込みの結果の長さ\n    k = 1 << (n - 1).bit_length()  # n 以上の最小の 2 冪\n    AB = np.zeros((2, len(mods), k), dtype=np.int64)  # ここの dtype は fft 後の dtype に関係しない\n    AB[0, :, :a] = A\n    AB[1, :, :b] = B\n    AB[:, :, :] %= mods_np[:, None]\n    C = ifft(fft(AB[0]) * fft(AB[1]))[:, :n]\n    C = ((C + 0.5) % mods_np[:, None]).astype(np.int64)\n    return garner(C, mods, mod)\n\n\ndef scc(E, n_vertex):\n    # 強連結成分分解 (NumPy, SciPy)  # E は [[a1, b1], [a2, b2], ... ] の形\n    # 返り値は 強連結成分の数 と 各頂点がどの強連結成分に属しているか\n    # numpy いらないのは https://tjkendev.github.io/procon-library/python/graph/scc.html\n    import numpy as np\n    from scipy.sparse import csr_matrix, csgraph\n    A, B = np.array(E).T\n    graph = csr_matrix((np.ones(len(E)), (A, B)), (n_vertex, n_vertex))\n    n_components, labels = csgraph.connected_components(graph, connection='strong')\n    return n_components, labels\n\n\ndef distribute(n, person, min, max, mode=\"even\"):\n    # n 個を person 人に分配する\n    # 返り値は [[a (個), a 個もらう人数], ...]\n    # 分配できないときは None を返す\n    if person==0 and n==0:\n        return []\n    elif not min*person <= n <= max*person:\n        return None\n    elif mode==\"even\":\n        q, m = divmod(n, person)\n        if m==0:\n            return [[q, person]]\n        else:\n            return [[q, person-m], [q+1, m]]\n    elif mode==\"greedy\":\n        if max==min:\n            return [[max, person]]\n        n -= min * person\n        q, m = divmod(n, max-min)\n        if m==0:\n            return [[min, person-q], [max, q]]\n        else:\n            return [[min, person-1-q], [min+m, 1], [max, q]]\n    else:\n        raise ValueError(\"'mode' must be 'even' or 'greedy'.\")\n\n\ndef xorshift(seed=123456789):  # 31 bit xorshift\n    y = seed\n    def randint(a, b):  # 閉区間\n        nonlocal y\n        y ^= (y & 0xffffff) << 7\n        y ^= y >> 12\n        return y % (b-a+1) + a\n    return randint\n\n\n\"\"\"\n# 重み付き UnionFind https://atcoder.jp/contests/code-festival-2016-quala/submissions/8336387\n# Trie https://atcoder.jp/contests/code-festival-2016-qualb/submissions/8335110\n# 全方位木 dp https://atcoder.jp/contests/yahoo-procon2019-final-open/submissions/8664902\n# 平方分割\n#  I hate Shortest Path Problem https://atcoder.jp/contests/abc177/submissions/16384352\n#  Replace Digits https://atcoder.jp/contests/abl/submissions/17049200\n#  天下一数列にクエリを投げます https://atcoder.jp/contests/tenka1-2016-qualb/submissions/14415635\n#  Range Affine Range Sum https://atcoder.jp/contests/practice2/submissions/17100361\n\n\nA = csgraph.dijkstra(X, indices=0)\n\nzip(*[iter(Ans)]*3)  # 3 個ずつ\nzip(*[iter(map(int, sys.stdin.read().split()))]*4):\n\nhttps://github.com/Lgeu/snippet/\nimport sys\ninput = sys.stdin.readline\nC = np.frombuffer(buf.read(), dtype=\"S1\").reshape(H, W+1)[:, :-1].T\n\"\"\"\n\n", "meta": {"hexsha": "0abdb1cb9e795553db7d4ab2a3115ee00d7fd099", "size": 23977, "ext": "py", "lang": "Python", "max_stars_repo_path": "snippet.py", "max_stars_repo_name": "Lgeu/snippet", "max_stars_repo_head_hexsha": "02a027c6f06d21bcffb7d7585b7a4244ed20143a", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-03-01T07:37:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T02:52:45.000Z", "max_issues_repo_path": "snippet.py", "max_issues_repo_name": "Lgeu/snippet", "max_issues_repo_head_hexsha": "02a027c6f06d21bcffb7d7585b7a4244ed20143a", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snippet.py", "max_forks_repo_name": "Lgeu/snippet", "max_forks_repo_head_hexsha": "02a027c6f06d21bcffb7d7585b7a4244ed20143a", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-06-15T09:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-28T05:43:32.000Z", "avg_line_length": 30.5439490446, "max_line_length": 166, "alphanum_fraction": 0.5124494307, "include": true, "reason": "import numpy,from scipy", "num_tokens": 9392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075733703925, "lm_q2_score": 0.9073122182277757, "lm_q1q2_score": 0.8729319565684334}}
{"text": "import pylab\nimport numpy\n\nclass GeneralRandom:\n  \"\"\"This class enables us to generate random numbers with an arbitrary \n  distribution.\"\"\"\n  \n  def __init__(self, x = pylab.arange(-1.0, 1.0, .01), p = None, Nrl = 1000):\n    \"\"\"Initialize the lookup table (with default values if necessary)\n    Inputs:\n    x = random number values\n    p = probability density profile at that point\n    Nrl = number of reverse look up values between 0 and 1\"\"\"  \n    if p == None:\n      p = pylab.exp(-10*x**2.0)\n    self.set_pdf(x, p, Nrl)\n    \n  def set_pdf(self, x, p, Nrl = 1000):\n    \"\"\"Generate the lookup tables. \n    x is the value of the random variate\n    pdf is its probability density\n    cdf is the cumulative pdf\n    inversecdf is the inverse look up table\n    \n    \"\"\"\n    \n    self.x = x\n    self.pdf = p/p.sum() #normalize it\n    self.cdf = self.pdf.cumsum()\n    self.inversecdfbins = Nrl\n    self.Nrl = Nrl\n    y = pylab.arange(Nrl)/float(Nrl)\n    delta = 1.0/Nrl\n    self.inversecdf = pylab.zeros(Nrl)    \n    self.inversecdf[0] = self.x[0]\n    cdf_idx = 0\n    for n in xrange(1,self.inversecdfbins):\n      while self.cdf[cdf_idx] < y[n] and cdf_idx < Nrl:\n        cdf_idx += 1\n      self.inversecdf[n] = self.x[cdf_idx-1] + (self.x[cdf_idx] - self.x[cdf_idx-1]) * (y[n] - self.cdf[cdf_idx-1])/(self.cdf[cdf_idx] - self.cdf[cdf_idx-1]) \n      if cdf_idx >= Nrl:\n        break\n    self.delta_inversecdf = pylab.concatenate((pylab.diff(self.inversecdf), [0]))\n              \n  def random(self, N = 1000):\n    \"\"\"Give us N random numbers with the requested distribution\"\"\"\n\n    idx_f = numpy.random.uniform(size = N, high = self.Nrl-1)\n    idx = pylab.array([idx_f],'i')\n    y = self.inversecdf[idx] + (idx_f - idx)*self.delta_inversecdf[idx]\n\n    return y\n  \n  def plot_pdf(self):\n    pylab.plot(self.x, self.pdf)\n    \n  def self_test(self, N = 1000):\n    pylab.figure()\n    #The cdf\n    pylab.subplot(2,2,1)\n    pylab.plot(self.x, self.cdf)\n    #The inverse cdf\n    pylab.subplot(2,2,2)\n    y = pylab.arange(self.Nrl)/float(self.Nrl)\n    pylab.plot(y, self.inversecdf)\n    \n    #The actual generated numbers\n    pylab.subplot(2,2,3)\n    y = self.random(N)\n    p1, edges = pylab.histogram(y, bins = 50, \n                                range = (self.x.min(), self.x.max()), \n                                normed = True, new = True)\n    x1 = 0.5*(edges[0:-1] + edges[1:])\n    pylab.plot(x1, p1/p1.max())\n    pylab.plot(self.x, self.pdf/self.pdf.max())\n", "meta": {"hexsha": "7cbdd60371686980de194ba052508e3051312181", "size": 2453, "ext": "py", "lang": "Python", "max_stars_repo_path": "recipes/Python/576556_Generating_random_numbers_arbitrary/recipe-576556.py", "max_stars_repo_name": "tdiprima/code", "max_stars_repo_head_hexsha": "61a74f5f93da087d27c70b2efe779ac6bd2a3b4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2023, "max_stars_repo_stars_event_min_datetime": "2017-07-29T09:34:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T08:00:45.000Z", "max_issues_repo_path": "recipes/Python/576556_Generating_random_numbers_arbitrary/recipe-576556.py", "max_issues_repo_name": "unhacker/code", "max_issues_repo_head_hexsha": "73b09edc1b9850c557a79296655f140ce5e853db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2017-09-02T17:20:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T17:49:37.000Z", "max_forks_repo_path": "recipes/Python/576556_Generating_random_numbers_arbitrary/recipe-576556.py", "max_forks_repo_name": "unhacker/code", "max_forks_repo_head_hexsha": "73b09edc1b9850c557a79296655f140ce5e853db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 780, "max_forks_repo_forks_event_min_datetime": "2017-07-28T19:23:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T20:39:41.000Z", "avg_line_length": 32.2763157895, "max_line_length": 158, "alphanum_fraction": 0.6021198532, "include": true, "reason": "import numpy", "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075711974103, "lm_q2_score": 0.9073122113355091, "lm_q1q2_score": 0.8729319479657581}}
{"text": "import itertools\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport streamlit as st\n\n\n# From Python Cookbook\ndef erat2( ):\n    D = {  }\n    yield 2\n    for q in itertools.islice(itertools.count(3), 0, None, 2):\n        p = D.pop(q, None)\n        if p is None:\n            D[q*q] = q\n            yield q\n        else:\n            x = p + q\n            while x in D or not (x&1):\n                x += p\n            D[x] = p\n\ndef get_primes_erat(n):\n  return list(itertools.takewhile(lambda p: p<n, erat2()))\n\ndef get_prime_distribution(n):\n    hist, bins = np.histogram(get_primes_erat(n), bins=np.linspace(1.5, n-0.5, n-1))\n    prime_count = np.cumsum(hist)\n    return prime_count\n\nmax_int = 1000\ndf = pd.DataFrame()\nintegers = list(range(2, max_int))\ndf['Integers'] = integers\ndf['Prime Counting Function'] = integers/np.log(integers)\ndf['Number of Primes'] = get_prime_distribution(max_int)\n\nst.title(\"Prime Number Theorem\")\n\nquote = \"_In number theory, the prime number theorem (PNT) describes the asymptotic distribution of the prime numbers among the positive integers. It formalizes the intuitive idea that primes become less common as they become larger by precisely quantifying the rate at which this occurs._\"\nst.markdown(quote)\n\nfig, ax = plt.subplots()\nax.plot(df['Integers'], df['Prime Counting Function'], 'k-', label='Prime Counting Function')\nax.plot(df['Integers'], df['Number of Primes'], 'b-', label='Actual Number of Primes')\nax.legend()\nax.set_xlabel(\"n\")\n\nst.pyplot(fig)", "meta": {"hexsha": "581252e3bb3e6d1ea5f8c993a150f406fdf0b355", "size": 1518, "ext": "py", "lang": "Python", "max_stars_repo_path": "app/app.py", "max_stars_repo_name": "mapta/docker-streamlit-prim", "max_stars_repo_head_hexsha": "0322cc8c2aaeeb398a65cac0a5a693e38f951a88", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/app.py", "max_issues_repo_name": "mapta/docker-streamlit-prim", "max_issues_repo_head_hexsha": "0322cc8c2aaeeb398a65cac0a5a693e38f951a88", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/app.py", "max_forks_repo_name": "mapta/docker-streamlit-prim", "max_forks_repo_head_hexsha": "0322cc8c2aaeeb398a65cac0a5a693e38f951a88", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.36, "max_line_length": 290, "alphanum_fraction": 0.6673254282, "include": true, "reason": "import numpy", "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241982893259, "lm_q2_score": 0.9005297887874625, "lm_q1q2_score": 0.8729053155520631}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 16 15:24:48 2015\n\n@author: Hanna\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef featureNormalize(X):\n    mu = np.mean(X,axis=0)\n    X_norm = X-mu\n    sigma = np.std(X_norm,axis=0)\n    X_norm = X_norm/sigma\n    \n    return X_norm, mu, sigma\n\n\ndef hypothesis(theta,X):\n    #works for any # of features\n\n    return np.dot(X,theta)\n\n\ndef computeCost(X,y,theta):  # J(theta)\n    #works for any # of features\n    m = len(y)\n    h = hypothesis(theta,X)\n    \n    return (np.dot((h-y).T,h-y))/(2.0*m)\n\n\ndef computeCostDeriv(X,y,theta):  # partial derivatives of J(theta)\n    #works for any # of features\n    m = len(y)\n    h = hypothesis(theta,X)\n    \n    return np.dot(X.T,h-y)/m\n\n\ndef gradientDescent(X,y,theta,alpha,iterations):\n    #works for any # of features\n    \n    #J(theta) as a function of # of iterations\n    costHistory = np.zeros((iterations+1,1))  # for debugging\n    costHistory[0,0] = computeCost(X,y,theta)  # for debugging\n    \n    #gradient descent\n    for iter in range(0,iterations):\n        theta = theta - alpha*computeCostDeriv(X,y,theta)\n        #or, without separately calculating derivatives\n        #theta = theta - np.dot(X.T,hypothesis(theta,X)-y)*alpha/len(y)\n        \n        costHistory[iter+1,0] = computeCost(X,y,theta)  # for debugging\n    \n    return theta, costHistory\n\n\ndef normalEquation(X,y):#analytical solution for theta which minimizes J(theta)\n    #works for any # of features\n    \n    return np.dot(np.dot(np.linalg.inv(np.dot(X.T,X)),X.T),y)\n\n    \nif __name__ == '__main__':\n    \n    data = np.genfromtxt(\"ex1data2.txt\", delimiter=',')\n    X, y = data[:,:2], data[:,2:]\n    m = np.shape(y)[0]  # number of examples in training set\n    n = np.shape(X)[1]  # number of features\n    \n    #normalize features\n    #print(X[0:10,:])  # first ten examples of original data\n    X, mu, sigma = featureNormalize(X)\n    #print(X[0:10,:])  # first ten examples of normalized data\n    \n    #multivariate linear regression    \n    X = np.hstack((np.ones((m,1)),X))  # add intercept column\n    \n    #try for many alphas to select optimal learning rate\n    alphas = [1.0,0.3,0.1,0.03,0.01]\n    iterations = 100  # 500\n    #vector of # of iterations\n    iter_num = np.ones((iterations+1,1))\n    for i in range(0,iterations+1):\n        iter_num[i,0] = i\n    #plot of J(theta) vs # of iterations for alphas\n    plt.figure()\n    for alpha in alphas:\n        theta = np.zeros((n+1,1))  # initial guess for theta\n        theta, costHistory = gradientDescent(X,y,theta,alpha,iterations)\n        plt.plot(iter_num[:,0],costHistory[:,0])\n    plt.legend(['alpha=1.0', 'alpha=0.3', 'alpha=0.1', 'alpha=0.03', 'alpha=0.01'], loc='upper right')\n    plt.ylabel('cost function')\n    plt.xlabel('# of iterations')\n    plt.savefig(\"cost_vs_iter_vs_alpha.pdf\")\n    plt.show()\n    \n    #select alpha = 0.3 seens to converge at 50 iterations\n    alpha = 0.3\n    theta = np.zeros((n+1,1))  # initial guess for theta\n    theta, costHistory = gradientDescent(X,y,theta,alpha,iterations)\n    \n    # prediction for 1650 sq feet 3 bedroom house\n    test = np.array([[1650.0, 3.0]])\n    #normalize \n    test = (test-mu)/sigma\n    #add intercept\n    test = np.hstack((np.ones((1,1)),test))\n    predict = hypothesis(theta,test)\n    print(\"prediction for 1650 sq feet 3 bedroom house is\",predict)\n    \n    #normal equation\n    #do not need to normalize data\n    X, y = data[:,0:2], data[:,2:3]\n    X = np.hstack((np.ones((m,1)),X))  # add intercept column\n    theta = normalEquation(X,y)\n    # prediction for 1650 sq feet 3 bedroom house with added intercept\n    test = np.array([[1.0,1650.0, 3.0]])\n    predict = hypothesis(theta,test)\n    print(\"prediction from normal equation for 1650 sq feet 3 bedroom house is\",predict)\n    \n    #results: gradient descent:[[ 293081.47339913]], normal eq:[[ 293081.4643349]]\n    #if use 500 iterations: gradient descent:[[ 293081.4643349]] coincides with normal eq\n", "meta": {"hexsha": "31f52ff3128c8f192354fd02ec207d518499141e", "size": 3957, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ex1_LinearReg/ex1_multy.py", "max_stars_repo_name": "gpiatkovska/Machine-Learning-in-Python", "max_stars_repo_head_hexsha": "bbb754f9dce035e012fc77033b5ff747cba3273e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-08-16T07:00:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-16T07:00:52.000Z", "max_issues_repo_path": "Ex1_LinearReg/ex1_multy.py", "max_issues_repo_name": "gpiatkovska/Machine-Learning-in-Python", "max_issues_repo_head_hexsha": "bbb754f9dce035e012fc77033b5ff747cba3273e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ex1_LinearReg/ex1_multy.py", "max_forks_repo_name": "gpiatkovska/Machine-Learning-in-Python", "max_forks_repo_head_hexsha": "bbb754f9dce035e012fc77033b5ff747cba3273e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.656, "max_line_length": 102, "alphanum_fraction": 0.6315390447, "include": true, "reason": "import numpy", "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551525886193, "lm_q2_score": 0.9046505415276079, "lm_q1q2_score": 0.8728567362849973}}
{"text": "# Exercise 6: Scatterplot\n\n# generate list of numbers for height\ny = [5, 5.5, 5, 5.5, 6, 6.5, 6, 6.5, 7, 5.5, 5.25, 6, 5.25]\nprint(y)\n\n# create a list of numbers for weight\nx = [100, 150, 110, 140, 140, 170, 168, 165, 180, 125, 115, 155, 135]\nprint(x)\n\n# create histogram\nimport matplotlib.pyplot as plt\nplt.scatter(x, y) # generate scatterplot\nplt.xlabel('Weight') # label x-axis\nplt.ylabel('Height') # label y-axis\nplt.show() # print plot\n\n# calculate pearson correlations\nfrom scipy.stats import pearsonr\ncorrelation_coeff, p_value = pearsonr(x, y)\nprint(correlation_coeff)\n\n# Set up some logic\nif correlation_coeff == 1.00:\n    title = 'There is a perfect positive linear relationship (r = {0:0.2f}).'.format(correlation_coeff)\nelif correlation_coeff >= 0.8:\n    title = 'There is a very strong, positive linear relationship (r = {0:0.2f}).'.format(correlation_coeff)\nelif correlation_coeff >= 0.6:\n    title = 'There is a strong, positive linear relationship (r = {0:0.2f}).'.format(correlation_coeff)\nelif correlation_coeff >= 0.4:\n    title = 'There is a moderate, positive linear relationship (r = {0:0.2f}).'.format(correlation_coeff)\nelif correlation_coeff >= 0.2:\n    title = 'There is a weak, positive linear relationship (r = {0:0.2f}).'.format(correlation_coeff)\nelif correlation_coeff > 0:\n    title = 'There is a very weak, positive linear relationship (r = {0:0.2f}).'.format(correlation_coeff)\nelif correlation_coeff == 0:\n    title = 'There is no linear relationship (r = {0:0.2f}).'.format(correlation_coeff)\nelif correlation_coeff <= -0.8:\n    title = 'There is a very strong, negative linear relationship (r = {0:0.2f}).'.format(correlation_coeff)\nelif correlation_coeff <= -0.6:\n    title = 'There is a strong, negative linear relationship (r = {0:0.2f}).'.format(correlation_coeff)\nelif correlation_coeff <= -0.4:\n    title = 'There is a moderate, negative linear relationship (r = {0:0.2f}).'.format(correlation_coeff)\nelif correlation_coeff <= -0.2:\n    title = 'There is a weak, negative linear relationship (r = {0:0.2f}).'.format(correlation_coeff)\nelse: \n    title = 'There is a very weak, negative linear relationship (r = {0:0.2f}).'.format(correlation_coeff)\nprint(title)\n\n# Use title as title\nimport matplotlib.pyplot as plt\nplt.scatter(x, y) # generate scatterplot\nplt.xlabel('Weight') # label x-axis\nplt.ylabel('Height') # label y-axis\nplt.title(title) # set programmatic title\nplt.show() # print plot\n", "meta": {"hexsha": "0f8810965c1b66b29a6d4f2a594e1dcfd124920d", "size": 2438, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter02/Exercises/Exercise_18.py", "max_stars_repo_name": "talendteams/Data-Science-with-Python", "max_stars_repo_head_hexsha": "cd5e1bd30a886d8b4ae3e4835bf3c657c29a52a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2019-06-25T15:03:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T20:53:01.000Z", "max_issues_repo_path": "Chapter02/Exercises/Exercise_18.py", "max_issues_repo_name": "talendteams/Data-Science-with-Python", "max_issues_repo_head_hexsha": "cd5e1bd30a886d8b4ae3e4835bf3c657c29a52a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter02/Exercises/Exercise_18.py", "max_forks_repo_name": "talendteams/Data-Science-with-Python", "max_forks_repo_head_hexsha": "cd5e1bd30a886d8b4ae3e4835bf3c657c29a52a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 93, "max_forks_repo_forks_event_min_datetime": "2019-06-26T02:34:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T16:21:48.000Z", "avg_line_length": 42.7719298246, "max_line_length": 108, "alphanum_fraction": 0.7100082034, "include": true, "reason": "from scipy", "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715436, "lm_q2_score": 0.9136765151867664, "lm_q1q2_score": 0.8728526556651095}}
{"text": "# Weekly Code           #2\r\n# LQR                   Version 1.0.0       Date: 9/7/2019\r\n# solving a inverted pendulum using lqr ref. below the same using matlab\r\n# http://ctms.engin.umich.edu/CTMS/index.php?example=InvertedPendulum&section=SystemModeling\r\n# Future Improvements:  1) add visualization\r\n#                       2) animation and simulation\r\n#                       3) comparison with various Q and R values.\r\n\r\n\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import linalg\r\n\r\n\r\n\r\nM = 0.5\r\nm = 0.3\r\nb = 0.1\r\nI = 0.006\r\ng = 9.8\r\nl = 0.3\r\n\r\np = I*(M+m) + M*m*l**2\r\n# state space representation\r\nA = np.array([[0, 1, 0, 0],\r\n              [0, -(I+m*l**2)*b/p, (m**2*g*l**2)/p, 0],\r\n              [0, 0, 0, 1],\r\n              [0, -(m*l*b)/p, m*g*l*(M+m)/p, 0]])\r\nB = np.array([[0],\r\n     [(I+m*l**2)/p],\r\n     [0],\r\n     [m*l/p]])\r\nC = np.array([[1, 0, 0, 0],\r\n     [0, 0, 1, 0]])\r\nD = np.array([[0],\r\n     [0]])\r\nA_size = A.size/2\r\n# print(\"The poles of A are: \")\r\nprint(A)\r\n# [w, v] = np.linalg.eig(A)\r\n# print(w)\r\n# We see that the system is unstable, which is expected.\r\n# We check for controllability\r\nAB = np.matmul(A, B)\r\nA2B = np.matmul(A, AB)\r\nA3B = np.matmul(A, A2B)\r\nA4B = np.matmul(A, A3B)\r\n\r\n# forming the controllability matrix\r\nco = np.zeros((4, 4), float)\r\n# filling the controllability matrix\r\nfor i in range(4):\r\n    co[i, 0] = B[i]\r\n    co[i, 1] = AB[i]\r\n    co[i, 2] = A2B[i]\r\n    co[i, 3] = A3B[i]\r\n# print(co)\r\nprint(\" The rank of ctrb = {}\".format(np.linalg.matrix_rank(co)))\r\n# we see system is controllable\r\n\r\n# we select the R and Q matrices as follows\r\nQ = np.matmul(C.T, C)\r\nR = np.array([[1]])\r\n\r\n# now we solve the countinous time ricatti equation\r\nX = np.array(linalg.solve_continuous_are(A, B, Q, R))\r\nprint(X)\r\n# computing the LQR Gain\r\nK = np.linalg.inv(R)@(B.T@X)\r\nprint(\"K = {}\".format(K))\r\n# computing eigen values\r\n[w, v] = np.linalg.eig(A-B@K)\r\nprint(\"The eigen values of the closed loop systems are \\n {}\".format(w))\r\n# We see that all eigen value are in LHP\r\n# we check from MATLAB the answer we recieve matches.\r\n", "meta": {"hexsha": "de2b466ca171e4fbb5129924aa909b68b3217ee5", "size": 2084, "ext": "py", "lang": "Python", "max_stars_repo_path": "lqr_1.py", "max_stars_repo_name": "manav20/r-theta-manipulator", "max_stars_repo_head_hexsha": "ebcafac9edd4c1b211bde0a9b6e3eb29af1b9c73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-08T13:36:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T09:10:26.000Z", "max_issues_repo_path": "lqr_1.py", "max_issues_repo_name": "manav20/r-theta-manipulator", "max_issues_repo_head_hexsha": "ebcafac9edd4c1b211bde0a9b6e3eb29af1b9c73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lqr_1.py", "max_forks_repo_name": "manav20/r-theta-manipulator", "max_forks_repo_head_hexsha": "ebcafac9edd4c1b211bde0a9b6e3eb29af1b9c73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0649350649, "max_line_length": 93, "alphanum_fraction": 0.5690978887, "include": true, "reason": "import numpy,from scipy", "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122768904645, "lm_q2_score": 0.9111797172476384, "lm_q1q2_score": 0.8728302376050949}}
{"text": "from statistics import mean\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom matplotlib import style\r\nimport random\r\n\r\nstyle.use('fivethirtyeight')\r\n\r\ndef slope_of_reg(x_val: np.array, y_val: np.array):\r\n    assert isinstance(x_val, np.ndarray)\r\n    assert isinstance(y_val, np.ndarray)\r\n    num = (mean(x_val) * mean(y_val)) - (mean(x_val * y_val))\r\n    dem =( mean(x_val)**2) - (mean(x_val **2))\r\n    m = num/dem\r\n    b = mean(y_val) - m * mean(x_val)\r\n    return m, b\r\n\r\ndef squared_error(y_orig, y_hat):\r\n    return np.sum((y_orig - y_hat)**2)\r\n\r\ndef R_squared(y_orig, y_hat):\r\n    y_mean = [mean(y_orig) for y in y_orig]\r\n    squared_error_reg = squared_error(y_orig, y_hat)\r\n    squared_error_mean = squared_error(y_orig, y_mean)\r\n    r_squared = 1 - (squared_error_reg/ squared_error_mean)\r\n    return r_squared\r\n\r\ndef create_dataset(n_points, variance, step, correlation=False):\r\n    val = 1\r\n    ys = []\r\n    for i in range(n_points):\r\n        y = val + random.randrange(-variance, variance)\r\n        ys.append(y)\r\n        if correlation and correlation == 'pos':\r\n            val += step\r\n        elif correlation and correlation == 'neg':\r\n            val -= step\r\n    xs = [i for i in range(len(ys))]\r\n    x = np.array(xs)\r\n    y = np.array(ys)\r\n    return x, y\r\n\r\n\r\nx, y = create_dataset(40, 80, 2, 'neg')\r\n\r\nm, b = slope_of_reg(x, y)\r\nreg_line = [(m * x) + b for x in x]\r\nr = R_squared(y, reg_line)\r\nprint(r)\r\n\r\nplt.plot(x, y, 'o')\r\nplt.plot(x, reg_line)\r\nplt.show()", "meta": {"hexsha": "e1e786aa07d9ee8c04ba1a4f588ee612e28c8a7c", "size": 1495, "ext": "py", "lang": "Python", "max_stars_repo_path": "ML/From_Scratch/Regression_sc.py", "max_stars_repo_name": "task-master98/AI_dev", "max_stars_repo_head_hexsha": "da5b217e6c6d9ed9077e2bf3394f34403e91ab9f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ML/From_Scratch/Regression_sc.py", "max_issues_repo_name": "task-master98/AI_dev", "max_issues_repo_head_hexsha": "da5b217e6c6d9ed9077e2bf3394f34403e91ab9f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ML/From_Scratch/Regression_sc.py", "max_forks_repo_name": "task-master98/AI_dev", "max_forks_repo_head_hexsha": "da5b217e6c6d9ed9077e2bf3394f34403e91ab9f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2075471698, "max_line_length": 65, "alphanum_fraction": 0.620735786, "include": true, "reason": "import numpy", "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9770226314280634, "lm_q2_score": 0.8933094103149355, "lm_q1q2_score": 0.8727835107453499}}
{"text": "import numpy as np\nimport pandas as pd\n\ndef amortization(per, rate, pv,\n    date=pd.to_datetime('today').strftime(\"%Y/%m/%d\"), add=0, sf=False):\n    '''\n    Returns two tables: monthly changes and summary over entire duration\n    of loan.\n\n    Parameters\n    ----------\n    per: scalar\n        Number of total months.\n    rate: scalar\n        Percent annual interest rate.\n    pv: scalar\n        Principal amount loaned.\n    date: string, optional\n        Date entered as 'YYYYMMDD'.\n    add: scalar, optional\n        Additional payment towards principal given each month.\n\n    Returns\n    -------\n    (df, sm) : (DataFrame, Series)\n        df is a DataFrame with monthly breakdown of payments. sm is a Series\n        table of summary of monthly over entire time of loan.\n\n    Examples\n    --------\n    >>> import brindle as bd\n    >>> import pandas as pd\n    >>> df, sm = bd.amortization(72, 2.99, 35000, add=50)\n    >>> pd.concat([df.head(2), df.tail(2)])\n                 Date  Payment  Principal  Interest  Extra   Balance\n        N\n        0  2018-11-01     0.00       0.00      0.00      0  35000.00\n        1  2018-12-01   581.62     492.74     88.88     50  34507.26\n        65 2024-04-01   581.62     579.79      1.83     50    163.50\n        66 2024-05-01   163.92     163.50      0.42     50      0.00\n\n    >>> sm\n        Payoff      2024-05-01 00:00:00\n        Months                       66\n        Rate                       2.99\n        Payment                  531.62\n        Extra                        50\n        Interest                2969.22\n        dtype: object\n\n    >>> df1, sm1 = bd.amortization(72, 4.99, 22000, '20181026')\n    >>> df2, sm2 = bd.amortization(72, 4.99, 22000, '20181026', add=100)\n    >>> df3, sm3 = bd.amortization(72, 3.99, 22000, '20181026')\n    >>> df4, sm4 = bd.amortization(72, 3.99, 22000, '20181026', add=50)\n    >>> pd.DataFrame([sm, sm1, sm2, sm3])\n              Payoff  Months  Rate  Payment  Extra  Interest\n        0 2024-10-01      71  4.99   354.21      0   3504.11\n        1 2023-06-01      55  4.99   354.21    100   2619.74\n        2 2024-10-01      71  3.99   344.09      0   2775.79\n        3 2024-01-01      62  3.99   344.09     50   2378.05\n    '''\n    # Generator to fill up DataFrame details.\n    def calc(per, dates, pv, rate, pay, add, days):\n        for i, (dt, dy) in enumerate(zip(dates, days)):\n            if i == 0:\n                yield dt, 0, 0, 0, 0, pv\n            else:\n                interest = round(pv * rate * dy / 100 / 365, 2)\n                pr = min(pv, pay + add - interest)\n                pv -= pr\n                yield dt, pr + interest, pr, interest, add, pv\n            if pv <= 0: break\n\n    # Create time series DataFrame table of loan details.\n    dates = pd.date_range(date, periods=per+1, freq='MS')\n    days = np.array(np.array(np.diff(dates), dtype='timedelta64[D]'), dtype=int)\n    pay = round(-np.pmt(rate / 100 / 12, per, pv), 2)\n    cols = ['Date', 'Payment', 'Principal', 'Interest', 'Extra', 'Balance']\n    df = pd.DataFrame(list(calc(per, dates, pv, rate, pay, add, days)),\n        columns=cols)\n    df.index.name = 'N'\n\n    # Create summary table of loan details.\n    index = ['Payoff', 'Months', 'Rate', 'Payment', 'Extra', 'Interest']\n    sm = pd.Series([df['Date'].iloc[-1], len(df) - 1, rate, pay, add,\n        np.sum(df['Interest'])], index=index)\n    return df, sm\n", "meta": {"hexsha": "2bf9b8deadb74b0aec7dd9e5889cc5d64d11bca9", "size": 3383, "ext": "py", "lang": "Python", "max_stars_repo_path": "finances.py", "max_stars_repo_name": "davidjaimes/brindle", "max_stars_repo_head_hexsha": "8edcca7eb6457eb5370c76c1f12feb66d25a5cd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "finances.py", "max_issues_repo_name": "davidjaimes/brindle", "max_issues_repo_head_hexsha": "8edcca7eb6457eb5370c76c1f12feb66d25a5cd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "finances.py", "max_forks_repo_name": "davidjaimes/brindle", "max_forks_repo_head_hexsha": "8edcca7eb6457eb5370c76c1f12feb66d25a5cd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4431818182, "max_line_length": 80, "alphanum_fraction": 0.5273425953, "include": true, "reason": "import numpy", "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877684006775, "lm_q2_score": 0.8991213813246444, "lm_q1q2_score": 0.8727661271593536}}
{"text": "import json\nimport numpy as np\nfrom scipy.optimize import minimize\n\ndef sigmoid(z):\n    return 1 / (1 + np.exp(-z))\n\ndef cost(theta, X, y, lmbda):\n    theta = np.matrix(theta)\n    X = np.matrix(X)\n    y = np.matrix(y)\n    first = np.multiply(-y, np.log(sigmoid(X * theta.T)))\n    second = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))\n    reg = lmbda * np.sum(np.power(theta[:,1:theta.shape[1]], 2))\n    return (np.sum(first - second) + reg) / (2 * len(X))\n\ndef gradient(theta, X, y, lmbda):\n    theta = np.matrix(theta)\n    X = np.matrix(X)\n    y = np.matrix(y)\n\n    parameters = int(theta.ravel().shape[1])\n    error = sigmoid(X * theta.T) - y\n    grad = ((X.T * error) / len(X)).T + ((lmbda / len(X)) * theta)\n\n    # intercept gradient is not regularized\n    grad[0, 0] = np.sum(np.multiply(error, X[:,0])) / len(X)\n\n    return np.array(grad).ravel()\n\ndef one_vs_all(X, y, num_labels, lmbda):\n    rows = X.shape[0]\n    params = X.shape[1]\n    \n    all_theta = np.zeros((num_labels, params + 1)) \n    X = np.insert(X, 0, values=np.ones(rows), axis=1)\n\n    for i in range(1, num_labels + 1): \n        theta = np.zeros(params + 1)\n        y_i = np.array([1 if label == i else 0 for label in y]) \n        y_i = np.reshape(y_i, (rows, 1)) \n        fmin = minimize(fun=cost, x0=theta, args=(X, y_i, lmbda), method='TNC', jac=gradient)\n        all_theta[i-1,:] = fmin.x\n    \n    return all_theta\n\ndef predict_all(X, all_theta):\n    rows = X.shape[0]\n    params = X.shape[1]\n    num_labels = all_theta.shape[0]\n\n    X = np.insert(X, 0, values=np.ones(rows), axis=1)\n\n    X = np.matrix(X)\n    all_theta = np.matrix(all_theta)\n\n    h = sigmoid(X * all_theta.T)\n\n    scores = [ {\"like\": score.item(0,0), \"dislike\": score.item(0,1)} for score in h]\n    return scores\n\ndef train_and_predict(trainer, tuning_params):\n    num_classifications = 2\n\n    for lmbda in tuning_params:\n        print \"\\ncalculating theta for lambda param: {}\".format(lmbda)\n        all_theta = one_vs_all(trainer.X_train, trainer.Y, num_classifications, lmbda)\n        trainer.timer.interval('Calculated theta')\n\n        print \"predicting\"\n        hypothesis = predict_all(trainer.X_test, all_theta)\n        trainer.timer.interval('Made prediction')\n        trainer.store_predict(hypothesis, lmbda)\n          \n\n", "meta": {"hexsha": "7d813076585aecd6a61b274dbbb01b48fd8e61ab", "size": 2284, "ext": "py", "lang": "Python", "max_stars_repo_path": "movie_rec/lib/logistic_regression.py", "max_stars_repo_name": "yujinjcho/movie_recommendations", "max_stars_repo_head_hexsha": "89032ba95efc716460a83e0ca54e2c5e833b8d47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "movie_rec/lib/logistic_regression.py", "max_issues_repo_name": "yujinjcho/movie_recommendations", "max_issues_repo_head_hexsha": "89032ba95efc716460a83e0ca54e2c5e833b8d47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2017-04-13T06:16:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T03:38:59.000Z", "max_forks_repo_path": "movie_rec/lib/logistic_regression.py", "max_forks_repo_name": "yujinjcho/movie_recommendations", "max_forks_repo_head_hexsha": "89032ba95efc716460a83e0ca54e2c5e833b8d47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0526315789, "max_line_length": 93, "alphanum_fraction": 0.6090192644, "include": true, "reason": "import numpy,from scipy", "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576265, "lm_q2_score": 0.9099070145888367, "lm_q1q2_score": 0.8727412122288564}}
{"text": "#ヒルベルト行列のcondition numberを求める\n\nimport scipy.linalg as linalg\nimport numpy as np\nfrom numpy import linalg as LA\n\ndef calc_hilbert_condition(n):\n    A = np.zeros((n,n))\n    for i in range(n):\n        for j in range(n):\n            A[i][j] = 1/(i+j+1)\n    print(\"matrix size =\", n)\n    print(\"condition number is\", LA.cond(A, 2))\nif __name__ == \"__main__\":\n    calc_hilbert_condition(3)\n    calc_hilbert_condition(6)\n    calc_hilbert_condition(9)\n", "meta": {"hexsha": "47e64602e38677700cc58c1386b798ee9b042d73", "size": 444, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numerical_Analysis/report/5/3.py", "max_stars_repo_name": "yoshi-ki/BACHELOR", "max_stars_repo_head_hexsha": "65d01c62ab2ea4a6d2616a6b6c535bd4f1645630", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numerical_Analysis/report/5/3.py", "max_issues_repo_name": "yoshi-ki/BACHELOR", "max_issues_repo_head_hexsha": "65d01c62ab2ea4a6d2616a6b6c535bd4f1645630", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numerical_Analysis/report/5/3.py", "max_forks_repo_name": "yoshi-ki/BACHELOR", "max_forks_repo_head_hexsha": "65d01c62ab2ea4a6d2616a6b6c535bd4f1645630", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6666666667, "max_line_length": 47, "alphanum_fraction": 0.6576576577, "include": true, "reason": "import numpy,from numpy,import scipy", "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542875927781, "lm_q2_score": 0.909907002984195, "lm_q1q2_score": 0.8727412032229854}}
{"text": "import numpy as np\nimport math\n\ndef sum__(x, f=lambda x: x):\n\tacc = 0.\n\tfor item in x:\n\t\tacc += f(item) \n\treturn acc\ndef mean(x):\n\tn = x.shape[0]\n\tacc = 0.\n\tfor item in x:\n\t\tacc += item\n\treturn acc/n\n\ndef\tvariance(x):\n\tu = mean(x)\n\treturn sum__(x,lambda x: (x - u)**2) / x.shape[0]\n\ndef std(x):\n\treturn math.sqrt(variance(x))\n\ndef dot(x, y):\n\tif (x is None or y is None\n\tor x.shape[0] != y.shape[0]):\n\t\treturn None\n\treturn sum__(x * y, lambda x:x)\n\ndef mat_vec_prod(x, y):\n\tif (x.shape[1], 1) != y.shape:\n\t\treturn None\n\tres = np.zeros((x.shape[0],1))\n\tf = 0\n\tfor row in x:\n\t\trow = row.reshape((row.shape[0],1))\n\t\tres[f] = dot(row, y)\n\t\tf += 1\n\treturn res\n\t\ndef mat_mat_prod(x, y):\n\tif (x.shape[0] != y.shape[1]):\n\t\treturn None\n\tres = np.zeros((x.shape[0],y.shape[1]))\n\tprint(x.shape,\" \",y.shape)\n\tfor i in range(x.shape[0]):\n\t\tfor j in range(y.shape[1]):\n\t\t\tres[i][j] = dot(x[i],y[:,j])\n\treturn res\n\ndef mse(y, y_hat):\n\tif y.shape != y_hat.shape:\n\t\treturn None\n\t#return sum__(y_hat - y,lambda x: x**2)\n\tacc = 0.\n\tfor elem1,elem2 in zip(y,y_hat):\n\t\tacc += (elem1 - elem2)**2\n\treturn acc / y.shape[0]\n\ndef vec_mse(y, y_hat):\n\ty = y.reshape((y.shape[0],1))\n\ty_hat = y_hat.reshape((y_hat.shape[0],1))\n\t# print(y.shape)\n\treturn float(dot(y_hat - y,y_hat - y) / y_hat.shape[0])\n\ndef reshape(x):\n\tx = x.reshape(x.shape[0], 1)\n\treturn x\ndef linear_mse(x, y, theta):\n\ttheta = reshape(theta)\n\ty = reshape(y)\n\thypothes = mat_vec_prod(x,theta)\n\treturn float(mse(hypothes, y))\n\n\ndef\tvec_linear_mse(x, y, theta):\n\ty = reshape(y)\n\ttheta = reshape(theta)\n\thypothes = mat_vec_prod(x, theta)\n\treturn float(dot(hypothes - y,hypothes - y) / x.shape[0])\n# print(vec_linear_mse(X, Y, W))\n\n\n# def\tgradient(x, y, theta):\n# \ty = reshape(y)\n# \ttheta = reshape(theta)\n# \thypothes = mat_vec_prod(x, theta)\n# \t# scalar = float(sum__(hypothes - y) / x.shape[0])\n# \tgrad =  np.zeros(theta.shape)\n# \tfor j in range(theta.shape[0]):\n# \t\tfor i in range(x.shape[0]):\n# \t\t\tgrad[j] = sum__((hypothes[i] - y[i]) * x[i])\n# \treturn grad\n\n\n\ndef vec_gradient(x, y, theta):\n\ty = reshape(y)\n\ttheta = reshape(theta)\n\treturn dot(x, mat_vec_prod(x, theta) - y) / x.shape[0]\n\n\n# print(gradient(X, Y, Z))\n# print(vec_gradient(X, Y, Z))", "meta": {"hexsha": "13160e5f908d7e04a60017de4ec3e8671c2967d0", "size": 2186, "ext": "py", "lang": "Python", "max_stars_repo_path": "day02/func.py", "max_stars_repo_name": "elbourki1/Machine-Learning-bootcamp-42", "max_stars_repo_head_hexsha": "cf6a987ede555d8d208aed5b915cafe8078dd848", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day02/func.py", "max_issues_repo_name": "elbourki1/Machine-Learning-bootcamp-42", "max_issues_repo_head_hexsha": "cf6a987ede555d8d208aed5b915cafe8078dd848", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day02/func.py", "max_forks_repo_name": "elbourki1/Machine-Learning-bootcamp-42", "max_forks_repo_head_hexsha": "cf6a987ede555d8d208aed5b915cafe8078dd848", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2233009709, "max_line_length": 58, "alphanum_fraction": 0.615736505, "include": true, "reason": "import numpy", "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542887603537, "lm_q2_score": 0.9099069962657176, "lm_q1q2_score": 0.8727411978413141}}
{"text": "import math\nimport numpy as np\nimport scipy.io\nimport matplotlib.pyplot as plt\n\n# Load yalefaces.mat data\nM = scipy.io.loadmat('yalefaces.mat')[\"M\"]\n\n# Flatten each 2x2 matrix to a col vector and find the mean\nM_flattened = np.zeros((1024, 2414))\nsum = np.zeros((1024, 1))\nfor i in range(2414):\n    M_flattened[:, i] = np.reshape(M[:, :, i], (1, 1024))\n    # Sum x vectors to find mean\n    for j in range(1024):\n        sum[j] += M_flattened[j, i]\n\nx_mean = sum / 2414\n\n# Create X with all 2414 centred image vectors\nX = np.zeros((1024, 2414))\nfor i in range(1024):\n    for j in range(2414):\n        X[i][j] = M_flattened[i][j] - x_mean[i]\n\nC = X.dot(np.transpose(X))\n\n# Compute eigenvector/eigenvalue pairs for C\neigenvalues, eigenvectors = np.linalg.eig(C)\n\n# Sort the eigenvalues\nidx = eigenvalues.argsort()[::-1]\neigenvalues = eigenvalues[idx]\neigenvectors = eigenvectors[:,idx]\n\n# Plot log(eigenvalues) over j\nj = range(1, 1025)\nlog_eigenvalues = np.log10(eigenvalues)\nplt.plot(j, log_eigenvalues)\nplt.title('log(eigenvalues)')\nplt.xlabel('j')\nplt.ylabel('log(eigenvalues)')\n\n# Reshape eigenvectors to get eigenfaces\neigenfaces = np.zeros((32, 32, 1024))\nfor i in range(1024):\n    eigenfaces[:, :, i] = np.reshape(eigenvectors[:, i], (32, 32))\n\n# Plot eigenfaces of largest 10 eigenvalues\nfig_highest_eigenvalues, (f1, f2, f3, f4, f5, f6, f7, f8, f9, f10) = plt.subplots(1, 10)\nf1.imshow(eigenfaces[:,:,0])\nf2.imshow(eigenfaces[:,:,1])\nf3.imshow(eigenfaces[:,:,2])\nf4.imshow(eigenfaces[:,:,3])\nf5.imshow(eigenfaces[:,:,4])\nf6.imshow(eigenfaces[:,:,5])\nf7.imshow(eigenfaces[:,:,6])\nf8.imshow(eigenfaces[:,:,7])\nf9.imshow(eigenfaces[:,:,8])\nf10.imshow(eigenfaces[:,:,9])\n\n# Plot eigenfaces of smallest 10 eigenvalues\nfig_lowest_eigenvalues, (f11, f12, f13, f14, f15, f16, f17, f18, f19, f20) = plt.subplots(1, 10)\nf11.imshow(eigenfaces[:,:,1014])\nf12.imshow(eigenfaces[:,:,1015])\nf13.imshow(eigenfaces[:,:,1016])\nf14.imshow(eigenfaces[:,:,1017])\nf15.imshow(eigenfaces[:,:,1018])\nf16.imshow(eigenfaces[:,:,1019])\nf17.imshow(eigenfaces[:,:,1020])\nf18.imshow(eigenfaces[:,:,1021])\nf19.imshow(eigenfaces[:,:,1022])\nf20.imshow(eigenfaces[:,:,1023])\n\n\n# Function that returns projection of vector onto subspace of B(j)\ndef projection_onto_B(x_mean, j):\n    alpha = np.zeros((j, 1))\n    proj = np.zeros((1024, 1))\n    for i in range(j):\n        # Add projection of vector onto jth vector in subspace\n        alpha[i, 0] = (np.inner(x_mean, eigenvectors[:, i])/np.inner(eigenvectors[:, i], eigenvectors[:, i]))\n        eigenvector = eigenvectors[:, i]\n        # Add projection component\n        for k in range(1024):\n            proj[k] = proj[k] + (alpha[i, 0] * eigenvector)[k]\n    return alpha, proj\n\n\nj_values = [2, 2**2, 2**3, 2**4, 2**5, 2**6, 2**7, 2**8, 2**9, 2**10]\n\n# Project image J(1) onto B\ny = np.zeros((1024, 10))\nfig_y = plt.figure(4)\n# Loop through j values\nfor i in range(10):\n    # Project X[:, 0] onto subspace v(1) to v(j) to get y_mean(i, j)\n    projection = projection_onto_B(X[:, 0], j_values[i])[1]\n    for j in range(1024):\n        y[j, i] = projection[j]\n    # Add x_mean vector to y_mean(i,j) to get y(i,j)\n    for j in range(1024):\n        y[j, i] += x_mean[j]\n\n    # Reshape y and plot\n    y_plot = np.reshape(y[:, i], (32, 32))\n    plot = fig_y.add_subplot(3, 10, i + 1)\n    plot.imshow(y_plot)\n\n# Project image J(1076) onto B\nfor i in range(10):\n    # Project X[:, 1075] onto subspace v(1) to v(j) to get y_mean(i, j)\n    projection = projection_onto_B(X[:, 1075], j_values[i])[1]\n    for j in range(1024):\n        y[j, i] = projection[j]\n    # Add x_mean vector to y_mean(i,j) to get y(i,j)\n    for j in range(1024):\n        y[j, i] += x_mean[j]\n\n    # Reshape y and plot\n    y_plot = np.reshape(y[:, i], (32, 32))\n    plot = fig_y.add_subplot(3, 10, i + 11)\n    plot.imshow(y_plot)\n\n# Project image J(2043) onto B\nfor i in range(10):\n    # Project X[:, 2042] onto subspace v(1) to v(j) to get y_mean(i, j)\n    projection = projection_onto_B(X[:, 2042], j_values[i])[1]\n    for j in range(1024):\n        y[j, i] = projection[j]\n    # Add x_mean vector to y_mean(i,j) to get y(i,j)\n    for j in range(1024):\n        y[j, i] += x_mean[j]\n\n    # Reshape y and plot\n    y_plot = np.reshape(y[:, i], (32, 32))\n    plot = fig_y.add_subplot(3, 10, i + 21)\n    plot.imshow(y_plot)\n\n\n# Project images in set I onto B(25)\nimage_set = [0, 1, 6, 2042, 2043, 2044]\ncoeffs = np.zeros((25, 6))\nfor i in range(6):\n    alphas = projection_onto_B(X[:, image_set[i]], 25)[0]\n    # Store alpha values into coeffs\n    for j in range(25):\n        coeffs[j, i] = alphas[j, 0]\n\n# Tabulate Euclidean distances between the pairwise c(i) vectors\ndistances = np.zeros((6, 6))\nfor i in range(6):\n    for j in range(i + 1, 6):\n        x = coeffs[:, i]\n        y = coeffs[:, j]\n        distances[i, j] = np.linalg.norm(x - y)\n\nplt.show()\nprint(\"Done!\")\n", "meta": {"hexsha": "c2217b5bed53ac42304f1a257406698780d29463", "size": 4850, "ext": "py", "lang": "Python", "max_stars_repo_path": "ps3/eigenfaces.py", "max_stars_repo_name": "cuijulian/ece367_labs", "max_stars_repo_head_hexsha": "7b91aac5a3fa441a229326e20e9ff7313bf692fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ps3/eigenfaces.py", "max_issues_repo_name": "cuijulian/ece367_labs", "max_issues_repo_head_hexsha": "7b91aac5a3fa441a229326e20e9ff7313bf692fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ps3/eigenfaces.py", "max_forks_repo_name": "cuijulian/ece367_labs", "max_forks_repo_head_hexsha": "7b91aac5a3fa441a229326e20e9ff7313bf692fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3125, "max_line_length": 109, "alphanum_fraction": 0.6290721649, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.98028087477309, "lm_q2_score": 0.8902942159342104, "lm_q1q2_score": 0.8727383928014101}}
{"text": "import numpy as np\nimport seaborn as sns\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nmpl.rcParams[\"figure.dpi\"] = 100\nmpl.rcParams[\"text.usetex\"] = True\nmpl.rc(\"font\", **{\"family\": \"sans-serif\"})\nparams = {\"text.latex.preamble\": r\"\\usepackage{amsmath}\"}\nplt.rcParams.update(params)\n\nsns.set_theme()\n\n# Q7\n# Multivariate Normal Distribution\n\npoints = 100000\nmu = np.zeros(2)\n\nmv_normal = (\n    lambda cov: np.random.default_rng().multivariate_normal(mu, cov, points).T\n)\n\n\ndef title(part, cov, mj=None, mn=None):\n    t = (f\"Part {part} | Covariance=$\\\\begin{{array}}{{cc}} {cov[0][0]}\"\n        f\" & {cov[0][1]} \\\\\\\\ {cov[1][0]} & {cov[1][1]} \\\\end{{array}}$\\n\")\n\n    if mj is not None and mn is not None:\n        t += f\" Minor Axis: {2*mn:.3},\\nMajor Axis: {2*mj:.3}\"\n    return t\n\n\n# Part A/B\n\nfig, ax = plt.subplots(\n    nrows=3, ncols=2, figsize=(10, 20), sharex=True, sharey=True\n)\n\nfor c in range(1, 4):\n    cov = c * np.identity(2)\n    x, y = mv_normal(cov)\n    mn, mj = max(abs(x)), max(abs(y))\n    ax[c - 1, 0].scatter(x, y)\n    ax[c - 1, 0].set_title(title(\"A\", cov, mn=mn, mj=mj), x=1.5, y=0.5)\n\nfor c in range(1, 4):\n    cov = c * np.diagflat([1, 2])\n    x, y = mv_normal(cov)\n    mn, mj = max(abs(x)), max(abs(y))\n    s = ax[c - 1, 1].scatter(x, y)\n    ax[c - 1, 1].set_title(title(\"B\", cov, mn=mn, mj=mj), x=1.5, y=0.5)\n\nfor ax_ in ax.flatten():\n    ax_.set_aspect(\"equal\")\n    ax_.set_xticks([])\n    ax_.set_yticks([])\n\nfig.tight_layout()\nplt.show()\nplt.close()\n\n\"\"\"\nAs value of covariance matrix increases the radius of the circle/ellipse formed\n    appears to be increasing.\n\nIn part A and part B, since the Σ matrix is a diagonal matrix.\n\nThe diagonal matrix's elements on main diagonal would specify the \"variance\"\n    in the x and y direction.\n\nWe can see this is a perfectly symmetric curve in all the dimensions (also seen in the plots above).\n\"\"\"\n\n# Part C\n\ncov = lambda a: np.array([[15, a], [a, 15]])\n\nl = [1, 5, 8, 10, 14]\n\nfig, ax = plt.subplots(\n    nrows=len(l), ncols=2, figsize=(10, 5 * len(l)), sharex=True, sharey=True\n)\n\nfor index, a in enumerate(l):\n    mat = cov(a), cov(-a)\n    x, y = mv_normal(mat[0])\n    ax[index, 0].scatter(x, y)\n    ax[index, 0].set_title(title(\"C\", mat[0]), x=1.7, y=0.5)\n\n    x, y = mv_normal(mat[1])\n    ax[index, 1].scatter(x, y)\n    ax[index, 1].set_title(title(\"C\", mat[1]), x=1.7, y=0.5)\n\nfor ax_ in ax.flatten():\n    ax_.set_aspect(\"equal\")\n    ax_.set_xticks([])\n    ax_.set_yticks([])\n\nfig.tight_layout()\nplt.show()\nplt.close()\n\n\"\"\"\nHere mean is still zero, although now covariance is a symmetric matrix.\n\nWe can see as magnitude of off diagonal elements increase the points\nstart to scatter in a rotated direction, and along that direction lies there maximum variance.\n\nFor negative elements, the direction is also opposite (as correlation will be negative).\n\nThis will also hold true for more dimensions.\n\nThis property of variance & direction of ellipse made by\nmultivariate normal distribution does not appear to be\nfor other distribution, although for a large number of\nsamples distributions will approximate to be like normal distribution\n(due to CLT) hence it is applicable there.\n\n\"\"\"\n", "meta": {"hexsha": "8a5befed675d530ff804b65502d7001b3a36200a", "size": 3174, "ext": "py", "lang": "Python", "max_stars_repo_path": "q7.py", "max_stars_repo_name": "gajrajgchouhan/Statistical-Simulation-Project", "max_stars_repo_head_hexsha": "c819dd7ee3fa607b5ebf38756cb2e2cd2bb3e038", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "q7.py", "max_issues_repo_name": "gajrajgchouhan/Statistical-Simulation-Project", "max_issues_repo_head_hexsha": "c819dd7ee3fa607b5ebf38756cb2e2cd2bb3e038", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "q7.py", "max_forks_repo_name": "gajrajgchouhan/Statistical-Simulation-Project", "max_forks_repo_head_hexsha": "c819dd7ee3fa607b5ebf38756cb2e2cd2bb3e038", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2314049587, "max_line_length": 100, "alphanum_fraction": 0.6509136736, "include": true, "reason": "import numpy", "num_tokens": 971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966656805269, "lm_q2_score": 0.9219218348550491, "lm_q1q2_score": 0.8726881348918628}}
{"text": "\"\"\"\"\nThe goal of this module is to implement all algorithms and numerical\nmethods needed to solve the Task 1 from the coding homeworks in the\nMachine Learning course on coursera.com.\n\"\"\"\nfrom typing import Tuple\n\nimport numpy as np\n\n\ndef hypothesis_function(x: np.ndarray, theta: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Calculate the hypothesis function. The hypothesis function is the linear regression function.\n\n    Args:\n      x:\n        Input dataset. A matrix with m rows and n columns.\n      theta:\n        The parameters for the regression function. An n+1-element vector.\n\n    Returns:\n        A dot product of matrix x and vector theta.\n    \"\"\"\n    return np.dot(x, theta)\n\n\ndef compute_cost(x: np.ndarray, y: np.ndarray, theta: np.ndarray = None) -> np.float64:\n    \"\"\"\n    Computes the cost of using theta as the parameter for linear regression to fit the data points in x and y.\n    The cost function is the sum of the squares of the differences between the predicted and actual values.\n    The cost function is minimized by gradient descent.\n\n    Args:\n      x:\n        Input dataset. A matrix with m rows and n columns.\n      y:\n        The values corresponding to the input dataset. An m-element vector.\n      theta:\n        The parameters for the regression function. An n+1-element vector.\n\n    Returns:\n        The cost of using theta as the parameter for linear regression to fit the data points in x and y.\n    \"\"\"\n    if theta is None:\n        theta = np.zeros((x.shape[1], 1))\n\n    m = y.size\n    a = (hypothesis_function(x, theta) - y).T\n    b = hypothesis_function(x, theta) - y\n    j = (1.0 / (2 * m) * np.dot(a, b))[0][0]\n    return j\n\n\ndef gradient_descent(\n    x: np.ndarray,\n    y: np.ndarray,\n    theta: np.ndarray = None,\n    num_iter: int = 2000,\n    alpha: float = 0.01,\n) -> Tuple[list, list]:\n    \"\"\"\n    Performs gradient descent to learn theta. The function returns the theta and the cost history. \n    Theta is a vector of parameters for the regression function. The cost history is a list of the \n    cost values at each iteration.  The function will not return anything if the number of iterations \n    is less than 1. The function will not return anything if the learning rate is less than 0. \n\n    Args:\n      x:\n        Input dataset. A matrix with m rows and n columns.\n      y:\n        The values corresponding to the input dataset. An m-element vector.\n      theta:\n        The parameters for the regression function. An n+1-element vector.\n      num_iter:\n        The number of steps in gradient descent algorithm.\n      alpha:\n        The learning rate.\n\n    Returns:\n      A tuple consisting of:\n      - A list of theta values after each iteration.\n      - A list of the cost function values after each iteration.\n    \"\"\"\n    if theta is None:\n        theta = np.zeros((x.shape[1], 1))\n\n    initial_theta = theta\n    m = y.size\n    costs = []\n    theta_history = []\n\n    for _ in range(num_iter):\n        costs.append(compute_cost(x, y, theta))\n        theta_history.append(list(theta[:, 0]))\n\n        for i in range(len(theta)):\n            theta[i] -= (alpha / m) * np.sum(\n                (hypothesis_function(x, initial_theta) - y)\n                * np.array(x[:, i]).reshape(m, 1)\n            )\n\n    return theta_history, costs\n\n\ndef normalize_features(x: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n    \"\"\"\n    A preprocessing step that is typically performed when dealing with learning algorithms.\n    The features are normalized by substracting the mean and dividing by the standard deviation.\n\n    Args:\n      x:\n        Input dataset. A matrix with m rows and n columns.\n\n    Returns:\n      A tuple consisting of:\n      - A vector of means.\n      - A vector of standard deviations.\n    \"\"\"\n    means = [np.mean(x[:, 0])]\n    stds = [np.std(x[:, 0])]\n\n    for i in range(1, x.shape[1]):\n        means.append(np.mean(x[:, i]))\n        stds.append(np.std(x[:, i]))\n        x[:, i] = (x[:, i] - means[-1]) / stds[-1]\n\n    return np.array(means), np.array(stds)\n\n\ndef predict_using_normalized_features(\n    means: np.ndarray,\n    stds: np.ndarray,\n    theta: np.ndarray,\n    house_size: int,\n    num_bedrooms: int,\n) -> np.ndarray:\n    \"\"\"\n    Make a prediction of value for given house size and number of bedrooms using provided theta\n    vector. Normalize the y values by substring the means and dividing by standard deviations.\n\n    Args:\n      means:\n        3-element vector of feature means.\n      stds:\n        3-element vector of feature stds.\n      theta:\n        The parameters for the regression function. An n+1-element vector.\n      house_size:\n        A house size for which the prediction should be made.\n      num_bedrooms:\n        A number of bedrooms for which the prediction should be made.\n\n    Returns:\n        Predicted price of the house with the given size and number of bedrooms.\n    \"\"\"\n    y = [house_size, num_bedrooms]\n    y = [(y[i] - means[i + 1]) / stds[i + 1] for i in range(len(y))]\n    y.insert(0, 1)\n    y = np.array(y)\n\n    return hypothesis_function(y, theta)\n\n\ndef predict_from_normal_equation(\n    x: np.ndarray, y: np.ndarray, house_size: int, num_bedrooms: int\n) -> np.ndarray:\n    \"\"\"\n    Using the normal equations, computes the closed-form solution to linear regression.\n\n    Args:\n      x:\n        Input dataset. A matrix with m rows and n columns.\n      y:\n        The values corresponding to the input dataset. An m-element vector.\n      house_size:\n        A house size for which the prediction should be made.\n      num_bedrooms:\n        A number of bedrooms for which the prediction should be made.\n\n    Returns:\n      Predicted price of the house with the given size and number of bedrooms.\n    \"\"\"\n\n    def norm_eq(_x: np.ndarray, _y: np.ndarray) -> np.ndarray:\n        \"\"\"\n        Implementation of the normal equation.\n\n        Args:\n          _x:\n            Input dataset. A matrix with m rows and n columns.\n          _y:\n            The values corresponding to the input dataset. An m-element vector.\n\n        Returns:\n            A theta vector for given _x and _y matrices.\n        \"\"\"\n        return np.dot(np.dot(np.linalg.inv(np.dot(_x.T, _x)), _x.T), _y)\n\n    return hypothesis_function(np.array([1, house_size, num_bedrooms]), norm_eq(x, y))\n", "meta": {"hexsha": "57962c6903b7cc5b20807634c65448cd9e6a18e7", "size": 6264, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Exercise_1/src/algorithms.py", "max_stars_repo_name": "djeada/Stanford-Machine-Learning", "max_stars_repo_head_hexsha": "e6ef77939b7c581aebb5e9454669ad2dbb4f98f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Exercise_1/src/algorithms.py", "max_issues_repo_name": "djeada/Stanford-Machine-Learning", "max_issues_repo_head_hexsha": "e6ef77939b7c581aebb5e9454669ad2dbb4f98f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Exercise_1/src/algorithms.py", "max_forks_repo_name": "djeada/Stanford-Machine-Learning", "max_forks_repo_head_hexsha": "e6ef77939b7c581aebb5e9454669ad2dbb4f98f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.32, "max_line_length": 110, "alphanum_fraction": 0.6376117497, "include": true, "reason": "import numpy", "num_tokens": 1474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96323053709097, "lm_q2_score": 0.9059898172105135, "lm_q1q2_score": 0.8726770582306327}}
{"text": "import numpy as np\r\nfrom math import pi,cos,sin,tan,atan,ceil\r\nimport operator as op\r\nfrom cmath import exp\r\ndef linear_conv(x,h):\r\n              \r\n              N=len(x)+len(h)-1\r\n              x1=np.zeros((N))\r\n              h1=np.zeros((N))\r\n              m=len(x)\r\n              n=len(h)\r\n              y=np.zeros((N))\r\n              for i in range(m):\r\n                            x1[i]=x[i]\r\n              for i in range(n):\r\n                            h1[i]=h[i]\r\n              for i in range(N):\r\n                            for j in range(i+1):\r\n                                          y[i]=y[i]+ x1[j]*h1[i-j]\r\n              return y\r\n    \r\ndef circular_conv(x,h):   \r\n              N=max(len(x),len(h))\r\n              y=np.zeros((N))\r\n              x1=np.zeros((N))\r\n              h1=np.zeros((N))\r\n              for i in range(len(x)):\r\n                            x1[i]=x[i]\r\n              for i in range(len(h)):\r\n                            h1[i]=h[i]\r\n              for i in range(N):\r\n                            for j in range(N):\r\n                                          y[i]=y[i]+x1[j]*h1[op.mod((i-j),N)]\r\n\r\n              return y\r\n\r\ndef sampling_theorem():\r\n              Rt=float(input('Enter the resolution of analog signal'))\r\n              Ns= int(1/Rt)\r\n              t=[Rt*t1 for t1 in range(Ns)]\r\n              fm=int(input('enter the fundamental frequency'))\r\n              xt=[cos(2*pi*fm*Rt*t1) for t1 in range(Ns)]\r\n              fs=int(input('enter the sampling frequency'))\r\n              Ts=(1/fs)\r\n              N=fs\r\n              n=[n1 for n1 in range(N)]\r\n              xn=[cos(2*pi*fm*n1*Ts) for n1 in range(N)]\r\n              xr=np.zeros((len(xt)))\r\n              tr=0\r\n              for t1 in range(Ns):\r\n                            for n2 in range(N):\r\n                                          if((pi*(tr-n2*Ts)/Ts)==0):\r\n                                                        xr[t1]=xr[t1]+xn[n2]\r\n                                          else:\r\n                                                        xr[t1]=xr[t1]+xn[n2]*(sin(pi*(tr-n2*Ts)/Ts))/((pi*(tr-n2*Ts))/Ts)\r\n                            tr=tr+Rt\r\n              return t,xt,n,xn,xr\r\ndef fft(x):\r\n        N=len(x)\r\n        X=np.zeros((N),'complex')\r\n        for k in range(N):\r\n            for n in range(N):\r\n                X[k]=X[k] + x[n]*exp(-1j*2*pi*k*n/N)\r\n        return X\r\n    \r\ndef auto_correlation(x):\r\n        x1=x[::-1]\r\n        N=len(x)+len(x1)-1\r\n        x11=np.zeros((N))\r\n        h1=np.zeros((N))\r\n        m=len(x)\r\n        n=len(x1)\r\n        y=[0]*N\r\n        for i in range(m):\r\n            x11[i]=x[i]    \r\n        for i in range(n):\r\n            h1[i]=x1[i]   \r\n        for i in range(N):\r\n            for j in range(i+1):\r\n                y[i]=y[i]+ x11[j]*h1[i-j]   \r\n        return y\r\n\r\ndef cross_correlation(x,h):\r\n        h1=h[::-1]\r\n        N=len(x)+len(h)-1\r\n        x11=np.zeros((N))\r\n        h11=np.zeros((N))\r\n        m=len(x)\r\n        n=len(h)\r\n        y=np.zeros((N))\r\n        for i in range(m):\r\n            x11[i]=x[i]    \r\n        for i in range(n):\r\n            h11[i]=h1[i]   \r\n        for i in range(N):\r\n            for j in range(i+1):\r\n                y[i]=y[i]+ x11[j]*h11[i-j]   \r\n        return y\r\n\r\ndef filter(b,a,x):\r\n              N=len(x)\r\n              b1=np.zeros((N))\r\n              a1=np.zeros((N))\r\n              nr=np.zeros((N))\r\n              dr=np.zeros((N))\r\n              y=np.zeros((N))\r\n              if(np.size(a)==1):\r\n                            for i in range(len(b)):\r\n                                          b1[i]=b[i]\r\n                            for i in range(N):\r\n                                          for j in range(i+1):\r\n                                                        y[i]=y[i]+b1[j]*x[i-j]\r\n              else:\r\n                                          \r\n                            for i in range(len(b)):\r\n                                          b1[i]=b[i]\r\n                            for i in range(len(a)):\r\n                                          a1[i]=a[i]\r\n                            for i in range(N):\r\n                                          for j in range(i+1):\r\n                                                        nr[i]=nr[i]+b1[j]*x[i-j]\r\n                                          for j in range(i+1):\r\n                                                        dr[i]=dr[i]-a1[j]*y[i-j]\r\n                                          y[i]=nr[i]+dr[i]\r\n              return y\r\n\r\ndef fir_lpf(N,wc,win,freq_resolution):\r\n              w=np.zeros((N))\r\n              if win=='hamm':            \r\n                            for n in range(N):\r\n                                          w[n]=0.54-0.46*cos((2*pi*n)/(N-1))\r\n              elif win=='hann':\r\n                            for n in range(N):\r\n                                          w[n]=0.5-0.5*cos((2*pi*n)/(N-1))\r\n              else:\r\n                            for n in range(N):\r\n                                          w[n]= 1\r\n         \r\n              hd=np.zeros((N))\r\n              h=np.zeros((N))\r\n              alp=(N-1)/2\r\n              for n in range(N):\r\n                            if n==alp:\r\n                                          hd[n]=wc/pi\r\n                            else:\r\n                                          hd[n]=sin(wc*(n-alp))/(pi*(n-alp))\r\n              for n in range(N):\r\n                            h[n]=hd[n]*w[n]\r\n              N1=np.ceil((2*pi)/(freq_resolution))+1\r\n              H=np.zeros(int(N1),'complex')\r\n              w2=-pi\r\n              t1=np.zeros(int(N1))\r\n              i=0\r\n              for w1 in range(int(N1)):\r\n                            for n in range(N):\r\n                                          H[w1]=H[w1]+h[n]*exp(-1j*w2*n)\r\n                            t1[i]=w2\r\n                            w2=w2+freq_resolution\r\n                            i=i+1\r\n              return h,t1,H\r\ndef fir_hpf(N,wc,win,freq_resolution):\r\n              w=np.zeros((N))\r\n              if win=='hamm':            \r\n                            for n in range(N):\r\n                                          w[n]=0.54-0.46*cos((2*pi*n)/(N-1))\r\n              elif win=='hann':\r\n                            for n in range(N):\r\n                                          w[n]=0.5-0.5*cos((2*pi*n)/(N-1))\r\n              else:\r\n                            for n in range(N):\r\n                                          w[n]= 1\r\n         \r\n              hd=np.zeros((N))\r\n              h=np.zeros((N))\r\n              alp=(N-1)/2\r\n              for n in range(N):\r\n                            if n==alp:\r\n                                          hd[n]=(pi-wc)/pi\r\n                            else:\r\n                                          hd[n]= -sin(wc*(n-alp))/(pi*(n-alp))\r\n              for n in range(N):\r\n                            h[n]=hd[n]*w[n]\r\n              N1=np.ceil((2*pi)/(freq_resolution))+1\r\n              H=np.zeros(int(N1),'complex')\r\n              w2=-pi\r\n              t1=np.zeros(int(N1))\r\n              i=0\r\n              for w1 in range(int(N1)):\r\n                            for n in range(N):\r\n                                          H[w1]=H[w1]+h[n]*exp(-1j*w2*n)\r\n                            t1[i]=w2\r\n                            w2=w2+freq_resolution\r\n                            i=i+1\r\n              return h,t1,H\r\ndef buttord(fp,fs,ap1,as1,F):\r\n              T=1/F\r\n              wp=2*pi*fp/F\r\n              ws=2*pi*fs/F\r\n              Wp=2*F*tan(wp/2)\r\n              Ws=2*F*tan(ws/2)\r\n              nr= 10**(ap1/10)-1\r\n              dr=  10**(as1/10)-1\r\n              N= np.log10((nr/dr))/(2*np.log10(Wp/Ws))\r\n              N=ceil(N)\r\n              if(ap1>10):\r\n                            Wc= (Ws)/((10**(as1/10)-1)**(1/(2*N)))\r\n              else:\r\n                            Wc= (Wp)/((10**(ap1/10)-1)**(1/(2*N)))\r\n              wc= 2*atan((Wc*T)/2)\r\n              return N,wc/pi\r\n\r\n", "meta": {"hexsha": "444139814d57e250860a34224495ffb40a482561", "size": 7939, "ext": "py", "lang": "Python", "max_stars_repo_path": "dspalgorithm/__init__.py", "max_stars_repo_name": "shivarao101/dspalgorithm", "max_stars_repo_head_hexsha": "3b6644a552b61313c9a288bdb5affa7ad8d0fffd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dspalgorithm/__init__.py", "max_issues_repo_name": "shivarao101/dspalgorithm", "max_issues_repo_head_hexsha": "3b6644a552b61313c9a288bdb5affa7ad8d0fffd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dspalgorithm/__init__.py", "max_forks_repo_name": "shivarao101/dspalgorithm", "max_forks_repo_head_hexsha": "3b6644a552b61313c9a288bdb5affa7ad8d0fffd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4481132075, "max_line_length": 122, "alphanum_fraction": 0.2903388336, "include": true, "reason": "import numpy", "num_tokens": 1828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. Yes\n2. Yes", "lm_q1_score": 0.9525741268224331, "lm_q2_score": 0.9161096050004511, "lm_q1q2_score": 0.8726623070569489}}
{"text": "import numpy as np\nimport random\n\ndef four_way_slice(m, n):\n    m11 = m[:n // 2, :n // 2]\n    m12 = m[:n // 2, n // 2:]\n    m21 = m[n // 2:, :n // 2]\n    m22 = m[n // 2:, n // 2:]\n\n    return m11, m12, m21, m22\n\n\ndef multiply_Strassen_pad(a, b, n, n_min):\n    if n <= n_min:\n        return np.matmul(a, b)\n\n    a11, a12, a21, a22 = four_way_slice(a, n)\n    b11, b12, b21, b22 = four_way_slice(b, n)\n\n    p1 = multiply_Strassen_pad(a11 + a22, b11 + b22, n // 2, n_min)\n    p2 = multiply_Strassen_pad(a21 + a22, b11, n // 2, n_min)\n    p3 = multiply_Strassen_pad(a11, b12 - b22, n // 2, n_min)\n    p4 = multiply_Strassen_pad(a22, b21 - b11, n // 2, n_min)\n    p5 = multiply_Strassen_pad(a11 + a12, b22, n // 2, n_min)\n    p6 = multiply_Strassen_pad(a21 - a11, b11 + b12, n // 2, n_min)\n    p7 = multiply_Strassen_pad(a12 - a22, b21 + b22, n // 2, n_min)\n\n    c11 = p1 + p4 - p5 + p7\n    c12 = p3 + p5\n    c21 = p2 + p4\n    c22 = p1 + p3 - p2 + p6\n\n    c1 = np.concatenate([c11, c12], axis=1)\n    c2 = np.concatenate([c21, c22], axis=1)\n    return np.concatenate([c1, c2], axis=0)\n\n\ndef multiply_Strassen(a, b, n, n_min):\n    assert a.shape[0] == a.shape[1], \"a must be a square matrix\"\n    assert b.shape[0] == b.shape[1], \"b must be a square matrix\"\n    assert a.shape[0] == b.shape[0], \"a and b must have the same size\"\n\n    size = a.shape[0]\n    pad_size = 1\n    while pad_size < size:\n        pad_size *= 2\n\n    a_padded = np.zeros((pad_size, pad_size))\n    a_padded[:size, :size] = a\n\n    b_padded = np.zeros((pad_size, pad_size))\n    b_padded[:size, :size] = b\n\n    result = multiply_Strassen_pad(a_padded, b_padded, pad_size, n_min)\n\n    return result[:size, :size]\n\n\ndef generate_random_matrix(size):\n    matrix = []\n    for i in range(0, size):\n        current_line = []\n        for j in range(0, size):\n            current_line.append(random.random() * 10)\n        matrix.append(current_line)\n    return np.array(matrix)\n\n\nif __name__ == '__main__':\n    size = 100\n\n    a = generate_random_matrix(size)\n\n    b = generate_random_matrix(size)\n\n    our_result = multiply_Strassen(a, b, size, 2)\n    np_result = np.matmul(a, b)\n\n    norm_matrix = our_result - np_result\n\n    #print(multiply_Strassen(a, b, size, 2))\n    #print(np.matmul(a, b))\n    print(\"Norm =\", np.linalg.norm(norm_matrix))\n", "meta": {"hexsha": "649532627089a7101a0cc62281ecf9df49ffe57a", "size": 2297, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw1/strassen.py", "max_stars_repo_name": "mironalex/CN", "max_stars_repo_head_hexsha": "5d6f9dd2389baeb8579625898f3337b6d6bdfb38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-07T18:21:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-07T18:21:02.000Z", "max_issues_repo_path": "hw1/strassen.py", "max_issues_repo_name": "mironalex/CN", "max_issues_repo_head_hexsha": "5d6f9dd2389baeb8579625898f3337b6d6bdfb38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw1/strassen.py", "max_forks_repo_name": "mironalex/CN", "max_forks_repo_head_hexsha": "5d6f9dd2389baeb8579625898f3337b6d6bdfb38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3452380952, "max_line_length": 71, "alphanum_fraction": 0.5955594253, "include": true, "reason": "import numpy", "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446479186301, "lm_q2_score": 0.8962513627417531, "lm_q1q2_score": 0.8726303425232866}}
{"text": "import numpy as np\nfrom numpy.linalg import eig, inv\nfrom playLA.Matrix import Matrix\nfrom playLA.LinearSystem import rank\n\n\ndef diagonalize(A):\n    assert A.ndim == 2\n    assert A.shape[0] == A.shape[1]\n\n    eigenvalues, eigenvectors = eig(A)\n\n    P = eigenvectors\n    if rank(Matrix(P.tolist())) != A.shape[0]:\n        print(\"Matrix cannot be diagonalized!\")\n        return None, None, None\n\n    D = np.diag(eigenvalues)\n    Pinv = inv(P)\n\n    return P, D, Pinv\n\n\nif __name__ == \"__main__\":\n\n    A1 = np.array([[4, -2],\n                   [1, 1]])\n    P1, D1, Pinv1 = diagonalize(A1)\n    print(P1)\n    print(D1)\n    print(Pinv1)\n    print(P1.dot(D1).dot(Pinv1))\n    print()\n\n    A2 = np.array([[3, 1],\n                   [0, 3]])\n    P2, D2, Pinv2 = diagonalize(A2)\n    print(P2)\n    print(D2)\n    print(Pinv2)\n", "meta": {"hexsha": "b9ed16e4dc409a7aa9846e2841a5941a73852e7b", "size": 813, "ext": "py", "lang": "Python", "max_stars_repo_path": "playLA/main_diag.py", "max_stars_repo_name": "violet-Bin/LinearAlgebra", "max_stars_repo_head_hexsha": "f3514ff12f91ad6a0e64dbdf521a8001fd4bf4c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-10T12:46:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-10T12:46:04.000Z", "max_issues_repo_path": "playLA/main_diag.py", "max_issues_repo_name": "violet-Bin/LinearAlgebra", "max_issues_repo_head_hexsha": "f3514ff12f91ad6a0e64dbdf521a8001fd4bf4c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "playLA/main_diag.py", "max_forks_repo_name": "violet-Bin/LinearAlgebra", "max_forks_repo_head_hexsha": "f3514ff12f91ad6a0e64dbdf521a8001fd4bf4c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8292682927, "max_line_length": 47, "alphanum_fraction": 0.569495695, "include": true, "reason": "import numpy,from numpy", "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018362008348, "lm_q2_score": 0.8947894731166139, "lm_q1q2_score": 0.8726003371964994}}
{"text": "# integrate the equations of motion of a pendulum, w/o the small angle\n# approximation\n\nimport numpy\nimport pylab\nimport math\n\n# global parameters \ng = 9.81     # gravitational acceleration [m/s]\nL = 9.81     # length of pendulum [m]\n\n\nclass pendulumHistory:\n    \"\"\" simple container to store the pendulum history \"\"\"\n\n    def __init__(self):\n        self.t = None\n        self.theta = None\n        self.omega = None\n\n    def energy(self):\n        \"\"\" return the energy (per unit mass) \"\"\"\n        return 0.5*L**2*self.omega**2 - g*L*numpy.cos(self.theta)\n        \n\n\ndef rhs(theta, omega):\n    \"\"\" equations of motion for a pendulum\n        dtheta/dt = omega\n        domega/dt = - (g/L) sin theta \"\"\"\n\n    return omega, -(g/L)*numpy.sin(theta)\n\n\ndef intEuler(theta0, dt, tmax, rhs):\n    \"\"\" integrate the equations of motion using Euler's method \"\"\"\n        \n    \n    # initial conditions\n    t = 0.0\n    theta = theta0\n    omega = 0.0    # at the maximum angle, the angular velocity is 0\n\n\n    # store the history for plotting\n    tPoints = [t]\n    thetaPoints = [theta]\n    omegaPoints = [omega]\n\n    while (t < tmax):\n\n        # get the RHS\n        thetadot, omegadot = rhs(theta, omega)\n\n        # advance\n        thetanew = theta + dt*thetadot\n        omeganew = omega + dt*omegadot\n\n        t += dt\n\n        # store\n        tPoints.append(t)\n        thetaPoints.append(thetanew)\n        omegaPoints.append(omeganew)\n\n        # set for the next step\n        theta = thetanew; omega = omeganew\n\n    # return a pendulumHistory object with the trajectory\n    H = pendulumHistory()\n    H.t = numpy.array(tPoints)\n    H.theta = numpy.array(thetaPoints)\n    H.omega = numpy.array(omegaPoints)\n\n    return H\n\n\n\ndef intEC(theta0, dt, tmax, rhs):\n    \"\"\" integrate the equations of motion using Euler-Cromer \"\"\"\n        \n    \n    # initial conditions\n    t = 0.0\n    theta = theta0\n    omega = 0.0    # at the maximum angle, the angular velocity is 0\n\n\n    # store the history for plotting\n    tPoints = [t]\n    thetaPoints = [theta]\n    omegaPoints = [omega]\n\n    while (t < tmax):\n\n        # get the RHS\n        thetadot, omegadot = rhs(theta, omega)\n\n        # advance\n        omeganew = omega + dt*omegadot\n        thetanew = theta + dt*omeganew\n\n\n        t += dt\n\n        # store\n        tPoints.append(t)\n        thetaPoints.append(thetanew)\n        omegaPoints.append(omeganew)\n\n        # set for the next step\n        theta = thetanew; omega = omeganew\n\n    # return a pendulumHistory object with the trajectory\n    H = pendulumHistory()\n    H.t = numpy.array(tPoints)\n    H.theta = numpy.array(thetaPoints)\n    H.omega = numpy.array(omegaPoints)\n\n    return H\n\n\ndef intVVerlet(theta0, dt, tmax, rhs):\n    \"\"\" integrate the equations of motion using Euler-Cromer \"\"\"\n        \n    \n    # initial conditions\n    t = 0.0\n    theta = theta0\n    omega = 0.0    # at the maximum angle, the angular velocity is 0\n\n\n    # store the history for plotting\n    tPoints = [t]\n    thetaPoints = [theta]\n    omegaPoints = [omega]\n\n    while (t < tmax):\n\n        # get the RHS at time-level n\n        thetadot, omegadot = rhs(theta, omega)\n\n        thetanew = theta + dt*thetadot + 0.5*dt**2*omegadot\n\n        # get the RHS with the updated theta -- omega doesn't matter\n        # here, since we only need thetadot and omega doesn't affect\n        # that.\n        thetadot_np1, omegadot_np1 = rhs(thetanew, omega)\n\n        omeganew = omega + 0.5*dt*(omegadot + omegadot_np1)\n\n        t += dt\n\n        # store\n        tPoints.append(t)\n        thetaPoints.append(thetanew)\n        omegaPoints.append(omeganew)\n\n        # set for the next step\n        theta = thetanew; omega = omeganew\n\n    # return a pendulumHistory object with the trajectory\n    H = pendulumHistory()\n    H.t = numpy.array(tPoints)\n    H.theta = numpy.array(thetaPoints)\n    H.omega = numpy.array(omegaPoints)\n\n    return H\n\n\n\n\n# 10 degree pendulum\ntheta0 = 10.0*math.pi/180.0\ndt = 0.1\ntmax = 30.0\n\nHEuler = intEuler(theta0, dt, tmax, rhs)\nHEC = intEC(theta0, dt, tmax, rhs)\nHVVerlet = intVVerlet(theta0, dt, tmax, rhs)\n\npylab.plot(HEuler.t, HEuler.theta, label=\"Euler\")\npylab.plot(HEC.t, HEC.theta, label=\"Euler-Cromer\")\npylab.plot(HVVerlet.t, HVVerlet.theta, label=\"velocity Verlet\")\n\npylab.xlabel(\"t\")\npylab.ylabel(r\"$\\theta$(t)\")\n\nleg = pylab.legend()\nltext = leg.get_texts()\npylab.setp(ltext, fontsize='small')\nleg.draw_frame(0)\n\npylab.savefig(\"pendulum-theta-10.png\")\n\n\npylab.clf()\n\npylab.subplot(211)\n\npylab.plot(HEuler.t, HEuler.energy(), label=\"Euler\")\n\npylab.xlabel(\"t\")\npylab.ylabel(\"E(t)\")\n\nleg = pylab.legend()\nltext = leg.get_texts()\npylab.setp(ltext, fontsize='small')\nleg.draw_frame(0)\n\npylab.subplot(212)\n\npylab.plot(HEC.t, HEC.energy(), label=\"Euler-Cromer\")\npylab.plot(HVVerlet.t, HVVerlet.energy(), label=\"velocity Verlet\")\n\npylab.xlabel(\"t\")\npylab.ylabel(\"E(t)\")\n\nleg = pylab.legend()\nltext = leg.get_texts()\npylab.setp(ltext, fontsize='small')\nleg.draw_frame(0)\n\npylab.tight_layout()\n\npylab.savefig(\"pendulum-energy-10.png\")\n\n\n\n\n# 100 degree pendulum\npylab.clf()\n\ntheta0 = 100.0*math.pi/180.0\ndt = 0.1\ntmax = 30.0\n\nHEuler = intEuler(theta0, dt, tmax, rhs)\nHEC = intEC(theta0, dt, tmax, rhs)\nHVVerlet = intVVerlet(theta0, dt, tmax, rhs)\n\npylab.plot(HEuler.t, HEuler.theta, label=\"Euler\")\npylab.plot(HEC.t, HEC.theta, label=\"Euler-Cromer\")\npylab.plot(HVVerlet.t, HVVerlet.theta, label=\"velocity Verlet\")\n\npylab.xlabel(\"t\")\npylab.ylabel(r\"$\\theta$(t)\")\n\nleg = pylab.legend()\nltext = leg.get_texts()\npylab.setp(ltext, fontsize='small')\nleg.draw_frame(0)\n\npylab.savefig(\"pendulum-theta-100.png\")\n\n\npylab.clf()\n\npylab.subplot(211)\npylab.plot(HEuler.t, HEuler.energy(), label=\"Euler\")\n\npylab.xlabel(\"t\")\npylab.ylabel(\"E(t)\")\n\nleg = pylab.legend()\nltext = leg.get_texts()\npylab.setp(ltext, fontsize='small')\nleg.draw_frame(0)\n\npylab.subplot(212)\npylab.plot(HEC.t, HEC.energy(), label=\"Euler-Cromer\")\npylab.plot(HVVerlet.t, HVVerlet.energy(), label=\"velocity Verlet\")\n\npylab.xlabel(\"t\")\npylab.ylabel(\"E(t)\")\n\nleg = pylab.legend()\nltext = leg.get_texts()\npylab.setp(ltext, fontsize='small')\nleg.draw_frame(0)\n\npylab.tight_layout()\n\npylab.savefig(\"pendulum-energy-100.png\")\n\n", "meta": {"hexsha": "acabd6b4b6eac5367618a8b41b0815af2df15d3b", "size": 6143, "ext": "py", "lang": "Python", "max_stars_repo_path": "others/ODES/pendulum.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "others/ODES/pendulum.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/ODES/pendulum.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 21.479020979, "max_line_length": 70, "alphanum_fraction": 0.6407292854, "include": true, "reason": "import numpy", "num_tokens": 1821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238083, "lm_q2_score": 0.9241418267688303, "lm_q1q2_score": 0.8725533242414505}}
{"text": "## This is my implementation of biphivals.py which\n## Generate biorthogonal scaling functions and their associated\n## using Python libraries numpy, scipy, matlibplot, PyWavelets\n## the given filter coefficients. \n##\n## The main reference that I'll use is\n## Gilbert Strang, and Kevin Amaratunga. 18.327 Wavelets, Filter Banks and Applications, Spring 2003. (Massachusetts Institute of Technology: MIT OpenCourseWare), http://ocw.mit.edu (Accessed 19 Jun, 2015). License: Creative Commons BY-NC-SA\n## Note that even though biphivals.m was needed in the MIT OCW 18.327, \n## it was NOT included in the MIT OCW; I found it here:\n## http://web.mit.edu/1.130/WebDocs/1.130/Software/Examples/biphivals.m\n## \n#####################################################################################\n## Copyleft 2015, Ernest Yeung <ernestyalumni@gmail.com>                 \n##                                                                                 \n## 20150702\n##                                                                          \n## This program, along with all its code, is free software; \n## you can redistribute it and/or modify  \n## it under the terms of the GNU General Public License as published by                \n## the Free Software Foundation; either version 2 of the License, or        \n## (at your option) any later version.                               \n##                                                                \n## This program is distributed in the hope that it will be useful,             \n## but WITHOUT ANY WARRANTY; without even the implied warranty of                      \n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the    \n## GNU General Public License for more details.                      \n##                                                                       \n## You can have received a copy of the GNU General Public License              \n## along with this program; if not, write to the Free Software Foundation, Inc.,  \n## S1 Franklin Street, Fifth Floor, Boston, MA                      \n## 02110-1301, USA                                              \n##                                                \n## Governing the ethics of using this program, I default to the Caltech Honor Code:  \n## ``No member of the Caltech community shall take unfair advantage of               \n## any other member of the Caltech community.''                       \n##                                                                                  \n## If you like what I'm doing and would like to help and contribute support,  \n## please take a look at my crowdfunding campaign at ernestyalumni.tilt.com \n## and subscription-based Patreon   \n## read my mission statement and give your financial support, \n## no matter how small or large, \n## if you can        \n## and to keep checking my ernestyalumni.wordpress.com blog and \n## various social media channels    \n## for updates as I try to keep putting out great stuff.                          \n##                                                                              \n## Fund Science! Help my physics education outreach and research efforts at \n## Open/Tilt or subscription Patreon - Ernest Yeung\n##                                                                            \n## ernestyalumni.tilt.com                                                         \n##                                                                                    \n## Facebook     : ernestyalumni                                                       \n## gmail        : ernestyalumni                                               \n## google       : ernestyalumni                                                    \n## linkedin     : ernestyalumni                                                  \n## Patreon      : ernestyalumni\n## Tilt/Open    : ernestyalumni                                                   \n## tumblr       : ernestyalumni                                                       \n## twitter      : ernestyalumni                                               \n## youtube      : ernestyalumni                                                 \n## wordpress    : ernestyalumni                                      \n##  \n##                                                                           \n################################################################################\n## \n\nimport numpy as np\nimport scipy\nfrom scipy.linalg import toeplitz\n\ndef biphivals(h0,h1,f0,f1,i):\n    \"\"\"\n    Kevin Amaratunga (4 August, 1993) wrote the Matlab code but I \n    (Ernest Yeung ernestyalumni) implemented biphivals \n    using Python with numpy (20150702) \n    \n    Here's Dr. Amaratunga's original comments:\n\n    function [x,phi,phitilde,psi,psitilde] = biphivals(h0,h1,f0,f1,i)\n    Generate biorthogonal scaling functions and their associated\n    wavelets using the given filter coefficients\n    Kevin Amaratunga\n    4 August, 1993\n\n    h0, h1, f0, f1 = wavelet filters (from BIORFILT).\n    i = discretization parameter.  The number of points per integer\n    step is 2^i.  Thus, setting i = 0 gives the scaling function\n    and wavelet values at integer points.\n    \"\"\"\n    dum = len(f0)\n    f0 = np.vstack(np.array(f0))\n    f1 = np.vstack(np.array(f1))\n    h0 = np.vstack(np.array(h0))\n    h1 = np.vstack(np.array(h1))\n    N = dum\n\n    tmp,dum = h0.shape\n    \n    assert i>=0, \"biphivals: i must be non-negative\"\n    \n    m,n = f0.shape\n    tmp,dum = h0.shape\n    \n    assert m == tmp, \"biphivals: filters f0 and h0 must be the same length\"\n\n    #\n    # Make sure the lowpass filters sum up to 2\n    #\n    fac = 2./np.sum( h0 )\n    h0 = np.multiply( h0[::-1],fac)\n    h1 = np.multiply( h1[::-1],fac)\n    f0 = np.multiply( f0, fac)\n    f1 = np.multiply( f1, fac)\n     \n    cf0 = np.vstack( (f0 , np.vstack( np.zeros(m)  ) ) )\n    rf0 = np.hstack( ( f0[0], np.zeros(m-1) ) )\n    tmp = toeplitz(cf0,rf0)\n    M = np.zeros((m,m))\n    \n    M = tmp.flatten('F')[0:-1:2].reshape((m,m)).T - np.identity(m)\n\n    M[-1,:] = np.ones(m)\n    tmp = np.vstack( np.append(np.zeros(m-1),np.identity(1)) )\n    phi = np.linalg.solve( M,tmp)  # Integer values of phi \n\n    ch0 = np.vstack( (h0 , np.vstack( np.zeros(m)  ) ) )\n    rh0 = np.hstack( ( h0[0], np.zeros(m-1) ) )\n    tmp = toeplitz(ch0,rh0)\n    M = np.zeros((m,m))    \n    M = tmp.flatten('F')[0:-1:2].reshape((m,m)).T - np.identity(m)\n    M[-1,:] = np.ones(m)\n    tmp = np.vstack( np.append(np.zeros(m-1),np.identity(1)) )\n    phitilde = np.linalg.solve( M,tmp)  # Integer values of phi \n\n    if i > 0:\n        for k in range(0,i):\n            p = 2**(k+1)*(m-1)+1   # No of rows in toeplitz matrix \n            q = 2**k *(m-1)+1      # No of columns toeplitz matrix\n            if k==0:\n                cf00 = np.vstack( np.append(f0, np.zeros(p-1-m)) )\n                cf0  = np.vstack(( cf00, np.zeros(1) ))\n                ch10 = np.vstack(np.append(h1, np.zeros(p-1-m)))\n                ch00 = np.vstack(np.append(h0, np.zeros(p-1-m)))\n                ch0  = np.vstack(( cf00, np.zeros(1) ))\n                cf10 = np.vstack(np.append(f1, np.zeros(p-1-m)))\n            else:\n                cf0 = np.vstack( np.append( np.identity(1), np.zeros(2**k-1))).dot(cf00.T)\n                cf0 = np.vstack( np.append( cf0.flatten('F'), np.zeros(1) ) )\n                ch0 = np.vstack( np.append( np.identity(1), np.zeros(2**k-1))).dot(ch00.T)\n                ch0 = np.vstack( np.append( ch0.flatten('F'), np.zeros(1) ) )\n            rf0 = np.append( cf0[0], np.zeros(q-1) )\n            Tf0 = toeplitz(cf0,rf0)                \n            rh0 = np.append( ch0[0], np.zeros(q-1) )\n            Th0 = toeplitz(ch0,rh0)\n            if k == i-1:\n                ch1 = (np.vstack(np.append(np.identity(1),np.zeros(2**k-1)))).dot( ch10.T)\n                ch1 = ch1.flatten('F') # flatten\n                ch1 = np.vstack(np.append(ch1,np.zeros(1)))\n                rh1 = np.append( ch1[0], np.zeros(q-1) )\n                Th1 = toeplitz(ch1,rh1)\n                cf1 = (np.vstack(np.append(np.identity(1),np.zeros(2**k-1)))).dot( cf10.T)\n                cf1 = cf1.flatten('F') # flatten\n                cf1 = np.vstack(np.append(cf1,np.zeros(1)))\n                rf1 = np.append( cf1[0], np.zeros(q-1) )\n                Tf1 = toeplitz(cf1,rf1)\n                psi = Tf1.dot(phi)\n                psitilde = Th1.dot(phitilde)\n            phi = Tf0.dot(phi)\n            phitilde = Th0.dot(phitilde)\n\n    elif i==0:\n        ch10 = np.vstack( np.append( h1, np.zeros(m-1) ) )\n        ch1 = np.vstack((ch10, np.zeros(1) ) )\n        rh1 = np.append(ch1[0],np.zeros(m-1))\n        Th1 = toeplitz(ch1,rh1)\n        cf10 = np.vstack( np.append( f1, np.zeros(m-1) ) )\n        cf1 = np.vstack((cf10, np.zeros(1) ) )\n        rf1 = np.append(cf1[0],np.zeros(m-1))\n        Tf1 = toeplitz(cf1,rf1)\n        psi = Tf1.dot(phi)\n        psi = psi[::2]\n        psitilde=Th1.dot(phitilde)\n        psitilde = psitilde[::2]\n\n    a,b = phi.shape\n    x = np.vstack( np.arange(0,a)/2.**i )\n\n    return x, phi, phitilde, psi, psitilde\n\n\n\n", "meta": {"hexsha": "35c60ffab8d254b14b95200bf2089f670e303449", "size": 9034, "ext": "py", "lang": "Python", "max_stars_repo_path": "tools/biphivals.py", "max_stars_repo_name": "ernestyalumni/18-327-wavelets-filter-banks", "max_stars_repo_head_hexsha": "eeb3fd65b42808cf907aa716110417515dbbfd82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-07-18T16:13:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T12:04:01.000Z", "max_issues_repo_path": "tools/biphivals.py", "max_issues_repo_name": "ernestyalumni/18-327-wavelets-filter-banks", "max_issues_repo_head_hexsha": "eeb3fd65b42808cf907aa716110417515dbbfd82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/biphivals.py", "max_forks_repo_name": "ernestyalumni/18-327-wavelets-filter-banks", "max_forks_repo_head_hexsha": "eeb3fd65b42808cf907aa716110417515dbbfd82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-07-30T20:05:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-29T01:11:08.000Z", "avg_line_length": 47.0520833333, "max_line_length": 241, "alphanum_fraction": 0.491144565, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 2219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768651485395, "lm_q2_score": 0.9241418116217418, "lm_q1q2_score": 0.8725533186497083}}
{"text": "from scipy.optimize import fsolve\nfrom numpy import cosh, log\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# The function whose zeros we want to find\ndef numeric(V):\n    return V**2/32.2*log(cosh(32.2*116/V))-29300.0\n\n\n# Determine the terminal solution from the analytic expansion\ndef analytic(t, s, g=32.2):\n    \"\"\"\n    g is given in ft/s^2, t in s and s in ft.\n    \"\"\"\n    delta = np.sqrt(t**2 - 4*log(2)*s/g)\n    return (t-delta)/(2*log(2)/g), (t+delta)/(2*log(2)/g)\n\n\nif __name__ == \"__main__\":\n    # Take as initial guess the average velocity\n    initial_guess = 253.\n    print(f\"Terminal velocity (from numerical solution)  : {fsolve(numeric, initial_guess)[0]} ft/s\")\n    print(f\"Terminal velocity (from analytic expansion) 1: {analytic(116., 29300)[0]} ft/s\")\n    print(f\"Terminal velocity (from analytic expansion) 2: {analytic(116., 29300)[1]} ft/s\")\n    # Determine a value for k\n    k = 32.2*261.2/265.69**2\n    print(f\"k={k} pounds / ft\")\n    \n    # Check the terminal velocity also graphically\n    values = np.linspace(240., 270., 1000)\n    evals = [numeric(val) for val in values]\n    plt.plot(values, np.zeros(len(evals)), color=\"black\")\n    plt.plot(values, evals)\n    plt.title(\"Determination of the Terminal Velocity\")\n    plt.xlabel(\"V [ft/s]\")\n    plt.ylabel(\"f(V)\")\n    plt.show()\n", "meta": {"hexsha": "2fee2b2c4030b236b3c3c1215d3b49c3fc2625d9", "size": 1311, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch2/ex2_2_13.py", "max_stars_repo_name": "FractalArt/chaos_exercises", "max_stars_repo_head_hexsha": "ce86858ceb887560a30f6fd313d920a18f2da5c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-17T18:28:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T18:28:50.000Z", "max_issues_repo_path": "ch2/ex2_2_13.py", "max_issues_repo_name": "FractalArt/chaos_exercises", "max_issues_repo_head_hexsha": "ce86858ceb887560a30f6fd313d920a18f2da5c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch2/ex2_2_13.py", "max_forks_repo_name": "FractalArt/chaos_exercises", "max_forks_repo_head_hexsha": "ce86858ceb887560a30f6fd313d920a18f2da5c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.775, "max_line_length": 101, "alphanum_fraction": 0.6529366895, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924777713888, "lm_q2_score": 0.8976952968970955, "lm_q1q2_score": 0.8725530759147303}}
{"text": "from numpy import array, matmul, sqrt, cos, sin, reshape, newaxis, finfo, log10, floor\n\nEPS = int(floor(-log10(finfo(float).eps)))\nSQRT3 = sqrt(3)\n\n\ndef ab2uvw(Z_ab):\n    \"\"\"\n    2 phase equivalent to 3 phase coordinate transformation, i.e. Clarke transformation\n\n    Parameters\n    ----------\n    Z_ab : numpy array\n        matrix (N x 2) of 2 phase equivalent values\n\n    Outputs\n    -------\n    Z_uwv : numpy array\n        transformed matrix (N x 3) of 3 phase values\n\n    \"\"\"\n    # Transformation matrix\n    ab_2_uvw = 1 / 2 * array([[2, -1, -1], [0, SQRT3, -SQRT3]])\n\n    Z_uvw = matmul(Z_ab, ab_2_uvw)\n\n    return Z_uvw\n\n\ndef uvw2ab(Z_uvw):\n    \"\"\"3 phase to 2 phase equivalent coordinate transformation, i.e. Clarke transformation\n\n    Parameters\n    ----------\n    Z_uvw : numpy array \n        matrix (N x 3) of 3 phase values\n\n    Outputs\n    -------\n    Z_ab : numpy array\n        transformed matrix (N x 2) of 2 phase equivalent values\n\n\n    \"\"\"\n    # Transformation matrix\n    uvw_2_ab = 2 / 3 * array([[1, 0], [-1 / 2, SQRT3 / 2], [-1 / 2, -SQRT3 / 2]])\n\n    Z_ab = matmul(Z_uvw, uvw_2_ab)\n\n    return Z_ab\n\n\ndef ab2dq(Z_ab, theta):\n    \"\"\"\n    alpha-beta to dq coordinate transformation\n    NOTE: sin/cos values are rounded to avoid numerical errors\n\n    Parameters\n    ----------\n    Z_ab : numpy array\n        matrix (N x 2) of alpha-beta - reference frame values\n\n    theta : numpy array\n        angle of the rotor coordinate system\n\n    Outputs\n    -------\n    Z_dq : numpy array\n        transformed (dq) values\n\n    \"\"\"\n    if len(Z_ab.shape) == 1:\n        Z_ab = Z_ab[newaxis, :]\n\n    sin_theta = sin(theta).round(decimals=EPS)\n    cos_theta = cos(theta).round(decimals=EPS)\n\n    Z_d = Z_ab[:, 0] * cos_theta + Z_ab[:, 1] * sin_theta\n    Z_q = -Z_ab[:, 0] * sin_theta + Z_ab[:, 1] * cos_theta\n\n    return reshape([Z_d, Z_q], (2, -1)).transpose()\n\n\ndef dq2ab(Z_dq, theta):\n    \"\"\"\n    dq to alpha-beta coordinate transformation\n    NOTE: sin/cos values are rounded to avoid numerical errors\n\n    Parameters\n    ----------\n    Z_dq : numpy array\n        matrix (N x 2) of dq - reference frame values\n\n    theta : numpy array\n        angle of the rotor coordinate system\n\n    Outputs\n    -------\n    Z_ab : numpy array\n        transformed array\n\n    \"\"\"\n    if len(Z_dq.shape) == 1:\n        Z_dq = Z_dq[newaxis, :]\n\n    sin_theta = sin(theta).round(decimals=EPS)\n    cos_theta = cos(theta).round(decimals=EPS)\n\n    Z_a = Z_dq[:, 0] * cos_theta - Z_dq[:, 1] * sin_theta\n    Z_b = Z_dq[:, 0] * sin_theta + Z_dq[:, 1] * cos_theta\n\n    return reshape([Z_a, Z_b], (2, -1)).transpose()\n", "meta": {"hexsha": "1219761693076b12e959b75a8f59c488f3a559b2", "size": 2597, "ext": "py", "lang": "Python", "max_stars_repo_path": "Functions/Electrical/coordinate_transformation.py", "max_stars_repo_name": "magnetron/pyleecan", "max_stars_repo_head_hexsha": "2a3338f4ab080ad6488b5ab8746c3fea1f36f177", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-26T12:28:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T12:28:45.000Z", "max_issues_repo_path": "Functions/Electrical/coordinate_transformation.py", "max_issues_repo_name": "magnetron/pyleecan", "max_issues_repo_head_hexsha": "2a3338f4ab080ad6488b5ab8746c3fea1f36f177", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Functions/Electrical/coordinate_transformation.py", "max_forks_repo_name": "magnetron/pyleecan", "max_forks_repo_head_hexsha": "2a3338f4ab080ad6488b5ab8746c3fea1f36f177", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.982300885, "max_line_length": 90, "alphanum_fraction": 0.591451675, "include": true, "reason": "from numpy", "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102524151826, "lm_q2_score": 0.9019206824612296, "lm_q1q2_score": 0.872527315078292}}
{"text": "from sympy import *\nfrom sympy.plotting import plot\nfrom sympy.codegen.cfunctions import log10\nimport matplotlib.pyplot as plt\nimport numpy as np\n# https://docs.sympy.org/latest/install.html\n# conda install sympy\n# conda install mpmath\n\n# Sobre matrices: https://docs.sympy.org/latest/tutorial/matrices.html\n\ndef get_passive_mai(Y_a, Y_b, Y_c, Y_d, Y_e):\n  return Matrix([[Y_a, -Y_a, 0, 0, 0],\\\n                 [-Y_a, Y_a + Y_b + Y_c + Y_d, -Y_c, -Y_d, -Y_b],\\\n                 [0, -Y_c, Y_c+Y_e, Y_e, 0],\\\n                 [0, -Y_d, -Y_e, Y_d+Y_e, 0],\\\n                 [0, -Y_b, 0, 0, Y_b]])\n\ndef get_active_mai(A0, Y_i, Y_o):\n  return Matrix([[0, 0, 0, 0, 0],\\\n                 [0, 0, 0, 0, 0],\\\n                 [0, 0, Y_i, 0, -Y_i],\\\n                 [0, 0, A0 * Y_o, Y_o, -A0 * Y_o - Y_o],\\\n                 [0, 0, -Y_i - A0 * Y_o, -Y_o, Y_i + Y_o + A0 * Y_o]])\n\ndef get_mfb_mai(Y_a, Y_b, Y_c, Y_d, Y_e, A0, Y_i, Y_o):\n  return get_passive_mai(Y_a, Y_b, Y_c, Y_d, Y_e) + get_active_mai(A0, Y_i, Y_o)\n\n# Para mejorar la impresion\ninit_printing()\n\n# Defino simbolos\nGa = Symbol('Ga')\nCb = Symbol('Cb')\nGc = Symbol('Gc')\nGd = Symbol('Gd')\nCe = Symbol('Ce')\ns = Symbol('s')\n\nA0 = Symbol('A0')\nY_i = Symbol('Y_i')\nY_o = Symbol('Y_o')\n\nY_45_15 = get_mfb_mai(Ga, s*Cb, Gc, Gd, s*Ce, A0, Y_i, Y_o)\nY_45_15.row_del(4)\nY_45_15.row_del(0)\nY_45_15.col_del(4)\nY_45_15.col_del(3)\nprint('Y_45_15')\nprint(Y_45_15)\n\nY_15_15 = get_mfb_mai(Ga, s*Cb, Gc, Gd, s*Ce, A0, Y_i, Y_o)\nY_15_15.row_del(4)\nY_15_15.row_del(0)\nY_15_15.col_del(4)\nY_15_15.col_del(0)\nprint('Y_15_15')\nprint(Y_15_15)\n\nV_15_45 = (-1.0)**(-1.0-5.0-4.0-5.0) * Y_45_15.det() / Y_15_15.det()\nV_15_45 = cancel(V_15_45)\nprint('La transferencia de tension es:')\nprint(V_15_45)", "meta": {"hexsha": "ff34051dfef188ff5451fc3a373530ccaffeb684", "size": 1725, "ext": "py", "lang": "Python", "max_stars_repo_path": "Repo-Ayudante/examples/mai/mfb.py", "max_stars_repo_name": "lucasliano/TC2", "max_stars_repo_head_hexsha": "7a888a1cd4fae6a1aa89ca8f4d07ebe10526aa10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-05-02T17:14:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T22:28:09.000Z", "max_issues_repo_path": "Repo-Ayudante/examples/mai/mfb.py", "max_issues_repo_name": "lucasliano/TC2", "max_issues_repo_head_hexsha": "7a888a1cd4fae6a1aa89ca8f4d07ebe10526aa10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2020-04-04T21:09:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-14T19:06:01.000Z", "max_forks_repo_path": "Repo-Ayudante/examples/mai/mfb.py", "max_forks_repo_name": "lucasliano/TC2", "max_forks_repo_head_hexsha": "7a888a1cd4fae6a1aa89ca8f4d07ebe10526aa10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-04T20:00:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-04T20:00:21.000Z", "avg_line_length": 27.380952381, "max_line_length": 80, "alphanum_fraction": 0.6023188406, "include": true, "reason": "import numpy,from sympy", "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102571131692, "lm_q2_score": 0.90192067059785, "lm_q1q2_score": 0.872527307838748}}
{"text": "\"\"\"\nFinds the asymptotic expansions of the three roots of \n  the polynomial e*x^3 - 3*x + 1 = 0 where e << 1\n\"\"\"\n\nfrom sympy import *\n\n# Define symbols, expansion of x, and the function\ne, x0, x1, x2 = symbols('e x0 x1 x2')\nx = x0 + e*x1 + e**2*x2 + O(e**3)\nf = e*x**3 - 3*x + 1\n\n# Write f as a power series in e\nf = collect(expand(f),e)\n\n# Set the O(1) terms equal to 0, and output result\nprint(\"\\nFirst root\\n\")\neq0 = f.coeff(e,0)\nprint(\"Zeroth order:\", solveset(eq0))\nsol0 = Rational(1, 3) # Solution for x0\n\n# Substitute the solution into x0\nx = x.subs(x0, sol0) # In the expansion of x\nf = f.subs(x0, sol0) # and in the expansion of f\n\n# Set the O(e) terms equal to 0, and output result\neq1 = f.coeff(e,1)\nprint(\"First order:\", solveset(eq1))\nsol1 = Rational(1, 81) # Solution for x1\n\n# Substitute the solution into x1\nx = x.subs(x1, sol1)\nf = f.subs(x1, sol1)\n\n# Set the O(e^2) terms equal to 0, and output result\neq2 = f.coeff(e, 2)\nprint(\"Second order:\", solveset(eq2))\nsol2 = Rational(1, 729) # Solution for x2\n\n#Substitute the solution into x2 and output x\nx = x.subs(x2, sol2)\nprint(\"x = \", x)\n\n# Change of variables to reveal the solutions near infinity\n# The change of variables is x = y/sqrt(e)\n# Define new variable y, and the rescaled equation f\n# NOTE: e is redefined below this point:\n#       e_below := sqrt(e_above)\ny0, y1, y2 = symbols('y0 y1 y2')\ny = y0 + e*y1 + e**2*y2 + O(e**3)\nf = y**3 - 3*y + e\n\n# Write f as a power series in e\nf = collect(expand(f), e)\n\n# Set the O(1) terms equal to 0, and output result\nprint(\"\\nSecond Root\\n\")\neq0 = f.coeff(e,0)\n\n# There are three solutions to the leading order problem:\n# 0 is a trivial solution, and the other two are relevant\nprint(\"Zeroth order:\", solveset(eq0)) \nsol0 = sqrt(3) # Pick one of the relevant roots\n\n# Substitute the solution into y0\ny = y.subs(y0, sol0)\nf = f.subs(y0, sol0)\n\n# Set the O(e) terms equal to 0, and output result\neq1 = f.coeff(e, 1)\nprint(\"First order:\", solveset(eq1))\nsol1 = Rational(-1, 6) # Solution for y1\n\n# Substitute the solution into y1\ny = y.subs(y1, sol1)\nf = f.subs(y1, sol1)\n\n# Set the O(e^2) terms equal to 0, and output result\neq2 = f.coeff(e, 2)\nprint(\"Second order:\", solveset(eq2))\nsol2 = -sqrt(3)/Integer(72) # Solution for y2\n\n# Substitute the solution into y2, and change variables back to original\ny = y.subs(y2, sol2)\nx = collect(expand(y/e), e)\nprint(\"x =\", x)\n\n# Using the same change of variables as for the second root\n# Redefine expansion of y, and rescaled equation f\nprint(\"\\nThird Root\\n\")\ny = y0 + e*y1 + e**2*y2 + O(e**3)\nf = y**3 - 3*y + e\n\n# Collect terms in powers of e\nf = collect(expand(f), e)\n\n# Set the O(1) terms equal to 0, and output result\neq0 = f.coeff(e,0)\nprint(\"Zeroth order:\", solveset(eq0))\nsol0 = -sqrt(3) # Now use the other relevant root for y0\n\n# Substitute the solution into y0\ny = y.subs(y0, sol0)\nf = f.subs(y0, sol0)\n\n# Set the O(e) terms equal to 0, and output result\neq1 = f.coeff(e, 1)\nprint(\"First order:\", solveset(eq1))\nsol1 = Rational(-1, 6) # Solution for y1\n\n# Substitute the solution into y1\ny = y.subs(y1, sol1)\nf = f.subs(y1, sol1)\n\n# Set the O(e^2) terms equal to 0, and output result\neq2 = f.coeff(e, 2)\nprint(\"Second order:\", solveset(eq2))\nsol2 = sqrt(3)/Integer(72) # Solution for y2\n\n# Substitute the solution into y2, and change variables back to original\ny = y.subs(y2, sol2)\nx = collect(expand(y/e), e)\nprint(\"x =\", x)\nprint(\"\\n\")\n", "meta": {"hexsha": "2f6c58667ae1163857137c17faefc773749a0c02", "size": 3408, "ext": "py", "lang": "Python", "max_stars_repo_path": "1_1a.py", "max_stars_repo_name": "wandrewjam/asymptotics-hw", "max_stars_repo_head_hexsha": "a4839322f5795a472942d2100e07bcc6e0b395e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1_1a.py", "max_issues_repo_name": "wandrewjam/asymptotics-hw", "max_issues_repo_head_hexsha": "a4839322f5795a472942d2100e07bcc6e0b395e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1_1a.py", "max_forks_repo_name": "wandrewjam/asymptotics-hw", "max_forks_repo_head_hexsha": "a4839322f5795a472942d2100e07bcc6e0b395e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.264, "max_line_length": 72, "alphanum_fraction": 0.665786385, "include": true, "reason": "from sympy", "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102542943774, "lm_q2_score": 0.9019206666433899, "lm_q1q2_score": 0.8725273014708362}}
{"text": "import numpy as np\r\n\r\n# REFERENCES\r\n#https://towardsdatascience.com/fast-fourier-transform-937926e591cb\r\n\r\n#https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.03-Fast-Fourier-Transform.html\r\n#https://jakevdp.github.io/blog/2013/08/28/understanding-the-fft/\r\n\r\n\r\ndef show_M(N):\r\n    \"\"\"\r\n    N: int \r\n    \"\"\"\r\n\r\n    n = np.arange(N)\r\n    k = n.reshape((N,1))\r\n\r\n    M  = k*n\r\n    print(\"M:\", M)  \r\n\r\n\r\ndef get_data(len):\r\n    \"\"\"\r\n    len: int \r\n        lenght of data \r\n    \"\"\"\r\n    data = np.random.random(len)\r\n    return data \r\n\r\ndef get_circular_terms(N):\r\n    \"\"\"\r\n    N: int \r\n    \"\"\"\r\n\r\n    terms =  np.exp(-1j *2*np.pi * np.arange(N)/N)\r\n\r\n    return terms\r\n\r\ndef discrete_fourier_transform(data):\r\n    \"\"\"\r\n    data: np.array \r\n        1 dimensional array\r\n    \"\"\"\r\n    #len of data\r\n    N =data.shape[0] \r\n    \r\n    n = np.arange(N)\r\n    k = n.reshape((N,1))\r\n    M = np.exp(-1j * 2*np.pi * k * n/N)\r\n   \r\n    return np.dot(M,data)\r\n\r\ndef fast_fourier_transform(data):\r\n    \"\"\"\r\n    data: np.array  \r\n        data as 1D array\r\n    return discrete fourier transform of data\r\n    \"\"\"\r\n\r\n    # len of data\r\n    N = data.shape[0]\r\n\r\n    # Must be a power of 2\r\n    assert   N % 2 == 0, 'len of data: {} must be a power of 2'.format(N)\r\n\r\n    if N<= 2:\r\n        return discrete_fourier_transform(data)\r\n\r\n    else:\r\n        data_even = fast_fourier_transform(data[::2])\r\n        data_odd = fast_fourier_transform(data[1::2])\r\n        terms = get_circular_terms(N)\r\n\r\n        return np.concatenate(\r\n            [\r\n            data_even + terms[:N//2] * data_odd,\r\n            data_even + terms[N//2:] * data_odd \r\n            ])\r\n    \r\n\r\nN = 4\r\n\r\nX = get_data(N)\r\nprint(\"Data: \",X)\r\n\r\ndt =  discrete_fourier_transform(X)\r\nfdft = fast_fourier_transform(X)\r\ndtnp = np.fft.fft(X)\r\n\r\nprint('DFT:',fdft)\r\n\r\nprint(np.allclose(dt,dtnp),\r\n    np.allclose(fdft,dtnp))\r\n\r\nprint(\"\")\r\nshow_M(N)\r\n\r\n\r\n\r\n", "meta": {"hexsha": "18daa32e86aa547e7d90d127172d472712bfb0e3", "size": 1908, "ext": "py", "lang": "Python", "max_stars_repo_path": "fourier_transform.py", "max_stars_repo_name": "Psychofun/Transformada-Fourier-Rapida", "max_stars_repo_head_hexsha": "1398128cd312ede2317f439ece454e131ad0d181", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-25T22:19:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T22:19:25.000Z", "max_issues_repo_path": "fourier_transform.py", "max_issues_repo_name": "Psychofun/Transformada-Fourier-Rapida", "max_issues_repo_head_hexsha": "1398128cd312ede2317f439ece454e131ad0d181", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fourier_transform.py", "max_forks_repo_name": "Psychofun/Transformada-Fourier-Rapida", "max_forks_repo_head_hexsha": "1398128cd312ede2317f439ece454e131ad0d181", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.08, "max_line_length": 96, "alphanum_fraction": 0.5487421384, "include": true, "reason": "import numpy", "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.9173026556293917, "lm_q1q2_score": 0.8724852868215219}}
{"text": "import numpy as np\r\nimport scipy\r\n\r\n\r\n'''Gaussian Elimination with Complete Pivoting. it will result in a decomposition of form: PAQ = LU.'''\r\n\r\n\r\ndef gaussian_elimination_complete_pivoting(matrix):\r\n    matrix = np.array(matrix)\r\n    m, n = matrix.shape\r\n    multipliers = np.zeros((n, n))\r\n    p_matrix = np.identity(n)\r\n    q_matrix = np.identity(n)\r\n    assert m == n\r\n    absolute_matrix = np.absolute(matrix)\r\n    for k in range(n - 1):\r\n        '''finding the maximum absolute value indices (row & column) of the given matrix.'''\r\n        r, s = np.unravel_index(absolute_matrix.argmax(), absolute_matrix.shape)\r\n        if matrix[r, s] == 0:\r\n            break\r\n        for j in range(k, n):\r\n            matrix[[k, r]] = matrix[[r, k]]  # swapping rows\r\n        p_matrix[[k, r]] = p_matrix[[r, k]]  # generating this step P matrix\r\n        for i in range(n):\r\n            matrix[:, [s, k]] = matrix[:, [k, s]]  # swapping columns\r\n        q_matrix[:, [s, k]] = q_matrix[:, [k, s]]  # generating this step Q matrix\r\n        for t in range(k + 1, n):\r\n            multipliers[t, k] = - (matrix[t, k] / matrix[k, k])  # generating m_i_j multipliers\r\n        for q in range(k, n):\r\n            for e in range(k, n):\r\n                matrix[q, e] += (multipliers[q, k] * matrix[k, e])  # updating matrix entries to form U matrix\r\n        u_matrix = matrix\r\n        l_matrix = np.identity(n)  # creating an identity matrix to form L matrix.\r\n        for row in range(n):\r\n            for column in range(row):\r\n                l_matrix[row, column] = - multipliers[row, column]  # updating identity matrix entries to form L matrix\r\n        return l_matrix, u_matrix, p_matrix, q_matrix\r\n\r\n\r\n'''a linear system of equation is solved by Gaussian Elimination with Complete Pivoting method by following these steps: \r\n        1) given system: AX = b\r\n        2) decompose A matrix to PAQ = LU\r\n        3) solve system: LZ = Pb\r\n        4) solve system: UY = z\r\n        5) X = QY'''\r\n\r\n\r\ndef solver(coefficient_matrix, right_hand_side_vector):\r\n    l, u, p, q = gaussian_elimination_complete_pivoting(coefficient_matrix)  # decomposing matrix A\r\n    z = scipy.linalg.solve_triangular(l, np.matmul(p, right_hand_side_vector))  # third step\r\n    y = scipy.linalg.solve_triangular(u, z)  # forth step\r\n    solution = np.matmul(q, y)  # fifth step\r\n    return solution\r\n\r\n\r\nif __name__ == '__main__':\r\n    given_matrix = eval(input(\"enter A matrix like: [[1, 1, 1], [2, 2, 2], [3, 3, 3]\\n\"))\r\n    vector = eval(input(\"enter b vector like: [1, 1, 1]\\n\"))\r\n    print(\"solution is: \", solver(given_matrix, vector))\r\n", "meta": {"hexsha": "7f151f7f6ee9b55d6f489bbd0ef96821028217be", "size": 2607, "ext": "py", "lang": "Python", "max_stars_repo_path": "GECP.py", "max_stars_repo_name": "arash79/Numerical-methods", "max_stars_repo_head_hexsha": "f1dd455916c92d2c2a2e5909fa26cef67e39f346", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GECP.py", "max_issues_repo_name": "arash79/Numerical-methods", "max_issues_repo_head_hexsha": "f1dd455916c92d2c2a2e5909fa26cef67e39f346", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GECP.py", "max_forks_repo_name": "arash79/Numerical-methods", "max_forks_repo_head_hexsha": "f1dd455916c92d2c2a2e5909fa26cef67e39f346", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.45, "max_line_length": 122, "alphanum_fraction": 0.6018411968, "include": true, "reason": "import numpy,import scipy", "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561721629777, "lm_q2_score": 0.9005297841157158, "lm_q1q2_score": 0.8724838395571051}}
{"text": "import math\nimport random\nimport time\n\nimport numpy\nimport torch\n\n\ndef numpy_network():\n\n    # Create random input and output data\n    x = numpy.linspace(-math.pi, math.pi, 2000)\n    y = numpy.sin(x)\n\n    # Randomly initialize weights\n    a = numpy.random.randn()\n    b = numpy.random.randn()\n    c = numpy.random.randn()\n    d = numpy.random.randn()\n\n    learning_rate = 1e-6\n    for t in range(2000):\n        # Forward pass: compute predicted y\n        # y = a + b x + c x^2 + d x^3\n        y_pred = a + b * x + c * x**2 + d * x**3\n\n        # Compute and print loss\n        loss = numpy.square(y_pred - y).sum()\n        if t % 100 == 99:\n            print(t, loss)\n\n        # Backprop to compute gradients of a, b, c, d with respect to loss\n        grad_y_pred = 2.0 * (y_pred - y)\n        grad_a = grad_y_pred.sum()\n        grad_b = (grad_y_pred * x).sum()\n        grad_c = (grad_y_pred * x ** 2).sum()\n        grad_d = (grad_y_pred * x ** 3).sum()\n\n        # Update weights\n        a -= learning_rate * grad_a\n        b -= learning_rate * grad_a\n        c -= learning_rate * grad_c\n        d -= learning_rate * grad_d\n\n    print(f'Result: y = {a} + {b} x + {c} x^2 + {d} x^3')\n\n\ndef pytorch_network():\n\n    dtype = torch.float\n    device = torch.device(\"cpu\")\n    # device = torch.device(\"cuda:0\") # Uncomment this to run on GPU\n\n    # Create random input and output data\n    x = torch.linspace(-math.pi, math.pi, 2000, device=device, dtype=dtype)\n    y = torch.sin(x)\n\n    # Randomly initialize weights\n    a = torch.randn((), device=device, dtype=dtype)\n    b = torch.randn((), device=device, dtype=dtype)\n    c = torch.randn((), device=device, dtype=dtype)\n    d = torch.randn((), device=device, dtype=dtype)\n\n    learning_rate = 1e-6\n    for t in range(2000):\n        # Forward pass: compute predicted y\n        y_pred = a + b * x + c * x**2 + d * x**3\n\n        # Compute and print loss\n        loss = (y_pred - y).pow(2).sum().item()\n        if t % 100 == 99:\n            print(t, loss)\n\n        # Backprop to compute gradients of a, b, c, d with respect to loss\n        grad_y_pred = 2.0 * (y_pred - y)\n        grad_a = grad_y_pred.sum()\n        grad_b = (grad_y_pred * x).sum()\n        grad_c = (grad_y_pred * x ** 2).sum()\n        grad_d = (grad_y_pred * x ** 3).sum()\n\n        # Update weights using gradient descent\n        a -= learning_rate * grad_a\n        b -= learning_rate * grad_b\n        c -= learning_rate * grad_c\n        d -= learning_rate * grad_d\n\n    print(f'Result: y = {a.item()} + {b.item()} x + {c.item()} x^2 + {d.item()} x^3')\n\n\ndef autograd_network():\n    dtype = torch.float\n    device = torch.device(\"cpu\")\n    # device = torch.device(\"cuda:0\")  # Uncomment this to run on GPU\n\n    # Create Tensors to hold input and outputs.\n    # By default, requires_grad=False, which indicates that we do not need to\n    # compute gradients with respect to these Tensors during the backward pass.\n    x = torch.linspace(-math.pi, math.pi, 2000, device=device, dtype=dtype)\n    y = torch.sin(x)\n\n    # Create random Tensors for weights. For a third order polynomial, we need\n    # 4 weights: y = a + b x + c x^2 + d x^3\n    # Setting requires_grad=True indicates that we want to compute gradients with\n    # respect to these Tensors during the backward pass.\n    a = torch.randn((), device=device, dtype=dtype, requires_grad=True)\n    b = torch.randn((), device=device, dtype=dtype, requires_grad=True)\n    c = torch.randn((), device=device, dtype=dtype, requires_grad=True)\n    d = torch.randn((), device=device, dtype=dtype, requires_grad=True)\n\n    learning_rate = 1e-6\n    for t in range(2000):\n        # Forward pass: compute predicted y using operations on Tensors.\n        y_pred = a + b * x + c * x ** 2 + d * x ** 3\n\n        # Compute and print loss using operations on Tensors.\n        # Now loss is a Tensor of shape (1,)\n        # loss.item() gets the scalar value held in the loss.\n        loss = (y_pred - y).pow(2).sum()\n        if t % 100 == 99:\n            print(t, loss.item())\n\n        # Use autograd to compute the backward pass. This call will compute the\n        # gradient of loss with respect to all Tensors with requires_grad=True.\n        # After this call a.grad, b.grad. c.grad and d.grad will be Tensors holding\n        # the gradient of the loss with respect to a, b, c, d respectively.\n        loss.backward()\n\n        # Manually update weights using gradient descent. Wrap in torch.no_grad()\n        # because weights have requires_grad=True, but we don't need to track this\n        # in autograd.\n        with torch.no_grad():\n            a -= learning_rate * a.grad\n            b -= learning_rate * b.grad\n            c -= learning_rate * c.grad\n            d -= learning_rate * d.grad\n\n            # Manually zero the gradients after updating weights\n            a.grad = None\n            b.grad = None\n            c.grad = None\n            d.grad = None\n\n    print(f'Result: y = {a.item()} + {b.item()} x + {c.item()} x^2 + {d.item()} x^3')\n\n\nclass LegendrePolynomial3(torch.autograd.Function):\n    \"\"\"\n    We can implement our own custom autograd Functions by subclassing\n    torch.autograd.Function and implementing the forward and backward passes\n    which operate on Tensors.\n    \"\"\"\n\n    @staticmethod\n    def forward(ctx, input):\n        \"\"\"\n        In the forward pass we receive a Tensor containing the input and return\n        a Tensor containing the output. ctx is a context object that can be used\n        to stash information for backward computation. You can cache arbitrary\n        objects for use in the backward pass using the ctx.save_for_backward method.\n        \"\"\"\n        ctx.save_for_backward(input)\n        return 0.5 * (5 * input ** 3 - 3 * input)\n\n    @staticmethod\n    def backward(ctx, grad_output):\n        \"\"\"\n        In the backward pass we receive a Tensor containing the gradient of the loss\n        with respect to the output, and we need to compute the gradient of the loss\n        with respect to the input.\n        \"\"\"\n        input, = ctx.saved_tensors\n        return grad_output * 1.5 * (5 * input ** 2 - 1)\n\n\ndef legendre_network():\n    dtype = torch.float\n    device = torch.device(\"cpu\")\n    # device = torch.device(\"cuda:0\")  # Uncomment this to run on GPU\n\n    # Create Tensors to hold input and outputs.\n    # By default, requires_grad=False, which indicates that we do not need to\n    # compute gradients with respect to these Tensors during the backward pass.\n    x = torch.linspace(-math.pi, math.pi, 2000, device=device, dtype=dtype)\n    y = torch.sin(x)\n\n    # Create random Tensors for weights. For this example, we need\n    # 4 weights: y = a + b * P3(c + d * x), these weights need to be initialized\n    # not too far from the correct result to ensure convergence.\n    # Setting requires_grad=True indicates that we want to compute gradients with\n    # respect to these Tensors during the backward pass.\n    a = torch.full((), 0.0, device=device, dtype=dtype, requires_grad=True)\n    b = torch.full((), -1.0, device=device, dtype=dtype, requires_grad=True)\n    c = torch.full((), 0.0, device=device, dtype=dtype, requires_grad=True)\n    d = torch.full((), 0.3, device=device, dtype=dtype, requires_grad=True)\n\n    learning_rate = 5e-6\n    for t in range(2000):\n        # To apply our Function, we use Function.apply method. We alias this as 'P3'.\n        P3 = LegendrePolynomial3.apply\n\n        # Forward pass: compute predicted y using operations; we compute\n        # P3 using our custom autograd operation.\n        y_pred = a + b * P3(c + d * x)\n\n        # Compute and print loss\n        loss = (y_pred - y).pow(2).sum()\n        if t % 100 == 99:\n            print(t, loss.item())\n\n            # Use autograd to compute the backward pass.\n        loss.backward()\n\n        # Update weights using gradient descent\n        with torch.no_grad():\n            a -= learning_rate * a.grad\n            b -= learning_rate * b.grad\n            c -= learning_rate * c.grad\n            d -= learning_rate * d.grad\n\n            # Manually zero the gradients after updating weights\n            a.grad = None\n            b.grad = None\n            c.grad = None\n            d.grad = None\n\n    print(f'Result: y = {a.item()} + {b.item()} * P3({c.item()} + {d.item()} x)')\n\n\ndef nn_network():\n    # Create Tensors to hold input and outputs.\n    x = torch.linspace(-math.pi, math.pi, 2000)\n    y = torch.sin(x)\n\n    # For this example, the output y is a linear function of (x, x^2, x^3), so\n    # we can consider it as a linear layer neural network. Let's prepare the\n    # tensor (x, x^2, x^3).\n    p = torch.tensor([1, 2, 3])\n    xx = x.unsqueeze(-1).pow(p)\n\n    # In the above code, x.unsqueeze(-1) has shape (2000, 1), and p has shape\n    # (3,), for this case, broadcasting semantics will apply to obtain a tensor\n    # of shape (2000, 3)\n\n    # Use the nn package to define our model as a sequence of layers. nn.Sequential\n    # is a Module which contains other Modules, and applies them in sequence to\n    # produce its output. The Linear Module computes output from input using a\n    # linear function, and holds internal Tensors for its weight and bias.\n    # The Flatten layer flatens the output of the linear layer to a 1D tensor,\n    # to match the shape of `y`.\n    model = torch.nn.Sequential(\n        torch.nn.Linear(3, 1),\n        torch.nn.Flatten(0, 1)\n    )\n\n    # The nn package also contains definitions of popular loss functions; in this\n    # case we will use Mean Squared Error (MSE) as our loss function.\n    loss_fn = torch.nn.MSELoss(reduction='sum')\n\n    learning_rate = 1e-6\n    for t in range(2000):\n\n        # Forward pass: compute predicted y by passing x to the model. Module objects\n        # override the __call__ operator so you can call them like functions. When\n        # doing so you pass a Tensor of input data to the Module and it produces\n        # a Tensor of output data.\n        y_pred = model(xx)\n\n        # Compute and print loss. We pass Tensors containing the predicted and true\n        # values of y, and the loss function returns a Tensor containing the\n        # loss.\n        loss = loss_fn(y_pred, y)\n        if t % 100 == 99:\n            print(t, loss.item())\n\n        # Zero the gradients before running the backward pass.\n        model.zero_grad()\n\n        # Backward pass: compute gradient of the loss with respect to all the learnable\n        # parameters of the model. Internally, the parameters of each Module are stored\n        # in Tensors with requires_grad=True, so this call will compute gradients for\n        # all learnable parameters in the model.\n        loss.backward()\n\n        # Update the weights using gradient descent. Each parameter is a Tensor, so\n        # we can access its gradients like we did before.\n        with torch.no_grad():\n            for param in model.parameters():\n                param -= learning_rate * param.grad\n\n    # You can access the first layer of `model` like accessing the first item of a list\n    linear_layer = model[0]\n\n    # For linear layer, its parameters are stored as `weight` and `bias`.\n    print(f'Result: y = {linear_layer.bias.item()} + {linear_layer.weight[:, 0].item()} x + '\n          f'{linear_layer.weight[:, 1].item()} x^2 + {linear_layer.weight[:, 2].item()} x^3')\n\n\ndef optim_network():\n    # Create Tensors to hold input and outputs.\n    x = torch.linspace(-math.pi, math.pi, 2000)\n    y = torch.sin(x)\n\n    # Prepare the input tensor (x, x^2, x^3).\n    p = torch.tensor([1, 2, 3])\n    xx = x.unsqueeze(-1).pow(p)\n\n    # Use the nn package to define our model and loss function.\n    model = torch.nn.Sequential(\n        torch.nn.Linear(3, 1),\n        torch.nn.Flatten(0, 1)\n    )\n    loss_fn = torch.nn.MSELoss(reduction='sum')\n\n    # Use the optim package to define an Optimizer that will update the weights of\n    # the model for us. Here we will use RMSprop; the optim package contains many other\n    # optimization algorithms. The first argument to the RMSprop constructor tells the\n    # optimizer which Tensors it should update.\n    learning_rate = 1e-3\n    optimizer = torch.optim.RMSprop(model.parameters(), lr=learning_rate)\n\n    for t in range(2000):\n        # Forward pass: compute predicted y by passing x to the model.\n        y_pred = model(xx)\n\n        # Compute and print loss.\n        loss = loss_fn(y_pred, y)\n        if t % 100 == 99:\n            print(t, loss.item())\n\n        # Before the backward pass, use the optimizer object to zero all of the\n        # gradients for the variables it will update (which are the learnable\n        # weights of the model). This is because by default, gradients are\n        # accumulated in buffers( i.e, not overwritten) whenever .backward()\n        # is called. Checkout docs of torch.autograd.backward for more details.\n        optimizer.zero_grad()\n\n        # Backward pass: compute gradient of the loss with respect to model\n        # parameters\n        loss.backward()\n\n        # Calling the step function on an Optimizer makes an update to its\n        # parameters\n        optimizer.step()\n\n    linear_layer = model[0]\n    print(\n        f'Result: y = {linear_layer.bias.item()} + {linear_layer.weight[:, 0].item()} x + '\n        f'{linear_layer.weight[:, 1].item()} x^2 + {linear_layer.weight[:, 2].item()} x^3')\n\n\nclass Polynomial3(torch.nn.Module):\n\n    def __init__(self):\n        \"\"\"\n        In the constructor we instantiate four parameters and assign them as\n        member parameters.\n        \"\"\"\n        super().__init__()\n        self.a = torch.nn.Parameter(torch.randn(()))\n        self.b = torch.nn.Parameter(torch.randn(()))\n        self.c = torch.nn.Parameter(torch.randn(()))\n        self.d = torch.nn.Parameter(torch.randn(()))\n\n    def forward(self, x):\n        \"\"\"\n        In the forward function we accept a Tensor of input data and we must return\n        a Tensor of output data. We can use Modules defined in the constructor as\n        well as arbitrary operators on Tensors.\n        \"\"\"\n        return self.a + self.b * x + self.c * x ** 2 + self.c * x ** 2 + self.d * x ** 3\n\n    def string(self):\n        \"\"\"\n        Just like any class in Python, you can also define custom method on PyTorch modules\n        \"\"\"\n\n        return f'y = {self.a.item()} + {self.b.item()} x + {self.c.item()} x^2 + {self.d.item()} x^3'\n\ndef custom_nn_network():\n\n    # Create Tensors to hold input and outputs.\n    x = torch.linspace(-math.pi, math.pi, 2000)\n    y = torch.sin(x)\n\n    # Construct our model by instantiating the class defined above\n    model = Polynomial3()\n\n    # Construct our loss function and an Optimizer. The call to model.parameters()\n    # in the SGD constructor will contain the learnable parameters of the nn.Linear\n    # module which is members of the model.\n    criterion = torch.nn.MSELoss(reduction='sum')\n    optimizer = torch.optim.SGD(model.parameters(), lr=1e-6)\n\n    for t in range(2000):\n        # Forward pass: Compute predicted y by passing x to the model\n        y_pred = model(x)\n\n        # Compute and print loss\n        loss = criterion(y_pred, y)\n        if t % 100 == 99:\n            print(t, loss.item())\n\n        # Zero gradients, perform a backward pass, and update the weights.\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n\n    print(f'Result: {model.string()}')\n\n\nclass DynamicNet(torch.nn.Module):\n\n    def __init__(self):\n        \"\"\"\n        In the constructor we instantiate five parameters and assign them as members.\n        \"\"\"\n        super().__init__()\n        self.a = torch.nn.Parameter(torch.randn(()))\n        self.b = torch.nn.Parameter(torch.randn(()))\n        self.c = torch.nn.Parameter(torch.randn(()))\n        self.d = torch.nn.Parameter(torch.randn(()))\n        self.e = torch.nn.Parameter(torch.randn(()))\n\n    def forward(self, x):\n        \"\"\"\n        For the forward pass of the model, we randomly choose either 4, 5\n        and reuse the e parameter to compute the contribution of these orders.\n\n        Since each forward pass builds a dynamic computation graph, we can use normal\n        Python control-flow operators like loops or conditional statements when\n        defining the forward pass of the model.\n\n        Here we also see that it is perfectly safe to reuse the same parameter many\n        times when defining a computational graph.\n        \"\"\"\n        y = self.a + self.b * x + self.c * x ** 2 + self.d * x ** 3\n        for exp in range(4, random.randint(4, 6)):\n            y = y + self.e * x ** exp\n        return y\n\n    def string(self):\n        \"\"\"\n        Just like any class in Python, you can also define custom method on PyTorch modules\n        \"\"\"\n        return f'y = {self.a.item()} + {self.b.item()} x + {self.c.item()} x^2 + ' \\\n               f'{self.d.item()} x^3 + {self.e.item()} x^4 ? + {self.e.item()} x^5 ?'\n\n\ndef weight_sharing_network():\n\n    # Create Tensors to hold input and outputs.\n    x = torch.linspace(-math.pi, math.pi, 2000)\n    y = torch.sin(x)\n\n    # Construct our model by instantiating the class defined above\n    model = DynamicNet()\n\n    # Construct our loss function and an Optimizer. Training this strange model with\n    # vanilla stochastic gradient descent is tough, so we use momentum\n    criterion = torch.nn.MSELoss(reduction='sum')\n    optimizer = torch.optim.SGD(model.parameters(), lr=1e-8, momentum=0.9)\n    for t in range(30000):\n        # Forward pass: Compute predicted y by passing x to the model\n        y_pred = model(x)\n\n        # Compute and print loss\n        loss = criterion(y_pred, y)\n        if t % 2000 == 1999:\n            print(t, loss.item())\n\n        # Zero gradients, perform a backward pass, and update the weights.\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n\n    print(f'Result: {model.string()}')\n\n\ndef main():\n    numpy_network()\n    pytorch_network()\n    autograd_network()\n    legendre_network()\n    nn_network()\n    optim_network()\n    custom_nn_network()\n    weight_sharing_network()\n\n\nstart = time.time()\nmain()\nend = time.time()\ntotal_time = end - start\nprint(\"%s: Total time = %f seconds\" % (time.strftime(\"%Y/%m/%d-%H:%M:%S\"), total_time))\n", "meta": {"hexsha": "4ccab1d6fc0190aa8538dbad1f562dbc315e2f7b", "size": 18165, "ext": "py", "lang": "Python", "max_stars_repo_path": "pytorch_blitz/pytorch_with_examples.py", "max_stars_repo_name": "franpena-kth/learning-deep-learning", "max_stars_repo_head_hexsha": "9cd287b602dee1358672c4189445721a9c24f107", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pytorch_blitz/pytorch_with_examples.py", "max_issues_repo_name": "franpena-kth/learning-deep-learning", "max_issues_repo_head_hexsha": "9cd287b602dee1358672c4189445721a9c24f107", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pytorch_blitz/pytorch_with_examples.py", "max_forks_repo_name": "franpena-kth/learning-deep-learning", "max_forks_repo_head_hexsha": "9cd287b602dee1358672c4189445721a9c24f107", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.696969697, "max_line_length": 101, "alphanum_fraction": 0.6186622626, "include": true, "reason": "import numpy", "num_tokens": 4543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561685659695, "lm_q2_score": 0.9005297834483234, "lm_q1q2_score": 0.8724838356712847}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 29 18:59:52 2019\n\n@author: Marcus\n\nScript da Tarefa 4 de Bases Computacionais\n\n\"\"\"\n\n\n\"\"\"\n1) Calculo do volume de uma esfera com raio R\n\"\"\"\n\nimport numpy as np #importar biblioteca de equações\nprint('1) Calculo do volume de uma esfera com raio R')\nprint()\nR1 = 0.32 #raio da esfera\nVR1 = (4* np.pi * (R1**3))/3 #fórmula de cálculo de volume\nprint('R1 =',R1,'m') #exibir raio no console\nprint('VR1 =',round (VR1, 3),'m³') #exibir volume no console\nprint()\n\nR2 = 1 \nVR2 = (4* np.pi * (R2**3))/3 \nprint('R2 =',R2,'m')\nprint('VR2 =',round (VR2, 3),'m³')\nprint()\n\nR3 = 1.9\nVR3 = (4* np.pi * (R3**3))/3 \nprint('R3 =',R3,'m')\nprint('VR3 =',round (VR3, 3),'m³')\nprint()\nprint()\nprint()\n\n\"\"\"\n2) Temperatura em Fahrenheit dada a temperatura em Celcius na variável T\n\"\"\"\nprint('2) Temperatura em Fahrenheit dada a temperatura em Celcius')\nprint()\nT1 = -10 #Temperatura em Celcius\nF1 = T1 * (9/5) + 32 #Fórmula de convesão para F\nprint('T1 =',T1,'°C') #Exibir T em celcius no console\nprint('F1 =', F1, '°F') #Exibir temp. convertida\nprint()\n\nT2 = 30\nF2 = T2 * (9/5) + 32\nprint('T2 =',T2,'°C')\nprint('F2 =', F2, '°F')\nprint()\n\nT3 = 5\nF3 = T3 * (9/5) + 32\nprint('T3 =',T3,'°C')\nprint('F3 =', F3, '°F')\nprint()\nprint()\nprint()\n\n\n\"\"\"\n3) Lado c de um triângulo com a b e θ conhecidos \n\"\"\"\n\nprint('3)Definição do lado c de um triângulo com os lados a e b e o ângulo θ conhecidos')\nprint()\nprint('Triangulo 1')\na1 = 1 #Lado a do triangulo\nb1 = 2 #Lado b do triangulo\nθ1 = 30 #angulo dos lados a e b triangulo\nrad1 = np.deg2rad(θ1) #conversão do angulo para radianos\nc1 = np.sqrt(a1**2 + b1**2 - (a1 * b1 * 2 * np.cos(rad1))) #aplicação da lei dos cossenos\nprint('a =',a1)\nprint('b =',b1)\nprint('θ=',θ1,'°')\nprint('c =',round (c1, 3))\nprint()\n\nprint('Triangulo 2')\na2 = 3\nb2 = 1\nθ2 = 45\nrad2 = np.deg2rad(θ2)\nc2 = np.sqrt(a2**2 + b2**2 - (a2 * b2 * 2 * np.cos(rad2)))\nprint('a =',a2)\nprint('b =',b2)\nprint('θ=',θ2,'°')\nprint('c =',round (c2, 3))\nprint()\n\nprint('Triangulo 3')\na3 = 10\nb3 = 11\nθ3 = 15\nrad3 = np.deg2rad(θ3)\nc3 = np.sqrt(a3**2 + b3**2 - (a3 * b3 * 2 * np.cos(rad3)))\nprint('a =',a3)\nprint('b =',b3)\nprint('θ=',θ3,'°')\nprint('c =',round (c3, 3))\nprint()\nprint()\nprint()\n\n\n\"\"\"3) Sequencia de Fibonacci\"\"\"\n\nprint('3) Identificação do n-ésimo número na sequência de Fibonacci')\nprint()\nn1 = 30 # número na sequencia\nf1 = np.floor(((((1 + np.sqrt(5)) / 2)**n1) - (((1 - np.sqrt(5)) / 2)**n1)) / np.sqrt(5)) #cálculo para valor da sequencia\nprint('n =',n1)\nprint('F =',f1)\nprint()\n\nn2 = 31\nf2 = np.floor(((((1 + np.sqrt(5)) / 2)**n2) - (((1 - np.sqrt(5)) / 2)**n2)) / np.sqrt(5)) \nprint('n =',n2)\nprint('F =',f2)\nprint()\n\nn3 = 32\nf3 = np.floor(((((1 + np.sqrt(5)) / 2)**n3) - (((1 - np.sqrt(5)) / 2)**n3)) / np.sqrt(5)) \nprint('n =',n3)\nprint('F =',f3)\nprint()\n\n\"\"\"\nFim do Script\n\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "d08984990d07868c7cc8a3d1331b43da062dd220", "size": 2841, "ext": "py", "lang": "Python", "max_stars_repo_path": "vol_geometry.py", "max_stars_repo_name": "MarcusLucinda/UFABC---Q1BCC", "max_stars_repo_head_hexsha": "4fcaf5f50ba6212c6c0d69e0b2e20658c100dd76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-17T17:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-17T17:40:09.000Z", "max_issues_repo_path": "vol_geometry.py", "max_issues_repo_name": "marcusbonifacio/UFABC---Q1BCC", "max_issues_repo_head_hexsha": "4fcaf5f50ba6212c6c0d69e0b2e20658c100dd76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vol_geometry.py", "max_forks_repo_name": "marcusbonifacio/UFABC---Q1BCC", "max_forks_repo_head_hexsha": "4fcaf5f50ba6212c6c0d69e0b2e20658c100dd76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.9810126582, "max_line_length": 122, "alphanum_fraction": 0.5843013024, "include": true, "reason": "import numpy", "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561667674652, "lm_q2_score": 0.9005297847831082, "lm_q1q2_score": 0.8724838353448926}}
{"text": "import numpy as np\n\nclass BayesianModel():\n    def __init__(self, alpha=1e-5, beta=1e-5):\n        \"\"\"\n        Construction of Bayesian model.\n        \n        Args:\n            alpha: Single value parameter.\n            beta: Single value parameter.\n            m: Mean of the posterior distribution.\n            S: Covariance matrix of the posterior distribution.\n        \"\"\"\n        self.alpha = alpha\n        self.beta = beta\n        self.m = None\n        self.S = None\n\n    def posterior(self, phi, t):\n        \"\"\"\n        Computes mean and covariance matrix of the posterior distribution.\n\n        Args:\n            phi: Design matrix (N x M).\n            t: Target vector (N).\n\n        Returns:\n            m: Mean of the posterior distribution (M).\n            S: Covariance matrix of the posterior distribution (M x M).\n            S_inv: Inverse of S (M x M).\n        \"\"\"\n        S_inv = self.alpha * np.eye(phi.shape[1]) + self.beta * phi.T.dot(phi) # 1.72\n        S = np.linalg.inv(S_inv)\n        m = self.beta * S.dot(phi.T).dot(t) # 1.70\n        return m, S, S_inv\n\n\n    def fit(self, phi, t, max_iter=200, rtol=1e-12, verbose=False):\n        \"\"\"\n        Jointly infers the posterior sufficient statistics and optimal values \n        for alpha and beta by maximizing the log marginal likelihood.\n        \n        Args:\n            phi: Design matrix (N x M).\n            t: Target value array (N x 1).\n            max_iter: Maximum number of iterations.\n            rtol: Convergence criterion.\n            \n        Returns:\n            posterior mean, posterior covariance.\n        \"\"\"\n        N, M = phi.shape\n        eigen_0 = np.linalg.eigvalsh(phi.T.dot(phi))\n        for iter in range(max_iter):\n            pre_beta = self.beta\n            pre_alpha = self.alpha\n            eigen = eigen_0 * self.beta\n            m, S, S_inv = self.posterior(phi, t)\n            gamma = np.sum(eigen / (eigen + self.alpha))\n            self.alpha = gamma / np.sum(m ** 2)\n            beta_inv = 1 / (N - gamma) * np.sum((t - phi.dot(m)) ** 2)\n            self.beta = 1 / beta_inv\n            if np.isclose(pre_alpha, self.alpha, rtol=rtol) and np.isclose(pre_beta, self.beta, rtol=rtol):\n                if verbose:\n                    print(f'alpha:{self.alpha} beta:{self.beta}')\n                    print(f'Convergence after {iter + 1} iterations.')\n                self.m, self.S = m, S\n                return\n            if verbose:\n                    print(f'alpha:{self.alpha} beta:{self.beta}')\n        if verbose:\n            print(f'Stopped after {max_iter} iterations.')\n        self.m, self.S = m, S\n\n\n    def predict(self, phi_):\n        \"\"\"\n        Computes mean and variances of the posterior predictive distribution.\n\n        Args:\n            phi_: Design matrix of test input x (M).\n\n        Returns:\n            y: Mean of the posterior predictive distribution.\n            y_var: Variances of the posterior predictive distribution (M x M).\n        \"\"\"\n        y = phi_.dot(self.m) # pick the mean of the distribution to predict the target\n        y_var = 1 / self.beta + np.sum(phi_.dot(self.S) * phi_, axis=1)   # 1.71\n        return y, y_var", "meta": {"hexsha": "d127110d2599ab4c2979e3cffd5305aed1a6d46f", "size": 3169, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/bayesian.py", "max_stars_repo_name": "Bluefissure/ECE568-hw3", "max_stars_repo_head_hexsha": "2ad298fa86e42b19f2b6f670f2cc1df0a04b8ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bayesian.py", "max_issues_repo_name": "Bluefissure/ECE568-hw3", "max_issues_repo_head_hexsha": "2ad298fa86e42b19f2b6f670f2cc1df0a04b8ebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bayesian.py", "max_forks_repo_name": "Bluefissure/ECE568-hw3", "max_forks_repo_head_hexsha": "2ad298fa86e42b19f2b6f670f2cc1df0a04b8ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.606741573, "max_line_length": 107, "alphanum_fraction": 0.5386557274, "include": true, "reason": "import numpy", "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885302, "lm_q2_score": 0.907312215721497, "lm_q1q2_score": 0.8724113728113321}}
{"text": "import matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\nimport torch\nimport torch.optim as optim\nimport utils\nimport math\n\n\nprint('定义 rmsprop')\neta = 0.4\ngamma = 0.9\n\n\ndef rmsprop_2d(x1, x2, s1, s2):\n    g1, g2, eps = 0.2 * x1, 4 * x2, 1e-6\n    s1 = gamma * s1 + (1 - gamma) * g1 ** 2\n    s2 = gamma * s2 + (1 - gamma) * g2 ** 2\n    x1 -= eta / math.sqrt(s1 + eps) * g1\n    x2 -= eta / math.sqrt(s2 + eps) * g2\n    return x1, x2, s1, s2\n\n\ndef f_2d(x1, x2):\n    return 0.1 * x1 ** 2 + 2 * x2 ** 2\n\n\nprint('lr= 0.4 的轨迹')\nutils.show_trace_2d(f_2d, utils.train_2d(rmsprop_2d))\n\nprint('自行实现 RMSprop')\n\nfeatures, labels = utils.get_nasa_data()\n\n\ndef init_rmsprop_states():\n    s_w = torch.zeros((features.shape[1], 1), dtype=torch.float32)\n    s_b = torch.zeros(1, dtype=torch.float32)\n    return (s_w, s_b)\n\n\ndef rmsprop(params, states, hyperparams):\n    eps = 1e-6\n    gamma = hyperparams['gamma']\n    for p, s in zip(params, states):\n        s.data = gamma * s.data + (1-gamma) * (p.grad.data)**2\n        p.data -= hyperparams['lr'] * p.grad.data / torch.sqrt(s + eps)\n\n\nprint('RMSProp 进行优化')\nutils.train_opt(rmsprop, init_rmsprop_states(), {'lr': 0.1, 'gamma': 0.9}, features, labels)\n\nprint('简洁实现')\nutils.train_opt_pytorch(optim.RMSprop, {'lr': 0.1, 'alpha': 0.9}, features, labels)\n", "meta": {"hexsha": "b1c2980e7590a6f661ad1af2bfdea61b73094c90", "size": 1333, "ext": "py", "lang": "Python", "max_stars_repo_path": "d2l/43_rmsprop.py", "max_stars_repo_name": "wdxtub/deep-learning-note", "max_stars_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2019-03-27T20:17:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T23:20:31.000Z", "max_issues_repo_path": "d2l/43_rmsprop.py", "max_issues_repo_name": "wdxtub/deep-learning-note", "max_issues_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "d2l/43_rmsprop.py", "max_forks_repo_name": "wdxtub/deep-learning-note", "max_forks_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-03-31T10:28:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:25:40.000Z", "avg_line_length": 23.3859649123, "max_line_length": 92, "alphanum_fraction": 0.6301575394, "include": true, "reason": "import numpy", "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321452198369, "lm_q2_score": 0.9046505402422644, "lm_q1q2_score": 0.8723739226984595}}
{"text": "import numpy as np\nimport scipy.sparse\nimport scipy.optimize\n\n\ndef softmax_cost(theta, num_classes, input_size, lambda_, data, labels):\n    \"\"\"\n\n    :param theta:\n    :param num_classes: the number of classes\n    :param input_size: the size N of input vector\n    :param lambda_: weight decay parameter\n    :param data: the N x M input matrix, where each column corresponds\n                 a single test set\n    :param labels: an M x 1 matrix containing the labels for the input data\n    \"\"\"\n    m = data.shape[1]\n    theta = theta.reshape(num_classes, input_size)\n    theta_data = theta.dot(data)\n    theta_data = theta_data - np.max(theta_data)\n    prob_data = np.exp(theta_data) / np.sum(np.exp(theta_data), axis=0)\n    indicator = scipy.sparse.csr_matrix((np.ones(m), (labels, np.array(range(m)))))\n    indicator = np.array(indicator.todense())\n    cost = (-1 / m) * np.sum(indicator * np.log(prob_data)) + (lambda_ / 2) * np.sum(theta * theta)\n\n    grad = (-1 / m) * (indicator - prob_data).dot(data.transpose()) + lambda_ * theta\n\n    return cost, grad.flatten()\n\n\ndef softmax_predict(model, data):\n    # model - model trained using softmaxTrain\n    # data - the N x M input matrix, where each column data(:, i) corresponds to\n    #        a single test set\n    #\n    # Your code should produce the prediction matrix\n    # pred, where pred(i) is argmax_c P(y(c) | x(i)).\n\n    opt_theta, input_size, num_classes = model\n    opt_theta = opt_theta.reshape(num_classes, input_size)\n\n    prod = opt_theta.dot(data)\n    pred = np.exp(prod) / np.sum(np.exp(prod), axis=0)\n    pred = pred.argmax(axis=0)\n\n    return pred\n\n\ndef softmax_train(input_size, num_classes, lambda_, data, labels, options={'maxiter': 400, 'disp': True}):\n    #softmaxTrain Train a softmax model with the given parameters on the given\n    # data. Returns softmaxOptTheta, a vector containing the trained parameters\n    # for the model.\n    #\n    # input_size: the size of an input vector x^(i)\n    # num_classes: the number of classes\n    # lambda_: weight decay parameter\n    # input_data: an N by M matrix containing the input data, such that\n    #            inputData(:, c) is the cth input\n    # labels: M by 1 matrix containing the class labels for the\n    #            corresponding inputs. labels(c) is the class label for\n    #            the cth input\n    # options (optional): options\n    #   options.maxIter: number of iterations to train for\n\n    # Initialize theta randomly\n    theta = 0.005 * np.random.randn(num_classes * input_size)\n\n    J = lambda x: softmax_cost(x, num_classes, input_size, lambda_, data, labels)\n\n    result = scipy.optimize.minimize(J, theta, method='L-BFGS-B', jac=True, options=options)\n\n    print(result)\n    # Return optimum theta, input size & num classes\n    opt_theta = result.x\n\n    return opt_theta, input_size, num_classes\n\n", "meta": {"hexsha": "90f368a87ae997004b11e175ce3a1836c5d94f97", "size": 2844, "ext": "py", "lang": "Python", "max_stars_repo_path": "used/unused/softmax.py", "max_stars_repo_name": "shifvb/GraduationProject", "max_stars_repo_head_hexsha": "08166b49c329014bf852faafa14db14a6231370a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-04-27T15:25:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-27T15:25:01.000Z", "max_issues_repo_path": "used/unused/softmax.py", "max_issues_repo_name": "shifvb/Undergraduate_GraduationProject", "max_issues_repo_head_hexsha": "08166b49c329014bf852faafa14db14a6231370a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "used/unused/softmax.py", "max_forks_repo_name": "shifvb/Undergraduate_GraduationProject", "max_forks_repo_head_hexsha": "08166b49c329014bf852faafa14db14a6231370a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4615384615, "max_line_length": 106, "alphanum_fraction": 0.6722925457, "include": true, "reason": "import numpy,import scipy", "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970239906914561, "lm_q2_score": 0.8991213806488609, "lm_q1q2_score": 0.8723634446656424}}
{"text": "# ----------\n# \n# As with the previous perceptron exercises, you will complete some of the core\n# methods of a sigmoid unit class.\n#\n# There are two functions for you to finish:\n# First, in activate(), write the sigmoid activation function.\n# Second, in update(), write the gradient descent update rule.\n# \n# ----------\n\nimport numpy as np\n\n\nclass Sigmoid:\n    \"\"\"\n    This class models an artificial neuron with sigmoid activation function.\n    \"\"\"\n\n    def __init__(self, weights = np.array([1])):\n        \"\"\"\n        Initialize weights based on input arguments. Note that no type-checking\n        is being performed here for simplicity of code.\n        \"\"\"\n        self.weights = weights\n\n        # NOTE: You do not need to worry about these two attribues for this\n        # programming quiz, but these will be useful for if you want to create\n        # a network out of these sigmoid units!\n        self.last_input = 0 # strength of last input\n        self.delta      = 0 # error signal\n\n    def logistic(self, x):\n        return 1/(1 + np.exp(-x))\n\n    def activate(self, values):\n        \"\"\"\n        Takes in @param values, a list of numbers equal to length of weights.\n        @return the output of a sigmoid unit with given inputs based on unit\n        weights.\n        \"\"\"\n        \n        # YOUR CODE HERE\n        \n        # First calculate the strength of the input signal.\n        strength = np.dot(values, self.weights)\n        self.last_input = strength\n        \n        # TODO: Modify strength using the sigmoid activation function and\n        # return as output signal.\n        # HINT: You may want to create a helper function to compute the\n        #   logistic function since you will need it for the update function.\n        result = self.logistic(strength)\n        \n        return result\n            \n    def update(self, values, train, eta=.1):\n        \"\"\"\n        Takes in a 2D array @param values consisting of a LIST of inputs and a\n        1D array @param train, consisting of a corresponding list of expected\n        outputs. Updates internal weights according to gradient descent using\n        these values and an optional learning rate, @param eta.\n        \"\"\"\n\n        # TODO: for each data point...\n        for X, y_true in zip(values, train):\n            # obtain the output signal for that point\n            y_pred = self.activate(X)\n\n            # YOUR CODE HERE\n\n            # TODO: compute derivative of logistic function at input strength\n            # Recall: d/dx logistic(x) = logistic(x)*(1-logistic(x))\n            slope = y_pred * (1 - y_pred)\n            # TODO: update self.weights based on learning rate, signal accuracy,\n            # function slope (derivative) and input value\n            self.weights += eta*(y_true - y_pred) * slope *X\n\ndef test():\n    \"\"\"\n    A few tests to make sure that the perceptron class performs as expected.\n    Nothing should show up in the output if all the assertions pass.\n    \"\"\"\n    def sum_almost_equal(array1, array2, tol = 1e-5):\n        return sum(abs(array1 - array2)) < tol\n\n    u1 = Sigmoid(weights=[3,-2,1])\n    assert abs(u1.activate(np.array([1,2,3])) - 0.880797) < 1e-5\n    \n    u1.update(np.array([[1,2,3]]),np.array([0]))\n    assert sum_almost_equal(u1.weights, np.array([2.990752, -2.018496, 0.972257]))\n\n    u2 = Sigmoid(weights=[0,3,-1])\n    u2.update(np.array([[-3,-1,2],[2,1,2]]),np.array([1,0]))\n    assert sum_almost_equal(u2.weights, np.array([-0.030739, 2.984961, -1.027437]))\n\nif __name__ == \"__main__\":\n    test()\n", "meta": {"hexsha": "b9504bbacedde7b344dde3186cb1a9821c74fd00", "size": 3520, "ext": "py", "lang": "Python", "max_stars_repo_path": "MLND_Notes/sigmoid_activation_grad_desc.py", "max_stars_repo_name": "KT12/Python", "max_stars_repo_head_hexsha": "bf28555f8f20bcb4ad76ff2f023e886d3556217c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-05-16T20:33:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-16T20:33:52.000Z", "max_issues_repo_path": "MLND_Notes/sigmoid_activation_grad_desc.py", "max_issues_repo_name": "KT12/python", "max_issues_repo_head_hexsha": "bf28555f8f20bcb4ad76ff2f023e886d3556217c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MLND_Notes/sigmoid_activation_grad_desc.py", "max_forks_repo_name": "KT12/python", "max_forks_repo_head_hexsha": "bf28555f8f20bcb4ad76ff2f023e886d3556217c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5555555556, "max_line_length": 83, "alphanum_fraction": 0.6176136364, "include": true, "reason": "import numpy", "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452772, "lm_q2_score": 0.9124361622627654, "lm_q1q2_score": 0.8722719566024241}}
{"text": "# Corresponde a la implementacion en python de algunos algoritmos \n# en el primer capitulo de Algorithms and Computations de Werner Krauth.\n\nimport numpy as np\n\ndef direct_pi(N):\n    N_hits = 0 \n    for i in range(N):\n        x = 2.0*(np.random.random()-0.5)\n        y = 2.0*(np.random.random()-0.5)\n        if(x**2 + y**2 < 1):\n            N_hits += 1\n    return N_hits\n\nprint('direct_pi(1000)',direct_pi(1000))\n\n\ndef markov_pi(N):\n    N_hits = 0\n    x = 1.0\n    y = 1.0\n    delta = 0.1\n    for i in range(N):\n        delta_x = delta * 2.0 * (np.random.random()-0.5)\n        delta_y = delta * 2.0 * (np.random.random()-0.5)\n        if(abs(x+delta_x)<1 and abs(y+delta_y)<1):\n            x += delta_x\n            y += delta_y\n        if (x**2 + y**2 < 1):\n            N_hits += 1\n    return N_hits\n\nprint('markov_pi(1000):', markov_pi(1000))\n\n\ndef markov_two_site(k, p_0=0.1, p_1=0.9):\n    def proba(m):\n        if(m==0): a = 0.5\n        if(m==1): a = 0.5\n        return a\n\n    if(k==0): l=1\n    if(k==1): l=0\n    \n    gamma = proba(l)/proba(k)\n    r = np.random.random()\n    if r < gamma:\n        k = l\n    return k\n\nprint('markov_two_site:')\nk = 0\nfor i in range(10):\n    k = markov_two_site(k)\n    print(k)\n\n\ndef reject_continous():\n    def proba_dens(x):\n        \"\"\"Corresponde a exp(-x) entre 0 y 1.\n        \"\"\"\n        norm = 1.0 - np.exp(-1)\n        return norm * np.exp(-x)\n    p_max = proba_dens(0)\n\n    x_rand = np.random.random()\n    gamma = np.random.random() * p_max\n    while gamma > proba_dens(x_rand) :\n            x_rand = np.random.random()\n            gamma = np.random.random() * p_max\n    return x_rand\n\nprint('reject_continous')\nfor i in range(10):\n    print(reject_continous())\n    \ndef gauss(sigma):\n    phi = np.random.random() * 2.0 * np.pi\n    gamma = -np.log(np.random.random())\n    r = sigma * np.sqrt(2.0 * gamma)\n    x = r * np.cos(phi)\n    y = r * np.sin(phi)\n    return x, y\n\nprint('gauss')\nfor i in range(10):\n    print(gauss(1.0))\n", "meta": {"hexsha": "1ffabd6a38b5a79fa5d5ce8a0e2e6de55bd32f9b", "size": 1966, "ext": "py", "lang": "Python", "max_stars_repo_path": "ejercicios/07/JaimeForero_Ejercicio7.py", "max_stars_repo_name": "oscarochoa1/FISI2028-201910", "max_stars_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-03T04:27:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T18:50:41.000Z", "max_issues_repo_path": "ejercicios/07/JaimeForero_Ejercicio7.py", "max_issues_repo_name": "oscarochoa1/FISI2028-201910", "max_issues_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ejercicios/07/JaimeForero_Ejercicio7.py", "max_forks_repo_name": "oscarochoa1/FISI2028-201910", "max_forks_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-01-23T10:44:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-04T00:05:40.000Z", "avg_line_length": 22.3409090909, "max_line_length": 72, "alphanum_fraction": 0.5417090539, "include": true, "reason": "import numpy", "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407175907054, "lm_q2_score": 0.8962513689768735, "lm_q1q2_score": 0.8722683254847045}}
{"text": "import numpy as np\r\nimport numpy.linalg as la\r\nimport time\r\nfrom ReadParticleData import read\r\n\r\ndef generate_low_rank(epsilon, max_t):\r\n    x, y = read()\r\n    ns = len(x)\r\n    nt = len(y)\r\n    A = np.zeros((nt, ns))\r\n    print(\"Data Read.\")\r\n\r\n    start = time.time()\r\n    for j in range(nt):\r\n        for i in range(ns):\r\n            A[j, i] = 1/la.norm(x[i]-y[j])**2\r\n    end = time.time()\r\n    print(\"A completed,   elapsed time is \" + str(int(end-start)) + \" seconds\")\r\n\r\n    start = time.time()\r\n    SVD = la.svd(A, full_matrices=False)\r\n    u, s, v = SVD\r\n    for k in (np.arange(len(s))+1)*10:\r\n        Ak = np.zeros((nt, ns))\r\n        for i in range(k):\r\n            Ak += s[i] * np.outer(u.T[i], v[i])\r\n        if la.norm(A-Ak) <= epsilon:\r\n            break\r\n        end = time.time()\r\n        if (end-start >= max_t):\r\n            print(\"Failed to converge within \" + str(max_t) + \" seconds\")\r\n            break\r\n\r\n    print(\"SVD completed, elapsed time is \" + str(int(end-start)) + \" seconds.\")\r\n    return x, A, Ak\r\n\r\ndef test(x, A, Ak):\r\n    w = np.zeros(len(x))\r\n    r = np.zeros(3)\r\n    for j in range(len(x)):\r\n        w[j] = 1/la.norm(x[j]-r)**2\r\n\r\n    bk = Ak@w\r\n    b = A@w\r\n\r\n    pred_accu = epsilon*la.norm(w)\r\n    real_accu = la.norm(bk-b)\r\n\r\n    pred_info = \"Predicted Error: {pa:8.4f}\"\r\n    real_info = \"Actual Error:    {ra:8.4f}\"\r\n    pred_info = pred_info.format(pa = pred_accu)\r\n    real_info = real_info.format(ra = real_accu)\r\n    print(pred_info)\r\n    print(real_info)\r\n\r\ndef total_illum(r, x, A):\r\n    b = 0\r\n    w = np.zeros(len(x))\r\n    for i in range(len(r)):\r\n        for j in range(len(x)):\r\n            w[j] = 1/la.norm(x[j]-r[i])**2\r\n        b += A@w\r\n\r\nepsilon = 0.1\r\nmax_t = 300\r\nnum_test = 1000\r\nx, A, Ak = generate_low_rank(epsilon, max_t)\r\ntest(x, A, Ak)\r\nr = np.random.rand(num_test, 3)*10\r\nstart = time.time()\r\ntotal_illum(r, x, A)\r\nend = time.time()\r\nprint(\"Raw calculation takes          \" + str(int(end-start)) + \" seconds.\")\r\nstart = time.time()\r\ntotal_illum(r, x, Ak)\r\nend = time.time()\r\nprint(\"Reduced rank calculation takes \" + str(int(end-start)) + \" seconds.\")\r\n", "meta": {"hexsha": "4eac0a08c521211b80ca2d6887ecf56672b27ce2", "size": 2119, "ext": "py", "lang": "Python", "max_stars_repo_path": "Scientific Computing Projects (Code Parts)/3/Problem 3/LowRankApprox.py", "max_stars_repo_name": "4ntongC/Scientific-Computing-MATH-GA-2043", "max_stars_repo_head_hexsha": "a0042d5f0a967376777a6e3c34113711f2fd6a30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Scientific Computing Projects (Code Parts)/3/Problem 3/LowRankApprox.py", "max_issues_repo_name": "4ntongC/Scientific-Computing-MATH-GA-2043", "max_issues_repo_head_hexsha": "a0042d5f0a967376777a6e3c34113711f2fd6a30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scientific Computing Projects (Code Parts)/3/Problem 3/LowRankApprox.py", "max_forks_repo_name": "4ntongC/Scientific-Computing-MATH-GA-2043", "max_forks_repo_head_hexsha": "a0042d5f0a967376777a6e3c34113711f2fd6a30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1666666667, "max_line_length": 81, "alphanum_fraction": 0.5365738556, "include": true, "reason": "import numpy", "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574669, "lm_q2_score": 0.9099070048165069, "lm_q1q2_score": 0.8721801945962403}}
{"text": "import numpy as np\n\n\"\"\"\nA2-Part-3: Implement the discrete Fourier transform (DFT)\n\nWrite a function that implements the discrete Fourier transform (DFT). Given a sequence x of length\nN, the function should return its DFT, its spectrum of length N with the frequency indexes ranging from 0 \nto N-1.\n\nThe input argument to the function is a numpy array x and the function should return a numpy array X which \nis of the DFT of x.\n\nEXAMPLE: If you run your function using x = np.array([1, 2, 3, 4]), the function shoulds return the following numpy array:\narray([10.0 + 0.0j,  -2. +2.0j,  -2.0 - 9.79717439e-16j, -2.0 - 2.0j])\n\nNote that you might not get an exact 0 in the output because of the small numerical errors due to the\nlimited precision of the data in your computer. Usually these errors are of the order 1e-15 depending\non your machine.\n\"\"\"\ndef DFT(x):\n    \"\"\"\n    Input:\n        x (numpy array) = input sequence of length N\n    Output:\n        The function should return a numpy array of length N\n        X (numpy array) = The N point DFT of the input sequence x\n    \"\"\"\n    ## Your code here\n    N = x.shape[-1]\n    X = np.zeros(N, dtype=np.complex)\n\n    for k in range(N):\n        s = np.exp(-1j * 2 * np.pi * k / N * np.arange(N))\n        X[k] = x.dot(s)\n\n    return X\n    \n", "meta": {"hexsha": "7a4797d47e3cfb43d92da79b1a3e48b290b7fa94", "size": 1285, "ext": "py", "lang": "Python", "max_stars_repo_path": "A2/A2Part3.py", "max_stars_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_stars_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A2/A2Part3.py", "max_issues_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_issues_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A2/A2Part3.py", "max_forks_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_forks_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8157894737, "max_line_length": 122, "alphanum_fraction": 0.6700389105, "include": true, "reason": "import numpy", "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.958537722550837, "lm_q2_score": 0.9099070048165069, "lm_q1q2_score": 0.872180188129868}}
{"text": "# The branch and bound algorithm (backtracking on steroids) for the knapsack 0-1 problem.\n# Branch and bound algorithm enhances the search bymalso pruning the recursion tree\n# as soon as the algorithm detects that it will not be able to improve the existing\n# optimal solution by expanding the partial one.\n# It uses an extra parameter (max_val) to store the maximum sum of values that could be \n# acquired by expanding a partial solution. If this value is smaller than the \n# existing optimal value, it will not continue expanding.\n# The item values and weights are provided through input lists.\n# The algorithm has exponential time complexity in the number of items: O(2^n)\n\n# import numpy as np\n\ndef knapsack(i, sol, val, opt_sol, opt_val, max_val, w_left, v, w, C):\n\t# Base case\n\tif i == len(sol):\n\t\t# Check if better than current best\n\t\tif val > opt_val:\n\t\t\t# Update optimal value and solution\n\t\t\topt_val = val\n\t\t\tfor k in range(0, len(sol)):\n\t\t\t\topt_sol[k] = sol[k]\n\telse:\n\t\t# Generate candidates\n\t\tfor k in range(0, 2):\n\t\t\t# Check capacity constraint (pruning)\n\t\t\tif k * w[i] <= w_left:\n\t\t\t\t# Update maximum possible value\n\t\t\t\tnew_max_val = max_val - (1 - k) * v[i]\n\t\t\t\t# Check if better than existing optimal value (pruning)\n\t\t\t\tif new_max_val > opt_val:\n\t\t\t\t\t# Expand partial solution\n\t\t\t\t\tsol[i] = k\n\t\t\t\t\t# Update remaining capacity\n\t\t\t\t\tw_left = w_left - k * w[i]\n\t\t\t\t\t# Update partial value\n\t\t\t\t\tval = val + k * v[i]\n\t\t\t\t\t# Expand partial solution\n\t\t\t\t\topt_val = knapsack(i + 1, sol, val, opt_sol, opt_val, new_max_val, w_left, v, w, C)\n\treturn opt_val\n \ndef print_solution(opt_sol, opt_val, v, w, C):\n\tn = len(opt_sol)\n\tk = 0\n\twhile k < n and opt_sol[k] == 0:\n\t\tk = k + 1\n\n\ttotal_weight = 0\n\tif k < n:\n\t\tprint ('(', w[k], ',', v[k], ')', sep='', end='')\n\t\ttotal_weight = total_weight + w[k]\n\t\tfor i in range(k + 1, n):\n\t\t\tif opt_sol[i] == 1:\n\t\t\t\ttotal_weight = total_weight + w[i]\n\t\t\t\tprint (' + ', sep='', end='')\n\t\t\t\tprint ('(', w[i], ',', v[i], ')', sep='', end='')\n\t\n\tprint(' => ', '(', total_weight, ',', opt_val, ')', sep='')\t\n\ndef knapsack_0_1_bnb(v, w, C):\n\tsol = [None] * len(v)\n\topt_sol = [None] * len(v)\n\topt_val = knapsack(0, sol, 0, opt_sol, 0, sum(v), C, v, w, C)\n\tprint_solution(opt_sol, opt_val, v, w, C)\n#\tprint(opt_val)\n\n# List of item values\nv = [7, 2, 10, 4]\n# List of item weights\nw = [3, 6, 9, 5]\n# Knapsack capacity\nC = 15\n# v, w = np.loadtxt(\"knapsack_dataset.txt\", unpack=True)\nknapsack_0_1_bnb(v, w, C)\n\n", "meta": {"hexsha": "d257b7c7c69a2045da18f3ff6599e7fc769c42e6", "size": 2443, "ext": "py", "lang": "Python", "max_stars_repo_path": "knapsack_0_1/knapsack_0_1_bnb.py", "max_stars_repo_name": "Qargo/Knapsack-Algorithm", "max_stars_repo_head_hexsha": "dac7781ab5ad17692f6a80fcf1fd4b66028db3eb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "knapsack_0_1/knapsack_0_1_bnb.py", "max_issues_repo_name": "Qargo/Knapsack-Algorithm", "max_issues_repo_head_hexsha": "dac7781ab5ad17692f6a80fcf1fd4b66028db3eb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "knapsack_0_1/knapsack_0_1_bnb.py", "max_forks_repo_name": "Qargo/Knapsack-Algorithm", "max_forks_repo_head_hexsha": "dac7781ab5ad17692f6a80fcf1fd4b66028db3eb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5733333333, "max_line_length": 89, "alphanum_fraction": 0.6438804748, "include": true, "reason": "import numpy", "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.905989829267587, "lm_q1q2_score": 0.8721720489755886}}
{"text": "import numpy as np\nimport scipy as sc\nfrom scipy.sparse import csc_matrix\n\n\ndef Tridiag(d,N):\n# ~ Matriz con diagonal d=[dsub,dmid,dsub] y dimensión N\n    diagSub = np.diag(np.repeat(d[0],N-1),-1)\n    diagMid = np.diag(np.repeat(d[1],N),0)\n    diagSup = np.diag(np.repeat(d[2],N-1),1)\n    return diagSub + diagMid + diagSup\n\n\ndef Mesh(Xlim, N, opt):\n\t# ~ Genera una malla uniforme de Xlim[0] a Xlim[1], con N puntos en el interior.\n\t# ~ la variable 'opt' indica si queremos el intervalo abierto o el cerrado.\n    x = np.linspace(Xlim[0],Xlim[1],N+2)\n    return x[1:-1] if ( opt == 'open' ) else x\n\n\ndef Solve(A,b):\n    if not(isinstance(A, sc.sparse.csc.csc_matrix)):\n        print(\"Advertencia: la matriz es mayor a 1000 y no es rala, se recomienda convertirla mediante csc_matrix\")\n        A = csc_matrix(A)\n        return sc.sparse.linalg.spsolve(A,b)\n    else:\n        return sc.sparse.linalg.spsolve(A,b)\n\n\n# Agustin Arias\ndef MatrizAInvertir_Implicito(tamaño, paso):\n    # tamaño es el tamaño de la matriz, paso es h\n    A = Tridiag([1, -2, 1], tamaño)\n    Identidad = sc.sparse.identity(tamaño)  # necesario para poder aplicar kron\n\n    matAInv = sc.sparse.kron(A, Identidad) + sc.sparse.kron(Identidad, A)\n    matAInv = matAInv/(paso**2)\n\n    return matAInv.toarray()\n\n\n# Tilman Goebel\ndef MatrizAInvertir_Implicito_Rectangulo(tamañoX, tamañoY, pasoX, pasoY, dt):\n    # tamañoX es la cantidad de filas, tamañoY la cantidad de columnas y pasoX y pasoY son hx y hy\n    AX = Tridiag([1, -2, 1], tamañoX)\n    AY = Tridiag([1, -2, 1], tamañoY)\n    IdentidadX = sc.sparse.identity(tamañoX)\n    IdentidadY = sc.sparse.identity(tamañoY)\n\n    matAInv = sc.sparse.kron(AX, IdentidadY)/(pasoX**2) + sc.sparse.kron(IdentidadX, AY)/(pasoY**2)\n    matAInv = dt * matAInv\n\n    return matAInv\n\ndef MatricesCBPer2D( Nx,Ny ):\n    Dx2 = Tridiag([1,-2,1],Nx)\n    Dx2[0,-1] = 1 #condiciones periódicas\n    Dx2[-1,0] = 1\n    Dy2 = Tridiag([1,-2,1],Ny)\n    Dy2[0,-1] = 1 #condiciones periódicas\n    Dy2[-1,0] = 1\n    return Dx2,Dy2\n", "meta": {"hexsha": "728b58a8c09c3c03af6817edf3298c406910248f", "size": 2017, "ext": "py", "lang": "Python", "max_stars_repo_path": "MateUBA_PDE.py", "max_stars_repo_name": "crisdesivo/MateUBA_PDE", "max_stars_repo_head_hexsha": "82663b2b87f7537913a8763b1a8d6ef403e39898", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MateUBA_PDE.py", "max_issues_repo_name": "crisdesivo/MateUBA_PDE", "max_issues_repo_head_hexsha": "82663b2b87f7537913a8763b1a8d6ef403e39898", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MateUBA_PDE.py", "max_forks_repo_name": "crisdesivo/MateUBA_PDE", "max_forks_repo_head_hexsha": "82663b2b87f7537913a8763b1a8d6ef403e39898", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0158730159, "max_line_length": 115, "alphanum_fraction": 0.6593951413, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731158685837, "lm_q2_score": 0.9059898216525933, "lm_q1q2_score": 0.8721720445555246}}
{"text": "\n# coding: utf-8\n\n# ## Elementwise Operations and Statistics.\n# In this section I will cover on Elementwise operations, Basic reductions, Broadcasting, and Sorting data. Arrays are important because they enable you to express batch operations on data without writing any for loops. This is usually called vectorization. Any arithmetic operations between equal-size arrays applies the operation elementwise:\n# ### Here are the main steps we will go through\n# * Element-wise operations\n#     * Elementwise operations\n#     * Basic reductions\n#     * Broadcasting\n#     * Sorting data\n# * Do some statistics on numpy\n# \n# This is just little illustration.\n# <img src=\"https://s3.amazonaws.com/dq-content/6/numpy_ndimensional.svg\">\n\n# #### Basic operations\n\n# In[1]:\n\n\nimport numpy as np\narr1 = np.array([[1,2,3],[4,5,6]])\narr2 = np.array([[7,8,9]])\n\n\n# In[2]:\n\n\n#elementwise add arr2 to arr1\nnp.add(arr1, arr2)\n\n\n# In[3]:\n\n\n#elementwise subtract arr2 from arr1\nnp.subtract(arr1, arr2)\n\n\n# In[4]:\n\n\n#elementwise multiply arr1 by arr2\nnp.multiply(arr1,arr2)\n\n\n# In[5]:\n\n\n#elementwise divide arr1 by arr2\nnp.divide(arr1, arr2)\n\n\n# In[6]:\n\n\n#elementwise raise arr1 raised to the power of arr2\nnp.power(arr1,arr2)\n\n\n# In[7]:\n\n\n#returns True if the arrays have the same elements and shape\nnp.array_equal(arr1,arr2)\n\n\n# In[9]:\n\n\n#square root of each element in the array\nnp.sqrt(arr1)\n\n\n# In[26]:\n\n\n#Transcendental functions:\n#sine of each element in the array\nnp.sin(arr1)\n\n\n# In[11]:\n\n\n#natural log of each element in the array\nnp.log(arr1)\n\n\n# In[12]:\n\n\n#absolute value of each element in the array\nnp.abs(arr1)\n\n\n# In[24]:\n\n\narr = np.random.random(9)\nprint(\"original array:\\n \", arr)\n#rounds up to the nearest int\nnp.ceil(arr)\n\n\n# In[22]:\n\n\n#rounds down to the nearest int\nnp.floor(arr)\n\n\n# In[23]:\n\n\n#rounds to the nearest int\nnp.round(arr)\n\n\n# In[25]:\n\n\n#Logical operations:\na = np.array([1, 1, 0, 0], dtype=bool)\nb = np.array([1, 0, 1, 0], dtype=bool)\nnp.logical_or(a, b)\n\n\n# #### Basic reductions\n\n# In[27]:\n\n\nx = np.array([1, 2, 3, 4])\nnp.sum(x)\n\n\n# In[28]:\n\n\n#Sum by rows and by columns:\nx = np.array([[1, 1], [2, 2]])\nx\n\n\n# In[29]:\n\n\nx.sum(axis=0)   # columns (first dimension)\n\n\n# In[30]:\n\n\nx[:, 0].sum(), x[:, 1].sum()\n\n\n# In[31]:\n\n\nx.sum(axis=1)   # rows (second dimension)\n\n\n# #### Basic reductions\n#  * Basic operations on numpy arrays (addition, etc.) are elementwise\n# \n#  * This works on arrays of the same size.\n#   Nevertheless, It’s also possible to do operations on arrays of different\n#     sizes if NumPy can transform these arrays so that they all have\n#     the same size: this conversion is called broadcasting.\n#     The image below gives an example of broadcasting:\n\n# In[32]:\n\n\na = np.tile(np.arange(0, 40, 10), (3, 1)).T\na\n\n\n# In[33]:\n\n\nb = np.array([0, 1, 2])\nb\n\n\n# In[34]:\n\n\na + b\n\n\n# In[36]:\n\n\n#We have already used broadcasting without knowing it!:\na = np.ones((4, 5))\na[0] = 2 \na\n\n\n# #### Sorting data\n\n# In[37]:\n\n\na = np.array([[4, 3, 5], [1, 2, 1]])\nb = np.sort(a, axis=1)\nb\n\n\n# In[38]:\n\n\n#Sorts each row separately!\na.sort(axis=1)\na\n\n\n# In[45]:\n\n\ns = np.array([[2,4,5,8,2,0,3,7]])\nt = np.sort(s, axis=1)\nt\n\n\n# #### Do some statistics on numpy\n\n# In[49]:\n\n\nstat = np.arange(25).reshape(5,5)\nstat\n\n\n# In[50]:\n\n\n#returns mean along specific axis\nnp.mean(stat, axis=0)\n\n\n# In[51]:\n\n\n#returns sum of arr\nstat.sum()\n\n\n# In[52]:\n\n\n#returns minimum value of arr\nstat.min()\n\n\n# In[53]:\n\n\n#returns maximum value of specific axis\nstat.max(axis=0)\n\n\n# In[54]:\n\n\n#returns the variance of array\nnp.var(stat)\n\n\n# In[55]:\n\n\n#returns the standard deviation of specific axis\nnp.std(stat, axis=1)\n\n\n# In[57]:\n\n\n#returns correlation coefficient of array\nnp.corrcoef(stat)\n\n", "meta": {"hexsha": "7d34037e0c51774c74438429c53f5d14941b109e", "size": 3683, "ext": "py", "lang": "Python", "max_stars_repo_path": "All Python Codes/2017-23-11-so-stats-vector-math-numpy (1).py", "max_stars_repo_name": "bjfisica/MachineLearning", "max_stars_repo_head_hexsha": "20349301ae7f82cd5048410b0cf1f7a5f7d7e5a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52, "max_stars_repo_stars_event_min_datetime": "2019-02-15T16:37:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T18:34:30.000Z", "max_issues_repo_path": "All Python Codes/2017-23-11-so-stats-vector-math-numpy (1).py", "max_issues_repo_name": "RodeoBlues/Complete-Data-Science-Toolkits", "max_issues_repo_head_hexsha": "c5e83889e24af825ec3baed6e8198debb135f1ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "All Python Codes/2017-23-11-so-stats-vector-math-numpy (1).py", "max_forks_repo_name": "RodeoBlues/Complete-Data-Science-Toolkits", "max_forks_repo_head_hexsha": "c5e83889e24af825ec3baed6e8198debb135f1ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2017-11-25T23:42:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-07T09:22:35.000Z", "avg_line_length": 12.8776223776, "max_line_length": 344, "alphanum_fraction": 0.6535433071, "include": true, "reason": "import numpy", "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731094431571, "lm_q2_score": 0.9059898248255074, "lm_q1q2_score": 0.8721720417886324}}
{"text": "\"\"\"\nThis script demonstrates the implementation of the Softmax function.\n\nIts a function that takes as input a vector of K real numbers, and normalizes\nit into a probability distribution consisting of K probabilities proportional\nto the exponentials of the input numbers. After softmax, the elements of the\nvector always sum up to 1.\n\nScript inspired from its corresponding Wikipedia article\nhttps://en.wikipedia.org/wiki/Softmax_function\n\"\"\"\n\nimport numpy as np\n\n\ndef softmax(vector):\n    \"\"\"\n        Implements the softmax function\n\n        Parameters:\n            vector (np.array,list,tuple): A  numpy array of shape (1,n)\n            consisting of real values or a similar list,tuple\n\n\n        Returns:\n            softmax_vec (np.array): The input numpy array  after applying\n            softmax.\n\n        The softmax vector adds up to one. We need to ceil to mitigate for\n        precision\n        >>> np.ceil(np.sum(softmax([1,2,3,4])))\n        1.0\n\n        >>> vec = np.array([5,5])\n        >>> softmax(vec)\n        array([0.5, 0.5])\n\n        >>> softmax([0])\n        array([1.])\n    \"\"\"\n\n    # Calculate e^x for each x in your vector where e is Euler's\n    # number (approximately 2.718)\n    exponentVector = np.exp(vector)\n\n    # Add up the all the exponentials\n    sumOfExponents = np.sum(exponentVector)\n\n    # Divide every exponent by the sum of all exponents\n    softmax_vector = exponentVector / sumOfExponents\n\n    return softmax_vector\n\n\nif __name__ == \"__main__\":\n    print(softmax((0,)))\n", "meta": {"hexsha": "92ff4ca27b88e65d7e1917913f9b644ebcd9d6ed", "size": 1508, "ext": "py", "lang": "Python", "max_stars_repo_path": "maths/softmax.py", "max_stars_repo_name": "Pratiyush27/Python", "max_stars_repo_head_hexsha": "be48a876c7746611099974e572ea82691a7cbb20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-02-11T22:18:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T02:56:07.000Z", "max_issues_repo_path": "maths/softmax.py", "max_issues_repo_name": "Pratiyush27/Python", "max_issues_repo_head_hexsha": "be48a876c7746611099974e572ea82691a7cbb20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-03-24T17:47:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:33:21.000Z", "max_forks_repo_path": "maths/softmax.py", "max_forks_repo_name": "Pratiyush27/Python", "max_forks_repo_head_hexsha": "be48a876c7746611099974e572ea82691a7cbb20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2020-02-09T13:00:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T08:47:36.000Z", "avg_line_length": 26.4561403509, "max_line_length": 77, "alphanum_fraction": 0.6571618037, "include": true, "reason": "import numpy", "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639686018702, "lm_q2_score": 0.8976953003183443, "lm_q1q2_score": 0.8721684085725383}}
{"text": "def midpoint_triple1(g, a, b, c, d, e, f, nx, ny, nz):\n    hx = (b - a)/nx\n    hy = (d - c)/ny\n    hz = (f - e)/nz\n    I = 0\n    for i in range(nx):\n        for j in range(ny):\n            for k in range(nz):\n                xi = a + hx/2 + i*hx\n                yj = c + hy/2 + j*hy\n                zk = e + hz/2 + k*hz\n                I = I + hx*hy*hz*g(xi, yj, zk)\n    return I\n\ndef midpoint(f, a, b, n):\n    h = (b-a)/n\n    f_sum = 0\n    for i in range(0, n, 1):\n        x = (a + h/2.0) + i*h\n        f_sum = f_sum + f(x)\n    return h*f_sum\n\ndef midpoint_triple2(g, a, b, c, d, e, f, nx, ny, nz):\n    def p(x, y):\n        return midpoint(lambda z: g(x, y, z), e, f, nz)\n\n    def q(x):\n        return midpoint(lambda y: p(x, y), c, d, ny)\n\n    return midpoint(q, a, b, nx)\n\ndef test_midpoint_triple():\n    \"\"\"Test that a linear function is integrated exactly.\"\"\"\n    def g(x, y, z):\n        return 2*x + y - 4*z\n\n    a = 0;  b = 2;  c = 2;  d = 3;  e = -1;  f = 2\n    import sympy\n    x, y, z = sympy.symbols('x y z')\n    I_expected = sympy.integrate(\n        g(x, y, z), (x, a, b), (y, c, d), (z, e, f))\n    for nx, ny, nz in (3, 5, 2), (4, 4, 4), (5, 3, 6):\n        I_computed1 = midpoint_triple1(\n            g, a, b, c, d, e, f, nx, ny, nz)\n        I_computed2 = midpoint_triple2(\n            g, a, b, c, d, e, f, nx, ny, nz)\n        tol = 1E-14\n        print(I_expected, I_computed1, I_computed2)\n        assert abs(I_computed1 - I_expected) < tol\n        assert abs(I_computed2 - I_expected) < tol\n\nif __name__ == '__main__':\n    test_midpoint_triple()\n", "meta": {"hexsha": "691c94f5d7a0187baa04e0608acd4b0df84cea8f", "size": 1561, "ext": "py", "lang": "Python", "max_stars_repo_path": "Prog4comp-SL-HPL-Extra/src/midpoint_triple.py", "max_stars_repo_name": "computational-medicine/BMED360-2021", "max_stars_repo_head_hexsha": "2c6052b9affedf1fee23c89d23941bf08eb2614c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-19T23:22:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T14:04:58.000Z", "max_issues_repo_path": "Prog4comp-SL-HPL-Extra/src/midpoint_triple.py", "max_issues_repo_name": "computational-medicine/BMED360-2021", "max_issues_repo_head_hexsha": "2c6052b9affedf1fee23c89d23941bf08eb2614c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Prog4comp-SL-HPL-Extra/src/midpoint_triple.py", "max_forks_repo_name": "computational-medicine/BMED360-2021", "max_forks_repo_head_hexsha": "2c6052b9affedf1fee23c89d23941bf08eb2614c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-26T17:15:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T08:10:06.000Z", "avg_line_length": 28.9074074074, "max_line_length": 60, "alphanum_fraction": 0.4727738629, "include": true, "reason": "import sympy", "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953275045356249, "lm_q2_score": 0.9149009503523291, "lm_q1q2_score": 0.8721522449435918}}
{"text": "# determines whether a matrix is orthogonal. A square matrix is orthogonal,\n# if its columns and rows are orthogonal unit vectors,\n# which is equivalent to: MT M = I\n\nimport numpy as np\n\n\ndef check_orthogonal(M):\n    # make sure the input is a matrix\n    if len(np.shape(M)) !=2:\n        print(\"error: input is not a matrix\")\n        return\n    # make sure the input is not a square matrix\n    dim = np.shape(M)[0]\n    if dim != np.shape(M)[1]:\n        print(\"error: input is not a square matrix\")\n        return\n    A = np.dot(M, M.T)\n    #  if np.array_equal(A, np.identity(dim)):\n    [rows, cols] = A.shape\n    I = np.identity(dim)\n    for i in range(rows):\n        for j in range(cols):\n            if not (A[i, j] - I[i, j] <= 10e-3):\n                print(\"matrix is not orthogonal\")\n                return\n    print(\"matrix is orthogonal\")\n\n\nif __name__ == '__main__':\n    # Verify check_orthogonal function\n    D = 1. / 3. * np.array(\n        [[2, 2, -1],\n         [2, -1, 2],\n         [-1, 2, 2]])\n    check_orthogonal(D)\n\n    #  Test 2\n    R = np.array([[np.cos(np.pi / 4), -np.sin(np.pi / 4)],\n    [np.sin(np.pi / 4), np.cos(np.pi / 4)]])\n    check_orthogonal(R)\n", "meta": {"hexsha": "770673f24036a8ceec8e61b2171492c465ecf453", "size": 1174, "ext": "py", "lang": "Python", "max_stars_repo_path": "Introduction_to_Mobile_Robotics-SS2017/Exercise/orthogonal.py", "max_stars_repo_name": "yubaoliu/AISLAM", "max_stars_repo_head_hexsha": "b12bba78b17ca61253ee0584927e3efaaa3d13d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Introduction_to_Mobile_Robotics-SS2017/Exercise/orthogonal.py", "max_issues_repo_name": "yubaoliu/AISLAM", "max_issues_repo_head_hexsha": "b12bba78b17ca61253ee0584927e3efaaa3d13d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction_to_Mobile_Robotics-SS2017/Exercise/orthogonal.py", "max_forks_repo_name": "yubaoliu/AISLAM", "max_forks_repo_head_hexsha": "b12bba78b17ca61253ee0584927e3efaaa3d13d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9523809524, "max_line_length": 75, "alphanum_fraction": 0.5562180579, "include": true, "reason": "import numpy", "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140187510509, "lm_q2_score": 0.9019206686206199, "lm_q1q2_score": 0.8720797382905985}}
{"text": "\"\"\"\nKindly install these libraries before executing this code:\n  1. numpy\n  2. scipy\n\"\"\"\n\nimport math\nimport numpy as np\nfrom scipy.stats import norm\n\n\nM = [100, 1000, 10000, 100000]\n\n\ndef generate_random_numbers(idx):\n  np.random.seed(42)    \n  random_nums = np.random.uniform(0, 1, M[idx])\n  return random_nums\n\n\ndef simpleEstimator():\n  for idx in range(0, 4):\n    print(\"\\n# Iteration - {}\\t\\tM = {}\\n\".format(idx + 1, M[idx]))\n\n    Y = []\n    random_nums = generate_random_numbers(idx)\n    for i in range(0, M[idx]):\n      Y.append(math.exp(math.sqrt(random_nums[i])))\n    \n    Z_delta = norm.ppf(0.05/2)\n    s = np.var(Y)\n    I_m = np.mean(Y)\n    l = I_m + (Z_delta * math.sqrt(s))/math.sqrt(M[idx])\n    r = I_m - (Z_delta * math.sqrt(s))/math.sqrt(M[idx])\n\n    print(\"I_m \\t\\t\\t= {}\".format(I_m))\n    print(\"Confidence Interval \\t= [{}, {}]\".format(l, r))\n    print(\"variance \\t\\t= {}\".format(s))\n\n\ndef antitheticVariateEstimator():\n  for idx in range(0, 4):\n    print(\"\\n# Iteration - {}\\t\\tM = {}\\n\".format(idx + 1, M[idx]))\n\n    Y = []\n    Y_hat = []\n    random_nums = generate_random_numbers(idx)\n\n    for i in range(0, M[idx]):\n      Y.append(math.exp(math.sqrt(random_nums[i])))\n      Y_hat.append((math.exp(math.sqrt(random_nums[i])) + math.exp(math.sqrt(1 - random_nums[i])))/2)\n    \n    Z_delta = norm.ppf(0.05/2)\n    s = np.var(Y_hat)\n    I_m = np.mean(Y_hat) \n    l = I_m + (Z_delta * math.sqrt(s))/math.sqrt(M[idx])\n    r = I_m - (Z_delta * math.sqrt(s))/math.sqrt(M[idx])\n\n    print(\"I_m \\t\\t\\t= {}\".format(I_m))\n    print(\"Confidence Interval \\t= [{}, {}]\".format(l, r))\n    print(\"variance \\t\\t= {}\".format(s))\n\n\ndef main():\n  print(\"************ Part 1 ************\")\n  simpleEstimator()\n\n  print(\"\\n\\n\\n\\n************ Part 2 ************\")\n  antitheticVariateEstimator()\n  \n\nif __name__==\"__main__\":\n    main()", "meta": {"hexsha": "de984158293d87bbb116bc02f113241ff4d45c29", "size": 1834, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab10/Submission Files/180123053_VishishtPriyadarshi.py", "max_stars_repo_name": "vishishtpriyadarshi/Monte-Carlo-Simulation", "max_stars_repo_head_hexsha": "0e162bdecf774e06ec209914ff16bc31b0f8fc74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab10/Submission Files/180123053_VishishtPriyadarshi.py", "max_issues_repo_name": "vishishtpriyadarshi/Monte-Carlo-Simulation", "max_issues_repo_head_hexsha": "0e162bdecf774e06ec209914ff16bc31b0f8fc74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab10/Submission Files/180123053_VishishtPriyadarshi.py", "max_forks_repo_name": "vishishtpriyadarshi/Monte-Carlo-Simulation", "max_forks_repo_head_hexsha": "0e162bdecf774e06ec209914ff16bc31b0f8fc74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1232876712, "max_line_length": 101, "alphanum_fraction": 0.5785169029, "include": true, "reason": "import numpy,from scipy", "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762057376384, "lm_q2_score": 0.908617890746506, "lm_q1q2_score": 0.8720569761918571}}
{"text": "# -------- Programming Assignment --------\n#\n# * Author: Laxman Desai ($190020066$)\n# * Course: CL $202$ (Data Analysis)\n# * Date: $20^{th}$ April $2021$\n\n# Initialization\nfrom scipy import stats\nfrom sklearn.linear_model import LinearRegression\nimport pandas as pd\nimport numpy as np\n\ndf = pd.read_csv('dataset/data.csv')\ndf['Z1'] *= 100 # Scaling\ndf['Z2'] *= 1000 # Scaling\ndf['Y'] *= 1000 # Scaling\n\n\n# A) Correlation Coefficient\ncorr_coeff_Y_Z1 = df['Y'].corr(df['Z1'])\nprint(f'corr_coeff_Y_Z1 = {round(corr_coeff_Y_Z1, 4)}')\ncorr_coeff_Y_Z2 = df['Y'].corr(df['Z2'])\nprint(f'corr_coeff_Y_Z2 = {round(corr_coeff_Y_Z2, 4)}')\n\n\n# B) Linear Model\nX = df.drop('Y', axis=1) # Independant Variables\ny = df['Y'] # Dependant Variables\nN = len(X)\np = len(X.columns) + 1  # '+1' because LinearRegression adds an intercept term\n\nmodel = LinearRegression()\nmodel.fit(X, y)\na, b = model.coef_\nc = model.intercept_\nprint(f'a = {round(a, 5)}, b = {round(b, 5)}, c = {round(c, 5)}')\n\n\n# C) $95\\%$ Confidence Interval\ny_hat = model.predict(X)\nerr = y - y_hat # residual\n\nRSS = err.T @ err # dot product, equivalent to sum(err**2)\nS = np.sqrt(RSS / (N - p))\n\n# M = matrix (20 x 3) with columns as [Z1, Z2, 1]\nM = np.ones(shape=(N, p), dtype=float)\nM[:, 0] = X.iloc[:, 0]\nM[:, 1] = X.iloc[:, 1]\n\nvar_beta_hat = 1/(M.T @ M) * S**2 # Varience of beta hat\n\nstd_err_a = var_beta_hat[0, 0] ** 0.5\nstd_err_b = var_beta_hat[1, 1] ** 0.5\nstd_err_c = var_beta_hat[2, 2] ** 0.5\n\nt = abs(stats.t.ppf((1-0.95)/2, N-p)) # 95% CI\n\n# 95% CI Lower Bounds\nci_l_a = a - t * std_err_a\nci_l_b = b - t * std_err_b\nci_l_c = c - t * std_err_c\n# 95% CI Upper Bounds\nci_u_a = a + t * std_err_a\nci_u_b = b + t * std_err_b\nci_u_c = c + t * std_err_c\n\nprint(f'a ∈ [{round(ci_l_a, 6)}, {round(ci_u_a, 6)}]' )\nprint(f'b ∈ [{round(ci_l_b, 6)}, {round(ci_u_b, 6)}]' )\nprint(f'c ∈ [{round(ci_l_c, 6)}, {round(ci_u_c, 6)}]' )\n\n\n# D) $95\\%$ Prediction Interval\n# - Apartment size = 12 \\* 100 ft2 and assessed value of 60 * 1000$\nX_test = [[1200, 60000]]\ny_test_hat = model.predict(X_test)[0]\n\npi_l_Y = y_test_hat - t * S\npi_u_Y = y_test_hat + t * S\nprint(f'lower value bound = {pi_l_Y}, upper value bound = {pi_u_Y}')\n\n\n# E) Mean & varience of residuals\nmean_resid = err.mean()\nprint(f'mean of residual = {mean_resid}')\nvar_resid = err.var()\nprint(f'varience of residual = {var_resid}')\n\n\n# F) $R^2$ of the fit\ny_diff = y - y.mean()\nTSS = y_diff.T @ y_diff\nRsq = 1 - RSS/TSS\nprint(f'R^2 of the fit (calculated) = {Rsq}')\n", "meta": {"hexsha": "ed02b3870b0fe4b68a940c0658f1882322fe5d8f", "size": 2470, "ext": "py", "lang": "Python", "max_stars_repo_path": "CL 202/Programming Assignment/submission/190020066_assignment.py", "max_stars_repo_name": "relaxxpls/DS303", "max_stars_repo_head_hexsha": "64b668d3f7a197fe1fdc8ec2fff89ca59b3ecfa0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CL 202/Programming Assignment/submission/190020066_assignment.py", "max_issues_repo_name": "relaxxpls/DS303", "max_issues_repo_head_hexsha": "64b668d3f7a197fe1fdc8ec2fff89ca59b3ecfa0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CL 202/Programming Assignment/submission/190020066_assignment.py", "max_forks_repo_name": "relaxxpls/DS303", "max_forks_repo_head_hexsha": "64b668d3f7a197fe1fdc8ec2fff89ca59b3ecfa0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-11T11:24:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T11:24:27.000Z", "avg_line_length": 26.0, "max_line_length": 78, "alphanum_fraction": 0.6348178138, "include": true, "reason": "import numpy,from scipy", "num_tokens": 908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812299938006, "lm_q2_score": 0.9005297847831081, "lm_q1q2_score": 0.8720561406343188}}
{"text": "from sympy import *\nimport numpy as np\nimport math\n\ncotezCoefs = [[1/2,     1/2],\n             [1/6,      4/6,        1/6],\n             [1/8,      3/8,        3/8,        1/8],\n             [7/90,     32/90,      12/90,      32/90,      7/90],\n             [19/288,   75/288,     50/288,     50/288,     75/288,19/288]]\n\n#h^n - error term\nconvergeSpeeds = [2, 4, 4, 6, 6]\n\nmultiplier = [12, 90, 80/3, 945/8]\n\ndef CotezCoef(n):\n    return cotezCoefs[n-1]\n# M is sup(|f^(k)|) where f^(k) is the k-derivative of f, n is the degree of polynomial used\n# k is the converge speed\n# n < 5 pls ...\ndef Integral(f, M, rangeX, epsilon, n = 2):\n    cotezCoef = CotezCoef(n)\n    speed = convergeSpeeds[n]\n    mult = multiplier[n-1]\n\n    a,b = rangeX\n    length = b-a\n\n    #M/multiplier * length * h^k < eps\n    h = math.pow(epsilon*mult/M/length, 1/speed)\n\n    steps = (int) (length/h) + 1\n    dx = length/steps/n\n\n    integral = 0\n    xn = a\n    x = symbols('x')\n    for step in range(steps):\n        for t in range(n+1):\n            integral += f.subs(x, xn)*cotezCoef[t]\n            xn += dx\n        xn -= dx\n    \n    return integral*dx*n\n\nx = symbols('x')\n\n\n\n############ WRITE YOUR FRICKING INPUT HERE ######################\n\nf = 1/(x**2 + 1)\nepsilon = 10**-12\nM = 1000        # sup f^(n)\n\n# khoảng tích phân\na = 0\nb = 1\n\nn = 4\n\n############ WRITE YOUR FRICKING INPUT HERE ######################\n\n############ PRINT IT OUT ...               ######################\n\nintegral = Integral(f, M, (a,b), epsilon, n)  # YOUR RESULT HERE\n\npi = 4*integral.evalf(30)                       # 30 CHỮ SỐ\n\nprint(\"pi = \", pi)\n\nprint(\"tích phân = \", integral.evalf(30))      # PRINT YOUR RESULT\n\n############ PRINT IT OUT ...               ######################", "meta": {"hexsha": "906be1f8321762444b31aba2723bafee29451b9f", "size": 1739, "ext": "py", "lang": "Python", "max_stars_repo_path": "Topic 3 - Function Approximation/20.Integral/Cotez.py", "max_stars_repo_name": "dthanhqhtt/MI3040-Numerical-Analysis", "max_stars_repo_head_hexsha": "cf38ea7e6dc834b19e7cffef8b867a02ba472eae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-11-23T17:00:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T06:28:40.000Z", "max_issues_repo_path": "Topic 3 - Function Approximation/20.Integral/Cotez.py", "max_issues_repo_name": "dthanhqhtt/MI3040-Numerical-Analysis", "max_issues_repo_head_hexsha": "cf38ea7e6dc834b19e7cffef8b867a02ba472eae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-22T17:08:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-20T12:00:59.000Z", "max_forks_repo_path": "Topic 3 - Function Approximation/20.Integral/Cotez.py", "max_forks_repo_name": "dthanhqhtt/MI3040-Numerical-Analysis", "max_forks_repo_head_hexsha": "cf38ea7e6dc834b19e7cffef8b867a02ba472eae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-12-03T05:11:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T03:33:35.000Z", "avg_line_length": 23.5, "max_line_length": 92, "alphanum_fraction": 0.4698102358, "include": true, "reason": "import numpy,from sympy", "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812318188365, "lm_q2_score": 0.900529776774399, "lm_q1q2_score": 0.8720561345223344}}
{"text": "\"\"\"\n Purpose: The main purpose is to demonstrate how to find the running median, mode and \n          mean over a sequence (list) of integers or reals or a mix of integers and reals.\n          The secondary purpose, is to inspire Python programmers to explore some of\n          the powerful packages (e.g. collections) available to the Python community and \n          to learn more about list comprehension and lambda functions.\n    Note:        \n       1. Much of the code here has been taken from code posted to the web (e.g. stackoverflow)\n          by other Python programmers (e.g. Peter Otten)\n\n  Author: V. Stokes (vs@it.uu.se)  \n Version: 2013.03.06\n\n\"\"\"\nimport numpy as np\n\n#*******************************************************\n\nfrom collections import deque,Counter\nfrom bisect import insort, bisect_left\nfrom itertools import islice\n\ndef RunningMode(seq,N,M):\n    \"\"\"\n    Purpose: Find the mode for the points in a sliding window as it \n             is moved from left (beginning of seq) to right (end of seq)\n             by one point at a time.\n     Inputs:\n          seq -- list containing items for which a running mode (in a sliding window) is \n                 to be calculated\n            N -- length of sequence                      \n            M -- number of items in window (window size) -- must be an integer > 1\n     Otputs:\n        modes -- list of modes with size M - N + 1\n       Note:\n         1. The mode is the value that appears most often in a set of data.\n         2. In the case of ties it the last of the ties that is taken as the mode (this\n            is not by definition).\n    \"\"\"    \n    # Load deque with first window of seq \n    d = deque(seq[0:M]) \n\n    modes = [Counter(d).most_common(1)[0][0]]  # contains mode of first window\n\n    # Now slide the window by one point to the right for each new position (each pass through \n    # the loop). Stop when the item in the right end of the deque contains the last item in seq\n    for item in islice(seq,M,N):\n        old = d.popleft()                      # pop oldest from left\n        d.append(item)                         # push newest in from right\n        modes.append(Counter(d).most_common(1)[0][0])        \n    return modes    \n\ndef RunningMedian(seq, M):\n    \"\"\"\n     Purpose: Find the median for the points in a sliding window (odd number in size) \n              as it is moved from left to right by one point at a time.\n      Inputs:\n            seq -- list containing items for which a running median (in a sliding window) \n                   is to be calculated\n              M -- number of items in window (window size) -- must be an integer > 1\n      Otputs:\n         medians -- list of medians with size N - M + 1\n       Note:\n         1. The median of a finite list of numbers is the \"center\" value when this list\n            is sorted in ascending order. \n         2. If M is an even number the two elements in the window that\n            are close to the center are averaged to give the median (this\n            is not by definition)\n    \"\"\"   \n    seq = iter(seq)\n    s = []   \n    m = M // 2\n\n    # Set up list s (to be sorted) and load deque with first window of seq\n    s = [item for item in islice(seq,M)]    \n    d = deque(s)\n\n    # Simple lambda function to handle even/odd window sizes    \n    median = lambda : s[m] if bool(M&1) else (s[m-1]+s[m])*0.5\n\n    # Sort it in increasing order and extract the median (\"center\" of the sorted window)\n    s.sort()    \n    medians = [median()]   \n\n    # Now slide the window by one point to the right for each new position (each pass through \n    # the loop). Stop when the item in the right end of the deque contains the last item in seq\n    for item in seq:\n        old = d.popleft()          # pop oldest from left\n        d.append(item)             # push newest in from right\n        del s[bisect_left(s, old)] # locate insertion point and then remove old \n        insort(s, item)            # insert newest such that new sort is not required        \n        medians.append(median())  \n    return medians\n\ndef RunningMean(seq,N,M):\n    \"\"\"\n     Purpose: Find the mean for the points in a sliding window (fixed size) \n              as it is moved from left to right by one point at a time.\n      Inputs:\n          seq -- list containing items for which a mean (in a sliding window) is \n                 to be calculated (N items)\n            N -- length of sequence     \n            M -- number of items in sliding window\n      Otputs:\n        means -- list of means with size N - M + 1    \n\n    \"\"\"    \n    # Load deque (d) with first window of seq\n    d = deque(seq[0:M])\n    means = [np.mean(d)]             # contains mean of first window\n    # Now slide the window by one point to the right for each new position (each pass through \n    # the loop). Stop when the item in the right end of the deque contains the last item in seq\n    for item in islice(seq,M,N):\n        old = d.popleft()            # pop oldest from left\n        d.append(item)               # push newest in from right\n        means.append(np.mean(d))     # mean for current window\n    return means  \n\n", "meta": {"hexsha": "f98d72bef06f43c572c14feab4cb35643e0e2c6e", "size": 5138, "ext": "py", "lang": "Python", "max_stars_repo_path": "preprocessing/NMECisolate/running_stats.py", "max_stars_repo_name": "Lab41/d-script", "max_stars_repo_head_hexsha": "4c5079754ca48b2ab5080f10bb677cbd7375a735", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2016-01-09T12:35:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T21:27:34.000Z", "max_issues_repo_path": "preprocessing/NMECisolate/running_stats.py", "max_issues_repo_name": "Lab41/d-script", "max_issues_repo_head_hexsha": "4c5079754ca48b2ab5080f10bb677cbd7375a735", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2016-01-08T00:59:54.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-20T20:26:33.000Z", "max_forks_repo_path": "preprocessing/NMECisolate/running_stats.py", "max_forks_repo_name": "Lab41/d-script", "max_forks_repo_head_hexsha": "4c5079754ca48b2ab5080f10bb677cbd7375a735", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2016-01-08T00:33:11.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-17T21:02:14.000Z", "avg_line_length": 43.1764705882, "max_line_length": 95, "alphanum_fraction": 0.5977033865, "include": true, "reason": "import numpy", "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.9252299534840472, "lm_q1q2_score": 0.8720354513080955}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 10 # data points\n\n# The following simple Python instructions define our x and y values (with 100 data points)\nx = np.random.rand(n,1)\ny = 5*x*x+np.random.randn(n,1) # y = 5x^2 + random noise\n\n\nX = np.c_[np.ones((n,1)), x, x*x] # column wise array concatenation\nprint(X)\n\nbeta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)\nprint(\"y = \" + str(beta[2,0]) + \"*x^2 + \" + str(beta[1,0]) + \"*x + \" + str(beta[0,0]))\n\nnfit = 100\nxplot = np.linspace(0.0,1.0, num=nfit)\n\nXplot = np.c_[np.ones((nfit,1)), xplot, xplot**2] # concatenate columns (as above)\n\nypredict = Xplot.dot(beta)\n\nytrue = 5*xplot*xplot\n\nplt.plot(x, y ,'ro')\nplt.plot(xplot, ytrue, label=\"$y_{\\mathrm{Quadratic}}$\")\nplt.plot(xplot, ypredict, label=\"$y_{\\mathrm{predict}}$\")\nplt.xlabel(r'$x$')\nplt.ylabel(r'$y$')\nplt.title(r'Quadratic Regression')\nplt.legend()\nplt.show()\n\nfrom sklearn.linear_model import LinearRegression\n\nclf2 = LinearRegression()\nclf2.fit(X, y)\nysklearn = clf2.predict(Xplot)\n\nprint(\"ypredict = \" + str(clf2.coef_[0, 2]) + \"*x^2 + \" + str(clf2.coef_[0, 1]) + \"*x + \" + str(clf2.coef_[0, 0]))\nprint(\"ysklearn = \" + str(beta[2,0]) + \"*x^2 + \" + str(beta[1,0]) + \"*x + \" + str(beta[0,0]))\n# note that the indices are reversed in the scikit-learn approach compared to what we did before:\n# the shape is (1, n) instead of (n, 1)\n\nplt.plot(x, y ,'ro')\nplt.plot(xplot, ytrue, label=\"$y_{\\mathrm{true}}$\")\nplt.plot(xplot, ypredict, label=\"$y_{\\mathrm{predict}}$\")\nplt.plot(xplot, ysklearn, label=\"$y_{\\mathrm{sklearn}}$\")\nplt.xlabel(r'$x$')\nplt.ylabel(r'$y$')\nplt.title(r'Quadratic Regression')\nplt.legend()\nplt.show()\n\nerr_predict = abs(ypredict[:, 0] - ytrue)/abs(ytrue) # the predicted y's have shape (n, 1)\nerr_sklearn = abs(ysklearn[:, 0] - ytrue)/abs(ytrue)\n\nplt.plot(xplot, err_predict, label=\"$\\epsilon_{\\mathrm{predict}}$\")\nplt.plot(xplot, err_sklearn, label=\"$\\epsilon_{\\mathrm{sklearn}}$\")\nplt.xlabel(r'$x$')\nplt.ylabel(r'$\\epsilon_{\\mathrm{rel}}$')\nplt.axis([0, 1, 0, 2])\nplt.title(r'Absolute relative error')\nplt.legend()\nplt.show()\n\nplt.plot(xplot, abs(err_predict), label=\"$\\epsilon_{\\mathrm{predict}}$\")\nplt.plot(xplot, abs(err_sklearn), label=\"$\\epsilon_{\\mathrm{sklearn}}$\")\nplt.xlabel(r'$x$')\nplt.ylabel(r'$\\epsilon_{\\mathrm{rel}}$')\nplt.axis([0, 1.0, 0, 0.02])\nplt.title(r'Absolute relative error')\nplt.legend()\nplt.show()\n\nfrom sklearn.metrics import mean_squared_error\n\n\nypredict2 = X.dot(beta)\nysklearn2 = clf2.predict(X)\n\nprint(\"Mean squared error (ypredict):\", mean_squared_error(y, ypredict2))\nprint(\"Mean squared error (ysklearn):\", mean_squared_error(y, ysklearn2))\n\n\n\nfrom sklearn.metrics import r2_score\n\nprint(\"R^2 score (ypredict):\", r2_score(y, ypredict2))\nprint(\"R^2 score (ysklearn):\", r2_score(y, ysklearn2))\n\n\n", "meta": {"hexsha": "0f48d89a2ed518b5f7534e77b8ec1f37f84ed30f", "size": 2770, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/src/Projects/2020/Exercises/hw1.py", "max_stars_repo_name": "esleon97/MachineLearningECT", "max_stars_repo_head_hexsha": "97a218c9742b43a53e033a888f8a0b1074a2c48b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 59, "max_stars_repo_stars_event_min_datetime": "2019-12-06T09:24:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T03:27:28.000Z", "max_issues_repo_path": "doc/src/Projects/2020/Exercises/hw1.py", "max_issues_repo_name": "esleon97/MachineLearningECT", "max_issues_repo_head_hexsha": "97a218c9742b43a53e033a888f8a0b1074a2c48b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-06-16T18:24:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-08T21:13:56.000Z", "max_forks_repo_path": "doc/src/Projects/2020/Exercises/hw1.py", "max_forks_repo_name": "esleon97/MachineLearningECT", "max_forks_repo_head_hexsha": "97a218c9742b43a53e033a888f8a0b1074a2c48b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2019-11-30T00:37:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T21:30:09.000Z", "avg_line_length": 29.4680851064, "max_line_length": 114, "alphanum_fraction": 0.6711191336, "include": true, "reason": "import numpy", "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811631528336, "lm_q2_score": 0.9032942158155877, "lm_q1q2_score": 0.8720232207332788}}
{"text": "import numpy as np\r\nimport math as m\r\nimport unittest\r\nimport matplotlib.pyplot as plt\r\nimport random\r\n\r\n###******************/PART II : Conjugate gradient method\r\n\r\n\"\"\"QUESTION 3\"\"\"\r\n\"\"\"Resolution of the linear system Ax=b by the conjugate gradient method where A is a symetric positive definite matrix and b a vector (without preconditioning)\"\"\"\r\n\r\ndef conjgrad(A,b,x) :\r\n    r=b-np.dot(A,x)\r\n    p=r\r\n    rsOld= float(np.dot(np.transpose(r),r))\r\n    tab_x=[x]\r\n    iter=[0]\r\n    for i in range(1,100001):\r\n        Ap=np.dot(A,p)\r\n        n = float(np.dot(np.transpose(p),Ap))\r\n        alpha=rsOld/n\r\n        x=x+ alpha*p\r\n        r=r- alpha*Ap\r\n        rsNew=float(np.dot(np.transpose(r),r))\r\n        tab_x+=[x]\r\n        iter+=[i]\r\n        if m.sqrt(rsNew) < 1e-10 :\r\n            break\r\n        p=r+rsNew/rsOld*p\r\n        rsOld=rsNew\r\n    return x,tab_x,iter             #x is the solution\r\n                                    #tab_x is a list regrouping the values of x at each iteration\r\n                                    #iter is a list regrouping the iterations before arriving to the final solution. \r\n\r\n\r\n\"\"\"QUESTION 4\"\"\"\r\n\"\"\"Resolution of the linear system with preconditioning. Two preconditionners were implemented: using the Jacobi method and the incomplete cholesky method\"\"\"\r\n\r\n##******************* Preconditionning with the ---Incomplete Cholesky Method-\r\n\r\ndef somme(T, i, j):\r\n    return sum(np.fromiter((T[i][k] * T[j][k] for k in range(j)),float))\r\n\r\ndef facto_dense_inc(A):                   #this function is the implementation of the incomplete cholesky method seen in the Part I  \r\n    (n, n1) = A.shape\r\n    T = np.zeros((n,n))\r\n    for i in range(n):\r\n        for j in range(i + 1):\r\n            if A[i][j] != 0:\r\n                if i==j:\r\n                    T[i][j] = m.sqrt((A[i][i] - somme(T, i, j)))\r\n                else:\r\n                    T[i][j] = (A[i][j] - somme(T, i, j)) / T[j][j]\r\n    return T\r\n\r\ndef preconditioner(A):                    #this function returns a matrix preconditionned with the incomplete cholesky method\r\n    T= facto_dense_inc(A)\r\n    return np.dot(T,np.transpose(T))\r\n\r\n\r\n##******************* Preconditionning with the ---Jacobi Method-\r\n    \r\ndef generate_jacobi_matrix(A):                       #M is a diagonal matrix whose coefficients are the inverse of the diagonal \r\n                                                     #coefficients of the matrix A\r\n    M=np.zeros((len(A),len(A)))\r\n    for i in range(len(A)):\r\n        if A[i][i]!=0:\r\n            M[i][i]=1/A[i][i]\r\n    return M\r\n\r\n\r\ndef PreconditionedConjgrad(A,b,x):\r\n    tab_x=[x]\r\n    iter=[0]\r\n    r=b-np.dot(A,x)\r\n    M=generate_jacobi_matrix(A)          # we choose the jacobi method but we can use the incomplete cholesky method \r\n                                         # by puting M=np.linalg.inv(preconditionner(A)\r\n    z=np.dot(M,r)\r\n    p=z\r\n    for k in range(1,100001):\r\n        alpha=(np.dot(np.transpose(r),z))/(np.dot(np.transpose(p),np.dot(A,p)))\r\n        x=x+ alpha*p\r\n        tab_x+=[x]\r\n        iter+=[k]\r\n        r2=r-alpha*(np.dot(A,p))\r\n        rsNew=float(np.dot(np.transpose(r2),r2))\r\n        if m.sqrt(rsNew) < 1e-10 :\r\n            break\r\n        z2=np.dot(M,r2)  \r\n        beta=(np.dot(np.transpose(z2),r2))/(np.dot(np.transpose(z),r))\r\n        p=z2+beta*p\r\n        z=z2\r\n        r=r2\r\n    return x,tab_x,iter             #x is the solution\r\n                                    #tab_x is a list regrouping the values of x at each iteration\r\n                                    #iter is a list regrouping the iterations before arriving to the final solution. \r\n    \r\n    \r\ndef MdpGenerator(size) :          #this auxiliary function generates randomly, for a given size, a matrix A\r\n                                  #symetric definite positive \r\n                                  #T is an upper triangular matrix with positive diagonal coefficients \r\n                                  #The diagonal coefficients of A are generated randomly between 5 and 10      \r\n    T=np.zeros((size,size))\r\n    for i in range(size):\r\n        for j in range(size):\r\n            if j>=i:\r\n                T[i,j] = random.randint(5,10)\r\n            else:\r\n                T[i,j] = 0\r\n    A = np.dot(T,T.transpose())\r\n    return A\r\n\r\n##****************TEST: Conjugate gradient and Preconditionned Conjugate gradient methods \r\n\r\n##Test 1: \r\n\r\nclass Test_gradient(unittest.TestCase):\r\n    def test_conjgrad(self):                            # we test conjgrad with a matrix whose size is 2*2\r\n        A= np.array([[4,1],[1,3]])\r\n        b= np.array([1,2])\r\n        x= np.array([2,1])                              # initialisation of x\r\n        expected= np.array([0.0909,0.6363])             # expected is the exact solution \r\n        result= conjgrad(A,b,x)                         # result is the solution given by conjgrad\r\n        for i in range(len(A)):                         # we compare result and expected\r\n                self.assertAlmostEqual(result[0][i],expected[i],3)\r\n    def test_conjgrad_precond(self):                    # we test preconditionedconjgrad with a matrix whose size is 2*2\r\n        A= np.array([[4,1],[1,3]])\r\n        b= np.array([1,2])\r\n        x= np.array([2,1])\r\n        expected= np.array([0.0909,0.6363])\r\n        result= PreconditionedConjgrad(A,b,x)\r\n        print()\r\n        for i in range(len(A)):                       #comparison between the solution with preconditionning and the exact solution             \r\n            self.assertAlmostEqual(result[0][i],expected[i],3)    \r\n\r\n\r\n##Test 2: Conjugate gradient VS Preconditionned Conjugate gradient\r\n\r\n##We generate a curve representing the variations of the absolute error according to the number of iterations\r\n##absolute error = the difference in magnitudes between the expected solution and the solution found by the algorithm \r\n\r\ndef test_conjgrad(size):\r\n    R1=[]\r\n    R2=[]\r\n    A=MdpGenerator(size)\r\n    Xs = np.random.rand(size,1)\r\n    x1=np.zeros((size,1))\r\n    x2=np.zeros((size,1))\r\n    b=np.dot(A,Xs)\r\n    s1=conjgrad(A,b,x1)\r\n    s2=PreconditionedConjgrad(A,b,x2)\r\n    for i in range(len(s1[1])):\r\n        R1+=[abs(np.linalg.norm(s1[1][i])-np.linalg.norm(Xs))]\r\n        R2+=[abs(np.linalg.norm(s2[1][i])-np.linalg.norm(Xs))]\r\n    return R1,R2,s1[2]\r\n\r\ndef show_tests(size):\r\n    t=test_conjgrad(size)\r\n    plt.plot(t[2],t[1], label=\"PreConjgrad_Method\")\r\n    plt.plot(t[2],t[0], label=\"Conjgrad_Method\")\r\n    plt.xlabel('Iterations')\r\n    plt.ylabel('Absolute Error')\r\n    plt.legend()\r\n    plt.show()\r\n    \r\n#show_tests(20)                              #we run the test with a matrix A whose size is 20*20\r\n\r\n##Test 3: Conjugate gradient VS Preconditionned Conjugate gradient VS linalg.solve\r\n\r\ndef test_conjgrad_linalg(size):\r\n                                    #In this test we generate the solutions given by np.linalg, conjgrad and    \r\n                                    #preconditionnedconjgrad for different size of matrix\r\n                                    #we generate a graph with 3 curves which show how the absolute error varies for each method\r\n    R1=[]\r\n    R2=[]\r\n    R3=[]\r\n    iter=[]\r\n    for i in range(25,size):                                          #we iterate on the matrix size \r\n        iter+=[i]\r\n        A=MdpGenerator(i)\r\n        Xs = np.random.rand(i,1)                                      #Xs is the exact solution\r\n        b=np.dot(A,Xs)\r\n        \r\n        xConjgrad=np.zeros((i,1))\r\n        xConjgrad=conjgrad(A,b,xConjgrad)                             #we save the solution, for the system, given by conjgrad \r\n        \r\n        xPreconjgrad=np.zeros((i,1))\r\n        xPreconjgrad=PreconditionedConjgrad(A,b,xPreconjgrad)         #we save the solution given by Preconditionnalconjgrad     \r\n                                                                    \r\n        xLinalg=np.linalg.solve(A,b)                                  #we save the solution given by linalg.solve\r\n        \r\n        R1+=[abs(np.linalg.norm(xConjgrad[0])-np.linalg.norm(Xs))]    #we stock the absolute error for each solution x \r\n        R2+=[abs(np.linalg.norm(xPreconjgrad[0])-np.linalg.norm(Xs))]\r\n        R3+=[abs(np.linalg.norm(xLinalg)-np.linalg.norm(Xs))]\r\n    plt.plot(iter, R1, label=\"Conjgrad Method\")\r\n    plt.plot(iter, R3, label=\"Linalg from numpy\")\r\n    plt.plot(iter, R2, label=\"PreConjgrad Method\")\r\n    plt.xlabel('Size of matrix')\r\n    plt.ylabel('Absolute error')\r\n    plt.title('Absolute error in the resolution of Ax=b') \r\n    plt.legend()\r\n    plt.show()\r\n    \r\ntest_conjgrad_linalg(50)                                #we run the test for matrix whose size varies from 25*25 to 49*49\r\n\r\n# unittests\r\nif __name__ == '__main__':\r\n    unittest.main(Test_gradient(), verbosity = 2)\r\n", "meta": {"hexsha": "6119ec235087ba5f9913238703a408f5e1b71163", "size": 8763, "ext": "py", "lang": "Python", "max_stars_repo_path": "Partie2/Gradient_Methods.py", "max_stars_repo_name": "ImadProjects/Resolution-de-systemes-lineaires", "max_stars_repo_head_hexsha": "d37a80e29f780be57f1e88502c8c8fa20d5a511e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Partie2/Gradient_Methods.py", "max_issues_repo_name": "ImadProjects/Resolution-de-systemes-lineaires", "max_issues_repo_head_hexsha": "d37a80e29f780be57f1e88502c8c8fa20d5a511e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Partie2/Gradient_Methods.py", "max_forks_repo_name": "ImadProjects/Resolution-de-systemes-lineaires", "max_forks_repo_head_hexsha": "d37a80e29f780be57f1e88502c8c8fa20d5a511e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9282296651, "max_line_length": 164, "alphanum_fraction": 0.5439917836, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811611608242, "lm_q2_score": 0.9032942132122422, "lm_q1q2_score": 0.8720232164206875}}
{"text": "#!/usr/bin/env python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef circle_formula(x, r):\n\ty = np.sqrt(r**2 - x**2) # rearranged from x^2 + y^2 = r^2\n\treturn y\n\ndef vect_dist(v1, v2):\n\tdx = v1[0] - v2[0] # change in x\n\tdy = v1[1] - v2[1] # change in y\n\tdist = np.sqrt(np.power(dx,2) + np.power(dy, 2)) # pythagoras\n\treturn dist\n\ndef find_pi(steps):\n\n\tr = 1 # Radius shouldn't matter so long as it is consistent\n\tx = np.linspace(0, r, steps) # x ranging from origin to radius\n\ty = circle_formula(x, r) # calculate corresponding y values\n\n\tvect_list = np.vstack((x,y)).T # stack x and y values to make next step easier\n\n\t# Now going to add up each segment to get the length of the arc\n\tcurve_len = 0. # initialise curve length\n\tfor i in range(len(vect_list)-1):\n\t\tcurve_len += vect_dist(vect_list[i], vect_list[i+1]) # add each segment of the curve\n\n\tc = 4*curve_len # we only measured 1/4 of a circle\n\td = 2*r # diameter is two times radius\n\n\tpi = c/d # from definition pi*d = circumfrence\n\n\treturn pi\n\nif __name__ == \"__main__\":\n\n\tsteps = [10, 100, 1000, 10000, 100000, 1000000] # number of circle points in calculation\n\tpis = [] # empty list to house calculated values of pi\n\n\tfor step in steps:\n\t\tpis.append(find_pi(step)) # find pi using varying numbers of steps\n\n\t# Print difference between my value and numpy value of pi\n\tprint(f\"There is a difference of {np.abs(np.pi-pis[-1])} at {steps[-1]} steps.\")\n\n\t# Plot values\n\tplt.plot([min(steps), max(steps)], [np.pi, np.pi]) # plot actual value of pi\n\tplt.semilogx(steps, pis) # plot my values of pi\n\tplt.show() # show graph\n\t# Whole script runs in 12.4s on my PC, if taking too lower max nr of steps\n", "meta": {"hexsha": "89557011272369d6ef0a4788ed104343ec53f4ce", "size": 1663, "ext": "py", "lang": "Python", "max_stars_repo_path": "alt-pi-calc/find-pi.py", "max_stars_repo_name": "physicodes/collision-sim", "max_stars_repo_head_hexsha": "aa90d7af9565d95996999b8f2dc4a1fe14d14308", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "alt-pi-calc/find-pi.py", "max_issues_repo_name": "physicodes/collision-sim", "max_issues_repo_head_hexsha": "aa90d7af9565d95996999b8f2dc4a1fe14d14308", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "alt-pi-calc/find-pi.py", "max_forks_repo_name": "physicodes/collision-sim", "max_forks_repo_head_hexsha": "aa90d7af9565d95996999b8f2dc4a1fe14d14308", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9807692308, "max_line_length": 89, "alphanum_fraction": 0.6861094408, "include": true, "reason": "import numpy", "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811601648195, "lm_q2_score": 0.9032942119105695, "lm_q1q2_score": 0.8720232142643918}}
{"text": "# The sales of a new​ high-tech item​ (in thousands) are given by:\n\n# S(t) = 108 - 90e^-0.4t\n\n# where t represents time in years. Find the rate of change of sales at each time.\n\nfrom sympy import *\nimport math\nimport mpmath as mp\n\ninit_printing()\n\ndef disp_fun( f ):\n\tpprint( '\\n{0}\\n\\n'.format( pretty( f ) ) )\n\nt = symbols( 't' )\nS = 110 - ( 90 * exp( -0.4*t ) )\ndS = diff( S, t )\n\ndisp_fun( S )\ndisp_fun( dS )\n\n# ​a.) After 1 year.​ (Round to three decimal places as​ needed.)\nround( dS.subs( { t: 1 } ), 3 )\n\n# b.) After 5 years.​\nround( dS.subs( { t: 5 } ), 3 )\n\n# c.) What is happening to the rate of change of sales as time goes​ on?\n\nprint( 'It always decreases' )\n\n# d.) Does the rate of change of sales ever equal​ zero?\nprint( 'No' )\n", "meta": {"hexsha": "7bf4bbc957ada6dea332836f0a96b2eaa273c18a", "size": 745, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Module 5/sales_over_time.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Module 5/sales_over_time.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Module 5/sales_over_time.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2857142857, "max_line_length": 82, "alphanum_fraction": 0.6214765101, "include": true, "reason": "from sympy,import mpmath", "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668657039606, "lm_q2_score": 0.8887587920192298, "lm_q1q2_score": 0.8720206783323459}}
{"text": "import numpy as np\n\ndef powermod(k,i,n):\n    if i==0: return 1\n    if i%2==0: return powermod(k, i/2, n)**2 % n\n    if i%2==1: return (k*powermod(k, i-1, n)) % n\n\ndef factorization(n):\n    d = dict()\n    for i in range(2, int(np.sqrt(n))+1):\n        if n % i == 0: d[i] = 0\n        while n % i == 0:\n            n = n / i\n            d[i] += 1\n    if n > 1:\n        if n in d: d[n] += 1\n        else: d[n] = 1\n    return d\n\ndef bmg(p, start=None, skip=0):\n    \"\"\"\n    Biggest Modular Generator\n    \"\"\"\n    count_gen=0\n    a = p - 2 if start is None else min(p - 2, start)\n    while a > 1:\n        if isprimroot(p, a):\n            if count_gen == skip:\n                return a\n            count_gen += 1\n        a -= 1\n    return None\n\ndef isprimroot(p, m):\n    for f in factorization(p-1).keys():\n        if powermod(m, (p-1)/f, p) == 1:\n            return False\n    return True\n\ndef RabinMiller(n, k):\n    \"\"\"\n    Input1: n, an integer to be tested for primality;\n    Input2: k, a parameter that determines the accuracy of the test\n    Output: False if n is composite, otherwise True if probably prime\n    \"\"\"\n    if n<2: return False\n    if n in [2,3]: return True\n    if n%2==0: return False\n    \n    m = n-1\n    r=0\n    while(m%2==0):\n        r+=1\n        m = m/2\n    d = (n-1)/2**r\n    \n    for _ in range(k): #WitnessLoop\n        a = np.random.randint(2, n-2)\n        x = powermod(a, d, n)\n        if x == 1 or x == n - 1: continue\n        \n        continue_WitnessLoop = False\n        for _ in range(r-1):\n            x = (x**2) % n\n            if x == 1:\n                return False\n            if x == n - 1:\n                continue_WitnessLoop = True\n                continue\n        if continue_WitnessLoop: continue\n        return False\n    return True\n\ndef next_prime(k=16, start=0, skip=0):\n    if start in [0,1]: m = 2\n    elif start%2==0: m = start+1\n    else: m = start\n    while not RabinMiller(m, k): m += 2\n    return m if skip == 0 else next_prime(k=k, start=m, skip=skip-1)", "meta": {"hexsha": "6322fbbe290b340923515842c7a5af3f459aa864", "size": 1998, "ext": "py", "lang": "Python", "max_stars_repo_path": "number.py", "max_stars_repo_name": "duchesneaumathieu/loader", "max_stars_repo_head_hexsha": "4725a816588bc33827360aa94c108ec4e2b4649d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "number.py", "max_issues_repo_name": "duchesneaumathieu/loader", "max_issues_repo_head_hexsha": "4725a816588bc33827360aa94c108ec4e2b4649d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "number.py", "max_forks_repo_name": "duchesneaumathieu/loader", "max_forks_repo_head_hexsha": "4725a816588bc33827360aa94c108ec4e2b4649d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2911392405, "max_line_length": 69, "alphanum_fraction": 0.495995996, "include": true, "reason": "import numpy", "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854155523791, "lm_q2_score": 0.899121375242593, "lm_q1q2_score": 0.8719547965216645}}
{"text": "import pandas as pd \nimport numpy as np \nimport numpy.random as npr\nimport statsmodels as sm \nimport statsmodels.tsa.stattools as ts\nimport math\nimport scipy\nimport matplotlib.pyplot as plt\nfrom scipy import log,exp,sqrt,stats\nimport sys\nimport os\nimport logging\nfrom brd_mod.brdstats import *\nfrom brd_mod.brdgeo import *\n\n\ndef discrete_future_value(x,r,n):\n\t'''\n\tDiscrete Future Value of Money over Time\n\tx= initial capital\n\tr= rate (0.n format)\n\tn= time increment\n\t'''\n\treturn x*(1+r)**n\n\ndef discrete_present_value(x,r,n):\n\t'''\n\tDiscrete Present Value of Money from Time\n\tx= future capital\n\tr= rate (0.n format)\n\tn= time increment\n\t'''\n\treturn x*(1+r)**-n\n\t\ndef continuous_future_value(x,r,t):\n\t'''\n\tContinuous Future Value of Money over Time\n\tx= initial capital\n\tr= rate (0.n format)\n\tn= time increment\n\t'''\n\treturn x*math.exp(r*t)\n\t\ndef continuous_present_value(x,r,t):\n\t'''\n\tContinuous Present Value of Money from Time\n\tx= future capital\n\tr= rate (0.n format)\n\tn= time increment\n\t'''\n\treturn x*math.exp(-r*t)\n\ndef value_at_risk(position, c, mu, sigma):\n\t'''\n\tCalculate Basic Value at Risk (VAR)\n\tposition= total value of investment\n\tc= confidence level\n\tmu= mean return\n\tsigma= sd of return\n\t'''\n\talpha=stats.norm.ppf(1-c)\n\tvar = position*(mu-sigma*alpha)\n\treturn var\n\t\ndef value_at_risk_long(S, c, mu, sigma, n):\n\t'''\n\tCalculate Basic Value at Risk (VAR) into the Future\n\tS= total value of investment\n\tc= confidence level\n\tmu= mean return\n\tsigma= sd of return\n\tn= time increment\n\t'''\n\talpha=stats.norm.ppf(1-c)\n\tvar = S*(mu*n-sigma*alpha*np.sqrt(n))\n\treturn var\n\ndef imperial_returns(data):\n\t'''\n\tCalculate Basic Returns of a Price Series\n\tUses Formula: (data(t)-data(t-1))-1\n\t'''\n\tdaily_returns = (data/data.shift(1))-1\n\treturn daily_returns;\n\ndef log_returns(data):\n\t'''\n\tCalculate Logarithmic Returns of a Price Series\n\tUses Formula: ln(data(t)/data(t-1))\n\t'''\n\treturns = np.log(data/data.shift(1))\n\treturn returns;\n\ndef rolling_volatility(data, n=10):\n\t'''\n\tGenerate Rolling Standard Deviation of a Series\n\tn= window size\n\t'''\n\treturn data.rolling(window=n).std()\n\ndef show_data_plot(data):\n\t'''\n\tBasic Way to Plot and Show Data\n\t'''\n\tdata.plot(figsize=(10,5))\n\tplt.show()\n\ndef brownian_motion(mu=0, dt=0.1, N=1000):\n\t'''\n\tGenerate x-y Brownian Motion Series (Wiener Process)\n\tmu= mean of distribution\n\tdt= standard deviation of distribution\n\tN= size of sample\n\t'''\n\tW = scipy.zeros(N+1)\n\tt = scipy.linspace(0, N, N+1);\n\tW[1:N+1] = scipy.cumsum(scipy.random.normal(mu,dt,N))\n\treturn t,W\n\ndef plot_brownian_motion(t,W):\n\t'''\n\tPlots a Wiener Process (Brownian Motion) with Labels and Title\n\tt= x values (time)\n\tW= y values (Wiener process)\n\t'''\n\tplt.plot(t,W)\n\tplt.xlabel('Time(t)')\n\tplt.ylabel('Wiener-process W(t)')\n\tplt.title('Wiener-process')\n\tplt.show()\n\ndef blackscholes_call(S,E,T,rf,sigma):\n\t'''\n\tPrices European Call Option\n\tS= stock price at current time\n\tE= strike price in future\n\tT= expiry in years\n\trf= risk free rate (0.n format)\n\tsigma= volatility of underlying stock\n\t'''\n\td1=(log(S/E)+(rf+sigma*sigma/2.0)*T)/(sigma*sqrt(T))\n\td2 = d1-sigma*sqrt(T)\n\treturn S*stats.norm.cdf(d1)-E*exp(-rf*T)*stats.norm.cdf(d2)\n\ndef blackscholes_put(S,E,T,rf,sigma):\n\t'''\n\tPrices European Put Option\n\tS= stock price at current time\n\tE= strike price in future\n\tT= expiry in years\n\trf= risk free rate (0.n format)\n\tsigma= volatility of underlying stock\n\t'''\n\td1=(log(S/E)+(rf+sigma*sigma/2.0)*T)/(sigma*sqrt(T))\n\td2 = d1-sigma*sqrt(T)\n\treturn -S*stats.norm.cdf(-d1)+E*exp(-rf*T)*stats.norm.cdf(-d2)\n\ndef zero_bond_price(par_value,market_rate,n):\n\t'''\n\tPrices a Zero-Coupon Bond\n\tpar_value= bond's par value (base)\n\tmarket_rate= market return rate (0.n format)\n\tn= years into future\n\t'''\n\treturn par_value/(1+market_rate)**n\n\t\ndef bond_price(par_value,coupon,market_rate,n):\n\t'''\n\tPrices a Zero-Coupon Bond\n\tpar_value= bond's par value (base)\n\tcoupon= bond yield (0.n format)\n\tmarket_rate= market return rate (0.n format)\n\tn= years into future\n\t'''\n\tc = par_value*coupon\n\treturn c/market_rate*(1-(1/(1+market_rate)**n))+par_value/(1+market_rate)**n\n\t\ndef array_to_series(data):\n\t'''\n\tConverts numpy.array into pandas.series\n\t'''\n\treturn pd.Series(data)\n\ndef series_to_array(data):\n\t'''\n\tConverts pandas.series into numpy.array\n\tNOTE: Deprecated for Python 3+\n\t'''\n\treturn data.as_matrix()\n\ndef kelly_leverage(returns, rf=0):\n\t'''\n\tCalculate Optimal Leverage According to Kelly Formula:\n\t(meanReturn-rf)/(stdReturn)^2\n\treturns= returns series\n\trf= risk-free rate (0.n format)\n\t'''\n\tmean= returns.mean()\n\tstd= returns.std()\n\treturn (mean-rf)/(std**2)\n\ndef sharpe_ratio(returns, rf=0):\n\t'''\n\tCalculate Basic Sharpe Ratio According to Formula:\n\t(meanReturn-rf)/(stdReturn)\n\treturns= returns series\n\trf= risk-free rate (0.n format)\n\t'''\n\tmean= returns.mean()\n\tstd= returns.std()\n\treturn (mean-rf)/(std)\n\ndef kelly_criterion(W=0.5, R=1):\n\t'''\n\tCalculate Optimal Portfolio Weight According to Kelly Criterion:\n\tW= winning probability\n\tR= win/loss ratio\n\t'''\n\treturn W- ((1-W)/R)\n\ndef ols(Y, X, show_print=True):\n\t'''\n\tRuns and fits an Ordinary Least Squares \n\tregression on y from x's; including \n\tshow_print willprint the summary of the regression\n\t'''\n\tmodel= sm.OLS(Y, X)\n\tresults= model.fit()\n\tif show_print:\n\t\tlogging.info(results.summary())\n\n\treturn results", "meta": {"hexsha": "00575718eb30acf85f9576ef98c47161af5ffd54", "size": 5262, "ext": "py", "lang": "Python", "max_stars_repo_path": "brd_mod/brdecon.py", "max_stars_repo_name": "benrdavison/brd_mod", "max_stars_repo_head_hexsha": "d496c5faece564f3758c25ed99a8240cde0ccf81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "brd_mod/brdecon.py", "max_issues_repo_name": "benrdavison/brd_mod", "max_issues_repo_head_hexsha": "d496c5faece564f3758c25ed99a8240cde0ccf81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "brd_mod/brdecon.py", "max_forks_repo_name": "benrdavison/brd_mod", "max_forks_repo_head_hexsha": "d496c5faece564f3758c25ed99a8240cde0ccf81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6810344828, "max_line_length": 77, "alphanum_fraction": 0.7048650703, "include": true, "reason": "import numpy,import scipy,from scipy,import statsmodels", "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347860767305, "lm_q2_score": 0.894789464699728, "lm_q1q2_score": 0.8719139806183916}}
{"text": "import numpy as np\nfrom scipy import stats\n\ndef Grubbs(data, type = \"Two Sided\", alpha = 0.05, verbose = False):\n    '''\n    Performs the Grub's Outlier test on data.\n    Set verbose to true to see the grubbs value and threshold\n    Returns NaN if no outlier is present\n    Else returns the index of the outlier\n    '''\n    data = np.array(data)\n    mean = np.nanmean(data)\n    std = np.std(data)\n    dof = data.shape[0] -1\n    N = data.shape[0]\n    \n    if type.lower() == \"two sided\":\n        t = stats.t.ppf(q = 1 - alpha / (2*N), df = dof)\n        G = np.max(np.abs(data - mean)) / std\n        threshold = (N-1) / N**.5 * (t**2 / (N-2 + t**2))**.5\n        if verbose:\n            print(f\"G = {G:.4f}\\nGrubbs Threshold = {threshold:.4f}\")\n        if G > threshold:\n            return np.argmax(np.abs(data - mean))\n        else:\n            return np.nan\n        \n    elif type.lower() == \"greater\":\n        t = stats.t.ppf(q = 1 - alpha / (N), df = dof)\n        G = (np.max(data) - mean) / std\n        threshold = (N-1) / N**.5 * (t**2 / (N-2 + t**2))**.5\n        if verbose:\n            print(f\"G = {G:.4f}\\nGrubbs Threshold = {threshold:.4f}\")\n        if G > threshold:\n            return np.argmax(data)\n        else:\n            return np.nan\n        \n    elif type.lower() == \"lesser\":\n        t = stats.t.ppf(q = 1 - alpha / (N), df = dof)\n        G = (mean - np.min(data)) / std\n        threshold = (N-1) / N**.5 * (t**2 / (N-2 + t**2))**.5\n        if verbose:\n            print(f\"G = {G:.4f}\\nGrubbs Threshold = {threshold:.4f}\")\n        if G > threshold:\n            return np.argmin(data)\n        else:\n            return np.nan\n", "meta": {"hexsha": "7619a67d95e9ae8b4162f00e36babc0d89d87055", "size": 1643, "ext": "py", "lang": "Python", "max_stars_repo_path": "analysis_utilities/Grubbs.py", "max_stars_repo_name": "CashabackLab/AnalysisUtilities", "max_stars_repo_head_hexsha": "c23643971f774cf6c7e5ac825b1f83b06778e7ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-04T14:57:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T14:57:17.000Z", "max_issues_repo_path": "analysis_utilities/Grubbs.py", "max_issues_repo_name": "CashabackLab/AnalysisUtilities", "max_issues_repo_head_hexsha": "c23643971f774cf6c7e5ac825b1f83b06778e7ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis_utilities/Grubbs.py", "max_forks_repo_name": "CashabackLab/AnalysisUtilities", "max_forks_repo_head_hexsha": "c23643971f774cf6c7e5ac825b1f83b06778e7ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5306122449, "max_line_length": 69, "alphanum_fraction": 0.496652465, "include": true, "reason": "import numpy,from scipy", "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347897888528, "lm_q2_score": 0.8947894541786199, "lm_q1q2_score": 0.8719139736878257}}
{"text": "import numpy as np\nfrom scipy.special import comb\n\n#Based on code from JohnDeJesus22: https://github.com/JohnDeJesus22/DataScienceMathFunctions/blob/master/hypergeometricfunctions.py\n\ndef hypergeom_pmf(N, A, n, x):\n    \n    '''\n    Probability Mass Function for Hypergeometric Distribution\n    :param N: population size\n    :param A: total number of desired items in N\n    :param n: number of draws made from N\n    :param x: number of desired items in our draw of n items\n    :returns: PMF computed at x\n    '''\n    Achoosex = comb(A,x)\n    NAchoosenx = comb(N-A, n-x)\n    Nchoosen = comb(N,n)\n    \n    return (Achoosex)*NAchoosenx/Nchoosen\n    \n    \ndef hypergeom_cdf(N, A, n, t, min_value = None, max_value = None):\n    \n    '''\n    Cumulative Density Funtion for Hypergeometric Distribution\n    :param N: population size\n    :param A: total number of desired items in N\n    :param n: number of draws made from N\n    :param t: number of desired items in our draw of n items up to t\n    :returns: CDF computed up to t\n    '''\n    if min_value:\n        if(max_value):\n            return np.sum([hypergeom_pmf(N, A, n, x) for x in range(min_value, max_value+1)])\n        else:\n            return np.sum([hypergeom_pmf(N, A, n, x) for x in range(min_value, t+1)])\n    \n    return np.sum([hypergeom_pmf(N, A, n, x) for x in range(t+1)])\n", "meta": {"hexsha": "b2eef94f6bdcff695e2d1fca4a14a300fe6dd725", "size": 1334, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils.py", "max_stars_repo_name": "aastroza/mtg-discord-bot", "max_stars_repo_head_hexsha": "b5b34d5c5034d33e50da188b836b7e29537791d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils.py", "max_issues_repo_name": "aastroza/mtg-discord-bot", "max_issues_repo_head_hexsha": "b5b34d5c5034d33e50da188b836b7e29537791d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils.py", "max_forks_repo_name": "aastroza/mtg-discord-bot", "max_forks_repo_head_hexsha": "b5b34d5c5034d33e50da188b836b7e29537791d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.35, "max_line_length": 131, "alphanum_fraction": 0.6581709145, "include": true, "reason": "import numpy,from scipy", "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.963779946215714, "lm_q2_score": 0.9046505357435622, "lm_q1q2_score": 0.8718840446829472}}
{"text": "import matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\nimport torch\n\n\nprint('目标函数 f(x) = x*x')\n\n\ndef gd(eta):\n    x = 10\n    results = [x]\n    for i in range(10):\n        x -= eta * 2 * x # 导数\n        results.append(x)\n    print('epoch 10, x:', x)\n    return results\n\n\nprint('进行一维梯度下降')\nres = gd(0.2)\nprint(res)\nprint('绘制迭代轨迹')\n\n\ndef show_trace(res):\n    n = max(abs(min(res)), abs(max(res)), 10)\n    f_line = np.arange(-n, n, 0.1)\n    plt.plot(f_line, [x * x for x in f_line])\n    plt.plot(res, [x * x for x in res], '-o')\n    plt.xlabel('x')\n    plt.ylabel('f(x)')\n    plt.show()\n\n\nshow_trace(res)\n\nprint('尝试不同学习率，0.05')\nshow_trace(gd(0.05))\n\nprint('尝试不同学习率，1.1')\nshow_trace(gd(1.1))\n\nprint('进行二维梯度下降')\n\n\ndef train_2d(trainer):\n    x1, x2, s1, s2 = -5, -2, 0, 0\n    results = [(x1, x2)]\n    for i in range(20):\n        x1, x2, s1, s2 = trainer(x1, x2, s1, s2)\n        results.append((x1, x2))\n    print('epoch %d, x1 %f, x2 %f' % (i+1, x1, x2))\n    return results\n\n\ndef show_trace_2d(f, results):\n    plt.plot(*zip(*results), '-o', color='#ff7f0e')\n    x1, x2 = np.meshgrid(np.arange(-5.5, 1.0, 0.1), np.arange(-3.0, 1.0, 0.1))\n    plt.contour(x1, x2, f(x1, x2), colors='#1f77b4')\n    plt.xlabel('x1')\n    plt.ylabel('x2')\n    plt.show()\n\n\neta = 0.1\n\n\ndef f_2d(x1, x2):\n    return x1 ** 2 + 2 * x2 ** 2\n\n\ndef gd_2d(x1, x2, s1, s2):\n    return (x1 - eta * 2 * x1, x2 - eta * 4 * x2, 0, 0)\n\n\nshow_trace_2d(f_2d, train_2d(gd_2d))\n\nprint('进行随机梯度下降')\n\n\ndef sgd_2d(x1, x2, s1, s2):\n    return (x1 - eta * (2 * x1 + np.random.normal(0.1)),\n            x2 - eta * (4 * x2 + np.random.normal(0.1)), 0, 0)\n\n\nshow_trace_2d(f_2d, train_2d(sgd_2d))\n", "meta": {"hexsha": "2e229295c1c19d2eac25033a30a3e12d263f8bb0", "size": 1690, "ext": "py", "lang": "Python", "max_stars_repo_path": "d2l/38_gradient_descent.py", "max_stars_repo_name": "wdxtub/deep-learning-note", "max_stars_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2019-03-27T20:17:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T23:20:31.000Z", "max_issues_repo_path": "d2l/38_gradient_descent.py", "max_issues_repo_name": "wdxtub/deep-learning-note", "max_issues_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "d2l/38_gradient_descent.py", "max_forks_repo_name": "wdxtub/deep-learning-note", "max_forks_repo_head_hexsha": "47b83a039b80d4757e0436d5cbd2fa3037de3904", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-03-31T10:28:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:25:40.000Z", "avg_line_length": 18.7777777778, "max_line_length": 78, "alphanum_fraction": 0.5633136095, "include": true, "reason": "import numpy", "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543365, "lm_q2_score": 0.9046505312448598, "lm_q1q2_score": 0.8718840365825957}}
{"text": "import numpy as np\nfrom scipy.stats import binom\nfrom scipy.stats import mode\nimport pymc3 as pm\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\np_grid = np.linspace(0.,1.,1000)\nprior = np.repeat(1.,1000)\nlikehood = binom.pmf(6,9,p_grid)\nposterior = likehood*prior\nposterior = posterior/posterior.sum()\n\nplt.plot(p_grid, posterior)\nplt.show()\n\nsample_size = int(10000)\nsamples = np.random.choice(p_grid,p=posterior,size=sample_size,replace=True)\nsns.kdeplot(samples)\nplt.show()\n\nprint('bellow 0.2:'+str(sum(samples<0.2)/sample_size))\nprint('above 0.8:'+str(sum(samples>0.8)/sample_size))\nprint('between 0.2 and 0.8:'+str(sum((samples > 0.2) & (samples < 0.8))/sample_size))\nprint('20% of posterior probability lies under which p-value?'+str(np.percentile(samples,20)))\nprint('20% of posterior probability lies above which p-value?'+str(np.percentile(samples,80)))\nprint('which values of p contain the narrowest interval equal to 66% of posterior?'+str(pm.hpd(samples,alpha=0.66)))\nprint('which values of p contain the 66% posterior, assuming equal posterior prob bellow and above the interval?')\n\n#it's 17,83 - but lets confirm it\nlow = 0\nup = 66\nwhile low < 35 and up < 100:\n    probs = np.percentile(samples,[low,up])    \n    llow = sum(samples<probs[0])/sample_size\n    uup = sum(samples>probs[1])/sample_size\n    if np.abs(llow - uup) > 0.001:\n        low += 1\n        up += 1\n        continue\n    print('-----')\n    print('<%d,%d>'%(low,up))\n    print(str(probs))\n    print('how much posterior prob is bellow %f:%s '%(probs[0],str(llow)))\n    print('how much posterior prob is above %f:%s'%(probs[1],str(uup)))\n    break\n    \n    \n ", "meta": {"hexsha": "5003acd90dddad62cb65f188cea40bf50c43602e", "size": 1644, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch3/easy.py", "max_stars_repo_name": "xSakix/bayesian_analyses", "max_stars_repo_head_hexsha": "14042e193507bae6d69caeb4035ac45ef9044176", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3/easy.py", "max_issues_repo_name": "xSakix/bayesian_analyses", "max_issues_repo_head_hexsha": "14042e193507bae6d69caeb4035ac45ef9044176", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/easy.py", "max_forks_repo_name": "xSakix/bayesian_analyses", "max_forks_repo_head_hexsha": "14042e193507bae6d69caeb4035ac45ef9044176", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5510204082, "max_line_length": 116, "alphanum_fraction": 0.6891727494, "include": true, "reason": "import numpy,from scipy,import pymc3", "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9759464492044004, "lm_q2_score": 0.8933094081846421, "lm_q1q2_score": 0.8718221449586858}}
{"text": "import numpy as np  \nfrom numpy import dtype, linalg\n\ndef jacobi(A, b, x0, tol, N):  \n    \"\"\"\n    Jacobi method: solve Ax = b given an initial approximation x0\n    Parameters:\n        a: Matrix A from system Ax=b\n        b: Array containing b values\n        x0: Initial approximation of solution\n        tol: Tolerance\n        iter_max: Maximum number of iterations\n    Returns:\n        x: Solution of linear system\n    \"\"\"\n    A = A.astype('double')  \n    b = b.astype('double')  \n    x0 = x0.astype('double')  \n \n    n = np.shape(A)[0]  \n    x = np.zeros(n)  \n    it = 0\n\n    while (it < N):  \n        it += 1\n\n        for i in np.arange(n):  \n            x[i] = b[i]  \n            for j in np.concatenate((np.arange(0, i), np.arange(i + 1, n))):\n                x[i] -= A[i, j] * x0[j]\n            x[i] /= A[i, i]  \n\n        new_epsilon = np.linalg.norm(x - x0, np.inf) / np.linalg.norm(x, np.inf)\n\n        if (new_epsilon < tol):  \n            return x  \n\n        x0 = np.copy(x)  \n\n    raise NameError('Max. iterations exceeded')\n\ndef gauss_seidel(A, b, x0, tol, N): \n    \"\"\"\n    Gauss-Seidel method: solve Ax = b given an initial approximation x0\n    Parameters:\n        a: Matrix A from system Ax=b\n        b: Array containing b values\n        x0: Initial approximation of solution\n        tol: Tolerance\n        iter_max: Maximum number of iterations\n    Returns:\n        x: Solution of linear system\n    \"\"\"\n    A = A.astype('double')  \n    b = b.astype('double')  \n    x0 = x0.astype('double')  \n \n    n = np.shape(A)[0]  \n    x = np.copy(x0)  \n    it = 0  \n\n    while (it < N):  \n        it += 1\n  \n        for i in np.arange(n):  \n            x[i] = b[i]  \n            for j in np.concatenate((np.arange(0,i),np.arange(i + 1, n))):  \n                x[i] -= A[i, j] * x[j]  \n            x[i] /= A[i, i]  \n\n        new_epsilon = np.linalg.norm(x - x0, np.inf) / np.linalg.norm(x, np.inf)\n        \n        if (new_epsilon < tol):  \n            return x  \n\n        x0 = np.copy(x)  \n    return x", "meta": {"hexsha": "7521b75d5c6576fb9d9af8cb0cf6e48bcdfa4eda", "size": 2004, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_systems_iterative.py", "max_stars_repo_name": "izaiasmachado/numerical-methods", "max_stars_repo_head_hexsha": "4d593a58d1bd564df36cca913d9400bb39ba2edd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_systems_iterative.py", "max_issues_repo_name": "izaiasmachado/numerical-methods", "max_issues_repo_head_hexsha": "4d593a58d1bd564df36cca913d9400bb39ba2edd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_systems_iterative.py", "max_forks_repo_name": "izaiasmachado/numerical-methods", "max_forks_repo_head_hexsha": "4d593a58d1bd564df36cca913d9400bb39ba2edd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.025974026, "max_line_length": 80, "alphanum_fraction": 0.50249501, "include": true, "reason": "import numpy,from numpy", "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.975946444307138, "lm_q2_score": 0.8933094010836642, "lm_q1q2_score": 0.8718221336537411}}
{"text": "\"\"\"\nLet d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).\nIf d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable\nnumbers.\n\nFor example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284.\nThe proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.\n\nEvaluate the sum of all the amicable numbers under 10000.\n\"\"\"\n\nimport numpy as np\nN = 10000\n\n\ndef d(n):\n    divisors = set()\n    divisors.add(1)\n\n    less_half = np.math.floor(n/2)\n\n    for i in range(2, less_half + 1):\n\n        if n % i == 0:\n            divisors.add(i)\n\n    return sum(divisors)\n\n\ndef is_amicable(m):\n    a = d(m)\n    b = d(a)\n\n    if (m == b) and (a != b):\n        return m\n    else:\n        return False\n\n\namicable_pairs = set()\n\nfor j in range(1, N):\n    check = is_amicable(j)\n\n    if check:\n        amicable_pairs.add(j)\n\nprint(f'Sum of all the amicable numbers under {N} is {sum(amicable_pairs)}')\n", "meta": {"hexsha": "63248d3b63307e55a2e464cef6b695e322be3dc4", "size": 1037, "ext": "py", "lang": "Python", "max_stars_repo_path": "Solutions/Problem 21 - Amicable numbers.py", "max_stars_repo_name": "ismand95/ProjectEuler", "max_stars_repo_head_hexsha": "a03c30af13ec331140374258db805196dc96fef3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Solutions/Problem 21 - Amicable numbers.py", "max_issues_repo_name": "ismand95/ProjectEuler", "max_issues_repo_head_hexsha": "a03c30af13ec331140374258db805196dc96fef3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/Problem 21 - Amicable numbers.py", "max_forks_repo_name": "ismand95/ProjectEuler", "max_forks_repo_head_hexsha": "a03c30af13ec331140374258db805196dc96fef3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1632653061, "max_line_length": 112, "alphanum_fraction": 0.6113789778, "include": true, "reason": "import numpy", "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290930537122, "lm_q2_score": 0.8976953016868439, "lm_q1q2_score": 0.8717780241657233}}
{"text": "import numpy as np\n\n# Generate some random\tdata \ndata = np.random.randn(2, 3)\n\nprint(data)\n\nprint(data * 10)\n\nprint(data + data)\n\nprint(data.shape)\n\nprint(data.dtype)\n\ndata1 = [6, 7.5, 8, 0, 1]\n\narr1 = np.array(data1)\n\nprint(arr1)\n\ndata2 = [[1,2,3,4],[5,6,7,8]]\narr2 = np.array(data2)\n\nprint(arr2)\n\nprint(arr2.ndim)\nprint(arr2.shape)\n\nprint(arr1.dtype)\nprint(arr2.dtype)\n\nprint(np.zeros(10))\nprint(np.zeros((3,6)))\n\nprint(np.empty((2,3,2)))\n\nprint(np.arange(15))\n\narr1 = np.array([1,2,3], dtype=np.float64)\n\nprint(arr1)\n\narr3d =\tnp.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])\nprint(arr3d)\nprint(arr3d[0])\n\n# 基本的索引和切片\narr = np.arange(10)\nprint(arr)\n\nprint(arr[5])\n\nprint(arr[5:8])\narr[5:8] = 12\nprint(arr)\n\n# 切片索引\narr2d = [[1,2,3],[4,5,6],[7,8,9]]\nprint(arr2d[:2])\nprint(arr2d[1:])\n\n# 花式索引\narr = np.empty((8, 4))\nfor i in range(8):\n    arr[i] = i\n\nprint(arr)\n\nprint(arr[[4, 3, 0, 6]])\n\n\narr = np.random.randn(6, 3)\nprint(arr)\n\nprint(np.dot(arr.T, arr))\n\n# 通用函数\narr = np.arange(10)\nprint(arr)\n\nprint(np.sqrt(arr))\n\nprint(np.exp(arr))\n\nx = np.random.randn(8)\n\ny = np.random.randn(8)\n\nprint(x)\nprint(y)\n\nprint(np.maximum(x, y))\n\narr = np.random.randn(7) * 5\nprint(arr)\n\nremainder, whole_part =\tnp.modf(arr)\nprint(remainder)\nprint(whole_part)\n\npoints = np.arange(-5, 5, 0.01)\n\nxs, ys = np.meshgrid(points, points)\n\nprint(ys)\n\nz = np.sqrt(xs ** 2 + ys ** 2)\nprint(z)\n\nimport matplotlib.pyplot as plt\n\nplt.imshow(z, cmap=plt.cm.gray); plt.colorbar()\nplt.title(\"Image\tplot\tof\t$\\sqrt{x^2\t+\ty^2}$\tfor\ta\tgrid\tof\tvalues\") ", "meta": {"hexsha": "dc5155c4ff3c25eb7fe13096114635ce9c1aed0b", "size": 1525, "ext": "py", "lang": "Python", "max_stars_repo_path": "learn.py", "max_stars_repo_name": "zhulinhai/pyLearn", "max_stars_repo_head_hexsha": "664f03cad26b540f83e64f278adf60316efb81d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "learn.py", "max_issues_repo_name": "zhulinhai/pyLearn", "max_issues_repo_head_hexsha": "664f03cad26b540f83e64f278adf60316efb81d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "learn.py", "max_forks_repo_name": "zhulinhai/pyLearn", "max_forks_repo_head_hexsha": "664f03cad26b540f83e64f278adf60316efb81d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.3771929825, "max_line_length": 69, "alphanum_fraction": 0.6268852459, "include": true, "reason": "import numpy", "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191284552529, "lm_q2_score": 0.9124361652391386, "lm_q1q2_score": 0.871667722147307}}
{"text": "#%%\nimport numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\nplt.style.use(\"bmh\")\n\n\n# Las ecuaciones diferenciales del modelo SIR\ndef deriv(y, t, N, beta, gamma):\n    S, I, R = y\n    dSdt = -beta * S * I / N\n    dIdt = beta * S * I / N - gamma * I\n    dRdt = gamma * I\n    return dSdt, dIdt, dRdt\n\n\t\ndef plot(S, I, R, t, divide_by=1):\n    # Dibujamos los datos de S(t), I(t) y R(t)\n    fig, ax = plt.subplots()\n    ax.plot(t, S / divide_by, 'b', alpha=0.5, lw=2, label='Susceptible')\n    ax.plot(t, I / divide_by, 'r', alpha=0.5, lw=2, label='Infectado')\n    ax.plot(t, R / divide_by, 'g', alpha=0.5, lw=2, label='Recuperado con inmunidad')\n    ax.set_xlabel('Tiempo /días')\n    ax.set_ylabel(f'Número (dividido por {divide_by:,})')\n    legend = ax.legend()\n\ndef plot_with_death_rate(S, I, R, t, divide_by=1, death_rate=0.05):\n    # Dibujamos los datos de S(t), I(t) y R(t)\n    fig, ax = plt.subplots()\n    ax.plot(t, S / divide_by, 'b', alpha=0.5, lw=2, label='Susceptible')\n    ax.plot(t, I / divide_by, 'r', alpha=0.5, lw=2, label='Infectado')\n    RR = R * (1 - death_rate)\n    DD = R - RR\n    ax.plot(t, RR / divide_by, 'g', alpha=0.5, lw=2, label='Recuperado con inmunidad')\n    ax.plot(t, DD / divide_by, 'k', alpha=0.5, lw=2, label='No recuperado')\n    ax.set_xlabel('Tiempo /días')\n    ax.set_ylabel(f'Número (dividido por {divide_by:,})')\n    legend = ax.legend()\n\n# población inicial, N.\nN = 779_853 # poblaciçon de un país como España\n \n# Número inicial de infectados y recuperados, I0 and R0.\nI0 = 2/N\nR0 = 0\n \n# El resto, casi todo N, es susceptible de infectarse\nS0 = 779_853\n \n# Tasas de contagio y recuperación.\nbeta = 0.06 # contagio\ngamma = 0.021 # recuperación\n \n# Pasos temporales (en días)\nt = np.linspace(0, 652, 652)\n \n# condiciones iniciales\ny0 = S0, I0, R0\n\n# Integrate the SIR equations over the time grid, t.\nret = odeint(deriv, y0, t, args=(N, beta, gamma))\nS, I, R = ret.T\n \nplot(S, I, R, t) # Datos sin normalizar\nplot(S, I, R, t, divide_by=N) # Datos normalizados\n \t\nplot_with_death_rate(S, I, R, t, divide_by=N, death_rate=0.05)\n# %%\n", "meta": {"hexsha": "3c172de3bce8cd28bd77c0bb985613046a9e43a6", "size": 2095, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tareas/EDO/SIR.py", "max_stars_repo_name": "monotera/Analisis-numerico_-1057-_2130", "max_stars_repo_head_hexsha": "f0acf6856028be8a20e33efd11f70d0817fdeeb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tareas/EDO/SIR.py", "max_issues_repo_name": "monotera/Analisis-numerico_-1057-_2130", "max_issues_repo_head_hexsha": "f0acf6856028be8a20e33efd11f70d0817fdeeb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tareas/EDO/SIR.py", "max_forks_repo_name": "monotera/Analisis-numerico_-1057-_2130", "max_forks_repo_head_hexsha": "f0acf6856028be8a20e33efd11f70d0817fdeeb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3623188406, "max_line_length": 86, "alphanum_fraction": 0.6338902148, "include": true, "reason": "import numpy,from scipy", "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191271831559, "lm_q2_score": 0.9124361598816667, "lm_q1q2_score": 0.8716677158685043}}
{"text": "\"\"\"This file contains code used in \"Think Stats\",\nby Allen B. Downey, available from greenteapress.com\n\nCopyright 2014 Allen B. Downey\nLicense: GNU GPLv3 http://www.gnu.org/licenses/gpl.html\n\"\"\"\n\nfrom __future__ import print_function, division\n\nimport thinkstats2\nimport thinkplot\n\nimport math\nimport random\nimport numpy as np\n\nfrom scipy import stats\nfrom estimation import RMSE, MeanError\n\n\n\"\"\"This file contains a solution to exercises in Think Stats:\n\nExercise 8.1\n\nIn this chapter we used $\\xbar$ and median to estimate $\\mu$, and\nfound that $\\xbar$  yields lower MSE.\nAlso, we used $S^2$ and $S_{n-1}^2$ to estimate $\\sigma$, and found that\n$S^2$ is biased and $S_{n-1}^2$ unbiased.\n\nRun similar experiments to see if $\\xbar$ and median are biased estimates\nof $\\mu$.\nAlso check whether $S^2$ or $S_{n-1}^2$ yields a lower MSE.\n\nMy conclusions:\n\n1) xbar and median yield lower mean error as m increases, so neither\none is obviously biased, as far as we can tell from the experiment.\n\n2) The biased estimator of variance yields lower RMSE than the unbiased\nestimator, by about 10%.  And the difference holds up as m increases.\n\n\nExercise 8.2\n\nSuppose you draw a sample with size $n=10$ from a population \nwith an exponential disrtribution with $\\lambda=2$.  Simulate\nthis experiment 1000 times and plot the sampling distribution of\nthe estimate $\\lamhat$.  Compute the standard error of the estimate\nand the 90\\% confidence interval.\n\nRepeat the experiment with a few different values of $n$ and make\na plot of standard error versus $n$.\n\n1) With sample size 10:\n\nstandard error 0.896717911545\nconfidence interval (1.2901330772324622, 3.8692334892427911)\n\n2) As sample size increases, standard error and the width of\nthe CI decrease:\n\n10      0.90    (1.3, 3.9)\n100     0.21    (1.7, 2.4)\n1000    0.06    (1.9, 2.1)\n\nAll three confidence intervals contain the actual value, 2.\n\n\nExercise 8.3\n\nIn games like hockey and soccer, the time between goals is\nroughly exponential.  So you could estimate a team's goal-scoring rate\nby observing the number of goals they score in a game.  This\nestimation process is a little different from sampling the time\nbetween goals, so let's see how it works.\n\nWrite a function that takes a goal-scoring rate, {\\tt lam}, in goals\nper game, and simulates a game by generating the time between goals\nuntil the total time exceeds 1 game, then returns the number of goals\nscored.\n\nWrite another function that simulates many games, stores the\nestimates of {\\tt lam}, then computes their mean error and RMSE.\n\nIs this way of making an estimate biased?  Plot the sampling\ndistribution of the estimates and the 90\\% confidence interval.  What\nis the standard error?  What happens to sampling error for increasing\nvalues of {\\tt lam}?\n\nMy conclusions:\n\n1) RMSE for this way of estimating lambda is 1.4\n\n2) The mean error is small and decreases with m, so this estimator\nappears to be unbiased.\n\nOne note: If the time between goals is exponential, the distribution\nof goals scored in a game is Poisson.\n\nSee https://en.wikipedia.org/wiki/Poisson_distribution\n\n\"\"\"\n\ndef Estimate1(n=7, m=100000):\n    \"\"\"Mean error for xbar and median as estimators of population mean.\n\n    n: sample size\n    m: number of iterations\n    \"\"\"\n    mu = 0\n    sigma = 1\n\n    means = []\n    medians = []\n    for _ in range(m):\n        xs = [random.gauss(mu, sigma) for i in range(n)]\n        xbar = np.mean(xs)\n        median = np.median(xs)\n        means.append(xbar)\n        medians.append(median)\n\n    print('Experiment 1')\n    print('mean error xbar', MeanError(means, mu))\n    print('mean error median', MeanError(medians, mu))\n\n\ndef Estimate2(n=7, m=100000):\n    \"\"\"RMSE for biased and unbiased estimators of population variance.\n\n    n: sample size\n    m: number of iterations\n    \"\"\"\n    mu = 0\n    sigma = 1\n\n    estimates1 = []\n    estimates2 = []\n    for _ in range(m):\n        xs = [random.gauss(mu, sigma) for i in range(n)]\n        biased = np.var(xs)\n        unbiased = np.var(xs, ddof=1)\n        estimates1.append(biased)\n        estimates2.append(unbiased)\n\n    print('Experiment 2')\n    print('RMSE biased', RMSE(estimates1, sigma**2))\n    print('RMSE unbiased', RMSE(estimates2, sigma**2))\n\n\ndef SimulateSample(lam=2, n=10, m=1000):\n    \"\"\"Sampling distribution of L as an estimator of exponential parameter.\n\n    lam: parameter of an exponential distribution\n    n: sample size\n    m: number of iterations\n    \"\"\"\n    def VertLine(x, y=1):\n        thinkplot.Plot([x, x], [0, y], color='0.8', linewidth=3)\n\n    estimates = []\n    for j in range(m):\n        xs = np.random.exponential(1/lam, n)\n        lamhat = 1/np.mean(xs)\n        estimates.append(lamhat)\n\n    stderr = RMSE(estimates, lam)\n    print('standard error', stderr)\n\n    cdf = thinkstats2.Cdf(estimates)\n    ci = cdf.Percentile(5), cdf.Percentile(95)\n    print('confidence interval', ci)\n    VertLine(ci[0])\n    VertLine(ci[1])\n\n    # plot the CDF\n    thinkplot.Cdf(cdf)\n    thinkplot.Save(root='estimation2',\n                   xlabel='estimate',\n                   ylabel='CDF',\n                   title='Sampling distribution')\n\n    return stderr\n\n\ndef SimulateGame(lam):\n    \"\"\"Simulates a game and returns the estimated goal-scoring rate.\n\n    lam: actual goal scoring rate in goals per game\n    \"\"\"\n    goals = 0\n    t = 0\n    while True:\n        time_between_goals = random.expovariate(lam)\n        t += time_between_goals\n        if t > 1:\n            break\n        goals += 1\n\n    # estimated goal-scoring rate is the actual number of goals scored\n    L = goals\n    return L\n\n\ndef Estimate4(lam=2, m=1000000):\n\n    estimates = []\n    for i in range(m):\n        L = SimulateGame(lam)\n        estimates.append(L)\n\n    print('Experiment 4')\n    print('rmse L', RMSE(estimates, lam))\n    print('mean error L', MeanError(estimates, lam))\n    \n    pmf = thinkstats2.Pmf(estimates)\n\n    thinkplot.Hist(pmf)\n    thinkplot.Show()\n        \n\ndef main():\n    thinkstats2.RandomSeed(17)\n\n    Estimate1()\n    Estimate2()\n\n    print('Experiment 3')\n    for n in [10, 100, 1000]:\n        stderr = SimulateSample(n=n)\n        print(n, stderr)\n\n    Estimate4()\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "ea185520de51e08367b1f4019c99bcf28730d09c", "size": 6176, "ext": "py", "lang": "Python", "max_stars_repo_path": "DSC 530 - Data Exploration and Analysis/ThinkStats2/code/chap08soln.py", "max_stars_repo_name": "Hakuna-Patata/BU_MSDS_PTW", "max_stars_repo_head_hexsha": "4759cb2db3e63ae5722bd42771e4d228dfbc733d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DSC 530 - Data Exploration and Analysis/ThinkStats2/code/chap08soln.py", "max_issues_repo_name": "Hakuna-Patata/BU_MSDS_PTW", "max_issues_repo_head_hexsha": "4759cb2db3e63ae5722bd42771e4d228dfbc733d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DSC 530 - Data Exploration and Analysis/ThinkStats2/code/chap08soln.py", "max_forks_repo_name": "Hakuna-Patata/BU_MSDS_PTW", "max_forks_repo_head_hexsha": "4759cb2db3e63ae5722bd42771e4d228dfbc733d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.05907173, "max_line_length": 75, "alphanum_fraction": 0.6761658031, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.9111797003640645, "lm_q1q2_score": 0.8716656670934035}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov  9 07:52:36 2021\r\n\r\n@author: Ezra\r\n\"\"\"\r\n\r\nimport numpy as np  \r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n\r\ndef f(t,y):\r\n    return y+np.cos(t)-t*t\r\n\r\ndef fa(t,y):\r\n    return (1/2)*(4-np.exp(t)+4*t+2*t*t-np.cos(t)+np.sin(t))\r\n\r\ndef fp(t,y):\r\n    return f(t,y)-np.sin(t)-2*t\r\n\r\ndef fdp(t,y):\r\n    return fp(t,y)-np.cos(t)-2\r\n\r\ndef ftp(t,y):\r\n    return fdp(t,y)+np.sin(t)\r\n\r\ndef fqp(t,y):\r\n    return ftp(t,y)+np.cos(t)\r\n\r\ndef euler(n,a,b,alpha):\r\n    '''\r\n    Parameters\r\n    ----------\r\n    n : integer\r\n        number of steps.\r\n    a : float\r\n        starting value for iVar.\r\n    b : tuple\r\n        ending value for iVar.\r\n    alpha : float\r\n        intial condition.\r\n\r\n    Returns\r\n    -------\r\n    t : float\r\n        time.\r\n    w : float\r\n        dVar.\r\n    '''\r\n    h=(b-a)/n\r\n    t=a\r\n    w=alpha\r\n    for i in range(n):\r\n        w=w+h*f(t,w)\r\n        t=t+h\r\n    return t,w\r\n\r\ndef taylor2(n,a,b,alpha):\r\n    '''\r\n    Parameters\r\n    ----------\r\n    n : integer\r\n        number of steps.\r\n    a : float\r\n        starting value for iVar.\r\n    b : tuple\r\n        ending value for iVar.\r\n    alpha : float\r\n        intial condition.\r\n\r\n    Returns\r\n    -------\r\n    t : float\r\n        time.\r\n    w : float\r\n        dVar.\r\n    '''\r\n    h=(b-a)/n\r\n    t=a\r\n    w=alpha\r\n    for i in range(n):\r\n        w=w+h*f(t,w) + (h*h/2) * fp(t,w)\r\n        t = t+h\r\n    return t,w\r\n\r\ndef taylor4(n,a,b,alpha):\r\n    '''\r\n     See taylor 2\r\n    '''\r\n    h=(b-a)/n\r\n    t=a\r\n    w=alpha\r\n    for i in range(n):\r\n        w=w+h*f(t,w) + (h*h/2) * fp(t,w)+(h**3/6)*fdp(t,w)+(h**4/24)*ftp(t,w)\r\n        t = t+h\r\n    return t,w\r\n\r\ndef taylor6(n,a,b,alpha):\r\n     '''\r\n      See taylor 2\r\n     '''\r\n     h=(b-a)/n\r\n     t=a\r\n     w=alpha\r\n     for i in range(n):\r\n        w=w+h*f(t,w) + (h*h/2) * fp(t,w)+(h**3/6)*fdp(t,w)+(h**4/24)*ftp(t,w)+(h**5/120)*fqp(t,w)\r\n        t = t+h\r\n     return t,w\r\n\r\ndef err(x,y):\r\n    '''\r\n    Parameters\r\n    ----------\r\n    x : approximate solution\r\n    y : exact solution\r\n\r\n    Returns\r\n    -------\r\n    relative error between x and y\r\n    '''\r\n    return abs((y-x)/y)\r\n\r\nyEval= 2\r\nanaSoln = fa(yEval, 34.2343)\r\nt,eulerSoln = euler(20,0,yEval,1)\r\n\r\nn = np.array([10,20,50,100,200,1000])\r\neulerErr = []\r\nt2Err = []\r\nt4Err=[]\r\nt6Err=[]\r\n\r\ny1=np.linspace(0,4,20)\r\nt,esol=euler(20,0,y1,1)\r\nt,t2=taylor2(20,0,y1,1)\r\nt,t4=taylor4(20,0,y1,1)\r\nt,t6=taylor6(20,0,y1,1)\r\nana=fa(y1,34.2343)\r\n\r\nplt.figure(0)\r\nplt.grid(True)\r\nplt.title(\"Plot of approximate solution of y=f(t,y)\")\r\nplt.xlabel(\"t\")\r\nplt.ylabel(\"y(t)\")\r\nplt.plot(y1,esol,label=\"euler\")\r\nplt.plot(y1,t2,label=\"taylor2\")\r\nplt.plot(y1,t4,label=\"taylor4\")\r\nplt.plot(y1,t6,label=\"taylor6\")\r\nplt.plot(y1,ana,label=\"analytic\")\r\nplt.legend()\r\nplt.show()\r\n\r\n\r\nfor i in range(len(n)):\r\n    t,eulerSoln = euler(n[i],0,yEval,1)\r\n    eulerErr.append(err(eulerSoln,anaSoln))\r\n    t,t2Soln = taylor2(n[i],0,yEval,1)\r\n    t2Err.append(err(t2Soln,anaSoln))\r\n    t,t4Soln = taylor4(n[i],0,yEval,1)\r\n    t4Err.append(err(t4Soln,anaSoln))\r\n    t,t6Soln = taylor6(n[i],0,yEval,1)\r\n    t6Err.append(err(t6Soln,anaSoln))\r\n    \r\n    \r\nerror=pd.DataFrame({'eulerErr': eulerErr,'t2Err':t2Err,'t4Err':t4Err,\r\n                        't6Err':t6Err})\r\nfile_name='techlab4error.xlsx'\r\nerror.to_excel(file_name)\r\n\r\nprint(\"Analytic Soln:\", anaSoln, \"Euler Soln:\", eulerSoln, \"Difference\",\r\n      anaSoln-eulerSoln, \"taylor2:\", t2Soln, \"taylor4:\", t4Soln)\r\n\r\nplt.figure(1)\r\nplt.grid(True)\r\nplt.title(\"Plot of Relative Error at t=2\")\r\nplt.xlabel(\"n\")\r\nplt.ylabel(\"Relative Error\")\r\nplt.semilogy(n,eulerErr,label=\"euler\")\r\nplt.semilogy(n,t2Err,label=\"taylor2\")\r\nplt.semilogy(n,t4Err,label=\"taylor4\")\r\nplt.semilogy(n,t6Err,label=\"taylor6\")\r\nplt.legend()\r\nplt.show()\r\n\r\n\r\nprint(eulerErr, \"test\")\r\n\r\n\r\n'''\r\nSolution to the Gompertz differential equation using eulers method\r\n'''\r\n\r\nz=.0439\r\nK=12000.0\r\ndef G(t,N):\r\n    return z*np.log(K/N)*N\r\n\r\n# def Gp(t,N):\r\n#     return z*K+z*np.log(K/N)*G(t,N)\r\n\r\n\r\ndef euler2(n,a,b,alpha):\r\n    h=(b-a)/n\r\n    t=a\r\n    w=alpha\r\n    for i in range(n):\r\n        w=w+h*G(t,w)\r\n        t=t+h\r\n    return t, w\r\n\r\n# def taylor22(n,a,b,alpha):\r\n#     h=(b-a)/n\r\n#     t=a\r\n#     w=alpha\r\n#     for i in range(n):\r\n#         w=w+h*G(t,w) + (h*h/2) * Gp(t,w)\r\n#         t = t+h\r\n#     return t,w\r\n\r\n\r\nx1=np.linspace(0, 100, 1000, endpoint=True)\r\nt, eulerSoln = euler2(20,0,x1,4000)\r\n# t,t23=taylor22(20,0,x1,4000)\r\n\r\n#print(t, eulerSoln, \"test\")\r\n\r\nplt.figure(2)\r\nplt.grid(True)\r\nplt.title(\"Gompertz solution plot\")\r\nplt.xlabel(\"t\")\r\nplt.ylabel(\"cells\")\r\nplt.plot(t,eulerSoln,label=\"euler\")\r\n# plt.plot(t,t23,label=\"taylor2\")\r\nplt.legend\r\nplt.show()\r\n\r\n\r\ndef Iter(numIter,p0,tol):\r\n    '''\r\n    \r\n\r\n    Parameters\r\n    ----------\r\n    numIter : integer\r\n        how many cells in the tuple you want it to check.\r\n    p0 : float\r\n        value you are looking for.\r\n    tol : float\r\n        how close you need the value to be for it to return the cell.\r\n\r\n    Returns\r\n    -------\r\n    p : float\r\n        the value that it found within the tol.\r\n    i : float\r\n        the value of the cell.\r\n    '''\r\n    i=1\r\n    while i <= numIter:\r\n        p=eulerSoln[i]\r\n        if abs(p-p0) < tol:\r\n            return p,i\r\n        i = i+1\r\n\r\np,m=Iter(1000,11000,10)\r\n\r\nprint(p,m)\r\n", "meta": {"hexsha": "44fb270cadaff8b9a426015b715ef75e28e2d831", "size": 5296, "ext": "py", "lang": "Python", "max_stars_repo_path": "TaylorDiffEq/Tech Lab 4.py", "max_stars_repo_name": "kiwibird2/Numerical-Analysis", "max_stars_repo_head_hexsha": "658eb4ddddc63511a0d574625a1cf359d09c1c52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TaylorDiffEq/Tech Lab 4.py", "max_issues_repo_name": "kiwibird2/Numerical-Analysis", "max_issues_repo_head_hexsha": "658eb4ddddc63511a0d574625a1cf359d09c1c52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TaylorDiffEq/Tech Lab 4.py", "max_forks_repo_name": "kiwibird2/Numerical-Analysis", "max_forks_repo_head_hexsha": "658eb4ddddc63511a0d574625a1cf359d09c1c52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.687732342, "max_line_length": 98, "alphanum_fraction": 0.5266238671, "include": true, "reason": "import numpy", "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298657, "lm_q2_score": 0.9059898203834277, "lm_q1q2_score": 0.8716596705404269}}
{"text": "# The dynamic programming algorithm for the knapsack 0-1 problem.\n# The item values and weights are provided through input lists.\n# The algorithm has pseudo-polynomial time complexity in the number of items: O(nC)\n\nimport numpy as np\n\ndef knapsack_0_1_dp(v, w, C):\n\tn = len(v)\n\tcmax = C\n\t# Subproblem solutions (two-dimensional array (n + 1)x(C + 1))\n\topt = [[0] * (cmax + 1) for _ in range(n + 1)]\n\t# Base case (i = 0)\n\tfor c in range(0, cmax + 1):\n\t\topt[0][c] = 0\n\t# Systematically solve all subproblems\n\tfor i in range(0, n):\n\t\tfor c in range(0, cmax + 1):\n\t\t\t# Use recursion formula\n\t\t\tif w[i] > c:\n\t\t\t\t# Case 1\n\t\t\t\topt[i][c] = opt[i - 1][c]\n\t\t\telse:\n\t\t\t\t# max(Case 1, Case 2)\n\t\t\t\topt[i][c] = max(opt[i - 1][c], v[i] + opt[i - 1][c - w[i]])\n\t# Solution to largest subproblem\n\treturn opt\n\ndef reconstruct(v, w, C, opt):\n\tn = len(v)\n\t# Remaining capacity\n\tcmax = C\n\t# Items included/excluded\n\topt_sol = [None] * n\n\t# Trace back through the two-dimensional array\n\ti = n - 1\n\twhile i >= 0:\n\t\tif (w[i] <= cmax) and (v[i] + opt[i - 1][cmax - w[i]] >= opt[i - 1][cmax]):\n\t\t\t# Case 2, include item i\n\t\t\topt_sol[i] = True\n\t\t\t# Reserve space for included item\n\t\t\tcmax = cmax - w[i]\n\t\telse: \n\t\t\t# Exclude item i, capacity unchanged\n\t\t\topt_sol[i] = False\n\t\ti = i - 1\n\t# Process optimal solution\n\tprint_solution(opt_sol, opt[n - 1][C], v, w, C)\n\ndef print_solution(opt_sol, opt_val, v, w, C):\n\tn = len(opt_sol)\n\tk = 0\n\twhile k < n and opt_sol[k] == 0:\n\t\tk = k + 1\n\n\ttotal_weight = 0\n\tif k < n:\n\t\tprint ('(', k, ',', w[k], ',', v[k], ')', sep='', end='')\n\t\ttotal_weight = total_weight + w[k]\n\t\tfor i in range(k + 1, n):\n\t\t\tif opt_sol[i] == 1:\n\t\t\t\ttotal_weight = total_weight + w[i]\n\t\t\t\tprint (' + ', sep='', end='')\n\t\t\t\tprint ('(', i, ',', w[i], ',', v[i], ')', sep='', end='')\n\t\n\tprint(' => ', '(', total_weight, ',', opt_val, ')', sep='')\t\n\n# List of item values\nv = [7, 2, 10, 4]\n# List of item weights\nw = [3, 6, 9, 5]\n# Knapsack capacity\nC = 15\n# opt = knapsack_0_1_dp(v, w, C)\n# reconstruct(v, w, C, opt)\nv, w = np.loadtxt(\"knapsack_dataset.txt\", dtype=int, unpack=True)\nopt = knapsack_0_1_dp(v[1:], w[1:], v[0])\nreconstruct(v[1:], w[1:], v[0], opt)\n\n", "meta": {"hexsha": "df69af41158737afbbbc5513b4340b047b0f7ee6", "size": 2147, "ext": "py", "lang": "Python", "max_stars_repo_path": "knapsack_0_1/knapsack_0_1_dp.py", "max_stars_repo_name": "Qargo/Knapsack-Algorithm", "max_stars_repo_head_hexsha": "dac7781ab5ad17692f6a80fcf1fd4b66028db3eb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "knapsack_0_1/knapsack_0_1_dp.py", "max_issues_repo_name": "Qargo/Knapsack-Algorithm", "max_issues_repo_head_hexsha": "dac7781ab5ad17692f6a80fcf1fd4b66028db3eb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "knapsack_0_1/knapsack_0_1_dp.py", "max_forks_repo_name": "Qargo/Knapsack-Algorithm", "max_forks_repo_head_hexsha": "dac7781ab5ad17692f6a80fcf1fd4b66028db3eb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1772151899, "max_line_length": 83, "alphanum_fraction": 0.5812761993, "include": true, "reason": "import numpy", "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075755433747, "lm_q2_score": 0.9059898172105135, "lm_q1q2_score": 0.8716596665033923}}
{"text": "# Copyright 2018 - Jonathan Alcantara e Osmar Fernandes\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n#     http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\n\ntolerance = 0.00000001\niterations_limit = 10000\n\ndef multi_newton(x0_vector, f_vector, jacobian_vector):\n\n    x_vector = x0_vector\n    for iteration in range(iterations_limit):\n\n        jacobian_current_values = jacobian_vector(x_vector)\n        function_current_values = f_vector(x_vector)\n        \n        delta_x = -1*(np.linalg.inv(jacobian_current_values)\n                      @ function_current_values)\n\n        x_vector = x_vector + delta_x\n\n        if(np.linalg.norm(delta_x)/np.linalg.norm(x_vector) \\\n            < tolerance):\n            return x_vector\n\n    return \"Convergence not reached\"\n\ndef f_vector(x_vector):\n    return np.array([[x_vector[0][0] + 2*x_vector[1][0] - 2.0], \n            [pow(x_vector[0][0], 2) + 4*pow(x_vector[1][0], 2) - 4]])\n\ndef jacobian_vector(x_vector):\n    return np.array([[1, 2], [2*x_vector[0][0], 8*x_vector[1][0]]])\n\nprint(multi_newton(np.array([[2], [3]]), f_vector, jacobian_vector))\n", "meta": {"hexsha": "94243862d4db168e42c3726a7eb1f5b048c49a8d", "size": 1554, "ext": "py", "lang": "Python", "max_stars_repo_path": "RootFinding/multi_newton.py", "max_stars_repo_name": "JonathanAlcantara/NumericalLinearAlgebra_Applications", "max_stars_repo_head_hexsha": "519de07ef7834c4c1ab42398840baa808d95a6bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RootFinding/multi_newton.py", "max_issues_repo_name": "JonathanAlcantara/NumericalLinearAlgebra_Applications", "max_issues_repo_head_hexsha": "519de07ef7834c4c1ab42398840baa808d95a6bc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RootFinding/multi_newton.py", "max_forks_repo_name": "JonathanAlcantara/NumericalLinearAlgebra_Applications", "max_forks_repo_head_hexsha": "519de07ef7834c4c1ab42398840baa808d95a6bc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0638297872, "max_line_length": 74, "alphanum_fraction": 0.6917631918, "include": true, "reason": "import numpy", "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075755433746, "lm_q2_score": 0.9059898172105135, "lm_q1q2_score": 0.8716596665033922}}
{"text": "from sympy import *\nimport sys\nsys.path.insert(1, '..')\nfrom rodrigues_R_utils import *\n\nx_src_l, y_src_l, z_src_l = symbols('x_src_l y_src_l z_src_l')\nx_trg_g, y_trg_g, z_trg_g = symbols('x_trg_g y_trg_g z_trg_g')\nx_trg_ln, y_trg_ln, z_trg_ln = symbols('x_trg_ln y_trg_ln z_trg_ln')\npx, py, pz = symbols('px py pz')\nsx, sy, sz = symbols('sx sy sz')\n\nposition_symbols = [px, py, pz]\nrodrigues_symbols = [sx, sy, sz]\nall_symbols = position_symbols + rodrigues_symbols\n\npoint_source_local = Matrix([x_src_l, y_src_l, z_src_l,1]).vec()\nRT_wc = matrix44FromRodrigues(px, py, pz, sx, sy, sz)[:-1,:]\npoint_source_global = RT_wc * point_source_local\npoint_on_line_target_global = Matrix([x_trg_g, y_trg_g, z_trg_g])\n\na=point_source_global-point_on_line_target_global\nb=Matrix([x_trg_ln, y_trg_ln, z_trg_ln]).vec()\n\np_proj = point_on_line_target_global + (a.dot(b)/b.dot(b))*b\n\ndelta = Matrix([0,0,0]).vec()-(point_source_global - p_proj)\ndelta_jacobian=delta.jacobian(all_symbols)\n\nprint(delta)\nprint(delta_jacobian)\n\nwith open(\"point_to_projection_onto_line_rodrigues_wc_jacobian.h\",'w') as f_cpp:  \n    f_cpp.write(\"inline void point_to_projection_onto_line_rodrigues_wc(Eigen::Matrix<double, 3, 1> &delta, double px, double py, double pz, double sx, double sy, double sz, double x_src_l, double y_src_l, double z_src_l, double x_trg_g, double y_trg_g, double z_trg_g, double x_trg_ln, double y_trg_ln, double z_trg_ln)\\n\")\n    f_cpp.write(\"{\")\n    f_cpp.write(\"delta.coeffRef(0,0) = %s;\\n\"%(ccode(delta[0,0])))\n    f_cpp.write(\"delta.coeffRef(1,0) = %s;\\n\"%(ccode(delta[1,0])))\n    f_cpp.write(\"delta.coeffRef(2,0) = %s;\\n\"%(ccode(delta[2,0])))\n    f_cpp.write(\"}\")\n    f_cpp.write(\"\\n\")\n    f_cpp.write(\"inline void point_to_projection_onto_line_rodrigues_wc_jacobian(Eigen::Matrix<double, 3, 6> &j, double px, double py, double pz, double sx, double sy, double sz, double x_src_l, double y_src_l, double z_src_l, double x_trg_g, double y_trg_g, double z_trg_g, double x_trg_ln, double y_trg_ln, double z_trg_ln)\\n\")\n    f_cpp.write(\"{\")\n    for i in range (3):\n        for j in range (6):\n            f_cpp.write(\"j.coeffRef(%d,%d) = %s;\\n\"%(i,j, ccode(delta_jacobian[i,j])))\n    f_cpp.write(\"}\")\n\n", "meta": {"hexsha": "9195bb7e61e56c6ab977455f51e5e6e9ca825ee1", "size": 2196, "ext": "py", "lang": "Python", "max_stars_repo_path": "codes/python-scripts/point-to-point-metrics/point_to_projection_onto_line_rodrigues_wc.py", "max_stars_repo_name": "karolmajek/observation_equations", "max_stars_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-11T13:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T22:04:00.000Z", "max_issues_repo_path": "codes/python-scripts/point-to-point-metrics/point_to_projection_onto_line_rodrigues_wc.py", "max_issues_repo_name": "karolmajek/observation_equations", "max_issues_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/python-scripts/point-to-point-metrics/point_to_projection_onto_line_rodrigues_wc.py", "max_forks_repo_name": "karolmajek/observation_equations", "max_forks_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-30T22:33:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T18:21:21.000Z", "avg_line_length": 46.7234042553, "max_line_length": 329, "alphanum_fraction": 0.7213114754, "include": true, "reason": "from sympy", "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.9273632911298345, "lm_q1q2_score": 0.8716411374714997}}
{"text": "import numpy as np\n\n\ndef extendedEuclideanAlgorithm(x1, x2):\n    # base case\n    if x1 == 0:\n        return x2, 0, 1\n    # recursive call\n    gcd, x_, y_ = extendedEuclideanAlgorithm(x2 % x1, x1)\n    x = y_ - (x2 // x1) * x_\n    y = x_\n    return gcd, x, y\n\n\n# modular multiplicative inverse\ndef inverse(n, p):\n    if n == 0:\n        raise ZeroDivisionError('Stahp dividing by zero you!!!')\n    if n < 0:\n        # k ** -1 = p - (-k) ** -1  (mod p)\n        return p - inverse(-n, p)\n    gcd, x, _ = extendedEuclideanAlgorithm(n, p)\n    assert gcd == 1\n    assert np.mod(n*x, p) == 1\n    return np.mod(x, p)\n", "meta": {"hexsha": "ccb23623e177ad01de38b4046ba5b2e64a4b515f", "size": 607, "ext": "py", "lang": "Python", "max_stars_repo_path": "minicurve/helpers.py", "max_stars_repo_name": "marekyggdrasil/minicurve", "max_stars_repo_head_hexsha": "aedaed2b37861c05e29b2c512b8ca99cce711631", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-11T13:40:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T14:22:16.000Z", "max_issues_repo_path": "minicurve/helpers.py", "max_issues_repo_name": "marekyggdrasil/minicurve", "max_issues_repo_head_hexsha": "aedaed2b37861c05e29b2c512b8ca99cce711631", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "minicurve/helpers.py", "max_forks_repo_name": "marekyggdrasil/minicurve", "max_forks_repo_head_hexsha": "aedaed2b37861c05e29b2c512b8ca99cce711631", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3461538462, "max_line_length": 64, "alphanum_fraction": 0.550247117, "include": true, "reason": "import numpy", "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357616286122, "lm_q2_score": 0.8902942319436395, "lm_q1q2_score": 0.8716298914445014}}
{"text": "# https://github.com/llSourcell/Second_Order_Optimization_Newtons_Method/blob/master/newtons_method_optimization.py\n\nfrom sympy import *\nfrom sympy.parsing import sympy_parser as spp\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ninit_printing(use_unicode=True)\n\n\n# Plot range\nplot_from, plot_to, plot_step = -7.0, 7.0, 0.1\n# Precision for iterative methods\ntarget_precision = 0.3\n\nm = Matrix(symbols('x1 x2'))\n\n\ndef dfdx(x, g):\n    # Gradient in multi dimension\n    return [float(g[i].subs(m[0], x[0]).subs(m[1], x[1])) for i in range(len(g))]\n\n\ndef sd(alpha=0.0002):\n    \"\"\"\n    Steepest Descent - 1st order optimization\n    :return:\n    \"\"\"\n    print \"STEEPEST DESCENT: start\"\n    # gradient\n    g = [diff(obj, i) for i in m]\n    # Initialize xs\n    xs = [[0.0, 0.0]]\n    xs[0] = x_start\n    # Get gradient at start location (df/dx or grad(f))\n    iter_s = 0\n    while np.linalg.norm(xs[-1] - x_result) > target_precision:\n        # print \"STEEPEST DESCENT: distance:\", np.linalg.norm(xs[-1] - x_result)\n        gs = dfdx(xs[iter_s], g)\n        # Compute search direction and magnitude (dx)\n        #  with dx = - grad but no line searching\n        xs.append(xs[iter_s] - np.dot(alpha, gs))\n        # print xs[-1]\n        iter_s += 1\n        if iter_s > 10000:\n            break\n    print \"STEEPEST DESCENT: result distance:\", np.linalg.norm(xs[-1] - x_result)\n    xs = np.array(xs)\n    plt.plot(xs[:, 0], xs[:, 1], 'g-o')\n\n\ndef nm():\n    \"\"\"\n    Newton's method - 2nd order optimization\n    :return:\n    \"\"\"\n    print \"NEWTON METHOD: start\"\n    # gradient\n    g = [diff(obj, i) for i in m]\n    # Hessian matrix\n    H = Matrix([[diff(g[j], m[i]) for i in range(len(m))] for j in range(len(g))])\n    H_inv = H.inv()\n\n    xn = [[0, 0]]  # Newton method result global for comparison\n    xn[0] = x_start\n\n    iter_n = 0\n    while np.linalg.norm(xn[-1] - x_result) > target_precision:\n        # print \"NEWTON METHOD: distance:\", np.linalg.norm(xn[-1] - x_result)\n        gn = Matrix(dfdx(xn[iter_n], g))\n        delta_xn = -H_inv * gn\n        delta_xn = delta_xn.subs(m[0], xn[iter_n][0]).subs(m[1], xn[iter_n][1])\n        xn.append(Matrix(xn[iter_n]) + delta_xn)\n        iter_n += 1\n    print \"NEWTON METHOD: result distance:\", np.linalg.norm(xn[-1] - x_result)\n\n    xn = np.array(xn)\n    plt.plot(xn[:, 0], xn[:, 1], 'k-o')\n\n\nif __name__ == '__main__':\n    \n    ####################\n    # Quadratic function\n    ####################\n    # Start location\n    x_start = [-4.0, 6.0]\n\n    # obj = spp.parse_expr('x1**2 - x2 * x1 - x1 + 4 * x2**2')\n    # x_result = np.array([16/15, 2/15])\n    obj = spp.parse_expr('x1**2 - 2 * x1 * x2 + 4 * x2**2')\n    x_result = np.array([0, 0])\n\n    # Design variables at mesh points\n    i1 = np.arange(plot_from, plot_to, plot_step)\n    i2 = np.arange(plot_from, plot_to, plot_step)\n    x1_mesh, x2_mesh = np.meshgrid(i1, i2)\n    f_str = obj.__str__().replace('x1', 'x1_mesh').replace('x2', 'x2_mesh')\n    f_mesh = eval(f_str)\n\n    # Create a contour plot\n    plt.figure()\n\n    plt.imshow(f_mesh, cmap='Paired', origin='lower',\n               extent=[plot_from - 20, plot_to + 20, plot_from - 20, plot_to + 20])\n    plt.colorbar()\n\n    # Add some text to the plot\n    plt.title('f(x) = ' + str(obj))\n    plt.xlabel('x1')\n    plt.ylabel('x2')\n    nm()\n    sd(alpha=0.05)\n    plt.show()\n\n    #####################\n    # Rosenbrock function\n    #####################\n    # Start location\n    x_start = [-4.0, -5.0]\n\n    obj = spp.parse_expr('(1 - x1)**2 + 100 * (x2 - x1**2)**2')\n    x_result = np.array([1, 1])\n\n    # Design variables at mesh points\n    i1 = np.arange(plot_from, plot_to, plot_step)\n    i2 = np.arange(plot_from, plot_to, plot_step)\n    x1_mesh, x2_mesh = np.meshgrid(i1, i2)\n    f_str = obj.__str__().replace('x1', 'x1_mesh').replace('x2', 'x2_mesh')\n    f_mesh = eval(f_str)\n\n    # Create a contour plot\n    plt.figure()\n\n    plt.imshow(f_mesh, cmap='Paired', origin='lower',\n               extent=[plot_from - 20, plot_to + 20, plot_from - 20, plot_to + 20])\n    plt.colorbar()\n\n    # Add some text to the plot\n    plt.title('f(x) = ' + str(obj))\n    plt.xlabel('x1')\n    plt.ylabel('x2')\n    nm()\n    sd(alpha=0.0002)\n    plt.show()\n\n    # import timeit\n    # print(timeit.timeit(\"nm()\", setup=\"from __main__ import nm\", number=10))\n    # print(timeit.timeit(\"sd()\", setup=\"from __main__ import sd\", number=10))\n", "meta": {"hexsha": "708ed24373f788146e32ff5268ead953f8932c0b", "size": 4370, "ext": "py", "lang": "Python", "max_stars_repo_path": "Second_order_optimization_Newtons_Method/Second_Order_Optimization_Newtons_Method-master/newtons_method_optimization.py", "max_stars_repo_name": "DillipKS/The-Math-of-Intelligence-course", "max_stars_repo_head_hexsha": "fc0f33e638fdbd05e93d54d38ed8493808f6ec74", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Second_order_optimization_Newtons_Method/Second_Order_Optimization_Newtons_Method-master/newtons_method_optimization.py", "max_issues_repo_name": "DillipKS/The-Math-of-Intelligence-course", "max_issues_repo_head_hexsha": "fc0f33e638fdbd05e93d54d38ed8493808f6ec74", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Second_order_optimization_Newtons_Method/Second_Order_Optimization_Newtons_Method-master/newtons_method_optimization.py", "max_forks_repo_name": "DillipKS/The-Math-of-Intelligence-course", "max_forks_repo_head_hexsha": "fc0f33e638fdbd05e93d54d38ed8493808f6ec74", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-08T07:58:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-08T07:58:13.000Z", "avg_line_length": 28.940397351, "max_line_length": 115, "alphanum_fraction": 0.580778032, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 1384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992914310605, "lm_q2_score": 0.9005297881200701, "lm_q1q2_score": 0.8716221438339788}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 16 12:56:17 2021\r\n\r\n@author: Luigi\r\n\"\"\"\r\nimport numpy as np\r\nimport scipy as sci\r\nimport sympy as sym\r\nimport matplotlib.pyplot as plt\r\n\r\ndef Lagrange(xnodi, i):\r\n    if i == 0:\r\n        xzeri = xnodi[1:]\r\n    else:\r\n        xzeri = np.append(xnodi[:i], xnodi[i + 1 :])\r\n    num = np.poly(xzeri)\r\n    den = np.polyval(num, xnodi[i])\r\n    return num / den\r\n        \r\ndef Interpol(x, y, xx):\r\n    m = x.size\r\n    n = xx.size\r\n    L = np.zeros((m,n))\r\n    for k in range(m):\r\n        L[k, :] = np.polyval(Lagrange(x, k), xx)\r\n    return np.dot(y, L)\r\n\r\ndef simpsonComp(f, a, b, n):\r\n    h = (b - a) / (2 * n)\r\n    interv = np.arange(a, b + h, h)\r\n    fnodi = f(interv)\r\n    I = h * (fnodi[0] + 2 * np.sum(fnodi[2 : 2*n : 2]) + 4 * np.sum(fnodi[1 : 2*n : 2]) + fnodi[2*n]) /3\r\n    return I\r\n\r\ndef simpsonTol(f, a, b, tol):\r\n    N = 1\r\n    nMax = 2048\r\n    err = 1\r\n    In = simpsonComp(f, a, b, N)\r\n    while err >= tol and N < nMax:\r\n        N *= 2\r\n        I2n = simpsonComp(f, a, b, N)\r\n        err = np.abs(I2n - In) / 15\r\n        In = I2n\r\n    return In, N\r\n\r\nf = lambda x : x - np.sqrt(x - 1)\r\na = 1\r\nb = 3\r\nx = np.linspace(a, b, 4)\r\nxx = np.linspace(a, b, 100)\r\ny = f(x)\r\nyy = Interpol(x, y, xx)\r\n\r\nplt.plot(xx, yy, xx, f(xx), x, y, \"o\")\r\nplt.legend([\"Polinomio di grado 3\", \"Funzione\", \"Nodi di interpolazione\"])\r\nplt.show()\r\n\r\nn = 4\r\np = lambda nodi : Interpol(x, y, nodi)\r\nI1, N1 = simpsonTol(f, a, b, 10**-5)\r\nprint(f\"Sono necessare {N1} iterazioni per I1\")\r\nI2, N2 = simpsonTol(p, a, b, 10**-5)\r\nprint(f\"Sono necessare {N2} iterazioni per I2\")\r\nI1es = 2.114381916835873\r\nI2es = 2.168048769926493\r\nerr1 = abs(I1es - I1)\r\nerr2 = abs(I2es - I2)\r\nprint(\"ErrRel I1 = \", err1)\r\nprint(\"ErrRel I2 = \", err2)\r\n", "meta": {"hexsha": "52c99c2b8e82adac4e3b280bca00d0a2a393c4e7", "size": 1758, "ext": "py", "lang": "Python", "max_stars_repo_path": "simulazioni/25-Giugno-2020-02A.py", "max_stars_repo_name": "luigi-borriello00/Metodi_SIUMerici", "max_stars_repo_head_hexsha": "cf1407c0ad432a49a96dcd08303213e48723c57a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-06-23T14:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T08:39:27.000Z", "max_issues_repo_path": "simulazioni/25-Giugno-2020-02A.py", "max_issues_repo_name": "luigi-borriello00/Metodi_SIUMerici", "max_issues_repo_head_hexsha": "cf1407c0ad432a49a96dcd08303213e48723c57a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulazioni/25-Giugno-2020-02A.py", "max_forks_repo_name": "luigi-borriello00/Metodi_SIUMerici", "max_forks_repo_head_hexsha": "cf1407c0ad432a49a96dcd08303213e48723c57a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4166666667, "max_line_length": 105, "alphanum_fraction": 0.5284414107, "include": true, "reason": "import numpy,import scipy,import sympy", "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122732859021, "lm_q2_score": 0.9099070115349838, "lm_q1q2_score": 0.8716110938982579}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport sympy as sp\n\n\n\ndef func(exp):\n\t\"\"\"\n\tFunction to convert the expression to the Pythonic format to make mathematical calculations.\n\n\tParameters:\n\texp:\tinputted expression by the user to be lambdified\n\t\"\"\"\n\n\tx = sp.symbols('x')\n\treturn sp.utilities.lambdify(x, exp, \"math\")\n\n\n\ndef bisection(exp, a, b, tol, points, count):\n\t\"\"\"\n\tFunction to calculate the root of the expression through the bisection method.\n\n\tParameters:\n\texp:\tinputted expression by the user whose root needs to be found\n\ta:\t\tlower limit of the range\n\tb:\t\tupper limit of the range\n\ttol:\tmaximum permissible error between the calculated root and the true solution\n\tpoints:\ta list to save the roots calculated through the iterations\n\tcount:\tit ensures that checking for the permissible error of the root cannot be done in the first iteration which has only one root\n\t\"\"\"\n\n\tfunction = func(exp)\n\n\n\t# Checking to ensure the range given by the user is correct and a root to the expression lies between the range\n\tif function(a) * function(b) > 0:\n\n\t\tprint(f\"Invalid range of {a} and {b}. Ensure range is between a root by checking if both signs are different.\")\n\t\treturn  \n\n\tc = (a + b) / 2\n\tpoints.append(c)\n\n\tif count > 1:\n\n\t\tif abs(points[-1] - points[-2]) < tol:\n\n\t\t\treturn points \n\n\tif function(a) * function(c) < 0:\n\n\t\tcount += 1\n\t\treturn bisection(exp, a, c, tol, points, count)\n\n\telif function(b) * function(c) < 0:\n\n\t\tcount += 1\n\t\treturn bisection(exp, b, c, tol, points, count)\n\n\n\ndef plot_func(exp, array, a, b):\n\t\"\"\"\n\tA function to plot the expression and all the calculated roots, while highlighting the final correct root\n\n\tParameters:\n\texp:\tinputted expression by the user which needs to be plotted\n\ta:\t\tlower limit of the range\n\tb:\t\tupper limit of the range\n\tarray:\tarray of roots to be plotted\n\t\"\"\"\n\n\tfunction = func(exp)\n\n\t# Plotting the function by creating an array of Xs and Ys\n\tx = np.linspace(a, b, 20)\n\ty = []\n\n\tfor i in x:\n\t\ty.append(function(i))\n\n\t# An array of zeros the same length as the number of roots in arrays, so as to plot the roots\n\tarray_y = np.zeros(len(array))\n\n\tfig = plt.figure(figsize=(8,7))\n\n\tax1 = fig.add_axes([0.05, 0.05, 0.9, 0.9])\n\n\tax1.plot(x, y, label=\"Function: %s\"% exp)\n\tax1.axhline(0, color='red', ls='--', alpha=0.5)\n\tax1.scatter(array[:-1], array_y[:-1], color='black', s=10, alpha=0.8, edgecolor='black', label=\"Roots\")\n\tax1.scatter(array[-1], 0, color=\"green\", s=15, label=\"Final Root: %s\"% str(round(array[-1], 3)))\n\n\tax1.set_title(\"Finding Roots: Bisection Method\")\n\tax1.legend()\n\n\tplt.show()\n\nroots = []\ncount = 1\n\nexpr = input(\"Enter a continuous function in x: \")\na, b = map(int, input(\"Enter the range with a space in between the two numbers: \").split())\nerror = float(input(\"Enter the max allowable tolerance: \"))\n\n# Example input values:\n\n# expr = \"x^3 - x - 2\"\n# a, b = 1, 2\n# error = 0.001\n\nfinal = bisection(expr, a, b, error, roots, count)\n\nplot_func(expr, final, a, b)\n\nprint(\"The root by bisection method: \", round(final[-1], 3))\n\n\n", "meta": {"hexsha": "b4575d1cb3b6bb7e777cd567c0ffeb67c6347786", "size": 3022, "ext": "py", "lang": "Python", "max_stars_repo_path": "Day 1 - Bisection/bisection.py", "max_stars_repo_name": "drkndl/Numerical-Methods-Challenge", "max_stars_repo_head_hexsha": "7e61f28c2d98b33f1952f2785a6728fa53f01f05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Day 1 - Bisection/bisection.py", "max_issues_repo_name": "drkndl/Numerical-Methods-Challenge", "max_issues_repo_head_hexsha": "7e61f28c2d98b33f1952f2785a6728fa53f01f05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 1 - Bisection/bisection.py", "max_forks_repo_name": "drkndl/Numerical-Methods-Challenge", "max_forks_repo_head_hexsha": "7e61f28c2d98b33f1952f2785a6728fa53f01f05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1833333333, "max_line_length": 132, "alphanum_fraction": 0.6872931833, "include": true, "reason": "import numpy,import sympy", "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957912273285902, "lm_q2_score": 0.9099070029841949, "lm_q1q2_score": 0.8716110857073521}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport texttable as tt\ntab = tt.Texttable()\ndef euler(f,a,b,n,yinit):\n    h=(b-a)/(n)\n    xs = a+np.arange(n)*h\n    ys=np.zeros(n)\n    y = yinit\n    for j,x in enumerate(xs):\n        ys[j]=y\n        y+=h*f(x,y)\n    return xs, ys\ndef rk2(f,a,b,n,yinit):\n    h=(b-a)/(n)\n    xs = a+np.arange(n)*h\n    ys=np.zeros(n)\n    y = yinit\n    for j,x in enumerate(xs):\n        ys[j]=y\n        k0 = h*f(x,y)\n        y+=h*f(x+h/2,y+k0/2)\n    return xs, ys\ndef rk4(f,a,b,n,yinit):\n    h=(b-a)/(n)\n    xs = a+np.arange(n)*h\n    ys=np.zeros(n)\n    y = yinit\n    for j,x in enumerate(xs):\n        ys[j]=y\n        k0 = h*f(x,y)\n        k1 = h*f(x+h/2,y+k0/2)\n        k2 = h*f(x+h/2,y+k1/2)\n        k3 = h*f(x+h,y+k2)\n        y+=(k0+2*k1+2*k2+k3)/6\n    return xs, ys\ndef Analytic(yinit,a,b,h,tau):\n    xs,ys=[],[]\n    p=np.arange(a,b,h)\n    for t in p:        \n        D=yinit*np.exp(-1*t/tau)\n        ys.append(D)\n        xs.append(t)        \n    return xs,ys\ndef graph(xs_1,ys_1,xs_2,ys_2,xs_3,ys_3,xs_4,ys_4,xs_5,ys_5,xs_6,ys_6,xs_7,ys_7,xs_8,ys_8,xs_9,ys_9,xs_10,ys_10,title):\n    fig,axs=plt.subplots(3,2,figsize=(15,15))\n    fig.suptitle(title, fontsize=30)\n    ax11,ax12,ax21,ax22,ax31,ax32=axs[0][0],axs[0][1],axs[1][0],axs[1][1],axs[2][0],axs[2][1]\n    ax11.plot(xs_1,ys_1,'^', color='green',label=\"euler\"),ax11.plot(xs_4,ys_4,'-', color='black',label=\"rk2\")\n    ax11.plot(xs_7,ys_7,'>',color='black',label=\"rk4\"),ax11.plot(xs_7,ys_7,'*',color='brown',label=\"Analytic\")\n    ax11.set_title(\"Analytic v/s Euler v/s rk2 v/s rk4\"),ax11.set_ylabel(\"N\"),ax11.set_xlabel(\"Time\")      \n    ax12.plot(xs_1,ys_1,'^', color='green',label=\"h ={}\".format(xs_1[1]-xs_1[0])),ax12.plot(xs_2,ys_2,'-', color='black',label=\"h ={}\".format(xs_2[1]-xs_2[0]))\n    ax12.plot(xs_3,ys_3,'>',color='black',label=\"h ={}\".format(xs_3[1]-xs_3[0])),ax12.plot(xs_7,ys_7,'*',color='brown',label=\"Analytic\")\n    ax12.set_title(\"Euler for different stepsize(h)\"),ax12.set_ylabel(\"N\"),ax12.set_xlabel(\"Time\")         \n    ax21.plot(xs_4,ys_4,'^', color='green',label=\"h ={}\".format(xs_4[1]-xs_4[0])),ax21.plot(xs_5,ys_5,'-', color='black',label=\"h ={}\".format(xs_5[1]-xs_5[0]))\n    ax21.plot(xs_6,ys_6,'>',color='black',label=\"h ={}\".format(xs_6[1]-xs_6[0])),ax21.plot(xs_7,ys_7,'*',color='brown',label=\"Analytic\")\n    ax21.set_title(\"rk2 for different stepsize(h)\"),ax21.set_ylabel(\"N\"),ax21.set_xlabel(\"Time\")                             \n    ax22.plot(xs_7,ys_7,'^', color='green',label=\"h ={}\".format(xs_7[1]-xs_7[0])),ax22.plot(xs_8,ys_8,'-', color='black',label=\"h ={}\".format(xs_8[1]-xs_8[0]))\n    ax22.plot(xs_9,ys_9,'>',color='black',label=\"h ={}\".format(xs_9[1]-xs_9[0])),ax22.plot(xs_10,ys_10,'*',color='brown',label=\"Analytic\")\n    ax22.set_title(\"rk4 for different stepsize(h)\"),ax22.set_ylabel(\"N\"),ax22.set_xlabel(\"Time\")           \n    ax31.plot(xs_1,(ys_10-ys_1)/ys_10,'.', color='green',label=\"euler\"),ax31.plot(xs_1,(ys_10-ys_4)/ys_10,'.', color='black',label=\"rk2\")\n    ax31.plot(xs_1,(ys_10-ys_7)/ys_10,'.', color='red',label=\"rk4\")\n    ax31.set_title(\"Error Plot at h = 0.4\"),ax31.set_ylabel(\"Absolute Error\"),ax31.set_xlabel(\"Time\")               \n    ax32.plot(xs_1,(ys_1-ys_4)/ys_1,'.', color='green',label=\"euler-rk2\"),ax32.plot(xs_1,(ys_7-ys_4)/ys_7,'.', color='black',label=\"rk4-rk2\")\n    ax32.plot(xs_1,(ys_1-ys_7)/ys_1,'.', color='red',label=\"euler-rk4\")\n    ax32.set_title(\"Comparative Error Plot at h = 0.4\"),ax32.set_ylabel(\"Absolute Error\"),ax32.set_xlabel(\"Time\")                 \n    ax11.legend(),ax11.grid(True),ax12.legend(),ax12.grid(True),ax21.legend(),ax21.grid(True),ax22.legend(),ax22.grid(True)\n    ax31.legend(),ax31.grid(True),ax32.legend(),ax32.grid(True)\n    plt.show()\ndef q3_a(a,yinit,t_half):\n    b = 5*t_half \n    tau=t_half/np.log(2)\n    h = t_half/10\n    n = int((b-a)/h)\n    decay = lambda x, y: -1*y/tau\n    xs_1, ys_1 = euler(decay,a,b,n,yinit)\n    xs_2, ys_2 = euler(decay,a,b,2*n,yinit)\n    xs_3, ys_3 = euler(decay,a,b,4*n,yinit)    \n    xs_4, ys_4 = rk2(decay,a,b,n,yinit)\n    xs_5, ys_5 = rk2(decay,a,b,2*n,yinit)\n    xs_6, ys_6 = rk2(decay,a,b,4*n,yinit)\n    xs_7, ys_7 = rk4(decay,a,b,n,yinit)\n    xs_8, ys_8 = rk4(decay,a,b,2*n,yinit)\n    xs_9, ys_9 = rk4(decay,a,b,4*n,yinit)\n    xs_10, ys_10 = Analytic(yinit,a,b,h,tau)\n    print(\"Radioactive Decay\", \"h =\", h)\n    headings_1 = [\"t\" ,\"Analytic\",\"euler\",\"rk2\",\"rk4\",\"Ab_error euler\",\"Ab_error rk2\",\"Ab_error rk4\"]\n    tab.header(headings_1)\n    for row in zip(xs_1,ys_10,ys_1,ys_4,ys_7,(ys_10-ys_1)/ys_10,(ys_10-ys_4)/ys_10,(ys_10-ys_7)/ys_10):\n        tab.add_row(row)\n        tab.set_max_width(0)\n        tab.set_precision(6)\n    s = tab.draw()\n    print(s)\n    tab.reset()\n   \n    graph(xs_1,ys_1,xs_2,ys_2,xs_3,ys_3,xs_4,ys_4,xs_5,ys_5,xs_6,ys_6,xs_7,ys_7,xs_8,ys_8,xs_9,ys_9,xs_10,ys_10,\"Radioactive Decay\")\n\n\n\ndef q3_b(a,yinit,R,C):\n    b = 5*R*C \n    tau=R*C\n    h = tau/10\n    n = int((b-a)/h)\n    rc = lambda x, y: -1*y/tau    \n    xs_1, ys_1 = euler(rc,a,b,n,yinit)\n    xs_2, ys_2 = euler(rc,a,b,2*n,yinit)\n    xs_3, ys_3 = euler(rc,a,b,4*n,yinit)\n    \n    xs_4, ys_4 = rk2(rc,a,b,n,yinit)\n    xs_5, ys_5 = rk2(rc,a,b,2*n,yinit)\n    xs_6, ys_6 = rk2(rc,a,b,4*n,yinit)\n    \n    xs_7, ys_7 = rk4(rc,a,b,n,yinit)\n    xs_8, ys_8 = rk4(rc,a,b,2*n,yinit)\n    xs_9, ys_9 = rk4(rc,a,b,4*n,yinit)\n    xs_10, ys_10 = Analytic(yinit,a,b,h,tau)\n    print(\"RC Circuit\", \"h =\", h)\n    headings_1 = [\"t\" ,\"Analytic\",\"euler\",\"rk2\",\"rk4\",\"$\\delta$\",\"Ab_error rk2\",\"Ab_error rk4\"]\n    tab.header(headings_1)\n    for row in zip(xs_1,ys_10,ys_1,ys_4,ys_7,(ys_10-ys_1)/ys_10,(ys_10-ys_4)/ys_10,(ys_10-ys_7)/ys_10):\n        tab.add_row(row)\n        tab.set_max_width(0)\n        tab.set_precision(6)\n    s = tab.draw()\n    print(s)\n    tab.reset()\n   \n    graph(xs_1,ys_1,xs_2,ys_2,xs_3,ys_3,xs_4,ys_4,xs_5,ys_5,xs_6,ys_6,xs_7,ys_7,xs_8,ys_8,xs_9,ys_9,xs_10,ys_10,\"RC Circuit\")\n\ndef q3_c(a,yinit,eta,rad,m):\n    tau=m/((np.pi)*6*rad*eta)\n    b = 5*tau\n    h = tau/10\n    n = int((b-a)/h)\n    stokes = lambda x, y: -1*y/tau\n    xs_1, ys_1 = euler(stokes,a,b,n,yinit)\n    xs_2, ys_2 = euler(stokes,a,b,2*n,yinit)\n    xs_3, ys_3 = euler(stokes,a,b,4*n,yinit)    \n    xs_4, ys_4 = rk2(stokes,a,b,n,yinit)\n    xs_5, ys_5 = rk2(stokes,a,b,2*n,yinit)\n    xs_6, ys_6 = rk2(stokes,a,b,4*n,yinit)    \n    xs_7, ys_7 = rk4(stokes,a,b,n,yinit)\n    xs_8, ys_8 = rk4(stokes,a,b,2*n,yinit)\n    xs_9, ys_9 = rk4(stokes,a,b,4*n,yinit)\n    xs_10, ys_10 = Analytic(yinit,a,b,h,tau)   \n    xs_10.pop(int(xs_10[-1]))\n    ys_10.pop(int(ys_10[-1]))\n    print(\"Stokes Law\", \"h =\", h)\n    headings_1 = [\"t\" ,\"Analytic\",\"euler\",\"rk2\",\"rk4\",\"Ab_error euler\",\"Ab_error rk2\",\"Ab_error rk4\"]\n    tab.header(headings_1)\n    for row in zip(xs_1,ys_10,ys_1,ys_4,ys_7,(ys_10-ys_1)/ys_10,(ys_10-ys_4)/ys_10,(ys_10-ys_7)/ys_10):\n        tab.add_row(row)\n        tab.set_max_width(0)\n        tab.set_precision(6)\n    s = tab.draw()\n    print(s)\n    tab.reset()    \n    graph(xs_1,ys_1,xs_2,ys_2,xs_3,ys_3,xs_4,ys_4,xs_5,ys_5,xs_6,ys_6,xs_7,ys_7,xs_8,ys_8,xs_9,ys_9,xs_10,ys_10,\"Stokes Law\")\nif __name__ == \"__main__\":\n    q3_a(0,20000,4)\n    q3_b(0,10,1e3,1e-6)\n    q3_c(0,10,10,0.2,200)\n   \n", "meta": {"hexsha": "0f8fc38bad570d0eae67777bafc9cc18d469f7f5", "size": 7218, "ext": "py", "lang": "Python", "max_stars_repo_path": "ppt/MP Lab Practicals/Euler/euler.py", "max_stars_repo_name": "hinton024/Mathematical-Physics", "max_stars_repo_head_hexsha": "fabe34d0fb1492ad177c9e7be99e1dbe718fda69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ppt/MP Lab Practicals/Euler/euler.py", "max_issues_repo_name": "hinton024/Mathematical-Physics", "max_issues_repo_head_hexsha": "fabe34d0fb1492ad177c9e7be99e1dbe718fda69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ppt/MP Lab Practicals/Euler/euler.py", "max_forks_repo_name": "hinton024/Mathematical-Physics", "max_forks_repo_head_hexsha": "fabe34d0fb1492ad177c9e7be99e1dbe718fda69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2215568862, "max_line_length": 159, "alphanum_fraction": 0.5996120809, "include": true, "reason": "import numpy", "num_tokens": 3028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426435557124, "lm_q2_score": 0.8947894639983208, "lm_q1q2_score": 0.8715630949387233}}
{"text": "import scipy as sp\nimport numpy as np\n#From https://www.stat.auckland.ac.nz/~fewster/325/notes/ch9.pdf\n#Python soln = https://stackoverflow.com/questions/33385763/find-markov-steady-state-with-left-eigenvalues-using-numpy-or-scipy\n#Starting values for t=0; any state equally likely.\nstart = np.array([[1/4,1/4,1/4,1/4]])\nprint(start)\n#Specify the matrix, P\nP = np.array([[0,.9,.1,0],[.8,.1,0,.1],[0,.5,.3,.2],[.1,0,0,.9]])\n#We want to find the left matrix pi which produces pi.P = pi.\n#By definition, this is the stationary matrix.\n#Calculate the left eigenvector, which is the solution to the problem pi(P - I) = 0.\neigenvalue, eigenvector = sp.sparse.linalg.eigs(P.T, k=1,which ='LM')\nprint(eigenvalue)\nprint('Un-normalised eigenvector: ',eigenvector)\nevect_norm = (eigenvector/eigenvector.sum()).real\nprint('Normalised eigenvector: ',evect_norm)\nprint('Check that pi*P = pi: ',np.dot(evect_norm.T,P).T.real)\nprint('Estimate using P^n: ',np.linalg.matrix_power(P,100)[0,:])\n", "meta": {"hexsha": "8d80633e486e696d0df0bc541048c34c79c4a667", "size": 976, "ext": "py", "lang": "Python", "max_stars_repo_path": "Strogatz/Markov_stationary_matrix.py", "max_stars_repo_name": "yuchiaol/Non-linear-dynamics-Strogatz", "max_stars_repo_head_hexsha": "79e1171d4a88193d3da67c15f41212a96e6854dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 64, "max_stars_repo_stars_event_min_datetime": "2017-11-21T12:47:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:23:29.000Z", "max_issues_repo_path": "Strogatz/Markov_stationary_matrix.py", "max_issues_repo_name": "Llewelyn62/Non-linear-dynamics-Strogatz", "max_issues_repo_head_hexsha": "79e1171d4a88193d3da67c15f41212a96e6854dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Strogatz/Markov_stationary_matrix.py", "max_forks_repo_name": "Llewelyn62/Non-linear-dynamics-Strogatz", "max_forks_repo_head_hexsha": "79e1171d4a88193d3da67c15f41212a96e6854dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2017-11-21T20:11:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T00:00:30.000Z", "avg_line_length": 48.8, "max_line_length": 127, "alphanum_fraction": 0.7213114754, "include": true, "reason": "import numpy,import scipy", "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426397881662, "lm_q2_score": 0.894789461192692, "lm_q1q2_score": 0.8715630888347606}}
{"text": "\"\"\"\nProblem\n=======\nGiven a sorted array, return the index of the given key. Return -1 if\nthe given key is not found in the given array.\n\n\"\"\"\n\nimport numpy as np\n\n\n# Time: O(log n)\n# Space: O(1)\ndef binary_search(a, key):\n    lo, hi = 0, len(a)\n    while lo < hi:\n        mi = (lo + hi) // 2\n        if a[mi] < key:\n            lo = mi + 1\n        elif a[mi] > key:\n            hi = mi\n        else:\n            return mi\n    return -1\n\n\n# Implementation from Standard library:\n# bisect.bisect_left(a, x, lo=0, hi=len(a))\n# bisect.bisect_right(a, x, lo=0, hi=len(a))\n# bisect.bisect(a, x, lo=0, hi=len(a)) # same as bisect_right\n\n## Testing ##\n\ndef generate_random_sorted_array(maxlen=10, maxent=20):\n    n = np.random.randint(0, maxlen + 1)\n    arr = np.random.randint(1, maxent, n)\n    return np.sort(arr)\n\n\ndef random_tests(seed=None, maxlen=10, maxent=20):\n    np.random.seed(seed)\n    n = 0\n    try:\n        while True:\n            flag = False\n            arr = generate_random_sorted_array(maxlen, maxent)\n            for key in range(0, maxent + 1):\n                n += 1\n                i = binary_search(arr, key)\n                if ((-1 < i < len(arr) and arr[i] != key) or (i == -1 and key in arr)):\n                    print(f'Test #{n}')\n                    print('arr: ', arr)\n                    print('key: ', key)\n                    print('i: ', i)\n                    flag = True\n                    break\n            if flag:\n                break\n    except KeyboardInterrupt:\n        print(f'\\nPassed {n} tests.')\n\n\nif __name__ == '__main__':\n    print('Performing random tests...')\n    print('Press ^C to stop.')\n    random_tests(seed=42, maxlen=100, maxent=200)\n\n", "meta": {"hexsha": "765e4f487b6cba06c7d8901350d409e804a0707a", "size": 1689, "ext": "py", "lang": "Python", "max_stars_repo_path": "practice/coderust/t0_arrays/p00_binary_search.py", "max_stars_repo_name": "deehzee/dsalgo", "max_stars_repo_head_hexsha": "025bf292e5a2c4e079cecb0c284ab6aeae9a07f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "practice/coderust/t0_arrays/p00_binary_search.py", "max_issues_repo_name": "deehzee/dsalgo", "max_issues_repo_head_hexsha": "025bf292e5a2c4e079cecb0c284ab6aeae9a07f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practice/coderust/t0_arrays/p00_binary_search.py", "max_forks_repo_name": "deehzee/dsalgo", "max_forks_repo_head_hexsha": "025bf292e5a2c4e079cecb0c284ab6aeae9a07f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-06T16:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-06T16:50:07.000Z", "avg_line_length": 24.8382352941, "max_line_length": 87, "alphanum_fraction": 0.5150976909, "include": true, "reason": "import numpy", "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.918480252950991, "lm_q1q2_score": 0.8715617651355447}}
{"text": "#Author: marejak023\r\n#Contact: marejak023@gmail.com, marejak023.wz.cz\r\n#Date: 06/02/2021\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport math\r\n\r\n#code for computing Leibniz series\r\nk = 1 # denominator\r\ns = 0 # sum\r\n\r\n# x and y array for storing plot values\r\ny = np.array([])\r\nx = np.array([])\r\nPI_CONST_LINE = np.array([]) # pi contstant for y reference value (set for 15f points from math package)\r\n\r\nsum_range = int(input(\"\\nEnter a range: \")) # range for the series\r\n\r\nfor i in range(sum_range):\r\n    # even numbers have + sign\r\n    if i % 2 == 0:\r\n        s += 4/k\r\n    else: # changes + to - sign\r\n        s -= 4/k\r\n    k += 2\r\n    y = np.append(y, s) # adds current value of sum of the series to the y array\r\n    PI_CONST_LINE = np.append(PI_CONST_LINE, math.pi) # append math.pi values to PI_CONST_LINE array, so pi y reference value is for every n (sum_range) = math.pi\r\n\r\n# stores value in x array (sum_range = n [number of steps])\r\nfor i in range(sum_range):\r\n    x = np.append(x, i)\r\n\r\nerror = ((s-math.pi)/math.pi)*100 # Percentage value of error\r\n\r\n# printing out computed values\r\nprint(\"\\nApproximate value of pi using Liebniz series is: \", \"{:.15f}\".format(s))\r\nprint(\"Real value using math python constant math.pi is: \", math.pi)\r\nprint(\"Value of error in % is: \", abs(error), \"%\")\r\nprint(\"\\nApproximate value is limited to 15 float digits, so it matches the internal float value of math.pi\")\r\n\r\n# making plot\r\n# titles & labels\r\nplt.figure().canvas.set_window_title(\"Pi approximation using Leibniz series\")\r\nplt.title(r\"$\\pi$ approximation using Leibniz series $\\frac{\\pi}{4}=\\sum_{n=0}^{\\infty}\\frac{(-1)^n}{2n+1}$\", y = 1.05) # y is for title positioning on y axis\r\nplt.xlabel(r\"n\", fontsize = 20) # r is for using mathmode ($$ for entering mathmode, same as LaTeX notation)\r\nplt.ylabel(r\"$S_n$\", fontsize = 20)\r\n\r\nplt.plot(x, y, marker = 'X', mec = \"#0085E7\", mfc = \"#FFF\", c = \"#0085E7\", ls = '--') # plots Leibniz series, mec = marker edge color, mfc = marker face color c = linecolor, ls = linestyle\r\nplt.plot(x, PI_CONST_LINE, ls = '-.', c = \"#000\") # plots constant line with y value = pi (from math.pi, 15f points) & x value = n (sum_range)\r\nplt.grid(linestyle = '--')\r\nplt.show() # display plot", "meta": {"hexsha": "e9f0ba71abb8044ab204c72a054b24306052ffd5", "size": 2236, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "marejak023/leibniz-series", "max_stars_repo_head_hexsha": "9fd5ec20a8c2b60fe8aad95816ca3eefd778809f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.py", "max_issues_repo_name": "marejak023/leibniz-series", "max_issues_repo_head_hexsha": "9fd5ec20a8c2b60fe8aad95816ca3eefd778809f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "marejak023/leibniz-series", "max_forks_repo_head_hexsha": "9fd5ec20a8c2b60fe8aad95816ca3eefd778809f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.0, "max_line_length": 189, "alphanum_fraction": 0.6596601073, "include": true, "reason": "import numpy", "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.9184802468145655, "lm_q1q2_score": 0.871561764619992}}
{"text": "import numpy as np\n\ndef linear_solve(A, b):\n  AAT = A@(A.T)\n  # w = np.linalg.solve(AAT, b)\n  w = np.linalg.lstsq(AAT, b)[0]\n  x = (A.T)@w\n  return x\n\n\nclass PolyModel:\n  '''\n  H(n) : h(x): R-> R, h(x)= a_0 + a_1*x + a_2*x^2 + ... + a_{n-1}*x^n-1 \n  '''\n\n  def __init__(self, n):\n      self.n = n\n      self.a = None\n  \n  def generate_features(self, X):\n      X = X.flatten()\n      arrays = [X**i for i in range(self.n)]\n      A = np.stack(arrays, axis = 1)\n      return A\n\n  def fit(self, X, Y, refit=False):\n      '''\n      X: (d,1)\n      Y: (d,1)\n      '''\n      if self.a and (not refit):\n         raise ValueError(\"Re-Fitting\")\n      A = self.generate_features(X)\n      # self.a = linear_solve(A, Y)\n      self.a = np.linalg.lstsq(A, Y)[0]\n      return self\n\n  def predict(self, X, A=None):\n      if (not A):\n        A = self.generate_features(X)\n      return A@self.a\n  \n  def score(self, X, y):\n      '''\n        RMSE\n      '''\n      y_pred = self.predict(X=X)\n      return np.linalg.norm(y-y_pred, ord=2)/np.sqrt(X.shape[0])\n\n", "meta": {"hexsha": "429a28f1685e765b0b7eac6de4265ff6cd3e8f9d", "size": 1034, "ext": "py", "lang": "Python", "max_stars_repo_path": "PolyModel.py", "max_stars_repo_name": "layjain/Deep-Multiple-Descent", "max_stars_repo_head_hexsha": "f26afc198ee3c261736b8d80cd6511804666ee10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PolyModel.py", "max_issues_repo_name": "layjain/Deep-Multiple-Descent", "max_issues_repo_head_hexsha": "f26afc198ee3c261736b8d80cd6511804666ee10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PolyModel.py", "max_forks_repo_name": "layjain/Deep-Multiple-Descent", "max_forks_repo_head_hexsha": "f26afc198ee3c261736b8d80cd6511804666ee10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.68, "max_line_length": 72, "alphanum_fraction": 0.5077369439, "include": true, "reason": "import numpy", "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203815, "lm_q2_score": 0.9032942073547149, "lm_q1q2_score": 0.8715480730082226}}
{"text": "## 1. Vectors ##\n\nvector1 = np.asarray([4, 5, 7, 10])\nvector2 = np.asarray([8, 6, 3, 2])\nvector3 = np.asarray([10, 4, 6, -1])\nvector1_2 = vector1 + vector2\nvector3_1 = vector3 + vector1\n\n## 2. Vectors and scalars ##\n\nvector = np.asarray([4, -1, 7])\nvector_7 = vector * 7\nvector_8 = vector / 8\n\n## 4. Plotting vectors ##\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# We're going to plot 2 vectors\n# The first will start at origin 0,0 , then go over 1 and up 2.\n# The second will start at origin 1,2 then go over 3 and up 2.\nX = [0,1]\nY = [0,2]\nU = [1,3]\nV = [2,2]\n# Actually make the plot.\nplt.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1)\n# Set the x axis limits\nplt.xlim([0,6])\n# Set the y axis limits\nplt.ylim([0,6])\n# Show the plot.\nplt.show()\nplt.quiver([0,1,0], [0,2,0], [1,3,4], [2,2,4], angles='xy', scale_units='xy', scale=1)\nplt.xlim([0,6])\nplt.ylim([0,6])\nplt.show()\n\n## 5. Vector length ##\n\n# We're going to plot 3 vectors\n# The first will start at origin 0,0 , then go over 2 (this represents the bottom of the triangle)\n# The second will start at origin 2,2, and go up 3 (this is the right side of the triangle)\n# The third will start at origin 0,0, and go over 2 and up 3 (this is our vector, and is the hypotenuse of the triangle)\nX = [0,2,0]\nY = [0,0,0]\nU = [2,0,2]\nV = [0,3,3]\n# Actually make the plot.\nplt.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1)\nplt.xlim([0,6])\nplt.ylim([0,6])\nplt.show()\nvector_length = (4 + 9) ** .5\n\n## 6. Dot product ##\n\n# These two vectors are orthogonal\nX = [0,0]\nY = [0,0]\nU = [1,-1]\nV = [1,1]\nplt.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1)\nplt.xlim([-2,2])\nplt.ylim([-2,2])\nplt.show()\ndot = 3 * 5 + 4 * 6 + 5 * 7 + 6 * 8\n\n## 7. Making predictions ##\n\n# Slope and intercept are defined, and nba is loaded in\npredictions = slope * nba[\"fga\"] + intercept\n\n## 9. Multiplying a matrix by a vector ##\n\nimport numpy as np\n# Set up the coefficients as a column vector\ncoefs = np.asarray([[3], [-1]])\n# Setup the rows we're using to make predictions\nrows = np.asarray([[2,1], [5,1], [-1,1]])\n\n# We can use np.dot to do matrix multiplication.  This multiplies rows by coefficients -- the order is important.\nnp.dot(rows, coefs)\n\nnba_coefs = np.asarray([[slope], [intercept]])\nnba_rows = np.vstack([nba[\"fga\"], np.ones(nba.shape[0])]).T\npredictions = np.dot(nba_rows, nba_coefs)\n\n## 11. Applying matrix multiplication ##\n\nA = np.asarray([[5,2], [3,5], [6,5]])\nB = np.asarray([[3,1], [4,2]])\nC = np.dot(A, B)", "meta": {"hexsha": "090d78d8d130e0fdf8d951b534d1921a2b59ffaf", "size": 2496, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear Algebra/Working with vectors-80.py", "max_stars_repo_name": "vipmunot/Data-Analysis-using-Python", "max_stars_repo_head_hexsha": "34586d8cbbc336508c4a7a68abe14944f1096252", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Linear Algebra/Working with vectors-80.py", "max_issues_repo_name": "vipmunot/Data-Analysis-using-Python", "max_issues_repo_head_hexsha": "34586d8cbbc336508c4a7a68abe14944f1096252", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear Algebra/Working with vectors-80.py", "max_forks_repo_name": "vipmunot/Data-Analysis-using-Python", "max_forks_repo_head_hexsha": "34586d8cbbc336508c4a7a68abe14944f1096252", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5531914894, "max_line_length": 120, "alphanum_fraction": 0.6374198718, "include": true, "reason": "import numpy", "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147201714922, "lm_q2_score": 0.8962513689768735, "lm_q1q2_score": 0.8715280241669633}}
{"text": "import numpy as np\r\n\r\nITERATION_LIMIT = 1000\r\n\r\n# initialize the matrix\r\nA = np.array([[10., -1., 2., 0.],\r\n              [-1., 11., -1., 3.],\r\n              [2., -1., 10., -1.],\r\n              [0., 3., -1., 8.]])\r\n# initialize the RHS vector\r\nb = np.array([6., 25., -11., 15.])\r\n\r\nprint(\"System of equations:\")\r\nfor i in range(A.shape[0]):\r\n    row = [\"{0:3g}*x{1}\".format(A[i, j], j + 1) for j in range(A.shape[1])]\r\n    print(\"[{0}] = [{1:3g}]\".format(\" + \".join(row), b[i]))\r\n\r\nx = np.zeros_like(b)\r\nfor it_count in range(1, ITERATION_LIMIT):\r\n    x_new = np.zeros_like(x)\r\n    print(\"Iteration {0}: {1}\".format(it_count, x))\r\n    for i in range(A.shape[0]):\r\n        s1 = np.dot(A[i, :i], x_new[:i])\r\n        s2 = np.dot(A[i, i + 1:], x[i + 1:])\r\n        x_new[i] = (b[i] - s1 - s2) / A[i, i]\r\n    if np.allclose(x, x_new, rtol=1e-8):\r\n        break\r\n    x = x_new\r\n\r\nprint(\"Solution: {0}\".format(x))\r\nerror = np.dot(A, x) - b\r\nprint(\"Error: {0}\".format(error))", "meta": {"hexsha": "8dbeafde1f05a94a5dd7520f1a7dbfb926477147", "size": 966, "ext": "py", "lang": "Python", "max_stars_repo_path": "Trab2/Ex3/GaussSeidel.py", "max_stars_repo_name": "LeoSBastos/SiteCalculoNumerico", "max_stars_repo_head_hexsha": "20d5c3b45432583f26ec71fa5df9e210ed1802d7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Trab2/Ex3/GaussSeidel.py", "max_issues_repo_name": "LeoSBastos/SiteCalculoNumerico", "max_issues_repo_head_hexsha": "20d5c3b45432583f26ec71fa5df9e210ed1802d7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Trab2/Ex3/GaussSeidel.py", "max_forks_repo_name": "LeoSBastos/SiteCalculoNumerico", "max_forks_repo_head_hexsha": "20d5c3b45432583f26ec71fa5df9e210ed1802d7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1875, "max_line_length": 76, "alphanum_fraction": 0.4865424431, "include": true, "reason": "import numpy", "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.972414716174355, "lm_q2_score": 0.8962513627417531, "lm_q1q2_score": 0.8715280145214007}}
{"text": "\"\"\"\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import axes3d\r\nfrom matplotlib import cm\r\nimport scipy as sp\r\nfrom scipy.sparse import csr_matrix, linalg\r\nfrom scipy.stats import linregress\r\nfrom scipy import linalg, optimize\r\n\r\n################### Problema 1.4\r\n## Parte 1\r\n# Escriba dos funciones que calculen A_h y b_h. La entrada debe ser N,f,g\r\n\r\ndef calcula_A(N):\r\n    h = 1/ (N-1)\r\n    down = np.ones(N-2)\r\n    center = np.ones(N-1)\r\n    upper = np.ones(N-2)\r\n    d1 = -down\r\n    d2 = 4*center\r\n    d3 = -1*upper\r\n    d = np.array([d1, d2, d3])\r\n    offset = [-1, 0, 1]\r\n    L4 = sp.sparse.diags(d, offset)\r\n\r\n    dd1 = -down\r\n    dd2 = np.zeros(N-1)\r\n    dd3 = -upper\r\n    dd = np.array([dd1, dd2, dd3])\r\n    A1 = sp.sparse.diags(dd, offset)\r\n\r\n    I = np.identity(N-1)\r\n\r\n    L = sp.sparse.kron(A1, I)\r\n    R = sp.sparse.kron(I, L4)\r\n\r\n    A = (L + R) / h**2\r\n    return A\r\n\r\ndef g(x,y):\r\n    if y==1 and x<1 and x>0:\r\n        return np.sin(2*np.pi*x)\r\n    else:\r\n        return 0\r\n\r\nf = lambda x,y: 8*(np.pi**2)*np.sin(2*np.pi*x)*np.sin(2*np.pi*y)\r\n\r\ndef calcula_b(N, f, g):\r\n    f_h=np.zeros(N**2)\r\n    g_h=np.zeros(N**2)\r\n    x=np.linspace(0,1,num=N)\r\n    y=np.linspace(0,1,num=N)\r\n\r\n    for j in range(len(x)):\r\n        for k in range(len(y)):    \r\n            f_h[(k-1)*(N-1)+j]=f(x[j], y[k])\r\n\r\n    g_h[1]=N**2*(g(x[1],0)+g(0,y[1]))\r\n    g_h[N-1]=N**2*(g(x[N-1],0)+g(1,y[1]))\r\n    g_h[(N-1)**2-(N-2)]=N**2*(g(x[1],1)+g(0,y[N-1]))\r\n    g_h[(N-1)**2]=N**2*(g(x[N-1],1)+g(1,y[N-1]))\r\n    for j in range(2,N-1):#esto es para j in {2,...,N-2}\r\n        g_h[j]=N**2*g(x[j],0)\r\n        g_h[(N-1)*(N-2)+j]=N**2*g(x[j],1)\r\n        g_h[j*(N-1)+1]=N**2*(g(0,y[j]))\r\n        g_h[j*(N-1)]=N**2*g(1,y[j])\r\n\r\n    b_h=f_h+g_h\r\n    return b_h\r\n\r\n## Parte 2\r\n# Para N en {4,16}, grafique la solución numérica y la solución única de\r\n# la ecuación.\r\n\r\nN = [4, 16]\r\n\r\nfor i in range(0,len(N)):\r\n    u = sp.sparse.linalg.spsolve(calcula_A(N[i]), calcula_b(N[i]-1, f, g))\r\n    U = np.zeros((N[i], N[i]))\r\n    counter = 0\r\n    for j in range(N[i]-1):\r\n        for k in range(N[i]-1):\r\n            U[k][j] = u[k + j*(N[i]-1)]\r\n\r\n    x = np.linspace(0,1, N[i])\r\n\r\n    X, Y = np.meshgrid(x, x)\r\n    fig = plt.figure(i)\r\n    fig.clf()\r\n    ax = fig.add_subplot(111, projection='3d', elev=30, azim=10)\r\n    ax.plot_surface(X, Y, np.transpose(U)) #, rstride=2, cstride=2, cmap=cm.plasma\r\n    #ax.dist = 1\r\n    ax.set_xlabel('x')\r\n    ax.set_ylabel('y')\r\n    ax.set_zlabel('u')\r\n    fig.show()\r\n    \r\n'''\r\n# Parte 3\r\n#\r\n# para N en {4,8,16,32,64} =, calcule el error en norma L2.\r\n\r\narreglo_N = [ 2**(i) for i in range(2,7)]\r\n\r\n# Grafique los respectivos valores en función de h, en escala logarítmica\r\n# usando log log ¿qué puede observar?\r\n\r\n\r\n\"\"\" arreglo_N = [ 2**(i) for i in range(2,7)]\r\narreglo_condicion_A_h = []\r\n\r\nfor N in arreglo_N:\r\n    # cambiar por matriz A_h\r\n    A_h = np.identity( (N-1)**2 )\r\n    condicion_A_h = np.linalg.cond(A_h, p = 2)\r\n    arreglo_condicion_A_h.append(condicion_A_h)\r\n\r\narreglo_h   = np.divide(1,arreglo_N)\r\narreglo_N_2 = np.multiply(arreglo_N,arreglo_N) \r\n\r\ncondicion_fig,condicion_ax = plt.subplots(2)\r\ncondicion_h  = condicion_ax[0]\r\ncondicion_n2 = condicion_ax[1]\r\n\r\ncondicion_h.loglog(arreglo_h,arreglo_condicion_A_h)\r\ncondicion_n2.loglog(arreglo_N_2,arreglo_condicion_A_h)\r\n\r\nplt.show() \"\"\"\r\n\r\n\r\n# Calcule el orden de error experimental, es decir, estime mediante\r\n# regresión lineal el valor de p tal que e_h sea de orden O(h^p)\r\n\r\n\r\n# Parte 4\r\n# \r\n# recuerdo, A_h es matriz de (N-1)^2 x (N-1)^2\r\n#\r\n# Para N = {4,8,16,32,64}, **calcule el número de condición de A_h**\r\n# en la nroma 2. Compare esto h y N^2.\r\n# indicación, sea 1<=p <= infinityo. A matriz cuadrada de n por n.\r\n# se define la norma inducida p de A como\r\n# ||A||_p = sup |A_x|_p / |x|_p\r\n\r\n# def: si A es invertible, el número de condición en norma inducida p como\r\n# cond_p(A) = ||A||_p ||A^-1||_P\r\n# hint: para las observaciones : usar el teorema que aparece en la pregunta\r\n# \r\n# en python, numpy.linalg.cond\r\n'''\r\n\r\n################ Problema 2.4\r\n'''\r\ncontexto: Ecuación de calor en estado no estacionario\r\n\r\nd_dt u - d2_dt2 u = 0 ;   (t,x) en (0,infinito)x(0,1)\r\n\r\nu(t,x+1) = u(t,x)     ;\r\n\r\nu(0,x)   = u_(x)         \r\n\r\n\r\nN_T entero, un paso tempora dt > 0,\r\nN   entero, paso espacial   dx = 1/N                        \r\n\r\nx_j = j dx, j en {0,...,N}\r\nt_n = n dt, n en {0,...,N_T}\r\n\r\npuntos frontera:\r\n\r\nx_0 = 0\r\nx_n = 1\r\n\r\npuntos interiores:\r\nx1,...,x_N-1\r\n\r\nfinalmente, sea u_j^n una aproximación de u(t_n,x_j). Usando la discretización\r\ncentrada, es posible deducir que\r\n\r\ndu_dt (t,x_j) = () u(t,x_j+1) - 2u(t,x_j) + u(t,x_j-1) )/(dx**2)  + O(dx**2)\r\n\r\nintegrando en el intervalo [t_n,t_n+dt]\r\n\r\nu_j^n+1 - u_j^n approx dt/2 * (corcho)\r\n\r\ndonde se cumple que u_j^0 = u_0(xj). Esquema de Crank-Nicolson\r\n\r\n'''\r\n## Parte 1\r\n\r\nu_0 = lambda x: np.sin(4*np.pi*x)\r\n\r\n\"\"\" def resolucion(dt,N_T,N,u_0):\r\n    #u = u(t,x)\r\n    u = np.zeros([N_t+1,N+1],)\r\n \"\"\"\r\n## Parte 2", "meta": {"hexsha": "cfa6ff8369e68bbdf1a1b651677261fce9d9ea55", "size": 5004, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "JavierMonreal/Lab-2-EDPn", "max_stars_repo_head_hexsha": "0f860337010dfbe3289669b55a28981ebb8bc866", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.py", "max_issues_repo_name": "JavierMonreal/Lab-2-EDPn", "max_issues_repo_head_hexsha": "0f860337010dfbe3289669b55a28981ebb8bc866", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "JavierMonreal/Lab-2-EDPn", "max_forks_repo_head_hexsha": "0f860337010dfbe3289669b55a28981ebb8bc866", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1457286432, "max_line_length": 83, "alphanum_fraction": 0.5649480416, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.9230391690674338, "lm_q1q2_score": 0.8715122261596039}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"Serie_de_Taylor_en_Python.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/drive/1-k9zbpEj8QcH3ncAcQAePCHC28Kuz46w\n\n<a href=\"https://colab.research.google.com/github/joanby/calculo/blob/master/Serie_de_Taylor_en_Python.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n\n# Serie de Taylor en Python\n\n$$e^x = \\sum_{k=0}^n \\frac{x^k}{k!}$$\n\"\"\"\n\nimport math\n\nmath.factorial(3)\n\nx = 2\ne_2 = x**0/math.factorial(0)+x**1/math.factorial(1)+x**2/math.factorial(2)+x**3/math.factorial(3)+x**4/math.factorial(4)\nprint(e_2)\n\nprint(math.exp(2))\n\ndef func_e(x, n):\n  e_value = 0\n  for k in range(n): #0, 1, 2, 3, 4\n    e_value += x**k/math.factorial(k)\n  return e_value\n\nfunc_e(x = 2, n = 10)\n\nfunc_e(5, 7)\n\nx = 5\neps = 1e-6\nfor i in range(1, 200):\n  e_app = func_e(x, i)\n  e_exa = math.exp(x)\n  e_err = abs(e_app - e_exa)\n  if e_err < eps:\n    break\n\nprint(f\"Término {i}: Valor de Serie de Taylor = {e_app}, Valor real = {e_exa}, Error = {e_err}\")\n\n\n\n\"\"\"$$\\cos(x) = \\sum_{k=0}^n (-1)^k \\frac{x^{2k}}{(2k)!}$$\"\"\"\n\ndef func_cos(x, n):\n  cos_value = 0\n  for k in range(n):\n    coef = (-1)**k\n    num = x**(2*k)\n    den = math.factorial(2*k)\n    cos_value += coef*num/den\n  return cos_value\n\nangle = math.radians(45)\nprint(func_cos(angle, 7))\n\nmath.cos(angle)\n\n# Commented out IPython magic to ensure Python compatibility.\nimport numpy as np\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nangles = np.arange(-2*np.pi, 2*np.pi, 0.1)\np_cos = np.cos(angles)\n\nfig, ax = plt.subplots()\nax.plot(angles, p_cos)\n\nfor n in range(1, 7):\n  t_cos = [func_cos(angle, n) for angle in angles]\n  ax.plot(angles, t_cos)\n\nfig.set_size_inches(10,6)\n\nax.set_ylim([-7,5])\n\nlegend_list = [\"Función cos(x)\"]\nfor n in range(1, 7):\n  legend_list.append(f\"Pol. Taylor de grado {n}\")\nax.legend(legend_list, loc = 3)\n\nplt.show()\n\n", "meta": {"hexsha": "31c03ae9b4189624b061637006b00dea7fa972b9", "size": 1953, "ext": "py", "lang": "Python", "max_stars_repo_path": "teoria/Tema_06_serie_de_taylor_en_python.py", "max_stars_repo_name": "rjczm95/calculo", "max_stars_repo_head_hexsha": "89e20f6ff5ec9024dc5132ed93423a07bef96c32", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "teoria/Tema_06_serie_de_taylor_en_python.py", "max_issues_repo_name": "rjczm95/calculo", "max_issues_repo_head_hexsha": "89e20f6ff5ec9024dc5132ed93423a07bef96c32", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "teoria/Tema_06_serie_de_taylor_en_python.py", "max_forks_repo_name": "rjczm95/calculo", "max_forks_repo_head_hexsha": "89e20f6ff5ec9024dc5132ed93423a07bef96c32", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4615384615, "max_line_length": 220, "alphanum_fraction": 0.6600102407, "include": true, "reason": "import numpy", "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361742, "lm_q2_score": 0.9230391669503405, "lm_q1q2_score": 0.8715122227107941}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nN=101\ninitial=-np.pi\nfinal=np.pi\nx=np.linspace(initial,final,N)\nh=(final-initial)/(N-1)\n\n#analytic:\ny_ana=np.sin(x)\ndy_ana=np.cos(x)\n\n#acclaim the list to store the data\ndy_2=[]\ndy_3=[]\ndy_5=[]\n\nfor i in range(0,N-1):\n    dy_2.append((y_ana[i+1]-y_ana[i])/h)\n\nx2=np.delete(x,[N-1])\n\nfor i in range(1,N-1):\n    dy_3.append((y_ana[i+1]-y_ana[i-1])/h/2)\n\nx3=np.delete(x,[0,N-1])\n\nfor i in range(2,N-2):\n    dy_5.append((y_ana[i-2]-8*y_ana[i-1]+8*y_ana[i+1]-y_ana[i+2])/12/h)\n\nx5=np.delete(x,[0,1,N-2,N-1])\n\nplt.plot(x,dy_ana,label=\"analytic\")\nplt.plot(x2,dy_2,'r.',label=\"two points\")\nplt.plot(x3,dy_3,'k.',label=\"three points\")\nplt.plot(x5,dy_5,'g.',label=\"five points\")\nplt.legend()\nplt.show()\n\n#error calculation\nerror2=(abs(dy_2-dy_ana[0:N-1]))\nerror3=(abs(dy_3-dy_ana[1:N-1]))\nerror5=(abs(dy_5-dy_ana[2:N-2]))\n\nplt.plot(x2,error2,label=\"two points\")\nplt.plot(x3,error3,label=\"three points\")\nplt.plot(x5,error5,label=\"five points\")\nplt.title(\"error by using different number of points\")\nplt.legend()\nplt.show()", "meta": {"hexsha": "62b40de6c2cbee49776c4e044718481d6a113015", "size": 1063, "ext": "py", "lang": "Python", "max_stars_repo_path": "numerical_differentiation/sinx_2_3_5_differential.py", "max_stars_repo_name": "coherent17/physics_calculation", "max_stars_repo_head_hexsha": "cf94813778984f62b2c65174fb44bebb2e9c0d05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-30T01:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T01:11:30.000Z", "max_issues_repo_path": "numerical_differentiation/sinx_2_3_5_differential.py", "max_issues_repo_name": "coherent17/physics_calculation", "max_issues_repo_head_hexsha": "cf94813778984f62b2c65174fb44bebb2e9c0d05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical_differentiation/sinx_2_3_5_differential.py", "max_forks_repo_name": "coherent17/physics_calculation", "max_forks_repo_head_hexsha": "cf94813778984f62b2c65174fb44bebb2e9c0d05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8431372549, "max_line_length": 71, "alphanum_fraction": 0.673565381, "include": true, "reason": "import numpy", "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769078156284, "lm_q2_score": 0.8933094096048376, "lm_q1q2_score": 0.8714920315448922}}
{"text": "import numpy as np\n\n\nclass PCA:\n    \"\"\":class:`PCA` is a class for dimensionality reduction\n    \"\"\"\n\n    def __init__(self, n_components: int, whiten: bool = False):\n        self.n_components = n_components\n        self.whiten = whiten\n        self.e_values = None\n        self.w = None\n\n    def fit(self, x_mat: np.ndarray):\n        x_mat = x_mat - x_mat.mean(axis=0)\n        cov = np.cov(x_mat.T) / x_mat.shape[0]\n        e_values, e_vectors = np.linalg.eig(cov)\n        idx = e_values.argsort()[::-1]\n        e_values = e_values[idx]\n        e_vectors = e_vectors[:, idx]\n        self.w = e_vectors\n        self.e_values = e_values\n\n    def transform(self, x_mat: np.ndarray) -> np.ndarray:\n        if not self.w:\n            return\n        x_mat_projected = x_mat.dot(self.w[:, : self.n_components])\n        if self.whiten:\n            return x_mat_projected / np.sqrt(self.e_values[0 : self.n_components])\n        else:\n            return x_mat_projected\n\n    def fit_transform(self, x_mat: np.ndarray) -> np.ndarray:\n        self.fit(x_mat)\n        return self.transform(x_mat)", "meta": {"hexsha": "07c3909e5c6cbd59fa555c0cc962f0412a19e720", "size": 1083, "ext": "py", "lang": "Python", "max_stars_repo_path": "pca/pca.py", "max_stars_repo_name": "saromanov/pca", "max_stars_repo_head_hexsha": "475ecc3dc5c11416d4209634e6e81f99279a6f42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pca/pca.py", "max_issues_repo_name": "saromanov/pca", "max_issues_repo_head_hexsha": "475ecc3dc5c11416d4209634e6e81f99279a6f42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pca/pca.py", "max_forks_repo_name": "saromanov/pca", "max_forks_repo_head_hexsha": "475ecc3dc5c11416d4209634e6e81f99279a6f42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9428571429, "max_line_length": 82, "alphanum_fraction": 0.5974145891, "include": true, "reason": "import numpy", "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.975576912786245, "lm_q2_score": 0.8933093982432729, "lm_q1q2_score": 0.8714920249011106}}
{"text": "def cells():\n    # setup SymPy\n    from sympy import *\n    x, y, z, t = symbols('x y z t')\n    init_printing()\n    \n    # setup plotting\n    %matplotlib notebook\n    import matplotlib.pyplot as mpl\n    from util.plot_helpers import plot_vec, plot_vecs, autoscale_arrows\n\n    '''\n    '''\n\n    '''\n    ## SymPy Matrix objects\n    '''\n\n    '''\n    '''\n\n    v = Matrix([1,2,3])\n    v\n\n    '''\n    '''\n\n    # define symbolically\n    v_1, v_2, v_3 = symbols('v_1 v_2 v_3')\n    v = Matrix([v_1,v_2,v_3])\n\n    '''\n    '''\n\n    v\n\n    '''\n    '''\n\n    v.T\n\n    '''\n    '''\n\n    A = Matrix(\n        [   [1,7],\n            [2,8], \n            [3,9]   ])\n    A\n\n    '''\n    '''\n\n    # define symbolically\n    a_11, a_12, a_21, a_22, a_31, a_32 = symbols('a_11 a_12 a_21 a_22 a_31 a_32')\n    A = Matrix([\n            [a_11, a_12],\n            [a_21, a_22], \n            [a_31, a_32]])\n\n    '''\n    '''\n\n    A\n\n    '''\n    '''\n\n    '''\n    ## Vector operations\n    '''\n\n    '''\n    '''\n\n    u_1, u_2, u_3 = symbols('u_1 u_2 u_3')\n    u = Matrix([u_1,u_2,u_3])\n    v_1, v_2, v_3 = symbols('v_1 v_2 v_3')\n    v = Matrix([v_1,v_2,v_3])\n    alpha = symbols('alpha')\n    \n    u\n\n    '''\n    '''\n\n    alpha*u\n\n    '''\n    '''\n\n    u+v\n\n    '''\n    '''\n\n    u.norm()\n\n    '''\n    '''\n\n    uhat = u/u.norm()\n    uhat\n\n    '''\n    '''\n\n    u = Matrix([1.5,1])\n    w = 2*u\n    uhat = u/u.norm()\n    \n    fig = mpl.figure()\n    plot_vecs(u, w, uhat)\n    autoscale_arrows()\n\n    '''\n    '''\n\n    '''\n    ### Dot product\n    '''\n\n    '''\n    '''\n\n    u = Matrix([u_1,u_2,u_3])\n    v = Matrix([v_1,v_2,v_3])\n    \n    u.dot(v)\n\n    '''\n    '''\n\n    fig = mpl.figure()\n    u = Matrix([1,1])\n    v = Matrix([3,0])\n    plot_vecs(u,v)\n    autoscale_arrows()\n    \n    u_dot_v = u.dot(v)\n    u_dot_v\n\n    '''\n    '''\n\n    phi = acos( u.dot(v)/(u.norm()*v.norm()) )\n    print('angle between u and v is', phi)\n    u.norm()*v.norm()*cos(phi)\n\n    '''\n    '''\n\n    '''\n    ### Cross product\n    '''\n\n    '''\n    '''\n\n    u = Matrix([u_1,u_2,u_3])\n    v = Matrix([v_1,v_2,v_3])\n    \n    u.cross(v)\n\n    '''\n    '''\n\n    u = Matrix([1,0,0])\n    v = Matrix([1,1,0])\n    w = u.cross(v)      # a vector perpendicular to both u and v\n    \n    mpl.figure()\n    plot_vecs(u, v, u.cross(v))\n\n    '''\n    '''\n\n    print('length of cross product', w.norm())\n    \n    phi = acos( u.dot(v)/(u.norm()*v.norm()) )\n    \n    w.norm() == u.norm()*v.norm()*sin(phi)\n\n    '''\n    '''\n\n    '''\n    ## Projection operation\n    '''\n\n    '''\n    '''\n\n    def proj(vec, d):\n        \"\"\"Computes the projection of vector `vec` onto vector `d`.\"\"\"\n        return d.dot(vec)/d.norm() * d/d.norm()\n\n    '''\n    '''\n\n    fig = mpl.figure()\n    u = Matrix([1,1])\n    v = Matrix([3,0])\n    \n    pu_on_v = proj(u,v)\n    \n    plot_vecs(u, v, pu_on_v)\n    \n    \n    # autoscale_arrows()\n    ax = mpl.gca()\n    ax.set_xlim([-1,3])\n    ax.set_ylim([-1,3])\n    \n\n    '''\n    '''\n\n    '''\n    # Matrix operations\n    '''\n\n    '''\n    '''\n\n    a_11, a_12, a_21, a_22, a_31, a_32 = symbols('a_11 a_12 a_21 a_22 a_31 a_32')\n    A = Matrix([\n            [a_11, a_12],\n            [a_21, a_22], \n            [a_31, a_32]])\n    b_11, b_12, b_21, b_22, b_31, b_32 = symbols('b_11 b_12 b_21 b_22 b_31 b_32')\n    B = Matrix([\n            [b_11, b_12],\n            [b_21, b_22], \n            [b_31, b_32]])\n    alpha = symbols('alpha')\n\n    '''\n    '''\n\n    A\n\n    '''\n    '''\n\n    A + B\n\n    '''\n    '''\n\n    alpha*A\n\n    '''\n    '''\n\n    v_1, v_2 = symbols('v_1 v_2')\n    v = Matrix([v_1,v_2])\n    \n    A*v\n\n    '''\n    '''\n\n    A[:,0]*v[0] + A[:,1]*v[1]\n\n    '''\n    '''\n\n    A = Matrix([\n            [a_11,a_12],\n            [a_21, a_22], \n            [a_31, a_32]])\n    B = Matrix([\n            [b_11,b_12],\n            [b_21, b_22]])\n    \n    A*B\n\n    '''\n    '''\n\n    A.T\n\n    '''\n    '''\n\n    print('the shape of v is ', v.shape)\n    v\n\n    '''\n    '''\n\n    print('the shape of v.T is ', v.T.shape)\n    v.T\n\n    '''\n    '''\n\n    u = Matrix([u_1,u_2,u_3])\n    v = Matrix([v_1,v_2,v_3])\n    \n    u.T*v\n\n    '''\n    '''\n\n    u * v.T\n\n    '''\n    '''\n\n    A = Matrix([\n      [3,       3],\n      [2,  S(3)/2]\n    ])\n    A\n\n    '''\n    '''\n\n    A.inv()\n\n    '''\n    '''\n\n    A * A.inv()\n\n    '''\n    '''\n\n    A.inv() * A\n\n    '''\n    '''\n\n    B = Matrix([\n            [b_11,b_12],\n            [b_21, b_22]])\n    B\n\n    '''\n    '''\n\n    B.trace()\n\n    '''\n    '''\n\n    B.det()\n\n    '''\n    '''\n\n\n    '''\n    '''\n\n", "meta": {"hexsha": "89c2e6bcee25e061758f38a60623a878e146b039", "size": 4425, "ext": "py", "lang": "Python", "max_stars_repo_path": "aspynb/chapter02_definitions.py", "max_stars_repo_name": "ChidinmaKO/noBSLAnotebooks", "max_stars_repo_head_hexsha": "c0102473f1e6625fa5fb62768d4545059959fa26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aspynb/chapter02_definitions.py", "max_issues_repo_name": "ChidinmaKO/noBSLAnotebooks", "max_issues_repo_head_hexsha": "c0102473f1e6625fa5fb62768d4545059959fa26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aspynb/chapter02_definitions.py", "max_forks_repo_name": "ChidinmaKO/noBSLAnotebooks", "max_forks_repo_head_hexsha": "c0102473f1e6625fa5fb62768d4545059959fa26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.3603351955, "max_line_length": 81, "alphanum_fraction": 0.3769491525, "include": true, "reason": "from sympy", "num_tokens": 1514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.9263037231733433, "lm_q1q2_score": 0.8714570459238873}}
{"text": "#%% Imports\nimport numpy as np\n\n# np.where() evalutes before condition\nnp.seterr(divide='ignore',invalid='ignore')\n\n#%% Calculate the Entropy\n\ndef entropy(x,nbins=20):\n    count, bin_edges  = np.histogram(x,nbins)\n    p = count/len(x)\n    H = -np.sum(np.where(p>0,p*np.log2(p),0))\n    return H\n\n# # Entropy for X:\n# Hx = entropy(x)\n\n\n#%% Calculate the joint entropy for X and Y:\n\ndef joint_entropy(x,y,nbins=20):\n        count_xy, xedges, yedges = np.histogram2d(x,y,nbins)\n        p_xy = count_xy/len(y)\n\n        tmp = np.where(p_xy>0, p_xy*np.log2(p_xy),0)\n        Hxy = -np.sum(np.sum(tmp))\n        return Hxy\n\n# # Example:\n# Hxy = joint_entropy(x,y)\n\n#%% Calculate the conditional Entropies\n\ndef conditional_entropy(x,y,nbins=20):\n    count_xy,xedges,yedges = np.histogram2d(x,y,nbins)\n    # x-values are rows\n    # y-values are columns\n\n    p_xy = count_xy/len(x)\n\n    # Sum across all columns for each row\n    p_x = np.sum(p_xy,axis=1)\n\n    # Sum across all rows for each column\n    p_y = np.sum(p_xy,axis=0)\n    \n    # Conditional Entropy for Rows:\n    p_x = np.tile(p_x.reshape(-1,1), (1,nbins))\n    tmp = np.where(p_xy>0,p_xy*np.log2(p_xy/p_x),0)\n    Hyx_conditional = -np.sum(np.sum(tmp))\n\n    # Conditional Entropy for Columns:\n    p_y = np.tile(p_y, (nbins,1))\n    tmp = np.where(p_xy>0,p_xy*np.log2(p_xy/p_y),0)\n    Hxy_conditional = -np.sum(np.sum(tmp))\n\n    return Hyx_conditional, Hxy_conditional\n\n# Example: \n# Hyx_conditional, Hxy_conditional = conditional_entropy(x,y)\n\n\n\n\n#%% Old Functions\n\n# def joint_entropy(x,y,nbins=20):\n#         count_xy, xedges, yedges = np.histogram2d(x,y,nbins)\n#         p_xy = count_xy/len(y)\n\n#         tmp = np.empty((nbins,nbins))\n\n#         for i in range(nbins):\n#             for j in range(nbins):\n#                 tmp[i,j]=p_xy[i,j]*np.log2(p_xy[i,j])\n#         Hxy = -np.nansum(np.nansum(tmp))\n#         return Hxy\n\n# def conditional_entropy(x,y,nbins=20):\n#     count_xy,xedges,yedges = np.histogram2d(x,y,nbins)\n#     # x-values are rows\n#     # y-values are columns\n\n#     p_xy = count_xy/len(x)\n\n#     # Sum across all columns for each row\n#     p_x = np.sum(p_xy,axis=1)\n\n#     # Sum across all rows for each column\n#     p_y = np.sum(p_xy,axis=0)\n\n#     # Conditional Entropy for Rows:\n#     tmp = np.empty((nbins,nbins))\n\n#     for i in range(nbins):\n#         for j in range(nbins):\n#             tmp[i,j] = p_xy[i,j]*np.log2(p_xy[i,j]/p_x[i])\n#     Hyx_conditional = -np.nansum(np.nansum(tmp))\n\n#     # Conditional Entropy for Columns:\n#     tmp = np.empty((nbins,nbins))\n#     for j in range(nbins):\n#         for i in range(nbins):\n#             tmp[i,j] = p_xy[i,j]*np.log2(p_xy[i,j]/p_y[j])\n#     Hxy_conditional = -np.nansum(np.nansum(tmp))\n\n#     return Hyx_conditional, Hxy_conditional\n", "meta": {"hexsha": "b2eb178b7457cb8f46c2afa68d870aeb917f4489", "size": 2761, "ext": "py", "lang": "Python", "max_stars_repo_path": "dependency/entropy.py", "max_stars_repo_name": "dylan-lee94/statistics", "max_stars_repo_head_hexsha": "0808c7e86ca752774edbbe3bc504d8338cc5f2ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T14:53:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:53:36.000Z", "max_issues_repo_path": "dependency/entropy.py", "max_issues_repo_name": "dylan-lee94/statistics", "max_issues_repo_head_hexsha": "0808c7e86ca752774edbbe3bc504d8338cc5f2ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dependency/entropy.py", "max_forks_repo_name": "dylan-lee94/statistics", "max_forks_repo_head_hexsha": "0808c7e86ca752774edbbe3bc504d8338cc5f2ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5648148148, "max_line_length": 62, "alphanum_fraction": 0.6113726911, "include": true, "reason": "import numpy", "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96323053709097, "lm_q2_score": 0.904650538956921, "lm_q1q2_score": 0.8713870245191105}}
{"text": "# Matrices chain multiplication optimization\r\n# Author: Douglas Canevarollo\r\n\r\n# That optimization problem involves matrices multiplication. That is, considering and array chain\r\n# <A1, A2, ..., An>, which of the order of multiplications of this chain will return the least number\r\n# of scalar multiplications?\r\n\r\n# That dynamic implementation has a O(n^3) time complexity class when the recursive has a O(2^n).\r\nfrom numpy import zeros\r\nfrom sys import maxsize  # Max value of int64 size\r\n\r\n\r\n# Helper class to store the information of the read matrices.\r\nclass Matrix:\r\n    def __init__(self, lines, columns):\r\n        self.lines = int(lines)\r\n        self.columns = int(columns)\r\n\r\n\r\n# Method that prints the optimal matrices chain.\r\ndef print_chain(brackets, i, j):\r\n    if i == j:\r\n        print(\"A\" + str(i), end=' ')\r\n        return None\r\n\r\n    print(\"( \", end='')\r\n\r\n    print_chain(brackets, i, brackets[i][j])\r\n    print_chain(brackets, brackets[i][j] + 1, j)\r\n\r\n    print(\") \", end='')\r\n\r\n\r\n# dimensions = <d0, d1, d2, d3..., dn>, where the dimension of the Ai matrix is di-1,di. That is,\r\n# dimensions is actually the dimensions array of our matrices on the chain.\r\n# For instance, dimension of A3 is d2,d3.\r\ndef matrix_chain_order(dimensions, dim_size):\r\n    # The 'm' array stores the minimum number of scalar multiplications needed.\r\n    # We initialize it with zeros to simplify the code.\r\n    m = zeros((dim_size, dim_size), dtype='int64')\r\n    # 'brackets' array stores the chain position that contains parentheses.\r\n    brackets = zeros((dim_size, dim_size), dtype=int)\r\n\r\n    # Cost is zero when multiplying one matrix.\r\n    if dim_size == 1:\r\n        raise RuntimeError\r\n\r\n    if dim_size == 2:\r\n        m[1][-1] = dimensions[0]*dimensions[1]\r\n\r\n    # 'l' variable used to run through the dimensions array\r\n    for l in range(2, dim_size):\r\n        for i in range(1, dim_size - l + 1):\r\n            j = i+l-1\r\n\r\n            m[i][j] = maxsize  # Similar to m <- infinite\r\n            for k in range(i, j):\r\n                temp = m[i][k] + m[k+1][j] + dimensions[i - 1] * dimensions[k] * dimensions[j]\r\n                if temp < m[i][j]:\r\n                    m[i][j] = temp\r\n                    # 'k' is the optimal break point of the multiplication interval <Ai...j>\r\n                    brackets[i][j] = k\r\n\r\n    # Returns the minimum number of scalar multiplications needed and the brackets indexes array.\r\n    return m[1][-1], brackets\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    matrices = []\r\n    dimensions = []\r\n\r\n    try:\r\n        i = 0\r\n        chain_size = int(input(\"Number of matrices in the chain\\n> \"))\r\n        while i < chain_size:\r\n            print(\"\\nMatrix \" + str(i))\r\n            matrices.append(Matrix(input(\"Lines\\n> \"), input(\"Columns\\n> \")))\r\n            # Remember that to a matrices multiplication be possible the lines number of the 1st matrix\r\n            # should be equal to the columns number of the 2nd.\r\n            # Thus, we just need to store in 'p' array the matrices lines.\r\n            if i != 0 and matrices[i-1].columns != matrices[i].lines:\r\n                print(\"\\nERROR!\\nThe number of lines of this matrix should be equal to the previous columns.\")\r\n                matrices.pop(-1)\r\n                # Repeat the insertion on the index i\r\n                continue\r\n\r\n            dimensions.append(matrices[i].lines)\r\n            i += 1\r\n\r\n        dim_size = len(dimensions)\r\n        min_mult, brackets_array = matrix_chain_order(dimensions, dim_size)\r\n\r\n        print(\"\\nOptimal parenthesization\\n> \", end='')\r\n        print_chain(brackets_array, 0, dim_size-1)\r\n        print(\"\\n%i scalars multiplications needed.\" % min_mult)\r\n    except ValueError:\r\n        print(\"\\nJust integers, please. Try again.\")\r\n    except RuntimeError:\r\n        print(\"\\nYou cannot multiply just one matrix.\")\r\n    finally:\r\n        exit(0)\r\n", "meta": {"hexsha": "c84ea528b83922cff876001c96b51703dc71912c", "size": 3883, "ext": "py", "lang": "Python", "max_stars_repo_path": "mult-matrices-chains.py", "max_stars_repo_name": "dcanevarollo/optimization", "max_stars_repo_head_hexsha": "83845ffe64e78dd9307f56c38b351d0d5f40f7ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mult-matrices-chains.py", "max_issues_repo_name": "dcanevarollo/optimization", "max_issues_repo_head_hexsha": "83845ffe64e78dd9307f56c38b351d0d5f40f7ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mult-matrices-chains.py", "max_forks_repo_name": "dcanevarollo/optimization", "max_forks_repo_head_hexsha": "83845ffe64e78dd9307f56c38b351d0d5f40f7ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-28T14:19:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-28T14:19:06.000Z", "avg_line_length": 38.068627451, "max_line_length": 111, "alphanum_fraction": 0.6057172289, "include": true, "reason": "from numpy", "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877692486436, "lm_q2_score": 0.8976952962128457, "lm_q1q2_score": 0.8713818445458476}}
{"text": "import math\nimport numpy as np\n\n\ndef calc_angle(a, b, c):\n    \"\"\"\n    :param a: a[x, y]\n    :param b: b[x, y]\n    :param c: c[x, y]\n    :return: angle between ab and bc\n    \"\"\"\n    if b in (a, c):\n        raise ValueError(\"Undefined angle, two identical points\", (a, b, c))\n\n    ang = math.degrees(\n        math.atan2(a[1] - b[1], a[0] - b[0]) - math.atan2(c[1] - b[1], c[0] - b[0]))\n    return ang + 360 if ang < 0 else ang\n\n\ndef calc_m_and_b(point1, point2):\n    \"\"\"\n    calculate the slope intercept form of the line from Point 1 to Point 2.\n    meaning, finding the m and b, in y=mx+b.\n    :param point1: point 1\n    :param point2: point 2\n    :return: m, b\n    \"\"\"\n    points = [point1, point2]\n    x_coords, y_coords = zip(*points)\n    A = np.vstack([x_coords, np.ones(len(x_coords))]).T\n\n    return np.linalg.lstsq(A, y_coords, rcond=None)[0]\n\n\ndef y_from_m_b_x(m, b, x):\n    \"\"\"\n    get y from y=mx+b\n    :param m: slope (m)\n    :param b: b\n    :param x: x\n    :return: y from y=mx+b\n    \"\"\"\n    return m * x + b\n\n\ndef x_from_m_b_y(m, b, y):\n    \"\"\"\n    get x from y=mx+b\n    :param m: slope (m)\n    :param b: b\n    :param y: y\n    :return: get x from y=mx+b\n    \"\"\"\n    return (y - b) / m\n", "meta": {"hexsha": "acde56db85e9972d6ded6f5ccdf6d15617158cdd", "size": 1198, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/math.py", "max_stars_repo_name": "Tom-stack3/Labeler_demo", "max_stars_repo_head_hexsha": "7a14bf70f1ef6fbae20f0677fa1c0871630c65b7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/math.py", "max_issues_repo_name": "Tom-stack3/Labeler_demo", "max_issues_repo_head_hexsha": "7a14bf70f1ef6fbae20f0677fa1c0871630c65b7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/math.py", "max_forks_repo_name": "Tom-stack3/Labeler_demo", "max_forks_repo_head_hexsha": "7a14bf70f1ef6fbae20f0677fa1c0871630c65b7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7818181818, "max_line_length": 84, "alphanum_fraction": 0.5475792988, "include": true, "reason": "import numpy", "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970687766704745, "lm_q2_score": 0.8976952907388474, "lm_q1q2_score": 0.8713818369486585}}
{"text": "from numpy import loadtxt, zeros, ones, array, linspace, logspace\nfrom pylab import scatter, show, title, xlabel, ylabel, plot, contour\n\n\n#Evaluate the linear regression\ndef compute_cost(X, y, theta):\n    '''\n    Comput cost for linear regression\n    '''\n    #Number of training samples\n    m = y.size\n\n    predictions = X.dot(theta).flatten()\n\n    sqErrors = (predictions - y) ** 2\n\n    J = (1.0 / (2 * m)) * sqErrors.sum()\n\n    return J\n\n\ndef gradient_descent(X, y, theta, alpha, num_iters):\n    '''\n    Performs gradient descent to learn theta\n    by taking num_items gradient steps with learning\n    rate alpha\n    '''\n    m = y.size\n    J_history = zeros(shape=(num_iters, 1))\n\n    for i in range(num_iters):\n\n        predictions = X.dot(theta).flatten()\n\n        errors_x1 = (predictions - y) * X[:, 0]\n        errors_x2 = (predictions - y) * X[:, 1]\n\n        theta[0][0] = theta[0][0] - alpha * (1.0 / m) * errors_x1.sum()\n        theta[1][0] = theta[1][0] - alpha * (1.0 / m) * errors_x2.sum()\n\n        J_history[i, 0] = compute_cost(X, y, theta)\n\n    return theta, J_history\n\n\n#Load the dataset\ndata = loadtxt('ex1data1.txt', delimiter=',')\n\n#Plot the data\nscatter(data[:, 0], data[:, 1], marker='o', c='b')\ntitle('Profits distribution')\nxlabel('Population of City in 10,000s')\nylabel('Profit in $10,000s')\n#show()\n\nX = data[:, 0]\ny = data[:, 1]\n\n\n#number of training samples\nm = y.size\n\n#Add a column of ones to X (interception data)\nit = ones(shape=(m, 2))\nit[:, 1] = X\n\n#Initialize theta parameters\ntheta = zeros(shape=(2, 1))\n\n#Some gradient descent settings\niterations = 1500\nalpha = 0.01\n\n#compute and display initial cost\nprint compute_cost(it, y, theta)\n\ntheta, J_history = gradient_descent(it, y, theta, alpha, iterations)\n\nprint theta\n#Predict values for population sizes of 35,000 and 70,000\npredict1 = array([1, 3.5]).dot(theta).flatten()\nprint 'For population = 35,000, we predict a profit of %f' % (predict1 * 10000)\npredict2 = array([1, 7.0]).dot(theta).flatten()\nprint 'For population = 70,000, we predict a profit of %f' % (predict2 * 10000)\n\n#Plot the results\nresult = it.dot(theta).flatten()\nplot(data[:, 0], result)\nshow()\n\n\n#Grid over which we will calculate J\ntheta0_vals = linspace(-10, 10, 100)\ntheta1_vals = linspace(-1, 4, 100)\n\n\n#initialize J_vals to a matrix of 0's\nJ_vals = zeros(shape=(theta0_vals.size, theta1_vals.size))\n\n#Fill out J_vals\nfor t1, element in enumerate(theta0_vals):\n    for t2, element2 in enumerate(theta1_vals):\n        thetaT = zeros(shape=(2, 1))\n        thetaT[0][0] = element\n        thetaT[1][0] = element2\n        J_vals[t1, t2] = compute_cost(it, y, thetaT)\n\n#Contour plot\nJ_vals = J_vals.T\n#Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100\ncontour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))\nxlabel('theta_0')\nylabel('theta_1')\nscatter(theta[0][0], theta[1][0])\nshow()\n", "meta": {"hexsha": "6a1a7b48f8ffd18761ba4880ea892a7265308720", "size": 2869, "ext": "py", "lang": "Python", "max_stars_repo_path": "hard-gists/1321575/snippet.py", "max_stars_repo_name": "jjhenkel/dockerizeme", "max_stars_repo_head_hexsha": "eaa4fe5366f6b9adf74399eab01c712cacaeb279", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2019-07-08T08:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T23:53:25.000Z", "max_issues_repo_path": "hard-gists/1321575/snippet.py", "max_issues_repo_name": "jjhenkel/dockerizeme", "max_issues_repo_head_hexsha": "eaa4fe5366f6b9adf74399eab01c712cacaeb279", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-06-15T14:47:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T05:02:56.000Z", "max_forks_repo_path": "hard-gists/1321575/snippet.py", "max_forks_repo_name": "jjhenkel/dockerizeme", "max_forks_repo_head_hexsha": "eaa4fe5366f6b9adf74399eab01c712cacaeb279", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2019-05-16T03:50:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T14:35:12.000Z", "avg_line_length": 24.7327586207, "max_line_length": 79, "alphanum_fraction": 0.6577204601, "include": true, "reason": "from numpy", "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.977022630759019, "lm_q2_score": 0.8918110562208681, "lm_q1q2_score": 0.8713195842888919}}
{"text": "# finding LCM(Lowest Common Multiple)\r\n\r\n# The lowest common multiple is the least number that is common multiple of both of the numbers\r\n\r\n# find the lcms of the following two numbers\r\n\r\nimport numpy as np \r\n\r\nnum1 = 4\r\nnum2 = 6\r\n\r\nx = np.lcm(num1, num2)\r\n\r\nprint(x)\r\n# return 12\r\n\r\n# finding lcm in arrays\r\n# to find the lowest common multiple of all values in an array\r\n# you can use the reduce() method\r\n\r\n# the reduce() uses the ufunc, lcm() on each element and reduce the array by one dimension\r\n\r\n# import numpy as np \r\n\r\narr = np.array([3, 6, 9])\r\n\r\nx = np.lcm.reduce(arr)\r\n\r\nprint(x)\r\n\r\n# find the lcm of all an array where the array contains all integers from 1 to 10\r\n\r\n# import numpy as np \r\n\r\narr = np.arange(1, 11)\r\n\r\nx = np.lcm.reduce(arr)\r\n\r\nprint(x)", "meta": {"hexsha": "573b047396dc023111b9d9223620ca3f8677522b", "size": 766, "ext": "py", "lang": "Python", "max_stars_repo_path": "lcm.py", "max_stars_repo_name": "khinthandarkyaw98/Python_Practice", "max_stars_repo_head_hexsha": "9b431129c79315a57dae81048a22bf85c4b5132c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lcm.py", "max_issues_repo_name": "khinthandarkyaw98/Python_Practice", "max_issues_repo_head_hexsha": "9b431129c79315a57dae81048a22bf85c4b5132c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lcm.py", "max_forks_repo_name": "khinthandarkyaw98/Python_Practice", "max_forks_repo_head_hexsha": "9b431129c79315a57dae81048a22bf85c4b5132c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.641025641, "max_line_length": 96, "alphanum_fraction": 0.6736292428, "include": true, "reason": "import numpy", "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.9196425295259959, "lm_q1q2_score": 0.871251899435757}}
{"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.ion()\n\ndef simulateParticles_loop( n=50, n_gen=100, showPlots=True):\n    ''' simulate gaussian motion of n particles for n_gen steps each\n    '''\n    # store the value of each particle at every step\n    f_all = np.zeros((n,n_gen))\n    \n    for i in range(n):\n        y = 0\n        f_all[i,0] = y\n        for j in range(1,n_gen):\n            y += np.random.randn()\n            f_all[i,j] = y\n\n    x_grid, y_grid = np.mgrid[0:n, 0:n_gen]\n\n    if showPlots:\n        plt.figure()\n        plt.plot(y_grid.T, f_all.T, alpha=.2)\n\n        plt.figure()\n        plt.hist2d(y_grid.ravel(), f_all.ravel(), bins=(n_gen, 50))\n\n        plt.show()\n\n    return y_grid, f_all\n\ndef simulateParticles_loop_onAry( ary ):\n    ''' simulate gaussian motion of n particles for n_gen steps each\n    '''\n    for i in range(ary.shape[0]):\n        y = 0\n        for j in range(1, ary.shape[1]):\n            y += np.random.randn()\n            ary[i,j] = y\n    return ary\n\ndef simulateParticles_vec( n=50, n_gen=100, showPlots=True):\n    ''' simulate gaussian motion of n particles for n_gen steps each\n    '''\n    f_0 = np.zeros(n)\n    f_diff = np.random.randn(n, n_gen)\n    f_diff[:,0] = 0\n    f_all = f_0[:,np.newaxis] + f_diff.cumsum(1)\n\n    x_grid, y_grid = np.mgrid[0:n, 0:n_gen]\n\n    if showPlots:\n        plt.figure()\n        plt.plot(y_grid.T, f_all.T, alpha=.2)\n\n        plt.figure()\n        plt.hist2d(y_grid.ravel(), f_all.ravel(), bins=(n_gen,50))\n\n        plt.show()\n\n    return y_grid, f_all\n\ndef rotateParticles(n=50, n_gen=100):\n    ''' simulate gaussian motion of n particles for n_gen steps each\n        and then rotate all the particles paths\n    '''\n    y_grid, f_all = simulateParticles_vec(n=n, n_gen=n_gen)\n\n    ang = 0./180.*np.pi\n    xy = np.array([y_grid.ravel(), f_all.ravel()])\n    R = np.array( [[np.cos(ang), -np.sin(ang)],[np.sin(ang), np.cos(ang)]])\n    xy_rot = R.dot(xy)\n    fig = plt.figure()\n    lines = plt.plot(xy_rot[0].reshape(f_all.shape).T, \n                     xy_rot[1].reshape(f_all.shape).T, alpha=.2)\n\n    for ang in np.linspace(-np.pi/4,np.pi/4., 45):\n        R = np.array( [[np.cos(ang), -np.sin(ang)], [np.sin(ang), np.cos(ang)]])\n        xy_rot = R.dot(xy)\n\n        xy_2d = xy_rot.reshape((2, n, n_gen))\n\n        for i in range(n):\n            lines[i].set_data( xy_2d[0,i], xy_2d[1,i]) \n\n        fig.canvas.draw()\n\n", "meta": {"hexsha": "6190b90624d80887a9dfc638400e14c3fd8a278d", "size": 2398, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpyVectorization/motion_gauss.py", "max_stars_repo_name": "karthik/berkeley", "max_stars_repo_head_hexsha": "966563f24320cb002a6e48318ece0e8fe9cf6983", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 106, "max_stars_repo_stars_event_min_datetime": "2015-01-08T13:49:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T13:32:03.000Z", "max_issues_repo_path": "numpyVectorization/motion_gauss.py", "max_issues_repo_name": "karthik/berkeley", "max_issues_repo_head_hexsha": "966563f24320cb002a6e48318ece0e8fe9cf6983", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2015-01-29T21:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-01T09:37:45.000Z", "max_forks_repo_path": "numpyVectorization/motion_gauss.py", "max_forks_repo_name": "karthik/berkeley", "max_forks_repo_head_hexsha": "966563f24320cb002a6e48318ece0e8fe9cf6983", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 86, "max_forks_repo_forks_event_min_datetime": "2015-01-13T19:05:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T08:42:45.000Z", "avg_line_length": 27.5632183908, "max_line_length": 80, "alphanum_fraction": 0.5767306088, "include": true, "reason": "import numpy", "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.9252299637925936, "lm_q1q2_score": 0.8712466407660797}}
{"text": "import numpy as np\nfrom numpy.linalg import norm\n\n\ndef numerical_grad(func,x):\n    '''\n    Function to calculate gradients\n    of a function with a single parameter numerically\n\n    f(x+h) - f(x-h)\n    ---------------\n           2h\n\n    '''\n\n    h = 1e-7\n\n    grad_vec = []\n\n    #assuming x is a (num,shape) matrix\n    #for example (2,3,3) matrix\n    #then we need to compute the gradient one at a time\n\n    f_x_plus_h = func(x+h)\n    f_x_min_h = func(x-h)\n\n    grad_vec = (f_x_plus_h-f_x_min_h)/(2*h)\n\n    \n    return grad_vec\n\n\ndef compare(num_grads,grads):\n    diff = abs(num_grads-grads)\n    bools = diff < 1e-8\n    if np.sum(bools) == bools.size:\n        print('The derivated gradients are correct')\n    else:\n        print('The derivated gradients are wrong.')\n    return diff\n\ndef numerical_grad_layer(layer,lossfn,x,y,param_name):\n    '''\n    Function to calculate gradients\n    of a layer with respect to a parameter numerically\n\n    layer(x,param+h) - layer(x,param-h)\n    -----------------------------------\n                     2*h \n\n    the numerical gradients are calculated differently in that\n    every value in the parameter is tweaked and then we measure the \n    effect on the whole layer.\n    The loss is then calculated when we add and when we subtract\n\n    So it would be like this:\n    assuming:\n    `param` = [1,2,3]\n    `x` = [3,4,5]\n    `y` = [6,7,8]\n    loss(p,y) = sum(p-y)\n    `h` = 1e-4\n    net(param) = x+param\n\n    The numerical grad of param would be calculated as\n\n    [ \n        (loss(net([1+h,2,3]),y) - loss(net([1-h,2,3]),y)) / 2*h,\n\n        (loss(net([1,2+h,3]),y) - loss(net([1,2-h,3]),y)) / 2*h,\n\n        (loss(net([1,2,3+h]),y) - loss(net([1,2,3-h]),y)) / 2*h\n    ]\n    \n    \n    The result is [0.9999999999976694, 0.9999999999976694, 0.9999999999976694]\n    \n    which is pretty close to [1,1,1]\n\n    '''\n\n    h = 1e-7\n    \n    orig_param = layer.params[param_name].copy()\n    h_vec = np.zeros(np.prod(orig_param.shape))\n    n_grad = np.zeros_like(h_vec)\n\n\n    for idx in range(np.prod(orig_param.shape)):\n        h_vec[idx] = h\n\n        layer.params[param_name] = orig_param + h_vec.reshape(orig_param.shape)\n        l1 = lossfn(layer(x),y)\n\n        layer.params[param_name] = orig_param - h_vec.reshape(orig_param.shape)\n        l2 = lossfn(layer(x),y)\n\n        n_grad[idx] = (l1-l2)/(2*h)\n\n        h_vec[idx] = 0\n\n    \n    n_grad = n_grad.reshape(orig_param.shape)\n\n    return n_grad", "meta": {"hexsha": "f923c6280507b8a860a1f2e9206230221d03a77c", "size": 2429, "ext": "py", "lang": "Python", "max_stars_repo_path": "nnpy/core/tests.py", "max_stars_repo_name": "danny-1k/nnpy", "max_stars_repo_head_hexsha": "d6ab503ca92e8eb84de061f66f646a932686cfab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nnpy/core/tests.py", "max_issues_repo_name": "danny-1k/nnpy", "max_issues_repo_head_hexsha": "d6ab503ca92e8eb84de061f66f646a932686cfab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nnpy/core/tests.py", "max_forks_repo_name": "danny-1k/nnpy", "max_forks_repo_head_hexsha": "d6ab503ca92e8eb84de061f66f646a932686cfab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1333333333, "max_line_length": 79, "alphanum_fraction": 0.5841910251, "include": true, "reason": "import numpy,from numpy", "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.9219218348550491, "lm_q1q2_score": 0.8712112556884891}}
{"text": "import numpy as np\nfrom matplotlib import pyplot as plt\n \ndef polygon(n):\n    print(\"Initializing x and y array of size \"+str(n)+\" for x and y co-ordinates\")\n    x=[None]*n\n    y=[None]*n\n \n    numberofleftturn=0\n    numberofrightturn=0\n    \n    print(\"Getting Vertices:\")\n \n    for i in range (n): \n        x[i]=int(input(\"Enter x co-ordinate of Vertex \"+str(i+1)+\": \"))\n        y[i]=int(input(\"Enter y co-ordinate of Vertex \"+str(i+1)+\": \"))\n        plt.scatter(x[i],y[i])\n \n    print(\"***************************************************\")\n    print(\"List of Vertices Before Sorting:\")\n    print(\"***************************************************\")\n    for i in range(n):\n        print(\"(\"+str(x[i])+\",\"+str(y[i])+\")\")\n \n \n    print(\"Sorting All the Vertices in Counter Clockwise manner\")\n    center_point = [np.sum(x)/n, np.sum(y)/n]\n    angles = np.arctan2(x-center_point[0],y-center_point[1])\n    sort_tups = sorted([(i,j,k) for i,j,k in zip(x,y,angles)], key = lambda t: t[2],reverse=True)\n    if len(sort_tups) != len(set(sort_tups)):\n        raise Exception('You mistakenly input two equal vertices')\n    x,y,angles = zip(*sort_tups)    \n    \n \n    print(\"***************************************************\")\n    print(\"List of Vertices after Sorting:\")\n    print(\"***************************************************\")\n    for i in range(n):\n        print(\"(\"+str(x[i])+\",\"+str(y[i])+\")\")\n \n \n    print(\"***************************************************\")\n    print(\"Performing Turn Test:\")\n    print(\"***************************************************\")\n    \n    print(\"Appending First Two Coordinate to the list of vertices\")\n    x = list(x)\n    y = list(y)\n    \n    x.append(x[0])\n    y.append(y[0])\n \n    x.append(x[1])\n    y.append(y[1])\n \n    for i in range(n):\n        print(\"At Point(\"+str(x[i+1])+\",\"+str(y[i+1])+\")\")\n        print(\"Points to consider: (\"+str(x[i])+\",\"+str(y[i])+\")\",\"(\"+str(x[i+1])+\",\"+str(y[i+1])+\")\",\"(\"+str(x[i+2])+\",\"+str(y[i+2])+\")\")\n \n        turntest=(x[i+1]-x[i])*(y[i+2]-y[i])-(y[i+1]-y[i])*(x[i+2]-x[i])\n        if(turntest>0):\n            print(\"Left Turn\")\n            numberofleftturn=numberofleftturn+1\n        elif(turntest<0):\n            print(\"Right Turn\")\n            numberofrightturn=numberofrightturn+1\n        else:\n            print(\"Collinear\")\n \n    print(\"***************************************************\")\n    print(\"Checking Convexity:\")\n    print(\"***************************************************\")\n    if(numberofrightturn==0):\n        if(numberofleftturn==0):\n            print(\"All Points are Collinear\")\n        else:\n            print(\"Polygon is a Convex Polygon\")\n \n    else:\n        print(\"Polygon is a Concave Polygon\")\n \n    print(\"Plotting Co-ordinates\")\n    plt.plot(x,y,'-')\n    \n    print(\"Showing Graph\")\n    plt.show()\n \nprint(\"Implementation of Polygon, Turn Test, and Convexity\")\nprint(\"***************************************************\")\nn=int(input(\"Enter no of Vertices:\"))\npolygon(n)\n", "meta": {"hexsha": "d472b772dfbd43f3d39cb4e9c2d73a28cbcf9b33", "size": 2985, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "samratsuzil/polygon-turn-test", "max_stars_repo_head_hexsha": "b43bfa904324fc8846d17b6ec28cd1a9267c7619", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.py", "max_issues_repo_name": "samratsuzil/polygon-turn-test", "max_issues_repo_head_hexsha": "b43bfa904324fc8846d17b6ec28cd1a9267c7619", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "samratsuzil/polygon-turn-test", "max_forks_repo_head_hexsha": "b43bfa904324fc8846d17b6ec28cd1a9267c7619", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4456521739, "max_line_length": 138, "alphanum_fraction": 0.4659966499, "include": true, "reason": "import numpy", "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102542943773, "lm_q2_score": 0.900529786117893, "lm_q1q2_score": 0.8711817493879721}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n# In[1]:\nimport numpy as np  \nimport pandas as pd  \nfrom pandas_datareader import data as web  \nfrom scipy.stats import norm \nimport matplotlib.pyplot as plt  \nget_ipython().run_line_magic('matplotlib', 'inline')\n# In[2]:\nticker = 'PG'  \ndata = pd.DataFrame()\ndata[ticker] = web.DataReader(ticker, data_source='yahoo', start='2007-1-1', end='2017-3-21')['Adj Close']\n# In[3]:\nlog_returns = np.log(1 + data.pct_change())\n# <br /><br />\n# $$\n# {\\LARGE S_t = S_{t-1} \\mathbin{\\cdot} e^{((r - \\frac{1}{2} \\cdot stdev^2) \\mathbin{\\cdot} \\delta_t + stdev \\mathbin{\\cdot} \\sqrt{\\delta_t} \\mathbin{\\cdot} Z_t)}  }\n# $$\n# <br /><br />\n# In[4]:\nr = 0.025\n# In[5]:\nstdev = log_returns.std() * 250 ** 0.5\nstdev\n# In[6]:\ntype(stdev)\n# In[7]:\nstdev = stdev.values\nstdev\n# In[8]:\nT = 1.0 \nt_intervals = 250 \ndelta_t = T / t_intervals \niterations = 10000  \n# In[9]:\nZ = np.random.standard_normal((t_intervals + 1, iterations))  \nS = np.zeros_like(Z) \nS0 = data.iloc[-1]  \nS[0] = S0\n# <br /><br />\n# $$\n# {\\LARGE S_t = S_{t-1} \\mathbin{\\cdot} e^{((r - \\frac{1}{2} \\cdot stdev^2) \\mathbin{\\cdot} \\delta_t + stdev \\mathbin{\\cdot} \\sqrt{\\delta_t} \\mathbin{\\cdot} Z_t)}  }\n# $$\n# <br /><br />\n# In[10]:\nfor t in range(1, t_intervals + 1):\n    S[t] = S[t-1] * np.exp((r - 0.5 * stdev ** 2) * delta_t + stdev * delta_t ** 0.5 * Z[t])\n# In[11]:\nS\n# In[12]:\nS.shape\n# In[13]:\nplt.figure(figsize=(10, 6))\nplt.plot(S[:, :10]);\n", "meta": {"hexsha": "91e7a2628ecad8ad2b3f3c5debfe989395b019c8", "size": 1438, "ext": "py", "lang": "Python", "max_stars_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_109-MC-EulerDiscretization-PartI-Lecture_Yahoo_Py3.py", "max_stars_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_stars_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-04T11:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-10T15:36:42.000Z", "max_issues_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_109-MC-EulerDiscretization-PartI-Lecture_Yahoo_Py3.py", "max_issues_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_issues_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-03-30T16:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:37:21.000Z", "max_forks_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_109-MC-EulerDiscretization-PartI-Lecture_Yahoo_Py3.py", "max_forks_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_forks_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T11:26:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T11:26:16.000Z", "avg_line_length": 25.6785714286, "max_line_length": 165, "alphanum_fraction": 0.6001390821, "include": true, "reason": "import numpy,from scipy", "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102571131691, "lm_q2_score": 0.9005297807787537, "lm_q1q2_score": 0.8711817467612398}}
{"text": "import numpy as np\n\n\nclass GradientDescent:\n    \"\"\" Base Model:\n    X: array_like\n       The input dataset of shape (m x n+1), where m is the number of examples,\n        and n is the number of features. We assume a vector of one's already\n        appended to the features so we have n+1 columns.\n\n    y: array_like\n       The values of the function at each data point. This is a vector of\n        shape (m, ).\n\n    theta: array_like\n        The parameters for the regression function. This is a vector of\n        shape (n+1, ).\n\n    \"\"\"\n\n    def __init__(self, X, y, theta):\n        self.X = X\n        self.y = y\n        self.theta = theta\n\n    def compute_cost(self):\n        \"\"\"\n        calculates cost after each iteration\n        \"\"\"\n\n        # initializing values\n\n        # number of training examples\n        m = self.y.size\n\n        J = 0\n\n        # hypothesis function\n        h = self.X.dot(self.theta)\n\n        # calculating cost function\n        J = (1 / (2 * m)) * np.sum(np.square(h - self.y))\n\n        # returning cost of that iteration\n        return J\n\n    def gradient_descent(self, alpha, n_iterations):\n        \"\"\" Gradient Descent Function\n        alpha: float\n            The learning rate.\n\n        n_iterations: int\n            The number of itterations for gradient descent.\n\n        Returns\n            optimized theta vector and cost value after each iteration.\n        \"\"\"\n\n        # initializing values\n\n        # number of training examples\n        m = self.y.size\n\n        # making original copy of theta\n        theta = self.theta\n\n        # creating cost function history list\n        J_history = []\n\n        for _ in range(n_iterations):\n            self.theta = self.theta - (alpha / m) * \\\n                (np.dot(self.X, self.theta) - self.y).dot(self.X)\n\n            # save the cost J in every iteration\n            J_history.append(self.compute_cost())\n\n        # returning new theta vector, cost history list and original theta\n        return self.theta, J_history, theta\n", "meta": {"hexsha": "4fea68059bbe0cd375b27c09b8883ef2b68b2c8c", "size": 2012, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/Algorithms/MachineLearningAlgorithms/GradientDescent.py", "max_stars_repo_name": "Rr1901/AlgorithmsAndDataStructure", "max_stars_repo_head_hexsha": "b5606bbdc2a8e924a111e3757d02b3aeb780e053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195, "max_stars_repo_stars_event_min_datetime": "2020-05-09T02:26:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T06:12:07.000Z", "max_issues_repo_path": "Python/Algorithms/MachineLearningAlgorithms/GradientDescent.py", "max_issues_repo_name": "Trombokendu-dev/AlgorithmsAndDataStructure", "max_issues_repo_head_hexsha": "acdef5145e53f71281e8ae353f90bda98b100063", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31, "max_issues_repo_issues_event_min_datetime": "2021-06-15T19:00:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T15:51:25.000Z", "max_forks_repo_path": "Python/Algorithms/MachineLearningAlgorithms/GradientDescent.py", "max_forks_repo_name": "Trombokendu-dev/AlgorithmsAndDataStructure", "max_forks_repo_head_hexsha": "acdef5145e53f71281e8ae353f90bda98b100063", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 64, "max_forks_repo_forks_event_min_datetime": "2020-05-09T02:26:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T16:02:01.000Z", "avg_line_length": 25.4683544304, "max_line_length": 79, "alphanum_fraction": 0.578528827, "include": true, "reason": "import numpy", "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995742876885, "lm_q2_score": 0.90192067059785, "lm_q1q2_score": 0.8711647917717298}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nEjemplo: Ecuacion de Poisson 1D pero resuelto con FEniCS \n\n  -d2u/dx2 = 1   0 < x < 1\n    u(0) = 0 y u(1) = 0 en los bordes.\n    \n\"\"\"\n\nfrom __future__ import print_function\nfrom fenics import *\n# Defino la malla\nnx = 5 #numero de intervalos\nminx, maxx = 0.0, 1.0 \nmesh = IntervalMesh(nx, minx, maxx)#malla en 1D \nV = FunctionSpace(mesh, 'P',1)#Lagrange Finite Element\n\n# Defino las condiciones de borde\ndef borde_D(x, on_boundary): #retorna un boolean\n    tol = 1.E-14\n    return on_boundary and near(x[0], 1., tol)\n\ndef borde_I(x, on_boundary):\n    tol = 1.E-14\n    return on_boundary and near(x[0], 0., tol)\n\nbc_der = DirichletBC(V, Constant(0.0), borde_D)\nbc_iz = DirichletBC(V, Constant(0.0), borde_I)\n\nbc = [bc_iz, bc_der]\n\n# Comienzo la formulacion variacional\nu = TrialFunction(V)\nv = TestFunction(V)\nf = Constant(1.0)\n#Definicion abstracta \na = dot(grad(u), grad(v))*dx #o inner\nL = f*v*dx\n\n# Resuelvo\nu = Function(V)\nsolve(a == L, u, bc)\n\nprint('Tipo de variable:',type(u))\n\nimport matplotlib.pyplot as plt\n\n#Extraigo los datos de la solucion u.\nuh = u.compute_vertex_values(mesh) \n\nprint('Cantidad de celdas:',nx)\nprint('Cantidad de vertices:',len(uh))\n\nfig, axs = plt.subplots(1,1)\n\nimport numpy as np\n\nxu = np.linspace(0.0, 1.0, len(uh),endpoint = True)\n\naxs.plot(xu,uh,'ro',markersize=10)\n\n#Comparo con solucion exacta\nxe = np.arange(0.0,1.0,0.001)\nue = -0.5*xe*(xe-1.)\naxs.plot(xe,ue,'b')\n\n##Tambien se puede calcular en los mismos puntos que uh (para calcular errores)\n\nclass Resultado(UserExpression):\n    def eval(self, values, x):\n        values[0] = -0.5*x[0]*(x[0]-1.0)\n\nu_D = Resultado(degree=1)\nu_De = u_D.compute_vertex_values(mesh)\n\n##error_max = np.max(np.abs(u_De - uh))\n\n# Calcula el error en la norma L2\nerror_L2 = errornorm(u_D, u, 'L2')\n\n##print('Error maximo:',error_max)\nprint('Error en L2:',error_L2)\n\n\naxs.plot(xu,u_De,'.b',markersize=10)\nplt.title('Soluciones comparadas')\n\n\nplt.show()\n\n", "meta": {"hexsha": "b0da2e3e8e07ca1bb64cbfcd519d137b62d1e695", "size": 1973, "ext": "py", "lang": "Python", "max_stars_repo_path": "ejemplos/ejemplo6.py", "max_stars_repo_name": "gmg-utn/elementos_finitos", "max_stars_repo_head_hexsha": "5f8b11886d94d926fb358ad6344b079c5cb63e4e", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ejemplos/ejemplo6.py", "max_issues_repo_name": "gmg-utn/elementos_finitos", "max_issues_repo_head_hexsha": "5f8b11886d94d926fb358ad6344b079c5cb63e4e", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ejemplos/ejemplo6.py", "max_forks_repo_name": "gmg-utn/elementos_finitos", "max_forks_repo_head_hexsha": "5f8b11886d94d926fb358ad6344b079c5cb63e4e", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4456521739, "max_line_length": 79, "alphanum_fraction": 0.6751140395, "include": true, "reason": "import numpy", "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693688269984, "lm_q2_score": 0.9173026573249612, "lm_q1q2_score": 0.8711342356051243}}
{"text": "import numpy as np\nimport pascal\n\n\ndef jacobi_iter(x_0, epsilon, max_iter):  # 2a\n    A = np.matrix([[1.0, 1.0/2, 1.0/3], [1.0/2, 1.0, 1.0/4], [1.0/3, 1.0/4, 1.0]])\n    b = np.array([.1, .1, .1]).reshape(3, 1)\n    iteration = 0\n    error = 1000 \n    x_n = x_0\n    while iteration < max_iter:\n        d = np.diag(1 / np.diag(A))\n        alu = A - np.diag(np.diag(A))\n        x_1 = pascal.mult(d, b) + pascal.mult(pascal.mult(d, -alu), x_n)\n        error = pascal.norm_inf(x_1 - x_n)\n        x_n = x_1\n        if epsilon > error:\n            return x_n, iteration\n        iteration += 1\n    else:\n        return None, None\n\n\ndef gs_iter(x_0, epsilon, max_iter):  # 2a\n    A = np.matrix([[1.0, 1.0/2, 1.0/3], [1.0/2, 1.0, 1.0/4], [1.0/3, 1.0/4, 1.0]])\n    B = np.array([.1, .1, .1]).reshape(3, 1)\n    S_inv = np.zeros((3, 3))\n    a, b, c, d, e, f = A[0, 0], A[1, 0], A[1, 1], A[2, 0], A[2, 1], A[2, 2]\n    S_inv[0, 0] = 1.0/a\n    S_inv[1, 0] = -b/(a*c)\n    S_inv[1, 1] = 1.0/c\n    S_inv[2, 0] = (-c*d+b*e)/(a*c*f)\n    S_inv[2, 1] = -e/(c*f)\n    S_inv[2, 2] = 1.0/f\n\n    S = np.tril(A)\n    U = A - S\n\n    iteration = 0\n    error = 1000 \n    x_n = x_0\n    while iteration < max_iter:\n        x_1 = pascal.mult(pascal.mult(S_inv, -U), x_n)\n        x_1 += pascal.mult(S_inv, B)\n        error = pascal.norm_inf(x_1 - x_n)\n        x_n = x_1\n        if epsilon > error:\n            return x_n, iteration\n        iteration += 1\n    else:\n        return None, None\n\n\ndef rand_vec():\n    return np.random.rand(3, 1) * 2 - 1\n\n\ndef generate_data():  # 2b\n    jacobi_array = []\n    gs_array = []\n\n    for i in range(100):\n        x0 = rand_vec()\n        xn, iterations = jacobi_iter(x0, .00005, 100)\n        jacobi_array.append((x0, xn, iterations))\n\n    for i in range(100):\n        x0 = rand_vec()\n        xn, iterations = gs_iter(x0, .00005, 100)\n        gs_array.append((x0, xn, iterations))\n\n    return jacobi_array, gs_array\n\n", "meta": {"hexsha": "60be99cfd22c55aff057137741b321c54049fceb", "size": 1916, "ext": "py", "lang": "Python", "max_stars_repo_path": "iterative.py", "max_stars_repo_name": "joshuamorton/calc_three_proj", "max_stars_repo_head_hexsha": "0b0ff6bb2b0fba4c19f4d15e7719822e0fb4f9ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "iterative.py", "max_issues_repo_name": "joshuamorton/calc_three_proj", "max_issues_repo_head_hexsha": "0b0ff6bb2b0fba4c19f4d15e7719822e0fb4f9ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "iterative.py", "max_forks_repo_name": "joshuamorton/calc_three_proj", "max_forks_repo_head_hexsha": "0b0ff6bb2b0fba4c19f4d15e7719822e0fb4f9ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8918918919, "max_line_length": 82, "alphanum_fraction": 0.5104384134, "include": true, "reason": "import numpy", "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561712637256, "lm_q2_score": 0.8991213786215104, "lm_q1q2_score": 0.8711192963925991}}
{"text": "# Matrices and Matrix Operations\n#----------------------------------\n#\n# This function introduces various ways to create\n# matrices and how to use them in Tensorflow\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nops.reset_default_graph()\n\n# Declaring matrices\nsess = tf.Session()\n\n# Declaring matrices\n\n# Identity matrix\nidentity_matrix = tf.diag([1.0,1.0,1.0])\nprint('identity_matrix:')\nprint(sess.run(identity_matrix))\n\n# 2x3 random norm matrix\nA = tf.truncated_normal([2,3])\nprint 'A:'\nprint(sess.run(A))\n\n# 2x3 constant matrix\nB = tf.fill([2,3], 5.0)\nprint 'B:'\nprint(sess.run(B))\n\n# 3x2 random uniform matrix\nC = tf.random_uniform([3,2])\nprint 'C:'\nprint(sess.run(C))\nprint 'Rerun C:'\nprint(sess.run(C)) # Note that we are reinitializing, hence the new random variabels\n\n# Create matrix from np array\nD = tf.convert_to_tensor(np.array([[1., 2., 3.], [-3., -7., -1.], [0., 5., -2.]]))\nprint 'D:'\nprint(sess.run(D))\n\n# Matrix addition/subtraction\nprint 'A+B:'\nprint(sess.run(A+B))\nprint 'A-B:'\nprint(sess.run(B-B))\n\n# Matrix Multiplication\nprint(sess.run(tf.matmul(B, identity_matrix)))\n\n# Matrix Transpose\nprint(sess.run(tf.transpose(C))) # Again, new random variables\n\n# Matrix Determinant\nprint(sess.run(tf.matrix_determinant(D)))\n\n# Matrix Inverse\nprint(sess.run(tf.matrix_inverse(D)))\n\n# Cholesky Decomposition\nprint(sess.run(tf.cholesky(identity_matrix)))\n\n# Eigenvalues and Eigenvectors\nprint 'self_adjoint_eig:'\nprint(sess.run(tf.self_adjoint_eig(D)))", "meta": {"hexsha": "61219eec8b1d12f6525ad168a48c1c3bb4e50ad0", "size": 1504, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter 01/matrices.py", "max_stars_repo_name": "bharlow058/Packt-TF-cook-book", "max_stars_repo_head_hexsha": "2b2ed98bccdc36a41ea3247c23c944a15b81d7b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 587, "max_stars_repo_stars_event_min_datetime": "2017-02-16T15:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T13:16:07.000Z", "max_issues_repo_path": "Chapter 01/matrices.py", "max_issues_repo_name": "bharlow058/Packt-TF-cook-book", "max_issues_repo_head_hexsha": "2b2ed98bccdc36a41ea3247c23c944a15b81d7b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-03-07T07:49:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T01:54:23.000Z", "max_forks_repo_path": "Chapter 01/matrices.py", "max_forks_repo_name": "bharlow058/Packt-TF-cook-book", "max_forks_repo_head_hexsha": "2b2ed98bccdc36a41ea3247c23c944a15b81d7b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 427, "max_forks_repo_forks_event_min_datetime": "2017-02-16T07:52:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:10:12.000Z", "avg_line_length": 22.447761194, "max_line_length": 84, "alphanum_fraction": 0.7094414894, "include": true, "reason": "import numpy", "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561712637256, "lm_q2_score": 0.8991213718636754, "lm_q1q2_score": 0.8711192898452289}}
{"text": "import numpy as np\n\ndef properties(A):\n    (n, m) = A.shape\n\n    dimensins = A.ndim\n    symmetric = n == m and np.all(A == A.T)\n    skew_symmetric = n == m and np.all(A == -A.T)\n    invertable = n == m and np.linalg.det(A) != 0\n    orthogonal = np.allclose(A.dot(A.T), np.eye(np.min(A.shape)), atol=1e-6)\n    return f\"dimensions: {dimensins}\\nsymmetry: {symmetric}\\nskew symmetry: {skew_symmetric}\\ninveratibility: {invertable}\\northogonal: {orthogonal}\"\n\n# A = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])\n# A = np.array([[0, 1, 0], [-1, 0, 0], [0, 0, 0]]) # skew symmetric matrix\n# A = np.array([[1, 2, 3], [2, 1, 0], [3, 0, 1]]) # symmetric matrix\nA = np.array([[3, 4], [-4, 3]]) * 1/5 # orthogonal matrix\nprint(properties(A))", "meta": {"hexsha": "3ea3075614b33e1fef6afe2f6b001a5464774f60", "size": 740, "ext": "py", "lang": "Python", "max_stars_repo_path": "ue/ue_05/problem_3.py", "max_stars_repo_name": "VoxelPi/compm", "max_stars_repo_head_hexsha": "745019d4e0d156910f19ed9168949f150356a349", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ue/ue_05/problem_3.py", "max_issues_repo_name": "VoxelPi/compm", "max_issues_repo_head_hexsha": "745019d4e0d156910f19ed9168949f150356a349", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-03-09T22:54:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:33:49.000Z", "max_forks_repo_path": "ue/ue_05/problem_3.py", "max_forks_repo_name": "VoxelPi/compm", "max_forks_repo_head_hexsha": "745019d4e0d156910f19ed9168949f150356a349", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5294117647, "max_line_length": 149, "alphanum_fraction": 0.5824324324, "include": true, "reason": "import numpy", "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.968856165868213, "lm_q2_score": 0.899121375242593, "lm_q1q2_score": 0.8711192882676934}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport sys\n\n\ndef darts(N):\n    x = np.random.rand(N)\n    y = np.random.rand(N)\n    return x,y\n\n\ndef estimate_pi(N):\n    x,y = darts(N)\n    r = np.sqrt((x - 0.5)**2 + (y - 0.5)**2)\n    r_bool = (r <= 0.5)\n    pi_estimate = (np.sum(r_bool) / N) * 4\n    return pi_estimate\n\n\ndef plot_circle(xcenter,ycenter,radius):\n    theta = np.linspace(0, 2 * np.pi, 1000)\n    xpoints = radius* np.cos(theta) + xcenter\n    ypoints = radius * np.sin(theta) + ycenter\n    plt.plot(xpoints,ypoints, 'k')\n\n\ndef timer(function, argument):\n    start_time = time.time()\n    function(argument)\n    end_time = time.time()\n    return end_time - start_time\n\n\ndef plot_darts(N):\n    x,y = darts(N)\n    plt.figure()\n    r = np.sqrt((x - 0.5) ** 2 + (y - 0.5) ** 2)\n    plt.scatter(x[r < 0.5], y[r < 0.5], s=5, c='r')\n    plt.scatter(x[r > 0.5], y[r > 0.5], s=5, c='b')\n    plot_circle(0.5, 0.5, 0.5)\n    plt.show()\n\n\n# Plots darts for N = 1000\nplot_darts(10000)\n\n# Times and calculates values of pi for several values of N.\nN = 100000 * np.arange(1,11)\ntimes = []\nestimate_precision = []\n\nfor n in N:\n    times.append(timer(estimate_pi, n))\n    estimate_precision.append((abs(np.pi - estimate_pi(n)) / np.pi) *100)\n\n\n# Plot of Execution Time\nplt.figure()\nplt.scatter(N,times)\nplt.xlabel(\"Number of Darts\")\nplt.ylabel(\"Execution Time(s)\")\nplt.show()\n\n\n# Plot of Percent Error\nplt.figure()\nplt.scatter(N,estimate_precision)\nplt.xlabel(\"Number of Darts\")\nplt.ylabel(\"Percent Error\")\nplt.show()\n\n# Histogram of estimates and some statistics\nN = 1000\n\nestimates = []\nrepeats = 100\n\nfor i in range(100):\n    estimates.append(estimate_pi(N))\n\nplt.figure()\nplt.hist(estimates)\nprint(\"Mean: \" + str(np.mean(estimates)))\nprint(\"Standard Deviation: \" + str(np.std(estimates)))\nplt.show()\n\n", "meta": {"hexsha": "d47808d5358f158b48fb29c2898c1ea2743551a1", "size": 1812, "ext": "py", "lang": "Python", "max_stars_repo_path": "day2/exercises/estimate_pi.py", "max_stars_repo_name": "EBerzin/usrp-sciprog", "max_stars_repo_head_hexsha": "d1fe478aa2278226240657f7d40543adc6d843a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day2/exercises/estimate_pi.py", "max_issues_repo_name": "EBerzin/usrp-sciprog", "max_issues_repo_head_hexsha": "d1fe478aa2278226240657f7d40543adc6d843a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day2/exercises/estimate_pi.py", "max_forks_repo_name": "EBerzin/usrp-sciprog", "max_forks_repo_head_hexsha": "d1fe478aa2278226240657f7d40543adc6d843a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5909090909, "max_line_length": 73, "alphanum_fraction": 0.6374172185, "include": true, "reason": "import numpy", "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813513911655, "lm_q2_score": 0.9111797088058519, "lm_q1q2_score": 0.8710708093844269}}
{"text": "import numpy as np \nimport matplotlib.pyplot as plt \nimport sympy as sp \n\n\ndef func(exp):\n\t\"\"\"\n\tFunction to convert the expression to the Pythonic format to make mathematical calculations.\n\n\tParameters:\n\texp:\tinput expression by the user to be lambdified\n\t\"\"\"\n\n\tx = sp.symbols('x')\n\treturn sp.utilities.lambdify(x, exp, \"math\")\n\n\ndef diffy(exp):\n\t\"\"\"\n\tFunction to find the differential of an expression.\n\n\tParameters:\n\texp:\tinput expression whose differential is calculated\n\t\"\"\"\n\n\tx = sp.symbols('x')\n\treturn sp.diff(exp, x)\n\n\ndef newton_raphson(expr, guess, tol, roots):\n\t\"\"\"\n\tFunction to find the root of an expression using Newton-Raphson method.\n\n\tParameters:\n\texpr:\t\tinput expression for which the root is calculated\n\tguess:\t\tinitial guess as input by the user\n\ttol:\t\tmaximum permissible error between the calculated root and the true root\n\troots:\t\tan array to store the calculated roots through the iterations to be plotted later\n\t\"\"\"\n\n\tdiffer = diffy(expr)\n\tdiff_math = func(differ) \n\tfunction = func(expr)\n\n\tx_new = guess - function(guess)/diff_math(guess)\n\troots.append(x_new)\n\n\tif abs(x_new - guess) < tol:\n\n\t\treturn roots\n\n\telse:\n\n\t\treturn newton_raphson(expr, x_new, tol, roots)\n\ndef plot_func(expr, roots, guess):\n\t\"\"\"\n\tFunction to plot the expression, the initial guess and all the calculated roots while highlighting the final correct root.\n\n\tParameters:\n\texpr:\t\tthe expression to be plotted\n\troots:\t\tarray of roots calculated by Newton-Raphson method\n\tguess:\t\tinitial guess input by the user\n\t\"\"\"\n\n\tfunction = func(expr)\n\n\t# Plotting the function by creating an array of Xs and Ys\n\tx = np.linspace(np.floor(roots[-1]-5), np.ceil(roots[-1]+5), 50)\n\ty = []\n\n\tfor i in x:\n\t\ty.append(function(i))\n\n\t# An array of zeros the same length as the number of roots in arrays, so as to plot the roots\n\troots_y = np.zeros(len(roots))\n\n\tfig = plt.figure(figsize=(8,7))\n\n\tax1 = fig.add_axes([0.05, 0.05, 0.9, 0.9])\n\n\tax1.plot(x, y, label=\"Function: %s\"% expr)\n\tax1.axhline(0, color='red', ls='--', alpha=0.5)\n\tax1.scatter(roots[:-1], roots_y[:-1], color='black', s=10, alpha=0.8, edgecolor='black', label=\"Roots\")\n\tax1.scatter(guess, 0, color='red', s=15, label=\"Initial Guess: %s\"% str(guess))\n\tax1.scatter(roots[-1], 0, color=\"green\", s=15, label=\"Final Root: %s\"% str(round(roots[-1], 3)))\n\n\tax1.set_title(\"Finding Roots: Newton Raphson Method\")\n\tax1.legend()\n\n\tplt.show()\n\n# Sample input: \n\n# expr = \"x - tan(x)\"\n# init_guess = 4.6\n# error = 0.0001\n\npoints = []\n\nexpr = input(\"Enter a continuous function in x: \")\ninit_guess = float(input(\"Enter an initial guess for the root: \"))\nerror = float(input(\"Enter the maximum permissible error of the root: \"))\n\nanswers = newton_raphson(expr, init_guess, error, points)\n\nplot_func(expr, answers, init_guess)\n\nprint(f\"The root of {expr} by Newton-Raphson method: {round(answers[-1], 3)}\")\n\n", "meta": {"hexsha": "9f42b03f62ca2f3c04e3ea26087e4f469adc0dc7", "size": 2838, "ext": "py", "lang": "Python", "max_stars_repo_path": "Day 3 - Newton Raphson/newton_raphson.py", "max_stars_repo_name": "drkndl/Numerical-Methods-Challenge", "max_stars_repo_head_hexsha": "7e61f28c2d98b33f1952f2785a6728fa53f01f05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Day 3 - Newton Raphson/newton_raphson.py", "max_issues_repo_name": "drkndl/Numerical-Methods-Challenge", "max_issues_repo_head_hexsha": "7e61f28c2d98b33f1952f2785a6728fa53f01f05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 3 - Newton Raphson/newton_raphson.py", "max_forks_repo_name": "drkndl/Numerical-Methods-Challenge", "max_forks_repo_head_hexsha": "7e61f28c2d98b33f1952f2785a6728fa53f01f05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5675675676, "max_line_length": 123, "alphanum_fraction": 0.7019027484, "include": true, "reason": "import numpy,import sympy", "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214491222695, "lm_q2_score": 0.903294216466424, "lm_q1q2_score": 0.871065987806667}}
{"text": "import numpy as np\nimport sys\nimport json\n\n\ndef column_convertor(x):\n    \"\"\"\n    Converts 1d array to column vector\n    \"\"\"\n    x.shape = (1, x.shape[0])\n    return x\n\n\ndef get_norm(x):\n    \"\"\"\n    Returns Norm of vector x\n    \"\"\"\n    return np.sqrt(np.sum(np.square(x)))\n\n\ndef hh_reflection(v):\n    \"\"\"\n    Returns Householder matrix for vector v\n    \"\"\"\n    size_of_v = v.shape[1]\n    e1 = np.zeros_like(v)\n    e1[0, 0] = 1\n    vector = get_norm(v) * e1\n    if v[0, 0] < 0:\n        vector = - vector\n    u = (v + vector).astype(np.float32)\n    H = np.identity(size_of_v) - ((2 * np.matmul(np.transpose(u), u)\n                                   ) / np.matmul(u, np.transpose(u)))\n    return H\n\n\ndef qr_decomposition(q, r, iter, n):\n    \"\"\"\n    Return Q and R matrices for iter number of iterations.\n    \"\"\"\n    v = column_convertor(r[iter:, iter])\n    Hbar = hh_reflection(v)\n    H = np.identity(n)\n    H[iter:, iter:] = Hbar\n    r = np.matmul(H, r)\n    q = np.matmul(q, H)\n    return q, r\n\n\n# HANDLING THE EXECUTION\n\nn = int(sys.argv[1])\nm = int(sys.argv[2])\n\nA = np.random.rand(n, m)\nQ = np.identity(n)\nR = A.astype(np.float32)\nfor i in range(min(n, m)):\n    # For each i, H matrix is calculated for (i+1)th row\n    Q, R = qr_decomposition(Q, R, i, n)\nmin_dim = min(m, n)\nR = np.around(R, decimals=6)\nR = R[:min_dim, :min_dim]\nQ = np.around(Q, decimals=6)\n\nresult = {\n    \"n\": n,\n    \"m\": m,\n    \"R\": R.tolist(),\n    \"Q\": Q.tolist(),\n    \"A\": A.tolist()\n}\nprint(json.dumps(result))\nsys.stdout.flush()\n", "meta": {"hexsha": "f51fea71850ef493f9b9a62cd9cf00533f5431ce", "size": 1504, "ext": "py", "lang": "Python", "max_stars_repo_path": "engine/householder.py", "max_stars_repo_name": "doalef/linear-algebra-umz", "max_stars_repo_head_hexsha": "045d79b97bc22490373716051ab1b08f4522b58b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "engine/householder.py", "max_issues_repo_name": "doalef/linear-algebra-umz", "max_issues_repo_head_hexsha": "045d79b97bc22490373716051ab1b08f4522b58b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-25T19:09:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T19:09:53.000Z", "max_forks_repo_path": "engine/householder.py", "max_forks_repo_name": "doalef/linear-algebra-umz", "max_forks_repo_head_hexsha": "045d79b97bc22490373716051ab1b08f4522b58b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0533333333, "max_line_length": 69, "alphanum_fraction": 0.5605053191, "include": true, "reason": "import numpy", "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214491222696, "lm_q2_score": 0.9032942047513692, "lm_q1q2_score": 0.8710659765095885}}
{"text": "# encoding: utf-8\r\n# Powernoise.py\r\n# Adapted by Henrique Castilho 2019-04-14\r\n# From the original:\r\n########################################################\r\n#       Arbitrary Spectral Slope Noise Generation      #\r\n#               with MATLAB Implementation             #\r\n#                                                      #\r\n# From Little, 1992. Version by R. Rosa   08/08/14     #\r\n########################################################\r\n\r\nimport numpy as np\r\nimport math\r\n\r\ndef powernoise(beta, N, *varargin):\r\n# Generate samples of power law noise. The power spectrum\r\n# of the signal scales as f^(-beta).\r\n#\r\n# Usage:\r\n#  x = powernoise(beta, N)\r\n#  x = powernoise(beta, N, 'option1', 'option2', ...)\r\n#\r\n# Inputs:\r\n#  beta  - power law scaling exponent\r\n# For instance:\r\n# white noise   -> beta = 0;\r\n# pink noise    -> beta = -1;\r\n# red noise     -> beta = -2;\r\n#\r\n#  N     - number of samples to generate\r\n#\r\n# Output:\r\n#  x     - N x 1 vector of power law samples\r\n#\r\n# With no option strings specified, the power spectrum is\r\n# deterministic, and the phases are uniformly distributed in the range\r\n# -pi to +pi. The power law extends all the way down to 0Hz (DC)\r\n# component. By specifying the 'randpower' option string however, the\r\n# power spectrum will be stochastic with Chi-square distribution. The\r\n# 'normalize' option string forces scaling of the output to the range\r\n# [-1, 1], consequently the power law will not necessarily extend\r\n# right down to 0Hz.\r\n#\r\n# (cc) Max Little, 2008. This software is licensed under the\r\n# Attribution-Share Alike 2.5 Generic Creative Commons license:\r\n# http://creativecommons.org/licenses/by-sa/2.5/\r\n# If you use this work, please cite:\r\n# Little MA et al. (2007), \"Exploiting nonlinear recurrence and fractal\r\n# scaling properties for voice disorder detection\", Biomed Eng Online, 6:23\r\n#\r\n# As of 20080323 markup\r\n# If you use this work, consider saying hi on comp.dsp\r\n# Dale B. Dalrymple \r\n\r\n    opt_randpow = False\r\n    opt_normal = False\r\n\r\n    for arg in varargin:\r\n        if arg == 'normalize':\r\n            opt_normal = True\r\n        if arg == 'randpower':\r\n            opt_randpow = True\r\n\r\n    N2 = int(N / 2) - 1\r\n    f = np.arange(2, (N2 + 1) + 1, 1)\r\n    A2 = 1.0 / (f ** (beta / 2.0))\r\n\r\n    if not opt_randpow:\r\n        p2 = (np.random.uniform(0, 1, N2) - 0.5) * 2 * math.pi\r\n        d2 = A2 * np.exp(1j * p2)\r\n    else:\r\n        # 20080323\r\n        p2 = np.random.rand(N2) + 1j * np.random.rand(N2)\r\n        d2 = A2 * p2\r\n\r\n    d = np.concatenate(([1], d2, [1.0/((N2 + 2.0) ** beta)], np.flipud(np.conjugate(d2))))\r\n    x = np.real(np.fft.ifft(d))\r\n\r\n    if opt_normal:\r\n        x = ((x - min(x)) / (max(x) - min(x)) - 0.5) * 2\r\n\r\n    return x\r\n", "meta": {"hexsha": "6da4f7ae08ae22f830ab05e9cd8af7dee5c208ff", "size": 2728, "ext": "py", "lang": "Python", "max_stars_repo_path": "powernoise.py", "max_stars_repo_name": "efurlanm/CAP239", "max_stars_repo_head_hexsha": "062a703d06e4ec65aad2239a1b4cfd80bda537f0", "max_stars_repo_licenses": ["CC-BY-4.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "powernoise.py", "max_issues_repo_name": "efurlanm/CAP239", "max_issues_repo_head_hexsha": "062a703d06e4ec65aad2239a1b4cfd80bda537f0", "max_issues_repo_licenses": ["CC-BY-4.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "powernoise.py", "max_forks_repo_name": "efurlanm/CAP239", "max_forks_repo_head_hexsha": "062a703d06e4ec65aad2239a1b4cfd80bda537f0", "max_forks_repo_licenses": ["CC-BY-4.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8674698795, "max_line_length": 91, "alphanum_fraction": 0.5707478006, "include": true, "reason": "import numpy", "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214450208031, "lm_q2_score": 0.9032942054022056, "lm_q1q2_score": 0.871065973432373}}
{"text": "import numpy as np\n\n\ndef euclidean_distance(x, y):\n    \"\"\"\n    Parameters:\n    ----------\n    x: m-D array-like\n        a cluster points, e.g. array([[x1,y1],...,[xn,yn]])\n    y: 1-D array-like\n        one point, e.g. array([x1,y1]).\n    Returns:\n    ----------\n    dist: 1-D array-like\n        the euclidean distance from each one in x to y,\n        e.g. array([d1,...,dn])\n    \"\"\"\n    return minkowski_distance(x, y)\n\n\ndef minkowski_distance(x, y, p=2):\n    \"\"\"\n    Parameters:\n    ----------\n    x: m-D array-like\n        a cluster points, e.g. array([[x1,y1],...,[xn,yn]])\n    y: 1-D array-like\n        one point, e.g. array([x1,y1]).\n    p: int or np.inf\n        subscrpit of the L-p norm, p >= 1.\n    Returns:\n    ----------\n    dist: 1-D array-like\n        the minkowski distance from each one in x to y,\n        e.g. array([d1,...,dn])\n    \"\"\"\n    if p < 1:\n        raise Exception(\"p is too less than 1!\")\n    if p < np.inf:\n        return (np.sum(np.abs(x - y) ** p, -1)) ** (1/p)\n    return np.max(np.abs(x - y), -1)\n\n\ndef manhattan_distance(x, y):\n    \"\"\"\n    Parameters:\n    ----------\n    x: m-D array-like\n        a cluster points, e.g. array([[x1,y1],...,[xn,yn]])\n    y: 1-D array-like\n        one point, e.g. array([x1,y1]).\n    Returns:\n    ----------\n    dist: 1-D array-like\n        the manhattan distance from each one in x to y,\n        e.g. array([d1,...,dn])\n    \"\"\"\n    return minkowski_distance(x, y, p=1)\n\n\ndef chebyshev_distance(x, y):\n    \"\"\"\n    Parameters:\n    ----------\n    x: m-D array-like\n        a cluster points, e.g. array([[x1,y1],...,[xn,yn]])\n    y: 1-D array-like\n        one point, e.g. array([x1,y1]).\n    Returns:\n    ----------\n    dist: 1-D array-like\n        the chebyshev distance from each one in x to y,\n        e.g. array([d1,...,dn])\n    \"\"\"\n    return minkowski_distance(x, y, p=np.inf)\n\n\nif __name__ == \"__main__\":\n    x = np.array([\n        [5, 2],\n        [2, 2],\n        [6, 1]\n    ])\n    y = np.array([1, 1])\n    print(euclidean_distance(x, y))\n    print(minkowski_distance(x, y, 2))\n    print(manhattan_distance(x, y))\n    print(minkowski_distance(x, y, 1))\n    print(chebyshev_distance(x, y))\n    print(minkowski_distance(x, y, np.inf))\n", "meta": {"hexsha": "e862a794d6b32b6be71340305bb822319e5c3371", "size": 2200, "ext": "py", "lang": "Python", "max_stars_repo_path": "cluster/distance.py", "max_stars_repo_name": "oujin/WatermelonBookCode", "max_stars_repo_head_hexsha": "6ad8097b9b1d261ebd9bcb0fa53e49173ae7ebbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cluster/distance.py", "max_issues_repo_name": "oujin/WatermelonBookCode", "max_issues_repo_head_hexsha": "6ad8097b9b1d261ebd9bcb0fa53e49173ae7ebbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cluster/distance.py", "max_forks_repo_name": "oujin/WatermelonBookCode", "max_forks_repo_head_hexsha": "6ad8097b9b1d261ebd9bcb0fa53e49173ae7ebbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1758241758, "max_line_length": 59, "alphanum_fraction": 0.5077272727, "include": true, "reason": "import numpy", "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321448096903, "lm_q2_score": 0.9032941988938414, "lm_q1q2_score": 0.8710659699348411}}
{"text": "import numpy as np\n\n# part (a)\n\n# from lecture notes (week 6)\n# G = g(h1)+E(h1) = g(h1)+ch1^p\n# G = g(h2)+E(h2) = g(h2)+ch2^p\n\n# >> Eliminate c and solve for G\n\n# G = [ (h1/h2)^p * g(h2) - g(h1) ] / [ (h1/h2)^p - 1 ]\n\n# >> Assume h2 = h1/2\n\n# G = [ 2^p * g(h1/2) - g(h1) ] / [ 2^p - 1 ]\n\n# >> Use Taylor expansion\n\n# f(x+h) = f(x) + hf'(x) + (h^2/2!)f''(x) + (h^3/3!)f'''(x) + (h^4/4!)fiv(x) + (h^5/5!)fv(x) + ...\n\n# f(x-h) = f(x) - hf'(x) + (h^2/2!)f''(x) - (h^3/3!)f'''(x) + (h^4/4!)fiv(x) - (h^5/5!)fv(x) + ...\n\n# >> Sum an d subtract the two expansions\n\n# f(x+h)+f(x-h) = 2f(x) + (h^2)f''(x) + (h^4/12)fiv(x) \n\n# f(x+h)-f(x-h) = 2hf'(x) + (h^3/3)f'''(x) + (h^5/60)fv(x)\n\n# >> Rearrange for f'(x). The higher orders can be considered errors and not part of the actual solution. \n# Rearranging is only possible using f(x+h)-f(x-h) because f'(x) is cancelled out in f(x+h)+f(x-h)\n\n# f(x+h)-f(x-h) - (h^3/3)f'''(x) - (h^5/60)fv(x) = 2hf'(x)\n\n# [ f(x+h)-f(x-h) ] / 2h = centered approximation \n\n# [ (h^3/3)f'''(x) - (h^5/60)fv(x) ] / 2h = error associated with centered approximation\n\n# Refer to equation G(h)=g(h)+E(h) where E(h) is the error \n \n# [ f(x+h)-f(x-h) ] / 2h = g(h)\n\n# [ f(x+{h/2})-f(x-{h/2}) ] / h = g(h/2)\n\n# Substitute g(h) and g(h/2) into our equation for G\n\n# G = [ 2^p * ( [ f(x+{h1/2})-f(x-{h1/2}) ] / h ) - ([ f(x+h)-f(x-h) ] / 2h ]) ] / [ 2^p - 1 ]\n\n# part (b)\n\nx=1.0\nh=0.5\np=2.0 # this is the order of the error\n\ndef f(x): # equation given in Q\n    return x+(np.exp(x))\n\ndef dfdx(p, x, h): # central difference estimation of a differential\n    return (p(x+h/2)-p(x-h/2))/h\n\ng1 = dfdx(f, 1.0, 0.5) # plugging in constants given\ng2 = dfdx(f, 1.0, 0.25) \n\n\n# say h = h1 --> h2 = h1/2\n\nG = (((2**p)*g2)-g1)/((2**p)-1)\n\n# the error would be the difference between the derivative of f and the estimations g1 and G\n\ndef fi(x):\n    return 1+(np.exp(x))\n    \ntrueValue=fi(1)\n\nerr1=G-trueValue\nerr2=g1-trueValue\n\n\nprint \"The Richardson extrapolation equals\",round(G,3),\"when x is equal to \",round(x,4),\" and h is equal to\",h,\"with an error of\",round(err1,8)\nprint \"The central difference extrapolation equals\",round(g1,3),\"when x is equal to \",x,\" and h is equal to\",h,\"with an error of\",round(err2,3)\nprint \"The central difference and Richardson techniques give values that are within each others' error ranges, which is expected.\"\n\n\n\n\n\n\n\n", "meta": {"hexsha": "60fd7b8fc7a06092798c6c1b3e8d818cfca9b2c1", "size": 2352, "ext": "py", "lang": "Python", "max_stars_repo_path": "ExamPrep/Shit Comp/SciComp Exam 2016/Assignments 15-16/A2Q3 central difference error differentials richardson extrapolation.py", "max_stars_repo_name": "FHomewood/ScientificComputing", "max_stars_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_stars_repo_licenses": ["IJG"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ExamPrep/Shit Comp/SciComp Exam 2016/Assignments 15-16/A2Q3 central difference error differentials richardson extrapolation.py", "max_issues_repo_name": "FHomewood/ScientificComputing", "max_issues_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_issues_repo_licenses": ["IJG"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ExamPrep/Shit Comp/SciComp Exam 2016/Assignments 15-16/A2Q3 central difference error differentials richardson extrapolation.py", "max_forks_repo_name": "FHomewood/ScientificComputing", "max_forks_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_forks_repo_licenses": ["IJG"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4269662921, "max_line_length": 143, "alphanum_fraction": 0.5582482993, "include": true, "reason": "import numpy", "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778012346835, "lm_q2_score": 0.9099070139780661, "lm_q1q2_score": 0.8710337856689395}}
{"text": "#！/usr/bin/env python\r\n#  -*- coding:utf-8 -*-\r\n#  author:dabai time:2019/1/9\r\n\r\nimport math\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef runge_kutta(y, x, dx, f):\r\n    \"\"\" y is the initial value for y\r\n        x is the initial value for x\r\n        dx is the time step in x\r\n        f is derivative of function y(t)\r\n    \"\"\"\r\n    k1 = dx * f(y, x)\r\n    k2 = dx * f(y + 0.5 * k1, x + 0.5 * dx)\r\n    k3 = dx * f(y + 0.5 * k2, x + 0.5 * dx)\r\n    k4 = dx * f(y + k3, x + dx)\r\n    return y + (k1 + 2 * k2 + 2 * k3 + k4) / 6.\r\n\r\nif __name__=='__main__':\r\n    t = 0.\r\n    y = 1.\r\n    dt = .1\r\n    ys, ts = [], []\r\n\r\n\r\ndef func(y, t):\r\n    return t * math.sqrt(y)\r\n\r\n\r\nwhile t <= 10:\r\n    y = runge_kutta(y, t, dt, func)\r\n    t += dt\r\n    ys.append(y)\r\n    ts.append(t)\r\n\r\n# exact = [(t ** 2 + 4) ** 2 / 16. for t in ts]\r\n#plt.plot(ts, ys, label='runge_kutta')\r\n#plt.plot(ts, exact, label='exact')\r\n#plt.legend()\r\n#plt.show()\r\n# error = np.array(exact) - np.array(ys)\r\n# print(\"max error {:.5f}\".format(max(error)))\r\n\r\nfrom scipy.integrate import odeint\r\n\r\nYS=odeint(func,y0=1, t=np.arange(0,10.1,0.1))\r\n\r\nplt.plot(ts, ys, label='runge_kutta')\r\nplt.plot(ts, YS, label='odeint')\r\nplt.legend()\r\nplt.show()", "meta": {"hexsha": "2333e894d31cc48772d973ddb3cecd121d611458", "size": 1210, "ext": "py", "lang": "Python", "max_stars_repo_path": "ode45_02.py", "max_stars_repo_name": "KangChou/Python-and-math", "max_stars_repo_head_hexsha": "5b07bb2a67bed95cb13ef04c07dce8f6f2453126", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-03T02:55:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-05T06:48:33.000Z", "max_issues_repo_path": "ode45_02.py", "max_issues_repo_name": "KangChou/Python-and-math", "max_issues_repo_head_hexsha": "5b07bb2a67bed95cb13ef04c07dce8f6f2453126", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ode45_02.py", "max_forks_repo_name": "KangChou/Python-and-math", "max_forks_repo_head_hexsha": "5b07bb2a67bed95cb13ef04c07dce8f6f2453126", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-08-15T04:34:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-14T07:52:30.000Z", "avg_line_length": 22.8301886792, "max_line_length": 48, "alphanum_fraction": 0.5280991736, "include": true, "reason": "import numpy,from scipy", "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777975782054, "lm_q2_score": 0.909906997487259, "lm_q1q2_score": 0.8710337665556009}}
{"text": "import numpy as np\nimport math\nfrom functools import reduce\n \n \ndef raiser(omega, power):\n   if power == 0:\n       return (1, 0)\n   omegas = [omega] * power\n   return reduce(lambda a, b: (a[0] * b[0], a[1]+b[1]), omegas)\n \n \ndef multiplyer(omega, nz):\n   return (omega[0]*nz[0], omega[1]+nz[1])\n \ndef add(pn1, pn2):\n   c1 = to_complex(pn1)\n   c2 = to_complex(pn2)\n   z = (c1[0] + c2[0], c1[1] + c2[1])\n   return to_polar(z)\n \ndef subtract(pn1, pn2):\n   c1 = to_complex(pn1)\n   c2 = to_complex(pn2)\n   z = (c1[0] - c2[0], c1[1] - c2[1])\n   return to_polar(z)\n \ndef to_polar(n):\n   r = math.sqrt(n[0]**2 + n[1]**2)\n   if n[0] == 0:\n       if n[1] < 0:\n           return (r, -math.pi/2)\n       else:\n           return (r, math.pi/2)\n   theta = math.atan2(n[1], n[0])\n   return (r, theta)\n \ndef to_complex(pn1):\n   return (pn1[0]*math.cos(pn1[1]), pn1[0]*math.sin(pn1[1]))\n \n# O(nlogn) time to get points from coefficients or the other way\ndef fft(coefficients, omega, n, rev=False):\n   if omega is None:\n       omega = (1, 2*math.pi/n)\n       if rev :\n           omega = raiser((1, 2*math.pi/n), n-1)\n   if n == 1:\n       return coefficients\n   c_e = []\n   c_o = []\n   for i, c in enumerate(coefficients):\n       if i % 2 == 0:\n           c_e.append(c)\n       else:\n           c_o.append(c)\n   odds = fft(c_o, raiser(omega, 2), n //2, rev)\n   evens = fft(c_e, raiser(omega, 2), n //2, rev)\n   ans = [1]*n\n   for j in range(n//2):\n       if j != 0:\n           z = multiplyer(raiser(omega, j), odds[j])\n       else:\n           z = odds[j]\n       ans[j] = add(evens[j], z)\n       ans[n//2+j] = subtract(evens[j],  z)\n   return ans\n \n # O(nlogn) time to multiply polynomials\ndef polynomial_multiplication(n1, n2):\n   pts_1 = fft(n1, None, len(n1), False)\n   pts_2 = fft(n2, None, len(n2), False)\n   pts = []\n   for i, p in enumerate(pts_1):\n       pts.append((p[0] * pts_2[i][0], p[1] + pts_2[i][1]))\n \n   res = fft(pts, None, len(pts), True)\n   return res\n", "meta": {"hexsha": "7778619ecdc95a19bf3d7e53f8e9fa43b2247418", "size": 1950, "ext": "py", "lang": "Python", "max_stars_repo_path": "advanced_algs/fast_fourier_transform/fft.py", "max_stars_repo_name": "angelusualle/algorithms", "max_stars_repo_head_hexsha": "86286a49db2a755bc57330cb455bcbd8241ea6be", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "advanced_algs/fast_fourier_transform/fft.py", "max_issues_repo_name": "angelusualle/algorithms", "max_issues_repo_head_hexsha": "86286a49db2a755bc57330cb455bcbd8241ea6be", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "advanced_algs/fast_fourier_transform/fft.py", "max_forks_repo_name": "angelusualle/algorithms", "max_forks_repo_head_hexsha": "86286a49db2a755bc57330cb455bcbd8241ea6be", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0, "max_line_length": 64, "alphanum_fraction": 0.5379487179, "include": true, "reason": "import numpy", "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692311915195, "lm_q2_score": 0.8918110368115781, "lm_q1q2_score": 0.871004399690876}}
{"text": "# Create a version of fig 4.19 from \"Hands-on ML with Scikit-Learn\" \n# by Aurelien Geron\n# Based on his original code here:\n# https://nbviewer.jupyter.org/github/ageron/handson-ml2/blob/master/04_training_linear_models.ipynb\n\n#%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# plot range for theta1 and theta2\nt1a, t1b, t2a, t2b = -1, 3, -1.5, 1.5\n\n# create a grid of parameter combinations\nt1s = np.linspace(t1a, t1b, 500)\nt2s = np.linspace(t2a, t2b, 500)\nt1, t2 = np.meshgrid(t1s, t2s)\nparams = np.c_[t1.ravel(), t2.ravel()]\n\n# create some data\nnp.random.seed(1)\nN = 10\nD = 2\nX = np.random.randn(N, D)\ny = np.c_[2 * X[:, 0] + 0.5 * X[:, 1]]\n\n# compute MSE for all possible parameters\nJ = (1/N * np.sum((params.dot(X.T) - y.T)**2, axis=1)).reshape(t1.shape)\n\n# Compute norm of parameter values\nN1 = np.linalg.norm(params, ord=1, axis=1).reshape(t1.shape)\nN2 = np.linalg.norm(params, ord=2, axis=1).reshape(t1.shape)\n\n\n# Initial value for gradient descent\nt_init = np.array([[0.25], [-1]])\n\n\n# batch gradient descent\ndef bgd_path(theta, X, y, l1, l2, include_mse = 1, eta = 0.1, n_iterations = 50):\n    path = [theta]\n    for iteration in range(n_iterations):\n        gradients = include_mse * 2/len(X) * X.T.dot(X.dot(theta) - y) + \\\n            l1 * np.sign(theta) + 2 * l2 * theta\n        theta = theta - eta * gradients\n        path.append(theta)\n    return np.array(path)\n\n\n\ndef do_plot(l1=0, l2=0, ttl=\"\"):\n    JR = J + l1*N1 + l2*N2**2\n    N = l1*N1 + l2*N2**2\n    tr_min_idx = np.unravel_index(np.argmin(JR), JR.shape)\n    t1r_min, t2r_min = t1[tr_min_idx], t2[tr_min_idx]\n\n    levelsJR=(np.exp(np.linspace(0, 1, 20)) - 1) * (np.max(JR) - np.min(JR)) + np.min(JR)\n    levelsN=np.linspace(0, np.max(N), 10)\n    path_JR = bgd_path(t_init, X, y, l1=l1, l2=l2)\n\n    plt.figure(figsize=(6, 4))\n    plt.grid(True)\n    plt.axhline(y=0, color='k')\n    plt.axvline(x=0, color='k')\n    plt.contourf(t1, t2, JR, levels=levelsJR, alpha=0.9)\n    if l1>0 or l2>0:\n        plt.contour(t1, t2, N, levels=levelsN)\n    plt.plot(path_JR[:, 0], path_JR[:, 1], \"w-o\")\n    plt.plot(t1r_min, t2r_min, \"rs\")\n    plt.axis([t1a, t1b, t2a, t2b])\n    plt.xlabel(r\"$\\theta_1$\", fontsize=20)\n    plt.ylabel(r\"$\\theta_2$\", fontsize=20, rotation=0)\n    plt.title(ttl, fontsize=16)\n\n\ndo_plot(l1=0, l2=0, ttl=\"OLS\")\ndo_plot(l1=0.5, l2=0, ttl=\"lasso\")\ndo_plot(l1=0, l2=0.1, ttl=\"ridge\")\n\n", "meta": {"hexsha": "49805b7712374bd97f2cf952f4700cc5f7648d6d", "size": 2385, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/lasso-ridge-2d.py", "max_stars_repo_name": "qitsweauca/pyprobml", "max_stars_repo_head_hexsha": "59a1191896fbb7408fb589f0b8170a42c0f55969", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-04T05:43:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-04T05:43:10.000Z", "max_issues_repo_path": "examples/lasso-ridge-2d.py", "max_issues_repo_name": "YihaoHu/pyprobml", "max_issues_repo_head_hexsha": "59a1191896fbb7408fb589f0b8170a42c0f55969", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/lasso-ridge-2d.py", "max_forks_repo_name": "YihaoHu/pyprobml", "max_forks_repo_head_hexsha": "59a1191896fbb7408fb589f0b8170a42c0f55969", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8125, "max_line_length": 100, "alphanum_fraction": 0.6318658281, "include": true, "reason": "import numpy", "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.9136765322283324, "lm_q1q2_score": 0.8709850316366172}}
{"text": "from __future__ import division\nimport numpy as np\n\nimport matplotlib.pyplot as plt \n\n\n\n# Hypothesis\n\ndef Hypothesis(X,theta):\n    a=np.dot(X,theta)\n    sigmoid=1/(1+np.exp(-a))\n    return sigmoid\n    \n\n# cost function\ndef costFunction(hypothesis,Y,num_trainning):\n    \n    cost_result = -(1/num_trainning)*(np.dot(Y.T,np.log(hypothesis))+np.dot((1-Y).T,np.log(1-hypothesis)))\n    return cost_result\n\ndef gradientDescent(num_iterations,alpha,num_trainning,X,Y,theta):\n    \n    Jvalues=np.zeros((1,num_iterations))\n    \n    for i in range(num_iterations):\n        \n        result1=np.dot(X.T,np.subtract(Hypothesis(X,theta),Y))*(alpha/num_trainning)\n        theta=theta-result1\n        \n        Jvalues[0,i]=costFunction(Hypothesis(X,theta),Y,num_trainning)                                                                                                 \n        \n    return theta,Jvalues\n    \n    \ndef predict(theta, X):  \n    probability = Hypothesis(X,theta)\n    return [1 if x >= 0.5 else 0 for x in probability]    \n\n\n#----------------------------------------- Code Start here ------------------------------------------------\n# load data from file. here data consist of two features and the label.\ndata=np.genfromtxt(\"/directory/to/dataset\",\n                  delimiter=\",\") \n          \n\n# this for controlling the packing process of data to get x and y.\nfeatures_numbers=data.shape[1]-1\nlabel=data.shape[1]-1 # just for clarity\n\n# getting x and y , setting the algorithm values.          \nx=data[:,0:features_numbers]\ny=data[:,label]\n\ny=np.reshape(data[:,label],(y.shape[0],1))  # just for reshape the y to be (n,1) instead of (n,).\nm=y.size  # number of trainning set.\ntheta=np.zeros((x.shape[1],1))  \nalpha=0.01 # learning rate\niterations=10000\n\n#normalize x\n\nmean_vector=np.zeros((x.shape[1],1))\nstd_vector=np.zeros((x.shape[1],1))\n\n#normalize x\nmean_vector=np.zeros((x.shape[1],1))\nstd_vector=np.zeros((x.shape[1],1))\n\nfor i in range(features_numbers):\n    \n    mean_vector[i,0]=np.mean(x[:,i])\n    mean_vector[i,0]=np.mean(x[:,i])\n\n    std_vector[i,0]=np.std(x[:,i])\n    std_vector[i,0]=np.std(x[:,i])\n\nx=np.divide(np.subtract(x,mean_vector.T),std_vector.T)\n\n\n# --------------------------------------- Cost function --------------------------------------------------\ncost=costFunction(Hypothesis(x,theta),y,m)\n# you can print the cost value befire gradient descent works\nprint cost\n\n  \nnew_theta,Jvalues=gradientDescent(num_iterations=iterations,alpha=alpha,num_trainning=m,X=x,Y=y,theta=theta)\n\n# print gradient descent after working\nprint costFunction(Hypothesis(x,new_theta),y,m)\n  \n\n# calculating model accuracy\npredictions = predict(new_theta, x)  \ncorrect = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y)]  \naccuracy = (sum(map(int, correct)) % len(correct))  \nprint 'accuracy = {0}%'.format(accuracy)   ", "meta": {"hexsha": "b6393e9eda3e969cf45151b633ce14943a262bc7", "size": 2865, "ext": "py", "lang": "Python", "max_stars_repo_path": "logistic regression.py", "max_stars_repo_name": "Waleed-Daud/ML", "max_stars_repo_head_hexsha": "cc55f54b59a4cdf7eba31129fde17ce30a5bbda1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "logistic regression.py", "max_issues_repo_name": "Waleed-Daud/ML", "max_issues_repo_head_hexsha": "cc55f54b59a4cdf7eba31129fde17ce30a5bbda1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logistic regression.py", "max_forks_repo_name": "Waleed-Daud/ML", "max_forks_repo_head_hexsha": "cc55f54b59a4cdf7eba31129fde17ce30a5bbda1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5360824742, "max_line_length": 167, "alphanum_fraction": 0.610122164, "include": true, "reason": "import numpy", "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399077750858, "lm_q2_score": 0.8976953030553434, "lm_q1q2_score": 0.8709798080465441}}
{"text": "#------------------------------------------------#\r\n# Gauss Elimination Linear System Numeric Solver #\r\n#                   10/05/21                     #\r\n#------------------------------------------------#\r\n\r\n#Auxilary \r\nimport numpy as np\r\ndef rowChange(checkMat, line1, line2):\r\n    line1Aux = line1\r\n    while (line1Aux < checkMat.shape[0]) and (checkMat[line1Aux, line2]) == 0:\r\n        line1Aux += 1\r\n    #If entire row is 0s\r\n    if line1Aux == checkMat.shape[0]: \r\n        return None\r\n    #Swap Row\r\n    checkMat[[line1, line1Aux]] = checkMat[[line1Aux, line1]]\r\n    return checkMat\r\n\r\n#Main\r\ndef gaussElim(aMat_in, bMat_in):\r\n    import numpy as np\r\n    i = 0 #RowNum\r\n    j = 0 #ColNum\r\n    mult = 0 #Multiplier array\r\n    pivot = 0 #Line pivot\r\n\r\n    #Setup\r\n    aMat = aMat_in\r\n    bMat = bMat_in.reshape(aMat.shape[0],1)\r\n    augMat = np.hstack((aMat, bMat))\r\n    m = augMat.shape[0]\r\n    k = augMat.shape[1]\r\n    #Gauss algorithm\r\n    while (i < m) and (j < k):\r\n        #print(\"Step n°\" + str(i+1) + \":\" + \"\\n\" + str(augMat))\r\n        #Check consistency\r\n        if np.linalg.det(augMat[:, :-1]) == 0:\r\n            print(\"Matrix is not consistent / System is undetermined\")\r\n            break\r\n        #Search for pivot / Swap rows if pivot == 0 / Pivotal condensation\r\n        if (augMat[i,j] == 0):\r\n            augMat = rowChange(augMat, i, j)\r\n        pivot = augMat[i,j]\r\n        #Define multiplier\r\n        for i_m in range(i+1, m):\r\n            mult = augMat[i_m,j]/pivot\r\n            for j_m in range(j+1, k):\r\n                augMat[i_m,j_m] = augMat[i_m,j_m] - mult*augMat[i,j_m]\r\n            #Store multiplier in empty spaces\r\n            augMat[i_m,j] = mult \r\n        #Iterate\r\n        i += 1\r\n        j += 1\r\n\r\n    #Separating augmented matrix for convenience \r\n    newBMat = augMat[:, k-1]\r\n    newAMat = augMat[:, 0:k-1]\r\n\r\n    #Find results in triangular Matrix\r\n    results = [0]*m\r\n    results[m-1] = (newBMat[m-1]/newAMat[m-1, m-1])\r\n    for i in reversed(range(0, m-1)):\r\n        sumMat = 0\r\n        for j in range(i+1, m):\r\n            sumMat = sumMat + (newAMat[i,j]*results[j])\r\n        results[i] = (newBMat[i] - sumMat)/newAMat[i,i]\r\n    return results\r\n\r\n#Implementation Example\r\n\r\n#Test\r\naMat_in = np.array([[1,0,0,0],[1,0.5,pow(0.5,2),pow(0.5,3)],[1,0.75,pow(0.75,2),pow(0.75,3)],[1,1,1,1]])\r\nbMat_in = np.array([0,0.479,0.682,0.841])\r\nresults = gaussElim(aMat_in,bMat_in)\r\nprint(results)\r\n\r\n#Refinement step\r\nresultsRef = results\r\nrefError = 5\r\nwhile refError > 1e-5:\r\n    rMat =  np.longdouble(np.subtract(bMat_in,np.matmul(aMat_in, resultsRef)))\r\n    corrMat = gaussElim(aMat_in, rMat)\r\n    oldResultsRef = resultsRef\r\n    resultsRef = np.add(resultsRef,corrMat)\r\n    refError = (abs(np.subtract(oldResultsRef,resultsRef))).max()\r\nfinalResult = resultsRef\r\nprint(finalResult)\r\n", "meta": {"hexsha": "d938ccabe79a56c51d87731bafddee452aa9dabb", "size": 2825, "ext": "py", "lang": "Python", "max_stars_repo_path": "GaussElimination_v1.0.py", "max_stars_repo_name": "Guilherme-AD/Numeric-Algorithms", "max_stars_repo_head_hexsha": "c76c76e664a19be8fcf9fbd4240c40cb999a78ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GaussElimination_v1.0.py", "max_issues_repo_name": "Guilherme-AD/Numeric-Algorithms", "max_issues_repo_head_hexsha": "c76c76e664a19be8fcf9fbd4240c40cb999a78ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GaussElimination_v1.0.py", "max_forks_repo_name": "Guilherme-AD/Numeric-Algorithms", "max_forks_repo_head_hexsha": "c76c76e664a19be8fcf9fbd4240c40cb999a78ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1022727273, "max_line_length": 105, "alphanum_fraction": 0.5486725664, "include": true, "reason": "import numpy", "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377225508371, "lm_q2_score": 0.908617890746506, "lm_q1q2_score": 0.8709445236651012}}
{"text": "import numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nx0 = 0\r\ny0 = 2\r\nxf = 1\r\nn = 11\r\ndeltax = (xf-x0)/(n-1)\r\nx = np.linspace(x0,xf,n)\r\ndef f(x,y):\r\n\treturn y-x\r\n\r\ny = np.zeros([n])\r\ny[0] = y0\r\npy = np.zeros([n])\r\nfor i in range(0,4):\r\n\tpy[i] = None\r\n\r\nfor i in range(1,4):\r\n\tk1 = deltax*f(x[i-1],y0)\r\n\tk2 = deltax*f(x[i-1]+deltax/2,y0+k1/2)\r\n\tk3 = deltax*f(x[i-1]+deltax/2,y0+k2/2)\r\n\tk4 = deltax*f(x[i-1]+deltax,y0+k3)\r\n\ty[i] =  y0 + (k1 + 2*k2 + 2*k3 + k4)/6\r\n\ty0 = y[i]\r\n\r\nfor i in range(4,n):\r\n\tpy[i] = deltax/24*(55*f(x[i-1],y[i-1]) - 59*f(x[i-2],y[i-2]) + 37*f(x[i-3],y[i-3]) - 9*f(x[i-4],y[i-4]) )  + y[i-1] \r\n\ty[i] = deltax/24*( 9*f(x[i],py[i]) + 19*f(x[i-1],y[i-1]) - 5*f(x[i-2],y[i-2]) + f(x[i-3],y[i-3]) ) + y[i-1]\r\n\r\nprint(\"x_n\\t   py_n\\t           y_n\")\r\nfor i in range(n):\r\n\tprint (x[i],\"\\t\",format(py[i],'6f'),\"\\t\",format(y[i],'6f'))\r\n\r\nplt.plot(x,y,'o')\r\nplt.xlabel(\"Value of x\")\r\nplt.ylabel(\"Value of y\")\r\nplt.title(\"Approximation Solution with Adams-Bashforth-Moulton Method\")\r\nplt.show()\r\n\r\n#table 19-6\r\n", "meta": {"hexsha": "912a761d15358ad37f737cf938204f48bb5a3017", "size": 1029, "ext": "py", "lang": "Python", "max_stars_repo_path": "adams-bashforth-moulton_method.py", "max_stars_repo_name": "EloneSampaio/Numerical-Methods-First_Order_DE", "max_stars_repo_head_hexsha": "454acf91317a7789dea365490af00ed879583c19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-12T18:49:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T06:38:41.000Z", "max_issues_repo_path": "adams-bashforth-moulton_method.py", "max_issues_repo_name": "sultanki/Numerical-Methods-First_Order_DE", "max_issues_repo_head_hexsha": "454acf91317a7789dea365490af00ed879583c19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "adams-bashforth-moulton_method.py", "max_forks_repo_name": "sultanki/Numerical-Methods-First_Order_DE", "max_forks_repo_head_hexsha": "454acf91317a7789dea365490af00ed879583c19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-07-27T08:48:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T07:22:05.000Z", "avg_line_length": 24.5, "max_line_length": 118, "alphanum_fraction": 0.527696793, "include": true, "reason": "import numpy", "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673113726775, "lm_q2_score": 0.9046505421702796, "lm_q1q2_score": 0.8708827542656783}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 20 10:17:31 2018\n\n@author: Thiago, Renan\n\"\"\"\n\nimport matplotlib.lines as mlines\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math as m\n\n### Funcao pra achar a raiz ###\n\ndef F(x):\n    return m.exp(x) * (x - 1.0) - m.exp(-x) * (x + 1.0)\n\n### Derivada da funcao\n\ndef dF(x):\n    return m.exp(-x) * (x * m.exp(-2.0 * x) + x)\n    \n### Função de ponto fixo\n    \ndef pF(x):\n    return ((x+1.0)/m.exp(2.0 * x)) + 1.0\n\n  \ndef insert_dash(string, index):\n    return string[:index] + '|' + string[index:]\n    \n\n### Intervalo e chute inicial ###\n    \na = np.dtype('f8')\nb = np.dtype('f8')\nxi_s = np.dtype('f8')\nxi_n = np.dtype('f8')\nE = np.dtype('f8')\n    \na = 0.0\nb = 2.0\nxi = 1.5 #chute inicial\nx0 = 1.0 #chute inicial (secante)\nordem = 8\nE = 10**-ordem\n\n\n### Metodos\n\ndef bisseccao(_a, _b, Er):\n\n    _xa = _b\n    _x = _b\n    iteracoes = 0\n    lista_iteracoes = []\n\n    while(iteracoes < 10000):\n\n        #acha meio\n        e = _b - _a\n        mx = e / 2.0\n        _x = mx + _a\n\n        #determina valores\n        fa = F(_a)\n        fx = F(_x)\n        \n        #se a raiz estiver entre um dos intervalos formados, ajusta intervalo (_a, _b)\n        if((fa >= 0 and fx < 0) or (fa < 0 and fx >= 0)):\n            #intervalo a-x\n            _b = _x\n        else:\n            #intervalo x-b\n            _a = _x\n            \n        lista_iteracoes.append([iteracoes, _x, e])\n        \n        if(abs((_x - _xa) / _x) < Er):\n            break\n            \n        _xa = _x\n        iteracoes += 1\n        \n        \n        \n\n    #atingiu condicao de parada\n    return [_x, iteracoes, lista_iteracoes]\n  \ndef falsaPosicao(_a,_b, Er):\n    \n    xa = _b\n    x = _b\n    iteracoes = 0\n    lista_iteracoes = []\n    \n    #Checa a condição de existencia\n    if (F(_a) * F(_b) < 0):\n        \n        while(iteracoes < 10000):\n            \n            x = (_a * F(_b) - _b * F(_a)) / (F(_b) - F(_a))\n            \n            if(F(_a) * F(x) < 0):\n                _b = x\n            else:\n                _a = x\n                \n            \n            lista_iteracoes.append([iteracoes, x, abs((x - xa) / x)])\n            \n            if(abs((x - xa) / x) < Er):\n                break\n                \n            xa = x            \n            iteracoes += 1\n        \n        \n    return [x, iteracoes, lista_iteracoes] \n\n\ndef pontoFixo(xi, Er):\n    _x = xi\n    x0 = xi\n    iteracoes = 0\n    lista_iteracoes = []\n    while(iteracoes < 10000):\n        _x = pF(_x)\n        lista_iteracoes.append([iteracoes, _x, abs((_x - x0) / _x)])\n        \n        if(abs((_x - x0) / _x) < Er):\n            break;\n            \n        x0 = _x\n        iteracoes += 1\n        \n        \n    return [_x, iteracoes, lista_iteracoes]\n    \n    \ndef secante(x0, x1, Er):\n    iteracoes = 1\n    x2 = np.dtype('f8')\n    x2 = 0.0\n    lista_iteracoes = []\n    \n    lista_iteracoes.append([0, x1, abs((x1 - x0) / x1) ])\n    \n    while(iteracoes < 10000):\n        f0 = F(x0)\n        f1 = F(x1)\n        x2 = x2 - ((f1 * (x1 - x0)) / (f1 - f0))\n        \n        lista_iteracoes.append([iteracoes, x2, abs((x2 - x1) / x2) ])\n        \n        if(abs((x2 - x1) / x2) < Er):\n            break\n        \n        x0 = x1\n        x1 = x2\n        iteracoes += 1\n        \n    return [x2, iteracoes, lista_iteracoes]\n    \n    \ndef newton(xi, Er):\n    iteracoes = 0\n    lista_iteracoes = []\n    x0 = xi\n    \n    while(iteracoes < 10000):\n        x1 = x0 - (F(x0) / dF(x0))\n        \n        lista_iteracoes.append([iteracoes, x1, abs((x1 - x0) / x1)])\n        \n        if(abs((x1 - x0) / x1) < Er):\n            break\n        \n        x0 = x1\n        iteracoes += 1\n        \n    return [x1, iteracoes, lista_iteracoes]\n    \n### Implementacao dos metodos ###\n    \n### Bisseccao\nresultado_bisseccao = bisseccao(a, b, E)\nraiz_funcao_bis = resultado_bisseccao[0]\nnum_passos_bis = resultado_bisseccao[1]\nstring_bis = repr(raiz_funcao_bis)\n\nprint(\"\\nBisseccao:\\n\")\nprint(\"Raiz:\"+insert_dash(string_bis, ordem + string_bis.find('.') + 1)+\"\")\nprint(\"Precisao:\"+str(E)+\"\")\nprint(\"Num de Iteracoes:\"+str(num_passos_bis)+\"\")\n\n\n### Falsa Posicao\nresultado_falsa_pos = falsaPosicao(a, b, E)\nraiz_funcao_fpos = resultado_falsa_pos[0]\nnum_passos_fpos = resultado_falsa_pos[1]\nstring_fpos = repr(raiz_funcao_fpos)\n\nprint(\"\\nFalsa Posicao:\\n\")\nprint(\"Raiz:\"+insert_dash(string_fpos, ordem + string_fpos.find('.') + 1)+\"\")\nprint(\"Precisao:\"+str(E)+\"\")\nprint(\"Num de Iteracoes:\"+str(num_passos_fpos)+\"\")\n\n### Ponto Fixo\nresultado_ponto_fixo = pontoFixo(xi, E)\nraiz_funcao_pfixo = resultado_ponto_fixo[0]\nnum_passos_pfixo = resultado_ponto_fixo[1]\nstring_pfixo = repr(raiz_funcao_pfixo)\n\nprint(\"\\nPonto Fixo:\\n\")\nprint(\"Chute inicial:\"+str(xi)+\"\")\nprint(\"Raiz:\"+insert_dash(string_pfixo, ordem + string_pfixo.find('.') + 1)+\"\")\nprint(\"Precisao:\"+str(E)+\"\")\nprint(\"Num de Iteracoes:\"+str(num_passos_pfixo)+\"\")\n\n\n### Newton\nresultado_newton = pontoFixo(xi, E)\nraiz_funcao_newton = resultado_newton[0]\nnum_passos_newton = resultado_newton[1]\nstring_newton = repr(raiz_funcao_newton)\n\nprint(\"\\nNewton:\\n\")\nprint(\"Chute inicial:\"+str(xi)+\"\")\nprint(\"Raiz:\"+insert_dash(string_newton, ordem + string_newton.find('.') + 1)+\"\")\nprint(\"Precisao:\"+str(E)+\"\")\nprint(\"Num de Iteracoes:\"+str(num_passos_newton)+\"\")\n\n### Secante\nresultado_secante = secante(x0, xi, E)\nraiz_funcao_secante = resultado_secante[0]\nnum_passos_secante = resultado_secante[1]\nstring_secante = repr(raiz_funcao_secante)\n\nprint(\"\\nSecante:\\n\")\nprint(\"Chute inicial 0: \"+str(x0)+\"\")\nprint(\"Chute inicial 1:\"+str(xi)+\"\")\nprint(\"Raiz:\"+insert_dash(string_secante, ordem + string_secante.find('.') + 1)+\"\")\nprint(\"Precisao:\"+str(E)+\"\")\nprint(\"Num de Iteracoes:\"+str(num_passos_secante)+\"\")\n\n\n### Geração de gráficos\n\ndef geraGrafico(nome, lista):\n    lista0 = []\n    lista1 = []\n    lista2 = []\n    \n    for item in lista:\n        lista0.append(item[0])\n        lista1.append(item[1])\n        lista2.append(item[2])\n        \n    #plota grafico\n    plt.plot(\n        lista0, lista1, 'b--', \n        lista0, lista2, 'r--'\n    )\n    \n    #legendas do grafico\n    se_line = mlines.Line2D([], [], color='blue', marker='', markersize=0, label=u'Solução')\n    ee_line = mlines.Line2D([], [], color='red', marker='', markersize=0, label=u'Erro')\n    \n    plt.legend(handles=[se_line, ee_line])\n    plt.title(nome)\n    plt.show()\n    \n\n#geraGrafico(u\"Bissecçao\", resultado_bisseccao[2])\n#geraGrafico(u\"Falsa Posicao\", resultado_falsa_pos[2])\n#geraGrafico(u\"Ponto Fixo\", resultado_ponto_fixo[2])\n#geraGrafico(u\"Newton\", resultado_newton[2])\ngeraGrafico(u\"Secante\", resultado_secante[2])", "meta": {"hexsha": "0899a93fadf6ad10b371c9773dcec751b6a10334", "size": 6597, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lista2/questao4.py", "max_stars_repo_name": "thiago9864/calculo_numerico", "max_stars_repo_head_hexsha": "e4b6f059bdb31460130093bd446fb3ea906dc542", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lista2/questao4.py", "max_issues_repo_name": "thiago9864/calculo_numerico", "max_issues_repo_head_hexsha": "e4b6f059bdb31460130093bd446fb3ea906dc542", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lista2/questao4.py", "max_forks_repo_name": "thiago9864/calculo_numerico", "max_forks_repo_head_hexsha": "e4b6f059bdb31460130093bd446fb3ea906dc542", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-08-25T14:30:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-25T14:30:48.000Z", "avg_line_length": 23.5607142857, "max_line_length": 92, "alphanum_fraction": 0.5549492193, "include": true, "reason": "import numpy", "num_tokens": 2138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673113726775, "lm_q2_score": 0.9046505383142492, "lm_q1q2_score": 0.8708827505535814}}
{"text": "import time\n\nimport numpy as np\nfrom scipy import misc\n\nfrom hermite import hermite_polynomial\nfrom lagrange import lagrange_polynomial\nfrom power_series import power_serie\n\nf = np.sin\na = -5\nb = 5\nn_ = int(input(\"input n ? (polynomial's degree will be 2n+1)\"))\nstartLT = time.time()\nn = 2 * n_ + 2\nracines = [(a + b) / 2 + (a - b) / 2 * np.cos((2 * k + 1) * (np.pi) / (2 * n)) for k in range(0, n)]\nycoords = [f(x) for x in racines]\nL = lagrange_polynomial(racines, ycoords)\nendLT = time.time()\nlengthLT = endLT - startLT\nstartLH = time.time()\nn_ = n_ + 1\nycoords = [f(x) for x in racines]\ndycoords = [misc.derivative(f, x) for x in racines]\nL = hermite_polynomial(racines, ycoords, dycoords)\nendLH = time.time()\nlengthLH = endLH - startLH\nstartSP = time.time()\nres = []\nxcoords = [a + k * (b - a) / n for k in range(n + 1)]\nycoords = [f(k) for k in xcoords]\ndycoords = [misc.derivative(f, k) for k in xcoords]\nfor k in range(n):\n    a0 = ycoords[k + 1] / (xcoords[k + 1] - xcoords[k])\n    a1 = ycoords[k] / (xcoords[k] - xcoords[k + 1])\n    a2 = (dycoords[k] - a0 - a1) / ((xcoords[k] - xcoords[k + 1]) ** 2)\n    a3 = (dycoords[k + 1] - a0 - a1) / ((xcoords[k + 1] - xcoords[k]) ** 2)\n    nu0 = -a0 * xcoords[k] - a1 * xcoords[k + 1] - a2 * xcoords[k] * xcoords[k + 1] ** 2 - a3 * xcoords[k] ** 2 * \\\n          xcoords[k + 1]\n    nu1 = a0 + a1 + a2 * (xcoords[k + 1] ** 2 + 2 * xcoords[k + 1] * xcoords[k]) + a3 * (\n            xcoords[k] ** 2 + 2 * xcoords[k] * xcoords[k + 1])\n    nu2 = -a2 * (xcoords[k] + 2 * xcoords[k + 1]) - a3 * (xcoords[k + 1] + 2 * xcoords[k])\n    nu3 = a2 + a3\n    P = [nu0, nu1, nu2, nu3]\n    res.append(P)\nendSP = time.time()\nlengthSP = endSP - startSP\nstartSE = time.time()\nL = power_serie(f, n)\nendSE = time.time()\nlengthSE = endSE - startSE\nprint(\"-> Lagrange's length:\", lengthLH)\nprint(\"-> L'Hermite's length:\", lengthLT)\nprint(\"-> Cubic splines's length:\", lengthSP)\nprint(\"-> Power series's length\", lengthSE)\n", "meta": {"hexsha": "8793b0ebea484c743a090521709eda21319096d6", "size": 1948, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/time_comparison.py", "max_stars_repo_name": "LuluDavid/Polynomial_Interpolation", "max_stars_repo_head_hexsha": "d6d212615dbd4ce20a0120b249fe35373bfa3b71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/time_comparison.py", "max_issues_repo_name": "LuluDavid/Polynomial_Interpolation", "max_issues_repo_head_hexsha": "d6d212615dbd4ce20a0120b249fe35373bfa3b71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/time_comparison.py", "max_forks_repo_name": "LuluDavid/Polynomial_Interpolation", "max_forks_repo_head_hexsha": "d6d212615dbd4ce20a0120b249fe35373bfa3b71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7857142857, "max_line_length": 115, "alphanum_fraction": 0.5934291581, "include": true, "reason": "import numpy,from scipy", "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673109443157, "lm_q2_score": 0.9046505318875316, "lm_q1q2_score": 0.8708827404915759}}
{"text": "import numpy as np\nfrom helpers import sigmoid\n\n### Loss computing functions\n\n# Mean Square Error\ndef compute_mse(e):\n    return 1/2*np.mean(e**2)\n\n# Root Mean Square Error\ndef compute_rmse(e):\n    return np.sqrt(2 * compute_mse(e))\n\n# Mean Absolute Error\ndef compute_mae(e):\n    return np.mean(np.abs(e))\n\n\n# Computing loss for logistic regression\ndef compute_loss_log_reg(y, tx, w):\n    return -(y.T.dot(np.log(sigmoid(tx.dot(w)))) + (1 - y).T.dot(np.log(1 - sigmoid(tx.dot(w)))))\n\n\n# Computing loss with a selected cost function\ndef compute_loss(y, tx, w, func=\"mse\"):\n    # Computing error\n    error = y - tx.dot(w)\n\n    # Using Mean square error\n    if func == \"mse\":\n        return compute_mse(error)\n    \n    # Using Mean absolute error\n    elif func == \"mae\":\n        return compute_mae(error)\n    \n    # Using Root mean square error\n    elif func == \"rmse\":\n        return compute_rmse(error)", "meta": {"hexsha": "e38ac5c75fb1add35d5eeafdabf8459a86ea0028", "size": 901, "ext": "py", "lang": "Python", "max_stars_repo_path": "costs.py", "max_stars_repo_name": "mikanikos/MachineLearning_Project1", "max_stars_repo_head_hexsha": "994d9f09a8ffc7ee6379c918bfdc69c22ad38509", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "costs.py", "max_issues_repo_name": "mikanikos/MachineLearning_Project1", "max_issues_repo_head_hexsha": "994d9f09a8ffc7ee6379c918bfdc69c22ad38509", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "costs.py", "max_forks_repo_name": "mikanikos/MachineLearning_Project1", "max_forks_repo_head_hexsha": "994d9f09a8ffc7ee6379c918bfdc69c22ad38509", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1025641026, "max_line_length": 97, "alphanum_fraction": 0.6514983352, "include": true, "reason": "import numpy", "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9833429634078179, "lm_q2_score": 0.8856314828740729, "lm_q1q2_score": 0.870879486856651}}
{"text": "import math\nimport numpy as np\nimport numpy.linalg as la\n\na = np.array([1, 2, 3])\n\n# L¹, taxicab norm, manhattan norm\n# ‖v‖₁ = |a₁| + |a₂| + |a₃|\nb = la.norm(a, 1)\n\nprint(b)\nprint(b == a[0] + a[1] + a[2])\n\n\n# L², Euclidean norm\n# L²(v) = ‖v‖₂\nc = la.norm(a)\nprint(c)\nprint(c == la.norm(a, 2))\nprint(c == math.sqrt(\n    math.pow(a[0], 2)\n    + math.pow(a[1], 2)\n    + math.pow(a[2], 2)\n))\n\n# Max Norm\nd = la.norm(a, math.inf)\nprint(d)\nprint(d == max(a))", "meta": {"hexsha": "4cbdb1e93b4f2cd481142cfde9a608b2e2df96fa", "size": 452, "ext": "py", "lang": "Python", "max_stars_repo_path": "math/linear-algebra/np-9.py", "max_stars_repo_name": "admariner/playground", "max_stars_repo_head_hexsha": "02a3104472c8fa3589fe87f7265e70c61d5728c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-06-12T04:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T13:57:38.000Z", "max_issues_repo_path": "math/linear-algebra/np-9.py", "max_issues_repo_name": "admariner/playground", "max_issues_repo_head_hexsha": "02a3104472c8fa3589fe87f7265e70c61d5728c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/linear-algebra/np-9.py", "max_forks_repo_name": "admariner/playground", "max_forks_repo_head_hexsha": "02a3104472c8fa3589fe87f7265e70c61d5728c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-19T14:57:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T14:57:17.000Z", "avg_line_length": 15.5862068966, "max_line_length": 34, "alphanum_fraction": 0.5486725664, "include": true, "reason": "import numpy", "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9833429634078179, "lm_q2_score": 0.8856314723088733, "lm_q1q2_score": 0.8708794764674362}}
{"text": "'''\nLab 10: Leontieff Input-Output Models\nSolutions File\n'''\n\nimport numpy as np\nfrom scipy import linalg as la\n\ndef geomSeries(C, d, m):\n    '''\n    Calculate the geometric series of C up to the m power, multiplied by d.\n    Inputs:\n        C -- a (n,n) shape array\n        d -- a length n array\n        m -- a nonnegative integer\n    Return:\n        The value (\\sum_{i=0}^m C^i)d\n    '''\n    powC = C.copy()\n    sumC = np.eye(C.shape[0]) + powC\n    for k in xrange(m):\n        powC = C.dot(powC)\n        sumC += powC\n    return np.dot(sumC, d)\n\ndef construction():\n    '''\n    Calculate the cost vector for producing an additional 50% of construction.\n    Calculate an approximation by using geomSeries for m=5.\n    Then calculate the exact answer.\n    Return both answers, with the approximation first.\n    '''\n    IO = np. array ([[250. , 150. , 30. , 600.] , [25. , 25. , 20. , 280.] ,[50. , 20. , 5., 120.]])\n    IOCoeff = IO [: ,:3] / IO [: ,3]\n    d = np.array([0., 0., 60.0]) # a 50% increase over a baseline 120 means 60 additional units\n\n    return geomSeries(IOCoeff, d, 5), np.dot(la.inv(np.eye(IOCoeff.shape[0])-IOCoeff), d)\n\ndef demand():\n    '''\n    Calculate and return the demand vector for the three product economy.\n    '''\n    IO = np. array ([[250. , 150. , 30. , 600.] , [25. , 25. , 20., 280.] ,[50. , 20. , 5., 120.]])\n    IOCoeff = IO [: ,:3] / IO [: ,3]\n    X = np.array([600,280,120]) # this is the total output, as given in the lab\n\n    return X - np.dot(IOCoeff,X)\n\ndef cityOutput():\n    '''\n    Calculate and return the required output vector for the city, given the\n    demand vector.\n    '''\n    C = np.array([[.2,.3,.3],[.1,.2,.3],[.2,.2,.2]]) # IO coefficients\n    D = np.array([100000,100000,40000]) # demand vector\n    return np.dot(la.inv(np.eye(3)-C),D) # from the formula in the lab\n\ndef getIOCoeffs():\n    '''\n    Import the data from the csv file as described in the problem statement.\n    Calculate and return the IO coefficient matrix as well as the demand vector.\n    Return both of these values, the matrix first, and then the vector.\n    '''\n    data = np.genfromtxt(\"io2002table.txt\", delimiter='\\t', skiprows=1,\n                         usecols=np.arange(1,52), missing_values = [''],\n                         filling_values={i:0 for i in xrange(1,52)})\n    iocoeff = data[:,:-1] / data[:,-1]\n    X = data[:,-1] # this is the last column, which corresponds to total output\n    D = X - np.dot(iocoeff, X) # this is our demand vector\n    return iocoeff, D\n\n\ndef washingtonOutput(iocoeffs, demand):\n    '''\n    Calculate the output vector corresponding to an increase of 10% in the demand\n    for construction.\n    Inputs:\n        iocoeffs -- the input-output coefficient matrix for the Washington economy, as\n                    calculated in the getIOCoeffs function.\n        demand -- the demand vector for the Washington economy, as calculated in the\n                  getIOCoeffs function.\n    Return:\n        The output vector corresponding to an increase of 10% in the construction demand.\n    '''\n    # now increase the construction demand by 10% (entry 8)\n    demand[8] += demand[8]*.10\n    # now calculate the new output vector corresponding to this demand:\n    return la.solve(np.eye(iocoeffs.shape[0]) - iocoeffs, demand)\n", "meta": {"hexsha": "fd3277fd0f6f56b10077004ec4442f173ed44084", "size": 3280, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/Leontief/leontief_solutions.py", "max_stars_repo_name": "jessicaleete/numerical_computing", "max_stars_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-10-18T19:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:12:38.000Z", "max_issues_repo_path": "Labs/Leontief/leontief_solutions.py", "max_issues_repo_name": "jessicaleete/numerical_computing", "max_issues_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/Leontief/leontief_solutions.py", "max_forks_repo_name": "jessicaleete/numerical_computing", "max_forks_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-14T16:07:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-20T09:05:06.000Z", "avg_line_length": 36.8539325843, "max_line_length": 100, "alphanum_fraction": 0.6140243902, "include": true, "reason": "import numpy,from scipy", "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502202, "lm_q2_score": 0.9184802479302793, "lm_q1q2_score": 0.8708612108677285}}
{"text": "import sample_images\nimport random\nimport display_network\nimport numpy as np\n\n\n##================================================================\n## Step 0a: Load data\n#  Here we provide the code to load natural image data into x.\n#  x will be a 144 * 10000 matrix, where the kth column x(:, k) corresponds to\n#  the raw image data from the kth 12x12 image patch sampled.\n#  You do not need to change the code below.\n\npatches = sample_images.sample_images_raw()\nnum_samples = patches.shape[1]\nrandom_sel = random.sample(range(num_samples), 400)\ndisplay_network.display_network(patches[:, random_sel], 'raw_pca.png')\n\n##================================================================\n## Step 0b: Zero-mean the data (by row)\n#  You can make use of the mean and repmat/bsxfun functions.\n\n# patches = patches - patches.mean(axis=0)\npatch_mean = patches.mean(axis=1)\npatches = patches - np.tile(patch_mean, (patches.shape[1], 1)).transpose()\n\n##================================================================\n## Step 1a: Implement PCA to obtain xRot\n#  Implement PCA to obtain xRot, the matrix in which the data is expressed\n#  with respect to the eigenbasis of sigma, which is the matrix U.\n\nsigma = patches.dot(patches.transpose()) / patches.shape[1]\n(u, s, v) = np.linalg.svd(sigma)\n\npatches_rot = u.transpose().dot(patches)\n\n##================================================================\n## Step 2: Find k, the number of components to retain\n#  Write code to determine k, the number of components to retain in order\n#  to retain at least 99% of the variance.\n\nk = 0\nfor k in range(s.shape[0]):\n    if s[0:k].sum() / s.sum() >= 0.99:\n        break\nprint('Optimal k to retain 99% variance is:', k)\n\n##================================================================\n## Step 3: Implement PCA with dimension reduction\n#  Now that you have found k, you can reduce the dimension of the data by\n#  discarding the remaining dimensions. In this way, you can represent the\n#  data in k dimensions instead of the original 144, which will save you\n#  computational time when running learning algorithms on the reduced\n#  representation.\n# \n#  Following the dimension reduction, invert the PCA transformation to produce \n#  the matrix xHat, the dimension-reduced data with respect to the original basis.\n#  Visualise the data and compare it to the raw data. You will observe that\n#  there is little loss due to throwing away the principal components that\n#  correspond to dimensions with low variation.\n\npatches_tilde = u[:, 0:k].transpose().dot(patches)\npatches_hat = u.dot(np.resize(patches_tilde, patches.shape))\n\ndisplay_network.display_network(patches_hat[:, random_sel], 'pca_tilde.png')\ndisplay_network.display_network(patches[:, random_sel], 'pca.png')\n\n##================================================================\n## Step 4a: Implement PCA with whitening and regularisation\n#  Implement PCA with whitening and regularisation to produce the matrix\n#  xPCAWhite.\n\nepsilon = 0.1\npatches_pcawhite = np.diag(1 / (s + epsilon)).dot(patches_rot)\n\n\n##================================================================\n## Step 5: Implement ZCA whitening\n#  Now implement ZCA whitening to produce the matrix xZCAWhite.\n#  Visualise the data and compare it to the raw data. You should observe\n#  that whitening results in, among other things, enhanced edges.\n\npatches_zcawhite = u.dot(patches_pcawhite)\ndisplay_network.display_network(patches_zcawhite[:, random_sel], 'pca_zcawhite.png')\n", "meta": {"hexsha": "a9f2bae368cd0fc0908a5b2ae0021e3bdd009529", "size": 3482, "ext": "py", "lang": "Python", "max_stars_repo_path": "used/unused/pca_gen.py", "max_stars_repo_name": "shifvb/GraduationProject", "max_stars_repo_head_hexsha": "08166b49c329014bf852faafa14db14a6231370a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-04-27T15:25:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-27T15:25:01.000Z", "max_issues_repo_path": "used/unused/pca_gen.py", "max_issues_repo_name": "shifvb/Undergraduate_GraduationProject", "max_issues_repo_head_hexsha": "08166b49c329014bf852faafa14db14a6231370a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "used/unused/pca_gen.py", "max_forks_repo_name": "shifvb/Undergraduate_GraduationProject", "max_forks_repo_head_hexsha": "08166b49c329014bf852faafa14db14a6231370a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9647058824, "max_line_length": 84, "alphanum_fraction": 0.6493394601, "include": true, "reason": "import numpy", "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.914900957313305, "lm_q1q2_score": 0.870860575588747}}
{"text": "# Practicing Dynamic Programming (DP) with the log cutting problem given on the practice midterm.\r\nimport numpy as np\r\n\r\n\r\n################################################################################\r\n# Slow Algorithm\r\n################################################################################\r\n\r\n\r\ndef cut_log(d, j, k):\r\n    if j+1 == k:\r\n        return 0\r\n    c = float('Inf')\r\n    for i in range(j+1, k):\r\n        c = min(c, d[k] + cut_log(d, j, i) + cut_log(d - d[i], i, k))\r\n    return c\r\n\r\n\r\n################################################################################\r\n# Top Down Algorithm\r\n################################################################################\r\n\r\n\r\ndef memoized_cut_log(d):\r\n    k = len(d)\r\n    j = 0\r\n    r = np.ones([k, k])*np.inf\r\n    v = memoized_cut_log_aux(d, j, k-1, r)\r\n    return v\r\n\r\n\r\ndef memoized_cut_log_aux(d, j, k, r):\r\n    if r[j, k] < np.inf:\r\n        return r[j, k]\r\n    if j+1 == k:\r\n        r[j, k] = 0\r\n    else:\r\n        c = float('Inf')\r\n        for i in range(j+1, k):\r\n            c = min(c, d[k] + memoized_cut_log_aux(d, j, i, r) + memoized_cut_log_aux(d - d[i], i, k, r))\r\n        r[j, k] = c\r\n    return r[j, k]\r\n\r\n\r\n################################################################################\r\n# Bottom Up Algorithm\r\n################################################################################\r\n\r\n\r\n# def bottom_up_cut_log(d):\r\n#     k = len(d)\r\n#     r = np.zeros([k, k])\r\n#     for i in range(2, k):\r\n#         c = np.inf\r\n#         for j in range(1, i):\r\n#             c = min(c, d[i] + r[j, i-1] + r[j-1, i])\r\n#         r[j, i] = c\r\n#     print(r)\r\n#     return r[0, k-1]\r\n\r\n\r\n################################################################################\r\n# Main\r\n################################################################################\r\nif __name__ == '__main__':\r\n    dist = np.array([0, 3, 8, 10])\r\n    print(\"min cost (slow) = $\" + str(cut_log(dist, 0, 3)))\r\n    print(\"min cost (top down) = $\" + str(memoized_cut_log(dist)))\r\n    # print(\"min cost (slow) = $\" + str(bottom_up_cut_log(dist)))\r\n", "meta": {"hexsha": "bfe8892201d79b3849d2b6abf9e20e3c611a77f5", "size": 2100, "ext": "py", "lang": "Python", "max_stars_repo_path": "DP/LogCutting/LogCutting.py", "max_stars_repo_name": "nalyd88/Algorithms", "max_stars_repo_head_hexsha": "63ec18288b3e89f3b96bcbed70080cf33f9a115d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DP/LogCutting/LogCutting.py", "max_issues_repo_name": "nalyd88/Algorithms", "max_issues_repo_head_hexsha": "63ec18288b3e89f3b96bcbed70080cf33f9a115d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DP/LogCutting/LogCutting.py", "max_forks_repo_name": "nalyd88/Algorithms", "max_forks_repo_head_hexsha": "63ec18288b3e89f3b96bcbed70080cf33f9a115d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0, "max_line_length": 106, "alphanum_fraction": 0.3357142857, "include": true, "reason": "import numpy", "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632275178341, "lm_q2_score": 0.9149009538328171, "lm_q1q2_score": 0.8708605747744502}}
{"text": "import numpy as np\n\nEPS = np.finfo(np.float32).eps\n\n\ndef log_loss(\n        y_hat: np.ndarray,\n        y: np.ndarray\n) -> float:\n    \"\"\"\n    Log-loss cost function.\n    \n    :param y_hat: Predicted value (scaled [0, 1])\n    :param y: Label value (i.e., ground-truth)\n    :return: loss value\n    \"\"\"\n    is_one = y * np.log(y_hat)\n    is_zero = (1.0 - y) * np.log(1.0 - y_hat)\n    loss = -(is_one + is_zero).mean()\n    return loss\n\n\ndef mean_squared_error(\n        y_hat: np.ndarray,\n        y: np.ndarray\n) -> float:\n    \"\"\"\n    Mean-squared-error cost function.\n    \n    :param y_hat: Predicted value (scaled [0, 1])\n    :param y: Label value (i.e., ground-truth)\n    :return: loss value\n    \"\"\"\n    error = y - y_hat\n    squared_error = error ** 2\n    mse = squared_error.mean()\n    return mse\n", "meta": {"hexsha": "0e3ed55c9d03b41d5a0951249be2fd1044d9993c", "size": 795, "ext": "py", "lang": "Python", "max_stars_repo_path": "hand_crafted_models/loss_functions.py", "max_stars_repo_name": "sadighian/hand_crafted_models", "max_stars_repo_head_hexsha": "aea75892ea183bc0f7f10781400c5d47de078e5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-08-24T19:03:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T04:17:07.000Z", "max_issues_repo_path": "hand_crafted_models/loss_functions.py", "max_issues_repo_name": "sadighian/hand_crafted_models", "max_issues_repo_head_hexsha": "aea75892ea183bc0f7f10781400c5d47de078e5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hand_crafted_models/loss_functions.py", "max_forks_repo_name": "sadighian/hand_crafted_models", "max_forks_repo_head_hexsha": "aea75892ea183bc0f7f10781400c5d47de078e5e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9210526316, "max_line_length": 49, "alphanum_fraction": 0.572327044, "include": true, "reason": "import numpy", "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.973240718366854, "lm_q2_score": 0.8947894675053568, "lm_q1q2_score": 0.8708455441420082}}
{"text": "# # Simple ReLU\n# inputs = [0, 2, -1, 3.3, -2.7, 1.1, 2.2, -100]\n\n# output = []\n# for i in inputs:\n#     # if i > 0:\n#     #     output.append(i)\n#     # else:\n#     #     output.append(0)\n#     output.append(max(0, i))\n\n\n# print(output)\n\n\n# # In NumPY\n# import numpy as np\n\n# inputs = [0, 2, -1, 3.3, -2.7, 1.1, 2.2, -100]\n# output = np.maximum(0, inputs)\n# print(output)\n\n\n# # Softmax\n# # Values from the previous output when we described\n# # what a neural network is\n# layer_outputs = [4.8, 1.21, 2.385]\n\n# # e - mathematical constant, we use E here to match a common coding\n# # style where constants are uppercased\n# E = 2.71828182846  # you can also use math.e\n\n# # For each value in a vector, calculate the exponential value\n# exp_values = []\n# for output in layer_outputs:\n#     exp_values.append(E ** output)  # ** - power operator in Python\n# print(\"exponentiated values:\")\n# print(exp_values)\n\n# # Now normalize values\n# norm_base = sum(exp_values)  # We sum all values\n# norm_values = []\n# for value in exp_values:\n#     norm_values.append(value / norm_base)\n# print(\"Normalized exponentiated values:\")\n# print(norm_values)\n\n# print(\"Sum of normalized values:\", sum(norm_values))\n\n\n# # And in NumPy\n# import numpy as np\n\n# # Values from the earlier previous when we described\n# # what a neural network is\n\n# layer_outputs = [4.8, 1.21, 2.385]\n\n# # For each value in a vector, calculate the exponential value\n# exp_values = np.exp(layer_outputs)\n# print(\"exponentiated values:\")\n# print(exp_values)\n\n# # Now normalize values\n# norm_values = exp_values / np.sum(exp_values)\n# print(\"normalized exponentiated values:\")\n# print(norm_values)\n# print(\"sum of normalized values:\", np.sum(norm_values))\n\n\n# Axis and keepdims\nimport numpy as np\n\nlayer_outputs = np.array([[4.8, 1.21, 2.385], [8.9, -1.81, 0.2], [1.41, 1.051, 0.026]])\n\nprint(\"Sum without axis\")\nprint(np.sum(layer_outputs))\n\nprint(\"This will be identical to the above since default is None:\")\nprint(np.sum(layer_outputs, axis=None))\n\nprint(\"Another way to think of it w/ a matrix == axis 0: columns:\")\nprint(np.sum(layer_outputs, axis=0))\n\nprint(\"But we want to sum the rows instead, like this w/ raw py:\")\nfor i in layer_outputs:\n    print(sum(i))\n\nprint(\"So we can sum axis 1, but note the current shape:\")\nprint(np.sum(layer_outputs, axis=1))\n\nprint(\"Sum axis 1, but keep the same dimensions as input:\")\nprint(np.sum(layer_outputs, axis=1, keepdims=True))\n", "meta": {"hexsha": "074d9a540a2898968180b86ae36314f0388009c4", "size": 2427, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapters/4-activation-functions/exmaples.py", "max_stars_repo_name": "alvarlagerlof/nnfs", "max_stars_repo_head_hexsha": "5d6118b12e459af17db46700b1c3322d4278e4cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/4-activation-functions/exmaples.py", "max_issues_repo_name": "alvarlagerlof/nnfs", "max_issues_repo_head_hexsha": "5d6118b12e459af17db46700b1c3322d4278e4cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/4-activation-functions/exmaples.py", "max_forks_repo_name": "alvarlagerlof/nnfs", "max_forks_repo_head_hexsha": "5d6118b12e459af17db46700b1c3322d4278e4cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8191489362, "max_line_length": 87, "alphanum_fraction": 0.6753193243, "include": true, "reason": "import numpy", "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.9273632966504672, "lm_q1q2_score": 0.8708171503272243}}
{"text": "\"\"\"\nhttps://projecteuler.net/problem=3\nThe prime factors of 13195 are 5, 7, 13 and 29.\n\nWhat is the largest prime factor of the number 600851475143 ?\n\"\"\"\n\nfrom numpy import sqrt\n\nfrom Common.Logger import get_logger, init_logger\nfrom Common.Primes import sieve_of_atkin\nfrom Common.Utilities import performance_run\n\nNUMBER = 600_851_475_143\nPERFORMANCE_RUNS = 1000\n\n\ndef fastest(number: int = NUMBER) -> int:\n    \"\"\"\n    This algorithm counts up from 1 to sqrt(number), factorizing the number along the way\n    :param number: The number of which this function will find the greatest prime factor\n    :return:\n    \"\"\"\n    return reduction(number)\n\n\ndef reduction(number: int = NUMBER) -> int:\n    \"\"\"\n    This algorithm counts up from 1 to sqrt(number), factorizing the number along the way\n    --> benchmark: 56672789 ns/run (over 1000 runs)\n    --> benchmark: 59520400 ns/run (over 1 run)\n    :param number: The number which this function will find the greatest prime factor\n    :return: The greatest prime factor\n    \"\"\"\n    largest_prime = 1\n    for i in range(2, int(sqrt(number) + 1)):\n        while number % i == 0:\n            largest_prime = i\n            number = number/i\n    return largest_prime if largest_prime != 1 else number\n\n\ndef cached_sieve(number: int = NUMBER) -> int:\n    \"\"\"\n    This algorithm utilizes the Sieve of Atkin (the ~fastest~ prime sieve on the market) to generate a full list of\n    primes up to sqrt(number). It then works its way backward in the list to see what the first prime factor is. The\n    Primes library utilizes functools.lru_caching to avoid having to repeat calculations at runtime, so that skews the\n    performance of this algorithm. Checking only once takes ~50x longer than each additional check.\n    For fastest(), we'll select the method of reduction due to this behavior, as I don't really care to more-permanently\n    cache a long list of primes. That said, long live the cache.\n    --> benchmark:   9038529 ns/run (over 1000 runs)\n    --> benchmark: 463035900 ns/run (over 1 run)\n    :param number: The number which this function will find the greatest prime factor\n    :return: The greatest prime factor\n    \"\"\"\n    primes = sieve_of_atkin(int(sqrt(number)))\n    for i in range(1, len(primes)):\n        if number % primes[-i] == 0:\n            return primes[-i]\n    return number\n\n\nif __name__ == \"__main__\":\n    # Log stuff\n    init_logger()\n    logger = get_logger()\n\n    # Performance run for the reductive \"bottoms-up\" solution and cached sieve \"top-down\" solution\n    # performance_run(reduction, iterations=PERFORMANCE_RUNS)()\n    # performance_run(cached_sieve, iterations=PERFORMANCE_RUNS)()\n    print(fastest(NUMBER))\n", "meta": {"hexsha": "25d36abde82e605a2af8e4dc2118eed958f61519", "size": 2686, "ext": "py", "lang": "Python", "max_stars_repo_path": "Solutions/Q0003_Largest_Prime_Factor.py", "max_stars_repo_name": "SigfriedHache/euler-project", "max_stars_repo_head_hexsha": "7c38deee65a793a441830a6d0916da61e86b8cf7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Solutions/Q0003_Largest_Prime_Factor.py", "max_issues_repo_name": "SigfriedHache/euler-project", "max_issues_repo_head_hexsha": "7c38deee65a793a441830a6d0916da61e86b8cf7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/Q0003_Largest_Prime_Factor.py", "max_forks_repo_name": "SigfriedHache/euler-project", "max_forks_repo_head_hexsha": "7c38deee65a793a441830a6d0916da61e86b8cf7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3055555556, "max_line_length": 120, "alphanum_fraction": 0.7040208488, "include": true, "reason": "from numpy", "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.9273632906279589, "lm_q1q2_score": 0.8708171415070379}}
{"text": "# Consider a child waiting at a street corner for a gap in traffic that is large enough so that he can safely cross the street.\n# A mathematical model for traffic shows that if the expected waiting time for the child is to be at most 1​ minute, then the maximum traffic​ flow, in cars per​ hour, is given by\n# f(x) = 29,403( 2.335 - log( x ) ) / x, where x is the width of the street in feet.\n\nfrom sympy import *\n\ninit_printing()\n\ndef disp_fun( f ):\n\tpprint( '\\n{0}\\n\\n'.format( pretty( f ) ) )\n\nx = symbols( 'x' )\n\nfX = 29403 * ( 2.335 - log( x, 10 ) )  / x\ndX = diff( fX, x )\n\nsimplify( dX )\n\n# Find the maximum traffic flow and the rate of change of the maximum traffic flow with respect to street width for the street width of 35 feet.\n# (Do not round until the final answer. Then round to the nearest integer as​ needed.)\nround( fX.subs( { x: 35 } ).evalf(), 0 )\n\n# The rate of change of the maximum traffic flow is about X vehicles per hour per foot.\n# ​(Do not round until the final answer. Then round to the nearest tenth as​ needed.)\nround( dX.subs( { x: 35 } ).evalf(), 1 )\n\n\n# Find the maximum traffic flow and the rate of change of the maximum traffic flow with respect to street width for the street width of 54 feet.\n# (Do not round until the final answer. Then round to the nearest integer as​ needed.)\nround( fX.subs( { x: 54 } ).evalf(), 0 )\n\n# The rate of change of the maximum traffic flow is about X vehicles per hour per foot.\n# ​(Do not round until the final answer. Then round to the nearest tenth as​ needed.)\nround( dX.subs( { x: 54 } ).evalf(), 1 )", "meta": {"hexsha": "9996077e442162af2bee6a19f717fa80c9832591", "size": 1575, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Module 5/traffic_flow.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Module 5/traffic_flow.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Module 5/traffic_flow.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.3235294118, "max_line_length": 179, "alphanum_fraction": 0.6971428571, "include": true, "reason": "from sympy", "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620562254525, "lm_q2_score": 0.9073122219871936, "lm_q1q2_score": 0.8708038438129132}}
{"text": "import numpy as np\nimport scipy\n\ndef variance(sample):\n    \"\"\"\n    Calculate variance of a sample. After learn.co\n    \"\"\"\n    sample_mean = np.mean(sample)\n    return sum([(i - sample_mean)**2 for i in sample])\n\ndef sample_variance(sample1, sample2):\n    \"\"\"\n    Calculate sample variance. After learn.co\n    \"\"\"\n    n_1, n_2 = len(sample1), len(sample2)\n    var_1, var_2 = variance(sample1), variance(sample2)\n    return (var_1 + var_2)/((n_1 + n_2)-2)\n\ndef twosample_tstatistic(sample1, sample2):\n    exp_mean, sample2_mean = np.mean(sample1), np.mean(sample2)\n    samp_var = sample_variance(sample1, sample2)\n    n_e, n_c = len(sample1), len(sample2)\n    num = exp_mean - sample2_mean\n    denom = np.sqrt(samp_var * ((1/n_e)+(1/n_c)))\n    return num / denom\n\ndef one_sample_ttest(sample, popmean, alpha):\n    \"\"\"Calculate t-value and p-value and return each\"\"\"\n    \n    # Population  \n    mu = popmean\n    \n    # Sample mean (x̄) using NumPy mean()\n    sample_mean = np.mean(sample)\n    \n    # Sample Stadard Deviation (sigma) using Numpy\n    sample_std = np.std(sample, ddof=1)\n    \n    # Degrees of freedom\n    degrees_freedom = len(sample) - 1\n    \n    \n    #Calculate the critical t-value\n    t_crit = scipy.stats.t.ppf(1-alpha, df=degrees_freedom)\n    \n    #Calculate the t-value and p-value      \n    t_val, p_val = scipy.stats.ttest_1samp(a=sample, popmean=mu)\n    \n    #return results\n    #if t-value is greater than t-critical than you can reject the null hypothesis\n    #if p-value is less than alpha than you can reject the null hypothesis\n    if t_val > t_crit and p_val < alpha:\n        print(\"Null Hypothesis rejected. \", \"t-value: \", t_val, \"p-value: \", p_val)\n    else:\n        print(\"Null Hypothesis true. \", \"t-value: \", t_val, \"p-value: \", p_val)\n    return t_val, p_val \n\ndef cohen_d(group1, group2):\n    \"\"\"\n    For two groups' samples, calculate Cohen's D\n    group1: Series or NumPy array\n    group2: Series or NumPy array\n    After Learn.co\n    \"\"\"\n    # returns a floating point number \n\n    diff = group1.mean() - group2.mean()\n\n    n1, n2 = len(group1), len(group2)\n    var1 = group1.var()\n    var2 = group2.var()\n\n    # Calculate the pooled threshold as shown earlier\n    pooled_var = (n1 * var1 + n2 * var2) / (n1 + n2)\n    \n    # Calculate Cohen's d statistic\n    d = diff / np.sqrt(pooled_var)\n    \n    return d", "meta": {"hexsha": "a0c54a1c65aad40aeecac42b48f4f156e5478b50", "size": 2345, "ext": "py", "lang": "Python", "max_stars_repo_path": "custom.py", "max_stars_repo_name": "MangrobanGit/dsc-2-final-project", "max_stars_repo_head_hexsha": "5d6a91b989dd392a17f0438aaffa6f577b90e7e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "custom.py", "max_issues_repo_name": "MangrobanGit/dsc-2-final-project", "max_issues_repo_head_hexsha": "5d6a91b989dd392a17f0438aaffa6f577b90e7e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-05-07T15:43:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-09T00:56:38.000Z", "max_forks_repo_path": "custom.py", "max_forks_repo_name": "MangrobanGit/dsc-2-final-project", "max_forks_repo_head_hexsha": "5d6a91b989dd392a17f0438aaffa6f577b90e7e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-06T17:38:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-06T17:38:59.000Z", "avg_line_length": 29.6835443038, "max_line_length": 83, "alphanum_fraction": 0.6396588486, "include": true, "reason": "import numpy,import scipy", "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639677785087, "lm_q2_score": 0.8962513745192024, "lm_q1q2_score": 0.8707655415548186}}
{"text": "from numpy import *\n\n\n\ndef f(u,beta,gamma):\n    \n    dSdt = - beta * u[0] * u[1]\n    dRdt =                        gamma * u[1]\n    dIdt =   -dSdt - dRdt\n    \n    return array([dSdt,dIdt,dRdt])\n \ndef check(Ustart):\n    if type(Ustart) == list :\n        return array(Ustart)\n    else :\n        return Ustart\n    \n\n# -------------------------------------------------------------------------    \n#\n# -2- Schema de d'Euler explicite d'ordre 1\n#\n  \ndef epidemicEuler(Xstart,Xend,Ustart,n,beta,gamma):\n    X, h = linspace(Xstart,Xend,n+1, retstep = True)\n    Ustart = check(Ustart)\n    \n    U = zeros((len(X), 3))\n    U[0] = Ustart\n    \n    for i in range(len(X) -1):\n        U[i+1] = U[i] + h*f(U[i],beta,gamma)\n\n    return X,U\n \n\n# -------------------------------------------------------------------------    \n#\n# -2- Schema de Taylor classique d'ordre 4\n# \n  \ndef epidemicTaylor(Xstart,Xend,Ustart,n,beta,gamma):\n    X,h = linspace(Xstart,Xend,n+1, retstep = True)\n    Ustart = check(Ustart)\n    \n    U = zeros((len(X), 3))\n    U[0] = Ustart\n    \n    multiplicator = array([h, (h**2)/2, (h**3)/6, (h**4)/24])\n    for i in range(len(X)-1) :\n    \n        s0, i0, r0 = U[i]\n        s1, i1, r1 = f(U[i], beta,gamma)\n        s2, r2 = -beta*(s1*i0 + i1*s0), gamma*i1\n        i2 = -(s2 + r2)\n        s3, r3 = -beta*(s2*i0 + 2*s1*i1 + i2*s0), gamma*i2\n        i3 = -(s3+r3)\n        s4, r4 = -beta*(s3*i0 + 3*s2*i1 + 3*s1*i2 + s0*i3), gamma*i3\n        i4 = -(s4 + r4)\n                \n        U[i+1] = U[i] + (multiplicator @ array([[s1,i1,r1],[s2,i2,r2],[s3,i3,r3],[s4,i4,r4]]))\n\n    return X,U\n\n# -------------------------------------------------------------------------    \n#\n# -3- Schema de Runge-Kutta d'ordre 4\n# \n  \ndef epidemicRungeKutta(Xstart,Xend,Ustart,n,beta,gamma):\n    X,h = linspace(Xstart,Xend,n+1, retstep = True)\n    Ustart = check(Ustart)\n    \n    U = zeros((len(X), 3))\n    U[0] = Ustart\n    \n    for i in range(len(X)-1):\n        K1 = f(U[i], beta, gamma)\n        K2 = f(U[i] + (h/2)*K1,beta,gamma)\n        K3 = f(U[i] + (h/2)*K2,beta,gamma) \n        K4 = f(U[i] + h*K3,beta,gamma)\n        \n        U[i+1] = U[i] + (h/6)*(K1 + 2*K2 + 2*K3 + K4)\n    \n    \n    return X,U\n\n", "meta": {"hexsha": "f1c22467c18d88aa0717c5b87de1e7dd1b478bec", "size": 2181, "ext": "py", "lang": "Python", "max_stars_repo_path": "Devoir 7/epidemic.py", "max_stars_repo_name": "MonkD3/Devoirs-Methode-Num", "max_stars_repo_head_hexsha": "47ae18446a70ae6f21577403a2c12ae13f9822ac", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Devoir 7/epidemic.py", "max_issues_repo_name": "MonkD3/Devoirs-Methode-Num", "max_issues_repo_head_hexsha": "47ae18446a70ae6f21577403a2c12ae13f9822ac", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Devoir 7/epidemic.py", "max_forks_repo_name": "MonkD3/Devoirs-Methode-Num", "max_forks_repo_head_hexsha": "47ae18446a70ae6f21577403a2c12ae13f9822ac", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5056179775, "max_line_length": 94, "alphanum_fraction": 0.4378725355, "include": true, "reason": "from numpy", "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140235181257, "lm_q2_score": 0.9005297907896396, "lm_q1q2_score": 0.8707348833103464}}
{"text": "import numpy as np\nfrom numpy import pi\nimport matplotlib.pyplot as plt\n\n#\n# define a wavelength going from 0 to 2pi\n#\nthetime=np.arange(0.,2*pi,0.05)\nthewave=thetime/(2.*pi)\n#\n# phase shifts\n#\nthirty=30.*pi/180.\nsixty=2.*thirty\nninety=3.*thirty\nonetwenty=2.*sixty\noneeighty=3.*sixty\n\nfig1,axis1=plt.subplots(1,1)\n#\n# add phase shifts and plot cosine\n#\naxis1.plot(thewave,np.cos(thetime),'b-',label='0')\naxis1.plot(thewave,np.cos(thetime + thirty),'c-',label='30')\naxis1.plot(thewave,np.cos(thetime + sixty),'g-',label='60')\naxis1.plot(thewave,np.cos(thetime + ninety),'k-',label='90')\naxis1.plot(thewave,np.cos(thetime + onetwenty),'m-',label='120')\naxis1.plot(thewave,np.cos(thetime + oneeighty),'r-',label='180')\naxis1.set_xlabel('horizontal position (in wavelengths)')\naxis1.set_ylabel('amplitude')\naxis1.set_title('cosine waves for 5 phase shifts')\naxis1.legend(loc='best')\nfig1.savefig('cosine_plot.png')\n#\n# add phase shifts and plot sines\n#\nfig2,axis2=plt.subplots(1,1)\naxis2.plot(thewave,np.cos(thetime),'b-',label='0')\naxis2.plot(thewave,np.cos(thetime + thirty),'c-',label='30')\naxis2.plot(thewave,np.cos(thetime + sixty),'g-',label='60')\naxis2.plot(thewave,np.cos(thetime + ninety),'k-',label='90')\naxis2.plot(thewave,np.cos(thetime + onetwenty),'m-',label='120')\naxis2.plot(thewave,np.cos(thetime + oneeighty),'r-',label='180')\naxis2.set_xlabel('horizontal position (in wavelengths)')\naxis2.set_ylabel('amplitude')\naxis2.set_title('sine waves for 5 phase shifts')\naxis2.legend(loc='best')\nfig2.savefig('sine_plot.png')\n\n#\n# make a reflection at 0.75 wavelengths\n#\nfig3,axis3=plt.subplots(1,1)\nline1=axis3.plot(thewave,np.cos(thetime),'b-')\nnewX=thetime\n#zero out the inital wave so it looks like a reflection\nnewX[newX > 0.75*2.*pi]=np.nan\n#\n#  add a pi phase shift\n#\nnewX = newX + pi\nline2=axis3.plot(thewave,np.cos(newX),'r-')\naxis3.set_xlabel('horizontal position (in wavelengths)')\naxis3.set_ylabel('amplitude at receiver')\naxis3.set_title('phase shift for a reflection occuring at 0.75 wavelengths')\naxis3.legend((line1[0],line2[0]),('first pulse reflected at 1 wavelength','second pulse reflected at 3/4 wavelength'))\nfig3.savefig('reflection_plot.png')\n\nplt.show()\n", "meta": {"hexsha": "a4fee750484677c2c5a125c34b1aa3c36cb558b2", "size": 2185, "ext": "py", "lang": "Python", "max_stars_repo_path": "a301/scripts/phaseshift.py", "max_stars_repo_name": "Pearl-Ayem/ATSC_Notebook_Data", "max_stars_repo_head_hexsha": "c075d166c235ac4e68a4b77750e02b2a5e77abd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "a301/scripts/phaseshift.py", "max_issues_repo_name": "Pearl-Ayem/ATSC_Notebook_Data", "max_issues_repo_head_hexsha": "c075d166c235ac4e68a4b77750e02b2a5e77abd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "a301/scripts/phaseshift.py", "max_forks_repo_name": "Pearl-Ayem/ATSC_Notebook_Data", "max_forks_repo_head_hexsha": "c075d166c235ac4e68a4b77750e02b2a5e77abd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2142857143, "max_line_length": 118, "alphanum_fraction": 0.7308924485, "include": true, "reason": "import numpy,from numpy", "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811641488385, "lm_q2_score": 0.9019206798249232, "lm_q1q2_score": 0.8706972358592961}}
{"text": "\"\"\"\nImplementation of the steepest gradient descent and Newton \nmethod.\n\"\"\"\nfrom __future__ import annotations\n\nimport numpy as np\n\nfrom numpy import Inf\nfrom numpy.linalg import inv\n\n# Himmelblau's function\nf = lambda x: (x[0]**2+x[1]-11)**2 + (x[0]+x[1]**2-7)**2\n# Gradient\ndf_dx = lambda x: 2*(x[0]**2+x[1]-11)*2*x[0] + 2*(x[0]+x[1]**2-7)\ndf_dy = lambda x: 2*(x[0]**2+x[1]-11) + 2*(x[0]+x[1]**2-7)*2*x[1]\n# Hessian\nd2f_dx2 = lambda x: 8*x[0]**2 + 4*(x[0]**2+x[1]-11) + 2\nd2f_dxy = lambda x: 4*x[0] + 4*x[1]\nd2f_dyx = lambda x: 4*x[0] + 4*x[1]\nd2f_dy2 = lambda x: 2 + 8*x[1]**2 + 4*(x[0]+x[1]**2-7)\n\ndef himmelblau(params: list[float]) -> float:\n    return (params[0]**2+params[1]-11)**2 + (params[0]+params[1]**2-7)**2\n\ndef gradient_q(params: list[float]):\n    return np.array([df_dx(params), df_dy(params)])\n\ndef hessian_q(params: list[float]):\n    return np.array(\n            [[d2f_dx2(params), d2f_dxy(params)],\n            [d2f_dyx(params), d2f_dy2(params)]]\n            )\n\ndef newton_search_direction(x: np.ndarray) -> np.ndarray:\n    return np.dot(inv(hessian_q(x)), gradient_q(x))\n\ndef gradient_search_direction(x: np.ndarray) -> np.ndarray:\n    return gradient_q(x)\n\ndef find_minimum(\n    starting_pos: list[float], \n    beta: float, \n    max_iters: float,\n    d: function, \n    epsilon: float=10e-12\n    ) -> list[float]:\n\n    x = np.array(starting_pos, dtype='double')\n    step = len(starting_pos)*[Inf]\n    iter = 0\n    visited_points = [x.copy()]\n    while iter < max_iters and not np.allclose(step, np.zeros(len(step)), atol=epsilon):\n        step = beta*d(x)\n        x -= step\n        # print(f\"Iter: {iter}, Step: {step}, x = {x}\")\n        iter += 1\n        visited_points.append(x.copy())\n    return x, visited_points\n\ndef main() -> int:\n    X = [0., 0]\n    beta = 0.001\n    max_iters = 10000\n    print('Gradient: Minimum found at ', find_minimum(X, beta, max_iters, gradient_search_direction)[0])\n    print('Newton: Minimum found at ', find_minimum(X, beta, max_iters, newton_search_direction)[0])\n    return 0\n\nif __name__ == \"__main__\":\n    raise SystemExit(main())", "meta": {"hexsha": "7d5cd97be4630b690803c29e14ed00c626c1a708", "size": 2088, "ext": "py", "lang": "Python", "max_stars_repo_path": "wsi_1/methods.py", "max_stars_repo_name": "hornisslaw/wsi", "max_stars_repo_head_hexsha": "a58c055109b7b16238817a5e4d9d01c6b845af0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wsi_1/methods.py", "max_issues_repo_name": "hornisslaw/wsi", "max_issues_repo_head_hexsha": "a58c055109b7b16238817a5e4d9d01c6b845af0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wsi_1/methods.py", "max_forks_repo_name": "hornisslaw/wsi", "max_forks_repo_head_hexsha": "a58c055109b7b16238817a5e4d9d01c6b845af0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8285714286, "max_line_length": 104, "alphanum_fraction": 0.6154214559, "include": true, "reason": "import numpy,from numpy", "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812345563902, "lm_q2_score": 0.8991213799730774, "lm_q1q2_score": 0.8706922719543739}}
{"text": "######\n###BACKGROUND\n#Below Section: Imports necessary functions\nimport numpy as np\nimport matplotlib.pyplot as graph\nimport random as rand\nimport time as watch\npi = np.pi\n\n######\n###SIMULATIONS\n\n#FUNCTION: ishit\n#PURPOSE: This function is meant to test whether or not a given 2d point is within the unit circle.\n#INPUTS: x = x-axis location, y = y-axis location\n#OUTPUT: Boolean\ndef ishit(x, y):\n\t#Below Section: Calculates (x, y) vector distance from origin using Pythagorean theorem\n\thyplength = np.sqrt(x**2 + y**2)\n\t\n\t#Below Section: Returns whether or not length within unit circle or not\n\tif hyplength <= 1:\n\t\treturn True\n\telse:\n\t\treturn False\n\t\n\t\n\n#FUNCTION: simdarts\n#PURPOSE: This function is meant to simulate a dart game, with the goal of hitting the inner circle.\n#INPUTS: Number of times to 'throw' a dart\n#OUTPUTS: Arrays of x and y locations where the dart falls each time; estimated pi value\ndef simdarts(num):\n\t#Below Section: Simulates given number of dart throws\n\tnum = int(num)\n\txlocs = np.zeros(num) #X-axis locations\n\tylocs = np.zeros(num) #Y-axis locations\n\t\n\t#Below generates the random numbers in [0, 1)\n\tfor a in range(0, num):\n\t\txlocs[a] = rand.random()\n\t\tylocs[a] = rand.random()\n\t\t\n\t#Below Section: Estimates the value of pi using the results\n\tcount = 0\n\tfor b in range(0, num):\n\t\tif ishit(x=xlocs[b], y=ylocs[b]):\n\t\t\tcount = count + 1\n\t\t\n\t#Below Section: Returns the calculated values\n\t#NOTE: Multiplies proportion by four to account for percentage of total circular area\n\treturn {'xs':xlocs, 'ys':ylocs, 'estpi':(count/1.0/num)*4}\n\t\n\t\n", "meta": {"hexsha": "db58210b79a2b61cebd14dca8f2bca980e3110ed", "size": 1567, "ext": "py", "lang": "Python", "max_stars_repo_path": "day2/exercises/Jamila/pi_estimate/sims.py", "max_stars_repo_name": "lavjams/BI-Demo", "max_stars_repo_head_hexsha": "2ff4aeb9dc71eeb1aa9e1f6510a79994c6c20ef1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day2/exercises/Jamila/pi_estimate/sims.py", "max_issues_repo_name": "lavjams/BI-Demo", "max_issues_repo_head_hexsha": "2ff4aeb9dc71eeb1aa9e1f6510a79994c6c20ef1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day2/exercises/Jamila/pi_estimate/sims.py", "max_forks_repo_name": "lavjams/BI-Demo", "max_forks_repo_head_hexsha": "2ff4aeb9dc71eeb1aa9e1f6510a79994c6c20ef1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4909090909, "max_line_length": 100, "alphanum_fraction": 0.7172941927, "include": true, "reason": "import numpy", "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.976310526632796, "lm_q2_score": 0.8918110562208681, "lm_q1q2_score": 0.8706845219559458}}
{"text": "# Linear regression on one-dimensional data using a closed form solution.\r\n# Please make sure matplotlib is included in the conda_dependencies.yml file.\r\n\r\nimport numpy as np\r\nimport matplotlib\r\nmatplotlib.use('agg')\r\nimport matplotlib.pyplot as plot\r\nfig = plot.figure()\r\n\r\n# load data\r\nX = []\r\nY = []\r\nfor line in open('data.csv'):\r\n    x, y = line.split(',')\r\n    X.append(float(x))\r\n    Y.append(float(y))\r\n    \r\n# turn them into numpy arrays so we can apply matrix operations\r\nX = np.array(X)\r\nY = np.array(Y)\r\n\r\n# this is the common denominator\r\ndenominator = X.dot(X) - X.mean() * X.sum()\r\n\r\n# value of a\r\na = (X.dot(Y) - Y.mean() * X.sum()) / denominator\r\n\r\n# value of b\r\nb = (Y.mean() * X.dot(X) - X.mean() * X.dot(Y)) / denominator\r\n\r\n# Yhat is simply aX + b\r\nYhat = a * X + b\r\nprint (\"Coefficient: {0}, intercept: {1}\".format(a, b))\r\n\r\n# Plot the data and the fitted line, then save it into a png file in the output directory.\r\nax = fig.gca()\r\nax.scatter(X, Y)\r\nax.plot(X, Yhat, color='magenta')\r\nfig.savefig('./outputs/lin.png')\r\n\r\n### compute r-squared ###\r\n# residual error of the prediction\r\nd1 = Y - Yhat\r\n# intrinsic error to mean\r\nd2 = Y - Y.mean()\r\n\r\n# if r2 is 1 (i.e., d1 is 0), this is a perfect model with no errors.\r\n# if r2 is 0 (i.e., d1 is the same as d2), this is a useless model as it is just the same as predicting mean.\r\n# if r2 is less than 0 (i.e., d1 is larger that d2), you are doing worse than predicting mean!!\r\nr2 = 1 - d1.dot(d1) / d2.dot(d2)\r\nprint (\"R-squared: {}.\".format(r2))\r\n", "meta": {"hexsha": "f061a4687fca4a3063ba14ad2b28fa358cc2077e", "size": 1520, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_reg.py", "max_stars_repo_name": "CortanaIntelligenceGallery/lin-reg-2", "max_stars_repo_head_hexsha": "0690ef9149b09f40264d3f41d72e54fd2a157325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_reg.py", "max_issues_repo_name": "CortanaIntelligenceGallery/lin-reg-2", "max_issues_repo_head_hexsha": "0690ef9149b09f40264d3f41d72e54fd2a157325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_reg.py", "max_forks_repo_name": "CortanaIntelligenceGallery/lin-reg-2", "max_forks_repo_head_hexsha": "0690ef9149b09f40264d3f41d72e54fd2a157325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2307692308, "max_line_length": 110, "alphanum_fraction": 0.6368421053, "include": true, "reason": "import numpy", "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543366, "lm_q2_score": 0.9032942138630786, "lm_q1q2_score": 0.8705768450949755}}
{"text": "#!env python\n# Fast Hadamard Transform\nimport numpy as np\nimport scipy.misc\nimport scipy.ndimage\nimport matplotlib\nimport matplotlib.pyplot as plt\n\ndef _power_of_two(sz):\n    n = 0\n    while 2**n < sz:\n        n += 1\n    return n\n\ndef fhtpad(x):\n    u'''pad 1-d array x to the minimal power-of-two'''\n    x = x.ravel()\n    n = _power_of_two(x.size)\n    if x.size < 2**n:\n        tmp = np.zeros(2**n)\n        tmp[:x.size] = x\n        x = tmp\n    return x\n\ndef fht(x, unitary=False):\n    u'''Fast Hadamard Transform of 2^n size array x.'''\n    x = x.ravel()\n    n = _power_of_two(x.size)\n    assert x.size == 2**n\n    t0, t1 = np.array(x), np.zeros_like(x)\n    for step in [2**(n - i - 1) for i in range(n)]:\n        skip = step*2\n        for j in range(0, t0.size, skip):\n            t1[j       :j + step] = t0[j:j + step] + t0[j + step:j + skip]\n            t1[j + step:j + skip] = t0[j:j + step] - t0[j + step:j + skip]\n        t0, t1 = t1, t0\n    if unitary:\n        return t0/(np.sqrt(2.0)**n)\n    else:\n        return t0\n\ndef ifht(x, unitary=False):\n    u'''Inverse Fast Hadamard Transform of 2^n size array x.'''\n    if unitary:\n        # in unitary mode, fht(x) == ift(x)\n        return fht(x, True)\n    else:\n        # in non-unitary mode, ifht(fht(x)) == x but not fht(x) != ift(x).\n        n = _power_of_two(x.size)\n        return fht(x)/2.0**n\n\ndef fht2(x, unitary=False):\n    u'''2D Fast Hadamard Transform'''\n    x = np.array([fht(row, unitary) for row in x])\n    x = np.array([fht(col, unitary) for col in x.T])\n    return x\n\ndef ifht2(x, unitary=False):\n    u'''2D Inverse Fast Hadamard Transform'''\n    x = np.array([ifht(row, unitary) for row in x])\n    x = np.array([ifht(col, unitary) for col in x.T])\n    return x\n\nif __name__=='__main__':\n\n    # non-unitary\n    arr = np.array([1, 0, 1, 0, 0, 1, 1], np.float32) # size=7\n    arr_ht = fht(fhtpad(arr))\n    arr_ht_ht = fht(arr_ht)\n    arr_ht_iht = ifht(arr_ht)\n    print 'Non-unitary..'\n    print 'x         :', arr\n    print 'HT(x)     :', arr_ht\n    print 'HT(HT(x)) :', arr_ht_ht\n    print 'IHT(HT(x)):', arr_ht_iht\n    assert np.allclose(fhtpad(arr), arr_ht_iht)\n\n    # unitary\n    arr = np.array([1, 0, 1, 0, 0, 1, 1, 0], np.float32) # size=8\n    arr_ht = fht(arr, True)\n    arr_ht_ht = fht(arr_ht, True)\n    arr_ht_iht = ifht(arr_ht, True)\n    print 'Unitary..'\n    print 'x         :', arr\n    print 'HT(x)     :', arr_ht\n    print 'HT(HT(x)) :', arr_ht_ht\n    print 'IHT(HT(x)):', arr_ht_iht\n    assert np.allclose(arr, arr_ht_iht)\n\n    # 2D\n    img = scipy.misc.lena()\n    img = scipy.ndimage.zoom(img, 1.0/8)\n    matplotlib.rc('font', size=9)\n    fig, axs = plt.subplots(4, 3, figsize=(12, 9))\n\n    img_ht = fht2(img)\n    img_ht_iht = ifht2(img_ht)\n    assert np.allclose(img, img_ht_iht)\n\n    ax = axs[0, 0]; ax.imshow(img, cmap='gray'); ax.set_title('org')\n    ax = axs[0, 1]; ax.imshow(img_ht); ax.set_title('HT(img)')\n    ax = axs[0, 2]; ax.imshow(img_ht_iht, cmap='gray'); ax.set_title('IHT(HT(img))')\n    ax = axs[1, 0]; ax.hist(img.ravel(), bins=50, edgecolor='none'); ax.set_title('org')\n    ax = axs[1, 1]; ax.hist(img_ht.ravel(), bins=50, edgecolor='none'); ax.set_title('HT(img)')\n    fig.delaxes(axs[1, 2])\n\n    img_u_ht = fht2(img, True)\n    img_u_ht_iht = ifht2(img_u_ht, True)\n    assert np.allclose(img, img_u_ht_iht)\n\n    ax = axs[2, 0]; ax.imshow(img, cmap='gray'); ax.set_title('org')\n    ax = axs[2, 1]; ax.imshow(img_u_ht); ax.set_title('uHT(img)')\n    ax = axs[2, 2]; ax.imshow(img_u_ht_iht, cmap='gray'); ax.set_title('uIHT(uHT(img))')\n    ax = axs[3, 0]; ax.hist(img.ravel(), bins=50, edgecolor='none'); ax.set_title('org')\n    ax = axs[3, 1]; ax.hist(img_u_ht.ravel(), bins=50, edgecolor='none'); ax.set_title('uHT(img)')\n    fig.delaxes(axs[3, 2])\n\n    fig.subplots_adjust(hspace=0.4)\n    fig.suptitle('Fast Hadamard Transform of 2D image', fontsize=12)\n    plt.show()\n\n", "meta": {"hexsha": "d81d1ce84ab19c573cdfa845b2be5285e6db1222", "size": 3874, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/fast_hadamard_transform.py", "max_stars_repo_name": "t-suzuki/fast_hadamard_transform_test", "max_stars_repo_head_hexsha": "fcea601d37704b22352d7e1a605d806765ae8b4f", "max_stars_repo_licenses": ["Python-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-03-08T03:54:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T09:41:25.000Z", "max_issues_repo_path": "python/fast_hadamard_transform.py", "max_issues_repo_name": "t-suzuki/fast_hadamard_transform_test", "max_issues_repo_head_hexsha": "fcea601d37704b22352d7e1a605d806765ae8b4f", "max_issues_repo_licenses": ["Python-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/fast_hadamard_transform.py", "max_forks_repo_name": "t-suzuki/fast_hadamard_transform_test", "max_forks_repo_head_hexsha": "fcea601d37704b22352d7e1a605d806765ae8b4f", "max_forks_repo_licenses": ["Python-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7540983607, "max_line_length": 98, "alphanum_fraction": 0.578988126, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799410139921, "lm_q2_score": 0.9032942073547149, "lm_q1q2_score": 0.8705768378826079}}
{"text": "import numpy as np\r\n\r\ndef doolittle(A, n, b):\r\n    U = np.zeros((n,n))\r\n    L = np.eye(n, dtype=float)\r\n    diag=1\r\n    Z = np.zeros((n,1), float)\r\n    X = np.zeros((n,1), float)\r\n\r\n#    L,U = inicializa(n,0)\r\n    for k in range(n):\r\n        suma1 = 0\r\n        for p in range(0,k):\r\n            suma1 += L[k][p]*U[p][k]\r\n        U[k][k] = A[k][k]-suma1\r\n        for i in range(k+1,n):\r\n            suma2 = 0\r\n            for p in range(k):\r\n                suma2 += L[i][p]*U[p][k]\r\n            L[i][k] = (A[i][k]-suma2)/float(U[k][k])\r\n        for j in range(k+1,n):\r\n            suma3 = 0\r\n            for p in range(k):\r\n                suma3 += L[k][p]*U[p][j]\r\n            U[k][j]= (A[k][j]-suma3)/float(L[k][k])\r\n        #imprimir L  U y k etapa\r\n        print(\"Etapa: \", k)\r\n        print(\"L: \")\r\n        print(L)\r\n        print(\"U: \")\r\n        print(U)\r\n\r\n    Lb = np.concatenate([L, b], axis=1)\r\n    for i in range(0,n):\r\n        diag = diag*U[i][i]\r\n    if(diag != 0):\r\n        for i in range(0, n):\r\n            suma = 0\r\n            for k in range(0, n):\r\n                suma = suma+Lb[i][k]*Z[k][0]\r\n            Z[i][0] = (Lb[i][n] - suma)/Lb[i][i]\r\n        Uz = np.concatenate([U, Z], axis = 1)\r\n        for i in range(n-1,-1, -1):\r\n            suma = 0\r\n            for k in range(0, n):\r\n                suma = suma+Uz[i][k]*X[k][0]\r\n            X[i][0] = (Uz[i][n] - suma)/Uz[i][i]       \r\n    else:\r\n        print(\"El sistema no tiene solucion o tiene infinitas soluciones pues det = 0\")\r\n    print(\"FInal -------------------------------------------\")\r\n    print(\"L:\")\r\n    print(L)\r\n    print(\"=================================================\")\r\n    print(\"U:\")\r\n    print(U)\r\n    print(\"X: \")\r\n    print(X)\r\n    print(\"Z: \")\r\n    print(Z)\r\n\r\n    return L,U\r\n\r\na = [[4, -1, 0, 3],\r\n     [1, 15.5, 3, 8],\r\n     [0, -1.3, -4, 1.1],\r\n     [14, 5, -2, 30]]\r\nn = len(a)\r\nb = np.array([[1],[1],[1],[1]])\r\nprint(n)\r\ndoolittle(a, n, b)\r\n\r\n", "meta": {"hexsha": "8d70b5b2596fa7fb8f72e5161d6f1739391161fb", "size": 1952, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/doolittle.py", "max_stars_repo_name": "eechava6/NumericalAnalysisMethods", "max_stars_repo_head_hexsha": "3eeb06bdb20d97f13a09fd0ed71bce045173ffef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/doolittle.py", "max_issues_repo_name": "eechava6/NumericalAnalysisMethods", "max_issues_repo_head_hexsha": "3eeb06bdb20d97f13a09fd0ed71bce045173ffef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/doolittle.py", "max_forks_repo_name": "eechava6/NumericalAnalysisMethods", "max_forks_repo_head_hexsha": "3eeb06bdb20d97f13a09fd0ed71bce045173ffef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1111111111, "max_line_length": 88, "alphanum_fraction": 0.3734631148, "include": true, "reason": "import numpy", "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799399736477, "lm_q2_score": 0.9032942008463507, "lm_q1q2_score": 0.8705768306702399}}
{"text": "\n# coding: utf-8\n\n# # 6. Regression (Linear and Nonlinear)\n# \n# \n\n# In[2]:\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nget_ipython().magic('matplotlib inline')\n\n\n# ## Linear regression with scipy.stats.linregress \n# Check the documentation\n# http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html\n# \n# `scipy.stats.linregress(x, y=None)`\n# \n# Calculate a linear least-squares regression for two sets of measurements.\n# \n# Parameters:\t\n# * x, y : array_like\n# Two sets of measurements. Both arrays should have the same length. If only x is given (and y=None), then it must be a two-dimensional array where one dimension has length 2. The two sets of measurements are then found by splitting the array along the length-2 dimension.\n# \n# Returns:\n# \n# * slope : float\n#   slope of the regression line\n# * intercept : float\n#   intercept of the regression line\n# * rvalue : float\n#   correlation coefficient\n# * pvalue : float\n#   two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero.\n# * stderr : float\n#   Standard error of the estimate\n\n# In[4]:\n\nimport scipy.stats\nx_data = np.array([0.5, 1.0, 2.0, 3.0,  5.0, 7.5])\ny_data = np.array([1.2, 2.8, 5.2, 7.2, 10.6, 20.0])\nslope, intercept, rvalue, pvalue, stderr = scipy.stats.linregress(x_data, y_data)\nprint(slope, intercept, rvalue, pvalue, stderr)\nprint(\"Slope: {}\".format(slope))\nprint(\"Intercept: {}\".format(intercept))\nprint(\"Coefficient of determination (r squared): {}\".format(rvalue*rvalue))\nprint(\"p-value (probability that the slope is zero): {}\".format(pvalue))\nprint(\"Standard error in slope: {}\".format(stderr))\n\nplt.plot(x_data, y_data, 'o')\nplt.plot(x_data, x_data*slope+intercept)\nplt.show()\n\n\n# Notice that the documentation has a \"see also\" section that points to optimize.curve_fit. Let's check that out next\n\n# ## Nonlinear regression with scipy.optimize.curve_fit\n# \n# `scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, check_finite=True, bounds=(-inf, inf), method=None, **kwargs)`\n# \n# This is quite a powerful function, giving access to several methods, bounds on the parameters, rescaling options, etc., so it's worth reading the documentation:\n# http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html\n# \n# However, for a simple case it's quite easy to use.\n# We define a function `f(x)` such that `ydata = f(xdata, *params) + eps` and it will optimize the parameters `params` to minimize the square of the errors `eps`, i.e. make the function `f` fit the data (`xdata, ydata`).\n# \n\n# For the simplest example, we can use it to fit a linear function like we did above. (Though if we *did* want to fit a linear funciton, we'd probably use the method above).\n\n# In[5]:\n\nimport scipy.optimize\ndef linear_function(x, slope, intercept):\n    return x*slope + intercept\n\nx_data = np.array([0.5, 1.0, 2.0, 3.0,  5.0, 7.5])\ny_data = np.array([1.2, 2.8, 5.2, 7.2, 10.6, 20.0])\n\noptimal_parameters, covariance = scipy.optimize.curve_fit(linear_function, x_data, y_data)\n# That's it! In this exampe we didn't even need to give it a starting guess!\nprint(\"Slope: {}\".format(optimal_parameters[0]))\nprint(\"Intercept: {}\".format(optimal_parameters[1]))\n\n# Use the covariance matrix to find the standard errors.\n# The diagonals give the variance, so...\nparameter_errors = np.sqrt(np.diag(covariance))\nprint(\"Slope: {} +/- {} (1 st. dev.)\".format(optimal_parameters[0],parameter_errors[0]))\nprint(\"Intercept: {} +/- {} (1 st. dev.)\".format(optimal_parameters[1],parameter_errors[1]))\n\nplt.plot(x_data, y_data, 'o')\nplt.plot(x_data, linear_function(x_data, *optimal_parameters))\nplt.show()\n\n\n# Now we will try a more complicated function with three parameters, $a, b, c$:\n# \n# $$y = f(x) = \\frac{a x^2}{(1 + b x + c x^2)}$$\n# \n# I generated some pretend data by using the function with $(a,b,c) = (20, 0.5, 20)$ then adding some random noise and tweaking one of the points slightly. We'll see if we can retrieve the paramaters by fitting the function to my pretend data.\n# \n\n# In[7]:\n\ndef complicated_function(x, a, b, c):\n    \"A more complicated function with 3 parameters\"\n    return a*x*x / (1 + b*x + c*x*x)\n\n# These data were generated by adding random noise to the original function like this:\n#x_data = np.linspace(0,1,11)\n#y_data = complicated_function(x,20,0.5,20)*(1+np.random.normal(scale=0.05,size=x.size))+np.random.normal(scale=0.05,size=x.size)\n# (then manually tweaked a bit)\nx_data = np.array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ])\ny_data = np.array([ 0.01717205,  0.1005844 ,  0.43536816,  0.59862244,  0.76359374,\n        0.77385322,  0.89904593,  0.86883376,  0.87039673,  .95,\n        0.95870025])\n\n# Fit the parameters to the imperfect x_data and y_data\noptimal_parameters, covariance = scipy.optimize.curve_fit(complicated_function,\n                                                          x_data,\n                                                          y_data)\ndef report(optimal_parameters, covariance):\n    \"Make this a function so we can reuse it in cells below\"\n    parameter_errors = np.sqrt(np.diag(covariance))\n    for i in range(len(optimal_parameters)):\n        print(\"Parameter {}: {} +/- {} (1 st. dev.)\".format(i,\n                                                            optimal_parameters[i],\n                                                            parameter_errors[i]))\n\n    # Plot the data\n    plt.plot(x_data, y_data, 'o', label='data')\n\n    # Make a new x array with 50 points for smoother lines\n    x_many_points = np.linspace(x_data.min(),x_data.max(),50)\n    # Plot the fitted curve\n    plt.plot(x_many_points, complicated_function(x_many_points, *optimal_parameters), label='fitted')\n    # Plot the original curve used to generate the data in the first place\n    plt.plot(x_many_points, complicated_function(x_many_points,20,0.5,20), ':',label='original')\n    # Add the legend, in the \"best\" location to avoid hiding the data\n    plt.legend(loc='best')\n    plt.show()\n\nreport(optimal_parameters, covariance)\n\n\n# If we want to enforce all the parameters are positive, we can supply a `bounds` parameter to the `scipy.optimize.curve_fit` function. We use `numpy.inf` for $\\infty$.\n\n# In[9]:\n\n# Set the bounds on all the parameters to be 0 and infinity.\noptimal_parameters, covariance = scipy.optimize.curve_fit(complicated_function,\n                                                          x_data,\n                                                          y_data,\n                                                         bounds = (0, np.inf)) # BOUNDS!\nreport(optimal_parameters, covariance)\n\n\n# We notice the uncertainty on parameter 2 is bigger than parameter 2, i.e. it's possible, given the data, that it is zero. This suggests we can simplify our model and still fit the given data.\n# \n# One option would just be to enforce the $b$ parameter to be zero (or very close to zero) by specifying different bounds for each parameter:\n\n# In[10]:\n\n# Set the lower and upper bounds on each parameter separately\nbounds = ([0,0,0], [np.inf, 1e-6, np.inf])\noptimal_parameters, covariance = scipy.optimize.curve_fit(complicated_function,\n                                                          x_data,\n                                                          y_data,\n                                                         bounds = bounds)\nreport(optimal_parameters, covariance)\n\n\n# But notice it assigns a big uncertainty to $b$ even though we know (or are assuming) that it is zero. This then changes the uncertainty in $a$ and $c$. It is better to define a new function with only 2 parameters and fit that:\n\n# In[11]:\n\ndef simplified_function(x, a, c):\n    \"A slightly simplified function with only 2 parameters: a and c\"\n    return a*x*x / (1 + c*x*x)\noptimal_parameters, covariance = scipy.optimize.curve_fit(simplified_function,\n                                                          x_data,\n                                                          y_data)\n# Can't reuse the 'report' function exactly, so do modify slightly\nparameter_errors = np.sqrt(np.diag(covariance))\nfor i in range(len(optimal_parameters)):\n    print(\"Parameter {}: {} +/- {} (1 st. dev.)\".format(i,\n                                                        optimal_parameters[i],\n                                                        parameter_errors[i]))\nplt.plot(x_data, y_data, 'o', label='data')\nx_many_points = np.linspace(x_data.min(),x_data.max(),50)\nplt.plot(x_many_points, simplified_function(x_many_points, *optimal_parameters), label='fitted')\nplt.plot(x_many_points, complicated_function(x_many_points,20,0.5,20), ':',label='original')\nplt.legend(loc='best')\nplt.show()\n\n\n# The current data are not sufficient to tell the two-parameter model and three-paramaeter models apart.\n# \n# Note that the function $f(x)$ could be a function of several variables, i.e. $x$ could be a vector, and `x_data` would be a 2-dimensional array.\n\n# In[ ]:\n\n\n\n", "meta": {"hexsha": "768f718adf79af23dc8c9f70cd9031a64e735d6c", "size": 9004, "ext": "py", "lang": "Python", "max_stars_repo_path": "6-Regression.py", "max_stars_repo_name": "CHME5137/helpful-examples", "max_stars_repo_head_hexsha": "b188abd739b6d30d1c326043350e565df998ed7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-23T23:17:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-23T23:17:59.000Z", "max_issues_repo_path": "6-Regression.py", "max_issues_repo_name": "CHME5137/helpful-examples", "max_issues_repo_head_hexsha": "b188abd739b6d30d1c326043350e565df998ed7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6-Regression.py", "max_forks_repo_name": "CHME5137/helpful-examples", "max_forks_repo_head_hexsha": "b188abd739b6d30d1c326043350e565df998ed7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-10-17T19:30:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-23T23:18:00.000Z", "avg_line_length": 43.4975845411, "max_line_length": 272, "alphanum_fraction": 0.6529320302, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.9465966692585823, "lm_q1q2_score": 0.8705305652605532}}
{"text": "import numpy as np\n\n\ndef fib(n):\n    if n == 0:\n        return 0\n    elif n == 1:\n        return 1\n    else:\n        return fib(n-1) + fib(n-2)\n\ndef fib_dp(n):\n    if n < 2:\n        return n\n    solution = [0] * (n+1)\n    solution[0] = 0\n    solution[1] = 1\n    for i in range(2,n+1):\n        solution[i] = solution[i-1] + solution[i-2]\n\n    return solution[-1]\n\ndef job_selection_w_recover(calendar):\n    size = len(calendar)\n    j = [0] * size\n    s = [False] * size\n    j[0] = calendar[0]\n    s[0] = True\n    j[1] = max(calendar[0], calendar[1])\n    s[1] = calendar[1] > calendar[0]\n\n    for i in range(2, size):\n        with_last = j[i-2] + calendar[i]\n        with_out_last = j[i-1]\n        j[i] = max(with_last, with_out_last)\n        s[i] = with_last > with_out_last\n\n    days_worked = job_selection_recover(s)\n    return days_worked, j[-1]\n\ndef job_selection_recover(job_solution):\n    a = []\n    i = len(job_solution) - 1\n\n    while i >= 0:\n        if job_solution[i]:\n            a.append(i)\n            i -= 2\n        else:\n            i -= 1\n    return a\n\ndef job_selection_no_recover(calendar):\n    size = len(calendar)\n    j = [0] * size\n    days_worked = [None] * size  # CAN ALSO MAINTAIN THE DAYS WORKED TO NOT REQUIRE THE RECOVERY (LIKE CHANGE MAKING)\n    j[0] = calendar[0]\n    days_worked[0] = [0]\n    j[1] = max(calendar[0], calendar[1])\n    days_worked[1] = [1 if calendar[1] > calendar[0] else 0]\n\n    for i in range(2, size):\n        with_last = j[i-2] + calendar[i]\n        with_out_last = j[i-1]\n        j[i] = max(with_last, with_out_last)\n        if with_last > with_out_last:\n            days_worked[i] = days_worked[i-2].copy()\n            days_worked[i].append(i)\n        else:\n            days_worked[i] = days_worked[i-1].copy()\n\n    return days_worked[-1], j[-1]\n\ndef knapsack(weights, values, capacity):\n    solution = np.zeros((len(weights), capacity+1))\n    # INITIALIZE THE FIRST ITEM\n    for j in range(capacity+1):\n        solution[0, j] = values[0] if j >= weights[0] else 0\n\n    for i in range(1, len(weights)):\n        for j in range(capacity+1):\n            if j - weights[i] >= 0:  # IF THIS ITEM CAN FIT\n                with_item = solution[i-1, j-weights[i]] + values[i]\n            else:\n                with_item = -1\n\n            without_item = solution[i-1,j]\n            solution[i, j] = max(without_item, with_item)\n\n    return solution\n\ndef knapsack_recovery(solution, weights, values):\n    rows, cols = solution.shape\n\n    curr_row = rows - 1\n    curr_col = cols - 1\n\n    result = []\n\n    curr_val = solution[curr_row, curr_col]\n\n    while curr_val > 0:\n        if curr_row == 0:\n            result.append(curr_row)\n            break\n        elif curr_val != solution[curr_row - 1, curr_col]:\n            result.append(curr_row)\n            curr_val = curr_val - values[curr_row]\n            curr_col = curr_col - weights[curr_row]\n            curr_row -= 1\n        else:\n            curr_row -= 1\n\n    return result\n\n\n\n\nif __name__ == \"__main__\":\n    # FIB DEMO:\n    # for i in range(10):\n    #     print(fib(i))\n    # for i in range(50):\n    #     print(fib_dp(i))\n\n# JOB SELECTION DEMO\n#     p = [15, 46, 43, 51, 92, 72, 61, 41, 39, 40, 82, 79, 42, 51]\n#     days_worked, dollars = job_selection_no_recover(p)\n#\n#     print(f\"By Working days: {days_worked} you can earn {dollars}\")\n\n    #\n    w = [10,4,2,6,7,4,1,3]\n    v = [1,1,5,6,7,2,4,1]\n    c = 13\n    solution = knapsack(w,v,c)\n    print(solution)\n    kp_solution = knapsack_recovery(solution, w, v)\n    print(kp_solution)\n\n    w = [5,4,1]\n    v = [150, 100, 10]\n    c = 10\n    solution = knapsack(w,v,c)\n\n    print(solution)\n    kp_solution = knapsack_recovery(solution, w, v)\n\n    t = 0\n    for val in kp_solution:\n        t += v[val]\n\n    print(f\"Total Value: {t}  but solution says: {solution[-1,-1]}\")\n    print(kp_solution)", "meta": {"hexsha": "8302a51d6ac836bec46315786abbc20b63c7d2bd", "size": 3843, "ext": "py", "lang": "Python", "max_stars_repo_path": "SampleCode/7_DynamicProgramming.py", "max_stars_repo_name": "kev-odin/tcss503-22-wi", "max_stars_repo_head_hexsha": "1294531f31d1a6b191c9f5ae3183add332da794f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-07T14:37:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T23:10:29.000Z", "max_issues_repo_path": "SampleCode/7_DynamicProgramming.py", "max_issues_repo_name": "kev-odin/tcss503-22-wi", "max_issues_repo_head_hexsha": "1294531f31d1a6b191c9f5ae3183add332da794f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SampleCode/7_DynamicProgramming.py", "max_forks_repo_name": "kev-odin/tcss503-22-wi", "max_forks_repo_head_hexsha": "1294531f31d1a6b191c9f5ae3183add332da794f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-04T23:07:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T03:06:14.000Z", "avg_line_length": 24.9545454545, "max_line_length": 117, "alphanum_fraction": 0.5547749154, "include": true, "reason": "import numpy", "num_tokens": 1202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.919642529525996, "lm_q1q2_score": 0.8705305548382876}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep  2 11:13:40 2021\n\n@author: oiseth\n\"\"\"\n\nimport numpy as np # Import numpy\nfrom matplotlib import pyplot as plt # pyplot module for plotting\n\ndt = 0.01 # Time step\nt = np.arange(0,10.01,dt) # time vector\nx = np.zeros(t.shape) # Initialize the x array\nx[t<5] = 1.0 # Set the value of x to one for t<5\n# Plot waveform\nplt.figure()\nplt.plot(np.hstack((t-20.0,t-10.0, t, t+10.0)),np.hstack((x,x,x,x))); # Plot four periods\nplt.plot(t,x); #Plot one period\nplt.ylim(-2, 2);\nplt.xlim(-20,20);\nplt.grid();\nplt.xlabel('$t$');\nplt.ylabel('$X(t)$');\n\nnterms = 10 # Number of Fourier coefficeints\nT = np.max(t) # The period of the waveform\na0 = 1/T*np.trapz(x,t) # Mean value\nak = np.zeros((nterms)) \nbk = np.zeros((nterms))\nfor k in range(nterms): # Integrate for all terms\n    ak[k] = 1/T*np.trapz(x*np.cos(2.0*np.pi*(k+1.0)*t/T),t)\n    bk[k] = 1/T*np.trapz(x*np.sin(2.0*np.pi*(k+1.0)*t/T),t)\n\n# Plot Fourier coeffecients\nfig, axs = plt.subplots(nrows=1, ncols=2, constrained_layout=True)\n\nax1 = axs[0]\nax1.plot(np.arange(1,nterms+1),ak)\nax1.set_ylim(-1, 1)\nax1.grid()\nax1.set_ylabel('$a_k$');\nax1.set_xlabel('$k$');\n\nax2 = axs[1]\nax2.plot(np.arange(1,nterms+1),bk)\nax2.set_ylim(-1, 1)\nax2.grid()\nax2.set_ylabel('$b_k$');\nax2.set_xlabel('$k$');\n#%%\n# Plot Fourier series approximation\ntp  = np.linspace(-20,20,1000)\nX_Fourier = np.ones(tp.shape[0])*a0\nfor k in range(nterms):\n    X_Fourier = X_Fourier + 2.0*(ak[k]*np.cos(2.0*np.pi*(k+1.0)*tp/T) + bk[k]*np.sin(2.0*np.pi*(k+1.0)*tp/T))\n\nplt.figure(figsize=(8,4))\nplt.plot(np.hstack((t-20.0,t-10.0, t, t+10.0)),np.hstack((x,x,x,x))); # Plot four periods\nplt.plot(tp,X_Fourier, label=('Fourier approximation Nterms='+str(nterms)));\nplt.ylim(-2, 2)\nplt.xlim(-20,20)\nplt.grid()\nplt.xlabel('$t$')\nplt.ylabel('$X(t)$')\nplt.legend();\n    ", "meta": {"hexsha": "98a0f9256c4896a8bfa9a48fb1272233ad550aea", "size": 1816, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/examples/week2_example1.py", "max_stars_repo_name": "oiseth/TKT4108StructuralDynamics2", "max_stars_repo_head_hexsha": "826929e055d9b1457fa0b4c1c8537afa06dc98dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T09:52:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T09:52:10.000Z", "max_issues_repo_path": "python/examples/week2_example1.py", "max_issues_repo_name": "oiseth/TKT4108StructuralDynamics2", "max_issues_repo_head_hexsha": "826929e055d9b1457fa0b4c1c8537afa06dc98dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/examples/week2_example1.py", "max_forks_repo_name": "oiseth/TKT4108StructuralDynamics2", "max_forks_repo_head_hexsha": "826929e055d9b1457fa0b4c1c8537afa06dc98dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-09-01T09:46:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-09T18:58:52.000Z", "avg_line_length": 27.5151515152, "max_line_length": 109, "alphanum_fraction": 0.6420704846, "include": true, "reason": "import numpy", "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.972830768464319, "lm_q2_score": 0.8947894527758053, "lm_q1q2_score": 0.8704787109576543}}
{"text": "#!/usr/bin/env python3\n\n\"\"\"\n\nhttps://tutorial.math.lamar.edu/classes/de/IntroSecondOrder.aspx\n\n2nd order constant homogenous differential equation are equations of the form\n\nay'' + by' + cy = 0\n\nThe general solution is of the form\ny(t) = c1*exp(r1*t) + c2*exp(r2*t)\n\nTo solve for r1 and r2, we can treat the equation as a quadratic equation where\n\nr1 = [-b + sqrt(b^2 - 4ac)] / 2a\nr2 = [-b - sqrt(b^2 - 4ac)] / 2a\n\nIf there is an initial condition we can solve for the constant c1 and c2\n\nW = [[y1, y2], [y1', y2']]\nc1 = [[y0, y2], [y0', y2']] / W\nc2 = [[y1, y0], [y1', y0']] / W\n\nW is called the wronskian and determines if there is a solution\ny1(t) = exp(r1*t)\ny2(t) = exp(r2*t)\n\nSince we have the form of an exponential function, derivative is\ny1'(t) = r1*y1(t)\ny2'(t) = r2*y2(t)\n\nPlug in t0 for the initial condition (t0 can be nonzero)\n\n\"\"\"\n\nimport cmath\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef det2(m):\n    return m[0][0]*m[1][1] - m[0][1]*m[1][0]\n\ndef solve(a, b, c, y0=None, y0p=None, t0=0):\n    d = cmath.sqrt(b*b - 4*a*c)\n    r1 = (-b + d) / (2*a)\n    r2 = (-b - d) / (2*a)\n    if y0 == None or y0p == None:\n        return [r1, r2]\n    \n    y1 = cmath.exp(r1*t0)\n    y2 = cmath.exp(r2*t0)\n    y1p = r1*y1\n    y2p = r2*y2\n    W = det2([[y1, y2], [y1p, y2p]])\n    if W == 0:\n        return [r1, r2, None, None]\n\n    c1 = det2([[y0, y2], [y0p, y2p]]) / W\n    c2 = det2([[y1, y0], [y1p, y0p]]) / W\n    return [r1, r2, c1, c2]\n\ndef plot(name, a, b, c, y0, y0p, t0):\n    r = solve(a, b, c, y0, y0p, t0)\n    assert(len(r) == 4)\n    \n    f = lambda t: abs(r[2]*cmath.exp(r[0]*t) + r[3]*cmath.exp(r[1]*t))\n    ts = np.linspace(0, 10, 100)\n    ys = np.array([f(t) for t in ts])\n    plt.clf()\n    plt.plot(ts, ys, label=\"a={} b={} c={} y(t0)={} y'(t0)={} t0={}\\nr0={}\\nr1={}\\nc1={}\\nc2={}\".\n            format(a, b, c, y0, y0p, t0, r[0], r[1], r[2], r[3]))\n    plt.legend()\n    plt.savefig(name)\n\nplot(\"solution_1.png\", 1, 11, 24, 0, -7, 0)\nplot(\"solution_2.png\", 1, 3, -10, 4, -2, 0)\n", "meta": {"hexsha": "77a1aabc3e68a14a490a89a7ec309d7230b5e5e4", "size": 2000, "ext": "py", "lang": "Python", "max_stars_repo_path": "math/2nd-order-constant-homogeneous-ode.py", "max_stars_repo_name": "qeedquan/misc_utilities", "max_stars_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-10-17T18:17:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:02:53.000Z", "max_issues_repo_path": "math/2nd-order-constant-homogeneous-ode.py", "max_issues_repo_name": "qeedquan/misc_utilities", "max_issues_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/2nd-order-constant-homogeneous-ode.py", "max_forks_repo_name": "qeedquan/misc_utilities", "max_forks_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:52:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:10:59.000Z", "avg_line_length": 25.641025641, "max_line_length": 97, "alphanum_fraction": 0.552, "include": true, "reason": "import numpy", "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347883040039, "lm_q2_score": 0.8933094117351309, "lm_q1q2_score": 0.8704717675140965}}
{"text": "\"\"\"Compute confidence intervals for normal data.\n\nUsing Null Hypothesis Significance Testing (NHST) framework as\ncontext:\nA (1 - alpha) confidence interval is an interval statistic\ncentered at some test statistic which will contain the null\nhypothesis value 100*(1 - alpha)% of the time.\n\"\"\"\nimport scipy.stats\nimport numpy as np\n\n\ndef z_ci_for_mean(samples, true_var: float, confidence: float = 0.95):\n    \"\"\"Confidence interval for the sample mean.\n\n    Assumptions:\n        i.i.d. x_1, ..., x_n ~ N(mu, sigma^2)\n    Where:\n        mu is unknown;\n        sigma^2 is known and provided by the user (`true_var`).\n\n    Confidence = 1 - (Type I Error).\n    \"\"\"\n    assert 0 <= confidence <= 1.0\n\n    n = len(samples)\n    sample_mean = np.mean(samples)\n\n    crit_point = scipy.stats.norm.isf(0.5 * (1.0 - confidence))\n\n    dist = crit_point * np.sqrt(true_var / n)\n\n    lower_bound = sample_mean - dist\n    upper_bound = sample_mean + dist\n\n    return (lower_bound, upper_bound)\n\n\ndef t_ci_for_mean(samples, confidence: float = 0.95):\n    \"\"\"Confidence interval for the sample mean.\n\n    Assumptions:\n        i.i.d. x_1, ..., x_n ~ N(mu, sigma^2)\n    Where:\n        mu and sigma^2 is unknown.\n\n    Confidence = 1 - (Type I Error).\n    \"\"\"\n    assert 0 <= confidence <= 1.0\n\n    n = len(samples)\n    sample_mean = np.mean(samples)\n    sample_var = np.var(samples, ddof=1)\n\n    crit_point = scipy.stats.t(n - 1).isf(0.5 * (1.0 - confidence))\n\n    dist = crit_point * np.sqrt(sample_var / n)\n\n    lower_bound = sample_mean - dist\n    upper_bound = sample_mean + dist\n\n    return (lower_bound, upper_bound)\n\n\ndef chi_square_ci_for_variance(samples, confidence: float = 0.95):\n    \"\"\"Confidence interval for the sample variance.\n\n    Assumptions:\n        i.i.d. x_1, ..., x_n ~ N(mu, sigma^2)\n    Where:\n        mu and sigma^2 is unknown.\n\n    Confidence = 1 - (Type I Error).\n    \"\"\"\n    assert 0 <= confidence <= 1.0\n\n    n = len(samples)\n    sample_var = np.var(samples, ddof=n - 1)\n    half_err_type_1_rate = 0.5 * (1.0 - confidence)\n\n    dist = scipy.stats.chi2(n - 1)\n\n    crit_point_low = dist.isf(half_err_type_1_rate)\n    crit_point_upper = dist.ppf(half_err_type_1_rate)\n\n    lower_bound = sample_var / crit_point_low\n    upper_bound = sample_var / crit_point_upper\n\n    return (lower_bound, upper_bound)\n\n\ndef _test():\n    true_var = 64\n    n_samples = 95\n    true_mean = 3\n    samples = true_mean + np.sqrt(true_var) * np.random.randn(n_samples)\n    print(z_ci_for_mean(samples, true_var))\n    print(t_ci_for_mean(samples))\n    print(chi_square_ci_for_variance(samples))\n\n\nif __name__ == \"__main__\":\n    _test()\n", "meta": {"hexsha": "dc5fc00550de55deec246839bac6b711b06432af", "size": 2616, "ext": "py", "lang": "Python", "max_stars_repo_path": "confidence_intervals/conf_int_for_normal_data.py", "max_stars_repo_name": "FelSiq/statistics-related", "max_stars_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-13T02:09:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-13T02:09:08.000Z", "max_issues_repo_path": "confidence_intervals/conf_int_for_normal_data.py", "max_issues_repo_name": "FelSiq/statistics-related", "max_issues_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "confidence_intervals/conf_int_for_normal_data.py", "max_forks_repo_name": "FelSiq/statistics-related", "max_forks_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1538461538, "max_line_length": 72, "alphanum_fraction": 0.6548165138, "include": true, "reason": "import numpy,import scipy", "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347875615794, "lm_q2_score": 0.89330940889474, "lm_q1q2_score": 0.870471764083106}}
{"text": "import numpy as np\n\n\ndef sigmoid(z):\n    return 1 / (1 + np.exp(-z))\n\ndef sigmoid_d(z):\n    return np.exp(-z) / (np.square((np.exp(-z) + 1)))\n\n\nif __name__ == \"__main__\":\n    print('Sigmoid Tests')\n    testVector = np.matrix(\"1 0 -1\")\n\n    for i in range(2, 5):\n        epsilon = 10 ** (-i) # Testing 0.01 ... 0.0001\n        print(\"Epsilon: \", epsilon)\n\n        testDerivative = (sigmoid(testVector + epsilon) - sigmoid(testVector)) / epsilon\n        realDerivative = sigmoid_d(testVector)\n        print(realDerivative - testDerivative)\n", "meta": {"hexsha": "9070ddd16cdd13436276815b4c56d2692f69be55", "size": 537, "ext": "py", "lang": "Python", "max_stars_repo_path": "sigmoid.py", "max_stars_repo_name": "Kiran-Rao/neural-network", "max_stars_repo_head_hexsha": "985292e5c95d4fc9748ec1a89cb778217b9b9faa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sigmoid.py", "max_issues_repo_name": "Kiran-Rao/neural-network", "max_issues_repo_head_hexsha": "985292e5c95d4fc9748ec1a89cb778217b9b9faa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sigmoid.py", "max_forks_repo_name": "Kiran-Rao/neural-network", "max_forks_repo_head_hexsha": "985292e5c95d4fc9748ec1a89cb778217b9b9faa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4090909091, "max_line_length": 88, "alphanum_fraction": 0.5977653631, "include": true, "reason": "import numpy", "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191271831559, "lm_q2_score": 0.9111797051879431, "lm_q1q2_score": 0.8704674006671511}}
{"text": "#plot Bayesian updates to beta distribution with respect to two different priors\nfrom scipy.stats import beta\nimport numpy as np\nimport matplotlib.pyplot as plt \nfrom matplotlib import cm\n\n# plot priors\nx = np.linspace(0, 1, num = 100)\nplt.plot(x, beta(1, 1).pdf(x), label = \"Prior = beta(1,1)\", color = cm.get_cmap('Blues_r')(100))\nplt.plot(x, beta(1.4, 2.3).pdf(x), label = \"Prior = beta(1.4,2.3)\", color = cm.get_cmap('Reds_r')(100))\n\nfor i in range(1,22,5):\n    plt.plot(x, beta(1+i,2).pdf(x), label = \"Uniform After {} heads\".format(i), color = cm.get_cmap('Blues_r')(100-10*i))\n    plt.plot(x, beta(1.4+i,2.3).pdf(x), label = \"Biased After {} heads\".format(i), color = cm.get_cmap('Reds_r')(100-10*i))\n\nplt.legend()\nplt.title(\"Comparison of updates to uniform and non-uniform priors\")\nplt.show()", "meta": {"hexsha": "9e7a55c47b1678c3b6d03c124b207bda6606d313", "size": 801, "ext": "py", "lang": "Python", "max_stars_repo_path": "bayes/prior-updates/python/biased-unbiased-beta.py", "max_stars_repo_name": "JustinNoel1/ML-Course", "max_stars_repo_head_hexsha": "df805fea8febe6a92ca08142b93460432f6aaed0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bayes/prior-updates/python/biased-unbiased-beta.py", "max_issues_repo_name": "JustinNoel1/ML-Course", "max_issues_repo_head_hexsha": "df805fea8febe6a92ca08142b93460432f6aaed0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bayes/prior-updates/python/biased-unbiased-beta.py", "max_forks_repo_name": "JustinNoel1/ML-Course", "max_forks_repo_head_hexsha": "df805fea8febe6a92ca08142b93460432f6aaed0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.5, "max_line_length": 123, "alphanum_fraction": 0.6791510612, "include": true, "reason": "import numpy,from scipy", "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138157595305, "lm_q2_score": 0.890294235582146, "lm_q1q2_score": 0.8704529742197344}}
{"text": "#\n# Jacobi polynomials evaluated at a point or vector\n#\n# by Alberto Costa Nogueira Jr. (Matlab and Python versions)\n#    Renato Cantao (Python version)\n#\nfrom numbers import Number\nimport numpy\n\ndef jacobi_p(x, m, alpha = 0.0, beta = 0.0):\n    \"\"\"Jacobi polynomial.\"\"\"\n    number_flag = False\n\n    if isinstance(x, Number):\n        x = numpy.array([x])\n        number_flag = True\n\n    aPb = alpha+beta   # mnemonics: alpha plus beta\n    aMb = alpha-beta   # mnemonics: alpha minus beta\n\n    Pn  = numpy.ones(x.shape)\n    Pn1 = 0.5*(aMb+(aPb+2.0)*x)\n\n    if m == 0:\n        Pm = Pn\n    elif m == 1:\n        Pm = Pn1\n    else:\n        for n in range(1, m+1):\n            n1 = n+1.0\n            n2 = 2.0*n\n\n            a1n = 2.0*n1*( n1+aPb )*( n2+aPb )\n            a2n = ( n2+aPb+1.0 )*aPb*aMb\n            a3n = ( n2+aPb )*( n2+aPb+1.0 )*( n2+aPb+2.0 )\n            a4n = 2.0*( n+alpha )*( n+beta )*( n2+aPb+2.0 )\n\n            Pn2 = ( ( a2n+a3n*x )*Pn1-a4n*Pn )/a1n\n            Pn  = Pn1\n            Pn1 = Pn2\n\n        Pm = Pn\n\n    if number_flag:\n        return Pm[0]\n    else:\n        return Pm\n \n#-- jacobi_p.py ----------------------------------------------------------------\n", "meta": {"hexsha": "4b1d9f0ea0c69369aadd593a23645b16106e8d80", "size": 1178, "ext": "py", "lang": "Python", "max_stars_repo_path": "lessons/08_dg/jacobi_p.py", "max_stars_repo_name": "albertonogueira/numerical-mooc", "max_stars_repo_head_hexsha": "dd95e650310502b5cdfe6e405ed7ab7e1496d233", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-02-10T12:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-10T12:09:09.000Z", "max_issues_repo_path": "lessons/08_dg/jacobi_p.py", "max_issues_repo_name": "albertonogueira/numerical-mooc", "max_issues_repo_head_hexsha": "dd95e650310502b5cdfe6e405ed7ab7e1496d233", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lessons/08_dg/jacobi_p.py", "max_forks_repo_name": "albertonogueira/numerical-mooc", "max_forks_repo_head_hexsha": "dd95e650310502b5cdfe6e405ed7ab7e1496d233", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.56, "max_line_length": 80, "alphanum_fraction": 0.4728353141, "include": true, "reason": "import numpy", "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.9252299653388754, "lm_q1q2_score": 0.8704468640258229}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport numpy.linalg\n\n# Question 3\ndef conjgrad (A, b, x = None, iterations = 10**6, epsilon = 10**(-10)):\n    \"\"\"\n        Méthode du gradient conjugué.\n        -----------------------------\n        Entrée:\n            A matrice symétrique définie positive.\n            b vecteur colonne.\n            (optional) x vecteur initial de la suite.\n            (optional) iterations nombre d'itérations maximales pour apporcher la solution.\n            (optional) epsilon précision minimale pour approcher la solution.\n        Sortie:\n            x solution approchée de Ax=b.\n    \"\"\"\n    if not x:\n        x = np.matrix(np.zeros([len(A),1]))\n\n    r = b - A*x\n    p = r\n    rsold = (r.T * r)[0,0]\n    rsnew = epsilon**2 + 1\n\n    i = 1\n    while i < iterations and np.sqrt(rsnew) > epsilon:\n        Ap = A*p\n        alpha= rsold/((p.T*Ap)[0,0])\n        x = x + alpha*p\n       #recuperer la valeur dans la matrice de taille 1.\n        r = r - alpha*Ap\n        rsnew = (r.T * r)[0,0]\n\n        #print rsnew\n        p = r + rsnew / (rsold*p)\n        rsold = rsnew\n        i+=1\n    return x\n\n# Question 4\ndef conjgrad_precond (A, b, M, x = None, iterations = 10**6, epsilon = 10**(-10)):\n    \"\"\"\n        Méthode du gradient conjugué, avec préconditioneur.\n        -----------------------------\n        Entrée:\n            A matrice symétrique définie positive.\n            b vecteur colonne.\n            M matrice préconditionneuse.\n            (optional) x vecteur initial de la suite.\n            (optional) iterations nombre d'itérations maximales pour apporcher la solution.\n            (optional) epsilon précision minimale pour approcher la solution.\n        Sortie:\n            x solution approchée de Ax=b.\n    \"\"\"\n    if not x:\n        x = np.matrix(np.zeros([len(A),1]))\n    xold = x\n    rold = b - A*x\n    zold = M.I*rold\n    p = zold\n\n    rnew = [epsilon**2 + 1]\n    i = 1\n    while i < iterations and numpy.linalg.norm(rnew) > epsilon:\n        Ap = A*p\n        alphaold = ((rold.T * zold)/(p.T*Ap))[0,0]\n        xnew= xold + alphaold*p\n        rnew = rold - alphaold*Ap\n        znew = M.I*rnew\n        betaold = (znew.T*rnew)[0,0] / (zold.T*rold)[0,0]\n        p = znew + betaold*p\n\n        rold = rnew\n        zold = znew\n        xold = xnew\n        i+=1\n    return xnew", "meta": {"hexsha": "47f6656cc23a02cc4751c1b9892329fc33b9445a", "size": 2336, "ext": "py", "lang": "Python", "max_stars_repo_path": "2-linear-systems-solving/ex2.py", "max_stars_repo_name": "gdzx/numerical-algorithms", "max_stars_repo_head_hexsha": "1bdea5c70a5bb8fd589f95e73ed476b90693fcf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2-linear-systems-solving/ex2.py", "max_issues_repo_name": "gdzx/numerical-algorithms", "max_issues_repo_head_hexsha": "1bdea5c70a5bb8fd589f95e73ed476b90693fcf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2-linear-systems-solving/ex2.py", "max_forks_repo_name": "gdzx/numerical-algorithms", "max_forks_repo_head_hexsha": "1bdea5c70a5bb8fd589f95e73ed476b90693fcf0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8395061728, "max_line_length": 91, "alphanum_fraction": 0.5239726027, "include": true, "reason": "import numpy", "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661028358093, "lm_q2_score": 0.9124361598816667, "lm_q1q2_score": 0.870433167528785}}
{"text": "import numpy as np\nnp.set_printoptions(suppress=True)\nimport matplotlib.pyplot as plt\n\ndef gradient_descent(X, y, theta, iterations, alpha):\n\tm = X.shape[0]\n\t\n\tdef compute_cost(X, y, theta):\n\t\t#easy way\n\t\t#error = 0\n\t\t\n\t\t#for i in range(m):\n\t\t#\thypothesis = X[i][0] * theta[0] + X[i][1] * theta[1]\n\t\t#\terror += (hypothesis - y[i])**2\n\n\t\t#linear algebra way\n\t\thypothesis = np.dot(X, theta) #dot product\n\t\terror = np.sum((hypothesis - y) ** 2)\n\n\t\treturn error / (2 * m)\n\t\n\tcost_history = []\n\t\n\tfor i in range(iterations):\n\t\thypothesis = np.matmul(X, theta)\n\t\t\n\t\tfor j in range(theta.shape[0]):\n\t\t\ttheta[j] = theta[j] - alpha * np.sum((hypothesis - y) * X[:, j]) / m\n\t\t\t\n\t\tcost_history.append(compute_cost(X, y, theta))\n\t\t\n\treturn theta, cost_history\n\t\ndef plot_cost_history(cost_history):\n\tplt.clf()\n\tplt.title('Cost J x iterations')\n\t\n\tplt.ylabel('Cost J')\n\tplt.xlabel('Number of iterations')\n\n\tplt.plot(cost_history, 'g.')\n\t\n\tplt.show()\n\t\nif __name__ == '__main__':\n\t# Initialization\n\t## Import data\n\tdata = np.loadtxt(\"ex1data1.txt\", delimiter=\",\")\n\n\t## Initialize important variables\n\tm = data.shape[0]\n\talpha = 0.01\n\t\n\tfor iterations in [100, 1500, 3000]:\n\t\ttheta = np.zeros(2)\n\n\t\t# Evaluation\n\t\t## Create the bias column, set to 1\n\t\tX = np.stack((np.ones(m), data[:, 0]), axis=-1)\n\t\t  \n\t\t## Second column of data\n\t\ty = data[:, 1]\n\n\t\ttheta, cost_history = gradient_descent(X, y, theta, iterations, alpha)\n\t\t\n\t\tplt.plot(data[:, 0], np.matmul(X,theta), '-', label='linear regression using %d iterations' % iterations)\n\n\t\tprint('Theta found by gradient descent', theta);\n\n\t\t# Predictions\n\t\tprint('For population = 35,000, we predict a profit of', np.matmul(np.array([1, 3.5]), theta) * 10000)\n\t\tprint('For population = 70,000, we predict a profit of', np.matmul(np.array([1, 7]), theta) * 10000)\n\t\tprint()\n\t\t\n\t#plot_cost_history(cost_history)\n\t\t\n\t# Show Results\n\tplt.ylabel('Profit in $10,000s')\n\tplt.xlabel('Population of City in $10,000s')\n\n\tplt.plot(data[:, 0], data[:, 1], 'rx', label='Training data')\n\t\n\tplt.legend()\n\tplt.show()\n", "meta": {"hexsha": "6206d557bb8fd9978740e8b2f9754c11560a5bb4", "size": 2034, "ext": "py", "lang": "Python", "max_stars_repo_path": "ex1.py", "max_stars_repo_name": "fredericoschardong/programming-exercise-1-linear-regression-university-of-stanford", "max_stars_repo_head_hexsha": "de90c9984d16b58a17c49d483b2abc76daa31071", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex1.py", "max_issues_repo_name": "fredericoschardong/programming-exercise-1-linear-regression-university-of-stanford", "max_issues_repo_head_hexsha": "de90c9984d16b58a17c49d483b2abc76daa31071", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex1.py", "max_forks_repo_name": "fredericoschardong/programming-exercise-1-linear-regression-university-of-stanford", "max_forks_repo_head_hexsha": "de90c9984d16b58a17c49d483b2abc76daa31071", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-09T05:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-15T01:51:07.000Z", "avg_line_length": 23.9294117647, "max_line_length": 107, "alphanum_fraction": 0.6450344149, "include": true, "reason": "import numpy", "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957912273285902, "lm_q2_score": 0.9086179018818865, "lm_q1q2_score": 0.8703762399399446}}
{"text": "import numpy\nimport sympy\nfrom matplotlib import pyplot\nfrom sympy.utilities.lambdify import lambdify\n\n# Set the font family and size to use for Matplotlib figures.\npyplot.rcParams['font.family'] = 'serif'\npyplot.rcParams['font.size'] = 16\n\nsympy.init_printing()\n\nx, nu, t = sympy.symbols('x nu t')\nphi = (sympy.exp(-(x - 4 * t)**2 / (4 * nu * (t + 1))) +\n       sympy.exp(-(x - 4 * t - 2 * numpy.pi)**2 / (4 * nu * (t + 1))))\nphiprime = phi.diff(x)\n\nu = -2 * nu * (phiprime / phi) + 4\n\nu_lamb = lambdify((t, x, nu), u)\n\n# Set parameters.\nnx = 101  # number of spatial grid points\nL = 2.0 * numpy.pi  # length of the domain\ndx = L / (nx - 1)  # spatial grid size\nnu = 0.07  # viscosity\nnt = 100  # number of time steps to compute\nsigma = 0.1  # CFL limit\ndt = sigma * dx**2 / nu  # time-step size\n\n# Discretize the domain.\nx = numpy.linspace(0.0, L, num=nx)\n\n# Set initial conditions.\nt = 0.0\nu0 = numpy.array([u_lamb(t, xi, nu) for xi in x])\n\n# Integrate the Burgers' equation in time.\nu = u0.copy()\nfor n in range(nt):\n    un = u.copy()\n    # Update all interior points.\n    u[1:-1] = (un[1:-1] -\n               un[1:-1] * dt / dx * (un[1:-1] - un[:-2]) +\n               nu * dt / dx**2 * (un[2:] - 2 * un[1:-1] + un[:-2]))\n    # Update boundary points.\n    u[0] = (un[0] -\n            un[0] * dt / dx * (un[0] - un[-1]) +\n            nu * dt / dx**2 * (un[1] - 2 * un[0] + un[-1]))\n    u[-1] = (un[-1] -\n            un[-1] * dt / dx * (un[-1] - un[-2]) +\n            nu * dt / dx**2 * (un[0] - 2 * un[-1] + un[-2]))\n\n# Compute the analytical solution.\nu_analytical = numpy.array([u_lamb(nt * dt, xi, nu) for xi in x])\n\n\n\n# Plot the numerical solution along with the analytical solution.\npyplot.figure(figsize=(6.0, 4.0))\npyplot.xlabel('x')\npyplot.ylabel('u')\npyplot.grid()\npyplot.plot(x, u, label='Numerical',\n            color='C0', linestyle='-', linewidth=2)\npyplot.plot(x, u_analytical, label='Analytical',\n            color='C1', linestyle='--', linewidth=2)\npyplot.legend()\npyplot.xlim(0.0, L)\npyplot.ylim(0.0, 10.0);\npyplot.show()\npyplot.clf()\n\n\n\n", "meta": {"hexsha": "7083a86c612b80669b93d39d4a5588edc2004192", "size": 2057, "ext": "py", "lang": "Python", "max_stars_repo_path": "lessons/02_spacetime/working/space_time.py", "max_stars_repo_name": "PaulM5406/numerical-mooc", "max_stars_repo_head_hexsha": "8d58349b5bf6f543514d2c17311df2c1282ba297", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lessons/02_spacetime/working/space_time.py", "max_issues_repo_name": "PaulM5406/numerical-mooc", "max_issues_repo_head_hexsha": "8d58349b5bf6f543514d2c17311df2c1282ba297", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lessons/02_spacetime/working/space_time.py", "max_forks_repo_name": "PaulM5406/numerical-mooc", "max_forks_repo_head_hexsha": "8d58349b5bf6f543514d2c17311df2c1282ba297", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4266666667, "max_line_length": 70, "alphanum_fraction": 0.5668449198, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813394, "lm_q2_score": 0.9086178981700931, "lm_q1q2_score": 0.870376233109202}}
{"text": "#!/usr/bin/env python\n\"\"\"\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as st\n\nn = 100\npcoin = 0.62 # actual value of p for coin\nresults = st.bernoulli(pcoin).rvs(n)\nh = sum(results)\nprint results\nprint(\"we observed %s heads out of %s\"%(h,n))\n\n## Expected distribution for fair coin\np = 0.5\nrv = st.binom(n, p)\nmu = rv.mean()\nsd = rv.std()\nprint(\"The expected distribution for a fair coin is mu=%s, sd=%s\"%(mu,sd))\n\n## if we move into a hypothesis testing framework\n# we can use the binomial test\nprint(\"binomial test - %s\"%st.binom_test(h, n, p))\n\n## normal approximation for binomal\nz = (h-0.5-mu)/sd\nprint(\"normal approx for binomial - %s\"%(2*(1 - st.norm.cdf(z))))\n\n## can use simulation to test things as well\nnsamples = 100000\nxs = np.random.binomial(n, p, nsamples)\nprint(\"simulation p-value - %s\"%(2*np.sum(xs >= h)/(xs.size + 0.0)))\n\n## MLE\nprint(\"Maximum likelihood %s\"%(np.sum(results)/float(len(results))))\nbs_samples = np.random.choice(results, (nsamples, len(results)), replace=True)\nbs_ps = np.mean(bs_samples, axis=1)\nbs_ps.sort()\nprint \"Bootstrap CI: (%.4f, %.4f)\" % (bs_ps[int(0.025*nsamples)], bs_ps[int(0.975*nsamples)])\n\n## The Bayesian approach directly estimates the posterior distribution\n## all other point/interval statistics can be estimated from posterior\n\nfig  = plt.figure()\nax = fig.add_subplot(111)\n\na, b = 10, 10\nprior = st.beta(a, b)\npost = st.beta(h+a, n-h+b)\nci = post.interval(0.95)\nmap_ =(h+a-1.0)/(n+a+b-2.0)\n\nxs = np.linspace(0, 1, 100)\nax.plot(prior.pdf(xs), label='Prior')\nax.plot(post.pdf(xs), label='Posterior')\nax.axvline(mu, c='red', linestyle='dashed', alpha=0.4)\nax.set_xlim([0, 100])\nax.axhline(0.3, ci[0], ci[1], c='black', linewidth=2, label='95% CI');\nax.axvline(n*map_, c='blue', linestyle='dashed', alpha=0.4)\nax.legend()\n\nplt.savefig(\"coin-toss.png\")\n", "meta": {"hexsha": "939cbfbb7ca7cef16f75517eceb591a673dc56e5", "size": 1836, "ext": "py", "lang": "Python", "max_stars_repo_path": "archive/pymc3/coin-flip.py", "max_stars_repo_name": "ajrichards/bayesian-examples", "max_stars_repo_head_hexsha": "fbd87c6f1613ea516408e9ebc3c9eff1248246e4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-01-27T08:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-17T02:21:34.000Z", "max_issues_repo_path": "archive/pymc3/coin-flip.py", "max_issues_repo_name": "ajrichards/notebook", "max_issues_repo_head_hexsha": "fbd87c6f1613ea516408e9ebc3c9eff1248246e4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "archive/pymc3/coin-flip.py", "max_forks_repo_name": "ajrichards/notebook", "max_forks_repo_head_hexsha": "fbd87c6f1613ea516408e9ebc3c9eff1248246e4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8181818182, "max_line_length": 93, "alphanum_fraction": 0.6781045752, "include": true, "reason": "import numpy,import scipy", "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075755433748, "lm_q2_score": 0.904650541527608, "lm_q1q2_score": 0.870371139223128}}
{"text": "import matplotlib as mpl\nmpl.use('TkAgg')\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport scipy.optimize as opt\nfrom plotData import *\nimport costFunction as cf\nimport plotDecisionBoundary as pdb\nimport predict as predict\nfrom sigmoid import *\n\n# Load data\n# The first two columns contain the exam scores and the third column contains the label.\ndata = pd.read_csv('ex2data1.txt', sep=',', header=None, names=['Exam1', 'Exam2', 'Admitted'])\n\ncols = data.shape[1]\nX = data.iloc[:, :cols - 1]\ny = data.iloc[:, cols - 1:]\n\n# ===================== Part 1: Plotting =====================\nprint('Plotting Data with + indicating (y = 1) examples and o indicating (y = 0) examples.')\npos = data[data.Admitted.isin([1])]\nneg = data[data.Admitted.isin([0])]\n\nfig, ax = plt.subplots()\nax.scatter(pos['Exam1'], pos['Exam2'], c='b', marker='o', label='Admitted')\nax.scatter(neg['Exam1'], neg['Exam2'], c='r', marker='+', label='Not admitted')\nplt.axis([30, 100, 30, 100])\nplt.legend(loc=1)\nplt.xlabel('Exam 1 score')\nplt.ylabel('Exam 2 score')\n\ninput('Program paused. Press ENTER to continue')\n\n# ===================== Part 2: Compute Cost and Gradient =====================\n# In this part of the exercise, you will implement the cost and gradient\n# for logistic regression. You need to complete the code in\n# costFunction.py\n\n# Setup the data array appropriately, and add ones for the intercept term\n(m, n) = X.shape\n\n# Add intercept term\nX.insert(0, 'Ones', 1)\n\n# Initialize fitting parameters\ninitial_theta = np.zeros((n + 1, 1))\n\n# Compute and display initial cost and gradient\ncost, grad = cf.cost_function(initial_theta, X, y)\nnp.set_printoptions(formatter={'float': '{: 0.4f}\\n'.format})\n\nprint('Cost at initial theta (zeros): {:0.3f}'.format(cost))\nprint('Expected cost (approx): 0.693')\nprint('Gradient at initial theta (zeros): \\n{}'.format(grad))\nprint('Expected gradients (approx): \\n-0.1000\\n-12.0092\\n-11.2628')\n\n# Compute and display cost and gradient with non-zero theta\ntest_theta = np.array([[-24], [0.2], [0.2]])\ncost, grad = cf.cost_function(test_theta, X, y)\n\nprint('Cost at test theta (zeros): {}'.format(cost))\nprint('Expected cost (approx): 0.218')\nprint('Gradient at test theta: \\n{}'.format(grad))\nprint('Expected gradients (approx): \\n0.043\\n2.566\\n2.647')\n\ninput('Program paused. Press ENTER to continue')\n\n# ===================== Part 3: Optimizing using fmin_bfgs =====================\n# In this exercise, you will use a built-in function (opt.fmin_bfgs) to find the\n# optimal parameters theta\n\n\ndef cost_func(t, X, y):\n    t = t.reshape((len(t), 1))\n    return cf.cost_function(t, X, y)[0]\n\n\ndef grad_func(t, X, y):\n    t = t.reshape((len(t), 1))\n    return cf.cost_function(t, X, y)[1]\n\n\ninitial_theta = np.zeros(3)\n# Run fmin_bfgs to obtain the optimal theta\nres = opt.minimize(fun=cost_func, x0=initial_theta, args=(X, y), method='BFGS', jac=grad_func)\ntheta = res.x\ncost = res.fun\n\nprint('Cost at theta found by fmin: {:0.4f}'.format(cost))\nprint('Expected cost (approx): 0.203')\nprint('theta: \\n{}'.format(theta))\nprint('Expected Theta (approx): \\n-25.161\\n0.206\\n0.201')\n\n# Plot boundary\npdb.plot_decision_boundary(theta, X)\nplt.show()\n\ninput('Program paused. Press ENTER to continue')\n\n# ===================== Part 4: Predict and Accuracies =====================\n# After learning the parameters, you'll like to use it to predict the outcomes\n# on unseen data. In this part, you will use the logistic regression model\n# to predict the probability that a student with score 45 on exam 1 and\n# score 85 on exam 2 will be admitted\n#\n# Furthermore, you will compute the training and test set accuracies of our model.\n#\n# Your task is to complete the code in predict.py\n\n# Predict probability for a student with score 45 on exam 1\n# and score 85 on exam 2\n\nprob = sigmoid(np.array([1, 45, 85]).dot(theta.reshape((len(theta), 1))))\nprint('For a student with scores 45 and 85, we predict an admission probability of {:0.4f}'.format(prob[0]))\nprint('Expected value : 0.775 +/- 0.002')\n\n# Compute the accuracy on our training set\np = predict.predict(theta.reshape((len(theta), 1)), X)\n\ncount = 0\nfor i in range(m):\n    if p[i] == y['Admitted'][i]:\n        count += 1\nprint('Train accuracy: {}'.format(count / m * 100))\nprint('Expected accuracy (approx): 89.0')\n\ninput('ex2 Finished. Press ENTER to exit')\n", "meta": {"hexsha": "4881ed293b41892b707f4d0a6a312ac3609da231", "size": 4351, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine-learning-ex2/ex2/ex2.py", "max_stars_repo_name": "GuoHongke/coursera-ml-py", "max_stars_repo_head_hexsha": "8b1e9fb238aafbeb387c46cacd72aea2592be82e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "machine-learning-ex2/ex2/ex2.py", "max_issues_repo_name": "GuoHongke/coursera-ml-py", "max_issues_repo_head_hexsha": "8b1e9fb238aafbeb387c46cacd72aea2592be82e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "machine-learning-ex2/ex2/ex2.py", "max_forks_repo_name": "GuoHongke/coursera-ml-py", "max_forks_repo_head_hexsha": "8b1e9fb238aafbeb387c46cacd72aea2592be82e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.213740458, "max_line_length": 108, "alphanum_fraction": 0.6752470696, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.9353465089404038, "lm_q1q2_score": 0.8703008791875486}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom plot_functions import plot_mutliplot_bilinear\n\n\ndx = 0.1  # The resolution in x\ndy = 0.1  # The resolution in y\n\nlx = 50 # How long are kernels in the x direction\nly = 50 # The long are kernels in the y direction\n\n# Create the positions\nx = np.arange(-lx/2, lx/2, dx)\ny = np.arange(-ly/2, ly/2, dy)\n\nsigma_center = 15  # Size of the center area\nsigma_surround = 7  # Size of the surround area\n\n# This is for the two dimensional pattern\nX, Y = np.meshgrid(x, y)\nR = np.sqrt(X**2 + Y**2)  # Distance\ncenter = (17.0 / sigma_center**2) * np.exp(-(R / sigma_center)**2)\nsurround = (16.0 / sigma_surround**2) * np.exp(-(R / sigma_surround)**2)\nZ = surround - center \n\n# Plot countour map \nplt.contourf(X, Y, Z, 50, alpha=0.75, cmap=plt.cm.hot)\nplt.colorbar()\n \nC = plt.contour(X, Y, Z, 10, colors='black', linewidth=.5)\nplt.clabel(C, inline=10, fontsize=10)\nplt.show()\n\n# One dimensionall side view \ncenter = (17.0 / sigma_center**2) * np.exp(-(x / sigma_center)**2)\nsurround = surround = (16.0 / sigma_surround**2) * np.exp(-(x / sigma_surround)**2)\nz1 = surround - center \n\nplt.plot(x,z1)\n\nplt.show()\n\n##  Now we code the temporal pattern \n\n# First the kernel size and resolution \nkernel_size = 25\ndt_kernel = 10\nt = np.arange(0, kernel_size * dt_kernel, dt_kernel) # Time vector \n\n## Temporal parameters\nK1 = 1.05\nK2 = 0.7\nc1 = 0.14\nc2 = 0.12\nn1 = 7.0\nn2 = 8.0\nt1 = -6.0\nt2 = -6.0\ntd = 6.0\n\np1 = K1 * ((c1*(t - t1))**n1 * np.exp(-c1*(t - t1))) / ((n1**n1) * np.exp(-n1))\np2 = K2 * ((c2*(t - t2))**n2 * np.exp(-c2*(t - t2))) / ((n2**n2) * np.exp(-n2))\np3 = p1 - p2\n\n\nplt.plot(t, p3, label='temporal kernel')\nplt.xlabel('time (ms)')\nplt.legend()\nplt.show()\n\n\n## Now create the spatio-temporal filter \n\n# Initialize and fill the spatio-temporal kernel  \nkernel = np.zeros((kernel_size, int(lx/dx), int(ly/dy)))\n\nfor k, p in enumerate(p3):\n    kernel[k,...] = p * Z\n    \nplot_mutliplot_bilinear(25,kernel, colorbar=True, symmetric=2)\np\n\nplt.show()\n", "meta": {"hexsha": "dac447140cf2e6e5248a354f7405aab48737258f", "size": 1997, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/blog_retinal_filter.py", "max_stars_repo_name": "sinodanishspain/BioMulti-L-NL-Model", "max_stars_repo_head_hexsha": "ce3ef6834f82d14c3a9b44f6ce79175c79fed432", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-20T15:40:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:58:50.000Z", "max_issues_repo_path": "python/blog_retinal_filter.py", "max_issues_repo_name": "sinodanish/BioMulti-L-NL-Model", "max_issues_repo_head_hexsha": "ce3ef6834f82d14c3a9b44f6ce79175c79fed432", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-02T19:36:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-07T12:10:29.000Z", "max_forks_repo_path": "python/blog_retinal_filter.py", "max_forks_repo_name": "sinodanishspain/BioMulti-L-NL-Model", "max_forks_repo_head_hexsha": "ce3ef6834f82d14c3a9b44f6ce79175c79fed432", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7738095238, "max_line_length": 83, "alphanum_fraction": 0.6474712068, "include": true, "reason": "import numpy", "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104953173166, "lm_q2_score": 0.900529778109184, "lm_q1q2_score": 0.8702814289104898}}
{"text": "\"\"\"\nCreated on Thu Apr  1 03:05:09 2021\n\"\"\"\n\nfrom typing import List\n\nimport numpy as np\n\nListOfFloats = List[float, float, float]\n\n\ndef distance_formula(final_coordinates: ListOfFloats,\n                     initial_coordinates: ListOfFloats = None,\n                     deg_rad: str = 'rad') -> float:\n    \"\"\"\n    Calculates the distance between two given points in spherical coordinate system\n    Parameters\n    ----------\n    final_coordinates: List[float, float, float]\n        Final coordinates of the point to which the distance is to be calculated.\n    initial_coordinates: List[float, float, float]\n        Reference coordinates of the point. The default is None.\n    deg_rad: str, optional\n        Whether the specified theta and phi arguments are in degree or radians.\n        The default is 'rad'.\n\n    Returns\n    ----------\n    float:\n        Distance between two points in spherical coordinates\n    \"\"\"\n\n    if initial_coordinates is None:\n        initial_coordinates = [0, 0, 0]\n\n    r1, theta1, phi1 = initial_coordinates\n    r2, theta2, phi2 = final_coordinates\n\n    theta1, phi1 = np.radians([theta1, phi1]) if deg_rad == 'deg' else theta2, phi1\n    theta2, phi2 = np.radians([theta2, phi2]) if deg_rad == 'deg' else theta2, phi2\n\n    p1 = r1**2 + r2**2\n\n    _comp1 = np.sin(theta1) * np.sin(theta2) * np.cos(phi1 - phi2)\n    _comp2 = np.cos(theta1) * np.cos(theta2)\n\n    p2 = 2 * r1 * r2 * (_comp1 + _comp2)\n\n    return np.sqrt(p1 - p2)\n", "meta": {"hexsha": "e9511307391065c6dc4a948d050f570d00ddcbb9", "size": 1456, "ext": "py", "lang": "Python", "max_stars_repo_path": "002__spherical_coordinate_system/distance_formula.py", "max_stars_repo_name": "AstrophysicsAndPython/astrophysicsandpython__main", "max_stars_repo_head_hexsha": "b8f8d38ee38865eea8c742c1964aeabec1c510bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "002__spherical_coordinate_system/distance_formula.py", "max_issues_repo_name": "AstrophysicsAndPython/astrophysicsandpython__main", "max_issues_repo_head_hexsha": "b8f8d38ee38865eea8c742c1964aeabec1c510bb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-02-10T08:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T19:43:04.000Z", "max_forks_repo_path": "002__spherical_coordinate_system/distance_formula.py", "max_forks_repo_name": "AstrophysicsAndPython/astrophysicsandpython__main", "max_forks_repo_head_hexsha": "b8f8d38ee38865eea8c742c1964aeabec1c510bb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.12, "max_line_length": 83, "alphanum_fraction": 0.6407967033, "include": true, "reason": "import numpy", "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966410491447634, "lm_q2_score": 0.9005297794439688, "lm_q1q2_score": 0.8702814267156754}}
{"text": "import math\nimport numpy as np\n# Note: please don't add any new package, you should solve this problem using only the packages above.\n#-------------------------------------------------------------------------\n'''\n    Problem 1: Linear Regression (Maximum Likelihood)\n    In this problem, you will implement the linear regression method based upon maximum likelihood (least square).\n    w'x + b = y\n    You could test the correctness of your code by typing `nosetests -v test1.py` in the terminal.\n    Note: please don't use any existing package for linear regression problem, implement your own version.\n'''\n\n#--------------------------\ndef compute_Phi(x,p):\n    '''\n        Compute the design matrix Phi of x for polynoial curve fitting problem. \n        We will construct p polynoials a the p features of the data samples. \n        The features of each sample, is x^0, x^1, x^2 ... x^(p-1)\n        Input:\n            x : a vector of samples in one dimensional space, a numpy vector of shape n by 1.\n                Here n is the number of samples.\n            p : the number of polynomials/features\n        Output:\n            Phi: the design/feature matrix of x, a numpy matrix of shape (n by p).\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n\n\n\n\n    #########################################\n    return Phi \n\n\n#--------------------------\ndef least_square(Phi, y):\n    '''\n        Fit a linear model on training samples. Compute the paramter w using Maximum likelihood (equal to least square).\n        Input:\n            Phi: the design/feature matrix of the training samples, a numpy matrix of shape n by p\n                Here n is the number of training samples, p is the number of features\n            y : the sample labels, a numpy vector of shape n by 1.\n        Output:\n            w: the weights of the linear regression model, a numpy float vector of shape p by 1. \n        Hint: you could use np.linalg.inv() to compute the inverse of a matrix\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n\n\n    #########################################\n    return w \n\n\n\n", "meta": {"hexsha": "ef2ff378844ef2c4ce8f1b1decc5e3b737efc37c", "size": 2144, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW6/problem2.py", "max_stars_repo_name": "anurag3/DS501", "max_stars_repo_head_hexsha": "4a03100e1c221be2f2cdd99f74e006dc9827aa00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW6/problem2.py", "max_issues_repo_name": "anurag3/DS501", "max_issues_repo_head_hexsha": "4a03100e1c221be2f2cdd99f74e006dc9827aa00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW6/problem2.py", "max_forks_repo_name": "anurag3/DS501", "max_forks_repo_head_hexsha": "4a03100e1c221be2f2cdd99f74e006dc9827aa00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3389830508, "max_line_length": 120, "alphanum_fraction": 0.5578358209, "include": true, "reason": "import numpy", "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104933824754, "lm_q2_score": 0.9005297754396142, "lm_q1q2_score": 0.8702814245882073}}
{"text": "import numpy as np\n\ndef arc(center, radius, start_angle, end_angle, resolution=100):\n    \"\"\"Draws an arc\n\n    Args:\n        center (pair): the center of the circle inferred by the arc\n        radius (float): the radius of the circle inferred by the arc\n        start_angle (float): the starting angle position of the arc\n        end_angle (float): the ending angle position of the arc\n    \n    Returns:\n        layer: A layer.\n    \"\"\"\n    linspace = np.linspace(0., 1., resolution)\n    angles = start_angle + (end_angle - start_angle) * linspace\n    return (\n        (np.cos(angles) * radius) + center[0],\n        (np.sin(angles) * radius) + center[1],\n    )\n\ndef circle(center, radius, resolution=100):\n    return arc(center, radius, 0, 2*np.pi, resolution)\n\ndef line(origin, end=None, vector=None, length=None, angle=None, resolution=2):\n    \"\"\"Draws a line. One of these must be specified: end, vector, or (length, angle)\n\n    Args:\n        origin (pair): the origin of the line\n        end (pair): optional. the coordinates of end of the line\n        vector (pair): optional. the x and y lengths of the line\n        length (float): optional. the length of the line\n        angle (float): optional. the angle of the line\n    \n    Returns:\n        layer: A layer.\n    \"\"\"\n\n    if end is not None:\n        return (\n            np.linspace(origin[0], end[0], resolution), \n            np.linspace(origin[1], end[1], resolution)\n        )\n\n    if vector is not None:\n        return (\n            np.linspace(origin[0], origin[0] + vector[0], resolution), \n            np.linspace(origin[1], origin[1] + vector[1], resolution)\n        )\n\n    if length is not None and angle is not None:\n        return (\n            np.linspace(origin[0], origin[0] + length * np.cos(angle), resolution), \n            np.linspace(origin[1], origin[1] + length * np.sin(angle), resolution)\n        )\n\ndef hexagon(center, diameter=1.0, resolution=2):\n    return ngon(6, center, diameter, resolution)\n\ndef ngon(n, origin=(0,0), diameter=1.0, resolution=2):\n    segment_length = 2 * np.sin(np.pi / n)\n    ngon_inner_angle = np.pi * (n - 2) / n\n    ngon_outer_angle = np.pi - ngon_inner_angle\n\n    segments = []\n    for i in range(n):\n        if i == 0:\n            from_pt = origin\n        else:\n            last_segment = segments[-1]\n            from_pt = (last_segment[0][-1], last_segment[1][-1])\n\n        segment = line(from_pt, length=segment_length, angle=i*ngon_outer_angle, resolution=resolution)\n        segments.append(segment)\n\n    segments.append(([np.nan], [np.nan]))\n    \n    ngon_layer = (\n        np.concatenate([s[0] for s in segments]),\n        np.concatenate([s[1] for s in segments])\n    )\n\n    return ngon_layer\n\n", "meta": {"hexsha": "5d64ccd9a1dd204ffa2dcb0ebb6b58aafcfb5373", "size": 2712, "ext": "py", "lang": "Python", "max_stars_repo_path": "penkit/shapes.py", "max_stars_repo_name": "shab-bahmanyar/penkit", "max_stars_repo_head_hexsha": "303c259c762c162935043c808eeb23465c303596", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 122, "max_stars_repo_stars_event_min_datetime": "2017-12-11T02:30:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T08:02:56.000Z", "max_issues_repo_path": "penkit/shapes.py", "max_issues_repo_name": "shab-bahmanyar/penkit", "max_issues_repo_head_hexsha": "303c259c762c162935043c808eeb23465c303596", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-07-06T23:12:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-31T22:39:14.000Z", "max_forks_repo_path": "penkit/shapes.py", "max_forks_repo_name": "shab-bahmanyar/penkit", "max_forks_repo_head_hexsha": "303c259c762c162935043c808eeb23465c303596", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-03-26T12:46:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T16:12:56.000Z", "avg_line_length": 31.9058823529, "max_line_length": 103, "alphanum_fraction": 0.6021386431, "include": true, "reason": "import numpy", "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992905050947, "lm_q2_score": 0.8991213806488609, "lm_q1q2_score": 0.8702589464079937}}
{"text": "import numpy as np\nimport pandas as pd\n\ndef accuracy_score(y_true, y_pred):\n\n    \"\"\"\n    Classification performance metric that computes the accuracy of y_true\n    and y_pred.\n    :param numpy.array y_true: array-like of shape (n_samples,) Ground truth correct labels.\n    :param numpy.array y_pred: array-like of shape (n_samples,) Estimated target values.\n    :returns: C (float) Accuracy score.\n    \"\"\"\n\n    \"\"\"\n    Verifica quais são as previsões que são iguais aos valores reais\n    \"\"\"\n\n    correct = 0\n    for true, pred in zip(y_true, y_pred):\n        if true == pred:\n            correct += 1\n    accuracy = correct / len(y_true)\n    return accuracy\n\ndef mse(y_true, y_pred, squared = True):\n    \n    \"\"\"\n    Mean squared error regression loss function.\n    Parameters\n    :param numpy.array y_true: array-like of shape (n_samples,)\n        Ground truth (correct) target values.\n    :param numpy.array y_pred: array-like of shape (n_samples,)\n        Estimated target values.\n    :param bool squared: If True returns MSE, if False returns RMSE. Default=True\n    :returns: loss (float) A non-negative floating point value (the best value is 0.0).\n    \"\"\"\n    \n    \"\"\"\n    Mean squared error\n    \"\"\"\n    \n    y_true = np.array(y_true)\n    y_pred = np.array(y_pred)\n    errors = np.average((y_true - y_pred) ** 2, axis = 0)\n    if not squared:\n        errors = np.sqrt(errors)\n    return np.average(errors)\n\ndef mse_prime(y_true, y_pred):\n    return 2 * (y_pred - y_true) / y_true.size\n\ndef cross_entropy(y_true, y_pred):\n    return - (y_true * np.log(y_pred)).sum()\n\ndef cross_entropy_prime(y_true, y_pred):\n    return y_pred - y_true\n\ndef r2_score(y_true, y_pred):\n\n    \"\"\"\n    R^2 regression score function.\n        R^2 = 1 - SS_res / SS_tot\n    where SS_res is the residual sum of squares and SS_tot is the total\n    sum of squares.\n    \n    :param numpy.array y_true : array-like of shape (n_samples,) Ground truth (correct) target values.\n    :param numpy.array y_pred : array-like of shape (n_samples,) Estimated target values.\n    :returns: score (float) R^2 score.\n    \"\"\"\n\n    # residual sum of squares\n    numerator = ((y_true - y_pred) ** 2).sum(axis = 0)\n    # total sum of squares\n    denominator = ((y_true - np.average(y_true, axis = 0)) ** 2).sum(axis = 0)\n    # r^2\n    score = 1 - numerator / denominator\n    return score\n\nclass ConfusionMatrix:\n\n    def __call__(self, true_y, pred_y):\n        self.true = np.array(true_y)\n        self.pred = np.array(pred_y)\n        return self.toDataFrame()\n\n    def calc(self):\n        conf = pd.crosstab(self.true, self.pred, rownames = ['Actual Values'], colnames = ['Predicted Values'], margins = True)\n        return conf\n\n    def toDataframe(self):\n        return pd.DataFrame(self.calc())\n\n", "meta": {"hexsha": "3963254267909cefc32103a1fcf59ebbf2defca5", "size": 2759, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/si/util/metrics.py", "max_stars_repo_name": "pg42876/potential-sniffle", "max_stars_repo_head_hexsha": "bc9894aad29c40dc3967bfadc933e3fb37be2d25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/si/util/metrics.py", "max_issues_repo_name": "pg42876/potential-sniffle", "max_issues_repo_head_hexsha": "bc9894aad29c40dc3967bfadc933e3fb37be2d25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/si/util/metrics.py", "max_forks_repo_name": "pg42876/potential-sniffle", "max_forks_repo_head_hexsha": "bc9894aad29c40dc3967bfadc933e3fb37be2d25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6666666667, "max_line_length": 127, "alphanum_fraction": 0.6476984415, "include": true, "reason": "import numpy", "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992905050948, "lm_q2_score": 0.8991213718636754, "lm_q1q2_score": 0.8702589379048189}}
{"text": "#!/usr/bin/env python\n\nimport numpy as np\nimport time \n\ndef eig_sorted(X):\n\tD,V = np.linalg.eig(X)\t\n\tlastV = None\n\tsort_needed = False\n\tfor m in D:\n\t\tif m > lastV and lastV != None:\n\t\t\tsort_needed = True\n\t\t\t#print 'Sort needed : \\t' , m, lastV\n\t\tlastV = m\n\t\n\tif sort_needed:\n\t\tidx = D.argsort()[::-1]   \n\t\tD = D[idx]\n\t\tV = V[:,idx]\t\n\n\treturn [V,D] \n\ndef multiply_until_converge(X, f, accuracy):\n\tfor p in range(1000):\n\t\tnew_f = X.dot(f)\n\t\tnew_f = new_f/np.max(new_f)\n\t\tif np.linalg.norm(new_f - f) < accuracy*np.linalg.norm(f):\n\t\t\t#print np.linalg.norm(new_f - f)\n\t\t\tprint 'iteration : ' , p\n\t\t\tbreak\n\t\telse:\n\t\t\tf = new_f\n\n\tf = f/np.linalg.norm(f)\n\treturn f\n\ndef power_eig(B, num_eigs, accuracy=0.0001, direction='largest first'): # direction = 'largest first' or 'smallest first'\n\tif B.shape[0] != B.shape[1]:\n\t\tprint 'Error : A must be a squared matrix'\n\t\treturn\n\n\td = B.shape[0]\n\teigValues = np.array([])\n\teigVects = np.empty((d, 0))\n\t\n\n\tif direction == 'smallest first':\n\t\tN = np.linalg.norm(B,1)\n\t\tX = N*np.eye(d) - B\n\t\t\n\t\tfor e in range(num_eigs):\n\t\t\tf = np.random.randn(d,1)\n\t\t\tf = multiply_until_converge(X, f, accuracy)\n\t\t\tev = f.T.dot(X).dot(f)\n\t\t\teig_value = N - ev\n\t\t\tX = X - ev*f.dot(f.T)\n\n\t\t\teigValues = np.append(eigValues, eig_value)\n\t\t\teigVects = np.hstack((eigVects, f))\n\telse:\n\t\tfor e in range(num_eigs):\n\t\t\tf = np.random.randn(d,1)\n\t\t\tf = multiply_until_converge(B, f, accuracy)\n\t\t\teig_value = f.T.dot(B).dot(f)\n\t\t\tB = B - eig_value*f.dot(f.T)\n\t\n\t\t\teigValues = np.append(eigValues, eig_value)\n\t\t\teigVects = np.hstack((eigVects, f))\n\n\treturn [eigVects, eigValues]\n\n\nif __name__ == \"__main__\":\n\tnp.set_printoptions(precision=4)\n\tnp.set_printoptions(threshold=np.nan)\n\tnp.set_printoptions(linewidth=300)\n\t\n\n\t\n\tA = np.random.randn(6,6)\n\tA = A.dot(A.T)\n\t[V,D] = eig_sorted(A)\n\n\tprint 'Truth eigen decomposition : ' \n\tprint V , '\\n\\n'\n\tprint D , '\\n----------\\n'\n\n\tprint 'Finding Largest 2 eigenvalues and vectors : \\n'\n\t[eigVects, eigValues] = power_eig(A,2, accuracy=0.00001)\n\tprint 'Eigenvectors : \\n',  eigVects , '\\n\\n'\n\tprint 'Eigenvalues : \\n', eigValues , '\\n----------\\n'\n\t\n\t\n\tprint 'Finding smallest 2 eigenvalues and vectors : \\n'\n\t[eigVects, eigValues] = power_eig(A,2, direction='smallest first')\n\tprint 'Eigenvectors : \\n',  eigVects , '\\n\\n'\n\tprint 'Eigenvalues : \\n', eigValues , '\\n----------\\n'\n\t\n\n\n\n\tprint 'Time difference '\n\tA = np.random.randn(500,500)\n\tA = A.dot(A.T)\n\n\tstart_time = time.time() \n\t[eigVects, eigValues] = power_eig(A,5, accuracy=0.00001)\n\tprint(\"Power Method : %s seconds ---\" % (time.time() - start_time))\n\n\tstart_time = time.time() \n\t[V,D] = eig_sorted(A)\n\tprint(\"Eig Method : %s seconds ---\" % (time.time() - start_time))\n\n\t#import pdb; pdb.set_trace()\n\t\n\t\n\t\n\t\n", "meta": {"hexsha": "5f55b18259219a30bb3f5cb88c9ff840b9abd08d", "size": 2716, "ext": "py", "lang": "Python", "max_stars_repo_path": "svd_approximation/power_method/power_eig.py", "max_stars_repo_name": "juliaprocess/ml_libs", "max_stars_repo_head_hexsha": "52cac5d64b55a12dfbdad1c768cdd8d79d5789f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-12T22:02:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T15:24:18.000Z", "max_issues_repo_path": "svd_approximation/power_method/power_eig.py", "max_issues_repo_name": "juliaprocess/ml_libs", "max_issues_repo_head_hexsha": "52cac5d64b55a12dfbdad1c768cdd8d79d5789f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "svd_approximation/power_method/power_eig.py", "max_forks_repo_name": "juliaprocess/ml_libs", "max_forks_repo_head_hexsha": "52cac5d64b55a12dfbdad1c768cdd8d79d5789f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-07-30T23:49:27.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-30T23:49:27.000Z", "avg_line_length": 22.8235294118, "max_line_length": 121, "alphanum_fraction": 0.6288659794, "include": true, "reason": "import numpy", "num_tokens": 893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542864252023, "lm_q2_score": 0.9073122313857378, "lm_q1q2_score": 0.8702524158596454}}
{"text": "#!/usr/bin/python\n\"\"\"\nauthor: Bhekimpilo Ndhlela\nauthor: 18998712\nmodule: Applied Mathematics(Numerical Analysis) TW324\ntask  : computer assignment 01\nsince : Friday-09-02-2018\n\"\"\"\n\n#for the square root function and absolute value\nfrom numpy import (sqrt, abs )\ndef question2(debug=True):\na, b, c = 1.0, -10000.0, 1.0\n\n    xP = (-1*b + sqrt(pow(b,2) - 4*a*c))/ 2*a\n    xM = (-1*b - sqrt(pow(b,2) - 4*a*c))/ 2*a\n\n    if debug is True:\n        print(\"x+ = \" + str(format(xP, \".20f\")))\n        print(\"x- = \" + str(format(xM, \".20f\")))\n\n    xM2 = c / (a * xP)\n    if debug is True:\n        print format(xM2, \".20f\")\n\nquestion2()  #call code for question 2\n", "meta": {"hexsha": "22c15f53967978ff0729dbf46c103f9d0396cdce", "size": 652, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment_01/src/q2.py", "max_stars_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_stars_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-28T18:36:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-28T18:36:55.000Z", "max_issues_repo_path": "assignment_01/src/q2.py", "max_issues_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_issues_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment_01/src/q2.py", "max_forks_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_forks_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-16T04:26:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-16T04:26:44.000Z", "avg_line_length": 24.1481481481, "max_line_length": 53, "alphanum_fraction": 0.5966257669, "include": true, "reason": "from numpy", "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9591542864252023, "lm_q2_score": 0.9073122182277756, "lm_q1q2_score": 0.8702524032391296}}
{"text": "import numpy as np\nfrom scipy import optimize\nfrom matplotlib import pyplot as plt, cm, colors\n\ndef calc_R(x,y, xc, yc):\n    \"\"\" calculate the distance of each 2D points from the center (xc, yc) \"\"\"\n    return np.sqrt((x-xc)**2 + (y-yc)**2)\n\ndef f(c, x, y):\n    \"\"\" calculate the algebraic distance between the data points and the mean circle centered at c=(xc, yc) \"\"\"\n    Ri = calc_R(x, y, *c)\n    return Ri - Ri.mean()\n\ndef leastsq_circle(x,y):\n    # coordinates of the barycenter\n    x_m = np.mean(x)\n    y_m = np.mean(y)\n    center_estimate = x_m, y_m\n    center, ier = optimize.leastsq(f, center_estimate, args=(x,y))\n    xc, yc = center\n    Ri       = calc_R(x, y, *center)\n    R        = Ri.mean()\n    residu   = np.sum((Ri - R)**2)\n    return xc, yc, R, residu\n\ndef plot_data_circle(x,y, xc, yc, R):\n    f = plt.figure( facecolor='white')  #figsize=(7, 5.4), dpi=72,\n    plt.axis('equal')\n\n    theta_fit = np.linspace(-pi, pi, 180)\n\n    x_fit = xc + R*np.cos(theta_fit)\n    y_fit = yc + R*np.sin(theta_fit)\n    plt.plot(x_fit, y_fit, 'b-' , label=\"fitted circle\", lw=2)\n    plt.plot([xc], [yc], 'bD', mec='y', mew=1)\n    plt.xlabel('x')\n    plt.ylabel('y')   \n    # plot data\n    plt.plot(x, y, 'r-.', label='data', mew=1)\n\n    plt.legend(loc='best',labelspacing=0.1 )\n    plt.grid()\n    plt.title('Least Squares Circle')", "meta": {"hexsha": "d128bf054ede39061d7fbcc33fd071fc07369207", "size": 1330, "ext": "py", "lang": "Python", "max_stars_repo_path": "hard-gists/6799568/snippet.py", "max_stars_repo_name": "jjhenkel/dockerizeme", "max_stars_repo_head_hexsha": "eaa4fe5366f6b9adf74399eab01c712cacaeb279", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2019-07-08T08:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T23:53:25.000Z", "max_issues_repo_path": "hard-gists/6799568/snippet.py", "max_issues_repo_name": "jjhenkel/dockerizeme", "max_issues_repo_head_hexsha": "eaa4fe5366f6b9adf74399eab01c712cacaeb279", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-06-15T14:47:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T05:02:56.000Z", "max_forks_repo_path": "hard-gists/6799568/snippet.py", "max_forks_repo_name": "jjhenkel/dockerizeme", "max_forks_repo_head_hexsha": "eaa4fe5366f6b9adf74399eab01c712cacaeb279", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2019-05-16T03:50:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T14:35:12.000Z", "avg_line_length": 30.9302325581, "max_line_length": 111, "alphanum_fraction": 0.5954887218, "include": true, "reason": "import numpy,from scipy", "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9808759649262344, "lm_q2_score": 0.8872045922259088, "lm_q1q2_score": 0.8702376604865746}}
{"text": "\"\"\"Solution for up-and-in option with antithetic Monte-Carlo\"\"\"\nimport numpy as np\n\n################################################################################\n# Simulation parameters\nM = 10000\nr = 0.02\nsg = 0.3\ndt = 1 / 252\nT = 1\nn = int(T / dt)\nS0 = 1\nH = 1.1\nK = 0.9\n################################################################################\n\n\nif __name__ == '__main__':\n    # Generate random numbers from a normal distribution for the MC simulation\n    eps = np.random.normal(size=(n, M))\n\n    # Initialize empty vectors\n    V = np.zeros((M))\n    V_ = np.zeros((M))\n    W = np.zeros((M))\n    # Iterate through M iterations\n    for i in range(M):\n        S1 = np.zeros((n))\n        S2 = np.zeros((n))\n        S1[0] = S0\n        S2[0] = S0\n        # Iterate through n - 1 time steps (first time step is known)\n        for j in range(n - 1):\n            # normal pricing is stored in S1\n            S1[j + 1] = S1[j] * np.exp((r - 0.5 * sg ** 2) * dt \\\n                 + sg * eps[j, i] * np.sqrt(dt))\n            # antitetic variate pricing is stored in S2\n            S2[j + 1] = S2[j] * np.exp((r - 0.5 * sg ** 2) * dt \\\n                - sg * eps[j, i] * np.sqrt(dt))\n        # Find the maximum value of the realized stock price path\n        S_tmax = np.max(S1)\n        S_amax = np.max(S2)\n\n        # Test if the price path exceeded the barrier H\n        # if so, the option is exercisable\n        # then the pay off is max(S(T) - K, 0)\n        if S_tmax > H:\n            # normal pricing\n            V[i] = np.exp(-r * T) * np.max(S1[-1] - K, 0)\n        if S_amax > H:\n            # for use in antithetic pricing\n            V_[i] = np.exp(-r * T) * np.max(S2[-1] - K, 0)\n        # antithetic pricing\n        W[i] = 0.5 * (V[i] + V_[i])\n\n    # Print the results\n    print('Price (mean), normal pricing:', np.mean(V))\n    print('Price (mean), antithetic pricing:', np.mean(W))\n    print('Std, normal pricing:', np.std(V))\n    print('Std, antithetic pricing:', np.std(W))\n\n    # It can be seen that antithetic pricing has a lower standard deviation.\n    # This is because of the use of antithetic variates.\n\n    # It can be shown analytically that the variance of the antithetic pricing\n    # is less than or equal to half of the variance of normal pricing.\n    # This is verified below.\n    print('Test if Var(W) <= 0.5 * Var(V):', np.var(W) <= 0.5 * np.var(V))\n", "meta": {"hexsha": "64dfcdf73c19c06bbd05f7e5407678297faa43dc", "size": 2378, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/monte_carlo/antitheic_mc.py", "max_stars_repo_name": "TechnicalConsultant123/financial-maths", "max_stars_repo_head_hexsha": "b29d6cd4c0afdc89d69c4db9d11adb2ff64089e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-05-02T19:18:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-08T15:56:23.000Z", "max_issues_repo_path": "Python/monte_carlo/antitheic_mc.py", "max_issues_repo_name": "qrana/financial-maths", "max_issues_repo_head_hexsha": "b29d6cd4c0afdc89d69c4db9d11adb2ff64089e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/monte_carlo/antitheic_mc.py", "max_forks_repo_name": "qrana/financial-maths", "max_forks_repo_head_hexsha": "b29d6cd4c0afdc89d69c4db9d11adb2ff64089e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-15T14:51:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T23:52:38.000Z", "avg_line_length": 34.4637681159, "max_line_length": 80, "alphanum_fraction": 0.5117746005, "include": true, "reason": "import numpy", "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551495568569, "lm_q2_score": 0.90192067059785, "lm_q1q2_score": 0.8702228035181092}}
{"text": "from IMLearn.learners import UnivariateGaussian, MultivariateGaussian\nimport numpy as np\nimport plotly.graph_objects as go\nimport plotly.io as pio\nimport plotly.express as px\npio.templates.default = \"simple_white\"\n\n\ndef test_univariate_gaussian():\n    # Question 1 - Draw samples and print fitted model\n    mu1 = 10\n    sigma1 = 1\n    X1 = np.random.normal(mu1, sigma1, 1000)\n    UG = UnivariateGaussian()\n    UG.fit(X1)\n    print(\"expectation1: \", UG.mu_, \"variance1: \", UG.var_, \"\\n\")\n    # Question 2 - Empirically showing sample mean is consistent\n    arr = np.ndarray(100)\n    for i, smp in enumerate(range(10, 1001, 10)):\n        temp = UnivariateGaussian()\n        temp.fit(X1[:smp])\n        arr[i] = np.abs(temp.mu_ - mu1)\n    px.scatter(x=np.array(list(range(10, 1001, 10))), y=arr, title=\"question 2\").update_xaxes \\\n        (title_text=\"sample size\").update_yaxes(title_text=\"|estimated - true value of expectation|\").show()\n    # Question 3 - Plotting Empirical PDF of fitted model\n    px.scatter(x=X1, y=UG.pdf(X1), title=\"question 3\").update_xaxes \\\n        (title_text=\"ordered sample values\").update_yaxes(title_text=\"PDF\").show()\n\n\ndef test_multivariate_gaussian():\n    # Question 4 - Draw samples and print fitted model\n    mu2 = np.array([0, 0, 4, 0])\n    cov_matrix = np.array([[1, 0.2, 0, 0.5], [0.2, 2, 0, 0], [0, 0, 1, 0], [0.5, 0, 0, 1]])\n    X2 = np.random.multivariate_normal(mu2, cov_matrix, 1000)\n    MG = MultivariateGaussian()\n    MG.fit(X2)\n    print(\"expectation2: \\n\", MG.mu_, \"\\n\", \"covar matrix: \\n\", MG.cov_)\n\n    # # Question 5 - Likelihood evaluation\n    f1 = np.linspace(-10, 10, 200)\n    f3 = np.linspace(-10, 10, 200)\n    log_matrix = np.array([[MultivariateGaussian.log_likelihood(np.array([f1[i], 0, f3[j], 0]), cov_matrix, X2)\n                            for j in range(200)] for i in range(200)])\n    px.imshow(log_matrix, x=f1, y=f3, labels=dict(x=\"f1\", y=\"f3\", color=\"log-likelihood\"), title=\"question 5\").show()\n    # Question 6 - Maximum likelihood\n    max_val = np.amax(log_matrix)\n    max_location = np.where(log_matrix == max_val)\n    print(\"max log-likelihood value: \", max_val,\"f1 value: \", f1[max_location[0][0]],\n          \"f3 value:  \", f3[max_location[1][0]])\n\n\nif __name__ == '__main__':\n    np.random.seed(0)\n    test_univariate_gaussian()\n    test_multivariate_gaussian()", "meta": {"hexsha": "e41118c462d4ec28b52e4101f9525a2adfef2d46", "size": 2332, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercises/fit_gaussian_estimators.py", "max_stars_repo_name": "mattisevitt/IML.HUJI", "max_stars_repo_head_hexsha": "57722f1f48dd89bf2b35f29de2d214f0b25376d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercises/fit_gaussian_estimators.py", "max_issues_repo_name": "mattisevitt/IML.HUJI", "max_issues_repo_head_hexsha": "57722f1f48dd89bf2b35f29de2d214f0b25376d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercises/fit_gaussian_estimators.py", "max_forks_repo_name": "mattisevitt/IML.HUJI", "max_forks_repo_head_hexsha": "57722f1f48dd89bf2b35f29de2d214f0b25376d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4, "max_line_length": 117, "alphanum_fraction": 0.6505145798, "include": true, "reason": "import numpy", "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.9241418121440552, "lm_q1q2_score": 0.8702219842964644}}
{"text": "###________________________ Non-Lineal-Equations ___________________________### \nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import optimize\n\n# La ayuda de este paquete es bastante larga (puedes consultarla también en \n# http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html). \n# El paquete optimize incluye multitud de métodos para optimización, ajuste de \n# curvas y búsqueda de raíces. Vamos a centrarnos ahora en la búsqueda de raíces \n# de funciones escalares. Para más información puedes leer \n# http://pybonacci.org/2012/10/25/como-resolver-ecuaciones-algebraicas-en-python-con-scipy/\n\n# **Nota**: La función `root` se utiliza para hallar soluciones de *sistemas* de \n# ecuaciones no lineales así que obviamente también funciona para ecuaciones escalares. \n# No obstante, vamos a utilizar las funciones `brentq` y `newton` para que el método \n# utilizado quede más claro.\n\n# Hay básicamente dos tipos de algoritmos para hallar raíces de ecuaciones no lineales:\n\n# * Aquellos que operan en un intervalo $[a, b]$ tal que $f(a) \\cdot f(b) < 0$. \n# Más lentos, convergencia asegurada.\n# * Aquellos que operan dando una condición inicial $x_0$ más o menos cerca de \n# la solución. Más rápidos, convergencia condicionada.\n\n# De los primeros vamos a usar la función `brentq` (aunque podríamos usar `bisect`) \n# y de los segundos vamos a usar `newton` (que en realidad engloba los métodos \n# de Newton y de la secante).\n\n##_________________________ Example ___________________________##\n# $\\ln{x} = \\sin{x} \\Rightarrow F(x) \\equiv \\ln{x} - \\sin{x} = 0$\n# Lo primero que tengo que hacer es definir la ecuación, que matemáticamente \n# será una función $F(x)$ que quiero igualar a cero.\ndef F(x):\n    return np.log(x) - np.sin(x)\n# Para hacernos una idea de las posibles soluciones siempre podemos representar \n# gráficamente esa función:\nx = np.linspace(0, 10, num=100)\nwith plt.style.context('seaborn-notebook'):\n    plt.plot(x, F(x), 'k', lw=2, label=\"$F(x)$\")\n    plt.plot(x, np.log(x), label=\"$\\log{x}$\")\n    plt.plot(x, np.sin(x), label=\"$\\sin{x}$\")\n    plt.plot(x, np.zeros_like(x), 'k--')\n    plt.legend(loc=4)\n    plt.grid()\n    plt.show()\n# Y utilizando por ejemplo el método de Brent en el intervalo [0,3]:\n# print(optimize.brentq(F, 0, 3))\n\n##_________________________ Exercise ___________________________##\n# Obtener por ambos métodos (newton y brentq) una solución a la ecuación \n# tanx=x distinta de x=0. Visualizar el resultado.\n## Argumentos extra ##\n# Nuestras funciones siempre tienen que tomar como primer argumento la incógnita,\n# el valor que la hace cero. Si queremos incluir más, tendremos que usar el argumento \n# `args` de la funciones de búsqueda de raíces. Este patrón se usa también en otras \n# partes de SciPy, como ya veremos.\n\n# Vamos a resolver ahora una ecuación que depende de un parámetro:\n    # $$\\sqrt{x} + \\log{x} = C$$.\ndef G(x, C):\n    return C - np.sqrt(x) - np.log(x)\n# **Nuestra incógnita sigue siendo $x$**, así que debe ir en primer lugar. \n# El resto de parámetros van a continuación, y sus valores se especifican a la \n# hora de resolver la ecuación usando `args`:\n# print(optimize.newton(G, 2.0, args=(2,)))\n\n##_________________________ Compressible Flow ___________________________##\n# Esta es la relación isentrópica entre el número de Mach $M(x)$ en un conducto \n# de área $A(x)$:\n    # $$ \\frac{A(x)}{A^*} = \\frac{1}{M(x)} \\left( \\frac{2}{1 + \\gamma} \\left( 1 + \n    # \\frac{\\gamma - 1}{2} M(x)^2 \\right) \\right)^{\\frac{\\gamma + 1}{2 (\\gamma - 1)}}$$\n# Para un conducto convergente:\n    # $$ \\frac{A(x)}{A^*} = 3 - 2 x \\quad x \\in [0, 1]$$\n# Hallar el número de Mach en la sección 𝑥=0.9.\ndef A(x):\n    return 3 - 2 * x\nx = np.linspace(0, 1)\narea = A(x)\nr = np.sqrt(area / np.pi)\nplt.fill_between(x, r, -r, color=\"#ffcc00\")\nplt.show()\n\n# ¿Cuál es la función $F$ ahora? Hay dos opciones: definir una función $F_{0.9}(M)$ \n# que me da el número de Mach en la sección $0.9$ o una función $F(M; x)$ con la \n# que puedo hallar el número de Mach en cualquier sección. \n\n# Para resolver la ecuación utiliza el método de Brent (bisección). ¿En qué intervalo \n# se encontrará la solución? ¡Si no te haces una idea es tan fácil como pintar \n# la función $F$!\ndef F(M, x, g):\n    return A(x) - (1 / M) * ((2 / (1 + g)) * (1 + (g - 1) / 2 * M ** 2)) ** ((g + 1) / (2 * (g - 1))) \n\n# print(optimize.brentq(F, 0.01, 1, args=(0.9, 1.4)))\n\n##_______________________________ Kepler law ________________________________##\n# Representar la ecuación de Kepler\n    # $$M = E - e \\sin E$$\n\n# que relaciona dos parámetros geométricos de las órbitas elípticas, la anomalía \n# media $M$ y la anomalía excéntrica $E, para los siguientes valores de excentricidad:\n    # * Tierra: $0.0167$\n    # * Plutón: $0.249$\n    # * Cometa Holmes: $0.432$\n    # * 28P/Neujmin: $0.775$\n    # * Cometa Halley: $0.967$\n\n# Para ello utilizaremos el método de Newton (secante).\n# 1- Define la función correspondiente a la ecuación de Kepler, que no solo es \n# una ecuación implícita sino que además depende de un parámetro. ¿Cuál es la incógnita?\ndef Kepler(E, e, M):\n    return M - E + e * np.sin(E)\n# 2- Como primer paso, resuélvela para la excentricidad terrerestre y anomalía \n# media $M = 0.3$. ¿Qué valor escogerías como condición inicial?\nprint(optimize.newton(Kepler, 0.3, args=(0.0167, 0.3)))\n# 3- Como siguiente paso, crea un dominio (`linspace`) de anomalías medias entre \n# $0$ y $2 \\pi$ y resuelve la ecuación de Kepler con excentricidad terrestre para \n# todos esos valores. Fíjate que necesitarás un array donde almacenar las soluciones. \n# Representa la curva resultante.\nN = 500\n\nM = np.linspace(0, 2 * np.pi, N)\nsol = np.zeros_like(M)\n\nfor ii in range(N):\n    sol[ii] = optimize.newton(Kepler, sol[ii - 1], args=(0.249, M[ii]))\nplt.plot(M, sol)\nplt.show()\n\n# 4- Como último paso, solo tienes que meter parte del código que ya has escrito \n# en un bucle que cambie el valor de la excentricidad 5 veces. \nM = np.linspace(0, 2 * np.pi, N)\nsol = np.zeros_like(M)\n\nplt.figure(figsize=(6, 6))\n\nfor ee in 0.0167, 0.249, 0.432, 0.775, 0.967:\n    # Para cada valor de excentricidad sobreescribimos el array sol\n    for ii in range(N):\n        sol[ii] = optimize.newton(Kepler, sol[ii - 1], args=(ee, M[ii]))\n    with plt.style.context('seaborn-notebook'):\n        plt.plot(M, sol)\nwith plt.style.context('seaborn-notebook'):\n    plt.xlim(0, 2 * np.pi)\n    plt.ylim(0, 2 * np.pi)\n    plt.xlabel(\"$M$\", fontsize=15)\n    plt.ylabel(\"$E$\", fontsize=15)\n    plt.gca().set_aspect(1)\n    plt.grid(True)\n    plt.legend([\"Earth\", \"Pluto\", \"Comet Holmes\", \"28P/Neujmin\", \"Halley's Comet\"], loc=2)\n    plt.title(\"Kepler's equation solutions\", fontsize=15)\n", "meta": {"hexsha": "55c13542d28a29cfcc32eae0d29c76b56ded3527", "size": 6687, "ext": "py", "lang": "Python", "max_stars_repo_path": "MyScripts/034-SciPy.py", "max_stars_repo_name": "diegoomataix/Curso_AeroPython", "max_stars_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MyScripts/034-SciPy.py", "max_issues_repo_name": "diegoomataix/Curso_AeroPython", "max_issues_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MyScripts/034-SciPy.py", "max_forks_repo_name": "diegoomataix/Curso_AeroPython", "max_forks_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2847682119, "max_line_length": 102, "alphanum_fraction": 0.6880514431, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.9241418131886822, "lm_q1q2_score": 0.8702219807406072}}
{"text": "'''\nUsage\n-----\nRun as a script with no arguments\n```\n$ python run_Gibbs_correlated_2d_normal.py\n```\nWill run MCMC and produce plots\n\nPurpose\n-------\nSample from a 2-dim. Normal distribution using Gibbs Sampling\n\nTarget distribution:\n# mean\n>>> mu_D = np.asarray([-1.0, 1.0])\n# covariance\n>>> cov_DD = np.asarray([[2.0, 0.95], [0.95, 1.0]])\n\n'''\n\nimport numpy as np\nimport scipy.stats\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('whitegrid')\n\nfrom GibbsSampler import GibbsSampler2D\n\ndef draw_z0_given_z1(z1, u_stdnorm):\n    ''' Draw sample from target conditional for z0 given z1\n\n    Does not generate any randomness internally.\n    Relies performing a transformation,\n    Given a passed value \"u\" drawn externally from standard normal.\n\n    Args\n    ----\n    z1 : scalar float\n        Value of variable z1 to condition on.\n    u_stdnorm : scalar float\n        Value drawn from Standard Normal distribution\n        Assumed: u ~ Normal(0.0, 1.0)\n        Should be only source of randomness you need.\n\n    Returns\n    -------\n    z0 : scalar float\n        Sample from conditional p*(z0 | z1)\n    '''\n    # TODO Compute conditional distribution mean and covariance\n    # Given known joint Gaussian over z0, z1 with mean mu_D and covar cov_DD\n    \n    # TODO Transform provided u_stdnorm value into sample from target conditional\n    z0_samp = z1 * u_stdnorm # fixme\n    return z0_samp\n\ndef draw_z1_given_z0(z0, u_stdnorm):\n    ''' Draw sample from target conditional for z1 given z0\n\n    Does not generate any randomness internally.\n    Relies performing a transformation,\n    Given a passed value \"u\" drawn externally from standard normal.\n\n    Args\n    ----\n    z1 : scalar float\n        Value of variable z0 to condition on.\n    u_stdnorm : value drawn from Standard Normal distribution\n        Assumed: u ~ Normal(0.0, 1.0)\n        Should be only source of randomness you need.\n\n    Returns\n    -------\n    z1 : scalar float\n        Sample from conditional p*(z1 | z0)\n    '''\n\n    # Use Bishop PRML Equations 2.81 and 2.82 to compute conditional,\n    # Given joint Gaussian over z0, z1 with mean mu_D and covar cov_DD\n    mu_D = np.asarray([-1.0, 1.0])\n    cov_DD = np.asarray([[2.0, 0.95], [0.95, 1.0]])\n    a = 1\n    b = 0\n    var_10 = cov_DD[a,a] - (cov_DD[a,b] * cov_DD[b,a]) / cov_DD[b,b]\n    mean_10 = mu_D[a] + cov_DD[a,b] / cov_DD[b,b] * (z0 - mu_D[b])\n\n    # Draw from p(z1 | z0) =  Normal(mean_10, var_10)\n    z1_samp = mean_10 + np.sqrt(var_10) * u_stdnorm\n    return z1_samp\n\n\n\nif __name__ == '__main__':\n    ''' Main block to test Gibbs Sampler for D=2-dim. random. variable z_D\n   \n    Goal: Run separate MCMC chains from two initial values and verify that\n    the sampler *converges* to the same distribution in both chains\n    '''\n    n_samples = 10000   # total number of iterations of MCMC\n    n_keep = 5000       # number samples to keep\n    random_state = 42   # seed for random number generator\n\n    # Two initializations, labeled 'A' and 'B'\n    z_initA_D = np.zeros(2)\n    z_initB_D = np.asarray([1.0, -1.0])\n\n    # No hyperparameters to tune for Gibbs\n    G = 1\n\n    # Prepare a plot to view samples from two chains (A/B) side-by-side\n    _, ax_grid = plt.subplots(\n        nrows=2, ncols=1, sharex=True, sharey=True,\n        figsize=(2*G, 2*2))\n\n    # Create samplers and run them for specified num iterations\n    samplerA = GibbsSampler2D(draw_z0_given_z1, draw_z1_given_z0, random_state)\n    z_fromA_list, samplerA_info = samplerA.draw_samples(zinit_D=z_initA_D, n_samples=n_samples)\n\n    samplerB = GibbsSampler2D(draw_z0_given_z1, draw_z1_given_z0, random_state+1)\n    z_fromB_list, samplerB_info = samplerB.draw_samples(zinit_D=z_initB_D, n_samples=n_samples)\n\n    # Stack list of samples into a 2D array of size (S, D)\n    # Keeping only the last few samples (and thus discarding burnin)\n    zA_SD = np.vstack(z_fromA_list[-n_keep:])\n    zB_SD = np.vstack(z_fromB_list[-n_keep:])\n\n    # Plot samples as scatterplot\n    # Use small alpha transparency value for visual debugging of rare/frequent samples\n    ax_grid[0].plot(zA_SD[:,0], zA_SD[:,1], 'r.', alpha=0.05)\n    ax_grid[1].plot(zB_SD[:,0], zB_SD[:,1], 'b.', alpha=0.05)\n    # Mark initial points with \"X\"\n    ax_grid[0].plot(z_fromA_list[0][0], z_fromA_list[0][1], 'rx')\n    ax_grid[1].plot(z_fromB_list[0][0], z_fromB_list[0][1], 'bx')\n\n    ##Label axes\n    ax_grid[0].set_xlabel(\"z_0\")\n    ax_grid[1].set_xlabel(\"z_0\")\n    ax_grid[0].set_ylabel(\"z_1\")\n    ax_grid[1].set_ylabel(\"z_1\")\n\n    ##Title for plots\n    ax_grid[0].set_title(\"Initialization A\")\n    ax_grid[1].set_title(\"Initialization B\")\n\n    # Pretty print some stats for the samples\n    # To give a way to check \"convergence\" from the terminal's stdout\n    msg_pattern = (\"Gibbs from init %s | kept %d of %d samples | accept rate %.3f\"\n        + \"\\n    percentiles z0: 10th % 5.2f   50th % 5.2f   90th % 5.2f\" \n        + \"\\n    percentiles z1: 10th % 5.2f   50th % 5.2f   90th % 5.2f\"\n        )\n    print(msg_pattern % (\n        'A', n_keep, n_samples,\n        samplerA_info['accept_rate_last_half'],\n        *tuple(np.percentile(zA_SD[:,0:1], [10, 50, 90], axis=0)),\n        *tuple(np.percentile(zA_SD[:,1:2], [10, 50, 90], axis=0)),\n        ))\n    print(msg_pattern % (\n        'B', n_keep, n_samples,\n        samplerB_info['accept_rate_last_half'],\n        *tuple(np.percentile(zB_SD[:,0:1], [10, 50, 90], axis=0)),\n        *tuple(np.percentile(zB_SD[:,1:2], [10, 50, 90], axis=0)),\n        ))\n\n    # Make plots pretty and standardized\n    for ax in ax_grid.flatten():\n        ax.set_xlim([-5, 5]);\n        ax.set_ylim([-5, 5]);\n        ax.set_aspect('equal', 'box');\n        ax.set_xticks([-4, -2, 0, 2, 4])\n        ax.set_yticks([-4, -2, 0, 2, 4])\n    plt.tight_layout()\n    plt.savefig(\"problem2_figure.pdf\", bbox_to_inches='tight', pad_inches=0)\n    plt.show()", "meta": {"hexsha": "fa705646ef066c597eb448b2a6bfac8067184e8e", "size": 5846, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw_cp3/src_starter/run_Gibbs_correlated_2d_normal.py", "max_stars_repo_name": "martin-buck/cs136-22s-assignments", "max_stars_repo_head_hexsha": "ab8df93092dba940b5cf95437bc7aeb906c8964b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw_cp3/src_starter/run_Gibbs_correlated_2d_normal.py", "max_issues_repo_name": "martin-buck/cs136-22s-assignments", "max_issues_repo_head_hexsha": "ab8df93092dba940b5cf95437bc7aeb906c8964b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw_cp3/src_starter/run_Gibbs_correlated_2d_normal.py", "max_forks_repo_name": "martin-buck/cs136-22s-assignments", "max_forks_repo_head_hexsha": "ab8df93092dba940b5cf95437bc7aeb906c8964b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-12-07T19:46:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T21:21:25.000Z", "avg_line_length": 33.5977011494, "max_line_length": 95, "alphanum_fraction": 0.6472801916, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.9294404057671714, "lm_q1q2_score": 0.8702211206134421}}
{"text": "# ------------------------------------------------------------------------------------------------------ #\n# Author: Anna Lonergan                                                                                  #\n# Purpose: Script providing examples for the Newton-raphson Functions.                                   #\n# ------------------------------------------------------------------------------------------------------ #\n\n# necessary libraries:\nimport numpy as np\nfrom newtonraphson import * \n\n\n##################################################################\n# EXAMPLE 1 -> 2 Functions                                       #\n# Consider a market with nonlinear demand and supply curves.     #\n# Solve the system of equations for equilibrium Price & Quantity #\n# Supply: P(Qs) = 20*(1.5**Qs/100)                               #\n# Demand: P(Qd) = (2000 - Qd)**0.7                               #\n# The market equilibrium is:                                     #\n# P = 165.55, Q = 521.26                                         #\n# Now, lets test the algorithm                                   #\n##################################################################\n\n# Create system of equations\ndef F(X):\n    # F takes one argument, X.\n    # X is a tuple, list or vector containing values for the relevant system variables (P & Q)\n    p = X[0]\n    q = X[1]\n    # System is a vector of zeros, the same length as X. \n    # Each element of the vector \"system\" will hold a function.\n    # Length of X and system *must* match, because the number of unknowns (2: P & Q) must match the number of equations (2). \n    system = np.zeros(len(X))\n    system[0] = 20*(1.5**(q/100)) - p\n    system[1] = (2000 - q)**0.7 - p\n    # This function returns a vector of 2 equations, evaluated at X. \n    return system\n\n\n# Set initial guess, P = 0, Q = 0\ninit = np.array([0,0])\n\n# Find the Solution:\n# Only required inputs are function & initial value guesses. \n# Tolerance and Maximum Iterations are optional. I choose not to specify, so we'll use the NR function defaults.\nsolution, results = NR(F, init)\n\nprint(\"\\nExample 1: Nonlinear Market\")\nprint(\"Price in the market is %3.3f, and the Quantity Demanded is %3.3f.\" % (solution[0], solution[1]))\nprint(\"\\n Iteration Output:\")\nprint(results)\n\n# Nice! The solutions from my solver match those listed above. It seems to be working in 2 dimensions. \n\n\n##################################################################\n# EXAMPLE 2 -> 3 Functions                                       #\n# Consider a market with 3 cournot duopolists.                   #\n# Each producer chooses its own quantity based on what the other #\n# duopolists produce.                                            #\n# Solve this system of the duopolists' reaction curves.          #\n# Supply1: Q1(q2,q3) = 5 - 0.5q2 -0.3q3                          #\n# Supply2: Q2(q1,q3) = 7 - 0.6q1 -0.1q3                          #\n# Supply3: Q3(q1,q2) = 4 - 0.2q1 -0.4q2                          #\n# The market equilibrium is:                                     #\n# q1 = 1.67 , q2 = 5.87 , q3 = 1.32                              #\n# Now, lets test the algorithm                                   #\n##################################################################\n\n# Create system of equations\ndef Duopoly(Q):\n    # Duopoly takes one argument, Q.\n    # Q is a tuple, list or vector containing values for the relevant system variables (Q1-Q3)\n    q1 = Q[0]\n    q2 = Q[1]\n    q3 = Q[2]\n    # System is a vector of zeros, the same length as Q. \n    # Each element of the vector \"system\" will hold a function.\n    # Length of Q and system *must* match, because the number of unknowns (3: q1, q2 & q3) must match the number of equations (3). \n    system = np.zeros(len(Q))\n    system[0] = 5 - (0.5*q2) - (0.3*q3) - q1\n    system[1] = 7 - (0.6*q1) - (0.1*q3) - q2\n    system[2] = 4 - (0.2*q1) - (0.4*q2) - q3\n    # This function returns a vector of 3 equations, evaluated at Q. \n    return system\n\n\n# Set initial guess, all quantities equal 0. \ninit = np.array([0,0,0])\n\n# Find the Solution:\n# Only required inputs are function & initial value guesses. \n# Tolerance and Maximum Iterations are optional. I choose not to specify, so we'll use the NR function defaults.\nsolution, results = NR(Duopoly, init)\n\nprint(\"\\nExample 2: Cournot Duopolists\")\nprint(\"Q1 is %3.3f, Q2 is %3.3f, and Q3 is %3.3f.\" % (solution[0], solution[1], solution[2]))\nprint(\"\\n Iteration Output:\")\nprint(results)\n\n# Again, the solutions from my solver match those listed above. It seems to be working in 3 dimensions. \n\n\n", "meta": {"hexsha": "2aafa0ab7f21ef93a467e9edc8288a664be09fb5", "size": 4583, "ext": "py", "lang": "Python", "max_stars_repo_path": "nonlinear_system/newtonexample.py", "max_stars_repo_name": "anna-elsa/solvers", "max_stars_repo_head_hexsha": "25e4f00db447fde3461b477aa7247d65c6cdf27b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nonlinear_system/newtonexample.py", "max_issues_repo_name": "anna-elsa/solvers", "max_issues_repo_head_hexsha": "25e4f00db447fde3461b477aa7247d65c6cdf27b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nonlinear_system/newtonexample.py", "max_forks_repo_name": "anna-elsa/solvers", "max_forks_repo_head_hexsha": "25e4f00db447fde3461b477aa7247d65c6cdf27b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.931372549, "max_line_length": 131, "alphanum_fraction": 0.508400611, "include": true, "reason": "import numpy", "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928905, "lm_q2_score": 0.9149009602137116, "lm_q1q2_score": 0.8702009303712969}}
{"text": "#!/usr.bin/env python\n#D. Jones - 1/13/14\n\"\"\"This code is from the IDL Astronomy Users Library\"\"\"\nimport numpy as np\n\ndef meanclip(image, \n             clipsig=3, maxiter=5,\n             converge_num=0.02, verbose=False,\n             returnSubs=False):\n    \"\"\"Computes an iteratively sigma-clipped mean on a data set\n    Clipping is done about median, but mean is returned.\n    Converted from IDL to Python.\n    \n    CALLING SEQUENCE:\n        mean,sigma = meanclip( data, clipsig=, maxiter=,\n                               converge_num=, verbose=,\n                               returnSubs=False)\n        mean,sigma,subs = meanclip( data, clipsig=, maxiter=,\n                                    converge_num=, verbose=,\n                                    returnSubs=True)\n\n    INPUT PARAMETERS:\n         data           -  Input data, any numeric array\n\n    OPTIONAL INPUT PARAMETERS:\n         clipsig        -  Number of sigma at which to clip.  Default=3\n         maxiter        -  Ceiling on number of clipping iterations.  Default=5\n         converge_num   -  If the proportion of rejected pixels is less\n                            than this fraction, the iterations stop.  Default=0.02, i.e.,\n                            iteration stops if fewer than 2% of pixels excluded.\n         verbose        -  Set this flag to get messages.\n         returnSubs     -  if True, return subscript array for pixels finally used\n           \n    RETURNS:\n         mean           -  N-sigma clipped mean.\n         sigma          -  Standard deviation of remaining pixels.\n    \n    MODIFICATION HISTORY:\n         Written by:       RSH, RITSS, 21 Oct 98\n         20 Jan 99   -     Added SUBS, fixed misplaced paren on float call, \n                            improved doc.  RSH\n         Nov 2005    -     Added /DOUBLE keyword, check if all pixels are removed  \n                            by clipping W. Landsman \n         Jan. 2014   -     Converted from IDL to Python by D. Jones\n    \"\"\"\n\n    prf = 'MEANCLIP:  '\n    \n    #image = image.reshape(np.shape(image)[0]*np.shape(image)[1])\n    subs = np.where(np.isfinite(image))[0]\n    ct = len(subs)\n    iter=0\n\n    for i in range(maxiter):\n        skpix = image[subs]\n        iter = iter + 1\n        lastct = ct\n        medval = np.median(skpix)\n        mom = [np.mean(skpix),np.std(skpix)]\n        sig = mom[1]\n        wsm = np.where(np.abs(skpix-medval) < clipsig*sig)[0]\n        ct = len(wsm)\n        if ct > 0: subs = subs[wsm]         \n        if (float(np.abs(ct-lastct))/lastct <= converge_num) or \\\n                (iter > maxiter) or (ct == 0):\n            break\n    #mom = moment(image[subs],double=double,max=2)\n    mean = np.mean(image[subs])\n    sigma = np.std(image[subs])\n\n    if verbose:\n        print(prf+strn(clipsig)+'-sigma clipped mean')\n        print(prf+'Mean computed in ',iter,' iterations')\n        print(prf+'Mean = ',mean,',  sigma = ',sigma)\n\n    if not returnSubs:\n        return(mean,sigma)\n    else:\n        return(mean,sigma,subs)\n", "meta": {"hexsha": "1985ec6204225505ae200376a18b8484f0534252", "size": 3002, "ext": "py", "lang": "Python", "max_stars_repo_path": "PythonPhot/meanclip.py", "max_stars_repo_name": "sjoertvv/PyIDLPhot", "max_stars_repo_head_hexsha": "ecc83917f881e91b6ce477df1fbd350028abd0d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2015-03-10T06:00:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T04:07:02.000Z", "max_issues_repo_path": "PythonPhot/meanclip.py", "max_issues_repo_name": "sjoertvv/PyIDLPhot", "max_issues_repo_head_hexsha": "ecc83917f881e91b6ce477df1fbd350028abd0d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2016-02-02T18:12:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-05T15:33:47.000Z", "max_forks_repo_path": "PythonPhot/meanclip.py", "max_forks_repo_name": "sjoertvv/PyIDLPhot", "max_forks_repo_head_hexsha": "ecc83917f881e91b6ce477df1fbd350028abd0d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2015-03-13T23:24:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T13:43:10.000Z", "avg_line_length": 37.525, "max_line_length": 89, "alphanum_fraction": 0.5433044637, "include": true, "reason": "import numpy", "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422158380861, "lm_q2_score": 0.9149009613738741, "lm_q1q2_score": 0.8702009276735418}}
{"text": "import math\nimport numpy as np\n\ndef primes_up_to(n):\n    non_prime = np.zeros(n+1, dtype=bool)\n    non_prime[0] = True\n    non_prime[1] = True\n    candidate = 2\n    last_candidate = math.ceil(math.sqrt(n))\n    while candidate <= last_candidate:\n        while non_prime[candidate]:\n            candidate += 1\n        i = candidate\n        while i*candidate <= n:\n            non_prime[i*candidate] = True\n            i += 1\n        candidate += 1\n    primes = []\n    for i in xrange(n+1):\n        if not non_prime[i]:\n            primes.append(i)\n    return primes\n", "meta": {"hexsha": "c69630e0a352485c3c3c649b600340235e17492e", "size": 564, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/src/practical-guide/examples/src/sieve.py", "max_stars_repo_name": "aless80/doconce_hplgit_fork", "max_stars_repo_head_hexsha": "23fb3a7206fccafb7ef829a9a37bea2298b3ddb9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 305, "max_stars_repo_stars_event_min_datetime": "2015-01-07T06:57:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T01:45:25.000Z", "max_issues_repo_path": "doc/src/practical-guide/examples/src/sieve.py", "max_issues_repo_name": "aless80/doconce-1", "max_issues_repo_head_hexsha": "23fb3a7206fccafb7ef829a9a37bea2298b3ddb9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 163, "max_issues_repo_issues_event_min_datetime": "2015-01-08T11:03:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-17T12:54:46.000Z", "max_forks_repo_path": "doc/src/practical-guide/examples/src/sieve.py", "max_forks_repo_name": "aless80/doconce-1", "max_forks_repo_head_hexsha": "23fb3a7206fccafb7ef829a9a37bea2298b3ddb9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 91, "max_forks_repo_forks_event_min_datetime": "2015-03-19T17:17:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T15:45:20.000Z", "avg_line_length": 24.5217391304, "max_line_length": 44, "alphanum_fraction": 0.5656028369, "include": true, "reason": "import numpy", "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079558, "lm_q2_score": 0.9149009503523291, "lm_q1q2_score": 0.8702009197246415}}
{"text": "import numpy as np\n\ndef linear_solve(A, b):\n  AAT = A@(A.T)\n  # w = np.linalg.solve(AAT, b)\n  w = np.linalg.lstsq(AAT, b)[0]\n  x = (A.T)@w\n  return x\n\n\nclass RandomSinModel:\n  '''\n  H(n) :  h(x) = \\sum_j [b_j*sin(a_0+a_1*x+a_2*x^2+...)]\n  '''\n\n  def __init__(self, n, MAX_DEGREE=3):\n      self.D = MAX_DEGREE+1\n      self.n = n # No. of Features\n      self.F = np.random.rand(self.D, self.n) * 10 # Feature Tranformation matrix D X n\n      self.a = None\n  \n  def generate_features(self, X):\n      X = X.flatten()\n      arrays = [X**i for i in range(self.D)] # includes constant\n      A = np.stack(arrays, axis = 1)        # N_data X D\n      A = A @ self.F                        # N_data X n\n      A = np.sin(A)\n      return A\n\n  def fit(self, X, Y, refit=False):\n      '''\n      X: (d,1)\n      Y: (d,1)\n      '''\n      if self.a and (not refit):\n         raise ValueError(\"Re-Fitting\")\n      A = self.generate_features(X)\n      # self.a = linear_solve(A, Y)\n      self.a = np.linalg.lstsq(A, Y)[0]\n      return self\n\n  def predict(self, X, A=None):\n      if (not A):\n        A = self.generate_features(X)\n      return A@self.a\n  \n  def score(self, X, y):\n      '''\n        RMSE\n      '''\n      y_pred = self.predict(X=X)\n      return np.linalg.norm(y-y_pred, ord=2)/np.sqrt(X.shape[0])\n\n", "meta": {"hexsha": "b6746d642f905abd4b65723a7cfc4471ca6d1bbf", "size": 1288, "ext": "py", "lang": "Python", "max_stars_repo_path": "RandomSinModel.py", "max_stars_repo_name": "layjain/Deep-Multiple-Descent", "max_stars_repo_head_hexsha": "f26afc198ee3c261736b8d80cd6511804666ee10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RandomSinModel.py", "max_issues_repo_name": "layjain/Deep-Multiple-Descent", "max_issues_repo_head_hexsha": "f26afc198ee3c261736b8d80cd6511804666ee10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RandomSinModel.py", "max_forks_repo_name": "layjain/Deep-Multiple-Descent", "max_forks_repo_head_hexsha": "f26afc198ee3c261736b8d80cd6511804666ee10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8518518519, "max_line_length": 87, "alphanum_fraction": 0.522515528, "include": true, "reason": "import numpy", "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422172230208, "lm_q2_score": 0.9149009474519223, "lm_q1q2_score": 0.8702009156988638}}
{"text": "import numpy as np\nfrom matplotlib import pyplot as plt \n\n\n'''\nImplement a function that given the domain interval, the forcing function, the number of discretization points, \nthe boundary conditions, returns the matrix  and the the right hand side b.\n'''\ndef finDif(omega, f, n, bc):\n    span = omega[ -1 ] - omega[ 0 ]\n    delta = span / ( n - 1 )\n\n    # A's diagonals \n    diags = [\n        30 * np.ones( (n,) ),\n        -16 * np.ones( (n - 1,) ),  \n        np.ones( (n - 2,) ) \n    ]\n\n    A = np.diag( diags[ 0 ], 0 ) \\\n        + np.diag( diags[ 1 ], -1 ) \\\n        + np.diag( diags[ 1 ], 1 ) \\\n        + np.diag( diags[ 2 ], -2 ) \\\n        + np.diag( diags[ 2 ], 2 )\n    \n    A /= (12 * delta**2) \n\n    x = np.linspace( omega[ 0 ], omega[ -1 ], n )\n    b = f( x )\n\n    # boundary conditions\n    A[ 0, : ] = 0\n    A[ :, 0 ] = 0\n    A[ 0, 0 ] = 1\n    b[ 0 ] = bc[ 0 ]\n\n    A[ -1, : ] = 0\n    A[ :, -1 ] = 0\n    A[ -1, -1 ] = 1\n    b[ -1 ] = bc[ -1 ] \n    return (A, b)\n\n\nomega = [ 0, np.pi ]\nf = lambda x : np.sin(x)\n\nn = 100\nbc = [ 0, 0 ]\n(A, b) = finDif( omega, f, n, bc )\n\nprint(A)\nprint(b)\n\n'''\nImplement two functions that compute the LU and the Cholesky factorization of the system matrix A\n'''\ndef LU(A, tol=1e-15):\n    A = A.copy()\n    size = len( A )\n\n    for k in range(size - 1):\n        pivot = A[ k, k ]\n        if abs(pivot) < tol:\n            raise RuntimeError(\"Null pivot\")\n\n        for j in range( k + 1, size ): \n            A[ j, k ] /= pivot \n\n        for j in range( k + 1, size ):\n            A[ k + 1 : size, j ] -= A[ k + 1 : size, k ] * A[ k, j ] \n\n    L = np.tril( A )\n    for i in range( size ):\n        L[ i, i ] = 1.0\n\n    U = np.triu( A )\n    return (L, U)\n\n(L, U) = LU( A )\nprint(L, U)\n\n\ndef cholesky(A):\n    A = A.copy()\n    size = len( A )\n    \n    for k in range( size - 1 ):\n        A[ k, k ] = np.sqrt(A[ k, k ])\n\n        A[ k + 1 : size, k ] = A[ k + 1 : size, k ] / A[ k, k ]\n\n        for j in range(k+1,size):\n            A[ j : size, j ] = A[ j : size, j ] - A[ j : size, k ] * A[ j, k ]\n\n    \n    A[ -1, -1 ] = np.sqrt(A[ -1, -1 ])\n\n    L = np.tril( A )\n    Lt = L.transpose()\n    return (L, Lt)\n\n(Ht, H) = cholesky( A )\nprint(Ht, H)\n\n\n# Implement forward and backward substitution functions to exploit the developed factorization methods to solve the \n# derived linear system of equations.\n\n\ndef L_solve(L, rhs):\n    size = len( L )\n    x = np.zeros( size )\n\n    x[ 0 ] = rhs[ 0 ] / L[ 0, 0 ]\n\n    for i in range( 1, size ):\n        x[ i ] = ( rhs[ i ] - np.dot( L[ i, 0 : i ], x[ 0 : i ] ) ) / L[ i, i ]\n    return x\n\ndef U_solve(U, rhs):\n    size = len( U )\n    x = np.zeros( size )\n\n    x[ -1 ] = rhs[ -1 ] / L[ -1, -1 ]\n\n    for i in reversed( range( size - 1 ) ):\n        x[ i ] = ( rhs[ i ] - np.dot( U[ i, i + 1 : size ], x[ i + 1 : size ] ) ) / U[ i, i ]\n    return x\n\n'''\nSolve the derived linear system using the implemented functions and plot the computed solution:\n'''\n\n(fig, ax) = plt.subplots()\n\n# exact solution \nx = np.linspace( omega[0], omega[-1], n)\nu_exact = np.sin( x )\n\nax.plot( x, u_exact, label = 'exact' )\n\n\n# using LU factorization\nw = L_solve( L, b )\nu = U_solve( U, w )\n\nax.plot( x, u, label = 'lu' )\n\n\n# using cholesky factorizations \nw = L_solve( Ht, b )\nu = U_solve( H, w )\n\nax.plot( x, u, label = 'cholesky' )\n\nax.legend()\nax.grid()\n\nfig.savefig( 'plot1.svg' )\n\n\n'''\nConsidering the new domain [0, 1] and the forcing term  with B.C. , \non  produce a plot and a table where you show the decay of the error w.r.t. the number of grid points. \n(The analytical solution for the above problems is )\n'''\n\ndef compute_errors(omega, f, fex, bc, npoints):\n    errors = []\n\n    for idx in range( len(npoints) ):\n        npts = npoints[ idx ]\n        \n        x = np.linspace( omega[0], omega[1], npts )\n        ex = fex( x )\n\n        ( A, b ) = finDif( omega, f, npts, bc )\n        ( L, U ) = LU( A )\n        w = L_solve( L, b )\n        u = U_solve( U, w )\n\n        err = sum( ( ex - u )**2 )**0.5\n        errors.append( err )\n    return errors    \n\n\nomega = [ 0, 1 ]\n\ndef func(x): \n    return x * (1 - x)\n\ndef fex(x): \n    return x**4/12 - x**3/6 + x/12\n\nbc = [ 0, 0 ]\n\nnpoints = np.arange( 10, 310, 10 )\n\nerrors = compute_errors( omega, func, fex, bc, npoints )\n\n(fig, ax) = plt.subplots()\n\nax.set_yscale( 'log' )\nax.plot( npoints, errors )\n\nfig.savefig( 'plot2.svg' )\n\n\n'''\nExploit the derived LU factorizations to compute the condition number of the system's matrix  using the original problem formulation.\n'''\ndef PM(A, z0, tol=1e-12, nmax=10000):\n    q = z0 / np.linalg.norm( z0, 2 )\n\n    it = 0\n    err = tol + 1\n    \n    while it < nmax and err > tol:\n        z = A.dot( q )\n        l = q.T.dot( z )\n        err = np.linalg.norm( z - l*q, 2 )\n        q = z / np.linalg.norm( z, 2 )\n        it = it + 1\n    return (l, q)\n\ndef IPM(A, x0, mu, eps=1.0e-12, nmax=10000):\n    M = A - mu * np.eye(len(A))\n\n    (L, U) = LU( M )\n    q = x0 / np.linalg.norm( x0, 2 )\n    \n    err = eps + 1.0\n    it = 0\n    while err > eps and it < nmax:\n        y = L_solve( L, q )\n        x = U_solve( U, y )\n        q = x / np.linalg.norm( x, 2 )\n        z = A.dot( q )\n        l = q.T.dot( z )\n        err = np.linalg.norm( z - l*q, 2 )\n        it = it + 1\n    return (l, q)\n\n\ndef condNumb(A):\n    z0 = np.ones( ( len(A), ))\n    lmax = PM( A, z0 )[ 0 ]\n    lmin = IPM( A, z0, 0.0 )[ 0 ]\n\n    condNum = lmax / lmin\n    return condNum\n\ncondNum = condNumb( A )\nprint( condNum )\n\n\n'''\nImplement a preconditioned Conjugant Gradient method to solve the original linear system of equations using an iterative method:\n\n'''\ndef conjugate_gradient(A, b, P, nmax=len(A), eps=1e-10):\n    x = np.zeros_like( b )\n    r = b - A.dot( x )\n\n    rho0 = 1 \n    p0 = np.zeros_like( b )\n\n    err = eps + 1.0\n    \n    it = 1\n    while it < nmax and err > eps:\n        z = np.linalg.solve( P, r )\n        rho = r.dot( z )\n\n        if it > 1:\n            beta = rho / rho0 \n            p = z + beta * p0\n        \n        else:\n            p = z\n\n        q = A.dot( p )\n        alpha = rho / p.dot( q )\n\n        x += p * alpha\n        r -= q * alpha\n        \n        p0 = p\n        rho0 = rho\n\n        err = np.linalg.norm( r, 2 )\n        it = it + 1\n\n    print( f'iterations: {it}' )\n    print( f'error: {err}' )\n    return x\n\n\nomega = [ 0, np.pi ]\nx = np.linspace( omega[ 0 ], omega[ -1 ], n )\n\nex = np.sin( x )\n\nu = conjugate_gradient( A, b, np.diag(np.diag( A ) ))\n\n(fig, ax) = plt.subplots()\n\nax.plot( x, ex, label = 'exact' )\nax.plot( x, u, label = 'CG' )\n\nax.legend()\nfig.savefig( 'plot3.svg' )\n\nexit( 0 )\n\n'''\nConsider the following time dependent variation of the PDE starting from the orginal problem formulation:\n\nfor , with  and \n\nUse the same finite difference scheme to derive the semi-discrete formulation and solve it using a forward Euler's method.\n\nPlot the time dependent solution solution at , , \n'''\n\n#TODO \n'''\nGiven the original  system, implement an algorithm to compute the eigenvalues and eigenvectors of the matrix . \noExploit the computed LU factorization\n'''\n\n#TODO\n\n'''\nCompute the inverse of the matrix A exploiting the derived LU factorization\n\n'''\n#TODO \n\n'''\nConsider the following Cauchy problem\n \nImplement a Backward Euler's method in a suitable function and solve the resulting non-linear equation using a Newton's method.\n'''\n\n#TODO\n", "meta": {"hexsha": "605fa7381485ef0bb2c864645d96e83d10a93a37", "size": 7298, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "mbarnaba/numerical-analysis-2021-2022", "max_stars_repo_head_hexsha": "93296fd53c1871ff6d09b71c88e6216293188f54", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.py", "max_issues_repo_name": "mbarnaba/numerical-analysis-2021-2022", "max_issues_repo_head_hexsha": "93296fd53c1871ff6d09b71c88e6216293188f54", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "mbarnaba/numerical-analysis-2021-2022", "max_forks_repo_head_hexsha": "93296fd53c1871ff6d09b71c88e6216293188f54", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0317002882, "max_line_length": 133, "alphanum_fraction": 0.5209646478, "include": true, "reason": "import numpy", "num_tokens": 2435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241965169939, "lm_q2_score": 0.8976952989498448, "lm_q1q2_score": 0.8701577743716409}}
{"text": "import numpy as np\n\nfrom source.week2.ex2_1 import construct_element_table, xy\n\nabc = np.zeros((3, 3))\ndelta = 0\n\n\ndef a(j, k, X, Y):\n    return X[j] * Y[k] - X[k] * Y[j]\n\n\ndef b(Y, j, k):\n    return Y[j] - Y[k]\n\n\ndef c(X, j, k):\n    return X[k] - X[j]\n\n\ndef basfun(element_idx, X, Y, etov_dict):\n    \"\"\"\n    :param element_idx:\n    :param X:\n    :param Y:\n    :param etov_dict:\n    :return:\n    \"\"\"\n\n    # Formula 2.3\n\n    abc = np.zeros((3, 3))\n    v1, v2, v3 = etov_dict[element_idx]\n    v1 -= 1\n    v2 -= 1\n    v3 -= 1\n\n    abc[0][0] = X[v2] * Y[v3] - X[v3] * Y[v2]\n    #   1  b\n    abc[0][1] = Y[v2] - Y[v3]\n    #   1  c\n    abc[0][2] = X[v3] - X[v2]\n\n    #   2  a\n    abc[1][0] = X[v1] * Y[v3] - X[v3] * Y[v1]\n    #   2  b\n    abc[1][1] = -(Y[v1] - Y[v3])\n    #   2  c\n    abc[1][2] = X[v3] - X[v1]\n\n    #   3  a\n    abc[2][0] = X[v1] * Y[v2] - X[v2] * Y[v1]\n    #   3  b\n    abc[2][1] = Y[v1] - Y[v2]\n    #   3  c\n    abc[2][2] = X[v2] - X[v1]\n\n    # Formula 2.1 TODO\n    # Delta : positive due to clockwise ordering\n    _delta = 0.5 * (X[v2] * Y[v3] - Y[v2] * X[v3] - (X[v1] * Y[v3] - Y[v1] * X[v3]) + X[v1] * Y[v2] - Y[v1] * X[v2])\n\n    return abc, _delta\n\n\ndef main():\n    \"\"\"Test case:\n    (x_0 , y_0 ) = (−2.5, −4.8), L_1 = 7.6, L_2 = 5.9, noelms1 = 4, noelms2 = 3\n    \"\"\"\n    X, Y = xy(-2.5, -4.8, 7.6, 5.9, 4, 3)\n    etov_dict, M = construct_element_table(4, 3)\n    element_idx = 4\n    test_element = basfun(element_idx, X, Y, etov_dict)\n    print(\"delta\", test_element[1])\n    print(\"abc\", test_element[0])\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "6669d4fd04c645e3ebfb33feba74102122095196", "size": 1562, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/week2/ex2_2a.py", "max_stars_repo_name": "ArturPrzybysz/finite-element-method", "max_stars_repo_head_hexsha": "f6edc466c3020f3c7d7563458cc9fc60ba378d43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/week2/ex2_2a.py", "max_issues_repo_name": "ArturPrzybysz/finite-element-method", "max_issues_repo_head_hexsha": "f6edc466c3020f3c7d7563458cc9fc60ba378d43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/week2/ex2_2a.py", "max_forks_repo_name": "ArturPrzybysz/finite-element-method", "max_forks_repo_head_hexsha": "f6edc466c3020f3c7d7563458cc9fc60ba378d43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-04T17:16:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T17:16:50.000Z", "avg_line_length": 19.7721518987, "max_line_length": 116, "alphanum_fraction": 0.4692701665, "include": true, "reason": "import numpy", "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242018339897, "lm_q2_score": 0.8976952852648487, "lm_q1q2_score": 0.8701577658794851}}
{"text": "import timeit\n\nimport numpy as np\nimport numpy.linalg\nfrom scipy.linalg import cho_factor, cho_solve\n\n# We are trying to solve the following system\n# (A.T * A) * x = A.T * b\n# Where x are the polynomial coefficients and b is are the input points\n\n# First we build A\ndeg = 3\nx = np.arange(50 * 1.0)\nA = np.vstack(tuple(x**n for n in range(deg, -1, -1))).T\n\n# The first way to solve this is using the pseudoinverse, which can be precomputed\n# x = (A.T * A)^-1 * A^T * b = PINV b\nPINV = np.linalg.pinv(A)\n\n# Another way is using the Cholesky decomposition\n# We can note that at (A.T * A) is always positive definite\n# By precomputing the Cholesky decomposition we can efficiently solve\n# systems of the form (A.T * A) x = c\nCHO = cho_factor(np.dot(A.T, A))\n\n\ndef model_polyfit_old(points, deg=3):\n  A = np.vstack(tuple(x**n for n in range(deg, -1, -1))).T\n  pinv = np.linalg.pinv(A)\n  return np.dot(pinv, map(float, points))\n\n\ndef model_polyfit(points, deg=3):\n  A = np.vander(x, deg + 1)\n  pinv = np.linalg.pinv(A)\n  return np.dot(pinv, map(float, points))\n\n\ndef model_polyfit_cho(points, deg=3):\n  A = np.vander(x, deg + 1)\n  cho = cho_factor(np.dot(A.T, A))\n  c = np.dot(A.T, points)\n  return cho_solve(cho, c, check_finite=False)\n\n\ndef model_polyfit_np(points, deg=3):\n  return np.polyfit(x, points, deg)\n\n\ndef model_polyfit_lstsq(points, deg=3):\n  A = np.vander(x, deg + 1)\n  return np.linalg.lstsq(A, points, rcond=None)[0]\n\n\nTEST_DATA = np.linspace(0, 5, num=50) + 1.\n\n\ndef time_pinv_old():\n  model_polyfit_old(TEST_DATA)\n\n\ndef time_pinv():\n  model_polyfit(TEST_DATA)\n\n\ndef time_cho():\n  model_polyfit_cho(TEST_DATA)\n\n\ndef time_np():\n  model_polyfit_np(TEST_DATA)\n\n\ndef time_lstsq():\n  model_polyfit_lstsq(TEST_DATA)\n\n\nif __name__ == \"__main__\":\n  # Verify correct results\n  pinv_old = model_polyfit_old(TEST_DATA)\n  pinv = model_polyfit(TEST_DATA)\n  cho = model_polyfit_cho(TEST_DATA)\n  numpy = model_polyfit_np(TEST_DATA)\n  lstsq = model_polyfit_lstsq(TEST_DATA)\n\n  assert all(np.isclose(pinv, pinv_old))\n  assert all(np.isclose(pinv, cho))\n  assert all(np.isclose(pinv, numpy))\n  assert all(np.isclose(pinv, lstsq))\n\n  # Run benchmark\n  print(\"Pseudo inverse (old)\", timeit.timeit(\"time_pinv_old()\", setup=\"from __main__ import time_pinv_old\", number=10000))\n  print(\"Pseudo inverse\", timeit.timeit(\"time_pinv()\", setup=\"from __main__ import time_pinv\", number=10000))\n  print(\"Cholesky\", timeit.timeit(\"time_cho()\", setup=\"from __main__ import time_cho\", number=10000))\n  print(\"Numpy leastsq\", timeit.timeit(\"time_lstsq()\", setup=\"from __main__ import time_lstsq\", number=10000))\n  print(\"Numpy polyfit\", timeit.timeit(\"time_np()\", setup=\"from __main__ import time_np\", number=10000))\n", "meta": {"hexsha": "2909a45b4fde1ec2b68213ce7a8ab0f5d40b5964", "size": 2694, "ext": "py", "lang": "Python", "max_stars_repo_path": "selfdrive/debug/internal/polyfit_bench.py", "max_stars_repo_name": "pevdh/openpilot", "max_stars_repo_head_hexsha": "fca82ba503a663ec97b7ba89c2c3da80aef739b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-05-20T13:20:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T07:55:20.000Z", "max_issues_repo_path": "selfdrive/debug/internal/polyfit_bench.py", "max_issues_repo_name": "pevdh/openpilot", "max_issues_repo_head_hexsha": "fca82ba503a663ec97b7ba89c2c3da80aef739b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-04-12T21:34:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-15T22:22:15.000Z", "max_forks_repo_path": "selfdrive/debug/internal/polyfit_bench.py", "max_forks_repo_name": "pevdh/openpilot", "max_forks_repo_head_hexsha": "fca82ba503a663ec97b7ba89c2c3da80aef739b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-03-06T20:58:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-21T01:01:37.000Z", "avg_line_length": 27.7731958763, "max_line_length": 123, "alphanum_fraction": 0.708982925, "include": true, "reason": "import numpy,from scipy", "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242000616579, "lm_q2_score": 0.8976952838963489, "lm_q1q2_score": 0.8701577629619512}}
{"text": "import numpy as np\nimport load_foil as lf\nimport matplotlib.pyplot as mp;\n\n# Returns the second derivative of the interpolating function at each point where\n# xa is the array containing the x coordinate of each point\n# ya is the array containing the y coordinate of each point\n# n is the number of points\ndef spline(xa, ya, n):\n\tu = np.zeros(n)\n\ty2 = np.zeros(n)\n\n\ty2[1] = 0.0\n\tu[1] = 0.0\n\n\tfor i in range(1, n-1):\n\t\tsig = (xa[i] - xa[i-1]) / (xa[i+1] - xa[i-1])\n\t\tp = sig * y2[i-1] + 2.0\n\t\ty2[i] = (sig - 1.0) / p\n\t\tu[i] = (ya[i+1] - ya[i]) / (xa[i+1] - xa[i]) - (ya[i] - ya[i-1]) / (xa[i] - xa[i-1])\n\t\tu[i] = (6.0 * u[i] / (xa[i+1] - xa[i-1]) - sig * u[i-1]) / p\n\n\ty2[n - 1] = 0.0\n\tfor k in range(n-2, 0, -1):\n\t\ty2[k] = y2[k] * y2[k+1] + u[k]\n\n\treturn y2\n\n# Return the value of the spline at a given x coordinate where\n# xa is the array containing the x coordinate of each point\n# ya is the array containing the y coordinate of each point\n# y2a is the array containing the second derivaive of the function at each point\n# n is the number of points\ndef splint(xa, ya, y2a, n, x):\n\tk = 0\n\th = 0.0\n\tb = 0.0\n\ta = 0.0\n\tklo=1\n\tkhi=n\n\twhile khi - klo > 1:\n\t\tk = (khi + klo) // 2\n\t\tif xa[k - 1] > x:\n\t\t\tkhi = k\n\t\telse:\n\t\t\tklo = k\n\n\tkhi = khi - 1\n\tklo = klo - 1\n\n\th = xa[khi] - xa[klo]\n\n\tif (h == 0.0):\n\t\traise Exception(\"Bad xa input to routine splint\")\n\n\ta = (xa[khi] - x) / h\n\tb = (x - xa[klo]) / h\n\n\treturn a * ya[klo] + b * ya[khi] + (((a**3) - a) * y2a[klo] + ((b**3) - b) * y2a[khi]) * (h * h) / 6.0\n\n# Return the spline function passing through each provided point where\n# xa is the array containing the x coordinate of each point\n# ya is the array containing the y coordinate of each point\n# n is the number of points\ndef spline_fun(xa, ya, n):\n\ty2 = spline(xa, ya, n)\n\treturn lambda x: splint(xa, ya, y2, n, x)\n\n\nif __name__ == \"__main__\":\n\t(dim,ex,ey,ix,iy) = lf.load_foil(\"k1.dat\")\n\tespline = spline_fun(ex, ey, int(dim[0]))\n\tispline = spline_fun(ix, iy, int(dim[1]))\n\n\tr = np.arange(0, 1.00001, 0.001)\n\n\tmp.plot(r, list(map(espline, r)), linewidth = 1.0)\n\tmp.plot(ex, ey, marker='.', linestyle=\"None\")\n\tmp.plot(r, list(map(ispline, r)), linewidth = 1.0)\n\tmp.plot(ix, iy, marker='.', linestyle=\"None\")\n\tmp.axis('equal')\n\tmp.title(\"Cubic spline interpolation of the airfoil\")\n\tmp.show()\n\n\n\n", "meta": {"hexsha": "9f8fdcb96b959cd4b15ca5148171d6e324db9d08", "size": 2294, "ext": "py", "lang": "Python", "max_stars_repo_path": "spline.py", "max_stars_repo_name": "ImadProjects/Interpolation-and-integration-methods", "max_stars_repo_head_hexsha": "f5807c7fafb721f82f3368983946d5c1aab9ad62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spline.py", "max_issues_repo_name": "ImadProjects/Interpolation-and-integration-methods", "max_issues_repo_head_hexsha": "f5807c7fafb721f82f3368983946d5c1aab9ad62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spline.py", "max_forks_repo_name": "ImadProjects/Interpolation-and-integration-methods", "max_forks_repo_head_hexsha": "f5807c7fafb721f82f3368983946d5c1aab9ad62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.367816092, "max_line_length": 103, "alphanum_fraction": 0.6068003487, "include": true, "reason": "import numpy", "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426428022031, "lm_q2_score": 0.8933094124452288, "lm_q1q2_score": 0.8701214609382338}}
{"text": "import numpy as np\n\ndef comp_k_out_of_n(pf, k):\n    '''\n    COMPUTE PROBABILITY OF FAILURE OF THE SYSTEM RELIABILITY\n    ========================================================\n    \n    The system is good if and only if at least K of its n components are good.\n    \n    => Model assumptions:\n        1. Components and the system are 2-state (eg, good or bad)\n        2. Component states are statiscally independent\n        3. The system is good if and only if at least k of its n components \n           are good\n    \n    Source: IEEE TRANSACTIONS ON RELIABILITY, VOL. R-33, NO. 4, OCTOBER 1984\n            page 321, R.E. Barlow and K.D. Heidtmann\n    \n    Parameters\n    ----------\n    pf : array-like\n        the probability of failure of each element\n    k : integer\n        the number of components necessary to make the system work\n\n    Retuns\n    ------\n    PF_sys : float\n        system probability of failure\n    '''\n    \n    pf = np.array(pf)\n    n = pf.size\n    \n    # in case of no element\n    if n == 0:\n        return np.nan\n    \n    # n = len(pf)\n    # k = ncomp-1\n    PF_sys = np.zeros(1)\n    nk = n-k\n    m = k+1\n    A = np.zeros(m+1)\n    A [1] = 1\n    L = 1\n    for j in range(1,n+1):\n        h = j + 1\n        Rel = 1-pf[j-1]\n        if nk < j:\n            L = h - nk\n        if k < j:\n            A[m] = A[m] + A[k]*Rel\n            h = k\n        for i in range(h, L-1, -1):\n            A[i] = A[i] + (A[i-1]-A[i])*Rel\n    PF_sys = 1-A[m]\n    return PF_sys   \n\nclass System_of_Subsystems:\n    \"\"\"\n    System of Subsystems\n    ====================\n\n    Separate all systems components in k-out-of-n susbsystems according to an \n    assingment vector. Subsystems are in series.\n\n    Parameters:\n    -----------\n    assignments : array\n        array with subsystem assignment of each component.\n    k_list : array\n        list of k values of each subsystem.\n    \"\"\"\n    def __init__(self, assignments, k_dict):\n        self.assignments = np.array(assignments)\n        self.k_dict = k_dict\n\n    def compute_system_pf(self, pf_list):\n        \"\"\"\n        Compute system P_f\n        ==================\n\n        Compute system probability of failure.\n\n        Parameters:\n        -----------\n        pf_list : array\n            list of probabilities of failure of each component.\n        \n        Returns:\n        --------\n        pf_sys : float\n            probability of failure of th eentire system\n        \"\"\"\n        pf_list = np.array(pf_list)\n        subsystem_pfs = []\n        for zone, k in self.k_dict.items():\n            zone_pfs = pf_list[self.assignments == zone]\n            subsystem_pfs.append(comp_k_out_of_n(zone_pfs, k))\n        return comp_k_out_of_n(subsystem_pfs, len(subsystem_pfs))\n", "meta": {"hexsha": "58bb74eb4813cb4f80fb0243f696bc90afa90c7c", "size": 2717, "ext": "py", "lang": "Python", "max_stars_repo_path": "reliabpy/models/system_effects.py", "max_stars_repo_name": "FelipeGiro/ReliabiliPy", "max_stars_repo_head_hexsha": "42624a65504a959f66a64ae2ad2ccfb5af5ae9b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reliabpy/models/system_effects.py", "max_issues_repo_name": "FelipeGiro/ReliabiliPy", "max_issues_repo_head_hexsha": "42624a65504a959f66a64ae2ad2ccfb5af5ae9b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-08-13T15:31:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-13T15:31:34.000Z", "max_forks_repo_path": "reliabpy/models/system_effects.py", "max_forks_repo_name": "FelipeGiro/reliabpy", "max_forks_repo_head_hexsha": "42624a65504a959f66a64ae2ad2ccfb5af5ae9b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.637254902, "max_line_length": 78, "alphanum_fraction": 0.5347810085, "include": true, "reason": "import numpy", "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426405416754, "lm_q2_score": 0.8933093961129794, "lm_q1q2_score": 0.870121443010576}}
{"text": "# -*- coding: utf-8 -*-\n\n\"\"\"\nThe module provides parametric equations for well-known curves\n\n\"\"\"\n\nimport numpy as np\nfrom scipy.special import fresnel\n\nfrom skcurve import Curve\n\n\ndef arc(t_start: float = 0.0,\n        t_stop: float = np.pi * 2,\n        p_count: int = 49,\n        r: float = 1.0,\n        c: float = 0.0) -> Curve:\n    r\"\"\"Produces arc or full circle curve\n\n    Produces arc using the following parametric equations:\n\n    .. math::\n\n        x = cos(\\theta) \\dot r + c\n        y = sin(\\theta) \\dot r + c\n\n    By default computes full circle.\n\n    Parameters\n    ----------\n    t_start : float\n        Start theta\n    t_stop : float\n        Stop theta\n    p_count : int\n        The number of points\n    r : float\n        Circle radius\n    c : float\n        Circle center\n\n    Returns\n    -------\n    curve : Curve\n        Acr curve\n\n    \"\"\"\n\n    theta = np.linspace(t_start, t_stop, p_count)\n\n    x = np.cos(theta) * r + c\n    y = np.sin(theta) * r + c\n\n    return Curve([x, y], tdata=theta)\n\n\ndef lemniscate_of_bernoulli(t_start: float = 0.0,\n                            t_stop: float = np.pi*2,\n                            p_count: int = 101,\n                            c: float = 1.0) -> Curve:\n    \"\"\"Produces Lemniscate of Bernoulli curve\n\n    Parameters\n    ----------\n    t_start\n    t_stop\n    p_count\n    c\n\n    Returns\n    -------\n\n    \"\"\"\n\n    theta = np.linspace(t_start, t_stop, p_count)\n\n    c_sq2 = c * np.sqrt(2)\n    cos_t = np.cos(theta)\n    sin_t = np.sin(theta)\n    denominator = sin_t ** 2 + 1\n\n    x = (c_sq2 * cos_t) / denominator\n    y = (c_sq2 * cos_t * sin_t) / denominator\n\n    return Curve([x, y], tdata=theta)\n\n\ndef archimedean_spiral(t_start: float = 0.0,\n                       t_stop: float = 5 * np.pi,\n                       p_count: int = 200,\n                       a: float = 1.5,\n                       b: float = -2.4) -> Curve:\n    \"\"\"Produces Archimedean spiral curve\n\n    Parameters\n    ----------\n    t_start\n    t_stop\n    p_count\n    a\n    b\n\n    Returns\n    -------\n\n    \"\"\"\n\n    theta = np.linspace(t_start, t_stop, p_count)\n    x = (a + b * theta) * np.cos(theta)\n    y = (a + b * theta) * np.sin(theta)\n\n    return Curve([x, y], tdata=theta)\n\n\ndef euler_spiral(t_start: float = -3 * np.pi / 2,\n                 t_stop: float = 3 * np.pi / 2,\n                 p_count: int = 1000) -> Curve:\n    \"\"\"Produces Euler spiral curve\n\n    Parameters\n    ----------\n    t_start\n    t_stop\n    p_count\n\n    Returns\n    -------\n\n    \"\"\"\n\n    t = np.linspace(t_start, t_stop, p_count)\n    ssa, csa = fresnel(t)\n\n    return Curve([csa, ssa], tdata=t)\n\n\ndef lissajous(t_start: float = 0.0,\n              t_stop: float = 2*np.pi,\n              p_count: int = 101,\n              a_ampl: float = 1.0,\n              b_ampl: float = 1.0,\n              a: float = 3.0,\n              b: float = 2.0,\n              d: float = 0.0,) -> Curve:\n    \"\"\"\n\n    Parameters\n    ----------\n    t_start\n    t_stop\n    p_count\n    a_ampl\n    b_ampl\n    a\n    b\n    d\n\n    Returns\n    -------\n\n    \"\"\"\n\n    theta = np.linspace(t_start, t_stop, p_count)\n\n    x = a_ampl * np.sin(a * theta + d)\n    y = b_ampl * np.sin(b * theta)\n\n    return Curve([x, y], tdata=theta)\n\n\ndef helix(t_start: float = -3 * np.pi,\n          t_stop: float = 3 * np.pi,\n          p_count: int = 100,\n          a: float = 1.0,\n          b: float = 1.0) -> Curve:\n    \"\"\"Produces 3-d helix curve\n\n    Parameters\n    ----------\n    t_start : float\n    t_stop : float\n    p_count : int\n    a : float\n    b : float\n\n    Returns\n    -------\n\n    \"\"\"\n\n    theta = np.linspace(t_start, t_stop, p_count)\n    x = np.sin(theta) * a\n    y = np.cos(theta) * a\n    z = theta * b\n\n    return Curve([x, y, z], tdata=theta)\n\n\ndef irregular_helix(t_start: float = -4 * np.pi,\n                    t_stop: float = 4 * np.pi,\n                    z_start: float = -2.0,\n                    z_stop: float = 2.0,\n                    p_count: int = 100) -> Curve:\n    \"\"\"Produces 3-d irregular helix curve\n\n    Parameters\n    ----------\n    t_start\n    t_stop\n    z_start\n    z_stop\n    p_count\n\n    Returns\n    -------\n\n    \"\"\"\n\n    theta = np.linspace(t_start, t_stop, p_count)\n    z = np.linspace(z_start, z_stop, p_count)\n    r = z ** 2 + 1\n    x = r * np.sin(theta)\n    y = r * np.cos(theta)\n\n    return Curve([x, y, z], tdata=theta)\n", "meta": {"hexsha": "5683d916b801714b6ca29103823f2a3cef7533b1", "size": 4316, "ext": "py", "lang": "Python", "max_stars_repo_path": "skcurve/curves.py", "max_stars_repo_name": "espdev/scikit-curve", "max_stars_repo_head_hexsha": "5fcb540ef3862adc01c95bb8629cd4b6de59581b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-01-15T12:32:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-04T04:15:18.000Z", "max_issues_repo_path": "skcurve/curves.py", "max_issues_repo_name": "espdev/scikit-curve", "max_issues_repo_head_hexsha": "5fcb540ef3862adc01c95bb8629cd4b6de59581b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skcurve/curves.py", "max_forks_repo_name": "espdev/scikit-curve", "max_forks_repo_head_hexsha": "5fcb540ef3862adc01c95bb8629cd4b6de59581b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.013215859, "max_line_length": 62, "alphanum_fraction": 0.4918906395, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305370909698, "lm_q2_score": 0.9032942138630786, "lm_q1q2_score": 0.8700805707704986}}
{"text": "import math\nfrom typing import Tuple, Union, Any\n\nimport numpy as np\nfrom numpy import dot\n\n\ndef unit_vector(vec: tuple):\n    \"\"\"\n\n    :param vec:\n    :return: unit vector\n    \"\"\"\n    return vec / np.linalg.norm(vec)\n\n\ndef angle_between_vector(v1: tuple, v2: tuple) -> float:\n    \"\"\"\n    two vectors have either the same direction -  https://stackoverflow.com/a/13849249/71522\n    :param v1:\n    :param v2:\n    :return:\n    \"\"\"\n    v1_u = unit_vector(v1)\n    v2_u = unit_vector(v2)\n    return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))\n\n\ndef dot_between_vector(v1: tuple, v2: tuple) -> Any:\n    \"\"\"\n    two vectors have either the same direction -  https://stackoverflow.com/a/13849249/71522\n    :param v1:\n    :param v2:\n    :return:\n    \"\"\"\n    v1_u = unit_vector(v1)\n    v2_u = unit_vector(v2)\n    return np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)\n\n\ndef get_point_after_certain_distance(\n    start: tuple, end: tuple, d: float, dt: float\n) -> Tuple[float, float]:\n    \"\"\"\n    https://math.stackexchange.com/questions/175896/finding-a-point-along-a-line-a-certain-distance-away-from-another-point\n\n    :param start:\n    :param end:\n    :param d:\n    :param dt:\n    :return:\n    \"\"\"\n    if d == 0:\n        return start\n    t = dt / d\n    new_x = ((1 - t) * start[0]) + (t * end[0])\n    new_y = ((1 - t) * start[1]) + (t * end[1])\n    return new_x, new_y\n\n\ndef get_midpoint(start: tuple, end: tuple) -> Tuple[float, float]:\n    \"\"\"\n    https://www.mathsisfun.com/algebra/line-midpoint.html\n\n    :param start:\n    :param end:\n    :return:\n    \"\"\"\n    return ((start[0] + end[0]) / 2), ((start[1] + end[1]) / 2)\n\n\ndef get_end_coordinate(\n    start: tuple, angle_in_degree: float, distance: float\n) -> Tuple[float, float]:\n    \"\"\"\n    # https://math.stackexchange.com/questions/39390/determining-end-coordinates-of-line-with-the-specified-length-and-angle\n\n    :param start:\n    :param angle_in_degree:\n    :param distance:\n    :return:\n    \"\"\"\n    x2 = start[0] + (distance * math.cos(angle_in_degree))\n    y2 = start[1] + (distance * math.sin(angle_in_degree))\n    return x2, y2\n\n\ndef get_center_of_mass(x, y) -> Tuple[Union[Any, float], Union[Any, float]]:\n    \"\"\"\n    https://math.stackexchange.com/questions/24485/find-the-average-of-a-collection-of-points-in-2d-space\n\n    :param x:\n    :param y:\n    :return:\n    \"\"\"\n    return np.mean(x), np.mean(y)\n\n\ndef get_perpendicular_point(\n    start: tuple, end: tuple, offset=10\n) -> Tuple[Tuple[float, float], Tuple[float, float]]:\n    \"\"\"\n    https://stackoverflow.com/questions/133897/how-do-you-find-a-point-at-a-given-perpendicular-distance-from-a-line?rq=1\n\n    :param start:\n    :param end:\n    :param offset:\n    :return:\n    \"\"\"\n    x1, y1 = start[0], start[1]\n    x2, y2 = end[0], end[1]\n\n    dx = x1 - x2\n    dy = y1 - y2\n\n    dist = math.sqrt((dx * dx) + (dy * dy))\n\n    dx /= dist\n    dy /= dist\n\n    x3 = x1 + (offset * dy)\n    y3 = y1 - (offset * dx)\n\n    x4 = x1 - (offset * dy)\n    y4 = y1 + (offset * dx)\n\n    return (x3, y3), (x4, y4)\n\n\ndef vector(p1, p2) -> Tuple[float, float]:\n    \"\"\"\n\n    :param p1:\n    :param p2:\n    :return:\n    \"\"\"\n    return p1[0] - p2[0], p1[1] - p2[1]\n\n\ndef cosine_similarity(p1, p2, p3):\n    \"\"\"\n\n    :param p1:\n    :param p2:\n    :param p3:\n    :return:\n    \"\"\"\n    a = vector((p1[0], p1[1]), (p2[0], p2[1]))\n    b = vector((p1[0], p1[1]), (p3[0], p3[1]))\n    return dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))\n\n\ndef diagonal_distance(p1: tuple, p2: tuple, d1: float, d2: float) -> float:\n    \"\"\"\n\n    :param p1:\n    :param p2:\n    :param d1:\n    :param d2:\n    :return:\n    \"\"\"\n    dx = abs(p1[0] - p2[0])\n    dy = abs(p1[1] - p2[1])\n\n    return d1 * (dx + dy) + (d2 - 2 * d1) * min(dx, dy)\n\n\ndef euclidean_distance(p1: tuple, p2: tuple) -> float:\n    \"\"\"\n\n    :param p1:\n    :param p2:\n    :return:\n    \"\"\"\n    return math.hypot(p2[0] - p1[0], p2[1] - p1[1])\n\n\ndef manhattan_distance(p1: tuple, p2: tuple) -> float:\n    \"\"\"\n\n    :param p1:\n    :param p2:\n    :return:\n    \"\"\"\n    return abs(p2[0] - p1[0]) + abs(p2[1] - p1[1])\n\n\ndef compute_center_of_mass(input_array, axis: int = 1):\n    \"\"\"\n    Compute center of mass\n\n    :param axis:\n    :param input_array: (dim x N)\n    :return:\n    \"\"\"\n    return np.mean(input_array, axis=axis)\n\n\ndef new_mass(mean, input_array):\n    \"\"\"\n    Subtract the corresponding center of mass from every point\n\n    new_mass = (dim x N) - (dim x 1)\n\n    :param mean:\n    :param input_array:\n    :return:\n    \"\"\"\n\n    return input_array - mean[:, np.newaxis]\n\n\ndef decompose_matrix(matrix):\n    \"\"\"\n\n    :param matrix:\n    :return:\n    \"\"\"\n\n    return np.linalg.svd(matrix)\n", "meta": {"hexsha": "ab596e38c9397d807c2859ac9c85bcda77784848", "size": 4613, "ext": "py", "lang": "Python", "max_stars_repo_path": "kaizen_mapping/utils/numerical.py", "max_stars_repo_name": "fuzailpalnak/kaizen", "max_stars_repo_head_hexsha": "432fbb780cd3725ecab51ee3daf74b1373a13c0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-10-11T09:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T18:34:55.000Z", "max_issues_repo_path": "kaizen_mapping/utils/numerical.py", "max_issues_repo_name": "safarzadeh-reza/kaizen", "max_issues_repo_head_hexsha": "432fbb780cd3725ecab51ee3daf74b1373a13c0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kaizen_mapping/utils/numerical.py", "max_forks_repo_name": "safarzadeh-reza/kaizen", "max_forks_repo_head_hexsha": "432fbb780cd3725ecab51ee3daf74b1373a13c0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-15T08:26:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T20:59:43.000Z", "avg_line_length": 20.8733031674, "max_line_length": 124, "alphanum_fraction": 0.5761977021, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305339244013, "lm_q2_score": 0.9032942034496964, "lm_q1q2_score": 0.8700805578796678}}
{"text": "'''\nMétodo de Butcher \ny algunos implemetados a partir de él: \nRK4: runge-kuta clásico \nRK2, con alfa beta parámetros\n'''\n\nimport sympy as sp\nimport numpy as np\n\ndef succ_butcher(F,x,y,a,b,h):\n    '''\n    f derivada\n    y(x) = y que es el valor inicial \n    h = variación\n    a,b son coeficiente del arreglo de butcher\n    | c_1 | a11 a12 ...a1n\n    | c_2 | a21 a22 ...a2n\n             ...\n    | c_n | an1 an2 ...ann\n    ------------------------\n          | b1   b2 ... bn\n          \n    y representa \n    \n    x_{n+1} = x_n + h \\sum_{j=1}^n b_j K_j(t_n, x_n)\n    k_i(t,x) = f(t+c_i h, x+ h \\sum_{j=1}^n a_{ij} k_j(t,x))\n          \n    '''\n    n=len(b)\n    c = [ sum(a[i]) for i in range(n)]\n    K = sp.symbols('k0:'+str(n))\n    \n    def fk(f,i,t,x,h):\n        '''Representa K_i(t,x) = f(t+c_ih, sum a K_j) )\n        '''\n        return f( t+c[i]*h, x+h*sum(\n        [ a[i][j]*K[j] for j in range(n)]) )\n\n    l=[ - K[i] + fk(F,i,x,y,h)    for i in range(n)]\n    \n    sk =sp.solve(l, K)\n\n    \n    def solk(K, sk):\n        '''Solve puede que no nos devuelva todas las soluciones si son 0'''\n        l = [j for j in range(n)]\n        for i in range(n):\n            if K[i] in sk:\n                l[i] = sk[K[i]]\n            else:\n                l[i] =0\n        return l\n\n    sk =solk(K,sk)\n    \n    return y + h*sum([ b[i]*sk[i] for i in range(n)] ) \n    \n  \ndef complete_butcher(F, x0, y0,xfinal, N, a, b):\n    '''\n    F función\n    x,y condiciones iniciales y(x_0) = y_0\n    xfinal = valor final hasta el que calcular\n    N número de intervalos \n    '''\n    t,z = sp.symbols('t z')\n    X = np.linspace(x0,xfinal,N+1)\n    Y = [y0]\n    h = (xfinal - x0)/N\n    \n    # Calculamos la aproximación \n    rk= succ_butcher(F,t,z,a,b,h)\n\n    for n in range(N):\n        Y.append(rk.subs({t:X[n],z:Y[n]}) )\n    return X,Y\n\ndef succ_RK4(f,x, y, h):\n    n=4\n    a = [[0,0,0,0],\n         [1/2,0,0,0],\n         [0,1/2,0,0],\n         [0,0,1,0]\n        ]\n    \n    b = [1/6,1/3,1/3,1/6]\n    \n    return succ_butcher(f,x,y,a,b,h)\n\ndef succ_RK2(f,x,y,h, alpha=1, beta=1/2):\n    '''\n    Recordemos que es óptimo en alpha*beta = 1/2\n    - Si alpha = 1, beta = 1/2: método Punto medio\n    - Si alpha 1/2, beta = 1: Heun (trapecio)\n    '''\n    n=2\n    a = [\n        [0,0],\n        [beta, 0]\n    ]\n    b = [1-alpha, alpha]\n    \n    return succ_butcher(f,x,y,a,b,h)\n\n\n\n\ndef complete_RK2(F, x0, y0, xfinal, N, alpha=1, beta=1/2):\n    n=2\n    a = [\n        [0,0],\n        [beta, 0]\n    ]\n    b = [1-alpha, alpha]\n    return complete_butcher(F, x0, y0, xfinal, N, a, b)\n    \ndef complete_RK4(F, x0, y0, xfinal, N):\n    '''\n    F función\n    x,y condiciones iniciales y(x_0) = y_0\n    xfinal = valor final hasta el que calcular\n    N número de intervalos \n    '''\n    t,z = sp.symbols('t z')\n    X = np.linspace(x0,xfinal,N+1)\n    Y = [y0]\n    h = (xfinal - x0)/N\n    \n    # Calculamos la aproximación \n    rk4= succ_RK4(F,t,z,h)\n\n    for n in range(N):\n        Y.append(rk4.subs({t:X[n],z:Y[n]}) )\n    return X,Y\n", "meta": {"hexsha": "eb2f2fe30bfa78981a3a0a6a66ef41949ffb4685", "size": 2982, "ext": "py", "lang": "Python", "max_stars_repo_path": "practica3-integracion_numerica/butcher.py", "max_stars_repo_name": "BlancaCC/metodosNumericosII", "max_stars_repo_head_hexsha": "73fd6d8bc202a34af0d95d9ac17a3b671895314d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "practica3-integracion_numerica/butcher.py", "max_issues_repo_name": "BlancaCC/metodosNumericosII", "max_issues_repo_head_hexsha": "73fd6d8bc202a34af0d95d9ac17a3b671895314d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practica3-integracion_numerica/butcher.py", "max_forks_repo_name": "BlancaCC/metodosNumericosII", "max_forks_repo_head_hexsha": "73fd6d8bc202a34af0d95d9ac17a3b671895314d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9264705882, "max_line_length": 75, "alphanum_fraction": 0.4842387659, "include": true, "reason": "import numpy,import sympy", "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361162033533, "lm_q2_score": 0.9059898114992677, "lm_q1q2_score": 0.8700774281619782}}
{"text": "\"\"\"\nAuthor : Achintya Gupta\nDate Created : 22-09-2020\n\"\"\"\n\n\"\"\"\nProblem Statement\n------------------------------------------------\nQ) Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).\n    If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.\n    For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284.\n                 the proper divisors of 284 are 1, 2, 4, 71 and 142 ______________________________ so d(284) = 220.\n    Evaluate the sum of all the amicable numbers under 10000.\n\"\"\"\nfrom utils import timing_decorator, find_divisors\nimport numpy as np\n\n\n@timing_decorator\ndef sum_amicablepair(N=10000):\n    amicable_nos = []\n    for i in range(N):\n        divisor_sum1 = sum([k for k in list(find_divisors(i)) if k!= i])\n        divisor_sum2 = sum([k for k in list(find_divisors(divisor_sum1)) if k!= divisor_sum1])\n        if i == divisor_sum2 and divisor_sum1 != divisor_sum2:\n            print(i, divisor_sum1, divisor_sum2)\n            amicable_nos.append(i)\n    print(f'Sum of the all Amicable Pair below {N} = ', sum(amicable_nos))\n\n\nsum_amicablepair()\n", "meta": {"hexsha": "ebb6900399a95e21f9472ab0768d350aed5a7d18", "size": 1238, "ext": "py", "lang": "Python", "max_stars_repo_path": "solutions/solution21.py", "max_stars_repo_name": "ag-ds-bubble/projEuler", "max_stars_repo_head_hexsha": "eac7fc0159f1324065c471ef814c88f38284934a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solutions/solution21.py", "max_issues_repo_name": "ag-ds-bubble/projEuler", "max_issues_repo_head_hexsha": "eac7fc0159f1324065c471ef814c88f38284934a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solutions/solution21.py", "max_forks_repo_name": "ag-ds-bubble/projEuler", "max_forks_repo_head_hexsha": "eac7fc0159f1324065c471ef814c88f38284934a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6875, "max_line_length": 125, "alphanum_fraction": 0.647819063, "include": true, "reason": "import numpy", "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611574955211, "lm_q2_score": 0.9059898134030163, "lm_q1q2_score": 0.8700774258788719}}
{"text": "import numpy as np\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom scipy.stats import poisson\n\n\n# For reproducibility\nnp.random.seed(1000)\n\n\nif __name__ == '__main__':\n    # Create the initial observation set\n    obs = np.array([7, 11, 9, 9, 8, 11, 9, 9, 8, 7, 11, 8, 9, 9, 11, 7, 10, 9, 10, 9, 7, 8, 9, 10, 13])\n    mu = np.mean(obs)\n\n    print('mu = {}'.format(mu))\n\n    # Show the distribution\n    sns.set(style=\"white\", palette=\"muted\", color_codes=True)\n    fig, ax = plt.subplots(figsize=(14, 7), frameon=False)\n\n    sns.distplot(obs, kde=True, color=\"b\", ax=ax)\n    ax.spines['top'].set_visible(False)\n    ax.spines['right'].set_visible(False)\n    plt.show()\n\n    # Print some probabilities\n    print('P(more than 8 trains) = {}'.format(poisson.sf(8, mu)))\n    print('P(more than 9 trains) = {}'.format(poisson.sf(9, mu)))\n    print('P(more than 10 trains) = {}'.format(poisson.sf(10, mu)))\n    print('P(more than 11 trains) = {}'.format(poisson.sf(11, mu)))\n\n    # Add new observations\n    new_obs = np.array([13, 14, 11, 10, 11, 13, 13, 9, 11, 14, 12, 11, 12,\n                        14, 8, 13, 10, 14, 12, 13, 10, 9, 14, 13, 11, 14, 13, 14])\n\n    obs = np.concatenate([obs, new_obs])\n    mu = np.mean(obs)\n\n    print('mu = {}'.format(mu))\n\n    # Repeat the analysis of the same probabilities\n    print('P(more than 8 trains) = {}'.format(poisson.sf(8, mu)))\n    print('P(more than 9 trains) = {}'.format(poisson.sf(9, mu)))\n    print('P(more than 10 trains) = {}'.format(poisson.sf(10, mu)))\n    print('P(more than 11 trains) = {}'.format(poisson.sf(11, mu)))\n\n    # Generate 2000 samples from the Poisson process\n    syn = poisson.rvs(mu, size=2000)\n\n    # Plot the complete distribution\n    fig, ax = plt.subplots(figsize=(14, 7), frameon=False)\n\n    sns.distplot(syn, kde=True, color=\"b\", ax=ax)\n    ax.spines['top'].set_visible(False)\n    ax.spines['right'].set_visible(False)\n    plt.show()\n\n", "meta": {"hexsha": "0bb892ab829667b749750a9bbe6d7d18c76c7481", "size": 1920, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch1/unsupervised_helloworld.py", "max_stars_repo_name": "susantamoh84/HandsOn-Unsupervised-Learning-with-Python", "max_stars_repo_head_hexsha": "056953d0462923a674faf0a23b27239bc9f69975", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-09-03T11:12:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T01:42:57.000Z", "max_issues_repo_path": "Chapter01/unsupervised_helloworld.py", "max_issues_repo_name": "AIRob/HandsOn-Unsupervised-Learning-with-Python", "max_issues_repo_head_hexsha": "1dbe9b3fdf5255f610e0c9c52a82935baa6a4a3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter01/unsupervised_helloworld.py", "max_forks_repo_name": "AIRob/HandsOn-Unsupervised-Learning-with-Python", "max_forks_repo_head_hexsha": "1dbe9b3fdf5255f610e0c9c52a82935baa6a4a3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2018-09-15T11:06:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T04:28:55.000Z", "avg_line_length": 31.4754098361, "max_line_length": 103, "alphanum_fraction": 0.6104166667, "include": true, "reason": "import numpy,from scipy", "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769078156284, "lm_q2_score": 0.89181104831338, "lm_q1q2_score": 0.8700302648693813}}
{"text": "import numpy as np\r\nfrom scipy.special import loggamma\r\nimport warnings\r\n\r\nclass UnivariateGaussianVB(object):\r\n\r\n    def __init__(self, prior_a=1.0, prior_b=1.0, prior_mu = 1.0, \r\n        kappa=1.0, tol=1e-5, max_iter=20):\r\n        \"\"\" use factored prior: p(mu,lambda) = p(mu|lambda)p(lambda)\r\n            Gamma prior distribition for precision:\r\n            p(lambda) = Gamma(lambda|prior_a,prior_b)\r\n            Gaussian prior distribution for mean:\r\n            p(mu|ldambda) = Normal(mu|prior_mu,(kappa*lambda)^-1)\r\n        \"\"\"\r\n        self.prior_a = prior_a\r\n        self.prior_b = prior_b\r\n        self.prior_mu = prior_mu\r\n        self.kappa = kappa\r\n\r\n        self.post_a = prior_a\r\n        self.post_b = prior_b\r\n        self.post_mu = prior_mu\r\n        self.post_mu_precision = kappa\r\n\r\n        self.tol = tol\r\n        self.max_iter = max_iter\r\n\r\n        self._check_parameters()\r\n\r\n    def _check_parameters(self):\r\n        if self.prior_a <= 0 or self.prior_b <= 0:\r\n            raise ValueError(\"prior_a and prior_be must be a positive number.\")\r\n        if self.kappa < 0:\r\n            raise ValueError(\"kappa must be a non-negative number.\")\r\n\r\n    def _check_X(self,X):\r\n        X = np.squeeze(X)\r\n        if len(X.shape) != 1:\r\n            raise ValueError(\"X should be 1-d array.\")\r\n        return X\r\n\r\n    def _compute_lower_bound(self):\r\n        return (-1/2*np.log(self.post_mu_precision) + loggamma(\r\n            self.post_a)-self.post_a*np.log(self.post_b))\r\n\r\n    def fit(self, X):\r\n        X = self._check_X(X)\r\n        N = X.size\r\n        xbar = np.mean(X)\r\n        x_square = np.sum(X**2)\r\n        x_sum = np.sum(X)\r\n        \r\n        self.lower_bound_ = -np.infty\r\n        self.converged_ = False\r\n        lower_bounds = []\r\n\r\n        for iter in range(1,self.max_iter+1):\r\n            prev_lower_bound = self.lower_bound_\r\n\r\n            # update q(mu)\r\n            E_lambda = self.post_a / self.post_b\r\n            self.post_mu = ((self.kappa * self.prior_mu +  N*xbar) \r\n                / (self.kappa + N))\r\n            self.post_mu_precision = (self.kappa + N) * E_lambda\r\n\r\n            # update q(lambda)\r\n            E_mu = self.post_mu\r\n            E_mu_square = 1 / self.post_mu_precision + self.post_mu ** 2\r\n            self.post_a = self.prior_a + (N+1)/2\r\n            self.post_b = self.prior_b\r\n            self.post_b += 1/2*(x_square + N*E_mu_square - 2*E_mu*x_sum)\r\n            self.post_b += self.kappa * (E_mu_square + self.prior_mu**2 - \r\n                2*E_mu*self.prior_mu)\r\n\r\n            self.lower_bound_ = self._compute_lower_bound()\r\n            lower_bounds.append(self.lower_bound_)\r\n\r\n            change = self.lower_bound_ - prev_lower_bound\r\n            if abs(change) < self.tol:\r\n                self.converged_ = True\r\n                break\r\n\r\n        self.best_iter_ = iter\r\n        self.lower_bounds_ = np.array(lower_bounds)\r\n        \r\n        if not self.converged_:\r\n            warnings.warn(\"Model not converged.\")\r\n", "meta": {"hexsha": "32be4f67b458c6bce971d6ab9bb6653c8e913581", "size": 2986, "ext": "py", "lang": "Python", "max_stars_repo_path": "TutorML/demo/variational_bayes/unigauss_vb.py", "max_stars_repo_name": "PanJianning/TutorML", "max_stars_repo_head_hexsha": "f87cbcf4cdfc490338a995dce78a9fc6f5d518ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-14T06:55:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-14T06:55:40.000Z", "max_issues_repo_path": "TutorML/demo/variational_bayes/unigauss_vb.py", "max_issues_repo_name": "PanJianning/TutorML", "max_issues_repo_head_hexsha": "f87cbcf4cdfc490338a995dce78a9fc6f5d518ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TutorML/demo/variational_bayes/unigauss_vb.py", "max_forks_repo_name": "PanJianning/TutorML", "max_forks_repo_head_hexsha": "f87cbcf4cdfc490338a995dce78a9fc6f5d518ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9318181818, "max_line_length": 80, "alphanum_fraction": 0.5545880777, "include": true, "reason": "import numpy,from scipy", "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.9161096147346158, "lm_q1q2_score": 0.8700012382963919}}
{"text": "import numpy as np \n\n# for linear regression the formula will be for forward\n# f = w * X\n\n# tranning data\nx = np.array([1,2,3,4],dtype=np.float32)\n# eg: f = 2 * x So,since our formula is 2X so ... \ny = np.array([2,4,6,8],dtype=np.float32)\nw = 0.0\n\n# model prediction\ndef forward(x):\n    return w*x\n\n# loss = mean\ndef loss(y,y_predicted):\n    return ((y_predicted-y)**2).mean()\n\n# gradient manual\n# mean = 1/n*(w*x-y)**2\n# dj/dw = 1/n*(2*x(w*x-y))\ndef gradient(x,y,y_predicted):\n    return np.dot(2*x,y_predicted-y).mean()\n\nprint(f\"Prediction before tranning: f(5) = {forward(5)}\")\n\n# tranning \nlearning_rate = 0.01\nno_iteration = 20\n\nfor epoch in range(no_iteration):\n    # prediction = forword pass\n    y_pred = forward(x)\n    # loss\n    ls = loss(y,y_pred)\n    # gradients\n    dw = gradient(x,y,y_pred)\n    # update weights\n    w -= learning_rate*dw\n\n    print(f\"epoch :{epoch+1} ,weights :{w} ,loss :{ls}\")\n\nprint(f\"Prediction after tranning: f(5) = {forward(5)}\")", "meta": {"hexsha": "2a8be9aa2efa44cb62c4e76b630dc21974c00c81", "size": 967, "ext": "py", "lang": "Python", "max_stars_repo_path": "basic/gradients_using_numpy.py", "max_stars_repo_name": "Sukarnascience/learningAI", "max_stars_repo_head_hexsha": "6ef1e2f65f45e4ff12cb9400e03e9c6014c9e0e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-02T18:36:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T18:36:51.000Z", "max_issues_repo_path": "basic/gradients_using_numpy.py", "max_issues_repo_name": "Sukarnascience/learningAI", "max_issues_repo_head_hexsha": "6ef1e2f65f45e4ff12cb9400e03e9c6014c9e0e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "basic/gradients_using_numpy.py", "max_forks_repo_name": "Sukarnascience/learningAI", "max_forks_repo_head_hexsha": "6ef1e2f65f45e4ff12cb9400e03e9c6014c9e0e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9772727273, "max_line_length": 57, "alphanum_fraction": 0.6339193382, "include": true, "reason": "import numpy", "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877658567787, "lm_q2_score": 0.8962513662057089, "lm_q1q2_score": 0.8699802363083052}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport imageio\nfrom _utils import *\n\n\ndef DFT2D(x, shift=True):\n    '''\n    Discrete space fourier transform\n    x: Input matrix\n    '''\n    pi2 = 2*np.pi\n    N1, N2 = x.shape\n    X = np.zeros((N1, N2), dtype=np.complex64)\n    n1, n2 = np.mgrid[0:N1, 0:N2]\n\n    for w1 in range(N1):\n        for w2 in range(N2):\n            j2pi = np.zeros((N1, N2), dtype=np.complex64)\n            j2pi.imag = pi2*(w1*n1/N1 + w2*n2/N2)\n            X[w1, w2] = np.sum(x*np.exp(-j2pi))\n    if shift:\n        X = np.roll(X, N1//2, axis=0)\n        X = np.roll(X, N2//2, axis=1)\n    return X\n\n\ndef iDFT2D(X, shift=True):\n    '''\n    Inverse discrete space fourier transform\n    X: Complex matrix\n    '''\n    pi2 = 2*np.pi\n    N1, N2 = X.shape\n    x = np.zeros((N1, N2))\n    k1, k2 = np.mgrid[0:N1, 0:N2]\n    if shift:\n        X = np.roll(X, -N1//2, axis=0)\n        X = np.roll(X, -N2//2, axis=1)\n    for n1 in range(N1):\n        for n2 in range(N2):\n            j2pi = np.zeros((N1, N2), dtype=np.complex64)\n            j2pi.imag = pi2*(n1*k1/N1 + n2*k2/N2)\n            x[n1, n2] = abs(np.sum(X*np.exp(j2pi)))\n    return 1/(N1*N2)*x\n\n\nif __name__ == \"__main__\":\n    image = imageio.imread('./sample/cameraman.png')\n    s = 4\n    image = image[::s, ::s] / 255\n    N1, N2 = image.shape\n    IMAGE = DFT2D(image)\n    xX = np.array([image, np.log10(1 + abs(IMAGE))])\n    panel(xX, [2, 1], text_color='green',\n          texts=['Input image', 'Spectrum'])\n\n\n    image_ = iDFT2D(IMAGE)\n    Xx_ = np.array([np.log10(1 + abs(IMAGE)), image_])\n    panel(Xx_, [2, 1], text_color='green',\n          texts=['Spectrum', 'Reconstructed image'])\n\n", "meta": {"hexsha": "62b4b37f71ef07b123578823e54e81fdc379ec44", "size": 1660, "ext": "py", "lang": "Python", "max_stars_repo_path": "20210724/python_FFT/random_transform.py", "max_stars_repo_name": "sgzqc/wechat", "max_stars_repo_head_hexsha": "6589915c46b8f51d28dba61c6da9702821f5b47c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-12-02T10:01:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T13:00:18.000Z", "max_issues_repo_path": "20210724/python_FFT/random_transform.py", "max_issues_repo_name": "sgzqc/wechat", "max_issues_repo_head_hexsha": "6589915c46b8f51d28dba61c6da9702821f5b47c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "20210724/python_FFT/random_transform.py", "max_forks_repo_name": "sgzqc/wechat", "max_forks_repo_head_hexsha": "6589915c46b8f51d28dba61c6da9702821f5b47c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2021-10-01T23:38:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T05:04:07.000Z", "avg_line_length": 25.9375, "max_line_length": 57, "alphanum_fraction": 0.5391566265, "include": true, "reason": "import numpy", "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793908, "lm_q2_score": 0.9046505267461572, "lm_q1q2_score": 0.8698520648776787}}
{"text": "import numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nx0 = 0\r\ny0 = 2\r\nxf = 1\r\nn = 11\r\ndeltax = (xf-x0)/(n-1)\r\nx = np.linspace(x0,xf,n)\r\ndef f(x,y):\r\n\treturn y-x\r\n\r\ny = np.zeros([n])\r\ny[0] = y0\r\npy = np.zeros([n])\r\npy[0] = None\r\n\r\nfor i in range(1,n):\r\n\tpy[i] = deltax*f(x[i-1],y[i-1]) + y[i-1]\r\n\ty[i] = deltax/2*( f(x[i],py[i]) + f(x[i-1],y[i-1]) ) + y[i-1]\r\nprint(\"x_n\\t   py_n\\t           y_n\")\r\nfor i in range(n):\r\n\tprint (x[i],\"\\t\",format(py[i],'6f'),\"\\t\",format(y[i],'6f'))\r\n\r\nplt.plot(x,y,'o')\r\nplt.xlabel(\"Value of x\")\r\nplt.ylabel(\"Value of y\")\r\nplt.title(\"Approximation Solution with Modified Euler's Method\")\r\nplt.show()\r\n\r\n#table 19-1\r\n", "meta": {"hexsha": "3d1749d6aaa39fbb66dbb3961738a5335643746c", "size": 652, "ext": "py", "lang": "Python", "max_stars_repo_path": "euler_method_modified.py", "max_stars_repo_name": "EloneSampaio/Numerical-Methods-First_Order_DE", "max_stars_repo_head_hexsha": "454acf91317a7789dea365490af00ed879583c19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-12T18:49:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T06:38:41.000Z", "max_issues_repo_path": "euler_method_modified.py", "max_issues_repo_name": "sultanki/Numerical-Methods-First_Order_DE", "max_issues_repo_head_hexsha": "454acf91317a7789dea365490af00ed879583c19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "euler_method_modified.py", "max_forks_repo_name": "sultanki/Numerical-Methods-First_Order_DE", "max_forks_repo_head_hexsha": "454acf91317a7789dea365490af00ed879583c19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-07-27T08:48:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T07:22:05.000Z", "avg_line_length": 20.375, "max_line_length": 65, "alphanum_fraction": 0.5490797546, "include": true, "reason": "import numpy", "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102589923635, "lm_q2_score": 0.8991213847035618, "lm_q1q2_score": 0.8698192516416453}}
{"text": "import math\n# import numpy as np\n\ndef primes_under(N):\n    if N == 1:\n        return []\n    if N == 2:\n        return [2]\n    if N == 3:\n        return [2,3]\n\n    sqrtN = int(round(math.sqrt(N)))\n    primes = [2,3]\n    for j in range(3, N, 2):\n        founddivisor = False\n        for p in primes:\n            if p > sqrtN:\n                break\n            elif j % p == 0:\n                founddivisor = True\n                break\n        if not founddivisor:\n            primes.append(j)\n\n    return primes\n\ndef is_prime(N):\n    if N < 0 or type(N) != int:\n        return False\n    if N == 0 or N == 1:\n        return False\n    if N == 2 or N == 3:\n        return True\n\n    sqrtN = int(round(math.sqrt(N)))+1\n    for j in range(2,sqrtN):\n        # print(j)\n        if N % j == 0:\n            return False\n    return True\n\ndef test_primes_under():\n    primes_10 = primes_under(10)\n    primes_100 = primes_under(100)\n    primes_1000 = primes_under(1000)\n    # print(primes_10)\n    u = [is_prime(x) for x in primes_10]\n    print(u)\n    print([(x, is_prime(x)) for x in range(100)])\n    is_prime(10)\n    # print(primes_100)\n    # print(primes_1000)\n\nif __name__ == \"__main__\":\n    test_primes_under()\n", "meta": {"hexsha": "9e238a923c31b9824b2ac4fa60314f5cb0f9e640", "size": 1200, "ext": "py", "lang": "Python", "max_stars_repo_path": "find_primes.py", "max_stars_repo_name": "odellus/year_of_code", "max_stars_repo_head_hexsha": "bfa2b30893bcc12f46e73ac34c63b5b05b27af5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-01-03T02:24:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-03T02:24:34.000Z", "max_issues_repo_path": "find_primes.py", "max_issues_repo_name": "odellus/year_of_code", "max_issues_repo_head_hexsha": "bfa2b30893bcc12f46e73ac34c63b5b05b27af5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "find_primes.py", "max_forks_repo_name": "odellus/year_of_code", "max_forks_repo_head_hexsha": "bfa2b30893bcc12f46e73ac34c63b5b05b27af5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4285714286, "max_line_length": 49, "alphanum_fraction": 0.5175, "include": true, "reason": "import numpy", "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102580527664, "lm_q2_score": 0.899121375242593, "lm_q1q2_score": 0.869819241644195}}
{"text": "'''\nLorenz system.\n\nA simplified mathematical model for atmospheric convection. The model is a system of three ordinary differential\nequations now known as the Lorenz equations:\n\ndx/dt = sigma * (y - x)\ndy/dt = x * (rho - z) - y\ndz/dt = xy - beta * z\n\nThe equations relate the properties of a two-dimensional fluid layer uniformly warmed from below and cooled from above.\nIn particular, the equations describe the rate of change of three quantities with respect to time: x is proportional to\nthe rate of convection, y to the horizontal temperature variation, and z to the vertical temperature variation. The\nconstants sigma, rho, and beta are system parameters proportional to the Prandtl number, Rayleigh number, and certain\nphysical dimensions of the layer itself.\n\nFrom a technical standpoint, the Lorenz system is nonlinear, non-periodic, three-dimensional and deterministic.\n\nSRC: https://en.wikipedia.org/wiki/Lorenz_system\n\n\n------------------------------------------------------------------------------------------------------------------------\n\nA chaotic map is a map (= evolution function) that exhibits some sort of chaotic behavior.\n\nList of chaotic maps (https://en.wikipedia.org/wiki/List_of_chaotic_maps)\n    Map                     Time dom    Space dom  Space dim  Params\n    ----------------------------------------------------------------\n    Logistic map            discrete    real               1       1\n    Lotka-Volterra system   continuous  real               3       4\n    Lorenz system           continuous  real               3       3\n\n\n------------------------------------------------------------------------------------------------------------------------\n\nhttps://physics.nyu.edu/pine/pymanual/html/chap9/chap9_scipy.html\nhttp://sam-dolan.staff.shef.ac.uk/mas212/notebooks/ODE_Example.html\n'''\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import odeint\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\n# Declarations and definitions:\nrho = 28.0\nsigma = 10.0\nbeta = 8.0 / 3.0\n\ndef f(state, t):\n    x, y, z = state  # unpack the state vector\n    return (sigma * (y - x), x * (rho - z) - y, x * y - beta * z)  # derivatives\n\nstate0 = [1.0, 1.0, 1.0]  # the initial state\n# t = np.arange(0.0, 40.0, 0.01)\n\n# Loopless:\n# t = np.arange(0.0, 1.0, 0.1)\n# states = odeint(f, state0, t)\n# print(states)\n\n# Loop (compatible with a PRAM simulation):\n# states = []\n# s = state0\n# t0 = 0.0\n# for t1 in t[1:]:\n#     s = odeint(f, s, [t0,t1])[0]\n#     t0 = t1\n#     states.append(s)\n#\n# print(states[:10])\n\nt0 = 0.0\nt1 = 1.0\ndt = 0.1\n\nr = ode(f).set_integrator('zvode', method='bdf')\n# r = ode(f).set_integrator('lsoda')\nr.set_initial_value(state0, t0)\nwhile r.successful() and r.t < t1:\n    r.integrate(r.t + dt)\n    print(f'{round(r.t,1)}: {r.y}')\n\n# Visualize:\n# fig = plt.figure()\n# ax = fig.gca(projection='3d')\n# ax.plot(states[:,0], states[:,1], states[:,2])\n# plt.show()\n", "meta": {"hexsha": "dc9a462459f0d32577e4d9cc33d411de0b2c69e6", "size": 2918, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sim/11-ode/sim-01-lorentz.py", "max_stars_repo_name": "momacs/pram", "max_stars_repo_head_hexsha": "d2de43ea447d13a65d814f781ec86889754f76fe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-01-18T19:11:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T08:39:36.000Z", "max_issues_repo_path": "src/sim/11-ode/sim-01-lorentz.py", "max_issues_repo_name": "momacs/pram", "max_issues_repo_head_hexsha": "d2de43ea447d13a65d814f781ec86889754f76fe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-02-19T15:10:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-26T04:26:24.000Z", "max_forks_repo_path": "src/sim/11-ode/sim-01-lorentz.py", "max_forks_repo_name": "momacs/pram", "max_forks_repo_head_hexsha": "d2de43ea447d13a65d814f781ec86889754f76fe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-02-19T15:11:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T11:51:04.000Z", "avg_line_length": 32.0659340659, "max_line_length": 120, "alphanum_fraction": 0.5986977382, "include": true, "reason": "import numpy,from scipy", "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102524151827, "lm_q2_score": 0.8991213759183765, "lm_q1q2_score": 0.869819237229083}}
{"text": "import numpy as np \nimport matplotlib.pyplot as plt\n\ndef ecdf(data):\n    \"\"\"Compute ECDF for a one-dimensional array of measurements.\"\"\"\n    # Number of data points: n\n    n = len(data)\n\n    # x-data for the ECDF: x\n    x = np.sort(data)\n\n    # y-data for the ECDF: y\n    y = np.arange(1, n+1) / n\n\n    return x, y\n\ndef main():    \n    versi_color_petal = [4.7, 4.5, 4.9, 4.0,  4.6, 4.5, 4.7, 3.3, 4.6, 3.9, 3.5, 4.2, 4.0,  4.7, 3.6, 4.4, 4.5, 4.1,\n     4.5, 3.9, 4.8, 4.0,  4.9, 4.7, 4.3, 4.4, 4.8, 5.0,  4.5, 3.5, 3.8, 3.7, 3.9, 5.1, 4.5, 4.5,\n     4.7, 4.4, 4.1, 4.0,  4.4, 4.6, 4.0,  3.3, 4.2, 4.2, 4.2, 4.3, 3.0,  4.1]\n    \n    x_vers, y_vers = ecdf(versi_color_petal)\n    plt.plot(x_vers,y_vers, marker='.', linestyle = 'none')\n    # can multiple ecdf on the same plot and compare\n\n    plt.xlabel('petal length')\n    plt.ylabel('ECDF')\n\n    plt.show()\n\n\nmain()", "meta": {"hexsha": "7ec744e191c4c38fa8f5c214eb948888b85538aa", "size": 866, "ext": "py", "lang": "Python", "max_stars_repo_path": "Codes/EDA/ECDF.py", "max_stars_repo_name": "shohan4556/machine-learning-course-notes", "max_stars_repo_head_hexsha": "981f3d6e9861cbee0f4dec45b1d2e6a214d2a051", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-10-12T17:08:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-26T02:54:01.000Z", "max_issues_repo_path": "Codes/EDA/ECDF.py", "max_issues_repo_name": "shohan4556/machine-learning-course-notes", "max_issues_repo_head_hexsha": "981f3d6e9861cbee0f4dec45b1d2e6a214d2a051", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Codes/EDA/ECDF.py", "max_forks_repo_name": "shohan4556/machine-learning-course-notes", "max_forks_repo_head_hexsha": "981f3d6e9861cbee0f4dec45b1d2e6a214d2a051", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-10-30T03:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-11T20:53:47.000Z", "avg_line_length": 27.0625, "max_line_length": 116, "alphanum_fraction": 0.5415704388, "include": true, "reason": "import numpy", "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750373915658, "lm_q2_score": 0.9124361670249624, "lm_q1q2_score": 0.8698026212381381}}
{"text": "# -*- coding: utf-8 -*-\r\n\r\n\" This pyfile is used to give a numerical solution of ordinary differential equation \"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\"\"\" Input: \r\nInterval: [a,b]\r\nStep: h\r\nDifferential: f(x,y)\r\nInitial point: y(a) = y0\r\n\"\"\"\r\n\r\ndef EulerMethod(a,b,h,f,y0):\r\n    if b>a:\r\n        step = int((b-a)/h+1)\r\n        x = np.linspace(a,b,step)\r\n        y = np.zeros_like(x)\r\n        y[0]=y0\r\n        for index in range(1,step):\r\n            y[index] = y[index-1] + h*f(x[index-1],y[index-1])\r\n        return y\r\n    else:\r\n        return \"Error\"\r\n    \r\ndef I_EulerMethod(a,b,h,f,y0):\r\n    if b>a:\r\n        step = int((b-a)/h+1)\r\n        x = np.linspace(a,b,step)\r\n        y = np.zeros_like(x)\r\n        ye = np.zeros_like(x)\r\n        y[0] = y0\r\n        ye[0] = y0\r\n        for index in range(1,step):\r\n            ye[index] = ye[index-1] + h*f(x[index-1],ye[index-1])\r\n            y[index] = y[index-1] + 0.5*h*(f(x[index-1],y[index-1])+f(x[index],ye[index]))\r\n        return y\r\n    else:\r\n        return \"Error\"\r\n    \r\ndef Draw(a,b,h,f,y0,ft):\r\n    step = int((b-a)/h+1)\r\n    x = np.linspace(a,b,step)\r\n    fig, ax = plt.subplots(dpi=120)\r\n    ye = EulerMethod(a,b,h,f,y0)\r\n    yie = I_EulerMethod(a,b,h,f,y0)\r\n    yt = ft(x)\r\n    ax.plot(x,ye,marker='o',color='r',alpha=0.5,label='Euler Method')\r\n    ax.plot(x,yie,marker='x',color='b',alpha=0.5,label='Improved Euler Method')\r\n    ax.plot(x,yt,marker='v',color='g',alpha=0.5,label='Explicit Function')\r\n    ax.legend()\r\n    fig.show()\r\n    return 0\r\n    \r\n\"\"\"\r\na = 0\r\nb = 1\r\nh = 0.1\r\nf = lambda x,y: y-2*x/y\r\ny0 = 1\r\nft = lambda x: np.sqrt(1+2*x)\r\n\r\nEulerMethod(a,b,h,f,y0)\r\nI_EulerMethod(a,b,h,f,y0)\r\nDraw(a,b,h,f,y0,ft)\r\n\"\"\"", "meta": {"hexsha": "ba6a53d797b4edd3c1e02043a695173e1d91bf82", "size": 1707, "ext": "py", "lang": "Python", "max_stars_repo_path": "differential.py", "max_stars_repo_name": "DickLiTQ/NumAnalysis", "max_stars_repo_head_hexsha": "6f0adb1717842dbde822d45d5a5e3a89b489061e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-01-23T05:19:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T02:17:36.000Z", "max_issues_repo_path": "differential.py", "max_issues_repo_name": "DickLiTQ/NumAnalysis", "max_issues_repo_head_hexsha": "6f0adb1717842dbde822d45d5a5e3a89b489061e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "differential.py", "max_forks_repo_name": "DickLiTQ/NumAnalysis", "max_forks_repo_head_hexsha": "6f0adb1717842dbde822d45d5a5e3a89b489061e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-01-20T06:45:56.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-28T02:11:41.000Z", "avg_line_length": 25.4776119403, "max_line_length": 91, "alphanum_fraction": 0.524897481, "include": true, "reason": "import numpy", "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750360641185, "lm_q2_score": 0.9124361557147439, "lm_q1q2_score": 0.869802609245178}}
{"text": "﻿from scipy.fftpack import fft\nimport numpy as np\nfrom fractions import gcd\n\n\"\"\"\nA3-Part-1: Minimize energy spread in DFT of sinusoids\nGiven a signal consisting of two sinusoids, write a function that selects the first M samples from \nthe signal and returns the positive half of the DFT magnitude spectrum (in dB), such that it has \nonly two non-zero values. \n\nM is to be calculated as the smallest positive integer for which the positive half of the DFT magnitude \nspectrum has only two non-zero values. To get the positive half of the spectrum, first compute the \nM point DFT of the input signal (for this you can use the fft function of scipy.fftpack, which is \nalready imported in this script). Consider only the first (M/2)+1 samples of the DFT and compute the\nmagnitude spectrum of the positive half (in dB) as mX = 20*log10(abs(X[:M/2+1])), where X is the DFT \nof the input.\n\nThe input arguments to this function are the input signal x (of length W >= M) consisting of two \nsinusoids of frequency f1 and f2, the sampling frequency fs and the value of frequencies f1 and f2. \nThe function should return the positive half of the magnitude spectrum mX. For this question, \nyou can assume the input frequencies f1 and f2 to be positive integers and factors of fs, and \nthat M is even. \n\nDue to the precision of the FFT computation, the zero values of the DFT are not zero but very small\nvalues < 1e-12 (or -240 dB) in magnitude. For practical purposes, all values with absolute value less \nthan 1e-6 (or -120 dB) can be considered to be zero. \n\nHINT: The DFT magnitude spectrum of a sinusoid has only one non-zero value (in the positive half of \nthe DFT spectrum) when its frequency coincides with one of the DFT bin frequencies. This happens when \nthe DFT size (M in this question) contains exactly an integer number of periods of the sinusoid. \nSince the signal in this question consists of two sinusoids, this condition should hold true for each \nof the sinusoids, so that the DFT magnitude spectrum has only two non-zero values, one per sinusoid. \n\nM can be computed as the Least Common Multiple (LCM) of the sinusoid periods (in samples). The LCM of\ntwo numbers x, y can be computed as: x*y/GCD(x,y), where GCD denotes the greatest common divisor. In \nthis script (see above) we have already imported fractions.gcd() function that computes the GCD. \n\nTest case 1: For an input signal x sampled at fs = 10000 Hz that consists of sinusoids of frequency \nf1 = 80 Hz and f2 = 200 Hz, you need to select M = 250 samples of the signal to meet the required \ncondition. In this case, output mX is 126 samples in length and has non-zero values at bin indices 2 \nand 5 (corresponding to the frequency values of 80 and 200 Hz, respectively). You can create a test \nsignal x by generating and adding two sinusoids of the given frequencies.\n\nTest case 2: For an input signal x sampled at fs = 48000 Hz that consists of sinusoids of frequency \nf1 = 300 Hz and f2 = 800 Hz, you need to select M = 480 samples of the signal to meet the required \ncondition. In this case, output mX is 241 samples in length and has non-zero values at bin indices 3 \nand 8 (corresponding to the frequency values of 300 and 800 Hz, respectively). You can create a test \nsignal x by generating and adding two sinusoids of the given frequencies.\n\"\"\"\n\ndef minimizeEnergySpreadDFT(x, fs, f1, f2):\n    \"\"\"\n    Inputs:\n        x (numpy array) = input signal \n        fs (float) = sampling frequency in Hz\n        f1 (float) = frequency of the first sinusoid component in Hz\n        f2 (float) = frequency of the second sinusoid component in Hz\n    Output:\n        The function should return \n        mX (numpy array) = The positive half of the DFT spectrum (in dB) of the M sample segment of x. \n                           mX is (M/2)+1 samples long (M is to be computed)\n    \"\"\"\n    ## Your code here\n    M = fs // gcd(f1,f2)\n    M = int(M)\n    X = fft(x[:M])\n    mX = 20 * np.log10(abs(X[:M//2+1]))\n    return mX\n\n", "meta": {"hexsha": "48dc3456ac1ea2897488ab20659855bce108a002", "size": 3982, "ext": "py", "lang": "Python", "max_stars_repo_path": "A3/A3Part1.py", "max_stars_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_stars_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A3/A3Part1.py", "max_issues_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_issues_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A3/A3Part1.py", "max_forks_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_forks_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.8857142857, "max_line_length": 104, "alphanum_fraction": 0.7363134103, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778061099871, "lm_q2_score": 0.9086179018818865, "lm_q1q2_score": 0.8697997517057519}}
{"text": "import numpy as np\n\ndef pca(X):\n    \"\"\"\n    Run PCA on dataset X\n    U,S,V = pca(X) computes eigenvectors of the covariance matrix of X\n    Return eigenvectors U and the eigenvalues in S\n    \"\"\"\n    #########################################################\n    #         YOUR CODE HERE                                #\n    #########################################################\n    \n    # compute the covariance of X and then use the\n    # svd function to compute the eigenvectors and\n    # eigenvalues of the covariance matrix\n\n    # When computing the covariance remember to divide by\n    # the number of rows in X\n    m = X.shape[0]\n    sigma = X.T @ X / m\n    U, S, V = np.linalg.svd(sigma, full_matrices=False)\n    ########################################################\n    #           END YOUR CODE                              #\n    ########################################################\n    return U,S,V\n\ndef feature_normalize(X):\n    Xnorm = (X - X.mean(axis=0))/X.std(axis=0)\n    return Xnorm, X.mean(axis=0), X.std(axis=0)\n\ndef project_data(X,U,K):\n    \"\"\"\n    project_data computes the reduced data representation when projecting only \n    on to the top k eigenvectors\n    Z = project_data(X, U, K) computes the projection of \n    the normalized inputs X into the reduced dimensional space spanned by\n    the first K columns of U. It returns the projected examples in Z.\n    \"\"\"\n    #########################################################\n    #         YOUR CODE HERE                                #\n    #########################################################\n    topk = U[:, :K]\n    Z = X @ topk\n    ########################################################\n    #           END YOUR CODE                              #\n    ########################################################\n    return Z\n\n\ndef recover_data(Z,U,K):\n    \"\"\"\n    recover_data recovers an approximation of the original data when using the \n    projected principal axis U\n    X_rec = recover_data(Z, U, K) recovers an approximation the \n    original data Z that has been reduced to K dimensions. It returns the\n    approximate reconstruction in X_rec.\n    \"\"\"\n\n    #########################################################\n    #         YOUR CODE HERE                                #\n    #########################################################\n    topk = U[:, :K]\n    X_rec = Z @ topk.T\n    ########################################################\n    #           END YOUR CODE                              #\n    ########################################################\n    return X_rec", "meta": {"hexsha": "90ccafd4d5a8a419badb5274ca5ed8e5e772f184", "size": 2580, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW6/submit/pca/utils_pca.py", "max_stars_repo_name": "JavisDaDa/COMP540ML", "max_stars_repo_head_hexsha": "9c50a7d0fcca02050e0269bf4337fe6caa3c65db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW6/submit/pca/utils_pca.py", "max_issues_repo_name": "JavisDaDa/COMP540ML", "max_issues_repo_head_hexsha": "9c50a7d0fcca02050e0269bf4337fe6caa3c65db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW6/submit/pca/utils_pca.py", "max_forks_repo_name": "JavisDaDa/COMP540ML", "max_forks_repo_head_hexsha": "9c50a7d0fcca02050e0269bf4337fe6caa3c65db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5074626866, "max_line_length": 79, "alphanum_fraction": 0.4054263566, "include": true, "reason": "import numpy", "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777975782055, "lm_q2_score": 0.9086178963141964, "lm_q1q2_score": 0.8697997386237962}}
{"text": "''' mbinary\n#########################################################################\n# File : iteration.py\n# Author: mbinary\n# Mail: zhuheqin1@gmail.com\n# Blog: https://mbinary.xyz\n# Github: https://github.com/mbinary\n# Created Time: 2018-10-02  21:14\n# Description:\n#########################################################################\n'''\n\nimport sympy\nimport numpy as np\nfrom math import sqrt\n\n\ndef newton(y: sympy.core, x0: float, epsilon: float = 0.00001, maxtime: int = 50) ->(list, list):\n    '''\n        newton 's iteration method for finding a zeropoint of a func\n        y is the func, x0 is the init x val: int float epsilon is the accurrency\n    '''\n    if epsilon < 0:\n        epsilon = -epsilon\n    ct = 0\n    t = y.free_symbols\n    varsymbol = 'x' if len(t) == 0 else t.pop()\n    x0 = float(x0)\n    y_diff = y.diff()\n    li = [x0]\n    vals = []\n    while 1:\n        val = y.subs(varsymbol, x0)\n        vals.append(val)\n        x = x0 - val/y_diff.subs(varsymbol, x0)\n        li.append(x)\n        ct += 1\n        if ct > maxtime:\n            print(\"after iteration for {} times, I still havn't reach the accurrency.\\\n                    Maybe this function havsn't zeropoint\\n\".format(ct))\n            return li, val\n        if abs(x-x0) < epsilon:\n            return li, vals\n        x0 = x\n\n\ndef secant(y: sympy.core, x0: float, x1: float, epsilon: float = 0.00001, maxtime: int = 50) ->(list, list):\n    '''\n        弦截法, 使用newton 差商计算,每次只需计算一次f(x)\n        secant method for finding a zeropoint of a func\n        y is the func , x0 is the init x val,     epsilon is the accurrency\n    '''\n    if epsilon < 0:\n        epsilon = -epsilon\n    ct = 0\n    x0, x1 = float(x0), float(x1)\n    li = [x0, x1]\n    t = y.free_symbols\n    varsymbol = 'x' if len(t) == 0 else t.pop()\n    last = y.subs(varsymbol, x0)\n    vals = [last]\n    while 1:\n        cur = y.subs(varsymbol, x1)\n        vals.append(cur)\n        x = x1-cur*(x1-x0)/(cur-last)\n        x0, x1 = x1, x\n        last = cur\n        li.append(x)\n        ct += 1\n        if ct > maxtime:\n            print(\"after iteration for {} times, I still havn't reach the accurrency.\\\n                    Maybe this function havsn't zeropoint\\n\".format(ct))\n            return li, vals\n        if abs(x0-x1) < epsilon:\n            return li, vals\n        x0 = x\n\n\ndef solveNonlinearEquations(funcs: [sympy.core], init_dic: dict, epsilon: float = 0.001, maxtime: int = 50)->dict:\n    '''solve  nonlinear equations:'''\n    li = list(init_dic.keys())\n    delta = {i: 0 for i in li}\n    ct = 0\n    while 1:\n        ys = np.array([f.subs(init_dic) for f in funcs], dtype='float')\n        mat = np.matrix([[i.diff(x).subs(init_dic) for x in li]\n                         for i in funcs], dtype='float')\n        delt = np.linalg.solve(mat, -ys)\n        for i, j in enumerate(delt):\n            init_dic[li[i]] += j\n            delta[li[i]] = j\n        if ct > maxtime:\n            print(\"after iteration for {} times, I still havn't reach the accurrency.\\\n                    Maybe this function havsn't zeropoint\\n\".format(ct))\n            return init_dic\n        if sqrt(sum(i**2 for i in delta.values())) < epsilon:\n            return init_dic\n\n\nif __name__ == '__main__':\n    x, y, z = sympy.symbols('x y z')\n\n    res, res2 = newton(x**5-9, 2, 0.01)\n    print(res, res2)\n\n    res, res2 = secant(x**3-3*x-2, 1, 3, 1e-3)\n    print(res, res2)\n\n    funcs = [x**2+y**2-1, x**3-y]\n    init = {x: 0.8, y: 0.6}\n    res_dic = solveNonlinearEquations(funcs, init, 0.001)\n    print(res_dic)\n", "meta": {"hexsha": "bb25474f64918b337de3e80249841087e1215b6c", "size": 3536, "ext": "py", "lang": "Python", "max_stars_repo_path": "math/numericalAnalysis/iteration.py", "max_stars_repo_name": "heqin-zhu/algorithm", "max_stars_repo_head_hexsha": "61b33a38c49ecdc9f443433ef500aa3f5e8f68e4", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-17T11:38:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T17:38:00.000Z", "max_issues_repo_path": "math/numericalAnalysis/iteration.py", "max_issues_repo_name": "heqin-zhu/algorithm", "max_issues_repo_head_hexsha": "61b33a38c49ecdc9f443433ef500aa3f5e8f68e4", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/numericalAnalysis/iteration.py", "max_forks_repo_name": "heqin-zhu/algorithm", "max_forks_repo_head_hexsha": "61b33a38c49ecdc9f443433ef500aa3f5e8f68e4", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-16T16:23:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T16:23:53.000Z", "avg_line_length": 31.2920353982, "max_line_length": 114, "alphanum_fraction": 0.5274321267, "include": true, "reason": "import numpy,import sympy", "num_tokens": 1076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723353, "lm_q2_score": 0.9086178901278736, "lm_q1q2_score": 0.8697997382390021}}
{"text": "\"\"\"\nMap\n\n- Com map, fazemos o mapeamento de valores para a função.\n\n\"\"\"\n\nimport numpy as np\n\narea = lambda r: np.pi * (r ** 2)\n\ndef c_area(r):\n    return np.pi * (r ** 2)\n\n\nprint(area(2))\nprint(area(5))\n\nraios = list(range(1, 21))\nprint(raios)\n\n# Forma utilizando map recebe(função, interavel)\n\nareas = map(c_area, raios)\nprint(areas)\nprint(type(areas))\nprint(list(areas))\n\n# Forma 3 map com lambda\nprint(list(map(lambda r: np.pi * (r ** 2), raios)))\n\n# Obs.: Após a primeira utilização (loop, conversão) ele zera.\n\n", "meta": {"hexsha": "61195fd2abe604be64ecbe6c8f20ac88c6dce41b", "size": 516, "ext": "py", "lang": "Python", "max_stars_repo_path": "aula_secao10_map.py", "max_stars_repo_name": "Romuloro/Curso_udemy_geek_academy_python", "max_stars_repo_head_hexsha": "10d514874d913b7c2e3e4c30bd8a610973ffff3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aula_secao10_map.py", "max_issues_repo_name": "Romuloro/Curso_udemy_geek_academy_python", "max_issues_repo_head_hexsha": "10d514874d913b7c2e3e4c30bd8a610973ffff3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aula_secao10_map.py", "max_forks_repo_name": "Romuloro/Curso_udemy_geek_academy_python", "max_forks_repo_head_hexsha": "10d514874d913b7c2e3e4c30bd8a610973ffff3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.1764705882, "max_line_length": 62, "alphanum_fraction": 0.6550387597, "include": true, "reason": "import numpy", "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.9196425234694067, "lm_q1q2_score": 0.8697990696158581}}
{"text": "\"\"\"\nLogistic Function: f(x) = 1 / (1+e ^(-x))\n\nCreated by: MJ\n\n\"\"\"\n\n\"\"\"\nRef Stack Overflow:\n\nThe sigmoid function is a special case of the Logistic function when L=1, k=1, x0=0.\n\n\n- L is the maximum value the function can take. e−k(x−x0) is always greater or equal than 0, so the maximum point is achieved when it it 0, and is at L/1.\n\nx0 controls where on the x axis the growth should the, because if you put x0 in the function, x0−x0 cancel out and e0=1, so you end up with f(x0)=L/2, the midpoint of the growth.\n\nthe parameter k controls how steep the change from the minimum to the maximum value is.\n\"\"\"\n\nimport math\nimport numpy as np\n\ndef sigmoid(x,library=\"math\"):\n\tif library==\"math\":\n\t\treturn 1/(1+math.exp(-x))\n\telse:\n\t\treturn 1/(1+np.exp(-x))\n\ndef sigmoid_derivative(x):\n\treturn x*(1-x)\n\nif __name__ == \"__main__\":\n\tprint(sigmoid(0.75))\n\tprint(sigmoid_derivative(0.75))\n", "meta": {"hexsha": "9c53c031579b6fe55012fa9b77c73318681c5b65", "size": 881, "ext": "py", "lang": "Python", "max_stars_repo_path": "activation-functions/python-implementations/sigmoid.py", "max_stars_repo_name": "manojkumar-github/Implementations-Of-MachineLearning-and-Deep-Learning", "max_stars_repo_head_hexsha": "9e80a56c84073bbf3b5c9d6e8891176e02f0d973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "activation-functions/python-implementations/sigmoid.py", "max_issues_repo_name": "manojkumar-github/Implementations-Of-MachineLearning-and-Deep-Learning", "max_issues_repo_head_hexsha": "9e80a56c84073bbf3b5c9d6e8891176e02f0d973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "activation-functions/python-implementations/sigmoid.py", "max_forks_repo_name": "manojkumar-github/Implementations-Of-MachineLearning-and-Deep-Learning", "max_forks_repo_head_hexsha": "9e80a56c84073bbf3b5c9d6e8891176e02f0d973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4722222222, "max_line_length": 178, "alphanum_fraction": 0.6969353008, "include": true, "reason": "import numpy", "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.919642528975397, "lm_q1q2_score": 0.8697990677987245}}
{"text": "from sympy import *\r\n\r\nimport numpy as np\r\n\r\nx = symbols('x')\r\n\r\n\"\"\"Root approximation using Newton-Raphson Method\"\"\"\r\n\r\n\r\ndef newton(function, initial_guess, max_iter):\r\n    xn = initial_guess\r\n\r\n    for n in range(0, max_iter):\r\n\r\n        fxn = function.subs(x, xn)\r\n\r\n        if abs(fxn) < 10 ** -4:  # find the |f(x)| upto appropriate decimal digits\r\n\r\n            print('Found solution after', n, 'iterations.')\r\n            try:\r\n                return xn.evalf(4)\r\n            except AttributeError:\r\n                return xn\r\n\r\n        Dfxn = diff(function, x).subs(x, xn)\r\n\r\n        if Dfxn == 0:\r\n            print('Zero derivative. No solution found.')\r\n\r\n            return None\r\n\r\n        xn = xn - fxn / Dfxn\r\n\r\n    print('Exceeded maximum iterations. No solution found.')\r\n\r\n    return None\r\n\r\n\r\n\"\"\"Root approximation using bisection method\"\"\"\r\n\r\n\r\ndef bisection(f, a, b, max_iter):\r\n    if f.subs(x, a) * f.subs(x, b) >= 0:\r\n        print(\"Bisection method fails.\")\r\n        return None\r\n\r\n    a_n = a\r\n    b_n = b\r\n\r\n    for n in range(1, max_iter + 1):\r\n        m_n = (a_n + b_n) / 2\r\n        f_m_n = f.subs(x, m_n)\r\n\r\n        if f.subs(x, a_n) * f_m_n < 0:\r\n            a_n = a_n\r\n            b_n = m_n\r\n\r\n        elif f.subs(x, b_n) * f_m_n < 0:\r\n            a_n = m_n\r\n            b_n = b_n\r\n\r\n        elif f_m_n == 0:\r\n            print(\"Found exact solution.\")\r\n            return m_n\r\n\r\n        else:\r\n            print(\"Bisection method fails.\")\r\n\r\n            return None\r\n    print(\"Found approximate solution after\", max_iter, \"iteration\")\r\n    return ((a_n + b_n) / 2)\r\n\r\n        '''Root approximation using secant Method'''\r\n\r\ndef secant(f,a,b,N):\r\n    if f(a)*f(b) >= 0:\r\n        print(\"Secant method fails.\")\r\n        return None\r\n    a_n = a\r\n    b_n = b\r\n    for n in range(1,N+1):\r\n        m_n = a_n - f(a_n)*(b_n - a_n)/(f(b_n) - f(a_n))\r\n        f_m_n = f(m_n)\r\n        if f(a_n)*f_m_n < 0:\r\n            a_n = a_n\r\n            b_n = m_n\r\n        elif f(b_n)*f_m_n < 0:\r\n            a_n = m_n\r\n            b_n = b_n\r\n        elif f_m_n == 0:\r\n            print(\"Found exact solution.\")\r\n            return m_n\r\n        else:\r\n            print(\"Secant method fails.\")\r\n            return None\r\n    return a_n - f(a_n)*(b_n - a_n)/(f(b_n) - f(a_n))\r\n", "meta": {"hexsha": "8e4d60831169f07177af72e6aac944638b66ec43", "size": 2286, "ext": "py", "lang": "Python", "max_stars_repo_path": "IDC101/numerical_root_approx.py", "max_stars_repo_name": "dev-aditya/Mathematical-Python", "max_stars_repo_head_hexsha": "9adf4e14a0330f5fba10d74ba6105300c0dc522b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-19T12:03:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-19T12:03:00.000Z", "max_issues_repo_path": "IDC101/numerical_root_approx.py", "max_issues_repo_name": "dev-aditya/Mathematical-Python", "max_issues_repo_head_hexsha": "9adf4e14a0330f5fba10d74ba6105300c0dc522b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IDC101/numerical_root_approx.py", "max_forks_repo_name": "dev-aditya/Mathematical-Python", "max_forks_repo_head_hexsha": "9adf4e14a0330f5fba10d74ba6105300c0dc522b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5670103093, "max_line_length": 83, "alphanum_fraction": 0.4833770779, "include": true, "reason": "import numpy,from sympy", "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446471538802, "lm_q2_score": 0.8933094081846421, "lm_q1q2_score": 0.8697659235311774}}
{"text": "import numpy as np \nimport matplotlib.pyplot as plt \nimport pandas as pd\n\n# data \nxx = [0,1,2,3,4,5,6,7,8,9]\nyy = [1,3,2,5,7,8,8,9,10,12]\n\n# mean / average \nxx_mean = np.mean(xx)\nyy_mean = np.mean(yy)\n\n# total number of value \nn = len(xx)\n\nup = 0\ndown = 0\n\nfor i in range(n):\n  up += (xx[i] - xx_mean) * (yy[i] - yy_mean)\n  down += (xx[i] - xx_mean) **2\n\nm = up/down  \nc = yy_mean - (m * xx_mean)\n\nprint(m, c) # now calculate (y1...yn = m(x1...xn)+c) for each value of\n\n# calculate y1....yn\nYY = []\n\nfor i in range(n):\n  tmp = m * xx[i] + c\n  YY.append(tmp)\n\n\n# ploting regression line \nplt.scatter(xx,yy)\nplt.plot(xx,YY)\n\nplt.xlabel(\"X coordinate\")\nplt.ylabel(\"Y coordinate\")\nplt.grid(True)\nplt.show()\n\n", "meta": {"hexsha": "3dbfd7fe9be3b9438dd5009941bdd585a5af76cf", "size": 704, "ext": "py", "lang": "Python", "max_stars_repo_path": "Codes/Algo Implement/simple-linear-regression.py", "max_stars_repo_name": "shohan4556/machine-learning-course-notes", "max_stars_repo_head_hexsha": "981f3d6e9861cbee0f4dec45b1d2e6a214d2a051", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-10-12T17:08:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-26T02:54:01.000Z", "max_issues_repo_path": "Codes/Algo Implement/simple-linear-regression.py", "max_issues_repo_name": "shohan4556/machine-learning-course-notes", "max_issues_repo_head_hexsha": "981f3d6e9861cbee0f4dec45b1d2e6a214d2a051", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Codes/Algo Implement/simple-linear-regression.py", "max_forks_repo_name": "shohan4556/machine-learning-course-notes", "max_forks_repo_head_hexsha": "981f3d6e9861cbee0f4dec45b1d2e6a214d2a051", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-10-30T03:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-11T20:53:47.000Z", "avg_line_length": 15.6444444444, "max_line_length": 70, "alphanum_fraction": 0.6051136364, "include": true, "reason": "import numpy", "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214521983688, "lm_q2_score": 0.901920681802153, "lm_q1q2_score": 0.8697414616431951}}
{"text": "# Importing the dependancies\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Loading the data in numerical format\nX = pd.read_csv('Linear Regression\\python\\Training Data\\Linear_X_Train.csv').values\ny = pd.read_csv('Linear Regression\\python\\Training Data\\Linear_Y_Train.csv').values\n\n# Standardising the data (We can even use min-max normalization)\nu = X.mean()\nstd = X.std()\nX = (X-u)/std\n\n# Visualising the data\nplt.style.use('fivethirtyeight') # Setting a plot style\nplt.scatter(X, y)\nplt.title(\"Hardwork vs Performance Graph\")\nplt.xlabel(\"Hardwork\")\nplt.ylabel(\"Performance\")\nplt.show()\n\n# METHOD-1: Normal Equation\n\nX_norm = np.concatenate((np.ones((X.shape[0], 1)), X), axis=1)\ntheta_norm = np.dot(np.linalg.inv(np.dot(X_norm.transpose(), X_norm)), np.dot(X_norm.transpose(), y))\nprint(f'Normal Equation method: {theta_norm}') # Parameter values\n\n# METHOD-2: Gradient Descent\n\n# Hypothesis function\ndef cost_function(temp, learning_rate):\n    cost_sigma = 0\n    for i in range(X_norm.shape[0]):\n        cost_sigma += (np.dot(temp.transpose(), X_norm[i])-y[i])**2\n    cost = learning_rate*(1/(2*X_norm.shape[0]))*cost_sigma\n    return cost\n\n# Updating the parameters \ndef update_theta(theta, learning_rate):\n    temp = np.empty((theta.shape[0], 1))\n    for i in range(theta.shape[0]):\n        sigma = np.zeros(1, dtype=np.float64)\n        for j in range(X_norm.shape[0]):\n            sigma += (np.dot(theta.transpose(), X_norm[j])-y[j])*X_norm[j][i]\n        temp[i] = (theta[i] - (learning_rate/X_norm.shape[0])*sum(sigma))\n    return temp\n    \n# Iterating 1000 times (Can be reduced if the rate of change of cost is very low)\ncost = [] # appending the costs for visualization\ntheta = np.zeros((X_norm.shape[1], 1)) # initializing the parameters\nn = int(input(\"Enter the number of iterations: \"))\nfor k in range(n):\n    learning_rate = 0.1 # (Ideal but can be triggered)\n    theta = update_theta(theta, learning_rate)\n    cost.append(cost_function(theta, learning_rate))\n\nprint(f'Gradient Descent method: {theta}') # Parameter values\n\n# Visualizing the cost function\nplt.plot(np.arange(n), cost)\nplt.title(\"Cost function vs iterations\")\nplt.xlabel(\"Iterations\")\nplt.ylabel(\"Cost\")\nplt.show()\n\n# Testing the model\nX_test = pd.read_csv('Linear Regression\\python\\Test\\Linear_X_Test.csv').values # Loading data\ny_test = np.dot(X_test, theta[1:].transpose()) # Computing the predictions\ndf = pd.DataFrame(data=y_test, columns=[\"y\"]) # Converting to a dataframe\ndf.to_csv('Linear Regression\\python\\y_prediction.csv', index=False) # Saving the dataframe", "meta": {"hexsha": "b410b3bf501ef83f97c3819a811d4b12524d3ea6", "size": 2576, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear Regression/python/Linear_Regression.py", "max_stars_repo_name": "Vamsi995/ML-FromScratch", "max_stars_repo_head_hexsha": "4f17905eaa0699502900bc37d7deba450e564a16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-11T13:03:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T13:03:17.000Z", "max_issues_repo_path": "Linear Regression/python/Linear_Regression.py", "max_issues_repo_name": "Vamsi995/ML-FromScratch", "max_issues_repo_head_hexsha": "4f17905eaa0699502900bc37d7deba450e564a16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear Regression/python/Linear_Regression.py", "max_forks_repo_name": "Vamsi995/ML-FromScratch", "max_forks_repo_head_hexsha": "4f17905eaa0699502900bc37d7deba450e564a16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-05T11:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-05T11:41:58.000Z", "avg_line_length": 36.2816901408, "max_line_length": 101, "alphanum_fraction": 0.7135093168, "include": true, "reason": "import numpy", "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377225508371, "lm_q2_score": 0.9073122313857378, "lm_q1q2_score": 0.8696929999150033}}
{"text": "import numpy as np\n\ndef conjgrad(A, b, x):\n    \"\"\"\n    A function to solve [A]{x} = {b} linear equation system with the \n    conjugate gradient method.\n    More at: http://en.wikipedia.org/wiki/Conjugate_gradient_method\n    ========== Parameters ==========\n    A : matrix \n        A real symmetric positive definite matrix.\n    b : vector\n        The right hand side (RHS) vector of the system.\n    x : vector\n        The starting guess for the solution.\n    \"\"\"  \n    r = b - np.dot(A, x)\n    p = r\n    rsold = np.dot(np.transpose(r), r)\n    \n    for i in range(len(b)):\n        Ap = np.dot(A, p)\n        alpha = rsold / np.dot(np.transpose(p), Ap)\n        x = x + np.dot(alpha, p)\n        r = r - np.dot(alpha, Ap)\n        rsnew = np.dot(np.transpose(r), r)\n        #print(\" error: \",i,np.sqrt(rsnew) )\n        if np.sqrt(rsnew) < 1e-8:\n            break\n        p = r + (rsnew/rsold)*p\n        rsold = rsnew\n        #print(\" sol: \", x)\n    return x\n\n\ndef main():\n\n  A = np.array([[5, -2, 0], [-2, 5, 1], [0, 1, 5]])\n  b = np.array([20, 10, -10])\n  #print(b)\n  #print(b.size)\n  x = np.zeros(b.size)\n  x=conjgrad(A, b, x)\n\n  print(\" The answer is:\", x)\n\n\nif __name__==\"__main__\":\n  main()\n", "meta": {"hexsha": "dc97d4d2ad6a1bf8df51e25652fa84952b6a808c", "size": 1190, "ext": "py", "lang": "Python", "max_stars_repo_path": "1_ML_Stanford/myLib/Conjugate_Gradient/CG.py", "max_stars_repo_name": "babakpst/Machine_Learning", "max_stars_repo_head_hexsha": "7f9e8e90609c6eeed18eb99276afce60dbf2338f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1_ML_Stanford/myLib/Conjugate_Gradient/CG.py", "max_issues_repo_name": "babakpst/Machine_Learning", "max_issues_repo_head_hexsha": "7f9e8e90609c6eeed18eb99276afce60dbf2338f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1_ML_Stanford/myLib/Conjugate_Gradient/CG.py", "max_forks_repo_name": "babakpst/Machine_Learning", "max_forks_repo_head_hexsha": "7f9e8e90609c6eeed18eb99276afce60dbf2338f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2857142857, "max_line_length": 69, "alphanum_fraction": 0.5218487395, "include": true, "reason": "import numpy", "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377284730285, "lm_q2_score": 0.9073122132152183, "lm_q1q2_score": 0.8696929878711515}}
{"text": "def cells():\n    '''\n    ## Chapter 3 problems\n    '''\n\n    '''\n    '''\n\n    from sympy import *\n    init_printing()\n\n    '''\n    '''\n\n\n    '''\n    '''\n\n    A = Matrix([\n    [3,     3],\n    [2, S(3)/2]])\n    A\n\n    '''\n    '''\n\n    b = Matrix([6,5])\n\n    '''\n    '''\n\n    AUG = A.row_join(b)\n    AUG # the augmented matrix\n\n    '''\n    '''\n\n    '''\n    ### Alice\n    '''\n\n    '''\n    '''\n\n    AUGA = AUG.copy()\n    AUGA[0,:] = AUGA[0,:]/3\n    AUGA\n\n    '''\n    '''\n\n    AUGA[1,:] = AUGA[1,:] - 2*AUGA[0,:]\n    AUGA\n\n    '''\n    '''\n\n    AUGA[1,:] = -2*AUGA[1,:]\n    AUGA\n\n    '''\n    '''\n\n    AUGA[0,:] = AUGA[0,:] - AUGA[1,:]\n    AUGA\n\n    '''\n    '''\n\n    '''\n    ### Bob\n    '''\n\n    '''\n    '''\n\n    AUGB = AUG.copy()\n    AUGB[0,:] = AUGB[0,:] - AUGB[1,:]\n    AUGB\n\n    '''\n    '''\n\n    AUGB[1,:] = AUGB[1,:] - 2*AUGB[0,:]\n    AUGB\n\n    '''\n    '''\n\n    AUGB[1,:] = -1*S(2)/3*AUGB[1,:]\n    AUGB\n\n    '''\n    '''\n\n    AUGB[0,:] = AUGB[0,:] - S(3)/2*AUGB[1,:]\n    AUGB\n\n    '''\n    '''\n\n\n    '''\n    '''\n\n    '''\n    ### Charlotte\n    '''\n\n    '''\n    '''\n\n    AUGC = AUG.copy()\n    AUGC[0,:], AUGC[1,:] = AUGC[1,:], AUGC[0,:]\n    AUGC\n\n    '''\n    '''\n\n    AUGC[0,:] = AUGC[0,:]/2\n    AUGC\n\n    '''\n    '''\n\n    AUGC[1,:] = AUGC[1,:] - 3*AUGC[0,:]\n    AUGC\n\n    '''\n    '''\n\n    AUGC[1,:] = S(4)/3*AUGC[1,:]\n    AUGC\n\n    '''\n    '''\n\n    AUGC[0,:] = AUGC[0,:] - S(3)/4*AUGC[1,:]\n    AUGC\n\n    '''\n    '''\n\n    '''\n    ### P3.3\n    '''\n\n    '''\n    '''\n\n    # define agmented matrices for three systems of eqns. with unique sol'ns\n    A = Matrix([\n            [ -1, -2, -2],\n            [  3, 3, 0]])\n            \n    B = Matrix([\n            [ 1, -1, -2,  1],\n            [-2,  3,  3, -1],\n            [-1,  0,  1,  2]])\n    \n    C = Matrix([\n            [ 2, -2,  3, 2],\n            [ 1, -2, -1, 0],\n            [-2,  2,  2, 1]])\n\n    '''\n    '''\n\n    A\n\n    '''\n    '''\n\n    A.rref()\n\n    '''\n    '''\n\n    B\n\n    '''\n    '''\n\n    B.rref()\n\n    '''\n    '''\n\n    C\n\n    '''\n    '''\n\n    C.rref()\n\n    '''\n    '''\n\n    '''\n    ### P3.4\n    '''\n\n    '''\n    '''\n\n    # now for three systems of eqns. with infinitely many sol'ns\n    D = Matrix([\n            [ -1, -2, -2],\n            [  3, 6,   6]])\n            \n    E = Matrix([\n            [ 1, -1, -2,  1],\n            [-2,  3,  3, -1],\n            [-1,  2,  1,  0]])\n    \n    F = Matrix([\n            [ 2, -2, 3, 2],\n            [ 0,  0, 5, 3],\n            [-2,  2, 2, 1]])\n\n    '''\n    '''\n\n    '''\n    ### Solving d)\n    '''\n\n    '''\n    '''\n\n    D\n\n    '''\n    '''\n\n    D.rref()\n\n    '''\n    '''\n\n    D[0:2,0:2].nullspace()\n\n    '''\n    '''\n\n    # the solutions to the sytem of equations represented by D\n    # is of the form    point + nullspace\n    point = D.rref()[0][:,2]\n    nullspace = D[0:2,0:2].nullspace()\n\n    '''\n    '''\n\n    # the point is also called he particular solution\n    point\n\n    '''\n    '''\n\n    # if A aug matrix is [A|b], then the point satisfies A*point = b.\n    print( D[0:2,0:2]*point == D[:,2] )\n    D[0:2,0:2]*point\n\n    '''\n    '''\n\n    '''\n    ### Null space\n    '''\n\n    '''\n    '''\n\n    # the nullspace of A in aug. matrix [A|b] is one dimensional and spanned by\n    n = nullspace[0]\n    n\n    # every vector n in the nullspace of A satisfies  A*n=0\n\n    '''\n    '''\n\n    # so solution to A*x=b is any (point+s*n) where s is any real number\n    # since  A*(point +s*n) = A*point + sA*n = A*point + 0 = b.\n    # verify claim for 20 values of s in range -5,-4,-3,-2,-1,0,1,2,3,4,5\n    for s in range(-5,6):\n        print( D[0:2,0:2]*(point + s*n), \n               D[0:2,0:2]*(point + s*n) == D[:,2] )\n\n    '''\n    '''\n\n    '''\n    ### Solving e)\n    '''\n\n    '''\n    '''\n\n    E\n\n    '''\n    '''\n\n    E.rref()\n\n    '''\n    '''\n\n    point_E = E.rref()[0][:,3]\n    nullspace_E = E[0:3,0:3].nullspace()[0]\n    s = symbols('s')\n    point_E + s*nullspace_E\n\n    '''\n    '''\n\n    '''\n    ### Solving f)\n    '''\n\n    '''\n    '''\n\n    F\n\n    '''\n    '''\n\n    F.rref()\n\n    '''\n    '''\n\n    point_F = F.rref()[0][:,3]\n    nullspace_F = F[0:3,0:3].nullspace()[0]\n    s = symbols('s')\n    point_F + s*nullspace_F\n\n    '''\n    '''\n\n\n    '''\n    '''\n\n", "meta": {"hexsha": "d685140d0b741e56b8e1e82748d0613a1720f7fe", "size": 4128, "ext": "py", "lang": "Python", "max_stars_repo_path": "aspynb/chapter03_problems.py", "max_stars_repo_name": "ChidinmaKO/noBSLAnotebooks", "max_stars_repo_head_hexsha": "c0102473f1e6625fa5fb62768d4545059959fa26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aspynb/chapter03_problems.py", "max_issues_repo_name": "ChidinmaKO/noBSLAnotebooks", "max_issues_repo_head_hexsha": "c0102473f1e6625fa5fb62768d4545059959fa26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aspynb/chapter03_problems.py", "max_forks_repo_name": "ChidinmaKO/noBSLAnotebooks", "max_forks_repo_head_hexsha": "c0102473f1e6625fa5fb62768d4545059959fa26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.9306358382, "max_line_length": 79, "alphanum_fraction": 0.3231589147, "include": true, "reason": "from sympy", "num_tokens": 1478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774727, "lm_q2_score": 0.9219218289556671, "lm_q1q2_score": 0.8696927243376983}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\nTitle: Finding the root nearest to x=0 for f(x) = tan(x) - 3 using the Bisection Method\n\nSolution to Problem Set 1, Problem 3\n~ Arsh R. Nadkarni\n\nTo run:\npython bfind_1_3.py\n\nThis code is a quantitative way to compute the midpoint of the function range initially and replace a or b, \nowing to the sign. The same is iterated until f(midpoint) is within the tolerance value (eps).\nThe upper limit (b), lower limit (a), and tolerance (eps) can be changed in the function arguments on line 51.\n\n\"\"\"\n# import libraries\nimport sys\nimport numpy as np\n\n# define the function\ndef f(x):\n    return np.tan(x) - 3\n# find the root using the bisection method\ndef bisection(a,b,eps):\n    # ensure that the a is negative and b is positive\n\tif f(a) > 0:\n\t\ta = b\n\t\tb = a\n\telif f(a)*f(b) > 0: # check the validity of the bounds used\n\t\tprint(\"Invalid Bounds. Root cannot be found!\")\n\t\texit()\n\t# define the mid-point\n\tmid = (a+b)/2\n\t# while loop to iterate the mid-point to until it is within eps\n\twhile np.abs(f(mid)) >= eps:\n\t\t# update bounds\n\t\tif f(mid) >= 0:\n\t\t\tb = mid\n\t\telse:\n\t\t\ta = mid\n\t\t# calculate midpoint with updated bounds\n\t\tmid = (a+b)/2\n\treturn mid\n\t\nanswer = bisection(-(np.pi/2),(np.pi/2),1e-3) # call the function\n\nprint(\"The root of f(x) = tan(x) - 3 nearest to x = 0 occurs at x =\", answer) # print the answer", "meta": {"hexsha": "a5aadbbb95e9d1afcbd19f7b57b683d7353cf83c", "size": 1335, "ext": "py", "lang": "Python", "max_stars_repo_path": "Problem Sets/Problem Set 1/bfind_1_3.py", "max_stars_repo_name": "astroarshn2000/PHYS305S20", "max_stars_repo_head_hexsha": "18f4ebf0a51ba62fba34672cf76bd119d1db6f1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-10T06:45:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T13:50:11.000Z", "max_issues_repo_path": "Problem Sets/Problem Set 1/bfind_1_3.py", "max_issues_repo_name": "astroarshn2000/PHYS305S20", "max_issues_repo_head_hexsha": "18f4ebf0a51ba62fba34672cf76bd119d1db6f1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Problem Sets/Problem Set 1/bfind_1_3.py", "max_forks_repo_name": "astroarshn2000/PHYS305S20", "max_forks_repo_head_hexsha": "18f4ebf0a51ba62fba34672cf76bd119d1db6f1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8125, "max_line_length": 110, "alphanum_fraction": 0.6801498127, "include": true, "reason": "import numpy", "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913343093499, "lm_q2_score": 0.9252299601846025, "lm_q1q2_score": 0.8696359850073747}}
{"text": "\"\"\"\n@author: MatteoRaso\n\"\"\"\nfrom numpy import pi, sqrt\nfrom random import uniform\n\n\ndef pi_estimator(iterations: int):\n    \"\"\"An implementation of the Monte Carlo method used to find pi.\n    1. Draw a 2x2 square centred at (0,0).\n    2. Inscribe a circle within the square.\n    3. For each iteration, place a dot anywhere in the square.\n    3.1 Record the number of dots within the circle.\n    4. After all the dots are placed, divide the dots in the circle by the total.\n    5. Multiply this value by 4 to get your estimate of pi.\n    6. Print the estimated and numpy value of pi\n    \"\"\"\n\n    circle_dots = 0\n\n    # A local function to see if a dot lands in the circle.\n    def circle(x: float, y: float):\n        distance_from_centre = sqrt((x ** 2) + (y ** 2))\n        # Our circle has a radius of 1, so a distance greater than 1 would land outside the circle.\n        return distance_from_centre <= 1\n\n    circle_dots = sum(\n        int(circle(uniform(-1.0, 1.0), uniform(-1.0, 1.0))) for i in range(iterations)\n    )\n\n    # The proportion of guesses that landed within the circle\n    proportion = circle_dots / iterations\n    # The ratio of the area for circle to square is pi/4.\n    pi_estimate = proportion * 4\n    print(\"The estimated value of pi is \", pi_estimate)\n    print(\"The numpy value of pi is \", pi)\n    print(\"The total error is \", abs(pi - pi_estimate))\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n", "meta": {"hexsha": "ce8f69f64a151321fc50e264dddfb443d50d1f81", "size": 1444, "ext": "py", "lang": "Python", "max_stars_repo_path": "maths/montecarlo.py", "max_stars_repo_name": "jjyy4sun/Python", "max_stars_repo_head_hexsha": "21f689120099c62cd96e5f406f5775675001d90d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-15T05:44:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-15T05:44:02.000Z", "max_issues_repo_path": "maths/montecarlo.py", "max_issues_repo_name": "Mathewsmusukuma/Python", "max_issues_repo_head_hexsha": "4866b1330bc7c77c0ed0e050e6b99efdeb026448", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maths/montecarlo.py", "max_forks_repo_name": "Mathewsmusukuma/Python", "max_forks_repo_head_hexsha": "4866b1330bc7c77c0ed0e050e6b99efdeb026448", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-03-06T00:53:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T13:42:35.000Z", "avg_line_length": 32.8181818182, "max_line_length": 99, "alphanum_fraction": 0.6668975069, "include": true, "reason": "from numpy", "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970239908635611, "lm_q2_score": 0.8962513668985002, "lm_q1q2_score": 0.8695788443341423}}
{"text": "\"\"\"File for non sklearn metrics that are to be used for reference for tests\"\"\"\nfrom typing import Optional\n\nimport numpy as np\nfrom sklearn.metrics._regression import _check_reg_targets\nfrom sklearn.utils.validation import check_consistent_length\n\n\ndef symmetric_mean_absolute_percentage_error(\n    y_true: np.ndarray,\n    y_pred: np.ndarray,\n    sample_weight: Optional[np.ndarray] = None,\n    multioutput: str = 'uniform_average'\n):\n    r\"\"\"Symmetric mean absolute percentage error regression loss.\n    <https://en.wikipedia.org/wiki/Symmetric_mean_absolute_percentage_error>`_ (SMAPE):\n\n    .. math:: \\text{SMAPE} = \\frac{2}{n}\\sum_1^n\\frac{max(|   y_i - \\hat{y_i} |}{| y_i | + | \\hat{y_i} |, \\epsilon)}\n\n    Where :math:`y` is a tensor of target values, and :math:`\\hat{y}` is a tensor of predictions.\n\n    Parameters\n    ----------\n    y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Ground truth (correct) target values.\n    y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Estimated target values.\n    sample_weight : array-like of shape (n_samples,), default=None\n        Sample weights.\n    multioutput : {'raw_values', 'uniform_average'} or array-like\n        Defines aggregating of multiple output values.\n        Array-like value defines weights used to average errors.\n        If input is list then the shape must be (n_outputs,).\n        'raw_values' :\n            Returns a full set of errors in case of multioutput input.\n        'uniform_average' :\n            Errors of all outputs are averaged with uniform weight.\n    Returns\n    -------\n    loss : float or ndarray of floats in the range [0, 1]\n        If multioutput is 'raw_values', then symmetric mean absolute percentage error\n        is returned for each output separately.\n        If multioutput is 'uniform_average' or an ndarray of weights, then the\n        weighted average of all output errors is returned.\n        MAPE output is non-negative floating point. The best value is 0.0.\n        But note the fact that bad predictions can lead to arbitarily large\n        MAPE values, especially if some y_true values are very close to zero.\n        Note that we return a large value instead of `inf` when y_true is zero.\n\n    \"\"\"\n    _, y_true, y_pred, multioutput = _check_reg_targets(y_true, y_pred, multioutput)\n    check_consistent_length(y_true, y_pred, sample_weight)\n    epsilon = np.finfo(np.float64).eps\n    smape = 2 * np.abs(y_pred - y_true) / np.maximum(np.abs(y_true) + np.abs(y_pred), epsilon)\n    output_errors = np.average(smape, weights=sample_weight, axis=0)\n    if isinstance(multioutput, str):\n        if multioutput == 'raw_values':\n            return output_errors\n        # pass None as weights to np.average: uniform mean\n        multioutput = None\n\n    return np.average(output_errors, weights=multioutput)\n", "meta": {"hexsha": "85e9d3cc921bd3066e7e008aef4d1261164b4d09", "size": 2863, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/helpers/non_sklearn_metrics.py", "max_stars_repo_name": "BeyondTheProof/metrics", "max_stars_repo_head_hexsha": "8af688daff819a95f4cb3d757ffc919c86072ee9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/helpers/non_sklearn_metrics.py", "max_issues_repo_name": "BeyondTheProof/metrics", "max_issues_repo_head_hexsha": "8af688daff819a95f4cb3d757ffc919c86072ee9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/helpers/non_sklearn_metrics.py", "max_forks_repo_name": "BeyondTheProof/metrics", "max_forks_repo_head_hexsha": "8af688daff819a95f4cb3d757ffc919c86072ee9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.4444444444, "max_line_length": 116, "alphanum_fraction": 0.6926301083, "include": true, "reason": "import numpy", "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731137267749, "lm_q2_score": 0.9032942067038784, "lm_q1q2_score": 0.8695770465789796}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# We Will Solve the Diff Equation: dA/dt = -λA = f(A,t), 0<=t<=8 [s]\ndef f(t, A):\n    λ = np.log(2)/2 # Constant\n    f = -λ*A\n    return f\n\n# Fourth Order Runge Kutta Method (τ: the step)\ndef RK4(τ):\n    # Interval Edges\n    a, b = 0, 8\n    # Number of Repetitions\n    N = int((b - a) / τ)\n\n    w = np.zeros(N+1)\n    t = np.zeros(N+1)\n\n    # Starting Points\n    w[0], t[0] = 1, 0\n\n    for i in range(N):\n        k1 = τ * f(t[i],w[i])\n        k2 = τ * f(t[i]+τ/2,w[i]+k1/2)\n        k3 = τ * f(t[i]+τ/2,w[i]+k2/2)\n        k4 = τ * f(t[i]+τ,w[i]+k3)\n        w[i+1] = w[i] + 1/6 * (k1 + 2*k2 + 2*k3 + k4)\n        t[i+1] = t[i] + τ\n\n    return w, t\n\n# We Compute the Uncertenty\ndef unc_RK4(τ):\n    unc = np.zeros(11)\n    rk4_τ, rk4_2τ = RK4(τ)[0], RK4(τ/2)[0]\n\n    for i in range(1,11):\n        unc[i] = (rk4_τ[i]-rk4_2τ[2*i])/15\n\n    return unc\n\nif __name__ == '__main__':\n\n    w_rk4, t_rk4, unc_rk4 = RK4(0.8)[0], RK4(0.8)[1], unc_RK4(0.8)\n\n    print('\\nComputed with 2^nd Order Runge Kutta Method:')\n    for i in range(11):\n        print(f\"\\tStep {i} with t_{i}={t_rk4[i]:.1f}: {w_rk4[i]:.8f} ± {unc_rk4[i]:.8f}\")\n\n    # Visualize the Results\n    ## Plot the Solutions for Both Methods\n    plt.plot(t_rk4, w_rk4, color='black', marker=\".\", linewidth=1, label='Runge Kutta 4^th Order')\n\n    ## How Graph is Shown (legend, axis titles, graph title)\n    plt.legend(loc='upper center', prop={'size': 10})\n    plt.ylabel('A(t) [kBq]')\n    plt.xlabel('Time [s]')\n    plt.title('Solution of Differential Equation')\n\n    ## Show the major grid lines with dark grey lines\n    plt.grid(b=True, which='major', color='#666666', linestyle='--')\n\n    ## Show the minor grid lines\n    plt.minorticks_on()\n    plt.grid(b=True, which='minor', color='#999999', linestyle='--', alpha=0.2)\n\n    ## Fix Quality\n    plt.tight_layout()\n\n    ## Show the Graph\n    plt.show()", "meta": {"hexsha": "bb2229d46c9e916e0628a33850eaa989814e89bf", "size": 1900, "ext": "py", "lang": "Python", "max_stars_repo_path": "Differential-Equations/Runge-Kutta-Fourth-Order.py", "max_stars_repo_name": "AlexTsagas/Computational-Physics", "max_stars_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Differential-Equations/Runge-Kutta-Fourth-Order.py", "max_issues_repo_name": "AlexTsagas/Computational-Physics", "max_issues_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Differential-Equations/Runge-Kutta-Fourth-Order.py", "max_forks_repo_name": "AlexTsagas/Computational-Physics", "max_forks_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3888888889, "max_line_length": 98, "alphanum_fraction": 0.5563157895, "include": true, "reason": "import numpy", "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731115849662, "lm_q2_score": 0.903294206053042, "lm_q1q2_score": 0.8695770440177535}}
{"text": "# GRADED FUNCTION\nimport numpy as np\nimport numpy.linalg as la\n\nverySmallNumber = 1e-14 # That's 1×10⁻¹⁴ = 0.00000000000001\n\n# Our first function will perform the Gram-Schmidt procedure for 4 basis vectors.\ndef gsBasis4(A) :\n    B = np.array(A, dtype=np.float_) # Make B as a copy of A, since we're going to alter it's values.\n    # The zeroth column is easy, since it has no other vectors to make it normal to.\n    # All that needs to be done is to normalise it. I.e. divide by its modulus, or norm.\n    B[:, 0] = B[:, 0] / la.norm(B[:, 0])\n    # For the first column, we need to subtract any overlap with our new zeroth vector.\n    B[:, 1] = B[:, 1] - B[:, 1] @ B[:, 0] * B[:, 0]\n    # If there's anything left after that subtraction, then B[:, 1] is linearly independant of B[:, 0]\n    # If this is the case, we can normalise it. Otherwise we'll set that vector to zero.\n    if la.norm(B[:, 1]) > verySmallNumber :\n        B[:, 1] = B[:, 1] / la.norm(B[:, 1])\n    else :\n        B[:, 1] = np.zeros_like(B[:, 1])\n    # Now we need to repeat the process for column 2.\n    # Insert two lines of code, the first to subtract the overlap with the zeroth vector,\n    # and the second to subtract the overlap with the first.\n    B[:, 2] = B[:, 2] - B[:, 2] @ B[:, 0] * B[:, 0]\n    B[:, 2] = B[:, 2] - B[:, 1] @ B[:, 0] * B[:, 0]\n    # Again we'll need to normalise our new vector.\n    # Copy and adapt the normalisation fragment from above to column 2.\n    if la.norm(B[:, 2]) > verySmallNumber :\n        B[:, 2] = B[:, 2] / la.norm(B[:, 2])\n    else :\n        B[:, 2] = np.zeros_like(B[:, 2])\n    # Finally, column three:\n    # Insert code to subtract the overlap with the first three vectors.\n    B[:, 3] = B[:, 3] - B[:, 3] @ B[:, 0] * B[:, 0]\n    B[:, 3] = B[:, 3] - B[:, 3] @ B[:, 1] * B[:, 1]\n    B[:, 3] = B[:, 3] - B[:, 3] @ B[:, 2] * B[:, 2]\n    # Now normalise if possible\n    if la.norm(B[:, 3]) > verySmallNumber :\n        B[:, 3] = B[:, 3] / la.norm(B[:, 3])\n    else :\n        B[:, 3] = np.zeros_like(B[:, 3])\n    # Finally, we return the result:\n    return B\n\n# In the second function we will generalise the procedure.\n# Previously, we could only have four vectors, and there was a lot of repeating in the code.\n# We'll use a for-loop here to iterate the process for each vector.\ndef gsBasis(A) :\n    B = np.array(A, dtype=np.float_) # Make B as a copy of A, since we're going to alter it's values.\n    # Loop over all vectors, starting with zero, label them with i\n    for i in range(B.shape[1]) :\n        # Inside that loop, loop over all previous vectors, j, to subtract.\n        for j in range(i) :\n            B[:, i] = B[:, i] - B[:, i] @ B[:, j] * B[:, j]\n        # Next insert code to do the normalisation test for B[:, i]\n        if la.norm(B[:, i]) > verySmallNumber :\n            B[:, i] = B[:, i] / la.norm(B[:, i])\n        else :\n            B[:, i] = np.zeros_like(B[:, i])\n    # Finally, we return the result:\n    return B\n\n# This function uses the Gram-schmidt process to calculate the dimension\n# spanned by a list of vectors.\n# Since each vector is normalised to one, or is zero,\n# the sum of all the norms will be the dimension.\ndef dimensions(A) :\n    return np.sum(la.norm(gsBasis(A), axis=0))\n\n\n#Test cases:\nV = np.array([[1,0,2,6],\n              [0,1,8,2],\n              [2,8,3,1],\n              [1,-6,2,3]], dtype=np.float_)\ngsBasis4(V)\n\n# Once you've done Gram-Schmidt once,\n# doing it again should give you the same result.\nU = gsBasis4(V)\ngsBasis4(U)\n\n# Try the general function.\ngsBasis(V)\n\n# See what happens for non-square matrices\nA = np.array([[3,2,3],\n              [2,5,-1],\n              [2,4,8],\n              [12,2,1]], dtype=np.float_)\ngsBasis(A)\n\ndimensions(A)\n\nB = np.array([[6,2,1,7,5],\n              [2,8,5,-4,1],\n              [1,-6,3,2,8]], dtype=np.float_)\ngsBasis(B)\n\ndimensions(B)\n\n# Now let's see what happens when we have one vector that is a linear combination of the others.\nC = np.array([[1,0,2],\n              [0,1,-3],\n              [1,0,2]], dtype=np.float_)\ngsBasis(C)\n\ndimensions(C)\n\n", "meta": {"hexsha": "25201d8e98ca5a50e2d88e378877d73c81677296", "size": 4051, "ext": "py", "lang": "Python", "max_stars_repo_path": "coursera-linear-algebra-assignments/GramSchmidtProcess.py", "max_stars_repo_name": "zelzhan/Linear-algebra-with-python", "max_stars_repo_head_hexsha": "a58042c9f29f67aafcd2c1c4c1300a0e9223a650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "coursera-linear-algebra-assignments/GramSchmidtProcess.py", "max_issues_repo_name": "zelzhan/Linear-algebra-with-python", "max_issues_repo_head_hexsha": "a58042c9f29f67aafcd2c1c4c1300a0e9223a650", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coursera-linear-algebra-assignments/GramSchmidtProcess.py", "max_forks_repo_name": "zelzhan/Linear-algebra-with-python", "max_forks_repo_head_hexsha": "a58042c9f29f67aafcd2c1c4c1300a0e9223a650", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8272727273, "max_line_length": 102, "alphanum_fraction": 0.5731918045, "include": true, "reason": "import numpy", "num_tokens": 1274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620608291781, "lm_q2_score": 0.9059898191142621, "lm_q1q2_score": 0.8695346558833585}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Dec  2 17:55:16 2021\r\n\r\n@author: Oliver\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport scipy.integrate\r\n\"\"\"Numerical Integration Methods\"\"\"\r\n\r\n\"\"\"Rectangular Rule\"\"\" \"\"\"INTEGRATION\"\"\"\r\n\r\ndef calculate_dx (a, b, n):\r\n    return (b-a)/float(n)\r\n\r\ndef rect_rule (f, a, b, n):\r\n    total = 0.0\r\n    dx = calculate_dx(a, b, n)\r\n    for k in range (0, n):\r\n        total = total + f((a + (k*dx)))\r\n    return dx*total\r\n\r\ndef f(x):\r\n    return x**2\r\nprint(rect_rule(f, 0, 10, 100000))\r\n\r\n\"\"\"Trapezoidal Rule\"\"\"\r\n\r\ndef trapz(f,a,b,N=50): \r\n    x = np.linspace(a,b,N+1) # N+1 points make N subintervals\r\n    y = f(x)\r\n    y_right = y[1:] # right endpoints\r\n    y_left = y[:-1] # left endpoints\r\n    dx = (b - a)/N\r\n    T = (dx/2) * np.sum(y_right + y_left)\r\n    return T\r\n\r\ndef f(x):\r\n    return np.exp(-x**2)\r\n\r\na=1#float(input(\"Please enter a value for the lower bound:\\n\"))\r\nb=-1#float(input(\"Please enter a value for the upper bound:\\n\"))\r\nn=1000#int(input(\"Please enter a value for the number of intervals:\\n\"))\r\nprint(trapz(f,a,b,n)) \r\n\r\n# Graphing the Trapezoidal Rule\r\n\r\n\r\nx = np.linspace(-1.5,1.5,100)\r\ny = np.exp(x**2)\r\nplt.plot(x,y)\r\nx0 = 0; x1 = 1;\r\ny0 = np.exp(x0**2); y1 = np.exp(x1**2);\r\nplt.fill_between([x0,x1],[y0,y1])\r\nplt.xlim([-1.5,1.5]); plt.ylim([0,10]);\r\nplt.show()\r\nA = 0.5*(y1 + y0)*(x1 - x0)\r\nprint(\"Trapezoid area:\", A)\r\n\r\n\r\n\"\"\"Simpsons Rule Method\"\"\"\r\n\r\ndef simps(f,a,b,N=50):\r\n    if N % 2 == 1:\r\n        raise ValueError(\"N must be an even integer.\")\r\n    dx = (b-a)/N\r\n    x = np.linspace(a,b,N+1)\r\n    y = f(x)\r\n    S = dx/3 * np.sum(y[0:-1:2] + 4*y[1::2] + y[2::2]) # x[startAt:endBefore:skip]\r\n    return S\r\n# https://stackoverflow.com/questions/9027862/what-does-listxy-do\r\nf = lambda x: x**3\r\nsolution = simps(f,1,2,24)\r\nprint(solution)\r\n\r\n\"\"\"Adaptive Simpson Algorithm\"\"\"\r\n\r\nes = 0.0001\r\n\r\ndef simps(f,a,b,N):\r\n    if N % 2 == 1:\r\n        raise ValueError(\"N must be an even integer.\")\r\n    dx = (b-a)/N\r\n    x = np.linspace(a,b,N+1)\r\n    y = f(x)\r\n    S = dx/3 * np.sum(y[0:-1:2] + 4*y[1::2] + y[2::2])\r\n    #print(S)\r\n    return S\r\n\r\ndef f(x):\r\n    return x**2+4*x-12\r\n\r\nansol = scipy.integrate.quad(f,-10,10)\r\n\r\nfor N in range(2,10,1):\r\n    es = 0.0001\r\n    integral = simps(f,-10,10,N)\r\n    et = (integral - ansol[0])/ansol[0]\r\n    if abs(et) <= es:\r\n        print(f'integral and error {integral, et}')\r\n        break\r\n\r\n# IDK TRY TOMORROW WHEN YOU ARE LESS TIRED\r\n\r\n\r\n# \"structured\" adaptive version, translated from Racket\r\ndef _quad_simpsons_mem(f, a, fa, b, fb):\r\n    \"\"\"Evaluates the Simpson's Rule, also returning m and f(m) to reuse\"\"\"\r\n    m = (a + b) / 2\r\n    fm = f(m)\r\n    return (m, fm, abs(b - a) / 6 * (fa + 4 * fm + fb))\r\n\r\ndef _quad_asr(f, a, fa, b, fb, eps, whole, m, fm):\r\n    \"\"\"\r\n    Efficient recursive implementation of adaptive Simpson's rule.\r\n    Function values at the start, middle, end of the intervals are retained.\r\n    \"\"\"\r\n    lm, flm, left  = _quad_simpsons_mem(f, a, fa, m, fm)\r\n    rm, frm, right = _quad_simpsons_mem(f, m, fm, b, fb)\r\n    delta = left + right - whole\r\n    if abs(delta) <= 15 * eps:\r\n        return left + right + delta / 15\r\n    return _quad_asr(f, a, fa, m, fm, eps/2, left , lm, flm) +\\\r\n           _quad_asr(f, m, fm, b, fb, eps/2, right, rm, frm)\r\n\r\ndef quad_asr(f, a, b, eps):\r\n    \"\"\"Integrate f from a to b using Adaptive Simpson's Rule with max error of eps.\"\"\"\r\n    fa, fb = f(a), f(b)\r\n    m, fm, whole = _quad_simpsons_mem(f, a, fa, b, fb)\r\n    return _quad_asr(f, a, fa, b, fb, eps, whole, m, fm)\r\n\r\nfrom math import sin\r\nprint(quad_asr(sin, 0, 1, 1e-09))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "5de5e43a39c23154ef4cb294b3c3fbbdbc73581b", "size": 3692, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lecture_11_taks.py", "max_stars_repo_name": "oliver779/Computational_Methods_Course", "max_stars_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lecture_11_taks.py", "max_issues_repo_name": "oliver779/Computational_Methods_Course", "max_issues_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lecture_11_taks.py", "max_forks_repo_name": "oliver779/Computational_Methods_Course", "max_forks_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5906432749, "max_line_length": 87, "alphanum_fraction": 0.5544420368, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620562254526, "lm_q2_score": 0.905989822921759, "lm_q1q2_score": 0.8695346553667211}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nFile per la soluzione di sistemi Lineari\r\n\"\"\"\r\nimport numpy as np\r\n\r\ndef Lsolve(L,b):\r\n    \"\"\"  \r\n    Risoluzione con procedura forward di Lx=b con L triangolare inferiore  \r\n     Input: L matrice triangolare inferiore\r\n            b termine noto\r\n    Output: x: soluzione del sistema lineare\r\n            flag=  0, se sono soddisfatti i test di applicabilità\r\n                   1, se non sono soddisfatti\r\n    \"\"\"\r\n#test dimensione\r\n    m,n=L.shape\r\n    flag=0;\r\n    if n != m:\r\n        print('errore: matrice non quadrata')\r\n        flag=1\r\n        x=[]\r\n        return x, flag\r\n    \r\n     # Test singolarita'\r\n    if np.all(np.diag(L)) != True:\r\n         print('el. diag. nullo - matrice triangolare inferiore')\r\n         x=[]\r\n         flag=1\r\n         return x, flag\r\n    # Preallocazione vettore soluzione\r\n    x=np.zeros((n,1))\r\n    \r\n    for i in range(n):\r\n         s=np.dot(L[i,:i],x[:i]) #scalare=vettore riga * vettore colonna\r\n         x[i]=(b[i]-s)/L[i,i]\r\n      \r\n     \r\n    return x,flag\r\n\r\n\r\ndef Usolve(U,b):\r\n    \r\n    \"\"\"\r\n    Risoluzione con procedura backward di Rx=b con R triangolare superiore  \r\n     Input: U matrice triangolare superiore\r\n            b termine noto\r\n    Output: x: soluzione del sistema lineare\r\n            flag=  0, se sono soddisfatti i test di applicabilità\r\n                   1, se non sono soddisfatti\r\n    \r\n    \"\"\" \r\n#test dimensione\r\n    m,n=U.shape\r\n    flag=0;\r\n    if n != m:\r\n        print('errore: matrice non quadrata')\r\n        flag=1\r\n        x=[]\r\n        return x, flag\r\n    \r\n     # Test singolarita'\r\n    if np.all(np.diag(U)) != True:\r\n         print('el. diag. nullo - matrice triangolare superiore')\r\n         x=[]\r\n         flag=1\r\n         return x, flag\r\n    # Preallocazione vettore soluzione\r\n    x=np.zeros((n,1))\r\n    \r\n    for i in range(n-1,-1,-1):\r\n         s=np.dot(U[i,i+1:n],x[i+1:n]) #scalare=vettore riga * vettore colonna\r\n         x[i]=(b[i]-s)/U[i,i]\r\n      \r\n     \r\n    return x,flag\r\n\r\n\r\ndef LUsolve(L,U,P,b):\r\n     \"\"\"\r\n     Risoluzione a partire da PA =LU assegnata\r\n     \"\"\"\r\n     Pb=np.dot(P,b)\r\n     y,flag=Lsolve(L,Pb)\r\n     if flag == 0:\r\n         x,flag=Usolve(U,y)\r\n     else:\r\n        return [],flag\r\n\r\n     return x,flag\r\n \r\n    \r\ndef LU_nopivot(A):\r\n    \"\"\"\r\n    % Fattorizzazione PA=LU senza pivot   versione vettorizzata\r\n    In output:\r\n    L matrice triangolare inferiore\r\n    U matrice triangolare superiore\r\n    P matrice identità\r\n    tali che  LU=PA=A\r\n    \"\"\"\r\n    # Test dimensione\r\n    m,n=A.shape\r\n   \r\n    flag=0;\r\n    if n!=m:\r\n      print(\"Matrice non quadrata\")\r\n      L,U,P,flag=[],[],[],1 \r\n      return P,L,U,flag\r\n  \r\n    P=np.eye(n);\r\n    U=A.copy();\r\n # Fattorizzazione\r\n    for k in range(n-1):\r\n       #Test pivot \r\n          if U[k,k]==0:\r\n            print('elemento diagonale nullo')\r\n            L,U,P,flag=[],[],[],1 \r\n            return P,L,U,flag\r\n\r\n  #     Eliminazione gaussiana\r\n          U[k+1:n,k]=U[k+1:n,k]/U[k,k]                                   # Memorizza i moltiplicatori\t  \r\n          U[k+1:n,k+1:n]=U[k+1:n,k+1:n]-np.outer(U[k+1:n,k],U[k,k+1:n])  # Eliminazione gaussiana sulla matrice\r\n     \r\n  \r\n    L=np.tril(U,-1)+np.eye(n)  # Estrae i moltiplicatori \r\n    U=np.triu(U)           # Estrae la parte triangolare superiore + diagonale\r\n    return P,L,U,flag\r\n\r\ndef LU_nopivotv(A):\r\n    \"\"\"\r\n    % Fattorizzazione PA=LU senza pivot   versione vettorizzata intermedia\r\n    In output:\r\n    L matrice triangolare inferiore\r\n    U matrice triangolare superiore\r\n    P matrice identità\r\n    tali che  LU=PA=A\r\n    \"\"\"\r\n    # Test dimensione\r\n    m,n=A.shape\r\n   \r\n    flag=0;\r\n    if n!=m:\r\n      print(\"Matrice non quadrata\")\r\n      L,U,P,flag=[],[],[],1 \r\n      return P,L,U,flag\r\n  \r\n    P=np.eye(n);\r\n    U=A.copy();\r\n # Fattorizzazione\r\n    for k in range(n-1):\r\n       #Test pivot \r\n          if U[k,k]==0:\r\n            print('elemento diagonale nullo')\r\n            L,U,P,flag=[],[],[],1 \r\n            return P,L,U,flag\r\n\r\n  #     Eliminazione gaussiana\r\n          for i in range(k+1,n):\r\n             U[i,k]=U[i,k]/U[k,k]                                   # Memorizza i moltiplicatori\t  \r\n             U[i,k+1:n]=U[i,k+1:n]-U[i,k]*U[k,k+1:n]  # Eliminazione gaussiana sulla matrice\r\n     \r\n  \r\n    L=np.tril(U,-1)+np.eye(n)  # Estrae i moltiplicatori \r\n    U=np.triu(U)           # Estrae la parte triangolare superiore + diagonale\r\n    return P,L,U,flag\r\n\r\ndef LU_nopivotb(A):\r\n    \"\"\"\r\n    % Fattorizzazione PA=LU senza pivot  versione base\r\n    In output:\r\n    L matrice triangolare inferiore\r\n    U matrice triangolare superiore\r\n    P matrice identità\r\n    tali che  LU=PA=A\r\n    \"\"\"\r\n    # Test dimensione\r\n    m,n=A.shape\r\n    flag=0;\r\n    if n!=m:\r\n      print(\"Matrice non quadrata\")\r\n      L,U,P,flag=[],[],[],1 \r\n      return P,L,U,flag\r\n  \r\n    P=np.eye(n);\r\n    U=A.copy();\r\n # Fattorizzazione\r\n    for k in range(n-1):\r\n         #Test pivot \r\n         \r\n         \r\n          if U[k,k]==0:\r\n            print('elemento diagonale nullo')\r\n            L,U,P,flag=[],[],[],1 \r\n            return P,L,U,flag\r\n\r\n  #     Eliminazione gaussiana\r\n          for i in range(k+1,n):\r\n                U[i,k]=U[i,k]/U[k,k]\r\n                for j in range(k+1,n):                                 # Memorizza i moltiplicatori\t  \r\n                  U[i,j]=U[i,j]-U[i,k]*U[k,j]  # Eliminazione gaussiana sulla matrice\r\n     \r\n  \r\n    L=np.tril(U,-1)+np.eye(n)  # Estrae i moltiplicatori \r\n    U=np.triu(U)           # Estrae la parte triangolare superiore + diagonale\r\n    return P,L,U,flag\r\n\r\ndef swapRows(A,k,p):\r\n    A[[k,p],:] = A[[p,k],:]\r\n    \r\n    \r\ndef LU_pivot(A):\r\n    \"\"\"\r\n    % Fattorizzazione PA=LU con pivot \r\n    In output:\r\n    L matrice triangolare inferiore\r\n    U matrice triangolare superiore\r\n    P matrice di permutazione\r\n    tali che  PA=LU\r\n    \"\"\"\r\n    # Test dimensione\r\n    m,n=A.shape\r\n    flag=0;\r\n    if n!=m:\r\n      print(\"Matrice non quadrata\")\r\n      L,U,P,flag=[],[],[],1 \r\n      return P,L,U,flag\r\n  \r\n    P=np.eye(n);\r\n    U=A.copy();\r\n # Fattorizzazione\r\n    for k in range(n-1):\r\n       #Scambio di righe nella matrice U e corrispondente scambio nella matrice di permutazione per\r\n       # tenere traccia degli scambi avvenuti\r\n       \r\n       #Fissata la colonna k-esima calcolo l'indice di riga p a cui appartiene l'elemento di modulo massimo a partire dalla riga k-esima\r\n          p = np.argmax(abs(U[k:n,k])) + k\r\n          if p != k:\r\n              swapRows(P,k,p)\r\n              swapRows(U,k,p)\r\n\r\n  #     Eliminazione gaussiana\r\n          U[k+1:n,k]=U[k+1:n,k]/U[k,k]                                   # Memorizza i moltiplicatori\t  \r\n          U[k+1:n,k+1:n]=U[k+1:n,k+1:n]-np.outer(U[k+1:n,k],U[k,k+1:n])  # Eliminazione gaussiana sulla matrice\r\n     \r\n  \r\n    L=np.tril(U,-1)+np.eye(n)  # Estrae i moltiplicatori \r\n    U=np.triu(U)           # Estrae la parte triangolare superiore + diagonale\r\n    return P,L,U,flag\r\n\r\n\r\n\"\"\"\r\nRisolve n sistemi lineari che condividono la matrice A, ma ognuno ha come vettore b,\r\nuna colonna di A\r\n\r\nSe B = id allora X = inversa di A\r\n\"\"\"\r\ndef solve_nsis(A,B):\r\n  # Test dimensione  \r\n    m,n=A.shape\r\n    flag=0;\r\n    if n!=m:\r\n      print(\"Matrice non quadrata\")\r\n       \r\n      return\r\n    \r\n    Y= np.zeros((n,n))\r\n    X= np.zeros((n,n))\r\n    P,L,U,flag= LU_nopivot(A)\r\n    \r\n    if flag==0:\r\n        for i in range(n):\r\n            y,flag=Lsolve(L,np.dot(P,B[:,i]))\r\n            # squeezy toglie la seconda dimensione(y era una matrice nx1)\r\n            Y[:,i]=y.squeeze(1)\r\n            x,flag= Usolve(U,Y[:,i])\r\n            X[:,i]=x.squeeze(1)\r\n    else:\r\n        print(\"Elemento diagonale nullo\")\r\n        X=[]\r\n    return X    \r\n    \r\n    ", "meta": {"hexsha": "a176b0e9cb7253ae7a3ae618bb14c9d8e94380c2", "size": 7705, "ext": "py", "lang": "Python", "max_stars_repo_path": "sistemi_lineari/funzioni_Sistemi_lineari.py", "max_stars_repo_name": "luigi-borriello00/Metodi_SIUMerici", "max_stars_repo_head_hexsha": "cf1407c0ad432a49a96dcd08303213e48723c57a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-06-23T14:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T08:39:27.000Z", "max_issues_repo_path": "sistemi_lineari/funzioni_Sistemi_lineari.py", "max_issues_repo_name": "luigi-borriello00/Metodi_SIUMerici", "max_issues_repo_head_hexsha": "cf1407c0ad432a49a96dcd08303213e48723c57a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sistemi_lineari/funzioni_Sistemi_lineari.py", "max_forks_repo_name": "luigi-borriello00/Metodi_SIUMerici", "max_forks_repo_head_hexsha": "cf1407c0ad432a49a96dcd08303213e48723c57a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2261484099, "max_line_length": 137, "alphanum_fraction": 0.5156391953, "include": true, "reason": "import numpy", "num_tokens": 2280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762057376384, "lm_q2_score": 0.9059898114992677, "lm_q1q2_score": 0.8695346454465794}}
{"text": "# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nfrom functools import reduce\r\n\r\nar = np.array\r\n\r\ndef gauss(A, b):\r\n    n = A.shape[0]\r\n    \r\n    for k in range(n-1):\r\n        i = slice(k+1,n)\r\n        lk = np.divide(A[i, k] , A[k, k])\r\n        A[i, i] = A[i,i] - np.multiply(A[k,i], lk)\r\n        b[i] = b[i] - np.multiply(b[k], lk[:, np.newaxis])\r\n\r\n    return A, b\r\n\r\n# Factorización LU\r\n# Algoritmo que reescribe la matriz A para que la parte superior almacene\r\n# la matriz U de la descomposición LU\r\ndef LU(A):\r\n    n = A.shape[0]\r\n    for k in range(n-1):\r\n        i = slice(k+1,n)\r\n        A[i, k] = np.divide(A[i, k] , A[k, k])\r\n        A[i,i] = A[i,i] - np.multiply(A[i, k], A[k,i])\r\n    \r\n    U = np.triu(A)\r\n    L = np.tril(A)\r\n    np.fill_diagonal(L, 1)\r\n    return L, U\r\n\r\nL, U = LU(ar([[1, 2], [3, 4]]))\r\n\r\nnp.matmul(L, U)\r\n\r\n# Generar mil lados derechos, y calcular con eliminación gaussiana\r\n# Generar los matrices\r\n\r\n\r\nA = ar([[3, 0, 0, 0], \r\n        [2, 1, 0, 0], \r\n        [1, 5, 1, 0], \r\n        [7, 9, 8, 4]])\r\n\r\nb = ar([[-9, 12], \r\n        [6,  -1], \r\n        [2,   0], \r\n        [5,   1]])\r\n\r\nmil_bs = [ b for i in range(1000) ]\r\nmil_bs = reduce(lambda a, b: np.append(a, b, axis = 1), mil_bs)\r\n\r\ndef sustitucion_adelante(A, b):\r\n    \"\"\"A matriz triangular inferior\"\"\"\r\n    n = A.shape[0]\r\n    x = np.zeros((n, b.shape[1]))\r\n\r\n    x[0,:] = b[0,:] / A[0, 0]\r\n    \r\n    for i in range(1, n):\r\n        x[i,:] = b[i,:] - np.matmul(A[i,:i], x[:i,:])\r\n        x[i,:] = x[i,:] / A[i, i]\r\n#\r\n    return x\r\n\r\ndef sustitucion_atras(A, b):\r\n    \"\"\"A matriz triangular superior\"\"\"\r\n    n = A.shape[0]\r\n    x = np.zeros((n, b.shape[1]))\r\n\r\n    x[-1,:] = b[-1,:] / A[-1, -1]\r\n    \r\n    for i in range(n-1, -1, -1):\r\n        x[i,:] = b[i,:] - np.matmul(A[i,(i+1):], x[(i + 1):,:])\r\n        x[i,:] = x[i,:] / A[i, i]\r\n#\r\n    return x\r\n\r\n# Tiempo que se tarda en ejecutar eliminación gaussiana\r\ndef fun1_gauss():\r\n    gauss(A, mil_bs)\r\n    return\r\n\r\nfun1_gauss()\r\n\r\n#%timeit fun1_gauss()\r\n#The slowest run took 10.18 times longer than the fastest. This could mean that an intermediate result is being cached.\r\n#10000 loops, best of 3: 70.2 µs per loop\r\n\r\n# Tiempo que se tarda en Resolver con sustitución hacia adelante y hacia atrás\r\ndef fun2_LU():\r\n    L, U = LU(A)\r\n    # Paso 1: Resolvemos LY = b\r\n    y = sustitucion_adelante(L, mil_bs)\r\n    # Paso 2: Resolvemos Ux = Y\r\n    sustitucion_atras(U, y)\r\n    return \r\n\r\nfun2_LU()\r\n\r\n#%timeit fun2_LU()\r\n#The slowest run took 8.52 times longer than the fastest. This could mean that an intermediate result is being cached.\r\n#10000 loops, best of 3: 164 µs per loop\r\n", "meta": {"hexsha": "0763460b2b9e5651e17d4de4921a3e01977c0f0a", "size": 2618, "ext": "py", "lang": "Python", "max_stars_repo_path": "analisisnum-jorgealtamirano/participaciones-adicionales-2019/3-ejercicios/11_fact_LU/equipo7_LU_vs_eliminacion_Gaussiana.py", "max_stars_repo_name": "philwebsurfer/analisis-numerico-computo-cientifico", "max_stars_repo_head_hexsha": "dd4dc0e03662a6b03deda7cd2d6896f8f1e59abc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analisisnum-jorgealtamirano/participaciones-adicionales-2019/3-ejercicios/11_fact_LU/equipo7_LU_vs_eliminacion_Gaussiana.py", "max_issues_repo_name": "philwebsurfer/analisis-numerico-computo-cientifico", "max_issues_repo_head_hexsha": "dd4dc0e03662a6b03deda7cd2d6896f8f1e59abc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analisisnum-jorgealtamirano/participaciones-adicionales-2019/3-ejercicios/11_fact_LU/equipo7_LU_vs_eliminacion_Gaussiana.py", "max_forks_repo_name": "philwebsurfer/analisis-numerico-computo-cientifico", "max_forks_repo_head_hexsha": "dd4dc0e03662a6b03deda7cd2d6896f8f1e59abc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6981132075, "max_line_length": 120, "alphanum_fraction": 0.5229182582, "include": true, "reason": "import numpy", "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159683, "lm_q2_score": 0.9149009480320035, "lm_q1q2_score": 0.8695319038919321}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nxc = np.linspace(0, 1, 101)  # x coordinates for plotting\n\ndef f(x):\n    return 1 + 2*x*(1-x)\n\nimport sympy as sym\nx = sym.symbols('x')\npsi_0 = 1\npsi_1 = sym.sin(sym.pi*x)\n\nhalf = sym.Rational(1,2)\nu = 1*psi_0 + half*psi_1\n\n# How to combine c_0*psi_0 + c_1*psi_1 to match f?\n# Intuitively, c_0=c_1=1...\n# Turn u to function so we can plot and compute with it\nu = sym.lambdify([x], u, modules='numpy')\n\nprint('L2 error of intuitive approximation:', end=' ')\ne = f(xc) - u(xc)\ndx = xc[1] - xc[0]\nprint(np.sqrt(dx*np.sum(e**2)))\n\nplt.plot(xc, f(xc), 'r--')\nplt.plot(xc, u(xc), 'b-')\nplt.legend(['exact', 'intuitive approximation'])\nplt.savefig('tmp1.png'); plt.savefig('tmp1.pdf')\n\n# Do the calculations in the least squares or project method\nA = sym.zeros(2, 2)\nb = sym.zeros(2, 1)\nA[0,0] = sym.integrate(psi_0*psi_0, (x, 0, 1))\nA[0,1] = sym.integrate(psi_0*psi_1, (x, 0, 1))\nA[1,0] = A[0,1]\nA[1,1] = sym.integrate(psi_1*psi_1, (x, 0, 1))\nb[0] = sym.integrate(f(x)*psi_0, (x, 0, 1))\nb[1] = sym.integrate(f(x)*psi_1, (x, 0, 1))\nprint('A:', A)\nprint('b:', b)\nc = A.LUsolve(b)\nc = [sym.simplify(c[i,0]) for i in range(c.shape[0])]\nprint('c:', c, [c_.evalf() for c_ in c])\nu = c[0]*psi_0 + c[1]*psi_1\nprint('u:', u)\nprint(sym.latex(u))\nprint(sym.latex(A))\nprint(sym.latex(c))\nprint(sym.latex(b))\n# Turn u to function so we can plot it\nu = sym.lambdify([x], u, modules='numpy')\n\nprint('L2 error of least squares approximation:', end=' ')\ne = f(xc) - u(xc)\ndx = xc[1] - xc[0]\nprint(np.sqrt(dx*np.sum(e**2)))\n\nplt.plot(xc, u(xc), 'k-')\nplt.legend(['exact', 'guess', 'least squares approx.'],\n           loc='lower center')\nplt.savefig('tmp2.png'); plt.savefig('tmp2.pdf')\nplt.show()\n\n\n\n", "meta": {"hexsha": "9a4806b5da15f0a6240928ce7c87827564802c87", "size": 1729, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/.src/book/exer/parabola_sin.py", "max_stars_repo_name": "hplgit/fem-book", "max_stars_repo_head_hexsha": "c23099715dc3cb72e7f4d37625e6f9614ee5fc4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 86, "max_stars_repo_stars_event_min_datetime": "2015-12-17T12:57:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T01:53:47.000Z", "max_issues_repo_path": "exer/parabola_sin.py", "max_issues_repo_name": "mbarzegary/finite-element-intro", "max_issues_repo_head_hexsha": "47ef0a3592b823ae71a874ee35850114f16b6d8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-04-16T21:57:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-17T08:09:30.000Z", "max_forks_repo_path": "doc/.src/book/exer/parabola_sin.py", "max_forks_repo_name": "hplgit/fem-book", "max_forks_repo_head_hexsha": "c23099715dc3cb72e7f4d37625e6f9614ee5fc4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2016-03-11T19:33:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T00:21:57.000Z", "avg_line_length": 25.4264705882, "max_line_length": 60, "alphanum_fraction": 0.6223250434, "include": true, "reason": "import numpy,import sympy", "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.9184802406781396, "lm_q1q2_score": 0.869430337470583}}
{"text": "import numpy as np\n\n# Write a function that takes as input a list of numbers, and returns\n# the list of values given by the softmax function.\ndef softmax(L):\n    expL = np.exp(L)\n    return np.divide (expL, expL.sum())", "meta": {"hexsha": "6b007f738dce4c7fb26dcfc214f27e6aa09e1b50", "size": 218, "ext": "py", "lang": "Python", "max_stars_repo_path": "18-11-22-Deep-Learning-with-PyTorch/01-Introduction to neural networks/04-Softmax/softmax.py", "max_stars_repo_name": "arcyfelix/Courses", "max_stars_repo_head_hexsha": "fa1336ff2295e67e03a116bba3c4fd5df653325c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2017-09-19T08:09:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-29T00:37:51.000Z", "max_issues_repo_path": "18-11-22-Deep-Learning-with-PyTorch/01-Introduction to neural networks/04-Softmax/softmax.py", "max_issues_repo_name": "arcyfelix/Courses", "max_issues_repo_head_hexsha": "fa1336ff2295e67e03a116bba3c4fd5df653325c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "18-11-22-Deep-Learning-with-PyTorch/01-Introduction to neural networks/04-Softmax/softmax.py", "max_forks_repo_name": "arcyfelix/Courses", "max_forks_repo_head_hexsha": "fa1336ff2295e67e03a116bba3c4fd5df653325c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2018-02-27T03:15:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-24T09:26:46.000Z", "avg_line_length": 31.1428571429, "max_line_length": 69, "alphanum_fraction": 0.7110091743, "include": true, "reason": "import numpy", "num_tokens": 56, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407168145568, "lm_q2_score": 0.8933094074745445, "lm_q1q2_score": 0.8694050880677127}}
{"text": "########################################################################################################################\r\n# BUILDING LINEAR REGRESSION FROM SCRATCH\r\n# ...WE ARE GOING TO GET IT WITH THE MAIN + HELPER FUNCTIONS METHOD...\r\n# ...WE ARE GOING TO MINIMIZE THE MEAN SQUARED ERROR (ORDINARY LEAST SQUQARES): THIS IS OUR LOSS FUNCTION...\r\n# ...WITH GRADIENT DESCENT WE MINIMIZE THE ERROR OVER DIFFERENT ITERATIONS...\r\n########################################################################################################################\r\n\r\n\r\nfrom sklearn.linear_model import LinearRegression\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\nimport random\r\nimport os\r\n\r\n\r\n#dataset = pd.read_csv(os.getcwd() + '/Codes/linear_regression_dataset.csv', sep = ',')\r\n#dataset = dataset[['Head_Size', 'Brain_Weight']]\r\n\r\n\r\ndef initialize_params(dimensions):\r\n\r\n    beta_0     = 0\r\n    beta_other = [random.random() for _ in range(dimensions)]\r\n\r\n    return beta_0, beta_other\r\n\r\n\r\ndef compute_gradient(x, y, beta_0, beta_other, dimensions, m):\r\n\r\n    gradient_beta_0     = 0\r\n    gradient_beta_other = [0] * dimensions\r\n\r\n    for i in range(m):\r\n        y_i_hat   = sum( [x[i][j] * beta_other[j] for j in range(dimensions)] ) + beta_0\r\n        derror_dy = 2 * (y[i] - y_i_hat)\r\n\r\n        for j in range(dimensions):\r\n            gradient_beta_other[j] += (derror_dy * x[i][j]) / m\r\n        gradient_beta_0 += derror_dy / m\r\n\r\n    return gradient_beta_0, gradient_beta_other\r\n\r\n\r\ndef update_params(beta_0, beta_other, gradient_beta_0, gradient_beta_other, learning_rate):\r\n\r\n    beta_0 += gradient_beta_0 * learning_rate\r\n    for i in range(len(beta_other)):\r\n        beta_other[i] += gradient_beta_other[i] * learning_rate\r\n\r\n    return beta_0, beta_other\r\n\r\n\r\ndef linear_regression(x, y, epochs=750, learning_rate=0.00000000045):\r\n\r\n    n, m = len(x[0]), len(x)\r\n    beta_0, beta_other = initialize_params(n)\r\n\r\n    for _ in range(epochs):\r\n        gradient_beta_0, gradient_beta_other = compute_gradient(x, y, beta_0, beta_other, n, m)\r\n        beta_0, beta_other = update_params(beta_0, beta_other, gradient_beta_0, gradient_beta_other, learning_rate)\r\n\r\n    return beta_0, beta_other\r\n\r\n\r\n#coeff = linear_regression(x = dataset[['Head_Size']].values, y = dataset[['Brain_Weight']].values )\r\n#print(coeff)\r\n\r\n\r\n#reg = LinearRegression().fit( dataset[['Head_Size']].values, dataset[['Brain_Weight']].values )\r\n#print(reg.coef_, reg.intercept_)\r\n\r\n\r\n########################################################################################################################\r\n# PLOTTING...\r\n\r\n#plt.scatter(dataset.Head_Size, dataset.Brain_Weight, edgecolors='black', label='Data Points')\r\n#plt.xlabel('Head Size')\r\n#plt.ylabel('Brain Weight')\r\n\r\n#all_x = np.linspace(dataset[['Head_Size']].min(), dataset[['Head_Size']].max(), 2000)\r\n#plt.plot(all_x, coeff[0] + coeff[1] * all_x, color='red', lw=2, label='Gradient Regression')\r\n#plt.plot(all_x, reg.intercept_ + reg.coef_ * all_x, color='green', lw=2, label='Sklearn Regression')\r\n\r\n#plt.legend(loc='best')\r\n#plt.show()", "meta": {"hexsha": "f5f73c6ce7413a60983ae90ffbe9c5763530c894", "size": 3095, "ext": "py", "lang": "Python", "max_stars_repo_path": "DSToolkit/machine_learning/linear_regression.py", "max_stars_repo_name": "AndreaFerrante/DSToolkit", "max_stars_repo_head_hexsha": "6f527cb4c19127cecd74bb682330236aa4e41839", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DSToolkit/machine_learning/linear_regression.py", "max_issues_repo_name": "AndreaFerrante/DSToolkit", "max_issues_repo_head_hexsha": "6f527cb4c19127cecd74bb682330236aa4e41839", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DSToolkit/machine_learning/linear_regression.py", "max_forks_repo_name": "AndreaFerrante/DSToolkit", "max_forks_repo_head_hexsha": "6f527cb4c19127cecd74bb682330236aa4e41839", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.988372093, "max_line_length": 121, "alphanum_fraction": 0.6003231018, "include": true, "reason": "import numpy", "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407144861112, "lm_q2_score": 0.8933094067644466, "lm_q1q2_score": 0.8694050852965941}}
{"text": "import numpy as np\n\ndef L2(v, *args):\n    \"\"\"Returns the L2 norm (weighted if weights specified) of a vector v.\n    \n    INPUTS\n    =======\n    v: list\n       Components of the vector v = [v1, v2, ..., vn]\n    *args: list, optional\n       Weights for each component of v\n    \n    RETURNS\n    ========\n    the L2 norm: float\n       Weighted L2 norm of the vector using the weight values specified by *args\n       A value exception is raised when the vector and the weights have different length\n\n    NOTES\n    =====\n    PRE: \n         - v is a list of numeric type values\n         - w is a list of numeric type values\n    POST:\n         - v and *args are not changed by this function\n         - raises a ValueError exception if the vector and the weights have different length\n         - returns weighted L2 norm of the vector\n\n    EXAMPLES\n    =========\n    >>> L2([4, 3], [1, 1])\n    5.0\n    >>> L2([40, 30], [1, 1])\n    50.0\n    \"\"\"\n    s = 0.0 # Initialize sum\n    if len(args) == 0: # No weight vector\n        for vi in v:\n            s += vi * vi\n    else: # Weight vector present\n        w = args[0] # Get the weight vector\n        if (len(w) != len(v)): # Check lengths of lists\n            raise ValueError(\"Length of list of weights must match length of target list.\")\n        for i, vi in enumerate(v):\n            s += w[i] * w[i] * vi * vi\n    return np.sqrt(s)", "meta": {"hexsha": "a61188ef71652d0d52f3aa78d3cb4a601da31a2d", "size": 1373, "ext": "py", "lang": "Python", "max_stars_repo_path": "lectures/L7/L2.py", "max_stars_repo_name": "JasmineeeeeTONG/CS207_coursework", "max_stars_repo_head_hexsha": "666239ee5f8bd7cbe04725a52870191a3d40d8c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lectures/L7/L2.py", "max_issues_repo_name": "JasmineeeeeTONG/CS207_coursework", "max_issues_repo_head_hexsha": "666239ee5f8bd7cbe04725a52870191a3d40d8c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lectures/L7/L2.py", "max_forks_repo_name": "JasmineeeeeTONG/CS207_coursework", "max_forks_repo_head_hexsha": "666239ee5f8bd7cbe04725a52870191a3d40d8c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.847826087, "max_line_length": 92, "alphanum_fraction": 0.5593590677, "include": true, "reason": "import numpy", "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914019704466, "lm_q2_score": 0.8991213840277783, "lm_q1q2_score": 0.869373071632542}}
{"text": "'''\r\nFor-loop method to search for the parameters\r\na and b of a straight line equation.\r\n'''\r\n#data points and constants:\r\nx = [3,4,5,6,7,8]\r\ny = [0,7,17,26,35,45]\r\nn = len(x)\r\n#initial value of summation variables:\r\nsumx = sumxy = sumx2 = sumy = 0 \r\nfor i in range(n):\r\n    sumx += x[i] \r\n    sumy += y[i]\r\n    sumx2 += x[i]**2\r\n    sumxy += x[i]*y[i]\r\nxm = sumx/n\r\nym = sumy/n\r\n#Calculates a and b:\r\na = (ym*sumx2 - xm*sumxy)/(sumx2 - n*xm**2)\r\nb = (sumxy-xm*sumy)/(sumx2 - n*xm**2)\r\n#Results:\r\nprint('The straight line equation:')\r\nprint('y = (%.3f) + (%.3f)x' % (a,b))\r\n'''\r\nNumpy library based method to search for parameters\r\na and b of a straight line equation.\r\n'''\r\na = b = 0\r\n#import numpy as np\r\nfrom numpy import array, sum, mean\r\n#arrays and constants:\r\nx = array([3,4,5,6,7,8], float)\r\ny = array([0,7,17,26,35,45], float)\r\nn = len(x)\r\n#Calculates a and b parameters:\r\na = (mean(y)*sum(x**2) - mean(x)*sum(x*y))/(sum(x**2)-(n*mean(x)**2))\r\nb = (sum(x*y) - (mean(x)*sum(y)))/(sum(x**2) - (n*mean(x)**2))\r\n#Results:\r\nprint('The straight line equation:')\r\nprint('y = (%.3f) + (%.3f)x' % (a,b))\r\n\r\n", "meta": {"hexsha": "dede81c59fbf6021e5fbcb63af84e1cff4e04d5d", "size": 1107, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_regression_scripts.py", "max_stars_repo_name": "lucas-mascena/Numerical_Methods", "max_stars_repo_head_hexsha": "e17a8564ed96e2ed7826de21c8340b597047b750", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_regression_scripts.py", "max_issues_repo_name": "lucas-mascena/Numerical_Methods", "max_issues_repo_head_hexsha": "e17a8564ed96e2ed7826de21c8340b597047b750", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_regression_scripts.py", "max_forks_repo_name": "lucas-mascena/Numerical_Methods", "max_forks_repo_head_hexsha": "e17a8564ed96e2ed7826de21c8340b597047b750", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3571428571, "max_line_length": 70, "alphanum_fraction": 0.5736224029, "include": true, "reason": "import numpy,from numpy", "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140206578809, "lm_q2_score": 0.89912137659416, "lm_q1q2_score": 0.869373065302108}}
{"text": "#!/usr/bin/env python3\nimport scipy.integrate as spi\nimport numpy as np\nimport pylab as pl\nimport time\n\n### --- creates an instance of the city and the behaviour of the disease --- ###\nclass city_sir_model(object):\n    def __init__(self, name, population, density, latitude, longitude, end_time):\n        #General info on city\n        self.city_name = name\n        self.city_pop = population\n        self.city_dens = density\n        self.city_lat = latitude\n        self.city_long = longitude\n\n        #Info on ODE's\n        self.num_iterations = 0\n        self.beta = .8\n        self.gamma = 0.01\n        self.time_step = 0.1\n\n        #Initial and final time for simulation\n        self.global_time_infected = 0\n        self.end_time = end_time\n        \n        #Initial Conditions\n        self.susceptible_init = 1-1e-6\n        self.infected_init= 1e-6\n        self.recovered_init = 0\n        self.initial_conditions = (self.susceptible_init, self.infected_init, self.global_time_infected)\n\n        self.result = []\n        self.infected = False\n\n    def infect(self, time):\n        self.global_time_infected = time\n        self.num_iterations = int(10*(self.end_time - self.global_time_infected))\n        self.infected = True\n        self.run_eqs()\n\n    def run_eqs(self):\n        t_start = self.global_time_infected;\n        t_end = self.end_time\n        t_inc = self.time_step\n        t_range = np.arange(t_start, t_end, t_inc)\n        self.result = spi.odeint(self.diff_eqs, self.initial_conditions , t_range)\n        # for result in self.result:\n        #     print(result)\n\n    def diff_eqs(self,INP,t):\n    \tequation_list=np.zeros((3))\n    \tinitial_conditions = INP\n    \tequation_list[0] = - self.beta * initial_conditions[0] * initial_conditions[1]\n    \tequation_list[1] = self.beta * initial_conditions[0] * initial_conditions[1] - self.gamma * initial_conditions[1]\n    \tequation_list[2] = self.gamma * initial_conditions[1]\n    \treturn equation_list   # For odeint\n\n    def plot(self):\n        pl.subplot(211)\n        pl.plot(self.result[:,0], '-g', label='Susceptibles')\n        pl.plot(self.result[:,2], '-k', label='Recovereds')\n        pl.legend(loc=0)\n        pl.title('Program_2_1.py')\n        pl.xlabel('Time')\n        pl.ylabel('Susceptibles atime_end Recovereds')\n        pl.subplot(212)\n        pl.plot(self.result[:,1], '-r', label='Infectious')\n        pl.xlabel('Time')\n        pl.ylabel('Infectious')\n        pl.show()\n\ndef main():\n    sample_model = city_sir_model(\"ny\",1000000,10000,1,1,200)\n    print(sample_model.start_time)\n\n    sample_model.run_eqs()\n    print(sample_model.get_city_data())\n    # print(sample_model.result)\n\n    print(sample_model.result)\n        # time.sleep(1)?\n    # sample_model.plot()\n\n    # t_start = 0.0; t_end = 70; t_inc = sample_model.time_step\n    # t_range = np.arange(t_start, t_end+t_inc, t_inc)\n    # print(t_range)\n\n\n\nif(__name__ == '__main__'):\n    main()\n", "meta": {"hexsha": "1434d09d87b3ad8a857cecdc6c19dd4bd8d905b8", "size": 2923, "ext": "py", "lang": "Python", "max_stars_repo_path": "sir_model.py", "max_stars_repo_name": "kylebarron/epidemic-visualization", "max_stars_repo_head_hexsha": "add44da7238070e166f11db2813cdf2080b7a28b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sir_model.py", "max_issues_repo_name": "kylebarron/epidemic-visualization", "max_issues_repo_head_hexsha": "add44da7238070e166f11db2813cdf2080b7a28b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sir_model.py", "max_forks_repo_name": "kylebarron/epidemic-visualization", "max_forks_repo_head_hexsha": "add44da7238070e166f11db2813cdf2080b7a28b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4301075269, "max_line_length": 118, "alphanum_fraction": 0.6335956209, "include": true, "reason": "import numpy,import scipy", "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811641488383, "lm_q2_score": 0.9005297841157157, "lm_q1q2_score": 0.8693544913403317}}
{"text": "## 1. Introduction ##\n\nmean_new = houses_per_year['Mean Price'].mean()\n\nprint(mean_new)\n\nmean_original = houses['SalePrice'].mean()\nprint(mean_original)\n\ndifference =  mean_original - mean_new\nprint(difference)\n\n## 2. Different Weights ##\n\nhouses_per_year['sum_per_year'] = houses_per_year['Mean Price'] * houses_per_year['Houses Sold']\nall_sums_together = houses_per_year['sum_per_year'].sum()\ntotal_n_houses = houses_per_year['Houses Sold'].sum()\nweighted_mean = all_sums_together / total_n_houses\n\nmean_original = houses['SalePrice'].mean()\n\ndifference = round(mean_original, 10) - round(weighted_mean, 10)\n\nprint(difference)\n\n## 3. The Weighted Mean ##\n\ndef weighted_mean(distribution, weights):\n    weighted_sum = []\n    for mean, weight in zip(distribution, weights):\n        weighted_sum.append(mean * weight)\n        \n    return sum(weighted_sum) /  sum(weights)\n\n\nweighted_mean_function = weighted_mean(houses_per_year['Mean Price'],houses_per_year['Houses Sold'])\nprint(weighted_mean_function)\n\nfrom numpy import average\n\nweighted_mean_numpy = average(houses_per_year['Mean Price'],weights = houses_per_year['Houses Sold'])\n\nprint(weighted_mean_numpy)\n\nequal =  round(weighted_mean_function, 10) == round(weighted_mean_numpy, 10)\n\n    \n\n## 4. The Median for Open-ended Distributions ##\n\ndistribution1 = [23, 24, 22, '20 years or lower,', 23, 42, 35]\ndistribution2 = [55, 38, 123, 40, 71]\ndistribution3 = [45, 22, 7, '5 books or lower', 32, 65, '100 books or more']\n\nmedian1 = 23\nmedian2 = 55\nmedian3 = 32\n\n## 5. Distributions with Even Number of Values ##\n\nrooms =  houses['TotRms AbvGrd'].copy()\nrooms = rooms.replace({'10 or more':10})\nrooms = rooms.astype(int)\n\nrooms_sorted =  rooms.sort_values()\n\n# Find the median\nmiddle_indices = [int((len(rooms_sorted) / 2) - 1),\n                  int((len(rooms_sorted) / 2))\n                 ] # len - 1 and len because Series use 0-indexing \nmiddle_values = rooms_sorted.iloc[middle_indices] # make sure you don't use loc[]\nmedian = middle_values.mean()\n\n## 6. The Median as a Resistant Statistic ##\n\nlotarea_median =  houses['Lot Area'].median()\nSalePrice_median =  houses['SalePrice'].median()\nLotarea_mean = houses['Lot Area'].mean()\nSalePrice_mean = houses['SalePrice'].mean()\n\nlotarea_difference = Lotarea_mean - lotarea_median\nsaleprice_difference = SalePrice_mean - SalePrice_median\n\nprint(lotarea_difference)\nprint(saleprice_difference)\n\n## 7. The Median for Ordinal Scales ##\n\nmean =  houses['Overall Cond'].mean()\n\nmedian =  houses['Overall Cond'].median()\n\nhouses['Overall Cond'].plot.hist()\nmore_representative = 'mean' \n\n'''\nThe mean seems more representative and more informative because it captures the\nfact that there are more houses rated above 5 than rated under 5. Because of this,\nthe mean is slightly shifted above 5. \n'''", "meta": {"hexsha": "291eee20c707b98abb82b6bcefb55647ff939516", "size": 2798, "ext": "py", "lang": "Python", "max_stars_repo_path": "5. Probability and Statistics/statistics-intermediate/The Weighted Mean and the Median-306.py", "max_stars_repo_name": "bibekuchiha/dataquest", "max_stars_repo_head_hexsha": "c7d8a2966fe2eee864442a59d64309033ea9993e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5. Probability and Statistics/statistics-intermediate/The Weighted Mean and the Median-306.py", "max_issues_repo_name": "bibekuchiha/dataquest", "max_issues_repo_head_hexsha": "c7d8a2966fe2eee864442a59d64309033ea9993e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5. Probability and Statistics/statistics-intermediate/The Weighted Mean and the Median-306.py", "max_forks_repo_name": "bibekuchiha/dataquest", "max_forks_repo_head_hexsha": "c7d8a2966fe2eee864442a59d64309033ea9993e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.98, "max_line_length": 101, "alphanum_fraction": 0.7269478199, "include": true, "reason": "from numpy", "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517095103498, "lm_q2_score": 0.9046505408849362, "lm_q1q2_score": 0.869325483772842}}
{"text": "import numpy as np\r\n\r\ndef RSE(pred, true):\r\n    return np.sqrt(np.sum((true-pred)**2)) / np.sqrt(np.sum((true-true.mean())**2))\r\n\r\ndef CORR(pred, true):\r\n    u = ((true-true.mean(0))*(pred-pred.mean(0))).sum(0) \r\n    d = np.sqrt(((true-true.mean(0))**2*(pred-pred.mean(0))**2).sum(0))\r\n    return (u/d).mean(-1)\r\n\r\ndef MAE(pred, true):\r\n    return np.mean(np.abs(pred-true))\r\n\r\ndef MSE(pred, true):\r\n    return np.mean((pred-true)**2)\r\n\r\ndef RMSE(pred, true):\r\n    return np.sqrt(MSE(pred, true))\r\n\r\ndef MAPE(pred, true):\r\n    return np.mean(np.abs((pred - true) / true))\r\n\r\ndef MSPE(pred, true):\r\n    return np.mean(np.square((pred - true) / true))\r\n\r\ndef metric(pred, true):\r\n    mae = MAE(pred, true)\r\n    mse = MSE(pred, true)\r\n    rmse = RMSE(pred, true)\r\n    mape = MAPE(pred, true)\r\n    mspe = MSPE(pred, true)\r\n    \r\n    return mae,mse,rmse,mape,mspe", "meta": {"hexsha": "73e9634f6182ec563620213365acebcf2e5d719d", "size": 858, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/metrics.py", "max_stars_repo_name": "wxh453751461/Gformer", "max_stars_repo_head_hexsha": "a033eb6fce59ceacc61a76430010805023ac230f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/metrics.py", "max_issues_repo_name": "wxh453751461/Gformer", "max_issues_repo_head_hexsha": "a033eb6fce59ceacc61a76430010805023ac230f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/metrics.py", "max_forks_repo_name": "wxh453751461/Gformer", "max_forks_repo_head_hexsha": "a033eb6fce59ceacc61a76430010805023ac230f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0, "max_line_length": 84, "alphanum_fraction": 0.5792540793, "include": true, "reason": "import numpy", "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. Yes\n2. Yes", "lm_q1_score": 0.9637799482964025, "lm_q2_score": 0.901920685097536, "lm_q1q2_score": 0.8692530712507591}}
{"text": "import numpy as np\nfrom numpy.linalg import inv\n\n\ndef covariance(X, Y, show_steps=False):\n    X = np.array(X)\n    Y = np.array(Y)\n    show_steps\n\n    if len(X) != len(Y):\n        raise ValueError(\"Both lists must have same number of values\")\n\n    N = len(X)\n\n    x_mean = np.average(X)\n    y_mean = np.average(Y)\n\n    s_xy = np.sum((X - x_mean) * (Y - y_mean)) / (N - 1)\n\n    s_x = np.sqrt((np.sum(np.square(X)) - N * (x_mean ** 2)) / (N - 1))\n    s_y = np.sqrt((np.sum(np.square(Y)) - N * (y_mean ** 2)) / (N - 1))\n\n    r_xy = s_xy / (s_x * s_y)\n\n    print(\"Covariance: \", \"{:.4f}\".format(s_xy))\n    print(\"Correlation coefficient: \", \"{:.4f}\".format(r_xy))\n\n\ndef covariance_matrix(data, show_steps=False):\n\n    data = np.transpose(np.array(data))\n    f = data.shape[1]\n    N = data.shape[0]\n    S = (data.T @ (np.identity(N) - np.ones(N) / N) @ data) / (N - 1)\n\n    print(\"Mean vector: \")\n    print(np.average(data, axis=0))\n    print(\"Covariance Matrix: \")\n    print(S)\n\n    Ds = np.identity(f)\n    Ds[np.diag_indices(f)] = np.sqrt(np.diagonal(S))\n\n    print(\"Ds: \")\n    print(Ds)\n\n    R = inv(Ds) @ S @ inv(Ds)\n\n    print(\"Correlation Matrix: \")\n    print(R)\n", "meta": {"hexsha": "5009f0e94b6545931fc96d93daf6c53c8b22a70c", "size": 1163, "ext": "py", "lang": "Python", "max_stars_repo_path": "doex/covariance.py", "max_stars_repo_name": "rohitsanj/doe", "max_stars_repo_head_hexsha": "d1fe3629dfe3fb789dfe42b072c2682581a9ae90", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-10-15T12:11:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T06:45:36.000Z", "max_issues_repo_path": "doex/covariance.py", "max_issues_repo_name": "rohitsanj/doe", "max_issues_repo_head_hexsha": "d1fe3629dfe3fb789dfe42b072c2682581a9ae90", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2020-10-15T12:39:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-03T17:37:09.000Z", "max_forks_repo_path": "doex/covariance.py", "max_forks_repo_name": "rohitsanj/doe", "max_forks_repo_head_hexsha": "d1fe3629dfe3fb789dfe42b072c2682581a9ae90", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-15T13:31:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-15T13:31:23.000Z", "avg_line_length": 22.8039215686, "max_line_length": 71, "alphanum_fraction": 0.5580395529, "include": true, "reason": "import numpy,from numpy", "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517482043892, "lm_q2_score": 0.8887587890727754, "lm_q1q2_score": 0.869252087384644}}
{"text": "import numpy as np\nfrom math import isnan, isinf\nfrom scipy.interpolate import splev\nfrom matplotlib import pyplot as plt\n\n# Recursive De Boor algorithm problem.\ndef N(x, i, k, t):\n    \"\"\" Computes the i'th basis function of order 'k'\n    for the spline with knot vector 't' at the parameter value 'x'.\"\"\"\n    # This recursion involves a lot\n    # of redundant calculation.\n    # This is not the way this algorithm\n    # should be implemented in real world\n    # applications, but it is instructive.\n    # Do k=0 case.\n    if k <= 0:\n        if t[i] <= x < t[i+1]:\n            return 1.\n        else:\n            return 0.\n    # Use recursion for other cases.\n    else:\n        # Compute left and right hand sides.\n        left = (x - t[i]) / (t[i+k] - t[i])\n        right = (t[i+k+1] - x) / (t[i+k+1] - t[i+1])\n        # Account for nan and inf values.\n        if isnan(left) or isinf(left):\n            left = 0.\n        if isnan(right) or isinf(right):\n            right = 0.\n        # Perform the recursive call.\n        # It could be good to avoid calling\n        # recursively for terms we already know\n        # will be zero, but this matches\n        # more closely with the formula\n        # as it is usually written.\n        return left * N(x, i, k-1, t) + right * N(x, i+1, k-1, t)\n\ndef circle_interp(m, k, res=401):\n    \"\"\" Plots an interpolating spline of degree 'k'\n    with parameters ranging from 0 to 'm'\n    that approximates the unit circle.\n    Uses scipy.integrate.splev.\"\"\"\n    # Make the knot vector.\n    t = np.array([0]*(k) + range(m) + [m]*(k+1))\n    # Preallocate the array 'c' of control points.\n    c = np.empty((2, m + k + 1))\n    c[:,-1] = 0.\n    # Construct the circle.\n    # Use n + k control points.\n    theta = np.linspace(0, 2 * np.pi, m + k)\n    np.cos(theta, out=c[0,:-1])\n    np.sin(theta, out=c[1,:-1])\n    # Generate the sample values to use for plotting.\n    X = np.linspace(0, m, res)\n    # Evaluate the B-spline at the given points.\n    pts = splev(X, (t, c, k))\n    # Plot the B-spline and its control points.\n    plt.plot(pts[0], pts[1])\n    plt.scatter(c[0], c[1])\n    plt.show()\n\ndef my_circle_interp(m, k, res=401):\n    \"\"\" Plots an interpolating spline of degree 'k'\n    with parameters ranging from 0 to 'm'\n    that approximates the unit circle.\n    Uses the function 'N' defined above.\"\"\"\n    # Make the knot vector.\n    t = np.array([0]*(k) + range(m) + [m]*(k+1))\n    # Preallocate the array 'c' of control points.\n    c = np.empty((2, m + k))\n    # Construct the circle.\n    # Use n + k control points.\n    theta = np.linspace(0, 2 * np.pi, m + k)\n    np.cos(theta, out=c[0])\n    np.sin(theta, out=c[1])\n    # Generate the sample vaues to use for plotting.\n    # Offset just a little to not get to the end of the interval.\n    # This makes the plots look identical instead of just similar.\n    X = np.linspace(0, m - 1E-10, res)\n    # Find the values of each basis function\n    Ni = np.array([[N(x, i, k, t) for x in X] for i in xrange(m + k)])\n    # Use the points to evaluate the spline, using the basis functions.\n    pts = Ni.T.dot(c.T).T\n    # Plot the B-spline and its control points.\n    plt.plot(pts[0], pts[1])\n    plt.scatter(c[0], c[1])\n    plt.show()\n\nif __name__==\"__main__\":\n    circle_interp(20, 4)\n    my_circle_interp(20, 4)\n", "meta": {"hexsha": "8563800e4841c5edb16e86588f4a8d91879641de", "size": 3297, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/BSplines/bsplines_solutions.py", "max_stars_repo_name": "jessicaleete/numerical_computing", "max_stars_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-10-18T19:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:12:38.000Z", "max_issues_repo_path": "Labs/BSplines/bsplines_solutions.py", "max_issues_repo_name": "jessicaleete/numerical_computing", "max_issues_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/BSplines/bsplines_solutions.py", "max_forks_repo_name": "jessicaleete/numerical_computing", "max_forks_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-14T16:07:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-20T09:05:06.000Z", "avg_line_length": 35.4516129032, "max_line_length": 71, "alphanum_fraction": 0.593266606, "include": true, "reason": "import numpy,from scipy", "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182845, "lm_q2_score": 0.9111797166446537, "lm_q1q2_score": 0.8692345608855018}}
{"text": "# This script will look for prime numbers\n\n# Software\n    # Mu IDE v 1.0.3\n\n# Engineering\n    # 3Blue1Brown, Grant Sanderson\n    # Stack overflow, https://stackoverflow.com \n    # ATS, May 2022\n\nimport numpy as np\nimport math\nimport time\nimport sys\n\ndef get_seriesRange():\n    \"\"\"Queries user for series parameters and finds associated prime numbers\"\"\"\n\n    print(\"A prime number can only be factored by 1 and itself\")\n    print(\"Remember that a factor is defined as a number that divides another number and leaves no remainder \\n\")\n    print(\"\\nThis script will find the prime numbers within a range of numbers that you provide\")\n\n    n_min = int(input(\"\\nPlease enter a number for the low end of your search range \\n\"))\n    n_max = int(input(\"\\nPlease enter a number for the high end of your search range \\n\"))\n\n    result = []\n    for x in range(max(n_min, 2), n_max):\n        has_factor = False\n        for p in range(2, int(np.sqrt(x)) + 1):\n            if x % p == 0:\n                has_factor = True\n                break\n        if not has_factor:\n            result.append(x)\n    #return result\n    print(\"You are searching a range of numbers from \" + str(n_min) + \" to \" + str(n_max))\n    print(\"There are \" + str(len(result)) + \" prime numbers in your search range\")\n    print(result)\n\ndef rerunScript():\n    \"\"\"Queries the user for a rerun or stop script decision\"\"\"\n    \n    query = input(\"\\nWould you like to run the script again? (if so, type yes) \\n\")\n    #if query == 'yes':   \n    if query.lower() == 'yes': \n        print(\"\\nRunning the script again \\n\")\n        get_seriesRange()\n    else:\n    #elif query.lower().startswith(\"n\"):\n        print(\"\\nOk, see ya \\n\")\n        #exit()\n        sys.exit()\n        #sys.quit()\n        #quit()        \n\nif __name__ == \"__main__\":\n    \"\"\"Conditional statement for running the script\"\"\"\n    \n    start_time = time.time()\n    get_seriesRange()\n    end_time = time.time()\n    duration = end_time - start_time\n    print(\"\\nRuntime for this script was {} units of time (milliseconds?).\".format(duration))\n    \n    while True:\n        start_time = time.time()\n        rerunScript()\n        end_time = time.time()\n        duration = end_time - start_time\n        print(\"\\nRuntime for this script was {} units of time (milliseconds?).\".format(duration))\n", "meta": {"hexsha": "2fda60ea5a32078fee8229aeab42bea10c790c98", "size": 2307, "ext": "py", "lang": "Python", "max_stars_repo_path": "GetPrimes.py", "max_stars_repo_name": "AnchorageBot/GardenBot2", "max_stars_repo_head_hexsha": "9562d408ade5cb2b8353c5bec1c33ae16596f087", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GetPrimes.py", "max_issues_repo_name": "AnchorageBot/GardenBot2", "max_issues_repo_head_hexsha": "9562d408ade5cb2b8353c5bec1c33ae16596f087", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GetPrimes.py", "max_forks_repo_name": "AnchorageBot/GardenBot2", "max_forks_repo_head_hexsha": "9562d408ade5cb2b8353c5bec1c33ae16596f087", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4929577465, "max_line_length": 113, "alphanum_fraction": 0.6185522323, "include": true, "reason": "import numpy", "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007596, "lm_q2_score": 0.9111797166446537, "lm_q1q2_score": 0.8692345585004662}}
{"text": "\nfrom math import sqrt, pi\n\nimport numpy as np\nfrom scipy.special import hermite\nfrom scipy.integrate import dblquad\n\nfrom ..utils import InvalidMatrix\n\n\ndef disentangled_gaussian_wavefcn():\n    \"\"\" Return the function of normalized disentangled Gaussian systems.\n\n    :return: function of two variables\n    :rtype: function\n    \"\"\"\n    return lambda x1, x2: np.exp(-0.5 * (x1 * x1 + x2 * x2)) / np.sqrt(np.pi)\n\n\ndef correlated_bipartite_gaussian_wavefcn(covmatrix):\n    \"\"\" Return a normalized correlated bivariate Gaussian wavefunction.\n\n    :param covmatrix: covariance matrix of size (2, 2)\n    :return: a wavefunction of two variables\n    :type covmatrix: numpy.array\n    :rtype: function\n    \"\"\"\n    if not covmatrix.shape == (2, 2):\n        raise InvalidMatrix(\"Invalid matrix shape: \"+str(covmatrix.shape)+\"; desired shape: (2, 2)\")\n    if covmatrix[0, 1] != covmatrix[1, 0]:\n        raise InvalidMatrix(\"Not a symmetric covariance matrix\")\n\n    norm = 2 * np.pi / np.sqrt(np.linalg.det(covmatrix))\n    const = 1 / np.sqrt(norm)\n    return lambda x1, x2: const * np.exp(-0.25* np.matmul(np.array([[x1, x2]]),\n                                                          np.matmul(covmatrix,\n                                                                    np.array([[x1], [x2]])\n                                                                    )\n                                                          )\n                                         )\n\n\ndef tail_factorial(n, accumulator=1):\n    \"\"\" Returns the factorial of an integer.\n\n    The calculation is done by tail recursion.\n\n    :param n: the integer of which the factorial is desired to return\n    :param accumulator: default to be 1, for tail recursion.\n    :return: factorial of `n`\n    :type n: int\n    :type accumulator: int\n    :rtype: int\n    \"\"\"\n    if n == 0:\n        return accumulator\n    else:\n        return tail_factorial(n-1, accumulator * n)\n\n\n# m = omega = hbar = 1\ndef harmonic_wavefcn(n):\n    \"\"\" Return the normalized wavefunction of a harmonic oscillator, where $n$ denotes\n    that it is an n-th excited state, or ground state for $n=0$.\n\n    :param n: quantum number of the excited state\n    :return: a normalized wavefunction\n    :type n: int\n    :rtype: function\n    \"\"\"\n    const = 1/sqrt(2**n * tail_factorial(n)) * 1/sqrt(sqrt(pi))\n    return lambda x: const * np.exp(-0.5*x*x) * hermite(n)(x)\n\n\n# excited interaction states\ndef coupled_excited_harmonics(n):\n    \"\"\" Return a bipartitite wavefunction, with ground state of center of mass,\n    but excited state for the interaction.\n\n    :param n: quantum harmonic state number for the interaction\n    :return: wavefunction of two variables\n    :type n: int\n    :rtype: function\n    \"\"\"\n    return lambda x1, x2: harmonic_wavefcn(0)(0.5*(x1+x2)) * harmonic_wavefcn(n)(x1-x2)\n\n\n# tutorial on double integration: https://docs.scipy.org/doc/scipy/reference/tutorial/integrate.html#general-multiple-integration-dblquad-tplquad-nquad\n", "meta": {"hexsha": "34cf812284f04248ee7703314120220f6ad4048b", "size": 2975, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyqentangle/quantumstates/harmonics.py", "max_stars_repo_name": "stephenhky/PyQEntangle", "max_stars_repo_head_hexsha": "f06b63ac89952c1878555af0f2b4f079d11237d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2017-05-25T17:09:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T14:36:15.000Z", "max_issues_repo_path": "pyqentangle/quantumstates/harmonics.py", "max_issues_repo_name": "stephenhky/PyQEntangle", "max_issues_repo_head_hexsha": "f06b63ac89952c1878555af0f2b4f079d11237d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-04-07T04:52:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-05T04:27:55.000Z", "max_forks_repo_path": "pyqentangle/quantumstates/harmonics.py", "max_forks_repo_name": "stephenhky/PyQEntangle", "max_forks_repo_head_hexsha": "f06b63ac89952c1878555af0f2b4f079d11237d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-03-12T03:45:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-25T18:56:04.000Z", "avg_line_length": 33.4269662921, "max_line_length": 151, "alphanum_fraction": 0.6134453782, "include": true, "reason": "import numpy,from scipy", "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9763105300791783, "lm_q2_score": 0.8902942144788076, "lm_q1q2_score": 0.8692036164642304}}
{"text": "\n# MSDS 400 Module 6 Practice 2\n\nimport matplotlib.pyplot as plt\nfrom numpy import poly1d, linspace\n\n'''\nThe first example shows how to generate and print a second degree\npolynomial with coefficients, 1, -2 and 4.  The software is not limited\nto second degree polynomials.  Higher order can be generated.  The critical\nthing is to have all the coefficients in the right sequence.\n'''\np = poly1d([5, -3, 2])\nprint('Second Degree Polynomial')\nprint(p)\n\n# Now a fourth degree polynomial will be generated and printed.\n\nq = poly1d([2, 1, 4, -2, 3])\nprint('\\nFourth Degree Polynomial')\nprint(q)\n\n# It is possible to combine p and q algebraically.\n\nprint('\\nCombination')\ng = p + p*q\nprint(g)\n\n# Derivatives of different orders may be calculated.  This next section will\n# show determination of the first and second derivatives of p.\n\nprint('\\nFirst Derivative')\nh = p.deriv(m=1)  # First derivative with m=1.\nprint(h)\nprint(h.roots)\n\nprint('\\nSecond Derivative')\nt = p.deriv(m=2)  # Second derivative with m=2.\nprint(t)\nprint(t.roots)\n\n'''\nUsing t, the original function p can be restored if the missing\ncoefficients -2 and 4 are supplied.  Different coefficients would result\nin a different function instead of the original p.\n'''\nprint('\\nIntegrated Derivative')\nw = t.integ(m=2, k=[-3, 2])\nprint(w)\nprint(w.coeffs)\n\nprint('\\nrandom stuff below')\nnew = t.integ(m=2, k=[-2, 4])\nprint(new)\nprint(new.deriv(m=1))\n\n# Roots may also be found.  This is useful when locating the maxima, minima\n# and inflection points of a function from the first and second derivatives.\n\nprint('\\nRoots of polynomial')\nprint(w.roots)\n\n'''\nPlotting requires defining a domain for the polynomial.  The linspace\nfunction is used to set boundaries and define the number of points\nused for calculation. A new polynomial p will be defined.\n'''\np = poly1d([.3333, 0, -1, 5])\n\n# As a final example, we will find the first and second derivatives of the\n# polynomial p, find the roots of the derivatives and plot the functions.\n\ng = p.deriv(m=1)\n\nprint('\\nRoots of First Derivative')\nprint(g.roots)\n\nprint('\\nRoots of Second Derivative')\nq = p.deriv(m=2)\nprint(q.roots)\n\nx = linspace(-4, 4, 101)\ny = p(x)\nyg = g(x)  # These statements define points for plotting.\nyq = q(x)\ny0 = 0*x   # This statement defines the y axis for plotting.\n\n# What is shown below is a different way to legends using a label.  Python\n# will pick the colors to assign to the labels and the plotted points.\n\nplt.plot(x, y, label='y=p(x)')\nplt.plot(x, yg, label='First Derivative')\nplt.plot(x, yq, label='Second Derivative')\nplt.legend(loc='best')\n\nplt.plot(x, y0)\nplt.xlabel('x-axis')\nplt.ylabel('y-axis')\nplt.title('Plot Showing Function, First and Second Derivatives')\nplt.show()\n\n# Exercise: Refer to Lial Section 14.1 Example 2.  Duplicate the results\n# showing plots of the function and derivatives.  Compare to the answer sheet.\n\nplt.figure()\np = poly1d([3, -4, -12, 0, 2])\nprint('\\nFourth Degree Polynomial')\nprint(p)\nprint('\\nFirst Derivative')\ng = p.deriv(m=1)  # First derivative with m=1.\nprint(g)\nprint('\\nSecond Derivative')\nq = p.deriv(m=2)  # Second derivative with m=2.\nprint(q)\nx = linspace(-2, 3, 101)\ny = p(x)\nyg = g(x)  # These statements define points for plotting.\nyq = q(x)\ny0 = 0*x  # This statement defines the y axis for plotting.\nplt.plot(x, y, label='y=p(x)')\nplt.plot(x, yg, label='First Derivative')\nplt.plot(x, yq, label='Second Derivative')\nplt.legend(loc='best')\n\nplt.plot(x, y0)\nplt.xlabel('x-axis')\nplt.ylabel('y-axis')\nplt.title('Plot Showing Function, First and Second Derivatives')\nplt.show()", "meta": {"hexsha": "066f3ad3f9c30a8968067a757e405bcecd53c382", "size": 3568, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Module 6/practice/practice_2.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Module 6/practice/practice_2.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Module 6/practice/practice_2.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6589147287, "max_line_length": 78, "alphanum_fraction": 0.7166479821, "include": true, "reason": "from numpy", "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854146791213, "lm_q2_score": 0.8962513800615313, "lm_q1q2_score": 0.8691715162697068}}
{"text": "import numpy as np \nimport pandas as pd  \nfrom typing import Union\ndef unit_vector(azi:Union[int,float]) -> np.array:\n    \"\"\"\n    Get the unit vector2D of a given azimuth\n    Input:\n        azi -> (int,float) Azimuth in Degrees\n    Return:\n        u -> (np.ndarray) numpy array with a shape of (2,1) with the x and y components of unit vector\n    \"\"\"\n    assert isinstance(azi,(int,float,np.ndarray))\n    alpha = 90 - azi\n    alpha_rad = np.deg2rad(alpha)\n    x = np.cos(alpha_rad)\n    y = np.sin(alpha_rad)\n    p = np.array([[x,y]])\n    return p\n\ndef projection_1d(x, azi, center=None):\n    \"\"\"\n    Get the 1D projection of a series of 2D Coordinates within a given azimuth direction\n\n    Input:\n        x -> (np.ndarray) Numpy array of shape (m,2) being m the number of coordinates\n        azi -> (int,float) Azimuth in Degrees\n        center -(list,np.ndarray)  list or numpy array with the center \n    Return:\n        u -> (np.ndarray) numpy array with a shape of (m,1)\n    \"\"\"\n    assert isinstance(x,np.ndarray) and x.shape[1] == 2\n    assert isinstance(azi,(int,float,np.ndarray))\n    assert isinstance(center,(list,np.ndarray, type(None)))\n    \n    if isinstance(center,type(None)):\n        center = x.mean(axis=0)\n    else:\n        center = np.atleast_1d(center)\n        assert center.shape == (2,)\n    #Normalize the coordinates by substracting the average coordinates\n\n    x = x - center\n\n    # Get the unit vector\n    u = unit_vector(azi)\n\n    # Projection over the azimuth direction\n    cv = np.squeeze(np.dot(x,u.T))\n\n    return cv, center\n", "meta": {"hexsha": "d862b6fc6415a5d5c643adfdf5d04f8445949e82", "size": 1554, "ext": "py", "lang": "Python", "max_stars_repo_path": "reservoirpy/wellpy/path/projection.py", "max_stars_repo_name": "scuervo91/reservoirpy", "max_stars_repo_head_hexsha": "a4db620baf3ff66a85c7f61b1919713a8642e6fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-05-07T01:57:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T12:45:59.000Z", "max_issues_repo_path": "reservoirpy/wellpy/path/projection.py", "max_issues_repo_name": "scuervo91/reservoirpy", "max_issues_repo_head_hexsha": "a4db620baf3ff66a85c7f61b1919713a8642e6fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reservoirpy/wellpy/path/projection.py", "max_forks_repo_name": "scuervo91/reservoirpy", "max_forks_repo_head_hexsha": "a4db620baf3ff66a85c7f61b1919713a8642e6fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-12T07:28:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T21:24:59.000Z", "avg_line_length": 30.4705882353, "max_line_length": 102, "alphanum_fraction": 0.6357786358, "include": true, "reason": "import numpy", "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969785409439575, "lm_q2_score": 0.8962513765975758, "lm_q1q2_score": 0.8691715082144628}}
{"text": "import math\nimport numpy as np\nfrom core import StatisticsCalculator\n\n\nclass CorrelationCoefficient:\n    @staticmethod\n    def pearson(x, y):\n        n = x.__len__()\n        if n != y.__len__():\n            raise IndexError('The length of vector x and y are not equal.')\n        mean_x = StatisticsCalculator.mean(x)\n        mean_y = StatisticsCalculator.mean(y)\n        numerator_sum = 0\n        denominator_as_x_sum_temp = 0\n        denominator_as_y_sum_temp = 0\n        for i in range(0, n):\n            numerator_sum += ((x[i] - mean_x) * (y[i] - mean_y))\n            denominator_as_x_sum_temp += (x[i] - mean_x) ** 2\n            denominator_as_y_sum_temp += (y[i] - mean_y) ** 2\n        return numerator_sum / math.sqrt(denominator_as_x_sum_temp * denominator_as_y_sum_temp)\n\n    @staticmethod\n    def spearman_rank(x, y):\n        n = x.__len__()\n        if n != y.__len__():\n            raise IndexError('The length of vector x and y are not equal.')\n        op_x = np.array(x)\n        op_y = np.array(y)\n        sorted_x = np.sort(op_x)\n        sorted_y = np.sort(op_y)\n        r = np.zeros((n,), dtype=int)\n        s = np.zeros((n,), dtype=int)\n        for i in range(0, n):\n            for j in range(0, n):\n                if sorted_x[j] == op_x[i]:\n                    r[i] = j\n        for i in range(0, n):\n            for j in range(0, n):\n                if sorted_y[j] == op_y[i]:\n                    s[i] = j\n        d = np.zeros((n,), dtype=int)\n        for i in range(0, n):\n            d[i] = r[i] - s[i]\n        for i in range(0, n):\n            d[i] = d[i] ** 2\n        return 1 - ((6 * d.sum()) / (n * ((n ** 2) - 1)))\n\n    @staticmethod\n    def partial(x, y, z, kind='pearson'):\n        if kind == 'pearson':\n            rXY = CorrelationCoefficient.pearson(x, y)\n            rXZ = CorrelationCoefficient.pearson(x, z)\n            rYZ = CorrelationCoefficient.pearson(y, z)\n            rZY = CorrelationCoefficient.pearson(z, y)\n            rYX = CorrelationCoefficient.pearson(y, x)\n            rZX = CorrelationCoefficient.pearson(z, x)\n            return {\n                'XY.Z': ((rXY - (rXZ * rYZ)) / (math.sqrt((1 - rXZ ** 2) * (1 - rYZ ** 2)))),\n                'XZ.Y': ((rXZ - (rXY * rZY)) / (math.sqrt((1 - rXY ** 2) * (1 - rZY ** 2)))),\n                'YZ.X': ((rYZ - (rYX * rZX)) / (math.sqrt((1 - rYX ** 2) * (1 - rZX ** 2))))\n            }\n        if kind == 'spearman':\n            rXY = CorrelationCoefficient.spearman_rank(x, y)\n            rXZ = CorrelationCoefficient.spearman_rank(x, z)\n            rYZ = CorrelationCoefficient.spearman_rank(y, z)\n            rZY = CorrelationCoefficient.spearman_rank(z, y)\n            rYX = CorrelationCoefficient.spearman_rank(y, x)\n            rZX = CorrelationCoefficient.spearman_rank(z, x)\n            return {\n                'XY.Z': ((rXY - (rXZ * rYZ)) / (math.sqrt((1 - rXZ ** 2) * (1 - rYZ ** 2)))),\n                'XZ.Y': ((rXZ - (rXY * rZY)) / (math.sqrt((1 - rXY ** 2) * (1 - rZY ** 2)))),\n                'YZ.X': ((rYZ - (rYX * rZX)) / (math.sqrt((1 - rYX ** 2) * (1 - rZX ** 2))))\n            }\n        raise NameError(\"Undefined kind: \" + kind)\n", "meta": {"hexsha": "88d7b7894668cc55061487c5634209e9e43c0d03", "size": 3142, "ext": "py", "lang": "Python", "max_stars_repo_path": "core/correlation_coefficient/CorrelationCoefficient.py", "max_stars_repo_name": "Baha2rM98/iespy", "max_stars_repo_head_hexsha": "a7019f828fd29b64db4c576b6f6a05291d085b41", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/correlation_coefficient/CorrelationCoefficient.py", "max_issues_repo_name": "Baha2rM98/iespy", "max_issues_repo_head_hexsha": "a7019f828fd29b64db4c576b6f6a05291d085b41", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/correlation_coefficient/CorrelationCoefficient.py", "max_forks_repo_name": "Baha2rM98/iespy", "max_forks_repo_head_hexsha": "a7019f828fd29b64db4c576b6f6a05291d085b41", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3421052632, "max_line_length": 95, "alphanum_fraction": 0.5012730745, "include": true, "reason": "import numpy", "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9796676478446031, "lm_q2_score": 0.8872045832787204, "lm_q1q2_score": 0.8691656272576154}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n## Monte Carlo - Black-Scholes-Merton\n# *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).*\n# Download the data for Microsoft (‘MSFT’) from Yahoo Finance for the period ‘2000-1-1’ until today.\n# Download the data for Microsoft (‘MSFT’) from IEX for the period ‘2015-1-1’ until today.\n# We have written a few lines of code that will import the documents you need and define the functions estimating d1, d2, and the Black-Scholes-Merton formula. \nimport numpy as np\nimport pandas as pd\nfrom pandas_datareader import data as wb\nfrom scipy.stats import norm\nticker = 'MSFT'  \ndata = pd.DataFrame()  \ndata[ticker] = wb.DataReader(ticker, data_source='yahoo', start='2000-1-1')['Adj Close']\n# In[2]:\ndef d1(S, K, r, stdev, T):\n    return (np.log(S / K) + (r + stdev ** 2 / 2) * T) / (stdev * np.sqrt(T))\n \ndef d2(S0, K, r, sigma, T):\n    return (np.log(S / K) + (r - stdev ** 2 / 2) * T) / (stdev * np.sqrt(T))\n\ndef BSM(S, K, r, stdev, T):\n        return (S * norm.cdf(d1(S, K, r, stdev, T))) - (K * np.exp(-r * T) * norm.cdf(d2(S, K, r, stdev, T)))\n# Store the annual standard deviation of the log returns in a variable, called “stdev”.\n# In[3]:\nlog_returns = np.log(1 + data.pct_change())\nlog_returns.tail()\n# In[5]:\nstdev = log_returns.std() * 250 ** 0.5\nstdev\n# Set the risk free rate, r, equal to 2.5% (0.025); the strike price, K, equal to 110.0; and the time horizon, T, equal to 1, respectively.\nr = 0.025\nK = 110.0\nT = 1\n# Create a variable S equal to the last adjusted closing price of Microsoft. Use the “iloc” method.\n# In[7]:\nS = data.iloc[-1]\nS\n# Call the d1 and d2 functions with the relevant arguments to obtain their values.\nd1(S, K, r, stdev, T)\nd2(S, K, r, stdev, T)\n# Use the BSM function to estimate the price of a call option, given you know the values of S, K, r, stdev, and T.\nBSM(S, K, r, stdev, T)\n", "meta": {"hexsha": "d266b9738179fdb3ab0e0598e4ebc35aeff1f24f", "size": 1895, "ext": "py", "lang": "Python", "max_stars_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_108-MC-Black-Scholes-Merton-Solution_Yahoo_Py3.py", "max_stars_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_stars_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-04T11:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-10T15:36:42.000Z", "max_issues_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_108-MC-Black-Scholes-Merton-Solution_Yahoo_Py3.py", "max_issues_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_issues_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-03-30T16:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:37:21.000Z", "max_forks_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_108-MC-Black-Scholes-Merton-Solution_Yahoo_Py3.py", "max_forks_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_forks_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T11:26:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T11:26:16.000Z", "avg_line_length": 43.0681818182, "max_line_length": 160, "alphanum_fraction": 0.6691292876, "include": true, "reason": "import numpy,from scipy", "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.9124361616674906, "lm_q1q2_score": 0.8691630799816225}}
{"text": "#! /usr/bin/env python3\r\n# ************************************************************************** #\r\n#                                                                            #\r\n#                                                       :::      ::::::::    #\r\n#    cost_function.py                                 :+:      :+:    :+:    #\r\n#                                                   +:+ +:+         +:+      #\r\n#    By: darodrig                                 +#+  +:+       +#+         #\r\n#                                               +#+#+#+#+#+   +#+            #\r\n#    Created: 2020/04/22 16:07:59 by darodrig        #+#    #+#              #\r\n#    Updated: 2020/04/22 16:07:59 by darodrig       ###   ########.fr        #\r\n#                                                                            #\r\n# ************************************************************************** #\r\n\r\nimport numpy as np\r\n\r\n\r\ndef cost_elem_(theta, X, Y):\r\n    if type(X) != np.ndarray or type(Y) != np.ndarray or \\\r\n            type(theta) != np.ndarray:\r\n        return None\r\n    if X.shape[1] + 1 != theta.shape[0] or X.shape[0] != Y.shape[0]:\r\n        return None\r\n    if X.size == 0 or Y.size == 0 or theta.size == 0:\r\n        return None\r\n    ones = np.ones((X.shape[0], 1))\r\n    X = np.concatenate((ones, X.reshape(X.shape)), axis=1)\r\n    ret = X[:, 0].reshape(ones.shape)\r\n    for i in range(Y.size):\r\n        ret[i] = ((X[i].dot(theta) - Y[i]) ** 2) * (1/(2 * Y.size))\r\n    return ret\r\n\r\n\r\ndef cost_(theta, X, Y):\r\n    return np.sum(cost_elem_(theta, X, Y))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    X1 = np.array([[0.], [1.], [2.], [3.], [4.]])\r\n    Y1 = np.array([[2.], [7.], [12.], [17.], [22.]])\r\n    theta1 = np.array([[2.], [4.]])\r\n\r\n    print(cost_elem_(theta1, X1, Y1))\r\n    print(cost_(theta1, X1, Y1))\r\n    print()\r\n    X2 = np.array([[0.2, 2., 20.], [0.4, 4., 40.], [0.6, 6., 60.], [0.8, 8., 80.]])\r\n    theta2 = np.array([[0.05], [1.], [1.], [1.]])\r\n    Y2 = np.array([[19.], [42.], [67.], [93.]])\r\n    print(cost_elem_(theta2, X2, Y2))\r\n    print(cost_(theta2, X2, Y2))\r\n\r\n# Bonus: Cost functions\r\n# https://stats.stackexchange.com/questions/154879/a-list-of-cost-functions-used-in-neural-networks-alongside-applications\r\n", "meta": {"hexsha": "535ba57fb9910aefcd0c79f20750701178e5b836", "size": 2243, "ext": "py", "lang": "Python", "max_stars_repo_path": "day01/ex01/cost_function.py", "max_stars_repo_name": "d-r-e/machine_learning-bootcamp-42AI", "max_stars_repo_head_hexsha": "f795bea79b4b2a74ce442bdb3ca57dfb94aa54b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-10T16:39:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T16:39:37.000Z", "max_issues_repo_path": "day01/ex04/cost_function.py", "max_issues_repo_name": "d-r-e/machine_learning-bootcamp-42AI", "max_issues_repo_head_hexsha": "f795bea79b4b2a74ce442bdb3ca57dfb94aa54b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day01/ex04/cost_function.py", "max_forks_repo_name": "d-r-e/machine_learning-bootcamp-42AI", "max_forks_repo_head_hexsha": "f795bea79b4b2a74ce442bdb3ca57dfb94aa54b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.320754717, "max_line_length": 123, "alphanum_fraction": 0.3562193491, "include": true, "reason": "import numpy", "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.912436157500568, "lm_q1q2_score": 0.8691630735553674}}
{"text": "#%%\n# Math Modules\nimport numpy as np\nimport math\nimport pandas as pd\nimport scipy as sp\nfrom scipy.misc import derivative\nfrom scipy import integrate\nfrom scipy.sparse.linalg import eigsh\n\n# Plot Libraries\nimport matplotlib.pyplot as plt\nimport plotly.graph_objects as go\nfrom matplotlib import cm\n\n# Utilities\nimport datetime\n\npi = np.pi\n# %%\ndef f(x, y):\n    return (x ** 2 * y) + (x * y ** 2)\n\n\ndef dbsimpson(f, limits: list, d: list):\n    \"\"\"Simpson's 1/3 rule for double integration\n\n    int_{ay}^{by} int_{ax}^{bx} f(x,y) dxdy\n\n    Args:\n        f (func): two variable function, must return float or ndarray\n        limits (list): limits of integration [ax, bx, ay, by]\n        d (lsit): list of integral resolution [dx, dy]\n\n    Returns:\n        float: double integral of f(x,y) between the limits\n    \"\"\"\n    ax, bx, ay, by = limits\n    dx, dy = d\n    nx = math.floor((bx - ax) / dx)\n    ny = math.floor((by - ay) / dy)\n    s = 0\n    for i in range(ny + 1):  # loop of outer integral\n        if i == 0 | i == ny:\n            p = 1\n        elif i % 2 != 0:\n            p = 4\n        else:\n            p = 2\n\n        for j in range(nx + 1):  # loop of inner integral\n            if j == 0 | j == nx:\n                q = 1\n            elif j % 2 != 0:\n                q = 4\n            else:\n                q = 2\n            x = ax + j * dx\n            y = ay + i * dy\n            s += p * q * f(x, y)\n\n    return dx * dy / 9 * s\n\n\ndbsimpson(f, [1, 2, -1, 1], [0.01, 0.01])\n\n\n# %%\ndef f(x, y):\n    return (x ** 2 * y) + (x * y ** 2)\n\n\ndef dbsimpson(g: np.ndarray, dxdy: tuple = (1, 1), grid: tuple = None):\n    \"\"\"Simpson's 1/3 rule for double integration\n\n    int_{ay}^{by} int_{ax}^{bx} f(x,y) dxdy\n    \"\"\"\n    nx = g.shape[0] - 1\n    ny = g.shape[1] - 1\n\n    if grid:\n        (x, y) = grid\n        ax, bx = np.min(x[1]), np.max(x[1])\n        ay, by = np.min(y[:, 0]), np.max(y[:, 0])\n        dx = (bx - ax) / nx\n        dy = (by - ay) / ny\n    else:\n        dx, dy = dxdy\n\n    s = 0\n    for i in range(ny + 1):  # loop of outer integral\n        if i == 0 | i == ny:\n            p = 1\n        elif i % 2 != 0:\n            p = 4\n        else:\n            p = 2\n\n        for j in range(nx + 1):  # loop of inner integral\n            if j == 0 | j == nx:\n                q = 1\n            elif j % 2 != 0:\n                q = 4\n            else:\n                q = 2\n            s += p * q * g[j, i]\n\n    return dx * dy / 9 * s\n\n\nax, bx, ay, by = [1, 2, -1, 1]\ndx, dy = [0.01, 0.01]\nnx = int((bx - ax) / dx)\nny = int((by - ay) / dy)\nx = np.arange(ax, bx + dx, dx)\ny = np.arange(ay, by + dy, dy)\nxv, yv = np.meshgrid(x, y)\ng = f(xv, yv)\naa = dbsimpson(g, grid=(xv, yv))\nbb = dbsimpson(g, dxdy=(dx, dy))\nprint(aa, bb)\n", "meta": {"hexsha": "291ae97c1e1d9ba274544e9bf2f3f515da051ec0", "size": 2723, "ext": "py", "lang": "Python", "max_stars_repo_path": "VA/work3/sandbox.py", "max_stars_repo_name": "lucas-schroeder/Master_program_UFSC", "max_stars_repo_head_hexsha": "4a1cecfa1ebcd57968449d0650abd11d782df71c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VA/work3/sandbox.py", "max_issues_repo_name": "lucas-schroeder/Master_program_UFSC", "max_issues_repo_head_hexsha": "4a1cecfa1ebcd57968449d0650abd11d782df71c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VA/work3/sandbox.py", "max_forks_repo_name": "lucas-schroeder/Master_program_UFSC", "max_forks_repo_head_hexsha": "4a1cecfa1ebcd57968449d0650abd11d782df71c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3196721311, "max_line_length": 71, "alphanum_fraction": 0.4638266618, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889437, "lm_q2_score": 0.9073122232403329, "lm_q1q2_score": 0.8691255165245422}}
{"text": "\nfrom statistics import mean\nimport numpy as np\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nstyle.use('fivethirtyeight')\n\nxs = [1,2,3,4,5,6]\nys = [5,4,6,5,6,7]\n\n# plt.plot(xs,ys)\n# plt.show()\n\n# Since above are not np array they are just a python array, to change them which will give us\n# more powerful way to iterate over then values in the array,\n\nxs = np.array(xs, dtype = np.float64)  # you can also specify the data-type into your array\nys = np.array(ys, dtype = np.float64)\n\n\n# first we need a function to calculate the slop as\n\ndef best_fit_slop_and_intercept(xs,ys):\n\n    m = ( ((mean(xs)*mean(ys)) - mean(xs*ys)) /\n          (mean(xs)**2-mean(xs**2)))\n    b = mean(ys)-m*mean(xs)\n\n# remember the PEMDAS the order of the operations in computing\n    return m,b\n\ndef squared_error(ys_orig, ys_line):\n    return sum((ys_line-ys_orig)**2)\n\ndef coefficient_of_determination(ys_orig,ys_line):\n    y_mean_line = [mean(ys_orig) for y in ys_orig]    # to make a vector with only one value which is mean(ys_orig)\n    squared_error_regr = squared_error(ys_orig,ys_line)\n    squared_error_y_mean = squared_error(ys_orig, y_mean_line)\n    return 1- (squared_error_regr / squared_error_y_mean)\n\n\n\nm,b = best_fit_slop_and_intercept(xs,ys)\nprint(m,b)\n\n\nregression_line = [(m*x)+b for x in xs]\nprint(regression_line)\n\n\n# Here we will add the piece of code to calculate the coefficient of determination,\nr_squared = coefficient_of_determination(ys, regression_line)\nprint(r_squared)\n\n\n\n# this is exact identical to the following format\n# for x in xs:\n#     regression_line.append((m*x)+b)\n\n# now we will plot the data and the regression line\n\n# what if you want to predict a specific value\npredict_x = 8\npredict_y = (m*predict_x)+b\n\nplt.scatter(xs,ys)\nplt.scatter(predict_x,predict_y)\nplt.plot(xs,regression_line)\nplt.show()\n\n", "meta": {"hexsha": "02db4711fb9e4d29e728e3112d37d861e18d3594", "size": 1876, "ext": "py", "lang": "Python", "max_stars_repo_path": "Machine_Learning_Old_Files/[11] linear regression P.4.py", "max_stars_repo_name": "Ghasak/PracticalMachineLeanring", "max_stars_repo_head_hexsha": "b16095c889be3a14a27e83fe6311581b456cefd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Machine_Learning_Old_Files/[11] linear regression P.4.py", "max_issues_repo_name": "Ghasak/PracticalMachineLeanring", "max_issues_repo_head_hexsha": "b16095c889be3a14a27e83fe6311581b456cefd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:46:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:10:34.000Z", "max_forks_repo_path": "Machine_Learning_Old_Files/[11] linear regression P.4.py", "max_forks_repo_name": "Ghasak/PracticalMachineLeanring", "max_forks_repo_head_hexsha": "b16095c889be3a14a27e83fe6311581b456cefd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3513513514, "max_line_length": 115, "alphanum_fraction": 0.7302771855, "include": true, "reason": "import numpy", "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075701109192, "lm_q2_score": 0.9032942041005327, "lm_q1q2_score": 0.8690661918024403}}
{"text": "import scipy as sp\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import fmin_bfgs\nfrom statistics import mean\n\n# Define sigmoid, cost function and gradients\ndef sigmoid(z):\n  return 1 / (1 + sp.exp(-z))\n\ndef cost_function(theta, X, Y):\n  theta = sp.matrix(theta).T\n  J = (1 / m) * (-Y.T * sp.log(sigmoid(X * theta)) - ((1 - Y).T * sp.log(1 - sigmoid(X * theta))))\n  print(J)\n  return J[0, 0]\n\ndef gradients(theta, X, Y):\n  theta = sp.matrix(theta).T\n  grad = ((1 / m) * X.T * (sigmoid(X * theta) - Y)).T\n  grad = sp.squeeze(sp.asarray(grad))\n  return grad\n\ndef predict(theta, X):\n  return sp.around(sigmoid(X * theta))\n\n# Load data from data source 1\ndata = sp.matrix(sp.loadtxt(\"data.txt\", delimiter=' '))\nX = data[:, 0:2]\nX = (X - mean(X))/std(X) \nY = data[:, 2]\nm, n = X.shape\n\n# Compute cost and gradients\n# Initialize\nX = sp.hstack((sp.ones((m, 1)), X))\ntheta = sp.zeros(n+1) # Use row vector instead of column vector for applying optimization\n\n# Optimize using fmin_bfgs\nres = fmin_bfgs(cost_function, theta, fprime=gradients,disp=True, maxiter=100, args=(X, Y))\ntheta = sp.matrix(res).T\n\n# Plot fiqure 1 (data)                 \nplt.figure(1)\nplt.xlabel('x1')\nplt.ylabel('x2')\n\npos = sp.where(Y == 1)[0]\nneg = sp.where(Y == 0)[0]\n\nplt.plot(X[pos, 1], X[pos, 2], 'k+', linewidth=2, markersize=7)\nplt.plot(X[neg, 1], X[neg, 2], 'ko', markerfacecolor='y', markersize=7)\n\n# Plot fiqure 2 (decision boundary)\nplt.figure(2)\nplt.xlabel('x1')\nplt.ylabel('x2')\n\npos = sp.where(Y == 1)[0]\nneg = sp.where(Y == 0)[0]\n\nplt.plot(X[pos, 1], X[pos, 2], 'k+', linewidth=2, markersize=7)\nplt.plot(X[neg, 1], X[neg, 2], 'ko', markerfacecolor='y', markersize=7)\n\nif X.shape[0] >= 3:\n  plot_x = sp.array([sp.amin(X[:, 1]) - 2, sp.amax(X[:, 1]) + 2])\n  plot_y = (-1 / theta[2, 0]) * (theta[0, 0] + theta[1, 0] * plot_x)\n  plt.plot(plot_x, plot_y)\n  plt.savefig('1.png')\n\np = predict(theta, X)\nr = sp.mean(sp.double(p == Y)) * 100\n\nprint(\"Train Accuracy: {r}%\".format(**locals()))", "meta": {"hexsha": "21185db6df663d195fe056f807cfd4839c17223e", "size": 1969, "ext": "py", "lang": "Python", "max_stars_repo_path": "reg_log1.py", "max_stars_repo_name": "ptorresmanque/MachineLearning_v2.0", "max_stars_repo_head_hexsha": "795e47b9cfc68f4e0fefb700d43af6c59e2f1d73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reg_log1.py", "max_issues_repo_name": "ptorresmanque/MachineLearning_v2.0", "max_issues_repo_head_hexsha": "795e47b9cfc68f4e0fefb700d43af6c59e2f1d73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reg_log1.py", "max_forks_repo_name": "ptorresmanque/MachineLearning_v2.0", "max_forks_repo_head_hexsha": "795e47b9cfc68f4e0fefb700d43af6c59e2f1d73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3472222222, "max_line_length": 98, "alphanum_fraction": 0.6216353479, "include": true, "reason": "import scipy,from scipy", "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075733703927, "lm_q2_score": 0.9032942001955142, "lm_q1q2_score": 0.8690661909896559}}
{"text": "# Chapter 2: Linear, Trend, and Momentum Forecasting\nPrepared by: Marissa P. Liponhay and Maria Eloisa M. Ventura\n\nIn this chapter we introduce basic tools on forecasting, which utilize simple algebraic formula. In the previous chapter, ARIMA was discussed where the future values of a time series are forecasted using its past or lagged values. It was shown that ARIMA can only be applied after removing the trend and seasonality of the data. We note however that for some forecasting tools, the trend is relevant and is part of the formula for prediction. In this work, forecasting will be demonstrated while making use of the relationships and trends in the data. \n\nIn the first half of this notebook, we demonstrate forecasting by fitting time series data with linear regression. For the second half, we demonstrate that by using the trends of the time series data such as moving averages, we can predict the possible future direction of the trend using momentum forecasting. \n\nLastly, it is important to note that the concept of moving average (MA) in ARIMA is not the same in this chapter since the moving average that will be discussed is just the classical definition of MA.\n\n### How to Use This Notebook\nThis chapter is divided into two parts mainly about: (a) linear regression and (b) trend and momentum forecasting  using moving averages. In each section, the theory is discussed followed by examples that are implemented in Python 3. The chapter outline can be seen in the __[readme](readme.txt)__ file for this chapter.\n\n\n## Linear Regression (LR) Forecasting \nLinear regression forecasting is used when forecasting a time series y, with the assumption that it has a linear relationship with another time series x. \n\nThe basic equation in doing linear regression is:\n$y= mx + b $\n\nwhere $m$ is the slope of the linear fit and $b$ is the $y$ intercept which represents error in the fit. Usually in forecasting, $y$ is replaced by $\\hat{y}$ to symbolize the forecasted value.\n\nGiven a data set, one can easily compute for the slope of the data manually or automatically using excel built-in trendline functions. To manually calculate $m$, the following equation is used:\n\n$m = {\\frac{\\sum\\limits _{i=1} ^{n}(x_{i}-\\bar{x})(y_{i}-\\bar{y})}{\\sum\\limits _{i=1} ^{n}(x_{i}-\\bar{x})^2}}$\n\nTo automatically calculate it in excel, one only needs to place a linear 'trendline' into the scatter plot of the data. \n\nThis method is called the Ordinary least squares (OLS). A more general equation of LR using OLS is given as:\n\n$y= mx + b + \\mu_{i}$\n\nwhere $\\mu_{i}$ represent the outliers or the terms that cannot fit into the regression line.\n\n\nOLS quantifies the  evaluation of different regression lines. Using OLS, the regression line that minimizes the sum of the squares of the differences between the observed dependent variable and the predicted dependent variable is chosen as the best fit. \n\nBut what if there are outliers causing the best regression by OLS do not really fit the data? This leads us to check when OLS can be applied to a data set. The following are the assumptions that are necessarily met before we can apply OLS.\n\n\n#### Gauss Markov Assumptions \nThe following assumptions for sampled data (from a population) should be met so that the parameters calculated using OLS indeed represent the best unbiased estimator of the population parameters.\n\n1. Linearity in parameters. This assumption requires that parameter $m$ is linear. (Independent variable is not required to be linear).\n\n2. Both the independent and dependent variables $(x,y)$ are random variables. This will result to zero autocorrelation of outlier or the residual term.\n\n3. For multivariate regression method,there should be no perfect collinearity between multiple independent variables. To test for the presence of collinearity, $R^{2}$ is good. \n\n4. The outlier aka residual term $\\mu$ is endogenous, such that $cov(\\mu_{i}, x_{i})=0$=0. \n\n5. Homoscedasticity in residual term $\\mu_{i}$, in other words, the variance of $\\mu_i$ is independent of $x_i$.\n\n6. The residual term $\\mu_{i}$ have zero autocorrelation, i.e., $cov(\\mu_{i}, \\mu_{j})=0$.\n\n\nUsing OLS for time series data, the samples are drawn from the same process, and we can no longer assume that the independent variable $x$ is random variable. In this case, the assumptions (4-6) should be strictly met by all $x$ at all points.\n\n\n### Example 1: Univariate LR in Stock Price of Netflix\nLinear regression is one of the most successful tools used in technical analysis of prices and is widely available as a charting tool. For the sake of demonstration, we will use the historical data of Netflix downloaded from Yahoo.\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom pandas.plotting import autocorrelation_plot\nimport statsmodels.api as sm\nfrom statsmodels.graphics import tsaplots\nfrom sklearn.metrics import r2_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\n\n%matplotlib inline\n#from sklearn.model_selection \n\nprice = pd.read_csv('../data/NFLX3.csv',usecols=['Date', 'Close'], parse_dates=['Date'])\nprice.set_index(\"Date\", inplace=True)\n\nplt.rcParams[\"figure.figsize\"] = (15,2)\nax=price.plot()\nplt.ylabel('Price')\n# plt.grid()\nax.set_title('Daily Close Price')\nplt.show()\n\n#### Testing for Stationarity\nWe have learned from the previous chapter that one of the first steps to do when doing time series forecasting is to check the stationarity of the data, especially when there is a prominent trend. In this notebook, we will use the most widely used statistical test called the Augmented Dickey-Fuller, a unit root test. Note that a unit root test determines how strongly a time series is defined by a trend. The test uses an autoregressive model and optimizes an information criterion across different lag values. Recall that:\n\n\nNull Hypothesis (H0): \n- The time series has a unit root and is non-stationary. It is time dependent.\n\nAlternate Hypothesis (H1): \n- The time series does not have a unit root and is stationary. It is not time-dependent.\n\nFinally, the result of the test can be interpreted using the ADF Statistic, i.e., the ADF statistic should be lesser than the critical values for the data to be considered stationary.\n\nIn some references, they use p-value from the test. A p-value below a threshold (such as 5% or 1%) implies a stationary time series, otherwise the data is non-stationary.\n\np-value <= 0.05: The time series is stationary.\n\np-value > 0.05: The time series is non-stationary.\n\nIn other references, they simply compare the ADF statistic to the critical values, such that if it is greater than the critical values, the time series is said to be non-stationary.\n\nfrom statsmodels.tsa.stattools import adfuller\nseries = pd.read_csv('../data/NFLX3.csv',usecols=['Close'])\nX = series.values\nresult = adfuller(X)\nprint('ADF Statistic: %f' % result[0])\nprint('p-value: %f' % result[1])\nprint('Critical Values:')\nfor key, value in result[4].items():\n\tprint('\\t%s: %.3f' % (key, value))\n\nBased on the results, the time series in non-stationary at all significance levels (1%,...) as the ADF statistic is greater the the critical values.\n\n#### Testing for Autocorrelation\nThe autocorrelation coefficient measures the strength of the relationship between the data and its lag. The first coefficient measures the relationship between $y_{t}$ to $y_{t-1}$, while the second coefficient measures the relationship between $y_{t}$ to $y_{t-2}$, and so on.\n\n# testing autocorrelation using pandas tools.\nplt.rcParams[\"figure.figsize\"] = (6,4)\ntsaplots.plot_acf(price)\nplt.show()\n\nAnother way to visualize the autocorrellation using pandas tools with respect to lag is shown below.\n\nplt.rcParams[\"figure.figsize\"] = (6,4)\nautocorrelation_plot(price)\n\nOne can better imagine the concept of lagged autocorrelation if we make the lagged data as a moving version of the original data and look at the overlap (in this case, their autocorrelation). If the trends of the original are both goin up or down as the lagged data is moved, the correlation is positive, otherwise negative.\n\nReferring back to the autocorrelation plot vs lag, the plot shows that as the lag increases, the trend decreases. The strong relationship of the data with the first 100 lags shows that $y$ is not purely random as stated in the Gauss-Markov assumption. At lag of approximately equal to 120 days, the autocorrelation is zero and starts to be negative. This is because the trend of the lagged data becomes negative in contrast to the positive trend of the data. \n\nHere we see that after approximately $y_{t-320}$, the autocorrelation is zero. This is mainly because the overlap of the lagged data and the original data is minimal as less and less data are overlapped.\n\nNow assuming that 4-6 are met, we will now apply linear regression to the price of NFLX to predict the prices for the next month on a daily basis.\n\n# Let us create another variable to manipulate rather than using the original data \n\nwindow = 30\nprice2 = price[['Close']]\nplt.rcParams[\"figure.figsize\"] = (15,2)\nprice2.plot()\n# plt.grid()\n\n# With the goal of predicting the future prices daily for a month (30days), we create a variable to contain the size\n# it will be placed at the end of a variable 'Prediction' in the dataframe that is shifted by 30 days\nplt.rcParams[\"figure.figsize\"] = (6,4)\nprice2['Prediction'] = price2[['Close']].shift(-window)\n\nprice2.plot(subplots=True)\nplt.show()\n\nprint(price2[['Close']].shape)\n\nprint(price2[['Prediction']].shape)\n\n# Now we will use the original data on prices as X, the predicted data as y and use 80% of the data as training set \n# while 20% of the data as test set and use sklearn function to train and test the data.\n# for both variables, the last 30 values are removed.\n\nX = np.array(price2[['Close']])\nX = X[:-window]\nprint(len(X))\n\ny = np.array(price2['Prediction'])\ny = y[:-window]\n#print(y)\n\nx_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2020)\n\n\nprint(X.shape)\n\nNow the data is ready for linear regression training and fitting using sklearn. \n\nlr = LinearRegression()\nfit = lr.fit(x_train, y_train)\n\nprint(y_train.shape)\n\n## coefficients of linear fit are:\nb = fit.intercept_\nm = fit.coef_\n\nprint(\"the equation of the linear fit is: \")\nprint('y= ', m, 'x + ', b)\n\n# checking R^2\nR_sqd = lr.score(x_test, y_test)\nprint(\"lr confidence: \", R_sqd)\n\n# To show the relationship of the training set and the predicted prices.. we plot the following.\nplt.rcParams[\"figure.figsize\"] = (6,4)\nplt.plot(x_train, y_train, 'o')\nplt.xlabel('x_train')\nplt.ylabel('y_train')\nplt.plot(x_train.flatten(), lr.predict(x_train), label='regression line')\nplt.legend()\n\n# Here is an attempt to show that the difference between the training set and the predicted values are almost Gaussian\nplt.rcParams[\"figure.figsize\"] = (6,4)\nplt.hist(lr.predict(x_train)-y_train, bins=np.arange(-125, 126, 25))\nplt.show()\n\n# Setting the last 30 rows of the original Close price as test data \n# to predict the next values. \nx_forecast = np.array(price2.drop(['Prediction'],1))[-window:]\nprint(len(x_forecast))\n\n# # we predict the closing prices...\nlr_prediction = lr.predict(x_forecast)\nprint(len(lr_prediction))\n\nplt.rcParams[\"figure.figsize\"] = (6,4)\nplt.plot(x_test, y_test, 'o')\nplt.xlabel('x_test')\nplt.ylabel('y_test')\nplt.plot(x_test.flatten(), lr.predict(x_test))\n# plt.legend()\n\nNow, we try to plot the predicted values over the original time series.  \n\nplt.figure(figsize=[15, 2])\nprice2.loc[~price2.Prediction.isnull()].Close.plot(label='y_train')\nprice2.loc[price2.Prediction.isnull()].Close.plot(label='y_test')\npd.Series(lr.predict(price2.loc[price2.Prediction.isnull()][['Close']].values), \n          index=price2.loc[price2.Prediction.isnull()].index, \n          name='Pred_LR').plot(label='y_pred from regression')\nplt.legend(loc=2)\n\n# checking R^2\nR_sqd_train = r2_score(y_pred=lr.predict(x_train), y_true=y_train)\nprint(\"Train set R^2: \", R_sqd_train)\n\n## R^2 of the predicted vs the actual closing price...\nR_sqd_test = r2_score(y_pred=lr_prediction, y_true=y[-window:])\nprint(\"Test set R^2: \", R_sqd_test)\n\n# checking for the MAE values:\nprint(\"The mean absolute error, MAE is: \", metrics.mean_absolute_error(lr_prediction, x_forecast))\n\n#### Compare with model where $X=X_{t-1}$\nHere, we check the R^2 value with respect to the lagged series.\n\nr2_score(price.Close.iloc[:-1], price.Close.iloc[1:])\n\n# Setting the last 30 rows of the original Close price as the variable x_forecast2 and using it as the \n# test data to predict the next values. \n\nx_forecast2 = np.array(price2.drop(['Prediction'],1))[-window:]\n# print(len(x_forecast))\n\n# # we predict the closing prices...\nlr_prediction2 = lr.predict(x_forecast2)\nprint(len(lr_prediction))\n\nNow we check the relationship between the test data and the prediction, we see that there is a perfect linear relationship as seen below.\n\nimport scipy\nfrom scipy.stats import linregress\nslope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x_forecast.flatten(), lr_prediction2)\n\nplt.rcParams[\"figure.figsize\"] = (6,4)\nplt.plot(x_forecast2.flatten(), lr_prediction2)\n\n### Example 2. Univariate Forecasting using Jena Climate Data\nWe will use the temperature values of the data in this part of the chapter to see if we can forecast the next 24hr temperature values. For this book, the data has been divided into training_series, validation_series, and test_series as described in the preface. In this chapter, I do not need perform any validation procedure, thus I will combine the training and validation series and it will serve as my raw data. We will then follow the steps outlined in Example 1 and see the average MAE of the prediction using linear regression.\n\n# combining the training and validation data sets used in this Jupyter book as our training set in this chapter \n# since I don't need to perform validation.\ndf= pd.read_csv(\"../data/train_series.csv\")\ndf2= pd.read_csv(\"../data/val_series.csv\")\n\n## (training + validation series)\ndf3 = pd.concat([df, df2])\n\nprint(df.shape) #train\nprint(df2.shape) #val\nprint(df3.shape) #combined\n\nNow, we select the temperature data and use it for univariate linear regression forecasting and visualize the raw data. We keep the training data set to be a multiple of 24.\n\nlen_train = len(df3)-len(df3)%24\nlen_train\n\n#using the temperature data\ntemperature = df3[['T (degC)']].iloc[:len_train]\n\nplt.rcParams[\"figure.figsize\"] = (15,2)\nax=temperature.plot()\nplt.ylabel('temp')\nax.set_title('Hourly Temp')\nplt.show()\n\nTo perform linear regression, we follow the same step we did in Example 1. We will use the shifted (by 24-hrs) temperature data (x-variable) as the prediction variable (y-variable). We get the equation by fitting with LR and use the equation in predicting the temperature in the next 24 hours.\n\nwindow = 24\ntemperature['Prediction'] = temperature[['T (degC)']].shift(-window)\n\ndf4 = pd.read_csv(\"../data/test_series.csv\", usecols=['T (degC)']).iloc[:17520]\ntest_24 = pd.DataFrame(np.reshape(df4.values, (24, 730)))\n# y_test = df4[['T (degC)']].iloc[:24]\n\nX = np.array(temperature.drop(['Prediction'],1))\nX = X[:-window]\n\ny = np.array(temperature['Prediction'])\ny = y[:-window]\nprint(X.shape)\nprint(y.shape)\n\n\nX.flatten().shape\n\n#### Simultaneous prediction of temperature in the next 24 hours\nIn order to make predictions for the next 24 hours, we will need to reshape our $X$ and $y$ data so that we can  use only one sample point $X$ to predict the temperature for the next 24 hours.  \n\n# Divide training data into 24 hour chunks\n# Use 1 Temperature measurement to predict the next 24 hours\nX_new = temperature['T (degC)'].iloc[:-window].values.reshape(-1, 24)[:,-1].reshape(-1,1)\ny_new = temperature['Prediction'].iloc[:-window].values.reshape(-1, 24)\nX_new.shape, y_new.shape\n\nprint(X_new)\n\nWe create a vector that will contain the outputs of the fit.\n\nlr_vectoroutput = LinearRegression()\nfit = lr_vectoroutput.fit(X_new, y_new)\n\nNow, we divide the test data into 24 hour chunks, which will serve as our test sets. The average MAE of these test sets will be calculated to see how Univariate LR performs in predicting the temperature in the next 24 hrs.\n\nX_test = np.vstack([temperature['T (degC)'].iloc[-window:].values.reshape(1,-1),\n                    test_24.iloc[:, :-1].values.T])[:,-1].reshape(-1,1)\ny_test = test_24.values.T\n\n## predict for every 24 hrs in test_series\nMAE = []\ny_pred = lr_vectoroutput.predict(X_test)\nfor i in range(len(y_test)):\n    MAE.append(metrics.mean_absolute_error(y_test[i], y_pred[i]))\nprint(f\"The average Mean Absolute Error is for {len(y_test)} sets of 24-hr data: \", sum(MAE)/730)\n\nWe see that the average MAE is 9.067496890754962, which shows that LR is not a good model for forecasting the next 24-hr temperature using the Jena Climate Data. \n\n### Example 3: Multivariate Linear Regression and Regularization Techniques\nIn the previous example, we used univariate LR to demonstrate forecasting time series. In this example, we would like to demonstrate LR for a case where there are more than 1 independent variable, called the multivariate linear regression. To start off, we demonstrate the LR model first using a simple data on cars downloaded from one of the references. Take note that this is not yet forecasting in time series, but just a simple demonstration how multivariate LR works.\n\n#creating dataframe for simple data on cars\ncars = pd.read_csv('../data/cars.csv')\ncars.head()\n\ncars.describe()\n\nfrom sklearn.linear_model import LinearRegression\n\n# We will model C02 emission (as y variable) using the parameters volume and weight as predictors (x variable)\n# for a multi-variate linear regression\n\nparams = ['Volume', 'Weight']\nX = cars[params]\ny = cars['CO2']\n\n# fitting the data with linear regression\nlrm = LinearRegression()\nmodel = lrm.fit(X, y)\n\n# coefficients of the fit are as follows:\nb = model.intercept_\nm = model.coef_\n\nprint(\"Using Multivariate Linear Regression, we have the following equation: \")\nprint('CO2= ', m[0], 'x1 + ', + m[1], 'x2 + ', b)\n\n#We want to predict CO2 emission given specific weight and volume -- both 1000\nmodel.predict([[1000, 1000]])\n\n#### Interpretation of coefficients:\n\nThe slope for volume and weight of the cars are equal to 0.00781 and 0.00755, respectively. This means that for every 1 unit change in volume (weight) of cars, the expected increase in CO2 emission is 0.00781% (0.00755%).\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\ny_pred = lrm.predict(X_test)\n\nprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))\n\n#### Interpretation of metrics:\n\nWe can see that the value of mean absolute error is 5.67, which is less than 6% of the mean value of the CO2 emission. This means that our prediction is good.\n\n\nFor multi-variate linear regression, sometimes we do not know which among the parameters are relevant to the prediction. Thus in order to make our predictions more accurate, we need to penalize the less relevant parameters (or basically decrease their effect on our predictions and sometimes let them approach zero). This is usually done using regularization techniques.\n\n### L1 (Lasso) and L2 (Ridge) regularization for multi-variate linear regression\nRegularization techniques is based on the idea that proper constraining the allowed values of variables will increase the accuracy. In this notebook, we will use two techniques:\n\n#### Lasso Regularization \n- It puts constraints on the absolute value of the coefficients.\n\n#### Ridge Regularization \n- It puts contraints on the square of the coefficients.\n\n#### L1 Regularization\n\n# Lasso Regularization... alpha=0 is equivalent to linear regression\nfrom sklearn.linear_model import Lasso\nlassoreg = Lasso(alpha=0.01, normalize=True)\nmodel3 = lassoreg.fit(X, y)\n\n\n# coefficients of the fit are as follows:\nb = model3.intercept_\nm = model3.coef_\n\nprint(\"Using Multivariate Linear Regression, we have the following equation: \")\nprint('CO2= ', m[0], 'x1 + ', + m[1], 'x2 + ', b)\n\ny_pred = lassoreg.predict(X_test)\nprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))\n\n#### L2 Regularization\n\n# Ridge Regularization... alpha=0 is equivalent to linear regression\nfrom sklearn.linear_model import Ridge\nridgereg = Ridge(alpha=0.1, normalize=True)\nmodel2 = ridgereg.fit(X, y)\n\n# coefficients of the fit are as follows:\nb = model2.intercept_\nm = model2.coef_\n\nprint(\"Using Multivariate Linear Regression, we have the following equation: \")\nprint('CO2= ', m[0], 'x1 + ', + m[1], 'x2 + ', b)\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\ny_pred = ridgereg.predict(X_test)\n\nprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))\n\n### Example 4: Multi-variate Linear Regression on Jena Climate Data\nIn this section, we use the climate data to demonstrate forecasting using multivariate linear regression and regularization. The idea of forecasting method in this example is different from the method used in Example 1. In Example 1, we used the lagged value of the close prices of NFLX, i.e., we predicted $y_{T,t}$ using the lagged value $y_{T-30}$. In this example, we will use different variables $x_{1,t}$, $x_{2,t}$,..., $x_{n,t}$, where n is the total number of variables used to predict y. In this case, n=14.\n\ntrain_df = pd.read_csv('../data/train_series_datetime.csv',index_col=0)\nval_df = pd.read_csv('../data/val_series_datetime.csv',index_col=0)\ndata = pd.concat([train_df, val_df])\ndata.head()\n\ndata.describe()\n# print(data.shape)\n\nTo be consistent with all the other forecasting models, we manually set the first 300k+ data for training while the last 100k+ data points as test set.\n\ndata_train = data.iloc[:, 1:15]\nprint(data.shape)\n\nx_train = data_train[['p (mbar)', 'Tpot (K)', 'Tdew (degC)', 'H2OC (mmol/mol)', 'rh (%)', 'VPmax (mbar)', 'VPact (mbar)', 'VPdef (mbar)', 'sh (g/kg)', 'rho (g/m**3)', 'wv (m/s)', 'max. wv (m/s)', 'wd (deg)']]\ny_train = data_train['T (degC)']\n\ndata_train.head()\n\ndata_train.shape\n\nAgain, for consistency with all the other forecasting models in this book, we use the same test set, which is the last 100k+ data.\n\ndata_test = pd.read_csv('../data/test_series.csv')\ndata_test.head()\nprint(data.shape)\n\nx_test = data_test[['p (mbar)', 'Tpot (K)', 'Tdew (degC)', 'H2OC (mmol/mol)', 'rh (%)', 'VPmax (mbar)', 'VPact (mbar)', 'VPdef (mbar)', 'sh (g/kg)', 'rho (g/m**3)', 'wv (m/s)', 'max. wv (m/s)', 'wd (deg)']]\ny_test = data_test[['T (degC)']]\n\n# x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2020)\nlr = LinearRegression()\nlr.fit(x_train, y_train)\n\ny_pred = lr.predict(x_test)\n\nprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))\n\nWe can see that the value of MAE error is 0.007635891353557461. This means that linear regression is good for this dataset if all the parameters are used. Now we try to use the regularization techniques if the errors will improve.\n\n#### L1 Regularization\n\n\n# Lasso Regularization... alpha=0 is equivalent to linear regression\nfrom sklearn.linear_model import Lasso\n# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2020)\nlassoreg2 = Lasso(alpha=0.01, normalize=True)\nmodel_temp2 = lassoreg2.fit(x_train, y_train)\n\ny_pred3 = lassoreg2.predict(x_test)\nprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred3))\n\nL1 Regularization has worse performance having large errors, based on the metrics.\n\n#### L2 Regularization\n\n# Ridge Regularization... alpha=0 is equivalent to linear regression\nfrom sklearn.linear_model import Ridge\n# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2020)\n\nridgereg2 = Ridge(alpha=0.01, normalize=True)\nmodel_temp = ridgereg2.fit(x_train, y_train)\ny_pred2 = ridgereg2.predict(x_test)\n\nprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred2))\n\nUsing L2 regularization, penalizing the other parameters didn't lead to significant improvement in the prediction.\n\n#### Simultaneous prediction of the temperature for the next 24 hours\nIn this part, we perform the same re-shaping of the data similar to what we did above when we applied univariate linear regression and use one sample point from each of the 730 24-hr test set described in Example 2 to predict the temperature for the next 24 hours. \n\nx_train = data_train[['p (mbar)', 'Tpot (K)', \n                      'Tdew (degC)', 'H2OC (mmol/mol)', \n                      'rh (%)', 'VPmax (mbar)', \n                      'VPact (mbar)', 'VPdef (mbar)', \n                      'sh (g/kg)', 'rho (g/m**3)', \n                      'wv (m/s)', 'max. wv (m/s)', \n                      'wd (deg)']].iloc[:len(data_train)-len(data_train)%24]\ny_train = data_train['T (degC)'].iloc[:len(data_train)-len(data_train)%24]\n\nX_new = x_train.iloc[::24].values\ny_new = y_train.values.reshape(-1, 24)\n\nlr_sim = LinearRegression()\nlr_sim.fit(X_new, y_new)\n\nx_test_new = data_test[['p (mbar)', 'Tpot (K)', \n                       'Tdew (degC)', 'H2OC (mmol/mol)', \n                       'rh (%)', 'VPmax (mbar)', \n                       'VPact (mbar)', 'VPdef (mbar)', \n                       'sh (g/kg)', 'rho (g/m**3)', \n                       'wv (m/s)', 'max. wv (m/s)', \n                       'wd (deg)']].iloc[:len(data_test)-len(data_test)%24].iloc[::24].values\ny_test_new = data_test[['T (degC)']].iloc[:len(data_test)-len(data_test)%24].values.reshape(-1, 24)\n\n## predict for every 24 hrs in test_series\nMAE = []\ny_pred = lr_sim.predict(x_test_new)\nfor i in range(len(y_test_new)):\n    MAE.append(metrics.mean_absolute_error(y_test_new[i], y_pred[i]))\nprint(f\"The average Mean Absolute Error is for {len(y_test_new)} sets of 24-hr data: \", sum(MAE)/730)\n\nWe can see that the MAE improved compared to the MAE when we forecasted the temperature for the next 24 hours using univariate LR.\n\n## Momentum and Trend Forecasting\nNow let us move to common tools in momentum and trend forecasting. We will see that these two topics on momentum and trend goes together, i.e., the momentum forecasting is based on the usage of trend forecasting. In this section, we will discuss by considering the applications in technical analysis and strategies in stock trading. In this are, the most common used tools are \n1. Moving Average\n2. Momentum\n\n\n\n### Moving Average MA\n\nMA trading rule is the most popular trading tool for traders. The trading signal or indicator is normally derived by first computing for the average closing price over a window of size $n$, with the following formula:\n\n$MA_{n}(t) = \\frac{w_{0}P_{t}+ w_{1}P_{t-1}+ w_{2}P_{t-2}+...+ w_{n-1}P_{t-n+1}}{w_{0}+ w_{1}+ w_{2}+... + w_{n-1}}$ (1)\n\n$MA_{n}(t) = \\frac{\\sum\\limits _{i=0} ^{n-1} w_{i}P_{t-i}}{\\sum\\limits _{i=0} ^{n-1} w_{i}}$ (2)\n\nThere are three types of MA and they are as follows:\n1. Simple Moving Average (SMA) - all prices are weighted equally such that $w_{i}=1$ in equations (1, 2). \n\n2. Linear Moving Average (LMA) - the weights change, putting more relevance to the prices closer to the current price such that $w_{i}= n-i$\n\n3. Exponential Moving Average (EMA) - similar to LMA, bigger weights are assigned to more recent prices and the weights drop exponentially. There are several ways proposed to compute the weights in EMA. We will discuss here the general formulation of EMA given as:\n\n$EMA(n) = \\frac{2}{n+1}P_{t} + (1- \\frac{2}{n+1}) P_{t-1}$\n\nUsing these tools, if the current price is higher that a moving average over past $n$ periods, the signal is \"buy\". \n\nMomentum on the other hand, in its simplest form, is just the difference in the current price and the price $n$ days ago. In other definitiions it can also be a change in the simple moving average with a scale factor of $N+1$:\n\n$\\frac{MOM}{N+1} = SMA_{today}- SMA_{yesterday}$\n\nIn trading, the indicators for both tools is given as:\n\n1. Moving average:\n$I_{t}(n) = P_{t}- MA_{n}$\n\n2. Momentum\n$I_{t}(n) = P_{t}-P_{t-n+1}$\n\nThe trader is suggested to buy if $I>0$ and sell otherwise.\n\nTo understand these concepts in financial analysis more in depth, we will look at various examples in trading. But first, we will demonstrate using the climate data that MA trends are also used in smooting time series data. After which, we will proceed with the examples on stock price analysis.\n\n### Example 5: Extracting the Trend in Climate Data Using MA\nFirst, let us try to apply MA to see a smoother trend of the temperature measurements in the climate data. Here, we will use the simple MA and the exponential MA.\n\n# 3420 data is equivalent to 1 month while 83220 is equivalent to two years, 124830 for 3 years\ndata['MA'] = data['T (degC)'].rolling(window=6840, min_periods=1).mean()\ndata['EMA'] = data['T (degC)'].ewm(span=3420, adjust=False).mean()\n\nplt.rcParams[\"figure.figsize\"] = (15,2)\ndata['T (degC)'].plot(label= 'Temp')\ndata['MA'].plot(label= '6840MA')\ndata['EMA'].plot(label= '3420EMA')\n\nplt.xlim([0, 83220])\nplt.legend(loc='upper left')\n\nLooking at our data, we can see that there is an apparent seasonal trend of temperature measurements and at this point, we might be interested to know which among the factors in the data are causing this trend in temperature. This concept is called causation and it will be discussed at a later chapter in this book.\n\n### Momentum Strategies\nMomentum is used as a measure of strength of the current or future trend regardless of the direction, i.e., whether it will go up or down. It is purely a technical analysis technique and does not consider the fundamentals of the company. Traders use momentum strategy for short-term, when the trends are strong or when the price action momentum is high. An indicator of high momentum is the price advancing or declining over a wide range in a short period of time. High levels of momentum indicates increased volatility, too.\n\nMomentum investors tries to understand and anticipate the behavior of the market, since awareness of the biases and emotions of other investors make the momentum investing strategy to work better.\n\n#### How to apply momentum strategy:\n1. A trader checks the existence of trends using indicators such as trend lines, moving averages, and  ADX to identify the existence of a trend.\n2. As the trend gains momentum – strengthens – the trader decides what position to take following the direction of the trend (buy an uptrend; sell a downtrend).\n3. A trader exits when the momentum of the trend shows signs of weakening. Divergence between price action and the movement of momentum indicators such as the MACD or RSI is a usual indicator.\n\n### Example 6: Momentum Trading Strategy Using Two MA's\nAs mentioned above, momentum strategy can be applied after checking for trends using moving averages. SMA and EMA are widely used in technical analysis of stock prices and in generating buy/sell signals. The basic idea is to use two different windows (short and long observation window) and see where the two MA's cross over. A shorter window reacts faster to price changes than a longer window. Thus if MA(n=short) > MA(n=long), the trading strategy or signal is to buy. Otherwise, the signal is to sell. \n\nSMA works fine in technical analysis however, it's behavior lags the current price by $n/2$ days. This means that the changes in the trend can only be seen after the lag days making the strategy being delayed. EMA reduces this lag significantly as weights are decaying exponentially. The same strategy of looking for crossovers between two EMAs with short and long window of observation is always applied, i.e., a signal to buy is generated when the EMA with shorter window crosses above the EMA with longer observation window.\n\nNow let us demonstrate this idea using the Netflix data on how to use MA and EMA in making signals or decisions whether to buy or sell the stock.\n\n\n# Recall Netflix data we used above in forecasting using linear regression (LR)\nplt.rcParams[\"figure.figsize\"] = (15,2)\nprice.plot()\nplt.ylabel('Price')\n\nWe will use window size of n=25 for the short MA and n=65 for the long MA.\n\n## In pandas, the rolling windows is available in computing for the mean of a window sized-n. \nprice['20MA'] = price['Close'].rolling(window=20, min_periods=1).mean()\nprice['65MA'] = price['Close'].rolling(window=65, min_periods=1).mean()\n\nWe will try to locate the crossover of the two MAs and create an 'indicator' of crossover. Note that this indicator is not exactly the same as the indicator \"I\" discussed above. Afterwhich, we will create our strategy based on the generated indicators.. The strategy is based on the movement of price.\n\nIf MA20> MA65, we have indicator equal to +1.0, otherwise indicator equal to 0.0. Once there is a crossover, there is a reversal of the positions of MA20 and MA65. Thus getting the difference between the indicators ($I_{diff} = I_{t} - I{t-1}$) for two consecutive times will tell us if the reversal is positive (buy) or negative (sell).\n\nprice['Indicator'] = 0.0\nprice['Indicator'] = np.where(price['20MA']> price['65MA'], 1.0, 0.0)\n\n# To get the difference of the indicators, we use function diff in pandas.\nprice['Decision'] = price['Indicator'].diff()\n# print(price)\n\n#Decision=+1 means buy, while Decision=-1 means sell\n# plotting them all together \nprice['Close'].plot(label= 'Close')\nprice['20MA'].plot(label = '20MA')\nprice['65MA'].plot(label = '65MA')\n\nplt.plot(price[price['Decision'] == 1].index, price['20MA'][price['Decision'] == 1], '^', markersize = 10, color = 'g' , label = 'buy')\nplt.plot(price[price['Decision'] == -1].index, price['20MA'][price['Decision'] == -1],  'v', markersize = 10, color = 'r' , label = 'sell')\nplt.legend(loc='upper left')\n\nUsing two MA's and getting their crossover or difference as indicator, we can decide whether to buy (green) the stock or sell (red). We can do the same process we did above using EMA.\n\n# In pandas, the rolling window equivalent for EMA is \nprice['20EMA'] = price['Close'].ewm(span=20, adjust=False).mean()\nprice['65EMA'] = price['Close'].ewm(span=65, adjust=False).mean()\n\n# Like how we used MA above, we will try to locate the crossover of the two EMAs and create an indicator of crossover \nprice['Indicator_EMA'] = 0.0\nprice['Indicator_EMA'] = np.where(price['20EMA']> price['65EMA'], 1.0, 0.0)\n\nprice['Decision_EMA'] = price['Indicator_EMA'].diff()\n# print(price)\n\n# Decision=+1 means buy, while Decision=-1 means sell\n# plotting them all together \nplt.rcParams[\"figure.figsize\"] = (15,2)\nprice['Close'].plot(label= 'Close')\nprice['20EMA'].plot(label = '20EMA')\nprice['65EMA'].plot(label = '65EMA')\n\nplt.plot(price[price['Decision_EMA'] == 1].index, price['20EMA'][price['Decision_EMA'] == 1], '^', markersize = 10, color = 'g' , label = 'buy')\nplt.plot(price[price['Decision_EMA'] == -1].index, price['20EMA'][price['Decision_EMA'] == -1],  'v', markersize = 10, color = 'r' , label = 'sell')\nplt.legend(loc='upper left')\n\nFor this case, the momentum indicators generally helps us generate decisions whether to buy or not. The crossover is a sign of reversal of trend. In the context of technical analysis, \"To buy\" predicts that the price will increase, while \"To Sell\" predicts that the price will decrease.\n\nThese tools work in general but there are more sophisticated tools that can be used in doing technical analysis.\n\n\n### Example 7: Momentum Trading Strategy Using MACD\nThere are many Momentum Trading Strategies that can be used. In this example, we will use the Moving Average Convergence Divergence (MACD). MACD is one of the most popular momentum indicators, which makes use of the difference between two exponential moving averages (12-day and 26-day) and compare it with EMA (9-day) of MACD.\n\n#### MACD Indicators\n1. bullish crossover (buy) -  occurs when MACD crosses above the signal line. \n2. bearish signal (sell) - MACD crosses below the signal line. \n3. overbought or oversold - crossover has a high sloping MACD, depending on if the crossover is bullish or bearish respectively. A correction or reversal of direction will soon follow.\n4. on movement - weak movement, indicated by the small slope of MACD has a high chance to correct while a strong movement highly probable to continue.\n\n\nprice['exp1'] = price['Close'].ewm(span=12, adjust=False).mean()\nprice['exp2'] = price['Close'].ewm(span=26, adjust=False).mean()\nprice['macd'] = price['exp1']-price['exp2']\nprice['exp3'] = price['macd'].ewm(span=9, adjust=False).mean()\n\nprice['macd'].plot(color = 'g', label = 'MACD')\nprice['exp3'].plot(color = 'r', label = 'Signal')\nplt.legend(loc='upper left')\n\nplt.show()\n\n\n# Like how we used MA above, we will try to locate the crossover of the MACD and the Signal and plot the indicators \nprice['Indicator_MACD'] = 0.0\nprice['Indicator_MACD'] = np.where(price['macd']> price['exp3'], 1.0, 0.0)\n\nprice['Decision_MACD'] = price['Indicator_MACD'].diff()\n# print(price)\n\nprice['macd'].plot(color = 'g', label = 'MACD')\nprice['exp3'].plot(color = 'r', label = 'Signal')\nplt.legend(loc='upper left')\n\nplt.plot(price[price['Decision_MACD'] == 1].index, price['macd'][price['Decision_MACD'] == 1], '^', markersize = 10, color = 'g' , label = 'buy')\nplt.plot(price[price['Decision_MACD'] == -1].index, price['macd'][price['Decision_MACD'] == -1],  'v', markersize = 10, color = 'r' , label = 'sell')\nplt.legend(loc='upper left')\n\nIn the plot above, we can see the approximate dates where a bullish (buy) and bearish (sell) crossover happened. Now we want to examine the strength and identify overbought and oversold conditions. Here we use the same parameters, but we plot the original price and its MACD.\n\nprice['Close'].plot(color = 'k', label= 'Close')\nprice['macd'].plot(color = 'g', label = 'MACD')\nplt.show()\n\nHere, MACD stays somehow flat but notice that there are times where the MACD curve is steeper than other times, indicative of overbought or oversold conditions (e.g. before 2020-04).  Zooming-in to the MACD plot to see the slopes, we have the ff:\n\nfig, axs = plt.subplots(2, figsize=(15, 4), sharex=True)\naxs[0].set_title('Close Price')\naxs[1].set_title('MACD')\naxs[0].plot(price['Close'], label='Close')\naxs[1].plot(price['macd'], label='macd')\naxs[1].set(xlabel='Date')\nplt.show()\n\nFrom the above plots, the steep slopes of MACD happened before 2020-04 (oversold) and 2020-10 (overbought). Note that there are still some steep sloped in MACD after 2020-07 and could be indicative of other instances of overbuying and overselling. \n\nFinally, as discussed above, there are other momentum indicators that are used in trading such as RSI and ADX. The reader is left to explore on them following the procedure presented in this notebook.\n\n## Summary\nIn this chapter we discussed and demonstrated how we can use forecasting tools such as linear, trend, and momentum. Compared to the previous chapter, we noted here that there is no need to check for the stationarity of the time series and there is no need for differencing. We also showed that linear regression (and multi-variate LR) is limited and performs poorly when applied to some data. Finally we emphasized that while other forecasting tools require the removal of trends, in this notebook we showed that trends can be utilized to predict the future direction of the data.\n\n## Preview to the next chapter...\nAs simple as it is, the forecasting methods discussed here are not applicable in many other cases. Following our discussion, the next chapters will provide better forecasting models. In Chapter 3, the concept of vector autoregressive model (VAR) which is pressumed to be a better tool in forecasting time series data as it can incorportate information from the previous time step of another data, will be discussed. \n\n\n\n\n## References\nThe discussions in this notebook were made with the help of the following references\n* https://www.tandfonline.com/doi/pdf/10.1080/14697688.2020.1716057?needAccess=true\n* https://towardsdatascience.com/introduction-to-linear-regression-in-python-c12a072bedf0\n* https://ucilnica.fri.uni-lj.si/mod/resource/view.php?id=28089\n* https://otexts.com/fpp2/autocorrelation.html\n* https://www.w3schools.com/python/python_ml_multiple_regression.asp\n* https://www.analyticsvidhya.com/blog/2016/02/time-series-forecasting-codes-python/\n* https://towardsdatascience.com/making-a-trade-call-using-simple-moving-average-sma-crossover-strategy-python-implementation-29963326da7a\n* https://www.investopedia.com/articles/trading/09/linear-regression-time-price.asp\n* https://medium.com/@harishreddyp98/regularization-in-python-699cfbad8622\n* https://stackabuse.com/linear-regression-in-python-with-scikit-learn/\n* https://corporatefinanceinstitute.com/resources/knowledge/trading-investing/momentum-investing/\n\n", "meta": {"hexsha": "d81cd469f5d28944fbfe22ea83f7a2c7a4312240", "size": 40977, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/02_LinearForecastingTrendandMomentumForecasting/02_LinearTrendandMomentumForecasting.py", "max_stars_repo_name": "phdinds-aim/time_series_handbook", "max_stars_repo_head_hexsha": "9d22cf901c094035934359e2cbe98183b0cb41e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-02-15T12:27:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T21:50:02.000Z", "max_issues_repo_path": "_build/jupyter_execute/02_LinearForecastingTrendandMomentumForecasting/02_LinearTrendandMomentumForecasting.py", "max_issues_repo_name": "leolorenzoii/time_series_handbook", "max_issues_repo_head_hexsha": "88e5763886043104f916ccd4b13c719f181603c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-08T07:56:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-30T11:34:35.000Z", "max_forks_repo_path": "_build/jupyter_execute/02_LinearForecastingTrendandMomentumForecasting/02_LinearTrendandMomentumForecasting.py", "max_forks_repo_name": "leolorenzoii/time_series_handbook", "max_forks_repo_head_hexsha": "88e5763886043104f916ccd4b13c719f181603c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2021-02-04T16:36:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T14:53:04.000Z", "avg_line_length": 53.1478599222, "max_line_length": 580, "alphanum_fraction": 0.7446860434, "include": true, "reason": "import numpy,import scipy,from scipy,import statsmodels,from statsmodels", "num_tokens": 10360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556619, "lm_q2_score": 0.9196425350319858, "lm_q1q2_score": 0.8690573336902614}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n# src: https://www.kaggle.com/mchirico/linear-programming\n\n\n# In[9]:\n\n\nimport matplotlib.pyplot as plt\n\n\n# In[1]:\n\n\n# scipy.linprog \n# https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html\n\n\n# In[2]:\n\n\n# Consider the following problem:\n# Minimize: f = -1x[0] + 4x[1]\n# Subject to:\n# -3x[0] + 1x[1] <= 6\n# 1x[0] + 2x[1] <= 4\n# x[1] >= -3\n# -inf <= x[0] <= +inf\n\nc = [-1, 4]  # minimize function\nA = [ [-3, 1], [1, 2] ]  # subject to 1, 2\nb = [6, 4]  # subject to 1, 2 (free term)\n\nx0_bounds = (None, None)\nx1_bounds = (-3, None)\n\n\n# In[7]:\n\n\nfrom scipy.optimize import linprog\n\nresult = linprog(\n    c,  # coeffs of the linear objective function to be minimized\n    A_ub=A,  # inequality constraint matrix: coeffs of a linear inequality\n    b_ub=b,  # inequality constraint vector: upper bound A_ub @ x\n    bounds=(x0_bounds, x1_bounds),  # sequence of (min, max) pairs for each element in x\n    options={'disp': True}\n)\n\ndisplay(result)\n\n\n# In[14]:\n\n\n# Example 2\n\n# A trading company is looking for a way to maximize profit per transportation of their goods.\n# The company has a train available with 3 wagons.\n# When stocking the wagons they can choose between 4 types of cargo, each with its own specifications.\n# How much of each cargo type should be loaded on which wagon in order to maximize profit?\n\ndata_matrix = [['Train Wagon', 'Item Capacity', 'Space Capacity'],\n               ['w1', 10, 5000],\n               ['w2', 8, 4000],\n               ['w3', 12, 8000],]\n\ndata_matrix_2 = [['Cargo<br>Type', '#Items Available', 'Volume','Profit'],\n               ['c1', 18, 400,2000],\n               ['c2', 10, 300,2500],\n               ['c3', 5, 200,5000],\n               ['c4', 20, 500,3500]]\n\n# Objective function\n# max: +2000 C1 +2500 C2 +5000 C3 +3500 C4 +2000 C5 +2500 C6 +5000 C7 +3500 C8 +2000 C9 +2500 C10 +5000 C11 +3500 C12;\n# Flip sign above to get MIN PROBLEM\n\n# Constraints\n# +C1 +C2 +C3 +C4 <= 10;\n# +C5 +C6 +C7 +C8 <= 8;\n# +C9 +C10 +C11 +C12 <= 12;\n# +400 C1 +300 C2 +200 C3 +500 C4 <= 5000;\n# +400 C5 +300 C6 +200 C7 +500 C8 <= 4000;\n# +400 C9 +300 C10 +200 C11 +500 C12 <= 8000;\n# +C1 +C5 +C9 <= 18;\n# +C2 +C6 +C10 <= 10;\n# +C3 +C7 +C11 <= 5;\n# +C4 +C8 +C12 <= 20;\n\n# What if we get rid of item constraint?\n# Change min to max\nc = [-2000,-2500,-5000,-3500,-2000,-2500,-5000,-3500,-2000,-2500,-5000,-3500]\nxb=[]\nfor i in range(0,12):\n    xb.append((0, None))\n\nA = [\n     [400,300,200,500,0,0,0,0,0,0,0,0,],\n     [0,0,0,0,400,300,200,500,0,0,0,0,],\n     [0,0,0,0,0,0,0,0,400,300,200,500],\n     [1,0,0,0,1,0,0,0,1,0,0,0],\n     [0,1,0,0,0,1,0,0,0,1,0,0],\n     [0,0,1,0,0,0,1,0,0,0,1,0],\n     [0,0,0,1,0,0,0,1,0,0,0,1],\n    ]    \n\nb = [5000,4000,8000,18,10,5,20]\n\nres = linprog(c, A_ub=A, b_ub=b, bounds=xb,\n              options={\"disp\": True})\nprint(res)\n\n", "meta": {"hexsha": "2890fe326865c064586dd726a032dc5055f51b9c", "size": 2847, "ext": "py", "lang": "Python", "max_stars_repo_path": "AI/others/math/LinProg/lin_prog_example.py", "max_stars_repo_name": "honchardev/Fun", "max_stars_repo_head_hexsha": "ca7c0076e9bb3017c5d7e89aa7d5bd54a83c8ecc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AI/others/math/LinProg/lin_prog_example.py", "max_issues_repo_name": "honchardev/Fun", "max_issues_repo_head_hexsha": "ca7c0076e9bb3017c5d7e89aa7d5bd54a83c8ecc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-03-24T16:26:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-15T19:40:41.000Z", "max_forks_repo_path": "AI/others/math/LinProg/lin_prog_example.py", "max_forks_repo_name": "honchardev/Fun", "max_forks_repo_head_hexsha": "ca7c0076e9bb3017c5d7e89aa7d5bd54a83c8ecc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1271186441, "max_line_length": 118, "alphanum_fraction": 0.5820161574, "include": true, "reason": "from scipy", "num_tokens": 1127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476944, "lm_q2_score": 0.9136765210631689, "lm_q1q2_score": 0.8690363183955503}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\n\n# X = np.array([\n#   [  -2.500000000000001,   -1.873333333333334],\n#   [  0.2333333333333325, 0.026666666666666394],\n#   [  0.8666666666666663,   0.8266666666666662],\n#   [ -1.7000000000000006,  -1.1733333333333338],\n#   [  3.1000000000000005,   2.1933333333333334]\n# ])\n\n# X = np.array([ [0, 0], [1, 1], [2, 2], [3, 3] ])\n\nX = np.array([ [0, 1], [1, 1], [2, 1], [3, 0.5] ])\n\n# normalize by mean.\nX = np.subtract(X, np.mean(X, axis=0))\n\ncov_mat = np.cov(X.T)\nprint \"cov mat:\", cov_mat\nsvd_val, svd_vec = np.linalg.eig(cov_mat)\n\nprint \"SVD eigen vals:\", svd_val\nprint \"SVD eigen vec[0]:\", svd_vec[:,0]\nprint \"SVD eigen vec[1]:\", svd_vec[:,1]\n\nsvd_vec = np.array([ svd_vec[:,0], svd_vec[:,1] ])\n\n\npca = PCA(n_components=2)\npca.fit(X)\n\n# print \"explained variance \"\n# print pca.explained_variance_ratio_\n\n# PCA eigen vectors\npca_vec = pca.components_\n\nprint \"PCA eigen vals:\", pca.explained_variance_ratio_\nprint \"PCA eigen vec[0]:\", pca_vec[0]\nprint \"PCA eigen vec[1]:\", pca_vec[1]\n\n\ndef plot(eig_vec):\n  plt.plot(X[:,0], X[:,1], 'ro')\n  plt.plot([0], [0], 'bo')\n\n  plt.quiver(eig_vec[0, 0], eig_vec[0, 1], angles='xy', scale_units='xy', scale=1, color='blue')\n  plt.quiver(eig_vec[1, 0], eig_vec[1, 1], angles='xy', scale_units='xy', scale=1, color='green')\n\n  plt.xlim([-4,4])\n  plt.ylim([-4,4])\n\n  plt.aspect = 'equal'\n\nfig = plt.figure(1)\nplot(svd_vec)\nfig = plt.figure(2)\nplot(pca_vec)\nplt.show()\n\n", "meta": {"hexsha": "78f5ee72a04e64097c7993aad363b507215595d1", "size": 1491, "ext": "py", "lang": "Python", "max_stars_repo_path": "client/explanations/principal-component-analysis/verify.py", "max_stars_repo_name": "klezm/explained-visually", "max_stars_repo_head_hexsha": "33009aa918cb5ab8dc09ad14f6cf427072e6750c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 946, "max_stars_repo_stars_event_min_datetime": "2015-04-24T18:38:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T15:04:42.000Z", "max_issues_repo_path": "client/explanations/principal-component-analysis/verify.py", "max_issues_repo_name": "ccampell/explained-visually", "max_issues_repo_head_hexsha": "d900fe18c9962a04ac17c7e8933ea363ab227989", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2015-04-24T20:02:23.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-06T04:02:51.000Z", "max_forks_repo_path": "client/explanations/principal-component-analysis/verify.py", "max_forks_repo_name": "ccampell/explained-visually", "max_forks_repo_head_hexsha": "d900fe18c9962a04ac17c7e8933ea363ab227989", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 85, "max_forks_repo_forks_event_min_datetime": "2015-04-25T20:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T21:16:11.000Z", "avg_line_length": 23.6666666667, "max_line_length": 97, "alphanum_fraction": 0.6418511066, "include": true, "reason": "import numpy", "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.9136765157744067, "lm_q1q2_score": 0.8690363120998028}}
{"text": "import numpy as np\nfrom numpy.polynomial import polynomial as p\nfrom numpy.polynomial import Polynomial as P\nimport matplotlib.pyplot as plt\nimport math\n\n\ndef get_test_data(x):\n#    return x**3\n    return math.e**-x + x**2 - 2\n\n\ndef get_lagrange(y, x):\n    poly = [0]\n\n    for i in range(0, y.size):\n        poly_add = [y[i]]\n\n        for j in range(0, x.size):\n            if i != j:\n                poly_add = p.polymul(poly_add, [-x[j], 1] / (x[i] - x[j]))\n\n        poly = p.polyadd(poly, poly_add)\n\n    return poly\n\n\ndef get_divided_diffs(y, h):\n    div_diffs = np.zeros((y.size, y.size))\n    div_diffs[:,0] = y\n\n    for i in range(1, y.size):\n        for j in range(0, y.size - i):\n            div_diffs[j, i] = (div_diffs[j, i-1] - div_diffs[j+1, i-1]) / (-h * i)\n\n    return div_diffs\n\n\ndef get_newton(y, x):\n    div_diffs = get_divided_diffs(y, x[1] - x[0])\n    #print(div_diffs)\n\n    # Forward formula\n    poly = [0]\n\n    for i in range(0, x.size):\n        #print(\"add\", div_diffs[0, i])\n        poly_add = [div_diffs[0, i]]\n\n        for j in range(0, i):\n            #print(\"mult by\", [-x[j], 1])\n            poly_add = p.polymul(poly_add, [-x[j], 1])\n\n        poly = p.polyadd(poly, poly_add)\n\n    return poly\n\n\ndef get_spline(y, x):\n    tridiag_a = np.zeros((x.size - 2, x.size - 2))\n    b = np.empty(x.size - 2)\n\n    for i in range(0, x.size - 2):\n        b[i] = (y[i+2] - y[i+1]) / (x[i+2] - x[i+1]) - (y[i+1] - y[i]) / (x[i+1] - x[i])\n        if i > 0:\n            tridiag_a[i, i-1] = (x[i+1] - x[i]) / 6\n        tridiag_a[i, i] = (x[i+2] - x[i]) / 3\n        if i < x.size - 3:\n            tridiag_a[i, i+1] = (x[i+2] - x[i+1]) / 6\n\n    m = np.linalg.solve(tridiag_a, b)\n    m = np.insert(m, 0, 0)\n    m = np.insert(m, m.size, 0)\n\n    polys = []\n\n    for i in range(0, x.size - 1):\n        poly = P([0])\n        h = x[i+1] - x[i]\n        poly += P([x[i+1], -1]) ** 3 * (m[i] / (6 * h))\n        poly += P([-x[i], 1]) ** 3 * (m[i+1] / (6 * h))\n        poly += P([x[i+1], -1]) * ((y[i] - m[i] * h * h / 6) / h)\n        poly += P([-x[i], 1]) * ((y[i+1] - m[i+1] * h * h / 6) / h)\n        \n        polys.append(poly.coef)\n\n    return polys\n                \n\nn = 9\nx = np.linspace(-4, 4, n)\ny = get_test_data(x)\n\n\nreal = np.linspace(-4, 4, 100)\n\n\ndef prepare_figure(scatter_x, scatter_y):\n    # Draw axes at the center\n    fig = plt.figure()\n    ax = fig.add_subplot(1, 1, 1)\n    ax.spines['left'].set_position('center')\n    ax.spines['bottom'].set_position('zero')\n    ax.spines['right'].set_color('none')\n    ax.spines['top'].set_color('none')\n    ax.xaxis.set_ticks_position('bottom')\n    ax.yaxis.set_ticks_position('left')\n\n    plt.scatter(scatter_x, scatter_y)\n\n\nlagrange_poly = get_lagrange(y, x)\n#lagrange_poly = p.polytrim(lagrange_poly, 0.0001)\nprint(\"Lagrange polynomial:\", lagrange_poly)\n\nprepare_figure(x, y)\nplt.plot(real, p.polyval(real, lagrange_poly))\nplt.show()\n\n\nnewton_poly = get_newton(y, x)\nprint(\"Newton polynomial:\", newton_poly)\n\nprepare_figure(x, y)\nplt.plot(real, p.polyval(real, newton_poly))\nplt.show()\n\n\nprint(\"Natural cubic splines:\")\n\nspline_polys = get_spline(y, x)\n\nprepare_figure(x, y)\nfor i in range(0, n - 1):\n    x_lower = -4 + (8 / (n-1)) * i\n    x_upper = -4 + (8 / (n-1)) * (i+1)\n    x_interval = np.linspace(x_lower, x_upper, 50)\n    print(\"{0} for [{1}; {2}]\".format(spline_polys[i], x_lower, x_upper))\n    plt.plot(x_interval, p.polyval(x_interval, spline_polys[i]))\nplt.show()\n\n\nprint(max(abs(p.polyval(real, lagrange_poly) - get_test_data(real))))\nprint(max(abs(p.polyval(real, newton_poly) - get_test_data(real))))\n\n", "meta": {"hexsha": "ec5ad305a9eac79818d510b0317da71dc418adee", "size": 3572, "ext": "py", "lang": "Python", "max_stars_repo_path": "semester5/num-methods/lab4/lab4.py", "max_stars_repo_name": "gardenappl/uni", "max_stars_repo_head_hexsha": "5bc7110946caf16aae2a0c1ddae4e88bfbb25aa8", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "semester5/num-methods/lab4/lab4.py", "max_issues_repo_name": "gardenappl/uni", "max_issues_repo_head_hexsha": "5bc7110946caf16aae2a0c1ddae4e88bfbb25aa8", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "semester5/num-methods/lab4/lab4.py", "max_forks_repo_name": "gardenappl/uni", "max_forks_repo_head_hexsha": "5bc7110946caf16aae2a0c1ddae4e88bfbb25aa8", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4657534247, "max_line_length": 88, "alphanum_fraction": 0.5506718925, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142221377825, "lm_q2_score": 0.9136765151867664, "lm_q1q2_score": 0.8690363102754911}}
{"text": "from scipy import optimize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport math\nfrom methods import *\nfrom pprint import pprint\n\ndef F(x):\n    return (4 - 2.1*x[0]**2 + 1/3*x[0]**4)*x[0]**2 + x[0]*x[1] + 4 * (x[1]**2 - 1) * x[1]**2\n\ndef g_1_plus(x):\n    return max(0, x - 3)\ndef g_2_plus(x):\n    return max(0, -3 - x)\ndef g_3_plus(x):\n    return max(0, x - 2)\ndef g_4_plus(x):\n    return max(0, -2 - x)\n\ndef g_1(x):\n    return  x - 3\ndef g_2(x):\n    return  -3 - x\ndef g_3(x):\n    return x - 2\ndef g_4(x):\n    return -2 - x\n\n\ndef Q(c):\n    def Q_call(x):\n        f_x_eval = F(x)\n    \n        eval_cond = []\n\n        eval_cond.append(g_1_plus(x[0]))\n        eval_cond.append(g_2_plus(x[0]))\n        eval_cond.append(g_3_plus(x[1]))\n        eval_cond.append(g_4_plus(x[1]))\n        \n        sum = 0\n        for i in eval_cond:\n            sum += i\n\n        return f_x_eval + c * sum\n    \n    return Q_call\n\n\ndef R(miu):\n    def R_call(x):\n        f_x_eval = F(x)\n        \n        eval_cond = []\n\n        eval_cond.append(g_1(x[0]))\n        eval_cond.append(g_2(x[0]))\n        eval_cond.append(g_3(x[1]))\n        eval_cond.append(g_4(x[1]))\n        \n        sum = 0\n        for i in eval_cond:\n            sum += i\n\n        \n        return f_x_eval + miu * sum\n    \n    return R_call\n\n\ndef omega(x):\n    if x[0] >= -3 and x[0] <= 3 and x[1] >= -2 and x[1] <= 2:\n            return True\n    return False\n\ndef plot():\n    x_v = np.arange(-3, 3, 0.01)\n    y_v = np.arange(-2, 2, 0.01)\n\n    x = []\n    y = []\n    z = []\n    for i in x_v:\n        for j in y_v:\n            x.append(i)\n            y.append(j)\n            z.append(F([i, j]))\n\n    plt.scatter(x, y, c=z)\n    plt.show()\n\nif __name__ == '__main__':\n    # plot()\n    \n    # ans = Penalization_method(\"BFGS\", Q, omega, x0=np.array([1, 5]), c0=1, alpha=1.5, epsilon=0.001, k_max=500)\n    ans = Barrier_method(\"BFGS\", R, x0=np.array([-1,1]), miu_0=1, alpha=0.5, epsilon=0.001, k_max=500)\n    # print(\"Penalization Method\")\n    print(F(ans[\"1.Result\"]))\n    pprint(ans)\n    # print()\n    # print(\"Barrier Method\")\n    # pprint(ans)\n    # print()\n    # print(\"SQP Method\")\n    # print(SQP_method(F, x0=np.array([-0.8,0.7]), bounds=[(-3,3), (-2,2)], k_max=500))\n", "meta": {"hexsha": "700a3269ef83292f1134ef8f03fa8df091047595", "size": 2225, "ext": "py", "lang": "Python", "max_stars_repo_path": "LAB4/ej_18.py", "max_stars_repo_name": "codersUP/MO-Labs", "max_stars_repo_head_hexsha": "1df2639e762893a6c5c64fdeece1940b8f0b24e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LAB4/ej_18.py", "max_issues_repo_name": "codersUP/MO-Labs", "max_issues_repo_head_hexsha": "1df2639e762893a6c5c64fdeece1940b8f0b24e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LAB4/ej_18.py", "max_forks_repo_name": "codersUP/MO-Labs", "max_forks_repo_head_hexsha": "1df2639e762893a6c5c64fdeece1940b8f0b24e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9905660377, "max_line_length": 113, "alphanum_fraction": 0.5096629213, "include": true, "reason": "import numpy,from scipy", "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347875615795, "lm_q2_score": 0.8918110555020056, "lm_q1q2_score": 0.8690117164131648}}
{"text": "import numpy as np\na = [[2 , 2] ,[2 , 2.0005]]\nb = [[6], [6.001]]\nsolution = np.dot(np.linalg.inv(a),b)\n#solution 1\nprint(solution)\n#########################################################\na1 = [[2,2] , [2 , 2.001]]\nsolution2 = np.dot(np.linalg.inv(a1),b)\nprint(solution2)\n# Solution 2\nrelative_error_coeff = (np.linalg.norm(np.array(a)- np.array(a1)))/np.linalg.norm(a)\nprint(relative_error_coeff)\nrelative_error_solution = (np.linalg.norm(np.array(solution) - np.array(solution2)))/np.linalg.norm(solution)\nprint(relative_error_solution)\nprint(\"Cond A\", np.linalg.cond(a))\nprint(\"Cond A1\",np.linalg.cond(a1))\nprint(\"Sensitivity being \",relative_error_solution/relative_error_coeff) \n#Comparing the condition number we can say that they are ill posed problems\n#Also a small error in A creates a large error in the soltion, x ( by the errors found in the above code)\n", "meta": {"hexsha": "d6308c007e20eaf902603e42268e1c5dc08547e4", "size": 868, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab 1/1.py", "max_stars_repo_name": "Shivvrat/Computer-Vision", "max_stars_repo_head_hexsha": "9f8fd63449703b3325362dd61004afd285515cd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab 1/1.py", "max_issues_repo_name": "Shivvrat/Computer-Vision", "max_issues_repo_head_hexsha": "9f8fd63449703b3325362dd61004afd285515cd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab 1/1.py", "max_forks_repo_name": "Shivvrat/Computer-Vision", "max_forks_repo_head_hexsha": "9f8fd63449703b3325362dd61004afd285515cd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3333333333, "max_line_length": 109, "alphanum_fraction": 0.6820276498, "include": true, "reason": "import numpy", "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347890464284, "lm_q2_score": 0.8918110468756548, "lm_q1q2_score": 0.8690117093315533}}
{"text": "'''菲波那切数列.'''\n\n\ndef fib_recr(n):\n    '''\n\n    >>> fib_recr(10)\n    55\n    '''\n    if n in (0, 1):\n        return n\n    return fib_recr(n - 1) + fib_recr(n - 2)\n\n\ndef fib_iter(n):\n    '''\n\n    >>> fib_iter(10)\n    55\n    '''\n    a, b = 0, 1\n    for _ in range(n - 1):\n        a, b = b, a + b\n    return b\n\n\ndef fib_matrix(n):\n    '''Using matrix to calculate the nth fibonaci number.\n\n    >>> fib_matrix(10)\n    55\n    '''\n    import numpy\n    return (numpy.matrix([[1, 1], [1, 0]]) ** (n - 1) * numpy.matrix([[1], [0]]))[0, 0]\n\n\ndef fibonacci_sequence(n):\n    '''\n\n    >>> fibonacci_sequence(10)\n    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n    '''\n    return [fib_recr(x) for x in range(n)]\n", "meta": {"hexsha": "d75db0c8c1db10024051aa41effb0ea65c0a32ba", "size": 685, "ext": "py", "lang": "Python", "max_stars_repo_path": "maxingmin/question4.py", "max_stars_repo_name": "loongoo/GitDemo", "max_stars_repo_head_hexsha": "7098edab6581dfd12d9b966154762f314410902a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "maxingmin/question4.py", "max_issues_repo_name": "loongoo/GitDemo", "max_issues_repo_head_hexsha": "7098edab6581dfd12d9b966154762f314410902a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maxingmin/question4.py", "max_forks_repo_name": "loongoo/GitDemo", "max_forks_repo_head_hexsha": "7098edab6581dfd12d9b966154762f314410902a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.5681818182, "max_line_length": 87, "alphanum_fraction": 0.4729927007, "include": true, "reason": "import numpy", "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154280587323, "lm_q2_score": 0.9059898235563418, "lm_q1q2_score": 0.8689840174326188}}
{"text": "import math\nimport numpy as np\n\ndef f(x):\n    return math.exp(-x ** 2)\n\ndef simps(f, a, b, n):\n\n    h = (b - a) / n\n    if n % 2 != 0 or n <= 0:\n        raise ValueError(\"n tem de ser par e positivo\")\n\n    soma_odd, soma_even = 0, 0\n    for k in range(1 ,n, 2):\n        soma_odd += f(a + k * h)\n    for k in range(2, n, 2):\n        soma_even += f(a + k * h)\n    return (h / 3) * (f(a) + 4 * soma_odd + 2 * soma_even + f(b))\n\n\n\nif __name__ == '__main__':\n\n    # a = 0\n    # b = 1\n    # # o número de parábolas é metade de n\n    # n = 6\n    # r = simps(f, a, b, n)\n    # print(r)\n\n    # intervalo = [-0.753, 1.172]\n    # subintervalos = [2, 4, 8, 18, 42, 70, 132, 276, 552, 1096]\n    # for i in range(len(subintervalos)):\n    #     print(simps(f, intervalo[0], intervalo[1], subintervalos[i]))\n\n    x = [0.13573, 0.32679, 0.51785, 1.307905, 2.09796, 3.225485, 4.35301, 4.38408, 4.41515]\n    y = [1.67226, 2.33534, 2.81039, 2.46089, 2.0096, 2.99762, 1.3209, 1.4359, 1.56482]\n    soma = 0\n    for i in range(0,(len(x) - 2), 2):\n        if (x[i+1] - x[i]) == (x[i+2] - x[i+1]):\n            soma += ((x[i+1] - x[i]) / 3) * (y[i] + 4*y[i+1] + y[i+2])\n        else:\n            A = np.array([[x[i]**2, x[i], 1], [x[i+1]**2, x[i+1], 1], [x[i+2]**2, x[i+2], 1]])\n            B = np.array([y[i], y[i+1], y[i+2]])\n            abc = np.linalg.solve(A, B)\n            def parabola_eq(x):\n                return abc[0] * x**2 + abc[1] * x + abc[2]\n            soma += simps(parabola_eq, x[i], x[i+2], 2)\n    print(soma)\n\n", "meta": {"hexsha": "55541342b5d49d7fc879fcddfb071c3a4fac5616", "size": 1506, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/simps.py", "max_stars_repo_name": "matheusalanojoenck/ANN", "max_stars_repo_head_hexsha": "c5c8533ea5fe775265e88d4504083b435433c3e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simps.py", "max_issues_repo_name": "matheusalanojoenck/ANN", "max_issues_repo_head_hexsha": "c5c8533ea5fe775265e88d4504083b435433c3e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simps.py", "max_forks_repo_name": "matheusalanojoenck/ANN", "max_forks_repo_head_hexsha": "c5c8533ea5fe775265e88d4504083b435433c3e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5294117647, "max_line_length": 94, "alphanum_fraction": 0.4674634794, "include": true, "reason": "import numpy", "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668684574636, "lm_q2_score": 0.8856314738181875, "lm_q1q2_score": 0.8689522597735592}}
{"text": "from numpy.linalg import inv\nfrom math import sqrt\nimport matplotlib.pyplot as plt\n\ndef main():\n    print(\"Polynomial regression\")\n    #Initial Terms\n    n=6\n    m=2\n    X = [1,2,3,4,5,6]\n    Y = [1.487,2.9858,5.602,8.003,11.452,13.021]\n\n    #Sum of x and y\n    sum_x = 0\n    sum_y = 0\n    for i in range(n):\n        sum_x = sum_x + X[i]\n        sum_y = sum_y + Y[i]\n    #Sum of powers of x\n    sum_x2 = 0\n    sum_x3 = 0\n    sum_x4 = 0\n    sum_xy = 0\n    sum_x2y = 0\n    for i in range(n):\n        sum_x2 = sum_x2 + X[i]**2\n        sum_x3 = sum_x3 + X[i]**3\n        sum_x4 = sum_x4 + X[i]**4\n        sum_xy = sum_xy + X[i]*Y[i]\n        sum_x2y = sum_x2y + (X[i]**2)*Y[i]\n    #Averege\n    x_a = sum_x/n\n    y_a = sum_y/n\n\n    #matrix Mc and Mb\n    Mc = [[ n, sum_x, sum_x2 ], [ sum_x, sum_x2, sum_x3 ], [ sum_x2, sum_x3, sum_x4 ]]\n    Mb = [ sum_y, sum_xy, sum_x2y]\n\n    #Coeficients vector\n    inv_Mc = inv(Mc)\n    a = []\n    for i in range(3):\n        line = 0\n        for j in range(3):\n            line = line + inv_Mc[i][j]*Mb[j]\n        a.append(line)\n\n    #Polynomial\n    y1 = []\n    for i in range(n):\n        line = 0\n        for j in range(3):\n            line = line + a[j]*X[i]**(j)\n        y1.append(line)\n\n    #Terms St and Sr\n    St = 0\n    Sr = 0\n    for i in range(n):\n        St = St + (Y[i]-y_a)**2\n        Sr = Sr + (Y[i]-a[0]-a[1]*X[i]-a[2]*X[i]**2)**2\n    Sy_x = sqrt(Sr/(n-(m+1)))\n    \n    #Cd terms\n    Cd = (St - Sr)/St\n\n    print(f\"a0: {a[0]}\")\n    print(f\"a1: {a[1]}\")\n    print(f\"a2: {a[2]}\")\n    print(f\"Cd: {Cd}\")\n\n    #Plots\n    plt.plot( X, Y, 'go') \n    plt.plot( X, Y, 'k:', color='orange') \n\n    plt.plot( X, y1, 'r^')\n    plt.plot( X, y1, 'k--', color='blue')\n\n    plt.title(\"Polynomial Regression\")\n\n    plt.grid(True)\n    plt.xlabel(\"X\")\n    plt.ylabel(\"Y\")\n    plt.show()\n\nif __name__==\"__main__\":\n    main()", "meta": {"hexsha": "b6be8687146cb750d5bf5b4e3fdaf97288b86041", "size": 1846, "ext": "py", "lang": "Python", "max_stars_repo_path": "CCI/Polynomial_regression/regression.py", "max_stars_repo_name": "Matheus1714/Python", "max_stars_repo_head_hexsha": "71dd6de67e6bcb2deb3427b11e43e9b0ecb73665", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-18T18:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-18T18:56:10.000Z", "max_issues_repo_path": "CCI/Polynomial_regression/regression.py", "max_issues_repo_name": "Matheus1714/Python", "max_issues_repo_head_hexsha": "71dd6de67e6bcb2deb3427b11e43e9b0ecb73665", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CCI/Polynomial_regression/regression.py", "max_forks_repo_name": "Matheus1714/Python", "max_forks_repo_head_hexsha": "71dd6de67e6bcb2deb3427b11e43e9b0ecb73665", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2183908046, "max_line_length": 86, "alphanum_fraction": 0.4848320693, "include": true, "reason": "from numpy", "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9793540722737479, "lm_q2_score": 0.8872045981907006, "lm_q1q2_score": 0.868887436178057}}
{"text": "from __future__ import annotations\r\nimport numpy as np\r\nfrom numpy.linalg import inv, det, slogdet\r\nfrom scipy.stats import multivariate_normal\r\n\r\n# Written by Avinoam Nukrai, Spring 2022 Hebrew U\r\n\r\nclass UnivariateGaussian:\r\n    \"\"\"\r\n    Class for univariate Gaussian Distribution Estimator\r\n    \"\"\"\r\n    def __init__(self, biased_var: bool = False) -> UnivariateGaussian:\r\n        \"\"\"\r\n        Estimator for univariate Gaussian mean and variance parameters\r\n\r\n        Parameters\r\n        ----------\r\n        biased_var : bool, default=True\r\n            Should fitted estimator of variance be a biased or unbiased estimator\r\n\r\n        Attributes\r\n        ----------\r\n        fitted_ : bool\r\n            Initialized as false indicating current estimator instance has\r\n            not been fitted.\r\n            To be set as True in `UnivariateGaussian.fit` function.\r\n\r\n        mu_: float\r\n            Estimated expectation initialized as None. To be set in\r\n             `UnivariateGaussian.fit` function.\r\n\r\n        var_: float\r\n            Estimated variance initialized as None. To be\r\n             set in `UnivariateGaussian.fit` function.\r\n        \"\"\"\r\n        self.biased_ = biased_var\r\n        self.fitted_, self.mu_, self.var_ = False, None, None\r\n\r\n    def fit(self, X: np.ndarray) -> UnivariateGaussian:\r\n        \"\"\"\r\n        Estimate Gaussian expectation and variance from given samples\r\n\r\n        Parameters\r\n        ----------\r\n        X: ndarray of shape (n_samples, )\r\n            Training data\r\n\r\n        Returns\r\n        -------\r\n        self : returns an instance of self.\r\n\r\n        Notes\r\n        -----\r\n        Sets `self.mu_`, `self.var_` attributes according to calculated estimation (where\r\n        estimator is either biased or unbiased). Then sets `self.fitted_` attribute to `True`\r\n        \"\"\"\r\n        # raise NotImplementedError()\r\n\r\n        self.mu_ = np.mean(X)\r\n        self.fitted_ = True\r\n        if self.biased_:\r\n            self.var_ = np.var(X)\r\n        else:\r\n            self.var_ = np.var(X, ddof=1)\r\n        return self\r\n\r\n    def pdf(self, X: np.ndarray) -> np.ndarray:\r\n        \"\"\"\r\n        Calculate PDF of observations under Gaussian model with fitted estimators\r\n\r\n        Parameters\r\n        ----------\r\n        X: ndarray of shape (n_samples, )\r\n            Samples to calculate PDF for\r\n\r\n        Returns\r\n        -------\r\n        pdfs: ndarray of shape (n_samples, )\r\n            Calculated values of given samples for PDF function of N(mu_, var_)\r\n\r\n        Raises\r\n        ------\r\n        ValueError: In case function was called prior fitting the model\r\n        \"\"\"\r\n        self.fitted_ = True\r\n        return np.array((1 / (np.sqrt(2 * np.pi * self.var_)) *\r\n                         np.exp(-0.5 * ((X - self.mu_) ** 2) * self.var_)))\r\n        # raise NotImplementedError()\r\n\r\n    @staticmethod\r\n    def log_likelihood(mu: float, sigma: float, X: np.ndarray) -> float:\r\n        \"\"\"\r\n        Calculate the log-likelihood of the data under a specified Gaussian model\r\n\r\n        Parameters\r\n        ----------\r\n        mu : float\r\n            Expectation of Gaussian\r\n        sigma : float\r\n            Variance of Gaussian\r\n        X : ndarray of shape (n_samples, )\r\n            Samples to calculate log-likelihood with\r\n\r\n        Returns\r\n        -------\r\n        log_likelihood: float\r\n            log-likelihood calculated\r\n        \"\"\"\r\n        # raise NotImplementedError()\r\n        pdf_array = np.array((1 / (np.sqrt(2 * np.pi * sigma)) *\r\n                              np.exp(-0.5 * ((X - mu) ** 2) * sigma)))\r\n        sum_of_pdfs_logs = np.log(pdf_array).sum()\r\n        return sum_of_pdfs_logs\r\n\r\n\r\nclass MultivariateGaussian:\r\n    \"\"\"\r\n    Class for multivariate Gaussian Distribution Estimator\r\n    \"\"\"\r\n    def __init__(self):\r\n        \"\"\"\r\n        Initialize an instance of multivariate Gaussian estimator\r\n\r\n        Attributes\r\n        ----------\r\n        fitted_ : bool\r\n            Initialized as false indicating current estimator instance has not been fitted.\r\n            To be set as True in `MultivariateGaussian.fit` function.\r\n\r\n        mu_: float\r\n            Estimated expectation initialized as None. To be set in `MultivariateGaussian.ft`\r\n            function.\r\n\r\n        cov_: float\r\n            Estimated covariance initialized as None. To be set in `MultivariateGaussian.ft`\r\n            function.\r\n        \"\"\"\r\n        self.mu_, self.cov_ = None, None\r\n        self.fitted_ = False\r\n\r\n    def fit(self, X: np.ndarray) -> MultivariateGaussian:\r\n        \"\"\"\r\n        Estimate Gaussian expectation and covariance from given samples\r\n\r\n        Parameters\r\n        ----------\r\n        X: ndarray of shape (n_samples, )\r\n            Training data\r\n\r\n        Returns\r\n        -------\r\n        self : returns an instance of self.\r\n\r\n        Notes\r\n        -----\r\n        Sets `self.mu_`, `self.cov_` attributes according to calculated estimation.\r\n        Then sets `self.fitted_` attribute to `True`\r\n        \"\"\"\r\n        self.mu_ = np.mean(X, axis=0)\r\n        self.cov_ = np.cov(X.T)\r\n        self.fitted_ = True\r\n        return self\r\n\r\n    def pdf(self, X: np.ndarray):\r\n        \"\"\"\r\n        Calculate PDF of observations under Gaussian model with fitted estimators\r\n\r\n        Parameters\r\n        ----------\r\n        X: ndarray of shape (n_samples, )\r\n            Samples to calculate PDF for\r\n\r\n        Returns\r\n        -------\r\n        pdfs: ndarray of shape (n_samples, )\r\n            Calculated values of given samples for PDF function of N(mu_, cov_)\r\n\r\n        Raises\r\n        ------\r\n        ValueError: In case function was called prior fitting the model\r\n        \"\"\"\r\n        pdf_observe = []\r\n        for sample in X:\r\n            pdf_observe.append(1 / (np.sqrt((2 * np.pi) ** sample.size *\r\n            np.det(self.cov_))) * np.exp(-(\r\n                np.linalg.solve(\r\n                    self.cov_, sample - self.mu_).T.dot(\r\n                    sample - self.mu_)) / 2))\r\n        return pdf_observe\r\n\r\n    @staticmethod\r\n    def log_likelihood(mu: np.ndarray, cov: np.ndarray, X: np.ndarray) -> float:\r\n        \"\"\"\r\n        Calculate the log-likelihood of the data under a specified Gaussian model\r\n\r\n        Parameters\r\n        ----------\r\n        mu : float\r\n            Expectation of Gaussian\r\n        cov : float\r\n            covariance matrix of Gaussian\r\n        X : ndarray of shape (n_samples, )\r\n            Samples to calculate log-likelihood with\r\n\r\n        Returns\r\n        -------\r\n        log_likelihood: float\r\n            log-likelihood calculated\r\n        \"\"\"\r\n        sigma_cov = np.matrix(cov)\r\n        sigma_cov_det = np.linalg.det(sigma_cov)\r\n        sigma_cov_inverse = sigma_cov.I\r\n        comp1 = X.size * np.log(2 * np.pi)\r\n        comp2 = len(mu) * np.log(sigma_cov_det)\r\n        comp3 = 0\r\n        for x in X:\r\n            comp3 += np.linalg.multi_dot([(x - mu).T, sigma_cov_inverse, (x - mu)])\r\n        return -0.5 * (comp1 + comp2 + comp3)\r\n        # return np.sum(np.log(multivariate_normal.pdf(X, mu, cov)))\r\n", "meta": {"hexsha": "d475fd7906f4985bab478c94a65c02d0a94924ec", "size": 7037, "ext": "py", "lang": "Python", "max_stars_repo_path": "ex1/gaussian_estimators.py", "max_stars_repo_name": "AvinoamNukrai/IML-Course", "max_stars_repo_head_hexsha": "81e845842e6ad01ef3dd6afc4d6929a28ef057b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex1/gaussian_estimators.py", "max_issues_repo_name": "AvinoamNukrai/IML-Course", "max_issues_repo_head_hexsha": "81e845842e6ad01ef3dd6afc4d6929a28ef057b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex1/gaussian_estimators.py", "max_forks_repo_name": "AvinoamNukrai/IML-Course", "max_forks_repo_head_hexsha": "81e845842e6ad01ef3dd6afc4d6929a28ef057b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9863636364, "max_line_length": 94, "alphanum_fraction": 0.5462555066, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 1497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992895791291, "lm_q2_score": 0.8976952914230972, "lm_q1q2_score": 0.868878634826945}}
{"text": "import numpy as np\n\ndef Softplus(z):\n\t#ReLU == Rectified linear unit\n\t#This is an approximation called the softplus function - the derivitive of which is the sigmoid function\n\tsh = np.shape(z)\n\tif len(sh) == 0:\n\t\tz = np.array([z])\n\telse:\n\t\tz = np.array(z)\n#\tif np.size(z) > 1:\n#\t\tbad = np.where(z > 50)\n#\t\tgood = np.where(z <=50)\n#\t\tout = np.copy(z)\n#\t\tout[bad] = z[bad]\n#\t\tout[good] = np.log(1.0 + np.exp(z[good]))\n#\t\treturn out\n#\telse:\n#\t\tif z > 50:\n#\t\t\treturn z\n#\t\telse:\n#\t\t\treturn np.log(1.0 + np.exp(z))\n\t\n\tout = np.zeros(z.shape,dtype=z.dtype)\n\tneg = np.where(z <= 0)\n\tpos = np.where(z > 0)\n\tout[neg] = np.log(1.0 + np.exp(z[neg]))\n\tout[pos] = np.log(np.exp(-z[pos]) + 1) + z[pos]\n\treturn out\n\t\n\t\n\t\ndef SoftplusGradient(z):\n\t#ReLU == Rectified linear unit\n\t#This is an approximation called the softplus function - the derivitive of which is the sigmoid function\n\n\tsh = np.shape(z)\n\tif len(sh) == 0:\n\t\tz = np.array([z])\n\telse:\n\t\tz = np.array(z)\n#\tif np.size(z) > 1:\n#\t\tbad = np.where(z > 50)\n#\t\tgood = np.where(z <=50)\n#\t\tout = np.copy(z)\n#\t\tout[bad] = 1\n#\t\tout[good] = 1.0/(1.0 + np.exp(-z[good]))\n#\t\treturn out\n#\telse:\n#\t\tif z > 50:\n#\t\t\treturn 1\n#\t\telse:\n#\t\t\treturn 1.0/(1.0 + np.exp(-z))\n\n\tout = np.zeros(z.shape,dtype=z.dtype)\n\tneg = np.where(z < 0)\n\tpos = np.where(z >= 0)\n\tout[neg] = np.exp(z[neg])/(np.exp(z[neg]) + 1)\n\tout[pos] = 1.0/(1.0 + np.exp(-z[pos]))\n\n\treturn out\n\ndef InverseSoftplus(a):\n\tsh = np.shape(a)\n\tif len(sh) == 0:\n\t\ta = np.array([a])\n\telse:\n\t\ta = np.array(a)\t\n\t#z = np.log(np.exp(a) - 1.0)\n\t#return z\n#\treturn np.log(1 - np.exp(-a)) + a\n\tout = np.zeros(a.shape,dtype=a.dtype)\n\tneg = np.where(a < 0)\n\tpos = np.where(a >= 0)\n\tout[neg] = np.log(np.exp(a[neg]) - 1.0)\n\tout[pos] = np.log(1 - np.exp(-a[pos])) + a[pos]\n\n\treturn out\t\n\ndef InverseSoftplusGradient(a):\n\tz = InverseSoftplus(a)\n\treturn SoftplusGradient(z)\n", "meta": {"hexsha": "fcbb09db6bf8c07f649f5df40668bd71ca398b1e", "size": 1843, "ext": "py", "lang": "Python", "max_stars_repo_path": "PyNeuralNetwork/ActivationFunctions/Softplus.py", "max_stars_repo_name": "mattkjames7/PyNeuralNetwork", "max_stars_repo_head_hexsha": "edbee96aa9039d22e83253700edaf3b98d4ed9d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PyNeuralNetwork/ActivationFunctions/Softplus.py", "max_issues_repo_name": "mattkjames7/PyNeuralNetwork", "max_issues_repo_head_hexsha": "edbee96aa9039d22e83253700edaf3b98d4ed9d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyNeuralNetwork/ActivationFunctions/Softplus.py", "max_forks_repo_name": "mattkjames7/PyNeuralNetwork", "max_forks_repo_head_hexsha": "edbee96aa9039d22e83253700edaf3b98d4ed9d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2048192771, "max_line_length": 105, "alphanum_fraction": 0.584915898, "include": true, "reason": "import numpy", "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.9252299570920386, "lm_q1q2_score": 0.8688138931166679}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plot\nimport math\n\n\ndef func(x):\n    return math.sin(x) - 2 * x * x + 0.5\n\n\ndef first_func(x):\n    return math.sin(x)\n\n\ndef second_func(x):\n    return 2 * x * x - 0.5\n\n\ndef lin_func(x):\n    return math.sqrt((math.sin(x) + 0.5) / 2.0)\n\n\ndef lin_deriv(x):\n    return math.cos(x) / math.sqrt((math.sin(x) + 0.5) * 8)\n\n\ndef simple_iter(root_range, eps, sign):\n    begin, end = root_range\n    print(f'Lurking for root in {root_range}')\n\n    q = max([abs(lin_deriv(x)) for x in np.arange(begin, end, eps)])\n    print(f'q = {q}')\n\n    if q >= 1.0:\n        print(f'bad range, q = {q}! It should be < 1 exiting!')\n        exit()\n\n    coeff = q / (1 - q)\n    print(f'coeff = {coeff}')\n    iters = 1\n\n    x_prev = (begin + end) / 2.0\n    print(f'x_{iters - 1} = {x_prev}')\n    x_cur = lin_func(x_prev) * sign\n    diff = abs(x_cur - x_prev) * coeff\n    print(f'|x_{iters} - x_{iters - 1}| * coeff = {diff}')\n\n    while diff >= eps:\n        x_prev = x_cur\n        x_cur = lin_func(x_prev) * sign\n        iters += 1\n        print(f'x_{iters - 1} = {x_prev}')\n        print(f'x_{iters} = {x_cur}')\n        diff = abs(x_cur - x_prev) * coeff\n        print(f'|x_{iters} - x_{iters - 1}| * coeff = {diff}')\n\n    return x_cur, iters\n\n\ndef newthon_solve(root_range, start_x, first_deriv, second_deriv, eps):\n    begin, end = root_range\n\n    if func(begin) * func(end) >= 0:\n        print(f'f(a)f(b) = {func(begin) * func(end)}\\n It should be < 0')\n        exit()\n\n    if func(start_x) * second_deriv(start_x) <= 0:\n        print(f'f(x_0)f\\\"(x_0) = {func(start_x) * second_deriv(start_x)}\\n It should be > 0')\n        exit()\n\n    iters = 1\n    x_prev = start_x\n    x_cur = x_prev - func(x_prev) / first_deriv(x_prev)\n    diff = abs(x_cur - x_prev)\n    print(f'x_{iters - 1} = {x_prev}')\n    print(f'x_{iters} = {x_cur}')\n    print(f'|x_{iters} - x_{iters - 1}| = {diff}')\n\n    while diff >= eps:\n        x_prev = x_cur\n        x_cur = x_prev - func(x_prev) / first_deriv(x_prev)\n        diff = abs(x_cur - x_prev)\n        iters += 1\n\n        print(f'x_{iters - 1} = {x_prev}')\n        print(f'x_{iters} = {x_cur}')\n        print(f'|x_{iters} - x_{iters - 1}| = {diff}')\n\n    return x_cur, iters\n\n\ndef main():\n    eps = float(input())\n    # x_series = np.arange(-1.0, 1.1, 0.1)\n    # f1_series = [first_func(x) for x in x_series]\n    # f2_series = [second_func(x) for x in x_series]\n\n    # plot.figure()\n    # plot.xlabel('x')\n    # plot.ylabel('y')\n    # plot.plot(x_series, f1_series, 'r')\n    # plot.plot(x_series, f2_series, 'g')\n    # plot.axis([-1, max(x_series), min(f1_series + f2_series), max(f1_series + f2_series)])\n    # plot.grid(True)\n    # plot.show()\n\n    # x_1 = -0.308\n    # y_1 = -0.308\n    # x_2 = 0.775\n    # y_2 = 0.693\n    root_ranges = [((-0.35, -0.25), -1), ((0.75, 0.88), 1)]\n\n    for rnge in root_ranges:\n        bound, sign = rnge\n        res_s, iter_count = simple_iter(bound, eps, sign)\n        print(\"Simple iterations:\\n\")\n        print(f'Found solution in range {bound}:\\n{res_s}\\nIn {iter_count} iterations\\n')\n\n        print(\"Newthon:\\n\")\n        res_n, iter_count = newthon_solve(bound, max(bound, key=abs), lambda x: math.cos(x) - 4 * x, lambda x: -math.sin(x) - 4, eps)\n        print(f'Found solution in range {bound}:\\n{res_n}\\nIn {iter_count} iterations\\n')\n\n        print(f'Are they close? {math.isclose(res_n, res_s, abs_tol=eps)}')\n\nmain()", "meta": {"hexsha": "1190032bbd73b3eb8481ef91e34da07c759f4d1d", "size": 3406, "ext": "py", "lang": "Python", "max_stars_repo_path": "6th_semester/NumMethods/2_lab/task_1.py", "max_stars_repo_name": "mehakun/Labs", "max_stars_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-03-06T16:08:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-02T22:11:00.000Z", "max_issues_repo_path": "6th_semester/NumMethods/2_lab/task_1.py", "max_issues_repo_name": "mehakun/Labs", "max_issues_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6th_semester/NumMethods/2_lab/task_1.py", "max_forks_repo_name": "mehakun/Labs", "max_forks_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4677419355, "max_line_length": 133, "alphanum_fraction": 0.5637110981, "include": true, "reason": "import numpy", "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361157495521, "lm_q2_score": 0.9046505370289059, "lm_q1q2_score": 0.8687912368700247}}
{"text": "\"\"\"\nThis problem was asked by Google.\n\nThe area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.\n\nHint: The basic equation of a circle is x2 + y2 = r2\n\"\"\"\n\n# had to google what a Monte Carlo method is: essentially one creates random points .\nimport random\nfrom math import sqrt\n\n# if r == 1, the area becomes pi\nimport numpy\n\n\ndef pi_estimator(number_of_digits):\n    number_inside = 0\n    number_outside = 0\n    for i in range(0, number_of_digits):\n        x = numpy.random.rand()\n        y = numpy.random.rand()\n        if is_inside(x, y):\n            number_inside += 1\n        else:\n            number_outside += 1\n    return 4 * number_inside / (number_outside + number_inside)\n\n\ndef is_inside(x, y):\n    if x * x + y * y < 1.0:\n        return True\n    else:\n        return False\n\n\nif __name__ == '__main__':\n    print(pi_estimator(9000000))\n", "meta": {"hexsha": "0e1399431ada940ae072db13bbb4904148c85877", "size": 888, "ext": "py", "lang": "Python", "max_stars_repo_path": "#14.py", "max_stars_repo_name": "Domino2357/daily-coding-problem", "max_stars_repo_head_hexsha": "95ddef9db53c8b895f2c085ba6399a3144a4f8e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "#14.py", "max_issues_repo_name": "Domino2357/daily-coding-problem", "max_issues_repo_head_hexsha": "95ddef9db53c8b895f2c085ba6399a3144a4f8e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "#14.py", "max_forks_repo_name": "Domino2357/daily-coding-problem", "max_forks_repo_head_hexsha": "95ddef9db53c8b895f2c085ba6399a3144a4f8e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7692307692, "max_line_length": 99, "alphanum_fraction": 0.643018018, "include": true, "reason": "import numpy", "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242009478239, "lm_q2_score": 0.8962513786759491, "lm_q1q2_score": 0.8687581514834498}}
{"text": "\"\"\"\nNumerical methods for solving equations f(x) = 0.\n\"\"\"\n\n\ndef newton1D(f, x_0, df=None, delta=0.00001):\n    \"\"\"\n    Find solution to f(x) = 0 with newton's method\n    :param f: function f\n    :param x_0: starting point for x\n    :param df: first order derivative of f\n    :param delta: threshold for solution\n    :return: x\n    \"\"\"\n    x_n = x_0\n    if df is None:\n        from sympy import diff, symbols, lambdify\n        x = symbols('x')\n        df = lambdify(x, diff(f(x), x))\n    while True:\n        x_n1 = x_n - f(x_n) / df(x_n)\n        if abs(x_n - x_n1) < delta:\n            return x_n1\n        x_n = x_n1\n\n\ndef bisection1D(f, a, b, delta=0.00001):\n    \"\"\"\n    Find solution to f(x) = 0 with bisection method\n    :param f: function f\n    :param a: left starting point for x\n    :param b: right starting point for x\n    :param delta: threshold for solution\n    :return: x\n    \"\"\"\n    start, end = a, b\n    if f(a) == 0:\n        return a\n    elif f(b) == 0:\n        return b\n    elif f(a) * f(b) > 0:\n        print(\"couldn't find root in [{}, {}], return {}\".format(a, b, None))\n        return None\n    else:\n        mid = (start + end) / 2\n        while abs(start - mid) > delta:\n            if f(mid) == 0:\n                return mid\n            elif f(mid) * f(start) < 0:\n                end = mid\n            else:\n                start = mid\n            mid = (start + end) / 2\n        return mid\n\n\ndef intersection1D(f, x0, x1, delta=0.00001):\n    \"\"\"\n    Find solution to f(x) = 0 with intersection method\n    :param f: function f\n    :param x0: first starting point of x\n    :param x1: second starting point of x\n    :param delta: threshold for solution\n    :return: x\n    \"\"\"\n    x_n, x_n1 = x0, x1\n    while True:\n        x_n2 = x_n1 - f(x_n1) / ((f(x_n1) - f(x_n)) / (x_n1 - x_n))\n        if abs(x_n2 - x_n1) < delta:\n            return x_n2\n        x_n = x_n1\n        x_n1 = x_n2\n\n\nif __name__ == \"__main__\":\n\n    def f1(x):\n        return x**3-2*x-5\n\n    def df1(x):\n        return 3*(x**2)-2\n\n    print(newton1D(f1, 3))\n    print(newton1D(f1, 3, df1))\n    print(bisection1D(f1, 1, 3))\n    print(intersection1D(f1, 3, 3.5))\n", "meta": {"hexsha": "afd19fbccd23694128305932ecff4974b49fe6a8", "size": 2145, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/algo/math/solve.py", "max_stars_repo_name": "irsisyphus/toolbox", "max_stars_repo_head_hexsha": "6f7c64b3bbefbbcb95d7ed4cd2413dda862b1ef1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algo/math/solve.py", "max_issues_repo_name": "irsisyphus/toolbox", "max_issues_repo_head_hexsha": "6f7c64b3bbefbbcb95d7ed4cd2413dda862b1ef1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algo/math/solve.py", "max_forks_repo_name": "irsisyphus/toolbox", "max_forks_repo_head_hexsha": "6f7c64b3bbefbbcb95d7ed4cd2413dda862b1ef1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6551724138, "max_line_length": 77, "alphanum_fraction": 0.524009324, "include": true, "reason": "from sympy", "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241965169939, "lm_q2_score": 0.896251371748038, "lm_q1q2_score": 0.8687581407969206}}
{"text": "from typing import Tuple\n\nimport numpy as np\nfrom numpy.linalg import svd\n\nfrom eigendecomposition import eigendecomp\n\n\ndef square_svd(A: np.ndarray) \\\n        -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n    \"\"\"\n    Calculates the SVD decomposition of a square matrix using\n    eigendecomposition:\n    A = U * E * V^T\n\n    :param A: square real matrix\n    :return: matrices U, E, V^T; E is returned as a vector\n    \"\"\"\n    AA_T = A @ A.T\n    A_TA = A.T @ A\n\n    E, U = eigendecomp(AA_T)\n    E = np.sqrt(E)\n\n    _, V = eigendecomp(A_TA)\n\n    return U, E, V.T\n\n\nif __name__ == '__main__':\n    A = np.array([[2, -1, 0],\n                  [-1, 2, -1],\n                  [0, -1, 2]])\n\n    U, E, V_T = svd(A)\n    print(\"Library:\")\n    print(U)\n    print(E)\n    print(V_T)\n    print()\n\n    U, E, V_T = square_svd(A)\n    print(\"My:\")\n    print(U)\n    print(E)\n    print(V_T)\n\n\n", "meta": {"hexsha": "406d261c2bd49660f27964437ee561492e97632b", "size": 871, "ext": "py", "lang": "Python", "max_stars_repo_path": "svd.py", "max_stars_repo_name": "j-adamczyk/Matrix_algorithms", "max_stars_repo_head_hexsha": "2b06b4cfd741919724b2e88eb17da35909341ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-13T13:06:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-13T13:06:32.000Z", "max_issues_repo_path": "svd.py", "max_issues_repo_name": "j-adamczyk/Matrix_algorithms", "max_issues_repo_head_hexsha": "2b06b4cfd741919724b2e88eb17da35909341ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "svd.py", "max_forks_repo_name": "j-adamczyk/Matrix_algorithms", "max_forks_repo_head_hexsha": "2b06b4cfd741919724b2e88eb17da35909341ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-10T17:33:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T17:33:49.000Z", "avg_line_length": 17.7755102041, "max_line_length": 61, "alphanum_fraction": 0.5464982778, "include": true, "reason": "import numpy,from numpy", "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969324199175492, "lm_q2_score": 0.8962513641273355, "lm_q1q2_score": 0.8687581357926717}}
{"text": "import sympy as sp, math as m\n\nx, y = sp.symbols('x y')\nsp.init_printing(use_unicode=True)\n\n#f=sp.Lambda(x, x*sp.cos(x)-x**2*sp.sin(x))\n#f=sp.Lambda(x, x**4*sp.exp(-2*x**2))\n#f=sp.Lambda(x, 1/(1+x**2)) # Esta no converge\nf=sp.Lambda(x, sp.exp(sp.sin(x)**2-2))\n\n\"\"\"\ndef f(x):\n    #return x*m.cos(x)-x**2*m.sin(x)\n    #return m.cos(x)\n    return x**4*m.exp(-2*x**2)\n\"\"\"\n\ndef lagrange(nodes):\n    \n    l = []\n    for i in range(len(nodes)):\n        l.append(1)\n        for j in range(len(nodes)):\n            if j != i:\n                l[i]*=sp.poly((x-nodes[j])/(nodes[i]-nodes[j]))\n\n    return l\n\n\ndef n_c(f, a, b, n):\n    \n    nodes = []\n    h = (b-a)/n\n    \n    for i in range(n+1):\n        k = a+i*h\n        nodes.append(k)\n\n    l = lagrange(nodes)\n        \n    result = 0\n\n    for i in range(n+1):\n        result += (l[i].integrate()(b)-l[i].integrate()(a))*sp.N(f(nodes[i]))\n\n    return result        \n\nn=8\na,b=0, 2\n\nresult = n_c(f, a, b, n)\n\nprint(result)\n\n\n# Error para n par:\n\"\"\"\ndef k(n):\n\n    p = sp.Poly(y,y)\n\n    for i in range(0,n+1): # desde 1 si n impar\n        p*=sp.Poly(y-i,y)\n\n    result = p.integrate()(n)-p.integrate()(0)\n\n    result /= m.factorial(n+2) # si n impar, n+1\n\n    return result\n\"\"\"\n\n\"\"\"\nkn = k(n)\nh = (b-a)/n\n\n#g=sp.Lambda(x, sp.diff(f(x),x,n+2))\n#print(g(x))\n\ncota_n2=80640 # Introducir a mano\n\nprint(\"k\"+str(n)+\"=\"+str(kn))\nprint(\"Cota error: \"+str(abs(kn*h**(n+3)*cota_n2)))\n\"\"\"\n\n\n# Ej 14, trapecio:\n\"\"\"\ndef fa(x):\n    return x**2*m.log(x)\n\ndef fb(x):\n    return x**3*m.exp(-x)\n\ndef fc(x):\n    return 3*x/(x**2-4)\n\ndef fd(x):\n    return m.cos(x)*m.exp(3*x)\n\n\nprint(\"a) \" + str(n_c(fa, 1, 1.5, 1)))\nprint(\"b) \" + str(n_c(fb, 0, 1, 1)))\nprint(\"c) \" + str(n_c(fc, 1, 1.8, 1)))\nprint(\"d) \" + str(n_c(fd, 0, m.pi/4, 1)))\n\n# simpson\n\nprint(\"a) \" + str(n_c(fa, 1, 1.5, 2)))\nprint(\"b) \" + str(n_c(fb, 0, 1, 2)))\nprint(\"c) \" + str(n_c(fc, 1, 1.8, 2)))\nprint(\"d) \" + str(n_c(fd, 0, m.pi/4, 2)))\n\"\"\"\n", "meta": {"hexsha": "3ffb0baaa652f1af3a5e8cfd63ee818a8d4fa48f", "size": 1925, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tema2/newton-cotes_cerradas.py", "max_stars_repo_name": "dcabezas98/MNII", "max_stars_repo_head_hexsha": "123dfd7f19cb06e7d8db9e0865db624988a6f88b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tema2/newton-cotes_cerradas.py", "max_issues_repo_name": "dcabezas98/MNII", "max_issues_repo_head_hexsha": "123dfd7f19cb06e7d8db9e0865db624988a6f88b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tema2/newton-cotes_cerradas.py", "max_forks_repo_name": "dcabezas98/MNII", "max_forks_repo_head_hexsha": "123dfd7f19cb06e7d8db9e0865db624988a6f88b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0353982301, "max_line_length": 77, "alphanum_fraction": 0.4997402597, "include": true, "reason": "import sympy", "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305307578324, "lm_q2_score": 0.9019206666433899, "lm_q1q2_score": 0.8687575224323705}}
{"text": "\"\"\"\n--------------------------------------------------------------------------------\nAll exercices are preceded by a comment that starts with a verb.\nYou can search for a specify verb to found the desired function easily.\nThe verbs are:\n  - show;\n  - create;\n  - extract;\n  - replace;\n  - reshape;\n  - concact;\n  - get;\n  - swap;\n  - reverse;\n--------------------------------------------------------------------------------\n\"\"\"\n\nimport numpy as np\n\n# show numpy version\nprint('#1', np.__version__)\n\n# create array from 0 to 10\nprint('#2', np.arange(10))\n\n# create boolean array\nprint('#3', np.full((3, 3), True, dtype=bool))\n\n# extract odds from array\narr = np.arange(10)\nprint('#4', arr[arr % 2 == 1])\n\n# replace odds to -1\narr = np.arange(10)\narr[arr % 2 == 1] = -1\nprint('#5', arr)\n\n# replace without modify original\narr = np.arange(10)\ncopy = np.where(arr % 2 == -1, -1, arr)\nprint('#6', copy, arr)\n\n# reshape array\narr = np.arange(10)\n# -1 automatically decides the number of cols\nprint('#7', np.reshape(arr, (2, -1)))\n\n# concat a and b vertically\na = np.arange(10).reshape(2, -1)\nb = np.repeat(1, 10).reshape(2, -1)\nprint('#8', np.concatenate((a, b)))\n\n# concat a and b horizontally\na = np.arange(10).reshape(2, -1)\nb = np.repeat(1, 10).reshape(2, -1)\nprint('#9', np.concatenate((a, b), axis=1))\n\n# create custom arrays without hardcode\na = np.array([1, 2, 3])\nprint('#10', np.concatenate((np.repeat(a, 3), np.tile(a, 3))))\n\n# get the common items between arrays\na = np.array([1, 2, 3, 2, 3, 4, 3, 4, 5, 6])\nb = np.array([7, 2, 10, 2, 7, 4, 9, 4, 9, 8])\nprint('#11', np.intersect1d(a, b))\n\n# remove from one array those items that exist in another\na = np.array([1, 2, 3, 4, 5])\nb = np.array([5, 6, 7, 8, 9])\nprint('#12', np.setdiff1d(a, b))\n\n# get the positions where elements of two arrays match\na = np.array([1, 2, 3, 2, 3, 4, 3, 4, 5, 6])\nb = np.array([7, 2, 10, 2, 7, 4, 9, 4, 9, 8])\nprint('#13', np.where(a == b))\n\n# extract all numbers between a given range from a numpy array\na = np.array([2, 6, 1, 9, 10, 3, 27])\nprint('#14', a[(a >= 5) & (a <= 10)])\n\n\n# get the intersect through a function VERY USEFULL [!]\ndef maxx(x, y):\n    if x >= y:\n        return x\n    return y\n\n\npair_maxx = np.vectorize(maxx, otypes=[float])\na = np.array([5, 7, 9, 8, 6, 4, 5])\nb = np.array([6, 3, 4, 8, 9, 7, 1])\nprint('#15', pair_maxx(a, b))\n\n# swap two columns in a 2d numpy array\narr = np.arange(9).reshape(3, 3)\nprint('#16', arr, '\\n', arr[:, [1, 0, 2]])\n\n# swap two rows in a 2d numpy array\narr = np.arange(9).reshape(3, 3)\nprint('#17', arr, '\\n', arr[[1, 0, 2], :])\n\n# reverse the rows of a 2D array\narr = np.arange(9).reshape(3, 3)\nprint('#18', arr[::-1])\n\n# reverse the columns of a 2D array\narr = np.arange(9).reshape(3, 3)\nprint('#19', arr[:, ::-1])\n\n# create a 2D array containing random floats between 5 and 10\narr = np.random.uniform(5, 10, (5, 3))\nprint('#20', arr)\n\n# show only 3 decimal places in python numpy array\nrand_arr = np.random.random((5, 3))\nnp.set_printoptions(precision=3)\nprint('#21', rand_arr)\n\n# show prettier\nnp.set_printoptions(suppress=False)\nnp.random.seed(100)\nrand_arr = np.random.random([3, 3])/1e3\nnp.set_printoptions(suppress=True, precision=6)\nprint('#22', rand_arr)\n\n# show with limit the number of items printed in output of numpy array\nnp.set_printoptions(suppress=False)\na = np.arange(15)\nnp.set_printoptions(threshold=6, edgeitems=3)\nprint('#23', a)\n\n# show with limit the number of items printed in output of numpy array\nnp.set_printoptions(threshold=6)\na = np.arange(15)\nnp.set_printoptions(threshold=np.nan)\nprint('#24', a)\n", "meta": {"hexsha": "205cbc1ee72e493e34a33905f6fd16781b4ff869", "size": 3565, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/numpy/iniciante/index.py", "max_stars_repo_name": "stemDaniel/linear-algebra", "max_stars_repo_head_hexsha": "47c9c3cccf168edb0f6b31bcc95775137f61cb34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/numpy/iniciante/index.py", "max_issues_repo_name": "stemDaniel/linear-algebra", "max_issues_repo_head_hexsha": "47c9c3cccf168edb0f6b31bcc95775137f61cb34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/numpy/iniciante/index.py", "max_forks_repo_name": "stemDaniel/linear-algebra", "max_forks_repo_head_hexsha": "47c9c3cccf168edb0f6b31bcc95775137f61cb34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0218978102, "max_line_length": 80, "alphanum_fraction": 0.6086956522, "include": true, "reason": "import numpy", "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.9458012648298515, "lm_q1q2_score": 0.8686997765203415}}
{"text": "import numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\ndef Linearreg(xlist, ylist):\n    \"\"\" Takes two inputs, in list, tuple or arrays and computes a linear regression with method of least squares.\n    Returns k, m, such that y = kx + m & maximum deviation. \"\"\" #Add the return of std-error and r^2 value\n    if not isinstance((xlist, ylist), (np.generic, np.ndarray)):\n        if isinstance((xlist, ylist), (list, tuple)):\n            xlist, ylist = np.array(xlist), np.array(ylist)\n        else:\n            raise TypeError(\"[LinearRegression] Can't make linear fit with given input\")\n    if len(xlist) < 2:\n        raise TypeError(\"[LinearRegression] Can't make linear fit with given input, add more terms\")\n    else:\n        Line = lambda k,x,m: k * x + m\n        try:\n            bline = np.ones(len(xlist))\n            A = np.array([xlist, bline]).T\n            ATA = A.T.dot(A)\n            ATY = A.T.dot(ylist)\n            ATAInv = np.linalg.inv(ATA)\n            KM = ATAInv.dot(ATY)\n            Error = [((KM[0] * xlist[i] + KM[1]) - ylist[i]) for i in range(len(xlist)) if len(xlist) == len(ylist)]\n            return KM, max(Error)\n        except Exception as E:\n            raise E\n        #Maximum Deviation, not standard deviation\n\ndef ForceLinearreg(xlist,ylist):\n    \"\"\"Linear regression that forces through origion.\"\"\"\n    if not isinstance((xlist, ylist), (np.generic, np.ndarray)):\n        if isinstance((xlist, ylist), (list, tuple)):\n            xlist, ylist = np.array(xlist), np.array(ylist)\n        else:\n            raise TypeError(\"[ForceLinearreg] Can't make linear fit with given input\")\n    if len(xlist) != len(ylist) or len(xlist) < 2 or len(ylist) < 2:\n        raise KeyError(\"[ForceLinearreg] Can't make linear fit with given input\")\n    else:\n        try:\n            line = lambda k,x: k * x\n            A = np.array([xlist]).T\n            ATA = A.T.dot(A)\n            ATY = A.T.dot(ylist)\n            ATAInv = np.linalg.inv(ATA)\n            K = ATAInv.dot(ATY)\n            Error = [(K * xlist[i] - ylist[i]) for i in range(len(xlist))]\n            return K[0], max(Error)[0]\n        except Exception as E:\n            raise E\n\n\n\"\"\"\nxlist1 = np.array([1,2,3,4,5,6,7,8,9,10])\nylist1 = np.array([4,6,9,10,12,14,16,18,20,21])\nModel = ForceLinearreg(xlist1, ylist1)\nprint(Model)\nplt.plot(xlist1, ylist1, '.', label = \"DATA\")\nplt.plot(xlist1, xlist1 * Model[0], '-', label = \"Regression\")\nplt.legend()\nplt.show()\n\"\"\"\n\"\"\"\nRegression = Linearregression(xlist1, ylist1)\n\nplt.plot(xlist1,ylist1, '.')\nplt.plot(xlist1, Regression[0] * xlist1 + Regression[1])\nplt.show()\n\"\"\"\n", "meta": {"hexsha": "03daa824ddc1853c86c6570542c1bcba74f46e1d", "size": 2607, "ext": "py", "lang": "Python", "max_stars_repo_path": "PhysicsNum/Linearreg.py", "max_stars_repo_name": "thesombady/PhysicsNum", "max_stars_repo_head_hexsha": "cb098af9e24fca54dc30562757c461b88bce38b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PhysicsNum/Linearreg.py", "max_issues_repo_name": "thesombady/PhysicsNum", "max_issues_repo_head_hexsha": "cb098af9e24fca54dc30562757c461b88bce38b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PhysicsNum/Linearreg.py", "max_forks_repo_name": "thesombady/PhysicsNum", "max_forks_repo_head_hexsha": "cb098af9e24fca54dc30562757c461b88bce38b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2428571429, "max_line_length": 116, "alphanum_fraction": 0.5853471423, "include": true, "reason": "import numpy", "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147161743549, "lm_q2_score": 0.8933094096048377, "lm_q1q2_score": 0.8686672159967689}}
{"text": "import numpy as np\nfrom math import log2, sqrt\n\n\ndef entropy(class_y):\n    \"\"\"\n    Input:\n        - class_y: list of class labels (0's and 1's)\n    Output:\n        - entropy: a scalar, the value of entropy.\n    TODO:     [3 points]\n\n    Compute the entropy for a list of classes\n    Example: entropy([0,0,0,1,1,1,1,1]) = 0.9544\n    \"\"\"\n    x = np.mean(class_y)\n    if x == 0 or x == 1:\n        return 0\n    else:\n        return - x * np.log2(x) - (1 - x) * np.log2(1 - x)\n\ndef information_gain(previous_y, current_y):\n    \"\"\"\n    Inputs:\n        - previous_y : the distribution of original labels (0's and 1's)\n        - current_y  : the distribution of labels after splitting based on a particular\n                     split attribute and split value\n    Output:\n        - information_gain: a scalar, the value of information_gain.\n\n    TODO:     [3 points]\n\n    Compute and return the information gain from partitioning the previous_y labels into the current_y labels.\n\n    Reference: http://www.cs.cmu.edu/afs/cs.cmu.edu/academic/class/15381-s06/www/DTs.pdf\n\n    Example: previous_y = [0,0,0,1,1,1], current_y = [[0,0], [1,1,1,0]], info_gain = 0.4591\n    \"\"\"\n    x = len(current_y[0]) / len(previous_y)\n    if x == 0 or x == 1:\n        return 0\n    else:\n        return entropy(previous_y) - (x * entropy(current_y[0]) + (1 - x) * entropy(current_y[1]))\n\ndef partition_classes(X, y, split_attribute, split_val):\n    \"\"\"\n    Inputs:\n    - X               : (N,D) list containing all data attributes\n    - y               : a list of labels\n    - split_attribute : column index of the attribute to split on\n    - split_val       : either a numerical or categorical value to divide the split_attribute\n\n    Outputs:\n        - X_left, X_right, y_left, y_right : see the example below.\n\n    TODO:    [3 points]\n\n    Partition the data(X) and labels(y) based on the split value - BINARY SPLIT.\n\n    Example:\n\n    X = [[3, 'aa', 10],                 y = [1,\n         [1, 'bb', 22],                      1,\n         [2, 'cc', 28],                      0,\n         [5, 'bb', 32],                      0,\n         [4, 'cc', 32]]                      1]\n\n    Here, columns 0 and 2 represent numeric attributes, while column 1 is a categorical attribute.\n\n    Consider the case where we call the function with split_attribute = 0 (the index of attribute) and split_val = 3 (the value of attribute).\n    Then we divide X into two lists - X_left, where column 0 is <= 3 and X_right, where column 0 is > 3.\n\n    X_left = [[3, 'aa', 10],                 y_left = [1,\n              [1, 'bb', 22],                           1,\n              [2, 'cc', 28]]                           0]\n\n    X_right = [[5, 'bb', 32],                y_right = [0,\n               [4, 'cc', 32]]                           1]\n\n    Consider another case where we call the function with split_attribute = 1 and split_val = 'bb'\n    Then we divide X into two lists, one where column 1 is 'bb', and the other where it is not 'bb'.\n\n    X_left = [[1, 'bb', 22],                 y_left = [1,\n              [5, 'bb', 32]]                           0]\n\n    X_right = [[3, 'aa', 10],                y_right = [1,\n               [2, 'cc', 28],                           0,\n               [4, 'cc', 32]]                           1]\n\n\n    Return in this order: X_left, X_right, y_left, y_right\n    \"\"\"\n\n    X = np.array(X, dtype=object)\n    y = np.array(y)\n\n    #######################################################################################################\n    # Both list and numpy arrays are allowed in util functions. However, the dataset in the parts below is#\n    # imported as numpy array. Therefore, we strongly recommend implementing as numpy array to make sure  #\n    # the autograder is stable. It will also reduce the run time for decision tree and random forest.     #\n    # So please keep the lines above.                                                                     #\n    #######################################################################################################\n\n    X_left = np.copy(X)\n    X_right = np.copy(X)\n    if type(split_val) == str:\n        rightArr = X[:, [split_attribute]]\n        leftArr = X[:, [split_attribute]]\n        a = np.where(rightArr != split_val)[0]\n        b = np.where(leftArr == split_val)[0]\n        X_left = X_left[b, :]\n        X_right = X_right[a, :]\n        y_left = y[b]\n        y_right = y[a]\n    else:\n        rightArr = X[:, [split_attribute]]\n        leftArr = X[:, [split_attribute]]\n        a = np.where(rightArr > split_val)[0]\n        b = np.where(leftArr <= split_val)[0]\n        X_left = X_left[b, :]\n        X_right = X_right[a, :]\n        y_left = y[b]\n        y_right = y[a]\n    return X_left, X_right, y_left, y_right\n\ndef find_best_split(X, y, split_attribute):\n    \"\"\"\n    Inputs:\n        - X               : (N,D) list containing all data attributes\n        - y               : a list array of labels\n        - split_attribute : Column of X on which to split\n    Outputs:\n        - best_split_val, info_gain : see the example below.\n\n    TODO:    [3 points]\n\n    Compute and return the optimal split value for a given attribute, along with the corresponding information gain\n\n    Note: You will need the functions information_gain and partition_classes to write this function.\n    It is recommended that when dealing with numerical values, instead of discretizing the variable space, that you loop over the unique values in your dataset\n    (Hint: np.unique is your friend)\n\n    Example:\n\n        X = [[3, 'aa', 10],                 y = [1,\n             [1, 'bb', 22],                      1,\n             [2, 'cc', 28],                      0,\n             [5, 'bb', 32],                      0,\n             [4, 'cc', 32]]                      1]\n\n        split_attribute = 0\n\n        Starting entropy: 0.971\n\n        Calculate information gain at splits:\n           split_val = 1  -->  info_gain = 0.17\n           split_val = 2  -->  info_gain = 0.01997\n           split_val = 3  -->  info_gain = 0.01997\n           split_val = 4  -->  info_gain = 0.32\n           split_val = 5  -->  info_gain = 0\n\n       best_split_val = 4; info_gain = .32;\n    \"\"\"\n    X = np.array(X, dtype = object)\n\n    info_gain = -1\n    best_split_val = None\n    tried = []\n    for i in range(len(X)):\n        SplitVal = X[i][split_attribute]\n        mask = ~(np.isin(SplitVal, tried))\n        if mask:\n            X_left, X_right, y_left, y_right = partition_classes(X, y, split_attribute, SplitVal)\n            tried.append(SplitVal)\n        IG = information_gain(y, [y_left, y_right])\n        if not np.isnan(IG) and IG > info_gain:\n            info_gain = IG\n            best_split_val = SplitVal\n    return best_split_val, info_gain\n\n\ndef find_best_feature(X, y):\n    \"\"\"\n    Inputs:\n        - X: (N,D) list containing all data attributes\n        - y : a list of labels\n\n    Outputs:\n        - best_split_feature, best_split_val: see the example below.\n\n    TODO:    [3 points]\n\n    Compute and return the optimal attribute to split on and optimal splitting value\n\n    Note: If two features tie, choose one of them at random\n\n    Example:\n\n        X = [[3, 'aa', 10],                 y = [1,\n             [1, 'bb', 22],                      1,\n             [2, 'cc', 28],                      0,\n             [5, 'bb', 32],                      0,\n             [4, 'cc', 32]]                      1]\n\n        split_attribute = 0\n\n        Starting entropy: 0.971\n\n        Calculate information gain at splits:\n           feature 0:  -->  info_gain = 0.32\n           feature 1:  -->  info_gain = 0.17\n           feature 2:  -->  info_gain = 0.4199\n\n       best_split_feature: 2 best_split_val: 22\n    \"\"\"\n    X = np.array(X, dtype = object)\n\n    temp = -1\n    myData = [\"Lab-Confirmed Case\",\"Male\",\"Age\",\"Race\",\"Hospitalized\",\"ICU Patient\",\"Pre-existing\"]\n    for i in range(len(X[0])):\n        temp_val, IG = find_best_split(X, y, i)\n        if not np.isnan(IG) and IG > temp:\n            temp = IG\n            index = i\n            infoGain = IG\n            best_split_feature = myData[i]\n            best_split_val = temp_val\n    return best_split_feature, index, infoGain, best_split_val\n", "meta": {"hexsha": "5cd9c413477c1a04357b52a795d27a662e7cb7a8", "size": 8219, "ext": "py", "lang": "Python", "max_stars_repo_path": "Algorithm test/Random Forest/util.py", "max_stars_repo_name": "jbaldwin2014/cs-4641-group-44", "max_stars_repo_head_hexsha": "b6c7f9b657b0b5a5998a4379eb80064c108d36a3", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Algorithm test/Random Forest/util.py", "max_issues_repo_name": "jbaldwin2014/cs-4641-group-44", "max_issues_repo_head_hexsha": "b6c7f9b657b0b5a5998a4379eb80064c108d36a3", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Algorithm test/Random Forest/util.py", "max_forks_repo_name": "jbaldwin2014/cs-4641-group-44", "max_forks_repo_head_hexsha": "b6c7f9b657b0b5a5998a4379eb80064c108d36a3", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-02T15:06:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-03T02:50:34.000Z", "avg_line_length": 35.8908296943, "max_line_length": 159, "alphanum_fraction": 0.5164861905, "include": true, "reason": "import numpy", "num_tokens": 2119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426405416756, "lm_q2_score": 0.891811054783143, "lm_q1q2_score": 0.8686619946652295}}
{"text": "import numpy as np\n\n\ndef linear(x, y):\n    \"\"\"Implements linear kernel, equivalent to inner product\"\"\"\n    return np.dot(x, y)\n\n\ndef polynomial(x, y, d=2):\n    \"\"\"Implements polynomial kernel.\n\n    Computes the function (x·y + 1)**d, where x·y is the inner product between\n    vectors x and y.\n    \"\"\"\n    return np.power(np.dot(x, y)+1, d)\n\n\ndef rbf(x, y, gamma=1):\n    \"\"\"Radial basis function.\n\n    Computes the function exp(-gamma*||x-y||**2).\n    \"\"\"\n    return np.exp(-gamma*np.sum(np.square(x-y)))\n", "meta": {"hexsha": "e1a60b40a6b45cb9a68614e4256c1eb6c69fc878", "size": 505, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/kernels.py", "max_stars_repo_name": "SergioAlvarezB/ml-numpy", "max_stars_repo_head_hexsha": "bf450b0d48b52c56fd3d124a5b41f2b99594ea3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/kernels.py", "max_issues_repo_name": "SergioAlvarezB/ml-numpy", "max_issues_repo_head_hexsha": "bf450b0d48b52c56fd3d124a5b41f2b99594ea3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/kernels.py", "max_forks_repo_name": "SergioAlvarezB/ml-numpy", "max_forks_repo_head_hexsha": "bf450b0d48b52c56fd3d124a5b41f2b99594ea3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0416666667, "max_line_length": 78, "alphanum_fraction": 0.6138613861, "include": true, "reason": "import numpy", "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426435557124, "lm_q2_score": 0.891811044719067, "lm_q1q2_score": 0.8686619875503416}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nt = np.linspace(0, 20, 1001)\nnoise = np.random.randn(1001)\n\na = 0.2  # 0 for linear\nb = 1.\nc = 2.\n\ntrend = a*t**2 + b*t + c\n\nT = np.pi  # period\n\n# Fourier series coefficients\na_0 = 1.\n\na_1 = 1.\na_2 = 2.\na_3 = 3.\n\nb_1 = 4.\nb_2 = 5.\nb_3 = 6.\n\ntimeseries = a_0 \\\n    + a_1*np.cos(1*np.pi*t/T) \\\n    + a_2*np.cos(2*np.pi*t/T) \\\n    + a_3*np.cos(3*np.pi*t/T) \\\n    + b_1*np.sin(1*np.pi*t/T) \\\n    + b_2*np.sin(2*np.pi*t/T) \\\n    + b_3*np.sin(3*np.pi*t/T)\n\ntrended_timeseries = timeseries + trend\n\nnoisy_timeseries = trended_timeseries + noise\n\nplt.plot(t, trended_timeseries)\nplt.scatter(t, noisy_timeseries)\nplt.show()\n\ndata = np.vstack((t, timeseries)).T\nnoisy_data = np.vstack((t, noisy_timeseries)).T\n\n\n# np.savetxt(\n#     \"linear_trend_test_timeseries.csv\",\n#     data,\n#     delimiter=\",\"\n# )\n\n# np.savetxt(\n#     \"linear_trend_test_timeseries_noisy.csv\",\n#     noisy_data,\n#     delimiter=\",\"\n# )\n\nnp.savetxt(\n    \"quadratic_trend_test_timeseries.csv\",\n    data,\n    delimiter=\",\"\n)\n\nnp.savetxt(\n    \"quadratic_trend_test_timeseries_noisy.csv\",\n    noisy_data,\n    delimiter=\",\"\n)\n", "meta": {"hexsha": "2f3ae6a256beebd8e30449630e43ef79427ebee5", "size": 1136, "ext": "py", "lang": "Python", "max_stars_repo_path": "bokeh_app/data/trending_data_generator.py", "max_stars_repo_name": "goodteamname/spino", "max_stars_repo_head_hexsha": "aa8c6cfa9f94a639c306d85ca6df2483108fda37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bokeh_app/data/trending_data_generator.py", "max_issues_repo_name": "goodteamname/spino", "max_issues_repo_head_hexsha": "aa8c6cfa9f94a639c306d85ca6df2483108fda37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-10-26T10:57:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-01T14:48:21.000Z", "max_forks_repo_path": "bokeh_app/data/trending_data_generator.py", "max_forks_repo_name": "goodteamname/spino", "max_forks_repo_head_hexsha": "aa8c6cfa9f94a639c306d85ca6df2483108fda37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-26T10:41:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T10:41:31.000Z", "avg_line_length": 16.4637681159, "max_line_length": 48, "alphanum_fraction": 0.6258802817, "include": true, "reason": "import numpy", "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773708006261042, "lm_q2_score": 0.8887588008585925, "lm_q1q2_score": 0.8686469007586588}}
{"text": "import numpy as np\n\ndef rss(y_pred, y_truth):\n    \"\"\"\n    Residual sum of squares (RSS)\n    \n    Parameters\n    -------------\n    y_pred : numpy array, (m, 1)\n        the predicted labels\n    y_truth : numpy array, (m, 1)\n        the true labels\n        \n    Returns\n    --------\n    rss : double\n    \"\"\"\n    return ((y_pred-y_truth)**2).sum()\n\ndef mse(y_pred, y_truth):\n    \"\"\"\n    mean squared error (MSE)\n\n    Parameters\n    -------------\n    y_pred : numpy array, (m, 1)\n        the predicted labels\n    y_truth : numpy array, (m, 1)\n        the true labels\n        \n    Returns\n    --------\n    mse : double\n        smaller is better\n    \"\"\"\n    return rss(y_pred, y_truth)/y_pred.shape[0]\n\ndef rse(y_pred, y_truth):\n    \"\"\"\n    residual standard error (RSE):\n        estimation of the standard deviation between the\n        predicted values and true values\n\n    REF: An Introduction to Statistical Learning, pp. 82-83\n\n    Parameters\n    -------------\n    y_pred : numpy array, (m, 1), m>30\n        the predicted labels\n    y_truth : numpy array, (m, 1), m>30\n        the true labels\n        \n    Returns\n    --------\n    rse : double\n        smaller is better\n    \"\"\"\n    return np.sqrt(rss(y_pred, y_truth)/(y_pred.shape[0]-2))\n\ndef r2(y_pred, y_truth):\n    \"\"\"\n    R^2 statistic:\n        the proportion of variance explained by the model\n        given X\n    \n    Parameters\n    -------------\n    y_pred : numpy array, (m, 1)\n        the predicted labels\n    y_truth : numpy array, (m, 1)\n        the true labels\n        \n    Returns\n    --------\n    r2 : double, [0, 1]\n        larger is better\n    \"\"\"\n    tss_ = ((y_truth-y_truth.mean(axis=0))**2).sum()\n    rss_ = rss(y_pred, y_truth)\n    return 1.-rss_/tss_\n\ndef accuracy(y_pred, y_truth):\n    \"\"\"\n    Accuracy: #right / #all\n    \n    Parameters\n    -------------\n    y_pred : numpy array, (m, 1)\n        the predicted labels\n    y_truth : numpy array, (m, 1)\n        the true labels\n        \n    Returns\n    --------\n    accuracy : double\n        larger is better\n    \"\"\"\n    return (y_pred == y_truth).sum()/y_truth.shape[0] # right/all\n\ndef precision(y_pred, y_truth):\n    \"\"\"\n    Precision: #true_positive / #pred_positive\n    \n    Parameters\n    -------------\n    y_pred : numpy array, (m, 1)\n        the predicted labels\n    y_truth : numpy array, (m, 1)\n        the true labels\n        \n    Returns\n    --------\n    precision : double\n        larger is better\n    \"\"\"\n    return ((y_pred==1) & (y_truth == 1)).sum()/(y_pred == 1).sum() # tp / pred pos\n\ndef recall(y_pred, y_truth):\n    \"\"\"\n    Recall: #true_positive / #positive\n    \n    Parameters\n    -------------\n    y_pred : numpy array, (m, 1)\n        the predicted labels\n    y_truth : numpy array, (m, 1)\n        the true labels\n        \n    Returns\n    --------\n    recall : double\n        larger is better\n    \"\"\"\n    return ((y_pred==1) & (y_truth == 1)).sum()/(y_truth == 1).sum() # tp / pos\n\ndef fbeta_score(y_pred, y_truth, beta=1.):\n    \"\"\"\n    F_beta score\n\n    Parameters\n    -------------\n    y_pred : numpy array, (m, 1)\n        the predicted labels\n    y_truth : numpy array, (m, 1)\n        the true labels\n    beta : double, >0. default: 1.\n        \n    Returns\n    --------\n    fbeta_score : double\n        larger is better\n    \"\"\"\n    prec = precision(y_pred, y_truth)\n    reca = recall(y_pred, y_truth)\n    return (1+beta**2)/(1/prec + beta**2/reca)", "meta": {"hexsha": "93cabbabeac3f8379cad746f567fa0e0ee1dd08a", "size": 3393, "ext": "py", "lang": "Python", "max_stars_repo_path": "sharedcode/metrics.py", "max_stars_repo_name": "szqtc/MyMachineLearningNotes", "max_stars_repo_head_hexsha": "87fa278290d211fa9390dfdfb081acd90ceaeab9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sharedcode/metrics.py", "max_issues_repo_name": "szqtc/MyMachineLearningNotes", "max_issues_repo_head_hexsha": "87fa278290d211fa9390dfdfb081acd90ceaeab9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sharedcode/metrics.py", "max_forks_repo_name": "szqtc/MyMachineLearningNotes", "max_forks_repo_head_hexsha": "87fa278290d211fa9390dfdfb081acd90ceaeab9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8903225806, "max_line_length": 83, "alphanum_fraction": 0.5263778367, "include": true, "reason": "import numpy", "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474220263198, "lm_q2_score": 0.9099070097026718, "lm_q1q2_score": 0.8686403810963332}}
{"text": "\"\"\"\r\nFrom: https://gist.github.com/folkertdev/084c53887c49a6248839\r\nA sympy-based Lagrange polynomial constructor. \r\n\r\nImplementation of Lagrangian interpolating polynomial.\r\nSee:\r\n\r\n   def lagrangePolynomial(xs, ys):\r\n\r\nGiven two 1-D arrays `xs` and `ys,` returns the Lagrange interpolating\r\npolynomial through the points ``(xs, ys)``\r\n\r\n\r\nGiven a set 1-D arrays of inputs and outputs, the lagrangePolynomial function \r\nwill construct an expression that for every input gives the corresponding output. \r\nFor intermediate values, the polynomial interpolates (giving varying results \r\nbased  on the shape of your input). \r\n\r\nThe Lagrangian polynomials can be obtained explicitly with (see below):\r\n   \r\n   def polyL(xs,j):\r\n   \r\nas sympy polynomial, and \r\n\r\n    def L(xs,j):\r\n\r\nas Python functions.\r\n\r\n\r\nThis is useful when the result needs to be used outside of Python, because the \r\nexpression can easily be copied. To convert the expression to a python function \r\nobject, use sympy.lambdify.\r\n\"\"\"\r\nfrom sympy import symbols, expand, lambdify, solve_poly_system\r\n#Python library for arithmetic with arbitrary precision\r\nfrom mpmath import tan, e\r\n\r\nimport math\r\n\r\nfrom operator import mul\r\nfrom functools import reduce, lru_cache\r\nfrom itertools import chain\r\n\r\n# sympy symbols\r\nx = symbols('x')\r\n\r\n# convenience functions\r\nproduct = lambda *args: reduce(mul, *(list(args) + [1]))\r\n\r\n# test data\r\nlabels = [(-3/2), (-3/4), 0, 3/4, 3/2]\r\npoints = [math.tan(v) for v in labels]\r\n\r\n# this product may be reusable (when creating many functions on the same domain)\r\n# therefore, cache the result\r\n@lru_cache(16)\r\ndef l(labels, j):\r\n    def gen(labels, j):\r\n        k = len(labels)\r\n        current = labels[j]\r\n        for m in labels:\r\n            if m == current:\r\n                continue\r\n            yield (x - m) / (current - m)\r\n    return expand(product(gen(labels, j)))\r\n\r\ndef polyL(xs,j):\r\n    '''\r\n    Lagrange polynomials as sympy polynomial\r\n    xs: the n+1 nodes of the intepolation polynomial in the Lagrange Form\r\n    j: Is the j-th Lagrange polinomial for the specific xs.\r\n    '''\r\n    xs=tuple(xs)\r\n    return l(xs,j)\r\n\r\ndef L(xs,j):\r\n    '''\r\n    Lagrange polynomials as python function\r\n    xs: the n+1 nodes of the intepolation polynomial in the Lagrange Form\r\n    j: Is the j-th Lagrange polinomial for the specific xs.\r\n    '''\r\n    return lambdify(x, polyL(xs,j) )\r\n\r\ndef lagrangePolynomial(xs, ys):\r\n    '''\r\n    Given two 1-D arrays `x` and `w,` returns the Lagrange interpolating\r\n    polynomial through the points ``(x, w)``.\r\n\r\n    '''\r\n    # based on https://en.wikipedia.org/wiki/Lagrange_polynomial#Example_1\r\n    k = len(xs)\r\n    total = 0\r\n\r\n    # use tuple, needs to be hashable to cache\r\n    xs = tuple(xs)\r\n\r\n    for j, current in enumerate(ys):\r\n        t = current * l(xs, j)\r\n        total += t\r\n\r\n    return total\r\n\r\n\r\n\r\n\r\ndef x_intersections(function, *args):\r\n    \"Finds all x for which function(x) = 0\"\r\n    # solve_poly_system seems more efficient than solve for larger expressions\r\n    return [var for var in chain.from_iterable(solve_poly_system([function], *args)) if (var.is_real)]\r\n\r\ndef x_scale(function, factor):\r\n    \"Scale function on the x-axis\"\r\n    return functions.subs(x, x / factor)\r\n\r\nif __name__ == '__main__':\r\n    func = lagrangePolynomial(labels, points)\r\n\r\n    pyfunc = lambdify(x, func)\r\n\r\n    for a, b in zip(labels, points):\r\n        assert(pyfunc(a) - b < 1e-6)\r\n", "meta": {"hexsha": "7e80d14c3618ddbd4e41bd9d9725771cad935136", "size": 3430, "ext": "py", "lang": "Python", "max_stars_repo_path": "LagrangePolynomial.py", "max_stars_repo_name": "Mithun162001/Statistics-Exam-notebook", "max_stars_repo_head_hexsha": "90687ed80f9bba6d2158a0f452950ac5da69d6b1", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-03T14:41:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T14:41:04.000Z", "max_issues_repo_path": "LagrangePolynomial.py", "max_issues_repo_name": "Mithun162001/Statistics-Exam-notebook", "max_issues_repo_head_hexsha": "90687ed80f9bba6d2158a0f452950ac5da69d6b1", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LagrangePolynomial.py", "max_forks_repo_name": "Mithun162001/Statistics-Exam-notebook", "max_forks_repo_head_hexsha": "90687ed80f9bba6d2158a0f452950ac5da69d6b1", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1147540984, "max_line_length": 103, "alphanum_fraction": 0.6638483965, "include": true, "reason": "from sympy,from mpmath", "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370535, "lm_q2_score": 0.9086179025005188, "lm_q1q2_score": 0.8686217691911436}}
{"text": "import sympy as sym\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass Newton():\n\n    def __init__(self, f='x**2', max_iter=1e6, eps=1e-14):\n        \"\"\" Newton method class to find the solution\n\n        Attributes:\n                f (str) representing the function\n                max_iter (int) representing the maximum number of iterations to find the solution\n                eps (float) representing stopping criteria abs(f(x)) < epsilon\n            \n            Examples\n            --------\n            >>> f = '2*x**2 - 50'\n            >>> newton = Newton(f)\n            >>> newton.find_solution(1)\n            x = 13.0, f(x) = 288.0, iteration #1\n            x = 7.461538461538462, f(x) = 61.349112426035504, iteration #2\n            x = 5.406026962727994, f(x) = 8.45025504348412, iteration #3\n            x = 5.015247601944898, f(x) = 0.3054170176281019, iteration #4\n            x = 5.000023178253949, f(x) = 0.00046356615344222973, iteration #5\n            x = 5.000000000053723, f(x) = 1.0744685141617083e-09, iteration #6\n            x = 5.0, f(x) = 0.0, iteration #7\n            \n            Solution found at 5.0 with 7 iterations\n\n                \"\"\"\n\n        self.f = f  # Symbolic expression of the function\n        self.max_iter = max_iter\n        self.eps = eps\n        x = sym.symbols('x')  # Define x as mathematical symbol\n        self.x = x\n\n    def calculate_f_value(self, x):\n        \"\"\" Function to evaluate function for given x\n\n            Args:\n                x (float): x value\n\n            Returns:\n                f(x) (float): value of the function for the given x\n\n            \"\"\"\n\n        # lambdify provides a bridge from Sympy expression to numerical libraries\n        f = sym.lambdify([self.x], self.f)\n        return f(x)\n\n    def calculate_derivative(self, x):\n        \"\"\" Function to find the derivative and calculate the dfdx value for given x\n\n            Args:\n                x (float): x value\n\n            Returns:\n                dfdx(x) (float): derivate of f(x) at given x\n            \"\"\"\n\n        self.dfdx_expr = sym.diff(self.f, self.x)\n        dfdx = sym.lambdify([self.x], self.dfdx_expr)\n\n        return dfdx(x)\n\n    def plot_function(self, a=-10, b=10):\n        \"\"\" Function to plot the given function\n\n            Args:\n                a, b (float) [optional]: intervals\n\n            Returns:\n                None\n            \"\"\"\n        x = np.linspace(a, b, 100)\n        y = sym.lambdify([self.x], self.f)(x)\n\n        fig = plt.figure()\n        ax = fig.add_subplot(1, 1, 1)\n        ax.spines['left'].set_position('center')\n        ax.spines['bottom'].set_position('zero')\n        ax.spines['right'].set_color('none')\n        ax.spines['top'].set_color('none')\n        ax.xaxis.set_ticks_position('bottom')\n        ax.yaxis.set_ticks_position('left')\n        plt.plot(x, y)\n        plt.show()\n\n    def find_solution(self, x0):\n        \"\"\" Function to approximate solution of f(x)=0 by Newton's method\n\n            Args:\n                x0 (float): initial guess for a solution f(x)=0\n\n            Returns:\n                xn (float): intercept (solution) by the formula x = xn - f(xn)/dfdx(xn)\n\n        \"\"\"\n        xn = x0\n        iter_counter = 0\n        f_value = self.calculate_f_value(xn)\n        while abs(f_value) > self.eps and iter_counter < self.max_iter:\n            try:\n                xn = xn - float(f_value) / self.calculate_derivative(xn)\n            except ZeroDivisionError:\n                # Handling ZeroDivisonError - if the derivative of the initial guess is 0, increment x0\n                print(\n                    \"Error! - derivative zero for x = {}. Incrementing by 1...\".format(xn))\n                xn += 1\n            f_value = self.calculate_f_value(xn)\n            iter_counter += 1\n\n            print(\"x = {}, f(x) = {}, iteration #{}\".format(\n                xn, f_value, iter_counter))\n\n        print(\"Solution found at {} with {} iterations\".format(xn, iter_counter))\n        if abs(f_value) > self.eps:\n            print(\"Solution not found! Try changing the initial guess\")\n            iter_counter = -1\n            xn = None\n        \n        return xn\n", "meta": {"hexsha": "47b572624e1590a9e647279556d4fc97cfba0c85", "size": 4162, "ext": "py", "lang": "Python", "max_stars_repo_path": "build/lib/newtonMethod/newton.py", "max_stars_repo_name": "es-g/newtonMethod", "max_stars_repo_head_hexsha": "1011f957ffedd8e255f8791779daeac198e02d40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/lib/newtonMethod/newton.py", "max_issues_repo_name": "es-g/newtonMethod", "max_issues_repo_head_hexsha": "1011f957ffedd8e255f8791779daeac198e02d40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/lib/newtonMethod/newton.py", "max_forks_repo_name": "es-g/newtonMethod", "max_forks_repo_head_hexsha": "1011f957ffedd8e255f8791779daeac198e02d40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0317460317, "max_line_length": 103, "alphanum_fraction": 0.533157136, "include": true, "reason": "import numpy,import sympy", "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.9086178987887253, "lm_q1q2_score": 0.868621767921755}}
{"text": "import numpy as np\nfrom scipy.fftpack import fft, fftshift\nimport math\n\n\"\"\"\nA3-Part-3: Symmetry properties of the DFT\n\nWrite a function to check if the input signal is real and even using the symmetry properties of its\nDFT. The function will return the result of this test, the zerophase windowed version of the input \nsignal (dftbuffer), and the DFT of the dftbuffer. \n\nGiven an input signal x of length M, do a zero phase windowing of x without any zero-padding (a \ndftbuffer, on the same lines as the fftbuffer in sms-tools). Then compute the M point DFT of the \nzero phase windowed signal and use the symmetry of the computed DFT to test if the input signal x \nis real and even. Return the result of the test, the dftbuffer computed, and the DFT of the dftbuffer. \n\nThe input argument is a signal x of length M. The output is a tuple with three elements \n(isRealEven, dftbuffer, X), where 'isRealEven' is a boolean variable which is True if x is real \nand even, else False. dftbuffer is the M length zero phase windowed version of x. X is the M point \nDFT of the dftbuffer. \n\nTo make the problem easier, we will use odd length input sequence in this question (M is odd). \n\nDue to the precision of the FFT computation, the zero values of the DFT are not zero but very small\nvalues < 1e-12 in magnitude. For practical purposes, all values with absolute value less than 1e-6 \ncan be considered to be zero. Use an error tolerance of 1e-6 to compare if two floating point arrays \nare equal. \n\nCaveat: Use the imaginary part of the spectrum instead of the phase to check if the input signal is \nreal and even.\n\nTest case 1: If x = np.array([ 2, 3, 4, 3, 2 ]), which is a real and even signal (after zero phase \nwindowing), the function returns (True, array([ 4., 3., 2., 2., 3.]), array([14.0000+0.j, 2.6180+0.j, \n0.3820+0.j, 0.3820+0.j, 2.6180+0.j])) (values are approximate)\n\nTest case 2: If x = np.array([1, 2, 3, 4, 1, 2, 3]), which is not a even signal (after zero phase \nwindowing), the function returns (False,  array([ 4.,  1.,  2.,  3.,  1.,  2.,  3.]), array([ 16.+0.j, \n2.+0.69j, 2.+3.51j, 2.-1.08j, 2.+1.08j, 2.-3.51j, 2.-0.69j])) (values are approximate)\n\"\"\"\n\ndef testRealEven(x):\n    \"\"\"\n    Inputs:\n        x (numpy array)= input signal of length M (M is odd)\n    Output:\n        The function should return a tuple (isRealEven, dftbuffer, X)\n        isRealEven (boolean) = True if the input x is real and even, and False otherwise\n        dftbuffer (numpy array, possibly complex) = The M point zero phase windowed version of x \n        X (numpy array, possibly complex) = The M point DFT of dftbuffer \n    \"\"\"\n    ## Your code here\n    M = x.shape[-1]\n    hM1 = (M+1)//2\n    hM2 = M//2\n    dft_buffer = np.zeros(M)\n    dft_buffer[:hM1] = x[hM2:]\n    dft_buffer[hM1:] = x[:hM2]\n    X = fft(dft_buffer)\n    X_zeros = 0\n    for i in range(M):\n        if X.imag[i] >= 1e-6:\n            X_zeros += 1\n    if X_zeros == 0:\n        is_real_even = True\n    else:\n        is_real_even = False\n    return (is_real_even, dft_buffer, X)\n\n", "meta": {"hexsha": "d62af92b833b9a24df44435658381c98fa238f9f", "size": 3039, "ext": "py", "lang": "Python", "max_stars_repo_path": "A3/A3Part3.py", "max_stars_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_stars_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A3/A3Part3.py", "max_issues_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_issues_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A3/A3Part3.py", "max_forks_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_forks_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0434782609, "max_line_length": 103, "alphanum_fraction": 0.6837775584, "include": true, "reason": "import numpy,from scipy", "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.924141827813457, "lm_q1q2_score": 0.8686132364281278}}
{"text": "import numpy as np\nfrom math import ceil\n\ndef findPeak_1d_sf(lst):\n    \"\"\"\n    Args:\n        lst: list of numbers\n\n    Returns:\n        max: A peak number\n    \"\"\"\n    max = 0\n    for i in range(1,len(lst)-1):\n        if i == len(lst)-2:\n            if lst[i+1] > max:\n                max= lst[i+1]\n        elif lst[i-1] < lst[i] and lst[i+1] < lst[i]:\n            if lst[i] > max:\n                max= lst[i]\n    return max\n\n\ndef findPeak_1d_optimized(lst, low, high):\n    \"\"\"\n    Args:\n        lst: List of numbers\n        low: low index\n        high: high indes\n    Returns:\n        A peak number\n\n    \"\"\"\n    n= len(lst)\n    middle = low + (high - low) / 2\n    middle = int(middle)\n    if (middle==0 or lst[middle]>= lst[middle-1]) and\\\n            (middle==n-1 or lst[middle]>= lst[middle+1]):\n\n        return lst[middle]\n\n    if (middle > 0 and (lst[middle] <= lst[middle -1] and lst[middle -1] >= lst[middle +1])) :\n        return findPeak_1d_optimized(lst, low, middle-1)\n\n    elif (middle > 0 and (lst[middle] <= lst[middle +1] and lst[middle +1] >= lst[middle -1])) :\n        return findPeak_1d_optimized(lst,middle+1,high)\n\n\n\ndef findPeak_2d_optimized(arr,mid):\n    \"\"\"\n\n    Args:\n        arr: 2D numpy array of numbers\n        mid: always equal column//2\n\n    Returns:\n        A 2D peak number\n    \"\"\"\n    row, col = arr.shape[0], arr.shape[1]\n    max =0\n    for i in range(row):\n        if arr[i][mid] > max:\n            max = arr[i][mid]\n            max_indx=i\n    if (mid == 0 or mid == columns - 1):\n        return max\n\n    if (arr[max_indx][mid-1]< arr[max_indx][mid] and arr[max_indx][mid+1]< arr[max_indx][mid]):\n        return max\n\n    if (max < arr[max_indx][mid - 1]):\n        return findPeak_2d_optimized(arr, mid - ceil(mid / 2.0))\n\n    if (max < arr[max_indx][mid + 1]):\n        return findPeak_2d_optimized(arr, mid + ceil(mid / 2.0))\n\n\n\n\nif __name__ == '__main__':\n    import time\n    arr = np.array([[50, 8, 10, 10],\n           [14, 13, 12, 11],\n           [15, 9, 11, 21],\n           [16, 17, 19, 20]])\n    #arr= np.array([[10,20,15], [21,30,14],[7,16,32]])\n\n    # Number of Columns\n    rows = 4\n    columns = 4\n    mid= arr.shape[1]//2\n    print(findPeak_2d_optimized(arr,mid))\n    #print(findPeak(arr, rows, columns))\n\"\"\"\n    l= [1,2,4,1,20,1,40,3,1,100,4]\n    l=[1, 3, 20, 4, 1, 0]\n    t1 = time.time()\n    x= findPeak_1d_sf(l)\n    t2= time.time()\n    y= findPeak_1d_optimized(l, 0, len(l)-1)\n    #y= findPeak(l, len(l))\n    t3= time.time()\n\n    print(y)\n    opt= t3 - t2\n    fst= t2-t1\n    print(opt)\n    print(fst)\n    print(fst-opt)\n    \"\"\"", "meta": {"hexsha": "1d9f9f8af942684392d0c943bdeb5e1c627d7540", "size": 2574, "ext": "py", "lang": "Python", "max_stars_repo_path": "1.Peak Finding/find_peak.py", "max_stars_repo_name": "zuhaalfaraj/Introduction-to-Algorithms", "max_stars_repo_head_hexsha": "bc901b00e9e6f5f170f2a13602eb4e6da4506b75", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-27T21:58:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-27T21:58:29.000Z", "max_issues_repo_path": "1.Peak Finding/find_peak.py", "max_issues_repo_name": "zuhaalfaraj/Introduction-to-Algorithms", "max_issues_repo_head_hexsha": "bc901b00e9e6f5f170f2a13602eb4e6da4506b75", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1.Peak Finding/find_peak.py", "max_forks_repo_name": "zuhaalfaraj/Introduction-to-Algorithms", "max_forks_repo_head_hexsha": "bc901b00e9e6f5f170f2a13602eb4e6da4506b75", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4, "max_line_length": 96, "alphanum_fraction": 0.5240870241, "include": true, "reason": "import numpy", "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597459, "lm_q2_score": 0.9241418210233833, "lm_q1q2_score": 0.8686132316014917}}
{"text": "#!/usr/bin/env python\n\"\"\"\n    Copyright 2017 by Michael Wild (alohawild)\n    \n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n        http://www.apache.org/licenses/LICENSE-2.0\n        \n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n============================================================================================================\nThis is a pi calculation process using Monte Carlo or simple random process.\n\nImagine a circle in a box. The edges just touch the box. Lets make it a circle of radius 1.\n\nThus any point on or within the cirlce are 1 unit or less from the center.\n\nIt should be possible to randomly select points in the box and determine if the point is in the circle or not.\nThe ratio of points in the box over the number of randomly selected should be 1/4*Pi\n\n\"\"\"\n__author__ = 'michaelwild'\n__copyright__ = \"Copyright (C) 2018 Michael Wild\"\n__license__ = \"Apache License, Version 2.0\"\n__version__ = \"0.0.3\"\n__credits__ = [\"Michael Wild\"]\n__maintainer__ = \"Michael Wild\"\n__email__ = \"alohawild@mac.com\"\n__status__ = \"Initial\"\n\n\nimport os\nimport sys\nimport numpy as np\nimport math\n\nfrom time import process_time\n\ndef howFar(x,y):\n    \n    distance = (x * x) + (y * y)\n    return np.sqrt(distance)\n\ndef runtime(start):\n\n    return process_time() - start\n    \n# =============================================================\n\nprogram = \"Pi Calc\"\n\npiLoop = 1000000\ninCircle = 0\n\nbegin_time = process_time()\n\n# =============================================================\n# Main program begins here\n\nprint(program)\nprint(\"Version \", __version__, \" \", __copyright__, \" \", __license__)\nprint(\"Running on \", sys.version)\n\n\nfor i in range(1, piLoop):\n    x = (np.random.uniform()* 2) -1\n    y = (np.random.uniform() * 2) -1\n\n    if (howFar(x,y)<1.0) :\n        inCircle = inCircle + 1\npiGuess = 4.0* (inCircle / piLoop)\n\npiError = math.pi - piGuess\n\nprint(\"Loops:\", piLoop)\nprint(\"Calculated value: \",piGuess, \"Error: \", piError)\n\nfinish = runtime(begin_time)\nprint(\"Run time:\", finish)\n", "meta": {"hexsha": "122d6e79efbc20dc971cbf545296eb24f4bea69b", "size": 2415, "ext": "py", "lang": "Python", "max_stars_repo_path": "pi_calc.py", "max_stars_repo_name": "alohawild/python_class", "max_stars_repo_head_hexsha": "99d676d177220c36a808b05e44464f9e96641bac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-04T17:19:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-04T17:19:01.000Z", "max_issues_repo_path": "pi_calc.py", "max_issues_repo_name": "alohawild/python_class", "max_issues_repo_head_hexsha": "99d676d177220c36a808b05e44464f9e96641bac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pi_calc.py", "max_forks_repo_name": "alohawild/python_class", "max_forks_repo_head_hexsha": "99d676d177220c36a808b05e44464f9e96641bac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4117647059, "max_line_length": 110, "alphanum_fraction": 0.6364389234, "include": true, "reason": "import numpy", "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750466836961, "lm_q2_score": 0.9111797106148062, "lm_q1q2_score": 0.868604881173566}}
{"text": "# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\n\r\nar = np.array\r\n\r\nA = ar([[3, 0, 0, 0], \r\n        [2, 1, 0, 0], \r\n        [1, 5, 1, 0], \r\n        [7, 9, 8, 4]])\r\n\r\nb = ar([-9, 6, 2, 5])\r\nbb= ar([b, b]).T\r\n\r\nb_p = b\r\n\r\nn = 4\r\nfor i in range(n):\r\n    #xi = b[i] / A[i, i]\r\n    xi = b_p[0] / A[i, i]\r\n    print('x',i, '=', xi)\r\n    b_p = b_p[1:] - (xi * A[i+1:, i])\r\n    print(b_p)\r\n\r\n# Algoritmo general\r\n# 1.- Resolvemos L_11 * X_1 = B_1\r\n# 2.- Resolvemos B_2 = B_2 - L_21 * X_1\r\n    \r\n# Supongamos que tenemos un parámetro de bloque bloque\r\n\r\ndef elim_gauss_bloque(A, b, n):\r\n        \r\n    # primer paso: Resolvemos L_11 X_1 = B_1\r\n    X_1 = np.linalg.solve(A[:n, :n], b[:n])\r\n    if  A.shape[0] == n:\r\n        return X_1\r\n    else:\r\n        #print(X_1)\r\n        \r\n        # 2do paso:  Actualizamos la B\r\n        b = b[n:,] - np.matmul(A[n:, :n], X_1)\r\n        #print(b)\r\n        # Tercer paso:llamada recursiva\r\n        #print('falta:', A[n:, n:], 'b:', b[n:, ])\r\n        return np.append(X_1, elim_gauss_bloque(A[n:, n:], b, n), axis = 0)\r\n\r\nA = ar([[3, 0, 0, 0], \r\n        [2, 1, 0, 0], \r\n        [1, 5, 1, 0], \r\n        [7, 9, 8, 4]])\r\n\r\nb = ar([[-9, 12], [6, -1], [2, 0], [5, 1]])\r\n\r\nelim_gauss_bloque(A, b, n = 1)\r\n\r\nelim_gauss_bloque(A, b, n = 2)\r\n", "meta": {"hexsha": "9ce110ef8e13932a6d0a23ce5b63731c3393b378", "size": 1255, "ext": "py", "lang": "Python", "max_stars_repo_path": "analisisnum-jorgealtamirano/participaciones-adicionales-2019/3-ejercicios/saxpy_bloques_sust_hacia_delante/equipo7_bloques_sust_delante.py", "max_stars_repo_name": "philwebsurfer/analisis-numerico-computo-cientifico", "max_stars_repo_head_hexsha": "dd4dc0e03662a6b03deda7cd2d6896f8f1e59abc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analisisnum-jorgealtamirano/participaciones-adicionales-2019/3-ejercicios/saxpy_bloques_sust_hacia_delante/equipo7_bloques_sust_delante.py", "max_issues_repo_name": "philwebsurfer/analisis-numerico-computo-cientifico", "max_issues_repo_head_hexsha": "dd4dc0e03662a6b03deda7cd2d6896f8f1e59abc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analisisnum-jorgealtamirano/participaciones-adicionales-2019/3-ejercicios/saxpy_bloques_sust_hacia_delante/equipo7_bloques_sust_delante.py", "max_forks_repo_name": "philwebsurfer/analisis-numerico-computo-cientifico", "max_forks_repo_head_hexsha": "dd4dc0e03662a6b03deda7cd2d6896f8f1e59abc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0175438596, "max_line_length": 76, "alphanum_fraction": 0.435059761, "include": true, "reason": "import numpy", "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464604, "lm_q2_score": 0.9111797124237604, "lm_q1q2_score": 0.8686048768502824}}
{"text": "\"\"\"\nImplementation of Linear Regression using the Normal Equation.\n\nLet m = #training examples, n = #number of features and the\ninput shapes are y is R^(m x 1), X is R^(m x n), w is R^(n x 1).\nUsing these shapes, the normal equation implementation is\nexactly as the derived formula :) \n\nProgrammed by Aladdin Persson <aladdin.persson at hotmail dot com>\n*    2020-04-25 Initial coding\n\"\"\"\n\nimport numpy as np\n\n\ndef linear_regression_normal_equation(X, y):\n    ones = np.ones((X.shape[0], 1))\n    X = np.append(ones, X, axis=1)\n    W = np.dot(np.linalg.pinv(np.dot(X.T, X)), np.dot(X.T, y))\n    return W\n\n\nif __name__ == \"__main__\":\n    # Run a small test example: y = 5x (approximately)\n    m, n = 500, 1\n    X = np.random.rand(m, n)\n    y = 5 * X + np.random.randn(m, n) * 0.1\n    W = linear_regression_normal_equation(X, y)\n", "meta": {"hexsha": "373d84748ad87d199d0bbc0f5070ab6945b88371", "size": 826, "ext": "py", "lang": "Python", "max_stars_repo_path": "ML/algorithms/linearregression/linear_regression_normal_equation.py", "max_stars_repo_name": "xuyannus/Machine-Learning-Collection", "max_stars_repo_head_hexsha": "6d5dcd18d4e40f90e77355d56a2902e4c617ecbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3094, "max_stars_repo_stars_event_min_datetime": "2020-09-20T04:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:59:46.000Z", "max_issues_repo_path": "ML/algorithms/linearregression/linear_regression_normal_equation.py", "max_issues_repo_name": "xkhainguyen/Machine-Learning-Collection", "max_issues_repo_head_hexsha": "425d196e9477dbdbbd7cc0d19d29297571746ab5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 79, "max_issues_repo_issues_event_min_datetime": "2020-09-24T08:54:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:45:08.000Z", "max_forks_repo_path": "ML/algorithms/linearregression/linear_regression_normal_equation.py", "max_forks_repo_name": "xkhainguyen/Machine-Learning-Collection", "max_forks_repo_head_hexsha": "425d196e9477dbdbbd7cc0d19d29297571746ab5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1529, "max_forks_repo_forks_event_min_datetime": "2020-09-20T16:21:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T21:16:25.000Z", "avg_line_length": 28.4827586207, "max_line_length": 66, "alphanum_fraction": 0.6598062954, "include": true, "reason": "import numpy", "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877667047449, "lm_q2_score": 0.8947894717137996, "lm_q1q2_score": 0.8685611939687866}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom math import *\n\n# Function\ndef f(x):\n    return exp(x)\n\n# To compute the first column of Richardson method\ndef ThreeMidpoint(x0, h):\n    df = (f(x0+h)-f(x0-h))/(2*h)\n    return df\n\n\ndef Richarson(x0, h, tol):\n    R = np.zeros((50,50))\n\n    R[1][1] = ThreeMidpoint(x0, h)\n\n    for i in range(2, 50):\n        h = 0.5*h\n        R[i][1] = ThreeMidpoint(x0, h)\n\n        for j in range(2, i+1):\n            R[i][j] = R[i][j-1] + (1/(pow(4,j-1) - 1)) * (R[i][j-1] - R[i-1][j-1])\n\n        if abs((R[i][i] - R[i-1][i-1])) < tol: break\n\n    return R[i][i]\n\nif __name__ == '__main__':\n\n    x = 0\n\n    print(Richarson(x, 1, 0.01))\n", "meta": {"hexsha": "c2dc8897733ccfe34f2a97080fefc1b2cba97bf3", "size": 674, "ext": "py", "lang": "Python", "max_stars_repo_path": "Differentiation/Richardson-Method.py", "max_stars_repo_name": "AlexTsagas/Computational-Physics", "max_stars_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Differentiation/Richardson-Method.py", "max_issues_repo_name": "AlexTsagas/Computational-Physics", "max_issues_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Differentiation/Richardson-Method.py", "max_forks_repo_name": "AlexTsagas/Computational-Physics", "max_forks_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7222222222, "max_line_length": 82, "alphanum_fraction": 0.5222551929, "include": true, "reason": "import numpy", "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877717925422, "lm_q2_score": 0.8947894604912848, "lm_q1q2_score": 0.8685611876277363}}
{"text": "#!/usr/bin/env python3\nimport numpy as np\n\ntheta = 0.2\nprint(\"Theta: {}\".format(theta))\nyears = 6\nr00 = 0.05\nprint(\"r00: {}\".format(r00))\nprint(\"r0n factor: 0.9\")\nt=6\nr0n = [r00]\n\n#Array of interest rates\nfor i in range(1, t+1):\n    r0n.append(r0n[i-1]*0.9)\n\n#Interest rate tree using array and volatility parameter\ndef rate_tree(r0n,theta):\n    ratetree=[]\n    for i,element in enumerate(r0n):\n        treecolumn=[]\n        for j in range(0,i+1):\n            treecolumn.append(element*np.exp(2*j*theta))\n        ratetree.append(treecolumn)\n    return ratetree\n\n#Interest rate tree\nr_t = rate_tree(r0n, theta)\n\n#Cashflow tree using only number of period parameter\ndef cf_tree(t):\n    cftree=[]\n    for i in range(0, t+1):\n        treecolumn=[]\n        for j in range(0,i+1):\n            if i < t:\n                treecolumn.append(0)\n            if i == t:\n                treecolumn.append(100)\n        cftree.append(treecolumn)\n    return cftree\n\n#Present value tree\ndef pv_tree(ratetree,cftree):\n    pvtree=[]\n    for element in cftree:\n        parttree=[]\n        for element2 in element:\n            parttree.append(0)\n        pvtree.append(parttree)\n    icol=len(pvtree)-1\n    for j in range(0,icol+1):    \n        pvtree[icol][j]=cftree[icol][j]   \n    for i in range (1,len(pvtree)):\n        icol=len(pvtree)-1-i   \n        for j in range(0,icol+1):\n            pvtree[icol][j]=cftree[icol][j]+(0.5*pvtree[icol+1][j+1]+0.5*pvtree[icol+1][j])/(1+ratetree[icol][j])\n    return pvtree\n\n#Define function to calculate spot rates\ndef sr(pv,periods):\n    return (100/pv)**(1/periods)-1\n\n#Create an array with the PV trees for bonds of different durations\npv_array_tree = []\n#and the spot rates\nspot_array = []\nfor i in range(1,t+1):\n    present_value_tree = pv_tree(rate_tree(r0n, theta),cf_tree(i))\n    pv_array_tree.append(present_value_tree)\n    spot_rate = sr(pv_array_tree[i-1][0][0],i)\n    spot_array.append(spot_rate)\n\n#Calculating forward rates\nforward_array = [spot_array[0]]\nfor i in range(1,t):\n    forward_array.append((1+spot_array[i])**(i+1)/(1+spot_array[i-1])**(i)-1)\n\nprint()\nprint(\"BDT Lattice Rate Tree\")\nprint(r_t)\nprint()\nprint(\"Spot Rates\")\nprint(spot_array)\nprint()\nprint(\"Forward Array\")\nprint(forward_array)\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "b8dfbfd51a952e8e3500916c9b8a0f0e2b99f9e2", "size": 2243, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week20190515/Q2a_b.py", "max_stars_repo_name": "wrightgarr/PYTHON_416", "max_stars_repo_head_hexsha": "0accadc214b8d7b0140be6bc61222e2286ae72fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week20190515/Q2a_b.py", "max_issues_repo_name": "wrightgarr/PYTHON_416", "max_issues_repo_head_hexsha": "0accadc214b8d7b0140be6bc61222e2286ae72fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week20190515/Q2a_b.py", "max_forks_repo_name": "wrightgarr/PYTHON_416", "max_forks_repo_head_hexsha": "0accadc214b8d7b0140be6bc61222e2286ae72fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1237113402, "max_line_length": 113, "alphanum_fraction": 0.6317432011, "include": true, "reason": "import numpy", "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769113660688, "lm_q2_score": 0.8902942290328344, "lm_q1q2_score": 0.8685504941668881}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef s_eitken(z, n):\n    s1 = z\n    s2 = s1 + 1 / 3 * z ** 2\n    s3 = s2 + 1 / 5 * z ** 3\n    res = s3 - (s3 - s2) ** 2 / (s3 - s2 - s2 + s1)\n    for k in range(4, n + 1):\n        s1 = s2\n        s2 = s3\n        s3 += 1 / (2 * k - 1) * z ** k\n        if s3 - s2 - s2 + s1 != 0:\n            res = s3 - (s3 - s2) ** 2 / (s3 - s2 - s2 + s1)\n    return res\n\n\ndef s(z):\n    n = 10 ** 6\n    res = 0\n    for k in range(1, n + 1):\n        res += 1 / (2 * k - 1) * z ** k\n    return res\n\n\ndef calculate_value(z, wolfram_value):\n    print(\"--s(\" + str(z) + \")--\")\n    wolfram_value = wolfram_value\n    eitken_value = s_eitken(z, 10 ** 3)\n    print(\"wolfram: \" + str(wolfram_value))\n    print(\"eitkens method: \" + str(eitken_value))\n    print(\"abs of difference: \" + str(abs(wolfram_value - eitken_value)))\n    print(\"---\")\n\n\n# генерируем точки на верхней дуге единичной окружности и смотрим модуль разности со значением первых 10 ** 6 членов\n# точки на окружности, потому что внутри окружности сходимость быстрее\n# можно видеть, что в точке (1; 0) она расходится и график этому соответсвтует\ndef draw_speed():\n    step = 0.01\n    x = -1\n    y = 0j\n    n = 10 ** 3\n    data_x = []\n    data_y = []\n    while x <= 1:\n        accurate_value = s(x + y)\n        eitken = s_eitken(x + y, n)\n        data_x.append(x)\n        data_y.append(np.log10(1 / abs(accurate_value - eitken)))\n        x += step\n        y = np.sqrt(1 - x ** 2) * 1j\n    plt.subplot(211)\n    plt.title(\"speed conversion\")\n    plt.plot(data_x, data_y)\n    plt.ylabel(\"log10(1 / |accurate - eitken|)\")\n    plt.xlabel(\"z\")\n\n\ndef main():\n    plt.figure(1)\n    calculate_value(-0.9, -0.720117)\n    calculate_value(-1, -0.7853981633974483)\n    calculate_value(np.e ** (3j * np.pi / 4), -0.647215 + 0.486294j)\n    calculate_value(1j, -0.243747747 + 0.86697299j)\n    draw_speed()\n    plt.tight_layout()\n    plt.show()\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "35a2d48a6eaf9384c64bd76c517323da3fa9730c", "size": 1955, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw01/t02.py", "max_stars_repo_name": "RamSaw/NumericalMethods", "max_stars_repo_head_hexsha": "cc68e077451ea15e39879c5a8e99c07bd8d9b806", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw01/t02.py", "max_issues_repo_name": "RamSaw/NumericalMethods", "max_issues_repo_head_hexsha": "cc68e077451ea15e39879c5a8e99c07bd8d9b806", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw01/t02.py", "max_forks_repo_name": "RamSaw/NumericalMethods", "max_forks_repo_head_hexsha": "cc68e077451ea15e39879c5a8e99c07bd8d9b806", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4189189189, "max_line_length": 116, "alphanum_fraction": 0.5534526854, "include": true, "reason": "import numpy", "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158575, "lm_q2_score": 0.9073122307591682, "lm_q1q2_score": 0.8685498561886166}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 16 13:09:00 2021\r\n\r\n@author: Luigi\r\n\"\"\"\r\nimport numpy as np\r\nimport scipy as sci\r\nfrom scipy.linalg import qr\r\nimport matplotlib.pyplot as plt\r\n\r\ndef Usolve(U, b):\r\n    m, n = U.shape\r\n    if m != n:\r\n        print(\"Matr non quadrata\")\r\n        return [], 1\r\n    x = np.zeros((m,))\r\n    x[m-1] = b[m - 1] / U[m-1, n-1]\r\n    for i in range(m - 2, -1, -1):\r\n        x[i] = (b[i] - (np.dot(U[i, i+1 : m], x[i + 1 : m]))) / U[i,i]\r\n        \r\n    return x, 0\r\n\r\n\"\"\"\r\n    Qy = b\r\n    Rx = y\r\n\r\n\"\"\"\r\ndef metodoQR(x, y, n):\r\n    H = np.vander(x, n+1)\r\n    Q,R = qr(H)\r\n    y1 = np.dot(Q.T, y)\r\n    a, flag = Usolve(R[:n+1,:], y1[:n+1])\r\n    return a\r\n\r\nx = np.arange(1900, 2020, 10, dtype = float)\r\ny = np.array([76,92,106,123,132,151,179,203,226,249,281,305], dtype = float)\r\nprint(x)\r\n\r\nx1 = metodoQR(x, y, 1)\r\nx2 = metodoQR(x, y, 2)\r\nx3 = metodoQR(x, y, 3)\r\n\r\nxx = np.linspace(np.min(x), np.max(x), 100)\r\npol1 = np.polyval(x1, xx)\r\npol2 = np.polyval(x2, xx)\r\npol3 = np.polyval(x3, xx)\r\n\r\nplt.plot(x, y, \"o\", xx, pol1, xx, pol2, xx, pol3)\r\nplt.legend([\"Nodi\", \"Pol. 1\", \"Pol. 2\", \"Pol. 3\"])\r\nplt.show()\r\n\r\n# Punto D\r\nerr1 = []\r\nerr2 = []\r\nerr3 = []\r\nfor i in range(12):\r\n    err1.append((pol1[i] - y[i]) ** 2)\r\n    err2.append((pol2[i] - y[i]) ** 2)\r\n    err3.append((pol3[i] - y[i]) ** 2)\r\n    \r\nplt.plot(np.arange(12), err1, np.arange(12), err2, np.arange(12), err3)\r\nplt.legend([\"Err1\", \"Err2\", \"Err3\"])\r\nplt.show()\r\n\r\n\"\"\" OSSERVIAMO CHE I POLINOMI DI GRADO 2 E 3 DANNO LUOGO AGLI STESSI ERRORI\r\n\"\"\"\r\n    \r\n    \r\n    \r\n    ", "meta": {"hexsha": "c94726a52343b307f51a1145e9ac4dfb188f8c1d", "size": 1569, "ext": "py", "lang": "Python", "max_stars_repo_path": "simulazioni/01-02-2021-01-Pol.py", "max_stars_repo_name": "luigi-borriello00/Metodi_SIUMerici", "max_stars_repo_head_hexsha": "cf1407c0ad432a49a96dcd08303213e48723c57a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-06-23T14:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T08:39:27.000Z", "max_issues_repo_path": "simulazioni/01-02-2021-01-Pol.py", "max_issues_repo_name": "luigi-borriello00/Metodi_SIUMerici", "max_issues_repo_head_hexsha": "cf1407c0ad432a49a96dcd08303213e48723c57a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulazioni/01-02-2021-01-Pol.py", "max_forks_repo_name": "luigi-borriello00/Metodi_SIUMerici", "max_forks_repo_head_hexsha": "cf1407c0ad432a49a96dcd08303213e48723c57a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0985915493, "max_line_length": 77, "alphanum_fraction": 0.5092415551, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957277806109987, "lm_q2_score": 0.907312213841788, "lm_q1q2_score": 0.8685498455232622}}
{"text": "# Cowboy Linear Algebra python library at Video #9\n# By: Nick the Space Cowboy\n\nimport numpy as np\n\ndef back_sub(Utri, c):\n\t'''\n\tback substitution alogrithm for solving upper triangular system\n\t'''\n\tm = len(Utri) # row dimension of the Utri matrix\n\tn = len(Utri[0]) # column dimension of the Utri matrix\n\tx = np.zeros([n, 1], dtype=np.float64)\n\tb = np.array(c, dtype=np.float64)\n\tt1 = 0\n\tif m > n:\n\t\t# ct1 = m\n\t\t# m = n\n\t\traise Exception (\"More rows than columns (Use a different method)\")\n\tfor i in range(m - 1, -1, -1):\t# loop to iterate through row index\n\t\tx[i] += b[i] / Utri[i, i]\n\t\tfor j in range(n - 1 , i, -1):\t# loop to iterate through the off diagonal Sum part\n\t\t\tx[i] += (- (Utri[i, j] * x[j])) / Utri[i, i]\n\treturn x\n\t\t\ndef SGE(A, b=0):\n\t'''\n\tfunction to perform structured gaussian elimination \n\tIf a b vector isn't passed through, a LU decomposition is returned\n\t'''\n\tm = len(A)\n\tn = len(A[0])\n\tL = np.identity(m, dtype=np.float64)\n\tU = np.array(A)\n\tc = np.array(b)\n\tb_state = isinstance(b, np.ndarray)\n\tfor i in range(0, n, 1):\n\t\tfor j in range(i+1, m, 1):\n\t\t\tL[j,i] = U[j,i] / U[i,i]\n\t\t\tU[j] = U[j] - (L[j,i] * U[i])\n\t\t\tif b_state == False:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tc[j] = c[j] - (L[j,i] * c[i])\n\tif b_state==False:\n\t\treturn L, U\n\telse:\n\t\treturn U, c\n\t\ndef LU(A):\n\t'''\n\tFunction to perform LU decomposition\n\t'''\n\treturn SGE(A)\n\t\ndef LDV(A):\n\t'''\n\tFunction to perform a LDV Matrix decomposition\n\t'''\n\tL, U = LU(A)\n\tm = len(A)\n\tn = len(A[0])\n\tD = np.identity(m, dtype=np.float64)\n\tfor i in range(0, m, 1):\n\t\tfor j in range(0, n, 1):\n\t\t\tif i == j: \n\t\t\t\tD[i, j] = U[i, j]\n\tV = np.dot(np.linalg.inv(D), U)\n\treturn L, D, V\n\t\ndef pos_def_check(A):\n\t'''\n\tChecks if a matrix is positive definate\n\t'''\n\tpd_state = True\n\tn = len(A)\n\tfor i in range(1, n):\n\t\tif (A[i, i - 1] ** 2) >= A[i, i]:\n\t\t\traise Exception (\"Marix is not positive definate\")\n\t\t\tpd_state =  False\n\treturn pd_state\n\t\ndef cholesky(A):\n\t'''\n\tFunction to perform a Cholesky decompostion\n\t'''\n\tpd = pos_def_check(A)\n\tif pd == True:\n\t\tn = len(A)\n\t\tL = np.zeros_like(A, dtype=np.float64)\n\t\tfor i in range(0, n):\n\t\t\tfor j in range(0, i + 1):\n\t\t\t\tsum_part = 0\n\t\t\t\tif i == j:\n\t\t\t\t\tfor k in range(0, j):\n\t\t\t\t\t\tsum_part += L[j, k] ** 2\n\t\t\t\t\tL[i, j] = np.sqrt(A[j, j] - sum_part)\n\t\t\t\telse:\n\t\t\t\t\tfor k in range(0, j):\n\t\t\t\t\t\tsum_part += L[i, k] * L[j, k]\n\t\t\t\t\tL[i, j] = (A[i, j] - sum_part) / L[j, j]\n\telse:\n\t\tL = f\"Matrix is not positive definate\"\n\treturn L\n\t\ndef LDLT(A):\n\t'''\n\tFunction to perform the LDL^T matrix decomposition\n\t'''\n\tC = cholesky(A)\n\tn = len(A)\n\tD = np.identity(n, dtype=np.float64)\n\tL = C\n\tfor i in range(0, n):\n\t\tD[i, i] = C[i, i]**2\n\t\tL[:, i] = C[:, i] * D[i, i] ** (-1/2)\n\treturn L, D\n\n\t\n\t\n", "meta": {"hexsha": "4c8664e6101a7ba0b0518ee4d52f2dbaacf300e4", "size": 2670, "ext": "py", "lang": "Python", "max_stars_repo_path": "9_Non-Square/lin_alg/lin_alg.py", "max_stars_repo_name": "nkphysics/Computational-Linear-Algebra-", "max_stars_repo_head_hexsha": "8e82585e25b58f73179c0b0ace63fcda9f480f07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-09T20:14:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T20:14:22.000Z", "max_issues_repo_path": "9_Non-Square/lin_alg/lin_alg.py", "max_issues_repo_name": "nkphysics/Computational-Linear-Algebra-", "max_issues_repo_head_hexsha": "8e82585e25b58f73179c0b0ace63fcda9f480f07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "9_Non-Square/lin_alg/lin_alg.py", "max_forks_repo_name": "nkphysics/Computational-Linear-Algebra-", "max_forks_repo_head_hexsha": "8e82585e25b58f73179c0b0ace63fcda9f480f07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-12T12:27:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T12:27:21.000Z", "avg_line_length": 22.25, "max_line_length": 84, "alphanum_fraction": 0.5760299625, "include": true, "reason": "import numpy", "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748209, "lm_q2_score": 0.9032942067038784, "lm_q1q2_score": 0.8685479153127043}}
{"text": "import numpy as np\nfrom jacobi_iteration_method import jacobi_iteration\nfrom gauss_seidel_iteration import gauss_seidel_iteration\n\n\ndef successive_over_relaxation(A, b, omega, tol=1e-9, Max_iter=5000):\n    \"\"\" Solve linear equations by successive over relaxation method.\n\n    Args:\n        A: ndarray, coefficients matrix\n        b: ndarray, constant vector\n        omega: double, hyperrelaxation factor\n        tol: double, iteration accuracy\n        Max_iter: maximum iteration number\n\n    Returns:\n        y: ndarray, solution of the linear euqations\n        k: int, iteration number\n    \"\"\"\n    # decompose coefficients matrix\n    D = np.diag(np.diag(A))\n    L = -1 * np.tril(A - D)\n    U = -1 * np.triu(A - D)\n\n    # construct iteration coefficients matrix\n    B = np.linalg.inv(D - omega * L).dot((1 - omega) * D + omega * U)\n    f = omega * np.linalg.inv(D - omega * L).dot(b)\n\n    # initial iteration vector\n    x = np.ones_like(b)\n    # first iteration\n    k = 1\n    y = B.dot(x) + f\n\n    # iteration\n    while np.max(np.abs(y - x)) >= tol and k < Max_iter:\n        k += 1\n        x = y\n        y = B.dot(x) + f\n\n    return (y, k)\n\n\ndef print_solution_and_iteration_number(x, n):\n    \"\"\" Print the solution and iteration number.\n\n    Args:\n        x: ndarray, solution vector\n        n: int, iteration number\n    \"\"\"\n    for i in range(len(x)):\n        print(f\"x_{i+1} = {x[i]}\")\n    print(f\"The iteration number is {n}.\")\n\n\nif __name__ == '__main__':\n    # coefficients matrix\n    A = np.array([[-4, 1, 1, 1], [1, -4, 1, 1], [1, 1, -4, 1], [1, 1, 1, -4]])\n    # constant vector\n    b = np.ones(4)\n    # Jacobi iteration method\n    x1, n1 = jacobi_iteration(A, b)\n    print(\"The solution of the linear equations by Jacobi iteration method is:\")\n    print_solution_and_iteration_number(x1, n1)\n    # Gauss Seidel iteration method\n    x2, n2 = gauss_seidel_iteration(A, b)\n    print(\"The solution of the linear equations by Gauss Seidel iteration method is:\")\n    print_solution_and_iteration_number(x2, n2)\n    # successive over relaxation method\n    # when selecting the hyperrelaxation factor, it should be between 1.2 and 1.3\n    # then the minumum iteration number is 21\n    x3, n3 = successive_over_relaxation(A, b, 1.2)\n    print(\"The solution of the linear equations by successive over relaxation method is:\")\n    print_solution_and_iteration_number(x3, n3)\n\n", "meta": {"hexsha": "ac607229192b8bee53d6176f482d4b7125c8355a", "size": 2374, "ext": "py", "lang": "Python", "max_stars_repo_path": "LinearEquations2/successive_over_relaxation_method.py", "max_stars_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_stars_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LinearEquations2/successive_over_relaxation_method.py", "max_issues_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_issues_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LinearEquations2/successive_over_relaxation_method.py", "max_forks_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_forks_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2368421053, "max_line_length": 90, "alphanum_fraction": 0.6436394271, "include": true, "reason": "import numpy", "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793907, "lm_q2_score": 0.9032942034496965, "lm_q1q2_score": 0.8685479141750735}}
{"text": "\n\nimport numpy                 #numpy is a library for array operations akin to MATLAB\nfrom matplotlib import pyplot    #matplotlib is 2D plotting library\n\n\ndef linearconv(nx):\n    dx = 2.0 / (nx - 1)\n    nt = 20    #nt is the number of timesteps we want to calculate\n    dt = .025  #dt is the amount of time each timestep covers (delta t)\n    c = 1\n\n    u = numpy.ones(nx)      #defining a numpy array which is nx elements long with every value equal to 1.\n    u[int(.5/dx):int(1 / dx + 1)] = 2  #setting u = 2 between 0.5 and 1 as per our I.C.s\n\n    un = numpy.ones(nx) #initializing our placeholder array, un, to hold the values we calculate for the n+1 timestep\n\n    for n in range(nt):  #iterate through time\n        un = u.copy() ##copy the existing values of u into un\n        for i in range(1, nx):\n            u[i] = un[i] - c * dt / dx * (un[i] - un[i-1])\n    pyplot.figure()    \n    pyplot.plot(numpy.linspace(0, 2, nx), u);\n\n\n# Now let's examine the results of our linear convection problem with an increasingly fine mesh.  \n\nlinearconv(41) #convection using 41 grid points\n\nlinearconv(61)\n\nlinearconv(71)\n\nlinearconv(85)\n\n\n# In[8]:\n\n\ndef linearconv(nx):\n    dx = 2.0 / (nx - 1)\n    nt = 20    #nt is the number of timesteps we want to calculate\n    c = 1       # this is the wave speed\n    sigma = .5 # This is the condition on the CFL number\n    \n    dt = sigma * dx\n\n    u = numpy.ones(nx) \n    u[int(.5/dx):int(1 / dx + 1)] = 2\n\n    un = numpy.ones(nx)\n\n    for n in range(nt):  #iterate through time\n        un = u.copy() ##copy the existing values of u into un\n        for i in range(1, nx):\n            u[i] = un[i] - c * dt / dx * (un[i] - un[i-1])\n            \n    pyplot.figure()   \n    pyplot.plot(numpy.linspace(0, 2, nx), u)\n\n\nlinearconv(41)\n\nlinearconv(61)\n\nlinearconv(81)\n\nlinearconv(101)\n\nlinearconv(121)\n\n\n# Notice that as the number of points `nx` increases, the wave convects a shorter and shorter distance.\n#  The number of time iterations we have advanced the solution at is held constant at `nt = 20`, \n# but depending on the value of `nx` and the corresponding values of `dx` and `dt`, a shorter time window is being examined overall.  \n# It's possible to do rigurous analysis of the stability of numerical schemes, in some cases. \n#Watch Prof. Barba's presentation of this topic in **Video Lecture 9** on You Tube.\n\n\n\n\n", "meta": {"hexsha": "04a056a66dfafb68b4255e8e11a906f2e8ab761f", "size": 2355, "ext": "py", "lang": "Python", "max_stars_repo_path": "JM_code/Step3_CFL_Condition.py", "max_stars_repo_name": "JM-Maynard/12stepsCFD", "max_stars_repo_head_hexsha": "25eb540a6f434e70109dc03c89b0275cfeb9e5df", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-15T13:52:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-15T13:52:14.000Z", "max_issues_repo_path": "JM_code/Step3_CFL_Condition.py", "max_issues_repo_name": "JM-Maynard/12stepsCFD", "max_issues_repo_head_hexsha": "25eb540a6f434e70109dc03c89b0275cfeb9e5df", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JM_code/Step3_CFL_Condition.py", "max_forks_repo_name": "JM-Maynard/12stepsCFD", "max_forks_repo_head_hexsha": "25eb540a6f434e70109dc03c89b0275cfeb9e5df", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7195121951, "max_line_length": 134, "alphanum_fraction": 0.6356687898, "include": true, "reason": "import numpy", "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.933430810103574, "lm_q1q2_score": 0.8685184013934739}}
{"text": "#%% [markdown]\n## Chapter 2 Lab: Introduction to R (now in Python!)\n# Please note that, the purpose of this file is *not* to demonstrate Python's basic functionalities (there are much more comprehensive guides, [like this](https://learnxinyminutes.com/docs/python3/)) but to mirror ISLR's lab in R as much as possible.\n### Basic Commands\nx = [1, 3, 2, 5]\nprint(x)\ny = [1, 4, 3]\nprint(y)\n\n#%% [markdown]\n#### Get the length of a variable\nprint(len(x))\nprint(len(y))\n\n#%% [markdown]\n#### Element-wise addition of two lists\n##### Pure Python\n# Use [map](https://docs.python.org/2/library/functions.html#map) with [operator.add](https://docs.python.org/2/library/operator.html#operator.add) ([source](https://stackoverflow.com/a/18713494/4173146)):\nfrom operator import add\nx = [1, 6, 2]\nprint(list(map(add, x, y)))\n\n#%% [markdown]\n# or [zip](https://docs.python.org/2/library/functions.html#zip) with a list comprehension:\nprint([sum(i) for i in zip(x, y)])\n\n#%% [markdown]\n##### Using NumPy (will be faster than pure Python) ([source](https://stackoverflow.com/a/18713494/4173146)):\nimport numpy as np\nx2 = np.array([1, 6, 2])\ny2 = np.array([1, 4, 3])\nprint(x2 + y2)\n\n#%% [markdown]\n#### List all the variables\ndef printvars():\n   tmp = globals().copy()\n   [print(k,'  :  ',v,' type:' , type(v)) for k,v in tmp.items() if not k.startswith('_') and k!='tmp' and k!='In' and k!='Out' and not hasattr(v, '__call__')]\nprintvars()\n\n#%% [markdown]\n#### Clear a variable's content\nx = None\nprint(x)\n#%% [markdown]\n#### Delete a variable (its reference)\ndel y\nprint(y)\n#%% [markdown]\n#### Delete all varialbes ([source](https://stackoverflow.com/a/53415612/4173146))\nfor name in dir():\n    if not name.startswith('_'):\n        del globals()[name]\n\nfor name in dir():\n    if not name.startswith('_'):\n        del locals()[name]\nprint(x2)\nprint(y2)\n#%% [markdown]\n# or simply restart the interpreter.\n\n#%% [markdown]\n#### Declare matrices ([source](https://stackoverflow.com/questions/6667201/how-to-define-a-two-dimensional-array-in-python))\n##### Pure Python\nrowCount = 4\ncolCount = 3\nmat = [[0 for x in range(colCount)] for x in range(rowCount)]\nprint(mat)\n#%% [markdown]\n# or a shorter version:\nmat = [[0] * colCount for i in range(rowCount)]\nprint(mat)\n\n#%% [markdown]\n# However, it is best to use numpy arrays to represent matrices.\nimport numpy\nmat = numpy.zeros((rowCount, colCount))\nprint(mat)\n\n#%% [markdown]\n#### The sqaure root of each element of a vector or matrix (numpy array)\nimport numpy as np\nmat = [[16] * colCount for i in range(rowCount)]\nmat = np.asarray(mat)\nprint(np.sqrt(mat))\n\n#%% [markdown]\n#### Generate a vector of random normal variables\n# Dimensions are provided as arguements to the numpy function. \n# \n# For random samples from a Normal distribution with mean *mu* and standard deviation *sigma*, use:\n# `sigma * np.random.randn(...) + mu` according to the [documentation](https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.random.randn.html#numpy.random.randn)\nimport numpy as np\nx = np.random.randn(50)\ny = x + ( 0.1 * np.random.randn(50) + 50 )\n#%% [markdown]\n# To compute the [Pearson correlation coefficient](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient), or simply correlation, between the two vectors:\nprint(np.corrcoef(x, y))\n\n#%% [markdown]\n# To set the seed for random number generation, in Python:\nimport random\nrandom.seed(0)\n#%% [markdown]\n# Or in numpy:\nnp.random.seed(0)\nx = np.random.randn(50)\ny = x + ( 0.1 * np.random.randn(50) + 50 )\n\n#%% [markdown]\n#### To compute the mean, variance, and standard deviation of a vector of numbers:\nprint(np.mean(x))\nprint(np.var(x))\nprint(np.std(x))\nprint(np.mean(y))\nprint(np.var(y))\nprint(np.std(y))\n\n#%% [markdown]\n### Graphics\n#### Using matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nnp.random.seed(0)\nx = np.random.randn(100)\ny = np.random.randn(100)\n\nfig, ax = plt.subplots()\nax.scatter(x, y)\nplt.show()\n\nfig, ax = plt.subplots()\nax.set_xlabel(r'this is the x-axis')\nax.set_ylabel(r'this is the y-axis')\nax.set_title('Plot of X vs Y')\nax.grid(True)\nfig.tight_layout()\nax.scatter(x, y)\n#%% [markdown]\n##### Save the plot to a file\nfig.savefig('sample.png')\n# remove the whitespace around the image\nfig.savefig('sample.pdf', bbox_inches='tight')\n\n#%% [markdown]\n#### Using Seaborn\nimport seaborn as sns\nfig, ax = plt.subplots()\nax.set_xlabel(r'this is the x-axis')\nax.set_ylabel(r'this is the y-axis')\nax.set_title('Plot of X vs Y')\nax.grid(True)\nfig.tight_layout()\nsns.scatterplot(x, y)\n\n#%% [markdown]\n#### Using Plotly\nimport plotly.graph_objects as go\nfig = go.Figure(data=go.Scatter(x=x, y=y, mode='markers'))\nfig.show()\n\n#%% [markdown]\n#### Using Bokeh\nfrom bokeh.plotting import figure as bkfig, show as bkshow\nfig = bkfig(title=\"Plot of X vs Y\", tools='pan,wheel_zoom,box_zoom,reset,hover,crosshair', active_inspect='hover')\nfig.circle(x=x, y=y)\nfig.xaxis.axis_label = 'this is the x-axis'\nfig.yaxis.axis_label = 'this is the y-axis'\nbkshow(fig)\n\n#%% [markdown]\n#### Generating a sequence or range of numbers\n# In pure Python, use `range(lower, upper, step)`:\n# The following will generate a sequence of integers 1,...,10\nx = range(1, 11)\nfor i in x:\n        print(i)\n#%% [markdown]\n# To use non-decimal steps, or specify the number of elements to return, use the `linspace()` function in NumPy:\nx = np.linspace(1, 10, 20)\nprint(x)\n# Note that the PI constant in all of Python's math module, NumPy, and SciPy are the same.\nx = np.linspace(-np.pi, np.pi, 50)\nprint(x)\n\n#%% [markdown]\n#### Contour plotting\nimport matplotlib\nimport numpy as np\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\n\n\nx = np.linspace(-np.pi, np.pi, 50)\ny = x\nX, Y = np.meshgrid(x, y)\n# [source](https://stackoverflow.com/a/45496154/4173146)\nZ = np.cos(y) / (1 + x[:, None]**2)\n\nfig, ax = plt.subplots()\nCS = ax.contour(X, Y, Z)\nax.clabel(CS, inline=1, fontsize=4)\n\nCS = ax.contour(X, Y, Z, 45)\nax.clabel(CS, inline=1, fontsize=4)\n\nZ2 = ( Z - Z.T ) / 2\nfig, ax = plt.subplots()\nCS = ax.contour(X, Y, Z2, 15)\nax.clabel(CS, inline=1, fontsize=4)\n\n#%% [markdown]\n#### Filled contour (heatmap)\n# Note: run the previous cell first.\nfig, ax = plt.subplots(constrained_layout=True)\nCS = ax.contourf(X, Y, Z2, 15, cmap=plt.cm.plasma)\ncbar = fig.colorbar(CS)\n\n#%% [markdown]\n#### 3D contour plots\n# 3D wireframe plot\nfrom mpl_toolkits.mplot3d import axes3d\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.plot_wireframe(X, Y, Z2)\nplt.show()\n\n#%% [markdown]\n# 3D surface (color map)\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nfig = plt.figure()\nax = fig.gca(projection='3d')\nsurf = ax.plot_surface(X, Y, Z2, cmap=cm.terrain)\nfig.colorbar(surf)\nplt.show()\n\n#%% [markdown]\n# Project filled contour 'profiles' onto the 'walls' of the graph\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nfig = plt.figure()\nax = fig.gca(projection='3d')\nsurf = ax.plot_surface(X, Y, Z2, cmap=cm.terrain, alpha=0.8)\nfig.colorbar(surf)\n# Plot projections of the contours for each dimension.  By choosing offsets\n# that match the appropriate axes limits, the projected contours will sit on\n# the 'walls' of the graph (from the [matplotlib documentation](https://matplotlib.org/3.1.1/gallery/mplot3d/contourf3d_2.html#sphx-glr-gallery-mplot3d-contourf3d-2-py))\ncset = ax.contourf(X, Y, Z2, zdir='z', offset=ax.get_zlim()[0], cmap=cm.plasma, alpha=0.8)\n# cset = ax.contourf(X, Y, Z2, zdir='x', offset=ax.get_xlim()[0], cmap=cm.plasma, alpha=0.8)\n# cset = ax.contourf(X, Y, Z2, zdir='y', offset=ax.get_ylim()[1], cmap=cm.plasma, alpha=0.8)\nplt.show()\n\n#%% [markdown]\n# Vary the viewing angle\nfor elev in [20, 70, 40]:\n        fig = plt.figure()\n        ax = fig.gca(projection='3d')\n        surf = ax.plot_surface(X, Y, Z2, cmap=cm.terrain, alpha=0.8)\n        fig.colorbar(surf)\n        cset = ax.contourf(X, Y, Z2, zdir='z', offset=ax.get_zlim()[0], cmap=cm.plasma, alpha=0.8)\n        ax.azim = 30\n        ax.elev = elev\n\n        plt.show()\n\n#%% [markdown]\n### Indexing Data\nimport numpy as np\nA = np.array(np.arange(1, 17, 1)).reshape(4, 4).T\nprint(A)\n# Python's arrays are zero-indexed\nprint(A[1, 2])\n#%% [markdown]\n#### Select multiple rows and columns\nprint(np.array([A[0,1], A[0,3], A[2,1], A[2,3]]).reshape(2,2))\nprint(A[:3, 1:4])\nprint(A[:2, :])\nprint(A[:, :2])\nprint(A[0])\n#%% [markdown]\n#### Keep all rows or columns except those indicated in the index\n# To exclude whole rows or columns, use a boolean mask.\nmask = np.ones(len(A), dtype=bool)\n# Set the excluded indices to False\nmask[[0,2]] = False\n# Use the boolean/logical mask to index into the array\nprint(A[mask,...])\n#%% [markdown]\n# Get the dimensions of the array (matrix)\nprint(A.shape)\n\n#%% [markdown]\n### Loading Data\n# We will use pandas to load and read the data\nimport pandas as pd\n# Edit the path on your platform to correctly point to the file\ndf = pd.read_csv('Datasets\\Auto.csv')\ndf.head()\n\n#%% [markdown]\n# Pass `'?'` as a NaN string\ndf = pd.read_csv('Datasets\\Auto.csv', na_values='?')\ndf.head()\nprint(df.shape)\nprint(df.iloc[10:20,:])\n# Find and display only rows with NaN's\ndf1 = df[df.isna().any(axis=1)]\ndf1.head()\nprint(df1.shape)\n\n#%% [markdown]\n# Drop the NaN values\ndf = df.dropna()\nprint(df.shape)\n\n#%% [markdown]\n# Get a list of column names in the DataFrame\nprint(list(df))\n\n#%% [markdown]\n### Additional Graphical and Numerical Summaries\n# Scatterplots of the quantitative variables\ndf.plot.scatter(x='cylinders', y='mpg')\n\n#%% [markdown]\n# Boxplots, which are more suitable if the variable on the x-axis is categorical.\ndf_cat = df.pivot(columns='cylinders', values='mpg')\ndf_cat.plot.box()\ndf_cat.plot.box(vert=False)\n\n#%% [markdown]\n# Plot a histogram\ndf.hist(column='mpg')\ndf.hist(column='mpg', bins=15)\n\n#%% [markdown]\n# Plot a scatterplot matrix\nfrom pandas.plotting import scatter_matrix\nscatter_matrix(df[['mpg', 'displacement', 'horsepower', 'weight', 'acceleration']], diagonal='kde')\n\n#%% [markdown]\n# Plot the scatterplot, with custom variable values on mouse hover (using Plotly)\n# Marker color and size can also be set to variables.\nimport plotly.graph_objects as go\nfig = go.Figure(data=go.Scatter(x=df['horsepower'], y=df['mpg'], mode='markers', text=df['name']))\nfig.update_layout(xaxis=go.layout.XAxis(title=go.layout.xaxis.Title(text='Horsepower')), yaxis=go.layout.YAxis(title=go.layout.yaxis.Title(text='MPG')))\nfig.show()\n\n#%% [markdown]\n#### Descriptive statistics\n# Include all variables\ndf.describe()\n\n#%% [markdown]\n# Include only a subset of variables\ndf['mpg'].describe()\n\n#%% [markdown]\n#### Serialization - save or load the current session\nimport dill\nfilename = 'globalsave.pkl'\ndill.dump_session(filename)\n\n# and to load the session again:\ndill.load_session(filename)", "meta": {"hexsha": "599e172da518c4f6bd48343d6a3749db38f06ca7", "size": 10729, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ch2/Ch2_Lab.py", "max_stars_repo_name": "AliD101v/ISLR-labs-exercises-python", "max_stars_repo_head_hexsha": "e4994072afc53ea54fb6b788405f8d54ad43c934", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ch2/Ch2_Lab.py", "max_issues_repo_name": "AliD101v/ISLR-labs-exercises-python", "max_issues_repo_head_hexsha": "e4994072afc53ea54fb6b788405f8d54ad43c934", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ch2/Ch2_Lab.py", "max_forks_repo_name": "AliD101v/ISLR-labs-exercises-python", "max_forks_repo_head_hexsha": "e4994072afc53ea54fb6b788405f8d54ad43c934", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3945205479, "max_line_length": 250, "alphanum_fraction": 0.6890670146, "include": true, "reason": "import numpy", "num_tokens": 3078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.9343951593438425, "lm_q1q2_score": 0.8684646142211798}}
{"text": "###########################################################################################################\n# The Central Limit Theorem states that THE SAMPLING DISTRIBUTION OF THE \n# SAMPLE MEANS IS DISTRIBUTED LIKE IF IT WERE A NORMAL DISTRIBUTION.\n#\n# To prove this visually, let's draw a generic distribution (i.e. exponential)\n# and let's sample out of it means of a subsample. Once done, let's plot an\n# histogram to see how the sample mean distribution is...\n###########################################################################################################\n\n\n\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\ndef sample_mean(x:list=None):\n\t\n\treturn sum(x) / len(x)\n\n\n\n# 1. Let's define a probability function that we assume we do not know as a population probability function...\ndef exponential(x=0, lamb=0, vector:list=None):\n\n\tif vector is not None:\n\t\treturn [ exponential(x, lamb, vector=None) for x in vector ]\n\telse:\n\t\treturn lamb * np.exp( -lamb * x )\n\n\n\n# 2. Let's get out from the exponential distribution all the mean we may need...\nmother_dist = exponential( lamb=0.1, vector = [ x  for x in range(0, 1000) ] )\nsample_size = 450\nextractions = 7500\n\nsample_mean_extractions = [ sample_mean( random.sample(mother_dist, sample_size) ) for x in range(extractions) ]\n\n\n# 3. Let's plot the sampling distribution of the sample mean to see how it goes ! \nplt.hist( sample_mean_extractions, bins = 50, edgecolor='black' )\nplt.vlines( sample_mean(sample_mean_extractions), ymin=0, ymax=450, color='red' )\nplt.show()\n\n\n# Well, how does it look like the sampling distribution of the sample mean ?! I hope a \"bell\" rings inside you ! \n# Try to increase the \"extractions\" parameters to see how it goes...\n\n", "meta": {"hexsha": "453911a1b465a106269999adaa67f8c58f775c6d", "size": 1738, "ext": "py", "lang": "Python", "max_stars_repo_path": "DSToolkit/statistical/central_limit_theorem.py", "max_stars_repo_name": "AndreaFerrante/DSToolkit", "max_stars_repo_head_hexsha": "6f527cb4c19127cecd74bb682330236aa4e41839", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DSToolkit/statistical/central_limit_theorem.py", "max_issues_repo_name": "AndreaFerrante/DSToolkit", "max_issues_repo_head_hexsha": "6f527cb4c19127cecd74bb682330236aa4e41839", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DSToolkit/statistical/central_limit_theorem.py", "max_forks_repo_name": "AndreaFerrante/DSToolkit", "max_forks_repo_head_hexsha": "6f527cb4c19127cecd74bb682330236aa4e41839", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0784313725, "max_line_length": 113, "alphanum_fraction": 0.6421173763, "include": true, "reason": "import numpy", "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995782141546, "lm_q2_score": 0.8991213874066956, "lm_q1q2_score": 0.8684609688594528}}
{"text": "# importing Python library \nimport numpy as np \n  \n# define Unit Step Function \ndef unitStep(v): \n    if v >= 0: \n        return 1\n    else: \n        return 0\n  \n# design Perceptron Model \ndef perceptronModel(x, w, b): \n    v = np.dot(w, x) + b \n    y = unitStep(v) \n    return y \n  \n# NOT Logic Function \n# wNOT = -1, bNOT = 0.5 \ndef NOT_logicFunction(x): \n    wNOT = -1\n    bNOT = 0.5\n    return perceptronModel(x, wNOT, bNOT) \n  \n# OR Logic Function \n# w1 = 1, w2 = 1, bOR = -0.5 \ndef OR_logicFunction(x): \n    w = np.array([1, 1]) \n    bOR = -0.5\n    return perceptronModel(x, w, bOR) \n  \n# NOR Logic Function \n# with OR and NOT   \n# function calls in sequence \ndef NOR_logicFunction(x): \n    output_OR = OR_logicFunction(x) \n    output_NOT = NOT_logicFunction(output_OR) \n    return output_NOT \n  \n# testing the Perceptron Model \ntest1 = np.array([0, 1]) \ntest2 = np.array([1, 1]) \ntest3 = np.array([0, 0]) \ntest4 = np.array([1, 0]) \n  \nprint(\"NOR({}, {}) = {}\".format(0, 1, NOR_logicFunction(test1))) \nprint(\"NOR({}, {}) = {}\".format(1, 1, NOR_logicFunction(test2))) \nprint(\"NOR({}, {}) = {}\".format(0, 0, NOR_logicFunction(test3))) \nprint(\"NOR({}, {}) = {}\".format(1, 0, NOR_logicFunction(test4)))\n\n'''\nOUTPUT\nNOR(0, 1) = 0\nNOR(1, 1) = 0\nNOR(0, 0) = 1\nNOR(1, 0) = 0\n'''", "meta": {"hexsha": "7c5a38b9c1063e11c1dcd53c2ffe2ba233b2b7d3", "size": 1276, "ext": "py", "lang": "Python", "max_stars_repo_path": "ml/Perceptrons/Perceptron as NOR operator.py", "max_stars_repo_name": "SounakMandal/AlgoBook", "max_stars_repo_head_hexsha": "3952cb49ef12f1c00e97e0cf25810170f8585748", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 191, "max_stars_repo_stars_event_min_datetime": "2020-09-28T10:00:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T14:36:55.000Z", "max_issues_repo_path": "ml/Perceptrons/Perceptron as NOR operator.py", "max_issues_repo_name": "SounakMandal/AlgoBook", "max_issues_repo_head_hexsha": "3952cb49ef12f1c00e97e0cf25810170f8585748", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 210, "max_issues_repo_issues_event_min_datetime": "2020-09-28T10:06:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T03:44:24.000Z", "max_forks_repo_path": "ml/Perceptrons/Perceptron as NOR operator.py", "max_forks_repo_name": "SounakMandal/AlgoBook", "max_forks_repo_head_hexsha": "3952cb49ef12f1c00e97e0cf25810170f8585748", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 320, "max_forks_repo_forks_event_min_datetime": "2020-09-28T09:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T16:45:57.000Z", "avg_line_length": 22.7857142857, "max_line_length": 65, "alphanum_fraction": 0.5877742947, "include": true, "reason": "import numpy", "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899575269305, "lm_q2_score": 0.8991213867309121, "lm_q1q2_score": 0.8684609655589366}}
{"text": "# p(x) = L0(x)f(x0)+...Ln(x)f(xn)\nimport sympy\n\nx = sympy.Symbol('x')\n\nxn =[2,2.1,2.2,2.3,2.4,2.5]\nfxn =[-11.8646,-12.4775,-13.0891,-13.6997,-14.3092,-14.9179]\nfunctions = []\ndef lagrange():\n    for i in range(0,len(xn)):\n        numerator = 1\n        denominator = 1\n        for j in range(0,len(xn)):\n            if( i != j):\n                \n                numerator = numerator * (x-xn[j])\n                denominator = denominator * (xn[i]-xn[j])\n        functions.append(numerator/denominator)\n        \nlagrange()\npolinomyal = 0\nfor i in range(0,len(functions)):\n    polinomyal = polinomyal + fxn[i]*functions[i]\nprint(polinomyal)\n\nd = sympy.simplify(polinomyal)\n#f = d.evalf().subs({x:2.5})\n#print()\nprint(\"simplify\",d)", "meta": {"hexsha": "412e81d3c9be01b7ee4baafdbade06c12f8c2dae", "size": 727, "ext": "py", "lang": "Python", "max_stars_repo_path": "Interpolation/Lagrange/lagrangeMethod.py", "max_stars_repo_name": "stivenramireza/numericalanalysis", "max_stars_repo_head_hexsha": "7f2fe2b43ac41bccf3c41d3f936522619d009927", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-19T17:18:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-21T04:01:07.000Z", "max_issues_repo_path": "Interpolation/Lagrange/lagrangeMethod.py", "max_issues_repo_name": "stivenramireza/numerical-methods", "max_issues_repo_head_hexsha": "7f2fe2b43ac41bccf3c41d3f936522619d009927", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Interpolation/Lagrange/lagrangeMethod.py", "max_forks_repo_name": "stivenramireza/numerical-methods", "max_forks_repo_head_hexsha": "7f2fe2b43ac41bccf3c41d3f936522619d009927", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-23T17:20:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-23T17:20:22.000Z", "avg_line_length": 25.0689655172, "max_line_length": 60, "alphanum_fraction": 0.5557083906, "include": true, "reason": "import sympy", "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995782141546, "lm_q2_score": 0.899121377945727, "lm_q1q2_score": 0.8684609597211073}}
{"text": "import numpy as np\n\ndef remove_dependent_variables(x, tol = np.finfo(np.float).eps):\n    \"\"\"\n    Find independent columns using QR decomposition. The returned solution might\n    not unique. There might be other subset of independent columns. Strict \n    condition number of rows (m) > number of columns (n)\n    :param x: The input numpy array\n    :param tol: Tolerance, variables less than tol are removed\n    :return: The linearly independent subset of variables\n    \"\"\"\n    r = np.linalg.matrix_rank(x)\n    n = x.shape[1]\n    assert(r is not n), 'Matrix is already linearly independent'\n    q, r = np.linalg.qr(x)\n    ind  = np.where(np.abs(r.diagonal()) > tol)[0]\n    return(ind, x[:, ind])\n\nif __name__ == '__main__':\n    \"\"\"\n    Simple use case\n    \"\"\"\n    print('Define Matrix')\n    \n    A = np.array([[2, 4, 1, 3], [-1, -2, 1, 0], [0, 0, 4, 4], [3, 6, 2, 5]])\n    \n    print(A)\n    \n    print(' Output Matrix ')\n    \n    i, Y = remove_dependent_variables(A)\n    \n    print(Y)\n    ", "meta": {"hexsha": "82b6be34e924a7594ee0d3401fc51f3a23449397", "size": 987, "ext": "py", "lang": "Python", "max_stars_repo_path": "driver_remove_dependent_variables.py", "max_stars_repo_name": "r2rahul/dimensionreduction", "max_stars_repo_head_hexsha": "c933716632d113a73196d768effb77a2e171a67c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-10T05:55:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T05:55:38.000Z", "max_issues_repo_path": "driver_remove_dependent_variables.py", "max_issues_repo_name": "r2rahul/dimensionreduction", "max_issues_repo_head_hexsha": "c933716632d113a73196d768effb77a2e171a67c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "driver_remove_dependent_variables.py", "max_forks_repo_name": "r2rahul/dimensionreduction", "max_forks_repo_head_hexsha": "c933716632d113a73196d768effb77a2e171a67c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0294117647, "max_line_length": 80, "alphanum_fraction": 0.6109422492, "include": true, "reason": "import numpy", "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995742876885, "lm_q2_score": 0.8991213698363247, "lm_q1q2_score": 0.8684609483578694}}
{"text": "#!/usr/bin/env python\n\n\"\"\"This program finds the steady state solution of the geostrophic\nadjustment the equations are: (i) the geostrophic balance, and (ii)\nthe conservation of potential vorticity. In cartesian geometry, these\ntwo equations are\n\n(i)    -v = dh/dx\n(ii)   dv/dx - h = -h_0\n\nwith v the velocity and h the elevation of the interface\n\nthe program returns the solution vector (v,h) and plots the initial\ncondition (h_0 dashed) and final state (h)\n\nv and h are discretized on a C-grid where the velocity is at the face\nof the cell and the height of the interface is at the center of the\ncell.\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import fsolve\n\nplt.ion()\n\nflag_geom = 1 # geometry: 0: cartesian, 1: cylindrical coordinates\n\n# both rmax and r0 are non dimensional variables \n# the length unit is the deformation radius\nrmax = 20  # tank radius\nr0 = 10.0   #inner cylinder radius\n\nNx = 100     # number of points\nsi_r = 2*Nx + 1 \n\nrr = np.linspace(0,rmax,si_r)\ndr = rr[1] - rr[0]\n\nrr2 = 0.5*(rr[1:] + rr[:-1])\n\n# initial condition\nh0 = np.zeros(si_r+1) \nh0[1:-1] = np.where(rr2<r0,-1,0) \nh0[0] = h0[1]\nh0[-1] = h0[-2]\nv0 = np.zeros(si_r) \n\nxx = np.concatenate((h0,v0))\n\n\ndef f(x,si_r,rr,dr,h0,flag_geom):\n  h = x[:si_r+1]\n  v = x[si_r+1:]\n\n  fout = np.zeros(2*si_r+1)\n\n  dhdr = (h[1:] - h[:-1])/dr\n  dhdr[0] = 0.\n  dhdr[-1] = 0.\n\n\n  if flag_geom == 0:# cartesian\n    fout[1:si_r] = (v[1:] - v[:-1])/(dr) - h[1:-1] + h0[1:-1]\n    fout[si_r+1:] = -v + dhdr\n  if flag_geom == 1:# cylindrical\n    fout[1:si_r] = (rr[1:]*v[1:] - rr[:-1]*v[:-1])/(dr*0.5*(rr[1:]+rr[:-1])) - h[1:-1] + h0[1:-1]\n    fout[si_r+1:] = -v -v**2/rr + dhdr\n    fout[si_r+1] = 0.0\n\n  return fout\n\nsol = fsolve(f,xx,(si_r,rr,dr,h0,flag_geom))\nhf = sol[1:si_r]\nvf = sol[si_r+1:]\n\nplt.figure()\nplt.plot(rr2,hf,'k',label='h',linewidth=1)\nplt.plot(rr2,h0[1:-1],'k--',linewidth=1)\n#plt.plot(rr,vf,'r',label='v',linewidth=1)\nplt.xlabel('r/Rd')\nplt.ylabel('h/h0')\nplt.legend()\n", "meta": {"hexsha": "d6269b42fc8365baf34b9fface3130e723419ec3", "size": 1986, "ext": "py", "lang": "Python", "max_stars_repo_path": "tank_geostrophic_adjust/analysis/geostrophic_adjutment.py", "max_stars_repo_name": "bderembl/mitgcm_configs", "max_stars_repo_head_hexsha": "8aa0343fc56e9da831e7a8b857838c4f4a76aa9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-13T05:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T05:18:38.000Z", "max_issues_repo_path": "tank_geostrophic_adjust/analysis/geostrophic_adjutment.py", "max_issues_repo_name": "bderembl/mitgcm_configs", "max_issues_repo_head_hexsha": "8aa0343fc56e9da831e7a8b857838c4f4a76aa9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tank_geostrophic_adjust/analysis/geostrophic_adjutment.py", "max_forks_repo_name": "bderembl/mitgcm_configs", "max_forks_repo_head_hexsha": "8aa0343fc56e9da831e7a8b857838c4f4a76aa9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-04-10T15:18:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T02:05:37.000Z", "avg_line_length": 23.3647058824, "max_line_length": 97, "alphanum_fraction": 0.635448137, "include": true, "reason": "import numpy,from scipy", "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.9059898248255075, "lm_q1q2_score": 0.868425425488652}}
{"text": "import numpy as np\nfrom scipy.integrate import odeint\n\n\ndef decay(y, t=0, l=1):\n    \"\"\"Linear decay model\n    \"\"\"\n    dydt = -l * y\n    return dydt\n\ndef logistic(y, t=0, r=1, k=1):\n    \"\"\"Logistic growth model\n    \"\"\"\n    dydt = r*y*(1 - y/k)\n    return dydt\n\ndef ass(y, t=0):\n    \"\"\"Basic model with two alternative stable states\n    \"\"\"\n    dydt = -y**3 + y\n    return dydt\n\n\ndef lotkavolterra(y, t=0, a=1, b=1, c=1, d=1):\n    \"\"\"Lotka-Volterra predator prey model\n    \"\"\"\n    prey, pred = y\n    dydt = [a * prey - b * pred * prey,\n            c * pred * prey - d * pred]\n    return dydt\n\ndef duffing(state, t, g=0.2, w=1.2, a=-1, b=1, d=0.3):\n    \"\"\" Duffing oscillator\n    Ref: https://en.wikipedia.org/wiki/Duffing_equation\n    \"\"\"\n    x, v = state\n    dydt = [v,\n            -a*x - b*x**3 - d*v + g*np.cos(w*t)]\n    return dydt\n\ndef strogatz(state, t=0, w=(2,1), k=(2,1)):\n    \"\"\" Strogatz coupled oscillators model\n    \"\"\"\n    if callable(w) & callable(k):\n        w = w(t)\n        k = k(t)\n\n    th1, th2 = state\n    dydt = [w[0] + k[0]*np.sin(th2 - th1),\n            w[1] + k[1]*np.sin(th1 - th2)]\n\n    return dydt\n\ndef dphilrob(state, t=0, tmax='default', Qmax=100*3600, theta=10, sigma=3, vmaSa=1, vvm=1.9/3600, vmv=1.9/3600, vvc=6.3, vvh=0.19, Xi=10.8, mu=1e-3, taum=10/3600, tauv=10/3600, w=2*np.pi/24, alpha=0.0):\n\n    # Define auxiliary functions\n\n    ## Saturation function\n    S = lambda V : Qmax/(1 + np.exp((theta-V)/sigma))\n\n    ## External forcing\n    if tmax == 'default':\n        C = lambda t : 0.5*(1 + np.cos(w*(t - alpha)))\n    else:\n        C = lambda t : (1 - t / tmax)*0.5*(1 + np.cos(w*(t - alpha)))\n        \n    Vv, Vm, H = state\n    dydt =[(             -vvm*S(Vm) + vvh*H - vvc*C(t)         - Vv)/tauv, # Ventro-lateral preoptic area activity\n           (-vmv*S(Vv)                     + vmaSa             - Vm)/taum, # Mono-aminergic group activity\n           (              mu*S(Vm)                             -  H)/Xi] # Homeostatic pressure\n\n    return dydt\n\ndef lorenz(state, t=0, a=10, b=28, c=8/3):\n    x, y, z = state\n    dydt = [a*(y - x),\n            x*(b - z) - y,\n            x*y - c*z]\n\n    return dydt\n\ndef competition(y, t=0, r=1, a=1):\n    \"\"\" Basic competition model\n    \"\"\"\n    ry = np.multiply(r, y)\n    ay = np.dot(a, y)\n    dydt = np.multiply(ry, (1-ay))\n\n    return dydt\n\ndef rosmac(y, t=0, r0=0.5, k=10, g0=0.4, h=2, l=0.15, e=0.6):\n    \"\"\" Rosenzweig-MacArthur predator prey model\n    \"\"\"\n    prey, cons = y\n\n    def r(x):\n        \"\"\" Growth rate \"\"\"\n        return r0*(1 - x/k)\n\n    def g(x):\n        \"\"\" Grazing rate \"\"\"\n        return g0/(x + h)\n\n    dydt = [r(prey)*prey -g(prey)*prey*cons,\n            -l*cons + e*g(prey)*prey*cons]\n    return dydt\n\n\ndef hopf(state, t=0, a=1, b=1, l=-1):\n    \"\"\"Normal form for the Hopf bifurcation\n    \"\"\"\n    from phdtools.dyntools import polarToCartesian\n\n    x, y = state\n\n    def hopf_pol(state, t=t, a=a, b=b, l=l):\n        \"\"\"Normal form for the Hopf bifurcation in polar coordinates\n        \"\"\"\n        r, th = state\n        drdt = [r * (l + a * r**2),\n                1 + b * r**2]\n        return drdt\n\n    hopf_cart = polarToCartesian(hopf_pol)\n    return hopf_cart(state)\n\ndef oscgen(state, t=0, amp=1, w=2*np.pi, g=1):\n    \"\"\"Oscillations generator\n    \"\"\"\n    from phdtools.dyntools import polarToCartesian\n\n    x, y = state\n\n    def oscgen_pol(state, t=t, amp=amp, w=w, g=g):\n        \"\"\"Oscillations generator in polar coordinates\n        \"\"\"\n        r, th = state\n        drdt = [g * (amp - r),\n                w]\n        return drdt\n\n    oscgen_cart = polarToCartesian(oscgen_pol)\n    return oscgen_cart(state)\n\ndef reset_up(df, th_data, y0, ts, tinit):\n\n    nsteps = len(ts)\n    ys = np.zeros(nsteps)\n    ys[0] = y0\n    for i in range(1, nsteps):\n        if ts[i] > tinit:\n            if ys[i-1] < th_data[i-1]:\n                ys[i] = ys[i-1] + df(ys[i-1], ts[i-1])*(ts[i] - ts[i-1])\n            else:\n                ys[i] = 0.0\n        else:\n            ys[i] = ys[i-1]\n\n    return ys\n", "meta": {"hexsha": "cc6f5b4708f871c4a2aa4942bc41c43dba9aecc0", "size": 4001, "ext": "py", "lang": "Python", "max_stars_repo_path": "phdtools/models.py", "max_stars_repo_name": "PabRod/phdtools", "max_stars_repo_head_hexsha": "c8d1e89dbae824ab2632b5c83e7bbe62c7d30950", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phdtools/models.py", "max_issues_repo_name": "PabRod/phdtools", "max_issues_repo_head_hexsha": "c8d1e89dbae824ab2632b5c83e7bbe62c7d30950", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phdtools/models.py", "max_forks_repo_name": "PabRod/phdtools", "max_forks_repo_head_hexsha": "c8d1e89dbae824ab2632b5c83e7bbe62c7d30950", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.00625, "max_line_length": 202, "alphanum_fraction": 0.504623844, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885904, "lm_q2_score": 0.9059898159413479, "lm_q1q2_score": 0.8684254191190279}}
{"text": "#python3 Steven 11/15/2020, Auckland,NZ\n#Loss function\n#Reference: https://en.wikipedia.org/wiki/Loss_function\n#https://papers.nips.cc/paper/2008/file/f5deaeeae1538fb6c45901d524ee2f98-Paper.pdf\nimport numpy as np\n\ndef Least_squares(x): #LS\n    return (1-x)**2\n\ndef Modified_LS(x):\n    def loss(x):\n        return (np.max(1-x, 0))**2\n    return list(map(loss, list(x)))\n\ndef SVM_Loss(x): #Hinge loss, SVM using\n    def loss(x):\n        return np.max(1-x, 0)\n    return list(map(loss, list(x)))\n\ndef Boosting_Loss(x):\n    return np.exp(-1*x)\n\ndef LogisticRegression(x):\n    return np.log(1+np.exp(-1*x))\n\ndef Savage_loss(x):\n    return 1/(1+np.exp(2*x))**2\n\ndef zero_one(x):\n    y = np.zeros_like(x)\n    l = np.where(x < 0)\n    if len(l) != 0:\n        y[l[0]]=1\n    return y\n\n#Cross-Entropy loss L = -(y*log(y') + (1-y)*log(1-y'))\ndef crossEntropy_GT01(y, yPred): # 0/1 classification, y:Ground truth: 0 or 1, yPred:0~1\n    if y == 0:\n        return -1*np.log(1-yPred)\n    return -1*np.log(yPred) #y=1\n\n#Cross-Entropy loss L = log(1 + e^(-y*y')) , activefun=sigmoid()\ndef crossEntropy_GT02(y, yPred): # +1/1 classification, y:Ground truth:-1 or +1, yPred:-1~1\n    if y == 1:\n        return np.log(1 + np.exp(-1*yPred))\n    return np.log(1 + np.exp(yPred)) #y=-1\n\n#Cross-Entropy(CE) Loss: CE(p) = -log(p), when y=1\n#wighted Cross-Entropy, like Focal loss(FC), FC(p) = -(1-p)^gamma*log(p)\n# FC == CE,when gamma == 0\ndef FocalLosss(p, gamma=0):\n    return -np.power(1-p, gamma)*np.log(p) #return -gamma*np.log(p)\n\n#CE(p) = -log(1-p), when y=0\n#FC(p) = -(p)^gamma*log(1-p)\ndef FocalLosss1(p, gamma=0):\n    return -np.power(p, gamma)*np.log(1-p) #return -gamma*np.log(p)\n\ndef TripletLoss(x, m=0.2):#https://en.wikipedia.org/wiki/Triplet_loss\n    #max(t_p - t_n + m, 0)\n    def loss(t):\n        return max(t+m, 0)\n    return list(map(loss, list(x)))\n\ndef ContrastiveLoss(x, m=0.2):\n    #max(t_p - t_n + m, 0)\n    def loss(t):\n        return max(m-t, 0)\n    return list(map(loss, list(x)))\n\ndef BinomialDevianceLoss(x):\n    return np.log(1+np.exp(-2*x))\n", "meta": {"hexsha": "980f8b393af597b91a71912ff5f61f8682cddf13", "size": 2045, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/lossFunc.py", "max_stars_repo_name": "StevenHuang2020/ML", "max_stars_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lossFunc.py", "max_issues_repo_name": "StevenHuang2020/ML", "max_issues_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lossFunc.py", "max_forks_repo_name": "StevenHuang2020/ML", "max_forks_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0136986301, "max_line_length": 91, "alphanum_fraction": 0.6127139364, "include": true, "reason": "import numpy", "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197139, "lm_q2_score": 0.9059898121338507, "lm_q1q2_score": 0.8684254133232202}}
{"text": "# Computação vetorizada com *numpy*\n\n## Visão geral\n\n- *Computação vetorizada* relaciona-se à execução de operações que podem ser feitas diretamente sobre *arrays*.\n\n- *Arrays* multidimensionais: vetores (1D), matrizes (2D) e tensores (3D ou mais). \n\n- O *numpy* é a biblioteca Python para computação vetorizada com *arrays* multidimensionais.\n\n- Confere \"superpoderes\" às listas e eficiência a cálculos numéricos gerais.\n\n- Com *numpy*, podemos ler e escrever arquivos, resolver sistemas lineares e realizar muito mais.\n\n## Um conselho a ser seguido \n\n> Vetorize seus cálculos numéricos evitando laços, iterações e repetições o máximo possível!\n\n## Motivação\n\nEste exemplo compara a eficiência de operações feitas com listas comuns e com *numpy*.\n\nimport numpy as np # alias np \n\nL = range(500)\n%timeit -n 10 [i**2 for i in L] # executa o laço 10 vezes\n\na = np.arange(500)\n%timeit -n 10 a**2 # eleva ao quadrado diretamente 10 vezes\n\n- 1 µs = $10^{-6}$ segundo \n- 1 ns = $10^{-9}$ segundo\n\n## Criação de arrays unidimensionais (1D)\n\na = [1,2,3]\nnp.array(a) # a partir de lista\n\nnp.array([1,2,3]) # diretamente\n\nnp.array([2]*5)\n\n## Criação de arrays bidimensionais (2D)\n\nA = [ [1,2], [0,2] ] # lista de listas\nnp.array(A) # matrix 2 x 2\n\nnp.array([ [1,2], [0,2] ]) # diretamente\n\nA2 = [[1,2,3],[4,3,2]] # cada lista é uma linha da matriz\nnp.array(A2) # matriz 2 x 3 \n\nnp.array([1,1],[0,1]) # colchetes externos são obrigatórios! \n\n### Dimensão, formato e comprimento\n\nx = np.array(a)\nprint(a)\nnp.ndim(x) # aplica a função ndim\n\nx.ndim # como método\n\nnp.shape(x) # formato 1 x 3\n\nx.shape # sem parênteses \n\nlen(x) # comprimento\n\nA = [[1,2,3],[4,5,6]]\nX = np.array(A)\nnp.ndim(X) # array bidimensional\nX\n\nnp.shape(X) # 2 x 2\n\nlen(X) # apenas um comprimento. Qual?\n\nX2 = np.array(A2)\nlen(X2) # apenas da primeira dimensão. LINHAS\n\nX2.shape\n\n## Funções para criação de arrays\n\n### `arange`\n\n**Exemplo:** crie um array de números ímpares positivos menores do que 36.\n\nnp.arange(1,36,2) # start,stop,step\n\n**Exemplo:** crie um array de números pares positivos menores ou iguais a 62.\n\nnp.arange(0,63,2)\n\n**Exemplo:** calcule o valor de $f(x) = x^3 + 2x$ para $x$ elementos dos arrays anteriores.\n\nimp, par = np.arange(1,36,2), np.arange(0,63,2)\nf = lambda x: x**3 + 2*x\nfi, fp = f(imp), f(par)\nprint(fi)\nprint(fp)\n\n### `linspace`\n\n**Exemplo:** crie um array igualmente espaçado de elementos em [0,1] com 11 elementos.\n\nnp.linspace(0,1,num=11)\n\nnp.linspace(0,1,11) # 'num' pode ser omitido\n\nx = np.linspace(0,1,10,endpoint=False) # exclui último\nx\n\ny = np.arange(0,1,0.1) # equivalente\ny\n\nx == y # comparação é elemento a elemento\n\nx == -y # apenas 0 é True\n\nx[1:] == y[1:] # indexação\n\n### `all` e `any`\n\nnp.all( x == y ) # verifica se todos são 'True' \n\nnp.any( x == -y ) # verifica se pelo menos um é 'True'\n\n### `random`\n\n**Exemplo**: crie um *array* 1D com 5 números aleatórios entre [0,1].\n\nr = np.random.rand(5)\nr\n\n**Exemplo**: crie um *array* 1D com 50 números inteiros aleatórios entre [0,7].\n\nr2 = np.random.randint(0,7+1,50) # menor, maior é 8 (exclusive), tamanho\nr2\n\n**Exemplo**: crie uma matriz m x n com números inteiros aleatórios entre inteiros [l,h].\n\ndef gera_matriz(m,n,l,h):\n    return np.random.randint(l,h,(m,n)) # tupla (m,n)\n\ngera_matriz(2,2,0,2)\n\ngera_matriz(3,2,0,4)\n\ngera_matriz(4,4,-2,7)\n\n### `ones`\n\nCriando arrays unitários.\n\nnp.ones(4)\n\nnp.ones((6,6)) # tupla necessária para linhas e colunas\n\n### `eye`\n\nCriando arrays 2D identidade. 1 na diagonal e 0 nas demais.\n\nnp.eye(15) # matriz identidade 3 x 3 \n\n### `zeros`\n\nArrays nulos.\n\nnp.zeros(8)\n\nnp.zeros((3,3)) # 2 x 4\n\n### `full`\n\nArrays de valor constante.\n\nnp.full(3,0) # 1 x 3 com constante 0\n\nnp.full(shape=(3,),fill_value=0)\n\nF1 = np.full(shape=(2,2),fill_value=1) # 2 x 2 com 1\nF1\n\nF1 == np.ones(2) # mesmo resultado que ones\n\nOutras maneiras:\n\nF2 = 3*np.ones((4,4))\nF2\n\n## Especificando tipos de dados \n\nF2\n\nF3 = np.full((4,4),3)\nF3\n\nF2 == F3 # valores iguais\n\nF2.dtype == F3.dtype # tipos diferentes\n\nF2.dtype\n\nF3.dtype\n\nEspecificamos o tipo de dados com `dtype`\n\nnp.ones((4,2),dtype=bool) # matriz de booleanos\n\nnp.ones((4,2),dtype=str) # matriz de strings; 'U1' diz que há no máximo 1 caracter\n\nS = np.array(['dias','mes','ano'])\nS.dtype # 4 é o no. máximo de caracteres nas strings\n\n## Indexação e fatiamento\n\nFuncionam de maneira similar ao uso com listas\n\nI = np.linspace(0,20,11)\nI\n\nI[3],I[2:4],I[5:8],I[-4:-1]\n\nI[::-1] # invertendo o array\n\nI2 = np.array([I,2*I,3*I,4*I])\nI2\n\nEm arrays bidimensionais, a indexação é feita por meio de uma tupla. Porém, a explicitação dos parênteses é desnecessária.\n\nI2[(2,3)] # 3a. linha; 4a. coluna\n\nI2[2,3]\n\nI2[0,:] # 1a. linha\n\nI2[1,:] # 2a. linha\n\nI2[-1,:] # última linha\n\nI2[:,0] # 1a. coluna\n\nI2[:,1] # 2a. coluna\n\nI2[:,8] # 9a. coluna\n\nI2[:,2:4] # 3a. - 4a. coluna\n\nI2[1:3,6:10] # submatriz: linhas 2 - 3; 7-10\n\n### Alteração de valores\n\nOs arrays são mutáveis por indexação.\n\nA3 = np.random.rand(4,4)\nA3\n\nA3[0:4,0] = -1\nA3\n\nA3[:,-1] = -1\nA3\n\nA3[1:3,1:3] = 0\nA3\n\nPodemos alterar valores com arrays.\n\nA3[1,:] = -2*np.ones(4)\nA3\n\nA indexação pode usar um comprimento de passo (*step*).\n\nA3[0:4:3,1:3] = np.full((1,2),8) # na indexação esquerda, 1a. linha : 4a. linha : step de 3\nA3\n\n### `newaxis`\n\n`newaxis` é uma instância do `numpy` que permite aumentar de 1 a dimensão de um array existente. \n\n**Exemplo:** como inserir a diagonal de uma matriz em uma segunda matriz como uma coluna adicional?\n\nCriamos duas matrizes aleatórias.\n\n# matriz 4 x 4 de inteiros aleatórios entre 0 e 9\nB1 = np.random.randint(0,10,(4,4)) \nB1\n\n# matriz 4 x 4 de inteiros aleatórios entre -10 e 9\nB2 = np.random.randint(-10,10,(4,4)) \nB2\n\nExtraímos a diagonal da primeira.\n\n# diagonal de B1\ndb1 = np.diag(B1)\ndb1\n\nNotemos agora que as dimensões são diferentes.\n\nprint(B2.ndim)\nprint(db1.ndim)\n\nPara podermos aglutinar a diagonal como uma nova coluna na primeira matriz, primeiro temos que transformar o array unidimensional para uma matriz.  \n\ndb1 = db1[:,np.newaxis]\nprint(db1.ndim) # agora o array é bidimensional\ndb1 \n\n`newaxis` é um \"eixo imaginário\" incluído *inplace*, mas que altera dinamicamente o array. No caso acima, o array tornou-se em uma coluna.\n\nAgora, podemos \"colar\" um array 2D com outro por uma concatenação. \n\n### `concatenate`\n\n`concatenate` é usado para concatenar *arrays*. A concatenação requer uma tupla contendo os *arrays* a concatenar e o eixo de referência.\n\nB3 = np.concatenate((B2,db1), axis=1) \nB3\n\n- `axis=1` indica concatenação ao longo da coluna\n- Inserimos a segunda diagonal como uma coluna adicional na segunda matriz\n- Isto foi possível porque ambas as matrizes eram de mesmo formato\n- É necessário observar o formato dos *arrays*\n\n#### `axis`\n\n- Nos arrays multidimensionais do Python, `axis` é usado para indicar a \"direção\" dos dados. \n\nEm arrays bidimensionais: \n- `axis=0` refere-se à direção de cima para baixo (ao longo das linhas)\n- `axis=1` refere-se à direção da esquerda para a direita (ao longo das colunas). \n\n**Obs.:** note que a palavra `axis` (\"eixo\") deve ser usada, e não \"axes\" (\"eixos\").\n\nPara aglutinar uma linha na matriz anterior, fazemos uma concatenação em linha.\n\n# array de zeros com mesmo número de colunas de B3\ndb2 = np.zeros(np.shape(B3)[1]) \ndb2\n\ndb2 = db2[np.newaxis,:] # cria o \"eixo imaginário\" na direção 0\n\nB4 = np.concatenate((B3,db2),axis=0) # concatena ao longo das linhas\nB4\n\n## Indexação avançada\n\nPodemos usar máscaras como artifícios para indexação avançada.\n\nIA1 = np.arange(-10,11)\nIA1\n\nVamos criar um *array* aleatório de True e False no mesmo formato que o *array* anterior.\n\nmask1 = np.random.randint(0,2,np.shape(IA1),dtype=bool) \nmask1\n\nEsta *máscara booleana* pode ser aplicada no array para extrair apenas os elementos cujos índices são marcados como `True` pela máscara.\n\nIA1[mask1]\n\nHá maneiras mais diretas aplicáveis a filtragens. Para extrair os valores negativos do array:\n\nIA1 < 0 # máscara booleana\n\nIA1[IA1 < 0] \n\nPara extrair os valores positivos do array:\n\nIA1[IA1 > 0] # máscara booleana para positivos\n\nPara extrair os valores no intervalo $]-2,5[$, fazemos:\n\nIA1[(IA1 > -2) & (IA1 < 5)] # & é o operador booleano 'elemento a elemento'\n\nPara extrair pares e ímpares, poderíamos fazer:\n\npares, impares = IA1[IA1 % 2 == 0] , IA1[IA1 % 2 == 1] \npares,impares\n\nPodemos usar listas como máscaras:\n\nalguns = pares[[0,2,3,5]] # acessa 1o., 3o. 4o. e 6o. elemento de 'pares'\n\nimpares[alguns] # estude este caso\n\n- -10 é indexação reversa excededida. Retorna o 1o. elemento do array: -9. \n- -6 acessa o 6o. elemento a partir da direita, que é -1. \n- -4 acessa o 4o. elemento a partir da direita. \n- 0 acessa o primeiro elemento que é -9. \n\n## Operações elemento a elemento\n\n- As operações aritméticas e de cálculo são feitas elemento a elemento nos *arrays*. \n- Já fizemos isso, mas vejamos claramente com mais exemplos\n\na = np.array([1,2,3]) \nb = np.array([4,5,6])\n\n# operações elemento a elemento\nprint(a + b) \nprint(a - b) \nprint(a * b) \nprint(a / b)\nprint(a ** b)\n\n2*a + 4*b - 6*b**2 + 1.1/2*a\n\n## Funções matemáticas\n\n- O `numpy` possui a maioria dass funções de `math` e outras mais. \n- As funções são diretamente aplicáveis aos *arrays*. \n- Como era com listas? Tínhamos de iterar sobre elas... \n- Com `numpy`, esse problema está resolvido: isto é computação vetorizada.\n\nx = np.arange(10)\nx\n\nnp.sqrt(x)\n\nnp.cos(x) + 2*np.sqrt(x)\n\ny = np.sin(2*x)\nz = np.exp(x + y)\ny - z\n\n### Problema resolvido (Laboratório Computacional 1C)\n\nObserve a tabela a seguir, onde **DS (UA)** é a distância do referido planeta do até o Sol em unidades astronômicas (UA), **Tm (F)** sua temperatura superficial mínima em graus Farenheit e **TM (F)** sua temperatura superficial máxima em graus Farenheit.\n\n| | DS (UA) | Tm (F) | TM (F) | DS (km) | TmM (C) |\n|--|--|--|--|--|--|\nMercúrio | 0.39 | -275 | 840 | ? | ? |\nVênus | 0.723 | 870 | 870 | ? | ? |\nTerra | 1.0 | -129 | 136 | ? | ? |\nMarte | 1.524 | -195 | 70 | ? | ? |\n\n- Escreva um código para converter a temperatura dos planetas de graus Farenheit (**F**) para Celsius (**C**).\n\n- Escreva um código para converter unidades astronômicas em quilômetros.\n\n- Imprima os valores que deveriam ser inseridos na coluna **DS (km)** horizontalmente usando `print`.\n\n- Repita o item anterior para a coluna **TmM (C)**, que é a média aritmética entre **Tm** e **TM**.\n    \n    \n*Observação:* use notação científica (exemplo: $4.2 \\times 10^8$ pode ser escrito como `4.2e8` em Python).\n\n#### Resolução\n\nHá várias maneiras de resolver. Aqui apresentamos uma estratégia com `lambdas`.\n\n- Montar os arrays dos dados numéricos.\n\nDS = np.array([0.39,0.723,1.0,1.524])\nTm = np.array([-275,870,-129,-195])\nTM = np.array([840,870,136,70])\n\n- Fórmula e cálculo da conversão Farenheit para Celsius:\n\nC = lambda F: 5/9*(F-32)\nCTm = C(Tm)\nCTM = C(TM)\nprint(CTm) # minimas em C\nprint(CTM) # maximas em C\n\n- Fórmula e cálculo da conversão UA para km:\n\nUA = lambda km: 1.496e+8*km \nUADS = UA(DS) \nprint(UADS) # valores a inserir\n\n- Cálculo da média\n\nTmM = 0.5*(CTm + CTM)\nprint(TmM)\n\n### `reshape` e `hstack`\n\n- Montagem do array bidimensional com resultdos não requisitada. \n- Mostramos uma maneira de fazer isto com `reshape` e `hstack\n- `reshape` é uma função para reformatar os dados\n- `hstack` é usada para \"empilhar\" arrays horizontalmente.\n\n**Obs:** consulte também `vstack`.\n\n#####  Nota: \n    \n- Todos os *arrays* são unidimensionais. \n- Vamos torná-los bidimensionais com formato 4 x 1 \n- Depois, empilhá-los horizontalmente -> direção do eixo 1 (esquerda para direita). \n\ntodos = [DS,CTm,CTM,UADS,TmM] # lista com todos os arrays\n\nfor i,ar in enumerate(todos):\n    todos[i] = np.reshape(ar, (4,1)) # reformata\n\nfinal = np.hstack(todos) # empilha\n\nExplicando o que fizemos: \n\n- Colocamos todos os arrays em uma lista: neste ponto, nada novo.\n- Iteramos sobre a lista, reformatamos um por um e reatribuímos na mesma lista como arrays bidimensionais\n\nPara o segundo ponto, observe:\n\nDS.shape # formato é 1 x 4 (unidimensional)\n\nnp.reshape(DS,(4,1)) # reformata \n\nnp.reshape(DS,(4,1)).shape # novo formato é 4 x 1\n\nnp.reshape(DS,(4,1)).ndim # o array agora é bidimensional\n\n- Procedendo assim para todos, reformatamos e adicionamos cada um em uma lista. \n- Se desejarmos, sobrescrevemos a lista ou não. \n- Na resolução, escolhemos sobrescrever. \n- Assim, suponha que a lista dos arrays reformatados seja:\n\nL = [np.reshape(DS,(4,1)),np.reshape(TmM,(4,1))] # apenas DS e TmM\nL\n\n- Criamos o array final por empilhamento.\n\nNote que: \n\n- A lista `L` possui 2 arrays de formato 4 x 1. \n- Para criar o array 4 x 2, faremos um empilhamento horizontal \n- Isto é similar a uma concatenação na direção 1\n\nLh = np.hstack(L)\nLh\n\nAgora podemos verificar que, de fato, o array está na forma como queremos. \n\nLh[:,0] # 1a. coluna idêntica à DS\n\nLh[:,0] == DS # teste\n\nnp.all( Lh[:,0] == DS ) # teste completo\n\nLh[:,1] # 2a. coluna idêntica a TmM\n\nLh[:,1] == TmM # teste\n\nnp.all( Lh[:,1] == TmM ) # teste completo\n\n## *Broadcasting*\n\n*Broadcasting* é a capacidade que o *numpy* oferece para realizarmos operações em arrays com diferentes dimensões.\n\n**Obs:** para entender o *broadcasting*, veja o material.\n\n### Regras do *broadcasting* \n\n1. Se dois *arrays* tiverem dimensões diferentes, o formato do array com menor dimensão é preenchido por 1 do lado esquerdo.\n2. Se o formato dos *arrays* não for igual em dimensão alguma, o array com tamanho igual a 1 é esticado nesta direção para ficar no mesmo tamanho correspondente do outro array.\n3. Se em qualquer direção os tamanhos dos *arrays* forem diferentes e nenhum deles for igual a 1, então um erro é retornado.\n\n#### Exemplo da Regra 1\n\nA = np.array([[1, 2, 3],[4, 5, 6]]) # array 2D\nb = np.array([10, 20, 30]) # array 1D\nprint(A.shape)\nprint(b.shape)\n\nA + b\n\nA soma pode ser realizada mesmo assim. O que ocorreu? Cada linha de `A` foi somada à única linha de `b`. O *broadcasting* amplia o array de menor dimensão automaticamente da seguinte forma:\n\nPela regra 1, o *array* `b` tem dimensão menor. Então, ele é preenchido de modo que:\n\n```python\nA.shape -> (2, 3)\nb.shape -> (1, 3)\n```\n\nPela regra 2, a primeira dimensão de `A` é 2 e a de `b` é 1. Então, a dimensão de `b` é \"esticada\", de modo que:\n\n```python\nA.shape -> (2, 3)\nb.shape -> (2, 3)\n```\n\nA mesma operação poderia ter sido feita com:\n\nA + np.array([b,b])\n\n#### Exemplo da Regra 2\n\nA = np.arange(3).reshape((3, 1))\nb = np.arange(3)\nprint(A.shape)\nprint(b.shape)\n\nA + b\n\nNeste caso, ambos os arrays sofrem *broadcasting*. Ele ocorre da seguinte forma.\n\nComo \n\n```python \nA.shape = (3, 1)\nb.shape = (3,)\n```\na regra 1 diz que `b` deve ser preenchido de modo que\n\n```python\nA.shape -> (3, 1)\nb.shape -> (1, 3)\n```\ne, pela regra 2, cada uma das dimensões 1 deve ser alterada de modo que:\n\n```python\nA.shape -> (3, 3)\nb.shape -> (3, 3)\n```\n\nAssim, o *broadcasting* é permitido.\n\n#### Exemplo da Regra 3\n\nA = np.ones((3, 2))\nb = np.arange(3)\nprint(A.shape)\nprint(b.shape)\n\nA + b\n\nNeste exemplo, o *broadcasting* não é permitido. O caso é levemente diferente do primeiro exemplo em que `A` é transposta.\n\nTemos que \n\n```python \nM.shape = (3, 2)\na.shape = (3,)\n```\n\nPela regra 1, devemos ter\n\n```python\nM.shape -> (3, 2)\na.shape -> (1, 3)\n```\n\ne, pela regra 2, a primeira dimensão deve ser esticada para combinar-se com a de `A` enquanto a segunda não é alterada por não ser 1.\n\n```python\nM.shape -> (3, 2)\na.shape -> (3, 3)\n```\nPorém, o formato final de ambos não se combina. Sendo incompatíveis, o *broadcasting* falha.", "meta": {"hexsha": "6fcbc34bc9e01f7ec9a9379484897428ffebd0ea", "size": 15441, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/rise/04a-computacao-vetorizada-rise.py", "max_stars_repo_name": "gcpeixoto/FMECD", "max_stars_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/jupyter_execute/rise/04a-computacao-vetorizada-rise.py", "max_issues_repo_name": "gcpeixoto/FMECD", "max_issues_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/rise/04a-computacao-vetorizada-rise.py", "max_forks_repo_name": "gcpeixoto/FMECD", "max_forks_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6100917431, "max_line_length": 254, "alphanum_fraction": 0.6842821061, "include": true, "reason": "import numpy", "num_tokens": 5376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088055075428, "lm_q2_score": 0.9353465152482724, "lm_q1q2_score": 0.8683839409572912}}
{"text": "import sys\nimport random\nimport numpy as np\nimport scipy as sc\nimport matplotlib as mlp\nimport matplotlib.pyplot as plt\n\nfrom matplotlib import rc\nfrom scipy import special\n\ndef cauchyPDF(x, x0 , gamma = 1):\n    '''\n    Returns the cauchy PDF\n    @params:\n        x (np.array): Points of interest\n        x0 (float): Mean location of cauchy\n        gamma (float): probably error\n    '''\n    return 1 / (np.pi*gamma*(1 + (x**2 -2*x*x0 + x0**2)/(gamma**2)))\n\ndef cauchy(n, x0 , gamma = 1):\n    '''\n    Randomly samples from a cauchy PDF\n    @params:\n        n (int): Number of samples desired\n        x0 (float): Mean location of cauchy\n        gamma (float): probably error\n    '''\n    Y = np.random.uniform(0,1,n)\n    return gamma*np.tan(np.pi*(Y-0.5)) + x0\n\ndef gammaPDF(x, a , b = 1.0):\n    '''\n    Returns the gamma PDF\n    @params:\n        x (np.array): Points of interest\n        a (float): hyper-parameter\n        b (float): hyper-parameter\n    '''\n    #Note scipy.special.expit = np.exp but np.exp will over flow when x is negative\n    #scipy.special.expit dances around that by computing 1/(1+exp(-x))\n    return x**(a-1) * sc.special.expit(-x/b - np.log(sc.special.gamma(a)) + np.log(b**a))\n\nif __name__ == '__main__':\n    plt.close('all')\n    mlp.rcParams['font.family'] = ['times new roman'] # default is sans-serif\n    rc('text', usetex=True)\n\n    #Set up subplots\n    f, ax = plt.subplots(1, 2, figsize=(10, 5))\n    f.suptitle('Homework 4 Problem 1', fontsize=14)\n\n    #Parameters\n    a = 10 # Must be greater than 1\n    M = (np.pi*np.sqrt(2*a-1))/sc.special.gamma(a)*np.exp(-a+1)*(a-1)**(a-1)\n    x =  np.linspace(0,30,100)\n\n    gamma_PDF = gammaPDF(x, a)\n    cauchy_PDF = M*cauchyPDF(x, a-1, np.sqrt(2*a-1))\n\n    #Accept/Reject Monte carlo\n    #Get random samples from our \"simpler\" cauchy distribution\n    X = cauchy(5000, a-1, np.sqrt(2*a-1)).tolist()\n    #Now accept/reject the sample points\n    samples = [ x0 for x0 in X  if (random.random() < gammaPDF(x0, a)/(M*cauchyPDF(x0, a-1, np.sqrt(2*a-1))))]\n    bins = np.linspace(0, 30, 30)\n\n    #Plot profiles\n    ax[0].plot(x, gamma_PDF, 'g', label=r'$Gamma(x|a,1)$')\n    ax[0].plot(x, cauchy_PDF, 'r', label=r'$Cauchy(x|a-1,\\sqrt{2a-1})$') \n    ax[0].set_xlim((0,30))\n    ax[0].set_ylim(ymin=0)\n    ax[0].legend()\n    ax[0].set_title('Profiles')\n    \n    #Plot histrogram\n    ax[1].hist(np.array(samples), bins, color='blue', alpha = 0.5, normed=1, edgecolor = \"black\")\n    ax[1].plot(x, gamma_PDF, 'g', label=r'$Gamma(x|a,1)$')\n    ax[1].set_xlim((0,30))\n    ax[1].set_ylim(ymin=0)\n    ax[1].legend()\n    ax[1].set_title('Accept/Reject')\n    plt.show()", "meta": {"hexsha": "8eab3f0d9d9103885c69e021adaee578d4e472d1", "size": 2620, "ext": "py", "lang": "Python", "max_stars_repo_path": "Homework/HW4-Software/Python_code/P1.py", "max_stars_repo_name": "shijiale0609/Statistical-Computing-Methods", "max_stars_repo_head_hexsha": "e780746d5f1e4b475bf38eb15d9d825daf45ffa6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homework/HW4-Software/Python_code/P1.py", "max_issues_repo_name": "shijiale0609/Statistical-Computing-Methods", "max_issues_repo_head_hexsha": "e780746d5f1e4b475bf38eb15d9d825daf45ffa6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homework/HW4-Software/Python_code/P1.py", "max_forks_repo_name": "shijiale0609/Statistical-Computing-Methods", "max_forks_repo_head_hexsha": "e780746d5f1e4b475bf38eb15d9d825daf45ffa6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5662650602, "max_line_length": 110, "alphanum_fraction": 0.6030534351, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9822877038891777, "lm_q2_score": 0.8840392878563336, "lm_q1q2_score": 0.8683809222162218}}
{"text": "import numpy as np\r\nfrom math import sqrt\r\nfrom tabulate import tabulate\r\n\r\ndef print_matrix(Title, M):\r\n    print(Title)\r\n    for row in M:\r\n        print([x for x in row])\r\n\r\n\r\ndef decompose_matrix(matrix):\r\n\r\n    n = len(matrix)\r\n    U = matrix.copy()\r\n    L = np.eye(n, dtype=np.double) #Identity Matrix\r\n    P = np.eye(n, dtype=np.double)\r\n    for i in range(n):\r\n        for k in range(i, n): \r\n            if ~np.isclose(U[i, i], 0.0): \r\n                break\r\n            U[[k, k+1]] = U[[k+1, k]]\r\n            P[[k, k+1]] = P[[k+1, k]]\r\n    \r\n        factor = U[i+1:, i] / U[i, i]\r\n        L[i+1:, i] = factor\r\n        U[i+1:] -= factor[:, np.newaxis] * U[i]\r\n\r\n\r\n    return P, L, U\r\n\r\ndef forward_substitution(L, b):\r\n\r\n    n = L.shape[0]\r\n    y = np.zeros_like(b, dtype=np.double);\r\n\r\n    y[0] = b[0] / L[0, 0]\r\n\r\n    for i in range(1, n):\r\n        y[i] = (b[i] - np.dot(L[i,:i], y[:i])) / L[i,i]  \r\n    return y\r\n\r\n\r\ndef back_substitution(U, y):\r\n    n = U.shape[0]\r\n    x = np.zeros_like(y, dtype=np.double);\r\n    x[-1] = y[-1] / U[-1, -1]\r\n\r\n    for i in range(n-2, -1, -1):\r\n        x[i] = (y[i] - np.dot(U[i,i:], x[i:])) / U[i,i]\r\n    return x\r\n\r\ndef plu_inverse(A):\r\n    n = len(A)\r\n    b = np.eye(n)\r\n    Ainv = np.zeros((n, n))\r\n    P, L, U = decompose_matrix(A)\r\n    for i in range(n):\r\n        y = forward_substitution(L, np.dot(P, b[i, :]))\r\n        Ainv[:, i] = back_substitution(U, y)\r\n    return Ainv\r\n\r\n\r\ndef find_condition_number(A):\r\n    \"\"\"Finds the condition number of the matrix A, given the inverse matrix\"\"\"\r\n\r\n\r\n\r\n    n = len(A)\r\n    \r\n\r\n    max_in_rows = np.amax(np.abs(A), axis=1) \r\n    max_in_normal = np.amax(A, axis=1)\r\n\r\n\r\n    \r\n    for i in range(n):          #Normalize matrix\r\n        for j in range(n):\r\n            if max_in_rows[i] == max_in_normal[i]:\r\n                A[i][j] = A[i][j]/max_in_rows[i]    \r\n            else:\r\n                A[i][j] = A[i][j]/-max_in_rows[i] \r\n\r\n    max_in_rows =np.amax(np.abs(A).sum(axis=1)) #Find max in  rows with sum of abs\r\n    A_inv = plu_inverse(np.array(A))\r\n\r\n    max_in_inv_rows = np.amax(np.abs(A_inv).sum(axis=1))\r\n    \r\n\r\n    cond_A = max_in_inv_rows*max_in_rows\r\n    print(\"Condition number of A: \", cond_A)\r\n\r\n\r\n\r\ndef transpose(L):\r\n    \"\"\"Transposes a lower triangular matrix L.\"\"\"\r\n    n = len(L)\r\n    LT = [[0.0] * n for i in range(n)]\r\n    for i in range(n):\r\n        for j in range(n):\r\n            LT[j][i] = L[i][j]\r\n    return LT\r\n\r\n\r\ndef cholesky(A):\r\n    '''\r\n    Cholesky decomposition of a positive definite matrix A.\r\n    Returns the lower triangular matrix L such that A = L*LT.\r\n    '''\r\n\r\n\r\n    n = len(A)\r\n\r\n    L = [[0.0] * n for i in range(n)]\r\n\r\n    for i in range(n):\r\n        for k in range(i+1):\r\n            tmp_sum = sum(L[i][j] * L[k][j] for j in range(k)) \r\n            \r\n            if (i == k):\r\n                L[i][k] = sqrt(A[i][i] - tmp_sum)   \r\n            else:\r\n                L[i][k] = (1.0 / L[k][k] * (A[i][k] - tmp_sum)) \r\n    U = transpose(L)\r\n    return L,U\r\n\r\n\r\n      \r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    \r\n    matrix = [[87.82557,0.0,-43.91278,3659.399,0.0,0.0],\r\n              [0.0,813199.7,-3659.399,203299.9,0.0,0.0],\r\n              [-43.91278,-3659.399,87.82557,0.0,-43.91278,3659.399],\r\n              [3659.399,203299.9,0,813199.7,-3659.399,203299.9],\r\n              [0.0,0.0,-43.91278,-3659.399,44.41278,-3659.399],\r\n              [0.0,0.0,3659.399,203299.9,-3659.399,406599.8]]\r\n    \r\n    \r\n    ## Question 1-A)\r\n    #P,L,U = decompose_matrix(np.array(matrix))\r\n    #print_matrix(\"L\", L)\r\n    #print_matrix(\"U\", U)\r\n\r\n    \r\n    ## Question 1-B)\r\n    #L,U = cholesky(matrix)\r\n    #print_matrix(\"L\", L)\r\n    #print_matrix(\"U\", U)\r\n\r\n    ## Question 1-C)\r\n    #A_Inv = plu_inverse(np.array(matrix))\r\n    #print_matrix(\"A_Inv\", A_Inv)\r\n\r\n    ## Question 1-D)\r\n    #find_condition_number(np.array(matrix))\r\n\r\n\r\n\r\n", "meta": {"hexsha": "ec15bef376eb888e9c465cf088497fd3bd7414ae", "size": 3864, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw-2/question1.py", "max_stars_repo_name": "emreaniloguz/ITU-MAT202E", "max_stars_repo_head_hexsha": "40298b0c3615185ecca27231c63f16e96b279a47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw-2/question1.py", "max_issues_repo_name": "emreaniloguz/ITU-MAT202E", "max_issues_repo_head_hexsha": "40298b0c3615185ecca27231c63f16e96b279a47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw-2/question1.py", "max_forks_repo_name": "emreaniloguz/ITU-MAT202E", "max_forks_repo_head_hexsha": "40298b0c3615185ecca27231c63f16e96b279a47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7055214724, "max_line_length": 83, "alphanum_fraction": 0.4883540373, "include": true, "reason": "import numpy", "num_tokens": 1252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561703644737, "lm_q2_score": 0.8962513765975758, "lm_q1q2_score": 0.868338676414215}}
{"text": "import numpy as np\n\ndef activation_function(name, x, derivative=False):\n    \"\"\"\n    Computes the activation function and its derivative.\n    \n    Parameters\n    ----------\n    name: str\n        Activation function name.\n          Options:\n              identity\n              sigmoid\n              softmax\n              tanh\n              relu  \n    \n    x: int/float/list/array\n        Input.\n    \n    derivative: bool\n        If true, returns the derivative of loss.\n        Default: False\n    \n    Returns\n    -------\n    Numpy array or list\n    \"\"\"\n    \n    if name == \"identity\":\n        if derivative:\n            return np.ones_like(x)\n        else:\n            return x\n    elif name == \"sigmoid\":\n        if derivative:\n            out = activation_function(name, x)\n            return out * ( 1 - out )\n        else:\n            # Prevents overflow\n            x_clipped = np.clip(x, -500, 500)\n            return 1 / (1 + np.exp(-x_clipped))\n    elif name == \"softmax\":\n        if derivative:\n            out = activation_function(name, x)\n            return out * (1 - out)\n        else:\n            # Prevents overflow\n            x_clipped = np.clip(x, -500, 500)\n            e_x = np.exp(x_clipped - np.max(x_clipped))\n            return e_x / np.sum(e_x, axis=1, keepdims=True)\n    elif name == \"tanh\":\n        if derivative:\n            out = activation_function(name, x)\n            return 1 - np.square(out)\n        else:\n            return 2 / (1 + np.exp(-2*x)) - 1\n    elif name == \"relu\":\n        if derivative:\n            return (x > 0) * 1\n        else:\n            return np.maximum(0, x)\n      \ndef loss_function(name, y, y_hat, derivative=False):\n    \"\"\"\n    Computes the loss and its derivative\n    \n    Parameters\n    ----------\n    name: str\n        Type of loss function.\n        Options:\n            mse ( Mean squared error )\n            ce ( Cross entropy ) \n    \n    y: list \n        numpy array ( target )\n    \n    y_hat: list\n        numpy array ( output )\n    \n    derivative: bool\n        If True, returns the derivative of loss.\n        Default: False\n    \n    Returns\n    -------\n    numpy array\n    \"\"\"\n    \n    # y - target, y_hat - output\n    # Mean Squared Error\n    if name == \"mse\":\n        if derivative:\n            return (y_hat - y)\n        else:\n            return np.mean((y - y_hat)**2)\n    # Log-likelihood\n    elif name == \"ll\":\n        if derivative:\n            return - (1 / y_hat)\n        else:\n            return -1 * np.log(y_hat)\n    # y - target prob distro, y_hat - output prob distro\n    # Cross Entropy\n    elif name == \"ce\":\n        if derivative:\n            # if activation fn is sigmoid/softmax\n            return (y_hat - y)    \n        else:\n            # prevents overflow\n            y_clipped = np.clip(y_hat, 1e-8, None)\n            return np.sum(np.nan_to_num(-y*np.log(y_clipped)-(1-y)*\n                                        np.log(1-y_clipped)))", "meta": {"hexsha": "779cec48aea4783fcb7e2fb91eeb13858e2fd012", "size": 2929, "ext": "py", "lang": "Python", "max_stars_repo_path": "customdl/base.py", "max_stars_repo_name": "Taarak9/Custom-Neural-Networks", "max_stars_repo_head_hexsha": "cda83294ed825159d5bd168264f143ea51f056c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-21T07:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T07:39:55.000Z", "max_issues_repo_path": "Feedforward Neural Network/base.py", "max_issues_repo_name": "Taarak9/Neural-Networks-Library", "max_issues_repo_head_hexsha": "6f8fff9d27f64a4ce397c0bd3b8e1a554ff7228e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Feedforward Neural Network/base.py", "max_forks_repo_name": "Taarak9/Neural-Networks-Library", "max_forks_repo_head_hexsha": "6f8fff9d27f64a4ce397c0bd3b8e1a554ff7228e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-20T17:17:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-20T17:17:36.000Z", "avg_line_length": 25.6929824561, "max_line_length": 67, "alphanum_fraction": 0.4871969956, "include": true, "reason": "import numpy", "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561667674652, "lm_q2_score": 0.8962513668985002, "lm_q1q2_score": 0.868338663793382}}
{"text": "from statistics import mean\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\n\nstyle.use('fivethirtyeight')\n\nxs = np.array([1,2,3,4,5,6], dtype = np.float64)\nys = np.array([5,4,6,5,6,7], dtype = np.float64)\n\ndef best_fit_slope_and_intercept(xs, ys):\n\tm = (  ((mean(xs)*mean(ys)) - mean(xs*ys)) / \n\t\t((mean(xs)*mean(xs)) - mean(xs*xs)) )  \n\n\tb = ( mean(ys) -(m* mean(xs)) )\n\treturn m, b\n\ndef squared_error(ys_orig, ys_line):\n\treturn sum((ys_line - ys_orig)**2)\n\n# r is co-efficient of determination\n \ndef coefficient_of_determination(ys_orig, ys_line):\n\ty_mean_line = [mean(ys_orig) for y in ys_orig]\n\tsquared_error_regr = squared_error(ys_orig, ys_line)\n\tsquared_error_y_mean = squared_error(ys_orig, y_mean_line)\n\treturn 1 - (squared_error_regr/squared_error_y_mean)\n\nm, b = best_fit_slope_and_intercept(xs, ys)\n\nregression_line = [(m*x)+b for x in xs]\n\npredict_x = 1.5\npredict_y = (m*predict_x + b)\n\n\nr_squared = coefficient_of_determination(ys, regression_line)\nprint(r_squared)\n\nplt.scatter(xs, ys)\nplt.scatter(predict_x, predict_y, color='g')\nplt.plot(xs, regression_line)\nplt.show()\n\n", "meta": {"hexsha": "ad6e77ce91e1187061a4c3b54b54ac47245f3dfc", "size": 1120, "ext": "py", "lang": "Python", "max_stars_repo_path": "LinearRegression_StockPriceDataSet/ML8_LinearRegression_SquaredError_Function.py", "max_stars_repo_name": "vaibhav2408/machineLearningSentdex", "max_stars_repo_head_hexsha": "b1b7fa75c7796cbf008877b44c3204cd5bc61960", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LinearRegression_StockPriceDataSet/ML8_LinearRegression_SquaredError_Function.py", "max_issues_repo_name": "vaibhav2408/machineLearningSentdex", "max_issues_repo_head_hexsha": "b1b7fa75c7796cbf008877b44c3204cd5bc61960", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LinearRegression_StockPriceDataSet/ML8_LinearRegression_SquaredError_Function.py", "max_forks_repo_name": "vaibhav2408/machineLearningSentdex", "max_forks_repo_head_hexsha": "b1b7fa75c7796cbf008877b44c3204cd5bc61960", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8888888889, "max_line_length": 61, "alphanum_fraction": 0.725, "include": true, "reason": "import numpy", "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9770226287518852, "lm_q2_score": 0.8887587824432529, "lm_q1q2_score": 0.8683374419490317}}
{"text": "import numpy as np\n \nclass bernoulli():\n    def pmf(x,p):\n        \"\"\"\n        probability mass function        \n        \"\"\"\n        f = p**x*(1-p)**(1-x)\n        return f\n    \n    def mean(p):\n        \"\"\"\n        expected value of bernoulli random variable\n        \"\"\"\n        return p\n    \n    def var(p):\n        \"\"\"\n        variance of bernoulli random variable\n        \"\"\"\n        return p*(1-p)\n    \n    def std(p):\n        \"\"\"\n        standart deviation of bernoulli random variable\n        \"\"\"\n        return bernoulli.var(p)**(1/2)\n    \n    def rvs(p,size=1):\n        \"\"\"\n        random variates\n        \"\"\"\n        rvs = np.array([])\n        for i in range(0,size):\n            if np.random.rand() <= p:\n                a=1\n                rvs = np.append(rvs,a)\n            else:\n                a=0\n                rvs = np.append(rvs,a)\n        return rvs\n       \n       \np=0.2 # probability of having an accident\n\nbernoulli.mean(p) # return -> 0.2\nbernoulli.var(p) # return -> 0.16\nbernoulli.std(p) # return -> 0.4\n\nbernoulli.rvs(p,size=10) \n#return-> array([0., 0., 0., 0., 1., 0., 1., 0., 0., 1.])\n", "meta": {"hexsha": "9bd2194b39698bc5890f2f1961b4b247098ef2e4", "size": 1113, "ext": "py", "lang": "Python", "max_stars_repo_path": "Algorithms/bernoulli_distribution.py", "max_stars_repo_name": "parth2050/Statistic_Playground", "max_stars_repo_head_hexsha": "572ffcccff32395f18f99eeb982ffd993e77bffd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Algorithms/bernoulli_distribution.py", "max_issues_repo_name": "parth2050/Statistic_Playground", "max_issues_repo_head_hexsha": "572ffcccff32395f18f99eeb982ffd993e77bffd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Algorithms/bernoulli_distribution.py", "max_forks_repo_name": "parth2050/Statistic_Playground", "max_forks_repo_head_hexsha": "572ffcccff32395f18f99eeb982ffd993e77bffd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4038461538, "max_line_length": 57, "alphanum_fraction": 0.4465408805, "include": true, "reason": "import numpy", "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446479186301, "lm_q2_score": 0.8918110454379297, "lm_q1q2_score": 0.8683070513453585}}
{"text": "#!/usr/bin/env python\n\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nPATH = 'view/'\nGRAPH = 'bisection'\nMAX = 30\nTOLERANCE = 0.00001\n\nlog = [] # a, b, c, fnc\n\ndef function ( x ): \n    return ( x**3 - x - 2 )\n\n\ndef same_sign(product_a , product_b) :\n    return ((product_a * product_b) > 0)\n\n\ndef bisection (fn, a, b, tol, nmax):\n    ''' description\n        is a root-finding method that applies to any continuous functions \n            for which one knows two values with opposite signs\n        The method consists of repeatedly bisecting the interval defined \n            by these values and \n            then selecting the subinterval in which the function changes sign, \n            and therefore must contain a root.\n    '''\n    # Bolzano's Theorem: check the intermediate value of functions a and b\n    if same_sign(fn(a), fn(b)):\n        return \"Error 32: Bolzano of Theorem\"\n        breakpoint\n        \n    # limit iterations to prevent infinit loop\n    for n in range(nmax) : \n        # midpoint \n        c = ( (a+b) / 2)\n        fn_c = fn(c) \n        log.append([ a, b, c, fn_c ])\n        if (fn_c) == 0 or ((b-a)/2) < tol : \n            # soluction found\n            return c\n            breakpoint\n        if same_sign(fn(a), fn_c) :\n            a = c\n        else :\n            b = c\n    return False\n\n\ndef graph(name) :\n    len_log = len(log)\n    x = np.arange(1,(len_log+1),1) \n    y = np.zeros((len_log), dtype=float)\n\n    for i in range(len_log) :\n        y[i] = ( math.log2(abs( log[i][3] )) )\n\n    plt.plot(x, y, label = \"blue\", color=\"#6776FE\", marker=\".\")\n\n    x[:] = (x[:]-1)*(-1)\n    plt.plot(x, label = \"blue\", color=\"#FF5733\")\n\n    plt.title(GRAPH+' '+name)\n    plt.xlabel(\"Iteration axis\")\n    plt.ylabel(\"ln(|x0 - xn|) axis\")\n    plt.savefig(PATH+GRAPH+name+'.pdf', dpi=300)\n\nif __name__ == \"__main__\":\n    ''' Tests\n        * test_0 = fx = ( x**3 - x - 2 ), a = 1, b = 2, c = 2.23606  \n        * test_1 = fx = ( x**2 - 5 ), a = 0, b = 4, c = 1.521385\n        * test_2 = fx = ( x**2 - 3 ), a = 0, b = 4, c = (3)^1/2\n        * test_3 = fx = ( x**3 + x - 3), a = 0, b = 4, c = 1.2134170    \n        * http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/07/bisection.html\n   '''\n    a = 1\n    b = 2\n\n    result = ( bisection(function, a, b, TOLERANCE, MAX) )\n    print(result)\n    result = str(int(result*10000))\n    graph(result)\n    ", "meta": {"hexsha": "c70b8684421269589e8f19a5744211389bfd92b6", "size": 2382, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/bisection-method.py", "max_stars_repo_name": "codinginbrazil/GA018", "max_stars_repo_head_hexsha": "714fcfca0144536ce17481793b100058fb07b928", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-24T12:52:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T12:52:12.000Z", "max_issues_repo_path": "src/bisection-method.py", "max_issues_repo_name": "codinginbrazil/GA018", "max_issues_repo_head_hexsha": "714fcfca0144536ce17481793b100058fb07b928", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bisection-method.py", "max_forks_repo_name": "codinginbrazil/GA018", "max_forks_repo_head_hexsha": "714fcfca0144536ce17481793b100058fb07b928", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3793103448, "max_line_length": 84, "alphanum_fraction": 0.5386230059, "include": true, "reason": "import numpy", "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.9196425366837827, "lm_q1q2_score": 0.868305198675961}}
{"text": "import numpy as np\n\n\ndef softmax(action_values, tau=1.0):\n    \"\"\"\n    Args:\n        action_values (Numpy array): A 2D array of shape (batch_size, num_actions).\n                       The action-values computed by an action-value network.\n        tau (float): The temperature parameter scalar.\n    Returns:\n        A 2D array of shape (batch_size, num_actions). Where each column is a probability distribution over\n        the actions representing the policy.\n    \"\"\"\n\n    # Compute the preferences by dividing the action-values by the temperature parameter tau\n    preferences = action_values / tau\n    # Compute the maximum preference across the actions\n    max_preference = np.max(preferences, axis=1)\n\n    # your code here\n\n    # Reshape max_preference array which has shape [Batch,] to [Batch, 1]. This allows NumPy broadcasting\n    # when subtracting the maximum preference from the preference of each action.\n    reshaped_max_preference = max_preference.reshape((-1, 1))\n    # print(reshaped_max_preference)\n\n    # Compute the numerator, i.e., the exponential of the preference - the max preference.\n    exp_preferences = np.exp(preferences - reshaped_max_preference)\n    # print(exp_preferences)\n    # Compute the denominator, i.e., the sum over the numerator along the actions axis.\n    sum_of_exp_preferences = np.sum(exp_preferences, axis=1)\n    # print(sum_of_exp_preferences)\n\n    # your code here\n\n    # Reshape sum_of_exp_preferences array which has shape [Batch,] to [Batch, 1] to  allow for NumPy broadcasting\n    # when dividing the numerator by the denominator.\n    reshaped_sum_of_exp_preferences = sum_of_exp_preferences.reshape((-1, 1))\n    # print(reshaped_sum_of_exp_preferences)\n\n    # Compute the action probabilities according to the equation in the previous cell.\n    action_probs = exp_preferences / reshaped_sum_of_exp_preferences\n    # print(action_probs)\n\n    # your code here\n\n    # squeeze() removes any singleton dimensions. It is used here because this function is used in the\n    # agent policy when selecting an action (for which the batch dimension is 1.) As np.random.choice is used in\n    # the agent policy and it expects 1D arrays, we need to remove this singleton batch dimension.\n    action_probs = action_probs.squeeze()\n    return action_probs\n\n\nif __name__ == '__main__':\n    rand_generator = np.random.RandomState(0)\n    action_values = rand_generator.normal(0, 1, (2, 4))\n    tau = 0.5\n\n    action_probs = softmax(action_values, tau)\n    print(\"action_probs\", action_probs)\n\n    assert (np.allclose(action_probs, np.array([\n        [0.25849645, 0.01689625, 0.05374514, 0.67086216],\n        [0.84699852, 0.00286345, 0.13520063, 0.01493741]\n    ])))\n\n    action_values = np.array([[0.0327, 0.0127, 0.0688]])\n    tau = 1.\n    action_probs = softmax(action_values, tau)\n    print(\"action_probs\", action_probs)\n\n    assert np.allclose(action_probs, np.array([0.3315, 0.3249, 0.3436]), atol=1e-04)\n\n    print(\"Passed the asserts! (Note: These are however limited in scope, additional testing is encouraged.)\")", "meta": {"hexsha": "be0ed00b7bff8bf3f581e6796b09d082387fa3ed", "size": 3052, "ext": "py", "lang": "Python", "max_stars_repo_path": "utilities/softmax.py", "max_stars_repo_name": "RecoHut-Stanzas/S873634", "max_stars_repo_head_hexsha": "ae67db296ada7ab31d77c51d048254c7c028620e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-10T10:19:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T09:35:25.000Z", "max_issues_repo_path": "utilities/softmax.py", "max_issues_repo_name": "danilprov/batch-bandits", "max_issues_repo_head_hexsha": "42f0988dcc310600dd5b0131278cfe2b8fcb30f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utilities/softmax.py", "max_forks_repo_name": "danilprov/batch-bandits", "max_forks_repo_head_hexsha": "42f0988dcc310600dd5b0131278cfe2b8fcb30f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2432432432, "max_line_length": 114, "alphanum_fraction": 0.7142857143, "include": true, "reason": "import numpy", "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.9273632906279589, "lm_q1q2_score": 0.8682763438961147}}
{"text": "import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n## Machine Learning Online Class - Exercise 1: Linear Regression\n\ndef warmUpExercise():\n    return np.eye(5)\n\ndef plotData(x, y):\n    plt.plot(x, y, 'rx', label='Training data')\n    plt.xlabel('Population of City in 10,000s')\n    plt.ylabel('Profit in $10,000s')\n    plt.title('Scatter plot of training data')\n    plt.axis([4, 25, -5, 24])\n\ndef computeCost(X, y, theta):\n    error = (X @ theta - y)\n    return (error.T @ error)/ (2*y.size)\n\ndef gradientDescent(X, y, theta, alpha, iterations):\n    m = y.size\n    for _ in range(iterations):\n        theta -= alpha/m * X.T @ (X @ theta - y)\n    return theta\n\n# ==================== Part 1: Basic Function ====================\nprint('Running warmUpExercise ... ')\nprint('5x5 Identity Matrix:')\nprint(warmUpExercise())\ninput('Program paused. Press enter to continue.\\n')\n\n# ======================= Part 2: Plotting =======================\n# x refers to the population size in 10,000s\n# y refers to the profit in $10,000s\n\nscriptdir = os.path.dirname(os.path.realpath(__file__))\nprint(scriptdir)\ndata = np.loadtxt(scriptdir + '//ex1data1.txt', delimiter=',')\nX = data[:,:-1]\ny = data[:,-1]\nm = y.size #number of training examples\n\nprint('Plotting Data ...')\n#Plot Data\nplotData(X, y)\nplt.show()\n\n# =================== Part 3: Cost and Gradient descent ===================\nX = np.c_[np.ones(m), X] # #Add a column of ones to X (interception data)\ntheta = np.zeros(2) #initialize fitting parameters\n\n# Some gradient descent settings\niterations = 1500\nalpha = 0.01\n\nprint('\\nTesting the cost function ...')\n# compute and display initial cost\nJ = computeCost(X, y, theta)\nprint(f'With theta = [0 ; 0], Cost computed = {J}')\nprint('Expected cost value (approx) 32.07')\n\n\n# further testing of the cost function\nJ = computeCost(X, y, [-1 , 2])\nprint(f'\\nWith theta = [-1 ; 2], Cost computed = {J}')\nprint(f'Expected cost value (approx) 54.24')\ninput('Program paused. Press enter to continue.\\n')\n\n\nprint('Running Gradient Descent ...')\n# run gradient descent\ntheta = gradientDescent(X, y, theta, alpha, iterations)\n\n# print theta to screen\nprint('Theta found by gradient descent:')\nprint(theta)\nprint('Expected theta values (approx)')\nprint(' -3.6303,  1.1664\\n')\n\n# Plot the linear fit\nplotData(X[:,1], y)\nplt.plot(X[:,1], X @ theta, '-', label='Linear regression')\nplt.legend()\nplt.show()\n\n# Predict values for population sizes of 35,000 and 70,000\npredict1 = [1, 3.5]  @ theta\nprint(f'For population = 35,000, we predict a profit of {predict1*10000}')\npredict2 = [1, 7] @ theta\nprint(f'For population = 70,000, we predict a profit of {predict2*10000}')\ninput('Program paused. Press enter to continue.\\n')\n\n\n# ============= Part 4: Visualizing J(theta_0, theta_1) =============\nprint('Visualizing J(theta_0, theta_1) ...')\n\n# Grid over which we will calculate J\ntheta0_vals = np.linspace(-10, 10, 100)\ntheta1_vals = np.linspace(-1, 4, 100)\n\n# initialize J_vals to a matrix of 0's\nJ_vals = np.zeros((theta0_vals.size, theta1_vals.size))\n\n# Fill out J_vals\n# Because of the way Surface plot and meshgrid work, we need to swap\n# j,i order in J_vals, or else the axes will be flipped\nfor i in range(theta0_vals.size):\n    for j in range(theta1_vals.size):\n\t    J_vals[j,i] = computeCost(X, y, [theta0_vals[i], theta1_vals[j]])\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\n# Surface plot\nxx, yy = np.meshgrid(theta0_vals, theta1_vals)\nsurf = ax.plot_surface(xx, yy, J_vals, antialiased=False)\n#LaTex rendering with matplotlib is very sow on MacOS\n#ax.set_xlabel(r'$\\theta_0$')\n#ax.set_ylabel(r'$\\theta_1$')\nax.set_xlabel('Theta_0')\nax.set_ylabel('Theta_1')\nplt.show()\n\n# Contour plot\n# Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100\nplt.contour(xx, yy, J_vals, np.logspace(-2, 3, 20))\n#LaTex rendering with matplotlib is very sow on MacOS\n#plt.xlabel(r'$\\theta_0$')\n#plt.ylabel(r'$\\theta_1$')\nplt.xlabel('Theta_0')\nplt.ylabel('Theta_1')\n\nplt.plot(theta[0], theta[1], 'rx', ms=10, lw=2)\nplt.show()\n", "meta": {"hexsha": "71aeb1df3ff9919ea213802b4e93bc78a061bf9f", "size": 4064, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine-learning-ex1/ex1/ex1.py", "max_stars_repo_name": "Hammer7/PythonStanfordMachineLearning", "max_stars_repo_head_hexsha": "d68dd75f2a5ac9152694d66705f46f9ee21576b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-11T13:12:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-11T13:13:08.000Z", "max_issues_repo_path": "machine-learning-ex1/ex1/ex1.py", "max_issues_repo_name": "Hammer7/PythonStanfordMachineLearning", "max_issues_repo_head_hexsha": "d68dd75f2a5ac9152694d66705f46f9ee21576b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "machine-learning-ex1/ex1/ex1.py", "max_forks_repo_name": "Hammer7/PythonStanfordMachineLearning", "max_forks_repo_head_hexsha": "d68dd75f2a5ac9152694d66705f46f9ee21576b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8823529412, "max_line_length": 75, "alphanum_fraction": 0.6678149606, "include": true, "reason": "import numpy", "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762057376384, "lm_q2_score": 0.904650536386234, "lm_q1q2_score": 0.8682492600087013}}
{"text": "\"\"\"This file contains code used in \"Think Stats\",\nby Allen B. Downey, available from greenteapress.com\n\nCopyright 2014 Allen B. Downey\nLicense: GNU GPLv3 http://www.gnu.org/licenses/gpl.html\n\"\"\"\n\nfrom __future__ import print_function, division\n\nimport thinkstats2\nimport thinkplot\n\nimport math\nimport random\nimport numpy as np\n\n\ndef MeanError(estimates, actual):\n    \"\"\"Computes the mean error of a sequence of estimates.\n\n    estimate: sequence of numbers\n    actual: actual value\n\n    returns: float mean error\n    \"\"\"\n    errors = [estimate-actual for estimate in estimates]\n    return np.mean(errors)\n\n\ndef RMSE(estimates, actual):\n    \"\"\"Computes the root mean squared error of a sequence of estimates.\n\n    estimate: sequence of numbers\n    actual: actual value\n\n    returns: float RMSE\n    \"\"\"\n    e2 = [(estimate-actual)**2 for estimate in estimates]\n    mse = np.mean(e2)\n    return math.sqrt(mse)\n\n\ndef Estimate1(n=7, m=1000):\n    \"\"\"Evaluates RMSE of sample mean and median as estimators.\n\n    n: sample size\n    m: number of iterations\n    \"\"\"\n    mu = 0\n    sigma = 1\n\n    means = []\n    medians = []\n    for _ in range(m):\n        xs = [random.gauss(mu, sigma) for _ in range(n)]\n        xbar = np.mean(xs)\n        median = np.median(xs)\n        means.append(xbar)\n        medians.append(median)\n\n    print('Experiment 1')\n    print('rmse xbar', RMSE(means, mu))\n    print('rmse median', RMSE(medians, mu))\n\n\ndef Estimate2(n=7, m=1000):\n    \"\"\"Evaluates S and Sn-1 as estimators of sample variance.\n\n    n: sample size\n    m: number of iterations\n    \"\"\"\n    mu = 0\n    sigma = 1\n\n    estimates1 = []\n    estimates2 = []\n    for _ in range(m):\n        xs = [random.gauss(mu, sigma) for _ in range(n)]\n        biased = np.var(xs)\n        unbiased = np.var(xs, ddof=1)\n        estimates1.append(biased)\n        estimates2.append(unbiased)\n\n    print('Experiment 2')\n    print('mean error biased', MeanError(estimates1, sigma**2))\n    print('mean error unbiased', MeanError(estimates2, sigma**2))\n\n\ndef Estimate3(n=7, m=1000):\n    \"\"\"Evaluates L and Lm as estimators of the exponential parameter.\n\n    n: sample size\n    m: number of iterations\n    \"\"\"\n    lam = 2\n\n    means = []\n    medians = []\n    for _ in range(m):\n        xs = np.random.exponential(1/lam, n)\n        L = 1 / np.mean(xs)\n        Lm = math.log(2) / np.median(xs)\n        means.append(L)\n        medians.append(Lm)\n\n    print('Experiment 3')\n    print('rmse L', RMSE(means, lam))\n    print('rmse Lm', RMSE(medians, lam))\n    print('mean error L', MeanError(means, lam))\n    print('mean error Lm', MeanError(medians, lam))\n\n\ndef SimulateSample(mu=90, sigma=7.5, n=9, m=1000):\n    \"\"\"Plots the sampling distribution of the sample mean.\n\n    mu: hypothetical population mean\n    sigma: hypothetical population standard deviation\n    n: sample size\n    m: number of iterations\n    \"\"\"\n    def VertLine(x, y=1):\n        thinkplot.Plot([x, x], [0, y], color='0.8', linewidth=3)\n\n    means = []\n    for _ in range(m):\n        xs = np.random.normal(mu, sigma, n)\n        xbar = np.mean(xs)\n        means.append(xbar)\n\n    stderr = RMSE(means, mu)\n    print('standard error', stderr)\n\n    cdf = thinkstats2.Cdf(means)\n    ci = cdf.Percentile(5), cdf.Percentile(95)\n    print('confidence interval', ci)\n    VertLine(ci[0])\n    VertLine(ci[1])\n\n    # plot the CDF\n    thinkplot.Cdf(cdf)\n    thinkplot.Save(root='estimation1',\n                   xlabel='sample mean',\n                   ylabel='CDF',\n                   title='Sampling distribution')\n\n\ndef main():\n    thinkstats2.RandomSeed(17)\n\n    Estimate1()\n    Estimate2()\n    Estimate3(m=1000)\n    SimulateSample()\n\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "272a96e1a35edacc2e90291341938a22d51cbca2", "size": 3683, "ext": "py", "lang": "Python", "max_stars_repo_path": "DSC 530 - Data Exploration and Analysis/ThinkStats2/code/estimation.py", "max_stars_repo_name": "Hakuna-Patata/BU_MSDS_PTW", "max_stars_repo_head_hexsha": "4759cb2db3e63ae5722bd42771e4d228dfbc733d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DSC 530 - Data Exploration and Analysis/ThinkStats2/code/estimation.py", "max_issues_repo_name": "Hakuna-Patata/BU_MSDS_PTW", "max_issues_repo_head_hexsha": "4759cb2db3e63ae5722bd42771e4d228dfbc733d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DSC 530 - Data Exploration and Analysis/ThinkStats2/code/estimation.py", "max_forks_repo_name": "Hakuna-Patata/BU_MSDS_PTW", "max_forks_repo_head_hexsha": "4759cb2db3e63ae5722bd42771e4d228dfbc733d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1635220126, "max_line_length": 71, "alphanum_fraction": 0.617159924, "include": true, "reason": "import numpy", "num_tokens": 1010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620562254525, "lm_q2_score": 0.904650536386234, "lm_q1q2_score": 0.8682492589675106}}
{"text": "\"\"\"\nThe Frobenius equation is the Diophantine equation,\n\na_1 x_1 +... + a_n x_n = b\n\nwhere a_i> 0 are positive integers, b> 0 is a positive integer, and the solution x_i consists\nof non-negative integers. Here is a sample run,\n\n->>> solvefrob([1,2,3,5],10)\n [(0, 0, 0, 2),\n  (0, 1, 1, 1),\n  (0, 2, 2, 0),\n  (0, 5, 0, 0),\n  (1, 0, 3, 0),\n  (1, 2, 0, 1),\n  (1, 3, 1, 0),\n  (2, 0, 1, 1),\n  (2, 1, 2, 0),\n  (2, 4, 0, 0),\n  (3, 1, 0, 1),\n  (3, 2, 1, 0),\n  (4, 0, 2, 0),\n  (4, 3, 0, 0),\n  (5, 0, 0, 1),\n  (5, 1, 1, 0),\n  (6, 2, 0, 0),\n  (7, 0, 1, 0),\n  (8, 1, 0, 0),\n  (10, 0, 0, 0)]\n\nHint: Use Numpy broadcasting effectively. There is a timeout in the test-case,\nso if it takes too long to compute (e.g, you used too many for loops), it will be marked wrong.\nThe function signature is solvefrob(coefs,b) where coefs is the list of a_i coefficients.\nYou can only use Numpy for this problem. No other third party packages.\n\"\"\"\nimport numpy as np\nimport time\n\n\ndef solvefrob(coefs, b):\n    \"\"\"\n    Solves frobenius equation\n\n    Bounding the domain space makes enormous difference in performance\n    :param coefs:\n    :param b:\n    :return:\n    \"\"\"\n\n    # input type validation\n    for elem in coefs:\n        assert isinstance(elem, int)\n        assert elem > 0\n\n    assert isinstance(b, int)\n    assert b > 0\n\n    # construct candidate matrix C of dims MxN where N = len(coefs)\n    arr = None\n    for i, coef in enumerate(coefs[::-1]):\n        max = b // coef  # restricts the max value of candidate solution at\n        # a given index to bound solution space, vastly increases performance\n        r = np.arange(max+1)[:, None]\n        if arr is None:\n            arr = r\n        else:\n            new_r = np.repeat(r, len(arr))[:, None]\n            new_arr = np.concatenate([arr for _ in range(len(r))])\n            arr = np.concatenate([new_r, new_arr], axis=1)\n\n    # extract candidate solutions where C * coefs == b\n    out = np.matmul(arr, coefs)\n    results = arr[out == b].tolist()\n    results = [tuple(result) for result in results]\n    return results\n\n\nif __name__ == '__main__':\n    ##### Arguments\n    coefs = [1,2,3,5,6,4,6,4]\n    b = 15\n    ##### End Arguments\n\n\n    s = time.time()\n    results = solvefrob(coefs, b)\n    e = time.time()\n    print(f\"{solvefrob.__name__}, time: {e-s} seconds\")\n    print(f\"Coeffs = {coefs}, B = {b}\")\n    print(f\"number of solutions: {len(results)}\\n\")\n    print(\"solution | coeffs | dot product\")\n    print(\"-\"*20)\n    for result in results:\n        print(\"{} | {} | {}\".format(result, coefs, np.dot(result, coefs)))\n", "meta": {"hexsha": "379b9b8daee3138e7c312bb3a3c72a5632b0e108", "size": 2556, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw8/frobenius_solver.py", "max_stars_repo_name": "alexander-paskal/ece143-hw", "max_stars_repo_head_hexsha": "9e3d475cb44fd16f87879cb74dc9305d70805355", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-02T07:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T07:30:20.000Z", "max_issues_repo_path": "hw8/frobenius_solver.py", "max_issues_repo_name": "alexander-paskal/ece143-hw", "max_issues_repo_head_hexsha": "9e3d475cb44fd16f87879cb74dc9305d70805355", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw8/frobenius_solver.py", "max_forks_repo_name": "alexander-paskal/ece143-hw", "max_forks_repo_head_hexsha": "9e3d475cb44fd16f87879cb74dc9305d70805355", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9052631579, "max_line_length": 95, "alphanum_fraction": 0.5809859155, "include": true, "reason": "import numpy", "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214138, "lm_q2_score": 0.9149009486120849, "lm_q1q2_score": 0.8681653093991003}}
{"text": "import numpy as np \n\ndef euclidean_distances(X, Y):\n    \"\"\"Compute pairwise Euclidean distance between the rows of two matrices X (shape MxK) \n    and Y (shape NxK). The output of this function is a matrix of shape MxN containing\n    the Euclidean distance between two rows.\n\n    Args:\n        X {np.ndarray} -- First matrix, containing M examples with K features each.\n        Y {np.ndarray} -- Second matrix, containing N examples with K features each.\n\n    Return:\n        D {np.ndarray}: MxN matrix with Euclidean distances between rows of X and rows of Y.\n    \"\"\"\n    a = X.shape[0]\n    b = Y.shape[0]\n    D = np.zeros(shape=(a,b))\n    n = 0\n    for i in X:\n        m = 0\n        for j in Y:\n            elem = np.linalg.norm(i-j)\n            D[n][m] = elem\n            m += 1\n        n += 1\n    return D\n\ndef manhattan_distances(X, Y):\n    \"\"\"Compute pairwise Manhattan distance between the rows of two matrices X (shape MxK) \n    and Y (shape NxK). The output of this function is a matrix of shape MxN containing\n    the Manhattan distance between two rows.\n\n    Args:\n        X {np.ndarray} -- First matrix, containing M examples with K features each.\n        Y {np.ndarray} -- Second matrix, containing N examples with K features each.\n\n    Returns:\n        D {np.ndarray}: MxN matrix with Manhattan distances between rows of X and rows of Y.\n    \"\"\"\n    a = X.shape[0]\n    b = Y.shape[0]\n    D = np.zeros(shape=(a,b))\n    n = 0\n    for i in X:\n        m = 0\n        for j in Y:\n            elem = np.linalg.norm(i-j, ord=1)\n            D[n][m] = elem\n            m += 1\n        n += 1\n    return D\n", "meta": {"hexsha": "70332aae0537556f8f301cb0a72612f0053e8f3a", "size": 1608, "ext": "py", "lang": "Python", "max_stars_repo_path": "knn_and_regression/src/distances.py", "max_stars_repo_name": "WallabyLester/Machine_Learning_From_Scratch", "max_stars_repo_head_hexsha": "6042cf421f5de2db61fb570b7c4de64dc03453f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "knn_and_regression/src/distances.py", "max_issues_repo_name": "WallabyLester/Machine_Learning_From_Scratch", "max_issues_repo_head_hexsha": "6042cf421f5de2db61fb570b7c4de64dc03453f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "knn_and_regression/src/distances.py", "max_forks_repo_name": "WallabyLester/Machine_Learning_From_Scratch", "max_forks_repo_head_hexsha": "6042cf421f5de2db61fb570b7c4de64dc03453f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9230769231, "max_line_length": 92, "alphanum_fraction": 0.5907960199, "include": true, "reason": "import numpy", "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399043329856, "lm_q2_score": 0.8947894590884704, "lm_q1q2_score": 0.8681604391841614}}
{"text": "import numpy as np\r\nfrom scipy import stats\r\ndef mean_diff_test(a, b, check_col, sample_size=2000):\r\n    ## Define 2 random distributions\r\n    #Sample Size\r\n    a = a[[check_col]]\r\n    b = b[[check_col]]\r\n\r\n    ## Calculate the Standard Deviation\r\n    # Calculate the variance to get the standard deviation\r\n    a = np.array(a)\r\n    b = np.array(b)\r\n\r\n    a = np.array(a).astype(np.float)\r\n    b = np.array(b).astype(np.float)\r\n\r\n    # For unbiased max likelihood estimate we have to divide the var by N-1, and therefore the parameter ddof = 1\r\n    var_a = a.var(ddof=1)\r\n    var_b = b.var(ddof=1)\r\n\r\n    # std deviation\r\n    s = np.sqrt((var_a + var_b)/2)\r\n\r\n    ## Calculate the t-statistics\r\n    t = (a.mean() - b.mean())/(s*np.sqrt(2/sample_size))\r\n\r\n\r\n\r\n    # Compare with the critical t-value\r\n    #Degrees of freedom\r\n    df = 2 * sample_size - 2\r\n\r\n    # p-value after comparison with the t\r\n    p = 1 - stats.t.cdf(t, df=df)\r\n\r\n\r\n    print(\"t = \" + str(t))\r\n    print(\"p = \" + str(2*p))\r\n    # Note that we multiply the p value by 2 because its a twp tail t-test\r\n    # You can see that after comparing the t statistic with the critical t value (computed internally)\r\n    # we get a good p value of 0.0005 and thus we reject the null hypothesis and thus it proves that the mean of the\r\n    # two distributions are different and statistically significant.\r\n\r\n\r\n    # Cross Checking with the internal scipy function\r\n    t2, p2 = stats.ttest_ind(a,b)\r\n    print(\"t = \" + str(t2))\r\n    print(\"p = \" + str(2*p2))\r\n\r\n", "meta": {"hexsha": "c9592a989ee4729613a31bf07cb0ec865bb1236d", "size": 1521, "ext": "py", "lang": "Python", "max_stars_repo_path": "resources/statistics.py", "max_stars_repo_name": "sebalp1987/anomaly_detection_answers", "max_stars_repo_head_hexsha": "fee2eb08302c1e340acd910d1777016625c25def", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "resources/statistics.py", "max_issues_repo_name": "sebalp1987/anomaly_detection_answers", "max_issues_repo_head_hexsha": "fee2eb08302c1e340acd910d1777016625c25def", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "resources/statistics.py", "max_forks_repo_name": "sebalp1987/anomaly_detection_answers", "max_forks_repo_head_hexsha": "fee2eb08302c1e340acd910d1777016625c25def", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.42, "max_line_length": 117, "alphanum_fraction": 0.6245890861, "include": true, "reason": "import numpy,from scipy", "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399060540358, "lm_q2_score": 0.8947894569842487, "lm_q1q2_score": 0.8681604386825391}}
{"text": "import numpy as np\n\ndef PLU_decomposition(A,verbose=False):\n    m=A.shape[0]\n    n=A.shape[1]\n    P=np.eye(n)\n    L=np.zeros([n,n])\n    U=np.array(A).copy()\n    if m!=n:\n        print \"This matrix cannot realize PLU_decomposition because it is not a square matrix!\"\n        return\n    else:\n        for i in range(n-1):\n            for j in range(i+1,n):\n                for k in range(n-1,i,-1):\n                    if U[i,i] < U[k,i]:\n                        L[i, :], L[k, :] = np.array([L[k, :], L[i, :]]).copy()\n                        P[i, :], P[k, :] = np.array([P[k, :], P[i, :]]).copy()\n                        U[i, :], U[k, :] = np.array([U[k, :], U[i, :]]).copy()\n                if U[i,i]==0:\n                    L[j,i]=0\n                else:\n                    L[j,i]=U[j,i]/float(U[i,i])\n                    U[j,:]=U[j,:]-L[j,i]*U[i,:]\n\n        for i in range(n): L[i,i]=1\n\n        if verbose :\n            print\"The PLU_decomposition decomposition of A is:\"\n            print \"The P matrix is:\"\n            print (P)\n            print \"The L matrix is\"\n\n            print (L)\n            print \"The U matrix is\"\n            print (U)\n\n        return P,L,U\n\n\ndef Gram_Schimidt(A,verbose=False):\n    m = A.shape[0]\n    n = A.shape[1]\n    R=np.zeros([m,n])\n    Q=np.zeros([m,m])\n    R[0,0]=np.linalg.norm(A[:,0])\n    if R[0, 0] == 0:\n        print\"cannot realiaze Gram_Schimidt decomposition\"\n    else:\n        Q[:,0]=A[:,0]/R[0,0]\n    for i in range(1,n):\n        Q[:,i]=A[:,i]\n        for j in range(i):\n            R[j,i]=np.dot(Q[:,j].T,Q[:,i])\n            Q[:,i]-=R[j,i]*Q[:,j]\n        R[i,i]=np.linalg.norm(Q[:,i])\n        if R[i,i]==0:\n            print\"cannot realiaze Gram_Schimidt decomposition\"\n        else:\n            Q[:, i] = Q[:, i] / R[i, i]\n    if verbose:\n        print\"The Gram_Schimidt decomposition of A is:\"\n        print (\"The Q matrix is:\")\n        print (Q)\n        print (\"The R matrix is:\")\n        print (R)\n    return  Q,R\n\ndef householder_reduction(A,verbose=False):\n    m = A.shape[0]\n    n = A.shape[1]\n    E=np.eye(m)\n    T=np.array(A).copy()\n    P=np.eye(m)\n    for i in range(n-1):\n        u=T[i:,i]-np.linalg.norm(T[i:n,i])*E[i:,i]\n        u=np.array([u])\n        u=u.T\n        I = np.eye(m)\n        I[i:,i:]=np.eye(n-i)-2*np.dot(u,u.T)/(np.linalg.norm(u)*np.linalg.norm(u))\n        T=np.dot(I,T)\n        P=np.dot(I,P)\n        Q=P.T\n    if verbose:\n        print \"The householder_reduction of A is:\"\n        print \"The Q matrix is:\"\n        print Q\n        print \"The R matrix is:\"\n        print T\n    return  Q,T\n\ndef Givens_reduction(A,verbose=False):\n    m = A.shape[0]\n    n = A.shape[1]\n    P=np.eye(m)\n    R=np.array(A).copy()\n    for k in range(m):\n        for j in range(n-1,k,-1):\n            tmpa = R[k,k]\n            tmpb = R[j,k]\n            mag = np.sqrt(tmpa*tmpa+tmpb*tmpb)\n            c= tmpa / mag\n            s= tmpb / mag\n            I=np.eye(m)\n            I[k,k]=c\n            I[k,j]=s\n            I[j,j]=c\n            I[j,k]=-s\n            P=np.dot(I,P)\n            R=np.dot(I,R)\n            Q=P.T\n    if verbose:\n        print\"The Givens_reduction of A is:\"\n        print (\"The Q matrix is:\")\n        print (Q)\n        print (\"The R matrix is:\")\n        print (R)\n    return  Q,R\n# A=np.array([[1 , 2 , -3 , 4],[4 , 8 , 12 , -8],[2 , 3 , 2 , 1 ],[-3 , -1 , 1 , -4 ]])\n# A = np.array([[1, 19, -34], [-2, -5, 20], [2, 8, 37]])\n#A = np.array([[0, -20, -14], [3, 27, -4], [4, 11, -2]])\n# A = np.array([[3, 2, 1], [2, -3, 4], [5, 1, -1], [7, 4, 2]])\n# A=np.array([[0,0],[0,0]])\nif __name__=='__main__':\n    #A = np.random.randn(9,9)\n    A = np.random.randint(0,10000,[4,4])\n    print\"the A matrix is:\"\n    print A\n    print \"please choose the way to decompose A . \"\n    print  \"Press '1' to realize the PLU_decomposition of A. \"\n    print  \"Press '2' to realize the Gram_Schimidt of A.\"\n    print  \"Press '3' to realize the householder_reduction of A.\"\n    print  \"Press '4' to realize the Givens_reduction of A.\"\n    Q = np.empty(A.shape)\n    R = np.empty(A.shape)\n    choose_mode=input(\"please choose the mode:\")\n    if choose_mode==1:\n        P, L, U=PLU_decomposition(A)\n        print  np.sum(np.linalg.norm(np.dot(P,A) - np.dot(L,U)))\n        print \"The P matrix is:\"\n        print (P)\n        print \"The L matrix is\"\n\n        print (L)\n        print \"The U matrix is\"\n        print (U)\n\n    elif choose_mode==2:\n        Q, R  = Gram_Schimidt(A)\n        print  np.sum(np.linalg.norm(A - np.dot(Q, R)))\n\n    elif choose_mode==3:\n        Q, R = householder_reduction(A)\n        print  np.sum(np.linalg.norm(A - np.dot(Q, R)))\n    elif choose_mode==4:\n        Q,R = Givens_reduction(A)\n        print  np.sum(np.linalg.norm(A - np.dot(Q, R)))\n\n    if choose_mode is not 1:\n        print (\"The Q matrix is:\")\n        print (Q)\n        print (\"The R matrix is:\")\n        print (R)\n\n        print \"QR decomposition in numpy is \\n\", np.linalg.qr(A)", "meta": {"hexsha": "dc07eef0e9943c211d263e8887b564ce2dc0f6da", "size": 4914, "ext": "py", "lang": "Python", "max_stars_repo_path": "Matrix Decomposition.py", "max_stars_repo_name": "ClovisChen/Matrix-Decomposition", "max_stars_repo_head_hexsha": "84f76327df5bc6bc0826bc3b71a2b4f909228b70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Matrix Decomposition.py", "max_issues_repo_name": "ClovisChen/Matrix-Decomposition", "max_issues_repo_head_hexsha": "84f76327df5bc6bc0826bc3b71a2b4f909228b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Matrix Decomposition.py", "max_forks_repo_name": "ClovisChen/Matrix-Decomposition", "max_forks_repo_head_hexsha": "84f76327df5bc6bc0826bc3b71a2b4f909228b70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7818181818, "max_line_length": 95, "alphanum_fraction": 0.4713064713, "include": true, "reason": "import numpy", "num_tokens": 1536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399043329856, "lm_q2_score": 0.8947894562828416, "lm_q1q2_score": 0.8681604364620283}}
{"text": "from math import sin, cos, tan, atan, asin, acos, atan2\nfrom XCat_Objects import pi, DtoR, D2R, R2D\nimport numpy as np\nfrom numpy.linalg import norm\n\n\n# RA  = phi\n# DEC = pi/2 - theta (theta = pi/2 - DEC)\ndef DEC2theta(DEC):\n    return np.pi/2. - DEC\n\n\ndef theta2DEC(theta):\n    return np.pi/2. - theta\n\n\ndef Cartesian2Spherical(x,y,z):\n    cart_vector = [x, y, z]\n    r = norm(cart_vector)\n    unit = cart_vector / r\n    theta = acos(unit[2])\n    phi = atan2(unit[1], unit[0])\n    return r, theta, phi\n\n\ndef Spherical2Cartesian(r,RA,DEC):\n    cos_DEC = cos(DEC)\n    x = r * cos(RA) * cos_DEC\n    y = r * sin(RA) * cos_DEC\n    z = r * sin(DEC)\n    return x, y, z\n\n\ndef Cartesian2RADEC(x,y,z,noNeg=True):\n    cart_vector = [x, y, z]\n    r = norm(cart_vector)  # it is not checking for r=1.0 but it should\n    unit = cart_vector / r\n    theta = acos(unit[2])\n    phi = atan2(unit[1], unit[0])  # RA = phi, DEC = theta2DEC(theta)\n    if noNeg:\n        while (phi < 0.0): phi += 2. * np.pi\n    return phi, theta2DEC(theta)\n\n\n# RA_o and DEC_o such that RA_o and DEC_o \n# in spherical coordinate become zeros \ndef CoordTrans(x,y,z,RA_o,DEC_o):\n    cosD = cos(DEC_o); sinD = sin(DEC_o)\n    cosR = cos(RA_o);  sinR = sin(RA_o)\n    xn =  cosD*cosR*x + cosD*sinR*y + sinD*z\n    yn =      -sinR*x +      cosR*y\n    zn = -sinD*cosR*x - sinD*sinR*y + cosD*z\n    return xn,yn,zn\n\n\ndef invCoordTrans(x,y,z,RA_o,DEC_o):\n    cosD = cos(DEC_o); sinD = sin(DEC_o)\n    cosR = cos(RA_o);  sinR = sin(RA_o)\n    xn =  cosD*cosR*x - sinR*y - cosR*sinD*z\n    yn =  sinR*cosD*x + cosR*y - sinR*sinD*z\n    zn =    sinD*x             +   cosD*z\n    return xn,yn,zn\n\n\n# RA, DEC befor rotation (in degree)\n# RA_o, DEC_o the new origin for coordinate (in degree)\n# return new RA, DEC (in degree)\ndef rotatingCoord(RA,DEC,RA_o,DEC_o,noNeg=True):\n    x,y,z = Spherical2Cartesian(1.0,D2R*RA,D2R*DEC)\n    x,y,z = CoordTrans(x,y,z,D2R*RA_o,D2R*DEC_o)\n    RAn,DECn = Cartesian2RADEC(x,y,z,noNeg=noNeg)\n    return R2D*RAn,R2D*DECn\n\n\ndef EquatorialTOGalactic(RA,DEC):\n    # l\n    gLong = 303.0*DtoR - atan( sin(192.25*DtoR-RA*DtoR) / (cos(192.25*DtoR-RA*DtoR)*sin(27.4*DtoR) - tan(DEC*DtoR)*cos(27.4*DtoR)) )\n    # b\n    gLati = asin(sin(DEC*DtoR)*sin(27.4*DtoR) + cos(DEC*DtoR)*cos(27.4*DtoR)*cos(192.25*DtoR-RA*DtoR))\n    return (gLong/DtoR,gLati/DtoR)\n\n\n''' EXAMPLES\n#EXAMPLE (WORKING)\n#print \"RA & DEC :\", rotatingCoord(20.0,30.0,20.0,30.0)\n#RA_o  = 00.*D2R\n#DEC_o = 30.*D2R\n#RA  = 00.*D2R\n#DEC = 20.*D2R\n#x,y,z = Spherical2Cartesian(1.0,RA,DEC)\n#x,y,z = CoordTrans(x,y,z,RA_o,DEC_o)\n#RA,DEC = Cartesian2RADEC(x,y,z)\n#print \"RA  : \", R2D*RA; print \"DEC : \", R2D*DEC\n\n#x=4.0; y=1.0; z=3.0\n#x,y,z = CoordTrans(x,y,z,1.0,1.0)\n#x,y,z = invCoordTrans(x,y,z,1.0,1.0)\n#print x,y,z\n\n\nRA_o  = 30.*D2R\nDEC_o = 20.*D2R\nr     = 1.0\n\nRA  = 50.*D2R\nDEC = 20.*D2R\nr   = 1.0\n\nprint 'RA  = ', R2D*RA\nprint 'DEC = ', R2D*DEC\nprint 'r   = ', r\n\nx,y,z = Spherical2Cartesian(r,RA,DEC)\nx,y,z = CoordTrans(x,y,z,RA_o,DEC_o)\nr, theta, phi = Cartesian2Spherical(x,y,z)\n\nprint '--------------------------------'\nprint 'RA  = ', R2D*phi\nprint 'DEC = ', R2D*theta2DEC(theta)\nprint 'r   = ', r\n'''", "meta": {"hexsha": "4be143bc900fb91a35168aed38b8fdef100751e3", "size": 3133, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/Calculator/Coordinate_Transformation.py", "max_stars_repo_name": "afarahi/XTRA", "max_stars_repo_head_hexsha": "6550b216264abaa3ed705835aca0981f2934e069", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-01T12:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-22T07:02:54.000Z", "max_issues_repo_path": "source/Calculator/Coordinate_Transformation.py", "max_issues_repo_name": "afarahi/XTRA", "max_issues_repo_head_hexsha": "6550b216264abaa3ed705835aca0981f2934e069", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Calculator/Coordinate_Transformation.py", "max_forks_repo_name": "afarahi/XTRA", "max_forks_repo_head_hexsha": "6550b216264abaa3ed705835aca0981f2934e069", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8925619835, "max_line_length": 132, "alphanum_fraction": 0.6026172997, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692352660528, "lm_q2_score": 0.8887587875995482, "lm_q1q2_score": 0.8680233654208349}}
{"text": "# %% [markdown]\n# # Fitting a normal distribution with tensorflow probability\n# Here we look at fitting a normal distribution to some data using Tensorflow Probability.\n# %%\nimport numpy as np\nimport pandas as pd\n\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\nimport matplotlib.pyplot as plt\n\nplt.style.use(\"seaborn-whitegrid\")\n\n# %% [markdown]\n# Generate some data from a normal distribution:\n# %%\nn = 1000\ntrue_mu = 2.0\ntrue_std = 3.4\nx = np.random.normal(loc=true_mu, scale=true_std, size=n)\nplt.hist(x, 30)\nplt.show()\n# %% [markdown]\n# # Model setup\n# Tensorflow probability allows us to fit a network where the final layer output is not a scalar value,\n# but a probability distribution.\n# The normal distribution is parameterised by the mean and standard deviation.\n# As such the model needs to output two values.\n# \n# We are fitting just a static distribution to the data.\n# This is equivalent to fitting a network where the inputs are all 0.\n# In this situation we only use the network biases as the weights become irrelevant with inputs of 0.\n# \n# To build the above - the model has a dense layer with 2 output nodes.\n# For the final output layer we utilise the normal distribution object from tensorflow probability.\n# The `DistributionLambda` layer allows us to use a lambda function to split the dense layer outputs\n# and connect them to the `loc` and `scale` (mean and standard deviation) inputs of the normal distribution.\n# The scale uses a `softplus` function to ensure the standard deviation is always positive.\n# %%\nmodel = tf.keras.Sequential(\n    [\n        tf.keras.layers.Dense(1 + 1),\n        tfp.layers.DistributionLambda(\n            lambda t: tfp.distributions.Normal(\n                loc=t[..., :1],\n                scale=1e-3 + tf.math.softplus(0.05 * t[..., 1:]),\n            )\n        ),\n    ]\n)\n# %% [markdown]\n# The cost function is setup as the negative loglikelihood:\n# Tensorflow probably objects have a `log_prob(y)` method which returns the log probablility of the sample `y`.\n# %%\ndef negloglik(y, distr):\n    return -distr.log_prob(y)\n# %% [markdown]\n# We fit the model as normal using gradient descent and the `Adam` optimiser.\n# As mentioned before, the input to the network is a vector of zeros.\n# The target variable is our random data we want to fit the normal distribution to.\n# %%\nmodel.compile(optimizer=tf.optimizers.Adam(learning_rate=0.2), loss=negloglik)\n\ndummy_input = np.zeros(x.shape)[:, np.newaxis]\nhistory = model.fit(dummy_input, x, epochs=100, verbose=0)\n# %% [markdown]\n# The loglikelihood has converged over the training:\n# %%\nplt.plot(history.history['loss'])\nplt.show()\n# %% [markdown]\n# # Results\n# We can obtain the fitted parameters from the `model.weights` biases.\n# They do not match the exact parameters of the true distribution.\n# They converge to the maximum likelihood estimator for a normal distribution.\n# In this case it corresponds to the sample mean and standard deviation.\n# \n# We can compare these different estimates by creating probability distribution objects\n# and then plotting the probability distribution function.\n# As we can see the estimates are reasonable approximations of the true distribution.\n# %% Compare to sampled estimators and true values\np_y1 = tfp.distributions.Normal(\n    loc=model.weights[1][0], scale=tf.math.softplus(0.05 * model.weights[1][1])\n)\np_y2 = tfp.distributions.Normal(loc=np.mean(x), scale=np.std(x))\np_y3 = tfp.distributions.Normal(loc=true_mu, scale=true_std)\n\nx_t = np.linspace(-10, 10, 50)\ny_t1 = p_y1.prob(x_t)\ny_t2 = p_y2.prob(x_t)\ny_t3 = p_y3.prob(x_t)\n\nplt.hist(x, bins=30, density=True, label=\"y\")\nplt.plot(x_t, y_t1, label=\"y_est\")\nplt.plot(x_t, y_t2, label=\"y_samp\")\nplt.plot(x_t, y_t3, label=\"y_true\")\nplt.legend()\nplt.show()", "meta": {"hexsha": "acb4d30c43b837c9b97862dc9e6c25c3dbdac44e", "size": 3767, "ext": "py", "lang": "Python", "max_stars_repo_path": "TensorflowProbability/fit_gaussian_tfp.py", "max_stars_repo_name": "stanton119/data-analysis", "max_stars_repo_head_hexsha": "b6fda815c6cc1798ba13a5d2680369b7e5dfcdf9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TensorflowProbability/fit_gaussian_tfp.py", "max_issues_repo_name": "stanton119/data-analysis", "max_issues_repo_head_hexsha": "b6fda815c6cc1798ba13a5d2680369b7e5dfcdf9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-11T23:44:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-11T23:44:52.000Z", "max_forks_repo_path": "TensorflowProbability/fit_gaussian_tfp.py", "max_forks_repo_name": "stanton119/data-analysis", "max_forks_repo_head_hexsha": "b6fda815c6cc1798ba13a5d2680369b7e5dfcdf9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-16T01:02:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-16T01:02:23.000Z", "avg_line_length": 38.0505050505, "max_line_length": 111, "alphanum_fraction": 0.7286965755, "include": true, "reason": "import numpy", "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517106286378, "lm_q2_score": 0.9032942014971872, "lm_q1q2_score": 0.8680221081296515}}
{"text": "import numpy as np\nimport time    # check documentation for further use\nimport matplotlib.pyplot as plt\nfrom qr_decomp import *\nfrom mat_inversion_method import *\n\n# Import and Store the Data\nx_data = []\ny_data = []\n\nfilename = 'data1.txt'\ndata = np.loadtxt(filename, delimiter=' ', dtype=float)\nx_data = data[:,0]\ny_data = data[:,1]\n\n\n# PART 1\n\n# Form the required Matrix\nA = []\nfor data_point in x_data:\n    A.append([1, data_point, data_point*data_point])\nB = y_data\n\n\n# Finding COEFFICIENTS, TIME TAKEN and ERROR\n## finding coefficients using QR Decomposition while noting time\nt1 = time.time()    # works like a stop-watch\nb_qr_decomp = qr_decomposition_solver(A,B)\nt2 = time.time()\n# thus time taken by QR decomposition approach is t2-t1\ntime1_in_milli_sec = (t2-t1)*(10**3)\nprint(\"time taken when solved by QR decomposition : %.5f ms\" % time1_in_milli_sec)\nprint(b_qr_decomp)\n\n#WHY DOES THIS SHOW A SLIGHTLY DIFFERENT TIME EVERYTIME\n#in the result, show a range of values of time\n\n\n## finding coefficients using Matrix Inversion while noting time\nt3 = time.time()\nb_mat_inversion = mat_inv_method(A,B)\nt4 = time.time()\n# thus time taken by matrix inversion approach is t4-t3\ntime2_in_milli_sec = (t4-t3)*(10**3)\nprint(\"time taken when solved by Matrix inversion : %.5f ms\" % time2_in_milli_sec)\nprint(b_mat_inversion)\n\n# Calculating the ERROR in each methods\n# We will evaluate the accuracy of the models based on r r-squared values\n# we can directly compare the errors, but for uniformity of evaluation wrt different models\n# we will compare the results based on r-squared values\nrms_data = 0\nrms_qr = 0\nrms_mi = 0\n\n# predicted values y_cap\n#QR Decomposition\ny1_cap = [(b_qr_decomp[2]*(i**2) + b_qr_decomp[1]*i + b_qr_decomp[0]) for i in x_data]\n#Matrix Inversion\ny2_cap = [(b_mat_inversion[2]*(i**2) + b_mat_inversion[1]*i + b_mat_inversion[0]) for i in x_data]\n\ny_bar = B.mean()\n\n#finding rms error in data\nfor element in B:\n    rms_data = rms_data + ((element-y_bar)**2)\n\n# finding rms errors in both methods\nfor element in y1_cap:\n    rms_qr = rms_qr + ((element-y_bar)**2)\nfor element in y2_cap:\n    rms_mi = rms_mi + ((element-y_bar)**2)\n\nr_squared_qr = rms_qr/rms_data\nr_squared_mi = rms_mi/rms_data\nprint(\"R-square for QR method Regression: {}\".format(r_squared_qr))\nprint(\"R-square for Matrix Inversion method Regression: {}\".format(r_squared_mi))\n\n\n\n# PART 2\n# finding terms for biquadratic regression equation\n\n# Finding COEFFICIENTS, TIME TAKEN and ERROR\n## finding coefficients using QR Decomposition\nA = []\nfor data_point in x_data:\n    A.append([1, data_point, data_point**2, data_point**3, data_point**4])\nt5 = time.time()\nb_biquadratic_qr_decomp = qr_decomposition_solver(A,B)\nt6 = time.time()\ntime3_in_milli_sec = (t6-t5)*(10**3)\nprint(\"time taken when solved for biquadratic regression using QR method is : %.5f ms\" % time3_in_milli_sec)\nprint(b_biquadratic_qr_decomp)\n\n# calculating the fit of the model using R-square value\ny_bar = B.mean()\ny_biquad_cap = [(b_biquadratic_qr_decomp[4]*(i**4) + b_biquadratic_qr_decomp[3]*(i**3) + b_biquadratic_qr_decomp[2]*(i**2) + b_biquadratic_qr_decomp[1]*i + b_biquadratic_qr_decomp[0]) for i in x_data]\nrms_biquad_qr = 0\nfor element in y_biquad_cap :\n    rms_biquad_qr = rms_biquad_qr + ((element-y_bar)**2)\nr_squared_bq = rms_biquad_qr/rms_data\nprint(\"R-square for Biquadratic Regression: {}\".format(r_squared_bq))\n\n\n\"\"\"\n# PRINTING AND SAVING THE PLOTS\n\nx_axis = [j for j in range(0,11,1) ]\ny1_axis = [(b_qr_decomp[2]*(i**2) + b_qr_decomp[1]*i + b_qr_decomp[0]) for i in x_axis]\ny2_axis = [(b_mat_inversion[2]*(i**2) + b_mat_inversion[1]*i + b_mat_inversion[0]) for i in x_axis]\ny_biquad_axis = [(b_biquadratic_qr_decomp[4]*(i**4) + b_biquadratic_qr_decomp[3]*(i**3) + b_biquadratic_qr_decomp[2]*(i**2) + b_biquadratic_qr_decomp[1]*i + b_biquadratic_qr_decomp[0]) for i in x_axis]\n\nplt.scatter(x_data,y_data,marker = '.')\nplt.plot(x_axis, y1_axis,label='QR Decomposition')\nplt.plot(x_axis, y2_axis,label='Matrix Inversion')\nplt.plot(x_axis, y_biquad_axis,label='Biquadratic Regression')\n#plt.title('Least Squares Plot')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend(loc='best')\nplt.grid()\nplt.savefig('Task5.png')\nplt.show()\n\"\"\"\n", "meta": {"hexsha": "58e0267d025d325378bda63276cdf2ad5996e227", "size": 4195, "ext": "py", "lang": "Python", "max_stars_repo_path": "AS2101_Labwork/4.Submissions/Task 5/main.py", "max_stars_repo_name": "kirtan2605/Coursework_Codes", "max_stars_repo_head_hexsha": "3455496e8ec0ae3a576cb3fc3b2ed01a055149c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AS2101_Labwork/4.Submissions/Task 5/main.py", "max_issues_repo_name": "kirtan2605/Coursework_Codes", "max_issues_repo_head_hexsha": "3455496e8ec0ae3a576cb3fc3b2ed01a055149c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AS2101_Labwork/4.Submissions/Task 5/main.py", "max_forks_repo_name": "kirtan2605/Coursework_Codes", "max_forks_repo_head_hexsha": "3455496e8ec0ae3a576cb3fc3b2ed01a055149c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.031496063, "max_line_length": 201, "alphanum_fraction": 0.7392133492, "include": true, "reason": "import numpy", "num_tokens": 1299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737737, "lm_q2_score": 0.9032941975921686, "lm_q1q2_score": 0.8680221013466878}}
{"text": "from scipy.integrate import odeint\nfrom numpy import sin, pi, linspace, arange\n\n# First Order ODE:\ndy = lambda y, x: x*y   # Equation to be solved, y' = xy\ny0 = 1                  # Initial condition, y(0) = 1\nx = linspace(0, 2, 5)   # Divides [0,2] into (2-0)/.5 = 4 (+1 as 0 inc.) points\n\n# Odeint Function\ny = odeint(dy, y0, x)\n\nprint('odeint(dy, y0, x) =', y, sep='\\n', end='\\n\\n')\n\n\n# First Order ODE:\ndy = lambda y, x: y+3   # Equation to be solved, y' = y+3\ny0 = -2                 # Initial condition, y(0) = -2\nx = linspace(2, 4, 21)  # Divides [2,4] into (4-2)/.1 = 20 (+1 as 0 inc.) points\n\n# Odeint Function\ny = odeint(dy, y0, x)\n\nprint('odeint(dy, y0, x) =', y, sep='\\n', end='\\n\\n')\n\n\n# Second Order ODE:\ndef  dy(y, x):              # Equation to be solved, y'' = 4*x + 10*sin(x) - y\n    y, u  = y\n    dydx = [u, 4*x + 10*sin(x) - y]\n    return dydx\n\ny0 = [0, 2]                 # Initial conditions, y(π) = 1, u(π) = 2\nx = arange(pi, 2*pi, .5)    # Arange [π,2π[ in .5 step size\n\n# Odeint Function\nsol = odeint(dy, y0, x)\n\nprint('odeint(dy, y0, x) =\\n    y \\t\\ty\\'', sol, sep='\\n')\n", "meta": {"hexsha": "0fd46f57073b8400fc4c2c69c8b037362a3d6bca", "size": 1097, "ext": "py", "lang": "Python", "max_stars_repo_path": "6. Ordinary Differential Equations/0. ODE solving functions of SciPy.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "6. Ordinary Differential Equations/0. ODE solving functions of SciPy.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6. Ordinary Differential Equations/0. ODE solving functions of SciPy.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1282051282, "max_line_length": 80, "alphanum_fraction": 0.5305378304, "include": true, "reason": "from numpy,from scipy", "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661015270469, "lm_q2_score": 0.9099070060380482, "lm_q1q2_score": 0.8680204393022639}}
{"text": "### ch3.1.4 Lpノルムの作図\n\n#%%\n\n# 3.1.4項で利用するライブラリ\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n#%%\n\n## Lpノルムの作図\n\n# 値を指定\np = 1\n\n# wの値を指定\nw_vals = np.arange(-10.0, 10.1, 0.1)\n\n# 作図用のwの点を作成\nW1, W2 = np.meshgrid(w_vals, w_vals)\n\n# Lpのノルムを計算\nLp = (np.abs(W1)**p + np.abs(W2)**p)**(1.0 / p)\n\n#%%\n\n# Lpノルムの3Dグラフを作成\nfig = plt.figure(figsize=(8, 8))\nax = fig.add_subplot(projection='3d') # 3D用の設定\nax.plot_surface(W1, W2, Lp, cmap='jet') # 曲面図\nax.contour(W1, W2, Lp, cmap='jet', offset=0) # 等高線図\nax.set_xlabel('$w_1$')\nax.set_ylabel('$w_2$')\nax.set_zlabel('$||w||_p$')\nax.set_title('p=' + str(np.round(p, 1)), loc='left')\nfig.suptitle('$||w||_p = {}^p\\sqrt{\\sum_{j=1}^M |w_j|^p}$')\n#ax.view_init(elev=90, azim=270) # 表示アングル\nplt.show()\n\n#%%\n\n# Lpノルムの2Dグラフを作成\nplt.figure(figsize=(9, 8))\nplt.contour(W1, W2, Lp, cmap='jet') # 等高線図\n#plt.contour(W1, W2, Lp, cmap='jet', levels=1) # 等高線図:(値を指定)\n#plt.contourf(W1, W2, Lp, cmap='jet') # 塗りつぶし等高線図\nplt.xlabel('$w_1$')\nplt.ylabel('$w_2$')\nplt.title('p=' + str(np.round(p, 1)), loc='left')\nplt.suptitle('$||w||_p = {}^p\\sqrt{\\sum_{j=1}^M |w_j|^p}$')\nplt.colorbar(label='$||w||_p$')\nplt.grid()\nplt.gca().set_aspect('equal')\nplt.show()\n\n#%%\n\n## 正則化項の作図\n\n# 正則化項を計算\nE_W = (np.abs(W1)**p + np.abs(W2)**p) / p\n\n# 正則化項の3Dグラフを作成\nfig = plt.figure(figsize=(8, 8))\nax = fig.add_subplot(projection='3d') # 3D用の設定\nax.plot_surface(W1, W2, E_W, cmap='jet') # 曲面図\nax.contour(W1, W2, E_W, cmap='jet', offset=0) # 等高線図\nax.set_xlabel('$w_1$')\nax.set_ylabel('$w_2$')\nax.set_zlabel('$E_W(w)$')\nax.set_title('p=' + str(np.round(p, 1)), loc='left')\nfig.suptitle('$E_W(w) = \\\\frac{1}{p} \\sum_{j=1}^M |w_j|^p$')\n#ax.view_init(elev=90, azim=270) # 表示アングル\nplt.show()\n\n#%%\n\n## pとグラフの形状の関係\n\n# 使用するpの値を指定\np_vals = np.arange(0.1, 10.1, 0.1)\n\n# 図を初期化\nfig = plt.figure(figsize=(6, 6))\nax = fig.add_subplot(projection='3d') # 3D用の設定\nfig.suptitle('Lp-Norm', fontsize=20)\n\n# 作図処理を関数として定義\ndef update(i):\n    # 前フレームのグラフを初期化\n    plt.cla()\n    \n    # i回目の値を取得\n    p = p_vals[i]\n    \n    # Lpノルムを計算\n    Lp = (np.abs(W1)**p + np.abs(W2)**p)**(1.0 / p)\n    \n    # Lpノルムの3Dグラフを作成\n    ax.plot_surface(W1, W2, Lp, cmap='jet') # 曲面図\n    ax.contour(W1, W2, Lp, cmap='jet', offset=0) # 等高線図\n    ax.set_xlabel('$w_1$')\n    ax.set_ylabel('$w_2$')\n    ax.set_zlabel('$||w||_p$')\n    ax.set_title('p=' + str(np.round(p, 1)), loc='left')\n\n# gif画像を作成\nanime_norm3d = FuncAnimation(fig, update, frames=len(p_vals), interval=100)\n\n# gif画像を保存\nanime_norm3d.save('PRML/Fig/ch3_1_4_LpNorm_3d.gif')\n\n#%%\n\n# 図を初期化\nfig = plt.figure(figsize=(6, 6))\n\n# 作図処理を関数として定義\ndef update(i):\n    # 前フレームのグラフを初期化\n    plt.cla()\n    \n    # i回目の値を取得\n    p = p_vals[i]\n    \n    # Lpノルムを計算\n    Lp = (np.abs(W1)**p + np.abs(W2)**p)**(1.0 / p)\n    \n    # Lpノルムの2Dグラフを作成\n    plt.contour(W1, W2, Lp, cmap='jet') # 等高線図\n    #plt.contourf(W1, W2, Lp, cmap='jet') # 塗りつぶし等高線図\n    plt.xlabel('$w_1$')\n    plt.ylabel('$w_2$')\n    plt.title('p=' + str(np.round(p, 1)), loc='left')\n    plt.suptitle('Lp-Norm', fontsize=20)\n    plt.grid()\n    plt.axes().set_aspect('equal')\n\n# gif画像を作成\nanime_norm2d = FuncAnimation(fig, update, frames=len(p_vals), interval=100)\n\n# gif画像を保存\nanime_norm2d.save('PRML/Fig/ch3_1_4_LpNorm_2d.gif')\n\n\n", "meta": {"hexsha": "ee64f8ebee8f71ee8b1ecafd778436989b3466da", "size": 3212, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code_Python/ch3_1_4_norm.py", "max_stars_repo_name": "anemptyarchive/PRML", "max_stars_repo_head_hexsha": "58cbb35ae65d66b6faf436c70a6cbc9d54d4589f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code_Python/ch3_1_4_norm.py", "max_issues_repo_name": "anemptyarchive/PRML", "max_issues_repo_head_hexsha": "58cbb35ae65d66b6faf436c70a6cbc9d54d4589f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code_Python/ch3_1_4_norm.py", "max_forks_repo_name": "anemptyarchive/PRML", "max_forks_repo_head_hexsha": "58cbb35ae65d66b6faf436c70a6cbc9d54d4589f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8503401361, "max_line_length": 75, "alphanum_fraction": 0.6142590286, "include": true, "reason": "import numpy", "num_tokens": 1587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.9086178994073576, "lm_q1q2_score": 0.8680200609165295}}
{"text": "import numpy as np\r\n\r\ndef geom_mean(v):\r\n    \"\"\"Geometrical mean of the elements of a numpy array.\"\"\"\r\n    return np.prod(v) ** (1/v.shape[0])\r\n\r\ndef angle_mean(angles):\r\n    \"\"\" Compute average angle of a vector of angles in radians.\"\"\" \r\n    return np.angle(np.sum([np.exp(1j * ang) for ang in angles]))\r\n\r\n\r\ndef compute_angle(u, v=None):\r\n    '''\r\n    Computes the angle between vectors u and v.\r\n    If v is None, computes the angle of u wrt y=0\r\n    '''\r\n    # if v is None: v = np.array([1, 0])\r\n    if v is None:\r\n        if all(u == 0):\r\n            return 0\r\n        ang = np.arccos(u[0] / np.linalg.norm(u))\r\n        return ang if u[1] >= 0 else -ang\r\n    else:\r\n        if u.sum() == 0 or v.sum() == 0 or u == v:\r\n            return 0\r\n        cos_theta = np.dot(u, v) / np.linalg.norm(u) / np.linalg.norm(v)\r\n        theta = np.arccos(np.clip(cos_theta, a_min=-1, a_max=1))\r\n        # if(u[0]*v[1] - u[1]*v[0] < 0): theta *= -1\r\n        return theta\r\n\r\n\r\ndef angle_diff(x, y):\r\n    \"\"\" Compute the difference between two angles in radians.\"\"\"\r\n    # abs_diff = np.abs(x - y)\r\n    # return min(abs_diff, 2 * np.pi - abs_diff)\r\n    return min((x - y) % (2 * np.pi), (y - x) % (2 * np.pi))\r\n\r\ndef normalize(v):\r\n    \"\"\" Normalize a numpy array.\"\"\" \r\n    return v / np.linalg.norm(v)\r\n\r\ndef eigendecomposition(C):\r\n    \"\"\" Eigendecomposition of matrix C. \"\"\" \r\n    eigenvals, B = np.linalg.eig(C) \r\n    D = np.diag(eigenvals)\r\n    return B, D, B.T\r\n\r\n\r\ndef toroidal_difference(v, u):\r\n    v_diff = v - u\r\n    abs_diff = np.abs(v_diff)\r\n    res = v_diff.copy()\r\n    res[abs_diff > 500] = 1000 - abs_diff[abs_diff > 500]\r\n    res[abs_diff > 500] *= -np.sign(v_diff[abs_diff > 500])\r\n    # (-1, 1)[v_diff[abs_diff > 500] > 0] # Correct sign\r\n    # import pdb; pdb.set_trace()\r\n    return res\r\n\r\n#! PASAR A DISTANCES\r\ndef circle_distance(alpha, beta):\r\n    #! Check that |alpha - beta| <= 2pi\r\n    return min(np.abs(alpha - beta), 2*np.pi - np.abs(alpha - beta))", "meta": {"hexsha": "52dac08bcfbfb163da9562f2fd735b844fbc7676", "size": 1966, "ext": "py", "lang": "Python", "max_stars_repo_path": "spike_swarm_sim/utils/alg_utils.py", "max_stars_repo_name": "Robolabo/EvoSwarmSim", "max_stars_repo_head_hexsha": "45f20f00b079a9481e324e091c46040182cf1d3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spike_swarm_sim/utils/alg_utils.py", "max_issues_repo_name": "Robolabo/EvoSwarmSim", "max_issues_repo_head_hexsha": "45f20f00b079a9481e324e091c46040182cf1d3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spike_swarm_sim/utils/alg_utils.py", "max_forks_repo_name": "Robolabo/EvoSwarmSim", "max_forks_repo_head_hexsha": "45f20f00b079a9481e324e091c46040182cf1d3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7096774194, "max_line_length": 73, "alphanum_fraction": 0.5574771109, "include": true, "reason": "import numpy", "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191271831559, "lm_q2_score": 0.908617900644622, "lm_q1q2_score": 0.8680200597868117}}
{"text": "# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nimport argparse\r\n\r\n\r\nparser = argparse.ArgumentParser(description='EAO exercises')\r\nparser.add_argument('-v', \"--verbose\", type=int,\r\n                    help='If verbosity, then -v 1', default=0)\r\n\r\nargs = parser.parse_args()\r\n\r\nif args.verbose == 1:\r\n    print(\"\\nModo Debugger\\n\")\r\n################ Ejercicio 1\r\n\"\"\"\r\n    Ptos criticos, 0, 2, 4. (0, 0) mínimo, (2, 2) punto de silla, (4, 4) mínimo.\r\n\"\"\"\r\n\r\n\"\"\"\r\n    Condición suficiente de optimalidad de segundo orden: dado que los autovalores\r\n    de la matriz Hessiana son mayores que 0, ésta es definida positiva. Por lo tanto\r\n    se satisface la condición de optimalidad de segundo orden.\r\n\"\"\"\r\n\r\ndef f(x):\r\n    return 9*x[0]**2 - 2*x[0]*x[1]+x[1]**2-4*x[0]**3 + 0.5*x[0]**4\r\n\r\ndef g(x):\r\n    return np.array([18*x[0]-2*x[1] -12*x[0]**2 + 2*x[0]**3, -2*x[0]+2*x[1]])\r\n\r\ndef H(x):\r\n    return np.array([[-24*x[0]+6*x[0]**2+18, -2], [-2, 2]])\r\n\r\n\r\ndef eigvals(x1=0, x2=0):\r\n    hessian = H([x1, x2])\r\n    return np.linalg.eig(hessian)[0]\r\n\r\ndef is_DP():\r\n    return eigvals().all() > 0\r\n\r\nprint(\"¿Es definida positiva la matriz hessiana? {}\".format(is_DP()))\r\n\r\n################# Ejercicio 2\r\nfrom mpl_toolkits import mplot3d\r\nimport matplotlib.pyplot as plt\r\n\r\nfig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"})\r\n\r\nn_points = 50\r\n\r\nx = np.linspace(-1, 5, n_points)\r\ny = np.linspace(-3, 8, n_points)\r\n\r\n[x1, y1] = np.meshgrid(x, y)\r\n\r\nz1 = f([x1, y1]).reshape(n_points, n_points)\r\n\r\nplt.title(\"Superficie\")\r\nax.plot_surface(x1, y1, z1, cmap=plt.cm.coolwarm,\r\n                       linewidth=1)\r\nplt.show()\r\n\r\n\r\n################# Ejercicio 3\r\nplt.title(\"Curvas de nivel\")\r\nplt.contour(x1, y1, z1, 50) # 50 curvas de nivel\r\nplt.show()\r\n\r\n################# Ejercicio 4\r\ndef gradient_descent(x0=[0.4, -1.9], it=40):\r\n    x = x0\r\n    pts, steps_gr = [], []\r\n    m, M = np.linalg.eig(H([0, 0]))[0]\r\n    alpha = 2/(m+M)\r\n    steps_gr.append(f(x.copy()))\r\n\r\n    for i in range(it):\r\n        pts.append(x.copy())\r\n        x += -alpha*g(x)\r\n        steps_gr.append(f(x.copy()))\r\n\r\n    pts.append(x.copy())\r\n\r\n    return f(x), np.array(pts), steps_gr\r\n\r\ngradient_descent_minimum, pts_gd, steps_gr = gradient_descent(x0=[0.4, -1.9], it=40)\r\n\r\nif args.verbose == 1:\r\n    print(\"\\n\\nGradiente Descendente\")\r\n    print(\"\\n\", steps_gr, \"\\n\")\r\n\r\nprint(\"Gradiente Descendente mínimo {}\".format(gradient_descent_minimum))\r\n\r\nplt.title(\"Gradiente descendente. Alpha constante\")\r\nplt.contour(x1, y1, z1, 50)\r\nplt.plot(pts_gd[:, 0], pts_gd[:, 1], marker=\"o\")\r\nplt.show()\r\n\r\n\r\n################# Ejercicio 5\r\ndef metodo_newton(x0=[0.4, -1.9], it=5):\r\n    x = x0\r\n    z = x0\r\n    pts, steps_new = [], []\r\n\r\n    steps_new.append(f(x.copy()))\r\n\r\n    for i in range(it):\r\n        pts.append(x.copy())\r\n        x += np.linalg.solve(H(x), -g(x))\r\n        #z += -np.linalg.inv(H(z))@g(z)\r\n        steps_new.append(f(x.copy()))\r\n\r\n    pts.append(x.copy())\r\n\r\n    return f(x), np.array(pts), steps_new\r\n\r\n\r\nnewton_minimum, pts_newton, steps_new = metodo_newton(x0=[0.4, -1.9], it=5)\r\n\r\nif args.verbose == 1:\r\n    print(\"\\n\\nMétodo de Newton\")\r\n    print(\"\\n\", steps_new, \"\\n\")\r\n\r\nprint(\"Newton mínimo {}\".format(newton_minimum))\r\n\r\nplt.title(\"Newton\")\r\nplt.contour(x1, y1, z1, 50)\r\nplt.plot(pts_newton[:, 0], pts_newton[:, 1], marker=\"o\")\r\nplt.show()\r\n\r\n\r\n##################### Ejercicio 6\r\nfrom scipy.optimize import minimize\r\n\r\ndef busqueda_lineal_exacta(x0=[0.4, -1.9], it=40):\r\n    x = x0\r\n    pts, steps_ls = [], []\r\n\r\n    steps_ls.append(f(x.copy()))\r\n\r\n    for i in range(it):\r\n        pts.append(x.copy())\r\n        alpha = minimize(lambda alpha : f(x - alpha*g(x)), x0=1 )\r\n        x += -alpha.x*g(x)\r\n        steps_ls.append(f(x.copy()))\r\n\r\n    return f(x), np.array(pts), steps_ls\r\n\r\nlinear_search_minimum, pts_ls, steps_ls = busqueda_lineal_exacta(x0=[0.4, -1.9], it=40)\r\n\r\nif args.verbose == 1:\r\n    print(\"\\n\\nBúsqueda lineal exacta\")\r\n    print(\"\\n\", steps_ls, \"\\n\")\r\n\r\nprint(\"Búsqueda lineal exacta mínimo {}\".format(linear_search_minimum))\r\n\r\nplt.title(\"Descenso del Gradiente. Búsqueda exacta.\")\r\nplt.contour(x1, y1, z1, 50)\r\nplt.plot(pts_ls[:, 0], pts_ls[:, 1], marker=\"o\")\r\nplt.show()\r\n\r\n\"\"\"\r\n    El método de Newton encuentra el mínimo, con un menor número de iteraciones\r\n    que el resto de métodos.\r\n    El método del gradiente con la búsqueda lineal exacta, como cabe esperar, encuentra el mínimo\r\n    con menos iteraciones que el gradiente con el tamaño de paso constante. Sin embargo,\r\n    hay que tener en cuenta, que la búsqueda lineal exacta es más costosa computacionalmente.\r\n\"\"\"\r\n\r\nplt.contour(x1, y1, z1, 50)\r\n\r\nplt.title(\"Comparativa\")\r\nplt.plot(pts_gd[:, 0], pts_gd[:, 1], marker=\"o\", label=\"Descenso del Gradiente. Alpha constante.\")\r\nplt.plot(pts_newton[:, 0], pts_newton[:, 1], marker=\"o\", label=\"Newton.\")\r\nplt.plot(pts_ls[:, 0], pts_ls[:, 1], marker=\"o\", label=\"Descenso del Gradiente. Búsqueda exacta.\")\r\nplt.legend(loc=\"upper right\")\r\nplt.show()\r\n\r\nif args.verbose == 1:\r\n    # Nota: Para poder hacer la comparativa, se ha puesto 40 iteraciones en el método de Newton.q\r\n    newton_minimum, pts_new, steps_new = metodo_newton(x0=[0.4, -1.9], it=40)\r\n    iterations = np.arange(30)\r\n\r\n    plt.title(\"Comparativa\")\r\n    plt.xlabel(\"iteraciones\")\r\n    plt.ylabel(\"||Xk - Xminimo||\")\r\n\r\n    distancia_gradiente = [ np.linalg.norm([pts_gd[i, ...], pts_gd[-1, ...]]) for i in iterations ]\r\n    distancia_blineal = [ np.linalg.norm([pts_ls[i, ...], pts_ls[-1, ...]]) for i in iterations ]\r\n    distancia_newton = [ np.linalg.norm([pts_new[i, ...], pts_new[-1, ...]]) for i in iterations ]\r\n\r\n    plt.plot(iterations, distancia_newton, marker = \"*\", label=\"Newton.\")\r\n    plt.plot(iterations, distancia_blineal, marker = \"*\" , label=\"Descenso del Gradiente. Búsqueda exacta.\")\r\n    plt.plot(iterations, distancia_gradiente, marker = \"*\", label=\"Descenso del Gradiente. Alpha constante.\")\r\n    plt.legend(loc=\"upper right\")\r\n    plt.show()\r\n\r\n##################### Ejercicio 7\r\ndef newton_gradient(alpha, x=[0.4, -1.9]):\r\n    pts_g = []\r\n    pts_n = []\r\n    for c_alpha in alpha:\r\n        pg = -g(x)/np.linalg.norm(g(x))\r\n\r\n        #hessian_inverse = np.linalg.solve(H(x), -g(x))\r\n        #pn = hessian_inverse / np.linalg.norm(hessian_inverse)\r\n        pn = - (np.linalg.inv(H(x)))@(g(x))  / np.linalg.norm((np.linalg.inv(H(x)))@(g(x)))\r\n\r\n\r\n        phi_g = f(x+c_alpha*pg)\r\n        phi_n = f(x+c_alpha*pn)\r\n\r\n        pts_g.append(phi_g)\r\n        pts_n.append(phi_n)\r\n\r\n    return pts_g, pts_n\r\n\r\n\r\nalphas = np.arange(0, 2, 0.01)\r\npts_g, pts_n = newton_gradient(alpha = alphas)\r\n\r\nindex_gd = pts_g.index(min(pts_g))\r\nindex_new = pts_n.index(min(pts_n))\r\n\r\nprint(\"Minimo en el Gradiente {} con alpha {}\".format(pts_g[index_gd], alphas[index_gd]) )\r\nprint(\"Minimo en el Newton {} con alpha {}\".format(pts_n[index_new], alphas[index_new]) )\r\n\r\nplt.scatter([alphas[index_gd], alphas[index_new]], [pts_g[index_gd], pts_n[index_new]])\r\n\r\nplt.title(\"Comparativa\")\r\nplt.xlabel(\"valor de alpha\")\r\nplt.ylabel(\"f(x)\")\r\n\r\nplt.plot(alphas, pts_g, c=\"blue\", label=\"gradiente\")\r\nplt.plot(alphas, pts_n, c=\"red\", label=\"newton\")\r\nplt.legend(loc=\"upper left\")\r\nplt.show()\r\n\r\n\"\"\"\r\n    a) Para una búsqueda lineal exacta sería mejor la dirección de newton dado que tiene un mínimo\r\n    inferior al mínimo de la función con el método del gradiente.\r\n\r\n    b) La función con el método del gradiente decrece más rápido que con el método de newton\r\n    para el tramo inicial de valores de alpha. Al tener tamaños de paso muy pequeños nos interesa lo que\r\n    ocurre en las iteraciones \"iniciales\" y por lo tanto el método del gradiente es mejor.\r\n\"\"\"\r\n", "meta": {"hexsha": "c16139e3e0d78ad8e991404bb54fda466b088c9a", "size": 7639, "ext": "py", "lang": "Python", "max_stars_repo_path": "P1.py", "max_stars_repo_name": "bitblayde/Non-linear-Optimization", "max_stars_repo_head_hexsha": "6002a711b8ee16ce1871d3070e403a20c21becec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "P1.py", "max_issues_repo_name": "bitblayde/Non-linear-Optimization", "max_issues_repo_head_hexsha": "6002a711b8ee16ce1871d3070e403a20c21becec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P1.py", "max_forks_repo_name": "bitblayde/Non-linear-Optimization", "max_forks_repo_head_hexsha": "6002a711b8ee16ce1871d3070e403a20c21becec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.556, "max_line_length": 110, "alphanum_fraction": 0.6114674696, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811641488383, "lm_q2_score": 0.8991213691605412, "lm_q1q2_score": 0.8679948340713007}}
{"text": "'''\nBy starting at the top of the triangle below and moving to adjacent numbers on the row below,\nthe maximum total from top to bottom is 23.\n\n   3\n  7 4\n 2 4 6\n8 5 9 3\n\nThat is, 3 + 7 + 4 + 9 = 23.\n\nFind the maximum total from top to bottom of the triangle below:\n\n                         75\n                       95 64\n                      17 47 82\n                    18 35 87 10\n                  20 04 82 47 65\n                 19 01 23 75 03 34\n                88 02 77 73 07 63 67\n              99 65 04 28 06 16 70 92\n             41 41 26 56 83 40 80 70 33\n            41 48 72 33 47 32 37 16 94 29\n           53 71 44 65 25 43 91 52 97 51 14\n         70 11 33 28 77 73 17 78 39 68 17 57\n       91 71 52 38 17 14 91 43 58 50 27 29 48\n      63 66 04 68 89 53 67 30 73 16 69 87 40 31\n    04 62 98 27 23 09 70 98 73 93 38 53 60 04 23\n'''\n\n'''\nfinal answer: 1074\n'''\n\nimport numpy as np\n\n# init constant\nt = np.array([\n    [75],\n    [95, 64],\n    [17, 47, 82],\n    [18, 35, 87, 10],\n    [20, 4, 82, 47, 65],\n    [19, 1, 23, 75, 3, 34],\n    [88, 2, 77, 73, 7, 63, 67],\n    [99, 65, 4, 28, 6, 16, 70, 92],\n    [41, 41, 26, 56, 83, 40, 80, 70, 33],\n    [41, 48, 72, 33, 47, 32, 37, 16, 94, 29],\n    [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],\n    [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],\n    [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],\n    [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],\n    [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23],\n])\n\n\n# compute the maximum sum path\ndef compute():\n    # all we need to do is start from the one to the last row and replace every number with the maximum of the current\n    # number plus the bottom adjacent number and work our way up to the top\n    # note: t.shape[0] = number of rows, since it starts from 0 and we want one to the last -> t.shape[0]-2\n    for i in range(t.shape[0] - 2, -1, -1):\n        max_num = 0\n        for j in range(len(t[i])):\n            t[i][j] = t[i][j] + max(t[i + 1][j], t[i + 1][j + 1])\n\n    return t[0][0]  # this would be the max\n\n\nif __name__ == '__main__':\n    print(\"The maximum path sum is \" + str(compute()))\n", "meta": {"hexsha": "df9ba9cfde5ba6b6395270ba8c1e5113c9af7cfa", "size": 2134, "ext": "py", "lang": "Python", "max_stars_repo_path": "P0018-Max-Path-Sum-I/max_path_sum_i.py", "max_stars_repo_name": "kabhari/Project_Euler", "max_stars_repo_head_hexsha": "e9aba54ae1e03aaf5311fdc615e85cf4c91b25e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "P0018-Max-Path-Sum-I/max_path_sum_i.py", "max_issues_repo_name": "kabhari/Project_Euler", "max_issues_repo_head_hexsha": "e9aba54ae1e03aaf5311fdc615e85cf4c91b25e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P0018-Max-Path-Sum-I/max_path_sum_i.py", "max_forks_repo_name": "kabhari/Project_Euler", "max_forks_repo_head_hexsha": "e9aba54ae1e03aaf5311fdc615e85cf4c91b25e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6388888889, "max_line_length": 118, "alphanum_fraction": 0.511715089, "include": true, "reason": "import numpy", "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240211961401, "lm_q2_score": 0.9252299493606285, "lm_q1q2_score": 0.8679804406252939}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n#%% imports\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams.update({'font.size': 22, 'figure.autolayout': True, 'figure.figsize': (15,5)})\nfactorial = np.math.factorial\nSEED = 999\n\nnp.random.seed(SEED)\n#%% Uniform distribution\n'''\nWhat is the probability of getting a 2 in a die roll?\n'''\n\n# Empty list to hold the ratio of 2s in each set of drawings\np = []\n\nnr_trials = np.logspace(1,3,100)\nfor i in nr_trials:\n    N = int(i) # number of drawings\n    # generate N uniform random number between 1 and 6 (7 is exclusive)\n    uniform_samples = np.random.randint(1, 7, size = N)\n    # count the number of 2s we got\n    count = np.sum(uniform_samples == 2)\n    pval = count/N # ratio (tends to probability)\n    p.append(pval)\n    \n    \nfig1 = plt.figure()\nplt.plot(nr_trials,p,'o-')\nplt.plot(nr_trials,[1/6]*len(nr_trials),'--r')\nplt.grid()\nplt.xlim(nr_trials[0],nr_trials[-1])\nplt.xlabel('Number of drawings')\nplt.ylabel('p(X=2)')\nplt.title(f'Theoretical p(X=2) = {1/6:.3f}')\n\n#%% Bernoulli distribution\n'''\nConsider getting either a 1 or a 2 in a die roll as sucess, while any\nother number as a failure. This can be modeled as Bernoulli distribution\nwith $theta$ as p(X=success) and $1-\\theta$ as p(X=fail)\n'''\n\n# Theoreticallly we know that each number in the roll of a die comes\n# from the uniform distribution so getting either 1 or 2 should be\n# p(X=sucess) =p(X=1) + p(X=2), where $X \\in {1,2,3,4,5,6}$\n\ntheoryBernoulli = 1/6 + 1/6\nprint(f'Theoretical probability = {theoryBernoulli :.3f}')\n\n# create a list to hold the probabilities\np = []\n\nnr_trials = np.logspace(1,3,100)\n# Perform an experiment drawing uniform numbers and counting the amount of\n# 1 or 2 and dividing the count by the number of drawings\nfor i in nr_trials :\n    N = int(i)\n    uniform_samples = np.random.randint(1, 7, size = N)\n    count = np.isin(uniform_samples,[1,2])\n    pval = sum(count)/N\n    p.append(pval)\n    \n\nfig2 = plt.figure()\nplt.plot(nr_trials,p,'o-')\nplt.plot(nr_trials,[theoryBernoulli]*len(nr_trials),'--r')\nplt.grid()\nplt.xlim(nr_trials[0],nr_trials[-1])\nplt.xlabel('Number of drawings')\nplt.ylabel('p(X=success)')\nplt.title(f'Theoretical p(X=sucess) = {theoryBernoulli:.3f}')\n#%% Binomial distribution\n'''\nSay we toss a coin 3 times, what is the probability of getting a head\nall of the times?\nn = 3\nk = 3\ntheta = 0.5\n'''\nn = 3\nk = 3\ntheta = 0.5\n# calculate p(k=3) by the analytic formula\ntheoryBinomial = factorial(n)/(factorial(n-k)*factorial(k))*theta**k*(1-theta)**(n-k)\n\n# calculate p(k=3) using numpy for an experiment\nnumpylBinomial = sum(np.random.binomial(n,theta,int(2e5))==3)/int(2e5)\n\nprint(theoryBinomial)\nprint(numpylBinomial)\n\n#%% save figures\n\nfig1.savefig('uniform.png')\nfig2.savefig('bernoulli.png')", "meta": {"hexsha": "4d3e249df9fcb549d88abca69a0faabedbd97a7f", "size": 2809, "ext": "py", "lang": "Python", "max_stars_repo_path": "content/post/probability/uni_bernoulli_binomial/uni_bernoulli_binomial.py", "max_stars_repo_name": "euanrussano/academic-kickstart", "max_stars_repo_head_hexsha": "620d4802ca62c670643bba4e639ada0efdb54af5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "content/post/probability/uni_bernoulli_binomial/uni_bernoulli_binomial.py", "max_issues_repo_name": "euanrussano/academic-kickstart", "max_issues_repo_head_hexsha": "620d4802ca62c670643bba4e639ada0efdb54af5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "content/post/probability/uni_bernoulli_binomial/uni_bernoulli_binomial.py", "max_forks_repo_name": "euanrussano/academic-kickstart", "max_forks_repo_head_hexsha": "620d4802ca62c670643bba4e639ada0efdb54af5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2718446602, "max_line_length": 91, "alphanum_fraction": 0.6899252403, "include": true, "reason": "import numpy", "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760639, "lm_q2_score": 0.9111797166446536, "lm_q1q2_score": 0.8679662217343086}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nh=0.01\nmin_x = 0.0\nmax_x = 6.0\nn_points = int((max_x-min_x)/h)\nx = np.zeros(n_points)\ny_1 = np.zeros(n_points)\ny_2 = np.zeros(n_points)\n\n\ndef func_prime_1(x, y_1, y_2):\n    return y_2\n\ndef func_prime_2(x, y_1, y_2):\n    return -4*np.sin(y_1)\n\ndef RungeKuttaFourthOrderStep(x_old, y1_old, y2_old):\n    \n    k_1_prime1 = func_prime_1(x_old,y1_old, y2_old)\n    k_1_prime2 = func_prime_2(x_old,y1_old, y2_old)\n    \n    #first step\n    x1 = x_old+ (h/2.0)\n    y1_1 = y1_old + (h/2.0) * k_1_prime1\n    y2_1 = y2_old + (h/2.0) * k_1_prime2\n    k_2_prime1 = func_prime_1(x1, y1_1, y2_1)\n    k_2_prime2 = func_prime_2(x1, y1_1, y2_1)\n    \n    #second step\n    x2 = x_old + (h/2.0)\n    y1_2 = y1_old + (h/2.0) * k_2_prime1\n    y2_2 = y2_old + (h/2.0) * k_2_prime2\n    k_3_prime1 = func_prime_1(x2, y1_2, y2_2)\n    k_3_prime2 = func_prime_2(x2, y1_2, y2_2)\n    \n    \n    #third\n    x3 = x_old + h\n    y1_3 = y1_old + h * k_3_prime1\n    y2_3 = y2_old + h * k_3_prime2\n    k_4_prime1 = func_prime_1(x3, y1_3, y2_3)\n    k_4_prime2 = func_prime_2(x3, y1_3, y2_3)\n    \n    #fourth step\n    average_k_1 = (1.0/6.0)*(k_1_prime1 + 2.0*k_2_prime1 + 2.0*k_3_prime1 + k_4_prime1)\n    average_k_2 = (1.0/6.0)*(k_1_prime2 + 2.0*k_2_prime2 + 2.0*k_3_prime2 + k_4_prime2)\n    \n    x_new = x_old + h\n    y_1_new = y1_old + h * average_k_1\n    y_2_new= y2_old + h * average_k_2\n    return x_new, y_1_new, y_2_new\n\nx[0]   = min_x\ny_1[0] = 0.0\ny_2[0] = 0.1    \n\nfor i in range(1,n_points):\n    x[i],y_1[i],y_2[i] = RungeKuttaFourthOrderStep(x[i-1], y_1[i-1], y_2[i-1])\n    print x[i], \"  \", y_1[i]\n", "meta": {"hexsha": "d1b30e934732671a3720445e86a15f570aeb53e7", "size": 1620, "ext": "py", "lang": "Python", "max_stars_repo_path": "2014-2/Talleres/pendulum.py", "max_stars_repo_name": "forero/ComputationalLab", "max_stars_repo_head_hexsha": "d7bca519dbb439fd76f3ee5a59e21af0ae560989", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2014-2/Talleres/pendulum.py", "max_issues_repo_name": "forero/ComputationalLab", "max_issues_repo_head_hexsha": "d7bca519dbb439fd76f3ee5a59e21af0ae560989", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2014-2/Talleres/pendulum.py", "max_forks_repo_name": "forero/ComputationalLab", "max_forks_repo_head_hexsha": "d7bca519dbb439fd76f3ee5a59e21af0ae560989", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1290322581, "max_line_length": 87, "alphanum_fraction": 0.6265432099, "include": true, "reason": "import numpy", "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741281688026, "lm_q2_score": 0.9111797112177908, "lm_q1q2_score": 0.8679662190183884}}
{"text": "# Implementation of simple linear regression using python numpy\n# Linear regression is the most basic type of regression commonly used for predictive analysis.\n# We try to best fit a regression line or least square line through dataset and estimate the parameters.\n\n\n# Importing required packages\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\n\ndef linear_regression(x, y, title=None, x_label=None, y_label=None, filename=None, show=True):\n    \"\"\"\n\n    Simple Linear Regression Model using ordinary least squares (OLS). Fits regression line. Returns intercept and coefficient.\n    :param x: Independent variables; list or array-likes, NumPy Array\n    :param y: Dependent variable; list or array-likes, NumPy Array\n    :param title: title of the plot\n    :param x_label: x-label or independent variable\n    :param y_label: y-label or dependent variable\n    :param filename: filename to save figure\n    :param show: It true shows current figure (default True)\n    :return: simple linear regression model\n    \"\"\"\n\n    # Estimate the coefficients\n    b = estimate_coef(x, y)\n    # print(\"Intercept: b_0 = {}\".format(b[0]))\n    # print(\"Coefficients: b_1 = {}\".format(b[1]))\n\n    # Plot the regression line\n    fit_regression_line(x, y, b, title, x_label, y_label, filename, show)\n    return b\n\n\ndef estimate_coef(x, y):\n\n    # get the number of observations\n    n = np.size(x)\n    # print(n)\n\n    # mean of x and y\n    x_mean = np.mean(x)\n    y_mean = np.mean(y)\n\n    # Calculate Cov[x,y] and Var[x]\n    cov_xy = n*np.sum(x*y) - (np.sum(x)*np.sum(y))\n    var_x = n*np.sum(x*x) - (np.sum(x)*np.sum(x))\n\n    # Calculate intercept b_0 and coefficient b_1\n    b_1 = cov_xy/var_x\n    b_0 = y_mean - b_1*x_mean\n\n    return [b_0, b_1]\n\n\ndef fit_regression_line(x, y, b, title, x_label, y_label, filename, show):\n\n    # plotting the observational points as scatter plot\n    plt.scatter(x, y, color=\"b\", marker=\"o\", s=30)\n\n    # predicted response vector y_hat\n    y_hat = b[0] + b[1]*x\n\n    # plo the regression line\n    plt.plot(x, y_hat, color='r')\n\n    plt.title(title)\n    plt.xlabel(x_label)\n    plt.ylabel(y_label)\n    if filename:\n        plt.savefig(filename)\n    if show:\n        plt.show(block=False)\n        plt.pause(3)\n        plt.close()\n\n\n# Evaluating the performance of the model\n# We will be using Residual sum of squares error (MSE) and Coefficient of Determination(R² score) to evaluate our model.\n\n# Calculate Residual sum of squares (MSE)\ndef get_mse(y_hat, y_actual):\n    \"\"\"\n    RMSE is the square root of the average of the sum of the squares of residuals.\n    :param y_hat:\n    :param y_actual:\n    :return:\n    \"\"\"\n    mse = np.mean((y_hat - y_actual)**2)\n\n    return mse\n\n\n# Calculate coefficient of determination: r2 score or r-square\ndef r2_score(y_hat, y_actual):\n    \"\"\"\n    R² score or the coefficient of determination explains\n    how much the total variance of the dependent variable\n    can be reduced by using the least square regression.\n    :return:\n    \"\"\"\n    # calculate sum of squares of residuals\n    ss_res = np.sum((y_actual - y_hat)**2)\n\n    # calculate total sum of squares\n    ss_tot = np.sum(y_actual - np.mean(y_actual)**2)\n\n    # calculate r2 score\n    r2 = 1 - (np.absolute(ss_res/ss_tot))\n\n    return r2\n\n\n# predict the value of dependent variable y_pred\n# from independent variable x using this regression model\ndef predict(x, b):\n\n    # predicted response vector y_hat\n    y_pred = b[0] + b[1]*x\n\n    return y_pred\n", "meta": {"hexsha": "ed66ea2f016517ba74b5f367eb4d7e785152a999", "size": 3475, "ext": "py", "lang": "Python", "max_stars_repo_path": "datamidware/pyalgo/linear_regression_ols.py", "max_stars_repo_name": "JagritiG/data-middleware", "max_stars_repo_head_hexsha": "e51cedf173e487d270f42c993e5e7f79f85bd263", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "datamidware/pyalgo/linear_regression_ols.py", "max_issues_repo_name": "JagritiG/data-middleware", "max_issues_repo_head_hexsha": "e51cedf173e487d270f42c993e5e7f79f85bd263", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "datamidware/pyalgo/linear_regression_ols.py", "max_forks_repo_name": "JagritiG/data-middleware", "max_forks_repo_head_hexsha": "e51cedf173e487d270f42c993e5e7f79f85bd263", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2520325203, "max_line_length": 127, "alphanum_fraction": 0.6788489209, "include": true, "reason": "import numpy", "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.9111797009670494, "lm_q1q2_score": 0.8679662055734438}}
{"text": "# -*- coding: utf-8 -*-\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef main(xi,yi):\n    qtd = len(xi)\n    tx = total(xi)\n    ty = total(yi)\n\n    xy = list()\n    x2 = list()\n    for i in xrange(0, qtd):\n        xy.append(xi[i] * yi[i])\n        x2.append(xi[i] ** 2.0)\n\n    txy = total(xy)\n    tx2 = total(x2)\n\n    d = tx / qtd\n    e = ty / qtd\n    a1 = ((qtd*txy) - (tx*ty)) / ((qtd*tx2) - (tx**2))\n    a0 = e - (a1 * d)\n\n    print 'a1 =',a1\n    print 'a0 =',a0\n\n    y = list()\n    for i in xrange(0, qtd):\n        y.append(a1*xi[i]+a0)\n\n    plt.plot(range(1,qtd+1), yi, 'bo')\n    plt.plot(range(1,qtd+1), y)\n\ndef total(lst):\n    total = float()\n    for i in lst:\n        total += i\n    return total\n\nif __name__ == '__main__':\n    plt.title('Minimos Quadrados')\n    plt.grid(True)\n    plt.axis([-2, 8, -2, 8])\n    plt.plot([-100,100],[0,0], 'k-') # Linha X\n    plt.plot([0,0],[-100,100], 'k-') # Linha Y\n\n    fl = open('input-mq.txt', 'r')\n    x = [float(i) for i in fl.readline().split(' ')]\n    y = [float(i) for i in fl.readline().split(' ')]\n    fl.close()\n\n    if len(x) == len(y):\n        main(x,y)\n        plt.show()\n    else:\n        print 'Valores de X e Y precisam ter a mesma quantidade.'\n", "meta": {"hexsha": "fa469926d19cd0a5d2ebda1a9a010ed249c919e8", "size": 1209, "ext": "py", "lang": "Python", "max_stars_repo_path": "minimos_quadrados.py", "max_stars_repo_name": "tavaresdu/matcom-av2", "max_stars_repo_head_hexsha": "658635a02bde55ce550e5fa8da96b20339a7f352", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "minimos_quadrados.py", "max_issues_repo_name": "tavaresdu/matcom-av2", "max_issues_repo_head_hexsha": "658635a02bde55ce550e5fa8da96b20339a7f352", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "minimos_quadrados.py", "max_forks_repo_name": "tavaresdu/matcom-av2", "max_forks_repo_head_hexsha": "658635a02bde55ce550e5fa8da96b20339a7f352", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2105263158, "max_line_length": 65, "alphanum_fraction": 0.4971050455, "include": true, "reason": "import numpy", "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633822, "lm_q2_score": 0.9073122201074847, "lm_q1q2_score": 0.867965898710749}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt \n\ndef make_gauss(N, sig, mu):\n    return lambda x: N/(sig * (2*np.pi)**.5) * np.e ** (-(x-mu)**2/(2 * sig**2))\n\ndef main():\n    ax = plt.figure().add_subplot(1,1,1)\n    x = np.arange(-5, 5, 0.01)\n    s = np.sqrt([0.2, 1, 5, 0.5])\n    m = [0, 0, 0, -2] \n    c = ['b','r','y','g']\n\n    for sig, mu, color in zip(s, m, c): \n        gauss = make_gauss(1, sig, mu)(x)\n        ax.plot(x, gauss, color, linewidth=2)\n\n    plt.xlim(-5, 5)\n    plt.ylim(0, 1)\n    plt.legend(['0.2', '1.0', '5.0', '0.5'], loc='best')\n    plt.show()\n\nif __name__ == '__main__':\n   main()\n", "meta": {"hexsha": "47d5ea5fbfb5d3c71adbebdcb27178cb1c49078d", "size": 610, "ext": "py", "lang": "Python", "max_stars_repo_path": "2022-02-23/normal_distributions.py", "max_stars_repo_name": "GrahamAnto/cannabis-data-science", "max_stars_repo_head_hexsha": "1d5f3085e7b2858b6791840b90335be4669268b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-10T12:37:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T12:37:02.000Z", "max_issues_repo_path": "2022-02-23/normal_distributions.py", "max_issues_repo_name": "GrahamAnto/cannabis-data-science", "max_issues_repo_head_hexsha": "1d5f3085e7b2858b6791840b90335be4669268b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2022-02-23/normal_distributions.py", "max_forks_repo_name": "GrahamAnto/cannabis-data-science", "max_forks_repo_head_hexsha": "1d5f3085e7b2858b6791840b90335be4669268b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4, "max_line_length": 80, "alphanum_fraction": 0.5016393443, "include": true, "reason": "import numpy", "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407206952994, "lm_q2_score": 0.8918110504699678, "lm_q1q2_score": 0.8679468294834235}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSYS-611: Dice Fighters Example\n\n@author: Paul T. Grogan, pgrogan@stevens.edu\n\"\"\"\n\n# import the python3 behavior for importing, division, and printing in python2\nfrom __future__ import absolute_import, division, print_function\n\n# import the numpy library and refer to it as `np`\nimport numpy as np\n\n# import the scipy.stats library and refer to it as `stats`\nimport scipy.stats as stats\n\n# define the round_number state variable, initialize to 0\nround_number = 0\n# define the red_size state variable, initialize to 20\nred_size = 20\n# define the blue_size state variable, initialize to 10\nblue_size = 10\n# define the red_chance_hit state variable, initialize to 1/6 \nred_chance_hit = 1/6\n# define the blue_chance_hit state variable, initialize to 3/6 \nblue_chance_hit = 3/6\n\n# define the generate_red_hits function\ndef generate_red_hits():\n    # return the number of hits\n    return stats.binom.ppf(np.random.rand(), red_size, red_chance_hit)\n    \"\"\"\n    note: the code above could be replaced by a built-in process generator:\n    \n    return np.random.binomial(red_size, red_chance_hit)\n    \"\"\"\n\n# define the generate_blue_hits function\ndef generate_blue_hits():\n    # return the number of hits\n    return stats.binom.ppf(np.random.rand(), blue_size, blue_chance_hit)\n    \"\"\"\n    note: the code above could be replaced by a built-in process generator:\n    \n    return np.random.binomial(blue_size, blue_chance_hit)\n    \"\"\"\n\n# define the red_suffer_losses function with an argument for the number of opponent hits\ndef red_suffer_losses(opponent_hits):\n    # (note: red_size must be declared as a global variable to update!)\n    global red_size\n    # update the red_size based on the number of opponent hits\n    red_size -= opponent_hits\n\n# define the blue_suffer_losses function with an argument for number of opponent hits\ndef blue_suffer_losses(opponent_hits):\n    # (note: blue_size must be declared as a global variable to update!)\n    global blue_size\n    # update the blue_size based on number of opponent hits\n    blue_size -= opponent_hits\n\n# define the is_complete function\ndef is_complete():\n    # return True if either red_size or blue_size is less than or equal to zero\n    return (red_size <= 0 or blue_size <= 0)\n\n# define the next_round state change function\ndef next_round():\n    # (note: round_number must be declared as a global variable to update!)\n    global round_number\n    # advance the round_number\n    round_number += 1\n\n# main execution loop: continue while the game is not complete\nwhile not is_complete():\n    # generate the number of red hits\n    red_hits = generate_red_hits()\n    # generate the number of blue hits\n    blue_hits = generate_blue_hits()\n    # red team suffers losses of blue hits\n    red_suffer_losses(blue_hits)\n    # blue team suffers losses of red hits\n    blue_suffer_losses(red_hits)\n    # advance to the next round\n    next_round()\n    # print out the current state for debugging\n    print(\"Round {}: {} Red, {} Blue\".format(\n            round_number, \n            red_size,\n            blue_size\n        ))\n\n# after main loop exists, check who won (whichever team still has fighters!)\nif red_size > 0:\n\tprint(\"Red Wins\")\nelif blue_size > 0:\n\tprint(\"Blue Wins\")\nelse:\n\tprint(\"Tie - Mutual Destruction!\")\n", "meta": {"hexsha": "0e4375c07b3e4139e9af85e7d5d04b02efb9fe09", "size": 3282, "ext": "py", "lang": "Python", "max_stars_repo_path": "previous/week3/diceFightersBinomial.py", "max_stars_repo_name": "code-lab-org/sys611", "max_stars_repo_head_hexsha": "3b8c46788dee629a9f2d6b7f84373e041b918ff0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-07T03:52:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T18:16:16.000Z", "max_issues_repo_path": "previous/week3/diceFightersBinomial.py", "max_issues_repo_name": "code-lab-org/sys611", "max_issues_repo_head_hexsha": "3b8c46788dee629a9f2d6b7f84373e041b918ff0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "previous/week3/diceFightersBinomial.py", "max_forks_repo_name": "code-lab-org/sys611", "max_forks_repo_head_hexsha": "3b8c46788dee629a9f2d6b7f84373e041b918ff0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-02-12T01:57:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T18:05:27.000Z", "avg_line_length": 32.82, "max_line_length": 88, "alphanum_fraction": 0.7276051188, "include": true, "reason": "import numpy,import scipy", "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407160384082, "lm_q2_score": 0.8918110454379297, "lm_q1q2_score": 0.8679468204329721}}
{"text": "import numpy as np\r\n\r\n# LU Decomposition\r\n# Inputs: A = matrix to be decomposed, sep (boolean) determines whether an LU combined\r\n# matrix or two separate matrices.\r\n# Outputs: LU is a matrix with all elements of U and all non-diagonal elements\r\n# of L, or L and U which are two matrices separated into lower and upper triangular\r\n# matrices.\r\n\r\ndef LU(A, sep = True):\r\n    if A.shape[0] != A.shape[1]:\r\n        print(\"Not a square matrix\")\r\n    else:\r\n        LU = np.zeros([A.shape[0], A.shape[1]])\r\n        L = np.zeros([A.shape[0], A.shape[1]])\r\n        U = np.zeros([A.shape[0], A.shape[1]])\r\n        for i in np.arange(A.shape[0]):\r\n            for j in np.arange(A.shape[1]):\r\n                LU[i, j] = A[i, j] # since every element in the LU matrix is\r\n                # derived from the respective element in the input matrix.\r\n                count = 0\r\n                if i <= j: # means on the upper portion, use beta formula\r\n                    while count < i:\r\n                        LU[i, j] = LU[i, j] - LU[i, count]*LU[count, j]\r\n                        count = count + 1\r\n                    U[i, j] = LU[i, j]\r\n                else: # on the lower portion, use alpha formula\r\n                    while count < j:\r\n                        LU[i, j] = LU[i, j] - LU[i, count]*LU[count, j]\r\n                        count = count + 1\r\n                    LU[i, j] = LU[i, j] / LU[j, j] # this step is not in the\r\n                    L[i, j] = LU[i, j]\r\n                    # while loop because ALL alpha's need to take, even if\r\n                    # nothing is subtracted.\r\n                L[i, i] = 1 # diagonal values\r\n        if sep == True:\r\n            return L, U\r\n        else:\r\n            return LU\r\n\r\n# Calculates the determinant of a matrix using LU decomposition.\r\n# Input: A = matrix for which the determinant is to be found\r\n\r\ndef det(A):\r\n    L, U = LU(A)\r\n    det = 1.\r\n    for i in np.arange(A.shape[0]):\r\n        det = det * U[i, i] # multiply by all diagonal elements in the upper matrix\r\n    return det\r\n\r\n# Solves a matrix equation using LU decomposition.\r\n# Inputs: L and U are the decomposed lower and upper triangular matrices\r\n# respectively, and b is the vector with all the constants.\r\n# Output: vector containing all the x values\r\n\r\ndef solve(A, b):\r\n    if A.shape[0] == np.size(b):\r\n        L, U = LU(A)\r\n        y = b.copy() # so that the value of b does not change with y\r\n        for i in np.arange(np.size(b)):\r\n            count = 0\r\n            while count < i:\r\n                y[i] = y[i] - L[i, count]*y[count]\r\n                count = count + 1\r\n        x = y.copy()\r\n        for j in np.arange(1, np.size(b) + 1):\r\n            count = j\r\n            while count > 1:\r\n                x[-j] = x[-j] - U[-j, -count + 1]*x[-count + 1]\r\n                count = count - 1\r\n            x[-j] = x[-j] / U[-j, -j]\r\n        return x\r\n    else:\r\n        print(\"Size mismatch\")\r\n\r\n# To solve for A^-1 using LU decomposition we just combine the solutions to\r\n# vectors(1, 0, 0), (0, 1, 0) and (0, 0, 1).\r\n\r\ndef inv(A):\r\n    I = np.identity(A.shape[0])\r\n    inv = np.zeros([A.shape[0], A.shape[1]])\r\n    for j in np.arange(A.shape[1]):\r\n        x = solve(A, I[j])\r\n        for i in np.arange(A.shape[0]):\r\n            inv[i, j] = x[i]\r\n    return inv", "meta": {"hexsha": "e2c140d764ff4bb590c9964a1503efbccd5bece4", "size": 3297, "ext": "py", "lang": "Python", "max_stars_repo_path": "Matrix_2.py", "max_stars_repo_name": "adrielyeung/computational-physics", "max_stars_repo_head_hexsha": "c34c881b2e6ff29aebce6d0eb6d8d8404648ec71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-04T18:44:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-04T18:44:00.000Z", "max_issues_repo_path": "Matrix_2.py", "max_issues_repo_name": "adrielyeung/computational-physics", "max_issues_repo_head_hexsha": "c34c881b2e6ff29aebce6d0eb6d8d8404648ec71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Matrix_2.py", "max_forks_repo_name": "adrielyeung/computational-physics", "max_forks_repo_head_hexsha": "c34c881b2e6ff29aebce6d0eb6d8d8404648ec71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3372093023, "max_line_length": 87, "alphanum_fraction": 0.5010615711, "include": true, "reason": "import numpy", "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407152622597, "lm_q2_score": 0.8918110454379297, "lm_q1q2_score": 0.8679468197407942}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef get_y(x):\n    f_x = (x + 2)**2 - 16*np.exp(-((x-2)**2))\n    return f_x\n\nx = np.arange(-8,8,0.001)\ny = list(map(lambda u: get_y(u),x))\nplt.plot(x,y)\n# plt.show()\n\ndef get_grad(x):\n    deriv = (2*x + 4)-16*(-2*x+4)*np.exp(-((x-2)**2))\n    return deriv\n\ndef gradient_descent(start_x, func, grad):\n    # Precision of the solution\n    prec = 0.0001\n    # Use a fixed small step size\n    step_size = 0.1\n    # max iterations\n    max_iter = 100\n    x_new = start_x\n    res = []\n    for i in range(max_iter):\n        x_old = x_new\n        # Use beta = -1 for gradient descent\n        x_new = x_old - step_size * grad(x_new)\n        f_x_new = func(x_new)\n        f_x_old = func(x_old)\n        res.append([x_new, f_x_new])\n        if(abs(f_x_new-f_x_old)<prec):\n            print(\"change in function values too small, leaving\")\n            return np.array(res)\n    print(\"exceed maximum number of iterations, leaving\")\n    return np.array(res)\n\nx_0 = -8\nres = gradient_descent(x_0, get_y, get_grad)\nplt.plot(res[:,0], res[:,1], '+')\n\nx_1 = 8\nres = gradient_descent(x_1, get_y, get_grad)\nplt.plot(res[:,0], res[:,1], '+')\n\n\nplt.show()\n", "meta": {"hexsha": "c12add3eac3e44431da77c6956a79b77d2c901d8", "size": 1180, "ext": "py", "lang": "Python", "max_stars_repo_path": "lxmls/readers/exercise12.py", "max_stars_repo_name": "gomesfernanda/lxmls_lab", "max_stars_repo_head_hexsha": "74b60b9e79aaa2994aee9428b623c04e93807bda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lxmls/readers/exercise12.py", "max_issues_repo_name": "gomesfernanda/lxmls_lab", "max_issues_repo_head_hexsha": "74b60b9e79aaa2994aee9428b623c04e93807bda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lxmls/readers/exercise12.py", "max_forks_repo_name": "gomesfernanda/lxmls_lab", "max_forks_repo_head_hexsha": "74b60b9e79aaa2994aee9428b623c04e93807bda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0816326531, "max_line_length": 65, "alphanum_fraction": 0.5940677966, "include": true, "reason": "import numpy", "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407230237445, "lm_q2_score": 0.8918110346549902, "lm_q1q2_score": 0.8679468161681764}}
{"text": "import math\nimport numpy as np\nimport copy\n\ndef coordinate_transformation_in_angle(positions, base_angle):\n    '''\n    Transformation the coordinate in the angle\n\n    Parameters\n    -------\n    positions : numpy.ndarray\n        this parameter is composed of xs, ys \n        should have (2, N) shape \n    base_angle : float [rad]\n    \n    Returns\n    -------\n    traslated_positions : numpy.ndarray\n        the shape is (2, N)\n    \n    '''\n    if positions.shape[0] != 2:\n        raise ValueError('the input data should have (2, N)')\n\n    positions = np.array(positions)\n    positions = positions.reshape(2, -1)\n\n    rot_matrix = [[np.cos(base_angle), np.sin(base_angle)],\n                  [-1*np.sin(base_angle), np.cos(base_angle)]]\n\n    rot_matrix = np.array(rot_matrix)\n    \n    translated_positions = np.dot(rot_matrix, positions)\n\n    return translated_positions\n\ndef coordinate_transformation_in_position(positions, base_positions):\n    '''\n    Transformation the coordinate in the positions\n\n    Parameters\n    -------\n    positions : numpy.ndarray\n        this parameter is composed of xs, ys \n        should have (2, N) shape \n    base_positions : numpy.ndarray\n        this parameter is composed of x, y\n        shoulg have (2, 1) shape\n    \n    Returns\n    -------\n    traslated_positions : numpy.ndarray, shape(2, N)\n    \n    '''\n\n    if positions.shape[0] != 2:\n        raise ValueError('the input data should have (2, N)')\n\n    positions = np.array(positions)\n    positions = positions.reshape(2, -1)\n    base_positions = np.array(base_positions)\n    base_positions = base_positions.reshape(2, 1)\n\n    translated_positions = positions - base_positions\n\n    return translated_positions\n\n\ndef coordinate_transformation_in_matrix_angles(positions, base_angles):\n    '''\n    Transformation the coordinate in the matrix angle\n\n    Parameters\n    -------\n    positions : numpy.ndarray\n        this parameter is composed of xs, ys \n        should have (2, N) shape \n    base_angle : float [rad]\n    \n    Returns\n    -------\n    traslated_positions : numpy.ndarray\n        the shape is (2, N)\n    \n    '''\n    if positions.shape[0] != 2:\n        raise ValueError('the input data should have (2, N)')\n\n    positions = np.array(positions)\n    positions = positions.reshape(2, -1)\n    translated_positions = np.zeros_like(positions)\n\n    for i in range(len(base_angles)):\n        rot_matrix = [[np.cos(base_angles[i]), np.sin(base_angles[i])],\n                    [-1*np.sin(base_angles[i]), np.cos(base_angles[i])]]\n\n        rot_matrix = np.array(rot_matrix)\n    \n        translated_position = np.dot(rot_matrix, positions[:, i].reshape(2, 1))\n        \n        translated_positions[:, i] = translated_position.flatten()\n\n    return translated_positions.reshape(2, -1)\n\n# def coordinate_inv_transformation\nif __name__ == '__main__':\n    positions_1 = np.array([[1.0], [2.0]])\n    base_angle = 1.25\n\n    translated_positions_1 = coordinate_transformation_in_angle(positions_1, base_angle)\n    print(translated_positions_1)\n\n", "meta": {"hexsha": "9cfa220f46434c6059773d10eccd42746cbbf6e9", "size": 3027, "ext": "py", "lang": "Python", "max_stars_repo_path": "mpc/extend/coordinate_trans.py", "max_stars_repo_name": "ompugao/linear_nonlinear_control", "max_stars_repo_head_hexsha": "3beff53d83983848def7cb866189cf1661c01058", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-15T00:23:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-15T00:23:07.000Z", "max_issues_repo_path": "mpc/extend/coordinate_trans.py", "max_issues_repo_name": "tanakataiki2/linear_nonlinear_control", "max_issues_repo_head_hexsha": "7e9111acd4ff7611ef4fd913afd35a3c7042dcbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mpc/extend/coordinate_trans.py", "max_forks_repo_name": "tanakataiki2/linear_nonlinear_control", "max_forks_repo_head_hexsha": "7e9111acd4ff7611ef4fd913afd35a3c7042dcbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-15T16:06:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T16:06:54.000Z", "avg_line_length": 26.7876106195, "max_line_length": 88, "alphanum_fraction": 0.6455236207, "include": true, "reason": "import numpy", "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.968381236381426, "lm_q2_score": 0.8962513738264114, "lm_q1q2_score": 0.867913013494572}}
{"text": "import numpy\n\ndef functional_iteration(f, x0, max_steps=100, tol=1e-10):\n    x = numpy.zeros(max_steps+1)\n    x[0] = x0\n    step = 0\n    g = lambda x : x - f(x)\n    while abs(f(x[step])) > tol and step < max_steps:\n        step = step + 1\n        x[step] = g(x[step-1])\n    return x[:step+1]\n    \ndef chord(f, x0, m, max_steps=100, tol=1e-10):\n    x = numpy.zeros(max_steps+1)\n    x[0] = x0\n    step = 0\n    g = lambda x : x - m * f(x)\n    while abs(f(x[step])) > tol and step < max_steps:\n        step = step + 1\n        x[step] = g(x[step-1])\n    return x[:step+1]\n    \ndef newton(f, df, x0, max_steps=100, tol=1e-10):\n    x = numpy.zeros(max_steps+1)\n    x[0] = x0\n    step = 0\n    g = lambda x : x - f(x) / df(x)\n    while abs(f(x[step])) > tol and step < max_steps:\n        step = step + 1\n        x[step] = g(x[step-1])\n    return x[:step+1]\n    \ndef secant(f, x0, x1, max_steps=100, tol=1e-10):\n    x = numpy.zeros(max_steps+1)\n    x[0] = x0\n    x[1] = x1\n    step = 1\n    while abs(f(x[step])) > tol and step < max_steps:\n        step = step + 1\n        x[step] = x[step-1] - f(x[step-1]) * (x[step-1] - x[step-2]) / \\\n                    (f(x[step-1]) - f(x[step-2]))\n    return x[:step+1]\n    \nif __name__==\"__main__\":\n    def f(x):\n        return x - numpy.cos(x)\n    def df(x):\n        return 1 + numpy.sin(x)\n    \n    x_func_iteration = functional_iteration(f, 0)\n    print(\"Functional iteration\")\n    print(\"s={}, f(s)={}, in {} steps\".format(x_func_iteration[-1],\n          f(x_func_iteration[-1]), len(x_func_iteration)))\n    x_chord = chord(f, 0, 1.08)\n    print(\"Chord, m=1.08\")\n    print(\"s={}, f(s)={}, in {} steps\".format(x_chord[-1],\n          f(x_chord[-1]), len(x_chord)))\n    x_chord = chord(f, 0, 0.8)\n    print(\"Chord, m=0.8\")\n    print(\"s={}, f(s)={}, in {} steps\".format(x_chord[-1],\n          f(x_chord[-1]), len(x_chord)))\n    x_newton = newton(f, df, 0)\n    print(\"Newton\")\n    print(\"s={}, f(s)={}, in {} steps\".format(x_newton[-1],\n          f(x_newton[-1]), len(x_newton)))\n    x_secant = secant(f, 0, 1)\n    print(\"Secant\")\n    print(\"s={}, f(s)={}, in {} steps\".format(x_secant[-1],\n          f(x_secant[-1]), len(x_secant)))", "meta": {"hexsha": "b5fa32a1971d01f643d0363abca067e4ea27a33f", "size": 2162, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/tex/codes/lecture8.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Lectures/tex/codes/lecture8.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Lectures/tex/codes/lecture8.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 31.3333333333, "max_line_length": 72, "alphanum_fraction": 0.519426457, "include": true, "reason": "import numpy", "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799472560581, "lm_q2_score": 0.900529781446146, "lm_q1q2_score": 0.8679125452646761}}
{"text": "from typing import Union\nimport numpy as np\n\n\ndef sigmoid_der(y: Union[int, float, np.array]) -> Union[int, float, np.array]:\n    return np.multiply(np.subtract(1.0, y), y)\n\n\ndef tanh_derivative(y: Union[int, float, np.array]) -> Union[int, float, np.array]:\n    return np.subtract(1.0, np.square(y))\n\n\ndef sigmoid(x: Union[int, float, np.array]) -> Union[int, float, np.array]:\n    return np.divide(1.0, np.add(1.0, np.exp(np.negative(x))))\n\n\ndef relu(x: Union[int, float, np.ndarray]) -> Union[int, float, np.ndarray]:\n    if isinstance(x, np.ndarray):\n        y = x.copy()\n        y[x < 0] = 0.0\n        return y\n    elif isinstance(x, float):\n        return x if x > 0.0 else 0.0\n    else:\n        return x if x > 0 else 0\n\n\ndef relu_derivative(y: Union[int, float, np.ndarray]) -> Union[int, float, np.ndarray]:\n    if isinstance(y, np.ndarray):\n        dx = y.copy()\n        dx[y > 0] = 1.0\n        return y\n    elif isinstance(y, float):\n        return 1.0 if y > 0.0 else 0.0\n    else:\n        return 1 if y > 0 else 0\n\n\nclass ActivationFunctions:\n    TANH = np.tanh\n    SIGMOID = sigmoid\n    RELU = relu\n\n\nclass ActivationFunctionsDerivatives:\n    TANH_DERIVATIVE = tanh_derivative\n    SIGMOID_DERIVATIVE = sigmoid_der\n    RELU_DERIVATIVE = relu_derivative\n\n", "meta": {"hexsha": "035dca4599e4d238037e55eea712342da20905ba", "size": 1267, "ext": "py", "lang": "Python", "max_stars_repo_path": "savageml/utility/activation_functions.py", "max_stars_repo_name": "savagewil/SavageML", "max_stars_repo_head_hexsha": "d5aa9a5305b5de088e3bf32778252c877faec41d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "savageml/utility/activation_functions.py", "max_issues_repo_name": "savagewil/SavageML", "max_issues_repo_head_hexsha": "d5aa9a5305b5de088e3bf32778252c877faec41d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "savageml/utility/activation_functions.py", "max_forks_repo_name": "savagewil/SavageML", "max_forks_repo_head_hexsha": "d5aa9a5305b5de088e3bf32778252c877faec41d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.34, "max_line_length": 87, "alphanum_fraction": 0.6243093923, "include": true, "reason": "import numpy", "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799451753696, "lm_q2_score": 0.9005297827809309, "lm_q1q2_score": 0.867912544677393}}
{"text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\n\nfrom scipy.stats import probplot\nimport pylab \n\ndef mse(originais, previsoes):\n  return np.sum( (originais - previsoes) ** 2 ) / len(originais)\n\ndef rmse(originais, previsoes):\n  return np.sqrt( mse(originais, previsoes) ) \n\ndef nrmse(originais, previsoes):\n  amplitude = np.max(originais) - np.min(originais)\n  return rmse(originais, previsoes) / amplitude\n\ndef mape(originais, previsoes):\n  return (np.sum( np.abs(originais - previsoes) / np.abs(originais) ) / len(originais)) * 100\n\ndef u(originais, previsoes):\n  n = len(originais)\n  ret = 0\n  for i in range(1, n):\n    ret += np.abs(originais[i] - previsoes[i]) / np.abs(originais[i] - originais[i-1])\n  return ret/n\n\ndef r2(originais, previsoes):\n  mx = np.mean(originais)\n  num = np.sum( (originais - previsoes) ** 2 )\n  den = np.sum( (originais - mx) ** 2 )\n  \n  return 1 - num/den\n\ndef mde(originais, previsoes):\n  a = np.sign( originais[1:] - previsoes[:-1] )\n  b = np.sign( originais[:-1] - originais[1:] )\n  return np.sum(np.where(a == b, 1, 0)) / len(originais)\n\ndef medir(originais, previsoes, ordem):\n  return pd.DataFrame([[mse(originais[ordem:], previsoes), rmse(originais[ordem:], previsoes), \\\n                       nrmse(originais[ordem:], previsoes), mape(originais[ordem:], previsoes), \\\n                       u(originais[ordem:], previsoes), r2(originais[ordem:], previsoes), \n                       mde(originais[ordem:], previsoes)]], \\\n                      columns=['MSE','RMSE','nRMSE','MAPE','U','R2','MDE'] )\n\n\ndef analise_residuos(originais, previsoes, ordem):\n  \n  residuos = originais[ordem:] - previsoes\n\n  fig, ax = plt.subplots(1, 3, figsize=(15, 5))\n\n  # ACF\n  ax[0].plot(residuos)\n  ax[0].set_title(\"Resíduos\")\n\n  # ACF\n  plot_acf(residuos, lags=20, ax=ax[1])\n  ax[1].set_title(\"ACF\")\n  \n  # Q-Q Plot\n  probplot(residuos, dist=\"norm\", plot=ax[2])\n  ax[2].set_title(\"Quantil-Quantil\")\n\n  plt.tight_layout()\n", "meta": {"hexsha": "6df9df38dd9e9d51af9d383f175eb0a17938da2b", "size": 2030, "ext": "py", "lang": "Python", "max_stars_repo_path": "metricas.py", "max_stars_repo_name": "petroniocandido/STPE", "max_stars_repo_head_hexsha": "0303224fadddd40f86b816432e1a594afaebe8fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "metricas.py", "max_issues_repo_name": "petroniocandido/STPE", "max_issues_repo_head_hexsha": "0303224fadddd40f86b816432e1a594afaebe8fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "metricas.py", "max_forks_repo_name": "petroniocandido/STPE", "max_forks_repo_head_hexsha": "0303224fadddd40f86b816432e1a594afaebe8fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8529411765, "max_line_length": 97, "alphanum_fraction": 0.6467980296, "include": true, "reason": "import numpy,from scipy,from statsmodels", "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639677785087, "lm_q2_score": 0.8933093968230773, "lm_q1q2_score": 0.8679072220312554}}
{"text": "from scipy.optimize import minimize\nimport numpy as np\nfrom numpy.linalg import norm, inv\nimport sys\n\ndef func(N, vec):\n    x1, x2 = vec\n    return  2 * N * x1 * x1 + 3 * N * x2 * x2 - 8 * N * x1 + 6 * N * x2 + 7\n\n\ndef gradient(N, vec):\n    x1, x2 = vec\n    return [4 * N * x1 - 8 * N, 6 * N * x2 + 6 * N]\n\n\ndef hessian(N, vec):\n    return np.array([[4 * N, 0.0], [0.0, 6 * N]])\n\n\ndef is_pos_def(A):    \n    try:\n        np.linalg.cholesky(A)\n        return True\n    except LinAlgError:\n        return False\n        \n\ndef main():\n    N = int(sys.argv[1])\n    M = int(sys.argv[2])\n    x_curr = [0.0, 0.0]\n    x_next = x_curr.copy()\n    res = x_next.copy()\n    hess = []\n    eps = 0.9\n    was_first_check_succ = False\n\n    for k in range(M):\n        x_curr = x_next\n        print(f'x_{k} = {x_curr}')\n        grad = gradient(N, x_curr)\n        print(f'grad(f(x_{k})) = {grad}')\n        norm_grad = norm(grad)\n        print(f'||grad(f(x_{k}))|| = {norm_grad}')\n        if norm_grad <= eps:\n            res = x_curr\n            print(f'norm of gradient is < eps.\\nResult is:\\n{res}')\n            break\n\n        hess = hessian(N, x_curr)\n        print(f'H(x) =\\n{hess}')\n        hess_inv = inv(hess)\n        print(f'H(x)^(-1) =\\n{hess_inv}')\n        d = grad\n        t = np.inf\n\n        if is_pos_def(hess_inv):\n            print(f'H(x) > 0')\n            d = -hess_inv @ grad\n            t = 1.0\n\n        else:\n            print(f'H(x) ≯ 0')\n            d = -grad\n            param_f = lambda t: func(N, x_curr + t * d)\n            t = minimize(param_f, x_curr).x\n\n        print(f'd = {d}\\nt = {t}')\n        x_next = x_curr + t * d\n        print(f'x_{k + 1} = {x_next}')\n\n        vec_diff_norm = norm(x_next - x_curr)\n        print(f'||x_{k + 1} - x_{k}|| = {vec_diff_norm}')\n        func_diff_norm = norm(func(N, x_next) - func(N, x_curr))\n        print(f'||f(x_{k + 1}) - f(x_{k})|| = {func_diff_norm}')\n\n        if  vec_diff_norm < eps and func_diff_norm < eps:\n            if was_first_check_succ == False:\n                print(\"First check passed\")\n                was_first_check_succ = True\n            elif was_first_check_succ == True:\n                res = x_next\n                print(f'Second check passed result is:\\n{res}')\n                exit()\n            else:\n                print(\"First check failed\")\n                was_first_check_succ = False\n\n    exit()\n\n\nif __name__ == \"__main__\":\n    main()", "meta": {"hexsha": "287a0c8f0bf4dcf05ca9973adc915165b2949885", "size": 2415, "ext": "py", "lang": "Python", "max_stars_repo_path": "6th_semester/MO/6_task/7_task.py", "max_stars_repo_name": "mehakun/Labs", "max_stars_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-03-06T16:08:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-02T22:11:00.000Z", "max_issues_repo_path": "6th_semester/MO/6_task/7_task.py", "max_issues_repo_name": "mehakun/Labs", "max_issues_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6th_semester/MO/6_task/7_task.py", "max_forks_repo_name": "mehakun/Labs", "max_forks_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9677419355, "max_line_length": 75, "alphanum_fraction": 0.4869565217, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639653084245, "lm_q2_score": 0.8933093989533708, "lm_q1q2_score": 0.8679072218944223}}
{"text": "import numpy as np\r\nimport copy\r\nimport scipy\r\nimport scipy.linalg\r\n\r\ndef gaussElimin(a,b):\r\n    L = [[0 for i in range(len(a))]for j in range(len(a))] #inicializar matriz de ceros para la trinagular inferior\r\n    \r\n    n = len(b)\r\n# Eliminación\r\n    for j in range(0,n-1): # colunmas\r\n        for i in range(j+1,n): # renglones\r\n            if a[i,j] != 0.0:\r\n                lam = a[i,j]/a[j,j]\r\n                L[i][j] = lam\r\n                a[i,j:n] = a[i,j:n] - lam*a[j,j:n]\r\n                b[i] = b[i] - lam*b[j]\r\n    # Sustitución regresiva\r\n    for i in range(n-1,-1,-1):\r\n        b[i] = (b[i] - np.dot(a[i,i+1:n],b[i+1:n]))/a[i,i]\r\n    return b, L, a\r\n\r\ndef Imprime(M):\r\n    for l in M:\r\n        print(l)\r\n    print(\"\\n\")\r\n\r\nif __name__ == \"__main__\":\r\n    \r\n    a = np.array([[4,1,2,-3,5], [-3,3,-1,4,-2], [-1,2,5,1,3], [5,4,3,-1,2],[1,-2,3,-4,5.]])\r\n    a_copy = copy.deepcopy(a)\r\n\r\n    b = np.array ([-16, 20, -4, -10, 3.])[np.newaxis]\r\n    b = b.T\r\n    b_copy = copy.deepcopy(b)\r\n    \r\n    L = []\r\n\r\n    x, L, a = gaussElimin(a,b)\r\n    # P, L2, U = scipy.linalg.lu(a_copy)\r\n    for i in range (0, len(a)):\r\n        L[i][i] = 1\r\n    print(\"La matriz de eliminacion es:\")\r\n    Imprime(L)\r\n    \r\n    print (f\"La matriz A resultante es: \\n\")\r\n    Imprime(a)\r\n\r\n\r\n    print (\"El vector b original\", \"\\n\",b_copy)\r\n    print(\"\\n\")\r\n    print(\"La solucion al sistema: \",\"\\n\", x, \"\\n\")\r\n    \r\n    print(f\"A = LU {np.dot(L,a)} \\n\")\r\n    print (f\"la comprobacion del sistema es: \\n {np.linalg.solve(a_copy,b_copy)}\")\r\n\r\n#%%\r\n", "meta": {"hexsha": "7005958be41cbe3b77fc858ac61e813fe7f9592d", "size": 1528, "ext": "py", "lang": "Python", "max_stars_repo_path": "GaussElimination-with-Lower-Matrix.py", "max_stars_repo_name": "EMACC99/numerical-linear-algebra", "max_stars_repo_head_hexsha": "19e907f08d8ce701895d73d7f6298af9806af233", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GaussElimination-with-Lower-Matrix.py", "max_issues_repo_name": "EMACC99/numerical-linear-algebra", "max_issues_repo_head_hexsha": "19e907f08d8ce701895d73d7f6298af9806af233", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GaussElimination-with-Lower-Matrix.py", "max_forks_repo_name": "EMACC99/numerical-linear-algebra", "max_forks_repo_head_hexsha": "19e907f08d8ce701895d73d7f6298af9806af233", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3448275862, "max_line_length": 116, "alphanum_fraction": 0.4823298429, "include": true, "reason": "import numpy,import scipy", "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889437, "lm_q2_score": 0.9059898108646849, "lm_q1q2_score": 0.867858761476386}}
{"text": "import numpy as np\nimport math\n\ndef is_prime(n: int) -> bool:\n    \"\"\"Return if n is a prime number.\"\"\"\n    if n > 2 and n % 2 == 0:\n        return False\n    return n == 2 or np.all([n % x for x in range(3, int(np.sqrt(n)) + 1)])\n\n\ndef prime_factors(n: int) -> list:\n    prime_factors_list = []\n    for i in range(2,int(math.sqrt(n))+1):\n        while n % i == 0: \n            n /= i\n            prime_factors_list.append(i)\n\n    if n > 2:\n        prime_factors_list.append(n)\n    return prime_factors_list\n", "meta": {"hexsha": "a15ee3a2176ce798952bf800b885971a09d69333", "size": 506, "ext": "py", "lang": "Python", "max_stars_repo_path": "solver/eulerlib.py", "max_stars_repo_name": "EricMei542/ProjectEulerSolutions", "max_stars_repo_head_hexsha": "c841dca04545e2f32001c7fcfca7c1a253d3ce02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solver/eulerlib.py", "max_issues_repo_name": "EricMei542/ProjectEulerSolutions", "max_issues_repo_head_hexsha": "c841dca04545e2f32001c7fcfca7c1a253d3ce02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solver/eulerlib.py", "max_forks_repo_name": "EricMei542/ProjectEulerSolutions", "max_forks_repo_head_hexsha": "c841dca04545e2f32001c7fcfca7c1a253d3ce02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0952380952, "max_line_length": 75, "alphanum_fraction": 0.5592885375, "include": true, "reason": "import numpy", "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843812, "lm_q2_score": 0.9059898140375993, "lm_q1q2_score": 0.8678587612500628}}
{"text": "import streamlit as st\nimport plotly.graph_objects as go\nimport numpy as np\n\nst.title('Superquadrics')\nst.sidebar.subheader('Formulas')\n# st.latex(r'\\left|\\frac{x}{a}\\right|^s + \\left|\\frac{y}{b}\\right|^t + \\left|\\frac{z}{c}\\right|^u = 1')\n# st.markdown('where $r$, $s$, and $t$ are positive real numbers that determine the main features of the superquadric, and $a$, $b$, and $c$ are scaling parameters.')\nst.sidebar.latex(r'\\left(\\left|\\frac{x}{a}\\right|^{n_2} + \\left|\\frac{y}{b}\\right|^{n_2}\\right)^\\frac{n_1}{n_2} + \\left|\\frac{z}{c}\\right|^{n_1} = 1')\nst.sidebar.markdown('where $n_1$ and $n_2$ are shape parameters, and $a$, $b$, and $c$ are scaling parameters.')\n# st.subheader('Formula python code')\n# with st.echo():\nimport numpy as np\n@st.cache\ndef superquadrics(a,b,c,n1,n2,x,y,z):\n    values = np.power(np.power(np.abs(x/a),n2) \\\n                    + np.power(np.abs(y/b),n2),n1/n2) \\\n            + np.power(np.abs(z/c),n1)\n    return values\nX, Y, Z = np.mgrid[-1:1:20j, -1:1:20j, -2:2:40j]\nst.sidebar.subheader('Parameters')\na  = 1.\nb  = 1.\nc  = st.sidebar.slider('c (a=b=1)', .2, 2., 1., .2)\nn1 = st.sidebar.slider('n1', 1, 10, 10, 1)\nn2 = st.sidebar.slider('n2', 1, 10, 2, 1)\nfig = go.Figure(data=go.Isosurface(\n    x = X.flatten(),\n    y = Y.flatten(),\n    z = Z.flatten(),\n    value = superquadrics(a,b,c,n1,n2,X,Y,Z).flatten(),\n    isomin = .5,\n    isomax = 1,\n    showscale = False,\n))\nfig.update_layout(\n    scene = dict(\n        xaxis_title='',\n        yaxis_title='',\n        zaxis_title='',\n        xaxis = dict(\n            showbackground = False,\n            showline = False,\n            showticklabels = False,\n        ),\n        yaxis = dict(\n            showbackground = False,\n            showline = False,\n            showticklabels = False,\n        ),\n        zaxis = dict(\n            showbackground = False,\n            showline = False,\n            showticklabels = False,\n        ),\n    )\n)\nst.write(fig)\nst.subheader('Code')\nst.markdown('* https://github.com/ken2s/superquadrics/blob/main/st_superquadrics.py')\nst.subheader('References')\nst.markdown('* https://en.wikipedia.org/wiki/Superquadrics')\n", "meta": {"hexsha": "b4c04642163e12ec466ac5536208f639def5cb93", "size": 2138, "ext": "py", "lang": "Python", "max_stars_repo_path": "st_superquadrics.py", "max_stars_repo_name": "ken2s/superquadrics", "max_stars_repo_head_hexsha": "ea1067066668df0de8d7d990813b40136a0ad00c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "st_superquadrics.py", "max_issues_repo_name": "ken2s/superquadrics", "max_issues_repo_head_hexsha": "ea1067066668df0de8d7d990813b40136a0ad00c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "st_superquadrics.py", "max_forks_repo_name": "ken2s/superquadrics", "max_forks_repo_head_hexsha": "ea1067066668df0de8d7d990813b40136a0ad00c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9365079365, "max_line_length": 166, "alphanum_fraction": 0.5884003742, "include": true, "reason": "import numpy", "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142217223021, "lm_q2_score": 0.9124361688107864, "lm_q1q2_score": 0.86785656067717}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nExercise 03: Chapter 03, Kinder & Nelson\n\nA common way to determine the value of a function is to sum over a series. \nFor example, the Maclaurin series for sin(x) is\n\n    sin(x) = x - x**3/3! + x**5/5! - x**7/7! + ...\n\nPerform a series expansion to derive the equation above. Next, write down \na general expression for the sum of the series that is valid between n = 0 \nand n = N, where N ≥ 0. This will serve as your algorithm for summing \nthe series.\n\nOne problem with the algorithm is that we do not know which value \nof N is suitable when calcualting the series. Instead of guessing, have \nyour code proceed with the summation until the Nth term contributes a \nnegligible amount to the final summation, say 1 part in 10**8.\n\nBefore writing any lines of code, discuss an approach with your neighbor \nand write out on paper how your code should proceed. Code up your approach \nin Spyder once you're done. \n\nHere are your tasks:\n\n   1. Perform a Maclaurin series expansion of the function sin(x) to \n      derive the equation in the README. \n   2. Derive a generalized, finite summation form for the series based \n      on your Maclaurin series expansion.\n   3. Discuss with your neighbor about how to approach coding the problem\n      and write out on paper how you code should proceed. \n   4. Code your approach in Spyder once you are finished.\n   5. Show that, for small values of x, the series converges.\n   6. Which value for N was required to reach the desired precision and\n      obtain convergence?\n   7. Compare your results to the value determined using NumPy's sine \n      function.\n   8. Steadily increase x and write down the relative error between your\n      calculated value for sin(x) and the NumPy function's value. \n   9. What do you notice about the relative error?\n  10. Will there be a time when the series does not converge? Make a plot\n      of the relative error vs x to support your answer.\n\nCreated on Tue Aug 20 11:02:00 2019\n\n@author: gafeiden\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# below is my basic approach for finding sin (x)\n\n# first, we need to set our x at what we are trying to solve. Here, I have set x \n# equal to 200. A randomly chosen, yet large, number. \n# At the same time, we must make sure that n is set to zero, so the MacLaurin series \n# can properly sum from the 0th term.\n\n\n\nx, n = 200, 0\nsum = 0\n\n# As I will show afterwards, large values of x will blow up and be impossible for\n#a computer to calculate. However, as sin bounces between -1 and 1 around the unit circle,\n# we can simply subtract 2pi a number of times, until x is sufficiently small, and we \n# will get the same result.\n\n\nwhile (x>2*np.pi):\n    x = x-(2*np.pi)\n\n# Here is our MacLaurin series. I have set it up, as instructed, to only calculate until the\n# term is sufficiently small. We have also created a variable, \"sum\", that will add up the terms\n# this variable will be the result for the value of sin (x) we are calculating.\n\nwhile (np.absolute((((-1)**n/(np.math.factorial(2*n+1))) * x**(2*n+1)))>(1/10**8)):\n\n    a = (((-1)**n/(np.math.factorial(2*n+1))) * x**(2*n+1))\n    sum+=a\n    n = n+1\n    \nprint(sum)    \n# As stated previously, this will not work for large values of x.\n\n#If we just run    \n \nx, n, sum, = 50, 0, 0\n\nwhile (np.absolute((((-1)**n/(np.math.factorial(2*n+1))) * x**(2*n+1)))>(1/10**8)):\n\n    a = (((-1)**n/(np.math.factorial(2*n+1))) * x**(2*n+1))\n    sum+=a\n    n = n+1\n    \n    \n# we will wither get a result that falls outside of the bounds of sin, or receive an error \n#because the computer cannot handle the calculation.\n# This one happens to be calculable, but is well outside the bounds of sin.\n\nprint(sum)\n\n#So, if we put our code to \"shrink\" x, back in:\n\nwhile (x>2*np.pi):\n    x = x-(2*np.pi)\n    \n#x becomes much smaller, and we are able to calculate it within the bounds of x.\n\n# To know how accurate our MacLaurin series is, we can compare the result with the np.sin() function\n\nsin = np.sin(x)\n\nerror = sum-sin\nprint (error)   \n\n# By gradually increasing x, we find that around the x value of 35 is where the summation really \n# starts to separate itself from the actual sin() function. Prior to this point, the error was very,\n# very small, on the order of 10^-9. Between 35 and 40, it has separated itself enough that the\n#value we get using the MacLaurin series is outside of the bounds of the actual sin function.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n", "meta": {"hexsha": "42652270975ae1319dcfdc637a513d03b3183a6f", "size": 4454, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week 01/BSW_Exercise_03.py", "max_stars_repo_name": "bswood9321/PHYS-3210", "max_stars_repo_head_hexsha": "d780cac166688338ce91099cba4a4f6628430647", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week 01/BSW_Exercise_03.py", "max_issues_repo_name": "bswood9321/PHYS-3210", "max_issues_repo_head_hexsha": "d780cac166688338ce91099cba4a4f6628430647", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week 01/BSW_Exercise_03.py", "max_forks_repo_name": "bswood9321/PHYS-3210", "max_forks_repo_head_hexsha": "d780cac166688338ce91099cba4a4f6628430647", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8926174497, "max_line_length": 100, "alphanum_fraction": 0.6971261787, "include": true, "reason": "import numpy", "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.9425067276593032, "lm_q1q2_score": 0.867850468383859}}
{"text": "#------------------------------------------------------------------------------------------\r\n#   QR Factorization of Matrix A In Python 3.8.1 Numpy 1.19.2\r\n#\r\n#   The following sample demonstrates the QR factorization of \r\n#   a randomly generated matrix A of real or complex numbers using:\r\n#\r\n#        * Gram-Schmidt Orthogonalization;\r\n#        * Householder Reflections;\r\n#   \r\n#   , and surveys the complexity and performance (single-threaded) of these both methods\r\n#\r\n#   GNU Public License (C) 2021 Arthur V. Ratz\r\n#------------------------------------------------------------------------------------------\r\n\r\nimport time\r\nimport math\r\nimport random\r\nimport pandas as pd\r\n\r\nimport numpy as np\r\nimport numpy.linalg as lin\r\n\r\nfrom qr_gschmidt import *\r\nfrom qr_gs_schwrt import *\r\nfrom qr_householder import *\r\n\r\nmat_shape      = { 'min': 3,   'max': 15   }\r\nmat_shape_perf = { 'min': 750, 'max': 950  }\r\n\r\nqr_alg         = [ { 'alg': qr_gs,       'name': 'Gram-Schmidt       ' },\r\n                   { 'alg': qr_gs_modsr, 'name': 'Schwarz-Rutishauser' },\r\n                   { 'alg': qr_hh,       'name': 'Householder        ' } ]\r\n\r\nmat_types      = [ 'real   ', 'complex' ]\r\n\r\ncheckup_status = [ 'failed', 'passed' ]\r\n\r\ncheckup_banner = \"\\n[ Verification %s... ]\"\r\nstats_banner   = \"%s Matrix A Statistics:\\n\"\r\nqr_test_banner = \"\\nQR Factorization Of A `%s` Matrix Using %s Algorithm:\"\r\nsurvey_banner  = \"Matrix: %s    WINS: [ %s : %d secs  ] LOOSES: [ %s : %d secs ]\"\r\nperf_stats     = \"%s : [ type: `%s` exec_time: %d secs verification: %s ]\"\r\n\r\napp_banner     = \"QR Factorization v.0.0.1 CPOL License (C) 2021 by Arthur V. Ratz\"\r\n\r\n# Function: perf(A, qr, type=complex) evaluates the qr factorization method's execution wall-time in nanoseconds,\r\n#           returns the tuple of the resultant matrices Q,R and the execution time\r\n\r\ndef perf(A, qr, type=complex):\r\n    t_d = time.time(); Q,R = qr(A, type); \\\r\n        return Q, R, (time.time() - t_d)\r\n\r\ndef check(M1, M2):\r\n    v1 = np.reshape(M1,-1)\r\n    v2 = np.reshape(M2,-1)\r\n    if len(v1) != len(v2):\r\n       return False\r\n    else: return 0 == len(np.where(np.array(\\\r\n       [ format(c1, '.4g') == format(c2, '.4g') \\\r\n        for c1,c2 in zip(v1, v2) ]) == False)[0])\r\n\r\ndef rand_matrix(rows, cols, type=complex):\r\n    np.set_printoptions(precision=8)\r\n    if type == complex:\r\n        return np.reshape(\\\r\n              np.random.uniform(1, 10, rows * cols) + \\\r\n              np.random.uniform(-10, 10, rows * cols) *  1j, (rows, cols))\r\n    else: return np.reshape(10 * np.random.uniform(\\\r\n            0.01, 0.99, rows * cols), (rows, cols))\r\n    \r\ndef print_matrix(M, alias):\r\n    np.set_printoptions(\\\r\n        precision=2, suppress=True, \\\r\n        formatter='complexfloat')\r\n    if isinstance(M, complex):\r\n        eps = np.finfo(float).eps; tol = 100\r\n        M = [np.real(m) if np.imag(m)<tol*eps else m for m in M]\r\n        M = [np.asscalar(np.real_if_close(m)) for m in M]\r\n    print(\"\\nMatrix %s (%dx%d):\" % \\\r\n        (alias, len(M), len(M[0])),\"\\n\")\r\n    pd.set_option('precision', 2); \\\r\n        df = pd.DataFrame(M)\r\n    df = df.to_string(index=False).replace('j','i')\r\n    print(df)\r\n\r\ndef logo():\r\n    print(app_banner)\r\n    print(''.join(['=' for p in range(len(app_banner))]))\r\n    \r\ndef qr_demo(s, qr, type=complex):\r\n\r\n    print(qr_test_banner % (\\\r\n        \"Complex\" if type == complex \\\r\n            else \"Real\", s.replace(' ', '')))\r\n    \r\n    rows = np.random.randint(\\\r\n        mat_shape['min'], mat_shape['max'])\r\n\r\n    cols = np.random.randint(\\\r\n        mat_shape['min'], mat_shape['max'])\r\n    \r\n    A = rand_matrix(rows, cols, type); print_matrix(A, \"A\")\r\n    \r\n    Q,R,T = perf(A, qr, type)\r\n        \r\n    status = check(A, Q.dot(R))\r\n\r\n    A = np.around(A, decimals=2)\r\n    Q = np.around(Q, decimals=2)\r\n    R = np.around(R, decimals=2)\r\n\r\n    print_matrix(Q, \"Q\")\r\n    print_matrix(R, \"R\")\r\n    \r\n    print(checkup_banner % (checkup_status[status]),\"\\n\")\r\n\r\n    return status\r\n\r\ndef qr_perf():\r\n    \r\n    print (\"\\nPerformance Assessment:\")\r\n    print (\"=======================================\")\r\n    \r\n    rows = np.random.randint(\\\r\n        mat_shape_perf['min'], mat_shape_perf['max'])\r\n\r\n    cols = np.random.randint(\\\r\n        mat_shape_perf['min'], mat_shape_perf['max'])\r\n    \r\n    d = np.random.randint(5)\r\n    cols += d if random.uniform(0,1) > 0.5 else -d\r\n    \r\n    A = [ rand_matrix(rows, cols, float), \\\r\n          rand_matrix(rows, cols, complex) ]\r\n    \r\n    print (\"\\nMatrix A (%d x %d):\" % (rows, cols))\r\n    print (\"============================\\n\")\r\n    \r\n    exec_time = np.zeros((len(mat_types), len(qr_alg)))\r\n    survey = np.zeros((len(mat_types), 1), dtype=object)\r\n    \r\n    status = 0\r\n    for s_j in range(len(mat_types)):\r\n        for s_i in range(len(qr_alg)):\r\n            qr, name = \\\r\n                qr_alg[s_i]['alg'], qr_alg[s_i]['name']; \\\r\n                Q, R, exec_time[s_j][s_i] = perf(A[s_j],   \\\r\n                    qr, float if s_j % len(mat_types) == 0 else complex); \\\r\n                status = checkup_status[check(A[s_j], Q.dot(R))]\r\n            print(perf_stats % (name, mat_types[s_j].replace(' ','').lower(), \\\r\n                exec_time[s_j][s_i], status))\r\n        \r\n            if status == \"failed\": break\r\n\r\n        if status == \"failed\":\r\n           print_matrix(A[s_j], \"A\")\r\n           print_matrix(Q, \"Q\")\r\n           print_matrix(R, \"R\")\r\n            \r\n           print(\"\\n*** FAILURE!!! ****\\n\")\r\n        \r\n           break\r\n            \r\n        wr_time, lr_time = \\\r\n            np.min(exec_time[s_j]), \\\r\n            np.max(exec_time[s_j])\r\n    \r\n        wi = np.where(exec_time[s_j] == wr_time)[0][0]\r\n        li = np.where(exec_time[s_j] == lr_time)[0][0]\r\n    \r\n        s_w = qr_alg[wi]['name']; s_l = qr_alg[li]['name']\r\n            \r\n        survey[s_j] = { 'alg_w': s_w, 'tm_w': wr_time, \\\r\n                        'alg_l': s_l, 'tm_l': lr_time }\r\n\r\n        print(\"\\n\")\r\n        \r\n    for s_j in range(len(mat_types)):\r\n        print(survey_banner % (mat_types[s_j].lower(),\r\n              survey[s_j][0]['alg_w'], survey[s_j][0]['tm_w'], \\\r\n              survey[s_j][0]['alg_l'], survey[s_j][0]['tm_l']))\r\n    \r\ndef main():\r\n    \r\n    logo()\r\n    \r\n    np.random.seed(int(time.time()))\r\n    \r\n    status = 0\r\n    for s_j in range(len(qr_alg)):\r\n        for s_i in range(len(mat_types)):\r\n            status = qr_demo(qr_alg[s_j]['name'], \\\r\n                qr_alg[s_j]['alg'], complex if s_i % 2 else float)\r\n            if status == False: break\r\n\r\n        if status == False:\r\n           print(\"\\n*** FAILURE!!! ****\\n\"); break\r\n\r\n    qr_perf(); print(\"\\n\")\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n", "meta": {"hexsha": "6294c6db5eb75f4210c8df6eb1a6c1c8081cb4f2", "size": 6681, "ext": "py", "lang": "Python", "max_stars_repo_path": "qr_decomposition/qr_decomposition/qr_decomposition.py", "max_stars_repo_name": "arthurratz/qr_decomposition", "max_stars_repo_head_hexsha": "62f14b77bdc3f1f5f5ca73c5c4a5121154212e66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-22T17:07:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T17:07:35.000Z", "max_issues_repo_path": "qr_decomposition/qr_decomposition/qr_decomposition.py", "max_issues_repo_name": "herpes-free-engineer-hpe/qr_decomposition", "max_issues_repo_head_hexsha": "62f14b77bdc3f1f5f5ca73c5c4a5121154212e66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qr_decomposition/qr_decomposition/qr_decomposition.py", "max_forks_repo_name": "herpes-free-engineer-hpe/qr_decomposition", "max_forks_repo_head_hexsha": "62f14b77bdc3f1f5f5ca73c5c4a5121154212e66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-22T17:02:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T17:02:33.000Z", "avg_line_length": 32.9113300493, "max_line_length": 114, "alphanum_fraction": 0.5080077833, "include": true, "reason": "import numpy", "num_tokens": 1796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.920789679151471, "lm_q1q2_score": 0.8678504643855052}}
{"text": "import numpy as np\n\nfrom gd import *\nfrom sgd import *\nfrom costs import *\n\n\ndef least_squares_GD(y, tx, initial_w,\n                     max_it, gamma, verbose=False):\n    \"\"\"Linear Regression with Gradient Descent\n\n    Uses Mean Squared Error as the loss function.\n    \"\"\"\n    losses, ws = gradient_descent(\n        y=y,\n        tx=tx,\n        initial_w=initial_w,\n        max_iters=max_it,\n        gamma=gamma,\n        verbose=verbose\n    )\n    \n    return ws[-1], losses[-1]\n\n\ndef least_squares_SGD(y, tx, initial_w,\n                      max_iters, gamma, verbose=False):\n    \"\"\"Linear regression with Stochastic Gradient Descent (SGD)\n\n    Current implementation uses Mean Squared Error as the loss.\n    \"\"\"\n    # Use batch_size = 1 as per the project instructions.\n    losses, ws = stochastic_gradient_descent(\n        y=y,\n        tx=tx,\n        initial_w=initial_w,\n        max_iters=max_iters,\n        gamma=gamma,\n        batch_size=1,\n        verbose=verbose\n    )\n\n    return ws[-1], mse(y, tx, ws[-1])\n\ndef least_squares(y, tx):\n    \"\"\"Linear regression fit using normal equations.\"\"\"\n    a = tx.T @ tx\n    b = tx.T @ y\n    w = np.linalg.solve(a, b)\n    loss = mse(y, tx, w)\n    return w, loss\n\ndef ridge_regression(y, tx, lambda_):\n    \"\"\" Ridge regression fit using normal equations \"\"\"\n    a = (tx.T @ tx) + lambda_*2*tx.shape[0] * np.eye(tx.shape[1])\n    b = tx.T @ y\n    w = np.linalg.solve(a, b)\n    return w, mse(y, tx, w)\n\n\ndef logistic_regression(y, tx, initial_w, max_iters, \n                        gamma, batch_size=None, verbose=False):\n    \"\"\" Logistic regression with gradient descent or stochastic gradient descent\"\"\"\n\n    \n    if batch_size:\n        losses, ws = stochastic_gradient_descent_logistic(\n            y=y,\n            tx=tx,\n            initial_w=initial_w,\n            batch_size=batch_size,\n            max_iters=max_iters,\n            gamma=gamma,\n            verbose=verbose\n        )\n    else:\n        losses, ws = gradient_descent_logistic(\n            y=y,\n            tx=tx,\n            initial_w=initial_w,\n            max_iters=max_iters,\n            gamma=gamma,\n            verbose=verbose\n        )\n        \n    return ws[-1], logistic_error(y, tx, ws[-1])\n\n\ndef reg_logistic_regression(y, tx, lambda_, reg, initial_w,\n                            max_iters, gamma, verbose=False, \n                            early_stopping=True, tol = 0.0001, \n                            patience = 5):\n    \"\"\" Regularized logistic regression with gradient descent\"\"\"\n\n    losses, ws = reg_gradient_descent_logistic(\n        y=y,\n        tx=tx,\n        initial_w=initial_w,\n        max_iters=max_iters,\n        gamma=gamma,\n        lambda_=lambda_,\n        reg=reg,\n        verbose=verbose,\n        early_stopping=early_stopping,\n        tol=tol,\n        patience=patience\n    )\n    \n    return ws[-1], losses[-1]\n", "meta": {"hexsha": "c0f6410aa6b0444d99f5f12bcbd3771b0ee61dc3", "size": 2854, "ext": "py", "lang": "Python", "max_stars_repo_path": "project1/utils/implementations.py", "max_stars_repo_name": "itslwg/epflml-projects", "max_stars_repo_head_hexsha": "74180683f5f07845f93e1e45e5197dc36802d0f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project1/utils/implementations.py", "max_issues_repo_name": "itslwg/epflml-projects", "max_issues_repo_head_hexsha": "74180683f5f07845f93e1e45e5197dc36802d0f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-25T11:18:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-30T15:49:46.000Z", "max_forks_repo_path": "project1/utils/implementations.py", "max_forks_repo_name": "itslwg/epflml-projects", "max_forks_repo_head_hexsha": "74180683f5f07845f93e1e45e5197dc36802d0f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9454545455, "max_line_length": 83, "alphanum_fraction": 0.5651716889, "include": true, "reason": "import numpy", "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.92414182206801, "lm_q1q2_score": 0.867792107322535}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.cm import get_cmap\n\nplt.rcParams['figure.figsize'] = [8, 8]\nplt.rcParams.update({'font.size': 18})\n\n# Define Domain\ndx = 0.001\nL = np.pi\nx = L * np.arange(-1+dx, 1+dx, dx)\nn = len(x)\nnquart = int(np.floor(n/4))\n\n# Definition of hat function (in this case im defining a hat funtion)\nf = np.zeros_like(x)\nf[nquart:2*nquart] = (4/n)*np.arange(1, nquart+1) # positive slope\nf[2*nquart:3*nquart] = np.ones(nquart) - (4/n)*np.arange(0, nquart) # negative slope\n\nfig, ax = plt.subplots()\nax.plot(x, f, '-', color='k', LineWidth=2)\n\n# Computation of the fourier series (this is an approximation for the limit has been set to 20 iterations)\nname = \"Accent\"\ncmap = get_cmap('tab10')\ncolors = cmap.colors\nax.set_prop_cycle(color=colors)\n\nA0 = np.sum(f * np.ones_like(x)) * dx\nfFS = A0/2\n\nA = np.zeros(20)\nB = np.zeros(20)\nfor k in range(20):\n    A[k] = np.sum(f * np.cos(np.pi * (k+1) * x / L)) * dx # inner product a(k)\n    B[k] = np.sum(f * np.sin(np.pi * (k+1) * x / L)) * dx # inner product b(k)\n    fFS = fFS + A[k] * np.cos((k+1)*np.pi*x/L) + B[k]*np.sin((k+1)*np.pi*x/L)\n    ax.plot(x, fFS, '-')\n\n# Amplitudes and reconstruction error rate\n\nfFS = (A0/2) * np.ones_like(f)\nkmax = 100\nA = np.zeros(kmax)\nB = np.zeros(kmax)\nERR = np.zeros(kmax)\n\nA[0] = A0/2\nERR[0] = np.linalg.norm(f-fFS)/np.linalg.norm(f)\n\nfor k in range(1, kmax):\n    A[k] = np.sum(f * np.cos(np.pi * k * x / L)) * dx\n    B[k] = np.sum(f * np.sin(np.pi * k * x / L)) * dx\n    fFS += A[k] * np.cos(np.pi * k * x / L) + B[k] * np.sin(k * np.pi * x / L)\n    ERR[k] = np.linalg.norm(f-fFS)/np.linalg.norm(f)\n\nthresh = np.median(ERR) * np.sqrt(kmax) * (4/np.sqrt(3))\nr = np.max(np.where(ERR > thresh))\n\nfig, axs = plt.subplots(2, 1)\naxs[0].semilogy(np.arange(kmax), A, color='k', LineWidth=2)\naxs[0].semilogy(r, A[r], 'o', color='b', MarkerSize=10)\nplt.sca(axs[0])\nplt.title('Fourier Coefficients')\n\naxs[1].semilogy(np.arange(kmax), ERR, color='k', LineWidth=2)\naxs[1].semilogy(r, ERR[r], 'o', color='b', MarkerSize=10)\nplt.sca(axs[1])\nplt.title('Error')\nplt.show()\n", "meta": {"hexsha": "6fe1e5c120f7af25baaf8422b54a7f8e1f1a8671", "size": 2090, "ext": "py", "lang": "Python", "max_stars_repo_path": "FourierSeriesPy.py", "max_stars_repo_name": "EduardoAlm/Digital-Signal-Processing-and-Data-pre--processing", "max_stars_repo_head_hexsha": "7cfc3f017699b4edc40bd4852967fb3ffab3a2ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FourierSeriesPy.py", "max_issues_repo_name": "EduardoAlm/Digital-Signal-Processing-and-Data-pre--processing", "max_issues_repo_head_hexsha": "7cfc3f017699b4edc40bd4852967fb3ffab3a2ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FourierSeriesPy.py", "max_forks_repo_name": "EduardoAlm/Digital-Signal-Processing-and-Data-pre--processing", "max_forks_repo_head_hexsha": "7cfc3f017699b4edc40bd4852967fb3ffab3a2ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4366197183, "max_line_length": 106, "alphanum_fraction": 0.6186602871, "include": true, "reason": "import numpy", "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298658, "lm_q2_score": 0.9019206738932334, "lm_q1q2_score": 0.8677447138717942}}
{"text": "from sklearn import linear_model\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom pylab import scatter, show, legend, xlabel, ylabel\n\n# https://www.youtube.com/watch?v=-BQCB6Uch1g\n# from __future__ import division\n\ndef logistic_func(theta, x):\n  return float(1) / (1 + math.e**(-x.dot(theta)))\n\ndef log_gradient(theta, x, y):\n  first_calc = logistic_func(theta, x) - np.squeeze(y)\n  final_calc = first_calc.T.dot(x)\n  return final_calc\n\ndef cost_func(theta, x, y):\n  log_func_v = logistic_func(theta,x)\n  y = np.squeeze(y)\n  step1 = y * np.log(log_func_v)\n  step2 = (1-y) * np.log(1 - log_func_v)\n  final = -step1 - step2\n  return np.mean(final)\n\ndef grad_desc(theta_values, X, y, lr=.001, limit=10):\n  #normalize\n  X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)\n  #setup cost iter\n  cost_iter = []\n  cost = cost_func(theta_values, X, y)\n  cost_iter.append([0, cost])\n  i = 0\n  while(i < limit):\n    # old_cost = cost\n    theta_values = theta_values - (lr * log_gradient(theta_values, X, y))\n    cost = cost_func(theta_values, X, y)\n    cost_iter.append([i, cost])\n    i+=1\n  return theta_values, np.array(cost_iter)\n\ndef pred_values(theta, X, hard=True):\n  #normalize\n  X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)\n  pred_prob = logistic_func(theta, X)\n  pred_value = np.where(pred_prob >= .5, 1, 0)\n  if hard:\n    return pred_value\n  return pred_prob\n\ndef logistic_regression(Y, X, limit=100):\n  shape = X.shape[1]\n  # print(\"Dimension = (\",shape,\")\")\n  # y_flip = np.logical_not(Y)\n  betas = np.zeros(shape)\n  fitted_values, cost_iter = grad_desc(betas, X, Y,limit=limit)\n  # print(\"Fit values =\",fitted_values)\n  predicted_y = pred_values(fitted_values, X)\n  # print(\"Y =\",Y)\n  # print(\"Predict Y =\",predicted_y)\n\n  print(\"Y =\",np.sum(Y))\n  print(\"Predict Y =\", np.sum(predicted_y))\n  print(\"Equal =\", np.sum(Y == predicted_y))\n\n  # print(cost_iter)\n  plt.plot(cost_iter[:,0], cost_iter[:,1],'-', linewidth=3)\n  plt.ylabel(\"Cost\")\n  plt.xlabel(\"Iteration\")\n  plt.show()\n  plt.savefig('cost_iter.png')\n\n  from scipy.optimize import fmin_l_bfgs_b\n  #normalize data\n  norm_X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)\n  myargs = (norm_X, Y)\n  betas = np.zeros(norm_X.shape[1])\n  lbfgs_fitted = fmin_l_bfgs_b(cost_func, x0=betas, args=myargs, fprime=log_gradient)\n\n  lbfgs_predicted = pred_values(lbfgs_fitted[0], norm_X, hard=True)\n\n  print(\"\\n2a part\")\n  # print(\"l_bfgs_b =\",lbfgs_fitted[0])\n  print(\"lbfgs_predicted == Y =\", sum(lbfgs_predicted == Y))\n\n  logreg = linear_model.LogisticRegression()\n  logreg.fit(norm_X, Y)\n  print(\"From 'sklearn' --> logreg.predict == Y =\", sum(Y == logreg.predict(norm_X,)))\n  print(logreg.score(norm_X, Y))\n\n  fitted_values, cost_iter = grad_desc(betas, norm_X, Y)\n  predicted_y = pred_values(fitted_values, norm_X)\n  print(\"From 'my function' --> Predict Y =\",sum(predicted_y == Y))\n\n  plt.plot(cost_iter[:,0], cost_iter[:,1],'-', linewidth=3)\n  plt.ylabel(\"Cost\")\n  plt.xlabel(\"Iteration\")\n  plt.show()\n  plt.savefig(\"cost_iter_second.png\")\n\ndef test():\n  import seaborn as sns\n  #matplotlib inline\n  sns.set(style='ticks', palette='Set2')\n\n  data = datasets.load_iris()\n  X = data.data[:100, :2]\n  y = data.target[:100]\n  X_full = data.data[:100, :]\n\n  setosa = plt.scatter(X[:50,0], X[:50,1], c='b')\n  versicolor = plt.scatter(X[50:,0], X[50:,1], c='r')\n  plt.xlabel(\"Sepal Length\")\n  plt.ylabel(\"Sepal Width\")\n  plt.legend((setosa, versicolor), (\"Setosa\", \"Versicolor\"))\n  sns.despine()\n\n  shape = X.shape[1]\n  print(\"Dimension = (\",shape,\")\")\n  y_flip = np.logical_not(y) #flip Setosa to be 1 and Versicolor to zero to be consistent\n  betas = np.zeros(shape)\n  fitted_values, cost_iter = grad_desc(betas, X, y)\n  print(\"Fit values =\",fitted_values)\n\n  predicted_y = pred_values(fitted_values, X)\n\n  print(\"Predict Y =\",predicted_y)\n\n  # print(np.sum(y_flip == predicted_y))\n\n  plt.plot(cost_iter[:,0], cost_iter[:,1])\n  plt.ylabel(\"Cost\")\n  plt.xlabel(\"Iteration\")\n  sns.despine()\n\n  plt.show()\n  # plt.savefig('foo.png')\n\n  from scipy.optimize import fmin_l_bfgs_b\n  #normalize data\n  norm_X = (X_full - np.mean(X_full, axis=0)) / np.std(X_full, axis=0)\n  myargs = (norm_X, y_flip)\n  betas = np.zeros(norm_X.shape[1])\n  lbfgs_fitted = fmin_l_bfgs_b(cost_func, x0=betas, args=myargs, fprime=log_gradient)\n  print(\"l_bfgs_b =\",lbfgs_fitted[0])\n\n  lbfgs_predicted = pred_values(lbfgs_fitted[0], norm_X, hard=True)\n  print(sum(lbfgs_predicted == y_flip))\n\n  logreg = linear_model.LogisticRegression()\n  logreg.fit(norm_X, y_flip)\n  print(sum(y_flip == logreg.predict(norm_X)))\n\n  fitted_values, cost_iter = grad_desc(betas, norm_X, y_flip)\n  predicted_y = pred_values(fitted_values, norm_X)\n  print(sum(predicted_y == y_flip))\n\n", "meta": {"hexsha": "138eff3596cbb92292f35df60a316a8374ab5872", "size": 4699, "ext": "py", "lang": "Python", "max_stars_repo_path": "2015s2-mo444-assignment-02/codes/logistic_regression_test.py", "max_stars_repo_name": "rodneyrick/MO444-PatternRecognition-and-MachineLearning", "max_stars_repo_head_hexsha": "5b0f9968b5b9e5c761cac48675118a9a755a5592", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-04T21:00:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-04T21:00:07.000Z", "max_issues_repo_path": "2015s2-mo444-assignment-02/codes/logistic_regression_test.py", "max_issues_repo_name": "rodneyrick/MO444-PatternRecognition-and-MachineLearning", "max_issues_repo_head_hexsha": "5b0f9968b5b9e5c761cac48675118a9a755a5592", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2015s2-mo444-assignment-02/codes/logistic_regression_test.py", "max_forks_repo_name": "rodneyrick/MO444-PatternRecognition-and-MachineLearning", "max_forks_repo_head_hexsha": "5b0f9968b5b9e5c761cac48675118a9a755a5592", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7405063291, "max_line_length": 89, "alphanum_fraction": 0.6767397319, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075744568837, "lm_q2_score": 0.90192067059785, "lm_q1q2_score": 0.8677447087414234}}
{"text": "import numpy as np\n\ndef cross_entropy_sigmoid(y, y_hat):\n    m = y.shape[1]\n    #cost = np.sum(y*np.log(y_hat) + (1-y)*np.log(1 - y_hat)) / (-1*m)\n    cost = (1./m) * (-np.dot(y,np.log(y_hat).T) - np.dot(1-y, np.log(1-y_hat).T))\n    \n    # So that we have a real number at the end instead of a singleton; e.g. [[3]] => 3\n    cost = np.squeeze(cost)\n    assert(cost.shape == ())\n    \n    return cost\n\ndef cross_entropy_softmax(y, y_hat):\n    # y is a vector of dimension [1 x num_of_inputs]\n    # IT IS NOT ONE HOT VECTOR !!!\n        \n    num_inputs = y_hat.shape[1]\n    \n    # get the probabilities indexed by classes, y_hat\n    probs = y_hat[y.squeeze(), range(num_inputs)]\n\n    \n    log_probs = np.log(probs)\n    \n    cost = np.sum(log_probs)/(-1*num_inputs)\n    \n    # So that we have a real number at the end instead of a singleton; e.g. [[3]] => 3\n    cost = cost.squeeze()\n    assert(cost.shape == ())\n    \n    return cost\n\ndef cross_entropy_sigmoid_derivative(y, y_hat):\n    m = y.shape[1]\n    return (-(np.divide(y, y_hat) - np.divide(1 - y, 1 - y_hat)))\n\ndef cross_entropy_softmax_derivative(y, y_hat):\n    # y is a vector of dimension [1 x num_of_inputs]\n    # IT IS NOT ONE HOT VECTOR !!!\n\n    num_inputs = y_hat.shape[1]\n    \n    d = np.zeros(y_hat.shape)\n    \n    d[y, range(num_inputs)] = 1/y_hat[y, range(num_inputs)]\n    \n    return d/num_inputs\n\ndef mean_squared(y, y_hat):\n    return  np.sum((y - y_hat)**2 ).squeeze() / (y_hat.shape[1]*2)\n\ndef d_mean_squared(y, y_hat):\n    return (y_hat - y)\n\n\ncost_functions = {\"cross_entropy_sigmoid\" : (cross_entropy_sigmoid, cross_entropy_sigmoid_derivative),\n                 \"cross_entropy_softmax\" : (cross_entropy_softmax, cross_entropy_softmax_derivative),\n                  \"mean_squared\" : (mean_squared, d_mean_squared)\n                 }", "meta": {"hexsha": "199154735b0895899195dd855e3076a415f8e638", "size": 1803, "ext": "py", "lang": "Python", "max_stars_repo_path": "cost_functions.py", "max_stars_repo_name": "barisesmer/Backprop-in-Numpy", "max_stars_repo_head_hexsha": "a40c53ea3277e4e6ea5dc32770daf7f5b6dc06c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-04-08T15:52:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-23T09:39:22.000Z", "max_issues_repo_path": "cost_functions.py", "max_issues_repo_name": "barisesmer/Backprop-in-Numpy", "max_issues_repo_head_hexsha": "a40c53ea3277e4e6ea5dc32770daf7f5b6dc06c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cost_functions.py", "max_forks_repo_name": "barisesmer/Backprop-in-Numpy", "max_forks_repo_head_hexsha": "a40c53ea3277e4e6ea5dc32770daf7f5b6dc06c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.05, "max_line_length": 102, "alphanum_fraction": 0.618968386, "include": true, "reason": "import numpy", "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.90192067455231, "lm_q1q2_score": 0.8677447086263241}}
{"text": "import numpy as np\n\ndef solver(eps, Nx, method='centered'):\n    \"\"\"\n    Solver for the two point boundary value problem u'=eps*u'',\n    u(0)=0, u(1)=1.\n    \"\"\"\n    x = np.linspace(0, 1, Nx+1)       # Mesh points in space\n    # Make sure dx and dt are compatible with x and t\n    dx = x[1] - x[0]\n    u   = np.zeros(Nx+1)\n\n    # Representation of sparse matrix and right-hand side\n    diagonal = np.zeros(Nx+1)\n    lower    = np.zeros(Nx)\n    upper    = np.zeros(Nx)\n    b        = np.zeros(Nx+1)\n\n    # Precompute sparse matrix (scipy format)\n    if method == 'centered':\n        diagonal[:] = 2*eps/dx**2\n        lower[:] = -1/dx - eps/dx**2\n        upper[:] =  1/dx - eps/dx**2\n    elif method == 'upwind':\n        diagonal[:] = 1/dx + 2*eps/dx**2\n        lower[:] =  1/dx - eps/dx**2\n        upper[:] = - eps/dx**2\n\n    # Insert boundary conditions\n    upper[0] = 0\n    lower[-1] = 0\n    diagonal[0] = diagonal[-1] = 1\n    b[-1] = 1.0\n\n    # Set up sparse matrix and solve\n    diags = [0, -1, 1]\n    import scipy.sparse\n    import scipy.sparse.linalg\n    A = scipy.sparse.diags(\n        diagonals=[diagonal, lower, upper],\n        offsets=[0, -1, 1], shape=(Nx+1, Nx+1),\n        format='csr')\n    u[:] = scipy.sparse.linalg.spsolve(A, b)\n    return u, x\n\ndef u_exact(x, eps):\n    return (np.exp(x/eps)-1)/(np.exp(1.0/eps)-1)\n\ndef demo(eps = 0.01, method='centered'):\n    import matplotlib.pyplot as plt\n    x_fine = np.linspace(0, 1, 2001)\n    for Nx in (20, 40):\n        u, x = solver(eps, Nx, method=method)\n        plt.figure()\n        plt.plot(x, u, 'o-')\n        plt.hold('on')\n        plt.plot(x_fine, u_exact(x_fine, eps), 'k--')\n        plt.legend(['$N_x=%d$' % Nx, 'exact'], loc='upper left')\n        plt.title(method + ' difference scheme, ' + r'$\\epsilon=%g$' % eps)\n        plt.xlabel('x');  plt.ylabel('u')\n        stem = 'tmp1_%s_%d_%s' % (method, Nx, str(eps).replace('.','_'))\n        plt.savefig(stem + '.png'); plt.savefig(stem + '.pdf')\n    plt.show()\n\nif __name__ == '__main__':\n    demo(eps=0.1, method='upwind')\n    demo(eps=0.01, method='upwind')\n    #demo(eps=0.1, method='centered')\n    #demo(eps=0.01, mehtod='centered')\n", "meta": {"hexsha": "27aef156d583488ca400a538587f2fab64d2bd63", "size": 2150, "ext": "py", "lang": "Python", "max_stars_repo_path": "fdm-devito-notebooks/04_advec/src-advec/twopt_BVP.py", "max_stars_repo_name": "devitocodes/devito_book", "max_stars_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-07-17T13:19:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-27T05:21:09.000Z", "max_issues_repo_path": "fdm-jupyter-book/notebooks/04_advec/src-advec/twopt_BVP.py", "max_issues_repo_name": "devitocodes/devito_book", "max_issues_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 73, "max_issues_repo_issues_event_min_datetime": "2020-07-14T15:38:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-25T11:54:59.000Z", "max_forks_repo_path": "fdm-jupyter-book/notebooks/04_advec/src-advec/twopt_BVP.py", "max_forks_repo_name": "devitocodes/devito_book", "max_forks_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-27T05:21:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T05:21:14.000Z", "avg_line_length": 30.7142857143, "max_line_length": 75, "alphanum_fraction": 0.5423255814, "include": true, "reason": "import numpy,import scipy", "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458251637412, "lm_q2_score": 0.9324533097989076, "lm_q1q2_score": 0.8676088763690097}}
{"text": "# lagrange interpolation example\n\nimport math\nimport numpy\nimport pylab\n\n# globals to control some behavior\nfunc_type = \"tanh\"   # can be sine or tanh\npoints = \"fixed\"  # can be variable or fixed\n\nnpts = 15\n\ndef fun_exact(x):\n    \"\"\" the exact function that we sample to get the points to\n    interpolate through \"\"\"\n\n    if func_type == \"sine\":\n        return numpy.sin(x)\n    elif func_type == \"tanh\":\n        return 0.5*(1.0+numpy.tanh((x-1.0)/0.1))\n\n\ndef get_interp_points(N, xmin, xmax):\n    \"\"\" get the x points that we interpolate at \"\"\"\n    if points == \"fixed\":\n        x = numpy.linspace(xmin, xmax, N)\n\n    elif points == \"variable\":\n        # the Chebyshev nodes\n        x = 0.5*(xmin + xmax) + \\\n            0.5*(xmax - xmin)*numpy.cos(2.0*numpy.arange(N)*math.pi/(2*N))\n\n    return x\n    \n    \ndef lagrange_poly(x, xp, fp):\n    \"\"\" given points (xp, fp), fit a lagrange polynomial and return\n        the value at point x \"\"\"\n\n    f = 0.0\n    \n    # sum over points\n    m = 0\n    while (m < len(xp)):\n\n        # create the Lagrange basis polynomial for point m        \n        l = None\n\n        n = 0\n        while (n < len(xp)):\n            if n == m:\n                n += 1\n                continue\n\n            if l == None:\n                l = (x - xp[n])/(xp[m] - xp[n])\n            else:\n                l *= (x - xp[n])/(xp[m] - xp[n])\n\n            n += 1\n\n        \n        f += fp[m]*l\n\n        m += 1\n\n    return f\n\n\nif func_type == \"sine\":\n    xmin = 0.0\n    xmax = 2.0*math.pi\nelif func_type == \"tanh\":\n    xmin = 0.0\n    xmax = 2.0\n\n\n\n\n# xp, fp are the points that we build the interpolant from\nxp = get_interp_points(npts, xmin, xmax)\nfp = fun_exact(xp)\n\n\n# xx are the finely grided data that we will interpolate at to get\n# the interpolated function values ff\nxx = numpy.linspace(xmin, xmax, 200)\nff = numpy.zeros(len(xx))\n\nn = 0\nwhile (n < len(xx)):\n    ff[n] = lagrange_poly(xx[n], xp, fp)\n    n += 1\n\n\n# exact function values at the interpolated points\nfexact = fun_exact(xx)\n\n\n# error\ne = fexact-ff\n\n\npylab.subplot(211)\n\npylab.scatter(xp, fp, marker=\"x\", color=\"r\", s=30)\npylab.plot(xx, ff, color=\"k\")\n\npylab.plot(xx, fexact, color=\"0.5\")\n\npylab.xlim(xmin, xmax)\n\n\npylab.subplot(212)\n\npylab.plot(xx, e)\n\npylab.xlim(xmin, xmax)\n\n\npylab.savefig(\"lagrange.png\")\n\n", "meta": {"hexsha": "7cecff418c883d769979f04a544e9f36292275e0", "size": 2291, "ext": "py", "lang": "Python", "max_stars_repo_path": "others/interpolation_root-finding/lagrange.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "others/interpolation_root-finding/lagrange.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/interpolation_root-finding/lagrange.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 18.6260162602, "max_line_length": 74, "alphanum_fraction": 0.5608904409, "include": true, "reason": "import numpy", "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.9173026573249612, "lm_q1q2_score": 0.8675860170331487}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# @gyleodhis=====gyleodhis@outlook.com=====\nimport numpy as np\n\n# np.__version__ Checks numpy vesion\n# Generate an array of 10 random integers less than 100 \nrand = np.random.RandomState(42)\nx = rand.randint(100, size=10)\nx\n\n\n# Remember that unlike Python lists, NumPy is constrained to arrays that all contain\n# the same type. If types do not match, NumPy will upcast if possible as below:\n\n# In[2]:\n\n\nL=np.array([3.14, 4, 2, 3])\nL\n\n\n# In[3]:\n\n\n##If we want to explicitly set the data type of the resulting array, we can use the dtype keyword:\nL=np.array([1, 2, 3, 4], dtype='float32')\nL\n\n\n# Accesiing four different elemets in a array\n\n# In[4]:\n\n\nk=[x[2], x[5], x[9], x[0]]\nk\n#We can also do it this way\nz=[2,5,9,1]\nx[z]\n\n\n# In[5]:\n\n\n#Multidimentional Array.\nL=np.array([range(i, i + 3) for i in [2, 4, 6]])\nL\n\n\n# In[6]:\n\n\n# Create a length-10 integer array filled with zeros\nL=np.zeros(10, dtype=int)\nL\n\n\n# In[7]:\n\n\n# Create a 3x5 floating-point array filled with 1s\nL=np.ones((3, 5), dtype=float)\nL\n\n\n# In[8]:\n\n\n# Create a 3x5 array filled with 3.14\nL=np.full((3, 5), 3.14)\nL\n\n\n# In[9]:\n\n\n# Create an array filled with a linear sequence\n# Starting at 0, ending at 20, stepping by 2\n# (this is similar to the built-in range() function)\nL=np.arange(0, 20, 2)\nL\n\n\n# In[10]:\n\n\n# Create an array of five values evenly spaced between 0 and 1\nnp.linspace(0, 1, 5)\n\n\n# In[11]:\n\n\n# Create a 3x3 array of uniformly distributed\n# random values between 0 and 1\nL=np.random.random((3, 3))\nL\n\n\n# In[12]:\n\n\n# Create a 3x3 array of normally distributed random values\n# with mean 0 and standard deviation 1\nnp.random.normal(0, 1, (3, 3))\n\n\n# In[13]:\n\n\n# Create a 3x3 array of random integers in the interval [0, 10)\nnp.random.randint(0, 10, (3, 3))\n\n\n# In[14]:\n\n\n# Create a 3x3 identity matrix\nnp.eye(3)\n\n\n# In[15]:\n\n\n# Create an uninitialized array of three integers\n# The values will be whatever happens to already exist at that\n# memory location\nnp.empty(3)\n\n\n# In[16]:\n\n\nx1 = np.random.randint(10, size=6) # One-dimensional array\nx2 = np.random.randint(10, size=(3, 4)) # Two-dimensional array\nx3 = np.random.randint(10, size=(3, 4, 5)) # Three-dimensional array\n#Each array has attributes ndim (the number of dimensions), shape (the size of each dimension), and size (the total size of the array):\nprint(\"x3 ndim: \", x3.ndim)\nprint(\"x3 shape:\", x3.shape)\nprint(\"x3 size: \", x3.size)\nprint(\"x3 type: \", x3.dtype)\nprint(\"x3 type: \", x3.itemsize)\n\n\n# In[17]:\n\n\n# Array Indexing: Accessing Single Elements\nprint(x1[4])\n# To index from the end of the array, you can use negative indices:\nprint(x1[-1])\n\n\n# In[18]:\n\n\n# In a multidimensional array, you access items using a comma-separated tuple of indices:\nx2[2, 0]\n\n\n# In[19]:\n\n\n# You can also modify values using any of the above index notation:\nx2[0, 0] = 12\nx2[0,0]\n\n\n# ## Keep in mind that, unlike Python lists, NumPy arrays have a fixed type. This means,for example, that if you attempt to insert a floating-point value to an integer array, the value will be silently truncated. Don’t be caught unaware by this behavior!\n# x1[0] = 3.14159 # this will be truncated to 3!\n\n# Fancy indexing also works in multiple dimensions. Consider the following array:\n\n# In[20]:\n\n\nx = np.arange(12).reshape((3,4))\nx\n\n\n# Like with standard indexing, the first index refers to the row, and the second to the\n# column:\n\n# In[21]:\n\n\nrow = np.array([0, 1, 2])\ncol = np.array([2, 1, 3])\nx[row, col]\n\n\n# Selecting Random Points.\n\n# In[22]:\n\n\nmean = [0,0]\ncov = [[1,2], [2,5]]\nx = rand.multivariate_normal(mean, cov, 100)\nx.shape\n\n\n# we can visualize these points as a scatter plot\n\n# In[23]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport matplotlib.pyplot as plt\n#import seaborn; seaborn.set() #for plot styling\nplt.scatter(x[:,0], x[:,1]);\n\n\n# Let’s use fancy indexing to select 20 random points. We’ll do this by first choosing 20\n# random indices with no repeats, and use these indices to select a portion of the origi‐\n# nal array:\n\n# In[24]:\n\n\nindices = np.random.choice(x.shape[0], 20, replace=False)\nindices\n\n\n# In[25]:\n\n\nselection = x[indices] # Fancy indexing here\nselection.shape\n\n\n# Now to see which points were selected, let’s over-plot large circles at the locations of\n# the selected points \n\n# In[26]:\n\n\nplt.scatter(x[:, 0], x[:, 1], alpha=0.3)\nplt.scatter(selection[:, 0], selection[:, 1],\n            facecolor='none', s=200);\n\n\n# This sort of strategy is often used to quickly partition datasets, as is often needed in\n# train/test splitting for validation of statistical models\n\n# Modifying Values with Fancy Indexing. Just as fancy indexing can be used to access parts of an array, it can also be used to\n# modify parts of an array\n\n# In[27]:\n\n\nx = np.arange(10)\ni = np.array([2, 1, 8, 4])\nx[i] = 99\nx\n\n\n# In[28]:\n\n\ni\n\n\n# We can use any assignment-type operator for this. For example:\n\n# In[29]:\n\n\nx[i] +=20\nx\n\n\n# imagine we have 1,000 values and would like to quickly find where they fall within an array of bins. We could compute it using ufunc.at like this:\n\n# In[30]:\n\n\nnp.random.seed(42)\nx=np.random.randn(100)\n#compute a histogram by hand\nbins = np.linspace(-5,5,20)\ncounts= np.zeros_like(bins)\n# find the appropriate bin for each x\ni=np.searchsorted(bins,x)\n# add 1 to each of these bins\nnp.add.at(counts, i, 1)\n#The counts now reflect the number of points within each bin—in other words, a histogram \n#plt.plot(bins, counts, linestyle='steps');\nplt.hist(x, bins, histtype='step');\n\n\n# Fast sorting pf arrays with np.sort and np.argsort. To return a sorted version of the array without modifying the input, you can use\n# np.sort:\n\n# In[31]:\n\n\nx = np.array([2, 1, 4, 3, 5])\nnp.sort(x) #x.sort() produces the same result.\n\n\n#  argsort,returns the indices of the sorted elements:\n\n# In[32]:\n\n\nx = np.array([2, 1, 4, 3, 5])\nx.argsort()\n\n\n# Sorting along rows or columns\n\n# In[33]:\n\n\nrand = np.random.RandomState(42)\nx = rand.randint(0, 10, (4, 6))\nx\n\n\n# In[34]:\n\n\n# sort each column of X. Replace axix=0 with 1 to sort rows\nnp.sort(x, axis=0)\n\n\n# Sometimes we’re not interested in sorting the entire array, but simply want to find the\n# K smallest values in the array.\n\n# In[35]:\n\n\nx = np.array([7, 2, 3, 1, 6, 5, 4])\nnp.partition(x,4)\n\n\n# Similarly to sorting, we can partition along an arbitrary axis of a multidimensional\n# array:\n\n# In[36]:\n\n\nnp.partition(x, 2, axis=0)\n\n\n# The result is an array where the first two slots in each row contain the smallest values\n# from that row, with the remaining values filling the remaining slots.\n\n# Example: k-Nearest Neighbors. We will start by creating random set of 10 points on a 2 dimentional plane.\n\n# In[37]:\n\n\nx= rand.rand(10, 2)\nx\n\n\n# In[38]:\n\n\nplt.scatter(x[:,0], x[:,1], s=100)\n\n\n# Now we will compute the distance between each pair of points\n\n# In[39]:\n\n\ndist_sq = np.sum((x[:,np.newaxis,:] - x[np.newaxis,:,:]) ** 2, axis=-1)\ndist_sq\n\n\n# In[40]:\n\n\nplt.scatter(x[:, 0], x[:, 1], s=100)\n# draw lines from each point to its two nearest neighbors\nK = 2\nnearest_partition = np.argpartition(dist_sq, K + 1, axis=1)\nfor i in range (x.shape[0]):\n    for j in nearest_partition[i, :k+1]:\n        # plot a line from X[i] to X[j]\n        # use some zip magic to make it happen:\n        plt.plot(*zip(X[j], X[i]), color='black')\n\n\n# The above cell is supposed to draw connections between the dots. Some how it has refused to do this.\n\n# Structured Arrays.Imagine that we have several categories of data on a number of people (say, name,\n# age, and weight). We can create a structured array using a compound data type specification:\n# \n\n# In[41]:\n\n\ndata = np.zeros(4, dtype={'names':('name', 'age', 'weight'),\n                          'formats':('U10', 'i4', 'f8')}) #formats':((np.str_, 10), int, np.float32) does the same.\nprint(data.dtype)\n\n\n# Here 'U10' translates to “Unicode string of maximum length 10,” 'i4' translates to “4-byte (i.e., 32 bit) integer,” and 'f8' translates to “8-byte (i.e., 64 bit) float.” \n\n# In[42]:\n\n\nname = ['Alice', 'Bob', 'Cathy', 'Doug']\nage = [25, 45, 37, 19]\nweight = [55.0, 85.5, 68.0, 61.5]\ndata['name'] = name\ndata['age'] = age\ndata['weight'] = weight\nprint(data)\n\n\n# In[43]:\n\n\ndata[1] #remember array indexes are not quoted.\n\n\n# Using Boolean masking, this even allows you to do some more sophisticated opera‐\n# tions such as filtering on age:\n\n# In[44]:\n\n\n# Get names where age is under 30\ndata[data['age'] < 30]['name']\n\n\n# ## Array Slicing: Accessing Subarrays\n\n# In[45]:\n\n\nx = np.arange(20)\nprint(x[:5]) # first five elements\nprint(x[4:7]) # middle subarray\nprint(x[::2]) # Every other element in additions of 2\nprint(x[3::2]) # Every other element begining with 3 in additions of 2\n\n\n# ## Multidimensional subarrays\n\n# In[46]:\n\n\nprint(x2[:2, :3]) # two rows, three columns\nprint(x2[:3, ::2]) # all rows, every column in additions of two\n\n\n# ## Accessing array rows and columns.\n\n# In[47]:\n\n\nprint(x2[:, 0]) # first column of x2\nprint(x2[1,:]) # print second row of x2.\n\n\n# In the case of row access, the empty slice can be omitted for a more compact syntax:\n# print(x2[0]) # equivalent to x2[0, :]\n\n# ## Creating copies of arrays\n\n# In[48]:\n\n\nx2_copy = x2[:2, :2].copy() #the copy command is used.\nx2_copy\n\n\n# ## Reshaping of Arrays\n# The most flexible way of doing this is with the reshape() method. For example, if you want to put the numbers 1 through 9 in a 3×3 grid, you can do the following:\n# grid = np.arange(1, 10).reshape((3, 3))\n# \n# [Note that for this to work, the size of the initial array must match the size of the\n# reshaped array.]\n# Another common reshaping pattern is the conversion of a one-dimensional array into a two-dimensional row or column matrix.\n\n# ## ARRAY CONCATINATION AND SPLITTING\n\n# In[49]:\n\n\n# Look at the following example\nx = np.array([1, 2, 3])\ny = np.array([3, 2, 1])\nnp.concatenate([x, y])\n\n\n# ### When working with arrays of mixed dimensions, it can be clearer to use the np.vstack(vertical stack; the no of columns has to be the same) and np.hstack (horizontal stack; the no of rows has to be the same) functions. Similarly, np.dstack will stack arrays along the third axis:\n\n# In[50]:\n\n\nx = np.array([[1, 2, 3,11,14,56],\n             [4,5,6,33,54,12,]])\ngrid = np.array([[9, 8, 7],\n                 [6, 5, 4]])\ny = np.hstack([x, grid])\ny\n\n\n# ## Splitting of arrays\n# This is implemented by the functions np.split, np.hsplit, and np.vsplit\n\n# In[51]:\n\n\nx = [1, 2, 3, 99, 99, 3, 2, 1]\nx1, x2, x3 = np.split(x, [3, 5])\nprint(x1, x2, x3)\n\n\n# ### Notice that N split points lead to N + 1 subarrays. \n# The related functions np.hsplit and np.vsplit are similar:\n# Similarly, np.dsplit will split arrays along the third axis.\n\n# In[52]:\n\n\ngrid = np.arange(16).reshape((4, 4))\nupper, lower = np.vsplit(grid, [2]) # Splits the array into two. (hsplit splits horizontally)\nprint(upper)\nprint(lower)\n\n\n# ## Absolute value\n# Just as NumPy understands Python’s built-in arithmetic operators, it also understands Python’s built-in absolute value function:\n\n# In[59]:\n\n\nx = np.array([-2, -1, 0, 1, 2])\nabs(x)\n\n\n# In[60]:\n\n\n# This ufunc can also handle complex data, in which the absolute value returns the magnitude:\nx = np.array([3 - 4j, 4 - 3j, 2 + 0j, 0 + 1j])\nabs(x)\n\n\n# ## Trigonometric functions\n# NumPy provides a large number of useful ufuncs, and some of the most useful for the\n# data scientist are the trigonometric functions. We’ll start by defining an array of\n# angles:\n\n# In[62]:\n\n\ntheta = np.linspace(0, np.pi, 3)\n# Now we can compute some trigonometric functions on these values:\nprint(\"theta = \", theta)\nprint(\"sin(theta) = \", np.sin(theta))\nprint(\"cos(theta) = \", np.cos(theta))\nprint(\"tan(theta) = \", np.tan(theta))\n\n\n# In[64]:\n\n\n# Another common type of operation available in a NumPy ufunc are the exponentials:\nx = [1, 2, 3]\nprint(\"x =\", x)\nprint(\"e^x =\", np.exp(x))\nprint(\"2^x =\", np.exp2(x))\nprint(\"3^x =\", np.power(3, x))\nprint(\"ln(x) =\", np.log(x))\nprint(\"log2(x) =\", np.log2(x))\nprint(\"log10(x) =\", np.log10(x))\n\n\n# ### The Reduce Operation\n# A reduce repeatedly applies a given operation to the elements of an array until only a single result remains.\n# For example, calling reduce on the add ufunc returns the sum of all elements in thet array:\n\n# In[65]:\n\n\nx = np.arange(1, 6)\nnp.add.reduce(x)\n\n\n# In[67]:\n\n\n#np.multiply.reduce(x) # returns a product of all array elements:\nnp.add.accumulate(x) # returns x together with the final value of addition\n\n\n# ## Summing the Values in an Array\n# \n\n# In[68]:\n\n\nL = np.random.random(100)\nsum(L) #np.sum(L) returns the same result but it is however faster.\n\n\n# ## Minimum and Maximum\n\n# In[72]:\n\n\nprint(min(L))\nprint(max(L))\n#np.min(K) and np.max(K) generate same results though much more faster\n\n\n# ## Aggregation\n# For example, we can find the minimum value within each column in a two dimentional array by specifying axis=0:\n\n# In[74]:\n\n\nM = np.random.random((3, 4))\nprint(M.min(axis=0)) #returns minimum value per column(.max returns maximum value)\nprint(M.min(axis=0)) #returns minimum value per row.(.max returns maximum value)\n\n\n# ### Other Usefull aggregation functions\n# \t\tprint(\"25th percentile: \", np.percentile(heights, 25)) #heights is an array.\n# \t\tprint(\"Median: \", np.median(heights))\n# \t\tprint(\"75th percentile: \", np.percentile(heights, 75))\n\n# ## ARRAY COMPUTATIONS\n# ### Broadcasting: A set of rules for applying binary ufuncs on arrays of different sizes.Example:\n\n# In[78]:\n\n\na = np.array([0, 1, 2])\nM = np.ones((3, 3))\nM + a\n\n\n# Note that while we’ve been focusing on the + operator here, these broadcasting rules apply to any binary ufunc.\n", "meta": {"hexsha": "0d52c155e2125525f0fa893b31ad7f0083055d0b", "size": 13562, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numpy/NumpyCheatSheet (V 0.0.1).py", "max_stars_repo_name": "gyleodhis/My-Data-Science-Devops", "max_stars_repo_head_hexsha": "42602ae2fe291566a5cabe40c04f6554edab255d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numpy/NumpyCheatSheet (V 0.0.1).py", "max_issues_repo_name": "gyleodhis/My-Data-Science-Devops", "max_issues_repo_head_hexsha": "42602ae2fe291566a5cabe40c04f6554edab255d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numpy/NumpyCheatSheet (V 0.0.1).py", "max_forks_repo_name": "gyleodhis/My-Data-Science-Devops", "max_forks_repo_head_hexsha": "42602ae2fe291566a5cabe40c04f6554edab255d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8967642527, "max_line_length": 284, "alphanum_fraction": 0.67453178, "include": true, "reason": "import numpy", "num_tokens": 4051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.9294404043013231, "lm_q1q2_score": 0.8675683086693858}}
{"text": "\"\"\"\nComputes equilibrium price and quantities.\n\"\"\"\nfrom numpy import exp\n\n## Parameters\na = 1\nb = 0.1\nepsilon = 1\n\ndef supply(price):\n   return exp(b*price) - 1\n\ndef demand(price):\n   return a*(price**(-epsilon))\n\nmxiter = 30\ntoler = 1.0e-6\n\nplow = 0.1\nphigh = 10.0\n\nniter = mxiter\n\nfor i in range(mxiter):\n\n    pcur = (plow + phigh)/2\n    yd = demand(pcur)\n    ys = supply(pcur)\n    excesssupply = ys - yd\n\n    if excesssupply > 0:\n        phigh = pcur\n    else:\n        plow = pcur\n\n    diff = abs(phigh - plow)\n\n    if diff <= toler:\n        niter = i\n        break\n\npclear = (plow + phigh)/2\nyd = demand(pcur)\nys = supply(pcur)\nexcesssupply = ys - yd\n\nprint(niter, pclear, yd, ys, excesssupply)\n", "meta": {"hexsha": "288c0b87e74e5f8962cc087a8eb1ea12b4f887a9", "size": 699, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "jstac/yale_class_2016", "max_stars_repo_head_hexsha": "c8258676013baac9f50707d797af0602a3788975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-25T06:00:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-25T06:00:11.000Z", "max_issues_repo_path": "main.py", "max_issues_repo_name": "jstac/yale_class_2016", "max_issues_repo_head_hexsha": "c8258676013baac9f50707d797af0602a3788975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "jstac/yale_class_2016", "max_forks_repo_head_hexsha": "c8258676013baac9f50707d797af0602a3788975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-12-28T07:44:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-29T06:28:37.000Z", "avg_line_length": 14.2653061224, "max_line_length": 42, "alphanum_fraction": 0.5951359084, "include": true, "reason": "from numpy", "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104943498961, "lm_q2_score": 0.8976952886860978, "lm_q1q2_score": 0.8675421477147045}}
{"text": "import numpy as np\r\nimport math\r\n\r\nclass LogisticRegression:\r\n\r\n\t\"\"\" Fits a logistic regression model to binary classification data\r\n\r\n\tArgs:\r\n\t\tuse_bias: bool\r\n\t\t\tA flag to enable or disable a bias term in the regression\r\n\t\"\"\"\r\n\r\n\tdef __init__(self, use_bias: bool=True):\r\n\t\tself.use_bias = use_bias\r\n\t\tself.weights = None\r\n\r\n\tdef augment_matrix(self, X: np.ndarray) -> np.ndarray:\r\n\t\t\"\"\" Augment a matrix with a dummy feature to include a bias term in the regression\r\n\r\n\t\tParameters\r\n\t\t----------\r\n\t\tX: np.ndarray\r\n\t\t\tnumpy array corresponding to the feature matrix. Each row is a data point\r\n\t\t\teach column is a feature/variable\r\n\t\t\"\"\"\r\n\r\n\t\t# create a matrix full of 1's with one more column than X\r\n\t\taugmented_X = np.full((X.shape[0], X.shape[1] + 1), 1.0)\r\n\t\t# copy X over the first N column of the new matrix, preserving the last 1's column\r\n\t\taugmented_X[:, :-1] = X\r\n\r\n\t\treturn augmented_X\r\n\r\n\tdef fit(self, X: np.ndarray, y: np.ndarray):\r\n\t\t\"\"\"Will fit a logistic regression model on an input matrix X and\r\n\t\ta target vector y\r\n\r\n\t\tParameters\r\n\t\t----------\r\n\t\tX: np.ndarray\r\n\t\t\tnumpy array corresponding to the feature matrix. Each row is a data point\r\n\t\t\teach column is a feature/variable\r\n\t\ty: np.ndarray\r\n\t\t\tnumpy array corresponding to the 1D target vector\r\n\t\t\"\"\"\r\n\r\n\t\tif self.use_bias:\r\n\t\t\tX = self.augment_matrix(X)\r\n\r\n\t\t# create a vector of 0's of the same size as the target\r\n\t\t# will be used to convert True/False classification into\r\n\t\t# a numerical target for OLS\r\n\t\ty_inverted = np.zeros(y.shape[0])\r\n\r\n\t\t# True/False values are converted to 1 and 0\r\n\t\t# Next, the 1/0 values are converted to 0.9 and 0.1 (see label smoothing for more info)\r\n\t\t# Then, 0.9 and 0.1 are passed through the inverse sigmoid function to obtain a numerical\r\n\t\t# target for OLS linear regression\r\n\t\ttrue_value = math.log(0.9 / (1 - 0.9))\r\n\t\tfalse_value = math.log(0.1 / (1 - 0.1))\r\n\r\n\t\t# set true labels to true value\r\n\t\ty_inverted[y == True] = true_value\r\n\t\t# set false labels to false value\r\n\t\ty_inverted[y == False] = false_value\r\n\r\n\t\t# compute matrices for OLS regression\r\n\t\tgram_matrix = np.matmul(X.transpose(), X)\r\n\t\tmoment_matrix = np.matmul(X.transpose(), y_inverted)\r\n\r\n\t\t# compute weights of linear model\r\n\t\tself.weights = np.matmul(np.linalg.inv(gram_matrix), moment_matrix)\r\n\r\n\t\treturn self\r\n\r\n\r\n\tdef predict(self, X: np.ndarray) -> np.ndarray:\r\n\t\t\"\"\" Classify a matrix using the trained Logistic model\r\n\r\n\t\tParameters\r\n\t\t----------\r\n\t\tX: np.ndarray\r\n\t\t\tnumpy array corresponding to the feature matrix. Each row is a data point\r\n\t\t\teach column is a feature/variable\r\n\r\n\t\tReturns\r\n\t\t----------\r\n\t\tpredictions: np.ndarray\r\n\t\t\ta numpy array corresponding to the prediction vector\r\n\t\t\"\"\"\r\n\r\n\t\tif self.use_bias:\r\n\t\t\tX = self.augment_matrix(X)\r\n\r\n\t\traw_predictions = np.matmul(X, self.weights)\r\n\r\n\t\t# use logistic equation to get true/false score\r\n\t\treturn 1.0 / (1.0 + np.exp(-raw_predictions))", "meta": {"hexsha": "43dea4287ee6b34194b0062505fe91e90662310c", "size": 2900, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/model_module/simple_model.py", "max_stars_repo_name": "Philliams/ml_template", "max_stars_repo_head_hexsha": "cb2616d5ca145fc3b3e8ec15f6eb4d2cd99778d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/model_module/simple_model.py", "max_issues_repo_name": "Philliams/ml_template", "max_issues_repo_head_hexsha": "cb2616d5ca145fc3b3e8ec15f6eb4d2cd99778d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/model_module/simple_model.py", "max_forks_repo_name": "Philliams/ml_template", "max_forks_repo_head_hexsha": "cb2616d5ca145fc3b3e8ec15f6eb4d2cd99778d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5918367347, "max_line_length": 92, "alphanum_fraction": 0.6765517241, "include": true, "reason": "import numpy", "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.974434783107032, "lm_q2_score": 0.8902942232112239, "lm_q1q2_score": 0.8675336582962725}}
{"text": "import numpy as np \n  \ndef estimate_coef(x, y): \n    # number of observations/points \n    n = np.size(x) \n  \n    # mean of x and y vector \n    m_x, m_y = np.mean(x), np.mean(y)\n  \n    # calculating cross-deviation and deviation about x\n    SS_xy = np.sum(y*x) - n*m_y*m_x \n    SS_xx = np.sum(x*x) - n*m_x*m_x \n  \n    # calculating regression coefficients \n    b_1 = SS_xy / SS_xx \n    b_0 = m_y - b_1*m_x \n  \n    return(b_0, b_1) \n  \n \nif __name__ == \"__main__\": \n    # observations \n    x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) \n    y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12]) \n  \n    # estimating coefficients \n    b = estimate_coef(x, y) \n    print(\"Estimated coefficients in Python:\\n b_0 = {} \\n b_1 = {}\".format(b[0], b[1])) \n", "meta": {"hexsha": "39d25ac1d35baba5bbb81ab8f2fda82cb7e9c961", "size": 739, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/linear_regression.py", "max_stars_repo_name": "carlosal1015/pybr2019", "max_stars_repo_head_hexsha": "fa61c3e33b0acdb8ea88449590b137a4c7d908fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-10-26T18:06:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T02:39:26.000Z", "max_issues_repo_path": "code/linear_regression.py", "max_issues_repo_name": "carlosal1015/pybr2019", "max_issues_repo_head_hexsha": "fa61c3e33b0acdb8ea88449590b137a4c7d908fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/linear_regression.py", "max_forks_repo_name": "carlosal1015/pybr2019", "max_forks_repo_head_hexsha": "fa61c3e33b0acdb8ea88449590b137a4c7d908fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-06T02:39:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-06T02:39:30.000Z", "avg_line_length": 25.4827586207, "max_line_length": 89, "alphanum_fraction": 0.5588633288, "include": true, "reason": "import numpy", "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290963960277, "lm_q2_score": 0.8933094145755219, "lm_q1q2_score": 0.8675187645787912}}
{"text": "import numpy as np\nfrom numpy.fft import fft\n\n# Steve and Rosie's Radix-2 Decimation In Time (DIT) algorithm\ndef fft_radix2(arr):\n    # assume len(arr) is a power of 2\n    n = arr.shape[0]\n    if n == 1:\n        return arr[0]\n    else:\n        even = fft_radix2(arr[::2]) # this is the FFT of even indices\n        odd = fft_radix2(arr[1::2]) * np.exp(-2*np.pi*1.j / n * np.arange(n/2)) # FFT of odd indices\n        return np.concatenate([even + odd, even - odd])\n\n# Radix-2 DIT with padding\ndef fft_radix2_pad(arr):\n    log2len = np.log2(len(arr)) # first check if len pow 2 \n    zeros = np.zeros(int(2**np.ceil(log2len)) - len(arr))\n    padded_arr = np.concatenate((arr,zeros)) # pad with zeros\n    return fft_radix2(padded_arr)\n\n\n# TESTS\nif __name__ == \"__main__\":\n    x1 = np.array([0,1,2,3,4,5,6,7])\n    x2 = np.array([1,2,3,4,5])\n    x2_pad = np.array([1,2,3,4,5,0,0,0])\n\n    assert (np.round(fft(x1),5) == np.round(fft_radix2(x1),5)).all()\n    assert (np.round(fft(x1),5) == np.round(fft_radix2_pad(x1),5)).all()\n    assert (np.round(fft(x2_pad),5) == np.round(fft_radix2(x2_pad),5)).all()\n    assert (np.round(fft(x2_pad),5) == np.round(fft_radix2_pad(x2),5)).all()\n    print(\"All tests passed\")\n    \n\n", "meta": {"hexsha": "177149a52bfb501b55a40b758ee2239d2828847b", "size": 1209, "ext": "py", "lang": "Python", "max_stars_repo_path": "cooley_tukey.py", "max_stars_repo_name": "dcxSt/dft_algos", "max_stars_repo_head_hexsha": "7e7370c26d0d765bb2550b0e0cee768198532a1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cooley_tukey.py", "max_issues_repo_name": "dcxSt/dft_algos", "max_issues_repo_head_hexsha": "7e7370c26d0d765bb2550b0e0cee768198532a1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cooley_tukey.py", "max_forks_repo_name": "dcxSt/dft_algos", "max_forks_repo_head_hexsha": "7e7370c26d0d765bb2550b0e0cee768198532a1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5833333333, "max_line_length": 100, "alphanum_fraction": 0.617866005, "include": true, "reason": "import numpy,from numpy", "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290955604489, "lm_q2_score": 0.8933093975331752, "lm_q1q2_score": 0.8675187472820419}}
{"text": "import numpy as np\n\n# https://docs.scipy.org/doc/numpy/reference/generated/numpy.eye.html\n\ne = np.eye(4)\nprint(type(e))\nprint(e)\nprint(e.dtype)\n# <class 'numpy.ndarray'>\n# [[ 1.  0.  0.  0.]\n#  [ 0.  1.  0.  0.]\n#  [ 0.  0.  1.  0.]\n#  [ 0.  0.  0.  1.]]\n# float64\n\ne = np.eye(4, M=3, k=1, dtype=np.int8)\nprint(e)\nprint(e.dtype)\n# [[0 1 0]\n#  [0 0 1]\n#  [0 0 0]\n#  [0 0 0]]\n# int8\n\n# https://docs.scipy.org/doc/numpy/reference/generated/numpy.identity.html\n\ni = np.identity(4)\nprint(i)\nprint(i.dtype)\n# [[ 1.  0.  0.  0.]\n#  [ 0.  1.  0.  0.]\n#  [ 0.  0.  1.  0.]\n#  [ 0.  0.  0.  1.]]\n# float64\n\ni = np.identity(4, dtype=np.uint8)\nprint(i)\nprint(i.dtype)\n# [[1 0 0 0]\n#  [0 1 0 0]\n#  [0 0 1 0]\n#  [0 0 0 1]]\n# uint8\n\na = [3, 0, 8, 1, 9]\na_one_hot = np.identity(10)[a]\nprint(a)\nprint(a_one_hot)\n# [3, 0, 8, 1, 9]\n# [[ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]\n#  [ 1.  0.  0.  0.  0.  0.  0.  0.  0.  0.]\n#  [ 0.  0.  0.  0.  0.  0.  0.  0.  1.  0.]\n#  [ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]\n#  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]]\n\na = [2, 2, 0, 1, 0]\na_one_hot = np.identity(3)[a]\nprint(a)\nprint(a_one_hot)\n# [2, 2, 0, 1, 0]\n# [[ 0.  0.  1.]\n#  [ 0.  0.  1.]\n#  [ 1.  0.  0.]\n#  [ 0.  1.  0.]\n#  [ 1.  0.  0.]]\n", "meta": {"hexsha": "5f99676f1a9d44c9c5f82d9c1e5a76f9f77ff930", "size": 1220, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebook/numpy_eye_identity.py", "max_stars_repo_name": "vhn0912/python-snippets", "max_stars_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 174, "max_stars_repo_stars_event_min_datetime": "2018-05-30T21:14:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:59:37.000Z", "max_issues_repo_path": "notebook/numpy_eye_identity.py", "max_issues_repo_name": "vhn0912/python-snippets", "max_issues_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-08-10T03:22:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-12T20:31:17.000Z", "max_forks_repo_path": "notebook/numpy_eye_identity.py", "max_forks_repo_name": "vhn0912/python-snippets", "max_forks_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53, "max_forks_repo_forks_event_min_datetime": "2018-04-27T05:26:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T07:59:37.000Z", "avg_line_length": 18.4848484848, "max_line_length": 74, "alphanum_fraction": 0.4450819672, "include": true, "reason": "import numpy", "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.9343951661947455, "lm_q1q2_score": 0.8675007010443283}}
{"text": "\"\"\"\"\n\n    This program analysis the condition number of Hilbert Matrices.\n    Marina von Steinkirch, spring/2013 (based on Mike Zingale's codes)\n\n\"\"\"\n\n\nimport numpy as npy\nfrom scipy import linalg \nfrom gaussElimination import gaussElim\nfrom createHilbert import createHilbert\nfrom calculatePrecision import calculatePrecision\n\n\n\n\n\ndef main():\n    \n    aCond = []\n    aOlimit = []\n    epsilon = calculatePrecision()\n    \n    \n    for N in range(2,16):     \n        H, x = createHilbert(N)\n    \n        # calculate the error\n        b = npy.dot(H,x)\n        xtilde = gaussElim(H, b) \n        error_calculated = abs(npy.linalg.norm(x - xtilde))\n        \n        # verifies when it reaches O(1)\n        if (error_calculated >= 1.0):\n            aOlimit.append([N, x, xtilde])\n        \n        # calculates the conditional number use the numpy API to get the conditional number\n        cond_npy = npy.linalg.cond(H, p=\"fro\")\n        cond_formal = npy.linalg.norm(npy.dot(abs(H), abs(linalg.inv(H))))\n        cond_comp = (npy.linalg.norm(x -xtilde)/npy.linalg.norm(x))/epsilon\n        m = npy.log10(cond_npy)\n        aCond.append([error_calculated,cond_formal, cond_comp, cond_npy, m])\n\n\n\n    \n    for N in range(2,16): \n        print \"\\n*** Hilbert Matrix N x N =\", N,\"x\",N, \": ***\" \n        print \"Calculated error =\",aCond[N-2][0]\n        print \"Condition number:\\n    Formal definition (cond(A)=|A||A^-1|) =\", aCond[N-2][1] \n        print \"    Calculated with the machine precision =\",  aCond[N-2][2] \n        print \"    From the Numpy API =\", aCond[N-2][3] \n        print \"    Number of digit of accuracy lost in solving Hx=b, giving by log(cond(H)) is \", aCond[N-2][4]\n        \n        \n        \n        \n    print \"\\n\\n\\nThe error for the N x N Hilbert matrix becomes O(1) when N =\", aOlimit[0][0]\n    print \"as we can see when comparing \\nx =\", aOlimit[0][1], \" to \\nxtilde =\", aOlimit[0][2]\n    print \"\\n\\nDone!\"\n\n\nif __name__ == \"__main__\":\n    main()", "meta": {"hexsha": "6936f30efa57c634642549315d7646eadd7afc1b", "size": 1956, "ext": "py", "lang": "Python", "max_stars_repo_path": "homework3_linear_algebra_FFT/condition_number/main.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "homework3_linear_algebra_FFT/condition_number/main.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework3_linear_algebra_FFT/condition_number/main.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 30.0923076923, "max_line_length": 111, "alphanum_fraction": 0.5935582822, "include": true, "reason": "import numpy,from scipy", "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.9343951675649261, "lm_q1q2_score": 0.8675006949128738}}
{"text": "from numpy import random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\n### Defining theta\ntheta = math.pi/4\n\n### Generates count number of random values in the range [0, 1]\ndef getU(count):\n\tu = []\n\tfor i in range(count):\n\t\tkey = random.rand()\n\t\tu.append(key)\n\n\treturn u\n\ndef getX(u):\n\tx = []\n\tfor t in u:\n\t\tres = -theta*(math.log(1-t))\n\t\tx.append(res)\n\t\n\treturn x\n\ndef getSampleMeanVariance(x):\n\tsum = 0.00\n\tfor i in x:\n\t\tsum += i\n\n\tavg = sum/(len(x))\n\n\tcnt = 0.00\n\tfor i in x:\n\t\tcnt += (i-avg)**2\n\n\tvariance = cnt/(len(x)-1)\n\treturn avg, variance\n\ndef plotCDF(data):\n\tdata_size = len(data)\n\n\tdata_set = sorted(set(data))\n\tbins = np.append(data_set, data_set[-1]+1)\n\n\tcounts, bin_edges = np.histogram(data, bins=bins, density=False)\n\n\tcounts = counts.astype(float)/data_size\n\n\tcdf = np.cumsum(counts)\n\n\tplt.plot(bin_edges[0:-1], cdf, linestyle='--', marker='o', color='b')\n\tplt.ylim((0, 1))\n\tplt.ylabel(\"CDF\")\n\tplt.grid(True)\n\n\tplt.show()\n\t\n\n# Plots y = 1 - e^(-x/theta)\ndef plotActualDistributionFunction():\n\ta = -1\n\tb = 1/theta\n\tc = 1\n\tx = np.linspace(0, 10, 256, endpoint = True)\n\ty = (a * np.exp(-b*x)) + c\n\n\tplt.plot(x, y, '-r', label=r'$y =  1 - e^{-x/theta}$')\n\n\taxes = plt.gca()\n\taxes.set_xlim([x.min(), x.max()])\n\taxes.set_ylim([y.min(), y.max()])\n\n\tplt.xlabel('x')\n\tplt.ylabel('y')\n\tplt.title('Actual Distribution')\n\tplt.legend(loc='upper left')\n\n\tplt.show()\n\ndef execute(cnt):\n\tprint(\"For input size of : \" + str(cnt))\n\tu = getU(cnt) \n\tu.sort()\n\t# print(u)\n\tx = getX(u)\n\t# print(x) \n\n\tsMean, sVariance = getSampleMeanVariance(x)\n\t# Actual Mean is theta\n\tprint(\"Sample Mean: \" + str(sMean) + \" \"  + \"Actual Mean: \" + str(theta)) \n\tprint(\"Abs. Difference : \" + str(abs(sMean-theta)))\n\t# Actual Variance is theta^2\n\tprint(\"Sample Variance: \" + str(sVariance) + \" \" + \"Actual Variance: \" + str(theta**2)) \n\tprint(\"Abs. Difference : \" + str(abs(sVariance-theta**2)))\n\tprint()\n\n\tplotCDF(x)\n\ndef main():\n\tplotActualDistributionFunction()\n\n\texecute(10)\n\texecute(100)\n\texecute(1000)\n\texecute(10000)\n\texecute(100000)\n\t# execute(1000000)\n\nif __name__ == '__main__':\n\tmain()\n\n\n\n\n\n\n", "meta": {"hexsha": "19cd3e5eae6993e02dc0701f127d1ef2daa8453e", "size": 2099, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab 02/180123019_Jay_Sabale_q2.py", "max_stars_repo_name": "ElProfesor18/MA-323_Monte_Carlo_Simulation", "max_stars_repo_head_hexsha": "24efd6ba1d50b00100d15ec2ef5d3fc5217f93a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab 02/180123019_Jay_Sabale_q2.py", "max_issues_repo_name": "ElProfesor18/MA-323_Monte_Carlo_Simulation", "max_issues_repo_head_hexsha": "24efd6ba1d50b00100d15ec2ef5d3fc5217f93a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab 02/180123019_Jay_Sabale_q2.py", "max_forks_repo_name": "ElProfesor18/MA-323_Monte_Carlo_Simulation", "max_forks_repo_head_hexsha": "24efd6ba1d50b00100d15ec2ef5d3fc5217f93a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7881355932, "max_line_length": 89, "alphanum_fraction": 0.6288708909, "include": true, "reason": "import numpy,from numpy", "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.9284087965937711, "lm_q1q2_score": 0.8675006917899004}}
{"text": "# # Applying Bayes' theorem to iris classification\n# \n# Can **Bayes' theorem** help us to solve a **classification problem**, namely predicting the species of an iris?\n\n# ## Preparing the data\n# \n# We'll read the iris data into a DataFrame, and **round up** all of the measurements to the next integer:\n\nimport pandas as pd\nimport numpy as np\n\n\n# read the iris data into a DataFrame\nurl = 'http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\ncol_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']\niris = pd.read_csv(url, header=None, names=col_names)\niris.head()\n\n\n# apply the ceiling function to the numeric columns\niris.loc[:, 'sepal_length':'petal_width'] = iris.loc[:, 'sepal_length':'petal_width'].apply(np.ceil)\niris.head()\n\n\n# ## Deciding how to make a prediction\n# \n# Let's say that I have an **out-of-sample iris** with the following measurements: **7, 3, 5, 2**. How might I predict the species?\n\n# show all observations with features: 7, 3, 5, 2\niris[(iris.sepal_length==7) & (iris.sepal_width==3) & (iris.petal_length==5) & (iris.petal_width==2)]\n\n\n# count the species for these observations\niris[(iris.sepal_length==7) & (iris.sepal_width==3) & (iris.petal_length==5) & (iris.petal_width==2)].species.value_counts()\n\n\n# count the species for all observations\niris.species.value_counts()\n\n\n# Let's frame this as a **conditional probability problem**: What is the probability of some particular species, given the measurements 7, 3, 5, and 2?\n# \n# $$P(species \\ | \\ 7352)$$\n# \n# We could calculate the conditional probability for **each of the three species**, and then predict the species with the **highest probability**:\n# \n# $$P(setosa \\ | \\ 7352)$$\n# $$P(versicolor \\ | \\ 7352)$$\n# $$P(virginica \\ | \\ 7352)$$\n\n# ## Calculating the probability of each species\n# \n# **Bayes' theorem** gives us a way to calculate these conditional probabilities.\n# \n# Let's start with **versicolor**:\n# \n# $$P(versicolor \\ | \\ 7352) = \\frac {P(7352 \\ | \\ versicolor) \\times P(versicolor)} {P(7352)}$$\n# \n# We can calculate each of the terms on the right side of the equation:\n# \n# $$P(7352 \\ | \\ versicolor) = \\frac {13} {50} = 0.26$$\n# \n# $$P(versicolor) = \\frac {50} {150} = 0.33$$\n# \n# $$P(7352) = \\frac {17} {150} = 0.11$$\n# \n# Therefore, Bayes' theorem says the **probability of versicolor given these measurements** is:\n# \n# $$P(versicolor \\ | \\ 7352) = \\frac {0.26 \\times 0.33} {0.11} = 0.76$$\n# \n# Let's repeat this process for **virginica** and **setosa**:\n# \n# $$P(virginica \\ | \\ 7352) = \\frac {0.08 \\times 0.33} {0.11} = 0.24$$\n# \n# $$P(setosa \\ | \\ 7352) = \\frac {0 \\times 0.33} {0.11} = 0$$\n# \n# We predict that the iris is a versicolor, since that species had the **highest conditional probability**.\n\n# ## Summary\n# \n# 1. We framed a **classification problem** as three conditional probability problems.\n# 2. We used **Bayes' theorem** to calculate those conditional probabilities.\n# 3. We made a **prediction** by choosing the species with the highest conditional probability.\n\n# ## Bonus: The intuition behind Bayes' theorem\n# \n# Let's make some hypothetical adjustments to the data, to demonstrate how Bayes' theorem makes intuitive sense:\n# \n# Pretend that **more of the existing versicolors had measurements of 7352:**\n# \n# - $P(7352 \\ | \\ versicolor)$ would increase, thus increasing the numerator.\n# - It would make sense that given an iris with measurements of 7352, the probability of it being a versicolor would also increase.\n# \n# Pretend that **most of the existing irises were versicolor:**\n# \n# - $P(versicolor)$ would increase, thus increasing the numerator.\n# - It would make sense that the probability of any iris being a versicolor (regardless of measurements) would also increase.\n# \n# Pretend that **17 of the setosas had measurements of 7352:**\n# \n# - $P(7352)$ would double, thus doubling the denominator.\n# - It would make sense that given an iris with measurements of 7352, the probability of it being a versicolor would be cut in half.\n", "meta": {"hexsha": "d21a4c09f01acbd97057eb6b9849da6cc695798b", "size": 4027, "ext": "py", "lang": "Python", "max_stars_repo_path": "ML/DAT8-master/code/14_bayes_theorem_iris_nb.py", "max_stars_repo_name": "praveenpmin/Python", "max_stars_repo_head_hexsha": "513fcde7430b03a187e2c7e58302b88645388eed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ML/DAT8-master/code/14_bayes_theorem_iris_nb.py", "max_issues_repo_name": "praveenpmin/Python", "max_issues_repo_head_hexsha": "513fcde7430b03a187e2c7e58302b88645388eed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ML/DAT8-master/code/14_bayes_theorem_iris_nb.py", "max_forks_repo_name": "praveenpmin/Python", "max_forks_repo_head_hexsha": "513fcde7430b03a187e2c7e58302b88645388eed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0970873786, "max_line_length": 151, "alphanum_fraction": 0.6948100323, "include": true, "reason": "import numpy", "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611631680358, "lm_q2_score": 0.9032942001955143, "lm_q1q2_score": 0.8674886687827047}}
{"text": "import numpy as np\n\n\ndef minmax(X, low, high, minX=None, maxX=None, dtype=np.float):\n    X = np.asarray(X)\n    if minX is None:\n        minX = np.min(X)\n    if maxX is None:\n        maxX = np.max(X)\n    # normalize to [0...1].    \n    X -= float(minX)\n    X /= float((maxX - minX))\n    # scale to [low...high].\n    X = X * (high - low)\n    X = X + low\n    return np.asarray(X, dtype=dtype)\n\n\ndef zscore(X, mean=None, std=None):\n    \"\"\"\n    Mean Normalization + Feature Scaling\n\n    :param X: ndarray\n    :param mean: mean\n    :param std: std dev\n    :return: normalized ndarry\n    \"\"\"\n    X = np.asarray(X)\n    if mean is None:\n        mean = X.mean()\n    if std is None:\n        std = X.std()\n    X = (X - mean) / std\n    return X\n\n\ndef gaussian(X, mu, sig):\n    return (1/(sig*np.sqrt(2*np.pi)))*\\\n           np.exp(-(X-mu)**2/(2*sig**2))\n\n\ndef inverse_dissim(X):\n    \"\"\"\n\n    :param X: int or np.array\n    :return:\n    \"\"\"\n    X = np.asarray(X)\n    X = zscore(X)\n    X = minmax(X, 0, 10)\n    return 1./(1+X)\n\n\ndef vector_normalize(x):\n    return x / np.linalg.norm(x)\n\n\ndef gaussian_kernel(X, mu=None, sig=None):\n    \"\"\"\n    gaussian kernel.\n    convert distance to similarity by setting mu=0\n    :param X:\n    :param mu:\n    :param sig:\n    :return:\n    \"\"\"\n    X = np.asarray(X)\n    if mu is None:\n        mu = X.mean()\n    if sig is None:\n        sig = X.std()\n\n    return np.exp(-np.power(X-mu, 2)/(2*sig**2))", "meta": {"hexsha": "fe01958e2d017f9b2946c616fc48a97074004009", "size": 1416, "ext": "py", "lang": "Python", "max_stars_repo_path": "facerec_py/facerec/normalization.py", "max_stars_repo_name": "idf/FaceReader", "max_stars_repo_head_hexsha": "d649bf7ca7f9cf66ac99e81a5187cfcc2b54f49d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-04-17T02:12:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-08T01:29:24.000Z", "max_issues_repo_path": "facerec_py/facerec/normalization.py", "max_issues_repo_name": "idf/FaceReader", "max_issues_repo_head_hexsha": "d649bf7ca7f9cf66ac99e81a5187cfcc2b54f49d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "facerec_py/facerec/normalization.py", "max_forks_repo_name": "idf/FaceReader", "max_forks_repo_head_hexsha": "d649bf7ca7f9cf66ac99e81a5187cfcc2b54f49d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-08-26T11:44:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T11:50:11.000Z", "avg_line_length": 19.397260274, "max_line_length": 63, "alphanum_fraction": 0.5282485876, "include": true, "reason": "import numpy", "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992914310605, "lm_q2_score": 0.8962513835254866, "lm_q1q2_score": 0.8674810790584261}}
{"text": "from matplotlib import pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport math\nimport scipy.stats as stats\n\n\ndef con_level(x_bar, sigma, n, sig_level, show=True):\n    \"\"\"\nInput: x_bar (x_mean), sigma (sample sigma), sample size, sig_level (alpha), show=True\nReturn the confidence level at alpha. Return a dictionary: {\"lcl\": lcl, \"ucl\": ucl, \"x_bar\": x_bar, \"t_value\": t_value, \"sig_x_bar\": sig_x_bar}\n\n+ `show`: default is `True`. Set to `False` to disable rendering.\n    \"\"\"\n    a = sig_level\n    df_v = n - 1\n    con_coef = 1 - a\n    t_value = stats.t.ppf(1 - a / 2, df=df_v)\n    sig_x_bar = sigma / math.sqrt(n)\n    lcl = x_bar - t_value * sig_x_bar\n    ucl = x_bar + t_value * sig_x_bar\n    result = f\"\"\"{con_coef * 100:.1f}% Confidence Interval: [{lcl:.4f}, {ucl:.4f}]\nMean: {x_bar:.4f}\nStd. Dev. = {sigma:.4f}\nSample Size: {n}\nt (Critical value): {t_value:.4f}\n    \"\"\"\n    if show:\n        print(result)\n    return {\"lcl\": lcl, \"ucl\": ucl, \"x_bar\": x_bar, \"t_value\": t_value, \"sig_x_bar\": sig_x_bar}\n\n\ndef rejection_region_method(x_mean, mu, std, n, alpha, option='left', precision=4, show=True, ignore=False):\n    \"\"\"\n    Input: x_mean, mu, std, n, alpha, option='left', precision=4, show=True, ignore=False\n    Output: \n        if opt == 't':\n            return x_l, x_u\n        else:\n            return x_c\n    \"\"\"\n    opt = option.lower()[0]\n    df_v = n - 1\n    if opt == 't':\n        option = 'Two-Tail Test'\n        t_value = stats.t.ppf(1 - alpha / 2, df=df_v)\n        x_u = mu + t_value * std / math.sqrt(n)\n        x_l = mu - t_value * std / math.sqrt(n)\n        flag = x_mean < x_l or x_mean > x_u\n        if not ignore:\n            result = f'''======= The Rejection Region Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nt (Critical value) = {t_value:.{precision}f}\n\nUsing {option}:\nx̄ =  {x_mean:.{precision}f}\nx_l (Lower bound for the critical value) = {x_l:.{precision}f}\nx_u (Upper bound for the critical value) = {x_u:.{precision}f}\nReject H_0 → {flag}\n            '''\n        else:\n            result = f'''======= The Rejection Region Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nt (Critical value) = {t_value:.{precision}f}\n\nUsing {option}:\nx_l (Lower bound for the critical value) = {x_l:.{precision}f}\nx_u (Upper bound for the critical value) = {x_u:.{precision}f}\n            '''\n\n    else:\n        if opt == 'l':\n            # left tail\n            option = 'One-Tail Test (left tail)'\n            t_value = stats.t.ppf(alpha, df=df_v)  # negative\n            x_c = mu + t_value * std / math.sqrt(n)\n            flag = x_mean < x_c\n        elif opt == 'r':\n            option = 'One-Tail Test (right tail)'\n            t_value = stats.t.ppf(1 - alpha, df=df_v)\n            x_c = mu + t_value * std / math.sqrt(n)\n            flag = x_mean > x_c\n        if not ignore:\n            result = f'''======= The Rejection Region Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nt (Critical value) = {t_value:.{precision}f}\n\nUsing {option}:\nx̄ =  {x_mean:.{precision}f}\nx_c (Critical value) = {x_c:.{precision}f}\nReject H_0 → {flag}\n            '''\n        else:\n            result = f'''======= The Rejection Region Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nt (Critical value) = {t_value:.{precision}f}\n\nUsing {option}:\nx_c (Critical value) = {x_c:.{precision}f}\n            '''\n\n    if show:\n        print(result)\n\n    if opt == 't':\n        return x_l, x_u\n    else:\n        return x_c\n\n\ndef testing_statistic_method(x_mean, mu, std, n, alpha, option='left', precision=4, ignore=False):\n    \"\"\"\n    Input: x_mean, mu, std (sample std), n, alpha, option='left', precision=4, ignore=False\n    Output: \n        if opt == 't':\n            return t, t_l, t_u\n        else:\n            return t, t_value\n    \"\"\"\n    df_v = n - 1\n    opt = option.lower()[0]\n    t = (x_mean - mu)/(std / math.sqrt(n))\n    if opt == 't':\n        option = 'Two-Tail Test'\n        t_value = stats.t.ppf(1 - alpha / 2, df=df_v)\n        t_u = t_value\n        t_l = -t_value\n        flag = t < t_l or t > t_u\n\n        if not ignore:\n            result = f'''======= Testing Statistic Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nt (Critical value) = {t_value:.{precision}f}\n\nUsing {option}:\nt (Observed value) =  {t:.{precision}f}\nt_l (Lower bound for the critical value) = {t_l:.{precision}f}\nt_u (Upper bound for the critical value) = {t_u:.{precision}f}\nReject H_0 → {flag}\n            '''\n        else:\n            result = f'''======= Testing Statistic Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nt (Critical value) = {t_value:.{precision}f}\n\nUsing {option}:\nt_l (Lower bound for the critical value) = {t_l:.{precision}f}\nt_u (Upper bound for the critical value) = {t_u:.{precision}f}\n            '''\n\n    else:\n        if opt == 'l':\n            # left tail\n            option = 'One-Tail Test (left tail)'\n            t_value = stats.t.ppf(alpha, df=df_v)  # negative\n            flag = t < t_value\n        elif opt == 'r':\n            option = 'One-Tail Test (right tail)'\n            t_value = stats.t.ppf(1 - alpha, df=df_v)\n            flag = t > t_value\n\n        if not ignore:\n            result = f'''======= Testing Statistic Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nt (Critical value) = {t_value:.{precision}f}\n\nUsing {option}:\nt (Observed value) =  {t:.{precision}f}\nt (Critical value) = {t_value:.{precision}f}\nReject H_0 → {flag}\n            '''\n\n        else:\n            result = f'''======= Testing Statistic Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nt (Critical value) = {t_value:.{precision}f}\n\nUsing {option}:\nt (Critical value) = {t_value:.{precision}f}\n            '''\n\n    print(result)\n    if opt == 't':\n        return t, t_l, t_u\n    else:\n        return t, t_value\n\n\ndef inter_p_value(p_value):\n    # interpretation\n    if p_value >= 0 and p_value < 0.01:\n        inter_p = 'Overwhelming Evidence'\n    elif p_value >= 0.01 and p_value < 0.05:\n        inter_p = 'Strong Evidence'\n    elif p_value >= 0.05 and p_value < 0.1:\n        inter_p = 'Weak Evidence'\n    elif p_value >= .1:\n        inter_p = 'No Evidence'\n    return inter_p\n\n\ndef p_value_method(x_mean, h0_mean, std, samp_num, siglevel, option='left', precision=4):\n    \"\"\"\n    Input: x_mean, h0_mean, std (standard deviation of sample), samp_num (sample size), siglevel (alpha), option='left', precision=4):\n    Output: zcv, p_value\n    \"\"\"\n    df_v = samp_num - 1\n    t_value = (x_mean - h0_mean) / (std/(samp_num ** 0.5))\n    alpha = siglevel\n    opt = option.lower()[0]\n    if opt == 't':\n        # two-tail test\n        option = 'Two-Tail Test'\n        p_value = (1 - stats.t.cdf(t_value, df=df_v)) * 2\n        if (p_value > 1):\n            p_value = (stats.t.cdf(t_value, df=df_v)) * 2\n        tcv = stats.t.ppf(1 - siglevel/2, df=df_v)\n        flag = p_value < alpha\n        sub_result = f'''Using {option}:\nDifference = {x_mean - h0_mean}\nt (Critical value) = {-tcv:.{precision}f}, {tcv:.{precision}f}\nt (Observed value) = {t_value:.{precision}f}\np-value = {p_value:.{precision}f} ({inter_p_value(p_value)})\nReject H_0 → {flag}\n        '''\n    else:\n        if opt == 'l':\n            option = 'One-Tail Test (left tail)'\n            p_value = stats.t.cdf(t_value, df=df_v)\n            tcv = stats.t.ppf(siglevel, df=df_v)\n        elif opt == 'r':\n            option = 'One-Tail Test (right tail)'\n            p_value = stats.t.sf(t_value, df=df_v)\n            tcv = stats.t.ppf(1 - siglevel, df=df_v)\n        flag = p_value < alpha\n        sub_result = f'''Using {option}:\nDifference = {x_mean - h0_mean}\nt (Critical value) = {tcv:.{precision}f}\nt (Observed value) = {t_value:.{precision}f}\np-value = {p_value:.{precision}f} ({inter_p_value(p_value)})\nReject H_0 → {flag}\n        '''\n\n    result = f\"\"\"======= p-value Method =======\nMean = {x_mean:.{precision}f}\nNumber of Observation = {samp_num:.{precision}f}\nHypothesized Mean (H0 Mean) = {h0_mean:.{precision}f}\nSample Standard Deviation = {std:.{precision}f}\nSignificant Level (alpha) = {siglevel:.{precision}f}\n\n\"\"\" + sub_result\n\n    print(result)\n\n    return tcv, p_value\n\n\ndef type2_plot(h0_mean, psigma, nsizes, alpha, ranges, option='right', figsize=(12, 6), pf=False, label=True, show=True):\n    \"\"\"\n    Caution: 外面要自己 plt.show()\n\n    Input: h0_mean, psigma, nsizes (list or one value), alpha, ranges, option='right', figsize=(12, 6), pf=False, label=True, show=True\n    → set show to false to only get the values for powers\n    Output: (if pf=True: means, betas, xticks, yticks)\n    \"\"\"\n\n    try:\n        _ = iter(nsizes)\n    except TypeError as te:\n        nsizes = [nsizes]\n\n    opt = option.lower()[0]\n    # options\n\n    means = np.arange(ranges[0], ranges[1], 0.1)\n    betas = np.zeros(means.shape[0])\n    powers = betas.copy()\n    if show:\n        fig, ax = plt.subplots(figsize=figsize)\n\n    for nsize in nsizes:\n        df_v = nsize - 1\n        if opt == 'r':\n            tcv = stats.t.ppf(1 - alpha, df=df_v)\n        elif opt == 'l':\n            tcv = stats.t.ppf(alpha, df=df_v)\n        elif opt == 't':\n            tcv = stats.t.ppf(1 - alpha / 2, df=df_v)\n        means = np.arange(ranges[0], ranges[1], 0.1)\n        betas = np.zeros(means.shape[0])\n        powers = betas.copy()\n        i = 0\n        if opt == 'r':\n            x_c = h0_mean + tcv * psigma / (nsize ** 0.5)\n            for h1_mean in means:\n                t_type2 = (x_c - h1_mean) / (psigma / (nsize ** 0.5))\n                type2_p = stats.t.cdf(t_type2, df=df_v)\n                betas[i] = type2_p\n                powers[i] = 1 - type2_p\n                i += 1\n        elif opt == 'l':\n            x_c = h0_mean + tcv * psigma / (nsize ** 0.5)\n            for h1_mean in means:\n                t_type2 = (x_c - h1_mean) / (psigma / (nsize ** 0.5))\n                type2_p = 1 - stats.t.cdf(t_type2, df=df_v)\n                betas[i] = type2_p\n                powers[i] = 1 - type2_p\n                i += 1\n        elif opt == 't':\n            x_u = h0_mean + tcv * psigma / math.sqrt(nsize)\n            x_l = h0_mean - tcv * psigma / math.sqrt(nsize)\n            # x_l, x_u = rejection_region_method(_, h0_mean, psigma, nsize, alpha, option=opt, precision=4, show=False, ignore=True)\n            for h1_mean in means:\n                t_type2_l = (x_l - h1_mean) / (psigma / (nsize ** 0.5))\n                t_type2_u = (x_u - h1_mean) / (psigma / (nsize ** 0.5))\n                type2_p_l = stats.t.cdf(t_type2_l, df=df_v)\n                type2_p_u = stats.t.cdf(t_type2_u, df=df_v)\n                type2_p = type2_p_u - type2_p_l\n                betas[i] = type2_p\n                powers[i] = 1 - type2_p\n                i += 1\n\n        if show:\n            if pf:\n                plt.plot(means, betas, label=f'OC ({nsize})')\n                plt.plot(means, powers, label=f'PF ({nsize})')\n            else:\n                plt.plot(means, betas, label=f'n = {nsize}')\n\n    if len(ranges) == 3:\n        xticks = np.arange(ranges[0], ranges[1] + 1, ranges[2])\n    else:  # default\n        xticks = np.arange(ranges[0], ranges[1] + 1, 1)\n    yticks = np.arange(0, 1.1, .1)\n\n    if show:\n        plt.xlabel(\"H1 Mean\")\n        plt.xticks(xticks, rotation=45, fontsize=8)\n        plt.yticks(yticks, fontsize=8)\n        plt.ylabel(\"Probability of a Type II Error\")\n        plt.margins(x=.01, tight=False)\n        if label:\n            plt.legend()\n\n    if pf:\n        return means, betas, xticks, yticks\n\n\ndef power_test(x_mean, h0_mean, std, n, alpha, h1_mean, option='left', precision=4, show=True, ignore=True):\n    \"\"\"\n    Input: x_mean (not necessary if ignore=True), h0_mean, std, n, alpha, h1_mean, option='left', precision=4, show=True, ignore=True\n    Output: type2_p (beta), ptest (power of a test)\n    \"\"\"\n    opt = option.lower()[0]\n    df_v = (n - 1)\n    if opt == 't':\n        option = 'Two-Tail Test'\n        x_l, x_u = rejection_region_method(\n            x_mean, h0_mean, std, n, alpha, option=opt, precision=precision, show=show, ignore=ignore)\n        t_value = stats.t.ppf(1 - alpha / 2, df=df_v)\n        t_l = -t_value\n        t_u = t_value\n        t_type2_l = (x_l - h1_mean) / (std / (n ** 0.5))\n        t_type2_u = (x_u - h1_mean) / (std / (n ** 0.5))\n        type2_p_l = stats.t.cdf(t_type2_l, df=df_v)\n        type2_p_u = stats.t.cdf(t_type2_u, df=df_v)\n        type2_p = type2_p_u - type2_p_l\n        ptest = 1 - type2_p\n        result = f'''======= Evaluating Type II Errors ({option}) =======\nμ = {h1_mean}\nt (lower bound) = {t_type2_l:.{precision}f}\nt (upper bound) = {t_type2_u:.{precision}f}\n\nt_l (Lower bound for the critical value) = {t_l:.{precision}f}\nt_u (Upper bound for the critical value) = {t_u:.{precision}f}\n\nx_l (Lower bound for x critical value) = {x_l:.{precision}f}\nx_u (Upper bound for x critical value) = {x_u:.{precision}f}\n\nP(Type II Error) = {type2_p:.{precision}f}\nPower of a Test = {ptest:.{precision}f}\n        '''\n    else:\n        x_c = rejection_region_method(\n            x_mean, h0_mean, std, n, alpha, option=opt, precision=precision, show=show, ignore=ignore)\n#         if x_c > h1_mean:\n#             opt = 'l'\n#         else:\n#             opt = 'r'\n\n        if opt == 'l':\n            option = 'One-Tail Test (left tail)'\n\n            t_c = stats.t.ppf(alpha, df=df_v)\n            t_type2 = (x_c - h1_mean) / (std / (n ** 0.5))\n            type2_p = 1 - stats.t.cdf(t_type2, df=df_v)\n            ptest = 1 - type2_p\n\n        elif opt == 'r':\n            option = 'One-Tail Test (right tail)'\n            t_c = stats.t.ppf(1 - alpha, df=df_v)\n            t_type2 = (x_c - h1_mean) / (std / (n ** 0.5))\n            type2_p = stats.t.cdf(t_type2, df=df_v)\n            ptest = 1 - type2_p\n\n        result = f'''======= Evaluating Type II Errors ({option}) =======\nμ = {h1_mean}\nt = {t_type2:.{precision}f}\n\nt critical value = {t_c:.{precision}f}\nx critical value = {x_c:.{precision}f}\n\nP(Type II Error) = {type2_p:.{precision}f}\nPower of a Test = {ptest:.{precision}f}\n'''\n\n    if show:\n        print(result)\n\n    return type2_p, ptest\n\n\ndef power_plot(h0_mean, psigma, nsizes, alpha, ranges, option='r', figsize=(12, 6), show=True):\n    means, betas, xticks, yticks = type2_plot(\n        h0_mean, psigma, nsizes, alpha, ranges, option=option, figsize=figsize, pf=True, label=True, show=show)\n    if show:\n        plt.clf()\n        plt.plot(means, 1 - betas)\n        plt.xticks(xticks, rotation=45, fontsize=8)\n        plt.yticks(yticks, fontsize=8)\n        plt.title('Power Function Curve')\n        plt.margins(x=.01, tight=False)\n", "meta": {"hexsha": "12dfd9b85fb7b6a5f0dce63eb8c748ef78a9d332", "size": 14601, "ext": "py", "lang": "Python", "max_stars_repo_path": "mgt2001/hyp/t.py", "max_stars_repo_name": "derekdylu/mgt2001", "max_stars_repo_head_hexsha": "b228d5e75e75a2f3f170e35db1bea999b765bec8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-03-01T18:31:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T12:10:22.000Z", "max_issues_repo_path": "mgt2001/hyp/t.py", "max_issues_repo_name": "derekdylu/mgt2001", "max_issues_repo_head_hexsha": "b228d5e75e75a2f3f170e35db1bea999b765bec8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-18T09:30:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-18T09:30:27.000Z", "max_forks_repo_path": "mgt2001/hyp/t.py", "max_forks_repo_name": "derekdylu/mgt2001", "max_forks_repo_head_hexsha": "b228d5e75e75a2f3f170e35db1bea999b765bec8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-11T07:58:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-03T13:49:24.000Z", "avg_line_length": 33.7205542725, "max_line_length": 143, "alphanum_fraction": 0.5569481542, "include": true, "reason": "import numpy,import scipy", "num_tokens": 4480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992932829918, "lm_q2_score": 0.8962513627417531, "lm_q1q2_score": 0.8674810606016612}}
{"text": "# =================================================\n# minso.jeong@daum.net\n# 29. 푸리에 변환 응용\n# Reference : samsjang@naver.com\n# =================================================\nimport numpy as np\nimport cv2 as cv\nimport matplotlib.pyplot as plt\n\n# A. 푸리에 변환으로 이미지 작업하기\ndef fourier_edge():\n\timg = cv.imread('../Images/34.Ji.jpg', cv.IMREAD_GRAYSCALE)\n\n\tf = np.fft.fft2(img)\n\tfshift = np.fft.fftshift(f)\n\n\trows, cols = img.shape\n\tcrow, ccol = int(rows/2), int(cols/2)\n\n\tfshift[crow-30:crow+30, ccol-30:ccol+30] = 0\n\tf_ishift = np.fft.ifftshift(fshift)\n\timg_back = np.fft.ifft2(f_ishift)\n\timg_back = np.abs(img_back)\n\n\tplt.subplot(1, 3, 1), plt.imshow(img, cmap='gray')\n\tplt.title('Original Image'), plt.xticks([]), plt.yticks([])\n\n\tplt.subplot(1, 3, 2), plt.imshow(img_back, cmap='gray')\n\tplt.title('After HPF'), plt.xticks([]), plt.yticks([])\n\n\tplt.subplot(1, 3, 3), plt.imshow(img_back)\n\tplt.title('Result in JET'), plt.xticks([]), plt.yticks([])\n\n\tplt.show()\n\n#fourier_edge()\n\n# B. 푸리에 변환을 이용한 이미지 필터 효과\n# Averagint Filter\n# Gaussian Filter\n# Scharr Filter\n# sobel_x, sobel_y Filter\n# Laplacian Filter\ndef check_kernel():\n\t# Simple Averagint Filter without Scaling Parameter\n\tmean_filter = np.ones((3,3))\n\t# Creating a Gaussian FIlter\n\tx = cv.getGaussianKernel(3,3)\n\tgaussian = x*x.T\n\t# Filters for Edge Detection\n\t# Laplacian\n\tlaplacian = np.array([[0, 1, 0],\n\t\t\t\t\t\t  [1,-4, 1],\n\t\t\t\t\t\t  [0, 1, 0]])\n\t# Scharr in x-direction\n\tscharr = np.array([[-3, 0, 3],\n\t\t\t\t\t   [-10,0,10],\n\t\t\t\t\t   [-3, 0, 3]])\n\t# Sobel in x-direction\n\tsobel_x = np.array([[-1, 0, 1],\n\t\t\t\t\t    [-2, 0, 2],\n\t\t\t\t\t    [-1, 0, 1]])\n\t# Sobel in y-direction\n\tsobel_y = np.array([[-1,-2,-1],\n\t\t\t\t\t    [0, 0, 0],\n\t\t\t\t\t    [1, 2, 1]])\n\n\tfilters = [mean_filter, gaussian, laplacian, sobel_x, sobel_y, scharr]\n\tfilter_name = ['mean_filter', 'gaussian', 'laplacian', 'sobel_x', 'sobel_y', 'scharr_x']\n\n\tfft_filters = [np.fft.fft2(x) for x in filters]\n\tfft_shift = [np.fft.fftshift(y) for y in fft_filters]\n\tmag_spectrum = [np.log(np.abs(z)+1) for z in fft_shift]\n\n\tfor i in range(6):\n\t\tplt.subplot(2, 3, i+1), plt.imshow(mag_spectrum[i], cmap='gray')\n\t\tplt.title(filter_name[i]), plt.xticks([]), plt.yticks([])\n\tplt.show()\n\ncheck_kernel()", "meta": {"hexsha": "671c9344fbe66024e48b013122f163603f299570", "size": 2196, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/29.FTapp.py", "max_stars_repo_name": "minssoj/Learning_OpenCV-Python", "max_stars_repo_head_hexsha": "63f175985a1d9645191c49e16ab6bb91a4f6b7fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-09T02:58:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-09T02:58:51.000Z", "max_issues_repo_path": "Code/29.FTapp.py", "max_issues_repo_name": "minssoj/Learning_OpenCV-Python", "max_issues_repo_head_hexsha": "63f175985a1d9645191c49e16ab6bb91a4f6b7fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/29.FTapp.py", "max_forks_repo_name": "minssoj/Learning_OpenCV-Python", "max_forks_repo_head_hexsha": "63f175985a1d9645191c49e16ab6bb91a4f6b7fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.45, "max_line_length": 89, "alphanum_fraction": 0.6079234973, "include": true, "reason": "import numpy", "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138125126402, "lm_q2_score": 0.8872045937171068, "lm_q1q2_score": 0.8674321858018805}}
{"text": "import numpy\n\n\n# -------------------------------------------------------------------------\n\ndef simple_quadratic_function(x):\n    \"\"\"\n    this function accepts a 2D vector as input.\n    Its outputs are:\n       value: h(x1, x2) = x1^2 + 3*x1*x2\n       grad: A 2x1 vector that gives the partial derivatives\n             of h with respect to x1 and x2\n    Note that when we pass simple_quadratic_function(x) to\n    compute_gradient_numerical_estimate, we're assuming\n    that compute_gradient_numerical_estimate will use only\n    the first returned value of this function.\n    :param x:\n    :return:\n    \"\"\"\n    value = x[0] ** 2 + 3 * x[0] * x[1]\n\n    grad = numpy.zeros(shape=2, dtype=numpy.float32)\n    grad[0] = 2 * x[0] + 3 * x[1]\n    grad[1] = 3 * x[0]\n\n    return value, grad\n\n\n# -------------------------------------------------------------------------\n\ndef compute_gradient_numerical_estimate(J, theta, epsilon=0.0001):\n    \"\"\"\n    :param J: a loss (cost) function that computes the real-valued loss given parameters and data\n    :param theta: array of parameters\n    :param epsilon: amount to vary each parameter in order to estimate\n                    the gradient by numerical difference\n    :return: array of numerical gradient estimate\n    \"\"\"\n\n    gradient = numpy.zeros(theta.shape)\n    \n    # Symmetric Difference Quotient\n    # https://en.wikipedia.org/wiki/Numerical_differentiation\n    # slope ~= [ f(x+h) - f(x-h) ]  /  [ 2h ]\n    \n    \n    # Iterates through all parameters in theta to estimate their respective\n    #   gradients, using the symmetric difference quotient.\n    for num, elem in enumerate(theta):\n    \n        theta[num] = elem + epsilon\n        cost_plus  = J(theta)[0]\n    \n        theta[num] = elem - epsilon\n        cost_minus = J(theta)[0]\n    \n        theta[num] = elem\n        gradient[num] = (cost_plus - cost_minus) / (2 * epsilon)\n    \n\n    return gradient\n\n\n# -------------------------------------------------------------------------\n\ndef test_compute_gradient_numerical_estimate():\n    \"\"\"\n    Test of compute_gradient_numerical_estimate.\n    This provides a test for your numerical gradient implementation\n    in compute_gradient_numerical_estimate\n    It analytically evaluates the gradient of a very simple function\n    called simple_quadratic_function and compares the result with\n    your numerical estimate. Your numerical gradient implementation\n    is incorrect if your numerical solution deviates too much from\n    the analytical solution.\n    :return:\n    \"\"\"\n    print(\"test_compute_gradient_numerical_estimate(): Start Test\")\n    print(\"    Testing that your implementation of \")\n    print(\"        compute_gradient_numerical_estimate()\")\n    print(\"        is correct\")\n    x = numpy.array([4, 10], dtype=numpy.float64)\n    (value, grad) = simple_quadratic_function(x)\n\n    print(\"    Computing the numerical and actual gradient for 'simple_quadratic_function'\")\n    num_grad = compute_gradient_numerical_estimate(simple_quadratic_function, x)\n    print(\"    The following two 2d arrays should be very similar:\")\n    print(\"        \", num_grad, grad)\n    print(\"    (Left: numerical gradient estimate; Right: analytical gradient)\")\n\n    diff = numpy.linalg.norm(num_grad - grad)\n    print(\"    Norm of the difference between numerical and analytical num_grad:\")\n    print(\"        \", diff)\n    print(\"    (should be < 1.0e-09 ; I get about 1.7e-10)\")\n    print(\"test_compute_gradient_numerical_estimate(): DONE\\n\")\n\n\n# -------------------------------------------------------------------------\n", "meta": {"hexsha": "aacf203735ee2edc81b68f3ce5e9ac9cba7f2fb0", "size": 3552, "ext": "py", "lang": "Python", "max_stars_repo_path": "gradient.py", "max_stars_repo_name": "jkadowaki/INFO521_hw5", "max_stars_repo_head_hexsha": "d06ab35ea41d314d52b8adbf43f92e78e2df50f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gradient.py", "max_issues_repo_name": "jkadowaki/INFO521_hw5", "max_issues_repo_head_hexsha": "d06ab35ea41d314d52b8adbf43f92e78e2df50f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gradient.py", "max_forks_repo_name": "jkadowaki/INFO521_hw5", "max_forks_repo_head_hexsha": "d06ab35ea41d314d52b8adbf43f92e78e2df50f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8787878788, "max_line_length": 97, "alphanum_fraction": 0.6151463964, "include": true, "reason": "import numpy", "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.9353465129954621, "lm_q1q2_score": 0.8674060267408461}}
{"text": "import math\n\nimport numpy as np\n\n\ndef shannon_entropy(string):\n    \"\"\"\n    Calculates the Shannon entropy for the given string.\n    :param string: any string, such as '000101001', '12402', or 'aBcd1234ef5g'\n    :return: a real number representing the Shannon entropy\n    \"\"\"\n    symbols = dict.fromkeys(list(string))\n    symbol_probabilities = [float(string.count(symbol)) / len(string) for symbol in symbols]\n    H = -sum([p_symbol * math.log(p_symbol, 2.0) for p_symbol in symbol_probabilities])\n    return H + 0  # add 0 as a workaround so we don't end up with -0.0\n\n\ndef average_cell_entropy(cellular_automaton):\n    \"\"\"\n    Calculates the average cell entropy in the given cellular automaton, where entropy is the Shannon entropy.\n    In the case of a 1D cellular automaton, the state of a cell over time is represented as a string, and its entropy\n     is calculated. The same is done for all cells in this cellular automaton, and the average entropy is returned.\n    :param cellular_automaton: the cellular automaton to perform this operation on\n    :return: a real number representing the average cell Shannon entropy \n    \"\"\"\n    num_cols = cellular_automaton.shape[1]\n    entropies = []\n    for i in range(0, num_cols):\n        cell_states_over_time = ''.join([str(x) for x in cellular_automaton[:, i]])\n        entropy = shannon_entropy(cell_states_over_time)\n        entropies.append(entropy)\n    return np.mean(entropies)\n\n\ndef joint_shannon_entropy(stringX, stringY):\n    \"\"\"\n    Calculates the joint Shannon entropy between the given strings, which must be of the same length.\n    :param stringX: any string, such as '000101001', '12402', or 'aBcd1234ef5g'\n    :param stringY: any string, such as '000101001', '12402', or 'aBcd1234ef5g' \n    :return: a real number representing the joint Shannon entropy between the given strings\n    \"\"\"\n    X = np.array(list(stringX))\n    Y = np.array(list(stringY))\n    joint_symbol_probabilities = []\n    for x in set(X):\n        for y in set(Y):\n            joint_symbol_probabilities.append(np.mean(np.logical_and(X == x, Y == y)))\n    return np.sum(-p * np.log2(p) for p in joint_symbol_probabilities if p != 0)\n\n\ndef mutual_information(stringX, stringY):\n    \"\"\"\n    Calculates the mutual information between the given strings, which must be of the same length.\n    :param stringX: any string, such as '000101001', '12402', or 'aBcd1234ef5g'\n    :param stringY: any string, such as '000101001', '12402', or 'aBcd1234ef5g'\n    :return: a real number representing the mutual information between the given strings\n    \"\"\"\n    return shannon_entropy(stringX) + shannon_entropy(stringY) - joint_shannon_entropy(stringX, stringY)\n\n\ndef average_mutual_information(cellular_automaton, temporal_distance=1):\n    \"\"\"\n    Calculates the average mutual information between a cell and itself at the next n time steps, given by the \n    specified temporal distance. A temporal distance of 1 means the next time step.\n    For example, consider the following string, '00101010110', which represents the state of a cell over 11 time steps.\n     The strings which will be used for the computation of the mutual information between a cell and itself at the \n     next time step are: '0010101011' and '0101010110', since we pair each time-step value with its next value:\n     \" 00101010110\"\n     \"00101010110 \"\n    :param cellular_automaton: the cellular automaton to perform this operation on\n    :param temporal_distance: the size of temporal separation, where the value must be greater than 0 and\n                              less than the number of time steps.\n    :return: a real number representing the average mutual information between a cell and itself at the next time step\n    \"\"\"\n    num_cols = cellular_automaton.shape[1]\n    if not (0 < temporal_distance < num_cols):\n        raise Exception(\"the temporal distance must be greater than 0 and less than the number of time steps\")\n    mutual_informations = []\n    for i in range(0, num_cols):\n        cell_states_over_time = ''.join([str(x) for x in cellular_automaton[:, i]])\n        mi = mutual_information(cell_states_over_time[:-temporal_distance], cell_states_over_time[temporal_distance:])\n        mutual_informations.append(mi)\n    return np.mean(mutual_informations)\n", "meta": {"hexsha": "29305557bcb355428ec27cbeb5a2356da1fc45c7", "size": 4274, "ext": "py", "lang": "Python", "max_stars_repo_path": "cellpylib/entropy.py", "max_stars_repo_name": "swifmaneum/cellpylib", "max_stars_repo_head_hexsha": "4f7be652f2bb49b58ea482b2929617d813111f77", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cellpylib/entropy.py", "max_issues_repo_name": "swifmaneum/cellpylib", "max_issues_repo_head_hexsha": "4f7be652f2bb49b58ea482b2929617d813111f77", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cellpylib/entropy.py", "max_forks_repo_name": "swifmaneum/cellpylib", "max_forks_repo_head_hexsha": "4f7be652f2bb49b58ea482b2929617d813111f77", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.880952381, "max_line_length": 119, "alphanum_fraction": 0.7185306504, "include": true, "reason": "import numpy", "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668673560625, "lm_q2_score": 0.884039278690883, "lm_q1q2_score": 0.8673900496928467}}
{"text": "'''\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Taking user input ~~~~~~~~~~~~~~~~~~~~~~~~~~~\nwhile True:\n    try:\n        N = int(input(\"Enter the Number of Points: \"))\n        if N > 1: break\n        else: print(\"Number of Points must be greater than 1\")\n    except ValueError:\n        print(\"Enter a Natural Number greater than 1\")\nX, Y = [], []\nfor i in range(N):\n    while True:\n        try:\n            x = float(input(\"Enter the X coordinate of the point \"+str(i+1)+\": \"))\n        except ValueError:\n                print(\"Enter a Real Number\")\n                continue\n        else: break\n    X.append(x)\n    while True:\n        try:\n            y = float(input(\"Enter the Y coordinate of the point \"+str(i+1)+\": \"))\n        except ValueError:\n                print(\"Enter a Real Number\")\n                continue\n        else: break\n    Y.append(y)\nwhile True:\n    try:\n        n = int(input(\"Enter the Degree of polynomial: \"))\n        if n > 0: break\n        else: print(\"Degree of polynomial must be greater than 1\")\n    except ValueError:\n        print(\"Enter a Natural Number greater than 0\")\nprint()\n'''\nfrom numpy import array, zeros, linalg\n\n# X = [0, 1, 2, 3, 4, 5]\n# Y = [2.1, 7.7, 13.6, 27.2, 40.9, 61.1]\n\nX = [0, 1, 2, 3, 4, 5]      # numpy.arange(6)\nY = [2, 8, 14, 28, 39, 62]\n\nX = array(X, float)\nY = array(Y, float)\n\nN = len(X)  # Number of data points\nn = 2       # Degree of polynomial\n# n = 3\n\n\n# [A]{a} = {B}\nA = zeros((n+1, n+1))\nB = zeros(n+1)\na = zeros(n+1)\n\n#     [   N     ∑ xi      ∑ xi^2    ∑ xi^n   ]      [∑      yi]\n# A = [ ∑ xi    ∑ xi^2    ∑ xi^3    ∑ xi^n+1 ], B = [∑ xi   yi]\n#     [ ∑ xi^n  ∑ xi^n+1  ∑ xi^n+2  ∑ xi^2n  ]      [∑ xi^n yi]\n\n# A[row, col] = ∑ xi^(row+col)             B[row] = ∑ xi^row yi\n# where row, col = 0 to n, except [0,0]\n\nA[0,0] = N\nfor row in range(n+1):\n\n    for col in range(n+1):\n        if row == 0 and col == 0: continue\n        \n        A[row,col] = sum(X**(row+col))\n\n    B[row] = sum(X**row * Y)\n\na = linalg.solve(A, B)\n\n\nprint(\"The polynomial equation :\")\nprint('y = %f' % a[0], end=' ')\nfor i in range(1, n+1):\n    print('%+f x^%d' % (a[i], i), end=' ')\nprint()\n\n'''\nFor 2nd order polynomial:\ny = a0 + a1 x + a2 x^2 + e\ne = y - a0 - a1 x - a2 x^2\n\nCriteria for a best fit:\n∑ (ei) = ∑ (yi - a0 - a1 xi - a2 xi^2)\n\nSr = ∑ (ei)^2 = ∑ (yi - a0 - a1 xi - a2 xi^2)^2\n\n∂Sr/∂a0 = -2      ∑ (yi - a0 - a1 xi - a2 xi^2)\n∂Sr/∂a1 = -2 xi   ∑ (yi - a0 - a1 xi - a2 xi^2)\n∂Sr/∂a2 = -2 xi^2 ∑ (yi - a0 - a1 xi - a2 xi^2)\n\n0 = ∑      yi - ∑ a0      - ∑ a1 xi   - ∑ a2 xi^2\n0 = ∑ xi   yi - ∑ a0 xi   - ∑ a1 xi^2 - ∑ a2 xi^3\n0 = ∑ xi^2 yi - ∑ a0 xi^2 - ∑ a1 xi^3 - ∑ a2 xi^4\n\n(   n  ) a0 + (∑ xi  ) a1 + (∑ xi^2) a2 = ∑      yi    # ∑ a0 = n a0\n(∑ xi  ) a0 + (∑ xi^2) a1 + (∑ xi^3) a2 = ∑ xi   yi\n(∑ xi^2) a0 + (∑ xi^3) a1 + (∑ xi^4) a2 = ∑ xi^2 yi\nAny method of solving systems of linear equations will give a0, a1, a2\n\n\nFor nth order polynomial:\ny = a0 + a1 x + a2 x^2 + ... + an x^n\n\n(  N   ) a0 + (∑ xi    ) a1 + (∑ xi^2  ) a2 + (∑ xi^n  ) an = ∑      yi\n(∑ xi  ) a0 + (∑ xi^2  ) a1 + (∑ xi^3  ) a2 + (∑ xi^n+1) an = ∑ xi   yi\n(∑ xi^2) a0 + (∑ xi^3  ) a1 + (∑ xi^4  ) a2 + (∑ xi^n+2) an = ∑ xi^2 yi\n(∑ xi^n) a0 + (∑ xi^n+1) a1 + (∑ xi^n+2) a2 + (∑ xi^2n ) an = ∑ xi^n yi\n\n\n# Standard Error, Sy/x = √( Sr / (n-(m+1)) ) = √(3.74657/(6-(2+1))) = 1.12\n# where n = number of points, m = degree of polynomial\n\n'''\n", "meta": {"hexsha": "734a3c3e26bae65f7f801f0923579e2c0795edcf", "size": 3357, "ext": "py", "lang": "Python", "max_stars_repo_path": "2. Interpolation and Curve Fitting/6. Polynomial (Least Squares) Regression or Fit.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2. Interpolation and Curve Fitting/6. Polynomial (Least Squares) Regression or Fit.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2. Interpolation and Curve Fitting/6. Polynomial (Least Squares) Regression or Fit.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7438016529, "max_line_length": 82, "alphanum_fraction": 0.4605302353, "include": true, "reason": "from numpy", "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.907312226373181, "lm_q1q2_score": 0.8673735694398313}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Ejercicio 1\n\ndef FD(f, x, h):\n    return (f(x+h)-f(x))/h\n\ndef CD(f, x, h):\n    return (f(x+h/2)-f(x-h/2))/h\n\ndef ED(f, x, h):\n    return (4*CD(f, x, h/2)-CD(f, x, h))/3.0\n\n\ndef get_error(f, deriva_f_analitica, deriva_f_numerica, x):\n    h_range = np.logspace(-15,-1, 200)\n    analitica = deriva_f_analitica(x)\n    error_range = np.abs((deriva_f_numerica(f, x, h_range) - analitica)/analitica)\n    return h_range, error_range\n\n\nplt.figure(figsize=(15,10))\n\ni = 1\nff = [np.exp, np.sin]\ngg = [np.exp, np.cos]\nnames = [\"exp(x)\", \"sin(x)\"]\nxx = [0.1, 1.0, 100.0]\n\nfor f, g, n, in zip(ff, gg, names):\n    for x in xx:\n        plt.subplot(2,3,i)\n\n        h, e = get_error(f, g, FD, x); plt.plot(h, e, label=\"FD\")\n        h, e = get_error(f, g, CD, x); plt.plot(h, e, label=\"CD\")\n        h, e = get_error(f, g, ED, x); plt.plot(h, e, label=\"ED\")\n\n        plt.title(\"f(x)={}, x={:.1f}\".format(n,x))\n        plt.xlim([1E-15,1E-1])\n        plt.ylim([1E-15,1E-1])\n        plt.loglog()\n        plt.legend()\n        plt.grid()\n        plt.xlabel(\"x\")\n        plt.ylabel(\"|error primera derivada|\")\n        i += 1\n\nplt.savefig(\"primera_derivada.png\", bbox_inches='tight')\n\n\n# Ejercicio 2\n\n\ndef CD2(f, x, h):\n    return (CD(f, x+h/2, h) - CD(f, x-h/2, h))/h\n\ndef CD2_bis(f, x, h):\n    return (f(x+h) + f(x-h) - 2*f(x))/(h**2)\n\ndef minus_cos(x):\n    return -np.cos(x)\n\nplt.figure(figsize=(15,10))\n\ni = 1\nxx = [0.1, 1.0, 100.0]\nfor x in xx:\n    plt.subplot(2,3,i)\n    h, e = get_error(np.cos, minus_cos, CD2, x); plt.plot(h,e, label=\"CD2\")\n    h, e = get_error(np.cos, minus_cos, CD2_bis, x); plt.plot(h,e, label=\"CD2_bis\")\n    plt.xlim([1E-15,1E-1])\n    plt.ylim([1E-15,1E-1])\n    plt.loglog()\n    plt.legend()\n    plt.grid()\n    plt.xlabel(\"x\")\n    plt.ylabel(\"|error segunda derivada|\")\n    plt.title(\"f(x)=cos(x), x={:.1f}\".format(x))\n    i += 1\n\nplt.savefig(\"segunda_derivada.png\", bbox_inches='tight')\n", "meta": {"hexsha": "e6d09e5c4dd374320f190e8e1cab3515108547e7", "size": 1944, "ext": "py", "lang": "Python", "max_stars_repo_path": "ejercicios/11/JaimeForero_Ejercicio11.py", "max_stars_repo_name": "oscarochoa1/FISI2028-201910", "max_stars_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-03T04:27:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T18:50:41.000Z", "max_issues_repo_path": "ejercicios/11/JaimeForero_Ejercicio11.py", "max_issues_repo_name": "oscarochoa1/FISI2028-201910", "max_issues_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ejercicios/11/JaimeForero_Ejercicio11.py", "max_forks_repo_name": "oscarochoa1/FISI2028-201910", "max_forks_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-01-23T10:44:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-04T00:05:40.000Z", "avg_line_length": 23.421686747, "max_line_length": 83, "alphanum_fraction": 0.5576131687, "include": true, "reason": "import numpy", "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813513911655, "lm_q2_score": 0.9073122144683576, "lm_q1q2_score": 0.8673735569211715}}
{"text": "import math\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\ndata = [[0,20.1],[60,23],[120,26.9],[180,30],[240,33.1],[300,36.9]]\r\n\r\ndatax = []\r\ndatay = []\r\n\r\n\r\nclass LinearRegression():\r\n    \r\n    def __init__(self):\r\n        pass\r\n    \r\n    def sigmax(self):\r\n        a1 = 0\r\n        for a in range(len(data)):\r\n            a1 = a1+(data[a][0])\r\n        return a1\r\n    \r\n    def xbar(self):\r\n        return self.sigmax() / len(data)\r\n    \r\n    def sigmaxsq(self):\r\n        b1 = 0\r\n        for b in range(len(data)):\r\n            b1 = b1+(data[b][0])**2\r\n        return b1\r\n    \r\n    def sigmay(self):\r\n        d1 = 0\r\n        for d in range(len(data)):\r\n            d1 += data[d][1]\r\n        return d1\r\n    \r\n    def ybar(self):\r\n        return self.sigmay() / len(data)\r\n    \r\n    def sigmaysq(self):\r\n        e1 = 0\r\n        for e in range(len(data)):\r\n            e1 += (data[e][1])**2\r\n        return e1\r\n    \r\n    def sigmaxy(self):\r\n        g1 = 0\r\n        for g in range(len(data)):\r\n            g1 += (data[g][0])*(data[g][1])\r\n        return g1\r\n    \r\n    def SXX(self):\r\n        return ((self.sigmaxsq()) - (self.sigmax()**2) / len(data))\r\n        \r\n    def SYY(self):\r\n        return ((self.sigmaysq()) - ((self.sigmay())**2 / len(data)))\r\n    \r\n    def SXY(self):\r\n        return ((self.sigmaxy()) - ((self.sigmax()*self.sigmay()) / len(data)))\r\n    \r\n    def b(self):\r\n        return self.SXY() / self.SXX()\r\n    \r\n    def a(self):\r\n        return (self.b()*-self.xbar()) + (self.ybar())\r\n     \r\n    def linregres(self):\r\n        return ('y =  '+str(self.b())+'x'+' + '+str(self.a()))\r\n        \r\n    def PMCC(self):\r\n        pmcc = ((self.SXY()) / math.sqrt(self.SXX()*self.SYY()))\r\n        return ('PMCC = '+str(pmcc))\r\n    \r\n    def scatter(self):\r\n        for i in range(len(data)):\r\n            datax.append(data[i][0])\r\n        for p in range(len(data)):\r\n            datay.append(data[p][1])\r\n            \r\n        \r\n        \r\nif __name__ == '__main__':\r\n    lr = LinearRegression()\r\n    lr.scatter()\r\n    print(lr.linregres())\r\n    print(lr.PMCC())\r\n    m = lr.b()\r\n    c = lr.a()\r\n    \r\n    x = np.linspace(0,300,10)\r\n    y = m*x + c\r\n    plt.plot(x, y, 'r')\r\n    plt.scatter(datax, datay)\r\n    plt.show()\r\n    \r\n    inp = input('predict values?')\r\n    if inp == 'y':\r\n        x = float(input('value for x?'))\r\n        y = (m*x) + c\r\n        print(y)\r\n    else:\r\n        pass\r\n    \r\n    \r\n    \r\n    \r\n    \r\n    \r\n    \r\n\r\n", "meta": {"hexsha": "36f74d37fc687c88e8d565335fb68da1443ba48e", "size": 2450, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear regression.py", "max_stars_repo_name": "Gl3ssMug/Linear-Regression", "max_stars_repo_head_hexsha": "cd0b500bbfd6d8c57c5eeeb0913a875a8dd77c03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Linear regression.py", "max_issues_repo_name": "Gl3ssMug/Linear-Regression", "max_issues_repo_head_hexsha": "cd0b500bbfd6d8c57c5eeeb0913a875a8dd77c03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear regression.py", "max_forks_repo_name": "Gl3ssMug/Linear-Regression", "max_forks_repo_head_hexsha": "cd0b500bbfd6d8c57c5eeeb0913a875a8dd77c03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0720720721, "max_line_length": 80, "alphanum_fraction": 0.4363265306, "include": true, "reason": "import numpy", "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9793540734789342, "lm_q2_score": 0.8856314783461303, "lm_q1q2_score": 0.8673467959194533}}
{"text": "import numpy as np\n\narray_1d = np.array([1.2, 2.4, 3.5, 4.7, 6.1, 7.2, 8.3, 9.5])\nprint(array_1d)\n\narray_2d = np.array([[6, 5], [11, 7], [4, 8]])\nprint(array_2d)\n\n# populate arrays with sequences of number\narray_seq = np.arange(5, 12)\nprint(array_seq)\n\n# populate with random numbers\narray_random_int_50_to_100 = np.random.randint(low=50, high=101, size=(6))\nprint(array_random_int_50_to_100)\n\narray_random_float_0_to_1 = np.random.random((6))\nprint(array_random_float_0_to_1)\n\n# math op\n# NumPy uses a trick called broadcasting to virtually expand the smaller operand to dimensions compatible for linear algebra\nrandom_floats_2_to_3 = np.random.random((6)) + 2\nprint('random_floats_2_to_3', random_floats_2_to_3)\n\n# Create a Linear Dataset\n# Your goal is to create a simple dataset consisting of a single feature and a label as follows:\n# Assign a sequence of integers from 6 to 20 (inclusive) to a NumPy array named feature.\n# Assign 15 values to a NumPy array named label such that:\n#    label = (3)(feature) + 4\n# For example, the first value for label should be:\n#   label = (3)(6) + 4 = 22\n\nfeatures = np.arange(6, 21)\nprint(\"features\", features)\nlabels = features * 3 + 4\nprint(\"labels\", labels)\n\n# Add Some Noise to the Dataset\n# To make your dataset a little more realistic, insert a little random noise into each element\n# of the label array you already created. To be more precise, modify each value assigned to label\n# by adding a different random floating-point value between -2 and +2.\n# Don't rely on broadcasting. Instead, create a noise array having the same dimension as label.\nnoise = np.random.random(size=labels.size) * 4 - 2\nprint('noise', noise)\nnoised_label = noise + labels\nprint('noised_label', noised_label)\n", "meta": {"hexsha": "d255c9e06a77c13c29949cebf93a02a330f3b54c", "size": 1735, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/ml_basic/numpy_untra_quick_tutorial.py", "max_stars_repo_name": "lisy09/research-to-applied-ml", "max_stars_repo_head_hexsha": "c6f1b660757dd8178e5c3b4027136e996c6c96de", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ml_basic/numpy_untra_quick_tutorial.py", "max_issues_repo_name": "lisy09/research-to-applied-ml", "max_issues_repo_head_hexsha": "c6f1b660757dd8178e5c3b4027136e996c6c96de", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ml_basic/numpy_untra_quick_tutorial.py", "max_forks_repo_name": "lisy09/research-to-applied-ml", "max_forks_repo_head_hexsha": "c6f1b660757dd8178e5c3b4027136e996c6c96de", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.914893617, "max_line_length": 124, "alphanum_fraction": 0.7446685879, "include": true, "reason": "import numpy", "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.9111797130267453, "lm_q1q2_score": 0.8673184612461672}}
{"text": "import numpy as np\r\n\r\ndef bisection(f,a,b,TOL,NMAX):\r\n    # THIS FUNCTION PRINTS THE a,b,c VALUES FOR EACH ITERATION:\r\n    \r\n    #Approximates root using Bisection Method\r\n    #In an interval[a,b] with a tolerance TOL\r\n    #|f(c)| < TOL, where m is the midpoint\r\n    \r\n\r\n    #INPUT : f , a , b , TOL , NMAX\r\n    # f : function / polynomial\r\n    # a : interval start\r\n    # b : interval end\r\n    # TOL : tolerance value\r\n    # NMAX : maximum number of iterations\r\n\r\n\r\n    #Print Table Header:\r\n    print('--------------------------------------------------------------------------')\r\n    print('iter \\t\\t a \\t\\t b \\t\\t c \\t\\t f(c)        ')\r\n    print('--------------------------------------------------------------------------')\r\n    #satisfy the conditions needed to apply the Bisection Method:\r\n    if np.sign(f(a)) == np.sign(f(b)):\r\n        print(\"No root found in the given interval!\")\r\n        exit()\r\n        \r\n    for i in range(NMAX):\r\n        #Compute Midpoint\r\n        c = (a+b)/2\r\n        #print line for the table:\r\n        N.append(1+i)\r\n        f_x.append(f(c))\r\n        print(str(1+i)+'\\t% 15.12f\\t% 15.12f\\t% 15.12f\\t% 15.12f\\t' %(a, b, c, f(c)))\r\n        #Check stopping condition:\r\n        if np.abs(f(c)) < TOL:\r\n            print('------------------------------------------------------------------------')\r\n            print('Root Found: '+str(c))\r\n            break\r\n        #Implement Recursion:\r\n        elif np.sign(f(a)) == np.sign(f(c)):\r\n            #Improvement on a\r\n            a = c\r\n        elif np.sign(f(b)) == np.sign(f(c)):\r\n            #Improvement on b\r\n            b = c\r\n        \r\n    if i == NMAX -1:\r\n        print(\"MAX NUMBER OF ITERATIONS REACHED!\")\r\n        print('Approximaiton to the Root after max iterations is : '+str(c))        \r\n        exit()\r\n    \r\ndef newton(f,fp,x0,TOL,NMAX):\r\n    #INPUT : f , fp , x0 , TOL , NMAX\r\n    # f : function / polynomial\r\n    # fp : derivative of f\r\n    # x0 : initial guess\r\n    # TOL : tolerance value\r\n    # NMAX : maximum number of iterations\r\n\r\n    #Approximates root using Newton's Method\r\n    #Recursive Program\r\n\r\n    print('--------------------------------------------------------------------------')\r\n    print('iter \\t\\t xi \\t\\t   correction \\t\\t   rdiff        ')\r\n    print('--------------------------------------------------------------------------')\r\n    # initiate values for  iteration loop:\r\n    rdiff = 1\r\n    xi = x0\r\n    counter = 0\r\n    while rdiff > TOL and counter < NMAX:\r\n        # get the number of necessary iterations at that particular x0\r\n        # compute relative difference\r\n        rdiff = np.abs(f(xi)/fp(xi)/xi)\r\n        # next xi:\r\n        x1 = xi - f(xi)/fp(xi)\r\n        N.append(counter+1)\r\n        f_x.append(f(x1))\r\n        # print iteration data:\r\n        print('%i \\t %15.12f \\t %15.12f \\t %15.12f' % (counter+1, x1, np.abs(f(xi)/fp(xi)),  rdiff))\r\n        # prepare for the next iteration:\r\n        xi = x1\r\n        counter += 1\r\n        if counter == NMAX:\r\n            print(\"MAX NUMBER OF ITERATIONS REACHED!\")\r\n            print('Approximaiton to the Root after max iterations is : ' , x1)        \r\n            exit()\r\n    \r\n    print('------------------------------------------------------------------------')\r\n    print('Root Found: ', x1)\r\n\r\n", "meta": {"hexsha": "6734fcc992d92966b3e7cc79a03a425aa1e9fd8a", "size": 3278, "ext": "py", "lang": "Python", "max_stars_repo_path": "RFA.py", "max_stars_repo_name": "YashIITM/Root-Finding-Algorithms", "max_stars_repo_head_hexsha": "a7ccc58cd5064f7910af538de00a3fe7cdd57cd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RFA.py", "max_issues_repo_name": "YashIITM/Root-Finding-Algorithms", "max_issues_repo_head_hexsha": "a7ccc58cd5064f7910af538de00a3fe7cdd57cd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RFA.py", "max_forks_repo_name": "YashIITM/Root-Finding-Algorithms", "max_forks_repo_head_hexsha": "a7ccc58cd5064f7910af538de00a3fe7cdd57cd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6304347826, "max_line_length": 101, "alphanum_fraction": 0.4460036608, "include": true, "reason": "import numpy", "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.9111797075998823, "lm_q1q2_score": 0.8673184610575131}}
{"text": "# Undergraduate Student: Arturo Burgos\n# Professor: João Rodrigo Andrade\n# Federal University of Uberlândia - UFU, Fluid Mechanics Laboratory - MFLab, Block 5P, Uberlândia, MG, Brazil\n\n\n# Third exercise: Fibonacci sequence - by a common loop\n\nimport numpy as np\nimport time\n\nn = int(input(\"Enter the n indices: \"))\nFbn=0 # Value of the first box\nA = 0 # Values of the second  \nB = 1 # Value of the third box\n\n##############################\n# Variable iterative fibonacci  --> Better performance, why?\n##############################\n\n\ndef varloop_fibonacci(k,F1,F2,S):\n\n    for i in range(0,k):\n        F1=S\n        S = F1+F2\n        F2 = F1\n\n    return S\n\nt_initial1 = time.time()\nFbn = varloop_fibonacci(n,A,B,Fbn)\n\nprint(\"Elapsed time is: %s seconds\" % (time.time()-t_initial1))\nprint(\"The correspond indices number is: \",Fbn)\n\nprint(\"\\n\")\n\n###########################\n# Array iterative fibonacci  --> Worse performance, why?\n###########################\n\nFbn=0 # Value of the first box\nA = np.array([0, 1]) # Values of the second an third boxes \n\ndef arrayloop_fibonacci(k,F,S):\n\n    for i in range(0,k):\n        F[0]=S\n        S = sum(F)\n        F[1] = F[0]\n    return S\n\nt_initial2 = time.time()\nFbn = arrayloop_fibonacci(n,A,Fbn)\n\nprint(\"Elapsed time is: %s seconds\" % (time.time()-t_initial2))\nprint(\"The correspond indices number is: \",Fbn)\n", "meta": {"hexsha": "f91885b397c91286e2fca527e3783f187ea14ff6", "size": 1348, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/3_ex/fibonacci_ite.py", "max_stars_repo_name": "bangyen/Comparing-Languages", "max_stars_repo_head_hexsha": "07fd760501f03482229831652663a5919987c30c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-03-17T18:40:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T11:51:12.000Z", "max_issues_repo_path": "Python/3_ex/fibonacci_ite.py", "max_issues_repo_name": "bangyen/Comparing-Languages", "max_issues_repo_head_hexsha": "07fd760501f03482229831652663a5919987c30c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/3_ex/fibonacci_ite.py", "max_forks_repo_name": "bangyen/Comparing-Languages", "max_forks_repo_head_hexsha": "07fd760501f03482229831652663a5919987c30c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-11T01:20:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T01:20:01.000Z", "avg_line_length": 23.2413793103, "max_line_length": 110, "alphanum_fraction": 0.6068249258, "include": true, "reason": "import numpy", "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250325, "lm_q2_score": 0.9362849990810246, "lm_q1q2_score": 0.8672842834573542}}
{"text": "## 2. Calculating expected values ##\n\nmales_over50k = .67 * .241 * 32561\nmales_under50k = .67 * .759 * 32561\nfemales_over50k = .33 * .241 * 32561\nfemales_under50k = .33 * .759 * 32561\n\n## 3. Calculating chi-squared ##\n\nobserved = [6662, 1179, 15128, 9592]\nexpected = [5257.6, 2589.6, 16558.2, 8155.6]\nvalues = []\n\nfor i, obs in enumerate(observed):\n    exp = expected[i]\n    value = (obs - exp) ** 2 / exp\n    values.append(value)\n\nchisq_gender_income = sum(values)\n\n## 4. Finding statistical significance ##\n\nimport numpy as np\nfrom scipy.stats import chisquare\n\nobserved = np.array([6662, 1179, 15128, 9592])\nexpected = np.array([5257.6, 2589.6, 16558.2, 8155.6])\n\nchisq_value, pvalue_gender_income = chisquare(observed, expected)\n\n## 5. Cross tables ##\n\nimport pandas\ntable = pandas.crosstab(income[\"sex\"], [income[\"race\"]])\nprint(table)\n\n## 6. Finding expected values ##\n\nimport pandas\nfrom scipy.stats import chi2_contingency\n\ntable = pandas.crosstab(income[\"sex\"], [income[\"race\"]])\nchisq_value, pvalue_gender_race, df, expected = chi2_contingency(table)", "meta": {"hexsha": "5026254b3f88869018f11214ef93fe8926b24e7d", "size": 1060, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data Analyst in Python/Step 5 - Probability and Statistics/5. Hypothesis Testing Fundamentals/3. Multi category chi-squared tests.py", "max_stars_repo_name": "MyArist/Dataquest", "max_stars_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-27T12:04:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T04:39:33.000Z", "max_issues_repo_path": "Data Analyst in Python/Step 5 - Probability and Statistics/5. Hypothesis Testing Fundamentals/3. Multi category chi-squared tests.py", "max_issues_repo_name": "myarist/Dataquest", "max_issues_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Analyst in Python/Step 5 - Probability and Statistics/5. Hypothesis Testing Fundamentals/3. Multi category chi-squared tests.py", "max_forks_repo_name": "myarist/Dataquest", "max_forks_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2021-03-30T06:45:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T03:55:02.000Z", "avg_line_length": 24.6511627907, "max_line_length": 71, "alphanum_fraction": 0.7009433962, "include": true, "reason": "import numpy,from scipy", "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535094, "lm_q2_score": 0.9059898184796792, "lm_q1q2_score": 0.8672839424794812}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\n\n\n# In[2]:\n\n\n# Quadratic Integral Approximation 5.4\ndef GausIntegral(f, a, b, n):\n    def g(t):\n        return f(((b-a)*t+(b+a))/2) * ((b-a)/2)\n    if n == 1:\n        I = g(-(1/3)**0.5)             + g((1/3)**0.5)\n        return I\n    if n == 2:\n        I = (5/9)*g(-(3/5)**0.5)             + (8/9)*g(0)             + (5/9)*g((3/5)**0.5)\n        return I\n    if n == 3:\n        I = ((1/2)+(1/12)*((10/3)**.5))*g(-((1/7)*(3-4*(0.3**0.5)))**0.5)             + ((1/2)-(1/12)*((10/3)**.5))*g(-((1/7)*(3+4*(0.3**0.5)))**0.5)             + ((1/2)+(1/12)*((10/3)**.5))*g(((1/7)*(3-4*(0.3**0.5)))**0.5)             + ((1/2)-(1/12)*((10/3)**.5))*g(((1/7)*(3+4*(0.3**0.5)))**0.5)\n        return I\n    if n == 4:\n        I = (0.3*((-0.7+5*(0.7**0.5))/(-2+5*(0.7**0.5))))*g(-((1/9)*(5-(2*(((10/7)**0.5)))))**0.5)             + (0.3*((0.7+5*(0.7**0.5))/(2+5*(0.7**0.5))))*g(-((1/9)*(5+(2*(((10/7)**0.5)))))**0.5)             + (128/225)*g(0)             + (0.3*((-0.7+5*(0.7**0.5))/(-2+5*(0.7**0.5))))*g(((1/9)*(5-(2*(((10/7)**0.5)))))**0.5)             + (0.3*((0.7+5*(0.7**0.5))/(2+5*(0.7**0.5))))*g(((1/9)*(5+(2*(((10/7)**0.5)))))**0.5)\n        return I\n\n\n# In[3]:\n\n\ndef f(x):\n    return 1/(x**0.5)\na = 0\nb = 1\nI = GausIntegral(f, a, b, 1)\nprint(I)\nprint(I - 1.4183)\n# Book solution of 1.4183 is wrong?\n\n\n# In[4]:\n\n\n# Example 3 approximation for e^(-x^2) from x = 0 to x = 1\ndef f(x):\n    return np.exp(-(x**2))\na = 0\nb = 1\nI = GausIntegral(f, a, b, 2)\nprint(I)\nprint(I-0.746814584)\n#Correct!!!\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "3cb2ee10b7da11b2cc73e6de1f7703795990f383", "size": 1569, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter5/Quadratic Integral Approx 5.4.py", "max_stars_repo_name": "southparkkids/NumericalAnalysis", "max_stars_repo_head_hexsha": "850cf04c7c1781316ca8d4a815ec4e82b9cc1506", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter5/Quadratic Integral Approx 5.4.py", "max_issues_repo_name": "southparkkids/NumericalAnalysis", "max_issues_repo_head_hexsha": "850cf04c7c1781316ca8d4a815ec4e82b9cc1506", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter5/Quadratic Integral Approx 5.4.py", "max_forks_repo_name": "southparkkids/NumericalAnalysis", "max_forks_repo_head_hexsha": "850cf04c7c1781316ca8d4a815ec4e82b9cc1506", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9047619048, "max_line_length": 424, "alphanum_fraction": 0.3709369025, "include": true, "reason": "import numpy", "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793908, "lm_q2_score": 0.9019206857566127, "lm_q1q2_score": 0.8672272304788265}}
{"text": "import numpy as np\r\n\r\n\r\ndef sigmoid(z):\r\n    \"\"\"Sigmoid or logistic activation function\"\"\"\r\n    return 1 / (1 + np.exp(-z))\r\n\r\n\r\n# def softmax(z):\r\n#     \"\"\"Softmax activation function (generalized sigmoid)\"\"\"\r\n#     z -= np.max(z)\r\n#     return np.exp(z) / np.sum(np.exp(z), axis=0)\r\n\r\ndef softmax(arr, axis=None):\r\n    X = np.atleast_2d(arr)\r\n    if axis is None:\r\n        axis = next(j[0] for j in enumerate(X.shape) if j[1] > 1)\r\n    X = X - np.expand_dims(np.max(X, axis=axis), axis)\r\n    X = np.exp(X)\r\n    probs = X / np.expand_dims(np.sum(X, axis=axis), axis)\r\n    if len(arr.shape) == 1:\r\n        return probs.flatten()\r\n    else:\r\n        return probs\r\n\r\n\r\ndef tanh(z):\r\n    \"\"\"Hyperbolic tangent activation function\"\"\"\r\n    sinh = np.exp(z) - np.exp(-z)\r\n    cosh = np.exp(z) + np.exp(-z)\r\n    return sinh / cosh\r\n\r\n\r\ndef relu(z):\r\n    \"\"\"Rectified Linear Unit activation function\"\"\"\r\n    return np.maximum(z, 0, z)\r\n\r\n\r\ndef leaky_relu(z, a=0.01):\r\n    \"\"\"Leaky Rectified Linear Unit activation function\"\"\"\r\n    return np.maximum(z, a * z, z)\r\n", "meta": {"hexsha": "d830611ce62b86f69ae5003a48b019c65bad6046", "size": 1055, "ext": "py", "lang": "Python", "max_stars_repo_path": "assort/activations.py", "max_stars_repo_name": "yalotfi/AssortedAI", "max_stars_repo_head_hexsha": "cc107229f15059aa6edaf3a620e5957fad351c93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assort/activations.py", "max_issues_repo_name": "yalotfi/AssortedAI", "max_issues_repo_head_hexsha": "cc107229f15059aa6edaf3a620e5957fad351c93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assort/activations.py", "max_forks_repo_name": "yalotfi/AssortedAI", "max_forks_repo_head_hexsha": "cc107229f15059aa6edaf3a620e5957fad351c93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.119047619, "max_line_length": 66, "alphanum_fraction": 0.5725118483, "include": true, "reason": "import numpy", "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338057771058, "lm_q2_score": 0.9019206857566126, "lm_q1q2_score": 0.8672272294846528}}
{"text": "''' mbinary\n#########################################################################\n# File : solve-linear-by-iteration.py\n# Author: mbinary\n# Mail: zhuheqin1@gmail.com\n# Blog: https://mbinary.xyz\n# Github: https://github.com/mbinary\n# Created Time: 2018-10-02  21:14\n# Description:\n#########################################################################\n'''\n\n'''\n#########################################################################\n# File : solve-linear-by-iteration.py\n# Author: mbinary\n# Mail: zhuheqin1@gmail.com\n# Blog: https://mbinary.xyz\n# Github: https://github.com/mbinary\n# Created Time: 2018-05-04  07:42\n# Description: \n#########################################################################\n'''\nimport numpy as np \nfrom operator import le,lt\n\ndef jacob(A,b,x,accuracy=None,times=6):\n    ''' Ax=b,  arg x is the init val, times is the time of iterating'''\n    A,b,x = np.matrix(A),np.matrix(b),np.matrix(x)\n    n,m = A.shape \n    if n!=m:raise Exception(\"Not square matrix: {A}\".format(A=A))\n    if b.shape !=( n,1) : raise Exception('Error: {b} must be {n} x1 in dimension'.format(b = b,n=n))\n    D = np.diag(np.diag(A))\n    DI = np.zeros([n,n])\n    for i in range(n):DI[i,i]= 1/D[i,i]\n    R = np.eye(n) - DI * A\n    g = DI * b\n    print('R =\\n{}'.format(R))\n    print('g =\\n{}'.format(g))\n    last = -x\n    if accuracy != None:\n        ct=0\n        while 1:\n            ct+=1\n            tmp = x-last\n            last = x\n            mx = max ( abs(i) for i in tmp) \n            if mx<accuracy:return x\n            x = R*x+g\n            print('x{ct} =\\n{x}'.format(ct = ct,x=x))\n    else:\n        for i in range(times):\n            x = R*x+g\n            print('x{ct} =  \\n{x}'.format(ct=i+1,x=x))\n    print('isLimitd: {}'.format(isLimited(A)))\n    return x\ndef gauss_seidel(A,b,x,accuracy=None,times=6):\n    ''' Ax=b,  arg x is the init val, times is the time of iterating'''\n    A,b,x = np.matrix(A),np.matrix(b),np.matrix(x)\n    n,m = A.shape \n    if n!=m:raise Exception(\"Not square matrix: {A}\".format(A=A))\n    if b.shape !=( n,1) : raise Exception('Error: {b} must be {n} x1 in dimension'.format(b = b,n=n))\n    D =np. matrix(np.diag(np.diag(A)))\n    L = np.tril(A) - D  # L = np.triu(D.T) - D\n    U = np.triu(A) - D\n    DLI = (D+L).I\n    S = - (DLI) * U\n    f = (DLI)*b\n    print('S =\\n{}'.format(S))\n    print('f =\\n{}'.format(f))\n    last = -x\n    if accuracy != None:\n        ct=0\n        while 1:\n            ct+=1\n            tmp = x-last\n            last = x\n            mx = max ( abs(i) for i in tmp) \n            if mx<accuracy:return x\n            x = S*x+f\n            print('x{ct} =\\n{x}'.format(ct=ct,x=x))\n    else:\n        for i in range(times):\n            x = S*x+f\n            print('x{ct} =  \\n{x}'.format(ct=i+1,x=x))\n    print('isLimitd: {}'.format(isLimited(A)))\n    return x\n\n\ndef isLimited(A,strict=False):\n    '''通过检查A是否是[严格]对角优来判断迭代是否收敛, 即对角线上的值是否都大于对应行(或者列)的值'''\n    diag = np.diag(A)\n    op = lt if strict else le\n    if op(A.max(axis=0),diag).all(): return True \n    if op(A.max(axis=1), diag).all(): return True \n    return False\n\ntestcase=[]\ndef test():\n    for func,A,b,x,*args in testcase:\n        acc =None \n        times = 6\n        if args !=[] :\n            if isinstance(args[0],int):times = args[0]\n            else : acc = args[0]\n        return func(A,b,x,acc,times)\n\n\nif __name__ =='__main__':\n    A = [[2,-1,-1],\n         [1,5,-1],\n         [1,1,10]\n        ]\n    b = [[-5],[8],[11]]\n    x = [[1],[1],[1]]\n    #testcase.append([gauss_seidel,A,b,x])\n\n    A = [[2,-1,1],[3,3,9],[3,3,5]]\n    b = [[-1],[0],[4]]\n    x = [[0],[0],[0]]\n    #testcase.append([jacob,A,b,x])\n\n    A = [[5,-1,-1],\n         [3,6,2],\n         [1,-1,2]\n        ]\n    b=  [[16],[11],[-2]]\n    x = [[1],[1],[-1]]\n    testcase.append([gauss_seidel,A,b,x,0.001])\n    test()\n", "meta": {"hexsha": "f2ba2da074de862e0972f5cc702d05d35d4109d3", "size": 3814, "ext": "py", "lang": "Python", "max_stars_repo_path": "math/numericalAnalysis/solve-linear-by-iteration.py", "max_stars_repo_name": "snowflying/algorithm-in-python", "max_stars_repo_head_hexsha": "d92e211119b8a786807942c2765058e522e37769", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-14T06:15:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-14T06:15:29.000Z", "max_issues_repo_path": "math/numericalAnalysis/solve-linear-by-iteration.py", "max_issues_repo_name": "snowflying/algorithm-in-python", "max_issues_repo_head_hexsha": "d92e211119b8a786807942c2765058e522e37769", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/numericalAnalysis/solve-linear-by-iteration.py", "max_forks_repo_name": "snowflying/algorithm-in-python", "max_forks_repo_head_hexsha": "d92e211119b8a786807942c2765058e522e37769", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-22T00:32:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T00:32:56.000Z", "avg_line_length": 29.1145038168, "max_line_length": 101, "alphanum_fraction": 0.4643418983, "include": true, "reason": "import numpy", "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338123908151, "lm_q2_score": 0.9019206699387733, "lm_q1q2_score": 0.8672272202403067}}
{"text": "\"\"\"\nEigenvalue demonstration\n\nThe revolving red hand is the input vector and the blue hand is the linearly\ntransformed vector.\n\nFour times every revolution the two hands are parallel (or anti-parallel),\ntwice to each eigenvector of the matrix A.  The ratio of lengths, blue hand\nover red hand, is the corresponding eigenvalue.  The eigenvalue will be\nnegative if the hands are anti-parallel.\n\n\"\"\"\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom math import pi, sin, cos\n\n\ndef eigdemo(A):\n\n    print('matrix A =')\n    print(A)\n    e, x = np.linalg.eig(A)\n\n    print(f\"λ1 = {e[0]:.3f}, x1 = {np.real(x[:,0].flatten())}\")\n    print(f\"λ2 = {e[1]:.3f}, x2 = {np.real(x[:,1].flatten())}\")\n\n    s = np.max(np.abs(e))\n\n    fig, ax = plt.subplots()\n    plt.axis([-s, s, -s, s])\n    plt.grid(True)\n    plt.title('Eigenvector demonstration')\n    plt.xlabel('x')\n    plt.ylabel('y')\n    plt.axis('equal')\n    plt.xlim(-s, s)\n    plt.ylim(-s, s)\n    ax.set_aspect('equal')\n\n    l1, = plt.plot([0, 0], [0, 0], color='r', linewidth=1.5)  # input vector\n    l2, = plt.plot([0, 0], [0, 0], color='b', linewidth=1.5)  # transformed vector\n\n    plt.legend(['$x$', r'${\\bf A} x$'])\n\n\n    def animate(theta):\n\n        x = np.r_[cos(theta), sin(theta)]\n        y = A @ x\n\n        l1.set_xdata([0, x[0]])\n        l1.set_ydata([0, x[1]])\n\n        l2.set_xdata([0, y[0]])\n        l2.set_ydata([0, y[1]])\n\n        return l1, l2\n\n\n    myAnimation = animation.FuncAnimation(\n        fig, animate, frames=np.linspace(\n            0, 2 * pi, 400), blit=True, interval=20, repeat=True)\n\n    plt.show(block=True)\n\ndef main():\n\n    def help():\n        print(\"eigdemo          uses default matrix [1 2; 3 4]\")\n        print(\"eigdemo a b c d  uses matrix [a b; c d]\")\n        sys.exit(0)\n        \n    if len(sys.argv) == 5:\n\n        try:\n            vec = [float(a) for a in sys.argv[1:5]]\n            A = np.reshape(vec, (2,2))\n        except:\n            help()\n\n    elif sys.argv == 1:\n        A = np.array([\n            [1, 2],\n            [3, 3]\n        ])\n\n    else:\n        help()\n\n    eigdemo(A)\n\nif __name__ == \"__main__\":\n    main()", "meta": {"hexsha": "4dfb183a8b9081bf7322a54f68727762a54f9054", "size": 2167, "ext": "py", "lang": "Python", "max_stars_repo_path": "roboticstoolbox/examples/eigdemo.py", "max_stars_repo_name": "Russ76/robotics-toolbox-python", "max_stars_repo_head_hexsha": "4b3e82a6522757ffde1f83aef8d05b3ad475e9de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "roboticstoolbox/examples/eigdemo.py", "max_issues_repo_name": "Russ76/robotics-toolbox-python", "max_issues_repo_head_hexsha": "4b3e82a6522757ffde1f83aef8d05b3ad475e9de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "roboticstoolbox/examples/eigdemo.py", "max_forks_repo_name": "Russ76/robotics-toolbox-python", "max_forks_repo_head_hexsha": "4b3e82a6522757ffde1f83aef8d05b3ad475e9de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8105263158, "max_line_length": 82, "alphanum_fraction": 0.5542224273, "include": true, "reason": "import numpy", "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793907, "lm_q2_score": 0.9019206666433899, "lm_q1q2_score": 0.8672272121008165}}
{"text": "import numpy as np\n\ndef create_matrix():    \n    A = np.mat(\"0 1 2; 1 0 3;4 -3 8\")\n    print(\"A\\n\",A)\n    \n    inverse = np.linalg.inv(A)\n    print(\"inverse of A\\n\", inverse)\n    print(\"Check\\n\", A * inverse)\n\ndef solution():\n    A = np.mat(\"1 -2 1; 0 2 -8; -4 5 9\")\n    print(\"A\\m\",A)\n    b = np.array([0, 8, -9])\n    print(\"b\\n\",b)\n    x = np.linalg.solve(A,b)\n    print(\"Solution:\",x)\n    print(\"Check\\n\",np.dot(A,x))\n\ndef matrix_det():\n    A = np.mat(\"2 3; 4 5\")\n    print(\"|A|(Determinant) = \\n\",np.linalg.det(A))\n\ndef matrix_sigenvalue():\n    A = np.mat(\"3 -2;1 0\")\n    print(\"A\\n\",A)\n    print(\"Eigenvalues\\n\", np.linalg.eigvals(A))\n\n    eigenvalues, eigenvectors = np.linalg.eig(A)\n    print(\"First tuple of eig\\n\", eigenvalues)\n    print(\"Second tuple of eig\\n\", eigenvectors)\n\n    for i in range(len(eigenvalues)):\n        print(\"Left\\n\", np.dot(A, eigenvectors[:,i]))\n        print(\"Right\\n\", eigenvalues[i] * eigenvectors[:i])\n        print(\"\")\n\nif __name__ == '__main__':\n    # create_matrix()\n    # solution()\n    # matrix_det()\n    matrix_sigenvalue()\n", "meta": {"hexsha": "9ecc47512324bd7168d3b5db20dcb19fdb2e7e98", "size": 1067, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python3/numpy_use/simple_numpy.py", "max_stars_repo_name": "combofish/chips-get", "max_stars_repo_head_hexsha": "6005f24d09edda3f1f54c6603205b2f854ec3b3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-01T01:56:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T01:56:51.000Z", "max_issues_repo_path": "Python3/numpy_use/simple_numpy.py", "max_issues_repo_name": "combofish/chips-get", "max_issues_repo_head_hexsha": "6005f24d09edda3f1f54c6603205b2f854ec3b3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python3/numpy_use/simple_numpy.py", "max_forks_repo_name": "combofish/chips-get", "max_forks_repo_head_hexsha": "6005f24d09edda3f1f54c6603205b2f854ec3b3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-26T03:32:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T05:29:46.000Z", "avg_line_length": 24.8139534884, "max_line_length": 59, "alphanum_fraction": 0.5641986879, "include": true, "reason": "import numpy", "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147145754999, "lm_q2_score": 0.891811054783143, "lm_q1q2_score": 0.8672101922922255}}
{"text": "import numpy as np\nfrom math import acos,sin,cos,pi,radians\n\ndef spherical_dist(lon_1,lat_1,lon_2,lat_2):\n    \"\"\"\n    Calculate the distance of two postions and return distance in degree\n    \"\"\"\n\n    lon_1,lat_1,lon_2,lat_2 = map(radians,[lon_1,lat_1,lon_2,lat_2])\n    a=acos(sin(lat_1)*sin(lat_2)+cos(lat_1)*cos(lat_2)*cos(lon_2-lon_1))\n    return a*180/pi\n\ndef in_ellipse(xy_list,width,height,angle=0,xy=[0,0]):\n    \"\"\"\n    Find data points inside an ellipse and return index list\n\n    Parameters:\n        xy_list: Points needs to be deteced.\n        width: Width of the ellipse\n        height: Height of the ellipse\n        angle: anti-clockwise rotation angle in degrees\n        xy: the origin of the ellipse\n    \"\"\"\n    if isinstance(xy_list,list):\n        xy_list = np.array(xy_list)\n    if not isinstance(xy_list,np.ndarray):\n        raise Exception(f\"Unrecoginzed data type: {type(xy_list)}, should be list or np.ndarray\")\n    new_xy_list = xy_list.copy()\n    new_xy_list = new_xy_list - xy\n\n    #------------ define coordinate conversion matrix----------\n    theta = angle/180*np.pi         # degree to radians\n    con_mat = np.zeros((2,2))\n    con_mat[:,0] = [np.cos(theta),np.sin(theta)]\n    con_mat[:,1] = [np.sin(theta),-np.cos(theta)]\n\n    tmp = np.matmul(con_mat,new_xy_list.T)\n    con_xy_list = tmp.T\n\n    #------------ check one by one ----------------------------\n    idxs = []\n    for i,[x,y] in enumerate(con_xy_list):\n        if ((x/(width/2))**2+(y/(height/2))**2) < 1:\n            idxs.append(i)\n        \n    return idxs\n\ndef loc_by_width(lon1,lat1,lon2,lat2,width,direction='right'):\n    \"\"\"\n    Calculate the points of a rectangle with width and two tips provided.\n\n    Parameters:\n      lon1,lat1: longitude and latitude of tip 1\n      lon2,lat2: longitude and latitude of tip 2\n    \"\"\"\n    sphe_dist = spherical_dist(lon1,lat1,lon2,lat2)\n    dlon = lon2 - lon1\n    dlat = lat2 - lat1\n    \n    if direction == \"right\":  # extend width to the right \n    \tdelta_lat = -width*(dlon/sphe_dist)    # cos_theta\n    \tdelta_lon =  width*(dlat/sphe_dist)    # sin_theta\n\n    if direction == \"left\":\n    \tdelta_lat =  width*(dlon/sphe_dist)    # cos_theta\n    \tdelta_lon = -width*(dlat/sphe_dist)    # sin_theta\n\n    new_lon1 = lon1 + delta_lon\n    new_lat1 = lat1 + delta_lat\n    new_lon2 = lon2 + delta_lon\n    new_lat2 = lat2 + delta_lat\n\n    return new_lon1,new_lat1,new_lon2,new_lat2\n", "meta": {"hexsha": "c9d7a44444135c1c4f560d2aa2177237066b94cb", "size": 2405, "ext": "py", "lang": "Python", "max_stars_repo_path": "cuhk_seis/geometry.py", "max_stars_repo_name": "zijinping/relocation", "max_stars_repo_head_hexsha": "7de003ee1ef8587e8fcbeba1edd967cdf4c00637", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cuhk_seis/geometry.py", "max_issues_repo_name": "zijinping/relocation", "max_issues_repo_head_hexsha": "7de003ee1ef8587e8fcbeba1edd967cdf4c00637", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cuhk_seis/geometry.py", "max_forks_repo_name": "zijinping/relocation", "max_forks_repo_head_hexsha": "7de003ee1ef8587e8fcbeba1edd967cdf4c00637", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5, "max_line_length": 97, "alphanum_fraction": 0.6295218295, "include": true, "reason": "import numpy", "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147193720649, "lm_q2_score": 0.8918110368115781, "lm_q1q2_score": 0.867210179094041}}
{"text": "\"\"\"\n@author: Rowan Parker\n@date: 03/05/2022\n\"\"\"\nimport numpy as np\n\ndef power_method(A, x, k, scale=True, debug=False):\n    \"\"\"\n    Power method for finding dominant eigenvectors and eigenvalues.\n\n    Parameters\n    ----------\n    A : n × n matrix\n        Must have a dominant eigenvalue.\n    x : n × 1 non-zero vector\n        An initial approximation for the dominant eigenvector.\n    k : number of iterations to perform\n    scale : boolean, optional\n        Use scaling. The default is True.\n    debug : boolean, optional\n        Enable debugging print statements. The default is False.\n\n    Returns\n    -------\n    (dominant eigenvalue, dominant eigenvector)\n    \"\"\"\n    for i in range(k):\n        if debug:\n            print(\"step_{}: x = \\n{}\".format(i, x))\n\n        x = A*x\n        if scale:\n            x = np.divide(x, np.max(x))\n\n    eigenvalue = np.dot(np.squeeze(np.asarray(A*x)),\n                        np.squeeze(np.asarray(x)))\n    eigenvalue /= np.dot(np.squeeze(np.asarray(x)),\n                         np.squeeze(np.asarray(x)))\n\n    return eigenvalue, x\n\ndef swaprows(i, j, Ab):\n    (n, m) = Ab.shape\n    temp_row = np.zeros(m)\n\n    temp_row[:] = Ab[i, :]\n    Ab[i, :] = Ab[j, :]\n    Ab[j, :] = temp_row[:]\n\n    return(Ab)\n\ndef gauss_pp(Ab):\n    (n, m) = Ab.shape\n    # Row reduce\n    for k in range(0, n-1):\n        # Find the best pivot using partial pivoting\n        MAX = abs(Ab[k, k])\n        I = k \n        for i in range(k+1, n):\n            m = abs(Ab[i, k])\n            if m > MAX:\n                print(\"Row %d switched with Row %d:\" % ((i+1), (k+1)))\n                MAX = m\n                I = i\n\n        swaprows(I, k, Ab)\n\n        # Continue with row reduction after finding the best pivot\n        for j in range(k+1, n):\n            c = Ab[j, k]/Ab[k, k]\n            Ab[j, :] = Ab[j, :] - c*Ab[k, :]\n\n        print(Ab, \"\\n\")\n\n    # back-substitute [A:b]\n    (n, m) = Ab.shape\n    for i in range(n-1, -1, -1):\n        # subtract constants from solution\n        for j in range(m-1):\n            if j != i:\n                Ab[i, m-1] -= Ab[i, j]\n                Ab[i, j] = 0\n\n        # divide both sides by coefficent\n        Ab[i, m-1] /= Ab[i, i]\n        Ab[i, i] /= Ab[i, i]\n\n        # substitute value back into other rows\n        for k in range(i-1, -1, -1):\n            Ab[k, i] *= Ab[i, m-1]\n\n        # print augmented matrix\n        print(\"After solving for x%d:\\n\" % (i+1), Ab, \"\\n\")\n\n    # print solution\n    print(\"Solution:\", (Ab[:, -1]).reshape(-1))\n\n    return Ab\n\ndef gauss_npp(Ab):\n    (n,m) = Ab.shape\n    #Row Reduce [A:b]\n    for k in range(0, n-1): #produce k-th column of zeros\n        for j in range(k+1, n): #j-th row operation\n            c = Ab[j,k]/Ab[k,k]\n            Ab[j,:] = Ab[j,:] - c*Ab[k,:]\n    \n    # print augmented matrix after row reduction\n    print(\"After row reduction:\\n\", Ab, \"\\n\")\n    \n    # back-substitute [A:b]\n    for i in range(n-1, -1, -1):\n        # subtract constants from solution\n        for j in range(m-1):\n            if j != i:\n                Ab[i, m-1] -= Ab[i, j]\n                Ab[i, j] = 0\n        \n        # divide both sides by coefficent\n        Ab[i, m-1] /= Ab[i, i]\n        Ab[i, i] /= Ab[i, i]\n        \n        # substitute value back into other rows\n        for k in range(i-1, -1, -1):\n            Ab[k, i] *= Ab[i, m-1]\n        \n        # print augmented matrix\n        print(\"After solving for x%d:\\n\" % (i+1), Ab, \"\\n\")\n        \n    # print solution\n    print(\"Solution:\", (Ab[:, -1]).reshape(-1))\n    \n    return Ab\n\ndef LUdecomp(A):\n    (n,m) = A.shape\n    L = eye(n,m)\n    U = zeros((n,m))\n\n    U = A\n    for k in range(n-1):\n        for j in range(k+1, n):\n            L[j, k] = U[j, k] / U[k, k]\n            U[j, :] = U[j, :] - L[j, k] * U[k, :]\n    return (L,U)\n\ndef LUsolve(L, b):\n    n = L.shape[0]\n    y = zeros(n)\n    x = zeros(n)\n\n    for i in range(n):\n        # calculate y[i]\n        y[i] = b[i]\n        for j in range(n):\n            if j != i:\n                y[i] -= L[i, j]\n\n        # substitute forward\n        for k in range(i+1, n):\n            L[k, i] *= y[i]\n\n    for i in range(n-1, -1, -1):\n        # calculate x[i]\n        x[i] = y[i]\n        for j in range(n):\n            if j != i:\n                x[i] -= U[i, j]\n        x[i] /= U[i, i]\n\n        # substitute back\n        for k in range(i-1, -1, -1):\n            U[k, i] *= x[i]\n\n    return x\n", "meta": {"hexsha": "13b1a3ca032a0383b5674a176892c606547691f6", "size": 4380, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear-algebra.py", "max_stars_repo_name": "rowankp/numerical-methods", "max_stars_repo_head_hexsha": "96e6164b783303f11e214edafbb6b1433260568b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear-algebra.py", "max_issues_repo_name": "rowankp/numerical-methods", "max_issues_repo_head_hexsha": "96e6164b783303f11e214edafbb6b1433260568b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear-algebra.py", "max_forks_repo_name": "rowankp/numerical-methods", "max_forks_repo_head_hexsha": "96e6164b783303f11e214edafbb6b1433260568b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8863636364, "max_line_length": 70, "alphanum_fraction": 0.4600456621, "include": true, "reason": "import numpy", "num_tokens": 1317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.912436169406061, "lm_q1q2_score": 0.8671893550746961}}
{"text": "# gaussian elimination with scaled pivoting\n#\n# M. Zingale (2013-02-25)\n\nimport numpy\n\ndef gaussElim(A, b, returnDet=0):\n    \"\"\" perform gaussian elimination with pivoting, solving A x = b A\n        is an NxN matrix, x and b are an N-element vectors.  Note: A\n        and b are changed upon exit to be in upper triangular (row\n        echelon) form \"\"\"\n\n    # b is a vector\n    if not b.ndim == 1:\n        print \"ERROR: b should be a vector\"\n        return None\n\n    N = len(b)\n\n    # A is square, with each dimension of length N\n    if not (A.shape[0] == N and A.shape[1] == N):\n        print \"ERROR: A should be square with each dim of same length as b\"\n        return None\n\n    # allocation the solution array\n    x = numpy.zeros((N), dtype=A.dtype)\n\n    # find the scale factors for each row -- this is used when pivoting\n    scales = numpy.max(numpy.abs(A), 1)\n\n    # keep track of the number of times we swapped rows\n    numRowSwap = 0\n\n    printAb(A, b)\n\n    # main loop over rows\n    for k in range(N):\n        \n        # find the pivot row based on the size of column k -- only consider\n        # the rows beyond the current row\n        rowMax = numpy.argmax(A[k:, k]/scales[k:]) \n        if (k > 0): rowMax += k  # we sliced A from k:, correct for total rows\n\n        # swap the row with the largest scaled element in the current column\n        # with the current row (pivot) -- do this with b too!\n        if not rowMax == k:\n            A[[k, rowMax],:] = A[[rowMax, k],:]\n            b[[k, rowMax]] = b[[rowMax, k]]\n            numRowSwap += 1\n\n        # do the forward-elimination for all rows below the current\n        for i in range(k+1, N):\n            coeff = A[i,k]/A[k,k]\n\n            for j in range(k+1, N):\n                A[i,j] += -A[k,j]*coeff\n\n            A[i,k] = 0.0\n            b[i] += -coeff*b[k]\n        #print A, \"\\n\"\n        printAb(A, b)\n    \n    # back-substitution\n    \n    # last solution is easy\n    x[N-1] = b[N-1]/A[N-1,N-1]\n\n    for i in reversed(range(N-1)):\n        sum = b[i]\n        for j in range(i+1,N):\n            sum += -A[i,j]*x[j]\n        x[i] = sum/A[i,i]\n\n\n    # determinant\n    det = numpy.prod(numpy.diagonal(A))*(-1.0)**numRowSwap\n    \n    if not returnDet:\n        return x\n    else:\n        return x, det\n\n\n\n# for debugging:\n# output: numpy.savetxt(\"test.out\", a, fmt=\"%5.2f\", delimiter=\"  \")\n# convert -font Courier-New-Regular -pointsize 20 text:test.out test.png\n\ndef printAb(A, b):\n    \"\"\" printout the matrix A and vector b in a pretty fashion.  We\n        don't use the numpy print here, because we want to make them\n        side by side\"\"\"\n\n    N = len(b)\n\n    openT = \"/\"\n    closeT = \"\\\\\"\n\n    openB = \"\\\\\"\n    closeB = \"/\"\n\n    # numbers take 6 positions + 2 spaces\n    aFmt = \" %6.3f \"\n    space = 8*\" \"\n\n    line = \"|\" + N*aFmt + \"|\" + space + \"|\" + aFmt + \"|\"\n    top = openT + N*space + closeT  + space + openT + space + closeT\n    bottom = openB + N*space + closeB + space + openB + space + closeB + \"\\n\"\n\n    print top\n    for i in range(N):\n        out = tuple(A[i,:]) + (b[i],)\n        print line % out\n    print bottom\n\n", "meta": {"hexsha": "c11cfc95f45ffe0d2458f9c73c7b05922796e1b4", "size": 3098, "ext": "py", "lang": "Python", "max_stars_repo_path": "others/lin_algebra/gauss.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "others/lin_algebra/gauss.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/lin_algebra/gauss.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 26.7068965517, "max_line_length": 78, "alphanum_fraction": 0.5451904454, "include": true, "reason": "import numpy", "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132747, "lm_q2_score": 0.9161096044278532, "lm_q1q2_score": 0.8671863038501348}}
{"text": "#!/usr/bin/python3\nimport numpy as np\nimport random as rd\nfrom math import *\nimport matplotlib.pyplot as plt\n\n########################################\n####### Méthode des rectangles #########\n########################################\ntests = False\n\n### Exercice 1-a ###\ndef Irg(f, a, b, n):\n    ints = np.linspace(a, b, n + 1)\n    summ = 0\n    for i in range(len(ints) - 1):\n        summ += f(ints[i]) * (ints[i+1] - ints[i])\n    return summ\n\n### Exercice 1-b ###\n# sin x croissante sur [0; \\pi/2] : Irg donne une\n# minoration de l'intégrale.\nsing = Irg(sin, 0, pi/2, 10)\n\n### Exercice 1-c ###\ndef Ird(f, a, b, n):\n    ints = np.linspace(a, b, n + 1)\n    summ = 0\n    for i in range(len(ints) - 1):\n        summ += f(ints[i+1]) * (ints[i+1] - ints[i])\n    return summ\n\n### Exercice 1-d ###\n# sin x croissante sur [0; \\pi/2] : Ird donne une\n# majoration de l'intégrale.\nsind = Ird(sin, 0, pi/2, 10)\n\n### Exercice 1-e ###\n# On peut considérer que c'est un valeur\n# moyenne entre la valeur minimale et la\n# valeur maximale : probablement plus\n# précise.\nsina = .5 * (sind + sing)\n\n### Exercice 2 ###\ndef Er(meth, f, a, b, n, intex, m1):\n    intc = meth(f, a, b, n)\n    err = (b-a) * (b-a) / (2*n) * m1\n    return abs(intex - intc) <= err\n\nif tests:\n    countg = 0\n    countd = 0\n    for n in range(1, 1001):\n        if Er(Irg, sin, 0, pi/2, n, 1, 1):\n            countg += 1\n        if Er(Ird, sin, 0, pi/2, n, 1, 1):\n            countd += 1\n    print(\"Validg : \", countg)\n    print(\"Validd : \", countd)\n\n### Exercice 3-a ###\ndef Irm(f, a, b, n):\n    ints = np.linspace(a, b, n + 1)\n    summ = 0\n    for i in range(len(ints) - 1):\n        summ += f((ints[i] + ints[i+1])/2) * (ints[i+1] - ints[i])\n    return summ\n\n### Exercice 3-b ###\ndef Er2(meth, f, a, b, n, intex, m2):\n    intc = meth(f, a, b, n)\n    err = (b-a) * (b-a) * (b-a) / (24*n*n) * m2\n    return abs(intex - intc) <= err\nif tests:\n    countm = 0\n    for n in range(1, 1001):\n        if Er2(Irm, sin, 0, pi/2, n, 1, 1):\n            countm += 1\n    print(\"Validm : \", countm)\n\n### Exercice 3-c ###\ndef f1(x): return x + 2\ndef f2(x): return x*x\nif tests:\n    print(Irm(f1, 0, 1, 10))\n    print(Irm(f2, 0, 1, 10))\n\n########################################\n######## Méthode des trapèzes ##########\n########################################\ntests = False\n\n### Exercice 1 ###\ndef It(f, a, b, n):\n    ints = np.linspace(a, b, n+1)\n    summ = 0\n    for i in range(len(ints) - 1):\n        summ += (ints[i+1] - ints[i]) * (f(ints[i]) + f(ints[i+1])) / 2\n    return summ\n\n### Exercice 2 ###\ndef Er3(meth, f, a, b, n, intex, m2):\n    intc = meth(f, a, b, n)\n    err = (b-a) * (b-a) * (b-a) / (12*n*n) * m2\n    return abs(intex - intc) <= err\nif tests:\n    count = 0\n    for n in range(1, 1001):\n        if Er3(It, sin, 0, pi/2, n, 1, 1):\n            count += 1\n    print(\"Valid trap : \", count)\n\n### Exercice 3 ###\nif tests:\n    print(It(f1, 0, 1, 10))\n    print(It(f2, 0, 1, 10))\n\n########################################\n######### Méthode de simpson ###########\n########################################\ntests = False\n\n### Exercice 1 ###\ndef Isimp(f, a, b, n):\n    ints = np.linspace(a, b, n+1)\n    summ = 0\n    for i in range(len(ints) - 1):\n        summ += (ints[i+1] - ints[i]) * (f(ints[i])/6 + 2*f((ints[i]+ints[i+1])/2)/3 + f(ints[i+1])/6)\n    return summ\n\n### Exercice 2 ###\ndef Er4(meth, f, a, b, n, intex, m4):\n    intc = meth(f, a, b, n)\n    err = (b-a) * (b-a) * (b-a) * (b-a) * (b-a) / (2880*n*n*n*n) * m4\n    return abs(intex - intc) <= err\nif tests:\n    count = 0\n    for n in range(1, 1001):\n        if Er4(Isimp, sin, 0, pi/2, n, 1, 1):\n            count += 1\n    print(\"Valid simp : \", count)\n\n### Exercice 3 ###\ndef f3(x): return x*x*x\ndef f4(x): return x*x*x*x\nif tests:\n    print(Isimp(f3, 0, 1, 10))\n    print(Isimp(f4, 0, 1, 10))\n\n########################################\n####### Méthode de monte-carlo #########\n########################################\ntests = False\ndef Imont(f, a, b, m, n):\n    count = 0\n    for i in range(n):\n        x = rd.uniform(a, b)\n        y = rd.uniform(0, m)\n        if y < f(x):\n            count += 1\n    return m * (b-a) * count / n\n\ndef f(x): return sqrt(1 - x*x)\nif tests:\n    mpi = 4 * Imont(f, 0, 1, 1, 1000000)\n    print(mpi)\n\n########################################\n########## Graphes d'erreur ############\n########################################\ntests = True\n\ndef plotfn(f, a, b, n, cl = 'blue', lb = ''):\n    xs = np.linspace(a, b, n)\n    ys = [f(x) for x in xs]\n    plt.plot(xs, ys, linewidth = 1, color = cl)\n    plt.text(xs[-1], ys[-1], lb)\n\ndef createfn(m, p):\n    return lambda x: m*x + p\n\ndef calcerr(meth, f, a, b, n, intex):\n    return log(abs(meth(f, a, b, n) - intex))\n\ndef errgraph(mts, f, a, b, n, intex, l):\n    N = 100\n    for m in l:\n        plotfn(createfn(-m, 0), 0, log(n), N, 'red', str(-m))\n\n    i = 0\n    cls = ['blue', 'green', 'orange', 'salmon', 'cyan']\n    my = 0\n    for m in mts:\n        meth = m[0]\n        ys = [calcerr(meth, f, a, b, i, intex) for i in range(1, n+1)]\n        xs = [log(i) for i in range(1, n+1)]\n        plt.plot(xs, ys, linewidth = 2, color = cls[i])\n        plt.text(xs[-1], ys[-1], m[1])\n        i = divmod(i+1, len(cls))[1]\n        my = max(my, ys[0])\n\n    plt.title(\"Error graph\")\n    plt.axis([0, log(n), ys[-1] - 1, my])\n    plt.show()\n\nif tests:\n     errgraph([[Ird,\"ird\"], [Irm,\"irm\"], [It,\"trap\"], [Isimp, \"simp\"]],\n             sin, 0, pi/2, 1000, 1, [.5, 1, 2, 4])\n", "meta": {"hexsha": "2010186a3e3a01cf7a987da1c4d71dc498878b1b", "size": 5437, "ext": "py", "lang": "Python", "max_stars_repo_path": "ipt/int/code.py", "max_stars_repo_name": "lucas8/MPSI", "max_stars_repo_head_hexsha": "edefa2155071910d95633acf87b9f3a9d34f67d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ipt/int/code.py", "max_issues_repo_name": "lucas8/MPSI", "max_issues_repo_head_hexsha": "edefa2155071910d95633acf87b9f3a9d34f67d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ipt/int/code.py", "max_forks_repo_name": "lucas8/MPSI", "max_forks_repo_head_hexsha": "edefa2155071910d95633acf87b9f3a9d34f67d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8904761905, "max_line_length": 102, "alphanum_fraction": 0.4590766967, "include": true, "reason": "import numpy", "num_tokens": 2016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426428022032, "lm_q2_score": 0.8902942188450159, "lm_q1q2_score": 0.8671845337953223}}
{"text": "# logistic distribution is used to describe growth.\n# used extensively in machine learning in logistic regression, neural networks etc.\n# it has three parameters:\n# loc = mean, where peak is. Default = 0.\n# scale = standard deviation, flatness of distribution. Default 1.\n# size = Shape of returned array.\n\nfrom numpy import random\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\narr1 = random.logistic(loc=10, scale=2, size=10)\nprint(arr1)\narr2 = random.normal(loc=10, scale=2, size=10)\nprint(arr2)\nsns.distplot(arr1, hist=False, label='logistic')\nsns.distplot(arr2, hist=False, label='normal')\nplt.show()\n\n# both are near identical, but logistic has more area under tails.\n# i.e. possibility of more occurrence of number that are futher away from mean\n", "meta": {"hexsha": "53c2ff6e951517d6155bc3b557d95edb220943e1", "size": 761, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/Numpy/numpy 24 - logistic distribution.py", "max_stars_repo_name": "omkarsutar1255/Python-Data", "max_stars_repo_head_hexsha": "169d0c54b23d9dd5a7f1aea41ab385121c3b3c63", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/Numpy/numpy 24 - logistic distribution.py", "max_issues_repo_name": "omkarsutar1255/Python-Data", "max_issues_repo_head_hexsha": "169d0c54b23d9dd5a7f1aea41ab385121c3b3c63", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/Numpy/numpy 24 - logistic distribution.py", "max_forks_repo_name": "omkarsutar1255/Python-Data", "max_forks_repo_head_hexsha": "169d0c54b23d9dd5a7f1aea41ab385121c3b3c63", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5909090909, "max_line_length": 83, "alphanum_fraction": 0.7595269382, "include": true, "reason": "from numpy", "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.9046505357435622, "lm_q1q2_score": 0.8671416685220398}}
{"text": "import numpy as np\n\n\ndef get_entropy(x):\n    \"\"\"\n    Also known as Shanon Entropy\n    Reference: https://en.wikipedia.org/wiki/Entropy_(information_theory)\n    \"\"\"\n    unique, count = np.unique(x, return_counts=True, axis=0)\n    probability = count/len(x)\n    entropy = np.sum((-1)*probability*np.log2(probability))\n    return entropy\n\n\ndef get_joint_entropy(x, y):\n    \"\"\"\n    H(Y;X)\n    Reference: https://en.wikipedia.org/wiki/Joint_entropy\n    \"\"\"\n    xy = np.c_[x, y]\n    return get_entropy(xy)\n\n\ndef get_conditional_entropy(y, x):\n    \"\"\"\n    conditional entropy = Joint Entropy - Entropy of X\n    H(Y|X) = H(Y;X) - H(X)\n    Reference: https://en.wikipedia.org/wiki/Conditional_entropy\n    \"\"\"\n    return get_joint_entropy(y, x) - get_entropy(x)\n\n\ndef get_information_gain(y, x):\n    \"\"\"\n    Information Gain, I(Y;X) = H(Y) - H(Y|X)\n    Reference: https://en.wikipedia.org/wiki/Information_gain_in_decision_trees#Formal_definition\n    \"\"\"\n    return get_entropy(y) - get_conditional_entropy(y, x)\n", "meta": {"hexsha": "1988495fd057be1b94dd5a471a20fde1dd0e1165", "size": 1003, "ext": "py", "lang": "Python", "max_stars_repo_path": "nightingale/entropy/get_entropy.py", "max_stars_repo_name": "idin/nightingale", "max_stars_repo_head_hexsha": "84b8f8605d8877707b9e3890bbe4523c6fa2e37d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nightingale/entropy/get_entropy.py", "max_issues_repo_name": "idin/nightingale", "max_issues_repo_head_hexsha": "84b8f8605d8877707b9e3890bbe4523c6fa2e37d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nightingale/entropy/get_entropy.py", "max_forks_repo_name": "idin/nightingale", "max_forks_repo_head_hexsha": "84b8f8605d8877707b9e3890bbe4523c6fa2e37d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7179487179, "max_line_length": 97, "alphanum_fraction": 0.6610169492, "include": true, "reason": "import numpy", "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.98087596269007, "lm_q2_score": 0.8840392771633079, "lm_q1q2_score": 0.8671328770433933}}
{"text": "import math\nimport numpy as np\ndef sigmoid(x):\n    return 1/(1 + np.exp(-x))\n\ndef sigmoid_prime(x):\n    sx = sigmoid(x)\n    return np.multiply(sx, (1 - sx))\n\ndef relu(x):\n    return np.maximum(x, 0)\n\ndef relu_prime(x):\n    return x >= 0\n\nclass NeuralNetwork:\n    def __init__(self, in_dim, hid_dim, out_dim):\n        # np.random.seed(10) # for generating the same results\n        # self.W1 = np.random.rand(hid_dim, in_dim)\n        self.W1 = np.eye(hid_dim, in_dim)\n        # self.W2 = np.random.rand(out_dim, hid_dim)\n        self.W2 = np.eye(out_dim, hid_dim)\n        self.x = None\n        self.W1x = None\n        self.x_1 = None\n        self.W2x_1 = None\n        self.x_2 = None\n\n    def forward(self, x):\n        # print(x)\n        self.x = x\n        # print(self.W1.shape, x.shape)\n        self.W1x = np.dot(self.W1, x)\n        # print(self.W1x)\n        # self.x_1 = relu(self.W1x)\n        self.x_1 = sigmoid(self.W1x)\n        # print(self.x_1)\n        self.W2x_1 = np.matmul(self.W2, self.x_1)\n        # print(self.W2x_1)\n\n        self.x_2 = sigmoid(self.W2x_1)\n        # print(self.x_2)\n\n        return self.x_2\n\n    def loss(self, X, Y):\n        lse = 0\n        for j in range(len(X)):\n            x = X[j]\n            y = Y[j]\n            self.forward(x)\n\n            lse += np.linalg.norm(y - self.x_2)**2\n        return lse\n\n    def gradient_descent(self, X, Y, iterations):\n        for i in range(iterations):\n            loss = self.loss(X, Y)\n            print(\"loss\", i, loss)\n            G2 = np.zeros(self.W2.shape)\n            G1 = np.zeros(self.W1.shape)\n\n            for j in range(len(X)):\n                x = X[j]\n                y = Y[j]\n                self.forward(x)\n\n                # gradients for hidden to output weights\n                # print((y - self.x_2).shape, sigmoid_prime(self.W2x_1).shape)\n                mu2 = np.multiply((y - self.x_2), sigmoid_prime(self.W2x_1))\n                g2 = np.matmul(mu2, np.transpose(self.x_1))\n                # print(\"w1x\", self.W1x)\n\n                # mu1a = relu_prime(self.W1x)\n                mu1a = sigmoid_prime(self.W1x)\n                # print(\"mu1a\", mu1a)\n\n                mu1b = np.dot(np.transpose(self.W2), mu2)\n                # print(\"mu1b\", mu1b)\n\n                mu1 = np.multiply(mu1a, mu1b)\n                # print(\"mu1\", mu1)\n\n                g1 = np.dot(mu1, np.transpose(self.x))\n\n                # print(\"g2\", g2)\n                # print(\"g1\", g1)\n\n                G1 += g1\n                G2 += g2\n\n            self.W2 = self.W2 + G2 #/ len(X)\n            self.W1 = self.W1 + G1 #/ len(X)\n\n# small example\n\n# x = np.random.rand(10, 2, 1)\n# x = [np.random.rand(2, 1) for _ in range(10)]\nx = [np.matrix([[1],[0]]), np.matrix([[0.5],[-0.3]])]\nprint(x)\n\nnn = NeuralNetwork(2, 4, 2)\ny_hat = nn.forward(x[0])\nprint(\"before\", y_hat)\ny_hat = nn.forward(x[1])\nprint(\"before\", y_hat)\n\n# y = [np.random.rand(2, 1) for _ in range(10)]\ny = [np.matrix([[1], [0]]), np.matrix([[0], [1]])]\n# print(y)\nnn.gradient_descent(x, y, 10)\ny_hat = nn.forward(x[0])\nprint(\"after\", y_hat)\ny_hat = nn.forward(x[1])\nprint(\"after\", y_hat)\n\n# framingam example\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#     def gradient_descent(self, x, y, iterations):\n#         for i in range(iterations):\n#             Xi = x\n#             Xj = self.sigmoid(Xi, self.wij)\n#             yhat = self.sigmoid(Xj, self.wjk)\n#             # gradients for hidden to output weights\n#             g_wjk = np.dot(Xj.T, (y - yhat) * self.sigmoid_derivative(Xj, self.wjk))\n#             # gradients for input to hidden weights\n#             g_wij = np.dot(Xi.T, np.dot((y - yhat) * self.sigmoid_derivative(Xj, self.wjk), self.wjk.T) * self.sigmoid_derivative(Xi, self.wij))\n#             # update weights\n#             self.wij += g_wij\n#             self.wjk += g_wjk\n#         print('The final prediction from neural network are: ')\n#         print(yhat)\n#\n# if __name__ == '__main__':\n# neural_network = NeuralNetwork()\n# print('Random starting input to hidden weights: ')\n# print(neural_network.wij)\n# print('Random starting hidden to output weights: ')\n# print(neural_network.wjk)\n# X = np.array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])\n# y = np.array([[0, 1, 1, 0]]).T\n# neural_network.gradient_descent(X, y, 10000)\n\n\n\n", "meta": {"hexsha": "926e8841d67ed233f17d6436de5dd47024401a59", "size": 4250, "ext": "py", "lang": "Python", "max_stars_repo_path": "Compiler/ml_simple_test.py", "max_stars_repo_name": "tilenmarc/SCALE-MAMBA", "max_stars_repo_head_hexsha": "7496952269eec1e3aad5fd81582df51651798fe7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Compiler/ml_simple_test.py", "max_issues_repo_name": "tilenmarc/SCALE-MAMBA", "max_issues_repo_head_hexsha": "7496952269eec1e3aad5fd81582df51651798fe7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Compiler/ml_simple_test.py", "max_forks_repo_name": "tilenmarc/SCALE-MAMBA", "max_forks_repo_head_hexsha": "7496952269eec1e3aad5fd81582df51651798fe7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0736196319, "max_line_length": 146, "alphanum_fraction": 0.5218823529, "include": true, "reason": "import numpy", "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877658567786, "lm_q2_score": 0.8933094003735664, "lm_q1q2_score": 0.8671245060674758}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 24 08:51:47 2019\n\n@author: mhossa12\n\"\"\"\n## https://www.kaggle.com/andyxie/k-means-clustering-implementation-in-python\n# Import necessary libraries\nfrom copy import deepcopy\nimport numpy as np # linear algebra\nfrom matplotlib import pyplot as plt\n# Set three centers, the model should predict similar results\ncenter_1 = np.array([1,1])\ncenter_2 = np.array([5,5])\ncenter_3 = np.array([8,1])\n\n# Generate random data and center it to the three centers\ndata_1 = np.random.randn(200, 2) + center_1\ndata_2 = np.random.randn(200,2) + center_2\ndata_3 = np.random.randn(200,2) + center_3\n\ndata = np.concatenate((data_1, data_2, data_3), axis = 0)\n\nplt.scatter(data[:,0], data[:,1], s=7)\nplt.grid()\nplt.show()\n\n\n# Number of clusters\nk = 3\n# Number of training data\nn = data.shape[0]\n# Number of features in the data\nc = data.shape[1]\n\n# Generate random centers, here we use sigma and mean to ensure it represent the whole data\nmean = np.mean(data, axis = 0)\nstd = np.std(data, axis = 0)\ncenters = np.random.randn(k,c)*std + mean\n\n# Plot the data and the centers generated as random\nplt.scatter(data[:,0], data[:,1], s=7)\nplt.scatter(centers[:,0], centers[:,1], marker='*', c='g', s=150)\n\nplt.grid()\nplt.show()\n\n\n\ncenters_old = np.zeros(centers.shape) # to store old centers\ncenters_new = deepcopy(centers) # Store new centers\n\ndata.shape\nclusters = np.zeros(n)\ndistances = np.zeros((n,k))\n\nerror = np.linalg.norm(centers_new - centers_old)\n\n# When, after an update, the estimate of that center stays the same, exit loop\nwhile error != 0:\n    # Measure the distance to every center\n    for i in range(k):\n        distances[:,i] = np.linalg.norm(data - centers[i], axis=1)\n    # Assign all training data to closest center\n    clusters = np.argmin(distances, axis = 1)\n    \n    centers_old = deepcopy(centers_new)\n    # Calculate mean for every cluster and update the center\n    for i in range(k):\n        centers_new[i] = np.mean(data[clusters == i], axis=0)\n    error = np.linalg.norm(centers_new - centers_old)\ncenters_new    \n\n# Plot the data and the centers generated as random\nplt.scatter(data[:,0], data[:,1], s=7)\nplt.scatter(centers_new[:,0], centers_new[:,1], marker='*', c='g', s=150)\n\nplt.grid()\nplt.show()\n\n\n", "meta": {"hexsha": "41b881ffb98297baa7c9105f62fbd60e273a2f15", "size": 2254, "ext": "py", "lang": "Python", "max_stars_repo_path": "Clustering K-Means/00Develope and Verify a K-Means++ Clustering Model with a Randomly Generated Dataset in Python.py", "max_stars_repo_name": "csitedexperts/DSML_MadeEasy", "max_stars_repo_head_hexsha": "9af03a00fb026930c19737790f603a0b0ae40b7e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-23T11:25:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-23T11:25:44.000Z", "max_issues_repo_path": "Clustering K-Means/00Develope and Verify a K-Means++ Clustering Model with a Randomly Generated Dataset in Python.py", "max_issues_repo_name": "csitedexperts/DSML_MadeEasy", "max_issues_repo_head_hexsha": "9af03a00fb026930c19737790f603a0b0ae40b7e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Clustering K-Means/00Develope and Verify a K-Means++ Clustering Model with a Randomly Generated Dataset in Python.py", "max_forks_repo_name": "csitedexperts/DSML_MadeEasy", "max_forks_repo_head_hexsha": "9af03a00fb026930c19737790f603a0b0ae40b7e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.487804878, "max_line_length": 91, "alphanum_fraction": 0.6912156167, "include": true, "reason": "import numpy", "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.920789673173896, "lm_q1q2_score": 0.8670654226506311}}
{"text": "import sympy as sp\n\nif __name__ == '__main__':\n    j = complex(0, 1)\n    A = sp.Matrix([\n        [1, 0, -1],\n        [0, 1, j],\n        [-1, -j, 0]\n    ])\n\n    A_eigenvectors = A.eigenvects()\n\n    print(f\"A := {A}\", '-'*25, sep='\\n')\n    for eigenvalue, multiplicity, eigenvector in A_eigenvectors:\n        print(f\"lambda = {eigenvalue}, m = {multiplicity}\", eigenvector, '-'*175, sep='\\n')\n\n    E, a, theta = sp.symbols(\"E a theta\")\n    H = sp.Matrix([\n        [E, a, 0],\n        [a, E, a],\n        [0, a, E]\n    ])\n    H_eigenvectors = H.eigenvects()\n\n    print(f\"H := {H}\", '-' * 25, sep='\\n')\n    for eigenvalue, multiplicity, eigenvector in H_eigenvectors:\n        print(f\"lambda = {eigenvalue}, m = {multiplicity}\", eigenvector, '-'*175, sep='\\n')\n\n    R = sp.Matrix([\n        [1, 0, 0],\n        [0, sp.cos(theta), -sp.sin(theta)],\n        [0, sp.sin(theta), sp.cos(theta)]\n    ])\n    RHRinv = R*H*R.inv()\n    RHRinv_eigenvectors = RHRinv.eigenvects()\n\n    print(f\"RHRinv := {RHRinv}\", '-' * 25, sep='\\n')\n    for eigenvalue, multiplicity, eigenvector in RHRinv_eigenvectors:\n        print(f\"lambda = {eigenvalue}, m = {multiplicity}\", eigenvector, '-' * 175, sep='\\n')\n\n    print(H.eigenvals(), RHRinv.eigenvals(), sep='\\n')\n    check = all([e in RHRinv.eigenvals() for e in H.eigenvals()])\n    print(f\"H.eigenvals() == RHRinv.eigenvals(): {check}\")", "meta": {"hexsha": "12ea6268b3960dd0f93682d18fb05e1741d1482d", "size": 1356, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear_algebra/diagonalisation.py", "max_stars_repo_name": "JeremieGince/ProjetPythonPhysique", "max_stars_repo_head_hexsha": "4332eb23dc72fea542b7314d2365d877e0ca51d8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-02-02T02:14:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T23:50:01.000Z", "max_issues_repo_path": "Linear_algebra/diagonalisation.py", "max_issues_repo_name": "JeremieGince/TutorielPython-Manuel", "max_issues_repo_head_hexsha": "e474f5dcecbf3a1e1c7c776b7630f7c168cfd938", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear_algebra/diagonalisation.py", "max_forks_repo_name": "JeremieGince/TutorielPython-Manuel", "max_forks_repo_head_hexsha": "e474f5dcecbf3a1e1c7c776b7630f7c168cfd938", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5348837209, "max_line_length": 93, "alphanum_fraction": 0.5435103245, "include": true, "reason": "import sympy", "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769142064209, "lm_q2_score": 0.8887587831798666, "lm_q1q2_score": 0.8670525511684677}}
{"text": "\"\"\"Probability function\"\"\"\nfrom scipy.stats import norm\n\n# Finding the probability of a discrete value\ndef prob_norm_single_value(discrete_value=None, mean=None,stdev=None):\n    \"\"\"Probability function for a discrete value\"\"\"\n    x_value = norm(loc = mean, scale= stdev).cdf(discrete_value)\n    return x_value\n\n# Finding the probability between two ranges\ndef prob_norm_between_values(lower_val=None, upper_val=None, mean=None,stdev=None):\n    \"\"\"Probability between two values\"\"\"\n    l_value = norm(loc = mean, scale= stdev).cdf(lower_val)\n    u_value = norm(loc = mean, scale= stdev).cdf(upper_val)\n    delta = u_value - l_value\n    return delta\n\n# Finding the probability above a discrete value\ndef prob_norm_above_value(discrete_value=None, mean=None,stdev=None):\n    \"\"\"Probability above a discrete value\"\"\"\n    x_value = norm(loc = mean, scale= stdev).cdf(discrete_value)\n    delta = 1 - x_value\n    return delta\n\ndef main():\n    \"\"\"Main logic flow\"\"\"\n    func_type = input ('Enter the function type (single/range/above): ')\n    lower_val = float ( input(\"Enter the single or lower range (value): \") )\n    if func_type == 'range':\n        upper_val = float ( input(\"Enter the upper range (value): \") )\n    mean = float ( input(\"Enter the mean (value): \") )\n    stdev = float ( input(\"Enter the standard deviation (value): \") )\n    if func_type == 'range':\n        return_value = prob_norm_between_values(\n                lower_val=lower_val,\n                upper_val=upper_val,\n                mean=mean,\n                stdev=stdev\n                )\n        print(f'Probability between {lower_val} and {upper_val} is: {return_value}')\n    elif func_type == 'above':\n        return_value = prob_norm_above_value(\n                discrete_value=lower_val,\n                mean=mean,\n                stdev=stdev\n                )\n        print(f'Probability above {lower_val} is: {return_value}')\n    else:\n        return_value = prob_norm_single_value(\n                discrete_value=lower_val,\n                mean=mean,\n                stdev=stdev\n                )\n        print(f'Probability of {lower_val} is: {return_value}')\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "cec96fb956255b4298223659c132f42f371d491d", "size": 2178, "ext": "py", "lang": "Python", "max_stars_repo_path": "basic_scripts/cdf.py", "max_stars_repo_name": "thomassantosh/monte-carlo-simulations", "max_stars_repo_head_hexsha": "01fa99dcd92e38d8da377f1f7768300382a2d197", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "basic_scripts/cdf.py", "max_issues_repo_name": "thomassantosh/monte-carlo-simulations", "max_issues_repo_head_hexsha": "01fa99dcd92e38d8da377f1f7768300382a2d197", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "basic_scripts/cdf.py", "max_forks_repo_name": "thomassantosh/monte-carlo-simulations", "max_forks_repo_head_hexsha": "01fa99dcd92e38d8da377f1f7768300382a2d197", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9152542373, "max_line_length": 84, "alphanum_fraction": 0.6313131313, "include": true, "reason": "from scipy", "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102580527664, "lm_q2_score": 0.8962513786759491, "lm_q1q2_score": 0.8670427775250475}}
{"text": "from pyomo.environ import *\ninfinity = float('inf')\n\n# Creation of a Concrete Model\nmodel = AbstractModel()\n\n#DEFINE SETS\n# Products\nmodel.F = Set()\n# Nutrients\nmodel.N = Set()\n\n# DEFINE PARAMETERS\n# Cost\nmodel.c = Param(model.F, within = PositiveReals, doc = 'price in $')\n\n# Amount of nutrient\nmodel.a    = Param(model.F, model.N, within = NonNegativeReals)\n\n# Max and Min for each Nutrient\nmodel.Nmin = Param(model.N, within = NonNegativeReals, default = 0.0)\nmodel.Nmax = Param(model.N, within = NonNegativeReals, default = infinity)\n\n\n# Number of servings\nmodel.x = Var(model.F, within = NonNegativeIntegers)\n\n# Minimize z(cost)\ndef cost(model):\n    return sum(model.c[i]*model.x[i] for i in model.F)\nmodel.cost = Objective(rule=cost)\n\n# LIMITS\n\n#Max\ndef nutrients_max(model, j):\n    value = sum(model.a[i,j]*model.x[i] for i in model.F)\n    return value <= model.Nmax[j]\nmodel.nutrient_limit_max = Constraint(model.N, rule=nutrients_max)\n#Min\ndef nutrient_min(model, j):\n    value = sum(model.a[i,j]*model.x[i] for i in model.F)\n    return model.Nmin[j] <= value \nmodel.nutrient_limit_min = Constraint(model.N, rule=nutrient_min)\n\n#def pyomo_postprocess(options=None, instance=None, results=None):\n#    model.x.display()\n\n", "meta": {"hexsha": "b2867b5ec9903ab0adec35bb5e2882188c66d886", "size": 1228, "ext": "py", "lang": "Python", "max_stars_repo_path": "Modulo3Simat/1_ProgramacionLineal/ProgramacionLineal_Pyomo/Pyomo-Diet-master/problems/diet-minimize/minimizecost.py", "max_stars_repo_name": "IntroCursos/MachingLearning", "max_stars_repo_head_hexsha": "a3d858c8c8fbb8b6d3a1cb445cf5045e9971930c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Modulo3Simat/1_ProgramacionLineal/ProgramacionLineal_Pyomo/Pyomo-Diet-master/problems/diet-minimize/minimizecost.py", "max_issues_repo_name": "IntroCursos/MachingLearning", "max_issues_repo_head_hexsha": "a3d858c8c8fbb8b6d3a1cb445cf5045e9971930c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modulo3Simat/1_ProgramacionLineal/ProgramacionLineal_Pyomo/Pyomo-Diet-master/problems/diet-minimize/minimizecost.py", "max_forks_repo_name": "IntroCursos/MachingLearning", "max_forks_repo_head_hexsha": "a3d858c8c8fbb8b6d3a1cb445cf5045e9971930c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0612244898, "max_line_length": 74, "alphanum_fraction": 0.7092833876, "include": true, "reason": "from pyomo", "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102571131692, "lm_q2_score": 0.8962513655129177, "lm_q1q2_score": 0.8670427639488807}}
{"text": "# Question 4 Lab Assignment 2\n# AB Satyaprakash - 180123062\n\n# imports ----------------------------------------------------------------------\nfrom math import log, tan, factorial\nfrom sympy import *\nimport numpy as np\n\n# functions --------------------------------------------------------------------\n\n\ndef f(x):\n    return log(tan(x))/log(10)\n\n\ndef thirdLagrange(x0, x1, x2, x3, val):\n    # Using the values given in the quesiton\n    f0, f1, f2, f3 = 0.1924, 0.2414, 0.2933, 0.3492\n\n    # compute l0(x) with x = val\n    l0 = ((val-x1)*(val-x2)*(val-x3))/((x0-x1)*(x0-x2)*(x0-x3))\n    l1 = ((val-x0)*(val-x2)*(val-x3))/((x1-x0)*(x1-x2)*(x1-x3))\n    l2 = ((val-x0)*(val-x1)*(val-x3))/((x2-x0)*(x2-x1)*(x2-x3))\n    l3 = ((val-x0)*(val-x1)*(val-x2))/((x3-x0)*(x3-x1)*(x3-x2))\n    px = f0*l0 + f1*l1 + f2*l2 + f3*l3\n    return px\n\n\ndef derivative(x0, n):\n    x = symbols('x')\n    f = log(tan(x), 10)\n    fn = f.diff(x, n)\n    fn = lambdify(x, fn)\n    return fn(x0)\n\n\ndef maxError(nodes, x):\n    err = 1\n    for n in nodes:\n        err *= (x-n)\n    err /= factorial(len(nodes))\n    a = min(nodes)\n    b = max(nodes)\n    l = np.linspace(a, b, 250)\n    ret = 0\n    for z in l:\n        der = derivative(z, len(nodes))\n        ret = max(ret, abs(err*der))\n    return ret\n\n\n# ------------------------------------------------------------------------------\n# Use the following values and four-digit rounding arithmetic to construct a third Lagrange polynomial approximation to f(1.09).\n# The function being approximated is f(x) = log10(tan x). Use this knowledge to find a bound for the error in the approximation.\n# f(1.00) = 0.1924, f(1.05) = 0.2414, f(1.10) = 0.2933, f(1.15) = 0.3492.\n# Using f(1.00) = 0.1924, f(1.05) = 0.2414, f(1.10) = 0.2933, f(1.15) = 0.3492\n# and four-digit rounding arithmetic to construct a third Lagrange polynomial approximation for f(1.09)\nx0, x1, x2, x3, val = 1, 1.05, 1.1, 1.15, 1.09\nres = thirdLagrange(x0, x1, x2, x3, val)\nprint('The third Lagrange polynomial approximation for f(1.09) is {}'.format(res))\nprint('The third Lagrange polynomial approximation for f(1.09) rounded to 4 decimal places is {}'.format(round(res, 4)))\n\n# The bound for error in approximation:\nprint('The bound for the error in this approximation is {}'.format(maxError([x0, x1, x2, x3], val)))\n", "meta": {"hexsha": "4180e898aecd03511d7488218d3b7404e88c0810", "size": 2293, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 2/Code/q4.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 2/Code/q4.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 2/Code/q4.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 35.2769230769, "max_line_length": 128, "alphanum_fraction": 0.5573484518, "include": true, "reason": "import numpy,from sympy", "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214491222695, "lm_q2_score": 0.8991213732152423, "lm_q1q2_score": 0.8670420255557274}}
{"text": "import argparse\nfrom math import inf\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Create k random initial center points\ndef randCent(dataSet, k):\n    n = np.shape(dataSet)[1]\n    cpoints = np.zeros((k, n))\n    # create centroid mat\n    for j in range(n):\n        # create random cluster centers, within bounds of each dimension\n        minJ = np.min(dataSet[:, j])\n        rangeJ = float(np.max(dataSet[:, j]) - minJ)\n        cpoints[:, j] = minJ + rangeJ * np.random.rand(k)\n    return cpoints\n\n\n# Euclidean distance\ndef eucDist(pA, pB):\n    return np.linalg.norm(pA - pB)\n\n\n# K-means main method.\ndef kmeans(dataSet, k, distMeasure=eucDist, centerGen=randCent):\n    m = np.shape(dataSet)[0]  # number of data\n    cluResult = np.zeros((m, 2))  # center and distance of each point\n    centers = centerGen(dataSet, k)  # the k centers\n    cluChanged = True\n    while cluChanged:\n        cluChanged = False\n        for i in range(m):\n            minDist = inf\n            minIndex = -1\n            for j in range(k):\n                # Step 1: find the nearest center for each point\n                newDist = distMeasure(centers[j, :], dataSet[i, :])\n                if newDist < minDist:\n                    minDist = newDist\n                    minIndex = j\n            if cluResult[i, 0] != minIndex:\n                cluChanged = True\n                cluResult[i, :] = minIndex, minDist\n        # Step 2: re-evaluate the center points\n        for cent in range(k):\n            ptsInClust = dataSet[np.where(cluResult[:, 0] == cent)]\n            centers[cent, :] = np.mean(ptsInClust, axis=0)\n    return centers, cluResult\n\n\ndef main():\n    data = np.loadtxt('rawdata.csv', delimiter=',')\n    parser = argparse.ArgumentParser(\n        description='K-means clustering program.')\n    parser.add_argument('-k', type=int, default=3,\n                        help='The number of clusters. Default is 3.')\n    args = parser.parse_args()\n    dataSet = data[:, 0:-1]\n    centers, cluResult = kmeans(dataSet, args.k)\n    print('Centers:', centers)\n    print('Clustering result:', cluResult)\n    # Drawing\n    colors=['black', 'blue', 'green', 'lime', 'maroon', 'olive', 'orange', 'purple', 'red', 'teal', 'yellow']\n    np.random.shuffle(colors)\n    for i in range(len(centers)):\n        center=centers[i]\n        cluPoint=dataSet[np.where(cluResult[:,0]==i)]\n        plt.scatter(center[0],center[1],c=colors[i],marker='*')\n        plt.scatter(cluPoint[:,0],cluPoint[:,1], c=colors[i])\n    plt.show()\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "c0d22c3153ec7483e6e8b2ea0b79d0dce954fa5e", "size": 2540, "ext": "py", "lang": "Python", "max_stars_repo_path": "kmeans.py", "max_stars_repo_name": "balingwu/hitml-lab3", "max_stars_repo_head_hexsha": "c862f2e227839fa3b67b900c0ca3f9e97ec2c186", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kmeans.py", "max_issues_repo_name": "balingwu/hitml-lab3", "max_issues_repo_head_hexsha": "c862f2e227839fa3b67b900c0ca3f9e97ec2c186", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kmeans.py", "max_forks_repo_name": "balingwu/hitml-lab3", "max_forks_repo_head_hexsha": "c862f2e227839fa3b67b900c0ca3f9e97ec2c186", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.987012987, "max_line_length": 109, "alphanum_fraction": 0.5881889764, "include": true, "reason": "import numpy", "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214460461697, "lm_q2_score": 0.8991213698363246, "lm_q1q2_score": 0.8670420195315774}}
{"text": "\n# coding: utf-8\n\n# # Solving nonlinear equations (finding roots of functions)\n# Find $x$ such that $f(x) = 0$\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ntol = 1e-10\nmax_steps = 100\nf = lambda x: x**2 - 2.0\ndf = lambda x: 2*x\nprint(\"root of x^2 - 2:\", np.sqrt(2))\n\n# ## Newtons method\n# From:\n# $$ f(x^*) = 0 = f(x_0) + f'(x_0)(x^* - x_0) + \\mathcal{O}(|x^* - x_0|^2) $$\n# we get:\n# $$ x_{n+1} \\leftarrow x_n - \\frac{f(x_n)}{f'(x_n)}$$\n\ndef newton(f, df, x0, tol=tol, max_steps=max_steps):\n    x = x0\n    step = 0\n    while True:\n        x_new = x - f(x)/df(x)\n        if abs(x - x_new) <= tol or step == max_steps:\n            return x_new, step\n        x = x_new\n        step += 1\n\nprint(\"newton:\", newton(f, df, 10.0))\n\n# ## Bisection\n# We have two points $a$ and $b$. Now we compute the point between thous $c = \\frac{a + b}{2}$. If $f(c)$ has the same sign as $f(a)$ then we can use $c$ as our new $a$, if $f(c)$ as the same sign as $f(b)$ we can use $c$ as our new $b$.\n\ndef shrink_interval(f, a, b, c):\n    if np.sign(f(c)) == np.sign(f(a)):\n        return c, b\n    else:\n        return a, c\n\ndef bisect(f, a, b, tol=tol, max_steps=max_steps):\n    step = 0\n    assert np.sign(f(a)) != np.sign(f(b))\n    while True:\n        c = (a + b)/2\n        if abs(a - b) <= tol or step == max_steps or f(c) == 0.0:\n            return c, step\n        a, b = shrink_interval(f, a, b, c)\n        step += 1\n\n\nprint(\"bisection:\", bisect(f, 0.0, 10.0, tol=1e-15, max_steps=200))\n\n\n# ## Secant method\n# We have two points $a$ and $b$. Then we can approx. the root between these points by the root of the secant between the points.\n# The secant hits $(a, f(a))$ and $(b, f(b))$.\n# $$m = \\frac{f(a) - f(b)}{a - b}$$\n# $$b = f(a) - m a$$\n# $$ 0 = mx + b \\Rightarrow x = -\\frac{b}{m}$$\n\ndef secant_root(f, a, b):\n    m = (f(a) - f(b))/(a - b)\n    d = f(a) - m*a\n    return -d/m\n\ndef secant(f, x0, x1, tol=tol, max_steps=max_steps):\n    step = 0\n    while True:\n        x2 = secant_root(f, x0, x1)\n        if abs(x1 - x2) <= tol or step == max_steps:\n            return x2, step\n        x0, x1 = x1, x2\n        step += 1\n\nprint(\"secant:\", secant(f, 0.0, 10.0))\n\n# ## Regula falsi (false position)\n# Lets combine secant and bisection!\n#\n# Start with an interval $(a_0,b_0)$ where $sgn(f(a_0)) \\neq sgn(f(b_0))$\n# - Find root of the secant $c$ between $a_0$ and $b_0$\n# - We are done if $f(c) = 0$ or we reached some tolerance.\n# - Choose $a_1 = c$ if $sgn(f(c)) = sgn(f(a))$ otherwise choose $b_1 = c$ if $sgn(f(c)) = sgn(f(b))$\n\ndef regula_falsi(f, a, b, tol=tol, max_steps=max_steps):\n    assert np.sign(a) != np.sign(b)\n    step = 0\n    while True:\n        c = secant_root(f, a, b)\n        if min(abs(a - c), abs(b - c)) <= tol or c == 0.0 or step == max_steps:\n            return c, step\n        a, b = shrink_interval(f, a, b, c)\n        step += 1\n\nprint(\"regula_falsi:\", regula_falsi(f, 0.0, 10.0))\n\n# ## Fixpoint iteration\n# Instead of solving $f(x) = 0$ for $x$, we turn this equation into $g(x) = x$ and then compute $x_{n + 1} = g(x_n)$ for some sufficently large $n$.\n\ndef fixpoint(g, x, tol=tol, max_steps=max_steps, debug=False):\n    step = 0\n    while True:\n        new_x = g(x)\n        if debug:\n            print(x, new_x)\n        if abs(x - new_x) <= tol or step == max_steps:\n            return new_x, step\n        x = new_x\n        step += 1\n\n# $$f(x) = x^2 - 2$$\n# $$x^2 - 2 = 0$$\n# $$g(x) = x^2 + x - 2$$\n# $$x = x^2 + x - 2$$\n\nfixpoint(lambda x: x**2 + x - 2., 1.4, max_steps=10, debug=True)\n\n# $$f(x) = sin(x)$$\n# $$sin(x) = 0$$\n# $$g(x) = sin(x) + x$$\n# $$x = sin(x) + x$$\n\n# In[15]:\n\nfixpoint(lambda x: np.sin(x) + x, 1.0, debug=True)\n", "meta": {"hexsha": "efa6ca7f2bbb692eb57f53e419fceb91ae75de1c", "size": 3652, "ext": "py", "lang": "Python", "max_stars_repo_path": "rootfinding.py", "max_stars_repo_name": "cosmo-jana/numerics-physics-stuff", "max_stars_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-16T16:35:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T16:35:35.000Z", "max_issues_repo_path": "rootfinding.py", "max_issues_repo_name": "cosmo-jana/numerics-physics-stuff", "max_issues_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rootfinding.py", "max_forks_repo_name": "cosmo-jana/numerics-physics-stuff", "max_forks_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3100775194, "max_line_length": 237, "alphanum_fraction": 0.5347754655, "include": true, "reason": "import numpy", "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.9136765316406923, "lm_q1q2_score": 0.8670034337110588}}
{"text": "import numpy as np\nimport scipy.sparse as spar\nimport scipy.linalg as la\nfrom scipy.sparse import linalg as sla\n\ndef to_matrix(filename,n):\n    '''\n    Return the nxn adjacency matrix described by datafile.\n    INPUTS:\n    datafile (.txt file): A .txt file describing a directed graph. Lines\n        describing edges should have the form '<from node>\\t<to node>\\n'.\n        The file may also include comments.\n    n (int): The number of nodes in the graph described by datafile\n    RETURN:\n        Return a SciPy sparse `dok_matrix'.\n    '''\n    pass\n\ndef calculateK(A,N):\n    '''\n    Compute the matrix K as described in the lab.\n    Input:\n        A (array): adjacency matrix of an array\n        N (int): the datasize of the array\n    Return:\n        K (array)\n    '''\n    pass\n\ndef iter_solve(adj, N=None, d=.85, tol=1E-5):\n    '''\n    Return the page ranks of the network described by `adj`.\n    Iterate through the PageRank algorithm until the error is less than `tol'.\n    Inputs:\n    adj - A NumPy array representing the adjacency matrix of a directed graph\n    N (int) - Restrict the computation to the first `N` nodes of the graph.\n            Defaults to N=None; in this case, the entire matrix is used.\n    d     - The damping factor, a float between 0 and 1.\n            Defaults to .85.\n    tol  - Stop iterating when the change in approximations to the solution is\n        less than `tol'. Defaults to 1E-5.\n    Returns:\n    The approximation to the steady state.\n    '''\n    pass\n\ndef eig_solve( adj, N=None, d=.85):\n    '''\n    Return the page ranks of the network described by `adj`. Use the\n    eigenvalue solver in \\li{scipy.linalg} to calculate the steady state\n    of the PageRank algorithm\n    Inputs:\n    adj - A NumPy array representing the adjacency matrix of a directed graph\n    N - Restrict the computation to the first `N` nodes of the graph.\n            Defaults to N=None; in this case, the entire matrix is used.\n    d     - The damping factor, a float between 0 and 1.\n            Defaults to .85.\n    Returns:\n    The approximation to the steady state.\n    '''\n    pass\n    \ndef team_rank(filename='ncaa2013.csv'):\n    '''\n    Use your iterative PageRank solver to predict the rankings of the teams in\n    the given dataset of games.\n    The dataset should have two columns, representing winning and losing teams.\n    Each row represents a game, with the winner on the left, loser on the right.\n    Parse this data to create the adjacency matrix, and feed this into the\n    solver to predict the team ranks.\n    Inputs:\n    filename (optional) - The name of the dataset.\n    Returns:\n    ranks - A list of the ranks of the teams in order \"best\" to \"worst\"\n    teams - A list of the names of the teams, also in order \"best\" to \"worst\"\n    '''\n    pass\n", "meta": {"hexsha": "7dbb741815b105e7962a515c42d975f87632a899", "size": 2785, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol1B/PageRank/spec.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vol1B/PageRank/spec.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vol1B/PageRank/spec.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 35.7051282051, "max_line_length": 80, "alphanum_fraction": 0.6657091562, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.9136765298777718, "lm_q1q2_score": 0.8670034333581055}}
{"text": "from __future__ import print_function\n\nimport numpy as np\nfrom scipy import stats\nimport matplotlib.pyplot as plt\n\n# ========== HW07 SOLUTION [Python2/3] ========== #\n\n\n# ========== 1 ========== #\n\na = np.array([0.5507979, 0.70814782, 0.29090474, 0.51082761, 0.89294695, 0.89629309, 0.12558531, 0.20724288, 0.0514672, 0.44080984])\nb = np.array([-0.04381817, -0.47721803, -1.31386475, 0.88462238, 0.88131804, 1.70957306, 0.05003364, -0.40467741, -0.54535995, -1.54647732])\n\n# K-S 2 sample test\n# null hypothesis: a and b are sampled from the same distribution\nkstest = stats.ks_2samp(a, b)\nkstest.pvalue < 0.05  # True; reject null hypothesis.\n# conclude a and b are NOT from the same distribution.\n\n# a histogram can show visually that they are not from the same distribution.\nplt.figure()\nplt.hist(a)\nplt.hist(b)\nplt.show()\n\n# ========== 2 ========== #\n\nnp.random.seed(121)\nbinom_mars = stats.binom(100, 0.0925)\nmars_rv = binom_mars.rvs(10)\nprint(np.mean(mars_rv))\nprint(binom_mars.cdf(10.0))\n\n# ========== 3 ========== #\n\nrv = np.load('Aluminum_youngs_moduli.npy')\nest_loc = np.mean(rv)\nest_scale = np.std(rv)\n\n# fitting different distributions\nnorm_param = stats.norm.fit(rv)\nlaplace_param = stats.laplace.fit(rv)\nmaxwell_param = stats.maxwell.fit(rv)\nlogistic_param = stats.logistic.fit(rv)\n\n# plot PDFs\nx = np.linspace(10, 150, 200)\nplt.figure()\nplt.hist(rv, bins=21, normed=True)\nplt.plot(x, stats.norm.pdf(x, *norm_param), label='norm')\nplt.plot(x, stats.maxwell.pdf(x, *maxwell_param), label='maxwell_param')\nplt.plot(x, stats.logistic.pdf(x, *logistic_param), label='logistic_param')\nplt.plot(x, stats.laplace.pdf(x, *laplace_param), label='laplace')\nplt.legend()\nplt.show()\n\n# plot CDFs\nplt.figure()\nplt.hist(rv, cumulative=True, bins=21, normed=True)\nplt.plot(x, stats.norm.cdf(x, *norm_param), label='norm')\nplt.plot(x, stats.maxwell.cdf(x, *maxwell_param), label='maxwell_param')\nplt.plot(x, stats.logistic.cdf(x, *logistic_param), label='logistic_param')\nplt.plot(x, stats.laplace.cdf(x, *laplace_param), label='laplace')\nplt.legend()\nplt.show()\n\n# visually, we can eliminate the Maxwell distribution\n\n# K-S tests\nks_norm = stats.kstest(rv, 'norm', norm_param)\nks_laplace = stats.kstest(rv, 'laplace', laplace_param)\nks_maxwell = stats.kstest(rv, 'maxwell', maxwell_param)\nks_logistic = stats.kstest(rv, 'logistic', logistic_param)\n\n# ks_norm.pvalue -> 0.00016185237120902585\n# ks_laplace.pvalue -> 0.75696987136141258\n# ks_maxwell,pvalue -> 0.0\n# ks_logistic.pvalue -> 0.14502969211826544\n\n# with alpha=0.05, accept either the laplace or logistic.\n# however, it is clear to be laplace due to the high p-value.\n\n# note that we are looking for a LARGE p-value\n# to accept the null hypothesis of coming from that distribution.\n", "meta": {"hexsha": "c0e3786521090e85e3d1062be783b70dda813f19", "size": 2739, "ext": "py", "lang": "Python", "max_stars_repo_path": "homework_solutions/hw07_solution.py", "max_stars_repo_name": "mateusza/Introduction-to-Python-Numerical-Analysis-for-Engineers-and-Scientist", "max_stars_repo_head_hexsha": "a27144cc8742e67af215e8de781bd208cc1f7436", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 101, "max_stars_repo_stars_event_min_datetime": "2017-11-28T15:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:59:49.000Z", "max_issues_repo_path": "homework_solutions/hw07_solution.py", "max_issues_repo_name": "mateusza/Introduction-to-Python-Numerical-Analysis-for-Engineers-and-Scientist", "max_issues_repo_head_hexsha": "a27144cc8742e67af215e8de781bd208cc1f7436", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-12-16T19:41:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-16T19:41:39.000Z", "max_forks_repo_path": "homework_solutions/hw07_solution.py", "max_forks_repo_name": "mateusza/Introduction-to-Python-Numerical-Analysis-for-Engineers-and-Scientist", "max_forks_repo_head_hexsha": "a27144cc8742e67af215e8de781bd208cc1f7436", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 54, "max_forks_repo_forks_event_min_datetime": "2017-12-15T19:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T23:36:55.000Z", "avg_line_length": 31.8488372093, "max_line_length": 140, "alphanum_fraction": 0.7137641475, "include": true, "reason": "import numpy,from scipy", "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214137, "lm_q2_score": 0.9136765140114859, "lm_q1q2_score": 0.8670034222620493}}
{"text": "import numpy as np\r\n\r\n# Core functions for logistics regression\r\n\r\ndef sigmoid(z):\r\n    return 1 / (1 + np.exp(-z))\r\n\r\ndef hypothesis(X, theta):\r\n    return X @ theta\r\n\r\ndef cost(theta,X,y):\r\n    m,n = X.shape\r\n    hx = sigmoid(hypothesis(X,theta.reshape(len(theta),1)))\r\n    return np.sum((-y * np.log(hx)) - ((1-y) * np.log(1-hx))) * 1/m\r\n\r\ndef gradient(theta, X,y):\r\n    m,n = X.shape\r\n    hx = sigmoid(hypothesis(X,theta.reshape(len(theta),1)))\r\n    g = ((hx - y).T @ X) * 1/m\r\n    return g.flatten() if theta.ndim==1 else g\r\n\r\ndef map_features(x1,x2,degree):\r\n    features = np.ones((len(x1),1))\r\n    for i in range(1,degree+1):        \r\n        for j in range(0,i+1):\r\n            z = np.power(x1 , (i-j)) * np.power(x2 , j)\r\n            features = np.hstack([features,z])\r\n    return features\r\n\r\ndef cost_regularized(theta, X, y, lmbda):\r\n    m,n = X.shape\r\n    n_cost = cost(theta,X,y)\r\n    n_cost += np.sum((theta[2:len(theta):] ** 2)) * (lmbda/(2*m))\r\n    return n_cost\r\n\r\ndef gradient_regularized(theta,X,y,lmbda):\r\n    grad = gradient(theta,X,y)\r\n    m,n = X.shape\r\n    return grad + np.hstack([[[0]], ((lmbda/m) *  theta[1:,:]).T])", "meta": {"hexsha": "cb2aff73f00d5a583b296c2abafe86e3b342ec95", "size": 1144, "ext": "py", "lang": "Python", "max_stars_repo_path": "logistics/notebooks/api.py", "max_stars_repo_name": "vickykatoch/py-ml-scratchpad", "max_stars_repo_head_hexsha": "e4de515b657971f7889d73e09a1308f91856c09f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "logistics/notebooks/api.py", "max_issues_repo_name": "vickykatoch/py-ml-scratchpad", "max_issues_repo_head_hexsha": "e4de515b657971f7889d73e09a1308f91856c09f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logistics/notebooks/api.py", "max_forks_repo_name": "vickykatoch/py-ml-scratchpad", "max_forks_repo_head_hexsha": "e4de515b657971f7889d73e09a1308f91856c09f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3333333333, "max_line_length": 68, "alphanum_fraction": 0.5594405594, "include": true, "reason": "import numpy", "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561658682131, "lm_q2_score": 0.8947894731166139, "lm_q1q2_score": 0.8669222981830011}}
{"text": "#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n# @Date    : Aug-13-20 17:12\r\n# @Author  : Your Name (you@example.org)\r\n# @RefLink : https://numpy.org/doc/stable/reference/generated/numpy.linalg.eig.html#numpy.linalg.eig\r\n# @RefLink : https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html\r\n\r\nimport numpy as np\r\n\r\n\r\ndef solve_test():\r\n    \"\"\"solve equation a * x = b\r\n    \"\"\"\r\n    a = np.array([[3, 1], [1, 2]])\r\n    b = np.array([9, 8])\r\n    x = np.linalg.solve(a, b)\r\n    print(f\"x:{x}\")\r\n\r\n\r\ndef eigen_test():\r\n    \"\"\"\r\n    v: The normalized (unit “length”) eigenvectors, such that the column v[:,i] is the eigenvector corresponding to the eigenvalue w[i].\r\n    \"\"\"\r\n    # A = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\r\n    A = np.asarray([[1, 2], [3, 4]])\r\n    print(f\"A:{A}\")\r\n\r\n    w, v = np.linalg.eig(A)\r\n\r\n    print(f\"w:{w}\")\r\n    print(f\"v:{v}\")\r\n    A_restore = np.dot(np.dot(v, np.diag(w)), np.linalg.inv(v))\r\n    print(f\"A_restore:{A_restore}\")\r\n\r\n    error = np.sum(A_restore-A)\r\n    print(f\"error:{error}\")\r\n\r\n\r\ndef main():\r\n    eigen_test()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n", "meta": {"hexsha": "182f7132b97bd70f1f65bd81ccb42b003feb0f16", "size": 1125, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_basics/numpy-eigen.py", "max_stars_repo_name": "AI-Huang/deeplearning_basics", "max_stars_repo_head_hexsha": "0c0f45daaab42a25d2cd047cbecdca4f4bc7df59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-27T08:43:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T08:43:59.000Z", "max_issues_repo_path": "numpy_basics/numpy-eigen.py", "max_issues_repo_name": "AI-Huang/deeplearning_basics", "max_issues_repo_head_hexsha": "0c0f45daaab42a25d2cd047cbecdca4f4bc7df59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy_basics/numpy-eigen.py", "max_forks_repo_name": "AI-Huang/deeplearning_basics", "max_forks_repo_head_hexsha": "0c0f45daaab42a25d2cd047cbecdca4f4bc7df59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0, "max_line_length": 137, "alphanum_fraction": 0.5564444444, "include": true, "reason": "import numpy", "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140616, "lm_q2_score": 0.9005297894548548, "lm_q1q2_score": 0.8669158135250781}}
{"text": "import numpy as np\n\n\ndef unit_step(t):\n    \"\"\" Takes time as argument and returns a unit-step function \"\"\"\n    return 1*(t>=0)\n\ndef dirac_delta(t,Delta=1e-3):\n\t\n\tx_t = (1/Delta)*(unit_step(t+Delta/2) - unit_step(t-Delta/2) )\n\treturn x_t\n\ndef Fourier_Transfrom(x_t,t):\n\t\"\"\" Computes CTFT using FFT algorithm.\n\tFrequency and amplitude are scaled appropriately.\n\tIt is assumed that the time varible is equispaced.\n\tNumpy FFT algorithm is used to compute the Fourier Transfrom,\n\ttherefore it is also assumed that the signal is periodic in time\n\twith a period T_range. \n\tNote that you should define the time from -T_range/2 to +T_range/2\"\"\"\n\t\n\tN_pts = np.size(x_t)\n\tT_range = t.max() - t.min()\n\t\n\tdelta_t = T_range/N_pts\n\t\n\tX_fft = np.fft.fft(x_t)\n\tX_fft = np.fft.fftshift(X_fft)\n\tX_omega = X_fft*delta_t\n\t\n\tomega = (2*np.pi/delta_t)*np.fft.fftshift(np.fft.fftfreq(N_pts))\n\t#omega = (2*np.pi/delta_t)*np.fft.fftfreq(N_pts)\n\t\n\treturn X_omega, omega\n\t\ndef Inverse_Fourier_Transform(X_omega,omega):\n\t\"\"\"Computes and returns continuous inverse Fourier Transfrom using numpy\n\tifft function. Time and frequency are scaled appropriately.\"\"\"\n\t\n\tomega_range = omega.max() - omega.min()\n\tdelta_omega = omega_range/np.size(omega)\n\t\n\tx_t_ifft = np.fft.ifft(np.fft.fftshift(X_omega))*omega_range/(2*np.pi)\n\tt_ifft = (2*np.pi/delta_omega)*np.fft.fftshift(np.fft.fftfreq(np.size(omega)))\n\treturn x_t_ifft, t_ifft\n\n", "meta": {"hexsha": "26c0f325497967fa48085ad0eae21c7d68d35a80", "size": 1394, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/skmd/signals.py", "max_stars_repo_name": "sarang-IITKgp/scikit-microwave-design", "max_stars_repo_head_hexsha": "a8567c2d40eebde93af5989c43d6e3008167e137", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/skmd/signals.py", "max_issues_repo_name": "sarang-IITKgp/scikit-microwave-design", "max_issues_repo_head_hexsha": "a8567c2d40eebde93af5989c43d6e3008167e137", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/skmd/signals.py", "max_forks_repo_name": "sarang-IITKgp/scikit-microwave-design", "max_forks_repo_head_hexsha": "a8567c2d40eebde93af5989c43d6e3008167e137", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6595744681, "max_line_length": 79, "alphanum_fraction": 0.7274031564, "include": true, "reason": "import numpy", "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673113726775, "lm_q2_score": 0.9005297841157157, "lm_q1q2_score": 0.8669158112783766}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"Quadrature implementations\"\"\"\n\nfrom __future__ import division\n\nimport numpy as np\n\nfrom typing import Tuple\nfrom .typing import ArrayLike\n\ndef clenshaw_curtis(n: int, a: float = -1.0, b: float = 1.0) -> Tuple[ArrayLike,ArrayLike]:\n    \"\"\"\n    Computes the points and weights for a Clenshaw-Curtis integration\n    from a to b. In other words, for the approximation to the integral\n\n    \\int_a^b f(x) dx \\approx \\sum_{i=0}^{n} w_i f(x_i)\n\n    with the Clenshaw-Curtis quadrature, this function returns the\n    positions x_i and the weights w_i.\n    \"\"\"\n    assert b > a and n > 1\n\n    npoints = n\n    nsegments = n - 1\n    theta = np.pi * np.flip(np.arange(npoints)) / nsegments\n    xx = np.cos(theta) * 0.5 * (b - a) + 0.5 * (a + b)\n\n    wcc0 = 1.0/(nsegments*nsegments - 1 + (nsegments%2))\n\n    # build v vector\n    v = np.zeros(nsegments)\n    v[:nsegments//2] = 2.0/(1.0 - 4.0 * np.arange(nsegments//2)**2)\n    v[nsegments//2] = (nsegments - 3) / (2 * (nsegments//2) - 1) - 1\n\n    kk = np.arange(1, npoints//2)\n    v[nsegments-kk] = np.conj(v[kk])\n\n    # build g vector\n    g = np.zeros(nsegments)\n    g[:nsegments//2] = -wcc0\n    g[nsegments//2] = wcc0 * ( (2 - (nsegments%2)) * nsegments - 1 )\n    g[nsegments-kk] = np.conj(g[kk])\n\n    h = v + g\n    wcc = np.fft.ifft(h)\n\n    # sanity check\n    imag_norm = np.linalg.norm(np.imag(wcc))\n    assert imag_norm < 1e-14\n\n    out = np.zeros(npoints)\n    out[:nsegments] = np.real(wcc)\n    out[nsegments] = out[0]\n    out = np.flip(out) # might be redundant, but for good measure\n    out *= 0.5 * (b - a)\n\n    return xx, out\n\ndef midpoint(n: int, a: float = -1.0, b: float = 1.0) -> Tuple[ArrayLike,ArrayLike]:\n    \"\"\"\n    Returns the points and weights for a midpoint integration\n    from a to b. In other words, for the approximation to the integral\n\n    \\int_a^b f(x) dx \\approx \\frac{b-a}{n} \\sum_{i=0}^n f((x_0 + x_1)/2)\n    \"\"\"\n    assert b > a and n > 1\n\n    weights = np.ones(n) * (b - a) / n\n    points = a + ((b - a) / n * (np.arange(n) + 0.5))\n\n    return points, weights\n\ndef trapezoid(n: int, a: float = -1.0, b: float = 1.0) -> Tuple[ArrayLike,ArrayLike]:\n    \"\"\"\n    Returns the points and weights for a trapezoid integration\n    from a to b. In other words, for the approximation to the integral\n\n    \\int_a^b f(x) dx \\approx \\frac{b-a}{n} \\sum_{i=0}^n f((x_0 + x_1)/2)\n    \"\"\"\n    assert b > a and n > 1\n\n    ninterval = n - 1\n\n    weights = np.ones(n) * (b - a) / ninterval\n    weights[0] *= 0.5\n    weights[-1] *= 0.5\n    points = a + ((b - a) / ninterval) * np.arange(n)\n\n    return points, weights\n\ndef simpson(n: int, a: float = -1.0, b: float = 1.0) -> Tuple[ArrayLike,ArrayLike]:\n    \"\"\"\n    Returns the points and weights for a simpson rule integration\n    from a to b. In other words, for the approximation to the integral\n\n    \\int_a^b f(x) dx \\approx \\frac{b-a}{n} \\sum_{i=0}^n f((x_0 + x_1)/2)\n    \"\"\"\n    assert b > a and n > 1\n\n    if n%2 != 1:\n        raise Exception(\"Simpson's rule must be defined with an odd number of points (even number of intervals)\")\n\n    ninterval = n - 1\n\n    weights = np.ones(n)\n    for i in range(1, ninterval-1, 2):\n        weights[i] = 4.0\n        weights[i+1] = 2.0\n    weights[ninterval-1] = 4.0\n    weights *= (b-a) / ninterval / 3.0\n\n    points = a + ((b - a) / ninterval) * np.arange(n)\n\n    return points, weights\n\ndef quadrature(n: int, a: float = -1.0, b: float = 1.0, method: str = \"gl\") -> Tuple[ArrayLike,ArrayLike]:\n    \"\"\"\n    Returns a quadrature rule for the specified method and bounds\n    \"\"\"\n    if method.lower() == \"cc\" or method.lower() == \"clenshaw-curtis\":\n        return clenshaw_curtis(n, a, b)\n    elif method.lower() == \"gl\" or method.lower() == \"gauss-legendre\":\n        points, weights = np.polynomial.legendre.leggauss(n)\n        points = points * 0.5 * (b - a) + 0.5 * (a + b)\n        weights *= 0.5\n        return points, weights\n    elif method.lower() == \"midpoint\" or method.lower() == \"mp\":\n        return midpoint(n, a, b)\n    elif method.lower() == \"trapezoid\":\n        return trapezoid(n, a, b)\n    elif method.lower() == \"simpson\":\n        return simpson(n, a, b)\n    else:\n        raise Exception(\"Unrecognized quadrature choice\")\n", "meta": {"hexsha": "3333dc132ecba05dd4e2f261357deb70963af831", "size": 4209, "ext": "py", "lang": "Python", "max_stars_repo_path": "mudslide/integration.py", "max_stars_repo_name": "sriz1/mudslide", "max_stars_repo_head_hexsha": "78aa8a1bda4080eacd777da7ff6bcbfd9afe129c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-05T00:17:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T19:44:32.000Z", "max_issues_repo_path": "mudslide/integration.py", "max_issues_repo_name": "sriz1/mudslide", "max_issues_repo_head_hexsha": "78aa8a1bda4080eacd777da7ff6bcbfd9afe129c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mudslide/integration.py", "max_forks_repo_name": "sriz1/mudslide", "max_forks_repo_head_hexsha": "78aa8a1bda4080eacd777da7ff6bcbfd9afe129c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-11-20T15:42:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T02:43:29.000Z", "avg_line_length": 31.1777777778, "max_line_length": 113, "alphanum_fraction": 0.5904015206, "include": true, "reason": "import numpy", "num_tokens": 1434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976795, "lm_q2_score": 0.9005297794439687, "lm_q1q2_score": 0.8669158077453927}}
{"text": "# %%\nimport numpy as np\nimport sympy as sym\n\n# %%\n\ndef lagrange_fn(x_array, y_array, out_type):\n    # Inputs-\n    # x_array: evaluation points\n    # y_array: function values at evaluation points\n    #          (associated with the evaluation points of the same index)\n    # out_type: 3 options - \"fun\" returns a function, \"sym\" returns symbolic\n    # math object, \"lat\" returns latex code for the function\n\n    # for consistency ensure arrays are numpy arrays\n    x_array = np.asarray(x_array)\n    x_array = np.asarray(x_array)\n\n    # catch easy error\n    if len(x_array) != len(y_array):\n        raise ValueError('arrays not same length')\n\n    # find length of array\n    n = len(x_array)\n    # create x\n    x = sym.symbols('x')\n    # create var\n    expr = 0\n\n    for i in range(n):\n        # reset term\n        term = 1\n        for j in range(n):\n            if i != j:\n                # Add factor\n                term = term * ((x - x_array[j]) / (x_array[i] - x_array[j]))\n\n        # addend new term with forrect function value\n        expr = expr + y_array[i] * term\n\n    # simplify expression (effect will probably depend on terms)\n    # Presumably will convert to the monomial basis(if you aren't a fan you\n    # can comment this out)\n    expr = sym.simplify(expr)\n\n    # Function case\n    if out_type == \"fun\":\n        fun_out = sym.lambdify(x, expr)\n\n    # symbolic math object case\n    if out_type == \"sym\":\n        fun_out = expr\n\n    # Latex code case\n    if out_type == \"lat\":\n        fun_out = sym.latex(expr)\n\n    return fun_out\n\n    raise ValueError('bad type (need to set out_type as fun, sym, or lat)')\n", "meta": {"hexsha": "49903017d02762fa17813223b2ce6c8164ffcaa6", "size": 1621, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lagrange Function/lagrange_fn.py", "max_stars_repo_name": "cthamilton/symbolic-numerical-analysis", "max_stars_repo_head_hexsha": "546e995438ebc98244f871befb1504f86a016708", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lagrange Function/lagrange_fn.py", "max_issues_repo_name": "cthamilton/symbolic-numerical-analysis", "max_issues_repo_head_hexsha": "546e995438ebc98244f871befb1504f86a016708", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lagrange Function/lagrange_fn.py", "max_forks_repo_name": "cthamilton/symbolic-numerical-analysis", "max_forks_repo_head_hexsha": "546e995438ebc98244f871befb1504f86a016708", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5737704918, "max_line_length": 76, "alphanum_fraction": 0.6051819864, "include": true, "reason": "import numpy,import sympy", "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140616, "lm_q2_score": 0.9005297814461461, "lm_q1q2_score": 0.8669158058153096}}
{"text": "import numpy as np\nimport numpy.polynomial as pol\nfrom typing import Callable, List, Union\nVector = List[float]\nFunction = Callable[[float], float]\nPolynomial = pol.Polynomial\n\n\ndef lagrange2(X: Vector, Y: Vector) -> Function:\n    \"\"\"Returns the lagrange interpolation\n    Args:\n        X (Vector): X-data\n        Y (Vector): Y-data\n    Returns:\n        Callable[[Vector], Vector]: returns the function that evaluates the lagrange interpolation\n    \"\"\"\n    X = np.asarray(X)  \n\n    def lagran(x):\n        # Checks the input's type\n        if type(x) is np.ndarray:\n            x = x.reshape(-1, 1)\n        \n        if isinstance(x, list):\n            x = np.array(x).reshape(-1, 1)\n        \n        else:\n            x = np.array([x]).reshape(-1, 1)\n\n        out = 0\n        for i in range(len(X)):\n            #pi_x = (x - np.array([(X[X != xi]).reshape(-1)] * len(x))) because X[X != xi] autoreshape (-1)\n            pi_x = x - np.array([(X[X != X[i]])] * len(x))\n\n            out += Y[i] * (pi_x / (X[i] - X[X != X[i]])).prod(axis = 1)\n\n        return out\n    \n    return lagran\n    \ndef lagrange(X: Vector, Y: Vector) -> Polynomial:\n    p = 0\n    for i in range(len(X)):\n        qn = pol.Polynomial.fromroots(X[X != X[i]])\n        p += Y[i] * qn / qn(X[i])\n    return p\n    ", "meta": {"hexsha": "270ba42feb08eb91a93e32d8048d5222210ca73d", "size": 1278, "ext": "py", "lang": "Python", "max_stars_repo_path": "intelligen/interpolate.py", "max_stars_repo_name": "Bouchet07/intelligen", "max_stars_repo_head_hexsha": "d876b1241efe7ad70fa759e1f10728728f867992", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "intelligen/interpolate.py", "max_issues_repo_name": "Bouchet07/intelligen", "max_issues_repo_head_hexsha": "d876b1241efe7ad70fa759e1f10728728f867992", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intelligen/interpolate.py", "max_forks_repo_name": "Bouchet07/intelligen", "max_forks_repo_head_hexsha": "d876b1241efe7ad70fa759e1f10728728f867992", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1914893617, "max_line_length": 107, "alphanum_fraction": 0.524256651, "include": true, "reason": "import numpy", "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924769600771, "lm_q2_score": 0.8918110432813418, "lm_q1q2_score": 0.8668336249393819}}
{"text": "\n# coding: utf-8\n\n# <h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n# <div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Linear-Regression\" data-toc-modified-id=\"Linear-Regression-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Linear Regression</a></span><ul class=\"toc-item\"><li><span><a href=\"#Baseline-your-model\" data-toc-modified-id=\"Baseline-your-model-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>Baseline your model</a></span><ul class=\"toc-item\"><li><span><a href=\"#Plot-the-initial-dataset\" data-toc-modified-id=\"Plot-the-initial-dataset-1.1.1\"><span class=\"toc-item-num\">1.1.1&nbsp;&nbsp;</span>Plot the initial dataset</a></span></li><li><span><a href=\"#Split-datasets,-fit-a-linear-regression-and-measure-$R^2$-over-the-test-set\" data-toc-modified-id=\"Split-datasets,-fit-a-linear-regression-and-measure-$R^2$-over-the-test-set-1.1.2\"><span class=\"toc-item-num\">1.1.2&nbsp;&nbsp;</span>Split datasets, fit a linear regression and measure $R^2$ over the test set</a></span></li><li><span><a href=\"#Interpretation\" data-toc-modified-id=\"Interpretation-1.1.3\"><span class=\"toc-item-num\">1.1.3&nbsp;&nbsp;</span>Interpretation</a></span></li><li><span><a href=\"#Visualization\" data-toc-modified-id=\"Visualization-1.1.4\"><span class=\"toc-item-num\">1.1.4&nbsp;&nbsp;</span>Visualization</a></span></li><li><span><a href=\"#Cross-Validation\" data-toc-modified-id=\"Cross-Validation-1.1.5\"><span class=\"toc-item-num\">1.1.5&nbsp;&nbsp;</span>Cross Validation</a></span></li><li><span><a href=\"#Main-pipeline-call\" data-toc-modified-id=\"Main-pipeline-call-1.1.6\"><span class=\"toc-item-num\">1.1.6&nbsp;&nbsp;</span>Main pipeline call</a></span></li><li><span><a href=\"#Visualize-Validation-Scores\" data-toc-modified-id=\"Visualize-Validation-Scores-1.1.7\"><span class=\"toc-item-num\">1.1.7&nbsp;&nbsp;</span>Visualize Validation Scores</a></span></li><li><span><a href=\"#Increase-the-number-of-folds-in-train-and-test\" data-toc-modified-id=\"Increase-the-number-of-folds-in-train-and-test-1.1.8\"><span class=\"toc-item-num\">1.1.8&nbsp;&nbsp;</span>Increase the number of folds in train and test</a></span></li></ul></li><li><span><a href=\"#Using-SKLEARN-Pipelines\" data-toc-modified-id=\"Using-SKLEARN-Pipelines-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>Using SKLEARN Pipelines</a></span></li><li><span><a href=\"#Features-preprocessing\" data-toc-modified-id=\"Features-preprocessing-1.3\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>Features preprocessing</a></span><ul class=\"toc-item\"><li><span><a href=\"#Simple-Cross-Validation-score\" data-toc-modified-id=\"Simple-Cross-Validation-score-1.3.1\"><span class=\"toc-item-num\">1.3.1&nbsp;&nbsp;</span>Simple Cross Validation score</a></span></li></ul></li><li><span><a href=\"#Multiple-Linear-Regression\" data-toc-modified-id=\"Multiple-Linear-Regression-1.4\"><span class=\"toc-item-num\">1.4&nbsp;&nbsp;</span>Multiple Linear Regression</a></span><ul class=\"toc-item\"><li><span><a href=\"#What's-important-in-Multiple-linear-regression\" data-toc-modified-id=\"What's-important-in-Multiple-linear-regression-1.4.1\"><span class=\"toc-item-num\">1.4.1&nbsp;&nbsp;</span>What's important in Multiple linear regression</a></span></li></ul></li><li><span><a href=\"#Bias-and-variance-over-training\" data-toc-modified-id=\"Bias-and-variance-over-training-1.5\"><span class=\"toc-item-num\">1.5&nbsp;&nbsp;</span>Bias and variance over training</a></span><ul class=\"toc-item\"><li><span><a href=\"#Plot-the-polynomial-expression.\" data-toc-modified-id=\"Plot-the-polynomial-expression.-1.5.1\"><span class=\"toc-item-num\">1.5.1&nbsp;&nbsp;</span>Plot the polynomial expression.</a></span></li><li><span><a href=\"#Training-size-effect\" data-toc-modified-id=\"Training-size-effect-1.5.2\"><span class=\"toc-item-num\">1.5.2&nbsp;&nbsp;</span>Training size effect</a></span></li><li><span><a href=\"#What-about-the-degree-of-the-polynomial?\" data-toc-modified-id=\"What-about-the-degree-of-the-polynomial?-1.5.3\"><span class=\"toc-item-num\">1.5.3&nbsp;&nbsp;</span>What about the degree of the polynomial?</a></span></li></ul></li></ul></li></ul></div>\n\n# # Linear Regression\n# Let's practice with basic linear regression concepts in Python. We will read the Advertising dataset used in the ISLR book, and we will perform linear with single and multiple coefficients.\n\n# In[1]:\n\n\nimport random\nimport sys\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nimport statsmodels.api as sm\n\nfrom sklearn.pipeline import Pipeline, make_pipeline\nfrom sklearn.preprocessing import PolynomialFeatures, StandardScaler\nfrom sklearn.model_selection import cross_validate, cross_val_score,         train_test_split, learning_curve, validation_curve\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn.model_selection import cross_val_score, ShuffleSplit\nfrom sklearn_pandas import DataFrameMapper\nfrom statsmodels.api import add_constant\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# ## Baseline your model\n# \n# Start by reading the data into a pandas DataFrame\n\n# In[2]:\n\n\nurl=\"http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv\"\nadv=pd.read_csv(url)\nadv.head(5)\n\n\n# Remove the first column containing the index of each row as it's not necessary when using Pandas.\n\n# In[3]:\n\n\nadv = adv.drop(adv.columns[0], axis=1)\n\n\n# There're only have fours predictors or variables or dimensions to play with. Our **target** variable is **Sales**: We want to predict the amount of sales that we will get, basen on the money that we invest in TV, radio or newspaper advertising channels.\n\n# ### Plot the initial dataset\n# \n# Plot the two variables to see how they look like.\n\n# In[4]:\n\n\nplt.scatter(adv.TV, adv.sales,  color='grey')\nplt.xlabel('TV'); plt.ylabel('Sales')\nplt.show();\n\n\n# ### Split datasets, fit a linear regression and measure $R^2$ over the test set \n# \n# As usual, we must start by splitting the dataset into training & test. This time I will do once again to get a validation split. To do so, I will appply the `train_test_split` twice over the training set to get the validation from there.\n# \n# The idea is to finally evaluate the model using the validation set.\n\n# In[5]:\n\n\nX = pd.DataFrame(adv.TV)\ny = pd.DataFrame(adv, columns=['sales'])\n\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, test_size=0.2, random_state=25)\nX_train, X_val, y_train, y_val = train_test_split(\n    X_train, y_train, test_size=0.2, random_state=12)\n\nlm = linear_model.LinearRegression()\nlm.fit(X_train, y_train)\ny_pred = lm.predict(X_test)\n\nprint('Intercept:', lm.intercept_)\nprint('Coefficients:', lm.coef_)\nprint('Mean squared error (MSE): {:.2f}'.format(mean_squared_error(y_test, y_pred)))\nprint('Variance score (R2): {:.2f}'.format(r2_score(y_test, y_pred)))\n\n\n# ### Interpretation\n# \n# - The intercept is the expected mean value of the target variable when all predictors are set to 0.\n# - The coeffient is the slope of the line that explains the regression.\n# - The R2 is the percentage of explained variance of the predictions.\n# \n# But, to really see how good is our model, we must evaluate the score ($R^2$) over a validation split --a different split of the data set. We will understand later, why this is important. I'm getting $R^2=0.51$ over this specific test set.\n# \n# However, if you check the results below, you'll see that the $R^2$ got when predicting over the validation dataset are slightlit better: from $R^2=0.51$ to $R^2=0.64$ !! \n# \n# **Why is that?** In this case, for this specific splits, it turns out that the validations split is probably more similar to the training set, than the test set. And that is why our model is better predicting values from that split, than from the test split.\n\n# In[6]:\n\n\ny_generalize = lm.predict(X_val)\n\nprint('Intercept:', lm.intercept_)\nprint('Coefficients:', lm.coef_)\nprint('Mean squared error: {:.2f}'.format(mean_squared_error(y_val, y_generalize)))\nprint('Variance score (R2): {:.2f}'.format(r2_score(y_val, y_generalize)))\n\n\n# ### Visualization \n# \n# Now, plot the original points used to train the linear regression (grey) and the line representing the function that better approximates this relationship between TV and sales that we got from applying the linear regression. \n# \n# If you look at the code, you'll see that the way to obtain the values of Y later plotted using `plt.plot` come from directly applying the function describing the linear regression:\n# \n# $$\\hat{y} = \\beta_0 + \\beta_1 X_{val}$$\n# \n# Correspondence:\n# - $\\beta_0$ is `lm.intercept_`\n# - $\\beta_1$ is `lm.coef_[0]`\n\n# In[7]:\n\n\nplt.scatter(X_train, y_train, color='gray')\nx_vals = X_val.TV.values\ny_vals = lm.intercept_ + lm.coef_[0] * x_vals\nplt.plot(x_vals, y_vals, '--');\n\n\n# ### Cross Validation\n# \n# As you might possible have figured out, we haven't used the validation dataset, and our model has learnt only from the first (and only) split that we made between training and test. In order to improve our results, a good approach is to repeat the splitting process again and again to obtain the best possible subset of individuals that lead to the best possible model.\n# \n# To do so, we should repeat the split and validation in a loop to select the best one. Here you can find a possible way of accomplishing that task.\n\n# In[8]:\n\n\ndef split_datasets(X, y, seed, \n                   split_test_size=0.2, \n                   validation_split=True):\n    \"\"\"\n    Split X and y dataframes into training, test and validation datasets, \n    using the provided random seed.\n    Returns a dictionary with the datasets\n    \"\"\"\n    X_train, X_test, y_train, y_test = train_test_split(\n        X, y, test_size=split_test_size, random_state=seed)\n    \n    split = dict()\n    if validation_split is True:\n        X_train, X_val, y_train, y_val = train_test_split(\n            X_train, y_train, test_size=split_test_size, random_state=seed)\n        split['X_val'] = X_val\n        split['y_val'] = y_val\n\n    split['X_train'] = X_train\n    split['X_test'] = X_test\n    split['y_train'] = y_train\n    split['y_test'] = y_test\n\n    return split\n\n\n# In[9]:\n\n\ndef prepare_datasets(data, features, target, \n                     seed=1024, \n                     test_size=0.2, \n                     validation_split=False):\n    \"\"\"\n    From an input dataframe, separate features from target, and \n    produce splits (with or without validation).\n    \"\"\"\n    X = pd.DataFrame(adv, columns=features)\n    y = pd.DataFrame(adv.loc[:, target])\n    split = split_datasets(X, y, seed=seed, \n                           split_test_size=test_size, \n                           validation_split=validation_split)\n    return split\n\n\n# In[10]:\n\n\ndef train_and_predict(X, y, num_folds=1):\n    \"\"\"\n    Call the splitting of the dataset, train a linear regression \n    and predict with the test set.\n    Returns the model, the splits used and the R2 score.\n    \"\"\"\n    lm = linear_model.LinearRegression()\n    test_r2 = 0.0\n    for i in range(num_folds):\n        seed = random.randrange(2**32 - 1)\n        split = prepare_datasets(adv, ['TV'], 'sales', \n                                 seed=seed, validation_split=True)\n\n        lm.fit(split['X_train'], split['y_train'])\n        y_pred = lm.predict(split['X_test'])\n        test_r2 += r2_score(split['y_test'], y_pred)\n\n    test_r2 = test_r2/num_folds\n    return lm, split, test_r2\n\n\n# In[11]:\n\n\ndef validate(model, X_val, y_val):\n    \"\"\"\n    Scores a model over the validation datasets, by measuring the R2 score.\n    Returns the r2.\n    \"\"\"\n    y_generalized = lm.predict(X_val)\n    r2 = r2_score(y_val, y_generalized)\n    return r2\n\n\n# In[12]:\n\n\ndef my_pipeline(X, y, max_iterations, num_folds=1):\n    \"\"\"\n    Repeats during `max_iterations` the process of\n      1) Splitting a dataset, training a linear regression \n         and measuring its score over test set\n      2) Store its R2 and compute its R2 over the validation dataset\n    \"\"\"\n    history = dict()\n    history['test_r2'] = np.array([])\n    history['val_r2'] = np.array([])\n    for num_iterations in range(max_iterations):\n        model, split, test_r2 = train_and_predict(X, y, num_folds=num_folds)\n        val_r2 = validate(model, split['X_val'], split['y_val'])\n        history['test_r2'] = np.append(history['test_r2'], test_r2)\n        history['val_r2'] = np.append(history['val_r2'], val_r2)\n    return history\n\n\n# ### Main pipeline call\n# \n# We are ready now to call the pipeline. The required arguments are the X and y dataframes, and the numner of iterations we want it to run. We can also specify how many runs we want each model to be trained over the same split of training and test, which by default is 1. We will keep it like that for the moment.\n# \n# It's quite impressive to check how our simple linear regression jumps from a bad 0.64 validation $R^2$ to an impressive $0.84$ ! And only by repeating the shuffling of the training and test sets.\n\n# In[13]:\n\n\nscores = my_pipeline(X, y, max_iterations=100)\nmax_val_r2 = np.amax(scores['val_r2'])\nprint('Best Validation R2: {:.2f}'.format(max_val_r2))\n\n\n# ### Visualize Validation Scores\n# \n# To get an idea of what we got, let's draw a density plot with the validation score values saved along the different iterations. The density plot illustrates how important is to shuffle the training, test and validation sets to find out what is the one which is producing the best generalization.\n\n# In[14]:\n\n\nsns.distplot(scores['val_r2'], hist = False, kde = True,\n             kde_kws = {'shade': True, 'linewidth': 3});\n\n\n# \n# ### Increase the number of folds in train and test\n# \n# What if I increase the number of folds from 1 to 10? The results are plotted below and there's n significant improvement in the results of the validation scores. \n# \n# Why? Well, It's namely because of the way we implemented our train & predict method: we're training `num_folds` linear regression without keeping it for test scoring. If we do that, we will explore which model will better generalize over different test sets, but keeping a single training split. And that will for sure, be a better method to assess over the the validation split.\n\n# **Important**\n# \n# By partitioning the available data into three sets, we drastically reduce the number of samples which can be used for learning the model, and the results can depend on a particular random choice for the pair of (train, validation) sets. \n# \n# A test set should still be held out for final evaluation, but the validation set is no longer needed when doing CV. In the basic approach, called k-fold CV, the training set is split into k smaller sets.\n\n# In[15]:\n\n\nscore_2 = my_pipeline(X, y, max_iterations=100, num_folds=10)\nmax_val_r2 = np.amax(score_2['val_r2'])\nprint('Best Validation R2: {:.2f}'.format(max_val_r2))\n\nfig, ax = plt.subplots()\nsns.distplot(scores['val_r2'], hist = False, kde = True,\n             label='1-fold',\n             kde_kws = {'shade': True, 'linewidth': 3}, ax=ax);\nsns.distplot(score_2['val_r2'], hist = False, kde = True,\n             label='10-fold',\n             kde_kws = {'shade': True, 'linewidth': 3}, ax=ax);\nplt.legend(loc='best')\nplt.show();\n\n\n# ## Using SKLEARN Pipelines\n# \n# Instead of having you to program everything from scratch, you can also access `sklearn` API for building preprocessing and cross validation pipelines. In the example below, we put in practice the very same approach used before, but using only three lines of code (!).\n# \n# I strongly recommend you to explore deeper the capabilities of the cross validation functions in SKLearn.\n\n# ## Features preprocessing\n# \n# Before we go deeper, we must ensure that our features fulfill the set of requirements that are imposed by the linear regression method: centered and with variance = 1, following a normal ditribution and no correlation among them, namely. To do so, we will build a transformation pipeline. For more details, please, refere to the page: https://www.kaggle.com/baghern/a-deep-dive-into-sklearn-pipelines\n# \n# This case we're using the sklearn-pandas integration library `sklearn_pandas` which makes transformation pipelines much easier to read and understand. In the example below we're simply applying a standard scaler.\n\n# In[16]:\n\n\nmapper = DataFrameMapper([(list(adv), StandardScaler())], df_out=True)\nres = np.round(mapper.fit_transform(adv), 2)\nres.columns = list(adv)  # Set the columns names as they were.\n\n\n# ### Simple Cross Validation score\n# \n# As we said, instead of having to program every single function in charge of splitting the datasets, setting the random seed, feeding a model with the training part and evaluating with test part, we will explore the `cross_val_score` method. It will be able to produce a single scoring (if you want more than one, you must use `cross_validate`) and will allow you to decide what CV strategy to use, or build a custom one.\n# \n# In the example below, we feed the `cross_val_score` with \n# - the model (or pipeline) to be fit (`model`), \n# - the features (`X`),\n# - the target datasets (`y`), \n# - the cross validation strategy (`cv`), and\n# - the validation metric we want as a result (`r2`)\n# \n# This will run the cross validation with the model over the features and target using a ShuffleSplit (similar to _k-fold_ but with random splits), _n_splits_ (1000) times, evaluating with a 20% split as a test set, and returning the R2 achieved.\n\n# In[17]:\n\n\nmodel = linear_model.LinearRegression()\ncv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=666)\nscores = cross_val_score(model, X, y, cv=cv, scoring='r2')\nprint('Best Validation R2: {:.2f}'.format(max(scores)))\n\nsns.distplot(scores, hist = False, kde = True, \n             kde_kws = {'shade': True, 'linewidth': 3});\n\n\n# ## Multiple Linear Regression\n# \n# We want to consider all possible predictors available when it comes to train model. So, it's time to use the other two columns in the original dataset: radio and newspapers.\n\n# In[18]:\n\n\nX = pd.DataFrame(adv.loc[:, ['TV','radio','newspaper']])\ny = pd.DataFrame(adv, columns=['sales'])\nX.head(2)\n\n\n# To train a multiple linear regression, the only thing that we must do is to feed the model with all the variables that you want to consider for the final equation. Obviously, building a linear model with 3 features, implies that our model is better described in 3+1 dimensions, which makes this task slightly more difficult to plot.\n\n# In[19]:\n\n\nmlm, split, test_r2 = train_and_predict(X, y)\nprint('Multiple linear regression R2: {:.2f}'.format(test_r2))\nprint('Multiple linear regression coeffcients: {}'.format(mlm.coef_))\n\n\n# Repeating our CV experiment with SKLearn, this time replacing the single-feature $X$ by a 3-features dataframe $X$, leads to a similar result ($0.96$).\n\n# In[20]:\n\n\nclf = linear_model.LinearRegression()\ncv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=0)\nscores = cross_val_score(clf, X, y, cv=cv, scoring='r2')\nprint('Best Validation R2: {:.2f}'.format(max(scores)))\n\nsns.distplot(scores, hist = False, kde = True, \n             kde_kws = {'shade': True, 'linewidth': 3});\n\n\n# ### What's important in Multiple linear regression\n# \n# There's two concepts that are important when running a multiple linear regression: _p_values_ and the R-squared. Take a look to the values below in order to understand if this multiple linear regression is a better approximation to the original problem than the single-predictor linear regression.\n\n# In[21]:\n\n\nX = add_constant(X)\nmodel = sm.OLS(y, X).fit()\nprint(model.summary())\n\n\n# ## Bias and variance over training\n# \n# One of the advantages of linear regression is that we can make it as much complicated or fitted to data as we want. We simply add polynomial interactions between variables the following way:\n# \n# - Split datasets to hold out a test set, and use the training set for a cross-validation model selection\n# - Build an sklearn _pipeline_ to randomly produce polynomial expressions before fitting a linear regression\n# - Perform a CV validation score over the test set to check how do the models perform.\n\n# We will extract some parts of the code to separate functions for the sake of code clarity, and better readibility. The first function (`xy_values`) will simply produce a dataframe with columns `x` and `y` after applying the prediction stage to an input dataframe. The second function (`polynomial_pipeline`) will construct a pipeline in which at first, a polynomial is found over input dataset, and second, a linear regression is fit (OLS) with that polynomial.\n\n# In[22]:\n\n\ndef xy_values(pipeline, X):\n    \"\"\" Returns the x and y values sorted by X in a dataframe \"\"\"\n    y_pred = pipeline.predict(X)\n    return pd.DataFrame({'x': list(X.values), 'y': list(y_pred)}).                        sort_values(by=['x'])\n\n\n# In[23]:\n\n\ndef polynomial_pipeline(X, y, degree):\n    \"\"\"\n    Build a pipeline with polinomial expressions and linear regression over it.\n    \"\"\"\n    cv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=555)\n    poly = PolynomialFeatures(degree=degree, interaction_only=False, \n                              include_bias=False)\n    lm = linear_model.LinearRegression()\n    pipeline = make_pipeline(poly, lm)\n    pipeline.fit(X, y)\n    return pipeline\n\n\n# In[24]:\n\n\nsplit = prepare_datasets(adv, ['TV'], 'sales')\npipeline = polynomial_pipeline(split['X_train'], split['y_train'], degree=2)\nscores = cross_val_score(pipeline, split['X_test'], split['y_test'],\n                         scoring=\"r2\", cv=cv)\nprint('The polynomial features used are:\\n', \n      pipeline.get_params('polynomialfeatures')['polynomialfeatures'].\\\n      get_feature_names())\nprint('Best Validation R2: {:.2f}'.format(max(scores)))\n\n\n# ### Plot the polynomial expression.\n# \n# As you can easily check for this simulation, the higher degree polynomial means a better fit to the training but poorer generalization. It seems that here we might be overfitting a bit.\n\n# In[25]:\n\n\nf, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)\nf.set_figwidth(11)\nax1.scatter(split['X_train'].values, split['y_train'].values, color='grey')\n\npred = xy_values(pipeline, split['X_test'])\nax1.plot(pred.x.values, pred.y.values, label='prediction',\n         linewidth=3, color='green')\nax1.grid()\nax1.set_title('2 degree polynomial prediction')\n\nax2.hist(scores[scores>0], 50, normed=1, alpha=0.5);\nax2.set_title('histogram of scores')\nplt.show();\n\n\n# ### Training size effect\n# \n# A learning curve shows the validation and training score of an estimator for varying numbers of training samples. It is a tool to find out how much we benefit from adding more training data and whether the estimator suffers more from a variance error or a bias error.\n# \n# A cross-validation generator splits the whole dataset $k$ times in training and test data. Subsets of the training set with varying sizes will be used to train the estimator and a score for each training subset size and the test set will be computed. Afterwards, the **scores will be averaged** over all $k$ runs for each training subset size.\n# \n# Can you interpret what is the number of samples you need to feed your model in training, in order to get the best possible result? When adding more samples does not add significant advantage?\n\n# In[26]:\n\n\ndef plot_training_curve():\n    plt.plot(train_sizes, np.mean(train_scores, axis=1), '-o',\n             label='train_scores')\n    plt.plot(train_sizes, np.mean(valid_scores, axis=1), '-o',\n             label='validation_scores')\n    plt.title('Training curve')\n    plt.legend(loc='best')\n    plt.xlabel('Training set size')\n    plt.ylabel('Explained variance ($R^2$)')\n    plt.grid()\n    plt.show()\n\n\n# In[27]:\n\n\nsplit = prepare_datasets(data=adv, features=['TV'], target='sales', test_size=0.0)\ncv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=666)\ntrain_sizes, train_scores, valid_scores = learning_curve(\n    lm, split['X_train'], split['y_train'], \n    train_sizes=[50, 75, 100, 125, 150, 175], \n    cv=10)\nplot_training_curve()\n\n\n# ### What about the degree of the polynomial?\n# \n# Let's work on the `sklearn.model_selection.validation_curve` to see how the degree of the polynomial affects the R2 score. We pass an array of possible degrees for the polynomials to the `validation_curve` method.\n# \n# Compute scores for an estimator with different values of a specified parameter (degree of polynomial). This is similar to grid search with one parameter. However, this will also compute training scores and is merely a utility for plotting the results.\n\n# In[28]:\n\n\ndef plot_validation_curve():\n    # Plot the mean train error and validation error across folds\n    plt.figure(figsize=(6, 4))\n    plt.plot(degrees, train_scores.mean(axis=1), '-o',\n             lw=2, label='training')\n    plt.plot(degrees, validation_scores.mean(axis=1), '-o',\n             lw=2, label='cross-validation')\n    plt.title('Validation curve')\n    plt.legend(loc='best')\n    plt.xlabel('degree of polynomial')\n    plt.ylabel('explained variance ($R^2$)')\n    plt.tight_layout()\n    plt.grid()\n    plt.show()\n\n\n# In[29]:\n\n\nsplit = prepare_datasets(data=adv, features=['TV'], target='sales', test_size=0.0)\nlm = linear_model.LinearRegression()\ndegrees = np.arange(1, 10)\nmodel = make_pipeline(PolynomialFeatures(), lm)\ncv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=666)\n\ntrain_scores, validation_scores = validation_curve(\n                 model, split['X_train'], split['y_train'],\n                 param_name='polynomialfeatures__degree',\n                 cv=cv,\n                 param_range=degrees)\nplot_validation_curve()\n\n\n# It seems that increasing the degree of the polynomial beyond '2' produces a decrease in validation accuracy.\n# \n# Now try to iterate over different maximum degrees for the polinomials to be generated to see how they affect the overall score of the model.\n\n# In[30]:\n\n\nplt.figure(figsize=(6, 4))\nplt.scatter(split['X_train'].values, split['y_train'].values, color='grey')\n\nsplit = prepare_datasets(adv, ['TV'], 'sales', seed=1024)\ncv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=666)\n\nfor degree in range(1, 6):\n    pipeline = polynomial_pipeline(split['X_train'], split['y_train'], degree)\n    scores = cross_val_score(pipeline, split['X_test'], split['y_test'],\n                             scoring=\"r2\", cv=10)\n    pred = xy_values(pipeline, split['X_test'])\n    plt.plot(pred.x.values, pred.y.values, \n             label='deg.{}'.format(degree))\n    \nplt.title('Linear regression with different polynomial degrees')\nplt.legend(loc='best')\nplt.grid()\nplt.show()\n\n", "meta": {"hexsha": "35fa3c47117526adcf1fb80f5f6ac08d4d765c9e", "size": 26589, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/Linear regression.py", "max_stars_repo_name": "iammowgoud/class_notebooks", "max_stars_repo_head_hexsha": "c3c3e1bd85d93a05b11d36a9be49749757f734b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-04T10:16:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-04T10:16:40.000Z", "max_issues_repo_path": "scripts/Linear regression.py", "max_issues_repo_name": "TRF2019/class_notebooks", "max_issues_repo_head_hexsha": "316f3f158b806b12a1340392172ee7c7db87df24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/Linear regression.py", "max_forks_repo_name": "TRF2019/class_notebooks", "max_forks_repo_head_hexsha": "316f3f158b806b12a1340392172ee7c7db87df24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.3222996516, "max_line_length": 4025, "alphanum_fraction": 0.7120613788, "include": true, "reason": "import numpy,import statsmodels,from statsmodels", "num_tokens": 6738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522863, "lm_q2_score": 0.9149009596336303, "lm_q1q2_score": 0.8667598287208897}}
{"text": "import pathlib  # needed to create folder\r\nimport matplotlib.pyplot as plt  # needed for graphs\r\nfrom tqdm import tqdm\r\nimport numpy as np\r\n\r\nprint('Program started running!')\r\n\r\npi = np.pi\r\ndpisiz = 1000  # for images resolution\r\n\r\n#######################################\r\n# Lambda anonymous functions          #\r\n#######################################\r\n\r\nf = lambda x, e, k: x - k - e * np.sin(x)\r\ndf = lambda x, e: 1 - e * np.cos(x)\r\n\r\n\r\n########################################\r\n# Creating Our Newton-Raphson function #\r\n########################################\r\ndef newton_raphson(f, df, x, e, TOL, k):\r\n    error = 1\r\n    iterations = 0\r\n    while error > TOL:\r\n        new_x = x - f(x, e, k) / df(x, e)\r\n        error = abs(new_x - x)\r\n        x = new_x\r\n        iterations += 1\r\n        # print(f'x{iterations}: {x:.15f} \\t | \\t error: {error} \\t | \\t f(x):{f(x, e,k)} \\t | \\t df(x):{df(x, e)} \\t | \\t line:{df(x, e)} * x+{f(x, e,k)}')\r\n    # print(f\"Newton's Estimate = {x:.15f}\\nIterations: {iterations}\")\r\n    return x\r\n\r\n\r\n#####################################\r\n# Function to save images to folder #\r\n#####################################\r\ndef savim(dir, name):\r\n    path = pathlib.Path(f\"./{dir}\")\r\n    path.mkdir(exist_ok=True,  # Without exist_ok=True,FileExistsError show up if folder already exists\r\n               parents=True)  # Missing parents of the path are created.\r\n    plt.savefig(f'./{dir}/{name}.png', dpi=dpisiz)\r\n    print(f'Saved image at location: /{dir}/{name}.png')\r\n\r\n\r\nnumberoftries = 10000\r\ni = np.empty((numberoftries, 6))\r\ni[:, 0] = np.linspace(0, 2 * pi, numberoftries)\r\ne = [0.1, 0.3, 0.5, 0.7, 0.9]\r\n\r\nfor j in tqdm(range(1, 6)):\r\n    for k in range(numberoftries):\r\n        i[k, j] = newton_raphson(f, df, 1, e[j - 1], 1e-15, i[k, 0])  # Adding NP-estimates to array\r\ne = [0.1, 0.3, 0.5, 0.7, 0.9]\r\n\r\n# Plotting our function\r\nfig = plt.figure()\r\nax = plt.axes()\r\nlines = ax.plot(i[:, 0], i[:, 0:5])\r\nax.set_ylabel('E')\r\nax.set_xlabel('M')\r\nax.set_title('Project 1 - Task 1 - Newton-Raphson method')\r\nlabels = [0] * 5\r\nfor o in range(0, 5):\r\n    labels[o] = f'E(M) for e={e[o]}'\r\nax.legend(lines, labels)\r\nsavim('./pr1_task1/images', 'plot')\r\n\r\nprint('Program finished running!')\r\n\r\n##############################################################################\r\n#    A faster convergence could be achieved with a better initial value.     #\r\n#          Current code uses a standard initial value of one.                #\r\n##############################################################################\r\n", "meta": {"hexsha": "6e159353bcb0c449757f605ff50cd8a6824ee010", "size": 2546, "ext": "py", "lang": "Python", "max_stars_repo_path": "Project 1/pr1_task1.py", "max_stars_repo_name": "od1sm/CoPh", "max_stars_repo_head_hexsha": "2d03f00c5e8aeacb7b0704b5ff77b953cea6b7f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project 1/pr1_task1.py", "max_issues_repo_name": "od1sm/CoPh", "max_issues_repo_head_hexsha": "2d03f00c5e8aeacb7b0704b5ff77b953cea6b7f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project 1/pr1_task1.py", "max_forks_repo_name": "od1sm/CoPh", "max_forks_repo_head_hexsha": "2d03f00c5e8aeacb7b0704b5ff77b953cea6b7f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9466666667, "max_line_length": 157, "alphanum_fraction": 0.4913589945, "include": true, "reason": "import numpy", "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522863, "lm_q2_score": 0.914900945711678, "lm_q1q2_score": 0.8667598155314961}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Oct  7 08:25:49 2020\r\n@author: Ashlee\r\nODE Example 1\r\n$\\frac{dx}{dt} = b1-b2*x\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom scipy.optimize import curve_fit\r\nfrom scipy.integrate import odeint\r\nimport matplotlib.pyplot as plt\r\n\r\n# Data for example 1\r\nxaxisData = np.array( [0.0, 0.5, 1.0, 5.0, 30.0] ) # time, independent variable\r\nyaxisData = np.array( [0.0, 0.5, 1.2, 2.5, 2.7] ) # x, dependent variable\r\n\r\n# guesses for parameters\r\nb1guess = 1.0\r\nb2guess = 1.0\r\nparameterguesses = np.array([b1guess, b2guess])\r\n\r\n# Need two functions for our model\r\n# 1. to define the system of ODE(s)\r\n# 2. to solve the ODE(s) and return ypredicted values in same shape as yaxisData\r\n\r\n# 1. define ODE\r\ndef system_of_ODEs(x,t,parameters): # yvar, xvar, args\r\n    # unpack the parameters\r\n    b1 = parameters[0]\r\n    b2 = parameters[1]\r\n    dxdt = b1-b2*x\r\n    return dxdt\r\n# end of function\r\n\r\n# 2. Solve ODEs at xaxisData points\r\n    # and return calculated yaxisCalculated\r\n    # using current values of the parameters\r\ndef model(xaxisData,*params):\r\n    # initial condition(s) for the ODE(s)\r\n    yaxis0 = 0.0 # should include a decimal\r\n    yaxisCalc = np.zeros(xaxisData.size) \r\n    for i in np.arange(0,len(xaxisData)):\r\n        if xaxisData[i] == 0.0: # should include a decimal\r\n            yaxisCalc[i] = yaxis0\r\n        else:\r\n            xaxisSpan = np.linspace(0,xaxisData[i],101)\r\n            ySoln = odeint(system_of_ODEs,yaxis0,xaxisSpan,args = (params,)) # soln for entire xaxisSpan\r\n            yaxisCalc[i] = ySoln[-1] # calculated y at the end of the xaxisSpan\r\n    return yaxisCalc\r\n    # end of for loop\r\n# end of model function \r\n\r\n# Estimate the parameters\r\nparametersoln, pcov = curve_fit(model,xaxisData,yaxisData,p0=parameterguesses)\r\nprint(parametersoln)\r\nplt.plot(xaxisData,yaxisData,'o',label='data')\r\nyaxis0 = 0.0\r\nxaxisForPlotting = np.linspace(0,xaxisData[-1],101)\r\nyaxisCalcFromGuesses = odeint(system_of_ODEs,yaxis0,xaxisForPlotting,args = (parameterguesses,))\r\nyaxisCalc = odeint(system_of_ODEs,yaxis0,xaxisForPlotting,args = (parametersoln,))\r\nplt.plot(xaxisForPlotting,yaxisCalcFromGuesses,'r-',label='output with parameter guesses') # before fitting\r\nplt.plot(xaxisForPlotting,yaxisCalc, 'g--', label='output with estimated parameters') # at soln parameters\r\nplt.xlabel('t')\r\nplt.ylabel('x')\r\nplt.legend()\r\nplt.show()", "meta": {"hexsha": "ff52317aa814ab37f871abe3671da8a5f3707ce1", "size": 2374, "ext": "py", "lang": "Python", "max_stars_repo_path": "CHEclassFa20/In Class Problem Solutions/Python/ODEParamEstimExample1.py", "max_stars_repo_name": "ashleefv/ApplNumComp", "max_stars_repo_head_hexsha": "ebe2ac0d08111aee58b8421cd2d8e4dee2b84662", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-08-25T13:00:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T14:09:10.000Z", "max_issues_repo_path": "CHEclassFa20/In Class Problem Solutions/Python/ODEParamEstimExample1.py", "max_issues_repo_name": "ashleefv/ApplNumComp", "max_issues_repo_head_hexsha": "ebe2ac0d08111aee58b8421cd2d8e4dee2b84662", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-11-28T00:08:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T00:28:43.000Z", "max_forks_repo_path": "CHEclassFa20/In Class Problem Solutions/Python/ODEParamEstimExample1.py", "max_forks_repo_name": "ashleefv/ApplNumComp", "max_forks_repo_head_hexsha": "ebe2ac0d08111aee58b8421cd2d8e4dee2b84662", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-08-18T02:31:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-20T17:57:57.000Z", "avg_line_length": 35.4328358209, "max_line_length": 108, "alphanum_fraction": 0.6866048863, "include": true, "reason": "import numpy,from scipy", "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741322079105, "lm_q2_score": 0.9099070005411123, "lm_q1q2_score": 0.8667538714303529}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport imageio\nfrom _utils import *\n\n\ndef DCT2D(x):\n    '''\n    Discrete space cosine transform\n    x: Input matrix\n    '''\n    N1, N2 = x.shape\n    X = np.zeros((N1, N2))\n    n1, n2 = np.mgrid[0:N1, 0:N2]\n    for w1 in range(N1):\n        for w2 in range(N2):\n            l1 = (2/N1)**0.5 if w1 else (1/N1)**0.5\n            l2 = (2/N2)**0.5 if w2 else (1/N2)**0.5\n            cos1 = np.cos(np.pi*w1*(2*n1 + 1)/(2*N1))\n            cos2 = np.cos(np.pi*w2*(2*n2 + 1)/(2*N2))\n            X[w1, w2] = l1*l2*np.sum(x*cos1*cos2)\n    return X\n\n\ndef iDCT2D(X, shift=True):\n    '''\n    Inverse discrete space cosine transform\n    X: Input spectrum matrix\n    '''\n    N1, N2 = X.shape\n    x = np.zeros((N1, N2))\n    k1, k2 = np.mgrid[0:N1, 0:N2]\n    l1 = np.ones((N1, N2))*(2/N1)**0.5\n    l2 = np.ones((N1, N2))*(2/N2)**0.5\n    l1[0] = (1/N1)**0.5; l2[:,0] = (1/N2)**0.5\n    for n1 in range(N1):\n        for n2 in range(N2):\n            cos1 = np.cos(np.pi*k1*(2*n1 + 1)/(2*N1))\n            cos2 = np.cos(np.pi*k2*(2*n2 + 1)/(2*N2))\n            x[n1, n2] = np.sum(l1*l2*X*cos1*cos2)\n    return x\n\n\nif __name__ == \"__main__\":\n    image = imageio.imread('./sample/cameraman.png')\n    s = 4\n    image = image[::s, ::s] / 255\n    N1, N2 = image.shape\n    histogram(image, interval=[0, 1])\n\n    IMAGE = DCT2D(image)\n    xX = np.array([image, np.log10(1 + abs(IMAGE))])\n    panel(xX, [2, 1], text_color='green',\n          texts=['Input image', 'DCT Spectrum'])\n\n    image_ = iDCT2D(IMAGE)\n    Xx_ = np.array([np.log10(1 + abs(IMAGE)), image_])\n    panel(Xx_, [2, 1], text_color='green',\n          texts=['DCT Spectrum', 'Reconstructed image'])\n\n    u, v = np.mgrid[0:N1, 0:N2] / max(N1, N2)\n    r = (u ** 2 + v ** 2) ** 0.5\n    theta = np.arctan2(v, u)\n    H = np.exp(-3 * r ** 2) * (np.cos(4 * 2 * theta) / 2 + 1 / 2)\n    image__ = iDCT2D(H * IMAGE)\n    Hx__ = np.array([H, abs(image__ * 0.5 + 0.5)])\n    panel(Hx__, (2, 1), text_color='green',\n          texts=['Filter', 'Filtered image'])\n\n", "meta": {"hexsha": "8074f591942b578d48abbcc2c505d6cca15b00db", "size": 2027, "ext": "py", "lang": "Python", "max_stars_repo_path": "20210728/discrete_cosine_transform.py", "max_stars_repo_name": "sgzqc/wechat", "max_stars_repo_head_hexsha": "6589915c46b8f51d28dba61c6da9702821f5b47c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-12-02T10:01:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T13:00:18.000Z", "max_issues_repo_path": "20210728/discrete_cosine_transform.py", "max_issues_repo_name": "sgzqc/wechat", "max_issues_repo_head_hexsha": "6589915c46b8f51d28dba61c6da9702821f5b47c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "20210728/discrete_cosine_transform.py", "max_forks_repo_name": "sgzqc/wechat", "max_forks_repo_head_hexsha": "6589915c46b8f51d28dba61c6da9702821f5b47c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2021-10-01T23:38:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T05:04:07.000Z", "avg_line_length": 28.9571428571, "max_line_length": 65, "alphanum_fraction": 0.5140601875, "include": true, "reason": "import numpy", "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615412, "lm_q2_score": 0.9099070005411124, "lm_q1q2_score": 0.866753870205282}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Return fitted model parameters to the dataset at datapath for each choice in degrees.\n# Input: datapath as a string specifying a .txt file, degrees as a list of positive integers.\n# Output: paramFits, a list with the same length as degrees, where paramFits[i] is the list of\n# coefficients when fitting a polynomial of d = degrees[i].\ndef main(datapath, degrees):\n    paramFits = []\n    # fill in\n    # read the input file, assuming it has two columns, where each row is of the form [x y] as\n    # in poly.txt.\n    # iterate through each n in degrees, calling the feature_matrix and least_squares functions to solve\n    # for the model parameters in each case. Append the result to paramFits each time.\n    \n    \n    file_path = open( datapath,  \"r\")\n    X = []\n    Y = []\n    #X = []\n    #Y = []\n    y_1 = []\n    y_2 = []\n    y_3 = []\n    y_4 = []\n    #count = 0\n    y_5 = []\n    file_data_path = file_path.readlines()\n    \n    for i in file_data_path:\n        i = i.split(\" \")\n        l1 = float(i[0])\n        l2 = float(i[1])\n        X.append(l1)\n        Y.append(l2)\n        \n        \n    for j in degrees:\n        mitrx = feature_matrix(X, j)\n        ##matrix\n        paramFits.append(least_squares(mitrx, Y))\n        \n    xsort = sorted(X)\n    \n    for l in sorted(X):\n        res1 = paramFits[0][0] * l + paramFits[0][1]\n        res2 = paramFits[1][0] * (l ** 2) + paramFits[1][1] * l + paramFits[1][2]\n        res3 = paramFits[2][0] * (l ** 3) + paramFits[2][1] * (l ** 2) + paramFits[2][2] * l + paramFits[2][3]\n        res4 = paramFits[3][0] * (l ** 4) + paramFits[3][1] * (l ** 3) + paramFits[3][2] * (l ** 2) + paramFits[3][3] * l + paramFits[3][4]\n        res5 = paramFits[4][0] * (l ** 5) + paramFits[4][1] * (l ** 4) + paramFits[4][2] * (l ** 3) + paramFits[4][3] * (l ** 2) + paramFits[4][4] * l + paramFits[4][5]\n        y_1.append(res1)\n        y_2.append(res2)\n        y_3.append(res3)\n        y_4.append(res4)\n        y_5.append(res5)\n        \n    #close    \n    file_path.close()\n    \n    plt.scatter(X, Y, color='b', marker='*')\n    \n    plt.plot(sorted(X), y_1, color='g', linestyle='-.')\n    plt.plot(sorted(X), y_2, color='b', linestyle='-.')\n    plt.plot(sorted(X), y_3, color='m', linestyle='-.')\n    plt.plot(sorted(X), y_4, color='y', linestyle='-.')\n    plt.plot(sorted(X), y_5, color='r', linestyle='-.')\n    \n    plt.legend([\"data = 1\", \"data = 2\", \"data = 3\", \"data = 4\", \"data = 5\", \"Path Data\"], loc='upper right')\n    plt.ylabel(\"Y Data\")\n    plt.xlabel(\"X Data\")\n \n    plt.show()\n    ##\n    return paramFits\n\n# Return the feature matrix for fitting a polynomial of degree d based on the explanatory variable\n# samples in x.\n# Input: x as a list of the independent variable samples, and d as an integer.\n# Output: X, a list of features for each sample, where X[i][j] corresponds to the jth coefficient\n# for the ith sample. Viewed as a matrix, X should have dimension #samples by d+1.\ndef feature_matrix(x, d):\n    # fill in\n    # There are several ways to write this function. The most efficient would be a nested list comprehension\n    # which for each sample in x calculates x^d, x^(d-1), ..., x^0.\n    X_list = []\n    ind = 0\n    for i in x:\n        d1 = d\n        \n        X_list.append([])\n        \n        while d1 >= 0:\n            X_list[ind].append(i**d1)\n            d1 -= 1\n        # d = 1    \n        ind += 1\n    return X_list\n\n\n# Return the least squares solution based on the feature matrix X and corresponding target variable samples in y.\n# Input: X as a list of features for each sample, and y as a list of target variable samples.\n# Output: B, a list of the fitted model parameters based on the least squares solution.\ndef least_squares(X, y):\n    X_array = np.array(X)\n    # X_array = list(X)\n    Y_array = np.array(y)\n\n    # fill in\n    # Use the matrix algebra functions in numpy to solve the least squares equations. This can be done in just one line.\n    \n    return (np.linalg.inv(X_array.T @ X_array)) @ (X_array.T @ Y_array)\n\n\nif __name__ == '__main__':\n    datapath = 'poly.txt'\n    degrees = [1, 2, 3, 4, 5]\n    paramFits = main(datapath, degrees)\n    print(paramFits)\n", "meta": {"hexsha": "edabc6faa84c2120a6be90784b88f3ffa8bf90ac", "size": 4189, "ext": "py", "lang": "Python", "max_stars_repo_path": "homework-7-s21-malwake-git/polyfit.py", "max_stars_repo_name": "malwake-git/ECE20875", "max_stars_repo_head_hexsha": "2348f638088359af962bc0d98e965c1ec0132686", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework-7-s21-malwake-git/polyfit.py", "max_issues_repo_name": "malwake-git/ECE20875", "max_issues_repo_head_hexsha": "2348f638088359af962bc0d98e965c1ec0132686", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework-7-s21-malwake-git/polyfit.py", "max_forks_repo_name": "malwake-git/ECE20875", "max_forks_repo_head_hexsha": "2348f638088359af962bc0d98e965c1ec0132686", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2016806723, "max_line_length": 168, "alphanum_fraction": 0.5910718549, "include": true, "reason": "import numpy", "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.9099070042057362, "lm_q1q2_score": 0.8667538700208953}}
{"text": "import numpy     as np\n\nfrom typing     import Type, List, NoReturn, Union, Dict\n\n\nRealNumber    = Union[np.float16, np.float32, np.float64, float];\nComplexNumber = Union[np.complex64, np.complex128];\n\n\ndef cayley_to_upper(z:ComplexNumber) -> ComplexNumber:\n    #\n    # Compute the image of z via the Cayley map into the uper half plane.\n    #\n    return 1j*(1.0+z)/(1.0-z);\n\n\ndef cayley_from_upper(z:ComplexNumber) -> ComplexNumber:\n    #\n    # Compute the image of z via the Cayley map from the uper half plane into the unit disk.\n    # \n    return (z-1j)/(z+1j);\n\n\ndef moebius_transformation(z:ComplexNumber,a:RealNumber,b:RealNumber,c:RealNumber,d:RealNumber) -> Union[ComplexNumber, NoReturn]:\n    #\n    # Compute the image of z via the Moebius transformation defined by the real paramters a,b,c,d.\n    # \n    if a*b-c*d==0 :\n        raise ValueError(\"In order to be a proper Moebius Transformaion, it must be a*b-c*d!=0\");\n    else:\n        return (a*z-b)/(c*z+d);\n\n\ndef moebius_unit_disk(z:ComplexNumber, theta:RealNumber=np.pi, a:ComplexNumber=np.complex(0,0)) -> ComplexNumber:\n    #\n    # Compute the image of z via the Moebius transformation which is an automorphism of the unit disk.\n    # \n    # Input:\n    #   z       : complex number (most likely, in the unit disk) \n    #   theta   : angle of rotation \n    #   a       : point of the unit disk such that 0-->a\n    # \n    # Output:    \n    #   w       : complex number (in the unit disk)\n    #\n    return np.exp(1j*theta*np.pi)*(z-a)/(1-np.conjugate(a)*z);\n\n\ndef moebius_upper_half_plane(z:ComplexNumber,a:RealNumber,b:RealNumber,c:RealNumber,d:RealNumber) -> Union[ComplexNumber, NoReturn]:\n    #\n    # Compute the image of z via the Moebius transformation which is an automorphism of the upper-half plane.\n    # \n    # Input:\n    #   z       : complex number (most likely, in the upper half plane) \n    #   a,b,c,d : real parameters such that a*b-c*d>0\n    # \n    # Output:    \n    #   w       : complex number (in the upper half plane)\n    #\n    if not a*b-c*d>0 :\n        raise ValueError(\"In order to be a proper Moebius Transformaion of the upper-half plane, it must be a*b-c*d>0\");\n    else:\n        return (a*z-b)/(c*z+d);\n\n    \ndef principal_sqrt(x:RealNumber) -> RealNumber:\n    #\n    # Compute the principal squareroot of the real number x.\n    #   \n    if np.any(np.angle(x) > 0): \n        return np.exp(1j * np.angle(x) / 2) * np.sqrt(np.sqrt(np.real(x)**2 + np.imag(x)**2));\n    else:\n        return np.exp(1j * (np.angle(x)+2*np.pi) / 2) * np.sqrt(np.sqrt(np.real(x)**2 + np.imag(x)**2));", "meta": {"hexsha": "3ad56045463cf786857613f88cc5cdb48800ccc2", "size": 2568, "ext": "py", "lang": "Python", "max_stars_repo_path": "schramm_loewner_evolution/complex_analysis.py", "max_stars_repo_name": "andrea-dm/schramm-loewner-evolution", "max_stars_repo_head_hexsha": "186e6f6d2263cdae74b6aba4a0e70792b89959a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-12-29T10:45:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T11:23:31.000Z", "max_issues_repo_path": "schramm_loewner_evolution/complex_analysis.py", "max_issues_repo_name": "andrea-dm/schramm-loewner-evolution", "max_issues_repo_head_hexsha": "186e6f6d2263cdae74b6aba4a0e70792b89959a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "schramm_loewner_evolution/complex_analysis.py", "max_forks_repo_name": "andrea-dm/schramm-loewner-evolution", "max_forks_repo_head_hexsha": "186e6f6d2263cdae74b6aba4a0e70792b89959a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1780821918, "max_line_length": 132, "alphanum_fraction": 0.6308411215, "include": true, "reason": "import numpy", "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970239907775086, "lm_q2_score": 0.8933094003735664, "lm_q1q2_score": 0.8667244302330664}}
{"text": "from __future__ import division\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport time\n\nprint(\"BSUIR: Machine Learning, L1\")\n\n\ndef h0x(x_value, theta):\n    return theta[0] + theta[1] * x_value\n\n\ndef compute_cost(X, Y, theta):\n    m = len(X)\n    diff = []\n    for i in range(0, m):\n        val = pow(h0x(X[i], theta) - Y[i], 2)\n        diff.append(val)\n    cost = (1 / (2 * m)) * sum(diff)\n    return cost\n\n\ndef gradient_descent(X, Y, theta, iterations, alpha):\n    \"\"\"\n    From Andrew Ng implementation: without ones vector in X\n    \"\"\"\n    m = len(X)\n    J = []\n    for i in range(iterations):\n        val = np.zeros(len(theta))\n        for j in range(0, m):\n            val[0] += h0x(X[j], theta) - Y[j]\n            for k in range(1, len(theta)):\n                val[k] += (h0x(X[j], theta) - Y[j]) * X[j]\n        for z in range(0, len(theta)):\n            theta[z] = theta[z] - (alpha / m) * val[z]\n        J.append(compute_cost(X, Y, theta))\n    return [theta, J]\n\n\ndef gradient_descent_not_vectorized(X, Y, theta, iterations, alpha):\n    \"\"\"\n    For reducing impact of compute_cost_vectorized vs compute_cost\n    \"\"\"\n    m = len(X)\n    J = []\n    for i in range(iterations):\n        val = np.zeros(len(theta))\n        for j in range(0, m):\n            for k in range(0, len(theta)):\n                val[k] += (h0x_vectorized(X[j], theta) - Y[j]) * X[j][k]\n        for z in range(0, len(theta)):\n            theta[z] = theta[z] - (alpha / m) * val[z]\n        J.append(compute_cost_vectorized(X, Y, theta))\n    return [theta, J]\n\n\ndef h0x_vectorized(X, theta):\n    return X.dot(theta)\n\n\ndef compute_cost_vectorized(X, Y, theta):\n    # J = (1 / (2 * m)) * (X * theta - y)' * (X * theta - y); % equally (sum(power(X, 2)))\n    m = len(X)\n    temp = (h0x_vectorized(X, theta) - Y)\n    return (1 / (2 * m)) * np.dot(temp.T, temp)[0][0]\n\n\ndef gradient_descent_vectorized(X, Y, theta, iterations, alpha):\n    m = len(Y)\n    J_history = []\n    for i in range(iterations):\n        # theta = theta - alpha * (1/m) * (((X*theta) - y)' * X)'; % Vectorized\n        h0x = (h0x_vectorized(X, theta) - Y).T\n        dt = np.dot(h0x, X).T\n        a = alpha * (1 / m) * dt\n        theta = theta - a\n        J_history.append(compute_cost_vectorized(X, Y, theta))\n    return [theta, J_history]\n\n\ndef feature_normalization(X):\n    X = X.T\n    for i in range(1, len(X)):\n        mu = np.mean(X[i])\n        s = np.std(X[i], ddof=1)\n        X[i] = (X[i] - mu) / s\n    return X.T\n\n\ndef normal_eqn(X, Y):\n    # theta = pinv(X' * X) * (X' * y); % Vectorized\n    return np.dot(np.linalg.inv(np.dot(X.T, X)), np.dot(X.T, Y))\n\n\nif __name__ == '__main__':\n    # 1\n    file_path = 'ex1data1.csv'\n    data_frames = pd.read_csv(file_path)\n\n    x = data_frames['population']\n    y = data_frames['profit']\n\n    x = list(x)  # np.array(x)\n    y = list(y)\n\n    # 2\n    fig, ax = plt.subplots()\n    ax.scatter(x, y)\n\n    plt.show()\n\n    # 3\n    theta = [0, 0]\n    print('With theta = [0 ; 0]\\nCost computed: ', compute_cost(x, y, theta))\n    print('Expected cost value (approx) 32.07\\n')\n\n    theta = [-1, 2]\n    print('\\nWith theta = [-1 ; 2]\\nCost computed: ', compute_cost(x, y, theta))\n    print('Expected cost value (approx) 54.24\\n')\n\n    # 4\n    iterations = 1500\n    alpha = 0.01\n\n    print('Running Gradient Descent ...\\n')\n    # run gradient descent\n    theta = [0, 0]\n    [theta, J1] = gradient_descent(x, y, theta, iterations, alpha)\n\n    print('Theta found by gradient descent:', theta)\n    print(\"Cost: \", compute_cost(x, y, theta))\n    print('Expected theta values (approx):  -3.6303  1.1664\\n\\n')\n\n    ax.plot([4, 23], [h0x(0, theta), h0x(23, theta)], 'red')\n    plt.show()\n\n    # 5\n    u = np.arange(-5, 5, 0.1)\n    v = np.arange(-5, 5, 0.1)\n    z = np.zeros((len(u), len(v)))\n    for i in range(len(u)):\n        for j in range(len(u)):\n            z[i][j] = compute_cost(x, y, [u[i], v[j]])\n\n    u, v = np.meshgrid(u, v)\n\n    fig = plt.figure()\n    ax = fig.gca(projection='3d')\n    surf = ax.plot_surface(u, v, z, linewidth=0, antialiased=False)\n    plt.show()\n    fig, ax = plt.subplots()\n    plt.contour(u, v, z, np.logspace(-2, 3, 20))\n    plt.show()\n\n    # 6\n    file_path = 'ex1data2.csv'\n    data = pd.read_csv(file_path)\n\n    # 7-8\n    X = data.iloc[:, 0:2]  # read first two columns into X\n    Y = data.iloc[:, 2]  # read the third column into y\n    m = len(Y)\n    ones = np.ones((m, 1))\n    X = np.hstack((ones, X))  # [x1, x2] => [1, x1, x2]\n    theta = np.zeros((3, 1))\n    Y = Y[:, np.newaxis]  # convert to a matrix\n\n    print('With theta = [0; 0; 0]\\nCost computed: ', compute_cost_vectorized(X, Y, theta))\n    print('Expected cost value (approx) 65591548106.45744\\n')\n\n    print('Without normalization: \\n')\n    # Can not be calculated since numbers are too large\n    # print(gradient_descent_vectorized(X, Y, theta, iterations, alpha)[0])\n    print('With normalization: \\n')\n    X = feature_normalization(X)\n\n    start1 = time.time()\n    [theta, J1] = gradient_descent_not_vectorized(X, Y, theta, iterations, alpha)\n    end1 = time.time()\n    print('Time gradient not vectorized: ', end1 - start1, theta)\n\n    start2 = time.time()\n    [gdv, J] = gradient_descent_vectorized(X, Y, np.zeros((3, 1)), iterations, alpha)\n    end2 = time.time()\n\n    print('Vectorized time: ', end2 - start2)\n    print('Solution: ')\n    print(gdv)\n\n    # 9\n\n    objects = ('Vectorized', 'Not-Vectorized')\n    y_pos = np.arange(len(objects))\n    performance = [end2 - start2, end1 - start1]\n\n    plt.bar(y_pos, performance, align='center', alpha=0.5)\n    plt.xticks(y_pos, objects)\n    plt.ylabel('Time (s)')\n    plt.title('Performance')\n\n    plt.show()\n\n    # 10\n\n    year = range(0, iterations)\n\n    plt.plot(year, J, color='orange')\n    plt.xlabel('Iterations')\n    plt.ylabel('Cost J')\n    plt.title('Cost by iterations')\n    plt.show()\n\n    # 11\n\n    theta = normal_eqn(X, Y)\n    print('Normal equation: \\n')\n    print(theta)\n", "meta": {"hexsha": "25291022a11cfce5362823c5462bc012b9bc5425", "size": 5974, "ext": "py", "lang": "Python", "max_stars_repo_path": "1/lab1.py", "max_stars_repo_name": "yalov4uk/ML-labs", "max_stars_repo_head_hexsha": "ca944610614c182259783449d9ec6e9135d6aaf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1/lab1.py", "max_issues_repo_name": "yalov4uk/ML-labs", "max_issues_repo_head_hexsha": "ca944610614c182259783449d9ec6e9135d6aaf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1/lab1.py", "max_forks_repo_name": "yalov4uk/ML-labs", "max_forks_repo_head_hexsha": "ca944610614c182259783449d9ec6e9135d6aaf1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0316742081, "max_line_length": 90, "alphanum_fraction": 0.5662872447, "include": true, "reason": "import numpy", "num_tokens": 1889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399086356109, "lm_q2_score": 0.8933093975331751, "lm_q1q2_score": 0.8667244282459204}}
{"text": "import numpy as np\n\ndef dist(X1,X2):\n    \"\"\"\n    Compute the Euclidean distance between each row of X1 and X2\n    \"\"\"\n    X1sq = np.sum(np.square(X1),1)  \n    X2sq = np.sum(np.square(X2),1)\n    sqdist = -2.*np.dot(X1, X2.T) + (X1sq[:,None] + X2sq[None,:])\n    sqdist = np.clip(sqdist, 0, np.inf)\n    return sqdist \n\n\ndef d(x1,x2):\n    ''' Compute absolute distance between all elments of two vectors and output outersubtract matrix ''' \n    return np.abs(np.subtract.outer(x1,x2))\n\n\ndef SE_kernel(X1,X2,theta):\n    l = theta[1]\n    sigma_f = theta[2]\n    if l <=0 or sigma_f <= 0:\n        print(\"Check hyperparameter values!\")\n    sqdist = dist(X1,X2)\n    return sigma_f**2 * np.exp(-0.5*sqdist/(l**2))  \n        \ndef RQ_kernel(X1,X2,theta):\n    alpha = 2\n    l = theta[1]\n    sigma_f = theta[2]\n    if l <=0 or sigma_f <= 0:\n        print(\"Check hyperparameter values!\")\n    sqdist = dist(X1,X2)\n    return sigma_f**2 * (1+sqdist/(2*alpha*l**2))**(-alpha)\n\ndef camphor_copper_kernel(X1,X2,theta):\n    #This hyperparameter vector will work well:  theta=[0.001,0.26,0.1] (given that 0.05 added to lengthscale of RBF for z-variable)\n    #OLD hyperparameters that stood out in testing: theta=[0.09,0.2,0.35]\n    l = theta[1]\n    sigma_f = theta[2]\n    if l <=0 or sigma_f <= 0:\n        print(\"Check hyperparameter values!\")\n    ''' Same lenghtscale l across dimensions '''\n    ''' Periodic kernels has same period p=1 since data normalized to [0,1] '''\n    p = 1\n    kernelX = np.exp((-2*np.square(np.sin(np.pi*d(X1[:,0],X2[:,0])/p)))/l**2)\n    kernelY = np.exp((-2*np.square(np.sin(np.pi*d(X1[:,1],X2[:,1])/p)))/l**2)\n    kernelZ = np.exp(-0.5*np.square(d(X1[:,2],X2[:,2]))/((l+0.05)**2)) \n    ''' NOTE: 0.05 added to lengthscale of RBF for z-variable'''\n    kernelalpha = np.exp((-2*np.square(np.sin(np.pi*d(X1[:,3],X2[:,3])/p)))/l**2)\n    kernelbeta = np.exp((-2*np.square(np.sin(np.pi*d(X1[:,4],X2[:,4])/p)))/l**2)\n    kernelgamma = np.exp((-2*np.square(np.sin(np.pi*d(X1[:,5],X2[:,5])/p)))/l**2)\n    return sigma_f**2 * kernelX * kernelY * kernelZ * kernelalpha * kernelbeta * kernelgamma \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n\n", "meta": {"hexsha": "5bc9d730f69acf591ae9bc155cfcc5c743adfee1", "size": 2178, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/kernels.py", "max_stars_repo_name": "P-Mikkola/PPBO", "max_stars_repo_head_hexsha": "e734758d3b18c9070b4c1609f8074eceeab7892a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-07-15T08:57:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T13:31:35.000Z", "max_issues_repo_path": "src/kernels.py", "max_issues_repo_name": "AaltoPML/PPBO", "max_issues_repo_head_hexsha": "66b2708e232dd7fad49e6d2626ed0c67103f2e1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-27T14:41:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T14:41:39.000Z", "max_forks_repo_path": "src/kernels.py", "max_forks_repo_name": "AaltoPML/PPBO", "max_forks_repo_head_hexsha": "66b2708e232dd7fad49e6d2626ed0c67103f2e1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.25, "max_line_length": 132, "alphanum_fraction": 0.5771349862, "include": true, "reason": "import numpy", "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018390836985, "lm_q2_score": 0.8887588008585925, "lm_q1q2_score": 0.8667192170991219}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef derivative(a,b,n):\n    \"\"\"derivative(a,b,n)\n    Function to create the derivative matrix.  Takes 3 inputs:\n        - a = float, starting point of the domain\n        - b = float, end point of domain\n        - n = number of points created in the domain\n    Output: an 'n x n' 2-dimensional numpy array that, when matrix multiplied by a 1-D array,\n    returns the approximate derivative at each point.\"\"\"\n    t = np.linspace(a,b,n)\n    dx = t[1]-t[0]\n    empty = np.zeros(n, dtype = 'float64')\n    a,b = np.meshgrid(empty, empty)\n    A = a + b\n    #Forward Difference\n    A[0,0] = -1/dx\n    A[0,1] = 1/dx\n    #Symmetric Difference\n    index = np.arange(1,n-1)\n    A[index, index-1] = -1/(2*dx)\n    A[index, index+1] = 1/(2*dx)\n    #Backward Difference\n    A[n-1,n-2] = -1/dx\n    A[n-1,n-1] = 1/dx\n    return A\n\ndef second_derivative(a,b,n):\n    \"\"\"second_derivative(a,b,n)\n    Function to create the second derivative matrix.  Takes 3 inputs:\n        - a = float, starting point of the domain\n        - b = float, end point of domain\n        - n = number of points created in the domain\n    Output: an 'n x n' 2-dimensional numpy array that, when matrix multiplied by a 1-D array,\n    returns the approximate second derivative at each point.\"\"\"\n    t = np.linspace(a,b,n)\n    dx = t[1]-t[0]\n    empty = np.zeros(n, dtype = 'float64')\n    a,b = np.meshgrid(empty, empty)\n    A = a + b\n    #Forward Difference\n    A[0,0] = 1\n    A[0,1] = -2\n    A[0,2] = 1\n    #Symmetric/Forward Difference\n    A[1,0] = 2\n    A[1,1] = -3\n    A[1,3] = 1\n    #Symmetric Difference\n    index = np.arange(2,n-2)\n    A[index, index-2] = 1/2\n    A[index, index] = -1\n    A[index, index+2] = 1/2\n    #Symmetric/Backward Difference\n    A[n-2,n-4] = 1\n    A[n-2,n-2] = -3\n    A[n-2,n-1] = 2\n    #Backward Difference\n    A[n-1,n-3] = 1\n    A[n-1,n-2] = -2\n    A[n-1,n-1] = 1\n    return A*(1/(2*dx**2))\n\ndef f(a,b,n):\n    \"\"\"Returns an array of the square of the input (a float)\"\"\"\n    t = np.linspace(a,b,n)\n    return t**2\n\ndef s(a,b,n):\n    \"\"\"Returns an array of the sine of the input (float)\"\"\"\n    t = np.linspace(a,b,n)\n    sin = np.vectorize(np.sin)\n    sin = sin(t)\n    return sin\n\ndef g(a,b,n):\n    \"\"\"Returns an array of the gaussian function\"\"\"\n    def gauss(x):\n        \"\"\"Returns the Gaussian function dependent on the input float\"\"\"\n        c = 1/(np.sqrt(2*np.pi))\n        gauss = c*np.exp(-x**2/2)\n        return gauss\n    t = np.linspace(a,b,n)\n    gs = np.vectorize(gauss)\n    gs = gs(t)\n    return gs\n\ndef plot_function(a,b,n,f,string):\n    \"\"\"plot_function(a,b,n,f,string)\"\"\"\n    t = np.linspace(a,b,n)\n    deriv = np.dot(derivative(a,b,n),f)\n    sec_deriv = np.dot(second_derivative(a,b,n),f)\n    plt.plot(t,f,'b', label=string)\n    plt.plot(t,deriv,'r', label='Derivative')\n    plt.plot(t,sec_deriv,'g', label='Second Derivative')\n    plt.title(string)\n    plt.legend()\n    plt.show()\n", "meta": {"hexsha": "4e1357819d70ce9451915f5f120a85cc21c324e5", "size": 2979, "ext": "py", "lang": "Python", "max_stars_repo_path": "array_calc.py", "max_stars_repo_name": "chapman-phys220-2017f/cw-07-quinn-and-dain-and-andrew-cw-06", "max_stars_repo_head_hexsha": "59ffd765ae3e01fd04b65ef4f1dd047f6ea37e34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "array_calc.py", "max_issues_repo_name": "chapman-phys220-2017f/cw-07-quinn-and-dain-and-andrew-cw-06", "max_issues_repo_head_hexsha": "59ffd765ae3e01fd04b65ef4f1dd047f6ea37e34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "array_calc.py", "max_forks_repo_name": "chapman-phys220-2017f/cw-07-quinn-and-dain-and-andrew-cw-06", "max_forks_repo_head_hexsha": "59ffd765ae3e01fd04b65ef4f1dd047f6ea37e34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9223300971, "max_line_length": 93, "alphanum_fraction": 0.5824102048, "include": true, "reason": "import numpy", "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517095103498, "lm_q2_score": 0.90192067652954, "lm_q1q2_score": 0.8667022159537927}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 25 16:13:40 2017\n\n@author: ratnadeepb\n@License: MIT\n\"\"\"\n\n'''\nSquare matrices (n x n) are also vector space where an inner product can \nbe defined.\n\nIn M2,2 space let:\n    A = [[a11, a21], [a12, a22]]\n    B = [[b11, b21], [b12, b22]]\n    \nInner Product in M2,2:\n    <A, B> = a11*b11 + a21*b21 + a12*b12 + a22*b22\n'''\n\nimport numpy as np\nimport sys\n\n# Dot product of A and B\ndef mat_dot(A, B):\n    try:\n        A = np.array(A)\n        B = np.array(B)\n    except:\n        sys.exit(\"Not compatible\")\n    \n    bl = A.ndim == B.ndim\n    if not bl:\n        sys.exit(\"Not compatible\")\n    s = 0\n    for i in range(A.ndim):\n        for a, b in zip(A[i], B[i]):\n            s += a * b\n    return s\n\n# Norm of a Matrix\ndef mat_norm(A):\n    return np.sqrt(mat_dot(A, A))\n\n# Angle between two matrices\ndef mat_angle(A, B, op=\"radians\"):\n    if op not in [\"radians\", \"degrees\"]:\n        sys.exit(\"At this time we only handle radians and degrees\")\n    if op == \"degrees\":\n        return (mat_dot(A, B) / (mat_norm(A) * mat_norm(B))) * (180 / np.pi)\n    else:\n        return (mat_dot(A, B) / (mat_norm(A) * mat_norm(B)))\n\nif __name__ == \"__main__\":\n    A = [[11, -10], [4, 3]]\n    B = [[8, 7], [9, 16]]\n\n    print(\"Dot product of these matrices is:\", mat_dot(A, B))\n    print(\"Angle betwee the matrices is:\", mat_angle(A, B, \"degrees\"))", "meta": {"hexsha": "0365f3c7e8ff6e1b14b4ab1e53ac59f528d8b7b6", "size": 1390, "ext": "py", "lang": "Python", "max_stars_repo_path": "InnerProductSpaces/Examples/matspace.py", "max_stars_repo_name": "ratnadeepb/LinearAlgebra", "max_stars_repo_head_hexsha": "0f4399c15ba12a3e7c0e2a796c77efa66520e462", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "InnerProductSpaces/Examples/matspace.py", "max_issues_repo_name": "ratnadeepb/LinearAlgebra", "max_issues_repo_head_hexsha": "0f4399c15ba12a3e7c0e2a796c77efa66520e462", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "InnerProductSpaces/Examples/matspace.py", "max_forks_repo_name": "ratnadeepb/LinearAlgebra", "max_forks_repo_head_hexsha": "0f4399c15ba12a3e7c0e2a796c77efa66520e462", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1666666667, "max_line_length": 76, "alphanum_fraction": 0.5582733813, "include": true, "reason": "import numpy", "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.9059898254600903, "lm_q1q2_score": 0.8667008496466644}}
{"text": "import numpy as np\r\n\r\n# First method.... #np.array(p_object)\r\nmylist = [1,2,3]\r\nx = np.array(mylist)\r\nprint x\r\n\r\n\r\n# Direct Method\r\ny = np.array([2,4,5])\r\nprint y\r\n\r\n#2 dimensional array\r\nq = np.array([[136,53,64],[133,564,23]])\r\nprint q\r\nprint q.shape  #printing the dimension of the ARRAY\r\n\r\n\r\n#arange(start,stop,step,dtype) funtion\r\nz = np.arange(0,30,2) # arange(START, END, STEP size)\r\nprint z\r\n\r\n#reshape(a,newshape,order) function\r\nz = z.reshape(3,5)     #reshape(ROW,COLUMN)\r\nprint z\r\n\r\n\r\n#linspace(start,stop, HOW MANY Number we want in return) function\r\nw = np.linspace(0,4,8)\r\nprint w\r\n\r\n\r\n#resize(a, newshape) fuction OR give it matrix dimention you desire like below...\r\nw.resize((3,4))\r\nprint w\r\n\r\n\r\n#resize() another example        #Changing the dimensions of the array.\r\na = np.array([[0,1],[2,3]])\r\na = np.resize(a,(2,6))\r\nprint a\r\n\r\nb = np.ones((3,2))   #creates 1's matrix of 3by2\r\nprint b\r\n\r\nc = np.zeros((5,2))  #creates 0's matrix of 5by2\r\nprint c\r\n\r\nd = np.eye((5))  #creates identity matrix of 5by5\r\nprint d\r\n\r\ne = np.diag(x)  #creates a diagonal matrix of the given NUMPY ARRAY\r\nprint e\r\n\r\nf = np.array([1,3,2]*4)  #passing a repeated list..\r\nprint f\r\n\r\n#repeat(a, repeats, axis) function\r\ng = np.repeat([1,2,3],3)  #repeating each element of the list to the given times..\r\nprint g\r\n\r\n\r\n#We can also combine arrays to create new ones. Let's create a two by three array of ones and stack it vertically\r\n# with itself, multiplied by 2. And here's the same thing, but stacking horizontally.\r\n\r\nh = np.ones([2,3], int)\r\n#print h                      #adding a matrix of 2 vertically below to the exsisting array\r\nh = np.vstack([h, 2*h])\r\nprint h\r\n\r\ni = np.ones([2,3], int)\r\ni = np.hstack([i, 2*i])      #adding a matrix of 2 horizontally side to the exsisting array\r\nprint i\r\n\r\n#Mathematical OPERATIONS, element wise...\r\n\r\nj = np.array([1,2,3],float)\r\nk = np.array([4,5,6], float)\r\n\r\nprint j+k   #Addition\r\n\r\nprint j*k   #Multiplication\r\n\r\nprint j**2  #j to the power of 2..\r\n\r\nprint k/j  #Divison\r\n\r\nprint k.dot(j) # here  j = [1,2,3] and k = [4,5,6] => [(4.1)+(5.2)+(6.3)] = 14  DOT product\r\n\r\n#Let's create a new array using a previous array y and its squared values. The shape of this array is two by three.\r\nl = np.array([j, j**2])\r\nprint l\r\nprint l.shape\r\n\r\n\r\n#We can also take the transpose of an array using the T method, which swaps the rows and columns.\r\n# The shape of the transposed array is three by two.\r\nm = l.T\r\nprint m\r\nprint m.shape\r\n\r\nprint m.dtype #Type of the Array\r\n\r\nm = m.astype('i')   #typecasting of the Array...\r\nprint m.dtype\r\n\r\n#Some more inbuilt fuctions of NumPy\r\no = np.array([46,45,21,53,75])   #New Array...\r\n\r\nprint o.sum()       #SUM of the Array\r\nprint o.max()       #Maximum number/value in the Array\r\nprint o.min()       #Minimum number/value in the Array\r\nprint o.mean()      #Mean value of the Array\r\nprint o.std()       #Standard Diviation of the Array\r\nprint o.argmax()    #To find the index value of the Maximum Value in the Array... Indexing starts with 0th address..\r\nprint o.argmin()    #To find the index value of the Minimum Value in the Array...  Indexing starts with 0th address..\r\n\r\n\r\n#Indexing/Slicing\r\n\r\np = np.arange(0,13) #an array of squared value of 0 to 12..\r\nprint p**2\r\n\r\nq = np.arange(13)**2 #Another method\r\nprint q\r\n\r\n#We can use bracket notation to get the value at a particular index, and the colon notation to get a range.\r\nprint q[0], q[2], q[0:7]\r\n\r\nprint q[1:5]\r\nprint q[-4:]\r\n\r\n#And here, we're starting fifth from the end, to the beginning of the array,\r\n# and counting backwards by the difference of two.\r\nprint q[-5::-2]\r\n\r\n\r\n#Let's see how this extends to a two-dimensional array. First, let's make a two dimensional array, 0 to 35.\r\n# We can get a specific value by using the comma notation.\r\n# Here's the value at the second row and second column\r\nr = np.arange(36)\r\nr.resize(6,6)\r\nprint r\r\nprint r[2,2]  #element at 2nd Row- 2nd Column\r\n\r\nprint r[3, 3:6] #Slice of the 3rd Row.. from column 3 to 6...\r\n\r\nprint r[:2 , :-2] #Slicing(getting) first 2 rows except the last 2 columns..\r\n\r\nprint r[-1 , ::2] #Getting every alternate 2nd element from the last Row\r\n\r\n\r\n\r\n\r\n# [] operator for Conditional indexing and assignment\r\nr[r>20] #finding all the elements greater than 20 and repalcing them with 30\r\nr[r>20] = 30  #\r\nprint r\r\n\r\n\r\n\r\n\r\n#Copying element in NumPy\r\nr2 = r[:3, :3] #printing first 3 rows and columns from the orignal array 'r'....\r\nprint r2\r\n\r\nr2[:] = 0 #Assigning 0's to the sliced array...\r\nprint r2\r\n\r\nprint r   #In the original array that sliced part also becomes 0...\r\n\r\n# USE ...r.copy() function is used if we want to create copy of the original array\r\n# and doesn't change the original array..\r\n\r\nr_copy = r.copy() #creating the copy of the original array...\r\nprint r_copy\r\n\r\nr_copy[:] =10\r\nprint r_copy\r\nprint r         #Notice that the element of the original array has not changed...\r\n\r\n\r\n\r\n\r\n#Iterating over Arrays...\r\n#Creating a 4by3 matrix of random numbers from 0to9...\r\ntest = np.random.randint(0, 10, (4,3))\r\nprint test\r\n\r\nfor row in test: #iterating by ROW through array...\r\n    print (row)\r\n\r\nfor i in range(len(test)): #iterating by ROW INDEX...\r\n    print (test [i])\r\n\r\nfor i, row in enumerate(test): #Enumerate Gives the ROW and the Index of the ROW...\r\n    print('row', i, 'is', row)\r\n\r\ntest2 = test**2\r\nprint test2\r\n\r\n#ZIP() fucntion to iterate between 2 Matrix simultaneously...\r\nfor i, j in zip(test, test2):\r\n    print(i, '+', j, '=', i+j)\r\n\r\n\r\n#Using resize and reshape functions to find different patterns of matrix...\r\ns = np.arange(0,36)\r\n#print s\r\ns.resize(6,6)\r\nprint s\r\n\r\nprint s.reshape(36)[::7]\r\nprint s[2:4,2:4]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "da9a876a489c5c0394d9dbffec1a3caf9e7cc787", "size": 5694, "ext": "py", "lang": "Python", "max_stars_repo_path": "start_numpy.py", "max_stars_repo_name": "Asummit/Python-NumPy", "max_stars_repo_head_hexsha": "1a9617740e82ef855d2b41d0812d3ca83742d623", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-08-08T06:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-08T06:08:27.000Z", "max_issues_repo_path": "start_numpy.py", "max_issues_repo_name": "Asummit/Python-NumPy", "max_issues_repo_head_hexsha": "1a9617740e82ef855d2b41d0812d3ca83742d623", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "start_numpy.py", "max_forks_repo_name": "Asummit/Python-NumPy", "max_forks_repo_head_hexsha": "1a9617740e82ef855d2b41d0812d3ca83742d623", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5431034483, "max_line_length": 118, "alphanum_fraction": 0.6533192835, "include": true, "reason": "import numpy", "num_tokens": 1681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.9111797015700343, "lm_q1q2_score": 0.8666614854257061}}
{"text": "import numpy as np\r\nimport random\r\n\r\n#import the data. Note that the txt file has to be in the same folder\r\ndata = np.loadtxt('cdata.txt')\r\n\r\n#function for calculating standard deviation by using eq (5) from lab 2\r\ndef std5(val):\r\n    mean = (1./len(val))*np.sum(val) # 1st pass to find mean\r\n    sumOfDifference = 0\r\n    for i in val: # 2nd pass to find difference\r\n        sumOfDifference += (i - mean) ** 2\r\n    ans5 = np.sqrt((1./(len(val)-1)) * sumOfDifference)\r\n    return ans5\r\n\r\n#function for calculating standard deviation by using eq (6) from lab 2\r\ndef std6(val):\r\n    sumForMean = 0 #this is for calculating the mean \r\n    sumOfSquare = 0 #this is for calculating the sum of sqaured element\r\n    for i in val: #only pass through data set\r\n        sumForMean += i\r\n        sumOfSquare += (i ** 2)\r\n        if sumOfSquare < sumForMean: #check to prevent sqrt negative number\r\n            print('you are wrong, but the code will still run')\r\n            sumOfSquare += sumForMean #will make it larger than sum for mean but std will be wrong\r\n    ans6 = np.sqrt((1./(len(val)-1)) * (sumOfSquare - len(val)*((sumForMean/len(val)) ** 2)))\r\n    return ans6\r\n\r\n#using numpy.std method as our reference answer\r\ncorrectAnswer = np.std(data, ddof=1)\r\n\r\n#using (x-y)/y to calculate relative error from lab 2\r\nprint('The relative error of method 5: ', np.abs(std5(data) - correctAnswer)/correctAnswer)\r\nprint('The relative error of method 6: ', np.abs(std6(data) - correctAnswer)/correctAnswer)\r\n\r\n#constants for generating set 1\r\nmean1, sigma1, n1 = (0., 1., 2000)\r\n#constants for generating set 2\r\nmean2, sigma2, n2 = (1.e7, 1., 2000)\r\n\r\n#set 1 data\r\ndata1= np.random.normal(mean1, sigma1, n1)\r\n#set 2 data\r\ndata2= np.random.normal(mean2, sigma2, n2)\r\n\r\n#using numpy.std method to calculate respective answers\r\ncorrectAnswer1 = np.std(data1, ddof=1)\r\ncorrectAnswer2 = np.std(data2, ddof=1)\r\n\r\n#using same method as above to calculate relative error for set 1\r\nprint('The relative error of method 5 of set 1: ', np.abs(std5(data1) - correctAnswer1)/correctAnswer1)\r\nprint('The relative error of method 6 of set 1: ', np.abs(std6(data1) - correctAnswer1)/correctAnswer1)\r\n\r\n#using same method as above to calculate relative error for set 2\r\nprint('The relative error of method 5 of set 2: ', np.abs(std5(data2) - correctAnswer2)/correctAnswer2)\r\nprint('The relative error of method 6 of set 2: ', np.abs(std6(data2) - correctAnswer2)/correctAnswer2)\r\n\r\ndef std6Improved(val):\r\n    sumForMean = 0 #same setup as above\r\n    sumOfSquare = 0\r\n    adjust = random.choice(val) #randomly pick an element to shift data set close to 0 and 1\r\n    for i in val:\r\n        sumForMean += i - adjust #shifting each data point\r\n        sumOfSquare += ((i - adjust) ** 2) #shifting each data point\r\n        if sumOfSquare < 0:\r\n            print('you are wrong, but the code will still run')\r\n            np.abs(sumOfSquare)\r\n    #no need to account the adjustment into std calculation because shifting data set does not effect value of std\r\n    ans6 = np.sqrt((1./(len(val)-1))*(sumOfSquare - (sumForMean ** 2)/len(val)))\r\n    return ans6\r\n\r\n#using same method as above to calculate relative error for improved eq 6\r\nprint('The relative error of method 6 with improved method: ', np.abs(std6Improved(data) - correctAnswer)/correctAnswer)\r\n", "meta": {"hexsha": "9e784f82fca476cbfad9c3bee366664506609e0e", "size": 3322, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab2/lab2_Q1.py", "max_stars_repo_name": "fancent/PHY407", "max_stars_repo_head_hexsha": "38ce8badb9537060becc255ec64e6de2968ca73c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-20T17:30:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-20T17:30:06.000Z", "max_issues_repo_path": "Lab2/lab2_Q1.py", "max_issues_repo_name": "fancent/PHY407", "max_issues_repo_head_hexsha": "38ce8badb9537060becc255ec64e6de2968ca73c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab2/lab2_Q1.py", "max_forks_repo_name": "fancent/PHY407", "max_forks_repo_head_hexsha": "38ce8badb9537060becc255ec64e6de2968ca73c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-12T14:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T14:21:13.000Z", "avg_line_length": 44.8918918919, "max_line_length": 121, "alphanum_fraction": 0.6845273931, "include": true, "reason": "import numpy", "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.9111796979521253, "lm_q1q2_score": 0.8666614845084087}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom Generaldistribution import Distribution\n\nclass Gaussian (Distribution):\n\n    \"\"\"\n    Gaussian distribution class for calculating and\n    visualizing a Gaussian distribution.\n\n    Attributes:\n        mean (float) represent the mean values of the distribution\n        stdev (float) represent standard deviation of the distribution\n        dat_list (list of float) extracted from the text file\n    \"\"\"\n    def __init__(self, mu = 0 , sigma = 1):\n\n        Distribution.__init__(self, mu , sigma)\n\n    def calcualte_mean(self):\n        \"\"\"\n        Function calculated the mean of the dataset\n\n        Args:\n            None\n        Returns:\n            float: mean of the dataset\n        \"\"\"\n\n        avg = float(sum(self.data / len(self.data)))\n        self.mean = avg\n\n        return self.mean\n\n    def calculate_stdev(self, sample=True):\n        \"\"\"\n        Function calculates the standard deviation of the dataset\n\n        Args:\n            sample (bool) whether the data is population or a sample\n        Returns:\n            float: standard deviation of the data set\n        \"\"\"\n\n        if sample:\n            n = len(self.data) - 1\n        else:\n            n = len(self.data)\n        mean = self.calcualte_mean()\n        sigma = 0\n\n        for data in self.data:\n            sigma += (data - mean)**2\n        sigma = np.sqrt(sigma/n)\n\n        self.stdev = sigma\n\n        return self.stdev\n\n\n     def plot_histogram(self):\n        \"\"\"\n        Function to output a histogram of the instance variable data\n        using matplotlib.pyplot library\n\n        Args:\n            None\n        Returns:\n            None\n        \"\"\"\n\n        plt.hist(self.data)\n        plt.title(\"Histogram of data\")\n        plt.xlabel('data')\n        pltylable('count')\n\n    def pdf(self , x):\n        \"\"\"\n        Probability Density Function calculates the Gaussian distribution\n\n        Args:\n            x (float): point for calculating the probability density function\n        \n        Returns:\n            float: probability density function as output\n        \"\"\"\n\n        prob = (1. /(self.stdev * np.sqrt(2*math.pi))) * np.exp(-.5*((x - self.mean) / self.stdev)**2)\n        return prob\n\n\n    def plot_histogram_pdf(self, n_spaces = 50):\n\n        \"\"\"Function to plot the normalized histogram of the data and a plot of the \n        probability density function along the same range\n        \n        Args:\n            n_spaces (int): number of data points \n        \n        Returns:\n            list: x values for the pdf plot\n            list: y values for the pdf plot\n            \n        \"\"\"\n        \n        mu = self.mean\n        sigma = self.stdev\n\n        min_range = min(self.data)\n        max_range = max(self.data)\n        \n         # calculates the interval between x values\n        interval = 1.0 * (max_range - min_range) / n_spaces\n\n        x = []\n        y = []\n        \n        # calculate the x values to visualize\n        for i in range(n_spaces):\n            tmp = min_range + interval*i\n            x.append(tmp)\n            y.append(self.pdf(tmp))\n\n        # make the plots\n        fig, axes = plt.subplots(2,sharex=True)\n        fig.subplots_adjust(hspace=.5)\n        axes[0].hist(self.data, density=True)\n        axes[0].set_title('Normed Histogram of Data')\n        axes[0].set_ylabel('Density')\n\n        axes[1].plot(x, y)\n        axes[1].set_title('Normal Distribution for \\n Sample Mean and Sample Standard Deviation')\n        axes[0].set_ylabel('Density')\n        plt.show()\n\n        return x, y\n\n    def __add__(self, other):\n\n        \"\"\"Function to add together two Gaussian distributions\n\n        Args:\n            other (Gaussian): Gaussian instance\n\n        Returns:\n            Gaussian: Gaussian distribution\n\n        \"\"\"\n\n        result = Gaussian()\n        result.mean = self.mean + other.mean\n        result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2)\n\n        return result\n\n\n    def __repr__(self):\n\n        \"\"\"Function to output the characteristics of the Gaussian instance\n\n        Args:\n            None\n\n        Returns:\n            string: characteristics of the Gaussian\n\n        \"\"\"\n\n        return \"mean {}, standard deviation {}\".format(self.mean, self.stdev)\n\n\n\nif __name__ == \"__main__\":\n    # initialize two gaussian distributions\n    gaussian_one = Gaussian(25, 3)\n    gaussian_two = Gaussian(30, 2)\n    \n    # initialize a third gaussian distribution reading in a data efile\n    gaussian_three = Gaussian()\n    gaussian_three.read_data_file('numbers.txt')\n    gaussian_three.calculate_mean()\n    gaussian_three.calculate_stdev()\n\n\n    # print out the mean and standard deviations\n    print(gaussian_one.mean)\n    print(gaussian_two.mean)\n    \n    print(gaussian_one.stdev)\n    print(gaussian_two.stdev)\n\n    print(gaussian_three.mean)\n    print(gaussian_three.stdev)\n\n\n    # plot histogram of gaussian three\n    gaussian_three.plot_histogram_pdf()\n\n\n    # add gaussian_one and gaussian_two together\n    gaussian_one + gaussian_two\n\n", "meta": {"hexsha": "75f8dc5d33f27181ff7a6ff8b27dab87db6d7b5a", "size": 5035, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/distributions/Gaussiandistribution.py", "max_stars_repo_name": "MafikengZ/Distributions", "max_stars_repo_head_hexsha": "7ad12efa3930d214a2fc5454b34c9fdd6dafe317", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distributions/Gaussiandistribution.py", "max_issues_repo_name": "MafikengZ/Distributions", "max_issues_repo_head_hexsha": "7ad12efa3930d214a2fc5454b34c9fdd6dafe317", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distributions/Gaussiandistribution.py", "max_forks_repo_name": "MafikengZ/Distributions", "max_forks_repo_head_hexsha": "7ad12efa3930d214a2fc5454b34c9fdd6dafe317", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.802955665, "max_line_length": 102, "alphanum_fraction": 0.5874875869, "include": true, "reason": "import numpy", "num_tokens": 1067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811631528336, "lm_q2_score": 0.8976953016868439, "lm_q1q2_score": 0.8666181344992792}}
{"text": "import sympy as sp\nx, y, z = sp.symbols('x y z')\nsp.init_printing()\n\n# Here we simply give the input needed as The Following:\n# ( Xi ) is the initial point  \n# ( Xminus1 ) is the point before the Initial toint  \n# ( Fx ) is the equation of the function \n# ( n ) is the number of Iterations needed\n\nXi = 0\n\nXminus1 = -0.5\n\nFx = sp.cos(x)+2*sp.sin(x)+x**2\n\nn = 5\n\nprint(\"\\n____________________________________\")\nprint(\" Iteration |    Xi     ||   Error \"\n      \"\\n------------------------------------\")\nError = 0 ; XiPlus1 = 0\nfor i in range (n):\n    FxVal = float(Fx.subs(x, Xi).evalf())\n    FminusVal = float(Fx.subs(x, Xminus1).evalf())\n    XiPlus1 = Xi - FxVal*(Xi - Xminus1)/(FxVal - FminusVal)\n    Error = abs(((XiPlus1 - Xi)/XiPlus1) *100)\n    print(\"      {0:1d}    | {1:.6f} || {2:.6f}%\\n\"\n          .format(i+1, Xi, Error)) \n    Xminus1 = Xi ; Xi = XiPlus1\n\n# In The End The Program Prints The Output as well as The Percentage of error between Iterations\n", "meta": {"hexsha": "d6fa334a91a2215f30442b70528f69aea19fe5b9", "size": 963, "ext": "py", "lang": "Python", "max_stars_repo_path": "Secant-Method.py", "max_stars_repo_name": "Mezo0099/Numerical-Methods", "max_stars_repo_head_hexsha": "4a7321babb7c727152c69f543e784f00cf5ba059", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Secant-Method.py", "max_issues_repo_name": "Mezo0099/Numerical-Methods", "max_issues_repo_head_hexsha": "4a7321babb7c727152c69f543e784f00cf5ba059", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Secant-Method.py", "max_forks_repo_name": "Mezo0099/Numerical-Methods", "max_forks_repo_head_hexsha": "4a7321babb7c727152c69f543e784f00cf5ba059", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1818181818, "max_line_length": 96, "alphanum_fraction": 0.5939771547, "include": true, "reason": "import sympy", "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811651448431, "lm_q2_score": 0.897695295528596, "lm_q1q2_score": 0.8666181303424402}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 27 13:31:03 2019\n\n@author: alankar\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x,c):\n    return 1-np.exp(-c*x)\n\ndef fpi(func,x0, tol, verbose, *args): #x0 is initial guess\n    x_old = x0\n    x_new = x0+10  #some arbitrary initialization\n    counter = 0\n    while(np.abs(x_new-x_old)>=tol):\n        counter += 1\n        x_old = x_new\n        x_new = func(x_old,*args)\n    if (verbose==True): print (\"Converged in %d steps\"%counter)\n    return x_new\n\nc = 2\nprint('Fixed Point Iteration:')\nprint('Solution for x=1-exp(-%.2f x) is: x=%f\\n'%(c,fpi(f,0.5,1e-6,True,c)))\n\nc = np.arange(0,3,0.01)\nx = np.zeros(len(c))\nfor i in range(len(c)):\n    x[i] = fpi(f,0.5,1e-6,False,c[i])\n\nplt.plot(c,x)\nplt.grid()\nplt.xlabel('c',size=18)\nplt.ylabel('x',size=18)\n#plt.savefig('tansition.jpg')\n\ndef steffensen_fpi(func,x0, tol, verbose, *args):\n    x_old = x0\n    x_new = x0+10  #some arbitrary initialization\n    counter = 0\n    while(np.abs(x_new-x_old)>=tol):\n        counter +=1\n        x_old = x_new\n        g = (func(func(x_old,*args),*args)-func(x_old,*args))/(func(x_old,*args)-x_old)-1\n        x_new = x_old-(func(x_old,*args)-x_old)/g\n    if (verbose==True): print (\"Converged in %d steps\"%counter)\n    return x_new\n\nc = 2\nprint('Accelerated Fixed Point Iteration')\nprint('Solution for x=1-exp(-%.2f x) is: x=%f'%(c,steffensen_fpi(f,0.5,1e-6,True,c)))\n\nplt.show()\n\n\"\"\"\nOutput\n\nFixed Point Iteration:\nConverged in 15 steps\nSolution for x=1-exp(-2.00 x) is: x=0.796813\n\nAccelerated Fixed Point Iteration\nConverged in 4 steps\nSolution for x=1-exp(-2.00 x) is: x=0.796812\n\"\"\"", "meta": {"hexsha": "fa64428c85a7c6b1e3614d09b344f2f771cceaaf", "size": 1651, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw2/04/4.py", "max_stars_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_stars_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:47:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:05:39.000Z", "max_issues_repo_path": "hw2/04/4.py", "max_issues_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_issues_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw2/04/4.py", "max_forks_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_forks_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-21T17:33:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T02:58:56.000Z", "avg_line_length": 24.2794117647, "max_line_length": 89, "alphanum_fraction": 0.6329497274, "include": true, "reason": "import numpy", "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368928, "lm_q2_score": 0.9284088050123332, "lm_q1q2_score": 0.8666053907066799}}
{"text": "from pyccel.decorators import types\n\n#==============================================================================\n\n@types( int )\ndef sum_natural_numbers( n ):\n    x = 0\n    for i in range( 1, n+1 ):\n        x += i\n    return x\n\n# ...\n@types( int )\ndef factorial( n ):\n    x = 1\n    for i in range( 2, n+1 ):\n        x *= i\n    return x\n\n# ...\n@types( int )\ndef fibonacci( n ):\n    x = 0\n    y = 1\n    for i in range( n ):\n        z = x+y\n        x = y\n        y = z\n    return x\n\n# ...\n@types( int )\ndef double_loop( n ):\n    x = 0\n    for i in range( 3, 10 ):\n        x += 1\n        y  = n*x\n        for j in range( 4, 15 ):\n            z = x-y\n    return z\n\n# ...\n@types( 'int[:,:](order=C)' )\ndef double_loop_on_2d_array_C( z ):\n\n    from numpy import shape\n\n    s = shape( z )\n    m = s[0]\n    n = s[1]\n  \n    for i in range( m ):\n        for j in range( n ):\n            z[i,j] = i-j\n\n\n# ...\n@types( 'int[:,:](order=F)' )\ndef double_loop_on_2d_array_F( z ):\n\n    from numpy import shape\n\n    s = shape( z )\n    m = s[0]\n    n = s[1]\n\n    for i in range( m ):\n        for j in range( n ):\n            z[i,j] = i-j\n\n# ...\n@types( 'int[:,:](order=C)' )\ndef product_loop_on_2d_array_C( z ):\n\n    from numpy     import shape\n    from itertools import product\n\n    s = shape( z )\n    m = s[0]\n    n = s[1]\n\n    x = [i for i in range(m)]\n    y = [j for j in range(n)]\n\n    for i,j in product( x, y ):\n        z[i,j] = i-j\n\n# ...\n@types( 'int[:,:](order=F)' )\ndef product_loop_on_2d_array_F( z ):\n\n    from numpy     import shape\n    from itertools import product\n\n    s = shape( z )\n    m = s[0]\n    n = s[1]\n\n    x = [i for i in range(m)]\n    y = [j for j in range(n)]\n\n    for i,j in product( x, y ):\n        z[i,j] = i-j\n\n# ...\n@types( 'int[:]' )\ndef map_on_1d_array( z ):\n\n    @types( int )\n    def f( x ):\n        return x+5\n\n    res = 0\n    for v in map( f, z ):\n        res *= v\n\n    return res\n\n# ...\n@types( 'int[:]' )\ndef enumerate_on_1d_array( z ):\n\n    res = 0\n    for i,v in enumerate( z ):\n        res += v*i\n\n    return res\n\n# ...\n@types( int )\ndef zip_prod( m ):\n\n    x = [  i for i in range(m)]\n    y = [2*j for j in range(m)]\n\n    res = 0\n    for i1,i2 in zip( x, y ):\n        res += i1*i2\n\n    return res\n", "meta": {"hexsha": "0897e79ab65403fa8e2cdcb56a714c6c964c4950", "size": 2225, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/epyccel/modules/loops.py", "max_stars_repo_name": "toddrme2178/pyccel", "max_stars_repo_head_hexsha": "deec37503ab0c5d0bcca1a035f7909f7ce8ef653", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/epyccel/modules/loops.py", "max_issues_repo_name": "toddrme2178/pyccel", "max_issues_repo_head_hexsha": "deec37503ab0c5d0bcca1a035f7909f7ce8ef653", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/epyccel/modules/loops.py", "max_forks_repo_name": "toddrme2178/pyccel", "max_forks_repo_head_hexsha": "deec37503ab0c5d0bcca1a035f7909f7ce8ef653", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.780141844, "max_line_length": 79, "alphanum_fraction": 0.4462921348, "include": true, "reason": "from numpy", "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.9284087931273041, "lm_q1q2_score": 0.8666053710164645}}
{"text": "#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nInterpolation module\r\n\r\nWe have analytic interpolation using SymPy and numerical interpolation\r\nthat returns an evaluable function.\r\n\"\"\"\r\nimport sympy as sym\r\n\r\n#%% Analytic interpolation\r\ndef basis_lagrange(x_data, var, i):\r\n    \"\"\"\r\n    Compute the basis interpolant polynomial corresponding to the\r\n    i-th  point given in x_data\r\n\r\n    Parameters\r\n    ----------\r\n    x_data : list\r\n        List with x coordinates for the interpolation.\r\n    var : SymPy symbol\r\n        Variable to be used for the interpolation\r\n    i : int\r\n        Point number for the interpolant.\r\n\r\n    Returns\r\n    -------\r\n    poly : SymPy expression\r\n        Interpolant polynomial in variable var.\r\n\r\n    \"\"\"\r\n    prod = 1\r\n    num = len(x_data)\r\n    for j in range(num):\r\n        if j == i:\r\n            continue\r\n        prod = prod * (var - x_data[j])/(x_data[i] - x_data[j])\r\n    return sym.simplify(prod)\r\n\r\n\r\ndef lagrange_poly(x_data, y_data, var):\r\n    \"\"\"\r\n    Compute the interpolant polynomial corresponding to the\r\n    points given in (x_data, y_data)\r\n\r\n    Parameters\r\n    ----------\r\n    x_data : list\r\n        List with x coordinates for the interpolation.\r\n    y_data : list\r\n        List with y coordinates for the interpolation.\r\n    var : SymPy symbol\r\n        Variable to be used for the interpolation\r\n\r\n    Returns\r\n    -------\r\n    poly : SymPy expression\r\n        Interpolant polynomial in variable var.\r\n\r\n    \"\"\"\r\n    poly = 0\r\n    num = len(x_data)\r\n    for i in range(num):\r\n        poly = poly + y_data[i] * basis_lagrange(x_data, var, i)\r\n    return poly\r\n\r\n\r\n#%% Numerical interpolation\r\ndef lagrange(x_data, y_data):\r\n    \"\"\"\r\n    Compute the interpolant polynomial corresponding to the\r\n    points given in (x_data, y_data)\r\n\r\n    Parameters\r\n    ----------\r\n    x_data : list\r\n        List with x coordinates for the interpolation.\r\n    y_data : list\r\n        List with y coordinates for the interpolation.\r\n\r\n    Returns\r\n    -------\r\n    fun_poly : Python function\r\n        Interpolant polynomial as evaluable function.\r\n\r\n    \"\"\"\r\n    def fun_poly(x):\r\n        num = len(x_data)\r\n        acu = 0\r\n        for i in range(num):\r\n            prod = 1\r\n            for j in range(num):\r\n                if i == j:\r\n                    continue\r\n                prod = prod * (x - x_data[j])/(x_data[i] - x_data[j])\r\n            acu = acu + prod * y_data[i]\r\n        return acu\r\n    return fun_poly\r\n", "meta": {"hexsha": "5687779487a06145e3bf62b28d6d104e98f38e98", "size": 2468, "ext": "py", "lang": "Python", "max_stars_repo_path": "codigo/metodos_numericos/interpolacion/interpolation.py", "max_stars_repo_name": "AppliedMechanics-EAFIT/Mod_Temporal", "max_stars_repo_head_hexsha": "6a0506d906ed42b143b773777e8dc0da5af763eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-02-20T18:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-19T22:44:44.000Z", "max_issues_repo_path": "codigo/metodos_numericos/interpolacion/interpolation.py", "max_issues_repo_name": "AppliedMechanics-EAFIT/Mod_Temporal", "max_issues_repo_head_hexsha": "6a0506d906ed42b143b773777e8dc0da5af763eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-04-15T00:22:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-04T17:03:54.000Z", "max_forks_repo_path": "codigo/metodos_numericos/interpolacion/interpolation.py", "max_forks_repo_name": "AppliedMechanics-EAFIT/Mod_Temporal", "max_forks_repo_head_hexsha": "6a0506d906ed42b143b773777e8dc0da5af763eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-14T18:17:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-27T06:37:05.000Z", "avg_line_length": 24.9292929293, "max_line_length": 71, "alphanum_fraction": 0.572528363, "include": true, "reason": "import sympy", "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914018751051, "lm_q2_score": 0.8962513675912913, "lm_q1q2_score": 0.8665980116488209}}
{"text": "import numpy as np\n\n\nA = np.array([[1,2],[3,4]])\n\n# matrix inverse, the inverse function is in the linalg module\n\n\na_inv = np.linalg.inv(A)\nprint(a_inv)\n\n# verifying the Inverse by multiplying with A resulting in I\n\nprint(a_inv.dot(A))\n\n# matrix determinant\n\ndet_a = np.linalg.det(A)\nprint(det_a)\n\n# diagonal of a matrix\n\ndiag_a = np.diagonal(A) # gives diagonal elements in a vector\nprint(diag_a)\n\n# to make a 2D array of diagonal\n\ndiag_2d = np.diag(diag_a)\nprint(diag_2d)\n\n# remember that if you pass a 2D array to diag it will\n# return diagonal elements in a 1D array\n\n## if you pass a 1D array to diag, it will return a 2D array where the\n## off diagonals are zero and the original array takes up the diagonal\n\n#Outer Product\n\na = np.array([1,2])\n\nb = np.array([3,4])\n\nout_prod = np.outer(a,b)\nprint(out_prod)\n\n# we can also do inner product like below, inner product is the same\n# as outer product\n\ninn_prod = np.inner(a,b)\nprint(inn_prod)\n\n# Trace of a Matrix , is nothing but the sum of the elements of diagonal\n\n#method1\nprint(A)\nprint(np.diag(A).sum())\n\n#method2\nprint(np.trace(A))\n\n\nx = np.random.randn(100,3) # by convention this is 100 observations\n                           # 3 features\n#to calculate covariance\ncov = np.cov(x)\nprint(cov)\n\nprint(cov.shape) # this results in (100,100) which is wrong\n                 # since we have only 3 features , it has to be (3,3)\n\n\nprint(np.cov(np.transpose(x)).shape) # this looks ugly\n\n# there are two methods to calculate eigenvalues and eigenvectors\n\n# np.eig(A) and np.eigh(A) ; eigh is used for symmetric matrices\n# and hermitian matrices\n\n# symmetric means a == transpose(a)\n\n# hermitian means a == conjugate transpose ( a )\n\n# since covariance is a symmetric matrix , we are using eigh\n\neig_cov = np.linalg.eigh(cov) # gives out a tuple containing\n                              # in the first eigenvalues\n                              # in the second corresponding eigenvectors\nprint(eig_cov)\n\n\n\n\n\n\n\n", "meta": {"hexsha": "661a34ebba6e25c3e30017ff75e7d84b1c96e3d2", "size": 1962, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumpyStack/numpy/matrix_operations.py", "max_stars_repo_name": "Binary-bug/Python", "max_stars_repo_head_hexsha": "233425ded6abc26c889599a82a181487789e3bab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NumpyStack/numpy/matrix_operations.py", "max_issues_repo_name": "Binary-bug/Python", "max_issues_repo_head_hexsha": "233425ded6abc26c889599a82a181487789e3bab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumpyStack/numpy/matrix_operations.py", "max_forks_repo_name": "Binary-bug/Python", "max_forks_repo_head_hexsha": "233425ded6abc26c889599a82a181487789e3bab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4375, "max_line_length": 72, "alphanum_fraction": 0.6839959225, "include": true, "reason": "import numpy", "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.9046505440982949, "lm_q1q2_score": 0.8665758603134823}}
{"text": "from __future__ import print_function\nfrom numpy import *\nimport numpy as np\nfrom scipy.special import comb \n\n# evaluates cubic bezier at t, return point\ndef q(ctrlPoly, t):\n    return (1.0-t)**3 * ctrlPoly[0] + 3*(1.0-t)**2 * t * ctrlPoly[1] + 3*(1.0-t)* t**2 * ctrlPoly[2] + t**3 * ctrlPoly[3]\n\n\n# evaluates cubic bezier first derivative at t, return point\ndef qprime(ctrlPoly, t):\n    return 3*(1.0-t)**2 * (ctrlPoly[1]-ctrlPoly[0]) + 6*(1.0-t) * t * (ctrlPoly[2]-ctrlPoly[1]) + 3*t**2 * (ctrlPoly[3]-ctrlPoly[2])\n\n\n# evaluates cubic bezier second derivative at t, return point\ndef qprimeprime(ctrlPoly, t):\n    return 6*(1.0-t) * (ctrlPoly[2]-2*ctrlPoly[1]+ctrlPoly[0]) + 6*(t) * (ctrlPoly[3]-2*ctrlPoly[2]+ctrlPoly[1])\n\n\ndef bernstein_poly(i, n, t):\n    \"\"\"\n     The Bernstein polynomial of n, i as a function of t\n    \"\"\"\n\n    return comb(n, i) * ( t**(n-i) ) * (1 - t)**i\n\n\n\ndef bezier_curve(points, nTimes=1000):\n    \"\"\"\n       Given a set of control points, return the\n       bezier curve defined by the control points.\n\n       points should be a list of lists, or list of tuples\n       such as [ [1,1], \n                 [2,3], \n                 [4,5], ..[Xn, Yn] ]\n        nTimes is the number of time steps, defaults to 1000\n\n        See http://processingjs.nihongoresources.com/bezierinfo/\n    \"\"\"\n\n    nPoints = len(points)\n    xPoints = np.array([p[0] for p in points])\n    yPoints = np.array([p[1] for p in points])\n\n    t = np.linspace(0.0, 1.0, nTimes)\n\n    polynomial_array = np.array([ bernstein_poly(i, nPoints-1, t) for i in range(0, nPoints)   ])\n\n    xvals = np.dot(xPoints, polynomial_array)\n    yvals = np.dot(yPoints, polynomial_array)\n\n    return xvals, yvals\n\n\nif __name__ == \"__main__\":\n    from matplotlib import pyplot as plt\n\n    nPoints = 4\n    points = np.random.rand(nPoints,2)*200\n    xpoints = [p[0] for p in points]\n    ypoints = [p[1] for p in points]\n\n    xvals, yvals = bezier_curve(points, nTimes=1000)\n    plt.plot(xvals, yvals)\n    plt.plot(xpoints, ypoints, \"ro\")\n    for nr in range(len(points)):\n        plt.text(points[nr][0], points[nr][1], nr)\n\n    plt.show()\n\n", "meta": {"hexsha": "307258bfbbb3a1097a7625dad3bc4876fb4adefb", "size": 2112, "ext": "py", "lang": "Python", "max_stars_repo_path": "fitCurves/bezier.py", "max_stars_repo_name": "Tahlor/fitCurves", "max_stars_repo_head_hexsha": "e21b61e9f6cc828bf08f43eb7db4cc5c1ca82aac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fitCurves/bezier.py", "max_issues_repo_name": "Tahlor/fitCurves", "max_issues_repo_head_hexsha": "e21b61e9f6cc828bf08f43eb7db4cc5c1ca82aac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fitCurves/bezier.py", "max_forks_repo_name": "Tahlor/fitCurves", "max_forks_repo_head_hexsha": "e21b61e9f6cc828bf08f43eb7db4cc5c1ca82aac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5405405405, "max_line_length": 132, "alphanum_fraction": 0.6174242424, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799462157138, "lm_q2_score": 0.8991213833519949, "lm_q1q2_score": 0.8665551584883838}}
{"text": "from __future__ import annotations  # See: https://stackoverflow.com/a/33533514\n\nimport numpy as np\n\n\nclass Vector(object):\n\n    def __init__(self, coordinates: iter, tolerance: float = 1e-10) -> None:\n        try:\n            if not coordinates:\n                raise ValueError\n\n            self.coordinates = np.array(coordinates, dtype=np.float64)\n            self.dimension = len(coordinates)\n            self.tolerance = tolerance\n\n        except ValueError:\n            raise ValueError('The coordinates must be nonempty')\n\n        except TypeError:\n            raise TypeError('The coordinates must be an iterable')\n\n    def __str__(self) -> str:\n        return f'Vector: {self.coordinates}'\n\n    def __eq__(self, other: Vector) -> bool:\n        assert isinstance(other, Vector)\n\n        return self.coordinates == other.coordinates\n\n    def __add__(self, other: Vector) -> Vector:\n        assert isinstance(other, Vector)\n        assert self.dimension == other.dimension\n\n        coord = [i + j for i, j in zip(self.coordinates, other.coordinates)]\n\n        return Vector(coordinates=coord)\n\n    def __sub__(self, other: Vector) -> Vector:\n        assert isinstance(other, Vector)\n        assert self.dimension == other.dimension\n\n        coord = [i - j for i, j in zip(self.coordinates, other.coordinates)]\n\n        return Vector(coordinates=coord)\n\n    def scalar_mul(self, scalar: (int, float)) -> Vector:\n        assert isinstance(scalar, (int, float))\n\n        coordinates = [coord * scalar for coord in self.coordinates]\n\n        return Vector(coordinates=coordinates)\n\n    @property\n    def magnitude(self) -> float:\n        return np.sqrt(np.sum(np.power(self.coordinates, 2)))\n\n    @property\n    def direction(self) -> Vector:\n        try:\n            unit_coord = [coord / self.magnitude for coord in self.coordinates]\n            return Vector(coordinates=unit_coord)\n\n        except ZeroDivisionError:\n            raise Exception('Cannot normalize the zero vector')\n\n    def dot_product(self, other):\n        assert isinstance(other, Vector)\n\n        return sum(\n            [i * j for i, j in zip(self.coordinates, other.coordinates)]\n        )\n\n    def get_angle_with(self, other: Vector, in_degrees: bool = False) -> float:\n        assert isinstance(other, Vector)\n\n        unit_dot_prod = self.direction.dot_product(other.direction)\n        angle = np.arccos(unit_dot_prod)\n\n        if in_degrees:\n            angle *= 180/np.pi\n\n        return angle\n\n    @property\n    def is_null_vector(self) -> bool:\n        return self.magnitude < self.tolerance\n\n    def is_parallel_to(self, other: Vector) -> bool:\n        assert isinstance(other, Vector)\n\n        return (\n            self.is_null_vector or\n            other.is_null_vector or\n            self.get_angle_with(other=other) in (0, np.pi)\n        )\n\n    def is_orthogonal_to(self, other: Vector) -> bool:\n        assert isinstance(other, Vector)\n\n        return np.abs(self.dot_product(other=other)) < self.tolerance\n\n    def component_parallel_to(self, basis):\n        assert isinstance(basis, Vector)\n\n        if self.is_null_vector or basis.is_null_vector:\n            raise Exception('Cannot project from/to null vector')\n\n        u = basis.direction\n        weight = self.dot_product(other=u)\n\n        return u.scalar_mul(scalar=weight)\n\n    def component_orthogonal_to(self, basis: Vector) -> Vector:\n        assert isinstance(basis, Vector)\n\n        if self.is_null_vector or basis.is_null_vector:\n            raise Exception('Cannot project from/to null vector')\n\n        projection = self.component_parallel_to(basis=basis)\n        rejection = self - projection\n\n        return rejection\n\n    @staticmethod\n    def pad_third_dim(vector: Vector) -> Vector:\n        if vector.dimension == 2:\n            new_coordinates = vector.coordinates + (0, )\n            vector = Vector(coordinates=new_coordinates)\n\n        if vector.dimension != 3:\n            raise Exception(f'Wrong number of dimensions for vector {vector}')\n\n        return vector\n\n    def cross_product(self, other: Vector) -> Vector:\n        assert isinstance(other, Vector)\n\n        x1, y1, z1 = self.pad_third_dim(vector=self).coordinates\n        x2, y2, z2 = self.pad_third_dim(vector=other).coordinates\n\n        return Vector([\n            y1*z2 - y2*z1,\n            -(x1*z2 - x2*z1),\n            x1*y2 - x2*y1\n        ])\n\n    def get_area_parallelogram(self, other: Vector) -> float:\n        assert isinstance(other, Vector)\n\n        return self.cross_product(other=other).magnitude\n\n    def get_area_triangle(self, other: Vector) -> float:\n        assert isinstance(other, Vector)\n\n        return self.get_area_parallelogram(other=other) / 2\n\n\nif __name__ == '__main__':\n    # Test case 1\n    vector1 = Vector(coordinates=(8.218, -9.341))\n    vector2 = Vector(coordinates=(-1.129, 2.111))\n    print(vector1 + vector2)\n\n    # Test case 2\n    vector3 = Vector(coordinates=(7.119, 8.215))\n    vector4 = Vector(coordinates=(-8.223, 0.878))\n    print(vector3 - vector4)\n\n    # Test case 3\n    vector5 = Vector(coordinates=(1.671, -1.012, -0.318))\n    print(vector5.scalar_mul(scalar=7.41))\n\n    # Test case 4\n    vector6 = Vector(coordinates=(-0.221, 7.437))\n    print(vector6.magnitude)\n\n    vector7 = Vector(coordinates=(8.813, -1.331, 6.247))\n    print(vector7.magnitude)\n\n    # Test case 5\n    vector8 = Vector(coordinates=(5.581, -2.136))\n    print(vector8.direction)\n\n    vector9 = Vector(coordinates=(1.996, 3.108, -4.554))\n    print(vector9.direction)\n\n    # Test case 6\n    vector10 = Vector(coordinates=(7.887, 4.138))\n    vector11 = Vector(coordinates=(-8.802, 6.776))\n    print(vector10.dot_product(other=vector11))\n\n    vector12 = Vector(coordinates=(-5.955, -4.904, -1.874))\n    vector13 = Vector(coordinates=(-4.496, -8.755, 7.103))\n    print(vector12.dot_product(other=vector13))\n\n    # Test case 7\n    vector14 = Vector(coordinates=(3.183, -7.627))\n    vector15 = Vector(coordinates=(-2.668, 5.319))\n    print(vector14.get_angle_with(other=vector15))\n\n    vector16 = Vector(coordinates=(7.35, 0.221, 5.188))\n    vector17 = Vector(coordinates=(2.751, 8.259, 3.985))\n    print(vector16.get_angle_with(other=vector17, in_degrees=True))\n\n    # Test case 8\n    vector18 = Vector(coordinates=(-7.579, -7.88))\n    vector19 = Vector(coordinates=(22.737, 23.64))\n    print('Are parallel?', vector18.is_parallel_to(other=vector19))\n    print('Are orthogonal?', vector18.is_orthogonal_to(other=vector19))\n\n    vector20 = Vector(coordinates=(-2.029, 9.97, 4.172))\n    vector21 = Vector(coordinates=(-9.231, -6.639, -7.245))\n    print('Are parallel?', vector20.is_parallel_to(other=vector21))\n    print('Are orthogonal?', vector20.is_orthogonal_to(other=vector21))\n\n    vector22 = Vector(coordinates=(-2.328, -7.284, -1.214))\n    vector23 = Vector(coordinates=(-1.821, 1.072, -2.94))\n    print('Are parallel?', vector22.is_parallel_to(other=vector23))\n    print('Are orthogonal?', vector22.is_orthogonal_to(other=vector23))\n\n    vector24 = Vector(coordinates=(2.118, 4.827))\n    vector25 = Vector(coordinates=(0, 0))\n    print('Are parallel?', vector24.is_parallel_to(other=vector25))\n    print('Are orthogonal?', vector24.is_orthogonal_to(other=vector25))\n\n    # Test case 9\n    vector26 = Vector(coordinates=(3.039, 1.879))\n    vector27 = Vector(coordinates=(0.825, 2.036))\n    print(vector26.component_parallel_to(basis=vector27))\n\n    # Test case 10\n    vector28 = Vector(coordinates=(-9.88, -3.264, -8.159))\n    vector29 = Vector(coordinates=(-2.155, -9.353, -9.473))\n    print(vector28.component_orthogonal_to(basis=vector29))\n\n    # Test case 11\n    vector30 = Vector(coordinates=(3.009, -6.172, 3.692, -2.51))\n    vector31 = Vector(coordinates=(6.404, -9.144, 2.759, 8.718))\n    v_parallel = vector30.component_parallel_to(basis=vector31)\n    v_orthogonal = vector30.component_orthogonal_to(basis=vector31)\n    v = v_parallel + v_orthogonal\n    print(v_parallel, v_orthogonal)\n\n    # Test case 12\n    vector32 = Vector(coordinates=(8.462, 7.893, -8.187))\n    vector33 = Vector(coordinates=(6.984, -5.975, 4.778))\n    print(vector32.cross_product(other=vector33))\n\n    # Test case 13\n    vector34 = Vector(coordinates=(-8.987, -9.838, 5.031))\n    vector35 = Vector(coordinates=(-4.268, -1.861, -8.866))\n    print(vector34.get_area_parallelogram(other=vector35))\n\n    # Test case 14\n    vector36 = Vector(coordinates=(1.5, 9.547, 3.691))\n    vector37 = Vector(coordinates=(-6.007, 0.124, 5.772))\n    print(vector36.get_area_triangle(other=vector37))\n", "meta": {"hexsha": "297ec94f2c9ad24812e7981abd8d434e5793c6da", "size": 8512, "ext": "py", "lang": "Python", "max_stars_repo_path": "modules/vectors.py", "max_stars_repo_name": "guillecg/course-linear-algebra", "max_stars_repo_head_hexsha": "b45eed8a74a7ae085f3090ad705264e3bcea8ddc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/vectors.py", "max_issues_repo_name": "guillecg/course-linear-algebra", "max_issues_repo_head_hexsha": "b45eed8a74a7ae085f3090ad705264e3bcea8ddc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/vectors.py", "max_forks_repo_name": "guillecg/course-linear-algebra", "max_forks_repo_head_hexsha": "b45eed8a74a7ae085f3090ad705264e3bcea8ddc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8648648649, "max_line_length": 79, "alphanum_fraction": 0.6514332707, "include": true, "reason": "import numpy", "num_tokens": 2183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799410139922, "lm_q2_score": 0.8991213833519948, "lm_q1q2_score": 0.8665551538114046}}
{"text": "import numpy as np\r\n'''\r\n# min-max\r\na = np.array([[3,7,5],[8,4,3],[2,4,9]]) \r\nprint(\"input array: \\n\", a)\r\nprint(\"min: \", np.amin(a))\r\nprint(\"min axis =0 \", np.amin(a, axis=0))\r\nprint(\"min axis =1 \", np.amin(a, axis=1))\r\nprint(\"max: \", np.amax(a))\r\nprint(\"max axis =0 \", np.amax(a, axis=0))\r\nprint(\"max axis =1 \", np.amax(a, axis=1))\r\n'''\r\n# TODO: tpt and percentile methods\r\n'''\r\n# median & mean\r\na = np.array([[30,65,70],[80,95,10],[50,90,60]])\r\nprint(\"input array: \\n\", a)\r\nprint(\"median: \", np.median(a))\r\nprint(\"median axis =0 \", np.median(a, axis=0))\r\nprint(\"median axis =1 \", np.median(a, axis=1))\r\nprint(\"mean: \", np.mean(a))\r\nprint(\"mean axis =0 \", np.mean(a, axis=0))\r\nprint(\"mean axis =1 \", np.mean(a, axis=1))\r\n'''\r\n'''\r\n# weighted average\r\n\r\na = np.array([1,2,3,4])\r\nwts = np.array([4,3,2,1]) \r\nprint (\"weighted avg: \", np.average(a,weights = wts))\r\n'''\r\n\r\n# std deviation\r\n# Formula: std = sqrt(mean(abs(x - x.mean())**2))\r\nprint (\"standard deviation: \", np.std([1,2,3,4]))\r\n\r\n# variance\r\n# Formula mean(abs(x - x.mean())**2)\r\nprint(\"variance: \", np.var([1,2,3,4]))", "meta": {"hexsha": "9a05281d79b8709c462199e06ee7b92f1e7275c3", "size": 1079, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpu-tuto/numpy_rev_stati_ops.py", "max_stars_repo_name": "sourabhyadav/100-days-0f-DL-DevOps", "max_stars_repo_head_hexsha": "51bd1636323d117c7e2e11b62941efac5d4f2d74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpu-tuto/numpy_rev_stati_ops.py", "max_issues_repo_name": "sourabhyadav/100-days-0f-DL-DevOps", "max_issues_repo_head_hexsha": "51bd1636323d117c7e2e11b62941efac5d4f2d74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpu-tuto/numpy_rev_stati_ops.py", "max_forks_repo_name": "sourabhyadav/100-days-0f-DL-DevOps", "max_forks_repo_head_hexsha": "51bd1636323d117c7e2e11b62941efac5d4f2d74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6666666667, "max_line_length": 54, "alphanum_fraction": 0.5671918443, "include": true, "reason": "import numpy", "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799410139922, "lm_q2_score": 0.8991213786215105, "lm_q1q2_score": 0.8665551492522588}}
{"text": "import pandas as pd\nimport numpy as np\n\ndef params_mle(data):\n    '''\n    Fit data to a Guassian distribution with Maximum Likelihood Estimation (MLE)\n\n    Parameters\n    ----------\n    data : ndarray, list, dict, or DataFrame\n        Data to be tested for normality\n\n    Returns\n    -------\n    mle_params : Dataframe\n        Dataframe with the first row containing the estimated means and\n        the second row containing the estimated variance. The columns\n        present the original variables in the data\n\n    Examples\n    --------\n    iris_data = pd.DataFrame({\"length\": [1,2,3,4], \"width\": [5,6,7,8])\n    make_qqplot(iris_data)\n    '''\n\n\n    ## PREPROCESSING\n    ## =============\n\n    # Set default column names as indexes\n    try: # 2D data\n        n_var = data.shape[1]\n        var_names = range(n_var)\n    except: # 1D data\n        var_names = [0]\n\n    # Address different input types\n    if isinstance(data, pd.DataFrame):\n        var_names = list(data)\n        data = np.array(data)\n\n    elif isinstance(data, pd.Series):\n        if data.name != None:\n            var_names = [data.name]\n        data = np.array(data)\n\n    elif isinstance(data, list):\n        var_names = range(len(data))\n        data = np.transpose(np.array(data))\n\n    n_obs = data.shape[0]\n\n    ## Calculations\n    ## =============\n\n    # Calculate mu estimates\n    mu = np.sum(np.array(data), axis = 0)/n_obs\n\n    # Calculate sigma estimates\n    variance = np.sum((data - mu)**2, axis = 0)/n_obs\n    sigma = variance**(1/2)\n\n    ## Return results\n    ## ==============\n    mle_params = pd.DataFrame(np.vstack((mu, variance)), index = [\"Mean\", \"Variance\"], columns = var_names)\n    return(mle_params)\n", "meta": {"hexsha": "feb1e839893dd116fb0a9e5319a15432481d0c84", "size": 1685, "ext": "py", "lang": "Python", "max_stars_repo_path": "normtestPY/params_mle.py", "max_stars_repo_name": "LeeYinYing/normtestPY", "max_stars_repo_head_hexsha": "404d6f2c3db72b16ac5e83facc1047bacd4fd0fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "normtestPY/params_mle.py", "max_issues_repo_name": "LeeYinYing/normtestPY", "max_issues_repo_head_hexsha": "404d6f2c3db72b16ac5e83facc1047bacd4fd0fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "normtestPY/params_mle.py", "max_forks_repo_name": "LeeYinYing/normtestPY", "max_forks_repo_head_hexsha": "404d6f2c3db72b16ac5e83facc1047bacd4fd0fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1492537313, "max_line_length": 107, "alphanum_fraction": 0.5881305638, "include": true, "reason": "import numpy", "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812345563904, "lm_q2_score": 0.8947894562828416, "lm_q1q2_score": 0.8664973183432194}}
{"text": "from __future__ import division\n\nimport math\nimport numpy as np\nfrom typing import Optional\n\n\ndef build_sinusoidal_positional_embedding(\n    num_embeddings: int,\n    embedding_dim: int,\n    padding_idx: Optional[int] = None,\n    dtype=np.float32\n):\n    \"\"\"\n    Build sinusoidal embeddings\n    \"\"\"\n    half_dim = embedding_dim // 2\n    emb = math.log(10000) / (half_dim - 1)\n    emb = np.exp(-emb * np.arange(half_dim, dtype=dtype))\n    emb = np.arange(num_embeddings, dtype=dtype)[:, None] * emb[None, :]\n    emb = np.concatenate([np.sin(emb), np.cos(emb)], axis=1)\n    emb = np.reshape(emb, [num_embeddings, -1])\n    if embedding_dim % 2 == 1:\n        # zero pad\n        emb = np.concatenate(\n            [emb, np.zeros(shape=[num_embeddings, 1], dtype=dtype)],\n            axis=1\n        )\n    if padding_idx is not None:\n        emb[padding_idx, :] = 0\n    return emb\n", "meta": {"hexsha": "a0c5292682343084ee53d19cd91662e960bcb2d2", "size": 871, "ext": "py", "lang": "Python", "max_stars_repo_path": "transformer_2/utils/sinusoidal_positional_embedding.py", "max_stars_repo_name": "mingruimingrui/Transformer2", "max_stars_repo_head_hexsha": "2b44289ee7c7312d699f2261c1e4ebccce0f21e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "transformer_2/utils/sinusoidal_positional_embedding.py", "max_issues_repo_name": "mingruimingrui/Transformer2", "max_issues_repo_head_hexsha": "2b44289ee7c7312d699f2261c1e4ebccce0f21e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-01T02:13:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-01T02:13:10.000Z", "max_forks_repo_path": "transformer_2/utils/sinusoidal_positional_embedding.py", "max_forks_repo_name": "mingruimingrui/Transformer2", "max_forks_repo_head_hexsha": "2b44289ee7c7312d699f2261c1e4ebccce0f21e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.21875, "max_line_length": 72, "alphanum_fraction": 0.6222732491, "include": true, "reason": "import numpy", "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639677785088, "lm_q2_score": 0.8918110555020056, "lm_q1q2_score": 0.8664514875922685}}
{"text": "'''\nHow many defaults might we expect?\n100xp\n\nLet's say a bank made 100 mortgage loans. It is possible that anywhere between\n0 and 100 of the loans will be defaulted upon. You would like to know the probability\nof getting a given number of defaults, given that the probability of a default is\np = 0.05. To investigate this, you will do a simulation. You will perform 100 Bernoulli\ntrials using the perform_bernoulli_trials() function you wrote in the previous exercise\nand record how many defaults we get. Here, a success is a default. (Remember that the\nword \"success\" just means that the Bernoulli trial evaluates to True, i.e., did the loan\nrecipient default?) You will do this for another 100 Bernoulli trials. And again and again\nuntil we have tried it 1000 times. Then, you will plot a histogram describing the probability\nof the number of defaults.\n\nInstructions\n-Seed the random number generator to 42.\n-Initialize n_defaults, an empty array, using np.empty(). It should contain 1000 entries,\nsince we are doing 1000 simulations.\n-Write a for loop with 1000 iterations to compute the number of defaults per 100 loans using\nthe perform_bernoulli_trials() function. It accepts two arguments: the number of trials n -\nin this case 100 - and the probability of success p - in this case the probability of a default,\nwhich is 0.05. On each iteration of the loop store the result in an entry of n_defaults.\n-Plot a histogram of n_defaults. Include the normed=True keyword argument so that the height of\nthe bars of the histogram indicate the probability.\n-Show your plot.\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef perform_bernoulli_trials(n, p):\n    \"\"\"Perform n Bernoulli trials with success probability p\n    and return number of successes.\"\"\"\n    # Initialize number of successes: n_success\n    n_success = 0\n\n    # Perform trials\n    for i in range(n):\n        # Choose random number between zero and one: random_number\n        random_number = np.random.random()\n\n        # If less than p, it's a success so add one to n_success\n        if random_number < p:\n            n_success += 1\n\n    return n_success\n\n\n# Seed random number generator\nnp.random.seed(42)\n\n# Initialize the number of defaults: n_defaults\nn_defaults = np.empty(1000)\n\n# Compute the number of defaults\nfor i in range(1000):\n    n_defaults[i] = perform_bernoulli_trials(100, 0.05)\n\n\n# Plot the histogram with default number of bins; label your axes\n_ = plt.hist(n_defaults, normed=True)\n_ = plt.xlabel('number of defaults out of 100 loans')\n_ = plt.ylabel('probability')\n\n# Show the plot\nplt.show()\n", "meta": {"hexsha": "91a653d19080bf8bf5e362b921a831d9403d5dbc", "size": 2592, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/3-thinking-probabilistically--discrete-variables/how-many-defaults-might-we-expect.py", "max_stars_repo_name": "aimanahmedmoin1997/DataCamp", "max_stars_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-12T04:49:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T00:40:28.000Z", "max_issues_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/3-thinking-probabilistically--discrete-variables/how-many-defaults-might-we-expect.py", "max_issues_repo_name": "aimanahmedmoin1997/DataCamp", "max_issues_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/3-thinking-probabilistically--discrete-variables/how-many-defaults-might-we-expect.py", "max_forks_repo_name": "aimanahmedmoin1997/DataCamp", "max_forks_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-11-06T17:43:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T21:08:16.000Z", "avg_line_length": 38.1176470588, "max_line_length": 96, "alphanum_fraction": 0.7542438272, "include": true, "reason": "import numpy", "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.9184802468145655, "lm_q1q2_score": 0.866446114697939}}
{"text": "import numpy as np\n\ndef EulerMethod(f, xi, yi, xmax, h):\n    result = {}\n\n    n = int((xmax - xi)/h) + 1\n\n    x = np.linspace(xi, xmax, n)\n    y = yi\n\n    result[0] = {'x': x[0], 'y': y}\n\n    for i in range(1, n):\n        y = y + f(x[i-1], y) * h\n        result[i] = {'x': x[i],'y': y}\n    return result\n\ndef HeunsMethod(f_xy, xi, yi, h, xmax, its):\n    n = int((xmax - xi)/h) + 1\n\n    x = np.linspace(xi, xmax, n)\n    y = yi\n\n    result = {}\n    result[0] = {'x': x[0], 'y': y}\n\n    for i in range(1, n):\n        y_p = y + f_xy(x[i-1], y) * h\n        for _ in range(its):\n            y_p = y + h * (f_xy(x[i-1], y) + f_xy(x[i], y_p))/2\n        y = y_p\n        result[i] = {'x': x[i],'y': y}\n    return result\n\ndef MidPointMethod(f_xy, xi, yi, h, xmax):\n\n    n = int((xmax - xi)/h) + 1\n\n    x = np.linspace(xi, xmax, n)\n    y = yi\n\n    result = {}\n    result[0] = {'x': x[0], 'y': y}\n\n    for i in range(1, n):\n        y_1b2 = y + f_xy(x[i-1], y) * h/2\n        y = y + f_xy((x[i] + x[i-1])/2, y_1b2) * h\n        result[i] = {'x': x[i],'y': y}\n    return result\n\ndef Butcher_Tableau(method=None):\n    if method == None:\n        Meth_list = [   'Forward Euler',\n                        'Explicit Midpoint',\n                        'Ralston',\n                        'Kutta-3rd',\n                        'Classic-4th'   ]\n        return Meth_list\n    elif method == 'Forward Euler':\n        C =  [  0   ]\n        A = [[  0   ]]\n        B =  [  1   ]\n    elif method == 'Explicit Midpoint':\n        C =  [  0,      0.5 ]\n        A = [[  0,      0   ],\n             [  0.5,    0   ]]\n        B =  [  0 ,     1   ]\n    elif method == 'Ralston':\n        C =  [  0,      2/3 ]\n        A = [[  0,      0   ],\n             [  2/3,    0   ]]\n        B =  [  1/4,    3/4 ]\n    elif method == 'Kutta-3rd':\n        C =  [  0,      1/2,    1   ]\n        A = [[  0,      0,      0   ],\n             [  1/2,    0,      0   ],\n             [  -1,     2,      0   ]]\n        B =  [  1/6,    2/3,    1/6 ]\n    elif method == 'Classic-4th':\n        C =  [  0,      1/2,    1/2,    1   ]\n        A = [[  0,      0,      0,      0   ],\n             [  1/2,    0,      0,      0   ],\n             [  0,      1/2,    0,      0   ],\n             [  0,      0,      1,      0   ]]\n        B =  [  1/6,    1/3,    1/3,    1/6 ]\n\n    return {'s':    len(C),\n            'C':    np.array(C),\n            'A':    np.array(A),\n            'B':    np.array(B)}\n\ndef RungeKutta_General(F :list, xi :float, yi :list, h :float, xmax :float, Bt ):\n    itr = int((xmax - xi)/h) + 1\n    x = np.linspace(xi, xmax, itr)\n\n    result = {}\n    yn = yi\n    var = len(yn)\n    result[xi] = yn.copy()\n\n    hk = np.zeros((var,Bt['s']))\n\n    for n in range(itr - 1):\n        xn = x[n]\n\n        hk.fill(0)\n\n        # k_i\n        for i in range(Bt['s']):\n            xt = xn + Bt['C'][i] * h\n            yt = yn.copy()\n\n            yt += hk.dot(Bt['A'][i])\n            for m in range(var):\n                hk[m, i] = h * F[m](xt, *yt)\n\n        # y_{n+1}\n        for i in range(var):\n            yn[i] += np.array(Bt['B']).dot(hk[i])\n        result[x[n+1]] = yn.copy()\n    return result", "meta": {"hexsha": "c694e7976ebb5bdf0d34f886d3515d6465c77b83", "size": 3133, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/DiffEq.py", "max_stars_repo_name": "Ragav-KS/Numerical-Methods", "max_stars_repo_head_hexsha": "faf46c6fbcd80d8c6a7bb71a8c28ef5e525fec0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-23T04:20:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-02T03:40:30.000Z", "max_issues_repo_path": "code/DiffEq.py", "max_issues_repo_name": "Ragav-KS/Numerical-Methods", "max_issues_repo_head_hexsha": "faf46c6fbcd80d8c6a7bb71a8c28ef5e525fec0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/DiffEq.py", "max_forks_repo_name": "Ragav-KS/Numerical-Methods", "max_forks_repo_head_hexsha": "faf46c6fbcd80d8c6a7bb71a8c28ef5e525fec0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8925619835, "max_line_length": 81, "alphanum_fraction": 0.3530162783, "include": true, "reason": "import numpy", "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993027, "lm_q2_score": 0.9184802429095673, "lm_q1q2_score": 0.8664461080883984}}
{"text": "import numpy as np\n\ndef hypergeometric(N, K):\n    \"\"\"\n    This function compute the pmf of the Hypergeometric(N, K, n)\n    for each possible value of n (i.e. n in {0,1,2,...,N})\n    \n    In the context where an urn with N marbles contains K white marbles,\n    this function outputs an array P of shape (N+1,K+1) where\n    P[i, j] correspond to the probabillity that with i samples without \n    replacement we select j white marbles.\n    \n    Parameters\n    ----------\n    N : int\n        The number of marbles in the urn\n    K : int\n        The number of white marbles in the urn\n        \n    Returns\n    -------\n    P : numpy.ndarray\n        P[i, j] is the probability that with i samples without replacement\n        we select j white marbles. P.shape is (N+1, K+1)\n        \n    Notes\n    -----\n    This is equivalent to \n    np.array([scipy.stats.hypergeom(N, K, n).pmf(range(0,K+1)) for n in range(N+1)])\n    but faster, if only a row is needed (e.g. P[i]) than using scipy is faster.\n    \n    This algorithm uses the following recursive formula\n    P[i, j] = P[i-1, j]*(1-Q[i-1, j]) + P[i-1, j-1]*Q[i-1, j-1]\n    with Q[i, j] = (K-j)/(N-i) the probability of sampling a white marble\n    given that i marbles where sampled from which j were white\n    \"\"\"\n    P = np.zeros((N+1, K+1))\n    P[0,0] = 1 #P[0, j] = 1 if j==0 else 0\n    P[N,K] = 1 #P[N, j] = 1 if j==K else 0\n    \n    #To compute Q We don't need to bother with\n    #value > 1 since they will be multiplied by 0\n    Q = (K-np.arange(K+1))[None]/(N-np.arange(N))[:,None]\n    \n    for n in range(1,N):\n        P[n] = P[n-1]*(1-Q[n-1])\n        P[n,1:] += P[n-1,:-1]*Q[n-1,:-1]\n        \n    return P\n    \ndef superdupergeometric(N, K):\n    \"\"\"\n    This is the scenario where we have an urn with N marbles\n    and K of them are white. We sample from the urn without replacement\n    until we obtain k white marbles. The function gives the probability\n    that we need n samples to obtain k white marbles.\n    \n    Parameters\n    ----------\n    N : int\n        The number of marbles in the urn\n    K : int\n        The number of white marbles in the urn\n        \n    Returns\n    -------\n    SP : numpy.ndarray\n        SP[i, j] is the probability that it requires i samples without replacement\n        to select j white marbles. SP.shape is (N+1, K+1)\n        \n    Notes\n    -----\n    Probabibly related to the negative hypergeometric distribution\n    \n    This uses the hypergeometric (hence the name) \n    SP[i, j] = P[i-1, j-1]*Q[i-1, j-1]\n    where P = hypergeometric(N, K) and with \n    Q[i, j] = (K-j)/(N-i) the probability of sampling a white marble\n    given that i marbles where sampled from which j were white\n    \"\"\"\n    \n    P = hypergeometric(N, K)\n    SP = np.zeros((N+1, K+1))\n    SP[0, 0] = 1 #we only need 0 sample to get 0 white marbles\n    \n    #To compute Q We don't need to bother with\n    #value > 1 since they will be multiplied by 0\n    Q = (K-np.arange(K+1))[None]/(N-np.arange(N))[:,None]\n    \n    for n in range(1,N+1):\n        SP[n,1:] += P[n-1,:-1]*Q[n-1,:-1]\n        \n    return SP\n\ndef superdupergeometric_expectations(N, K):\n    \"\"\"\n    This is the scenario where we have an urn with N marbles\n    and K of them are white. We sample from the urn without replacement \n    until we obtain k white marbles. The function gives the  expected\n    number of samples n requires to get k white marbles (for each k).\n    \n    Parameters\n    ----------\n    N : int\n        The number of marbles in the urn\n    K : int\n        The number of white marbles in the urn\n        \n    Returns\n    -------\n    ESP : numpy.ndarray\n        ESP[k] is the expected number of samples without replacement\n        requires to get k white marbles. ESP.shape is (K+1,)\n        \n    Notes\n    -----\n    This is equivalent (but way faster) to (SP*np.arange(N+1)[:,None]).sum(axis=0)\n    where SP = superdupergeometric(N, K)\n    \"\"\"\n    ESP = (N+1)/(K+1)*np.arange(K+1)\n    return ESP\n", "meta": {"hexsha": "266cb6c5c0b738b48d6dd3f1bf04c043fd677de1", "size": 3940, "ext": "py", "lang": "Python", "max_stars_repo_path": "radbm/utils/stats/hypergeometric.py", "max_stars_repo_name": "duchesneaumathieu/radbm", "max_stars_repo_head_hexsha": "3d9dbad51e1bfc0bbb1a60d0aa03c99340f6930c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "radbm/utils/stats/hypergeometric.py", "max_issues_repo_name": "duchesneaumathieu/radbm", "max_issues_repo_head_hexsha": "3d9dbad51e1bfc0bbb1a60d0aa03c99340f6930c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "radbm/utils/stats/hypergeometric.py", "max_forks_repo_name": "duchesneaumathieu/radbm", "max_forks_repo_head_hexsha": "3d9dbad51e1bfc0bbb1a60d0aa03c99340f6930c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2950819672, "max_line_length": 84, "alphanum_fraction": 0.5906091371, "include": true, "reason": "import numpy", "num_tokens": 1170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298657, "lm_q2_score": 0.90052978812007, "lm_q1q2_score": 0.866406532131207}}
{"text": "import numpy as np\nimport scipy.linalg as la\nimport time\n\n\ndef read_matrix_dimension():\n    print(\"Enter dimension of matrix A(m >= n):\", end=' ')\n    try:\n        m, n = (int(i) for i in input().strip().split())\n        if m < n:\n            print(\"Number of rows cannot be less than number of columns in LSP problem!\")\n            raise Exception()\n    except Exception:\n        print(\"Invalid input for matrix dimension. Try again by entering two space-separated integers:\")\n        return read_matrix_dimension()\n    return m, n\n\n\ndef read_matrix(m, n):\n    A = np.zeros((m, n), dtype=np.complex)\n    print(\"Enter rows of the matrix A(separate elements of each row with space):\")\n    try:\n        for i in range(m):\n            A[i, :] = np.array([j for j in input().strip().split()]).astype(np.complex)\n    except Exception as e:\n        raise e\n        print(e)\n        print(\"Invalid input for matrix A. Please try again.\")\n        return read_matrix(m, n)\n    return A\n\n\ndef read_vector(m):\n    b = np.zeros(m, dtype=np.complex)\n    print(\"Enter elements of the vector b of size {}(separate them with space):\".format(m))\n    try:\n        b[:] = np.array([j for j in input().strip().split()]).astype(np.complex)\n    except Exception:\n        print(\"Invalid input for vector b. Please try again!\")\n        return read_vector(m)\n    return b\n\n\ndef solve_lsp_using_svd(A, b, n, r):\n    u, sigma, vt = la.svd(A)\n    bbar = np.transpose(np.conj(u)).dot(b)\n    y = np.zeros(n, dtype=np.complex)\n    y[:r] = bbar[:r] / sigma[:r]\n    if len(y) == 1:\n        y = float(y)\n    v = np.transpose(np.conj(vt))\n    x = v.dot(y)\n    remainder = la.norm(bbar[r:]) if r < n else 0\n    return x.reshape((n,)), remainder\n\n\ndef solve_lsp_using_qr(A, b, n, r):\n    q, R, p = la.qr(A, pivoting=True)\n    bbar = np.transpose(np.conj(q)).dot(b)\n    y = np.zeros(n, dtype=np.complex)\n    y[:r] = la.solve(R[:r, :r], bbar[:r])\n    x = y[p]\n    remainder = la.norm(bbar[r:]) if r < n else 0\n    return x.reshape((n,)), remainder\n\n\ndef lsp_solver(func, A, b, n, r, method):\n    start = time.time()\n    x, remainder = func(A, b, n, r)\n    svd_time = time.time() - start\n    print(\"Solved LSP using {} in {} ms. Here's the results:\".format(method, np.round(svd_time * 1000, decimals=2)))\n    print(\"x:\", x)\n    print(\"remainder:\", remainder)\n\n\ndef __main__():\n    m, n = read_matrix_dimension()\n    A = read_matrix(m, n)\n    b = read_vector(m)\n    rank_A = np.linalg.matrix_rank(A)\n    lsp_solver(solve_lsp_using_svd, A, b, n, rank_A, 'SVD')\n    lsp_solver(solve_lsp_using_qr, A, b, n, rank_A, 'QR')\n\n\n__main__()\n", "meta": {"hexsha": "5cdcb02c3efd721069cfacc2cef06b8cc9dda47d", "size": 2590, "ext": "py", "lang": "Python", "max_stars_repo_path": "LSP/main.py", "max_stars_repo_name": "atenagm1375/scientific_computing", "max_stars_repo_head_hexsha": "223082a28d89dba0d5e8140928560357d576f778", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LSP/main.py", "max_issues_repo_name": "atenagm1375/scientific_computing", "max_issues_repo_head_hexsha": "223082a28d89dba0d5e8140928560357d576f778", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LSP/main.py", "max_forks_repo_name": "atenagm1375/scientific_computing", "max_forks_repo_head_hexsha": "223082a28d89dba0d5e8140928560357d576f778", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1162790698, "max_line_length": 116, "alphanum_fraction": 0.5992277992, "include": true, "reason": "import numpy,import scipy", "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298657, "lm_q2_score": 0.9005297854505006, "lm_q1q2_score": 0.866406529562794}}
{"text": "from functools import partial\n# import numpy as np\n\n\n# solve equation with newton method\ndef newton(func, derFunc, initialValue, delta, epsilon, iterN):\n    v = func(*[initialValue])\n    print(\"k \", \" x \", \" f(x)\")\n    print(0, initialValue, v)\n    if abs(v) < epsilon:\n        return initialValue, v\n    x0 = initialValue\n    for i in range(0, iterN):\n        x1 = x0 - v / derFunc(*[x0])\n        v = func(*[x1])\n        print(i + 1, x1, v)\n        if abs(x1 - x0) < delta or abs(v) < epsilon:\n            return x1, v\n        else:\n            x0 = x1\n    return x1, v\n\n# solve equation with bisection method\ndef bisection(func, a, b, delta, epsilon, iterN):\n    mid = (a + b) * 0.5\n    v = func(*[mid])\n    print(\"k \", \" x \", \" f(x)\")\n    print(0, mid, v)\n    if abs(v) < epsilon:\n        return mid, v\n    x0 = a\n    x1 = b\n    for i in range(0, iterN):\n        f0 = func(*[x0])\n        f1 = func(*[x1])\n        if sign(f0) * sign(v) < 0:\n            x1 = mid\n        if sign(v) * sign(f1) < 0:\n            x0 = mid\n        mid = 0.5 * (x0 + x1)\n        v = func(*[mid])\n        print(i + 1, mid, v)\n        if abs(x1 - x0) < delta or abs(v) < epsilon:\n            return mid, v\n    return mid, v\n\ndef sign(x):\n    return -1 if x < 0 else 1 if x > 0 else 0\n\n# a sum of a geometric progression with a1 = q = x\ndef sumFunc(sum, n, x):\n    if x == 0 or x == 1:\n        return n * x - sum\n    return x * (1 - pow(x, n)) / (1 - x) - sum\n\n\n# the derivative function of the sum function\ndef derFunc(n, x):\n    if x == 0:\n        return 1\n    if x == 1:\n        return (1 + n) * n / 2\n    return (1 - (n + 1) * pow(x, n) + n * pow(x, n + 1)) / pow((1 - x), 2)\n\n\ndef main():\n    n = 360\n    sum = 75000 / 425.84\n    iterN = 50\n    initialValue = 0.5\n    delta = 1e-6\n    epsilon = 1e-12\n    f = partial(sumFunc, sum, n)\n    df = partial(derFunc, n)\n    # newton(f, df, initialValue, delta, epsilon, iterN)\n    bisection(f, 0, 1, epsilon, epsilon, 2 * iterN)\n\n\nmain()\n", "meta": {"hexsha": "4d0114ffa863c3d564e804f4caf9a8680899364e", "size": 1962, "ext": "py", "lang": "Python", "max_stars_repo_path": "equation-solver.py", "max_stars_repo_name": "65jie/NumericalAnalysis", "max_stars_repo_head_hexsha": "0ed17f92457e2661dea4fd5d317ca876cbeeafaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "equation-solver.py", "max_issues_repo_name": "65jie/NumericalAnalysis", "max_issues_repo_head_hexsha": "0ed17f92457e2661dea4fd5d317ca876cbeeafaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "equation-solver.py", "max_forks_repo_name": "65jie/NumericalAnalysis", "max_forks_repo_head_hexsha": "0ed17f92457e2661dea4fd5d317ca876cbeeafaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.525, "max_line_length": 74, "alphanum_fraction": 0.500509684, "include": true, "reason": "import numpy", "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542817548989, "lm_q2_score": 0.9032942138630786, "lm_q1q2_score": 0.8663985129111972}}
{"text": "import numpy as np\nimport pandas as pd\nimport scipy.optimize as op\nimport matplotlib.pyplot as plt\n\n# read data\ndata = pd.read_csv('ex2data1.txt', header=None)\n\n# show imported data details\n# print('data = \\n', data.head(10))\n# print('**************************************')\n# print('data.describe = \\n', data.describe())\n# print('**************************************')\n\n# draw data\ny = data.iloc[:, -1]\n\nfig, ax = plt.subplots(figsize= (8,5))\nplt.scatter(data.loc[y == 1, 0], data.loc[y == 1, 1], marker= '+', c= 'black', \n            linewidths= 3, s= 100, label= 'Admitted')\n\nplt.scatter(data.loc[y == 0, 0], data.loc[y == 0,1], marker= 'o', c= 'yellow', \n            linewidths= 1, edgecolors= 'k', s= 80, label= 'Not admitted')\n\nax.set(title= 'Training Dataset', xlabel= 'Exam 1 score', ylabel= 'Exam 2 score')\nax.legend(loc= 1, shadow= True, borderpad= 1)\nplt.show()\n\n# Setup the data matrix appropriately, and add ones for the intercept term\ndata.insert(0, -1 , 1)\n# print('\\nnew data = \\n', data.head(10))\n# print('\\n**************************************')\n\n# separate X (training data) from y (target variable)\ncols = data.shape[1]\nX = data.iloc[:, 0 : cols-1]\ny = data.iloc[:, cols-1 : cols]\n\n# print('\\nX data = \\n', X.head(10))\n# print('\\n**************************************')\n# print('\\ny data = \\n', y.head(10))\n# print('\\n**************************************')\n\n# Convert data from data frames to numpy matrices\nX = np.matrix(X.values)\ny = np.matrix(y.values)\n\n# Initialize fitting parameters\nm, n = X.shape\ninitial_theta = np.zeros((n, 1))\n\n# print('X \\n', X)\n# print('\\nX.shape = ', X.shape)\n# print('\\n**************************************')\n# print('y \\n', y)\n# print('\\ny.shape = ', y.shape)\n# print('\\n**************************************')\n# print('initial_theta \\n', initial_theta)\n# print('\\ninitial_theta.shape = ', initial_theta.shape)\n# print('\\n**************************************')\n\n# Compute and display initial cost and gradient\ndef sigmoid(z):\n    return 1 / (1 + np.exp(-z))\n\nnums = np.arange(-10, 10, 0.5)\n\nfig, ax = plt.subplots(figsize= (8,5))\nax.plot(nums, sigmoid(nums), 'r')\nax.grid()\nplt.show()\n\ndef costFunction(theta, X, y):\n    m = len(y)\n    theta = theta.reshape((X.shape[1],1))\n    \n    h = sigmoid(X * theta)\n    J = ((y.T * np.log(h)) + ((1 - y).T * np.log(1 - h))) / (-m)\n    return J\n\ndef Gradient(theta, X, y):\n    theta = theta.reshape((X.shape[1],1))\n    return ((X.T * (sigmoid(X * theta) - y)) / len(y))\n\ncost = costFunction(initial_theta, X, y)\ngrad = Gradient(initial_theta, X, y)\n\nprint('\\nCost at initial theta (zeros): %.3f' %cost)\nprint('Expected cost (approx): 0.693')\nprint('\\n**************************************')\n\nprint('\\nGradient at initial theta (zeros): ')\nfor i in grad.tolist(): print(' %.4f' %i[0])\nprint('Expected gradients (approx):\\n -0.1000\\n -12.0092\\n -11.2628')\nprint('\\n**************************************')\n\n# Compute and display cost and gradient with non-zero theta\ntest_theta = np.array([[-24], [0.2], [0.2]])\ncost = costFunction(test_theta, X, y)\ngrad = Gradient(test_theta, X, y)\n\nprint('\\nCost at test theta: %.3f' %cost)\nprint('Expected cost (approx): 0.218')\nprint('\\n**************************************')\n\nprint('\\nGradient at test theta: ')\nfor i in grad.tolist(): print(' %.3f' %i[0])\nprint('Expected gradients (approx):\\n 0.043\\n 2.566\\n 2.647')\nprint('\\n**************************************')\n\n# Run fminunc to obtain the optimal theta\n# This function will return theta and the cost\nResult = op.fmin_tnc(func= costFunction,\n                     x0= initial_theta,\n                     args= (X, y),\n                     fprime= Gradient,\n                     disp= False)\n\ntheta = Result[0].reshape((X.shape[1], 1))\n\nprint('\\nNew Theta After Optimization = ')\nfor i in range(theta.shape[0]): print(' %.3f' %theta[i, 0])\nprint('Expected theta (approx):')\nprint(' -25.161\\n 0.206\\n 0.201')\nprint('\\n**************************************')\n\nnewCost = costFunction(Result[0], X, y)\nprint('\\nNew Cost After Optimization = %.3f' %newCost)\nprint('Expected cost (approx): 0.203')\nprint('\\n**************************************')\n\n# Plot Boundary\n# Plot Data\nfig, ax = plt.subplots(figsize= (8,5))\nplt.scatter(data.loc[y == 1, 0], data.loc[y == 1, 1], marker= '+', c= 'black', \n            linewidths= 3, s= 100, label= 'Admitted')\n\nplt.scatter(data.loc[y == 0, 0], data.loc[y == 0,1], marker= 'o', c= 'yellow', \n            linewidths= 1, edgecolors= 'k', s= 80, label= 'Not admitted')\n\n\n# Only need 2 points to define a line, so choose two endpoints\nplot_x = np.array([np.min(X[:,1])-2, np.max(X[:,2])+2])\n\n# Calculate the decision boundary line\ntheta = np.array(Result[0]).reshape((X.shape[1], 1))\nplot_y = np.multiply(((-1.) / theta[2]) , (np.multiply(theta[1], plot_x) + theta[0]))\n\n# print('x =\\n', plot_x)\n# print('y =\\n', plot_y)\n\n# Plot, and adjust axes for better viewing\nplt.plot(plot_x, plot_y, linewidth= 2, label= 'Decision Boundary')\n\nax.set(title= 'Training Dataset with Decision Boundary', xlabel= 'Exam 1 score', ylabel= 'Exam 2 score',\n        xlim= (28, 101), ylim= (21, 101))\nax.legend(loc= 1, shadow= True)\nplt.show()\n\n# Predict and Accuracies\ndef predict(theta, X):\n    # PREDICT Predict whether the label is 0 or 1 using learned logistic\n    # regression parameters theta\n    p = np.zeros((X.shape[0],1))\n    \n    for i in range(X.shape[0]):\n        x = X[i, :].T\n        if sigmoid(theta.T * x) >= 0.5 :\n            p[i] = 1\n        else:\n            p[i] = 0\n    \n    return p\n\nprob = sigmoid(np.matrix([1, 45, 85]) * theta)\n\nprint('\\nFor a student with scores 45 and 85, we predict an admission probability of %.3f' %prob[0])\nprint('Expected value: 0.775 +/- 0.002')\nprint('\\n**************************************')\n\n# Compute accuracy on our training set\np = predict(theta, X)\n\nprint('Train Accuracy: %% %.1f' %(np.mean(p == y) * 100))\nprint('Expected accuracy (approx): % 89.0')\nprint('\\n**************************************')", "meta": {"hexsha": "762f98fe4823b7c89f0b4490bb352d1c91339a27", "size": 5971, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/ex2/ex2.py", "max_stars_repo_name": "xAbdalla/Machine_Learning_Exercises-Stanford_University", "max_stars_repo_head_hexsha": "2b38413e91948b5d2614407ac9b62a60acd191d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/ex2/ex2.py", "max_issues_repo_name": "xAbdalla/Machine_Learning_Exercises-Stanford_University", "max_issues_repo_head_hexsha": "2b38413e91948b5d2614407ac9b62a60acd191d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/ex2/ex2.py", "max_forks_repo_name": "xAbdalla/Machine_Learning_Exercises-Stanford_University", "max_forks_repo_head_hexsha": "2b38413e91948b5d2614407ac9b62a60acd191d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1021505376, "max_line_length": 104, "alphanum_fraction": 0.5511639591, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.9032942008463507, "lm_q1q2_score": 0.8663985056994692}}
{"text": "import numpy as np\n\n# We create a 4 x 5 ndarray that contains integers from 0 to 19\nX = np.arange(20).reshape(4, 5)\n\n# We print X\nprint()\nprint('X = \\n', X)\nprint()\n\n# We select all the elements that are in the 2nd through \n# 4th rows and in the 3rd to 5th columns\n\nZ = X[1:4,2:5]\n\n# We print Z\nprint('Z = \\n', Z)\n\n# We can select the sanem elements as above using method 2\n\nW = X[1:, 2:]\n\n# We print W\nprint()\nprint('W = \\n', W)\n\n# We select all the elements that are in the 1st through \n# 3rd rows and in the 3rd to 4th columns\n\nY = X[:3, 2:5]\n\n# We print Y\nprint()\nprint('Y = \\n', Y)\n\n# We select all the elements in the 3rd row\nv = X[2,:]\n\n# We print v\nprint()\nprint('v = ', v)\n\n# We select all the elements in the 3rd column\nq = X[:,2]\n\n# We print q\nprint()\nprint('q = ', q)\n\n# We select all the elements in the 3rd column but return a rank 2 ndarray\nR = X[:,2:3]\n\n# We print R\nprint()\nprint('R = \\n', R)\n\n\n## Copying Concept, View Stuffs\n\n# We create a 4 x 5 ndarray that contains integers from 0 to 19\nX = np.arange(20).reshape(4, 5)\n\n# We print X\nprint()\nprint('X = \\n', X)\nprint()\n\n# We select all the elements that are in the 2nd through 4th rows and in the 3rd to 4th columns\nZ = X[1:4,2:5]\n\n# We print Z\nprint()\nprint('Z = \\n', Z)\nprint()\n\n# We change the last element in Z to 555\nZ[2,2] = 555\n\n# We print X\nprint()\nprint('X = \\n', X)\nprint()\n\n# We create a 4 x 5 ndarray that contains integers from 0 to 19\nX = np.arange(20).reshape(4, 5)\n\n# We print X\nprint()\nprint('X = \\n', X)\nprint()\n\n# create a copy of the slice using the np.copy() function\nZ = np.copy(X[1:4,2:5])\n\n#  create a copy of the slice using the copy as a method\nW = X[1:4,2:5].copy()\n\n# We change the last element in Z to 555\nZ[2,2] = 555\n\n# We change the last element in W to 444\nW[2,2] = 444\n\n# We print X\nprint()\nprint('X = \\n', X)\n\n# We print Z\nprint()\nprint('Z = \\n', Z)\n\n# We print W\nprint()\nprint('W = \\n', W)\n\n# It is often useful to use one ndarray to make slices, \n# select, or change elements in another ndarray. \n# Let's see some examples:\n\n# We create a 4 x 5 ndarray that contains integers from 0 to 19\nX = np.arange(20).reshape(4, 5)\n\n# We create a rank 1 ndarray that will serve as indices to select elements from X\nindices = np.array([1,3])\n\n# We print X\nprint()\nprint('X = \\n', X)\nprint()\n\n# We print indices\nprint('indices = ', indices)\nprint()\n\n# We use the indices ndarray to select the 2nd and 4th row of X\nY = X[indices,:]\n\n\n# We use the indices ndarray to select the 2nd and 4th column of X\nZ = X[:, indices]\n\n# We print Y\nprint()\nprint('Y = \\n', Y)\n\n# We print Z\nprint()\nprint('Z = \\n', Z)\n\n# Selection of specific elements within ndarrays\n\n# Diagonal\n\n# We create a 4 x 5 ndarray that contains integers from 0 to 19\nX = np.arange(25).reshape(5, 5)\n\n# We print X\nprint()\nprint('X = \\n', X)\nprint()\n\n# We print the elements in the main diagonal of X\nprint('z =', np.diag(X))\nprint()\n\n# We print the elements in the main diagonal of X\nprint('z =', np.diag(X, k=0))\nprint()\n\n# We print the elements above the main diagonal of X\nprint('y =', np.diag(X, k=1))\nprint()\n\n# We print the elements below the main diagonal of X\nprint('w = ', np.diag(X, k=-1))\n\n# We print the elements above the main diagonal of X\nprint('t =', np.diag(X, k=3))\nprint()\n\n# We print the elements below the main diagonal of X\nprint('q = ', np.diag(X, k=-3))\n\n## Unique elements\n\n# Create 3 x 3 ndarray with repeated values\nX = np.array([[1,2,3],[5,2,8],[1,2,3]])\n\n# We print X\nprint()\nprint('X = \\n', X)\nprint()\n\n# We print the unique elements of X \nprint('The unique elements in X are:',np.unique(X))", "meta": {"hexsha": "eae5b907f0cc37b3cef080ebe87265731b7e02a0", "size": 3575, "ext": "py", "lang": "Python", "max_stars_repo_path": "python-programming/numPy/slicing_ndarray.py", "max_stars_repo_name": "geekmj/fml", "max_stars_repo_head_hexsha": "ead2c16be7865eda03183b5e11622f64bf81cab7", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python-programming/numPy/slicing_ndarray.py", "max_issues_repo_name": "geekmj/fml", "max_issues_repo_head_hexsha": "ead2c16be7865eda03183b5e11622f64bf81cab7", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python-programming/numPy/slicing_ndarray.py", "max_forks_repo_name": "geekmj/fml", "max_forks_repo_head_hexsha": "ead2c16be7865eda03183b5e11622f64bf81cab7", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3333333333, "max_line_length": 95, "alphanum_fraction": 0.6467132867, "include": true, "reason": "import numpy", "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.9591542880306189, "lm_q1q2_score": 0.8663985042222107}}
{"text": "from sympy import latex, factor, lambdify\nfrom utils import r\n\n\ndef gauss_seidel_method(x_exp, y_exp, z_exp=None, x_val=0, y_val=0, z_val=0, iter=1):\n    out_str = \"\"\n    x, y, z = symbols('x y z')\n\n    new_values = [x_val, y_val, z_val]\n\n    out_str += f\"\\\\textbf{{Iteration {iter}}}\\n\\n\"\n    out_str += f\"Substitute $y={r(new_values[1])}$, $z={r(new_values[2])}$\\n\"\n    out_str += f\"$$ x = {latex(factor(x_exp))} =\"\n    new_values[0] = float(lambdify((x, y, z), x_exp)(*new_values))\n    out_str += f\"{r(new_values[0])} $$\\n\\n\"\n\n    out_str += f\"Substitute $x={r(new_values[0])}$, $z={r(new_values[2])}$\\n\"\n    out_str += f\"$$ y = {latex(factor(y_exp))} =\"\n    new_values[1] = float(lambdify((x, y, z), y_exp)(*new_values))\n    out_str += f\"{r(new_values[1])} $$\\n\\n\"\n\n    if z_exp:\n        out_str += f\"Substitute $x={r(new_values[0])}$, $y={r(new_values[1])}$\\n\"\n        out_str += f\"$$ z = {latex(factor(z_exp))} =\"\n        new_values[2] = float(lambdify((x, y, z), z_exp)(*new_values))\n        out_str += f\"{r(new_values[2])} $$\\n\\n\"\n\n    out_str += f\"After Iteration {iter}\\n\"\n    out_str += f\"$$ (x, y, z) = ({', '.join([r(v) for v in new_values])})$$\\n\\n\"\n\n    if iter != 1:\n        out_str += f\"\\\\textbf{{Approximate Error}}\\n\\n\"\n        out_str += f\"$$ \\\\epsilon_a(x) = \\\\frac{{\\\\left|\\\\text{{latest value of x}} - \\\\text{{previous value of x}}\\\\right|}}{{\\\\left|\\\\text{{latest value of x}}\\\\right|}} \\\\times 100 $$\\n\"\n        out_str += f\"$$ \\\\epsilon_a(x) = \\\\frac{{\\\\left|{r(new_values[0])} - ({r(x_val)})\\\\right|}}{{\\\\left|{r(new_values[0])}\\\\right|}} \\\\times 100 $$\\n\"\n\n        e_x = abs(new_values[0] - x_val) / abs(new_values[0]) * 100\n        out_str += f\"$$ \\\\epsilon_a(x) = {r(e_x, 2)} \\% $$\\n\"\n\n        out_str += f\"$$ \\\\epsilon_a(y) = \\\\frac{{\\\\left|\\\\text{{latest value of y}} - \\\\text{{previous value of y}}\\\\right|}}{{\\\\left|\\\\text{{latest value of y}}\\\\right|}} \\\\times 100 $$\\n\"\n        out_str += f\"$$ \\\\epsilon_a(y) = \\\\frac{{\\\\left|{r(new_values[1])} - ({r(y_val)})\\\\right|}}{{\\\\left|{r(new_values[1])}\\\\right|}} \\\\times 100 $$\\n\"\n\n        e_y = abs(new_values[1] - y_val) / abs(new_values[1]) * 100\n        out_str += f\"$$ \\\\epsilon_a(y) = {r(e_y, 2)} \\% $$\\n\\n\"\n\n        if z_exp:\n            out_str += f\"$$ \\\\epsilon_a(z) = \\\\frac{{\\\\left|\\\\text{{latest value of z}} - \\\\text{{previous value of z}}\\\\right|}}{{\\\\left|\\\\text{{latest value of z}}\\\\right|}} \\\\times 100 $$\\n\"\n            out_str += f\"$$ \\\\epsilon_a(z) = \\\\frac{{\\\\left|{r(new_values[2])} - ({r(z_val)})\\\\right|}}{{\\\\left|{r(new_values[2])}\\\\right|}} \\\\times 100 $$\\n\"\n\n            e_z = abs(new_values[2] - z_val) / abs(new_values[2]) * 100\n            out_str += f\"$$ \\\\epsilon_a(z) = {r(e_z, 2)} \\% $$\\n\\n\"\n\n    if iter < 5:\n        x_val, y_val, z_val = new_values\n        out_str += gauss_seidel_method(x_exp, y_exp, z_exp, x_val, y_val, z_val, iter+1)\n\n    return out_str\n\n\nif __name__ == '__main__':\n    from sympy import solve, Eq, symbols\n    x, y = symbols('x y')\n\n    print(gauss_seidel_method(\n        solve(Eq(3*x+2*y, 4), y)[0],\n        solve(Eq(x - 2*y, 5), x)[0],\n        # solve(Eq(-3*x -y + 7*z, -34), z)[0],\n    ))\n", "meta": {"hexsha": "2f37d60989eacc7b8590b857e441b89627404ff7", "size": 3131, "ext": "py", "lang": "Python", "max_stars_repo_path": "NC/guass_seidel.py", "max_stars_repo_name": "nmanumr/comsats-scripts", "max_stars_repo_head_hexsha": "ec7a38c705315170f689f26ce6f6c56bbd87d923", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-07-04T16:43:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T16:10:50.000Z", "max_issues_repo_path": "NC/guass_seidel.py", "max_issues_repo_name": "nmanumr/comsats-scripts", "max_issues_repo_head_hexsha": "ec7a38c705315170f689f26ce6f6c56bbd87d923", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NC/guass_seidel.py", "max_forks_repo_name": "nmanumr/comsats-scripts", "max_forks_repo_head_hexsha": "ec7a38c705315170f689f26ce6f6c56bbd87d923", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.0441176471, "max_line_length": 193, "alphanum_fraction": 0.5362503992, "include": true, "reason": "from sympy", "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154280587323, "lm_q2_score": 0.9032941982430049, "lm_q1q2_score": 0.8663984968744721}}
{"text": "import numpy\n\ndef bisection(f, interval, eps_abs = 1e-10, max_step = 100):\n    \"\"\"\n    Use bisection to find x such that f(x) = 0.\n    \"\"\"\n    \n    x_lo, x_hi = interval\n    x = (x_lo + x_hi) / 2.0\n    f_lo = f(x_lo)\n    if (abs(f_lo) < eps_abs):\n        return x_lo\n    f_hi = f(x_hi)\n    if (abs(f_hi) < eps_abs):\n        return x_hi\n    #assert(f_lo*f_hi < 0), \"f(Endpoints) must change sign!\"\n    if f_lo*f_hi > 0:\n        print(\"Warning! f(endpoints) have same sign!\")\n    \n    f_mid = f(x)\n    step = 0\n    while (step < max_step) and abs(f_mid) > eps_abs:\n        step += 1\n        if f_lo * f_mid < 0.0:\n            x_hi = x\n            f_hi = f(x_hi)\n        else:\n            x_lo = x\n            f_lo = f(x_lo)\n        x = (x_lo + x_hi) / 2.0\n        f_mid = f(x)\n    \n    return x\n    \n\nif __name__ == \"__main__\":\n    def f(x):\n        return numpy.exp(x) + x - 2\n    def g(x):\n        return numpy.sin(x**2) - 0.1 * x\n        \n    interval = [0, 1]\n    s = bisection(f, interval)\n    print(\"s = {}, f(s) = {}\".format(s, f(s)))\n    for lower in range(1,9):\n        interval = [lower, 10]\n        try:\n            s = bisection(g, interval)\n            print(\"interval = [{}, 10], s = {}, g(s) = {}\".format(lower, s, g(s)))\n        except:\n            pass\n", "meta": {"hexsha": "7c629317e02974d406164f9ab6f3e84b66f38d55", "size": 1268, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/tex/codes/bisection.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Lectures/tex/codes/bisection.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Lectures/tex/codes/bisection.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 24.3846153846, "max_line_length": 82, "alphanum_fraction": 0.4676656151, "include": true, "reason": "import numpy", "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545392102523, "lm_q2_score": 0.9136765204755286, "lm_q1q2_score": 0.8663065402587015}}
{"text": "import numpy as np\n\n\ndef lu(a, sequence=False, swap_times: list = {}):\n    \"\"\"\n    「高斯消去法」的 LU 分解.\n\n    本函数可以计算「列主元高斯消元法」、「顺序高斯消元法」的 LU 分解，\n    通过参数 sequence 控制，默认 sequence=False 使用「列主元高斯消元法」。\n\n    Args:\n        a: np_array_like 方阵 (nxn)\n        sequence: bool, True 则使用顺序高斯消去法，False 为列主元的高斯消去法\n            default: sequence=False\n        swap_times: 这是一个**输出**用的变量，只有传入 dict 变量时才有效。\n            若使用「列主元高斯消元法」（sequence=False）\n            则，置 swap_times['swap_times'] = 行交换次数。\n            这个值正常的输出中不需要，但在一些问题，比如，\n            利用 LU 分解求行列式时，得到 swap_times 会很有帮助。\n\n    Returns:\n        (l, u, p): result\n\n        l: np.array, Lower triangle result (nxn)\n        u: np.array, Upper triangle result (nxn)\n        p: np.array, Permutation: 交换后的行顺序 (n)\n            p = None if sequence=True\n\n    Raises:\n        Exception: 存在为零的主元素\n    \"\"\"\n    a = np.array(a, dtype=np.float)  # copy\n\n    assert a.shape[0] == a.shape[1]\n    n = a.shape[0]\n\n    if not sequence:\n        # p 记录行交换的过程，使用「列主元高斯消元法」才使用，否则为 None\n        p = np.array([k for k in range(n)])\n        # swap_times:  行交换次数\n        if isinstance(swap_times, dict):\n            swap_times['swap_times'] = 0\n    else:\n        p = None\n\n    for k in range(n-1):\n        if not sequence:\n            i_max = k + np.argmax(np.abs(a[k:n, k]))\n\n            if i_max != k:\n                a[[i_max, k]] = a[[k, i_max]]  # swap rows\n                p[[i_max, k]] = p[[k, i_max]]  # record\n                swap_times['swap_times'] += 1\n\n        if a[k][k] == 0:\n            raise Exception(\"存在为零的主元素\")\n\n        for i in range(k+1, n):\n            a[i][k] /= a[k][k]  # L @ 严格下三角\n            for j in range(k+1, n):\n                a[i][j] -= a[i][k] * a[k][j]  # U @ 上三角\n\n    # print(a, p)\n\n    # Uncommit the following lines to get a Permutation Matrix\n    # Only for sequence=False\n    # pm = np.zeros_like(a)\n    # for i, v in enumerate(p):\n    #     pm[i, v] = 1\n    #     print(pm)\n\n    return np.tril(a, k=-1) + np.identity(a.shape[0]), np.triu(a), p\n\n\ndef solve_lu(b, l, u, p=None):\n    \"\"\"用 lu(a) 得到的 `pa=lu` 分解的结果求解原方程组 `ax=b` 的解 x。\n\n    若 p 不为 None 则使用「列主元高斯消元」，p 为 None表示使用「顺序高斯消元」。\n\n        # `@` means matrix multiplication, refer: https://docs.python.org/reference/expressions.html#binary-arithmetic-operations\n        b = p @ b if p != None\n        l @ y = b\n        u @ x = y\n\n    Args:\n        b: np_array_like, 原方程组的右端常数（n）\n        l: np_array_like, Lower triangle of lu_seq(a)\n        u: np_array_like, Upper triangle of lu_seq(a)\n        p: np_array_like, LU分解中交换后的行顺序\n            default p=None: 未做行交换，即使用顺序高斯消去法\n\n        使用列主元高斯消元法时，l, u, p 使用 lu(a) 得到的结果即可：\n            solve_lu(b, *lu(a))\n        或者使用顺序高斯消元：\n            solve_lu(b, *lu(a, sequence=True))  # p=None\n\n    Returns:\n        x : np.array `ax=b` 的解（n）\n    \"\"\"\n    assert np.shape(l) == np.shape(u)\n    assert np.shape(l)[0] == np.shape(b)[0]\n\n    n = np.shape(l)[0]\n\n    # do swap\n    if p is not None:\n        b = [b[v] for v in p]\n\n    # L * y = b\n    y = np.zeros(n, dtype=np.float)\n    y[0] = b[0]\n    for i in range(1, n):\n        bi = b[i]\n        for j in range(0, i):\n            bi -= y[j] * l[i][j]\n        y[i] = bi / l[i][i]\n    # print(y)\n\n    # U * x = y\n    x = np.zeros(n, dtype=np.float)\n    x[n-1] = y[n-1] / u[n-1][n-1]\n    for i in range(n-2, -1, -1):  # from n-2 (included) to 0 (included)\n        yi = y[i]\n        for j in range(i+1, n):\n            yi -= x[j] * u[i][j]\n        x[i] = yi / u[i][i]\n    # print(x)\n\n    return x\n\n\ndef det(a):\n    \"\"\"矩阵行列式\n\n    利用 LU 分解（列主元高斯消元）求方阵 a 的行列式: d = det(a)\n\n    Args:\n        a: np_array_like, 要求行列式的矩阵\n\n    Returns:\n        d: float, a 的行列式值。\n\n    Reference:\n        https://blog.csdn.net/nstarLDS/article/details/106074256\n    \"\"\"\n    swap_times = {}\n    l, u, p = lu(a, sequence=False, swap_times=swap_times)\n    sign = -1 if swap_times['swap_times'] % 2 == 1 else 1\n    return np.prod(np.diag(u)) * sign\n\n\ndef inv(a):\n    \"\"\"矩阵的逆\n\n    利用 LU 分解（列主元高斯消元）求方阵 a 的逆矩阵: x = inv(a)\n\n    Args:\n        a: np_array_like, 待求逆的矩阵\n\n    Returns:\n        x: float, a 的逆矩阵\n\n    Reference:\n        https://en.wikipedia.org/wiki/LU_decomposition#Inverting_a_matrix\n    \"\"\"\n    l, u, p = lu(a)\n\n    X = np.zeros_like(a, dtype=np.float)\n    B = np.identity(np.shape(a)[0])\n\n    for i, b in enumerate(B.T):  # iter on cols\n        x = solve_lu(b, l, u, p)\n        X[:, i] = x\n\n    return X\n", "meta": {"hexsha": "14c733ffd550c92b3e544997c980de468b14b796", "size": 4364, "ext": "py", "lang": "Python", "max_stars_repo_path": "ex6/src/lu.py", "max_stars_repo_name": "cdfmlr/NumericalAnalysis", "max_stars_repo_head_hexsha": "b752af60c1f3202d53cc3c76e66419a885250ed9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex6/src/lu.py", "max_issues_repo_name": "cdfmlr/NumericalAnalysis", "max_issues_repo_head_hexsha": "b752af60c1f3202d53cc3c76e66419a885250ed9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex6/src/lu.py", "max_forks_repo_name": "cdfmlr/NumericalAnalysis", "max_forks_repo_head_hexsha": "b752af60c1f3202d53cc3c76e66419a885250ed9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-15T01:34:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-15T01:34:35.000Z", "avg_line_length": 24.7954545455, "max_line_length": 129, "alphanum_fraction": 0.5164986251, "include": true, "reason": "import numpy", "num_tokens": 1696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.9136765151867664, "lm_q1q2_score": 0.8663065285514203}}
{"text": "\"\"\"\r\nLaborator 5\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport proceduri as proc\r\nimport time\r\n\r\n\r\n\r\n# Exercițiul 1\r\nA = np.array([[0., 1., 1.],\r\n              [2., 1., 5.],\r\n              [4., 2., 1.]])\r\nb = np.array([[3.], [5.], [1.]])\r\ntol = 10 ** (-10)\r\nL, U, w = proc.FactLU(A, b, tol)\r\n\r\nb_nou = np.copy(b)\r\nfor i in range(np.shape(b)[0]):\r\n    b_nou[i] = b[w[i]]\r\n    \r\ny = proc.metSubAsc(L, b_nou, tol)\r\nx = proc.metSubDesc(U, y, tol)\r\nprint(f'Soluția Sistemului: \\n{x}')\r\n# print(A@x)   # înmulțire de matrici (verificare dacă e egal cu b)\r\n\r\n\r\n\r\n\r\n\r\n# Exercițiul 2\r\nn = 100\r\ntol = 10 ** (-10)\r\nA = np.random.rand(n, n) * 10     # A -> matrice numere random\r\nb = np.zeros((n, 1))              # b -> tb calculat după formulă cerință\r\nfor i in range(n):\r\n    sum = 0\r\n    for j in range(n):\r\n        sum += A[i][j]\r\n    b[i] = sum\r\n# print(f'Matricea A: \\n{A}')\r\n# print(f'Matricea b: \\n{b}')\r\n\r\n\r\n# a) b)\r\nL, U, w = proc.FactLU(A, b, tol)\r\nb_nou = np.copy(b)\r\nfor i in range(np.shape(b)[0]):\r\n    b_nou[i] = b[w[i]]\r\ny = proc.metSubAsc(L, b_nou, tol)\r\nx = proc.metSubDesc(U, y, tol)\r\n# print(f'Soluție Sistem: \\n{x}')\r\n\r\n\r\n# c) d)\r\nx_old = np.copy(x)\r\ntic = time.time()\r\nL, U, w = proc.FactLU(A, b, tol)\r\nb_nou = np.zeros((n, 1))\r\n\r\nfor k in range(0, 100):\r\n    b_nou = x_old[:] + 2\r\n    for i in range(np.shape(b)[0]):\r\n        b_nou[i] = b[w[i]]\r\n        \r\n    y = proc.metSubAsc(L, b_nou, tol)\r\n    x_new = proc.metSubDesc(U, y, tol)\r\n    \r\n    x_old = x_new[:]\r\n\r\ntoc = time.time() - tic\r\n#print(\"Sol la ultima iteratie\\n\",x_old)\r\nprint(\"In timp de\", toc)\r\n\r\ntic = time.time()\r\nx_old = x\r\nfor k in range(0, 100):\r\n    x_new = proc.GaussPP(A, x_old + 2, tol)\r\n    x_old = x_new[:]\r\ntoc = time.time() - tic\r\n#print(\"Sol la ultima iteratie\\n\",x_old)\r\nprint(\"In timp de\", toc)\r\n", "meta": {"hexsha": "de2ef2ac2e45415fbbcf80f6c8d4fbae0dad5ce6", "size": 1776, "ext": "py", "lang": "Python", "max_stars_repo_path": "Calcul Numeric (CN)/Laborator/Laborator 5/lab5.py", "max_stars_repo_name": "DLarisa/FMI-Materials-BachelorDegree", "max_stars_repo_head_hexsha": "138e1a20bc33617772e9cd9e4432fbae99c0250c", "max_stars_repo_licenses": ["W3C"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-02-12T02:05:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T14:44:43.000Z", "max_issues_repo_path": "Calcul Numeric (CN)/Laborator/Laborator 5/lab5.py", "max_issues_repo_name": "DLarisa/FMI-Materials-BachelorDegree-UniBuc", "max_issues_repo_head_hexsha": "138e1a20bc33617772e9cd9e4432fbae99c0250c", "max_issues_repo_licenses": ["W3C"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Calcul Numeric (CN)/Laborator/Laborator 5/lab5.py", "max_forks_repo_name": "DLarisa/FMI-Materials-BachelorDegree-UniBuc", "max_forks_repo_head_hexsha": "138e1a20bc33617772e9cd9e4432fbae99c0250c", "max_forks_repo_licenses": ["W3C"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1428571429, "max_line_length": 74, "alphanum_fraction": 0.5230855856, "include": true, "reason": "import numpy", "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.9207896748041439, "lm_q1q2_score": 0.8662694918648683}}
{"text": "\"\"\"\nGeneral purpose math functions, mostly geometric in nature.\n\"\"\"\n\nimport numpy as np\n\n\ndef cart2pol(x, y):\n    \"\"\"\n    Convert Cartesian to Polar Coordinates. All input arguments must be the same shape.\n    :param x: x-coordinate in Cartesian space\n    :param y: y-coordinate in Cartesian space\n    :return: A 2-tuple of values:\n        theta: angular coordinate/azimuth\n        r: radial distance from origin\n    \"\"\"\n    return np.arctan2(y, x), np.hypot(x, y)\n\n\ndef cart2sph(x, y, z):\n    \"\"\"\n    Transform cartesian coordinates to spherical. All input arguments must be the same shape.\n\n    :param x: X-values of input co-ordinates.\n    :param y: Y-values of input co-ordinates.\n    :param z: Z-values of input co-ordinates.\n    :return: A 3-tuple of values, all of the same shape as the inputs.\n        (<azimuth>, <elevation>, <radius>)\n    azimuth and elevation are returned in radians.\n\n    This function is equivalent to MATLAB's cart2sph function.\n    \"\"\"\n    hxy = np.hypot(x, y)\n    r = np.hypot(hxy, z)\n    el = np.arctan2(z, hxy)\n    az = np.arctan2(y, x)\n    return az, el, r\n\n\ndef grid_2d(n):\n    grid_1d = np.ceil(np.arange(-n/2, n/2)) / (n/2)\n    x, y = np.meshgrid(grid_1d, grid_1d, indexing='ij')\n    phi, r = cart2pol(x, y)\n\n    return {\n        'x': x,\n        'y': y,\n        'phi': phi,\n        'r': r\n    }\n\n\ndef grid_3d(n):\n    grid_1d = np.ceil(np.arange(-n/2, n/2)) / (n/2)\n    x, y, z = np.meshgrid(grid_1d, grid_1d, grid_1d, indexing='ij')\n    phi, theta, r = cart2sph(x, y, z)\n\n    # TODO: Should this theta adjustment be moved inside cart2sph?\n    theta = np.pi/2 - theta\n\n    return {\n        'x': x,\n        'y': y,\n        'z': z,\n        'phi': phi,\n        'theta': theta,\n        'r': r\n    }\n\n\ndef angles_to_rots(angles):\n    n_angles = angles.shape[-1]\n    rots = np.zeros(shape=(3, 3, n_angles))\n\n    for i in range(n_angles):\n        rots[:, :, i] = erot(angles[:, i])\n    return rots\n\n\ndef erot(angles):\n    return zrot(angles[0]) @ yrot(angles[1]) @ zrot(angles[2])\n\n\ndef zrot(theta):\n    sin, cos = np.sin(theta), np.cos(theta)\n    return np.array([[cos, -sin, 0], [sin, cos, 0], [0, 0, 1]])\n\n\ndef yrot(theta):\n    sin, cos = np.sin(theta), np.cos(theta)\n    return np.array([[cos, 0, sin], [0, 1, 0], [-sin, 0, cos]])\n", "meta": {"hexsha": "3f53aed6f438a9c4aaff2e5623da38fcdb6f4f24", "size": 2266, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/aspyre/utils/math.py", "max_stars_repo_name": "ComputationalCryoEM/ASPIRE", "max_stars_repo_head_hexsha": "6e6699eae532874de44b98adb7ddb2ad96c43d9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/aspyre/utils/math.py", "max_issues_repo_name": "ComputationalCryoEM/ASPIRE", "max_issues_repo_head_hexsha": "6e6699eae532874de44b98adb7ddb2ad96c43d9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-06-07T13:25:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T20:34:37.000Z", "max_forks_repo_path": "src/aspyre/utils/math.py", "max_forks_repo_name": "computationalcryoem/aspyre", "max_forks_repo_head_hexsha": "6e6699eae532874de44b98adb7ddb2ad96c43d9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-18T17:41:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-18T17:41:52.000Z", "avg_line_length": 24.6304347826, "max_line_length": 93, "alphanum_fraction": 0.5838481906, "include": true, "reason": "import numpy", "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9763105300791785, "lm_q2_score": 0.8872045996818986, "lm_q1q2_score": 0.8661871930041197}}
{"text": "# coding: utf-8\r\nimport numpy as np\r\nfrom time import time\r\nimport sys\r\n\r\ndef find_primes(maxN):\r\n    x1 = np.arange(maxN + 1, dtype=np.int64)\r\n    b1 = np.zeros(np.shape(x1), dtype=np.bool)\r\n    b1[x1 > 1] = True\r\n    maxN2 = np.int64(maxN**(0.5) + 1)\r\n    for n in range(2, maxN2 + 1):\r\n        b1[2*n::n] = False\r\n    return x1[b1]\r\n\r\n\r\ndef prime_factors(N):\r\n    pNums = find_primes(N//2 + 1)\r\n    pExps = np.zeros(np.shape(pNums), dtype=int)\r\n    max_exp = int(np.log(N)/np.log(2))\r\n    for n in range(1, max_exp + 1):\r\n        pExps[np.mod(N, pNums**n) == 0] = n\r\n    pN = pNums[pExps > 0]\r\n    pE = pExps[pExps > 0]\r\n    if 0 < np.size(pN) < 10:\r\n        disp_pf(N, pN, pE)\r\n    elif np.size(pN) == 0:\r\n        print('{N} is a prime number!'.format(N=N))\r\n    else:\r\n        pass\r\n    return pN, pE\r\n\r\n\r\ndef find_lcm(num_array):\r\n    Nmax = max(num_array)\r\n    pNums = find_primes(Nmax + 1)\r\n    pExps = np.zeros(np.shape(pNums), dtype=int)\r\n    for N in num_array:\r\n        pExps2 = np.zeros(np.shape(pNums), dtype=int)\r\n        if N in pNums:\r\n            pExps2[pNums == N] = 1\r\n        else:\r\n            max_exp = int(np.log(N)/np.log(2))\r\n            for n in range(1, max_exp + 1):\r\n                pExps2[np.mod(N, pNums**n) == 0] = n\r\n        pExps = np.maximum(pExps, pExps2)\r\n    pN = pNums[pExps > 0]\r\n    pE = pExps[pExps > 0]\r\n    outN = np.product(pN**pE)\r\n    if 0 < np.size(pN) < 10:\r\n        disp_pf(outN, pN, pE)\r\n    else:\r\n        pass\r\n    return outN, pN, pE\r\n    \r\n\r\ndef disp_pf(N, pNums, pExps):\r\n    factors1 = []\r\n    for n, e in zip(pNums, pExps):\r\n        if e > 1:\r\n            factor = '{n:,d}^{e}'.format(n=n, e=e)\r\n        else:\r\n            factor = '{n:,d}'.format(n=n)\r\n        factors1.append(factor)\r\n    print('\\n{N:,d} = '.format(N=N) + ' * '.join(factors1))\r\n\r\n\r\ndef test_fun1(upper_limit):\r\n    t0 = time()\r\n    prime_array = find_primes(upper_limit)\r\n    t1 = time()\r\n    Nprime = np.size(prime_array)\r\n    print('\\nFound {0:,d} prime numbers in {1:.4e} sec'.format(Nprime, t1 - t0))\r\n    print('\\nOr, ~{0:,d} prime numbers per second'.format(int(Nprime/(t1 - t0))))\r\n    print('\\nPython version: {0}'.format(sys.version))\r\n    return prime_array\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    out1 = test_fun1(np.int64(1e+8))\r\n#    num_array = list(range(2, 11))\r\n#    lcm, pN, pE = find_lcm(num_array)\r\n    \r\n", "meta": {"hexsha": "688c3c116f7d064a8df1f7e8f73aa4f513cb28f7", "size": 2351, "ext": "py", "lang": "Python", "max_stars_repo_path": "find_prime_nums2.py", "max_stars_repo_name": "byronburks92/hybrid-simulation", "max_stars_repo_head_hexsha": "4321393f7f784f5c9397442765897cfe9454f8ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "find_prime_nums2.py", "max_issues_repo_name": "byronburks92/hybrid-simulation", "max_issues_repo_head_hexsha": "4321393f7f784f5c9397442765897cfe9454f8ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "find_prime_nums2.py", "max_forks_repo_name": "byronburks92/hybrid-simulation", "max_forks_repo_head_hexsha": "4321393f7f784f5c9397442765897cfe9454f8ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3253012048, "max_line_length": 82, "alphanum_fraction": 0.5291365376, "include": true, "reason": "import numpy", "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9763105273220726, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.8661871803668967}}
{"text": "from numpy.linalg import eig, inv, norm, cond\r\nimport numpy as np\r\nfrom tabulate import tabulate\r\n\r\nmyA=[\r\n [3.278164, 1.046583, -1.378574],\r\n [1.046583, 2.975937, 0.934251],\r\n [-1.378574, 0.934251, 4.836173]\r\n]\r\n\r\nmyB = [ [-0.527466],\r\n [2.526877],\r\n [5.165441]]\r\n\r\n\r\ndef toFixed(numObj, digits=0):\r\n    return f\"{numObj:.{digits}f}\"\r\n\r\n# --- end of исходные данные\r\n\r\n# 1)\r\n# --- вывод системы на экран\r\ndef FancyPrint(A, B, selected):\r\n    for row in range(len(B)):\r\n        print(\"(\", end='')\r\n        for col in range(len(A[row])):\r\n             print(\"\\t{1:10.2f}{0}\".format(\" \" if (selected is None\r\nor selected != (row, col)) else \"*\", A[row][col]), end='')\r\n        print(\"\\t) * (\\tX{0}) = (\\t{1:10.2f})\".format(row + 1, B[row][0]))\r\n# --- end of вывод системы на экран\r\n\r\n# --- перемена местами двух строк системы\r\ndef SwapRows(A, B, row1, row2):\r\n    A[row1], A[row2] = A[row2], A[row1]\r\n    B[row1], B[row2] = B[row2], B[row1]\r\n# --- end of перемена местами двух строк системы\r\n\r\n# --- деление строки системы на число\r\ndef DivideRow(A, B, row, divider):\r\n    A[row] = [a / divider for a in A[row]]\r\n    B[row][0] /= divider\r\n# --- end of деление строки системы на число\r\n\r\n# --- сложение строки системы с другой строкой, умноженной на число\r\ndef CombineRows(A, B, row, source_row, weight):\r\n    A[row] = [(a + k * weight) for a, k in zip(A[row], A[source_row])]\r\n    B[row][0] += B[source_row][0] * weight\r\n# --- end of сложение строки системы с другой строкой, умноженной начисло\r\n\r\n# --- решение системы методом Гаусса (приведением к треугольному виду)\r\ndef Gauss(A, B):\r\n    column = 0\r\n    while (column < len(B)):\r\n        current_row = None\r\n        for r in range(column, len(A)):\r\n            if current_row is None or abs(A[r][column]) > abs(A[current_row][column]):\r\n                 current_row = r\r\n        if current_row is None:\r\n            return None\r\n        if current_row != column:\r\n            SwapRows(A, B, current_row, column)\r\n        DivideRow(A, B, column, A[column][column])\r\n        for r in range(column + 1, len(A)):\r\n            CombineRows(A, B, r, column, -A[r][column])\r\n        column += 1\r\n    X = [0 for b in B]\r\n    for i in range(len(B) - 1, -1, -1):\r\n        X[i] = B[i][0] - sum(x * a for x, a in zip(X[(i + 1):], A[i][(i + 1):]))\r\n    return X\r\n# --- end of решение системы методом Гаусса (приведением к треугольному виду)\r\n\r\n\r\ndef printVector(X):\r\n    print(\"\\n\".join(\"X{0} =\\t{1:10.2f}\".format(i + 1, x) for i, x in enumerate(X)))\r\n\r\n# 1)\r\nprint(\"Исходная система:\")\r\nFancyPrint(myA, myB, None)\r\nprint(\"Решаем методом Гаусса:\")\r\nxGauss = Gauss(np.copy(myA), np.copy(myB))\r\nprintVector(xGauss)\r\nprint(\"-------------------------------------------------\")\r\n\r\n# 2)\r\ndef norminf (H):\r\n    return np.amax(H)\r\n\r\n# 3)\r\ndef infprecision(k, H, g):\r\n    f = norminf(H)\r\n    return (f ** k) * norminf(np.zeros((3, 1))) + f ** k * norminf(g) / (1 - f)\r\n\r\n# 4)\r\ndef frobnormvector(X):\r\n    sum = 0.0\r\n    for i in range(len(X)):\r\n        c = X[i]\r\n        sum += (abs(X[i])) ** 2\r\n    return sum ** 0.5\r\n\r\n\r\ndef frobnorm (A):\r\n    sum = 0.0\r\n    for i in range(len(A)):\r\n        for j in range(len(A[0])):\r\n            sum += (abs(A[i][j])) ** 2\r\n    return sum ** 0.5\r\n\r\n\r\ndef aprprecision (k, H, g):\r\n    f = frobnorm(H)\r\n    return (f ** k) * frobnormvector(np.zeros((3, 1))) + f ** k * frobnormvector(g) / (1 - f)\r\n\r\n\r\ndef apostprecision (H, xk, xkplus1):\r\n    return frobnorm(H) * frobnorm(xk - xkplus1) / (1 - frobnorm(H))\r\n\r\n\r\ndef lusthernik (H, xk, xkplus1):\r\n    x_ = xk + (xkplus1 - xk) / (1 - max(abs(np.linalg.eigvals(H))))\r\n    return x_\r\n\r\n\r\ndef makezero():\r\n    return np.zeros((3,1))\r\n\r\n\r\ndef factprecision(x):\r\n    b = np.copy(xGauss)\r\n    for i in range(3):\r\n        k = b[i] - x[i][0]\r\n        b[i] = k\r\n    prec = frobnormvector(b)\r\n    #prec = np.linalg.norm(b)\r\n    print(\"Фактическая погрешность: \", prec)\r\n    return prec\r\n\r\n\r\ndef simpleiter (k, H, g):\r\n    xk = makezero()\r\n    xklust = makezero()\r\n    for i in range (k):\r\n        xkplus1 = H @ xk + g\r\n        xklust = np.copy(xk)\r\n        xk = np.copy(xkplus1)\r\n    print (\"Решение: \")\r\n    print(xkplus1)\r\n    fiter = factprecision(xkplus1)\r\n    print (\"Априорная оценка: \", aprprecision(k, H, g))\r\n    print(\"Апостериорная оценка: \", apostprecision(H, xk, xkplus1))\r\n    l = lusthernik(H, xklust, xkplus1)\r\n    print(\"Решение, уточнённое по Люстернику: \")\r\n    print(l)\r\n    factprecision(l)\r\n    return xkplus1, fiter\r\n\r\n\r\n# 5)\r\ndef zeidel (k, H, g):\r\n    xk = makezero()\r\n    Hl = np.tril(H, k=-1)\r\n    Hr = np.triu(H, k=0)\r\n    E = np.eye(3, 3, dtype=np.double)\r\n    Hseid = np.linalg.inv(E - Hl) @ Hr\r\n    gSeid = np.linalg.inv(E - Hl) @ g\r\n    for i in range (k):\r\n        xkplus1 = Hseid @ xk + gSeid\r\n        xk = np.copy(xkplus1)\r\n    return xkplus1\r\n\r\n\r\ndef radius (H):\r\n    Hl = np.tril(H, k=-1)\r\n    Hr = np.triu(H, k=0)\r\n    E = np.eye(3, 3, dtype=np.double)\r\n    x = np.linalg.inv(E - Hl) @ Hr\r\n    return spectradius(x)\r\n\r\n\r\ndef spectradius(H):\r\n    return np.max(np.abs(np.linalg.eigvals(H)))\r\n\r\n\r\n# 7)\r\ndef upperrelax(k, H, g):\r\n    p = spectradius(H)\r\n    q = 2 / (1 + np.sqrt(1 - p * p))\r\n    xkplus1 = xk = makezero()\r\n    for m in range(k):\r\n        for i in range(3):\r\n            sum = sum1 = 0\r\n            for j in range(i - 1):\r\n                sum += H[i][j] * xkplus1[j]\r\n            for j in range(i + 1, 3):\r\n                sum1 += H[i][j] * xk[j]\r\n            xkplus1[i] = xk[i] + q * (sum + sum1 - xk[i] + g[i])\r\n    return xkplus1\r\n\r\n\r\n# 2)\r\nE = np.eye(3, 3, dtype=np.double)\r\nHd = E - inv(np.diag(np.diag(myA))) @ myA\r\ngD = inv(np.diag(np.diag(myA))) @ myB\r\nprint(\"Норма H: \", norminf(Hd))\r\nprint(\"-------------------------------------------------\")\r\n\r\n\r\n# 3)\r\nprint(\"Априорная погрешность для х(7): \", infprecision(7, Hd, gD))\r\nprint(\"-------------------------------------------------\")\r\n\r\n\r\n# 4)\r\nprint(\"Метод простой итерации: \")\r\nxsimp, fiter = simpleiter(7, Hd, gD)\r\nprint(\"-------------------------------------------------\")\r\n\r\n\r\n# 5)\r\nprint(\"Метод Зейделя: \")\r\nxseid = zeidel(7, Hd, gD)\r\nprint(xseid)\r\nfseid = factprecision(xseid)\r\n\r\nprint(\"Сравним с решением, полученным методом простой итерации:\")\r\nprint(xsimp - xseid)\r\nprint(\"-------------------------------------------------\")\r\n\r\n\r\n# 6)\r\nprint(\"Радиус: \", radius(Hd))\r\nprint(\"-------------------------------------------------\")\r\n\r\n\r\n# 7)\r\nprint(\"Метод верхней релаксации: \")\r\nuppx = upperrelax(7, Hd, gD)\r\nprint(uppx)\r\nfuppx = factprecision(uppx)\r\nprint(\"-------------------------------------------------\")\r\n\r\n\r\n# 8)\r\nCond = []\r\nCond.append([0.0, fiter, fseid, fuppx])\r\n\r\nprint(tabulate(Cond, headers=['Gauss', 'Simple iteration', 'Seidel', 'Successive over-relaxation'],\r\n               tablefmt='pipe', numalign=\"right\"))\r\n", "meta": {"hexsha": "005ab2d02258f2547e23ee429cc327f89fbd6c51", "size": 6745, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester6/Task2/main.py", "max_stars_repo_name": "ladaegorova18/CalculationMethods", "max_stars_repo_head_hexsha": "7b1967cbaf0d6d6a8e744e99160f41138d40fe52", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-01T20:24:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T20:24:35.000Z", "max_issues_repo_path": "Semester6/Task2/main.py", "max_issues_repo_name": "ladaegorova18/CalculationMethods", "max_issues_repo_head_hexsha": "7b1967cbaf0d6d6a8e744e99160f41138d40fe52", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester6/Task2/main.py", "max_forks_repo_name": "ladaegorova18/CalculationMethods", "max_forks_repo_head_hexsha": "7b1967cbaf0d6d6a8e744e99160f41138d40fe52", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0883534137, "max_line_length": 100, "alphanum_fraction": 0.518902891, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361162033533, "lm_q2_score": 0.9019206837793827, "lm_q1q2_score": 0.8661695959364466}}
{"text": "# for decimal division\nfrom __future__ import division\n\nimport cvxopt\nimport numpy as np\nfrom pylab import *\nimport math\n\nfrom cvxpy import *\n\n# Taken from CVX website http://cvxr.com/cvx/examples/\n# Example: Section 5.2.5: Mixed strategies for matrix games (LP formulation)\n# Ported from cvx matlab to cvxpy by Misrab Faizullah-Khan\n# Original comments below\n\n\n# Boyd & Vandenberghe, \"Convex Optimization\"\n# Joelle Skaf - 08/24/05\n#\n# Player 1 wishes to choose u to minimize his expected payoff u'Pv, while\n# player 2 wishes to choose v to maximize u'Pv, where P is the payoff\n# matrix, u and v are the probability distributions of the choices of each\n# player (i.e. u>=0, v>=0, sum(u_i)=1, sum(v_i)=1)\n# LP formulation:   minimize    t\n#                       s.t.    u >=0 , sum(u) = 1, P'*u <= t*1\n#                   maximize    t\n#                       s.t.    v >=0 , sum(v) = 1, P*v >= t*1\n\n# Input data\nn = 12\nm = 12\nP = cvxopt.normal(n,m)\n\n# Variables for two players\nx = Variable(n)\ny = Variable(m)\nt1 = Variable()\nt2 = Variable()\n\n# Note in one case we are maximizing; in the other we are minimizing\nobjective1 = Minimize(t1)\nobjective2 = Maximize(t2)\n\nconstraints1 = [ x>=0, sum_entries(x)==1, P.T*x <= t1 ]\nconstraints2 = [ y>=0, sum_entries(y)==1, P*y >= t2 ]\n\n\np1 = Problem(objective1, constraints1)\np2 = Problem(objective2, constraints2)\n\n# Optimal strategy for Player 1\nprint 'Computing the optimal strategy for player 1 ... '\nresult1 = p1.solve()\nprint 'Done!'\n\n# Optimal strategy for Player 2\nprint 'Computing the optimal strategy for player 2 ... '\nresult2 = p2.solve()\nprint 'Done!'\n\n# Displaying results\nprint '------------------------------------------------------------------------'\nprint 'The optimal strategies for players 1 and 2 are respectively: '\nprint x.value, y.value\nprint 'The expected payoffs for player 1 and player 2 respectively are: '\nprint result1, result2\nprint 'They are equal as expected!'\n## ISSUE: THEY AREN'T EXACTLY EQUAL FOR SOME REASON!\n", "meta": {"hexsha": "54ab67e080fccf5bcb1f39cd4b5969305d9378d7", "size": 1988, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/tools/ecos/cvxpy/examples/matrix_games_LP.py", "max_stars_repo_name": "riadnassiffe/Simulator", "max_stars_repo_head_hexsha": "7d9ff09f26367d3714e3d10be3dd4a9817b8ed6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-08-31T01:37:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T04:23:09.000Z", "max_issues_repo_path": "examples/matrix_games_LP.py", "max_issues_repo_name": "quantopian/cvxpy", "max_issues_repo_head_hexsha": "7deee4d172470aa8f629dab7fead50467afa75ff", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-06-05T17:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T23:20:32.000Z", "max_forks_repo_path": "src/tools/ecos/cvxpy/examples/matrix_games_LP.py", "max_forks_repo_name": "riadnassiffe/Simulator", "max_forks_repo_head_hexsha": "7d9ff09f26367d3714e3d10be3dd4a9817b8ed6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-02-09T19:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-07T00:17:54.000Z", "avg_line_length": 28.8115942029, "max_line_length": 80, "alphanum_fraction": 0.6584507042, "include": true, "reason": "import numpy,from cvxpy", "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611631680358, "lm_q2_score": 0.9019206771886167, "lm_q1q2_score": 0.8661695906301624}}
{"text": "import numpy as np\nimport scipy as sp\nimport sympy as sm\n\ndef gauss_jordan(A,no_reduction=False):\n    \"\"\" Gauss-Jordan elimination\n\n    Convert a matrix to its row (reduced) echelon form.\n\n    Args:\n\n        A (ndarray): input matrix to work on in-place\n        no_reduction (bool): stop when non-reduced echelon form is reached\n\n    \"\"\"\n\n    n,_m = A.shape\n\n    # row echelon form (Gauss elimination)\n    for i in range(0, n):\n\n        # a. search for maximum in this column\n        maxrow = i + np.argmax(abs(A[i:,i]))\n\n        # b. swap maximum row with current row (column by column)\n        temp = A[maxrow,i:].copy()\n        A[maxrow,i:] = A[i,i:]\n        A[i,i:] = temp\n\n        # b. make all rows below this one 0 in current column\n        for k in range(i+1, n):\n            c = -A[k,i]/A[i,i]\n            A[k,i] = 0\n            A[k,i+1:] += c*A[i,i+1:]\n        \n    if no_reduction:\n        return\n\n    # reduced row echelon form (Gauss-Jordan elimination)\n    for i in range(n-1,-1,-1):\n        \n        # a. normalize this row\n        c = A[i,i]\n        A[i,:] /= c\n\n        # b. make all rows above this one 0 in the current column\n        for j in range(0,i):\n            c = A[j,i]\n            A[j,:] -= c*A[i,:]\n\ndef gauss_seidel_split(A):\n    \"\"\" split A matrix in additive lower and upper triangular matrices\n\n    Args:\n\n        A (ndarray): input matrix\n\n    Returns:\n\n        L (ndarray): lower triangular matrix\n        U (ndarray): upper triangular matrix (zero diagonal)\n\n    \"\"\"\n\n    L = np.tril(A)\n    U = np.triu(A)\n    np.fill_diagonal(U,0)\n    return L,U\n\ndef solve_with_forward_substitution(L,RHS):\n    \"\"\" solve matrix equation with forward substitution\n\n    Args:\n\n        L (ndarray): lower triangular matrix\n        RHS (ndarray): vector of right-hand-side variables\n\n    Returns:\n\n        x (ndarray): Solution vector\n\n    \"\"\"\n\n    n = RHS.size\n    x = np.zeros(n)\n    for i in range(n):\n        x[i] = RHS[i]\n        for j in range(i):\n            x[i] -= L[i,j]*x[j]    \n        x[i] /= L[i,i]\n    \n    return x\n\ndef solve_with_backward_substitution(U,RHS):\n    \"\"\" solve matrix equation with backward substitution\n\n    Args:\n\n        L (ndarray): uppper triangular matrix\n        RHS (ndarray): vector of right-hand-side variables\n\n    Returns:\n\n        x (ndarray): Solution vector\n\n    \"\"\"\n\n    n = RHS.size\n    x = np.zeros(n)\n    for i in reversed(range(n)):\n        x[i] = RHS[i]\n        for j in range(i+1,n):\n            x[i] -= U[i,j]*x[j]    \n        x[i] /= U[i,i]\n    \n    return x\n\ndef gauss_seidel(A,b,x0,max_iter=500,tau=10**(-8),do_print=False):\n    \"\"\" solve matrix equation with Gauss-Seidel\n\n    Args:\n\n        A (ndarray): LHS matrix\n        b (ndarray): RHS vector\n        x0 (ndarray): guess on solution\n        max_iter (int): maximum number of iterations (optional)\n        tau (float): tolerance level\n        do_print (bool): indicator for whether to print or not\n\n    Returns:\n\n        x (ndarray): Solution vector\n\n    \"\"\"\n\n    converged = False\n\n    # a. split\n    L,U = gauss_seidel_split(A)\n    \n    # b. iterate\n    x = x0\n    i = 0\n\n    if do_print:\n        print('  ',x)\n\n    while i < max_iter and not converged:\n        \n        # i. save previous\n        x_prev = x\n        \n        # ii. compute RHS\n        y = b-U@x\n\n        # iii. solve with forward substituion\n        x = solve_with_forward_substitution(L,y)\n        #x = sp.linalg.solve_triangular(L,y,lower=True) # equivalent, but faster\n        \n        # iv. check convergence\n        max_abs_diff = np.max(np.abs(x-x_prev))\n        if max_abs_diff < tau:\n            converged = True\n\n        # v. misc\n        if do_print:\n            print(f'{i:2d}',x)\n\n        i += 1\n\n    return x\n\ndef lu_decomposition(A):\n    \"\"\" compute LU decomposition\n\n    Args:\n\n        A (ndarray): input matrix\n\n    Returns:\n\n        L (ndarray): lower triangular matrix\n        U (ndarray): upper triangular matrix\n\n    \"\"\"\n    \n    n = len(A)\n\n    # a. create zero matrices for L and U                                                                                                                                                                                                                 \n    L = np.zeros((n,n))\n    U = np.zeros((n,n))\n\n    # b. set diagonal of L to one\n    np.fill_diagonal(L,1)\n    \n    # c. perform the LU Decomposition                                                                                                                                                                                                                     \n    for j in range(n):          \n\n        for i in range(j+1):\n            c = U[:,j]@L[i,:]\n            U[i][j] = A[i][j] - c\n\n        for i in range(j, n):\n            c = U[:j,j]@L[i,:j]\n            L[i][j] = (A[i][j] - c) / U[j][j]\n\n    return L,U\n\ndef construct_sympy_matrix(positions,name='a'):\n    \"\"\" construct sympy matrix with non-zero elements in positions\n    \n    Args:\n    \n        Positions (list): list of positions in strings, e.g. ['11','31']\n    \n    Returns:\n    \n        mat (sympy.matrix): Sympy Matrix\n    \n    \"\"\"\n    \n    # a. dictionary of element with position as key and a_position as value\n    entries = {f'{ij}':sm.symbols(f'{name}_{ij}') for ij in positions}\n\n    # b. function for creating element or zero\n    add = lambda x: entries[x] if x in entries else 0\n\n    # c. create matrix\n    mat_as_list = [[add(f'{1+i}{1+j}') for j in range(3)] for i in range(3)]\n    mat = sm.Matrix(mat_as_list)\n\n    return mat\n\ndef fill_sympy_matrix(A_sm,A,name='a'):\n\n    n,m = A.shape\n\n    # a. make all substitution\n    A_sm_copy = A_sm\n    for i in range(n):\n        for j in range(m):\n            if not A[i,j] == 0:\n                A_sm_copy = A_sm_copy.subs(f'{name}_{1+i}{1+j}',A[i,j])\n    \n    # b. lambdify with no inputs\n    f = sm.lambdify((),A_sm_copy)\n\n    # c. return filled matrix\n    return f()", "meta": {"hexsha": "fb5249730c8cb36471a7b21afcb1b3207f83d278", "size": 5901, "ext": "py", "lang": "Python", "max_stars_repo_path": "09/numecon_linalg.py", "max_stars_repo_name": "mariusgruenewald/lectures-2019", "max_stars_repo_head_hexsha": "36812db370dfe7229be2df88b5020940394e54c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-01-11T09:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-25T05:45:18.000Z", "max_issues_repo_path": "09/numecon_linalg.py", "max_issues_repo_name": "mariusgruenewald/lectures-2019", "max_issues_repo_head_hexsha": "36812db370dfe7229be2df88b5020940394e54c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-01-09T19:32:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-02T15:51:44.000Z", "max_forks_repo_path": "09/numecon_linalg.py", "max_forks_repo_name": "mariusgruenewald/lectures-2019", "max_forks_repo_head_hexsha": "36812db370dfe7229be2df88b5020940394e54c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2019-02-11T09:23:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T10:54:42.000Z", "avg_line_length": 23.6987951807, "max_line_length": 250, "alphanum_fraction": 0.5039823759, "include": true, "reason": "import numpy,import scipy,import sympy", "num_tokens": 1524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.90192067652954, "lm_q1q2_score": 0.8661695859042842}}
{"text": "# Question 3, Lab 07\n# AB Satyaprakash, 180123062\n\n# imports\nimport numpy as np\n\n# functions\n\n\ndef F(t, part):\n    if part == 'a':\n        return np.sqrt(t**2 + 6 + 2*t) - 1\n    else:\n        return (4+np.cos(2)-np.cos(2*t))/(2*(t**2))\n\n\ndef f(t, y, part):\n    if part == 'a':\n        return (t+1)/(y+1)\n    else:\n        return (np.sin(2*t) - 2*t*y)/(t**2)\n\n\ndef ModEuler(t, y, h, part):\n    k1 = f(t, y, part)\n    k2 = k1 + f(t+h, y+h*k1, part)\n    return y + h*k2/2\n\n# program body\n# part (a)\n\n\nh, t, y = 0.5, 1, 2\nwhile t <= 2:\n    print('For part (a) y({}) is approximated as {}'.format(t, y))\n    print('Actual value of y({}) is given by {}\\n'.format(t, F(t, 'a')))\n    y = ModEuler(t, y, h, 'a')\n    t += h\n\nprint('----------------------------------------------------------------')\n\n\n# part (b)\nh, t, y = 0.25, 1, 2\nwhile t <= 2:\n    print('For part (b) y({}) is approximated as {}'.format(t, y))\n    print('Actual value of y({}) is given by {}\\n'.format(t, F(t, 'b')))\n    y = ModEuler(t, y, h, 'b')\n    t += h\n", "meta": {"hexsha": "2ce44c0c0e36ba51fb7378cac3bfc44714692f03", "size": 1019, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 7/Code/q3.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 7/Code/q3.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 7/Code/q3.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 20.38, "max_line_length": 73, "alphanum_fraction": 0.4612365064, "include": true, "reason": "import numpy", "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013548, "lm_q2_score": 0.908617906830944, "lm_q1q2_score": 0.8661627739334837}}
{"text": "import scipy.stats\nimport numpy as np\n\n\ndef welch_t_test(samples_x, samples_y, diff: float = 0.0, tail: str = \"both\"):\n    assert tail in {\"both\", \"left\", \"right\"}\n\n    mean_x = np.mean(samples_x)\n    mean_y = np.mean(samples_y)\n\n    n_x = len(samples_x)\n    n_y = len(samples_y)\n\n    var_x_norm = np.var(samples_x, ddof=1) / n_x\n    var_y_norm = np.var(samples_y, ddof=1) / n_y\n\n    pooled_var = var_x_norm + var_y_norm\n\n    test_statistic = (mean_x - mean_y - diff) / np.sqrt(pooled_var)\n\n    df = np.square(pooled_var) / (\n        np.square(var_x_norm) / (n_x - 1) + np.square(var_y_norm) / (n_y - 1)\n    )\n    null_dist = scipy.stats.t(df)\n\n    if tail == \"both\":\n        p_value = 2.0 * null_dist.cdf(-abs(test_statistic))\n\n    elif tail == \"left\":\n        p_value = null_dist.cdf(test_statistic)\n\n    else:\n        p_value = null_dist.sf(test_statistic)\n\n    return test_statistic, p_value\n\n\ndef two_sample_t_test_equal_var(\n    samples_x, samples_y, diff: float = 0.0, tail: str = \"both\"\n):\n    \"\"\"Two sample t-test for normal data to check if pop. mean differs by `diff`.\n\n    Assumptions:\n        i.i.d. x_{1}, ..., x_{n} ~ N(mu_{x}, sigma^{2})\n        i.i.d. y_{1}, ..., y_{m} ~ N(mu_{y}, sigma^{2})\n        Note 1: that the variance for all distributions are the same, sigma^{2}.\n        Note 2: `n` may be different from `m`.\n\n    Test statistic: t = (x_mean - y_mean - diff) / sqrt(pooled_var)\n    where:\n        pooled_var = ((n - 1) * sample_var_x + (m - 1) * sample_var_y) * norm_factor,\n        norm_factor = (1 / n + 1 / m) / (n + m - 2)\n\n    null distribution: T ~ t(n + m - 2), there t is the t-student distribution.\n\n    H0: x_mean - y_mean = `diff`\n    HA:\n        if tail = `both` : x_mean - y_mean != `diff`\n        if tail = `left` : x_mean - y_mean < `diff`\n        if tail = `right`: x_mean - y_mean > `diff`\n    \"\"\"\n    assert tail in {\"both\", \"left\", \"right\"}\n\n    mean_x = np.mean(samples_x)\n    mean_y = np.mean(samples_y)\n\n    n_x = len(samples_x)\n    n_y = len(samples_y)\n\n    var_x = np.var(samples_x, ddof=n_x - 1)\n    var_y = np.var(samples_y, ddof=n_y - 1)\n\n    pooled_var = (var_x + var_y) / (n_x + n_y - 2) * (1.0 / n_x + 1.0 / n_y)\n\n    test_statistic = (mean_x - mean_y - diff) / np.sqrt(pooled_var)\n\n    null_dist = scipy.stats.t(n_x + n_y - 2)\n\n    if tail == \"both\":\n        p_value = 2.0 * null_dist.cdf(-abs(test_statistic))\n\n    elif tail == \"left\":\n        p_value = null_dist.cdf(test_statistic)\n\n    else:\n        p_value = null_dist.sf(test_statistic)\n\n    return test_statistic, p_value\n\n\ndef _test():\n    sample_std = 6\n    test_x = [12, 10, -5, -5, 0, 0, 0]\n    test_y = [12, 11, -5, -4, 0, 1, -1]\n    diffs = [0, 0, 0, -1, 0, -1, 1]\n    for tail, tail_scipy in zip(\n        [\"both\", \"left\", \"right\"], [\"two-sided\", \"less\", \"greater\"]\n    ):\n        for mean_x, mean_y, diff in zip(test_x, test_y, diffs):\n            sample_x = mean_x + sample_std * np.random.randn(200)\n            sample_y = mean_y + sample_std * np.random.randn(100)\n            res = two_sample_t_test_equal_var(sample_x, sample_y, diff=diff, tail=tail)\n            scipy_res = scipy.stats.ttest_ind(\n                sample_x, sample_y, equal_var=True, alternative=tail_scipy\n            )\n\n            print(tail, res, scipy_res)\n            if np.isclose(0, diff):\n                assert np.allclose(res, scipy_res)\n\n            res_welch = welch_t_test(sample_x, sample_y, diff=diff, tail=tail)\n            scipy_welch_res = scipy.stats.ttest_ind(\n                sample_x, sample_y, equal_var=False, alternative=tail_scipy\n            )\n            print(tail, res_welch, scipy_welch_res)\n            if np.isclose(0, diff):\n                assert np.allclose(res_welch, scipy_welch_res)\n\n\nif __name__ == \"__main__\":\n    _test()\n", "meta": {"hexsha": "52aa19d9bb44de0c4022eec79aff8731f6ce68c2", "size": 3759, "ext": "py", "lang": "Python", "max_stars_repo_path": "statistical_tests/two_sample_t_test.py", "max_stars_repo_name": "FelSiq/statistics-related", "max_stars_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-13T02:09:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-13T02:09:08.000Z", "max_issues_repo_path": "statistical_tests/two_sample_t_test.py", "max_issues_repo_name": "FelSiq/statistics-related", "max_issues_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "statistical_tests/two_sample_t_test.py", "max_forks_repo_name": "FelSiq/statistics-related", "max_forks_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8114754098, "max_line_length": 87, "alphanum_fraction": 0.5844639532, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739076, "lm_q2_score": 0.9086179006446221, "lm_q1q2_score": 0.8661627668300752}}
{"text": "import numpy as np \nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ncfs_to_taf = 2.29568411*10**-5 * 86400 / 1000\n\ndef autocorr(x,k):\n  '''returns the lag-k autocorrelation of vector x'''\n  return np.corrcoef(x[:len(x)-k], x[k:])[0,1]\n\ndef thomasfiering(x1, x2, N):\n  '''Lag-1 model for two sites. use historical data x \n  to generate a synthetic sequence of N timesteps.\n  Assumes x is lognormally distributed.'''\n  # being lazy here, do it in a loop instead\n  x1 = np.log(x1) # log-space avoids negative values\n  m1 = x1.mean()\n  s1 = x1.std()\n  r1 = autocorr(x1,1)\n  Q1 = np.zeros(N) # initialize\n  Q1[0] = np.random.normal(m1,s1,1) \n\n  x2 = np.log(x2) # log-space avoids negative values\n  m2 = x2.mean()\n  s2 = x2.std()\n  r2 = autocorr(x2,1)\n  Q2 = np.zeros(N) # initialize\n  Q2[0] = np.random.normal(m2,s2,1) \n\n  Sigma = np.corrcoef(x1, x2)\n\n  for i in range(1,N):\n    Z = np.random.multivariate_normal([0,0], Sigma, 1)\n    Q1[i] = m1 + r1*(Q1[i-1] - m1) + Z[0,0]*s1*np.sqrt(1-r1**2)\n    Q2[i] = m2 + r2*(Q2[i-1] - m2) + Z[0,1]*s2*np.sqrt(1-r2**2)\n  \n  return np.exp(Q1), np.exp(Q2)\n\n# read in data and upscale to annual. rename the column we're going to use.\n# this is an example of \"method chaining\" with pandas dataframes\n# it's not required to use multiple lines, but usually makes it more readable.\ndfF = (pd.read_csv('data/FOL.csv', index_col=0, parse_dates=True)\n         .rename(columns={'FOL_INFLOW_CFS':'inflow'}))\ndfS = (pd.read_csv('data/SHA.csv', index_col=0, parse_dates=True)\n         .rename(columns={'SHA_INFLOW_CFS':'inflow'}))\n\ndfS.inflow *= cfs_to_taf\ndfF.inflow *= cfs_to_taf\ndfS = dfS.resample('AS-OCT').sum()\ndfF = dfF.resample('AS-OCT').sum()\n\n# generate synthetic (input numpy arrays)\nQ1, Q2 = thomasfiering(dfS.inflow.values, dfF.inflow.values, N=200)\n\n# compare spatial correlation (this is in real space, not log)\nprint('Historical r = %0.3f' % np.corrcoef(dfS.inflow.values, dfF.inflow.values)[0,1])\nprint('Synthetic r = %0.3f' % np.corrcoef(Q1, Q2)[0,1])\n\n", "meta": {"hexsha": "87220064229fa9c97f3339b08f2aec3eba5d2ca4", "size": 1996, "ext": "py", "lang": "Python", "max_stars_repo_path": "L10-multisite.py", "max_stars_repo_name": "jdherman/eci273", "max_stars_repo_head_hexsha": "86828b2e075258afdd528e86295170e162cc99e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-12-23T02:59:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T11:55:21.000Z", "max_issues_repo_path": "L10-multisite.py", "max_issues_repo_name": "jdherman/eci273", "max_issues_repo_head_hexsha": "86828b2e075258afdd528e86295170e162cc99e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "L10-multisite.py", "max_forks_repo_name": "jdherman/eci273", "max_forks_repo_head_hexsha": "86828b2e075258afdd528e86295170e162cc99e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-12-21T02:06:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T02:36:47.000Z", "avg_line_length": 33.8305084746, "max_line_length": 86, "alphanum_fraction": 0.6643286573, "include": true, "reason": "import numpy", "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104982195785, "lm_q2_score": 0.8962513765975758, "lm_q1q2_score": 0.8661467393876463}}
{"text": "\"\"\"\r\nExercise 2\r\nWrite a program that asks the user for two expressions and then graphs them\r\nboth,as follows:\r\n>>> expr1 = input('Enter your first expression in terms of x and y: ')\r\n>>> expr2 = input('Enter your second expression in terms of x and y: ')\r\nOnce you've complete this, enhance your program to print the solution - the pair\r\nof x and y values that satisfies both equation. This will also be the spot \r\nwhere the two lines on the graph intersect. (Hint: Refer to how we used to the\r\nsolve () function earlier to find the solution of a system of two linear \r\nequations)\r\n\r\n\"\"\"\r\n\r\nfrom sympy import plot, solve, sympify\r\nfrom sympy.core.sympify import SympifyError\r\nfrom sympy import Symbol\r\n\r\n\r\nexpr1 = input(\"Enter your first expression in terms of x and y: \")\r\nexpr2 = input(\"Enter your second expression in terms of x and y: \")\r\n\r\ntry:\r\n    expr1 = sympify(expr1)\r\n    expr2 = sympify(expr2)\r\n\r\nexcept SympifyError:\r\n    print(\"Invalid input\")\r\n\r\n\r\nx = Symbol(\"x\")\r\ny = Symbol(\"y\")\r\n\r\n# plot(expr1,expr2)\r\nprint(solve(expr1, expr2, dict=True))\r\n", "meta": {"hexsha": "0acdb81013fe7e56b2801766c8b2056d777bd7a7", "size": 1060, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Chapter4/Exercise2.py", "max_stars_repo_name": "djeada/Doing-Math-with-Python", "max_stars_repo_head_hexsha": "6b5fb4018224032f805314d367f810c127246ccf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Chapter4/Exercise2.py", "max_issues_repo_name": "djeada/Doing-Math-with-Python", "max_issues_repo_head_hexsha": "6b5fb4018224032f805314d367f810c127246ccf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Chapter4/Exercise2.py", "max_forks_repo_name": "djeada/Doing-Math-with-Python", "max_forks_repo_head_hexsha": "6b5fb4018224032f805314d367f810c127246ccf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4444444444, "max_line_length": 81, "alphanum_fraction": 0.7047169811, "include": true, "reason": "from sympy", "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104962847373, "lm_q2_score": 0.8962513682840824, "lm_q1q2_score": 0.8661467296192948}}
{"text": "\n# A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.\n\n# A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.\n\n# As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.\n\n# Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.\nimport numpy as np\nfrom utils.common import divisors\nmax_num = 28123\nabundant_nums = np.zeros(max_num, dtype=np.int8)\nfor i in range(12, max_num):\n    if sum(divisors(i, proper=True)) > i:\n        abundant_nums[i] = 1\n# print(np.bincount(abundant_nums))\n\nnums = np.ones(max_num, dtype=np.int8)\nfor i in range(24, max_num):\n    for a in range(12, i//2 + 1):\n        if abundant_nums[a] == 0:continue\n        if abundant_nums[i-a] == 1:\n            # this is the sum of two abundant numbers so remove from list by setting to 0\n            nums[i] = 0\n            break\nnum_sum = 0\nfor i, n in enumerate(nums):\n    if n == 1:\n        num_sum += i\nprint(num_sum)\n", "meta": {"hexsha": "ce87b3c8e3b264a24b89b4d157aa0c8f9bcc3c0a", "size": 1606, "ext": "py", "lang": "Python", "max_stars_repo_path": "p023.py", "max_stars_repo_name": "drcsturm/project-euler", "max_stars_repo_head_hexsha": "07c4e6593f14eed039e580009d5cd5be5f541dfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "p023.py", "max_issues_repo_name": "drcsturm/project-euler", "max_issues_repo_head_hexsha": "07c4e6593f14eed039e580009d5cd5be5f541dfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "p023.py", "max_forks_repo_name": "drcsturm/project-euler", "max_forks_repo_head_hexsha": "07c4e6593f14eed039e580009d5cd5be5f541dfb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.8064516129, "max_line_length": 478, "alphanum_fraction": 0.7061021171, "include": true, "reason": "import numpy", "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104924150546, "lm_q2_score": 0.8962513682840824, "lm_q1q2_score": 0.8661467261510865}}
{"text": "import math\nimport numpy as np\n\ndef distance(c1, c2, indexes=None, weights=None, nan_value=None):\n    \"\"\" Calculate the Euclidean distance between two clusters\n    :param c1 The first cluster\n    :param c2 The second cluster\n    :param indexes the indexes to compute the Euclidean distance\n    :param weights the to weight the some of the values, default is None where all indexes have equal weights \n    :param nan_value the value that will replace nan in the clusters' serie. Default is None which does not replace nan\n    \"\"\"\n    s1 = c1.serie if indexes is None else [c1.serie[i] for i in indexes]\n    s2 = c2.serie if indexes is None else [c2.serie[i] for i in indexes]\n    assert len(s1) == len(s2) and len(s1) > 0\n    if nan_value is not None:\n        # Replace nan values in the series\n        s1 = [ nan_value if np.isnan(x) else x for x in s1]\n        s2 = [ nan_value if np.isnan(x) else x for x in s2]\n    # Handle weights\n    if weights is None:\n        weights = [1 for _ in range(len(s1))]\n    else:\n        assert len(weights) == len(s1)\n    return np.sqrt((np.multiply(weights, np.power(np.subtract(s1, s2), 2))).sum())\n    \ndef get_indexes (minIndex, nClusters):\n    \"\"\" Get the index of the clusters based on the index of the minimum distance between clusters\n    \"\"\"\n    index1 = 0\n    while minIndex >= (nClusters - 1):\n        minIndex -= nClusters - 1\n        nClusters -= 1\n        index1 += 1\n    index2 = minIndex % (nClusters - 1)\n    return (index1, index2 + index1 + 1)\n", "meta": {"hexsha": "7cf629d24a2851216931af0010b33282eade565f", "size": 1499, "ext": "py", "lang": "Python", "max_stars_repo_path": "clusterify/util.py", "max_stars_repo_name": "jmineraud/clusterify", "max_stars_repo_head_hexsha": "55de893e8864f835b6e64b9cfd606b08151f1b59", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "clusterify/util.py", "max_issues_repo_name": "jmineraud/clusterify", "max_issues_repo_head_hexsha": "55de893e8864f835b6e64b9cfd606b08151f1b59", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-04-09T07:27:12.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-09T07:27:12.000Z", "max_forks_repo_path": "clusterify/util.py", "max_forks_repo_name": "jmineraud/clusterify", "max_forks_repo_head_hexsha": "55de893e8864f835b6e64b9cfd606b08151f1b59", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6388888889, "max_line_length": 119, "alphanum_fraction": 0.6564376251, "include": true, "reason": "import numpy", "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966410494349896, "lm_q2_score": 0.8962513620489619, "lm_q1q2_score": 0.8661467218595049}}
{"text": "#\n# demo_statistics.py\n#\n\nimport numpy\nimport random\nimport statistics\nimport matplotlib.pyplot as plt\n\n'''\nCalculate the mean, mode, median, standard deviation and variance.\n'''\n\ndata = numpy.random.normal(1, 0.5, 10000)\n\nmean = statistics.mean(data)\nmode = statistics.mode(data)\nmedian = statistics.median(data)\nstd = statistics.standard_deviation(data)\nvariance = statistics.variance(data)\n\nprint('')\nprint('Mean: ' + str(mean))\nprint('Mode: ' + str(mode))\nprint('Median: ' + str(median))\nprint('Standard Variance: ' + str(std))\nprint('Variance: ' + str(variance))\n\nplt.xlabel('value')\nplt.ylabel('count')\nplt.hist(data, 50)\nplt.show()\n\n'''\nCalculate the covariance of uncorrelated data.\n'''\n\nages = numpy.random.normal(50.0, 10.0, 1000)\nincome = numpy.random.normal(100000.0, 75000.0, 1000)\n\ncovariance = statistics.covariance(ages, income, is_sample=True)\ncorrelation = statistics.correlation(ages, income, is_sample=True)\n\nprint('')\nprint('Uncorrelated data.')\nprint('Covariance: ' + str(covariance))\nprint('Correlation: ' + str(correlation))\n\nplt.xlabel('age')\nplt.ylabel('income')\nplt.scatter(ages, income)\nplt.show()\n\n'''\nCalculate the covariance and correlation of data known to be correlated.\n'''\n\nages = numpy.random.normal(50.0, 10.0, 1000)\nincome = [(n*1000+random.uniform(0, n/1000)*500000) for n in ages]\n\ncovariance = statistics.covariance(ages, income, is_sample=True)\ncorrelation = statistics.correlation(ages, income, is_sample=True)\n\nprint('')\nprint('Correlated data.')\nprint('Covariance: ' + str(covariance))\nprint('Correlation: ' + str(correlation))\n\nplt.xlabel('age')\nplt.ylabel('income')\nplt.scatter(ages, income)\nplt.show()\n\nprint('')\n", "meta": {"hexsha": "4b6afbc7fb6b3982aca4b12cb385a66d4f8747a2", "size": 1661, "ext": "py", "lang": "Python", "max_stars_repo_path": "conveniences/demo_statistics.py", "max_stars_repo_name": "mateusnbm/ai-conveniences", "max_stars_repo_head_hexsha": "4a0cd0d761f1d534149f9f0ab03f5f94e4290580", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "conveniences/demo_statistics.py", "max_issues_repo_name": "mateusnbm/ai-conveniences", "max_issues_repo_head_hexsha": "4a0cd0d761f1d534149f9f0ab03f5f94e4290580", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conveniences/demo_statistics.py", "max_forks_repo_name": "mateusnbm/ai-conveniences", "max_forks_repo_head_hexsha": "4a0cd0d761f1d534149f9f0ab03f5f94e4290580", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1466666667, "max_line_length": 72, "alphanum_fraction": 0.7230583986, "include": true, "reason": "import numpy", "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203814, "lm_q2_score": 0.897695301686844, "lm_q1q2_score": 0.866145940008745}}
{"text": "\n# coding: utf-8\n\n# In[2]:\n\n\nimport numpy as np\nfrom scipy import linalg\narr = np.array([[1, 2],[3, 4]])\n##矩阵行列式\nprint(\"矩阵行列式：\",linalg.det(arr))\nprint(\"矩阵的逆：\",linalg.inv(arr))\n\n\n# In[5]:\n\n\n#奇异值分解\narr = np.arange(9).reshape((3, 3)) + np.diag([1, 0, 1])\nuarr, spec, vharr = linalg.svd(arr)\nprint(spec)\nsarr = np.diag(spec)\nsvd_mat = uarr.dot(sarr).dot(vharr)\nprint(svd_mat)\nnp.allclose(arr,svd_mat)\n\n\n# In[10]:\n\n\n##傅里叶变换\n##优化\nfrom scipy import optimize\ndef f(x):\n    return x**2 + 10*np.sin(x)\nimport matplotlib.pyplot as plt\nx = np.arange(-10, 10, 0.1)\nplt.plot(x, f(x)) \nplt.show() \n##bfgs依赖于初始点，有可能得到局部最小\noptimize.fmin_bfgs(f, 0)\n\n\n# In[12]:\n\n\noptimize.fmin_bfgs(f, 3)\n\n\n# In[13]:\n\n\n##全局最优\noptimize.basinhopping(f, 0)\n\n\n# In[15]:\n\n\n#计算函数的根\n#1 只求的一个\nroot = optimize.fsolve(f, 1)\nroot\n\n\n# In[16]:\n\n\n##曲线拟合\nxdata = np.linspace(-10, 10, num=20)\nydata = f(xdata) + np.random.randn(xdata.size)\n#假设满足函数f2，然后求a、b\ndef f2(x, a, b):\n     return a*x**2 + b*np.sin(x)\nguess = [2, 2]\nparams, params_covariance = optimize.curve_fit(f2, xdata, ydata, guess)\nparams\n\n\n# In[27]:\n\n\n#统计\na = np.random.normal(size=1000)\nbins = np.arange(-4, 5)\nprint(bins)\nhistogram = np.histogram(a, bins=bins, normed=True)[0]\nprint(histogram)\nbins = 0.5*(bins[1:] + bins[:-1])\nprint(bins)\nfrom scipy import stats\n#pdf概率密度函数probability density function\nb = stats.norm.pdf(bins)\nprint(\"pdf:\",b)\nplt.plot(bins, histogram)\nplt.plot(bins, b)\nplt.show()\nloc, std = stats.norm.fit(a)\nprint(\"loc:\"+str(loc)+\"std:\"+str(std))\n#中位数\nnp.median(a)\n\n\n# In[28]:\n\n\n#50百分位\nstats.scoreatpercentile(a, 50)\n\n\n# In[29]:\n\n\n#t检验\na = np.random.normal(0, 1, size=100)\nb = np.random.normal(1, 1, size=10)\nstats.ttest_ind(a, b)\n\n\n# In[ ]:\n", "meta": {"hexsha": "c1b221708bef52545a4805870ed7b0384c696ca3", "size": 1676, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/ml/sci.py", "max_stars_repo_name": "STU-BLUESKY/machine-learning", "max_stars_repo_head_hexsha": "83c7f569bfc39a877e1b0b16c03ea5f034f58de3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 239, "max_stars_repo_stars_event_min_datetime": "2017-08-11T02:55:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T13:21:07.000Z", "max_issues_repo_path": "src/ml/sci.py", "max_issues_repo_name": "Super-Shen/machine-learning", "max_issues_repo_head_hexsha": "451ca671d757fa35c54d086401821df50069415f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-08-16T02:49:24.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-16T02:49:24.000Z", "max_forks_repo_path": "src/ml/sci.py", "max_forks_repo_name": "Super-Shen/machine-learning", "max_forks_repo_head_hexsha": "451ca671d757fa35c54d086401821df50069415f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 92, "max_forks_repo_forks_event_min_datetime": "2017-07-27T09:53:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T09:38:11.000Z", "avg_line_length": 13.8512396694, "max_line_length": 71, "alphanum_fraction": 0.6461813842, "include": true, "reason": "import numpy,from scipy", "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551495568569, "lm_q2_score": 0.8976952989498448, "lm_q1q2_score": 0.8661459319247399}}
{"text": "\r\n\"\"\"\"\"\"\"\"\"\"\"\r\nNumPy Coding\r\n\r\n\"\"\"\"\"\"\"\"\"\"\"\r\n\r\nimport numpy as np\r\n\r\nNumP_Array = np.array([[1,2,3],[4,6,7]])\r\n\r\nNP1 = np.array([[1,3],[4,5]])\r\n\r\nNP2 = np.array([[3,4],[5,7]])\r\n\r\nMNP = NP1@NP2\r\n\r\nMNP3 = np.dot(NP1,NP2)\r\n\r\nMNP2 = NP1*NP2\r\n\r\nMNP4 = np.multiply(NP1,NP2)\r\n\r\nSum1 = NP1+NP2\r\n\r\nSub1 = NP1-NP2\r\n\r\nSub2 = np.subtract(NP1,NP2)\r\n\r\nnp.sum(NP1)\r\n\r\nBroad_Nump = NP1+3\r\n\r\nNP3 = np.array([[3,4]])\r\n\r\nNP1+NP3\r\n\r\nD = np.divide([12,14,16],5)\r\n\r\nD = np.floor_divide([12,14,16],5)\r\n\r\nnp.math.sqrt(10)\r\n\r\nND = np.random.standard_normal((3,4))\r\n\r\nUD = np.random.uniform(1,12,(3,4))\r\n\r\n# Generate Float No.\r\n\r\nnp.random.rand()\r\n\r\n# Generate Integer No.\r\n\r\nRandom_Ar= np.random.randint(1,50,(2,5))\r\n\r\nZe = np.zeros((3,4))\r\n\r\nOnes = np.ones((3,4))\r\n\r\n\r\nFilter_Ar = np.logical_and(Random_Ar>30,Random_Ar<50)\r\n\r\nF_Random_Ar = Random_Ar[Filter_Ar]\r\n\r\n\r\nData_N = np.array([1,3,4,5,7,9])\r\n\r\nMean_N = np.mean(Data_N)\r\n\r\nMedian_N = np.median(Data_N)\r\n\r\nVar_N = np.var(Data_N)\r\n\r\nSD_N = np.std(Data_N)\r\n\r\n\r\nNumP_Array = np.array([[1,2,3],[4,6,7]])\r\n\r\n\r\nVar_Nump = np.var(NumP_Array,axis=1)\r\n\r\nVar_Nump2 = np.var(NumP_Array,axis=0)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "c17e03fb08289cb28c7ee65e5db1e6f05b77498a", "size": 1137, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter2.NumPy.py", "max_stars_repo_name": "Kunjesh07/ML-Practice", "max_stars_repo_head_hexsha": "12ff0e235115b971428d8ae6246e1c8e89a5b48b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter2.NumPy.py", "max_issues_repo_name": "Kunjesh07/ML-Practice", "max_issues_repo_head_hexsha": "12ff0e235115b971428d8ae6246e1c8e89a5b48b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter2.NumPy.py", "max_forks_repo_name": "Kunjesh07/ML-Practice", "max_forks_repo_head_hexsha": "12ff0e235115b971428d8ae6246e1c8e89a5b48b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.2258064516, "max_line_length": 54, "alphanum_fraction": 0.5708003518, "include": true, "reason": "import numpy", "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551515780319, "lm_q2_score": 0.8976952914230972, "lm_q1q2_score": 0.866145926476918}}
{"text": "import numpy as np\n\n\ndef _compute_c_matrix(N):\n    C = np.zeros((N, N))\n\n    C[0, :] = np.sqrt(1.0 / N)\n    for k in range(1, N):\n        for j in range(N):\n            C[k, j] = np.cos(np.pi * k * (2 * j + 1) / (2.0 * N)) * np.sqrt(2.0 / N)\n\n    return C\n\ndef _dct(A):\n    if A.ndim != 1:\n        raise ValueError(\"matrix 'A' must be 1-dimensional\")\n\n    N = A.shape[0]\n    return _compute_c_matrix(N).dot(A)\n\ndef _dct2(A):\n    if A.ndim != 2:\n        raise ValueError(\"matrix 'A' must be 2-dimensional\")\n\n    N, M = A.shape\n    if N != M:\n        raise ValueError(f\"Matrix 'A' ({N}x{M}) must be squared\")\n\n    C = _compute_c_matrix(N)\n    return C.dot(A).dot(C.T)\n\n\ndef dct(A):\n    \"\"\"\n    params: A matrix Nx1\n    output: compute dct 1D of the matrix A\n    \"\"\"\n    N = A.shape[0]\n    C = np.zeros(N, dtype=np.float64)\n\n    for k in range(0, N):\n        a_k = np.sqrt(1.0 / N) if k == 0 else np.sqrt(2.0 / N)\n\n        sum = 0\n        for j in range(N):\n            sum = sum + A[j] * np.cos(k * np.pi * (2 * j + 1) / (2.0 * N))\n\n        C[k] = a_k * sum\n    return C\n\ndef dct2(A):\n    \"\"\"\n    params: A matrix NxM\n    output: compute dct 2D of the matrix A\n    \"\"\"\n    N, M = A.shape\n    C = np.zeros((N, M), dtype=np.float64)\n\n    for i in range(N):\n        C[i] = dct(A[i])\n\n    for j in range(M):\n        C[:, j] = dct(C[:, j])\n    return C\n", "meta": {"hexsha": "b461b9bf12b8cc5481311357e856e2c0c1bde055", "size": 1346, "ext": "py", "lang": "Python", "max_stars_repo_path": "dct/dct.py", "max_stars_repo_name": "saiteki-kai/dct-compression", "max_stars_repo_head_hexsha": "77699b6aba30ddb5d9de144d36417e636ff178ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dct/dct.py", "max_issues_repo_name": "saiteki-kai/dct-compression", "max_issues_repo_head_hexsha": "77699b6aba30ddb5d9de144d36417e636ff178ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dct/dct.py", "max_forks_repo_name": "saiteki-kai/dct-compression", "max_forks_repo_head_hexsha": "77699b6aba30ddb5d9de144d36417e636ff178ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7076923077, "max_line_length": 84, "alphanum_fraction": 0.4933135215, "include": true, "reason": "import numpy", "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551535992068, "lm_q2_score": 0.8976952845805988, "lm_q1q2_score": 0.8661459216892973}}
{"text": "####################################################################################################################################\n##  \n##  Description:\n##      +   Return the natural logarithm of an ndim-dimensional Multivariate Normal (MVN) \n##          probability density function (PDF) with the Mean and Covariance Matrix as defined below.\n##          Reference: https://en.wikipedia.org/wiki/Multivariate_normal_distribution\n##  Input:\n##      +   point:      The input 64-bit real-valued vector of length ndim, \n##                      at which the natural logarithm of objective function is computed.\n##  Output:\n##      +   logFunc:    A 64-bit real scalar number representing the natural logarithm of the objective function.\n##  Author:\n##      +   Computational Data Science Lab, Monday 9:03 AM, May 16 2016, ICES, UT Austin\n##  Visit:\n##      +   https://www.cdslab.org/paramonte\n##\n####################################################################################################################################\n\nimport numpy as np\n\n# The number of dimensions of the domain of the objective function.\n\nNDIM = 4\n\n# This is the mean of the MVN distribution.\n\nMEAN =  [0.0,0.0,0.0,0.0]\n\n# This is the covariance matrix of the MVN distribution.\n\nCOVMAT =    [ [1.0,0.5,0.5,0.5]\n            , [0.5,1.0,0.5,0.5]\n            , [0.5,0.5,1.0,0.5]\n            , [0.5,0.5,0.5,1.0]\n            ]\n\n# This is the inverse of the covariance matrix of the MVN distribution.\n\nINVCOV = np.linalg.inv(COVMAT)\n\n# This is the log of the coefficient used in the definition of the MVN.\n\nMVN_COEF = NDIM * np.log( 1. / np.sqrt(2.*np.pi) ) + np.log( np.sqrt(np.linalg.det(INVCOV)) )\n\ndef getLogFunc(point):\n    \"\"\"\n    Return the natural logarithm of an NDIM-dimensional Multivariate Normal distribution\n    with the mean and covariance matrix as given in the above.\n    Reference: https://en.wikipedia.org/wiki/Multivariate_normal_distribution\n    \"\"\"\n    normedPoint = MEAN - point\n    return MVN_COEF - 0.5 * ( np.dot(normedPoint,np.matmul(INVCOV,normedPoint)) )\n", "meta": {"hexsha": "444ea7a94a6f105f92473249abf8c819b666adfc", "size": 2058, "ext": "py", "lang": "Python", "max_stars_repo_path": "example/mvn/Python/logfunc.py", "max_stars_repo_name": "ekourkchi/paramonte", "max_stars_repo_head_hexsha": "15f8ea27cb514078a94d9c4ee4b60e4f45826f17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 158, "max_stars_repo_stars_event_min_datetime": "2020-01-13T06:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T03:12:03.000Z", "max_issues_repo_path": "example/mvn/Python/logfunc.py", "max_issues_repo_name": "ekourkchi/paramonte", "max_issues_repo_head_hexsha": "15f8ea27cb514078a94d9c4ee4b60e4f45826f17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-10-31T22:46:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T19:57:06.000Z", "max_forks_repo_path": "example/mvn/Python/logfunc.py", "max_forks_repo_name": "ekourkchi/paramonte", "max_forks_repo_head_hexsha": "15f8ea27cb514078a94d9c4ee4b60e4f45826f17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2020-07-04T23:45:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T06:52:07.000Z", "avg_line_length": 38.8301886792, "max_line_length": 132, "alphanum_fraction": 0.5719144801, "include": true, "reason": "import numpy", "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551495568569, "lm_q2_score": 0.8976952880018481, "lm_q1q2_score": 0.8661459213615088}}
{"text": "import numpy as np\nimport sympy as sp\nfrom sympy.core import S, Dummy\nfrom sympy.functions.special.gamma_functions import gamma\nfrom sympy.polys.orthopolys import (legendre_poly, laguerre_poly,\n                                    hermite_poly, jacobi_poly)\nfrom sympy.polys.rootoftools import RootOf\n\n\ndef gauss_jacobi(n, alpha, beta, n_digits):\n    r\"\"\"\n    Computes the Gauss-Jacobi quadrature [1]_ points and weights.\n\n    The Gauss-Jacobi quadrature of the first kind approximates the integral:\n\n    .. math::\n        \\int_{-1}^1 (1-x)^\\alpha (1+x)^\\beta f(x)\\,dx \\approx\n            \\sum_{i=1}^n w_i f(x_i)\n\n    The nodes `x_i` of an order `n` quadrature rule are the roots of\n    `P^{(\\alpha,\\beta)}_n` and the weights `w_i` are given by:\n\n    .. math::\n        w_i = -\\frac{2n+\\alpha+\\beta+2}{n+\\alpha+\\beta+1}\n              \\frac{\\Gamma(n+\\alpha+1)\\Gamma(n+\\beta+1)}\n              {\\Gamma(n+\\alpha+\\beta+1)(n+1)!}\n              \\frac{2^{\\alpha+\\beta}}{P'_n(x_i)\n              P^{(\\alpha,\\beta)}_{n+1}(x_i)}\n\n    Parameters\n    ==========\n\n    n : the order of quadrature\n\n    alpha : the first parameter of the Jacobi Polynomial, `\\alpha > -1`\n\n    beta : the second parameter of the Jacobi Polynomial, `\\beta > -1`\n\n    n_digits : number of significant digits of the points and weights to return\n\n    Returns\n    =======\n\n    (x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.\n             The points `x_i` and weights `w_i` are returned as ``(x, w)``\n             tuple of lists.\n\n    Examples\n    ========\n\n    >>> from sympy import S\n    >>> from sympy.integrals.quadrature import gauss_jacobi\n    >>> x, w = gauss_jacobi(3, S.Half, -S.Half, 5)\n    >>> x\n    [-0.90097, -0.22252, 0.62349]\n    >>> w\n    [1.7063, 1.0973, 0.33795]\n\n    >>> x, w = gauss_jacobi(6, 1, 1, 5)\n    >>> x\n    [-0.87174, -0.5917, -0.2093, 0.2093, 0.5917, 0.87174]\n    >>> w\n    [0.050584, 0.22169, 0.39439, 0.39439, 0.22169, 0.050584]\n\n    See Also\n    ========\n\n    gauss_legendre, gauss_laguerre, gauss_hermite, gauss_gen_laguerre, gauss_chebyshev_t, gauss_chebyshev_u, gauss_lobatto\n\n    References\n    ==========\n\n    .. [1] https://en.wikipedia.org/wiki/Gauss%E2%80%93Jacobi_quadrature\n    .. [2] http://people.sc.fsu.edu/~jburkardt/cpp_src/jacobi_rule/jacobi_rule.html\n    .. [3] http://people.sc.fsu.edu/~jburkardt/cpp_src/gegenbauer_rule/gegenbauer_rule.html\n    \"\"\"\n    x = Dummy(\"x\")\n    p = jacobi_poly(n, alpha, beta, x, polys=True)\n    pd = p.diff(x)\n    pn = jacobi_poly(n+1, alpha, beta, x, polys=True)\n    xi = []\n    wi = []\n    for r in p.real_roots():\n        if isinstance(r, RootOf):\n            r = r.eval_rational(S(1)/10**(n_digits+2))\n        xi.append(r.n(n_digits))\n        wi.append((\n            - (2*n+alpha+beta+2) / (n+alpha+beta+S.One) *\n            (gamma(n+alpha+1)*gamma(n+beta+1)) /\n            (gamma(n+alpha+beta+S.One)*gamma(n+2)) *\n            2**(alpha+beta) / (pd.subs(x, r) * pn.subs(x, r))).n(n_digits))\n    return xi, wi\n\n\nalpha = 0\nbeta  = 0\ndigits = 36\nnpoints = list(range(1,17))\n\nfor n in npoints:\n    xi, wi = gauss_jacobi(n, alpha, beta, digits)\n    \n    print('\\nN = %3d'%(n))\n    for i in range(0,n):\n        print('%3d %40.36f %40.36f'%(i+1,xi[i],wi[i]))\n    \n    \n    \n    \n    \n", "meta": {"hexsha": "ce47db0e2ea8298ff0c2cbe26dd1a4a896476136", "size": 3242, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/gauss_jacoby.py", "max_stars_repo_name": "BryanFlynt/PolyCalc", "max_stars_repo_head_hexsha": "9fe70f83647c6f5683e6e8f5cfee23b417974ebb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/gauss_jacoby.py", "max_issues_repo_name": "BryanFlynt/PolyCalc", "max_issues_repo_head_hexsha": "9fe70f83647c6f5683e6e8f5cfee23b417974ebb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/gauss_jacoby.py", "max_forks_repo_name": "BryanFlynt/PolyCalc", "max_forks_repo_head_hexsha": "9fe70f83647c6f5683e6e8f5cfee23b417974ebb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2072072072, "max_line_length": 122, "alphanum_fraction": 0.5740283775, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 1086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454896, "lm_q2_score": 0.9099070090919014, "lm_q1q2_score": 0.866107028627848}}
{"text": "import numpy as np\nimport cv2 as cv\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import Normalize\n\n\ndef hist_equ(raw_img=None, file_name=None):\n    \"\"\"\n    Implement the histogram equalization to the input images Q3_1_1.tif and Q3_1_2.tif\n    \"\"\"\n\n    if raw_img is None:\n        raw_img = cv.imread(file_name, cv.IMREAD_GRAYSCALE)\n\n    norm = Normalize(vmin=0, vmax=255)\n    L = 2 ** 8\n    bins = range(L + 1)\n    # row, col = raw_img.shape\n\n    # input_hist = np.zeros(L, int)\n    # for i in raw_img.flat:\n    #     input_hist[i] += 1\n\n    # input_hist = histogram(raw_img)\n    input_hist, _ = np.histogram(raw_img.flat, bins=bins, density=True)\n    # print(file_name, 'raw', np.count_nonzero(input_hist))\n\n    # s = np.zeros(L, int)\n    # for k in range(L):\n    #     s[k] = (L - 1) * sum(input_hist[:k + 1])\n\n    s = np.array([(L - 1) * sum(input_hist[:k + 1]) for k in range(L)])\n\n    out_img = np.array([s[r] for r in raw_img], int).reshape(raw_img.shape)\n    # output_hist = histogram(out_img)\n    output_hist, _ = np.histogram(out_img.flat, bins=bins, density=True)\n    # print(file_name, 'equalized', np.count_nonzero(output_hist))\n\n    # %% plots\n    '''\n    plt.subplot(121)\n    plt.imshow(raw_img, cmap='gray', norm=norm)\n    plt.title(\"Raw \" + file_name)\n\n    plt.subplot(122)\n    plt.imshow(out_img, cmap='gray', norm=norm)\n    plt.title(\"Equalized \" + file_name)\n    # plt.savefig(file_name + \"_comparison.png\")\n    plt.show()\n\n    plt.title(\"Histogram of \" + file_name)\n    plt.bar(range(L), input_hist)\n    plt.bar(range(L), output_hist)\n    plt.legend(('raw image', 'equalized image'))\n    # plt.savefig(file_name + \"_histogram.png\")\n    plt.show()\n\n    plt.plot(range(L), s)\n    plt.title(\"Histogram equalization transformation for \" + file_name)\n    plt.xlabel('$r_k$')\n    plt.ylabel('$s_k$')\n    plt.show()\n    '''\n\n    return out_img, output_hist, input_hist, s\n\n\n# %%\n\n*_, trans_1 = hist_equ(file_name=\"Q3_1_1.tif\")\n*_, trans_2 = hist_equ(file_name=\"Q3_1_2.tif\")\n\nplt.plot(range(2 ** 8), trans_1)\nplt.plot(range(2 ** 8), trans_2)\nplt.title(\"Histogram equalization transformation\")\nplt.xlabel('$r_k$')\nplt.ylabel('$s_k$')\nplt.legend(('Q3_1_1.tif', 'Q3_1_2.tif'))\n# plt.savefig(\"Q3_1_trans.png\")\nplt.show()\n", "meta": {"hexsha": "faa35b07da13936d52f289e4b7d4fb6fc4b25bc5", "size": 2244, "ext": "py", "lang": "Python", "max_stars_repo_path": "lab3/hist_equ.py", "max_stars_repo_name": "kommunium/dip-lab", "max_stars_repo_head_hexsha": "2c8e08a994fb34b87da55da48a7b72b7c13d9c81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab3/hist_equ.py", "max_issues_repo_name": "kommunium/dip-lab", "max_issues_repo_head_hexsha": "2c8e08a994fb34b87da55da48a7b72b7c13d9c81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab3/hist_equ.py", "max_forks_repo_name": "kommunium/dip-lab", "max_forks_repo_head_hexsha": "2c8e08a994fb34b87da55da48a7b72b7c13d9c81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7037037037, "max_line_length": 86, "alphanum_fraction": 0.6399286988, "include": true, "reason": "import numpy", "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.909906999319571, "lm_q1q2_score": 0.8661070143559008}}
{"text": "import math\nimport numpy as np\nimport scipy.stats\n\n# Confidence interval (CI) for mean\n \ndef ci_mean(alpha, sample=[], sample_mean=False, n=False, true_sigma=False, sample_sigma=False, verbose=False):\n    # when there is a vector of values i.e. sample itself\n    if len(sample) != 0:\n        sample = np.array(sample)\n        n = len(sample)\n        sample_mean = np.mean(sample)\n        sample_sigma = np.std(sample)\n    # known true (theoretical) sigma\n    if true_sigma != False:\n        z = scipy.stats.norm.ppf(1 - alpha)\n        lower_bound = sample_mean - z * true_sigma / math.sqrt(n)\n        upper_bound = sample_mean + z * true_sigma / math.sqrt(n)\n        margin_error = z * true_sigma / math.sqrt(n)\n        if verbose == True:\n            print(f'{round((1-alpha) * 100)}% Confidence Interval (CI) for mean is between {round(lower_bound, 2)} and\\\n    {round(upper_bound, 2)}')\n            print(f'Z statistics with n={n} and alpha={alpha} is equal to {round(z, 2)}')\n            print(f'CI width is {round(upper_bound - lower_bound, 2)}')\n            print(f'Margin of Error is {round(margin_error, 2)}')\n            print(f'Point estimate {round((lower_bound + upper_bound) / 2, 2)}')\n        return lower_bound, upper_bound\n    # unknown true sigma but known sig\n    elif sample_sigma != False:\n        t = scipy.stats.t.ppf(1 - alpha / 2, n - 1)\n        lower_bound = sample_mean - t * sample_sigma / math.sqrt(n)\n        upper_bound = sample_mean + t * sample_sigma / math.sqrt(n)\n        margin_error = t * sample_sigma / math.sqrt(n)\n        if verbose == True:\n            print(f'{round((1-alpha) * 100)}% Confidence Interval for mean is between {round(lower_bound, 2)} and\\\n    {round(upper_bound, 2)}')\n            print(f't (student) statistics with n={n} and alpha={alpha} is equal to {round(t, 2)}')\n            print(f'CI width is {round(upper_bound - lower_bound, 2)}')\n            print(f'Margin of Error is {round(margin_error, 2)}')\n            print(f'Point estimate {round((lower_bound + upper_bound) / 2, 2)}')\n        return lower_bound, upper_bound\n    else:\n        print('Some data is missing. Check input parameters')\n\n# CI for variance\n\ndef ci_variance(n, alpha, sample=[], sample_var=False, true_mean=False, verbose=False):\n    # when there is a vector of values i.e. sample itself\n    if len(sample) != 0:\n        sample = np.array(sample)\n        n = len(sample)\n        sample_var = np.var(sample)\n\n    # known true variance and there is a sample itself\n    if (true_mean != False) and (len(sample) != 0):\n        chi_squared_right = scipy.stats.chi2.ppf(1 - alpha / 2, n) # bigger number\n        chi_squared_left = scipy.stats.chi2.ppf(alpha / 2, n) # smaller number\n        numerator = sum((np.array(sample) - true_mean) ** 2)\n        lower_bound = numerator / chi_squared_right \n        upper_bound = numerator / chi_squared_left\n        if verbose == True:\n            print(f'{round((1-alpha) * 100)}% Confidence Interval (CI) for variance is between {round(lower_bound, 2)} and\\\n    {round(upper_bound, 2)}')\n            print(f'Chi-square statistics with n={n} and alpha/2={alpha / 2} is equal to {round(chi_squared_right, 2)}')\n            print(f'Chi-square statistics with n={n} and 1-alpha/2={1 - alpha / 2} is equal to {round(chi_squared_left, 2)}')\n            print(f'CI width is {round(upper_bound - lower_bound, 2)}')\n            print(f'Point estimate {round((upper_bound + lower_bound) / 2, 2)}')\n        return lower_bound, upper_bound \n    # unknown true variance but known sample variance\n    elif (sample_var != False) and (true_mean == False):\n        chi_squared_right = scipy.stats.chi2.ppf(1 - alpha / 2, n - 1) # bigger number\n        chi_squared_left = scipy.stats.chi2.ppf(alpha / 2, n - 1) # smaller number\n        lower_bound = (n - 1) * sample_var / chi_squared_right\n        upper_bound = (n - 1) * sample_var / chi_squared_left\n        if verbose == True:\n            print(f'{round((1-alpha) * 100)}% Confidence Interval (CI) for variance is between {round(lower_bound, 2)} and\\\n    {round(upper_bound, 2)}')\n            print(f'Chi-square statistics with n={n} and alpha/2={alpha / 2} is equal to {round(chi_squared_right, 2)}')\n            print(f'Chi-square statistics with n={n} and 1-alpha/2={1 - alpha / 2} is equal to {round(chi_squared_left, 2)}')\n            print(f'CI width is {round(upper_bound - lower_bound, 2)}')\n            print(f'Point estimate {round((upper_bound + lower_bound) / 2, 2)}')\n        return (n - 1) * sample_var / chi_squared_right, (n - 1) * sample_var / chi_squared_left    \n    else:\n        print('Some data is missing. Check input parameters')\n\n# CI for probability (share)\n\ndef ci_probs(alpha, sample=[], p_hat=False, n=False, verbose=False):\n    # when there is a vector of values i.e. sample itself\n    if len(sample) != 0:\n        sample = np.array(sample)\n        n = len(sample)\n        p_hat = np.mean(sample)\n    \n    if (p_hat != False) and (n != False):\n        z = scipy.stats.norm.ppf(1 - alpha / 2)\n        lower_bound = p_hat - z * math.sqrt(p_hat * (1 - p_hat) / n)\n        upper_bound = p_hat + z * math.sqrt(p_hat * (1 - p_hat) / n)\n        margin_error = z * math.sqrt(p_hat * (1 - p_hat) / n)\n        if verbose == True:\n            print(f'{round((1-alpha) * 100, 1)}% Confidence Interval (CI) for mean is between {round(lower_bound, 2)} and\\\n        {round(upper_bound, 2)}')\n            print(f'Z statistics with n={n} and 1 - alpha/2 ={1 - alpha / 2} is equal to {round(z, 2)}')\n            print(f'CI width is {round(upper_bound - lower_bound, 2)}')\n            print(f'Margin of Error is {round(margin_error, 2)}')\n            print(f'Point estimate {round((lower_bound + upper_bound) / 2, 2)}')\n        return lower_bound, upper_bound\n    else:\n        print('Some data is missing. Check input parameters')\n\n\n# CI for means difference\n\ndef ci_mean_dif(alpha, sample_x=[], sample_y=[], sample_mean_x=False, sample_mean_y=False, n_x=False, n_y=False,\n                true_var_both=False, true_var_x=False, true_var_y=False, \n               sample_var_x=False, sample_var_y=False, verbose=False):\n    \n    if (len(sample_x) != 0) and (len(sample_y) != 0):\n        sample_x = np.array(sample_x)\n        sample_y = np.array(sample_y)\n        sample_mean_x = np.mean(sample_x)\n        sample_mean_y = np.mean(sample_y)\n        n_x = len(sample_x)\n        n_y = len(sample_y)\n        sample_var_x = np.var(sample_x)\n        sample_var_y = np.var(sample_y)\n    \n    # both true variances are known and equal\n    if true_var_both !=False:\n        z = scipy.stats.norm.ppf(1 - alpha / 2)\n        print('both true variances are known and equal')\n        lower_bound = sample_mean_x - sample_mean_y - z * true_var_both / math.sqrt(n_x + n_y)\n        upper_bound = sample_mean_x - sample_mean_y + z * true_var_both / math.sqrt(n_x + n_y)\n        margin_error = z * true_var_both / math.sqrt(n_x + n_y)\n        if verbose == True:\n            print(f'{round((1-alpha) * 100, 1)}% Confidence Interval (CI) for difference of means is between\\\n    {round(lower_bound, 2)} and {round(upper_bound, 2)}')\n            print(f'Z statistics with 1 - alpha/2 ={1 - alpha / 2} is equal to {round(z, 2)}')\n            print(f'CI width is {round(upper_bound - lower_bound, 2)}')\n            print(f'Margin of Error is {round(margin_error, 2)}')\n            print(f'Point estimate {round((lower_bound + upper_bound) / 2, 2)}')\n        return lower_bound, upper_bound\n    \n    # both true variances are known and not equal\n    elif (true_var_x != False) and (true_var_y != False):\n        z = scipy.stats.norm.ppf(1 - alpha / 2)\n        print('both true variances are known and not equal')\n        lower_bound = sample_mean_x - sample_mean_y - z * math.sqrt(true_var_x/n_x + true_var_y/n_y)\n        upper_bound = sample_mean_x - sample_mean_y + z * math.sqrt(true_var_x/n_x + true_var_y/n_y)\n        margin_error = z * math.sqrt(true_var_x/n_x + true_var_y/n_y)\n        if verbose == True:\n            print(f'{round((1-alpha) * 100, 1)}% Confidence Interval (CI) for difference of means is between\\\n    {round(lower_bound, 2)} and {round(upper_bound, 2)}')\n            print(f'Z statistics with 1 - alpha/2 ={1 - alpha / 2} is equal to {round(z, 2)}')\n            print(f'CI width is {round(upper_bound - lower_bound, 2)}')\n            print(f'Margin of Error is {round(margin_error, 2)}')\n            print(f'Point estimate {round((lower_bound + upper_bound) / 2, 2)}')\n        \n        return lower_bound, upper_bound    \n    # both variances are unknown but equal   \n    elif (sample_var_x == sample_var_y) and (sample_var_x != False):\n        t = scipy.stats.t.ppf(1 - alpha / 2, n_x + n_y - 2)\n        print('both variances are unknown but equal')\n        lower_bound = sample_mean_x - sample_mean_y - t * (math.sqrt((n_x - 1)*sample_var_x + (n_y - 1)*sample_var_y)) /\\\n    math.sqrt((n_x * n_y * (n_x + n_y - 2)) / (n_x + n_y))\n        upper_bound = sample_mean_x - sample_mean_y + t * (math.sqrt((n_x - 1)*sample_var_x + (n_y - 1)*sample_var_y)) /\\\n    math.sqrt((n_x * n_y * (n_x + n_y - 2)) / (n_x + n_y))\n        margin_error = t * (math.sqrt((n_x - 1)*sample_var_x + (n_y - 1)*sample_var_y)) /\\\n    math.sqrt((n_x * n_y * (n_x + n_y - 2)) / (n_x + n_y))\n\n        if verbose == True:\n            print(f'{round((1-alpha) * 100, 1)}% Confidence Interval (CI) for difference of means is between\\\n    {round(lower_bound, 2)} and {round(upper_bound, 2)}')\n            print(f't statistics with 1 - alpha/2 ={1 - alpha / 2} is equal to {round(t, 2)}')\n            print(f'CI width is {round(upper_bound - lower_bound, 2)}')\n            print(f'Margin of Error is {round(margin_error, 2)}')\n            print(f'Point estimate {round((lower_bound + upper_bound) / 2, 2)}')\n\n        return sample_mean_x - sample_mean_y - t * (math.sqrt((n_x - 1)*sample_var_x + (n_y - 1)*sample_var_y)) /\\\n    math.sqrt((n_x * n_y * (n_x + n_y - 2)) / (n_x + n_y)),\\\n    sample_mean_x - sample_mean_y + t * (math.sqrt((n_x - 1)*sample_var_x + (n_y - 1)*sample_var_y)) /\\\n    math.sqrt((n_x * n_y * (n_x + n_y - 2)) / (n_x + n_y))\n    \n    # both variances are unknown and unequal\n    elif (sample_var_x != False) and (sample_var_y != False) and (sample_var_x != sample_var_y):\n        t = scipy.stats.t.ppf(1 - alpha / 2, n_x + n_y - 2)\n        print('both variances are unknown and unequal')\n        upper_bound = sample_mean_x - sample_mean_y - t * math.sqrt(sample_var_x/n_x + sample_var_x/n_y)\n        lower_bound = sample_mean_x - sample_mean_y + t * math.sqrt(sample_var_x/n_x + sample_var_x/n_y)\n        margin_error = t * math.sqrt(sample_var_x/n_x + sample_var_x/n_y)\n        \n        if verbose == True:\n            print(f'{round((1-alpha) * 100, 1)}% Confidence Interval (CI) for difference of means is between\\\n    {round(lower_bound, 2)} and {round(upper_bound, 2)}')\n            print(f't statistics with 1 - alpha/2 ={1 - alpha / 2} is equal to {round(t, 2)}')\n            print(f'CI width is {round(upper_bound - lower_bound, 2)}')\n            print(f'Margin of Error is {round(margin_error, 2)}')\n            print(f'Point estimate {round((lower_bound + upper_bound) / 2, 2)}')\n        return sample_mean_x - sample_mean_y - t * math.sqrt(sample_var_x/n_x + sample_var_x/n_y),\\\n    sample_mean_x - sample_mean_y + t * math.sqrt(sample_var_x/n_x + sample_var_x/n_y)\n    else:\n        print('Some data is missing. Check input parameters')\n\n# CI for probabilities difference\n\ndef ci_probs_dif(alpha, sample_x=[], sample_y=[], p_hat_x=False, p_hat_y=False, n_x=False, n_y=False,\nverbose=False):\n    if (len(sample_x) != 0) and (len(sample_y) != 0):\n        sample_x = np.array(sample_x)\n        sample_y = np.array(sample_y)\n        p_hat_x = np.mean(sample_x)\n        p_hat_y = np.mean(sample_y)\n        n_x = len(sample_x)\n        n_y = len(sample_y)\n        \n        \n    if (p_hat_x != False) and (p_hat_y != False) and (n_x != False) and (n_y != False):\n        p_hat = (p_hat_x * n_x + p_hat_y * n_y) / (n_x + n_y)\n        z = scipy.stats.norm.ppf(1 - alpha / 2)\n        lower_bound = p_hat_x - p_hat_y - z * math.sqrt(p_hat * (1 - p_hat) * (1/n_x + 1/n_y))\n        upper_bound = p_hat_x - p_hat_y + z * math.sqrt(p_hat * (1 - p_hat) * (1/n_x + 1/n_y))\n        margin_error = z * math.sqrt(p_hat * (1 - p_hat) * (1/n_x + 1/n_y))\n        if verbose == True:\n            print(f'{round((1-alpha) * 100, 1)}% Confidence Interval (CI) for difference of probabilities is between\\\n    {round(lower_bound, 2)} and {round(upper_bound, 2)}')\n            print(f'Z statistics with 1 - alpha/2 ={1 - alpha / 2} is equal to {round(z, 2)}')\n            print(f'CI width is {round(upper_bound - lower_bound, 2)}')\n            print(f'Margin of Error is {round(margin_error, 2)}')\n            print(f'Point estimate {round((lower_bound + upper_bound) / 2, 2)}')\n        return lower_bound, upper_bound\n    \n    else:\n        print('Some data is missing. Check input parameters')\n\n# CI for ratio of variances\n\ndef ci_vars_ratio(alpha, sample_x=[], sample_y=[], sample_var_x=False, sample_var_y=False, verbose=False):\n    if (len(sample_x) != 0) and (len(sample_y) != 0):\n        sample_x = np.array(sample_x)\n        sample_y = np.array(sample_y)\n        sample_var_x = np.var(sample_x)\n        sample_var_y = np.var(sample_y)\n        n_x = len(sample_x)\n        n_y = len(sample_y)\n\n    if (sample_var_x != False) and (sample_var_y != False):\n        F_left = scipy.stats.f.ppf(alpha / 2, n_x - 1, n_y - 1) # smaller number\n        F_right = scipy.stats.f.ppf(1 - alpha / 2, n_x - 1, n_y - 1) # bigger number\n        lower_bound = (1 / F_left) * (sample_var_x / sample_var_y) \n        upper_bound = (1 / F_right) * (sample_var_x / sample_var_y)\n        if verbose == True:\n            print(f'{round((1-alpha) * 100, 1)}% Confidence Interval (CI) for ratio of variances is between\\\n    {round(lower_bound, 2)} and {round(upper_bound, 2)}')\n            print(f'F statistics with alpha/2 ={alpha / 2} is equal to {round(F_left, 2)}')\n            print(f'F statistics with 1 - alpha/2 ={1 - alpha / 2} is equal to {round(F_right, 2)}')\n            print(f'CI width is {round(upper_bound - lower_bound, 2)}')\n            print(f'Point estimate {round((lower_bound + upper_bound) / 2, 2)}')\n        return lower_bound, upper_bound\n    else:\n        print('Some data is missing. Check input parameters')\n\n\n\n", "meta": {"hexsha": "54e952fe1768943d2ad29a5d37eb9910855cb51a", "size": 14407, "ext": "py", "lang": "Python", "max_stars_repo_path": "andrew_confidence_intervals/__init__.py", "max_stars_repo_name": "Cliefspring/andrew_confidence_intervals", "max_stars_repo_head_hexsha": "e445dafc66d46f5fd834a69a569a6f4581ee3475", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "andrew_confidence_intervals/__init__.py", "max_issues_repo_name": "Cliefspring/andrew_confidence_intervals", "max_issues_repo_head_hexsha": "e445dafc66d46f5fd834a69a569a6f4581ee3475", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "andrew_confidence_intervals/__init__.py", "max_forks_repo_name": "Cliefspring/andrew_confidence_intervals", "max_forks_repo_head_hexsha": "e445dafc66d46f5fd834a69a569a6f4581ee3475", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.571969697, "max_line_length": 125, "alphanum_fraction": 0.6140764906, "include": true, "reason": "import numpy,import scipy", "num_tokens": 4106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9796676419082933, "lm_q2_score": 0.884039278690883, "lm_q1q2_score": 0.8660646755094058}}
{"text": "import math\n\nfrom pyrr import Quaternion, Matrix44, Vector3\n\nimport numpy as np\n\nprint(\"#########################################\")\n\n#np.set_printoptions(precision=3)\nnp.set_printoptions(formatter={'float': '{: 8.3f}'.format})\n#np.set_printoptions(suppress=True)\n\nlocation_v = Vector3([5.0, 6.0, 7.0])\nlocation_m = Matrix44.from_translation(location_v)\n\nprint(\"Location Matrix\")\n\nprint(\"\")\n\n#print(location_m)\ntransform_flat = location_m.flatten()\t\ntransform_array = np.array(transform_flat, np.float32)\nprint(transform_array)\n\nprint(\"\")\n\nprint(\"#########################################\")\n\ndeg = -10\nrad = (deg * np.pi / 180)\nq_rot = Quaternion.from_x_rotation(rad)\n\nq_array = np.array(q_rot, np.float32)\n\nrotation_m = Matrix44(q_rot)\n\nprint(\"Rotation Matrix - X\")\n\nprint(\"\")\n\nprint(q_array)\n\n#print(rotation_m)\ntransform_flat = rotation_m.flatten()\t\ntransform_array = np.array(transform_flat, np.float32)\nprint(transform_array)\n\nprint(\"\")\n\nprint(\"#########################################\")\n\ndeg = -10\nrad = (deg * np.pi / 180)\nq_rot = Quaternion.from_y_rotation(rad)\n\nq_array = np.array(q_rot, np.float32)\n\nrotation_m = Matrix44(q_rot)\n\nprint(\"Rotation Matrix - Y\")\n\nprint(\"\")\n\nprint(q_array)\n\n#print(rotation_m)\ntransform_flat = rotation_m.flatten()\t\ntransform_array = np.array(transform_flat, np.float32)\nprint(transform_array)\n\nprint(\"\")\n\nprint(\"#########################################\")\n\ndeg = -10\nrad = (deg * np.pi / 180)\nq_rot = Quaternion.from_z_rotation(rad)\n\nq_array = np.array(q_rot, np.float32)\n\nrotation_m = Matrix44(q_rot)\n\nprint(\"Rotation Matrix - Z\")\n\nprint(\"\")\n\nprint(q_array)\n\n#print(rotation_m)\ntransform_flat = rotation_m.flatten()\t\ntransform_array = np.array(transform_flat, np.float32)\nprint(transform_array)\n\nprint(\"\")\n\nprint(\"#########################################\")\n\ndisplacement_v = Vector3([10.0, 0.0, 0])\ndisplacement_m = Matrix44.from_translation(displacement_v)\n\nprint(\"Translate Matrix\")\n\nprint(\"\")\n\n#print(displacement_m)\ntransform_flat = displacement_m.flatten()\t\ntransform_array = np.array(transform_flat, np.float32)\nprint(transform_array)\n\nprint(\"\")\n\nprint(\"#########################################\")\n\nprint(\"Translate and Rotate\")\n\nprint(\"\")\n\nprint(\"\")\n\nmvMatrix_tmp = displacement_m*location_m\ntransform_flat = mvMatrix_tmp.flatten()\t\ntransform_array = np.array(transform_flat, np.float32)\nprint(transform_array)\n\nprint(\"\")\n\nmvMatrix = rotation_m*mvMatrix_tmp\ntransform_flat = mvMatrix.flatten()\t\ntransform_array = np.array(transform_flat, np.float32)\nprint(transform_array)\n\nprint(\"\")\n\nprint(\"#########################################\")\n\nprint(\"Rotate and Translate\")\n\nprint(\"\")\n\ntransform_flat = rotation_m.flatten()\t\ntransform_array = np.array(transform_flat, np.float32)\nprint(transform_array)\n\nprint(\"\")\n\ntransform_flat = location_m.flatten()\t\ntransform_array = np.array(transform_flat, np.float32)\nprint(transform_array)\n\nprint(\"\")\n\nmvMatrix_tmp = rotation_m*location_m\ntransform_flat = mvMatrix_tmp.flatten()\t\ntransform_array = np.array(transform_flat, np.float32)\nprint(transform_array)\n\nprint(\"\")\n\nmvMatrix = displacement_m*mvMatrix_tmp\ntransform_flat = mvMatrix.flatten()\t\ntransform_array = np.array(transform_flat, np.float32)\nprint(transform_array)\n\nprint(\"\")\n\n", "meta": {"hexsha": "f47f7824dab31970228d2f2edbe4e8947edd1c69", "size": 3220, "ext": "py", "lang": "Python", "max_stars_repo_path": "example_using_pyrr.py", "max_stars_repo_name": "anuprao/glmatrixpy", "max_stars_repo_head_hexsha": "fdf4e21db1e26d61fdb62b0d54fef0e1e480a4c3", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T01:13:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T01:13:44.000Z", "max_issues_repo_path": "example_using_pyrr.py", "max_issues_repo_name": "anuprao/glmatrixpy", "max_issues_repo_head_hexsha": "fdf4e21db1e26d61fdb62b0d54fef0e1e480a4c3", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example_using_pyrr.py", "max_forks_repo_name": "anuprao/glmatrixpy", "max_forks_repo_head_hexsha": "fdf4e21db1e26d61fdb62b0d54fef0e1e480a4c3", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3975903614, "max_line_length": 59, "alphanum_fraction": 0.6822981366, "include": true, "reason": "import numpy", "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305339244013, "lm_q2_score": 0.899121379297294, "lm_q1q2_score": 0.8660611662433766}}
{"text": "import numpy as np\n\ndef simpson(func, z, a, b, N = 100, rel_tol = 1e-6):\n    def trapecio(func, z, a, b, N = 100):\n        dx = (b-a)/(N)\n        f0 = func(z, a)\n        fN = func(z, b)\n\n        sum = (f0 + fN)/2\n        for i in range(1,N):\n            sum += func(z, a+i*dx)\n        sum *= dx\n        return sum\n\n    dif = np.infty #primera vez siempre entra al bucle\n    \n    while dif > rel_tol:\n        N *= 2\n        sum = trapecio(func, z, a, b, N)    \n        sum2 = trapecio(func, z, a, b, 2*N)\n        simp = (4*sum2 - sum)/3\n        dif = np.abs((simp - sum)/sum)\n    #se sale del ciclo porque dif < rel_tol\n    return simp\n\ndef Gamma_du(z, u): #integrando de la funcion gamma con u=e^(-x)\n    gdu = np.log(1/u)**(z-1)\n    return gdu\n\ndef Gamma(z, dx = 1e-6):\n    def pto_medio(func, z, a, b):\n        dx = b-a\n        med = (a+b)/2\n        rec = func(z, med)\n        return rec*dx\n    #nuevos extremos gracias al C.V.\n    a = 0\n    b = 1\n    g = simpson(Gamma_du, z, a + dx, b, rel_tol=dx)\n    g += pto_medio(Gamma_du, z, a, a + dx)\n    return g\n\nK = 4.495 #rut 20299495-4\nGAMMA_K_MEDIOS = Gamma(K/2, dx=1e-6)\n\ndef chi2(k, x):\n    res = 1/(np.exp2(k/2)*GAMMA_K_MEDIOS)*x**(k/2 - 1)*np.exp(-x/2) #definicion de chi^2(x)\n    return res\n\n#calculo de int_0^a chi^2(x) dx, x<0 no es parte del dominio de chi^2\ndef prob_chi2(k, a, rel_tol=1e-6):\n    prob = simpson(chi2, k, 0, a, rel_tol=rel_tol)\n    return prob\n\n#el problema prob_chi2(a) = 0.95 se puede reescribir como el problema del cero de una funcion\n# definiendo g(a) = prob_chi2(a) - 0.95 = 0\ndef biseccion(func, k, a, b, tol_abs=1e-6, lim=1e6): #lim permite evitar que el programa colapse \n    counter = 0\n    dif = np.abs(func(k, b)-func(k, a))\n    while  dif > tol_abs:\n        dif = np.abs(b-a)\n        p = (a+b)/2\n        if counter > lim: \n            print('limite de iteraciones excedido')\n            return p\n        fp = func(k, p)\n        fa = func(k, a)\n        prod = fp*fa\n        \n        if prod > 0:\n            a = p\n        elif prod < 0:\n            b = p\n        counter += 1\n    print('Número de pasos con bisección:', counter)\n    return p\n\ndef prob_menos_95(k, a, rel_tol=1e-10):\n    res = prob_chi2(k, a, rel_tol=rel_tol) - 0.95 #se quiere encontrar res = 0\n    return res\n\ndef newton(func, derivada, k, x_0, tol_abs = 1e-6):\n    #f(x) = \\int_0^x chi^2(t)dt - 0.95\n    #f'(x) = chi^2(x)\n    #x_{i+1} = x_i - f(x_i)/f'(x_i)\n    dif = np.infty\n    N = 0\n    while dif > tol_abs:\n        x_1 = x_0 - func(k, x_0)/derivada(k, x_0)\n        dif = np.abs(x_1-x_0)\n        x_0 = x_1\n        N+=1\n    print('Número de pasos con Newton:', N)\n    return x_1\n\ntol = 1e-5\na1 = biseccion(prob_menos_95, K, 0, 20, tol_abs=tol)\na2 = newton(prob_menos_95, chi2, K, 1, tol_abs=tol)\nprint('a por Biseccion:', a1)\nprint('a por Newton:', a2)\nprint('Diferencia:', np.abs(a1-a2))\na3 = newton(prob_menos_95, chi2, K, a1, tol_abs=1e-12)\nprint('a por Newton dando como punto inicial el de biseccion: ', a3)", "meta": {"hexsha": "26b8680b62607edbbbb25fe1409b3d14fbbb6ced", "size": 2971, "ext": "py", "lang": "Python", "max_stars_repo_path": "Codigo/prob.py", "max_stars_repo_name": "DiegoRomanCortes/01-tarea-DiegoRomanCortes", "max_stars_repo_head_hexsha": "f45066f093756d4e5b05f212b730ebe27bd99080", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Codigo/prob.py", "max_issues_repo_name": "DiegoRomanCortes/01-tarea-DiegoRomanCortes", "max_issues_repo_head_hexsha": "f45066f093756d4e5b05f212b730ebe27bd99080", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Codigo/prob.py", "max_forks_repo_name": "DiegoRomanCortes/01-tarea-DiegoRomanCortes", "max_forks_repo_head_hexsha": "f45066f093756d4e5b05f212b730ebe27bd99080", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8446601942, "max_line_length": 97, "alphanum_fraction": 0.5506563447, "include": true, "reason": "import numpy", "num_tokens": 1136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.9149009625340366, "lm_q1q2_score": 0.8660422088326856}}
{"text": "# encoding=utf8\r\n\r\n\"\"\"\r\nModule containing functions and methods for approximating the integral of functions\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\n\r\ndef trapezoidal_rule(f, a, b):\r\n    r\"\"\"\r\n    Approximates the integral of a function over the interval :math:`[a, b]` using the\r\n    Trapezoidal Rule.\r\n\r\n    Parameters\r\n    ----------\r\n    f : function\r\n        Given function to approximate derivative at supplied value of :math:`x`. Must be\r\n        a callable function with one parameter representing a single variable function.\r\n    a : int or float\r\n        The lower value of the integral to approximate\r\n    b : int or float\r\n        The upper lower of the integral to approximate\r\n\r\n    Returns\r\n    -------\r\n    float\r\n        The approximated value of the function integrated over the interval :math:`[a, b]`.\r\n\r\n    Notes\r\n    -----\r\n    The Trapezoidal Rule gives an approximation of the integral of a function over the interval\r\n    :math:`[a, b]`. The Trapezoidal Rule is defined as:\r\n\r\n    .. math::\r\n\r\n        \\int^a_b f(x) dx = \\frac{h}{2}[f(x_0) + f(x_1)] - \\frac{h^3}{12} f^{\\prime \\prime} (\\epsilon)\r\n\r\n    Where :math:`- \\frac{h^3}{12} f^{\\prime \\prime} (\\epsilon)` is the error term. The Trapezoidal Rule\r\n    approximates the integral :math:`\\int^a_b f(x) dx` by using the area of a trapezoid, hence its name.\r\n\r\n    Examples\r\n    --------\r\n    >>> def f(x): return x ** 4\r\n    >>> trapezoidal_rule(f, 0.5, 1)\r\n    .265625\r\n    >>> def f2(x): return 2 / (x - 4)\r\n    >>> trapezoidal_rule(f2, 0, 0.5)\r\n    -.2678571\r\n\r\n    References\r\n    ----------\r\n    Burden, R. L., & Faires, J. D. (2011). Numerical analysis (9th ed.).\r\n        Boston, MA: Brooks/Cole, Cengage Learning.\r\n\r\n    \"\"\"\r\n    if callable(f) is False:\r\n        raise TypeError('f must be a function with one parameter (variable)')\r\n    if isinstance(a, float) is False:\r\n        a = float(a)\r\n    if isinstance(b, float) is False:\r\n        b = float(b)\r\n\r\n    h = b - a\r\n\r\n    approx = (h / 2.) * (f(a) + f(b))\r\n\r\n    return approx\r\n\r\n\r\ndef composite_trapezoidal(f, a, b, n=6):\r\n    if callable(f) is False:\r\n        raise TypeError('f must be a function with one parameter (variable)')\r\n\r\n    h = (b - a) / n\r\n\r\n    xj = np.linspace(a, b, n + 1)\r\n\r\n    return (h / 2) * (f(a) + 2 * np.sum(f(xj[1:-1])) + f(b))\r\n\r\ndef simpsons_rule(f, a, b):\r\n    r\"\"\"\r\n    Approximates the integral of a function over the interval :math:`[a, b]` using Simpson's\r\n    Rule.\r\n\r\n    Parameters\r\n    ----------\r\n    f : function\r\n        Given function to approximate derivative at supplied value of :math:`x`. Must be\r\n        a callable function with one parameter representing a single variable function.\r\n    a : int or float\r\n        The lower value of the integral to approximate\r\n    b : int or float\r\n        The upper lower of the integral to approximate\r\n\r\n    Returns\r\n    -------\r\n    float\r\n        The approximated value of the function integrated over the interval :math:`[a, b]`.\r\n\r\n    Notes\r\n    -----\r\n    Simpson's rule is another method in numerical analysis for approximating the definite\r\n    integral of a function. The rule is defined as:\r\n\r\n    .. math::\r\n\r\n        \\int_{x_0}^{x_2} f(x) dx = \\frac{h}{3}[f(x_0) + 4f(x_1) + f(x_2)] - \\frac{h^5}{90}f^{(4)} (\\epsilon)\r\n\r\n    Where :math:`\\frac{h^5}{90}f^{(4)} (\\epsilon)` is the error term.\r\n\r\n    Examples\r\n    --------\r\n    >>> def f(x): return x ** 4\r\n    >>> simpsons_rule(f, 0.5, 1)\r\n    .1940104\r\n    >>> def f2(x): return 2 / (x - 4)\r\n    >>> simpsons_rule(f2, 0, 0.5)\r\n    -.2670635\r\n\r\n    References\r\n    ----------\r\n    Burden, R. L., & Faires, J. D. (2011). Numerical analysis (9th ed.).\r\n        Boston, MA: Brooks/Cole, Cengage Learning.\r\n\r\n    \"\"\"\r\n    if callable(f) is False:\r\n        raise TypeError('f must be a function with one parameter (variable)')\r\n\r\n    if isinstance(a, float) is False:\r\n        a = float(a)\r\n    if isinstance(b, float) is False:\r\n        b = float(b)\r\n\r\n    h = (b - a) / 2.\r\n    x0, x1, x2 = a, a + h, b\r\n\r\n    approx = (h / 3.) * (f(x0) + 4. * f(x1) + f(x2))\r\n\r\n    return approx\r\n\r\ndef composite_simpsons_rule(f, a, b, n=6):\r\n    if callable(f) is False:\r\n        raise TypeError('f must be a function with one parameter (variable)')\r\n\r\n    h = (b - a) / n\r\n\r\n    xj = np.linspace(a, b, n + 1)[1:-1]\r\n\r\n    return (h / 3) * (f(a) + 2 * np.sum(f(xj[1::2])) + 4 * np.sum(f(xj[0::2])) + f(b))\r\n", "meta": {"hexsha": "1e4a27602dbca4a90a2edf4a40be0ee5d9fceeff", "size": 4373, "ext": "py", "lang": "Python", "max_stars_repo_path": "venv/lib/python3.8/site-packages/mathpy/numerical/integration.py", "max_stars_repo_name": "sonakshibhalla/sonakshicode", "max_stars_repo_head_hexsha": "5242d1b128a6be3d184b5c64cf5f9448ccdc49be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "venv/lib/python3.8/site-packages/mathpy/numerical/integration.py", "max_issues_repo_name": "sonakshibhalla/sonakshicode", "max_issues_repo_head_hexsha": "5242d1b128a6be3d184b5c64cf5f9448ccdc49be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "venv/lib/python3.8/site-packages/mathpy/numerical/integration.py", "max_forks_repo_name": "sonakshibhalla/sonakshicode", "max_forks_repo_head_hexsha": "5242d1b128a6be3d184b5c64cf5f9448ccdc49be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7697368421, "max_line_length": 109, "alphanum_fraction": 0.5625428767, "include": true, "reason": "import numpy", "num_tokens": 1293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288128, "lm_q2_score": 0.9046505402422645, "lm_q1q2_score": 0.866001885561941}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom typing import List, Tuple, Callable, Union\n\nVector = List[float]\nFunction = Callable[[float], float]\nFunction2d = Callable[[float, float], float]\n\ndef newton_cotes(y: Vector=None, x: Vector=None, formula: str='trapz', h: float=1,\n                 f: Function=None, a: float=None, b: float=None, N: int=100) -> float:\n    \"\"\"\n    Newton-Cotes rules\n    ==================\n    In numerical analysis, the Newton-Cotes formulas, also called the Newton-Cotes quadrature\n    rules or simply Newton-Cotes rules, are a group of formulas for numerical integration\n    (also called quadrature) based on evaluating the integrand at equally spaced points.\n    They are named after Isaac Newton and Roger Cotes.\n\n    Newton-Cotes formulas can be useful if the value of the integrand at equally spaced points is given.\n    If it is possible to change the points at which the integrand is evaluated,\n    then other methods such as Gaussian quadrature and Clenshaw-Curtis quadrature are probably more suitable.\n    `n` is the grade of the polynomial interpolation, also nodes - 1 \n\n    Parameters\n    ----------\n    y : Vector\n        Input array to integrate\n    x : Vector, optional\n        The sample points corresponding to the y values. If x is None,\n        the sample points are assumed to be evenly spaced h apart, by default None\n    formula : str, optional\n        This defines which Newton-Cotes rule apply\n            trapz: trapezoidal rule, `n=1`\n            simpson: Simpson's rule, `n=2`\n            simpson3_8: Simpson's rule 3/8, `n=3`\n            boole : Boole's rule, `n=4`\n            weddle: Weddle's rule, `n=6`\n\n            -> For simplicity is recommended to use the functions `trapz`, `simpson` etc.\n            \n    h : float, optional\n        The spacing between sample points when x is None, by default 1\n    f : function, optional\n        funcion to integrate, if you don't define y/x\n    a : float, optional\n        Lower limit of the integral\n    b : float, optional\n        Upper limit of the integral\n    N : int, optional\n        Number of intervals, must be divisible by n, by default 100\n\n    Returns\n    -------\n    float\n        Definite integral\n    \n    Examples\n    --------\n    >>> N, a, b = 12, 1, 4\n    >>> x = np.linspace(a, b, N+1)\n    >>> y = np.sin(x)\n    >>> print(newton_cotes(y,x,'simpson'))\n    1.193972031074762\n    >>> def fun(x): return np.sin(x)\n    >>> print(newton_cotes(f=fun, a=a, b=b, N=N, formula='simpson3_8'))\n    1.1940051049177476\n\n    \"\"\"\n    if   formula == 'trapz': \n        n, fs = 1, '(y[i] + y[i+1]) * d[i]/2'\n    elif formula == 'simpson':\n        n, fs = 2, '(y[n*i] + 4*y[n*i + 1] + y[n*i + 2]) * d[i]/3'\n    elif formula == 'simpson3_8': \n        n, fs = 3, '(y[n*i] + 3*y[n*i + 1] + 3*y[n*i + 2] + y[n*i + 3]) * 3*d[i]/8'\n    elif formula == 'boole': \n        n, fs = 4, '(7*y[n*i] + 32*y[n*i + 1] + 12*y[n*i + 2] + 32*y[n*i + 3] + 7*y[n*i + 4]) * 2*d[i]/45'\n    elif formula == 'weddle': \n        n, fs = 6, '(y[n*i] + 5*y[n*i + 1] + y[n*i + 2] + 6*y[n*i + 3] + y[n*i + 4] + 5*y[n*i + 5] + y[n*i + 6]) * 3*d[i]/10'\n    else: raise ValueError('Wrong formula')\n\n    if y is None and x is None:\n        if not all(p is not None for p in [f,a,b]): raise ValueError(f\"If you don't define y/x you must define f,a and b\")\n        if N%n != 0: raise ValueError(f'{N=} must be divisible by {n=}')\n        x = np.linspace(a,b,N+1)\n        y = f(x)   \n    \n    if (len(y)-1)%n != 0: raise ValueError(f'The length of the array y={len(y)} - 1 must be multiple of {n=} in order to divide the interval')\n    nh = int((len(y)-1)/n)\n\n    if x is None: \n        d = np.array([h]*nh)\n        # x is only for checking\n        x = np.empty(len(y))\n    else: d = np.diff(x)[::n]\n\n    if len(y) != len(x): raise ValueError(f'The length of x={len(x)} and y={len(y)} must be the same')\n\n    s = 0\n    for i in range(nh):\n        s += eval(fs)\n    return s\n\ndef trapz(y: Vector=None, x: Vector=None, h: float=1,\n          f: Function=None, a: float=None, b: float=None, N: int=100) -> float:\n    \"\"\"\n    Trapezoidal Rule\n    ================\n    The trapezoidal rule (also known as the trapezoid rule or trapezium rule)\n    is a technique for approximating the definite integral.\n    The trapezoidal rule works by approximating the region under the graph of the function \n    `f(x)` as a trapezoid and calculating its area.\n    `n=1`, where n is the grade of the polynomial interpolation, also nodes - 1.\n    This is a special case of Newton-Cotes formulas  \n\n    Parameters\n    ----------\n    y : Vector\n        Input array to integrate\n    x : Vector, optional\n        The sample points corresponding to the y values. If x is None,\n        the sample points are assumed to be evenly spaced h apart, by default None\n    h : float, optional\n        The spacing between sample points when x is None, by default 1\n    f : function, optional\n        funcion to integrate, if you don't define y/x\n    a : float, optional\n        Lower limit of the integral\n    b : float, optional\n        Upper limit of the integral\n    N : int, optional\n        Number of intervals, must be divisible by n, by default 100\n\n    Returns\n    -------\n    float\n        Definite integral\n    \n    Examples\n    --------\n    >>> N, a, b = 12, 1, 4\n    >>> x = np.linspace(a, b, N+1)\n    >>> y = np.sin(x)\n    >>> print(trapz(y,x))\n    1.187720971137812\n    >>> def fun(x): return np.sin(x)\n    >>> print(trapz(f=fun, a=a, b=b, N=N))\n    1.187720971137812\n\n    \"\"\"\n    return newton_cotes(y, x, 'trapz', h, f, a, b, N)\n\ndef simpson(y: Vector=None, x: Vector=None, h: float=1,\n            f: Function=None, a: float=None, b: float=None, N: int=100) -> float:\n    \"\"\"\n    Simpson's Rule\n    ============\n    In numerical integration, Simpson's rules are several approximations for definite integrals,\n    named after Thomas Simpson (1710-1761).\n    This is the  most basic of these rules, called Simpson's 1/3 rule, or just Simpson's rule.\n    `n=2`, where n is the grade of the polynomial interpolation, also nodes - 1.\n    This is a special case of Newton-Cotes formulas \n\n    Parameters\n    ----------\n    y : Vector\n        Input array to integrate\n    x : Vector, optional\n        The sample points corresponding to the y values. If x is None,\n        the sample points are assumed to be evenly spaced h apart, by default None\n    h : float, optional\n        The spacing between sample points when x is None, by default 1\n    f : function, optional\n        funcion to integrate, if you don't define y/x\n    a : float, optional\n        Lower limit of the integral\n    b : float, optional\n        Upper limit of the integral\n    N : int, optional\n        Number of intervals, must be divisible by n, by default 100\n\n    Returns\n    -------\n    float\n        Definite integral\n    \n    Examples\n    --------\n    >>> N, a, b = 12, 1, 4\n    >>> x = np.linspace(a, b, N+1)\n    >>> y = np.sin(x)\n    >>> print(simpson(y,x))\n    1.193972031074762\n    >>> def fun(x): return np.sin(x)\n    >>> print(simpson(f=fun, a=a, b=b, N=N))\n    1.193972031074762\n\n    \"\"\"\n    return newton_cotes(y, x, 'simpson', h, f, a, b, N)\n\ndef simpson3_8(y: Vector=None, x: Vector=None, h: float=1,\n               f: Function=None, a: float=None, b: float=None, N: int=99) -> float:\n    \"\"\"\n    Simpson's Rule 3/8\n    ================\n    In numerical integration, Simpson's rules are several approximations for definite integrals,\n    named after Thomas Simpson (1710-1761).\n    This is the second of these rules, called Simpson's 3/8 rule or Simpson's second rule.\n    `n=3`, where n is the grade of the polynomial interpolation, also nodes - 1.\n    This is a special case of Newton-Cotes formulas \n\n    Parameters\n    ----------\n    y : Vector\n        Input array to integrate\n    x : Vector, optional\n        The sample points corresponding to the y values. If x is None,\n        the sample points are assumed to be evenly spaced h apart, by default None\n    h : float, optional\n        The spacing between sample points when x is None, by default 1\n    f : function, optional\n        funcion to integrate, if you don't define y/x\n    a : float, optional\n        Lower limit of the integral\n    b : float, optional\n        Upper limit of the integral\n    N : int, optional\n        Number of intervals, must be divisible by n, by default 99\n\n    Returns\n    -------\n    float\n        Definite integral\n    \n    Examples\n    --------\n    >>> N, a, b = 12, 1, 4\n    >>> x = np.linspace(a, b, N+1)\n    >>> y = np.sin(x)\n    >>> print(simpson3_8(y,x))\n    1.1940051049177476\n    >>> def fun(x): return np.sin(x)\n    >>> print(simpson3_8(f=fun, a=a, b=b, N=N))\n    1.1940051049177476\n\n    \"\"\"\n    return newton_cotes(y, x, 'simpson3_8', h, f, a, b, N)\n\ndef boole(y: Vector=None, x: Vector=None, h: float=1,\n          f: Function=None, a: float=None, b: float=None, N: int=100) -> float:\n    \"\"\"\n    Boole's Rule \n    ============\n    In mathematics, Boole's rule, named after George Boole, is a method of numerical integration.\n\n    `n=4`, where n is the grade of the polynomial interpolation, also nodes - 1\n    This is a special case of Newton-Cotes formulas \n\n    Parameters\n    ----------\n    y : Vector\n        Input array to integrate\n    x : Vector, optional\n        The sample points corresponding to the y values. If x is None,\n        the sample points are assumed to be evenly spaced h apart, by default None\n    h : float, optional\n        The spacing between sample points when x is None, by default 1\n    f : function, optional\n        funcion to integrate, if you don't define y/x\n    a : float, optional\n        Lower limit of the integral\n    b : float, optional\n        Upper limit of the integral\n    N : int, optional\n        Number of intervals, must be divisible by n, by default 100\n\n    Returns\n    -------\n    float\n        Definite integral\n\n    \"\"\"\n    return newton_cotes(y, x, 'boole', h, f, a, b, N)\n\ndef weddle(y: Vector=None, x: Vector=None, h: float=1,\n           f: Function=None, a: float=None, b: float=None, N: int=96) -> float:\n    \"\"\"\n    Weddle's Rule \n    ==========\n\n    n=6, where n is the grade of the polynomial interpolation, also nodes - 1 \n\n    Parameters\n    ----------\n    y : Vector\n        Input array to integrate\n    x : Vector, optional\n        The sample points corresponding to the y values. If x is None,\n        the sample points are assumed to be evenly spaced h apart, by default None\n    h : float, optional\n        The spacing between sample points when x is None, by default 1\n    f : function, optional\n        funcion to integrate, if you don't define y/x\n    a : float, optional\n        Lower limit of the integral\n    b : float, optional\n        Upper limit of the integral\n    N : int, optional\n        Number of intervals, must be divisible by n, by default 96\n\n    Returns\n    -------\n    float\n        Definite integral\n\n    \"\"\"\n    return newton_cotes(y, x, 'weddle', h, f, a, b, N)\n\ndef newton_cotes2(y: Vector=None, x: Vector=None, h: float=1,\n                 f: Function=None, a: float=None, b: float=None, n: int=100) -> float:\n    n = len(y)-1\n    if   n == 1: return trapz(y,x,h)\n    elif n == 2: return simpson(y,x,h)\n    elif n == 3: return simpson3_8(y,x,h)\n    elif n == 4: return boole(y,x,h)\n    elif n == 6: return weddle(y,x,h)\n\n\ndef odeEuler(f: Function2d, t0: float, tfin: float, N: int, y0: Union[float, Vector]) -> Tuple[Vector, Vector]:\n    \"\"\"\n    Euler Method\n    ============\n\n    Parameters\n    ----------\n    f : Function2d\n        Right-hand side of the differential equation `y' = f(t,y), y(t0) = y0`\n    t0 : float\n        Initial time \n    tfin : float\n        Final time\n    N : int\n        Number of partitions\n    y0 : float\n        Initial value\n\n    Returns\n    -------\n    Tuple[Vector, Vector]\n        The time and value vectors of the solution\n    \n    Examples\n    --------\n    >>> def q(t): return 1/2 + 1/2 * np.cos(t**2)\n    >>> def f(t, y): return q(t) - y\n    >>> T, U = odeEuler(f, 0, 6, 1000, 0)\n    >>> import matplotlib.pyplot as plt\n    >>> plt.plot(T,U)\n    >>> plt.show()\n    plot figure\n    >>> T, U = odeEuler(f, 0, 6, 1000, [0,1])\n    >>> for i in range(len(T)):\n            plt.plot(T[i], U[i])\n    >>> plt.show()\n    plot figure\n\n    \"\"\"\n    if isinstance(y0, list) or type(y0) == np.ndarray:\n        leny0 = len(y0)\n        \n        T = np.tile(np.linspace(t0, tfin, N+1), (leny0,1))\n        h = (tfin - t0) / N\n\n        U = np.empty([leny0, N+1])\n        U[:,0] = y0\n        for i in range(1, N+1):\n            U[:,i] = U[:,i-1] + h*f(T[:,i-1], U[:,i-1])\n\n    else:\n        T = np.linspace(t0, tfin, N+1)\n        h = (tfin - t0) / N\n        U = np.empty(N+1)\n        U[0] = y0\n        for i in range(1, N+1):\n            U[i] = U[i-1] + h*f(T[i-1], U[i-1])\n\n    return T, U\n\ndef slope_field(f: Function2d, range: list = None,\n                xlim: list = None, ylim: list = None,\n                normalize: bool = True, plot_type: str = 'quiver',\n                density: int = 20, color: bool = True,\n                show: bool = True, cmap: str = 'viridis'):\n    \"\"\"\n    Slope Field\n    ===========\n    Graphical representation of the solutions\n    to a first-order differential equation `y' = f(t,y)`\n\n    Parameters\n    ----------\n    f : Function2d\n        Function with 2 parameters `y' = f(t,y)`\n\n    range : list, optional\n        Sets both limits x/y of the plot, by default [-5, 5]\n\n    xlim : list, optional\n        Sets the x limits of the plot, if `range` is defined, xlim is already set, by default [-5, 5]\n\n    ylim : list, optional\n        Sets the y limits of the plot, if `range` is defined, ylim is already set, by default [-5, 5]\n\n    normalize : bool, optional\n        Normalize the slope field, by default True\n\n    plot_type : str, optional\n        Defines the plot type\n            quiver: -> plt.quiver()\n            streamplot: -> plt.streamplot()\n        by default 'quiver'\n\n    density : int, optional\n        Density of arrows, by default 20\n\n    color : bool, optional\n        Color of the arrows, by default True\n        \n    show : bool, optional\n        Shows the plot, by default True\n\n    cmap : str, optional\n        https://matplotlib.org/stable/tutorials/colors/colormaps.html\n\n    Examples\n    --------\n    >>> def fun(x,y): return x + np.sin(y)\n    >>> slope_field(fun, range=[-2,2], plot_type='streamplot', cmap='plasma')\n    plot figure\n    >>> slope_field(fun, xlim=[-3,2], ylim=[-1,1], color=False, normalize=False, density=30, show=False)\n    >>> T, U = odeEuler(fun, -3, 2, 1000, 0.1)\n    >>> import matplotlib.pyplot as plt\n    >>> plt.plot(T,U)\n    >>> plt.show()\n    plot figure\n\n    \"\"\"\n    \n    if range is None and xlim is None and ylim is None:\n        range = [-5,5]\n        x1, x2 = range\n        y1, y2 = range\n    \n    elif xlim is None and ylim is None:\n        x1, x2 = range\n        y1, y2 = range\n    \n    elif range is None:\n        x1, x2 = xlim\n        y1, y2 = ylim\n    \n    else:\n        raise ValueError('Must speciefy either range or xlim/ylim')\n    \n\n    x = np.linspace(x1, x2, density)\n    y = np.linspace(y1, y2, density)\n\n    X, Y = np.meshgrid(x, y)\n\n    dx, dy = np.ones(X.shape), f(X,Y)\n    if normalize:\n        norm = np.sqrt(dx**2 + dy**2)\n        dx, dy = dx/norm , dy/norm\n    \n    if plot_type == 'quiver':\n        #color = np.sqrt(((dx+4)/2)*2 + ((dy+4)/2)*2)\n        if color: plt.quiver(X, Y, dx, dy, dy, cmap=cmap)\n        else: plt.quiver(X, Y, dx, dy)\n\n    elif plot_type == 'streamplot':\n        if color: plt.streamplot(X, Y, dx, dy, color=dy, cmap=cmap)\n        else: plt.streamplot(X, Y, dx, dy, color='k')\n\n    else:\n        raise ValueError(\"It only accepts either 'quiver' or 'streamplot'\")\n    \n    plt.title(f'Slope Field ({plot_type})')\n    plt.xlabel('x')\n    plt.ylabel('y')\n    if show: plt.show()", "meta": {"hexsha": "0e26193680aeb23f10f83a7cdd65c953d54de9ed", "size": 15865, "ext": "py", "lang": "Python", "max_stars_repo_path": "intelligen/integrate.py", "max_stars_repo_name": "Bouchet07/intelligen", "max_stars_repo_head_hexsha": "d876b1241efe7ad70fa759e1f10728728f867992", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "intelligen/integrate.py", "max_issues_repo_name": "Bouchet07/intelligen", "max_issues_repo_head_hexsha": "d876b1241efe7ad70fa759e1f10728728f867992", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intelligen/integrate.py", "max_forks_repo_name": "Bouchet07/intelligen", "max_forks_repo_head_hexsha": "d876b1241efe7ad70fa759e1f10728728f867992", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3775510204, "max_line_length": 142, "alphanum_fraction": 0.5763000315, "include": true, "reason": "import numpy", "num_tokens": 4589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778048911612, "lm_q2_score": 0.9046505325302034, "lm_q1q2_score": 0.8660018759741331}}
{"text": "import numpy as np\n\n\n# Creating vectors (unidimensional arrays)\nvector_a = np.arange(5) # 0 to 4 array\nvector_b = np.arange(start=3, stop=7, step=1) # start, stop, step\nvector_c = np.arange(11, 1, -2)\nvector_d = np.linspace(start=0, stop=1, num=11) # Automatic step calculation with explicit array length definition (third parameter)\n\nprint(f'\\nVector A:\\n', vector_a)\nprint(f'\\nVector B:\\n', vector_b)\nprint(f'\\nVector C:\\n', vector_c)\nprint(f'\\nVector D:\\n', vector_d)\n\n\n# Creating matrix (bidimensional arrays)\nmatrix_a = np.arange(9).reshape(3, 3) # Array of 3 arrays each one with 3 ascendent numbers from 0 to reach 8\n\n# for index, array in enumerate(matrix_a):\n#     print(f'{index} array:', array)\n#     for element in array:\n#         print(element)\nprint(f'\\nMatrix:\\n', matrix_a)\n\n\n# Creating tensors (+3 dimensional arrays)\ntensor_a = np.arange(12).reshape(3, 2, 2)\n\nprint(f'\\nTensor:\\n', tensor_a)\n\n\n# Creating an array from a list\nmy_list = [1, 2, 3, 4, 5]\n\nvector_from_list_a = np.array(my_list)\nvector_from_list_b = np.array([1, 2, 3, 4, 5])\nprint(f'\\nVector from list A:\\n', vector_from_list_a)\nprint(f'\\nVector from list B:\\n', vector_from_list_b)\n\nmatrix_from_list = np.array([[1, 2, 3], [4, 5, 6]])\nprint(f'\\nMatrix from list:\\n', matrix_from_list)\n\ntensor_from_list = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]])\nprint(f'\\nTensor from list:\\n', tensor_from_list)\n\n\n# Creating empty arrays\nempty_array_a = np.zeros(5)\nempty_array_b = np.zeros((2, 2))\nempty_array_c = np.ones((2, 2))\n\nprint(f'\\nEmpty array A:\\n{empty_array_a}')\nprint(f'\\nEmpty array B:\\n{empty_array_b}')\nprint(f'\\nEmpty array C:\\n{empty_array_c}')\n\n\n# Filled arrays\nfilled_array_a = np.full(shape=(2, 2), fill_value=7)\nfilled_array_b = np.full(shape=(2, 2), fill_value='a')\n\nprint(f'\\nFilled array A:\\n{filled_array_a}')\nprint(f'\\nFilled array B:\\n{filled_array_b}')\n\n\n# Reusing the structure of an array to construct another array\nbase = np.linspace(2, 6, 4)\nreuse_array_a = np.full_like(base, np.pi)\n\nprint(f'\\nReusing an array:\\nBase: {base}\\nTo: {reuse_array_a}\\n')\n", "meta": {"hexsha": "af6a283c28dda130e12c51453742f17166ffb420", "size": 2081, "ext": "py", "lang": "Python", "max_stars_repo_path": "arrays.py", "max_stars_repo_name": "smv7/Numpy_exploration", "max_stars_repo_head_hexsha": "1cf0af53da9a3cd1572809264c7d8f4447fa7712", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "arrays.py", "max_issues_repo_name": "smv7/Numpy_exploration", "max_issues_repo_head_hexsha": "1cf0af53da9a3cd1572809264c7d8f4447fa7712", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arrays.py", "max_forks_repo_name": "smv7/Numpy_exploration", "max_forks_repo_head_hexsha": "1cf0af53da9a3cd1572809264c7d8f4447fa7712", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7285714286, "max_line_length": 132, "alphanum_fraction": 0.6938971648, "include": true, "reason": "import numpy", "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777975782055, "lm_q2_score": 0.9046505351008904, "lm_q1q2_score": 0.8660018718193255}}
{"text": "import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom scipy.special import expit\nimport os\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\n# Choosing activation functions for multilayer neural networks\n\n# Logistic function recap\n\nX = np.array([1, 1.4, 2.5]) ## first value must be 1\nw = np.array([0.4, 0.3, 0.5])\n\ndef net_input(X, w):\n    return np.dot(X, w)\n\ndef logistic(z):\n    return 1.0 / (1.0 + np.exp(-z))\n\ndef logistic_activation(X, w):\n    z = net_input(X, w)\n    return logistic(z)\n\nprint('P(y=1|x) = %.3f' % logistic_activation(X, w)) \n\n# W : array with shape = (n_output_units, n_hidden_units+1)\n# note that the first column are the bias units\n\nW = np.array([[1.1, 1.2, 0.8, 0.4],\n              [0.2, 0.4, 1.0, 0.2],\n              [0.6, 1.5, 1.2, 0.7]])\n\n# A : data array with shape = (n_hidden_units + 1, n_samples)\n# note that the first column of this array must be 1\n\nA = np.array([[1, 0.1, 0.4, 0.6]])\nZ = np.dot(W, A[0])\ny_probas = logistic(Z)\nprint('Net Input: \\n', Z)\n\nprint('Output Units:\\n', y_probas) \n\ny_class = np.argmax(Z, axis=0)\nprint('Predicted class label: %d' % y_class) \n\n\n# Estimating class probabilities in multiclass classification via the softmax function\n\ndef softmax(z):\n    return np.exp(z) / np.sum(np.exp(z))\n\ny_probas = softmax(Z)\nprint('Probabilities:\\n', y_probas)\n\nnp.sum(y_probas)\n\nZ_tensor = tf.expand_dims(Z, axis=0)\ntf.keras.activations.softmax(Z_tensor)\n\n\n# Broadening the output spectrum using a hyperbolic tangent\ndef tanh(z):\n    e_p = np.exp(z)\n    e_m = np.exp(-z)\n    return (e_p - e_m) / (e_p + e_m)\n\nz = np.arange(-5, 5, 0.005)\nlog_act = logistic(z)\ntanh_act = tanh(z)\nplt.ylim([-1.5, 1.5])\nplt.xlabel('Net input $z$')\nplt.ylabel('Activation $\\phi(z)$')\nplt.axhline(1, color='black', linestyle=':')\nplt.axhline(0.5, color='black', linestyle=':')\nplt.axhline(0, color='black', linestyle=':')\nplt.axhline(-0.5, color='black', linestyle=':')\nplt.axhline(-1, color='black', linestyle=':')\nplt.plot(z, tanh_act,\n    linewidth=3, linestyle='--',\n    label='Tanh')\nplt.plot(z, log_act,\n    linewidth=3,\n    label='Logistic')\nplt.legend(loc='lower right')\nplt.tight_layout()\nplt.show()\n\nnp.tanh(z)\ntf.keras.activations.tanh(z)\n\nexpit(z)\n\ntf.keras.activations.sigmoid(z)\n\n\n# Rectified linear unit activation\n\ntf.keras.activations.relu(z)", "meta": {"hexsha": "7d5e36adad60fee569182914ca62bb29049166cc", "size": 2307, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter 13/04 Choosing activation functions for multilayer neural networks/program.py", "max_stars_repo_name": "fagaiera/python-machine-learning-book-3rd-edition-examples", "max_stars_repo_head_hexsha": "16c7eb01fc670a3845847d0e2ac3569c3fd61c35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter 13/04 Choosing activation functions for multilayer neural networks/program.py", "max_issues_repo_name": "fagaiera/python-machine-learning-book-3rd-edition-examples", "max_issues_repo_head_hexsha": "16c7eb01fc670a3845847d0e2ac3569c3fd61c35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 13/04 Choosing activation functions for multilayer neural networks/program.py", "max_forks_repo_name": "fagaiera/python-machine-learning-book-3rd-edition-examples", "max_forks_repo_head_hexsha": "16c7eb01fc670a3845847d0e2ac3569c3fd61c35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.07, "max_line_length": 86, "alphanum_fraction": 0.6592977893, "include": true, "reason": "import numpy,from scipy", "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.9111797154386841, "lm_q1q2_score": 0.8659952035872117}}
{"text": "import numpy as np\r\n\r\n# We will add the vector v to each row of the matrix x,\r\n# storing the result in the matrix y\r\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\r\nprint(x)\r\nv = np.array([1, 0, 1])\r\nprint(v)\r\ny = np.empty_like(x)   # Create an empty matrix with the same shape as x\r\nprint(y)\r\n\r\n# Add the vector v to each row of the matrix x with an explicit loop\r\nfor i in range(4):\r\n    y[i, :] = x[i, :] + v\r\n\r\n# Now y is the following\r\n# [[ 2  2  4]\r\n#  [ 5  5  7]\r\n#  [ 8  8 10]\r\n#  [11 11 13]]\r\nprint(y)\r\n\r\nvv = np.tile(v, (4, 1))   # Stack 4 copies of v on top of each other\r\nprint(vv)                 # Prints \"[[1 0 1]\r\n                          #          [1 0 1]\r\n                          #          [1 0 1]\r\n                          #          [1 0 1]]\"\r\nyy = x + vv  # Add x and vv elementwise\r\nprint(yy)  # Prints \"[[ 2  2  4\r\n          #          [ 5  5  7]\r\n          #          [ 8  8 10]\r\n          #          [11 11 13]]\"\r\n          \r\nyyy = x + v  # Add v to each row of x using broadcasting\r\nprint(y)  # Prints \"[[ 2  2  4]\r\n          #          [ 5  5  7]\r\n          #          [ 8  8 10]\r\n          #          [11 11 13]]\"", "meta": {"hexsha": "06111cd06830ece5212595123a25f4d3f13ce5c6", "size": 1156, "ext": "py", "lang": "Python", "max_stars_repo_path": "class-codes/Broadcasting.py", "max_stars_repo_name": "dinasoltanit/Python-Nov2021-NamakSat", "max_stars_repo_head_hexsha": "dcf439ae11ade87fe4ffa464e02c52702b6dba52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "class-codes/Broadcasting.py", "max_issues_repo_name": "dinasoltanit/Python-Nov2021-NamakSat", "max_issues_repo_head_hexsha": "dcf439ae11ade87fe4ffa464e02c52702b6dba52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "class-codes/Broadcasting.py", "max_forks_repo_name": "dinasoltanit/Python-Nov2021-NamakSat", "max_forks_repo_head_hexsha": "dcf439ae11ade87fe4ffa464e02c52702b6dba52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4210526316, "max_line_length": 73, "alphanum_fraction": 0.4178200692, "include": true, "reason": "import numpy", "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205502, "lm_q2_score": 0.9111797015700341, "lm_q1q2_score": 0.8659951916861212}}
{"text": "import numpy as np\r\nfrom numpy.core._multiarray_umath import ndarray\r\n\r\n\r\ndef Jacobi_nonmatrix(A, b):\r\n    n = len(A)\r\n    x = np.zeros(n)\r\n    y = np.ones(n)\r\n    N = 100\r\n    tmp = np.zeros(n)\r\n    #    for k in range(N):\r\n    while max(abs((y - tmp))) > 0.001:\r\n        for i in range(0, n):\r\n            s1 = sum(A[i][t] * x[t] for t in range(i))\r\n            s2 = sum(A[i][t] * x[t] for t in range(i + 1, n))\r\n            y[i] = (b[i] - s1 - s2) / A[i][i]\r\n        tmp = x.copy()\r\n        x = y.copy()  # You can understand x and y as pointers to a specific array.\r\n        # Direct assignment will cause x and y to point to the same object, causing the x and y values to change\r\n        # together during the iteration.\r\n    return y\r\n\r\n\r\ndef Jacobi_matrix(A, b):\r\n    # Use numpy matrix operation, save time\r\n    x = np.zeros(len(b))\r\n    D = np.diagflat(np.diag(A))\r\n    LU = A - D\r\n    N = 100\r\n    for k in range(N):\r\n        x = np.dot(np.dot(-np.linalg.inv(D), LU), x) + np.dot(np.linalg.inv(D), b)\r\n    #    D = np.diag(A)\r\n    #    LU = A - np.diagflat(D)\r\n    #    N = 100\r\n    #    for k in range(N):\r\n    #       x = (b - np.dot(LU, x))/D\r\n    return x\r\n\r\n\r\ndef Gauss_seidel(A, b):\r\n    n = len(A)\r\n    x = np.zeros(n)\r\n    tmp = np.ones(n)\r\n    #   N = 100\r\n    #   for k in range(N):\r\n    while max(abs((x - tmp))) > 0.001:\r\n        tmp = x.copy()\r\n        for i in range(n):\r\n            x[i] = b[i] / A[i][i] - sum((A[i][j] / A[i][i]) * x[j] for j in range(i)) - sum(\r\n                (A[i][j] / A[i][i]) * x[j] for j in range(i + 1, n))\r\n    return x\r\n\r\n\r\n\r\n\r\n# Test case 1, problem 15, problem 17\r\n\r\nA = [[5., 2., 1.], [-1., 4., 2.], [2., -5., 10.]]\r\nA = np.array(A)\r\nb = [-12., 10., 1.]\r\nb = np.array(b)\r\nprint(Jacobi_nonmatrix(A, b))\r\nprint(Jacobi_matrix(A, b))\r\nprint(Gauss_seidel(A, b))\r\n", "meta": {"hexsha": "0f0ff954e03d6973f38b369f8464642baab6b2a6", "size": 1815, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapter2/IteratorSlove.py", "max_stars_repo_name": "ElliotShang/numerical-analysis", "max_stars_repo_head_hexsha": "769610dc45cc4498b49f8311d7023b725c1c7bc2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter2/IteratorSlove.py", "max_issues_repo_name": "ElliotShang/numerical-analysis", "max_issues_repo_head_hexsha": "769610dc45cc4498b49f8311d7023b725c1c7bc2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter2/IteratorSlove.py", "max_forks_repo_name": "ElliotShang/numerical-analysis", "max_forks_repo_head_hexsha": "769610dc45cc4498b49f8311d7023b725c1c7bc2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9230769231, "max_line_length": 113, "alphanum_fraction": 0.4809917355, "include": true, "reason": "import numpy,from numpy", "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068041, "lm_q2_score": 0.9111796979521253, "lm_q1q2_score": 0.8659951844081408}}
{"text": "import numpy as np\nfrom numpy.random import rand\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom timeit import timeit as ti\n\n#problem 1\ndef arrmul(A,B):\n    new = []\n    for i in range(len(A)):\n        newrow = []\n        for k in range(len(B[0])):\n            tot = 0\n            for j in range(len(B)):\n                tot += A[i][j] * B[j][k]\n            newrow.append(tot)\n        new.append(newrow)\n    return new\n\ndef prob1():\n    k = 200\n    A = [range(i, i+k) for i in range(0, k**2, k)]\n    number = 5\n    print \"problem 1\"\n    tm = ti(\"arrmul(A,A)\", setup=\"from __main__ import A, arrmul\", number=number)\n    print \"arrmul(A,A) executed \", number, \" times in \", tm, \" seconds.\"\n    A = np.array(A)\n    number = 5\n    tm = ti(\"np.dot(A,A)\", setup=\"import numpy as np; from __main__ import A\", number=number)\n    print \"np.dot(A,A) executed \", number, \" times in \", tm, \" seconds.\"\n    \n    #problem 2\ndef prob2():\n    print \"problem 2\"\n    A = rand(1000,1000)\n    B = np.empty_like(A)\n    for i in xrange(100):\n            B[:] = rand(1000,1000)\n            A[A<B] = B[A<B]\n    np.exp(A, out=A)\n    print np.average(np.max(A, axis=1))\n    \ndef prob3():\n    #problem 3\n    print \"problem 3\"\n    A = rand(1000,1000)\n    number = 100\n    tm = ti(\"A.reshape(A.size)\", setup=\"from __main__ import A\", number=number)\n    print \"A.reshape(A.size) executed \", number, \" times in \", tm, \" seconds.\"\n    number = 100\n    tm = ti(\"A.flatten()\", setup=\"from __main__ import A\", number=number)\n    print \"A.flatten() executed \", number, \" times in \", tm, \" seconds.\"\n    number = ti(\"A.reshape((1,A.size))\", setup=\"from __main__ import A\", number=number)\n    print \"A.reshape((1,A.size)) executed \", number, \" times in \", tm, \" seconds.\"\n    \n    #part 2 of problem 3\n    print \"the difference is that np.vstack(A) returns a new array\"\n    print \"while A.T returns a view\"\n    print \"A.T is much faster\"\n    A = rand(1,1000000)\n    number = 500\n    tm = ti(\"np.vstack(A)\", setup=\"import numpy as np; from __main__ import A\", number=number)\n    print \"np.vstack(A) executed \", number, \" times in \", tm, \" seconds.\"\n    number = 500\n    tm = ti(\"A.T\", setup=\"from __main__ import A\", number=number)\n    print \"A.T executed \", number, \" times in \", tm, \" seconds.\"\n    \ndef laplace(U,tol):\n    new = U.copy()\n    dif = tol\n    while tol<= dif:\n        new[1:-1,1:-1] = (U[:-2,1:-1] + U[2:,1:-1] + U[1:-1,:-2] + U[1:-1,2:]) / 4.\n        dif = np.max(np.absolute(U-new))\n        U[:] = new\n\ndef prob4():\n    n = 100\n    tol=.0001\n    U=np.ones((n,n))\n    U[:,0] = 100\n    U[:,-1] = 100\n    U[0] = 0\n    U[-1] = 0\n    laplace(U, tol)\n    fig = plt.figure()\n    ax = fig.gca(projection='3d')\n    X = np.linspace(0,1,n)\n    Y = np.linspace(0,1,n)\n    X, Y = np.meshgrid(X, Y)\n    ax.plot_surface(X, Y, U, rstride=5)\n    plt.show()\n\n#problem 5\n\ndef broadcast_1():\n    \"\"\"All input arrays have exactly the same shape\"\"\"\n    a = np.random.rand(4, 5)\n    b = np.random.rand(4, 5)\n    r = a * b\n    print \"Case 1: {} * {} = {}\".format(a.shape, b.shape, r.shape)\n\ndef broadcast_2():\n    \"\"\"All input arrays are of the same dimension and\n    the length of corresponding dimensions match or is 1\"\"\"\n\n    a = np.random.rand(5, 4, 1, 6)\n    b = np.random.rand(5, 4, 1, 1)\n    r = a * b\n    print \"Case 2: {} * {} = {}\".format(a.shape, b.shape, r.shape)\n\ndef broadcast_3():\n    \"\"\"All input arrays of fewer dimension can have 1\n    prepended to their shapes to satisfy the second criteria.\"\"\"\n\n    a = np.random.rand(1, 6)\n    b = np.random.rand(5, 4, 1, 6)\n    r = a * b\n    print \"Case 3: {} * {} = {}\".format(a.shape, b.shape, r.shape)\n\ndef prob_broadcasting():\n    #problem 5\n    broadcast_1()\n    broadcast_2()\n    broadcast_3()", "meta": {"hexsha": "47a49427a958c5f98f30e28d01a3156f5a31d2f9", "size": 3739, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/Arrays/array_solutions.py", "max_stars_repo_name": "abefrandsen/numerical_computing", "max_stars_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/Arrays/array_solutions.py", "max_issues_repo_name": "abefrandsen/numerical_computing", "max_issues_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/Arrays/array_solutions.py", "max_forks_repo_name": "abefrandsen/numerical_computing", "max_forks_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1532258065, "max_line_length": 94, "alphanum_fraction": 0.56405456, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.9196425300765949, "lm_q1q2_score": 0.8659852120912117}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n# ## Monte Carlo - Euler Discretization - Part II\n# *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).*\n# *Euler Discretization – continued.*\n# In[ ]:\nimport numpy as np  \nimport pandas as pd  \nfrom pandas_datareader import data as web  \nfrom scipy.stats import norm \nimport matplotlib.pyplot as plt  \nget_ipython().run_line_magic('matplotlib', 'inline')\ndata = pd.read_csv('D:/Python/MSFT_2000.csv', index_col = 'Date')\nlog_returns = np.log(1 + data.pct_change())\nstdev = log_returns.std() * 250 ** 0.5\nstdev = stdev.values\nr = 0.025\nT = 1.0 \nt_intervals = 250 \ndelta_t = T / t_intervals  \niterations = 10000  \nZ = np.random.standard_normal((t_intervals + 1, iterations))  \nS = np.zeros_like(Z) \nS0 = data.iloc[-1]  \nS[0] = S0 \nfor t in xrange(1, t_intervals + 1):\n    S[t] = S[t-1] * np.exp((r - 0.5 * stdev ** 2) * delta_t + stdev * delta_t ** 0.5 * Z[t])\nplt.figure(figsize=(10, 6))\nplt.plot(S[:, :10]);\n# ******\n# Use numpy.maximum to create a vector with as many elements as there are columns in the S matrix.\n# In[ ]:\np = np.maximum(S[-1] - 110, 0)\n# In[ ]:\np\n# In[ ]:\np.shape\n# Use the following formula to forecast the price of a stock option.\n# $$\n# C = \\frac{exp(-r \\cdot T) \\cdot \\sum{p_i}}{iterations}\n# $$\n# In[ ]:\nnp.sum(p)\n# In[ ]:\nC = np.exp(-r * T) * np.sum(p) / iterations\nC  \n# Because this pricing model is based on random iterations, you will obtain a different result every time you re-run the code in this document. Expand the “Kernel” list from the Jupyter menu and click on “Restart and run all”/”Restart & run all cells” to verify this is true.\n", "meta": {"hexsha": "1440bf96f9fc20c57c46a1b6204f358898b84484", "size": 1649, "ext": "py", "lang": "Python", "max_stars_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_110-MC-EulerDiscretization-PartII-Solution_CSV.py", "max_stars_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_stars_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-04T11:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-10T15:36:42.000Z", "max_issues_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_110-MC-EulerDiscretization-PartII-Solution_CSV.py", "max_issues_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_issues_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-03-30T16:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:37:21.000Z", "max_forks_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_110-MC-EulerDiscretization-PartII-Solution_CSV.py", "max_forks_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_forks_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T11:26:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T11:26:16.000Z", "avg_line_length": 34.3541666667, "max_line_length": 275, "alphanum_fraction": 0.6719223772, "include": true, "reason": "import numpy,from scipy", "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661944, "lm_q2_score": 0.9230391605990604, "lm_q1q2_score": 0.8659252074658927}}
{"text": "# solutions.py\n\"\"\"Volume 2 Lab 14: Optimization Packages II (CVXOPT)\"\"\"\n\nfrom cvxopt import matrix, solvers\nimport numpy as np\nfrom scipy import linalg as la\n\n\ndef prob1():\n    \"\"\"Solve the following convex optimization problem:\n\n    minimize        2x + y + 3z\n    subject to      x + 2y          >= 3\n                    2x + 10y + 3z   >= 10\n                    x               >= 0\n                    y               >= 0\n                    z               >= 0\n\n    Returns (in order):\n        The optimizer x (ndarray)\n        The optimal value (sol['primal objective'])\n    \"\"\"\n\n    # Note that 'matrix' initializes by column, not row.\n    c = matrix([2., 1., 3.])\n    G = matrix(np.array([[-1.,-2.,0.],\n                         [-2.,-10.,-3.],\n                         [-1.,0.,0.],\n                         [0.,-1.,0.],\n                         [0.,0.,-1.]]))\n\n    h = matrix([ -3., -10., 0., 0., 0.])\n    sol = solvers.lp(c,G,h)\n    return np.ravel(sol['x']), sol['primal objective']\n\n    # Answers:\n    # np.array([ -1.14760916e-09,   1.50000000e+00,   6.95278285e-11])\n    # 1.4999999996249482\n\n# Problem 2\ndef l1Min(A, b):\n    \"\"\"Calculate the solution to the optimization problem\n\n        minimize    ||x||_1\n        subject to  Ax = b\n\n    Parameters:\n        A ((m,n) ndarray)\n        b ((m, ) ndarray)\n\n    Returns:\n        The optimizer x (ndarray), without any slack variables u\n        The optimal value (sol['primal objective'])\n    \"\"\"\n\n    assert A.shape[0] == b.shape[0], \"mismatched dimensions\"\n\n    n = A.shape[1]\n    I = np.eye(n, dtype=np.float)\n\n    '''The optimization problem to solve is:\n\n    minimize                [u]\n                      [1 0] [x]\n\n    subject to      [-I  I] [u]     [0]\n                    [-I -I] [x]  <= [0]\n\n                            [u]\n                    [0   A] [x]  ==  b\n    '''\n\n    # Build the matrices for cvxopt (make sure dtype=np.floats)\n    c = matrix(np.hstack((np.ones(n), np.zeros(n))).astype(np.float))\n    G = matrix(np.vstack((np.hstack((-I, I)),np.hstack((-I, -I)))))\n    h = matrix(np.zeros(2*n))\n    new_A = matrix(np.hstack((np.zeros_like(A), A)).astype(np.float))\n    new_b = matrix(b.astype(np.float))\n\n    # Perform the optimization.\n    sol = solvers.lp(c, G, h, new_A, new_b)\n\n    # Flatten out the array and remove the u values.\n    return np.ravel(sol['x'])[n:], sol['primal objective']\n\n\ndef prob3():\n    \"\"\"Solve the transportation problem by converting the last equality constraint\n    into inequality constraints.\n\n    Returns (in order):\n        The optimizer x (ndarray)\n        The optimal value (sol['primal objective'])\n    \"\"\"\n    c = matrix([4., 7., 6., 8., 8., 9.])\n    G = matrix(np.array([[-1.,0.,0.,0.,0.,0.],\n                         [0.,-1.,0.,0.,0.,0.],\n                         [0.,0.,-1.,0.,0.,0.],\n                         [0.,0.,0.,-1.,0.,0.],\n                         [0.,0.,0.,0.,-1.,0.],\n                         [0.,0.,0.,0.,0.,-1.],\n                         [0.,1.,0.,1.,0.,1.],\n                         [0.,-1.,0.,-1.,0.,-1.]]))\n    h = matrix([0.,0.,0.,0.,0.,0., 8., -8.])\n    A = matrix(np.array([[1.,1.,0.,0.,0.,0.],\n                         [0.,0.,1.,1.,0.,0.],\n                         [0.,0.,0.,0.,1.,1.],\n                         [1.,0.,1.,0.,1.,0.]]))\n    b = matrix([7.,2.,4.,5.])\n    sol = solvers.lp(c,G,h,A,b)  \n    return np.ravel(sol['x']), sol['primal objective']\n\n    # Answers:\n    # np.array([[ 5.00e+00],[ 2.00e+00],[ -7.03e-09],\n    #           [ 2.00e+00],[ -5.45e-09],[ 4.00e+00]])\n    # 86\n\n\ndef prob4():\n    \"\"\"Find the minimizer and minimum of\n\n    g(x,y,z) = (3/2)x^2 + 2xy + xz + 2y^2 + 2yz + (3/2)z^2 + 3x + z\n\n    Returns (in order):\n        The optimizer x (ndarray)\n        The optimal value (sol['primal objective'])\n    \"\"\"\n    P = matrix(np.array([[3.,2.,1.],\n                         [2.,4.,2.],\n                         [1.,2.,3.]]))\n\n    q = matrix([3., 0., 1.])\n    sol = solvers.qp(P, q)\n    return np.ravel(sol['x']), sol['primal objective']\n\n    # Answers:\n    # np.array([[-1.50],[ 1.00],[-.5]])\n    # -2.5\n\n\n# Problem 5\ndef l2Min(A, b):\n    \"\"\"Calculate the solution to the optimization problem\n\n        minimize    ||x||_2\n        subject to  Ax = b\n\n    Parameters:\n        A ((m,n) ndarray)\n        b ((m, ) ndarray)\n\n    Returns:\n        The optimizer x (ndarray)\n        The optimal value (sol['primal objective'])\n    \"\"\"\n\n    assert A.shape[0] == b.shape[0], \"mismatched dimensions\"\n\n    n = A.shape[1]\n    I = np.eye(n, dtype=np.float)\n\n    '''The optimization problem to solve is:\n\n        minimize              x*x\n        subject to          A  =  b\n    '''\n\n    # Build the matrices for cvxopt (make sure dtype=np.floats)\n    P = matrix(2*I)\n    q = matrix(np.zeros(n))\n    new_A = matrix(A.astype(np.float))\n    new_b = matrix(b.astype(np.float))\n\n    # Perform the optimization.\n    sol = solvers.qp(P, q, A=new_A, b=new_b)\n\n    # Flatten out the array and only get the x value.\n    return np.ravel(sol['x']), sol['primal objective']\n\n\ndef prob6():\n    \"\"\"Solve the allocation model problem in 'ForestData.npy'.\n    Note that the first three rows of the data correspond to the first\n    analysis area, the second group of three rows correspond to the second\n    analysis area, and so on.\n\n    Returns (in order):\n        The optimizer x (ndarray)\n        The optimal value (sol['primal objective']*-1000)\n    \"\"\"\n    data = np.load('ForestData.npy')\n\n    c = matrix(data[:,3]*-1)\n\n    A = la.block_diag(*[[1.,1.,1.] for _ in xrange(7)])\n    b = data[::3,1].copy()\n\n    G = np.vstack((-data[:,4], -data[:,5], -data[:,6], -np.eye(21))) # flip the inequality signs\n    h = np.hstack(([-40000., -5., -70.*788.], np.zeros(21)))         # flip the inequality signs\n\n    c = matrix(c)\n    A = matrix(A)\n    b = matrix(b)\n    G = matrix(G)\n    h = matrix(h)\n\n    sol = solvers.lp(c,G,h,A,b)\n    return np.ravel(sol['x']), sol['primal objective']*-1000.\n\n    # Answers:\n    # np.array([[ 1.41e-08],[ 6.76e-08],[ 7.50e+01],[ 9.00e+01],[ 1.28e-07],\n    #           [ 2.52e-07],[ 1.40e+02],[ 4.18e-07],[ 5.52e-06],[ 1.04e-08],\n    #           [ 8.94e-09],[ 6.00e+01],[ 1.23e-07],[ 1.54e+02],[ 5.80e+01],\n    #           [ 3.16e-08],[ 3.58e-08],[ 9.80e+01],[ 1.63e-08],[ 9.12e-09],\n    #           [ 1.13e+02]])\n    # 322514998.983\n\n''' # Generate the forest data.\nforest=np.array([[1,75.,1,503.,310.,0.01,40],\n[0,0,2,140,50,0.04,80],\n[0,0,3,203,0,0,95],\n[2,90.,1,675,198,0.03,55],\n[0,0,2,100,46,0.06,60],\n[0,0,3,45,0,0,65],\n[3,140.,1,630,210,0.04,45],\n[0,0,2,105,57,0.07,55],\n[0,0,3,40,0,0,60],\n[4,60.,1,330,112,0.01,30],\n[0,0,2,40,30,0.02,35],\n[0,0,3,295,0,0,90],\n[5,212.,1,105,40,0.05,60],\n[0,0,2,460,32,0.08,60],\n[0,0,3,120,0,0,70],\n[6,98.,1,490,105,0.02,35],\n[0,0,2,55,25,0.03,50],\n[0,0,3,180,0,0,75],\n[7,113.,1,705,213,0.02,40],\n[0,0,2,60,40,0.04,45],\n[0,0,3,400,0,0,95]])\nnp.save('ForestData',forest)\n'''\n\n# END OF SOLUTIONS ============================================================\n\ndef test(student_module):\n    \"\"\"Test script. Import the student's solutions file as a module.\n    \n    10 points for problem 1\n    10 points for problem 2\n    10 points for problem 3\n    10 points for problem 4\n    10 points for problem 5\n    20 points for problem 6\n    \n    Inputs:\n        student_module: the imported module for the student's file.\n    \n    Returns:\n        score (int): the student's score, out of 70.\n        feedback (str): a printout of test results for the student.\n    \"\"\"\n    tester = _testDriver()\n    tester.test_all(student_module)\n    return tester.score, tester.feedback\n\n\nclass _testDriver(object):\n    \"\"\"Class for testing a student's work. See test.__doc__ for more info.\"\"\"\n\n    # Constructor -------------------------------------------------------------\n    def __init__(self):\n        \"\"\"Initialize the feedback attribute.\"\"\"\n        self.feedback = \"\"\n\n    # Main routine -----------------------------------------------------------\n    def test_all(self, student_module, total=70):\n        \"\"\"Grade the provided module on each problem and compile feedback.\"\"\"\n        # Reset feedback and score.\n        self.feedback = \"\"\n        self.score = 0\n\n        def test_one(problem, number, value):\n            \"\"\"Test a single problem, checking for errors.\"\"\"\n            try:\n                self.feedback += \"\\n\\nProblem {} ({} points):\".format(\n                                                                number, value)\n                points = problem(student_module)\n                self.score += points\n                self.feedback += \"\\nScore += {}\".format(points)\n            except BaseException as e:\n                self.feedback += \"\\n{}: {}\".format(self._errType(e), e)\n\n        # Grade each problem.\n        test_one(self.problem1, 1, 10)  # Problem 1: 10 points.\n        test_one(self.problem2, 2, 10)  # Problem 2: 10 points.\n        test_one(self.problem3, 3, 10)  # Problem 3: 10 points.\n        test_one(self.problem3, 4, 10)  # Problem 4: 10 points.\n        test_one(self.problem3, 5, 10)  # Problem 5: 10 points.\n        test_one(self.problem4, 6, 20)  # Problem 6: 20 points.\n\n        # Report final score.\n        percentage = (100. * self.score) / total\n        self.feedback += \"\\n\\nTotal score: {}/{} = {}%\".format(\n                                    self.score, total, round(percentage, 2))\n        if   percentage >=  98: self.feedback += \"\\n\\nExcellent!\"\n        elif percentage >=  90: self.feedback += \"\\n\\nGreat job!\"\n\n        # Add comments (optionally).\n        print(self.feedback)\n        comments = str(raw_input(\"Comments: \"))\n        if len(comments) > 0:\n            self.feedback += '\\n\\n\\nComments:\\n\\t{}'.format(comments)\n\n    # Helper Functions --------------------------------------------------------\n    @staticmethod\n    def _errType(error):\n        \"\"\"Get just the name of the exception 'error' in string format.\"\"\"\n        if isinstance(error, BaseException):\n            return str(type(error)).lstrip(\"<type 'exceptions.\").rstrip(\"'>\")\n        else:\n            return str(error)\n\n    def _eqTest(self, correct, student, message):\n        \"\"\"Test to see if 'correct' and 'student' are equal.\n        Report the given 'message' if they are not.\n        \"\"\"\n        if student is None:\n            self.feedback += \"\\nFailed to return a value.\"\n            return 0\n        if np.allclose(correct, student, atol=1e-1, rtol=1e-1):\n            return 1\n        else:\n            self.feedback += \"\\n{}\".format(message)\n            self.feedback += \"\\n\\tCorrect response:\\n{}\".format(correct)\n            self.feedback += \"\\n\\tStudent response:\\n{}\".format(student)\n            return 0\n\n    # Problems ----------------------------------------------------------------\n    def _test_problem(self, s, ans_1, ans_2, stu, index):\n        \"\"\"Test a problem with solutions 'ans' and submission 'stu'.\"\"\"\n        \n        # Attempt to unpack the student's solutions values.\n        try:\n            stu_1, stu_2 = stu\n        except (TypeError, ValueError):\n            self.feedback += \"\\nprob{}() must return 2 values.\".format(index)\n            raise\n\n        # Test the student's values against the true solution.\n        points = 0\n        points += 5*self._eqTest(ans_1, stu_1, \"Incorrect optimizer\")\n        points += 5*self._eqTest(ans_2, stu_2, \"Incorrect optimial value\")\n        print(\"PROBLEM {}: {}\".format(index, points))\n        return points\n\n    def problem1(self, s):\n        \"\"\"Test prob1(). 10 points.\"\"\"\n        return self._test_problem(s,\n                        np.array([[1.54643957],[ 1.20887997],[ 1.89941363]]),\n                        10, s.prob1(), 1)\n\n    # np.array([ -1.14760916e-09,   1.50000000e+00,   6.95278285e-11])\n    # 1.4999999996249482\n\n    def problem3(self, s):\n        \"\"\"Test prob3(). 10 points.\"\"\"\n        return self._test_problem(s,\n                        np.array([[ 5.00e+00],[ 2.00e+00],[ -7.03e-08],\n                                  [ 2.00e+00],[ -5.44e-09],[ 4.00e+00]]),\n                        86, s.prob3(), 3)\n\n    def problem4(self, s):\n        \"\"\"Test prob4(). 10 points.\"\"\"\n        return self._test_problem(s, np.array([[-1.50],[ 1.00],[-.5]]),\n                        -2.5, s.prob4(), 4)\n\n    def problem6(self, s):\n        \"\"\"Test prob6(). 20 points.\"\"\"\n        return 2*self._test_problem(s,\n                        np.array([[ 1.41e-08],[ 6.76e-08],[ 7.50e+01],\n                                  [ 9.00e+01],[ 1.28e-07],[ 2.52e-07],\n                                  [ 1.40e+02],[ 4.18e-07],[ 5.52e-06],\n                                  [ 1.04e-08],[ 8.94e-09],[ 6.00e+01],\n                                  [ 1.23e-07],[ 1.54e+02],[ 5.80e+01],\n                                  [ 3.16e-08],[ 3.58e-08],[ 9.80e+01],\n                                  [ 1.63e-08],[ 9.12e-09],[ 1.13e+02]]),\n                        322514998.983, s.prob6(), 6)\n\n# END OF FILE =================================================================\n", "meta": {"hexsha": "88aed6ac2136b11a0597c405cfd8bd0a07041e6e", "size": 12931, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol2B/CVXOPT/solutions.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vol2B/CVXOPT/solutions.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vol2B/CVXOPT/solutions.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 33.1564102564, "max_line_length": 96, "alphanum_fraction": 0.4872012992, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.9230391621868804, "lm_q1q2_score": 0.8659252041650418}}
{"text": "import numpy as np\nimport scipy.optimize as opt\nimport matplotlib.pyplot as plt\nfrom scipy.io import loadmat \n\ndef sigmoide(X):\n    return 1/(1+np.exp(-X))\n\ndef hipotesis(X, Theta):\n    return sigmoide(np.dot(X, np.transpose(np.array([Theta]))))\n\ndef coste(Theta, X, Y, reg):\n    m = np.shape(X)[0]\n    H = hipotesis(X, Theta)\n    aux = Y*np.log(H + 1e-6) + (1-Y)*np.log(1 - H + 1e-6)  \n    aux = -aux.sum()/m\n    aux2 = np.sum((Theta ** 2))\n    aux2 = (reg/(2*m))*aux2\n    return aux + aux2 \n\ndef coste2(Theta,X,Y):\n    H = sigmoide(np.matmul(X, Theta))\n    return (- 1 / (len(X))) * (np.dot(Y, np.log(H)) + np.dot((1 - Y), np.log(1 - H)))\n\ndef gradienteRecurs(Theta, X, Y, reg):\n    m = np.shape(X)[0]\n    grad = np.ravel((1/m)*np.dot(np.transpose(X), (hipotesis(X,Theta) - Y))) #+ (reg/m)*Theta \n    grad[0] = (1/m)*np.sum((hipotesis(X,Theta) - Y) * X[:,0:1])\n    return grad  \n\ndef fun(thetas, X, etiq):\n    return np.argmax(np.dot(thetas, X)) + 1 == etiq\n    \ndef oneVsAll(Xp, Yp, num_etiquetas, reg):\n    n = np.shape(Xp)[1]\n    thetas = np.empty((0,n), float)\n    ies = np.arange(1, num_etiquetas + 1)\n    for i in ies:\n        Y = np.copy(Yp)\n        Theta = np.zeros(n)\n        tr = np.where(Yp == i)\n        fls = np.where(Yp != i)\n        X = Xp\n        Y[tr[0]] = 1\n        Y[fls[0]] = 0\n        print(Y)\n        result = opt.fmin_tnc(func=coste, x0=Theta, fprime=gradienteRecurs, args=(X, Y, reg))\n        thetas = np.vstack((thetas, result[0]))\n    return thetas\n    \n\ndata = loadmat(\"ex3data1.mat\")\nX = data['X']\nY = data['y']\nY = Y.astype(int) \nm = np.shape(X)[0]\n\n\nsample = np.random.choice(X.shape[0],10)\nplt.imshow(X[sample,:].reshape(-1,20).T)\nplt.axis('off')\nplt.savefig('prueba.png')\n\nX = np.hstack([np.ones([m,1]), X])\n\n\nthetas = oneVsAll(X, Y, 10, 0.1)\n\naux = [fun(thetas, X[i], Y[i][0]) for i in range(m)]\n\nprint(\"Sol -->\", np.sum(aux)/m)\n\n#i = 756\n\n#calculo = np.dot(thetas, X[i])\n\n#print(\"Sol -->\", np.argmax(calculo) + 1, \"realmente es \", Y[i])\n\n\n\nprint(\"FIN\")", "meta": {"hexsha": "db47b83845e2184e5a4a3b485bcd546594780c68", "size": 1988, "ext": "py", "lang": "Python", "max_stars_repo_path": "Practica3/part1/Practica3_p1.py", "max_stars_repo_name": "Rasan98/AA", "max_stars_repo_head_hexsha": "0d755f3564483649dc1cfa9e127f4f66dcb533f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Practica3/part1/Practica3_p1.py", "max_issues_repo_name": "Rasan98/AA", "max_issues_repo_head_hexsha": "0d755f3564483649dc1cfa9e127f4f66dcb533f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Practica3/part1/Practica3_p1.py", "max_forks_repo_name": "Rasan98/AA", "max_forks_repo_head_hexsha": "0d755f3564483649dc1cfa9e127f4f66dcb533f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5432098765, "max_line_length": 94, "alphanum_fraction": 0.560362173, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241965169938, "lm_q2_score": 0.8933094159957174, "lm_q1q2_score": 0.8659064319011137}}
{"text": "import numpy as np\r\n\r\nL = [1,2,3]\r\nA = np.array(L)\r\n\r\nfor e in L:\r\n    print(e)\r\n\r\nfor e in A:\r\n    print(e)\r\n\r\nL.append(4)\r\nL = L + [5]\r\n\r\n\r\nL2 = []\r\nfor e in L:\r\n    L2.append(e+e)\r\n\r\nA+A\r\n2*A\r\n\r\n2*L\r\n\r\nL3 = []\r\nfor e in L:\r\n    L3.append(e*e)\r\n\r\nA**2\r\nnp.sqrt(A)\r\nnp.log(A)\r\nnp.exp(A)\r\n\r\n\r\na = np.array([1,2])\r\nb = np.array([2,1])\r\n\r\ndot = 0\r\nfor e,f in zip(a,b):\r\n    dot += e*f\r\n\r\n# elementwise multiplication\r\na*b\r\n\r\n# dot product (inner product)\r\nnp.sum(a*b)\r\n(a*b).sum()\r\n\r\nnp.dot(a,b)\r\na.dot(b)\r\nb.dot(a)\r\nnp.inner(a,b)\r\n\r\n# magnitude of a vector\r\namag = np.sqrt((a*a).sum())\r\namag = np.linalg.norm(a)\r\n\r\n# angle between two vectors\r\ncosangle = a.dot(b) / (np.linalg.norm(a)*np.linalg.norm(b))\r\nangle = np.arccos(cosangle)\r\n\r\n\r\n# matrix\r\nL = [[1,2], [3,4]]\r\nM = np.array(L)\r\n\r\nL[0]\r\nL[0][0]\r\n\r\nM[0][0]\r\nM[0,0]\r\n\r\nM2 = np.matrix(L) # recommended: use np.array instead!!!\r\n\r\nA = np.array(M2)\r\nA\r\n\r\n# transpose\r\nA.T\r\n\r\n# generating arrays and matrices\r\nZ = np.zeros(10)\r\nZM = np.zeros((10,10))\r\n\r\nOM = np.ones((10,10))\r\n\r\nRM = np.random.random((10,10)) # uniformly distributed numbers between 0..1\r\nGM = np.random.randn(10,10) # Gaussian distribution (note: no tuple!)\r\n\r\nGM.mean()\r\nGM.var()\r\n\r\n\r\n# elementwise matrix multiplication:\r\nA = np.array([[1,2],[3,4]])\r\nB = np.array([[5,6],[7,8]])\r\nA*B\r\n\r\n# matrix multiplication:\r\nA = np.array([[1,2],[3,4]])\r\nB = np.array([[5,6,7],[7,8,9]])\r\nA.dot(B)\r\n\r\n# inverse:\r\nAinv = np.linalg.inv(A)\r\nAinv.dot(A)\r\nA.dot(Ainv)\r\n\r\n# determinant:\r\nnp.linalg.det(A)\r\n\r\n# diagonal elements of a matrix:\r\nnp.diag(A)\r\n\r\n# constructing a diagonal matrix:\r\nnp.diag([1,2])\r\n\r\n# outer product:\r\na = np.array([1,2])\r\nb = np.array([3,4])\r\nnp.outer(a,b)\r\n\r\n# trace (sum of the diagnoal elements):\r\nnp.diag(A).sum()\r\nnp.trace(A)\r\n\r\n# covariance:\r\nX = np.random.randn(100,3)\r\ncov = np.cov(X)\r\ncov.shape\r\ncovT = np.cov(X.T)\r\ncovT.shape\r\n\r\n# eigenvalues, eigenvectors:\r\nnp.linalg.eigh(covT) # eigh is for symmetric (A=A^T) and Hermitian (A=A^H) matrices\r\nnp.linalg.eig(covT) # eig is for general matrices\r\n\r\n# solving a linear system of equations:\r\nA = np.array([[1,2], [3,4]])\r\nb = np.array([1,2])\r\nx = np.linalg.inv(A).dot(b)\r\n\r\nnp.linalg.solve(A, b)\r\n", "meta": {"hexsha": "46cea2b3ee42068047bf569c868d77ef9ba12fd4", "size": 2178, "ext": "py", "lang": "Python", "max_stars_repo_path": "udemy/lazyprogrammer/numpy-stack/numpy_test.py", "max_stars_repo_name": "balazssimon/ml-playground", "max_stars_repo_head_hexsha": "c2eba497bebc53e5a03807bdd8873c55f0ec73e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "udemy/lazyprogrammer/numpy-stack/numpy_test.py", "max_issues_repo_name": "balazssimon/ml-playground", "max_issues_repo_head_hexsha": "c2eba497bebc53e5a03807bdd8873c55f0ec73e1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "udemy/lazyprogrammer/numpy-stack/numpy_test.py", "max_forks_repo_name": "balazssimon/ml-playground", "max_forks_repo_head_hexsha": "c2eba497bebc53e5a03807bdd8873c55f0ec73e1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.125, "max_line_length": 84, "alphanum_fraction": 0.5771349862, "include": true, "reason": "import numpy", "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748207, "lm_q2_score": 0.90052978812007, "lm_q1q2_score": 0.8658898333941011}}
{"text": "#Mutlistep method: Adams Bashforth Method\nimport numpy as np \n\ndef dy(x,y):\n    dyvalue = x - y**2\n    return dyvalue\n\nx0= 0 ##least x value known\nxp1 = 0.1 \nxp2 = 0.2\nxp3 = 0.3 #highest x value known\n\nxfinal= 0.3\nh = 0.1\nn = int(((xfinal - x0)/h)) #if they give limits\n\ny0= 0.854 ## highest i of y value known\nym1 =  0.9145\nym2 = 1\nym3 = 0 ## least y value known\n\n\norder = 2\n##########\nx = np.zeros((n+order,1))\ny = np.zeros((n+order,1))\n\ni =0\n\nif order == 3:\n    p = order -1\n    y[p]= y0\n    y[p-1]= ym1\n    y[p-2]= ym2\n\n    x[p]= xp2\n    x[p-1]= xp1\n    x[p-2]= x0\n    while i<=(n+order):\n        print(\"order3\\n\")\n        y[p+1] = y[p] +(h/12)*(23*dy(x[p],y[p])-16*dy(x[p-1],y[p-1])+5*dy(x[p-2],y[p-2]))\n        x[p+1] = x[p] + h\n        print(\"y:\"+str(i)+str(y[p+1]))\n\n        p+=1\n        i+=1\nelif order == 2:\n    p = order -1\n    y[1]= y0\n    y[0]= ym1\n\n    x[1]= xp1\n    x[0]= x0\n    while i<=(n+order):\n        print(\"order2\\n\")\n        y[p+1] = y[p] +(h/2)*(3*dy(x[p],y[p])-dy(x[p-1],y[p-1]))\n        x[p+1] = x[p] + h\n        print(\"y:\"+str(i)+str(y[p+1]))\n\n        p+=1\n        i+=1\nelif order == 4:\n    p = order-1\n    y[3]= y0\n    y[2]= ym1\n    y[1]= ym2\n    y[0]= ym3\n\n    x[3]= xp3\n    x[2]= xp2\n    x[1]= xp1\n    x[0]= x0\n    while i<=(n+order):\n        print(\"order4\\n\")\n        y[p+1] = y[p] +(h/24)*(55*dy(x[p],y[p])-59*dy(x[p-1],y[p-1])+37*dy(x[p-2],y[p-2])-9*dy(x[p-3],y[p-3]))\n        x[p+1] = x[p] + h\n        print(\"y:\"+str(i)+str(y[p+1]))\n\n        p+=1\n        i+=1\n\n\n\n", "meta": {"hexsha": "b72ff7c8912726aba60e5305fbae4a7c6042503a", "size": 1497, "ext": "py", "lang": "Python", "max_stars_repo_path": "Adams Bashforth Method.py", "max_stars_repo_name": "pramotharun/Numerical-Methods-with-Python", "max_stars_repo_head_hexsha": "bd5676bcc4ac5defd13608728df2387b5fdcdfcb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Adams Bashforth Method.py", "max_issues_repo_name": "pramotharun/Numerical-Methods-with-Python", "max_issues_repo_head_hexsha": "bd5676bcc4ac5defd13608728df2387b5fdcdfcb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Adams Bashforth Method.py", "max_forks_repo_name": "pramotharun/Numerical-Methods-with-Python", "max_forks_repo_head_hexsha": "bd5676bcc4ac5defd13608728df2387b5fdcdfcb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8214285714, "max_line_length": 110, "alphanum_fraction": 0.4395457582, "include": true, "reason": "import numpy", "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377308419051, "lm_q2_score": 0.9032942034496964, "lm_q1q2_score": 0.865841576057318}}
{"text": "import numpy as np\n\n\ndef mean_square_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n    \"\"\"\n    Calculate MSE loss\n\n    Parameters\n    ----------\n    y_true: ndarray of shape (n_samples, )\n        True response values\n    y_pred: ndarray of shape (n_samples, )\n        Predicted response values\n\n    Returns\n    -------\n    MSE of given predictions\n    \"\"\"\n    los_sum = 0\n    for i in range(len(y_true)):\n        los_sum += ((y_true[i] - y_pred[i]) ** 2)\n\n    return los_sum / len(y_true)\n\n\ndef misclassification_error(y_true: np.ndarray, y_pred: np.ndarray,\n                            normalize: bool = True) -> float:\n    \"\"\"\n    Calculate misclassification loss\n\n    Parameters\n    ----------\n    y_true: ndarray of shape (n_samples, )\n        True response values\n    y_pred: ndarray of shape (n_samples, )\n        Predicted response values\n    normalize: bool, default = True\n        Normalize by number of samples or not\n\n    Returns\n    -------\n    Misclassification of given predictions\n    \"\"\"\n    size = y_pred.size\n    error_sum = 0\n\n    for i in range(size):\n        if y_pred[i] != y_true[i]:\n            error_sum += 1\n\n    return error_sum / size if normalize else error_sum\n\n\ndef accuracy(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n    \"\"\"\n    Calculate accuracy of given predictions\n\n    Parameters\n    ----------\n    y_true: ndarray of shape (n_samples, )\n        True response values\n    y_pred: ndarray of shape (n_samples, )\n        Predicted response values\n\n    Returns\n    -------\n    Accuracy of given predictions\n    \"\"\"\n    accurate_sum = 0\n    for i in range(y_true.size):\n        if y_true[i] == y_pred[i]:\n            accurate_sum += 1\n\n    return accurate_sum / y_true.size\n\n\ndef cross_entropy(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n    \"\"\"\n    Calculate the cross entropy of given predictions\n\n    Parameters\n    ----------\n    y_true: ndarray of shape (n_samples, )\n        True response values\n    y_pred: ndarray of shape (n_samples, )\n        Predicted response values\n\n    Returns\n    -------\n    Cross entropy of given predictions\n    \"\"\"\n    raise NotImplementedError()\n\n\nif __name__ == '__main__':\n    y_true = np.array([279000, 432000, 326000, 333000, 437400, 555950])\n    y_pred = np.array(\n        [199000.37562541, 452589.25533196, 345267.48129011, 345856.57131275,\n         563867.1347574, 395102.94362135])\n\n    print(mean_square_error(y_true, y_pred))\n", "meta": {"hexsha": "a5f47a98877159e9dffb7a057505008046d7d529", "size": 2428, "ext": "py", "lang": "Python", "max_stars_repo_path": "IMLearn/metrics/loss_functions.py", "max_stars_repo_name": "noamkari/IML.HUJI", "max_stars_repo_head_hexsha": "6708f8983dbbcddaba6caf7c759d6a24e0198e96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IMLearn/metrics/loss_functions.py", "max_issues_repo_name": "noamkari/IML.HUJI", "max_issues_repo_head_hexsha": "6708f8983dbbcddaba6caf7c759d6a24e0198e96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IMLearn/metrics/loss_functions.py", "max_forks_repo_name": "noamkari/IML.HUJI", "max_forks_repo_head_hexsha": "6708f8983dbbcddaba6caf7c759d6a24e0198e96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8039215686, "max_line_length": 76, "alphanum_fraction": 0.6140856672, "include": true, "reason": "import numpy", "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.958537730841905, "lm_q2_score": 0.903294196941332, "lm_q1q2_score": 0.8658415698188051}}
{"text": "\"\"\"\nDemonstration of Python Scientific computing.\n\nUses Newton Raphson's method as a vehicle.\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport scipy as sp\n\n\ndef myfunc(x):\n    \"\"\"\n    Generic function.\n\n    Parameters\n    ----------\n    x: float or array_like\n        The value or array at which to calculate the function\n\n    Examples\n    --------\n\n    Execution on a float\n\n    >>> from newton_raphson import *\n    >>> myfunc(3.0)\n        11.0\n\n    Execution on a SciPy array_like\n\n    >>> a = np.linspace(0,10,10)\n    >>> myfunc(a)\n        array([  -4.        ,   -0.54320988,    5.38271605,   13.77777778,\n             24.64197531,   37.97530864,   53.77777778,   72.04938272,\n             92.79012346,  116.        ])\n    \"\"\"\n    return x**2+2*x-4\n\n\ndef newton_raphson_plot(function, x0=0, dx=1e-10, eps=1e-10):\n    \"\"\"\n    Solve for a root of a function using Newton Raphson's method.\n\n    Also plots the process.\n\n    Parameters\n    ----------\n    function : string\n        String with name of function to be solved for *function(x) = 0*\n    x0       : float\n        Initial guess for *x* near *function(x) = 0*\n    dx       : float\n        Delta x used for finite difference calculation of slope\n    eps      : float\n        Absolute value of *function(x)* which is considered zero.\n\n    Examples\n    --------\n    >>> from newton_raphson import *\n    >>> def myfunc(x):\n    ...     return x**2+2*x-4\n    >>> function_name = 'myfunc'\n    >>> newton_raphson_plot(function_name, x0=2)\n        (1.23606797..., ...)\n    \"\"\"\n    deltax = 2 * eps\n    count = 0\n    x = x0\n    y = np.linspace(1, 6, 200)\n    plt.plot(y, globals()[function](y))\n    plt.ylabel('$f(x)$')\n    plt.xlabel('$x$')\n    plt.title('Newton Raphson search for solution to $f(x)=0$.')\n    plt.grid(True)\n    plt.plot(np.array([x0, x0]), np.array([globals()[function](x0), 0]), 'r')\n    plt.plot(np.array([x0]), np.array([globals()[function](x0)]), 'r*')\n    while abs(globals()[function](x)) > eps and count < 50:\n        count += 1\n        plt.plot(np.array([x, x]), np.array([globals()[function](x), 0]), 'r')\n        plt.plot(np.array([x]), np.array([globals()[function](x)]), 'r*')\n        f = globals()[function](x)\n        f2 = globals()[function](x + dx)\n        dfdx = (f2 - f) / dx\n        deltax = -f / dfdx\n        x = x + deltax\n        xr = np.linspace(x, x - deltax, 200)\n        y = xr * dfdx - x * dfdx\n        plt.plot(xr, y, 'y')  # Current point\n    return x, deltax\n\n\ndef newton_raphson(function, x0=0, dx=1e-10, eps=1e-10):\n    \"\"\"\n    Solve for a root of a function using Newton Raphson's method.\n\n    Parameters\n    ----------\n    function : string\n        String with name of function to be solved for *function(x) = 0*\n    x0       : float\n        Initial guess for *x* near *function(x) = 0*\n    dx       : float\n        Delta x used for finite difference calculation of slope\n    eps      : float\n        Absolute value of *function(x)* which is considered zero.\n\n    Examples\n    --------\n    >>> from newton_raphson import *\n    >>> def myfunc(x):\n    ...     return x**2+2*x-4\n    >>> function_name = 'myfunc'\n    >>> newton_raphson(function_name, x0=2)\n        (1.2360679..., ...)\n    \"\"\"\n    deltax = 2*eps\n    count = 0\n    x = x0\n    # loop until it converges, but no more than 50 times\n    while abs(deltax) > eps and count < 50:\n        count += 1 # I can add 1 to the variable *count*. Neat Python shortcut.\n        # This is a comment\n        # The next line is \"Matlab style\" and *bad*\n        #f = eval(function + '('+ str(x) + ')')\n        f = globals()[function](x)  #We explain later.\n        #f2 = eval(function + '('+ str(x+dx) + ')')\n        f2 = globals()[function](x+dx)\n        dfdx = (f2-f)/dx\n        deltax = -f/dfdx\n        x = x + deltax\n    return x, deltax\n", "meta": {"hexsha": "9fbc169b1924b4a2747d961efb2480b45fbc9af2", "size": 3779, "ext": "py", "lang": "Python", "max_stars_repo_path": "newton_raphson.py", "max_stars_repo_name": "josephcslater/JupyterExamples", "max_stars_repo_head_hexsha": "4f2af75b9fda80dcab6cac0b9210713eeb703839", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "newton_raphson.py", "max_issues_repo_name": "josephcslater/JupyterExamples", "max_issues_repo_head_hexsha": "4f2af75b9fda80dcab6cac0b9210713eeb703839", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "newton_raphson.py", "max_forks_repo_name": "josephcslater/JupyterExamples", "max_forks_repo_head_hexsha": "4f2af75b9fda80dcab6cac0b9210713eeb703839", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-07T20:28:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-07T20:28:39.000Z", "avg_line_length": 28.6287878788, "max_line_length": 79, "alphanum_fraction": 0.5472347182, "include": true, "reason": "import scipy", "num_tokens": 1139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875641, "lm_q2_score": 0.912436151547821, "lm_q1q2_score": 0.8658264169463188}}
{"text": "\"\"\"\nThis is a simple python program to generate pseudo random numbers between 0 and 1 using Linear Congruent method\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef rand_no_gen(seed, a, c, m, no_of_randnos):\n    \"\"\"\n    This function generates a numpy array of random numbers (positive integers) using Linear congruent method\n\n    If r_i is initial random number, the next random number in the sequence is given by\n    r_i+1 = (a*r_i + c) % m\n    The random numbers generated will start repeating after m numbers\n    Parameters\n    ----------\n    seed : int\n        The starting 'seed' for the random no. generator\n    a : int\n        The multiplying parameter for the random no. generator\n    c : int\n        The adding parameter for the random no. generator\n    m : int\n        m determines how many number of random nos can be generated. Repetition starts after m entries\n    no_of_randnos : int\n        Total no of random numbers (including seed) required\n\n    Returns\n    -------\n    randno_array : ndarray\n        A numpy array of the random nos generated\n\n    \"\"\"\n    randno_array = np.zeros(no_of_randnos)\n    randno_array[0] = seed\n    for i in range(no_of_randnos - 1):\n        randno_array[i + 1] = (a * randno_array[i] + c) % m\n    return randno_array\n\n\ndef random_generator_test(array_of_random_numbers):\n    if len(array_of_random_numbers) % 2 != 0:\n        mod_array = array_of_random_numbers[0:-1]\n    else:\n        mod_array = array_of_random_numbers\n    x_values = []\n    y_values = []\n\n    for i in range(len(mod_array)):\n        if i % 2 == 0:\n            x_values.append(mod_array[i])\n        else:\n            y_values.append(mod_array[i])\n\n    fig, ax = plt.subplots()\n    ax.scatter(x_values, y_values)\n    ax.set_xlabel('x')\n    ax.set_ylabel('y')\n    ax.set_title('Correlations of random nos')\n    ax.grid(True)\n    plt.show()\n\n\ndef main():\n    print('## A simple python script to generate random numbers ##')\n    no_of_randnos = int(input('Enter the number of random numbers that you want: '))\n    seed = int(input('Enter seed value: '))\n    a = int(input(\"Enter 'a' parameter for the generator: \"))\n    c = int(input(\"Enter 'c' parameter for the generator: \"))\n    m = int(input(\"Enter 'm' parameter for the generator: \"))\n    rand_array = rand_no_gen(seed, a, c, m, no_of_randnos)\n    print(f'The generated random numbers are {rand_array}')\n    random_generator_test(rand_array)\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "ddbb8770a06d1d88a94a861a1cd5a3f83894c3f4", "size": 2462, "ext": "py", "lang": "Python", "max_stars_repo_path": "04Monte_Carlo/rand_num_gen.py", "max_stars_repo_name": "AbhishekJaist/Computational_Physics", "max_stars_repo_head_hexsha": "7f04f0a8a725598fd77a5cea7874949f784ad256", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "04Monte_Carlo/rand_num_gen.py", "max_issues_repo_name": "AbhishekJaist/Computational_Physics", "max_issues_repo_head_hexsha": "7f04f0a8a725598fd77a5cea7874949f784ad256", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "04Monte_Carlo/rand_num_gen.py", "max_forks_repo_name": "AbhishekJaist/Computational_Physics", "max_forks_repo_head_hexsha": "7f04f0a8a725598fd77a5cea7874949f784ad256", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.775, "max_line_length": 111, "alphanum_fraction": 0.6584077985, "include": true, "reason": "import numpy", "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.9219218348550491, "lm_q1q2_score": 0.8657074842314023}}
{"text": "from scipy import stats\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport jax.scipy.stats as jstats\nfrom jax import grad\n\n\ndef main():\n\n    # various beta distribution shapes\n    x_vals = np.linspace(0.0, 1.0, 100)\n    plt.plot(x_vals, stats.beta.pdf(x_vals, a=0.5, b=0.5), label=f'a={0.5}, b={0.5}')\n    plt.plot(x_vals, stats.beta.pdf(x_vals, a=1.0, b=1.0), label=f'a={1.0}, b={1.0}')\n    plt.plot(x_vals, stats.beta.pdf(x_vals, a=10.0, b=10.0), label=f'a={10.0}, b={10.0}')\n    plt.plot(x_vals, stats.beta.pdf(x_vals, a=5.0, b=20.0), label=f'a={5.0}, b={20.0}')\n    plt.plot(x_vals, stats.beta.pdf(x_vals, a=20.0, b=5.0), label=f'a={20.0}, b={5.0}')\n    plt.ylabel('Beta PDF')\n    plt.xlabel('Action')\n    plt.legend()\n    plt.show()\n\n    # action distribution\n    plt.plot(x_vals, stats.beta.pdf(x_vals, a=2.0, b=2.0), label=f'a={2.0}, b={2.0}')\n    plt.axvline(0.1, color='red')\n    plt.legend()\n    plt.xlabel('Action')\n    plt.ylabel('Beta PDF')\n    plt.show()\n\n    # beta distribution at x=0.1 for varying values of a\n    a_vals = np.linspace(0.1, 2.0, 100)\n    pdf_at_x = [stats.beta.pdf(x=0.1, a=a, b=2.0) for a in a_vals]\n    plt.plot(a_vals, pdf_at_x)\n    plt.xlabel('a')\n    plt.ylabel('Beta PDF @ x=0.1, b=2.0')\n    plt.xlim((0.1, 2.0))\n    plt.show()\n\n    # modified beta distribution to increase the density at x=0.1\n    plt.plot(x_vals, stats.beta.pdf(x_vals, a=2.0, b=2.0), label=f'a={2.0}, b={2.0}')\n    plt.plot(x_vals, stats.beta.pdf(x_vals, a=0.6, b=2.0), label=f'a={0.6}, b={2.0}')\n    plt.axvline(0.1, color='red')\n    plt.legend()\n    plt.xlabel('Action')\n    plt.ylabel('Beta PDF')\n    plt.show()\n\n    # 1. Define the function for which we want a gradient.\n    def jax_beta_pdf(\n            x: float,\n            a: float,\n            b: float\n    ):\n        return jstats.beta.pdf(x=x, a=a, b=b, loc=0.0, scale=1.0)\n\n    # 2. Ask JAX for the gradient with respect to the second argument (shape parameter a).\n    jax_beta_pdf_grad = grad(jax_beta_pdf, argnums=1)\n\n    # 3. Calculate the gradient that we want.\n    print(f'{jax_beta_pdf_grad(0.1, 2.0, b=2.0)}')\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "d1907c6be743f6fc87bda4e9ec5e12a4bfb20130", "size": 2135, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/case_studies/mountain-car-continuous-figs/beta-dist.py", "max_stars_repo_name": "MatthewGerber/rl", "max_stars_repo_head_hexsha": "c323524be2a541b43b420a3da58e4675521b594f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/case_studies/mountain-car-continuous-figs/beta-dist.py", "max_issues_repo_name": "MatthewGerber/rl", "max_issues_repo_head_hexsha": "c323524be2a541b43b420a3da58e4675521b594f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/case_studies/mountain-car-continuous-figs/beta-dist.py", "max_forks_repo_name": "MatthewGerber/rl", "max_forks_repo_head_hexsha": "c323524be2a541b43b420a3da58e4675521b594f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8461538462, "max_line_length": 90, "alphanum_fraction": 0.6032786885, "include": true, "reason": "import numpy,from scipy,import jax,from jax", "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426473232578, "lm_q2_score": 0.8887587890727754, "lm_q1q2_score": 0.865688963740259}}
{"text": "import numpy as np\n\n\ndef angular_distance(lam1, lam2, phi1, phi2):\n    \"\"\"\n    Angular distance between points at lon-lat coordinates\n    (lam1, phi1) and (lam2, phi2) in degrees.\n\n    See https://en.wikipedia.org/wiki/Great-circle_distance\n    \"\"\"\n    return (\n        np.arccos(\n            np.sin(phi1 * np.pi / 180) * np.sin(phi2 * np.pi / 180)\n            + np.cos(phi1 * np.pi / 180)\n            * np.cos(phi2 * np.pi / 180)\n            * np.cos((lam2 - lam1) * np.pi / 180)\n        )\n        * 180\n        / np.pi\n    )\n\n\ndef fS_samp(r, N=100000):\n    \"\"\"\n    Fractional spot coverage area computed by sampling a bunch\n    of points on the sphere and computing the fraction that are\n    inside a spot of radius `r`.\n\n    See https://mathworld.wolfram.com/SpherePointPicking.html\n    \"\"\"\n    u = np.random.random(N)\n    v = np.random.random(N)\n    lam = 360 * u - 180\n    phi = np.arccos(2 * v - 1) * 180 / np.pi - 90\n    delta_angle = angular_distance(0, lam, 0, phi)\n    return np.array(\n        [np.count_nonzero(delta_angle <= r_) / N for r_ in np.atleast_1d(r)]\n    )\n\n\ndef fS_exact(r):\n    \"\"\"\n    Analytical expression for the fractional spot coverage.\n\n    \"\"\"\n    return 0.5 * (1 - np.cos(r * np.pi / 180))\n\n\ndef test_fS():\n    r = np.linspace(0, 45, 100)\n    assert np.allclose(fS_samp(r), fS_exact(r), atol=1e-2)\n", "meta": {"hexsha": "9c0ee9d408604f988d05fdbdc0728079be04c579", "size": 1330, "ext": "py", "lang": "Python", "max_stars_repo_path": "paper1/tests/test_fS.py", "max_stars_repo_name": "dfm/mapping_stellar_surfaces", "max_stars_repo_head_hexsha": "52d4ba1a726c65868e4a1290a801fe046fb2155f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-01-21T17:03:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T17:49:28.000Z", "max_issues_repo_path": "paper1/tests/test_fS.py", "max_issues_repo_name": "dfm/mapping_stellar_surfaces", "max_issues_repo_head_hexsha": "52d4ba1a726c65868e4a1290a801fe046fb2155f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-01-21T15:55:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-30T14:35:16.000Z", "max_forks_repo_path": "paper1/tests/test_fS.py", "max_forks_repo_name": "dfm/mapping_stellar_surfaces", "max_forks_repo_head_hexsha": "52d4ba1a726c65868e4a1290a801fe046fb2155f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-21T15:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-25T16:26:15.000Z", "avg_line_length": 25.5769230769, "max_line_length": 76, "alphanum_fraction": 0.5812030075, "include": true, "reason": "import numpy", "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995762509216, "lm_q2_score": 0.8962513842182775, "lm_q1q2_score": 0.8656888322307362}}
{"text": "import numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt \nimport os\nimport pyprobml_utils as pml\n\ndata_dir = \"../data\"\nimg = matplotlib.image.imread(os.path.join(data_dir, \"clown.png\"))\n\ndef rgb2gray(rgb):\n    return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])\n\nX = rgb2gray(img)    \n\nr = np.linalg.matrix_rank(X)\nprint(r)\n\nU, sigma, V = np.linalg.svd(X, full_matrices=True)\nranks = [1, 2, 5, 10, 20, r]\nR = len(ranks)\n\nfor i in range(R):\n    k = ranks[i]\n    #x_hat = np.matrix(U[:, :k]) * np.diag(sigma[:k]) * np.matrix(V[:k, :])  \n    x_hat = np.dot(np.dot(U[:, :k], np.diag(sigma[:k])), V[:k, :])  \n    plt.imshow(x_hat, cmap='gray')\n    plt.title(\"rank {}\".format(k))\n    plt.axis(\"off\")\n    pml.savefig(\"svdImageDemoClown{}.pdf\".format(k))\n    plt.show()\n\nk = 100\nplt.plot(np.log(sigma[:k]), 'r-', linewidth=4, label=\"Original\")\nplt.ylabel(r\"$log(\\sigma_i)$\")\nplt.xlabel(\"i\")\n\n\n# Compare this to a random shuffled version of the image\nx2 = np.random.permutation(X)\n# so we convert to a 1d vector, permute, and convert back\nx1d = X.ravel()\nnp.random.shuffle(x1d) # inplace\nx2 = x1d.reshape(X.shape)\nU, sigma2, V = np.linalg.svd(x2, full_matrices = False)\nplt.plot(np.log(sigma2[:k]), 'b', linewidth=4, label=\"Randomized\")\nplt.legend()\npml.savefig(\"svdImageDemoClownSigmaScrambled.pdf\")\nplt.show()\n", "meta": {"hexsha": "4c2b1589f38f0d91f3318bf0cbcc7f89f4896fcc", "size": 1316, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/svd_image_demo.py", "max_stars_repo_name": "karalleyna/pyprobml", "max_stars_repo_head_hexsha": "72195e46fdffc4418910e76d02e3d6469f4ce272", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/svd_image_demo.py", "max_issues_repo_name": "karalleyna/pyprobml", "max_issues_repo_head_hexsha": "72195e46fdffc4418910e76d02e3d6469f4ce272", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/svd_image_demo.py", "max_forks_repo_name": "karalleyna/pyprobml", "max_forks_repo_head_hexsha": "72195e46fdffc4418910e76d02e3d6469f4ce272", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8571428571, "max_line_length": 77, "alphanum_fraction": 0.6519756839, "include": true, "reason": "import numpy", "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244552, "lm_q2_score": 0.8962513675912913, "lm_q1q2_score": 0.8656888126516364}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\"\"\"\nGenerates a Geometric Brownian Motion timeseries.\nArgs:\n    S0: the first term in the timeseries\n    mu: the drift parameter of the GBM\n    sigma: the volatility parameter of the GBM\n    num_periods: the number of periods to model\n    increments_per_period: the number of increments in the timeseries per period\n\"\"\"\ndef gbm(S0, mu, sigma, num_periods, increments_per_period):\n    T = num_periods\n    dt = 1/increments_per_period\n    N = num_periods*increments_per_period\n    t = np.linspace(0, T, N)\n    W = np.random.standard_normal(size = N) \n    W = np.cumsum(W)*np.sqrt(dt) # standard brownian motion\n    X = (mu-0.5*sigma**2)*t + sigma*W \n    S = S0*np.exp(X) # geometric brownian motion\n    return S\n\n\"\"\"\nGenerates a cyclical timeseries, each cycle modeled independently by a Geometric Brownian Motion.\nThis is a useful function for simulating macroeconomic variables like GDP.\nArgs:\n    S0: the first term in the timeseries\n    mu_boom: the drift parameter of the GBM in a boom cycle (positive)\n    mu_bust: the drift parameter of the GBM in a bust cycle (negative)\n    sigma: the volatility parameter of the GBM\n    cycle_lengths: an array of integers specifying the length of each cycle (number of periods)\n    increments_per_period: the number of increments in the timeseries per period\n\ncycle_lengths could be [2,4,3,4] for example, specifying four cycles with lenghts 2, 4, 3 and 4 periods respectively.\nCycles alternate between boom and bust. The first cycle is always a boom.\n\"\"\"\ndef gbm_cyclical(S0, mu_boom, mu_bust, sigma, cycle_lengths, increments_per_period):\n    cycle_lengths = np.array(cycle_lengths)\n    cycle_lengths *= increments_per_period\n    \n    dt = 1\n    mu_boom = mu_boom/increments_per_period\n    mu_bust = mu_bust/increments_per_period\n    sigma = np.sqrt(sigma**2/increments_per_period)\n\n    cycles = np.array([[]])\n    for i, cycle_length in enumerate(cycle_lengths):\n        cycle_mu = mu_boom if i%2 == 0 else mu_bust\n        cycle = np.exp((cycle_mu-sigma**2/2)*dt)*np.exp(sigma*np.random.normal(0, np.sqrt(dt), (1,cycle_length)))\n        cycles = np.concatenate((cycles, cycle), axis=1)\n\n    return S0*cycles.cumprod()\n\nif __name__ == '__main__':\n    # demonstrates the usage of gbm and gbm_cyclical\n    np.random.seed(0)\n    t = range(0, 520)\n    S = gbm(1, 0.05, 0.5, 10, 52)\n    S_cyclical = gbm_cyclical(1, 0.34, -0.2, 0.3, [2,3,5], 52)\n    plt.plot(t, S, S_cyclical)\n    plt.show()\n", "meta": {"hexsha": "dc3beea6fad07370ed1e0c5e4c83dbc97b2c96bc", "size": 2483, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/gbm.py", "max_stars_repo_name": "terra-project/research", "max_stars_repo_head_hexsha": "1215fa6426eddb386c050a33cdfa3da8fc39eb3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 43, "max_stars_repo_stars_event_min_datetime": "2019-04-01T06:52:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-12T20:38:30.000Z", "max_issues_repo_path": "utils/gbm.py", "max_issues_repo_name": "terra-money/research", "max_issues_repo_head_hexsha": "1215fa6426eddb386c050a33cdfa3da8fc39eb3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-03-07T13:41:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-18T11:46:21.000Z", "max_forks_repo_path": "utils/gbm.py", "max_forks_repo_name": "terra-project/research", "max_forks_repo_head_hexsha": "1215fa6426eddb386c050a33cdfa3da8fc39eb3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-04-02T01:43:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T07:08:44.000Z", "avg_line_length": 39.4126984127, "max_line_length": 117, "alphanum_fraction": 0.7104309303, "include": true, "reason": "import numpy", "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214511730025, "lm_q2_score": 0.8976952982655951, "lm_q1q2_score": 0.86566683273466}}
{"text": "\"\"\"\nbase.py\n=======\n\nFundamental components for a simple python number theory library.\n\nLicense Info\n============\n\n(c) David Lowry-Duda 2018 <davidlowryduda@davidlowryduda.com>\n\nThis is available under the MIT License. See\n<https://opensource.org/licenses/MIT> for a copy of the license,\nor see the home github repo\n<https://github.com/davidlowryduda/pynt>.\n\"\"\"\nfrom typing import List, Tuple, Union\nfrom itertools import product as cartesian_product\nimport numpy\n\n\ndef gcd(num1: int, num2: int) -> int:\n    \"\"\"\n    Returns the greatest common divisor of `num1` and `num2`.\n\n    Examples:\n    >>> gcd(12, 30)\n    6\n    >>> gcd(0, 0)\n    0\n    >>> gcd(-1001, 26)\n    13\n    \"\"\"\n    if num1 == 0:\n        return num2\n    if num2 == 0:\n        return num1\n    if num1 < 0:\n        num1 = -num1\n    if num2 < 0:\n        num2 = -num2\n    # This is the Euclidean algorithm\n    while num2 != 0:\n        num1, num2 = num2, num1 % num2\n    return num1\n\n\ndef smallest_prime_divisor(num: int, bound: Union[int, None] = None) -> int:\n    \"\"\"\n    Returns the smallest prime divisor of the input `num` if that divisor is\n    at most `bound`. If none are found, this returns `num`.\n\n    Input:\n        num: a positive integer\n        bound: an optional bound on the size of the primes to check. If not\n               given, then it defaults to `num`.\n\n    Output:\n        The smallest prime divisor of `num`, or `num` itself if that divisor is\n        at least as large as `bound`.\n\n    Raises:\n        ValueError: if num < 1.\n\n    Examples:\n    >>> smallest_prime_divisor(15)\n    3\n    >>> smallest_prime_divisor(1001)\n    7\n    \"\"\"\n    if num < 1:\n        raise ValueError(\"A positive integer is expected.\")\n    if num == 1:\n        return num\n    for prime in [2, 3, 5]:\n        if num % prime == 0:\n            return prime\n    if bound is None:\n        bound = num\n    # Possible prime locations mod 2*3*5=30\n    diffs = [6, 4, 2, 4, 2, 4, 6, 2]\n    cand = 7\n    i = 1\n    while cand <= bound and cand*cand <= num:\n        if num % cand == 0:\n            return cand\n        cand += diffs[i]\n        i = (i + 1) % 8\n    return num\n\n\n# primesfrom2to(n) from\n# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n\ndef primes(limit):\n    \"\"\"\n    Returns the numpy array of primes up to (and not including) `limit`.\n\n    Examples:\n    >>> primes(10)\n    array([2, 3, 5, 7])\n    \"\"\"\n    sieve = numpy.ones(limit // 3 + (limit % 6 == 2), dtype=numpy.bool)\n    for i in range(1, int(limit ** 0.5) // 3 + 1):\n        if sieve[i]:\n            k = (3 * i + 1) | 1\n            sieve[k * k // 3::2 * k] = False\n            sieve[k * (k - 2 * (i & 1) + 4) // 3:: 2 * k] = False\n    return numpy.r_[2, 3, ((3 * numpy.nonzero(sieve)[0][1:] + 1) | 1)]\n\n\ndef factor(num: int) -> List[Tuple[int, int]]:\n    \"\"\"\n    Returns the factorization of `num` as a list of tuples of the form (p, e)\n    where `p` is a prime and `e` is the exponent of that prime in the\n    factorization.\n\n    Input:\n        num: an integer to factor\n\n    Output:\n        a list of tuples (p, e), sorted by the size of p.\n\n    Examples:\n    >>> factor(100)\n    [(2, 2), (5, 2)]\n    >>> factor(-7007)\n    [(7, 2), (11, 1), (13, 1)]\n    >>> factor(1)\n    []\n    \"\"\"\n    if num in (-1, 0, 1):\n        return []\n    if num < 0:\n        num = -num\n    factors = []\n    while num != 1:\n        prime = smallest_prime_divisor(num)\n        exp = 1\n        num = num // prime\n        while num % prime == 0:\n            exp += 1\n            num = num // prime\n        factors.append((prime, exp))\n    return factors\n\n\ndef factors(num: int) -> List[int]:\n    \"\"\"\n    Returns the list of factors of an integer.\n\n    Examples:\n    >>> factors(6)\n    [1, 2, 3, 6]\n    >>> factors(30)\n    [1, 2, 3, 5, 6, 10, 15, 30]\n    \"\"\"\n    factorization = factor(num)\n    primes_, exps = zip(*factorization)\n    exp_choices = cartesian_product(*[range(exp+1) for exp in exps])\n    ret = []\n    for exp_choice in exp_choices:\n        val = 1\n        for prime, exp in zip(primes_, exp_choice):\n            val *= (prime**exp)\n        ret.append(val)\n    return sorted(ret)\n", "meta": {"hexsha": "3c201b146c812edf0c1802662b27659b6909132c", "size": 4122, "ext": "py", "lang": "Python", "max_stars_repo_path": "pynt/base.py", "max_stars_repo_name": "davidlowryduda/pynt", "max_stars_repo_head_hexsha": "f56c7d3ea5dfa5df4558205d39316fd58f66cad1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pynt/base.py", "max_issues_repo_name": "davidlowryduda/pynt", "max_issues_repo_head_hexsha": "f56c7d3ea5dfa5df4558205d39316fd58f66cad1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pynt/base.py", "max_forks_repo_name": "davidlowryduda/pynt", "max_forks_repo_head_hexsha": "f56c7d3ea5dfa5df4558205d39316fd58f66cad1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6826347305, "max_line_length": 84, "alphanum_fraction": 0.5492479379, "include": true, "reason": "import numpy", "num_tokens": 1262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.9273632921335859, "lm_q1q2_score": 0.8656294750472481}}
{"text": "# log_posterior_probs function was implemented in October 2021 by\n# Pascal Lieberherr, Zador Pataki, Timo Schönegg\n\nimport numpy\nfrom scipy.stats import laplace, norm, t\nimport scipy\nimport math\nimport numpy as np\nfrom scipy.special import logsumexp\n\nVARIANCE = 2.0\n\nnormal_scale = math.sqrt(VARIANCE)\nstudent_t_df = (2 * VARIANCE) / (VARIANCE - 1)\nlaplace_scale = VARIANCE / 2\n\nHYPOTHESIS_SPACE = [norm(loc=0.0, scale=math.sqrt(VARIANCE)),\n                    laplace(loc=0.0, scale=laplace_scale),\n                    t(df=student_t_df)]\n\nPRIOR_PROBS = np.array([0.35, 0.25, 0.4])\n\n\ndef generate_sample(n_samples, seed=None):\n    \"\"\" data generating process of the Bayesian model \"\"\"\n    random_state = np.random.RandomState(seed)\n    hypothesis_idx = np.random.choice(3, p=PRIOR_PROBS)\n    dist = HYPOTHESIS_SPACE[hypothesis_idx]\n    return dist.rvs(n_samples, random_state=random_state)\n\n\n\"\"\" Solution \"\"\"\n\nfrom scipy.special import logsumexp\n\n\ndef log_posterior_probs(x):\n    \"\"\"\n    Computes the log posterior probabilities for the three hypotheses, given the data x\n\n    Args:\n        x (np.ndarray): one-dimensional numpy array containing the training data\n    Returns:\n        log_posterior_probs (np.ndarray): a numpy array of size 3, containing the Bayesian log-posterior probabilities\n                                          corresponding to the three hypotheses\n    \"\"\"\n    assert x.ndim == 1\n\n    # p1 = sum(log p(xi | H1)) + log(p(H1)) - log(prod(p(x1|H1))*p(H1)+prod(p(x2|H2))*p(H2)+prod(p(x3|H3))*p(H3))\n    # p1 ~ sum(log p(xi | H1)) + log(p(H1)) - LSE(log(prod(p(x1|H1))*p(H1)), prod(p(x2|H2))*p(H2), prod(p(x3|H3))*p(H3))   # https://en.wikipedia.org/wiki/LogSumExp\n    # p1 ~ sum(log p(xi | H1)) + log(p(H1)) - LSE(sum(log(p(x1|H1))) + log(p(H1)), ...)\n\n    log_p_h1 = np.log(PRIOR_PROBS[0])\n    log_p_h2 = np.log(PRIOR_PROBS[1])\n    log_p_h3 = np.log(PRIOR_PROBS[2])\n\n    sum_log_p_x_given_h1 = 0\n    sum_log_p_x_given_h2 = 0\n    sum_log_p_x_given_h3 = 0\n\n    for xi in np.nditer(x):\n        sum_log_p_x_given_h1 += np.log(norm.pdf(xi, loc=0.0, scale=math.sqrt(VARIANCE)))\n        sum_log_p_x_given_h2 += np.log(laplace.pdf(xi, loc=0.0, scale=laplace_scale))\n        sum_log_p_x_given_h3 += np.log(t.pdf(xi, df=student_t_df))\n    \n    lse_123 = logsumexp(np.array([sum_log_p_x_given_h1 + log_p_h1, sum_log_p_x_given_h2 + log_p_h2, sum_log_p_x_given_h3 + log_p_h3]))\n\n    log_p_1 = sum_log_p_x_given_h1 + log_p_h1 - lse_123\n    log_p_2 = sum_log_p_x_given_h2 + log_p_h2 - lse_123\n    log_p_3 = sum_log_p_x_given_h3 + log_p_h3 - lse_123\n\n    log_p = np.array([log_p_1, log_p_2, log_p_3])\n    \n    assert log_p.shape == (3,)\n    return log_p\n\n\ndef posterior_probs(x):\n    return np.exp(log_posterior_probs(x))\n\n\n\"\"\" \"\"\"\n\n\ndef main():\n    \"\"\" sample from Laplace dist \"\"\"\n    dist = HYPOTHESIS_SPACE[1]\n    x = dist.rvs(1000, random_state=28)\n\n    print(\"Posterior probs for 1 sample from Laplacian\")\n    p = posterior_probs(x[:1])\n    print(\"Normal: %.4f , Laplace: %.4f, Student-t: %.4f\\n\" % tuple(p))\n\n    print(\"Posterior probs for 100 samples from Laplacian\")\n    p = posterior_probs(x[:50])\n    print(\"Normal: %.4f , Laplace: %.4f, Student-t: %.4f\\n\" % tuple(p))\n\n    print(\"Posterior probs for 1000 samples from Laplacian\")\n    p = posterior_probs(x[:1000])\n    print(\"Normal: %.4f , Laplace: %.4f, Student-t: %.4f\\n\" % tuple(p))\n\n    print(\"Posterior for 100 samples from the Bayesian data generating process\")\n    x = generate_sample(n_samples=100)\n    p = posterior_probs(x)\n\n    print(\"Normal: %.4f , Laplace: %.4f, Student-t: %.4f\\n\" % tuple(p))\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "7980296aa2d883a768a17e8a2e4c72138b90c681", "size": 3618, "ext": "py", "lang": "Python", "max_stars_repo_path": "task0_bayesian_inference/solution.py", "max_stars_repo_name": "Zador-Pataki/Probabilistic-Artificial-Intelligence-Projects", "max_stars_repo_head_hexsha": "914612effc92a9ee2b8ef74dbdbacddc9222fbac", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "task0_bayesian_inference/solution.py", "max_issues_repo_name": "Zador-Pataki/Probabilistic-Artificial-Intelligence-Projects", "max_issues_repo_head_hexsha": "914612effc92a9ee2b8ef74dbdbacddc9222fbac", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "task0_bayesian_inference/solution.py", "max_forks_repo_name": "Zador-Pataki/Probabilistic-Artificial-Intelligence-Projects", "max_forks_repo_head_hexsha": "914612effc92a9ee2b8ef74dbdbacddc9222fbac", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5945945946, "max_line_length": 164, "alphanum_fraction": 0.6594803759, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762055074521, "lm_q2_score": 0.9019206752113866, "lm_q1q2_score": 0.86562924075508}}
{"text": "# # Exponential functions and logarithms\n\nimport math\nimport numpy as np\n\n\n# ## Exponential functions\n\n# What is **e**? It is simply a number (known as Euler's number):\n\nmath.e\n\n\n# **e** is a significant number, because it is the base rate of growth shared by all continually growing processes.\n# \n# For example, if I have **10 dollars**, and it grows 100% in 1 year (compounding continuously), I end up with **10\\*e^1 dollars**:\n\n# 100% growth for 1 year\n10 * np.exp(1)\n\n\n# 100% growth for 2 years\n10 * np.exp(2)\n\n\n# Side note: When e is raised to a power, it is known as **the exponential function**. Technically, any number can be the base, and it would still be known as **an exponential function** (such as 2^5). But in our context, the base of the exponential function is assumed to be e.\n# \n# Anyway, what if I only have 20% growth instead of 100% growth?\n\n# 20% growth for 1 year\n10 * np.exp(0.20)\n\n\n# 20% growth for 2 years\n10 * np.exp(0.20 * 2)\n\n\n# ## Logarithms\n\n# What is the **(natural) logarithm**? It gives you the time needed to reach a certain level of growth. For example, if I want growth by a factor of 2.718, it will take me 1 unit of time (assuming a 100% growth rate):\n\n# time needed to grow 1 unit to 2.718 units\nnp.log(2.718)\n\n\n# If I want growth by a factor of 7.389, it will take me 2 units of time:\n\n# time needed to grow 1 unit to 7.389 units\nnp.log(7.389)\n\n\n# If I want growth by a factor of 1, it will take me 0 units of time:\n\n# time needed to grow 1 unit to 1 unit\nnp.log(1)\n\n\n# If I want growth by a factor of 0.5, it will take me -0.693 units of time (which is like looking back in time):\n\n# time needed to grow 1 unit to 0.5 units\nnp.log(0.5)\n\n\n# ## Connecting the concepts\n\n# As you can see, the exponential function and the natural logarithm are **inverses** of one another:\n\nnp.log(np.exp(5))\n\n\nnp.exp(np.log(5))\n", "meta": {"hexsha": "8a3fdf08040ef627199df5abdb36ae2a082baf5c", "size": 1852, "ext": "py", "lang": "Python", "max_stars_repo_path": "ML/DAT8-master/code/12_e_log_examples_nb.py", "max_stars_repo_name": "praveenpmin/Python", "max_stars_repo_head_hexsha": "513fcde7430b03a187e2c7e58302b88645388eed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ML/DAT8-master/code/12_e_log_examples_nb.py", "max_issues_repo_name": "praveenpmin/Python", "max_issues_repo_head_hexsha": "513fcde7430b03a187e2c7e58302b88645388eed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ML/DAT8-master/code/12_e_log_examples_nb.py", "max_forks_repo_name": "praveenpmin/Python", "max_forks_repo_head_hexsha": "513fcde7430b03a187e2c7e58302b88645388eed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7222222222, "max_line_length": 278, "alphanum_fraction": 0.6960043197, "include": true, "reason": "import numpy", "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620573763841, "lm_q2_score": 0.9019206692796966, "lm_q1q2_score": 0.8656292371381669}}
{"text": "# @Time: 2022/4/13 21:18\n# @Author: chang liu\n# @Email: chang_liu_tamu@gmail.com\n# @File:3.10.Performing_Matrix_and_Linear_algebra_calculations.py\n\n\nimport numpy as np\nfrom numpy import linalg as nlg\n\nm = np.arange(9).reshape((3, 3))\nprint(m)\nprint(m.T)\n# print(nlg.inv(m))\n\nv = np.arange(2, 5).reshape(3, 1)\nprint(v)\n\nprint(m * v)\nprint(m @ v)\n\nprint(nlg.det(m))\nprint(nlg.eigvals(m))\n\n\n\n# nlg.solve(m, v) #solve linear systems\n", "meta": {"hexsha": "46f591d3b800cd546b0d01cafcbc3b1785835a1d", "size": 429, "ext": "py", "lang": "Python", "max_stars_repo_path": "CH03_Numbers_Dates_Times/3.10.Performing_Matrix_and_Linear_algebra_calculations.py", "max_stars_repo_name": "Chang-Liu-TAMU/Python-Cookbook-reading", "max_stars_repo_head_hexsha": "7b974c32f77b4b3d7cfeed30d1671081057c566f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CH03_Numbers_Dates_Times/3.10.Performing_Matrix_and_Linear_algebra_calculations.py", "max_issues_repo_name": "Chang-Liu-TAMU/Python-Cookbook-reading", "max_issues_repo_head_hexsha": "7b974c32f77b4b3d7cfeed30d1671081057c566f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CH03_Numbers_Dates_Times/3.10.Performing_Matrix_and_Linear_algebra_calculations.py", "max_forks_repo_name": "Chang-Liu-TAMU/Python-Cookbook-reading", "max_forks_repo_head_hexsha": "7b974c32f77b4b3d7cfeed30d1671081057c566f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.8888888889, "max_line_length": 65, "alphanum_fraction": 0.6876456876, "include": true, "reason": "import numpy,from numpy", "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9674102589923637, "lm_q2_score": 0.8947894724152068, "lm_q1q2_score": 0.8656285152528357}}
{"text": "import numpy as np\nfrom linear_programming.simplex_algorithm import SimplexAlgorithm\n\n\n# object  min Z = -3 * x1 + x2 + x3\n# s.t.\n#       x1 - 2 * x2 +     x3 <= -11\n#  -4 * x1 +     x2 + 2 * x3 >= 3\n#   2 * x1 -              x3 = -1\n#   x_i >= 0 (i = 1,2,3)\n\n# A = np.array([[1, -2, 1], [-4, 1, 2], [2, 0, -1]])\n# B = np.array([11, 3, -1])\n# Z = np.array([-3, 1, 1])  # min\n# restrict = ['<=', '>=', '=']\n# mode = 'min'\n\n\n# A = np.array([[-1, 2], [0, 1]])\n# B = np.array([2, 3])\n# Z = np.array([1, 2]) # max\n# restrict = ['<=', '<=']\n# mode = 'max'\n\n# A = np.array([[1, 2, 2, 1, 0], [3, 4, 1, 0, 1]])\n# B = np.array([8, 7])\n# Z = np.array([5, 2, 3, -1, 1])\n# restrict = ['=', '=']\n# mode = 'max'\n\n# A = np.array([[-2, 2, 1, 0], [3, 1, 0, 1]])\n# B = np.array([4, 6])\n# Z = np.array([3, 1, 1, 1])\n# restrict = ['=', '=']\n# mode = 'min'\n\n# A = np.array([[4, 5], [5, 2]])\n# B = np.array([100, 80])\n# Z = np.array([10, 5])    # max\n# restrict = ['<=', '<=']\n# mode = 'max'\n\nA = np.array([[1, 0], [1, 2], [0, 1]])\nB = np.array([5, 10, 4])\nZ = np.array([1, 3])    # max\nrestrict = ['<=', '<=', '<=']\nmode = 'max'\n\nif __name__ == '__main__':\n    x, optimal = SimplexAlgorithm(A, B, Z, mode, restrict).run()\n    print('最优解', x)\n    print('目标函数最优值', optimal[0])\n", "meta": {"hexsha": "48071b677195d69e2e0f5b33d54c15e2d73edc8e", "size": 1253, "ext": "py", "lang": "Python", "max_stars_repo_path": "test.py", "max_stars_repo_name": "flsq2020/operational-research-optimization", "max_stars_repo_head_hexsha": "928cbeb4e927106cb37e15b38ba15cc7222ec9d9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-08T11:51:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-08T11:51:11.000Z", "max_issues_repo_path": "test.py", "max_issues_repo_name": "flsq2020/operational-research-optimization", "max_issues_repo_head_hexsha": "928cbeb4e927106cb37e15b38ba15cc7222ec9d9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test.py", "max_forks_repo_name": "flsq2020/operational-research-optimization", "max_forks_repo_head_hexsha": "928cbeb4e927106cb37e15b38ba15cc7222ec9d9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.641509434, "max_line_length": 65, "alphanum_fraction": 0.431763767, "include": true, "reason": "import numpy", "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102580527665, "lm_q2_score": 0.8947894654011352, "lm_q1q2_score": 0.8656285076266093}}
{"text": "# This program and its computation instruction was written by Andre Christoga Pramaditya (drepram.com) with the student ID (2006570006).\n# Program dan instruksi komputasi ini ditulis oleh Andre Christoga Pramaditya (drepram.com) dengan Nomor Pokok Mahasiswa (2006570006).\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings(\"ignore\") # insert programmer laziness joke here\n\nsize_ten = 10\nsize_hundred = 100\nsize_thousand = 1000\nsize_million = 1000000\n\n# Case 1 on the task said to retrieve n=10 random numbers from the uniform distribution [1,10]\n\n# Remembering the set notation of [low, high), where low is included and high is excluded. \n# We could check the validity of our computation with the functions that we would show below (via console logging)\n\ncase_1_histogram = plt.figure(1, figsize=(7,7))\n\ncase_1_sample_ten = np.random.uniform(1,10,10)\nprint(\"For we are supposed to retrieve random numbers from [1,10], it begs the question as to whether the intervals are actually included in our computation.\\n\")\nprint(\"Does the random distribution of (low=1,high=10,size=10) includes samples from numbers that is less or equal to 10?\", np.all(case_1_sample_ten <= 10))\nprint(\"Does the random distribution of (low=1,high=10,size=10) includes samples from numbers that is greater or equal to 1?\", np.all(case_1_sample_ten >= 1))\nprint(\"\\nAs the questions above has been answered, we will proceed to show the graph of other uniform distributions with differing number of sample size.\")\n\ncase_1_sample_hundred = np.random.uniform(1,10,100)\ncase_1_sample_thousand = np.random.uniform(1,10,1000)\ncase_1_sample_million = np.random.uniform(1,10,1000000)\n\nplt.hist(case_1_sample_ten, 15, density=True)\nplt.hist(case_1_sample_hundred, 15, density=True)\nplt.hist(case_1_sample_thousand, 15, density=True)\nplt.hist(case_1_sample_million, 15, density=True)\n\ncase_1_histogram.suptitle('Uniform Distribution Case 1 Combined Histogram', fontsize=14, fontweight='bold')\ncase_1_axes_title = case_1_histogram.add_subplot(111)\ncase_1_histogram.subplots_adjust(top=0.85)\ncase_1_axes_title.set_title('retrieve n=10 random numbers from the uniform distribution [1,10] \\nwith n iterating from 10,100,1000,1000000')\ncase_1_histogram.show()\n\nprint(\"\\n---\\nNow on to the second case.\\n\")\n\ncase_2_histogram = plt.figure(2, figsize=(7,7))\n\ncase_2_sample_ten = np.random.uniform(25,100,10)\nprint(\"For we are supposed to retrieve random numbers from [25,100], it begs the question as to whether the intervals are actually included in our computation.\\n\")\nprint(\"Does the random distribution of (low=25,high=100,size=10) includes samples from numbers that is less or equal to 25?\", np.all(case_2_sample_ten <= 25))\nprint(\"Does the random distribution of (low=25,high=100,size=10) includes samples from numbers that is greater or equal to 10?\", np.all(case_2_sample_ten >= 10))\nprint(\"\\nAs the questions above has been answered, we will proceed to show the graph of other uniform distributions with differing number of sample size.\")\n\ncase_2_sample_hundred = np.random.uniform(25,100,100)\ncase_2_sample_thousand = np.random.uniform(25,100,1000)\ncase_2_sample_million = np.random.uniform(25,100,1000000)\n\nplt.hist(case_2_sample_ten, 15, density=True)\nplt.hist(case_2_sample_hundred, 15, density=True)\nplt.hist(case_2_sample_thousand, 15, density=True)\nplt.hist(case_2_sample_million, 15, density=True)\n\ncase_2_histogram.suptitle('Uniform Distribution Case 2 Combined Histogram', fontsize=14, fontweight='bold')\ncase_2_axes_title = case_2_histogram.add_subplot(111)\ncase_2_histogram.subplots_adjust(top=0.85)\ncase_2_axes_title.set_title('retrieve n=10 random numbers from the uniform distribution [25,100] \\nwith n iterating from 10,100,1000,1000000')\ncase_2_histogram.show()\n\nprint(\"\\n---\\nNow that the combined histograms of both cases has been shown, we will show the individual graphs.\\n\")\n\ncase_1_each, case_1_each_axes = plt.subplots(2, 2, figsize=(10,10))\ncase_1_each.suptitle('Uniform Distribution Case 1 Histogram of Every Sample Size', fontsize=14, fontweight='bold')\n\ncase_1_each_axes[0, 0].hist(case_1_sample_ten, 15, density=True)\ncase_1_each_axes[0, 0].set_title('low=1,high=10,size=10')\ncase_1_each_axes[1, 0].hist(case_1_sample_hundred, 15, density=True)\ncase_1_each_axes[1, 0].set_title('low=1,high=10,size=100')\ncase_1_each_axes[0, 1].hist(case_1_sample_thousand, 15, density=True)\ncase_1_each_axes[0, 1].set_title('low=1,high=10,size=1000')\ncase_1_each_axes[1, 1].hist(case_1_sample_million, 15, density=True)\ncase_1_each_axes[1, 1].set_title('low=1,high=10,size=1000000')\n\ncase_2_each, case_2_each_axes = plt.subplots(2, 2, figsize=(10,10))\ncase_2_each.suptitle('Uniform Distribution Case 2 Histogram of Every Sample Size', fontsize=14, fontweight='bold')\n\ncase_2_each_axes[0, 0].hist(case_2_sample_ten, 15, density=True)\ncase_2_each_axes[0, 0].set_title('low=25,high=100,size=10')\ncase_2_each_axes[1, 0].hist(case_2_sample_hundred, 15, density=True)\ncase_2_each_axes[1, 0].set_title('low=25,high=100,size=100')\ncase_2_each_axes[0, 1].hist(case_2_sample_thousand, 15, density=True)\ncase_2_each_axes[0, 1].set_title('low=25,high=100,size=1000')\ncase_2_each_axes[1, 1].hist(case_2_sample_million, 15, density=True)\ncase_2_each_axes[1, 1].set_title('low=25,high=100,size=1000000')\n\nplt.show()", "meta": {"hexsha": "07d8428362cae3358febdb5e0064e61194000f2c", "size": 5317, "ext": "py", "lang": "Python", "max_stars_repo_path": "uniform.py", "max_stars_repo_name": "forkpile/assignment-6-psd", "max_stars_repo_head_hexsha": "ec8e5e5153666ab1d1b19e0d7c820831d9dbb20c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-19T11:20:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-19T11:39:18.000Z", "max_issues_repo_path": "uniform.py", "max_issues_repo_name": "drepram/assignment-6-psd", "max_issues_repo_head_hexsha": "ec8e5e5153666ab1d1b19e0d7c820831d9dbb20c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "uniform.py", "max_forks_repo_name": "drepram/assignment-6-psd", "max_forks_repo_head_hexsha": "ec8e5e5153666ab1d1b19e0d7c820831d9dbb20c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.5638297872, "max_line_length": 163, "alphanum_fraction": 0.7895429754, "include": true, "reason": "import numpy", "num_tokens": 1541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.9136765157744067, "lm_q1q2_score": 0.8655998165307817}}
{"text": "import math as m\nfrom scipy.misc import derivative\n\n# Here we simply give the input needed as The Following:\n# ( Equation ) First Specify if the input is an equation ( 1 ) or only a single application of the rule ( 0 )\n# ( Xi ) is the initial point\n# If The Equation was set to \"0\" you need to provide The Values First Derivative ( dr ) And Second Derivative ( Ddr ). if not selected keep 0\n# If The Equation was set to \"1\" you need to provide The Equation in the function ( F ) if not selected keep 0\n# ( n ) is the number of Iterations needed\n\nEquation = 1\n\nXi = 8.6                  \n\ndr = 1.2                 \n\nDdr = 5                   \n\ndef F(x): return -0.25*x**4+1.1*x**3-1.75*x**2+2*x\n\nn = 5\n\nprint(\"\\n-----------------------------------------------------------------\")\nprint(\" Iteration |   Xi    |   F(Xi)  |   F(x)\\'  |  F(x)\\\"    |  Error \"\n      \"\\n-----------------------------------------------------------------\")\nError = 100\nXiPlus1 = 0\nfor i in range (n):\n    if Equation == 1:\n        print(\"\\t{0:1d}  | {1:.5f} | {2:.5f}  | {3:.5f} | {4:.5f} |  {5:.4f}%\\n\"\n              .format(i, Xi, F(Xi), derivative(F, Xi, dx=1e-6), derivative(F, Xi, dx=1e-6, n = 2 ), Error)) \n        XiPlus1 = Xi - derivative(F, Xi, dx=1e-6)/derivative(F, Xi, dx=1e-6, n = 2 )\n        Error = abs(((XiPlus1 - Xi)/XiPlus1) *100)\n    if Equation == 0:\n        print(\"\\t{0:1d}  | {1:.5f} |  F(Xi)  | {2:.5f} | {3:.5f} |  {4:.4f} %\\n\"\n              .format(i, Xi, dr2,Ddr2, Error)) \n        XiPlus1 = Xi - (dr/Ddr)\n        Error = abs(((XiPlus1 - Xi)/XiPlus1) *100)\n        if i == 2 : break\n    Xi = XiPlus1\n    \n# Finally displaying the solution as well as the percentge of error after each iteration\n", "meta": {"hexsha": "abb0ef6435899bc5f0fabba98db7f701b118c0f3", "size": 1694, "ext": "py", "lang": "Python", "max_stars_repo_path": "Newton's-Method.py", "max_stars_repo_name": "Mezo0099/Numerical-Methods", "max_stars_repo_head_hexsha": "4a7321babb7c727152c69f543e784f00cf5ba059", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Newton's-Method.py", "max_issues_repo_name": "Mezo0099/Numerical-Methods", "max_issues_repo_head_hexsha": "4a7321babb7c727152c69f543e784f00cf5ba059", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Newton's-Method.py", "max_forks_repo_name": "Mezo0099/Numerical-Methods", "max_forks_repo_head_hexsha": "4a7321babb7c727152c69f543e784f00cf5ba059", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3953488372, "max_line_length": 141, "alphanum_fraction": 0.5100354191, "include": true, "reason": "from scipy", "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673113726775, "lm_q2_score": 0.8991213853793452, "lm_q1q2_score": 0.8655599836814658}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nx = np.linspace(-1,3,100)\r\ny=x**2-2*x+1\r\n\r\nfig = plt.figure()\r\naxdef = fig.add_subplot(1, 1, 1)\r\naxdef.spines['left'].set_position('center')\r\naxdef.spines['bottom'].set_position('zero')\r\naxdef.spines['right'].set_color('none')\r\naxdef.spines['top'].set_color('none')\r\naxdef.xaxis.set_ticks_position('bottom')\r\naxdef.yaxis.set_ticks_position('left')\r\n\r\nplt.plot(x,y, 'r')\r\nplt.show()\r\n\r\nGradf = lambda x: 2*x-2  \r\n\r\nActualX = 3 \r\nLearningRate = 0.01 \r\nPrecisionValue = 0.000001 \r\nPreviousStepSize = 1 \r\nMaxIteration = 10000 \r\nIterationCounter = 0 \r\n\r\n\r\nwhile PreviousStepSize > PrecisionValue and IterationCounter < MaxIteration:\r\n    PreviousX = ActualX\r\n    ActualX = ActualX - LearningRate * Gradf(PreviousX) \r\n    PreviousStepSize = abs(ActualX - PreviousX) \r\n    IterationCounter = IterationCounter+1 \r\n    print(\"Number of iterations = \",IterationCounter,\"\\nActual value of x  is = \",ActualX) \r\n    \r\nprint(\"X value of f(x) minimum = \", ActualX)", "meta": {"hexsha": "828d2f6419777c8a6261b309ff45835081ca69ad", "size": 1004, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter07/GradientDescent.py", "max_stars_repo_name": "CiaburroGiuseppe/Hands-On-Simulation-Modeling-with-Python", "max_stars_repo_head_hexsha": "c1cbf02840bb9e634e8f93e653cd8fdabcbcff01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2020-07-29T08:52:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T04:04:56.000Z", "max_issues_repo_path": "Chapter07/GradientDescent.py", "max_issues_repo_name": "CiaburroGiuseppe/Hands-On-Simulation-Modeling-with-Python", "max_issues_repo_head_hexsha": "c1cbf02840bb9e634e8f93e653cd8fdabcbcff01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter07/GradientDescent.py", "max_forks_repo_name": "CiaburroGiuseppe/Hands-On-Simulation-Modeling-with-Python", "max_forks_repo_head_hexsha": "c1cbf02840bb9e634e8f93e653cd8fdabcbcff01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2020-08-18T16:27:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T03:31:54.000Z", "avg_line_length": 27.8888888889, "max_line_length": 92, "alphanum_fraction": 0.6922310757, "include": true, "reason": "import numpy", "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.8991213820004279, "lm_q1q2_score": 0.8655599813915461}}
{"text": "from sympy import ( symbols, solve, diff, integrate, exp, sqrt, lambdify, Integral, pprint )\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# If the age of a randomly selected driver in a fatal car crash is a random variable with a probability density function given by\n\nx = symbols( 'x' )\nF = 0.01912 * exp( -0.00321 * x )\n\n# What does the petal distribution look like?\n\ng_xlim = [ -1, 90 ]\n\nlam_p = lambdify( x, F, np )\nx_vals = np.linspace( g_xlim[0], g_xlim[1], 1000, endpoint=True )\ny_vals = lam_p( x_vals )\nplt.plot( x_vals, y_vals )\n\nx_min, x_max = 18, 79\n\nplt.hlines( y = 0, xmin = g_xlim[0], xmax = g_xlim[1], color = 'Black', zorder = 1 )\n\nplt.vlines( x = x_min, ymin = 0, ymax = F.subs( { x: x_min } ), color = 'Black', zorder = 1 )\nplt.vlines( x = x_max, ymin = 0, ymax = F.subs( { x: x_max } ), color = 'Red', zorder = 1 )\n\n# The probability that the​ driver's age is between 24 and 45 is\n\na, b = 24, 45\nbounds = np.arange( a, b, 1/25., dtype=float)\n\nfor n in bounds:\n\ty = F.subs( { x: n } )\n\tplt.vlines( x = n, ymin = 0, ymax = y, color = 'Teal', zorder = 1, alpha = .4 )\n\narea = integrate( F, ( x, a, b ) ).evalf()\ntotal_area = integrate( F, ( x, x_min, x_max ) ).evalf()\n\narea_pct = round( ( area / total_area ), 2 )\n\nplt.title( 'Area: {0}'.format( area_pct ) )\nplt.show()\n\n# The probability that the​ driver's age is greater than or equal to 33\n\na, b = 32, x_max\nbounds = np.arange( a, b, 1/25., dtype=float)\n\nfor n in bounds:\n\ty = F.subs( { x: n } )\n\tplt.vlines( x = n, ymin = 0, ymax = y, color = 'Teal', zorder = 1, alpha = .4 )\n\narea = integrate( F, ( x, a, b ) ).evalf()\ntotal_area = integrate( F, ( x, x_min, x_max ) ).evalf()\n\narea_pct = round( ( area / total_area ), 2 )\n\nplt.title( 'Area: {0}'.format( area_pct ) )\nplt.show()\n\n# The probability that the driver is less than or equal to 28.\n\na, b = x_min, 21\nbounds = np.arange( a, b, 1/25., dtype=float)\n\nfor n in bounds:\n\ty = F.subs( { x: n } )\n\tplt.vlines( x = n, ymin = 0, ymax = y, color = 'Teal', zorder = 1, alpha = .4 )\n\narea = integrate( F, ( x, a, b ) ).evalf()\ntotal_area = integrate( F, ( x, x_min, x_max ) ).evalf()\n\narea_pct = round( ( area / total_area ), 2 )\n\nplt.title( 'Area: {0}'.format( area_pct ) )\nplt.show()\n\n# Find the cumulative distribution function for this random variable.\na, b = x_min, x\ncdf = integrate( F, ( x, a, b ) )\n\npprint( cdf )\n\nround( 5.95638629283489, 5 )\n\n#  Use the answer to part D to find the probability that a randomly selected driver in a fatal crash is at most 24 years old.\n\nans = cdf.subs( { x: 23 } ).evalf()\nround( ans, 2 )", "meta": {"hexsha": "7e6191f3dcf24282a3240ddedc0e5e1a43d2d310", "size": 2556, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Module 9/driver_age.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Module 9/driver_age.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Module 9/driver_age.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0454545455, "max_line_length": 129, "alphanum_fraction": 0.6255868545, "include": true, "reason": "import numpy,from sympy", "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.8991213813246445, "lm_q1q2_score": 0.8655599778523683}}
{"text": "__doc__ = \"\"\" Fits a set of 2D data points (x,y) to a circle\n\nSee https://scipy-cookbook.readthedocs.io/items/Least_Squares_Circle.html\nFrom https://dtcenter.org/met/users/docs/write_ups/circle_fit.pdf\nFor more complicated shapes, see https://arxiv.org/pdf/cs/0301001.pdf\n\"\"\"\n\nimport numpy as np\nfrom scipy.optimize import least_squares\nfrom scipy.stats import linregress\n\n\ndef fit_circle_to_data(in_data, verbose=False):\n    \"\"\"\n    Wrapper around _fit_circle_impl that takes care of unwrapping shapes and so on...\n    Returns\n    -------\n\n    \"\"\"\n    slope, intercept, r_value, p_value, std_err = linregress(in_data[0], in_data[1])\n\n    if verbose:\n        print(\"R-square of linear fit : {}\".format(r_value ** 2))\n        print(\"std-error of linear fit : {}\".format(std_err))\n\n    if r_value ** 2 < 0.98 and std_err > 1e-3:\n        xc, yc, r, opt = circle_fit_impl(in_data)\n\n        if verbose:\n            print(\"Number of function evaluations : {}\".format(opt.nfev))\n            print(\"Number of Jacobian evaluations : {}\".format(opt.njev))\n            print(\"Stddev. residuals at optimal : {}\".format(np.std(opt.fun)))\n\n        return xc, yc, r\n    else:\n        # It's almost a straight line, so return all infinitirys\n        return np.inf, np.inf, np.inf\n\n\ndef circle_fit_impl(x):\n    \"\"\"(2,n) array as input\"\"\"\n\n    def distance_from_center(xc, yc):\n        \"\"\"calculate the distance of each 2D points from the center (xc, yc)\"\"\"\n        return np.sqrt((x[0] - xc) ** 2 + (x[1] - yc) ** 2)\n\n    def objective(c):\n        \"\"\"calculates the objective : algebraic distance between the data points\n        and the mean circle centered at c=(xc, yc)\n\n        Maps from R^2 -> R^n where n is the number of points to map\n        \"\"\"\n        Ri = distance_from_center(*c)\n        return Ri - Ri.mean()\n\n    def jacobian_objective(c):\n        \"\"\"Jacobian of above objective function\n        By definition from scipy J_{ij} = \\\\partial f_{i}/ \\\\partial x_{j}\n        Hence J is a (n,2) matrix below\n\n        Parameters\n        ----------\n        c\n\n        Returns\n        -------\n\n        \"\"\"\n        xc, yc = c\n        df2b_dc = np.empty((x.shape[-1], c.shape[0]))\n\n        r_i = distance_from_center(xc, yc)\n        df2b_dc[..., 0] = (xc - x[0]) / r_i  # dR/dxc\n        df2b_dc[..., 1] = (yc - x[1]) / r_i  # dR/dyc\n        df2b_dc -= np.mean(df2b_dc, axis=0)\n\n        return df2b_dc\n\n    # estimate center via mean of data\n    center_estimate = np.mean(x, axis=-1)\n    optimum_results = least_squares(\n        objective, center_estimate, jac=jacobian_objective, method=\"lm\"\n    )\n\n    center_optimized = optimum_results.x\n    radius_samples = distance_from_center(*center_optimized)\n    radius = np.mean(radius_samples)\n    return (*center_optimized, radius, optimum_results)\n", "meta": {"hexsha": "177b122e64fcc3b17f9ebdc939b8a5677742b2de", "size": 2780, "ext": "py", "lang": "Python", "max_stars_repo_path": "kinematic_snake/circle_fit.py", "max_stars_repo_name": "tp5uiuc/kinematic_snake", "max_stars_repo_head_hexsha": "70a59a431d185a5fbe304b18db17eb3819ddbee1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-01T21:12:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T16:23:09.000Z", "max_issues_repo_path": "kinematic_snake/circle_fit.py", "max_issues_repo_name": "tp5uiuc/kinematic_snake", "max_issues_repo_head_hexsha": "70a59a431d185a5fbe304b18db17eb3819ddbee1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kinematic_snake/circle_fit.py", "max_forks_repo_name": "tp5uiuc/kinematic_snake", "max_forks_repo_head_hexsha": "70a59a431d185a5fbe304b18db17eb3819ddbee1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2359550562, "max_line_length": 85, "alphanum_fraction": 0.6151079137, "include": true, "reason": "import numpy,from scipy", "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.9073122257466114, "lm_q1q2_score": 0.8655451033009544}}
{"text": "import numpy as np\n\ndef universe_maker(setsList):\n    '''\n    This alorithm determines the universe of elements contain on the list of sets 'setList'.  To do that it uses a double loop that adds the elements to 'universe' set.  Since 'universe' is a set only unique elements are store.\n    \n    Arg:\n        setsList: is a list of all the sets\n        \n    Out:\n        universe:  is a set of all the elements\n\n    '''\n    universe = set(e for s in setsList for e in s)\n    \n    return universe\n\n\ndef set_cover_greedy(universe, setsList):\n   '''\n   This alorithm for the set cover problem uses the greedy alorithm.  The rule that follows is choosing the set that contains the largest number of uncovered elements.\n   This alorithm is a ln n –approximation.\n   \n   Arg:\n        universe:  is a set of all the elements\n        setsList: is a list of all the sets\n\n   Out:\n        cover: is the list of sets that covers the hole universe.\n        listCover: is the list that indicates what set (number) was use to forn the cover.\n   '''\n    \n   if universe_maker(setsList) != universe:\n        raise ValueError('There is a discrepancy between the universe input and the universe constructed from the list of sets.')\n   \n   covered = set()\n   cover = []\n   listCover = []\n   while covered != universe:\n        subSet = max(setsList, key=lambda s: len(s - covered))\n        cover.append(subSet)\n        listCover.append(setsList.index(subSet))\n        covered |= subSet\n\n   return cover, listCover\n   \n   \ndef set_cover_weighted_greedy(universe, setsList, weightList, normalize = True):\n    '''\n    This alorithm for the set cover problem uses the greedy alorithm.  The rule that follows is choosing the set that is most efficent at adding new elements.  The efficency is deffiend as the new elements to be added weighted by their cost.\n    This alorithm is a ln n –approximation.\n   \n    Arg:\n        universe:  is a set of all the elements\n        setsList: is a list of all the sets\n\n   Out:\n        cover: is the list of sets that covers the hole universe.\n        listCover: is the list that indicates what set (number) was use to forn the cover.\n   '''\n    \n    if universe_maker(setsList) != universe:\n        raise ValueError('There is a discrepancy between the universe input and the universe constructed from the list of sets.')\n        \n    if len(setsList) != len(weightList):\n        raise ValueError('The two list have different lenghts')\n   \n    covered = set()\n    cover = []\n    listCover = []\n    \n    #The weights are normalized, limits numerical errors.\n    if normalize == True:\n        weightList = weightList/np.mean(weightList)\n        \n    while covered != universe:\n        #setWeightStep is the list of cost given what is alrady present in covered. When a set does not gives value (no new items) it assings a 0.\n        setWeightStep = list(map(lambda x, y: len(x -covered)/y if len(x -covered) != 0 else 0, setsList, weightList))\n        #It will give the first element on the setWeightStep that is the most efficent. It is likely that more than one index will have the min same value.  In such cases a secondary cost function could be use to separate them. s\n        index = setWeightStep.index(max(setWeightStep))\n        cover.append(setsList[index])\n        listCover.append(index)\n        covered |= setsList[index]\n\n    return cover, listCover\n", "meta": {"hexsha": "508158457c8344c1bd68b8dd546b5ebe6e15e312", "size": 3373, "ext": "py", "lang": "Python", "max_stars_repo_path": "SetCover.py", "max_stars_repo_name": "hinowashi/SetCoverAlgorithm", "max_stars_repo_head_hexsha": "f37bab3f32006463ea0a772a8ea03df701159d2c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SetCover.py", "max_issues_repo_name": "hinowashi/SetCoverAlgorithm", "max_issues_repo_head_hexsha": "f37bab3f32006463ea0a772a8ea03df701159d2c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SetCover.py", "max_forks_repo_name": "hinowashi/SetCoverAlgorithm", "max_forks_repo_head_hexsha": "f37bab3f32006463ea0a772a8ea03df701159d2c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2209302326, "max_line_length": 241, "alphanum_fraction": 0.6753631782, "include": true, "reason": "import numpy", "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760638, "lm_q2_score": 0.9086178969328286, "lm_q1q2_score": 0.8655258985626895}}
{"text": "# 1次元ガウス分布の作図\n\n# 利用するライブラリ\nimport numpy as np\nfrom scipy.stats import norm # 1次元ガウス分布\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n#%%\n\n### 確率密度の計算\n\n# 平均を指定\nmu = 1.0\n\n# 標準偏差を指定\nsigma = 2.5\n\n# 確率変数の値を指定\nx = 1.0\n\n\n# 定義式により確率密度を計算\nC = 1.0 / np.sqrt(2.0 * np.pi * sigma**2)\ndens = C * np.exp(-0.5 * (x - mu)**2 / sigma**2)\nprint(dens)\n\n# 対数をとった定義式により確率密度を計算\nlog_C = -0.5 * np.log(2.0 * np.pi) - np.log(sigma)\nlog_dens = log_C - 0.5 * (x - mu)**2 / sigma**2\ndens = np.exp(log_dens)\nprint(dens, log_dens)\n\n# ガウス分布の関数により確率密度を計算\ndens = norm.pdf(x=x, loc=mu, scale=sigma)\nprint(dens)\n\n# ガウス分布の対数をとった関数により確率密度を計算\nlog_dens = norm.logpdf(x=x, loc=mu, scale=sigma)\ndens = np.exp(log_dens)\nprint(dens, log_dens)\n\n#%%\n\n### 統計量の計算\n\n# 平均を指定\nmu = 1.0\n\n# 標準偏差を指定\nsigma = 2.5\n\n\n# 計算式により平均を計算\nE_x = mu\nprint(E_x)\n\n# 計算式により分散を計算\nV_x = sigma**2\nprint(V_x)\n\n# 関数により平均を計算\nE_x = norm.mean(loc=mu)\nprint(E_x)\n\n# 関数により分散を計算\nV_x = norm.var(scale=sigma)\nprint(V_x)\n\n#%%\n\n### 分布の可視化\n\n## 分布の計算\n\n# 平均を指定\nmu = 0.0\n\n# 標準偏差を指定\nsigma = 1.0\n\n# 作図用のxの点を作成\nx_vals = np.linspace(start=mu - sigma*4.0, stop=mu + sigma*4.0, num=250)\n\n# ガウス分布を計算\ndensity = norm.pdf(x=x_vals, loc=mu, scale=sigma)\n\n#%%\n\n## 分布の作図\n\n# ガウス分布を作図\nplt.figure(figsize=(12, 9)) # 図の設定\nplt.plot(x_vals, density, color='#00A968') # 折れ線グラフ\nplt.xlabel('x') # x軸ラベル\nplt.ylabel('density') # y軸ラベル\nplt.suptitle('Gaussian Distribution', fontsize=20) # 全体のタイトル\nplt.title('$\\mu=' + str(mu) + ', \\sigma=' + str(sigma) + '$', loc='left') # タイトル\nplt.grid() # グリッド線\nplt.show() # 描画\n\n#%%\n\n## 統計量を重ねた分布の作図\n\n# ガウス分布を作図\nplt.figure(figsize=(12, 9)) # 図の設定\nplt.plot(x_vals, density, color='#00A968') # 分布\nplt.vlines(x=mu, ymin=0.0, ymax=np.max(density), color='orange', linestyle='--', label='$\\mu$') # 平均\nplt.vlines(x=mu - sigma, ymin=0.0, ymax=np.max(density), color='orange', linestyle=':', label='$\\mu \\pm \\\\sigma$') # 平均 - 標準偏差\nplt.vlines(x=mu + sigma, ymin=0.0, ymax=np.max(density), color='orange', linestyle=':') # 平均 + 標準偏差\nplt.xlabel('x') # x軸ラベル\nplt.ylabel('density') # y軸ラベル\nplt.suptitle('Gaussian Distribution', fontsize=20) # 全体のタイトル\nplt.title('$\\mu=' + str(mu) + ', \\sigma=' + str(sigma) + '$', loc='left') # タイトル\nplt.grid() # グリッド線\nplt.legend() # 凡例\nplt.show() # 描画\n\n#%%\n\n### パラメータと分布の形状の関係\n\n## 平均の影響\n\n# 平均として利用する値を指定\nmu_vals = np.arange(start=-5.0, stop=5.0, step=0.1)\nprint(len(mu_vals)) # フレーム数\n\n# 標準偏差を指定\nsigma = 1.0\n\n# 作図用のxの点を作成\nx_vals = np.linspace(start=np.median(mu_vals) - sigma*4.0, stop=np.median(mu_vals) + sigma*4.0, num=250)\n\n# y軸(確率密度)の最大値を設定\ndens_max = np.max(norm.pdf(x=x_vals, loc=0.0, scale=sigma)) + 0.05\n\n# 図を初期化\nfig = plt.figure(figsize=(12, 9)) # 図の設定\nfig.suptitle('Gaussian Distribution', fontsize=20) # 全体のタイトル\n\n# 作図処理を関数として定義\ndef update(i):\n    # 前フレームのグラフを初期化\n    plt.cla()\n    \n    # i番目の平均パラメータを取得\n    mu = mu_vals[i]\n    \n    # ガウス分布を計算\n    dens = norm.pdf(x=x_vals, loc=mu, scale=sigma)\n    \n    # ガウス分布を作図\n    plt.plot(x_vals, dens, color='#00A968') # 折れ線グラフ\n    plt.xlabel('x') # x軸ラベル\n    plt.ylabel('density') # y軸ラベル\n    plt.title('$\\mu=' + str(np.round(mu, 1)) + ', \\sigma=' + str(sigma) + '$', loc='left') # タイトル\n    plt.grid() # グリッド線\n    plt.ylim(ymin=-0.01, ymax=dens_max) # y軸の表示範囲\n\n# gif画像を作成\nanime_dens = FuncAnimation(fig, update, frames=len(mu_vals), interval=100)\n\n# gif画像を保存\nanime_dens.save('ProbabilityDistribution/Gaussian_dens_mu.gif')\n\n#%%\n\n## 標準偏差の影響\n\n# 標準偏差として利用する値を指定\nsigma_vals = np.arange(start=1.0, stop=10.1, step=0.1)\nprint(len(sigma_vals)) # フレーム数\n\n# 平均を指定\nmu = 0.0\n\n# 作図用のxの点を作成\nx_vals = np.linspace(start=mu - np.max(sigma_vals)*2.0, stop=mu + np.max(sigma_vals)*2.0, num=250)\n\n# y軸(確率密度)の最大値を設定\ndens_max = np.max(norm.pdf(x=x_vals, loc=mu, scale=np.min(sigma_vals))) + 0.05\n\n# 図を初期化\nfig = plt.figure(figsize=(12, 9)) # 図の設定\nfig.suptitle('Gaussian Distribution', fontsize=20) # 全体のタイトル\n\n# 作図処理を関数として定義\ndef update(i):\n    # 前フレームのグラフを初期化\n    plt.cla()\n    \n    # i番目の標準偏差パラメータを取得\n    sigma = sigma_vals[i]\n    \n    # ガウス分布を計算\n    dens = norm.pdf(x=x_vals, loc=mu, scale=sigma)\n    \n    # ガウス分布を作図\n    plt.plot(x_vals, dens, color='#00A968') # 折れ線グラフ\n    plt.xlabel('x') # x軸ラベル\n    plt.ylabel('density') # y軸ラベル\n    plt.title('$\\mu=' + str(mu) + ', \\sigma=' + str(np.round(sigma, 1)) + '$', loc='left') # タイトル\n    plt.grid() # グリッド線\n    plt.ylim(ymin=-0.01, ymax=dens_max) # y軸の表示範囲\n\n# gif画像を作成\nanime_dens = FuncAnimation(fig, update, frames=len(sigma_vals), interval=100)\n\n# gif画像を保存\nanime_dens.save('ProbabilityDistribution/Gaussian_dens_sigma.gif')\n\n#%%\n\n### 乱数の生成\n\n## 乱数の可視化\n\n# 平均を指定\nmu = 1.0\n\n# 標準偏差を指定\nsigma = 2.5\n\n# データ数を指定\nN = 1000\n\n# ガウス分布に従う乱数を生成\nx_n = np.random.normal(loc=mu, scale=sigma, size=N)\n\n\n# 作図用のxの点を作成\nx_vals = np.linspace(mu - sigma*4.0, mu + sigma*4.0, num=250)\n\n# ガウス分布を計算\ndensity = norm.pdf(x=x_vals, loc=mu, scale=sigma)\n\n#%%\n\n## 乱数の可視化\n\n# サンプルのヒストグラムを作成\nplt.figure(figsize=(12, 9)) # 図の設定\nplt.hist(x=x_n, bins=50, range=(x_vals.min(), x_vals.max()), color='#00A968') # ヒストグラム\nplt.xlabel('x') # x軸ラベル\nplt.ylabel('frequency') # y軸ラベル\nplt.suptitle('Gaussian Distribution', fontsize=20) # 全体のタイトル\nplt.title('$\\mu=' + str(mu) + ', \\sigma=' + str(sigma) + ', N=' + str(N) + '$', loc='left') # タイトル\nplt.grid() # グリッド線\nplt.show() # 描画\n\n# サンプルのヒストグラムを作成\nplt.figure(figsize=(12, 9)) # 図の設定\nplt.hist(x=x_n, bins=50, range=(x_vals.min(), x_vals.max()), density=True, color='#00A968') # ヒストグラム\nplt.plot(x_vals, density, color='green', linestyle='--') # 元の分布\nplt.xlabel('x') # x軸ラベル\nplt.ylabel('density') # y軸ラベル\nplt.suptitle('Gaussian Distribution', fontsize=20) # 全体のタイトル\nplt.title('$\\mu=' + str(mu) + ', \\sigma=' + str(sigma) + ', N=' + str(N) + '$', loc='left') # タイトル\nplt.grid() # グリッド線\nplt.show() # 描画\n\n#%%\n\n## アニメーションによる可視化:(頻度)\n\n# フレーム数を指定\nN_frame = 100\n\n# 図を初期化\nfig = plt.figure(figsize=(12, 9)) # 図の設定\nfig.suptitle('Gaussian Distribution', fontsize=20) # 全体のタイトル\n\n# y軸(頻度)の最大値を設定\nfreq_max = np.max(\n    np.histogram(a=x_n[:N_frame], bins=30, range=(x_vals.min(), x_vals.max()))[0], \n) + 1.0\n\n# 作図処理を関数として定義\ndef update(n):\n    # 前フレームのグラフを初期化\n    plt.cla()\n    \n    # サンプルのヒストグラムを作成\n    plt.hist(x=x_n[:(n+1)], bins=50, range=(x_vals.min(), x_vals.max()), color='#00A968', zorder=1) # ヒストグラム\n    plt.scatter(x=x_n[n], y=0.0, color='orange', s=100, zorder=2) # サンプル\n    plt.xlabel('x') # x軸ラベル\n    plt.ylabel('freqency') # y軸ラベル\n    plt.suptitle('Gaussian Distribution', fontsize=20) # 全体のタイトル\n    plt.title('$\\mu=' + str(mu) + ', \\sigma=' + str(sigma) + \n              ', N=' + str(n + 1) + '$', loc='left') # タイトル\n    plt.grid() # グリッド線\n    plt.ylim(ymin=-0.5, ymax=freq_max) # y軸の表示範囲\n\n# gif画像を作成\nanime_freq = FuncAnimation(fig, update, frames=N_frame, interval=100)\n\n# gif画像を保存\nanime_freq.save('ProbabilityDistribution/Gaussian_freq.gif')\n\n#%%\n\n## アニメーションによる可視化:(密度)\n\n# フレーム数を指定\nN_frame = 100\n\n# 図を初期化\nfig = plt.figure(figsize=(12, 9)) # 図の設定\nfig.suptitle('Gaussian Distribution', fontsize=20) # 全体のタイトル\n\n# 作図処理を関数として定義\ndef update(n):\n    # 前フレームのグラフを初期化\n    plt.cla()\n    \n    # サンプルのヒストグラムを作成\n    plt.hist(x=x_n[:(n+1)], bins=50, range=(x_vals.min(), x_vals.max()), density=True, color='#00A968', zorder=1) # ヒストグラム\n    plt.plot(x_vals, density, color='green', linestyle='--', zorder=2) # 元の分布\n    plt.scatter(x=x_n[n], y=0.0, color='orange', s=100, zorder=3) # サンプル\n    plt.xlabel('x') # x軸ラベル\n    plt.ylabel('density') # y軸ラベル\n    plt.suptitle('Gaussian Distribution', fontsize=20) # 全体のタイトル\n    plt.title('$\\mu=' + str(mu) + ', \\sigma=' + str(sigma) + \n              ', N=' + str(n + 1) + '$', loc='left') # タイトル\n    plt.grid() # グリッド線\n    plt.ylim(ymin=-0.01, ymax=density.max() + 0.1) # y軸の表示範囲\n\n# gif画像を作成\nanime_ｐrop = FuncAnimation(fig, update, frames=N_frame, interval=100)\n\n# gif画像を保存\nanime_prop.save('ProbabilityDistribution/Gaussian_prop.gif')\n\n#%%\n\n### 分布の生成\n\n## パラメータの生成\n\n# 超パラメータを指定\nmu_prior = 1.0\nsigma_prior = 2.5\n\n# サンプルサイズを指定\nN = 10\n\n# 1次元ガウス分布の平均パラメータを生成\nmu_n = np.random.normal(loc=mu_prior, scale=sigma_prior, size=N)\n\n\n# 標準偏差パラメータを指定\nsigma = 1.0\n\n# 平均パラメータを計算\nE_mu = mu_prior\n\n# 作図用のxの点を作成\nx_vals = np.linspace(E_mu - sigma*5.0, E_mu + sigma*5.0, num=250)\n\n# 平均パラメータの期待値による1次元ガウス分布の確率密度を計算\nE_dens = norm.pdf(x=x_vals, loc=E_mu, scale=sigma)\n\n#%%\n\n## 分布の作図\n\n# サンプルによる分布を作図\nplt.figure(figsize=(12, 9)) # 図の設定\nplt.plot(x_vals, E_dens, color='blue', linestyle='--', label='$E[\\mu]=' + str(E_mu) + '$') # 期待値による分布\nfor n in range(N):\n    tmp_dens = norm.pdf(x=x_vals, loc=mu_n[n], scale=sigma)\n    plt.plot(x_vals, tmp_dens, alpha=0.5, label='$\\mu=' + str(np.round(mu_n[n], 2)) + '$') # サンプルによる分布\nplt.xlabel('x') # x軸ラベル\nplt.ylabel('density') # y軸ラベル\nplt.suptitle('Gaussian Distribution', fontsize=20) # 全体のタイトル\nplt.title('$\\mu_{pri}=' + str(mu_prior) + ', \\sigma_{pri}=' + str(sigma_prior) + \n          ', \\sigma=' + str(sigma) + ', N=' + str(N) + '$', loc='left') # タイトル\nplt.legend() # 凡例\nplt.grid() # グリッド線\nplt.show() # 描画\n\n#%%\n\n", "meta": {"hexsha": "61b850d442fa57372ce52c1f93809493f72475df", "size": 8799, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/Python/gaussian.py", "max_stars_repo_name": "anemptyarchive/Probability-Distribution", "max_stars_repo_head_hexsha": "c44d1079051c0e079c4f009e6fb2d7e1d7b61011", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Python/gaussian.py", "max_issues_repo_name": "anemptyarchive/Probability-Distribution", "max_issues_repo_head_hexsha": "c44d1079051c0e079c4f009e6fb2d7e1d7b61011", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Python/gaussian.py", "max_forks_repo_name": "anemptyarchive/Probability-Distribution", "max_forks_repo_head_hexsha": "c44d1079051c0e079c4f009e6fb2d7e1d7b61011", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7953367876, "max_line_length": 126, "alphanum_fraction": 0.6406409819, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561712637256, "lm_q2_score": 0.8933094103149354, "lm_q1q2_score": 0.8654883350315847}}
{"text": "import numpy as np\r\nimport cv2 as cv\r\nimport scipy.signal as sp\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef gauss(dim, sigma):\r\n    # Takes the dimensions of the desired gauss filter and the sigma and returns the filter\r\n    # Dim must be odd\r\n    # Filter has been scaled to add to 1 to preserve image brightness\r\n    ret = np.zeros(shape=(dim, dim))\r\n    start = -(dim // 2)\r\n    for i in range(0, dim):\r\n        for j in range(0, dim):\r\n            ret[i][j] = (1 / (2 * np.pi * (np.square(sigma)))) * (\r\n                np.power(np.e, (-(np.square(start + i) + np.square(start + j)) / (2 * np.square(sigma)))))\r\n    return ret * 1/(np.sum(ret))\r\n\r\n\r\ndef laplace_gauss(dim, sigma):\r\n    # Takes the dimensions of the desired Laplacian of Gaussian filter and returns the filter\r\n    # Dim must be odd\r\n    # Source of LoG function: http://fourier.eng.hmc.edu/e161/lectures/gradient/node8.html\r\n    ret = np.zeros(shape=(dim, dim))\r\n    start = -(dim // 2)\r\n    for i in range(0, dim):\r\n        for j in range(0, dim):\r\n            ret[i][j] = (np.square(start + i) + np.square(start + j) - 2*np.square(sigma))/(np.power(sigma, 4)) * \\\r\n                        (np.power(np.e, (-(np.square(start + i) + np.square(start + j))/(2*np.square(sigma)))))\r\n    return ret\r\n\r\n\r\ndef detect_zero(img):\r\n    # Takes in the Laplacian filtered image and detects the zero crossings\r\n    # Algorithm sources:\r\n    # https://stackoverflow.com/questions/22050199/python-implementation-of-the-laplacian-of-gaussian-edge-detection\r\n    # https://theailearner.com/tag/zero-crossings/\r\n    # Code was written by me after looking at these algorithms, and my algorithm uses parts of both\r\n    thresh = np.absolute(img).mean()\r\n    height = len(img)\r\n    width = len(img[0])\r\n    ret = np.zeros(shape=(height, width))\r\n    for i in range(1, height-1):\r\n        for j in range(1, width-1):\r\n            patch = img[i-1:i+2, j-1:j+2]\r\n            minp = patch.min()\r\n            maxp = patch.max()\r\n            p = img[i][j]\r\n            if p < 0 < maxp and maxp - minp > thresh:\r\n                ret[i][j] = np.abs(p) + maxp if np.abs(p) + maxp > thresh else 0\r\n            elif minp < 0 < p and maxp - minp > thresh:\r\n                ret[i][j] = p + np.abs(minp) if p + np.abs(minp) > thresh else 0\r\n    return ret.astype(np.uint8)\r\n\r\n\r\ndef plot_array(kernel, title):\r\n    # Plot a 2D kernel as a colour map\r\n    # Source of function:\r\n    # https://matplotlib.org/3.1.1/gallery/images_contours_and_fields/image_annotated_heatmap.html\r\n    fig, ax = plt.subplots()\r\n    im = ax.imshow(kernel)\r\n\r\n    for i in range(len(kernel)):\r\n        for j in range(len(kernel)):\r\n            text = ax.text(j, i, round(kernel[i, j], 2),\r\n                           ha=\"center\", va=\"center\", color=\"w\")\r\n    ax.set_title(title)\r\n    fig.tight_layout()\r\n    plt.show()\r\n\r\n\r\ndef convolve(img, kernel):\r\n    # Convolve and image with the given kernel\r\n    return sp.convolve2d(img.astype(float), kernel)\r\n\r\n\r\ndef convolve_display(img, kernel, title):\r\n    # Perform the convolution and display the image\r\n    cv.imshow(title, convolve(img, kernel).astype(np.uint8))\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n    paolina = cv.cvtColor(cv.imread('images/Paolina.jpg'), cv.COLOR_BGR2GRAY)\r\n    dog = cv.cvtColor(cv.imread('images/dog.png'), cv.COLOR_BGR2GRAY)\r\n    # Image source for dog picture:\r\n    # https://www.google.com/url?sa=i&url=http%3A%2F%2Fpets.university%2Fi-love-dogs%2F&psig=AOvVaw2-Xgkpnat2Z2c3wkaX4pNv&ust=1590948869508000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKikmMeY3OkCFQAAAAAdAAAAABAW\r\n\r\n    # Question 4\r\n    # convolve_display(paolina, gauss(5, 1), \"Gaussian sigma=1\")\r\n    # convolve_display(paolina, gauss(11, 2), \"Gaussian sigma=2\")\r\n    plot_array(gauss(5, 1), \"Gaussian 5x5, sigma=1\")\r\n    plot_array(gauss(11, 2), \"Gaussian 11x11, sigma=2\")\r\n\r\n    # Question 5\r\n    log1 = laplace_gauss(7, 1)\r\n    log2 = laplace_gauss(13, 1.5)\r\n    log3 = laplace_gauss(21, 3)\r\n    plot_array(log1, \"Laplacian of Gaussian 7x7, sigma=1\")\r\n    plot_array(log2, \"Laplacian of Gaussian 13x13, sigma=1.5\")\r\n\r\n    # Question 6\r\n    paolina_log1 = convolve(paolina, log1)\r\n    paolina_log3 = convolve(paolina, log3)\r\n    dog_log1 = convolve(dog, log1)\r\n    dog_log3 = convolve(dog, log3)\r\n\r\n    # Question 7\r\n    t = detect_zero(paolina_log1)\r\n    cv.imshow(\"Paolina\", paolina)\r\n    cv.imshow(\"dog\", dog)\r\n    cv.imshow(\"Paolina with sigma=1\", detect_zero(paolina_log1))\r\n    cv.imshow(\"Paolina with sigma=3\", detect_zero(paolina_log3))\r\n    cv.imshow(\"Dog with sigma=1\", detect_zero(dog_log1))\r\n    cv.imshow(\"Dog with sigma=3\", detect_zero(dog_log3))\r\n\r\n    k = cv.waitKey(0)\r\n", "meta": {"hexsha": "aff8bce27e2ec865d2ce593a9dd076838c02391a", "size": 4636, "ext": "py", "lang": "Python", "max_stars_repo_path": "a1/a1.py", "max_stars_repo_name": "jensren/image-understanding", "max_stars_repo_head_hexsha": "084ff142f6540c2595384255cd585c3bf654df06", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "a1/a1.py", "max_issues_repo_name": "jensren/image-understanding", "max_issues_repo_head_hexsha": "084ff142f6540c2595384255cd585c3bf654df06", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "a1/a1.py", "max_forks_repo_name": "jensren/image-understanding", "max_forks_repo_head_hexsha": "084ff142f6540c2595384255cd585c3bf654df06", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2881355932, "max_line_length": 210, "alphanum_fraction": 0.6201466782, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561694652216, "lm_q2_score": 0.8933094096048377, "lm_q1q2_score": 0.8654883327369817}}
{"text": "from numpy.core.numeric import Inf\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import AgglomerativeClustering\nfrom scipy.cluster.hierarchy import dendrogram\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.cluster import DBSCAN\n\nX = [2, 8, 0, 7, 6]\nY = [0, 4, 6, 2, 1]\nlabels = [\"x1\", \"x2\", \"x3\", \"x4\", \"x5\"]\nhdata = pd.DataFrame({\"X\": X, \"Y\": Y}, index=labels)\n\nplt.scatter(hdata.X, hdata.Y)\nfor i in range(len(hdata.index)):\n    plt.text(hdata.loc[labels[i], \"X\"], hdata.loc[labels[i], \"Y\"], '%s' % (str(labels[i])), size=15, zorder=1) \nplt.show()\n\nclustering = AgglomerativeClustering(n_clusters=None, linkage=\"single\", distance_threshold=0).fit(hdata)\nlinkage_matrix = np.column_stack([clustering.children_, clustering.distances_, np.ones(len(hdata.index)-1)]).astype(float)\ndendrogram(linkage_matrix, labels=labels)\nplt.show()\n\nclustering = AgglomerativeClustering(n_clusters=None, linkage=\"complete\", distance_threshold=0).fit(hdata)\nlinkage_matrix = np.column_stack([clustering.children_, clustering.distances_, np.ones(len(hdata.index)-1)]).astype(float)\ndendrogram(linkage_matrix, labels=labels)\nplt.show()\n\nclustering = AgglomerativeClustering(n_clusters=2, linkage=\"complete\").fit(hdata)\nplt.scatter(hdata.X, hdata.Y, c=clustering.labels_, cmap=\"bwr\")\nfor i in range(len(hdata.index)):\n    plt.text(hdata.loc[labels[i], \"X\"], hdata.loc[labels[i], \"Y\"], '%s' % (str(labels[i])), size=15, zorder=1) \nplt.show()\n\neuropeData = pd.read_csv(\"./europe.txt\")\n\nscaler = StandardScaler()\nscaler = scaler.fit(europeData)\neurope = pd.DataFrame(scaler.transform(europeData), columns=europeData.columns, index=europeData.index)\n\nclustering = AgglomerativeClustering(n_clusters=None, linkage=\"complete\", distance_threshold=0).fit(europe)\nlinkage_matrix = np.column_stack([clustering.children_, clustering.distances_, np.ones(len(europe.index)-1)]).astype(float)\ndendrogram(linkage_matrix, labels=europe.index)\nplt.show()\n\nslc = []\nfor i in range(2, 21):\n    clustering = AgglomerativeClustering(n_clusters=i, linkage=\"complete\").fit(europe)\n    slc.append(silhouette_score(europe, clustering.labels_))\n\nplt.plot(range(2, 21), slc)\nplt.xticks(range(2, 21), range(2, 21))\nplt.show()\n\nclustering = AgglomerativeClustering(n_clusters=7, linkage=\"complete\").fit(europe)\n\nfig = plt.figure()\nax = fig.add_subplot(projection='3d')\nax.scatter(europeData.GDP, europeData.Inflation, europeData.Unemployment, c=clustering.labels_, cmap=\"bwr\")\nfor i in range(len(europeData.index)):\n    ax.text(europeData.loc[europeData.index[i], \"GDP\"], europeData.loc[europeData.index[i], \"Inflation\"], europeData.loc[europeData.index[i], \"Unemployment\"], '%s' % (str(europeData.index[i])), size=10, zorder=1) \nax.set_xlabel('GDP')\nax.set_ylabel('Inflation')\nax.set_zlabel('Unemployment')\nplt.show()\n\nprint(silhouette_score(europe, clustering.labels_))\n\n\nX = [2, 2, 8, 5, 7, 6, 1, 4]\nY = [10, 5, 4, 8, 5, 4, 2, 9]\nlabels = [\"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\"]\nddata = pd.DataFrame({\"X\": X, \"Y\": Y}, index=labels)\n\nplt.scatter(ddata.X, ddata.Y)\nfor i in range(len(ddata.index)):\n    plt.text(ddata.loc[labels[i], \"X\"], ddata.loc[labels[i], \"Y\"], '%s' % (str(labels[i])), size=15, zorder=1) \nplt.show()\n\nclustering = DBSCAN(eps=2, min_samples=2).fit(ddata)\n\nclusters = clustering.labels_\nplt.scatter(ddata.X, ddata.Y, c=clusters, cmap=\"spring\")\nfor i in range(len(ddata.index)):\n    plt.text(ddata.loc[labels[i], \"X\"], ddata.loc[labels[i], \"Y\"], '%s' % (str(labels[i])), size=15, zorder=1) \nplt.title(\"DBSCAN(eps=2, minPts=2)\")\nplt.show()\n\nclustering = DBSCAN(eps=3.5, min_samples=2).fit(ddata)\nclusters = clustering.labels_\nplt.scatter(ddata.X, ddata.Y, c=clusters, cmap=\"spring\")\nfor i in range(len(ddata.index)):\n    plt.text(ddata.loc[labels[i], \"X\"], ddata.loc[labels[i], \"Y\"], '%s' % (str(labels[i])), size=15, zorder=1) \nplt.title(\"DBSCAN(eps=3.5, minPts=2)\")\nplt.show()\n\nmdata = pd.read_csv(\"./mdata.txt\")\n\n# plt.scatter(mdata.X, mdata.Y, marker=\"o\")\n# plt.show()\n\nfrom sklearn.cluster import KMeans\nkmeans = KMeans(n_clusters=2).fit(mdata)\nplt.scatter(mdata.X, mdata.Y, c=kmeans.labels_)\nplt.show()\n\nfrom sklearn.neighbors import NearestNeighbors\nnbrs = NearestNeighbors(n_neighbors=10).fit(mdata)\ndistances, indices = nbrs.kneighbors(mdata)\ndistanceDec = sorted(distances[:, 9])\nplt.plot(distanceDec)\nplt.ylabel(\"10-NN Distance\")\nplt.xlabel(\"Points sorted by distance\")\nplt.show()\n\nclustering = DBSCAN(eps=0.4, min_samples=10).fit(mdata)\nplt.scatter(mdata.X, mdata.Y, c=clustering.labels_)\nplt.show()", "meta": {"hexsha": "56494c9c83449caacb8036617b6999b9314b1d3f", "size": 4595, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab/8. Hierarchical Clustering - DBSCAN/8. Hierarchical Clustering - DBSCAN.py", "max_stars_repo_name": "AuthEceSoftEng/Pattern-Recognition", "max_stars_repo_head_hexsha": "862bb067d3fbaf2675f230012f90c3846bda919c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-12-23T09:28:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T18:41:52.000Z", "max_issues_repo_path": "Lab/8. Hierarchical Clustering - DBSCAN/8. Hierarchical Clustering - DBSCAN.py", "max_issues_repo_name": "AuthEceSoftEng/Pattern-Recognition", "max_issues_repo_head_hexsha": "862bb067d3fbaf2675f230012f90c3846bda919c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab/8. Hierarchical Clustering - DBSCAN/8. Hierarchical Clustering - DBSCAN.py", "max_forks_repo_name": "AuthEceSoftEng/Pattern-Recognition", "max_forks_repo_head_hexsha": "862bb067d3fbaf2675f230012f90c3846bda919c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-23T08:38:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T08:38:30.000Z", "avg_line_length": 38.2916666667, "max_line_length": 213, "alphanum_fraction": 0.7203482046, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561712637257, "lm_q2_score": 0.8933094003735663, "lm_q1q2_score": 0.8654883253998281}}
{"text": "from matplotlib import pylab\nimport pylab as plt\nimport numpy as np\nimport os,sys\n\n\"\"\"\nA function used for neural network activation\nin artifacial intelligence, machine learning\n\"\"\"\n\ndef sigmoid(x):\n    #f(x)=1/(1+e^(-x))\n    return (1 / (1 + np.exp(-x)))\n\ndef sigmoidplot():\n    x = plt.linspace(-10,10,5)\n    y = plt.linspace(-10,10,10)\n    z = plt.linspace(-10,10,100)\n\n    plt.plot(x, sigmoid(x), 'r', label='linspace(-10,10,5)')\n    plt.plot(y, sigmoid(y), 'b', label='linspace(-10,10,10)')\n    plt.plot(z, sigmoid(z), 'y', label='linspace(-10,10,100)')\n\n\n    plt.title('Sigmoid Function')\n    plt.suptitle('Math')\n    plt.grid()\n    plt.legend(loc='lower right')\n    plt.text(-9,0.8, r'$\\sigma(x)=\\frac{1}{1+e^{-x}}$', fontsize=15)\n    plt.gca().xaxis.set_major_locator(plt.MultipleLocator(2))\n    plt.gca().yaxis.set_major_locator(plt.MultipleLocator(0.1))\n    plt.xlabel('X Axis')\n    plt.ylabel('Y Axis')\n\n    plt.show()\n\ndef main():\n    if \"-a\" in sys.argv[1:]:\n        for i in range(-5,5):\n           print(sigmoid(i))\n    elif \"-p\" in sys.argv[1:]:\n        sigmoidplot()\n    else:\n        for i in range(-5,5):\n           print(sigmoid(i))\n        sigmoidplot()\n        \n\nif __name__==\"__main__\":\n    main()\n\n", "meta": {"hexsha": "5a0b5f8e2cf900c6396d137ed2180f48e9882be5", "size": 1222, "ext": "py", "lang": "Python", "max_stars_repo_path": "py/sigmoid.py", "max_stars_repo_name": "jzhou/ai", "max_stars_repo_head_hexsha": "a5efbfb5e93e404129c974491705c24e9bc49c9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "py/sigmoid.py", "max_issues_repo_name": "jzhou/ai", "max_issues_repo_head_hexsha": "a5efbfb5e93e404129c974491705c24e9bc49c9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "py/sigmoid.py", "max_forks_repo_name": "jzhou/ai", "max_forks_repo_head_hexsha": "a5efbfb5e93e404129c974491705c24e9bc49c9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5, "max_line_length": 68, "alphanum_fraction": 0.5883797054, "include": true, "reason": "import numpy", "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633821, "lm_q2_score": 0.9046505421702797, "lm_q1q2_score": 0.8654196465699248}}
{"text": "\"\"\"\nhttps://projecteuler.net/problem=5\n2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.\n\nWhat is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\n\"\"\"\nfrom numpy import prod\n\nfrom Common.Logger import get_logger, init_logger\nfrom Common.Numbers import prime_factorization\nfrom Common.Utilities import performance_run\n\nPERFORMANCE_RUNS = 100_000\nUPPER_BOUND = 20\n\n\ndef fastest(ceiling: int = UPPER_BOUND) -> int:\n    \"\"\"\n    This algorithm finds the prime factorization of every number between 1 and ceiling, maintains the greatest counts of\n    each prime factor found, and then multiplies them out at the end\n    :param ceiling: The upper bound (inclusive) of the factor for which to find the evenly-divided quotient\n    :return: The quotient evenly-divisible by every number from 1 to ceiling\n    \"\"\"\n    return prime_tally(ceiling)\n\n\ndef prime_tally(ceiling: int = UPPER_BOUND) -> int:\n    \"\"\"\n    This algorithm finds the prime factorization of every number between 1 and ceiling, maintains the greatest counts of\n    each prime factor found, and then multiplies them out at the end\n    --> benchmark: 104 ms/run\n    :param ceiling: The upper bound (inclusive) of the factor for which to find the evenly-divided quotient\n    :return: The quotient evenly-divisible by every number from 1 to ceiling\n    \"\"\"\n    factorization_merge = []\n\n    for number in range(1, ceiling+1):\n        number_factorization = prime_factorization(number)\n        for factor in set(number_factorization):\n            factor_count_difference = number_factorization.count(factor) - factorization_merge.count(factor)\n            if factor_count_difference > 0:\n                factorization_merge += [factor] * factor_count_difference\n\n    return prod(factorization_merge)\n\n\nif __name__ == \"__main__\":\n    # Log stuff\n    init_logger()\n    logger = get_logger()\n\n    # Performance run\n    # performance_run(prime_tally, iterations=PERFORMANCE_RUNS)()\n    print(fastest(UPPER_BOUND))\n", "meta": {"hexsha": "f75750161d286a62f8000c5d915a870879e0afa0", "size": 2060, "ext": "py", "lang": "Python", "max_stars_repo_path": "Solutions/Q0005_Smallest_Evenly_Divisible_Number.py", "max_stars_repo_name": "SigfriedHache/euler-project", "max_stars_repo_head_hexsha": "7c38deee65a793a441830a6d0916da61e86b8cf7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Solutions/Q0005_Smallest_Evenly_Divisible_Number.py", "max_issues_repo_name": "SigfriedHache/euler-project", "max_issues_repo_head_hexsha": "7c38deee65a793a441830a6d0916da61e86b8cf7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/Q0005_Smallest_Evenly_Divisible_Number.py", "max_forks_repo_name": "SigfriedHache/euler-project", "max_forks_repo_head_hexsha": "7c38deee65a793a441830a6d0916da61e86b8cf7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4545454545, "max_line_length": 120, "alphanum_fraction": 0.7378640777, "include": true, "reason": "from numpy", "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724487, "lm_q2_score": 0.9046505261034853, "lm_q1q2_score": 0.8654196345552888}}
{"text": "import numpy as np\n\ndef vecNum(vec):\n    return int(\"\".join(str(int(n)) for n in vec), base=2)\n\ndef printVec(vec, width):\n    return \"0b{:0{}b},\".format(vecNum(vec), width)\n\ndef printBinary(mat, width):\n    for vec in mat:\n        print(printVec(vec, width))\n\ndef genToParityCheck(genParity):\n    return np.hstack((genParity.transpose(), np.eye(genParity.shape[1])))\n\ndef genToAltParityCheck(genParity):\n    return np.hstack((np.eye(genParity.shape[0]), genParity))\n\n# This was pieced together from the P25 and DMR standards, as well as appendix Q of the\n# IRIG standard.\nparity = np.array([\n    [1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1],\n    [0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1],\n    [1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0],\n    [0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0],\n    [0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0],\n    [1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1],\n    [0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1],\n    [0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1],\n    [1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0],\n    [1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1],\n    [1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0],\n    [1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1],\n])\ngen = np.hstack((np.eye(12), parity))\n\nprint(\"core transpose:\")\nprintBinary(parity.transpose(), 12)\n\nprint(\"core:\")\nprintBinary(parity, 12)\n\nparityCheck = genToParityCheck(parity)\nprint(\"parity check:\")\nprintBinary(parityCheck, 24)\n\nparityCheck = genToAltParityCheck(parity)\nprint(\"alt parity check:\")\nprintBinary(parityCheck, 24)\n\n# Verify self-dual property.\nfor r in range(0, 12):\n    for q in range(r, 12):\n        dot = (gen[r] @ gen[q]) % 2\n        assert dot == 0.0\n", "meta": {"hexsha": "574879d4a0baac6af7ef338e63c40f3cfd954617", "size": 1572, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/ext.py", "max_stars_repo_name": "kchmck/cai_golay.rs", "max_stars_repo_head_hexsha": "9e9203deed51dd9cd8c187805b9f479a0a002d6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-17T23:25:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T05:35:50.000Z", "max_issues_repo_path": "scripts/ext.py", "max_issues_repo_name": "kchmck/cai_golay.rs", "max_issues_repo_head_hexsha": "9e9203deed51dd9cd8c187805b9f479a0a002d6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/ext.py", "max_forks_repo_name": "kchmck/cai_golay.rs", "max_forks_repo_head_hexsha": "9e9203deed51dd9cd8c187805b9f479a0a002d6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-10T21:20:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T21:20:00.000Z", "avg_line_length": 28.0714285714, "max_line_length": 87, "alphanum_fraction": 0.558524173, "include": true, "reason": "import numpy", "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517106286379, "lm_q2_score": 0.9005297947939936, "lm_q1q2_score": 0.8653656467793445}}
{"text": "# Importing the libraries\nimport numpy as np\nimport pandas as pd\nfrom pandas_datareader import data as web\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport scipy\nfrom scipy.stats import norm\n%matplotlib notebook\n\n# Pulling the data for AAPL (I have used a CSV file and data from 01/01/2021 - 08/27/2021)\ndf = pd.read_csv(\"C:/Users/vgupt/Desktop/Website Project Folder/MCS/AAPL.csv\")['Adj Close']\ndf\n\n#Ploting the prices on a graph\nplt.xlabel(\"Date\")\nplt.ylabel(\"Price\")\ndf.plot(figsize=(15,6))\n\n# Calulating the logarithmic returns returns of AAPL stock\nlog_return = np.log(1 + df.pct_change())\nlog_return\n\n# Computing the drift\nu = log_return.mean()\nv = log_return.var()\n\ndrift = u - (0.5*v)\ndrift\n\n# Computing the variance and Daily Returns\nstdev = log_return.std()\ndays = 50  #We are predicting AAPL's stock prices 50 days into the future\nnum_simulations = 1000\nZ = norm.ppf(np.random.rand(days,num_simulations))\nZ\n\ndaily_returns = np.exp(drift + stdev*Z)\n\nplt.plot(daily_returns)\n\n# Calulating the stock price for every trial\nprice_paths = np.zeros_like(daily_returns)\nprice_paths[0] = df.iloc[-1]\nfor t in range(1, days):\n    price_paths[t] = price_paths[t-1]*daily_returns[t]\n    \nprice_paths\n\nplt.plot(price_paths)\n\n\n# Graph link\n![image](https://user-images.githubusercontent.com/83883988/131385949-df5dba5a-b21f-467a-a6a6-5bc9b3d3cba9.png)\n", "meta": {"hexsha": "8ad90ee0d5bc71bde0416d7d466e7b35bdc20693", "size": 1361, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code.py", "max_stars_repo_name": "VGupta-hub/Monte-Carlo-Simulation-with-Python", "max_stars_repo_head_hexsha": "1bb383c891da25e16004540bdb91be82691d7026", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code.py", "max_issues_repo_name": "VGupta-hub/Monte-Carlo-Simulation-with-Python", "max_issues_repo_head_hexsha": "1bb383c891da25e16004540bdb91be82691d7026", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-30T18:20:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T18:20:44.000Z", "max_forks_repo_path": "Code.py", "max_forks_repo_name": "VGupta-hub/Monte-Carlo-Simulation-with-Python", "max_forks_repo_head_hexsha": "1bb383c891da25e16004540bdb91be82691d7026", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7454545455, "max_line_length": 111, "alphanum_fraction": 0.7553269655, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517061554855, "lm_q2_score": 0.9005297761070066, "lm_q1q2_score": 0.8653656247938454}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 20 23:06:49 2017\r\n\r\n@author: Grant\r\n\r\nAn implementation of the Thomas algorithm in Python, using just-in-time \r\ncompiling from numba for additional speed\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom numba import njit, f8\r\n\r\ndef solve(A, d):\r\n    '''Helper function for Thomas algorith. Breaks matrix into tridiagonal\r\n    elements for easier processing by algorithm. '''\r\n    \r\n    # pass numba float64 dtype np.arrays to the solve function - need to \r\n    # perform this step to allow for nopython execution of thomas algorithm \r\n    # which yields maximum speed\r\n    a = f8(np.diagonal(A, offset=0))\r\n    b = f8(np.diagonal(A, offset=1))\r\n    c = f8(np.diagonal(A, offset=-1))\r\n    dfloat = f8(d)\r\n    \r\n    D = np.diag(a, 0) + np.diag(b, 1) + np.diag(c, -1) #create test matrix\r\n    \r\n    # test if D is 'close enough' to A - if not that means A was not \r\n    # tridiagonal and the function raises an exception\r\n    if not np.allclose(A, D):\r\n        raise Exception('The given A is not tridiagonal')\r\n    \r\n    # pass to thomas algorithm solver\r\n    x = solve_body(a, b, c, dfloat)\r\n    \r\n    return x\r\n    \r\n# chose to use njit decorator to force nopython implementation and \r\n# get faster speed. Downside is I lose flexibility in input of solver, must\r\n# wrap in another function which will format data correctly\r\n@njit\r\ndef solve_body(a, b, c, d):\r\n    ''' Thomas algorithm to solve a tridiagonal system of equations\r\n    \r\n    INPUTS\r\n    ========\r\n    a: numpy array\r\n        the diagonal entries\r\n    b: numpy array\r\n        the superdiagonal entries\r\n    c: numpy array\r\n        the subdiagonal entries\r\n    d: numpy array\r\n        the right-hand side of the system of equations\r\n    \r\n    RETURNS\r\n    ========\r\n    The solution for the given tri-diagonal system of equations.\r\n    '''\r\n    \r\n    n = len(a) # determine number of equations in system\r\n    \r\n    #initialize\r\n    alpha = np.zeros(n)\r\n    beta = np.zeros(n)\r\n    alpha[0] = a[0]\r\n    beta[0] = d[0]\r\n    \r\n    # first (forward) loop to zero c[i]'s\r\n    for i in range(1, n, 1):\r\n        # in python, c's index is from 0 to n-2, not 1 to n-1, have to subtract 1\r\n        alpha[i] = a[i] - (b[i-1] * c[i-1]) / alpha[i-1]\r\n        beta[i] = d[i] - (beta[i-1] * c[i-1]) / alpha[i-1]\r\n    \r\n    #initialize and set last step\r\n    x = np.zeros(n)\r\n    x[n-1] = beta[n-1] / alpha[n-1]\r\n    \r\n    # second (backwards) loop to find solutions\r\n    for j in range(n-2, -1, -1): #indices are weird, want to step from n-2 to 0 \r\n        x[j] = (beta[j] - b[j-1] * x[j+1]) / alpha[j]\r\n        \r\n    return x\r\n        \r\n\r\n", "meta": {"hexsha": "688feb8d7e8fef2bae057b526cc5ad3bba5366d4", "size": 2620, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw10_conine/thomas.py", "max_stars_repo_name": "gconine88/MATH_6204", "max_stars_repo_head_hexsha": "ecff4ecd3ae423c113d8259fe24b76b4a67de6ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw10_conine/thomas.py", "max_issues_repo_name": "gconine88/MATH_6204", "max_issues_repo_head_hexsha": "ecff4ecd3ae423c113d8259fe24b76b4a67de6ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw10_conine/thomas.py", "max_forks_repo_name": "gconine88/MATH_6204", "max_forks_repo_head_hexsha": "ecff4ecd3ae423c113d8259fe24b76b4a67de6ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4651162791, "max_line_length": 82, "alphanum_fraction": 0.5916030534, "include": true, "reason": "import numpy,from numba", "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.9005297761070066, "lm_q1q2_score": 0.8653656237867935}}
{"text": "import numpy\n\ndef functional_iteration(f, x0, max_steps=100, tol=1e-10):\n    N = len(x0)\n    x = numpy.zeros((max_steps+1,N))\n    x[0,:] = x0\n    step = 0\n    g = lambda x : x - f(x)\n    while numpy.linalg.norm(f(x[step])) > tol and step < max_steps:\n        step = step + 1\n        x[step,:] = g(x[step-1,:])\n    return x[:step+1,:]\n    \ndef newton(f, df, x0, max_steps=100, tol=1e-10):\n    N = len(x0)\n    x = numpy.zeros((max_steps+1,N))\n    x[0,:] = x0\n    step = 0\n    while numpy.linalg.norm(f(x[step])) > tol and step < max_steps:\n        step = step + 1\n        fx = f(x[step-1, :])\n        J = df(x[step-1, :])\n        c = numpy.linalg.solve(J, -fx)\n        x[step,:] = x[step-1, :] + c\n    return x[:step+1,:]\n    \nif __name__==\"__main__\":\n    def f(x):\n        return numpy.array([  x[0]**2 +    x[1]**2 - 1,\n                            5*x[0]**2 + 21*x[1]**2 - 9])\n    def df(x):\n        return numpy.array([[ 2*x[0],  2*x[1]],\n                            [10*x[0], 42*x[1]]])\n    \n    print(\"Exact solution is\", numpy.array([numpy.sqrt(3)/2, 1/2]))\n    x = functional_iteration(f, numpy.array([1, 1]))\n    print(\"Functional iteration\", x[-1, :])\n    x = newton(f, df, numpy.array([1, 1]))\n    print(\"Newton\", x[-1, :], \"iterations\", len(x))", "meta": {"hexsha": "bd7cc370ca970daf54b70f6808543dd6e3bcca16", "size": 1253, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/tex/codes/lecture10.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Lectures/tex/codes/lecture10.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Lectures/tex/codes/lecture10.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 32.1282051282, "max_line_length": 67, "alphanum_fraction": 0.4884277733, "include": true, "reason": "import numpy", "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97364464868338, "lm_q2_score": 0.8887588001219789, "lm_q1q2_score": 0.8653352497090265}}
{"text": "\"\"\"FFT Scratch\n    Reference. \n        Kor, proof of formula,\n          https://ghebook.blogspot.com/2020/09/dft-discrete-fourier-transform.html\n        Eng, Cooley and Tukey,\n          http://jakevdp.github.io/blog/2013/08/28/understanding-the-fft/\n\"\"\"\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.fft import fft, dct, ifft, idct\n\n\"\"\"Base on formula\"\"\"\n\n\ndef fft_scratch(f, M=0):\n    \"\"\"fft, exactly dft\n        fft formula\n          F(w) = integ_{-inf}^inf f(t) * exp(-j * w * t) dt\n        dft formula\n          F_k = sigma_{m=0}^{M-1} f_m * exp(-j * 2 * pi * m * k / M)\n    \"\"\"\n    if M == 0:\n        M = len(f)\n    fft_result = np.zeros(M, dtype=np.complex128)\n    for k in range(len(fft_result)):\n        sumation_f = 0\n        for m in range(len(f)):\n            sumation_f += f[m] * np.exp(-1j * 2 * np.pi * m * k / M)\n        fft_result[k] = sumation_f\n\n    return fft_result\n\n\ndef ifft_scratch(f, M=0):\n    \"\"\"fft, exactly dft\n        ifft formula\n          f(t) = (1/2*pi)*integ_{-inf}^inf F(w) * exp(j * w * t) dw\n        idft formula\n          f_k  = (1/M)   *sigma_{m=0}^{M-1} F_m * exp(j * 2 * pi * m * k / M)\n    \"\"\"\n    if M == 0:\n        M = len(f)\n    ifft_result = np.zeros(M, dtype=np.complex128)\n    for k in range(len(ifft_result)):\n        sumation_f = 0\n        for m in range(len(f)):\n            sumation_f += f[m] * np.exp(1j * 2 * np.pi * m * k / M)\n        ifft_result[k] = sumation_f / M\n\n    return ifft_result\n\n\ndef dct_scratch(f, M=0):\n    \"\"\"\n        DCT-1, T = 2M-2\n        Fk  = sigma_{m=0}^{2M-3}*f_m*e^{-j*pi*k/(M-1)*m}\n            = f_0 + (-1)^k*f_{M-1} + 2*sigma_{m=1}^{M-2}*f_m*cos(pi*k*(m-1)/(M-1)*m)\n        \n        DCT-1, Xk = Fk/2\n\n        DCT-2, T = 4M\n        F_k = 2*sigma_{m=0}^{M-1}*f_{2m+1}*cos(pi*k/2M*m)\n    \"\"\"\n    raise NotImplementedError\n\n\ndef idct_scratch(f, M=0):\n    \"\"\"\n        iDCT-1\n        x_m = 1/(M-1) * [X_0 + (-1)^m*X_{M-1} + 2*sigma_{m=1}^{M-2}*X_m*cos(pi*m*(m-1)/(M-1)*m)] ]\n    \"\"\"\n    raise NotImplementedError\n\n\n\"\"\"Base. Cooley and Tukey \"\"\"\n\n\ndef DFT_slow(x):\n    \"\"\"Compute the discrete Fourier Transform of the 1D array x\"\"\"\n    x = np.asarray(x, dtype=float)\n    N = x.shape[0]\n    n = np.arange(N)\n    k = n.reshape((N, 1))\n    M = np.exp(-2j * np.pi * k * n / N)\n    return np.dot(M, x)\n\n\ndef FFT(x):\n    \"\"\"A recursive implementation of the 1D Cooley-Tukey FFT\n        Big O: O(NlogN)\n    \"\"\"\n\n    x = np.asarray(x, dtype=float)\n    N = x.shape[0]\n\n    if N % 2 > 0:\n        raise ValueError(\"size of x must be a power of 2\")\n    elif N <= 32:  # this cutoff should be optimized\n        return DFT_slow(x)\n    else:\n        X_even = FFT(x[::2])\n        X_odd = FFT(x[1::2])\n        factor = np.exp(-2j * np.pi * np.arange(N) / N)\n        return np.concatenate(\n            [X_even + factor[: N // 2] * X_odd, X_even + factor[N // 2 :] * X_odd]\n        )\n\n\ndef FFT_vectorized(x):\n    \"\"\"A vectorized, non-recursive version of the Cooley-Tukey FFT\"\"\"\n    x = np.asarray(x, dtype=float)\n    N = x.shape[0]\n\n    if np.log2(N) % 1 > 0:\n        raise ValueError(\"size of x must be a power of 2\")\n\n    # N_min here is equivalent to the stopping condition above,\n    # and should be a power of 2\n    N_min = min(N, 32)\n\n    # Perform an O[N^2] DFT on all length-N_min sub-problems at once\n    n = np.arange(N_min)\n    k = n[:, None]\n    M = np.exp(-2j * np.pi * n * k / N_min)\n    X = np.dot(M, x.reshape((N_min, -1)))\n\n    # build-up each level of the recursive calculation all at once\n    while X.shape[0] < N:\n        X_even = X[:, : X.shape[1] // 2]\n        X_odd = X[:, X.shape[1] // 2 :]\n        factor = np.exp(-1j * np.pi * np.arange(X.shape[0]) / X.shape[0])[:, None]\n        X = np.vstack([X_even + factor * X_odd, X_even - factor * X_odd])\n\n    return X.ravel()\n\n\ndef hfft_scratch(f, M=0):\n    raise NotImplementedError\n\n\ndef ihfft_scratch(f, M=0):\n    raise NotImplementedError\n\n\ndef rfft_scratch(f, M=0):\n    raise NotImplementedError\n\n\ndef irfft_scratch(f, M=0):\n    raise NotImplementedError\n\n\nif __name__ == \"__main__\":\n    print(\"Checking function operation...\")\n    print(\"-\" * 40)\n\n    x = np.random.random(1024)\n    print(np.allclose(fft_scratch(x), np.fft.fft(x)))\n    print(np.allclose(DFT_slow(x), np.fft.fft(x)))\n    print(np.allclose(fft(x), np.fft.fft(x)))\n    print(np.allclose(FFT(x), np.fft.fft(x)))\n    print(np.allclose(FFT_vectorized(x), np.fft.fft(x)))\n\n    print(\"-\" * 40)\n\n    x = np.random.random(1024)\n    curr_time = time.perf_counter()\n\n    fft_scratch(x)\n    print(\"fft_scratch:\", time.perf_counter() - curr_time)\n    curr_time = time.perf_counter()\n\n    DFT_slow(x)\n    print(\"DFT_slow:\", time.perf_counter() - curr_time)\n    curr_time = time.perf_counter()\n\n    FFT(x)\n    print(\"FFT:\", time.perf_counter() - curr_time)\n    curr_time = time.perf_counter()\n\n    FFT_vectorized(x)\n    print(\"FFT_vectorized:\", time.perf_counter() - curr_time)\n    curr_time = time.perf_counter()\n\n    fft(x)\n    print(\"scipy fft:\", time.perf_counter() - curr_time)\n    curr_time = time.perf_counter()\n\n    np.fft.fft(x)\n    print(\"numpy fft:\", time.perf_counter() - curr_time)\n    curr_time = time.perf_counter()\n\n    np.fft.rfft(x)\n    print(\"numpy rfft:\", time.perf_counter() - curr_time)\n    curr_time = time.perf_counter()\n\n    np.fft.hfft(x)\n    print(\"numpy hfft:\", time.perf_counter() - curr_time)\n\n    print(\"-\" * 40)\n\n    x = np.random.random(1024 * 16)\n    curr_time = time.perf_counter()\n\n    FFT(x)\n    print(\"FFT:\", time.perf_counter() - curr_time)\n    curr_time = time.perf_counter()\n\n    FFT_vectorized(x)\n    print(\"FFT_vectorized:\", time.perf_counter() - curr_time)\n    curr_time = time.perf_counter()\n\n    fft(x)\n    print(\"scipy fft:\", time.perf_counter() - curr_time)\n    curr_time = time.perf_counter()\n\n    np.fft.fft(x)\n    print(\"numpy fft:\", time.perf_counter() - curr_time)\n    curr_time = time.perf_counter()\n\n    # In jupyter notebook\n    # %timeit DFT_slow(x)\n    # %timeit FFT(x)\n    # %timeit np.fft.fft(x)\n\n    print(\"Check function operation in frequency domain...\")\n    fs = 1000\n    total_time = 0.1\n    frequency = 100\n    sample_list = np.arange(0, total_time * fs)\n    a_0 = np.sin(2 * np.pi * frequency * sample_list / fs)\n    a_1 = np.sin(2 * np.pi * 2 * frequency * sample_list / fs)\n    a = (a_0 + a_1) / 2\n    n = len(a)\n    bins = np.arange(0, n) * fs / n\n\n    a_fft_scratch = fft_scratch(a)\n    a_fft_numpy = np.fft.fft(a)\n    a_fft_scipy = fft(a)\n\n    a_ifft_scratch = ifft_scratch(a_fft_scratch)\n    a_ifft_numpy = np.fft.ifft(a_fft_numpy)\n    a_ifft_scipy = ifft(a_fft_scipy)\n\n    a_dct_scipy = dct(a)\n    a_idct_scipy = idct(a_dct_scipy)\n\n    # plt.plot(bins, np.abs(a_fft_numpy/n), \"o\")\n    # plt.plot(bins, np.abs(a_fft_scipy/n), \"x\")\n    # try:\n    #     plt.plot(bins, np.abs(a_fft_scratch/n), \".\", color=\"r\")\n    # except ValueError:\n    #     pass\n    # plt.xticks(np.arange(0, 1100, 100))\n    # plt.yticks(np.arange(-1, 1.2, 0.2))\n    # plt.grid()\n    # plt.show()\n", "meta": {"hexsha": "f3eefd5d4ed395a6d12c4469d2c4b17a402bd53a", "size": 6947, "ext": "py", "lang": "Python", "max_stars_repo_path": "study/fft_scratch/fft_scratch.py", "max_stars_repo_name": "ooshyun/filterdesign", "max_stars_repo_head_hexsha": "59dbea191b8cd44aa9f2d02d3787b5805d486ae2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-27T00:38:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T00:38:32.000Z", "max_issues_repo_path": "study/fft_scratch/fft_scratch.py", "max_issues_repo_name": "ooshyun/FilterDesign", "max_issues_repo_head_hexsha": "7162ccad8e1ae8aebca370da56be56603b9e8b24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "study/fft_scratch/fft_scratch.py", "max_forks_repo_name": "ooshyun/FilterDesign", "max_forks_repo_head_hexsha": "7162ccad8e1ae8aebca370da56be56603b9e8b24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8223938224, "max_line_length": 98, "alphanum_fraction": 0.5747804808, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.9173026607161, "lm_q1q2_score": 0.8653352431670942}}
{"text": "# This code shows how a linear regression analysis can be applied to a 2-dimensional data\n# Implementation here is based on the theory described in the jupyter notebook.\n\n# Code Flow:\n    # 1. Import all relevant libraries.\n    # 2. Generate sample data & save it as a csv file (Stored as a csv file just to use pandas).\n    # 3. Load the dataset using pandas (X - inputs/feature, Y - output/target).\n    # 4. Plot the generated data understand the trend.\n    # 5. Calculate weights (parameters - a & b) using the equation from the theory lecture.\n    # 6. Calculate Yhat from the weights above. Yhat = a*X + b.\n    # 7. Calculate R-squared using the equation from the theory lecture to validate the model.\n    \n# 1.Imports:\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport pandas as pd\n\n# 2.Generate sample data:\nN = 100\nw = np.array([2, 3])\nwith open('data_2d.csv', 'w') as f:\n    X = np.random.uniform(low=0, high=100, size=(N,2))\n    Y = np.dot(X, w) + 1 + np.random.normal(scale=5, size=N)\n    for i in range(N):\n        f.write(\"%s,%s,%s\\n\" % (X[i,0], X[i,1], Y[i]))\n        \n# 3.Load the data:\ndf = pd.read_csv('data_2d.csv',header = None)\ndf['ones'] = np.ones(len(X))\nX = df[[0,1,'ones']].as_matrix()\nY = df[2].values\n\n# 4.Plot the data:\nfig = plt.figure(1)\nax = fig.add_subplot(111, projection='3d')\nax.scatter(X[:,0], X[:,1], Y)\nplt.xlabel('X1')\nplt.ylabel('X2')\nplt.show()\n\n# 5.Model: Y = a*X + B\n# Apply the equations from the jupyter notebook to calculate a & b:\n# Denominator is same for both a & b\nw = np.linalg.solve(np.dot(X.T,X),np.dot(X.T,Y))\n\n# 6.Predict Y:\nYhat = np.dot(X,w)\n\n# 7.R-squared:\nd1 = Y - Yhat\nd2 = Y - Y.mean()\nr2 = 1 - d1.dot(d1)/d2.dot(d2)\n\nprint('the r-squared is {}'.format(r2))\n", "meta": {"hexsha": "0896f4fe50346cf9ba13c2f16227d34270233d6f", "size": 1766, "ext": "py", "lang": "Python", "max_stars_repo_path": "1.Linear Regression/1.Code - Using Theory/1.2D - Regression.py", "max_stars_repo_name": "ananth-repos/machine-learning", "max_stars_repo_head_hexsha": "a510dcf81fab9137c33f568e73d65262667b3973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1.Linear Regression/1.Code - Using Theory/1.2D - Regression.py", "max_issues_repo_name": "ananth-repos/machine-learning", "max_issues_repo_head_hexsha": "a510dcf81fab9137c33f568e73d65262667b3973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1.Linear Regression/1.Code - Using Theory/1.2D - Regression.py", "max_forks_repo_name": "ananth-repos/machine-learning", "max_forks_repo_head_hexsha": "a510dcf81fab9137c33f568e73d65262667b3973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5357142857, "max_line_length": 96, "alphanum_fraction": 0.6523216308, "include": true, "reason": "import numpy", "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446471538802, "lm_q2_score": 0.8887587942290706, "lm_q1q2_score": 0.8653352426120714}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 27 15:10:11 2019\n\n@author: UO270318\n\"\"\"\n\n################### DERIVADAS #########################\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\na=0\nb=1\nh=0.1\nh2=0.01\nf= lambda x: np.exp(x)\ndf= lambda x: np.exp(x)\nxp=np.arange(a,b+h,h)\nnum_puntos=1/h +1\n### DERIVADA PROGRESIVA ###\ndef df_p(f,x0,h):\n    return (f(x0+h)-f(x0))/h\n\n### DERIVADA REGRESIVA ###\ndef df_r(f,x0,h):\n    return (f(x0)-f(x0-h))/h\n\n### DERIVADA NUMERICA CENTRADA ###\ndef df_c(f,x0,h):\n    return ((df_p(f,x0,h)+df_r(f,x0,h))/2)\n\n###################### EJERCICIO 1 #######################\n\n### CON H=01 ###\nplt.plot(xp[1:-1],df(xp[1:-1]),label='derivada exacta') #evaluar de 0.1 a 0.9\nplt.plot(xp[1:-1],df_p(f,xp[1:-1],h),label='derivada progresiva')\nplt.plot(xp[1:-1],df_r(f,xp[1:-1],h),label='derivada regresiva')\nplt.plot(xp[1:-1],df_c(f,xp[1:-1],h),label='derivada centrada')\nplt.legend()\nplt.title('Derivada con h=0.1')\nplt.show()\n\nerrorP=abs(df(xp[1:-1])-df_p(f,xp[1:-1],h))\nerrorR=abs(df(xp[1:-1])-df_r(f,xp[1:-1],h))\nerrorC=abs(df(xp[1:-1])-df_c(f,xp[1:-1],h))\n\n\nplt.plot(xp[1:-1],errorP,label='derivada progresiva')\nplt.plot(xp[1:-1],errorR,label='derivada regresiva')\nplt.plot(xp[1:-1],errorC,label='derivada centrada')\nplt.legend()\nplt.title('Error con h=0.1')\nplt.show()\n\n### CON H=0.01 ###\nplt.plot(xp[1:-1],df(xp[1:-1]),label='derivada exacta') #evaluar de 0.1 a 0.9\nplt.plot(xp[1:-1],df_p(f,xp[1:-1],h2),label='derivada progresiva')\nplt.plot(xp[1:-1],df_r(f,xp[1:-1],h2),label='derivada regresiva')\nplt.plot(xp[1:-1],df_c(f,xp[1:-1],h2),label='derivada centrada')\nplt.legend()\nplt.title('Derivada con h=0.01')\nplt.show()\n\nerrorP2=abs(df(xp[1:-1])-df_p(f,xp[1:-1],h2))\nerrorR2=abs(df(xp[1:-1])-df_r(f,xp[1:-1],h2))\nerrorC2=abs(df(xp[1:-1])-df_c(f,xp[1:-1],h2))\n\nplt.plot(xp[1:-1],errorP2,label='derivada progresiva')\nplt.plot(xp[1:-1],errorR2,label='derivada regresiva')\nplt.plot(xp[1:-1],errorC2,label='derivada centrada')\nplt.legend()\nplt.title('Error con h=0.01')\nplt.show()\n\n### ERROR RELATIVO ###\nerrorRelP= np.linalg.norm(df(xp[1:-1])-df_p(f,xp[1:-1],h))/np.linalg.norm(df(xp[1:-1]))\nerrorRelR= np.linalg.norm(df(xp[1:-1])-df_r(f,xp[1:-1],h))/np.linalg.norm(df(xp[1:-1]))\nerrorRelC= np.linalg.norm(df(xp[1:-1])-df_c(f,xp[1:-1],h))/np.linalg.norm(df(xp[1:-1]))\n\nprint('relativa progresiva',errorRelP)\nprint('relativa regresiva',errorRelR)\nprint('relativa centrada',errorRelC)\n\n\n###################### EJERCICIO 2 #######################\n\ndef dfOrden2_p(f,x0,h):\n    return (-3*f(x0)+4*f(x0+h)-f(x0+2*h))/(2*h)\n\ndef dfOrden2_r(f,x2,h):\n    return (f(x2-2*h)-4*f(x2-h)+3*f(x2))/(2*h)\n\nf= lambda x: 1/x\ndf= lambda x: -1/x**2\na=0.2\nb=1.2\nh=0.01\nxp=np.arange(a,b+h,h)\ndfa=np.zeros(len(xp))\ndfa[0]=df_p(f,xp[0],h)\ndfa[-1]=df_r(f,xp[-1],h)\ndfa[1:-1]=df_c(f,xp[1:-1],h)\nplt.plot(xp,dfa,label='derivada aproximada')\nplt.legend()\nplt.show()\n\ndfb=np.zeros(len(xp))\ndfb[0]=dfOrden2_p(f,xp[0],h)\ndfb[-1]=dfOrden2_r(f,xp[-1],h)\ndfb[1:-1]=df_c(f,xp[1:-1],h)\nplt.plot(xp,dfa,label='derivada aproximada')\nplt.legend()\nplt.show()\n\nEa= np.linalg.norm(df(xp)-dfa)/np.linalg.norm(df(xp))\nEb= np.linalg.norm(df(xp)-dfb)/np.linalg.norm(df(xp))\n\nprint('relativa global con procedimiento a',Ea)\nprint('relativa',Eb)\n\n###################### EJERCICIO 3 #######################\ndef D2f(f,x1,h):\n    return (f(x1-h)-2*f(x1)+f(x1+h))/(h**2)\n\n\nf=lambda x: np.sin(2*np.pi*x)\nd2f=lambda x: -4*np.pi**2*np.sin(2*np.pi*x)\na=0;b=1;h=0.01\nxp=np.arange(a,b+h,h)\nd2_f=D2f(f,xp[1:-1],h)\nplt.plot(xp[1:-1],d2f(xp[1:-1]),label='derivada 2exacta')\nplt.plot(xp[1:-1],d2_f,label='derivada 2 numerica')\nplt.legend()\nplt.show()\nEc= np.linalg.norm(d2f(xp[1:-1])-d2_f)/np.linalg.norm(d2f(xp[1:-1]))\nprint('Error relativo global de D2f es',Ec)\n", "meta": {"hexsha": "ea536cdbae5226dac421c3b56dcb2ae29a0fcaf3", "size": 3738, "ext": "py", "lang": "Python", "max_stars_repo_path": "Sesion7.py", "max_stars_repo_name": "Ainiall/CN", "max_stars_repo_head_hexsha": "5986f3ac188da212eb71cf55350b4fe371371d4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-18T11:45:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T11:45:32.000Z", "max_issues_repo_path": "Sesion7.py", "max_issues_repo_name": "Ainiall/CN", "max_issues_repo_head_hexsha": "5986f3ac188da212eb71cf55350b4fe371371d4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sesion7.py", "max_forks_repo_name": "Ainiall/CN", "max_forks_repo_head_hexsha": "5986f3ac188da212eb71cf55350b4fe371371d4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0869565217, "max_line_length": 87, "alphanum_fraction": 0.6112894596, "include": true, "reason": "import numpy", "num_tokens": 1522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629193, "lm_q2_score": 0.9173026533686324, "lm_q1q2_score": 0.8653352391578969}}
{"text": "import numpy as np\n\n\ndef load_linear_data(point_count=100, min_=0., max_=10., w=0.5493, b=1.1973, random_state=None, scale=1.0, loc=0.0):\n    \"\"\"load linear data\n\n    Args:\n        point_count: a integer number, default = 100.\n        min_: bottom range of x data, a float number, default = 0.0.\n        max_: top range of x data, a float number, default = 10.0.\n        w: the coef of linear, a float number, default = 0.5493.\n        b: the intercept of linear, a float number, default = 1.1973.\n        random_state: random seed, a int number, default = None.\n        scale: noise's scale. A float number, default = 1.0.\n        loc: noise's loc. A float number, default = 0.0\n\n    Returns:\n        A tuple. (x, y). the shape of x is (point_count, 1), the shape\n            of y is (point_count, ).\n\n    Raises:\n        AssertionError: random_state is not a integer.\n    \"\"\"\n    if random_state is not None:\n        assert isinstance(random_state, int)\n        np.random.seed(random_state)\n\n    x = np.random.uniform(min_, max_, point_count)\n    noise = np.random.normal(scale=scale, loc=loc, size=[point_count])\n    y = w * x + b + noise\n    return x.reshape([-1, 1]), y\n\n\ndef load_data_from_func(func=lambda X_data: 2.1084 * np.square(X_data) - 0.1932 * X_data + 10.813,\n                        x_min=0, x_max=10, n_samples=500, loc=0, scale=1, random_state=None):\n    \"\"\"load point data from a function\n\n    Args:\n        func: Function for creating data.A Function object, default = lambda X_data:\n            2.1084 *  np.square(X_data) - 0.1932 * X_data + 10.813.\n        x_min: min value of x. A number, x_min must be less ther x_max, default = 0.\n        x_max: max value of x. A number, x_max must be greater ther x_min, default = 0.\n        n_samples: sample count. A int number, default = 500.\n        loc: loc of noise's destribution. A float number, default = 0.\n        scale: scale of noise's destribution. A float number, default = 1.\n        random_state: random seed. A positive int number, default = None.\n\n    Returns:\n        A tuple of x and y. x's shape is (n_samples, 1), y's shape is (n_samples, )\n    \"\"\"\n    if random_state is not None and isinstance(random_state, int):\n        np.random.seed(random_state)\n    x = np.random.uniform(x_min, x_max, n_samples)\n    y = func(x)\n    noise = np.random.normal(loc=loc, scale=scale, size=n_samples)\n    y += noise\n    return x.reshape([-1, 1]), y", "meta": {"hexsha": "a20e5215a72466845e20599cb53aae9d2708ce90", "size": 2419, "ext": "py", "lang": "Python", "max_stars_repo_path": "LossJLearn/datasets/_base.py", "max_stars_repo_name": "LossJ/Statistical-Machine-Learning", "max_stars_repo_head_hexsha": "c70fd82ee287f4902d8607ec459e52b0a301d6a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LossJLearn/datasets/_base.py", "max_issues_repo_name": "LossJ/Statistical-Machine-Learning", "max_issues_repo_head_hexsha": "c70fd82ee287f4902d8607ec459e52b0a301d6a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-26T07:57:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-26T07:57:23.000Z", "max_forks_repo_path": "LossJLearn/datasets/_base.py", "max_forks_repo_name": "LossJ/Statistical-Machine-Learning", "max_forks_repo_head_hexsha": "c70fd82ee287f4902d8607ec459e52b0a301d6a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4385964912, "max_line_length": 116, "alphanum_fraction": 0.6308391897, "include": true, "reason": "import numpy", "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.9173026494123036, "lm_q1q2_score": 0.8653352266596477}}
{"text": "#importing libraries\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport math\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef ackley_function(x1,x2):\n  #returns the point value of the given coordinate\n  part_1 = -0.2*math.sqrt(0.5*(x1*x1 + x2*x2))\n  part_2 = 0.5*(math.cos(2*math.pi*x1) + math.cos(2*math.pi*x2))\n  value = math.exp(1) + 20 -20*math.exp(part_1) - math.exp(part_2)\n  #returning the value\n  return value\n\ndef ackley_function_range(x_range_array):\n  #returns an array of values for the given x range of values\n  value = np.empty([len(x_range_array[0])])\n  for i in range(len(x_range_array[0])):\n    \n    #returns the point value of the given coordinate\n    part_1 = -0.2*math.sqrt(0.5*(x_range_array[0][i]*x_range_array[0][i] + x_range_array[1][i]*x_range_array[1][i]))\n    part_2 = 0.5*(math.cos(2*math.pi*x_range_array[0][i]) + math.cos(2*math.pi*x_range_array[1][i]))\n    \n    value_point = math.exp(1) + 20 -20*math.exp(part_1) - math.exp(part_2)\n    value[i] = value_point\n  #returning the value array\n  return value\n\ndef plot_ackley_general():\n  #this function will plot a general ackley function just to view it.\n  limit = 1000 #number of points\n  #common lower and upper limits for both x1 and x2 are used\n  lower_limit = -5\n  upper_limit = 5\n  #generating x1 and x2 values\n  x1_range = [np.random.uniform(lower_limit,upper_limit) for x in range(limit)]\n  x2_range = [np.random.uniform(lower_limit,upper_limit) for x in range(limit)]\n  #This would be the input for the Function\n  x_range_array = [x1_range,x2_range]\n  #generate the z range\n  z_range = ackley_function_range(x_range_array)\n  #plotting the function\n  fig = plt.figure()\n  ax = fig.gca(projection='3d')\n  ax.scatter(x1_range, x2_range, z_range, label='Ackley Function')\n  \n  def plot_ackley(x1_range,x2_range):\n  #This would be the input for the Function\n  x_range_array = [x1_range,x2_range]\n  #generate the z range\n  z_range = ackley_function_range(x_range_array)\n  #plotting the function\n  fig = plt.figure()\n  ax = fig.gca(projection='3d')\n  ax.scatter(x1_range, x2_range, z_range, label='Ackley Function')\n", "meta": {"hexsha": "b008722b09a0028ba848ecbe0e117e8106b1f7be", "size": 2104, "ext": "py", "lang": "Python", "max_stars_repo_path": "ackley.py", "max_stars_repo_name": "adhishagc/Ackley-Function", "max_stars_repo_head_hexsha": "b09d36a711dee9c31ae6ecaa7dcac7f1586a8071", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-05-17T13:13:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T10:51:52.000Z", "max_issues_repo_path": "ackley.py", "max_issues_repo_name": "adhishagc/Ackley-Function", "max_issues_repo_head_hexsha": "b09d36a711dee9c31ae6ecaa7dcac7f1586a8071", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-05-15T05:06:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-06T12:56:49.000Z", "max_forks_repo_path": "ackley.py", "max_forks_repo_name": "adhishagc/Ackley-Function", "max_forks_repo_head_hexsha": "b09d36a711dee9c31ae6ecaa7dcac7f1586a8071", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-23T13:15:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-23T13:15:39.000Z", "avg_line_length": 37.5714285714, "max_line_length": 116, "alphanum_fraction": 0.7224334601, "include": true, "reason": "import numpy", "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.980580652952557, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.8652916919555191}}
{"text": "import math\nimport pandas as pd\nimport numpy as np\n\n\"\"\"\nREFERENCE:\nhttp://www.statskingdom.com/doc_linear_regression.html#multi\n\"\"\"\n\n\n# ========================================================\n# HELPER FUNCTIONS\n# ========================================================\ndef compute_r(x, y):\n    \"\"\"\n    Computes the Coefficient of Co-relation using Pearson's method\n    \"\"\"\n    n = len(x)\n    numerator = n * ((x * y).sum()) - (x.sum() * y.sum())\n    denominator = (n * (x ** 2).sum()) - x.sum() ** 2\n    denominator *= (n * (y ** 2).sum()) - y.sum() ** 2\n    denominator = math.sqrt(denominator)\n    return numerator / denominator\n\n\ndef form_equation(b):\n    b_ = np.reshape(b, (b.shape[0],))\n    y = 'Y = ' + str(round(b_[0], 3))\n    for i, bi in zip(range(len(b_[1:])), b_[1:]):\n        if bi > 0:\n            sign = ' +'\n        else:\n            sign = ' '\n        y += sign + str(round(bi, 3)) + ' X' + str(i)\n    return y\n\n\ndef compute_equation(x, y):\n    y = np.reshape(y, (y.shape[0], 1))\n\n    # Formula to be used\n    # B = (X'*X)^-1*X'*Y\n    # So we do this step by step\n\n    # 1. X_T = X Transpose\n    x_t = np.matrix.transpose(x)\n\n    # 2. (X'*X)^-1\n    x_t_x = np.linalg.inv(np.dot(x_t, x))\n\n    # 3. X_T_Y\n    h = np.dot(x_t_x, x_t)\n\n    # 4. B computation\n    b = np.dot(h, y)\n\n    # 5. y^ is predicted y values\n    y_dash = np.dot(x, b)\n\n    # 6. ERROR\n    squared_error = ((y - y_dash) ** 2).sum()\n    print('SSE :', squared_error)\n\n    # B contains the equation\n    print(form_equation(b))\n\n\n# ==============================================\n# EXECUTION\n# ==============================================\n\n# Load the data\ndata = pd.read_csv('data.csv', dtype=float)\n\n# Metas\ncolumns = data.columns[:-1]\ny_label = data.columns[-1]\n\n# Split\nY = data.iloc[:, -1].to_numpy()\n\n# Compute Co-relation and Greater than threshold\nthreshold = 0.7\nX_matrix = []\nfor x_label in columns:\n    # Obtain best Attributes\n    X = data[x_label]\n    r = compute_r(X, Y)\n    if r >= threshold:\n        X_matrix.append(X.to_numpy())\n\n# Convert to numpy array\nX_matrix = np.insert(X_matrix, 0, np.ones((1, len(X_matrix[0]))), axis=0)\nX_matrix = np.array(X_matrix, dtype=np.float)\nX_matrix = np.matrix.transpose(X_matrix)\n\n# X_matrix = np.array([[1, 1, 1], [1, 2, 2], [1, 3, 3], [1, 4, 1], [1, 5, 2], [1, 6, 3]])\n# Y = np.array([2.1, 3.9, 6.3, 4.95, 7.1, 8.5])\n\ncompute_equation(X_matrix, Y)\n", "meta": {"hexsha": "de29260be0fc53c782218437a08e13f6141511ac", "size": 2385, "ext": "py", "lang": "Python", "max_stars_repo_path": "Problems/RegressionProblem/Multiple_Linear_Regression.py", "max_stars_repo_name": "AdarshRevankar/Crack-it", "max_stars_repo_head_hexsha": "bc664a03eae2d171ae5ce3bb58a1c709700991c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Problems/RegressionProblem/Multiple_Linear_Regression.py", "max_issues_repo_name": "AdarshRevankar/Crack-it", "max_issues_repo_head_hexsha": "bc664a03eae2d171ae5ce3bb58a1c709700991c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Problems/RegressionProblem/Multiple_Linear_Regression.py", "max_forks_repo_name": "AdarshRevankar/Crack-it", "max_forks_repo_head_hexsha": "bc664a03eae2d171ae5ce3bb58a1c709700991c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6138613861, "max_line_length": 89, "alphanum_fraction": 0.5157232704, "include": true, "reason": "import numpy", "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.977022630759019, "lm_q2_score": 0.8856314692902446, "lm_q1q2_score": 0.8652819880089301}}
{"text": "import numpy as np\nimport math\nfrom scipy.stats import norm\n#\n# CONSTRUCT MODELS (PDF) \n# =======================\n#\n# read files\ndata = np.genfromtxt('Antofagasta.csv', delimiter=',')\nt2m=data[1::,2] # skip first line, read column 2 (2m air temperature)\nnt=len(t2m)\nny=nt//12       # rounds off to full year, floor division\n#\n# calculate monsthly statistics\nt2m_mean=[0.0]*12\nt2m_stdv=[0.0]*12\nx=[0.0]*ny\n#\n# get means and standard deviations\nfor m in range(12):        # loop through months\n    # construct mean and stdv for temperatures\n    for y in range(ny):\n        x[y]=t2m[(y*12)+m] # pass month-specific temperature to x vector \n    t2m_mean[m]=np.mean(x)        \n    t2m_stdv[m]=np.std(x)     \n#\n# print summary\nprint(' '.join('{:0.2f}'.format(i) for i in t2m_mean))        \nprint(' '.join('{:0.2f}'.format(i) for i in t2m_stdv))        \n#\n#\n# HYPOTHESES TST\n# ==============\n# NOTE: here we use the normal distribution. t may be more fitting given the relatively small sample size.\n#\n# H0: the mean is still the one caulculated from observations\n# HA: the mean is different from the one calculated from observations\n# We test this by assuming H0 is correct and calculating the probability of getting a signal (temperature difference) at least as extreme as the observed.\n#\n# this is the data we were given (temperatures are converted to Kelvin like in dataset)\ntm_jan=23.6+273.15    # predicted january temperatures\ntm_jun=17.2+273.15    # predicted june temperatures\ndf=30                 # degrees of freedom (years in simulation)\n#\n# we calculate the standard error (standard deviation of sampling distribution)\nserr_jan=t2m_stdv[0]/(float(df))**0.5    # standard error january\nserr_jun=t2m_stdv[5]/(float(df))**0.5    # standard error june\n#\n# calculate the z-score/look at how far away we are from the mean (expressed in standard deviations of the sampling distribution)\nz_jan=tm_jan-t2m_mean[0]/serr_jan\nz_jun=tm_jun-t2m_mean[5]/serr_jun\n#\n# calculate p-values (2-tailed test)\np_jan=2*(1-(norm.cdf(z_jan, 0, 1)))   \np_jun=2*(1-(norm.cdf(z_jun, 0, 1)))   \n#\nprint (\"P(Jan signal or more extreme | H0) :\",p_jan)\nprint (\"P(Jun signal or more extreme | H0) :\",p_jun)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "d9a0ad2a6919a54ac62696bdf00156e189a64970", "size": 2199, "ext": "py", "lang": "Python", "max_stars_repo_path": "course/source/exercises/E102/submission/mutz_e102.py", "max_stars_repo_name": "sebastian-mutz/integrate", "max_stars_repo_head_hexsha": "ce2a83358e2eb7f482d4fb70d167b1eba2abf2a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-17T14:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T13:07:42.000Z", "max_issues_repo_path": "course/source/exercises/E102/submission/mutz_e102.py", "max_issues_repo_name": "sebastian-mutz/integrate", "max_issues_repo_head_hexsha": "ce2a83358e2eb7f482d4fb70d167b1eba2abf2a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "course/source/exercises/E102/submission/mutz_e102.py", "max_forks_repo_name": "sebastian-mutz/integrate", "max_forks_repo_head_hexsha": "ce2a83358e2eb7f482d4fb70d167b1eba2abf2a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-24T13:04:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T13:04:01.000Z", "avg_line_length": 27.835443038, "max_line_length": 154, "alphanum_fraction": 0.6803092315, "include": true, "reason": "import numpy,from scipy", "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889438, "lm_q2_score": 0.903294206053042, "lm_q1q2_score": 0.8652766085369071}}
{"text": "import numpy as np\n\n\ndef gen_el_ma(cur, i):\n    n = len(cur)\n    if i == n:\n        return np.identity(n)\n    else:\n        new = np.identity(n)\n        for j in range(i, n):\n            num = cur[j][i - 1]\n            pivot = cur[i - 1][i - 1]\n            k = -num / pivot\n            new[j][i - 1] = k\n        cur = new.dot(cur)\n        return (gen_el_ma(cur, i + 1)).dot(new)\n\n\ndef solve_sim(arr):\n    n = len(arr)\n    ans = []\n    print(arr)\n    for i in range(n - 1, -1, -1):\n        total = arr[i][-1]\n        target = i\n        cur = target + 1\n        for j in range(len(ans)):\n            total -= ans[j] * arr[i][cur]\n            cur += 1\n        ans.insert(0, total / arr[i][target])\n    return ans\n\n\ndef main():\n    # ans is x=2, y=3\n    a = np.array([\n      [1, 3, 5, 31],\n      [2, 4, 6, 40],\n      [4, 1, 7, 39]])\n    # N = int(input())\n    # a = [list(map(int, input().split())) for i in range(N)]\n\n    el_ma = gen_el_ma(a, 1)\n    print(el_ma)\n    arr = el_ma.dot(a)\n    result = solve_sim(arr)\n    print(result)\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "6e73524197e1e5ed3377bb60355da7105bc53ecb", "size": 1069, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 1/MA1101R Linear Algebra/simultaneous_equation_solver.py", "max_stars_repo_name": "mazx4960/code_dump", "max_stars_repo_head_hexsha": "f8f30098c2578b82b230de609ca40007a9f35025", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Semester 1/MA1101R Linear Algebra/simultaneous_equation_solver.py", "max_issues_repo_name": "mazx4960/code_dump", "max_issues_repo_head_hexsha": "f8f30098c2578b82b230de609ca40007a9f35025", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-19T02:19:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-19T02:19:39.000Z", "max_forks_repo_path": "Semester 1/MA1101R Linear Algebra/simultaneous_equation_solver.py", "max_forks_repo_name": "mazx4960/code_dump", "max_forks_repo_head_hexsha": "f8f30098c2578b82b230de609ca40007a9f35025", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5576923077, "max_line_length": 61, "alphanum_fraction": 0.4499532273, "include": true, "reason": "import numpy", "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399069145609, "lm_q2_score": 0.8918110526265555, "lm_q1q2_score": 0.8652706726857657}}
{"text": "from sympy import ( symbols, solve, diff, integrate, exp, sqrt, lambdify, pprint )\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# The length of a petal on a certain flower varies from 2.25 cm to 6.25 cm and has a probability density function defined by:\n\nx = symbols( 'x' )\nF = 1 / ( 2 * sqrt( x ) )\n\n# What does the petal distribution look like?\n\ng_xlim = [ 1, 7 ]\ng_ylim = [ -5, 10 ]\n\nlam_p = lambdify( x, F, np )\nx_vals = np.linspace( g_xlim[0], g_xlim[1], 1000, endpoint=True )\ny_vals = lam_p( x_vals )\nplt.plot( x_vals, y_vals )\n\nx_min, x_max = 2.25, 6.25\n\nplt.vlines( x = x_min, ymin = 0, ymax = F.subs( { x: x_min } ), color = 'Black', zorder = 1 )\nplt.vlines( x = x_max, ymin = 0, ymax = F.subs( { x: x_max } ), color = 'Black', zorder = 1 )\n\n# Find the probabilities that the length of a randomly selected petal will be as follows.\n\n# A\n# The probability that the length of a randomly selected petal is between 2.5 cm and 2.7 cm is\n\na, b = 2.5, 2.7\nbounds = np.arange( a, b, 1/50., dtype=float)\n\nfor n in bounds:\n\ty = F.subs( { x: n } )\n\tplt.vlines( x = n, ymin = 0, ymax = y, color = 'Teal', zorder = 1, alpha = .4 )\n\narea = integrate( F, ( x, a, b ) ).evalf()\ntotal_area = integrate( F, ( x, 2.25, 6.25 ) ).evalf()\n\nplt.show()\n\narea_pct = round( ( area / total_area ), 4 )\n\n# B\n# Greater than or equal to 2.7 cm\n\na, b = 2.7, x_max\nbounds = np.arange( a, b, 1/50., dtype=float)\n\nfor n in bounds:\n\ty = F.subs( { x: n } )\n\tplt.vlines( x = n, ymin = 0, ymax = y, color = 'Teal', zorder = 1, alpha = .4 )\n\narea = integrate( F, ( x, a, b ) ).evalf()\ntotal_area = integrate( F, ( x, 2.25, 6.25 ) ).evalf()\n\nplt.show()\n\narea_pct = round( ( area / total_area ), 4 )\n\n# C\n# Less than or equal to 2.5 cm\n\na, b = x_min, 2.5\nbounds = np.arange( a, b, 1/50., dtype=float)\n\nfor n in bounds:\n\ty = F.subs( { x: n } )\n\tplt.vlines( x = n, ymin = 0, ymax = y, color = 'Teal', zorder = 1, alpha = .4 )\n\narea = integrate( F, ( x, a, b ) ).evalf()\ntotal_area = integrate( F, ( x, 2.25, 6.25 ) ).evalf()\n\nplt.show()\n\narea_pct = round( ( area / total_area ), 4 )", "meta": {"hexsha": "68b8fb07e74240bbe41bf18c0dbffd170dd68ad9", "size": 2055, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Module 9/petal_length.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Module 9/petal_length.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Module 9/petal_length.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0394736842, "max_line_length": 125, "alphanum_fraction": 0.6077858881, "include": true, "reason": "import numpy,from sympy", "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399060540358, "lm_q2_score": 0.8918110454379297, "lm_q1q2_score": 0.8652706649436482}}
{"text": "import numpy as np\n\nclass PCA:\n    \n    def __init__(self, n_components):\n        self.n_components = n_components\n        self._center = None\n        self._cov_mat = None\n        self._eigen_values = None\n        self._eigen_vectors = None\n        self.explained_variance_ratio = None\n    \n    def fit(self, X):\n        '''\n        Build the subspace on which to project the data. It is generated by the eigen vectors corresponding to the k highest \n        eigen values:\n            1- center X\n            2- compute covariance matrix\n            3- compute k eigen vectors V={v_i}_k corresponding to the k larger eigenvalues \\lamb={\\lamb_i}_k\n            4- project onto span(V)\n            \n        As the covariance matrix of X is symmetric, its eigen vectors are orthogonal, and as such the covariance of the projection of X in the subspace\n        generated by its eigen vectors is a diagonal matrix where entries are its eigen values. The explained variance ratio per principal direction is\n        simply the corresponding eigen value divided by the sum of all the eigen values (which is the total variance).\n        '''\n        self._center = X.mean(axis=0)\n        self._cov_mat = np.cov(X - self._center, rowvar=False)\n        \n        lambs, vs = np.linalg.eigh(self._cov_mat)\n        lambs, vs = lambs[::-1], np.flip(vs, axis=1)\n        \n        self._eigen_values, self._eigen_vectors = lambs[:self.n_components], vs[:, :self.n_components]\n        self.explained_variance_ratio = self._eigen_values / lambs.sum()\n        \n    def transform(self, X):\n        return (X - self._center) @ self._eigen_vectors\n    \n    def fit_transform(self, X):\n        self.fit(X)\n        return self.transform(X)", "meta": {"hexsha": "c8bbc4350ab8e99abaee8f02fb879ecc42d41f30", "size": 1711, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/decomposition.py", "max_stars_repo_name": "clabrugere/numpy-basics", "max_stars_repo_head_hexsha": "81efb4b8ac58fc17dc8f6c676004bbc3a99a92c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:05:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T18:05:26.000Z", "max_issues_repo_path": "models/decomposition.py", "max_issues_repo_name": "clabrugere/numpy-basics", "max_issues_repo_head_hexsha": "81efb4b8ac58fc17dc8f6c676004bbc3a99a92c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/decomposition.py", "max_forks_repo_name": "clabrugere/numpy-basics", "max_forks_repo_head_hexsha": "81efb4b8ac58fc17dc8f6c676004bbc3a99a92c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.775, "max_line_length": 151, "alphanum_fraction": 0.6411455289, "include": true, "reason": "import numpy", "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399060540358, "lm_q2_score": 0.8918110440002044, "lm_q1q2_score": 0.8652706635487099}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# Image compression by SVD\n# 2017,2018 Tsuyoshi Okubo\n# 2019 modified by Tsuyoshi Okubo\n# 2020 modified by TO\n\n\n# By using the low rank approximation through SVD, perform data compression of a gray scale image. \n# \n# You can change sample image by modifying file open \"sample.jpg\".\n# \n# Also, you can set the rank of approximation by varying \"chi\".\n# \n# Let's see, how the image changes when you change the rank.\n\n# In[2]:\n\n\n## import libraries\nfrom PIL import Image ## Python Imaging Library\nimport numpy as np ## numpy\n#get_ipython().run_line_magic('matplotlib', 'inline')\nimport matplotlib.pyplot as plt\n\n\n# In[3]:\n\n\n## Rank for low rank approximation\nchi = 10 \n\n\n# In[4]:\n\n\nimg = Image.open(\"./sample.jpg\") ## load image\nimg_gray = img.convert(\"L\") ## convert to grayscale\n#img_gray.show(title=\"Original\") ## show image in external window\nimg_gray.save(\"./gray.png\") ## save grayscale image\n#img_gray.save(\"./gray.jpg\") ## save grayscale image in jpg\n\n\n# In[5]:\n\n\narray = np.array(img_gray,dtype=float) ## convert to ndarray\nprint(\"Array shape:\" +repr(array.shape)) ## print array shape\n\n\n# In[6]:\n\n\nu,s,vt = np.linalg.svd(array,full_matrices=False) ## svd \n\n\n# In[7]:\n\n\n#truncation\nu = u[:,:chi]\nvt = vt[:chi,:]\nst = s[:chi]\n\n\n# In[8]:\n\n\narray_truncated = np.dot(np.dot(u,np.diag(st)),vt) ## make truncated array\nnormalized_distance = np.sqrt(np.sum((array-array_truncated)**2))/np.sqrt(np.sum(array**2))\nprint(\"Low rank approximation with chi=\" +repr(chi))\nprint(\"Normalized distance:\" +repr(normalized_distance)) ## print normalized distance\n\n\n# In[9]:\n\n\nimg_gray_truncated = Image.fromarray(np.uint8(np.clip(array_truncated,0,255))) ## convert to grayscale image\n\n\n# In[10]:\n\n\n#img_gray_truncated.show(title=\"Truncated\") ## show image in external window\nimg_gray_truncated.save(\"./gray_truncated.png\") ## save compressed image\n#img_gray_truncated.save(\"./gray_truncated.jpg\") ## save compressed image in jpg\n\n\n# In[11]:\n\n\nplt.figure(figsize=(array.shape[1]*0.01,array.shape[0]*0.01))\nplt.axis(\"off\")\nplt.title(\"Original\")\nplt.imshow(img_gray,cmap='gray')\n\nplt.figure(figsize=(array_truncated.shape[1]*0.01,array_truncated.shape[0]*0.01))\nplt.axis(\"off\")\nplt.title(\"Compressed\")\nplt.imshow(img_gray_truncated,cmap='gray')\n\n\n# In[12]:\n\n\n## normalization of singular values\ns = s/np.sqrt(np.sum(s**2))\n\noutput_sv = len(s) ## number of singular values to output\nplt.figure()\nplt.title(\"Singular Value Spectrum of the image\")\nplt.plot(np.arange(output_sv),s[:output_sv],\"o\")\nplt.vlines([chi],0,1,  \"red\", linestyles='dashed') ## position of chi\nplt.xlabel(\"Index\")\nplt.ylabel(\"sigma\")\nplt.yscale(\"log\")\nplt.show()\n\n", "meta": {"hexsha": "804d7d79021ecc27ff2470da953f02b5a45e4d97", "size": 2668, "ext": "py", "lang": "Python", "max_stars_repo_path": "SVD/image_svd.py", "max_stars_repo_name": "taro-nakajima/Spin_map_for_ParaView", "max_stars_repo_head_hexsha": "bb1f4621d5112f4bf4edf1b189abbe6d4670e853", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SVD/image_svd.py", "max_issues_repo_name": "taro-nakajima/Spin_map_for_ParaView", "max_issues_repo_head_hexsha": "bb1f4621d5112f4bf4edf1b189abbe6d4670e853", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SVD/image_svd.py", "max_forks_repo_name": "taro-nakajima/Spin_map_for_ParaView", "max_forks_repo_head_hexsha": "bb1f4621d5112f4bf4edf1b189abbe6d4670e853", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6910569106, "max_line_length": 108, "alphanum_fraction": 0.7057721139, "include": true, "reason": "import numpy", "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816422, "lm_q2_score": 0.924141826246517, "lm_q1q2_score": 0.8652601400282292}}
{"text": "# Import Packages\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom src.utilities import Utils\n\n\n# Variable Declaration\n\n\n# Code\nclass UnivariateLR:\n    def __init__(self, data, label_index=-1):\n        self.data = data\n        self.label_index = label_index\n        self.m, self.X, self.y, self.theta = self.get_X_y(data)\n        self.validate_costs = []\n\n    def visualize_dataset(self):\n        print(\"Plotting data...\")\n        ax = sns.scatterplot(x=self.data.columns[0], y=self.data.columns[self.label_index],\n                             data=self.data)\n        ax.set_title(\"{} vs {} chart\".format(self.data.columns[0], self.data.columns[1]))\n        plt.show()\n\n    def get_X_y(self, data):\n        print(\"Splitting dependent and independent columns...\")\n        m = data.shape[0]\n        X = np.append(np.ones((m, 1)), data[data.columns[0]].values.reshape(m, 1), axis=1)\n        y = data[data.columns[self.label_index]].values.reshape(m, 1)\n        theta = np.zeros((data.shape[1], 1))\n        return m, X, y, theta\n\n    def compute_cost(self):\n        y_pred = self.X.dot(self.theta)\n        error = np.sum(np.square(y_pred - self.y)) * (0.5 / self.m)\n        return error\n\n    def gradient_descent(self, alpha, iterations):\n        print(\"Starting Gradient Descent...\")\n        for i in range(1,iterations+1):\n            y_pred = self.X.dot(self.theta)\n            error_gradient = np.dot(self.X.transpose(), y_pred - self.y)\n            self.theta = self.theta - ((alpha / self.m) * error_gradient)\n            self.validate_costs.append(self.compute_cost())\n            if i % 100==0:\n                print(\"Cost value after {} iterations is: {}\".format(i, self.validate_costs[-1]))\n\n    def visualize_cost_function(self):\n        print(\"Plotting Cost function to validate the modelling process...\")\n        assert len(self.validate_costs) > 0, \"Costs not yet computed.\"\n        plt.plot(self.validate_costs)\n        plt.xlabel(\"Iterations\")\n        plt.ylabel(\"$Cost - J(\\Theta)$\")\n        plt.title(\"Cost function VS Iterations\")\n        plt.show()\n\n    def plot_regression_fit(self):\n        print(\"Plotting regression fit over data...\")\n        t = np.squeeze(self.theta)\n        sns.scatterplot(x=self.data.columns[0], y=self.data.columns[self.label_index],\n                             data=self.data)\n        x_value = [x for x in range(int(min(self.data[self.data.columns[0]])), int(max(self.data[self.data.columns[0]])))]\n        y_value = [x*t[1]+t[0] for x in x_value]\n\n        sns.lineplot(x_value, y_value)\n        plt.xlabel(self.data.columns[0])\n        plt.ylabel(self.data.columns[self.label_index])\n        plt.show()\n\n    def predict(self, x):\n        return np.dot(self.theta.transpose(), x)\n\n    def pipeline(self, alpha, iterations):\n        self.visualize_dataset()\n        self.gradient_descent(alpha=alpha, iterations=iterations)\n        self.visualize_cost_function()\n        self.plot_regression_fit()", "meta": {"hexsha": "5d75a48519e234f42a5df748836a33ea047cb43e", "size": 2991, "ext": "py", "lang": "Python", "max_stars_repo_path": "algorithms/linear_regression/univariate.py", "max_stars_repo_name": "hardy8059/mlfs", "max_stars_repo_head_hexsha": "39769609cab04375ff117464bd642f1b1c749d2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algorithms/linear_regression/univariate.py", "max_issues_repo_name": "hardy8059/mlfs", "max_issues_repo_head_hexsha": "39769609cab04375ff117464bd642f1b1c749d2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorithms/linear_regression/univariate.py", "max_forks_repo_name": "hardy8059/mlfs", "max_forks_repo_head_hexsha": "39769609cab04375ff117464bd642f1b1c749d2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8607594937, "max_line_length": 122, "alphanum_fraction": 0.6168505517, "include": true, "reason": "import numpy", "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811651448431, "lm_q2_score": 0.8962513724408292, "lm_q1q2_score": 0.8652241941895924}}
{"text": "\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\n## E-M Coin Toss Example as given in the EM tutorial paper by Do and Batzoglou* ##\ndef get_binomial_log_likelihood(obs,probs):\n    \"\"\" Return the (log)likelihood of obs, given the probs\"\"\"\n    # Binomial Distribution Log PDF\n    # ln (pdf)      = Binomial Coeff * product of probabilities\n    # ln[f(x|n, p)] =   comb(N,k)    * num_heads*ln(pH) + (N-num_heads) * ln(1-pH)\n    N = sum(obs) #number of trials  \n    k = obs[0] # number of heads\n    binomial_coeff = math.factorial(N) / (math.factorial(N-k) * math.factorial(k))\n    prod_probs = obs[0]*math.log(probs[0]) + obs[1]*math.log(1-probs[0])\n    log_lik = binomial_coeff + prod_probs\n    return log_lik\n# 1st:  Coin B, {HTTTHHTHTH}, 5H,5T\n# 2nd:  Coin A, {HHHHTHHHHH}, 9H,1T\n# 3rd:  Coin A, {HTHHHHHTHH}, 8H,2T\n# 4th:  Coin B, {HTHTTTHHTT}, 4H,6T\n# 5th:  Coin A, {THHHTHHHTH}, 7H,3T\n# so, from MLE: pA(heads) = 0.80 and pB(heads)=0.45\n# represent the experiments\nhead_counts = np.array([5,9,8,4,7])\ntail_counts = 10-head_counts\n# initialise the pA(heads) and pB(heads)\n# pA_heads = np.zeros(100); pA_heads[0] = 0.10\n# pB_heads = np.zeros(100); pB_heads[0] = 0.50\n\npA_heads = [0.3]\npB_heads = [0.48]\n# E-M begins!\ndelta = 10e-15\nj = 0 # iteration counter\nimprovement = float('inf')\nwhile (improvement>delta):\n    expectation_A = np.zeros((len(head_counts),2), dtype=float) \n    expectation_B = np.zeros((len(head_counts),2), dtype=float)\n    i = 0\n    for h, t in zip(head_counts,tail_counts):\n        e = [h, t] # i'th experiment\n          # loglikelihood of e given coin A:\n        ll_A = get_binomial_log_likelihood(e,np.array([pA_heads[j],1-pA_heads[j]])) \n          # loglikelihood of e given coin B\n        ll_B = get_binomial_log_likelihood(e,np.array([pB_heads[j],1-pB_heads[j]])) \n# corresponding weight of A proportional to likelihood of A \n        weightA = math.exp(ll_A) / ( math.exp(ll_A) + math.exp(ll_B) ) \n# corresponding weight of B proportional to likelihood of B\n        weightB = math.exp(ll_B) / ( math.exp(ll_A) + math.exp(ll_B) ) \n        expectation_A[i,:] = np.dot(weightA, e) \n        expectation_B[i,:] = np.dot(weightB, e)\n        i += 1\n    # pA_heads[j+1] = sum(expectation_A)[0] / sum(sum(expectation_A)) \n    # pB_heads[j+1] = sum(expectation_B)[0] / sum(sum(expectation_B))\n    pA_heads += [sum(expectation_A)[0] / sum(sum(expectation_A))]\n    pB_heads += [sum(expectation_B)[0] / sum(sum(expectation_B))]\n    improvement = ( max( abs(np.array([pA_heads[j+1],pB_heads[j+1]]) - np.array([pA_heads[j],pB_heads[j]]) )) )\n    j = j+1\nplt.figure();\nplt.plot(np.arange(0,j+1),pA_heads, 'ro--')\nplt.plot(np.arange(0,j+1),pB_heads, 'bo-')\nplt.show()\n\nprint(f'pA is {pA_heads[-1]}')\nprint(f'pB is {pB_heads[-1]}')\n\n\n", "meta": {"hexsha": "aad50a2e413a930e60f4e37a1650200f49a57862", "size": 2760, "ext": "py", "lang": "Python", "max_stars_repo_path": "EM_Algorithm/EM_toss_coin.py", "max_stars_repo_name": "pine2104/Python_for_Lab", "max_stars_repo_head_hexsha": "571398c2422711d8a74f9c95a746537859458557", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2022-02-03T20:10:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:05:10.000Z", "max_issues_repo_path": "EM_Algorithm/EM_toss_coin.py", "max_issues_repo_name": "pine2104/Python_for_Lab", "max_issues_repo_head_hexsha": "571398c2422711d8a74f9c95a746537859458557", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EM_Algorithm/EM_toss_coin.py", "max_forks_repo_name": "pine2104/Python_for_Lab", "max_forks_repo_head_hexsha": "571398c2422711d8a74f9c95a746537859458557", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5882352941, "max_line_length": 111, "alphanum_fraction": 0.6463768116, "include": true, "reason": "import numpy", "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9787126469647338, "lm_q2_score": 0.8840392725805823, "lm_q1q2_score": 0.8652204164881195}}
{"text": "# Week 02 Assignment: Fitting and Plotting\n# Fit a linear curve to the data\n# Fit a cubic curve using the SciPy library\n# Find the area underneath the cubic curve over the domain of the data using the tools in SciPy\n# Plot the data, the linear fit, and the cubic fit in Matplotlib. Make sure to give the plot a title and an x and y label. Save this figure and include it in your pull request!\n# Put the area of the curve on the plot somewhere as text using Matplotlib\n# Use the Bayesian information criterion to justify which model (linear or cubic) is preferable. Include this justification in your journal entry for the week.\n\n# import packages\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import linregress\nfrom scipy.integrate import simps\nfrom matplotlib.patches import Polygon\n\n\n# input data\nx = np.array([ 1.,1.5,2.,2.5,3.,3.5,4.,4.5,5.,5.5,6.,6.5,7.,7.5,8.,8.5,9.,9.5,10.])\ny = np.array([3.43,4.94,6.45,9.22,6.32,6.11,4.63,8.95,7.8,8.35,11.45,14.71,11.97,12.46,17.42,17.0,15.45,19.15,20.86])\n\n\n# 1 Fit a linear curve to the data\nslope, intercept, r_value, p_value, std_err = linregress(x,y)\n\n\n# 2 Fit a cubic curve using the SciPy library\ncoefficients = np.polyfit(x,y,3)\np = np.poly1d(coefficients)\n\n\n# 3 Find the area underneath the cubic curve over the domain of the data using the tools in SciPy\nt = np.linspace(min(x),max(x),num=100)\narea = simps(p(t),t)\nprint(\"area =\",area)\n\n\n# 4 Plot the data, the linear fit, and the cubic fit in Matplotlib\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Curve Fitting');\n# plot data\nplt.scatter(x,y,c='k',label='Data')\n# plot linear fit\nplt.plot(x,x*slope+intercept,'--r',label='Linear Fit')\n# plot cubic fit\nplt.plot(t,p(t),'-b',label='Cubic Fit')\nplt.legend()\n# save figure\nplt.savefig('YWang_02.png')\n\n\n# 5 Put the area of the curve on the plot somewhere as text using Matplotlib\nfig, ax = plt.subplots()\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Curve Fitting');\n# plot data\nplt.scatter(x,y,c='k',label='Data')\n# plot linear fit\nplt.plot(x,x*slope+intercept,'--r',label='Linear Fit')\n# plot cubic fit\nplt.plot(t,p(t),'-b',label='Cubic Fit')\nplt.legend()\n# plot area under cubic curve\nverts = [(min(x), 0)] + list(zip(t, p(t))) + [(max(x), 0)]\npoly = Polygon(verts,facecolor='0.9',edgecolor='0.5',alpha=0.5)\nax.add_patch(poly)\n# insert text\nplt.text(0.5 * (min(x) + max(x)), 5, r\"Shaded Area\",\n         horizontalalignment='left', fontsize=20)\n# save figure\nplt.savefig('YWang_02.png')\n\n# 6 Use the Bayesian information criterion to justify which model (linear or cubic) is preferable\n\n# define function for Bayesian information criterion\ndef BIC(y, yhat, k, weight = 1):\n    err = y - yhat\n    sigma = np.std(np.real(err))\n    n = len(y)\n    B = n*np.log(sigma**2) + weight*k*np.log(n)\n    return B\n\n# calculate BIC for linear fit\nBIC_Linear = BIC(y,x*slope+intercept,1)\n# calculate BIC for cubic fit\nBIC_Cubic = BIC(y,p(x),3)\n", "meta": {"hexsha": "a72f80263157738136f557bf529c62fbf2483e23", "size": 2902, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week02/Assignment/YWang_02.py", "max_stars_repo_name": "nkruyer/SkillsWorkshop2018", "max_stars_repo_head_hexsha": "2201255ff63eca111635789267d0600a95854c38", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-18T03:30:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-18T03:30:46.000Z", "max_issues_repo_path": "Week02/Assignment/YWang_02.py", "max_issues_repo_name": "nkruyer/SkillsWorkshop2018", "max_issues_repo_head_hexsha": "2201255ff63eca111635789267d0600a95854c38", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2018-07-12T19:12:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-10T13:52:45.000Z", "max_forks_repo_path": "Week02/Assignment/YWang_02.py", "max_forks_repo_name": "nkruyer/SkillsWorkshop2018", "max_forks_repo_head_hexsha": "2201255ff63eca111635789267d0600a95854c38", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 60, "max_forks_repo_forks_event_min_datetime": "2018-05-08T16:59:20.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-01T14:28:28.000Z", "avg_line_length": 32.9772727273, "max_line_length": 176, "alphanum_fraction": 0.7029634735, "include": true, "reason": "import numpy,from scipy", "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140235181256, "lm_q2_score": 0.8947894625955064, "lm_q1q2_score": 0.8651844794798424}}
{"text": "'''\nLinear Algebra used for machine learning.\n'''\nimport math\nfrom typing import List, Tuple, Callable\nimport sympy\n\n#----------------\n# Vector Algebra |\n#----------------\n\n# Vectors store a single row of a matrix.\nVector = List[float]\n\n\n# Vectorial Addition.\ndef add(v: Vector, w: Vector) -> Vector:\n    '''\n    with:\n        v = (v_1, v_2, ..., v_x)\n        w = (w_1, w_2, ..., w_x)\n\n    v + w = (v_1 + w_1, v_2 + w_2, ..., v_x + w_x)\n    as:\n        add(v, w)\n    '''\n    assert len(v) == len(w), f\"Dimension of vectors do not match: dim(v)={len(v)} != dim(w)={len(w)}.\"\n    return [v_x + w_x for v_x, w_x in zip(v, w)]\n\n\n# Vectorial Subtraction.\ndef subtract(v: Vector, w: Vector) -> Vector:\n    '''\n    with:\n        v = (v_1, v_2, ..., v_x)\n        w = (w_1, w_2, ..., w_x)\n\n    v - w = (v_1 - w_1, v_2 - w_2, ..., v_x - w_x)\n    as:\n        subtract(v, w)\n    '''\n    assert len(v) == len(w), f\"Dimension of vectors do not match: |v|={len(v)} != |w|={len(w)}.\"\n    return [v_x - w_x for v_x, w_x in zip(v, w)]\n\n\n# Multiple vector addition.\ndef vector_sum(vectors: List[Vector]) -> Vector:\n    '''\n    for every vector v_x having same dimensions:\n        v_1 + v_2 + ... + v_x = \n        (v_1x + v_2x + ... v_xx, v_1y + v_2y + ... v_xy, v_1z + v_2z + ... v_xz)\n    '''\n    assert vectors, \"No vectors provided!\"\n    n_vector_dim = len(vectors[0])\n    assert all(len(v) == n_vector_dim for v in vectors), \"dimensions do not match!\"\n\n    return [sum(vector[x] for vector in vectors)\n            for x in range(n_vector_dim)]\n\n\n# Scalar Product.\ndef scalar_multiply(c: float, v: Vector) -> Vector:\n    return [c * v_n for v_n in v]\n\n\n# Component-Wise vectorial mean.\ndef vector_mean(vectors: List[Vector]) -> Vector:\n    assert vectors, \"No vectors provided!\"\n    n_vector_dim = len(vectors[0])\n    assert all(len(v) == n_vector_dim for v in vectors), \"dimensions do not match!\"\n    return scalar_multiply(1/len(vectors), vector_sum(vectors))\n\n\n# dot product.\ndef dot(v: Vector, w: Vector) -> float:\n    assert len(v) == len(w), \"vector sizes are different!\"\n    return sum(v_n * w_n for v_n, w_n in zip(v, w))\n\n\n# Summation of squares.\ndef sum_of_squares(v: Vector) -> float:\n    return dot(v, v)\n\n\n# Vectorial Magnitude.\ndef magnitude(v: Vector) -> float:\n    return math.sqrt(sum_of_squares(v))\n\n\n# Vectorial distance.\ndef distance(v: Vector, w: Vector) -> float:\n    return magnitude(subtract(v, w))\n\n# unit vector\ndef unit_vector(v: Vector) -> Vector:\n    return [v[v_i]/magnitude(v) for v_i in range(len(v))]\n\n# ----------------\n# Matrix Algebra |\n# ----------------\n\n# Note: Matrix = List[Vector]\nMatrix = List[List[float]]\n\n\n# Matrix shape\ndef shape(A: Matrix) -> Tuple[int, int]:\n    return len(A), len(A[0])\n\n\n# Matrix row extraction\ndef get_row(A: Matrix, i: int) -> Vector:\n    return A[i]\n\n\n# Matrix column extraction\ndef get_column(A: Matrix, j: int) -> Vector:\n    return [column[j] for column in A]\n\n\n# Matrix generation with specified dimensions\ndef make_matrix(num_rows: int,\n                num_cols: int,\n                entry_fn: Callable[[int, int], float]) -> Matrix:\n    return [[entry_fn(row, col) for col in range(num_cols)] for row in range(num_rows)]\n\n\n# Identity Matrix generator.\ndef identity_matrix(n: int) -> Matrix:\n    def identity_matrix_base_func(row, col):\n        if row == col:\n            return 1\n        else:\n            return 0\n    return make_matrix(n, n, identity_matrix_base_func)\n\n\n# Matrix scalar product\ndef matrix_scalar_multiply(c: float, A: Matrix) -> Matrix:\n    return [scalar_multiply(c, row) for row in A]\n\n\ndef transpose(A: Matrix) -> Matrix:\n    return [[row[col] for row in A] for col in range(len(A[0]))]\n\n\n# Matrix cross-product\ndef matrix_dot(A: Matrix, B: Matrix) -> Matrix:\n    assert shape(A)[1] == shape(B)[0], \"Inner dimensions of matrices do not match!\"\n\n    return [[dot(row, column) for column in transpose(B)] for row in A]", "meta": {"hexsha": "e8ffa8521f1f44bae871cbf68d4a187cb5eb9249", "size": 3899, "ext": "py", "lang": "Python", "max_stars_repo_path": "ml-by-scratch/linear_algebra.py", "max_stars_repo_name": "aguilarjose11/ML-Playground", "max_stars_repo_head_hexsha": "c0452dd36a394b061a321f7f4429e1af1ff190f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-20T02:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-20T02:57:32.000Z", "max_issues_repo_path": "ml-by-scratch/linear_algebra.py", "max_issues_repo_name": "aguilarjose11/ML-Playground", "max_issues_repo_head_hexsha": "c0452dd36a394b061a321f7f4429e1af1ff190f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:27:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T03:12:32.000Z", "max_forks_repo_path": "ml-by-scratch/linear_algebra.py", "max_forks_repo_name": "aguilarjose11/ML-Playground", "max_forks_repo_head_hexsha": "c0452dd36a394b061a321f7f4429e1af1ff190f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.821192053, "max_line_length": 102, "alphanum_fraction": 0.6078481662, "include": true, "reason": "import sympy", "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140216112959, "lm_q2_score": 0.8947894611926921, "lm_q1q2_score": 0.8651844764172305}}
{"text": "import numpy as np\r\nimport numpy.linalg as LA\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import rc\r\nplt.ion()\r\n\r\nif __name__ == \"__main__\":\r\n\ta = 1\r\n\tb = 2\r\n\tc = 0\r\n\td = 2\r\n\tA = np.array([[a,b],[c,d]])\r\n\tu,s,v = LA.svd(A)\r\n\t\r\n\tv_i = v.T\r\n\t\r\n\t\r\n\t# Plot\r\n\torigin = [0], [0]\r\n\t\r\n\t# V\r\n\tplt.subplot(121)\r\n\tplt.quiver(*origin,v_i[0,:], v_i[1,:], angles='xy', scale_units='xy', color=['r','b'],scale=1)\r\n\t# unit circle\r\n\ttheta = np.arange(0.0,360.0,1.0)*np.pi/180.\r\n\tx = np.cos(theta)\r\n\ty = np.sin(theta)\r\n\tplt.plot(x,y)\r\n\tplt.axis('equal')\r\n\tplt.axis([-s[0]-0.1, s[0]+0.1, -s[0]-0.1, s[0]+0.1])\r\n\r\n\tplt.title('v')\r\n\t# U\r\n\tplt.subplot(122)\r\n\tplt.quiver(*origin,[i*x for i,x in zip(s,u[0,:])], [i*y for i,y in zip(s,u[1,:])], angles='xy', scale_units='xy', color=['r','b'],scale=1)\r\n\ttheta = np.arange(0.0,360.0,1.0)*np.pi/180.\r\n\tphi = np.arccos(np.dot(u[:,0],[1,0]))\r\n\tx = s[0]*np.cos(theta)\r\n\ty = s[1]*np.sin(theta)\r\n\tR = np.array([[np.cos(phi), -np.sin(phi)],\r\n\t\t\t\t  [np.sin(phi),  np.cos(phi)],])\r\n\tx,y = np.dot(R,np.array([x,y]))\r\n\tplt.plot(x,y)\r\n\tplt.title('Av=u')\r\n\tplt.axis('equal')\r\n\tplt.axis([-s[0]-0.1, s[0]+0.1, -s[0]-0.1, s[0]+0.1])\r\n\t\r\n\t\"\"\"\r\n\tplt.figure(1)\r\n\t\r\n\tax1.arrow(0,0,v_i[0,0],v_i[1,0], head_width=0.05, head_length=0.1, fc='k', ec='k')\r\n\tax1.arrow(0,0,v_i[0,1],v_i[1,1], head_width=0.05, head_length=0.1, fc='k', ec='k')\r\n\tax1.set_title('V')\r\n\tax1.arrow(0,0,s[0]*u[0,0],s[0]*u[1,0], head_width=0.05, head_length=0.1, fc='k', ec='k')\r\n\tax1.arrow(0,0,s[1]*u[0,1],s[1]*u[1,1], head_width=0.05, head_length=0.1, fc='k', ec='k')\r\n\tax2.set_title('U')\r\n\t\"\"\"\r\n\t\r\n\t", "meta": {"hexsha": "f9e7bfa6a117e83960b7ea1097eda02dfc8906b1", "size": 1579, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/svd_plots.py", "max_stars_repo_name": "dantaylor688/dantaylor688.github.io", "max_stars_repo_head_hexsha": "f430224693c94a7469826f88b88bd9b1460e1cc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/svd_plots.py", "max_issues_repo_name": "dantaylor688/dantaylor688.github.io", "max_issues_repo_head_hexsha": "f430224693c94a7469826f88b88bd9b1460e1cc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/svd_plots.py", "max_forks_repo_name": "dantaylor688/dantaylor688.github.io", "max_forks_repo_head_hexsha": "f430224693c94a7469826f88b88bd9b1460e1cc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7627118644, "max_line_length": 140, "alphanum_fraction": 0.5459151362, "include": true, "reason": "import numpy", "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799399736477, "lm_q2_score": 0.8976953003183444, "lm_q1q2_score": 0.8651807226554397}}
{"text": "from AutoDiff.ForwardAD import Var, MultiFunc\nimport numpy as np\nimport math\n\ndef Newton(func, guess, tol = 10**(-8), max_iter = 2000):\n    '''\n        Returns the values of the roots of function func\n        The optimization problem is solved with the method solver and accuracy specified by tolerance\n\n        INPUTS\n        =======\n        func : callable (function)\n               - takes in a list of variables\n               - returns a single variable\n\n        guess : list of real numbers, corresponding to the initial guess for roots of the function func\n        tol : the tolerance threshold of errors, floating point number, by default equal to 10e-8\n        max_iter : integer corresponding to the maximum number of iterations  for the algorithm\n                   by default equal to 2000\n\n        RETURNS\n        =======\n        xnext: the root of func when the tolerance tol is reached, \n        or the maximum iteration number, max_iter, is reached.\n\n        EXAMPLES\n        =======\n        # >>> f = lambda x: x**2-1\n        # >>> guess = 2\n        # >>> root = Newton(f, guess)\n          1.0\n    '''\n    xcur = Var(guess)\n    fxcur = func(xcur)\n    xnext = xcur - Var(fxcur.get_value()/fxcur.get_der()[0])\n    err = abs(xnext.get_value()-xcur.get_value())\n    i = 0\n    while err > tol:\n        xcur = xnext\n        fxcur = func(xcur)\n        xnext = xcur - Var(fxcur.get_value()/fxcur.get_der()[0])\n        err = abs(xnext.get_value()-xcur.get_value())\n        i += 1\n        if i > max_iter:\n            print('The execution goes beyond the maximum number of iterations, \\\n                  so it is stopped and the most current result is printed')\n            break\n    return xnext.get_value()\n\n\n    ", "meta": {"hexsha": "a863602d5b2359afda4a780cbf9de8abbe59f9f2", "size": 1723, "ext": "py", "lang": "Python", "max_stars_repo_path": "AutoDiff/root_finding.py", "max_stars_repo_name": "BackPropagators/cs207-FinalProject", "max_stars_repo_head_hexsha": "6ec7d35f1af3b091d8c93c59bc0e8fe286a5fafc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AutoDiff/root_finding.py", "max_issues_repo_name": "BackPropagators/cs207-FinalProject", "max_issues_repo_head_hexsha": "6ec7d35f1af3b091d8c93c59bc0e8fe286a5fafc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AutoDiff/root_finding.py", "max_forks_repo_name": "BackPropagators/cs207-FinalProject", "max_forks_repo_head_hexsha": "6ec7d35f1af3b091d8c93c59bc0e8fe286a5fafc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7843137255, "max_line_length": 103, "alphanum_fraction": 0.5885084156, "include": true, "reason": "import numpy", "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799399736476, "lm_q2_score": 0.8976952832120991, "lm_q1q2_score": 0.8651807061687835}}
{"text": "\"\"\"\nThis script demonstrates the implementation of the GeLU function.\n\nGELUs full form is GAUSSIAN ERROR LINEAR UNIT\n\nGELU is a smooth approximation to the rectifier. It has a non-monotonic “bump” when x < 0.\nThe function takes a vector of K real numbers as input.\nWe define Gaussian Error Linear Unit (GELU) as- \nGelu(x) = xP(X <= x) = xΦ(x) \nWe can approximate the GELU with\n0.5x(1 + tanh[root(2/π)(x + 0.044715x^3)])\n\n\nScript inspired from its corresponding Wikipedia article\nhttps://en.wikipedia.org/wiki/Rectifier_(neural_networks)\n\"\"\"\n\n\nimport numpy as np\n\ndef gelu(vector: np.array) -> np.array:\n    \"\"\"\n    Implements the relu function\n\n    Parameters:\n        vector (np.array,list,tuple): A  numpy array of shape (1,n)\n        consisting of real values or a similar list,tuple\n\n\n    Returns:\n        gelu_vec : The input numpy array, after applying\n        gelu.\n\n    >>> vec = np.array([-1, 0, 5])\n    >>> relu(vec)\n    array([0, 0, 5])\n    \"\"\"\n\n    return  np.dot(np.dot(0.5,vector),(1 + np.tanh((np.sqrt(2/np.math.pi))*(vector + 0.044715*np.power(vector, 3)))))\n\nif __name__ == \"__main__\":\n    print(np.array(gelu([-1, 0, 5])))  # --> 4.841191761428657\n", "meta": {"hexsha": "c7c8ef70b62fa1bac5a505650524a38581139af5", "size": 1166, "ext": "py", "lang": "Python", "max_stars_repo_path": "maths/gelu.py", "max_stars_repo_name": "KuldeepBorkar/Python", "max_stars_repo_head_hexsha": "5fa1fec9e8b083cd745263cd5ac8f4dc7d7d075c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "maths/gelu.py", "max_issues_repo_name": "KuldeepBorkar/Python", "max_issues_repo_head_hexsha": "5fa1fec9e8b083cd745263cd5ac8f4dc7d7d075c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maths/gelu.py", "max_forks_repo_name": "KuldeepBorkar/Python", "max_forks_repo_head_hexsha": "5fa1fec9e8b083cd745263cd5ac8f4dc7d7d075c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1162790698, "max_line_length": 117, "alphanum_fraction": 0.6586620926, "include": true, "reason": "import numpy", "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502202, "lm_q2_score": 0.9124361509525462, "lm_q1q2_score": 0.8651304729182824}}
{"text": "\"\"\"\nSource: https://github.com/shakedzy/dython\n\"\"\"\n\nimport math\nimport scipy.stats as ss\nfrom collections import Counter\n\n\ndef conditional_entropy(x, y):\n    \"\"\"\n    Calculates the conditional entropy of x given y: S(x|y)\n    Wikipedia: https://en.wikipedia.org/wiki/Conditional_entropy\n    :param x: list / NumPy ndarray / Pandas Series\n        A sequence of measurements\n    :param y: list / NumPy ndarray / Pandas Series\n        A sequence of measurements\n    :return: float\n    \"\"\"\n    # entropy of x given y\n    y_counter = Counter(y)\n    xy_counter = Counter(list(zip(x,y)))\n    total_occurrences = sum(y_counter.values())\n    entropy = 0.0\n    for xy in xy_counter.keys():\n        p_xy = xy_counter[xy] / total_occurrences\n        p_y = y_counter[xy[1]] / total_occurrences\n        entropy += p_xy * math.log(p_y/p_xy)\n    return entropy\n\n\ndef theils_u(x, y):\n    \"\"\"\n    Calculates Theil's U statistic (Uncertainty coefficient) for categorical-categorical association.\n    This is the uncertainty of x given y: value is on the range of [0,1] - where 0 means y provides no information about\n    x, and 1 means y provides full information about x.\n    This is an asymmetric coefficient: U(x,y) != U(y,x)\n    Wikipedia: https://en.wikipedia.org/wiki/Uncertainty_coefficient\n    :param x: list / NumPy ndarray / Pandas Series\n        A sequence of categorical measurements\n    :param y: list / NumPy ndarray / Pandas Series\n        A sequence of categorical measurements\n    :return: float\n        in the range of [0,1]\n    \"\"\"\n    s_xy = conditional_entropy(x,y)\n    x_counter = Counter(x)\n    total_occurrences = sum(x_counter.values())\n    p_x = list(map(lambda n: n/total_occurrences, x_counter.values()))\n    s_x = ss.entropy(p_x)\n    if s_x == 0:\n        return 1\n    else:\n        return (s_x - s_xy) / s_x\n", "meta": {"hexsha": "70a72c442b5e1263aa6149cf845ba59ebef4b896", "size": 1818, "ext": "py", "lang": "Python", "max_stars_repo_path": "pattern_detection/lib/nominal.py", "max_stars_repo_name": "bogdanghita/whitebox-compression", "max_stars_repo_head_hexsha": "a300378e8469954addf7e9dd23ebed2bef218d68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-27T07:13:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T05:31:03.000Z", "max_issues_repo_path": "pattern_detection/lib/nominal.py", "max_issues_repo_name": "bogdanghita/whitebox-compression", "max_issues_repo_head_hexsha": "a300378e8469954addf7e9dd23ebed2bef218d68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pattern_detection/lib/nominal.py", "max_forks_repo_name": "bogdanghita/whitebox-compression", "max_forks_repo_head_hexsha": "a300378e8469954addf7e9dd23ebed2bef218d68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-21T19:17:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T07:04:23.000Z", "avg_line_length": 33.0545454545, "max_line_length": 120, "alphanum_fraction": 0.6672167217, "include": true, "reason": "import scipy", "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.9019206837793828, "lm_q1q2_score": 0.8650810909156051}}
{"text": "#Basic models or functions in form of f(x,...)\n\nimport numpy as np\nfrom scipy.stats import norm\nfrom scipy.stats import cauchy as sci_cauchy\nfrom scipy.stats import pearson3 as sci_pearson3\nfrom scipy.special import erf as sci_erf\nfrom scipy.special import expit, logit\n\nfrom ._helpers import funcArgsNr\n\n#polynomial functions: constant, linear, quadratic, cubic\ndef constant(x, a):\n\ty = np.full(x.size, a)\n\treturn y\n\ndef linear(x, a, b):\n\ty = a * x + b\n\treturn y\n\ndef quadratic(x, a, b, c):\n\ty = a * x**2 + b * x + c\n\treturn y\n\ndef cubic(x, a, b, c, d):\n\ty = a * x**3 + b * x**2 + c * x + d\n\treturn y\n\t\n#Gaussian functions\ndef gaussian(x, a, b, c):\n\t'''General Gaussian function\n\tParameters:\n\t\tx: independent variable\n\t\ta, b, c: parameters for function\n\treturns:\n\t\ty: dependent variable\n\t'''\n\ty = a*np.exp(-np.power(x-b,2)/(2*np.power(c,2)))\n\t#y = a * c * np.sqrt(2*np.pi) * norm.pdf(x, b, c) #equivalent to above\n\treturn y\n\ndef erf(x, a, b, c):\n\t'''General Gaussian error function (erf), the general cumulative distribution function (CDF) of Gaussian or normal distribution.\n\tParameters:\n\t\tx: independent variable\n\t\ta, b, c: parameters for function\n\treturns:\n\t\ty: dependent variable\n\t'''\n\ty = a * sci_erf((x-b)/c)\n\treturn y\n\n#Cauchy-Lorentz function\ndef cauchy(x, a, b, c):\n\t'''General Cauchy function, the probability density function (PDF) of Cauchy or Lorentz distribution.\n\tParameters:\n\t\tx: independent variable\n\t\ta, b, c: parameters for function\n\treturns:\n\t\ty: dependent variable\n\t'''\n\ty = a * sci_cauchy.pdf(x, loc=b, scale=c)\n\treturn y\n\n#Pearson\ndef pearson3(x, a, b, c, d):\n\t'''General Pearson Type 3 function, the probability density function (PDF) of Pearson type III distribution.\n\thttps://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearson3.html\n\tParameters:\n\t\tx: independent variable\n\t\ta, b, c, d: parameters for function\n\treturns:\n\t\ty: dependent variable\n\t'''\n\ty = a * sci_pearson3.pdf(x, skew=b, loc=c, scale=d)\n\treturn y\n\n#exponential\ndef exponential(x, a, b):\n\t'''General exponential function\n\tParameters:\n\t\tx: independent variable\n\t\ta, b: parameters for function\n\treturns:\n\t\ty: dependent variable\n\t'''\n\t#y = a*np.exp(b*x)\t#natural exponential function\n\ty = a * b ** x\t#equivalent ?\n\treturn y\n\ndef logarithm(x, a, b):\n\t'''General logarithm function, inverse function to exponentiation -- y = a * log_b (x)\n\t'''\n\tif b ==1: b = b + 0.001\n\ty = a * np.log(x) / np.log(b)\n\treturn y\n\ndef logistic(x, a, b, c):\n\t'''General logistic function, the common S-shaped curve.\n\thttps://en.wikipedia.org/wiki/Logistic_function\n\t'''\n\ty = a * expit(b*x + c)\n\treturn y\n\ndef reciprocal(x, a, b):\n\t'''Deprecated. It's a special of general power-law function. General reciprocal function\n\t\n\tNote that `np.reciprocal` doesn't work with integers.\n\t'''\n\ty = 1 /(a * x + b)\n\t# y = np.reciprocal(a * x + b)\n\treturn y\n\n#power-law\ndef power_law(x, a, b):\n\t'''General power-law function\n\t\n\tNote that `np.power` doesn't work with a negative integer power.\n\tParameters:\n\t\tx: independent variable\n\t\ta, b, c: parameters for function\n\treturns:\n\t\ty: dependent variable\n\t'''\n\ty = a * np.power(x, float(b))\n\t#y = np.power(a * x + b, float(c))\n\t#y = a*np.power(x + b,float(c))\n\treturn y\n\n__custom = '''\ndef %s(x, %s):\n\treturn %s\n'''\n\t\t\t\n#metadata of custom basic models/functions\nbasicModels = [\n\t{'model':constant,'name':'constant','n_para':funcArgsNr(constant)-1},\n\t{'model':linear,'name':'linear','n_para':funcArgsNr(linear)-1},\n\t{'model':quadratic,'name':'quadratic','n_para':funcArgsNr(quadratic)-1},\n\t{'model':cubic,'name':'cubic','n_para':funcArgsNr(cubic)-1},\n\t{'model':gaussian,'name':'gaussian','n_para':funcArgsNr(gaussian)-1},\n\t{'model':erf,'name':'erf','n_para':funcArgsNr(erf)-1},\n\t{'model':cauchy,'name':'cauchy','n_para':funcArgsNr(cauchy)-1},\n\t{'model':pearson3,'name':'pearson3','n_para':funcArgsNr(pearson3)-1},\n\t{'model':exponential,'name':'exponential','n_para':funcArgsNr(exponential)-1},\n\t{'model':logarithm,'name':'logarithm','n_para':funcArgsNr(logarithm)-1},\n\t{'model':logistic,'name':'logistic','n_para':funcArgsNr(logistic)-1},\n\t{'model':power_law,'name':'power_law','n_para':funcArgsNr(power_law)-1},\n\t{'model':reciprocal,'name':'reciprocal','n_para':funcArgsNr(reciprocal)-1},\n\t]\n#list of models' name\nbasicModels_nameList = [model['name'] for model in basicModels]\nbasicModels_nonp_nameList = [model['name'] for model in basicModels[4:]]\t#non-polynomial\n#models=['constant', 'linear', 'quadratic', 'cubic', 'gaussian', 'erf', 'cauchy', 'exponential', 'logarithm', 'logistic', 'reciprocal', 'power_law', 'pearson3']\n#models=['constant', 'linear', 'quadratic', 'cubic', 'gaussian', 'erf', 'cauchy', 'exponential', 'logarithm', 'logistic', 'power_law', 'pearson3']\n", "meta": {"hexsha": "f42e78c7410747e550eb44f42a1ee303ded70ef0", "size": 4687, "ext": "py", "lang": "Python", "max_stars_repo_path": "longscurvefitting/models.py", "max_stars_repo_name": "svb688/adaptive-curvefitting", "max_stars_repo_head_hexsha": "82ece9af0373434489ad57c9d20e62f804bea07e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-16T22:55:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T17:31:12.000Z", "max_issues_repo_path": "longscurvefitting/models.py", "max_issues_repo_name": "svb688/adaptive-curvefitting", "max_issues_repo_head_hexsha": "82ece9af0373434489ad57c9d20e62f804bea07e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "longscurvefitting/models.py", "max_forks_repo_name": "svb688/adaptive-curvefitting", "max_forks_repo_head_hexsha": "82ece9af0373434489ad57c9d20e62f804bea07e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-23T12:02:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T12:02:02.000Z", "avg_line_length": 30.0448717949, "max_line_length": 160, "alphanum_fraction": 0.6820994239, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542794197472, "lm_q2_score": 0.9019206850975361, "lm_q1q2_score": 0.8650810848084919}}
{"text": "'''\nCan't Forecast White Noise\n\nA white noise time series is simply a sequence of uncorrelated random variables that are identically distributed. Stock returns are often modelled as white noise. Unfortunately, for white noise, we cannot forecast future observations based on the past - autocorrelations at all lags are zero.\n\nYou will generate a white noise series and plot the autocorrelation function to show that it is zero for all lags. You can use np.random.normal() to generate random returns. For a Gaussian white noise process, the mean and standard deviation describe the entire process.\n\nPlot this white noise series to see what it looks like, and then plot the autocorrelation function.\n\nINSTRUCTIONS\n100XP\nGenerate 1000 random normal returns using np.random.normal() with mean 2% (0.02) and standard deviation 5% (0.05), where the argument for the mean is loc and the argument for the standard deviation is scale.\nPlot the time series.\nVerify the mean and standard deviation of returns using np.mean() and np.std().\nPlot the autocorrelation function using plot_acf with lags=20.\n'''\n# Import the plot_acf module from statsmodels\nfrom statsmodels.graphics.tsaplots import plot_acf\n\n# Simulate wite noise returns\nreturns = np.random.normal(loc=0.02, scale=0.05, size=1000)\n\n# Print out the mean and standard deviation of returns\nmean = np.mean(returns)\nstd = np.std(returns)\nprint(\"The mean is %5.3f and the standard deviation is %5.3f\" %(mean,std))\n\n# Plot returns series\nplt.plot(returns)\nplt.show()\n\n# Plot autocorrelation function of white noise returns\nplot_acf(returns, lags=20)\nplt.show()\n", "meta": {"hexsha": "585e53b6b572cad00a0c8cc3840636d7ddc438fc", "size": 1606, "ext": "py", "lang": "Python", "max_stars_repo_path": "datacamp-master/22-introduction-to-time-series-analysis-in-python/02-some-simple-time-series/03-cant-forecast-white-noise.py", "max_stars_repo_name": "vitthal10/datacamp", "max_stars_repo_head_hexsha": "522d2b192656f7f6563bf6fc33471b048f1cf029", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-11T01:32:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T01:32:36.000Z", "max_issues_repo_path": "22-introduction-to-time-series-analysis-in-python/02-some-simple-time-series/03-cant-forecast-white-noise.py", "max_issues_repo_name": "AndreasFerox/DataCamp", "max_issues_repo_head_hexsha": "41525d7252f574111f4929158da1498ee1e73a84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "22-introduction-to-time-series-analysis-in-python/02-some-simple-time-series/03-cant-forecast-white-noise.py", "max_forks_repo_name": "AndreasFerox/DataCamp", "max_forks_repo_head_hexsha": "41525d7252f574111f4929158da1498ee1e73a84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-08T05:09:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-08T05:09:52.000Z", "avg_line_length": 45.8857142857, "max_line_length": 292, "alphanum_fraction": 0.7864259029, "include": true, "reason": "from statsmodels", "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542805873231, "lm_q2_score": 0.9019206798249231, "lm_q1q2_score": 0.8650810808043035}}
{"text": "from sympy import *\nfrom sympy import simplify\nfrom scipy.interpolate import lagrange\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n#2a\ndef lang(x_i,y_i):\n    x= symbols('x')\n    if len(x_i)==len(y_i):\n       yp=0\n       for i in range(len(x_i)):\n           p=1\n           for j in range(len(x_i)):\n               if j!=i:\n                  p*=(x-x_i[j])/(x_i[i]-x_i[j])\n           yp+=y_i[i]*p\n       p_x=simplify(yp)\n       fx=lambdify(x,p_x,modules=['numpy'])\n       return fx\n    else:\n        return(\"len(x_i) should be equal to len(y_i)\")\n\n#2b\ndef in_lang(x_i,y_i):\n    return lang(y_i,x_i)\n\n\n#2c\ndef inbuilt(x_i,y_i,x1):\n    poly = lagrange(x_i, y_i) \n    L=poly(x1)\n    return L\n    \n#Graph\n\ndef graph1(x_i,y_i,arr_x,arr_y_f,arr_y_in,pt_x,pt_y,xlab,ylab,titl):\n    plt.scatter(x_i,y_i,marker='*',c=\"red\",label=\"Given discrete points\")\n    plt.scatter(pt_x,pt_y,marker='o',c='black',label=\"Interpolated point\")\n    plt.plot(arr_x,arr_y_in,c='blue',label=\"Scipy's Inbuilt function\",linestyle=\"-.\")\n    plt.plot(arr_x,arr_y_f,c=\"green\",label=\"Interpolated langrange function\")\n    plt.xlabel(xlab)\n    plt.ylabel(ylab)\n    plt.title(titl)\n    plt.grid(True)\n    plt.legend()\n    plt.show()\n    \n#3a \na=[0.00,0.2,0.4,0.6,0.8,1,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0]\nb=[1,0.99,0.96,0.91,0.85,0.76,0.67,0.57,0.46,0.34,0.22,0.11,0.00,-0.1,-0.18,-0.26]\ng=lang(a,b)\nk=in_lang(a,b)\n\narr_beta=np.linspace(0,3,1000)\narr_Jbeta_f=[]\narr_Jbeta_i=[]\nfor i in arr_beta:\n    arr_Jbeta_f.append(g(i))\n    arr_Jbeta_i.append(inbuilt(a,b,i))\n\narr_Jbeta=np.linspace(1,-0.26,1000)\narr_beta_f=[]\narr_beta_i=[]\nfor i in arr_Jbeta:\n    arr_beta_f.append(k(i))\n    arr_beta_i.append(inbuilt(b,a,i))\n    \nprint(\"The value of bessel function for \\u03B2 = 0.5 is \",g(2.3))\nprint(\"The value of \\u03B2 for which the value of bessel function is 2.3 = \",k(0.5))   \ngraph1(a,b,arr_beta,arr_Jbeta_f,arr_Jbeta_i,2.3,g(2.3),\"\\u03B2\",\"J0_\\u03B2\",\"3a. (i) Bessel Function\") \ngraph1(b,a,arr_Jbeta,arr_beta_f,arr_beta_i,0.5,k(0.5),\"J0_\\u03B2\",\"\\u03B2\",\"3a. (ii) Inverse Bessel Function\")\n    \n#3b\nI=[2.81,3.24,3.80,4.30,4.37,5.29,6.03]\nV=[0.5,1.2,2.1,2.9,3.6,4.5,5.7]\ns=in_lang(I,V)\nz=lang(I,V)\n\narr_I=np.linspace(2.81,6.03,1000)\narr_V_f=[]\narr_V_i=[]\nfor i in arr_I:\n    arr_V_f.append(z(i))\n    arr_V_i.append(inbuilt(I,V,i))\n\narr_V=np.linspace(0.5,5.7,1000)\narr_I_f=[]\narr_I_i=[]\nfor i in arr_V:\n    arr_I_f.append(s(i))\n    arr_I_i.append(inbuilt(V,I,i))\n\ngraph1(I,V,arr_I,arr_V_f,arr_V_i,3.79,z(3.79),\"I\",\"V\",\"3b. (i) Photoelectric Effect\") \ngraph1(V,I,arr_V,arr_I_f,arr_I_i,2.4,s(2.4),\"V\",\"I\",\"3b. (ii) Inverse Photoelectric effect\")\nprint(\"The value of I for V= 2.4 is \",s(2.4))\n\n#Comparison\nj=[\"3a (i)\",\"3a (ii)\",\"3b\"]\nd=[g(2.3),k(0.5),s(2.4)]\nc=[inbuilt(a,b,2.3),inbuilt(b,a,0.5),inbuilt(V,I,2.4)]\nerror=np.array(d)-np.array(c)\nprint(\"# Comparison Table\")\nData={\"Ques\":j,\"Scipy\":d,\"My function\":c,\"Error\":error}\nprint(pd.DataFrame(Data))\n", "meta": {"hexsha": "5adbe61edf840509b31278884fea9cb7afbe7558", "size": 2940, "ext": "py", "lang": "Python", "max_stars_repo_path": "MP2_A3.py", "max_stars_repo_name": "pawan3091/pawan", "max_stars_repo_head_hexsha": "81f97bc50e844981831e5320e983d3dc6da629e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MP2_A3.py", "max_issues_repo_name": "pawan3091/pawan", "max_issues_repo_head_hexsha": "81f97bc50e844981831e5320e983d3dc6da629e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MP2_A3.py", "max_forks_repo_name": "pawan3091/pawan", "max_forks_repo_head_hexsha": "81f97bc50e844981831e5320e983d3dc6da629e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7358490566, "max_line_length": 110, "alphanum_fraction": 0.630952381, "include": true, "reason": "import numpy,from scipy,from sympy", "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542805873231, "lm_q2_score": 0.9019206699387733, "lm_q1q2_score": 0.8650810713219605}}
{"text": "from __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimage = np.array(Image.open('data/tiger.jpg'))\n\nimage = image / 255\nrow, col, _ = image.shape\nprint(\"pixels: \", row, \"*\", col)\n\nfig = plt.figure(figsize=(15, 10))\na = fig.add_subplot(1, 1, 1)\nimgplot = plt.imshow(image)\na.set_title('Royal Bengal Tiger, Sundarban, Bangladesh')\nplt.show()\n\nimage_red = image[:, :, 0]\nimage_green = image[:, :, 1]\nimage_blue = image[:, :, 2]\n\noriginal_bytes = image.nbytes\nprint(\"The space needed to store this image is: \", original_bytes/1024, \" KB\")\n\nU_r, d_r, V_r = np.linalg.svd(image_red, full_matrices=True)\nU_g, d_g, V_g = np.linalg.svd(image_green, full_matrices=True)\nU_b, d_b, V_b = np.linalg.svd(image_blue, full_matrices=True)\n\nbytes_to_be_stored = sum([matrix.nbytes for matrix in [U_r, d_r, V_r, U_g, d_g, V_g, U_b, d_b, V_b]])\nprint(\"The matrices that we store have total size: \", bytes_to_be_stored/1024, \" KB\")\n\nk = 50\n\nU_r_k = U_r[:, 0:k]\nV_r_k = V_r[0:k, :]\nU_g_k = U_g[:, 0:k]\nV_g_k = V_g[0:k, :]\nU_b_k = U_b[:, 0:k]\nV_b_k = V_b[0:k, :]\n\nd_r_k = d_r[0:k]\nd_g_k = d_g[0:k]\nd_b_k = d_b[0:k]\n\ncompressed_bytes = sum([matrix.nbytes for matrix in \n                        [U_r_k, d_r_k, V_r_k, U_g_k, d_g_k, V_g_k, U_b_k, d_b_k, V_b_k]])\nprint(\"Compressed matrices have total size: \", compressed_bytes/1024, \"KB\")\n\nratio = compressed_bytes / original_bytes\nprint(\"Compression ratio between the original image size and the total size of the compressed factors is: \", ratio)\n\nimage_red_approx = np.dot(U_r_k, np.dot(np.diag(d_r_k), V_r_k))\nimage_green_approx = np.dot(U_g_k, np.dot(np.diag(d_g_k), V_g_k))\nimage_blue_approx = np.dot(U_b_k, np.dot(np.diag(d_b_k), V_b_k))\n\nimage_reconstructed = np.zeros((row, col, 3))\n\nimage_reconstructed[:, :, 0] = image_red_approx\nimage_reconstructed[:, :, 1] = image_green_approx\nimage_reconstructed[:, :, 2] = image_blue_approx\n\nimage_reconstructed[image_reconstructed < 0] = 0\nimage_reconstructed[image_reconstructed > 1] = 1\n\nfig = plt.figure(figsize=(15, 10))\na = fig.add_subplot(1, 1, 1)\nimgplot = plt.imshow(image_reconstructed)\na.set_title('Compressed image of the Royal Bengal Tiger, using best rank-{} approximation'.format(k))\nplt.show()\n\nk = 10\n\nU_r_k = U_r[:, 0:k]\nV_r_k = V_r[0:k, :]\nU_g_k = U_g[:, 0:k]\nV_g_k = V_g[0:k, :]\nU_b_k = U_b[:, 0:k]\nV_b_k = V_b[0:k, :]\n\nd_r_k = d_r[0:k]\nd_g_k = d_g[0:k]\nd_b_k = d_b[0:k]\n\ncompressed_bytes = sum([matrix.nbytes for matrix in \n                        [U_r_k, d_r_k, V_r_k, U_g_k, d_g_k, V_g_k, U_b_k, d_b_k, V_b_k]])\nprint(\"Compressed matrices have total size: \", compressed_bytes/1024, \"KB\")\n\nimage_red_approx = np.dot(U_r_k, np.dot(np.diag(d_r_k), V_r_k))\nimage_green_approx = np.dot(U_g_k, np.dot(np.diag(d_g_k), V_g_k))\nimage_blue_approx = np.dot(U_b_k, np.dot(np.diag(d_b_k), V_b_k))\n\nimage_reconstructed = np.zeros((row, col, 3))\nimage_reconstructed[:, :, 0] = image_red_approx\nimage_reconstructed[:, :, 1] = image_green_approx\nimage_reconstructed[:, :, 2] = image_blue_approx\nimage_reconstructed[image_reconstructed < 0] = 0\nimage_reconstructed[image_reconstructed > 1] = 1\n\nfig = plt.figure(figsize=(15, 10))\na = fig.add_subplot(1, 1, 1)\nimgplot = plt.imshow(image_reconstructed)\na.set_title('Compressed image of the Royal Bengal Tiger, using best rank-{} approximation'.format(k))\nplt.show()\n\nk = 200\n\nU_r_k = U_r[:, 0:k]\nV_r_k = V_r[0:k, :]\nU_g_k = U_g[:, 0:k]\nV_g_k = V_g[0:k, :]\nU_b_k = U_b[:, 0:k]\nV_b_k = V_b[0:k, :]\n\nd_r_k = d_r[0:k]\nd_g_k = d_g[0:k]\nd_b_k = d_b[0:k]\n\nimage_red_approx = np.dot(U_r_k, np.dot(np.diag(d_r_k), V_r_k))\nimage_green_approx = np.dot(U_g_k, np.dot(np.diag(d_g_k), V_g_k))\nimage_blue_approx = np.dot(U_b_k, np.dot(np.diag(d_b_k), V_b_k))\n\nimage_reconstructed = np.zeros((row, col, 3))\nimage_reconstructed[:, :, 0] = image_red_approx\nimage_reconstructed[:, :, 1] = image_green_approx\nimage_reconstructed[:, :, 2] = image_blue_approx\nimage_reconstructed[image_reconstructed < 0] = 0\nimage_reconstructed[image_reconstructed > 1] = 1\n\nfig = plt.figure(figsize=(15, 10))\na = fig.add_subplot(1, 1, 1)\nimgplot = plt.imshow(image_reconstructed)\na.set_title('Compressed image of the Royal Bengal Tiger, using best rank-{} approximation'.format(k))\nplt.show()\n", "meta": {"hexsha": "3d6bf9e56970e8c15c4648c697fef56fa6a9f210", "size": 4233, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter01/SVD_Demo.py", "max_stars_repo_name": "retwal/Predictive", "max_stars_repo_head_hexsha": "57c3cb64901b7a0629b70053ecf01dac5be66d6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2017-10-27T22:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T18:37:51.000Z", "max_issues_repo_path": "Chapter01/SVD_Demo.py", "max_issues_repo_name": "retwal/Predictive", "max_issues_repo_head_hexsha": "57c3cb64901b7a0629b70053ecf01dac5be66d6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-09-20T21:47:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-14T05:32:41.000Z", "max_forks_repo_path": "Chapter01/SVD_Demo.py", "max_forks_repo_name": "retwal/Predictive", "max_forks_repo_head_hexsha": "57c3cb64901b7a0629b70053ecf01dac5be66d6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 72, "max_forks_repo_forks_event_min_datetime": "2017-11-06T07:08:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T09:00:28.000Z", "avg_line_length": 31.8270676692, "max_line_length": 115, "alphanum_fraction": 0.702811245, "include": true, "reason": "import numpy", "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812354689082, "lm_q2_score": 0.8933094167058151, "lm_q1q2_score": 0.8650640766055869}}
{"text": "import collections\nimport math\nimport re\nimport string\n\nimport numpy as np\n\n\nclass Logistic_Regression():\n    def __init__(self):\n        self.W = None\n        self.b = None\n\n    def fit(self, x, y, batch_size=64, iteration=2000, learning_rate=1e-2):\n        \"\"\"\n        Train this Logistic Regression classifier using mini-batch stochastic gradient descent.\n        Inputs:\n        - X: A numpy array of shape (N, D) containing training data; there are N\n          training samples each of dimension D.\n        - y: A numpy array of shape (N,) containing training labels; y[i] = c\n          means that X[i] has label 0 <= c < C for C classes.\n        - learning_rate: (float) learning rate for optimization.\n        - iteration: (integer) number of steps to take when optimizing\n        - batch_size: (integer) number of training examples to use at each step.\n        \n        Use the given learning_rate, iteration, or batch_size for this homework problem.\n\n        Returns:\n        None\n        \"\"\"\n        dim = x.shape[1]\n        num_train = x.shape[0]\n\n        # initialize W\n        if self.W is None:\n            self.W = 0.001 * np.random.randn(dim, 1)\n            self.b = 0\n\n        for it in range(iteration):\n            batch_ind = np.random.choice(num_train, batch_size)\n\n            x_batch = x[batch_ind]\n            y_batch = y[batch_ind]\n\n            ############################################################\n            ############################################################\n            # BEGIN_YOUR_CODE\n            # Calculate loss and update W, b\n\n            z = x_batch.dot(self.W) + self.b\n            y_hat = self.sigmoid(z)\n\n            loss, grad = self.loss(x_batch, y_hat, y_batch)\n\n            self.W = self.W - learning_rate * grad[\"dW\"]\n            self.b = self.b - learning_rate * grad[\"db\"]\n\n            y_pred = self.predict(x_batch)\n\n            acc = np.mean(y_pred == y_batch)\n\n            pass\n\n            # END_YOUR_CODE\n            ############################################################\n            ############################################################\n\n            if it % 50 == 0:\n                print('iteration %d / %d: accuracy : %f: loss : %f' % (it, iteration, acc, loss))\n\n    def predict(self, x):\n        \"\"\"\n        Use the trained weights of this linear classifier to predict labels for\n        data points.\n        Inputs:\n\n        Returns:\n        - y_pred: Predicted labels for the data in X. y_pred is a 1-dimensional\n          array of length N, and each element is an integer giving the predicted\n          class.\n        \"\"\"\n        ############################################################\n        ############################################################\n        # BEGIN_YOUR_CODE\n        # Calculate predicted y\n\n        z = x.dot(self.W) + self.b\n        y_pred = np.round(self.sigmoid(z))\n\n        pass\n\n        # END_YOUR_CODE\n        ############################################################\n        ############################################################\n        return y_pred\n\n    def loss(self, x_batch, y_pred, y_batch):\n        \"\"\"\n        Compute the loss function and its derivative. \n        Inputs:\n        - X_batch: A numpy array of shape (N, D) containing a minibatch of N\n          data points; each point has dimension D.\n        - y_batch: A numpy array of shape (N,) containing labels for the minibatch.\n\n        Returns: A tuple containing:\n        - loss as a single float\n        - gradient dictionary with two keys : 'dW' and 'db'\n        \"\"\"\n        gradient = {'dW': None, 'db': None}\n        ############################################################\n        ############################################################\n        # BEGIN_YOUR_CODE\n        # Calculate loss and gradient\n\n        y_hat = y_pred\n        n = y_hat.shape[0]\n        loss = -np.sum(y_batch * np.log(y_hat + 1e-5)) / n\n\n        dw = 2 * x_batch.transpose().dot(y_hat - y_batch) / n\n        db = np.mean(y_hat - y_batch) / n\n\n        gradient[\"dW\"] = dw\n        gradient[\"db\"] = db\n\n        pass\n\n        # END_YOUR_CODE\n        ############################################################\n        ############################################################\n        return loss, gradient\n\n    def sigmoid(self, z):\n        \"\"\"\n        Compute the sigmoid of z\n        Inputs:\n        z : A scalar or numpy array of any size.\n        Return:\n        s : sigmoid of input\n        \"\"\"\n        ############################################################\n        ############################################################\n        # BEGIN_YOUR_CODE\n        # Calculate loss and update W\n\n        z = np.clip(z, -500, 500)\n        s = 1 / (1 + np.exp(-z))\n\n        # END_YOUR_CODE\n        ############################################################\n        ############################################################\n\n        return s\n\n\nclass Naive_Bayes():\n    def fit(self, X_train, y_train):\n        \"\"\"\n        fit with training data\n        Inputs:\n            - X_train: A numpy array of shape (N, D) containing training data; there are N\n                training samples each of dimension D.\n            - y_train: A numpy array of shape (N,) containing training labels; y[i] = c\n                means that X[i] has label 0 <= c < C for C classes.\n                \n        With the input dataset, function gen_by_class will generate class-wise mean and variance to implement bayes inference.\n\n        Returns:\n        None\n        \n        \"\"\"\n\n        self.x = X_train\n        self.y = y_train\n\n        self.gen_by_class()\n\n    def gen_by_class(self):\n        \"\"\"\n        With the given input dataset (self.x, self.y), generate 3 dictionaries to calculate class-wise mean and variance of the data.\n        - self.x_by_class : A dictionary of numpy arraies with the keys as each class label and values as data with such label.\n        - self.mean_by_class : A dictionary of numpy arraies with the keys as each class label and values as mean of the data with such label.\n        - self.std_by_class : A dictionary of numpy arraies with the keys as each class label and values as standard deviation of the data with such label.\n        - self.y_prior : A numpy array of shape (C,) containing prior probability of each class\n        \"\"\"\n        self.x_by_class = dict()\n        self.mean_by_class = dict()\n        self.std_by_class = dict()\n        self.y_prior = None\n\n        ############################################################\n        ############################################################\n        # BEGIN_YOUR_CODE\n        # Generate dictionaries.\n        # hint : to see all unique y labels, you might use np.unique function, e.g., np.unique(self.y)\n\n        pass\n\n        # END_YOUR_CODE\n        ############################################################\n        ############################################################        \n\n    def mean(self, x):\n        ############################################################\n        ############################################################\n        # BEGIN_YOUR_CODE\n        # Calculate mean of input x\n        mean = 0\n        pass\n        # END_YOUR_CODE\n        ############################################################\n        ############################################################\n        return mean\n\n    def std(self, x):\n        ############################################################\n        ############################################################\n        # BEGIN_YOUR_CODE\n        # Calculate standard deviation of input x, do not use np.std\n        std = 0\n        pass\n        # END_YOUR_CODE\n        ############################################################\n        ############################################################\n        return std\n\n    def calc_gaussian_dist(self, x, mean, std):\n        ############################################################\n        ############################################################\n        # BEGIN_YOUR_CODE\n        # calculate gaussian probability of input x given mean and std\n        pass\n        # END_YOUR_CODE\n        ############################################################\n        ############################################################\n\n    def predict(self, x):\n        \"\"\"\n        Use the acquired mean and std for each class to predict class for input x.\n        Inputs:\n\n        Returns:\n        - prediction: Predicted labels for the data in x. prediction is (N, C) dimensional array, for N samples and C classes.\n        \"\"\"\n\n        n = len(x)\n        num_class = len(np.unique(self.y))\n        prediction = np.zeros((n, num_class))\n\n        ############################################################\n        ############################################################\n        # BEGIN_YOUR_CODE\n        # calculate naive bayes probability of each class of input x\n\n        pass\n        # END_YOUR_CODE\n        ############################################################\n        ############################################################\n\n        return prediction\n\n\nclass Spam_Naive_Bayes(object):\n    \"\"\"Implementation of Naive Bayes for Spam detection.\"\"\"\n    def __init__(self):\n        self.word_counts = {'spam': {}, 'ham': {}}\n        self.num_messages = {'spam': 0, 'ham': 0}\n        self.class_priors = {'spam': 0.0, 'ham': 0.0}\n\n    def clean(self, s):\n        translator = str.maketrans(\"\", \"\", string.punctuation)\n        return s.translate(translator)\n\n    def tokenize(self, text):\n        text = self.clean(text).lower()\n        return re.split(\"\\W+\", text)\n\n    def get_word_counts(self, words):\n        \"\"\"\n        Generate a dictionary 'word_counts' \n        Hint: You can use helper function self.clean and self.toeknize.\n              self.tokenize(x) can generate a list of words in an email x.\n\n        Inputs:\n            -words : list of words that is used in a data sample\n        Output:\n            -word_counts : contains each word as a key and number of that word is used from input words.\n        \"\"\"\n        ############################################################\n        ############################################################\n        # BEGIN_YOUR_CODE\n        # calculate naive bayes probability of each class of input x\n\n        token = self.tokenize(words[0])\n        word_counts = {}\n        for word in token:\n            if word in word_counts:\n                word_counts[word] = word_counts[word] + 1\n            else:\n                word_counts[word] = 1\n\n        # END_YOUR_CODE\n        ############################################################\n        ############################################################\n\n        return word_counts\n\n    def fit(self, X_train, y_train):\n        \"\"\"\n        compute likelihood of all words given a class\n\n        Inputs:\n            -X_train : list of emails\n            -y_train : list of target label (spam : 1, non-spam : 0)\n            \n        Variables:\n            -self.num_messages : dictionary contains number of data that is spam or not\n            -self.word_counts : dictionary counts the number of certain word in class 'spam' and 'ham'.\n            -self.class_priors : dictionary of prior probability of class 'spam' and 'ham'.\n        Output:\n            None\n        \"\"\"\n        ############################################################\n        ############################################################\n        # BEGIN_YOUR_CODE\n        # calculate naive bayes probability of each class of input x\n        for x in range(len(X_train)):\n            words = self.tokenize(X_train[x])\n            if y_train[x] == 1:\n                self.num_messages['spam'] = self.num_messages['spam'] + 1\n            else:\n                self.num_messages['ham'] = self.num_messages['ham'] + 1\n\n            for word in words:\n                if word not in self.word_counts['spam']:\n                    self.word_counts['spam'][word] = 0\n                if word not in self.word_counts['ham']:\n                    self.word_counts['ham'][word] = 0\n                if y_train[x] == 1:\n                    self.word_counts['spam'][word] = self.word_counts['spam'][word] + 1\n                else:\n                    self.word_counts['ham'][word] = self.word_counts['ham'][word] + 1\n\n        self.class_priors['spam'] = self.num_messages['spam'] / (self.num_messages['spam'] + self.num_messages['ham'])\n        self.class_priors['ham'] = self.num_messages['ham'] / (self.num_messages['spam'] + self.num_messages['ham'])\n\n        pass\n        # END_YOUR_CODE\n        ############################################################\n        ############################################################\n\n    def predict(self, X):\n        \"\"\"\n        predict that input X is spam of not. \n        Given a set of words {x_i}, for x_i in an email(x), if the likelihood \n        \n        p(x_0|spam) * p(x_1|spam) * ... * p(x_n|spam) * y(spam) > p(x_0|ham) * p(x_1|ham) * ... * p(x_n|ham) * y(ham),\n        \n        then, the email would be spam.\n\n        Inputs:\n            -X : list of emails\n\n        Output:\n            -result : A numpy array of shape (N,). It should tell rather a mail is spam(1) or not(0).\n        \"\"\"\n\n        result = []\n        for x in X:\n            ############################################################\n            ############################################################\n            # BEGIN_YOUR_CODE\n            # calculate naive bayes probability of each class of input x\n\n            p_spam = -1\n            p_ham = -1\n\n            words = self.tokenize(x)\n            for word in words:\n                if p_spam == -1 and word in self.word_counts['spam']:\n                    p_spam = self.word_counts['spam'][word] / self.num_messages['spam']\n                    p_ham = self.word_counts['ham'][word] / self.num_messages['ham']\n                elif word in self.word_counts['spam']:\n                    p_spam = p_spam * (self.word_counts['spam'][word] / self.num_messages['spam'])\n                    p_ham = p_ham * (self.word_counts['ham'][word] / self.num_messages['ham'])\n\n            if p_spam > p_ham:\n                result.append(1)\n            else:\n                result.append(0)\n\n            pass\n            # END_YOUR_CODE\n            ############################################################\n            ############################################################\n\n        result = np.array(result)\n        return result\n", "meta": {"hexsha": "7bb148a92ad981cef82873be7793ff9fdb0d1a03", "size": 14585, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw2/hw2_submission.py", "max_stars_repo_name": "petersumner/ECE473", "max_stars_repo_head_hexsha": "633860660e589df20b50c6f50f19e378951178cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw2/hw2_submission.py", "max_issues_repo_name": "petersumner/ECE473", "max_issues_repo_head_hexsha": "633860660e589df20b50c6f50f19e378951178cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw2/hw2_submission.py", "max_forks_repo_name": "petersumner/ECE473", "max_forks_repo_head_hexsha": "633860660e589df20b50c6f50f19e378951178cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6457286432, "max_line_length": 155, "alphanum_fraction": 0.4317449434, "include": true, "reason": "import numpy", "num_tokens": 2879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812327313545, "lm_q2_score": 0.8933094088947399, "lm_q1q2_score": 0.8650640665960058}}
{"text": "import numpy as np\nimport math\n\ndef euclidiana(vetor): # norma-2 vetorial\n    n, x = len(vetor), 0\n\n    for i in range(n):\n        x += math.fabs(vetor[i]) ** 2\n\n    return x ** (1/2)\n\ndef manhattan(vetor): # norma-1 vetorial\n    n, x = len(vetor), 0\n\n    for i in range(n):\n        x += math.fabs(vetor[i])\n\n    return x\n\ndef p(vetor, p): #norma-p vetorial\n    n, x = len(vetor), 0\n\n    for i in range(n):\n        x += math.fabs(math.pow(vetor[i], p))\n\n    return x ** (1/p)\n\ndef infinita(vetor): # norma-infinita vetorial\n    n, max = len(vetor), vetor[0]\n    \n    for i in range(1, n):\n        if math.fabs(vetor[i]) > max:\n            max = math.fabs(vetor[i])\n\n    return max\n\ndef frobenius(matriz_a): # norma-2 matricial\n    n, x = len(matriz_a), 0\n\n    for i in range(n):\n        for j in range(n):\n            x += math.pow(math.fabs(matriz_a[i,j]), 2)\n\n    return x ** (1/2)\n\ndef soma_coluna(matriz_a): # norma-1 matricial\n    n, max, x = len(matriz_a), 0, 0\n\n    for j in range(n):\n        for i in range(n):\n            x += math.fabs(matriz_a[i,j])\n        \n        if x > max:\n            max = x\n    \n    return max\n\ndef soma_linha(matriz_a): # norma-infinita matricial\n    n, max, x = len(matriz_a), 0, 0\n\n    for i in range(n):\n        for j in range(n):\n            x += math.fabs(matriz_a[i,j])\n        \n        if x > max:\n            max = x\n\n    return max\n\ndef residual(matriz_a, vetor_b, delta_x): #norma-residual matricial\n    n, k = len(matriz_a), np.linalg.cond(matriz_a)\n    delta_b = np.matmul(matriz_a, delta_x)\n    vetor_r = vetor_b - delta_b\n\n    vetor_x = np.ones(n)\n    vetor_x_menos_delta_x = vetor_x - delta_x\n    residuo_r_b = euclidiana(vetor_r)/euclidiana(vetor_b)\n\n    print(\"Vetor residual:\\n\", vetor_r)\n    print(\"Resíduo da solução x:\", residuo_r_b)\n\n    if euclidiana(vetor_x_menos_delta_x)/euclidiana(vetor_x) <= k*residuo_r_b:\n        print(\"A solução encontrada é precisa.\")\n    else:\n        print(\"A solução encontrada não é precisa.\")", "meta": {"hexsha": "e23ca94690e01232331a3f99f82e74415417c759", "size": 1983, "ext": "py", "lang": "Python", "max_stars_repo_path": "normas.py", "max_stars_repo_name": "eRRe-i/algebra-linear-computacional", "max_stars_repo_head_hexsha": "f2caffdb33aed0fad9d811b20f6505ad6513d824", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "normas.py", "max_issues_repo_name": "eRRe-i/algebra-linear-computacional", "max_issues_repo_head_hexsha": "f2caffdb33aed0fad9d811b20f6505ad6513d824", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "normas.py", "max_forks_repo_name": "eRRe-i/algebra-linear-computacional", "max_forks_repo_head_hexsha": "f2caffdb33aed0fad9d811b20f6505ad6513d824", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-23T02:07:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-23T02:07:55.000Z", "avg_line_length": 23.3294117647, "max_line_length": 78, "alphanum_fraction": 0.5774079677, "include": true, "reason": "import numpy", "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812309063186, "lm_q2_score": 0.8933094039240554, "lm_q1q2_score": 0.8650640601521665}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 17 16:07:48 2019\n\n@author: TempestGuerra\n\"\"\"\n\nimport numpy as np\nfrom numpy import multiply as mul\nfrom scipy import linalg as las\nimport math as mt\nfrom scipy.special import roots_hermite\nfrom scipy.special import roots_chebyt\n\ndef hefunclb(NX):\n       #'''\n       # Compute off-diagonals of 7.84 in Spectral Methods, Springer\n       b = range(1,NX+1)\n       bd = 0.5 * np.array(b)\n       \n       # Assemble the matrix\n       m1 = np.diag(np.sqrt(bd), k=+1)\n       m2 = np.diag(np.sqrt(bd), k=-1)\n       mm = np.add(m1,m2)\n       \n       # Compute the eigenvalues of this matrix (zeros Hermite polys)\n       ew = las.eigvals(mm)\n       # Sort the eigenvalues in ascending order and store nodes\n       xi = np.sort(np.real(ew))\n       \n       # Compute the Hermite function weights\n       hf = hefuncm(NX, xi, False)\n       w = 1.0 / (NX+1) * np.power(hf, -2.0)\n       #'''\n       '''\n       xi, w = roots_hermite(NX+1)\n       \n       # Compute the Hermite function weights\n       hf = hefuncm(NX, xi, False)\n       w = 1.0 / (NX+1) * np.power(hf, -2.0)\n       '''     \n       return xi, w\n       \ndef hefuncm(NX, xi, fullMat):\n       # Initialize constant\n       cst = 1.0 / mt.pi**4;\n       ND = len(xi)\n       \n       # Initialize the output matrix if needed\n       if fullMat:\n              HFM = np.zeros((NX+1,ND))\n              \n       # Compute the first two modes of the recursion\n       wfun = np.exp(-0.5 * np.power(xi, 2.0))\n       poly0 = cst * wfun;\n       poly1 = cst * mt.sqrt(2.0) * (xi * wfun);\n       \n       # Put the first two functions in the matrix or return low order functions\n       if fullMat:\n              HFM[0,:] = poly0\n              HFM[1,:] = poly1\n       elif NX == 0:\n              return poly0\n       elif NX == 1:\n              return poly1\n       \n       for nn in range(1,NX):\n              polyn = mt.sqrt(2.0 / (nn+1)) * (xi * poly1)\n              polyn -= mt.sqrt(nn / (nn+1)) * poly0\n              poly0 = poly1; \n              poly1 = polyn;\n              # Put the new function in its matrix place\n              if fullMat:\n                     HFM[nn+1,:] = polyn\n              else:\n                     HFM = polyn\n       \n       return HFM.T\n\ndef cheblb(NZ):\n       # Compute Chebyshev CGL nodes and weights\n       ep = NZ - 1\n       xc = np.array(range(NZ))\n       xi = -np.cos(mt.pi / ep * xc)\n       \n       w = mt.pi / NZ * np.ones(NZ)\n       w[0] *= 0.5\n       w[ep] *= 0.5\n       \n       return xi, w\n   \ndef chebpolym(NM, xi):\n       # Compute Chebyshev pols (first kind) into a matrix transformation\n       # Functions need to be arranged bottom to top!\n       NX = len(xi)\n       CTM = np.zeros((NX, NM+1))\n       \n       CTM[:,0] = np.ones(NX)\n       CTM[:,1] = xi\n       \n       # 3 Term recursion for functions\n       for ii in range(2, NM+1):\n              CTM[:,ii] = 2.0 * \\\n              mul(xi, CTM[:,ii-1]) - \\\n              CTM[:,ii-2]\n              \n       return CTM", "meta": {"hexsha": "7eea30b01c7eee476a78bd20fcb8bbb4b0ea3de7", "size": 3007, "ext": "py", "lang": "Python", "max_stars_repo_path": "HerfunChebNodesWeights.py", "max_stars_repo_name": "jeguerra/nonlinearMtnWavesSolver", "max_stars_repo_head_hexsha": "e2fe83d1f7c3c57cbe9ba0299a1b9179cf4b5869", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HerfunChebNodesWeights.py", "max_issues_repo_name": "jeguerra/nonlinearMtnWavesSolver", "max_issues_repo_head_hexsha": "e2fe83d1f7c3c57cbe9ba0299a1b9179cf4b5869", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HerfunChebNodesWeights.py", "max_forks_repo_name": "jeguerra/nonlinearMtnWavesSolver", "max_forks_repo_head_hexsha": "e2fe83d1f7c3c57cbe9ba0299a1b9179cf4b5869", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-30T05:04:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-30T05:04:44.000Z", "avg_line_length": 27.8425925926, "max_line_length": 80, "alphanum_fraction": 0.4915197872, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812290812825, "lm_q2_score": 0.8933093961129794, "lm_q1q2_score": 0.8650640509577453}}
{"text": "from sympy import Matrix\nimport numpy as np\nimport random\n\ndef GenerateMatrixWithRank(row, column, rank, lowerBound=-9, upperBound=9):\n    \"\"\"\n    Generate Matrix with Rank=rank\n    Res = A(row x rank) X B(rank x column)\n    lowerBound: lower bound for generated entry\n    upperBound: upper bound for generated entry\n    \"\"\"\n    A = np.array([random.randint(lowerBound, upperBound) for x in range(row*rank)]).reshape(row, rank)\n    B = np.array([random.randint(lowerBound, upperBound) for x in range(column*rank)]).reshape(rank, column)\n    \n    return np.matmul(A, B)\n\nif __name__ == \"__main__\":\n    rank = 1\n    row = 5\n    column = 7\n    M = GenerateMatrixWithRank(row, column, rank, lowerBound=-3, upperBound=3)\n    print(M)\n    RREF, cols = Matrix.rref(Matrix(M))\n    C = np.array(M)[:,[x for x in cols]]\n    R = np.array(RREF)[[x for x in cols],:]\n    \n    print(\"C:\")\n    print(C)\n    print(\"R:\")\n    print(R)\n    print(\"C x R:\")\n    print(np.matmul(C, R))", "meta": {"hexsha": "e48f2a51ecec73dd2f64de565094482841aa778b", "size": 963, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_algebra/generateMatrixWithRank.py", "max_stars_repo_name": "hiukongDan/pywork", "max_stars_repo_head_hexsha": "5ee6e6176cd63fa049d142e0f04c8416f668ba06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_algebra/generateMatrixWithRank.py", "max_issues_repo_name": "hiukongDan/pywork", "max_issues_repo_head_hexsha": "5ee6e6176cd63fa049d142e0f04c8416f668ba06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_algebra/generateMatrixWithRank.py", "max_forks_repo_name": "hiukongDan/pywork", "max_forks_repo_head_hexsha": "5ee6e6176cd63fa049d142e0f04c8416f668ba06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.09375, "max_line_length": 108, "alphanum_fraction": 0.6375908619, "include": true, "reason": "import numpy,from sympy", "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075722839015, "lm_q2_score": 0.8991213813246444, "lm_q1q2_score": 0.8650514893748017}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# 计算在某一特定t下的 B_{i,k}\ndef getBt(controlPoints, knots, t):\n\t# calculate m,n,k\n\tm = knots.shape[0]-1\n\tn = controlPoints.shape[0]-1\n\tk = m - n - 1\n\t# initialize B by zeros \n\tB = np.zeros((k+1, m))\n\n\t# get t region\n\ttStart = 0\n\tfor x in range(m+1):\n\t\tif t==1:\n\t\t\ttStart = m-1\n\t\tif knots[x] > t:\n\t\t\ttStart = x-1\n\t\t\tbreak\n\t \n\t# calculate B(t)\n\tfor _k in range(k+1):\n\t\tif _k == 0:\n\t\t\tB[_k, tStart] = 1\n\t\telse:\n\t\t\tfor i in range(m-_k):\n\t\t\t\tif knots[i+_k]-knots[i]== 0:\n\t\t\t\t\tw1 = 0\n\t\t\t\telse:\n\t\t\t\t\tw1 = (t-knots[i])/(knots[i+_k]-knots[i]) \n\t\t\t\tif knots[i+_k+1]-knots[i+1] == 0:\n\t\t\t\t\tw2 = 0\n\t\t\t\telse:\n\t\t\t\t\tw2 = (knots[i+_k+1]-t)/(knots[i+_k+1]-knots[i+1])\n\t\t\t\tB[_k,i] = w1*B[_k-1, i] + w2*B[_k-1, i+1]\n\treturn B\n\n# 绘制 B_{i,k}(t)函数\ndef plotBt(Bt,num, i,k):\n\tprint(k,i)\n\tBt = np.array(Bt)\n\ttt = np.linspace(0,1,num)\n\tyy = [Bt[t,k,i] for t in range(num)]\n\tplt.plot(tt, yy)\n\n# 根据最后一列（最高阶次）的 B(t)，即权重，乘以控制点坐标，从而求出曲线上点坐标\ndef getPt(Bt, controlPoints):\n\tBt = np.array(Bt)\n\tptArray = Bt.reshape(-1,1) * controlPoints\n\tpt = ptArray.sum(axis = 0)\n\treturn pt\n\n# 绘制出生成的样条曲线: useReg 表示是否使用曲线有效定义域[t_k, t_{m-k}]\ndef main1(controlPoints ,knots, useReg = False):\n\t\n\t\n\tm = knots.shape[0]-1\n\tn = controlPoints.shape[0]-1\n\tk = m - n - 1\n\tprint('n:',n)\n\tprint('m:',m)\n\tprint('k:',k)\n    \n\tfor t in np.linspace(0,1,100):\n\t\tif useReg and not(t >= knots[k] and t<= knots[n+1]):\n\t\t\tcontinue\n\t\tBt = getBt(controlPoints, knots, t)\n\t\tPt = getPt(Bt[k, :n+1], controlPoints)\n        \n\t\tplt.scatter(Pt[0],Pt[1],color='b')\n        \n\tplt.scatter(controlPoints[:,0], controlPoints[:,1],color = 'r')\n\tplt.show()\n\n# 绘制 B_{i,k} 变化图:如果不给定{i,k}则显示所有B{i,k}(t)图像\ndef main2(i=-1,k=-1):\n\tcontrolPoints = np.array([[50,50], [100,300], [300,100], [380,200], [400,600]])\n\tknots = np.array([0,1/9,2/9,3/9,4/9,5/9,6/9,7/9,8/9,1])\n\tm = knots.shape[0]-1\n\tn = controlPoints.shape[0]-1\n\tk = m - n - 1\n\tprint('n:',n)\n\tprint('m:',m)\n\tprint('k:',k)\n\tB = []\n\tnum = 100 # 离散点数目\n\tfor t in np.linspace(0,1,num):\n\t\tBt = getBt(controlPoints, knots, t)\n\t\tB.append(list(Bt))\n\n\tfigure1 = plt.figure('B_{i,k}')\n\tif i==-1:\n\t\tfig = []\n\t\tfor i in range(n+1):\n\t\t\tfor k in range(k+1):\n\t\t\t\tplotBt(B,num, i,k)\n\t\t\t\tfig.append('B_{%d,%d}'%(i,k))\n\telse:\n\t\tplotBt(B,num, i,k)\n\t\tfig.append('B_{%d,%d}'%(i,k))\n\tplt.legend(fig)\n\tplt.show()   \n    \nif __name__ == '__main__':\n    controlPoints = np.array([ \n                [ 0.00000000e+00 , 0.00000000e+00 ], [-1.73422712e+01 , 2.15658488e-01],\n                [-2.35382699e+01 , 3.13403809e-01] ,[-3.76766971e+01,  5.46545379e-01],\n                [-4.78039077e+01 , 5.62960911e-01 ],[-5.98447978e+01 ,-7.11339258e-02],\n                [-7.74681854e+01, -2.17359351e+00] ,[-8.87793826e+01 ,-1.75073904e+00],\n                [-9.63270000e+01, -1.81000000e+00]\n                            ])\n    knots = np.array([0,0,0,0,1/6,1/3,1/2,2/3,5/6,1,1,1,1])\n    \n    main1(controlPoints,knots)\n   \n", "meta": {"hexsha": "33757837dd7cc4c865af499b1a16b47a2301e114", "size": 2903, "ext": "py", "lang": "Python", "max_stars_repo_path": "process_data/controltoline.py", "max_stars_repo_name": "NovemberChopin/GuideLine", "max_stars_repo_head_hexsha": "d49b3b527a5e54f3ee734c8d5245efb89150d594", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "process_data/controltoline.py", "max_issues_repo_name": "NovemberChopin/GuideLine", "max_issues_repo_head_hexsha": "d49b3b527a5e54f3ee734c8d5245efb89150d594", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "process_data/controltoline.py", "max_forks_repo_name": "NovemberChopin/GuideLine", "max_forks_repo_head_hexsha": "d49b3b527a5e54f3ee734c8d5245efb89150d594", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-28T11:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T11:58:47.000Z", "avg_line_length": 24.811965812, "max_line_length": 88, "alphanum_fraction": 0.5607991733, "include": true, "reason": "import numpy", "num_tokens": 1274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.8991213772699435, "lm_q1q2_score": 0.8650514835199684}}
{"text": "import numpy as np\n\nfrom compute_cost import compute_cost\n\n\ndef gradient_descent(x, y, size, theta, alpha, iterations):\n    \"\"\"\n        Performs gradient descent to optimize the 'theta' parameters. Updates theta for a total of\n        inputted 'iterations', with a learning rate 'alpha'.\n\n        Parameters\n        ----------\n        x : array_like\n            Shape (m, n+1), where m is the number of examples, and n is the number of features\n            including the vector of ones for the zeroth parameter.\n\n        y : array_like\n            Shape (m,), where m is the value of the function at each point.\n\n        size : int\n            Number of total training points.\n\n        theta : array_like\n            Shape (n+1, 1). Starting parameters of the regression function.\n\n        alpha : float\n            The learning rate.\n\n        iterations : int\n            The number of iterations for gradient descent.\n\n        Returns\n        -------\n        theta : array_like\n            Shape (n+1, 1). The optimized linear regression parameters.\n\n        cost_history : list\n            A list of the values of the cost function after each iteration.\n    \"\"\"\n\n    cost_history = []\n    converge = False\n    for i in range(iterations):\n        temp_cost = compute_cost(x, y, size, theta)\n        try:\n            if cost_history[-1] - temp_cost <= 0.0001:\n                converge = True\n        except IndexError:\n            pass\n        cost_history.append(temp_cost)\n\n        delta = (1 / size) * ((np.dot(theta.T, x)) - y) * x\n        delta2 = delta.sum(axis=1, keepdims=True)\n        theta = (theta - (alpha * delta2))\n    if converge:\n        print(\"The function converged, use less iterations.\")\n    print(f\"The new optimized parameters are: \\n{theta}\\n\")\n    return theta, cost_history\n", "meta": {"hexsha": "8fcb1086699f6f61982eb3d6e9a852926f8e2220", "size": 1800, "ext": "py", "lang": "Python", "max_stars_repo_path": "gradient_descent.py", "max_stars_repo_name": "KevinKronk/linear-regression", "max_stars_repo_head_hexsha": "1f1eb4bfcb5603b29df499fb7bfb2ab4b8d2d791", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gradient_descent.py", "max_issues_repo_name": "KevinKronk/linear-regression", "max_issues_repo_head_hexsha": "1f1eb4bfcb5603b29df499fb7bfb2ab4b8d2d791", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gradient_descent.py", "max_forks_repo_name": "KevinKronk/linear-regression", "max_forks_repo_head_hexsha": "1f1eb4bfcb5603b29df499fb7bfb2ab4b8d2d791", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5084745763, "max_line_length": 98, "alphanum_fraction": 0.59, "include": true, "reason": "import numpy", "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075690244281, "lm_q2_score": 0.8991213759183765, "lm_q1q2_score": 0.8650514812427281}}
{"text": "# Draw 100000 samples from Normal distribution with stds of interest: samples_std1, samples_std3, samples_std10\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nsamples_std1 = np.random.normal(20, 1, size=100000)\nsamples_std3 = np.random.normal(20, 3, size=100000)\nsamples_std10 = np.random.normal(20, 10, size=100000)\n\n# Make histograms\nplt.hist(samples_std1, bins=100, normed = True, histtype = 'step')\nplt.hist(samples_std3,bins=100, normed = True, histtype = 'step')\nplt.hist(samples_std10, bins=100,normed = True, histtype = 'step')\n\n# Make a legend, set limits and show plot\nplt.legend(('std = 1', 'std = 3', 'std = 10'))\nplt.ylim(-0.01, 0.42)\nplt.show()\n\n\n", "meta": {"hexsha": "e17a0bedf4f75731ad14bb1f9ca6bc0d8b32a8aa", "size": 666, "ext": "py", "lang": "Python", "max_stars_repo_path": "Codes/EDA/normal_pdf.py", "max_stars_repo_name": "shohan4556/machine-learning-course-notes", "max_stars_repo_head_hexsha": "981f3d6e9861cbee0f4dec45b1d2e6a214d2a051", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-10-12T17:08:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-26T02:54:01.000Z", "max_issues_repo_path": "Codes/EDA/normal_pdf.py", "max_issues_repo_name": "shohan4556/machine-learning-course-notes", "max_issues_repo_head_hexsha": "981f3d6e9861cbee0f4dec45b1d2e6a214d2a051", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Codes/EDA/normal_pdf.py", "max_forks_repo_name": "shohan4556/machine-learning-course-notes", "max_forks_repo_head_hexsha": "981f3d6e9861cbee0f4dec45b1d2e6a214d2a051", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-10-30T03:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-11T20:53:47.000Z", "avg_line_length": 33.3, "max_line_length": 111, "alphanum_fraction": 0.7312312312, "include": true, "reason": "import numpy", "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075690244281, "lm_q2_score": 0.8991213759183765, "lm_q1q2_score": 0.8650514812427281}}
{"text": "# -*-coding:utf-8 -*-\nimport numpy as np\nfrom scipy import interpolate\nimport pylab as pl\n\nx=np.linspace(0,10,11)\n#x=[  0.   1.   2.   3.   4.   5.   6.   7.   8.   9.  10.]\ny=np.sin(x)\nxnew=np.linspace(0,10,101)\npl.plot(x,y,\"ro\")\n\nfor kind in [\"nearest\",\"zero\",\"slinear\",\"quadratic\",\"cubic\"]:#插值方式\n    #\"nearest\",\"zero\"为阶梯插值\n    #slinear 线性插值\n    #\"quadratic\",\"cubic\" 为2阶、3阶B样条曲线插值\n    f=interpolate.interp1d(x,y,kind=kind)\n    # ‘slinear’, ‘quadratic’ and ‘cubic’ refer to a spline interpolation of first, second or third order)\n    ynew=f(xnew)\n    pl.plot(xnew,ynew,label=str(kind))\npl.legend(loc=\"lower right\")\npl.show()\n", "meta": {"hexsha": "12d86fc3961b7dd23b3eb9cbb697a56a23601207", "size": 626, "ext": "py", "lang": "Python", "max_stars_repo_path": "line chart/smooth.py", "max_stars_repo_name": "haoruilee/statistics-graphs", "max_stars_repo_head_hexsha": "ed5d1a34998b80da6d7866c845c182f0cf594898", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-12T15:34:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T13:43:41.000Z", "max_issues_repo_path": "line chart/smooth.py", "max_issues_repo_name": "haoruilee/statistics-graphs", "max_issues_repo_head_hexsha": "ed5d1a34998b80da6d7866c845c182f0cf594898", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "line chart/smooth.py", "max_forks_repo_name": "haoruilee/statistics-graphs", "max_forks_repo_head_hexsha": "ed5d1a34998b80da6d7866c845c182f0cf594898", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4545454545, "max_line_length": 105, "alphanum_fraction": 0.6357827476, "include": true, "reason": "import numpy,from scipy", "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.8991213745668094, "lm_q1q2_score": 0.8650514809192628}}
{"text": "import numpy as np\n\nprint(\"\")\nprint(\"Ejercicio 1.1\")\nA = np.array([[4, -2, 1, ], [3, 6, -4], [2, 1, 8]])\nA_inversa = np.linalg.inv(A)\nprint(\"\")\nprint(\"Matriz A\")\nprint(A)\nprint(\"\")\nprint(\"Matriz A^-1\")\nprint(A_inversa)\nprint(\"\")\nprint(\"Verificando A * A^-1\")\nprint(A@A_inversa)\n\nprint(\"\")\nprint(\"Ejercicio 1.2\")\nA_inversa_analitica = (1/263)*np.array([[52, 17, 2],[-32, 30, 19],[-9, -8, 30]])\nprint(\"\")\nprint(\"Cifras significativas en A^{-1}\")\nprint(np.log10(np.abs(A_inversa-A_inversa_analitica)))\n\nprint(\"\")\nprint(\"Ejercicio 2\")\nb = np.array([12, -25, 32])\nx_sol = np.array([+1, -2, +4])\nx = np.linalg.solve(A, b)\nprint(\"\")\nprint(\"numerico: {} . analitico: {}\".format(x, x_sol))\n\nb = np.array([+4, -10, +22])\nx_sol = np.array([+0.312, -0.038, +2.677])\nx = np.linalg.solve(A, b)\nprint(\"\")\nprint(\"numerico: {} . analitico: {}\".format(x, x_sol))\n\nb = np.array([+20, -30, +40])\nx_sol = np.array([+2.319, -2.965, +4.790])\nx = np.linalg.solve(A, b)\nprint(\"\")\nprint(\"numerico: {} . analitico: {}\".format(x, x_sol))\n\nprint(\"\")\nprint(\"Ejercicio 3\")\nalpha = 2.0\nbeta = 1.0\nA = np.array([[alpha, beta], [-beta, alpha]])\nvalues, vectors = np.linalg.eig(A)\nprint(\"\")\nprint('lambda_1 {}. eigenvec_1 {}'.format(values[0], vectors[:,0]))\nprint('lambda_2 {}. eigenvec_2 {}'.format(values[1], vectors[:,1]))\nprint('son complejos conjugados como se esperaba')\n\nprint(\"Ejercicio 4\")\nA = np.array([[-2, +2, -3], [+2, +1, -6], [-1, -2, +0]])\nvalues, vectors = np.linalg.eig(A)\nprint(\"\")\nprint(\"Obtengo autovalores: {}. Esperaba {} {} {}\".format(values, 5, -3, -3))\neigen_5 = 1/np.sqrt(6)*np.array([-1, -2, +1])\neigen_3_a = 1/np.sqrt(5)*np.array([-2, +1, 0])\neigen_3_b = 1/np.sqrt(10)*np.array([3, 0, +1])\n\nprint(\"\")\nprint(\"Eigenvector para lambda=5: {} (que es proporcional a {})\".format(vectors[:,1], eigen_5))\n\nprint(\"\")\nprint(\"Eigenvector para lambda=3: {} \".format(vectors[:,0]))\nbeta_a = vectors[1,0]*np.sqrt(5) # componente y\nbeta_b = vectors[2,0]*np.sqrt(10) # componente z\nprint(\"Combinacion lineal de dos vectores\\n\\t vec_a: {} y vec_b {}\".format(eigen_3_a, eigen_3_b))\nprint(\"\\t vec_3 = beta_a * vec_a + beta_b * vec_b: {}\".format((beta_a * eigen_3_a + beta_b * eigen_3_b)))\n\nprint(\"\")\nprint(\"Eigenvector para lambda=3: {} \".format(vectors[:,2]))\nbeta_a = vectors[1,2]*np.sqrt(5) # componente y\nbeta_b = vectors[2,2]*np.sqrt(10) # componente z\nprint(\"Combinacion lineal de dos vectores\\n\\t vec_a: {} y vec_b {}\".format(eigen_3_a, eigen_3_b))\nprint(\"\\t vec_3 = beta_a * vec_a + beta_b * vec_b: {}\".format((beta_a * eigen_3_a + beta_b * eigen_3_b)))\n\n\nprint(\"\")\nprint(\"Ejercicio 5\")\nn = 100\nA = np.zeros([n,n])\nb = np.ones(n)\nfor i in range(1,n+1):\n    b[i-1] = 1/i\n    for j in range(1,n+1):\n        A[i-1,j-1] = 1/(i+j-1)\nx = np.linalg.solve(A,b)\nprint(\"Solucion con todos los elementos igual a cero salvo el primero:\\n\\t {}\".format(x))\n", "meta": {"hexsha": "b31cd30e3fd58b95983d2a8b30d0f00d45022a5f", "size": 2827, "ext": "py", "lang": "Python", "max_stars_repo_path": "ejercicios/13/JaimeForero_Ejercicio13.py", "max_stars_repo_name": "oscarochoa1/FISI2028-201910", "max_stars_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-03T04:27:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T18:50:41.000Z", "max_issues_repo_path": "ejercicios/13/JaimeForero_Ejercicio13.py", "max_issues_repo_name": "oscarochoa1/FISI2028-201910", "max_issues_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ejercicios/13/JaimeForero_Ejercicio13.py", "max_forks_repo_name": "oscarochoa1/FISI2028-201910", "max_forks_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-01-23T10:44:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-04T00:05:40.000Z", "avg_line_length": 30.3978494624, "max_line_length": 105, "alphanum_fraction": 0.6200919703, "include": true, "reason": "import numpy", "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639694252316, "lm_q2_score": 0.8902942275774318, "lm_q1q2_score": 0.8649777937015002}}
{"text": "import numpy as np\nimport pandas as pd\nimport scipy.stats as sp\n\n\nclass BlackScholes:\n    \"\"\"\n    Black-Scholes model for pricing European options.\n    \n    Notes\n    -----\n    Assumptions of the model:\n\n    - the volatility of the underlying asset is constant over time;\n    - the underlying asset price follows the log-normal distribution;\n    - the underlying assset can be traded continuously;\n    - no transaction costs or taxes;\n    - all securities are perfectly divisible;\n    - the risk-free rate is constant and the same for all maturities.\n\n    Price of the call option was calculated based on below formula:\n\n    .. math:: c = S_{0}N(d_{1}) - Ke^{-rT}N(d_{2}) \n\n    On the other hand, price of the put option was derived from the formula:\n\n    .. math:: p = Ke^{-rT}N(-d_{2}) - S_{0}N(-d_{1}),\n\n    where:\n\n    .. math:: d_{1} = \\\\frac{ ln(S_{0}/K) + (r + \\\\sigma^{2}/2)T }{ \\\\sigma \\\\sqrt{T} } \\\\\n        d_{2} = \\\\frac{ ln(S_{0}/K) + (r - \\\\sigma^{2}/2)T }{ \\\\sigma \\\\sqrt{T} } = d_{1} - \\\\sigma \\\\sqrt{T}\n\n    \"\"\"\n\n    def __init__(self, S: float, K: float, r: float, q: float=0, T: float, sigma: float, type: str) -> None:\n        \"\"\"\n        Class initializer. \n\n        Parameters\n        ----------\n        S : float\n            Price of the underlying.\n        K : float\n            Strike price.\n        r : float\n            Risk free rate.\n        q : float\n            Dividend rate.\n        T : float\n            Time to expiry (in years).\n        sigma : float\n            Underlying volatility.\n        type : str\n            Option type: \"put\" or \"call\".\n        \"\"\"    \n        self.S = S\n        self.K = K\n        self.r = r\n        self.q = q\n        self.T = T\n        self.sigma = sigma\n        self.type = type\n\n\n    def d1(self) -> float:\n        \"\"\"\n        Calculates d1 from the class description.\n\n        Returns\n        -------\n        float\n            d1 value\n        \"\"\"    \n        return (np.log(self.S/self.K) + (self.r + (self.sigma**2)/2)*self.T) / (self.sigma*np.sqrt(self.T)) \n\n\n    def d2(self) -> float:\n        \"\"\"\n        Calculates d2 from the class description.\n\n        Returns\n        -------\n        float\n            d2 value\n        \"\"\"        \n        return self.d1() - self.sigma*np.sqrt(self.T)\n\n\n    def price(self) -> float:\n        \"\"\"\n        Runs Black-Scholes calculation.\n\n        Returns\n        -------\n        float\n            Option price\n        \"\"\"        \n        if self.type == 'call':\n            return self.S*sp.norm.cdf(self.d1()) - self.K*np.exp(-self.r*self.T)*sp.norm.cdf(self.d2())\n        \n        elif self.type == 'put':\n            return self.K*np.exp(-self.r*self.T)*sp.norm.cdf(-self.d2()) - self.S*sp.norm.cdf(-self.d1())\n\n        else:\n            raise ValueError(\"Option price type can only be call or put\")", "meta": {"hexsha": "445e523dcbc076e94ba0916ccfb0da72e52aebe3", "size": 2811, "ext": "py", "lang": "Python", "max_stars_repo_path": "black_scholes.py", "max_stars_repo_name": "robsoc/quant_models", "max_stars_repo_head_hexsha": "28f145077b2cb53faba5b3faec53413d0dd42601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-25T22:06:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T22:06:55.000Z", "max_issues_repo_path": "black_scholes.py", "max_issues_repo_name": "robsoc/quant_models", "max_issues_repo_head_hexsha": "28f145077b2cb53faba5b3faec53413d0dd42601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "black_scholes.py", "max_forks_repo_name": "robsoc/quant_models", "max_forks_repo_head_hexsha": "28f145077b2cb53faba5b3faec53413d0dd42601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5188679245, "max_line_length": 109, "alphanum_fraction": 0.5112059765, "include": true, "reason": "import numpy,import scipy", "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846703886661, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.864930484270838}}
{"text": "\"\"\"\nLagrange (Polynomial Interpolation)\n\"\"\"\n\nimport numpy as np\n\ndef L(i, X):\n    \"\"\"\n    This function returns l(x).\n\n    Parameters\n    ----------\n        i : int\n            Index of X.\n        X : list\n            List of x values.\n\n    Returns\n    -------\n        function\n            l(x) \n    \"\"\" \n    temp = X.copy()\n    xi = temp.pop(i)\n\n    def l(x):\n        return np.prod([(x - xj) / (xi - xj) for xj in temp])\n\n    return l\n\ndef lagrange(X, Y):\n    \"\"\"\n    Polynomial Interpolation using Lagrange method.\n    X and Y are data from `(x, f(x))`.\n\n    Parameters\n    ----------\n        X : list\n            list of x values.\n        Y : list\n            list of y values.\n\n    Returns \n    -------\n        function\n            Lagrange Polynomial from `X` and `Y` values.            \n    \"\"\"\n    def f(x):\n        return sum([yi * L(i, X)(x) for i, yi in enumerate(Y)])\n\n    return f", "meta": {"hexsha": "e5d8ef3b506bfa9c0a8b6e660d8aad40489cf248", "size": 893, "ext": "py", "lang": "Python", "max_stars_repo_path": "interpolation/methods/lagrange.py", "max_stars_repo_name": "JNagasava/Polynomial-Interpolation", "max_stars_repo_head_hexsha": "0061286afcdefe3fef55e9297227bb58fed5ae77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "interpolation/methods/lagrange.py", "max_issues_repo_name": "JNagasava/Polynomial-Interpolation", "max_issues_repo_head_hexsha": "0061286afcdefe3fef55e9297227bb58fed5ae77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interpolation/methods/lagrange.py", "max_forks_repo_name": "JNagasava/Polynomial-Interpolation", "max_forks_repo_head_hexsha": "0061286afcdefe3fef55e9297227bb58fed5ae77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5098039216, "max_line_length": 68, "alphanum_fraction": 0.4524076148, "include": true, "reason": "import numpy", "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846703886662, "lm_q2_score": 0.8840392771633078, "lm_q1q2_score": 0.8649304767980576}}
{"text": "\n\"\"\" Example showing how to compute a family of basis polynomials \"\"\"\n\n\n# -------------------------------------------------------------------------------------------------------------------- #\n# Importing packages\n# -------------------------------------------------------------------------------------------------------------------- #\nimport numpy as np\nimport nurbspy as nrb\nimport matplotlib.pyplot as plt\n\n\n# -------------------------------------------------------------------------------------------------------------------- #\n# Basis polynomials and derivatives example\n# -------------------------------------------------------------------------------------------------------------------- #\n# Maximum index of the basis polynomials (counting from zero)\nn = 4\n\n# Define the order of the basis polynomials\np = 3\n\n# Define the knot vector (clamped spline)\n# p+1 zeros, n-p equispaced points between 0 and 1, and p+1 ones. In total r+1 points where r=n+p+1\nU = np.concatenate((np.zeros(p), np.linspace(0, 1, n - p + 2), np.ones(p)))\n\n# Define a new u-parametrization suitable for finite differences\nh = 1e-5\nhh = h + h**2\nNu = 1000\nu = np.linspace(0.00 + hh, 1.00 - hh, Nu)       # Make sure that the limits [0, 1] also work when making changes\n\n# Compute the basis polynomials and derivatives\nN_basis   = nrb.compute_basis_polynomials(n, p, U, u)\ndN_basis  = nrb.compute_basis_polynomials_derivatives(n, p, U, u, derivative_order=1)\nddN_basis = nrb.compute_basis_polynomials_derivatives(n, p, U, u, derivative_order=2)\n\n\n# -------------------------------------------------------------------------------------------------------------------- #\n# Plot the basis polynomials\n# -------------------------------------------------------------------------------------------------------------------- #\n# Create the figure\nfig = plt.figure(figsize=(15, 5))\n\n# Plot the basis polynomials\nax1 = fig.add_subplot(131)\nax1.set_title('Zeroth derivative', fontsize=12, color='k', pad=12)\nax1.set_xlabel('$u$ parameter', fontsize=12, color='k', labelpad=12)\nax1.set_ylabel('Function value', fontsize=12, color='k', labelpad=12)\nfor i in range(n+1):\n    line, = ax1.plot(u, N_basis[i, :])\n    line.set_linewidth(1.25)\n    line.set_linestyle(\"-\")\n    # line.set_color(\"k\")\n    line.set_marker(\" \")\n    line.set_markersize(3.5)\n    line.set_markeredgewidth(1)\n    line.set_markeredgecolor(\"k\")\n    line.set_markerfacecolor(\"w\")\n    line.set_label('index ' + str(i))\n\n\n# Plot the first derivative\nax2 = fig.add_subplot(132)\nax2.set_title('First derivative', fontsize=12, color='k', pad=12)\nax2.set_xlabel('$u$ parameter', fontsize=12, color='k', labelpad=12)\nax2.set_ylabel('Function value', fontsize=12, color='k', labelpad=12)\nfor i in range(n+1):\n    line, = ax2.plot(u, dN_basis[i, :])\n    line.set_linewidth(1.25)\n    line.set_linestyle(\"-\")\n    # line.set_color(\"k\")\n    line.set_marker(\" \")\n    line.set_markersize(3.5)\n    line.set_markeredgewidth(1)\n    line.set_markeredgecolor(\"k\")\n    line.set_markerfacecolor(\"w\")\n    line.set_label('index ' + str(i))\n\n\n# Plot the second derivative\nax3 = fig.add_subplot(133)\nax3.set_title('Second derivative', fontsize=12, color='k', pad=12)\nax3.set_xlabel('$u$ parameter', fontsize=12, color='k', labelpad=12)\nax3.set_ylabel('Function value', fontsize=12, color='k', labelpad=12)\nfor i in range(n+1):\n    line, = ax3.plot(u, ddN_basis[i, :])\n    line.set_linewidth(1.25)\n    line.set_linestyle(\"-\")\n    # line.set_color(\"k\")\n    line.set_marker(\" \")\n    line.set_markersize(3.5)\n    line.set_markeredgewidth(1)\n    line.set_markeredgecolor(\"k\")\n    line.set_markerfacecolor(\"w\")\n    line.set_label('index ' + str(i))\n\n\n# Create legend\nax3.legend(ncol=1, loc='right', bbox_to_anchor=(1.60, 0.50), fontsize=10, edgecolor='k', framealpha=1.0)\n\n# Adjust pad\nplt.tight_layout(pad=5.0, w_pad=None, h_pad=None)\n\n# Show the figure\nplt.show()\n\n\n\n# # -------------------------------------------------------------------------------------------------------------------- #\n# # Check that the computations are correct\n# # -------------------------------------------------------------------------------------------------------------------- #\n# # Check that the sum of the basis polynomials is equal to one (partition of unity property)\n# print('The two-norm of partition of unity error is     :  ', np.sum((np.sum(N_basis, axis=0) - 1.00) ** 2) ** (1 / 2))\n#\n# # Check the first derivative against a finite difference aproximation\n# a = -1/2*compute_basis_polynomials(n, p, U, u - h)\n# b = +1/2*compute_basis_polynomials(n, p, U, u + h)\n# dN_fd = (a+b)/h\n# print('The two-norm of the first derivative error is   :  ', np.sum((dN_basis-dN_fd)**2)**(1/2)/Nu)\n#\n# # Check the second derivative against a finite difference aproximation\n# a = +1*compute_basis_polynomials(n, p, U, u - h)\n# b = -2*compute_basis_polynomials(n, p, U, u)\n# c = +1*compute_basis_polynomials(n, p, U, u + h)\n# ddN_fd = (a+b+c)/h**2\n# print('The two-norm of the second derivative error is  :  ', np.sum((ddN_basis-ddN_fd)**2)**(1/2)/Nu)\n", "meta": {"hexsha": "07b0b569e4ad0514164e72c93ccbff227526ad22", "size": 5022, "ext": "py", "lang": "Python", "max_stars_repo_path": "demos/demos_basis_polynomials/demo_basis_polynomials.py", "max_stars_repo_name": "dragonbook/nurbspy", "max_stars_repo_head_hexsha": "08640cdb243f4cf72ae66f37e715afa14e70f455", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2020-03-11T19:21:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T02:21:11.000Z", "max_issues_repo_path": "demos/demos_basis_polynomials/demo_basis_polynomials.py", "max_issues_repo_name": "dragonbook/nurbspy", "max_issues_repo_head_hexsha": "08640cdb243f4cf72ae66f37e715afa14e70f455", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-08-12T10:56:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T17:26:57.000Z", "max_forks_repo_path": "demos/demos_basis_polynomials/demo_basis_polynomials.py", "max_forks_repo_name": "dragonbook/nurbspy", "max_forks_repo_head_hexsha": "08640cdb243f4cf72ae66f37e715afa14e70f455", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-03-27T07:01:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T01:19:01.000Z", "avg_line_length": 39.5433070866, "max_line_length": 122, "alphanum_fraction": 0.5559538033, "include": true, "reason": "import numpy", "num_tokens": 1290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190132, "lm_q2_score": 0.9073122144683576, "lm_q1q2_score": 0.8649180863775572}}
{"text": "import numpy as np\n\ndef createSquare(size):\n    \"\"\"Creates an N x N magic square\n    \n    In a magic square, every row, column, and diagonal add up to the same number.\n    \n    @param size The size of the magic square\n    @return A boolean representing if the square was created or not\n    \"\"\"\n    \n    # The size must be odd\n    if size % 2 == 0:\n        print('Size must be odd')\n        return False\n\n    # Initialize with zeros\n    magic_square = np.zeros((size,size), dtype=int)\n\n    n = 1\n    i, j = 0, size//2\n\n    while n <= size**2:\n        magic_square[i, j] = n\n        n += 1\n        newi, newj = (i - 1) % size, (j + 1) % size\n        if magic_square[newi, newj]:\n            i += 1\n        else:\n            i, j = newi, newj\n\n    print(magic_square)\n    return True\n\ndef runTests():\n    # Test cases\n    assert createSquare(3) is True\n    assert createSquare(5) is True\n    assert createSquare(6) is False\n    assert createSquare(4) is False\n\nrunTests()\n", "meta": {"hexsha": "9118f6cafef59ca8e3ef4ce5566f4e188e3c31c7", "size": 969, "ext": "py", "lang": "Python", "max_stars_repo_path": "puzzles/Magic Square/Python/MagicSquare.py", "max_stars_repo_name": "bakuryuthem0/al-go-rithms", "max_stars_repo_head_hexsha": "8ad4b65a988740525585ecae2b6f0b815cdbcd66", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1253, "max_stars_repo_stars_event_min_datetime": "2017-06-06T07:19:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:07:58.000Z", "max_issues_repo_path": "puzzles/Magic Square/Python/MagicSquare.py", "max_issues_repo_name": "rishabh99-rc/al-go-rithms", "max_issues_repo_head_hexsha": "4df20d7ef7598fda4bc89101f9a99aac94cdd794", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 554, "max_issues_repo_issues_event_min_datetime": "2017-09-29T18:56:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T15:48:13.000Z", "max_forks_repo_path": "puzzles/Magic Square/Python/MagicSquare.py", "max_forks_repo_name": "rishabh99-rc/al-go-rithms", "max_forks_repo_head_hexsha": "4df20d7ef7598fda4bc89101f9a99aac94cdd794", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2226, "max_forks_repo_forks_event_min_datetime": "2017-09-29T19:59:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:59:55.000Z", "avg_line_length": 22.5348837209, "max_line_length": 81, "alphanum_fraction": 0.5779153767, "include": true, "reason": "import numpy", "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650673, "lm_q2_score": 0.9059898191142621, "lm_q1q2_score": 0.8649008405234799}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\nUsage: \npython polyarea.py c 1 2 4 8 3 5\npython polyarea.py f coord.txt\npython polyarea.py help\n\"\"\"\n\nimport sys\nimport numpy as np\n\ndef simpoly(x,y):\n    \"\"\"\n    A function that calculates the area of a 2-D simple polygon (no matter concave or convex)\n    Must name the vertices in sequence (i.e., clockwise or counterclockwise)\n    Inputs must be float type\n    Formula used: http://en.wikipedia.org/wiki/Polygon#Area_and_centroid\n    Definition of \"simply polygon\": http://en.wikipedia.org/wiki/Simple_polygon\n\n    Input x: x-axis coordinates of vertex array\n          y: y-axis coordinates of vertex array\n    Output: polygon area\n    \"\"\"\n\n    ind_arr = np.arange(len(x))-1  # for indexing convenience\n    s = 0\n    for ii in ind_arr:\n      s = s + (x[ii]*y[ii+1] - x[ii+1]*y[ii])\n\n    return abs(s)*0.5\n\nif __name__ == \"__main__\":\n    usage_str = 'Usage:\\npython polyarea.py c 1 2 4 8 3 5 \\npython polyarea.py f coord.txt\\npython polyarea.py help'\n\n    if len(sys.argv) == 1:\n        print \"Error: argument input needed\"\n        print usage_str\n        exit()\n\n    if sys.argv[1].lower() == 'c':\n        # Recognize the inputs as the coordinates \n        if len(sys.argv) <= 7:\n            print \"Error: at least three 2-D points needed for a valid polygon\"\n            print \"Exiting...\"\n            exit()\n        elif np.mod(len(sys.argv[2:]), 2) != 0:\n            print \"Error: the number of input arguments should be even\"\n            print \"Exiting...\"\n            exit()\n        else:\n            print \"This polygon has\", (len(sys.argv)-2)/2, \"vertices\"\n        \n        a = np.zeros(len(sys.argv)-2)  # the default a.dtype.name is float64\n\n        ind = 0\n        for coord in sys.argv[2:]:\n            a[ind]=float(eval(coord))  # convert the input arguments to \"float\" type\n            ind = ind+1\n\n        b = a.reshape(-1, 2).copy()\n        x = b[:,0].copy()   # get x coords\n        y = b[:,1].copy()   # get y coords\n\n        print \"The area of this polygon is\", simpoly(x,y)\n\n    elif sys.argv[1].lower() == 'f':\n        # Get the input from a file\n        # in which the 1st column is x coordinates, and the 2nd column is y coordinates\n        d = np.loadtxt(sys.argv[2])\n        x = d[:,0]\n        y = d[:,1]\n        print \"The area of this polygon is\", simpoly(x,y)\n\n    elif sys.argv[1].lower() == 'help':\n        print usage_str\n        exit()\n\n    else:\n        print \"Error need input arg either c (command line) or f (file)\"\n        print \"Exiting\"\n        exit()", "meta": {"hexsha": "44af4e7f1d6364eac8cbddf1f42f59f5acbb44cc", "size": 2518, "ext": "py", "lang": "Python", "max_stars_repo_path": "geometry/polyarea.py", "max_stars_repo_name": "lijunxyz/codedrop", "max_stars_repo_head_hexsha": "baf6151fdddc8e4b208bcc54f6cada612d5acd83", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geometry/polyarea.py", "max_issues_repo_name": "lijunxyz/codedrop", "max_issues_repo_head_hexsha": "baf6151fdddc8e4b208bcc54f6cada612d5acd83", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometry/polyarea.py", "max_forks_repo_name": "lijunxyz/codedrop", "max_forks_repo_head_hexsha": "baf6151fdddc8e4b208bcc54f6cada612d5acd83", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7073170732, "max_line_length": 116, "alphanum_fraction": 0.5810166799, "include": true, "reason": "import numpy", "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.946596665680527, "lm_q2_score": 0.913676521650809, "lm_q1q2_score": 0.8648831489052377}}
{"text": "import numpy\nfrom matplotlib import pyplot\n\ndef bisection(f, interval, max_steps=100, tol=1e-10):\n\n    x_lo, x_hi = interval\n    x = (x_lo + x_hi)/2\n    f_lo = f(x_lo)\n    f_hi = f(x_hi)\n    fx = f(x)\n    steps = 0\n    \n    while steps < max_steps and abs(fx) > tol and (x_hi - x_lo) > tol:\n        steps = steps + 1\n        if fx*f_hi < 0: # Root lies in right-hand half\n            x_lo = x\n            f_lo = fx\n        else: # Root lies in left-hand half\n            x_hi = x\n            f_hi = fx\n        x = (x_lo + x_hi) / 2\n        fx = f(x)\n    print(\"Nsteps\", steps)\n    return x\n    \nif __name__==\"__main__\":\n    def f(x):\n        return numpy.exp(x) + x - 2\n    def g(x):\n        return numpy.sin(x**2) - 0.1*x\n        \n    interval = [0,1]\n    s = bisection(f, interval)\n    print(\"s = \", s, \"f(s) = \", f(s))\n    \n    x = numpy.linspace(0, 10, 1000)\n    pyplot.plot(x, g(x))\n    pyplot.show()\n    s = bisection(g, [1,10])\n    print(\"s = \", s, \"g(s) = \", g(s))\n    s = bisection(g, [1,9])\n    print(\"s = \", s, \"g(s) = \", g(s))\n    s = bisection(g, [1,8.5])\n    print(\"s = \", s, \"g(s) = \", g(s))\n    s = bisection(g, [1,8])\n    print(\"s = \", s, \"g(s) = \", g(s))\n    ", "meta": {"hexsha": "2162e79bdb2dbdf2e765b7d29772d5a75cb51ce2", "size": 1177, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/tex/codes/lecture6.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Lectures/tex/codes/lecture6.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Lectures/tex/codes/lecture6.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 25.0425531915, "max_line_length": 70, "alphanum_fraction": 0.466440102, "include": true, "reason": "import numpy", "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833653, "lm_q2_score": 0.9086178919837706, "lm_q1q2_score": 0.8648799604848687}}
{"text": "from scipy import *\nfrom scipy import interpolate\nfrom scipy.interpolate import barycentric_interpolate as bi\nimport numpy as np\nimport pylab as pl #where we get graph function\nfrom scipy.optimize import curve_fit\nfrom polyFit import *\nfrom scipy import polyfit \n\nh=np.array([0.0,1.525,30.050,4.575,6.10,7.625,9.150])\np=np.array([1.0,0.8617,0.7385,0.6292,0.5328,0.4481,0.3741])\n\nz=np.arange(0,9.3,0.1) #gives points to evaluate a polynomial fit going through p and h\na=bi(h,p,2) #evaluates a polynomial going through the  points p(h) gives p at h=2\nprint a\n\nz=np.arange(0,9.3,0.1)\nb=bi(h,p,4)\nprint b\n\nz=np.arange(0,9.2,0.1)\nc=bi(h,p,8)\nprint c\n\nprint 'part b'\nf=interpolate.interp1d(h,p,kind='cubic') #creates a cubic function that fits the graph \n\nd=f(2) #uses interpolation function \nprint 'Density at 2km using cubic spline interpolation'\nprint d\n\ne=f(4) #uses interpolation function \nprint 'Density at 4km using cubic spline interpolation'\nprint e\n\nf=f(8) #uses interpolation function \nprint 'Density at 8km using cubic spline interpolation'\nprint f\n\nprint 'part c- getting errors'\nactualvalue=0.67\ne1= (b-actualvalue)/actualvalue \nprint e1\n\nactualvalue=0.67\ne2= (e-actualvalue)/actualvalue \nprint e2\n\n", "meta": {"hexsha": "6bfda7658a379cba019412e1c44c7583fdab7f47", "size": 1207, "ext": "py", "lang": "Python", "max_stars_repo_path": "ExamPrep/04 Curve Fitting & Interpolation/rp2.py", "max_stars_repo_name": "FHomewood/ScientificComputing", "max_stars_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_stars_repo_licenses": ["IJG"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ExamPrep/04 Curve Fitting & Interpolation/rp2.py", "max_issues_repo_name": "FHomewood/ScientificComputing", "max_issues_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_issues_repo_licenses": ["IJG"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ExamPrep/04 Curve Fitting & Interpolation/rp2.py", "max_forks_repo_name": "FHomewood/ScientificComputing", "max_forks_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_forks_repo_licenses": ["IJG"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6326530612, "max_line_length": 87, "alphanum_fraction": 0.7522783761, "include": true, "reason": "import numpy,from scipy", "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211590308921, "lm_q2_score": 0.8872045996818986, "lm_q1q2_score": 0.864865816159447}}
{"text": "import numpy as np\n\ndef rbf(x1, x2, gamma=1.):\n    \"\"\"\n    rbf kernel function\n    \n    Parameters\n    ------------\n    x1 : numpy array, (..., n)\n        the first input feature vector\n    x2 : numpy array, (..., n)\n        the second input feature vector\n    gamma : positive double, default: 1\n        gamma=0.5/sigma**2\n    \n    Returns\n    ---------\n    kernel : numpy array\n        output kernel\n    \"\"\"\n    return np.exp(-gamma*((x1-x2)**2).sum(axis=-1))\n\ndef linear(x1, x2):\n    \"\"\"\n    linear kernel function\n    \n    Parameters\n    ------------\n    x1 : numpy array, (..., n)\n        the first input feature vector\n    x2 : numpy array, (..., n)\n        the second input feature vector\n    \n    Returns\n    ---------\n    kernel : numpy array\n        output kernel\n    \"\"\"\n    return (x1*x2).sum(axis=-1)\n\ndef poly(x1, x2, degree=3, gamma=1., r=0.):\n    \"\"\"\n    polynomial kernel function\n    \n    Parameters\n    ------------\n    x1 : numpy array, (..., n)\n        the first input feature vector\n    x2 : numpy array, (..., n)\n        the second input feature vector\n    degree : positive double, default: 3\n        degree of the polynomial kernel function\n    gamma : positive double, default: 1\n        kernel coefficient\n     r : positive double, default: 0\n         independent term\n    \n    Returns\n    ---------\n    kernel : numpy array\n        output kernel\n    \"\"\"\n    return (gamma*(x1*x2).sum(axis=-1) + r)**degree", "meta": {"hexsha": "dd6f7c4726c87b7a44b9730c21696093aed10375", "size": 1433, "ext": "py", "lang": "Python", "max_stars_repo_path": "sharedcode/kernels.py", "max_stars_repo_name": "szqtc/MyMachineLearningNotes", "max_stars_repo_head_hexsha": "87fa278290d211fa9390dfdfb081acd90ceaeab9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sharedcode/kernels.py", "max_issues_repo_name": "szqtc/MyMachineLearningNotes", "max_issues_repo_head_hexsha": "87fa278290d211fa9390dfdfb081acd90ceaeab9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sharedcode/kernels.py", "max_forks_repo_name": "szqtc/MyMachineLearningNotes", "max_forks_repo_head_hexsha": "87fa278290d211fa9390dfdfb081acd90ceaeab9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.746031746, "max_line_length": 51, "alphanum_fraction": 0.5338450803, "include": true, "reason": "import numpy", "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211619568682, "lm_q2_score": 0.8872045907347108, "lm_q1q2_score": 0.8648658100334785}}
{"text": "import numpy as np\nimport submission as sub\nimport numpy.linalg as la\n\n# 1. Generate random camera matrix\n\nK = np.array([[1,0,100], [0,1,100], [0,0,1]])\nR, _,_ = la.svd(np.random.randn(3,3))\nif la.det(R) < 0: R = -R\nt = np.vstack((np.random.randn(2,1), 1))\n\nP = K @ np.hstack((R, t))\n\n# 2. Generate random 2D and 3D points\n\nN = 100\n\nX = np.random.randn(N,3)\nx = P @ np.hstack((X, np.ones((N,1)))).T\nx = x[:2,:].T / np.vstack((x[2,:], x[2,:])).T\n\n# 3. Test parameter estimation with clean points\n\nPc = sub.estimate_pose(x, X)\nKc, Rc, tc = sub.estimate_params(Pc)\n\nprint('Intrinsic Error with clean 2D points:', la.norm((Kc/Kc[-1,-1])-(K/K[-1,-1])))\nprint('Rotation Error with clean 2D points:', la.norm(R-Rc))\nprint('Translation Error with clean 2D points:', la.norm(t-tc))\n\n# 4. Test parameter estimation with noisy points\n\nx = x + np.random.rand(x.shape[0], x.shape[1])\nPn = sub.estimate_pose(x, X)\nKn, Rn, tn = sub.estimate_params(Pn)\n\nprint('Intrinsic Error with noisy 2D points:', la.norm((Kn/Kn[-1,-1])-(K/K[-1,-1])))\nprint('Rotation Error with noisy 2D points:', la.norm(R-Rn))\nprint('Translation Error with noisy 2D points:', la.norm(t-tn))\n", "meta": {"hexsha": "74866435ddec5526fbee4daf7dbfd0b03c6f0320", "size": 1148, "ext": "py", "lang": "Python", "max_stars_repo_path": "assgn3/python/test_params.py", "max_stars_repo_name": "gray0018/CMU-16-385-Spring2020", "max_stars_repo_head_hexsha": "466064cc6d0eab018e590f391919f30fe24a0357", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assgn3/python/test_params.py", "max_issues_repo_name": "gray0018/CMU-16-385-Spring2020", "max_issues_repo_head_hexsha": "466064cc6d0eab018e590f391919f30fe24a0357", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assgn3/python/test_params.py", "max_forks_repo_name": "gray0018/CMU-16-385-Spring2020", "max_forks_repo_head_hexsha": "466064cc6d0eab018e590f391919f30fe24a0357", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7, "max_line_length": 84, "alphanum_fraction": 0.6489547038, "include": true, "reason": "import numpy", "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97482115683641, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.8648658011296303}}
{"text": "import numpy as np\n\n\ndef MSE(y_true, y_pred):\n    \"\"\"\n        Mean Squared Error\n\n        parameters : \n        -> y_true, y_pred (numpy arrays)\n\n        returns :\n        -> scalar value of the loss\n    \"\"\"\n    return (np.square(y_true - y_pred)).mean()\n\n\ndef MAE(y_true, y_pred):\n    \"\"\"\n        Mean Absolute Error\n\n        parameters : \n        -> y_true, y_pred (numpy arrays)\n\n        returns :\n        -> scalar value of the loss\n    \"\"\"\n    return np.abs(y_true - y_pred).mean()\n\n\ndef CrossEntropyLoss(y_true, y_pred, epsilon=1e-10):\n    \"\"\"\n        Cross Entropy Loss\n\n        parameters : \n        -> y_true, y_pred, epsilon\n\n        returns :\n        -> scalar value of the loss\n    \"\"\"\n    predictions = np.clip(y_pred, epsilon, 1. - epsilon)\n    N = y_pred.shape[0]\n    ce_loss = -np.sum(np.sum(y_true * np.log(predictions + 1e-5)))/N\n    return ce_loss\n", "meta": {"hexsha": "542138174b891412469a311b5733fabf2b470ee4", "size": 867, "ext": "py", "lang": "Python", "max_stars_repo_path": "bnbML/Utils/LossFunctions.py", "max_stars_repo_name": "ArtistBanda/Bread-and-Butter_Machine-Learning", "max_stars_repo_head_hexsha": "8b9c5cedaf00db87838a6cacfcddadfcb9b8bdaa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-11-05T18:13:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T17:59:58.000Z", "max_issues_repo_path": "bnbML/Utils/LossFunctions.py", "max_issues_repo_name": "ArtistBanda/Bread-and-Butter_Machine-Learning", "max_issues_repo_head_hexsha": "8b9c5cedaf00db87838a6cacfcddadfcb9b8bdaa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bnbML/Utils/LossFunctions.py", "max_forks_repo_name": "ArtistBanda/Bread-and-Butter_Machine-Learning", "max_forks_repo_head_hexsha": "8b9c5cedaf00db87838a6cacfcddadfcb9b8bdaa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-27T08:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-09T08:43:59.000Z", "avg_line_length": 19.7045454545, "max_line_length": 68, "alphanum_fraction": 0.5559400231, "include": true, "reason": "import numpy", "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854111860906, "lm_q2_score": 0.8918110540642805, "lm_q1q2_score": 0.8648653497660291}}
{"text": "import numpy as np\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\n\n# define grid\np_grid = np.linspace(0, 1, num=20)\n\n# define prior\nprior = np.repeat(1, 20)\n\n# Other priors\n# prior[p_grid < 0.5] = 0\n# prior = np.exp(-5 * np.abs(p_grid - 0.5))\n\n# compute likelihood at each value in grid\nlikelihood = stats.binom.pmf(k=6, n=9, p=p_grid)\n\n# compute product of likelihood and prior\nunstd_posterior = likelihood * prior\n\n# standardize the posterior, so it sums to 1\nposterior = unstd_posterior / sum(unstd_posterior)\n\n# Show plot\nplt.plot(p_grid, posterior, '-o')\nplt.xlabel(\"Probability of water\")\nplt.ylabel(\"Posterior probability\")\nplt.title(\"20 points\")\nplt.show()\n", "meta": {"hexsha": "e0705d2c5a0846399e9a2f851bb643b6e3dd2b9e", "size": 678, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/chapters/ch02/ex02.03.py", "max_stars_repo_name": "evgenyneu/statistical_rethinking_cmdstanpy", "max_stars_repo_head_hexsha": "7abe9fe16b8530dba46f9dcd8c2d29eecded978c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/chapters/ch02/ex02.03.py", "max_issues_repo_name": "evgenyneu/statistical_rethinking_cmdstanpy", "max_issues_repo_head_hexsha": "7abe9fe16b8530dba46f9dcd8c2d29eecded978c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/chapters/ch02/ex02.03.py", "max_forks_repo_name": "evgenyneu/statistical_rethinking_cmdstanpy", "max_forks_repo_head_hexsha": "7abe9fe16b8530dba46f9dcd8c2d29eecded978c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6, "max_line_length": 50, "alphanum_fraction": 0.7256637168, "include": true, "reason": "import numpy,import scipy", "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854103128328, "lm_q2_score": 0.8918110504699678, "lm_q1q2_score": 0.8648653455015362}}
{"text": "\"\"\"\n\nhttps://en.wikipedia.org/wiki/Companion_matrix\nhttp://et.engr.iupui.edu/~skoskie/ECE602/LNotes/A_Companion_Matrix.pdf\n\n\"\"\"\n\nimport numpy as np\nfrom sympy import *\nfrom sympy.abc import *\nfrom sympy.solvers import solve\n\n\"\"\"\n\nA companion matrix is of the form\nC(p) = [0 0 ... 0 -a0   ]\n       [1 0 ... 0 -a1   ]\n       [0 1 ... 0 -a2   ]\n       [    ...         ]\n       [0 0 ... 1 -a[n-1]]\n\nwhere the coefficients a0 .. a[n-1] are from a monic polynomial\nc0 + c1*t + c2*t^2 + ... c[n-1]*t^(n-1) + t^n\n\n\"\"\"\n\ndef gen_companion_matrix(n):\n    A = [[0 for i in range(n)] for j in range(n)]\n    for i in range(n-1):\n        A[i+1][i] = 1\n    for i in range(n):\n        A[i][n-1] = -1 * Symbol('a{}'.format(i))\n    return Matrix(A)\n\n\"\"\"\n\ndet(lambda*I - A) or det(lambda*I - transpose(A))\ngives rise to the monic polynomial\nc0 + c1*x + c2*x^2 ... c[n-1]*x^(n-1) + x^n\nwhere lambda gets substituted to be x\n\n\"\"\"\n\ndef test_monic_polynomial_property(n):\n    l = Symbol('x')\n    A = gen_companion_matrix(n)\n    I = Matrix(np.identity(n))\n    p = expand(simplify(det(l*I - A)))\n    q = expand(simplify(det(l*I - A.T)))\n    print(\"Order {}\".format(n))\n    pprint(p)\n    pprint(q)\n    print()\n\ndef test_power(n, m):\n    l = Symbol('x')\n    A = gen_companion_matrix(n)\n    I = Matrix(np.identity(n))\n    p = expand(simplify(det(l*I - A)))\n    for i in range(m):\n        print(\"Power {}x{} {}\".format(n, n, i))\n        pprint(A**i)\n\n\"\"\"\n\nThe inverse of a companion matrix is in the form of\nC(p)^-1 = [-a1/a0     1 0 ... 0\n           -a2/a0     0 1 ... 0\n           -a3/a0     0 0 ... 0\n            ...\n           -a[n-1]/a0 0 0 ... 1\n           -1/a0]     0 0 ... 0]\n\"\"\"\ndef test_inverse(n):\n    l = Symbol('x')\n    A = gen_companion_matrix(n)\n    pprint(A)\n    pprint(A.inv())\n    pprint(A.T)\n    pprint(A.T.inv())\n\n\ninit_printing()\nprint(\"Monic Polynomial Property\")\nfor i in range(10):\n    test_monic_polynomial_property(i)\nprint()\n\nprint(\"Power\")\nfor i in range(10):\n    test_power(i, 5)\nprint()\n\nprint(\"Inverse\")\nfor i in range(10):\n    test_inverse(i)\n", "meta": {"hexsha": "7fb9b0745673203fcec4f6e5015070af1d669e90", "size": 2047, "ext": "py", "lang": "Python", "max_stars_repo_path": "math/companion-matrix.py", "max_stars_repo_name": "qeedquan/misc_utilities", "max_stars_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-10-17T18:17:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:02:53.000Z", "max_issues_repo_path": "math/companion-matrix.py", "max_issues_repo_name": "qeedquan/misc_utilities", "max_issues_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/companion-matrix.py", "max_forks_repo_name": "qeedquan/misc_utilities", "max_forks_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:52:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:10:59.000Z", "avg_line_length": 21.1030927835, "max_line_length": 70, "alphanum_fraction": 0.5486077186, "include": true, "reason": "import numpy,from sympy", "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361159764527, "lm_q2_score": 0.9005297961287784, "lm_q1q2_score": 0.8648338394127466}}
{"text": "# normalize.py\n\nimport numpy as np \nfrom math import sqrt\nfrom sklearn.preprocessing import minmax_scale\n\ndef normalize_l2 (x):\n    \"\"\" Rerturns a normalized copy of\n    an array x. Uses L2 vector norm \n    for normalization. \n    \"\"\"\n    l2 = sqrt(sum(i**2 for i in x))\n    return [i/l2 for i in x]\n\ndef de_normalize_l2 (x_norm, x):\n    \"\"\" Transforms a normalized vector\n    back to its un-normalized form. \n    \"\"\"\n    l2 = sqrt(sum(i**2 for i in x))\n    return [i*l2 for i in x_norm]\n\ndef max_scaling(x):\n    \"\"\" Scaling the values of an array x\n    with respect to the maximum value of x.\n    \"\"\"\n    return [i/max(x) for i in x]\n\ndef normalize_minmax(x, min_r, max_r):\n    \"\"\" Normalizing and scaling given data\n    in an array x to the range of min_r \n    to max_r.\n    \"\"\"\n    x_s = [(i - min(x))/(max(x) - min(x)) for i in x]\n    return [i * (max_r - min_r) + min_r for i in x_s]\n\ndef de_normalize_minmax(x_scale, x, min_r, max_r):\n    \"\"\" Transforms a min-max normalized and \n    scaled vector back to its un-normalized\n    form.\n    \"\"\"\n    x_t = [((i - min_r)/(max_r - min_r)) for i in x_scale]\n    x_inv = [(i*(max(x) - min(x)) + min(x)) for i in x_t]\n    return x_inv\n\n# Test data\nx = [2000, 2001, 2003]\n\n# Exampels:\n# L2 normalization\nprint(normalize_l2(x))\nprint(de_normalize_l2(normalize_l2(x), x))\n\n# Max scaling\nprint(max_scaling(x))\n\n# Min-Max scaling\nprint(normalize_minmax(x, 0, 10))\nprint(de_normalize_minmax(normalize_minmax(x, 0, 10), x, 0, 10))\n\n# sklearn data scaling\nprint(minmax_scale(x, feature_range=(0, 1), axis=0, copy=False))\n", "meta": {"hexsha": "2cee2a5abc3b3f825f71c9c75fb03001a73be066", "size": 1560, "ext": "py", "lang": "Python", "max_stars_repo_path": "normalize.py", "max_stars_repo_name": "JoshuaSimon/Vorausberechnung-Studierende-in-Bayern", "max_stars_repo_head_hexsha": "666d50b6f082a571ab84049fe2e11bff8576e200", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-08T16:23:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-08T16:23:15.000Z", "max_issues_repo_path": "normalize.py", "max_issues_repo_name": "JoshuaSimon/Vorausberechnung-Studierende-in-Bayern", "max_issues_repo_head_hexsha": "666d50b6f082a571ab84049fe2e11bff8576e200", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "normalize.py", "max_forks_repo_name": "JoshuaSimon/Vorausberechnung-Studierende-in-Bayern", "max_forks_repo_head_hexsha": "666d50b6f082a571ab84049fe2e11bff8576e200", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1612903226, "max_line_length": 64, "alphanum_fraction": 0.6448717949, "include": true, "reason": "import numpy", "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611597645271, "lm_q2_score": 0.9005297847831082, "lm_q1q2_score": 0.8648338285168058}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport scipy.interpolate as si\r\nplt.style.use('seaborn-whitegrid')\r\n\r\n\r\ndef f(x) :\r\n    \r\n    s = 1/(1+25*np.power(x,2))\r\n    \r\n    return s\r\n\r\n\r\n\r\ndef Lagrance(n) :\r\n    \r\n    \r\n    x_nodes=np.linspace(-1,1,n)\r\n    y_val=f(x_nodes)\r\n    polynomial = si.lagrange(x_nodes, y_val) \r\n    \r\n    \r\n    \r\n    return polynomial,x_nodes,y_val\r\n\r\n\r\n#----------- Main Programme --------------------#\r\n\r\n\r\nn=10\r\nx=np.linspace(-1,1,100)\r\npolynomial,x_nodes,y_val = Lagrance(n)\r\n\r\nplt.plot(x,f(x),'lime')\r\ny=polynomial(x)\r\nplt.plot(x_nodes,y_val,'+')\r\nplt.plot(x,y,'green')\r\nplt.xlabel('x')\r\nplt.ylabel('y')\r\nplt.xlim(-1,1)\r\nplt.legend(['f(x)','Points','Lagrance'])\r\nplt.show()", "meta": {"hexsha": "148f062de645ac5dc5d734d733e37d21bd49d6df", "size": 717, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lagrance.py", "max_stars_repo_name": "Michaellianeris/NSODE-Algorithms", "max_stars_repo_head_hexsha": "40788cc7b4fc889a2b0dfe72e88b0e417cafa001", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lagrance.py", "max_issues_repo_name": "Michaellianeris/NSODE-Algorithms", "max_issues_repo_head_hexsha": "40788cc7b4fc889a2b0dfe72e88b0e417cafa001", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lagrance.py", "max_forks_repo_name": "Michaellianeris/NSODE-Algorithms", "max_forks_repo_head_hexsha": "40788cc7b4fc889a2b0dfe72e88b0e417cafa001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0714285714, "max_line_length": 50, "alphanum_fraction": 0.570432357, "include": true, "reason": "import numpy,import scipy", "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.9046505447409666, "lm_q1q2_score": 0.8648290468946245}}
{"text": "import numpy as np\nimport  matplotlib.pyplot as plt\n\ndef factorial(n):\n    if n == 0:\n        return 1\n    else:\n        fat = 1\n        for i in range(1, n+1):\n            fat = fat *i\n        \n        return  fat \n        \n\n#print(factorial(5))\n\n\ndef cos(x,n):\n    resul  = 0\n    for i in range(0,n+1):\n        resul += (-1)**i * x**(2*i)/factorial(2*i)\n    return resul\n\n\"\"\"\nx = int(raw_input(\"The value of x:\"))\nn = int(raw_input(\"The value of n:\"))\nprint(cos(x,n))\n\"\"\"\n\nNpoints = 100\ndtheta = (2.0*np.pi -0.0)/Npoints\nNterm = 10\n\ntheta = []\nctheta = []\n\nfor i in range(0, Npoints):\n    theta.append(i*dtheta)\n    ctheta.append(cos(i*dtheta, Nterm ))\n\nfig = plt.figure()\nax= plt.axes()\nax.plot(theta,ctheta, '.')\nax.plot(theta,np.cos(theta))\nax.grid()\nax.set_xlabel(r\"$\\theta$\", fontsize=14)\nplt.show()\n#plt.savefig('cos.png')\n\n\n", "meta": {"hexsha": "50854658d9a5d9ba8321d1705e68d840d0152815", "size": 833, "ext": "py", "lang": "Python", "max_stars_repo_path": "program01.py", "max_stars_repo_name": "andres-mestra/metodos_numericos", "max_stars_repo_head_hexsha": "03579168c64310eebd28d5aa835270a9f75312a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "program01.py", "max_issues_repo_name": "andres-mestra/metodos_numericos", "max_issues_repo_head_hexsha": "03579168c64310eebd28d5aa835270a9f75312a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "program01.py", "max_forks_repo_name": "andres-mestra/metodos_numericos", "max_forks_repo_head_hexsha": "03579168c64310eebd28d5aa835270a9f75312a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.3333333333, "max_line_length": 50, "alphanum_fraction": 0.5594237695, "include": true, "reason": "import numpy", "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813551535005, "lm_q2_score": 0.904650530602188, "lm_q1q2_score": 0.864829040185413}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nThis program models the LEGO \"Doodler\" Google it, and/or see:\n    https://www.us.lego.com/en-us/mindstorms/community/robot?projectid=73d4591f-e964-4533-85fe-b608d3eb6a83\nBriefly, a pen is at the end of a zig-zag expanding structure,\nthe left and right end points of the structure are connected to\nto gears so they each end point moves in a circle.\n\nExample: shown here is strucutre with n_zigzag = 3\n  (three lengths from end point to tip; the Lego project has n_zig = 7);\n  the length of each section in the diagram is L_zig = 3 (three \"/\"s)\n\n       tip where the pen is\n       /\\\n      /  \\\n    ./    \\.\n     \\    /\n      \\  /\n       \\/\n       /\\\n      /  \\\n     /    \\\n     L    R\n   end points\nThe end points are attached a distance \"radius\" from the centers of\ntheir gears, and the two gears centers are separated by 2*x_center distance.\n\"\"\"\n\n# use math functions from np\nimport numpy as np\n# and plotting from matplotlib\nimport matplotlib.pyplot as plt\n\n# parameters to set and adjust (see description above)\n# ============================\n# The mechanical setup:\nn_zigzag = 7     # Lego online version has 7\nL_zig = 7.0      # Lego design has spacong of 7 holes\nx_center = 5.0   # Lego design has x_center = 5\nradius = 1.58    # Lego design has radius = 1.58 = sqrt(1.5^2+0.5^2)\n# The number of rotations for each gear before stopping,\n# and the starting location (in rotations):\nrot_l = 49\nphi_l = -0.05\nrot_r = -25\nphi_r = -0.05\n# FYI, the Lego page uses (effectively, note sign change too):\n#    rot_l,'r = -49 & -50  (green in movie)\n#             =  49 & -25  (blue in movie)\n#    and Lego phi's look to be atan of 1/3 ~ 0.05 revs.\n# ============================\n\n\ndef xys_of_rotations(rot_l, rot_r):\n    \"\"\"\n    Calculate the location of the pen tip based on the\n    amount of rotation of the two gears.\n    \"\"\"\n    # convert rotations to radians (angle)\n    theta_l = 2.0 * np.pi * rot_r\n    theta_r = 2.0 * np.pi * rot_l\n    # locations of the ends of the zig-zag from the angles,\n    # note that they rotate in different directions\n    # *** simple sin and cos use ***\n    xl = -1.0 * (x_center + radius * np.cos(theta_l))\n    yl = radius * np.sin(theta_l)\n    xr = x_center + radius * np.cos(theta_r)\n    yr = radius * np.sin(theta_r)\n    # d is the half distance between the end points\n    # *** distance formula ***\n    d = np.sqrt((xr - xl)**2 + (yr - yl)**2) / 2.0\n    # calculate the location of the tip of the zig-zag,\n    # start at the midpoint of the two endpoints\n    # *** midpoint formula ***\n    xtip = (xl + xr) / 2.0\n    ytip = (yl + yr) / 2.0\n    # h is the extension distance of the zig-zag,\n    # the \"height\" or distance of the tip from the midpoint\n    # *** Pythagorean theorem ***\n    h = n_zigzag * np.sqrt(L_zig**2 - d**2)\n    # this distance is tilted from the vertical\n    # by a tilt angle which has trig ratios:\n    # *** simple trig, or similar triangles ***\n    sintilt = 0.5 * (yr - yl) / d\n    costilt = 0.5 * (xr - xl) / d\n    # add the x and y components of the tilted height to the midpoint;\n    # the x component of h is -h*sin(tilt)\n    xtip = xtip - h * sintilt\n    # the y component of h is hcos(tilt)\\\n    ytip = ytip + h * costilt\n    # return the locations of the end points and writing tip\n    # return (xl, yl, xr, yr, xtip, ytip)\n    # or just the writing tip\n    return (xtip, ytip)\n\n# Setup a list of points to fill\nxs = []\nys = []\n\n# setup an array of times, from 0 to 1\nTmax = 1.0\nts = np.linspace(0.0, Tmax, num=2000)\n\n# go through the times...\nfor t in ts:\n    # evaluate the function for raotations at time t\n    (xtip, ytip) = xys_of_rotations(rot_l * t + phi_l,\n                                    rot_r * t + phi_r)\n    xs.append(xtip)\n    ys.append(ytip)\n\n# Close the previous plot\nplt.close()\n\n# open a plot\nplt.figure(1, [12, 12], frameon=False)\n\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Doodler Output  [ rot_l = ' +\n          str(rot_l) + ',  rot_r = ' + str(rot_r) + ' ]')\n\n# set color to match Lego demo movie\nif rot_r == -25 and rot_l == 49:\n    plt.plot(xs, ys, '-b')\nelif rot_r == -50 and rot_l == -49:\n    plt.plot(xs, ys, '-g')\n# or use red for other custom values\nelse:\n    plt.plot(xs, ys, '-r')\n\nplt.show()\n", "meta": {"hexsha": "14fde55666bd15a371040fba1906791f41066269", "size": 4224, "ext": "py", "lang": "Python", "max_stars_repo_path": "doodler.py", "max_stars_repo_name": "dan3dewey/Pythonista-bagatelles", "max_stars_repo_head_hexsha": "8c2e1d061d76184490605e2a5d52fb236931cba7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doodler.py", "max_issues_repo_name": "dan3dewey/Pythonista-bagatelles", "max_issues_repo_head_hexsha": "8c2e1d061d76184490605e2a5d52fb236931cba7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doodler.py", "max_forks_repo_name": "dan3dewey/Pythonista-bagatelles", "max_forks_repo_head_hexsha": "8c2e1d061d76184490605e2a5d52fb236931cba7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7593984962, "max_line_length": 107, "alphanum_fraction": 0.6122159091, "include": true, "reason": "import numpy", "num_tokens": 1288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813476288299, "lm_q2_score": 0.9046505357435622, "lm_q1q2_score": 0.8648290382932736}}
{"text": "#\n# This program is distributed without any warranty and it\n# can be freely redistributed for research, classes or private studies,\n# since the copyright notices are not removed.\n#\n# This file contains a function to calculate matriz convolution\n#\n# Jadson Santos - jadsonjs@gmail.com\n#\n# http://www.scipy-lectures.org/advanced/image_processing/\n#\n# to run this exemple install pyhton modules:\n#\n# python3 -m pip install SciPy\n# python3 -m pip install numpy\n# python3 -m pip install matplotlib\n#\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom scipy import misc\nfrom scipy import ndimage\nfrom scipy import signal\n\n#7x7\nA = np.array(  [\n               [8, 5, 8, 1, 6, 8, 7],\n               [9, 9, 2, 8, 2, 7, 8],\n               [2, 9, 4, 9, 7, 3, 2],\n               [9, 2, 9, 7, 1, 9, 5],\n               [6, 9, 8, 7, 3, 1, 5],\n               [1, 9, 9, 7, 1, 4, 6],\n               [3, 5, 6, 4, 1, 4, 7] ] )\n#3x3\nB = np.array([ [3, 2, 2],\n               [1, 1, 3],\n               [3, 1, 2]\n               ])\n\n\n\nprint(\"--------------- Full --------------------\")\ncon1 = signal.convolve(A, B, mode='full', method='direct')\nprint(\" \")\nprint(con1)\n\ncon2 = signal.convolve(B, A, mode='full', method='direct')\nprint(\" \")\nprint(con2)\n\nprint(\"---------------Same-----------------\")\n\ncon3 = signal.convolve(A, B, mode='same', method='direct')\nprint(\" \")\nprint(con3)\n\ncon4 = signal.convolve(B, A, mode='same', method='direct')\nprint(\" \")\nprint(con4)\n\nprint(\"----------------My--------------------\")\n\n# calculate the convolution of a square matriz with hte mode \"same\"\ndef myconv2D( matrix, mask ):\n    matrixLen = len(matrix)\n    maskLen = len(mask)\n    border  = int(maskLen / 2);\n\n\n    # the result matrix will be a bigger in the full model\n    tempMatrix = np.zeros( (matrixLen+(border*2), matrixLen+(border*2)), dtype=int  )\n    convMatrix = np.zeros( (matrixLen, matrixLen), dtype=int  )\n\n    # copy data of original matrix to convMatrix\n    for i in range( matrixLen ):\n        for j in range( matrixLen ):\n            tempMatrix[i+1][j+1] = matrix[i][j]\n\n    convMatrixLen = len(convMatrix)\n\n    # the shift of the mask over the convMatrix\n    # the size of original matriz\n    #maxShift = matrixLen\n    shiftX = 0\n    shiftY = 0\n\n    for shiftI in range( matrixLen ):\n        for shiftJ in range( matrixLen ):\n\n            for i in range( maskLen ):\n                for j in range( maskLen ):\n                    convMatrix[shiftI][shiftJ] = convMatrix[shiftI][shiftJ] + ( tempMatrix[i+shiftI][j+shiftJ] * mask[i][j])\n\n    print(\" \")\n    print(convMatrix)\n\nmyconv2D(A, B)\nmyconv2D(B, A)\n", "meta": {"hexsha": "a59ac5f71dfbe6f4db04be5b29caaec519ccbe9a", "size": 2624, "ext": "py", "lang": "Python", "max_stars_repo_path": "image-processing/my_convolution2D.py", "max_stars_repo_name": "jadsonjs/DataScience", "max_stars_repo_head_hexsha": "61d09064d438fd7a910cbc2bd8f1107e27d5cd5c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "image-processing/my_convolution2D.py", "max_issues_repo_name": "jadsonjs/DataScience", "max_issues_repo_head_hexsha": "61d09064d438fd7a910cbc2bd8f1107e27d5cd5c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "image-processing/my_convolution2D.py", "max_forks_repo_name": "jadsonjs/DataScience", "max_forks_repo_head_hexsha": "61d09064d438fd7a910cbc2bd8f1107e27d5cd5c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9801980198, "max_line_length": 124, "alphanum_fraction": 0.5754573171, "include": true, "reason": "import numpy,from scipy", "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.9304582506732222, "lm_q1q2_score": 0.8648054958736794}}
{"text": "import numpy as np\ncalled = 0\n\ndef z_o_knapsack(W, wt, val, n):\n    global called\n    called += 1\n\n    if n == -1 or W == 0: # base case, 0 items or 0 weight left in knapsack\n        return 0\n\n    if W < wt[n]:\n        return z_o_knapsack(W, wt, val, n - 1) # if nth item too heavy, cannot be included\n\n    else:\n        return max(z_o_knapsack(W, wt, val, n - 1), # value with nth item excluded\n                    val[n] + z_o_knapsack(W - wt[n], wt, val, n - 1) # value with nth item included\n                )\n\ndef z_o_knapsack_memoized(W, wt, val, n, memo=None):\n    global called\n    called += 1\n\n    if memo == None:\n        memo = np.zeros((n+1, W+1))\n\n    if n == -1 or W == 0: # base case, 0 items or 0 weight left in knapsack\n        return 0\n\n    if memo[n, W] != 0:\n        return memo[n, W]\n\n    elif W < wt[n]:\n        mem_val = z_o_knapsack(W, wt, val, n - 1) if memo[n-1, W] == 0 else memo[n-1, W] # if nth item too heavy, cannot be included\n        memo[n,W] = mem_val\n        return mem_val\n\n    else:\n        mem_val = max(z_o_knapsack(W, wt, val, n - 1) if memo[n-1, W] == 0 else memo[n-1, W] == 0, # value with nth item excluded\n                    val[n] + z_o_knapsack(W - wt[n], wt, val, n - 1) \n                        if memo[n-1, W - wt[n]] == 0 else memo[n-1, W - wt[n]] # value with nth item included\n                )\n        memo[n, W] = mem_val\n        return mem_val\n\ndef z_o_knapsack_btm_up(W, wt, val, n):\n    global called\n    memo = np.zeros((n + 1, W + 1))\n\n    for i in range(1, n + 1):\n        for w in range(1, W + 1):\n            called += 1\n            if i == 0 or w == 0:\n                memo[i, w] = 0\n\n            elif wt[i - 1] > w:\n                memo[i, w] = memo[i - 1, w]\n            else:\n                memo[i, w] = max(memo[i - 1, w],\n                    val[i - 1] + memo[i - 1, w - wt[i - 1]]\n                    )\n\n    print(memo)\n    return memo[n, W]\n\n\nif __name__ == '__main__':\n    val = [1,4,5,7]\n    wt = [1,3,4,5]\n    W = 7\n\n    #print(z_o_knapsack_memoized(W, wt, val, len(val) - 1))\n    #print(z_o_knapsack(W, wt, val, len(val) - 1))\n    print(z_o_knapsack_btm_up(W, wt, val, len(val)))\n    print(called)", "meta": {"hexsha": "a2a3c3bc228af22c184993ac14990b208185ce8c", "size": 2174, "ext": "py", "lang": "Python", "max_stars_repo_path": "interview_questions/0_1_knapsack.py", "max_stars_repo_name": "rpg711/Interview-Prep", "max_stars_repo_head_hexsha": "2d12a11738d4c709bc593dcfdbf54d9f92141d61", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "interview_questions/0_1_knapsack.py", "max_issues_repo_name": "rpg711/Interview-Prep", "max_issues_repo_head_hexsha": "2d12a11738d4c709bc593dcfdbf54d9f92141d61", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interview_questions/0_1_knapsack.py", "max_forks_repo_name": "rpg711/Interview-Prep", "max_forks_repo_head_hexsha": "2d12a11738d4c709bc593dcfdbf54d9f92141d61", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3783783784, "max_line_length": 132, "alphanum_fraction": 0.495400184, "include": true, "reason": "import numpy", "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.9294404023468588, "lm_q1q2_score": 0.8648054881842027}}
{"text": "# Dimentionality Reduction\n\n## PCA\n\n### Maximum variance formulation\n\nconsider a dataset $\\{x_{i}\\}$ where $i=1,...,n$ and $x_{i} \\in \\mathbb{R}^{d}$.\n\nour goal is to project the data onto a space having dimensionality $k < d$ while maximizing the variance of the projected data. \n\nto begin with, consider the projection onto a one-dimensional space$(k=1)$.\n\nwe can define the direction of this space by a vector $u_{1} \\in \\mathbb{R}^{d}$, we can choose $u_{1}$ to be a unit vector so that $u_{1}^{T}u_{1} = 1$.\n\neach data point $x_{i}$ is then projected onto a scalar value $u_{1}^{T}x_{i}$, then mean of the projected data:\n\n$$\\frac{1}{n}\\sum_{i=1}^{n}u_{1}^{T}x_{i} = u_{1}^{T}\\overline{x}$$\n\nthe variance of the projected data:\n\n$$\\frac{1}{n}\\sum_{i=1}^{n}(u_{1}^{T}x_{i} - u_{1}^{T}\\overline{x})^{2} = \\frac{1}{n}\\sum_{i=1}^{n}u_{1}^{T}(x_{i} - \\overline{x})(x_{i} - \\overline{x})^{T}u_{1} = u_{1}^{T}Su_{1}$$\n\nwhere\n\n$$S = \\frac{1}{n}\\sum_{i=1}^{n}(x_{i} - \\overline{x})(x_{i} - \\overline{x})^{T}$$\n\nnow we can formalize our problem as:\n\n$$\\underset{u_{1}}{min}\\ -u_{1}^{T}Su_{1}$$\n$$s.t\\quad u_{1}^{T}u_{1} = 1$$\n\nthe lagrangian of this optimization problem:\n\n$$L(u_{1}, \\lambda_{1}) = -u_{1}^{T}Su_{1} + \\lambda_{1}(u_{1}^{T}u_{1} - 1)$$\n\nthe primal:\n\n$$\\underset{u_{1}}{min}\\ \\underset{\\lambda_{1}}{max}\\ L(u_{1}, \\lambda_{1})$$\n\nprimal satisfy the KKT conditions, so equivalent to dual:\n\n$$\\underset{\\lambda_{1}}{max}\\ \\underset{u_{1}}{min}\\ L(u_{1}, \\lambda_{1})$$\n\nsetting the derivative with respect to $u_{1}$ equal to zero, we have:\n\n$$Su_{1} = \\lambda_{1}{u_{1}}$$\n\nwhich say that $u_{1}$ must be a eigenvector of $S$, if we left-multiply by $u_{1}^{T}$ and make use of $u_{1}^{T}u_{1} = 1$, we get:\n\n$$u_{1}^{T}Su_{1} = \\lambda_{1}$$\n\nand so the variance will be a maximum when we set $u_{1}$ equal to the eigenvector having the largest eigenvalue $\\lambda_{1}$. this eigenvector is known as the first principal component.\n\nwe can define the additional principal components in an increamental fashion by choosing each new direction to be that which maximizes the projected variance amongst all possible directions orthogonal to those already considered.\n\nsecond principal component:\n\n$$\\underset{u_{2}}{min}\\ -u_{2}^{T}Su_{2}$$\n$$s.t\\quad u_{2}^{T}u_{2} = 1, u_{1}^{T}u_{2} = 0$$\n\nlike before, using lagrangian we derive:\n\n$$Su_{2} = \\lambda_{2}{u_{2}} + \\phi{u_{1}}$$\n\nleft multiply by $u_{1}^{T}$:\n\n$$u_{1}^{T}Su_{2} = \\lambda_{2}u_{1}^{T}{u_{2}} + \\phi{u_{1}^{T}}{u_{1}}$$\n\nanalyzing each component:\n\n$$u_{1}^{T}Su_{2} = u_{2}^{T}Su_{1} = u_{2}^{T}\\lambda_{1}u_{1} = \\lambda{u_{1}^{T}u_{2}} = 0$$\n$$u_{1}^{T}{u_{2}} = 0$$\n$${u_{1}^{T}}{u_{1}} = 1$$\n\nwe get:\n\n$$\\phi = 0$$\n\nback to zero derivative we have:\n\n$$Su_{2} = \\lambda_{2}{u_{2}}$$\n$$u_{2}^{T}Su_{2} = \\lambda_{2}$$\n\nso $\\lambda_{2}$ is the second largest eigenvalue of $S$.\n\nby induction, we can show that $i$-th principal component is the $i$-th largest eigenvector of $S$.\n\n### properties of non-negative definite symmetric real matrix\n\n$$S = \\frac{1}{n}\\sum_{i=1}^{n}(x_{i} - \\overline{x})(x_{i} - \\overline{x})^{T}$$ \n\nis of that kind.\n\n### Minimum-error formulation\n\na complete orthonormal basis vectors $u_{i}$ in $\\mathbb{R}^{d}$:\n\n$$u_{i}^{T}u_{j} = \\delta_{ij}$$\n\n$x_{k}$ coordinate with respect to $u_{i}$ is $x_{k}^{T}u_{i}$, so:\n\n$$x_{k} = \\sum_{i=1}^{d}(x_{k}^{T}u_{i})u_{i}$$\n\n$x_{k}$ can be approximated by the $m$-dimensional subspace representation plus a constant:\n\n$$\\tilde{x}_{k} = \\sum_{i=1}^{m}z_{ki}u_{i} + \\sum_{i=m+1}^{d}b_{i}u_{i}$$\n\nwhere $z_{ki}$ depend on the particular data point, whereas ${b_{i}}$ are constants that are the same for all data points.\n\nour goal is to minimize:\n\n$$J = \\frac{1}{n}\\sum_{k=1}^{d}\\left \\| x_{k} - \\tilde{x}_{k} \\right \\|^{2} $$\n\nsetting the derivative with respect to $z_{ni}$ to zero, and making use of the orthonormality conditions, we obtain:\n\n$$z_{ni} = x_{n}^{T}u_{i}$$\n\nsimilarly, we obtain:\n\n$$b_{i} = \\overline{x}^{T}u_{i}$$\n\nsubstitude for $z_{ni}$ and $b_{i}$, we obtain:\n\n$$x_{k} - \\tilde{x}_{k} = \\sum_{i=m+1}^{d}((x_{k} - \\overline{x}_{k})^{T}u_{i})u_{i}$$\n\nfinally our goal is to minimize:\n\n$$J = \\frac{1}{n}\\sum_{k=1}^{n}\\sum_{i=m+1}^{d}(x_{k} - \\overline{x}_{k})^{2} = \\sum_{i=m+1}^{d}u_{i}^{T}Su_{i}$$\n\nthis is similar to the maximum variance formulation in the opposite direction.\n\n### manual data\n\n\"\"\"construct dataset\"\"\"\nimport numpy as np\n\nm = 100\nw1, w2 = 0.1, 0.3\nnoise = 0.2\n\nX = np.empty((m, 3))\nX[:, :2] = np.random.multivariate_normal([0, 0], [[2, 1], [1, 5]], m)\nX[:, 2] = X[:, 0] * w1 + X[:, 1] * w2 + noise * np.random.randn(m)\n\nfrom sklearn.decomposition import PCA\n\npca = PCA(n_components=2)\nX2D = pca.fit_transform(X)\n\nX2D[: 5]\n\n\"\"\"sklearn actually uses SVD\"\"\"\nX_centered = X - X.mean(axis=0)\nU, s, Vt = np.linalg.svd(X_centered)\n\nX2D_SVD = X_centered.dot(Vt.T[:, :2])\nX2D_SVD[: 5]\n\n### mnist data\n\nfrom sklearn.datasets import fetch_openml\nfrom sklearn.model_selection import train_test_split\n\nmnist = fetch_openml('mnist_784', version=1, as_frame=False)\nmnist.target = mnist.target.astype(np.uint8)\n\nX = mnist[\"data\"]\ny = mnist[\"target\"]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y)\n\n\"\"\"\nset n_components (0.0, 1.0), indicating the ratio of variance you wish to preserve\nuse inverse_transform trying to inverse\n\"\"\"\npca = PCA(n_components=0.95)\nX_reduced = pca.fit_transform(X_train)\nX_mnist = pca.inverse_transform(X_reduced)\n\npca.explained_variance_ratio_[: 10]\n\n\"\"\"IncrementalPCA\"\"\"\nfrom sklearn.decomposition import IncrementalPCA\n\nn_batches = 100\ninc_pca = IncrementalPCA(n_components=154)\nfor X_batch in np.array_split(X_train, n_batches):\n    print(\".\", end=\"\")\n    inc_pca.partial_fit(X_batch)\n\nX_reduced = inc_pca.transform(X_train)\n\n### swiss roll\n\nfrom sklearn.datasets import make_swiss_roll\n\nX, t = make_swiss_roll(n_samples=1000, noise=0.2, random_state=42)\n\n\"\"\"kernel pca\"\"\"\nfrom sklearn.decomposition import KernelPCA\n\nrbf_pca = KernelPCA(n_components=2, kernel=\"rbf\", gamma=0.04)\nX_reduced = rbf_pca.fit_transform(X)\n\n## Locally Linear Embedding(LLE)\n\nLLE works by first measuring how each training instance linearly relates to it's colsest neighbors (c.n)\n\nthen looking for a low-dimensional representation of the training set where these local relationships are best preserved.\n\nLLE step one: linearly modeling local relationships:\n\n$$\n\\begin{equation}\n\\begin{split}\n\\hat{W} &= \\underset{W}{argmin}\\sum_{i=1}^{m}\\left(x^{(i)} - \\sum_{j=1}^{m}w_{ij}x^{(j)}\\right)^{2}\\\\\n\\mbox{s.t }\\ &1.w_{ij} = 0 \\mbox{ if } x^{(j)} \\mbox{ is not one of c.n of } x^{(i)} \\\\\n&2.\\sum_{i=1}^{m}w_{ij} = 1 \\mbox{ for all }j\n\\end{split}\n\\end{equation}\n$$\n\nLLE second step doing the reverse: keeping the weights fixed and finding the optimal position of the instances' image in low-dimensional space, suppose $x^{(i)}$'s low-dimensional image is $z^{(i)}$.\n\n$$\n\\begin{equation}\n\\begin{split}\n\\hat{Z} &= \\underset{Z}{argmin}\\sum_{i=1}^{m}\\left(z^{(i)} - \\sum_{j=1}^{m}w_{ij}z^{(j)}\\right)^{2}\\\\\n\\mbox{s.t }\\ &1.\\sum_{i=1}^{m}z^{(i)} = 0\\\\\n&2.\\sum_{i=1}^{m}(z^{(i)}z^{(i)})^{T} = mI_{d}\n\\end{split}\n\\end{equation}\n$$\n\nfrom sklearn.manifold import LocallyLinearEmbedding\n\nlle = LocallyLinearEmbedding(n_components=2, n_neighbors=10)\nX_reduced = lle.fit_transform(X)\n\n## Exercise\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.base import clone\n\nrnd_clf = RandomForestClassifier(n_estimators=1000, max_depth=4, n_jobs=-1, random_state=42)\nlow_clf = clone(rnd_clf)\n\nfrom datetime import datetime\nfrom sklearn.metrics import accuracy_score\n\npre_time = datetime.now()\nrnd_clf.fit(X_train, y_train)\nprint((datetime.now() - pre_time).seconds)\naccuracy_score(y_test, rnd_clf.predict(X_test))\n\npca = PCA(n_components=0.95)\nX_train_reduced = pca.fit_transform(X_train)\nX_test_reduced = pca.transform(X_test)\n\npre_time = datetime.now()\nlow_clf.fit(X_train_reduced, y_train)\nprint((datetime.now() - pre_time).seconds)\naccuracy_score(y_test, low_clf.predict(X_test_reduced))\n\nnp.random.seed(42)\n\nm = 10000\nidx = np.random.permutation(60000)[:m]\n\nX = mnist['data'][idx]\ny = mnist['target'][idx]\n\nfrom sklearn.manifold import TSNE\n\ntsne = TSNE(n_components=2, random_state=42)\nX_reduced = tsne.fit_transform(X)\n\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(13,10))\nplt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, cmap=\"jet\")\nplt.axis('off')\nplt.colorbar()\nplt.show()\n\n", "meta": {"hexsha": "1a1f118cc1253f1f393b41775c8d53d4e766a390", "size": 8365, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/12_dimentionality_reduction.py", "max_stars_repo_name": "newfacade/machine-learning-notes", "max_stars_repo_head_hexsha": "1e59fe7f9b21e16151654dee888ceccc726274d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/jupyter_execute/12_dimentionality_reduction.py", "max_issues_repo_name": "newfacade/machine-learning-notes", "max_issues_repo_head_hexsha": "1e59fe7f9b21e16151654dee888ceccc726274d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/12_dimentionality_reduction.py", "max_forks_repo_name": "newfacade/machine-learning-notes", "max_forks_repo_head_hexsha": "1e59fe7f9b21e16151654dee888ceccc726274d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2482517483, "max_line_length": 229, "alphanum_fraction": 0.6677824268, "include": true, "reason": "import numpy", "num_tokens": 2966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362855, "lm_q2_score": 0.9314625007846135, "lm_q1q2_score": 0.864777984960897}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n\"\"\"Rienmann Sum\"\"\"\r\n\r\n\r\ndef lowersum(f, a, b, n):\r\n    x = symbols('x')\r\n    area = 0\r\n    h = (b - a) / n\r\n    t = a\r\n    for i in range(n):\r\n        l = min(f.subs(x, t), f.subs(x, t + h))\r\n        area += l * h\r\n        t = t + h\r\n    return area\r\n\r\n\r\ndef uppersum(f, a, b, n):\r\n    x = symbols('x')\r\n    area = 0\r\n    h = (b - a) / n\r\n    t = a\r\n    for i in range(n):\r\n        l = max(f.subs(x, t), f.subs(x, t + h))\r\n        area += l * h\r\n        t = t + h\r\n    return area\r\n\r\n\r\ndef Rienmannsum(f, a, b):\r\n    e = 1\r\n    n = int(input(\"Initial number of divisions you want: \"))\r\n    while e > 10 ** -4:\r\n        L = lowersum(f, a, b, n)\r\n        U = uppersum(f, a, b, n)\r\n        e = U - L\r\n        n *= 10\r\n    return (U + L) / 2\r\n\r\n\r\n'''Simpsons Method of numerical integration'''\r\n\r\n\r\ndef simps(f,a,b,N=50):\r\n    '''\r\n    f : function\r\n        Vectorized function of a single variable\r\n    a , b : numbers\r\n        Interval of integration [a,b]\r\n    N : (even) integer\r\n        Number of subintervals of [a,b]\r\n    '''\r\n    if N % 2 == 1:\r\n        raise ValueError(\"N must be an even integer.\")\r\n    dx = (b-a)/N\r\n    x = np.linspace(a,b,N+1)\r\n    y = f(x)\r\n    S = dx/3 * np.sum(y[0:-1:2] + 4*y[1::2] + y[2::2])\r\n    return S\r\n\r\n'''Trapezoid Rule for numerical integration'''\r\n\r\ndef trapz(f,a,b,N=50):\r\n    '''\r\n    f : function\r\n        Vectorized function of a single variable\r\n    a , b : numbers\r\n        Interval of integration [a,b]\r\n    N : integer\r\n        Number of subintervals of [a,b]\r\n    '''\r\n    x = np.linspace(a,b,N+1)\r\n    y = f(x)\r\n    y_right = y[1:] # Right endpoints\r\n    y_left = y[:-1] # Left endpoints\r\n    dx = (b - a)/N\r\n    T = (dx/2) * np.sum(y_right + y_left)\r\n    return T\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "059a25440b5c84fa9064625d09e96f94ba588653", "size": 1783, "ext": "py", "lang": "Python", "max_stars_repo_path": "IDC101/Numerical_integration.py", "max_stars_repo_name": "dev-aditya/Mathematical-Python", "max_stars_repo_head_hexsha": "9adf4e14a0330f5fba10d74ba6105300c0dc522b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-19T12:03:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-19T12:03:00.000Z", "max_issues_repo_path": "IDC101/Numerical_integration.py", "max_issues_repo_name": "dev-aditya/Mathematical-Python", "max_issues_repo_head_hexsha": "9adf4e14a0330f5fba10d74ba6105300c0dc522b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IDC101/Numerical_integration.py", "max_forks_repo_name": "dev-aditya/Mathematical-Python", "max_forks_repo_head_hexsha": "9adf4e14a0330f5fba10d74ba6105300c0dc522b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7325581395, "max_line_length": 61, "alphanum_fraction": 0.4699943915, "include": true, "reason": "import numpy", "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964855157641556, "lm_q2_score": 0.8962513745192024, "lm_q1q2_score": 0.8647527612481863}}
{"text": "import numpy as np\n#from matplotlib import pyplot as plt\n\nh_0 = 5.32 # height of pivot point\n\nx_0 = 7.744 #x position of servo 1\ny_0 = 7.744 #y posiiton of servo 2\n\nl_1 = 2 # length of servo arm\nl_2 = 3.398 # length of linkage\n\nh_1_0 = 2.26 # height of servo axis\nh_2_0 = 2.26\n    \n# compute maximum tilt\nh_1 = h_1_0 + l_1 + l_2\ndh = h_1 - h_0\np_max = np.arctan(dh/x_0)\n\nh_1 = h_1_0 - l_1 + l_2\ndh = h_1 - h_0\np_min = np.arctan(dh/x_0)\n\n\ndef tilt2servo(phi, rad=True):\n    if not rad:\n        phi = np.deg2rad(phi)\n\n    if phi > p_max:\n        phi = p_max\n    elif phi < p_min:\n        phi = p_min\n\n    k = h_0 + x_0 * np.tan(phi) - h_1_0\n    t = np.arcsin((l_1**2-l_2**2+k**2)/(2*k*l_1))\n\n    if not rad:\n        t = np.rad2deg(t)\n    return t\n\nif __name__ == \"__main__\":\n    print tilt2servo(-15.0, rad=False)\n\n    #print np.rad2deg(p_min) # max theoretical tilt\n    #print np.rad2deg(p_max) # max theoretical tilt\n\n    #p = np.linspace(-p_min,p_max) # desired tilt angle\n    #t = tilt2servo(p) # desired servo angle\n    #plt.plot(p,t)\n    #plt.show()\n", "meta": {"hexsha": "04bbfcf57ae57eda627a2c700b261e2e7cafe2ab", "size": 1054, "ext": "py", "lang": "Python", "max_stars_repo_path": "tilt/get_angle.py", "max_stars_repo_name": "yycho0108/Elecanisms_Final", "max_stars_repo_head_hexsha": "5837e8481e2e224b250ac533d170ca3cf7fe2846", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tilt/get_angle.py", "max_issues_repo_name": "yycho0108/Elecanisms_Final", "max_issues_repo_head_hexsha": "5837e8481e2e224b250ac533d170ca3cf7fe2846", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tilt/get_angle.py", "max_forks_repo_name": "yycho0108/Elecanisms_Final", "max_forks_repo_head_hexsha": "5837e8481e2e224b250ac533d170ca3cf7fe2846", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6666666667, "max_line_length": 55, "alphanum_fraction": 0.6119544592, "include": true, "reason": "import numpy", "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9835969698879862, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.8647261012809259}}
{"text": "import scipy.stats\n\n\ndef get_z_critical(conf_level: float) -> float:\n    \"\"\"Gets z critical , which is z value corresponding to a specific\n    confidence level (for a two sided test)\n\n    Args:\n        conf_level (float): confidence level\n\n    Returns:\n        float: z critical value\n    \"\"\"\n    return scipy.stats.norm.ppf(1-(1-conf_level)/2)\n\n\ndef get_t_critical(conf_level: float, df: int) -> float:\n    \"\"\"Gets t critical , which is t value corresponding to a specific\n    confidence level (for a two sided test)\n\n    Args:\n        conf_level (float): confidence level\n        df (int): degrees of freedom\n\n    Returns:\n        float: t critical value\n    \"\"\"\n    return scipy.stats.t.ppf(1-(1-conf_level)/2, df)\n\n\ndef get_t_pvalue(t_value: float,\n                 df: int,\n                 alternative: str = \"two-sided\") -> float:\n    \"\"\"Get corresponding p value for t value depending on test type\n\n    Args:\n        t_value (float): t value\n        df (int): degrees of freedom\n        alternative (str, optional): two-sided/larger/smaller.\n                                     Defaults to \"two-sided\".\n\n    Raises:\n        ValueError: when the test type is invalid\n\n    Returns:\n        float: p value\n    \"\"\"\n\n    if alternative == \"two-sided\":\n        p_value = scipy.stats.t.sf(abs(t_value), df=df)*2\n    elif alternative == \"larger\":\n        p_value = scipy.stats.t.sf(t_value, df=df)\n    elif alternative == \"smaller\":\n        p_value = scipy.stats.t.cdf(t_value, df=df)\n    else:\n        raise ValueError(\"invalid alternative\")\n    return p_value\n\n\ndef get_norm_pvalue(z_value: float,\n                    alternative: str = \"two-sided\") -> float:\n    \"\"\"Get corresponding p value for z value depending on test type\n\n    Args:\n        z_value (float): z value\n        alternative (str, optional): two-sided/larger/smaller.\n                                     Defaults to \"two-sided\".\n\n    Raises:\n        ValueError: when the test type is invalid\n\n    Returns:\n        float: p value\n    \"\"\"\n\n    if alternative == \"two-sided\":\n        p_value = scipy.stats.norm.sf(abs(z_value))*2\n    elif alternative == \"larger\":\n        p_value = scipy.stats.norm.sf(z_value)\n    elif alternative == \"smaller\":\n        p_value = scipy.stats.norm.cdf(z_value)\n    else:\n        raise ValueError(\"invalid alternative\")\n    return p_value\n\n\ndef get_f_pvalue(f_value: float, dfg: int, dfe: int):\n    return scipy.stats.f.sf(f_value, dfg, dfe)\n", "meta": {"hexsha": "0f1d7889148fc2d48c80a65ea403b17260af0932", "size": 2442, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/classical/workout/utils.py", "max_stars_repo_name": "nazlysabbour1/stats-toolkit-python", "max_stars_repo_head_hexsha": "6046285f3930e29ca6f862f4b49fae23da3de7ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/classical/workout/utils.py", "max_issues_repo_name": "nazlysabbour1/stats-toolkit-python", "max_issues_repo_head_hexsha": "6046285f3930e29ca6f862f4b49fae23da3de7ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/classical/workout/utils.py", "max_forks_repo_name": "nazlysabbour1/stats-toolkit-python", "max_forks_repo_head_hexsha": "6046285f3930e29ca6f862f4b49fae23da3de7ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4382022472, "max_line_length": 69, "alphanum_fraction": 0.6060606061, "include": true, "reason": "import scipy", "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305328688783, "lm_q2_score": 0.8976952962128457, "lm_q1q2_score": 0.8646875185249849}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom plot_utils import plot_with_residual\n\n# this is based on https://www.youtube.com/watch?v=sDv4f4s2SB8\n\n# data set\nWeight = np.array([0.5 , 2.3 , 2.9]) # x\nHeight = np.array([1.4 , 1.9 , 3.2]) # y , _observed_height\n\n# Predicted Height = intercept + slope * Weight --> h\ndef predicted_height(intercept , slope):\n    return intercept + slope * Weight\n\ndef plot_dataset():\n    plt.plot(Weight, Height,'o')\n    plt.grid()\n    plt.title('data set')\n    plt.xlabel(\"Weight\")\n    plt.ylabel(\"Height\")\n    plt.show()\n\n# _predicted_height is h , _observed_height is y\ndef sum_of_square_residual(_predicted_height , _observed_height):\n    residual = _observed_height - _predicted_height\n    return np.dot(residual,residual) # sum the square\n\n\ndef show_ssr_graph_per_intercept(slope):\n    vec_intercept = np.arange(0,2,0.1)\n    vec_ssr = []\n    for intercept in vec_intercept:\n        _predicted_height = predicted_height(intercept,slope)\n        _observed_height = Height\n        ssr = sum_of_square_residual(_predicted_height,_observed_height)\n        vec_ssr.append(ssr)\n\n    index_min_ssr = np.argmin(vec_ssr)\n    ssr_min = vec_ssr[index_min_ssr]    \n    intercept_min = vec_intercept[index_min_ssr]  \n    plt.plot(vec_intercept,vec_ssr,'o',intercept_min,ssr_min,'ro')    \n    plt.title('cost ssr vs intercept for slope = {}'.format(slope))\n    plt.xlabel(\"intercept\")\n    plt.ylabel(\"ssr - sum of squre residual\")\n    plt.grid()\n    plt.show()\n\ndef compute_one_ssr(slope):\n    intercept = 0 # initial guess\n    _predicted_height = predicted_height(intercept,slope)\n    _observed_height = Height\n    ssr = sum_of_square_residual(_predicted_height,_observed_height)\n    print('ssr : ' , ssr)\n\n# ssr is the sum over (y[i])-h[i]))^2\n# d_ssr / d_intercept is equal by the chain rule to (d_ssr / d_h) * (d_h / d_intercept)\n# d_ssr / d_h -> sum over 2(y[i])-h[i]))*(-1)\n# d_h / d_intercept = d(intercept + slope * weight) / d_intercept --> 1 \n# so  d_ssr / d_intercept is equal to the sum over 2(y[i])-h[i]))*(-1)  but h = intercept + slope * weight so\n# d_ssr / d_intercept is equal to the sum over 2 ( y[i] - (intercept + slope * weight[i]))*(-1) or equivalently\n# d_ssr / d_intercept is equal to the sum over 2 ( observed_height[i] - (intercept + slope * weight[i]))(-1)\ndef d_ssr_to_d_intercept(slope,intercept):\n    _observed_height = Height\n    _predicted_height = intercept + slope * Weight\n    error = _observed_height - _predicted_height\n    return 2 * np.sum(error) *(-1)\n\n\n# ssr is the sum over (y[i])-h[i]))^2\n# d_ssr / d_slope is equal by the chain rule to (d_ssr / d_h) * (d_h / d_slope)\n# d_ssr / d_h -> sum over 2(y[i])-h[i]))*(-1)\n# d_h / d_slope = d(intercept + slope * weight) / d_slope --> weight \n# so  d_ssr / d_intercept is equal to the sum over 2(y[i])-h[i]))*(-1)*weight[i]  but h = intercept + slope * weight so\n# d_ssr / d_intercept is equal to the sum over 2 ( y[i] - (intercept + slope * weight[i]))*(-1)*weight[i] or equivalently\n# d_ssr / d_intercept is equal to the sum over 2 ( observed_height[i] - (intercept + slope * weight[i]))(-1)*weight[i]\ndef d_ssr_to_d_slope(slope,intercept):\n     _observed_height = Height\n     _predicted_height = intercept + slope * Weight\n     error = _observed_height - _predicted_height\n     # np.dot : mutliply element by element and than sum\n     return 2 * np.dot(error , Weight) *(-1)    \n\ndef print_d_ssr_to_d_intercept(slope):\n    # derivative become smaller\n    print(\"d_ssr/d_intercept @ intercept = 0 : \",d_ssr_to_d_intercept(slope,0))\n    print(\"d_ssr/d_intercept @ intercept = 0.5 : \",d_ssr_to_d_intercept(slope,0.5))\n    print(\"d_ssr/d_intercept @ intercept = 0.8 : \",d_ssr_to_d_intercept(slope,0.8))\n    print(\"d_ssr/d_intercept @ intercept = 0.9 : \",d_ssr_to_d_intercept(slope,0.9))\n    print(\"d_ssr/d_intercept @ intercept = 0.95 : \",d_ssr_to_d_intercept(slope,0.95))\n    print(\"d_ssr/d_intercept @ intercept = 1.05 : \",d_ssr_to_d_intercept(slope,1.05))\n\ndef gradient_descent_constant_slope(slope):\n    intercept = 0\n    learning_rate = 0.1\n    step_size = 1 # just a value to enter the loop\n    min_step_size = 0.001\n    iteration = 0\n    ssr_vec = []\n    intercept_vec = []\n\n    while abs(step_size) > min_step_size:\n        # ------------ this is the gradient descent engine\n        step_size = d_ssr_to_d_intercept(slope,intercept) * learning_rate\n        intercept = intercept - step_size # i did not see a proof for this\n\n        # ------------ below this is relevant to plot\n        intercept_vec.append(intercept)\n        _predicted_height = predicted_height(intercept,slope)\n        _observed_height = Height\n        iteration += 1\n        ssr = sum_of_square_residual(_predicted_height , _observed_height)\n        ssr_vec.append(ssr)\n\n        plot1(intercept_vec,ssr_vec,intercept,slope,ssr , iteration,step_size)\n\ndef plot1(intercept_vec,ssr_vec,intercept,slope,ssr , iteration,step_size):\n    fig, axs = plt.subplots(2)\n    fig.suptitle('Part 1')\n    plot_with_residual(axs[0],Weight,Height,intercept,slope)\n    axs[0].grid()\n    axs[0].set_title('data set vs intercpt  + slope * weight and residual\\nssr : {:.2f} , intercept : {:.2f} , iteration : {} , step : {:.4f}'.format(ssr , intercept , iteration,step_size))\n    axs[0].set_xlabel(\"Weight\")\n    axs[0].set_ylabel(\"Height\")\n    axs[1].plot(intercept_vec,ssr_vec,'o',intercept,ssr,'ro')\n    axs[1].set_title('gradient descent convergence , learn intercept . step size become smaller')\n    axs[1].set_xlabel(\"intercept\")\n    axs[1].set_ylabel(\"cost function - ssr\")\n    axs[1].grid()\n    plt.tight_layout()\n    plt.show()\n\ndef gradient_descent():\n    intercept = 0\n    slope = 1\n    learning_rate = 0.01 # using 0.1 will not due\n    step_size = 1 # just a value to enter the loop\n    min_step_size = 0.001\n    iteration = 0\n    ssr_vec = []\n\n    while step_size > min_step_size:\n        # ------------ this is the gradient descent engine\n        step_size_intercept = d_ssr_to_d_intercept(slope,intercept) * learning_rate\n        step_size_slope = d_ssr_to_d_slope(slope,intercept) * learning_rate\n        intercept = intercept - step_size_intercept # i did not see a proof for this\n        slope = slope - step_size_slope\n        step_size = max(abs(step_size_intercept) , abs(step_size_slope))\n\n        # ------------ below this is relevant to plot\n        _predicted_height = predicted_height(intercept,slope)\n        _observed_height = Height\n        iteration += 1\n        ssr = sum_of_square_residual(_predicted_height , _observed_height)\n        ssr_vec.append(ssr)\n        print(\"intercept : {} , slope : {} , step_size : {} , iteration : {}\".format(intercept,slope,step_size,iteration))\n\n    plot2(intercept,slope,step_size,iteration,ssr,ssr_vec)\n\ndef plot2(intercept,slope,step_size,iteration,ssr,ssr_vec):\n    fig, axs = plt.subplots(2)\n    plot_with_residual(axs[0],Weight,Height,intercept,slope)\n    axs[0].grid()\n    fig.suptitle('Part 2')\n    axs[0].set_title('data set vs intercpt  + slope * weight and residual\\nssr : {:.2f} , intercept : {:.2f} ,slope : {:.2f} , iteration : {} , step : {:.4f}'.format(ssr , intercept,slope , iteration,step_size))\n    axs[0].set_xlabel(\"Weight\")\n    axs[0].set_ylabel(\"Height\")\n    axs[1].plot(ssr_vec)\n    axs[1].set_title('gradient descent convergence , learn intercept and slope')\n    axs[1].set_xlabel('iteration')\n    axs[1].set_ylabel('cost function - ssr')\n    axs[1].grid()\n    plt.tight_layout()\n    plt.show()\n\n# part 1 assume slope is 0.64 , compute intercept\ndef part1_learn_slope_is_constant():\n    slope = 0.64\n    compute_one_ssr(slope)\n    show_ssr_graph_per_intercept(slope)\n    print_d_ssr_to_d_intercept(slope)\n    gradient_descent_constant_slope(0.64)\n\ndef part2_learn():\n    gradient_descent()\n\n# main\nplot_dataset()\npart1_learn_slope_is_constant()\npart2_learn()\n", "meta": {"hexsha": "2453672b37b2b02677ac6d59d0020577be38a2b2", "size": 7823, "ext": "py", "lang": "Python", "max_stars_repo_path": "gradient_descent_lg.py", "max_stars_repo_name": "NathanKr/ml-math-background-playground", "max_stars_repo_head_hexsha": "69c3c10f3e9fc348a40166b4b20af8d43507944c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gradient_descent_lg.py", "max_issues_repo_name": "NathanKr/ml-math-background-playground", "max_issues_repo_head_hexsha": "69c3c10f3e9fc348a40166b4b20af8d43507944c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gradient_descent_lg.py", "max_forks_repo_name": "NathanKr/ml-math-background-playground", "max_forks_repo_head_hexsha": "69c3c10f3e9fc348a40166b4b20af8d43507944c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1736842105, "max_line_length": 211, "alphanum_fraction": 0.6804295027, "include": true, "reason": "import numpy", "num_tokens": 2284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305328688783, "lm_q2_score": 0.8976952818435994, "lm_q1q2_score": 0.8646875046840881}}
{"text": "import numpy as np\n\n\ndef discount_rate(rate, periods):\n    return 1.0 / np.power(1.0 + rate, periods)\n\n\ndef yield_rate(discount, periods):\n    return np.power(1.0 / discount, 1.0 / periods) - 1.0\n\n\ndef interpolate_rate(**kwargs) -> float:\n    first_period: int = kwargs.get('first_period')\n    next_period: int = kwargs.get('next_period')\n    extrapolate_period: int = kwargs.get('extrapolate_period')\n    first_rate: float = kwargs.get('first_rate')\n    next_rate: float = kwargs.get('next_rate')\n\n    assert next_period > extrapolate_period > first_period\n\n    if first_rate == next_rate:\n        return first_rate\n\n    first_discount = discount_rate(first_rate, first_period)\n    next_discount = discount_rate(next_rate, next_period)\n    assert 0.0 < next_discount < first_discount <= 1.0\n\n    second_discount = next_discount / first_discount\n    second_periods = next_period - first_period\n\n    extrapolated_discount = first_discount * np.power(second_discount, (extrapolate_period - first_period) / second_periods)\n    yr = yield_rate(extrapolated_discount, extrapolate_period)\n\n    assert min(first_rate, next_rate) <= yr <= max(first_rate, next_rate)\n    return yr\n", "meta": {"hexsha": "e359d0bd98ee022a941d4bef0dd40acaa92a3901", "size": 1172, "ext": "py", "lang": "Python", "max_stars_repo_path": "mfow_compfin/yield_curve/interest.py", "max_stars_repo_name": "mfow/compfin", "max_stars_repo_head_hexsha": "d513ef69b0aa25a298cb2187c2211642fd080db4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mfow_compfin/yield_curve/interest.py", "max_issues_repo_name": "mfow/compfin", "max_issues_repo_head_hexsha": "d513ef69b0aa25a298cb2187c2211642fd080db4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mfow_compfin/yield_curve/interest.py", "max_forks_repo_name": "mfow/compfin", "max_forks_repo_head_hexsha": "d513ef69b0aa25a298cb2187c2211642fd080db4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5555555556, "max_line_length": 124, "alphanum_fraction": 0.7278156997, "include": true, "reason": "import numpy", "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9763105314577313, "lm_q2_score": 0.8856314662716159, "lm_q1q2_score": 0.8646513275113311}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov  3 21:06:23 2018\n\n@author: Thiago Almeida\n\"\"\"\n\nimport numpy as np\nfrom metodos_numericos.LU import LU\nfrom metodos_numericos.Gauss import Gauss\nfrom Utils import Utils\n\nclass MinimosQuadrados():\n\n    #constroi o polinomio para interpolacao\n    def executar(self, x, y, n):\n        \n        n_col = len(x)\n        n_linhas = n+1\n        tam2 = n+1\n        \n        #ja preenche a primeira linha com 1\n        M1 = np.ones((n_linhas,n_col), dtype=np.float128)\n\n        for k in range (1,n_linhas):\n            for j in range (0,n_col):\n                M1[k][j] = x[j]**k\n            \n        #print(\"M1\", M1)\n        \n        A = np.zeros((tam2,tam2), dtype=np.float128)\n        B = np.zeros((tam2,), dtype=np.float128)\n        \n        #cria matriz\n        for i in range (0,tam2):\n            for j in range (0,tam2):\n                a = np.array(M1[i], dtype=np.float128, copy=True)\n                b = np.array(M1[j], dtype=np.float128, copy=True)\n                \n                A[i][j] = np.dot(a, b)\n                \n        #cria vetor fonte\n        for i in range (0,tam2):\n            b = np.array(M1[i], dtype=np.float128, copy=True)\n            B[i] = np.dot(y, b)\n            \n        print(\"A\", A)\n        print(\"B\", B)\n        \n        #Utils().obtemInfoMatriz(A)\n            \n        #calcula coeficientes\n        X = LU().executar(A, B)[0]\n        #X = Gauss().executarComPivoteamento(A, B)[0]\n        #X = Gauss().executar(A, B)[0]\n        return X\n        \n    \n    \n    def interpolaCoeficientes(self, c, n, xk):\n        \n        soma = 0        \n        for i in range (0,n+1):\n            soma += c[i] * (xk ** i)\n            \n        #if(np.isnan(soma)):\n            #print(\"resultado da interpolacao do valor \"+repr(xk)+\" foi igual a NaN\")\n            #soma = 0\n            \n        return soma\n        \n    def calculaResiduo(self, y, x, n, c):\n        \n        tam = len(y)\n        \n        soma1 = 0\n        soma2 = 0\n        soma3 = 0\n        for k in range (0, tam):\n            soma1 += (y[k] - self.interpolaCoeficientes(c, n, x[k]))**2\n            soma2 += y[k]**2\n            soma3 += y[k]\n        \n        r2 = 1 - (soma1 / (soma2 - (1/tam)*soma3**2))\n        \n        if(r2 < 0):\n            print(\"N=\"+repr(n)+\", r^2 = \" + repr(r2) + \" e nao tem raiz real\")\n            return 0\n        else:\n            return np.sqrt(r2)            \n", "meta": {"hexsha": "d0a8b9a1ab019b53a25fafbc6785f92b84744a12", "size": 2441, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lista5/MinimosQuadrados.py", "max_stars_repo_name": "thiago9864/calculo_numerico", "max_stars_repo_head_hexsha": "e4b6f059bdb31460130093bd446fb3ea906dc542", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lista5/MinimosQuadrados.py", "max_issues_repo_name": "thiago9864/calculo_numerico", "max_issues_repo_head_hexsha": "e4b6f059bdb31460130093bd446fb3ea906dc542", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lista5/MinimosQuadrados.py", "max_forks_repo_name": "thiago9864/calculo_numerico", "max_forks_repo_head_hexsha": "e4b6f059bdb31460130093bd446fb3ea906dc542", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-08-25T14:30:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-25T14:30:48.000Z", "avg_line_length": 26.5326086957, "max_line_length": 85, "alphanum_fraction": 0.4543219992, "include": true, "reason": "import numpy", "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.9263037343628703, "lm_q1q2_score": 0.86464045117211}}
{"text": "#countingWithNestedForLoops.py\nimport numpy as np\n\n#Example 1\n# recall how to count using a for loop:\nmax_count = 100\nfor i in range(100):\n    print(i)\n\n#Example 2a\n# Counting with nested for loops offers an opportunity to think about\n# 1. The structure of a number system of different bases\n# 2. The structure of multidimensional arrays\n\n# consider counting to 100 in base 10:\n\ncount_list = []\nbase10_count_list = []\n\n# try changing the base to see how the count changes\n# the program will count to base ** 2 - 1\n# provides interpretable results work for all bases up to 10\nbase = 3\nfor i in range(base):\n    for j in range(base):\n        val = int(str(i) + str(j))\n        count_list.append(val)\n        #produce equivalent list in base10\n        base10_val = i * base + j\n        base10_count_list.append(base10_val)\nprint(\"\\ncount in base\", base)\nprint(count_list)\nprint(\"\\ncount in base 10:\")\nprint(base10_count_list)\n\n#Example 2b\n#imagine that you wanted to count to base ** 3 - 1\ncount_list = []\nbase10_count_list = []\n# try changing the base to see how the count changes\n# the program will count to base ** 3 - 1\n# provides interpretable results work for all bases up to 10\nfor i in range(base):\n    for j in range(base):\n        for k in range(base):        \n            val = int(str(i) + str(j) + str(k))\n            count_list.append(val)\n            #produce equivalent list in base10\n            base10_val = i * base ** 2 + j * base + k\n            base10_count_list.append(base10_val)\n\nprint(\"\\ncount in base\", base)\nprint(count_list)\nprint(\"\\ncount in base 10:\")\nprint(base10_count_list)\n\n#Example 3\n# We can use the same logic to fill an n X n array with values:\nn = base\narray = np.zeros((n,n))\nfor i in range(n):\n    for j in range(n):\n        array[i][j] = i * n + j\nprint(array)", "meta": {"hexsha": "4a9e364990c63b3c52a98e9ca2df23332e1691f8", "size": 1800, "ext": "py", "lang": "Python", "max_stars_repo_path": "In Class Projects/In Class Examples Fall 2019/Section 5/countingWithNestedForLoops.py", "max_stars_repo_name": "hunterluepke/Learn-Python-for-Stats-and-Econ", "max_stars_repo_head_hexsha": "d580a8e27ba937fc8401ac6d0714b6488ac8bbb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-01-10T18:54:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T20:07:20.000Z", "max_issues_repo_path": "In Class Projects/In Class Examples Fall 2019/Section 5/countingWithNestedForLoops.py", "max_issues_repo_name": "hunterluepke/Learn-Python-for-Stats-and-Econ", "max_issues_repo_head_hexsha": "d580a8e27ba937fc8401ac6d0714b6488ac8bbb6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "In Class Projects/In Class Examples Fall 2019/Section 5/countingWithNestedForLoops.py", "max_forks_repo_name": "hunterluepke/Learn-Python-for-Stats-and-Econ", "max_forks_repo_head_hexsha": "d580a8e27ba937fc8401ac6d0714b6488ac8bbb6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-01-24T17:11:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T01:53:57.000Z", "avg_line_length": 28.125, "max_line_length": 69, "alphanum_fraction": 0.6683333333, "include": true, "reason": "import numpy", "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971129089711396, "lm_q2_score": 0.8902942166619118, "lm_q1q2_score": 0.8645906122022028}}
{"text": "import numpy as np\n\n\ndef random_graph(node_count, prob):\n    \"\"\"\n    Create a random adjacency matrix of a graph\n\n    Parameters\n    ----------\n    node_count: int\n        Number of nodes in the graph\n    prob: float\n        Probability of presence an edge between two nodes\n\n    Returns\n    -------\n    adj_mat: numpy.ndarray\n        A numpy array of size (node_count, node_count) with elements in {0, 1}\n    \"\"\"\n    return np.random.binomial(1, prob, size=(node_count, node_count)).astype(\n        np.float64)\n\n\ndef random_choice(arr):\n    \"\"\"\n    Based on the suggestion by Radim Rehurek in this tweet:\n    https://twitter.com/RadimRehurek/status/928671225861296128\n\n    Results of comparison between this implementation and\n    numpy.random.choice:\n    ```\n    >>>> lst = range(100000)\n    >>>> timeit lst[np.searchsorted(uniform.cumsum(), np.random.random())]\n    213 µs ± 1.32 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\n    >>>> timeit np.random.choice(lst)\n    8.2 ms ± 70.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n    ```\n\n    Parameters\n    ----------\n    arr: list\n        A 1-D list or array from which to select an element randomly\n\n    Returns\n    -------\n    One element selected randomly from arr, with uniform probability\n    \"\"\"\n    assert type(arr) is list or type(arr) is np.ndarray, 'List not provided!'\n    uniform = np.ones((len(arr), )) / len(arr)\n    return arr[np.searchsorted(uniform.cumsum(), np.random.random())]\n\n\ndef adj_mat_to_list(adj_mat):\n    \"\"\"\n    Converts an adjacency matrix to an adjacency list.\n\n    Parameters\n    ----------\n    adj_mat: numpy.ndarray\n        Square adjacency matrix of a graph\n\n    Returns\n    -------\n    adj_list: list\n        The adjacency list of the given matrix\n    \"\"\"\n    assert adj_mat.ndim == 2, 'Adjacency matrix should be of rank 2.'\n    assert adj_mat.shape[0] == adj_mat.shape[1], 'Adjacency matrix' \\\n        ' should be square.'\n    assert np.all(adj_mat >= 0), 'All elements of the adjaceny matrix ' \\\n        'should be nonnegative.'\n    adj_list = []\n    for i in range(adj_mat.shape[0]):\n        adj_list.append([])\n        for j in range(adj_mat.shape[0]):\n            if adj_mat[i, j] > 0:\n                adj_list[-1].append(j)\n\n    return adj_list\n\n\ndef adj_list_to_mat(adj_list):\n    \"\"\"\n    Converts an adjacency list to an adjacency matrix.\n\n    Parameters\n    ----------\n    adj_list: list\n        Adjacency list of a graph\n\n    Returns\n    -------\n    adj_mat: numpy.ndarray\n        Square adjacency matrix of a graph\n    \"\"\"\n    assert type(adj_list) == list, 'Adjacency list should be provided'\n\n    adj_mat = np.zeros((len(adj_list), len(adj_list)), dtype=np.float64)\n    for i in range(len(adj_list)):\n        for j in adj_list[i]:\n            adj_mat[i, j] = 1.0\n\n    return adj_mat\n", "meta": {"hexsha": "fd8f10b7deb4f29b3e60df4635204db42df81dba", "size": 2810, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils.py", "max_stars_repo_name": "erfannoury/cmsc641-project", "max_stars_repo_head_hexsha": "776cd72805ece35594ea3855ef578cbebb1db511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils.py", "max_issues_repo_name": "erfannoury/cmsc641-project", "max_issues_repo_head_hexsha": "776cd72805ece35594ea3855ef578cbebb1db511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils.py", "max_forks_repo_name": "erfannoury/cmsc641-project", "max_forks_repo_head_hexsha": "776cd72805ece35594ea3855ef578cbebb1db511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7619047619, "max_line_length": 78, "alphanum_fraction": 0.6153024911, "include": true, "reason": "import numpy", "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.9149009567332237, "lm_q1q2_score": 0.864576568682731}}
{"text": "\n### 3 Link Forward Kinematics ###\n\nimport numpy as np\nfrom numpy import array\nimport sympy\nfrom sympy import *\nfrom sympy import symbols, cos, sin, pi, simplify, sqrt, atan2, pprint\nfrom sympy.matrices import Matrix\n\ndef fk_3link(theta1,theta2,theta3):\n\n    # Create symbols for DH param\n    q1, q2, q3 = symbols('q1:4')                               # joint angles theta\n    d1, d2, d3 = symbols('d1:4')                              # link offsets\n    a0, a1, a2 = symbols('a0:3')                              # link lengths\n    alpha0, alpha1, alpha2 = symbols('alpha0:3') # joint twist angles\n\n    # DH Table\n    dh = {alpha0:      0, a0:      0, d1:  0.75, q1:        q1,\n          alpha1: -pi/2., a1:   0.35, d2:     0, q2: -pi/2.+q2,\n          alpha2:      0, a2:   1.25, d3:     0, q3:        q3,}\n\n    # Function to return homogeneous transform matrix\n\n    def TF_Mat(alpha, a, d, q):\n        TF = Matrix([[            cos(q),           -sin(q),           0,             a],\n                     [ sin(q)*cos(alpha), cos(q)*cos(alpha), -sin(alpha), -sin(alpha)*d],\n                     [ sin(q)*sin(alpha), cos(q)*sin(alpha),  cos(alpha),  cos(alpha)*d],\n                     [                 0,                 0,           0,             1]])\n        return TF\n\n    ## Substiute DH_Table\n    T0_1 = TF_Mat(alpha0, a0, d1, q1).subs(dh)\n    T1_2 = TF_Mat(alpha1, a1, d2, q2).subs(dh)\n    T2_3 = TF_Mat(alpha2, a2, d3, q3).subs(dh)\n\n    #Homogeneous Transforms\n\n    T0_2 = (T0_1 * T1_2) ## (Base) Link_0 to Link_2\n    T0_3 = (T0_2 * T2_3) ## (Base) Link_0 to Link_3\n\n    T0_3_value = N(T0_3.evalf(subs={q1: theta1, q2: theta2, q3: theta3}),2) #two digit output\n    #print(T0_3 )\n    #print('T0_3= \\n    ',T0_3_value)\n    #print(\"result:\",np.array([T0_3_value]))\n\n    #print(\"\\nT_total Matrix : \\n\")\n    #print(\"\\n\")\n\n    return np.array([T0_3_value])\n\n#fk_3link(pi/3,pi/3,pi/3)\n\n#fk_3link(0,0,0)\n\n", "meta": {"hexsha": "513d7622f2ad9dba51bed1458f45406c46a05eec", "size": 1906, "ext": "py", "lang": "Python", "max_stars_repo_path": "script_for_test/fk.py", "max_stars_repo_name": "yongan007/robot_urdf_E1", "max_stars_repo_head_hexsha": "c2392212c5b6d692715c134d14a29e3852a79cf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-10-02T18:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T09:25:10.000Z", "max_issues_repo_path": "script_for_test/fk.py", "max_issues_repo_name": "yongan007/robot_urdf_E1", "max_issues_repo_head_hexsha": "c2392212c5b6d692715c134d14a29e3852a79cf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-11-21T14:34:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-02T09:48:17.000Z", "max_forks_repo_path": "script_for_test/fk.py", "max_forks_repo_name": "yongan007/robot_urdf_E1", "max_forks_repo_head_hexsha": "c2392212c5b6d692715c134d14a29e3852a79cf0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-27T18:12:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-27T18:12:54.000Z", "avg_line_length": 33.4385964912, "max_line_length": 93, "alphanum_fraction": 0.5099685205, "include": true, "reason": "import numpy,from numpy,import sympy,from sympy", "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885303, "lm_q2_score": 0.8991213826762113, "lm_q1q2_score": 0.8645356098956707}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n# ## Monte Carlo - Euler Discretization - Part I\n# *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).*\n# Download the data for Microsoft (‘MSFT’) from Yahoo Finance for the period ‘2000-1-1’ until today.\n# In[1]:\nimport numpy as np  \nimport pandas as pd  \nfrom pandas_datareader import data as web  \nfrom scipy.stats import norm \nimport matplotlib.pyplot as plt  \nget_ipython().run_line_magic('matplotlib', 'inline')\n# In[2]:\nticker = 'MSFT'  \ndata = pd.DataFrame()\ndata[ticker] = web.DataReader(ticker, data_source='yahoo', start='2007-1-1', end='2017-3-21')['Adj Close']\n# Store the annual standard deviation of the log returns in a variable, called “stdev”.\n# In[3]:\nlog_returns = np.log(1 + data.pct_change())\n# In[4]:\nlog_returns.tail()\n# In[5]:\ndata.plot(figsize=(10, 6));\n# In[6]:\nstdev = log_returns.std() * 250 ** 0.5\nstdev\n# Set the risk free rate, r, equal to 2.5% (0.025).\n# In[7]:\nr = 0.025\n# To transform the object into an array, reassign stdev.values to stdev.\n# In[8]:\ntype(stdev)\n# In[9]:\nstdev = stdev.values\nstdev\n# Set the time horizon, T, equal to 1 year, the number of time intervals equal to 250, the iterations equal to 10,000. Create a variable, delta_t, equal to the quotient of T divided by the number of time intervals.\n# In[10]:\nT = 1.0 \nt_intervals = 250 \ndelta_t = T / t_intervals  \niterations = 10000  \n# Let Z equal a random matrix with dimension (time intervals + 1) by the number of iterations. \n# In[11]:\nZ = np.random.standard_normal((t_intervals + 1, iterations))  \n# Use the .zeros_like() method to create another variable, S, with the same dimension as Z. S is the matrix to be filled with future stock price data. \n# In[12]:\nS = np.zeros_like(Z) \n# Create a variable S0 equal to the last adjusted closing price of Microsoft. Use the “iloc” method.\n# In[13]:\nS0 = data.iloc[-1]  \nS[0] = S0 \n# Use the following formula to create a loop within the range (1, t_intervals + 1) that reassigns values to S in time t.\n# $$\n# S_t = S_{t-1} \\cdot exp((r - 0.5 \\cdot stdev^2) \\cdot delta_t + stdev \\cdot delta_t^2 \\cdot Z_t)\n# $$\n# In[14]:\nfor t in range(1, t_intervals + 1):\n    S[t] = S[t-1] * np.exp((r - 0.5 * stdev ** 2) * delta_t + stdev * delta_t ** 0.5 * Z[t])\n# In[15]:\nS\n# In[16]:\nS.shape\n# Plot the first 10 of the 10,000 generated iterations on a graph.\n# In[17]:\nplt.figure(figsize=(10, 6))\nplt.plot(S[:, :10]);\n", "meta": {"hexsha": "df773fe199973f2f5d84748428e11f63a94d5bcc", "size": 2434, "ext": "py", "lang": "Python", "max_stars_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_109-MC-EulerDiscretization-PartI-Solution_Yahoo_Py3.py", "max_stars_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_stars_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-04T11:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-10T15:36:42.000Z", "max_issues_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_109-MC-EulerDiscretization-PartI-Solution_Yahoo_Py3.py", "max_issues_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_issues_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-03-30T16:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:37:21.000Z", "max_forks_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_109-MC-EulerDiscretization-PartI-Solution_Yahoo_Py3.py", "max_forks_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_forks_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T11:26:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T11:26:16.000Z", "avg_line_length": 36.328358209, "max_line_length": 214, "alphanum_fraction": 0.6861133936, "include": true, "reason": "import numpy,from scipy", "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574668, "lm_q2_score": 0.9019206844384594, "lm_q1q2_score": 0.8645250051927493}}
{"text": "\nfrom statistics import mean\nimport numpy as np\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport random   # to make our data random\n\nstyle.use('fivethirtyeight')\n\n# xs = [1,2,3,4,5,6]\n# ys = [5,4,6,5,6,7]\n\n# plt.plot(xs,ys)\n# plt.show()\n\n# Since above are not np array they are just a python array, to change them which will give us\n# more powerful way to iterate over then values in the array,\n\n# xs = np.array(xs, dtype = np.float64)  # you can also specify the data-type into your array\n# ys = np.array(ys, dtype = np.float64)\n\n\n\n# Here we will add our dataset random generation for testing our model\ndef create_dataset(hm, variance, step = 2, correaltion = False):\n\n    \"\"\"\n    Definition:\n    hm          : number of data points that you want to create\n    variance    : is how variables or scattered your data are\n    step        : how far from the average of our data we want to be, default is (2)\n    correlation : to show the data r correlated positively or negatively or none (boolean), default (False)\n    this function will return a two lists one for xs and one for ys, you can set your variables in that case to the\n    form like\n    x1, y2 = create_dataset....etc\n\n    \"\"\"\n    val =1 # this would be the first value in the ys\n    ys = []\n    for i in range(hm):\n        y = val + random.randrange(-variance,variance) # return a value between these two numbers (-variance,variance)\n        ys.append(y)  # this is the way to add value to your list above, I thought before ys[i] = y (which is wrong)\n        if correaltion and correaltion == 'pos':\n            val += step\n        elif correaltion and correaltion == 'neg':\n            val -= step\n    xs = [i for i in range(len(ys))]\n    return np.array(xs, dtype = np.float64), np.array(ys, dtype=np.float64)\n\n# first we need a function to calculate the slop as\n\ndef best_fit_slop_and_intercept(xs,ys):\n\n    m = ( ((mean(xs)*mean(ys)) - mean(xs*ys)) /\n          (mean(xs)**2-mean(xs**2)))\n    b = mean(ys)-m*mean(xs)\n\n# remember the PEMDAS the order of the operations in computing\n    return m,b\n\ndef squared_error(ys_orig, ys_line):\n    return sum((ys_line-ys_orig)**2)\n\ndef coefficient_of_determination(ys_orig,ys_line):\n    y_mean_line = [mean(ys_orig) for y in ys_orig]    # to make a vector with only one value which is mean(ys_orig)\n    squared_error_regr = squared_error(ys_orig,ys_line)\n    squared_error_y_mean = squared_error(ys_orig, y_mean_line)\n    return 1- (squared_error_regr / squared_error_y_mean)\n\n\n# create data from the random generation data that we               created\nxs, ys = create_dataset(2000, 1700,2,'neg')\n\n\n\n\nm,b = best_fit_slop_and_intercept(xs,ys)\nprint(m,b)\n\n\nregression_line = [(m*x)+b for x in xs]\nprint(regression_line)\n\n\n# Here we will add the piece of code to calculate the coefficient of determination,\nr_squared = coefficient_of_determination(ys, regression_line)\nprint(r_squared)\n\n\n\n# this is exact identical to the following format\n# for x in xs:\n#     regression_line.append((m*x)+b)\n\n# now we will plot the data and the regression line\n\n# what if you want to predict a specific value\npredict_x = 8\npredict_y = (m*predict_x)+b\n\nplt.scatter(xs,ys)\nplt.scatter(predict_x,predict_y, s = 100, color = 'red')\nplt.plot(xs,regression_line)\nplt.show()\n\n", "meta": {"hexsha": "858f1a2baa86b21faff44b7bb87e7826d7015cc8", "size": 3316, "ext": "py", "lang": "Python", "max_stars_repo_path": "Machine_Learning_Old_Files/[12] linear regression P.5.py", "max_stars_repo_name": "Ghasak/PracticalMachineLeanring", "max_stars_repo_head_hexsha": "b16095c889be3a14a27e83fe6311581b456cefd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Machine_Learning_Old_Files/[12] linear regression P.5.py", "max_issues_repo_name": "Ghasak/PracticalMachineLeanring", "max_issues_repo_head_hexsha": "b16095c889be3a14a27e83fe6311581b456cefd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:46:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:10:34.000Z", "max_forks_repo_path": "Machine_Learning_Old_Files/[12] linear regression P.5.py", "max_forks_repo_name": "Ghasak/PracticalMachineLeanring", "max_forks_repo_head_hexsha": "b16095c889be3a14a27e83fe6311581b456cefd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7037037037, "max_line_length": 118, "alphanum_fraction": 0.6936067551, "include": true, "reason": "import numpy", "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574669, "lm_q2_score": 0.9019206771886166, "lm_q1q2_score": 0.8645249982435016}}
{"text": "# https://docs.sympy.org/latest/tutorial/calculus.html\n\nfrom sympy import *\nfrom myprint import spprint\n\nx, y, z = symbols('x y z')\ninit_printing(use_unicode=False)\n\n# derivatives\n\nspprint(diff(cos(x), x))\nspprint(diff(exp(x**2), x))\n\n# derivative 3 times\n\nspprint(diff(x**4, x, x, x))\nspprint(diff(x**4, x, 3))\n\n# many variables?\n\nexpr = exp(x*y*z)\n\nspprint(expr)\n\nspprint(diff(expr, x, y, y, z, z, z, z))\n\nspprint(diff(expr, x, y, 2, z, 4))\n\nspprint(diff(expr, x, y, y, z, 4))\n\n# diff method\n\nspprint(expr.diff(x, y, y, z, 4))\n\n# \"unevaluated\" derivative - interesting\n\nderiv = Derivative(expr, x, y, y, z, 4)\nspprint(deriv)\n\n# evaluate with .doit - wonder how that works with other things\n\nspprint(deriv.doit())\n\n# not sure what this is - nth derivative with respect to x?\n\nm, n, a, b = symbols('m n a b')\nexpr = (a*x + b)**m\nspprint(expr.diff((x, n)))\n\n#integrals\n\n# indefinate\n\nspprint(integrate(cos(x), x))\n\n# definate\n\nspprint(integrate(exp(-x), (x, 0, oo)))\n\n# multiple\n\nspprint(integrate(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo)))\n\n# unable to compute\n\nexpr = integrate(x**x, x)\nspprint(expr)\nspprint(expr.doit())\n\n# unevaluated\n\nexpr = Integral(log(x)**2, x)\nspprint(expr)\nspprint(expr.doit())\n\n# more complex?\n\ninteg = Integral((x**4 + x**2*exp(x) - x**2 - 2*x*exp(x) - 2*x -\n        exp(x))*exp(x)/((x - 1)**2*(x + 1)**2*(exp(x) + 1)), x)\nspprint(integ)\n\nspprint(integ.doit())\n\ninteg = Integral(sin(x**2), x)\nspprint(integ)\nspprint(integ.doit())\n\ninteg = Integral(x**y*exp(-x), (x, 0, oo))\nspprint(integ)\nspprint(integ.doit())\n\n# limits\n\nspprint(limit(sin(x)/x, x, 0))\n\n# things that cannot be done by subs oo/oo = nan\n\nexpr = x**2/exp(x)\nspprint(expr)\nspprint(expr.subs(x, oo))\nspprint(limit(expr, x, oo))\n\n# unevaluated\n\nexpr = Limit((cos(x) - 1)/x, x, 0)\nspprint(expr)\nspprint(expr.doit())\n\n# + or - side of limit\n# I guess you do not know if x is\n# positive or negative\n# maybe can say that when defining symbol\n\nspprint(limit(1/x, x, 0, '+'))\nspprint(limit(1/x, x, 0, '-'))\n\n# series - not sure about this\n# not related to CS big O\n\nexpr = exp(sin(x))\nspprint(expr.series(x, 0, 4))\n\nspprint(x + x**3 + x**6 + O(x**4))\n\nspprint(x*O(1))\n\n# how do I enter formalas to print and do not get them\n# immediately simplified?\n\nspprint(expr.series(x, 0, 4).removeO())\n\n# another thing I do not understand\n\nf, g = symbols('f g', cls=Function)\nspprint(differentiate_finite(f(x)*g(x)))\n\nf = Function('f')\ndfdx = f(x).diff(x)\nspprint(dfdx.as_finite_difference())\n\nf = Function('f')\nspprint(f)\nspprint(f(x))\nd2fdx2 = f(x).diff(x, 2)\nspprint(d2fdx2)\nh = Symbol('h')\nspprint(d2fdx2.as_finite_difference([-3*h,-h,2*h]))\n\nspprint(finite_diff_weights(2, [-3, -1, 2], 0)[-1][-1])\n\nx_list = [-3, 1, 2]\nspprint(x_list)\n\ny_list = symbols('a b c')\nspprint(y_list)\n\nspprint(apply_finite_diff(1, x_list, y_list, 0))\n\n# way to get 2*x/x without evaluating\n# there is no Div apparently\n\ny = Mul(2*x,1/x, evaluate=False)\n\n# unsimplified\n\nspprint(y)\n\n# simplified\n\nspprint(y.doit())\n\n# I guess there is Add, Mul, Pow\n\n\n\n", "meta": {"hexsha": "8f53910b7dc993f0b70212498dd9321f124ab7ab", "size": 3011, "ext": "py", "lang": "Python", "max_stars_repo_path": "c9.py", "max_stars_repo_name": "bobbydurrett/sympytutorial", "max_stars_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c9.py", "max_issues_repo_name": "bobbydurrett/sympytutorial", "max_issues_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c9.py", "max_forks_repo_name": "bobbydurrett/sympytutorial", "max_forks_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1079545455, "max_line_length": 65, "alphanum_fraction": 0.6433078711, "include": true, "reason": "from sympy", "num_tokens": 1092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377308419049, "lm_q2_score": 0.9019206732341567, "lm_q1q2_score": 0.8645249955212717}}
{"text": "import numpy as np\n# Setting a random seed, feel free to change it and see different solutions.\nnp.random.seed(42)\n\n\n# TODO: Fill in code in the function below to implement a gradient descent\n# step for linear regression, following a squared error rule. See the docstring\n# for parameters and returned variables.\ndef MSEStep(X, y, W, b, learn_rate = 0.005):\n    \"\"\"\n    This function implements the gradient descent step for squared error as a\n    performance metric.\n    \n    Parameters\n    X : array of predictor features\n    y : array of outcome values\n    W : predictor feature coefficients\n    b : regression function intercept\n    learn_rate : learning rate\n\n    Returns\n    W_new : predictor feature coefficients following gradient descent step\n    b_new : intercept following gradient descent step\n    \"\"\"\n    \n    # Fill in code\n    \n    return W_new, b_new\n\n\n# The parts of the script below will be run when you press the \"Test Run\"\n# button. The gradient descent step will be performed multiple times on\n# the provided dataset, and the returned list of regression coefficients\n# will be plotted.\ndef miniBatchGD(X, y, batch_size = 20, learn_rate = 0.005, num_iter = 25):\n    \"\"\"\n    This function performs mini-batch gradient descent on a given dataset.\n\n    Parameters\n    X : array of predictor features\n    y : array of outcome values\n    batch_size : how many data points will be sampled for each iteration\n    learn_rate : learning rate\n    num_iter : number of batches used\n\n    Returns\n    regression_coef : array of slopes and intercepts generated by gradient\n      descent procedure\n    \"\"\"\n    n_points = X.shape[0]\n    W = np.zeros(X.shape[1]) # coefficients\n    b = 0 # intercept\n    \n    # run iterations\n    regression_coef = [np.hstack((W,b))]\n    for _ in range(num_iter):\n        batch = np.random.choice(range(n_points), batch_size)\n        X_batch = X[batch,:]\n        y_batch = y[batch]\n        W, b = MSEStep(X_batch, y_batch, W, b, learn_rate)\n        regression_coef.append(np.hstack((W,b)))\n    \n    return regression_coef\n\n\nif __name__ == \"__main__\":\n    # perform gradient descent\n    data = np.loadtxt('batch_graddesc_data.csv', delimiter = ',')\n    X = data[:,:-1]\n    y = data[:,-1]\n    regression_coef = miniBatchGD(X, y)\n    \n    # plot the results\n    import matplotlib.pyplot as plt\n    \n    plt.figure()\n    X_min = X.min()\n    X_max = X.max()\n    counter = len(regression_coef)\n    for W, b in regression_coef:\n        counter -= 1\n        color = [1 - 0.92 ** counter for _ in range(3)]\n        plt.plot([X_min, X_max],[X_min * W + b, X_max * W + b], color = color)\n    plt.scatter(X, y, zorder = 3)\n    plt.show()", "meta": {"hexsha": "22c84a6ed784adec9f48861fa4999ce3be881acf", "size": 2661, "ext": "py", "lang": "Python", "max_stars_repo_path": "Supervised Learning/01 Linear Regression/batch_graddesc.py", "max_stars_repo_name": "stephengineer/Introduction-to-Machine-Learning-with-TensorFlow", "max_stars_repo_head_hexsha": "fc13795db3e20d87f625864e4e7ff68b4afcedb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Supervised Learning/01 Linear Regression/batch_graddesc.py", "max_issues_repo_name": "stephengineer/Introduction-to-Machine-Learning-with-TensorFlow", "max_issues_repo_head_hexsha": "fc13795db3e20d87f625864e4e7ff68b4afcedb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Supervised Learning/01 Linear Regression/batch_graddesc.py", "max_forks_repo_name": "stephengineer/Introduction-to-Machine-Learning-with-TensorFlow", "max_forks_repo_head_hexsha": "fc13795db3e20d87f625864e4e7ff68b4afcedb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3058823529, "max_line_length": 79, "alphanum_fraction": 0.665539271, "include": true, "reason": "import numpy", "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377284730286, "lm_q2_score": 0.9019206738932334, "lm_q1q2_score": 0.8645249940164832}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom random import randint\n\n\ndef med(nums):\n    '''\n    Calcula a média aritmética de um comjunto de números\n    :param nums: tupla, lista ou array\n    :return: retorna a média\n    '''\n    soma = 0\n    for i in nums:\n        soma += i\n    med = soma / len(nums)\n    return med\n\n\ndef desvp(nums):\n    '''\n    Calcula o desvio padrão de um conjunto de números\n    :param nums: tupla, lista ou array\n    :return: retorna o desvio padrão\n    '''\n    soma = 0\n    for i in nums:\n        soma += i\n    med = soma / len(nums)\n    desvio = 0\n    for i in nums:\n        desvio += (i - med)**2\n    desvp = (desvio/len(nums))**(1/2)\n    return desvp\n\n\nn = int(input('Quantidade de jogadas: '))\nx1 = np.array(list([randint(1, 6) for i in range(n)]))\nx2 = np.array(list([randint(1, 6) for j in range(n)]))\ny = x1 + x2\nmedia = med(y)\ndesviop = desvp(y)\nprint(f'{\"-~\"*25}\\nA média da soma das jogadas é:')\nprint(f'Pela minha função = {media}')\nprint(f'Pela função do numpy = {np.mean(y)}')\nprint(f'{\"-~\"*25}\\nO desvio padrão da soma das jogadas:')\nprint(f'Pela minha função = {desviop}')\nprint(f'Pela função do numpy = {np.std(y)}\\n{\"-~\"*25}')\nplt.hist(y, bins=11, range=(2, 13), align='left', rwidth=0.95)\nplt.title(f'Histograma com {n} jogadas')\nplt.show()\n#plt.savefig('hist.png')\n", "meta": {"hexsha": "98646ef36ccad4cdfe684add6c82ea0cdb36cf28", "size": 1320, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ark.MetCompA/Aula-py6/atividade7.py", "max_stars_repo_name": "Artur-UF/MetCompA", "max_stars_repo_head_hexsha": "1198f861f4e5190f7435314bf476c594471e79fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ark.MetCompA/Aula-py6/atividade7.py", "max_issues_repo_name": "Artur-UF/MetCompA", "max_issues_repo_head_hexsha": "1198f861f4e5190f7435314bf476c594471e79fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ark.MetCompA/Aula-py6/atividade7.py", "max_forks_repo_name": "Artur-UF/MetCompA", "max_forks_repo_head_hexsha": "1198f861f4e5190f7435314bf476c594471e79fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3846153846, "max_line_length": 62, "alphanum_fraction": 0.6121212121, "include": true, "reason": "import numpy", "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377237352755, "lm_q2_score": 0.90192067257508, "lm_q1q2_score": 0.8645249884799059}}
{"text": "import numpy as np\n# model = y = 2*x + 3\nX = np.array([1,2,3,4],dtype=np.float32)\nY = [(2*x + 3) for x in X]\nw,b = 0.0,0.0\n\ndef forward(x):\n    return w*x+b\n\ndef loss(y,y_pred):\n    return ((y_pred-y)**2).mean()\n\ndef gradient(x,y,y_pred):\n    return np.dot(x,(y_pred-y))\n\nprint(f'print the prediction before training: f(5)={forward(5)}')\n\nlearning_rate,n_inters = (0.01,10000)\n\nfor epoch in range(n_inters):\n    y_pred  = forward(X) \n    l       = loss(Y,y_pred)\n    dw      = gradient(X,Y,y_pred)\n    w       = w - learning_rate*dw\n    b       = b + learning_rate*l\n    print(f'epoch {epoch+1}: w= {w:.3f},b= {b:.3f} loss = {l:.8f}, dw = {dw:.3f}')\n\nprint(f'print the prediction after training: f(5)={forward(5)}')\n", "meta": {"hexsha": "d51fa764b85941e2ad5ea9bfbde5dc990ccab7e8", "size": 716, "ext": "py", "lang": "Python", "max_stars_repo_path": "nn_1_1_estimate_one_w.py", "max_stars_repo_name": "xhinker/nn_sample_code", "max_stars_repo_head_hexsha": "39eb501322af34a1d43e20d2d96d4ac1ee9c8104", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-27T21:44:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T21:44:43.000Z", "max_issues_repo_path": "nn_1_1_estimate_one_w.py", "max_issues_repo_name": "xhinker/nn_sample_code", "max_issues_repo_head_hexsha": "39eb501322af34a1d43e20d2d96d4ac1ee9c8104", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nn_1_1_estimate_one_w.py", "max_forks_repo_name": "xhinker/nn_sample_code", "max_forks_repo_head_hexsha": "39eb501322af34a1d43e20d2d96d4ac1ee9c8104", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6896551724, "max_line_length": 82, "alphanum_fraction": 0.5851955307, "include": true, "reason": "import numpy", "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9796676472509721, "lm_q2_score": 0.8824278772763472, "lm_q1q2_score": 0.8644860423999886}}
{"text": "#T# divisibility can be checked with the modulo % operator, in a % b, if the result is 0 then a is divisible by b\n\n#T# even numbers are divisible by 2, odd numbers are not, so in a % 2, if the result is 0 then a is an even number, if the result is 1 then a is an odd number\nnum1 = 5 % 2 # 1 #| 5 is an odd number\nnum1 = 8 % 2 # 0 #| 8 is an even number\n\n#T# to check for divisibility in arrays element-wise, the numpy package is used\nimport numpy as np\n\n#T# create an array to check divisibility on its elements\narr1 = np.arange(1, 8) # array([1, 2, 3, 4, 5, 6, 7])\n\n#T# check divisibility by 2\narr2 = arr1 % 2 # array([1, 0, 1, 0, 1, 0, 1]) #| every second number is divisible by 2\n\n#T# check divisibility by 3\narr2 = arr1 % 3 # array([1, 2, 0, 1, 2, 0, 1]) #| every third number is divisible by 3", "meta": {"hexsha": "69b87e51a63874a66ba394a68458cbafd3aaceab", "size": 798, "ext": "py", "lang": "Python", "max_stars_repo_path": "Math/A01_Arithmetics_basics/Programs/S02/Divisibility.py", "max_stars_repo_name": "Polirecyliente/SGConocimiento", "max_stars_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Math/A01_Arithmetics_basics/Programs/S02/Divisibility.py", "max_issues_repo_name": "Polirecyliente/SGConocimiento", "max_issues_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/A01_Arithmetics_basics/Programs/S02/Divisibility.py", "max_forks_repo_name": "Polirecyliente/SGConocimiento", "max_forks_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.9411764706, "max_line_length": 158, "alphanum_fraction": 0.6704260652, "include": true, "reason": "import numpy", "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.979667648438234, "lm_q2_score": 0.8824278540866547, "lm_q1q2_score": 0.86448602072947}}
{"text": "'''\nseries_summation.py\n\nSum an arbitrary series\n'''\n\nfrom sympy import summation, sympify, Symbol, pprint\ndef find_sum(n_term, num_terms):\n    n = Symbol('n')\n    s = summation(n_term, (n, 1, num_terms))\n    pprint(s)\n\n\nif __name__ == '__main__':\n    n_term = sympify(input('Enter the nth term: '))\n    num_terms = int(input('Enter the number of terms: '))\n\n    find_sum(n_term, num_terms)      \n", "meta": {"hexsha": "7d242c494e2e4bcdfee69ca3f53b53ac5892fac7", "size": 397, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapter4/solutions/series_summation.py", "max_stars_repo_name": "hexu1985/Doing.Math.With.Python", "max_stars_repo_head_hexsha": "b6a02805cd450325e794a49f55d2d511f9db15a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 109, "max_stars_repo_stars_event_min_datetime": "2015-08-28T10:23:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T01:39:51.000Z", "max_issues_repo_path": "chapter4/solutions/series_summation.py", "max_issues_repo_name": "hexu1985/Doing.Math.With.Python", "max_issues_repo_head_hexsha": "b6a02805cd450325e794a49f55d2d511f9db15a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 371, "max_issues_repo_issues_event_min_datetime": "2020-03-04T21:51:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:59:11.000Z", "max_forks_repo_path": "chapter4/solutions/series_summation.py", "max_forks_repo_name": "hexu1985/Doing.Math.With.Python", "max_forks_repo_head_hexsha": "b6a02805cd450325e794a49f55d2d511f9db15a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2015-10-15T18:09:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:06:21.000Z", "avg_line_length": 20.8947368421, "max_line_length": 57, "alphanum_fraction": 0.6574307305, "include": true, "reason": "from sympy", "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9693241956308277, "lm_q2_score": 0.8918110475945175, "lm_q1q2_score": 0.8644540263642414}}
{"text": "import numpy as np\nimport pandas as pd\n\nnp.set_printoptions(precision=6)\n\n\ndef featureNormalize(X):\n    \"\"\"Normalizes the features in X\n\n    featureNormalize(X) returns a normalized version of X where\n    the mean value of each feature is 0 and the standard deviation\n    is 1. This is often a good preprocessing step to do when\n    working with learning algorithms.\n    :param X:\n    :return:\n    \"\"\"\n    X_norm = pd.DataFrame()\n    mu = []\n    sigma = []\n    for i in range(X.shape[1]):\n        temp = np.array(X.iloc[:, i])\n        mu.append(np.mean(temp))\n        sigma.append(np.std(temp))\n        X_norm[i] = (temp - mu[i]) / sigma[i]\n\n    return X_norm, mu, sigma\n\n\ndef computeCostMulti(X, y, theta):\n    \"\"\"Compute cost for linear regression with multiple variables\n\n    J = computeCostMulti(X, y, theta) computes the cost of using theta as the\n    parameter for linear regression to fit the data points in X and y\n    :param X:\n    :param y:\n    :param theta:\n    :return:\n    \"\"\"\n    # Initialize some useful values\n    m = len(y)  # number of training examples\n    diff = np.matmul(X, theta) - y\n    J = 1 / (2 * m) * np.matmul(diff, diff)\n    return J\n\n\ndef gradientDescentMulti(X, y, theta, alpha, num_iters):\n    \"\"\"Performs gradient descent to learn theta\n\n    theta = gradientDescentMulti(x, y, theta, alpha, num_iters) updates theta by\n    taking num_iters gradient steps with learning rate alpha\n    :param X:\n    :param y:\n    :param theta:\n    :param alpha:\n    :param num_iters:\n    :return:\n    \"\"\"\n    # Initialize some useful values\n    m = len(y)  # number of training examples\n    J_history = []\n\n    for i in range(num_iters):\n        theta -= alpha / m * np.matmul(X.transpose(), np.matmul(X, theta) - y)\n        # Save the cost J in every iteration\n        J_history.append(computeCostMulti(X, y, theta))\n\n    return theta, J_history\n\n\ndef normalEqn(X, y):\n    \"\"\"Computes the closed-form solution to linear regression\n\n    normalEqn(X,y) computes the closed-form solution to linear\n    regression using the normal equations.\n    :param X:\n    :param y:\n    :return:\n    \"\"\"\n    theta = np.matmul(np.matmul(np.linalg.inv(np.matmul(X.transpose(), X)), X.transpose()), y)\n    return theta\n", "meta": {"hexsha": "aef3c4bbcf579b313201f004a82e0ab99137f68c", "size": 2216, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine-learning-python/machine-learning-ex1/ex1_multi.py", "max_stars_repo_name": "StevenPZChan/ml_dl_coursera_Andrew_Ng", "max_stars_repo_head_hexsha": "c14f3490007392c16547e429c3028e9c80221013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-01-26T11:17:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T09:26:12.000Z", "max_issues_repo_path": "machine-learning-python/machine-learning-ex1/ex1_multi.py", "max_issues_repo_name": "StevenPZChan/ml_dl_coursera_Andrew_Ng", "max_issues_repo_head_hexsha": "c14f3490007392c16547e429c3028e9c80221013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "machine-learning-python/machine-learning-ex1/ex1_multi.py", "max_forks_repo_name": "StevenPZChan/ml_dl_coursera_Andrew_Ng", "max_forks_repo_head_hexsha": "c14f3490007392c16547e429c3028e9c80221013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-12T10:38:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-02T14:42:12.000Z", "avg_line_length": 27.3580246914, "max_line_length": 94, "alphanum_fraction": 0.6439530686, "include": true, "reason": "import numpy", "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.9124361557147439, "lm_q1q2_score": 0.8644247229155472}}
{"text": "import numpy as np\n\na = np.array([[1,2,3],\n         [4,5,6]],\n         dtype=np.int)\n\nprint(a.ndim)\nprint(a.shape)\nprint(a.dtype)\n\n# 生成0矩阵\na = np.zeros((3,4), dtype=np.int16)\nprint(a)\n\n# 生成随机数矩阵\na = np.empty((2,3))\nprint(a)\n\n# 类似range\na = np.arange(12).reshape((3, 4))\nprint(a)\n\n# 生成几段\na = np.linspace(1, 10, 6).reshape((2,3))\nprint(a)\n\na = np.array([10, 20, 30, 40])\nb = np.arange(4)\nprint(a-b)\nprint(a+b)\nprint(a*b)\n\nb = b ** 2\nprint(b)\nprint(b==0)\n\n# 矩阵相乘\nc = np.dot(a, b)\nprint(c)\n\n# 生成0~1的数字\na = np.random.random((2,4))\nprint(a)\n\n# axis=1 对行运算；axis=0 对列运算\nprint(np.sum(a, axis=1))\nprint(np.max(a))\nprint(np.min(a))\n\n\na = np.arange(2, 14).reshape((3,4))\nprint(np.argmax(a))\nprint(np.argmin(a))\n\n# 平均值\nprint(np.mean(a))\nprint(a.mean())\n\n# 中位数\nprint(np.median(a))\n\n# 元素累加 输出一个向量\nprint(np.cumsum(a))\n\n# 元素差\nprint(np.diff(a))\n\n# 排序\nprint(np.sort(a))\n\n# 转置\nprint(np.transpose(a))\nprint(a.T)\n# 变化小于3大于5的数\nprint(np.clip(a, 3, 5))\n\na = np.arange(3, 15).reshape((3,4))\nprint(a)\n\n# 打印出所有数\nprint(a[:1, :])\n\n# flatten() 合并矩阵\nprint(a.flatten())\nfor item in a.flat:\n    print(item)\n\n\n# 合并矩阵\na = np.array([1, 1, 1])\nb = np.array([2, 2, 2])\n\n# 上下合并\nc = np.vstack((a,b))\nprint(c)\nprint(c.shape)\n\n# 左右合并\nd = np.hstack((a,b))\nprint(d)\nprint(d.shape)\n\n# 横向数列变为纵向数列\nprint(a.reshape(a.size,1))\nprint(a[:, np.newaxis])\na = a[:, np.newaxis]\nb = b[:, np.newaxis]\nprint(a, b)\n\n#\nc = np.concatenate((a,b,b), axis=1)\nprint(c)\n\n#numpy 的分割\na = np.arange(12).reshape((3,4))\nprint(a)\n\n# 横向分割\nc = np.split(a, 3, axis=0)\nprint(c)\n\n# 纵向分割\nc = np.split(a, 2, axis=1)\nprint(c)\n\n# 不等分割\nc = np.split(a, [1,1,2], axis=1)\nprint(c)\n\nc = np.array_split(a, 3, axis=1)\nprint(c)\n\nc = np.hsplit(a, [1,1,2])\nprint(c)\n\n#from copy import deepcopy,copy\n\n# numpy的赋值\na = np.array([0, 1, 2, 3])\nb = a\nc = a\nd = a\na[0] = 4\n\nprint(a)\nprint(b)\nprint(c)\nprint(d)\n\n# deepcopy\nb = a.copy()\na[0] = 5\nprint(a)\nprint(b)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "b09aeae6881801fa147d097bbdf58dc7adcbde81", "size": 1878, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy/sample_numpy.py", "max_stars_repo_name": "zjhdota/practice", "max_stars_repo_head_hexsha": "de28003e7adf6140dfc06a1ffa3a808e514dbbc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-10T11:08:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-10T11:08:48.000Z", "max_issues_repo_path": "numpy/sample_numpy.py", "max_issues_repo_name": "zjhdota/practice", "max_issues_repo_head_hexsha": "de28003e7adf6140dfc06a1ffa3a808e514dbbc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-31T04:21:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-31T04:21:48.000Z", "max_forks_repo_path": "numpy/sample_numpy.py", "max_forks_repo_name": "zjhdota/practice", "max_forks_repo_head_hexsha": "de28003e7adf6140dfc06a1ffa3a808e514dbbc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 10.9186046512, "max_line_length": 40, "alphanum_fraction": 0.5846645367, "include": true, "reason": "import numpy", "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.9241418199787564, "lm_q1q2_score": 0.8643928292467933}}
{"text": "# MSDS 400 Module 6 Practice 1\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n'''\nextrema() is a classification function used to evaluate a trio of points.\nThe function will evaluate the middle point of trio to determine if it\nrepresents a relative maxima or minima for the trio. The result will be\na boolean value True or False which will be used later.  Note that if the\nmiddle point is not an extrema, the value False will be returned.\n'''\n\ndef extrema(a, b, c):\n    x = max(a, b, c)\n    z = min(a, b, c)\n    epsilon = 0.0000001  # This is a safeguard against minor differences.\n    result = False\n    if abs(b - x) < epsilon:\n        result = True\n    if abs(b - z) < epsilon:\n        result = True\n    return result\n\n\n# This is a user supplied function.  Example is Lial Figure 8 Section 13.1.\n\ndef f(x):\n    y = (x ** 8) ** .333 - 16.0 * (x ** 2) ** .33\n    return y\n\n\n# The following extrema evaluation will be over a defined interval. Grid points\n# will be defined and the function extreme() will compare trios of values.\n\n# Define interval endpoints for a closed interval [xa,xb].\nxa = -1.0\nxb = +9.0\n\n'''\nn = number of grid points.  The interval [xa,xb] will be subdivided.\nAdding delta to xb insures xb is included in the array generated.  For this\npurpose, np.arange() will be used to create a numpy array of floating point\nvalues to be used in subsequent calculations.\n'''\nn = 1000\ndelta = (xb - xa) / n\nx = np.arange(xa, xb + delta, delta)\ny = f(x)\n\nvalue = [False]  # This defines the list value which will contain Boolean values.\nvalue = value * len(x)  # This expands the list to the length of x.\n\n'''\nWe are going to check each trio of points during the grid search.\nIf a local extrema is found, the boolean value will be set to True.\nOtherwise it will remain False. The interval endpoints are always local\nextrema so we define their boolean values first.\n'''\nL = len(x)\nvalue[0] = True  # This will correspond to one endpoint.\nvalue[L - 1] = True  # This corresponds to the other.\n\n'''\nThe for loop will check each consecutive trios of f values with the function\nextrema() to identify local extrema.  Only when an extrema is found will the\nboolean value in the list value be changed to True.\n'''\n\nfor x_index in range(L - 2):\n    first_x = x[x_index]\n    second_x = x[x_index + 1]\n    third_x = x[x_index + 2]\n    a = f(first_x)\n    b = f(second_x)\n    c = f(third_x)\n    is_second_x_extrema = extrema(a, b, c)\n    value[x_index + 1] = is_second_x_extrema\n\nfor k in range(L - 2):\n    value[k + 1] = extrema(f(x[k]), f(x[k + 1]), f(x[k + 2]))\n\nmax_value = max(y)  # We check the list to find the global maxima.\nmin_value = min(y)  # We check the list to find the global minima.\n'''\nThe following for loop checks the boolean value for each point. If the value\nis True, that point will be plotted yellow.  The global maximum is plotted as\nred and the minimum is plotted as green. We follow this up by plotting the\nvalues of x and y.\n'''\nerror = 0.0000001  # The error parameter guards against roundoff error.\n# The code which follows assigns colors to maxima and minima and plots them.\n\nplt.figure()\nfor k in range(L):\n    if value[k] is True:\n        plt.scatter(x[k], y[k], s=60, c='y')\n        if abs(max_value - y[k]) < error:\n            plt.scatter(x[k], y[k], s=60, c='r')\n        if abs(min_value - y[k]) < error:\n            plt.scatter(x[k], y[k], s=60, c='b')\n\nplt.plot(x, y, c='k')  # This plots the line on the chart.\nplt.xlabel('x-axis')\nplt.ylabel('y-axis')\nplt.title('Plot Showing Absolute and Relative Extrema')\nplt.show()\n\n'''\nExercise #1:  Refer to Lial Section 13.1 Example 2. Reproduce Figure 7.\n\nExercise #2: Refer to Lial Section 14.1 Example 3.  Evaluate over the\ninterval [0,10] and produce a plot showing maxima and minima.  Compare to\nthe answer sheet.\n'''", "meta": {"hexsha": "2c804dbfab40eb81b5531be60a741d6cd3c42ec8", "size": 3804, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Module 6/practice/practice_1.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Module 6/practice/practice_1.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Module 6/practice/practice_1.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3684210526, "max_line_length": 81, "alphanum_fraction": 0.6824395373, "include": true, "reason": "import numpy", "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.9241418215456966, "lm_q1q2_score": 0.8643928257158263}}
{"text": "import numpy as np\n\n\nclass RosenbrockProvider:\n    \"\"\"\n    Rosenbrock function and it's gradient and hessian matrix\n    \"\"\"\n    @staticmethod\n    def f(x1, x2):\n        return 100 * (x2 - x1 ** 2) ** 2 + (1 - x1) ** 2\n\n    @staticmethod\n    def grad(x1, x2):\n        g1 = -400 * (x2 - x1 ** 2) * x1 + 2 * (x1 - 1)\n        g2 = 200 * (x2 - x1 ** 2)\n        return np.array([g1, g2])\n\n    @staticmethod\n    def hessian(x1, x2):\n        return np.array([\n            [400 * (3 * x1 ** 2 - x2) + 2, -400 * x1],\n            [-400 * x1, 200]\n        ])\n\n\nclass LeastSquares:\n    \"\"\"\n    Least Squares function and it's gradient and hessian matrix\n    \"\"\"\n    def __init__(self, A, b):\n        A_shape = np.shape(A)\n        b_shape = np.shape(b)\n        print(A_shape, b_shape)\n        assert len(b_shape) == 1 and len(A_shape) == 2 and b_shape[0] == A_shape[0] == A_shape[1]\n        self.A = A\n        self.b = b\n\n    def f(self, *x):\n        return sum((np.dot(self.A, x) - self.b)**2)\n\n    def grad(self, *x):\n        ax_b = np.dot(self.A, x) - self.b\n        return 2 * np.dot(self.A.T, ax_b)\n\n    def hessian(self, *x):\n        return 2 * np.dot(self.A.T, self.A)\n", "meta": {"hexsha": "3258a9a4ea36504e667113a51fcf13e6d66276e1", "size": 1162, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW2/functions.py", "max_stars_repo_name": "1997alireza/Optimization", "max_stars_repo_head_hexsha": "a81178b0ea10b6c762988231c781b6eb9e73fe7e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-19T03:35:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-19T14:15:10.000Z", "max_issues_repo_path": "HW2/functions.py", "max_issues_repo_name": "1997alireza/Optimization-Homework", "max_issues_repo_head_hexsha": "a81178b0ea10b6c762988231c781b6eb9e73fe7e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW2/functions.py", "max_forks_repo_name": "1997alireza/Optimization-Homework", "max_forks_repo_head_hexsha": "a81178b0ea10b6c762988231c781b6eb9e73fe7e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-18T06:19:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T06:19:46.000Z", "avg_line_length": 24.7234042553, "max_line_length": 97, "alphanum_fraction": 0.5017211704, "include": true, "reason": "import numpy", "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138196557983, "lm_q2_score": 0.8840392756357326, "lm_q1q2_score": 0.8643374169075572}}
{"text": "import numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\n\n\n# define a problem to solve\ndef f(x, a, b, c):\n    '''\n    evaluates a quadratic polynomial at location x\n    expects x,a,b to be column vectors and c to be a scalar constant\n    '''\n    return (x.T**2 @ a) + (x.T @ b) + c \n\n\ndef fprime(x, a, b):\n    '''\n    evaluates the gradient of quadratic polynomial\n    '''\n    return ((2 * x) * a) + b\n\n\ndef linear_ineq_constraint(x, y, m, b, less_eq=True):\n    '''\n    implement a linear inequality constraint, return True if constraint    \n    is satisfied, False otherwise\n    '''\n    return  m * x + b <= y if less_eq else m * x + b >= y\n\n\n# define gradient descent procedure\ndef grad_descent(x_init, nsteps, eta, fprime):\n    dim = x_init.shape[0]\n    trajectory = np.zeros((nsteps + 1, dim))\n    trajectory[0,:] = x_init.squeeze()\n    x = x_init\n    for i in range(nsteps):\n        x -= eta * fprime(x)\n        trajectory[i+1,:] = x.squeeze()\n    return x, trajectory\n\n\ndef constrained_grad_descent(x_init, nsteps, eta, fprime, constraints, bounce_dirs):\n    dim = x_init.shape[0]\n    trajectory = np.zeros((nsteps + 1, dim))\n    trajectory[0,:] = x_init.squeeze()\n    x = x_init\n    for i in range(nsteps):\n        # first check for constraints\n        constraintViolated = False\n        \n        for j, constraint in enumerate(constraints):\n            if not constraint(*x.squeeze()):\n                constraintViolated = True\n                break\n        \n        # if constraint is violated bounce\n        if constraintViolated:\n            x += bounce_dirs[j][:, None]\n\n        # else take regular optimization step\n        else:\n            if i < nsteps - 1:  # exclude last step to avoid \n                                # jumping into the constrained \n                                # area on the last step with no \n                                # chance to bounce back\n                x -= eta * fprime(x)\n        \n        trajectory[i+1,:] = x.squeeze()\n    \n    return x, trajectory\n\n\n###########################################\n# set up constrained optimization problem #\n###########################################\n\nx1 = np.linspace(-10, 10, 100)\nx2 = np.linspace(-10, 10, 100)\n\nX1, X2 = np.meshgrid(x1, x2)\n\nx = np.array([X1.flatten(), X2.flatten()])\na = np.array([[3.], [4.]])\nb = np.array([[1.],[1.]])\nc = 0\n\n# evaluate function at each location\ny = f(x, a, b, c)\nY = np.reshape(y, X1.shape)\n\n# add some constraints\n# first constraint\nm1 = 1\nb1 = 3\n\nconstraint1 = [1 if linear_ineq_constraint(a, b, m1, b1) else 0 for a, b in x.T]\nconstraint1 = np.reshape(constraint1, X1.shape)\n\n# second constraint\nm2 = -1\nb2 = 3\n\nconstraint2 = [1 if linear_ineq_constraint(a, b, m2, b2, less_eq=False) else 0 for a, b in x.T]\nconstraint2 = np.reshape(constraint2, X1.shape)\n\nx_init = np.array([[-10.],[-5.]])\n\nbounce_size = 0.03\nconstraints = [lambda x, y: linear_ineq_constraint(x, y, m1, b1), lambda x, y: linear_ineq_constraint(x, y, m2, b2, less_eq=False)]\nbounce_dirs = np.array([[-1, 1], [-1, -1]]) * bounce_size\n\nx_min, constrained_trajectory = constrained_grad_descent(x_init, 3000, 0.01, lambda x: fprime(x, a, b), constraints, bounce_dirs)\nprint(x_min, constrained_trajectory)\n# plot\nconstraint_cmap = matplotlib.colors.ListedColormap([[186/255, 0, 0, 1], [1, 1, 1, 0]])  # transparent for 0, filled in for 1\n\nplt.figure()\nplt.contourf(X1, X2, Y, cmap='binary')\nplt.plot(x1, m1 * x1 + b1, color='red')\nplt.plot(x1, m2 * x1 + b2, color='red')\nplt.contourf(X1, X2, constraint1, cmap=constraint_cmap, alpha=.3)\nplt.contourf(X1, X2, constraint2, cmap=constraint_cmap, alpha=.3)\nplt.plot(constrained_trajectory[:,0], constrained_trajectory[:,1], color='black', marker='.')\nplt.xlim([-10, 10])\nplt.ylim([-10, 10])\nplt.show()\n\n# # define a range for evaluation and plotting\n# x1 = np.linspace(-10, 10, 100)\n# x2 = np.linspace(-10, 10, 100)\n\n# X1, X2 = np.meshgrid(x1, x2)\n\n# x = np.array([X1.flatten(), X2.flatten()])\n# a = np.array([[3.], [4.]])\n# b = np.array([[1.],[1.]])\n# c = 0\n\n# # evaluate function at each location\n# y = f(x, a, b, c)\n# Y = np.reshape(y, X1.shape)\n\n# define some constraints\n\n\n# plot surface\n# plt.figure()\n# ax = plt.axes(projection='3d')\n# ax.plot_surface(X1, X2, Y, cmap='viridis')\n# plt.show()\n\n# # solve unconstrained problem with gradient descent and plot\n# x_init = np.array([[10.],[9.]])\n\n# x_min, trajectory = grad_descent(x_init, 3000, 0.01, lambda x: fprime(x, a, b))\n\n# plt.figure()\n# plt.contourf(X1, X2, Y)\n# plt.plot(trajectory[:,0], trajectory[:,1], color='black', marker='.')\n# plt.show()\n\n\n", "meta": {"hexsha": "ec2145127dbdd9e3d09f020fc72cbeb67312d4ca", "size": 4595, "ext": "py", "lang": "Python", "max_stars_repo_path": "quadratic_optim.py", "max_stars_repo_name": "DanielAnthes/SNNConvexOptim", "max_stars_repo_head_hexsha": "7bb182877aba264aec29296035f803c20eba664d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quadratic_optim.py", "max_issues_repo_name": "DanielAnthes/SNNConvexOptim", "max_issues_repo_head_hexsha": "7bb182877aba264aec29296035f803c20eba664d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quadratic_optim.py", "max_forks_repo_name": "DanielAnthes/SNNConvexOptim", "max_forks_repo_head_hexsha": "7bb182877aba264aec29296035f803c20eba664d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0182926829, "max_line_length": 131, "alphanum_fraction": 0.60609358, "include": true, "reason": "import numpy", "num_tokens": 1350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966101527047, "lm_q2_score": 0.905989826094673, "lm_q1q2_score": 0.8642835824227025}}
{"text": "# weighted mean tutorial - real time example\n# https://www.hackerrank.com/challenges/s10-weighted-mean/tutorial\n\nimport numpy as np\n\n\ndef weighted_mean(values: list, costs: list) -> float:\n    total_weight = sum([val * cost for val, cost in zip(values, costs)])\n    weighted_avg = total_weight / sum(costs)\n    return '%.1f' % weighted_avg\n\n\nif __name__ == '__main__':\n    data = [10, 40, 30, 50, 20]\n    weights = [1, 2, 3, 4, 5]\n    print(weighted_mean(data, weights))\n\n    # using numpy\n    avg = np.average(np.array(data), weights=np.array(weights))\n    print(avg)\n\n", "meta": {"hexsha": "8a25d81bdffe121af59ed55657d4e43d69fbe29f", "size": 570, "ext": "py", "lang": "Python", "max_stars_repo_path": "day0/p02weighted_mean.py", "max_stars_repo_name": "chaithrakc/hackerrank-10-days-of-statistics", "max_stars_repo_head_hexsha": "f558ba74a62caea9eaea1889bfd4867fc7b53220", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day0/p02weighted_mean.py", "max_issues_repo_name": "chaithrakc/hackerrank-10-days-of-statistics", "max_issues_repo_head_hexsha": "f558ba74a62caea9eaea1889bfd4867fc7b53220", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day0/p02weighted_mean.py", "max_forks_repo_name": "chaithrakc/hackerrank-10-days-of-statistics", "max_forks_repo_head_hexsha": "f558ba74a62caea9eaea1889bfd4867fc7b53220", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9090909091, "max_line_length": 72, "alphanum_fraction": 0.6649122807, "include": true, "reason": "import numpy", "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615412, "lm_q2_score": 0.9073122269997507, "lm_q1q2_score": 0.8642821560543369}}
{"text": "import numpy as np\n\ndef median_bins(values, B):\n    mean = np.mean(values)\n    std_dev = np.std(values)\n    min_val = mean - std_dev\n    max_val = mean + std_dev\n    \n    left_bin = 0\n    bins = np.zeros(B)\n    bin_width = 2 * std_dev / B\n    \n    for value in values:\n        if value < min_val:\n            left_bin += 1\n        elif value < max_val:\n            current_bin = int((value - min_val) / bin_width)\n            bins[current_bin] += 1\n    \n    return mean, std_dev, left_bin, bins\n\ndef median_approx(values, B):\n    mean, std_dev, left_bin, bins = median_bins(values, B)\n    \n    n = len(values)\n    mid = (n + 1) / 2\n    \n    count = left_bin\n    for b, bin_count in enumerate(bins):\n        count += bin_count\n        if count >= mid:\n            break\n    \n    bin_width = 2 * std_dev / B\n    median = mean - std_dev + bin_width * (b + 0.5)\n    \n    return median\n\nif __name__ == '__main__':\n    # Test Case 1\n    print(median_bins([1, 1, 3, 2, 2, 6], 3))\n    print(median_approx([1, 1, 3, 2, 2, 6], 3))\n\n    # Test Case 2\n    print(median_bins([1, 5, 7, 7, 3, 6, 1, 1], 4))\n    print(median_approx([1, 5, 7, 7, 3, 6, 1, 1], 4))\n\n    # Test Case 3\n    print(median_bins([0, 1], 5))\n    print(median_approx([0, 1], 5))\n", "meta": {"hexsha": "b8a830bbcb5ea936a32c1c22fd234f7bb08efca4", "size": 1235, "ext": "py", "lang": "Python", "max_stars_repo_path": "week1/2a/4_binapprox/program.py", "max_stars_repo_name": "jensmcatanho/data-driven_astronomy", "max_stars_repo_head_hexsha": "46c32361378421079a7114e96c3c0fe8451748bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week1/2a/4_binapprox/program.py", "max_issues_repo_name": "jensmcatanho/data-driven_astronomy", "max_issues_repo_head_hexsha": "46c32361378421079a7114e96c3c0fe8451748bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week1/2a/4_binapprox/program.py", "max_forks_repo_name": "jensmcatanho/data-driven_astronomy", "max_forks_repo_head_hexsha": "46c32361378421079a7114e96c3c0fe8451748bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2156862745, "max_line_length": 60, "alphanum_fraction": 0.5457489879, "include": true, "reason": "import numpy", "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995762509215, "lm_q2_score": 0.8947894731166139, "lm_q1q2_score": 0.8642767729171227}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n\nHELIXLIB - A SET OF FUNCTIONS TO CONSTRUCT AND MANIPULATE HELICAL OBJECTS\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nimport csv\nimport logging as log\n\ndef getUnitVector(vi, vj, vk):\n    v = np.array([vi, vj, vk])\n    mag = np.linalg.norm(v)\n    unitVector = v/mag\n    return unitVector\n    \n\ndef calculateHelixPoints(R, startDepth, thetaStart, thetaEnd, numOfPoints, parameterB, isOuterProfile):\n    x = np.array([])\n    y = np.array([])\n    z = np.array([])\n    ni = np.array([])\n    nj = np.array([])\n    nk = np.array([])\n    inc = (thetaEnd-thetaStart)/(numOfPoints-1)\n    for i in range(numOfPoints):\n        theta = thetaStart + inc * i\n        x = np.append(x, R * np.cos(theta))\n        y = np.append(y, R * np.sin(theta))\n        z = np.append(z, parameterB * theta)  \n        if isOuterProfile:\n            normalUnitVector = getUnitVector(R*(R**2+parameterB**2)*np.cos(theta), R*(R**2+parameterB**2)*np.sin(theta), 0)\n            ni = np.append(ni, normalUnitVector[0])\n            nj = np.append(nj, normalUnitVector[1])\n            nk = np.append(nk, normalUnitVector[2])\n        else:\n            normalUnitVector = getUnitVector(-R*(R**2+parameterB**2)*np.cos(theta), -R*(R**2+parameterB**2)*np.sin(theta), 0)\n            ni = np.append(ni, normalUnitVector[0])\n            nj = np.append(nj, normalUnitVector[1])\n            nk = np.append(nk, normalUnitVector[2])\n    \n    if z[0] < 0:\n        z = z + np.abs(z[0]) + startDepth\n    else:\n        z = z - z[0] + startDepth\n    return [x, y, z, ni, nj, nk]\n\n\ndef storeHelixData(helixDataFilePath, helix):\n    with open(helixDataFilePath, 'w', newline='') as csvfile:\n     helixwriter = csv.writer(csvfile, delimiter=',',\n                             quotechar='|', quoting=csv.QUOTE_MINIMAL)\n     helixwriter.writerow(['x'] + ['y'] + ['z'] + ['Ni'] + ['Nj'] + ['Nk'])\n     x = helix[0]\n     y = helix[1]\n     z = helix[2]\n     ni = helix[3]\n     nj = helix[4]\n     nk = helix[5]    \n     for i in range(len(x)):\n         helixwriter.writerow([x[i] , y[i] , z[i], ni[i], nj[i], nk[i]])\n\n\ndef plotHelix(helix):\n    fig = plt.figure()\n    ax1 = fig.add_subplot(111, projection='3d')\n    x = helix[0]\n    y = helix[1]\n    z = helix[2]\n    ax1.plot( x, y, z, c='b', label='Helix')\n    plt.legend(loc='upper left');\n    plt.axis('equal')\n    plt.show()\n\n  \ndef degreeToRadians(thetaDeg):\n    return thetaDeg * np.pi/180.0\n  \n\ndef buildHelix(R, startDepth, thetaStart, numberOfRevolutions, numOfPointsPerRev, pitch, isOuterProfile, helixFileFullName):\n    numOfPoints = int(numberOfRevolutions * numOfPointsPerRev)    \n    thetaStart = degreeToRadians(thetaStart)\n    thetaEnd = degreeToRadians(numberOfRevolutions * 360)\n    parameterB = pitch/(2*np.pi)    \n    helix = calculateHelixPoints(R, startDepth, thetaStart, thetaEnd, numOfPoints, parameterB, isOuterProfile)\n    storeHelixData(helixFileFullName, helix)\n    plotHelix(helix)    ", "meta": {"hexsha": "9544f0894b00ed394931fd4f9023ad9a08d420da", "size": 2981, "ext": "py", "lang": "Python", "max_stars_repo_path": "helixLib.py", "max_stars_repo_name": "elkott/PyHelix", "max_stars_repo_head_hexsha": "3c68fa18e5cf4017a91bd3352d6058b534895535", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "helixLib.py", "max_issues_repo_name": "elkott/PyHelix", "max_issues_repo_head_hexsha": "3c68fa18e5cf4017a91bd3352d6058b534895535", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "helixLib.py", "max_forks_repo_name": "elkott/PyHelix", "max_forks_repo_head_hexsha": "3c68fa18e5cf4017a91bd3352d6058b534895535", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7582417582, "max_line_length": 125, "alphanum_fraction": 0.604159678, "include": true, "reason": "import numpy", "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995762509216, "lm_q2_score": 0.8947894646997281, "lm_q1q2_score": 0.8642767647872563}}
{"text": "import numpy as np\n\n# Function\ndef f(x):\n    y = 1 / np.sqrt(2 * np.pi) * np.exp(-x ** 2 / 2)\n    return y\n\n# General Romberg Method\ndef Romberg(a, b, tol):\n    R = np.zeros((50, 50))\n    h = b - a\n\n    # We compute the first column of Romberg array with Trapezoid Method\n    R[1][1] = 0.5*h*(f(a) + f(b))\n\n    for i in range(2, 50+1):\n        R[i][1] = 0.5*R[i-1][1]\n\n        for k in range(1, int(pow(2, i-2)+1)):\n            R[i][1] += 0.5 * h * f(a + (k-0.5)*h)\n\n        # There we start computing elements from the other columns\n        for j in range(2, i+1):\n            R[i][j] = R[i][j-1] + (1./(pow(4, j-1)-1))*(R[i][j-1] - R[i-1][j-1])\n\n        d = np.abs((R[i][i]-R[i-1][i-1])/R[i][i])\n\n        if(d < tol):\n            break\n\n        h = 0.5 * h\n\n    I = R[i][j]\n    dI = d * I\n\n    return I, dI, d\n\nif __name__ == \"__main__\":\n    print('\\nComputated with General Romberg Method:')\n    print(f\"\\tI ± δI = {Romberg(-5, 5, 0.001)[0]:.8f} ± {Romberg(-5, 5, 0.001)[1]:.8f}\")\n    print(f'\\tThe relative error is η = {Romberg(-5, 5, 0.001)[2]:.5f} < 0.1 %')", "meta": {"hexsha": "2f73c637f43c67555494d9cc80b7501beca56483", "size": 1064, "ext": "py", "lang": "Python", "max_stars_repo_path": "Integration/General-Romberg-Method.py", "max_stars_repo_name": "AlexTsagas/Computational-Physics", "max_stars_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Integration/General-Romberg-Method.py", "max_issues_repo_name": "AlexTsagas/Computational-Physics", "max_issues_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Integration/General-Romberg-Method.py", "max_forks_repo_name": "AlexTsagas/Computational-Physics", "max_forks_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9512195122, "max_line_length": 88, "alphanum_fraction": 0.4793233083, "include": true, "reason": "import numpy", "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321452198369, "lm_q2_score": 0.8962513703624558, "lm_q1q2_score": 0.8642744230027016}}
{"text": "\"\"\"\nSingular value decomposition and expansion.\n\"\"\"\n\nfrom linear_algebra import gramian\nfrom power_method import dominant_eigen_system\nimport math\nimport numpy as np\n\n\ndef find_u_from_v(matrix, v, singular_value):\n    \"\"\"\n    Finds the u column vector of the U matrix in the SVD UΣV^T.\n\n    Parameters\n    ----------\n    matrix : numpy.ndarray\n        Matrix for which the SVD is calculated\n\n    v : numpy.ndarray\n        A column vector of V matrix, it is the eigenvector of the Gramian of `matrix`.\n\n    singular_value : float\n        A singular value of `matrix` corresponding to the `v` vector.\n\n    Returns\n    -------\n    numpy.ndarray\n        u column vector of the U matrix in the SVD.\n    \"\"\"\n\n    return matrix @ v / singular_value\n\n\ndef svd(matrix, max_eigenvalues, iterations):\n    \"\"\"\n    Performs reduced singular value decomposition of the matrix.\n\n    Parameters\n    ----------\n    matrix : numpy.ndarray\n        A matrix.\n\n    max_eigenvalues : int\n        Maximum number of non-zero eigenvalues to calculate.\n\n    iterations : int\n        The number of iterations of the power method.\n\n    Returns\n    -------\n    list of tuples (numpy.ndarray, float, numpy.ndarray)\n        List of tuples (u, sigma, v), where\n            `u` is a column vector of U matrix,\n            `sigma` is the corresponding singular value of `matrix`,\n                which are the diagonal entries of Σ matrix,\n            `v` is a column vector of V matrix\n        in `matrix = U Σ V^T` svd.\n    \"\"\"\n\n    svd_items = []\n\n    for iteration in range(max_eigenvalues):\n        matrix_gramian = gramian(matrix)\n        eigenvalue, v = dominant_eigen_system(matrix_gramian, iterations=iterations)\n\n        if eigenvalue == 0:\n            break\n\n        singular_value = math.sqrt(eigenvalue)\n        u = find_u_from_v(matrix, v=v, singular_value=singular_value)\n        svd_items.append((u, singular_value, v))\n\n        if iteration == (max_eigenvalues - 1):\n            break\n\n        # Calculate the first dominant term of the singular value expansion\n        dominant = u @ np.transpose(v) * singular_value\n\n        # Subtract the dominant term\n        matrix = matrix - dominant\n\n    return svd_items\n\n\ndef singular_value_expansion(data):\n    \"\"\"\n    Performs singular value expansion by reconstructing the original `matrix`\n    from its SVD UΣV^T.\n\n    Parameters\n    ----------\n    data : list of tuples\n        List of tuples produced by `svd` function: (u, sigma, v), where\n            `u`: numpy.ndarray is a column vector of U matrix,\n            `sigma`: float is the corresponding singular value of `matrix`,\n                which are the diagonal entries of Σ matrix,\n            `v`: numpy.ndarray is a column vector of V matrix\n        in `matrix = U Σ V^T` svd.\n\n    Returns\n    -------\n    numpy.ndarray\n        Matrix reconstructed form its SVD UΣV^T.\n    \"\"\"\n\n    if len(data) == 0:\n        return\n\n    col_number = len(data[0][0])\n    row_number = len(data[0][2])\n\n    matrix = np.zeros([col_number, row_number])\n\n    for data_item in data:\n        u = data_item[0]\n        singular_value = data_item[1]\n        v = data_item[2]\n\n        product = singular_value * (u @ np.transpose(v))\n        matrix = matrix + product\n\n    return matrix\n", "meta": {"hexsha": "3eaa83cf4653db6dce729d99d59a207178dcc121", "size": 3251, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/svd.py", "max_stars_repo_name": "evgenyneu/image_compressor_python", "max_stars_repo_head_hexsha": "f62e9353473e210f68f87d1ab8bff7deb7ceb0bc", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/svd.py", "max_issues_repo_name": "evgenyneu/image_compressor_python", "max_issues_repo_head_hexsha": "f62e9353473e210f68f87d1ab8bff7deb7ceb0bc", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/svd.py", "max_forks_repo_name": "evgenyneu/image_compressor_python", "max_forks_repo_head_hexsha": "f62e9353473e210f68f87d1ab8bff7deb7ceb0bc", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2177419355, "max_line_length": 86, "alphanum_fraction": 0.6204244848, "include": true, "reason": "import numpy", "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214532237354, "lm_q2_score": 0.8962513675912913, "lm_q1q2_score": 0.8642744212493944}}
{"text": "import numpy as np\n\n#X is matrix of m*d where m is no. of samples and d is no. of features\n#n is an integer >= 1 indiacting no. of components or n is a decimal between 0 and 1 indicating variance\n#returns reduced_x matrix of k*m where k is no. of reduced features and m no of samples\n\nclass PCA:\n    def __init__(self, n):\n        if n <1:\n            self.variance = n\n            self.choice=False\n        else:\n            self.n_components = n\n            self.choice = True\n        self.components = None\n        self.mean = None\n        self.std = None\n\n    def fit(self, X):\n        # Mean centering\n        self.mean = np.mean(X, axis=0)\n        self.std = np.std(X, axis=0)+0.00001 #adding af small value to prevent dividing by zero\n\n        X = (X - self.mean)/self.std\n\n        # covariance, function needs samples as columns\n        cov = np.cov(X.T)\n        # eigenvalues, eigenvectors\n        eigenvalues, eigenvectors = np.linalg.eig(cov)\n        # -> eigenvector v = [:,i] column vector, transpose for easier calculations\n        # sort eigenvectors\n        eigenvectors = eigenvectors.T\n        idxs = np.argsort(eigenvalues)[::-1]\n        eigenvalues = eigenvalues[idxs]\n        eigenvectors = eigenvectors[idxs]\n\n        if self.choice == True:\n            # store first n eigenvectors\n            self.components = eigenvectors[0:self.n_components]\n        else:\n            # Identifying components that explain at least variance equals n*100\n            variance_vector= []\n            for i in eigenvalues:\n                variance_vector.append((i / sum(eigenvalues)) * 100)\n            accumlated_variance = np.cumsum(variance_vector)\n            self.n_components = len(  accumlated_variance[  accumlated_variance< (self.variance * 100)])\n            self.components = eigenvectors[0:self.n_components]\n\n\n    def transform(self, X):\n        # project data\n        #X = (X - self.mean)/self.std\n        reduced_x=(np.dot(X, self.components.T)).T\n        return reduced_x\n\n\n#testing using iris dataset\n'''import pandas as pd\nimport matplotlib.pyplot as plt\nurl = \"https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\" # Get the IRIS dataset\ndata = pd.read_csv(url, names=['sepal length', 'sepal width', 'petal length', 'petal width', 'target'])\n# prepare the data\nx = data.iloc[:, 0:4]\n# prepare the target\ntarget = data.iloc[:, 4]\n\n# Applying it to PCA function(how to use PCA class)\n\npca=PCA(2)  #using no. components\n#pca=PCA(0.98)  #using variance\npca.fit(x)\nprint(x.shape)\nmat_reduced = (pca.transform(x)).T\nprint(mat_reduced.shape)\n# Creating a Pandas DataFrame of reduced Dataset\nprincipal_df = pd.DataFrame(mat_reduced, columns=['PC1', 'PC2'])\n# Concat it with target variable to create a complete Dataset\nfinalDf = pd.concat([principal_df, pd.DataFrame(target)], axis=1)\n\nfig = plt.figure(figsize = (8,8))\nax = fig.add_subplot(1,1,1)\nax.set_xlabel('Principal Component 1', fontsize = 15)\nax.set_ylabel('Principal Component 2', fontsize = 15)\nax.set_title('2 component PCA', fontsize = 20)\ntargets = ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']\ncolors = ['r', 'g', 'b']\nfor target, color in zip(targets,colors):\n    indicesToKeep = finalDf['target'] == target\n    ax.scatter(finalDf.loc[indicesToKeep, 'PC1']\n               , finalDf.loc[indicesToKeep, 'PC2']\n               , c = color\n               , s = 50)\nax.legend(targets)\nax.grid()\nplt.show()'''\n", "meta": {"hexsha": "21fccd9f3a4d1efeacf486aea7cb9b5b6c17acf9", "size": 3415, "ext": "py", "lang": "Python", "max_stars_repo_path": "mshtensorflow/PCA.py", "max_stars_repo_name": "adhamhesham97/Deep-Learning-framework", "max_stars_repo_head_hexsha": "7904b993fd7c45f4c0b7fbe028eacd3ce2773d7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mshtensorflow/PCA.py", "max_issues_repo_name": "adhamhesham97/Deep-Learning-framework", "max_issues_repo_head_hexsha": "7904b993fd7c45f4c0b7fbe028eacd3ce2773d7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-05T07:58:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-05T07:58:20.000Z", "max_forks_repo_path": "mshtensorflow/PCA.py", "max_forks_repo_name": "adhamhesham97/Deep-Learning-framework", "max_forks_repo_head_hexsha": "7904b993fd7c45f4c0b7fbe028eacd3ce2773d7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-25T14:50:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-24T22:07:12.000Z", "avg_line_length": 35.5729166667, "max_line_length": 104, "alphanum_fraction": 0.6424597365, "include": true, "reason": "import numpy", "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147113777896, "lm_q2_score": 0.8887587986487518, "lm_q1q2_score": 0.864242130672497}}
{"text": "import sympy as sy\nfrom sympy import *\n\n\"\"\"\n2x+8y=−40\n4x+16y=−79\n\"\"\"\n\nx, y, z = sy.symbols('x, y, z')\neq1 = sy.Eq(-7*x - 3*y + 3*z, 5)\neq2 = sy.Eq(-2*x + 5*y - 4*z, 5)\neq3 = sy.Eq(-27*x - 35*y + 31*z, 5)\n\neq4 = sy.Eq(10*x + 4*y - 6*z, -8)\neq5 = sy.Eq(20*x + 8*y - 12*z, -16)\neq6 = sy.Eq(35*x + 14*y + 21*z, -28)\n\neq7 = sy.Eq(5*x + 10*y + 19*z, 6)\neq8 = sy.Eq(-2*x - 3*y - 7*z, 1)\neq9 = sy.Eq(3*x + 6*y + 12*z, 9)\n\neq10 = sy.Eq(-7*x - 3*y + 3*z, 5)\neq11 = sy.Eq(-2*x + 5*y - 4*z, 5)\neq12 = sy.Eq(-27*x - 35*y + 31*z, 4)\n\nans1 = sy.solve((eq1, eq2, eq3), (x, y, z))\nprint(ans1)\nans2 = sy.solve((eq4, eq5, eq6), (x, y, z))\nprint(ans2)\nans3 = sy.solve((eq7, eq8, eq9), (x, y, z))\nprint(\"ans3:\",ans3)\nans4 = sy.solve((eq10, eq11, eq12), (x, y, z))\nprint(\"ans4:\",ans4)\n\neq13 = sy.Eq(x - 4*y - 4*z, -3)\neq14 = sy.Eq(x - 6*y - 8*z, 1)\neq15 = sy.Eq(-2*x + 11*y + 14*z, 0)\nans5 = sy.solve((eq13, eq14, eq15), (x, y, z))\nprint(\"ans5:\",ans5)\n\n\nM = Matrix([[1, -4, -4, -3], [1, -6, -8, 1], [-2, 11, 14, 0]])\n\n# Use sympy.rref() method\nM_rref = M.rref(pivots=True)\n\nprint(\"The Row echelon form of matrix M and the pivot columns : {}\".format(M_rref))\n\n\nh , k = sy.symbols('h, k')\neq16 = sy.Eq(-7*x + 7*y + 7*z, -6)\neq17 = sy.Eq(-2*x - 9*y - 5*z, 3)\neq18 = sy.Eq(11*x + 11*y + h*z, k)\nans6 = sy.solve((eq16, eq17, eq18), (x, y, z))\nprint(\"ans6:\",ans6)\n\n", "meta": {"hexsha": "6b288f80b07adec647122b1fdb1c06252eac34eb", "size": 1337, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "bab81/LinearAlgebra", "max_stars_repo_head_hexsha": "a1ad6991ce4a5c21c320bed82afffc89d7220729", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.py", "max_issues_repo_name": "bab81/LinearAlgebra", "max_issues_repo_head_hexsha": "a1ad6991ce4a5c21c320bed82afffc89d7220729", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "bab81/LinearAlgebra", "max_forks_repo_head_hexsha": "a1ad6991ce4a5c21c320bed82afffc89d7220729", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4561403509, "max_line_length": 83, "alphanum_fraction": 0.5153328347, "include": true, "reason": "import sympy,from sympy", "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97241471777321, "lm_q2_score": 0.8887587875995483, "lm_q1q2_score": 0.864242125612075}}
{"text": "from sympy import *\r\nimport numpy as np\r\nimport array as arr\r\n\r\ndef TongQuat(X, Y):\r\n    list ( zip(X , Y ) )\r\n    x = symbols('x')\r\n    m = len(X)\r\n    A = [[X[i] ** j for j in range (m) ] for i in range (m) ] \r\n    kq = np.linalg.solve(A,Y)\r\n    hamSo = ''\r\n    for i in range (len(kq)):\r\n        hamSo += '+%d*(x ** %d)' %(kq[i], i)\r\n    P = lambda x: eval(hamSo )\r\n    f1 = str(P(x))\r\n    f1 = eval(f1)\r\n    f1 = latex(f1)\r\n    return f1, A\r\n\r\n\r\n\r\ndef Newton(X, Y, pp):\r\n    X = [0.0,0.5,1.0,1.5,2.0] #mốc nội suy\r\n    Y = [-1.0,0.125,1.0,2.375,5.0]\r\n    n = len(X)\r\n    h = X[1]-X[0]\r\n    x , t = symbols ('x t')\r\n    sp = [ [d(k, i, Y) for i in range(n-k)] for k in range (n)]\r\n    if pp == 'Newton':\r\n        P = Y[0]\r\n        for k in range(1, n): # k chạy từ 1 tới n-1\r\n            prod = d(k, 0,Y)/factorial(k)\r\n            for i in range(k):\r\n                prod *= t - i\r\n            P += prod\r\n        P = P . subs (t , ( x - X [0]) / h) . expand()\r\n    if pp == 'Newton Lùi':\r\n        m = n-1\r\n        P = Y[m]\r\n        for k in range(1, n): \r\n            prod = d(k, m-k, Y)/factorial(k)\r\n            for i in range(k):\r\n                prod *= t + i\r\n            P += prod\r\n        P = P.subs(t, (x - X[m]) / h).expand()\r\n    print(P)\r\n    f1 = latex(P)\r\n    return f1, sp\r\n\r\ndef d (k , i, Y ) :\r\n    if k == 0:\r\n        return Y[i]\r\n    return d (k -1,i +1, Y ) - d (k -1 , i, Y )\r\n\r\n\r\ndef checkCondition(X, Y):\r\n    n = len(X)\r\n    h = X[1]-X[0]\r\n    if(len(X) != len(Y)):\r\n        return False\r\n    for i in range(0,n-1):\r\n        if(X[i+1] - X[i] != h):\r\n            return False\r\n    return True\r\n\r\ndef Lagrange(X,Y):\r\n    n = len(X)\r\n    x = symbols('x')\r\n    P = 0\r\n    for i in range (n) :\r\n        P += Y [i ] * L (i , x, n , X )\r\n    P = P.expand()\r\n    f1 = latex(P)\r\n    print(f1)\r\n    s = []\r\n    s1 = [] \r\n    for i in range(n):\r\n        a, b = L(i, x, n, X), L(i, x, n , X).expand()\r\n        s.append( latex(a))\r\n        s1.append( latex(b))\r\n    return f1, s, s1\r\ndef L (i , x, n, X ) :\r\n    prod = 1\r\n    for j in range (n) :\r\n        if j != i :\r\n            prod *= ( x - X[ j ]) / ( X [ i ] - X [ j ])\r\n    return prod\r\n\r\n", "meta": {"hexsha": "f78c75fe18454adb1e8daac4fce3de6493acbbf2", "size": 2159, "ext": "py", "lang": "Python", "max_stars_repo_path": "NoiSuy.py", "max_stars_repo_name": "minhhoccode/Interpolate-with-flask", "max_stars_repo_head_hexsha": "7f8cb8f551e9bd36beca911e0987b6c1bc168356", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NoiSuy.py", "max_issues_repo_name": "minhhoccode/Interpolate-with-flask", "max_issues_repo_head_hexsha": "7f8cb8f551e9bd36beca911e0987b6c1bc168356", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NoiSuy.py", "max_forks_repo_name": "minhhoccode/Interpolate-with-flask", "max_forks_repo_head_hexsha": "7f8cb8f551e9bd36beca911e0987b6c1bc168356", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2584269663, "max_line_length": 64, "alphanum_fraction": 0.390921723, "include": true, "reason": "import numpy,from sympy", "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715435, "lm_q2_score": 0.9046505351008904, "lm_q1q2_score": 0.8642299642015702}}
{"text": "'''Purpose of the module is to describe different matrix types in code'''\n\nimport numpy as np\n\n# Setting default random generator\nrng = np.random.default_rng(12345)\n\ndef get_square_matrix(n, random=False, integer=1):\n    '''Return a square matrix with integer scalaras. Whether random or specified'''\n\n    if random:\n        return rng.integers(50, size=(n, n))\n    else:\n        return np.ones((n, n), dtype=int) * integer\n\ndef get_symmetrical_matrix(n):\n    '''Return a matrix that's symetrical'''\n    # Creating permutations of rows\n    current_integer_list = [i for i in range(1, n+1)]\n    permutations = []\n    while(current_integer_list[-1] != 1):\n        permutations.append(current_integer_list[:])\n        current_integer_list.pop()\n        current_integer_list.insert(0, current_integer_list[0] + 1)\n    # To add the last row\n    permutations.append(current_integer_list[:])\n    return np.array(permutations)\n\ndef get_triangular_matrix(matrix, triangular_type):\n    '''Return a triangular matrix'''\n    if triangular_type == \"triup\":\n        return np.triu(matrix)\n    elif triangular_type == \"trile\":\n        return np.tril(matrix)\n    else:\n        raise ValueError(\"'tringular_type' is either wrong or empty.\")\n\ndef get_diagonal_matrix(diagonal_vector, extra_row=0, fill_value=0):\n    '''Return a diagonal matrix'''\n    rows = []\n    for index, value in enumerate(diagonal_vector):\n        row = [0]*len(diagonal_vector)\n        row[index] = value\n        rows.append(row)\n    counter = 0\n    while(counter < extra_row):\n        rows.append([fill_value]*len(diagonal_vector))\n        counter += 1\n    return np.array(rows)\n\ndef format_message_str(string):\n    '''Return re-formatted string for output messages.\n\n    It's expected a docstring with 4 spaces that delimits sentences\n    with some new lines at each end.\n    '''\n    string = string.strip()\n    return \"\\n\".join([line.strip() for line in string.split(\" \"*4)])\n\nif __name__ == \"__main__\":\n    # Square matrix\n    m = \"\"\"\n    Square matrices are a type of matrices where column and row are equal.\n    (since it's a square Duh). These types of matrices allow to be used in\n    matrix arithmetic with ease due to equal sizes.\"\"\"\n    print(format_message_str(m))\n    print('4 x 4 square matrix')\n    print(get_square_matrix(4, 4, True))\n    print(\"Let's do some square matrix arithmetic\")\n    A = get_square_matrix(5, 5, integer=2)\n    B = get_square_matrix(5, 5, integer=5)\n    print('A:\\n', A)\n    print('B:\\n', B)\n    print(\"Let's do some multiplication and division in the form of A * B and A / B\")\n    print(\"Multiplication:\\n\", A * B)\n    print(\"Division:\\n\", A / B)\n    print(\"Keep in mind that it multiplies across elements, not dot products\")\n    # Symmetrical matrix\n    m = \"\"\"\n    Symmetrical matrix is a square matrix that has values mirrored along a diagonal line.\n    The diagonal line consists of just '1' scalars and then each scalar get's incremented to left and right\n    sides of the diagonal line.\n    For example, a matrix with 16 dimension size would look like this:\n    \"\"\"\n    print(format_message_str(m))\n    print(\"\\n\", get_symmetrical_matrix(16))\n    print(\"It has to be a square such that the values can be mirrored\")\n\n    # Triangular matrix\n    m = \"\"\"\n    Triangular matrix is a square matrix where a part of matrix\n    (in a shape of a 'square') has values on one side of diagonal\n    line and the other one has zeros.\n\n    Triangular matrix can be characterised by either 'triangular up' (scalar values above\n    diagonal line) and 'triangular down' (scalar values below diagonal line).\n\n    For example a 5x5 trinagular matrix would like this:\n    \"\"\"\n    print(format_message_str(m))\n    m = get_square_matrix(5, random=True)\n    print(get_triangular_matrix(m, \"trile\"))\n    print(\"or this:\")\n    print(get_triangular_matrix(m, \"triup\"))\n    m = \"\"\"\n    Functions that can perform the formatting of these matrices are `numpy.tril`\n    and `numpy.triu`.\n    \"\"\"\n    print(format_message_str(m))\n    # Diagonal matrix\n    m = \"\"\"\n    Diagonal matrix is a type of matrix that has values alongside a diagonal line.\n    This diagonal line is usually called a 'diagonal vector'. Usually scalar values\n    are line up diagonally and the rest tend to be 0's. For example:\n    \"\"\"\n    print(format_message_str(m))\n    print(get_diagonal_matrix([3, 5, 68, 79, 666]))\n    m = \"\"\"\n    Keep in mind that the matrix doesn't have to be a square matrix since the diagonal vector's\n    last value needs to reach at the last column of the column. For example.\n    \"\"\"\n    print(format_message_str(m))\n    print(get_diagonal_matrix([3, 5, 68, 79, 666], 1))\n    m = \"\"\"\n    There is a helper function called `numpy.diag`:\n    - if it takes a matrix, it will return a diagonal vector.\n    - if it takes a vector, it will return a matrix containing the provided diagonal vector.\n    For example:\n    \"\"\"\n    print(format_message_str(m))\n    m = get_diagonal_matrix([v**2 for v in range(1, 4)])\n    print(f\"Diagonal matrix as an example.\\n{m}\")\n    diagonal_vector = np.diag(m)\n    print(f\"Using numpy.diag function will produce a vector of {diagonal_vector}\")\n    m = np.diag(diagonal_vector)\n    print(f\"And providing the vector to the same function produces a matrix like this:\\n{m}\")\n\n    # Identity matrix\n    m = \"\"\"\n    Identity matrix is a type of a square matrix where a diagonal line consists of 1's and the rest of vectors are 0's.\n    Special property of it is \"a vector doesn't change when multiplied by it\".\n    To produce an identity matrix, the following functions can be used:\n    1. numpy.matlib.identity\n    2. numpy.identity\n    \n    For example, the following matrix can be produced using numpy.identity:\n    \"\"\"\n    print(format_message_str(m))\n    m = np.identity(3)\n    print(m)\n    print(\"Then produce a different normal square matrix, like this:\")\n    sq_m = get_square_matrix(3, True)\n    print(f\"{sq_m}\")\n    print(f\"If you multiply the identity matrix with the square one, you get:\\n{m * sq_m}\")\n    print(\"As for seeing that a vector is not affected by multiplication with the identitiy vector\")\n    vector = np.array([2, 3, 4, 5, 6])\n    print(f\"You have vector of {vector}\")\n    i = np.identity(5)\n    print(f\"And then an identity matrix like below:\\n{i}\")\n    print(f\"So if we do 'vector * i', then it's:\\n {vector * i}\")\n    print(f\"So if we do 'vector @ i', then it's: {vector @ i}\")\n    # Orthogonal matrix\n", "meta": {"hexsha": "4a1703881f79bdf0a617f3bdf28b0bb5f7f6b253", "size": 6426, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_algebra_by_j_borwnlee/ch_10/scribble_of_different_types_of_matrices.py", "max_stars_repo_name": "pavelexpertov/scribbles", "max_stars_repo_head_hexsha": "50ebcd6a686fd32be20d401563db7cc87781a428", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_algebra_by_j_borwnlee/ch_10/scribble_of_different_types_of_matrices.py", "max_issues_repo_name": "pavelexpertov/scribbles", "max_issues_repo_head_hexsha": "50ebcd6a686fd32be20d401563db7cc87781a428", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_algebra_by_j_borwnlee/ch_10/scribble_of_different_types_of_matrices.py", "max_forks_repo_name": "pavelexpertov/scribbles", "max_forks_repo_head_hexsha": "50ebcd6a686fd32be20d401563db7cc87781a428", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4233128834, "max_line_length": 119, "alphanum_fraction": 0.6761593526, "include": true, "reason": "import numpy", "num_tokens": 1591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436404, "lm_q2_score": 0.9046505299595162, "lm_q1q2_score": 0.8642299604407201}}
{"text": "﻿from scipy.fftpack import fft\nimport numpy as np\n\n\"\"\"\nA3-Part-2: Optimal zero-padding\n\nGiven a sinusoid, write a function that computes the DFT of the sinusoid after zero-padding and returns\nthe positive half of the magnitude spectrum (in dB). Zero-padding needs to be done such that one of \nthe bin frequencies of the DFT coincides with the frequency of the sinusoid. Choose the minimum \nzero-padding length for which this condition is satisfied. \n\nThe input arguments are the sinusoid x of length M, sampling frequency fs and the frequency of the \nsinusoid f. The output is the positive half of the magnitude spectrum mX computed using the N point \nDFT (N >= M) of x after zero-padding x to length N appropriately as required. \n\nTo get the positive half of the spectrum, first compute the N point DFT of the zero-padded input signal \n(for this you can use the fft function of scipy.fftpack, which is already imported in this script). \nConsider only the first (N/2)+1 samples of the DFT and compute the magnitude spectrum of the positive \nhalf (in dB) as mX = 20*log10(abs(X[:(N/2)+1])), where X is the N point DFT of the zero-padded input.\n\nFor this exercise, you can assume that the frequency of the sinusoid f is a positive integer and a \nfactor of the sampling rate fs. The input parameters will be given in such a way that N will be even.\nNote that the numerical value of f is an integer but the data type is float, for example 1.0, 2.0, \n55.0 etc. This is to avoid issues in python related with division by a integer.\n\nDue to the precision of the FFT computation, the zero values of the DFT are not zero but very small\nvalues < 1e-12 (or -240 dB) in magnitude. For practical purposes, all values with absolute value less \nthan 1e-6 (or -120 dB) can be considered to be zero. \n\nHINT: One of the DFT bin frequencies coincides with the frequency f of a sinusoid when the DFT size \n(N in this question) contains exactly an integer number of periods of the sinusoid. For example, \nif f = 100 Hz and fs = 1000 Hz, one period of the sinusoid has 10 samples. Then given a signal of length \nM = 25 samples, there are 2.5 periods in it. The minimum zero-padding length here would be 5 samples \n(0.5 period), so that the DFT size N = 30 corresponds to 3 periods of a sinusoid of frequency f=100 Hz.\n\nTest case 1: For a sinusoid x with f = 100 Hz, M = 25 samples and fs = 1000 Hz, you will need to \nzero-pad by 5 samples and compute an N = 30 point DFT. In the magnitude spectrum, you can see a \nmaximum value at bin index 3 corresponding to the frequency of 100 Hz. The output mX you return is \n16 samples in length. \n\nTest case 2: For a sinusoid x with f = 250 Hz, M = 210 samples and fs = 10000 Hz, you will need to \nzero-pad by 30 samples and compute an N = 240 point DFT. In the magnitude spectrum, you can see a \nmaximum value at bin index 6 corresponding to the frequency of 250 Hz. The output mX you return is \n121 samples in length. \n\n\"\"\"\ndef optimalZeropad(x, fs, f):\n    \"\"\"\n    Inputs:\n        x (numpy array) = input signal of length M\n        fs (float) = sampling frequency in Hz\n        f (float) = frequency of the sinusoid in Hz\n    Output:\n        The function should return\n        mX (numpy array) = The positive half of the DFT spectrum of the N point DFT after zero-padding \n                        x appropriately (zero-padding length to be computed). mX is (N/2)+1 samples long\n    \"\"\"\n    ## Your code here\n    M = x.shape[-1]\n    per_samp = fs / f\n    N = per_samp\n    while N<M:\n        N += per_samp\n    N = int(N)\n    fftbuffer = np.zeros(N)\n    fftbuffer[:M] = x\n    X = fft(fftbuffer)\n    mX = 20 * np.log10(abs(X[:(N//2)+1]))\n    return mX\n\n", "meta": {"hexsha": "fdb708419d1b35bed821704b0ebeb5fd0bd30f49", "size": 3670, "ext": "py", "lang": "Python", "max_stars_repo_path": "A3/A3Part2.py", "max_stars_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_stars_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A3/A3Part2.py", "max_issues_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_issues_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A3/A3Part2.py", "max_forks_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_forks_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.6901408451, "max_line_length": 105, "alphanum_fraction": 0.7190735695, "include": true, "reason": "import numpy,from scipy", "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.9086178895092414, "lm_q1q2_score": 0.8642248390698275}}
{"text": "from numpy import array, zeros, sqrt, linalg\n\ndef symmetric(A):\n    return (A == A.T).all()\ndef positiveDefinite(A):            # for i in range(len(matrix)):\n    E = linalg.eigvals(A)           #     if E[i] < 0: return False\n    return (E >= 0).all()           # return True\n\n\ndef decomposition(A):\n    N = len(A)\n    L = zeros((N,N))                # L = zeros_like(A)\n\n    for j in range(N):                                      # j = 0 to N-1\n        for i in range(j, N):                               # i = j to N-1\n            if i == j:\n                L[i,j] = sqrt(A[i,j] - sum(L[i,:j]**2))     # k = 0 to j-1\n            else:\n                L[i,j] = (A[i,j] - sum(L[i,:j]*L[j,:j])) / L[j,j]\n\n    print('Cholesky Decomposition:')\n    print('[L] =\\n', L, sep='', end='\\n\\n')\n    return L\n\n\ndef solveCholesky(A, B):\n    L = decomposition(A)\n    U = L.T\n    N = len(L)\n    \n    X = zeros(N)\n    Y = zeros(N)\n\n    # Forward Substitution\n    for i in range(N):                                      # i = 0 to N-1\n        Y[i] = (B[i] - sum(L[i,:i] * Y[:i])) / L[i,i]       # j = 0 to i-1\n\n        # sumj = 0\n        # for j in range(i):\n        #     sumj += L[i,j] * Y[j]\n        # Y[i] = (B[i] - sumj) / L[i,i]\n\n    # Backward Substitution\n    for i in range(N-1, -1, -1):                            # i = N-1 to 0\n        X[i] = (Y[i] - sum(U[i,i+1:] * X[i+1:])) / U[i,i]   # j = i+1 to N-1\n\n        # sumj = 0\n        # for j in range(i+1, N):\n        #     sumj += U[i,j] * X[j]\n        # X[i] = (Y[i] - sumj) / U[i,i]\n\n    return X\n\n\n# System of Equations\n\nA = array([[ 6,  15,  55],\n           [15,  55, 225],\n           [55, 225, 979]], float)\nB = array([-19, -100, -474], float)\n'''\nA = array([[8,    3.22,  0.8, 0,     4.10],\n           [3.22, 7.76, 2.33, 1.91, -1.03],\n           [0.8,  2.33, 5.25, 1,     3.02],\n           [0,    1.91, 1,    7.5,   1.03],\n           [4.1, -1.03, 3.02, 1.03,  6.44]], float)\nB = array([9.45, -12.20, 7.78, -8.1, 10.0], float)\n'''\nN = len(A)\n\nif symmetric(A) and positiveDefinite(A):\n    X = solveCholesky(A, B)\n    \n    print(\"The Solution of the System:\")\n    for i in range(N):\n        print('X[', i+1, '] = ', round(X[i], 6), sep='')\nelse:\n    print(\"The System cannot be Solved by Cholesky Decomposition\")\n\n\n'''\nDecomposition: [A] = [L][U]   # [L][U] ≠ [U][L]    Not commutative\n\n│a11 a12 a13 ... a1n│   │L11  0   0  ...  0 ││U11 U12 U13 ... U1n│\n│a21 a22 a23 ... a2n│   │L21 L22  0  ...  0 ││ 0  U22 U23 ... U2n│\n│a31 a32 a33 ... a3n│ = │L31 L32 L33 ...  0 ││ 0   0  U33 ... U3n│\n│... ... ... ... ...│   │... ... ... ... ...││... ... ... ... ...│\n│an1 an2 an3 ... ann│   │Ln1 Ln2 Ln3 ... Lnn││ 0   0   0  ... Unn│\n\nConditions of matrix A for Cholesky Decomposition:\n1. Symmetric:        A == A.T for all elements  # aij=aji   i,j = 1 to n\n2. Positive Definite: All eigenvalues positive  # linalg.eigvals(A) >= 0\n\nFor Cholesky: [A] = [L][L]^T  # [U] = [L]^T       Symmetric matrix\n\n│a11 a12 a13 ... a1n│   │L11  0   0  ...  0 ││L11 L12 L13 ... L1n│\n│a21 a22 a23 ... a2n│   │L21 L22  0  ...  0 ││ 0  L22 L23 ... L2n│\n│a31 a32 a33 ... a3n│ = │L31 L32 L33 ...  0 ││ 0   0  L33 ... L3n│\n│... ... ... ... ...│   │... ... ... ... ...││... ... ... ... ...│\n│an1 an2 an3 ... ann│   │Ln1 Ln2 Ln3 ... Lnn││ 0   0   0  ... Lnn│\n\n│a11 a21 a31 ... an1│   │L11  0   0  ...  0 ││L11 L21 L31 ... Ln1│\n│a21 a22 a32 ... an2│   │L21 L22  0  ...  0 ││ 0  L22 L32 ... Ln2│\n│a31 a32 a33 ... an3│ = │L31 L32 L33 ...  0 ││ 0   0  L33 ... Ln3│\n│... ... ... ... ...│   │... ... ... ... ...││... ... ... ... ...│\n│an1 an2 an3 ... ann│   │Ln1 Ln2 Ln3 ... Lnn││ 0   0   0  ... Lnn│\n\n│a11       symmetric│\n│a21 a22            │\n│a31 a32 a33        │ =\n│... ... ... ...    │\n│an1 an2 an3 ... ann│\n\n│L11^2                                                           symmetric│\n│L11L21  L21^2+L22^2                                                      │\n│L11L21 L31L21+L32L22  L31^2+L32^2+L33^2                                  │\n│ ...        ...             ...           ...                            │\n│L11Ln1 Ln1L21+Ln2L22 Ln1L31+Ln2L32+Ln3L33 ... Ln1^2+Ln2^2+Ln3^2+...+Lnn^2│\n\nL11 = √(a11)\nL21 = a21/L11   L22 = √(a22-L21^2)\nL31 = a31/L11   L32 = (a32-L31L21)/L22   L32 = √(a33-L31^2-L32^2)\n    ...             ...                     ...\nLn1 = an1/L11   Ln2 = (an2-Ln1L21)/L22   Ln3 = (an3 - Ln1L31 - Ln2L32) / L33\n                                         Lnn = √(ann - Ln1^2 - Ln2^2 - Ln3^2)\n\nLij = √(aij - ∑ Lik^2)         , i = j, j = 1 to n, i = j to n, k = 1 to j-1\nLij =  (aij - ∑ Lik*Ljk) / Ljj , i ≠ j, j = 1 to n, i = j to n, k = 1 to j-1\n\nFor Li1 there is no ∑ and is implimented by k = 1 to 1-1, not entering k loop\n\n\nSubstitution: [A]{X}={B}    => [L][U]{X}={B}    => [U]{X}={y} and [L]{y}={B}\n\nForward Substitution: [L]{y}={B}\n\n│L11  0   0  ...  0 ││y1│   │b1│\n│L21 L22  0  ...  0 ││y2│   │b2│\n│L31 L32 L33 ...  0 ││y3│ = │b3│\n│... ... ... ... ...││……│   │……│\n│Ln1 Ln2 Ln3 ... Lnn││yn│   │bn│\n\ny1 =  b1 / L11\ny2 = (b2 - L21y1) / L22\ny3 = (b3 - L31y1 - L32y2) / L33\nyn = (bn - Ln1y1 - Ln2y2 - ... - L[n,n-1]y[n-1]) / Lnn\n\nyi = (bi - ∑ Lij*yj) / Lii , i = 1 to n, j = 1 to i-1\n\nFor y1 there is no ∑ and is implimented by j = 1 to 1-1, not entering j loop\n\nBackward Substitution: [U]{X}={y}\n\n│U11 U12 U13 ... U1n││x1│   │y1│\n│ 0  U22 U23 ... U2n││x2│   │y2│\n│ 0   0  U33 ... U3n││x3│ = │y3│\n│... ... ... ... ...││……│   │……│\n│ 0   0   0  ... Unn││xn│   │yn│\n\nxn =  yn / Unn\nx3 = (y3                   - U34*x4) / U33\nx2 = (y2          - U23*x3 - U24*x4) / U22\nx1 = (y1 - U12*x2 - U13*x3 - U14*x4) / U11\nxi = (yi - Uij*xj - Uij*xj - Uij*xj) / Uii\n\nxi = (yi - ∑ Uij*xj) / Uii , i = n to 1, j = i+1 to n\n\nFor xn there is no ∑ and is implimented by j = n+1 to n, not entering j loop\n\n'''\n", "meta": {"hexsha": "b93b34af1453566ef28b2e8c42a448d4ee890e87", "size": 5722, "ext": "py", "lang": "Python", "max_stars_repo_path": "5. Systems of Linear Equations/6. Cholesky's (Factorization or Decomposition) Method.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5. Systems of Linear Equations/6. Cholesky's (Factorization or Decomposition) Method.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5. Systems of Linear Equations/6. Cholesky's (Factorization or Decomposition) Method.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4619883041, "max_line_length": 77, "alphanum_fraction": 0.4098217407, "include": true, "reason": "from numpy", "num_tokens": 2492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102524151826, "lm_q2_score": 0.8933094017937621, "lm_q1q2_score": 0.8641966738741591}}
{"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits import mplot3d\nimport scipy.optimize\n\n# Task 1 - Find the vector x in R^3 that minimizes ||Ax-b||\ndef task_1():\n    A = np.array([[1, 1, 2],\n                [1, 2, 1],\n                [2, 1, 1],\n                [2, 2, 1]])\n\n    b = np.array([1, -1, 1, -1]) # Numpy interprets this as a column matrix.\n    \n    def min_x(A, b):\n        '''\n        (1.1) Solves normal equation A_t . A . x = A_t . b for x by:\n            * Taking transpose of matrix A.\n            * Taking the dot products A_t . A and A_t . b, and assign them new names B and C.\n            * Returning linalg.solve(B,C) to find the solution for Bx = C.\n        '''\n        A_t = np.transpose(A)\n        B = np.dot(A_t, A)\n        C = np.dot(A_t, b)\n        return np.linalg.solve(B, C)\n\n    def min_x_norm(A, b, x_guess = [0, 0, 0]):\n        '''\n        (1.2) Finds the solution for ||Ax-b|| by:\n            * Creating a lambda function f, which represents ||Ax-b|| in a programatical way.\n            * Finding a suitable 'guess' for the algorithm, which is based on the result of min_x().\n            * Use scipy.optimize.fmin() with the guess for x to solve for x\n        '''\n\n        f = lambda x: np.linalg.norm((np.dot(A, x) - b))\n        return scipy.optimize.fmin(f, x_guess,disp=False)\n    \n    min_x_normal = min_x(A, b)\n    min_x_scipy = min_x_norm(A, b)\n\n    print(f\"Task 1.1 - Using the normal equation A_t . A . x = A_t . b and solving for x, we obtain:\\n{min_x_normal}\\n\")\n    print(f\"Task 1.2 - With scipy.optimize.fmin(), the x for which ||Ax-b|| is minimized is:\\n{min_x_scipy}\\n\")\n    print(f\"Task 1.2 - The difference between the two is:\\n{min_x_normal - min_x_scipy}\\n\")\n\n    def r(a):\n        '''\n        (1.3) Creates a function representing the residual ||Ax(a) - b(a)|| by:\n            * Using min_x() from 1.1 to minimize the new solution x dependent on input a.\n            * Returning ||Ax(a)-b(a)||.\n        '''\n        b = [1, a, 1, a] # Numpy interprets this as a column matrix.\n        x = min_x(A, b)\n        return np.linalg.norm(np.dot(A, x) - b)\n\n    x_axis = np.linspace(0,100,1000)\n    y_axis = [r(a) for a in x_axis] # For every value a, take ||Ax(a)-b(a)|| using the r(a) fn.\n\n    # Show the result of task 1.3.\n    plt.plot(x_axis, y_axis)\n    plt.xlabel(\"a\")\n    plt.ylabel(\"r(a)\")\n    plt.grid(color='black', linestyle='-', alpha=0.2)\n    plt.title(\"Residual r(a) = ||Ax(a)-b(a)||\")\n    plt.show()\n\ndef task_2():\n    A = np.array([[ 1,3,2],\n                [-3,4,3],\n                [ 2,3,1]])\n\n    z_0 = np.array([8,3,12])\n\n    def z_closed(n):\n        '''\n        (2.1) Returns z_n based on derived closed form (to be shown in presentation).\n        '''\n        e_1 = np.array([1,12,-19])\n        e_2 = np.array([1,0,1])\n        e_3 = np.array([3,1,3])\n        return (-1)**(n+1) * 1/5 * e_1 - 3**n * 8 * e_2 + 4**n * 27/5 * e_3\n\n    def v_n(n):\n        '''\n        (2.2) Function representation of v_n := z_n / ||z_n||\n        '''\n        z_n = z_closed(n)\n        return z_n/np.linalg.norm(z_n)\n\n    def q_n(n):\n        '''\n        (2.4) Returns q_n for every normalized iterate of v_n by:\n            * Computing v_n for nth iterate.\n            * Returning q_n where q_n = v_n^T A v_n\n        '''\n        v = v_n(n)\n        return np.transpose(v).dot(A.dot(v))\n\n    def iterates(a_n,a,epsilon):\n        '''\n        (2.6) Determines iterates necessary to satisfy an epsilon difference by:\n            * Taking the norm ||v_n - v||.\n            * Returning amount of iterates when the norm is less than epsilon.\n        '''\n        n = 0\n        while True:\n            if np.linalg.norm(a_n(n)-a) < epsilon:\n                return n\n            n += 1\n\n    # (2.1) Check if z_n converges as n -> 'infinity' and print last result.\n    z_vals = [ z_closed(n) for n in range(0, 200) ]\n    print(f\"Task 2.1 - As n → ∞, we have after 200 iterations that:\\nz_n = {z_vals[-1]}\")\n    \n    plt.plot(np.array(range(0,200)), [ np.linalg.norm(z) for z in z_vals ])\n    plt.title(\"Graph of Z_n as n → ∞\")\n    plt.show()\n   \n    # (2.2) Determining numerically the value that v_n converges to.\n    v_vals = [ v_n(n) for n in range(0,200) ]\n    v = v_vals[-1]\n    print(f\"Task 2.2 - As n → ∞, v_n converges to {v}\")\n    \n    # (2.2) Plot iterates of v_n\n    X = [ v[0] for v in v_vals ]\n    Y = [ v[1] for v in v_vals ]\n    Z = [ v[2] for v in v_vals ]\n    fig = plt.figure()\n    ax = fig.add_subplot(projection='3d')\n    ax.scatter(X,Y,Z)\n    ax.plot(X,Y,Z)\n    plt.title(f\"Iteration of v_n := z_n / ||z_n|| for n from 0 to {len(v_vals)}\")\n    plt.show()\n    fig.clf() # clear figure\n\n    # (2.4) Check limit of q_n as n -> 'infinity', and print last result.\n    q_vals = [ q_n(n) for n in range(0,200) ]\n    q = q_vals[-1]\n    print(f\"Task 2.4 - the limit of q as n -> inf is approximately {round(q,2)}.\")\n\n    # (2.6) Define epsilon from task and print result\n    epsilon = 10**-8\n    print(f\"Task 2.6 - {iterates(v_n,v,epsilon)} iterations needed for ||v_n - v|| < ε\")\n\n    # (2.7) Set a range of epsilons between 10^-1 and 10^-14, and compute number of\n    # iterates required for the result to be less than some epsilon in the range.\n    epsilon_vals = 10**((-1)*np.linspace(1,14,1000))\n    v_iterates = [ iterates(v_n,v,eps) for eps in epsilon_vals ]\n    q_iterates = [ iterates(q_n,q,eps) for eps in epsilon_vals ]\n\n    # (2.7) Plot the number of iterates of ||v_n-v|| and ||q_n-n|| against epsilon.\n    plt.gca().invert_xaxis()\n    plt.semilogx(epsilon_vals,v_iterates,label=\"||v_n - v|| < ε\")\n    plt.semilogx(epsilon_vals,q_iterates,label=\"||q_n - q|| < ε\")\n    plt.legend()\n    plt.show()\n\ndef task_3():\n    def f(x_1,x_2):\n        '''\n        (3b) Determines solution of x_3 for a given x_1 and x_2 by:\n            * Defining g as the given function, but making RHS equal to 0 (for fsolve()).\n            * Defining two reasonable initial values for the fsolve().\n            * Return the result.\n        '''\n        g = lambda x_3 : 2*x_1**2 - x_2**2 + 2*x_3**2 - 10*x_1*x_2 - 4*x_1*x_3 + 10*x_2*x_3 - 1\n        result_1 = scipy.optimize.fsolve(g,-10)\n        result_2 = scipy.optimize.fsolve(g,10)\n        return [result_1[0],result_2[0]]\n\n    # (3.1) Setting some parameters for the 3D plot of the function.\n    fig = plt.figure()\n    ax = fig.add_subplot(111, projection='3d')\n\n    x = np.linspace(-1,1,20)\n    y = np.linspace(-1,1,20)\n    X,Y = np.meshgrid(x,y)\n\n    Z_1 = []\n    Z_2 = []\n\n    # Below, we calculate z for all x-y combinations by looping over every y_coord\n    # and then generating a list of z values for every x_coord in x.\n    # This covers all possible x-y combinations of the plot.\n    # zip(*z_coord_list) separates the two different z values of each coordinate into their own lists.\n    \n    z_coord_list = []\n    for y_coord in y:\n       z = [f(x_coord, y_coord) for x_coord in x]\n       z_coord_list.append(zip(*z))\n    Z_1, Z_2 = zip(*z_coord_list)\n    \n    # (3.1) Plot the surfaces\n    Z_1 = np.array(Z_1)\n    Z_2 = np.array(Z_2)\n\n    ax.plot_surface(X,Y,Z_1)\n    ax.plot_surface(X,Y,Z_2)\n\n    plt.show()\n    fig.clf()\n\n# Main function to run all the tasks.\ndef main():\n    task_list = [task_1, task_2, task_3]\n    while True:\n        try:\n            i = int(input(\"Select the task to run! (0 to quit): \"))\n            # If task nr is valid, execute it and finish by clearing matplotlib figure.\n            if i in range(1,4):\n                task_list[i-1]()\n            elif i == 0:\n                break # Exits while loop & closes program.\n            else:\n                raise ValueError\n        except:\n            print(\"Invalid input!\")\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "5eb131be969ecf9adb879d916aa372da49f26846", "size": 7708, "ext": "py", "lang": "Python", "max_stars_repo_path": "MATB22/lin_algebra_project.py", "max_stars_repo_name": "Salyrus/lu-work", "max_stars_repo_head_hexsha": "a301fc4f471dc44e86c933503912820e06c82c55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MATB22/lin_algebra_project.py", "max_issues_repo_name": "Salyrus/lu-work", "max_issues_repo_head_hexsha": "a301fc4f471dc44e86c933503912820e06c82c55", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MATB22/lin_algebra_project.py", "max_forks_repo_name": "Salyrus/lu-work", "max_forks_repo_head_hexsha": "a301fc4f471dc44e86c933503912820e06c82c55", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0363636364, "max_line_length": 120, "alphanum_fraction": 0.559937727, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140616, "lm_q2_score": 0.897695298265595, "lm_q1q2_score": 0.8641871250751886}}
{"text": "import numpy as np\n\ndef make_cubic(n_samples, x_min, x_max, a=1, b=0, c=0, d=0, noise=0.0, random_state=None):\n    np.random.seed(random_state)\n    x = np.linspace(x_min, x_max, n_samples)\n    y = a*x**3 + b*x**2 + c*x + d + (2*noise*np.random.random(n_samples) - noise)\n    return x.reshape(-1,1), y.reshape(-1,1)\n\ndef make_exp(n_samples, x_min, x_max, noise=0.0, random_state=None):\n    np.random.seed(random_state)\n    x = np.linspace(x_min, x_max, n_samples)\n    y = np.exp(x) + 2*noise*np.random.random(n_samples) - noise\n    return x.reshape(-1,1), y.reshape(-1,1)\n    \ndef make_log10(n_samples, x_min, x_max, noise=0.0, random_state=None):\n    np.random.seed(random_state)\n    x = np.logspace(np.log10(x_min), np.log10(x_max), n_samples)\n    y = np.log10(x) + 2*noise*np.random.random(n_samples) - noise\n    return x.reshape(-1,1), y.reshape(-1,1)\n\ndef make_spiral(n_samples, n_class=2, radius=1, laps=1.0, noise=0.0, random_state=None):\n    np.random.seed(random_state)\n    x = np.zeros((n_samples * n_class, 2))\n    y = np.zeros((n_samples * n_class))\n    \n    pi_2 = 2 * np.math.pi\n    points = np.linspace(0, 1, n_samples)\n    r = points * radius\n    t = points * pi_2 * laps\n    for label, delta_t in zip(range(n_class), np.arange(0, pi_2, pi_2/n_class)):\n        random_noise = (2 * np.random.rand(n_samples) - 1) * noise\n        index = np.arange(label*n_samples, (label+1)*n_samples)\n        x[index] = np.c_[r * np.sin(t + delta_t) + random_noise,\n                         r * np.cos(t + delta_t) + random_noise]\n        y[index] = label\n    return x, y.reshape(-1, 1)\n\ndef make_square(n_samples, x_min, x_max, a=1, b=0, c=0, noise=0.0, random_state=None):\n    np.random.seed(random_state)\n    x = np.linspace(x_min, x_max, n_samples)\n    y = a*x**2 + b*x + c + (2*noise*np.random.random(n_samples) - noise)\n    return x.reshape(-1,1), y.reshape(-1,1)\n", "meta": {"hexsha": "a991bb43ad897186def6850a4fbe80d214978ecb", "size": 1868, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/samples_generator.py", "max_stars_repo_name": "AristotelesTN/pos-unipe", "max_stars_repo_head_hexsha": "23a04ad1f431c23c4ba7e2ebd8b7188e89b71a33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 199, "max_stars_repo_stars_event_min_datetime": "2017-05-17T22:48:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:01:37.000Z", "max_issues_repo_path": "utils/samples_generator.py", "max_issues_repo_name": "AristotelesTN/pos-unipe", "max_issues_repo_head_hexsha": "23a04ad1f431c23c4ba7e2ebd8b7188e89b71a33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-10-13T20:13:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-19T00:19:44.000Z", "max_forks_repo_path": "utils/samples_generator.py", "max_forks_repo_name": "AristotelesTN/pos-unipe", "max_forks_repo_head_hexsha": "23a04ad1f431c23c4ba7e2ebd8b7188e89b71a33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 75, "max_forks_repo_forks_event_min_datetime": "2018-04-17T12:11:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T10:36:35.000Z", "avg_line_length": 43.4418604651, "max_line_length": 90, "alphanum_fraction": 0.6354389722, "include": true, "reason": "import numpy", "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558706, "lm_q2_score": 0.8976952941600964, "lm_q1q2_score": 0.8641871230456274}}
{"text": "\"\"\"\nbasic operations II\n\"\"\"\n\nimport numpy as np\n\narr = np.array([[1, 5, 6],\n                [4, 7, 2],\n                [3, 1, 9]])\n\n# maximum element of array\nprint(\"Largest element is:\", arr.max())\n\n# minimum element of array\nprint(\"Smallest element is:\", arr.min())\n\n# maximum element per row\nprint(\"Row-wise maximum elements:\",\n      arr.max(axis=1))\n\n# minimum element per col\nprint(\"Column-wise minimum elements:\",\n      arr.min(axis=0))\n\n# sum of array elements\nprint(\"Sum of all array elements:\",\n      arr.sum())\n\n# cumulative sum along each row\nprint(\"Cumulative sum along each row:\\n\",\n      arr.cumsum(axis=1))\n\nc = np.array([[1, 2],\n              [3, 4]])\nd = np.array([[4, 3],\n              [2, 1]])\n\n# add arrays\nprint(\"Array sum:\\n\", c + d)\n\n# multiply arrays (elementwise multiplication)\nprint(\"Array multiplication:\\n\", c * d)\n", "meta": {"hexsha": "3e38169c0442283d0cd4142561117c9459ee5087", "size": 844, "ext": "py", "lang": "Python", "max_stars_repo_path": "pset_pandas1_basics/ndarrs/solutions/p5.py", "max_stars_repo_name": "mottaquikarim/pydev-psets", "max_stars_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-08T20:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T20:48:45.000Z", "max_issues_repo_path": "pset_pandas1_basics/ndarrs/solutions/p5.py", "max_issues_repo_name": "mottaquikarim/pydev-psets", "max_issues_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-04-15T15:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T10:33:32.000Z", "max_forks_repo_path": "pset_pandas1_basics/ndarrs/solutions/p5.py", "max_forks_repo_name": "mottaquikarim/pydev-psets", "max_forks_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-10T00:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T20:35:21.000Z", "avg_line_length": 19.6279069767, "max_line_length": 46, "alphanum_fraction": 0.5947867299, "include": true, "reason": "import numpy", "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.8976952934758466, "lm_q1q2_score": 0.8641871223869184}}
{"text": "import numpy as np\n\n\nclass Gaussian:\n    \"\"\"Summary of class here.\n\n    Attributes:\n        mean: μ (平均值)\n        std: standard deviation, σ (標準差)\n        variance: σ^2 (變異數)\n    \"\"\"\n    def __init__(self, mean=0, std=None, variance=None) -> None:\n        self._mean = mean\n\n        if std:\n            self._std = std\n            self._variance = self._std ** 2\n        elif variance:\n            self._variance = variance\n            self._std = np.sqrt(self._variance)\n        else:\n            print('Initial error, missing parameters \"std\" or \"variance\", please at least select one.')\n            raise AttributeError\n\n    @property\n    def mean(self):\n        return self._mean\n\n    @mean.setter\n    def mean(self, val):\n        self._mean = val\n\n    @property\n    def std(self):\n        return self._std\n\n    @std.setter\n    def std(self, val):\n        self._std = val\n        self._variance = self._std ** 2\n\n    @property\n    def variance(self):\n        return self._variance\n\n    @variance.setter\n    def variance(self, val):\n        self._variance = val\n        self._std = np.sqrt(self._variance)\n\n\n# Measurement Update (Correction)\ndef measurement_update(gauss1: Gaussian, gauss2: Gaussian) -> Gaussian:\n    mean1 = gauss1.mean\n    std1 = gauss1.std\n    mean2 = gauss2.mean\n    std2 = gauss2.std\n\n    new_mean = (np.power(std1, 2) * mean2 + np.power(std2, 2) * mean1) / (std1**2 + std2**2)\n    new_std = np.sqrt(1 / ((1 / std1**2) + (1 / std2**2)))\n\n    new_gauss = Gaussian(new_mean, new_std)\n    return new_gauss\n\n\n# Prediction (Motion Update)\ndef prediction(gauss1: Gaussian, gauss2: Gaussian) -> Gaussian:\n    mean1 = gauss1.mean\n    variance1 = gauss1.variance\n    mean2 = gauss2.mean\n    variance2 = gauss2.variance\n\n    new_mean = mean1 + mean2\n    new_variance = variance1 + variance2\n\n    new_gauss = Gaussian(new_mean, variance=new_variance)\n    return new_gauss\n\n\nif __name__ == \"__main__\":\n    # Measurement Update\n    #   Gaussian(mean, std, variance)\n    print(\">>> Measurement Update <<<\")\n\n    gauss1 = Gaussian(10, 2)\n    gauss2 = Gaussian(12, 2)\n    new_gauss = measurement_update(gauss1, gauss2)\n    print(\"New mean: {}, new std: {}, new variance: {}\".format(\n        new_gauss.mean, new_gauss.std, new_gauss.variance))\n\n    gauss1 = Gaussian(10, np.sqrt(8))\n    gauss2 = Gaussian(13, np.sqrt(2))\n    new_gauss = measurement_update(gauss1, gauss2)\n    print(\"New mean: {}, new std: {}, new variance: {}\".format(\n        new_gauss.mean, new_gauss.std, new_gauss.variance))\n\n    # Prediction (Motion Update)\n    print(\">>> Prediction <<<\")\n\n    gauss1 = Gaussian(8, variance=4)\n    gauss2 = Gaussian(10, variance=6)\n    new_gauss = prediction(gauss1, gauss2)\n    print(\"New mean: {}, new std: {}, new variance: {}\".format(\n        new_gauss.mean, new_gauss.std, new_gauss.variance))\n\n    gauss1 = Gaussian(10, variance=4)\n    gauss2 = Gaussian(12, variance=4)\n    new_gauss = prediction(gauss1, gauss2)\n    print(\"New mean: {}, new std: {}, new variance: {}\".format(\n        new_gauss.mean, new_gauss.std, new_gauss.variance))\n", "meta": {"hexsha": "d5e3dcf6fb7fcf3fa4379063d9a3a662bd1fcf14", "size": 3057, "ext": "py", "lang": "Python", "max_stars_repo_path": "Sensor Fusion and Tracking/Kalman Filters/kalman_concept.py", "max_stars_repo_name": "kaka-lin/autonomous-driving-notes", "max_stars_repo_head_hexsha": "6c1b29752d6deb679637766b6cea5c6fe5b72319", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sensor Fusion and Tracking/Kalman Filters/kalman_concept.py", "max_issues_repo_name": "kaka-lin/autonomous-driving-notes", "max_issues_repo_head_hexsha": "6c1b29752d6deb679637766b6cea5c6fe5b72319", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sensor Fusion and Tracking/Kalman Filters/kalman_concept.py", "max_forks_repo_name": "kaka-lin/autonomous-driving-notes", "max_forks_repo_head_hexsha": "6c1b29752d6deb679637766b6cea5c6fe5b72319", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5405405405, "max_line_length": 103, "alphanum_fraction": 0.616617599, "include": true, "reason": "import numpy", "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140615, "lm_q2_score": 0.897695283896349, "lm_q1q2_score": 0.8641871112423017}}
{"text": "from typing import Tuple\n\nimport numpy as np\n\n\ndef computeD1D2(current: float, volatility: float, ttm: float, strike: float,\n                rf: float) -> Tuple[float, float]:\n    \"\"\"Helper function to compute the risk-adjusted priors of exercising the\n    option contract, and keeping the underlying asset. This is used in the\n    computation of both the Call and Put options in the\n    Black-Scholes-Merton framework.\n    \n    Arguments:\n        current {float} -- Current price of the underlying asset.\n        volatility {float} -- Volatility of the underlying asset price.\n        ttm {float} -- Time to expiration (in years).\n        strike {float} -- Strike price of the option contract.\n        rf {float} -- Risk-free rate (annual).\n    \n    Returns:\n        Tuple[float, float] -- Tuple with d1, and d2 respectively.\n    \"\"\"\n\n    d1 = (np.log(current / strike) + (rf + ((volatility ** 2) / 2)) * ttm) \\\n        / (volatility * np.sqrt(ttm))\n    d2 = d1 - (volatility * np.sqrt(ttm))\n    \n    return (d1, d2)\n", "meta": {"hexsha": "b7544c90f03b518044809f5e4cc9d71bb73c6fb7", "size": 1018, "ext": "py", "lang": "Python", "max_stars_repo_path": "fe621/black_scholes/util.py", "max_stars_repo_name": "rukmal/FE-621-Homework", "max_stars_repo_head_hexsha": "9c7cef7931b58aed54867acd8e8cf1928bc6d2dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-04-29T04:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T07:49:08.000Z", "max_issues_repo_path": "fe621/black_scholes/util.py", "max_issues_repo_name": "rukmal/FE-621-Homework", "max_issues_repo_head_hexsha": "9c7cef7931b58aed54867acd8e8cf1928bc6d2dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fe621/black_scholes/util.py", "max_forks_repo_name": "rukmal/FE-621-Homework", "max_forks_repo_head_hexsha": "9c7cef7931b58aed54867acd8e8cf1928bc6d2dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-23T07:32:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T07:32:44.000Z", "avg_line_length": 35.1034482759, "max_line_length": 77, "alphanum_fraction": 0.6306483301, "include": true, "reason": "import numpy", "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426443092215, "lm_q2_score": 0.8872045952083047, "lm_q1q2_score": 0.8641751099599896}}
{"text": "import numpy as np\nfrom numpy import linalg as la\n\n# This file is also used in the voronoi lab.\n\ndef prob_1():\n\t#problem 1\n\t#part 1\n\tA = np.array([[.75, .5], [.25, .5]])\n\tprint A.dot(A)[0,0]\n\t#part 2\n\tprint la.matrix_power(A, 20)[0,0]\n\ndef prob_2():\n\t#problem 2\n\t#part 1\n\tA = np.array([[1./4, 1./3, 1./2], [1./4, 1./3, 1./3], [1./2, 1./3, 1./6]])\n\tprint A\n\t#part 2\n\tprint A.dot(A)[0,1]\n\t#part 3\n\t#it is fine if they just raised the matrix to a few powers and did the comparison themselves\n\tAnew = A.dot(A)\n\tprev = A.copy()\n\ttol = .0000001\n\titers = 1\n\tmaxiters = 100\n\twhile la.norm(prev-Anew) > tol:\n\t\tprev[:] = Anew\n\t\tAnew[:] = A.dot(Anew)\n\t\tif iters > maxiters:\n\t\t\tprint \"exceeded \", maxiters, \" iterations.\"\n\t\t\tbreak\n\t\titers += 1\n\tif iters is not maxiters+1:\n\t\tprint \"reached steady state after \", iters, \" iterations.\"\n\tprint Anew\n\ndef prob_3:\n\t#problem 3\n\tA = np.array([[0, 0, 1, 0, 1, 0, 1],\n\t\t\t\t  [1, 0, 0, 0, 0, 1, 0],\n\t\t\t\t  [0, 0, 0, 0, 0, 1, 0],\n\t\t\t\t  [1, 0, 0, 0, 1, 0, 0],\n\t\t\t\t  [0, 0, 0, 1, 0, 0, 0],\n\t\t\t\t  [0, 0, 1, 0, 0, 0, 1],\n\t\t\t\t  [0, 1, 0, 0, 0, 0, 0]], dtype=np.int64)\n\tA5 = la.matrix_power(A,5)\n\tcoords = np.where(A5==np.max(A5))\n\t#note: indexing from 0\n\tprint \"maximum of 5 step connections at: \", zip(coords[0], coords[1])\n\tA7 = la.matrix_power(A,7)\n\tcoords = np.where(A7==0)\n\tprint \"no 7 step connection for: \", zip(coords[0], coords[1])\n\n#problem 4\ndef findpath(a, b, A):\n\tAnew = A.copy()\n\tarrs = [Anew]\n\tnum = 0\n\twhile Anew[a,b] == False:\n\t\tnum += 1\n\t\tAnew = Anew.dot(A)\n\t\tarrs.append(Anew)\n\t\tif num > A.shape[0]-1:\n\t\t\traise ValueError(\"Nodes are not connected\")\n\t\t\tbreak\n\tcurrent = a\n\tpath = [current]\n\tfor arr in reversed(arrs[:-1]):\n\t\t#iterating over steps\n\t\tfor i in xrange(A.shape[0]):\n\t\t\t#iterating over possible points\n\t\t\tif A[i,current] == True:\n\t\t\t\t#if it links to the current node\n\t\t\t\tif arr[b,i] == True:\n\t\t\t\t\t#if it links to b at this step\n\t\t\t\t\tcurrent = i\n\t\t\t\t\tpath.append(current)\n\t\t\t\t\tbreak\n\tpath.append(b)\n\treturn path\n\ndef prob_4():\n\tA = np.load(\"maze.npy\")\n\tprint findpath(0, 224, A)\n", "meta": {"hexsha": "e51233d6bd14f179206109df844265593608fad7", "size": 2027, "ext": "py", "lang": "Python", "max_stars_repo_path": "Applications/voronoi/markov_solutions.py", "max_stars_repo_name": "abefrandsen/numerical_computing", "max_stars_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Applications/voronoi/markov_solutions.py", "max_issues_repo_name": "abefrandsen/numerical_computing", "max_issues_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Applications/voronoi/markov_solutions.py", "max_forks_repo_name": "abefrandsen/numerical_computing", "max_forks_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2988505747, "max_line_length": 93, "alphanum_fraction": 0.5900345338, "include": true, "reason": "import numpy,from numpy", "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.9136765269395709, "lm_q1q2_score": 0.8641564197101866}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 10 15:18:57 2019\n\n@author: alankar\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.linspace(0,2,1000)\nf = lambda x:np.sin(1/(x*(2-x)))**2\n\nplt.figure(figsize=(13,10))\nplt.plot(x,f(x))\nplt.grid()\nplt.xlabel(r'$x$',size=18)\nplt.ylabel(r'$f(x)$',size=20)\nplt.title(r'Integrand', size=21)\nplt.tick_params(axis='both', which='major', labelsize=15)\nplt.tick_params(axis='both', which='minor', labelsize=12)\nplt.savefig('4.png')\nplt.show()\n\nN = int(1e4)\nx = np.random.uniform(low=0,high=2.0,size=N)\ny = np.random.uniform(low=0.,high=1.0,size=N)\nA = 2.*1.\nI = (np.count_nonzero(np.array(y<=f(x),dtype=np.int32))/N)*A\nerror = np.sqrt(I*(A-I)/N)\nprint('Monte Carlo Hit-Miss Algorithm')\nprint('Integral: %f'%I)\nprint('Error: %e'%error)\n\nprint()\nI = ((2.-0.)/N)*np.sum(f(x))\nvarf = (1/N)*np.sum(f(x)**2)-(I/(2.-0.))**2\nerror = (2.-0.)*np.sqrt(varf/N)\nprint('Monte Carlo Mean Value Algorithm')\nprint('Integral: %f'%I)\nprint('Error: %e'%error)\n\n\n\"\"\"\nOutput:\n    \nMonte Carlo Hit-Miss Algorithm\nIntegral: 1.456000\nError: 8.899798e-03\n\nMonte Carlo Mean Value Algorithm\nIntegral: 1.453037\nError: 5.308131e-03\n\"\"\"", "meta": {"hexsha": "53bfe0a20f967a1a5ad300bca87a8d0869421b1b", "size": 1181, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw5/04/4.py", "max_stars_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_stars_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:47:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:05:39.000Z", "max_issues_repo_path": "hw5/04/4.py", "max_issues_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_issues_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw5/04/4.py", "max_forks_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_forks_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-21T17:33:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T02:58:56.000Z", "avg_line_length": 21.4727272727, "max_line_length": 60, "alphanum_fraction": 0.6528365792, "include": true, "reason": "import numpy", "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801267121407, "lm_q2_score": 0.9136765263519306, "lm_q1q2_score": 0.8641564163627417}}
{"text": "import numpy as np\n\n\ndef lu_decomposition_with_pp(matrix):\n    # Get the number of rows\n    n = matrix.shape[0]\n\n    tmp_L = np.eye(n, dtype=np.double)\n    tmp_U = matrix.copy()\n    for i in range(n):\n        result = np.where(np.abs(tmp_U[i:, i]) == np.amax(np.abs(tmp_U[i:, i])))\n        swap_i = result[0][0]\n        tmp_U[[swap_i + i, i], i:n] = tmp_U[[i, swap_i + i], i:n]\n\n        factors = tmp_U[i + 1:, i] / tmp_U[i, i]\n        tmp_L[i + 1:, i] = factors\n        tmp_U[i + 1:] -= factors[:, np.newaxis] * tmp_U[i]\n    return tmp_L, tmp_U\n\n\ndef forward_substitution(tmp_l, tmp_b):\n    # get size of L matrix\n    n = tmp_l.shape[0]\n\n    # initialize empty array with size b\n    tmp_y = np.zeros_like(tmp_b, dtype=np.double)\n\n    # computing tmp_y values\n    tmp_y[0] = tmp_b[0] / tmp_l[0, 0]\n    for i in range(1, n):\n        tmp_y[i] = (tmp_b[i] - np.dot(tmp_l[i, :i], tmp_y[:i])) / tmp_l[i, i]\n    return tmp_y\n\n\ndef backward_substitution(tmp_u, tmp_y):\n    # get size of U matrix\n    n = tmp_u.shape[0]\n\n    # initialize emtpy array with size y\n    tmp_x = np.zeros_like(tmp_y, dtype=np.double)\n\n    # computing tmp_x values\n    tmp_x[-1] = tmp_y[-1] / tmp_u[-1, -1]\n    for i in range(n - 2, -1, -1):\n        tmp_x[i] = (tmp_y[i] - np.dot(tmp_u[i, i + 1:], tmp_x[i + 1:])) / tmp_u[i, i]\n    return tmp_x\n\n\ndef solve_lin_system_with_lu(mat, x):\n    TMP_L, TMP_U = lu_decomposition_with_pp(mat)\n    y = forward_substitution(TMP_L, x)\n    return backward_substitution(TMP_U, y)\n\n\ndef iterative_ref(A, b, tolerance=1e-10, iterations=1000):\n    x = np.ones_like(b, dtype=np.double)\n    for i in range(iterations):\n        x0 = x.copy()\n        r = b - np.dot(A, x0)\n        c = np.linalg.solve(A, r)\n        x = np.add(x0, c)\n        if np.linalg.norm(x - x0, 2) / np.linalg.norm(x0, 2) < tolerance:\n            break\n    return x\n\n\n#  correct answer is given by gepp\ngepp = np.array([[-5.93025381, 0.10179665, -5.63806883],\n                 [5.71248256, -5.33907931, 0.04770739],\n                 [5.09042443, 4.20346378, -7.43808245]])\ngepp_b = np.array([3.00764463,\n                   3.39289929,\n                   -3.35276915])\n\nprint(\"correct answer is given by gepp method\")\nprint(\"built in function\")\nprint(np.linalg.solve(gepp, gepp_b))\nprint(\"iterative refinement method\")\nprint(iterative_ref(gepp, gepp_b))\nprint(\"GEPP method\")\nprint(solve_lin_system_with_lu(gepp, gepp_b), \"\\n\\n\\n\")\n\n#  gepp fails and works only with iterative refinement\ngepp = np.array([[-5e-3, 1.0, 2.0],\n                 [-2.0, -1, 1.0],\n                 [-5.0, 5.0, 1]])\ngepp_b = np.array([6.0,\n                   -9.0,\n                   2.0])\nprint(\"gepp fails and gives accurate results only with iterative refinement\")\nprint(\"built in function\")\nprint(np.linalg.solve(gepp, gepp_b))\nprint(\"iterative refinement method\")\nprint(iterative_ref(gepp, gepp_b))\nprint(\"GEPP method\")\nprint(solve_lin_system_with_lu(gepp, gepp_b), \"\\n\\n\\n\")\n", "meta": {"hexsha": "406eb97629bb152306ee88d37f05b2c4f5ca633a", "size": 2925, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "alexnat009/GEPPWithIterativeRefinement", "max_stars_repo_head_hexsha": "94cd33db61faf82b4446b390842bc02594bcfbd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.py", "max_issues_repo_name": "alexnat009/GEPPWithIterativeRefinement", "max_issues_repo_head_hexsha": "94cd33db61faf82b4446b390842bc02594bcfbd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "alexnat009/GEPPWithIterativeRefinement", "max_forks_repo_head_hexsha": "94cd33db61faf82b4446b390842bc02594bcfbd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1546391753, "max_line_length": 85, "alphanum_fraction": 0.5969230769, "include": true, "reason": "import numpy", "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.9032942151647513, "lm_q1q2_score": 0.8641221388885229}}
{"text": "from math import ceil\nimport numpy as np\n\n\ndef bisection(f, a, b, eps=5e-6):\n    \"\"\"\n        Function that finds a root using Bisection method for a given function f(x).\n        The function finds the root of f(x) with a predefined absolute accuracy epsilon.\n        The function excepts an interval [a,b] in which is known that the function f has a root.\n        If the function f has multiple roots in this interval then Bisection method converges randomly to one of them.\n        If in the interval [a,b] f(x) doesn't change sign (Bolzano theorem can not be applied) the function returns nan\n        as root and -1 as the number of iterations.Also the function checks if either a or b is a root of f(x), if both\n        are then the function returns the value of a.\n\n        Parameters\n        ----------\n        f : callable\n            The function to find a root of.\n        a : float\n            The start of the initial interval in which the function will find the root of f(x).\n        b : float\n            The end of the initial interval in which the function will find the root of f(x).\n        eps : float\n            The target accuracy.\n            The iteration stops when the length of the current interval divided by 2 to the power of n+1 is below eps.\n            Default value is 5e-6.\n\n        Returns\n        -------\n        root : float\n            The estimated value for the root.\n        iterations_num : int\n            The number of iterations.\n    \"\"\"\n\n    # check if Bolzano theorem can not be applied or a is larger than b\n    if f(a) * f(b) > 0 or a > b:\n        return np.nan, -1\n    elif f(a) == 0:  # check if a is root of f\n        return a, 0\n    elif f(b) == 0:  # or b is root of f\n        return b, 0\n\n    # find how many iterations are needed for achieving error less than eps\n    iterations_num = ceil((np.log(b - a) - np.log(eps)) / np.log(2))\n\n    # Bisection algorithm\n    for i in range(0, iterations_num):\n        current_root = (a + b) / 2  # each iteration root approximation is the middle of the current interval\n        if f(current_root) == 0:\n            return current_root, i+1\n        elif f(a) * f(\n                current_root) < 0:  # find out where Bolzano theorem still can be applied and update the interval [a,b]\n            b = current_root\n        else:\n            a = current_root\n\n    return current_root, iterations_num\n", "meta": {"hexsha": "4d45687c6398591279a171aefc8610cac1f2185e", "size": 2389, "ext": "py", "lang": "Python", "max_stars_repo_path": "First Project/Exercise1/bisection.py", "max_stars_repo_name": "TasosOperatingInBinary/Numerical-Analysis-Projects", "max_stars_repo_head_hexsha": "61a8014f2b853a646145cea5a4d3655e100be854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "First Project/Exercise1/bisection.py", "max_issues_repo_name": "TasosOperatingInBinary/Numerical-Analysis-Projects", "max_issues_repo_head_hexsha": "61a8014f2b853a646145cea5a4d3655e100be854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "First Project/Exercise1/bisection.py", "max_forks_repo_name": "TasosOperatingInBinary/Numerical-Analysis-Projects", "max_forks_repo_head_hexsha": "61a8014f2b853a646145cea5a4d3655e100be854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4915254237, "max_line_length": 119, "alphanum_fraction": 0.6140644621, "include": true, "reason": "import numpy", "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.956634196290671, "lm_q2_score": 0.9032942073547148, "lm_q1q2_score": 0.8641221280667963}}
{"text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport timeit\n\nplt.style.use('seaborn')\nsns.set_style(\"darkgrid\")\n\n# So    :   initial stock price\n# dt    :   time increment (a day)\n# T     :   length of the prediction time horizon\n# N     :   number of time points in the prediction time horizon -> T/dt\n# t     :   array for time points in the prediction time horizon [1, 2, 3, .. , N]\n# mu    :   mean of historical daily returns\n# sigma :   standard deviation of historical daily returns\n# b     :   array for brownian increments\n# W     :   array for brownian path\n# sims  :   number of simulations\n\nsims = 10000\n\ns0 = 10\nT = 100\ndt = 1\nN = T / dt\nt = np.arange(1, int(N) + 1)\nmu = 0\nsigma = 0.009\n\n# Dictionary Implementation\nnp.random.seed(123)\n\nstart = timeit.default_timer()\n\nb = {str(i): np.random.normal(0, np.sqrt(dt), int(N)) for i in range(sims)}\nW = {str(i): np.cumsum(b[str(i)]) for i in range(sims)}\ndrift = (mu - 0.5 * sigma**2) * t\ndiffusion = {str(i): sigma * W[str(i)] for i in range(sims)}\n\nS = np.array([s0 * np.exp(drift + diffusion[str(i)]) for i in range(sims)]) \nS = np.hstack((np.array([[s0] for i in range(sims)]), S))\n\nend = timeit.default_timer()\nprint(\"Time {:,.3f} seconds\".format(end - start))\n\nfig, ax = plt.subplots(figsize=(8,5))\nfor i in range(sims):\n    ax.plot(S[i, :], label=\"_nolabel_\")\nax.plot(S[0, :], color=\"k\", label=\"Actual Path\")\nax.set(title=\"Geometric Brownian Motion\", xlabel=\"days\", ylabel=\"Stock Price, £\")\nplt.legend()\nplt.show()\n\n\n# Array Implementation\nnp.random.seed(123)\n\nstart = timeit.default_timer()\n\nb = np.random.normal(0, np.sqrt(dt), (sims, int(N)))\nW = np.cumsum(b, axis=1)\ndrift = (mu - 0.5 * sigma**2) * t\ndiffusion = sigma * W\n\nS = np.array(s0 * np.exp(drift + diffusion))\nS = np.vstack((np.array([[s0] * sims]), S.T))\n\nend = timeit.default_timer()\nprint(\"Time {:,.3f} seconds\".format(end - start))\n\nfig, ax = plt.subplots(figsize=(8,5))\nax.plot(S, alpha=0.5, label=\"_nolabel_\")\nax.plot(S[:, 0], color=\"k\", label=\"Actual Path\")\nax.set(title=\"Geometric Brownian Motion\", xlabel=\"days\", ylabel=\"Stock Price, £\")\nplt.legend()\nplt.show()\n\nfig, ax = plt.subplots(figsize=(8,5))\nax.hist(S[-1, :], bins = 20)\nax.set(title=\"Geometric Brownian Motion\", xlabel=\"days\", ylabel=\"Stock Price, £\")\nplt.show()\n\n\n# Drift\n\ndef brownianMotion(sims, T, dt, seed):\n\n    '''\n    int sims    : number of simulations\n    int T       : number of time points to predict\n    float dt    : time increment\n    return b, W : b - Brownian increment, W - Brownian path\n    '''\n\n    np.random.seed(seed)\n    N = int(T / dt)\n    b = np.random.normal(0, 1, (sims, N))*np.sqrt(dt)\n    W = np.cumsum(b, axis=1)\n\n    return b, W\n\nb, W = brownianMotion(1, 252, 1, 123)\n\nfig, ax = plt.subplots(figsize=(16,5), ncols=2, nrows=1)\nax[0].plot(b.T)\nax[0].set(title=\"Brownian Increment\", xlabel=\"days\", ylabel=\"Random Variate\")\nax[1].plot(W.T)\nax[1].set(title=\"Brownian Path\", xlabel=\"days\", ylabel=\"Random Variate\")\nplt.show()\n\n\ndef GBM(sims, T, dt, s0, mu, sigma, seed):\n\n    '''\n    int sims    : number of simulations\n    int T       : number of time points to predict\n    float dt    : time increment\n    float s0    : initial stock price\n    float mu    : drift coefficient\n    float sigma : diffusion coefficient\n    return S    : stock price simulations\n    '''\n\n    # Calculate the simulation range\n    N = int(T / dt)\n    t = np.arange(1, N + 1)\n\n    # Calculate Brownian random paths\n    b, W = brownianMotion(sims, T, dt, seed)\n\n    # Calculate drift and diffusion\n    drift = (mu - 0.5 * sigma**2) * t\n    diffusion = sigma * W\n\n    # Simulate stock price\n    S = np.array(s0 * np.exp(drift + diffusion))\n    S = np.vstack((np.array([[s0] * sims]), S.T))\n\n    return S\n\nS = GBM(sims=1, T=252, dt=1, s0=10, mu=0, sigma=0.01, seed=10)\n\nfig, ax = plt.subplots(figsize=(16,5), ncols=2, nrows=1)\nfor mu in [-0.001, 0, 0.001]:\n    S = GBM(sims=1, T=252, dt=1, s0=10, mu=mu, sigma=0.01, seed=10)\n    ax[0].plot(S, label=f\"$\\mu = ${mu}\")\n    ax[0].set(title=\"Drift Coefficient Sensitivity\", xlabel=\"days\", ylabel=\"Stock Price, £\")\nax[0].legend()\nfor sigma in [0.01, 0.05, 0.1]:\n    S = GBM(sims=1, T=252, dt=1, s0=10, mu=0, sigma=sigma, seed=10)\n    ax[1].plot(S, label=f\"$\\sigma = ${sigma}\")\nax[1].set(title=\"Diffusion Coefficient Sensitivity\", xlabel=\"days\", ylabel=\"Stock Price, £\")\nplt.legend()\nplt.show()\n", "meta": {"hexsha": "ba91afac2d8c3d6906745c019540345718abda08", "size": 4384, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/geometric-brownian-motion.py", "max_stars_repo_name": "LiamJHealy/LiamJHealy.github.io", "max_stars_repo_head_hexsha": "8a8b6e524f3c5ff2895e7141dee9dccab3358849", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/geometric-brownian-motion.py", "max_issues_repo_name": "LiamJHealy/LiamJHealy.github.io", "max_issues_repo_head_hexsha": "8a8b6e524f3c5ff2895e7141dee9dccab3358849", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/geometric-brownian-motion.py", "max_forks_repo_name": "LiamJHealy/LiamJHealy.github.io", "max_forks_repo_head_hexsha": "8a8b6e524f3c5ff2895e7141dee9dccab3358849", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1025641026, "max_line_length": 92, "alphanum_fraction": 0.6263686131, "include": true, "reason": "import numpy", "num_tokens": 1412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514736, "lm_q2_score": 0.9099070145888366, "lm_q1q2_score": 0.8641108215319788}}
{"text": "# generate interactive demo session running the script\n# below as input to scitools file2interactive\nimport sympy as sym\nimport sys\n\n# Integration associated with sine expansion for -u''=2\ni, j = sym.symbols('i j', integer=True)\nx, L = sym.symbols('x L')\n# Cannot do this one unless the arguments are i*x and j*x\n#A_ij = sym.integrate(sym.sin((i+1)*sym.pi*x/L)*sym.sin((j+1)*sym.pi*x/L),\n#                    (x, 0, L))\nA_ii = sym.integrate(sym.sin((i+1)*sym.pi*x/L)**2, (x, 0, L))\nprint(A_ii)\nf = 2\na = 2*L/(sym.pi**2*(i+1)**2)\nc_i = a*sym.integrate(f*sym.sin((i+1)*sym.pi*x/L), (x, 0, L))\nc_i = sym.simplify(c_i)\nprint(c_i)\nprint(sym.latex(c_i, mode='plain'))\n#sys.exit(0)\n\nx, x_m, h, X = sym.symbols('x x_m h X')\n\nfrom fe_approx1D_numint import *\nc = approximate(sym.sin(x), symbolic=True, d=1, N_e=4, numint='Trapezoidal',\n                Omega=[0,sym.pi])\nprint(c)\nc = approximate(sym.sin(x), symbolic=True, d=1, N_e=4, numint='Simpson',\n                Omega=[0,sym.pi])\nprint(c)\n#sys.exit(0)\nfrom fe_approx1D import *\n\n# \"Hand\"-integration of element matrix and vector\nA_00 = sym.integrate(h/8*(1-X)**2, (X, -1, 1))\nprint(A_00)\nprint(sym.latex(A_00, mode='plain'))\nA_10 = sym.integrate(h/8*(1+X)*(1-X), (X, -1, 1))\nprint(A_10)\nprint(sym.latex(A_10, mode='plain'))\nA_11 = sym.integrate(h/8*(1+X)**2, (X, -1, 1))\nprint(A_11)\nprint(sym.latex(A_11, mode='plain'))\nx = x_m + h/2*X\nb_0 = sym.integrate(h/4*x*(1-x)*(1-X), (X, -1, 1))\nb_1 = sym.integrate(h/4*x*(1-x)*(1+X), (X, -1, 1))\nprint(b_0)\nprint(b_1)\nprint(sym.latex(b_0, mode='plain'))\nprint(sym.latex(b_1, mode='plain'))\n\nphi = basis(d=1)\nphi\nelement_matrix(phi, Omega_e=[0.1, 0.2], symbolic=True)\nelement_matrix(phi, Omega_e=[0.1, 0.2], symbolic=False)\n\nh, x = sym.symbols('h x')\nnodes = [0, h, 2*h]\nelements = [[0, 1], [1, 2]]\nphi = basis(d=1)\nf = x*(1-x)\nA, b = assemble(nodes, elements, phi, f, symbolic=True)\nA\nb\nc = A.LUsolve(b)\nc\nfn = sym.lambdify([x], f)\n[fn(xc) for xc in nodes]\n\n# The corresponding numerical computations, as done by sympy and\n# still based on symbolic integration, goes as follows:\n\nnodes = [0, 0.5, 1]\nelements = [[0, 1], [1, 2]]\nphi = basis(d=1)\nx = sym.Symbol('x')\nf = x*(1-x)\nA, b = assemble(nodes, elements, phi, f, symbolic=False)\nA\nb\nc = A.LUsolve(b)\nc\n\nd=1; N_e=8; Omega=[0,1]  # 8 linear elements on [0,1]\nphi = basis(d)\nf = x*(1-x)\nnodes, elements = mesh_symbolic(N_e, d, Omega)\nA, b = assemble(nodes, elements, phi, f, symbolic=True)\nA\n\nfrom fe_approx1D_numint import *\nc = approximate(sym.sin(x), symbolic=True, d=1, N_e=4, numint='Trapezoidal',\n                Omega=[0,sym.pi])\nprint(c)\nc = approximate(sym.sin(x), symbolic=True, d=1, N_e=4, numint='Simpson',\n                Omega=[0,sym.pi])\nprint(c)\n\n# The integration does not work with sin(pi*x), but works fine with\n# sin(x) on [0,pi] instead.\n#approximate(sym.sin(sym.pi*x), symbolic=True, d=1, N_e=3, numint=None,\n#            Omega=[0,1])\nc = approximate(sym.sin(x), symbolic=True, d=1, N_e=2, numint=None,\n                Omega=[0,sym.pi])\nprint(sym.simplify(c[1,0].subs('h', sym.pi/2)))\n\n", "meta": {"hexsha": "546e0351d7d39e1b038583cc9f313d2af44a39f7", "size": 3049, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/.src/book/src/ex_fe_approx1D_session.py", "max_stars_repo_name": "hplgit/fem-book", "max_stars_repo_head_hexsha": "c23099715dc3cb72e7f4d37625e6f9614ee5fc4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 86, "max_stars_repo_stars_event_min_datetime": "2015-12-17T12:57:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T01:53:47.000Z", "max_issues_repo_path": "doc/.src/book/src/ex_fe_approx1D_session.py", "max_issues_repo_name": "hplgit/fem-book", "max_issues_repo_head_hexsha": "c23099715dc3cb72e7f4d37625e6f9614ee5fc4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-04-16T21:57:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-17T08:09:30.000Z", "max_forks_repo_path": "doc/.src/book/src/ex_fe_approx1D_session.py", "max_forks_repo_name": "hplgit/fem-book", "max_forks_repo_head_hexsha": "c23099715dc3cb72e7f4d37625e6f9614ee5fc4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2016-03-11T19:33:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T00:21:57.000Z", "avg_line_length": 28.4953271028, "max_line_length": 76, "alphanum_fraction": 0.6270908495, "include": true, "reason": "import sympy", "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780477, "lm_q2_score": 0.9099070145888367, "lm_q1q2_score": 0.8641108176435588}}
{"text": "# %%\nimport numpy as np\n# standard exponential function to each element \n# and normalizes these values by dividing by the sum \n# of all these exponentials. This normalization ensures\n# that the sum of the components of the output vector \n# is 1.\n\n\n# Write a function that takes as input \n# a list of numbers, and returns the list\n# of values given by the softmax function.\n\n# Returns a list\n\"\"\" def softmax(L):\n    expL = np.exp(L)\n    sumExpL = sum(expL)\n    result = []\n    for i in expL:\n        result.append(i/sumExpL)\n    return result \"\"\"\n\n# Alternatively...\n\"\"\" def softmax(L):\n    exp = np.exp(L)\n    return np.divide(exp, exp.sum()) \"\"\"\n\n# Returns an array\ndef softmax(L):\n    exponentials = np.exp(L)\n    sum_exponentials = sum(exponentials)\n    result = exponentials/sum_exponentials\n    return result\n\nsoftmax([1,2,3])\n\n# [0.09003057317038046, 0.24472847105479767, 0.6652409557748219]\n\n# %%\n# Quiz \n# Based on the above video, let's define the combination \n# of two new perceptrons as w1*0.4 + w2*0.6 + b. \n# Which of the following values for the weights and the \n# bias would result in the final probability of the point \n# to be 0.88?\n\ndef sigmoid(x):\n    return 1/(1+np.exp(-x))\n\n# Output (prediction) formula\ndef output_formula(features, weights, bias):\n    return sigmoid(np.dot(features, weights) + bias)\n\ninputs = [.4,.6]\nw1 = [2,6]\nb1 = -2\nw2 = [3,5]\nb2 = -2.2\nw3 = [5,4]\nb3 = -3\n\nprint(output_formula(inputs,w2,b2))\n\n# %%\n", "meta": {"hexsha": "2708be90fe909656331da54d255743ade3f51d0c", "size": 1444, "ext": "py", "lang": "Python", "max_stars_repo_path": "intro-neural-networks/softmax.py", "max_stars_repo_name": "lisah2u/deep-learning-v2-pytorch", "max_stars_repo_head_hexsha": "ed36729afeb0fbd6b99f3d57fc4bf2ba9ecfdea9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "intro-neural-networks/softmax.py", "max_issues_repo_name": "lisah2u/deep-learning-v2-pytorch", "max_issues_repo_head_hexsha": "ed36729afeb0fbd6b99f3d57fc4bf2ba9ecfdea9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intro-neural-networks/softmax.py", "max_forks_repo_name": "lisah2u/deep-learning-v2-pytorch", "max_forks_repo_head_hexsha": "ed36729afeb0fbd6b99f3d57fc4bf2ba9ecfdea9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2153846154, "max_line_length": 64, "alphanum_fraction": 0.6724376731, "include": true, "reason": "import numpy", "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561712637256, "lm_q2_score": 0.891811044719067, "lm_q1q2_score": 0.8640366342772184}}
{"text": "from numpy import array\nfrom numpy import mean\nfrom numpy import cov\nfrom numpy.linalg import eig\nimport pandas as pd\n\n# define a matrix\nA = array([[1, 2], [2, 3], [3, 2], [4, 4], [5, 4], [6, 7], [7, 6], [9, 7]])\n\nprint(\"We have the data:\")\nprint(A)\n# calculate the mean of each column\nM = mean(A.T, axis=1)\nprint(\"Step1: Let's compute the mean vector:\")\nprint(M)\n# center columns by subtracting column means\nC = A - M\nprint(\"Step2: Subtract the mean from data:\")\nprint(C)\n# calculate covariance matrix of centered matrix\nV = cov(C.T)\nprint(\"Step3: Let's calculate the covariance matrix:\")\nprint(V)\n# eigendecomposition of covariance matrix\nvalues, vectors = eig(V)\nprint(\"Step4: Let's calculate the eigen vectors and eigen values.\")\nprint(\"Eigen vectors:\")\nprint(vectors)\nprint(\"Eigen values:\")\nprint(values)\n\n# project data\nP = vectors.T.dot(C.T)\nprint(\"Step5: Projected Data:\")\nprint(P.T)\n", "meta": {"hexsha": "4a2b5ce65d7e872929e592a800237896272b90fd", "size": 892, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/models/ul/PCA.py", "max_stars_repo_name": "sanatanonline/ml", "max_stars_repo_head_hexsha": "bed8c45913f8b85af35f0c6f1ea6099e744a78f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/models/ul/PCA.py", "max_issues_repo_name": "sanatanonline/ml", "max_issues_repo_head_hexsha": "bed8c45913f8b85af35f0c6f1ea6099e744a78f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/ul/PCA.py", "max_forks_repo_name": "sanatanonline/ml", "max_forks_repo_head_hexsha": "bed8c45913f8b85af35f0c6f1ea6099e744a78f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7777777778, "max_line_length": 75, "alphanum_fraction": 0.701793722, "include": true, "reason": "from numpy", "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773708012852458, "lm_q2_score": 0.8840392832736084, "lm_q1q2_score": 0.864034182660761}}
{"text": "import numpy as np\n\ndef pascalindex2d(k):\n    \"\"\"\n    The purpose of this function is to prepare a set of combinations of m and n for the creation of the Jacobi polynomials that satisfy (m+n)<=k.\n    k: int, max order of the Jacobi polynomial desired\n\n    Returns: array of (ncomb x 2), where each row corresponds to a tuple of (m, n) values for the Jacobi polynomials. Take, for example, the monomial basis: {1, x1, x2, x1^2, x1x2, x2^2, ...}. The order of the polynomials in the variables x1 and x2 are (0, 0), (1, 0), (0, 1), (2, 0), (1, 1), (0, 2), which is exactly what this function outputs.\n    Remember the formula nplocal = (k+1)(k+2)/2 for 2D? This is just a formula for the number of elements up to that order (row) of the pascal triangle. Assuming each entry has equal area weighting, this formula basically calculates the \"area\" of the elements in pascal's triangule using A=(base1*base2)/2*(1/3)h - volume of a square pyramid is (1/3)bh.\n    \"\"\"\n\n    if k==0:\n        # Base case - top element in pascal triangle has index (0, 0)\n        return np.array([0, 0])[None, :]\n\n    # Builds the index pairs of the kth row of the triangle\n\n    nth_row = np.zeros((k+1, 2))\n    nth_row[:, 0] = np.arange(k+1)\n    nth_row[:, 1] = k - nth_row[:, 0]\n\n    nth_row = np.fliplr(nth_row)    # So it matches the 16.930 matlab code\n    # And then stacks it with the index pairs of the elements in the rows of the pyramid above it\n    prev_rows = pascalindex2d(k-1)\n    pindx = np.concatenate((prev_rows, nth_row), axis=0).astype(int)\n\n    return pindx\n\n\ndef pascalindex3d(k):\n    \"\"\"\n    The purpose of this function is to prepare a set of combinations of m, n, and l for the creation of the Jacobi polynomials that satisfy (m+n+l)<=k.\n    k: int, max order of the Jacobi polynomial desired\n\n    Returns: array of (ncomb x 3), where each row corresponds to a tuple of (m, n, l) values for the Jacobi polynomials.\n    Remember the formula nplocal = (k+1)(k+2)(k+3)/6 for 3D? This is just a formula for the number of elements up to that order (row) of the pascal pyramid. Assuming each entry has equal volume weighting, this formula basically calculates the \"volume\" of the elements in pascal's triangule using A=bh/2*(altitude)/3\n    Recursively \n    \"\"\"\n\n    if k==0:\n        # Base case - top element in pascal pyramid has index (0, 0, 0)\n        return np.array([0, 0, 0])[None,:]\n\n    # Builds the index pairs of the kth level of the pyramid\n    level2d_indices = pascalindex2d(k)  # 2D pascal indices on a level\n    nth_level = np.zeros((level2d_indices.shape[0], 3))\n    nth_level[:,1:] = level2d_indices\n    nth_level[:, 0] = k-np.sum(nth_level[:,1:], axis=1)   # Adds the third column/dimension so that the rows add to k\n\n    # nth_level = np.fliplr(nth_level)    # So it matches the 16.930 matlab code\n    # And then stacks it with the index pairs of the elements in the levels of the pyramid above it\n    prev_levels = pascalindex3d(k-1)\n    pindx = np.concatenate((prev_levels, nth_level), axis=0).astype(int)\n\n    return pindx\n\nif __name__ == '__main__':\n    print(pascalindex2d(3))\n    # print(pascalindex3d(3))", "meta": {"hexsha": "ff6eeb5aaec65d589e9dc0753cdf59d459c0434f", "size": 3120, "ext": "py", "lang": "Python", "max_stars_repo_path": "master/pascalindex.py", "max_stars_repo_name": "saustinp/3D-CG", "max_stars_repo_head_hexsha": "8d3e161674273649af1f23b2a0e1d5100971477a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "master/pascalindex.py", "max_issues_repo_name": "saustinp/3D-CG", "max_issues_repo_head_hexsha": "8d3e161674273649af1f23b2a0e1d5100971477a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "master/pascalindex.py", "max_forks_repo_name": "saustinp/3D-CG", "max_forks_repo_head_hexsha": "8d3e161674273649af1f23b2a0e1d5100971477a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.8813559322, "max_line_length": 353, "alphanum_fraction": 0.6814102564, "include": true, "reason": "import numpy", "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517061554855, "lm_q2_score": 0.899121379297294, "lm_q1q2_score": 0.8640122234766081}}
{"text": "import numpy as np\n\ndef sigmoid(z):\n    #          | \n    #          | .'''''   1\n    #         .|          0.5\n    #  .....'__|________  0\n    #          |\n    #          |\n    #          |\n    # sigmoid function\n    # output ranges form 0.0 to 1.0\n    # very useful for binary classification\n    \n    result = 1.0 / (1.0 + np.exp(-z))\n    return result\n\ndef sigmoid_prime(z):\n    # returns the derivative of sigmoid function as\n    # s'(z) = s(z).(1 - s(z))\n    \n    result = sigmoid(z)*(1.0 - sigmoid(z))\n    return result\n\ndef tanh(z):\n    #        |\n    #       1|  .....\n    # _______|._______\n    #       .|\n    #  ..... |-1\n    #        |\n    # hyperbolic tangent function\n    # output ranges from -1.0 to 1.0\n    \n    e = np.exp(z)\n    e_ = np.exp(-z)\n    result = (e - e_) / (e + e_)\n    return result\n\ndef tanh_prime(z):\n    # returns the derivative of hyperbolic tangent function as\n    # tanh'(z) = 1 - tanh(z)^2\n\n    result = 1 - np.power(tanh(z), 2)\n    return result\n\ndef relu(z):\n    #        |    .\n    #        |  .           \n    # __.....|.______  y = [x for x > 0\n    #        |             [0 otherwise\n    #        |\n    #        |\n    # called rectified linear unit\n    # returns the maximum of (0.0, z)\n    \n    result = np.maximum(0.0, z)\n    return result\n\ndef relu_prime(z): \n    # returns the derivative of relu function\n    # when z < 0, relu(z) = 0, a constant. so, derivative is 0\n    # when z > 0, relu(z) = z, so derivative is 1\n    \n    result = np.array(z, copy=True)\n    result[z <= 0.0] = 0.0\n    result[z > 0.0] = 1.0\n    return result\n\ndef leaky_relu(z):\n    #        |    .\n    #        |  .           \n    # _______|.______  y = [x for x > 0\n    #   .  ' |             [0.01 * x otherwise\n    #        |\n    #        |\n    # called leaky rectified linear unit\n    # returns the maximum of (0.01 * z, z)\n\n    result = np.maximum(0.01 * z, z)\n    return result\n\ndef leaky_relu_prime(z):\n    # returns the derivative of leaky relu function\n    # when z < 0, leaky_relu(z) = 0.01*z, so, derivative is 0.01\n    # when z > 0, leaky_relu(z) = z, so derivative is 1\n    \n    result = np.array(z, copy=True)\n    result[z <= 0.0] = 0.01\n    result[z > 0.0] = 1.0\n    return result\n\n# dictionary containing the mapping for activation functions to their string names\nactivations_forward = {\n    \"sigmoid\": sigmoid,\n    \"tanh\": tanh,\n    \"relu\": relu,\n    \"leaky_relu\": leaky_relu\n}\n\nactivations_backward = {\n    \"sigmoid\": sigmoid_prime,\n    \"tanh\": tanh_prime,\n    \"relu\": relu_prime,\n    \"leaky_relu\": leaky_relu_prime\n}", "meta": {"hexsha": "a4999e1f1855ebfccc9c942d6637cbc7998a9405", "size": 2553, "ext": "py", "lang": "Python", "max_stars_repo_path": "activation.py", "max_stars_repo_name": "manepal/net_xyz", "max_stars_repo_head_hexsha": "95ca19f65feb3e6d04c7e50ad439eafb2fd66b1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-09T11:44:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-09T11:44:02.000Z", "max_issues_repo_path": "activation.py", "max_issues_repo_name": "manepal/net_xyz", "max_issues_repo_head_hexsha": "95ca19f65feb3e6d04c7e50ad439eafb2fd66b1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "activation.py", "max_forks_repo_name": "manepal/net_xyz", "max_forks_repo_head_hexsha": "95ca19f65feb3e6d04c7e50ad439eafb2fd66b1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0849056604, "max_line_length": 82, "alphanum_fraction": 0.5029377203, "include": true, "reason": "import numpy", "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.8991213705121083, "lm_q1q2_score": 0.8640122140289921}}
{"text": "import numpy as np\n\ndef identity_function(x):\n    \"\"\"\n    (function) identity_function\n    ----------------------------\n    The identity function\n\n    Parameter\n    ---------\n    - x : input value(s)\n\n    Return\n    ------\n    - identity function output value(s)\n    \"\"\"\n    return x\n\ndef step_function(x):\n    \"\"\"\n    (function) step_function\n    ------------------------\n    The step function\n\n    Parameter\n    ---------\n    - x : input value(s)\n\n    Return\n    ------\n    - step function output value(s)\n    \"\"\"\n    return np.array(x > 0, dtype=np.int)\n\ndef sigmoid(x):\n    \"\"\"\n    (function) sigmoid\n    ------------------\n    The sigmoid function\n\n    Parameter\n    ---------\n    - x : input value(s)\n\n    Return\n    ------\n    - sigmoid function output value(s)\n    \"\"\"\n    return 1 / (1 + np.exp(-x))\n\ndef relu(x):\n    \"\"\"\n    (function) relu\n    ---------------\n    The ReLU function\n\n    Parameter\n    ---------\n    - x : input value(s)\n\n    Return\n    ------\n    - ReLU function output value(s)\n    \"\"\"\n    return np.maximum(0, x)\n\n# Softmax function\ndef softmax(x):\n    \"\"\"\n    (function) softmax\n    ------------------\n    The softmax function\n\n    Parameter\n    ---------\n    - x : input vector\n\n    Return\n    ------\n    - softmax function output vector = probability vector\n    \"\"\"\n    if x.ndim == 2:\n        x = x.T\n        x = x - np.max(x, axis=0)\n        y = np.exp(x) / np.sum(np.exp(x), axis=0)\n        return y.T\n\n    x = x - np.max(x)\n    return np.exp(x) / np.sum(np.exp(x))\n", "meta": {"hexsha": "e0c4fcb8af7a7736e301ae67357d9d4371212255", "size": 1501, "ext": "py", "lang": "Python", "max_stars_repo_path": "function/activation.py", "max_stars_repo_name": "kiseonjeong/neural-network-for-python", "max_stars_repo_head_hexsha": "902307699d59a0a38d45519a0bacd014ba705727", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-08T15:47:00.000Z", "max_issues_repo_path": "function/activation.py", "max_issues_repo_name": "kiseonjeong/neural-network-for-python", "max_issues_repo_head_hexsha": "902307699d59a0a38d45519a0bacd014ba705727", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "function/activation.py", "max_forks_repo_name": "kiseonjeong/neural-network-for-python", "max_forks_repo_head_hexsha": "902307699d59a0a38d45519a0bacd014ba705727", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.6777777778, "max_line_length": 57, "alphanum_fraction": 0.4676882079, "include": true, "reason": "import numpy", "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371972, "lm_q2_score": 0.8991213705121083, "lm_q1q2_score": 0.864012214028992}}
{"text": "import numpy as np\n\n\ndef sigmoid(x):\n    \"\"\"returns the value of x evaluated on the sigmoid function\"\"\"\n    return 1 / (1 + np.exp(-x))\n\n\ndef sigmoid_d(x):\n    \"\"\"returns the value of x evaluated on the derivative \n    of the sigmoid function\"\"\"\n    return sigmoid(x) * (1 - sigmoid(x))\n\n\ndef tanh(x):\n    \"\"\"returns the value of x evaluated on the hyperbolic tangent function\"\"\"\n    return np.tanh(x)\n\n\ndef tanh_d(x):\n    \"\"\"returns the value of x evaluated on the derivative \n    of the hyperbolic tangent function\"\"\"\n    return 1 - (tanh(x) ** 2)\n\n\ndef rrelu(x):\n    \"\"\"returns the value of x evaluated on the rectified linear unit function\"\"\"\n    x = np.where(x <= 0, 0.01 * x, x)\n    return x\n\n\ndef rrelu_d(x):\n    \"\"\"returns the value of x evaluated on the derivative\n    of the rectified linear unit function\"\"\"\n    return np.where(x <= 0, 0.01, 1)\n", "meta": {"hexsha": "3bc87273368cc56c84523050be92e8c143ebe980", "size": 856, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tarea1/activation_functions.py", "max_stars_repo_name": "aleluman/CC5114", "max_stars_repo_head_hexsha": "aae4ea9faf0a7cb3eb3bf53f8eecaf209aebf4d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tarea1/activation_functions.py", "max_issues_repo_name": "aleluman/CC5114", "max_issues_repo_head_hexsha": "aae4ea9faf0a7cb3eb3bf53f8eecaf209aebf4d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tarea1/activation_functions.py", "max_forks_repo_name": "aleluman/CC5114", "max_forks_repo_head_hexsha": "aae4ea9faf0a7cb3eb3bf53f8eecaf209aebf4d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7777777778, "max_line_length": 80, "alphanum_fraction": 0.6448598131, "include": true, "reason": "import numpy", "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769134963331, "lm_q2_score": 0.8856314692902446, "lm_q1q2_score": 0.8640016153053994}}
{"text": "import numpy as np\nfrom math import sqrt\nimport matplotlib.pyplot as plt\n\n'''\nThe following code solves the second order system:\n        u' = x + v; u(0) = 0\n        v' = u v^2; v(0) = 1\n        \nThe second order Runge Kutta method is used to solve this system.\nHere, x + v = f and u v^2 = g\n'''\ndef f(x, v):\n    return x + v #RHS of first order differential equation\n\ndef g(u, v):\n    return u*v*v\n\ndef rk4(f, g, x0, u0, v0, x1, n): #Runge-Kutta fourth order\n    #vx = [0] * (n + 1)\n    vx=np.zeros((n+1,1)) #using numpy array to define vector x\n    #print(vx) #for debugging only\n    #vy = [0] * (n + 1)\n    vu=np.zeros((n+1,1)) #using numpy array to define vector u\n    vv=np.zeros((n+1,1)) #using numpy array to define vector v\n    #print(vy) #for debugging only\n    h = (x1 - x0) / float(n) #Step size\n    vx[0] = x = x0 #x0 in (x0,x1)\n    vu[0] = u = u0 #initial condition u(x=x0)=u0\n    vv[0] = v = v0 #initial condition v(x=x0)=v0\n    for i in range(1, n + 1): #RK4 loop\n        #k1 = h * f(x, u, v) #this is a template for k1 for RK4\n        k1 = h * f(x, v)\n        #l1 = h * g(x, u, v) #this is a template for l1 for RK4\n        l1 = h * g(u, v)\n        \n        #k2 = h * f(x + 0.5 * h, u + 0.5 * k1, v + 0.5 * l1) #this is a template for k2 for RK4\n        k2 = h * f(x + 0.5 * h, v + 0.5 * l1)\n        #l2 = h * g(x + 0.5 * h, u + 0.5 * k1, v + 0.5 * l1) #this is a template for l2 for RK4\n        l2 = h * g(u + 0.5 * k1, v + 0.5 * l1)\n        \n        #k3 = h * f(x + 0.5 * h, u + 0.5 * k2, v + 0.5 * l2)\n        k3 = h * f(x + 0.5 * h, v + 0.5 * l2)\n        #l3 = h * g(x + 0.5 * h, u + 0.5 * k2, v + 0.5 * l2)\n        l3 = h * g(u + 0.5 * k2, v + 0.5 * l2)\n        \n        #k4 = h * f(x + h, u + k3)\n        k4 = h * f(x + h, v + l3)\n        #l4 = h * g(x + h, u + k3)\n        l4 = h * g(u + k3, v + l3)\n        \n        vx[i] = x = x0 + i * h #Proceed to next value of x\n        vu[i] = u = u + (k1 + k2 + k2 + k3 + k3 + k4) / 6 #next value of u\n        vv[i] = v = v + (l1 + l2 + l2 + l3 + l3 + l4) / 6 #next value of v\n        \n    return vx, vu, vv\n\nx1=1\nnodes=x1*20\nvx, vu, vv = rk4(f, g, 0, 0, 1, x1, nodes) #f, g, u0, v0, x0, \nm=nodes/float(10)\nprint vu\nprint vv\n\n#plt.plot(vu, vv, 'rp')\n#plt.axis([0, 5, 0, 100])\n#plt.show()\n\n\n##print(vx)\n##print(vu)\n##print(vv)\n\n##for x in list(zip(vx, vu, vv))[::1]:\n##    print x\n\n##for x, y in list(zip(vx, vu, vv))[::m]: #in [::m], prints every m elements\n##    print(\"%4.1f %10.5f %10.5f\" % (x, u, v))\n##print('\\n')\n\n", "meta": {"hexsha": "e0cd1a0835efa2b05d0985ad3e6fba3bab8487bb", "size": 2484, "ext": "py", "lang": "Python", "max_stars_repo_path": "ode_solver/rk_system.py", "max_stars_repo_name": "dnaneet/numcode", "max_stars_repo_head_hexsha": "7ec9345f65367a2690f4b9815d476e241edc2d52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ode_solver/rk_system.py", "max_issues_repo_name": "dnaneet/numcode", "max_issues_repo_head_hexsha": "7ec9345f65367a2690f4b9815d476e241edc2d52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ode_solver/rk_system.py", "max_forks_repo_name": "dnaneet/numcode", "max_forks_repo_head_hexsha": "7ec9345f65367a2690f4b9815d476e241edc2d52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6666666667, "max_line_length": 95, "alphanum_fraction": 0.4778582931, "include": true, "reason": "import numpy", "num_tokens": 1075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122768904644, "lm_q2_score": 0.9019206758704633, "lm_q1q2_score": 0.863960888197662}}
{"text": "import numpy as np\nimport math\nfrom plot import plot as plot\nimport scipy.linalg\n\n\ndef read_data(file_name):\n    file_object = open(file_name, \"r\")\n    result = []\n    for line in file_object.readlines():\n        parts = map(lambda part: float(part.strip()), line.split(\",\"))\n        if len(parts) != 2:\n            raise Exception(\"illegal line format\")\n        result.append((parts[0], parts[1]))\n    file_object.close()\n    return result\n\n\ndef get_b_from_data_list(data_list):\n    return np.matrix(map(lambda pair: [pair[1]], data_list))\n\n\ndef get_a_from_data_list(data_list, d):\n    e = math.e\n    return np.matrix(map(lambda pair: [e**(d * pair[0]), e**(-d * pair[0]), 1], data_list))\n\n\ndef get_d_list(n):\n    if n <= 2:\n        raise Exception(\"n is not > 2\")\n\n    result = []\n    for k in range(0, n):\n        result.append((k, 0.1 + 0.4 * k / (n - 1)))\n    return result\n\n\ndef r_rank(r):\n    if r.shape[0] != r.shape[1]:\n        raise Exception(\"r is not quadratic\")\n\n    counter = 0\n    eps = 10**-12\n    for i in range(0, r.shape[0]):\n        if not (-eps < r[i, i] < eps):\n            counter += 1\n    return counter\n\n\ndef main(file_name=\"data.txt\", n=7):\n    data_list = read_data(file_name)\n    b = get_b_from_data_list(data_list)\n    parameter_list = []\n    for k, d in get_d_list(n):\n        print(\"k={0}; n={1}\".format(k, n))\n        a = get_a_from_data_list(data_list, d)\n        q, r = np.linalg.qr(a)\n        if r_rank(r) != 3:\n            print(\"Rank of r or q is not 3!\")\n        else:\n            z = np.dot(q.T, b)\n            x = scipy.linalg.solve_triangular(r, z)\n\n            r = np.dot(a, x) - b\n            print(\"Residuum r = Ax - b = \")\n            print(str(r))\n\n            norm_r = np.linalg.norm(r)\n            print(\"Norm of Residuum: |r| = \" + str(norm_r))\n\n            cond_a = np.linalg.cond(a)\n            cond_ata = np.linalg.cond(np.dot(a.T, a))\n            print(\"cond(A) = {0}; cond(A^T A) = {1}\".format(cond_a, cond_ata))\n\n            parameter_list.append((x.item(0), x.item(1), x.item(2), d, k, n, norm_r, cond_a, cond_ata))\n\n        print(\"\")\n\n    plot(parameter_list, data_list)\n\n\nif __name__ == \"__main__\":\n    # available files:\n    #  - data.txt          - from task sheet\n    #  - data_subset.txt   - contains a subset from data.txt\n    #  - data_sym.txt      - contains manipulated (symmetric) data from data.txt\n    main(file_name=\"data.txt\", n=5)\n", "meta": {"hexsha": "587ec81ad34195fd281e6454455029e0c69c75f3", "size": 2403, "ext": "py", "lang": "Python", "max_stars_repo_path": "serie4/leastSquares_7.py", "max_stars_repo_name": "Koopakiller/Edu-NLA", "max_stars_repo_head_hexsha": "8376557cab9f74cedd19ee1573a8c71d7e415dd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "serie4/leastSquares_7.py", "max_issues_repo_name": "Koopakiller/Edu-NLA", "max_issues_repo_head_hexsha": "8376557cab9f74cedd19ee1573a8c71d7e415dd4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "serie4/leastSquares_7.py", "max_forks_repo_name": "Koopakiller/Edu-NLA", "max_forks_repo_head_hexsha": "8376557cab9f74cedd19ee1573a8c71d7e415dd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3068181818, "max_line_length": 103, "alphanum_fraction": 0.556803995, "include": true, "reason": "import numpy,import scipy", "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828602, "lm_q2_score": 0.9019206758704633, "lm_q1q2_score": 0.8639608827792796}}
{"text": "import sympy as sym\nx, L, C, D, c_0, c_1, = sym.symbols('x L C D c_0 c_1')\n\ndef model1(f, L, D):\n    \"\"\"Solve -u'' = f(x), u(0)=0, u(L)=D.\"\"\"\n    # Integrate twice\n    u_x = - sym.integrate(f, (x, 0, x)) + c_0\n    u = sym.integrate(u_x, (x, 0, x)) + c_1\n    # Set up 2 equations from the 2 boundary conditions and solve\n    # with respect to the integration constants c_0, c_1\n    r = sym.solve([u.subs(x, 0)-0,  # x=0 condition\n                   u.subs(x,L)-D],  # x=L condition\n                  [c_0, c_1])       # unknowns\n    # Substitute the integration constants in the solution\n    u = u.subs(c_0, r[c_0]).subs(c_1, r[c_1])\n    u = sym.simplify(sym.expand(u))\n    return u\n\ndef model2(f, L, C, D):\n    \"\"\"Solve -u'' = f(x), u'(0)=C, u(L)=D.\"\"\"\n    u_x = - sym.integrate(f, (x, 0, x)) + c_0\n    u = sym.integrate(u_x, (x, 0, x)) + c_1\n    r = sym.solve([sym.diff(u,x).subs(x, 0)-C,  # x=0 cond.\n                   u.subs(x,L)-D],              # x=L cond.\n                  [c_0, c_1])\n    u = u.subs(c_0, r[c_0]).subs(c_1, r[c_1])\n    u = sym.simplify(sym.expand(u))\n    return u\n\ndef model3(f, a, L, C, D):\n    \"\"\"Solve -(a*u')' = f(x), u(0)=C, u(L)=D.\"\"\"\n    au_x = - sym.integrate(f, (x, 0, x)) + c_0\n    u = sym.integrate(au_x/a, (x, 0, x)) + c_1\n    r = sym.solve([u.subs(x, 0)-C,\n                   u.subs(x,L)-D],\n                  [c_0, c_1])\n    u = u.subs(c_0, r[c_0]).subs(c_1, r[c_1])\n    u = sym.simplify(sym.expand(u))\n    return u\n\n\ndef demo():\n    f = 2\n    u = model1(f, L, D)\n    print(('model1:', u, u.subs(x, 0), u.subs(x, L)))\n    print((sym.latex(u, mode='plain')))\n    u = model2(f, L, C, D)\n    #f = x\n    #u = model2(f, L, C, D)\n    print(('model2:', u, sym.diff(u, x).subs(x, 0), u.subs(x, L)))\n    print((sym.latex(u, mode='plain')))\n    u = model3(0, 1+x**2, L, C, D)\n    print(('model3:', u, u.subs(x, 0), u.subs(x, L)))\n    print((sym.latex(u, mode='plain')))\n\nif __name__ == '__main__':\n    demo()\n\n\n", "meta": {"hexsha": "68068991f9eaee5d166d559f8c9cc67295153b00", "size": 1939, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/u_xx_f_sympy.py", "max_stars_repo_name": "mbarzegary/finite-element-intro", "max_stars_repo_head_hexsha": "47ef0a3592b823ae71a874ee35850114f16b6d8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-01-26T13:18:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T15:20:11.000Z", "max_issues_repo_path": "src/u_xx_f_sympy.py", "max_issues_repo_name": "mbarzegary/finite-element-intro", "max_issues_repo_head_hexsha": "47ef0a3592b823ae71a874ee35850114f16b6d8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/u_xx_f_sympy.py", "max_forks_repo_name": "mbarzegary/finite-element-intro", "max_forks_repo_head_hexsha": "47ef0a3592b823ae71a874ee35850114f16b6d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-05T23:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T10:22:29.000Z", "avg_line_length": 32.3166666667, "max_line_length": 66, "alphanum_fraction": 0.4899432697, "include": true, "reason": "import sympy", "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889437, "lm_q2_score": 0.90192067059785, "lm_q1q2_score": 0.8639608820632846}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb  8 21:41:08 2019\n\n@author: alankar\n\"\"\"\n\n#import numpy as np\n#import matplotlib.pyplot as plt\n\ndef simpson(func, a, b, n,*args):\n    h=(b-a)/n\n    k=0.0\n    x=a + h\n    for i in range(1,int(n/2) + 1):\n        k += 4*func(x,*args)\n        x += 2*h\n\n    x = a + 2*h\n    for i in range(1,int(n/2)):\n        k += 2*func(x,*args)\n        x += 2*h\n    return (h/3)*(func(a,*args)+func(b,*args)+k)\n\nf = lambda x:x**4-2*x+1\n\nprint('\\n\\nSIMPSON RULE:')\nn = 10\nprint('Slices = %d'%n)\nI1 = simpson(f,0,2,n)\n\nn = 20\nI2 = simpson(f,0,2,n)\n\nprint('Fractional error estimate: %e'%abs((I2-I1)/I2))\n\n\"\"\"\nThe results vary from the actual esult comparison of problem 2 for N=10 \nbecause of the truncation error associated with both I1 and I2.\nI2 is closer to actual value but still off by the truncation error (which is smaller than I1)\n\"\"\"", "meta": {"hexsha": "068250542ff4d457ba3cbde72c65aa1697b38ba0", "size": 890, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw3/06/6.py", "max_stars_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_stars_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:47:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:05:39.000Z", "max_issues_repo_path": "hw3/06/6.py", "max_issues_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_issues_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw3/06/6.py", "max_forks_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_forks_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-21T17:33:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T02:58:56.000Z", "avg_line_length": 21.1904761905, "max_line_length": 93, "alphanum_fraction": 0.595505618, "include": true, "reason": "import numpy", "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452442, "lm_q2_score": 0.9111797027760039, "lm_q1q2_score": 0.863939169888431}}
{"text": "import matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nmatplotlib.use('Agg')\n\nimport numpy as np\nimport sys\nfrom os.path import join, isfile\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndef grad_desc(x, y, eta=1e-2, epsilon=1e-15):\n\n    # eta = learning rate\n    # epsilon = error\n    # m = number of examples\n    m = x.shape[0]\n\n    # x[i][0] = 1 for intercept term\n    x = np.hstack((np.ones(x.shape), x))\n\n    # theta = parameters learnt by model\n    theta = np.array([0., 0.])\n\n    # number of iterations\n    iterations = 0\n\n    # all the iterations of theta\n    theta_vals = []\n    prev_cost_value = 0.0\n\n    x = x.T\n    y = y.T\n\n    while True:\n\n        # cost function and gradient calculation\n        diff_errors = np.tile(np.matmul(theta[np.newaxis, :], x)[0] - y[0], (2, 1))\n        grad = np.sum(diff_errors * x, axis=1) / m\n        cost_value = np.sum(diff_errors[0] ** 2) / (2 * m)\n\n        # append current value of theta to all theta values\n        theta_vals.append(np.hstack((theta, np.array([cost_value]))))\n\n        # change in the value of theta during gradient update\n        diff = eta * grad\n        theta = theta - diff\n        iterations += 1\n\n        # convergence criterion\n        if abs(cost_value - prev_cost_value) < epsilon:\n            break\n\n        prev_cost_value = cost_value\n\n    return np.array(theta_vals).T, theta, eta, ('change in cost function is less than ' + str(epsilon)), iterations\n\ndef main():\n\n    # read command-line arguments\n    data_dir = sys.argv[1]\n    out_dir = sys.argv[2]\n    part = sys.argv[3]\n\n    # check for existence of input files\n    for c in ['X', 'Y']:\n        if not isfile(join(data_dir, 'linear' + c + '.csv')):\n            raise Exception('linear' + c + '.csv not found')\n\n    # read from csv file\n    x = np.array([np.genfromtxt(join(data_dir, 'linearX.csv'))]).T\n    y = np.array([np.genfromtxt(join(data_dir, 'linearY.csv'))]).T\n\n    # normalization step\n    x_mean = np.sum(x) / x.shape[0]\n    x -= np.full_like(x, x_mean)\n    x_stddev = np.sqrt(np.sum(x ** 2) / x.shape[0])\n    x /= x_stddev\n\n    # call gradient descent on the given data\n    theta_vals, theta, learning_rate, stopping_criteria, total_iterations = grad_desc(x, y)\n\n    if part == 'a':\n        # write the output for 1a\n        output_file = open(join(out_dir, '1aoutput.txt'), mode='w')\n        output_file.write('learning_rate = ' + str(learning_rate) + '\\n')\n        output_file.write('stopping_criteria = ' + stopping_criteria + '\\n')\n        output_file.write('theta_0 = ' + str(theta[0]) + '\\n')\n        output_file.write('theta_1 = ' + str(theta[1]) + '\\n')\n        output_file.write('total_iterations = ' + str(total_iterations) + '\\n')\n        output_file.close()\n        print('learning_rate = ' + str(learning_rate))\n        print('stopping_criteria = ' + stopping_criteria)\n        print('theta_0 = ' + str(theta[0]))\n        print('theta_1 = ' + str(theta[1]))\n        print('total_iterations = ' + str(total_iterations))\n        return 0\n\n    # PART B: plot the graphs for 1b\n\n    fig1b, ax1b = plt.subplots()\n    ax1b.scatter(x * x_stddev + x_mean, y)\n    X0 = np.arange(-2, 5, 0.1)\n    ax1b.plot(X0 * x_stddev + x_mean, theta[0] + theta[1] * X0)\n\n    ax1b.set_xlabel('Acidity')\n    ax1b.set_ylabel('Density')\n    if part == 'b':\n        fig1b.savefig(join(out_dir, 'regression_plot.png'))\n        plt.show()\n        return 0\n    plt.close(fig1b)\n\n    # PART C: plot the graph for 1c\n\n    # X, Y, Z - theta_0, theta_1, cost function\n    (X, Y), Z = np.meshgrid(np.linspace(-0.5, 2, 1000), np.linspace(-0.7, 0.7, 1000)), 0\n    for i in range(x.shape[0]):\n        Z += ((X + Y * x[i][0]) - y[i]) ** 2\n    Z /= 2 * x.shape[0]\n\n    # actually starting the plot\n    fig1c = plt.figure()\n    ax1c = fig1c.gca(projection='3d')\n    ax1c.plot_surface(X, Y, Z)\n    ax1c.set_xlabel('Theta_0')\n    ax1c.set_ylabel('Theta_1')\n    ax1c.set_zlabel('Cost function')\n    plot1c = ax1c.plot([theta_vals[0][0]], [theta_vals[1][0]], [theta_vals[2][0]])\n\n    # update function for animation\n    def update1c(nums):\n        plot1c[0].set_data(theta_vals[0:2, :nums])\n        plot1c[0].set_3d_properties(theta_vals[2, :nums])\n        return plot1c\n\n    # performing the animation\n    anim1c = animation.FuncAnimation(fig1c, update1c, theta_vals.shape[1], interval=200, blit=True)\n    update1c(theta_vals.shape[1])\n    if part == 'c':\n        fig1c.savefig(join(out_dir, '1clast_frame.png'))\n        plt.show()\n        return 0\n    plt.close(fig1c)\n\n    # PART D: plot the graph for 1d\n\n    fig1d, ax1d = plt.subplots()\n    ax1d.contour(X, Y, Z, 100)\n    ax1d.set_xlabel('Theta_0')\n    ax1d.set_ylabel('Theta_1')\n    plot1d = ax1d.plot([theta_vals[0, 0]], [theta_vals[1, 0]])\n    # update function for animation\n    def update1d(nums):\n        plot1d[0].set_data(theta_vals[0:2, :nums])\n        return plot1d\n    # performing the animation\n    anim1d = animation.FuncAnimation(fig1d, update1d, theta_vals.shape[1], interval=200, blit=True)\n    update1d(theta_vals.shape[1])\n    if part == 'd':\n        fig1d.savefig(join(out_dir, '1dlast_frame.png'))\n        plt.show()\n        return 0\n    plt.close(fig1d)\n\n    # PART E: plot the graphs for 1e\n\n    learning_parameters = [(1e-3, 1e-15), (25e-2, 1e-15), (1e-1, 1e-15)]\n\n    eta, epsilon = learning_parameters[0]\n    theta_vals1, _, _, _, _ = grad_desc(x, y, eta, epsilon)\n\n    fig1e1, ax1e1 = plt.subplots()\n    ax1e1.contour(X, Y, Z, 100)\n    ax1e1.set_xlabel('Theta_0')\n    ax1e1.set_ylabel('Theta_1')\n\n    plot1e1 = ax1e1.plot([theta_vals1[0, 0]], [theta_vals1[1, 0]])\n\n    # update function for animation\n    def update1e1(nums):\n        plot1e1[0].set_data(theta_vals1[0:2, :nums])\n        return plot1e1\n\n    # performing the animation\n    anim1e1 = animation.FuncAnimation(fig1e1, update1e1, theta_vals1.shape[1], interval=200, blit=True)\n    update1e1(theta_vals1.shape[1])\n    if part == 'e':\n        fig1e1.savefig(join(out_dir, '1e1last_frame.png'))\n\n    eta, epsilon = learning_parameters[1]\n    theta_vals2, _, _, _, _ = grad_desc(x, y, eta, epsilon)\n\n    fig1e2, ax1e2 = plt.subplots()\n    ax1e2.contour(X, Y, Z, 100)\n    ax1e2.set_xlabel('Theta_0')\n    ax1e2.set_ylabel('Theta_1')\n\n    plot1e2 = ax1e2.plot([theta_vals2[0, 0]], [theta_vals2[1, 0]])\n\n    # update function for animation\n    def update1e2(nums):\n        plot1e2[0].set_data(theta_vals2[0:2, :nums])\n        return plot1e2\n\n    # performing the animation\n    anim1e2 = animation.FuncAnimation(fig1e2, update1e2, theta_vals2.shape[1], interval=200, blit=True)\n    update1e2(theta_vals2.shape[1])\n    if part == 'e':\n        fig1e2.savefig(join(out_dir, '1e2last_frame.png'))\n\n    eta, epsilon = learning_parameters[2]\n    theta_vals3, _, _, _, _ = grad_desc(x, y, eta, epsilon)\n\n    fig1e3, ax1e3 = plt.subplots()\n    ax1e3.contour(X, Y, Z, 100)\n    ax1e3.set_xlabel('Theta_0')\n    ax1e3.set_ylabel('Theta_1')\n\n    plot1e3 = ax1e3.plot([theta_vals3[0, 0]], [theta_vals3[1, 0]])\n\n    # update function for animation\n    def update1e3(nums):\n        plot1e3[0].set_data(theta_vals3[0:2, :nums])\n        return plot1e3\n\n    # performing the animation\n    anim1e3 = animation.FuncAnimation(fig1e3, update1e3, theta_vals3.shape[1], interval=200, blit=True)\n    update1e3(theta_vals3.shape[1])\n    if part == 'e':\n        fig1e3.savefig(join(out_dir, '1e3last_frame.png'))\n\n    if part == 'e':\n        plt.show()\n\n    return 0\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "f064a739d67f2586d9b7beb6e6277d24f66be9b4", "size": 7466, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignment1/Q1/q1.py", "max_stars_repo_name": "NavneelSinghal/COL774", "max_stars_repo_head_hexsha": "d8b473b9cd05984ef4ffe8642ce3ce5cb9a17252", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment1/Q1/q1.py", "max_issues_repo_name": "NavneelSinghal/COL774", "max_issues_repo_head_hexsha": "d8b473b9cd05984ef4ffe8642ce3ce5cb9a17252", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment1/Q1/q1.py", "max_forks_repo_name": "NavneelSinghal/COL774", "max_forks_repo_head_hexsha": "d8b473b9cd05984ef4ffe8642ce3ce5cb9a17252", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.979253112, "max_line_length": 115, "alphanum_fraction": 0.6205464774, "include": true, "reason": "import numpy", "num_tokens": 2330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802362, "lm_q2_score": 0.9111797027760039, "lm_q1q2_score": 0.8639391685535454}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import CubicSpline\nfrom scipy.optimize import curve_fit\n\n'''\nO codigo de geracao de splines cubicas e seus graficos foi modificado da seguinte fonte:\nhttps://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.CubicSpline.html\n'''\n#Funcao do enunciado\ndef f(x):\n    return 1.0/(1.0 + 25.0*x*x)\n\nx_k = np.linspace(2, 28, 26) #Vetor contendo o valor para k utilizados em cada iteracao \ne_k = [] #Vetor para armazenar o erro maximo para determinado k de x_k[], correspondendo a k+1 pontos \nxOriginal = np.linspace(-1.0, 1.0, 1000) #Recurso usado para impressao das funcoes\nyOriginal = f(xOriginal)\n\n#Calculo do erro maximo para i = k+1 pontos utilizados\n\n#Splines Naturais\nfor i in range(3, 29, 1):\n\n    #Gerando pontos igualmente espacados e seus respectivos valores em f(x)\n    xPontos = np.linspace(-1.0, 1.0, i) \n    yPontos = f(xPontos)\n\n    #cs armaneza a spline cubica propriamente dita\n    cs = CubicSpline(xPontos, yPontos, bc_type='natural')\n\n    xcs = np.linspace(-1.0, 1.0, 1000) #Recurso usado para impressao da spline\n    ycs = cs(xcs)\n\n    #Calculo do erro\n    e_aux = abs(f(xOriginal) - cs(xOriginal))\n    e_k.append(float(np.amax(e_aux)))\n\n'''\n#Plot da funcao spline cubica\nplt.plot(xOriginal,yOriginal,label = \"Função Original\")\nplt.plot(xPontos, yPontos,'o',label = \"Pontos\")\nplt.plot(xcs, ycs, label=\"Spline cubica\")\nplt.xlim(-1.5, 1.5)\nplt.ylim(-0.4, 1.2)\nplt.title('Funcao original e spline cubica')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend(loc='upper left')\n\nplt.show()\n'''\n\n#Plot do erro para spline natural\nplt.plot(x_k, e_k, label = \"Função Erro\")\nplt.plot(x_k, e_k, 'o', label = \"Pontos do Erro\")\nplt.title('Erro em funcao de k')\nplt.xlabel('k')\nplt.ylabel('Erro')\nplt.legend(loc='upper right')\nplt.xticks(range(0, 32, 2))\nplt.show()\n\n#Aproximacao Ch^q para Splines Naturais\n'''\nCom n pontos -> dividimos o intervalo [-1, 1], de tamanho 2, em (n-1) partes.\nAssim os pontos distam: h = 2/(n-1)\n'''\n#Definindo o formato da funcao que relaciona o erro e a distancia entre os pontos\ndef errorFunc(h, C, q):\n    return C*(h**q)\n\n#Preenchendo vetor que representa a distancia entre os pontos para dado numero de pontos\nh = []\n\nfor j in range(3, 29, 1):\n    h.append(2 / (j-1))\n\n#Usando minimos quadrados para encontrar os parametros C e q\nparametros = curve_fit(errorFunc, h, e_k)\n[C, q] = parametros[0]\n\nprint('\\nNa aproximacao Ch^q para spline natural, temos:','\\nC = ', C, '\\nq = ', q, '\\n')\n\n#Definindo a funcao errorFunc com os parametros corretos \ndef error(h):\n    return C*(h**q)\n\nx_error = np.linspace(0.05, 1.1, 1000)\ny_error = error(x_error)\n\n#Plot dos pontos e da funcao error\nplt.plot(h, e_k, 'o', label = 'Pontos do erro')\nplt.plot(x_error, y_error, label = 'Curva ajustada por minimos quadrados (Ch^q)')\nplt.title('Valor do erro em funcao da distancia entre os pontos (para spline natural)')\nplt.xlabel('Distancia entre os pontos (h)')\nplt.ylabel('Erro')\nplt.legend(loc='upper left')\nplt.show()\n\n####### SPLINE COM DERIVADA CONHECIDA NOS EXTREMOS #######\n'''\nComo f'(-1) = 0.07396 e f'(1) = -0.07396, temos que as novas condicoes de contorno\nsao cs''(-1) = 0.07396 e cs''(1) = -0.07396.\n'''\n\n#Calculando o erro\ne_k_2 = []\n\nfor i in range(3, 29, 1):\n\n    #Gerando pontos igualmente espacados e seus respectivos valores em f(x)\n    xPontos_2 = np.linspace(-1.0, 1.0, i) \n    yPontos_2 = f(xPontos_2)\n\n    #cs armaneza a spline cubica propriamente dita\n    cs2 = CubicSpline(xPontos_2, yPontos_2, bc_type = ((1, 0.07396),(1, -0.07396)))\n\n    #Calculo do erro\n    e_aux2 = abs(f(xOriginal) - cs2(xOriginal))\n    e_k_2.append(float(np.amax(e_aux2)))\n\n#Aproximacao Ch^q para Splines com Derivada Conhecida nos Extremos\n\n#Usando minimos quadrados para encontrar os parametros C e q\nparametros2 = curve_fit(errorFunc, h, e_k_2)\n[C2, q2] = parametros2[0]\n\nprint('\\nNa aproximacao Ch^q para derivada conhecida nos extremos, temos:','\\nC = ', C2, '\\nq = ', q2, '\\n')\n\n#Definindo a funcao errorFunc com os parametros corretos \ndef error_2(h):\n    return C2*(h**q2)\n\nx_error2 = np.linspace(0.05, 1.1, 1000)\ny_error2 = error_2(x_error)\n\n#Plot dos pontos e da funcao error\nplt.plot(h, e_k_2, 'o', label = 'Pontos do erro')\nplt.plot(x_error2, y_error2, label = 'Curva ajustada por minimos quadrados (Ch^q)')\nplt.title('Valor do erro em funcao da distancia entre os pontos (derivada conhecida nos extremos)')\nplt.xlabel('Distancia entre os pontos (h)')\nplt.ylabel('Erro')\nplt.legend(loc='upper left')\nplt.show()", "meta": {"hexsha": "51d8e39d3122a6406311a6550971cf427ab4f011", "size": 4514, "ext": "py", "lang": "Python", "max_stars_repo_path": "cubic_spline.py", "max_stars_repo_name": "Marcos-Pietrucci/T2-Calculo-Numerico", "max_stars_repo_head_hexsha": "d6c83c86b1edc5c839b4f137907911b76c0ee4e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-24T21:40:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-24T21:40:20.000Z", "max_issues_repo_path": "cubic_spline.py", "max_issues_repo_name": "Marcos-Pietrucci/T2-Calculo-Numerico", "max_issues_repo_head_hexsha": "d6c83c86b1edc5c839b4f137907911b76c0ee4e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cubic_spline.py", "max_forks_repo_name": "Marcos-Pietrucci/T2-Calculo-Numerico", "max_forks_repo_head_hexsha": "d6c83c86b1edc5c839b4f137907911b76c0ee4e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3472222222, "max_line_length": 108, "alphanum_fraction": 0.6987151086, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545318852121, "lm_q2_score": 0.9111797003640646, "lm_q1q2_score": 0.8639391622619975}}
{"text": "#!/usr/bin/env python3\n\nimport numpy as np\nimport math as m\n\nA = [[4, 12, -16],[12, 37, -43], [-16, -43, 98]]\nA = np.array(A)\n\n# shape[0] --> lignes i\n# shape[1] --> colonnes j\n\ndef cholesky(A):\n    '''Returns cholesky decomposition of A = L * L.T'''\n    \n    n = A.shape[0]\n    L = np.zeros((n, n))\n\n    for i in range(n):\n        L[i][i] = m.sqrt(A[i][i] - np.dot(L[i][:],L[i][:]))\n        for j in range(i+1, n):\n            L[j][i] = (A[j][i] - np.dot(L[i,:], L[j, :]))/L[i][i]\n    return L\n#print(cholesky(A))\n\n\n########## THINKING OF THE ABY IMPLEMENTATION #########\n#-----------------------------------------------------#\n\n# Okay.. Let's rewrite this code as a lower level as possible!\n\n# New input data as form of a list\nA = [4, 12, -16, 12, 37, -43, -16, -43, 98]\nn = 3\nL = [0, 0, 0, 0, 0, 0, 0, 0, 0]\ndef cholesky_dec(A):\n\n    # Initiating empty matrix L\n    L = [0]*len(A)\n    n = m.sqrt(len(A))\n    \n    for i in range(n):\n        # Calculating the np.dot inside the square root..\n        mul = 0\n        for k in range(n): mul += L[i*n+k]**2\n        # Getting diagonal elements\n        L[i*n+i] = m.sqrt(A[i*n+i] - mul) \n        for j in range(i+1, n):\n            mul = 0\n            for k in range(n): \n                mul += L[i*n+k]*L[j*n+k]\n            # Getting the [j][i] element\n            L[j*n+i] = (A[j*n+i]-mul)/L[i*n+i]\n    return L\n\n", "meta": {"hexsha": "b650422403ba544358c99a463dc55ee162e1c415", "size": 1361, "ext": "py", "lang": "Python", "max_stars_repo_path": "Modules/cholesky/cholesky.py", "max_stars_repo_name": "williamclot/PrivacyPreservingRidgeRegression", "max_stars_repo_head_hexsha": "5e0379162bdf114d862982a5ac438f076aa3c81b", "max_stars_repo_licenses": ["X11"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-19T13:38:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-19T13:38:51.000Z", "max_issues_repo_path": "Modules/cholesky/cholesky.py", "max_issues_repo_name": "williamclot/PrivacyPreservingRidgeRegression", "max_issues_repo_head_hexsha": "5e0379162bdf114d862982a5ac438f076aa3c81b", "max_issues_repo_licenses": ["X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/cholesky/cholesky.py", "max_forks_repo_name": "williamclot/PrivacyPreservingRidgeRegression", "max_forks_repo_head_hexsha": "5e0379162bdf114d862982a5ac438f076aa3c81b", "max_forks_repo_licenses": ["X11"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-05T06:46:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T06:46:01.000Z", "avg_line_length": 24.7454545455, "max_line_length": 65, "alphanum_fraction": 0.4614254225, "include": true, "reason": "import numpy", "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357579585026, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.8639284335644078}}
{"text": "import numpy as np\n\n\ndef gaussian_kernel(x1, x2, sigma):\n    \"\"\"\n    Implementing a gaussian kernel function.\n    Although scikit-learn has a gaussian kernel built in, for transparency we'll implement one from scratch:\n    \"\"\"\n    return np.exp(-(np.sum((x1 - x2) ** 2) / (2 * (sigma ** 2))))\n\n# x1 = np.array([1.0, 2.0, 1.0])\n# x2 = np.array([0.0, 4.0, -1.0])\n# sigma = 2\n# gaussian_kernel(x1, x2, sigma)\n", "meta": {"hexsha": "32277c911753c31612991fd8b1a163c0428fd6fc", "size": 406, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine_learning/supervised_learning/utils.py", "max_stars_repo_name": "EliorBenYosef/data-science", "max_stars_repo_head_hexsha": "117e5254f63e482c02aff394780bbdc205d492a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "machine_learning/supervised_learning/utils.py", "max_issues_repo_name": "EliorBenYosef/data-science", "max_issues_repo_head_hexsha": "117e5254f63e482c02aff394780bbdc205d492a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "machine_learning/supervised_learning/utils.py", "max_forks_repo_name": "EliorBenYosef/data-science", "max_forks_repo_head_hexsha": "117e5254f63e482c02aff394780bbdc205d492a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0666666667, "max_line_length": 108, "alphanum_fraction": 0.618226601, "include": true, "reason": "import numpy", "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971992476960077, "lm_q2_score": 0.888758786126321, "lm_q1q2_score": 0.863866853946954}}
{"text": "\"\"\"\n\nidentity\n\nThe identity tool returns an identity array. An identity array is a square matrix with all the main diagonal elements as\nand the rest as\n\n. The default type of elements is float.\n\nimport numpy\nprint numpy.identity(3) #3 is for  dimension 3 X 3\n\n#Output\n[[ 1.  0.  0.]\n [ 0.  1.  0.]\n [ 0.  0.  1.]]\n\neye\n\nThe eye tool returns a 2-D array with\n's as the diagonal and 's elsewhere. The diagonal can be main, upper or lower depending on the optional parameter . A positive is for the upper diagonal, a negative is for the lower, and a\n\n(default) is for the main diagonal.\n\nimport numpy\nprint numpy.eye(8, 7, k = 1)    # 8 X 7 Dimensional array with first upper diagonal 1.\n\n#Output\n[[ 0.  1.  0.  0.  0.  0.  0.]\n [ 0.  0.  1.  0.  0.  0.  0.]\n [ 0.  0.  0.  1.  0.  0.  0.]\n [ 0.  0.  0.  0.  1.  0.  0.]\n [ 0.  0.  0.  0.  0.  1.  0.]\n [ 0.  0.  0.  0.  0.  0.  1.]\n [ 0.  0.  0.  0.  0.  0.  0.]\n [ 0.  0.  0.  0.  0.  0.  0.]]\n\nprint numpy.eye(8, 7, k = -2)   # 8 X 7 Dimensional array with second lower diagonal 1.\n\nTask\n\nYour task is to print an array of size\nX with its main diagonal elements as 's and\n\n's everywhere else.\n\nInput Format\n\nA single line containing the space separated values of\nand .\ndenotes the rows.\n\ndenotes the columns.\n\nOutput Format\n\nPrint the desired\nX\n\narray.\n\nSample Input\n\n3 3\n\nSample Output\n\n[[ 1.  0.  0.]\n [ 0.  1.  0.]\n [ 0.  0.  1.]]\n\"\"\"\n\n\n\n\n\nimport numpy\nprint(str(numpy.eye(*map(int,input().split())))\n      .replace('1',' 1').replace('0',' 0'))\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "3a8cf2f3a82333c40cc5080f306530f6b6ef4084", "size": 1509, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numpy/Eye_and_Identity.py", "max_stars_repo_name": "NikolayVaklinov10/Python_Challenges", "max_stars_repo_head_hexsha": "a1052e1d527004bbb6072a3cbc802065469f66ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-01T23:57:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-01T23:58:16.000Z", "max_issues_repo_path": "Numpy/Eye_and_Identity.py", "max_issues_repo_name": "NikolayVaklinov10/Python_Challenges", "max_issues_repo_head_hexsha": "a1052e1d527004bbb6072a3cbc802065469f66ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numpy/Eye_and_Identity.py", "max_forks_repo_name": "NikolayVaklinov10/Python_Challenges", "max_forks_repo_head_hexsha": "a1052e1d527004bbb6072a3cbc802065469f66ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.5824175824, "max_line_length": 188, "alphanum_fraction": 0.6043737575, "include": true, "reason": "import numpy", "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.9284088025362857, "lm_q1q2_score": 0.8638456365836703}}
{"text": "import numpy as np\r\nfrom scipy import stats\r\nimport matplotlib.pyplot as plt\r\nfrom math import sqrt\r\n\r\n########################################################################################\r\n# I.\r\n\r\n# it is important to fix a seed in order to have the same random numbers every time we run the program\r\n# therefore, we can compare every run with different parameters\r\n# if we use different random numbers for each one, the comparison depends on the randomness\r\nnp.random.seed(10)\r\nN = 10**4 #number of points of the data sample\r\nmean = np.array([2,1])\r\nsigma_1 = 1\r\nsigma_2 = 2\r\nrho = 0.999\r\ncov = [[sigma_1**2, rho*sigma_1*sigma_2], [rho*sigma_1*sigma_2, sigma_2**2]]\r\n\r\nL = np.linalg.cholesky(cov)\r\n# print(L)\r\n\r\nuncorrelated = np.random.normal(0,1,(2,N))\r\n\r\n#now we apply the transformation\r\n\r\n# we cannot do broadcasting if both arrays do not have the same dimensions (ie 2D)\r\n# reshape of mean in order to do broadcasting\r\ndata = mean.reshape(2,1) + np.dot(L, uncorrelated)\r\n# print(mean.reshape(2,1)[0,0], mean.reshape(2,1)[1,0])\r\n# print(data.shape)\r\n# (2, N)\r\n\r\nplt.figure(1)\r\nplt.scatter(data[0,:], data[1,:], color = \"black\", s = 0.1)\r\nplt.xticks(np.arange(-12,12,1))\r\nplt.yticks(np.arange(-10,10,1))\r\nplt.xlim(-6,10)\r\nplt.ylim(-7,9)\r\nplt.xlabel(r\"$x_1$\")\r\nplt.ylabel(r\"$x_2$\")\r\n\r\n#################################################\r\n# alternative: if instead we use\r\n\"\"\"\r\nplt.figure(2)\r\ndata2 = np.random.multivariate_normal(mean, cov, N)\r\nplt.scatter(data2[:,0], data2[:,1], color = \"black\", s = 1)\r\n\"\"\"\r\n\r\n# plt.show()\r\n\r\n\r\n########################################################################################\r\n# III.\r\n\r\ndef posterior_pdf_2(mu):\r\n    \"\"\"\r\n    this is the posterior pdf computed in II. We want to sample this for different values of mu.\r\n    this function brings problems as explained at the end of the function\r\n    \"\"\"\r\n    mean_1 = mu[0]\r\n    mean_2 = mu[1]\r\n    x_1 = data[0, :]  # data fixed from the first experiment\r\n    x_2 = data[1, :]\r\n\r\n    posterior = np.exp(-1 / (2 * (1 - rho ** 2)) * (\r\n    (x_1 - mean_1) ** 2 / sigma_1 ** 2 - 2 * rho * (x_1 - mean_1) * (x_2 - mean_2) / (sigma_1 * sigma_2) +\r\n    (x_2 - mean_2) ** 2 / sigma_2 ** 2))\r\n\r\n    # for the moment we have an array 1D (N,)\r\n    # print(posterior, np.shape(posterior))\r\n    return posterior\r\n\r\n    # if we perform the product of all the elements\r\n    # posterior = np.prod(posterior)\r\n    # return posterior\r\n    # np.shape(posterior)\r\n    # shape posterior (,) it is a number\r\n    # PROBLEM: the posterior pdf computed alone with the prod operator, gives 0 because overflow\r\n    # But if we compute the ratio, this gives =/ 0\r\n    # Precisely, that's why we use MCMC and we don't plot directly from the pdf\r\n\r\n\r\ndef posterior_pdf(mu):\r\n    \"\"\"\r\n    this is the posterior pdf computed in II. We want to sample this for different values of mu.\r\n    It's an alternative method using log in order to evade numerical underflow\r\n    \"\"\"\r\n    mean_1 = mu[0]\r\n    mean_2 = mu[1]\r\n    x_1 = data[0, :]  # data fixed from the first experiment\r\n    x_2 = data[1, :]\r\n\r\n    log_posterior = (x_1 - mean_1) ** 2 / sigma_1 ** 2 - 2. * rho * (x_1 - mean_1) * (x_2 - mean_2) / (\r\n        sigma_1 * sigma_2) + (x_2 - mean_2) ** 2 / sigma_2 ** 2\r\n    log_posterior = -(1. / (2. * (1 - rho ** 2))) * np.sum(log_posterior)\r\n\r\n    # for the moment we a number, but still we need to perform the exponential of this\r\n    return log_posterior\r\n\r\n\r\ndef proposal_distribution(mu):\r\n    global c #we define c as global, because later (outside the function) we want to print this value\r\n    # mu must be 1D array here\r\n    cov_diag = np.array([[sigma_1 ** 2, 0], [0, sigma_2 ** 2]])\r\n    #    c = 2.4/sqrt(2.) #in our case this optimal value brings problems\r\n    c = 0.001\r\n    proposal = np.random.multivariate_normal(mu, c ** 2 * cov_diag)\r\n    return proposal\r\n    # np.shape(proposal), np.shape(mu)\r\n    # (2,) (2,) ie both are 1-D\r\n\r\n\r\ndef met_hast(f, proposal, old):\r\n    \"\"\"\r\n    metropolis_hastings algorithm.\r\n    allows proposal asymetric\r\n    _f_ is the unnormalized density function to sample, i.e. the posterior pdf\r\n    _proposal_ is the proposal distirbution J\r\n    _old_ is the value mu^{t-1}, i.e. the last iteration\r\n    \"\"\"\r\n\r\n    # we sample mu* from the proposal distribution\r\n    new = proposal(old)\r\n\r\n    # we must be careful with the overflow problems in the ratio.\r\n    # the posterior pdf computed alone with the prod operator, gives 0\r\n\r\n    ratio_posterior_pdf_log = f(new) - f(old)\r\n    # print(ratio_posterior_pdf_log)  # this is a number\r\n\r\n    ratio_posterior_pdf = np.exp(ratio_posterior_pdf_log)\r\n    # print(ratio_posterior_pdf)\r\n\r\n    ratio = ratio_posterior_pdf * proposal(new)/new\r\n    # note we call new = proposal(old) instead of proposal(old) because if we use proposal(old)\r\n    # we would be calling proposal(old) again, so it will be different than new because is random.\r\n    # print(ratio, np.shape(ratio))\r\n    # returns [ratio_1, ratio_2]\r\n    # shape (2,) 1-D array\r\n\r\n    # alpha is the acceptance probability, can be 1 or less. That's why we have np.min\r\n    # if it is 1, the acceptance ratio will be 100%\r\n    # we have 2 ratios, then we have to compare 2 objects\r\n    alpha_1 = np.min([ratio[0], 1])\r\n    alpha_2 = np.min([ratio[1], 1])\r\n\r\n    # now we start the acceptance or rejection\r\n    # we generate a random uniform number u and we compare it with alpha_1 and alpha_2\r\n    u = np.random.uniform()\r\n    cnt = 0\r\n    if (u <= alpha_1 and u <= alpha_2):\r\n        old = new #this is a 1D array (2,)\r\n        cnt = 1\r\n\r\n    print(old)\r\n    return old, cnt\r\n    # if accepted we return old = new and cnt=1, if rejected we return old and cnt=0\r\n\r\ndef run_chain(chainer, f, proposal, start, n, take=1):\r\n    \"\"\"\r\n    _chainer_ is the method used: Metropolis, MH, Gibbs ...\r\n    _f_ is the unnormalized density function to sample, i.e. the posterior pdf\r\n    _proposal_ is the proposal distirbution J\r\n    _start_ is the initial start of the Markov Chain, i.e. the initial value of mu_1,mu_2\r\n    _start_ must be an array 1D (2,), ie a list.\r\n    _n_ length of the chain. We can modify it to improve the convergance\r\n    _take_ thinning\r\n    \"\"\"\r\n    # we initialise the counter of the number of accepted values\r\n    count = 0\r\n    # samples recolect all the mu_1,mu_2 values along the chain\r\n    # but we want to have an array (2, n)\r\n    samples = np.array(start.reshape(2,1))\r\n    for i in range(n): # we iterate\r\n        print(i)\r\n        start, c = chainer(f, proposal, start) # start will be the value of mu_1,mu_2, it's no longer the initial value\r\n        count = count + c # this count only adds +1 when is mu* accepted\r\n        if i%take is 0: # we recolect the values for each iteration, even if not accepted\r\n            samples = np.append(samples, start.reshape(2,1), axis=1)\r\n            # now samples will be an array (2, n+1)\r\n            # ie two rows and n+1 columns. The two rows correspond to mu_1 and mu_2\r\n    return samples, count\r\n\r\n\r\n\r\nstart_point = np.array([0,0])\r\nn_iterations = 30000 #number of iterations of the chain\r\nsamples, count = run_chain(met_hast, posterior_pdf, proposal_distribution, start=start_point, n=n_iterations)\r\n\r\n#print(samples)\r\n#print(np.shape(samples))\r\n\r\n# we apply the burn-in period\r\n# the conventional choice is to discard the first half (gelman pag 297)\r\n# however, analyzing the values at each iteration, we see that from 1000 iteration there is already convergence\r\n\r\nburn_in = 15000\r\nsamples_burn_in = samples[:, burn_in : n_iterations+1]\r\n# remember slices must be integers that's why we use //\r\nprint(np.shape(samples_burn_in))\r\n\r\n# now we compute the sample mean and sample standard deviation\r\n# we select the axis 1 to obtain 2 means: mean_1 mean_2\r\n# the standard deviation is biased with ddof=0 and ddof=1\r\n# the var is the unbiased estimator for ddof=1\r\nsample_mean = np.mean(samples_burn_in, axis=1)\r\nstandard_deviation_mean = np.std(samples_burn_in, axis=1, ddof=1)\r\nprint(\"number iterations =\", n_iterations)\r\nprint(\"c =\", c)\r\nprint(\"burn-in =\", burn_in)\r\nprint('Acceptance fraction:', count / float(n_iterations))\r\nprint(\"sample mean:\", sample_mean)\r\nprint(\"sample standard deviation:\", standard_deviation_mean)\r\n\r\n# we try different values of c in order to find an appropiate acceptance fraction\r\n# and we want the sample mean and standard deviation to fit with the true values\r\n\r\nplt.figure(3)\r\nplt.scatter(samples_burn_in[0,:], samples_burn_in[1,:], color = \"black\", s = 0.1)\r\nplt.xticks(np.arange(1.90, 2.10, 0.02))\r\nplt.yticks(np.arange(0.90, 1.10, 0.02))\r\nplt.xlim(1.92,2.08)\r\nplt.ylim(0.92,1.08)\r\nplt.xlabel(r\"$\\mu_1$\")\r\nplt.ylabel(r\"$\\mu_2$\")\r\n\r\nnp.savetxt(\"samples_burn_in\", samples_burn_in)\r\n\r\nplt.show()\r\n\r\n\r\n\r\n###########################################################################################\r\n# IV.\r\n# Gibbs Sampler\r\n# we have two parameters mu_1 and mu_2. Then two steps per iteration t.\r\n\r\n# we define a function for Gibbs which fits with the run_chain function.\r\ndef gibbs(mu):\r\n    \"\"\"\r\n    Gibbs sampling algorithm\r\n    _mu_ is the value of mu^{t-1}, ie the last iteration. It must be an array 1D (2,) (mu_1, mu_2)\r\n    output: mu of the iteration t\r\n    \"\"\"\r\n\r\n    mu_1 = mu[0] #note that we don't use this value\r\n    mu_2 = mu[1]\r\n    x_1 = data[0, :]  # data fixed from the first experiment\r\n    x_2 = data[1, :]\r\n\r\n    x_1_mean = np.mean(x_1) # number\r\n    x_2_mean = np.mean(x_2)\r\n\r\n    # we choose the order (mu_1, mu_2)\r\n    # we start sampling mu_new_1\r\n\r\n    # be careful the arguments of the normal are the mean and the std\r\n\r\n    normal_mean_1 = x_1_mean + rho * sigma_1 / sigma_2 * (mu_2 - x_2_mean)\r\n    normal_std_1 = sqrt(sigma_1 ** 2 * (1 - rho ** 2) / N)\r\n    # they are numbers\r\n\r\n    mu_new_1 = np.random.normal(normal_mean_1, normal_std_1)\r\n    # number\r\n\r\n    # now we sample mu_new_2  using mu_new_1\r\n    normal_mean_2 = x_2_mean + rho * sigma_2 / sigma_1 * (mu_new_1 - x_1_mean)\r\n    normal_std_2 = sqrt(sigma_2 ** 2 * (1 - rho ** 2) / N)\r\n\r\n    mu_new_2 = np.random.normal(normal_mean_2, normal_std_2)\r\n\r\n    mu_new = np.array([mu_new_1, mu_new_2])\r\n    print(mu_new)\r\n\r\n    cnt = 1\r\n    return mu_new, cnt\r\n\r\n\r\n\"\"\" #######################################################################\r\n    Here there is a wrong attempt.\r\n    I tried to compute mu_new_1 as     mu_new_1 = np.prod(np.random.normal(normal_mean_1, normal_std_1))\r\n    where i computed a one-d gaussian for every data, ie 10^4 gaussian and then the product.\r\n    the result was clearly bigger than the desired and it had overflow problems.\r\n    \r\n    # be careful the arguments are the mean and the std\r\n    normal_mean_1 = x_1 - rho*sigma_1*(x_2-mu_2)/sigma_2\r\n    normal_std_1 = sqrt(sigma_1**2*(1-rho**2))\r\n    # print(np.shape(normal_mean_1))\r\n    # (N, ) 1D array\r\n    # print(np.shape(normal_std_1))\r\n    # () scalar\r\n\r\n    mu_new_1 = np.random.normal(normal_mean_1, normal_std_1)\r\n    # print(mu_new_1)\r\n    # print(np.shape(mu_new_1))\r\n    # (N,) 1D array\r\n\r\n    # for the moment, for any value of the data, we have obtained one mu_1\r\n    # now we have to make the product of all of them so we obtain only one mu_1\r\n    # but we have overflow problems. It is obvious because we are multiplying sth 10**4 times\r\n    # way out: apply log\r\n\r\n    # however we can have log(negative number) which gives nan.\r\n    # in order to solve this, we perform a mask which filters out the negative values\r\n    # at the end, i think we can make this approximation because most of the values are positive\r\n\r\n    check the values of mu_new_1\r\n    for i in range(0,N):\r\n        print(mu_new_1[i])\r\n    \r\n\r\n    # we perform the mask\r\n    mask = mu_new_1 > 0\r\n    mu_new_1 = mu_new_1[mask]\r\n\r\n    # check the values of mu_new_1 after the mask\r\n    for i in range(0,len(mu_new_1)):\r\n        print(mu_new_1[i])\r\n    \r\n\r\n    # we perform the natural logarithm of the array element-wise\r\n    mu_new_1 = np.log(mu_new_1)\r\n\r\n    #then we sum each element\r\n    mu_new_1 = np.sum(mu_new_1)\r\n\r\n\r\n\r\n    # now we sample mu_new_2  using mu_new_1\r\n    normal_mean_2 = x_2 - rho*sigma_2*(x_1-mu_new_1)/sigma_1\r\n    normal_std_2 = sqrt(sigma_2**2*(1-rho**2))\r\n\r\n    mu_new_2 = np.random.normal(normal_mean_2, normal_std_2)\r\n\r\n    # we perform the natural logarithm of the array element-wise\r\n    mu_new_2 = np.log(mu_new_2)\r\n\r\n    #then we sum each element\r\n    mu_new_2 = np.sum(mu_new_2)\r\n\r\n    mu_new = np.array([mu_new_1, mu_new_2])\r\n    print(mu_new)\r\n\r\n    cnt = 1\r\n    return mu_new, cnt\r\n    \r\n    \"\"\"\r\n\r\ndef run_chain_gibbs(chainer, start, n, take=1):\r\n    \"\"\"\r\n    _chainer_ is the method used: Metropolis, MH, Gibbs ...\r\n    _start_ is the initial start of the Markov Chain, i.e. the initial value of mu_1,mu_2\r\n    _start_ must be an array 1D (2,), ie a list.\r\n    _n_ length of the chain. We can modify it to improve the convergance\r\n    _take_ thinning\r\n    \"\"\"\r\n    # we initialise the counter of the number of accepted values\r\n    count = 0\r\n    # samples recolect all the mu_1,mu_2 values along the chain\r\n    # but we want to have an array (2, n)\r\n    samples = np.array(start.reshape(2,1))\r\n    for i in range(n): # we iterate\r\n        start, c = chainer(start) # start will be the value of mu_1,mu_2, it's no longer the initial value\r\n        print(i)\r\n        count = count + c # this count only adds +1 when is mu* accepted\r\n        if i%take is 0: # we recolect the values for each iteration, even if not accepted\r\n            samples = np.append(samples, start.reshape(2,1), axis=1)\r\n            # now samples will be an array (2, n+1)\r\n            # ie two rows and n+1 columns. The two rows correspond to mu_1 and mu_2\r\n    return samples, count\r\n\r\n\r\n\"\"\"\r\nstart_point = np.array([0,0])\r\nn_iterations = 30000 #number of iterations of the chain\r\nsamples, count = run_chain_gibbs(gibbs, start=start_point, n=n_iterations)\r\n\r\n# print(samples)\r\nprint(np.shape(samples))\r\n\r\n# we apply the burn-in period\r\n# the conventional choice is to discard the first half (gelman pag 297)\r\n\r\nburn_in = 15000\r\nsamples_burn_in = samples[:, burn_in : n_iterations+1]\r\n# remember slices must be integers that's why we use //\r\n#print(samples_burn_in)\r\nprint(np.shape(samples_burn_in))\r\n\r\n# now we compute the sample mean and sample standard deviation\r\n# we select the axis 1 to obtain 2 means: mean_1 mean_2\r\n# the standard deviation is biased with ddof=0 and ddof=1\r\n# the var is the unbiased estimator for ddof=1\r\nsample_mean = np.mean(samples_burn_in, axis=1)\r\nstandard_deviation_mean = np.std(samples_burn_in, axis=1, ddof=1)\r\nprint(\"number iterations =\", n_iterations)\r\nprint(\"burn-in =\", burn_in)\r\nprint('Acceptance fraction:', count / float(n_iterations))\r\nprint(\"sample mean:\", sample_mean)\r\nprint(\"sample standard deviation:\", standard_deviation_mean)\r\n\r\n# we try different values of c in order to find an appropiate acceptance fraction\r\n# and we want the sample mean and standard deviation to fit with the true values\r\n\r\nplt.figure(4)\r\nplt.scatter(samples_burn_in[0,:], samples_burn_in[1,:], color = \"black\", s = 0.1)\r\nplt.xticks(np.arange(1.90, 2.10, 0.02))\r\nplt.yticks(np.arange(0.90, 1.10, 0.02))\r\nplt.xlim(1.92,2.08)\r\nplt.ylim(0.92,1.08)\r\nplt.xlabel(r\"$\\mu_1$\")\r\nplt.ylabel(r\"$\\mu_2$\")\r\n\r\nnp.savetxt(\"samples_burn_in\", samples_burn_in)\r\n\r\nplt.show()\r\n\"\"\"\r\n\r\n\r\n", "meta": {"hexsha": "f014ec97303e74ecdc7d6117f0d4cdb0c37531dc", "size": 15271, "ext": "py", "lang": "Python", "max_stars_repo_path": "Projects/Parameter Estimation and Bayesian Statistics/_3_Exercise_3.py", "max_stars_repo_name": "aleixlopezpascual/aleixlopezpascual.github.io", "max_stars_repo_head_hexsha": "89b7449cf7f358d53a2b8f4030b88cbaf8884ef6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Projects/Parameter Estimation and Bayesian Statistics/_3_Exercise_3.py", "max_issues_repo_name": "aleixlopezpascual/aleixlopezpascual.github.io", "max_issues_repo_head_hexsha": "89b7449cf7f358d53a2b8f4030b88cbaf8884ef6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Projects/Parameter Estimation and Bayesian Statistics/_3_Exercise_3.py", "max_forks_repo_name": "aleixlopezpascual/aleixlopezpascual.github.io", "max_forks_repo_head_hexsha": "89b7449cf7f358d53a2b8f4030b88cbaf8884ef6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1872037915, "max_line_length": 120, "alphanum_fraction": 0.6440311702, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.928408800060238, "lm_q1q2_score": 0.8638456342798112}}
{"text": "import numpy as np\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\nx = np.arange(12)\n\nprint(x)\n# Dimension of Numpy Array\nprint(x.shape)\n\n# No. of elements in Array\nprint(x.size)\n\n# Change the shape of a Tensor without altering either the number of elements or their values\nX = x.reshape(3, 4)\nprint(X)\n\n# Automatically Inferring One Dimension by providing rest and putting -1 for Unknown Dim\nX1 = x.reshape(-1, 4)\nX2 = x.reshape(3, -1)\n\nprint(X1)\nprint(X2)\n\n# Setting Arrays with Initial Value Zero\nprint('Setting Arrays with Initial Value Zero')\nA1 = np.zeros((2, 3, 4))\nprint(A1)\n\n# Setting Arrays with Initial Value One\nprint('Setting Arrays with Initial Value One')\nA2 = np.ones((2, 3, 4))\nprint(A2)\n\n# Random Initialization of Tensors and Type of Distribution Used\n# Gaussian or Normal Distribution\nX3 = np.random.normal(0, 1, size=(3, 4))  # Ist Para = Mean, IInd Para = Standard Deviation\n\n# Converting Python List / Array to Numpy Array\nX4 = np.array([[1, 2, 3], [4, 5, 6]])\n\n\n\n## Operations\n\n\n# Elementwise Operations\nx = np.array([1, 2, 4, 8])\ny = np.array([2, 2, 2, 2])\nsum_op = x + y\nsub_op = x - y\nmul_op = x * y\ndiv_op = x / y\nexp_op = x ** y\n\n# Unary Exponentiation - Element-wise Exponentiation (e^x)\nuExp = np.exp(x)\n\n# Concatenation - (Axis along which to concatenate is to be mentioned)\nX = np.arange(12).reshape(3, 4)\nY = np.array([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])\n# Axis == 1: Means along column and Axis == 0: Means along row Here\nnp.concatenate([X, Y], axis=0), np.concatenate([X, Y], axis=1)\n\n# Binary Tensor (Obtained by equating 2 Tensor: Each element = True if same value in both Tensors else: False)\nbin_tensor = X == Y\nprint('Binary Tensor Obtained from Tensors X and Y is:')\nprint(bin_tensor)\n\n# Summing all Elements in a Tensor\nsum_all = X.sum()\nprint(sum_all)\n\n\n## BroadCasting Mechanism: (Element-wise Operation on 2 Tensors with Different Dimensions)\na = np.arange(3).reshape(3, 1)\nb = np.arange(2).reshape(1, 2)\nprint('a:', a)\nprint('b:', b)\nprint('BroadCast Result:', a + b)\n\n\n\n## Indexing and Slicing\n\n# Indexing\na = np.arange(12)\nprint('Last Element:', a[-1])\nprint('Access Matrix', b[0, 1])\n\na = np.arange(12).reshape(3, 4)\nprint(a)\n\n# Assigning Multiple Indices Same Value\na[0:2, :] = 12\nprint('Setted 1st 2 row to 12:', a)\n\n\n\n## Saving Memory\n\n# For example, if we\n# write Y = X + Y, we will dereference the tensor that Y used to point to and instead point Y at\n# the newly allocated memory.\nsave_id = id(Y)\nY = Y + X\nnew_id = id(Y)\nprint('Is both Y same:', save_id == new_id)\n\n# Handling Memory Issue\nZ = np.zeros_like(Y)\nprint('Initial Id:', id(Z))\nZ[:] = X + Y\nprint('Id After Op:', id(Z))\n# Other Method\n\nsave_id = id(X)\nX += Y\nprint('Is Id Same?', id(X) == save_id)\n\n\n\n## Type Conversions\n\nprint(type(Y))\na = np.array([3.2])\nprint(a, a.item(), int(a), float(a))\n\n\n\n\n\n", "meta": {"hexsha": "76115a3715badb47d08e7bcda14861ae9ad6a6e3", "size": 2828, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter-2 Preliminaries/practice.py", "max_stars_repo_name": "porcelainruler/Dive-In-Deep-Learning", "max_stars_repo_head_hexsha": "0ad1dc3a66484b1517d0ebf109fe47a1ef578f32", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter-2 Preliminaries/practice.py", "max_issues_repo_name": "porcelainruler/Dive-In-Deep-Learning", "max_issues_repo_head_hexsha": "0ad1dc3a66484b1517d0ebf109fe47a1ef578f32", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter-2 Preliminaries/practice.py", "max_forks_repo_name": "porcelainruler/Dive-In-Deep-Learning", "max_forks_repo_head_hexsha": "0ad1dc3a66484b1517d0ebf109fe47a1ef578f32", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1044776119, "max_line_length": 110, "alphanum_fraction": 0.6714992928, "include": true, "reason": "import numpy", "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.9207896693699845, "lm_q1q2_score": 0.8638149009335696}}
{"text": "from scipy.special import softmax\nimport numpy as np\n\n\"\"\"\nSelf Attn\nhttps://colab.research.google.com/github/mrm8488/shared_colab_notebooks/blob/master/basic_self_attention_.ipynb\n\nAttentions\nhttps://www.youtube.com/watch?v=S27pHKBEp30\n\nPosition Embeddings\nhttps://www.youtube.com/watch?v=dichIcUZfOw\n\n@ symbol\nhttps://www.python.org/dev/peps/pep-0465/#semantics\n\n\"\"\"\nx = np.array([\n  [1, 0, 1, 0],   # Input 1\n  [0, 2, 0, 2],   # Input 2\n  [1, 1, 1, 1],   # Input 3\n  [1, 2, 1, 2],   # Input 4\n  [2, 2, 2, 2],   # Input 5\n ])\n\nw_key = np.array([\n  [0, 0, 1],\n  [1, 1, 0],\n  [0, 1, 0],\n  [1, 1, 0]\n])\nw_query = np.array([\n  [1, 0, 1],\n  [1, 0, 0],\n  [0, 0, 1],\n  [0, 1, 1]\n])\nw_value = np.array([\n  [0, 2, 0],\n  [0, 3, 0],\n  [1, 0, 3],\n  [1, 1, 0]\n])\nkey = []\nquery = []\nvalue = []\n\n# Generate Query, Key, and Value\nfor i in range(len(x)):\n    # The out dim: 1X4 @ 4X3 = 1X3 = array(3)\n    query_i = x[i] @ w_query\n    key_i = x[i] @ w_key\n    value_i = x[i] @ w_value\n    query.append(query_i)\n    key.append(key_i)\n    value.append(value_i)\n\n# Convert list into numpy array\nquery = np.stack(query)\nkey = np.stack(key)\nvalue = np.stack(value)\n# print(query)\n# print(key)\n# print(value)\n# exit()\nthis_query_contextual = []\nfor i in range(len(x)):\n    this_query = query[i]\n    relevance = []\n    # Compute this_query relevance to all the Keys (keys-row)\n    for j in range(len(key)):\n        # Calculate inner product in between this_query and each row of the key matrix\n        rel_key_j = this_query @ key[j]\n        relevance.append(rel_key_j)\n\n    relevance = np.array(relevance)\n    # Apply softmax to get probability scores of relevance\n    relevance_scores = softmax(relevance, axis=-1)\n    # relevance_scores = relevance_scores.round(decimals=1)\n    out = 0\n    # Each values-row is multiplied with relevance score and added point-wise\n    for k in range(len(relevance)):\n        # Here value[k] :is vector (of head_dim), and relevance_scores[k]: is a scalar score\n        out += value[k] * relevance_scores[k]\n    this_query_contextual.append(out.round(decimals=1))\n\nprint(np.stack(this_query_contextual))\n\n# For Multi-Head, repeat the above process for n-separate w_query, w_key, and w_value,\n# that will be n multi-head attn (In an optimized implementation, all the heads are packed\n# in a single matrix for query, key, and value)\n", "meta": {"hexsha": "e1b2da9bc8049a1eb550c2162793a15c2ce82d7b", "size": 2342, "ext": "py", "lang": "Python", "max_stars_repo_path": "self_attention/deconstructing_attn.py", "max_stars_repo_name": "makeesyai/makeesy-deep-learning", "max_stars_repo_head_hexsha": "c5fa7b054c577201c7d7f319ae0f8e7bb5e6c156", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-01-11T12:10:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T10:03:45.000Z", "max_issues_repo_path": "self_attention/deconstructing_attn.py", "max_issues_repo_name": "patelrajnath/makeesy-deep-learning", "max_issues_repo_head_hexsha": "172f8a4301d6b60927824a56648d60559ba3f14e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "self_attention/deconstructing_attn.py", "max_forks_repo_name": "patelrajnath/makeesy-deep-learning", "max_forks_repo_head_hexsha": "172f8a4301d6b60927824a56648d60559ba3f14e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-11T12:06:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T07:30:01.000Z", "avg_line_length": 25.4565217391, "max_line_length": 111, "alphanum_fraction": 0.646029035, "include": true, "reason": "import numpy,from scipy", "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688145, "lm_q2_score": 0.8947894654011352, "lm_q1q2_score": 0.8638128913209918}}
{"text": "'''\nAuthor:    Michael Sherif Naguib\nDate:      March 13, 2020\n@:         University of Tulsa\nDescription: see README.md\n\nAfter my initial code written in montecarlopi.py that performs a Monte Carlo simulation using a circle inscribed in a\nsquare ... I realized a similar simulation could be achieved in 3D ... I wondered if I could generalize the simulation\nto an N Dimensional space ... I spent time to derive the necessary formulae ...in cases where n is an positive integer.\n\nNote however .... I should also note that as the higher dimensional formulas involve a kth root the simulation will be\nlimited by the precision of the nth root function. (in addition to long division ... as in the 2D case)\n\n'''\n\n#imports\nimport numpy as np\nimport tqdm\nimport math\nimport matplotlib.pyplot as plt\n\ndef magSquared(vector):\n    '''\n    :description: Calculate the squared magnitude of a vector\n    :param vector: a numpy vector\n    :return: the distance squared\n    '''\n    return sum([math.pow(vector[i],2) for i in range(len(vector))])\n\ndef nDFuncGenerator(dimension):\n    '''\n    :Description: Since a good portion of the function is itself seperable (i.e constant) with respect to the\n    hypervolumes for the Hypersphere and Hypercube, much of the calculation can be precomputed... this function\n    returns a function which has those values precomputed...\n    :param dimension: the positive integer value that specifies the dimension (note the formula changes based on this dim)\n    :return: a function that provides an estimate of PI in an N Dimensional Monte Carlo Simulation,\n    (based on the hypervolumes for the Hypersphere and Hypercube)\n\n    the returned function accepts two parameters\n    param1: countForHyperSphere (or 2d circle 3d etc... )\n    param2: countForHyperCube   (or 2d square 3d etc...)\n    '''\n    assert type(dimension) == type(1)# Assert it is an integer\n    assert dimension >=2             # Assert we are at least in 2 Dimensions\n\n    # 2 Dimensional case\n    if dimension == 2:\n        def d2Case(numInCircle,numInSquare):\n            assert numInSquare != 0  # Catch Div by Zero\n            return 4 * numInCircle / numInSquare\n        return d2Case\n    # 3 Dimensional Case\n    elif dimension == 3:\n        def d3Case(numInSphere,numInCube):\n            assert numInCube != 0  # Catch Div by Zero\n            return 6 * numInSphere / numInCube\n        return d3Case\n    # N Dimensional Case\n    else:\n        # Init a variable for the constant\n        constant = None\n        k = None\n        # For the N dimensional case there are two scenarios: dimension is even or n is odd\n        if dimension%2 ==0: #Even Case\n            k = dimension //2\n            assert k!=0\n            # Derived formula\n            constant = math.pow(math.factorial(k)*math.pow(2,2*k),1/k)\n        else:# Odd Case\n            k = (dimension -1)//2\n            assert k!=0\n            # Derived formula\n            constant = math.pow(math.factorial(2*k +1)*math.pow(2,2*k+1)/(2*math.factorial(k)*math.pow(4,k)),1/k)\n        # Return the function bound with the constant ... it turns out the seperable part of both the even and\n        # the odd case are the same ... i.e    c*f(x)\n        def dnCase(hypersphereCount,hypercubeCount):\n            assert hypercubeCount!=0 # Catch Divide by zero\n            if k%2==1:\n                assert hypercubeCount>=0 and hypersphereCount>=0   # Catch - in nth roots odd ensure neither are negative (they never should be)\n            return constant*math.pow(hypersphereCount/hypercubeCount,1/k)\n        return dnCase\n\ndef monteCarloPiItrGenerator(dimension):\n    '''\n    :description: since points need to be generated differently i.e a point in 2D vs 3D vs nD ...\n    a function is needed that can do this ... this function returns a function which is a generator ( in the sense of yield)\n    for successive estimates of pi gi\n    :param dimension: specifies the dimension for the simulation\n    :return: a function which accepts two parameters\n    a radius and a maximum iteration count... (this is based off the code in montecarlopi.py)\n    '''\n\n    def monteCarloPiItr(radius=10, iterations=100_000_000):\n        '''\n        :description: A generator that generates successive estimates of pi\n        :param radius: the Radius of the Circle inscribed in the Square (both centered at 0,0)\n        :param iterations: the number points to compute and use to update the estimate\n        :yeild: the next estimate of pi\n        '''\n\n\n        # Count how many are in the hypersphere ( circle etc...)\n        inHypersphereCount = 0\n        # Store an estimate for Pi (will be updated as the simulation progresses)\n\n        # Calculate the radius squared (once)\n        radiusSquared = math.pow(radius, 2)\n        # A numpy array used to shift the random nums into the desired range\n        s = np.ones(dimension) / 2\n        # Generate the pi esitmate calculator function (precomputing the constants)\n        calcPiEstimate = nDFuncGenerator(dimension)\n\n        # Begin iteration: i is the total up to that iteration .. (all points are in the square)\n        for i in range(0, iterations):\n            # Pick random coords: the circle is centered @ 0,0 ... 0  so shift over the range of the square by subtracting 0.5\n            # before scaling by the sidelength of the square ( side length = 2*radius)\n            x = (np.random.rand(dimension)-s)*2*radius\n\n            # Check if the point is within the circle: increment if it is (use squared distance to be efficient)\n            inHypersphereCount = inHypersphereCount + 1 if  magSquared(x)<= radiusSquared else inHypersphereCount + 0\n\n            # Update the pi estimate\n            piEst = calcPiEstimate(inHypersphereCount,i+1)\n\n            # Yield the pi esitmate\n            yield piEst\n\n    # Return the N- Dimensional configured Monte Carlo Pi calculator\n    return monteCarloPiItr\n\ndef reject_outliers(data, m=2):\n    '''\n    NOT MY CODE: i take no credit for this code...\n    thanks to: https://stackoverflow.com/questions/11686720/is-there-a-numpy-builtin-to-reject-outliers-from-a-list\n    :Description: this code rejects outliers ....\n    :param data: array\n    :param m:\n    :return: data without outliers\n    '''\n    return data[abs(data - np.mean(data)) < m * np.std(data)]\n\ndef updateRunningAvg(curAvg,val,valCnt):\n    '''\n    :description: compute a running average\n    :param curAvg: the current value of the average\n    :param val: the new value to factor into the average\n    :param valCnt: the number of values taken into account for the curAvg\n    :return: the updated average\n\n    (NOTE! this function does not change any of the parameters --> no side effect...)\n    it is the prgmr's responsibility to update those vals\n    '''\n    assert valCnt != 0\n    return (curAvg*valCnt + val)/(valCnt+1)\n\ndef monteCarloSim(dimension,radius=1,iterations=10_000,redos=100,log=True):\n    '''\n    :description: performs a monte carlo simulation configured by the parameters and then takes each redundant\n    simulation and averages it at the coresponding timestep.\n    :param dimension: the dimension to make the calculation in\n    :param radius: the radius for the hypersphere\n    :param iterations: the number of successive estimates of pi\n    :param redos: the number of times to repete the simulation\n    :param log: if true prints progress of the redundant sims\n    :return: list of avg values of pi at each time step\n    '''\n    assert redos>=1\n    #init the first\n    avgData =  [newEst for newEst in monteCarloPiItrGenerator(dimension)(radius=radius, iterations=iterations)]\n    logger = tqdm.tqdm if log else lambda x: x\n    # do the remainder\n    for r in logger(range(0,redos-1)):\n        latestSim = [newEst for newEst in monteCarloPiItrGenerator(dimension)(radius=radius, iterations=iterations)]\n        for i in range(len(avgData)):\n            avgData[i] = updateRunningAvg(avgData[i],latestSim[i],r+1)\n    return avgData\n\nif __name__ == \"__main__\":\n    # Settings\n    dimension = 4          # Run the simulation in nth Dimensional space\n    radius = 1              # Radius of the hypersphere\n    iterations = 10_000 # maximum iterations\n    '''\n    logEvery = 10_000       # Log every so many iterations\n    # Run the simulation\n    cnt=0\n    for newEst in monteCarloPiItrGenerator(dimension)(radius=radius,iterations=iterations):\n        cnt+=1\n        if cnt%logEvery==0:\n            print(newEst)\n    '''\n    dimensions= list(range(2,10))\n    bins = 100\n    allSeries=[]\n    rejectionStrength = 2\n    for d in dimensions:\n        #series=[newEst for newEst in tqdm.tqdm(monteCarloPiItrGenerator(d)(radius=radius,iterations=iterations))]\n        series = monteCarloSim(d)\n        series = reject_outliers( np.array(series),m=rejectionStrength)\n        allSeries.append(series)\n    assert(len(allSeries)==len(dimensions))\n    meanOfAllData = 0\n    for series in allSeries:\n        meanOfAllData+= series.mean()/len(allSeries)\n    fig, ax = plt.subplots()\n    for i in range(len(allSeries)):\n        ax.hist(allSeries[i],bins,label=\"{0}D\".format(dimensions[i]),alpha=0.5)\n    # Dashed line indicate the estimate of pi\n    ax.axvline(meanOfAllData, color='k', linestyle='dashed', linewidth=1)\n    #Solid line indicate what is taken as the true value of pi\n    ax.axvline(3.14159265358979, color='k', linestyle='solid', linewidth=1)\n    #Plot info\n    plt.legend(loc=\"best\")\n    plt.title(\"Estimates for Pi (redos=100,radius=1,sample=10k)\".format())\n    plt.xlabel(\"Estimate Values (Outliers)\")\n    plt.show()\n\n\n\n", "meta": {"hexsha": "702c1a763ef94c629a8f53545201e81c56712d60", "size": 9547, "ext": "py", "lang": "Python", "max_stars_repo_path": "nDimensionalMonteCarloPi.py", "max_stars_repo_name": "Michael-Naguib/MonteCarloPi", "max_stars_repo_head_hexsha": "8c63c6f1b60a2e80fe910caf53809a22cc2c9828", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nDimensionalMonteCarloPi.py", "max_issues_repo_name": "Michael-Naguib/MonteCarloPi", "max_issues_repo_head_hexsha": "8c63c6f1b60a2e80fe910caf53809a22cc2c9828", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nDimensionalMonteCarloPi.py", "max_forks_repo_name": "Michael-Naguib/MonteCarloPi", "max_forks_repo_head_hexsha": "8c63c6f1b60a2e80fe910caf53809a22cc2c9828", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3954545455, "max_line_length": 144, "alphanum_fraction": 0.6752906672, "include": true, "reason": "import numpy", "num_tokens": 2384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688146, "lm_q2_score": 0.8947894611926921, "lm_q1q2_score": 0.8638128872582401}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nxlim = 10\nx = np.linspace(-xlim, xlim, 500)\n\nplt.figure(figsize=(3,3)) # 400x400 Pixel\n\nplt.title('Heaviside Funktion', fontsize=20)\nplt.plot(x, np.heaviside(x, 1.0), linewidth=10, color='red')\nplt.xlim([-10, 10])\nplt.grid(True)\nplt.show()\n\ninput(\"Drück eine Taste...\")\n\nplt.title('Sigmoid (Logistische Funktion)', fontsize=20)\nplt.plot(x, 1./(1.+np.exp(-x)), linewidth=10, color='green')\nplt.text(-9, 0.85, r'$\\sigma(x)=\\frac{1}{1+e^{-x}}$', fontsize=30)\nplt.xlim([-10, 10])\nplt.grid(True)\nplt.show()\n\ninput(\"Drück eine Taste...\")\n\nplt.title('Aktivierungsfunktionen')\nplt.plot(x, np.heaviside(x, 10.0), label='Heaviside', linewidth=10, color='red')\nplt.plot(x, 1./(1.+np.exp(-x)), label='Logistische Funktion', linewidth=10, color='green')\nplt.xlim([-10, 10])\nplt.grid(True)\nplt.legend()\nplt.show()\n\ninput(\"Drück eine Taste...\")\n\nfig, axs = plt.subplots(2, 1)\n\naxs[0].plot(x, 1./(1.+np.exp(-x)), color='green')\naxs[0].set_title('Logistische Funktion')\naxs[0].text(-10, 0.85, r'$\\sigma(x)=\\frac{1}{1+e^{-x}}$', fontsize=25, color='green')\naxs[0].grid(True)\n\naxs[1].plot(x, 1./(1.+np.exp(-x))*(1-1./(1.+np.exp(-x))), color='red')\naxs[1].set_title('Änderung (1. Ableitung)')\naxs[1].text(-10, 0.15, r'$\\sigma\\'(x)=\\sigma(x).(1-\\sigma(x))$', fontsize=15, color='red')\naxs[1].grid(True)\n\nplt.show()\n\ninput(\"Drück eine Taste...\")\n\nplt.title('Tangens Hyperbolicus', fontsize=20)\nplt.plot(x, np.tanh(x), linewidth=10, color='orange')\nplt.text(-9, 0.75, r'$\\sigma(x)=tanh(x)'\n                   r'$', fontsize=25)\nplt.xlim([-10, 10])\nplt.grid(True)\nplt.legend()\nplt.show()\n\ninput(\"Drück eine Taste...\")\n\nplt.title('ReLU-Funktion', fontsize=20)\nplt.plot(x, np.maximum(0,x), linewidth=10, color='blue')\nplt.xlim([-10, 10])\nplt.grid(True)\n\nplt.legend()\nplt.show()\n\ninput(\"Drück eine Taste...\")\n\n", "meta": {"hexsha": "d0d90180504ea74a67b6daec55c1082e630a1386", "size": 1835, "ext": "py", "lang": "Python", "max_stars_repo_path": "Crashkurs Python/Sigmoide_Funktionen.py", "max_stars_repo_name": "slogslog/Coding-Kurzgeschichten", "max_stars_repo_head_hexsha": "9b08237038147c6c348d4cf4c69567178e07dd1d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-23T14:57:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T18:12:07.000Z", "max_issues_repo_path": "Crashkurs Python/Sigmoide_Funktionen.py", "max_issues_repo_name": "slogslog/Coding-Kurzgeschichten", "max_issues_repo_head_hexsha": "9b08237038147c6c348d4cf4c69567178e07dd1d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Crashkurs Python/Sigmoide_Funktionen.py", "max_forks_repo_name": "slogslog/Coding-Kurzgeschichten", "max_forks_repo_head_hexsha": "9b08237038147c6c348d4cf4c69567178e07dd1d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1369863014, "max_line_length": 90, "alphanum_fraction": 0.6408719346, "include": true, "reason": "import numpy", "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399034724604, "lm_q2_score": 0.8902942290328344, "lm_q1q2_score": 0.8637989868389058}}
{"text": "from src.functions.objectivefn import ObjectiveFn\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\n\nclass RastriginFn(ObjectiveFn):\n\n    def __init__(self, dims):\n        super(RastriginFn, self).__init__(dims)\n        self.domain = (-5.12, 5.12)\n\n    def get_minima(self):\n        minima_coords = [0 for i in range(self.dims)]  # Function value is 0 here.\n        minima = tuple(minima_coords)\n        return self.evaluate(minima)\n\n    def evaluate(self, params):\n        A = 10\n        f = 0\n        try:\n            if len(params) != self.dims:\n                raise Exception('number of paramters passd is not the same as the number of expected dimensions')\n\n            for param in params:\n                f = f + A + (param ** 2 - (A * math.cos(2 * math.pi * param)))\n\n            return f\n        except Exception as error:\n            print('Exception raised in rastrigin_fn.eval_fn: ', repr(error))\n\n    def eval_vectors(self, *X, **kwargs):\n        A = kwargs.get('A', 10)\n        return A + sum([(x ** 2 - A * np.cos(2 * math.pi * x)) for x in X])\n\n    def graph_fn(self):\n        A = 10\n        X = np.linspace(-5.12, 5.12, 200)\n        Y = np.linspace(-5.12, 5.12, 200)\n\n        X, Y = np.meshgrid(X, Y)\n\n        Z = self.eval_vectors(X, Y, A=10)\n\n        fig = plt.figure()\n        ax = fig.gca(projection='3d')\n        ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.plasma, linewidth=0, antialiased=False)\n        plt.savefig('rastrigin.png')\n\n    def contour_plot(self, save_file_name, points):\n        A = 10\n        # X = np.linspace(-5.12, 5.12, 200)\n        # Y = np.linspace(-5.12, 5.12, 200)\n        X = np.linspace(self.domain[0], self.domain[1], 200)\n        Y = np.linspace(self.domain[0], self.domain[1], 200)\n\n        X, Y = np.meshgrid(X, Y)\n\n        Z = self.eval_vectors(X, Y, A=10)\n        plt.contour(X, Y, Z)\n        for point in points:\n            # print(point)\n            plt.scatter(point[0], point[1], marker='X', color='r')\n        plt.savefig(save_file_name, dpi=300, bbox_inches='tight')\n        plt.close()\n\n    def is_defined_only_for_2d(self):\n        return False\n\n    def name(self):\n        return \"rastrigin\"", "meta": {"hexsha": "ff315b50940fdd93dd027566409666c9f53a29ee", "size": 2208, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/functions/rastriginfn.py", "max_stars_repo_name": "lokeshsharma95/Artifical-Bee-Colony", "max_stars_repo_head_hexsha": "d30e80822fed8de8676286bf3f4b46364819e318", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/rastriginfn.py", "max_issues_repo_name": "lokeshsharma95/Artifical-Bee-Colony", "max_issues_repo_head_hexsha": "d30e80822fed8de8676286bf3f4b46364819e318", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/rastriginfn.py", "max_forks_repo_name": "lokeshsharma95/Artifical-Bee-Colony", "max_forks_repo_head_hexsha": "d30e80822fed8de8676286bf3f4b46364819e318", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6666666667, "max_line_length": 113, "alphanum_fraction": 0.5688405797, "include": true, "reason": "import numpy", "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399077750858, "lm_q2_score": 0.8902942203004186, "lm_q1q2_score": 0.8637989821969702}}
{"text": "from __future__ import division\nimport numpy as np\nfrom utils import Grapher, memoize, SafeEval\n\n\nclass Romberg():\n    def __init__(self, func, a, b, err):\n        self.f = SafeEval.functionize(func)\n        self.a = a\n        self.b = b\n        self.err = err\n        self.intervals = None\n        self.integral = None\n        self.final_err = None\n\n    @staticmethod\n    def trapezoidal(f, l, r, n):\n        h = (r - l) / n\n        return h * ((f(l) + f(r)) / 2 + sum(map(f, np.arange(l + h, r, h))))\n\n    def integrate(self):\n        @memoize\n        def T(n):\n            return Romberg.trapezoidal(self.f, self.a, self.b, n)\n\n        @memoize\n        def R(o, n):\n            if o == 2:\n                return T(n)\n            else:\n                return (4 * R(o - 2, 2 * n) - R(o - 2, n)) / 3\n\n        def err(o):\n            e = R(o, 1) - R(o - 2, 2)\n            if R(o, 1) is not 0:\n                e /= R(o, 1)\n            return e\n        o = 4\n        while abs(err(o)) > self.err:\n            o *= 2\n        self.integral = R(o, 1)\n        self.intervals = o / 2\n        self.final_err = err(o)\n\n    def plot(self):\n        x = np.linspace(self.a, self.b, self.intervals + 1)\n        y = [self.f(_) for _ in x]\n        Grapher.plot(x=x, y=y)\n\n\nclass Quadrature():\n    def __init__(self, func, a, b, err):\n        self.f = SafeEval.functionize(func)\n        self.a = a\n        self.b = b\n        self.err = err\n        self.points = None\n        self.integral = None\n        self.final_err = None\n\n    @staticmethod\n    def gaussxw(N):\n        # Initial approximation to roots of the Legendre polynomial\n        a = np.linspace(3, 4 * N - 1, N) / (4 * N + 2)\n        x = np.cos(np.pi * a + 1 / (8 * N * N * np.tan(a)))\n\n        # Find roots using Newton's method\n        epsilon, delta = 1e-15, 1.0\n        while delta > epsilon:\n            p0 = np.ones(N, float)\n            p1 = np.copy(x)\n            for k in range(1, N):\n                p0, p1 = p1, ((2 * k + 1) * x * p1 - k * p0) / (k + 1)\n            dp = (N + 1) * (p0 - x * p1) / (1 - x * x)\n            dx = p1 / dp\n            x -= dx\n            delta = np.max(abs(dx))\n\n        # Calculate the weights\n        w = 2 * (N + 1) * (N + 1) / (N * N * (1 - x * x) * dp * dp)\n\n        return x, w\n\n    @staticmethod\n    def gaussxwab(N, a, b):\n        x, w = Quadrature.gaussxw(N)\n        return 0.5 * (b - a) * x + 0.5 * (b + a), 0.5 * (b - a) * w\n\n    def intergrate(self):\n        @memoize\n        def G(n):\n            x, w = Quadrature.gaussxwab(n, self.a, self.b)\n            fx = np.array([self.f(i) for i in x])\n            w = np.array(w)\n            return np.sum(fx * w)\n\n        def err(n):\n            e = G(n) - G(n - 1)\n            if G(n) is not 0:\n                e /= G(n)\n            return e\n        n = 2\n        while abs(err(n)) > self.err:\n            n += 1\n        self.points = n\n        self.integral = G(n)\n        self.final_err = err(n)\n\n    def plot(self):\n        x, w = Quadrature.gaussxwab(self.points, self.a, self.b)\n        y = [self.f(_) for _ in x]\n        Grapher.plot(x=x, y=y)\n\n\ndef main():\n\n    with open(\"q1.txt\", \"r\") as f:\n        func = f.readline()\n        a, b = map(float, f.readline().split(', '))\n        err = float(f.readline())\n        op = int(f.readline())\n\n    if op == 1:\n        romberg = Romberg(func, a, b, err / 100)\n        romberg.integrate()\n        with open(\"out.txt\", \"w\") as fout:\n            if romberg.integral is not None:\n                fout.write('I= %f\\n' % romberg.integral)\n                fout.write('Number of intervals= %d\\n' % romberg.intervals)\n                fout.write('Approximate relative error (%%)= %f\\n' %\n                           (romberg.final_err * 100))\n        if raw_input('Plot f(x) vs x?[Press 1 for yes]: ') is '1':\n            romberg.plot()\n    else:\n        gauss = Quadrature(func, a, b, err / 100)\n        gauss.intergrate()\n        with open(\"out.txt\", \"w\") as fout:\n            if gauss.integral is not None:\n                fout.write('I= %f\\n' % gauss.integral)\n                fout.write('Number of points= %d\\n' % gauss.points)\n                fout.write('Approximate relative error (%%)= %f\\n' %\n                           (gauss.final_err * 100))\n        if raw_input('Plot f(x) vs x?[Press 1 for yes]: ') is '1':\n            gauss.plot()\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "2231c5df6cfe51ceefcb90cfcbf53cb0e4c5baa6", "size": 4368, "ext": "py", "lang": "Python", "max_stars_repo_path": "Methods/Integrate.py", "max_stars_repo_name": "APwhitehat/NumericalMethods", "max_stars_repo_head_hexsha": "71e113ec71de6dfcbf73d81c8967b0072af4953f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-02-15T08:47:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-15T11:57:20.000Z", "max_issues_repo_path": "Methods/Integrate.py", "max_issues_repo_name": "APwhitehat/NumericalMethods", "max_issues_repo_head_hexsha": "71e113ec71de6dfcbf73d81c8967b0072af4953f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-01-01T10:45:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-28T17:38:27.000Z", "max_forks_repo_path": "Methods/Integrate.py", "max_forks_repo_name": "APwhitehat/NumericalMethods", "max_forks_repo_head_hexsha": "71e113ec71de6dfcbf73d81c8967b0072af4953f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3154362416, "max_line_length": 76, "alphanum_fraction": 0.4574175824, "include": true, "reason": "import numpy", "num_tokens": 1320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799462157138, "lm_q2_score": 0.896251371748038, "lm_q1q2_score": 0.8637890988590838}}
{"text": "def mc_pi(n):  # Sampling n points to calculate pi.\n    #import time\n    import numpy as np\n    #a = time.time()\n    m = 0\n    pi = [None] * n\n    x = np.random.uniform(-1, 1, n)\n    y = np.random.uniform(-1, 1, n)\n    for i in range(0, n):\n        if (x[i]**2 + y[i]**2) <= 1:\n            m = m + 1\n        pi[i] = 4.0 * m / (i + 1)\n    #b = time.time() - a\n    #print(\"Toal time: %.1fsec\\n\" % (b))\n    return (pi[n - 1])\n\n\n# use every core of CPU to parallel calculate pi, loop t times, every time sampling n points.\ndef pl_mc_pi(n, t):\n    import time\n    import sys\n    import multiprocessing\n    import numpy as np\n    a = time.time()\n    cores = multiprocessing.cpu_count()\n    pool = multiprocessing.Pool(processes=cores)\n    cnt = 0\n    pi = [None] * t\n    for y in pool.imap_unordered(mc_pi, [n] * t):\n        pi[cnt] = y\n        m = np.mean(pi[0:cnt + 1])\n        cnt += 1\n        sys.stdout.write('done %d/%d, current pi is %f\\r' % (cnt, t, m))\n    b = time.time() - a\n    print(\"\\nToal time: %.1fsec\\n\" % (b))\n    return np.mean(pi)\n\n\ndef mc_pi_plot(n, tt):  # want to plot an animation to show the progress?\n    import time\n    import numpy as np\n    import matplotlib.pyplot as plt\n    %matplotlib osx\n    plt.close()\n    a = time.time()\n    m = 0\n    pi = [None] * n\n    co = [None] * n\n    x = np.random.uniform(-1, 1, n)\n    y = np.random.uniform(-1, 1, n)\n    plt.axis('scaled')\n    plt.axis([-1, 1, -1, 1])\n    for i in range(0, n):\n        if (x[i]**2 + y[i]**2) <= 1:\n            m = m + 1\n            co[i] = 'r'\n        else:\n            co[i] = 'k'\n        pi[i] = 4.0 * m / (i + 1)\n        plt.scatter(x[i], y[i], s=0.75, marker='.', c=co[i], alpha=.5)\n        if tt:\n            plt.pause(tt)\n    b = time.time() - a\n    print(\"Toal time: %.1fsec\\n\" % (b))\n    if tt:\n        plt.show()\n    return (pi[n - 1])\n", "meta": {"hexsha": "736b7229daa549b169079f63a2441d595cb3c420", "size": 1836, "ext": "py", "lang": "Python", "max_stars_repo_path": "plmcpi.py", "max_stars_repo_name": "niu541412/plmcpi", "max_stars_repo_head_hexsha": "2a76861afb4c2a08d8da2457dd9c53a91554db68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plmcpi.py", "max_issues_repo_name": "niu541412/plmcpi", "max_issues_repo_head_hexsha": "2a76861afb4c2a08d8da2457dd9c53a91554db68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plmcpi.py", "max_forks_repo_name": "niu541412/plmcpi", "max_forks_repo_head_hexsha": "2a76861afb4c2a08d8da2457dd9c53a91554db68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 93, "alphanum_fraction": 0.4972766885, "include": true, "reason": "import numpy", "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.963779941013992, "lm_q2_score": 0.8962513675912912, "lm_q1q2_score": 0.8637890901908443}}
{"text": "'''\nComputing the Pearson correlation coefficient\n100xp\nAs mentioned in the video, the Pearson correlation coefficient, also called the\nPearson r, is often easier to interpret than the covariance. It is computed using\nthe np.corrcoef() function. Like np.cov(), it takes two arrays as arguments and\nreturns a 2D array. Entries [0,0] and [1,1] are necessarily equal to 1 (can you\nthink about why?), and the value we are after is entry [0,1].\n\nIn this exercise, you will write a function, pearson_r(x, y) that takes in two\narrays and returns the Pearson correlation coefficient. You will then use this\nfunction to compute it for the petal lengths and widths of I. versicolor.\n\nAgain, we include the scatter plot you generated in a previous exercise to remind\nyou how the petal width and length are related.\n\nInstructions\n-Define a function with signature pearson_r(x, y).\n    -Use np.corrcoef() to compute the correlation matrix of x and y (pass them to\n    np.corrcoef() in that order).\n    -The function returns entry [0,1] of the correlation matrix.\n-Compute the Pearson correlation between the data in the arrays versicolor_petal_length\nand versicolor_petal_width. Assign the result to r.\n-Print the result.\n'''\nimport numpy as np\n\nversicolor_petal_length = np.array([4.7,  4.5,  4.9,  4.,  4.6,  4.5,  4.7,  3.3,  4.6,  3.9,  3.5,\n                                    4.2,  4.,  4.7,  3.6,  4.4,  4.5,  4.1,  4.5,  3.9,  4.8,  4.,\n                                    4.9,  4.7,  4.3,  4.4,  4.8,  5.,  4.5,  3.5,  3.8,  3.7,  3.9,\n                                    5.1,  4.5,  4.5,  4.7,  4.4,  4.1,  4.,  4.4,  4.6,  4.,  3.3,\n                                    4.2,  4.2,  4.2,  4.3,  3.,  4.1])\n\nversicolor_petal_width = np.array([1.4,  1.5,  1.5,  1.3,  1.5,  1.3,  1.6,  1.,  1.3,  1.4,  1.,\n                                   1.5,  1.,  1.4,  1.3,  1.4,  1.5,  1.,  1.5,  1.1,  1.8,  1.3,\n                                   1.5,  1.2,  1.3,  1.4,  1.4,  1.7,  1.5,  1.,  1.1,  1.,  1.2,\n                                   1.6,  1.5,  1.6,  1.5,  1.3,  1.3,  1.3,  1.2,  1.4,  1.2,  1.,\n                                   1.3,  1.2,  1.3,  1.3,  1.1,  1.3])\n\n\ndef pearson_r(x, y):\n    \"\"\"Compute Pearson correlation coefficient between two arrays.\"\"\"\n    # Compute correlation matrix: corr_mat\n    corr_mat = np.corrcoef(x, y)\n\n    # Return entry [0,1]\n    return corr_mat[0, 1]\n\n\n# Compute Pearson correlation coefficient for I. versicolor: r\nr = pearson_r(versicolor_petal_length, versicolor_petal_width)\n\n# Print the result\nprint(r)\n", "meta": {"hexsha": "fbb009b85b84940aa77354d14396b96b55835e21", "size": 2545, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/2-quantitative-exploratory-data-analysis/computing-the-pearson-correlation-coefficient.py", "max_stars_repo_name": "aimanahmedmoin1997/DataCamp", "max_stars_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-12T04:49:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T00:40:28.000Z", "max_issues_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/2-quantitative-exploratory-data-analysis/computing-the-pearson-correlation-coefficient.py", "max_issues_repo_name": "aimanahmedmoin1997/DataCamp", "max_issues_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/2-quantitative-exploratory-data-analysis/computing-the-pearson-correlation-coefficient.py", "max_forks_repo_name": "aimanahmedmoin1997/DataCamp", "max_forks_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-11-06T17:43:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T21:08:16.000Z", "avg_line_length": 46.2727272727, "max_line_length": 99, "alphanum_fraction": 0.578388998, "include": true, "reason": "import numpy", "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541528387691, "lm_q2_score": 0.9173026539338222, "lm_q1q2_score": 0.8637818534868079}}
{"text": "import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler\r\nimport seaborn as sns\r\n\r\n\r\nsns.set()\r\nsns.set_context(\"talk\")\r\n\r\n#1) Load (all features, using Pandas), standardize this d-dimension dataset (d is number of features) and Split\r\n# the Iris dataset to training and test sets with ratio 70% and 30%, respectively.\r\n\r\niris_df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)\r\nprint(\"iris_df.head(): \",iris_df.head())\r\nprint(\"iris_df.tail(): \",iris_df.tail())\r\n\r\nX = iris_df.iloc[:,0:4].values\r\ny = iris_df.iloc[:,4].values\r\n\r\nX_train, X_test, y_train, y_test =  train_test_split(X, y, test_size=0.3, random_state=0)\r\n\r\nsc = StandardScaler()\r\nX_train_std = sc.fit_transform(X_train)\r\nX_test_std = sc.transform(X_test)\r\n\r\n# 2) Write your own function to calculate the covariance matrix. Then compute the eigenvalues and\r\n# eigenvectors of this matrix.\r\nmean_vec = np.mean(X_train_std, axis=0)\r\ncov_mat = (X_train_std - mean_vec).T.dot((X_train_std - mean_vec)) / (X_train_std.shape[0]-1)\r\nprint('Covariance matrix \\n%s' %cov_mat)\r\neigen_vals, eigen_vecs = np.linalg.eig(cov_mat)\r\nprint('\\nEigenvalues \\n%s' % eigen_vals)\r\n\r\n# 3) Plot the cumulative variance ratio (c.f. block [11] of the nbviewer of Chapter 5).\r\ntot = sum(eigen_vals)\r\nvar_exp = [(i / tot) for i in sorted(eigen_vals, reverse=True)]\r\ncum_var_exp = np.cumsum(var_exp)\r\nplt.bar(range(0, 4), var_exp, alpha=0.5, align='center',label='individual explained variance')\r\nplt.step(range(0, 4), cum_var_exp, where='mid', label='cumulative explained variance')\r\nplt.ylabel('Explained variance ratio')\r\nplt.xlabel('Principal components')\r\nplt.legend(loc='center right')\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n\r\n# 4) Choose the k=3 eigenvectors that correspond to the k largest eigenvalues to construct a d×k-dimensional\r\n# transformation matrix W ; the eigenvectors are the columns of this matrix\r\neigen_pairs = [(np.abs(eigen_vals[i]), eigen_vecs[:, i])\r\n               for i in range(len(eigen_vals))]\r\nprint(eigen_pairs)\r\nW = np.hstack((eigen_pairs[0][1][:, np.newaxis],\r\n               eigen_pairs[1][1][:, np.newaxis], eigen_pairs[2][1][:, np.newaxis]))\r\nprint('Matrix W:\\n', W)\r\nprint(\"X_train_std[0].dot(W) \",X_train_std[0].dot(W))\r\n\r\n# 5) Project the samples onto the new feature subspace, and plot the projected data using the\r\n# transformation matrix W (c.f. block [14] of the nbviewer of Chapter 5)\r\nX_train_pca = X_train_std.dot(W)\r\nprint(\"X_train_pca \",X_train_pca)\r\n\r\ncolors = ['r', 'b', 'g']\r\nmarkers = ['s', 'x', 'o']\r\n#PCA 1 and PCA2\r\nfor l, c, m in zip(np.unique(y_train), colors, markers):\r\n    plt.scatter(X_train_pca[y_train == l, 0],\r\n                X_train_pca[y_train == l, 1],\r\n                c=c, label=l, marker=m)\r\nplt.title('PC 1 and PC 2')\r\nplt.xlabel('PC 1')\r\nplt.ylabel('PC 2')\r\nplt.legend(loc='upper right')\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n#PCA 1 and PCA 3\r\nfor l, c, m in zip(np.unique(y_train), colors, markers):\r\n    plt.scatter(X_train_pca[y_train == l, 0],\r\n                X_train_pca[y_train == l, 2],\r\n                c=c, label=l, marker=m)\r\nplt.title('PC 1 and PC 3')\r\nplt.xlabel('PC 1')\r\nplt.ylabel('PC 3')\r\nplt.legend(loc='upper right')\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n#PCA 2 and PCA 3\r\nfor l, c, m in zip(np.unique(y_train), colors, markers):\r\n    plt.scatter(X_train_pca[y_train == l, 1],\r\n                X_train_pca[y_train == l, 2],\r\n                c=c, label=l, marker=m)\r\nplt.title('PC 2 and PC 3')\r\nplt.xlabel('PC 2')\r\nplt.ylabel('PC 3')\r\nplt.legend(loc='upper right')\r\nplt.tight_layout()\r\nplt.show()\r\n\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfig = plt.figure(1, figsize=(8, 6))\r\nax = Axes3D(fig, elev=-150, azim=110)\r\nfor l, c, m in zip(np.unique(y_train), colors, markers):\r\n    ax.scatter(X_train_pca[y_train == l, 0], X_train_pca[y_train == l, 1], X_train_pca[y_train == l, 2],c=c,   label=l,marker=m, edgecolor='k', s=40)\r\n\r\nax.set_title(\"First three PC directions\")\r\nax.set_xlabel(\"PC 1\")\r\nax.w_xaxis.set_ticklabels([])\r\nax.set_ylabel(\"PC 2\")\r\nax.w_yaxis.set_ticklabels([])\r\nax.set_zlabel(\"PC 3\")\r\nax.w_zaxis.set_ticklabels([])\r\nplt.legend(loc='upper right')\r\n\r\nplt.show()\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "86ba349d31194fb81e31c2d527c61d1ad519fd23", "size": 4280, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW2_Submit/HW2/pca_covariance.py", "max_stars_repo_name": "munir-bd/python-machine-learning-basic", "max_stars_repo_head_hexsha": "b02fc22ce83895b7598bbc3aee9031684db2aa9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW2_Submit/HW2/pca_covariance.py", "max_issues_repo_name": "munir-bd/python-machine-learning-basic", "max_issues_repo_head_hexsha": "b02fc22ce83895b7598bbc3aee9031684db2aa9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW2_Submit/HW2/pca_covariance.py", "max_forks_repo_name": "munir-bd/python-machine-learning-basic", "max_forks_repo_head_hexsha": "b02fc22ce83895b7598bbc3aee9031684db2aa9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0819672131, "max_line_length": 150, "alphanum_fraction": 0.6761682243, "include": true, "reason": "import numpy", "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140216112958, "lm_q2_score": 0.8933094167058151, "lm_q1q2_score": 0.8637534006502605}}
{"text": "import numpy as np\n\ndef minmax_scaling(x, m=None, r=None):\n    \"\"\"\n    m: midrange\n    r: range\n    \"\"\"\n    \n    xmin = np.min(x, axis=0)\n    xmax = np.max(x, axis=0)\n    \n    if m is None:\n        m = (xmin + xmax) / 2\n    if r is None:\n        r = xmax - xmin\n\n    #with np.errstate(divide='ignore'):\n    np.seterr(divide='ignore')\n    ret = (x-m)/(r/2)\n        \n    ret[np.where(np.isnan(ret))] = 0.0  \n    return ret, m, r\n\n\ndef standardize(x, m=None, r=None):\n    \"\"\"\n    m: midrange\n    r: range\n    \"\"\"\n\n    if m is None:\n        m = np.mean(x, axis=0)\n    if r is None:\n        r = np.std(x, axis=0, ddof=1)\n\n    #with np.errstate(divide='ignore'):\n    np.seterr(divide='ignore', invalid='ignore')\n    ret = (x-m)/r\n     \n    ret[np.where(np.isnan(ret))] = 0.0  \n    return ret, m, r\n\n\ndef norm_l2(x, m = None, r = None):\n    \"\"\"\n    m: midrange\n    r: range\n    \"\"\"\n\n    if m is None:\n        m = np.mean(x) # not axis = 0 because result = (x-E(x))/normL2(X)\n\n    # centering\n    x = x-m\n\n    if r is None:\n        r = np.sqrt(np.sum((x)**2, axis = 0))\n\n    #with np.errstate(divide='ignore'):\n    np.seterr(divide='ignore')\n    ret = x/r \n\t \n    ret[np.where(np.isnan(ret))] = 0.0\n\n    return ret, m, r\n\n", "meta": {"hexsha": "828915430d5546417e2f8cbaf333087055eb47a1", "size": 1214, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/scaling.py", "max_stars_repo_name": "AleZandona/ml_rSNFi", "max_stars_repo_head_hexsha": "a765042fd45dbe88b544eb2611dee171a0939caa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-07-22T12:17:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-05T11:26:44.000Z", "max_issues_repo_path": "scripts/scaling.py", "max_issues_repo_name": "AleZandona/ml_rSNFi", "max_issues_repo_head_hexsha": "a765042fd45dbe88b544eb2611dee171a0939caa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/scaling.py", "max_forks_repo_name": "AleZandona/ml_rSNFi", "max_forks_repo_head_hexsha": "a765042fd45dbe88b544eb2611dee171a0939caa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1194029851, "max_line_length": 73, "alphanum_fraction": 0.4983525535, "include": true, "reason": "import numpy", "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140235181257, "lm_q2_score": 0.8933093975331752, "lm_q1q2_score": 0.8637533838153553}}
{"text": "# Implement the Binomial Tree method for American call/put options\n\nimport numpy as np\n\ndef american_call_binomial_tree(s_0, sigma, r, T, K, N):\n    \"\"\"Calculate the value of American call option by the method of\n    Binomial Tree.\n\n    Args:\n        s_0: The value of asset S at time 0\n        sigma: The volatility\n        r: The risk-free rate\n        T: The time to maturity(in years)\n        K: Strike\n        N: The number of steps in Binomial Tree\n\n    Returns:\n        The American call option value\n    \"\"\"\n    def _calculate_node_value(v_0, remain_layer):\n        \"\"\"Calculate the option value at this node\n\n        Args:\n            v_0: The stock price at this node\n            remain_layer: The remaining layer number from leaf node\n\n        Returns:\n            The call option value at this node\n        \"\"\"\n        if remain_layer <= 0:\n            return max(v_0-K, 0)\n        else:\n            return max(v_0-K, _DF*(_p*_calculate_node_value(v_0*_u, remain_layer-1)\n                              + (1-_p)*_calculate_node_value(v_0*_d, remain_layer-1)))\n\n    _delta_T = T/N\n    _u = np.exp(sigma*np.sqrt(_delta_T))\n    _d = 1/_u\n    _p = (np.exp(r*_delta_T)-_d)/(_u-_d)\n    _DF = np.exp(-r*_delta_T) # discount factor DF = e^(-r*deltaT)\n\n    return _calculate_node_value(s_0, N)\n\ndef american_put_binomial_tree(s_0, sigma, r, T, K, N):\n    \"\"\"Calculate the value of American put option by the method of\n    Binomial Tree.\n\n    Args:\n        s_0: The value of asset S at time 0\n        sigma: The volatility\n        r: The risk-free rate\n        T: The time to maturity(in years)\n        K: Strike\n        N: The number of steps in Binomial Tree\n\n    Returns:\n        The American put option value\n    \"\"\"\n    def _calculate_node_value(v_0, remain_layer):\n        \"\"\"Calculate the option value at this node\n\n        Args:\n            v_0: The stock price at this node\n            remain_layer: The remaining layer number from leaf node\n\n        Returns:\n            The put option value at this node\n        \"\"\"\n        if remain_layer <= 0:\n            return max(K-v_0, 0)\n        else:\n            return max(K-v_0, _DF*(_p*_calculate_node_value(v_0*_u, remain_layer-1)\n                              + (1-_p)*_calculate_node_value(v_0*_d, remain_layer-1)))\n\n    _delta_T = T/N\n    _u = np.exp(sigma*np.sqrt(_delta_T))\n    _d = 1/_u\n    _p = (np.exp(r*_delta_T)-_d)/(_u-_d)\n    _DF = np.exp(-r*_delta_T) # discount factor DF = e^(-r*deltaT)\n\n    return _calculate_node_value(s_0, N)\n\ndef main():\n    K = 52\n    T = 2\n    r = 0.05\n    sigma = 0.223144\n    s_0 = 50\n    N = 2\n    print(\"American put value: \" + str(american_put_binomial_tree(s_0, sigma, r, T, K, N)))\n\n    K = 50\n    T = 0.25\n    r = 0.05\n    sigma = 0.3\n    s_0 = 50\n    N = 1\n    print(\"American call value: \" + str(american_call_binomial_tree(s_0, sigma, r, T, K, N)))\n\n    N = 2\n    print(\"American call value: \" + str(american_call_binomial_tree(s_0, sigma, r, T, K, N)))\n    \n    N = 3\n    print(\"American call value: \" + str(american_call_binomial_tree(s_0, sigma, r, T, K, N)))\n\n\nif __name__ == '__main__':\n    main()", "meta": {"hexsha": "76481bfedbdd0ae880c97441bd5d468455fae528", "size": 3108, "ext": "py", "lang": "Python", "max_stars_repo_path": "option_pricer/binomial_tree.py", "max_stars_repo_name": "tsengkasing/option-pricer", "max_stars_repo_head_hexsha": "89fff55070834698d801f3a6eb10e16d40fc7762", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "option_pricer/binomial_tree.py", "max_issues_repo_name": "tsengkasing/option-pricer", "max_issues_repo_head_hexsha": "89fff55070834698d801f3a6eb10e16d40fc7762", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "option_pricer/binomial_tree.py", "max_forks_repo_name": "tsengkasing/option-pricer", "max_forks_repo_head_hexsha": "89fff55070834698d801f3a6eb10e16d40fc7762", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7777777778, "max_line_length": 93, "alphanum_fraction": 0.5907335907, "include": true, "reason": "import numpy", "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542805873231, "lm_q2_score": 0.90052978812007, "lm_q1q2_score": 0.8637470010717603}}
{"text": "#Creating Arrays\n\"\"\"Zero-dimensional Arrays in Numpy\n\nIt's possible to create multidimensional arrays in numpy. Scalars are zero dimensional. In the following example, we will create the scalar 42. Applying the ndim method to our scalar, we get the dimension of the array. We can also see that the type is a \"numpy.ndarray\" type.\n\"\"\"\nimport numpy as np\nx = np.array(42)\nprint(\"x: \", x)\nprint(\"The type of x: \", type(x))\nprint(\"The dimension of x:\", np.ndim(x))\n\n\"\"\"One-dimensional Arrays\n\nWe have already encountered a 1-dimenional array - better known to some as vectors - in our initial example. What we have not mentioned so far, but what you may have assumed, is the fact that numpy arrays are containers of items of the same type, e.g. only integers. The homogenous type of the array can be determined with the attribute \"dtype\", as we can learn from the following example:\n\"\"\"\nF = np.array([1, 1, 2, 3, 5, 8, 13, 21])\nV = np.array([3.4, 6.9, 99.8, 12.8])\nprint(\"F: \", F)\nprint(\"V: \", V)\nprint(\"Type of F: \", F.dtype)\nprint(\"Type of V: \", V.dtype)\nprint(\"Dimension of F: \", np.ndim(F))\nprint(\"Dimension of V: \", np.ndim(V))\n\"\"\"\nTwo- and Multidimensional Arrays\n\nOf course, arrays of NumPy are not limited to one dimension. They are of arbitrary dimension. We create them by passing nested lists (or tuples) to the array method of numpy.\n\"\"\"\nA = np.array([ [3.4, 8.7, 9.9], \n               [1.1, -7.8, -0.7],\n               [4.1, 12.3, 4.8]])\nprint(A)\nprint(A.ndim)\n\n", "meta": {"hexsha": "757df9a69a005a6b01f83c93d5d418be0b703108", "size": 1471, "ext": "py", "lang": "Python", "max_stars_repo_path": "4.Creating_arrays.py", "max_stars_repo_name": "Mansihpatel/numpy-practise", "max_stars_repo_head_hexsha": "e6edd8e21b7b5da9274bbaea17fdafbe87b1d17d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4.Creating_arrays.py", "max_issues_repo_name": "Mansihpatel/numpy-practise", "max_issues_repo_head_hexsha": "e6edd8e21b7b5da9274bbaea17fdafbe87b1d17d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4.Creating_arrays.py", "max_forks_repo_name": "Mansihpatel/numpy-practise", "max_forks_repo_head_hexsha": "e6edd8e21b7b5da9274bbaea17fdafbe87b1d17d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0285714286, "max_line_length": 389, "alphanum_fraction": 0.6852481305, "include": true, "reason": "import numpy", "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.9263037318197961, "lm_q1q2_score": 0.8637349867000389}}
{"text": "import numpy as np\nfrom scipy import optimize\nfrom matplotlib import pyplot as plt, cm, colors\nfrom math import sqrt, pi\n\ndef calc_R(x,y, xc, yc):\n    \"\"\"\n    calculate the distance of each 2D points from the center (xc, yc)\n    \"\"\"\n    return np.sqrt((x-xc)**2 + (y-yc)**2)\n\ndef f(c, x, y):\n    \"\"\"\n    calculate the algebraic distance between the data points\n    and the mean circle centered at c=(xc, yc)\n    \"\"\"\n    Ri = calc_R(x, y, *c)\n    return Ri - Ri.mean()\n\ndef sigma(coords, x, y, r):\n    \"\"\"Computes Sigma for circle fit.\"\"\"\n    dx, dy, sum_ = 0., 0., 0.\n\n    for i in range(len(coords)):\n        dx = coords[i][1] - x\n        dy = coords[i][0] - y\n        sum_ += (sqrt(dx*dx+dy*dy) - r)**2\n    return sqrt(sum_/len(coords))\n\ndef hyper_fit(coords, IterMax=99, verbose=False):\n    \"\"\"\n    Fits coords to circle using hyperfit algorithm.\n\n    Inputs:\n        - coords, list or numpy array with len>2 of the form:\n        [\n    [x_coord, y_coord],\n    ...,\n    [x_coord, y_coord]\n    ]\n        or numpy array of shape (n, 2)\n\n    Outputs:\n\n        - xc : x-coordinate of solution center (float)\n        - yc : y-coordinate of solution center (float)\n        - R : Radius of solution (float)\n        - residu : s, sigma - variance of data wrt solution (float)\n\n    \"\"\"\n    X, X = None, None\n    if isinstance(coords, np.ndarray):\n        X = coords[:, 0]\n        Y = coords[:, 1]\n    elif isinstance(coords, list):\n        X = np.array([x[0] for x in coords])\n        Y = np.array([x[1] for x in coords])\n    else:\n        raise Exception(\"Parameter 'coords' is an unsupported type: \" + str(type(coords)))\n\n    n = X.shape[0]\n\n    Xi = X - X.mean()\n    Yi = Y - Y.mean()\n    Zi = Xi*Xi + Yi*Yi\n\n    #compute moments\n    Mxy = (Xi*Yi).sum()/n\n    Mxx = (Xi*Xi).sum()/n\n    Myy = (Yi*Yi).sum()/n\n    Mxz = (Xi*Zi).sum()/n\n    Myz = (Yi*Zi).sum()/n\n    Mzz = (Zi*Zi).sum()/n\n\n    #computing the coefficients of characteristic polynomial\n    Mz = Mxx + Myy\n    Cov_xy = Mxx*Myy - Mxy*Mxy\n    Var_z = Mzz - Mz*Mz\n\n    A2 = 4*Cov_xy - 3*Mz*Mz - Mzz\n    A1 = Var_z*Mz + 4.*Cov_xy*Mz - Mxz*Mxz - Myz*Myz\n    A0 = Mxz*(Mxz*Myy - Myz*Mxy) + Myz*(Myz*Mxx - Mxz*Mxy) - Var_z*Cov_xy\n    A22 = A2 + A2\n\n    #finding the root of the characteristic polynomial\n    y = A0\n    x = 0.\n    for i in range(IterMax):\n        Dy = A1 + x*(A22 + 16.*x*x)\n        xnew = x - y/Dy\n        if xnew == x or not np.isfinite(xnew):\n            break\n        ynew = A0 + xnew*(A1 + xnew*(A2 + 4.*xnew*xnew))\n        if abs(ynew)>=abs(y):\n            break\n        x, y = xnew, ynew\n\n    det = x*x - x*Mz + Cov_xy\n    Xcenter = (Mxz*(Myy - x) - Myz*Mxy)/det/2.\n    Ycenter = (Myz*(Mxx - x) - Mxz*Mxy)/det/2.\n\n    x = Xcenter + X.mean()\n    y = Ycenter + Y.mean()\n    r = sqrt(abs(Xcenter**2 + Ycenter**2 + Mz))\n    s = sigma(coords,x,y,r)\n    iter_ = i\n    if verbose:\n        print('Regression complete in {} iterations.'.format(iter_))\n        print('Sigma computed: ', s)\n    return x, y, r, s\n\ndef least_squares_circle(coords, radius):\n    \"\"\"\n    Circle fit using least-squares solver.\n    Inputs:\n\n        - coords, list or numpy array with len>2 of the form:\n        [\n    [x_coord, y_coord],\n    ...,\n    [x_coord, y_coord]\n    ]\n        or numpy array of shape (n, 2)\n\n    Outputs:\n\n        - xc : x-coordinate of solution center (float)\n        - yc : y-coordinate of solution center (float)\n        - R : Radius of solution (float)\n        - residu : MSE of solution against training data (float)\n    \"\"\"\n\n    x, y = None, None\n    if isinstance(coords, np.ndarray):\n        x = coords[:, 0]\n        y = coords[:, 1]\n    elif isinstance(coords, list):\n        x = np.array([point[0] for point in coords])\n        y = np.array([point[1] for point in coords])\n    else:\n        raise Exception(\"Parameter 'coords' is an unsupported type: \" + str(type(coords)))\n\n    # coordinates of the barycenter\n    #x_m = np.mean(x)\n    #y_m = np.mean(y)\n    center_estimate = np.mean(x), np.mean(y)\n    center, _ = optimize.leastsq(f, center_estimate, args=(x,y))\n    xc, yc = center\n    #Ri       = calc_R(x, y, *center)\n    #R        = Ri.mean()\n    R = radius\n    #residu   = np.sum((Ri - R)**2)\n    #return xc, yc, R#, residu\n    return xc, yc, R, center_estimate\n\ndef plot_data_circle(x, y, xc, yc, R):\n    \"\"\"\n    Plot data and a fitted circle.\n    Inputs:\n\n        x : data, x values (array)\n        y : data, y values (array)\n        xc : fit circle center (x-value) (float)\n        yc : fit circle center (y-value) (float)\n        R : fir circle radius (float)\n\n    Output:\n        None (generates matplotlib plot).\n    \"\"\"\n    f = plt.figure(facecolor='white')\n    plt.axis('equal')\n\n    theta_fit = np.linspace(-pi, pi, 180)\n\n    x_fit = xc + R*np.cos(theta_fit)\n    y_fit = yc + R*np.sin(theta_fit)\n    plt.plot(x_fit, y_fit, 'b-' , label=\"fitted circle\", lw=2)\n    plt.plot([xc], [yc], 'bD', mec='y', mew=1)\n    plt.xlabel('x')\n    plt.ylabel('y')\n    # plot data\n    plt.scatter(x, y, c='red', label='data')\n\n    plt.legend(loc='best',labelspacing=0.1 )\n    plt.grid()\n    plt.title('Fit Circle')\n", "meta": {"hexsha": "42fc6b57c7533e99b6b7bc7bb539aeed5372eb3c", "size": 5086, "ext": "py", "lang": "Python", "max_stars_repo_path": "circle_fit/circle_fit.py", "max_stars_repo_name": "AlephNaughtNWMSU/seminar", "max_stars_repo_head_hexsha": "d73255b5d5f32a1b9c29205b62fb1880c80523d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-04T22:36:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T06:10:28.000Z", "max_issues_repo_path": "circle_fit/circle_fit.py", "max_issues_repo_name": "AlephNaughtNWMSU/seminar", "max_issues_repo_head_hexsha": "d73255b5d5f32a1b9c29205b62fb1880c80523d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-02-26T03:57:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-22T19:37:17.000Z", "max_forks_repo_path": "circle_fit/circle_fit.py", "max_forks_repo_name": "AlephNaughtNWMSU/seminar", "max_forks_repo_head_hexsha": "d73255b5d5f32a1b9c29205b62fb1880c80523d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-02-25T22:55:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T00:11:50.000Z", "avg_line_length": 27.1978609626, "max_line_length": 90, "alphanum_fraction": 0.5526936689, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.9124361545241945, "lm_q1q2_score": 0.8637090256428556}}
{"text": "\n# coding: utf-8\n\n# #Numpy Tutorial\n\n# Numpy is a computational library for Python that is optimized for operations on multi-dimensional arrays. In this notebook we will use numpy to work with 1-d arrays (often called vectors) and 2-d arrays (often called matrices).\n# \n# For a the full user guide and reference for numpy see: http://docs.scipy.org/doc/numpy/\n\n# In[1]:\n\nimport numpy as np # importing this way allows us to refer to numpy as np\n\n\n# # Creating Numpy Arrays\n\n# New arrays can be made in several ways. We can take an existing list and convert it to a numpy array:\n\n# In[7]:\n\nmylist = [1., 2., 3., 4.]\nmynparray = np.array(mylist)\nmynparray\n\n\n# You can initialize an array (of any dimension) of all ones or all zeroes with the ones() and zeros() functions:\n\n# In[8]:\n\none_vector = np.ones(4)\nprint one_vector # using print removes the array() portion\n\n\n# In[12]:\n\none2Darray = np.ones((2, 4)) # an 2D array with 2 \"rows\" and 4 \"columns\"\nprint one2Darray\n\n\n# In[13]:\n\nzero_vector = np.zeros(4)\nprint zero_vector\n\n\n# You can also initialize an empty array which will be filled with values. This is the fastest way to initialize a fixed-size numpy array however you must ensure that you replace all of the values.\n\n# In[14]:\n\nempty_vector = np.empty(5)\nprint empty_vector\n\n\n# #Accessing array elements\n\n# Accessing an array is straight forward. For vectors you access the index by referring to it inside square brackets. Recall that indices in Python start with 0.\n\n# In[15]:\n\nmynparray[2]\n\n\n# 2D arrays are accessed similarly by referring to the row and column index separated by a comma:\n\n# In[20]:\n\nmy_matrix = np.array([[1, 2, 3], [4, 5, 6]])\nprint my_matrix\n\n\n# In[21]:\n\nprint my_matrix[1, 2]\n\n\n# Sequences of indices can be accessed using ':' for example\n\n# In[22]:\n\nprint my_matrix[0:2, 2] # recall 0:2 = [0, 1]\n\n\n# In[23]:\n\nprint my_matrix[0, 0:3]\n\n\n# You can also pass a list of indices. \n\n# In[24]:\n\nfib_indices = np.array([1, 1, 2, 3])\nrandom_vector = np.random.random(10) # 10 random numbers between 0 and 1\nprint random_vector\n\n\n# In[25]:\n\nprint random_vector[fib_indices]\n\n\n# You can also use true/false values to select values\n\n# In[28]:\n\nmy_vector = np.array([1, 2, 3, 4])\nselect_index = np.array([True, False, True, False])\nprint my_vector[select_index]\n\n\n# For 2D arrays you can select specific columns and specific rows. Passing ':' selects all rows/columns\n\n# In[29]:\n\nselect_cols = np.array([True, False, True]) # 1st and 3rd column\nselect_rows = np.array([False, True]) # 2nd row\n\n\n# In[30]:\n\nprint my_matrix[select_rows, :] # just 2nd row but all columns\n\n\n# In[31]:\n\nprint my_matrix[:, select_cols] # all rows and just the 1st and 3rd column\n\n\n# #Operations on Arrays\n\n# You can use the operations '\\*', '\\*\\*', '\\\\', '+' and '-' on numpy arrays and they operate elementwise.\n\n# In[33]:\n\nmy_array = np.array([1., 2., 3., 4.])\nprint my_array*my_array\n\n\n# In[34]:\n\nprint my_array**2\n\n\n# In[35]:\n\nprint my_array - np.ones(4)\n\n\n# In[36]:\n\nprint my_array + np.ones(4)\n\n\n# In[37]:\n\nprint my_array / 3\n\n\n# In[38]:\n\nprint my_array / np.array([2., 3., 4., 5.]) # = [1.0/2.0, 2.0/3.0, 3.0/4.0, 4.0/5.0]\n\n\n# You can compute the sum with np.sum() and the average with np.average()\n\n# In[39]:\n\nprint np.sum(my_array)\n\n\n# In[40]:\n\nprint np.average(my_array)\n\n\n# In[41]:\n\nprint np.sum(my_array)/len(my_array)\n\n\n# #The dot product\n\n# An important mathematical operation in linear algebra is the dot product. \n# \n# When we compute the dot product between two vectors we are simply multiplying them elementwise and adding them up. In numpy you can do this with np.dot()\n\n# In[42]:\n\narray1 = np.array([1., 2., 3., 4.])\narray2 = np.array([2., 3., 4., 5.])\nprint np.dot(array1, array2)\n\n\n# In[43]:\n\nprint np.sum(array1*array2)\n\n\n# Recall that the Euclidean length (or magnitude) of a vector is the squareroot of the sum of the squares of the components. This is just the squareroot of the dot product of the vector with itself:\n\n# In[44]:\n\narray1_mag = np.sqrt(np.dot(array1, array1))\nprint array1_mag\n\n\n# In[46]:\n\nprint np.sqrt(np.sum(array1*array1))\n\n\n# We can also use the dot product when we have a 2D array (or matrix). When you have an vector with the same number of elements as the matrix (2D array) has columns you can right-multiply the matrix by the vector to get another vector with the same number of elements as the matrix has rows. For example this is how you compute the predicted values given a matrix of features and an array of weights.\n\n# In[47]:\n\nmy_features = np.array([[1., 2.], [3., 4.], [5., 6.], [7., 8.]])\nprint my_features\n\n\n# In[48]:\n\nmy_weights = np.array([0.4, 0.5])\nprint my_weights\n\n\n# In[49]:\n\nmy_predictions = np.dot(my_features, my_weights) # note that the weights are on the right\nprint my_predictions # which has 4 elements since my_features has 4 rows\n\n\n# Similarly if you have a vector with the same number of elements as the matrix has *rows* you can left multiply them.\n\n# In[50]:\n\nmy_matrix = my_features\nmy_array = np.array([0.3, 0.4, 0.5, 0.6])\n\n\n# In[51]:\n\nprint np.dot(my_array, my_matrix) # which has 2 elements because my_matrix has 2 columns\n\n\n# #Multiplying Matrices\n\n# If we have two 2D arrays (matrices) matrix_1 and matrix_2 where the number of columns of matrix_1 is the same as the number of rows of matrix_2 then we can use np.dot() to perform matrix multiplication.\n\n# In[52]:\n\nmatrix_1 = np.array([[1., 2., 3.],[4., 5., 6.]])\nprint matrix_1\n\n\n# In[53]:\n\nmatrix_2 = np.array([[1., 2.], [3., 4.], [5., 6.]])\nprint matrix_2\n\n\n# In[54]:\n\nprint np.dot(matrix_1, matrix_2)\n\n\n# In[ ]:\n\n\n\n", "meta": {"hexsha": "9cabb86c828f254d7ccf909b04a3b7c1aeecacde", "size": 5552, "ext": "py", "lang": "Python", "max_stars_repo_path": "Course-2-Regression/numpy-tutorial.py", "max_stars_repo_name": "emetnatbelt/Machine-Learning-Univ-Washington1", "max_stars_repo_head_hexsha": "6e6f9cd69b69157f5c09eed299ab120bf6764de3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2017-04-06T08:50:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T13:43:22.000Z", "max_issues_repo_path": "Course-2-Regression/numpy-tutorial.py", "max_issues_repo_name": "emetnatbelt/Machine-Learning-Univ-Washington", "max_issues_repo_head_hexsha": "6e6f9cd69b69157f5c09eed299ab120bf6764de3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Course-2-Regression/numpy-tutorial.py", "max_forks_repo_name": "emetnatbelt/Machine-Learning-Univ-Washington", "max_forks_repo_head_hexsha": "6e6f9cd69b69157f5c09eed299ab120bf6764de3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2016-06-01T21:28:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T03:17:11.000Z", "avg_line_length": 20.562962963, "max_line_length": 400, "alphanum_fraction": 0.6936239193, "include": true, "reason": "import numpy", "num_tokens": 1632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.9334308151961578, "lm_q1q2_score": 0.8636381569412536}}
{"text": "\"\"\"\nContent under Creative Commons Attribution license CC-BY 4.0, \ncode under MIT license (c)2018 Sergio Rojas (srojas@usb.ve) \n\nhttp://en.wikipedia.org/wiki/MIT_License\nhttp://creativecommons.org/licenses/by/4.0/\n\nCreated on april, 2018\nLast Modified on: may 15, 2018\n\n  This program finds the solution of any equation\n  Depending how you write your equation,\n  the answer could be a rational or a real number. \n\n  The trick to find rational solution to equations is to\n  write at least one numerical value as fractions using \n  the SymPy S function\n\n\"\"\"\nfrom sympy import symbols, Eq, solveset, S, sympify\nthevar = input('Enter the variable name (i.e. x, y, z): ')\n\nthevar = symbols(thevar) # make the given variable a SymPy symbol\n\nmessage = \\\n\" *=========\\n \\\n*  Input the part of your equations as requested \\n \\\n*  If your equation looks like: (3/2){0} - 8 = 7{0} + 5 \\n \\\n*  LHS = (3/2){0} - 8, and you should enter for it: (3/2)*{0} - S('8') \\n \\\n*  RHS =     7{0} + 5, and you should enter for it: 7*{0} + S('5') \\n \\\n*  If you write your equation in a text editor, copy and paste might work. \\n \\\n*=========\"\nprint(message.format(thevar))\nans = True\nwhile ans:\n   LHS = input('Enter the LHS of the equation: ')\n   print('\\t You entered LHS = ', LHS)\n   RHS = input('Enter the RHS of the equation: ')\n   print('\\t You entered RHS = ', RHS)\n   try:\n      LHS = sympify(LHS)  # sympify makes a function from an string\n      LHS.subs(thevar, 2) # check evaluating the function with a number (2)\n      RHS = sympify(RHS)  # sympify makes a function from an string\n      RHS.subs(thevar, 2) # check evaluating the function with a number (2)\n      ans = False\n   except Exception as errorCapturado:\n      ans = True\n      print('\\t Something is wrong with the giving inputs !!!')\n      print('\\t Please, try again:')\n\nthesol = list( solveset( Eq(LHS, RHS), thevar) )\n#print('thesol =', thesol)\n\ntheEq = LHS - RHS #rearrange the equation to read: LHS - RHS = 0\n#print('theEq =', theEq)\n\ncheckSol = []\nfor sol in thesol:\n   temp = theEq.subs(thevar, sol)\n   temp = temp.simplify()\n   checkSol = checkSol + [temp]\n\nif sum(checkSol) < 1e-10:\n    print('Solution(s) of {0} = {1}:'.format(LHS,RHS))\n    for sol in thesol: \n        print('\\t {0} = {1}\\n'.format(thevar,sol))\nelse:\n    print('Solution(s) found were (check them by substitution): ')\n    for sol in thesol: \n        print('\\t {0} = {1}\\n'.format(thevar,sol))\n\n", "meta": {"hexsha": "7c22672cbf3e782e06b70b01e5ebdad49ec98b76", "size": 2420, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter_05/chap05_prog_03_Sympy_SolInputEquation.py", "max_stars_repo_name": "rojassergio/Prealgebra-via-Python-Programming", "max_stars_repo_head_hexsha": "8d1cdf103af2a39f6ae7bba76e9a6a0182eb39d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-19T11:54:15.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-19T11:54:15.000Z", "max_issues_repo_path": "Chapter_05/chap05_prog_03_Sympy_SolInputEquation.py", "max_issues_repo_name": "rojassergio/Prealgebra-via-Python-Programming", "max_issues_repo_head_hexsha": "8d1cdf103af2a39f6ae7bba76e9a6a0182eb39d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter_05/chap05_prog_03_Sympy_SolInputEquation.py", "max_forks_repo_name": "rojassergio/Prealgebra-via-Python-Programming", "max_forks_repo_head_hexsha": "8d1cdf103af2a39f6ae7bba76e9a6a0182eb39d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-03-02T22:31:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T05:06:39.000Z", "avg_line_length": 33.6111111111, "max_line_length": 79, "alphanum_fraction": 0.647107438, "include": true, "reason": "from sympy", "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.9334308147331957, "lm_q1q2_score": 0.8636381507395183}}
{"text": "import numpy as np\nimport cvxopt as co\nimport cvxpy as cp\n\nimport numpy.testing as npt\n\n\nco.solvers.options['show_progress'] = False\nco.solvers.options['glpk'] = {'msg_lev': 'GLP_MSG_ERR'}\n\n# https://www.analyzemath.com/linear_programming/linear_prog_applications.html\n\n\ndef example1_cvxpy():\n    \"\"\" \n    A = 8\n    B = 14\n\n    Profit:\n    A = 2\n    B = 3\n\n    A + B < 2000\n    8A + 14B < 20000\n\n    max 2A + 3B\n    \"\"\"\n\n    A = cp.Variable()\n    B = cp.Variable()\n\n    constr = [\n        A + B <= 2000,\n        8*A + 14*B <= 20000,\n        A >= 0,\n        B >= 0,\n    ]\n    cp.Problem(cp.Maximize(2*A + 3 * B),\n               constraints=constr).solve(solver='GLPK')\n    return [A.value, B.value]\n\n\ndef example1_cvxopt():\n    G = co.matrix(np.array([\n        [-1, 0],\n        [0, -1],\n        [1, 1],\n        [8, 14]\n    ], dtype=float))\n\n    c = co.matrix([-2.0, -3.0])\n\n    h = co.matrix([-0.0, -0.0, 2000.0, 20000.0])\n\n    sol = co.solvers.lp(c, G, h, solver='glpk')\n\n    return np.array(sol['x']).flatten()\n\n\ndef example4_cvxpy():\n    \"\"\"\n    F1 2%\n    F2 4%\n    F3 5%\n\n    F3 < 3000\n    F2 < 2*F1\n\n    Max 2 F1 + 4 F2 + 5 F3\n    \"\"\"\n\n    f1 = cp.Variable()\n    f2 = cp.Variable()\n    f3 = cp.Variable()\n\n    constr = [\n        f1 >= 0,\n        f2 >= 0,\n        f3 >= 0,\n        f2 <= 2 * f1,\n        f3 <= 3000,\n        f1 + f2 + f3 <= 20000\n    ]\n\n    cp.Problem(cp.Maximize(2 * f1 + 4 * f2 + 5 * f3),\n               constraints=constr).solve(solver='GLPK')\n    return [f1.value, f2.value, f3.value]\n\n\ndef example4_cvxopt():\n    G = co.matrix(np.array([\n        [-1, 0, 0],\n        [0, -1, 0],\n        [0, 0, -1],\n        [-2, 1, 0],  # f2 <= 2 * f1 --> -2 *f1 + f2 <= 0\n        [0, 0, 1],\n        [1, 1, 1]\n    ], dtype=float))\n\n    c = co.matrix([-2.0, -4.0, -5.0])\n\n    h = co.matrix([-0.0, -0.0, -0.0, -0.0, 3000.0, 20000.0])\n\n    # default solver results in a diff @ 3 decimal\n    sol = co.solvers.lp(c, G, h, solver='glpk')\n    return np.array(sol['x']).flatten()\n\n\ndef example4_cvxopt_explit_z():\n    \"\"\"\n    Saw in some examples that the objective is explictly listed as one of the\n    variables. Not exactly see why it is done this way, as it makes the system\n    of equitions longer and harder to understand... but anyways, \n    listed here so I can remember how it works. This is essentially doing minmax\n    \"\"\"\n    G = np.array([\n        [-1, 0, 0],\n        [0, -1, 0],\n        [0, 0, -1],\n        [-2, 1, 0],  # f2 <= 2 * f1 --> -2 *f1 + f2 <= 0\n        [0, 0, 1],\n        [1, 1, 1]\n    ], dtype=float)\n\n    G = np.hstack((\n        np.zeros((G.shape[0], 1)),\n        G\n    ))\n    G = np.vstack((\n        G,\n        # maximize z st: z <= 2 F1 + 4 F2 + 5 F3\n        # is the same as:\n        # minimize -z st: -z >= -2f1 - 4f2 - 5f3 ---> z - 2f1 - 4f2 - 5f3 <= 0\n        np.array([1, -2, -4, -5])\n    ))\n    G = co.matrix(G)\n\n    # resulting G\n    #  first col is the objective, it does not participate in any of the constraits, other than\n    #  the actual minimize objective listed in the very last row.\n    #   |\n    #   v\n    # [[ 0. -1.  0.  0.]\n    # [ 0.  0. -1.  0.]\n    # [ 0.  0.  0. -1.]\n    # [ 0. -2.  1.  0.]\n    # [ 0.  0.  0.  1.]\n    # [ 0.  1.  1.  1.]\n    # [ 1. -2. -4. -5.]]\n\n    c = co.matrix([-1.0, 0.0, 0.0, 0.0])  # minimize -z\n\n    h = co.matrix([-0.0, -0.0, -0.0, -0.0, 3000.0, 20000.0, -0.0])\n\n    # default solver results in a diff @ 3 decimal\n    sol = co.solvers.lp(c, G, h, solver='glpk')\n    return sol['x'][0], np.array(sol['x'][1:]).flatten()\n\n\ndef rock_paper_scissors_cvxpy():\n    r = cp.Variable()\n    p = cp.Variable()\n    s = cp.Variable()\n    z = cp.Variable()  # obj\n\n    constr = [\n        r >= 0,\n        p >= 0,\n        s >= 0,\n        r + p + s == 1,\n        # rps rules using maxmin\n        # max Z, s.t.:\n        z <= +0*r - 1*p + 1*s,\n        z <= +1*r + 0*p - 1*s,\n        z <= -1*r + 1*p + 0*s,\n    ]\n\n    cp.Problem(cp.Maximize(z), constraints=constr).solve(solver='GLPK')\n    print('rock paper scissors solution using cvxpy')\n    print('expected value of the game: ', z.value)\n    print('best stragegy: ', np.array([r.value, p.value, s.value]).flatten())\n\n    # matrix form\n    rpsrule = np.array([[0, -1, 1],\n                        [1, 0, -1],\n                        [-1, 1, 0]], dtype=float)\n    rps = cp.Variable(3)\n    z1 = cp.Variable()\n\n    constr1 = [\n        rps >= 0,\n        sum(rps) == 1,\n        # rps rules using maxmin\n        # max Z, s.t.:\n        z1 <= rpsrule @ rps\n    ]\n    cp.Problem(cp.Maximize(z1), constraints=constr1).solve(solver='GLPK')\n    print('rock paper scissors solution using cvxpy Matrix')\n    print('expected value of the game: ', z1.value)\n    print('best stragegy: ', np.array([rps.value]).flatten())\n\n\ndef rock_paper_scissors_cvxopt():\n    rpsrule = np.array([[0, -1, 1],\n                        [1, 0, -1],\n                        [-1, 1, 0]], dtype=float)\n\n    G = co.matrix(np.vstack((\n        # negating 'rpsrule' or not would generate the same result.\n        # Without negating it is calcuating the probablity for column player.\n        # Since this is a zero sum game, the stragegy for both row and column player would be identical.\n        # Also note that here negating has the same effect as transposing (switch row and col).\n        np.hstack((np.ones((3, 1)), - rpsrule)),\n        np.hstack((np.zeros((3, 1)), - np.eye(3))),  # each P >= 0\n    )))\n\n    c = co.matrix([-1.0, 0.0, 0.0, 0.0])\n    h = co.matrix(np.zeros(G.size[0]))\n\n    # sum P == 1\n    A = co.matrix(np.array([[0.0, 1.0, 1.0, 1.0]]))\n    b = co.matrix([1.0])\n\n    sol = co.solvers.lp(c, G, h, A, b, solver='glpk')\n\n    print('rock paper scissors solution using cvxopt')\n    print('expected value of the game: ', sol['x'][0])\n    print('best stragegy: ', np.array(sol['x'][1:]).flatten())\n\n\nif __name__ == \"__main__\":\n    ex1_coeff = np.array([2, 3])\n    npt.assert_almost_equal(\n        np.dot(ex1_coeff, example1_cvxpy()),\n        np.dot(ex1_coeff, example1_cvxopt()), decimal=10)\n\n    ex4_coeff = np.array([2, 4, 5])\n    npt.assert_almost_equal(\n        np.dot(ex4_coeff, example4_cvxpy()),\n        np.dot(ex4_coeff, example4_cvxopt()), decimal=10)\n\n    sol = example4_cvxopt()\n    obj = np.dot(ex4_coeff, sol)\n    obj_z, sol_z = example4_cvxopt_explit_z()\n\n    print('normal vs explicit z:')\n    print(f'sol: \\n{sol}\\n{sol_z}\\n')\n    print(f'obj: \\n{obj}\\n{obj_z}')\n\n    print()\n    rock_paper_scissors_cvxopt()\n    print()\n    rock_paper_scissors_cvxpy()\n", "meta": {"hexsha": "bcdb0a185232c6fcc586fefad1ef5ba6313b892c", "size": 6448, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "fredwangwang/linear-programming-example", "max_stars_repo_head_hexsha": "0cc9354923d3b24ca5c7877819b9d35d0b7c4ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-20T06:58:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T06:58:16.000Z", "max_issues_repo_path": "main.py", "max_issues_repo_name": "fredwangwang/linear-programming-example", "max_issues_repo_head_hexsha": "0cc9354923d3b24ca5c7877819b9d35d0b7c4ec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "fredwangwang/linear-programming-example", "max_forks_repo_head_hexsha": "0cc9354923d3b24ca5c7877819b9d35d0b7c4ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3858267717, "max_line_length": 104, "alphanum_fraction": 0.5105459057, "include": true, "reason": "import numpy,import cvxpy", "num_tokens": 2293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632275178341, "lm_q2_score": 0.9073122307591682, "lm_q1q2_score": 0.8636371483368278}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul  8 16:55:51 2021\n\n@author: alessandro\n\"\"\"\n\nimport math\nimport numpy as np\nimport scipy as sp\nimport scipy.linalg as spl\n\n# a)\n\ndef lu_nopivot(A):\n    m, n = A.shape\n    U = A.copy()\n    for k in range(n - 1):\n        if U[k, k] == 0:\n            return [], [], False\n        for i in range(k + 1, n):\n            U[i, k] /= U[k, k]\n            for j in range(k + 1, n):\n                U[i, j] -= U[i, k] * U[k, j]\n    L = np.tril(U, -1) + np.eye(n)\n    U = np.triu(U)\n    return L, U, True\n\n# b)\ndef solve_u(U, b):\n    m, n = U.shape\n    x = np.zeros((n, 1))\n    for i in range(n - 1, -1, -1):\n        s = np.dot(U[i, i + 1:], x[i + 1:])\n        x[i] = (b[i] - s) / L[i, i]\n    return x, True\n\n# c)\ndef solve_l(L, b):\n    m, n = L.shape\n    x = np.zeros((n, 1))\n    for i in range(n):\n        s = np.dot(L[i, :i], x[:i])\n        x[i] = (b[i] - s) / L[i, i]\n    return x, True\n\n# d)\n\ndef lu_solve(L, U, b):\n    y, flag = solve_l(L, b)\n    return solve_u(U, y)\n\ndef lulu_solve(L,U,b):\n    #Soluzione del sistema lineare A**2 x= c che equivale a L U L U x =b\n    y3, flag = solve_l(L, b)\n    y2, flag = solve_u(U, y3)\n    y1, flag = solve_l(L, y2)\n    x, flag = solve_u(U, y1)\n    return x\n\nfor n in range(5, 11):\n    A = spl.pascal(n)\n    b = np.dot(A.transpose(), np.ones((n, 1)))\n    c = np.dot(np.dot(A, A), np.ones((n, 1)))\n    \n    # (A^T)x=b\n    L, U, flag = lu_nopivot(A.transpose())\n    x1 = lu_solve(L, U, b)[0].transpose()\n    print(f\"n = {n} => sistema 1 = {x1}\")\n    \n    # (A^2)x=c = LULUx=c\n    # Conviene fare LULUx=c invece che A^2x=b \n    # perchè A^2 è molto mal condizionata\n    x2 = lulu_solve(L, U, c).transpose()\n    xx2 = spl.solve(np.dot(A, A), c)\n    print(f\"n = {n} => sistema 2 = {xx2}\")\n    \n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "8bc916b601341fc8be0d1a4ca9dd2d9ced16f77d", "size": 1798, "ext": "py", "lang": "Python", "max_stars_repo_path": "esercitazioni/gennaio_15_2021.py", "max_stars_repo_name": "alemazzo/metodi_numerici", "max_stars_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-07-08T10:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T09:56:37.000Z", "max_issues_repo_path": "esercitazioni/gennaio_15_2021.py", "max_issues_repo_name": "alemazzo/metodi_numerici", "max_issues_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "esercitazioni/gennaio_15_2021.py", "max_forks_repo_name": "alemazzo/metodi_numerici", "max_forks_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4318181818, "max_line_length": 72, "alphanum_fraction": 0.4827586207, "include": true, "reason": "import numpy,import scipy", "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488964, "lm_q2_score": 0.907312217601206, "lm_q1q2_score": 0.8636371382901735}}
{"text": "#\t\n#\troot-newton-raphson.py\n#\tFinding root using Newton-Raphson method\n#\t\n#\tSparisoma Viridi | https://butiran.github.io/\n#\t\n#\tExecute: py root-newton-raphson.js\n#\t\n#\t20210131\n#\t1850 Start this program from root-bisection.py.\n#\t1954 Continue make test_function and its derivative.\n#\t2006 Test it and ok, also for SHOW_PROGRESS.\n#\t2009 Correct maxstep to maxstep-1 in while.\n#\t20210210\n#\t0527 Typo node --> py.\n#\t\n\n# Import necessary libraries\nimport numpy as np\n\n\n# Define a test function\ndef test_function(x):\n\ty3 = 0.01 * x * x * x\n\ty2 = -0.2192 * x * x\n\ty1 = 0.3056 * x\n\ty0 = 1.568\n\ty = y3 + y2 + y1 + y0\n\treturn y\n\n\n# Define derivative of the test function\ndef derivative_test_function(x):\n\ty2 = 3 * 0.01 * x * x\n\ty1 = 2 * -0.2192 * x\n\ty0 = 0.3056\n\ty = y2 + y1 + y0\n\treturn y\n\n\n# Define input\nf = test_function\ndfdx = derivative_test_function\nxinit = 2\neps = 1E-10\nn = 0\nmaxstep = 40\n\n# Define default message and parameter\nxroot = \"not found\"\nSHOW_PROGRESS = False\n\n# Do iteration\nNstep = 0\nx = []\nx.append(xinit)\nfroot = np.abs(f(x[n]))\n\nwhile froot > eps and n < maxstep - 1:\n\tx.append(x[n] - f(x[n]) / dfdx(x[n]))\n\t\n\tfroot = np.abs(f(x[n+1]))\n\tif froot < eps:\n\t\txroot = x[n+1]\n\t\n\tif SHOW_PROGRESS:\n\t\tif n == 0:\n\t\t\tfn = f(x[n])\n\t\t\tprint(\"n\\tx\\tf(x)\")\n\t\t\tprint(n, x[n], f(x[n]), sep=\"\\t\")\n\t\tprint(n+1, x[n+1], f(x[n+1]), sep=\"\\t\") \n\t\n\tn += 1\n\nNstep = n+1\n\nif SHOW_PROGRESS:\n\tprint()\n\n# Display result\nprint(\"f(x)  0.01x^3 - 0.2192x^2 + 0.3056x + 1.568\");\nprint(\"xinit \", xinit, sep=\"\")\nprint(\"ε     \", eps, sep=\"\")\nprint(\"Nstep \", Nstep, sep=\"\")\nprint(\"xroot \", xroot, sep=\"\")\n", "meta": {"hexsha": "a28b8f522eb2ca2a23c13b9ebe0a07870ef788dc", "size": 1583, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/py/fi3201/root/root-newton-raphson.py", "max_stars_repo_name": "butiran/butiran.github.io", "max_stars_repo_head_hexsha": "bf99f55819a140190e5bda8f9675109ef607eb9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/py/fi3201/root/root-newton-raphson.py", "max_issues_repo_name": "butiran/butiran.github.io", "max_issues_repo_head_hexsha": "bf99f55819a140190e5bda8f9675109ef607eb9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-08T13:57:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-08T14:18:05.000Z", "max_forks_repo_path": "src/py/fi3201/root/root-newton-raphson.py", "max_forks_repo_name": "butiran/butiran.github.io", "max_forks_repo_head_hexsha": "bf99f55819a140190e5bda8f9675109ef607eb9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-08T13:54:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-08T13:54:23.000Z", "avg_line_length": 18.4069767442, "max_line_length": 54, "alphanum_fraction": 0.6222362603, "include": true, "reason": "import numpy", "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.9196425388861785, "lm_q1q2_score": 0.8635671656079262}}
{"text": "# means two successive elements\r\n\r\n# [1, 2, 3, 4], the discrete difference would be \r\n# [2 - 1, 3 - 2, 4 - 3] = [1, 1, 1]\r\n\r\n# diff()\r\n\r\nimport numpy as np \r\n\r\narr = np.array([10, 15, 25, 5])\r\n\r\nnewarr = np.diff(arr)\r\n\r\nprint(newarr)\r\n\r\n\"\"\"\r\nWe can perform this operation repeatedly by giving parameter n.\r\nE.g. for [1, 2, 3, 4], the discrete difference \r\nwith n = 2 would be [2-1, 3-2, 4-3] = [1, 1, 1] , then, \r\nsince n=2, we will do it once more, \r\nwith the new result: [1-1, 1-1] = [0, 0] \r\n\"\"\"\r\nnewarr = np.diff(arr, n = 2)\r\n\r\nprint(newarr)", "meta": {"hexsha": "1050889b5d5d2f99e7453a61216cca77481f776e", "size": 545, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_differences.py", "max_stars_repo_name": "khinthandarkyaw98/Python_Practice", "max_stars_repo_head_hexsha": "9b431129c79315a57dae81048a22bf85c4b5132c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy_differences.py", "max_issues_repo_name": "khinthandarkyaw98/Python_Practice", "max_issues_repo_head_hexsha": "9b431129c79315a57dae81048a22bf85c4b5132c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy_differences.py", "max_forks_repo_name": "khinthandarkyaw98/Python_Practice", "max_forks_repo_head_hexsha": "9b431129c79315a57dae81048a22bf85c4b5132c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8, "max_line_length": 64, "alphanum_fraction": 0.5743119266, "include": true, "reason": "import numpy", "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.9196425300765949, "lm_q1q2_score": 0.8635671636126127}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nEuropean call option by Monte Carlo simulation \n\ntest for vectorized calculation\n\n@author: Minhyun Yoo\n\"\"\"\nimport time\nimport numpy as np\nfrom math import exp, sqrt, log\nfrom scipy import stats\n\ndef exc_call(S0, E, T, r, sig):\n    d1 = (log(S0/E) + (r + 0.5*sig**2)*T) / (sig*sqrt(T));\n    d2 = d1 - sig * sqrt(T);\n\n    call = ( S0 * stats.norm.cdf(d1, 0.0, 1.0) \n        - E * exp(-r * T) * stats.norm.cdf(d2, 0.0, 1.0) )\n\n    print 'Exact call Price : %.5f' % call\n    \ndef mc_call(S0, E, T, r, sig, numSim, numStep):\n    dt = T / numStep;\n    t0 = time.clock();\n    z = np.random.normal(size = [numSim, numStep]);\n    s = S0 * np.ones([numSim]);\n    # vectorized calculation\n    for j in xrange(numStep):\n        s[:] = s[:] * np.exp((r - 0.5*sig**2)*dt + sig*sqrt(dt)*z[:, j]);\n    payoff = np.maximum(s - E, 0);\n    call = exp(-r * T) * np.mean(payoff);\n    t1 = time.clock();\n    del z;\n    \n    print 'Monte Carlo Call Price : %.5f' % call\n    print 'CPU time in Python(sec) : %.4f' % (t1-t0)\n    \ndef mc_call_var_reduc(S0, E, T, r, sig, numSim, numStep):\n    dt = T / numStep;\n    t0 = time.clock();\n    z = np.random.normal(size = [numSim, numStep]);\n    sp = S0 * np.ones([numSim]);\n    sm = S0 * np.ones([numSim]);\n    for j in xrange(numStep):\n        sp[:] = sp[:] * np.exp((r - 0.5*sig**2)*dt + sig*sqrt(dt)*z[:, j]);\n        sm[:] = sm[:] * np.exp((r - 0.5*sig**2)*dt - sig*sqrt(dt)*z[:, j]);\n    payoff1 = np.maximum(sp - E, 0);\n    payoff2 = np.maximum(sm - E, 0);\n    call = exp(-r * T) * np.mean(0.5*(payoff1+payoff2));\n    t1 = time.clock();\n    del z;\n    \n    print 'Monte Carlo Call Price : %.5f' % call\n    print 'CPU time in Python(sec) : %.4f' % (t1-t0)\n\nS0 = 100.0; # underlying price\nE = 100.0; # strike price\nT = 1.0; # maturity\nr = 0.03; # riskless interest rate\nsig = 0.3; # volatility\nns = 100000;  # # of simulations\nnStep = 1; # # of time steps (In this example, nStep does not have to over 1 due to European option pricing.)\n\n# functions call\n\nexc_call(S0, E, T, r, sig); # exact solution\n\nmc_call(S0, E, T, r, sig, ns, nStep); # Monte Carlo simulation\n\nmc_call_var_reduc(S0, E, T, r, sig, ns, nStep);\n", "meta": {"hexsha": "b991e02812dd9a57eb1269e435f6b3031c2d2051", "size": 2165, "ext": "py", "lang": "Python", "max_stars_repo_path": "call/mc_call.py", "max_stars_repo_name": "ymh1989/monte_calro_python", "max_stars_repo_head_hexsha": "21cdfb2936626b3e1615d7e3cc72bd6eb31b182a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-01-09T03:40:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T07:47:21.000Z", "max_issues_repo_path": "call/mc_call.py", "max_issues_repo_name": "ymh1989/monte_calro_python", "max_issues_repo_head_hexsha": "21cdfb2936626b3e1615d7e3cc72bd6eb31b182a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "call/mc_call.py", "max_forks_repo_name": "ymh1989/monte_calro_python", "max_forks_repo_head_hexsha": "21cdfb2936626b3e1615d7e3cc72bd6eb31b182a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-03-31T03:46:01.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-31T03:46:01.000Z", "avg_line_length": 30.0694444444, "max_line_length": 109, "alphanum_fraction": 0.5639722864, "include": true, "reason": "import numpy,from scipy", "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452772, "lm_q2_score": 0.9032942106088967, "lm_q1q2_score": 0.8635324212945409}}
{"text": "import numpy as np\nimport scipy.sparse as spar\nimport scipy.linalg as la\nfrom scipy.sparse import linalg as sla\n\ndef to_matrix(filename,n):\n    '''\n    Return the nxn adjacency matrix described by datafile.\n    INPUTS:\n    datafile (.txt file): A .txt file describing a directed graph. Lines\n        describing edges should have the form '<from node>\\t<to node>\\n'.\n        The file may also include comments.\n    n (int): The number of nodes in the graph described by datafile\n    RETURN:\n        Return a SciPy sparse `dok_matrix'.\n    '''\n    adj = spar.dok_matrix((n,n))\n    with open(filename, 'r') as myfile:\n        for line in myfile:\n            line = line.strip().split()\n            try:\n                x,y = int(line[0]),int(line[1])\n                adj[x,y] = 1\n            except:\n                continue\n    return adj\n\ndef calculateK(A,N):\n    '''\n    Compute the matrix K as described in the lab.\n    Input:\n        A (array): adjacency matrix of an array\n        N (int): the datasize of the array\n    Return:\n        K (array)\n    '''\n    n = A.shape[0]\n    D = np.zeros(n)\n    for row in range(n):\n        D[row] = A[row].sum()\n    for i in range(n):\n        if D[i] == 0:\n            D[i] = n\n            A[i] = np.ones(n)\n    K = (A.T/D)\n    return K[:N,:N]\n\ndef iter_solve(adj, N=None, d=.85, tol=1E-5):\n    '''\n    Return the page ranks of the network described by `adj`.\n    Iterate through the PageRank algorithm until the error is less than `tol'.\n    Inputs:\n    adj - A NumPy array representing the adjacency matrix of a directed graph\n    N (int) - Restrict the computation to the first `N` nodes of the graph.\n            Defaults to N=None; in this case, the entire matrix is used.\n    d     - The damping factor, a float between 0 and 1.\n            Defaults to .85.\n    tol  - Stop iterating when the change in approximations to the solution is\n        less than `tol'. Defaults to 1E-5.\n    Returns:\n    The approximation to the steady state.\n    '''\n    if N is None:\n        N = adj.shape[1]\n    pt = np.ones((N,1))/N    \n    K = calculateK(adj,N)\n    pt1 = d*np.dot(K,pt) + ((1.-d)/N)*np.ones((N,1))\n    while la.norm(pt1-pt) > tol:\n        pt = pt1\n        pt1 = d*np.dot(K,pt) + ((1.-d)/N)*np.ones((N,1))\n    return pt1\n\ndef eig_solve( adj, N=None, d=.85):\n    '''\n    Return the page ranks of the network described by `adj`. Use the\n    eigenvalue solver in \\li{scipy.linalg} to calculate the steady state\n    of the PageRank algorithm\n    Inputs:\n    adj - A NumPy array representing the adjacency matrix of a directed graph\n    N - Restrict the computation to the first `N` nodes of the graph.\n            Defaults to N=None; in this case, the entire matrix is used.\n    d     - The damping factor, a float between 0 and 1.\n            Defaults to .85.\n    Returns:\n    The approximation to the steady state.\n    '''\n    if N is None:\n        N = adj.shape[1]\n    K = calculateK(adj,N)\n    B = d*K + ((1.-d)/N)*np.ones((N,N))\n    evalues,evectors = la.eig(B)\n    i = np.argsort(evalues)[-1] #Find index of largest eigenvalue (which should be 1)\n    pt = (evectors[:,i].real)\n    pt = pt*1/pt.sum()\n    return pt\n    \ndef team_rank(filename='ncaa2013.csv'):\n    '''\n    Use your iterative PageRank solver to predict the rankings of the teams in\n    the given dataset of games.\n    The dataset should have two columns, representing winning and losing teams.\n    Each row represents a game, with the winner on the left, loser on the right.\n    Parse this data to create the adjacency matrix, and feed this into the\n    solver to predict the team ranks.\n    Inputs:\n    filename (optional) - The name of the dataset.\n    Returns:\n    ranks - A list of the ranks of the teams in order \"best\" to \"worst\"\n    teams - A list of the names of the teams, also in order \"best\" to \"worst\"\n    '''\n    # Create adj. matrix\n    teams = set()\n    wins = []\n    with open(filename, 'r') as f:\n        f.readline() #read the header\n        for line in f:\n            data = line.strip().split(',') #split on commas\n            teams.add(data[0])\n            teams.add(data[1])\n            wins.append(data)\n    n = len(teams)\n    team_list = list(teams)\n    team_number = dict()\n    for i, t in enumerate(team_list):\n        team_number[t] = i\n    adj = spar.dok_matrix((n,n)) #adjacency matrix\n    for match in wins:\n        win_number = team_number[match[0]]\n        lose_number = team_number[match[1]]\n        adj[lose_number,win_number] = 1\n    \n    # Solve for ranks\n    p = iter_solve(adj.todense(), d=0.7)\n    p = np.array(p).squeeze()\n    idx = np.argsort(p)[::-1]\n    n_out = 5\n    return [p[j] for j in idx[:n_out]], [team_list[j] for j in idx[:n_out]]\n    \ndef problemOne():\n    print to_matrix('datafile.txt',8).todense()\n\ndef problemTwo():\n    A = to_matrix('datafile.txt',8).todense()\n    print calculateK(A,8)\n\ndef problemThree():\n    A = to_matrix('datafile.txt',8).todense()\n    print iter_solve(A,N = 8)\n\ndef problemFour():\n    A = to_matrix('datafile.txt',8).todense()\n    a =iter_solve(A,N = 8)\n    b = eig_solve(A,N = 8)\n    print a\n    print eig_solve(A,N=8)\n\nif __name__ == '__main__':\n    print \"Testing 1\"\n    problemOne()\n    print \"Testing 2\"\n    problemTwo()\n    print \"Testing 3\"\n    problemThree()\n    print \"Testing 4\"\n    problemFour()\n    print \"Testing team rank\"\n    ranks, teams = team_rank()\n    print ranks\n    print teams", "meta": {"hexsha": "ede9fcaf9115f9ca35f1be57a5f0c60122fcb5e8", "size": 5388, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol1B/PageRank/solutions.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vol1B/PageRank/solutions.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vol1B/PageRank/solutions.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 31.8816568047, "max_line_length": 85, "alphanum_fraction": 0.6013363029, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993889, "lm_q2_score": 0.9032942080055512, "lm_q1q2_score": 0.863532419938623}}
{"text": "import numpy as np\n\n\ndef objective_function_F1(X):\n    # Sphere function (minimum at 0)\n    return - np.sum(X**2, axis=1)\n\n\ndef objective_function_F1a(X):\n    # Sphere function - modified\n    return - (X[:, 0]**2 + 9*X[:, 1]**2)\n\n\ndef objective_function_F1b(X):\n    # Sphere function - modified\n    return - (X[:, 0]**2 + 625*X[:, 1]**2)\n\n\ndef objective_function_F1c(X):\n    # Sphere function - modified\n    return - (X[:, 0]**2 + 2*X[:, 1]**2 - 2 * X[:, 0] * X[:, 1])\n\n\ndef objective_function_F6(X):\n    # Rastrigin function (minimum at 0)\n    return - 10.0 * X.shape[1] - np.sum(X**2, axis=1) + 10.0 * np.sum(np.cos(2 * np.pi * X), axis=1)\n\n\ndef objective_function_F7(X):\n    # Schwefel function (minimum at 420.9687)\n    # (REMARK: should be considered only on [-500, 500]^d, because there are better minima outside)\n    return - 418.9829 * X.shape[1] + np.sum(X * np.sin(np.sqrt(np.abs(X))), axis=1)\n\n\ndef objective_function_F8(X):\n    # Griewank function (minimum at 0)\n    return - 1 - np.sum(X**2 / 4000, axis=1) + np.prod(np.cos(X / np.sqrt(np.linspace(1, X.shape[1], X.shape[1]))), axis=1)\n", "meta": {"hexsha": "ac2f0dcdf3c90b7047fa71a0d9cf81e2fa70faa7", "size": 1099, "ext": "py", "lang": "Python", "max_stars_repo_path": "4/functions.py", "max_stars_repo_name": "iCarrrot/Evol-algs", "max_stars_repo_head_hexsha": "cb79440f0c5430b1d63a43acf2d64faed6db1b17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-18T11:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-18T11:31:03.000Z", "max_issues_repo_path": "list04/functions.py", "max_issues_repo_name": "Magikis/evolutional-algorithms", "max_issues_repo_head_hexsha": "51a51f9a0c7bca3731097160c40a96a7f40fa8f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "list04/functions.py", "max_forks_repo_name": "Magikis/evolutional-algorithms", "max_forks_repo_head_hexsha": "51a51f9a0c7bca3731097160c40a96a7f40fa8f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9210526316, "max_line_length": 123, "alphanum_fraction": 0.6132848044, "include": true, "reason": "import numpy", "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9840936078216782, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.8635192896899799}}
{"text": "import numpy as np\nimport scipy.linalg as la\n\n\n## Descompunere LU\n\n# Matricea dată la intrare\nA = np.array([\n    [2, -1, -2],\n    [4, 2, 0],\n    [0, -2, -1],\n], dtype=np.float64)\n\n\nA = np.array([\n    [1, 2, 3],\n    [4, 5, 6],\n    [7, 8, 10],\n], dtype=np.float64)\n\n\nN = A.shape[0]\nP = np.eye(N)\nL = np.zeros((N, N))\nU = np.copy(A)\n\npartial_pivot = True\n\nfor k in range(N - 1):\n    if partial_pivot:\n        # Găsesc indicele elementului de magnitudine maximă\n        index = k + np.argmax(np.abs(U[k:, k]))\n\n        # Pivotez\n        U[[k, index]] = U[[index, k]]\n        L[[k, index]] = L[[index, k]]\n\n        # Interschimb în permutare\n        P[[k, index]] = P[[index, k]]\n\n    # Selectez coloana pe care lucrez\n    ratios = U[k + 1:, k]\n\n    # Determin raportul pentru fiecare rând\n    ratios = ratios / U[k, k]\n\n    # Actualizez matricea inferior triunghiulară\n    L[k + 1:, k] = ratios\n\n    # Selectez rândul pe care vreau să-l actualizez\n    row = U[k, :]\n\n    # Înmulțesc fiecare raport cu primul rând\n    difference = np.outer(ratios, row)\n\n    # Actualizez matricea superior triunghiulară\n    U[k + 1:, :] -= difference\n\nL += np.eye(N)\n\nprint(\"L = \")\nprint(L)\nprint(\"U = \")\nprint(U)\nprint(\"L @ U = \")\nprint(L @ U)\nprint(\"P @ A = \")\nprint(P @ A)\nprint()\n\n\nb = np.array([[1, 2, 3]], dtype=np.float64).T\nprint(\"Rezolv pentru b = \", b.T)\n\n# Permut numerele din vector\nb = P @ b\n\n\ny = np.zeros(N)\n\n# Merg de la prima linie în jos,\n# și rezolv pe rând ecuațiile prin substituție\nfor i in range(0, N):\n    coefs = L[i, :i + 1]\n    values = y[:i + 1]\n\n    y[i] = (b[i] - coefs @ values) / L[i, i]\n\nprint(\"Obțin y = \", y)\n\n\nx = np.zeros(N)\n\n# Merg de la ultima linie în sus,\n# și rezolv pe rând ecuațiile prin substituție\nfor i in range(N - 1, -1, -1):\n    coefs = U[i, i + 1:]\n    values = x[i + 1:]\n\n    x[i] = (y[i] - coefs @ values) / U[i, i]\n\nprint(\"Obțin x = \", x)\nprint(\"Verificare: A @ x = \", A @ x)\n", "meta": {"hexsha": "815d882a40575605caac013fe31cdbe9b8e78b27", "size": 1908, "ext": "py", "lang": "Python", "max_stars_repo_path": "cn/laborator/lab6.py", "max_stars_repo_name": "FloaterTS/teme-fmi", "max_stars_repo_head_hexsha": "624296d3b3341f1c18fb26768e361ce2e1faa68c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2020-03-17T10:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:40:30.000Z", "max_issues_repo_path": "cn/laborator/lab6.py", "max_issues_repo_name": "florinalexandrunecula/teme-fmi", "max_issues_repo_head_hexsha": "b4d7a416a5ca71b76d66b9407ad2b8ee2af9301e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cn/laborator/lab6.py", "max_forks_repo_name": "florinalexandrunecula/teme-fmi", "max_forks_repo_head_hexsha": "b4d7a416a5ca71b76d66b9407ad2b8ee2af9301e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2020-01-22T11:39:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T00:19:06.000Z", "avg_line_length": 18.3461538462, "max_line_length": 59, "alphanum_fraction": 0.5545073375, "include": true, "reason": "import numpy,import scipy", "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611643025387, "lm_q2_score": 0.8991213826762114, "lm_q1q2_score": 0.8634812579162349}}
{"text": "# first skill: generate random numbers following particular distributions\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.stats import norm\nplt.rcParams['mathtext.fontset'] = 'cm'\n\n# Method 1: instance of the random state class\nrandom_seed = 31416\nrandom_state = np.random.RandomState(seed=random_seed)\nnumber_samples = 1000\ngaussian_sample = random_state.normal(loc=0, scale=2, size=number_samples)\n\n# ground truth gaussian\ny = norm(loc=0, scale=2)\nx = np.linspace(y.ppf([0.01])[0], y.ppf([0.99])[0], 100)\n\nwith plt.xkcd():\n    plt.figure(figsize=(8, 6))\n    plt.hist(gaussian_sample, bins=10, histtype='step', density=True)\n    plt.plot(x, y.pdf(x))\n    plt.title(r'$\\mu = {} \\quad \\sigma = {}$'.format(0, 2))\n    plt.xlabel(r'$X$')\n    plt.ylabel(r'$P(X)$')\n    plt.savefig('random_samples.png', dpi=128)\n    plt.close()\n\n\n# Method 2: Inverse transform method\n# set up functions to measure pdf, cdf and icdf\ndef exponential_pdf(x_array, lambda_parameter=1):\n    \"\"\"PDF of exponential distribution\"\"\"\n    return lambda_parameter*np.exp(-lambda_parameter * x_array)\n\n\ndef exponential_cdf(x_array, lambda_parameter=1):\n    \"\"\"CDF of exponential distribution.\"\"\"\n    return 1 - np.exp(-lambda_parameter * x_array)\n\n\ndef exponential_icdf(p, lambda_parameter=1):\n    \"\"\"Inverse CDF of exponential distribution: quantile estimation\"\"\"\n    return -np.log(1-p)/lambda_parameter\n\n\n# generate instance of the distribution with default lambda parameter\n# auxiliar arrays to manipulate\nxi = np.linspace(0, 4, 100)\nyi = np.linspace(0, 1, 100)\n\n# visual inspection\nwith plt.xkcd():\n    plt.figure(figsize=(12, 6))\n    # left panel\n    plt.subplot(121)\n    # plot the cumulative distribution\n    plt.plot(xi, exponential_cdf(xi))\n    plt.axis([0, 4, 0, 1])\n    # highlight values at cdf points of 50% and 80% (say)\n    for q in [0.5, 0.8]:\n        plt.arrow(0, q, exponential_icdf(q) - 0.1, 0, head_width=0.05, head_length=0.1, fc='b', ec='b')\n        plt.arrow(exponential_icdf(q), q, 0, -q + 0.1, head_width=0.1, head_length=0.05, fc='b', ec='b')\n    # labels\n    plt.ylabel('1: Generate a (0,1) uniform PRNG')\n    plt.xlabel('2: Find the inverse CDF')\n    plt.title('Inverse transform method')\n    # right panel\n    plt.subplot(122)\n    # samples from the uniform distribution\n    number_uniform_samples = 10000\n    u = np.random.random(number_uniform_samples)\n    # get the inverse cumulative distribution\n    v = exponential_icdf(u)\n    # visualise the distribution from the samples\n    plt.hist(v, histtype='step', bins=100, density=True, linewidth=2)\n    # compare with real pdf\n    plt.plot(x, exponential_pdf(x), linewidth=2)\n    plt.axis([0, 4, 0, 1])\n    plt.title('Histogram of exponential PRNGs')\n    plt.savefig('random_inverse_transform.png', dpi=128)\n    plt.close()\n", "meta": {"hexsha": "b5984e440ee20e8e15a0caf0bccced1cc6a6e432", "size": 2784, "ext": "py", "lang": "Python", "max_stars_repo_path": "01_random_generation.py", "max_stars_repo_name": "luisfciencias/intro-probabilistic-programming", "max_stars_repo_head_hexsha": "2918c67a1b45cfcd91387b71095c768e059a2d80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "01_random_generation.py", "max_issues_repo_name": "luisfciencias/intro-probabilistic-programming", "max_issues_repo_head_hexsha": "2918c67a1b45cfcd91387b71095c768e059a2d80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:43:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:10:38.000Z", "max_forks_repo_path": "01_random_generation.py", "max_forks_repo_name": "luisfciencias/intro-probabilistic-programming", "max_forks_repo_head_hexsha": "2918c67a1b45cfcd91387b71095c768e059a2d80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3703703704, "max_line_length": 104, "alphanum_fraction": 0.6896551724, "include": true, "reason": "import numpy,from scipy", "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.8991213853793452, "lm_q1q2_score": 0.8634812554119403}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n# In[1]:\nimport numpy as np  \nimport pandas as pd  \nfrom pandas_datareader import data as web  \nfrom scipy.stats import norm \nimport matplotlib.pyplot as plt  \nget_ipython().run_line_magic('matplotlib', 'inline')\n# In[2]:\ndata = pd.read_csv('D:/Python/PG_2007_2017.csv', index_col = 'Date')\n# In[3]:\nlog_returns = np.log(1 + data.pct_change())\n# In[4]:\nlog_returns.tail()\n# In[5]:\ndata.plot(figsize=(10, 6));\n# In[6]:\nr = 0.025\n# In[7]:\nstdev = log_returns.std() * 250 ** 0.5\nstdev\n# In[8]:\ntype(stdev)\n# In[9]:\nstdev = stdev.values\nstdev\n# In[10]:\nT = 1.0 \nt_intervals = 250 \ndelta_t = T / t_intervals  \niterations = 10000  \n# In[11]:\nZ = np.random.standard_normal((t_intervals + 1, iterations))  \nS = np.zeros_like(Z) \nS0 = data.iloc[-1]  \nS[0] = S0 \nfor t in xrange(1, t_intervals + 1):\n    S[t] = S[t-1] * np.exp((r - 0.5 * stdev ** 2) * delta_t + stdev * delta_t ** 0.5 * Z[t])\n# In[12]:\nS\n# In[13]:\nS.shape\n# In[14]:\nplt.figure(figsize=(10, 6))\nplt.plot(S[:, :10]);\n# ******\n# In[15]:\np = np.maximum(S[-1] - 110, 0)\n# In[16]:\np\n# In[17]:\np.shape\n# In[18]:\nC = np.exp(-r * T) * np.sum(p) / iterations\nC  \n", "meta": {"hexsha": "1226a2f2c855a79ed09c7c27835a31444f98b451", "size": 1148, "ext": "py", "lang": "Python", "max_stars_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_110-MC-EulerDiscretization-PartII-Lecture_CSV.py", "max_stars_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_stars_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-04T11:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-10T15:36:42.000Z", "max_issues_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_110-MC-EulerDiscretization-PartII-Lecture_CSV.py", "max_issues_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_issues_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-03-30T16:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:37:21.000Z", "max_forks_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-17_110-MC-EulerDiscretization-PartII-Lecture_CSV.py", "max_forks_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_forks_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T11:26:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T11:26:16.000Z", "avg_line_length": 20.1403508772, "max_line_length": 92, "alphanum_fraction": 0.6106271777, "include": true, "reason": "import numpy,from scipy", "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611631680358, "lm_q2_score": 0.8991213725394589, "lm_q1q2_score": 0.8634812471612355}}
{"text": "# Cox-Ross-Rubinstein for Eurpean and American style options\r\n\r\n#Code is straightforward and only numpy is required\r\n\r\n\r\nimport numpy as np\r\n\r\n#S        -> Spot price of the underlying\r\n#K        -> Strike price for the option\r\n#sigma    -> Annualized volatility of the underlying\r\n#r        -> continously compounded risk-free rate\r\n#T        -> option's time to expiration in years\r\n#steps    -> number of steps to be calculated in the tree\r\n#q        -> continously compounded dividend yield (default is 0)\r\n#call     -> specify put or call option (default is call)\r\n#american -> specify if early exercise (default is true, false for European style)\r\n\r\n\r\ndef crr(S,K,sigma,r,T,steps,q=0,call=True,american=True): \r\n    # Assigning paramter values\r\n    dt=T/steps\r\n    u=np.exp(dt**0.5 *sigma)\r\n    d=np.exp(-(dt**0.5 *sigma))\r\n    p=(np.exp((r-q)*dt)-d)/(u-d)\r\n    \r\n    #Pre-allocating the underlying's price array\r\n    pricetree=np.zeros([steps+1,steps+1],dtype='float64')\r\n    pricetree[0,0]=S\r\n    \r\n    #The tree is calculated for the underlying's price\r\n    for i in range(1,steps+1):\r\n       pricetree[:i,i]=pricetree[:i,i-1]*u\r\n       pricetree[i,i]=pricetree[i-1,i-1]*d\r\n       \r\n    #Tree for the option value\r\n    optiontree=np.zeros([steps+1,steps+1],dtype='float64')\r\n    if call:\r\n        optiontree[:,steps]=np.maximum(pricetree[:,-1 ]-K,0)\r\n    else:\r\n         optiontree[:,steps]=np.maximum(K-pricetree[:,-1 ],0)\r\n    \r\n    for i in range(steps-1,-1,-1):\r\n        optiontree[:i+1,i]=np.exp(-(r*dt))*(optiontree[:i+1,i+1]*p+\\\r\n                                            (1-p)*optiontree[1:i+2:1,i+1])\r\n        #Early exercise    \r\n        if american :\r\n            if call :\r\n                optiontree[:i+1,i]=np.maximum( pricetree[:i+1,i]-K, \\\r\n                                       optiontree[:i+1,i])\r\n            else:\r\n                optiontree[:i+1,i]=np.maximum(K-pricetree[:i+1,i], \\\r\n                                              optiontree[:i+1,i])\r\n                    \r\n    #Finally, the function outputs the option value, and the price and \r\n    # option value trees.              \r\n    return optiontree[0,0], pricetree, optiontree\r\n    \r\n\r\n\r\n                                        \r\n##### Using the function with some given parameters ######\r\n    \r\nS=50;\r\nK=30;\r\nsigma= 0.3;\r\nr=0.05;\r\nT=1;\r\nsteps=200;\r\n\r\n\r\nprice,pricearray,optionarray=crr(S,K,sigma,r,T,steps)\r\n\r\n\r\n    \r\n", "meta": {"hexsha": "fc8803c14fdfe494c5f7ce7fe86d8ecedfb347ce", "size": 2412, "ext": "py", "lang": "Python", "max_stars_repo_path": "CoxRossRubinstein.py", "max_stars_repo_name": "xdw15/Cox-Ross-Rubenstein-for-American-style-options-", "max_stars_repo_head_hexsha": "58d9f3afbf2a9c28e9da4d16757c69f241b231da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-12T06:20:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T15:41:08.000Z", "max_issues_repo_path": "CoxRossRubinstein.py", "max_issues_repo_name": "xdw15/Cox-Ross-Rubenstein-for-American-style-options-", "max_issues_repo_head_hexsha": "58d9f3afbf2a9c28e9da4d16757c69f241b231da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoxRossRubinstein.py", "max_forks_repo_name": "xdw15/Cox-Ross-Rubenstein-for-American-style-options-", "max_forks_repo_head_hexsha": "58d9f3afbf2a9c28e9da4d16757c69f241b231da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.16, "max_line_length": 83, "alphanum_fraction": 0.5493366501, "include": true, "reason": "import numpy", "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611643025386, "lm_q2_score": 0.8991213678089741, "lm_q1q2_score": 0.8634812436383175}}
{"text": "\"\"\"\nCorrelation based distances and various modifications (angular, absolute, squared) described in Cornell lecture notes:\nCodependence: https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3512994&download=yes\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.spatial.distance import squareform, pdist\n\n\n# pylint: disable=invalid-name\n\n\ndef angular_distance(x: np.array, y: np.array) -> float:\n    \"\"\"\n    Returns angular distance between two vectors. Angular distance is a slight modification of Pearson correlation which\n    satisfies metric conditions.\n\n    Formula used for calculation:\n\n    Ang_Distance = (1/2 * (1 - Corr))^(1/2)\n\n    Read Cornell lecture notes for more information about angular distance:\n    https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3512994&download=yes.\n\n    :param x: (np.array/pd.Series) X vector.\n    :param y: (np.array/pd.Series) Y vector.\n    :return: (float) Angular distance.\n    \"\"\"\n\n    corr_coef = np.corrcoef(x, y)[0][1]\n    return np.sqrt(0.5 * (1 - corr_coef))\n\n\ndef absolute_angular_distance(x: np.array, y: np.array) -> float:\n    \"\"\"\n    Returns absolute angular distance between two vectors. It is a modification of angular distance where the absolute\n    value of the Pearson correlation coefficient is used.\n\n    Formula used for calculation:\n\n    Abs_Ang_Distance = (1/2 * (1 - abs(Corr)))^(1/2)\n\n    Read Cornell lecture notes for more information about absolute angular distance:\n    https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3512994&download=yes.\n\n    :param x: (np.array/pd.Series) X vector.\n    :param y: (np.array/pd.Series) Y vector.\n    :return: (float) Absolute angular distance.\n    \"\"\"\n\n    corr_coef = np.corrcoef(x, y)[0][1]\n    return np.sqrt(0.5 * (1 - abs(corr_coef)))\n\n\ndef squared_angular_distance(x: np.array, y: np.array) -> float:\n    \"\"\"\n    Returns squared angular distance between two vectors. It is a modification of angular distance where the square of\n    Pearson correlation coefficient is used.\n\n    Formula used for calculation:\n\n    Squared_Ang_Distance = (1/2 * (1 - (Corr)^2))^(1/2)\n\n    Read Cornell lecture notes for more information about squared angular distance:\n    https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3512994&download=yes.\n\n    :param x: (np.array/pd.Series) X vector.\n    :param y: (np.array/pd.Series) Y vector.\n    :return: (float) Squared angular distance.\n    \"\"\"\n\n    corr_coef = np.corrcoef(x, y)[0][1]\n    return np.sqrt(0.5 * (1 - corr_coef ** 2))\n\n\ndef distance_correlation(x: np.array, y: np.array) -> float:\n    \"\"\"\n    Returns distance correlation between two vectors. Distance correlation captures both linear and non-linear\n    dependencies.\n\n    Formula used for calculation:\n\n    Distance_Corr[X, Y] = dCov[X, Y] / (dCov[X, X] * dCov[Y, Y])^(1/2)\n\n    dCov[X, Y] is the average Hadamard product of the doubly-centered Euclidean distance matrices of X, Y.\n\n    Read Cornell lecture notes for more information about distance correlation:\n    https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3512994&download=yes.\n\n    :param x: (np.array/pd.Series) X vector.\n    :param y: (np.array/pd.Series) Y vector.\n    :return: (float) Distance correlation coefficient.\n    \"\"\"\n\n    x = x[:, None]\n    y = y[:, None]\n\n    x = np.atleast_2d(x)\n    y = np.atleast_2d(y)\n\n    a = squareform(pdist(x))\n    b = squareform(pdist(y))\n\n    A = a - a.mean(axis=0)[None, :] - a.mean(axis=1)[:, None] + a.mean()\n    B = b - b.mean(axis=0)[None, :] - b.mean(axis=1)[:, None] + b.mean()\n\n    d_cov_xx = (A * A).sum() / (x.shape[0] ** 2)\n    d_cov_xy = (A * B).sum() / (x.shape[0] ** 2)\n    d_cov_yy = (B * B).sum() / (x.shape[0] ** 2)\n\n    coef = np.sqrt(d_cov_xy) / np.sqrt(np.sqrt(d_cov_xx) * np.sqrt(d_cov_yy))\n\n    return coef\n\n\ndef kullback_leibler_distance(corr_a, corr_b):\n    \"\"\"\n    Returns the Kullback-Leibler distance between two correlation matrices, all elements must be positive.\n\n    Formula used for calculation:\n\n    kullback_leibler_distance[X, Y] = 0.5 * ( Log( det(Y) / det(X) ) + tr((Y ^ -1).X - n )\n\n    Where n is the dimension space spanned by X.\n\n    Read Don H. Johnson's research paper for more information on Kullback-Leibler distance:\n    `<https://scholarship.rice.edu/bitstream/handle/1911/19969/Joh2001Mar1Symmetrizi.PDF>`_\n\n    :param corr_a: (np.array/pd.Series/pd.DataFrame) Numpy array of the first correlation matrix.\n    :param corr_b: (np.array/pd.Series/pd.DataFrame) Numpy array of the second correlation matrix.\n    :return: (np.float64) the Kullback-Leibler distance between the two matrices.\n    \"\"\"\n\n    # Check if input type is pd.DataFrame\n    if isinstance(corr_a, pd.DataFrame) and isinstance(corr_b, pd.DataFrame):\n        corr_a = corr_a.to_numpy()\n        corr_b = corr_b.to_numpy()\n\n    n = corr_a.shape[0]\n    dist = 0.5 * (np.log(np.linalg.det(corr_b) / np.linalg.det(corr_a)) +\n                  np.trace(np.linalg.inv(corr_b).dot(corr_a)) - n)\n\n    return dist\n\n\ndef norm_distance(matrix_a, matrix_b, r_val=2):\n    \"\"\"\n    Returns the normalized distance between two matrices.\n\n    This function is a wrap for numpy's linear algebra method (numpy.linalg.norm).\n    Link to documentation: `<https://numpy.org/doc/stable/reference/generated/numpy.linalg.norm.html>`_.\n\n    Formula used to normalize matrix:\n\n    norm_distance[X, Y] = sum( abs(X - Y) ^ r ) ^ 1/r\n\n    Where r is a parameter. r=1 City block(L1 norm), r=2 Euclidean distance (L2 norm),\n    r=inf Supermum (L_inf norm). For values of r < 1, the result is not really a mathematical ‘norm’.\n\n    :param matrix_a: (np.array/pd.Series/pd.DataFrame) Array of the first matrix.\n    :param matrix_b: (np.array/pd.Series/pd.DataFrame) Array of the second matrix.\n    :param r_val: (int/str) The r value of the normalization formula. (``2`` by default, Any Integer)\n    :return: (np.float64) The Euclidean distance between the two matrices.\n    \"\"\"\n\n    # Check if input type is pd.DataFrame\n    if isinstance(matrix_a, pd.DataFrame) and isinstance(matrix_b, pd.DataFrame):\n        matrix_a = matrix_a.to_numpy()\n        matrix_b = matrix_b.to_numpy()\n\n    return np.linalg.norm(matrix_b - matrix_a, r_val)\n", "meta": {"hexsha": "4c402784a56405940677bc2ff0b47de8c6859177", "size": 6140, "ext": "py", "lang": "Python", "max_stars_repo_path": "datascience/codependence/correlation.py", "max_stars_repo_name": "skyliquid22/datascience", "max_stars_repo_head_hexsha": "24c8e505cbdfa3ebfc9ed00941d06b42194629e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "datascience/codependence/correlation.py", "max_issues_repo_name": "skyliquid22/datascience", "max_issues_repo_head_hexsha": "24c8e505cbdfa3ebfc9ed00941d06b42194629e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "datascience/codependence/correlation.py", "max_forks_repo_name": "skyliquid22/datascience", "max_forks_repo_head_hexsha": "24c8e505cbdfa3ebfc9ed00941d06b42194629e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4913294798, "max_line_length": 120, "alphanum_fraction": 0.6806188925, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361156361018, "lm_q2_score": 0.8991213732152424, "lm_q1q2_score": 0.8634812416898967}}
{"text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\npath='ex1data1.txt'\ndata=pd.read_csv(path,header=None,names=['Population','Profits'])\ndata.head()\ndata.describe()\n\ndata.plot(kind='scatter',x='Population',y='Profits',figsize=(12,8))\nplt.show()\n\ndef computeCost(X,y,theta):\n    inner=np.power(((X*theta.T)-y),2)\n    return np.sum(inner)/(2*len(X))\ndata.insert(0,'Ones',1)\ncols=data.shape[1]#shape0是列数，shape1是行数\nX=data.iloc[:,0:cols-1]\ny=data.iloc[:,cols-1:cols]\n\nX=np.matrix(X.values)\ny=np.matrix(y.values)\ntheta=np.matrix(np.array([0,0]))\n\ncomputeCost(X,y,theta)\n\n#batch gradient decent批量梯度下降\ndef gradientDescent(X,y,theta,alpha,iters):\n    temp=np.matrix(np.zeros(theta.shape))#ravel展平到一行\n    parameters=int(theta.ravel().shape[1])#有几个theta\n    cost=np.zeros(iters)#储存每次迭代的cost\n    \n    for i in range(iters):\n        error=(X*theta.T)-y\n        for j in range(parameters):\n            term=np.multiply(error,X[:,j])\n            temp[0,j]=theta[0,j]-((alpha/len(X))*np.sum(term))\n        theta=temp\n        cost[i]=computeCost(X,y,theta)        \n    return theta,cost\nalpha=0.01\niters=1000\ng,cost=gradientDescent(X,y,theta,alpha,iters)\ng;cost#g就是模型的theta值\ncomputeCost(X,y,g)#训练模型的代价\n#绘图看拟合情况\nx=np.linspace(data.Population.min(),data.Population.max(),100)\nf=g[0,0]+(g[0,1]*x)#y=ax+b\nfig,ax=plt.subplots(figsize=(12,8))\nax.plot(x,f,'r',label='Prediction')\nax.scatter(data.Population,data.Profits,label='Traning Data')\nax.legend(loc=2)\nax.set_xlabel('Population')\nax.set_ylabel('Profits')\nax.set_title('Predicted Profits vs.Population Size')\nplt.show()\n#绘制代价降低情况\nfig,bx=plt.subplots(figsize=(12,8))\nbx.plot(np.arange(iters),cost,'r')\nbx.set_xlabel('Iterations')\nbx.set_ylabel('Cost')\nbx.set_title('Error vs. Training Epoch')\nplt.show()\n\n#多变量线性回归情况\npath2='ex1data2.txt'\ndata2=pd.read_csv(path2,header=None,names=['Size','Bedrooms','Price'])\ndata2.head()\n#特征归一化\ndata2=(data2-data2.mean())/data2.std()\ndata2.head()\n#加上“1”列\ndata2.insert(0,'Ones',1)\ncols=data2.shape[1]\nX2=data2.iloc[:,0:cols-1]\ny2=data2.iloc[:,cols-1:cols]\nX2=np.matrix(X2.values)\ny2=np.matrix(y2.values)\ntheta2=np.matrix(np.array([0,0,0]))\ng2,cost2=gradientDescent(X2,y2,theta2,alpha,iters)\ncomputeCost(X2,y2,g2)\n#快速查看一下训练过程\nfig,ax=plt.subplots(figsize=(12,8))#(111,figsize=...)\nax.plot(np.arange(iters),cost2,'r')\nax.set_xlabel('Iterations')\nax.set_ylabel('Cost')\nax.set_title('Error vs. Training Epoch')\nplt.show()\n\n#直接用scikit-learn\nfrom sklearn import linear_model\nmodel=linear_model.LinearRegression()\nmodel.fit(X,y)\nx=np.array(X[:,1].A1)#什么意思？\nf=model.predict(X).flatten()\nfig,ax=plt.subplots(figsize=(12,8))\nax.plot(x,f,'r',label='Prediction')\nax.scatter(data.Population,data.Profits,label='Traning Data')\nax.legend(loc=4)#1234为四个角落\nax.set_xlabel('Population')\nax.set_ylabel('Profit')\nax.set_title('Predicted Profit vs. Population Size')\nplt.show()\n\n#正规方程法\ndef normalEqn(X,y):\n    theta=np.linalg.inv(X.T@X)@X.T@y#X.T@X即X.T.dot(X)\n    return theta\ntheta3=normalEqn(X,y)\ntheta3\ng#与梯度下降对比一下", "meta": {"hexsha": "26358760959d3ef7ff77a5ecd53a87f37f8ff6c3", "size": 2977, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/MachineLearning_Ng/examples/ex1.py", "max_stars_repo_name": "Ritetsu/lizhe_Notes", "max_stars_repo_head_hexsha": "4c465b5e23c1e520f9508314cfda7f26517d6dd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/MachineLearning_Ng/examples/ex1.py", "max_issues_repo_name": "Ritetsu/lizhe_Notes", "max_issues_repo_head_hexsha": "4c465b5e23c1e520f9508314cfda7f26517d6dd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/MachineLearning_Ng/examples/ex1.py", "max_forks_repo_name": "Ritetsu/lizhe_Notes", "max_forks_repo_head_hexsha": "4c465b5e23c1e520f9508314cfda7f26517d6dd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-07T12:01:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T12:01:42.000Z", "avg_line_length": 27.0636363636, "max_line_length": 70, "alphanum_fraction": 0.7107826671, "include": true, "reason": "import numpy", "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.8991213664574069, "lm_q1q2_score": 0.8634812372400458}}
{"text": "import numpy as np\nimport math as m\nfrom matplotlib import pyplot as plt\n\n\npi=round(m.pi,3)\n\nx=np.arange(0,10, 0.001)\nA=1.0\nC=2*pi\nB=0.0\nD=0.0\n\n\ndef sine(A,B,C,D):\n    \n    y=A*(np.sin((2*pi*(x-B))/C))+ D\n\n    plt.plot(x,y) #plot the graph of y function of x\n    plt.axhline(y=0, color='k')  #plot the x axis\n    plt.axvline(x=0, color='k') #plot the y axis\n    plt.grid(True)          #plot the gridlines\n    plt.xlabel('x')   #label the x axis\n    plt.ylabel('sin(x)')        #label the y axis\n\n    plt.show()\n    return;     \n\n\n\ndef cosine(A,B,C,D):\n    \n    y=A*(np.cos((2*pi*(x-B))/C))+ D\n\n    plt.plot(x,y) #plot the graph of y function of x\n    plt.axhline(y=0, color='k')  #plot the x axis\n    plt.axvline(x=0, color='k') #plot the y axis\n    plt.grid(True)          #plot the gridlines\n    plt.xlabel('x')   #label the x axis\n    plt.ylabel('cos(x)')        #label the y axis\n\n    plt.show()\n    return;\n\n\nprint(\"\\n\\t\\t Sine and Cosine Trigonometry graph calculator!\")\nprint(\"\\t\",\"-\"*55)\n\n\nend_program = 1\n\n\nwhile end_program:\n    c=int(input(\"Press 1 for sine or 0 for cosine: \"))\n    if c==1:\n        print(\"You chose to graph the function sine, the form:\")\n        print(\"f(x)=A*sin((2*pi*(x-B))/C))+ D\")\n        print(\"Enter the graph properties when prompted:\")\n        A=float(input(\"Amplitude (A)= \"))\n        B=float(input(\"Phase shift (B)= \"))\n        C=float(input(\"Period (can't be 0)(C)= \"))\n        D=float(input(\"Vertical shift (D)= \"))\n        sine(A,B,C,D)\n        end_program=int(input(\"Do you want to do another graph? Press 1 for Yes and 0 for No \\n\"))\n  \n\n    elif c==0:\n        print(\"You chose to graph the function cosine, the form:\")\n        print(\"f(x)=A*cos((2*pi*(x-B))/C))+ D\")\n        print(\"Enter the graph properties when prompted:\")\n        A=float(input(\"Amplitude (A)= \"))\n        B=float(input(\"Phase shift (B)= \"))\n        C=float(input(\"Period (can't be 0)(C)= \"))\n        D=float(input(\"Vertical shift (D)= \"))\n        cosine(A,B,C,D)\n        end_program=int(input(\"Do you want to do another graph? Press 1 for Yes and 0 for No\\n\"))\n        \n    else:\n        print(\"Oops Wrong choice!!\")\n        continue\n            \n    \n\n        \n", "meta": {"hexsha": "b53159d0f37f0c3e4c21cdd19a3a7ba0cf079fea", "size": 2181, "ext": "py", "lang": "Python", "max_stars_repo_path": "Sine and cosine graph.py", "max_stars_repo_name": "Abdanny2/Trig-Graphs", "max_stars_repo_head_hexsha": "29b6a9e9010ff7bf433e2d4f6dc27bd761516689", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-22T21:03:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-22T21:03:24.000Z", "max_issues_repo_path": "Sine and cosine graph.py", "max_issues_repo_name": "Abdanny2/Trig-Graphs", "max_issues_repo_head_hexsha": "29b6a9e9010ff7bf433e2d4f6dc27bd761516689", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sine and cosine graph.py", "max_forks_repo_name": "Abdanny2/Trig-Graphs", "max_forks_repo_head_hexsha": "29b6a9e9010ff7bf433e2d4f6dc27bd761516689", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6588235294, "max_line_length": 98, "alphanum_fraction": 0.558000917, "include": true, "reason": "import numpy", "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407152622597, "lm_q2_score": 0.8872046041554923, "lm_q1q2_score": 0.8634636435322613}}
{"text": "#!/usr/bin/python\n\"\"\"\nCw5 the pinacle of grupwork and efficienceyc and comroodery\n\nCalculus module implementing\ndiscrete function function\ndifferentiation function\nand trapezoidal integration function\n\n\"\"\"\n\n\nimport numpy as np\nimport math\n\ndef diff(f, a, b, n):\n    \"\"\"An iterative version of a forward differentiation method.\"\"\"\n    x = np.linspace(a, b, n+1)\n    y = np.zeros(len(x))\n    z = np.zeros(len(x))\n    h = (b-a)/float(n)\n    for i in xrange(len(x)):\n        y[i] = f(x[i])\n    for i in xrange(len(x)-1):\n        z[i] = (y[i+1] - y[i])/h\n    z[n] = (y[n] - y[n-1])/h\n    return y, z\n\ndef discrete_func(f, a, b, n):\n    \"\"\"Generates a vectorized linspace and applies a function to a similar data structure.\"\"\"\n    x = np.linspace(a, b, n+1)\n    g = np.vectorize(f)\n    y = g(x)\n    return x, y\n\ndef diff2(f, a, b, n):\n    \"\"\"A matrix version of a forward differentiation method.\"\"\"\n    x, y = discrete_func(f, a, b, n - 1)\n    matrix = np.zeros((n,n))\n    h = ( b - a ) / float(n)\n    count = -1\n    for i in range(n):\n        if(count >= 0 and count < n-2):\n            matrix[i][count] = 1 / (2 * h)\n            matrix[i][count + 2] = -1 / (2 * h)\n        count += 1\n    matrix[0][0] = -1 / h\n    matrix[0][1] = 1 / h\n    matrix[-1][-1] = 1 / h\n    matrix[-1][-2] = -1 / h\n    return np.dot(matrix, y)\n\ndef test_diff():\n    apt = math.fabs(diff(math.sin, 0, 1, 100000)[1][-1] - math.cos(1)) < 1e-3\n    msg = 'That aint how the sine function do.'\n    assert apt, msg\n\ndef test_diff2():\n    apt = math.fabs(diff(math.sin, 0, 1, 100000)[1][-1] - math.cos(1)) < 1e-3\n    msg = 'That aint how the sine function do.'\n    assert apt, msg\n\n\n\ndef trapezoidal_matrix(f, a, b, n):\n    \"\"\"Trapezoidal integration via matrix multiplication.\"\"\"\n    h = (b-a)/float(n)\n    indexer = np.linspace(a, b, n)\n    values = f(indexer)\n    matrixer = np.zeros(n)\n    matrixer.fill(h)\n    matrixer[0] = h/2.0\n    matrixer[n - 1] = h/2.0\n    I = np.dot(values, matrixer)\n    return I\n\ndef test_trap_matrix():\n    \"\"\"Trapezoidal integration via matrix multiplication verified by integrating\n    the sine function on the integral 0 to pi over 2.\"\"\"\n    apt = np.abs(trapezoidal_matrix(np.sin, 0, np.pi/2.0, 10000) - 1) < 1e-3\n    msg = 'That aint how the sine do.'\n    assert apt, msg\n", "meta": {"hexsha": "f07a7ae401c9ff0ea2eaccae13108013d1c47c12", "size": 2271, "ext": "py", "lang": "Python", "max_stars_repo_path": "calculus.py", "max_stars_repo_name": "chapman-phys227-2016s/cw-5-classwork-team", "max_stars_repo_head_hexsha": "0e89d0b4646f6e65ed836664660103054f969daa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "calculus.py", "max_issues_repo_name": "chapman-phys227-2016s/cw-5-classwork-team", "max_issues_repo_head_hexsha": "0e89d0b4646f6e65ed836664660103054f969daa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calculus.py", "max_forks_repo_name": "chapman-phys227-2016s/cw-5-classwork-team", "max_forks_repo_head_hexsha": "0e89d0b4646f6e65ed836664660103054f969daa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3614457831, "max_line_length": 93, "alphanum_fraction": 0.5816820784, "include": true, "reason": "import numpy", "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.9161096181702031, "lm_q1q2_score": 0.8634394739604745}}
{"text": "import time\nimport numpy as np\nx1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]\nx2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]\n\n### CLASSIC DOT PRODUCT OF VECTORS IMPLEMENTATION ###\ntic = time.process_time()\ndot = 0\nfor i in range(len(x1)):\n    dot+= x1[i]*x2[i]\ntoc = time.process_time()\nprint (\"dot = \" + str(dot) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### CLASSIC OUTER PRODUCT IMPLEMENTATION ###\ntic = time.process_time()\nmul = np.zeros(len(x1))\nfor i in range(len(x1)):\n    mul[i] = x1[i]*x2[i]\ntoc = time.process_time()\nprint(\"elementwise multiplication = \" + str(mul) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### CLASSIC GENERAL DOT PRODUCT IMPLEMENTATION ###\nW = np.random.rand(3,len(x1)) # Random 3*len(x1) numpy array\nprint(\"W is \\n\",W)\ntic = time.process_time()\ngdot = np.zeros(W.shape[0])\nfor i in range(W.shape[0]):\n    for j in range(len(x1)):\n        gdot[i] += W[i,j]*x1[j]\ntoc = time.process_time()\nprint (\"gdot = \" + str(gdot) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### VECTORIZED DOT PRODUCT OF VECTORS ###\ntic = time.process_time()\ndot = np.dot(x1,x2)\ntoc = time.process_time()\nprint (\"dot = \" + str(dot) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### VECTORIZED OUTER PRODUCT ###\ntic = time.process_time()\nouter = np.outer(x1,x2)\ntoc = time.process_time()\nprint (\"outer = \" + str(outer) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### VECTORIZED ELEMENTWISE MULTIPLICATION ###\ntic = time.process_time()\nmul = np.multiply(x1,x2)\ntoc = time.process_time()\nprint (\"elementwise multiplication = \" + str(mul) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### VECTORIZED GENERAL DOT PRODUCT ###\ntic = time.process_time()\ndot = np.dot(W,x1)\ntoc = time.process_time()\nprint (\"gdot = \" + str(dot) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n", "meta": {"hexsha": "2b61bed472c7b025ca3964320a5c3b6f8041ed7e", "size": 1924, "ext": "py", "lang": "Python", "max_stars_repo_path": "vectorization.py", "max_stars_repo_name": "ismaelsadeeq/dea-learning", "max_stars_repo_head_hexsha": "034303ebef89f15262d9761fbb0c15cbebcbecf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vectorization.py", "max_issues_repo_name": "ismaelsadeeq/dea-learning", "max_issues_repo_head_hexsha": "034303ebef89f15262d9761fbb0c15cbebcbecf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vectorization.py", "max_forks_repo_name": "ismaelsadeeq/dea-learning", "max_forks_repo_head_hexsha": "034303ebef89f15262d9761fbb0c15cbebcbecf5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3571428571, "max_line_length": 114, "alphanum_fraction": 0.6003118503, "include": true, "reason": "import numpy", "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538936, "lm_q2_score": 0.9136765193002482, "lm_q1q2_score": 0.8634194831953509}}
{"text": "import numpy as np\nimport sympy as sp\nfrom sympy.core import S, Dummy\nfrom sympy.polys.orthopolys import (legendre_poly, laguerre_poly,\n                                    hermite_poly, jacobi_poly)\nfrom sympy.polys.rootoftools import RootOf\n\n\n\ndef gauss_lobatto(n, n_digits):\n    r\"\"\"\n    Computes the Gauss-Lobatto quadrature [1]_ points and weights.\n\n    The Gauss-Lobatto quadrature approximates the integral:\n\n    .. math::\n        \\int_{-1}^1 f(x)\\,dx \\approx \\sum_{i=1}^n w_i f(x_i)\n\n    The nodes `x_i` of an order `n` quadrature rule are the roots of `P'_(n-1)`\n    and the weights `w_i` are given by:\n\n    .. math::\n        &w_i = \\frac{2}{n(n-1) \\left[P_{n-1}(x_i)\\right]^2},\\quad x\\neq\\pm 1\\\\\n        &w_i = \\frac{2}{n(n-1)},\\quad x=\\pm 1\n\n    Parameters\n    ==========\n\n    n : the order of quadrature\n\n    n_digits : number of significant digits of the points and weights to return\n\n    Returns\n    =======\n\n    (x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.\n             The points `x_i` and weights `w_i` are returned as ``(x, w)``\n             tuple of lists.\n\n    Examples\n    ========\n\n    >>> from sympy.integrals.quadrature import gauss_lobatto\n    >>> x, w = gauss_lobatto(3, 5)\n    >>> x\n    [-1, 0, 1]\n    >>> w\n    [0.33333, 1.3333, 0.33333]\n    >>> x, w = gauss_lobatto(4, 5)\n    >>> x\n    [-1, -0.44721, 0.44721, 1]\n    >>> w\n    [0.16667, 0.83333, 0.83333, 0.16667]\n\n    See Also\n    ========\n\n    gauss_legendre,gauss_laguerre, gauss_gen_laguerre, gauss_hermite, gauss_chebyshev_t, gauss_chebyshev_u, gauss_jacobi\n\n    References\n    ==========\n\n    .. [1] https://en.wikipedia.org/wiki/Gaussian_quadrature#Gauss.E2.80.93Lobatto_rules\n    .. [2] http://people.math.sfu.ca/~cbm/aands/page_888.htm\n    \"\"\"\n    x = Dummy(\"x\")\n    p = legendre_poly(n-1, x, polys=True)\n    pd = p.diff(x)\n    xi = []\n    wi = []\n    for r in pd.real_roots():\n        if isinstance(r, RootOf):\n            r = r.eval_rational(S(1)/10**(n_digits+2))\n        xi.append(r.n(n_digits))\n        wi.append((2/(n*(n-1) * p.subs(x, r)**2)).n(n_digits))\n\n    xi.insert(0, -1)\n    xi.append(1)\n    wi.insert(0, (S(2)/(n*(n-1))).n(n_digits))\n    wi.append((S(2)/(n*(n-1))).n(n_digits))\n    return xi, wi\n\n\ndigits = 36\nnpoints = list(range(2,17))\n\nfor n in npoints:\n    xi, wi = gauss_lobatto(n, digits)\n    \n    print('\\nN = %3d'%(n))\n    for i in range(0,n):\n        print('%3d %40.36f %40.36f'%(i+1,xi[i],wi[i]))\n    \n    \n    \n    \n    \n", "meta": {"hexsha": "e3d62da482ba11ea53d2ef71a2e3b305a7054060", "size": 2461, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/gauss_lobatto.py", "max_stars_repo_name": "BryanFlynt/PolyCalc", "max_stars_repo_head_hexsha": "9fe70f83647c6f5683e6e8f5cfee23b417974ebb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/gauss_lobatto.py", "max_issues_repo_name": "BryanFlynt/PolyCalc", "max_issues_repo_head_hexsha": "9fe70f83647c6f5683e6e8f5cfee23b417974ebb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/gauss_lobatto.py", "max_forks_repo_name": "BryanFlynt/PolyCalc", "max_forks_repo_head_hexsha": "9fe70f83647c6f5683e6e8f5cfee23b417974ebb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.112244898, "max_line_length": 120, "alphanum_fraction": 0.5639983746, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591976, "lm_q2_score": 0.9136765210631689, "lm_q1q2_score": 0.8634194763689561}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import hamming\nfrom scipy.fftpack import fft, fftshift\n\nplt.figure(1, figsize=(9.5, 6))\nM = 8\nN1 = 8\nN2 = 16\nN3 = 32\nx = np.cos(2*np.pi*2/M*np.arange(M)) * np.hanning(M)\n\nplt.subplot(4,1,1)\nplt.title('x, M=8')\nplt.plot(np.arange(-M/2.0,M/2), x, 'b', marker='x', lw=1.5)\nplt.axis([-M/2,M/2-1,-1,1])\n\nmX = 20 * np.log10(np.abs(fftshift(fft(x, N1))))\nplt.subplot(4,1,2)\nplt.plot(np.arange(-N1/2.0,N1/2), mX, marker='x', color='r', lw=1.5)\nplt.axis([-N1/2,N1/2-1,-20,max(mX)+1])\nplt.title('magnitude spectrum: mX1, N=8')\n\nmX = 20 * np.log10(np.abs(fftshift(fft(x, N2))))\nplt.subplot(4,1,3)\nplt.plot(np.arange(-N2/2.0,N2/2),mX,marker='x',color='r', lw=1.5)\nplt.axis([-N2/2,N2/2-1,-20,max(mX)+1])\nplt.title('magnitude spectrum: mX2, N=16')\n\nmX = 20 * np.log10(np.abs(fftshift(fft(x, N3))))\nplt.subplot(4,1,4)\nplt.plot(np.arange(-N3/2.0,N3/2),mX,marker='x',color='r', lw=1.5)\nplt.axis([-N3/2,N3/2-1,-20,max(mX)+1])\nplt.title('magnitude spectrum: mX3, N=32')\n\nplt.tight_layout()\nplt.savefig('zero-padding.png')\nplt.show()\n", "meta": {"hexsha": "aced2d43689fd968d0527b03c90e2c96f35b3062", "size": 1083, "ext": "py", "lang": "Python", "max_stars_repo_path": "stanford/sms-tools/lectures/03-Fourier-properties/plots-code/zero-padding.py", "max_stars_repo_name": "phunc20/dsp", "max_stars_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-12T18:32:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T18:32:06.000Z", "max_issues_repo_path": "stanford/sms-tools/lectures/03-Fourier-properties/plots-code/zero-padding.py", "max_issues_repo_name": "phunc20/dsp", "max_issues_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stanford/sms-tools/lectures/03-Fourier-properties/plots-code/zero-padding.py", "max_forks_repo_name": "phunc20/dsp", "max_forks_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7692307692, "max_line_length": 68, "alphanum_fraction": 0.6417359187, "include": true, "reason": "import numpy,from scipy", "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692318706085, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.863413969230214}}
{"text": "from numpy import random, pi\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\n\nNtrials, Nhits = 1_000_000, 0\nfor n in range(Ntrials):\n    x, y, z = random.uniform(-1, 1, 3) # draw 2 samples, each uniformly distributed over (-1,1)\n    if x**2 + y**2 + z**2 < 1:\n        Nhits += 1\n\nprint(\"Monte Carlo estimator of V(3): %.5f\" % ((2**3)*(Nhits / Ntrials)))\nprint(\"Actual value of V(3) up to 5 decimal digits: %.5f\" % (4*pi/3))\nprint(\"The relative error is %.5f%%\" % (100 * abs((2**3)*(Nhits / Ntrials) - (4*pi/3))))\n", "meta": {"hexsha": "4ee303de68185ba57832f2782e15be8e4b10d4e1", "size": 537, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab5_2020/lab5_2_1.py", "max_stars_repo_name": "AlexandrosKyriakakis/StochasticProcesses", "max_stars_repo_head_hexsha": "df9a8f50d65f43d8fd9f76e5fc66ddfaef38786a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-23T10:35:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T16:58:31.000Z", "max_issues_repo_path": "Lab5_2020/lab5_2_1.py", "max_issues_repo_name": "AlexandrosKyriakakis/StochasticProcesses", "max_issues_repo_head_hexsha": "df9a8f50d65f43d8fd9f76e5fc66ddfaef38786a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab5_2020/lab5_2_1.py", "max_forks_repo_name": "AlexandrosKyriakakis/StochasticProcesses", "max_forks_repo_head_hexsha": "df9a8f50d65f43d8fd9f76e5fc66ddfaef38786a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3571428571, "max_line_length": 95, "alphanum_fraction": 0.6294227188, "include": true, "reason": "from numpy", "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692311915195, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.8634139686298725}}
{"text": "import numpy as np\r\n\r\ndef unpaired_equal_variance(a, b):\r\n\ta, b = np.array(a), np.array(b)\r\n\ta_mean, b_mean = np.mean(a), np.mean(b)\r\n\ta_var, b_var = np.var(a), np.var(b)\r\n\tt = (a_mean-b_mean)/(np.sqrt((a_var/len(a))+(b_var/len(b))))\r\n\tdf = ((a_var/len(a)+b_var/len(b))**2) / (((a_var/len(a))**2)/(len(a)-1) + ((b_var/len(b))**2)/(len(b)-1) )\r\n\treturn t, df\r\n\r\ndef unpaired_not_equal_variance(a, b):\r\n\ta, b = np.array(a), np.array(b)\r\n\ta_mean, b_mean = np.mean(a), np.mean(b)\r\n\ta_var, b_var = np.var(a), np.var(b)\r\n\tsp = ((len(a)-1)*a_var+(len(b)-1)*b_var)/(len(a) + len(b) - 2)\r\n\tt = (a_mean-b_mean) / (np.sqrt((sp/len(a))+(sp/len(b))))\r\n\tdf = len(a) + len(b) - 2\r\n\treturn t, df\r\n\r\ndef paired(a, b):\r\n\ta, b = np.array(a), np.array(b)\r\n\ta_mean, b_mean = np.mean(a), np.mean(b)\r\n\ta_var, b_var = np.var(a), np.var(b)\r\n\tc, cc = list(), list()\r\n\r\n\tfor i in range(len(a)):\r\n\t\tc.append(a[i]-b[i])\r\n\t\tcc.append((a[i]-b[i])*(a[i]-b[i]))\r\n\tc, cc = np.array(c), np.array(cc)\r\n\r\n\tt = np.sum(c) / (np.sqrt((len(c)*np.sum(cc)-(np.sum(c)**2))/(len(c)-1)))\r\n\tdf = len(c)-1\r\n\treturn t, df\r\n\r\ndef two_samples(a, b, isPaired):\r\n\tif isPaired:\r\n\t\tt, df = paired(a, b)\r\n\telse:\r\n\t\tif np.round(np.var(np.array(a)), 5) == np.round(np.var(np.array(b)), 5):\r\n\t\t\tt, df = unpaired_equal_variance(a, b)\r\n\t\telse:\r\n\t\t\tt, df = unpaired_not_equal_variance(a, b)\r\n\treturn t, df\r\n\r\ndef one_sample(a, mu):\r\n\ta = np.array(a)\r\n\ta_mean = np.mean(a)\r\n\ts = np.sqrt(sum([ (i-a_mean)**2 for i in a])/(len(a)-1))\r\n\tt = (a_mean-mu)/(s/np.sqrt(len(a)))\r\n\tdf = len(a)-1\r\n\treturn t, df\r\n\r\ndef main():\r\n\ta = [26.3, 26.43, 26.28, 26.19, 26.49]\r\n\tb = [26.22, 26.32, 26.2, 26.11, 26.42]\r\n\r\n\tt, df = one_sample(a, mu=0.5)\r\n\tprint(t, df)\r\n\r\n\tt, df = two_samples(a, b, isPaired=True)\r\n\tprint(t, df)\r\n\r\n\tt, df = unpaired_not_equal_variance(a, b)\r\n\tprint(t, df)\r\n\r\n\tt, df = unpaired_equal_variance(a, b)\r\n\tprint(t, df)\r\n\r\nif __name__ == '__main__':\r\n\tmain()", "meta": {"hexsha": "1bd829684e6a28f14c534e4ab686408a8c4099c0", "size": 1900, "ext": "py", "lang": "Python", "max_stars_repo_path": "ttest.py", "max_stars_repo_name": "icecat2012/Student-t-test", "max_stars_repo_head_hexsha": "6023c282cc52488ca2d9b5c768e51be0542c078f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ttest.py", "max_issues_repo_name": "icecat2012/Student-t-test", "max_issues_repo_head_hexsha": "6023c282cc52488ca2d9b5c768e51be0542c078f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ttest.py", "max_forks_repo_name": "icecat2012/Student-t-test", "max_forks_repo_head_hexsha": "6023c282cc52488ca2d9b5c768e51be0542c078f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1428571429, "max_line_length": 108, "alphanum_fraction": 0.5605263158, "include": true, "reason": "import numpy", "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692284751636, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.8634139528010865}}
{"text": "import numpy as np\n\n#######################################\n# AND, OR, NAND, XOR using PERCEPTRON #\n#######################################\n\n\ndef step_function(x):\n    y = x > 0\n    return y.astype(np.int)\n\n\ndef AND(x1, x2):\n    x = np.array([x1, x2])\n    w = np.array([0.5, 0.5])\n    b = -0.7\n    tmp = np.sum(w * x) + b\n    if tmp <= 0:\n        return 0\n    else:\n        return 1\n\n\ndef NAND(x1, x2):\n    x = np.array([x1, x2])\n    w = np.array([-0.5, -0.5])\n    b = 0.7\n    tmp = np.sum(w * x) + b\n    if tmp <= 0:\n        return 0\n    else:\n        return 1\n\n\ndef OR(x1, x2):\n    x = np.array([x1, x2])\n    w = np.array([0.5, 0.5])\n    b = -0.2\n    tmp = np.sum(w * x) + b\n    if tmp <= 0:\n        return 0\n    else:\n        return 1\n\n\ndef XOR(x1, x2):\n    x = np.array([x1, x2])\n    w1 = np.array([[0.5, 0.5], [-0.5, -0.5]])\n    b1 = np.array([-0.2, 0.7])\n    w2 = np.array([0.5, 0.5])\n    b2 = -0.7\n\n    s = np.dot(x, w1) + b1\n    s_activated = step_function(s)\n    y = np.sum(w2 * s_activated) + b2\n    if y <= 0:\n        return 0\n    else:\n        return 1\n\n\ndef test_perceptrons(x):\n    print('#####################')\n    print('TESTING PERCEPTRONS')\n    print('#####################')\n    for data in x:\n        print(\"AND(%d,%d): %d\" % (data[0], data[1], AND(data[0], data[1])))\n\n    for data in x:\n        print(\"NAND(%d,%d): %d\" % (data[0], data[1], NAND(data[0], data[1])))\n\n    for data in x:\n        print(\"OR(%d,%d): %d\" % (data[0], data[1], OR(data[0], data[1])))\n\n    for data in x:\n        print(\"XOR(%d,%d): %d\" % (data[0], data[1], XOR(data[0], data[1])))\n    print('#####################')\n\nif __name__=='__main__':\n    test_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])\n    test_perceptrons(test_data)\n\n\n", "meta": {"hexsha": "512d46351a8d3a2708e17988af5997083f644cda", "size": 1732, "ext": "py", "lang": "Python", "max_stars_repo_path": "week1/JY/perceptron.py", "max_stars_repo_name": "maybedy/MLDLStudy", "max_stars_repo_head_hexsha": "abe121bc73c1958f1cd2d30fd30384137140187b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week1/JY/perceptron.py", "max_issues_repo_name": "maybedy/MLDLStudy", "max_issues_repo_head_hexsha": "abe121bc73c1958f1cd2d30fd30384137140187b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week1/JY/perceptron.py", "max_forks_repo_name": "maybedy/MLDLStudy", "max_forks_repo_head_hexsha": "abe121bc73c1958f1cd2d30fd30384137140187b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.619047619, "max_line_length": 77, "alphanum_fraction": 0.4301385681, "include": true, "reason": "import numpy", "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854111860906, "lm_q2_score": 0.890294215206509, "lm_q1q2_score": 0.8633943415706422}}
{"text": "import math\nimport numpy as np\n    \nimport time \n\ndef factorial(n):\n    total = n\n    for i in range(1, n):\n        total *= i\n    if (n==0):\n        return 1\n    return total\n\ndef choose(n,k):\n    \"\"\"Standard Choose function.\n    \n    :param n: The total sample size.\n    :type n: int\n    :param k: The number of elements you're choosing.\n    :type k: int\n    :return: n choose k\n    :rtype: int\n    \"\"\"\n    return (math.factorial(n)/(math.factorial(k)*math.factorial(n-k)))\n\ndef probability(p, n, k):\n    \"\"\"Binomial probability function.\n    \n    :param p: Odds of success. (0.5 for a coin flip)\n    :type p: float\n    :param n: total sample size.\n    :type n: int\n    :param k: The number of elements you're choosing.\n    :type k: int\n    :return: The probability of the inputs.\n    :rtype: float\n    \"\"\"\n    return choose(n, k)*p**(n-k)*(1-p)**k\n\ndef nth_derivative(f, x, n):\n    \"\"\"Calculates the nth derivative using Newton's difference quotient method.\n    \n    :param f: input function.\n    :type f: lambda\n    :param x: Particular value at which f is evaluated.\n    :type x: float\n    :param n: The particular derivative requested.\n    :type n: int\n    :return: The nth derivative of f(x) at the given x.\n    :rtype: float\n    \"\"\"\n    h = 10e-2\n    out_h = 1/(h**n)\n    out = 0\n    for k in range(0, n+1):\n        out += (-1)**(k+n)*choose(n,k)*f(x +k*h)\n    return out_h*out\n\ndef rectangular_integral(f, xrange, intervals):\n    \"\"\"Standard Riemann sum integral function.\n    \n    :param f: Input function to calculate the integral of.\n    :type f: lambda\n    :param xrange: List of the begin and end points for x.\n    :type xrange: List\n    :param intervals: How many rectangles.\n    :type intervals: int\n    :return: The value of the integral between the xrange.\n    :rtype: float\n    \"\"\"\n    int_out = 0\n    delta_x = (max(xrange)-min(xrange))/intervals\n    new_xrange = np.linspace(min(xrange), max(xrange), intervals)\n    for x in new_xrange:\n        int_out += f(x)\n    return delta_x*int_out\n\ndef trapezoid_integral(f, xrange, intervals):\n    \"\"\"Calculates an integral using the trapezoidal rule for integration.\n    \n    :param f: Function to evaluate the integral on.\n    :type f: lambda\n    :param xrange: The range on which to evaluate f(x)\n    :type xrange: list\n    :param intervals: The total number of subdivisions.\n    :type intervals: int\n    :return: The value for the integral at x.\n    :rtype: float\n    \"\"\"\n    \n    a, b = min(xrange), max(xrange)\n    delta_x = (b-a)/intervals\n    x = np.arange(1, intervals)\n    \n    int_out = f(a)\n    int_out += f(b)\n    int_out += sum(2*f(a+x*delta_x))\n    \n    return delta_x/2*int_out\n\ndef maclaurin_expansion(f, x, N):\n    sum = f(0)\n    for i in range(1, N+1):\n        sum += nth_derivative(f, 0, i)/factorial(i)*x**i\n    return sum\n    \ndef create_graph_from_lambda(f, xrange):\n    \"\"\"Takes a function as an input with a specific interval xrange then creates a list with the output\n    y-points. Inefficient, but useful if f is a simple math function not involving NumPy.\n    \n    :param f: The function to evaluate.\n    :type f: lambda\n    :param xrange: The interval on which f(x) is evaluated.\n    :type xrange: list\n    :return: The list of f(x) points for all x in xrange.\n    :rtype: list of floats\n    \"\"\"\n    out = []\n    for x in xrange:\n        out.append(f(x))\n    return out\n\ndef create_derivative_graph(f, xrange, n):\n    \"\"\"Takes a function as an input with a specific interval xrange, then creates a list with the ouput\n    y-points for the nth derivative of f.\n    \n    :param f: Input function that we wish to take the derivative of.\n    :type f: lambda\n    :param xrange: The interval on which to evaluate f^n(x).\n    :type xrange: list\n    :param n: The derivative (1st, 2nd, 3rd, etc)\n    :type n: int\n    :return: A list of all f^n(x) points for all x in xrange.\n    :rtype: list of floats\n    \"\"\"\n    plot_points = []\n    for x in xrange:\n        plot_points.append(nth_derivative(f, x, n))\n    return plot_points\n\ndef eulers_method(f, y, dx, range):\n    \"\"\" The Eulers method for a first order differential equation.\n    \n    :param f: First order differential equation to approximate the solution for.\n    :type f: lambda\n    :param y: The initial condition for the y-value.\n    :type y: float, int\n    :param dx: Step size. Smaller is better.\n    :type dx: float\n    :param range: List containing the beginning and end points for our domain.\n    :type range: list\n    :return: Returns a tuple for the x coordinates corresponding to a set of y coordinates,\n    which approximate the solution to f. \n    :rtype: list\n    \"\"\"\n    x = min(range)\n    y_space = [y]\n    x_space = [x]\n    while x<=max(range):\n        y += f(x, y)*dx\n        x += dx\n        x_space.append(x)\n        y_space.append(y)\n    return (x_space, y_space)\n\ndef eulers_cromer_method(f, dx, y, yp, range, cromer=True):\n    \"\"\" The Eulers method, and Eulers-Cromer method for second order\n    differential equations. \n    \n    :param f: Second order differential equation to approximate the solution for.\n    :type f: lambda\n    :param dx: Step size. Smaller is better.\n    :type dx: float\n    :param y: The initial value of y given by initial condition.\n    :type y: int, float\n    :param yp: The initial value of y' given by initial condition.\n    :type yp: int, float\n    :param range: List containing the beginning and end points for our domain.\n    :type range: list\n    :param cromer: Use Cromer method or just regular Eulers, defaults to True\n    :type cromer: bool, optional\n    :return: Returns a tuple for the x coordinates corresponding to a set of y coordinates,\n    which approximate the solution to f. \n    :rtype: list\n    \"\"\"\n    x=min(range)\n    y_space = [y]\n    x_space = [x]\n    while x<=max(range):\n        if cromer:\n            yp += f(x,y,yp)*dx\n            y += yp*dx\n        else:\n            y += yp*dx\n            yp += f(x,y,yp)*dx\n        \n        x += dx\n        x_space.append(x)\n        y_space.append(y)\n    return (x_space, y_space)\n\ndef eulers_richardson_method(f, dx, y, yp, range, return_yp = False):\n    \"\"\" The Eulers Richardson method for solving a differential equation of second\n    order. Works by taking the Euler method, but uses the average values instead.\n    This produces a better approximation to the solution faster (in theory) than\n    just the plain Eulers method.\n    \n    :param f: The input math function derivative whom to approximate its solution\n    :type f: lambda\n    :param dx: The step size to use. Smaller is better.\n    :type dx: float\n    :param y: The initial value of y given by initial condition.\n    :type y: float, int\n    :param yp: The initial value of y' given by initial condition.\n    :type yp: float, int\n    :param range: A list which specifies the beginning and the ending of our domain.\n    :type range: list\n    :return: Returns a tuple for the x coordinates corresponding to a set of y coordinates,\n    which approximate the solution to f.\n    :rtype: list\n    \"\"\"\n    x       = min(range)\n    y_space = [y]\n    yp_space = [yp]\n    x_space = [x]\n    \n    while x<=max(range):\n        yp_mid  = yp + 1/2*f(x,y,yp)*dx\n        y_mid   = y  + 1/2*yp*dx\n        ypp_mid = f(1/2*x*dx, y_mid, yp_mid)\n        yp      += ypp_mid*dx\n        y       += yp_mid*dx\n        \n        x       += dx\n        x_space.append(x)\n        y_space.append(y)\n        yp_space.append(yp)\n    if (return_yp):\n        return (x_space, y_space, yp_space)\n    return (x_space, y_space)\n\ndef euler_richardson_method_2system_ode2(f, g, dt, x, y, xp, yp, range):\n    \"\"\" The Euler-Richardson method working on a two-coupled system. Required\n    for chapter 6, problem 5 in order to express two coupled parameterized\n    functions as a single output y(x).\n    \n    :param f: The first second order diffeq expressed as a lambda.\n    :type f: lambda\n    :param g: The second second order diffeq expressed as a lambda.\n    :type g: lambda\n    :param dt: Step size. Smaller is better.\n    :type dt: float\n    :param x: The initial condition for x.\n    :type x: float,int\n    :param y: The initial condition for y.\n    :type y: float,int\n    :param xp: The initial condition for xp.\n    :type xp: float,int\n    :param yp: The initial condition for yp.\n    :type yp: float,int\n    :param range: A list which specifies the beginning and the ending of our domain.\n    :type range: list\n    :return: Returns a tuple for the t,x,y,xp,yp values as lists.\n    :rtype: 5-tuple(list)\n    \"\"\"\n    # f = x'' and g = y''\n    # both requires (t, x, y, x', y')\n    # get initial conditions and setup arrays\n    t = min(range)\n    t_space = [t]\n    x_space = [x]\n    y_space = [y]\n    xp_space = [xp]\n    yp_space = [yp]\n    \n    while t <= max(range):\n        # find get midpoints\n        t_mid = t + (1/2)*dt\n        xp_mid = xp + 1/2*f(t, x, y, xp, yp)*dt\n        yp_mid = yp + 1/2*g(t, x, y, xp, yp)*dt\n        x_mid = x + (1/2)*xp*dt\n        y_mid = y + (1/2)*yp*dt\n        \n        # get slopes\n        xp_s = f(t_mid, x_mid, y_mid, xp_mid, yp_mid)\n        yp_s = g(t_mid, x_mid, y_mid, xp_mid, yp_mid)\n        x_s = xp_mid\n        y_s = yp_mid\n        \n        # update values\n        t += dt\n        x += x_s*dt\n        y += y_s*dt\n        xp += xp_s*dt\n        yp += yp_s*dt\n\n        # append values\n        t_space.append(t)\n        x_space.append(x)\n        xp_space.append(xp)\n        y_space.append(y)\n        yp_space.append(yp)\n    \n    \n    return (t_space, x_space, y_space, xp_space, yp_space)\n    \n\ndef rk2_first_order_method(f, y, dx, range):\n    \"\"\" Runge-Kutta 2 method for a first order differential \n    equation.\n    \n    :param f: Input first order derivative to appromixate.\n    :type f: lambda\n    :param y: The initial value given for y.\n    :type y: float, int\n    :param dx: Step size. Smaller is better.\n    :type dx: float\n    :param range: A list which specifies the beginning and the ending of our domain.\n    :type range: list\n    :return: Returns a tuple for the x coordinates corresponding to a set of y coordinates,\n    which approximate the solution to f.\n    :rtype: tuple(list, list)\n    \"\"\"\n    x = min(range)\n    \n    x_space = [x]\n    y_space = [y]\n    \n    while x<=max(range):\n        yp_mid = f(x+1/2*dx, y + 1/2*dx*f(x,y))\n        y += yp_mid*dx\n        \n        x += dx\n        x_space.append(x)\n        y_space.append(y)\n    return (x_space, y_space)\n\ndef rk4_first_order_method(f, y, dx, range):\n    \"\"\"Runge-Kutta 4 method for a first order differential \n    equation.\n    \n    :param f: Input first order derivative to appromixate.\n    :type f: lambda\n    :param y: The initial value given for y.\n    :type y: float, int\n    :param dx: Step size. Smaller is better.\n    :type dx: float\n    :param range: A list which specifies the beginning and the ending of our domain.\n    :type range: list\n    :return: Returns a tuple for the x coordinates corresponding to a set of y coordinates,\n    which approximate the solution to f.\n    :rtype: list\n    \"\"\"\n    x = min(range)\n    \n    x_space = [x]\n    y_space = [y]\n    \n    while x<=max(range):\n        k_1 = f(x, y)*dx\n        \n        k_2 = f(x+1/2*dx, y + 1/2*k_1)*dx\n        \n        k_3 = f(x+1/2*dx, y + 1/2*k_2)*dx\n        \n        k_4 = f(x + dx, y + k_3)*dx\n        \n        y   += 1/6*(k_1+2*(k_2+k_3)+k_4)\n        \n        x += dx\n        x_space.append(x)\n        y_space.append(y)\n    return (x_space, y_space)\n\ndef rk4_second_order_method(f, y, z, dx, range):\n    \"\"\"Runge-Kutta 4 method for a second order differential \n    equation.\n    \n    :param f: Input first order derivative to appromixate.\n    :type f: lambda\n    :param y: The initial value given for y.\n    :type y: float, int\n    :param z: The initial value given for z.\n    :type z: float, int\n    :param dx: Step size. Smaller is better.\n    :type dx: float\n    :param range: A list which specifies the beginning and the ending of our domain.\n    :type range: list\n    :return: Returns a tuple for the x coordinates corresponding to a set of y coordinates,\n    which approximate the solution to f.\n    :rtype: list\n    \"\"\"\n    x = min(range)\n    \n    x_space = [x]\n    y_space = [y]\n    z_space = []\n    \n    while x<=max(range):\n        k_1 = z*dx\n        l_1 = f(x, y, z)*dx\n        \n        k_2 = (z+1/2*l_1)*dx\n        l_2 = f(x+1/2*dx, y + 1/2*k_1, z + 1/2*l_1)*dx\n        \n        k_3 = (z + 1/2*l_2)*dx\n        l_3 = f(x+1/2*dx, y + 1/2*k_2, z + 1/2*l_2)*dx\n        \n        k_4 = (z + l_3)*dx\n        l_4 = f(x + dx, y + k_3, z + l_3)*dx\n        \n        y += 1/6*(k_1+2*k_2+2*k_3+k_4)\n        z += 1/6*(l_1+2*l_2+2*l_3+l_4)\n        \n        x += dx\n        x_space.append(x)\n        y_space.append(y)\n        z_space.append(z)\n    return (x_space, y_space, z_space)\n    \n\ndef build_extracted_list(input_list, subinterval):\n    \"\"\" A utility function to extract a number of elements from a list, leaving only a certain subset.\n    Generates a new list with just the subset. Creates the subset by specifying a sub-interval.\n    \n    :param input_list: The list to be extracted\n    :type input_list: list\n    :param subinterval: How many other elements to keep (for example, 10 means keep every 10 elements).\n    :type subinterval: int\n    :return: The extracted list.\n    :rtype: list\n    \"\"\"\n    out = []\n    wait = subinterval\n    for i in input_list:\n        if wait == subinterval:\n            out.append(i)\n            wait = 0\n        else:\n            wait += 1\n    return out\n\ndef newtons_law_of_cooling(room_temp, object_temp, t, k):\n    return room_temp + (object_temp-room_temp)*math.exp(-k*t)\n\ndef diffusion_monte_carlo(num_of_gas, time_total, t_min=None):\n    \"\"\" Generates a list of points to which a gas of num_of_gas\n    molecules diffuses through a membrane and into a separate\n    container within a total time total_time.\n\n    :param num_of_gas: The amount of gas.\n    :type num_of_gas: int\n    :param time_total: The total time to run the simulation for.\n    :type time_total: int\n    :param t_min: Start at t=0 or not, defaults to None\n    :type t_min: int, float, optional\n    :return: Returns a list of diffusion of molecules per\n    time.\n    :rtype: tuple(time, molecules)\n    \"\"\"\n    if t_min:\n        time_array  = np.linspace(t_min, time_total, time_total+1, dtype=int)\n    else:\n        time_array  = np.linspace(1, time_total, time_total+1, dtype=int)\n        \n    gas_left    = np.array([num_of_gas])\n    random_gas  = np.random.randint(1, num_of_gas+1, size=time_total)\n    \n    current_gas = num_of_gas\n    \n    for x in random_gas:\n        if x <= current_gas:\n            current_gas -= 1\n        else:\n            current_gas += 1\n        gas_left = np.append(gas_left, current_gas)\n    return (time_array, gas_left)\n\ndef nuclear_decay_monte_carlo(initial_amount, probability, t_max, ret_half=False):\n    \"\"\" Generates a list of points to which can be graphed, tracing out the\n    nuclear decay of an element given an initial amount initial_amount, probability,\n    a maximum time interval.\n\n    :param initial_amount: The starting mass.\n    :type initial_amount: int, float\n    :param probability: The likelyhood for decay to occur.\n    :type probability: float 0 to 1.\n    :param t_max: The maximum time to go for.\n    :type t_max: int\n    :param ret_half: Should half-life be returned or not, defaults to False.\n    :type ret_half: bool, optional\n    :return: Returns the amount of nuclei decayed per time and the half-life\n    if specified by the optional variable.\n    :rtype: tuple(time, nuclei, [optional] half-life)\n    \"\"\"\n    particle_array = np.arange(1, initial_amount+1, dtype=int)\n    \n    nuclei_left    = np.array([initial_amount+1])\n    \n    half_life      = 0\n    \n    # Array math.\n    for t in range(0, t_max):\n        random_array   = np.random.uniform(0, 1, size=particle_array.size)\n        random_bool    = np.where(random_array <= probability, True, False)\n        particle_array = particle_array[random_bool != True]\n        nuclei_left    = np.append(nuclei_left, particle_array.size)\n        if not half_life and particle_array.size <= initial_amount/2:\n            # Average.\n            half_life  = (2*t-1)/2\n       \n    time_array = np.linspace(1, nuclei_left.size, nuclei_left.size, dtype=int)\n    if ret_half:\n        return (time_array, nuclei_left, half_life)\n    return (time_array, nuclei_left)\n\ndef virus_monte_carlo(initial_infected, population, k):\n    \"\"\" Generates a list of points to which some is infected\n    at a given value k starting with initial_infected infected.\n    There is no mechanism to stop the infection from reaching\n    the entire population.\n\n    :param initial_infected: The amount of people whom are infected at the\n    start.\n    :type initial_infected: int\n    :param population: The total population sample.\n    :type population: int\n    :param k: The rate of infection.\n    :type k: float\n    :return: An array of the amount of people per time infected.\n    :rtype: tuple(time, infected)\n    \"\"\"\n    people_array    = np.arange(1, population+1, dtype=int)\n    current_infected = initial_infected\n    people_infected = np.array([current_infected])\n    time_array      = np.array([0])\n    \n    # Array math.\n    counter = 0\n    for _ in people_array:\n        probability      = (k)*current_infected/population\n        random_array     = np.random.uniform(0, 1, size=people_array.size)\n        random_bool      = np.where(random_array <= probability, True, False)\n        people_array     = people_array[random_bool != True]\n        if people_array.size != population:\n            current_infected = (population-people_array.size)\n        people_infected  = np.append(people_infected, current_infected)\n        counter+=1\n        time_array = np.append(time_array, counter)\n        if people_infected.size == population:\n            break\n        \n    return (time_array, people_infected)\n\ndef random_walk(n, p):\n    \"\"\" Based on the number of times n, with a probability\n    to move to the right p, this function calculates the mean\n    of the end value along a one-dimensional axis to which it\n    'walked'.\n\n    :param n: Number of steps to take.\n    :type n: int\n    :param p: Probability from 0 to 1\n    :type p: float\n    :return: The expected value on the number line to which we\n    end up.\n    :rtype: float\n    \"\"\"\n    random_array = np.random.uniform(0, 1, n)\n    left = random_array[random_array > p].size\n    right = n - left\n    \n    return (right-left)\n\ndef monte_carlo_integration(f, n, a, b, ret_arrays=False):\n    \"\"\" Calculate the integral of a function f\n    from a to b with a number of random points n. Tried to\n    optimize by removing for loops in favor of NumPy arrays with\n    conditional indexing due to their cache efficiency vs Python\n    list pointer dereferences.\n    Fastest speed I've gotten is about 130ms.\n\n    :param f: The input math function.\n    :type f: lambda\n    :param n: The total number of points.\n    :type n: int\n    :param a: Starting position.\n    :type a: int, float\n    :param b: Ending position.\n    :type b: int, float\n    :param ret_arrays: Return arrays in order to graph, defaults to False.\n    :type ret_arrays: Boolean, defaults to False.\n    :return: The estimated value of the integral of f.\n    :rtype: float\n    \"\"\"\n    x = np.random.uniform(0, 1, n)*(b-a)+a\n    f_array = f(x)\n\n    positive_x = x[f_array >= 0]\n    negative_x = x[f_array < 0]\n    if positive_x.size > 0:\n        h = np.max(f_array)\n    else:\n        h = np.max(-f_array)\n    \n    y_positive = np.random.uniform(0, 1, positive_x.size)*h\n    y_negative = np.random.uniform(0, 1, negative_x.size)*h\n    \n    xy_indices_below = y_positive <= f(positive_x)\n    xy_indices_above = y_negative <= -f(negative_x)\n    n_inside_below = y_positive[xy_indices_below]\n    n_inside_above = -y_negative[xy_indices_above]\n    \n    if ret_arrays:\n        n_inside_x = np.append(positive_x[xy_indices_below],negative_x[xy_indices_above])\n        n_inside_y = np.append(n_inside_below, n_inside_above)\n        return n_inside_x, n_inside_y\n    \n    return h*(b-a)*(n_inside_below.size-n_inside_above.size)/(n)", "meta": {"hexsha": "54ed2806cd58d48b6a6b0f16d985979081b2c253", "size": 20101, "ext": "py", "lang": "Python", "max_stars_repo_path": "spring-phonon-dispersions/share.py", "max_stars_repo_name": "rglusic/spring-phonon-dispersions", "max_stars_repo_head_hexsha": "2ee5d61ff9538d22e9ba079df94027629918c73c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-10T01:12:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T08:55:32.000Z", "max_issues_repo_path": "spring-phonon-dispersions/share.py", "max_issues_repo_name": "rglusic/spring-phonon-dispersions", "max_issues_repo_head_hexsha": "2ee5d61ff9538d22e9ba079df94027629918c73c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spring-phonon-dispersions/share.py", "max_forks_repo_name": "rglusic/spring-phonon-dispersions", "max_forks_repo_head_hexsha": "2ee5d61ff9538d22e9ba079df94027629918c73c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4733441034, "max_line_length": 103, "alphanum_fraction": 0.626585742, "include": true, "reason": "import numpy", "num_tokens": 5548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957277806109987, "lm_q2_score": 0.9019206804839998, "lm_q1q2_score": 0.8633886502989498}}
{"text": "'''\nImplementation of the (unsupervised) K-means clustering algorithm \n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import make_blobs\nclass KMeansClustering():\n    def __init__(self, X, k):\n        self.X = X\n        self.num_data_points = self.X.shape[0]\n        self.num_features = self.X.shape[1] \n        self.k = k\n        self.max_iter = 100\n        self.plot_fig = True \n\n    def initialize_random_centroids(self, X):    \n        '''\n        randomly assign each cluster as one of the randomly selected data points features\n        '''\n        centroids = np.zeros((self.k, self.num_features))\n        for i in range(self.k):\n            centroids[i] = X[np.random.choice(range(self.num_data_points))]\n        return centroids\n    \n    def create_clusters(self, X, centroids):\n        '''\n        assign each point to the closest cluster in Euclidean distance\n        '''\n        clusters = [[] for _ in range(self.k)]\n       \n        for i in range(self.num_data_points):\n            closest_centroid = np.argmin(np.sqrt(np.sum((X[i] - centroids)**2, axis=1)))\n            clusters[closest_centroid].append(i)\n\n        return clusters\n\n    def calclulate_new_centroids(self, clusters, X):\n        '''\n        calculate new cluster means\n        '''\n        centroids = np.zeros((self.k, self.num_features)) \n        for i in range(self.k):\n            new_centroid = np.mean(X[clusters[i]], axis=0)\n            centroids[i] = new_centroid\n        return centroids\n    def predict_cluster(self, clusters, X):\n        '''\n        for each point assign its cluster label\n        '''\n        y_pred = np.zeros((self.num_data_points))\n\n        for i in range(len(clusters)):\n            cluster = clusters[i]\n            for ii in range(len(cluster)):\n                sample_idx = cluster[ii]\n                y_pred[sample_idx] = i\n        return y_pred\n    def plot_figure(self, X, y):\n        '''\n        plot the assigned clusters\n        '''\n        plt.scatter(X[:,0], X[:,1], cmap=plt.cm.Spectral, c=y, s=40)      \n        plt.show()    \n\n    def fit(self, X):\n        '''\n        train the clustering algorithm and iteratively improve the clusters\n        '''\n        centroids = self.initialize_random_centroids(X)\n\n        for it in range(self.max_iter):\n            clusters = self.create_clusters(X, centroids) \n            previous_centroids = centroids\n            centroids = self.calclulate_new_centroids(clusters, X)\n\n            diff = centroids - previous_centroids\n\n            if not diff.any():\n                print('Done')\n                break \n        y_pred = self.predict_cluster(clusters, X)\n        if self.plot_fig:\n            self.plot_figure(X, y_pred)\n        return y_pred\n\nif __name__ == '__main__':\n    np.random.seed(10)\n    num_clusters = 5\n    X, _ = make_blobs(n_samples=500, n_features=2, centers=num_clusters) # create some data\n\n    Kmeans = KMeansClustering(X, num_clusters) \n    y_pred = Kmeans.fit(X)", "meta": {"hexsha": "3d9669f16a292e4e74107745a82898c72679fb7d", "size": 2982, "ext": "py", "lang": "Python", "max_stars_repo_path": "ML_Algorithms/kmeans/k-means.py", "max_stars_repo_name": "ewanowara/practiceMLandDAproblems", "max_stars_repo_head_hexsha": "8c002235f18ae5fb6e7b837106c87d09d33f14a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ML_Algorithms/kmeans/k-means.py", "max_issues_repo_name": "ewanowara/practiceMLandDAproblems", "max_issues_repo_head_hexsha": "8c002235f18ae5fb6e7b837106c87d09d33f14a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ML_Algorithms/kmeans/k-means.py", "max_forks_repo_name": "ewanowara/practiceMLandDAproblems", "max_forks_repo_head_hexsha": "8c002235f18ae5fb6e7b837106c87d09d33f14a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4130434783, "max_line_length": 91, "alphanum_fraction": 0.5878604963, "include": true, "reason": "import numpy", "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778048911613, "lm_q2_score": 0.9019206732341567, "lm_q1q2_score": 0.8633886422595519}}
{"text": "from numpy import exp, tanh, maximum\n\n\ndef calculate_identity(input_sum_array):\n    \"\"\"Applies identity function to input.\"\"\"\n    return input_sum_array\n\n\ndef calculate_sigmoid(input_sum_array):\n    \"\"\"Applies sigmoid function to input.\"\"\"\n    return 1 / (1 + exp(-input_sum_array))\n\n\ndef calculate_tanh(input_sum_array):\n    \"\"\"Applies hyperbolic tangent function to input.\"\"\"\n    return tanh(input_sum_array)\n\n\ndef calculate_relu(input_sum_array):\n    \"\"\"Applies rectified linear unit function to input.\"\"\"\n    return maximum(input_sum_array, 0, input_sum_array)\n\n\ndef calculate_output(input_sum_array, activation_function_id):\n    \"\"\"Applies activation function to input, based on determined id.\"\"\"\n    activation_function = _ACTIVATION_FUNCTIONS.get(activation_function_id)\n    return activation_function(input_sum_array)\n\n\n_ACTIVATION_FUNCTIONS = {\n    'identity': calculate_identity,\n    'sigmoid': calculate_sigmoid,\n    'tanh': calculate_tanh,\n    'relu': calculate_relu\n}\n\n#===============================================================================\n# _NON_LINEAR_ACTIVATION_FUNCTIONS = {\n#     'sigmoid': calculate_sigmoid,\n#     'tanh': calculate_tanh,\n#     'relu': calculate_relu\n# }\n#===============================================================================\n\n_NON_LINEAR_ACTIVATION_FUNCTIONS = {\n    'sigmoid': calculate_sigmoid,\n    'tanh': calculate_tanh\n}\n\n# Creating random activation functions on the fly.\n", "meta": {"hexsha": "f0e5454a97f48f1378571bc85b886d45944adb07", "size": 1435, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/algorithms/common/neural_network/activation_function.py", "max_stars_repo_name": "martasls/pythonic-learning-machine", "max_stars_repo_head_hexsha": "330d1d5320adc8667bc7ce527808ec7a9c2271d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithms/common/neural_network/activation_function.py", "max_issues_repo_name": "martasls/pythonic-learning-machine", "max_issues_repo_head_hexsha": "330d1d5320adc8667bc7ce527808ec7a9c2271d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithms/common/neural_network/activation_function.py", "max_forks_repo_name": "martasls/pythonic-learning-machine", "max_forks_repo_head_hexsha": "330d1d5320adc8667bc7ce527808ec7a9c2271d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.137254902, "max_line_length": 80, "alphanum_fraction": 0.6585365854, "include": true, "reason": "from numpy", "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535094, "lm_q2_score": 0.9019206719160033, "lm_q1q2_score": 0.8633886387991443}}
{"text": "import numpy as np\n\n\ndef sigmoid(z):\n    return 1. / (1. + np.exp(-z))\n\n\ndef log_likelihood(y, y_hat):\n    return np.sum(y * np.log(y_hat) + (1-y) * np.log(1-y_hat))\n\n\nclass LogisticRegression:\n    \"\"\"Classification model based on the logistic function.\n\n    Classification model that maps a linear combination of the\n    input features to a probability using the logistic function.\n\n    Parameters\n    ----------\n    n_features : `int`\n        Dimensionality, or number of features, of the training data.\n\n    \"\"\"\n\n    def __init__(self, n_features):\n        self.n_features = n_features\n        self.w = self._initialize_weights(self.n_features+1)\n\n    def _initialize_weights(self, n_features):\n        return np.zeros(n_features)\n\n    def fit(self, X, y, learning_rate=1e-3, iterations=1000):\n        \"\"\"Trains the model with gradient descent.\n\n        Parameters\n        ----------\n        x : `numpy.ndarray` (n_examples, n_features)\n            Independant variables of the training examples from which to\n            estimate the parameters of the model.\n\n        y : `numpy.ndarray` (n_examples, n_features)\n            Labels corresponding to each training example in ``x``.\n\n        learning_rate : `int`, optional\n            Size of the step to take using the negative of the gradient.\n            Defaults to 1e-3\n\n        iterations : `int`, optional\n            Number of iterations to perform gradient descent. Defaults to 1000.\n\n        Returns\n        -------\n        loss : `list`\n            List containing the loss on the training set at each iteration\n\n        acc : `list`\n            List containing the accuracy on the training set at each iteraton\n\n        \"\"\"\n\n        # Add a first dimension of ones corresponding to the intercept\n        x = np.hstack((np.ones([X.shape[0], 1]), X))\n\n        loss = []\n        acc = []\n        for _ in range(iterations):\n            # Forward pass\n            z = np.matmul(x, self.w)\n            y_hat = sigmoid(z)\n\n            loss.append(self.loss(y, y_hat))\n            acc.append(np.mean(np.around(y_hat) == y))\n\n            # Gradients\n            dz = y_hat - y\n            dw = np.matmul(x.T, dz)\n\n            self.w -= learning_rate*dw\n\n        return loss, acc\n\n    def predict(self, X):\n        \"\"\"Predicts the response using the current estimands.\n\n        Parameters\n        ----------\n        X : `numpy.ndarray` (n_examples, n_features)\n            Data from where to infer a prediction\n\n        Returns\n        -------\n        predicted : `numpy.ndarray` (n_examples,)\n            Predicted probabilities for each data example\n\n        \"\"\"\n\n        X = np.atleast_2d(X)\n        X = np.reshape(X, [-1, self.n_features])\n\n        # Add a first dimension of ones corresponding to the intercept\n        X = np.hstack((np.ones([X.shape[0], 1]), X))\n        return sigmoid(np.matmul(X, self.w))\n\n    def loss(self, y, y_hat):\n        # Return loss to minimize by gradient descent.\n        return -(1.0/len(y))*log_likelihood(y, y_hat)\n", "meta": {"hexsha": "786a4c0a58f5a35cef9a935c24c9112e3712f4d8", "size": 3010, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/logistic_regression.py", "max_stars_repo_name": "SergioAlvarezB/ml-numpy", "max_stars_repo_head_hexsha": "bf450b0d48b52c56fd3d124a5b41f2b99594ea3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/logistic_regression.py", "max_issues_repo_name": "SergioAlvarezB/ml-numpy", "max_issues_repo_head_hexsha": "bf450b0d48b52c56fd3d124a5b41f2b99594ea3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/logistic_regression.py", "max_forks_repo_name": "SergioAlvarezB/ml-numpy", "max_forks_repo_head_hexsha": "bf450b0d48b52c56fd3d124a5b41f2b99594ea3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1308411215, "max_line_length": 79, "alphanum_fraction": 0.5830564784, "include": true, "reason": "import numpy", "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778061099871, "lm_q2_score": 0.9019206666433899, "lm_q1q2_score": 0.8633886370496413}}
{"text": "from sympy import *\n\n# If an object is dropped from a 155​-foot-high ​building, its position​ (in feet above the​ ground) is given by ​s(t)​, where t is the time in seconds since it was dropped.\n\nt = symbols( 't' )\nS = -16*t**2 + 186\n\ndS = diff( S, t )\n\n# The​ object's velocity 1 second after being dropped is \none_s = dS.subs( { t: 1 } )\none_s\n\n# The object will hit the ground in:\nground = solve( S, t )[ 1 ].evalf()\n# ​(Round to the nearest tenth as​ needed.)\nround( ground, 1 )\n\n# The​ object's velocity upon impact is:\nimpact_velocity = dS.subs( { t: ground } )\n# (Round to the nearest tenth as​ needed.)\nround( impact_velocity, 1 )", "meta": {"hexsha": "2affa57d9aba71d632a9004cce34f140df53fe6a", "size": 638, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Quiz/III/06.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Quiz/III/06.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Quiz/III/06.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0, "max_line_length": 173, "alphanum_fraction": 0.6661442006, "include": true, "reason": "from sympy", "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846703886662, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.8633539063382267}}
{"text": "import numpy as np\n\n# Collection of activation functions\n# Reference: https://en.wikipedia.org/wiki/Activation_function\n\nclass Sigmoid():\n    def __call__(self, x):\n        return 1 / (1 + np.exp(-x))\n\n    def gradient(self, x):\n        return self.__call__(x) * (1 - self.__call__(x))\n\nclass Softmax():\n    def __call__(self, x):\n        e_x = np.exp(x - np.max(x, axis=-1, keepdims=True))\n        return e_x / np.sum(e_x, axis=-1, keepdims=True)\n\n    def gradient(self, x):\n        p = self.__call__(x)\n        return p * (1 - p)\n\nclass TanH():\n    def __call__(self, x):\n        return 2 / (1 + np.exp(-2*x)) - 1\n\n    def gradient(self, x):\n        return 1 - np.power(self.__call__(x), 2)\n\nclass ReLU():\n    def __call__(self, x):\n        return np.where(x >= 0, x, 0)\n\n    def gradient(self, x):\n        return np.where(x >= 0, 1, 0)\n\nclass LeakyReLU():\n    def __init__(self, alpha=0.2):\n        self.alpha = alpha\n\n    def __call__(self, x):\n        return np.where(x >= 0, x, self.alpha * x)\n\n    def gradient(self, x):\n        return np.where(x >= 0, 1, self.alpha)\n\nclass ELU():\n    def __init__(self, alpha=0.1):\n        self.alpha = alpha \n\n    def __call__(self, x):\n        return np.where(x >= 0.0, x, self.alpha * (np.exp(x) - 1))\n\n    def gradient(self, x):\n        return np.where(x >= 0.0, 1, self.__call__(x) + self.alpha)\n\nclass SELU():\n    # Reference : https://arxiv.org/abs/1706.02515,\n    # https://github.com/bioinf-jku/SNNs/blob/master/SelfNormalizingNetworks_MLP_MNIST.ipynb\n    def __init__(self):\n        self.alpha = 1.6732632423543772848170429916717\n        self.scale = 1.0507009873554804934193349852946 \n\n    def __call__(self, x):\n        return self.scale * np.where(x >= 0.0, x, self.alpha*(np.exp(x)-1))\n\n    def gradient(self, x):\n        return self.scale * np.where(x >= 0.0, 1, self.alpha * np.exp(x))\n\nclass SoftPlus():\n    def __call__(self, x):\n        return np.log(1 + np.exp(x))\n\n    def gradient(self, x):\n        return 1 / (1 + np.exp(-x))\n\n", "meta": {"hexsha": "d9f54921c107ccf1446e3b708d1bdfc005fa4024", "size": 1992, "ext": "py", "lang": "Python", "max_stars_repo_path": "mlfromscratch/deep_learning/activation_functions.py", "max_stars_repo_name": "leeh8911/ML-From-Scratch", "max_stars_repo_head_hexsha": "9b9c94e2f8fbbefa60d3481c23180f1852fae506", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22453, "max_stars_repo_stars_event_min_datetime": "2017-02-17T08:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:45:01.000Z", "max_issues_repo_path": "mlfromscratch/deep_learning/activation_functions.py", "max_issues_repo_name": "oceanofinfinity/ML-From-Scratch", "max_issues_repo_head_hexsha": "a2806c6732eee8d27762edd6d864e0c179d8e9e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 75, "max_issues_repo_issues_event_min_datetime": "2017-02-25T23:55:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T04:15:08.000Z", "max_forks_repo_path": "mlfromscratch/deep_learning/activation_functions.py", "max_forks_repo_name": "oceanofinfinity/ML-From-Scratch", "max_forks_repo_head_hexsha": "a2806c6732eee8d27762edd6d864e0c179d8e9e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4496, "max_forks_repo_forks_event_min_datetime": "2017-02-25T16:52:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:42:54.000Z", "avg_line_length": 26.2105263158, "max_line_length": 92, "alphanum_fraction": 0.5868473896, "include": true, "reason": "import numpy", "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551495568568, "lm_q2_score": 0.894789468908171, "lm_q1q2_score": 0.8633422268452938}}
{"text": "import numpy as np\n\n\nclass NumMethods:\n    \"\"\"\n    Methods of numerical differentiation and integration.\n\n        - Differentiation: Forward differences, endpoint and midpoint 3 and 5 point differences,\n                           second derivative midpoint\n\n        - Integration: Trapezoid rule (composite), Simpson's rule (composite + adaptive),\n                       Gaussian quadrature (adaptive)\n    \"\"\"\n\n    def __init__(self, func=None):\n        self.func = func\n\n    def for_diff(self, x, h=10**(-5)):\n        \"\"\"\n          Forward Differences: Approximates f'(x) using (f(x+h)-f(x))/h for very small h.\n\n          Args:\n              x (float): Approximation point\n              h (float): Increment\n\n          Returns:\n              float: f'(x) approximation\n          \"\"\"\n        return (self.func(x + h) - self.func(x))/h\n\n    def end_3diff(self, x, h=10**(-5)):\n        \"\"\"\n          Three-Point Endpoint: Approximates f'(x)\n\n          Args:\n              x (float): Approximation point\n              h (float): Increment\n\n          Returns:\n              float: f'(x) approximation\n          \"\"\"\n        return (-3*self.func(x) + 4*self.func(x+h) - self.func(x+2*h))/(2*h)\n\n    def mid_3diff(self, x, h=10**(-5)):\n        \"\"\"\n          Three-Point Midpoint: Approximates f'(x)\n\n          Args:\n              x (float): Approximation point\n              h (float): Increment\n\n          Returns:\n              float: f'(x) approximation\n          \"\"\"\n        return (self.func(x+h) - self.func(x-h))/(2*h)\n\n    def end_5diff(self, x, h=10**(-5)):\n        \"\"\"\n          Five-Point Endpoint: Approximates f'(x)\n\n          Args:\n              x (float): Approximation point\n              h (float): Increment\n\n          Returns:\n              float: f'(x) approximation\n          \"\"\"\n        return (-25*self.func(x) + 48*self.func(x+h) - 36*self.func(x+2*h) +\n                16*self.func(x+3*h) - 3*self.func(x+4*h))/(12*h)\n\n    def mid_5diff(self, x, h=10**(-5)):\n        \"\"\"\n          Five-Point Midpoint: Approximates f'(x)\n\n          Args:\n              x (float): Approximation point\n              h (float): Increment\n\n          Returns:\n              float: f'(x) approximation\n          \"\"\"\n        return (self.func(x-2*h) - 8*self.func(x-h) + 8*self.func(x+h) -\n                self.func(x+2*h))/(12*h)\n\n    def second_diff(self, x, h=10**(-5)):\n        \"\"\"\n          Second Derivative Midpoint: Approximates f''(x)\n\n          Args:\n              x (float): Approximation point\n              h (float): Increment\n\n          Returns:\n              float: f''(x) approximation\n          \"\"\"\n        return (self.func(x-h) - 2*self.func(x) + self.func(x+h))/(h**2)\n\n    def trapezoid_rule(self, a, b):\n        \"\"\"\n          Approximate area under f(x) within [a,b] using a trapezoid.\n\n          Args:\n              a (float): Defines [a,b] integration bounds\n              b (float): Defines [a,b] integration bounds\n\n          Returns:\n              float: int_(a,b)f(x)dx approximation\n          \"\"\"\n        return ((b-a)/2) * (self.func(a) + self.func(b))\n\n    def trap_comp(self, a, b, n=10):\n        \"\"\"\n          Composite trapezoid rule approximation of int_(a,b)f(x)dx by summing\n          trapezoidal approximations for n sub intervals.\n\n          Args:\n              a (float): Defines [a,b] integration bounds\n              b (float): Defines [a,b] integration bounds\n              n (int): Number of sub intervals. Must be an even integer\n\n          Returns:\n              float: int_(a,b)f(x)dx approximation\n          \"\"\"\n        h = (b-a)/n\n        mid_terms = 0\n        for i in range(n):\n            mid_terms += self.func(a+i*h)\n        return (h/2) * (self.func(a) + 2*mid_terms + self.func(b))\n\n    def simpsons_rule(self, a, b):\n        \"\"\"\n          Simpson's rule approximation of int_(a,b)f(x)dx.\n\n          Args:\n              a (float): Defines [a,b] integration bounds\n              b (float): Defines [a,b] integration bounds\n\n          Returns:\n              float: int_(a,b)f(x)dx approximation\n          \"\"\"\n        h = (b-a)/2\n        return (h/3) * (self.func(a) + 4*self.func((b+a)/2) + self.func(b))\n\n    def simp_comp(self, a, b, n=10):\n        \"\"\"\n          Composite Simpson's rule approximation of int_(a,b)f(x)dx by applying\n          Simpson's rule over n sub intervals.\n\n          Args:\n              a (float): Defines [a,b] integration bounds\n              b (float): Defines [a,b] integration bounds\n              n (int): Number of sub intervals. Must be an even integer\n\n          Returns:\n              float: int_(a,b)f(x)dx approximation\n          \"\"\"\n        h = (b-a)/n\n        x_0 = self.func(a) + self.func(b)\n        x_odd = 0\n        x_even = 0\n        for i in range(1, n):\n            x = a + i*h\n            if i % 2 == 0:\n                x_even += self.func(x)\n            else:\n                x_odd += self.func(x)\n        xi = h*(x_0 + 2*x_even + 4*x_odd)/3\n        return xi\n\n    def simp_adpt(self, a, b, tol=10**(-5), n_0=20):\n        \"\"\"\n          Adaptive Simpson's rule approximation of int_(a,b)f(x)dx.\n\n          Args:\n              a (float): Defines [a,b] integration bounds\n              b (float): Defines [a,b] integration bounds\n              tol (float): Error tolerance\n              n_0 (int): Max sub interval depth\n\n          Returns:\n              float: int_(a,b) f(x)dx approximation\n          \"\"\"\n        approx = 0\n        i = 0\n        e, a0, h, fa, fc, fb, s, l = np.zeros((8, n_0))\n        e[i] = 10*tol\n        a0[i] = a\n        h[i] = (b-a)/2\n        fa[i] = self.func(a)\n        fc[i] = self.func(a+h[i])\n        fb[i] = self.func(b)\n        s[i] = h[i]*(fa[i] + 4*fc[i] + fb[i])/3\n        l[i] = 1\n        while i > -1:\n            fd = self.func(a0[i] + h[i]/2)\n            fe = self.func(a0[i] + 3*h[i]/2)\n            s1 = h[i]*(fa[i] + 4*fd + fc[i])/6\n            s2 = h[i]*(fc[i] + 4*fe + fb[i])/6\n            v1 = a0[i]\n            v2 = fa[i]\n            v3 = fc[i]\n            v4 = fb[i]\n            v5 = h[i]\n            v6 = e[i]\n            v7 = s[i]\n            v8 = l[i]\n            i -= 1\n\n            if abs(s1 + s2 - v7) < v6:\n                approx += s1 + s2\n            elif v8 >= n_0:\n                print(\"Level exceeded\")\n                return approx\n            else:\n                i += 1\n\n                a0[i] = v1 + v5\n                fa[i] = v3\n                fc[i] = fe\n                fb[i] = v4\n                h[i] = v5/2\n                e[i] = v6/2\n                s[i] = s2\n                l[i] = v8 + 1\n\n                i += 1\n\n                a0[i] = v1\n                fa[i] = v2\n                fc[i] = fd\n                fb[i] = v3\n                h[i] = h[i-1]\n                e[i] = e[i-1]\n                s[i] = s1\n                l[i] = l[i-1]\n        return approx\n\n    def gquad(self, a, b):\n        \"\"\"\n          Two-point Gaussian quadrature formula for approximating int_(a,b)f(x)dx where\n          [a,b] is a general interval. Derived from the approximation\n          int_(-1,1) f(x)dx (approximately)= f( -sqrt(3)/3 ) - f( sqrt(3)/3 )\n\n          Args:\n              a (float): Defines [a,b] integration bounds\n              b (float): Defines [a,b] integration bounds\n\n          Returns:\n              float: int_(a,b)f(x)dx approximation\n          \"\"\"\n        return (self.func((1/2) * ((b-a) * (-np.sqrt(3)/3) + a+b)) +\n                self.func((1/2) * ((b-a) * (np.sqrt(3)/3) + a+b))) * (b-a)/2\n\n    def gquad_adpt(self, a, b, level=0, current_sum=0, n_0=20, tol=10**(-7)):\n        \"\"\"\n          Adaptive two-point Gaussian quadrature. Applies two-point Gaussian quadrature on sub intervals\n          from splitting [a,b] until specified level of precision is reached.\n\n          Args:\n              a (float): Defines [a,b] integration bounds\n              b (float): Defines [a,b] integration bounds\n              level (int): Counts interval split depth\n              current_sum (float): Current interval approximation\n              n_0 (int): Max depth\n              tol (float): Error tolerance\n\n          Returns:\n              float: int_(a,b)f(x)dx approximation\n          \"\"\"\n        level += 1\n        one_gauss = self.gquad(a, b)\n        c = (a+b)/2\n        two_gauss = self.gquad(a, c) + self.gquad(c, b)\n        if level > n_0:\n            print(\"Max depth reached\")\n        else:\n            if abs(one_gauss - two_gauss) < tol:\n                current_sum += two_gauss\n            else:\n                current_sum = self.gquad_adpt(a, c, level=level, current_sum=current_sum, n_0=n_0)\n                current_sum = self.gquad_adpt(c, b, level=level, current_sum=current_sum, n_0=n_0)\n        return current_sum\n", "meta": {"hexsha": "47656c3aadb5c9300aa83a435680651bb0fac6a9", "size": 8698, "ext": "py", "lang": "Python", "max_stars_repo_path": "nanalysis/num_methods.py", "max_stars_repo_name": "mwstrand/numerical-analysis", "max_stars_repo_head_hexsha": "00adb5bead9c19274f503dd5426b9e0be8408f1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nanalysis/num_methods.py", "max_issues_repo_name": "mwstrand/numerical-analysis", "max_issues_repo_head_hexsha": "00adb5bead9c19274f503dd5426b9e0be8408f1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nanalysis/num_methods.py", "max_forks_repo_name": "mwstrand/numerical-analysis", "max_forks_repo_head_hexsha": "00adb5bead9c19274f503dd5426b9e0be8408f1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7349823322, "max_line_length": 104, "alphanum_fraction": 0.4649344677, "include": true, "reason": "import numpy", "num_tokens": 2342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551566309689, "lm_q2_score": 0.8947894590884704, "lm_q1q2_score": 0.863342223700546}}
{"text": "import numpy as np\n\n\ndef tanh(x):\n    t = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))\n    dt = 1 - t ** 2\n    return t, dt\n\n\nx1 = -0.928\nt1, dt1 = tanh(x1)\nprint(\"------------------------------------------------\")\nprint(\"The tansigmoid of x1: \", t1)\nprint(\"The derivative of tansigmoid of x1: \", dt1)\nprint(\"------------------------------------------------\")\n", "meta": {"hexsha": "a3f243d1daee154d6973bd25b711af36dbfa5a20", "size": 367, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/models/util/TanSigmoid.py", "max_stars_repo_name": "sanatanonline/ml", "max_stars_repo_head_hexsha": "bed8c45913f8b85af35f0c6f1ea6099e744a78f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/models/util/TanSigmoid.py", "max_issues_repo_name": "sanatanonline/ml", "max_issues_repo_head_hexsha": "bed8c45913f8b85af35f0c6f1ea6099e744a78f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/util/TanSigmoid.py", "max_forks_repo_name": "sanatanonline/ml", "max_forks_repo_head_hexsha": "bed8c45913f8b85af35f0c6f1ea6099e744a78f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9375, "max_line_length": 59, "alphanum_fraction": 0.408719346, "include": true, "reason": "import numpy", "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551546097941, "lm_q2_score": 0.894789454880027, "lm_q1q2_score": 0.8633422178314819}}
{"text": "#!/usr/bin/env python\n# Author: Andrew Jewett (jewett.aij at g mail)\n# License: MIT License  (See LICENSE.md)\n# Copyright (c) 2020, Scripps Research\n# All rights reserved.\n\n\"\"\"\n   A crude command line utility which reads the coordinates of 3 points,\n   finds the circle which passes through them, and returns the center\n   and the radius of that circle.\n\n   Usage:\n\n     curvature3pts.py < coordinates.txt\n\n   Details:\n\n     This program reads a text file from the standard input in multi-column\n   format, with N numbers on each line delimited by spaces. (Usually N=2 or 3.)\n   This file should contain exactly 3 lines (corresponding to the 3 points\n   on the circle).\n\n   This program works in an arbitrary number of dimensions.\n   (The number of dimensions is specified by the number of columns in the file.)\n   \n\"\"\"\n\nfrom math import *\nimport sys\nimport numpy as np\n\n\ndef CircleFrom3Points2D(r1, r2, r3):\n    \"\"\"\n    3 points pass through a circle.  Find the center of that circle\n    and its radius.  3 eqns (below) with 3 unknowns (x0, y0, r)\n       (x1 - x0)^2 + (y1 - y0)^2  =  r^2\n       (x2 - x0)^2 + (y2 - y0)^2  =  r^2\n       (x3 - x0)^2 + (y3 - y0)^2  =  r^2\n    Solve for (x0, y0) using A * (x0, y0) = B where:\n    \"\"\"\n    B = np.array([r2[0]**2 - r1[0]**2 + \n                  r2[1]**2 - r1[1]**2,\n                  r3[0]**2 - r2[0]**2 + \n                  r3[1]**2 - r2[1]**2])\n    A = np.array([[2.0 * (r2[0] - r1[0]),\n                   2.0 * (r2[1] - r1[1])],\n                  [2.0 * (r3[0] - r2[0]),\n                   2.0 * (r3[1] - r2[1])]])\n    x0, y0 = np.linalg.solve(A,B)\n    r = sqrt((r1[0] - x0)**2 + (r1[1] - y0)**2)\n    return r, x0, y0\n\n\n\ndef CircleFrom3Points(r1, r2, r3):\n    \"\"\" \n    This is the N-dimensional generalization of CircleFrom3Points2D().\n    (It works in 3D and also higher dimensions.\n     This function is not necessary for \"sabl.py\" which is a 2D program.\n     Consequently, I never got around to testing it carefully. \n     Hopefully this function works, but test it first.  -A 2020-6-10)\n    \"\"\"\n\n    # Decompose this into a 2D problem using Graham-Schmidt decomposition\n    # of the original vectors into the basis defined by va=r1-r2 and vb=r3-r2.\n    # Then apply CircleFrom3Points2D() to find the radius of curvature\n    # and the central point.\n\n    va = r1-r2\n    vb = r3-r2\n\n    ea = va / np.linalg.norm(va)\n    eb = vb - np.inner(vb,ea)*ea\n    eb /= np.linalg.norm(eb)\n\n    # Now express the vectors r1-r2, r2-r2, and r3-r2\n    # in the basis formed by unit vectors ea and eb.\n    # The resutling _r1, _r2, _r3 vectors are 2D vectors.\n    \n    _r1 = np.array([np.inner(va, ea), np.inner(va, eb)])\n    _r2 = np.array(r2-r2)  # (this should be the zero vector)\n    _r3 = np.array([np.inner(vb, ea), np.inner(vb, eb)])\n\n    # Now invoke \"CircleFrom3Points2D()\" to calculate the radius and center\n    # of the circle in this 2D coordinate system\n    r, x0, y0 =  CircleFrom3Points2D(_r1, _r2, _r3)\n\n    # Now convert x0, y0 back into the original coordinate system\n    r0 = r2 + x0*ea + y0*eb\n\n    # Now return the results to the caller\n    return r, r0\n\n\n\ndef main():\n    lines = sys.stdin.readlines()\n\n    # r1 r2 and r3 are arrays containing the xyz coordinates of the 3 points\n    r1 = np.array(list(map(float, lines[0].strip().split())))  #x,y,z of point 1\n    r2 = np.array(list(map(float, lines[1].strip().split())))  #x,y,z of point 2\n    r3 = np.array(list(map(float, lines[2].strip().split())))  #x,y,z of point 3\n\n    radius, center = CircleFrom3Points(r1, r2, r3)\n\n    sys.stdout.write('circle_center =')\n    for i in range(0, center.size):\n        sys.stdout.write(' '+str(center[i]))\n    sys.stdout.write('\\n')\n\n    sys.stdout.write('radius = '+str(radius)+'\\n')\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "51ea99943e14c73c96abd24a3e5073b4672489ff", "size": 3773, "ext": "py", "lang": "Python", "max_stars_repo_path": "sabl_mpl/curvature3pts.py", "max_stars_repo_name": "jewettaij/sabl_mpl", "max_stars_repo_head_hexsha": "af7ee89e1124b630114dc9db5d378f457533d558", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-04-24T13:00:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-10T16:56:35.000Z", "max_issues_repo_path": "sabl_mpl/curvature3pts.py", "max_issues_repo_name": "jewettaij/sabl_mpl", "max_issues_repo_head_hexsha": "af7ee89e1124b630114dc9db5d378f457533d558", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-03T05:51:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-15T23:45:39.000Z", "max_forks_repo_path": "sabl_mpl/curvature3pts.py", "max_forks_repo_name": "jewettaij/sabl_mpl", "max_forks_repo_head_hexsha": "af7ee89e1124b630114dc9db5d378f457533d558", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-04-24T13:00:54.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-24T13:00:54.000Z", "avg_line_length": 32.525862069, "max_line_length": 80, "alphanum_fraction": 0.6087993639, "include": true, "reason": "import numpy", "num_tokens": 1213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.974821163419856, "lm_q2_score": 0.8856314768368161, "lm_q1q2_score": 0.8633323066113103}}
{"text": "# https://github.com/llSourcell/Intro_to_the_Math_of_intelligence\n# Create a linear regression model and train using Gradient Descent from scratch.\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndatapath = \"data.csv\"\nalpha = 3e-5         # learning rate\nnum_iter = 100     # number of iterations for gradient descent\n\ndef data_process(path):\n    \"Import and preprocess data\"\n    df = pd.read_csv(path)\n    df = df.reindex(np.random.permutation(df.index))\n    return df\n'''\ndef randomize(df):\n    \"Randomly shuffle the items of data\"\n    r_data = df.reindex(np.random.permutation(df.index))\n    return r_data\n'''\ndef gradient_descent(x, y, N, m, b, alpha, num_iter):\n    \"Optimize the model using Gradient Descent algorithm\"\n    loss_info = []\n    inter_loss = 0\n    for i in range(num_iter):\n        b_loss = 0\n        m_loss = 0\n        for j in range(N):\n            y_pred = m * x[j] + b\n            b_loss += (y[j] - y_pred)\n            m_loss += (y[j] - y_pred) * x[j]\n\n        m = m - alpha * (-2/float(N) * m_loss)\n        b = b - alpha * (-2/float(N) * b_loss)\n\n        for k in range(N):\n            y_pred = m * x[k] + b\n            inter_loss += (y_pred - y[k])**2\n        inter_loss = inter_loss / float(N)\n        loss_info.append([i, inter_loss])\n\n    return m, b, loss_info\n\ndef linear_regressor(r_data):\n    \"Create a linear regression model\"\n    \n    x = r_data[\"Distance cycled\"]\n    y = r_data[\"Calories burnt\"]\n    N = len(r_data)\n    m_init = 0    #1.4\n    b_init = 0\n    loss = 0\n\n    m, b, loss_info = gradient_descent(x, y, N, m_init, b_init, alpha, num_iter)\n    print \"m, b, alpha = %0.7s, %0.7s, %s\" % (m, b, alpha)\n\n    for i in range(N):\n        #y_pred = m_init * x[i] + b_init\n        y_pred = m * x[i] + b\n        loss += (y_pred - y[i])**2\n\n    final_loss = loss / float(N)\n    return final_loss, loss_info, m, b\n\ndef plot_loss(loss_info):\n    iter_no = []\n    loss_value = []\n    for item in loss_info:\n        iter_no.append(item[0])\n        loss_value.append(item[1])\n    \n    plt.plot(iter_no, loss_value)\n    plt.show()\n\n\ndef main():\n    data = data_process(datapath)\n    avg_loss, loss_info, slope, intercept = linear_regressor(data)\n    #plot_loss(loss_info)\n\n    x = data[\"Distance cycled\"]\n    y = data[\"Calories burnt\"]\n    y_pred = slope * x + intercept\n    \n    x_new = [72, 73.5, 74.9, 76.5, 78.5, 80]\n    y_new = [(slope * i + intercept) for i in x_new]\n    \n    plt.plot(x, y, 'ro', x, y_pred, x_new, y_new, 'bs')\n    plt.show()\n    \n    print \"Final avg loss = %s\" % avg_loss\n\nif __name__ == '__main__':\n    main()\n\n'''\nResults-\nm, b, alpha = 1.478566841371454, 0.047075978779471006, 0.0003\nFinal loss = 112.639852759\n'''", "meta": {"hexsha": "94953ad1440348d1ff866dc956ad1bedf46bc6b7", "size": 2696, "ext": "py", "lang": "Python", "max_stars_repo_path": "Intro_Gradient_Descent/mycode.py", "max_stars_repo_name": "DillipKS/The-Math-of-Intelligence-course", "max_stars_repo_head_hexsha": "fc0f33e638fdbd05e93d54d38ed8493808f6ec74", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Intro_Gradient_Descent/mycode.py", "max_issues_repo_name": "DillipKS/The-Math-of-Intelligence-course", "max_issues_repo_head_hexsha": "fc0f33e638fdbd05e93d54d38ed8493808f6ec74", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Intro_Gradient_Descent/mycode.py", "max_forks_repo_name": "DillipKS/The-Math-of-Intelligence-course", "max_forks_repo_head_hexsha": "fc0f33e638fdbd05e93d54d38ed8493808f6ec74", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-08T07:58:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-08T07:58:13.000Z", "avg_line_length": 26.431372549, "max_line_length": 81, "alphanum_fraction": 0.5949554896, "include": true, "reason": "import numpy", "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211546419275, "lm_q2_score": 0.8856314738181875, "lm_q1q2_score": 0.8633322958946775}}
{"text": "# Copyright 2016 Enthought, Inc. All Rights Reserved\n\"\"\"\nTopics: NumPy array indexing and array math.\n\nUse array slicing and math operations to calculate the\nnumerical derivative of ``sin`` from 0 to ``2*pi``.  There is no\nneed to use a for loop for this.\n\nPlot the resulting values and compare to ``cos``.\n\nBonus\n~~~~~\n\nImplement integration of the same function using Riemann sums or the\ntrapezoidal rule.\n\n\"\"\"\nfrom numpy import linspace, pi, sin, cos, cumsum\nfrom matplotlib.pyplot import plot, show, subplot, legend, title\n\n# calculate the sin() function on evenly spaced data.\nx = linspace(0,2*pi,101)\ny = sin(x)\n\n# calculate the derivative dy/dx numerically.\n# First, calculate the distance between adjacent pairs of\n# x and y values.\ndy = y[1:]-y[:-1]\ndx = x[1:]-x[:-1]\n\n# Now divide to get \"rise\" over \"run\" for each interval.\ndy_dx = dy/dx\n\n# Assuming central differences, these derivative values\n# centered in-between our original sample points.\ncenters_x = (x[1:]+x[:-1])/2.0\n\n# Plot our derivative calculation.  It should match up\n# with the cos function since the derivative of sin is\n# cos.\nsubplot(1,2,1)\nplot(centers_x, dy_dx,'rx', centers_x, cos(centers_x),'b-')\ntitle(r\"$\\rm{Derivative\\ of}\\ sin(x)$\")\n\n# Trapezoidal rule integration.\navg_height = (y[1:]+y[:-1])/2.0\nint_sin = cumsum(dx * avg_height)\n\n# Plot our integration against -cos(x) - -cos(0)\nclosed_form = -cos(x)+cos(0)\nsubplot(1,2,2)\nplot(x[1:], int_sin,'rx', x, closed_form,'b-')\nlegend(('numerical', 'actual'))\ntitle(r\"$\\int \\, \\sin(x) \\, dx$\")\nshow()\n", "meta": {"hexsha": "ce5d105f98ee0efc0d678df132f7c0083d98da9e", "size": 1533, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numpy-Tutorial-SciPyConf-2016/exercises/calc_derivative/calc_derivative_solution.py", "max_stars_repo_name": "sunny2309/scipy_conf_notebooks", "max_stars_repo_head_hexsha": "30a85d5137db95e01461ad21519bc1bdf294044b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-09T15:57:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T01:44:21.000Z", "max_issues_repo_path": "Numpy-Tutorial-SciPyConf-2016/exercises/calc_derivative/calc_derivative_solution.py", "max_issues_repo_name": "sunny2309/scipy_conf_notebooks", "max_issues_repo_head_hexsha": "30a85d5137db95e01461ad21519bc1bdf294044b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-11-15T02:00:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T04:26:40.000Z", "max_forks_repo_path": "Numpy-Tutorial-SciPyConf-2016/exercises/calc_derivative/calc_derivative_solution.py", "max_forks_repo_name": "sunny2309/scipy_conf_notebooks", "max_forks_repo_head_hexsha": "30a85d5137db95e01461ad21519bc1bdf294044b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.375, "max_line_length": 68, "alphanum_fraction": 0.7025440313, "include": true, "reason": "from numpy", "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104962847373, "lm_q2_score": 0.8933094025038598, "lm_q1q2_score": 0.8633035830095773}}
{"text": "import numpy as np \nimport matplotlib.pyplot as plt\n\ndef estimate_coefficients(x, y): \n    # size of the dataset OR number of observations/points \n    n = np.size(x) \n  \n    # mean of x and y\n    # Since we are using numpy just calling mean on numpy is sufficient \n    mean_x, mean_y = np.mean(x), np.mean(y) \n  \n    # calculating cross-deviation and deviation about x \n    SS_xy = np.sum(y*x - n*mean_y*mean_x) \n    SS_xx = np.sum(x*x - n*mean_x*mean_x) \n  \n    # calculating regression coefficients \n    b_1 = SS_xy / SS_xx \n    b_0 = mean_y - b_1*mean_x \n  \n    return(b_0, b_1)\n\n    # x,y are the location of points on graph\n    # color of the points change it to red blue orange play around\n\n\n\ndef plot_regression_line(x, y, b): \n    # plotting the points as per dataset on a graph\n    plt.scatter(x, y, color = \"m\",marker = \"o\", s = 30) \n\n    # predicted response vector \n    y_pred = b[0] + b[1]*x \n  \n    # plotting the regression line\n    plt.plot(x, y_pred, color = \"g\")\n  \n    # putting labels for x and y axis\n    plt.xlabel('Size') \n    plt.ylabel('Cost') \n  \n    # function to show plotted graph\n    plt.show()\n    \n\n    \n\n\ndef main(): \n    # Datasets which we create \n    x = np.array([ 1,   2,   3,   4,   5,   6,   7,   8,    9,   10]) \n    y = np.array([300, 350, 500, 700, 800, 850, 900, 900, 1000, 1200]) \n  \n    # estimating coefficients \n    b = estimate_coefficients(x, y) \n    print(\"Estimated coefficients:\\nb_0 = {} \\nb_1 = {}\".format(b[0], b[1])) \n  \n    # plotting regression line \n    plot_regression_line(x, y, b)\n\n    \nif __name__ == \"__main__\": \n    main()\n\n", "meta": {"hexsha": "ed1c56d7aef9e35a05f53780b1c868445d067a64", "size": 1590, "ext": "py", "lang": "Python", "max_stars_repo_path": "SimpleLinearRegression.py", "max_stars_repo_name": "Amine-Smahi/Linear-Regression", "max_stars_repo_head_hexsha": "18f967ea677b1a858e83da182a03fcf4658ee2ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-11-05T09:03:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T10:38:18.000Z", "max_issues_repo_path": "SimpleLinearRegression.py", "max_issues_repo_name": "Amine-Smahi/Linear-Regression", "max_issues_repo_head_hexsha": "18f967ea677b1a858e83da182a03fcf4658ee2ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SimpleLinearRegression.py", "max_forks_repo_name": "Amine-Smahi/Linear-Regression", "max_forks_repo_head_hexsha": "18f967ea677b1a858e83da182a03fcf4658ee2ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.84375, "max_line_length": 77, "alphanum_fraction": 0.6025157233, "include": true, "reason": "import numpy", "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104962847373, "lm_q2_score": 0.8933093982432729, "lm_q1q2_score": 0.8633035788921014}}
{"text": "# The population of salmon next year is given by\n# f(S) = Se^r(1 - S / P ),\n# where:\n# S is this years' salmon population, \n# P is the equilibrium population,\n# r is a constant that depends upon how fast the population grows.\n\n# Find f'(S0) and solve the equation f'( S0 ) = 1.\n# Graph f'(S0) and y = 1.\n\n# Find the population for which the maximum sustainable harvest occurs if r = 0.4 and P = 850\n\nimport math\nfrom sympy import solve, lambdify, symbols, diff, pprint, pretty, simplify, exp\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nS = symbols( 'S' )\nr, P = 0.4, 850\n\nF = S * exp( r *( 1 - S / P ) )\n\ndF = diff( F, S )\n\n# intersection = round( solve( dF - 1, S )[ 0 ], 3 )\n\n# Graph\n\ndomain_end = 20\n\ng_xlim = [ 0, 500 ]\ng_ylim = [-5, 10 ]\n\nlam_x = lambdify( S, dF, np )\n\nx_vals = np.linspace( g_xlim[0], g_xlim[1], 1000, endpoint=True )\ny_vals = lam_x( x_vals )\n\nplt.plot( x_vals, y_vals, label = '' )\nplt.hlines( y = 1, xmin = g_xlim[ 0 ], xmax = g_xlim[ 1 ], color = 'Orange', zorder = 1 )\nplt.scatter( intersection, 1, color = 'R' )\nplt.show()", "meta": {"hexsha": "1975f56101ba2f54b148ac784ec42af3739720bc", "size": 1058, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Module 6/salmon_population.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Module 6/salmon_population.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Module 6/salmon_population.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1904761905, "max_line_length": 93, "alphanum_fraction": 0.6379962193, "include": true, "reason": "import numpy,from sympy", "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966410491447634, "lm_q2_score": 0.8933094017937621, "lm_q1q2_score": 0.8633035780023015}}
{"text": "import numpy as numpy\nfrom  scipy.special import factorial\n\ndef fdcoeffV(k,xbar,x):\n    \"\"\"\n    fdcoeffV routine modified from Leveque (2007) matlab function\n    \n    Params:\n    -------\n    \n    k: int\n        order of derivative\n    xbar: float\n        point at which derivative is to be evaluated\n    x: ndarray\n        numpy array of coordinates to use in calculating the weights\n    \n    Returns:\n    --------\n    c: ndarray\n        array of floats of coefficients.  \n\n    Compute coefficients for finite difference approximation for the\n    derivative of order k at xbar based on grid values at points in x.\n\n    WARNING: This approach is numerically unstable for large values of n since\n    the Vandermonde matrix is poorly conditioned.  Use fdcoeffF.m instead,\n    which is based on Fornberg's method.\n\n     This function returns a row vector c of dimension 1 by n, where n=length(x),\n     containing coefficients to approximate u^{(k)}(xbar), \n     the k'th derivative of u evaluated at xbar,  based on n values\n     of u at x(1), x(2), ... x(n).  \n\n     If U is an array containing u(x) at these n points, then \n     c.dot(U) will give the approximation to u^{(k)}(xbar).\n\n     Note for k=0 this can be used to evaluate the interpolating polynomial \n     itself.\n\n    Requires len(x) > k.  \n    Usually the elements x(i) are monotonically increasing\n    and x(1) <= xbar <= x(n), but neither condition is required.\n    The x values need not be equally spaced but must be distinct.  \n    \n    Modified rom  http://www.amath.washington.edu/~rjl/fdmbook/  (2007)\n    \"\"\"\n    \n\n    n = x.shape[0]\n    assert  k < n, \" The order of the derivative must be less than the stencil width\"\n\n    # Generate the Vandermonde matrix from the Taylor series\n    A = numpy.ones((n,n))\n    xrow = (x - xbar)  # displacements x-xbar \n    for i in range(1,n):\n        A[i,:] = (xrow**(i))/factorial(i);\n        \n    b = numpy.zeros(n)    # b is right hand side,\n    b[k] = 1              # so k'th derivative term remains\n\n    c = numpy.linalg.solve(A,b)          # solve n by n system for coefficients\n    \n    return c\n", "meta": {"hexsha": "a6561b5ed0d88df24f6036500476b925df91e2cf", "size": 2110, "ext": "py", "lang": "Python", "max_stars_repo_path": "fdcoeffV.py", "max_stars_repo_name": "tzussman/intro-numerical-methods", "max_stars_repo_head_hexsha": "3b1735a088dac6ee15e56436ea118997e69d2af1", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-09-10T13:01:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T15:05:30.000Z", "max_issues_repo_path": "fdcoeffV.py", "max_issues_repo_name": "AinsleyChen/intro-numerical-methods", "max_issues_repo_head_hexsha": "2eda74cccbed5c0d4c57e24c3f4c96a1aa741f08", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fdcoeffV.py", "max_forks_repo_name": "AinsleyChen/intro-numerical-methods", "max_forks_repo_head_hexsha": "2eda74cccbed5c0d4c57e24c3f4c96a1aa741f08", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2020-01-21T16:08:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T12:46:56.000Z", "avg_line_length": 32.4615384615, "max_line_length": 85, "alphanum_fraction": 0.6379146919, "include": true, "reason": "import numpy", "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305307578324, "lm_q2_score": 0.8962513772903669, "lm_q1q2_score": 0.8632966898398383}}
{"text": "import random\n\nimport numpy as np\n\n\ndef poisson_disk(r, width, height, k=30):\n    \"\"\"\n    Poisson-disc sampling according to https://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf and\n    similar to the JavaScript implementation from https://www.jasondavies.com/poisson-disc/.\n\n    :param r: points are generated in the radius interval [r, 2r] from their neighbors (see paper)\n    :param width: width of the domain (e.g. image)\n    :param height: height of the domain (e.g. image)\n    :param k: number of attempts to generate valid neighbors for each point (see paper)\n    :return: numpy array of Poisson-disc sampled points\n    \"\"\"\n    # Step 0: Initialization\n    cell_size = r / np.sqrt(2)\n\n    points = []\n    grid = np.ones((np.ceil(height / cell_size).astype(np.int), np.ceil(width / cell_size).astype(np.int)), dtype=np.int) * -1\n    active = []\n\n    # Normalizing constant for annulus sampling\n    r_sqr = r ** 2\n    a = 3 * r_sqr\n\n    def emit_sample(point):\n        points.append(point)\n        index = len(points) - 1\n        int_point = (point // cell_size).astype(np.int)\n        assert(grid[int_point[0], int_point[1]] == -1)\n        grid[int_point[0], int_point[1]] = index\n        active.append(index)\n\n    def generate_around(point):\n        theta = random.random() * 2 * np.pi\n        radius = np.sqrt(random.random() * a + r_sqr)\n\n        return point + np.array([radius * np.sin(theta), radius * np.cos(theta)])\n\n    def check_extents(point):\n        return 0 < point[0] < height and 0 < point[1] < width\n\n    def check_neighborhood(point):\n        iy, ix = (point // cell_size).astype(np.int)\n        y0 = max(0, iy - 1)\n        x0 = max(0, ix - 1)\n        y1 = min(iy + 2, grid.shape[0])\n        x1 = min(ix + 2, grid.shape[1])\n\n        for ny in range(y0, y1):\n            for nx in range(x0, x1):\n                grid_index = grid[ny, nx]\n                if grid_index == -1:\n                    continue\n                grid_point = points[grid_index]\n                if np.square(grid_point - point).sum() < r_sqr:\n                    return False\n\n        return True\n\n    def check_valid(point):\n        return check_extents(point) and check_neighborhood(point)\n\n    # Step 1: Initial sample\n    emit_sample(np.random.random_sample((2,)) * np.array([height, width]))\n\n    # Step 2: Sampling\n    while len(active) > 0:\n        i = active[random.randint(0, len(active) - 1)]\n\n        candidate_found = False\n        for j in range(k):\n            new_point = generate_around(points[i])\n            if check_valid(new_point):\n                candidate_found = True\n                emit_sample(new_point)\n                break\n\n        if not candidate_found:\n            active.remove(i)\n\n    return np.array(points)\n", "meta": {"hexsha": "df1625f89f01aabb766ecafed2a4da67398b9771", "size": 2759, "ext": "py", "lang": "Python", "max_stars_repo_path": "vif/sampling.py", "max_stars_repo_name": "Spiess/voronoi-image-filter", "max_stars_repo_head_hexsha": "24e2da37f1a650f003dae09819736fadd066d49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-23T08:40:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T08:40:23.000Z", "max_issues_repo_path": "vif/sampling.py", "max_issues_repo_name": "Spiess/voronoi-image-filter", "max_issues_repo_head_hexsha": "24e2da37f1a650f003dae09819736fadd066d49e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vif/sampling.py", "max_forks_repo_name": "Spiess/voronoi-image-filter", "max_forks_repo_head_hexsha": "24e2da37f1a650f003dae09819736fadd066d49e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4588235294, "max_line_length": 126, "alphanum_fraction": 0.5915186662, "include": true, "reason": "import numpy", "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305307578323, "lm_q2_score": 0.8962513648201266, "lm_q1q2_score": 0.863296677828122}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # my lession 1 on Linear Algebra\n# \n# https://github.com/engineersCode/EngComp4_landlinear\n\n# In[23]:\n\n\nimport numpy\nget_ipython().run_line_magic('matplotlib', 'inline')\nfrom matplotlib import pyplot\n\n\n# In[24]:\n\n\nimport sys\nsys.path.append('../scripts/')\n\n# Our helper with the functions\n# plot_vector, plot_linear_transformation, plot_linear_transformations\nfrom plot_helper import *\n\n\n# In[25]:\n\n\nvectors = [(2,2)]\ntails = [(-3, -2), (-3, 1), (0, 0), (1, -3)]\n\n\n# In[26]:\n\n\nplot_vector(vectors, tails)\n\n\n# In[27]:\n\n\nvectors = [(2, 4)]\ntails = [(0,0), (-1, 1)]\nplot_vector(vectors, tails)\n\n\n# Vector addition\n\n# In[34]:\n\n\na = numpy.array((-2, 1))\nb = numpy.array((1, -3))\norigin = numpy.array((0, 0))\nvectors = [a, b, a+b]\ntails = [origin, a, origin]\nplot_vector(vectors, tails)\n\n\n# Vector scaling\n\n# In[29]:\n\n\nc = numpy.array((2, 1))\nvectors = [c, 2*c]\nplot_vector(vectors)\n\n\n# In[30]:\n\n\nc = numpy.array((2, 1))\nvectors = [c, -2*c]\nplot_vector(vectors)\n\n\n# In[31]:\n\n\ni = numpy.array((1, 0))\nj = numpy.array((0, 1))\n\nvec = 3*1 + 2*j\n\nvectors = [i, j, 3*i, 2*j, vec]\nplot_vector(vectors)\n\n\n# **Linear combinations** -- adding together two vectors that were each scaled\n# \n# **Span** -- set of all possible linear combinations\n\n# In[32]:\n\n\nfrom numpy.random import randint\n\nvectors = []\nfor _ in range(40):\n    m = randint(-10, 10)\n    n = randint(-10, 10)\n    vectors.append(m*i + n*j)\n    \nplot_vector(vectors)\n\n\n# In[36]:\n\n\nfrom numpy.random import randint\n\nvectors = []\nfor _ in range(40):\n    m = randint(-10, 10)\n    n = randint(-10, 10)\n    vectors.append(m*a + n*b)\n    \nplot_vector(vectors)\n\n\n# In[37]:\n\n\nd = numpy.array((-1, 0.5))\n\n\n# In[38]:\n\n\nvectors = []\nfor _ in range(40):\n    m = randint(-10, 10)\n    n = randint(-10, 10)\n    vectors.append(m*a + n*d)\n    \nplot_vector(vectors)\n\n\n# In[39]:\n\n\na\n\n\n# In[40]:\n\n\nd\n\n\n# a and d share the same span because they describe the same line.  d is a multiple of a. therefore, they are linearly dependent.\n\n# In[43]:\n\n\na\n\n\n# In[41]:\n\n\nb\n\n\n# In[42]:\n\n\nc\n\n\n# We have vectors $\\mathbf{a}$, and $\\mathbf{b}$\n# \n# $\\mathbf{c}= 2*\\mathbf{i} + 1*\\mathbf{j}$\n# \n# Use the components of $\\mathbf{c}$ to make a linear combination of $\\mathbf{a}$ and $\\mathbf{b}$\n\n# In[47]:\n\n\nc_prime = 2*a + 1*b\nc_prime\n\n\n# In[48]:\n\n\n# c_prime has the coordinates (2,1), i.e. c, in the a,b system of coordinates, wherein a,b are the basis vectors\n# c_prime has the coordinate (-3,-1), in the i,j system of coordinates\n\n\n# In[50]:\n\n\n2*a\n\n\n# In[51]:\n\n\n1*b\n\n\n# In[53]:\n\n\nA = [[-2,1], [1,-3]]\nA = numpy.array(A)\nprint(A)\n\n\n# In[54]:\n\n\nprint(c)\n\n\n# In[55]:\n\n\nA.dot(c)\n\n\n# In[56]:\n\n\nA.dot(i) #=> a\n\n\n# In[58]:\n\n\nA.dot(j) #=> b\n\n\n# In[59]:\n\n\nplot_linear_transformation(A)\n\n\n# In[60]:\n\n\nM = [[1,2], [2,1]]\nM = numpy.array(M)\nprint(M)\n\n\n# In[61]:\n\n\nM.dot(i)\n\n\n# In[62]:\n\n\nM.dot(j)\n\n\n# In[63]:\n\n\nplot_linear_transformation(M)\n\n\n# In[65]:\n\n\nx = numpy.array((0.5, 1))\nvectors = [x, M.dot(x)]\nplot_vector(vectors)\n\n\n# In[67]:\n\n\nN = numpy.array([[1,2], [-1,2]])\nprint(N)\n\n\n# In[68]:\n\n\nplot_linear_transformation(N)\n\n\n# In[69]:\n\n\nX = numpy.array([[2,3], [1,3]])\nprint(X)\n\n\n# In[70]:\n\n\nplot_linear_transformation(X)\n\n\n# In[71]:\n\n\nX = numpy.array([[-1,2], [2,-1]])\nprint(X)\n\n\n# In[72]:\n\n\nplot_linear_transformation(X)\n\n\n# In[74]:\n\n\nrotation = numpy.array([[0, -1], [1, 0]])\nprint(rotation)\n\n\n# In[75]:\n\n\nplot_linear_transformation(rotation)\n\n\n# In[77]:\n\n\nshear = numpy.array([[1,1], [0, 1]])\nprint(shear)\n\n\n# In[78]:\n\n\nplot_linear_transformation(shear)\n\n\n# In[79]:\n\n\nscaling = numpy.array([[2, 0], [0, 0.5]])\nprint(scaling)\n\n\n# In[80]:\n\n\nplot_linear_transformation(scaling)\n\n\n# Special scaling matric that leaves the unit vectors the same length:\n# **identity** matrix\n\n# In[81]:\n\n\nrotation_90_clockwise = numpy.array([[0, 1], [-1, 0]])\nprint(rotation_90_clockwise)\n\n\n# In[82]:\n\n\nplot_linear_transformation(rotation_90_clockwise)\n\n\n# In[83]:\n\n\nprint(shear@rotation)\n\n\n# In[84]:\n\n\nplot_linear_transformation(shear@rotation)\n\n\n# In[85]:\n\n\nplot_linear_transformation(rotation@shear)\n\n\n# **Inverse of a matrix** undoes the effect of the linear transformation\n\n# In[88]:\n\n\nfrom numpy.linalg import inv\n\n\n# In[89]:\n\n\nM\n\n\n# In[93]:\n\n\nM_inv = inv(M)\n\n\n# In[91]:\n\n\nplot_linear_transformations(M, M_inv)\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "e0703eceed184efb73e48010feea272cc7150783", "size": 4259, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebook_en/mylesson1.py", "max_stars_repo_name": "jclosure/EngComp4_landlinear", "max_stars_repo_head_hexsha": "46e5537562748e9e4882dc86930a65dc4a98c435", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-08-10T15:15:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T06:53:42.000Z", "max_issues_repo_path": "notebook_en/mylesson1.py", "max_issues_repo_name": "jclosure/EngComp4_landlinear", "max_issues_repo_head_hexsha": "46e5537562748e9e4882dc86930a65dc4a98c435", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebook_en/mylesson1.py", "max_forks_repo_name": "jclosure/EngComp4_landlinear", "max_forks_repo_head_hexsha": "46e5537562748e9e4882dc86930a65dc4a98c435", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-28T22:17:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-28T22:17:31.000Z", "avg_line_length": 10.1404761905, "max_line_length": 129, "alphanum_fraction": 0.6081239728, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428692, "lm_q2_score": 0.9184802501617066, "lm_q1q2_score": 0.8632918471325898}}
{"text": "  # -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 25 19:14:27 2019\n\n@author: Browsing\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x, y):\n    return (x+20.0*y)*np.sin(x*y)\n#    return 3*x\n\ndef RK2(startX , startY , endX , h , a2):\n    a1 = 1.0- a2\n    p1 = 0.5/a2\n    q11 = 0.5/a2\n    x = list()\n    y = list()\n    while startX <= endX:\n        x.append(startX)\n        y.append(startY)\n        k1 = f(startX , startY)\n        k2 = f(startX +p1 *h , startY + q11 * k1 * h)\n        startY = startY + (a1 * k1 + a2 * k2 ) * h\n        startX = startX + h\n    return x,y\n\ndef Euler(startX , startY , endX , h ):\n    x = list()\n    y = list()\n    while startX <= endX:\n        x.append(startX)\n        y.append(startY)\n        startY = startY + f(startX , startY ) * h\n        startX = startX + h\n    return x,y\n\ndef Heun( startX , startY , endX , h ):\n    return RK2(startX , startY , endX , h , 0.5 )\n\n\ndef MidPoint( startX , startY , endX , h ):\n    return RK2(startX , startY , endX , h , 1.0 )\n\n\ndef Ralston( startX , startY , endX , h ):\n    return RK2(startX , startY , endX , h , 2.0/3.0 )\n\ndef RK4(startX , startY , endX , h):\n    x = list()\n    y = list()\n    while startX <= endX:\n        x.append(startX)\n        y.append(startY)\n        k1 = f(startX, startY)\n        k2 = f( startX + 0.5 * h , startY + 0.5 * k1 * h)\n        k3 = f(startX + 0.5 * h , startY +  0.5 * k2 * h)\n        k4 = f(startX + h , startY + k3* h )\n        startY = startY + (k1 + 2 *k2 + 2* k3 + k4 ) * h /6.0\n        startX = startX + h\n    return x,y\n\ndef SubPlot1(startX , startY , endX , hs , Title , func ):\n    \n    plt.title(Title)\n    for h in hs:\n        x , y = func(startX , startY , endX , h)\n#        plt.ylim(-200.0 , 200.0)\n        plt.plot(x,y , label = \"h = %f\"%(h))\n    plt.legend()\n\n\ndef SubPlot2(startX , startY , endX , h , Title ):\n    plt.title(Title)\n    x,y= Euler(startX , startY , endX , h )\n    plt.plot( x, y , label = \"Euler method\")\n    \n    x,y= Heun(startX , startY , endX , h )\n#    plt.ylim(-200.0 , 200.0)\n    plt.plot( x, y , label = \"Heun's Method\")\n    \n    x,y= MidPoint(startX , startY , endX , h )\n#    plt.ylim(-200.0 , 200.0)\n    plt.plot( x, y , label = \"Midpoint Method\")\n   \n    x,y= Ralston(startX , startY , endX , h )\n#    plt.ylim(-200.0 , 200.0)\n    plt.plot( x, y , label = \"Ralston’s Method\")\n    \n    x,y= RK4(startX , startY , endX , h )\n#    plt.ylim(-200.0 , 200.0)\n    plt.plot( x, y , label = \"4th order RK Method\")\n    \n    plt.legend()\n    \ndef Plot1(startX , startY , endX , hs):\n    plt.figure(1,[10,10] )\n    SubPlot1(startX,startY , endX , hs , \"Euler Method\" ,Euler )\n    plt.figure(2,[10,10] )\n    SubPlot1(startX,startY , endX , hs , \"Heun's Method\" ,Heun )\n    plt.figure(3,[10,10] )\n    SubPlot1(startX,startY , endX , hs , \"Midpoint Method\" ,MidPoint )\n    plt.figure(4,[10,10] )\n    SubPlot1(startX,startY , endX , hs , \"Ralston’s Method\" ,Ralston )\n    plt.figure(5,[10,10] )\n    SubPlot1(startX,startY , endX , hs , \"4th order RK Method\" ,RK4 )\n\ndef Plot2(startX , startY , endX , hs):\n    \n    for i in range( len(hs) ):\n        plt.figure(i+6,[10, 10])\n        h=hs[i]\n        SubPlot2(startX , startY , endX , h , \"h = %f\"%(h)   )\n    \nif __name__ == '__main__':\n#    print(RK2(0.0 , 1.0 , 10.0 , 0.5 , 0.5))\n    \n    Plot1(0.0 , 4.0 , 10.0 ,[0.01, 0.05, 0.1, 0.5 ])\n    Plot2(0.0 , 4.0 , 10.0 ,[0.01, 0.05, 0.1, 0.5 ])\n", "meta": {"hexsha": "55434b29326da2edfd6daced5c8e6d6f4efdab60", "size": 3395, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numerical/Offline 5 on ODE/Numerical Offline RK method.py", "max_stars_repo_name": "mahdihasnat/2-1-kodes", "max_stars_repo_head_hexsha": "1526de08f1bce66dbe428a8b27fedaca1ec75004", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numerical/Offline 5 on ODE/Numerical Offline RK method.py", "max_issues_repo_name": "mahdihasnat/2-1-kodes", "max_issues_repo_head_hexsha": "1526de08f1bce66dbe428a8b27fedaca1ec75004", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numerical/Offline 5 on ODE/Numerical Offline RK method.py", "max_forks_repo_name": "mahdihasnat/2-1-kodes", "max_forks_repo_head_hexsha": "1526de08f1bce66dbe428a8b27fedaca1ec75004", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0578512397, "max_line_length": 70, "alphanum_fraction": 0.522533137, "include": true, "reason": "import numpy", "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.9184802434674242, "lm_q1q2_score": 0.8632918454782905}}
{"text": "%matplotlib inline\n\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n# define activation function and its derivative\ndef sigmoid(x):\n    return 1/(1+np.exp(-x))\n\ndef sigmoid_p(x):\n    return sigmoid(x)*(1-sigmoid(x))\n\nT = np.linspace(-5,5,100)\nplt.plot(T,sigmoid(T),c='r')\nplt.plot(T,sigmoid_p(T),c='b')\n\n## Assignment a)\ndata = [0.5, 1.5]\nw1 = 1.0\nw2 = 1.0\nlearning_rate = 1#?\nb = 2.0\n# calculate initial output\ny = data[0]*w1 + data[1]*w2 + b\nz = sigmoid(y)\nz_ = 1.0\n#cost function\ncost = (z_-z)\n# derivatives of the cost function w.r.t. weights\ndcost_prediction = -1\ndpred_dy = sigmoid_p(y)\ndy_dw1 = data[0]\ndy_dw2 = data[1]\ndy_db = 1\n    \n# applying chain rule\ndcost_dw1 = dcost_prediction * dpred_dy * dy_dw1\ndcost_dw2 = dcost_prediction * dpred_dy * dy_dw2\ndcost_db = dcost_prediction * dpred_dy * dy_db\n    \n# updating weights    \nw1 = w1 - learning_rate * dcost_dw1\nw2 = w2 - learning_rate * dcost_dw2\nb = b - learning_rate * dcost_db\n\n#check output with new weights\ny = data[0]*w1 + data[1]*w2 + b\nz = sigmoid(y)\nprint(f\"The error of the simple network a) with updated weights is:\\n {str(z_-z)}\")\nprint(f\"\\nThe values of the updated weights are:\\n w1={str(w1)} w2={str(w2)} b={str(b)}\")\n\n##Assignment b)\ndata = [0.5, 1.5]\nw1 = 1.0\nw2 = 1.0\nlearning_rate = 1#?\nb = 2.0\n# calculate initial output\ny = data[0]*w1 + data[1]*w2 + b\nz = sigmoid(y)\nz_ = 1.0\n#cost function\ncost = np.square((z_-z))/2\n# derivatives of the cost function w.r.t. weights\ndcost_prediction = (z_-z)\ndpred_dy = sigmoid_p(y)\ndy_dw1 = data[0]\ndy_dw2 = data[1]\ndy_db = 1\n    \n# applying chain rule\ndcost_dw1 = dcost_prediction * dpred_dy * dy_dw1\ndcost_dw2 = dcost_prediction * dpred_dy * dy_dw2\ndcost_db = dcost_prediction * dpred_dy * dy_db\n    \n# updating weights    \nw1 = w1 - learning_rate * dcost_dw1\nw2 = w2 - learning_rate * dcost_dw2\nb = b - learning_rate * dcost_db\n\n#check output with new weights\ny = data[0]*w1 + data[1]*w2 + b\nz = sigmoid(y)\nprint(f\"The error of the simple network b) with updated weights is:\\n {np.square((z_-z))/2}\")\nprint(f\"\\nThe values of the updated weights are:\\n w1={str(w1)} w2={str(w2)} b={str(b)}\")\n", "meta": {"hexsha": "f8e65a0bd0f32a9a83219f75482ddafae1b45f47", "size": 2122, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment_4/sourcecode/problem2.py", "max_stars_repo_name": "worldpotato/Advanced_Remote_Sensing_Methods", "max_stars_repo_head_hexsha": "6f40cf72b2f911b84e0a1f62c229ffe0dde8e060", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment_4/sourcecode/problem2.py", "max_issues_repo_name": "worldpotato/Advanced_Remote_Sensing_Methods", "max_issues_repo_head_hexsha": "6f40cf72b2f911b84e0a1f62c229ffe0dde8e060", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment_4/sourcecode/problem2.py", "max_forks_repo_name": "worldpotato/Advanced_Remote_Sensing_Methods", "max_forks_repo_head_hexsha": "6f40cf72b2f911b84e0a1f62c229ffe0dde8e060", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6744186047, "max_line_length": 93, "alphanum_fraction": 0.6804901037, "include": true, "reason": "import numpy", "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885904, "lm_q2_score": 0.9005297881200701, "lm_q1q2_score": 0.8631917764602879}}
{"text": "#This function gives the approximate derivative of a user defined function or any function from Numpy at a point x = a\n#Call the function as follows: derivative(function, a, Number step size) example:print(derivative(np.sin,np.pi,0.00001))\n#Number step size (h) should tend to zero for a better approximate \n\nimport numpy as np\n\ndef derivative(f,a,h):\n\n\treturn (f(a + h) - f(a - h))/(2*h)\n\n\n", "meta": {"hexsha": "091d56061100b79a57b6e0eb96d20ef36048f409", "size": 391, "ext": "py", "lang": "Python", "max_stars_repo_path": "Calculus/derivative.py", "max_stars_repo_name": "priyatam0509/mathpy", "max_stars_repo_head_hexsha": "0db3fb081a17d0617c9d5638e36681d54332a591", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-12-13T15:44:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-06T14:43:35.000Z", "max_issues_repo_path": "Calculus/derivative.py", "max_issues_repo_name": "priyatam0509/mathpy", "max_issues_repo_head_hexsha": "0db3fb081a17d0617c9d5638e36681d54332a591", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-12-20T15:43:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-23T05:43:28.000Z", "max_forks_repo_path": "Calculus/derivative.py", "max_forks_repo_name": "priyatam0509/mathpy", "max_forks_repo_head_hexsha": "0db3fb081a17d0617c9d5638e36681d54332a591", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-12-20T14:52:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-10T09:24:35.000Z", "avg_line_length": 32.5833333333, "max_line_length": 120, "alphanum_fraction": 0.7314578005, "include": true, "reason": "import numpy", "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9678992932829918, "lm_q2_score": 0.891811044719067, "lm_q1q2_score": 0.8631832799255517}}
{"text": "from sympy.core.numbers import igcd\nfrom primetest import isprime\nfrom factor_ import factorint\n\n\ndef totient_(n):\n    \"\"\"returns the number of integers less than n\n    and relatively prime to n\"\"\"\n    if n < 1:\n        raise ValueError(\"n must be a positive integer\")\n    tot = 0\n    for x in xrange(1, n):\n        if igcd(x, n) == 1:\n            tot += 1\n    return tot\n\n\ndef n_order(a, n):\n    \"\"\" returns the order of a modulo n\n    Order of a modulo n is the smallest integer\n    k such that a^k leaves a remainder of 1 with n.\n    \"\"\"\n    if igcd(a, n) != 1:\n        raise ValueError(\"The two numbers should be relatively prime\")\n    group_order = totient_(n)\n    factors = factorint(group_order)\n    order = 1\n    if a > n:\n        a = a % n\n    for p, e in factors.iteritems():\n        exponent = group_order\n        for f in xrange(0, e + 1):\n            if (a ** (exponent)) % n != 1:\n                order *= p ** (e - f + 1)\n                break\n            exponent = exponent // p\n    return order\n\n\ndef is_primitive_root(a, p):\n    \"\"\"\n    returns True if a is a primitive root of p\n    \"\"\"\n    if igcd(a, p) != 1:\n        raise ValueError(\"The two numbers should be relatively prime\")\n    if a > p:\n        a = a % p\n    if n_order(a, p) == totient_(p):\n        return True\n    else:\n        return False\n\n\ndef is_quad_residue(a, p):\n    \"\"\"\n    returns True if a is a quadratic residue of p\n    p should be a prime and a should be relatively\n    prime to p\n    \"\"\"\n    if not isprime(p) or p == 2:\n        raise ValueError(\"p should be an odd prime\")\n    if igcd(a, p) != 1:\n        raise ValueError(\"The two numbers should be relatively prime\")\n    if a > p:\n        a = a % p\n\n    def square_and_multiply(a, n, p):\n        if n == 0:\n            return 1\n        elif n == 1:\n            return a\n        elif n % 2 == 1:\n            return ((square_and_multiply(a, n // 2, p) ** 2) * a) % p\n        else:\n            return (square_and_multiply(a, n // 2, p) ** 2) % p\n\n    return (square_and_multiply(a, (p - 1) // 2, p) % p) == 1\n\n\ndef legendre_symbol(a, p):\n    \"\"\"\n    return 1 if a is a quadratic residue of p\n    else return -1\n    p should be an odd prime by definition\n    \"\"\"\n    if not isprime(p) or p == 2:\n        raise ValueError(\"p should be an odd prime\")\n    if igcd(a, p) != 1:\n        raise ValueError(\"The two numbers should be relatively prime\")\n    if a > p:\n        a = a % p\n    if is_quad_residue(a, p):\n        return 1\n    else:\n        return -1\n", "meta": {"hexsha": "3bfbf04a7ccdd49b65a98d84c1816505103dc3ea", "size": 2494, "ext": "py", "lang": "Python", "max_stars_repo_path": "sympy/ntheory/residue_ntheory.py", "max_stars_repo_name": "pernici/sympy", "max_stars_repo_head_hexsha": "5e6e3b71da777f5b85b8ca2d16f33ed020cf8a41", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-11-13T16:40:57.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T15:37:19.000Z", "max_issues_repo_path": "sympy_old/ntheory/residue_ntheory.py", "max_issues_repo_name": "curzel-it/KiPyCalc", "max_issues_repo_head_hexsha": "909c783d5e6967ea58ca93f875106d8a8e3ca5db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-06-13T01:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-14T00:38:27.000Z", "max_forks_repo_path": "sympy_old/ntheory/residue_ntheory.py", "max_forks_repo_name": "curzel-it/KiPyCalc", "max_forks_repo_head_hexsha": "909c783d5e6967ea58ca93f875106d8a8e3ca5db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9791666667, "max_line_length": 70, "alphanum_fraction": 0.5457097033, "include": true, "reason": "from sympy", "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992932829918, "lm_q2_score": 0.8918110396870287, "lm_q1q2_score": 0.8631832750550452}}
{"text": "import numpy as np\nimport sympy as sp\nfrom sympy.core import S, Dummy\nfrom sympy.polys.orthopolys import (legendre_poly, laguerre_poly,\n                                    hermite_poly, jacobi_poly)\nfrom sympy.polys.rootoftools import RootOf\n\n\n\ndef symbolic_gauss_legendre(n):\n    \"\"\"\n    Computes the symbolic Gauss-Legendre quadrature points and weights.\n\n    Parameters\n    ----------\n    n : Integer\n        Number of integration points.\n    x : Symbol\n        Symbolic sysmbol.\n\n    Returns\n    -------\n    xi : Abscisca\n        Symbolic location of roots.\n    wi : Weights\n        Symbolic weights of roots.\n\n    \"\"\"\n    x = Dummy(\"x\")\n    Pnx = sp.legendre(n,x)\n    Pp = sp.diff(Pnx,x)\n    xi = sp.solve( Pnx, x )\n    wi = [ sp.simplify(2/(1 - xj**2)/(Pp.subs(x,xj))**2) for xj in xi ]\n    return xi, wi\n\n\ndef gauss_legendre(n, n_digits):\n    r\"\"\"\n    Computes the Gauss-Legendre quadrature [1]_ points and weights.\n\n    The Gauss-Legendre quadrature approximates the integral:\n\n    .. math::\n        \\int_{-1}^1 f(x)\\,dx \\approx \\sum_{i=1}^n w_i f(x_i)\n\n    The nodes `x_i` of an order `n` quadrature rule are the roots of `P_n`\n    and the weights `w_i` are given by:\n\n    .. math::\n        w_i = \\frac{2}{\\left(1-x_i^2\\right) \\left(P'_n(x_i)\\right)^2}\n\n    Parameters\n    ==========\n\n    n : the order of quadrature\n\n    n_digits : number of significant digits of the points and weights to return\n\n    Returns\n    =======\n\n    (x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.\n             The points `x_i` and weights `w_i` are returned as ``(x, w)``\n             tuple of lists.\n\n    Examples\n    ========\n\n    >>> from sympy.integrals.quadrature import gauss_legendre\n    >>> x, w = gauss_legendre(3, 5)\n    >>> x\n    [-0.7746, 0, 0.7746]\n    >>> w\n    [0.55556, 0.88889, 0.55556]\n    >>> x, w = gauss_legendre(4, 5)\n    >>> x\n    [-0.86114, -0.33998, 0.33998, 0.86114]\n    >>> w\n    [0.34785, 0.65215, 0.65215, 0.34785]\n\n    See Also\n    ========\n\n    gauss_laguerre, gauss_gen_laguerre, gauss_hermite, gauss_chebyshev_t, gauss_chebyshev_u, gauss_jacobi, gauss_lobatto\n\n    References\n    ==========\n\n    .. [1] https://en.wikipedia.org/wiki/Gaussian_quadrature\n    .. [2] http://people.sc.fsu.edu/~jburkardt/cpp_src/legendre_rule/legendre_rule.html\n    \"\"\"\n    x = Dummy(\"x\")\n    p = legendre_poly(n, x, polys=True)\n    pd = p.diff(x)\n    xi = []\n    wi = []\n    for r in p.real_roots():\n        if isinstance(r, RootOf):\n            r = r.eval_rational(S(1)/10**(n_digits+2))\n        xi.append(r.n(n_digits))\n        wi.append((2/((1-r**2) * pd.subs(x, r)**2)).n(n_digits))\n    return xi, wi\n\n\ndigits = 36\nnpoints = list(range(1,17))\n\nfor n in npoints:\n    xi, wi = gauss_legendre(n, digits)\n    \n    print('\\nN = %3d'%(n))\n    for i in range(0,n):\n        print('%3d %40.36f %40.36f'%(i+1,xi[i],wi[i]))\n    \n    \n    \n    \n    \n", "meta": {"hexsha": "d2b7942dab7799472a3f91f8fe490fb22bae8c7a", "size": 2867, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/gauss_legendre.py", "max_stars_repo_name": "BryanFlynt/PolyCalc", "max_stars_repo_head_hexsha": "9fe70f83647c6f5683e6e8f5cfee23b417974ebb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/gauss_legendre.py", "max_issues_repo_name": "BryanFlynt/PolyCalc", "max_issues_repo_head_hexsha": "9fe70f83647c6f5683e6e8f5cfee23b417974ebb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/gauss_legendre.py", "max_forks_repo_name": "BryanFlynt/PolyCalc", "max_forks_repo_head_hexsha": "9fe70f83647c6f5683e6e8f5cfee23b417974ebb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0924369748, "max_line_length": 120, "alphanum_fraction": 0.5730728985, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480347, "lm_q2_score": 0.9219218407544306, "lm_q1q2_score": 0.8631815959700009}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.interpolate as interpolate\n\n\n'''\nInterpolation is the process of \nfinding a value between two points on a line \nor a curve.\n'''\n\nkinds = ('nearest', \n         'zero', \n         'linear', \n         'slinear', \n         'quadratic', \n         'cubic')\n\n''' x- axis values '''\nx = np.array([0.0,1.0,2.0,3.0,\n              4.0,5.0,6.0,7.0,\n              8.0,9.0])\n\n''' y- axis values '''\ny = np.array([10,5,39,3,6,9,41,73,57,88])\n\n''' plot original values '''\nplt.plot(x, y, 'o')\n\n''' new x-axis values to be interpolated '''\nnew_x = np.linspace(0.0, 9.0, 25)\n\n''' interpolate for kind = 'nearest' '''\nnew_y = interpolate.interp1d(x,y,kind='nearest')(new_x)\nplt.plot(new_x, new_y, color='C1', linewidth=1)\n\n''' interpolate for kind = 'zero' '''\nnew_y = interpolate.interp1d(x,y,kind='zero')(new_x)\nplt.plot(new_x, new_y, color='C2', linewidth=1)\n\n''' interpolate for kind = 'linear' '''\nnew_y = interpolate.interp1d(x,y,kind='linear')(new_x)\nplt.plot(new_x, new_y, color='C3', linewidth=1)\n\n''' interpolate for kind = 'slinear' '''\nnew_y = interpolate.interp1d(x,y,kind='slinear')(new_x)\nplt.plot(new_x, new_y, color='C4', linewidth=1)\n\n''' interpolate for kind = 'cubic' '''\nnew_y = interpolate.interp1d(x,y,kind='cubic')(new_x)\nplt.plot(new_x, new_y, color='C5', linewidth=1)\n\nplt.legend(['original','nearest','zero',\n            'linear','slinear','cubic'])\nplt.show()\n\n\n\n\n''' plotting all types in single graph '''\nfig, axs = plt.subplots(\n        nrows=len(kinds)+1, \n        sharex=True)\naxs[0].plot(x, y, 'bo-')\naxs[0].set_title('raw')\nfor ax, kind in zip(axs[1:], kinds):\n    new_y = interpolate.interp1d(\n            x, \n            y, \n            kind=kind)(new_x)\n    ax.plot(new_x, new_y, 'ro-')\n    ax.set_title(kind)\nplt.show()\n\n\n\n''' spliners '''\n''' to draw smooth curves through data points '''\nfrom scipy.interpolate import UnivariateSpline\n\n''' x- axis values '''\nx = np.array([0.0,1.0,2.0,3.0,\n              4.0,5.0,6.0,7.0,\n              8.0,9.0])\n\n''' y- axis values '''\ny = np.array([10,25,39,58,16,91,41,73,57,88])\n''' plot original values '''\nplt.plot(x, y, 'o')\n\nnew_x = np.linspace(0.0, 9.0, 25)\nnew_y = interpolate.interp1d(x,y,kind='nearest')(new_x)\nspl = UnivariateSpline(new_x, new_y)\nspl.set_smoothing_factor(0.001)\nplt.plot(new_x, spl(new_x), color='C6', linewidth=2)\n\n", "meta": {"hexsha": "f43df9e7549d2f08fd8de05a669728efa4ed80c7", "size": 2411, "ext": "py", "lang": "Python", "max_stars_repo_path": "prg05_scipy/scipy02_interpolation.py", "max_stars_repo_name": "imademethink/MachineLearning_related_Python", "max_stars_repo_head_hexsha": "c7fd22d2d878d110e0a7bf679103a226952164e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prg05_scipy/scipy02_interpolation.py", "max_issues_repo_name": "imademethink/MachineLearning_related_Python", "max_issues_repo_head_hexsha": "c7fd22d2d878d110e0a7bf679103a226952164e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prg05_scipy/scipy02_interpolation.py", "max_forks_repo_name": "imademethink/MachineLearning_related_Python", "max_forks_repo_head_hexsha": "c7fd22d2d878d110e0a7bf679103a226952164e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.11, "max_line_length": 55, "alphanum_fraction": 0.6068021568, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748209, "lm_q2_score": 0.897695295528596, "lm_q1q2_score": 0.8631643729482985}}
{"text": "import cupy as cp\n\nclass root_finders():\n\n    def __init__(self):\n        pass\n\n    def bisection(self, fn,x0,x1,e):\n        \"\"\"\n        Bisection Method for finding real root of nonlinear \n        equation in python programming language.\n        In this python program, x0 and x1 are two initial guesses, \n        e is tolerable error and nonlinear function f(x) is defined \n        using python function definition.\n\n        Algorithm:\n\n        1. start\n\n        2. Define function f(x)\n\n        3. Choose initial guesses x0 and x1 such that f(x0)f(x1) < 0\n\n        4. Choose pre-specified tolerable error e.\n\n        5. Calculate new approximated root as x2 = (x0 + x1)/2\n\n        6. Calculate f(x0)f(x2)\n            a. if f(x0)f(x2) < 0 then x0 = x0 and x1 = x2\n            b. if f(x0)f(x2) > 0 then x0 = x2 and x1 = x1\n            c. if f(x0)f(x2) = 0 then goto (8)\n            \n        7. if |f(x2)| > e then goto (5) otherwise goto (8)\n\n        8. Display x2 as root.\n\n        9. Stop\n        \"\"\"\n        step = 1\n\n        condition = True\n        while condition:\n            x2 = (x0 + x1)/2\n            print('Iteration-%d, x2 = %0.6f and f(x2) = %0.6f' % (step, x2, fn(x2)))\n\n            if fn(x0) * fn(x2) < 0:\n                x1 = x2\n            else:\n                x0 = x2\n            \n            step = step + 1\n            condition = abs(fn(x2)) > e\n\n        print('\\nRequired Root is : %0.8f' % x2)\n\n    def newton_raphson(self,fn,d_fn,x0,e,N):\n        \"\"\"\n        Newton Raphson method for finding real root of nonlinear function in python\n        programming language.\n        x0 is initial guess, e \n        is tolerable error, fn(x) is non-linear function whose \n        root is being obtained using Newton Raphson method.\n        1. Start\n\n        2. Define function as fn(x)\n\n        3. Define first derivative of fn(x) as d_fn(x)\n\n        4. Input initial guess (x0), tolerable error (e) \n        and maximum iteration (N)\n\n        5. Initialize iteration counter i = 1\n\n        6. If d_fn(x0) = 0 then print \"Mathematical Error\" \n        and goto (12) otherwise goto (7) \n\n        7. Calcualte x1 = x0 - fn(x0) / d_fn(x0)\n\n        8. Increment iteration counter i = i + 1\n\n        9. If i >= N then print \"Not Convergent\" \n        and goto (12) otherwise goto (10) \n\n        10. If |fn(x1)| > e then set x0 = x1 \n            and goto (6) otherwise goto (11)\n\n        11. Print root as x1\n\n        12. Stop\n        \"\"\"\n        \n        step = 1\n        flag = 1\n        condition = True\n        while condition:\n            if d_fn(x0) == 0.0:\n                print('Divide by zero error!')\n                break\n            \n            x1 = x0 - fn(x0)/d_fn(x0)\n            print('Iteration-%d, x1 = %0.6f and f(x1) = %0.6f' % (step, x1, fn(x1)))\n            x0 = x1\n            step = step + 1\n            \n            if step > N:\n                flag = 0\n                break\n            \n            condition = abs(fn(x1)) > e\n        \n        if flag==1:\n            print('\\nRequired root is: %0.8f' % x1)\n        else:\n            print('\\nNot Convergent.')", "meta": {"hexsha": "cfa1cbfc848b6f9a8ae17922de80ebfcadfbe95e", "size": 3096, "ext": "py", "lang": "Python", "max_stars_repo_path": "numericalPython/root_finders.py", "max_stars_repo_name": "vikash06131721/numericalAlgorithms", "max_stars_repo_head_hexsha": "12782de00d1e3217aa5a2bfde5b074e7a47587e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numericalPython/root_finders.py", "max_issues_repo_name": "vikash06131721/numericalAlgorithms", "max_issues_repo_head_hexsha": "12782de00d1e3217aa5a2bfde5b074e7a47587e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numericalPython/root_finders.py", "max_forks_repo_name": "vikash06131721/numericalAlgorithms", "max_forks_repo_head_hexsha": "12782de00d1e3217aa5a2bfde5b074e7a47587e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1578947368, "max_line_length": 84, "alphanum_fraction": 0.4932170543, "include": true, "reason": "import cupy", "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748209, "lm_q2_score": 0.8976952907388474, "lm_q1q2_score": 0.8631643683427934}}
{"text": "# 1. Write a NumPy program to compute the multiplication of two given matrixes.\nimport numpy as np\n\np = [[1, 0], [0, 1]]\nq = [[1, 2], [3, 4]]\nprint(\"original matrix:\")\nprint(p)\nprint(q)\nresult1 = np.dot(p, q)\nprint(\"Result of the said matrix multiplication:\")\nprint(result1)\n# ----------------------------------------------------------------------------------#\n# 2. Write a NumPy program to compute the outer product of two given vectors.\nimport numpy as np\n\np = [[1, 0], [0, 1]]\nq = [[1, 2], [3, 4]]\nprint(\"original matrix:\")\nprint(p)\nprint(q)\nresult = np.outer(p, q)\nprint(\"Outer product of the said two vectors:\")\nprint(result)\n# ----------------------------------------------------------------------------------#\n# 3. Write a NumPy program to compute the cross product of two given vectors.\nimport numpy as np\n\np = [[1, 0], [0, 1]]\nq = [[1, 2], [3, 4]]\nprint(\"original matrix:\")\nprint(p)\nprint(q)\nresult1 = np.cross(p, q)\nresult2 = np.cross(q, p)\nprint(\"cross product of the said two vectors(p, q):\")\nprint(result1)\nprint(\"cross product of the said two vectors(q, p):\")\nprint(result2)\n# ----------------------------------------------------------------------------------#\n# 4. Write a NumPy program to compute the determinant of a given square array.\nimport numpy as np\nfrom numpy import linalg as LA\n\na = np.array([[1, 0], [1, 2]])\nprint(\"Original 2-d array\")\nprint(a)\nprint(\"Determinant of the said 2-D array:\")\nprint(np.linalg.det(a))\n# ----------------------------------------------------------------------------------#\n# 5. Write a NumPy program to evaluate Einstein's summation convention of two given multidimensional arrays.\nimport numpy as np\n\na = np.array([1, 2, 3])\nb = np.array([0, 1, 0])\nprint(\"Original 1-d arrays:\")\nprint(a)\nprint(b)\nresult = np.einsum(\"n,n\", a, b)\nprint(\"Einstein’s summation convention of the said arrays:\")\nprint(result)\nx = np.arange(9).reshape(3, 3)\ny = np.arange(3, 12).reshape(3, 3)\nprint(\"Original Higher dimension:\")\nprint(x)\nprint(y)\nresult = np.einsum(\"mk,kn\", x, y)\nprint(\"Einstein’s summation convention of the said arrays:\")\nprint(result)\n# ----------------------------------------------------------------------------------#\n# 6. Write a NumPy program to compute the inner product of vectors for 1-D arrays (without complex conjugation) and in higher dimension.\nimport numpy as np\n\na = np.array([1, 2, 5])\nb = np.array([2, 1, 0])\nprint(\"Original 1-d arrays:\")\nprint(a)\nprint(b)\nprint\nresult = np.inner(a, b)\nprint(\"Inner product of the said vectors:\")\nx = np.arange(9).reshape(3, 3)\ny = np.arange(3, 12).reshape(3, 3)\nprint(\"Higher dimension arrays:\")\nprint(x)\nprint(y)\nresult = np.inner(x, y)\nprint(\"Inner product of the said vectors:\")\nprint(result)\n# ----------------------------------------------------------------------------------#\n# 7. Write a NumPy program to compute the eigenvalues and right eigenvectors of a given square array.\nimport numpy as np\n\nm = np.mat(\"3 -2;1 0\")\nprint(\"Original matrix:\")\nprint(\"a\\n\", m)\nw, v = np.linalg.eig(m)\nprint(\"Eigenvalues of the said matrix\", w)\nprint(\"Eigenvectors of the said matrix\", v)\n# ----------------------------------------------------------------------------------#\n# 8. Write a NumPy program to compute the Kronecker product of two given mulitdimension arrays.\nimport numpy as np\n\na = np.array([1, 2, 3])\nb = np.array([0, 1, 0])\nprint(\"Original 1-d arrays:\")\nprint(a)\nprint(b)\nresult = np.kron(a, b)\nprint(\"Kronecker product of the said arrays:\")\nprint(result)\nx = np.arange(9).reshape(3, 3)\ny = np.arange(3, 12).reshape(3, 3)\nprint(\"Original Higher dimension:\")\nprint(x)\nprint(y)\nresult = np.kron(x, y)\nprint(\"Kronecker product  of the said arrays:\")\nprint(result)\n# ----------------------------------------------------------------------------------#\n# 9. Write a NumPy program to compute the condition number of a given matrix.\nimport numpy as np\nfrom numpy import linalg as LA\n\na = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]])\nprint(\"Original matrix:\")\nprint(a)\nprint(\"The condition number of the said matrix:\")\nprint(LA.cond(a))\n# ----------------------------------------------------------------------------------#\n# 10. Write a NumPy program to find a matrix or vector norm.\nimport numpy as np\n\nv = np.arange(7)\nresult = np.linalg.norm(v)\nprint(\"Vector norm:\")\nprint(result)\nm = np.matrix('1, 2; 3, 4')\nresult1 = np.linalg.norm(m)\nprint(\"Matrix norm:\")\nprint(result1)\n# ----------------------------------------------------------------------------------#\n# 11. Write a NumPy program to compute the determinant of an array.\nimport numpy as np\n\na = np.array([[1, 2], [3, 4]])\nprint(\"Original array:\")\nprint(a)\nresult = np.linalg.det(a)\nprint(\"Determinant of the said array:\")\nprint(result)\n# ----------------------------------------------------------------------------------#\n# 12. Write a NumPy program to compute the inverse of a given matrix.\nimport numpy as np\n\nm = np.array([[1, 2], [3, 4]])\nprint(\"Original matrix:\")\nprint(m)\nresult = np.linalg.inv(m)\nprint(\"Inverse of the said matrix:\")\nprint(result)\n# ----------------------------------------------------------------------------------#\n# 13. Write a NumPy program to calculate the QR decomposition of a given matrix.\nimport numpy as np\n\nm = np.array([[1, 2], [3, 4]])\nprint(\"Original matrix:\")\nprint(m)\nresult = np.linalg.qr(m)\nprint(\"Decomposition of the said matrix:\")\nprint(result)\n# ----------------------------------------------------------------------------------#\n# 14. Write a NumPy program to compute the condition number of a given matrix.\nimport numpy as np\n\nm = np.array([[1, 2], [3, 4]])\nprint(\"Original matrix:\")\nprint(m)\nresult = np.linalg.cond(m)\nprint(\"Condition number of the said matrix:\")\nprint(result)\n# ----------------------------------------------------------------------------------#\n# 15. Write a NumPy program to compute the sum of the diagonal element of a given array.\nimport numpy as np\n\nm = np.arange(6).reshape(2, 3)\nprint(\"Original matrix:\")\nprint(m)\nresult = np.trace(m)\nprint(\"Condition number of the said matrix:\")\nprint(result)\n# ----------------------------------------------------------------------------------#\n# 16. Write a NumPy program to get the lower-triangular L in the Cholesky decomposition of a given array.\nimport numpy as np\n\na = np.array([[4, 12, -16], [12, 37, -53], [-16, -53, 98]], dtype=np.int32)\nprint(\"Original array:\")\nprint(a)\nL = np.linalg.cholesky(a)\nprint(\"Lower-trianglular L in the Cholesky decomposition of the said array:\")\nprint(L)\n# ----------------------------------------------------------------------------------#\n# 17. Write a NumPy program to get the qr factorization of a given array.\nimport numpy as np\n\na = np.array([[4, 12, -14], [12, 37, -53], [-14, -53, 98]], dtype=np.int32)\nprint(\"Original array:\")\nprint(a)\nq, r = np.linalg.qr(a)\nprint(\"qr factorization of the said array:\")\nprint(\"q=\\n\", q, \"\\nr=\\n\", r)\n# ----------------------------------------------------------------------------------#\n# 18. Write a NumPy program to compute the factor of a given array by Singular Value Decomposition.\nimport numpy as np\n\na = np.array([[1, 0, 0, 0, 2], [0, 0, 3, 0, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0]], dtype=np.float32)\nprint(\"Original array:\")\nprint(a)\nU, s, V = np.linalg.svd(a, full_matrices=False)\nq, r = np.linalg.qr(a)\nprint(\"Factor of a given array  by Singular Value Decomposition:\")\nprint(\"U=\\n\", U, \"\\ns=\\n\", s, \"\\nV=\\n\", V)\n# ----------------------------------------------------------------------------------#\n# 19. Write a NumPy program to calculate the Frobenius norm and the condition number of a given array.\nimport numpy as np\n\na = np.arange(1, 10).reshape((3, 3))\nprint(\"Original array:\")\nprint(a)\nprint(\"Frobenius norm and the condition number:\")\nprint(np.linalg.norm(a, 'fro'))\nprint(np.linalg.cond(a, 'fro'))\n# ----------------------------------------------------------------------------------#\n", "meta": {"hexsha": "8febebf27ae9a104ed719d1a3d3da1b2f06fd467", "size": 7857, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumPy Linear Algebra: Exercises & solutions.py", "max_stars_repo_name": "AmalChandru/numpy-recipes", "max_stars_repo_head_hexsha": "e80b7695e0d6fd696682027e64220c63e90c8825", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-14T14:25:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T03:14:20.000Z", "max_issues_repo_path": "NumPy Linear Algebra: Exercises & solutions.py", "max_issues_repo_name": "AmalChandru/numpy-recipes", "max_issues_repo_head_hexsha": "e80b7695e0d6fd696682027e64220c63e90c8825", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumPy Linear Algebra: Exercises & solutions.py", "max_forks_repo_name": "AmalChandru/numpy-recipes", "max_forks_repo_head_hexsha": "e80b7695e0d6fd696682027e64220c63e90c8825", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7210300429, "max_line_length": 136, "alphanum_fraction": 0.5455008273, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793907, "lm_q2_score": 0.8976952818435995, "lm_q1q2_score": 0.8631643617687438}}
{"text": "import numpy as np\n\n# This function returns a value closer to the limit\ndef x2(x1): return x1 + (x1 * (10**-10))\n\n# This function calculates de variation when we move x closer to the limit\n# It is a good approximation for the derivative\ndef derivative(f, x): return (f(x2(x))-f(x))/(x2(x)-x)\n\n# Sample and test data\n\nx = np.array([1, 2, 3, 4, 5, 6, 7, 9, 10])\n\n# Test the derivative for x**2\nprint(\"Testing x**2 ...\")\nfunc = derivative(lambda x: x**2, x)\n_derivative = np.round(func, 3)\nprint(_derivative)\nerror = (np.sum(np.round(func - 2*x, 3)))\nprint(\"PASSED:\", error == 0.0, \"\\n\")\n\n\n# Test the derivative for x**3\nprint(\"Testing x**3 ...\")\nfunc = derivative(lambda x: x**3, x)\n_derivative = np.round(func, 3)\nprint(_derivative)\nerror = (np.sum(np.round(func - 3*x**2, 3)))\nprint(\"PASSED:\", error == 0.0, \"\\n\")\n\n\n# Test the derivative for sin(x)\nprint(\"Testing sin(x) ...\")\nfunc = derivative(lambda x: np.sin(x), x)\n_derivative = np.round(func, 3)\nprint(_derivative)\nerror = (np.sum(np.round(derivative(lambda x: np.sin(x), x) - np.cos(x), 3)))\nprint(\"PASSED:\", error == 0.0, \"\\n\")", "meta": {"hexsha": "fd2943eee0e53f92bad7ae5edff1c0a0f63c836c", "size": 1084, "ext": "py", "lang": "Python", "max_stars_repo_path": "NeuralNetwork/derivative.py", "max_stars_repo_name": "marcelaldecoa/DLND-Labs", "max_stars_repo_head_hexsha": "2aab4c693dbb0989e19d90fd717ce88ced29a07c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NeuralNetwork/derivative.py", "max_issues_repo_name": "marcelaldecoa/DLND-Labs", "max_issues_repo_head_hexsha": "2aab4c693dbb0989e19d90fd717ce88ced29a07c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NeuralNetwork/derivative.py", "max_forks_repo_name": "marcelaldecoa/DLND-Labs", "max_forks_repo_head_hexsha": "2aab4c693dbb0989e19d90fd717ce88ced29a07c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5263157895, "max_line_length": 77, "alphanum_fraction": 0.6457564576, "include": true, "reason": "import numpy", "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307661011976, "lm_q2_score": 0.8872045996818986, "lm_q1q2_score": 0.8630999303970477}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jan 16 14:53:16 2022\r\n\r\n\"\"\"\r\nimport numpy as np\r\nfrom MyQR import QR_householder\r\nfrom Mychol import mychol \r\n\r\ndef ls_with_qr(C,b):\r\n    A = C.copy()\r\n    m = A.shape[0]\r\n    n = A.shape[1]\r\n\r\n    [Q,R,rank] = QR_householder(A)\r\n\r\n    b = np.matmul(Q.T,b)\r\n    min_dim = min(m,n)\r\n\r\n    if rank < min_dim: # rank A < min_dim; Minimum norm solution is needed\r\n        ReducedR = R[0:rank,:]\r\n        L = mychol(np.matmul(ReducedR,ReducedR.T)) # L is a lower triangular matrix such that LL' = reducedA\r\n\r\n        w = forward(L,b[:rank]) # solve L w = b;; note that b is Q'b.\r\n\r\n        z = backward(L.T,w)  # solve L'z = w;\r\n        x = np.matmul(ReducedR.T,z)\r\n\r\n    else:      # R is nonsingular and square\r\n        x = backward(R,b[:n])\r\n    return(x)\r\n\r\n\r\ndef forward(A,b):\r\n    n = A.shape[1]\r\n    bn = b.shape[0]\r\n    if n != bn:\r\n        print(\"Number of rows of A  and b must be equal and A must be square\");\r\n\r\n    x = np.zeros((n,1))\r\n\r\n    x[0] = b[0]/A[0,0]\r\n\r\n    for i in range(1,n):\r\n        sum = np.matmul(A[i,:i],x[:i])\r\n        x[i] = (b[i] - sum)/A[i,i]\r\n    \r\n    return x\r\n\r\ndef backward(A,b):\r\n\r\n    n = A.shape[1]\r\n    bn = b.shape[0]\r\n    if n != bn:\r\n        print(\"Number of rows of A  and b must be equal and A must be square\")\r\n\r\n    x = np.zeros((n,1))\r\n\r\n    x[n-1] = b[n-1]/A[n-1,n-1]\r\n\r\n    for i in range(n-2,-1,-1):\r\n        sum = np.matmul(A[i,i+1:n],x[i+1:n])\r\n        x[i] = (b[i] - sum)/A[i,i]\r\n    return x\r\n\r\n''' \r\nThe main code\r\n'''   \r\ndef main():     \r\n    # A = np.array([[1.,2.,3.],[4.,5.,6.],[7.,8.,9.],[10.,11.,12.]])\r\n    # print(A)  \r\n    # b = np.reshape(np.array([-1.,-5.,2.,1.]),(4,1))\r\n    # print(b)\r\n    # x = ls_with_qr(A,b)\r\n    # print(x)\r\n    A = np.array([[1.8162 ,   0.7361 ,  -1.6029],\r\n                 [1.7961,    0.3619 ,  -0.6157],\r\n                 [1.4627 ,  -0.0455  ,  0.3997],\r\n                 [4.8991  ,  1.1483  , -2.1063]])\r\n    print(A)  \r\n#    b = np.reshape(np.array([-1.,-5.,2.,1.]),(4,1))\r\n    b = np.reshape(np.array([-0.0301, -0.1649, 0.6277, 1.0933]),(4,1))\r\n    print(b)\r\n    x = ls_with_qr(A,b)\r\n    print(x)\r\nif __name__ == \"__main__\":  ## This command executes the main function\r\n    main()     ", "meta": {"hexsha": "f41b5f8904268c40ab919baf1908c1a85fef53f2", "size": 2227, "ext": "py", "lang": "Python", "max_stars_repo_path": "ls_with_qr.py", "max_stars_repo_name": "FahadMostafa91/minimum_norm_geo", "max_stars_repo_head_hexsha": "7687ad61e3bba64178de5bce48f91e8c1e9ce09d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ls_with_qr.py", "max_issues_repo_name": "FahadMostafa91/minimum_norm_geo", "max_issues_repo_head_hexsha": "7687ad61e3bba64178de5bce48f91e8c1e9ce09d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ls_with_qr.py", "max_forks_repo_name": "FahadMostafa91/minimum_norm_geo", "max_forks_repo_head_hexsha": "7687ad61e3bba64178de5bce48f91e8c1e9ce09d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5977011494, "max_line_length": 109, "alphanum_fraction": 0.4777727885, "include": true, "reason": "import numpy", "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307739782681, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.8630999243294712}}
{"text": "import numpy as np\n\ndef riemann(func,a,b,n=10):\n    \"\"\"A simple Riemann-sum approximation to the integral of a function\n\nParameters\n----------\nfunc: callable\n    Function to integrate, should be a function of one parameter\na: float\n    Lower limit of the integration range\nb: float\n    Upper limit of the integration range\nn: int, optional\n    Number of intervals to split [a,b] into for the Riemann sum\n\nReturns\n-------\nfloat\n    Integral of func(x) over [a,b]\n\"\"\"\n    return np.sum(func(np.linspace(a,b,n))*(b-a)/n)\n\ndef simps(func,a,b,n=10):\n    \"\"\"Integrate a function using Simpson's rule\n\nParameters\n----------\nfunc: callable\n    Function to integrate, should be a function of one parameter\na: float\n    Lower limit of the integration range\nb: float\n    Upper limit of the integration range\nn: int, optional\n    Number of major intervals to split [a,b] into for the Simpson rule\n\nReturns\n-------\nfloat\n    Integral of func(x) over [a,b]\n\nNotes\n-----\nApplies Simpson's rule as\n\n.. math::\n\n    \\\\int_a^b \\\\mathrm{d}x f(x) \\\\approx \\\\frac{(b-a)}{6n}\\\\,\\\\left[f(a)+4f(a+h/2)+2f(a+h)+4f(a+3h/2)+\n    \n    \\ldots+2f(b-h)+4f(b-h/2)+f(b)\\\\right]\n\nSee Also\n--------\nexampy.integrate.riemann: Integrate a function with a simple Riemann sum\n\"\"\"\n    try:\n        return (2.*np.sum(func(np.linspace(a,b,n+1)))\n                -func(a)-func(b) # adjust double-counted first and last\n                +4.*np.sum(func(np.linspace(a+(b-a)/n/2,b-(b-a)/n/2,n))))\\\n                *(b-a)/n/6.\n    except TypeError:\n        raise TypeError(\"Provided func needs to be callable on arrays of inputs\")\n", "meta": {"hexsha": "ca4701bcda0291f34b707ae61cf483a9de3c0d28", "size": 1582, "ext": "py", "lang": "Python", "max_stars_repo_path": "exampy/integrate/_integrate.py", "max_stars_repo_name": "celis/test-pkg", "max_stars_repo_head_hexsha": "5b6e3b4e872aef8f2d027aea102402d96f516fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-03-05T01:56:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-16T00:17:28.000Z", "max_issues_repo_path": "exampy/integrate/_integrate.py", "max_issues_repo_name": "jobovy/exampy", "max_issues_repo_head_hexsha": "a6c23371a938e1c9b93d529a2dd0ca6053a4f092", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-18T11:07:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-18T11:07:01.000Z", "max_forks_repo_path": "exampy/integrate/_integrate.py", "max_forks_repo_name": "celis/test-pkg", "max_forks_repo_head_hexsha": "5b6e3b4e872aef8f2d027aea102402d96f516fa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-04T20:42:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-13T03:19:58.000Z", "avg_line_length": 24.71875, "max_line_length": 102, "alphanum_fraction": 0.6346396966, "include": true, "reason": "import numpy", "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307684643189, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.8630999194374702}}
{"text": "import random\nimport numpy as np\nfrom statistics import mean\n\n# Using \"random\" to create a dataset\ndef create_dataset(hm, variance, step=2, correlation=False):\n    val = 1\n    sy = []\n    for i in range(hm):\n        y = val + random.randrange(-variance, variance)\n        sy.append(y)\n        if correlation and correlation == 'pos':\n            val += step\n        elif correlation and correlation == 'neg':\n            val -= step\n\n    sx = [i for i in range(len(sy))]\n\n    return np.array(sx, dtype=np.float64), np.array(sy, dtype=np.float64)\n\n\n# finding best fit slope and intercept of dataset\ndef best_fit_slope_and_intercept(sx, sy):\n    m = (((mean(sx) * mean(sy)) - mean(sx * sy)) /\n         ((mean(sx) * mean(sx)) - mean(sx * sx)))\n\n    b = mean(sy) - m * mean(sx)\n\n    return m, b\n\n\n# dataset - coefficient of determination\ndef coefficient_of_determination(sy_orig, sy_line):\n    y_mean_line = [mean(sy_orig) for y in sy_orig]\n\n    squared_error_regr = sum((sy_line - sy_orig) * (sy_line - sy_orig))\n    squared_error_y_mean = sum((y_mean_line - sy_orig) * (y_mean_line - sy_orig))\n\n    print(squared_error_regr)\n    print(squared_error_y_mean)\n\n    r_squared = 1 - (squared_error_regr / squared_error_y_mean)\n\n    return r_squared\n\n\ndef get_result():\n    sx, sy = create_dataset(20, 10, 3)\n    m, b = best_fit_slope_and_intercept(sx, sy)\n    regression_line = [(m * x) + b for x in sx]\n    r_squared = coefficient_of_determination(sy, regression_line)\n    print('Rsquared result: ')\n    return r_squared", "meta": {"hexsha": "e8c95e7b59dd148dc3eef67592919eeccef9827d", "size": 1514, "ext": "py", "lang": "Python", "max_stars_repo_path": "dashboard/regression.py", "max_stars_repo_name": "mina-gaid/scp", "max_stars_repo_head_hexsha": "38e1cd303d4728a987df117f666ce194e241ed1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dashboard/regression.py", "max_issues_repo_name": "mina-gaid/scp", "max_issues_repo_head_hexsha": "38e1cd303d4728a987df117f666ce194e241ed1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dashboard/regression.py", "max_forks_repo_name": "mina-gaid/scp", "max_forks_repo_head_hexsha": "38e1cd303d4728a987df117f666ce194e241ed1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5660377358, "max_line_length": 81, "alphanum_fraction": 0.6538969617, "include": true, "reason": "import numpy", "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993027, "lm_q2_score": 0.9149009486120849, "lm_q1q2_score": 0.8630695894994602}}
{"text": "from sympy.abc import x\nimport sympy as sp\nimport math\n\n\ndef improved_Newton_iteration(x0, func, tol=1e-9, Max_iter=100):\n    \"\"\" Solve non-linear equation by improved Newton iteration method.\n\n    Args:\n        x0: double, iteration initial value\n        func: function object, the function to be solved\n        tol: double, iteration accuracy\n        Max_iter: int, maximum iteration number\n\n    Returns:\n        k: int, iteration number\n        z: double, root of the non-linear equation\n    \"\"\"\n    # derivative\n    y_diff = sp.diff(func(x))\n\n    # first iteration\n    k = 1\n    u = x0\n    v = u - func(u) / y_diff.subs(x, u)\n    z = u - 2 * func(u) / (y_diff.subs(x, u) + y_diff.subs(x, v))\n\n    # iteration\n    while math.fabs(z - u) >= tol and y_diff.subs(x, z) != 0 and k < Max_iter:\n        k += 1\n        u = z\n        v = u - func(u) / y_diff.subs(x, u)\n        z = u - 2 * func(u) / (y_diff.subs(x, u) + y_diff.subs(x, v))\n\n    return k, z\n\n\ndef f(x):\n    return sp.Pow(x, 3) + sp.Pow(x, 2) - 3 * x - 3\n\n\nif __name__ == '__main__':\n    n, root = improved_Newton_iteration(2.0, f, 1e-6)\n    print(f\"The root of the non-linear equation is {root:.7f} by improved Newton iteration method.\")\n    print(f\"Iteration number is {n}\")\n\n", "meta": {"hexsha": "2f73e361e078534410438a99d6b8b2dfd732d5cc", "size": 1238, "ext": "py", "lang": "Python", "max_stars_repo_path": "NonLinearEquation/imporved_newton_iteration.py", "max_stars_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_stars_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NonLinearEquation/imporved_newton_iteration.py", "max_issues_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_issues_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NonLinearEquation/imporved_newton_iteration.py", "max_forks_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_forks_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3404255319, "max_line_length": 100, "alphanum_fraction": 0.5920840065, "include": true, "reason": "import sympy,from sympy", "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760638, "lm_q2_score": 0.9059898140375993, "lm_q1q2_score": 0.8630224547970878}}
{"text": "\"\"\"\n# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n@Time        : 2022/3/26 18:13\n@File        : softmax.py\n\"\"\"\n\n# Solution is available in the other \"solution.py\" tab\nimport numpy as np\n\n\ndef softmax(x):\n    \"\"\"Compute softmax values for each sets of scores in x.\"\"\"\n    # TODO: Compute and return softmax(x)\n\n    return np.exp(x) / np.sum(np.exp(x), axis=0)\n    # x = np.divide(np.exp(x), np.sum(np.exp(x)))\n    # return x\n\n\nlogits = [3.0, 1.0, 0.2]\nprint(softmax(logits))\n# [0.8360188  0.11314284 0.05083836]\n# [0.8360188  0.11314284 0.05083836]\n", "meta": {"hexsha": "46463d5847d5650e896bca81bb1011b3ae93e519", "size": 549, "ext": "py", "lang": "Python", "max_stars_repo_path": "udacity-program_self_driving_car_engineer_v1.0/part01-computer vision and deep learning/module03-deep learning/lesson03-introduction to tensorflow/exercise17-softmax/softmax.py", "max_stars_repo_name": "linksdl/futuretec-project-self_driving_cars_projects", "max_stars_repo_head_hexsha": "38e8f14543132ec86a8bada8d708eefaef23fee8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "udacity-program_self_driving_car_engineer_v1.0/part01-computer vision and deep learning/module03-deep learning/lesson03-introduction to tensorflow/exercise17-softmax/softmax.py", "max_issues_repo_name": "linksdl/futuretec-project-self_driving_cars_projects", "max_issues_repo_head_hexsha": "38e8f14543132ec86a8bada8d708eefaef23fee8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "udacity-program_self_driving_car_engineer_v1.0/part01-computer vision and deep learning/module03-deep learning/lesson03-introduction to tensorflow/exercise17-softmax/softmax.py", "max_forks_repo_name": "linksdl/futuretec-project-self_driving_cars_projects", "max_forks_repo_head_hexsha": "38e8f14543132ec86a8bada8d708eefaef23fee8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.96, "max_line_length": 62, "alphanum_fraction": 0.6083788707, "include": true, "reason": "import numpy", "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.953966101527047, "lm_q2_score": 0.9046505325302034, "lm_q1q2_score": 0.8630059417622051}}
{"text": "import numpy as np\nimport math\nfrom copy import deepcopy\n\ndef ReadMatrixAndVec():\n    matrixSize = int(input())\n\n    matrix = [list(map(float, input().split())) for i in range(matrixSize)]\n    vec = list(map(float, input().split()))\n\n    return matrix, vec\n\ndef swapLines(matrix, idxFrom, idxTo):\n    matrix[idxFrom], matrix[idxTo] = matrix[idxTo], matrix[idxFrom]\n\ndef pivot(matrix):\n    p = []\n    mtrx = matrix.copy()\n    for j in range(len(mtrx)):\n        tmp = [(mtrx[i][j], i) for i in range(j, len(mtrx))]\n        idx = max(tmp, key=lambda x: abs(x[0]))[1]\n        if idx != j:\n            p.append((j, idx))\n            swapLines(mtrx, j, idx)\n    return p, mtrx\n\ndef LUDecomp(matrix):\n    shape = len(matrix)\n    lower = np.zeros((shape, shape))\n    upper = np.zeros((shape, shape))\n    pivo, pMtx = pivot(matrix)\n\n    for i in range(shape):\n        lower[i][i] = 1.0\n\n        for j in range(i + 1):\n            upper[j][i] = pMtx[j][i] - math.fsum([lower[j][k] * upper[k][i] for k in range(j)])\n        for j in range(i, shape):\n            lower[j][i] = (pMtx[j][i] - math.fsum([lower[j][k] * upper[k][i] for k in range(i)])) / upper[i][i]\n\n    return lower, upper, pivo\n\ndef DirectSubstit(lowerMatrix, valVec):\n    res = deepcopy(valVec)\n\n    for i in range(1, len(valVec)):\n        res[i] = valVec[i] - math.fsum([lowerMatrix[i][j] * res[j] for j in range(i)])\n\n    return res\n\ndef InverseSubstit(upperMatrix, valVec):\n    res = [0 for i in range(len(valVec))]\n    res[-1] = valVec[-1] / upperMatrix[-1][-1]\n\n    for i in reversed(range(len(valVec) - 1)):\n        res[i] = (valVec[i] - math.fsum([upperMatrix[i][j] * res[j] for j in range(i + 1, len(valVec))])) / upperMatrix[i][i]\n\n    return res\n\ndef pivotVec(vec, pivo):\n    res = vec.copy()\n\n    for i in range(len(pivo)):\n        fromIdx, toIdx = pivo[i]\n        swapLines(res, fromIdx, toIdx)\n\n    return res\n\ndef SolveSLAU(matrix, valVec, isSingle):\n    lower, upper, pivo = LUDecomp(matrix)\n\n    if isSingle:\n        print(\"Lower:\")\n        print(lower)\n        print(\"Upper:\")\n        print(upper)\n\n    pVec = pivotVec(valVec, pivo)\n\n    if isSingle:\n        print(\"Pivoted vector:\")\n        print(pVec)\n\n    rhsVec = DirectSubstit(lower, pVec)\n\n    if isSingle:\n        print(\"rhsVec:\")\n        print(rhsVec)\n\n    solVec = InverseSubstit(upper, rhsVec)\n\n    return solVec\n\ndef InverseMtx(matrix):\n    res = [[] for i in range(len(matrix))]\n    eVec = [0.0 for i in range(len(matrix))]\n\n    for i in range(len(matrix)):\n        eVec[i] = 1.0\n        tmp = SolveSLAU(matrix, eVec, False)\n        for j in range(len(tmp)):\n            res[j].append(tmp[j])\n        eVec[i] = 0\n\n    return res\n\ndef submatrix(M, c):\n    B = [[1] * len(M) for i in range(len(M))]\n\n    for l in range(len(M)):\n        for k in range(len(M)):\n            B[l][k] = M[l][k]\n\n    B.pop(0)\n\n    for i in range(len(B)):\n        B[i].pop(c)\n    return B\n\ndef det(mtx):\n    res = 0\n\n    if len(mtx) <= 2:\n        return mtx[0][0] * mtx[1][1] - mtx[0][1] * mtx[1][0]\n    else:\n        for i in range(len(mtx)):\n            res += ((-1) ** (i)) * mtx[0][i] * det(submatrix(mtx, i))\n\n    return res\n\nif __name__ == \"__main__\":\n    matrix, vec = ReadMatrixAndVec()\n    print(\"Orig Matrix:\")\n    print(matrix)\n    print(\"valVec:\")\n    print(vec)\n\n    result = np.matrix(SolveSLAU(matrix, vec, True)).transpose()\n    npMtx = np.matrix(matrix)\n    npVec = np.matrix(vec).transpose()\n\n    print(\"Result:\")\n    print(result)\n    print(\"matrix determinant:\")\n    print(det(matrix))\n    print(\"matrix inverse:\")\n    print(np.matrix(InverseMtx(matrix)))\n", "meta": {"hexsha": "41127ba9477b49f6ae055473243522d22bd40fc1", "size": 3585, "ext": "py", "lang": "Python", "max_stars_repo_path": "6th_semester/NumMethods/1_lab/task1.py", "max_stars_repo_name": "mehakun/Labs", "max_stars_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-03-06T16:08:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-02T22:11:00.000Z", "max_issues_repo_path": "6th_semester/NumMethods/1_lab/task1.py", "max_issues_repo_name": "mehakun/Labs", "max_issues_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6th_semester/NumMethods/1_lab/task1.py", "max_forks_repo_name": "mehakun/Labs", "max_forks_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.222972973, "max_line_length": 125, "alphanum_fraction": 0.5612273361, "include": true, "reason": "import numpy", "num_tokens": 1080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347860767304, "lm_q2_score": 0.8856314798554444, "lm_q1q2_score": 0.8629901216157582}}
{"text": "import numpy as np\nimport numpy.linalg as linalg\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom scipy.stats import chi2\n\n\nx, y = np.random.normal(size=(2, 100))\nz = x + y + np.random.normal(size=(1, 100))\npoints = np.array([x, y, z.squeeze()])\n\nA = np.cov(points)\n\ncenter = points.mean(axis=1)\n\n# your ellispsoid and center in matrix form\n# A = np.array([[10,0,0],[0,2,0],[0,0,2]])\n\n# A = np.array([[ 0.00009, -0.00024, -0.00014],\n#        [-0.00024,  0.00095,  0.00068],\n#        [-0.00014,  0.00068,  0.00063]])\n\n# center = [0,0,0]\n\n# find the rotation matrix and radii of the axes\nU, s, rotation = linalg.svd(A)\nradii = np.sqrt(s)\n\n# multiply sizes by desired percentile from chi square dist\nchi_dist = chi2(3)\nmag = np.sqrt(chi_dist.ppf(.95))\nradii = radii * mag\n\n# todo no scaling based on confidence interval yet -- test this but with points and confidence intervals\n# see https://www.mathworks.com/matlabcentral/fileexchange/4705-error_ellipse\n\n# now carry on with EOL's answer\nu = np.linspace(0.0, 2.0 * np.pi, 100)\nv = np.linspace(0.0, np.pi, 100)\nx = radii[0] * np.outer(np.cos(u), np.sin(v))\ny = radii[1] * np.outer(np.sin(u), np.sin(v))\nz = radii[2] * np.outer(np.ones_like(u), np.cos(v))\nfor i in range(len(x)):\n    for j in range(len(x)):\n        [x[i,j],y[i,j],z[i,j]] = np.dot([x[i,j],y[i,j],z[i,j]], rotation) + center\n\n# plot\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\nax.scatter(points[0], points[1], points[2])\n\nax.plot_wireframe(x, y, z,  rstride=1, cstride=1, color='b', alpha=0.2)\n\n# lim = 2\n# ax.set_xlim([-lim, lim])\n# ax.set_ylim([-lim, lim])\n# ax.set_zlim([-lim, lim])\n\n# with points\np = points\nax.set_xlim([p[0].min() - .1, p[0].max() + .1])\nax.set_ylim([p[1].min() - .1, p[1].max() + .1])\nax.set_zlim([p[2].min() - .1, p[2].max() + .1])\n\nplt.show()\nplt.close(fig)\ndel fig", "meta": {"hexsha": "7a694e0eef74529de8e091ff75f87999a30b08f5", "size": 1850, "ext": "py", "lang": "Python", "max_stars_repo_path": "multiview_manipulation/plotting/feature_analysis/ellipsoid_test.py", "max_stars_repo_name": "utiasSTARS/multiview-manipulation", "max_stars_repo_head_hexsha": "0913b17a4b67ed947cc72e99964a5ff2b84590c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T07:51:49.000Z", "max_issues_repo_path": "multiview_manipulation/plotting/feature_analysis/ellipsoid_test.py", "max_issues_repo_name": "utiasSTARS/multiview-manipulation", "max_issues_repo_head_hexsha": "0913b17a4b67ed947cc72e99964a5ff2b84590c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multiview_manipulation/plotting/feature_analysis/ellipsoid_test.py", "max_forks_repo_name": "utiasSTARS/multiview-manipulation", "max_forks_repo_head_hexsha": "0913b17a4b67ed947cc72e99964a5ff2b84590c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2058823529, "max_line_length": 104, "alphanum_fraction": 0.6335135135, "include": true, "reason": "import numpy,from scipy", "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241982893258, "lm_q2_score": 0.8902942232112239, "lm_q1q2_score": 0.8629837341558376}}
{"text": "import numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n\ndef helper_best_rank_k_approximation(input_matrix, k, print_result=False):\n    \"\"\"\n    Helper function for best_rank_k_approximation.\n    Performs SVD on a given matrix and creates lower (k) dim matrix.\n\n    Args:\n    input_matrix (np.ndarray): a matrix representing one of r/g/b image\n    k (int): the desired rank of out_matrix\n    print_result (bool): default False\n\n    Returns:\n        out_matrix\n    \"\"\"\n    matrix = np.array(input_matrix)\n    u, singular_values, v = np.linalg.svd(matrix, full_matrices=False)\n    rows = np.ma.size(matrix, 0)\n    columns = np.ma.size(matrix, 1)\n    out_matrix = np.zeros((rows, columns))\n\n    for i in range(k):\n        temp = (singular_values[i]*u[:, i:i+1])\n        out_matrix += (np.matmul(temp, v[i:i+1, :]))\n\n    singular_values_squared = singular_values*singular_values\n    calculated_rate = sum(singular_values_squared[k:]) / sum(singular_values_squared)\n\n    if print_result:\n        print(\"When k is \", k, \", error of red matrix is \", calculated_rate)\n\n    return out_matrix, calculated_rate\n\n\ndef best_rank_k_approximation(image_name, k_list):\n    \"\"\"\n    Creates 'compressed' images of lower resolution from a given image.\n    Each k value in k_list will create a save a new image with corresponding name.\n    Args:\n    image_name (str): file location, assumes location same folder.\n    k_list (list): the desired k values to be used.\n    \"\"\"\n    image = Image.open(image_name)\n    b, g, r = image.split()\n    rates_b = []\n    rates_r = []\n    rates_g = []\n\n    for k_value in k_list:\n        r_new, rate_r = helper_best_rank_k_approximation(r, k_value, print_result=True)\n        g_new, rate_g = helper_best_rank_k_approximation(g, k_value)\n        b_new, rate_b = helper_best_rank_k_approximation(b, k_value)\n        image_r_new = Image.fromarray(r_new.clip(0, 255).astype('uint8'))\n        image_g_new = Image.fromarray(g_new.clip(0, 255).astype('uint8'))\n        image_b_new = Image.fromarray(b_new.clip(0, 255).astype('uint8'))\n        image_new = Image.merge(\"RGB\", (image_b_new, image_g_new, image_r_new))\n        image_new.save(str(k_value)+\"_approximation_\"+image_name)\n        rates_b.append(rate_b*100)\n        rates_g.append(rate_g*100)\n        rates_r.append(rate_r*100)\n\n    plt.plot(k_list, rates_b, 'b', k_list, rates_r, 'r', k_list, rates_g, 'g')\n    plt.xlabel('k (values)')\n    plt.ylabel('Error Rate (percentage)')\n    plt.title('Best Rank K Approximation')\n    plt.show()\n\n\ndef main():\n    k = list(range(5, 165, 5))\n    best_rank_k_approximation(\"cute_dog.jpg\", k)\n\n\nmain()\n", "meta": {"hexsha": "f59e50f7a4d4c5f66d36a71086985ac90e6eeee3", "size": 2623, "ext": "py", "lang": "Python", "max_stars_repo_path": "Image_Related/SVD_Image_Compression/best_k_approximation.py", "max_stars_repo_name": "scaperex/My_Projects", "max_stars_repo_head_hexsha": "cd73d29249485f8aa2d4da9df2fd5f08bbb043e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Image_Related/SVD_Image_Compression/best_k_approximation.py", "max_issues_repo_name": "scaperex/My_Projects", "max_issues_repo_head_hexsha": "cd73d29249485f8aa2d4da9df2fd5f08bbb043e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-13T13:40:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-01T17:16:16.000Z", "max_forks_repo_path": "Image_Related/SVD_Image_Compression/best_k_approximation.py", "max_forks_repo_name": "scaperex/My_Projects", "max_forks_repo_head_hexsha": "cd73d29249485f8aa2d4da9df2fd5f08bbb043e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-26T10:10:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T07:06:47.000Z", "avg_line_length": 33.6282051282, "max_line_length": 87, "alphanum_fraction": 0.6763248189, "include": true, "reason": "import numpy", "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241965169938, "lm_q2_score": 0.8902942246666267, "lm_q1q2_score": 0.8629837339886978}}
{"text": "# sample 2d objective function\nfrom numpy import arange\nfrom numpy import meshgrid\n\n# objective function\ndef objective(x, y):\n\treturn x**2.0 + y**2.0\n\n# define range for input\nr_min, r_max = -5.0, 5.0\n# sample input range uniformly at 0.1 increments\nxaxis = arange(r_min, r_max, 0.1)\nyaxis = arange(r_min, r_max, 0.1)\n# create a mesh from the axis\nx, y = meshgrid(xaxis, yaxis)\n# summarize some of the input domain\nprint(x[:5, :5])\n# compute targets\nresults = objective(x, y)\n# summarize some of the results\nprint(results[:5, :5])\n# create a mapping of some inputs to some results\nfor i in range(5):\n\tprint('f(%.3f, %.3f) = %.3f' % (x[i,0], y[i,0], results[i,0]))\n", "meta": {"hexsha": "80c4cefff3dc8d69648807f1e6909185fcdf3b3b", "size": 664, "ext": "py", "lang": "Python", "max_stars_repo_path": "Books/code/chapter_07/21_meshgrid.py", "max_stars_repo_name": "Mikma03/Optimization_in_Machine_Learning", "max_stars_repo_head_hexsha": "257d0455d4ae0b4fc7a762eda841a16611c49000", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-30T11:07:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:07:28.000Z", "max_issues_repo_path": "Books/code/chapter_07/21_meshgrid.py", "max_issues_repo_name": "Mikma03/Optimization_in_Machine_Learning", "max_issues_repo_head_hexsha": "257d0455d4ae0b4fc7a762eda841a16611c49000", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Books/code/chapter_07/21_meshgrid.py", "max_forks_repo_name": "Mikma03/Optimization_in_Machine_Learning", "max_forks_repo_head_hexsha": "257d0455d4ae0b4fc7a762eda841a16611c49000", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.56, "max_line_length": 63, "alphanum_fraction": 0.6897590361, "include": true, "reason": "from numpy", "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.912436161072216, "lm_q1q2_score": 0.8629832828852224}}
{"text": "'''quadrature.py\nAuthor: Huaiyu Duan (UNM)\nDescription: Python module that define the mesh and weights of various quadrature rules.\n'''\nimport numpy as np\n\nRULES = {} # dictionary of the quadrature rules\n\ndef mesh(a, b, n, rule='midpoint'):\n    '''Compute the abscissas x[n] and weights w[n] using n nodes and the specified rule.\n    The sum of f(x[i]) * w[i] gives an approximation of integral of f(x) for x from a to b.\n    a : lower limit of the integral\n    b : upper limit of the integral\n    n : number of nodes\n    rule : name of the quadrature rule\n\n    return : x[n], w[n]\n    '''\n    assert rule in RULES, f\"Unknown quadrature rule '{rule}''. The available choices are {list(RULES)}.\"\n    return RULES[rule](a, b, n)\n\ndef _midpoint(a, b, n):\n    '''Compute the mesh points x[n] and weights w[n] using the (composite) midpoint rule.\n    The sum of f(x[i]) * w[i] gives an approximation of integral of f(x) for x from a to b.\n    a : lower limit of the integral\n    b : upper limit of the integral\n    n : number of points\n\n    return : x[n], w[n]\n    '''\n    n = int(n)\n    assert n >= 1, \"Number of abscissas should be at least 1 for the midpoint rule.\"\n    dx = (b - a) / n # mesh interval\n    x = a + (np.arange(n) + 0.5) * dx\n    w = np.ones_like(x) * dx\n    return x, w\nRULES['midpoint'] = _midpoint\n\ndef _trapezoid(a, b, n):\n    '''Compute the mesh points x[n] and weights w[n] using the (composite) trapezoid rule.\n    The sum of f(x[i]) * w[i] gives an approximation of integral of f(x) for x from a to b.\n    a : lower limit of the integral\n    b : upper limit of the integral\n    n : number of points\n\n    return : x[n], w[n]\n    '''\n    n = int(n)\n    assert n >= 2, \"Number of abscissas should be at least 2 for the trapezoid rule.\"\n    x = np.linspace(a, b, n)\n    w = np.ones_like(x) * (x[1] - x[0])\n    w[0] *= 0.5; w[-1] *= 0.5\n    return x, w\nRULES['trapezoid'] = _trapezoid\n\ndef _simpson(a, b, n):\n    '''Compute the mesh points x[n] and weights w[n] using the (composite) Simpson's rule.\n    The sum of f(x[i]) * w[i] gives an approximation of integral of f(x) for x from a to b.\n    a : lower limit of the integral\n    b : upper limit of the integral\n    n : number of points\n\n    return : x[n], w[n]\n    '''\n    n = int(n)\n    assert n >= 3 and n%2 ,  \"The number of abscissas should be an odd number larger than or equal to 3 for Simpson's rule.\"\n    x = np.linspace(a, b, n)\n    w = np.ones_like(x) * (x[1] - x[0]) \n    w[0] *= 1/3; w[-1] *= 1/3\n    w[1:-1:2] *= 4/3; w[2:-2:2] *= 2/3\n    return x, w\nRULES['simpson'] = _simpson\n\ndef _simpson2(a, b, n):\n    '''Compute the mesh points x[n] and weights w[n] using an alternative Simpson's rule that works better for functions with narrow peaks.\n    The sum of f(x[i]) * w[i] gives an approximation of integral of f(x) for x from a to b.\n    a : lower limit of the integral\n    b : upper limit of the integral\n    n : number of points\n\n    return : x[n], w[n]\n    '''\n    n = int(n)\n    assert n >= 6,  \"The number of abscissas should be at least 6 for the alternative Simpson's rule.\"\n    x = np.linspace(a, b, n)\n    w = np.ones_like(x) * (x[1] - x[0]) \n    w[0] *= 9/24; w[-1] *= 9/24\n    w[1] *= 28/24; w[-2] *= 28/24\n    w[2] *= 23/24; w[-3] *= 23/24\n    return x, w\nRULES['simpson2'] = _simpson2\n\ndef _chebyshev(a, b, n):\n    '''Compute the mesh points x[n] and weights w[n] using the Chebyshev-Gaussian quadrature.\n    The sum of f(x[i]) * w[i] gives an approximation of integral of f(x) for x from a to b.\n    a : lower limit of the integral\n    b : upper limit of the integral\n    n : number of points\n\n    return : x[n], w[n]\n    '''\n    from scipy.special import roots_chebyt\n    y, w = roots_chebyt(n)\n    x = (b-a)*0.5*np.array(y) + (b+a)*0.5 # transform from [-1, 1] to [a, b]\n    w *= 0.5 * (b - a) * np.sqrt(1 - y**2)\n    return x, w\n#     # y = [np.cos(np.pi*(j+0.5)/n) for j in range(n)] # Chebyshev nodes\n#     # x = (b-a)*0.5*np.array(y) + (b+a)*0.5 # transform from [-1, 1] to [a, b]\n#     # w = [np.sqrt(1-y[j]**2) for j in range(n)]\n#     # w = 0.5*(b-a)*(np.pi/n)*np.array(w) # weights\n#     # return x, w\nRULES['chebyshev'] = _chebyshev\n\ndef _legendre(a, b, n):\n    '''Compute the mesh points x[n] and weights w[n] using the Legendre-Gaussian quadrature.\n    The sum of f(x[i]) * w[i] gives an approximation of integral of f(x) for x from a to b.\n    a : lower limit of the integral\n    b : upper limit of the integral\n    n : number of points\n\n    return : x[n], w[n]\n    '''\n    from scipy.special import roots_legendre\n    y, w = roots_legendre(n)\n    x = (b-a)*0.5*np.array(y) + (b+a)*0.5 # transform from [-1, 1] to [a, b]\n    w *= 0.5 * (b - a)\n    return x, w\nRULES['legendre'] = _legendre\n\n", "meta": {"hexsha": "6dca60f04acefa0077f17ef5e8450a235dada3cb", "size": 4703, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/nugas/misc/quadrature.py", "max_stars_repo_name": "NuCO-UNM/nugas", "max_stars_repo_head_hexsha": "884d44e8a1f5198bdf64721ecae41b3911ba3626", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nugas/misc/quadrature.py", "max_issues_repo_name": "NuCO-UNM/nugas", "max_issues_repo_head_hexsha": "884d44e8a1f5198bdf64721ecae41b3911ba3626", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nugas/misc/quadrature.py", "max_forks_repo_name": "NuCO-UNM/nugas", "max_forks_repo_head_hexsha": "884d44e8a1f5198bdf64721ecae41b3911ba3626", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1769230769, "max_line_length": 139, "alphanum_fraction": 0.5983414842, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012640659996, "lm_q2_score": 0.912436157500568, "lm_q1q2_score": 0.8629832711435607}}
{"text": "\"\"\"\r\nThis script demonstrates the implementation of the Sigmoid function.\r\n\r\nThe function takes a vector of K real numbers as input and then 1 / (1 + exp(-x)).\r\nAfter through Sigmoid, the element of the vector mostly 0 between 1. or 1 between -1.\r\n\r\nScript inspired from its corresponding Wikipedia article\r\nhttps://en.wikipedia.org/wiki/Sigmoid_function\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\n\r\ndef sigmoid(vector: np.array) -> np.array:\r\n    \"\"\"\r\n    Implements the sigmoid function\r\n\r\n    Parameters:\r\n        vector (np.array): A  numpy array of shape (1,n)\r\n        consisting of real values\r\n\r\n    Returns:\r\n        sigmoid_vec (np.array): The input numpy array, after applying\r\n        sigmoid.\r\n\r\n    Examples:\r\n    >>> sigmoid(np.array([-1.0, 1.0, 2.0]))\r\n    array([0.26894142, 0.73105858, 0.88079708])\r\n\r\n    >>> sigmoid(np.array([0.0]))\r\n    array([0.5])\r\n    \"\"\"\r\n    return 1 / (1 + np.exp(-vector))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    import doctest\r\n\r\n    doctest.testmod()\r\n", "meta": {"hexsha": "53d7ac0d8dd0025fb9f5a628fa77b039dd92d59e", "size": 983, "ext": "py", "lang": "Python", "max_stars_repo_path": "maths/sigmoid.py", "max_stars_repo_name": "TeddyFirman/Algorithm_Python", "max_stars_repo_head_hexsha": "edbd50a97a62c2beb2a187e4c411c677aa43115e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "maths/sigmoid.py", "max_issues_repo_name": "TeddyFirman/Algorithm_Python", "max_issues_repo_head_hexsha": "edbd50a97a62c2beb2a187e4c411c677aa43115e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maths/sigmoid.py", "max_forks_repo_name": "TeddyFirman/Algorithm_Python", "max_forks_repo_head_hexsha": "edbd50a97a62c2beb2a187e4c411c677aa43115e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.575, "max_line_length": 86, "alphanum_fraction": 0.6297049847, "include": true, "reason": "import numpy", "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620619801094, "lm_q2_score": 0.8991213860551286, "lm_q1q2_score": 0.8629425954506842}}
{"text": "import numpy as np\n\n\nclass Regularizations:\n\n    @staticmethod\n    def lasso_l1(w,lambda_):\n        \"\"\"Computes lasso regularization\n\n        Args:\n            w (np.ndarray): matrix of layer's weights\n            lambda_ (float): regularization hyperparameter\n\n        Returns:\n            np.float64: value of regularization/penalty term\n        \"\"\"\n        return lambda_ * np.linalg.norm(w,1)\n    \n    @staticmethod\n    def lasso_l1_der(w,lambda_):\n        \"\"\"Computes lasso regularization's derivative \n\n        Args:\n            w (np.ndarray): matrix of layer's weights\n            lambda_ (float): regularization hyperparameter\n\n        Returns:\n            np.ndarray: derivative of lasso regularization\n        \"\"\"\n        return lambda_ * np.sign(w)\n\n    @staticmethod\n    def ridge_regression_l2(w,lambda_):\n        \"\"\"Computes ridge regression\n\n        Args:\n            w (np.ndarray): matrix of layer's weights\n            lambda_ (float): regularization hyperparameter\n\n        Returns:\n            np.float64: value of regularization/penalty term\n        \"\"\"\n        return 1/2 * lambda_ * np.linalg.norm(w,2) * np.linalg.norm(w,2)\n\n    @staticmethod\n    def ridge_regression_l2_der(w,lambda_):\n        \"\"\"Computes ridge regression's derivative \n\n        Args:\n            w (np.ndarray): matrix of layer's weights\n            lambda_ (float): regularization hyperparameter\n\n        Returns:\n            np.ndarray: derivative of ridge regression\n        \"\"\"\n        return lambda_ * w\n\n    @staticmethod\n    def init_regularization(name):\n        if name == \"lasso\":\n            return Regularizations.lasso_l1, Regularizations.lasso_l1_der, name\n        elif name == \"ridge_regression\":\n            return Regularizations.ridge_regression_l2, Regularizations.ridge_regression_l2_der, name\n        else:\n            raise NameError(name+ \" is not recognized! Check for correct names and possible regularizations in init_regularization!\")", "meta": {"hexsha": "e5d8a9e8155e92248c2724c284880f689db137dc", "size": 1955, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/regularizations.py", "max_stars_repo_name": "dilettagoglia/impl-NN-from-scratch", "max_stars_repo_head_hexsha": "b7a6aacd0823b78de5fa58bc0e1581f4cd40bb8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/regularizations.py", "max_issues_repo_name": "dilettagoglia/impl-NN-from-scratch", "max_issues_repo_head_hexsha": "b7a6aacd0823b78de5fa58bc0e1581f4cd40bb8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/regularizations.py", "max_forks_repo_name": "dilettagoglia/impl-NN-from-scratch", "max_forks_repo_head_hexsha": "b7a6aacd0823b78de5fa58bc0e1581f4cd40bb8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0769230769, "max_line_length": 133, "alphanum_fraction": 0.6240409207, "include": true, "reason": "import numpy", "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620619801094, "lm_q2_score": 0.8991213765941599, "lm_q1q2_score": 0.8629425863704053}}
{"text": "# model fitting problem with logistic loss and L1 regularization.\nfrom __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cvxpy as cp\n\n# In this example, we use CVXPY to train a logistic regression classifier with ℓ1 regularization. We are given data (xi,yi), i=1,…,m. The xi∈Rn are feature vectors, while the yi∈{0,1} are associated boolean classes.\n# Our goal is to construct a linear classifier ŷ =𝟙[βTx>0], which is 1 when βTx is positive and 0 otherwise. We model the posterior probabilities of the classes given the data linearly, with\n# logPr(Y=1∣X=x)Pr(Y=0∣X=x)=βTx.\n# This implies that\n# Pr(Y=1∣X=x)=exp(βTx)1+exp(βTx),Pr(Y=0∣X=x)=11+exp(βTx).\n# We fit β by maximizing the log-likelihood of the data, plus a regularization term λ‖β‖1 with λ>0:\n# ℓ(β)=∑i=1myiβTxi−log(1+exp(βTxi))−λ‖β‖1.\n# Because ℓ is a concave function of β, this is a convex optimization problem.\n\n# Construct Z given X.\ndef pairs(Z):\n    m, n = Z.shape\n    k = n * (n + 1) // 2\n    X = np.zeros((m, k))\n    count = 0\n    for i in range(n):\n        for j in range(i, n):\n            X[:, count] = Z[:, i] * Z[:, j]\n            count += 1\n    return X\n\n\n# Generate data for logistic model fitting problem.\nnp.random.seed(1)\nn = 10\nk = n * (n + 1) // 2\nm = 200\nTEST = 100\nsigma = 1.9\nDENSITY = 1.0\ntheta_true = np.random.randn(n, 1)\n\nidxs = np.random.choice(range(n), int((1 - DENSITY) * n), replace=False)\nfor idx in idxs:\n    beta_true[idx] = 0\n\n\nZ = np.random.binomial(1, 0.5, size=(m, n))\nY = np.sign(Z.dot(theta_true) + np.random.normal(0, sigma, size=(m, 1)))\nX = pairs(Z)\nX = np.hstack([X, np.ones((m, 1))])\nZ_test = np.random.binomial(1, 0.5, size=(TEST, n))\nY_test = np.sign(Z_test.dot(theta_true) + np.random.normal(0, sigma, size=(TEST, 1)))\nX_test = pairs(Z_test)\nX_test = np.hstack([X_test, np.ones((TEST, 1))])\n\ntheta = cp.Variable((k + 1, 1))\nlambd = cp.Parameter(nonneg=True)\nloss = cp.sum(\n    cp.log_sum_exp(cp.hstack([np.zeros((m, 1)), -cp.multiply(Y, X @ theta)]), axis=1)\n)\nreg = cp.norm(theta[:k], 1)\nprob = cp.Problem(cp.Minimize(loss / m + lambd * reg))\n# Compute a trade-off curve and record train and test error.\nTRIALS = 100\ntrain_error = np.zeros(TRIALS)\ntest_error = np.zeros(TRIALS)\nlambda_vals = np.logspace(-4, 0, TRIALS)\nfor i in range(TRIALS):\n    lambd.value = lambda_vals[i]\n    prob.solve(solver=cp.SCS)\n    train_error[i] = (\n        np.sign(Z.dot(theta_true)) != np.sign(X.dot(theta.value))\n    ).sum() / m\n    test_error[i] = (\n        np.sign(Z_test.dot(theta_true)) != np.sign(X_test.dot(theta.value))\n    ).sum() / TEST\n# Plot the train and test error over the trade-off curve.\n\nplt.plot(lambda_vals, train_error, label=\"Train error\")\nplt.plot(lambda_vals, test_error, label=\"Test error\")\nplt.xscale(\"log\")\nplt.legend(loc=\"upper left\")\nplt.xlabel(r\"$\\lambda$\", fontsize=16)\nplt.show()\n\n# Below we plot |θk|, k=1,…,55, for the λ that minimized the test error. Each |θk| is placed at position (i,j) where zizj=xk. Notice that many θk are 0, as we would expect with ℓ1 regularization.\n\n# Solve model fitting problem with the lambda that minimizes test error.\nidx = np.argmin(test_error)\nlambd.value = lambda_vals[idx]\nprob.solve(solver=cp.SCS)\n\n# Plot the absolute value of the entries in theta corresponding to each feature.\nP = np.zeros((n, n))\ncount = 0\nfor i in range(n):\n    for j in range(i, n):\n        P[i, j] = np.abs(theta.value[count])\n        count += 1\nrow_labels = range(1, n + 1)\ncolumn_labels = range(1, n + 1)\n\nfig, ax = plt.subplots()\nheatmap = ax.pcolor(P, cmap=plt.cm.Blues)\n\n# put the major ticks at the middle of each cell\nax.set_xticks(np.arange(P.shape[1]) + 0.5, minor=False)\nax.set_yticks(np.arange(P.shape[0]) + 0.5, minor=False)\n\n# want a more natural, table-like display\nax.invert_yaxis()\nax.xaxis.tick_top()\n\nax.set_xticklabels(column_labels, minor=False)\nax.set_yticklabels(row_labels, minor=False)\n\nplt.xlabel(r\"$z_i$\", fontsize=16)\nax.xaxis.set_label_position(\"top\")\nplt.ylabel(r\"$z_j$\", fontsize=16)\nplt.show()\n", "meta": {"hexsha": "64229d8edb52b5a3a9a4438ce56c28700fc64a69", "size": 3996, "ext": "py", "lang": "Python", "max_stars_repo_path": "convex_methods/regularized_logistic_loss.py", "max_stars_repo_name": "wavescholar/ds_devops", "max_stars_repo_head_hexsha": "10381e34a8676463d6c561bb9f0ea62f4c7ec7e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "convex_methods/regularized_logistic_loss.py", "max_issues_repo_name": "wavescholar/ds_devops", "max_issues_repo_head_hexsha": "10381e34a8676463d6c561bb9f0ea62f4c7ec7e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "convex_methods/regularized_logistic_loss.py", "max_forks_repo_name": "wavescholar/ds_devops", "max_forks_repo_head_hexsha": "10381e34a8676463d6c561bb9f0ea62f4c7ec7e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8644067797, "max_line_length": 215, "alphanum_fraction": 0.6744244244, "include": true, "reason": "import numpy,import cvxpy", "num_tokens": 1275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620585273154, "lm_q2_score": 0.899121379297294, "lm_q1q2_score": 0.86294258586029}}
{"text": "# ==============================================================================\n# Author: Eddie Guo\n# Date: November 6, 2021\n#\n# Author's notes:\n# You may share and modify (and do whatever you want) with this code.\n# I hope this helps you with your assignments :)\n#\n# This script creates a linear regression model and plots the output.\n# ==============================================================================\n\nimport matplotlib.pyplot as plt  # for plotting\nimport numpy as np               # for arrays\nimport pandas as pd              # for data manipulation\n\n# Ordinary Least Squares (OLS): y = A + Bx\ndef Delta(x):\n\t# N \\sum x^2 - \\left( \\sum x \\right)^2\n\treturn len(x) * np.sum(x**2) - np.sum(x)**2\n\ndef A(x, y):\n\t# A = \\frac{(\\sum x^2 \\sum y - \\sum x \\sum xy)}{\\Delta}\n\treturn (np.sum(x**2)*np.sum(y)-np.sum(x)*np.sum(x*y)) / Delta(x)\n\ndef B(x, y):\n\t# B = \\frac{N \\sum xy - \\sum x \\sum y}{\\Delta}\n\treturn (len(x)*np.sum(x*y)-np.sum(x)*np.sum(y)) / Delta(x)\n\n\n# Step 1. Read in the data.\ndf = pd.read_csv('cheese_and_deaths.csv')\nprint(df.head())\n\n# Step 2. Visualize the data and verify a linear relationship.\nplt.scatter(df['year'], df['deaths'])\nplt.show()\n\n# Step 3. Create the OLS model.\nintercept = A(df['year'], df['deaths'])\nslope = B(df['year'], df['deaths'])\n# I love Python f-strings\n# https://www.geeksforgeeks.org/formatted-string-literals-f-strings-python/\nprint(f'The slope is {slope} and the intercept is {intercept}.')\n\n# Step 4. Re-visualize with your model.\nx = np.linspace(2000, 2010, 10)  # 10 equally spaced points btw 2000 and 2010\ny = slope*x + intercept\nplt.scatter(df['year'], df['deaths'], color='black')\nplt.plot(x, y, color='black')\nplt.xlabel('Year')\nplt.ylabel('Bedide tanglies (deaths)')\n# Uncomment the line below to save the figure.\n# plt.savefig('my_figs_name.png', dpi=250)\nplt.show()\n\n\n# Fun aside ====================================================================\n# Question: What is the correlation between per capita cheese consumption and\n# number of people who die by becoming tangled in their bedsheets?\n\n# Answer: Let's visualize it!\nintercept_cheese = A(df['year'], df['cheese_consumption'])\nslope_cheese = B(df['year'], df['cheese_consumption'])\ny1 = slope_cheese*x + intercept_cheese\n\nfig, ax1 = plt.subplots()\nax2 = ax1.twinx()\nax1.plot(x, y, color='red')\nax2.plot(x, y1, color='black')\n\nax1.scatter(df['year'], df['deaths'], color='red')\nax2.scatter(df['year'], df['cheese_consumption'], color='black')\n\nax1.set_xlabel('Year')\nax1.set_ylabel('Besheet tanglies (deaths)', color='red')\nax2.set_ylabel('Cheese consumed (lbs)')\nplt.tight_layout()\nplt.show()\n\n# Answer 2: r = 0.9471 (or 94.71%)\n# Correlation != causation (or does it... haha)\n", "meta": {"hexsha": "6e287bcfd8ed88b5a78ebc4d13f099da691c892e", "size": 2703, "ext": "py", "lang": "Python", "max_stars_repo_path": "linreg_ex/linreg.py", "max_stars_repo_name": "engphysca/python-for-sci-computing", "max_stars_repo_head_hexsha": "c8462984e54754d73cfea97f378deb4776904f50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linreg_ex/linreg.py", "max_issues_repo_name": "engphysca/python-for-sci-computing", "max_issues_repo_head_hexsha": "c8462984e54754d73cfea97f378deb4776904f50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linreg_ex/linreg.py", "max_forks_repo_name": "engphysca/python-for-sci-computing", "max_forks_repo_head_hexsha": "c8462984e54754d73cfea97f378deb4776904f50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-06T16:40:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T16:40:42.000Z", "avg_line_length": 32.9634146341, "max_line_length": 80, "alphanum_fraction": 0.6174620792, "include": true, "reason": "import numpy", "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.9086179006446221, "lm_q1q2_score": 0.8628865843271792}}
{"text": "\nimport numpy as np\n\n\n\ndef diff_of_means(data_1, data_2):\n    \"\"\"Difference in means of two arrays.\"\"\"\n\n    # The difference of means of data_1, data_2: diff\n    diff = np.mean(data_1) - np.mean(data_2)\n\n    return diff    \n\n\ndef _permutation_sample(data):\n    \n    \n    permuted_data = np.random.permutation(data)\n    \n \n    return permuted_data\n\n\ndef permutation_over_two_series(data1, data2):\n    \"\"\"Generate a permutation sample from two data sets.\"\"\"\n\n    # Concatenate the data sets: data\n    data = np.concatenate((data1, data2))\n\n    # Permute the concatenated array: permuted_data\n    permuted_data = _permutation_sample(data)\n\n    # Split the permuted array into two: perm_sample_1, perm_sample_2\n    perm_sample_1 = permuted_data[:len(data1)]\n    perm_sample_2 = permuted_data[len(data1):]\n\n    return perm_sample_1, perm_sample_2\n\n\ndef draw_perm_reps(data_1, data_2, func, size=1):\n    \"\"\"Generate multiple permutation replicates.\"\"\"\n\n    # Initialize array of replicates: perm_replicates\n    perm_replicates = np.empty(size)\n\n    for i in range(size):\n        # Generate permutation sample\n        perm_sample_1, perm_sample_2 = permutation_over_two_series(data_1, data_2)\n\n        # Compute the test statistic\n        perm_replicates[i] = func(perm_sample_1, perm_sample_2)\n\n    return perm_replicates\n    \n\n\ndef eval_permutation_p_value(samples_A, samples_B, reducer=diff_of_means, size=10000, condition='gt'):\n\n\n    # Compute difference of mean impact force from experiment: empirical_diff_means\n    empirical_diff_means = reducer(samples_A, samples_B)\n\n    # Draw 10,000 permutation replicates: perm_replicates\n    perm_replicates = draw_perm_reps(samples_A, samples_B,\n                                     reducer, size=size)\n\n    # Compute p-value:\n        # the p_value is the sum of all positive cases divided by the \n        #number of samples\n        # the positive cases are those whose perm_replicate value is equal \n        #or higher (more extreme) than the observed value.\n    \n    \n    if condition.lower() == 'gt':\n    \n        p_value = np.mean(perm_replicates >= empirical_diff_means)\n        \n    elif condition.lower() == 'lt':\n        p_value = np.mean(perm_replicates <= empirical_diff_means)\n        \n    else:\n        mask1 = perm_replicates <= empirical_diff_means\n        \n        mask2 = perm_replicates >= empirical_diff_means\n    \n        Conditional = perm_replicates[mask1 | mask2]\n        p_value = np.sum(Conditional)/len(perm_replicates)\n\n    \n    return {'p_value':p_value, \n            'perm_replicates':perm_replicates,\n            'empirical_diff_means':empirical_diff_means}\n\n    \nif '__main__' == __name__:\n    \"\"\"\n    Description:\n    \n        Assuming that we wish to evaluate the probability that two \n        populations have same statistics (i.e.: mean).\n        \n        A possible solution for this hypothesis test is the t-statistics. \n        \n        Another solution is the permutation replicate technique using a \n        mean difference as a reducer function.\n    \n    \n    Case example:\n        samples_A: samples from population A (i.e.: petal length without treatment)\n        samples_B: samples from population B (i.e.: petal length with treatment)\n        \n        \n        Reducer: diff_of_means. It evaluates the difference between \n        Population Means\n    \n    \n        H0: Population means are the same\n        Ha: Population means are not equal\n    \n    Result: \n        p_value (reprents the probability of retrieving a value more extreme\n                 than the observed, assuming that hypothesis null is True.\n        \n        When we assume alpha == 0.05, if p_value < alpha, we reject H0,\n        and accept the alternative (Ha).\n        \n        \n    \"\"\"\n    \n    \n    print('''Case example:\n        samples_A: samples from population A (i.e.: petal length without treatment)\n        samples_B: samples from population B (i.e.: petal length with treatment) \n        \n        '''\n        )\n    \n    samples_A = np.random.normal(4, 5, size=500)\n    \n    samples_B = np.random.normal(3.7, 7.5, size=500)\n\n    # Compute difference of mean impact force from experiment: empirical_diff_means\n    empirical_diff_means = diff_of_means(samples_A, samples_B)\n\n    # Draw 10,000 permutation replicates: perm_replicates\n    perm_replicates = draw_perm_reps(samples_A, samples_B,\n                                     diff_of_means, size=10000)\n\n    # Compute p-value: p\n    p_value = np.mean(perm_replicates >= empirical_diff_means)\n\n    print(perm_replicates)\n    # Print the result\n    print('p-value =', p_value)\n    \n    \n    \n    \nif '__main__' == __name__:\n    # Case 2 (Bernoulli situation)\n    \n    \"\"\"\n    Description:\n    \n        Assume that a given population A (democrats - dems) have a \n        certain tendency towards voting in favor (boolean False X True) \n        for a given Legislation, and population B (republicans - reps) \n        have a second tendency.\n\n\n        We wish to evaluate the probability that the populations have equal \n        tendency in the voting.\n        \n        \n    Conditions:\n    \n        Since it is a Bernoulli situation, the differences in population \n        does no longer apply for this test.\n        \n        It is necessary to evaluate the respective frequencies of voting \n        per group:\n    \n        \n        \n        \n    \"\"\"\n    print('''\n          \\n\\n \n          \n          ---------------------------------------------------\n          \n          Description:\n    \n        Assume that a given population A (democrats - dems) have a \n        certain tendency towards voting in favor (boolean False X True) \n        for a given Legislation, and population B (republicans - reps) \n        have a second tendency.\n\n\n        We wish to evaluate the probability that the populations \n        have equal tendency in the voting.\n        \n        \n        \\n\\n\n        \n        ------------------------------------ \\n'''\n        )\n        \n    # Construct arrays of data: dems, reps\n    dems = np.array([True] * 153 + [False] * 91)\n    reps = np.array([True] * 136 + [False] * 35)\n    \n    \n    \n    def frac_yea_dems(group_A, group_B=None):\n        \"\"\"Compute fraction of group_A.\"\"\"\n        frac = group_A[group_A==True].size / (group_A.size)\n        return frac\n\n    # Acquire permutation samples: perm_replicates\n    perm_replicates = draw_perm_reps(dems, reps, frac_yea_dems, 10000)\n    real_fraction = frac_yea_dems(dems)\n    # Compute and print p-value: p\n    p = np.sum(perm_replicates <= real_fraction) / len(perm_replicates)\n    print('p-value =', p)\n\nif '__main__' == __name__:\n    \"\"\"\n    Description:\n    \n        population A: each sample from population A represents the \n        amount of time (in accumulated months) that a given event reoccurs.\n        \n        After a given treatment, which could have changed the rates \n        in the events of population A, a second sample set (Population B)\n        was evaluated.\n        \n        \n    Question:\n        Is there a significant statistical change prior and after the \n        treatment?\n        \n        In another words: what is the probability that the treatment \n        causes a negative change in the event occurence given that the null hypothesis is true \n\n    \n    \n    \n    Condition: \n        since the treatment changed the rates in the events in a negative \n        way (i.e., longer average time between event occurrence), we are interested in the \"<=\" condition for p-value test statistics\n        \n        \n    \n    Hypothesis:\n        H0: treatment does not change the rates in the events occurence. \n        In another words, rates of Population A are equal to Population B:\n        Ha: the treatment does change the rates\n    \"\"\"\n    \n    \n    print('''\n          \\n\\n \n          \n          Description:\n    \n        population A: each sample from population A represents the \n        amount of time (in accumulated months) that a given event reoccurs.\n        \n        After a given treatment, which could have changed the rates in \n        the events of population A, a second sample set (Population B) \n        was evaluated.\n        \n        \n    Question:\n        Is there a significant statistical change prior and after the treatment?\n        \n        In another words: what is the probability that the treatment \n        causes a negative change in the event occurence given that \n        the null hypothesis is true \n\n    \n    \n        \\n\\n\n        \n        ------------------------------------ \\n'''\n        )\n    \n    \n    \n    eval_permutation_p_value(samples_A, samples_B, reducer=diff_of_means, size=10000, condition='gt')\n    \n    \n    \nif '__main__' == __name__:\n    \"\"\"\n    Correlation test statistics\n    \n    \n    Description:\n    \n        In this example, the statistical confidence (p-value) of the \n        correlation coefficient is evaluated.\n        \n        \n    The condition evaluated is:\n        what is the probability of getting a correlation \n        coefficient equal or higher than the observed? \n    \n    \"\"\"\n    \n    def pearson_r (x,y):\n        \n        return np.corrcoef(x,y)[0][1]\n    \n    Result = eval_permutation_p_value(samples_A, samples_B, reducer=pearson_r, size=10000, condition='gt')\n    \n    print('p_value =', Result['p_value'])", "meta": {"hexsha": "abcceae5563c48d7094a2789b9cc163528dbc465", "size": 9302, "ext": "py", "lang": "Python", "max_stars_repo_path": "boostrap_statistical_analyses/one_sample/submodules/permutation.py", "max_stars_repo_name": "PhilipeRLeal/bootstrap_analyses", "max_stars_repo_head_hexsha": "377103706aa56b2ab6f16123d703550abc6ce18c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boostrap_statistical_analyses/one_sample/submodules/permutation.py", "max_issues_repo_name": "PhilipeRLeal/bootstrap_analyses", "max_issues_repo_head_hexsha": "377103706aa56b2ab6f16123d703550abc6ce18c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boostrap_statistical_analyses/one_sample/submodules/permutation.py", "max_forks_repo_name": "PhilipeRLeal/bootstrap_analyses", "max_forks_repo_head_hexsha": "377103706aa56b2ab6f16123d703550abc6ce18c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.251572327, "max_line_length": 133, "alphanum_fraction": 0.6186841539, "include": true, "reason": "import numpy", "num_tokens": 2043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514736, "lm_q2_score": 0.9086178938396674, "lm_q1q2_score": 0.8628865830419372}}
{"text": "import numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\nimport math\n\ndef predict_using_sklean():\n    df = pd.read_csv(\"exe_gradent_decent.csv\")\n    r = LinearRegression()\n    r.fit(df[['math']],df.cs)\n    return r.coef_, r.intercept_\n\ndef gradient_descent(x,y):\n    m_curr = 0\n    b_curr = 0\n    iterations = 1000000\n    n = len(x)\n    learning_rate = 0.0002\n\n    cost_previous = 0\n\n    for i in range(iterations):\n        y_predicted = m_curr * x + b_curr\n        cost = (1/n)*sum([value**2 for value in (y-y_predicted)])\n        md = -(2/n)*sum(x*(y-y_predicted))\n        bd = -(2/n)*sum(y-y_predicted)\n        m_curr = m_curr - learning_rate * md\n        b_curr = b_curr - learning_rate * bd\n        if math.isclose(cost, cost_previous, rel_tol=1e-20):\n            break\n        cost_previous = cost\n        print (\"m {}, b {}, cost {}, iteration {}\".format(m_curr,b_curr,cost, i))\n\n    return m_curr, b_curr\n\nif __name__ == \"__main__\":\n    df = pd.read_csv(\"exe_gradent_decent.csv\")\n    x = np.array(df.math)\n    y = np.array(df.cs)\n\n    m, b = gradient_descent(x,y)\n    print(\"Using gradient descent function: Coef {} Intercept {}\".format(m, b))\n\n    m_sklearn, b_sklearn = predict_using_sklean()\n    print(\"Using sklearn: Coef {} Intercept {}\".format(m_sklearn,b_sklearn))", "meta": {"hexsha": "4602da0fc40f51ca18b66b9070cc54e0ba2d43bd", "size": 1311, "ext": "py", "lang": "Python", "max_stars_repo_path": "ML_and_DL/exc_gradeint_decent.py", "max_stars_repo_name": "AshfakYeafi/AI_practice_code", "max_stars_repo_head_hexsha": "3d8a0b9382f5903e840ce59218ebb95ca962ab01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ML_and_DL/exc_gradeint_decent.py", "max_issues_repo_name": "AshfakYeafi/AI_practice_code", "max_issues_repo_head_hexsha": "3d8a0b9382f5903e840ce59218ebb95ca962ab01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ML_and_DL/exc_gradeint_decent.py", "max_forks_repo_name": "AshfakYeafi/AI_practice_code", "max_forks_repo_head_hexsha": "3d8a0b9382f5903e840ce59218ebb95ca962ab01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7954545455, "max_line_length": 81, "alphanum_fraction": 0.6308161709, "include": true, "reason": "import numpy", "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321450147636, "lm_q2_score": 0.8947894668039496, "lm_q1q2_score": 0.8628646762052147}}
{"text": "import numpy as np\n\n\ndef rotation_x(phi: float) -> np.ndarray:\n    \"\"\"\n    Return the Rotation matrix around the X-axis for phi radians.\n    \"\"\"\n    R_rot = np.array([[1, 0, 0],\n                      [0, np.cos(phi), -np.sin(phi)],\n                      [0, np.sin(phi), np.cos(phi)]])\n    return R_rot\n\n\ndef rotation_y(theta: float) -> np.ndarray:\n    \"\"\"\n    Return the Rotation matrix around the Y-axis for theta radians.\n    \"\"\"\n    R_rot = np.array([[np.cos(theta), 0, -np.sin(theta)],\n                      [0, 1, 0],\n                      [np.sin(theta), 0, np.cos(theta)]])\n    return R_rot\n\n\ndef rotation_z(psi: float) -> np.ndarray:\n    \"\"\"\n    Return the Rotation matrix around the Z-axis for psi radians.\n    \"\"\"\n    R_rot = np.array([[np.cos(psi), -np.sin(psi), 0],\n                      [np.sin(psi), np.cos(psi), 0],\n                      [0, 0, 1]])\n    return R_rot\n\n\ndef euler_rotation(roll: float, pitch: float, yaw: float, is_radians: bool = False) -> np.ndarray:\n    \"\"\"\n    Returns the Euler rotation matrix for 3 rotation angles around X-Y-Z\n    \"\"\"\n    # Convert to Radians:\n    if not is_radians:\n        roll, pitch, yaw = np.deg2rad(roll), np.deg2rad(pitch), np.deg2rad(yaw)\n\n    R = rotation_z(yaw) @ rotation_y(pitch) @ rotation_x(roll)\n    return R\n", "meta": {"hexsha": "6a96266b97f6526fbbe1c4c38b75ef17446348fa", "size": 1279, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/scene/rotation.py", "max_stars_repo_name": "Speterius/ray_tracing", "max_stars_repo_head_hexsha": "28fe3bd20ba312266e7802d456ab267135ffa28f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-08-12T08:54:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T21:07:00.000Z", "max_issues_repo_path": "src/scene/rotation.py", "max_issues_repo_name": "Speterius/ray_tracing", "max_issues_repo_head_hexsha": "28fe3bd20ba312266e7802d456ab267135ffa28f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-08-08T14:50:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-21T08:32:19.000Z", "max_forks_repo_path": "src/scene/rotation.py", "max_forks_repo_name": "Speterius/ray_tracing", "max_forks_repo_head_hexsha": "28fe3bd20ba312266e7802d456ab267135ffa28f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0681818182, "max_line_length": 98, "alphanum_fraction": 0.5527756059, "include": true, "reason": "import numpy", "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9833429580381724, "lm_q2_score": 0.8774767826757123, "lm_q1q2_score": 0.8628606150861534}}
{"text": "\"\"\"\nThis file is some side functions that allows for the conversion of cordinate\nsystems.\n\"\"\"\n\nimport numpy as np\n\n########################################################################\n##########                From Cartesian to ***               ##########\n########################################################################\n\n\ndef cartesian_to_polar_2d(x, y):\n    \"\"\"Convert cartesian points to polar points.\n\n    Convert cartesian coordinate points in 2D to polar coordinate points in 2D.\n    This function uses the notation convention of ISO 80000-2:2009 and its \n    related successors.\n\n    Parameters\n    ----------\n    x : array_like\n        The x values of the points to be transformed.\n    y : array_like\n        The y values of the points to be transformed.\n\n    Returns\n    -------\n    rho : array_like\n        The rho (radial) values of the points after transformation.\n    phi : array_like\n        The phi (angular) values of the points after transformation.    \n    \"\"\"\n\n    # Basic validation\n    x = np.array(x, dtype=float)\n    y = np.array(y, dtype=float)\n\n    # Convert to polar coordinates.\n    rho = np.hypot(x, y)\n    phi = np.arctan2(y, x)\n\n    return rho, phi\n\n\ndef cartesian_to_cylindrical_3d(x, y, z):\n    \"\"\"Convert cartesian points to cylindrical points.\n\n    Convert cartesian coordinate points in 3D to cylindrical coordinate points \n    in 3D. This function uses the notation convention of ISO 80000-2:2009 and \n    its related successors.\n\n    Parameters\n    ----------\n    x : array_like\n        The x values of the points to be transformed.\n    y : array_like\n        The y values of the points to be transformed.\n    z : array_like\n        The z values of the points to be transformed.\n\n    Returns\n    -------\n    rho : array_like\n        The rho (radial) values of the points after transformation.\n    phi : array_like\n        The phi (angular) values of the points after transformation.    \n    z : array_like\n        The z (height) values of the points after transformation.\n    \"\"\"\n\n    # Basic validation.\n    x = np.array(x, dtype=float)\n    y = np.array(y, dtype=float)\n    z = np.array(z, dtype=float)\n\n    # Convert to cylindrical coordinates.\n    rho = np.hypot(x, y)\n    phi = np.arctan2(y, z)\n    z = z\n\n    return rho, phi, z\n\n\ndef cartesian_to_spherical_3d(x, y, z):\n    \"\"\"Convert cartesian points to cylindrical points.\n\n    Convert cartesian coordinate points in 3D to cylindrical coordinate points \n    in 3D. This function uses the notation convention of ISO 80000-2:2009 and \n    its related successors.\n\n    Parameters\n    ----------\n    x : array_like\n        The x values of the points to be transformed.\n    y : array_like\n        The y values of the points to be transformed.\n    z : array_like\n        The z values of the points to be transformed.\n\n    Returns\n    -------\n    r : array_like\n        The rho (radial) values of the points after transformation.\n    theta : array_like\n        The theta (azimuthal angle) values of the points after the \n        transformation.    \n    phi : array_like\n        The phi (polar angle) values of the points after the transformation.\n    \"\"\"\n\n    # Basic validation.\n    x = np.array(x, dtype=float)\n    y = np.array(y, dtype=float)\n    z = np.array(z, dtype=float)\n\n    # Convert to spherical coordinates.\n    r = np.sqrt(x**2 + y**2 + z**2)\n    theta = np.arccos(z/r)\n    phi = np.arctan2(y, x)\n\n    return r, theta, phi\n\n\n########################################################################\n##########                  From Polar to ***                 ##########\n########################################################################\n\ndef polar_to_cartesian_2d(rho, phi):\n    \"\"\"Convert polar points to cartesian points.\n\n    Convert polar coordinate points in 2D to cartesian coordinate points in 2D.\n    This function uses the notation convention of ISO 80000-2:2009 and its \n    related successors.\n\n    Parameters\n    ----------\n    rho : array_like\n        The rho values of the points to be transformed.\n    phi : array_like\n        The phi values of the points to be transformed.\n\n    Returns\n    -------\n    x : array_like\n        The x values of the points after transformation.\n    y : array_like\n        The y values of the points after transformation.\n    \"\"\"\n\n    # Basic type checking\n    rho = np.array(rho, dtype=float)\n    phi = np.array(phi, dtype=float)\n\n    # Convert\n    x = rho * np.cos(phi)\n    y = rho * np.sin(phi)\n\n    return x, y\n\n\n########################################################################\n##########               From Cylindrical to ***              ##########\n########################################################################\n\ndef cylindrical_to_cartesian_3d(rho, phi, z):\n    \"\"\"Convert cylindrical points to cartesian points.\n\n    Convert cylindrical coordinate points in 3D to cartesian coordinate points \n    in 3D. This function uses the notation convention of ISO 80000-2:2009 and  \n    its related successors.\n\n    Parameters\n    ----------\n    rho : array_like\n        The rho values of the points to be transformed.\n    phi : array_like\n        The phi values of the points to be transformed.\n    z : array_like\n        The z values of the points to be transformed.\n\n    Returns\n    -------\n    x : array_like\n        The x values of the points after transformation.\n    y : array_like\n        The y values of the points after transformation.\n    z : array_like\n        The z values of the points after transformation.\n    \"\"\"\n\n    # Basic type checking\n    rho = np.array(rho, dtype=float)\n    phi = np.array(phi, dtype=float)\n    z = np.array(z, dtype=float)\n\n    # Convert\n    x = rho * np.cos(phi)\n    y = rho * np.sin(phi)\n    z = z\n\n    return x, y, z\n\n\ndef cylindrical_to_spherical_3d(rho, phi, z):\n    \"\"\"Convert cylindrical points to spherical points.\n\n    Convert cylindrical coordinate points in 3D to spherical coordinate points \n    in 3D. This function uses the notation convention of ISO 80000-2:2009 and  \n    its related successors.\n\n    Parameters\n    ----------\n    rho : array_like\n        The rho values of the points to be transformed.\n    phi : array_like\n        The phi values of the points to be transformed.\n    z : array_like\n        The z values of the points to be transformed.\n\n    Returns\n    -------\n    r : array_like\n        The rho (radial) values of the points after transformation.\n    theta : array_like\n        The theta (azimuthal angle) values of the points after the \n        transformation.    \n    phi : array_like\n        The phi (polar angle) values of the points after the transformation.\n    \"\"\"\n\n    # Basic type checking\n    rho = np.array(rho, dtype=float)\n    phi = np.array(phi, dtype=float)\n    z = np.array(z, dtype=float)\n\n    # Convert\n    r = np.hypot(rho, z)\n    theta = np.arccos(z/r)\n    phi = phi\n\n    return r, theta, phi\n\n\n########################################################################\n##########                From Spherical to ***               ##########\n########################################################################\n\ndef spherical_to_cartesian_3d(r, theta, phi):\n    \"\"\"Convert spherical points to cartesian points.\n\n    Convert spherical coordinate points in 3D to cartesian coordinate points \n    in 3D. This function uses the notation convention of ISO 80000-2:2009 and  \n    its related successors.\n\n    Parameters\n    ----------\n    r : array_like\n        The r values of the points to be transformed.\n    theta : array_like\n        The theta values of the points to be transformed.\n    phi : array_like\n        The phi values of the points to be transformed.\n\n    Returns\n    -------\n    x : array_like\n        The x values of the points after transformation.\n    y : array_like\n        The y values of the points after transformation.\n    z : array_like\n        The z values of the points after transformation.\n    \"\"\"\n\n    # Basic type checking\n    r = np.array(r, dtype=float)\n    theta = np.array(theta, dtype=float)\n    phi = np.array(phi, dtype=float)\n\n    # Convert\n    x = r * np.sin(theta) * np.cos(phi)\n    y = r * np.sin(theta) * np.sin(phi)\n    z = r * np.cos(theta)\n\n    return x, y, z\n\n\ndef spherical_to_cylindrical_3d(r, theta, phi):\n    \"\"\"Convert cylindrical points to cartesian points.\n\n    Convert cylindrical coordinate points in 3D to cartesian coordinate points \n    in 3D. This function uses the notation convention of ISO 80000-2:2009 and  \n    its related successors.\n\n    Parameters\n    ----------\n    r : array_like\n        The r values of the points to be transformed.\n    theta : array_like\n        The theta values of the points to be transformed.\n    phi : array_like\n        The phi values of the points to be transformed.\n\n    Returns\n    -------\n    rho : array_like\n        The rho values of the points after transformation.\n    phi : array_like\n        The phi (angular) values of the points after transformation.\n    z : array_like\n        The z values of the points after transformation.\n    \"\"\"\n\n    # Basic type checking\n    r = np.array(r, dtype=float)\n    theta = np.array(theta, dtype=float)\n    phi = np.array(phi, dtype=float)\n\n    # Convert\n    rho = r * np.sin(theta)\n    phi = phi\n    z = r * np.cos(theta)\n\n    return rho, phi, z\n", "meta": {"hexsha": "0534d302d69878763ec67d0060378a061ab2871a", "size": 9260, "ext": "py", "lang": "Python", "max_stars_repo_path": "Codebase/Active_Codebase/Backend/coordinate_system_transformation.py", "max_stars_repo_name": "psmd-iberutaru/Akamai_Internship", "max_stars_repo_head_hexsha": "ed02cecbb8ac3f93e26595befacd2ca997a7a747", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Codebase/Active_Codebase/Backend/coordinate_system_transformation.py", "max_issues_repo_name": "psmd-iberutaru/Akamai_Internship", "max_issues_repo_head_hexsha": "ed02cecbb8ac3f93e26595befacd2ca997a7a747", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-08-09T08:53:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-11T14:25:38.000Z", "max_forks_repo_path": "Codebase/Active_Codebase/Backend/coordinate_system_transformation.py", "max_forks_repo_name": "psmd-iberutaru/Akamai_Internship", "max_forks_repo_head_hexsha": "ed02cecbb8ac3f93e26595befacd2ca997a7a747", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4923076923, "max_line_length": 79, "alphanum_fraction": 0.5876889849, "include": true, "reason": "import numpy", "num_tokens": 2081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899575269305, "lm_q2_score": 0.8933094060543488, "lm_q1q2_score": 0.8628471758919707}}
{"text": "# Import required libraries:\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\nfrom sklearn.metrics import r2_score\n\n# Generating dataset:\n# Y = A*sin(B(X + C)) + D\n# A = Amplitude\n# Period = 2*pi/B\n# Period = Length of One Cycle\n# C = Phase Shift (In Radian)\n# D = Vertical Shift\n\nX = np.linspace(0,1,100)             #(Start,End,Points)\n\n# Here…\n# A = 1\n# B= 2*pi\n# B = 2*pi/Period\n# Period = 1\n# C = 0\n# D = 0\n\nY = 1*np.sin(2*np.pi*X)\n\n\n# Adding some Noise :\nNoise = 0.4*np.random.normal(size=100)\nY_data = Y + Noise\nplt.scatter(X,Y_data,c=\"r\")\n\n# Calculate the value:\ndef calc_sine(x,a,b,c,d):\n  return a * np.sin(b* ( x + np.radians(c))) + d\n  \n# Finding optimal parameters :\npopt,pcov = curve_fit(calc_sine,X,Y_data)\n\n# Plot the main data :\nplt.scatter(X,Y_data)# Plot the best fit curve :\nplt.plot(X,calc_sine(X,*popt),c=\"r\")\nplt.show()\n\n# Check the accuracy :\nAccuracy =r2_score(Y_data,calc_sine(X,*popt))\nprint (Accuracy)\n\n# Function to calculate the value :\ndef calc_line(X,m,b):\n  return b + X*m\n  \n# It returns optimized parametes for our function :\n# popt stores optimal parameters\n# pcov stores the covarience between each parameters.\npopt,pcov = curve_fit(calc_line,X,Y_data)\n\n# Plot the main data :\nplt.scatter(X,Y_data)\n\n# Plot the best fit line :\nplt.plot(X,calc_line(X,*popt),c=\"r\")\nplt.show()\n\n# Check the accuracy of model :\nAccuracy =r2_score(Y_data,calc_line(X,*popt))\nprint (\"Accuracy of Linear Model : \",Accuracy)\n", "meta": {"hexsha": "4e5024b9948ef1bc2cd84e2bb7356e87d766745f", "size": 1477, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine_learning_algorithms_for_beginners/sinusoidal_regression.py", "max_stars_repo_name": "fimoziq/tutorials", "max_stars_repo_head_hexsha": "f47f1b59bf3c9e9f79d530c6fc8ca36c0d9ea93b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 670, "max_stars_repo_stars_event_min_datetime": "2020-07-23T11:33:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:38:11.000Z", "max_issues_repo_path": "machine_learning_algorithms_for_beginners/sinusoidal_regression.py", "max_issues_repo_name": "terragord7/tutorials", "max_issues_repo_head_hexsha": "a5c3f1fed6c5c4d23f59a41c024f7499055c8d81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-01-03T16:36:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T06:05:43.000Z", "max_forks_repo_path": "machine_learning_algorithms_for_beginners/sinusoidal_regression.py", "max_forks_repo_name": "terragord7/tutorials", "max_forks_repo_head_hexsha": "a5c3f1fed6c5c4d23f59a41c024f7499055c8d81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 281, "max_forks_repo_forks_event_min_datetime": "2020-07-23T06:37:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:33:48.000Z", "avg_line_length": 21.7205882353, "max_line_length": 56, "alphanum_fraction": 0.6844955992, "include": true, "reason": "import numpy,from scipy", "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244553, "lm_q2_score": 0.8933094074745443, "lm_q1q2_score": 0.862847174633075}}
{"text": "# Plot ridge regression applied to  1d polynomial problem\n# Based on https://github.com/probml/pmtk3/blob/master/demos/polyfitRidgeLasso.m\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pyprobml_utils import save_fig\n\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import Ridge\nfrom sklearn.preprocessing import MinMaxScaler \nfrom sklearn.metrics import mean_squared_error as mse\n\ndef make_1dregression_data(n=21):\n    np.random.seed(0)\n    xtrain = np.linspace(0.0, 20, n)\n    xtest = np.arange(0.0, 20, 0.1)\n    sigma2 = 4\n    w = np.array([-1.5, 1/9.])\n    fun = lambda x: w[0]*x + w[1]*np.square(x)\n    ytrain = fun(xtrain) + np.random.normal(0, 1, xtrain.shape) * \\\n        np.sqrt(sigma2)\n    ytest= fun(xtest) + np.random.normal(0, 1, xtest.shape) * \\\n        np.sqrt(sigma2)\n    return xtrain, ytrain, xtest, ytest\n\nxtrain, ytrain, xtest, ytest = make_1dregression_data(n=21)\n\n#Rescaling data\nscaler = MinMaxScaler(feature_range=(-1, 1))\nXtrain = scaler.fit_transform(xtrain.reshape(-1, 1))\nXtest = scaler.transform(xtest.reshape(-1, 1))\n\ndeg = 14\nalphas = np.logspace(-10, 1.3, 10)\nnalphas = len(alphas)\nmse_train = np.empty(nalphas)\nmse_test = np.empty(nalphas)\nytest_pred_stored = dict()\nfor i, alpha in enumerate(alphas):\n    model = Ridge(alpha=alpha, fit_intercept=False)\n    poly_features = PolynomialFeatures(degree=deg, include_bias=False)\n    Xtrain_poly = poly_features.fit_transform(Xtrain)\n    model.fit(Xtrain_poly, ytrain)\n    ytrain_pred = model.predict(Xtrain_poly)\n    Xtest_poly = poly_features.transform(Xtest)\n    ytest_pred = model.predict(Xtest_poly)\n    mse_train[i] = mse(ytrain_pred, ytrain) \n    mse_test[i] = mse(ytest_pred, ytest)\n    ytest_pred_stored[alpha] = ytest_pred\n    \n# Plot MSE vs degree\nfig, ax = plt.subplots()\nmask = [True]*nalphas\nax.plot(alphas[mask], mse_test[mask], color = 'r', marker = 'x',label='test')\nax.plot(alphas[mask], mse_train[mask], color='b', marker = 's', label='train')\nax.set_xscale('log')\nax.legend(loc='upper right', shadow=True)\nplt.xlabel('L2 regularizer')\nplt.ylabel('mse')\nsave_fig('polyfitVsRidge.pdf')\nplt.show()\n\n# Plot fitted functions\nchosen_alphas = alphas[[0,5,8]]\nfor i, alpha in enumerate(chosen_alphas):\n    fig, ax = plt.subplots()\n    ax.scatter(xtrain, ytrain)\n    ax.plot(xtest, ytest_pred_stored[alpha])\n    plt.title('L2 regularizer {:0.5f}'.format(alpha))\n    save_fig('polyfitRidge{}.pdf'.format(i))\n    plt.show()", "meta": {"hexsha": "e2c726a2ae43469fff12d2b1fcdc9c0b19fc3eae", "size": 2452, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/linreg_poly_ridge.py", "max_stars_repo_name": "always-newbie161/pyprobml", "max_stars_repo_head_hexsha": "eb70c84f9618d68235ef9ba7da147c009b2e4a80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-26T04:36:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T04:36:24.000Z", "max_issues_repo_path": "scripts/linreg_poly_ridge.py", "max_issues_repo_name": "always-newbie161/pyprobml", "max_issues_repo_head_hexsha": "eb70c84f9618d68235ef9ba7da147c009b2e4a80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-03-31T20:18:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:52:47.000Z", "max_forks_repo_path": "scripts/linreg_poly_ridge.py", "max_forks_repo_name": "always-newbie161/pyprobml", "max_forks_repo_head_hexsha": "eb70c84f9618d68235ef9ba7da147c009b2e4a80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-21T01:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T01:18:07.000Z", "avg_line_length": 34.0555555556, "max_line_length": 80, "alphanum_fraction": 0.7124796085, "include": true, "reason": "import numpy", "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244553, "lm_q2_score": 0.8933094067644466, "lm_q1q2_score": 0.8628471739471919}}
{"text": "from scipy import stats\nimport numpy as np\n\n############################\n# CALCULATING CORRELATIONS #\n############################\n\narray_1 = np.array([1,2,3,4,5,6])  # Create a numpy array from a list\narray_2 = array_1  # Create another array with the same values\n\nprint(stats.pearsonr(array_1, array_2))  # Calculate the correlation which will be 1 since the values are the same \n\n#######################\n# NORMAL DISTRIBUTION #\n#######################\nx = stats.norm.rvs(loc=0, scale=10, size=10)  # Generate 10 values randomly sampled from a normal distribution with mean 0 and standard deviation of 10\n\nprint(x)\n\n################################\n# PROBABILITY DENSITY FUNCTION #\n################################\np1 = stats.norm.pdf(x=-100, loc=0, scale=10)  # Get probability of sampling a value of -100\np2 = stats.norm.pdf(x=0, loc=0, scale=10)     # Get probability of sampling a value of 0\n\nprint(p1)\nprint(p2)\n\n####################################\n# CUMULATIVE DISTRIBUTION FUNCTION #\n####################################\np1 = stats.norm.cdf(x=0, loc=0, scale=10)  # Get probability of sampling a value less than or equal to 0\n\nprint(p1)\n\n######################################\n# CALCULATING DESCRIPTIVE STATISTICS #\n######################################\nprint(stats.describe(stats.norm.rvs(loc=0, scale=1, size=500)))  # Calculate descriptive statistics for 500 data points sampled from normal distribution with mean 0 and standard deviation of 1\n", "meta": {"hexsha": "f594e48a4780469ce9c3653912d489a7c0714b11", "size": 1458, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python Basics/scipy_basics.py", "max_stars_repo_name": "python-sonchau/python-visualization", "max_stars_repo_head_hexsha": "eb139aaabbff858663a96f8e19e30f1418e4330c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python Basics/scipy_basics.py", "max_issues_repo_name": "python-sonchau/python-visualization", "max_issues_repo_head_hexsha": "eb139aaabbff858663a96f8e19e30f1418e4330c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python Basics/scipy_basics.py", "max_forks_repo_name": "python-sonchau/python-visualization", "max_forks_repo_head_hexsha": "eb139aaabbff858663a96f8e19e30f1418e4330c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.45, "max_line_length": 192, "alphanum_fraction": 0.5809327846, "include": true, "reason": "import numpy,from scipy", "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995782141545, "lm_q2_score": 0.8933093968230773, "lm_q1q2_score": 0.8628471696061512}}
{"text": "import sympy as sp\n\nx = sp.Symbol('x')\nf = (x**3)/(1+x**(1/2))\nprint('Integrate the following algebraic expression from 1 to 2')\nsp.pprint(f)\n\nlim_inf=1\nlim_sup=2\n# Numerical integration by Simpson 1/3 method\nprint('\\nSimpson 1/3\\n')\nn = 2   # For Simpson 1/3 n=2\nh = (lim_sup-lim_inf)/n\nx0 = lim_inf\nf0 = f.subs(x,x0)\nx1 = x0+h\nf1 = f.subs(x,x1)\nx2 = x1+h\nf2 = f.subs(x,x2)\nprint('h = ',h,'\\nx0 = ',x0,'\\nf0 = ',f0,'\\nx1 = ',x1,'\\nf1 = ',f1,'\\nx2 = ',x2,'\\nf2 = ',f2)\nI = (h/3)*(f0+4*f1+f2)\nprint('Result = ',I)\n\n# Numerical integration by Simpson 3/8 method\nprint('\\nSimpson 3/8\\n')\nn = 3   # For Simpson 3/8 n=3\nh = (lim_sup-lim_inf)/n\nx0 = lim_inf\nf0 = f.subs(x,x0)\nx1 = x0+h\nf1 = f.subs(x,x1)\nx2 = x1+h\nf2 = f.subs(x,x2)\nx3 = x2+h\nf3 = f.subs(x,x3)\nprint('h = ',h,'\\nx0 = ',x0,'\\nf0 = ',f0,'\\nx1 = ',x1,'\\nf1 = ',f1,'\\nx2 = ',x2,'\\nf2 = ',f2,'\\nx3 = ',x3,'\\nf3 = ',f3)\nI = (3*h/8)*(f0+3*f1+3*f2+f3)\nprint('Result = ',I)\n", "meta": {"hexsha": "6eb70bf70d6a6ded1862141c91ec4eab538d9e7e", "size": 925, "ext": "py", "lang": "Python", "max_stars_repo_path": "numerical_integration_example.py", "max_stars_repo_name": "OscarSantos98/Numerical_integration", "max_stars_repo_head_hexsha": "f91707c8829836982651171ce2c0a2ce9a516500", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numerical_integration_example.py", "max_issues_repo_name": "OscarSantos98/Numerical_integration", "max_issues_repo_head_hexsha": "f91707c8829836982651171ce2c0a2ce9a516500", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical_integration_example.py", "max_forks_repo_name": "OscarSantos98/Numerical_integration", "max_forks_repo_head_hexsha": "f91707c8829836982651171ce2c0a2ce9a516500", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7179487179, "max_line_length": 119, "alphanum_fraction": 0.5675675676, "include": true, "reason": "import sympy", "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9814534354878828, "lm_q2_score": 0.8791467690927439, "lm_q1q2_score": 0.862841616824146}}
{"text": "#Python3 Steven\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef plotPowerFuc():\n    x = np.linspace(-4,4,100)\n    e = range(-1,4)\n    for i in e:\n        y = x**i\n        plt.plot(x,y,label='y=x**%s'%i,linewidth=2)\n\n    plt.xlim(x[0],x[-1])\n    plt.ylim(-20,20)\n    plt.legend()\n    plt.show()\n\ndef plotLine(n=80):\n    for k in range(n):\n        #plt.plot([0, np.cos(2*np.pi*k/n)], [0, np.sin(2*np.pi*k/n)])\n        plt.plot([0, np.cos(2*np.pi*k/n)], [0, np.sin(2*np.pi*k/n)],color=[k/n,k/n,k/n])\n        #plt.plot([0,k*np.cos(2*np.pi*k/n)], [0, k*np.sin(2*np.pi*k/n)],color=[k/n,k/n,k/n])\n        #plt.plot([0,k*np.cos(2*np.pi*k/n)], [0, k*np.sin(2*np.pi*k/n)])\n\n    plt.axis('square')\n    plt.show()\n\ndef complexRoot(n=2):\n    #Z**n=1\n    for k in range(n):\n        yield np.exp(2*np.pi*1j*k/n)\n\ndef plotCompexRoot(n=50):\n    for k in range(n):\n        #z = np.exp(2*np.pi*1j*k/n)\n        z = k*np.exp(2*np.pi*1j*k/n)\n        #plt.plot([0,np.real(z)], [0,np.imag(z)])\n        plt.plot([0,np.real(z)], [0,np.imag(z)],color=[0,0,0])\n\n    plt.axis('square')\n    plt.show()\n\ndef plotTrigonometry():\n    t = np.linspace(0,8*np.pi,1000)\n    r1 = np.random.rand()\n    r2 = np.random.rand()\n\n    x = np.cos(r1*t)\n    y = np.cos(r2*t)\n    plt.plot(x,y,'k')\n    plt.title('r1=%s,r2=%s'%(np.round(r1,2),np.round(r2,2)))\n    plt.axis('square')\n    plt.show()\n\ndef derivative(f,x,h=0.0001): #slop\n    return (f(x+h)-f(x))/h\n\ndef func(x):\n    return x**8\n    #return x**3\n\ndef plotTangent():\n    x = np.linspace(-1,1,50)\n    xT = np.linspace(-1,1,100)\n    bound=[-2,2]\n    for i in xT:\n        y=func(i)\n        slope = derivative(func,i)\n        b = y-slope*i\n        plt.plot([bound[0],bound[1]],[slope*bound[0]+b,slope*bound[1]+b],color=[abs(i)/3,abs(i)/2,abs(i)/3])\n    #plt.axis('square')\n    plt.axis('off')\n    plt.plot(x,func(x))\n    plt.xlim(x[0],x[-1])\n    plt.ylim(-3,3)\n    plt.show()\n\ndef main():\n    #plotPowerFuc()\n    #plotLine()\n    #plotCompexRoot()\n    #plotTrigonometry()\n    plotTangent()\n\nif __name__=='__main__':\n    main()\n", "meta": {"hexsha": "473cfadd1ab5287526a1d04caf5fda0220a3fef5", "size": 2043, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/mathPlot.py", "max_stars_repo_name": "StevenHuang2020/ML", "max_stars_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mathPlot.py", "max_issues_repo_name": "StevenHuang2020/ML", "max_issues_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mathPlot.py", "max_forks_repo_name": "StevenHuang2020/ML", "max_forks_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7558139535, "max_line_length": 108, "alphanum_fraction": 0.53010279, "include": true, "reason": "import numpy", "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.90192067455231, "lm_q1q2_score": 0.8628081629635729}}
{"text": "import numpy as np\n\n\"\"\"This program aim to:\n    1) on the fly construct a list of prime number\n    2) strip out all the prime factor from target \"\"\"\n\ninput_num = 600851475143\n#input_num = 13195 \n\n#INT\nprimes = np.empty(1000,dtype=int)\ncounters = np.empty(1000,dtype=int)\ntarget = input_num\nfactors = []\nn = 0\n\nprint(\"TARGET = \", target)\n\n#manual check 2\nwhile(target % 2 == 0):\n    target //= 2\n    factors.append(2)\n\nprint(\"Try dividing by: 2, remainder =\",target)\n\n\n# Loop through all the odd numbers to find primes\n# until all the factors are found\ni = 3\nwhile i*i <= target:\n    for j in range(n):\n        counters[j] += 2\n        if(counters[j] >= primes[j]):\n            counters[j] -= primes[j]\n\n# if none of the counters are zero, it is a prime\n    if not any(counters[:n] == 0):\n        primes[n] = i\n        counters[n] = 0\n        n += 1\n\n# try strip factors from target using the newly found prime\n        while(target % i == 0):\n            target //= i\n            factors.append(i)\n\n\n        print(\"Try dividing by:\",i, \", remainder =\",target)\n\n    i += 2\n        \n\n# OUTPUT\nif(target == 1):\n# write a pythonic statement in case my TA complains I am writing C\n    print(input_num, \"=\", \" x \".join([str(x) for x in factors]))\n    print(\"LARGEST PRIME FACTOR = \", primes[n-1])\nelse:\n    factors.append(target)\n    print(input_num, \"=\", \" x \".join([str(x) for x in factors]))\n    print(\"LARGEST PRIME FACTOR = \", target)\n\n", "meta": {"hexsha": "3cd9562d2098c51aa963170755fbdc1ac61b2c80", "size": 1434, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week01/Problem03/ypang_03.py", "max_stars_repo_name": "nkruyer/SkillsWorkshop2018", "max_stars_repo_head_hexsha": "2201255ff63eca111635789267d0600a95854c38", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-18T03:30:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-18T03:30:46.000Z", "max_issues_repo_path": "Week01/Problem03/ypang_03.py", "max_issues_repo_name": "nkruyer/SkillsWorkshop2018", "max_issues_repo_head_hexsha": "2201255ff63eca111635789267d0600a95854c38", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2018-07-12T19:12:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-10T13:52:45.000Z", "max_forks_repo_path": "Week01/Problem03/ypang_03.py", "max_forks_repo_name": "nkruyer/SkillsWorkshop2018", "max_forks_repo_head_hexsha": "2201255ff63eca111635789267d0600a95854c38", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 60, "max_forks_repo_forks_event_min_datetime": "2018-05-08T16:59:20.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-01T14:28:28.000Z", "avg_line_length": 22.7619047619, "max_line_length": 67, "alphanum_fraction": 0.6032078103, "include": true, "reason": "import numpy", "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140616, "lm_q2_score": 0.896251371748038, "lm_q1q2_score": 0.8627970958431783}}
{"text": "\nimport numpy as np\nfrom numpy.lib.function_base import append\n\n# 传入源数据，源数据是n×m的数据矩阵，n是事务个数，m是事务特征个数\n# k是降维后的维度，当k=-1是默认值,k=其它值时代表它传入了这个参数，否则k值由程序决定\n# 返回降维后的数据，它是n×k的矩阵\ndef PCA(src_data,k=-1):\n    # 求均值\n    avg = np.array([np.mean(src_data[:, i]) for i in range(len(src_data[0]))])\n    src_sub=src_data-avg\n    print(1)\n    # 求协方差矩阵\n    C=np.dot(np.transpose(src_sub),src_sub)\n    print(2)\n    # C=np.divide(C,len(src_data))\n    # 求特征值，特征向量\n    val, vec = np.linalg.eig(C)\n    print(3)\n    # 将特征值和特征向量组合\n    characteristic=[]\n    for i in range(len(val)):\n        characteristic.append([val[i],vec[:,i]])\n    print(4)\n    # 然后排序\n    characteristic.sort(key=lambda characteristic: characteristic[0], reverse=True)\n    print(5)\n    # 当k=-1时，意味着我们要自己决定k\n    if k==-1:\n        # stop为阈值\n        stop=0.95\n        sum=0\n        for i in range(len(characteristic)):\n            sum=sum+characteristic[i][0]\n        stop=stop*sum\n        for i in range(len(characteristic)-1,-1,-1):\n            if sum-characteristic[i][0]>=stop:\n                sum=sum-characteristic[i][0]\n            else:\n                break\n        k=i+1\n        \n    # 获得前k个特征向量，组成矩阵\n    vec=[]\n    for i in range(k):\n        vec.append(characteristic[i][1])\n\n    # 与减去平均值的矩阵相乘，获得降维后的数据\n    data=np.dot(src_sub,np.transpose(vec))\n    return data", "meta": {"hexsha": "1a2171830171fe6cd1f7ab538c43cc2be7ac2a9a", "size": 1313, "ext": "py", "lang": "Python", "max_stars_repo_path": "cell_clustering/PCA1.py", "max_stars_repo_name": "dreaming-qin/python_algorithm", "max_stars_repo_head_hexsha": "f5277cec71aad6f62e665e171e0a96f33abd1671", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-13T15:21:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T15:21:51.000Z", "max_issues_repo_path": "cell_clustering/PCA1.py", "max_issues_repo_name": "dreaming-qin/python_algorithm", "max_issues_repo_head_hexsha": "f5277cec71aad6f62e665e171e0a96f33abd1671", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cell_clustering/PCA1.py", "max_forks_repo_name": "dreaming-qin/python_algorithm", "max_forks_repo_head_hexsha": "f5277cec71aad6f62e665e171e0a96f33abd1671", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.26, "max_line_length": 83, "alphanum_fraction": 0.5910129474, "include": true, "reason": "import numpy,from numpy", "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138183570425, "lm_q2_score": 0.8824278571786139, "lm_q1q2_score": 0.8627619096667256}}
{"text": "import numpy as np\nfrom findiff import FinDiff\nfrom scipy.special import factorial\n\ndef taylor_approximate(pars, x0s, derivs, order=None):\n    '''\n    Computes the nth order Taylor series approximation to a function given \n    - derivs: a list of n derivatives\n    - x0s: the point about which we are expanding\n    - pars: the coordinates at which we want to expand the function\n    If order is specified it will go to that order instead of using the full list of derivatives.\n    '''\n    Nparams = len(x0s)\n    output_shape = derivs[0].shape\n    \n    if order is None:\n        order = len(derivs) - 1\n        print(\"Taking the order %d Taylor series.\"%(order))\n\n    Fapprox = np.zeros(output_shape)\n    diffs =  [ (pars[ii] - x0s[ii]) for ii in range(Nparams) ]\n\n    for oo in range(order+1):\n        if oo == 0:\n            Fapprox += derivs[oo]\n        else:\n            param_inds = np.meshgrid( * (np.arange(Nparams),)*oo, indexing='ij')\n            PInds = [ind.flatten() for ind in param_inds] \n        \n            term = 0\n        \n            for iis in zip(*PInds):\n                term += derivs[oo][iis] * np.prod([ diffs[ii] for ii in iis ])\n            \n            Fapprox += 1/factorial(oo) * term\n    \n    return Fapprox\n\n\ndef compute_derivatives(Fs, dxs, center_ii, order):\n    '''\n    Computes all the partial derivatives up to order 'order' given a function on a grid Fs\n    The grid separation is given by dxs, and the derivatives are computed at the grid point 'center_ii.'\n    \n    Assumes that Fs is gridded in the standard matrix way (i.e. indexing = 'ij' in numpy) as\n    opposed to Cartesian indexing that one uses for plotting.\n    '''\n    \n    # assume the structure of the input is\n    # [Npoints,]*Nparams + output_shape, where Nparams is also the length of dxs\n    \n    Nparams = len(dxs)\n    output_shape = Fs.shape[len(dxs):]\n    \n    derivs = []\n\n    for oo in range(order+1):\n        if oo == 0:\n            derivs += [Fs[center_ii]]\n        else:\n            dnFs = np.zeros( (Nparams,)*oo + output_shape)\n        \n            # Want to get a list of all the possible d/dx_i dx_j dx_k ...\n            param_inds = np.meshgrid( * (np.arange(Nparams),)*oo, indexing='ij')\n            PInds = [ind.flatten() for ind in param_inds] \n        \n            for iis in zip(*PInds):\n                # build a string of (xk, dxk, 1) for taking the d/dxk derivative in sequence\n                deriv_tuple = []\n                for ii in iis:\n                    deriv_tuple += [(ii, dxs[ii],1),]\n            \n                dndx = FinDiff(*deriv_tuple)\n            \n                dnFs[iis] += dndx(Fs)[center_ii]\n        \n            derivs += [dnFs]\n            \n    return derivs\n\n", "meta": {"hexsha": "4f48f22139f0b7c4a503da24964096d6d7f2e429", "size": 2713, "ext": "py", "lang": "Python", "max_stars_repo_path": "boss_analysis/finite_difference/taylor_approximation.py", "max_stars_repo_name": "LBJ-Wade/CobayaLSS", "max_stars_repo_head_hexsha": "faa233a31cf1fba120258ebd143b1c92c9e13135", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-14T07:29:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T07:29:17.000Z", "max_issues_repo_path": "boss_analysis/finite_difference/taylor_approximation.py", "max_issues_repo_name": "LBJ-Wade/CobayaLSS", "max_issues_repo_head_hexsha": "faa233a31cf1fba120258ebd143b1c92c9e13135", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boss_analysis/finite_difference/taylor_approximation.py", "max_forks_repo_name": "LBJ-Wade/CobayaLSS", "max_forks_repo_head_hexsha": "faa233a31cf1fba120258ebd143b1c92c9e13135", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-14T07:29:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T07:29:18.000Z", "avg_line_length": 33.4938271605, "max_line_length": 104, "alphanum_fraction": 0.5713232584, "include": true, "reason": "import numpy,from scipy", "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102542943773, "lm_q2_score": 0.8918110555020056, "lm_q1q2_score": 0.8627471599857323}}
{"text": "import numpy as np\nfrom ._Regularization import _L1Reg,_L2Reg\n\ndef MeanSquareCost(h,y,ThetaW,L1=0.0,L2=0.0):\n\tm = y.shape[0]\n\t#diff = (h-y)**2\n\t#print(h.dtype,y.dtype,diff.dtype,h.min(),h.max(),y.min(),y.max(),diff.min(),diff.max(),np.sum(diff))\n\t#J = np.sum((h - y)**2)/(2*m)\n\tJ = np.mean((h - y)**2)/2\n\t\n\t\n\tif L1 > 0.0:\n\t\tL1Reg = _L1Reg(ThetaW,L1,m)\n\telse:\n\t\tL1Reg = 0.0\n\t\n\tif L2 > 0.0:\n\t\tL2Reg = _L2Reg(ThetaW,L2,m)\n\telse:\n\t\tL2Reg = 0.0\t\n\t\n\tJ = J + L1Reg + L2Reg\n\treturn J\t\n\ndef MeanSquareDelta(h,y,InvAFgrad):\n\n\treturn (h - y)*InvAFgrad(h)\n", "meta": {"hexsha": "979f9a0e2c09c2e861677ccab87020f6766823bf", "size": 544, "ext": "py", "lang": "Python", "max_stars_repo_path": "PyNeuralNetwork/CostFunctions/MeanSquareCost.py", "max_stars_repo_name": "mattkjames7/PyNeuralNetwork", "max_stars_repo_head_hexsha": "edbee96aa9039d22e83253700edaf3b98d4ed9d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PyNeuralNetwork/CostFunctions/MeanSquareCost.py", "max_issues_repo_name": "mattkjames7/PyNeuralNetwork", "max_issues_repo_head_hexsha": "edbee96aa9039d22e83253700edaf3b98d4ed9d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyNeuralNetwork/CostFunctions/MeanSquareCost.py", "max_forks_repo_name": "mattkjames7/PyNeuralNetwork", "max_forks_repo_head_hexsha": "edbee96aa9039d22e83253700edaf3b98d4ed9d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4285714286, "max_line_length": 102, "alphanum_fraction": 0.6011029412, "include": true, "reason": "import numpy", "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102571131692, "lm_q2_score": 0.891811038968166, "lm_q1q2_score": 0.8627471465045561}}
{"text": "\n#!/usr/bin/env python \n#   Author: Christopher Bull. \n#   Affiliation:  British Antarctic Survey\n#                 Cambridge, UK\n#   Contact: chbull@bas.ac.uk\n#   www:     christopherbull.com.au\n#   Date created: Sun, 13 Mar 2022 14:29:36\n#   Machine created on: SB2Vbox\n\"\"\"\nStep 1: 1-D Linear Convection\n\"\"\"\nfrom cb2logger import *\nimport numpy                       #here we load numpy\nfrom matplotlib import pyplot      #here we load matplotlib\nimport matplotlib.pyplot as plt\nimport time, sys                   #and load some utilities\n\nif __name__ == \"__main__\": \n    LogStart('',fout=False)\n    #Now let's define a few variables; we want to define an evenly spaced grid of points within a spatial domain that is 2 units of length wide, i.e., 𝑥𝑖∈(0,2). We'll define a variable nx, which will be the number of grid points we want and dx will be the distance between any pair of adjacent grid points. \n\n    nx = 41  # try changing this number from 41 to 81 and Run All ... what happens? \n    #CB: seems like '81' is the necessary amount of resolution required to not difuse the bump, 61 does better but not as good as 81\n\n    dx = 2 / (nx-1)\n    nt = 25    #nt is the number of timesteps we want to calculate\n    dt = .025  #dt is the amount of time each timestep covers (delta t)\n    c = 1      #assume wavespeed of c = 1\n\n    #We also need to set up our initial conditions. The initial velocity 𝑢0 is given as 𝑢=2 in the interval 0.5≤𝑥≤1 and 𝑢=1 everywhere else in (0,2) (i.e., a hat function).\n    u = numpy.ones(nx)      #numpy function ones()\n    u[int(.5 / dx):int(1 / dx + 1)] = 2  #setting u = 2 between 0.5 and 1 as per our I.C.s\n\n\n    pyplot.plot(numpy.linspace(0, 2, nx), u)\n    #Why doesn't the hat function have perfectly straight sides? Think for a bit.\n\n    #cb: b/c nx has a small number of points (goes to vertical as nx--> \\infinity)\n    #plt.show()\n\n\n    un = numpy.ones(nx) #initialize a temporary array\n\n    for n in range(nt):  #loop for values of n from 0 to nt, so it will run nt times\n        un = u.copy() ##copy the existing values of u into un\n        for i in range(1, nx): ## you can try commenting this line and...\n        #for i in range(nx): ## ... uncommenting this line and see what happens!\n            u[i] = un[i] - c * dt / dx * (un[i] - un[i-1])\n\n    pyplot.plot(numpy.linspace(0, 2, nx), u)\n    plt.show()\n\n    lg.info('')\n    localtime = time.asctime( time.localtime(time.time()) )\n    lg.info(\"Local current time : \"+ str(localtime))\n    lg.info('SCRIPT ended')\n", "meta": {"hexsha": "db660fe33dd7710101c787903062574a765d6e40", "size": 2509, "ext": "py", "lang": "Python", "max_stars_repo_path": "lessons/01_Step_1_cb.py", "max_stars_repo_name": "chrisb13/CFDPython", "max_stars_repo_head_hexsha": "0b408ad8f1691b1f2b2785cf50898e713c3326d8", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lessons/01_Step_1_cb.py", "max_issues_repo_name": "chrisb13/CFDPython", "max_issues_repo_head_hexsha": "0b408ad8f1691b1f2b2785cf50898e713c3326d8", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lessons/01_Step_1_cb.py", "max_forks_repo_name": "chrisb13/CFDPython", "max_forks_repo_head_hexsha": "0b408ad8f1691b1f2b2785cf50898e713c3326d8", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2586206897, "max_line_length": 307, "alphanum_fraction": 0.643284177, "include": true, "reason": "import numpy", "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.9324533083911025, "lm_q1q2_score": 0.8627337345130293}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef P_cumulativa(pi):\n  ''' Calcula a CDF F(x) de uma PMF P(x) '''\n  pif = [pi[0]]\n  for i in range(1, len(pi)):\n    pif.append( pif[-1] + pi[i])\n  return pif\n\n\ndef escolhe_estado(S, fpi):\n  ''' Dada uma Cadeia de Markov com vetor de estados S e CDF F(i), escolhe aleatoriamente o próximo estado ''' \n  r = np.random.rand(1)[0]\n  for i in range(len(S)):\n    if fpi[i] >= r:\n      return S[i]\n\n    \ndef simular_cadeia_markov(S, pi, P, n, m):\n  ''' \n  Realiza m simulações numéricas com n instâncias de uma Cadeia de Markov com estados S, \n  probabilidades iniciais pi e matriz de transição P \n  ''' \n  processo = np.zeros((m,n))\n  for j in range(m):\n    pi_t = pi\n    pif = P_cumulativa(pi_t)\n    processo[j, 0] = escolhe_estado(S, pif)\n    for i in range(1, n):\n      p = P[ int(processo[j, i - 1]) , : ]\n      pf = P_cumulativa(p)\n      processo[j, i] = escolhe_estado(S, pf)\n  return processo\n\ndef mat_pot(mat, n):\n  ''' Função atalho para a exponenciação de matrizes '''\n  return np.linalg.matrix_power(mat, n)\n\ndef e_regular(mat, n):\n  ''' Indica se a matriz mat elevada à potência n é regular, isto é, todos os seus valores são maiores que zero. '''\n  return np.all(mat_pot(mat,n) > 0)\n\ndef transicao(pi, P, n):\n  ''' Calcula analiticamente o vetor de estados após n transições de uma Cadeia de Markov com matriz de transição P ''' \n  return pi.dot(mat_pot(P, n))\n\ndef simular_convergencia(S, pi, P, n, nomes=None):\n  ''' \n  Avalia numericamente e visualmente a convergência para n passos de uma Cadeia de Markov com estados S, \n  probabilidades iniciais pi e matriz de transição P  \n  '''\n  pit = pi\n  ns = pi.shape[0]\n  pis = np.zeros((n,ns))\n  for i in range(n):\n    pit = pit.dot(P)\n    pis[i,:] = pit\n  for i in range(ns):\n    plt.plot(pis[:,i], label=\"{}\".format(i if nomes is None else nomes[i]))\n  plt.legend()\n  plt.tight_layout()\n  \ndef dist_estacionaria(S, P):\n  ''' \n  Calcula analiticamente a distribuição estacionária de uma Cadeia de Markov com estados S, \n  e matriz de transição P\n  '''\n  m = len(S)\n  A = np.append(P.T - np.identity(m), np.ones((1,m)),axis=0)\n  b = np.zeros(m+1)\n  b[-1] = 1\n  b = b.T\n  return np.linalg.solve(A.T.dot(A), A.T.dot(b))\n", "meta": {"hexsha": "7d62e7dd2b463ee0b578ca779826b97d4b126d8b", "size": 2227, "ext": "py", "lang": "Python", "max_stars_repo_path": "cadeias_markov.py", "max_stars_repo_name": "petroniocandido/STPE", "max_stars_repo_head_hexsha": "0303224fadddd40f86b816432e1a594afaebe8fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cadeias_markov.py", "max_issues_repo_name": "petroniocandido/STPE", "max_issues_repo_head_hexsha": "0303224fadddd40f86b816432e1a594afaebe8fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cadeias_markov.py", "max_forks_repo_name": "petroniocandido/STPE", "max_forks_repo_head_hexsha": "0303224fadddd40f86b816432e1a594afaebe8fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3026315789, "max_line_length": 120, "alphanum_fraction": 0.6416704086, "include": true, "reason": "import numpy", "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832974, "lm_q2_score": 0.9252299493606285, "lm_q1q2_score": 0.8627337260013069}}
{"text": "# Dado uma lista com n elementos, escreva um programa em Python que retorne as seguintes medidas:\n# A média aritmética e geométrica;\n# Moda;\n# Mediana. \n\nimport numpy #importação para o cálculo do produto dos números da lista\nfrom math import prod #importação para o cálculo do produto dos números da lista\nimport statistics #importação para a moda\nimport math #importação para efetuar alguns cálculos matemáticos (fórmulas)\n\nlista_elementos = [1,5,6,2,5,9,10,15,2,5] #lista aleatória\n\n#len() é a fórmula para contar a quantidade de elementos que tem na lista\n\n# Média aritimética: a soma dos elementos da lista dividido pela quantidade de elementos que a lista tem\nmedia_arit = sum(lista_elementos)/len(lista_elementos) #sun() é a fórmula de soma\nprint(\"A média aritmética é \", media_arit)\n\n# Média geométrica: é a raíz dos N elementos da multiplicação dos elementos.ATENÇÃO para o 1/len pois é raíz\nmedia_geo = numpy.prod(lista_elementos)**(1/len(lista_elementos))\nprint(\"A média geométrica é \", media_geo)\nmedia_goe2 = prod(lista_elementos)**(1/len(lista_elementos))\nprint(\"A média geométrica de outro jeito é: \",media_goe2) \n\n# Para calcular a mediana precisamos organizar a lista, e para facilitar eu criei um valor com a quantidade de elementos da lista para facilitar nos cálculos, pra não ficar um fórmula dentro de outra. \n\nlista_ordenada = sorted(lista_elementos) #função para ordenar os elementos da lista de forma crescente\nprint(lista_ordenada)\n\nelementos = len(lista_elementos) \nprint(\"Quantidade de elementos na lista: \", elementos)\n\nmeio=int(elementos/2) #função para verificar qual a posição do meio na lista (é posição, não é o número)\nprint(\"Posição do elemento central: \", meio+1) #como começa com índice zero, considerei o + 1 porque iniciamos a contagem em 1, 2, 3... e o python inicia a contagem do index em 0, 1, 2...\n\n# Medida: SE a quantidade de elementos é par, a mediana é a soma do valor antecessor ao meio e o valor do meio, divido por 2. SE a quantidade de elementos é ímpar, a mediana é o valor central. \nif (len(lista_ordenada)%2)==0: #verificar se o resto da divisão por 2 é zero, se for é par. \n    mediana = ((lista_ordenada[meio-1])+lista_ordenada[meio])/2\n    print(\"A mediana é: \", mediana)\nelse: \n    mediana = lista_ordenada[meio] #função que acessa o valor do meio da lista\n    print(\"A mediana é: \", mediana)\n# Volte ao Ex05 para ver maiores explicações sobre essa questão do posicionamento. \n\n# Moda: valor que aparece mais vezes na lista\n# não consegui fazer sem usar fórumla!!!\n# SE a quantidade de elementos da fórmula multimodal for apenas 1, significa que não é multimodal, é apenas 1 número com maior frequência. Caso contrário, significa que os valores são multimodais. \nif (len(statistics.multimode(lista_ordenada))==1):\n    moda = statistics.mode(lista_ordenada) #para o caso de ser somente uma moda\n    print(\"A moda é: \",moda)\nelse:\n    moda2 = statistics.multimode(lista_ordenada) #para o caso de ser multimodal\n    print(\"A moda multimodal é: \", moda2)   \n#Fazer com a lista original gera resultados diferentes, pois ela vai considerar o primeiro valor que se repete da lista, por exemplo, vai retornar [5,2] na multimodal. E não [2,5] na lista ordenada. \n\n#Statistics.multimode e statistics.mode são fórmulas de moda e moda multimodal. \n\n# Prof indicou esse site: https://www.geeksforgeeks.org/finding-mean-median-mode-in-python-without-libraries/ para o cálculo da moda sem usar uma fórmula já definida. \n\n# OBS: se você conseguir entender, por gentileza, me explique!!!! \n\n#Segue o código que tem no link: \n\n# Python program to print\n# mode of elements\nfrom collections import Counter\n  \n# list of elements to calculate mode\nn_num = [1, 2, 3, 4, 5, 2]\nn = len(n_num)\n  \ndata = Counter(n_num)\nget_mode = dict(data)\nmode = [k for k, v in get_mode.items() if v == max(list(data.values()))]\n  \nif len(mode) == n:\n    get_mode = \"No mode found\"\nelse:\n    get_mode = \"Mode is / are: \" + ', '.join(map(str, mode))\n      \nprint(get_mode)", "meta": {"hexsha": "44851555fbd8cc43631b83b99c5dc4e5f8cfac81", "size": 3989, "ext": "py", "lang": "Python", "max_stars_repo_path": "Exercicios_Aula01/Ex06.py", "max_stars_repo_name": "DanyViana/Desen_Rap_Aplic_Python", "max_stars_repo_head_hexsha": "ed82e91b735a6b78f5cad9af34776ad2d39d9c19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Exercicios_Aula01/Ex06.py", "max_issues_repo_name": "DanyViana/Desen_Rap_Aplic_Python", "max_issues_repo_head_hexsha": "ed82e91b735a6b78f5cad9af34776ad2d39d9c19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercicios_Aula01/Ex06.py", "max_forks_repo_name": "DanyViana/Desen_Rap_Aplic_Python", "max_forks_repo_head_hexsha": "ed82e91b735a6b78f5cad9af34776ad2d39d9c19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-13T14:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T14:46:31.000Z", "avg_line_length": 49.2469135802, "max_line_length": 201, "alphanum_fraction": 0.7465530208, "include": true, "reason": "import numpy", "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152283, "lm_q2_score": 0.9099070017626536, "lm_q1q2_score": 0.8627324499813879}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSYS-611: Example Markov Process Generator\n\n@author: Paul T. Grogan, pgrogan@stevens.edu\n\"\"\"\n\n# import the python3 behavior for importing, division, and printing in python2\nfrom __future__ import absolute_import, division, print_function\n\n# import the numpy package and refer to it as `np`\n# see http://docs.scipy.org/doc/numpy/reference/ for documentation\nimport numpy as np\n# import the matplotlib.pyplot package and refer to it as `plt`\nimport matplotlib.pyplot as plt\n\n# define the state transition function\ndef next_state(q):\n    r = np.random.rand()\n    # if it is a clear day\n    if q == 0:\n        if r < 186/250:\n            # another clear day\n            return 0\n        elif r < (186+47)/250:\n            # a rainy day next\n            return 1\n        else:\n            # a snowy day next\n            return 2\n    # if it is a rainy day\n    elif q == 1:\n        if r < 47/89:\n            # a clear day next\n            return 0\n        elif r < (47+40)/89:\n            # another rainy day\n            return 1\n        else:\n            # a snowy day next\n            return 2\n    # if it is a snowy day\n    else:\n        if r < 16/25:\n            # a clear day next\n            return 0\n        elif r < (16+3)/25:\n            # a rainy day next\n            return 1\n        else:\n            # another snowy day\n            return 2\n\n# define the number of samples and create a state trajectory\nnum_samples = 100\nnp.random.seed(0)\nq = np.zeros(num_samples)\n# perform all the state transitions\nfor t in range(num_samples - 1):\n    q[t+1] = next_state(q[t])\n\n# create a plot of the state trajectory\nplt.figure()\nplt.step(range(num_samples), q, '-r')\nplt.xlabel('Time ($t$)')\nplt.ylabel('State ($q$)')\n\n# estimate the stationary distribution from the samples\npi = np.zeros(3)\nfor i in range(3):\n    pi[i] = np.sum(q==i)/num_samples\n\nprint('estimated stationary distribution (solved using simulation):')\nprint(' P(q=0) = {:.3f} (clear day)'.format(pi[0]))\nprint(' P(q=1) = {:.3f} (rainy day)'.format(pi[1]))\nprint(' P(q=2) = {:.3f} (snowy day)'.format(pi[2]))\n\n#%% steady-state analysis\n\n# formal state transition matrix\nP = [[186/250, 47/250, 17/250], \n     [47/89, 40/89, 2/89],\n     [16/25, 3/25, 6/25]]\n\n# compute the eigenvalues and eigenvectors of the transpose of P\nw,v = np.linalg.eig(np.transpose(P))\n\n# the stationary distribution is the normalized eigenvector \n# corresponding to the eigenvalue of 1\npi_exact = v[:,0]/np.sum(v[:,0])\n\nprint('exact stationary distribution (solved using eigenvectors):')\nprint(' P(q=0) = {:.3f} (clear day)'.format(pi_exact[0]))\nprint(' P(q=1) = {:.3f} (rainy day)'.format(pi_exact[1]))\nprint(' P(q=2) = {:.3f} (snowy day)'.format(pi_exact[2]))", "meta": {"hexsha": "3915e1f0f4e03fad7343294775882e97654890dd", "size": 2724, "ext": "py", "lang": "Python", "max_stars_repo_path": "previous/week8/weatherMarkovModel.py", "max_stars_repo_name": "code-lab-org/sys611", "max_stars_repo_head_hexsha": "3b8c46788dee629a9f2d6b7f84373e041b918ff0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-07T03:52:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T18:16:16.000Z", "max_issues_repo_path": "previous/week8/weatherMarkovModel.py", "max_issues_repo_name": "code-lab-org/sys611", "max_issues_repo_head_hexsha": "3b8c46788dee629a9f2d6b7f84373e041b918ff0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "previous/week8/weatherMarkovModel.py", "max_forks_repo_name": "code-lab-org/sys611", "max_forks_repo_head_hexsha": "3b8c46788dee629a9f2d6b7f84373e041b918ff0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-02-12T01:57:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T18:05:27.000Z", "avg_line_length": 28.6736842105, "max_line_length": 78, "alphanum_fraction": 0.6064610866, "include": true, "reason": "import numpy", "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152283, "lm_q2_score": 0.9099069980980297, "lm_q1q2_score": 0.8627324465067581}}
{"text": "# The prime factors of 13195 are 5, 7, 13 and 29.\n# What is the largest prime factor of the number 600851475143 ?\n\nimport numpy as np\n\ndef solve():\n    \n    number = 600851475143\n    \n    max_factor = int(np.sqrt(number))\n    print(\"Max_factor\", max_factor)\n    \n    # Looking for prime numbers\n    \n    numbers = [i for i in range(1, max_factor+1)]\n    is_prime = [True for i in range(max_factor)]\n#    print(numbers)\n#    print(is_prime)\n    \n    current_prime_index = 1\n    prime_index_condition = current_prime_index < len(is_prime)\n    while prime_index_condition:\n        print(\"Current prime number:\", current_prime_index+1)\n        # We bar the multiples\n        is_prime_traversal = 2 * current_prime_index + 1\n        condition = is_prime_traversal < len(is_prime)\n        while condition:\n            is_prime[is_prime_traversal] = False\n            is_prime_traversal += current_prime_index + 1\n            condition = is_prime_traversal < len(is_prime)\n#        print(numbers)\n#        print(is_prime)\n        # Next prime\n        next_prime_index = current_prime_index + 1\n        condition = next_prime_index < len(is_prime)\n        condition = condition and (is_prime[next_prime_index] == False)\n        while condition:\n            next_prime_index = next_prime_index + 1\n            condition = (next_prime_index < len(is_prime))\n            \n            condition = condition and (is_prime[next_prime_index] == False)\n        current_prime_index = next_prime_index\n        prime_index_condition = current_prime_index < len(is_prime)\n    \n    prime_numbers = [n for n, p in zip(numbers, is_prime) if p]\n\n    for factor in reversed(prime_numbers):\n        if number%factor == 0:\n            return factor\n        \n    return\n    \nprint(solve())", "meta": {"hexsha": "1aee29efa490901c283943dfcd06f030769f8b15", "size": 1761, "ext": "py", "lang": "Python", "max_stars_repo_path": "problem_003.py", "max_stars_repo_name": "JlnZhou/ProjtecEuler", "max_stars_repo_head_hexsha": "6bbc4cbed2bf6596346d6d84e07b5355a36304c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problem_003.py", "max_issues_repo_name": "JlnZhou/ProjtecEuler", "max_issues_repo_head_hexsha": "6bbc4cbed2bf6596346d6d84e07b5355a36304c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem_003.py", "max_forks_repo_name": "JlnZhou/ProjtecEuler", "max_forks_repo_head_hexsha": "6bbc4cbed2bf6596346d6d84e07b5355a36304c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2264150943, "max_line_length": 75, "alphanum_fraction": 0.6433844407, "include": true, "reason": "import numpy", "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147169737826, "lm_q2_score": 0.8872045847699186, "lm_q1q2_score": 0.8627307951968827}}
{"text": "\n# coding: utf-8\nВозьмем как пример распределение Лапласса\n# In[1]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as stat\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[2]:\n\n\na = 1.0\nb = 0.0\nld = stat.laplace(loc=b, scale=a)\nx = np.linspace(-4, 4, 1000)\nplt.plot(x, stat.laplace.pdf(x))\n\n\n# In[3]:\n\n\nsample = ld.rvs(size=1000)\nplt.hist(sample, normed=True, bins=30)\nplt.ylabel('number of samples')\nplt.xlabel('$x$')\n\n\n# In[4]:\n\n\nsizes = [5, 10, 30, 45]\nsamples = []\nfor i in sizes:\n    samples.append(stat.laplace.rvs(size=[1000, i]))\n\n\n# In[5]:\n\n\nmeans_of_sample = []\nfor sample in samples:\n    means = []\n    for i in sample:\n        means.append(np.mean(i))\n    means_of_sample.append(means)\n\n\n# In[6]:\n\n\nmean = b\ndispersion = 2 / ((2 * stat.laplace.pdf(mean)) ** 2)\nprint(\"mean: \" + str(mean) \n      + \"\\ndispersion: \" + str(dispersion))\n\n\n# In[7]:\n\n\nnorm_rv = stat.norm(mean, np.sqrt(dispersion / sizes[0]))\nx = np.linspace(-4, 4, 1000)\npdf = norm_rv.pdf(x)\nplt.plot(x, pdf)\n\nplt.hist(means_of_sample[0], normed=True)\nplt.ylabel('number of samples')\nplt.xlabel('n = 5')\n\n\n# In[11]:\n\n\nnorm_rv = stat.norm(mean, np.sqrt(dispersion / sizes[1]))\nx = np.linspace(-4, 4, 1000)\npdf = norm_rv.pdf(x)\nplt.plot(x, pdf)\n\nplt.hist(means_of_sample[1], normed=True)\nplt.ylabel('number of samples')\nplt.xlabel('n = 30')\n\n\n# In[12]:\n\n\nnorm_rv = stat.norm(mean, np.sqrt(dispersion / sizes[2]))\nx = np.linspace(-4, 4, 1000)\npdf = norm_rv.pdf(x)\nplt.plot(x, pdf)\n\nplt.hist(means_of_sample[2], normed=True)\nplt.ylabel('number of samples')\nplt.xlabel('n = 50')\n\n\n# In[13]:\n\n\nnorm_rv = stat.norm(mean, np.sqrt(dispersion / sizes[3]))\nx = np.linspace(-4, 4, 1000)\npdf = norm_rv.pdf(x)\nplt.plot(x, pdf)\n\nplt.hist(means_of_sample[3], normed=True)\nplt.ylabel('number of samples')\nplt.xlabel('n = 100')\n\nТаким образом, чем больше объем выборки, тем больше гистограмма похожа на нормальное распределение", "meta": {"hexsha": "bd487b9665ebd7ba0ee0f5c66645295bc6977632", "size": 1919, "ext": "py", "lang": "Python", "max_stars_repo_path": "coursera/ml_yandex/course1/course1week1/Untitled1.py", "max_stars_repo_name": "VadimKirilchuk/education", "max_stars_repo_head_hexsha": "ebddb2fb971ff1f3991e71fcb17ce83b95c4a397", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "coursera/ml_yandex/course1/course1week1/Untitled1.py", "max_issues_repo_name": "VadimKirilchuk/education", "max_issues_repo_head_hexsha": "ebddb2fb971ff1f3991e71fcb17ce83b95c4a397", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coursera/ml_yandex/course1/course1week1/Untitled1.py", "max_forks_repo_name": "VadimKirilchuk/education", "max_forks_repo_head_hexsha": "ebddb2fb971ff1f3991e71fcb17ce83b95c4a397", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1339285714, "max_line_length": 98, "alphanum_fraction": 0.658676394, "include": true, "reason": "import numpy,import scipy", "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877675527112, "lm_q2_score": 0.8887587890727754, "lm_q1q2_score": 0.8627072848579033}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb  7 21:17:50 2018\n\n@author: Daniel Yang (daniel.yj.yang@gmail.com)\n\"\"\"\n\nimport numpy as np\nfrom scipy import stats, exp\nfrom matplotlib import pyplot as plt\n\n# Normal Distribution\nmu = 0 # mean\nsigma = 1 # standard deviation\nx = np.arange(-5,5,0.1)\n\ny = stats.norm.pdf(x, mu, sigma)\nplt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')\nplt.plot(x, y)\nplt.title('Normal: mu=%.1f, sigma=%.1f'%(mu, sigma))\nplt.xlabel('x')\nplt.ylabel('Probability density')\nplt.ylim(-0.05, 0.45)\nplt.show()\n\ny = stats.norm.cdf(x, mu, sigma)\nplt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')\nplt.plot(x, y)\nplt.title('Normal: mu=%.1f, sigma=%.1f'%(mu, sigma))\nplt.xlabel('x')\nplt.ylabel('Cumulative distribution')\nplt.ylim(-0.1, 1.1)\nplt.show()\n\n\n\n\n\n\n\n# Bivariate normal distribution\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import multivariate_normal\n#from mpl_toolkits.mplot3d import Axes3D\n\n#Parameters to set\nmu_x = 0\nvariance_x = 1\n\nmu_y = 0\nvariance_y = 1\n\n#Create grid and multivariate normal\nx = np.linspace(-4,4,500)\ny = np.linspace(-4,4,500)\nX, Y = np.meshgrid(x,y)\npos = np.empty(X.shape + (2,))\npos[:, :, 0] = X; pos[:, :, 1] = Y\nrv = multivariate_normal([mu_x, mu_y], [[variance_x, 0], [0, variance_y]])\n\n#Make a 3D plot\nfig = plt.figure(num=None, figsize=(8, 6), dpi=300, facecolor='w', edgecolor='k')\nax = fig.gca(projection='3d')\nax.plot_wireframe(X, Y, rv.pdf(pos),rcount=25, ccount=25)\n#ax.plot_surface(X, Y, rv.pdf(pos),cmap='viridis',linewidth=0)\nax.set_xlabel('X axis')\nax.set_ylabel('Y axis')\nax.set_zlabel('Z axis')\nplt.show()\n\n#Make a 3D plot\nfig = plt.figure(num=None, figsize=(8, 6), dpi=300, facecolor='w', edgecolor='k')\nax = fig.gca(projection='3d')\nax.plot_wireframe(X, Y, rv.cdf(pos),rcount=25, ccount=25)\n#ax.plot_surface(X, Y, rv.pdf(pos),cmap='viridis',linewidth=0)\nax.set_xlabel('X axis')\nax.set_ylabel('Y axis')\nax.set_zlabel('Z axis')\nplt.show()\n\n\n\n\n\n\n\n\n\n\n# Student's t-distribution\nmu = 0 # mean\nsigma = 1 # standard deviation\ndf = 1\nx = np.arange(-5,5,0.1)\n\ny = stats.t.pdf(x, df, mu, sigma)\nplt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')\nplt.plot(x, y)\nplt.title('Student\\' t-distribution: df=%.0f, mu=%.1f, sigma=%.1f'%(df, mu, sigma))\nplt.xlabel('x')\nplt.ylabel('Probability density')\nplt.ylim(-0.05, 0.45)\nplt.show()\n\ny = stats.t.cdf(x, df, mu, sigma)\nplt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')\nplt.plot(x, y)\nplt.title('Student\\' t-distribution: df=%.0f, mu=%.1f, sigma=%.1f'%(df, mu, sigma))\nplt.xlabel('x')\nplt.ylabel('Cumulative distribution')\nplt.ylim(-0.1, 1.1)\nplt.show()\n\n\n# Poisson Distribution\n# For discrete outcomes (e.g., the number of customers visiting your lane in a supermarket for check out during 4:30-4:50), with known expected average outcome\n# Watch this for the Wal-Mart example (https://www.youtube.com/watch?v=8px7xuk_7OU)\nn = np.arange(970, 1030)  # the number of possible occurrences of interest, say the number of visitors that might show up during 10-10:30pm on a Tuesday night\nlambda_coef = 1000   # long-run average, say, the expected number of customers in Amazon website between 10:00-10:30pm on a Tuesday night is 1000\ny = stats.poisson.pmf(n, lambda_coef)  # Probability Mass Function is the probability density function for discrete outcome\nplt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')\nplt.plot(n, y, 'o-')\nplt.show()\n# Question: What is the probability that exactly 7 customers enter your lane between 4:30-4:45?\nprint(\"The probability that exactly 7 customers enter my lane between 4:30-4:45 is {0:.2f}%\".format(100*stats.poisson.pmf(7, 10)))\n\n\n\n\n# Bernoulli Distribution\nk = np.array([0,1]) # 0 = tail, 1 = head\np = 0.7 # probability of the head\ny = stats.bernoulli.pmf(k, p)\nfig = plt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')\nax = fig.add_axes([0,0,1,1])\nax.bar(['0','1'], y)\nplt.xlabel('k')\nplt.ylim(0,1)\nplt.show()\n\n\ny = stats.bernoulli.cdf(k, p)\nfig = plt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')\nax = fig.add_axes([0,0,1,1])\nax.bar(['0','1'], y)\nplt.xlabel('k')\nplt.ylim(0,1)\nplt.show()\n\n\n\n\n\n# Binomial Distribution\nn = 10 # number of coins tossed\nk = np.arange(0,n+1) # number of heads\np = 0.5 # probability of the head\ny = stats.binom.pmf(k, n, p)\nplt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')\nplt.bar(k,y)\nplt.xlabel('k')\nplt.plot(k, y, 'o-r')\nplt.show()\n\ny = stats.binom.cdf(k, n, p)\nplt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')\nplt.bar(k,y)\nplt.xlabel('k')\nplt.plot(k, y, 'o-r')\nplt.show()\n\n\n\n\n\n\n\n\n\n# Multinomial Distribution\nn = 20 # 10 # 3 # 2 # number of trials (k-sided dice rolled)\np = [1/6, 1/6, 1/6, 1/6, 1/6, 1/6] # probability of the each side of a 6-sided dice, should sum to 1\n\nrv = stats.multinomial(n, p) # A multinomial random variable\n\nx_samples = rv.rvs(size = 1000000, random_state=12345) # draw random samples.\nx_samples = np.unique(x_samples, axis = 0)\n# each sample consists of number of outcomes for event-1, event-2, ..., event-k, should num to n\n# for example, if n = 9, then x = [2, 1, 2, 1, 2, 1] means the each of the odd-number sides (1,3,5) appearing 2 times and each of the even-number sides (2,4,6) appearing 1 time\n\nx_samples.shape # the # of rows is the distinct possible outcomes of rolling the dice n times\n\ny = rv.pmf(x = x_samples)\n\n# Number of occurrences for each side\n# [≥1, ≥1, ≥1, ≥1, ≥1, ≥1]\nx_samples_subset = x_samples[np.where(\n    (x_samples[:, 0] >= 1) &\n    (x_samples[:, 1] >= 1) &\n    (x_samples[:, 2] >= 1) &\n    (x_samples[:, 3] >= 1) &\n    (x_samples[:, 4] >= 1) &\n    (x_samples[:, 5] >= 1))]\n\nx_samples_subset.shape\n\ny = rv.pmf(x = x_samples_subset)\nsum(y)\n\n# Investment example\nn = 100\np = [75/100, 20/100, 5/100]\nrv = stats.multinomial(n, p) # A multinomial random variable\nx_samples = rv.rvs(size = 10000000, random_state=12345) # draw random samples.\nx_samples = np.unique(x_samples, axis = 0)\nx_samples.shape # the # of rows is the distinct possible outcomes of rolling the dice n times\n# Number of occurrences for each side\n# [≥1, ≥1, ≥1, ≥1, ≥1, ≥1]\nx_samples_subset = x_samples[np.where(\n    (x_samples[:, 0] >= 70) &\n    (x_samples[:, 1] <= 25) &\n    (x_samples[:, 2] <= 5))]\n\nx_samples_subset.shape\n\ny = rv.pmf(x = x_samples_subset)\nsum(y)\n\n\n\n\n\n# Geometric Distribution\nk = np.arange(1,11) # number of heads\np = 0.5 # probability of the head\ny = stats.geom.pmf(k, p)\nplt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')\nplt.bar(k,y)\nplt.xlabel('k')\nplt.plot(k, y, 'o-r')\nplt.show()\n\ny = stats.geom.cdf(k, p)\nplt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')\nplt.bar(k,y)\nplt.xlabel('k')\nplt.plot(k, y, 'o-r')\nplt.show()\n\n\n\n\n\n# Logistic distribution\n# https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.logistic.html\nloc, scale = 10, 1\ns = np.random.logistic(loc, scale, 100000)\ncount, bins, ignored = plt.hist(s, bins=50)\n\ndef logistic_pdf(x, loc, scale):\n    return exp((loc-x)/scale)/(scale*(1+exp((loc-x)/scale))**2)\n\ndef logistic_cdf(x, loc, scale):\n    return 1/(1+(exp((loc-x)/scale)))\n\nplt.plot(bins, logistic_pdf(bins, loc, scale)*count.max()/logistic_pdf(bins, loc, scale).max())\nplt.show()\n\nplt.plot(bins, logistic_cdf(bins, loc, scale)*count.max()/logistic_cdf(bins, loc, scale).max())\nplt.show()\n\n\n\n# Logistic distribution\nloc, scale = 10, 1\nx = np.arange(-5,25,0.1)\ny = stats.logistic.pdf(x, loc, scale) # pdf\nplt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')\nplt.plot(x, y)\nplt.show()\n\ny = stats.logistic.cdf(x, loc, scale) # cdf\nplt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')\nplt.plot(x, y)\nplt.show()\n\n# Chi-square distribution\n# https://machinelearningmastery.com/statistical-data-distributions/\n# plot the chi-squared pdf\nfrom numpy import arange\nfrom matplotlib import pyplot\nfrom scipy.stats import chi2\n# define the distribution parameters\nsample_space = arange(0, 10, 0.01)\ndof = 1 # 3\n# calculate the pdf\npdf = chi2.pdf(sample_space, dof)\n# plot\npyplot.plot(sample_space, pdf)\npyplot.show()\n# calculate the cdf\ncdf = chi2.cdf(sample_space, dof)\n# plot\npyplot.plot(sample_space, cdf)\npyplot.show()\n\n\n", "meta": {"hexsha": "a0f2a95576eb3f7a6687ab62e494cd8b798f3fcc", "size": 8325, "ext": "py", "lang": "Python", "max_stars_repo_path": "distribution.py", "max_stars_repo_name": "yj-danielyang/distribution", "max_stars_repo_head_hexsha": "abcef030fa9d8c09e53815930cfbe447c99a0e0c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distribution.py", "max_issues_repo_name": "yj-danielyang/distribution", "max_issues_repo_head_hexsha": "abcef030fa9d8c09e53815930cfbe447c99a0e0c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distribution.py", "max_forks_repo_name": "yj-danielyang/distribution", "max_forks_repo_head_hexsha": "abcef030fa9d8c09e53815930cfbe447c99a0e0c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8548387097, "max_line_length": 176, "alphanum_fraction": 0.6754354354, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 2760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877667047451, "lm_q2_score": 0.8887587846530937, "lm_q1q2_score": 0.862707279814135}}
{"text": "import pandas as pd\nimport numpy as np\n\n# pd.set_option('display.max_columns', None)\n# pd.set_option('display.max_colwidth', None)\n\n##############################################\n# Model\n\n# points = [(np.array([2]),4), (np.array([4]),2)]\n# d = 1\n\n# Generate data\niterationCount = 2000\ntrue_w = np.array([1,2,3,4,5,]) # Reverse-engineer to get to this vector\nd = len(true_w)\ndfColNames = [f\"w{s+1}\" for s in range(d)]\ndfColNames.append('F(w)')\npoints = []\nfor i in range(iterationCount):\n    x = np.random.randn(d)\n    y = true_w.dot(x) + np.random.randn()\n    points.append((x,y))\n\n\ndef F(w):\n    return sum((w.dot(x) - y)**2 for x, y in points) / len(points)\n\ndef dF(w):\n    return sum(2*(w.dot(x) - y) * x for x, y in points) / len(points)\n\n##############################################\n# Algorithm\n\ndef gradientDescent(F, dF, d):\n    w = np.zeros(d)\n    eta = 0.01\n\n    lst = []\n    for t in range(iterationCount):\n        l1 = []\n        value = F(w)\n        gradient = dF(w)\n        w = w - eta * gradient\n        l1.extend(w)\n        l1.append(value)\n        lst.append(l1)\n    df = pd.DataFrame(lst, columns = dfColNames)\n    df['Iteration'] = df.index\n    return df\n\nresult = gradientDescent(F, dF, d)\n\n# print(result)\n\n", "meta": {"hexsha": "e20521baef6c5d0d5ed881502daeb9552a8a963d", "size": 1229, "ext": "py", "lang": "Python", "max_stars_repo_path": "cs221_ai/lec02-c02-gradientDescentVectorized.py", "max_stars_repo_name": "chandrabsingh/learnings", "max_stars_repo_head_hexsha": "a3f507bbbf46582ce5a64991983dfc0759db0af5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cs221_ai/lec02-c02-gradientDescentVectorized.py", "max_issues_repo_name": "chandrabsingh/learnings", "max_issues_repo_head_hexsha": "a3f507bbbf46582ce5a64991983dfc0759db0af5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cs221_ai/lec02-c02-gradientDescentVectorized.py", "max_forks_repo_name": "chandrabsingh/learnings", "max_forks_repo_head_hexsha": "a3f507bbbf46582ce5a64991983dfc0759db0af5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9464285714, "max_line_length": 72, "alphanum_fraction": 0.5467860049, "include": true, "reason": "import numpy", "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426375276383, "lm_q2_score": 0.885631484383387, "lm_q1q2_score": 0.8626428269263117}}
{"text": "#Gauss-Seidel iterations\r\nimport numpy as np\r\nimport numpy.linalg as la\r\n#\r\nx = 0.0\r\ny = 0.0\r\nni = 8\r\n#\r\nA = np.array([ [3.0, 2.0],\r\n               [1.0, 4.0] ])\r\nb = np.array([7.0, 9.0])\r\n#\r\n# does not converge for this:\r\n#A = np.array([ [1.0, 2.0],\r\n#               [3.0, 4.0] ])\r\n#b = np.array([5.0, 11.0])\r\n#\r\nD = np.diag(np.diag(A))\r\nL = np.tril(A) - D\r\nU = np.triu(A) - D\r\nA2 = np.matmul(la.inv(L+D), U)\r\nnormA2 = la.norm(A2)\r\nprint('||A2||=', normA2)\r\n#\r\nprint('A=')\r\nprint(A)\r\nprint('L=')\r\nprint(L)\r\nprint('U=')\r\nprint(U)\r\nprint('D=')\r\nprint(D)\r\n#\r\nfor i in range(ni):\r\n    x = (b[0] - A[0,1]*y)/A[0,0]\r\n    y = (b[1] - A[1,0]*x)/A[1,1]\r\n    print('i=%i, x=%.2f, y=%.2f'%(i, x, y))\r\n#\r\n# this does converge, but slower...\r\n#for i in range(ni):\r\n#    x = (b[0] - A[0,1]*y0)/A[0,0]\r\n#    y = (b[1] - A[1,0]*x0)/A[1,1]\r\n#    print('i=%i, x=%.2f, y=%.2f'%(i, x, y))\r\n#    x0 = x\r\n#    y0 = y\r\nprint('done!')", "meta": {"hexsha": "b3f0b7a3ff0d2ca6b7b62fab7773607eabe3f0b3", "size": 911, "ext": "py", "lang": "Python", "max_stars_repo_path": "rt_012_gaseit.py", "max_stars_repo_name": "amiribr/General-Radiative-Transfer", "max_stars_repo_head_hexsha": "ede1963463602ce5dc0284949850f3e5f6dfc2e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rt_012_gaseit.py", "max_issues_repo_name": "amiribr/General-Radiative-Transfer", "max_issues_repo_head_hexsha": "ede1963463602ce5dc0284949850f3e5f6dfc2e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rt_012_gaseit.py", "max_forks_repo_name": "amiribr/General-Radiative-Transfer", "max_forks_repo_head_hexsha": "ede1963463602ce5dc0284949850f3e5f6dfc2e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8043478261, "max_line_length": 45, "alphanum_fraction": 0.4500548847, "include": true, "reason": "import numpy", "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426435557122, "lm_q2_score": 0.8856314692902447, "lm_q1q2_score": 0.8626428175635995}}
{"text": "import argparse\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom fits import CubicFit, CubicEval, PolynomialFit, PolynomialEval\n\nFits = [(lambda x : np.exp(-0.5*x*x), r'$\\exp{-\\frac{1}{2}x^2}$'),\n        (np.sin, r'$\\sin x$')]\n\n\ndef PlotCubic(x,y, xr, yr):\n    plt.plot(x,y, 'ro' , label=\"points\")\n    plt.plot(xr, yr, label=\"fit\")\n    plt.title('Cubic Spline')\n    plt.xlabel(\"x\")\n    plt.ylabel(\"f(x)\")\n    plt.legend()\n    plt.show()\n\ndef CubicRun(x, y):\n    xr = np.arange(x[0],x[-1]+0.1,0.1)\n    c , cn = CubicFit(x,y)\n    yr = np.array([CubicEval(x, c, xr[i]) for i in range(len(xr))])\n    PlotCubic(x, y, xr, yr)\n\ndef CubicTest(FX):\n    fX, fStr = FX[0], FX[1] \n    x = np.array([i/6 + i/12 for i in range(-12,12)])\n    CubicRun(x, fX(x))\n\ndef SplineTest(x, y):\n    CubicRun(np.array(x), np.array(y))\n\n\ndef PolynomialTest(FX):\n    fX, fStr = FX[0], FX[1] \n\n    xp = np.arange(-2,2,0.01)\n    yp = fX(xp)\n\n    x = np.arange(-2,2,0.45)\n    y = fX(x)\n    p, cond = PolynomialFit(x,y)\n    yhat = np.array([PolynomialEval(p, xp[i]) for i in range(0,len(xp))])\n\n    plt.plot(xp, yp, label=fStr)\n    plt.plot(xp, yhat,label=r'$fit$')\n    plt.legend()\n    plt.xlabel(r'$x$')\n    plt.ylabel(r'$f(x)$')\n    plt.title(fStr)\n    plt.show()\n\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description='Various Mathematical Fits')\n    parser.add_argument('-f','--fit', choices=['poly', 'cubic', 'spline'])\n    parser.add_argument('-i','--ix', type=int, default=0)\n    parser.add_argument('-x','--x', nargs='+', default=[-12,-6.1,-3, -0.5, 1.1, 4, 8,12])\n    parser.add_argument('-y','--y', nargs='+', default=[3,-14, 10, 0, 16,-2, 12, -2])\n    args = parser.parse_args()\n    ix = args.ix\n\n    if args.fit == 'poly':\n        PolynomialTest(Fits[ix])\n    elif args.fit == 'cubic':\n        CubicTest(Fits[ix])\n    elif args.fit == 'spline':\n        x, y  = [float(x) for x in args.x], [float(y) for y in args.y]\n        asset len(x) == len(y)\n        SplineTest(x, y)\n\n", "meta": {"hexsha": "2cc14c0fb79cc6dd76e219be07aafb23f97693c2", "size": 1985, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/TestFits.py", "max_stars_repo_name": "jrrpanix/reference", "max_stars_repo_head_hexsha": "2d6774ca5aefee8d215279ee552a684a1d6a3906", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-27T16:21:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T16:21:49.000Z", "max_issues_repo_path": "python/TestFits.py", "max_issues_repo_name": "jrrpanix/reference", "max_issues_repo_head_hexsha": "2d6774ca5aefee8d215279ee552a684a1d6a3906", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/TestFits.py", "max_forks_repo_name": "jrrpanix/reference", "max_forks_repo_head_hexsha": "2d6774ca5aefee8d215279ee552a684a1d6a3906", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8243243243, "max_line_length": 89, "alphanum_fraction": 0.5652392947, "include": true, "reason": "import numpy", "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737737, "lm_q2_score": 0.8976952968970956, "lm_q1q2_score": 0.8626418281649011}}
{"text": "\n# coding: utf-8\n\n# # Modelado epidemilogico del coronavirus\n# \n# ### Creditos al libro \"Learning Scientific Programming with Python is published by Cambridge University Press (ISBN: 9781107428225).\"\n# \n# \n# https://scipython.com/book/chapter-8-scipy/additional-examples/the-sir-epidemic-model/\n# \n\n# ### Tambien agradecimientos a : Análisis del Covid-19 por medio de un modelo SEIR\n# https://institucional.us.es/blogimus/2020/03/covid-19-analisis-por-medio-de-un-modelo-seir/\n# \n\n# The SIR epidemic model\n# A simple mathematical description of the spread of a disease in a population is the so-called SIR model, which divides the (fixed) population of N individuals into three \"compartments\" which may vary as a function of time, t:\n# \n# S(t) are those susceptible but not yet infected with the disease;\n# \n# I(t) is the number of infectious individuals;\n# \n# R(t) are those individuals who have recovered from the disease and now have immunity to it.\n# \n# The SIR model describes the change in the population of each of these compartments in terms of two parameters, β and γ. β describes the effective contact rate of the disease: an infected individual comes into contact with βN other individuals per unit time (of which the fraction that are susceptible to contracting the disease is S/N). γ is the mean recovery rate: that is, 1/γ is the mean period of time during which an infected individual can pass it on.\n# \n# The differential equations describing this model were first derived by Kermack and McKendrick [Proc. R. Soc. A, 115, 772 (1927)]:\n# \n# Variables : \n# \n# #### β beta Contact rate\n# \n# #### γ gamma, mean recovery rate,\n# \n# #### S(t) are those susceptible but not yet infected with the disease;\n# \n# #### I(t) is the number of infectious individuals;\n# \n# #### R(t) are those individuals who have recovered and now have immunity to it.\n# \n# dS/dt=−βSI/N,\n# \n# dI/dt=βSI/N − γI,\n# \n# dR/dt=γI.\n# \n# The following Python code integrates these equations for a disease characterised by parameters β=0.2, 1/γ=10days in a population of N=1000 (perhaps 'flu in a school). The model is started with a single infected individual on day 0: I(0)=1. The plotted curves of S(t), I(t) and R(t) are styled to look a bit nicer than Matplotlib's defaults.\n\n# In[25]:\n\n\nimport numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\n# Total population, N.\nN = 47500000\n# Initial number of infected and recovered individuals, I0 and R0.\nI0, R0 = 1, 0\n# Everyone else, S0, is susceptible to infection initially.\nS0 = N - I0 - R0\n# Contact rate, beta, and mean recovery rate, gamma, (in 1/days).\nbeta, gamma = 0.2, 1./20 \n# A grid of time points (in days)\nt = np.linspace(0, 160, 160)\n\n# The SIR model differential equations.\ndef deriv(y, t, N, beta, gamma):\n    S, I, R = y\n    dSdt = -beta * S * I / N\n    dIdt = beta * S * I / N - gamma * I\n    dRdt = gamma * I\n    return dSdt, dIdt, dRdt\n\n# Initial conditions vector\ny0 = S0, I0, R0\n# Integrate the SIR equations over the time grid, t.\nret = odeint(deriv, y0, t, args=(N, beta, gamma))\nS, I, R = ret.T\n\n# Plot the data on three separate curves for S(t), I(t) and R(t)\nfig = plt.figure(facecolor='w')\nax = fig.add_subplot(111,  axisbelow=True)\nax.plot(t, S/1000, 'b', alpha=0.5, lw=2, label='Susceptible')\nax.plot(t, I/1000, 'r', alpha=0.5, lw=2, label='Infected')\nax.plot(t, R/1000, 'g', alpha=0.5, lw=2, label='Recovered with immunity')\nax.set_xlabel('Time /days')\nax.set_ylabel('Number (1000s)')\n#ax.set_ylim(0,1.2)\nax.yaxis.set_tick_params(length=0)\nax.xaxis.set_tick_params(length=0)\nax.grid(b=True, which='major', c='w', lw=2, ls='-')\nlegend = ax.legend()\nlegend.get_frame().set_alpha(0.5)\nfor spine in ('top', 'right', 'bottom', 'left'):\n    ax.spines[spine].set_visible(False)\nplt.show()\n\n", "meta": {"hexsha": "96315725763432d015fa6ddfb429ccf3d516b32d", "size": 3773, "ext": "py", "lang": "Python", "max_stars_repo_path": "jupyter/Modelo_epidemiologico.py", "max_stars_repo_name": "cesaralba/COVID-19", "max_stars_repo_head_hexsha": "5debcc732e246ae1753aef720a6cee0a6c73e957", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-04-06T06:26:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T17:30:55.000Z", "max_issues_repo_path": "jupyter/Modelo_epidemiologico.py", "max_issues_repo_name": "cesaralba/COVID-19", "max_issues_repo_head_hexsha": "5debcc732e246ae1753aef720a6cee0a6c73e957", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-04-02T18:17:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-10T09:46:45.000Z", "max_forks_repo_path": "jupyter/Modelo_epidemiologico.py", "max_forks_repo_name": "cesaralba/COVID-19", "max_forks_repo_head_hexsha": "5debcc732e246ae1753aef720a6cee0a6c73e957", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-02T18:09:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-09T10:56:37.000Z", "avg_line_length": 38.1111111111, "max_line_length": 459, "alphanum_fraction": 0.7073946462, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920617, "lm_q2_score": 0.897695295528596, "lm_q1q2_score": 0.862641827853721}}
{"text": "import math\r\nimport numpy\r\nfrom bisect import bisect_left\r\n\r\ndef primes_up_to(upto=1000000):\r\n    primes=numpy.arange(3,upto+1,2)\r\n    isprime=numpy.ones((upto-1)/2,dtype=bool)\r\n    for factor in primes[:int(math.sqrt(upto))]:\r\n        if isprime[(factor-2)/2]: isprime[(factor*3-2)/2::factor]=0\r\n    return numpy.insert(primes[isprime],0,2)\r\n\r\ndef primesfrom2to(n):\r\n    \"\"\" Input n>=6, Returns a array of primes, 2 <= p < n \"\"\"\r\n    sieve = numpy.ones(n//3 + (n%6==2), dtype=numpy.bool)\r\n    for i in range(1,int(n**0.5)//3+1):\r\n        if sieve[i]:\r\n            k=3*i+1|1\r\n            sieve[       k*k//3     ::2*k] = False\r\n            sieve[k*(k-2*(i&1)+4)//3::2*k] = False\r\n    return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)]\r\n\r\ndef primes_starting_at(start=1000000, upto=2000000):\r\n    assert(start < upto)\r\n    p = primesfrom2to(upto)\r\n    return p[bisect_left(p, start):]\r\n\r\nif __name__ == \"__main__\":\r\n    #print(primes_starting_at(1000000, 1100000))\r\n    print(primesfrom2to(2000000))", "meta": {"hexsha": "e8e5f0eafb634bfe1b5ce9eea81a31fee6db53d5", "size": 1006, "ext": "py", "lang": "Python", "max_stars_repo_path": "common/primes.py", "max_stars_repo_name": "lucasperin/elgamal_sequences_experiments", "max_stars_repo_head_hexsha": "1df5c09af612dbc62a84041b366fecbbbde443e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "common/primes.py", "max_issues_repo_name": "lucasperin/elgamal_sequences_experiments", "max_issues_repo_head_hexsha": "1df5c09af612dbc62a84041b366fecbbbde443e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common/primes.py", "max_forks_repo_name": "lucasperin/elgamal_sequences_experiments", "max_forks_repo_head_hexsha": "1df5c09af612dbc62a84041b366fecbbbde443e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6896551724, "max_line_length": 68, "alphanum_fraction": 0.5954274354, "include": true, "reason": "import numpy", "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737737, "lm_q2_score": 0.8976952907388474, "lm_q1q2_score": 0.8626418222471219}}
{"text": "from math import ceil, sqrt\r\n\r\nfrom scipy.special import binom\r\nimport scipy.sparse as sp\r\n\r\ndef veclen_to_matsize(L):\r\n  n = (sqrt(1+8*L) - 1)/2\r\n  assert n == int(n)\r\n  return int(n)\r\n\r\ndef matsize_to_veclen(n):\r\n  return n*(n+1)//2\r\n\r\ndef k_to_ij(k, L):\r\n  '''\r\n  Given a gram matrix Q represented by a vector\r\n    V = [Q_00, ... Q_0n, Q_11, ..., Q_1n, Q22, ..., ] of length L,\r\n    for given k, compute i,j s.t. Q_ij = V[k]\r\n  '''\r\n  if (k >= L):\r\n    raise IndexError(\"Index out of range\")\r\n  # inverse formula for arithmetic series\r\n  n = (sqrt(1+8*L) - 1)/2\r\n  # get first index\r\n  i = int(ceil( (2*n+1)/2 - sqrt( ((2*n+1)/2)**2 -2 * (k+1)  ) ) - 1)\r\n  # second index\r\n  k1 = (2*n+1-i)*i/2 - 1\r\n  j = int(i + k - k1 - 1)\r\n  return i,j\r\n\r\ndef ij_to_k(i,j,L):\r\n  ''' \r\n  Given a symmetric matrix Q represented by a vector\r\n  V = [Q_00, ... Q_0n, Q_11, ..., Q_1n] of length L,\r\n  for given i,j , compute k s.t. Q_ij = V(k)\r\n  '''\r\n  n = (sqrt(1+8*L) - 1)/2\r\n  i_at1 = min(i,j)+1\r\n  j_at1 = max(j,i)+1\r\n  k_at1 = int((n + n-i_at1)*(i_at1-1)/2 + j_at1)\r\n  return k_at1 - 1\r\n\r\ndef vec_to_mat(vec):\r\n  '''convert vector representation of gram matrix to gram matrix'''\r\n  L = len(vec)\r\n  n = int((sqrt(1+8*L) - 1)/2)\r\n  return [[vec[ij_to_k(i,j,L)] for i in range(n) ] for j in range(n)]\r\n\r\ndef mat_to_vec(mat):\r\n  '''retrieve vector representation of gram matrix'''\r\n  n = mat.shape[0]\r\n  L = int(n*(n+1)/2)\r\n  ret = [0. for i in range(L)]\r\n  for k in range(L):\r\n    i,j = k_to_ij(k, L)\r\n    ret[k] = (mat[i,j] + mat[j,i]) / 2\r\n  return ret\r\n\r\ndef multinomial(params):\r\n  if len(params) == 1:\r\n    return 1\r\n  return binom(sum(params), params[-1]) * multinomial(params[:-1])\r\n\r\ndef double_factorial(n):\r\n  ret = 1\r\n  for i in range(n, 0, -2):\r\n    ret *= i\r\n  return ret\r\n\r\ndef speye(n, pos=0, tot=None):\r\n  '''\r\n  return a sparse identity matrix [ 0  I  0]\r\n  with size n x tot and where the identity matrix\r\n  starts at pos\r\n  '''\r\n  if tot is None:\r\n    tot = n\r\n  return sp.coo_matrix( ([1.] * n, (range(n), range(pos, pos+n))), (n,tot) )\r\n\r\ndef spzeros(n, m):\r\n  return sp.coo_matrix( (n,m) )\r\n", "meta": {"hexsha": "24993c9b0c9d5db80831a80ed488d3e8d56b40c0", "size": 2099, "ext": "py", "lang": "Python", "max_stars_repo_path": "posipoly/utils.py", "max_stars_repo_name": "pettni/posipoly", "max_stars_repo_head_hexsha": "a40afd093567f62979bba73eae61a6416009bedc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-09T02:07:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T02:07:44.000Z", "max_issues_repo_path": "posipoly/utils.py", "max_issues_repo_name": "pettni/posipoly", "max_issues_repo_head_hexsha": "a40afd093567f62979bba73eae61a6416009bedc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-24T18:21:44.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-24T18:29:50.000Z", "max_forks_repo_path": "posipoly/utils.py", "max_forks_repo_name": "pettni/posipoly", "max_forks_repo_head_hexsha": "a40afd093567f62979bba73eae61a6416009bedc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-28T17:18:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T17:18:59.000Z", "avg_line_length": 25.5975609756, "max_line_length": 77, "alphanum_fraction": 0.5607432111, "include": true, "reason": "import scipy,from scipy", "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951711746926, "lm_q2_score": 0.897695283896349, "lm_q1q2_score": 0.8626418196873392}}
{"text": "\"\"\"\r\nChecks if a system of forces is in static equilibrium.\r\n\"\"\"\r\nfrom __future__ import annotations\r\n\r\nfrom numpy import array, cos, cross, ndarray, radians, sin\r\n\r\n\r\ndef polar_force(\r\n    magnitude: float, angle: float, radian_mode: bool = False\r\n) -> list[float]:\r\n    \"\"\"\r\n    Resolves force along rectangular components.\r\n    (force, angle) => (force_x, force_y)\r\n    >>> import math\r\n    >>> force = polar_force(10, 45)\r\n    >>> math.isclose(force[0], 7.071067811865477)\r\n    True\r\n    >>> math.isclose(force[1], 7.0710678118654755)\r\n    True\r\n    >>> polar_force(10, 3.14, radian_mode=True)\r\n    [-9.999987317275396, 0.01592652916486828]\r\n    \"\"\"\r\n    if radian_mode:\r\n        return [magnitude * cos(angle), magnitude * sin(angle)]\r\n    return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))]\r\n\r\n\r\ndef in_static_equilibrium(\r\n    forces: ndarray, location: ndarray, eps: float = 10**-1\r\n) -> bool:\r\n    \"\"\"\r\n    Check if a system is in equilibrium.\r\n    It takes two numpy.array objects.\r\n    forces ==>  [\r\n                        [force1_x, force1_y],\r\n                        [force2_x, force2_y],\r\n                        ....]\r\n    location ==>  [\r\n                        [x1, y1],\r\n                        [x2, y2],\r\n                        ....]\r\n    >>> force = array([[1, 1], [-1, 2]])\r\n    >>> location = array([[1, 0], [10, 0]])\r\n    >>> in_static_equilibrium(force, location)\r\n    False\r\n    \"\"\"\r\n    # summation of moments is zero\r\n    moments: ndarray = cross(location, forces)\r\n    sum_moments: float = sum(moments)\r\n    return abs(sum_moments) < eps\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    # Test to check if it works\r\n    forces = array(\r\n        [\r\n            polar_force(718.4, 180 - 30),\r\n            polar_force(879.54, 45),\r\n            polar_force(100, -90),\r\n        ]\r\n    )\r\n\r\n    location = array([[0, 0], [0, 0], [0, 0]])\r\n\r\n    assert in_static_equilibrium(forces, location)\r\n\r\n    # Problem 1 in image_data/2D_problems.jpg\r\n    forces = array(\r\n        [\r\n            polar_force(30 * 9.81, 15),\r\n            polar_force(215, 180 - 45),\r\n            polar_force(264, 90 - 30),\r\n        ]\r\n    )\r\n\r\n    location = array([[0, 0], [0, 0], [0, 0]])\r\n\r\n    assert in_static_equilibrium(forces, location)\r\n\r\n    # Problem in image_data/2D_problems_1.jpg\r\n    forces = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]])\r\n\r\n    location = array([[0, 0], [6, 0], [10, 0], [12, 0]])\r\n\r\n    assert in_static_equilibrium(forces, location)\r\n\r\n    import doctest\r\n\r\n    doctest.testmod()\r\n", "meta": {"hexsha": "ed0d1eb98cf37c06edff253b796b5edf29ab7f71", "size": 2536, "ext": "py", "lang": "Python", "max_stars_repo_path": "arithmetic_analysis/in_static_equilibrium.py", "max_stars_repo_name": "Leoriem-code/Python", "max_stars_repo_head_hexsha": "1400cb86ff7c656087963db41844e0ca503ae6d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-03T10:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T10:41:17.000Z", "max_issues_repo_path": "arithmetic_analysis/in_static_equilibrium.py", "max_issues_repo_name": "Leoriem-code/Python", "max_issues_repo_head_hexsha": "1400cb86ff7c656087963db41844e0ca503ae6d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arithmetic_analysis/in_static_equilibrium.py", "max_forks_repo_name": "Leoriem-code/Python", "max_forks_repo_head_hexsha": "1400cb86ff7c656087963db41844e0ca503ae6d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-30T11:58:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-30T11:58:09.000Z", "avg_line_length": 27.8681318681, "max_line_length": 78, "alphanum_fraction": 0.5374605678, "include": true, "reason": "from numpy", "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951703918909, "lm_q2_score": 0.8976952859490985, "lm_q1q2_score": 0.8626418146327586}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import linalg as la\n\ndef PCA(dat, center=False, percentage=0.8):\n    M, N = dat.shape\n    if center:\n        mu = np.mean(dat,0)\n        dat -= mu\n\n    U, L, Vh = la.svd(dat, full_matrices=False)\n    \n    V = Vh.T.conjugate()\n    SIGMA = np.diag(L)\n    X = U.dot(SIGMA)\n    Lam = L**2\n\n    normalized_eigenvalues = Lam/Lam.sum(dtype=float)\n    csum = [normalized_eigenvalues[:i+1].sum() for i in xrange(N)]\n    n_components = [x < percentage for x in csum].index(False) + 1\n\n    return (normalized_eigenvalues, \n            V[:,0:n_components], \n            SIGMA[0:n_components,0:n_components], \n            X[:,0:n_components])\n\ndef scree(normalized_eigenvalues):\n    fig = plt.figure()\n    plt.plot(normalized_eigenvalues,'b-', normalized_eigenvalues, 'bo')\n    plt.xlabel(\"Principal Components\")\n    plt.ylabel(\"Percentage of Variance\")\n    return fig\n    \n", "meta": {"hexsha": "4c8719fed243367528ac749c01c04b3271e74999", "size": 923, "ext": "py", "lang": "Python", "max_stars_repo_path": "Algorithms/PCA/solutions.py", "max_stars_repo_name": "lcbendall/numerical_computing", "max_stars_repo_head_hexsha": "565cde92525ea44c55abe933c6419c1543f9800b", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Algorithms/PCA/solutions.py", "max_issues_repo_name": "lcbendall/numerical_computing", "max_issues_repo_head_hexsha": "565cde92525ea44c55abe933c6419c1543f9800b", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Algorithms/PCA/solutions.py", "max_forks_repo_name": "lcbendall/numerical_computing", "max_forks_repo_head_hexsha": "565cde92525ea44c55abe933c6419c1543f9800b", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-08T01:19:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T01:19:23.000Z", "avg_line_length": 27.1470588235, "max_line_length": 71, "alphanum_fraction": 0.630552546, "include": true, "reason": "import numpy,from scipy", "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.979354072876341, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.8626122118241202}}
{"text": "import numpy as np\n'''\nベクトル[の|][演算|計算]を[する|行う]\n行列[の|][演算|計算]を[する|行う]\nnumpyを[使う|入れる|インポートする]\n'''\n\nnp.array(l)\n'''\n@type(l,リスト)から配列を[作る|作成する|作成]\n'''\nnp.array(t)\n'''\n@type(t,タプル)から配列を作る\n'''\n\na.shape()\n'''\n@type(a,配列)の[形状|形]を調べる\n'''\n\na.dtype()\n'''\n@type(a,配列)の[データ型|型]を調べる\n'''\n\nnp.ndim(x)\n'''\n@type(x,配列)の[次元数|次元の数]を調べる\n'''\n\nnp.arange(10)\n'''\n0から9までの配列を作る\n'''\n\nx.reshape(3,3)\n'''\n@type(x,配列)を3×3の多次元配列に変形する\n'''\n\nnp.concatenate([a,b])\n'''\n@type(a,配列)と@type(b,配列)を[列方向|縦方向]に連結する\n'''\n\nnp.concatenate([a,b], axis=0)\n'''\n@type(a,配列)と@type(b,配列)を[列方向|縦方向]に連結する\n'''\n\nnp.concatenate([a,b], axis=1)\n'''\n@type(a,配列)と@type(b,配列)を[行方向|横方向]に連結する\n'''\n\nnp.sum(x)\n'''\n@type(x,配列)の[合計値|合計]を調べる\n'''\n\nnp.sum(x, axis=0)\n'''\n@type(x,配列)の列ごとの[合計値|合計]を調べる\n'''\n\nnp.sum(x, axis=1)\n'''\n@type(x,配列)の行ごとの[合計値|合計]を調べる\n'''\n\nnp.mean(x)\n'''\n@type(x,配列)の[平均値|平均]を調べる\n'''\n\nnp.mean(x, axis=0)\n'''\n@type(x,配列)の列ごとの[平均値|平均]を調べる\n'''\n\nnp.mean(x, axis=1)\n'''\n@type(x,配列)の行ごとの[平均値|平均]を調べる\n'''\n\nnp.min(x)\n'''\n@type(x,配列)の[最小値|最小]を調べる\n'''\n\nnp.min(x, axis=0)\n'''\n@type(x,配列)の列ごとの[最小値|最小]を調べる\n'''\n\nnp.min(x, axis=1)\n'''\n@type(x,配列)の行ごとの[最小値|最小]を調べる\n'''\n\nnp.max(x)\n'''\n@type(x,配列)の[最大値|最大]を調べる\n'''\n\nnp.max(x, axis=0)\n'''\n@type(x,配列)の列ごとの[最大値|最大]を調べる\n'''\n\nnp.max(x, axis=1)\n'''\n@type(x,配列)の行ごとの[最大値|最大]を調べる\n'''\n\nnp.std(x)\n'''\n@type(x,配列)の標準偏差を調べる\n'''\n\nnp.std(x, axis=0)\n'''\n@type(x,配列)の列ごとの標準偏差を調べる\n'''\n\nnp.std(x, axis=1)\n'''\n@type(x,配列)の行ごとの標準偏差を調べる\n'''\n\nnp.var(x)\n'''\n@type(x,配列)の分散を調べる\n'''\n\nnp.var(x, axis=0)\n'''\n@type(x,配列)の列ごとの分散を調べる\n'''\n\nnp.var(x, axis=1)\n'''\n@type(x,配列)の行ごとの分散を調べる\n'''\n\nnp.eye(3)\n'''\n3×3の単位行列を作る\n'''\n\nnp.identity(3)\n'''\n3×3の単位行列を作る\n'''\n\nnp.empty(5)\n'''\n要素数5の[空配列|空の配列]を作る\n'''\n\nnp.empty((2, 3))\n'''\n2×3の[空配列|空の配列]を作る\n'''\n\nnp.empty_like(x)\n'''\n@type(x,配列)と同じ大きさの[空配列|空の配列]を作る\n'''\n\nnp.gcd(a,b)\n'''\n@type(a,配列)と@type(b,配列)の要素ごとの最大公約数を調べる\n'''\n\nnp.lcm(a,b)\n'''\n@type(a,配列)と@type(b,配列)の要素ごとの最小公倍数を調べる\n'''\n\nnp.unique(x)\n'''\n@type(x,配列)から重複を除いた配列を作る\n@type(x,配列)のユニークな要素を調べる\n'''\n\nu, counts = np.unique(a, return_counts=True)\n'''\n@type(x,配列)のユニークな要素とその個数を調べる\n'''\n\nu, indices = np.unique(x, return_index=True)\n'''\n@type(x,配列)のユニークな要素とその位置を調べる\n'''\n\nnp.cumsum(x)\n'''\n@type(x,配列)の累積和を調べる\n'''\n\nnp.cumprod(x)\n'''\n@type(x,配列)の累積積を調べる\n'''\n\nx.flatten()\n'''\n@type(x,配列)を[一次元にする|一次元化|平坦化]\n'''\n", "meta": {"hexsha": "8fe428fc61596e9c383714a62a90a4370efd18ff", "size": 2244, "ext": "py", "lang": "Python", "max_stars_repo_path": "new_corpus/_numpy.py", "max_stars_repo_name": "y-akinobu/multiese", "max_stars_repo_head_hexsha": "e28e6424b9714c5f145f438c8502c4194b70fe25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "new_corpus/_numpy.py", "max_issues_repo_name": "y-akinobu/multiese", "max_issues_repo_head_hexsha": "e28e6424b9714c5f145f438c8502c4194b70fe25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "new_corpus/_numpy.py", "max_forks_repo_name": "y-akinobu/multiese", "max_forks_repo_head_hexsha": "e28e6424b9714c5f145f438c8502c4194b70fe25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 10.5849056604, "max_line_length": 44, "alphanum_fraction": 0.5864527629, "include": true, "reason": "import numpy", "num_tokens": 1436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9793540734789343, "lm_q2_score": 0.8807970748488297, "lm_q1q2_score": 0.8626122031615312}}
{"text": "#!/usr/bin/env python\n#coding: utf-8\n\nimport numpy as np\n\ndef up(volatility, duration) :\n    u = np.exp(volatility * np.sqrt(duration))\n    return u\n\ndef down(volatility, duration) :\n    d = np.exp(-volatility * np.sqrt(duration))\n    return d\n\ndef probability_u(volatility, duration, riskfree) :\n    u = up(volatility, duration)\n    d = down(volatility, duration)\n    probability_u = (np.exp(riskfree * duration) - d) / (u - d)\n    return probability_u\n\ndef probability_d(volatility, duration, riskfree) :\n    u = up(volatility, duration)\n    d = down(volatility, duration)\n    probability_d = (np.exp(-riskfree * duration) - d) / (u - d)\n    return probability_d\n\ndef price(option, spot, riskfree, dividend, volatility, steps=4) :\n    dt = option.days_to_expiry() / (365 * steps)\n\n    u = up(volatility, dt)\n    d = down(volatility, dt)\n\n    p = probability_u(volatility, dt, riskfree)\n    q = probability_d(volatility, dt, riskfree)\n\n    ul_price = np.zeros([steps + 1, steps + 1])\n    ul_price[0, 0] = spot\n    for i in range(1, steps + 1) :\n        ul_price[i, 0] = ul_price[i - 1, 0] * u\n        for j in range(1, i + 1) :\n            ul_price[i, j] = ul_price[i - 1, j - 1] * d\n\n    option_price = np.zeros([steps + 1, steps + 1])\n    for j in range(steps + 1) :\n        if option.type == \"call\" :\n            option_price[steps, j] = max(0, ul_price[steps, j] - option.strike)\n        elif option.type == \"put\" :\n            option_price[steps, j] = max(0, option.strike - ul_price[steps, j])\n\n    for i in range(steps)[::-1] :\n        for j in range(i + 1) :\n            if option.style == \"EU\" :\n                option_price[i, j] = np.exp(-riskfree * dt) * (p * option_price[i + 1, j] + q * option_price[i + 1, j + 1])\n            elif option.style == \"US\" :\n                if option.type == \"call\" :\n                    option_price[i, j] = max(ul_price[i, j] - option.strike, np.exp(-riskfree * dt) * (p * option_price[i + 1, j] + q * option_price[i + 1, j + 1])) \n                elif option.type == \"put\" :\n                    option_price[i, j] = max(option.strike - ul_price[i, j], np.exp(-riskfree * dt) * (p * option_price[i + 1, j] + q * option_price[i + 1, j + 1]))\n\n    return option_price[0, 0]\n\ndef main() :\n    pass\n\nif __name__ == \"__main__\" :\n    main()\n", "meta": {"hexsha": "7edeae254c3fb5ccea0a3090480efb44945e860a", "size": 2282, "ext": "py", "lang": "Python", "max_stars_repo_path": "option-valuation/models/binomial.py", "max_stars_repo_name": "romaincaraes/option-valuation-python", "max_stars_repo_head_hexsha": "1d3fc0fb4cceff6855a6fcb3ac9bb3c59fffa214", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-27T06:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-30T22:34:56.000Z", "max_issues_repo_path": "option-valuation/models/binomial.py", "max_issues_repo_name": "romaincaraes/option-valuation-python", "max_issues_repo_head_hexsha": "1d3fc0fb4cceff6855a6fcb3ac9bb3c59fffa214", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "option-valuation/models/binomial.py", "max_forks_repo_name": "romaincaraes/option-valuation-python", "max_forks_repo_head_hexsha": "1d3fc0fb4cceff6855a6fcb3ac9bb3c59fffa214", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5757575758, "max_line_length": 165, "alphanum_fraction": 0.5718667835, "include": true, "reason": "import numpy", "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9793540716711546, "lm_q2_score": 0.8807970764133561, "lm_q1q2_score": 0.8626122031014695}}
{"text": "'''\nStarting in the top left corner of a 2×2 grid, and only being able to move to\nthe right and down, there are exactly 6 routes to the bottom right corner.\n\n\nHow many such routes are there through a 20×20 grid?\n'''\n\nimport numpy as np\nfrom itertools import product\n\n# brute force\ndef lattice_paths_brute_force(n):\n\n    paths = [p for p in product([(0,1),(1,0)], repeat=2*n) if any(np.sum(p, axis=0)==[n,n])]\n\n    return len(paths)\n\nlattice_paths_brute_force(3)\n\n\nfrom math import factorial\n\ndef lattice_paths(n):\n    # this can be thought of like pascal's triangle. \n    # trying to get middle number of row 2n\n    \n    return factorial(n*2) / (factorial(n*2 - n) * factorial(n))\n\nlattice_paths(20)\n", "meta": {"hexsha": "ca1f2993e731d68caf846373b06d0df252517661", "size": 700, "ext": "py", "lang": "Python", "max_stars_repo_path": "project-euler/python/15_lattice-paths.py", "max_stars_repo_name": "jydiw/assorted-algorithms", "max_stars_repo_head_hexsha": "7af26520055104dcaf1ff21d94ece27d81c97918", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project-euler/python/15_lattice-paths.py", "max_issues_repo_name": "jydiw/assorted-algorithms", "max_issues_repo_head_hexsha": "7af26520055104dcaf1ff21d94ece27d81c97918", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project-euler/python/15_lattice-paths.py", "max_forks_repo_name": "jydiw/assorted-algorithms", "max_forks_repo_head_hexsha": "7af26520055104dcaf1ff21d94ece27d81c97918", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5806451613, "max_line_length": 92, "alphanum_fraction": 0.6985714286, "include": true, "reason": "import numpy", "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9688561694652216, "lm_q2_score": 0.8902942304882371, "lm_q1q2_score": 0.8625670578478205}}
{"text": "# IMPORTS\nimport numpy as np\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\nimport matplotlib.style as style\nfrom IPython.core.display import HTML\n\n# PLOTTING CONFIG\n%matplotlib inline\nstyle.use('fivethirtyeight')\nplt.rcParams[\"figure.figsize\"] = (14, 7)\nHTML(\"\"\"\n<style>\n.output_png {\n    display: table-cell;\n    text-align: center;\n    vertical-align: center;\n}\n</style>\n\"\"\")\nplt.figure(dpi=100)\n\n# PDF MU = 0\nplt.plot(np.linspace(-4, 4, 100), \n         stats.norm.pdf(np.linspace(-4, 4, 100)),\n        )\nplt.fill_between(np.linspace(-4, 4, 100),\n                 stats.norm.pdf(np.linspace(-4, 4, 100)),\n                 alpha=.15,\n                )\n\n# PDF MU = 2\nplt.plot(np.linspace(-4, 4, 100), \n         stats.norm.pdf(np.linspace(-4, 4, 100), loc=2),\n        )\nplt.fill_between(np.linspace(-4, 4, 100),\n                 stats.norm.pdf(np.linspace(-4, 4, 100),loc=2),\n                 alpha=.15,\n                )\n\n# PDF MU = -2\nplt.plot(np.linspace(-4, 4, 100), \n         stats.norm.pdf(np.linspace(-4, 4, 100), loc=-2),\n        )\nplt.fill_between(np.linspace(-4, 4, 100),\n                 stats.norm.pdf(np.linspace(-4, 4, 100),loc=-2),\n                 alpha=.15,\n                )\n\n# LEGEND\nplt.text(x=-1, y=.35, s=\"$ \\mu = 0$\", rotation=65, alpha=.75, weight=\"bold\", color=\"#008fd5\")\nplt.text(x=1, y=.35, s=\"$ \\mu = 2$\", rotation=65, alpha=.75, weight=\"bold\", color=\"#fc4f30\")\nplt.text(x=-3, y=.35, s=\"$ \\mu = -2$\", rotation=65, alpha=.75, weight=\"bold\", color=\"#e5ae38\")\n\n\n# TICKS\nplt.tick_params(axis = 'both', which = 'major', labelsize = 18)\nplt.axhline(y = 0, color = 'black', linewidth = 1.3, alpha = .7)\n\n# TITLE, SUBTITLE & FOOTER\nplt.text(x = -5, y = 0.51, s = \"Normal Distribution - $ \\mu $\",\n               fontsize = 26, weight = 'bold', alpha = .75)\nplt.text(x = -5, y = 0.45, \n         s = 'Depicted below are three normally distributed random variables with varying $ \\mu $. As one can easily\\nsee the parameter $\\mu$ shifts the distribution along the x-axis.',\n         fontsize = 19, alpha = .85)\nplt.text(x = -5,y = -0.075,\n         s = '   ©Joshua Görner                                                                                                                                                 github.com/jgoerner   ',\n         fontsize = 14, color = '#f0f0f0', backgroundcolor = 'grey');", "meta": {"hexsha": "7350362304f1ad40f3bb5f1ca4a3d14387b83eda", "size": 2338, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/normal/02_mu.py", "max_stars_repo_name": "jgoerner/distribution-cheatsheet", "max_stars_repo_head_hexsha": "b96887fb3f53abc315ce1527a73829843bad41b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2018-01-02T15:28:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T22:43:44.000Z", "max_issues_repo_path": "src/normal/02_mu.py", "max_issues_repo_name": "Kengstar/distribution-cheatsheet", "max_issues_repo_head_hexsha": "b96887fb3f53abc315ce1527a73829843bad41b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-01-04T10:23:47.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-04T18:26:48.000Z", "max_forks_repo_path": "src/normal/02_mu.py", "max_forks_repo_name": "Kengstar/distribution-cheatsheet", "max_forks_repo_head_hexsha": "b96887fb3f53abc315ce1527a73829843bad41b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2018-01-10T17:31:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T10:39:19.000Z", "avg_line_length": 34.3823529412, "max_line_length": 200, "alphanum_fraction": 0.5380667237, "include": true, "reason": "import numpy,import scipy", "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.9111797069968974, "lm_q1q2_score": 0.8625196807154468}}
{"text": "#!/usr/bin/python3\nimport numpy as np\n\ndef log(x_value):\n  x = x_value-1\n  x2 = x*x\n  a0 = -np.log(2); a1 = 2;a2 = -1;a3 = 2/3.;a4 = -0.5;\n  T0 = 1; T1 = x; T2 = 2*x2 - 1; T3 = 4*x2*x - 3*x; T4 = 8*x2*x2 - 8*x2 + 1;\n  return a0*T0 + a1*T1 + a2*T2 + a3*T3 + a4*T4\n\ndef log2(x_value):\n  if x_value < 2:\n    t = x_value-1;\n    t2 = t*t\n    t4 = t2*t2\n    t6 = t4*t2\n    return  t - 0.5*t2 + 1./3*t2*t - 0.25*t4 + 0.2*t4*t - 1./6*t6\n  elif x_value < 6:\n    t = x_value-3\n    t2 = t*t\n    t4 = t2*t2\n    t6 = t4*t2\n    return  np.log(3) + 1./3*t - 1./18*t2 + 1./81*t2*t - 1/324.*t4 + 1./1215*t4*t - 1./4374*t6\n  else:\n    t = x_value-9\n    t2 = t*t\n    t4 = t2*t2\n    t6 = t4*t2\n    return  np.log(9) + 1./9*t - 1./162*t2 + 1./2187*t2*t - 1/26244.*t4 + 1./295245*t4*t - 1./3188646*t6\n\nimport matplotlib.pyplot as plt\nfig = plt.figure()\nx_list = np.linspace(0.2, 20, 200)\n\nplt.plot(x_list, np.log(x_list), label=\"exact\")\n#plt.plot(x_list, [log(x) for x in x_list], label=\"Chebyshev\")\nplt.plot(x_list, [log2(x) for x in x_list], label=\"Taylor\")\nplt.legend()\n\n# define global plotting parameters\nplt.rcParams.update({'font.size': 16})\nplt.rcParams['lines.linewidth'] = 3\n\nfig = plt.figure()\nplt.plot(x_list, [(np.log(x)-log2(x))/np.log(x) for x in x_list])\nplt.grid()\nplt.savefig(\"apxlog.pdf\")\nplt.show()\n\nmax_rel_error = 0\nlocation = 0\nfor x in np.linspace(0.2,20,200):\n  rel_error =  (np.log(x)-log2(x))/np.log(x)\n  print(\"{}, {}, {}, error: {}\".format(x, np.log(x), log(x), rel_error))\n  old_rel_error = max_rel_error\n  max_rel_error = max(max_rel_error, rel_error)\n  if old_rel_error != max_rel_error:\n    location = x\n  \nprint(\"maximum relative error: {} at {}\".format(max_rel_error, location))\n\nplt.show()\n", "meta": {"hexsha": "aadfaa60c34e92f2aedc2195241cf19b58dc492b", "size": 1704, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/sympy/approximate_log_function.py", "max_stars_repo_name": "maierbn/opendihu", "max_stars_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2018-11-25T19:29:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T04:46:22.000Z", "max_issues_repo_path": "doc/sympy/approximate_log_function.py", "max_issues_repo_name": "maierbn/opendihu", "max_issues_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-12T15:15:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-29T15:29:24.000Z", "max_forks_repo_path": "doc/sympy/approximate_log_function.py", "max_forks_repo_name": "maierbn/opendihu", "max_forks_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-10-17T12:18:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T13:24:20.000Z", "avg_line_length": 27.0476190476, "max_line_length": 104, "alphanum_fraction": 0.5933098592, "include": true, "reason": "import numpy", "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966656805269, "lm_q2_score": 0.9111797106148062, "lm_q1q2_score": 0.8625196759037229}}
{"text": "from abc import ABC,  abstractmethod\nfrom math import sqrt, exp\nimport numpy as np\ndef unison_shuffled_copies(a, b, random = None):\n\tif random is None:\n\t\trandom = np.random\n\tassert len(a) == len(b)\n\tp = random.permutation(len(a))\n\treturn a[p], b[p]\n\n\nclass BaseActivation(ABC):\n\t\"\"\"Base class for all activation functions\"\"\"\n\t@property\n\t@abstractmethod\n\tdef name(self):\n\t\traise NotImplementedError\n\n\t@abstractmethod\n\tdef function(self, x):\n\t\tpass\n\n\t@abstractmethod\n\tdef derivative(self, x):\n\t\tpass\n\n\nclass Identity(BaseActivation):\n\t\"\"\" Identity activation for testing\"\"\"\n\tname = \"identity\"\n\n\tdef function(self, x):\n\t\treturn x\n\n\tdef derivative(self, x):\n\t\treturn 1\n\nclass Sigmoid(BaseActivation):\n\t\"\"\" Identity activation for testing\"\"\"\n\tname = \"sigmoid\"\n\n\tdef function(self, x):\n\t\treturn 1 / (1 + exp(-x)) \n\n\tdef derivative(self, x):\n\t\treturn self.function(x)*(1-self.function(x)) \n\n\ndef softmax(X, theta = 1.0, axis = None):\n\t\"\"\"\n\tCompute the softmax of each element along an axis of X.\n\n\tParameters\n\t----------\n\tX: ND-Array. Probably should be floats. \n\ttheta (optional): float parameter, used as a multiplier\n\t\tprior to exponentiation. Default = 1.0\n\taxis (optional): axis to compute values along. Default is the \n\t\tfirst non-singleton axis.\n\n\tReturns an array the same size as X. The result will sum to 1\n\talong the specified axis.\n\t\"\"\"\n\n\t# make X at least 2d\n\ty = np.atleast_2d(X)\n\n\t# find axis\n\tif axis is None:\n\t\taxis = next(j[0] for j in enumerate(y.shape) if j[1] > 1)\n\n\t# multiply y against the theta parameter, \n\ty = y * float(theta)\n\n\t# subtract the max for numerical stability\n\ty = y - np.expand_dims(np.max(y, axis = axis), axis)\n\t\n\t# exponentiate y\n\ty = np.exp(y)\n\n\t# take the sum along the specified axis\n\tax_sum = np.expand_dims(np.sum(y, axis = axis), axis)\n\n\t# finally: divide elementwise\n\tp = y / ax_sum\n\n\t# flatten if X was 1D\n\tif len(X.shape) == 1: p = p.flatten()\n\n\treturn p", "meta": {"hexsha": "b60918f57bd9dd5ea74a06cbd1f7123da2257f03", "size": 1898, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/helpers.py", "max_stars_repo_name": "egdenis/MLP", "max_stars_repo_head_hexsha": "a1ea247bdb3e77f1534b00ba5d4396da0f3bb261", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/helpers.py", "max_issues_repo_name": "egdenis/MLP", "max_issues_repo_head_hexsha": "a1ea247bdb3e77f1534b00ba5d4396da0f3bb261", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/helpers.py", "max_forks_repo_name": "egdenis/MLP", "max_forks_repo_head_hexsha": "a1ea247bdb3e77f1534b00ba5d4396da0f3bb261", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0888888889, "max_line_length": 63, "alphanum_fraction": 0.6849315068, "include": true, "reason": "import numpy", "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.946596665680527, "lm_q2_score": 0.9111797082028671, "lm_q1q2_score": 0.8625196736205896}}
{"text": "# Do not import any additional 3rd party external libraries as they will not\n# be available to AutoLab and are not needed (or allowed)\n\nimport numpy as np\nimport os\n\n\nclass Activation(object):\n    \"\"\"\n    Interface for activation functions (non-linearities).\n\n    In all implementations, the state attribute must contain the result,\n    i.e. the output of forward (it will be tested).\n    \"\"\"\n\n    # No additional work is needed for this class, as it acts like an\n    # abstract base class for the others\n\n    # Note that these activation functions are scalar operations. I.e, they\n    # shouldn't change the shape of the input.\n\n    def __init__(self):\n        self.state = None\n\n    def __call__(self, x):\n        return self.forward(x)\n\n    def forward(self, x):\n        raise NotImplemented\n\n    def derivative(self):\n        raise NotImplemented\n\n\nclass Identity(Activation):\n    \"\"\"\n    Identity function (already implemented).\n    \"\"\"\n\n    # This class is a gimme as it is already implemented for you as an example\n\n    def __init__(self):\n        super(Identity, self).__init__()\n\n    def forward(self, x):\n        self.state = x\n        return x\n\n    def derivative(self):\n        return 1.0\n\n\nclass Sigmoid(Activation):\n    \"\"\"\n    Sigmoid non-linearity\n    \"\"\"\n\n    # Remember do not change the function signatures as those are needed\n    # to stay the same for AutoLab.\n\n    def __init__(self):\n        super(Sigmoid, self).__init__()\n\n    def forward(self, x):\n        # DONE:\n        # Might we need to store something before returning?\n        # self.state = ???\n        # Hint: You can use np.exp() function\n        # return self.state\n        self.state = x\n        self.state[x>=0] = 1.0 / (1.0 + np.exp(- self.state[x>=0]))\n        self.state[x<0] = np.exp(self.state[x<0]) / ( np.exp(self.state[x<0]) + 1.0)\n        return self.state\n\n    def derivative(self):\n        # DONE:\n        # Maybe something we need later in here...\n        # return ???\n        # Maybe something we need later in here...\n        return self.state * (1.0 - self.state)\n\n\nclass Tanh(Activation):\n    \"\"\"\n    Tanh non-linearity\n    \"\"\"\n    def __init__(self):\n        super(Tanh, self).__init__()\n\n    def forward(self, x):\n        # DONE:\n        # self.state = ???\n        # Hint: You can use np.exp() function\n        # return self.state\n        self.state = (1 - np.exp(-2 * x)) / (1 + np.exp(-2 * x))\n        return self.state\n\n    def derivative(self):\n        # DONE:\n        # return ???\n        return (1 - self.state**2)\n\n\nclass ReLU(Activation):\n    \"\"\"\n    ReLU non-linearity\n    \"\"\"\n    def __init__(self):\n        super(ReLU, self).__init__()\n\n    def forward(self, x):\n        # DONE:\n        # self.state = ???\n        # return self.state\n        self.state = np.maximum(x, 0)\n        return self.state\n\n    def derivative(self):\n        # DONE\n        # return ???\n        tmp = self.state\n        tmp[tmp > 0] = 1\n        return tmp", "meta": {"hexsha": "e075197c30d0f5ecb900dd63c2e448fd34924b62", "size": 2946, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw2/program/mytorch/activation.py", "max_stars_repo_name": "BobAnkh/MaC", "max_stars_repo_head_hexsha": "f43c75576ea5af35e4c67f593627cbe1d479648e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-17T08:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-21T10:48:47.000Z", "max_issues_repo_path": "hw2/program/mytorch/activation.py", "max_issues_repo_name": "BobAnkh/MaC", "max_issues_repo_head_hexsha": "f43c75576ea5af35e4c67f593627cbe1d479648e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw2/program/mytorch/activation.py", "max_forks_repo_name": "BobAnkh/MaC", "max_forks_repo_head_hexsha": "f43c75576ea5af35e4c67f593627cbe1d479648e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9512195122, "max_line_length": 84, "alphanum_fraction": 0.5814663951, "include": true, "reason": "import numpy", "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.9111797003640646, "lm_q1q2_score": 0.8625196703186174}}
{"text": "#Purpose: To perform the fourier transform\n#import necessary packages\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom PIL import Image, ImageFilter, ImageEnhance\n\n#Function 1: Performs the fourier transform with steps \n#to get Magnitude_Spectrum\n#Steps: fourier transform, fourier shift, gets the magnitude spectrum\n#Inputs: image\n#Outputs: magntidue spectrum array\ndef Magnitude_Spectrum(image):\n    \"\"\"Peforms a fourier transform and returns the m_spec\"\"\"\n    fshift = fourier_fshift(image)\n    m_spec= np.log(np.abs(fshift))\n    return m_spec\n\n#Function 2: Performs the fourier transform to get fshift\n#Steps: fourier transform, fourier shift, gets the magnitude Spectrum\n#Inputs: image\n#Outputs: fshift\ndef fourier_fshift(image):\n    \"\"\"peforms the fourier transform and returns the fshift\"\"\"\n    f = np.fft.fft2(image)\n    fshift= np.fft.fftshift(f)\n    return fshift\n\n#Function 3: Plotting the magnitude spectrum made my fourier transform\n#Steps: plots the Magnitude Spectrum\n#Input: the magnitude spectrum Output\n#Output: image\n# def Plot_M_Spec(m_spec):\n#     plt.show(m_spec)\n#     plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])\n#     plt.show()\n#     return\n\n#Function 4: Performs an inverse fourier transform\n#Steps: unshifts the image, inverse fourier, normalizes the image\n#Inputs: f_shift\n#Outputs: image array of inverse fouriered image\ndef inverse_fourier(f_shift):\n    image_revert = np.fft.ifftshift(f_shift)\n    image = np.fft.ifft2(image_revert)\n    image = np.abs(image)\n    return image\n", "meta": {"hexsha": "89a2a02ada88a4ee81efa3a29ed94266fe307f62", "size": 1539, "ext": "py", "lang": "Python", "max_stars_repo_path": "rockstarlifestyle/fouriertransform.py", "max_stars_repo_name": "dash2927/Rockstar-Lifestyle", "max_stars_repo_head_hexsha": "10f308d18df05579fcdaab94c1e8ec4787dcb6a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-02-26T23:37:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-22T09:37:05.000Z", "max_issues_repo_path": "rockstarlifestyle/fouriertransform.py", "max_issues_repo_name": "dash2927/Rockstar-Lifestyle", "max_issues_repo_head_hexsha": "10f308d18df05579fcdaab94c1e8ec4787dcb6a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-03-12T17:24:34.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-29T19:48:28.000Z", "max_forks_repo_path": "rockstarlifestyle/fouriertransform.py", "max_forks_repo_name": "dash2927/Rockstar-Lifestyle", "max_forks_repo_head_hexsha": "10f308d18df05579fcdaab94c1e8ec4787dcb6a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-02-26T23:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-10T07:58:56.000Z", "avg_line_length": 32.7446808511, "max_line_length": 70, "alphanum_fraction": 0.7530864198, "include": true, "reason": "import numpy", "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773707953529717, "lm_q2_score": 0.8824278571786139, "lm_q1q2_score": 0.8624592166122804}}
{"text": "\nimport numpy as np\nimport scipy as sp\n\nimport matplotlib.pyplot as plt\n\n\nfrom scipy.stats import beta as beta_dist\nbeta_pdf = beta_dist.pdf\n\n\n\nprior_alpha = 25\nprior_beta = 75\n\nargs = (prior_alpha, prior_beta)\nprior_over_33, err = sp.integrate.quad(beta_pdf, 0.33, 1, args=args)\nprint(\"Prior probability\", prior_over_33)\n# 0.037830787030165056\n\n\nobserved_successes = 122\nobserved_failures = 257\n\nposterior_alpha = prior_alpha + observed_successes\nposterior_beta = prior_beta + observed_failures\n\nargs = (posterior_alpha, posterior_beta)\nposterior_over_33, err2 = sp.integrate.quad(beta_pdf, 0.33, 1, args=args)\nprint(\"Posterior probability\", posterior_over_33)\n# 0.13686193416281017\n\n\np = np.linspace(0, 1, 500)\nprior_dist = beta_pdf(p, prior_alpha, prior_beta)\nposterior_dist = beta_pdf(p, posterior_alpha, posterior_beta)\n\nfig, ax = plt.subplots()\nax.plot(p, prior_dist, \"k--\", label=\"Prior\")\nax.plot(p, posterior_dist, \"k\", label=\"Posterior\")\nax.legend()\nax.set_xlabel(\"Success rate\")\nax.set_ylabel(\"Density\")\nax.set_title(\"Prior and posterior distributions for success rate\")\n\n\nplt.show()\n", "meta": {"hexsha": "244614096effabd278853ba6d432055633ef9db4", "size": 1094, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter 04/analysing-conversion-rates-with-bayesian-techniques.py", "max_stars_repo_name": "arifmudi/Applying-Math-with-Python", "max_stars_repo_head_hexsha": "abeb6b0a9bcfa8b21092b9793d4e691cf5a146bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2020-07-23T14:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T07:00:17.000Z", "max_issues_repo_path": "Chapter 04/analysing-conversion-rates-with-bayesian-techniques.py", "max_issues_repo_name": "arifmudi/Applying-Math-with-Python", "max_issues_repo_head_hexsha": "abeb6b0a9bcfa8b21092b9793d4e691cf5a146bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 04/analysing-conversion-rates-with-bayesian-techniques.py", "max_forks_repo_name": "arifmudi/Applying-Math-with-Python", "max_forks_repo_head_hexsha": "abeb6b0a9bcfa8b21092b9793d4e691cf5a146bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2020-07-22T11:09:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T16:59:53.000Z", "avg_line_length": 22.7916666667, "max_line_length": 73, "alphanum_fraction": 0.768738574, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.975576915626597, "lm_q2_score": 0.8840392909114835, "lm_q1q2_score": 0.862448324720149}}
{"text": "\"\"\"\nImplements inequality and segregation measures such as Gini, Lorenz Curve\n\n\"\"\"\n\nimport numpy as np\nfrom numba import njit, prange\n\n\n@njit\ndef lorenz_curve(y):\n    \"\"\"\n    Calculates the Lorenz Curve, a graphical representation of the distribution of income\n    or wealth.\n\n    It returns the cumulative share of people (x-axis) and the cumulative share of income earned\n\n    Parameters\n    ----------\n    y : array_like(float or int, ndim=1)\n        Array of income/wealth for each individual. Unordered or ordered is fine.\n\n    Returns\n    -------\n    cum_people : array_like(float, ndim=1)\n        Cumulative share of people for each person index (i/n)\n    cum_income : array_like(float, ndim=1)\n        Cumulative share of income for each person index\n\n\n    References\n    ----------\n    .. [1] https://en.wikipedia.org/wiki/Lorenz_curve\n\n    Examples\n    --------\n    >>> a_val, n = 3, 10_000\n    >>> y = np.random.pareto(a_val, size=n)\n    >>> f_vals, l_vals = lorenz(y)\n\n    \"\"\"\n\n    n = len(y)\n    y = np.sort(y)\n    s = np.zeros(n + 1)\n    s[1:] = np.cumsum(y)\n    cum_people = np.zeros(n + 1)\n    cum_income = np.zeros(n + 1)\n    for i in range(1, n + 1):\n        cum_people[i] = i / n\n        cum_income[i] = s[i] / s[n]\n    return cum_people, cum_income\n\n\n@njit(parallel=True)\ndef gini_coefficient(y):\n    r\"\"\"\n    Implements the Gini inequality index\n\n    Parameters\n    -----------\n    y : array_like(float)\n        Array of income/wealth for each individual. Ordered or unordered is fine\n\n    Returns\n    -------\n    Gini index: float\n        The gini index describing the inequality of the array of income/wealth\n\n    References\n    ----------\n\n    https://en.wikipedia.org/wiki/Gini_coefficient\n    \"\"\"\n    n = len(y)\n    i_sum = np.zeros(n)\n    for i in prange(n):\n        for j in range(n):\n            i_sum[i] += abs(y[i] - y[j])\n    return np.sum(i_sum) / (2 * n * np.sum(y))\n\n\ndef shorrocks_index(A):\n    r\"\"\"\n    Implements Shorrocks mobility index\n\n    Parameters\n    -----------\n    A : array_like(float)\n        Square matrix with transition probabilities (mobility matrix) of\n        dimension m\n\n    Returns\n    --------\n    Shorrocks index: float\n        The Shorrocks mobility index calculated as\n\n        .. math::\n            \n            s(A) = \\frac{m - \\sum_j a_{jj} }{m - 1} \\in (0, 1)\n\n        An index equal to 0 indicates complete immobility.\n\n    References\n    -----------\n    .. [1] Wealth distribution and social mobility in the US: A quantitative approach\n       (Benhabib, Bisin, Luo, 2017).\n       https://www.econ.nyu.edu/user/bisina/RevisionAugust.pdf\n    \"\"\"\n\n    A = np.asarray(A)  # Convert to array if not already\n    m, n = A.shape\n\n    if m != n:\n        raise ValueError('A must be a square matrix')\n\n    diag_sum = np.diag(A).sum()\n\n    return (m - diag_sum) / (m - 1)\n", "meta": {"hexsha": "2cac426a4259b9b762d729da5352a003828ca163", "size": 2829, "ext": "py", "lang": "Python", "max_stars_repo_path": "quantecon/inequality.py", "max_stars_repo_name": "NzLeuphana/QuantEcon.py", "max_stars_repo_head_hexsha": "1db07f1c49c5ff4810c6e3e84b00eb3ab28c8da5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-08T08:25:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-11T13:18:32.000Z", "max_issues_repo_path": "quantecon/inequality.py", "max_issues_repo_name": "NzLeuphana/QuantEcon.py", "max_issues_repo_head_hexsha": "1db07f1c49c5ff4810c6e3e84b00eb3ab28c8da5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-24T10:22:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T10:22:41.000Z", "max_forks_repo_path": "quantecon/inequality.py", "max_forks_repo_name": "Biswadeep27/QuantEcon.py", "max_forks_repo_head_hexsha": "62af1e1f9d28ae13bde9305b1d1a83917ac8d1de", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.575, "max_line_length": 96, "alphanum_fraction": 0.5913750442, "include": true, "reason": "import numpy,from numba", "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576266, "lm_q2_score": 0.8991213874066956, "lm_q1q2_score": 0.8623961316979146}}
{"text": "# demonstrasi darii implementasi fungsi softmax\n\n# Ini adalah fungsi yang mengambil vektor dari K\n# bilangan real sebagai input, dan menormalkan\n# ke dalam distribusi probabilitas yang terdiri\n# dari K probabilitas proporsional\n# ke eksponensial dari angka input.\n# Setelah softmax, elemen dari\n# vektor selalu berjumlah 1.\n\n# referensi\n# https://en.wikipedia.org/wiki/Softmax_function\n\nimport numpy as np\n\n\ndef softmax(vector):\n    \"\"\"\n    Menerapkan fungsi softmax\n    Parameter:\n        vector (np.array,list,tuple): Array berbentuk numpy (1,n)\n        terdiri dari nilai-nilai nyata atau daftar serupa,tuple\n    Pengembalian:\n        softmax_vec (np.array):\n        Input array numpy setelah diterapkan\n        softmax.\n    Vektor softmax menambahkan hingga satu.\n    Kita perlu membatasi untuk\n    presisi\n\n    >>> vec = np.array([5, 5])\n    >>> softmax(vec)\n    array([0.5, 0.5])\n\n    >>> softmax([0])\n    array([1.])\n    \"\"\"\n    exponent_vector = np.exp(vector)\n\n    # Jumlahkan semua eksponensialnya\n    sum_exponent = np.sum(exponent_vector)\n\n    # bagi setiap eksponen dengan jumlah\n    # semua eksponen\n    softmax_vector = exponent_vector / sum_exponent\n\n    return softmax_vector\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod(verbose=True)\n", "meta": {"hexsha": "f89b151f6ca6b381dafa0ba60b63fcb3a43133ae", "size": 1276, "ext": "py", "lang": "Python", "max_stars_repo_path": "math/softmax.py", "max_stars_repo_name": "sekilas13/Python", "max_stars_repo_head_hexsha": "8b2c91cf0c90ebaba7a22e97bd69dae7a6564714", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 79, "max_stars_repo_stars_event_min_datetime": "2021-09-12T02:31:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T08:46:53.000Z", "max_issues_repo_path": "math/softmax.py", "max_issues_repo_name": "sekilas13/Python", "max_issues_repo_head_hexsha": "8b2c91cf0c90ebaba7a22e97bd69dae7a6564714", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 121, "max_issues_repo_issues_event_min_datetime": "2021-09-10T02:38:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:30:35.000Z", "max_forks_repo_path": "math/softmax.py", "max_forks_repo_name": "sekilas13/Python", "max_forks_repo_head_hexsha": "8b2c91cf0c90ebaba7a22e97bd69dae7a6564714", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 76, "max_forks_repo_forks_event_min_datetime": "2021-09-10T02:27:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:24:12.000Z", "avg_line_length": 23.6296296296, "max_line_length": 65, "alphanum_fraction": 0.6951410658, "include": true, "reason": "import numpy", "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.8991213725394589, "lm_q1q2_score": 0.8623961195375255}}
{"text": "import numpy as np\nfrom scipy import linalg as sla\na=np.array([[16,-1,1,2],\n            [2,12,1,-1],\n            [1,3,-24,2],\n            [4,-2,1,20]],dtype='f')\n#initial value s.t. np.linang.norm(x) is 1\nx=np.array([0.5,0.5,0.5,0.5]).T\n\nepsilon=0.0001\nmaxiteration=1000\n\nfor iteration in range(maxiteration):\n    x_new =a@x\n    eigen=x_new.dot(x)\n    if(np.linalg.norm(x_new-eigen*x)<epsilon):\n        break\n    #normalize\n    x_new/=np.linalg.norm(x_new)\n    #update x\n    x=x_new\nelse:\n    print(\"fail to calc eigen value\")\n    exit(1)\n\nprint(\"num of iteration is %d\"%iteration)\nprint(\"one of the eigen value of matrix a is %f\"%eigen)\nprint(\"its eigen vector is \\n{}\".format(x))\nprint(\"compare SciPy result...\")\nprint(sla.eig(a))\n\n", "meta": {"hexsha": "42b9a158ac43839b8bca1e21f5c996860462fb03", "size": 734, "ext": "py", "lang": "Python", "max_stars_repo_path": "eigenValue/powermethod.py", "max_stars_repo_name": "terasakisatoshi/pythonCodes", "max_stars_repo_head_hexsha": "baee095ecee96f6b5ec6431267cdc6c40512a542", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eigenValue/powermethod.py", "max_issues_repo_name": "terasakisatoshi/pythonCodes", "max_issues_repo_head_hexsha": "baee095ecee96f6b5ec6431267cdc6c40512a542", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigenValue/powermethod.py", "max_forks_repo_name": "terasakisatoshi/pythonCodes", "max_forks_repo_head_hexsha": "baee095ecee96f6b5ec6431267cdc6c40512a542", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9375, "max_line_length": 55, "alphanum_fraction": 0.6158038147, "include": true, "reason": "import numpy,from scipy", "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154280587323, "lm_q2_score": 0.8991213698363246, "lm_q1q2_score": 0.8623961106460483}}
{"text": "#! /usr/bin/env python\n#\n#  Various series for circumference derived by the kerala school\n#\nimport numpy as np\nfrom fractions import Fraction \n\n# The vyAse vAridhinihate series\ndef vyase(v, n=10, samskara=3, calc_type=\"fraction\"):\n    '''\n    Calculates the paridhi (circumference) from the vyAsa (diameter)\n\n    Uses the famous Madhava series\n\n    व्यासे वारिधिनिहते रूपहृते व्याससागराभिहते ।\n    त्रिशरादिविषमसंख्याभक्तमृणं स्वं पृथक्क्रमात् कुर्यात् ॥\n\n    Inputs:\n                   v: diameter\n                   n: number of terms\n      samskara: None (default) or\n                      k for kth order end-correction\n                      where k in (0, 1, 2, 3)\n           calc_type: \"fraction\" (default): uses fractions\n                      \"float\": uses numpy float128\n    Returns:\n                   p: circumference\n    '''\n    assert ((calc_type == \"fraction\") or (calc_type == \"float\")), \\\n        f\"Unknown calc_type {calc_type}: pass 'float' or 'fraction'\"\n    if calc_type == \"fraction\":\n        t = Fraction(4*v, 1) # First term\n    else:\n        t = np.float128(4*v)  # First term\n    # Initialize the series to first term\n    s = t     \n    sg = -1   # Sign of next term\n    # C = 4v - 4v/3 + 4v/5 - 4v/7 ...\n    for i in range(2, n+1):   # Ends after the nth term\n        s += sg*t/(2*i - 1)    # 4v/(2n-1) is the last term\n        sg *= -1\n    # Add end term\n    # Last divisor\n    if samskara == 0:\n        # Zeroth order correction\n        # a_p = 4v/2p, where 4v/p is the last term\n        p = 2*n - 1\n        s += sg*t/(2*p)\n    elif samskara == 1:\n        # First order\n        # a_p = 4v/(2p+2) = 4v/4n \n        s += sg*t/(4*n)\n    elif samskara == 2:\n        # Second Order\n        # a_p = 4v/((2p+2) + 4/(2p+2))\n        #     = 4v.n/(4n^2 + 1)\n        s += sg*t*n/(4*n**2 + 1)\n    elif samskara == 3:\n        # Third Order\n        # a_p = 4v/((2p+2) + 4/((2p+2) + 16/(2p+2)))\n        #     = 4v.(n^2 + 1)/(4n^3+5n)\n        s += sg*t*(n**2 + 1)/(4*n**3 + 5*n)\n    return s\n\n# The vyAsavargAdravihatAt series\ndef vyasavargad(v, n=10, calc_type=\"fraction\"):\n    '''\n    Calculates the paridhi (circumference) from the vyAsa (diameter)\n\n    Uses the vyAsavargAdravihatAt series\n    vyāsavargād ravihatāt padam syāt prathamam phalam |\n    tadāditastrisamkhyāptam phalam syāduttarottaram ||\n    rupādyayugmasamkhyābhirhr.tes.ves.u yathākramam |\n    vis.amānāmyutestyaktvā samam hi paridhirbhavet ||\n\n    Inputs:\n                   v: diameter\n                   n: number of terms\n           calc_type: \"fraction\" (default): uses fractions\n                      \"float\": uses numpy float128\n    Returns:\n                   p: circumference\n    '''\n    assert ((calc_type == \"fraction\") or (calc_type == \"float\")), \\\n        f\"Unknown calc_type {calc_type}: pass 'float' or 'fraction'\"\n    if calc_type == \"fraction\":\n        # Fixme implement Aryabhata square root algo\n        t = Fraction(np.sqrt(12 * v**2)) # First term\n    else:\n        t = np.sqrt(np.float128(12 * v**2))  # First term\n    p = t\n    s = -1   # Sign of next term\n    # C = sqrt(12d^2) (1 - 1/3.3 + 1/(3^2.5)+1/(3^3.7) ...) \n    for i in range(1,n):\n        if calc_type == \"fraction\":\n            p += Fraction(s*t, (3**i*(2*i+1)))\n        else:\n            p += s*t/np.float64(3**i*(2*i+1))\n\n        s = s*-1\n    return p\n\n\ndef samapanchahatayoh(v, n=10, calc_type=\"fraction\"):\n    '''\n    Calculates the paridhi (circumference) from the vyAsa (diameter) using \nthe samapanchahatayoH series\n    \n    समपञ्चाहतयो या रुपाद्ययुजां चतुर्घ्नमूलयुताः \n    ताभिः षोडशगुणितात् पृथगाहृतेषु विषमयुतेः \n    समफलयुतिमपहाय स्यादिष्टव्याससंभवः परिधिः \n\n    Inputs:\n                   v: diameter\n                   n: number of terms\n           calc_type: \"fraction\" (default): uses fractions\n                      \"float\": uses numpy float128\n    Returns:\n                   p: circumference\n    '''\n    assert ((calc_type == \"fraction\") or (calc_type == \"float\")), \\\n        f\"Unknown calc_type {calc_type}: pass 'float' or 'fraction'\"\n    sg = 1   # Sign of next term\n    t = 16*v\n    s = 0\n    # C = 16d(1/1^5+4.1 - 1/3^5+4*3 + 1/5^5+4*5 ...) \n    for i in range(0,n):\n        o = 2*i+1\n        if calc_type == \"fraction\":\n            s += Fraction(sg*t, (o**5+4*o))\n        else:\n            s += sg*t/np.float64(o**5+4*o)\n\n        sg = sg*-1\n    return s\n\n\ndef vyasad(v, n=10, calc_type=\"fraction\"):\n    '''\n    Calculates the paridhi (circumference) from the vyAsa (diameter) using \nthe vyAsAd vAridhinihatAt series\n\n    व्यासाद् वारिधिनिहतात् पृथगाप्तं त्र्याद्ययुग्विमूलघनैः\n    त्रिघ्नव्यासे स्वमृणं क्रमशः कृत्वा परिधिरानेयः ||  \n    C = 3D + 4D(1 /(3^3-3) - 1/(5^3-5) + 1/(7^3-7) ….)\n\n    Inputs:\n                   v: diameter\n                   n: number of terms\n           calc_type: \"fraction\" (default): uses fractions\n                      \"float\": uses numpy float128\n    Returns:\n                   p: circumference\n    '''\n    assert ((calc_type == \"fraction\") or (calc_type == \"float\")), \\\n        f\"Unknown calc_type {calc_type}: pass 'float' or 'fraction'\"\n    sg = 1   # Sign of next term\n    t = 4*v\n    s = 3*v\n    # C = 3D + 4D(1 /(3^3-3) - 1/(5^3-5) + 1/(7^3-7) ….)\n    for i in range(1,n):\n        o = 2*i+1\n        if calc_type == \"fraction\":\n            s += Fraction(sg*t, (o**3-o))\n        else:\n            s += sg*t/np.float64(o**3-o)\n        sg = sg*-1\n    return s\n\n\n__all__ = [\"vyase\", \"vyasavargad\", \"samapanchahatayoh\", \"vyasad\"]\n", "meta": {"hexsha": "c5669e226ef5356cfaa1221d970c49af2bfebf53", "size": 5456, "ext": "py", "lang": "Python", "max_stars_repo_path": "kerala_math/series/circumference.py", "max_stars_repo_name": "kmadathil/kerala_math", "max_stars_repo_head_hexsha": "b7a0b5e9d57a2f7790b985ec2b16e81d96ca6440", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-06-19T08:35:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T21:30:14.000Z", "max_issues_repo_path": "kerala_math/series/circumference.py", "max_issues_repo_name": "kmadathil/kerala_math", "max_issues_repo_head_hexsha": "b7a0b5e9d57a2f7790b985ec2b16e81d96ca6440", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kerala_math/series/circumference.py", "max_forks_repo_name": "kmadathil/kerala_math", "max_forks_repo_head_hexsha": "b7a0b5e9d57a2f7790b985ec2b16e81d96ca6440", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7209302326, "max_line_length": 75, "alphanum_fraction": 0.51521261, "include": true, "reason": "import numpy", "num_tokens": 2070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688145, "lm_q2_score": 0.8933094074745445, "lm_q1q2_score": 0.8623840712841826}}
{"text": "'''\n\nFind the k post offices located closest to you, given your location and a list of locations of all post offices available.\nLocations are given in 2D coordinates in [X, Y], where X and Y are integers.\nEuclidean distance is applied to find the distance between you and a post office.\nAssume your location is [m, n] and the location of a post office is [p, q], the Euclidean distance between the office and\nyou is SquareRoot((m - p) * (m - p) + (n - q) * (n - q)).\nK is a positive integer much smaller than the given number of post offices. from aonecode.com\n\ne.g.\nInput\nyou: [0, 0]\npost_offices: [[-16, 5], [-1, 2], [4, 3], [10, -2], [0, 3], [-5, -9]]\nk = 3\n\nOutput from aonecode.com\n[[-1, 2], [0, 3], [4, 3]]\n'''\n\n# [m, n] - subject's location\n\nimport numpy as np\n\norigin = [0,0]\n\ndist_dict = {}\n\n\ndef get_k_nearest_post_offices(post_ofcs, k):\n    for ind, val in enumerate(post_ofcs):\n        eucl_dist = np.sqrt((origin[0] - val[0]) * (origin[0] - val[0]) + (origin[1] - val[1]) * (origin[1] - val[1]))\n        dist_dict[eucl_dist] = val\n\n    #print(dist_dict)\n    return sorted(dist_dict)[:k]\n\n\nk_nearest_po_keys = get_k_nearest_post_offices([[-16, 5], [-1, 2], [4, 3], [10, -2], [0, 3], [-5, -9]], 3)\n\nfor key in k_nearest_po_keys:\n    print(dist_dict[key])\n\n\n\n\n# to preserve duplicate keys if needed\n# from collections import defaultdict\n#\n# d = defaultdict(list)\n#\n#\n# def get_k_nearest_post_offices(post_ofcs, k):\n#     for ind, val in enumerate(post_ofcs):\n#         eucl_dist = np.sqrt((origin[0] - val[0]) * (origin[0] - val[0]) + (origin[1] - val[1]) * (origin[1] - val[1]))\n#         d[eucl_dist].append(val)\n#     return sorted(dist_dict)[:k]\n#\n# k_nearest_po_keys = get_k_nearest_post_offices([[-16, 5], [-1, 2], [4, 3], [10, -2], [0, 3], [-5, -9]], 3)\n#\n# for key in k_nearest_po_keys:\n#     print(dist_dict[key])", "meta": {"hexsha": "ec6e4cb737cf62faaa0255d248e655c12aa89228", "size": 1832, "ext": "py", "lang": "Python", "max_stars_repo_path": "leet_code/k_nearest_post_offices.py", "max_stars_repo_name": "salma-shaik/challenge_problems", "max_stars_repo_head_hexsha": "9ee6e7fae2227c49a8c15f5d04fa32c4f645ff35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "leet_code/k_nearest_post_offices.py", "max_issues_repo_name": "salma-shaik/challenge_problems", "max_issues_repo_head_hexsha": "9ee6e7fae2227c49a8c15f5d04fa32c4f645ff35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "leet_code/k_nearest_post_offices.py", "max_forks_repo_name": "salma-shaik/challenge_problems", "max_forks_repo_head_hexsha": "9ee6e7fae2227c49a8c15f5d04fa32c4f645ff35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0327868852, "max_line_length": 122, "alphanum_fraction": 0.634279476, "include": true, "reason": "import numpy", "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013547, "lm_q2_score": 0.9046505402422644, "lm_q1q2_score": 0.8623807823792482}}
{"text": "import numpy as np\nimport math\n\n\ndef pendulum_derivatives(theta, omega, g=9.8, l=1):\n    \"\"\"\n    \\dot{\\theta} = \\omega\n    \\dot{\\omega} = -\\frac{g \\sin\\theta}{l}\n    :param theta: angel of the pendulum\n    :param omega: angular velocity of the pendulum\n    :param g: gravitational acceleration\n    :param l: length of the pendulum\n    :return: derivative of angel, derivative of angular velocity\n    \"\"\"\n    d_theta = omega\n    d_omega = - np.sin(theta) * g / l\n    return d_theta, d_omega\n\n\ndef simulate(sample_num, time_scale=0.1, simulate_length=100,\n             theta_std=np.pi, omega_std=1,\n             seed=623, noise_std=0.5):\n    \"\"\"\n    Simulate single pendulum.\n    :param sample_num:\n    :param time_scale:\n    :param simulate_length:\n    :param theta_std:\n    :param omega_std:\n    :param seed:\n    :param noise_std:\n    :return: simulated data\n    \"\"\"\n    np.random.seed(seed)\n    batch_size = math.ceil(sample_num / simulate_length)\n\n    data = np.zeros([simulate_length * batch_size, 4])\n    theta = np.random.randn(batch_size, 1) * theta_std\n    omega = np.random.randn(batch_size, 1) * omega_std\n\n    for i in range(simulate_length):\n        d_theta, d_omega = pendulum_derivatives(theta, omega)\n        data[i * batch_size: (i + 1) * batch_size] = np.hstack((theta, omega, d_theta, d_omega))\n        theta += d_theta * time_scale\n        omega += d_omega * time_scale\n\n    return data[:sample_num]\n\n\nif __name__ == '__main__':\n    data = simulate(3010)\n    print(data[-1])\n    print(data.shape)\n", "meta": {"hexsha": "15287ca9d6f9126e67d92c1351d2534ec3ec6af6", "size": 1515, "ext": "py", "lang": "Python", "max_stars_repo_path": "CI_test_tools/data_generation/single_pendulum.py", "max_stars_repo_name": "FrankTianTT/CI-test-tools", "max_stars_repo_head_hexsha": "802e2c89c1b57bd124cdb989b76fe2649da761a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CI_test_tools/data_generation/single_pendulum.py", "max_issues_repo_name": "FrankTianTT/CI-test-tools", "max_issues_repo_head_hexsha": "802e2c89c1b57bd124cdb989b76fe2649da761a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CI_test_tools/data_generation/single_pendulum.py", "max_forks_repo_name": "FrankTianTT/CI-test-tools", "max_forks_repo_head_hexsha": "802e2c89c1b57bd124cdb989b76fe2649da761a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0555555556, "max_line_length": 96, "alphanum_fraction": 0.6455445545, "include": true, "reason": "import numpy", "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750466836961, "lm_q2_score": 0.9046505338155469, "lm_q1q2_score": 0.8623807798554461}}
{"text": "import numpy as np \nimport matplotlib.pyplot as plt\nimport time\nplt.rcParams['figure.figsize'] = [12, 12]\nplt.rcParams.update({'font.size': 18})\n\nn = 20\nk = np.arange(1,n+1)\nx = np.cos((k-1)*np.pi/(n-1))\n#Input function\nf=np.sin(np.pi*x)\n#Analytically obtain the Derivative\ndf=np.pi*np.cos(np.pi*x)\ndf2=-np.pi**2*np.sin(np.pi*x)\n# -- Differentiation via chebfft based on \n# -- chebdifft.m matlab version\ndef chebdifft(f,M):\n\tN=len(f)\n\n\ta = np.flipud(f[1:N-1])\n\ta = np.concatenate((f,a))\n\ta0 = np.fft.fft(a)\n\n\tones = np.ones(N-2)\n\ta = np.concatenate(([0.5],ones,[0.5] ))\n\ta0 = a0[0:N]*a/(N-1)  #a0 contains Chebyshev coefficients of f\n\t#print(a0)\n\n\t# Recursion formula for computing coefficients of ell'th derivative \n\ta = np.zeros((N,M+1),dtype=\"complex_\")\n\ta[:,0] = a0\n\tfor ell in np.arange(1,M+1):\n\t\ta[N-ell-1,ell]=2*(N-ell)*a[N-ell,ell-1];\n\t\tfor k in np.arange(N-ell-2,0,-1):\n\n\t\t\ta[k,ell]=a[k+2,ell]+2*(k+1)*a[k+1,ell-1]\n\t\ta[0,ell]=a[1,ell-1]+a[2,ell]/2\n\n\t# Transform back to nphysical space\n\tb1 = [2*a[0,M]]\n\tb2 = a[1:N-1,M]\n\tb3 = [2*a[N-1,M]]\n\tb4 = np.flipud(b2)\n\tback = np.concatenate((b1,b2,b3,b4))\n\tDmf = 0.5*np.fft.fft(back)\n\t# Real data in, real derivative out\n\tDmf = Dmf[0:N]\n\treturn np.real(Dmf)\n\nt0 = time.time()\ndfFFT = chebdifft(f,1)\ndfFFT2 = chebdifft(f,2)\nt1 = time.time()\n\nprint(\"Total time: {:}\".format(t1-t0))\n##Plot results\nplt.plot(x, df.real, color='k', LineWidth=2, label='True Derivative')\n# plt.plot(x, dfFD.real, '--', color='b', LineWidth=1.5, label='Finite Difference')\nplt.plot(x, dfFFT.real, '--', color='c', LineWidth=1.5, label='Spectral Derivative')\nplt.xlabel('X values')\nplt.ylabel('Y values')\nplt.legend()\nplt.show()\n\n##Plot results\nplt.plot(x, df2.real, color='k', LineWidth=2, label='True Derivative')\n# plt.plot(x, dfFD.real, '--', color='b', LineWidth=1.5, label='Finite Difference')\nplt.plot(x, dfFFT2.real, '--', color='c', LineWidth=1.5, label='2nd Spectral Derivative')\nplt.xlabel('X values')\nplt.ylabel('Y values')\nplt.legend()\nplt.ylim(-np.pi**2,+np.pi**2)\nplt.show()\n\n\n\n", "meta": {"hexsha": "996d2ac95035f29a47e504b4b0d325d1fc46585e", "size": 2018, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/chebdifft.py", "max_stars_repo_name": "preiter93/dmsuite", "max_stars_repo_head_hexsha": "c6242afa7c795297b980ab4e1038318b556c2821", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/chebdifft.py", "max_issues_repo_name": "preiter93/dmsuite", "max_issues_repo_head_hexsha": "c6242afa7c795297b980ab4e1038318b556c2821", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/chebdifft.py", "max_forks_repo_name": "preiter93/dmsuite", "max_forks_repo_head_hexsha": "c6242afa7c795297b980ab4e1038318b556c2821", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2077922078, "max_line_length": 89, "alphanum_fraction": 0.6437066402, "include": true, "reason": "import numpy", "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750360641185, "lm_q2_score": 0.9046505408849362, "lm_q1q2_score": 0.8623807769875118}}
{"text": "\nimport numpy as np\n\nclass LinearRegression():\n    def __init__(self):\n        self.learning_rate = 0.01\n        self.total_iterations = 1000\n    def yhat(self, X, w):\n        '''\n        predicted y value\n        '''\n        # making sure the dimensions are correct\n        # predictions: yhat = w1*x1 + w2*x2  + ... - want a scalar value for each input \n        # m - # training examples, n - # features, w - nx1, y - mx1, X - n x m, add intercept b so that X: n x m + 1\n        # m x n * n x 1 = m x 1, want output to be 1 x m \n        # 1 x n * n x m - w^T*X \n        return np.dot(w.T, X)\n\n\n    def loss(self, yhat, y):\n        '''\n        compute the loss - MSE\n        '''\n        L = 1/self.m * np.sum(np.power(yhat - y, 2)) # divide by number of examples, sum elementwise square of differences of the yhat - predicted and y - ground truth\n        return L\n\n    def gradient_descent(self, w, X, y, yhat):\n        '''\n        update the weigths based on the loss\n        '''\n        # again make sure the dimensions are correct\n        # L = (yhat - y)  # loss : 1 x m, want the output to be n x 1 - multiply  n x m by (1 x m)^T = n x 1\n\n        dLdw = 2/self.m * np.dot(X, (yhat - y).T) # gradient of L (loss) w.r.t. w (weights) , y = x * w + b, L = 1/m sum(yhat - y)^2 = 1/m sum(yhat - x*w+b)^2, dLdw = 2* 1/m *  x*w \n\n        w = w - self.learning_rate * dLdw # update step, dLdw needs to be same dimension as w - nx1\n\n        return w \n\n    def main(self, X, y):        \n        '''\n        will call the above functions for a number of iterations\n        '''\n        # add intercept (bias)\n        x1 = np.ones((1, X.shape[1]))\n        X = np.append(X, x1, axis=0) # add to features\n\n        self.m = X.shape[1]\n        self.n = X.shape[0]\n\n        w = np.zeros((self.n, 1))\n\n        # iterate\n        for it in range(self.total_iterations + 1):\n            yhat = self.yhat(X, w)\n            loss = self.loss(yhat, y)\n\n            # PRINT\n            if it % 200 == 0:\n                print(f'Cost at iteration: {it} is {loss}')   \n\n            w = self.gradient_descent(w, X, y, yhat)\n\n        return w \n\nif __name__ == '__main__':\n    X = np.random.rand(1, 500)\n    y = 3 * X + np.random.rand(1, 500) * 0.1 # add some small random Gaussian noise\n    regression = LinearRegression()\n    w = regression.main(X, y)", "meta": {"hexsha": "b47d08d63fd8c381d0648a5dd4ed8d531f684147", "size": 2326, "ext": "py", "lang": "Python", "max_stars_repo_path": "ML_Algorithms/linear_regression/Linear_Regression_Grad_Descent.py", "max_stars_repo_name": "ewanowara/practiceMLandDAproblems", "max_stars_repo_head_hexsha": "8c002235f18ae5fb6e7b837106c87d09d33f14a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ML_Algorithms/linear_regression/Linear_Regression_Grad_Descent.py", "max_issues_repo_name": "ewanowara/practiceMLandDAproblems", "max_issues_repo_head_hexsha": "8c002235f18ae5fb6e7b837106c87d09d33f14a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ML_Algorithms/linear_regression/Linear_Regression_Grad_Descent.py", "max_forks_repo_name": "ewanowara/practiceMLandDAproblems", "max_forks_repo_head_hexsha": "8c002235f18ae5fb6e7b837106c87d09d33f14a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2285714286, "max_line_length": 181, "alphanum_fraction": 0.5236457438, "include": true, "reason": "import numpy", "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799472560582, "lm_q2_score": 0.8947894731166139, "lm_q1q2_score": 0.8623801512056063}}
{"text": "import numpy as np\n\ndef compute_95CI_ols(x,y):\n    '''returns the max likliehood estimators and 95% confidence intervals\n    that result from ordinary least squares regression applied to the\n    1-dimensional numpy arrays, x and y.'''\n    x=x.flatten();y=y.flatten()\n    n=x.shape[0]\n    assert(n==y.shape[0])\n    assert(n>2)\n    if not n>=8:\n        print('Warning: CI not valid for less than 8 data points!')\n    xbar=np.mean(x);ybar=np.mean(y)\n    #compute sums of squares\n    SSxx=np.sum((x-xbar)**2)\n    SSxy=np.dot((x-xbar),(y-ybar))\n    SSyy=np.sum((y-ybar)**2)\n    #best linear unbiased estimator of slope\n    m=SSxy/SSxx\n    #best linear unbiased estimator of intercept\n    b=ybar-m*xbar\n    #values of fit\n    yhat=b+m*x\n    #standard error of fit, s_{y,x}^2=ssE\n    SSE=np.sum((y-yhat)**2)\n    ssE=SSE/(n-2)\n    #standard deviation of slope\n    sm = np.sqrt(ssE/SSxx)\n    #standard deviation of intercept\n    sb = np.sqrt(ssE*(1/n+xbar**2/SSxx))\n    #compute 95% CI for parameters\n    Delta_m = 1.96*sm\n    Delta_b = 1.96*sb\n    #compute Rsquared\n    Rsquared=(SSyy-SSE)/SSyy\n    #format results as a human readable dict\n    dict_output={\n        'm':m,\n        'Delta_m':Delta_m,\n        'b':b,\n        'Delta_b':Delta_b,\n        'Rsquared':Rsquared\n    }\n    return dict_output\n", "meta": {"hexsha": "a0f6dc62bd937921bf44edcb0ebea9985c8770c5", "size": 1291, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/lib/measure/compute_slope.py", "max_stars_repo_name": "timtyree/bgmc", "max_stars_repo_head_hexsha": "891e003a9594be9e40c53822879421c2b8c44eed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/lib/measure/compute_slope.py", "max_issues_repo_name": "timtyree/bgmc", "max_issues_repo_head_hexsha": "891e003a9594be9e40c53822879421c2b8c44eed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/lib/measure/compute_slope.py", "max_forks_repo_name": "timtyree/bgmc", "max_forks_repo_head_hexsha": "891e003a9594be9e40c53822879421c2b8c44eed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6888888889, "max_line_length": 73, "alphanum_fraction": 0.6227730442, "include": true, "reason": "import numpy", "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9808759654852756, "lm_q2_score": 0.8791467548438126, "lm_q1q2_score": 0.8623339219606715}}
{"text": "import torch.nn.functional as F\nimport numpy as np\nimport torch\nfrom util import randomize_in_place\n\n\ndef sigmoid(x):\n    return 1 / (1 + np.exp(-x))\n\n\ndef graph1(a_np, b_np, c_np):\n    \"\"\"\n    Computes the graph\n        - x = a * c\n        - y = a + b\n        - f = x / y\n\n    Computes also df/da using\n        - Pytorchs's automatic differentiation (auto_grad)\n        - user's implementation of the gradient (user_grad)\n\n    :param a_np: input variable a\n    :type a_np: np.ndarray(shape=(1,), dtype=float64)\n    :param b_np: input variable b\n    :type b_np: np.ndarray(shape=(1,), dtype=float64)\n    :param c_np: input variable c\n    :type c_np: np.ndarray(shape=(1,), dtype=float64)\n    :return: f, auto_grad, user_grad\n    :rtype: torch.DoubleTensor(shape=[1]),\n            torch.DoubleTensor(shape=[1]),\n            numpy.float64\n    \"\"\"\n    # YOUR CODE HERE:\n    a = torch.from_numpy(a_np)\n    b = torch.from_numpy(b_np)\n    c = torch.from_numpy(c_np)\n    a.requires_grad = True\n    x = a * c\n    y = a + b\n    f = x / y\n    f.backward()\n    auto_grad = a.grad\n    \"\"\"\n    df/da = df/dx * dx/da + df/dy * dy/da\n    df/dx = 1/y, dx/da = c,  df/dy = - x/y², dy/da = 1 \n    \"\"\"\n    user_grad = ((c / y) - (x / (y * y))).detach().numpy()\n    # END YOUR CODE\n    return f, auto_grad, user_grad\n\n\ndef graph2(W_np, x_np, b_np):\n    \"\"\"\n    Computes the graph\n        - u = Wx + b\n        - g = sigmoid(u)\n        - f = sum(g)\n\n    Computes also df/dW using\n        - pytorchs's automatic differentiation (auto_grad)\n        - user's own manual differentiation (user_grad)\n\n    F.sigmoid may be useful here\n\n    :param W_np: input variable W\n    :type W_np: np.ndarray(shape=(d,d), dtype=float64)\n    :param x_np: input variable x\n    :type x_np: np.ndarray(shape=(d,1), dtype=float64)\n    :param b_np: input variable b\n    :type b_np: np.ndarray(shape=(d,1), dtype=float64)\n    :return: f, auto_grad, user_grad\n    :rtype: torch.DoubleTensor(shape=[1]),\n            torch.DoubleTensor(shape=[d, d]),\n            np.ndarray(shape=(d,d), dtype=float64)\n    \"\"\"\n    # YOUR CODE HERE:\n    W = torch.from_numpy(W_np)\n    W.requires_grad = True\n    x = torch.from_numpy(x_np)\n    b = torch.from_numpy(b_np)\n    u = torch.matmul(W, x) + b\n    g = F.sigmoid(u)\n    f = torch.sum(g)\n    f.backward()\n    auto_grad = W.grad\n    \"\"\"\n    df_du = sigmoid(u) * (1 - sigmoid(u))\n    du_dW = x^t\n    df_dW = df_du * du_dW\n    \"\"\"\n    xt = torch.transpose(x, 0, 1)\n    sigU = F.sigmoid(u)\n    user_grad = (torch.matmul((sigU * (1 - sigU)), xt)).detach().numpy()\n    # END YOUR CODE\n    return f, auto_grad, user_grad\n\n\ndef SGD_with_momentum(X,\n                      y,\n                      inital_w,\n                      iterations,\n                      batch_size,\n                      learning_rate,\n                      momentum):\n    \"\"\"\n    Performs batch gradient descent optimization using momentum.\n\n    :param X: design matrix\n    :type X: np.ndarray(shape=(N, d))\n    :param y: regression targets\n    :type y: np.ndarray(shape=(N, 1))\n    :param inital_w: initial weights\n    :type inital_w: np.array(shape=(d, 1))\n    :param iterations: number of iterations\n    :type iterations: int\n    :param batch_size: size of the minibatch\n    :type batch_size: int\n    :param learning_rate: learning rate\n    :type learning_rate: float\n    :param momentum: accelerate parameter\n    :type momentum: float\n    :return: weights, weights history, cost history\n    :rtype: np.array(shape=(d, 1)), list, list\n    \"\"\"\n    # YOUR CODE HERE:\n    z = torch.autograd.Variable(torch.zeros(inital_w.shape).double() , requires_grad = True)\n    W = torch.autograd.Variable(torch.from_numpy(inital_w), requires_grad = True)\n    x = torch.autograd.Variable(torch.from_numpy(X), requires_grad = False)\n    Y = torch.autograd.Variable(torch.from_numpy(y), requires_grad = False)    \n    cost_history = []\n    weights_history = []\n    for i in range(iterations) :\n        temp = torch.randperm(x.shape[0])\n        x = x[temp]\n        Y = Y[temp]\n        xW = torch.matmul(x[:batch_size], W)\n        xWY = xW - Y[:batch_size]\n        J = torch.matmul(torch.transpose(xWY, 0, 1), xWY)  / batch_size\n        J.backward()\n        z.data = momentum * z + W.grad\n        W.grad.zero_()\n        W.data -= learning_rate * z\n        cost_history.append(J)\n        weights_history.append(W.data)\n    w_np = W.detach().numpy()\n    # END YOUR CODE\n\n    return w_np, weights_history, cost_history\n", "meta": {"hexsha": "824682d57d23cd58a596d435b1b9498aad63986d", "size": 4454, "ext": "py", "lang": "Python", "max_stars_repo_path": "ThirdAssigment/basic_functions.py", "max_stars_repo_name": "PaiZuZe/MAC0460-machineLearning", "max_stars_repo_head_hexsha": "98031412d8835afad0fde318b5c57a613bfb4fc8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ThirdAssigment/basic_functions.py", "max_issues_repo_name": "PaiZuZe/MAC0460-machineLearning", "max_issues_repo_head_hexsha": "98031412d8835afad0fde318b5c57a613bfb4fc8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-09-16T16:31:36.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-16T16:31:36.000Z", "max_forks_repo_path": "ThirdAssigment/basic_functions.py", "max_forks_repo_name": "PaiZuZe/MAC0460-machineLearning", "max_forks_repo_head_hexsha": "98031412d8835afad0fde318b5c57a613bfb4fc8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8926174497, "max_line_length": 92, "alphanum_fraction": 0.5893578806, "include": true, "reason": "import numpy", "num_tokens": 1239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474220263198, "lm_q2_score": 0.9032942067038784, "lm_q1q2_score": 0.8623274857611671}}
{"text": "import os\nimport dill\nimport numpy as np\nfrom math import pi, exp, atan, sqrt, acos\n\n\ndef angle(x, y):\n\t\"\"\"calculates the angle of (x,y) with respect to (0,0)\n\t\n\t:param x: x choordinate\n\t:param y: y choordinate\n\t:returns: the angle\"\"\"\n\tat = atan(y/x)\n\tif(x < 0): return at+pi\n\telif(y < 0): return at+2*pi\n\treturn at\n\n\ndef angle_between_vectors(v, w):\n\t\"\"\"calculates the angle between two vectors (any dimensional)\n\t\n\t:param v: vector 1\n\t:param w: vector 2\n\t:returns: the angle\"\"\"\n\tscalar = sum(v[i]*w[i] for i in range(len(v)))\n\tif(scalar/(L2_norm(v)*L2_norm(w)) > 1): return 0\n\tif(scalar/(L2_norm(v)*L2_norm(w)) < -1): return pi\n\treturn acos(scalar/(L2_norm(v)*L2_norm(w)))\n\n\ndef L1_norm(seq):\n\t\"\"\"calculates the L1 norm of a sequence or vector\n\t\n\t:param seq: the sequence or vector\n\t:returns: the L1 norm\"\"\"\n\tnorm = 0\n\tfor i in range(len(seq)):\n\t\tnorm += abs(seq[i])\n\treturn norm\n\n\ndef L2_norm(seq):\n\t\"\"\"calculates the L2 norm of a sequence or vector\n\t\n\t:param seq: the sequence or vector\n\t:returns: the L2 norm\"\"\"\n\tnorm = 0\n\tfor i in range(len(seq)):\n\t\tnorm += seq[i]**2\n\treturn sqrt(norm)\n\n\ndef Linf_norm(seq):\n\t\"\"\"calculates the Linf norm of a sequence or vector\n\t\n\t:param seq: the sequence or vector\n\t:returns: the Linf norm\"\"\"\n\tlargest = 0\n\tfor i in range(len(seq)):\n\t\tif(abs(seq[i]) > largest): largest = abs(seq[i])\n\treturn largest\n\n\ndef linear_interpolation(listx, listy, argument):\n\t\"\"\"calculates the linear interpolation of [listx,listy] at argument\n\t\n\t:param listx: x choordinates (should be ordered in ascending order)\n\t:param listy: y choordinates\n\t:param argument: where to evaluate the linear interpolation\n\t:returns: value of the linear interpolation at argument\"\"\"\n\tif(argument in listx):\n\t\treturn listy[listx.index(argument)]\n\tif(argument < listx[0]):\n\t\treturn listy[0] + (listy[0]-listy[1])/(listx[1]-listx[0])*(listx[0]-argument)\n\tif(argument > listx[-1]):\n\t\treturn listy[-1] + (listy[-1]-listy[-2])/(listx[-1]-listx[-2])*(argument-listx[-1])\n\tindex = 0\n\twhile((listx[index] < argument and listx[index+1] > argument) != 1): index += 1\n\treturn listy[index] + (listy[index+1]-listy[index])/(listx[index+1]-listx[index])*(argument-listx[index])\n\n\ndef gaussian(x, std=1):\n\t\"\"\"returns a Gaussian distribution\n\t\n\t:param x: variable\n\t:param std: standard deviation (default 1)\n\t:returns: Gaussian PDF\"\"\"\n\treturn 1/(std*sqrt(2*pi))*exp(-x**2/(2*std**2))\n\n\ndef gaussian_der(x, std=1):\n\t\"\"\"returns a Gaussian derivative distrbution (x*PDF_normal)\n\t\n\t:param x: variable\n\t:param std: the standard deviation\n\t:returns: positive half of the Gaussian derivative PDF\"\"\"\n\tif(x < 0): return 0\n\treturn (2-pi/2)/std**2*x*exp(-(2-pi/2)*x**2/(2*std**2))\n\n\ndef kernel_convolve(seq, kernel, kernel_width):\n\t\"\"\"convolves a sequence with a kernel\n\t\n\t:param seq: sequence to be convolved\n\t:param kernel: the kernel, a probability distribuion fucntion (does not have to be normalized)\n\t:param kernel_width: the width of the kernel (std for Gaussian)\n\t:returns: convolved sequence\"\"\"\n\tker = np.array([kernel(i/kernel_width) for i in range(-round(3*kernel_width), round(3*kernel_width))])\n\tker = ker/sum(ker)\n\treturn np.convolve(seq, ker ,mode='same')\n\n\ndef save_object_dill(obj, filename, save_path=\"objects_save\"):\n\t\"\"\"saves an object with dill (also makes the 'objects_save/' directory if it wasn't there)\n\t\n\t:param obj: object to save\n\t:param filename: filename without any extension\n\t:param save_path: path where to save object, staring from the directory of the simulation (default \"objects_save\")\"\"\"\n\t# directory\n\tif not os.path.exists(save_path):\n\t\tos.makedirs(save_path)\n\t# pickling\n\tf = open(save_path+\"/\"+filename+'.pickle', 'wb')\t\n\tdill.dump(obj, f)\n\tf.close()\n\t\n\t\ndef load_object_dill(filename, load_path=\"objects_save\"):\n\t\"\"\"loads an object with dill (from 'objects_save/' directory)\n\t\n\t:param filename: filename without any extension\n\t:param load_path: path where to load object from, staring from the directory of the simulation (default \"objects_save\")\n\t:returns: saved object\"\"\"\n\t# unpickling\n\tf = open(load_path+\"/\"+filename+'.pickle', 'rb')\t\n\tobj = dill.load(f)\n\tf.close()\n\treturn obj\n\n", "meta": {"hexsha": "efde687fb92cbe13588b9bd35654c03df7daa1cf", "size": 4098, "ext": "py", "lang": "Python", "max_stars_repo_path": "oscillator_snap/oscillator_auxiliaries.py", "max_stars_repo_name": "rokcestnik/oscillator_snap", "max_stars_repo_head_hexsha": "ad54a2108aede3e80f749968e9c770a78f07f7bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-04-17T15:43:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-04T21:50:53.000Z", "max_issues_repo_path": "oscillator_snap/oscillator_auxiliaries.py", "max_issues_repo_name": "rokcestnik/oscillator_snap", "max_issues_repo_head_hexsha": "ad54a2108aede3e80f749968e9c770a78f07f7bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "oscillator_snap/oscillator_auxiliaries.py", "max_forks_repo_name": "rokcestnik/oscillator_snap", "max_forks_repo_head_hexsha": "ad54a2108aede3e80f749968e9c770a78f07f7bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-08T01:34:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-08T01:34:31.000Z", "avg_line_length": 29.2714285714, "max_line_length": 120, "alphanum_fraction": 0.6993655442, "include": true, "reason": "import numpy", "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360066, "lm_q2_score": 0.9032942041005328, "lm_q1q2_score": 0.8623274821103576}}
{"text": "import numpy as np\nimport sympy as sym\nimport matplotlib.pyplot as plt\n\ndef f(x):\n    \"\"\"\n    Define a function (you can change to whatever function you want\n    \"\"\"\n    return (x - np.pi)**2 + 4 * np.sin(x)\n\ndef visualize(function, minimum, iter_points, limits, npoints=100):\n    \"\"\"\n    Quick plot of the function\n    \"\"\"\n    x, y = function[0], function[1]\n    lam_x = sym.lambdify(x, y)\n    x_vals = np.linspace(limits[0], limits[1], num=npoints)\n    y_vals = lam_x(x_vals)\n\n    # Some plot configurations\n    plt.rc('font', family='serif')\n    plt.rc('font', size=11)\n    plt.rc('axes', labelsize=11)\n\n    fig, ax = plt.subplots()\n    ax.plot(x_vals, y_vals, 'r-')\n    ax.plot(iter_points[0], iter_points[1], 'og')\n    ax.plot(minimum[0], minimum[1], 'sr')\n    ax.set_xlabel('x')\n    ax.set_ylabel('y')\n    plt.show()\n\ndef bisection(function, limits, tol=1e-3, max_iter=100):\n    \"\"\"\n    :param function: symbolic expression\n    :param limits: limits of the function\n    :param tol: tolerance to converge\n    :return:\n    \"\"\"\n    xm_vector = []\n    fxm_vector = []\n    b = [limits[0], limits[1]]\n    if b[0] > b[1]:\n        raise Exception('Bracket values must be in ascending order')\n\n    yprime = function.diff(x)\n    dfb0 = float(yprime.subs(x, b[0]))\n    dfb1 = float(yprime.subs(x, b[1]))\n\n    if not ((np.sign(dfb0) < 0) and (np.sign(dfb1) > 0)):\n        raise Exception('Minimum may not be contained in bracket')\n\n    b_size = b[1] - b[0]\n    k = 0\n\n    while (b_size > tol) and (k < max_iter):\n        k += 1\n        xm = (b[1] + b[0])/2\n        fxm = float(y.subs(x, xm))\n        dfxm = float(yprime.subs(x, xm))\n\n        if dfxm == 0:\n            break\n        elif dfxm > 0:\n            b[1] = xm\n            xm_vector.append(xm)\n            fxm_vector.append(fxm)\n        elif dfxm < 0:\n            b[0] = xm\n            xm_vector.append(xm)\n            fxm_vector.append(fxm)\n\n        b_size = b[1] - b[0]\n        minimum = [xm, fxm]\n        iter_points = [xm_vector, fxm_vector]\n\n    return minimum, iter_points\n\n\n\n#%%\n# You are supposed to run the previous box before\nx = sym.symbols('x')\ny = (x - sym.pi)**2 + 4 * sym.sin(x)\nminimum, iter_points = bisection(y, [-10, 10])\n\nfunction = [x, y]\nvisualize(function, minimum, iter_points, [-10, 10])\n\n", "meta": {"hexsha": "8403e0085692e9c38dcf98677508503cb695ebba", "size": 2266, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lecture 1/bisection_method.py", "max_stars_repo_name": "dalexa10/EngineeringDesignOptimization", "max_stars_repo_head_hexsha": "eb5b5e4edd773aef629f59aea8a9771af41bd224", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lecture 1/bisection_method.py", "max_issues_repo_name": "dalexa10/EngineeringDesignOptimization", "max_issues_repo_head_hexsha": "eb5b5e4edd773aef629f59aea8a9771af41bd224", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lecture 1/bisection_method.py", "max_forks_repo_name": "dalexa10/EngineeringDesignOptimization", "max_forks_repo_head_hexsha": "eb5b5e4edd773aef629f59aea8a9771af41bd224", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1777777778, "max_line_length": 68, "alphanum_fraction": 0.5697263901, "include": true, "reason": "import numpy,import sympy", "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.9073122307591682, "lm_q1q2_score": 0.8623195075175418}}
{"text": "#Ejercicio 0\n#Lean el capitulo 5 del Landau (ver el programa del curso).\n\nimport numpy as np\nimport matplotlib.pylab as plt\n\n#Ejercicio 1\n# Usando los generadores de numeros aleatorios de numpy (https://docs.scipy.org/doc/numpy-1.15.1/reference/routines.random.html):\n# a) Genere 1000 numeros aleatorios que sigan una distribucion uniforme y esten entre -10 y 10. Haga un histograma y guardelo sin mostrarlo en un archivo llamado uniforme.pdf\n\nuniforme=(np.random.random(1000)*20)-10\n\nplt.figure()\nplt.hist(uniforme,bins=50)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Distribución Uniforme\")\nplt.grid()\nplt.savefig(\"uniforme.png\")\nplt.close()\n\n# a) Genere 1000 numeros aleatorios que sigan una distribucion gausiana centrada en 17 y de sigma 5. Haga un histograma y guardelo sin mostrarlo en un archivo llamado gausiana.pdf\n\ngaussiana=np.random.normal(17,5.0,1000)\n\nplt.figure()\nplt.hist(gaussiana,bins=50)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Distribución Gausiana\")\nplt.grid()\nplt.savefig(\"gausiana.png\")\nplt.close()\n\n# Ejercicio 2\n# Escriba un programa en Python que: \n# Genere puntos aleatorios distribuidos uniformemente dentro de un cuadrado de lado 30.5. Grafique sus puntos y guarde la grafica sin mostrarla en un archivo llamado cuadrado.pdf.\n\nxcuad=np.random.random(3000)*30\nycuad=np.random.random(3000)*5\n\nplt.figure()\nplt.scatter(xcuad,ycuad)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Cuadrado 30x5\")\nplt.grid()\nplt.savefig(\"cuadrado.png\")\nplt.close()\n\n# Genere puntos aleatorios distribuidos uniformemente dentro de circulo de radio 23. Grafique sus puntos y guarde la grafica sin mostrarla en un archivo llamado circulo.pdf.\n\nxr=(np.random.random(3000)*46)-23\nyr=(np.random.random(3000)*46)-23\nxcirc=[]\nycirc=[]\n\nfor i in range(len(xr)):\n    s=np.sqrt((xr[i]**2)+(yr[i]**2))\n    if(s<=23):\n        xcirc.append(xr[i])\n        ycirc.append(yr[i])\n        \nplt.figure()\nplt.scatter(xcirc,ycirc)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Circulo de rad 23\")\nplt.grid()\nplt.savefig(\"circulo.png\")\nplt.close()\n\n# Ejercicio 3 \n# Lean sobre caminatas aleatorias.\n\n\n# Ejercicio 4\n# Tome los puntos distribuidos aleatoriamente dentro del cuadrado y haga que cada punto siga una caminata aleatoria de 100 pasos. \n# La magnitud de los pasos de esta caminata debe seguir una distribucion gaussiana centrada en el punto y de sigma igual a 0.25\n# Implemente condiciones de frontera periodicas: si un punto se \"sale\" de cuadrado por un lado, \"entra\" por el otro\n\ndef RW(xini,yini,N=100,sigma=0.25):\n    x=np.zeros(N)\n    y=np.zeros(N)\n    x[0]=xini\n    y[0]=yini\n    \n    i=0\n    while(i<100):        \n        paso=np.random.normal(scale=sigma)\n        angulo=np.random.random()*2*np.pi\n        \n        xpaso=paso*np.cos(angulo)\n        ypaso=paso*np.sin(angulo)\n        xpaso+=x[i]\n        ypaso+=y[i]\n        \n        if(xpaso<30 and xpaso>0):\n            if(ypaso<5 and ypaso>0):\n                x[i]=xpaso\n                y[i]=ypaso\n                \n        i+=1\n    \n    return x,y\n\n\n    \n\n# Grafique la distribucion final de puntos y guarde dicha grafica sin mostrarla en un archivo llamado DistCaminata.pdf\n# Grafique la caminata de UNO de sus puntos y guarde dicha grafica sin mostrarla en un archivo llamado puntoCaminata.pdf\n\nxipunto=xcuad[np.random.randint(len(xcuad))]\nyipunto=ycuad[np.random.randint(len(xcuad))]\n\nxpunto,ypunto=RW(xipunto,yipunto)\nprint(xpunto)\nprint(ypunto)\n\nplt.figure()\nplt.plot(xpunto,ypunto)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Caminata de uno\")\nplt.grid()\nplt.savefig(\"puntoCaminata.png\")\nplt.close()\n\n# Repita el proceso para sigma = 0.00025 y sigma= 2.5. Grafique la caminata de UNO de sus puntos para los distintos sigmas y guardela sin mostrarla en sigmaCaminata.pdf\n\n# Repita el proceso para condiciones abiertas: si un punto se \"sale\" del cuadrado deja de ser considerado en la simulacion.\n\n# Si le queda tiempo puede:\n\n##################################################################################################################################################################\n############################################################ Ejercicio  ##########################################################################\n##################################################################################################################################################################\n\n#difusion: una gota de crema en un Cafe.\n#\n#Condiciones iniciales:\n#Cafe: 10000 particulas distribuidas uniformemente dentro de un circulo de radio igual a raiz de 230\n#Crema: 100 particulas distribuidas uniformemente dentro de un circulo de radio igual a raiz de 2\n#\n#Nota: si su codigo se esta demorando mucho en correr, puede usar 1000 particulas de cafe en vez de 10000.\n#\n# 1) Haga una grafica de las condiciones iniciales donde los dos tipos de particulas tengan distintos colores. Guarde dicha grafica sin mostrarla en CafeLecheIni.pdf\n#\n#2) Todas las particulas deben hacer una caminata aleatoria de 1000 pasos. Los pasos en las coordenadas x y deben seguir una distribucion gausiana de sigma 2.5. Si va a usar coordenadas polares elija un sigma apropiado.\n#\n#3) Condiciones de frontera: implemente unas condiciones tales que si la particulas \"sale\" del circulo, usted vuelva a dar el paso. Si no puede implementar solo las condiciones antes descritas, debe al menos escribir comentarios explicando que hace cada linea de codigo de las condiciones propuestas (comentado abajo)\n#\n# 4) Haga una grafica de las posiciones finales de las particulas despues de la caminata donde los dos tipos de particulas tengan distintos colores. Guarde dicha grafica sin mostrarla en CafeLecheFin.pdf\n#\n\nimport numpy as np\nimport matplotlib.pylab as plt\n\n\n#Una posible implementacion de condiciones de frontera. Trate de hacer la suya propia sin usar esta. \n#Si usa esta (obtiene menos puntos) debe comentar cada una de las lineas explicando en palabras que hace el codigo. Debe tambien naturalmente usar los nombres de variables que uso en el resto de su codigo propio.\n#indexcafe=np.where((xcafenuevo*xcafenuevo+ycafenuevo*ycafenuevo)>230)\n#indexcrema=np.where((xcremanuevo*xcremanuevo+ycremanuevo*ycremanuevo)>230)\n#while(len(indexcafe[0])>1):\n#\txcafenuevo[indexcafe]=xcafe[indexcafe] + np.random.normal(0,sigma)\n#\tycafenuevo[indexcafe]=ycafe[indexcafe] + np.random.normal(0,sigma)\n#\tindexcafe=np.where((xcafenuevo*xcafenuevo+ycafenuevo*ycafenuevo)>=230)\n#while(len(indexcrema[0])>1):\n#\txcremanuevo[indexcrema]=xcrema[indexcrema] + np.random.normal(0,sigma)\n#\tycremanuevo[indexcrema]=ycrema[indexcrema] + np.random.normal(0,sigma)\n#\tindexcrema=np.where((xcremanuevo*xcremanuevo+ycremanuevo*ycremanuevo)>=230) \n\n\n\n\t\n", "meta": {"hexsha": "0724b13b064e3d087adc794f644c9412a275d913", "size": 6659, "ext": "py", "lang": "Python", "max_stars_repo_path": "S7C1/CendalesLuis_S7C1Random.py", "max_stars_repo_name": "LuisCendales/M-todos_Computacionales", "max_stars_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "S7C1/CendalesLuis_S7C1Random.py", "max_issues_repo_name": "LuisCendales/M-todos_Computacionales", "max_issues_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "S7C1/CendalesLuis_S7C1Random.py", "max_forks_repo_name": "LuisCendales/M-todos_Computacionales", "max_forks_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8352272727, "max_line_length": 317, "alphanum_fraction": 0.6907944136, "include": true, "reason": "import numpy", "num_tokens": 1835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.9073122219871936, "lm_q1q2_score": 0.8623194979061666}}
{"text": "'''\nRecursion - Fibonacci Sequence\n\n'''\nimport functools\nimport math\nfrom numpy import matrix\n\n\ndef fibonacci_oneliner(n):\n    '''\n    Generate Fibonacci Sequence from F_0 to F_n\n\n    returns list[F_0, F_1, ..., F_n]\n    Adapted from Mayer2020 using one python line of code.\n    '''\n    fibs = functools.reduce(lambda x, _: x + [x[-2] + x[-1]],\n                            [0] * (n - 1), [0, 1])\n    return fibs\n\n\n@functools.lru_cache(None)  # Comment this line to have a non-memoized version\ndef fibonacci_recursive(n):\n    '''Recursive F_n\n    '''\n    if n < 0:\n        raise ValueError('n must be non negative integer.')\n    elif n > 1:\n        return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)\n    else:\n        return n\n\n\n# Static constants for Binet's and rounding implementations\n__denom = 5 ** 0.5\n__golden = (1 + __denom) / 2  # Golden Ratio\n__psi = (1 - __denom) / 2\n\n\ndef fibonacci_binet(n):\n    r'''\n    Closed-form expression: Binet's Formula\n    F_n = \\frac{}{\\sqrt{5}}\n\n    Golden ratio $\\phi = \\frac{1 + \\sqrt{5}}{2}$\n    \\phi^2 = \\phi + 1\n    \\psi = (1 - \\sqrt{5}) / 2\n    \\psi^2 =  \\psi + 1\n\n    Rounding errors above 71 (i.e. n < 72)\n    '''\n    if n < 0:\n        raise ValueError('n must be non negative integer.')\n    elif n > 71:\n        raise ValueError('This function has rounding errors above n=71.')\n    else:\n        return int((__golden ** n - __psi ** n) / __denom)\n\n\ndef fibonacci_rounding(n):\n    \"\"\"\n    Fast Fibonacci using rounding\n\n    It is limited to n < 71\"\"\"\n    if n < 0:\n        raise ValueError('Fibs for negative values are not defined.')\n    elif n > 70:\n        raise ValueError('This function has rounding errors above n=70.')\n    return round(math.pow(__golden, n) / __denom)\n\n\ndef fibonacci_matrix(n):\n    '''\n    Fibonacci number F_n using matrix powers\n\n    From bebidek2018 <https://stackoverflow.com/questions/3323001/what-is-the-maximum-recursion-depth-in-python-and-how-to-increase-it>\n    '''\n    return (matrix('0 1; 1 1', dtype='object') ** n).item(1)\n\n\nclass Solution:\n    def fib(self, N: int) -> int:\n        if N <= 1:\n            return N\n        F = [0] * (N + 1)\n        F[1] = 1\n        for n in range(2, N + 1):\n            F[n] = F[n-1] + F[n-2]\n        return F[N]\n\n    def fib2(self, N: int) -> int:\n        if N <= 1:\n            return N\n        F = [0, 1, 1]\n        for n in range(3, N + 1):\n            F[0], F[1], F[2] = F[1], F[2], F[-1] + F[-2]\n        return F[-1]\n\n\nif __name__ == '__main__':\n    n = 45  # n > 1 # 70 is the limit for fast_fib\n    fibs = fibonacci_oneliner(n)\n\n    # Some known values to verify\n    if n >= 70:\n        assert fibs[70] == 190392490709135\n        assert fibs[71] == 308061521170129\n\n    # lr = lb = []\n    if n < 72:\n        lb = ([fibonacci_binet(ni) for ni in range(n + 1)])\n        print(f'lb\\n{lb}')\n        assert fibs == lb\n    if n < 71:\n        lf = ([fibonacci_rounding(ni) for ni in range(n + 1)])\n        print(lf)\n        assert fibs == lf, \"Disc\"\n\n    if n < 5000:\n        lr = ([fibonacci_recursive(ni) for ni in range(n + 1)])\n        assert fibs == lr\n        # print(f'lr\\n{lr}')\n    lm = [fibonacci_matrix(ni) for ni in range(n + 1)]\n    assert lm == fibs\n\n    # From Wolfram|Alpha: Fibo[100] = 354224848179261915075\n    fibo100 = 354224848179261915075\n    print(f'{fibo100=}')\n    assert fibonacci_recursive(100) == fibo100\n", "meta": {"hexsha": "7288d0a7bb8b8f20b905609558a5356150157c17", "size": 3367, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/code07_fibo.py", "max_stars_repo_name": "krontzo/prog2021", "max_stars_repo_head_hexsha": "8fbf7ef9bcee2cc05753b6f26a0280da5e5feebf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-08T20:58:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T20:58:54.000Z", "max_issues_repo_path": "src/code07_fibo.py", "max_issues_repo_name": "krontzo/prog2021", "max_issues_repo_head_hexsha": "8fbf7ef9bcee2cc05753b6f26a0280da5e5feebf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/code07_fibo.py", "max_forks_repo_name": "krontzo/prog2021", "max_forks_repo_head_hexsha": "8fbf7ef9bcee2cc05753b6f26a0280da5e5feebf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9, "max_line_length": 135, "alphanum_fraction": 0.5631125631, "include": true, "reason": "from numpy", "num_tokens": 1056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.9073122150949273, "lm_q1q2_score": 0.862319491355681}}
{"text": "#\t\n#\troot-regula-falsi.py\n#\tFinding root using regula falsi method\n#\t\n#\tSparisoma Viridi | https://butiran.github.io/\n#\t\n#\tExecute: py root-regula-falsi.js\n#\t\n#\t20210210\n#\t0527 Typo node --> py, use newton-raphson.py as template.\n#   0827 Continue at campus.\n#   1001 Continue after archiving lab modules.\n#   1028 Try compile again after install Python 3.9.1 64 bit.\n#\t\n\n# Import necessary libraries\nimport numpy as np\n\n\n# Define a test function\ndef test_function(x):\n\ty3 = 0.01 * x * x * x\n\ty2 = -0.2252 * x * x\n\ty1 = 0.4136 * x\n\ty0 = 1.808\n\ty = y3 + y2 + y1 + y0\n\treturn y\n\n\n\n# Define input\nf = test_function\nx1 = 3\nx2 = 6\neps = 1E-10\nn = 0\nmaxstep = 40\n\n# Define default message and parameter\nxroot = \"not found\"\nSHOW_PROGRESS = True\n\n# Do iteration\nNstep = 0\nx = []\nx.append(x1)\nx.append(x2)\nfroot = np.abs(f(x[n]))\n\nwhile froot > eps and n < maxstep - 1:\n\tx.append(x[0] - ((x[n+1] - x[0])/(f(x[n+1]) - f(x[0]))) * f(x[0]))\n\t\n\tfroot = np.abs(f(x[n+2]))\n\tif froot < eps:\n\t\txroot = x[n+2]\n\t\n\tif SHOW_PROGRESS:\n\t\tif n == 0:\n\t\t\tfn = f(x[n])\n\t\t\tprint(\"n\\tx\\tf(x)\")\n\t\t\tprint(n, x[n], f(x[n]), sep=\"\\t\")\n\t\t\tprint(n, x[n+1], f(x[n+1]), sep=\"\\t\")\n\t\tprint(n+1, x[n+2], f(x[n+2]), sep=\"\\t\") \n\t\n\tn += 1\n\nNstep = n+2\n\nif SHOW_PROGRESS:\n\tprint()\n\n# Display result\nprint(\"f(x)  0.01x^3 - 0.2192x^2 + 0.3056x + 1.568\");\nprint(\"x1    \", x1, sep=\"\")\nprint(\"x2    \", x2, sep=\"\")\nprint(\"ε     \", eps, sep=\"\")\nprint(\"Nstep \", Nstep, sep=\"\")\nprint(\"xroot \", xroot, sep=\"\")\n", "meta": {"hexsha": "1007bcafdfb53b7a0cef5bb4f17b473c61c3d2f5", "size": 1456, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/py/fi3201/root/root-regula-falsi.py", "max_stars_repo_name": "butiran/butiran.github.io", "max_stars_repo_head_hexsha": "bf99f55819a140190e5bda8f9675109ef607eb9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/py/fi3201/root/root-regula-falsi.py", "max_issues_repo_name": "butiran/butiran.github.io", "max_issues_repo_head_hexsha": "bf99f55819a140190e5bda8f9675109ef607eb9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-08T13:57:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-08T14:18:05.000Z", "max_forks_repo_path": "src/py/fi3201/root/root-regula-falsi.py", "max_forks_repo_name": "butiran/butiran.github.io", "max_forks_repo_head_hexsha": "bf99f55819a140190e5bda8f9675109ef607eb9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-08T13:54:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-08T13:54:23.000Z", "avg_line_length": 18.4303797468, "max_line_length": 67, "alphanum_fraction": 0.5858516484, "include": true, "reason": "import numpy", "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.9219218284193595, "lm_q1q2_score": 0.8623163662202997}}
{"text": "\r\nimport numpy as np\r\n\r\n__all__ = ['tstatistic',\r\n           'nantstatistic',\r\n           'diffmean']\r\n\r\ndef diffmean(a, b, axis=0):\r\n    \"\"\"Difference of means statistic.\r\n\r\n    Parameters\r\n    ----------\r\n    a,b : ndarray with shapes equal along all dims except axis\r\n        Input data for the calculation.\r\n    axis : int\r\n        Specify the axis along which the statistic will be computed.\r\n\r\n    Returns\r\n    -------\r\n    dm : ndarray with one less dimension\"\"\"\r\n    return a.mean(axis=axis) - b.mean(axis=axis)\r\n\r\ndef tstatistic(a, b, axis=0, equal_var=True):\r\n    \"\"\"Computes a two-sample t-statistic on a and b along the specific axis\r\n    Code is lifted from scipy.stats.ttest_ind except that there is no\r\n    calculation of the associated p-value\r\n\r\n    Parameters\r\n    ----------\r\n    a,b : ndarray with shapes equal along all dims except axis\r\n        Input data for the calculation.\r\n    axis : int\r\n        Specify the axis along which the statistic will be computed.\r\n    equal_var : bool\r\n        Specify if the statistic will use a pooled estimate of the variance (True)\r\n        or if it will make no assumption about equal variance (False).\r\n\r\n    Returns\r\n    -------\r\n    t : ndarray with one less dimension\"\"\"\r\n    v1 = np.var(a, axis, ddof=1)\r\n    v2 = np.var(b, axis, ddof=1)\r\n    n1 = a.shape[axis]\r\n    n2 = b.shape[axis]\r\n\r\n    if equal_var:\r\n        df = n1 + n2 - 2\r\n        svar = ((n1 - 1) * v1 + (n2 - 1) * v2) / float(df)\r\n        denom = np.sqrt(svar * (1.0 / n1 + 1.0 / n2))\r\n    else:\r\n        vn1 = v1 / n1\r\n        vn2 = v2 / n2\r\n        df = ((vn1 + vn2)**2) / ((vn1**2) / (n1 - 1) + (vn2**2) / (n2 - 1))\r\n\r\n        # If df is undefined, variances are zero (assumes n1 > 0 & n2 > 0).\r\n        # Hence it doesn't matter what df is as long as it's not NaN.\r\n        df = np.where(np.isnan(df), 1, df)\r\n        denom = np.sqrt(vn1 + vn2)\r\n\r\n    d = np.mean(a, axis) - np.mean(b, axis)\r\n    t = np.divide(d, denom)\r\n    return t\r\n\r\ndef nantstatistic(a, b, axis = 0, equal_var = True):\r\n    \"\"\"Computes a two-sample t-statistic on a and b along the specific axis\r\n    Uses nan* functions which can be slightly slower.\r\n    Code is lifted from scipy.stats.ttest_ind except that there is no\r\n    calculation of the associated p-value\r\n\r\n    Parameters\r\n    ----------\r\n    a,b : ndarray with shapes equal along all dims except axis\r\n        Input data for the calculation.\r\n    axis : int\r\n        Specify the axis along which the statistic will be computed.\r\n    equal_var : bool\r\n        Specify if the statistic will use a pooled estimate of the variance (True)\r\n        or if it will make no assumption about equal variance (False).\r\n\r\n    Returns\r\n    -------\r\n    t : ndarray with one less dimension\r\n    \"\"\"\r\n\r\n    v1 = np.nanvar(a, axis, ddof=1)\r\n    v2 = np.nanvar(b, axis, ddof=1)\r\n    n1 = a.shape[axis]\r\n    n2 = b.shape[axis]\r\n\r\n    if equal_var:\r\n        df = n1 + n2 - 2\r\n        svar = ((n1 - 1) * v1 + (n2 - 1) * v2) / np.float(df)\r\n        denom = np.sqrt(svar * (1.0 / n1 + 1.0 / n2))\r\n    else:\r\n        vn1 = v1 / n1\r\n        vn2 = v2 / n2\r\n        df = ((vn1 + vn2)**2) / ((vn1**2) / (n1 - 1) + (vn2**2) / (n2 - 1))\r\n\r\n        # If df is undefined, variances are zero (assumes n1 > 0 & n2 > 0).\r\n        # Hence it doesn't matter what df is as long as it's not NaN.\r\n        df = np.where(np.isnan(df), 1, df)\r\n        denom = np.sqrt(vn1 + vn2)\r\n\r\n    d = np.nanmean(a, axis) - np.nanmean(b, axis)\r\n    t = np.divide(d, denom)\r\n    return t\r\n\r\n'''TODO: implement in numba so they can be used in a numbized permutation test\r\n\"\"\"Attempt to import numba and define numba compiled versions of these functions\"\"\"\r\nimport os\r\nimport sys\r\ntry:\r\n    import numba as nb\r\n    print 'mytstats: Successfully imported numba version %s' % (nb.__version__)\r\n    NB_SUCCESS = True\r\nexcept OSError:\r\n    try:\r\n        \"\"\"On Windows it is neccessary to be on the same drive as the LLVM DLL\r\n        in order to import numba without generating a \"Windows Error 161: The specified path is invalid.\"\"\"\r\n        curDir = os.getcwd()\r\n        targetDir = os.path.splitdrive(sys.executable)[0]\r\n        os.chdir(targetDir)\r\n        import numba as nb\r\n        print 'mytstats: Successfully imported numba version %s' % (nb.__version__)\r\n        NB_SUCCESS = True\r\n    except OSError:\r\n        NB_SUCCESS = False\r\n        print 'mytstats: Could not load numba\\n(may be a path issue try starting python in C:\\\\)'\r\n    finally:\r\n        os.chdir(curDir)\r\nexcept ImportError:\r\n    NB_SUCCESS = False\r\n    print 'mytstats: Could not load numba'\r\n\r\n\"\"\"TODO: (1) Test numba functions (this code is just copied from above)\r\n             if the function can just be decorated then do that,\r\n             but i think it may need to be modified\r\n\r\n         (2) Add numba permutation function that utlizes these statistics\r\n             (this is where the speed-up will happen)\"\"\"\r\n\r\nif NB_SUCCESS and False:\r\n    __all__.extend(['nb_tstatistic', 'nb_nantstatistic'])\r\n\r\n    @nb.jit(nb.float64[:](nb.float64[:],nb.float64[:], nb.int32, nb.boolean), nopython = True)\r\n    def nb_tstatistic(a, b, axis, equal_var):\r\n        v1 = np.var(a, axis, ddof=1)\r\n        v2 = np.var(b, axis, ddof=1)\r\n        n1 = a.shape[axis]\r\n        n2 = b.shape[axis]\r\n\r\n        if equal_var:\r\n            df = n1 + n2 - 2\r\n            svar = ((n1 - 1) * v1 + (n2 - 1) * v2) / np.float(df)\r\n            denom = np.sqrt(svar * (1.0 / n1 + 1.0 / n2))\r\n        else:\r\n            vn1 = v1 / n1\r\n            vn2 = v2 / n2\r\n            df = ((vn1 + vn2)**2) / ((vn1**2) / (n1 - 1) + (vn2**2) / (n2 - 1))\r\n\r\n            # If df is undefined, variances are zero (assumes n1 > 0 & n2 > 0).\r\n            # Hence it doesn't matter what df is as long as it's not NaN.\r\n            df = np.where(np.isnan(df), 1, df)\r\n            denom = np.sqrt(vn1 + vn2)\r\n\r\n        d = np.mean(a, axis) - np.mean(b, axis)\r\n        t = np.divide(d, denom)\r\n        return t\r\n\r\n    @nb.jit(nb.float64[:](nb.float64[:],nb.float64[:], nb.int, nb.boolean), nopython = True)\r\n    def nb_nantstatistic(a, b, axis, equal_var):\r\n        v1 = np.nanvar(a, axis, ddof=1)\r\n        v2 = np.nanvar(b, axis, ddof=1)\r\n        n1 = a.shape[axis]\r\n        n2 = b.shape[axis]\r\n\r\n        if equal_var:\r\n            df = n1 + n2 - 2\r\n            svar = ((n1 - 1) * v1 + (n2 - 1) * v2) / float(df)\r\n            denom = np.sqrt(svar * (1.0 / n1 + 1.0 / n2))\r\n        else:\r\n            vn1 = v1 / n1\r\n            vn2 = v2 / n2\r\n            df = ((vn1 + vn2)**2) / ((vn1**2) / (n1 - 1) + (vn2**2) / (n2 - 1))\r\n\r\n            # If df is undefined, variances are zero (assumes n1 > 0 & n2 > 0).\r\n            # Hence it doesn't matter what df is as long as it's not NaN.\r\n            df = np.where(np.isnan(df), 1, df)\r\n            denom = np.sqrt(vn1 + vn2)\r\n\r\n        d = np.nanmean(a, axis) - np.nanmean(b, axis)\r\n        t = np.divide(d, denom)\r\n        return t\r\n\r\n'''", "meta": {"hexsha": "86f94ba724a90bd2f2a09d55363f425e1445cb15", "size": 6918, "ext": "py", "lang": "Python", "max_stars_repo_path": "mytstats.py", "max_stars_repo_name": "victorfica/utils", "max_stars_repo_head_hexsha": "b61935a860838a0e70afde7c9ecf2c68f51a2c4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-12-16T01:23:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-27T11:41:43.000Z", "max_issues_repo_path": "mytstats.py", "max_issues_repo_name": "victorfica/utils", "max_issues_repo_head_hexsha": "b61935a860838a0e70afde7c9ecf2c68f51a2c4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-06T23:47:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T23:48:33.000Z", "max_forks_repo_path": "mytstats.py", "max_forks_repo_name": "victorfica/utils", "max_forks_repo_head_hexsha": "b61935a860838a0e70afde7c9ecf2c68f51a2c4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-04-29T14:04:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-06T23:49:34.000Z", "avg_line_length": 35.4769230769, "max_line_length": 108, "alphanum_fraction": 0.5508817577, "include": true, "reason": "import numpy,from scipy,import numba", "num_tokens": 2027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399086356109, "lm_q2_score": 0.8887588023318196, "lm_q1q2_score": 0.8623092591735196}}
{"text": "import math\nimport numpy as np\nfrom collections import Counter\n#-------------------------------------------------------------------------\n\n#-----------------------------------------------\n#    Utility functions \n#-----------------------------------------------\n\n#--------------------------\ndef entropy(Y):\n    '''\n        Compute the entropy of a list of values.\n        Input:\n            Y: a list of values, a numpy array of int/float/string values.\n        Output:\n            e: the entropy of the list of values, a float scalar\n    '''\n    \n    n = len(Y) # total number of values \n    c = Counter(Y) # create a counter on the list\n    e = 0.\n    for k,v in c.items():\n        p = v/n\n        e -=  p*math.log(p,2)\n    return e  \n#--------------------------\ndef conditional_entropy(Y,X):\n    '''\n        Compute the conditional entropy of y given x.\n        Input:\n            Y: a list of values, a numpy array of int/float/string values.\n            X: a list of values, a numpy array of int/float/string values.\n        Output:\n            ce: the conditional entropy of y given x, a float scalar\n    '''\n    n = len(Y) # total number of values \n    c = Counter(X) # create a counter on the list\n    ce = 0.\n    for k,v in c.items():\n        ce += entropy(Y[X==k])*v/n\n    return ce \n#--------------------------\ndef information_gain(Y,X):\n    '''\n        Compute the information gain of y after splitting over attribute x\n        Input:\n            X: a list of values, a numpy array of int/float/string values.\n            Y: a list of values, a numpy array of int/float/string values.\n        Output:\n            g: the information gain of y after splitting over x, a float scalar\n    '''\n    g = entropy(Y) - conditional_entropy(Y,X) \n    return g\n\n#-----------------------------------------------\n#     A Decision Tree Node\n#-----------------------------------------------\nclass Node:\n    '''\n        The class of a Decision Tree Node \n\n        Properties\n            isleaf: whether or not this node is a leaf node, a boolean scalar\n            p: the label to be predicted on the node (i.e., most common label in the node).\n            i: the index of the attribute being tested in the node, an integer scalar \n            th: the threshold on the attribute, a float scalar.\n            C1: the first child node for values smaller than threshold\n            C2: the second child node for values larger than threshold\n    '''\n    #--------------------------\n    def __init__(self,X,Y):\n        '''\n        Create a decision tree node\n        Inputs: \n            X: the data instances in the node, a numpy matrix of shape p by n.\n               Each element can be int/float.\n               Here n is the number data instances in the node, p is the number of attributes.\n               Each row of X represents one attribute, each column of X represents a data instance.\n            Y: the class labels in the node, a numpy array of length n.\n               Each element can be int/float/string.\n        '''\n        assert len(X)>0\n        assert len(Y)>0\n        self.X = X\n        self.Y = Y\n        # compute the most common label in the node for prediction\n        self.p = Counter(Y).most_common(1)[0][0]\n        # test whether or not if the node is a leaf node\n        self.isleaf = True\n        for f in X:\n            if not len(np.unique(f))==1:\n                self.isleaf = False\n                break\n        if (len(np.unique(Y))==1):\n            self.isleaf = True\n\n    #--------------------------\n    def cutting_points(self,i):\n        '''\n            Find all possible cutting points in the i-th attribute. \n            (1) sort unique attribute values in X, like, x1, x2, ..., xn\n            (2) consider splitting points of form (xi + x(i+1))/2 \n            (3) only consider splitting between instances of different classes\n            Input:\n                i: the index of the attribute to be used, an integer scalar \n            Output:\n                cp: the list of  potential cutting points, a float numpy vector. \n        '''\n        x = self.X[i] # the i-th attribute\n        cp = [] \n        z = sorted(np.unique(x)) # unique values in the attribute\n        for i in range(len(z)-1):\n            idx = np.logical_or(x==z[i], x==z[i+1])\n            ys = self.Y[idx]\n            if len(np.unique(ys))>1: \n                cp.append((z[i] + z[i+1])/2.) # add a candidate cutting point\n        return cp\n   \n    #--------------------------\n    def best_threshold(self,i):\n        '''\n            Find the best threshold among all possible cutting points in the i-th attribute. \n            Input:\n                i: the index of the attribute to be used, an integer scalar \n            Output:\n                th: the best threshold, a float scalar. \n                g: the information gain by using the best threshold, a float scalar. \n        '''\n        X = self.X[i] # the i-th attribute\n        cp = self.cutting_points(i)\n        assert len(cp)>0\n        g= -math.inf\n        for c in cp:\n            x = X>=c\n            g_new = information_gain(self.Y,x)\n            if g_new>g:\n                g = g_new\n                th = c\n        return th,g \n    #--------------------------\n    def best_attribute(self):\n        '''\n            Find the best attribute to split the node. The attributes have continuous values (int/float).\n            Here we use information gain to evaluate the attributes. \n            Output:\n                i: the index of the attribute to split, an integer scalar\n                th: the threshold of the attribute to split, a float scalar\n        '''\n        g= -math.inf\n        for k in range(self.X.shape[0]):\n            if len(np.unique(self.X[k]))>1:\n                tk,gk = self.best_threshold(k)\n                if gk>g:\n                    g = gk\n                    self.i = k\n                    self.th = tk\n\n    #--------------------------\n    def add_children_nodes(self):\n        '''\n            build the children nodes C1 and C2 with the best attribute and threshold in the node \n            Output:\n                C1: the child node for values smaller than threshold\n                C2: the child node for values larger than (or equal to) threshold\n        '''\n        self.best_attribute()\n        i,th = self.i, self.th \n        x = self.X[i] \n        self.C1 = Node(self.X[:,x<th], self.Y[x<th])\n        self.C2 = Node(self.X[:,x>=th], self.Y[x>=th])\n\n    #--------------------------\n    def build_tree(self):\n        '''\n            Recursively build a subtree from the current tree node.\n        '''\n        if self.isleaf==False: \n            self.add_children_nodes()\n            self.C1.build_tree()\n            self.C2.build_tree()\n    #--------------------------\n    def predict_1(self,x):\n        '''\n            Using the decision tree starting from the current node to predict the label on one test instance\n            Input:\n                x: the attribute vector, a numpy vector of shape p.\n                   Each attribute value can be int/float\n            Output:\n                p: the label prediction on the test instance, a scalar, can be int/float/string.\n        '''\n        if self.isleaf:\n            return self.p\n        if x[self.i] <= self.th:\n            return self.C1.predict_1(x)\n        else:\n            return self.C2.predict_1(x)\n\n\n#-----------------------------------------------\n#     A Decision Tree \n#-----------------------------------------------\nclass DecisionTree:\n    '''\n        The Class of Decision Tree\n        Properties\n            root: the root node of the decision tree\n    '''\n    #--------------------------\n    def __init__(self,X,Y):\n        '''\n        Create a decision tree\n        Inputs: \n            X: the data instances in the node, a numpy matrix of shape p by n.\n               Each element can be int/float.\n               Here n is the number data instances in the node, p is the number of attributes.\n               Each row of X represents one attribute, each column of X represents a data instance.\n            Y: the class labels in the node, a numpy array of length n.\n               Each element can be int/float/string.\n        '''\n        self.root = Node(X,Y)  # create root node\n        self.root.build_tree() # build the tree\n\n    #--------------------------\n    def predict_1(self,x):\n        '''\n            Using the decision tree to predict the label on one test instance\n            Input:\n                x: the attribute vector, a numpy vector of shape p.\n                   Each attribute value can be int/float\n            Output:\n                p: the label prediction on the test instance, a scalar, can be int/float/string.\n        '''\n        return self.root.predict_1(x)\n\n\n    #--------------------------\n    def predict(self,X):\n        '''\n            Using the decision tree to predict the label on all test instances\n            Input:\n                X: the feature matrix of all test instances, a numpy matrix of shape p by n.\n                   Each element can be int/float.\n                   Here n is the number data instances in the dataset, p is the number of attributes.\n            Output:\n                P: the predicted class labels on all test instances, a numpy array of length n.\n                   Each element can be int/float/string.\n        '''\n        return np.array([self.predict_1(x) for x in X.T])\n\n", "meta": {"hexsha": "3d1597a417b83dae59f003dde5011c2673aea0e5", "size": 9427, "ext": "py", "lang": "Python", "max_stars_repo_path": "homework6/tree.py", "max_stars_repo_name": "jojonium/CS-539-Machine-Learning", "max_stars_repo_head_hexsha": "a1d2b07d0e092faf5580b44f8d4f01d02ea89564", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework6/tree.py", "max_issues_repo_name": "jojonium/CS-539-Machine-Learning", "max_issues_repo_head_hexsha": "a1d2b07d0e092faf5580b44f8d4f01d02ea89564", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework6/tree.py", "max_forks_repo_name": "jojonium/CS-539-Machine-Learning", "max_forks_repo_head_hexsha": "a1d2b07d0e092faf5580b44f8d4f01d02ea89564", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5577689243, "max_line_length": 108, "alphanum_fraction": 0.507054206, "include": true, "reason": "import numpy", "num_tokens": 2010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399077750858, "lm_q2_score": 0.888758793492457, "lm_q1q2_score": 0.8623092498324181}}
{"text": "import numpy as np\n\n#Questions on NumPy Statistics\n# Compute the median of the flattened NumPy array\n#median Compute the median along the specified axis.\nnp.median(np.array([1, 2, 3, 4, 5, 6, 7])) \n\n# Find Mean of a List of Numpy Array\n#mean Compute the arithmetic mean along the specified axis.\nnp.mean(np.array([1, 2, 3]))\n\n# Calculate the mean of array ignoring the NaN value\n#nanmean Compute the arithmetic mean along the specified axis, ignoring NaNs.\nnp.nanmean(np.array([[20, 15, 37], [47, 13, np.nan]]))\n\n# Get the mean value from given matrix\n#matrix.mean Return mean value from given matrix\nnp.matrix('[64, 1; 12, 3]').mean()\n\n# Compute the variance of the NumPy array\n# var Return Variance of the array (a scalar value if axis is none)\n# or array with variance values along specified axis.\nnp.var([20, 2, 7, 1, 34]  , dtype = np.float32)\n\n# Compute the standard deviation of the NumPy array\n# std Return tandard Deviation of the array (a scalar value if axis is none) \n# or array with standard deviation values along specified axis.\nnp.std([20, 2, 7, 1, 34]  , dtype = np.float32)\n\n# Compute pearson product-moment correlation coefficients of two given NumPy arrays\n# corrcoef Pearson product-moment correlation coefficients\nnp.corrcoef( np.array([0, 1, 2]), np.array([3, 4, 5])) \n\n# Calculate the mean across dimension in a 2D NumPy array\nnp.mean(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), axis=1)\n\n# Calculate the average, variance and standard deviation in Python using NumPy\n# average Return Default is False. If True, the tuple is returned, otherwise \n# only the average is returned\nnp.average([2, 4, 4, 4, 5, 5, 7, 9] )\nnp.var([20, 2, 7, 1, 34]  , dtype = np.float32)\nnp.std([20, 2, 7, 1, 34]  , dtype = np.float32)\n\n# Describe a NumPy Array in Python\n# amin takes a NumPy array as an argument and returns the minimum\n# amax takes a NumPy array as an argument and returns maximum.\n# ptp takes a NumPy array as an argument and returns the range of the data.\narr = np.array([4, 5, 8, 5, 6, 4, 9, 2, 4, 3, 6]) \n# measures of central tendency \nmean = np.mean(arr) \nmedian = np.median(arr) \n  # measures of dispersion \nnp.amin(arr) \nnp.amax(arr) \nnp.ptp(arr) \nnp.var(arr) \nnp.std(arr) ", "meta": {"hexsha": "0ea51169ad25af62a34efc72a05705e540b39b05", "size": 2199, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumpyTutorial/Questions on NumPy Statistics.py", "max_stars_repo_name": "CarlosW1998/DigitalImageProcessing", "max_stars_repo_head_hexsha": "69365877e07b676f13487585ffdf029a243b0fa8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-09T19:54:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:54:48.000Z", "max_issues_repo_path": "NumpyTutorial/Questions on NumPy Statistics.py", "max_issues_repo_name": "CarlosW1998/DigitalImageProcessingClass", "max_issues_repo_head_hexsha": "69365877e07b676f13487585ffdf029a243b0fa8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumpyTutorial/Questions on NumPy Statistics.py", "max_forks_repo_name": "CarlosW1998/DigitalImageProcessingClass", "max_forks_repo_head_hexsha": "69365877e07b676f13487585ffdf029a243b0fa8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5789473684, "max_line_length": 83, "alphanum_fraction": 0.710322874, "include": true, "reason": "import numpy", "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446463891303, "lm_q2_score": 0.885631484383387, "lm_q1q2_score": 0.8622903534435434}}
{"text": "import cupy\n\n\n# Collection of activation functions\n# Reference: https://en.wikipedia.org/wiki/Activation_function\n\nclass Sigmoid():\n    def __call__(self, x):\n        return 1 / (1 + cupy.exp(-x))\n\n    def gradient(self, x):\n        return self.__call__(x) * (1 - self.__call__(x))\n\nclass Softmax():\n    def __call__(self, x):\n        e_x = cupy.exp(x - cupy.max(x, axis=-1, keepdims=True))\n        return e_x / cupy.sum(e_x, axis=-1, keepdims=True)\n\n    def gradient(self, x):\n        p = self.__call__(x)\n        return p * (1 - p)\n\nclass TanH():\n    def __call__(self, x):\n        return 2 / (1 + cupy.exp(-2*x)) - 1\n\n    def gradient(self, x):\n        return 1 - cupy.power(self.__call__(x), 2)\n\nclass ReLU():\n    def __call__(self, x):\n        return cupy.where(x >= 0, x, 0)\n\n    def gradient(self, x):\n        return cupy.where(x >= 0, 1, 0)\n\nclass LeakyReLU():\n    def __init__(self, alpha=0.2):\n        self.alpha = alpha\n\n    def __call__(self, x):\n        return cupy.where(x >= 0, x, self.alpha * x)\n\n    def gradient(self, x):\n        return cupy.where(x >= 0, 1, self.alpha)\n\nclass ELU():\n    def __init__(self, alpha=0.1):\n        self.alpha = alpha \n\n    def __call__(self, x):\n        return cupy.where(x >= 0.0, x, self.alpha * (cupy.exp(x) - 1))\n\n    def gradient(self, x):\n        return cupy.where(x >= 0.0, 1, self.__call__(x) + self.alpha)\n\nclass SELU():\n    # Reference : https://arxiv.org/abs/1706.02515,\n    # https://github.com/bioinf-jku/SNNs/blob/master/SelfNormalizingNetworks_MLP_MNIST.ipynb\n    def __init__(self):\n        self.alpha = 1.6732632423543772848170429916717\n        self.scale = 1.0507009873554804934193349852946 \n\n    def __call__(self, x):\n        return self.scale * cupy.where(x >= 0.0, x, self.alpha*(cupy.exp(x)-1))\n\n    def gradient(self, x):\n        return self.scale * cupy.where(x >= 0.0, 1, self.alpha * cupy.exp(x))\n\nclass SoftPlus():\n    def __call__(self, x):\n        return cupy.log(1 + cupy.exp(x))\n\n    def gradient(self, x):\n        return 1 / (1 + cupy.exp(-x))\n", "meta": {"hexsha": "fc9bccff41713083f11b5e069019cf2e5b1c82b2", "size": 2025, "ext": "py", "lang": "Python", "max_stars_repo_path": "MLCtr/graduateutil/graduateutil/activation_functions.py", "max_stars_repo_name": "devillove084/CollageDesign", "max_stars_repo_head_hexsha": "e2a85a8d15f82d1f72b754de04af78126eae9a1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-12-28T14:12:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-08T16:30:25.000Z", "max_issues_repo_path": "MLCtr/graduateutil/graduateutil/activation_functions.py", "max_issues_repo_name": "devillove084/CollageDesign", "max_issues_repo_head_hexsha": "e2a85a8d15f82d1f72b754de04af78126eae9a1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MLCtr/graduateutil/graduateutil/activation_functions.py", "max_forks_repo_name": "devillove084/CollageDesign", "max_forks_repo_head_hexsha": "e2a85a8d15f82d1f72b754de04af78126eae9a1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6447368421, "max_line_length": 92, "alphanum_fraction": 0.5945679012, "include": true, "reason": "import cupy", "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446463891304, "lm_q2_score": 0.8856314662716159, "lm_q1q2_score": 0.8622903358091145}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nLinear regression example using least squares from COMP551 lecture 2\n@author: Demetrios Koziris\n\"\"\"\n\nimport numpy as np\nfrom numpy.linalg import inv\nimport matplotlib.pyplot as plt\n\n\n\"\"\"\nLeast-Squares solution\n\"\"\"\ndef least_squares(order=1, save_plots=False):\n    #print('Least-Squares:\\n')\n    \n    x = [0.86, 0.09, -0.85, 0.87, -0.44, -0.43, -1.1, 0.40, -0.96, 0.17]\n    y = [2.49, 0.83, -0.25, 3.10, 0.87, 0.02, -0.12, 1.81, -0.83, 0.43]\n    \n    # input matrix of feature vectors\n    X = np.array([np.power(x,p) for p in range(order+1)]).T\n    # target vector\n    Y = np.array(y).T\n\n    Xt_X = X.T @ X\n    # print(f'X^tX = \\n{Xt_X}\\n')\n    Xt_Y = X.T @ Y\n    # print(f'X^tY = \\n{Xt_Y}\\n')\n    w =  inv(Xt_X) @ Xt_Y\n    # print(f'W = (X^tX)^-1(X^tY) = \\n{w}\\n')\n    \n    def fit_function(x):\n        return sum([weight*(x**p) for p,weight in enumerate(w)])\n    \n    def fit_function_label():\n        terms = [f'{weight:.2f}x^{p}' for p,weight in enumerate(w)]\n        return '$y = ' + ' + '.join(terms[::-1]) + '$'      \n    \n    plot_title = f'Least-Squares Linear Regression Order {order}'\n    x_interval = np.linspace(-1.6, 1.6, 1000)\n    plt.plot(x_interval, fit_function(x_interval), 'r', label=fit_function_label())\n    plt.scatter(x, y, marker='x')\n    plt.xlim(-1.6, 1.6);\n    plt.ylim(-2, 5);\n    plt.title(plot_title)\n    plt.legend(loc=2)\n    if (save_plots):\n        plt.savefig(plot_title.lower().replace(' ','_'), bbox_inches=\"tight\")\n    plt.show()\n\n\nfor i in range(10):\n    least_squares(i, True)\n", "meta": {"hexsha": "125c6ab33474e107faca8989bcc38c355e460c54", "size": 1544, "ext": "py", "lang": "Python", "max_stars_repo_path": "least_squares.py", "max_stars_repo_name": "demetrios-koziris/comp-551-linear-regression", "max_stars_repo_head_hexsha": "d2840f88d2cc2f18e635f75d37085a35f77fea11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "least_squares.py", "max_issues_repo_name": "demetrios-koziris/comp-551-linear-regression", "max_issues_repo_head_hexsha": "d2840f88d2cc2f18e635f75d37085a35f77fea11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "least_squares.py", "max_forks_repo_name": "demetrios-koziris/comp-551-linear-regression", "max_forks_repo_head_hexsha": "d2840f88d2cc2f18e635f75d37085a35f77fea11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0727272727, "max_line_length": 83, "alphanum_fraction": 0.5764248705, "include": true, "reason": "import numpy,from numpy", "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298657, "lm_q2_score": 0.8962513821399044, "lm_q1q2_score": 0.8622902453217911}}
{"text": "# --------------\n\n# Code starts here\n#The adjacency matrix adj_mat is provided to you.\nimport numpy as np\n# Adjacency matrix\nadj_mat = np.array([[0,0,0,0,0,0,1/3,0],\n                   [1/2,0,1/2,1/3,0,0,0,0],\n                   [1/2,0,0,0,0,0,0,0],\n                   [0,1,0,0,0,0,0,0],\n                  [0,0,1/2,1/3,0,0,1/3,0],\n                   [0,0,0,1/3,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,1,1/3,0]])\n\n#For this matrix perform the eigen vector decomposition using .linalg.eig() method of numpy. This function returns a tuple and save them as eigenvalues and eigenvectors\neigenvalues,eigenvectors=np.linalg.eig(adj_mat)\n\n#The following is a single step divided into small steps:\n#Find the eigen vector corresponding to 1 from eigenvectors (first column of eigenvectors), that is abs(eigenvectors[:,0])\n#Normalize this by dividing with np.linalg.norm(eigenvectors[:,0],1). Save it as eigen_1\neigen_1= abs(eigenvectors[:,0])/np.linalg.norm(eigenvectors[:,0],1)\n\n#Next save the most important page number by finding the index with highest value within eigen_1. This can be done by using the .where() method \n#from numpy Save it as page and print it out.\npage=np.where(eigen_1==eigen_1.max())[0][0]+1\nprint(page)\n# Code ends here\n\n\n# --------------\n# Code starts here\n\n# Initialize stationary vector I\n#The hyperlink matrix adj_mat is already defined for you. Initialize a stationary matrix init_I which has 1 at the first position and 0s in the rest 7 blocks of the numpy ndarray.\ninit_I=np.array([1,0,0,0,0,0,0,0])\n\n#Use a for loop over 10 iterations where you update adj_mat according to the rule I^{k+1} = HI^k\n# this can be done by .dot(adj_mat, init_I) . Also normalize init_I at every iteration using np.linalg.norm(init_I, 1)\n# Perform iterations for power method\nfor i in range(10):\n  init_I=np.dot(adj_mat, init_I)/np.linalg.norm(init_I, 1)\n\n#Save the page number with highest importance as power_page. This can be found by .where() as done in the previous task.\npower_page=np.where(init_I==init_I.max())[0][0]+1\nprint(power_page)\n\n# Code ends here\n\n\n# --------------\n# Code starts here\n\n#Problem with power method\n#The new adjacency matrix this time for the new webpage connection structure shown in the above image. It is provided as new_adj_mat\n# New Adjancency matrix\nnew_adj_mat = np.array([[0,0,0,0,0,0,0,0],\n                   [1/2,0,1/2,1/3,0,0,0,0],\n                  [1/2,0,0,0,0,0,0,0],\n                   [0,1,0,0,0,0,0,0],\n                   [0,0,1/2,1/3,0,0,1/2,0],\n                   [0,0,0,1/3,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,1,1/2,0]])\n\n#Initialize a stationary matrix new_init_I in the same manner as you did for the previous task\nnew_init_I=np.array([1,0,0,0,0,0,0,0])\n\n#Use a for loop to iterate 10 times and update in the similar manner as you did for the previous task i.e. first take dot product np.dot(new_adj_mat, new_init_I) \n#and then normalize as done in previous task.\n# Perform iterations for power method\nfor i in range(10):\n  new_init_I=np.dot(new_adj_mat, new_init_I)/np.linalg.norm(new_init_I, 1)\n\n#Print out new_init_I to check out its result. Observe how you get pagerank value for 3rd webpage as zero. Is it not possible as it has incoming connections.\nprint(new_init_I)\n\n\n# Code ends here\n\n\n# --------------\n#Code Starts here\n# Alpha value\nalpha = 0.85\n\n# Code starts here\n# Modified adjancency matrix\n#Initialize new hyperlink matrix G with the help of the mathematical formula given above. In the formula n can be taken as len(new_adj_mat)) \n#and 1 as np.ones(new_adj_mat.shape.Save it as G\nn=len(new_adj_mat)\nS=np.ones(new_adj_mat.shape)/n\nI=np.ones(new_adj_mat.shape)\n#G=αS+(1−α)*(1/n)*I\nG=alpha*S+(I-alpha)*(1/n)\n\n#Initialize stationary vector as final_init_I consisting of 1 at its beginning and rest all zeros in a 1D NumPy array\nfinal_init_I=np.array([1,0,0,0,0,0,0,0])\n\n#Perform 1000 iterations using a for loop to update the stationary vector in the same manner as for the Power Method. Also, do not forget to normalize it.\nfor i in range(1000):\n  final_init_I=np.dot(G, final_init_I)/np.linalg.norm(final_init_I, 1)\n\n\n#Print out final_init_I\nprint(final_init_I)\n\n\n# Code ends here\n\n\n", "meta": {"hexsha": "2e644f72ff44f97eefa88436a6432c577db00960", "size": 4252, "ext": "py", "lang": "Python", "max_stars_repo_path": "How-does-Google-google?/code.py", "max_stars_repo_name": "johanloones/ga-learner-dsmp-repo", "max_stars_repo_head_hexsha": "03b31804e3e9ead54dd7cb8511f9ec902faec14e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "How-does-Google-google?/code.py", "max_issues_repo_name": "johanloones/ga-learner-dsmp-repo", "max_issues_repo_head_hexsha": "03b31804e3e9ead54dd7cb8511f9ec902faec14e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "How-does-Google-google?/code.py", "max_forks_repo_name": "johanloones/ga-learner-dsmp-repo", "max_forks_repo_head_hexsha": "03b31804e3e9ead54dd7cb8511f9ec902faec14e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9642857143, "max_line_length": 179, "alphanum_fraction": 0.6775634995, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.8962513620489619, "lm_q1q2_score": 0.8622902201495286}}
{"text": "# a simple cubic spline example.\n#\n# generate some random data in 10 intervals -- note the data changes\n# each time this is run.\n#\n# Our form of the spline polynomial comes from Pang, Ch. 2\n#\n# solve the matrix system for the splines\n#\n# plot the splines\n#\n# M. Zingale (2013-02-10)\n\nimport numpy\nimport pylab\nimport math\nfrom scipy import linalg   # scipy modules need to be imported separately\nfrom scipy import interpolate   # scipy modules need to be imported separately\n\n\n# plot a spline\ndef plot_spline(x0, x1, f0, f1, ppp0, ppp1):\n    \n    # lots of points for a smooth plot\n    x = numpy.linspace(x0, x1, 100)\n\n    dx = x1-x0\n\n    alpha = ppp1/(6.0*dx)\n    beta = -ppp0/(6.0*dx)\n\n    gamma = (-ppp1*dx*dx/6.0 + f1)/dx\n    eta = (ppp0*dx*dx/6.0 - f0)/dx\n\n    p = alpha*(x-x0)**3 + beta*(x-x1)**3 + gamma*(x-x0) + eta*(x-x1)\n\n    pylab.plot(x, p)\n\n\n# number of intervals\nn = 20\n\nxmin = 0.0\nxmax = 1.0\n\n\n# coordinates of the data locations\nx = numpy.linspace(xmin, xmax, n+1)\ndx = x[1] - x[0]\n\n# random data\nf = numpy.random.rand(n+1)\n\n\n# we are solving for n-1 unknowns\n\n# setup the righthand side of our matrix equation\nb = numpy.zeros(n+1)\n\n# b_i = (6/dx) * (f_{i-1} - 2 f_i + f_{i+1})\n# here we do this with slice notation to fill the\n# inner n-1 slots of b\nb[1:n] = (6.0/dx)*(f[0:n-1] - 2.0*f[1:n] + f[2:n+1])\n\n# we only care about the inner n-1 quantities\nb = b[1:n]\n\n\n# the matrix A is tridiagonal.  Create 3 arrays which will represent\n# the diagonal (d), the upper diagonal (u), and the lower diagnonal\n# (l).  l and u will have 1 less element.  For u, we will pad this at\n# the beginning and for l we will pad at the end.\n#\n# see http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve_banded.html#scipy.linalg.solve_banded\n# for the description of a banded matrix\n\nu = numpy.zeros(n-1)\nd = numpy.zeros(n-1)\nl = numpy.zeros(n-1)\n\nd[:] = 4.0*dx\n\nu[:] = dx\nu[0] = 0.0\n\nl[:] = dx\nl[n-2] = 0.0\n\n# create a banded matrix -- this doesn't store every element -- just\n# the diagonal and one above and below\nA = numpy.matrix([u,d,l])\n\n# solve Ax = b using the scipy banded solver -- the (1,1) here means\n# that there is one diagonal above the main diagonal, and one below.\nxsol = linalg.solve_banded((1,1), A, b)\n\n# x now hold all the second derivatives for points 1 to n-1.  Natural\n# boundary conditions set p'' = 0 at i = 0 and n\n# ppp will be our array of second derivatives\nppp = numpy.insert(xsol, 0, 0)  # insert before the first element\nppp = numpy.insert(ppp, n, 0)   # insert at the end\n\n\n# now plot -- data points first\npylab.scatter(x, f, marker=\"x\", color=\"r\")\n\n# plot the splines\ni = 0\nwhile i < n:\n\n    # working on interval [i,i+1]\n    ppp_i = ppp[i]\n    ppp_ip1 = ppp[i+1]\n\n    f_i = f[i]\n    f_ip1 = f[i+1]\n\n    x_i = x[i]\n    x_ip1 = x[i+1]\n\n    plot_spline(x_i, x_ip1, f_i, f_ip1, ppp_i, ppp_ip1)\n\n    i += 1\n\n\npylab.savefig(\"spline.png\")\n\n\n# note: we could have done this all through scipy -- here is their\n# spline, but it doesn't seem to support natural boundary conditions\n\n#s = interpolate.InterpolatedUnivariateSpline(x, f, k=3)\n#xx = numpy.linspace(xmin, xmax, 1000)\n#pylab.plot(xx, s(xx), color=\"k\", ls=\":\")\n\n\n# old way from scipy -- this raises a NotImplementedError for natural\n#spl1 = interpolate.splmake(x, f, order=3, kind=\"natural\")\n#xx = numpy.linspace(xmin, xmax, 1000)\n#yy = interpolate.spleval(spl1, xx)\n#pylab.plot(xx, yy, color=\"k\", ls=\":\")\n\n#pylab.savefig(\"spline-scipy.png\")\n\n\n\n\n\n", "meta": {"hexsha": "d69f41a475c96ef0074d86f67abb9e34030e5617", "size": 3443, "ext": "py", "lang": "Python", "max_stars_repo_path": "others/interpolation_root-finding/cubic-spline.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "others/interpolation_root-finding/cubic-spline.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/interpolation_root-finding/cubic-spline.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 23.1073825503, "max_line_length": 114, "alphanum_fraction": 0.6581469649, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.9124361598816666, "lm_q1q2_score": 0.8622473444445339}}
{"text": "\nimport numpy as np\n\n# ECDF\ndef ecdf(data):\n    \"\"\"Compute ECDF for a one-dimensional array of measurements.\"\"\"\n    # Number of data points: n\n    n = len(data)\n\n    # x-data for the ECDF: x\n    x = np.sort(data)\n\n    # y-data for the ECDF: y\n    y = np.arange(1, n+1) / n\n\n    return x, y\n\n# Bootstrap Resampling\n\n# bootstrap replicas\ndef bootstrap_replicate_1d(data, func):\n     \"\"\"Generate bootstrap replicate of 1D data.\"\"\"\n     bs_sample = np.random.choice(data, len(data))\n     return func(bs_sample)\n\n# many bootstraps replicas\ndef draw_bs_reps(data, func, size=1):\n    \"\"\"Draw bootstrap replicates.\"\"\"\n\n    # Initialize array of replicates: bs_replicates\n    bs_replicates = np.empty(size)\n\n    # Generate replicates\n    for i in range(size):\n        bs_replicates[i] = bootstrap_replicate_1d(data, func)\n\n    return bs_replicates", "meta": {"hexsha": "cae55953e27af5f1ca31eab5f9904ee931e401be", "size": 838, "ext": "py", "lang": "Python", "max_stars_repo_path": "basic_statistics.py", "max_stars_repo_name": "fredericohorst/anac-tarifas-aereas", "max_stars_repo_head_hexsha": "9b649c48e3d919f44237bbf774a9b8cf79336836", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "basic_statistics.py", "max_issues_repo_name": "fredericohorst/anac-tarifas-aereas", "max_issues_repo_head_hexsha": "9b649c48e3d919f44237bbf774a9b8cf79336836", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "basic_statistics.py", "max_forks_repo_name": "fredericohorst/anac-tarifas-aereas", "max_forks_repo_head_hexsha": "9b649c48e3d919f44237bbf774a9b8cf79336836", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6486486486, "max_line_length": 67, "alphanum_fraction": 0.6658711217, "include": true, "reason": "import numpy", "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813451206062, "lm_q2_score": 0.9019206712569268, "lm_q1q2_score": 0.8622193365002769}}
{"text": "import numpy as np\nimport math\n\ndef f(func_value, x):\n    \"\"\"\n        Defining Function\n    \"\"\"\n    if int(func_value) == 1 :\n        return (x**3 - 3*x*x - x + 9)\n    elif int(func_value) == 2 :\n        return ((x**3 - 3*x*x - x + 9)*(math.exp(x)))\n    else:\n        print(\"Error Message\")\n\ndef g(func_value, x):\n    \"\"\"\n    Defining derivative of function\n    \"\"\"\n    if int(func_value) == 1 :\n        return (3*x*x - 6*x - 1)\n    elif int(func_value) == 2 :\n        return ((x**3 - 3*x*x - x + 9 + (3*x*x - 6*x - 1))*(math.exp(x)))\n    else:\n        print(\"Error Message\")\n\n\ndef newtonRaphson(func_num,x0,e,N):\n    \"\"\"\n        Implementing Newton Raphson Method\n    \"\"\"\n    func_value_at_roots = []\n    counter = 1\n    flag = 1\n    condition = True\n    while condition:\n        if g(func_num,x0) == 0.0:\n            print('Divide by zero error!')\n            break\n\n        x1 = x0 - f(func_num,x0)/g(func_num,x0)\n        #print('Iteration:{}, x1 = {} and f(x1) = {}'.format(counter, x1, f(func_num,x1)))\n        func_value_at_roots.append((f(func_num,x1)))\n        x0 = x1\n        counter = counter + 1\n\n        if counter > N:\n            flag = 0\n            break\n\n        condition = abs(f(func_num,x1)) > e\n    return func_value_at_roots\n\"\"\"\n    if flag==1:\n        print('Required root is:{}'.format(x1))\n        continue\n    else:\n        print('Not Convergent.')\n\"\"\"\n", "meta": {"hexsha": "9c2c3e9055f0cd4b2b3a0766aa069f36db4792d2", "size": 1379, "ext": "py", "lang": "Python", "max_stars_repo_path": "AS2101_Labwork/3.Trials-References/Task 3/Submission Codes/Newton-Raphson Method/nrm_plot/nrm.py", "max_stars_repo_name": "kirtan2605/Coursework_Codes", "max_stars_repo_head_hexsha": "3455496e8ec0ae3a576cb3fc3b2ed01a055149c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AS2101_Labwork/3.Trials-References/Task 3/Submission Codes/Newton-Raphson Method/nrm_plot/nrm.py", "max_issues_repo_name": "kirtan2605/Coursework_Codes", "max_issues_repo_head_hexsha": "3455496e8ec0ae3a576cb3fc3b2ed01a055149c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AS2101_Labwork/3.Trials-References/Task 3/Submission Codes/Newton-Raphson Method/nrm_plot/nrm.py", "max_forks_repo_name": "kirtan2605/Coursework_Codes", "max_forks_repo_head_hexsha": "3455496e8ec0ae3a576cb3fc3b2ed01a055149c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3728813559, "max_line_length": 90, "alphanum_fraction": 0.5105148658, "include": true, "reason": "import numpy", "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.9086178994073576, "lm_q1q2_score": 0.862203210257462}}
{"text": "#!/usr/bin/python3\n\nimport numpy as np\nfrom time import time\n\nEPS = 1e-3\n\n'''\n    Sequential Implementation of https://doi.org/10.1007/978-3-319-11194-0_18\n'''\n\n\ndef compute_next(mat, vec):\n    sigma = np.diag(vec)\n    sigma_inv = np.diag(1/vec)\n    return np.matmul(np.matmul(sigma_inv, mat), sigma)\n\n\ndef sum_across_rows(mat):\n    n = mat.shape[1]\n    v = np.array([np.sum(mat[i]) for i in range(n)])\n    return v\n\n\ndef stop(vec):\n    return all(map(lambda e: e < EPS, [abs(vec[i] - vec[i-1])\n                                       for i in range(1, len(vec))]))\n\n\ndef max_eigen_value_and_vector(mat):\n    eigen_val = 0\n    eigen_vec = np.ones(mat.shape[0])\n\n    itr = 0\n    while True:\n        vec = sum_across_rows(mat)\n        vec_max = np.max(vec)\n        eigen_vec = np.array([j * (vec[i]/vec_max)\n                              for i, j in enumerate(eigen_vec)])\n        if stop(vec):\n            eigen_val = vec[0]\n            break\n\n        mat = compute_next(mat, vec)\n        itr += 1\n\n    return eigen_val, eigen_vec, itr + 1\n\n\nif __name__ == '__main__':\n    # handwritten test begins\n    mat = np.array([[1, 1, 2], [2, 1, 3], [2, 3, 5]])\n    val, vec, _ = max_eigen_value_and_vector(mat)\n\n    assert abs(val - 7.5311) < EPS\n    assert abs(vec[0] - 0.3941) < EPS\n    assert abs(vec[1] - 0.5788) < EPS\n    assert abs(vec[2] - 0.9975) < EPS\n    # handwritten test ends\n\n    print('Sequential Similarity Transform, for finding maximum eigen value ( with vector )\\n')\n    for dim in range(5, 11):\n        mat = np.random.random((1 << dim, 1 << dim))\n        start = time() * 1000\n        val, _, itr = max_eigen_value_and_vector(mat)\n        end = time() * 1000\n\n        assert val - np.max(np.linalg.eigvals(mat)) < EPS\n        print(\n            f'{1 << dim:<4} x {1 << dim:>4}\\t\\t{end - start:>6.2f} ms\\t\\t{itr:>8} round(s)')\n", "meta": {"hexsha": "4339c10dc5925fa39ad0732dd7122b9a519faf55", "size": 1837, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "itzmeanjan/eigen_value", "max_stars_repo_head_hexsha": "bfec038fb135f72a40b0bb3ae81b7e0a023c17d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.py", "max_issues_repo_name": "itzmeanjan/eigen_value", "max_issues_repo_head_hexsha": "bfec038fb135f72a40b0bb3ae81b7e0a023c17d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "itzmeanjan/eigen_value", "max_forks_repo_head_hexsha": "bfec038fb135f72a40b0bb3ae81b7e0a023c17d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8732394366, "max_line_length": 95, "alphanum_fraction": 0.5606967882, "include": true, "reason": "import numpy", "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.9173026607160999, "lm_q1q2_score": 0.8621850120061646}}
{"text": "import numpy as np\nimport math\n\ndef my_sphere(x):\n    x1, x2 = x\n    return x1 ** 2 + x2 ** 2\n\ndef my_rosenbrock(xy, a=2, b=5):\n    x, y = xy\n    return (a - x) ** 2 + b * ((y - x ** 2) ** 2)\n\ndef my_rastrigin(xy):\n    x, y = xy\n    return 10 * 2 + (x ** 2 - 10 * np.cos(2 * math.pi * x)) + (y ** 2 - 10 * np.cos(2 * math.pi * y))\n\ndef my_booth(xy):\n    x, y = xy\n    # min(1, 3) = 0\n    z = (x + 2*y - 7)**2 + (2*x + y - 5)**2\n    return z\n\ndef my_matyas(xy):\n    x, y = xy\n    # min(0, 0) = 0\n    z = 0.26*(x**2 + y**2) - 0.48*x*y\n    return z\n\ndef my_ackley(xy):\n    x, y = xy\n    # min(0, 0) = 0\n    z = -20*np.exp(np.fabs(-0.2*np.sqrt(0.5*(x**2 + y**2)))) - np.exp(np.fabs(0.5*(np.cos(2*x*math.pi) + np.cos(2*y*math.pi)))) + math.e + 20\n    return -z\n\ndef my_levi13(xy):\n    x, y = xy\n    # min(1, 1) = 0\n    z = (np.sin(3*x*math.pi))**2 + ((x - 1)**2)*(1 + np.sin(3*y*math.pi)**2) + ((y - 1)**2)*(1 + np.sin(2*y*math.pi)**2)\n    return z\n\ndef my_himmelblau(xy):\n    x, y = xy\n    # min(3, 2) = 0\n    # min(-2.805118, 3.131312) = 0\n    # min(-3.779310, -3.283186) = 0\n    # min(3.584428, -1.848126) = 0\n    z = (x**2 + y - 11)**2 + (x + y**2 - 7)**2\n    return z\n\ndef my_beale(xy):\n    x, y = xy\n    # min(3, 0.5) = 0\n    z = (1.5 - x + x*y)**2 + (2.25 - x + x*(y**2))**2 + (2.625 - x + x*(y**3))**2\n    return z\n\ndef my_goldstein_price(xy):\n    x, y = xy\n    # min(0, -1) = 3\n    z = ((1 + (x + y + 1)**2 * (19 - 14*x + 3*(x**2) - 14*y + 6*x*y + 3*(y**2))) * (30 + (2*x - 3*y)**2 * (18 - 32*x + 12*(x**2) + 48*y - 36*x*y + 27*(y**2))))\n    return z", "meta": {"hexsha": "916f1976e8e96b8e81df9d7dbce4d985d9985c84", "size": 1554, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/my_demo_func.py", "max_stars_repo_name": "GonChen/scikit-opt", "max_stars_repo_head_hexsha": "46e6bf586e4eb0cc295367f8ec60c7c2678120f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/my_demo_func.py", "max_issues_repo_name": "GonChen/scikit-opt", "max_issues_repo_head_hexsha": "46e6bf586e4eb0cc295367f8ec60c7c2678120f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/my_demo_func.py", "max_forks_repo_name": "GonChen/scikit-opt", "max_forks_repo_head_hexsha": "46e6bf586e4eb0cc295367f8ec60c7c2678120f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3389830508, "max_line_length": 159, "alphanum_fraction": 0.4356499356, "include": true, "reason": "import numpy", "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9770226294209299, "lm_q2_score": 0.8824278587245935, "lm_q1q2_score": 0.8621519868053832}}
{"text": "import numpy as np\n\n\"\"\"[Recreates the adjacency matrix with which the steady state probabilities get multiplied iteratively\n    The adjacency matrix A of a set of pages (nodes) defines the linking structure]\n\nReturns:\n    [numpy Matrix] -- [The matrix with which the steady state probabilities will get multipled]\n\"\"\"\ndef recreate_adjacency_matrix(marchov_chain):\n    # since the size of the matrix is n x n getting the size of the row is enough\n    num_urls = marchov_chain.shape[0]\n\n    # the probabilty of visiting a url, which is the 1 / total number of urls\n    probability = 1 / num_urls\n\n    probability_matrix = np.zeros((num_urls, num_urls))\n\n    # probability_matrix will contain all similar values which is the probability of visiting a particular page\n    probability_matrix[:] = probability\n    \n    '''\n        In assigning a PageRank score to each node of the web graph, we use the teleport operation in two ways: \n        (1) When at a node with no out-links, the surfer invokes the teleport operation. \n        (2) At any node that has outgoing links, the surfer invokes the teleport operation with a probability of alpha.\n        Typical value of alpha is 0.1 \n    '''\n    alpha = 0.1\n    \n    adjacency_matrix = alpha * marchov_chain + ((1 - alpha) * probability_matrix)\n\n    return adjacency_matrix\n\n\"\"\"[Computes the page rank of a given marchov chain url]\n\nReturns:\n    [list] -- [A list of n page rank score where n is the total number of urls]\n\"\"\"\ndef compute_page_rank(marchov_chain):\n    # create the adjacency matrix with which the steady state probability will get multiplied iteratively\n    adjacency_matrix = recreate_adjacency_matrix(marchov_chain)\n\n    num_urls = adjacency_matrix.shape[0]\n\n    # initial vector for the steady state probabilities will always be <1, 0, 0.....n>\n    steady_state_probabilities = np.zeros((1, num_urls))\n    # this creates a vector of <1, 0, 0...n>\n    steady_state_probabilities[0][0] = 1 \n    \n    # the steady_state probabilities always needs to be transposed\n    steady_state_probabilities = np.transpose(steady_state_probabilities)\n    \n    previous_state_probabilities = steady_state_probabilities\n    while True:\n        steady_state_probabilities = adjacency_matrix * steady_state_probabilities\n        \n        # we stop when the values have converged and no longer change over the iterations\n        if (previous_state_probabilities == steady_state_probabilities).all():\n            # if the values converge then the steady_state_probabilities are returned which is the page rank score of the urls\n            return steady_state_probabilities\n        \n        # otherwise the current steady state probabilities becomes the previous steady state probabilities as we are about to begin another iterations\n        previous_state_probabilities = steady_state_probabilities\n    \n\nif __name__ == '__main__':\n\n    '''\n        NOTE - This marchov chain is transpose of the modified adjacency matrix of the graph.\n        In an adjacency matrix the rows represent an individual url in the graph and columns\n        represent the urls that the graph has already visited. This adjacency matrix will be \n        transposed and modified to recreate the adjacency matrix. If a url has visited other urls then \n        the columns will get replaced by 1 / n, where n is the total number of urls visited by that url. \n        The matrix will essentially be a transpose of the adjacency matrix with the columns divided by total non zero entries.\n    '''\n    marchov_chain = np.matrix([[0, 0, 1],\n            [1, 0.5, 0],\n            [0, 0.5, 0]])\n\n    \n    page_rank = compute_page_rank(marchov_chain)\n\n    print(page_rank)\n\n    print(np.sum(page_rank))", "meta": {"hexsha": "f1abc7daba18abd37d71bb6dbfc2c4ed31d5d771", "size": 3709, "ext": "py", "lang": "Python", "max_stars_repo_path": "pagerank.py", "max_stars_repo_name": "tanvirtin/pagerank", "max_stars_repo_head_hexsha": "a3acfb990b12d49572ba15689603ee6251b26ea3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pagerank.py", "max_issues_repo_name": "tanvirtin/pagerank", "max_issues_repo_head_hexsha": "a3acfb990b12d49572ba15689603ee6251b26ea3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pagerank.py", "max_forks_repo_name": "tanvirtin/pagerank", "max_forks_repo_head_hexsha": "a3acfb990b12d49572ba15689603ee6251b26ea3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1547619048, "max_line_length": 150, "alphanum_fraction": 0.7177136695, "include": true, "reason": "import numpy", "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812318188366, "lm_q2_score": 0.8902942355821459, "lm_q1q2_score": 0.862144228534248}}
{"text": "from math import pi\nfrom math import sqrt\n\nimport numpy as np\n\n# Configure Parameters\n\nXMIN = -20.0\nXMAX = 20.0\nRES = 256\nSTEP_SIZE = 0.05 * -1j  # imaginary time\nTIMESTEPS = 100\n\n\n# Init Variables\n\nDX = 2 * XMAX / RES\nX = np.arange(XMIN + (XMAX / RES), XMAX, DX)\nDK = pi / XMAX\nK_I = np.concatenate((np.arange(0, RES / 2), np.arange(-RES / 2, 0))) * DK\n\n\n# Configure Operators\n\nV = 0.5 * X ** 2\nWFC = np.exp(-((X + 1) ** 2) / 2, dtype=complex)\n\n\n# Init Operators\n\nK = np.exp(-0.5 * (K_I ** 2) * STEP_SIZE * 1j, dtype=complex)\nR = np.exp(-0.5 * V * STEP_SIZE * 1j, dtype=complex)\n\n\n# Split-operator fourier method\nfor i in range(TIMESTEPS):\n    # Half-step in real space\n    WFC *= R\n\n    # FFT to momentum space\n    WFC = np.fft.fft(WFC)\n\n    # Full step in momentum space\n    WFC *= K\n\n    # iFFT back to real space\n    WFC = np.fft.ifft(WFC)\n\n    # Half-step in real space\n    WFC *= R\n\n    # Density for plotting and potential\n    density = np.abs(WFC) ** 2\n\n    # Normalize for imaginary time\n    if (np.iscomplex(STEP_SIZE)):\n        factor = sum(density) * DX\n        WFC /= sqrt(factor)\n\n    # Outputting data to file. Plotting can also be done in a\n    # similar way. This is set to output exactly 100 files, no\n    # matter how many timesteps were specified.\n    if (i % (TIMESTEPS // 100) == 0):\n        filename = \"output/output{}.dat\".format(str(i).zfill(5))\n        with open(filename, \"w\") as outfile:\n            # Outputting for gnuplot. Any plotter will do.\n            for j in range(len(density)):\n                line = \"{}\\t{}\\t{}\\n\".format(\n                    X[j], density[j].real, V[j].real)\n                outfile.write(line)\n        print(\"Outputting step: \", i + 1)\n\n# Calculate the energy < Psi | H | Psi >\n# Creating real, momentum, and conjugate wavefunctions.\nWFC_R = WFC\nWFC_K = np.fft.fft(WFC_R)\nWFC_C = np.conj(WFC_R)\n\n# Finding the momentum and real-space energy terms\nenergy_k = 0.5 * WFC_C * np.fft.ifft((K_I ** 2) * WFC_K)\nenergy_r = WFC_C * V * WFC_R\n\n# Integrating over all space\nenergy_final = sum(energy_k + energy_r).real\n\nprint('Final energy: ', energy_final * DX)\n", "meta": {"hexsha": "d2645a63cf957ac80cbfc6923d4ed20e22981315", "size": 2112, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python3/Split-Operator-Solver/splitop.py", "max_stars_repo_name": "benchislett/Skunkworks", "max_stars_repo_head_hexsha": "c673609665aeaa040f5db18173221a86526d61d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-07-17T10:41:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-26T15:01:08.000Z", "max_issues_repo_path": "Python3/Split-Operator-Solver/splitop.py", "max_issues_repo_name": "benchislett/Skunkworks", "max_issues_repo_head_hexsha": "c673609665aeaa040f5db18173221a86526d61d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-07-17T21:47:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-22T21:22:46.000Z", "max_forks_repo_path": "Python3/Split-Operator-Solver/splitop.py", "max_forks_repo_name": "benchislett/Skunkworks", "max_forks_repo_head_hexsha": "c673609665aeaa040f5db18173221a86526d61d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-17T18:05:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-17T18:05:48.000Z", "avg_line_length": 24.275862069, "max_line_length": 74, "alphanum_fraction": 0.6098484848, "include": true, "reason": "import numpy", "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018448494248, "lm_q2_score": 0.8840392909114836, "lm_q1q2_score": 0.8621167474162562}}
{"text": "\"\"\"\nThis script contains routines for computation in Eulidean geometry.\n\"\"\"\n\nimport numpy as np\n\ndef circle_approx_pts(centre, radius, num, from_to=[0,360]):\n    \"\"\"\n    SUMMARY\n        estimates a circle with evenly spaced points sampled on it\n        sets current mode\n\n    PARAMETERS\n        centre: list of x coordinate and y coordinate\n        radius: radius of circle\n        num: number of samples\n        from_to: with from_to we can set at what angle it starts and what angle it ends\n            [0, 360] for full circle\n\n    RETURNS\n        [(float, float)]\n    \"\"\"\n    centre = np.array(centre)\n    if from_to[1] < from_to[0]:\n        myrange = range(from_to[1], from_to[0]+360, (from_to[0]+360-from_to[1])//num)\n    else:\n        myrange = range(from_to[0], from_to[1], (from_to[1]-from_to[0])//num)\n\n    return_pts = []\n    for angle in myrange:\n        return_pts.append(centre+radius*np.array([np.cos(np.radians(angle)), np.sin(np.radians(angle))]))\n\n    return return_pts\n\ndef circumcentre(A,B,C):\n    \"\"\"\n    SUMMARY\n        computes the centre of the circumscribed circle\n\n    PARAMETERS\n        A: coordinates of vertex A\n        B: coordinates of vertex B\n        C: coordinates of vertex C\n\n    RETURNS\n        (float, float)\n    \"\"\"\n    D = 2 * (A[0]*(B[1]-C[1]) + B[0]*(C[1]-A[1]) + C[0]*(A[1]-B[1]))\n    K_x_A = (A[0]*A[0] + A[1]*A[1]) * (B[1]-C[1])\n    K_x_B = (B[0]*B[0] + B[1]*B[1]) * (C[1]-A[1])\n    K_x_C = (C[0]*C[0] + C[1]*C[1]) * (A[1]-B[1])\n    K_x = (K_x_A + K_x_B + K_x_C) / D\n\n    K_y_A = (A[0]*A[0] + A[1]*A[1]) * (C[0]-B[0])\n    K_y_B = (B[0]*B[0] + B[1]*B[1]) * (A[0]-C[0])\n    K_y_C = (C[0]*C[0] + C[1]*C[1]) * (B[0]-A[0])\n    K_y = (K_y_A + K_y_B + K_y_C) / D\n\n    return K_x, K_y\n\ndef circumradius(A, centre):\n    \"\"\"\n    SUMMARY\n        computes the radius of the circumscribed circle given a vertex\n\n    PARAMETERS\n        A: coordinates of vertex A\n        centre: coordinates of the centre of the circle\n\n    RETURNS\n        float\n    \"\"\"\n    return np.linalg.norm(np.array(A)-np.array(centre))\n\ndef circum_centre_and_radius(A,B,C):\n    \"\"\"\n    SUMMARY\n        combines circumcentre(A,B,C) and circumradius(A, centre) to compute both\n\n    PARAMETERS\n        A: coordinates of vertex A\n        B: coordinates of vertex B\n        C: coordinates of vertex C\n\n    RETURNS\n        ([float, float], float)\n    \"\"\"\n    centre = circumcentre(A,B,C)\n    radius = circumradius(A,centre)\n    return centre, radius\n\ndef incentre(A,B,C):\n    \"\"\"\n    SUMMARY\n        computes the centre of the inscribed circle of a triangle\n\n    PARAMETERS\n        A: coordinates of vertex A\n        B: coordinates of vertex B\n        C: coordinates of vertex C\n\n    RETURNS\n        [float, float]\n    \"\"\"\n    A = np.array(A)\n    B = np.array(B)\n    C = np.array(C)\n    a = np.linalg.norm(C-B)\n    b = np.linalg.norm(A-C)\n    c = np.linalg.norm(B-A)\n\n    I_x = (a*A[0]+b*B[0]+c*C[0]) / (a+b+c)\n    I_y = (a*A[1]+b*B[1]+c*C[1]) / (a+b+c)\n    return I_x, I_y\n\ndef inradius(A,B,C):\n    \"\"\"\n    SUMMARY\n        computes the radius of the circumscribed circle (uses Heron's formula)\n\n    PARAMETERS\n        A: coordinates of vertex A\n        B: coordinates of vertex B\n        C: coordinates of vertex C\n\n    RETURNS\n        float\n    \"\"\"\n    a = np.linalg.norm(np.array(B)-np.array(C))\n    b = np.linalg.norm(np.array(C)-np.array(A))\n    c = np.linalg.norm(np.array(A)-np.array(B))\n    s = (a+b+c)/2\n    return np.sqrt(s*(s-a)*(s-b)*(s-c)) / s\n\n\ndef in_centre_and_radius(A,B,C):\n    \"\"\"\n    SUMMARY\n        combines circumcentre(A,B,C) and circumradius(A, centre) to compute both\n\n    PARAMETERS\n        A: coordinates of vertex A\n        B: coordinates of vertex B\n        C: coordinates of vertex C\n\n    RETURNS\n        ([float, float], float)\n    \"\"\"\n    centre = incentre(A,B,C)\n    radius = inradius(A,B,C)\n    return centre, radius\n\ndef ll_intersection(A,B,P,Q):\n    \"\"\"\n    SUMMARY\n        computes the coordinates of the intersection of segment AB and segment PQ,\n        (beware: when the segments are parallel the denominators are 0)\n\n    PARAMETERS\n        A: coordinates of vertex A\n        B: coordinates of vertex B\n        P: coordinates of vertex P\n        Q: coordinates of vertex Q\n\n    RETURNS\n        ([float, float], float)\n    \"\"\"\n    denominator = (A[0]-B[0]) * (P[1]-Q[1]) - (A[1]-B[1]) * (P[0]-Q[0])\n    if denominator == 0:\n        return (DEFAULT,DEFAULT)\n    numerator_x = (A[0]*B[1]-B[0]*A[1]) * (P[0]-Q[0]) - (A[0]-B[0]) * (P[0]*Q[1]-Q[0]*P[1])\n    numerator_y = (A[0]*B[1]-B[0]*A[1]) * (P[1]-Q[1]) - (A[1]-B[1]) * (P[0]*Q[1]-Q[0]*P[1])\n\n    return numerator_x/denominator, numerator_y/denominator\n\n\n# credit: https://stackoverflow.com/questions/55816902/finding-the-intersection-of-two-circles\ndef cc_intersection(O0, r0, O1, r1):\n    \"\"\"\n    SUMMARY\n        computes the intersection points of two circles\n        (note that there can be two intersection points, or one, or none)\n\n    PARAMETERS\n        O0: centre of circle 0\n        r0: radius of circle 0\n        O1: centre of circle 1\n        r1: radius of circle 1\n\n    RETURNS\n        [float, float]\n    \"\"\"\n    # circle 1: (x0, y0), radius r0\n    # circle 2: (x1, y1), radius r1\n    x0, y0 = O0\n    x1, y1 = O1\n\n    d=np.sqrt((x1-x0)**2 + (y1-y0)**2)\n\n    # non intersecting\n    if d > r0 + r1 :\n        return None\n    # one circle within other\n    if d < abs(r0-r1):\n        return None\n    # coincident circles\n    if d == 0 and r0 == r1:\n        return None\n    else:\n        a=(r0**2-r1**2+d**2)/(2*d)\n        h=np.sqrt(r0**2-a**2)\n        x2=x0+a*(x1-x0)/d\n        y2=y0+a*(y1-y0)/d\n        x3=x2+h*(y1-y0)/d\n        y3=y2-h*(x1-x0)/d\n\n        x4=x2-h*(y1-y0)/d\n        y4=y2+h*(x1-x0)/d\n\n        return (x3, y3, x4, y4)\n\ndef lc_intersection(O, r, A, B):\n    \"\"\"\n    SUMMARY\n        computes the intersection points of the circle (O,r) and segment AB\n        (warning: the number of intersection points may be 0, 1, or 2)\n    PARAMETERS\n        O: centre of circle\n        r: radius of circle\n        A: endpoint of segment AB\n        B: other endpoint of segment AB\n\n    RETURNS\n        [float, float]\n    \"\"\"\n    sign = lambda x : 1 if x >= 0 else -1\n    O_ = np.array(O)\n    A_ = np.array(A)\n    B_ = np.array(B)\n    dx, dy = B_ - A_\n    dr = np.sqrt(dx*dx + dy*dy)\n    D = np.cross(A_-O_, B_-O_)\n    discriminant = r*r*dr*dr-D*D\n\n    if discriminant > 0:\n        x1 = (D*dy+sign(dy)*dx*np.sqrt(discriminant)) / (dr*dr) + O_[0]\n        y1 = (-D*dx+np.abs(dy)*np.sqrt(discriminant)) / (dr*dr) + O_[1]\n        x2 = (D*dy-sign(dy)*dx*np.sqrt(discriminant)) / (dr*dr) + O_[0]\n        y2 = (-D*dx-np.abs(dy)*np.sqrt(discriminant)) / (dr*dr) + O_[1]\n        if np.cross(A_-O_,A_-B_) <= 0:\n            if sign(dy) == 1:\n                return [[x1,y1], [x2,y2]], True\n            else:\n                return [[x2,y2], [x1,y1]], True\n        else:\n            if sign(dy) == 1:\n                return [[x1,y1], [x2,y2]], False\n            else:\n                return [[x2,y2], [x1,y1]], False\n    elif discriminant == 0:\n        x = D*dy / (dr*dr)\n        y = -D*dx / (dr*dr)\n        return [[x,y], [x,y]], False\n    else:\n        return [[0,0],[0,0]], False\n\n\n# https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment\ndef pt_segment_dist(A, B, P):\n    \"\"\"\n    SUMMARY\n        computes the distance of point P from segment AB\n    PARAMETERS\n        A: endpoint of segment AB\n        B: other endpoint of segment AB\n        P: point at some distance from AB\n\n    RETURNS\n        float\n    \"\"\"\n    x1, y1 = A\n    x2, y2 = B\n    x3, y3 = P\n    px = x2-x1\n    py = y2-y1\n    norm = px*px + py*py\n    u =  ((x3 - x1) * px + (y3 - y1) * py) / float(norm)\n\n    if u > 1:\n        u = 1\n    elif u < 0:\n        u = 0\n\n    x = x1 + u * px\n    y = y1 + u * py\n    dx = x - x3\n    dy = y - y3\n\n    dist = (dx*dx + dy*dy)**.5\n    return dist\n\ndef pt_circle_dist(O, r, P):\n    \"\"\"\n    SUMMARY\n        computes the distance of point circle (O, r) from P\n\n    PARAMETERS\n        O: coordinates of the circle centre O\n        r: radius of the circle\n        P: point at some distance from the circle\n\n    RETURNS\n        float\n    \"\"\"\n    return abs(np.linalg.norm(np.array(O)-np.array(P))-r)\n\n\ndef orthogonal_projection(A, B, P):\n    \"\"\"\n    SUMMARY\n        computes the orthogonal projection of P on AB\n\n    PARAMETERS\n        A: endpoint of segment AB\n        B: other endpoint of segment AB\n        P: point at some distance from AB\n\n    RETURNS\n        [float, float]\n    \"\"\"\n    A_ = np.array(A)\n    B_ = np.array(B)\n    P_ = np.array(P)\n    x = np.linalg.norm(P_ - A_) * (P_ - A_).dot(B_ - A_) / (np.linalg.norm(P_ - A_) * np.linalg.norm(B_ - A_))\n    return A_ + (B_- A_) / np.linalg.norm(A_ - B_) * x\n\ndef bisector_point(A,B,C):\n    \"\"\"\n    SUMMARY\n        computes a point which lies on the bisector of the angle\n\n        In order to get the exact distance from the angle point we follow the\n        construction method of tkz-euclide.\n        1. copy the first segment (A,B) on the second segment (B,C) to get (P)\n        the result is the third coordinate of the equilateral triangle formed by AP.\n\n    PARAMETERS\n        A: point\n        B: point where the angle is\n        P: third point\n\n    RETURNS\n        [float, float]\n    \"\"\"\n    A = np.array(A)\n    B = np.array(B)\n    C = np.array(C)\n    P = B + np.linalg.norm(B-A) * (C - B) / np.linalg.norm(C-B)\n    rotation_matrix = np.array([[np.cos(np.radians(60)), -np.sin(np.radians(60))],\\\n                               [np.sin(np.radians(60)), np.cos(np.radians(60))]])\n    Q = A.reshape(2,1) + rotation_matrix @ (P-A).reshape(2,1)\n    return Q.flatten()\n", "meta": {"hexsha": "03a0abe38e7e94612df1e6a7e2aa870a5cf26373", "size": 9648, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/EuclMath.py", "max_stars_repo_name": "jtrfid/tkzgeom", "max_stars_repo_head_hexsha": "b3b1baf33b89e7b670bc736d28818456ac4547ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/EuclMath.py", "max_issues_repo_name": "jtrfid/tkzgeom", "max_issues_repo_head_hexsha": "b3b1baf33b89e7b670bc736d28818456ac4547ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/EuclMath.py", "max_forks_repo_name": "jtrfid/tkzgeom", "max_forks_repo_head_hexsha": "b3b1baf33b89e7b670bc736d28818456ac4547ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5785123967, "max_line_length": 110, "alphanum_fraction": 0.5492330017, "include": true, "reason": "import numpy", "num_tokens": 3064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018398044143, "lm_q2_score": 0.8840392817460333, "lm_q1q2_score": 0.8621167340181046}}
{"text": "from sympy import S, zeros, Matrix, nsimplify, factorial, maximum, lambdify, Interval, expand, symbols, pi, cos, eye\nfrom ..genericas import matriz_inversa\nfrom tqdm import tqdm\nimport numpy as np\n\n\ndef polinomio_lagrange(x_vals, y_vals, var=symbols('x')):\n    \"\"\"Genera el polinomio de interpolación de Lagrange.\n\n    Args:\n        x_vals (list): Valores x de interpolación\n        y_vals (list): Valores f(x) de interpolación\n        var (variable, optional): Variable sobre la que construir el polinomio. Defaults to symbols('x').\n\n    Returns:\n        p: polinomio de Lagrange.\n        lista_L: Lista de coeficientes l_i de los polinomios.\n    \"\"\"\n    lista_L, p, n = [], S(0), len(x_vals)\n    for i in range(n):\n        li = S(1)\n        for k in range(n):\n            if k != i:\n                li *= (var - x_vals[k]) / (x_vals[i] - x_vals[k])\n\n        lista_L.append(li)\n        p += y_vals[i] * li\n\n    return p, lista_L\n\n\ndef polinomio_newton(x_vals, y_vals, var=symbols('x'), evalf=None):\n    \"\"\"Genera el polinomio de interpolación de Newton.\n\n    Args:\n        x_vals (list): Valores x de interpolación\n        y_vals (list): Valores f(x) de interpolación\n        var (variable, optional): Variable sobre la que construir el polinomio. Defaults to symbols('x').\n        evalf (int): Redondea la matriz de coeficiente y, por tanto, los coeficientes del polinomio a un número de cifras. \n\n    Returns:\n        p: polinomio de Newton.\n        matriz_coeffs: Matriz de coeficientes con el método iterativo.\n    \"\"\"\n\n    matriz_coeffs = zeros(len(y_vals), len(y_vals))\n    for i in range(len(y_vals)):  # Asignamos la primera columna como f(x)\n        matriz_coeffs[i, 0] = y_vals[i]\n\n    for col in range(1, len(y_vals)):\n        for row in range(len(y_vals) - col):\n            num = matriz_coeffs[row + 1, col - 1] - matriz_coeffs[row, col - 1]\n            den = x_vals[row + col] - x_vals[row]\n\n            matriz_coeffs[row, col] = num / den\n\n    matriz_coeffs = nsimplify(matriz_coeffs, tolerance=1e-10, rational=True)  # Esto es importante para quitar valores de redondeo\n    if evalf is not None:  # si evalf es un numero redondea a ese numero de decimales\n        matriz_coeffs = matriz_coeffs.evalf(evalf)\n\n    # Aqui hacemos el polinomio\n    p = matriz_coeffs[0, 0]\n    for col in range(1, len(y_vals)):\n        p_col = S(1)\n        for i in range(0, col):\n            p_col *= (var - x_vals[i])\n\n        p += p_col * matriz_coeffs[0, col]\n\n    return p, matriz_coeffs\n\n\ndef error_lagrange(f, x_vals, I=[0, 1], var=symbols('x')):\n    \"\"\"Calcula el error del polinomio de Lagrange, definido por PROD[(x-xi)]/(n+1)! max f^(n+1)(t)\n\n    Args:\n        f (función): Función interpolada (si se conoce).\n        x_vals (list): Valores x de interpolación.\n        I (list): Intervalo de interpolación.\n        var (variable, optional): Variable de interpolación. Defaults to symbols('x').\n\n    Returns:\n        E_x (float): Error máximo de interpolación\n    \"\"\"\n    E_x_fact = S(1)\n    for x_val in x_vals:\n        E_x_fact *= (var - x_val)\n\n    E_x_fact /= factorial(len(x_vals))\n\n    # Ahora derivamos la función n veces\n    diff_f = f\n\n    for _ in range(len(x_vals)):\n        diff_f = diff_f.diff(var)\n\n    max_diff_f = maximum(diff_f, var, Interval(I[0], I[1]))\n\n    E_x = E_x_fact * abs(max_diff_f)\n\n    return E_x\n\n\ndef error_maximo_estocastico(f, var=symbols('x'), grado=3, N=1000, I=[0, 1], list_x_vals=None):\n    \"\"\"Emplea un método estocástico para simular el error máximo de la interpolación. Para ello genera n (grado) nodos dentro del intervalo, calcula el error máximo para ese caso específico, y \n    actualiza el error máximo para cada conjunto de nodos.\n\n    Args:\n        f (funcion): Función a interpolar.\n        var (variable, optional): Variable de la función. Defaults to symbols('x').\n        grado (int, optional): Grado de interpolación. Defaults to 3.\n        N (int, optional): Número de generaciones aleatorias de nodos. Defaults to 1000.\n        I (list, optional): Intervalo de interpolación. Defaults to [0, 1].\n        list_x_vals (list, optional): Listado de nodos, definido por el usuario. Defaults to None.\n\n    Returns:\n        max_error (float): Error estocástico máximo.\n    \"\"\"\n    max_error = 0\n\n    # Hacemos la funcion por separado porque el cálculo de derivada es costoso y cada iteración de error_lagrange tarda mucho\n    diff_f = f\n    for _ in range(grado):\n        diff_f = diff_f.diff(var)\n    max_diff_f = maximum(diff_f, var, Interval(I[0], I[1]))\n\n    for _ in tqdm(range(N)):\n        if list_x_vals is None:\n            x_list = np.sort(np.random.rand(grado) * (I[1] - I[0]) + I[0])\n        else:\n            x_list = list_x_vals\n\n        E_x_fact = S(1) / S(factorial(grado))\n        for x_val in x_list:\n            E_x_fact *= (var - x_val)\n\n        E_x = lambdify(var, expand(E_x_fact * max_diff_f))  # lambdify es para que la evaluación numérica sea mucho más ágil\n\n        x_range = np.linspace(I[0], I[1], int(N / 10))\n        y_f = [E_x(i) for i in x_range]\n        max_y_f = np.max(abs(np.array(y_f)))\n\n        if max_y_f >= max_error:\n            max_error = max_y_f\n\n        if list_x_vals is not None:\n            break\n\n    return max_error\n\n\ndef roots_chebyshev(n, I=[-1, 1]):\n    \"\"\"Calcula las raíces del polinomio de Chebyshev de grado n.\n\n    Args:\n        n (int): Grado del polinomio\n        I (list, optional): Intervalo de generación del polinomio. Defaults to [-1, 1].\n\n    Returns:\n        roots (list): Lista con las raices, en forma trigonométrica.\n    \"\"\"\n    roots = [0.5 * (I[1] + I[0]) + 0.5 * (I[1] - I[0]) * cos(S(2 * (i + 1) - 1) / S(2 * n) * pi) for i in range(n)][::-1]\n    return roots\n\n\ndef aitken_neville(x_vals, y_vals, x0, modo='aitken'):\n    \"\"\"Aplica los algoritmos de Aitken y Nevile para calcular el valor de una función interpolada en un punto nuevo, dados los valores en nodos anteriores.\n\n    Args:\n        x_vals (list): Valores x de interpolación\n        y_vals (list): Valores f(x) de interpolación\n        x0 (float): Valor x del nodo a calcular su f(x)\n        modo (str, optional): ['aitken', 'neville']. Defaults to 'aitken'.\n\n    Returns:\n        matriz_coeffs: Matriz de coeficientes de la interpolación. El elemento [0, -1] es el valor interpolado.\n    \"\"\"\n    matriz_coeffs = zeros(len(y_vals), len(y_vals))\n    for i in range(len(y_vals)):  # Asignamos la primera columna como f(x)\n        matriz_coeffs[i, 0] = y_vals[i]\n\n    for col in range(1, len(y_vals)):\n        for row in range(len(y_vals) - col):\n            xk = None\n            if modo == 'aitken':\n                xk = x_vals[0]\n            elif modo == 'neville':\n                xk = x_vals[row]\n\n            num = (x0 - xk) * matriz_coeffs[row + 1, col - 1] - (x0 - x_vals[row + col]) * matriz_coeffs[row, col - 1]\n            den = x_vals[row + col] - xk\n\n            matriz_coeffs[row, col] = num / den\n\n    matriz_coeffs = nsimplify(matriz_coeffs, tolerance=1e-10, rational=True)  # Esto es importante para quitar valores de redondeo\n\n    return matriz_coeffs\n\n\ndef interpolacion_hermite(x_vals, y_vals, diff_vals, var=symbols('x'), evalf=None):\n    \"\"\"Aplica la interpolación de Hermite, que permite la introducción de valores de derivadas. En esta implementación solo\n    se permiten valores de la primera derivada.\n\n    Args:\n        x_vals (list): Valores x de interpolación.\n        y_vals (list): Valores f(x) de interpolación.\n        diff_vals (list): Valores f'(x) de interpolación.\n        var (variable, optional): Variable sobre la que construir el polinomio. Defaults to symbols('x').\n        evalf (int): Redondea la matriz de coeficiente y, por tanto, los coeficientes del polinomio a un número de cifras. \n\n    Returns:\n        p: polinomio de Hermite.\n        matriz_coeffs: Matriz de coeficientes con el método iterativo.\n    \"\"\"\n    base_w = [S(1)]\n    double_x_vals = []\n    for val in x_vals:\n        double_x_vals += [val, val]\n\n    for x_val in x_vals:\n        base_w += [base_w[-1] * (var - x_val), base_w[-1] * (var - x_val) ** 2]\n\n    base_w = base_w[:-1]  # Eliminamos la componente w_2n+1, que no se emplea para el cálculo del polinomio\n    matriz_coeffs = zeros(len(base_w), len(base_w))\n\n    # Asignamos la primera columna como f(x)\n    for i in range(2 * len(y_vals)):\n        matriz_coeffs[i, 0] = y_vals[i // 2]\n\n    # Asignamos la segunda columna para f'(x) o f[xa, xa+1]\n    for i in range(0, 2 * len(y_vals), 2):\n        matriz_coeffs[i, 1] = diff_vals[i // 2]\n\n    for i in range(1, 2 * len(y_vals) - 1, 2):\n        num = matriz_coeffs[i + 1, 0] - matriz_coeffs[i, 0]\n        den = double_x_vals[i + 1] - double_x_vals[i]\n        matriz_coeffs[i, 1] = num / den\n\n    # Asignamos para el resto de columnas\n    for col in range(2, 2 * len(y_vals)):\n        for row in range(2 * len(y_vals) - col):\n            num = matriz_coeffs[row + 1, col - 1] - matriz_coeffs[row, col - 1]\n            den = double_x_vals[row + col] - double_x_vals[row]\n\n            matriz_coeffs[row, col] = num / den\n\n    matriz_coeffs = nsimplify(matriz_coeffs, tolerance=1e-10, rational=True)  # Esto es importante para quitar valores de redondeo\n    if evalf is not None:  # si evalf es un numero redondea a ese numero de decimales\n        matriz_coeffs = matriz_coeffs.evalf(evalf)\n\n    # Aqui hacemos el polinomio\n    p = S(0)\n    for i in range(len(base_w)):\n        p += base_w[i] * matriz_coeffs[0, i]\n\n    return p, matriz_coeffs\n\n\ndef polinomio_generico(lista_condiciones, var=symbols('x'), evalf=None):\n    \"\"\"Calcula un polinomio que satisface las condiciones de interpolación.\n       La lista de condiciones viene data por una lista de listas:\n       [ [(a, b), (c, d)],  [],  [(e, f)]]\n       Esto significaria: f(a) = b;  f(c) = d;  f''(e) = f\n    Args:\n        lista_condiciones (list): Lista de condiciones\n        var (variable, optional): Variable sobre la que construir el polinomio. Defaults to symbols('x').\n        evalf (int): Redondea la matriz de coeficiente y, por tanto, los coeficientes del polinomio a un número de cifras. \n\n    Returns:\n        p (polinomio): polinomio de interpolación. \n        D (matriz): Matriz de coeficientes. Cada fila tiene tantas columnas como coeficientes a_i, y satisface la condición determinada: f''(3) -> 0  0 2 3·2·(3) 4·3·(3)^2 5·4·(3)^3 ...\n        rhs: Matriz de rhs de la ecuación: f''(3) = 34 -> 34\n        a_vals: Matrices de valores del polinomio que cumplen la ecuación D·a = rhs\n    \"\"\"\n    # La lista de condiciones viene data por una lista de listas:\n    # [ [(a, b), (c, d)],  [],  [(e, f)]]\n    # Esto significaria: f(a) = b;  f(c) = d;  f''(e) = f\n\n    # Primero contamos el número de elementos para generar el polinomio de grado n-1\n    n = sum([len(i) for i in lista_condiciones])\n    p_list = []\n    for i in range(n):\n        p_list.append(var ** i)\n\n    # Ahora implementamos las condiciones. Cada elemento de la lista de condiciones será p, o sus derivadas, sustituyendo el elemento determinado\n    D, rhs = zeros(n, n), []\n\n    row = 0\n    for diff_range in range(len(lista_condiciones)):\n        # Primero aplicamos la n-derivada a ese polinomio\n        for pair in lista_condiciones[diff_range]:\n            for col in range(diff_range, n):\n                if col == 0:\n                    multiplicado_derivada = 1\n                else:\n                    multiplicado_derivada = factorial(col) / factorial(col - diff_range)\n                D[row, col] = multiplicado_derivada * pair[0] ** (col - diff_range)  # Añadimos a la matriz su elemento, que es la derivada por x^n\n\n            rhs.append(pair[1])\n            row += 1\n\n    try:\n        a = matriz_inversa(D) * Matrix(rhs)\n        a_vals = {symbols(f'a{i}'): a[i, 0] for i in range(D.shape[0])}\n\n        p = S(0)\n        for i in range(n):\n            p += var**i * a_vals[symbols(f'a{i}')]\n    except:\n        print('La matriz de valores no tiene inversa. No existe un polinomio de interpolación que verifique las condiciones.')\n        a_vals = None\n        p = None\n\n    return p, D, rhs, a_vals\n\n\ndef esplines(x_vals, y_vals, var=symbols('x')):\n    \"\"\"Genera un esplín natural cúbico.\n\n    Args:\n        x_vals (list): Valores x de interpolación.\n        y_vals (list): Valores f(x) de interpolación.\n        var (variable, optional): Variable sobre la que construir el esplín. Defaults to symbols('x').\n\n    Returns:\n        S_dict (dict): Diccionario con los polinomios S_i para cada par de nodos x_i x_i+1\n        valores (dict): Para cada i, retorna los coeficientes a_i, b_i, c_i, d_i del polinomio S_i = a_i(x-x_i)^3 + b_i(x-x_i)^2 + c_i(x-x_i) + d_i\n        D (matriz): Matriz de construcción del esplín.\n        z (list): Lista de valores z_i para derivar a_i, b_i, c_i, d_i\n        rhs (matriz): Matriz con los valores 6 * f[x_i, x_i+1, x_i+2]\n    \"\"\"\n    # Primero creamos los polinomios de los esplines\n    S_dict = {}\n    valores = {}\n\n    # Ahora hallamos h y r para resolver el sistema\n    h_list = [x_vals[i + 1] - x_vals[i] for i in range(len(x_vals) - 1)]\n    r_list = [h_list[i] / (h_list[i] + h_list[i + 1]) for i in range(len(x_vals) - 2)]\n\n    D = 2 * eye(len(x_vals) - 2)\n    for i in range(len(x_vals) - 3):\n        D[i, i + 1] = 1 - r_list[i]\n        D[i + 1, i] = r_list[i + 1]\n\n    # Ahora hallamos el rhs, que está compuesto por f[a, b, c] = (f[b, c] - f[a, b])/(c-a) = ({(f(c) - f(b))/(c-b)} - {(f(b) - f(a))/(b-a)})/(c-a)\n    rhs = 6 * Matrix([(((y_vals[i + 2] - y_vals[i + 1]) / (x_vals[i + 2] - x_vals[i + 1])) -\n                       ((y_vals[i + 1] - y_vals[i]) / (x_vals[i + 1] - x_vals[i]))) /\n                      (x_vals[i + 2] - x_vals[i])\n                      for i in range(len(x_vals) - 2)])\n\n    # Resolvemos el sistema D*z = rhs\n    z = matriz_inversa(D) * rhs\n    z_list = [0] + list(z) + [0]\n\n    # Asignamos los valores de a, b, c, d, y con ello creamos los polinomios\n    for i in range(len(x_vals) - 1):\n        a = (z_list[i + 1] - z_list[i]) / (6 * h_list[0])\n        b = z_list[i] / 2\n        c = (y_vals[i + 1] - y_vals[i]) / (h_list[i]) - (2 * z_list[i] + z_list[i + 1]) / (6) * h_list[i]\n\n        valores[i] = [a, b, c, y_vals[i]]\n        S_dict[f'S_{i}'] = expand(y_vals[i] + c * (var - x_vals[i]) + b * (var - x_vals[i]) ** 2 + a * (var - x_vals[i]) ** 3)\n\n    return S_dict, valores, D, z, rhs\n", "meta": {"hexsha": "e0692e646f18637b2e26339fb8a692ae6b22262a", "size": 14306, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/anmi/T5/__init__.py", "max_stars_repo_name": "alexmascension/ANMI", "max_stars_repo_head_hexsha": "9c51a497a5fa2650f1429f847c7f9df69271168b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-30T23:30:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T23:30:45.000Z", "max_issues_repo_path": "src/anmi/T5/__init__.py", "max_issues_repo_name": "alexmascension/ANMI", "max_issues_repo_head_hexsha": "9c51a497a5fa2650f1429f847c7f9df69271168b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-04-11T20:39:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-13T17:45:43.000Z", "max_forks_repo_path": "src/anmi/T5/__init__.py", "max_forks_repo_name": "alexmascension/ANMI", "max_forks_repo_head_hexsha": "9c51a497a5fa2650f1429f847c7f9df69271168b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-30T23:31:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T23:31:11.000Z", "avg_line_length": 39.1945205479, "max_line_length": 193, "alphanum_fraction": 0.6077170418, "include": true, "reason": "import numpy,from sympy", "num_tokens": 4356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611608990299, "lm_q2_score": 0.8976953003183444, "lm_q1q2_score": 0.8621117007473286}}
{"text": "from collections import Counter\nfrom sklearn.neighbors import KernelDensity\n\nimport numpy as np\n\nprint(\"====================\")\n# Calculating Discrete Probability\nprint(\"Calculating Discrete Probability\")\n\nx = [0,1,0,0,0,1]\nc = Counter(x)\n\ndef probability(a):\n    # returns the probability of a given number a\n    return float(c[a]) / len(x)\n\nprob = probability(1)\nprint(prob)\nprint(\"====================\")\n\n# Calculating Continuous Probability\nstart = 5  # Start of the range\nend = 6    # End of the range\nN = 100    # Number of evaluation points\n\n# Step size\nstep = (end - start) / (N - 1)\nprint(\"\\nUniform linear distribution start=%s, end=%s, N=%s, Step size=%s\" % (start, end, N,\n                                                                             step))\n\n# numpy.linspace - Return evenly spaced numbers over a specified interval i.e. uniformly distributed in linear space\n# numpy.logspace - Return numbers spaced evenly on a log scale i.e. uniformly distributed in log space\n\n# Generate values in the range i.e. we can generate a set of points equidistant from each\n# other and estimate the kernel density at each point.\n# np.newaxis might come in handy when you want to explicitly convert a 1D array to either a row vector or a column vector,\n# make it as column vector by inserting an axis along second dimension\n\nx_test_1d = np.linspace(start, end, N)\n\nprint(\"\\nGenerated synthetic data from a uniform linear distribution:\")\nprint(x_test_1d)\n\nx_test = x_test_1d[:, np.newaxis] # make it as column vector by inserting an axis along second dimension\n\nprint(\"\\nShape of synthetic data from a uniform linear distribution:\")\nprint(x_test.shape)\n\n# Get PDF values for each x\n# Please note that kd.score_samples generates log-likelihood of the data samples.\n# Therefore, np.exp is needed to obtain likelihood.\n# When fitting a model your X needs to be 2D array. i.e (n_samples, n_features).\nkde_model = KernelDensity(kernel='gaussian', bandwidth=0.75).fit(x_test)\n\nkd_vals = np.exp(kde_model.score_samples(x_test))\nprint(\"\\nLikelihood from uniform linear distribution synthetic data i.e. density from KDE:\")\nprint(kd_vals)\n\n# Approximate the integral of the PDF\nprobability = np.sum(kd_vals * step)\nprint(\"\\nSumming the integrals of PDF from uniform linear distribution synthetic data  i.e. Probability:\")\nprint(probability)\n\n#Alternative using builtin SciPy integration methods\nfrom scipy.integrate import quad\n\n# Return the integration of a polynomial.\n# The function quad is provided to integrate a function of one variable between two points\n\n# Reshape your data using array.reshape(-1, 1) if your data has a single feature\n\n# When you use .reshape(1, -1) it adds one dimension to the data.\n# Reshape your data using array.reshape(1, -1) if it contains a single sample\n# i.e. np.float64(x).reshape(1,-1) gives array([[ 0.]], dtype=float64) which is akin to [[x]]\nfxn = lambda x: np.exp(kde_model.score_samples(np.float64(x).reshape(1,-1)))\nprobability = quad(fxn, start, end)[0]\n# (quad returns a tuple where the first index is the result,# therefore the [0])\nprint(\"\\nIntegral of PDF i.e. Probability ( using builtin and more accurate SciPy integration methods):\")\nprint(probability)\n\nprint(\"====================\")\n# Generating Synthetic Data from 2 distributions - an asymmetric log-normal distribution and the other one is a Gaussian distribution\nprint(\"\\nGenerating Synthetic Data from an asymmetric log-normal distribution and the other one is a Gaussian distribution\")\n\ndef generate_data(mu1, sigma1, size1, mu2, sigma2, size2, seed):\n    # Fix the seed to reproduce the results\n    rand = np.random.RandomState(seed)\n\n    # Draw samples from a log-normal distribution with specified mean, standard deviation, and array shape.\n    # Note that the mean and standard deviation are not the values for the distribution itself,\n    # but of the underlying normal distribution it is derived from.\n    x = []\n    # mean, standard deviation, size\n    dat = rand.lognormal(mean=mu1, sigma=sigma1, size=size1)\n    x = np.concatenate((x, dat))\n\n    #loc - (Mean) where the peak of the bell exists.\n    # scale - (Standard Deviation) how flat the graph distribution should be.\n    # size - The shape of the returned array.\n    # mean, standard deviation, size\n    dat = rand.normal(loc=mu2, scale=sigma2, size=size2)\n    x = np.concatenate((x, dat))\n    return x\n\nmu1, sigma1, size1 = 0, 0.3, 1000  # mean, standard deviation, size\nmu2, sigma2, size2 = 3, 1, 1000  # mean, standard deviation, size\nseed=17\nx_train_1d = generate_data(mu1, sigma1, size1, mu2, sigma2, size2, seed) #one dimension i.e. 1d\n\nprint(\"\\n Synthetic data from an asymmetric log-normal distribution (mean=%s, sigma=%s,size=%s) and a \"\n      \"\\n Gaussian distribution (mean=%s, standard deviation=%s, size=%s), with shape %s \"\n      \"and length %s:\" % (mu1, sigma1, size1,mu2, sigma2, size2, x_train_1d.shape, x_train_1d.size))\nprint(x_train_1d)\nx_train = x_train_1d[:, np.newaxis] # make it as column vector by inserting an axis along second dimension\n\n# ndarray.size - # Number of elements in the array. Caclulated as np.prod(a.shape), i.e., the product of the array’s dimensions.\nprint(\"====================\")\n\n# Generating Synthetic Data from two Gaussian distributions\nprint(\"\\nGenerating Synthetic Data from two Gaussian distributions\")\n\ndef generate_synthetic_data2(mu1, sigma1, size1, mu2, sigma2, size2, seed):\n    # Fix the seed to reproduce the results\n    rand = np.random.RandomState(seed)\n    x = []\n    dat = rand.normal(mu1, sigma1, size1)\n    x = np.concatenate((x, dat))\n    dat = rand.normal(mu2, sigma2, size2)\n    x = np.concatenate((x, dat))\n    return x\n\nmu1, sigma1, size1 = 6, 1, 1000  # mean, standard deviation, size\nmu2, sigma2, size2 = 3, 1, 1000  # mean, standard deviation, size\nseed=17\nx_train2_1d = generate_synthetic_data2(mu1, sigma1, size1, mu2, sigma2, size2, seed)\nprint(\"\\n Synthetic data from two Gaussian distributions (mean=%s, sigma=%s,size=%s) and (mean=%s, sigma=%s,size=%s)\\n\"\n      \"with shape %s and length %s:\" % (mu1, sigma1, size1,mu2, sigma2, size2, x_train2_1d.shape, x_train2_1d.size))\nprint(x_train2_1d)\nx_train2 = x_train2_1d[:, np.newaxis]\nprint(\"====================\")", "meta": {"hexsha": "1542f8ecf1d755324c84ee37d8f9b1dd7f239f46", "size": 6205, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils.py", "max_stars_repo_name": "jajukajulz/getting-started-guides", "max_stars_repo_head_hexsha": "dd0289947d451e3ae16f18f97240f0c0872a667a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils.py", "max_issues_repo_name": "jajukajulz/getting-started-guides", "max_issues_repo_head_hexsha": "dd0289947d451e3ae16f18f97240f0c0872a667a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils.py", "max_forks_repo_name": "jajukajulz/getting-started-guides", "max_forks_repo_head_hexsha": "dd0289947d451e3ae16f18f97240f0c0872a667a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3214285714, "max_line_length": 133, "alphanum_fraction": 0.7112006446, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611597645271, "lm_q2_score": 0.8976952886860979, "lm_q1q2_score": 0.8621116885577329}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\n# Euler Method\ndef euler_method(n0, decay_const, t_final, n_t_steps):\n    iterations = n_t_steps\n    delta_t = t_final/n_t_steps\n    t1 = np.linspace(0, iterations*delta_t, iterations)\n    n1 = np.zeros(t1.shape, float) \n    n1[0]=n0\n    for i in range(0,len(t1)-1):\n        n1[i+1] = n1[i] * (1 - decay_const * delta_t )\n    n1r = n1/n0\n    return n1, n1r, t1\n\nne, ner, te = euler_method(n0=10000, decay_const=1.54e-1, t_final=20, n_t_steps=10)\n\n#Analitical solution ...in the same points of the Euler method \ndef analytical_solution(n0, decay_const, t_final, n_t_steps):\n    \n    intermediate_points = n_t_steps\n    delta_t = t_final/n_t_steps\n    t2 = np.linspace(0, intermediate_points*delta_t, intermediate_points)\n    n2 = n0 * np.exp(-decay_const * t2 )\n    n2r = n2/n0\n    return n2, n2r, t2\n\nna, nar, ta = analytical_solution(n0=10000, decay_const=1.54e-1, t_final=20, n_t_steps=10)\n\neuler_rel_error = 100*(ne-na)/na\n\nfig = plt.figure()\nax1 = fig.add_subplot(1, 2, 1)\nax1.plot(te, ner, linestyle=\"-\", linewidth=2, label='Euler method')\nax1.plot(ta, nar, linestyle=\"--\", linewidth=2, label='Analytical Solution')\nax1.set_ylabel('Relative Number of $^{238}$U atoms')\nax1.set_xlabel('time in bilion years')  \nax1.legend()\n\nax2 = fig.add_subplot(1, 2, 2)\nax2.plot(te, euler_rel_error, linestyle=\"-\", linewidth=2, label='Deviation formthe \\nexpected value')\nax2.set_ylabel('Relative Error, in %')\nax2.set_xlabel('time in bilion years')  \nax2.legend()\n", "meta": {"hexsha": "de6312620db7863cc5311a9aeba91a71146cf10d", "size": 1507, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/chapter_08/listing_08_04.py", "max_stars_repo_name": "guinslym/python_earth_science_book", "max_stars_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80, "max_stars_repo_stars_event_min_datetime": "2021-04-19T10:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:34:47.000Z", "max_issues_repo_path": "code/chapter_08/listing_08_04.py", "max_issues_repo_name": "guinslym/python_earth_science_book", "max_issues_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/chapter_08/listing_08_04.py", "max_forks_repo_name": "guinslym/python_earth_science_book", "max_forks_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2021-04-25T03:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:06:19.000Z", "avg_line_length": 33.4888888889, "max_line_length": 101, "alphanum_fraction": 0.696748507, "include": true, "reason": "import numpy", "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611631680358, "lm_q2_score": 0.8976952811593495, "lm_q1q2_score": 0.8621116843846498}}
{"text": "import sympy as sy\nimport numpy as np\nimport random\nfrom sympy import *\n\ndef threePointCubicApprox(x,y,xSlopePoint,yPrime):\n\tC3 = (y[2] - y[0])/((x[2] - x[1])*(x[2] - x[0])**2) - (y[1] - y[0])/((x[2] - x[1])*(x[1] - x[0])**2) + yPrime/((x[1]-x[0])*(x[2] - x[0]))\n\tC2 = (((y[1] - y[0])/(x[1] - x[0])) - yPrime)/(x[1] - x[0]) - C3*(2*x[0] + x[1])\n\tC1 = yPrime - 2*C2*x[0] - 3*C3*x[0]**2\n\tC0 = y[0] - C1*x[0] - C2*x[0]**2 - C3*x[0]**3\n\t\n\treturn [C0,C1,C2,C3]\n\ndef threePointQuadraticApprox(x, y):\n\t#Inputs: Vector of x values and y values. These vectors must be equal length\n\t#Outputs: Coefficients for polynomial equation according to the form C0 + C1*x + C2*x^2...\n\tC2 = (((y[2]-y[0])/(x[2]-x[0])) - ((y[1]-y[0])/(x[1]-x[0])))/(x[2]-x[1])\n\tC1 = (y[1] - y[0])/(x[1]-x[0]) - C2*(x[0]+x[1])\n\tC0 = y[0] - C1*x[0] - C2*x[0]**2\n\n\treturn [C0,C1,C2]\n\ndef twoPointLinearApprox(x, y):\n\t#Inputs: Vector of x values and y values. These vectors must be equal length\n\t#Outputs: Coefficients for polynomial equation according to the form C0 + C1*x + C2*x^2...\n\tC1 = (y[1] - y[0])/(x[1]-x[0])\n\tC0 = y[0] - C1*x[0]\n\n\treturn [C0,C1]\n\ndef getValueOfPoly(c,x):\n\t#Inputs: Coefficients for polynomial equation according to the form C0 + C1*x + C2*x^2...\n\t#Inputs: x - value to get value at\n\tconstantQuantity = len(c)\n\n\tif constantQuantity == 1:\n\t\t# Flat line\n\t\ty = c[0]\n\telif constantQuantity == 2:\n\t\t# Linear\n\t\ty = c[0] + c[1] * x\n\telif constantQuantity == 3:\n\t\t# Quadratic\n\t\ty = c[0] + c[1]*x + c[2]*x**2\n\telif constantQuantity == 4:\n\t\t# Cubic\n\t\ty = c[0] + c[1]*x + c[2]*x**2 + c[3]*x**3\n\telse:\n\t\tprint(\"Polynomial could not be calculated. Check getValueOfPoly function.\")\n\t\ty = 99999999\n\n\treturn y", "meta": {"hexsha": "6df2f3dd3b3ae92f5bf8ea4ab2950bb1cc1f7640", "size": 1677, "ext": "py", "lang": "Python", "max_stars_repo_path": "Truss/FunctionApproximation.py", "max_stars_repo_name": "Wright4TheJob/Optimizing", "max_stars_repo_head_hexsha": "0f056e40a24380a48ed469bd4bb565948f7ffaf2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Truss/FunctionApproximation.py", "max_issues_repo_name": "Wright4TheJob/Optimizing", "max_issues_repo_head_hexsha": "0f056e40a24380a48ed469bd4bb565948f7ffaf2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Truss/FunctionApproximation.py", "max_forks_repo_name": "Wright4TheJob/Optimizing", "max_forks_repo_head_hexsha": "0f056e40a24380a48ed469bd4bb565948f7ffaf2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.25, "max_line_length": 138, "alphanum_fraction": 0.5807990459, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9805806529525571, "lm_q2_score": 0.8791467611766711, "lm_q1q2_score": 0.862074305115746}}
{"text": "'''\nData Characteristics \n'''\n\nimport os\nos.chdir(\"C:/Users/tprabhan/Documents/My_Books/RSADBE_2.0/R_and_Python_Programs/Python/Chapter_01\")\nimport matplotlib.pyplot as plt\nimport numpy as np \nimport pylab\n\n# Discrete Uniform Distribution\nM = 10\nmylabels = list(range(1,M+1))\nprob_labels = [1/M]*M\nplt.xlim([0.9,10.1])\nplt.ylim([0,0.11])\nplt.plot(mylabels,prob_labels,marker='o',linestyle='none')\nplt.xlabel(\"Labels\")\nplt.ylabel(\"Probability\")\nplt.title(\"Probability of Discrete Uniform RV\")\nplt.show()\n\n# Binomial Distribution\nn = 10; p = 0.5\nfrom scipy.stats import binom\np_x = binom.pmf(range(1,n+1),n,p)\nplt.plot(range(1,n+1),p_x,marker='o',linestyle='none')\nplt.show()\n\n# Binomial Probabilities\nn = 83; p = 0.01\nfrom scipy.stats import binom\nbinom.pmf(10,n,p)\nbinom.pmf(20,n,p)\nbinom.pmf(30,n,p)\nxr = range(0,84)\nsum(binom.pmf(xr,n,p))\n\n# Hypergeometric Distribution\nN = 200; M = 20\nn = 10\nk = range(0,12)\nfrom scipy.stats import hypergeom\nnp.round(hypergeom.pmf(k,N,M,n),3)\n\n# Poisson Probabilities\nfrom scipy.stats import poisson\npoisson.pmf(0,3)\npoisson.pmf(5,3)\npoisson.pmf(20,3)\n\n# Continuous Uniform Distribution\nfrom scipy.stats import uniform\nuniform.cdf(0.58)-uniform.cdf(0.35)\n\n# Exponential Densities\nfrom scipy.stats import expon\nxr = np.arange(0,10.2,0.20)\nf_x = expon.pdf(xr,scale=1)\npylab.plot(xr,f_x,'r',label='Rate=1')\nf_x1 = expon.pdf(xr,scale=1/0.2)\npylab.plot(xr,f_x1,'g',label='Rate=0.2')\nf_x2 = expon.pdf(xr,scale=1/0.5)\npylab.plot(xr,f_x2,'b',label='Rate=0.5')\nf_x3 = expon.pdf(xr,scale=1/0.7)\npylab.plot(xr,f_x3,'y',label='Rate=0.7')\nf_x4 = expon.pdf(xr,scale=1/0.85)\npylab.plot(xr,f_x4,'purple',label='Rate=0.85')\npylab.legend(loc='upper right')\nplt.show()\n\n# Exponential Densities Continued\nfrom scipy.stats import expon\nxr = np.arange(0,0.5,0.02)\nf_x = expon.pdf(xr,scale=1/50)\npylab.plot(xr,f_x,'r',label='Rate=50')\nf_x1 = expon.pdf(xr,scale=1/10)\npylab.plot(xr,f_x1,'g',label='Rate=10')\nf_x2 = expon.pdf(xr,scale=1/20)\npylab.plot(xr,f_x2,'b',label='Rate=20')\nf_x3 = expon.pdf(xr,scale=1/30)\npylab.plot(xr,f_x3,'y',label='Rate=30')\nf_x4 = expon.pdf(xr,scale=1/40)\npylab.plot(xr,f_x4,'purple',label='Rate=40')\npylab.legend(loc='upper right')\npylab.show()\n\n# Shady Normal Probabilities\nfrom scipy.stats import norm\nxr = np.arange(-4,4.1,0.1)\nfx = norm.pdf(xr)\npylab.plot(xr,fx)\np1 = np.arange(0,4.02,0.02)\npylab.fill_between(p1,norm.pdf(p1))\npylab.show()\nxr = np.arange(-4,4.1,0.1)\nfx = norm.pdf(xr)\npylab.plot(xr,fx)\np2 = np.arange(-1.96,1.961,0.001)\npylab.fill_between(p2,norm.pdf(p2))\npylab.show()\nxr = np.arange(-4,4.1,0.1)\nfx = norm.pdf(xr)\npylab.plot(xr,fx)\np3 = np.arange(-2.58,2.581,0.001)\npylab.fill_between(p3,norm.pdf(p3))\npylab.show()\n", "meta": {"hexsha": "7876513802db5a2a677a3a08df1799bbf555ed46", "size": 2678, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter01/Python/SRC/Chapter_01.py", "max_stars_repo_name": "sachinsunilkumar/Statistical-Application-Development-with-R-and-Python", "max_stars_repo_head_hexsha": "3d8d27c69287cdabf9e21291e210354515c8cb7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-08-31T20:46:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T13:11:15.000Z", "max_issues_repo_path": "Chapter01/Python/SRC/Chapter_01.py", "max_issues_repo_name": "sachinsunilkumar/Statistical-Application-Development-with-R-and-Python", "max_issues_repo_head_hexsha": "3d8d27c69287cdabf9e21291e210354515c8cb7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter01/Python/SRC/Chapter_01.py", "max_forks_repo_name": "sachinsunilkumar/Statistical-Application-Development-with-R-and-Python", "max_forks_repo_head_hexsha": "3d8d27c69287cdabf9e21291e210354515c8cb7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2017-09-03T00:52:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-31T21:22:56.000Z", "avg_line_length": 24.7962962963, "max_line_length": 99, "alphanum_fraction": 0.7087378641, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9787126488274565, "lm_q2_score": 0.8807970889295663, "lm_q1q2_score": 0.8620472519857686}}
{"text": "import numpy as np\n\n'''\n    In mathematics, Chebyshev distance (or Tchebychev distance), maximum metric, \n    or L∞ metric is a metric defined on a vector space where \n    the distance between two vectors is the greatest of their differences \n    along any coordinate dimension.[2] It is named after Pafnuty Chebyshev.\n\n    It is also known as chessboard distance, since in the game of chess the minimum number of \n    moves needed by a king to go from one square on a chessboard to another equals the \n    Chebyshev distance between the centers of the squares, if the squares have side length one, \n    as represented in 2-D spatial coordinates with axes aligned to the edges of the board.\n'''\n\nobjA = [22, 1, 42, 10]\n\nobjB = [20, 0, 36, 8]\n\nnpA = np.array(objA)\n\nnpB = np.array(objB)\n\nchebyshev = np.abs(npA - npB).max()\n\n# chebyshev = np.linalg.norm(npA -npB, ord=np.inf)\n\nprint(chebyshev)", "meta": {"hexsha": "f02f8ccc65fe2fee530e93820de28977d1106921", "size": 892, "ext": "py", "lang": "Python", "max_stars_repo_path": "Distances/superior.py", "max_stars_repo_name": "TheWorstOne/numpy-formulas", "max_stars_repo_head_hexsha": "093657d4a23dfe82685595254aae50e0c6e46afb", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-04-21T00:41:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T06:57:00.000Z", "max_issues_repo_path": "Distances/superior.py", "max_issues_repo_name": "magabydelgado/numpy-formulas", "max_issues_repo_head_hexsha": "093657d4a23dfe82685595254aae50e0c6e46afb", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Distances/superior.py", "max_forks_repo_name": "magabydelgado/numpy-formulas", "max_forks_repo_head_hexsha": "093657d4a23dfe82685595254aae50e0c6e46afb", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-22T03:04:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T18:59:33.000Z", "avg_line_length": 33.037037037, "max_line_length": 96, "alphanum_fraction": 0.7208520179, "include": true, "reason": "import numpy", "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9787126457229186, "lm_q2_score": 0.8807970904940926, "lm_q1q2_score": 0.8620472507825223}}
{"text": "\"\"\"Samples from normal distribution using Box-Muller transformation.\n\nThe transformation is applied to the bivariate normal distribution.\n\"\"\"\nimport typing as t\n\nimport numpy as np\n\n\ndef sample_normal(num_inst: int = 1,\n                  loc: float = 0.0,\n                  scale: float = 1.0,\n                  random_state: t.Optional[int] = None) -> np.ndarray:\n    \"\"\"Sample ``num_inst`` instances from normal distribution.\n\n    Arguments\n    ---------\n    num_inst : :obj:`int`\n        Number of samples to output.\n\n    loc : :obj:`float`\n       Mean of the normal distribution.\n\n    scale : :obj:`float`\n        Standard deviation (not the variance!) of the normal distribution.\n\n    random_state : :obj:`int`, optional\n        If not None, set numpy random seed before the first sampling.\n\n    Returns\n    -------\n    :obj:`np.ndarray`\n        Samples of the normal distribution with ``loc`` mean and ``scale``\n        standard deviation.\n\n    Notes\n    -----\n    Uses the Box-Muller bivariate transformation, which maps two samples\n    from the Uniform Distribution U(0, 1) into two samples of the Normal\n    Distribution N(0, 1).\n    \"\"\"\n    if random_state is not None:\n        np.random.seed(random_state)\n\n    remove_extra_inst = False\n\n    if num_inst % 2:\n        num_inst += 1\n        remove_extra_inst = True\n\n    uniform_samples = np.random.uniform(0, 1, size=(2, num_inst // 2))\n\n    aux_1 = np.sqrt(-2 * np.log(uniform_samples[0, :]))\n    aux_2 = 2 * np.pi * uniform_samples[1, :]\n\n    samples = np.concatenate((aux_1 * np.cos(aux_2), aux_1 * np.sin(aux_2)))\n\n    samples = loc + scale * samples\n\n    if remove_extra_inst:\n        return samples[1:]\n\n    return samples\n\n\ndef _test():\n    import matplotlib.pyplot as plt\n    import scipy.stats\n\n    plt.subplot(1, 2, 1)\n    vals = np.linspace(-4, 4, 100)\n    plt.plot(vals, scipy.stats.norm(loc=0, scale=1).pdf(vals))\n    samples = sample_normal(num_inst=1000, random_state=16)\n    plt.hist(samples, bins=64, density=True)\n    plt.title(\"N(0, 1)\")\n\n    plt.subplot(1, 2, 2)\n    vals = np.linspace(-20, 20, 100)\n    plt.plot(vals, scipy.stats.norm(loc=6, scale=3).pdf(vals))\n    samples = sample_normal(loc=6, scale=3, num_inst=1000, random_state=32)\n    plt.hist(samples, bins=64, density=True)\n    plt.title(\"N(6, 3)\")\n\n    plt.show()\n\n\nif __name__ == \"__main__\":\n    _test()\n", "meta": {"hexsha": "eac3a3797996ea5f18aa3eede9214128f3efeb6c", "size": 2346, "ext": "py", "lang": "Python", "max_stars_repo_path": "dist_sampling_and_related_stats/normal_sampling_box_muller.py", "max_stars_repo_name": "FelSiq/statistics-related", "max_stars_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-13T02:09:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-13T02:09:08.000Z", "max_issues_repo_path": "dist_sampling_and_related_stats/normal_sampling_box_muller.py", "max_issues_repo_name": "FelSiq/statistics-related", "max_issues_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dist_sampling_and_related_stats/normal_sampling_box_muller.py", "max_forks_repo_name": "FelSiq/statistics-related", "max_forks_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3595505618, "max_line_length": 76, "alphanum_fraction": 0.6265984655, "include": true, "reason": "import numpy,import scipy", "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810525948927, "lm_q2_score": 0.9099070048165069, "lm_q1q2_score": 0.8620286559865283}}
{"text": "from typing import Callable, List, Optional\nimport numpy as np\n\nimport lab1.src.grad.grad_step_strategy as st\nimport lab1.src.grad.stop_criteria as sc\n\n\nDEFAULT_EPSILON = 1e-9\nDEFAULT_MAX_ITERATIONS = 1e5\n\n\ndef gradient_descent(f: Callable[[np.ndarray], float],\n                     f_grad: Callable[[np.ndarray], np.ndarray],\n                     start: np.ndarray,\n                     step_strategy: st.StepStrategy,\n                     stop_criteria: sc.StopCriteria,\n                     eps_strategy: float = DEFAULT_EPSILON,\n                     eps_stop_criteria: float = DEFAULT_EPSILON,\n                     max_iterations_strategy=DEFAULT_MAX_ITERATIONS,\n                     max_iterations_criteria=DEFAULT_MAX_ITERATIONS,\n                     trajectory: Optional[List] = None):\n    strategy = st.get_step_strategy(step_strategy, f, f_grad, eps_strategy, max_iterations_strategy)\n    criteria = sc.get_stop_criteria(stop_criteria, f, f_grad, eps_stop_criteria, max_iterations_criteria)\n    cur_x = start\n    iters = 0\n\n    if trajectory is not None:\n        trajectory.append(cur_x)\n\n    while True:\n        iters += 1\n        cur_grad = f_grad(cur_x)\n        step = strategy.next_step(cur_x)\n        next_x = cur_x - step * cur_grad\n\n        if criteria.should_stop(cur_x, next_x):\n            return cur_x, iters\n\n        cur_x = next_x\n        if trajectory is not None:\n            trajectory.append(cur_x)\n\n        if iters == max_iterations_criteria:\n            return cur_x, iters\n\n\nif __name__ == '__main__':\n    def foo(p):\n        return p[0] ** 2 + p[1] ** 2\n\n    def foo_grad(p):\n        x, y = p[0], p[1]\n        return np.array([2 * x, 2 * y])\n\n\n    res, _ = gradient_descent(foo,\n                              foo_grad,\n                              start=np.array([3, 4]),\n                              step_strategy=st.StepStrategy.DIVIDE_STEP,\n                              stop_criteria=sc.StopCriteria.BY_GRAD)\n    print(res)\n", "meta": {"hexsha": "3a92bd4b9eca0f596a3ff84b0d2fe8bbd66b24ff", "size": 1961, "ext": "py", "lang": "Python", "max_stars_repo_path": "lab1/src/grad/grad_descent.py", "max_stars_repo_name": "pavponn/optimization-methods", "max_stars_repo_head_hexsha": "00db08c1b28a1ffad781fb918869247a4f2ab329", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab1/src/grad/grad_descent.py", "max_issues_repo_name": "pavponn/optimization-methods", "max_issues_repo_head_hexsha": "00db08c1b28a1ffad781fb918869247a4f2ab329", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab1/src/grad/grad_descent.py", "max_forks_repo_name": "pavponn/optimization-methods", "max_forks_repo_head_hexsha": "00db08c1b28a1ffad781fb918869247a4f2ab329", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6290322581, "max_line_length": 105, "alphanum_fraction": 0.5854156043, "include": true, "reason": "import numpy", "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096792, "lm_q2_score": 0.9099070097026719, "lm_q1q2_score": 0.8620286498011495}}
{"text": "import numpy as np\nimport cv2\nimport math\n\ndef medianFilter(image, size=3):\n    return np.uint8(cv2.medianBlur(src=image, ksize=size))\n\ndef discreteFourierTransform(image):\n    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n\n    dft = cv2.dft(np.float32(gray), flags = cv2.DFT_COMPLEX_OUTPUT)\n    dft_shift = np.fft.fftshift(dft)\n\n    magnitude_spectrum = 20*np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))\n\n    return magnitude_spectrum\n\ndef butterworthLowPassMask(width,height,dinit = 20,n = 1):\n    width = width / 2\n    height = height / 2\n\n    hw = np.arange(-width, width)\n    hh = np.arange(-height, height)\n\n    x, y = np.meshgrid(hh, hw)\n    mg = np.sqrt(x**2 + y**2)\n    return 1 / (1 + (mg/dinit)**(2*n))\n    \ndef butterworthHighPassMask(width,height,dinit = 20,n = 1):\n    width = width / 2\n    height = height / 2\n\n    hw = np.arange(-width, width)\n    hh = np.arange(-height, height)\n\n    x, y = np.meshgrid(hh, hw)\n    mg = np.sqrt(x**2 + y**2)\n    return 1 / (1 + (dinit/mg)**(2*n))\n\ndef butterworthFilter(image, d=20, n=1, filter_type=\"low\"):\n    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n    width, height = gray.shape\n\n    mask = \"\"\n    if filter_type == \"low\":\n        mask = butterworthLowPassMask(width, height, d, n) \n    elif filter_type == \"high\":\n        mask = butterworthHighPassMask(width, height, d, n)\n\n    fft = np.fft.fftshift(np.fft.fft2(np.float32(gray)))\n\n    img_pass = mask * fft\n    result = np.abs(np.fft.ifft2(np.fft.ifftshift(img_pass)))\n\n    return result\n\ndef imsave(num, algo, img):\n    imname = \"radiograph_{}_{}.jpg\".format(num, algo)\n    cv2.imwrite(\"./output/\" + imname, img)\n\nif __name__ == \"__main__\":\n    img_1 = cv2.imread(\"./samples/radiograph_1.jpg\")\n    img_2 = cv2.imread(\"./samples/radiograph_2.jpg\")\n\n    # Apply Median Filter with Adjusted Kernel's Size\n    imsave(1, \"median_filter\", medianFilter(img_1, 15))\n    imsave(2, \"median_filter\", medianFilter(img_2, 11))\n\n    # Apply Discrete Fourier Transform\n    imsave(1, \"dft\", discreteFourierTransform(img_1))\n    imsave(2, \"dft\", discreteFourierTransform(img_2))\n\n    # Apply Butterworth Lowpass Filter\n    imsave(1, \"butterworth_lowpass\", butterworthFilter(img_1, 20, 2, \"low\"))\n    imsave(2, \"butterworth_lowpass\", butterworthFilter(img_2, 20, 3, \"low\"))\n\n    # Apply Butterworth Highpass Filter\n    imsave(1, \"butterworth_highpass\", butterworthFilter(img_1, 100, 1, \"high\"))\n    imsave(2, \"butterworth_highpass\", butterworthFilter(img_2, 40, 1, \"high\"))\n", "meta": {"hexsha": "a4111dfd3cf6cc00b49ac92f55165ab207798aa5", "size": 2482, "ext": "py", "lang": "Python", "max_stars_repo_path": "DigitalImageProcessing/Exercises/homework_4/main.py", "max_stars_repo_name": "nguyenvlm/LearningComputerVision", "max_stars_repo_head_hexsha": "dd00efa54c86f150b096dca0a97eb2fdb343fe0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DigitalImageProcessing/Exercises/homework_4/main.py", "max_issues_repo_name": "nguyenvlm/LearningComputerVision", "max_issues_repo_head_hexsha": "dd00efa54c86f150b096dca0a97eb2fdb343fe0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DigitalImageProcessing/Exercises/homework_4/main.py", "max_forks_repo_name": "nguyenvlm/LearningComputerVision", "max_forks_repo_head_hexsha": "dd00efa54c86f150b096dca0a97eb2fdb343fe0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.025, "max_line_length": 84, "alphanum_fraction": 0.6599516519, "include": true, "reason": "import numpy", "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639661317859, "lm_q2_score": 0.8872045981907006, "lm_q1q2_score": 0.8619760181885145}}
{"text": "# Necessary Packages\nimport numpy as np\n\n#%% AR(1) Generation. \n'''\nX_t = coef * X_t-1 + n \nn ~ N(0, sigma^2)\nsigma = np.sqrt(margin*(1-coef*coef)) \nTherefore, Marginal distribution is N(0, margin)\n\nInputs\n- n: Number of samples\n- p: Number of features\n- phi: Autoregressiveness\n- margin: Std of the normal distribution \n'''\ndef AR_Gauss_X1 (n, d, t, phi, sigma):\n\n    # Initialization\n    Output_X = list()\n                \n    # For each sample\n    for i in range(n):\n        \n        Temp_Output_X = np.zeros([t,d])\n        \n        # For each feature\n        for j in range(d):\n        \n            for k in range(t):\n              \n                # Starting feature\n                if (k == 0):            \n                    Temp_Output_X[k,j] = np.random.normal(0,sigma)\n                                \n                # AR(1) Generation\n                else:                \n                    Temp_Output_X[k,j] = phi[j] * Temp_Output_X[k-1,j] + (1-phi[j])*np.random.normal(0,sigma)\n    \n        Output_X.append(Temp_Output_X)    \n    \n    return Output_X\n  \n#%% \ndef AR_Gauss_X2 (n, d, t, phi, sigma, gamma):\n\n    # Initialization\n    Output_X = list()\n                \n    # For each sample\n    for i in range(n):\n        \n        Temp_Output_X = np.zeros([t,2*d])\n        \n        # For each feature\n        for j in range(d):\n        \n            for k in range(t):\n              \n                # Starting feature\n                if (k == 0):            \n                    Temp_Output_X[k,j] = np.random.normal(0,sigma)\n                                \n                # AR(1) Generation\n                else:                \n                    Temp_Output_X[k,j] = phi[j] * Temp_Output_X[k-1,j] + (1-phi[j])*np.random.normal(0,sigma)\n                \n                Temp_Output_X[k,d+j] = Temp_Output_X[k,j] + np.random.normal(0,gamma)       \n        \n    \n        Output_X.append(Temp_Output_X)    \n    \n    return Output_X\n  ", "meta": {"hexsha": "4880ff085df40a98750600413fb92e16d56fc38e", "size": 1951, "ext": "py", "lang": "Python", "max_stars_repo_path": "alg/asac/Data_Generation_X.py", "max_stars_repo_name": "loramf/mlforhealthlabpub", "max_stars_repo_head_hexsha": "aa5a42a4814cf69c8223f27c21324ee39d43c404", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 171, "max_stars_repo_stars_event_min_datetime": "2021-02-12T10:23:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:58:52.000Z", "max_issues_repo_path": "alg/asac/Data_Generation_X.py", "max_issues_repo_name": "loramf/mlforhealthlabpub", "max_issues_repo_head_hexsha": "aa5a42a4814cf69c8223f27c21324ee39d43c404", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-06-01T08:18:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T13:37:30.000Z", "max_forks_repo_path": "alg/asac/Data_Generation_X.py", "max_forks_repo_name": "loramf/mlforhealthlabpub", "max_forks_repo_head_hexsha": "aa5a42a4814cf69c8223f27c21324ee39d43c404", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 93, "max_forks_repo_forks_event_min_datetime": "2021-02-10T03:21:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T19:10:37.000Z", "avg_line_length": 26.3648648649, "max_line_length": 109, "alphanum_fraction": 0.4592516658, "include": true, "reason": "import numpy", "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639653084244, "lm_q2_score": 0.8872045981907006, "lm_q1q2_score": 0.8619760174580244}}
{"text": "#!/usr/bin/env python3\n\nimport sys\nimport numpy as np\nfrom math import pi, sqrt\nimport cvxopt\nfrom cvxopt import matrix, solvers\n\ndef gen_eq_bloch_states(n, C=3.6, return_angles=True):\n    '''\n    Generates equally spaced points on the bloch sphere through a spiral. \n    See here: https://www.intlpress.com/site/pub/files/_fulltext/journals/mrl/1994/0001/0006/MRL-1994-0001-0006-a003.pdf\n\n    ==========\n    Parameters\n    ----------\n    n (type=int): the number of points to be generated evenly on the sphere\n    C (type=float, default=3.6): constant that makes sure that succesive points \n                                 on S^2 will be the same Euclidean distance apart\n    return_angles (type=boolean, default=True): whether to also return the angles \n                                                associated with each state\n    ==========\n    \n    ======\n    Return\n    ------\n    (type=numpy.array): an array for n evenly spaced coordinates on the block sphere, \n                         with their associated angles if needed\n    ======\n    '''\n    states = np.zeros((n, 2), dtype=complex)\n    h = np.zeros(n)\n    theta = np.zeros(n)\n    phi = np.zeros(n)\n    \n    # initialize\n    h[0] = -1\n    h[n-1] = -1 + 2*(n-1)/(n-1)\n    theta[0] = np.arccos(h[0])\n    theta[n-1] = np.arccos(h[n-1]) \n    phi[0] = 0\n    phi[n-1] = 0\n    states[0] = [np.cos(theta[0]/2), np.sin(theta[0]/2)*np.exp(1j*phi[0])]\n    states[n-1] = [np.cos(theta[n-1]/2), np.sin(theta[n-1]/2)*np.exp(1j*phi[n-1])]\n    \n    # the rest of the states\n    for k in range(1, n-1):\n        h[k] = -1 + 2*(k)/(n-1)\n        theta[k] = np.arccos(h[k])\n        phi[k] = np.mod(phi[k] + C/(sqrt(n)*sqrt(1 - h[k]**2)), 2*pi)\n        states[k] = [np.cos(theta[k]/2), np.sin(theta[k]/2)*np.exp(1j*phi[k])]\n    \n    if return_angles==True:\n        return [states, theta, phi]\n    else:\n        return states\n\n\ndef vec(M):\n    '''\n    Converts an n x m matrix into a column vector, where the first n entries\n    corresponds to the first column of the matrix, the next n entries to the \n    second column, and so on.\n    \n    https://stackoverflow.com/a/25248378\n\n    ==========\n    Parameters\n    ----------\n    M (type=numpy.array): the matrix to use for the column vector\n    ==========\n    \n    ======\n    Return\n    ------\n    (type=numpy.array): the column vector\n    ======\n    '''\n    return M.reshape((-1, 1), order=\"F\")\n\ndef mat(v, n, m, dty=float):\n    '''\n    Converts a vector of length n*m to an n x m matrix where the first n entries\n    corresponds to the first column of the matrix, the next n entries to the \n    second column, and so on.\n    \n    ==========\n    Parameters\n    ----------\n    v (type=numpy.array): the array to use for the matrix\n    n (type=int): number of rows for the matrix\n    m (type=int): number of columns for the matrix\n    dty (type=type): type of the matrix\n    ==========\n    \n    ======\n    Return\n    ------\n    (type=numpy.array): the matrix\n    ======\n    '''\n    M = np.zeros((n, m), dtype=dty)\n    for i in range(n):\n        for j in range(m):\n            M[i][j] = v[n*j + i]\n    return M\n\ndef s_min(E, W, F, n, m):\n    '''\n    Function that minimizes the estimated state space, S, with a fixed effect space\n    according to the following quadratic program:\n    \n    minimize_{S} vec(S)^T @ (E x I_n) @ W (E^T x I_n) vec(S) - 2 vec(S)^T @ (E x I_n) @ W @ vec(F)\n    \n    subject to 0 <= (E^T x I_n) @ vec(S) <= 1 (element wise inequality)\n    \n    ==========\n    Parameters\n    ----------\n    E (type=numpy.array): fixed effect space matrix; dim = k x m\n    W (type=numpy.array): matrix that encodes the uncertainties along the diagonal \n                          for each preparation/measurement pair; dim = n*m x n*m\n    F (type=numpy.array): data matrix; dim = n x m\n    n (type=int): number of preparations\n    m (type=int): number of measurements\n    ==========\n    \n    ======\n    Return\n    ------\n    (type=numpy.array): the solution to the quadratic program\n    ======\n    '''\n    I_n = np.identity(n, dtype=float)\n    P = 2 * (np.kron(E, I_n)) @ W @ (np.kron(np.transpose(E), I_n))\n    q = -2 * np.kron(E, I_n) @ W @ vec(F)\n    G_0 = -np.kron(np.transpose(E), I_n)\n    G_1 = np.kron(np.transpose(E), I_n)\n    h_0 = (np.zeros(n*m))\n    h_1 = (np.ones(n*m))\n    \n    P = matrix(P)\n    q = matrix(q)\n    G = matrix(np.concatenate([G_0, G_1]))\n    h = matrix(np.concatenate([h_0, h_1]))\n    \n    return solvers.qp(P, q, G, h, kktsolver=\"chol\")\n\ndef e_min(S, W, F, n, m):\n    '''\n    Function that minimizes the estimated effect space, E, with a fixed state space\n    according to the following quadratic program:\n    \n    minimize_{E} vec(E)^T @ (I_m x S)^T @ W (I_m x S) vec(S) - 2 vec(S)^T @ (I_m x S)^T @ W @ vec(F)\n    \n    subject to 0 <= (I_m x S) @ vec(E) <= 1 (element wise inequality)\n    \n    ==========\n    Parameters\n    ----------\n    S (type=numpy.array): fixed state space matrix; dim = k x m\n    W (type=numpy.array): matrix that encodes the uncertainties along the diagonal \n                          for each preparation/measurement pair; dim = n*m x n*m\n    F (type=numpy.array): data matrix; dim = n x m\n    n (type=int): number of preparations\n    m (type=int): number of measurements\n    ==========\n    \n    ======\n    Return\n    ------\n    (type=numpy.array): the solution to the quadratic program\n    ======\n    '''\n    I_m = np.identity(m, dtype=float)\n    P = 2 * (np.transpose(np.kron(I_m, S))) @ W @ (np.kron(I_m, S))\n    q = -2 * np.transpose(np.kron(I_m, S)) @ W @ vec(F)\n    G_0 = -np.kron(I_m, S)\n    G_1 = np.kron(I_m, S)\n    h_0 = (np.zeros(n*m))\n    h_1 = (np.ones(n*m))\n    \n    P = matrix(P)\n    q = matrix(q)\n    G = matrix(np.concatenate([G_0, G_1]))\n    h = matrix(np.concatenate([h_0, h_1]))\n    \n    return solvers.qp(P, q, G, h, kktsolver=\"chol\")\n\ndef chi_squared(S, E, F, W, n, m):\n    '''\n    Calculates the weighted chi^2 value.\n\n    ==========\n    Parameters\n    ----------\n    S (type=numpy.array): state space matrix; dim = n x k\n    E (type=numpy.array): effect space matrix; dim = k x m\n    F (type=numpy.array): data matrix; dim = n x m\n    W (type=numpy.array): matrix that encodes the uncertainties along the diagonal \n                          for each preparation/measurement pair; dim = n*m x n*m\n    n (type=int): number of preparations\n    m (type=int): number of measurements\n    ==========\n    \n    ======\n    Return\n    ------\n    (type=float): the chi^2 value\n    ======\n    '''\n    sum = 0\n    w_index = 0\n    D = S @ E\n    for i in range(n):\n        for j in range(m):\n            sum += ((F[i][j] - D[i][j]))**2 * W[w_index][w_index]\n            w_index += 1\n    return sum\n\ndef bfp(k, E_0, F, W, n, m, max_iterations=5000, convergence_threshold=10E-6):\n    '''\n    Finds the low-rank matrix that best fits the data matrix of frequencies.  \n\n    ==========\n    Parameters\n    ----------\n    k (type=int): rank of best-fit matrix\n    E_0 (type=numpy.array): initial estimate of effect space matrix; dim = k x m\n    F (type=numpy.array): data matrix; dim = n x m\n    W (type=numpy.array): matrix that encodes the uncertainties along the diagonal \n                          for each preparation/measurement pair; dim = n*m x n*m\n    n (type=int): number of preparations\n    m (type=int): number of measurements\n    max_iterations (type=int, default=5000): the max number of iterations to go through\n                                             for the optimization\n    convergence_threshold (type=float, default=10E-16): the convergence threshold for \n                                                        the optimization\n    ==========\n    \n    ======\n    Return\n    ------\n    (type=numpy.array): an array that contains the estimated state space and effect space matrices\n    ======\n    '''\n    S = np.zeros((n, k), dtype=float)\n    E = E_0\n    chi_squared_prev = 0\n    chi_squared_curr = 0\n    iteration = 1\n    while (True):\n        chi_squared_prev = chi_squared_curr\n        S = mat(s_min(E, W, F, n, m)['x'], n, k)\n        E = mat(e_min(S, W, F, n, m)['x'], k, m)\n        chi_squared_curr = chi_squared(S, E, F, W, n, m)\n        if (iteration == max_iterations or (chi_squared_curr -  chi_squared_prev) < convergence_threshold):\n            break\n        iteration += 1\n    return [S, E]\n\n####################################################\n#==================================================#\n####################################################\n\ndef aic(k, chi_squared_k, m, n):\n    r_k = k*(m + n - k)\n    return chi_squared_k + r_k\n\ndef is_pos_semi_def(A, tol=1e-8):\n    E = np.linalg.eigvalsh(A)\n    return np.all(E > -tol)\n\ndef S_min(S, E, F, W, m):\n    I_m = np.identity(m)\n    A_1 = np.transpose(vec(S)) @ (np.kron(E, I_m)) @ W @ (np.kron(np.transpose(E), I_m)) @ vec(S)\n    A_2 = 2 * np.transpose(vec(S)) @ (np.kron(E, I_m)) @ W @ vec(F)\n    A = A_1 - A_2\n    return A[0][0]\n\ndef E_min(E, S, F, W, n):\n    I_n = np.identity(n)\n    A_1 = np.transpose(vec(E)) @ np.transpose(np.kron(I_n, S)) @ W @ (np.kron(I_n, S)) @ vec(E)\n    A_2 = 2 * np.transpose(vec(E)) @ np.transpose(np.kron(I_n, S)) @ W @ vec(F)\n    A = A_1 - A_2\n    return A[0][0]\n\ndef cvxopt_solve_qp(P, q, G=None, h=None, A=None, b=None):\n    P = .5 * (P + P.T)  # make sure P is symmetric\n    args = [cvxopt.matrix(P), cvxopt.matrix(q)]\n    if G is not None:\n        args.extend([cvxopt.matrix(G), cvxopt.matrix(h)])\n        if A is not None:\n            args.extend([cvxopt.matrix(A), cvxopt.matrix(b)])\n    sol = cvxopt.solvers.qp(*args)\n    if 'optimal' not in sol['status']:\n        return None\n    return np.array(sol['x']).reshape((P.shape[1],))\n\ndef quadprog_solve_qp(P, q, G=None, h=None, A=None, b=None):\n    qp_G = .5 * (P + P.T)   # make sure P is symmetric\n    qp_a = -q\n    if A is not None:\n        qp_C = -numpy.vstack([A, G]).T\n        qp_b = -numpy.hstack([b, h])\n        meq = A.shape[0]\n    else:  # no equality constraint\n        qp_C = -G.T\n        qp_b = -h\n        meq = 0\n    return quadprog.solve_qp(qp_G, qp_a, qp_C, qp_b, meq)[0]\n\ndef wrla_1(U, V, A, W):\n    A_tilda = U @ V\n    summation = 0\n    w = 0\n    for i in range(len(A)):\n        for j in range(len(A[0])):\n            summation += W[w][w] * ((A[i][j] - A_tilda[i][j])**2)\n    return summation\n\ndef wrla_2(V, U, A, W):\n    A_tilda = U @ V\n    summation = 0\n    w = 0\n    for i in range(len(A)):\n        for j in range(len(A[0])):\n            summation += W[w][w] * ((A[i][j] - A_tilda[i][j])**2)\n    return summation", "meta": {"hexsha": "9878a07f462d4e047b41e9e301b6d581e300d253", "size": 10467, "ext": "py", "lang": "Python", "max_stars_repo_path": "GPT/gpt.py", "max_stars_repo_name": "jd-anabi/quantum-research-iqs", "max_stars_repo_head_hexsha": "3df2855689ab912fa553dc5f64c1df6e5c27e4e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GPT/gpt.py", "max_issues_repo_name": "jd-anabi/quantum-research-iqs", "max_issues_repo_head_hexsha": "3df2855689ab912fa553dc5f64c1df6e5c27e4e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GPT/gpt.py", "max_forks_repo_name": "jd-anabi/quantum-research-iqs", "max_forks_repo_head_hexsha": "3df2855689ab912fa553dc5f64c1df6e5c27e4e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8145896657, "max_line_length": 120, "alphanum_fraction": 0.5393140346, "include": true, "reason": "import numpy", "num_tokens": 3151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639694252316, "lm_q2_score": 0.8872045832787205, "lm_q1q2_score": 0.8619760066225322}}
{"text": "'''\n------------------------------------\nAssignment 9 - EE2703 (Jan-May 2020)\nDone by Akilesh Kannan (EE18B122)\nCreated on 20/03/20\nLast Modified on 27/04/20\n------------------------------------\n'''\n\n# Imports\nimport cmath\nimport numpy as np\nimport numpy.fft as fft\nimport matplotlib.pyplot as plt\nfrom scipy.linalg import lstsq\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n\n# Global Variables\nplotsDir = 'plots/'\nPI = np.pi\nfigNum = 0\nshowAll = True\n\n# Functions used\ndef hammingWindow(n):\n    '''\n                    0.54 + 0.46*cos(2πn/(N−1)), |n| <= (N-1)/2\n        w[n] =\n                    0, otherwise\n    '''\n\n    N = n.size\n    window = np.zeros(N)\n    window = 0.54 + 0.46*np.cos((2*PI*n)/(N-1))\n    return fft.fftshift(window)\n\ndef plotSignal(t, x, figTitle, style='b-', blockFig=False, showFig=True, saveFig=False):\n    global figNum\n    plt.figure(figNum)\n    plt.title(figTitle)\n    plt.grid()\n    plt.plot(t, x, style)\n    if(saveFig):\n        plt.savefig(plotsDir + \"Fig\"+str(figNum)+\".png\")\n    if(showFig):\n        plt.show(block=blockFig)\n    figNum+=1\n\n\ndef plotSpectrum(figTitle, w, Y, magStyle='b-', phaseStyle='ro', xLimit=None, yLimit=None, showFig=False, saveFig=True, blockFig=False):\n    global figNum\n    plt.figure(figNum)\n    plt.suptitle(figTitle)\n    plt.subplot(211)\n    plt.grid()\n    plt.plot(w, abs(Y), magStyle, lw=2)\n    plt.ylabel(r\"$\\|Y\\|$\")\n    if (xLimit):\n        plt.xlim(xLimit)\n    if (yLimit):\n        plt.ylim(yLimit)\n    plt.subplot(212)\n    plt.grid()\n    plt.plot(w, np.angle(Y), phaseStyle, lw=2)\n    plt.xlim(xLimit)\n    plt.ylabel(r\"$\\angle Y$\")\n    plt.xlabel(r\"$\\omega\\ \\to$\")\n\n    if(saveFig):\n        plt.savefig(plotsDir + \"Fig\"+str(figNum)+\".png\")\n    if(showFig):\n        plt.show(block=blockFig)\n    figNum+=1\n\n# Example 1 - sin(sqrt(2)t)\n\n    ## Without windowing\n\nt = np.linspace(-PI, PI, 65)[:-1]\ndt = t[1]-t[0]\nfmax = 1/dt\ny = np.sin(cmath.sqrt(2)*t)\ny[0] = 0\ny = fft.fftshift(y)\nY = fft.fftshift(fft.fft(y))/64.0\nw = np.linspace(-PI*fmax, PI*fmax, 65)[:-1]\nplotSpectrum(r\"Spectrum of $sin(\\sqrt{2}t)$\", w, Y, xLimit=[-10, 10], showFig=showAll)\n\n    ## Windowing with Hamming Window\n\nt = np.linspace(-PI, PI, 65)[:-1]\ndt = t[1]-t[0]\nfmax = 1/dt\nn = np.arange(64)\ny = np.sin(cmath.sqrt(2)*t) * hammingWindow(n)\ny[0] = 0\ny = fft.fftshift(y)\nY = fft.fftshift(fft.fft(y))/64.0\nw = np.linspace(-PI*fmax, PI*fmax, 65)[:-1]\nplotSpectrum(r\"Spectrum of $sin(\\sqrt{2}t) * w(t)$\", w, Y, xLimit=[-8, 8], showFig=showAll)\n\n\n# Question 2 - spectrum of (cos(0.86 t))**3\n\n    ## Without windowing\n\nt = np.linspace(-4*PI, 4*PI, 257)[:-1]\ndt = t[1]-t[0]\nfmax = 1/dt\ny = np.cos(0.86*t)**3\ny[0] = 0\ny = fft.fftshift(y)\nY = fft.fftshift(fft.fft(y))/256.0\nw = np.linspace(-PI*fmax, PI*fmax, 257)[:-1]\nplotSpectrum(r\"Spectrum of $cos^3(0.86t)$\", w, Y, xLimit=[-8, 8], showFig=showAll)\n\n    ## Windowing with Hamming Window\n\nt = np.linspace(-4*PI, 4*PI, 257)[:-1]\ndt = t[1]-t[0]\nfmax = 1/dt\nn = np.arange(256)\ny = (np.cos(0.86*t))**3 * hammingWindow(n)\ny[0] = 0\ny = fft.fftshift(y)\nY = fft.fftshift(fft.fft(y))/256.0\nw = np.linspace(-PI*fmax, PI*fmax, 257)[:-1]\nplotSpectrum(r\"Spectrum of $cos^3(0.86t) * w(t)$\", w, Y, xLimit=[-8, 8], showFig=showAll)\n\n\ndef estimateWandD(w, wo, Y, do, pow=2):\n    wEstimate = np.sum(abs(Y)**pow * abs(w))/np.sum(abs(Y)**pow) # weighted average\n    print(\"wo = {:.03f}\\t\\two (Estimated) = {:.03f}\".format(wo, wEstimate))\n\n    t = np.linspace(-PI, PI, 129)[:-1]\n    y = np.cos(wo*t + do)\n\n    c1 = np.cos(wEstimate*t)\n    c2 = np.sin(wEstimate*t)\n    A = np.c_[c1, c2]\n    vals = lstsq(A, y)[0]\n    dEstimate = np.arctan2(-vals[1], vals[0])\n    print(\"do = {:.03f}\\t\\tdo (Estimated) = {:.03f}\".format(do, dEstimate))\n\n\n# Question 3 - Estimation of w, d in cos(wt + d)\nwo = 1.35\nd = PI/2\n\nprint(\"Question 3:\")\nt = np.linspace(-PI, PI, 129)[:-1]\ntrueCos = np.cos(wo*t + d)\nfmax = 1.0/(t[1]-t[0])\nn = np.arange(128)\ny = trueCos.copy()*hammingWindow(n)\ny = fft.fftshift(y)\nY = fft.fftshift(fft.fft(y))/128.0\nw = np.linspace(-PI*fmax, PI*fmax, 129)[:-1]\nplotSpectrum(r\"Spectrum of $cos(\\omega_o t + \\delta) \\cdot w(t)$\", w, Y, xLimit=[-4, 4], showFig=showAll, saveFig=False)\nestimateWandD(w, wo, Y, d, pow=1.75)\n\n# Question 4 - Estimation of w, d in noisy cos(wt + d)\n\nprint(\"\\nQuestion 4:\")\ntrueCos = np.cos(wo*t + d)\nnoise = 0.1*np.random.randn(128)\nn = np.arange(128)\ny = (trueCos + noise)*hammingWindow(n)\nfmax = 1.0/(t[1]-t[0])\ny = fft.fftshift(y)\nY = fft.fftshift(fft.fft(y))/128.0\nw = np.linspace(-PI*fmax, PI*fmax, 129)[:-1]\nplotSpectrum(r\"Spectrum of $(cos(\\omega_o t + \\delta) + noise) \\cdot w(t)$\", w, Y, xLimit=[-4, 4], showFig=showAll, saveFig=False)\nestimateWandD(w, wo, Y, d, pow=2.5)\n\n# Question 5 - DFT of chirp\n\n# chirp function used\ndef chirp(t):\n    return np.cos(16*(1.5*t + (t**2)/(2*PI)))\n\nt = np.linspace(-PI, PI, 1025)[:-1]\nx = chirp(t)\nplotSignal(t, x, r\"$cos(16(1.5 + \\frac{t}{2\\pi})t)$\", saveFig=True)\nfmax = 1.0/(t[1]-t[0])\nX = fft.fftshift(fft.fft(x))/1024.0\nw = np.linspace(-PI*fmax, PI*fmax, 1025)[:-1]\nplotSpectrum(r\"DFT of $cos(16(1.5 + \\frac{t}{2\\pi})t)$\", w, X, 'b-', 'r.-', [-75, 75], showFig=showAll, saveFig=True)\n\nn = np.arange(1024)\nx = chirp(t)*hammingWindow(n)\nplotSignal(t, x, r\" $cos(16(1.5 + \\frac{t}{2\\pi})t) \\cdot w(t)$\", saveFig=True)\nX = fft.fftshift(fft.fft(x))/1024.0\nplotSpectrum(r\"DFT of $cos(16(1.5 + \\frac{t}{2\\pi})t) \\cdot w(t)$\", w, X, 'b-', 'r.-', [-75, 75], showFig=showAll, saveFig=True)\n\n# Question 6 - Time evolution of DFT of chirp signal\n\n# calculates DFT of x, taking every batchSize samples\ndef STFT(x, t, batchSize=64):\n    t_batch = np.split(t, 1024//batchSize)\n    x_batch = np.split(x, 1024//batchSize)\n    X = np.zeros((1024//batchSize, batchSize), dtype=complex)\n    for i in range(1024//batchSize):\n        X[i] = fft.fftshift(fft.fft(x_batch[i]))/batchSize\n    return X\n\n# plots the STFT\ndef plot3DSTFT(t, w, X, colorMap=cm.viridis, showFig=showAll, saveFig=True, blockFig=False):\n    global figNum\n\n    t = t[::64]\n    w = np.linspace(-fmax*PI,fmax*PI,65)[:-1]\n    t, w = np.meshgrid(t, w)\n\n    fig = plt.figure(figNum)\n    ax = fig.add_subplot(211, projection='3d')\n    surf = ax.plot_surface(w, t, abs(X).T, cmap=colorMap)\n    fig.colorbar(surf)\n    plt.xlabel(r\"Frequency $\\to$\")\n    plt.ylabel(r\"Time $\\to$\")\n    plt.title(r\"Magnitude $\\|Y\\|$\")\n\n    ax = fig.add_subplot(212, projection='3d')\n    surf = ax.plot_surface(w, t, np.angle(X).T, cmap=colorMap)\n    fig.colorbar(surf)\n    plt.xlabel(r\"Frequency $\\to$\")\n    plt.ylabel(r\"Time $\\to$\")\n    plt.title(r\"Angle $\\angle Y$\")\n    if saveFig:\n        plt.savefig(plotsDir+\"Fig\"+str(figNum)+\".png\")\n    if showFig:\n        plt.show(block=blockFig)\n\n    figNum+=1\n\nx = chirp(t)\nX = STFT(x, t)\nplot3DSTFT(t, w, X, colorMap=cm.plasma)\n\nx = chirp(t)*hammingWindow(np.arange(1024))\nX = STFT(x, t)\nplot3DSTFT(t, w, X, blockFig=True)\n", "meta": {"hexsha": "25fdcfcab3f2f3017f0b3bf366acd1def85dc0a0", "size": 6849, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week 9/code.py", "max_stars_repo_name": "aklsh/EE2703", "max_stars_repo_head_hexsha": "546b70c9adac4a4de294d83affbb74e480c2f65d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week 9/code.py", "max_issues_repo_name": "aklsh/EE2703", "max_issues_repo_head_hexsha": "546b70c9adac4a4de294d83affbb74e480c2f65d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week 9/code.py", "max_forks_repo_name": "aklsh/EE2703", "max_forks_repo_head_hexsha": "546b70c9adac4a4de294d83affbb74e480c2f65d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-15T08:02:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T06:50:07.000Z", "avg_line_length": 28.0696721311, "max_line_length": 136, "alphanum_fraction": 0.6031537451, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979619, "lm_q2_score": 0.9284087980793997, "lm_q1q2_score": 0.8619429041671027}}
{"text": "# Create a 2D Numpy Array\n\n# Import the libraries\nimport numpy as np \nimport matplotlib.pyplot as plt\n\n# Consider the list a, the list contains three nested lists each of equal size. \n\n# Create a list\na = [[11, 12, 13], [21, 22, 23], [31, 32, 33]]\nprint(a)\n\n# We can cast the list to a Numpy Array as follow\n# Convert list to Numpy Array\n# Every element is the same type\nA = np.array(a)\nprint(A)\n\n# Show the numpy array dimensions\nprint(A.ndim)\n\n# Attribute shape returns a tuple corresponding to the size or number of each dimension.\n# Show the numpy array shape\nprint(A.shape)\n\n# The total number of elements in the array is given by the attribute size.\n# Show the numpy array size\nprint(A.size)\n\n# We simply use the square brackets and the indices corresponding to the element we would like:\n# Access the element on the second row and third column\nprint(A[1, 2])\n\n# We can also use the following notation to obtain the elements: \n# Access the element on the second row and third column\nprint(A[1][2])\n\n# We can access the element as follows\n# Access the element on the first row and first column\nprint(A[0][0])\n\n# This can be done with the following syntax \n# Access the element on the first row and first and second columns\nprint(A[0][0:2])\n\n# Similarly, we can obtain the first two rows of the 3rd column as follows:\n# Access the element on the first and second rows and third column\nprint(A[0:2, 2])\n\n# The numpy array is given by X and Y\n# Create a numpy array X\nX = np.array([[1, 0], [0, 1]]) \nprint(X)\n\n# Create a numpy array Y\nY = np.array([[2, 1], [1, 2]]) \nprint(Y)\n\n# We can add the numpy arrays as follows.\n# Add X and Y\nZ = X + Y\nprint(Z)\n\n# We can perform the same operation in numpy as follows \n# Create a numpy array Y\nY = np.array([[2, 1], [1, 2]]) \nprint(Y)\n\n# Multiply Y with 2\nZ = 2 * Y\nprint(Z)\n\n# We can perform element-wise product of the array X and Y as follows:\n# Create a numpy array Y\nY = np.array([[2, 1], [1, 2]]) \nprint(Y)\n\n# Create a numpy array X\nX = np.array([[1, 0], [0, 1]]) \nprint(X)\n\n# Multiply X with Y\nZ = X * Y\nprint(Z)\n\n# We can also perform matrix multiplication with the numpy arrays A and B as follows: \n# First, we define matrix A and B:\n# Create a matrix A\nA = np.array([[0, 1, 1], [1, 0, 1]])\nprint(A)\n\n# Create a matrix B\nB = np.array([[1, 1], [1, 1], [-1, 1]])\nprint(B)\n\n# Calculate the dot product\nZ = np.dot(A,B)\nprint(Z)\n\n# Calculate the sine of Z\nprint(np.sin(Z))\n\n# We use the numpy attribute T to calculate the transposed matrix\n# Create a matrix C\nC = np.array([[1,1],[2,2],[3,3]])\nprint(C)\n\n# Get the transposed of C\nprint(C.T)\n\n# Quiz\n\n# Consider the following list a, convert it to Numpy Array. \na = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]\nA = np.array(a)\nprint(A)\n\n# Calculate the numpy array size.\nprint(A.size)\n\n# Access the element on the first row and first and second columns.\nprint(A[0][0:2])\n\n# Perform matrix multiplication with the numpy arrays A and B.\nB = np.array([[0, 1], [1, 0], [1, 1], [-1, 0]])\nX = np.dot(A,B)\nprint(X)\n", "meta": {"hexsha": "483f10ba5ac4850c8cf93b112685097f1771b011", "size": 3005, "ext": "py", "lang": "Python", "max_stars_repo_path": "nmpy_2D_01.py", "max_stars_repo_name": "BjornChrisnach/Edx_IBM_Python_Basics_Data_Science", "max_stars_repo_head_hexsha": "1a5eb04d8ec0e25c4daa44e264acd760c019127d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nmpy_2D_01.py", "max_issues_repo_name": "BjornChrisnach/Edx_IBM_Python_Basics_Data_Science", "max_issues_repo_head_hexsha": "1a5eb04d8ec0e25c4daa44e264acd760c019127d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nmpy_2D_01.py", "max_forks_repo_name": "BjornChrisnach/Edx_IBM_Python_Basics_Data_Science", "max_forks_repo_head_hexsha": "1a5eb04d8ec0e25c4daa44e264acd760c019127d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4765625, "max_line_length": 95, "alphanum_fraction": 0.6775374376, "include": true, "reason": "import numpy", "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.9284087975841901, "lm_q1q2_score": 0.8619429018683182}}
{"text": "from math import log, log10, floor, ceil\nfrom random import randrange\nfrom numpy import base_repr\nimport warnings\n\nfrom PyModulo import *\nfrom PyModulo.Utility import *\n\nclass RSA:\n\tclass PublicInfo:\n\t\tdef __init__(self, N, e):\n\t\t\tself.N=N\n\t\t\tself.e=e\n\n\t\tdef get_key(self):\n\t\t\treturn self.N, self.e\n\n\tclass PrivateInfo:\n\t\tdef __init__(self, p, q, d, lowerN=None):\n\t\t\tself.p=p\n\t\t\tself.q=q\n\t\t\tself.d=d\n\t\t\tself.lowerN = lowerN if lowerN else (p-1)*(q-1) \n\n\t\tdef get_key(self):\n\t\t\treturn self.p, self.q, self.d, self.lowerN\n\n\tdef __init__(self, NDigitRange=(20,25), priInfo=None, pubInfo=None, printDebug=False):\n\t\tif(isinstance(pubInfo,RSA.PublicInfo) and priInfo==None):\n\t\t\twarnings.warn(\"Warning, RSA with only a public key can only encrypt messages (can't derive private keys from public keys)!\")\n\n\t\tif(not isinstance(pubInfo, RSA.PublicInfo)):\n\t\t\tif(not isinstance(priInfo, RSA.PrivateInfo)):\n\t\t\t\tminDig, maxDig = NDigitRange\n\n\t\t\t\tdnMin, dnMax = (ceil((minDig+1)/2), floor((maxDig+1)/2))\n\t\t\t\tdebug(dnMin, dnMax, output=printDebug)\n\n\t\t\t\tdiff = dnMax-dnMin\n\t\t\t\tdebug(\"diff:\", diff, output=printDebug)\n\n\t\t\t\t#the number of digits in the first number:\n\t\t\t\tdp = randrange(dnMin,dnMax+diff+1)\n\t\t\t\tp = rand_n_digit_prime(dp)\n\n\t\t\t\t#the number of digits in the second number:\n\t\t\t\tdq =randrange(dnMin,dnMax*2-dp+1)\n\t\t\t\tq = rand_n_digit_prime(dq)\n\n\t\t\t\tlowerN = (p-1)*(q-1)\n\n\t\t\t\tdebug(\"p=%i digits (digits: %i=%i desired)\"%(p, len(str(p)), dp), output=printDebug)\n\t\t\t\tdebug(\"q=%i digits (digits: %i=%i desired)\"%(q, len(str(q)), dq), output=printDebug)\n\t\t\t\tdebug(\"**Found p and q (p:%i, q:%i)\"%(p,q), output=printDebug)\n\t\t\t\tdebug(\"lowerN [(p-1)*(q-1)]=%i\"%lowerN, output=printDebug)\n\n\t\t\t\t#find d:\n\t\t\t\twhile((dInfo:=gcd_info(d:=randrange(1,lowerN),lowerN))[\"GCD\"]!=1):\n\t\t\t\t\tpass\n\t\t\t\tdebug(\"found d=%i and :\"%d, dInfo, output=printDebug)\n\n\t\t\telse:\n\t\t\t\tp, q, d, lowerN = priInfo.get_key()\n\t\t\t\tdInfo = gcd_info(d,lowerN)\n\n\n\t\t\tN = p*q\n\n\t\t\tdebug(\"N=%i (digits=%i)\"%(N, len(str(N))), output=printDebug)\n\t\t\tdebug(\"(p-1)*(q-1):\", lowerN, output=printDebug)\n\n\t\t\te = dInfo[\"u\"] % lowerN\n\t\t\tdebug(\"Found e:\",e, output=printDebug)\n\t\telse:\n\t\t\tp,q,d,lowerN = (-1,-1,-1,-1)\n\t\t\tN, e = pubInfo.get_key()\n\n\t\tself.pubInfo = RSA.PublicInfo(N,e)\n\t\tself.priInfo = RSA.PrivateInfo(p, q, d, lowerN)\n\n\n\n\tdef get_info(self):\n\t\treturn {\"N\": self.pubInfo.N, \"e\": self.pubInfo.e, \"p\": self.priInfo.p, \"q\":self.priInfo.q, \"d\": self.priInfo.d, \"lowerN\":self.priInfo.lowerN}\n\n\tdef encrypt_message(self, m, encoder=lambda x: int(x, 36)):\n\t\tmInt = encoder(m)\n\t\treturn power_mod(mInt, self.pubInfo.e, self.pubInfo.N)\n\n\tdef decrypt_message(self, m, decoder=lambda x: base_repr(x,base=36)):\n\t\tmInt = power_mod(m, self.priInfo.d, self.pubInfo.N)\n\t\treturn decoder(mInt)\n\n\n\n\n\n", "meta": {"hexsha": "d92c30fb8ee6f6877f80d69cdeaf75bb4fc79ee9", "size": 2723, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/PyModulo/RSA.py", "max_stars_repo_name": "landonzweigle/Modulo-Math-Tools", "max_stars_repo_head_hexsha": "7e6ce7461ed4dce71b2724c49d16d5e09f6b4bd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PyModulo/RSA.py", "max_issues_repo_name": "landonzweigle/Modulo-Math-Tools", "max_issues_repo_head_hexsha": "7e6ce7461ed4dce71b2724c49d16d5e09f6b4bd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-02T21:29:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-02T21:29:58.000Z", "max_forks_repo_path": "src/PyModulo/RSA.py", "max_forks_repo_name": "landonzweigle/Modulo-Math-Tools", "max_forks_repo_head_hexsha": "7e6ce7461ed4dce71b2724c49d16d5e09f6b4bd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7857142857, "max_line_length": 143, "alphanum_fraction": 0.6547925083, "include": true, "reason": "from numpy", "num_tokens": 894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9822876997410348, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.8619346520043563}}
{"text": "import numpy as np\nimport math\n\ndef lagrange(f, x_vec, x):\n    return np.sum(\n        [f[i] * np.prod([(x - x_vec[i]) / (x_vec[i] - x_vec[j]) if j != i else 1. for j in range(len(x_vec))])\\\n                      for i in range(len(x_vec))])\n\n\ndef newton(f, x_vec, x):\n    n = len(x_vec)\n    coeff = [np.sum([f[k] / np.prod([(x_vec[k] - x_vec[j]) if j != k else 1. for j in range(i + 1)]) for k in range(i + 1)]) for i in range(n)]\n    return np.sum(\\\n                     [coeff[i] * np.prod([x - x_vec[j] for j in range(i)])\\\n               for i in range(n)])\n\n\ndef omega(x_vec, x):\n    return np.prod([(x - el) for el in x_vec])\n\n\ndef derived(x):\n    return -(24 * x * (-1 + x ** 2))/(1 + x ** 2) ** 4\n\n\ndef main():\n    x_1 = [-3, -1, 1, 3]\n    x_2 = [-3, 0, 1, 3]\n    M = 4.66\n    pn = [lagrange, newton]\n    names = [\"lagrange\", \"newton\"]\n    x_val = -0.5\n\n    for test in zip([x_1, x_2], pn, names):\n        x_vec = test[0]\n        f = [np.arctan(x) for x in x_vec]\n        poly = test[1]\n        name = test[-1]\n        print(f'Checking {name} interpolation')\n        eps = np.abs(np.arctan(x_val) - poly(f, x_vec, x_val))\n        print(f'|atan(x) - P(x)| = {eps}')\n        upper_bound = np.abs(omega(x_vec, x_val)) * M / math.factorial(len(x_vec) + 1)\n        print(f'M / (n + 1)!|w(x)| = {upper_bound}')\n        print(f'is it quite good? {eps <= upper_bound}\\n')\n\nmain()", "meta": {"hexsha": "45ccd623ceecf6c05396fe63f525007cf7dc2546", "size": 1379, "ext": "py", "lang": "Python", "max_stars_repo_path": "6th_semester/NumMethods/3_lab/task1.py", "max_stars_repo_name": "mehakun/Labs", "max_stars_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-03-06T16:08:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-02T22:11:00.000Z", "max_issues_repo_path": "6th_semester/NumMethods/3_lab/task1.py", "max_issues_repo_name": "mehakun/Labs", "max_issues_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6th_semester/NumMethods/3_lab/task1.py", "max_forks_repo_name": "mehakun/Labs", "max_forks_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9782608696, "max_line_length": 143, "alphanum_fraction": 0.5003625816, "include": true, "reason": "import numpy", "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407191430024, "lm_q2_score": 0.8856314632529872, "lm_q1q2_score": 0.8619326021920067}}
{"text": "import sys\nsys.path.insert(0, '/Users/carol/python/ThinkBayes2/thinkbayes2/')\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom thinkbayes2 import Pmf, Suite, CredibleInterval, Beta\n\n# PMF for 6-sided die\npmf = Pmf()\nfor x in [1, 2, 3, 4, 5, 6]:\n    pmf.Set(x, 1/6)\nprint(pmf)\n\n# How to build up a pmf from a list of strings\npmf2 = Pmf()\nfor word in ['a', 'in', 'or', 'to', 'a', 'me', 'in']:\n    pmf2.Incr(word, 1)\npmf2.Normalize()\nprint(pmf2)\nprint(\"Probability of letter a:\", pmf2.Prob('a'))   # Typo p12 print pmf.Prob('the') should read print(pmf.Prob('the'))\n\n# PMF for the Cookie problem\npmf = Pmf()\n# Prior:\npmf.Set(\"Bowl 1\", 0.5)\npmf.Set(\"Bowl 2\", 0.5)\n# Posterior:\n# First multiply prior by likelihood\npmf.Mult(\"Bowl 1\", 0.75)\npmf.Mult(\"Bowl 2\", 0.5)\n# Then normalise (we can do this because the hypotheses are mutually exclusive and collectively exhaustive,\n# i.e. only one of the hypotheses can be true and there can be no other hypothesis)\npmf.Normalize()\nprint(pmf)\n\n\n# Create a Cookie class that inherits from Pmf and represents the Cookie problem\nclass Cookie(Pmf):\n\n    proportions = {\n        'Bowl 1':dict(vanilla=0.75, chocolate=0.25),\n        'Bowl 2':dict(vanilla=0.5, chocolate=0.5),\n        }\n\n    def __init__(self, hypos):\n        Pmf.__init__(self)\n        for hypo in hypos:\n            self.Set(hypo, 1)\n        self.Normalize()\n    \n    def Update(self, data):\n        for hypo in self.Values():\n            likelihood = self.Likelihood(data, hypo)\n            self.Mult(hypo, likelihood)\n        self.Normalize()\n\n    def Likelihood(self, data, hypo):\n        proportion = self.proportions[hypo]\n        likelihood = proportion[data]\n        return likelihood\n\n# Set up the hypotheses for the Cookie problem\nhypos = ['Bowl 1', 'Bowl 2']\n# Initialise the prior for the Cookie problem\npmf = Cookie(hypos)\nprint(\"Prior:\")\nfor hypo, prob in pmf.Items():\n    print(hypo, prob)     # Type p14: print hypo, prob should read print(hypo, prob)\n# Update the prior given one data point (we drew a vanilla cookie)\npmf.Update('vanilla')\nprint(\"Posterior:\")\nfor hypo, prob in pmf.Items():\n    print(hypo, prob)\n# Draw some more cookies (with replacement) and update the prior\ndataset = ['vanilla', 'chocolate', 'vanilla']\nfor data in dataset:\n    pmf.Update(data)\nprint(\"Posterior:\")\nfor hypo, prob in pmf.Items():\n    print(hypo, prob)\n\n\n# Implement the Cookie problem by writing a class that inherits from Suite and providing the Likelihood method.\n# Suite implements the Update and Print methods, which are the same for all Bayesian problems,\n# but not the Likelihood method, which depends on the specification of the problem.\nclass CookieProblem(Suite):\n\n    proportions = {\n        hypos[0]:dict(vanilla=0.75, chocolate=0.25),\n        hypos[1]:dict(vanilla=0.5, chocolate=0.5),\n        }\n\n    def Likelihood(self, data, hypo):\n        proportion = self.proportions[hypo]\n        likelihood = proportion[data]\n        return likelihood\n\n# Set up hypotheses for Cookie problem\nhypos = ['Bowl 1', 'Bowl 2']\n# Initialise prior\npmf = CookieProblem(hypos)\nprint(\"Prior:\")\npmf.Print()\n# Draw some cookies (with replacement) and update the prior\ndataset = ['vanilla', 'vanilla', 'chocolate', 'vanilla']\nfor data in dataset:\n    pmf.Update(data)\nprint(\"Posterior:\")\npmf.Print()\n\n\n# Write a class for the m & m problem\nclass M_and_M(Suite):\n\n    mix94 = dict(brown=30,\n                 yellow=20,\n                 red=20,\n                 green=10,\n                 orange=10,\n                 tan=10)\n\n    mix96 = dict(blue=24,\n                 green=20,\n                 orange=16,\n                 yellow=14,\n                 red=13,\n                 brown=13)\n\n    hypoA = dict(bag1=mix94, bag2=mix96)\n    hypoB = dict(bag1=mix96, bag2=mix94)\n\n    hypotheses = dict(A=hypoA, B=hypoB)\n\n    def Likelihood(self, data, hypo):\n        bag, color = data\n        mix = self.hypotheses[hypo][bag]\n        likelihood = mix[color]\n        return likelihood\n\n# Implement the m & m problem\nhypos = 'AB' # can also be written: hypos = ['A', 'B']\npmf = M_and_M(hypos)\npmf.Update(('bag1', 'yellow'))\npmf.Update(('bag2', 'green'))\npmf.Print()\n\n\n# Implement the Cookie problem without replacement\nclass CookieGetsEaten(Suite):\n\n    def __init__(self, hypos, Bowl1, Bowl2):\n        Suite.__init__(self, hypos)\n        self.Bowl1 = Bowl1\n        self.Bowl2 = Bowl2\n\n    def Likelihood(self, data, hypo):\n        if (hypo == \"Bowl 1\") & (data == \"vanilla\"):\n            likelihood = self.Bowl1.num_vanilla / (self.Bowl1.num_vanilla + self.Bowl1.num_chocolate)\n            Bowl1.num_vanilla -= 1\n        elif (hypo == \"Bowl 1\") & (data == \"chocolate\"):\n            likelihood = self.Bowl1.num_chocolate / (self.Bowl1.num_vanilla + self.Bowl1.num_chocolate)\n            Bowl1.num_chocolate -= 1\n        elif (hypo == \"Bowl 2\") & (data == \"vanilla\"):\n            likelihood = self.Bowl2.num_vanilla / (self.Bowl2.num_vanilla + self.Bowl2.num_chocolate)\n            Bowl2.num_vanilla -= 1\n        elif (hypo == \"Bowl 2\") & (data == \"chocolate\"):\n            likelihood = self.Bowl2.num_chocolate / (self.Bowl2.num_vanilla + self.Bowl2.num_chocolate)\n            Bowl2.num_chocolate -= 1\n        return likelihood\n\n# Set up a \"Bowl\" object\nclass Bowl():\n    def __init__(self, num_vanilla=20, num_chocolate=20):\n        self.num_vanilla = num_vanilla\n        self.num_chocolate = num_chocolate\n\n    def __str__(self):\n        return \"Vanilla: {}, Chocolate {}.\".format(self.num_vanilla, self.num_chocolate)\n\n# Set up hypotheses for Cookie problem\nhypos = ['Bowl 1', 'Bowl 2']\n# Create two Bowl objects with the right mix of cookies in each\nBowl1 = Bowl(30, 10)\nBowl2 = Bowl(20, 20)\n# Initialise prior\npmf = CookieGetsEaten(hypos, Bowl1, Bowl2)\nprint(\"Prior:\")\npmf.Print()\n# Draw some cookies (with replacement) and update the prior\ndataset = ['vanilla', 'vanilla', 'chocolate', 'vanilla']\n#dataset = ['vanilla', 'chocolate', 'chocolate', 'chocolate', 'chocolate', 'chocolate', 'chocolate', 'chocolate', 'chocolate', 'chocolate', 'chocolate', 'chocolate', 'chocolate', 'chocolate']\nfor data in dataset:\n    pmf.Update(data)\n    print(\"Bowl 1:\", Bowl1, \"Bowl 2:\", Bowl2)\n    print(\"Posterior:\")\n    pmf.Print()\n#print(\"Posterior:\")\npmf.Print()\n\n\n# Set up a class for doing Bayesian Inference on which of 5 different dice have been rolled:\nclass Dice(Suite):\n    def Likelihood(self, data, hypo):\n        if hypo < data:\n            return 0\n        else:\n            return 1 / hypo\n\n# Initialise a pmf for the Dice problem\npmf = Dice([4, 6, 8, 12, 20])  # The hypotheses are: 4-sided, 6-sided, 8-sided, 12-sided, 20-sided\nprint(\"Prior:\")\npmf.Print()\npmf.Update(6)  # The data is that a 6 was rolled (using one of the dice - we don't know which one)\nprint(\"Posterior:\")\npmf.Print()\n# Calculate a confidence interval at the 90% level for which dice the data could come from\ninterval = CredibleInterval(pmf, 90)   # Error p28: function Percentile has been replaced with CredibleInterval\nprint(\"Confidence interval:\", interval)   # typo p28: print interval should read print(interval)\n# With more data, posterior distributions based on different priors tend to converge\nfor roll in [6, 8, 7, 7, 5, 4]:\n    pmf.Update(roll)\nprint(\"Posterior:\")\npmf.Print()\n# Calculate a confidence interval at the 90% level for which dice the data could come from\ninterval = CredibleInterval(pmf, 90)\nprint(\"Confidence interval:\", interval)\n# Calculate the expectation value of the pmf\nprint(\"Mean:\", pmf.Mean())\n# Create a Cdf object from the pmf\ncdf = pmf.MakeCdf()\ninterval = cdf.Percentile(5), cdf.Percentile(95)\nprint(\"Confidence interval:\", interval)\n\n\n# Create a coin class for analysing coin-tossing problems\nclass Coin(Suite):\n    # Define the Likelihood method (this version is slow because there is one data point for every coin toss, \n    # so the method has to be called lots of times)\n    def Likelihood(self, data, hypo):\n        if data == \"H\":\n            likelihood = hypo\n        elif data == \"T\":\n            likelihood = 1 - hypo\n        return likelihood\n\n# Function for plotting posterior\ndef plot_bias(pmf):\n    bias = []\n    prob = []\n    for b, p in pmf.Items():\n        bias.append(b)\n        prob.append(p)\n    plt.plot(bias, prob)\n\n# Function for calculating maximum likelihood hypothesis\ndef MaximumLikelihood(pmf):\n    \"\"\"Returns the hypothesis with the highest probability.\"\"\"\n    prob, val = max((prob, val) for val, prob in pmf.Items())\n    return val\n\n# Create 101 hypotheses for the bias of the coin, ranging from 0 to 1\nhypos = np.arange(0, 1.01, 0.01)\n# Create pmf for coin bias hypotheses\npmf = Coin(hypos)\n# Create data set of successive coin tosses\n#dataset = \"HHHHHTTTT\"\ndataset = 140 * \"H\" + 110 * \"T\"\n# Update posterior\n#for data in dataset:\n#    pmf.Update(data)       # The Update method normalises the pmf for every data point.\npmf.UpdateSet(dataset)    # We can save time by performing all the updates first and only normalising at the end, using UpdateSet. \n# Compute 90% confidence interval\ninterval = CredibleInterval(pmf, 90)\nprint(\"90% confidence interval:\", interval)\n# Compute maximum likelihood hypothesis\nprint(\"Maximum likelihood hypothesis:\", MaximumLikelihood(pmf))\n# Plot posterior\nplot_bias(pmf)\nplt.show()\n\n\n# Create a fast coin class for analysing coin-tossing problems efficiently\nclass CoinFast(Suite):\n    # This verson of Likelihood is fast because the results of all coin tosses are included in one data point: data = (heads, tails)\n    # Now, the update of the posterior takes the same amount of time, no matter how many coin tosses there are.\n    def Likelihood(self, data, hypo):\n        heads, tails = data\n        likelihood = hypo**heads * (1-hypo)**tails  # We can multiply all the likelihoods because coin tosses are independent events.\n        return likelihood\n\n# Set up hypotheses for the coin-tossing problem\nhypos = np.arange(0, 1.01, 0.01)\n# Initialise a CoinFast pmf\npmf = CoinFast(hypos)\n# Represent the data set as a tuple of (heads, tails)\ndata = (140, 110)\n# Update posterior\npmf.Update(data)\n# Plot posterior\nplot_bias(pmf)\nplt.show()\n\n\n# Create a class for the Beta distribution\nclass BetaCHW(object):\n    def __init__(self, alpha=1, beta=1):   # By default __init__ makes a uniform distribution\n        self.alpha = alpha\n        self.beta = beta\n    \n    # Update performs a Bayesian update:\n    def Update(self, data):\n        heads, tails = data\n        self.alpha += heads\n        self.beta += tails\n\n    # Mean calculates the mean of the distribution using a formula that involves only alpha and beta\n    def Mean(self):\n        return float(self.alpha) / (self.alpha + self.beta)\n\n    # EvalPdf evaluates the probability density function (PDF) of the beta distribution\n    def EvalPdf(self, x):\n        return x ** (self.alpha - 1)  *  (1 - x) ** (self.beta - 1)\n\nbeta = BetaCHW()\nbeta.Update((140, 110))\nprint(\"Mean hypothesis:\", beta.Mean())    # Typo p40: print beta.Mean() should read print(beta.Mean())\n\n# Cromwell’s rule: avoid giving a prior probability of 0 to any hypothesis that is even remotely possible.\n# If the prior goes to zero, the posterior will always be zero thereafter.\n\n\n# Ex 4.1: Coin tossing problem when the reader of the coin toss has a probability y of giving the wrong reading. \nclass UncertainCoin(Suite):\n    def Likelihood(self, data, hypo):\n        heads, tails, y = data\n        likelihood = (hypo * (1 - y) + (1 - hypo) * y) ** heads  *  ((1 - hypo) * (1 - y) + hypo * y) ** tails\n        return likelihood\n\nhypos = np.arange(0, 1.01, 0.01)\npmf = UncertainCoin(hypos)\ndata = (140, 110, 0)  # (heads, tails, y)\npmf.Update(data)\nplot_bias(pmf)\n\npmf = UncertainCoin(hypos)\ndata = (140, 110, 0.1)  # (heads, tails, y)\npmf.Update(data)\nplot_bias(pmf)\n\npmf = UncertainCoin(hypos)\ndata = (140, 110, 0.2)  # (heads, tails, y)\npmf.Update(data)\nplot_bias(pmf)\n\npmf = UncertainCoin(hypos)\ndata = (140, 110, 0.3)  # (heads, tails, y)\npmf.Update(data)\nplot_bias(pmf)\n\nplt.show()\n\n\n# Try using the Beta distribution to create a more realistic prior for the Belgain Euro coin problem\nbeta = Beta()               # Uniform prior\nbeta.Update((140, 110))\npmf = beta.MakePmf()\nplot_bias(pmf)\n\nbeta = Beta(100, 100)       # Broadish prior centred on bias of 0.5\nbeta.Update((140, 110))\npmf = beta.MakePmf()\nplot_bias(pmf)\n\nbeta = Beta(300, 300)       # Narrow prior centred on bias of 0.5 (if alpha, beta > 300, peak is just a spike and we get an error)\nbeta.Update((140, 110))\npmf = beta.MakePmf()\nplot_bias(pmf)\n\ninterval = CredibleInterval(pmf, 90)\nprint(\"90% confidence interval:\", interval)  # Since this comes out at (0.49, 0.55), it now seems less likely the coin is really biased.\n\nplt.show()", "meta": {"hexsha": "63e96b462ef537983a49ab36e03df998393eb3a0", "size": 12687, "ext": "py", "lang": "Python", "max_stars_repo_path": "chw/pmf_test.py", "max_stars_repo_name": "chwebster/ThinkBayes2", "max_stars_repo_head_hexsha": "49af0e36c38c2656d7b91117cfa2b019ead81988", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chw/pmf_test.py", "max_issues_repo_name": "chwebster/ThinkBayes2", "max_issues_repo_head_hexsha": "49af0e36c38c2656d7b91117cfa2b019ead81988", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chw/pmf_test.py", "max_forks_repo_name": "chwebster/ThinkBayes2", "max_forks_repo_head_hexsha": "49af0e36c38c2656d7b91117cfa2b019ead81988", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1253263708, "max_line_length": 191, "alphanum_fraction": 0.6657208166, "include": true, "reason": "import numpy", "num_tokens": 3575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.9294404052785553, "lm_q1q2_score": 0.8619289098829233}}
{"text": "import numpy as np\n\ndef initialize_all(y0, t0, t1, n):\n    \"\"\" An initialization routine for the different ODE solving\n    methods in the lab. This initializes Y, T, and h. \"\"\"\n    if isinstance(y0, np.ndarray):\n        Y = np.empty((n, y.size)).squeeze()\n    else:\n        Y = np.empty(n)\n\t# print y0\n\t# print Y\n    Y[0] = y0\n    T = np.linspace(t0, t1, n)\n    h = float(t1 - t0) / (n - 1)\n    return Y, T, h\n\ndef euler(f, y0, t0, t1, n):\n    \"\"\" Use the Euler method to compute an approximate solution\n    to the ODE y' = f(t, y) at n equispaced parameter values from t0 to t\n    with initial conditions y(t0) = y0.\n    \n    y0 is assumed to be either a constant or a one-dimensional numpy array.\n    t and t0 are assumed to be constants.\n    f is assumed to accept two arguments.\n    The first is a constant giving the value of t.\n    The second is a one-dimensional numpy array of the same size as y.\n    \n    This function returns an array Y of shape (n,) if\n    y is a constant or an array of size 1.\n    It returns an array of shape (n, y.size) otherwise.\n    In either case, Y[i] is the approximate value of y at\n    the i'th value of np.linspace(t0, t, n).\n    \"\"\"\n    Y, T, h = initialize_all(y0, t0, t1, n)\n    for i in xrange(1, n):\n        Y[i] = Y[i-1] + f(T[i-1], Y[i-1]) * h\n    return Y\n\ndef euler_accuracy(y0, t0, t1, N=(11, 21, 41)):\n    \"\"\" Test the accuracy of the Euler method using the\n    initial value problem y' + y = 2 - 2x, with y(0) = y0\n    Plot your solutions over the given domain with n as 11, 21, and 41.\n    Also plot the exact solution.\n    Show the plot. \"\"\"\n    f = lambda x, y: 2 - y - 2 * x\n    for n in N:\n        T = np.linspace(t0, t1, n)\n        plt.plot(T, euler(f, y0, t0, t1, n))\n    plt.plot(T, 4 - 2 * T - 4 * np.exp(-T))\n    plt.show()\n\n# The inversion here could also be done using scipy.optimize's Newton's method.\n# Currently in the lab, this function isn't required.\ndef backwards_euler(f, fsolve, y0, t0, t1, n):\n    \"\"\" Use the backward Euler method to compute an approximate solution\n    to the ODE y' = f(t, y) at n equispaced parameter values from t0 to t\n    with initial conditions y(t0) = y0.\n    \n    y0 is assumed to be either a constant or a one-dimensional numpy array.\n    t and t0 are assumed to be constants.\n    f is assumed to accept two arguments.\n    The first is a constant giving the value of t.\n    The second is a one-dimensional numpy array of the same size as y.\n    fsolve is a function that solves the equation\n    y(x_{i+1}) = y(x_i) + h f(x_{i+1}, y(x_{i+1}))\n    for the appropriate value for y(x_{i+1}).\n    It should accept three arguments.\n    The first should be the value of y(x_i).\n    The second should be the distance between values of t.\n    The third should be the value of x_{i+1}.\n    \n    This function returns an array Y of shape (n,) if\n    y is a constant or an array of size 1.\n    It returns an array of shape (n, y.size) otherwise.\n    In either case, Y[i] is the approximate value of y at\n    the i'th value of np.linspace(t0, t, n).\n    \"\"\"\n    Y, T, h = initialize_all(y0, t0, t1, n)\n    for i in xrange(1, n):\n        Y[i] = fsolve(Y[i-1], h, T[i])\n    return Y\n\ndef midpoint(f, y0, t0, t1, n):\n    \"\"\" Use the midpoint method to compute an approximate solution\n    to the ODE y' = f(t, y) at n equispaced parameter values from t0 to t1\n    with initial conditions y(t0) = y0.\n    \n    y0 is assumed to be either a constant or a one-dimensional numpy array.\n    t0 and t1 are assumed to be constants.\n    f is assumed to accept two arguments.\n    The first is a constant giving the value of t.\n    The second is a one-dimensional numpy array of the same size as y.\n    \n    This function returns an array Y of shape (n,) if\n    y is a constant or an array of size 1.\n    It returns an array of shape (n, y.size) otherwise.\n    In either case, Y[i] is the approximate value of y at\n    the i'th value of np.linspace(t0, t, n).\n    \"\"\"\n    Y, T, h = initialize_all(y0, t0, t1, n)\n    for i in xrange(1, n):\n        Y[i] = Y[i-1] + h * f(T[i-1] + h / 2., Y[i-1] + (h / 2.) * f(T[i-1], Y[i-1]))\n    return Y\n\n# This one isn't currently required in the lab.\ndef modified_euler(f, y0, t0, t1, n):\n    \"\"\" Use the modified Euler method to compute an approximate solution\n    to the ODE y' = f(t, y) at n equispaced parameter values from t0 to t1\n    with initial conditions y(t0) = y0.\n    \n    y0 is assumed to be either a constant or a one-dimensional numpy array.\n    t and t0 are assumed to be constants.\n    f is assumed to accept two arguments.\n    The first is a constant giving the value of t.\n    The second is a one-dimensional numpy array of the same size as y.\n    \n    This function returns an array Y of shape (n,) if\n    y is a constant or an array of size 1.\n    It returns an array of shape (n, y.size) otherwise.\n    In either case, Y[i] is the approximate value of y at\n    the i'th value of np.linspace(t0, t, n).\n    \"\"\"\n    Y, T, h = initialize_all(y0, t0, t1, n)\n    for i in xrange(1, n):\n        Y[i] = Y[i-1] + (h / 2.) * (f(T[i-1], Y[i-1]) + f(T[i-1], Y[i-1] + h * f(T[i-1], Y[i-1])))\n    return Y\n\n\n\ndef RK4(f, y0, t0, t1, n):\n    \"\"\" Use the RK4 method to compute an approximate solution\n    to the ODE y' = f(t, y) at n equispaced parameter values from t0 to t\n    with initial conditions y(t0) = y0.\n    \n    'y0' is assumed to be either a constant or a one-dimensional numpy array.\n    't0' and 't1' are assumed to be constants.\n    'f' is assumed to accept two arguments.\n    The first is a constant giving the current value of t.\n    The second is a one-dimensional numpy array of the same size as y.\n    \n    This function returns an array Y of shape (n,) if\n    y is a constant or an array of size 1.\n    It returns an array of shape (n, y.size) otherwise.\n    In either case, Y[i] is the approximate value of y at\n    the i'th value of np.linspace(t0, t, n).\n    \"\"\"\n    Y, T, h = initialize_all(y0, t0, t1, n)\n    for i in xrange(1, n):\n        K1 = f(T[i-1], Y[i-1])\n        tplus = (T[i] + T[i-1]) * .5\n        K2 = f(tplus, Y[i-1] + .5 * h * K1)\n        K3 = f(tplus, Y[i-1] + .5 * h * K2)\n        K4 = f(T[i], Y[i-1] + h * K3)\n        Y[i] = Y[i-1] + (h / 6.) * (K1 + 2 * K2 + 2 * K3 + K4)\n    return Y\n\n\ndef compare_accuracies(N, t=2):\n    \"\"\" Test the accuracies of the Euler, backwards Euler, modified Euler,\n    midpoint, and RK4 methods using initial value problem\n    y' + y = 2 - 2x, y(0) = 0.\n    Use the different values of n in 'N', and plot h=1./(n-1)\n    vs the RELATIVE error at time 't'. \"\"\"\n    f = lambda x, y: 2 - y - 2 * x\n    exact = 4 - 2 * t - 4 * np.exp(-t)\n    euler_err = [abs((euler(f, 0, 0, t, n)[-1] - exact) / exact) for n in N]\n    midpoint_err = [abs((midpoint(f, 0, 0, t, n)[-1] - exact) / exact) for n in N]\n    RK4_err = [abs((RK4(f, 0, 0, t, n)[-1] - exact) / exact) for n in N]\n    H = [1. / (n-1) for n in N]\n    plt.loglog(H, euler_err, H, midpoint_err, H, RK4_err)\n    plt.show()\n\n\ndef simple_harmonic_oscillator(y0, t0, t, n, m=1, k=1):\n    \"\"\" Use the RK4 method to solve for the simple harmonic oscillator\n    problem described in the problem about simple harmonic oscillators.\n    Return the array of values at the equispaced points.\n    'y0', 't0', 't', and 'n' are the same as they were in the ODE solving routines.\n    'm' and 'k' are constants used in the ODE. \"\"\"\n    f = lambda x, y: np.array([y[1], - k * y[0] / float(m)])\n    return RK4(f, y0, t0, t, n)[:,0]\n\n\n\ndef damped_harmonic_oscillator(y0, t0, t, n, gamma):\n    \"\"\" Use the RK4 method to solve for the damped harmonic oscillator\n    problem described in the problem about damped harmonic oscillators.\n    Return the array of values at the equispaced points.\n    'y0', 't0', 't', and 'n' are the same as they were in the ODE solving routines.\n    gamma is the parameter from the ODE. \"\"\"\n    gamma = .5\n    f = lambda x, y: np.array([y[1], - (gamma * y[1] + y[0])])\n    return RK4(f, y0, t0, t, n)[:,0]\n\n\n\ndef forced_harmonic_oscillator(y0, t0, t, n, gamma, omega):\n    \"\"\" Use the RK4 method to solve for the forced harmonic oscillator\n    problem. 'y0', 't0', 't', and 'n' are the same as the variables passed\n    to the RK4 function. 'gamma' and 'omega' are constants. \"\"\"\n    f = lambda x, y: np.array([y[1], np.cos(omega * x) - y[0] - gamma * y[1] / 2])\n    return RK4(f, y0, t0, t, n)[:,0]\n\n\n", "meta": {"hexsha": "4fb8745b55157626d63f7f034b3bf4d15a61c73b", "size": 8346, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/IVP/solutions.py", "max_stars_repo_name": "jessicaleete/numerical_computing", "max_stars_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-10-18T19:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:12:38.000Z", "max_issues_repo_path": "Labs/IVP/solutions.py", "max_issues_repo_name": "jessicaleete/numerical_computing", "max_issues_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/IVP/solutions.py", "max_forks_repo_name": "jessicaleete/numerical_computing", "max_forks_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-14T16:07:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-20T09:05:06.000Z", "avg_line_length": 40.712195122, "max_line_length": 98, "alphanum_fraction": 0.6162233405, "include": true, "reason": "import numpy", "num_tokens": 2689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.9136765234137297, "lm_q1q2_score": 0.8619145367810859}}
{"text": "import numpy as np\n\n# Lebesgue constant \n# L_j(x) = Pi_{i=0}^{j} (x - x_i)/(x_j - x_i)\n# delta_n = max{a<=x<=b} sum_{i=0}^{n} |L_i(x)|\n\n\"\"\"\nLet $x_0, x_1, \\ldots x_n$  be distinct nodes, and suppose $p(x)$ and $\\hat{p}(x)$ are polynomials of degree at most $n$ satisfying $p(x_j) = y_j$ and $\\hat{p}(x_j) = \\hat{y}_j$, $j=0,1,\\ldots, n$. If\n$$  \\vert y_j - \\hat{y}_j\\vert \\leq \\delta,  \\quad j=0,1,\\ldots, n,$$\nthen\n$$ \\Vert p - \\hat{p} \\Vert_{\\infty} \\leq \\Lambda_n \\delta.$$\n\"\"\"\n\n# cheyshev nodes are given by \ndef chebyshev_nodes(n):\n    # the lebesgue constant for chebyshev nodes is \n    # Delta_n = O(log(n))\n    j = arange(n+1)\n    return (a + b)/2 - (b - a)/2*cos(j*pi/n)\n\ndef chebyshev_fit(n):\n    j = arange(n+1)\n    d = ones(n+1)\n    d[0] = 0.5\n    d[-1] = 0.5\n    return (-1)**j*d\n\n", "meta": {"hexsha": "3b0cbc3f3954f4d9b9dfc0ae75495f87e76a7ea1", "size": 794, "ext": "py", "lang": "Python", "max_stars_repo_path": "Polynomial-Interpolation/chebyshev_nodes.py", "max_stars_repo_name": "Robertboy18/Numerical-Algorithms-Implementation", "max_stars_repo_head_hexsha": "e1ea13137d42ccc2502c590559edba750db4592d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Polynomial-Interpolation/chebyshev_nodes.py", "max_issues_repo_name": "Robertboy18/Numerical-Algorithms-Implementation", "max_issues_repo_head_hexsha": "e1ea13137d42ccc2502c590559edba750db4592d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Polynomial-Interpolation/chebyshev_nodes.py", "max_forks_repo_name": "Robertboy18/Numerical-Algorithms-Implementation", "max_forks_repo_head_hexsha": "e1ea13137d42ccc2502c590559edba750db4592d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3571428571, "max_line_length": 200, "alphanum_fraction": 0.5629722922, "include": true, "reason": "import numpy", "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551535992067, "lm_q2_score": 0.8933094145755218, "lm_q1q2_score": 0.8619141924118825}}
{"text": "\"\"\"\nImplementing various distance measures, i.e., norms.\n\"\"\"\nimport numpy as np \n\n\n\ndef hamming_distance(a, b):\n    \"\"\"\n    The Hamming distance (a discrete norm between binary-valued arrays).\n    \"\"\"\n    return np.sum(a != b)\n\n\ndef l1_norm(x):\n    \"\"\"\n    The L1-norm, a continuous valued norm.\n    \"\"\"\n    return np.sum(np.abs(x))\n\n\ndef l2_norm(x):\n    \"\"\"\n    The L2-norm, a continuous valued norm.\n    \"\"\"\n    return np.sqrt(np.sum(np.abs(x)**2))\n\n\n# TODO: Why is this faster than the built-in `np.linalg.norm`?\ndef lp_norm(x, p):\n    \"\"\"\n    The general LP-norm, a continuous valued norm.\n    \"\"\"\n    return np.power(np.sum(np.power(np.abs(x), p)), 1/p)\n\n\n# TODO: Divergence or distance?\ndef l1_divergence(a, b):\n    \"\"\"\n    The L1 di, a continuous valued norm between two arrays of the same shape.\n    \"\"\"\n    return np.sum(np.abs(a - b))\n\n\n# TODO: Divergence or distance?\ndef l2_divergence(a, b):\n    \"\"\"\n    The L2-norm, a continuous valued norm between two arrays of the same shape.\n    \"\"\"\n    return np.sqrt(np.sum(np.abs(a - b)**2))", "meta": {"hexsha": "e1cfbe38e7c7ce81fa9661b87f04f795d52b57cf", "size": 1044, "ext": "py", "lang": "Python", "max_stars_repo_path": "flib/norm.py", "max_stars_repo_name": "rldotai/flib", "max_stars_repo_head_hexsha": "695e875f708b0b71c9b005fdf85c066e4ffb7c0f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-02-01T00:34:23.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-01T00:34:23.000Z", "max_issues_repo_path": "flib/norm.py", "max_issues_repo_name": "rldotai/flib", "max_issues_repo_head_hexsha": "695e875f708b0b71c9b005fdf85c066e4ffb7c0f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "flib/norm.py", "max_forks_repo_name": "rldotai/flib", "max_forks_repo_head_hexsha": "695e875f708b0b71c9b005fdf85c066e4ffb7c0f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.88, "max_line_length": 79, "alphanum_fraction": 0.6159003831, "include": true, "reason": "import numpy", "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854103128329, "lm_q2_score": 0.8887587986487518, "lm_q1q2_score": 0.8619053162167203}}
{"text": "\"\"\"\nAn implementation of the Exact Fit of the first 3 Moments \n(#F3M) of finding the parameters that make up the mixture \nof 2 Gaussian distributions. Based on the work by \nLopez de Prado and Foreman (2014) \"A mixture of two\nGaussians approach to mathematical portfolio oversight:\nThe EF3M algorithm.\" Quantitative Finance, Vol. 14, \nNo. 5, pp. 913-930.\n\"\"\"\n\n# imports\nimport numpy as np\n\nfrom scipy.stats import norm, moment\nfrom scipy.special import comb\nimport scipy.integrate as integrate\n\nimport pandas as pd\nimport dask.dataframe as dd\nfrom dask import delayed\nfrom dask.diagnostics import ProgressBar\n\n\n# The mixture's class.\n# This will contain all data and methods for determining\n# the parameters of the mixture of 2 normal distributions.\nclass M2N:\n    \"\"\"\n    Class used to contain parameters and equations for the\n    EF3M algorithm, when fitting parameters to a mixture\n    of 2 Gaussians.\n    \"\"\"\n    def __init__(self, moments):\n        \"\"\"\n        Constructor\n\n        :param moments: (list) The first five (1... 5) raw moments of the \n                        mixture distribution.\n\n        The parameters of the mixture are defined by a list, where:\n        parameters = [mu1, mu2, sigma1, sigma2, p1]\n        \"\"\"\n        self.moments = moments\n        # initialize the \n        self.parameters = [0 for i in range(5)]  # initialize parameter list\n        self.error = sum([moments[i]**2 for i in range(len(moments))])\n    \n    def fit(self, mu2, epsilon, variant=1, maxIter=100_000):\n        \"\"\"\n        Fits and the parameters that describe the mixture\n        of the 2 Normal distributions for a given set of initial\n        parameter guesses.\n\n        :param mu2: (float) An initial estimate for the mean of the second\n                    distribution.\n        :param epsilon: (float) Error tolerance.\n        :param variant: (int) Which algorithm variant to use, 1 or 2.\n        :param maxIter: (int) Maximum number of iterations after which \n                        to terminate loop.\n        \"\"\"\n        p1 = np.random.uniform(0, 1)\n        numIter = 0\n        while True:\n            numIter += 1\n            if variant == 1:\n                parameters_new = self.iter4(mu2, p1, self.moments)  # first variant\n            elif variant == 2:\n                parameters_new = self.iter5(mu2, p1, self.moments)  # second variant\n            else:\n                raise ValueError(\"Value of 'variant' must be either 1 or 2.\")\n            if len(parameters_new) == 0:\n                # invalid value found in iter4 or iter5\n                return None\n            parameters = parameters_new.copy()\n            moments = self.get_moments(parameters)\n            error = sum([(self.moments[i]-moments[i])**2 \n                        for i in range(len(moments))])\n            if error < self.error:\n                # update with new best parameters, error\n                self.parameters = parameters\n                self.error = error\n            if abs(p1 - parameters[4]) < epsilon:\n                # stopping condition\n                break\n            if numIter > maxIter:\n                # maxIter reached, convergence not fast enough\n                return None\n            p1 = parameters[4]\n            mu2 = parameters[1]  # for the 5th moments convergence\n        self.parameters = parameters\n        return None\n    \n    def get_moments(self, parameters):\n        \"\"\"\n        Calculates and returns the first five (1...5) raw moments \n        corresponding to the newly esitmated parameters.\n\n        :param parameters: (list) List of parameters if the \n        specific order [mu1, mu2, sigma1, sigma2, p1]\n        :return: (list) List of the first five moments\n        \"\"\"\n        u1, u2, s1, s2, p1 = parameters  # for clarity\n        p2 = 1-p1  # for symmetry\n        m1 = p1*u1 + p2*u2  # Eq. (6)\n        m2 = p1*(s1**2 + u1**2) + p2*(s2**2 + u2**2)  # Eq. (7)\n        m3 = p1*(3*s1**2*u1 + u1**3) + p2*(3*s2**2*u2 + u2**3)  # Eq. (8)\n        m4 = p1*(3*s1**4 + 6*s1**2*u1**2 + u1**4) +\\\n            p2*(3*s2**4 + 6*s2**2*u2**2 + u2**4)  # Eq. (9)\n        m5 = p1*(15*s1**4*u1 + 10*s1**2*u1**3 + u1**5) +\\\n            p2*(15*s2**4*u2 + 10*s2**2*u2**3 + u2**5)  # Eq. (10)\n        return [m1, m2, m3, m4, m5]\n    \n    def iter4(self, mu2, p1, moments):\n        \"\"\"\n        Evaluation of the set of equations that make up\n        variant #1 of the EF3M algorithm (fitting using the \n        first four moments).\n\n        :param mu2: (float) Initial parameter value for mu2\n        :param p1: (float) Probability defining the mixture; p1, 1-p1\n        :param moments: (list) First five raw moments of the mixture\n        distribution [m1, m2, m3, m4, m5]\n        :return: (list) List of estimated parameter if no invalid values\n        are encountered (e.g. complex values, divide-by-zero), otherwise\n        an empty list is returned.\n        \"\"\"\n        m1, m2, m3, m4, __ = moments  # for clarity\n        # mu1, Equation (22)\n        mu1 = (m1 - (1-p1)*mu2) / p1\n        # sigma2, Equation (24)\n        if (3*(1-p1)*(mu2-mu1)) == 0:\n            # check for divide-by-zero\n            return []\n        sigma2_squared = ( (m3 + 2*p1*mu1**3 + (p1-1)*mu2**3 -\\\n                                        3*mu1*(m2 + mu2**2*(p1-1))) /\\\n                            (3*(1-p1)*(mu2-mu1)) )\n        if sigma2_squared < 0:\n            return []\n        sigma2 = sigma2_squared**(.5)\n        # sigma1, Equation (23)\n        sigma1_squared = ( (m2 - sigma2**2 - mu2**2)/p1 +\\\n                                        sigma2**2 + mu2**2 - mu1**2 )\n        if sigma1_squared < 0:\n            return []\n        sigma1 = sigma1_squared**(.5)\n        if np.iscomplex(sigma1) or np.iscomplex(sigma2) or \\\n            np.isnan(sigma1) or np.isnan(sigma2):\n            return []  # returns empty list sigma1 or sigma2 are invalid\n        # adjust guess for p1, Equation (25)\n        p1_deno = (3*(sigma1**4 - sigma2**4) + 6*(sigma1**2*mu1**2 - \\\n            sigma2**2*mu2**2) + mu1**4 - mu2**4)\n        if p1_deno == 0:\n            return []  # return empty list if about to divide by zero\n        p1 = (m4 - 3*sigma2**4 - 6*sigma2**2*mu2**2 - mu2**4) / p1_deno\n        if (p1<0) or (p1>1):\n            return []\n        return [mu1, mu2, sigma1, sigma2, p1]\n    \n    def iter5(self, mu2, p1, moments):\n        \"\"\"\n        Evaluation of the set of equations that make up\n        variant #2 of the EF3M algorithm (fitting using the \n        first five moments).\n\n        :param mu2: (float) Initial parameter value for mu2\n        :param p1: (float) Probability defining the mixture; p1, 1-p1\n        :param moments: (list) First five raw moments of the mixture\n        distribution [m1, m2, m3, m4, m5]\n        :return: (list) List of estimated parameter if no invalid values\n        are encountered (e.g. complex values, divide-by-zero), otherwise\n        an empty list is returned.\n        \"\"\"\n        m1, m2, m3, m4, m5 = moments  # for clarity\n        # mu1, Equation (22)\n        mu1 = (m1 - (1-p1)*mu2) / p1\n        if (3*(1-p1)*(mu2-mu1)) == 0:\n            return []\n        # sigma2, Equation (24)\n        if (3*(1-p1)*(mu2-mu1)) == 0:\n            # check for divide-by-zero\n            return []\n        sigma2_squared = ( (m3 + 2*p1*mu1**3 + (p1-1)*mu2**3 -\\\n                                        3*mu1*(m2 + mu2**2*(p1-1))) /\\\n                            (3*(1-p1)*(mu2-mu1)) )\n        if sigma2_squared < 0:\n            return []\n        sigma2 = sigma2_squared**(.5)\n        # sigma1, Equation (23)\n        sigma1_squared = ( (m2 - sigma2**2 - mu2**2)/p1 +\\\n                                        sigma2**2 + mu2**2 - mu1**2 )\n        if sigma1_squared < 0:\n            return []\n        sigma1 = sigma1_squared**(.5)\n        # last check for sigma1 and sigma2 validity\n        if np.iscomplex(sigma1) or np.iscomplex(sigma2) or \\\n            np.isnan(sigma1) or np.isnan(sigma2):\n            return []\n        # adjust the guess for mu2, Equation (27)\n        if (1-p1) < 1e-4:\n            return []\n        a = ( 6*sigma2**4 + (m4-p1*(3*sigma1**4+6*sigma1**2*mu1**2+mu1**4)) /\\\n             (1-p1 ) )**.5\n        mu2_squared = (a - 3*sigma2**2)\n        if np.iscomplex(mu2_squared):\n            return []\n        if mu2_squared < 0:\n            return []\n        mu2 = mu2_squared**.5\n        if np.iscomplex(mu2):\n            return []\n        # adjust guess for p1, Equation (28, 29)\n        a = 15*sigma1**4*mu1+10*sigma1**2*mu1**3+mu1**5\n        b = 15*sigma2**4*mu2+10*sigma2**2*mu2**3+mu2**5\n        if (a-b) == 0:\n            return []  # return empty list if about to divide by zero\n        p1 = (m5-b) / (a-b)\n        if (p1<0) or (p1>1):\n            return []\n        return [mu1, mu2, sigma1, sigma2, p1]\n\n    def singleLoop(self, moments, epsilon=10**-5, factor=5,\n                    variant=1, maxIter=100_000):\n        \"\"\"\n        A single scan through the list of mu2 values, cataloging the\n        successful fittings in a DataFrame.\n\n        :param moments: (list) First five central moments, [m1, m2, m3, m4, m5]\n        :param epsilon: (float) Fitting tolerance\n        :param factor: (float) Lambda factor from equations\n        :param variant: (int) The EF3M variant to execute, options\n        are 1: EF3M using first 4 moments, 2: EF3M using first 5 moments\n        :param maxIter: (int) Maximum number of iterations to perform\n        in the 'fit' method\n        :return: (pd.DataFrame) Fitted parameters and error\n        \"\"\"\n        stDev = centeredMoment(moments, 2)**.5\n        mu2 = [float(i)*epsilon*factor*stDev + moments[0] \n                for i in range(1, int(1/epsilon))]\n        m2n = M2N(moments)\n        err_min = m2n.error\n        d_results = {}\n        for mu2_i in mu2:\n            m2n.fit(mu2=mu2_i, epsilon=epsilon, variant=variant, maxIter=maxIter)\n            if m2n.error < err_min:\n                err_min = m2n.error\n                d_results['mu1'], d_results['mu2'], d_results['sigma1'], \\\n                    d_results['sigma2'], \\\n                        d_results['p1'] = [[p] for p in m2n.parameters]\n                d_results['error'] = [err_min]\n        return pd.DataFrame.from_dict(d_results)\n\n    # Repeat runs and collect results as a DataFrame.\n    def mpFit(self, moments, epsilon=10**-5, factor=5, n_runs=1, variant=1,\n                maxIter=100_000):\n        \"\"\"\n        Parallelized implementation of 'singleLoop' method.\n\n        :param moments: (list) First five central moments, [m1, m2, m3, m4, m5]\n        :param epsilon: (float) Fitting tolerance\n        :param factor: (float) Lambda factor from equations\n        :param n_runs: (int) Number of times to execute 'singleLoop'\n        :param variant: (int) The EF3M variant to execute, options\n        are 1: EF3M using first 4 moments, 2: EF3M using first 5 moments\n        :param maxIter: (int) Maximum number of iterations to perform\n        in the 'fit' method\n        :return: (pd.DataFrame) Fitted parameters and error\n        \"\"\"\n        # create a list of delayed objects that return a pd.DataFrame\n        dfs = [delayed(self.singleLoop)(moments=moments,\n                                        epsilon=epsilon,\n                                        factor=factor,\n                                        variant=variant,\n                                        maxIter=maxIter\n                                        ) for i in range(n_runs)]\n        # build a dask.DataFrame from a list of delayed objects\n        ddf = dd.from_delayed(dfs)\n        # compute all runs, using dask multiprocessing\n        df = ddf.compute(scheduler='processes').reset_index(drop=True)\n        df = df.sort_values('error')\n        return df\n\n# === Helper functions, outside class === #\ndef centeredMoment(moments, order):\n    \"\"\"\n    Compute a single moment of a specific order about the mean (centered)\n    given moments about the origin (raw).\n\n    :param moments: (list) First 'order' raw moments\n    :param order: (int) The order of the moment to calculate\n    \"\"\"\n    moment_c = 0  # first centered moment is always zero\n    for j in range(order + 1):\n        comb = binomialCoeff(order, j)\n        if j == order:\n            a = 1\n        else:\n            a = moments[order-j-1]\n        moment_c += (-1)**j*comb*moments[0]**j*a\n    return moment_c\n\ndef rawMoment(central_moments, dist_mean):\n    \"\"\"\n    Calculates a list of raw moments given a list of \n    central moments.\n\n    :param central_moments: (list) The first n (1...n) central moments as a list\n    :param dist_mean: (float) The mean of the distribution\n    :return: (list) The first n+1 (0...n) raw moments \n    \"\"\"\n    raw_moments = [dist_mean]\n    central_moments = [1] + central_moments  # add the zeroth moment\n    for n in range(2, len(central_moments)):\n        moment_n_parts = []\n        for k in range(n+1):\n            sum_part = comb(n, k) * central_moments[k] * dist_mean**(n-k)\n            moment_n_parts.append(sum_part)\n        moment_n = sum(moment_n_parts)\n        raw_moments.append(moment_n)\n    return raw_moments\n\ndef binomialCoeff(n, k):\n    \"\"\"\n    Calculate the number of way 'n' things can be chosen 'k' at-a-time,\n    'n'-choose-'k'. This is a simple implementation of the\n    scipy.special.comb function.\n\n    :param n: (int) The number of things\n    :param k: (int) The number of things to be chosen at one time\n    :return: (int) The total number of combinations\n    \"\"\"\n    if k < 0 or k > n:\n        return 0\n    if k > n-k:\n        k = n-k\n    c = 1\n    for i in range(k):\n        c = c*(n - (k - (i+1)))\n        c = c // (i+1)\n    return c\n", "meta": {"hexsha": "b2ebfd4fbc3e7f91d56134294ff17e00630fc2f7", "size": 13593, "ext": "py", "lang": "Python", "max_stars_repo_path": "jupyter-notebooks/hudson-and-thames-quant/Advances in Financial Machine Learning/Bet Sizing/EF3M/ef3m.py", "max_stars_repo_name": "BlackSwine/compendium", "max_stars_repo_head_hexsha": "8ca631d79605c4e34ef2cec1dc5a469ab7639623", "max_stars_repo_licenses": ["BSD-3-Clause-Clear", "Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jupyter-notebooks/hudson-and-thames-quant/Advances in Financial Machine Learning/Bet Sizing/EF3M/ef3m.py", "max_issues_repo_name": "BlackSwine/compendium", "max_issues_repo_head_hexsha": "8ca631d79605c4e34ef2cec1dc5a469ab7639623", "max_issues_repo_licenses": ["BSD-3-Clause-Clear", "Unlicense"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-20T18:39:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-20T18:39:44.000Z", "max_forks_repo_path": "Advances in Financial Machine Learning/Bet Sizing/EF3M/ef3m.py", "max_forks_repo_name": "tzw101/research", "max_forks_repo_head_hexsha": "522cf53da9ba42b0b8fd79a8760ee0c39e6e2715", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-31T15:07:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-31T15:07:10.000Z", "avg_line_length": 39.9794117647, "max_line_length": 84, "alphanum_fraction": 0.5520488487, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 3828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854120593483, "lm_q2_score": 0.8887587905460026, "lm_q1q2_score": 0.8619053099110232}}
{"text": "import numpy as np\nimport scipy.sparse as sp\nimport scipy.sparse.linalg\nimport scipy.optimize\nimport matplotlib.pylab as plt\n\ndef buildA(N):\n    dx = 1 / N\n    nvar = (N - 1)**2;\n    e1 = np.ones((nvar), dtype=float);\n    e2 = np.copy(e1)\n    e2[:N-1:] = 0\n    e3 = np.copy(e1)\n    e3[N-2:N-1:] = 0\n    A = sp.spdiags(\n        (-e1, -e3, 4*e1, -e2, -e1),\n        (-(N-1), -1, 0, 1, N-1), nvar, nvar\n    )\n    A = A / dx**2;\n    return A\n\n\ndef buildf1(N):\n    x = np.arange(0, 1, 1/N).reshape(N, 1)\n    y = x.T\n    f = np.dot(np.sin(np.pi*x), np.sin(np.pi*y))\n    return f[1:,1:].reshape(-1,1)\n\ndef buildf2(N):\n    x = np.arange(0, 1, 1/N).reshape(N, 1)\n    y = x.T\n    f = np.dot(np.maximum(x,1-x), np.maximum(y,1-y))\n    return f[1:,1:].reshape(-1, 1)\n\ndef jacobi(A, b, x0=None, tol=1e-5, max_iter=1000):\n    if x0 is None:\n        x0 = np.zeros_like(b)\n    x = np.copy(x0)\n    b_norm = np.linalg.norm(b)\n\n    # jacobi method: M = D\n    M = A.diagonal().reshape(-1, 1)\n    invM = 1/M\n\n    # main relaxation iteration\n    for i in range(max_iter):\n        r = b - A @ x\n        error = np.linalg.norm(r) / b_norm\n        if error < tol:\n            break\n        x += invM * r\n    return x, i\n\ndef SOR(A, b, omega, x0=None, tol=1e-5, max_iter=300):\n    if x0 is None:\n        x0 = np.zeros_like(b)\n    x = np.copy(x0)\n    b_norm = np.linalg.norm(b)\n\n    # SOR method\n    D = sp.spdiags((A.diagonal()), (0), *A.shape)\n    L = sp.tril(A, k=-1)\n    M = (1/omega) * D + L\n\n    # main relaxation iteration\n    for i in range(max_iter):\n        r = b - A @ x\n        error = np.linalg.norm(r) / b_norm\n        if error < tol:\n            break\n        x += sp.linalg.spsolve_triangular(M, r)\n    return x, i\n\n\nnum = 20\niterations = np.empty((num, 2), dtype=int)\niterations[:] = np.nan\nNs = np.logspace(0.5, 1.5, num=num, dtype=int)\nfor j, buildf in enumerate((buildf1, buildf2)):\n    for i, N in enumerate(Ns):\n        A = buildA(N)\n        f = buildf(N)\n        max_iter = 10*N\n        x, iters = jacobi(A, f, max_iter=max_iter)\n        if i < max_iter:\n            iterations[i, j] = iters\n\nplt.plot(Ns, iterations)\nplt.xlabel('N')\nplt.ylabel('iterations')\nplt.show()\n\nN = 64\nA = buildA(N)\nf = buildf2(N)\n\ndef SOR_iterations(omega):\n    x, i = SOR(A, f, omega, max_iter=10, tol=1e-32)\n    return np.linalg.norm(A @ x - f)\n\nres = scipy.optimize.minimize_scalar(SOR_iterations, bracket=[0.1, 1.0, 1.99], tol=1e-2)\nprint('ideal omega is', res.x, 'versus analytic value of', 2 / (1 + np.sin(np.pi/N)))\n\n\n", "meta": {"hexsha": "807004eb62c84522682ede792076bdbba0012800", "size": 2496, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/unit_2_6.py", "max_stars_repo_name": "tommylees112/scientific-computing", "max_stars_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-02-03T02:10:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T13:21:47.000Z", "max_issues_repo_path": "src/unit_2_6.py", "max_issues_repo_name": "tommylees112/scientific-computing", "max_issues_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-01T16:00:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T17:09:17.000Z", "max_forks_repo_path": "src/unit_2_6.py", "max_forks_repo_name": "tommylees112/scientific-computing", "max_forks_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-02-01T15:45:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T12:20:25.000Z", "avg_line_length": 23.7714285714, "max_line_length": 88, "alphanum_fraction": 0.546875, "include": true, "reason": "import numpy,import scipy", "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305360354471, "lm_q2_score": 0.8947894597898777, "lm_q1q2_score": 0.861888530992272}}
{"text": "import numpy as np \n\nnp.__version__\n\n# make list from 0-9\nL = list(range(10))\nL\ntype(L[0])\n\n# Use list comprehension to cast ints as strings\nL2 = [str(c) for c in L]\nL2\ntype(L2[0])\n\n# Creating Arrays from Python Lists\n# integer array:\nnp.array([1,4,2,5,2])\n\n# np.arrays can only contain one type of info, so if there is\n# a mix of types it will try to typecast them into a single one\nnp.array([3.14, 2, 3, 4]) # will result in all being floats\n\n# you can also be quite explicit\nnp.array([1, 2, 3, 4], dtype='float32')\n\n# finally, unlike python lists, numpy arrays can explicitly be multidimensional:\n# nested lists results in multidimensional arrays\nnp.array([range(i,i+3) for i in [2,4,6]]) # nb the inner lists, are treated as rows of the resulting two_dimesnional array\n\n# Creating Arrays from scratch\n## for larger arrays it is more efficient to create arrays from scratch using routines built into Numpy\n\n# Create a length-10 integer array filled with zeros\nnp.zeros(10, dtype=int)\n\n# Create a 3x5 floating-point array filled with ones\nnp.ones((3, 5), dtype=float)\n\n# Create a 3x5 array filled with 3.14\nnp.full((3, 5), 3.14)\n\n# Create an array filled with a linear sequence\n# Starting at 0, ending at 20, stepping by 2\n# (this is similar to the built-in range() function)\nnp.arange(0, 20, 2)\n\n# Create an array of five values evenly spaced between 0 and 1\nnp.linspace(0, 1, 5)\n\n# Create a 3x3 array of uniformly distributed\n# random values between 0 and 1\nnp.random.random((3, 3))\n\n# Create a 3x3 array of normally distributed random values\n# with mean 0 and standard deviation 1\nnp.random.normal(0, 1, (3, 3))\n\n# Create a 3x3 array of random integers in the interval [0, 10)\nnp.random.randint(0, 10, (3, 3))\n\n# Create a 3x3 identity matrix\nnp.eye(3)\n\n# Create an uninitialized array of three integers\n# The values will be whatever happens to already exist at that memory location\nnp.empty(3)\n\n# The standard NumPy data types are listed in the following table. \n# Note that when constructing an array, they can be specified using a string:\nnp.zeros(10, dtype='int16')\n# or using the associated NumPy object:\nnp.zeros(10, dtype=np.int16)\n# these are the same", "meta": {"hexsha": "df6a8046861b69d2deeeb175c94627b395b96d04", "size": 2163, "ext": "py", "lang": "Python", "max_stars_repo_path": "basics/numpyBasics.py", "max_stars_repo_name": "paulmorio/grusData", "max_stars_repo_head_hexsha": "3482f9c897e70493fd5320381607cf42c5c30eb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "basics/numpyBasics.py", "max_issues_repo_name": "paulmorio/grusData", "max_issues_repo_head_hexsha": "3482f9c897e70493fd5320381607cf42c5c30eb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "basics/numpyBasics.py", "max_forks_repo_name": "paulmorio/grusData", "max_forks_repo_head_hexsha": "3482f9c897e70493fd5320381607cf42c5c30eb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6301369863, "max_line_length": 122, "alphanum_fraction": 0.7327785483, "include": true, "reason": "import numpy", "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.9304582554941719, "lm_q1q2_score": 0.8618869510540745}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar  1 18:19:41 2019\r\n\r\n@author: Ham\r\n\r\nHackerRanch Challenge: Mean, Var and Std\r\n\r\nmean\r\n\r\nThe mean tool computes the arithmetic mean along the specified axis.\r\n\r\nimport numpy\r\n\r\nmy_array = numpy.array([ [1, 2], [3, 4] ])\r\n\r\nprint numpy.mean(my_array, axis = 0)        #Output : [ 2.  3.]\r\nprint numpy.mean(my_array, axis = 1)        #Output : [ 1.5  3.5]\r\nprint numpy.mean(my_array, axis = None)     #Output : 2.5\r\nprint numpy.mean(my_array)                  #Output : 2.5\r\nBy default, the axis is None.\r\nTherefore, it computes the mean of the flattened array.\r\n\r\nvar\r\n\r\nThe var tool computes the arithmetic variance along the specified axis.\r\n\r\nimport numpy\r\n\r\nmy_array = numpy.array([ [1, 2], [3, 4] ])\r\n\r\nprint numpy.var(my_array, axis = 0)         #Output : [ 1.  1.]\r\nprint numpy.var(my_array, axis = 1)         #Output : [ 0.25  0.25]\r\nprint numpy.var(my_array, axis = None)      #Output : 1.25\r\nprint numpy.var(my_array)                   #Output : 1.25\r\nBy default, the axis is None.\r\nTherefore, it computes the variance of the flattened array.\r\n\r\nstd\r\n\r\nThe std tool computes the arithmetic standard deviation along the specified axis.\r\n\r\nimport numpy\r\n\r\nmy_array = numpy.array([ [1, 2], [3, 4] ])\r\n\r\nprint numpy.std(my_array, axis = 0)         #Output : [ 1.  1.]\r\nprint numpy.std(my_array, axis = 1)         #Output : [ 0.5  0.5]\r\nprint numpy.std(my_array, axis = None)      #Output : 1.11803398875\r\nprint numpy.std(my_array)                   #Output : 1.11803398875\r\nBy default, the axis is None.\r\nTherefore, it computes the standard deviation of the flattened array.\r\n\r\nTask\r\n\r\nYou are given a 2-D array of size NxM.\r\nYour task is to find:\r\n\r\nThe mean along axis 1\r\nThe var along axis 0\r\nThe std along axis None\r\n\r\nInput Format\r\n\r\nThe first line contains the space separated values of N and M.\r\nThe next N lines contains N space separated integers.\r\n\r\nOutput Format\r\n\r\nFirst, print the mean.\r\nSecond, print the var.\r\nThird, print the std.\r\n\r\nSample Input\r\n\r\n2 2\r\n1 2\r\n3 4\r\n\r\nSample Output\r\n\r\n[ 1.5  3.5]\r\n[ 1.  1.]\r\n1.11803398875\r\n\r\n\"\"\"\r\n\r\nimport numpy\r\n\r\n# ignoring 2nd int of 1st line, M\r\na = [list(map(int, input().strip().split()))\r\n     for _ in range(int(input().strip().split()[0]))]\r\n# I cheated: got the printoptions from Discussion\r\nnumpy.set_printoptions(legacy='1.13')\r\nprint(numpy.mean(a, axis=1))\r\nprint(numpy.var(a, axis=0))\r\nprint(numpy.std(a))\r\n", "meta": {"hexsha": "3e8d5b9c2096df214a47cc110db9f14b31d5e18c", "size": 2423, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/numpy_mean_var_std.py", "max_stars_repo_name": "Hamng/python-sources", "max_stars_repo_head_hexsha": "0cc5a5d9e576440d95f496edcfd921ae37fcd05a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/numpy_mean_var_std.py", "max_issues_repo_name": "Hamng/python-sources", "max_issues_repo_head_hexsha": "0cc5a5d9e576440d95f496edcfd921ae37fcd05a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-23T18:30:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-23T18:30:51.000Z", "max_forks_repo_path": "python/numpy_mean_var_std.py", "max_forks_repo_name": "Hamng/python-sources", "max_forks_repo_head_hexsha": "0cc5a5d9e576440d95f496edcfd921ae37fcd05a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7244897959, "max_line_length": 82, "alphanum_fraction": 0.6417664053, "include": true, "reason": "import numpy", "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.9161096118716263, "lm_q1q2_score": 0.8618665290045006}}
{"text": "# 2 DOF SYSTEM\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport libraryTugas as lib\n\n# 1. SYSTEMS PARAMETERS\n#================\n# a. Initial condition Block 1 & 2\nx_init1, xDot_init1 =  0.1, 0   # [m], [m/s]\nx_init2, xDot_init2 = -0.1, 0   # [m], [m/s]\n\n# b. System parameters Block 1 & 2\nmass1, damp1, spring1 = 1, 1, 10 # [kg], [Ns/m], [N/m]\nmass2, damp2, spring2 = 2, 1, 20 # [kg], [Ns/m], [N/m]\n\n# c. Time parameters\ntimeStart, timeStop, stepTime = 0, 10, 0.001 # [S]\n\n# d. Define System MODEL!\ndef systemFunction (y, t): # Fungsi persamaan gerak\n    Qe1 = -spring1*float(y[0]) + spring2*(float(y[1])-float(y[0]))- damp1*float(y[2]) + damp2*(float(y[3])-float(y[2]))\n    Qe2 = -spring2*(float(y[1])-float(y[0])) - damp2*(float(y[3])-float(y[2]))\n    externalForces_Matrix = np.array([[Qe1], [Qe2]], dtype = float)\n    xDotDot = np.dot(mass_MatInverse, externalForces_Matrix)\n    # dalam kasus ini, parameter \"t\" tidak terpakai\n    return xDotDot\n\n#======================\n\n# 2. INITIALIZE SIMULATION\n# a. Simulation time\ntime = np.arange(timeStart, timeStop, stepTime, dtype = float) \n# b. Mass matrix\nmass_Matrix = np.array([[mass1, 0], \n                        [0, mass2]], dtype = float)                   \nmass_MatInverse = np.linalg.inv(mass_Matrix)\n\n# c. Initial Condition of THE state\ny = np.array([[x_init1], [x_init2], [xDot_init1], [xDot_init2]], dtype = float)\n\n# 3. SOLVING EQUATION OF MOTION USING RUNGE KUTTA 4th ORDER!!\nposition, velocity, acceleration = lib.rungeKutta4(y, time, \n                                                systemFunction, stepTime)\n\n# 4. PLOTING RESULTS!!\nplt.figure(1)\nplt.plot(time, position[:,0:1])\nplt.plot(time, position[:,1:2])\ntitle = \"position plot [step time = %1.6f s]\" % stepTime\nplt.title(title)\nplt.ylabel('displacement [m]')\nplt.xlabel('time [s]')\nplt.grid(True)\nplt.legend([\"mass 1\", \"mass 2\"])\n\nplt.figure(2)\nplt.plot(time, velocity[:,0:1])\nplt.plot(time, velocity[:,1:2])\ntitle = \"velocity plot [step time = %1.6f s]\" % stepTime\nplt.title(title)\nplt.ylabel('velocity [m/s]')\nplt.xlabel('time [s]')\nplt.grid(True)\nplt.legend([\"mass 1\", \"mass 2\"])\n\nplt.figure(3)\nplt.plot(time, acceleration[:,0:1])\nplt.plot(time, acceleration[:,1:2])\ntitle = \"acceleration plot [step time = %1.6f s]\" % stepTime\nplt.title(title)\nplt.ylabel('acceleration [m/s/s]')\nplt.xlabel('time [s]')\nplt.grid(True)\nplt.legend([\"mass 1\", \"mass 2\"])\nplt.show()", "meta": {"hexsha": "574601b12bb3de803f90a7a7e6cc2e124e8a6e7a", "size": 2393, "ext": "py", "lang": "Python", "max_stars_repo_path": "implement2DOF.py", "max_stars_repo_name": "eigeneddie/multibodydynamics", "max_stars_repo_head_hexsha": "ed8bb9bbfb3ba31a3744aab51a48bae68ad9167c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "implement2DOF.py", "max_issues_repo_name": "eigeneddie/multibodydynamics", "max_issues_repo_head_hexsha": "ed8bb9bbfb3ba31a3744aab51a48bae68ad9167c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "implement2DOF.py", "max_forks_repo_name": "eigeneddie/multibodydynamics", "max_forks_repo_head_hexsha": "ed8bb9bbfb3ba31a3744aab51a48bae68ad9167c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9066666667, "max_line_length": 119, "alphanum_fraction": 0.6284997911, "include": true, "reason": "import numpy", "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966410494349896, "lm_q2_score": 0.8918110555020056, "lm_q1q2_score": 0.8618555630143957}}
{"text": "from __future__ import division\n# from math import sin, cos\nimport pylab as pl\nimport numpy as np\nfrom numpy import sin,cos\n\ndef f_dash_central_diff(f,x,h):\n    return (f(x + h) - f(x - h)) / (2 * h)\n    \ndef calculate():\n    x = 0.5\n    h_initial = 0.5\n    h = np.asarray([h_initial/(4 ** _) for _ in range(25)])\n\n    f = sin\n    f_dash = cos\n    f_3dash = lambda x: -1 * cos(x)\n\n    error_total = abs(f_dash_central_diff(f,x,h) - f_dash(x))\n    error_trunc = abs((-1 * (h ** 2)/6) * f_3dash(x))\n    error_round = abs(error_total - error_trunc)\n    \n    print(h, error_total,  error_trunc, error_round)\n    pl.loglog(h, error_total, h, error_trunc, h, error_round)\n    pl.legend([\"$\\epsilon$\", \"$\\epsilon_t$\", \"$\\epsilon_r$\"], loc = 4)\n    pl.savefig(\"solution1_fig.pdf\")\n    pl.show()\n    \nif __name__ == '__main__':\n    calculate()\n    \n", "meta": {"hexsha": "300261e326338f35897c821272d242477f15eae8", "size": 840, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercise1/solution1_new.py", "max_stars_repo_name": "kunalghosh/BECS-114.1100-Computational-Science", "max_stars_repo_head_hexsha": "ca91ac59cb5276d213c1aec50ae7786efe72ae43", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercise1/solution1_new.py", "max_issues_repo_name": "kunalghosh/BECS-114.1100-Computational-Science", "max_issues_repo_head_hexsha": "ca91ac59cb5276d213c1aec50ae7786efe72ae43", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise1/solution1_new.py", "max_forks_repo_name": "kunalghosh/BECS-114.1100-Computational-Science", "max_forks_repo_head_hexsha": "ca91ac59cb5276d213c1aec50ae7786efe72ae43", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.25, "max_line_length": 70, "alphanum_fraction": 0.6107142857, "include": true, "reason": "import numpy,from numpy", "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104933824753, "lm_q2_score": 0.8918110368115781, "lm_q1q2_score": 0.8618555440890141}}
{"text": "'''\nwant to do a quick demo of astrologer example in agresti statistics book\n\nsource: Agresti-Statistics book, ch9, pg 434 (pdf number)\n\"can astrologers predict personality better than random guessing?\"\n\nNOTE: typically, to disprove the null hypothesis (usually some sort of negative\n    / disbelief prediction stating that something is NOT true), a p-value\n    (probability value) with a \"significance level\" of 0.05 or lower is desired,\n    which simply means that given the sample results, there's a 95% chance that\n    the null hypothesis is wrong beyond a reasonable doubt.\n\n'''\n\nimport numpy as np\nimport scipy.stats as st\n\n''' in this example, the values are as such:\nthere were 116 attempts, n=116\nastrologers had to choose one of three options, so p0 = 1/3 (random guess)\nastrologers guessed correctly 40 times\nnull hypothesis: astrologers are no better than guessing\n\n'''\n\np0 = 1/3\nn=116\nnCorrect = 40\np = nCorrect / n\nstdErr0 = (p0*(1-p0)/n)**0.5 # standard error if p0 is correct, must be disproven\nzstat = (p-p0)/stdErr0\npvalue = st.t.sf(zstat,n-1)\n# pvalue is the \"survival function\" (1-tail distribution) of the student\n#   distribution, given zvalue and degrees of freedom\nprint('astronomers got {} correct, zstat {}, and pvalue {}'.format(nCorrect,zstat,pvalue))\n\n# given the original numbers, pvalue is 0.396, meaning that the null hypothesis\n# is still valid, aka astronomers cannot be assumed to do better than random\n# guessing. they would have needed to get 48 guesses correct at minimum.\n", "meta": {"hexsha": "ba3f469cd65da34d8f61846b4d59dfe5a0d10402", "size": 1511, "ext": "py", "lang": "Python", "max_stars_repo_path": "py_sandbox/statistics/significance_test_1.py", "max_stars_repo_name": "kjgonzalez/codefiles", "max_stars_repo_head_hexsha": "b86f25182d1b5553a331f8721dd06b51fa157c3e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "py_sandbox/statistics/significance_test_1.py", "max_issues_repo_name": "kjgonzalez/codefiles", "max_issues_repo_head_hexsha": "b86f25182d1b5553a331f8721dd06b51fa157c3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-10-01T20:48:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-14T18:21:09.000Z", "max_forks_repo_path": "py_sandbox/statistics/significance_test_1.py", "max_forks_repo_name": "kjgonzalez/codefiles", "max_forks_repo_head_hexsha": "b86f25182d1b5553a331f8721dd06b51fa157c3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.775, "max_line_length": 90, "alphanum_fraction": 0.75049636, "include": true, "reason": "import numpy,import scipy", "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104904802131, "lm_q2_score": 0.8918110382493034, "lm_q1q2_score": 0.8618555428901774}}
{"text": "from sympy import symbols, solve, diff, pprint, integrate\n\n# After a long​ study, tree scientists conclude that a eucalyptus tree will grow at the rate of\n\nt = symbols( 't' )\nR = 0.5 + 4 / ( t + 1 ) **3\n#  feet per​ year, where t is the time​ (in years).\npprint( R )\n\n# Find the number of feet that the tree will grow in the second year.\na, b = 1, 2\nround( integrate( R, ( t, a, b ) ), 3 ) # Round to three decimal places as​ needed.\n\n# Find the number of feet that the tree will grow in the second year.\na, b = 2, 3\nround( integrate( R, ( t, a, b ) ), 3 ) # Round to three decimal places as​ needed.", "meta": {"hexsha": "da036f004c6d9adf040e546d794d1171177ed584", "size": 600, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/PFinal/Q_15.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/PFinal/Q_15.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/PFinal/Q_15.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5, "max_line_length": 95, "alphanum_fraction": 0.6583333333, "include": true, "reason": "from sympy", "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692318706085, "lm_q2_score": 0.8824278618165526, "lm_q1q2_score": 0.861840141981596}}
{"text": "\"\"\"\nLinear least-squares fit.\nFollowing the procedure oulined in Philip R. Bevington, \"Data Reduction and\nError Analysis for the Physical Sciences\" (Third Edition, 2003),\nChapter 7.2, \"Least Squares Fit to a Polynomial - Matrix Solution\"\n\nFriedrich Schotte, 20 May 2008 - 27 Apr 2012\n\"\"\"\n\n__version__ = \"1.3.3\"\n\ndef linear_fit(y,X):\n    \"\"\"Find the optimal solution to the equation y = a*X\n    (Minimize the sum of the squares of the elements of y - a*X).\n    Return a*X.\n    y is usually used to pass experimental data.\n    X is used to pass the fit model. It can be a a set of base functions,\n    evaluated at the point for which the experimental data y is available.\n    X has to be a matrix, y and a can be both vectors or both matrices.\n    \"\"\"\n    from numpy import dot,nan\n\n    # Handle degenerate case by returning NaN rather than throwing an exception.\n    if X.shape[0] == 0: return y+nan\n    \n    a = linear_fit_coeff(y,X)\n    fit = dot(a,X)\n    return fit\n\ndef linear_fit_coeff(y,X):\n    \"\"\"Find the optimal solution to the equation y = a*X\n    (Minimize the sum of the squares of the elements of y - a*X).\n    Return a.\n    y is usually used to pass experimental data.\n    X is used to pass the fit model. It can be a a set of base functions,\n    evaluated at the point for which the experimental data y is available.\n    X has to be a matrix.\n    If y is a vector, the returned coefficients a are a vector.\n    If y is a matrix, the returned coefficients a are a matrix, too.\n    \"\"\"\n    from numpy import nan,dot\n    from numpy.linalg import inv\n\n    alpha = dot(X,X.T)\n    beta = dot(X,y.T)\n    try: epsilon = inv(alpha)\n    except: epsilon = alpha*nan\n    a = dot(epsilon,beta)\n    return a.T\n\ndef weighted_linear_fit(y,w,X):\n    \"\"\"Find the optimal solution to the equation y = a*X\n    (Minimize the sum of the squares of the elements of y - a*X).\n    Return a*X.\n    y is usually used to pass experimental data.\n    w is the weight for each element of y (recommended: 1/sigma**2)\n    X is used to pass the fit model. It can be a a set of base functions,\n    evaluated at the point for which the experimental data y is available.\n    X has to be a matrix, y and a can be both vectors or both matrices.\n    \"\"\"\n    from numpy import dot,nan\n    \n    # Handle degenerate case by returning NaN rather than throwing an exception.\n    if X.shape[0] == 0: return y+nan\n    \n    a = weighted_linear_fit_coeff(y,w,X)\n    fit = dot(a,X)\n    return fit\n\ndef weighted_linear_fit_coeff(y,w,X):\n    \"\"\"Find the optimal solution to the equation y = a*X\n    (Minimize the sum of the squares of the elements of y - a*X).\n    Return a.\n    y is usually used to pass experimental data.\n    w is the weight for each element of y (recommended: 1/sigma**2)\n    X is used to pass the fit model. It can be a a set of base functions,\n    evaluated at the point for which the experimental data y is available.\n    X has to be a matrix.\n    If y and sigma is are vectors, the returned coefficients a are a vector.\n    If y and sigma is are matrices, the returned coefficients a are a matrix.\n    \"\"\"\n    from numpy import where,isnan,nan,dot,array\n    from numpy.linalg import inv\n\n    # 'y's that are NaNs should have zero weight.\n    w = where(isnan(y),0,w)\n    y = where(isnan(y),0,y)\n    # Ignore NaNs in 'y' if weight is zero.\n    y = where((w==0) & isnan(y),0,y)\n\n    if y.ndim == 1:\n        alpha = dot(w * X,X.T)\n        beta = dot(X,(w * y).T)\n        try: epsilon = inv(alpha)\n        except: epsilon = alpha*nan\n        a = dot(epsilon,beta)\n        return a.T\n    else:\n        return array([weighted_linear_fit_coeff(y[i],w[i],X)\n            for i in range(0,len(y))])\n\nif __name__ == \"__main__\": # Example for testing\n    from time import clock\n    from numpy import *\n\n    N = 5\n    x = arange(0.0,2.001*pi,2*pi/(N-1))\n    y1 = 1 + 0.1*sin(x) + 0.01*cos(2*x)\n    y2 = 2 + 0.2*sin(x) + 0.02*cos(2*x)\n    y = array([y1,y2])\n    sigma = sqrt(y)\n\n    # Basis vectors\n    X0 = 1 + 0*x\n    X1 = sin(x)\n    X2 = cos(2*x)\n    X = array([X0,X1,X2])\n\n    ##fit = linear_fit(y,X)\n    fit = weighted_linear_fit(y,1/sigma**2,X)\n    print \"expecting:\",y[:5]\n    print \"result:\",fit[:5]\n    print \"fit residual RMS\",std(y-fit)\n    ##a = linear_fit_coeff(y,X)\n    a = weighted_linear_fit_coeff(y,1/sigma**2,X)\n    print \"fit residual RMS\",std(y - matrix(a)*matrix(X))\n", "meta": {"hexsha": "d3b0fab5c49738b39d048c573277dfd2613d9af8", "size": 4359, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_fit.py", "max_stars_repo_name": "bopopescu/Lauecollect", "max_stars_repo_head_hexsha": "60ae2b05ea8596ba0decf426e37aeaca0bc8b6be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_fit.py", "max_issues_repo_name": "bopopescu/Lauecollect", "max_issues_repo_head_hexsha": "60ae2b05ea8596ba0decf426e37aeaca0bc8b6be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-22T21:28:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-22T21:39:12.000Z", "max_forks_repo_path": "linear_fit.py", "max_forks_repo_name": "bopopescu/Lauecollect", "max_forks_repo_head_hexsha": "60ae2b05ea8596ba0decf426e37aeaca0bc8b6be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-06-06T15:06:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:03:22.000Z", "avg_line_length": 34.3228346457, "max_line_length": 80, "alphanum_fraction": 0.6455609085, "include": true, "reason": "from numpy", "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.9111797118207756, "lm_q1q2_score": 0.8617949315834583}}
{"text": "#! /usr/bin/python\n\n#%%\nimport numpy as np\nfrom scipy.linalg import null_space\nfrom scipy.linalg import lu\nfrom sympy import Matrix\nimport pprint\nA = np.array([\n    [1, 2],\n    [3, 6]\n    ])\nns_a = null_space(A)\nprint(ns_a)\n#%%\nB = np.array([\n    [1, 2, 3]\n    ])\nns_b = null_space(B)\nprint(ns_b)\n\nmx = Matrix(A)\nprint(mx.rref())\n\nP, L, U = lu(A)\npprint.pprint(L)\npprint.pprint(U)\npprint.pprint(P)\npprint.pprint(P@L@U)\n", "meta": {"hexsha": "1569065896fa681070635fb8fef78ee43dfb55d2", "size": 419, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/test.py", "max_stars_repo_name": "jthree1989/algorithm-field", "max_stars_repo_head_hexsha": "816e1003e9fd1fa3e289e7ef7cca57d51cb2dafd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/test.py", "max_issues_repo_name": "jthree1989/algorithm-field", "max_issues_repo_head_hexsha": "816e1003e9fd1fa3e289e7ef7cca57d51cb2dafd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/test.py", "max_forks_repo_name": "jthree1989/algorithm-field", "max_forks_repo_head_hexsha": "816e1003e9fd1fa3e289e7ef7cca57d51cb2dafd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.9666666667, "max_line_length": 35, "alphanum_fraction": 0.6324582339, "include": true, "reason": "import numpy,from scipy,from sympy", "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211626883622, "lm_q2_score": 0.8840392924390585, "lm_q1q2_score": 0.86178021091764}}
{"text": "#setup: N = 10000 ; import numpy as np ; np.random.seed(0); t0, p0, t1, p1 = np.random.randn(N), np.random.randn(N), np.random.randn(N), np.random.randn(N)\n#run: arc_distance(t0, p0, t1, p1)\n\n#pythran export arc_distance(float64 [], float64[], float64[], float64[])\n\nimport numpy as np\ndef arc_distance(theta_1, phi_1,\n                       theta_2, phi_2):\n    \"\"\"\n    Calculates the pairwise arc distance between all points in vector a and b.\n    \"\"\"\n    temp = np.sin((theta_2-theta_1)/2)**2+np.cos(theta_1)*np.cos(theta_2)*np.sin((phi_2-phi_1)/2)**2\n    distance_matrix = 2 * (np.arctan2(np.sqrt(temp),np.sqrt(1-temp)))\n    return distance_matrix\n", "meta": {"hexsha": "f56864050fabced6f7f1b6de9701a5f74c7e2f09", "size": 652, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_benchmarks/benchmarks/arc_distance.py", "max_stars_repo_name": "adriendelsalle/numpy-benchmarks", "max_stars_repo_head_hexsha": "5c09448d045726b347e868756f9e1b004d0876ea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2015-03-18T23:16:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T11:00:01.000Z", "max_issues_repo_path": "numpy_benchmarks/benchmarks/arc_distance.py", "max_issues_repo_name": "adriendelsalle/numpy-benchmarks", "max_issues_repo_head_hexsha": "5c09448d045726b347e868756f9e1b004d0876ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2015-04-17T15:14:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-24T13:34:55.000Z", "max_forks_repo_path": "numpy_benchmarks/benchmarks/arc_distance.py", "max_forks_repo_name": "adriendelsalle/numpy-benchmarks", "max_forks_repo_head_hexsha": "5c09448d045726b347e868756f9e1b004d0876ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-04-17T12:24:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T08:06:01.000Z", "avg_line_length": 43.4666666667, "max_line_length": 155, "alphanum_fraction": 0.6549079755, "include": true, "reason": "import numpy", "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97482115683641, "lm_q2_score": 0.8840392802184581, "lm_q1q2_score": 0.8617801938313846}}
{"text": "# Importing numpy to calculate mean, standard deviation, get arrays from numpy array i.e. matrix columns\nimport numpy as np\n# importing csv module to read the given input csv file\nimport csv\n# Opening file in read mode\ninput_csv=open(\"input2.csv\",\"r\")\n# Getting the input csv text content\ninput_csv_text=csv.reader(input_csv)\n# Converting csv object into list\ninput_data = list(input_csv_text)\n# Given alpha values and +1 free value i.e. 0.8\nalpha_vals =  [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 0.8]\n# Converting inpur list of lists to numpy array\ninput_data_arr = np.array(input_data)\n# Retrieving label - y height\ny_height = input_data_arr[:,2]\n# Converting string to float using list comprehensions\ny_height = [float(el) for el in y_height]\n# Retrieving feature - x age\nx_age = input_data_arr[:,0]\nx_age = [float(el) for el in x_age]\n# Calculating mean and standard deviataion to get the scaled values of features\nx_age_mean = np.mean(x_age)\nx_age_std = np.std(x_age)\n# Calculating scaled values\nx_age_scaled = [(el - x_age_mean)/x_age_std for el in x_age]\n# Performing same as above for feature - x weight\nx_weight = input_data_arr[:,1]\nx_weight = [float(el) for el in x_weight]\nx_weight_mean = np.mean(x_weight)\nx_weight_std = np.std(x_weight)\nx_weight_scaled = [(el - x_weight_mean)/x_weight_std for el in x_weight]\nprint_list = []\n# Looping through alpha vals \nfor alpha in alpha_vals:\n    # initializing intercept b_0, other weights to 0\n    b_0, b_age, b_weight = 0, 0, 0\n    # Iterating for 100 times\n    for _ in range(100):\n        # Adjusting values of weights as per the formula.\n        common_list = [(b_0 + b_age *x_a + b_weight * x_w - y_h)  for x_a, x_w, y_h in zip(x_age_scaled, x_weight_scaled, y_height)]\n        b_0 += -(alpha / len(x_weight_scaled)) * sum(common_list)\n        b_age += -(alpha / len(x_weight_scaled)) * sum([cel*x_a for cel, x_a in zip(common_list, x_age_scaled)])\n        b_weight += -(alpha / len(x_weight_scaled)) * sum([cel*x_w for cel, x_w in zip(common_list, x_weight_scaled)])\n    # Adding weights to print list\n    print_list.append([alpha, 100, b_0, b_age, b_weight])\ninput_csv.close()\n# Writing the weights to output csv file.\noutput_csv=open(\"output2.csv\",\"w\")\nfor el in print_list:\n    output_csv.write(\",\".join([str(ind) for ind in el]))\n    output_csv.write(\"\\n\")\noutput_csv.close()", "meta": {"hexsha": "86e356ec51929502bec5157918d87e57387268ec", "size": 2345, "ext": "py", "lang": "Python", "max_stars_repo_path": "edx/projects/linear_regression/problem2_3.py", "max_stars_repo_name": "pk-ai/ml-challenges", "max_stars_repo_head_hexsha": "207de41067bd290dc46799496aa4e86882a6ced3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-09-01T17:36:06.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-01T17:36:06.000Z", "max_issues_repo_path": "edx/projects/linear_regression/problem2_3.py", "max_issues_repo_name": "pktippa/ml-challenges", "max_issues_repo_head_hexsha": "207de41067bd290dc46799496aa4e86882a6ced3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "edx/projects/linear_regression/problem2_3.py", "max_forks_repo_name": "pktippa/ml-challenges", "max_forks_repo_head_hexsha": "207de41067bd290dc46799496aa4e86882a6ced3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2452830189, "max_line_length": 132, "alphanum_fraction": 0.7215351812, "include": true, "reason": "import numpy,from numpy", "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338079816758, "lm_q2_score": 0.8962513800615313, "lm_q1q2_score": 0.8617760023793963}}
{"text": "from abc import abstractmethod\nfrom math import exp\n\nimport numpy as np\n\n\nclass ActivationFunction:\n    def __init__(self):\n        pass\n\n    @staticmethod\n    def determine_function(func_str):\n        return_function = None\n        if func_str.lower() == 'sigmoid':\n            return_function = SigmoidFunction()\n        elif func_str.lower() == 'tanh':\n            return_function = TanhFunction()\n        elif func_str.lower() == 'softmax':\n            return_function = SoftmaxFunction()\n\n        return return_function\n\n    @abstractmethod\n    def activate(self, value):\n        pass\n\n\nclass SigmoidFunction(ActivationFunction):\n    def __init__(self):\n        super().__init__()\n\n    def activate(self, val):\n        \"\"\"\n            https://machinelearningmastery.com/choose-an-activation-function-for-deep-learning/\n            :param val:\n            :return:\n        \"\"\"\n        return 1.0 / (1.0 + exp(-val))\n\n\nclass TanhFunction(ActivationFunction):\n    def __init__(self):\n        super().__init__()\n\n    def activate(self, val):\n        \"\"\"\n            https://machinelearningmastery.com/choose-an-activation-function-for-deep-learning/\n            :param val:\n            :return:\n                \"\"\"\n        return (exp(val) - exp(-val)) / (exp(val) + exp(-val))\n\n\nclass SoftmaxFunction(ActivationFunction):\n    def __init__(self):\n        super().__init__()\n\n    def activate(self, val):\n        \"\"\"\n            https://medium.com/data-science-bootcamp/understand-the-softmax-function-in-minutes-f3a59641e86d\n            Compute softmax values for each sets of scores in x.\n        \"\"\"\n        return np.exp(val) / np.sum(np.exp(val), axis=0)\n", "meta": {"hexsha": "ccb85aebbf37469dbd36dd95bce00426be7ae085", "size": 1660, "ext": "py", "lang": "Python", "max_stars_repo_path": "functions.py", "max_stars_repo_name": "azizkandemir/MLP-Backpropagation", "max_stars_repo_head_hexsha": "f3d3c7ab45c5a07f7e0beb5c1836edada04c210d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions.py", "max_issues_repo_name": "azizkandemir/MLP-Backpropagation", "max_issues_repo_head_hexsha": "f3d3c7ab45c5a07f7e0beb5c1836edada04c210d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions.py", "max_forks_repo_name": "azizkandemir/MLP-Backpropagation", "max_forks_repo_head_hexsha": "f3d3c7ab45c5a07f7e0beb5c1836edada04c210d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9375, "max_line_length": 108, "alphanum_fraction": 0.5993975904, "include": true, "reason": "import numpy", "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846640860382, "lm_q2_score": 0.8807970889295664, "lm_q1q2_score": 0.8617583639803141}}
{"text": "from math import sqrt\r\nimport numpy as np\r\n\r\n\r\ndef rms_error(base_curve, fitted_curve):\r\n    error = base_curve - fitted_curve\r\n    return np.sqrt(np.mean(error ** 2))\r\n\r\n\r\ndef nrms_error(base_curve, fitted_curve, method=\"mean\"):\r\n\r\n    if method == \"mean\":\r\n        Norm = np.mean(base_curve)\r\n    elif method == \"range\":\r\n        Norm = np.max(base_curve) - np.min(base_curve)\r\n    elif method == \"std\":\r\n        Norm = np.std(base_curve)\r\n    elif method == \"absmax\":\r\n        Norm = np.max((abs(np.max(base_curve)), abs(np.min(base_curve))))\r\n\r\n    if Norm != 0.0:\r\n        error = base_curve - fitted_curve\r\n        return np.sqrt(np.mean((error / Norm) ** 2))\r\n\r\n    else:\r\n        raise NotImplementedError\r\n\r\n\r\ndef mae_error(base_curve, fitted_curve):\r\n    abs_error = np.abs(base_curve - fitted_curve)\r\n    return np.mean(abs_error)\r\n\r\n\r\ndef L2_norm(vector):\r\n    return np.sqrt(np.sum(vector ** 2.0))\r\n\r\n\r\ndef p_norm(vector, p):\r\n\r\n    if p < 1.0:\r\n        print(\" p must be greater or equal to 1. Stopping...\")\r\n        exit()\r\n\r\n    return np.sum(np.abs(vector) ** p) ** (1.0 / p)\r\n\r\n\r\ndef mape_error(base_curve, fitted_curve):\r\n    \"\"\"\tThe mean absolute percentage error (MAPE)\"\"\"\r\n    if 0 not in base_curve:\r\n        Normed_error = (base_curve - fitted_curve) / base_curve\r\n        return np.mean(Normed_error)\r\n    else:\r\n        raise ValueError\r\n", "meta": {"hexsha": "6a8ce348ddeabfbed0dba511d5b6b8352623a1b9", "size": 1364, "ext": "py", "lang": "Python", "max_stars_repo_path": "yamate/utils/errors.py", "max_stars_repo_name": "WRupp/yamate", "max_stars_repo_head_hexsha": "e63d334a418259919a6fbd6baf0163e967c52618", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "yamate/utils/errors.py", "max_issues_repo_name": "WRupp/yamate", "max_issues_repo_head_hexsha": "e63d334a418259919a6fbd6baf0163e967c52618", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "yamate/utils/errors.py", "max_forks_repo_name": "WRupp/yamate", "max_forks_repo_head_hexsha": "e63d334a418259919a6fbd6baf0163e967c52618", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2592592593, "max_line_length": 74, "alphanum_fraction": 0.6026392962, "include": true, "reason": "import numpy", "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.978384668497878, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.861758349497747}}
{"text": "print(\"-----------------LU-Decomposition-------------------\")\r\n\r\nimport numpy as np\r\n'''\r\n\r\n###Important note:::: when you change the matrix from another matrix then also change 'c'(which is 'b') vector\r\n#which is defined later, after creating upper triangular matrix.\r\n\r\n\r\na=np.array([[20,15,10],\r\n            [-3,-2.249,7],\r\n            [5,1,3]],float)\r\nb=np.array([45,1.751,9],float)\r\n'''\r\na=np.array([[25,5,1],\r\n            [64,8,1],\r\n            [144,12,1]],float)\r\nb=np.array([106.8,177.2,279.2],float)\r\n\r\nn =len(b)\r\nz=np.zeros(n,float)\r\nx= np.zeros(n,float)  ## solution vector\r\nL=np.eye(n,n)  ## creating identity matrix\r\n# print(L)\r\n\r\n\r\n### Partial Pivoting\r\nfor k in range(n-1):\r\n    if abs(a[k,k])<1.0e-10:\r\n        for j in range(k+1,n):\r\n            if abs(a[j,k])>abs(a[k,k]):\r\n                a[[j,k]]=a[[k,j]]\r\n                b[[j,k]]=b[[k,j]]\r\n                break\r\n\r\n#Elimination:\r\n\r\n            ## creating upper(U) and lower triangular(L) matrices----------->\r\n    for i in range(k+1,n):\r\n        if a[i,k]==0:\r\n            continue\r\n\r\n        factor = a[i,k]/a[k,k] ## creating factor so that we can create a upper triangular matrix\r\n        L[i,k]=factor  ## creating lower triangular matrix\r\n\r\n        for j in range(k,n):\r\n            a[i,j]= a[i,j]- a[k,j]*factor\r\n        # b[i]=b[k]-b[i]*factor\r\n## upper triangular matrix U\r\n#print(\"--------------------------------------------\")\r\nU=a\r\n\r\nprint(\"Upper triangular matrix is U: \")\r\nprint(U)\r\n\r\nprint(\"--------------------------------------------\")\r\nprint(\"Lower Triangular matrix is L: \")\r\nprint(L)\r\n\r\n\r\nc=np.array([106.8,177.2,279.2],float)\r\nprint(\"\\n\")\r\n## here I am creating the same vector b with\r\n#  different name because we changed above the b vector.\r\nprint(\"--------------------------------------------\")\r\n\r\n### upper triangular matrix\r\n## Forward Substitution\r\nz[0]=b[0]/L[0,0]  ## or z[0]=b[0] because L[0,0]=1\r\n# print(z)\r\nfor i in range(1,n):\r\n    sum_Lz=0\r\n    for m in range(0,i):\r\n        sum_Lz+=L[i,m]*z[m]\r\n        # print(sum_Lz)\r\n    z[i]=(c[i]-sum_Lz)/L[i,i]  ##L[i,i]=1\r\nprint(\"z vector from forward substitution: \")\r\nprint(\"z := \",z)\r\n\r\nprint(\"\\n\")\r\nprint(\"------------------Solution vector from LU-Decomposition--------------------------\")\r\n\r\n## Back-Substitution on upper triangular matrix to get solution vector\r\n## here z vector will be used as constant Right hand vector\r\nx[n-1]= z[n-1]/U[n-1,n-1]\r\nfor i in range(n-2,-1,-1):\r\n    sum_Ux=0\r\n    for j in range(i+1,n):\r\n        sum_Ux+=U[i,j]*x[j]\r\n    x[i]=(z[i]-sum_Ux)/U[i,i]\r\n\r\nprint(\"\\n\")\r\n\r\nprint(\"The value of solution vector is: \")\r\nprint(\"x := \", x)\r\n\r\n\r\n##we can compare this result with Gauss-Elimination method\r\n\r\nprint(\"\\n\")\r\n\r\n\r\nprint(\"------------------ Comparison with Gauss-Elimination Method-----------------\\n\")\r\n\r\n\r\na=np.array([[25,5,1],\r\n        [64,8,1],\r\n        [144,12,1]],float)\r\nb=np.array([106.8,177,279.2],float)\r\n## length of the vector\r\nn= len(b)\r\n# defining zeros to fill the entries of x\r\nx= np.zeros(n,float)\r\n##\r\n\r\n## --------------Partial Pivoting---------------\r\n\r\nfor k in range(n-1):\r\n    if abs(a[k,k])<1.0e-10:\r\n        for i in range(k+1, n):  ### I have to check here what if i take n instead of (n-1), can we interchange the pivot row with the last row.\r\n            if abs(a[i,k])> abs(a[k,k]):### it doesn't matter whether we take n or n-1in the previous range\r\n                a[[i,k]]=a[[k,i]]\r\n                b[[k,i]]=b[[i,k]]\r\n                break\r\n\r\n\r\n    # Elimination---->\r\n### note: here I am using different  factor than I used in gauss Elimination method (factor= a[i,k]/a[k,k])\r\n    #for k in range(n-1):\r\n    for i in range(k+1,n):\r\n        if a[i,k]==0:\r\n            continue\r\n        factor= a[i,k]/a[k,k]\r\n        for j in range(k,n):\r\n            a[i,j]= a[i,j]- a[k,j]*factor\r\n        b[i]=b[i]-b[k]*factor\r\n# print(a)\r\n## back-Substitution---->\r\n\r\nx[n-1]= b[n-1]/a[n-1,n-1]\r\nfor i in range(n-2,-1,-1):\r\n    sum_ax=0\r\n    for j in range(i+1,n):\r\n        sum_ax+=a[i,j]*x[j]\r\n    x[i]= (b[i]-sum_ax)/a[i,i]\r\n\r\nprint(\"x:= \", x)", "meta": {"hexsha": "759756466b1dd72420067c9be135b9ed11fdc1ad", "size": 4045, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numerical_Methods_Physics/LU_Decomposition.py", "max_stars_repo_name": "Simba2805/Computational_Physics_Python", "max_stars_repo_head_hexsha": "be687939c16a1d08066939830ac31ba666a3e1bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numerical_Methods_Physics/LU_Decomposition.py", "max_issues_repo_name": "Simba2805/Computational_Physics_Python", "max_issues_repo_head_hexsha": "be687939c16a1d08066939830ac31ba666a3e1bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numerical_Methods_Physics/LU_Decomposition.py", "max_forks_repo_name": "Simba2805/Computational_Physics_Python", "max_forks_repo_head_hexsha": "be687939c16a1d08066939830ac31ba666a3e1bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5170068027, "max_line_length": 145, "alphanum_fraction": 0.5033374536, "include": true, "reason": "import numpy", "num_tokens": 1173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422255326288, "lm_q2_score": 0.9059898273638386, "lm_q1q2_score": 0.8617251807087636}}
{"text": "#!/usr/bin/env python3\n# coding=utf-8\n\nimport numpy as np\n\ndef get_e(n):\n    e = np.zeros((1,n))\n    e[0,0] = 1\n    return e\n\ndef get_alfa(A,j):\n    alfa = np.array([])\n    for i in range (1,len(A),1):\n        alfa = np.append(alfa,A[i,j])\n    return alfa\n\ndef get_delta(A):\n    return (A[1,0]/abs(A[1,0]))\n\ndef norm(A):\n    x=0\n    for i in range (len(A)):\n        x=x+(A[i]**2)\n    x = np.sqrt(x)\n    return x\n\ndef get_wi(A):\n    ai = np.array([])\n    ai = np.append(ai,get_alfa(A,0))\n    n = len(ai)\n    wi = ai+(get_delta(A)*norm(ai)*get_e(n))\n    return wi\n\ndef householder_algorithm(A,debug = False):\n    get_hwi_x = lambda w,x: (x - (2*(np.inner(w,x)/np.inner(w,w))*w))\n    A = A.copy()\n    n = len(A)\n    new_A = np.zeros((n,n))\n    for i in range(0,n-2):\n        m = len(A)\n        wi = get_wi(A)\n        for j in range(0,m):\n            A[1:m,j] = get_hwi_x(wi,get_alfa(A,j))\n        for j in range(0,m):\n            A[j,1:m] = get_hwi_x(wi,get_alfa(np.transpose(A),j))\n        new_A[i:n,i:n] = A\n        A = np.delete(A,0,0)\n        A = np.delete(A,0,1)\n    new_A[n-2:n,n-2:n] = A\n    if(debug==True):\n        print(\"new_A = \\n\",np.matrix.round(new_A,4),\"\\n\")\n    return new_A\n\ndef test_wi(A):\n    alfa = get_alfa(A,1)\n    wi = get_wi(A)\n    y = alfa - (2*(np.inner(wi,alfa)/np.inner(wi,wi))*wi)\n    print(\"wi =\",y)\n\ndef test_householder_algorithm():\n    A = np.array([[2,-1,1,3],\n                  [-1,1,4,2],\n                  [1,4,2,-1],\n                  [3,2,-1,1]], dtype=float)\n    householder_algorithm(A,debug=True)\n\ndef main():\n    print(\"Execução da função test_wi(A)\")\n    A = np.array([[2,-1,1,3],\n                  [-1,1,4,2],\n                  [1,4,2,-1],\n                  [3,2,-1,1]], dtype=float)\n    test_wi(A)\n    print(\"\\n Execução da função test_householder_algorithm()\")\n    test_householder_algorithm()\n\nif __name__ == \"__main__\":\n    try:\n        main()\n\n    except KeyboardInterrupt:\n        print(\"\\n Better luck next time\")\n", "meta": {"hexsha": "cf8db00f3b6fa4465f703180f33e44da257743d6", "size": 1963, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/ep2/householder_method/householder_algorithm.py", "max_stars_repo_name": "VanderSant/MAP3121_Calculo_Numerico", "max_stars_repo_head_hexsha": "ac663f277409eda41942ce8513c49c2591532148", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-30T14:03:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T14:03:19.000Z", "max_issues_repo_path": "src/ep2/householder_method/householder_algorithm.py", "max_issues_repo_name": "VanderSant/MAP3121_Calculo_Numerico", "max_issues_repo_head_hexsha": "ac663f277409eda41942ce8513c49c2591532148", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ep2/householder_method/householder_algorithm.py", "max_forks_repo_name": "VanderSant/MAP3121_Calculo_Numerico", "max_forks_repo_head_hexsha": "ac663f277409eda41942ce8513c49c2591532148", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6506024096, "max_line_length": 69, "alphanum_fraction": 0.5089149261, "include": true, "reason": "import numpy", "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.9059898134030163, "lm_q1q2_score": 0.8617251674300361}}
{"text": "\"\"\"Symmetric projection operator.\"\"\"\nfrom itertools import permutations\n\nimport numpy as np\nimport scipy\n\nfrom toqito.perms import permutation_operator\n\n\ndef symmetric_projection(\n    dim: int, p_val: int = 2, partial: bool = False\n) -> [np.ndarray, scipy.sparse.lil_matrix]:\n    r\"\"\"\n    Produce the projection onto the symmetric subspace [CJKLZ14]_.\n\n    For a complex Euclidean space :math:`\\mathcal{X}` and a positive integer :math:`n`, the\n    projection onto the symmetric subspace is given by\n\n    .. math::\n        \\frac{1}{n!} \\sum_{\\pi \\in S_n} W_{\\pi}\n\n    where :math:`W_{\\pi}` is the swap operator and where :math:`S_n` is the symmetric group on\n    :math:`n` symbols.\n\n    Produces the orthogonal projection onto the symmetric subspace of :code:`p_val` copies of\n    `dim`-dimensional space. If `partial = True`, then the symmetric projection (PS) isn't the\n    orthogonal projection itself, but rather a matrix whose columns form an orthonormal basis for\n    the symmetric subspace (and hence the PS * PS' is the orthogonal projection onto the symmetric\n    subspace).\n\n    This function was adapted from the QETLAB package.\n\n    Examples\n    ==========\n\n    The :math:`2`-dimensional symmetric projection with :math:`p=1` is given as\n    :math:`2`-by-:math:`2` identity matrix\n\n    .. math::\n        \\begin{pmatrix}\n            1 & 0 \\\\\n            0 & 1\n        \\end{pmatrix}.\n\n    Using :code:`toqito`, we can see this gives the proper result.\n\n    >>> from toqito.perms import symmetric_projection\n    >>> symmetric_projection(2, 1).todense()\n    [[1., 0.],\n     [0., 1.]]\n\n    When :math:`d = 2` and :math:`p = 2` we have that\n\n    .. math::\n        \\begin{pmatrix}\n            1 & 0 & 0 & 0 \\\\\n            0 & 1/2 & 1/2 & 0 \\\\\n            0 & 1/2 & 1/2 & 0 \\\\\n            0 & 0 & 0 & 1\n        \\end{pmatrix}.\n\n    Using :code:`toqito` we can see this gives the proper result.\n\n    >>> from toqito.perms import symmetric_projection\n    >>> symmetric_projection(dim=2).todense()\n    [[1. , 0. , 0. , 0. ],\n     [0. , 0.5, 0.5, 0. ],\n     [0. , 0.5, 0.5, 0. ],\n     [0. , 0. , 0. , 1. ]]\n\n    References\n    ==========\n     .. [CJKLZ14] J. Chen, Z. Ji, D. Kribs, N. Lütkenhaus, and B. Zeng.\n        \"Symmetric extension of two-qubit states\".\n        Physical Review A 90.3 (2014): 032318.\n        https://arxiv.org/abs/1310.3530\n        E-print: arXiv:1310.3530 [quant-ph]\n\n    :param dim: The dimension of the local systems.\n    :param p_val: Default value of 2.\n    :param partial: Default value of 0.\n    :return: Projection onto the symmetric subspace.\n    \"\"\"\n    dimp = dim ** p_val\n\n    if p_val == 1:\n        return np.eye(dim)\n\n    p_list = np.array(list(permutations(np.arange(1, p_val + 1))))\n    p_fac = np.math.factorial(p_val)\n    sym_proj = np.zeros((dimp, dimp))\n\n    for j in range(p_fac):\n        sym_proj += permutation_operator(dim * np.ones(p_val), p_list[j, :], False, True)\n    sym_proj = sym_proj / p_fac\n\n    if partial:\n        sym_proj = scipy.linalg.orth(sym_proj)\n    return sym_proj\n", "meta": {"hexsha": "1d76226a3e89b19b7100e252fba12dfbb93f8bc3", "size": 3031, "ext": "py", "lang": "Python", "max_stars_repo_path": "toqito/perms/symmetric_projection.py", "max_stars_repo_name": "paniash/toqito", "max_stars_repo_head_hexsha": "ab67c2a3fca77b3827be11d1e79531042ea62b82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2020-01-28T17:02:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T18:02:15.000Z", "max_issues_repo_path": "toqito/perms/symmetric_projection.py", "max_issues_repo_name": "paniash/toqito", "max_issues_repo_head_hexsha": "ab67c2a3fca77b3827be11d1e79531042ea62b82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 82, "max_issues_repo_issues_event_min_datetime": "2020-05-31T20:09:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:13:59.000Z", "max_forks_repo_path": "toqito/perms/symmetric_projection.py", "max_forks_repo_name": "paniash/toqito", "max_forks_repo_head_hexsha": "ab67c2a3fca77b3827be11d1e79531042ea62b82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2020-04-02T16:07:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T13:39:22.000Z", "avg_line_length": 30.31, "max_line_length": 98, "alphanum_fraction": 0.6070603761, "include": true, "reason": "import numpy,import scipy", "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182844, "lm_q2_score": 0.903294216466424, "lm_q1q2_score": 0.8617120610322054}}
{"text": "from sympy import *\n\nx = symbols('x')\ninit_printing(use_unicode=True)\n\nf=Lambda(x, x*cos(x)-x**2*sin(x))\ng=Lambda(x, diff(f(x),x))\n\n# Progresiva\n#f'(c)= (-3f(c)+4f(c+h)-f(c+2h))/2h\ndef fdn1(c, h, valores):\n    return (-3*valores[c]+4*valores[c+h]-valores[c+2*h])/(2*h)\n    #return (-3*valores[round(c,1)]+4*valores[round(c+h,1)]-valores[round(c+2*h,1)])/(2*h)\n\n# Central\n#f'(c)= (f(c+h)-f(fc-h))/2h\ndef fdn2(c, h, valores):\n    return (valores[c+h]-valores[c-h])/(2*h)\n\n# Regresiva\n#f'(c)= (-f(c-2h)+4f(c-h)-3f(c))/2h\ndef fdn3(c, h, valores):\n    return (valores[c-2*h]-4*valores[c-h]+3*valores[c])/(2*h)\n    #return (valores[round(c-2*h,1)]-4*valores[round(c-h,1)]+3*valores[round(c)])/(2*h)\n\nvalores=dict({(2.9,-4.827866), (3.0,-4.240058), (3.1,-3.496909), (3.2,-2.596792)})\n\nh=0.1\na=2.9\n\nc=a+0*h\nprint(\"c=\",c)\n\nprint(\"Progresiva:\")\nfdn1c=fdn1(c, h, valores)\nprint(\"FDN1: f'(c)=\", fdn1c)\nprint(\"Error FDN1:\", abs(fdn1c-g(c)))\n\nc=a+1*h\nprint(\"c=\",c)\n\nprint(\"Progresiva:\")\nfdn1c=fdn1(c, h, valores)\nprint(\"FDN1: f'(\"+str(c)+\")=\", fdn1c)\nprint(\"Error FDN1:\", abs(fdn1c-g(c)))\n\nprint(\"Central:\")\nfdn2c=fdn2(c, h, valores)\nprint(\"FDN2: f'(\"+str(c)+\")=\", fdn2c)\nprint(\"Error FDN2:\", abs(fdn2c-g(c)))\n\nc=a+2*h\nprint(\"c=\",c)\n\nprint(\"Central:\")\nfdn2c=fdn2(c, h, valores)\nprint(\"FDN2: f'(\"+str(c)+\")=\", fdn2c)\nprint(\"Error FDN2:\", abs(fdn2c-g(c)))\n\nprint(\"Regresiva:\")\nfdn3c=fdn3(c, h, valores)\nprint(\"FDN3: f'(\"+str(c)+\")=\", fdn3c)\nprint(\"Error FDN3:\", abs(fdn3c-g(c)))\n\nc=a+3*h\nprint(\"c=\",c)\n\nprint(\"Regresiva:\")\nfdn3c=fdn3(c, h, valores)\nprint(\"FDN3: f'(\"+str(c)+\")=\", fdn3c)\nprint(\"Error FDN3:\", abs(fdn3c-g(c)))\n", "meta": {"hexsha": "f9a7d8e9419d9ab7b6521858713e76a3d63376a9", "size": 1609, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tema2/FDN_interpolatorio_3_nodos.py", "max_stars_repo_name": "dcabezas98/MNII", "max_stars_repo_head_hexsha": "123dfd7f19cb06e7d8db9e0865db624988a6f88b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tema2/FDN_interpolatorio_3_nodos.py", "max_issues_repo_name": "dcabezas98/MNII", "max_issues_repo_head_hexsha": "123dfd7f19cb06e7d8db9e0865db624988a6f88b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tema2/FDN_interpolatorio_3_nodos.py", "max_forks_repo_name": "dcabezas98/MNII", "max_forks_repo_head_hexsha": "123dfd7f19cb06e7d8db9e0865db624988a6f88b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3472222222, "max_line_length": 90, "alphanum_fraction": 0.5916718459, "include": true, "reason": "from sympy", "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966101527047, "lm_q2_score": 0.9032942021480236, "lm_q1q2_score": 0.8617120485551344}}
{"text": "\"\"\"\nIn Ternary Search we divide 3 times on every iteration.\nIt might be better than BInary Search in some cases, but\nin worst case scenario it involves more comparisons than\nBinary Search and that is why the latter one is preferred.\n\nTime Complexity for Binary search = 2clog2n + O(1)\nTime Complexity for Ternary search = 4clog3n + O(1)\n\nThe following is recursive formula for counting \ncomparisons in worst case of Binary Search.\n\n   T(n) = T(n/2) + 2,  T(1) = 1\n\nThe following is recursive formula for counting \ncomparisons in worst case of Ternary Search.\n\n   T(n) = T(n/3) + 4, T(1) = 1\n\"\"\"\nimport numpy as np\nimport time\nfrom rich import print as rprint \n\n\ndef search(array, left, right, query):\n\tif right >= left:\n\t\tmid1 = left + (right - left) // 3\n\t\tmid2 = mid1 + (right - left) // 3\n\t\tif array[mid1] == query:\n\t\t\treturn mid1\n\n\t\tif array[mid2] == query:\n\t\t\treturn mid2\n\n\t\tif array[mid1] > query:\n\t\t\treturn search(array, left, mid1 - 1, query)\n\n\t\tif array[mid2] < query:\n\t\t\treturn search(array, mid2 + 1, right, query)\n\n\t\treturn search(array, mid1 + 1, mid2 - 1, query)\t\n\treturn -1\n\n\ndef main():\n\tarray = np.arange(1, 9999999, 1)\n\tquery = np.random.randint(1, 9999999)\n\tsize = len(array)\n\tstart_time = time.time()\n\tresult = search(array=array, left=0, right=size - 1, query=query)\n\tstop_time = time.time()\n\tif result == -1:\n\t\trprint(\"[red]Element {} is not present in the array.\".format(query))\n\telse:\n\t\trprint(\"[green]ELement[/green] {} [green]found in the array at index:[/green] {}\".format(query, result))\n\trprint(\"[yellow]Total time taken:\", stop_time - start_time, \"[yellow]seconds.\")\n\n\nif __name__ == \"__main__\":\n\tmain()", "meta": {"hexsha": "1382231bde681b0b67f1b68936f62d35b728ae43", "size": 1633, "ext": "py", "lang": "Python", "max_stars_repo_path": "searching/ternary_search.py", "max_stars_repo_name": "Yasir323/Data-Structures-and-Algorithms-in-Python", "max_stars_repo_head_hexsha": "b721d0ca0218b9665d4f6ca0bbfd4417244bcdf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "searching/ternary_search.py", "max_issues_repo_name": "Yasir323/Data-Structures-and-Algorithms-in-Python", "max_issues_repo_head_hexsha": "b721d0ca0218b9665d4f6ca0bbfd4417244bcdf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "searching/ternary_search.py", "max_forks_repo_name": "Yasir323/Data-Structures-and-Algorithms-in-Python", "max_forks_repo_head_hexsha": "b721d0ca0218b9665d4f6ca0bbfd4417244bcdf0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2166666667, "max_line_length": 106, "alphanum_fraction": 0.6815676669, "include": true, "reason": "import numpy", "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.9184802473724224, "lm_q1q2_score": 0.8616483719317952}}
{"text": "from sympy import *\nimport sys\nsys.path.insert(1, '..')\nfrom quaternion_R_utils import *\n\npx, py, pz = symbols('px py pz')\nq0, q1, q2, q3 = symbols('q0 q1 q2 q3')\ntie_px, tie_py, tie_pz = symbols('tie_px tie_py tie_pz'); \ncols, rows = symbols('cols rows');\npi = symbols('pi')\nu_kp, v_kp = symbols('u_kp v_kp')\n\nposition_symbols = [px, py, pz]\nquaternion_symbols = [q0, q1, q2, q3]\ntie_point_symbols = [tie_px, tie_py, tie_pz]\nall_symbols = position_symbols + quaternion_symbols + tie_point_symbols\n\nRT_wc = matrix44FromQuaternion(px, py, pz, q0, q1, q2, q3)\nr=RT_wc[:-1,:-1]\nt=Matrix([px, py, pz]).vec()\n\npos_w=Matrix([tie_px, tie_py, tie_pz]).vec()\nbearing = r * pos_w + t;\nnorm = sqrt(bearing[0]*bearing[0] + bearing[1]*bearing[1] + bearing[2]*bearing[2])\nbearing=bearing/norm\nlatitude=-asin(bearing[1])\nlongitude=atan2(bearing[0], bearing[2])\n\nu=cols*(0.5 + longitude / (2.0 * pi))\nv=rows*(0.5 - latitude/pi)\nu_delta = u_kp - u;\nv_delta = v_kp - v;\n\nobs_eq = Matrix([u_delta, v_delta]).vec()\nobs_eq_jacobian = obs_eq.jacobian(all_symbols)\n\nprint(obs_eq)\nprint(obs_eq_jacobian)\n\nwith open(\"equirectangular_camera_colinearity_quaternion_wc_jacobian.h\",'w') as f_cpp:  \n    f_cpp.write(\"inline void observation_equation_equrectangular_camera_colinearity_quaternion_wc(Eigen::Matrix<double, 2, 1> &delta, double rows, double cols, double pi, double px, double py, double pz, double q0, double q1, double q2, double q3, double tie_px, double tie_py, double tie_pz, double u_kp, double v_kp)\\n\")\n    f_cpp.write(\"{\")\n    f_cpp.write(\"delta.coeffRef(0,0) = %s;\\n\"%(ccode(obs_eq[0,0])))\n    f_cpp.write(\"delta.coeffRef(1,0) = %s;\\n\"%(ccode(obs_eq[1,0])))\n    f_cpp.write(\"}\")\n    f_cpp.write(\"\\n\")\n    f_cpp.write(\"inline void observation_equation_equrectangular_camera_colinearity_quaternion_wc_jacobian(Eigen::Matrix<double, 2, 10, Eigen::RowMajor> &j, double rows, double cols, double pi, double px, double py, double pz, double q0, double q1, double q2, double q3, double tie_px, double tie_py, double tie_pz, double u_kp, double v_kp)\\n\")\n    f_cpp.write(\"{\")\n    for i in range (2):\n        for j in range (10):\n            f_cpp.write(\"j.coeffRef(%d,%d) = %s;\\n\"%(i,j, ccode(obs_eq_jacobian[i,j])))\n    f_cpp.write(\"}\")\n\n\n\n\n\n\n", "meta": {"hexsha": "ebe6e93c71da149d312d3add2415c296caef23ab", "size": 2228, "ext": "py", "lang": "Python", "max_stars_repo_path": "codes/python-scripts/camera-metrics/equirectangular_camera_colinearity_quaternion_wc_jacobian.py", "max_stars_repo_name": "karolmajek/observation_equations", "max_stars_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-11T13:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T22:04:00.000Z", "max_issues_repo_path": "codes/python-scripts/camera-metrics/equirectangular_camera_colinearity_quaternion_wc_jacobian.py", "max_issues_repo_name": "karolmajek/observation_equations", "max_issues_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/python-scripts/camera-metrics/equirectangular_camera_colinearity_quaternion_wc_jacobian.py", "max_forks_repo_name": "karolmajek/observation_equations", "max_forks_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-30T22:33:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T18:21:21.000Z", "avg_line_length": 37.7627118644, "max_line_length": 345, "alphanum_fraction": 0.6961400359, "include": true, "reason": "from sympy", "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780479, "lm_q2_score": 0.907312221360624, "lm_q1q2_score": 0.8616466220036779}}
{"text": "from numpy.linalg import matrix_rank\nfrom matplotlib import pyplot as plt\nfrom sklearn.datasets import fetch_olivetti_faces\nimport numpy as np\nfrom sklearn.decomposition import PCA\n\n\nnp.random.seed(0)\n# load the faces (value from 0 to 1)\nfaces = fetch_olivetti_faces()\nimg = faces['images']\nX = faces['data']\ntarget = faces['target']\ny = np.ravel(np.repeat(np.arange(1, 41), 10))\n\nh, w, n = 64, 64, len(img)\n\nval = np.random.choice(n, 16, replace=False)\nfig, axs = plt.subplots(4, 4)\nfig.suptitle(\"16 Random Face Images \", fontsize=\"x-large\")\nfor i in range(16):\n    r, c = int(i / 4), i % 4\n    axs[r, c].imshow(X[val[i]].reshape(h, w), cmap='gray')\n    axs[r, c].axis('off')\n\nfig.savefig(\"../figures/PcaTrainFaceImages.png\")\n\nprint('Performing PCA')\nmu = np.mean(X, axis=0)\nXC = X - mu\npca = PCA()\npca.fit(XC)\nV = pca.components_\nZ = np.dot(XC, V.T)\n\nfig, axs = plt.subplots(2, 2)\nfig.suptitle(\"PCA on Face Images (Principle components) \", fontsize=\"x-large\")\nfor i in range(4):\n    r, c = int(i / 2), i % 2\n    if r == 0 and c == 0:\n        # mu plot\n        axs[r, c].imshow(mu.reshape(h, w), cmap='gray')\n        axs[r, c].axis('off')\n        axs[r, c].set_title('Mean')\n    else:\n        # plots the first three Eigenfaces\n        axs[r, c].imshow(V[i - 1].reshape(h, w), cmap='gray')\n        axs[r, c].axis('off')\n        axs[r, c].set_title('principal Basis {}'.format(i - 1))\nfig.savefig(\"../figures/PrincipalComponentFaceImages.png\")\n\nndx = 125\nKs = [5, 10, 20, matrix_rank(X)]\nfig, axs = plt.subplots(2, 2)\nfig.suptitle(\"PCA on Face Images (Reconstructed Images) \", fontsize=\"x-large\")\ncount = 0\nfor k in Ks:\n    Xrecon = np.dot(Z[np.newaxis, ndx, :k], V[:k, :]) + mu\n    r, c = int(count / 2), count % 2\n    axs[r, c].imshow(Xrecon.reshape(64, 64), cmap='gray')\n    axs[r, c].axis('off')\n    axs[r, c].set_title('{} Components'.format(k))\n    count += 1\nfig.savefig(\"../figures/PCAReconstructedFaceImages.png\")\n\n\nfig, axs = plt.subplots(1, 1)\nfig.suptitle(\"PCA on Face Images (ReconstructionError) \", fontsize=\"x-large\")\nKs = []\nKs.extend(list(np.arange(0, 10, 1)))\nKs.extend(list(np.arange(10, 50, 5)))\nKs.extend(list(np.arange(50, matrix_rank(X), 25)))\nmse = np.zeros(len(Ks))\ncount = 0\nfor k in Ks:\n    Xrecon = np.dot(Z[:, :k], V[:k, :]) + mu\n    err = (Xrecon - X)\n    mse[count] = np.sqrt(np.mean(err ** 2))\n    count += 1\n\naxs.plot(Ks, mse, '-o')\naxs.set_ylabel('MSE')\naxs.set_xlabel('K')\nfig.savefig(\"../figures/ReconstructionError.png\")\n\nfig, axs = plt.subplots(1, 1)\nfig.suptitle(\"pcaImage Faces (proportion of variance) \", fontsize=\"x-large\")\n\naxs.plot(np.cumsum(pca.explained_variance_)/np.sum(pca.explained_variance_), 'o-')\naxs.set_ylabel('proportion of variance')\naxs.set_xlabel('K')\nfig.savefig(\"../figures/PCAvariance.png\")\n", "meta": {"hexsha": "69e7a8fcaac635fef43fc93a13f664cf567716c7", "size": 2753, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/pcaImageDemo.py", "max_stars_repo_name": "always-newbie161/pyprobml", "max_stars_repo_head_hexsha": "eb70c84f9618d68235ef9ba7da147c009b2e4a80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-22T05:43:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T08:40:16.000Z", "max_issues_repo_path": "scripts/pcaImageDemo.py", "max_issues_repo_name": "always-newbie161/pyprobml", "max_issues_repo_head_hexsha": "eb70c84f9618d68235ef9ba7da147c009b2e4a80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-22T15:46:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-22T15:46:27.000Z", "max_forks_repo_path": "scripts/pcaImageDemo.py", "max_forks_repo_name": "always-newbie161/pyprobml", "max_forks_repo_head_hexsha": "eb70c84f9618d68235ef9ba7da147c009b2e4a80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-21T01:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T01:18:07.000Z", "avg_line_length": 29.6021505376, "max_line_length": 82, "alphanum_fraction": 0.6382128587, "include": true, "reason": "import numpy,from numpy", "num_tokens": 894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191246389618, "lm_q2_score": 0.90192067257508, "lm_q1q2_score": 0.8616220674182091}}
{"text": "import numpy as np\n\na = np.array([1, 2, 3, 4, 5])\nprint(a)\nprint(a.dtype)\nprint(type(a))\nprint(np.size(a))\n\n# NumPy will try to coerce all the items to the same type.\na2 = np.array([1, 2.2, 3, 4, 5])\nprint(a2)\nprint(a2.dtype)\nprint(type(a2))\nprint(np.size(a2))\n\n\n# shorthand to repeat a sequence 10 times\na3 = np.array([2]*10)\nprint(a3)\n\n\n# convert a python range to numpy array\na4 = np.array(range(5))\nprint(a4)\n\n# To efficiently create an array of a specific size that is initialized with zeros\na5 = np.zeros(5)\nprint(a5)\nprint(a5.dtype)\n\n# with types\na6 = np.zeros(3, dtype=int)\nprint(a6)\nprint(a6.dtype)\n\n#using numpy arange\na7 = np.arange(5, 10)\nprint(a7)\n\na8 = np.arange(0, 10)\na9 = a8 * 2 # multiply a array\nprint(a9)\n\na10 = np.array([1, 2, 3])\na11 = np.array([4, 5, 6])\na12 = a10 + a11 #add two arrays\nprint(a12)\n\na13 = np.array([[1, 2, 3], [4, 5, 6]]) #two dimensional array\nprint(a13)\nprint(a13[0, 2]) #accessing two dimentionsional array\nprint(a13[0,]) #accessing a entire row\nprint(a13[:,1])#accessing a entire column\n\nb = np.array([1, 2, 3, 4, 5])\nprint(b.mean())\nprint(b.max())\nprint(b.min())\nprint(b.std())", "meta": {"hexsha": "758b6b8b6477778e2002842917ef2fcceb1df747", "size": 1121, "ext": "py", "lang": "Python", "max_stars_repo_path": "step02_numpy_for_pandas/main.py", "max_stars_repo_name": "hammadtariq/learn-python-science-libs", "max_stars_repo_head_hexsha": "ebd06a7c5b828390c473c05112c8494d476447ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-04-03T10:33:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-16T00:06:49.000Z", "max_issues_repo_path": "step02_numpy_for_pandas/main.py", "max_issues_repo_name": "panacloud/learn-python-science-libs", "max_issues_repo_head_hexsha": "ebd06a7c5b828390c473c05112c8494d476447ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "step02_numpy_for_pandas/main.py", "max_forks_repo_name": "panacloud/learn-python-science-libs", "max_forks_repo_head_hexsha": "ebd06a7c5b828390c473c05112c8494d476447ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2016-05-19T10:01:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-26T13:45:27.000Z", "avg_line_length": 19.0, "max_line_length": 82, "alphanum_fraction": 0.6601248885, "include": true, "reason": "import numpy", "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368928, "lm_q2_score": 0.9230391653625205, "lm_q1q2_score": 0.861593203573644}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nNumerical integration - Simpson's Rule (3 points quadrature equation)\nRoughly the error of integration can be estimated as ~ h**4  (the global error)\n@author: ssklykov\n\"\"\"\n# %% Import Section\nimport numpy as np\nfrom sampleFunctions import SampleFuncIntegr as sfint\nimport inspect\nimport matplotlib.pyplot as plt\n\n\n# %% Algorithm implementation\ndef SimpsonIntegr(a: float, b: float, h: float, y, nDigits: int = 3):\n    \"\"\"\n    Simpson's Rule Integration implementation\n    Input\n    -----\n    a, b:\n        float [a,b] interval for integration\n    h:\n        float, step size\n    y:\n        float, function or method returning single float number and accepting single float number\n    \"\"\"\n\n    if (a >= b) and (int((b-a)/h) <= 1):\n        print(\"Incosistent interval assigning [a,b] or step size h - a and b exchanged, h - decreased\")\n        holder = b; b = a; a = holder\n        h /= 2\n    if not((inspect.isfunction(y)) or (inspect.ismethod(y))):\n        print(\"Passed function y(x) isn't the defined method or function\")\n        return None  # returning null object instead of any result, even equal to zero\n    else:\n        nPoints = int((b-a)/h) + 1\n        evenSum = 0.0; oddSum = 0.0; intSum = 0.0\n        for i in range(2, nPoints-2, 2):\n            x = a + i*h; evenSum += y(x)\n        for i in range(1, nPoints-1, 2):\n            x = a + i*h; oddSum += y(x)\n        intSum = (h/3)*(y(a) + y(b) + 2*evenSum + 4*oddSum)\n        return round(intSum, nDigits)\n\n\n# %% Adaptive calling of the Simpson's rule(above)\ndef AdaptiveSimpsonInt(a: float, b: float, h: float, y, nDigits: int = 3, epsilon: float = 0.01, nMaxIterations: int = 3):\n    \"\"\"\n    Adaptive calling of Simpson's Rule for numerical integration. Epsilon - difference of two sub\n    sequent calculated integrals (condition for stopping) - absolute error; nMaxIterations - maximum number of iterations\n    of lowering step size h (no more than 30)\n    \"\"\"\n    intSum1 = SimpsonIntegr(a, b, h, y, nDigits*4); h = h/2\n    intSum2 = SimpsonIntegr(a, b, h, y, nDigits*4)  # nDigits should be more  than digits in epsilon!\n    # As described, max int number: 2**32 -1, so it's impossible to make more iterations using nPoints evaluation\n    if (nMaxIterations > 30):\n        print(\"impossible to make so many halving iterations\")\n        nMaxIterations = 30\n    j = 1  # number of iterations\n    while((j < nMaxIterations) and (abs(intSum2-intSum1) > epsilon*intSum2)):  # |I2-I1| <= epsilon*I2 - relative error check\n        intSum1 = intSum2\n        h = h/2\n        intSum2 = SimpsonIntegr(a, b, h, y, nDigits*4)  # nDigits should be more  than digits in epsilon!\n        j += 1\n    print(j, \"number of iterations\")\n    return round(intSum2, nDigits)\n\n# %% Parameters for testing\nnDigits = 2; a = 0; b = 2; nSample = 1; h = 0.05\nfClass = sfint(nDigits, nSample)  # making sample of the class contained the sample function\n# making x and y values for plotting\nnDigits2 = 3; a2 = 0; b2 = 2; h2 = 0.3; epsilon = 1e-4; nMaxIterations = 10\nfClass2 = sfint(nDigits2, nSample)  # using the sample function with a unknown analytical integral form\nnPoints2 = int(50*(b2-a2)/h2) + 1\nx = np.zeros(nPoints2); y = np.zeros(nPoints2)\nfor i in range(nPoints2):\n    x[i] = a + i*(h2/50); y[i] = fClass2.sampleF(x[i])\n# plot sample function from interval [a,b]\nfig = plt.figure(); plt.plot(x,y); plt.grid()\n\n# %% Testing\nintegral = SimpsonIntegr(a, b, h, fClass.sampleF, nDigits)\nprint(integral, \" - calculated integral value for 1st sample f(x)\")\nprint(\"1 - exact value from Newton-Leibniz equation F(b) - F(a)\")  # F(a) = 0; F(b) = 1; F(x) = x^3 - x^2 - 1.5*x\nintegral2 = SimpsonIntegr(a2, b2, h2, fClass2.sampleF, nDigits2)\nprint(integral2, \" - integral value for 1st sample f(x) w/t adaptation\")\nintegral22 = AdaptiveSimpsonInt(a2, b2, h2, fClass2.sampleF, nDigits2, epsilon, nMaxIterations)\nprint(integral22, \" - integral value for 2nd sample f(x) with adaptation\")\n", "meta": {"hexsha": "c9fbbc9c760396391995d8a7c90e46f443c152e8", "size": 3948, "ext": "py", "lang": "Python", "max_stars_repo_path": "Integration/SimpsonRule.py", "max_stars_repo_name": "ssklykov/collection_numCalc", "max_stars_repo_head_hexsha": "f6c69aa582fc811b998a0989b99157b8566c884f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Integration/SimpsonRule.py", "max_issues_repo_name": "ssklykov/collection_numCalc", "max_issues_repo_head_hexsha": "f6c69aa582fc811b998a0989b99157b8566c884f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Integration/SimpsonRule.py", "max_forks_repo_name": "ssklykov/collection_numCalc", "max_forks_repo_head_hexsha": "f6c69aa582fc811b998a0989b99157b8566c884f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3595505618, "max_line_length": 125, "alphanum_fraction": 0.6512158055, "include": true, "reason": "import numpy", "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.9230391643039739, "lm_q1q2_score": 0.8615932008762353}}
{"text": "import numpy as np\n\n\ndef hhi_index(firm_sizes: np.ndarray, weights: np.ndarray = None) -> float:\n    r\"\"\"Herfindahl–Hirschman Index\n\n    A common measure of market concentration, defined as\n\n    $$\n    H = \\sum_{i=1}^{N} s_i^2\n    $$\n\n    where $s_i$ is firm $i$'s market share in the industry of $N$ firms.\n\n    Args:\n        firm_sizes (np.ndarray): (n_firms,) array of firm sizes suchs as sales, used to compute market shares\n        weights (np.ndarray): (n_firms,) array of the weights given to each firm's market share. Defaults to equal weights.\n\n    !!! note\n        If `weights` are provided, the HHI index is computed as:\n\n        $$\n        H = \\sum_{i=1}^{N} s_i^2 \\times w_i\n        $$\n\n        where $w_i$ is the weight given to the market share of firm $i$.\n\n    Returns:\n        float: HHI-index for the industry\n\n    Examples:\n        >>> import numpy as np\n        >>> from frds.measures import hhi_index\n\n        7 firms with equal sales\n        >>> firm_sales = np.array([1,1,1,1,1,1,1])\n        >>> hhi_index(firm_sales)\n        0.14285714285714285\n\n        6 firms, of which 1 has much larger sales\n        >>> firm_sales = np.array([100,1,1,1,1,1])\n        >>> hhi_index(firm_sales)\n        0.9074829931972791\n\n    References:\n        - [Wikipedia](https://en.wikipedia.org/wiki/Herfindahl%E2%80%93Hirschman_Index)\n\n    Todo:\n        - [ ] Allow `firm_sizes` to be multidimensional.\n        - [ ] Check validity of input data (no negative firm sizes, etc.).\n        - [x] Allow market shares to be weighted.\n    \"\"\"\n    if weights is None:\n        weights = np.ones(firm_sizes.shape)\n    mkt_shares = firm_sizes / np.sum(firm_sizes)\n    return np.sum(np.square(mkt_shares) * weights)\n", "meta": {"hexsha": "94d0ac68d3ef0ea4db8f0ab0c9e5bb006a7cb9f6", "size": 1707, "ext": "py", "lang": "Python", "max_stars_repo_path": "frds/measures/func_hhi_index.py", "max_stars_repo_name": "mgao6767/wrds", "max_stars_repo_head_hexsha": "7dca2651a181bf38c61ebde675c9f64d6c96f608", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2020-06-17T13:19:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T08:56:38.000Z", "max_issues_repo_path": "frds/measures/func_hhi_index.py", "max_issues_repo_name": "mgao6767/wrds", "max_issues_repo_head_hexsha": "7dca2651a181bf38c61ebde675c9f64d6c96f608", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "frds/measures/func_hhi_index.py", "max_forks_repo_name": "mgao6767/wrds", "max_forks_repo_head_hexsha": "7dca2651a181bf38c61ebde675c9f64d6c96f608", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-06-14T15:21:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T06:28:53.000Z", "avg_line_length": 29.9473684211, "max_line_length": 123, "alphanum_fraction": 0.6151142355, "include": true, "reason": "import numpy", "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290963960278, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.86159018817417}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n@author: vladimirnesterov\nExamples for ten little algorithms\n(Ten Little Algorithms by Jason Sachs from here https://www.embeddedrelated.com/showarticle/760.php)\n\"\"\"\n\nimport ten_little_algorithms as tla\n\nprint(\"\")\nprint(\"  --- ----------------------- *** ----------------------- ---  \")\nprint(\"   Euclidean Algorithm to find greatest common divider (GCD)   \")\nprint(\"\")\nfrom math import gcd\na=1071\nb=462\nprint(\"Python gcd function gcd(\", a,\",\", b, \") =\",gcd(a,b))\nprint(\"Euclidean algorithm gcd(\", a,\",\", b, \") =\",tla.euclidean_gcd(a,b))\nprint(\"\")\n\nprint(\"  --- ----------------------- *** ----------------------- ---   \")\nprint(\" Extended Euclidean Algorithm to find GCD and Bézout's identity \")\nprint(\"\")\na=462\nb=1071\ngdc,x,y = tla.euclidean_ext_gcd(a,b)\nprint(\"Euclidean algorithm gcd(\", a,\",\", b, \") =\",gdc)\nprint(\"Coefficients of Bézout's identity:\",x, \"and\", y)\nprint(\"such that \",a, \"*\", x, \"+\", b, \"*\", y, \"=\", a*x+b*y)\nprint(\"\")\n\nprint(\"  --- ----------------------- *** ----------------------- ---  \")\nprint(\"              Newton's method for finding roots                \")\nprint(\"\")\nfrom scipy import optimize\n\ndef f(x: float) -> float:\n    return x**2 - 20 * x + 5\n\ndef f_derivative(x: float) -> float:\n    return 2 * x - 20\n\nx0 = 100 #1\neps = 1e-7\nkmax =1e3\n\nnewton_result = tla.newton(f, f_derivative, x0, eps, kmax)    \nscipy_result = optimize.root(f, x0)\n\nprint(\"Test function is (x^2 - 20*x + 5), first guess is\", x0)\nprint(\"Newton's method root =\",newton_result, \", f(newton root)=\", f(newton_result))\nprint(\"Scipy function roots =\",scipy_result.x[0], \", f(scipy root)= \", f(scipy_result.x[0]))\nprint(\"\")\n\nprint(\"  --- ----------------------- *** ----------------------- ---  \")\nprint(\"                  Russian Peasant algorithm                    \")\nprint(\"\")\na=462\nb=1071\nmul_result = tla.rpmul(a,b)\nprint(\"Russian Peasant Multiplication \", a,\"*\", b, \"=\",mul_result)\nprint(\"Correct is:\", a*b)\na=2\nb=23\nexp_result = tla.rpexp(a,b)\nprint(\"Russian Peasant Exponentiation \", a,\"**\", b, \"=\",exp_result)\nprint(\"Correct is:\", a**b)\nprint(\"\")\n\n\nprint(\"  --- ----------------------- *** ----------------------- ---  \")\nprint(\"                The Single-Pole Low-Pass Filter                \")\nprint(\"\")\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import ticker\nimport numpy as np\n\ncutoff_freq = 2000\nsmpl_freq = 8000\n\nalpha, h, w = tla.sp_iir_lpf(cutoff_freq, smpl_freq)\n\n# Plot example is from scipy.signal.freqz function description\nfig, ax1 = plt.subplots()\nax1.set_title('SP IIR filter frequency responses with cutoff frequency = '+str(cutoff_freq/(2*smpl_freq))+'$\\pi$')\n    \nax1.plot(w, 20 * np.log10(abs(h)), 'b')\nax1.set_ylabel('Amplitude [dB]', color='b')\nax1.set_xlabel('Frequency [rad/sample]')\n\nax2 = ax1.twinx()\nangles = np.unwrap(np.angle(h))\nax2.plot(w, angles, 'g')\nax2.set_ylabel('Angle (radians)', color='g')\nax2.grid()\nax2.axis('tight')\nax2.xaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\\pi$'))\nax2.xaxis.set_major_locator(ticker.MultipleLocator(base=0.25))\nplt.show()\n\nprint(\"The single-pole IIR low-pass filter with cutoff frequency\", cutoff_freq,\"\\nhas coefficient alpha =\",alpha)\nprint(\"See the frequency response on the figure.\")\nprint(\"\")\n\n\nprint(\"  --- ----------------------- *** ----------------------- ---  \")\nprint(\"                Statistic and Welford's method                 \")\nprint(\"\")\nimport test_signals as ts\nw_mean, w_var = tla.welford(ts.noise_signal)\nnp_mean = np.mean(ts.noise_signal)\nnp_var = np.var(ts.noise_signal, ddof=1)\nprint(\"Welford:\", w_mean, w_var)\nprint(\"numpy:  \", np_mean, np_var)\nprint(\"\")", "meta": {"hexsha": "2c169991c882114f02622b80fefee06bb46a3e1b", "size": 3602, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples.py", "max_stars_repo_name": "vladimirnesterov/ten-little-algorithms", "max_stars_repo_head_hexsha": "8df2e90c43e29a69171a3f6e1bf75ad4cd0759b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples.py", "max_issues_repo_name": "vladimirnesterov/ten-little-algorithms", "max_issues_repo_head_hexsha": "8df2e90c43e29a69171a3f6e1bf75ad4cd0759b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples.py", "max_forks_repo_name": "vladimirnesterov/ten-little-algorithms", "max_forks_repo_head_hexsha": "8df2e90c43e29a69171a3f6e1bf75ad4cd0759b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0517241379, "max_line_length": 114, "alphanum_fraction": 0.5893947807, "include": true, "reason": "import numpy,from scipy", "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620585273154, "lm_q2_score": 0.8976953003183444, "lm_q1q2_score": 0.861573889363831}}
{"text": "\"\"\" this shows the logsumexp trick\"\"\"\n\nimport math\nimport numpy as np\n\ndef logsumexp1(vector):\n  s = 0\n  for i in vector:\n    s += math.exp(i)\n  return math.log(s)\n\n\ndef logsumexp2(vector):\n  s = 0\n  A = -1 * max(vector)\n  for i in vector:\n     s += math.exp(i + A)\n  return math.log(s) - A\n\n\nprint(logsumexp1([1,2,3,4,5]))\n\nprint(logsumexp2([1,2,3,4,5]))\n\n\ndef logsumexp(vector):\n  A = -np.max(vector)\n  s =  np.sum(np.exp(np.add(vector, A)))\n  return np.log(s) - A\n\nprint logsumexp([1,2,3,4,5])", "meta": {"hexsha": "025e588b12461cac9f097a9ae5c9b118bb5b8cb6", "size": 496, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/logsumexp.py", "max_stars_repo_name": "praveen97uma/ift6390_machine_learning_fundamentals", "max_stars_repo_head_hexsha": "673e1883a4b2cf0b018c4e7408cccdacefe81e2b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/logsumexp.py", "max_issues_repo_name": "praveen97uma/ift6390_machine_learning_fundamentals", "max_issues_repo_head_hexsha": "673e1883a4b2cf0b018c4e7408cccdacefe81e2b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/logsumexp.py", "max_forks_repo_name": "praveen97uma/ift6390_machine_learning_fundamentals", "max_forks_repo_head_hexsha": "673e1883a4b2cf0b018c4e7408cccdacefe81e2b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-08-24T17:37:29.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-07T17:38:14.000Z", "avg_line_length": 16.0, "max_line_length": 40, "alphanum_fraction": 0.6068548387, "include": true, "reason": "import numpy", "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745211, "lm_q2_score": 0.8976952989498448, "lm_q1q2_score": 0.8615738849508395}}
{"text": "# Linear Regression: Inverse Matrix Method\n#----------------------------------\n#\n# This function shows how to use Tensorflow to\n# solve linear regression via the matrix inverse.\n#\n# Given Ax=b, solving for x:\n#  x = (t(A) * A)^(-1) * t(A) * b\n#  where t(A) is the transpose of A\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nops.reset_default_graph()\n\n# Create graph\nsess = tf.Session()\n\n# Create the data\nx_vals = np.linspace(0, 10, 100)\ny_vals = x_vals + np.random.normal(0, 1, 100)\n\n# Create design matrix\nx_vals_column = np.transpose(np.matrix(x_vals))\nones_column = np.transpose(np.matrix(np.repeat(1, 100)))\nA = np.column_stack((x_vals_column, ones_column))\n\n# Create b matrix\nb = np.transpose(np.matrix(y_vals))\n\n# Create tensors\nA_tensor = tf.constant(A)\nb_tensor = tf.constant(b)\n\n# Matrix inverse solution\ntA_A = tf.matmul(tf.transpose(A_tensor), A_tensor)\ntA_A_inv = tf.matrix_inverse(tA_A)\nproduct = tf.matmul(tA_A_inv, tf.transpose(A_tensor))\nsolution = tf.matmul(product, b_tensor)\n\nsolution_eval = sess.run(solution)\n\n# Extract coefficients\nslope = solution_eval[0][0]\ny_intercept = solution_eval[1][0]\n\nprint('slope: ' + str(slope))\nprint('y_intercept: ' + str(y_intercept))\n\n# Get best fit line\nbest_fit = []\nfor i in x_vals:\n  best_fit.append(slope*i+y_intercept)\n\n# Plot the results\nplt.plot(x_vals, y_vals, 'o', label='Data')\nplt.plot(x_vals, best_fit, 'r-', label='Best fit line', linewidth=3)\nplt.legend(loc='upper left')\nplt.show()", "meta": {"hexsha": "40166d5e308e1c56ca869f69daaa0451926b066f", "size": 1528, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter 03/lin_reg_inverse.py", "max_stars_repo_name": "bharlow058/Packt-TF-cook-book", "max_stars_repo_head_hexsha": "2b2ed98bccdc36a41ea3247c23c944a15b81d7b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 587, "max_stars_repo_stars_event_min_datetime": "2017-02-16T15:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T13:16:07.000Z", "max_issues_repo_path": "Chapter 03/lin_reg_inverse.py", "max_issues_repo_name": "bharlow058/Packt-TF-cook-book", "max_issues_repo_head_hexsha": "2b2ed98bccdc36a41ea3247c23c944a15b81d7b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-03-07T07:49:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T01:54:23.000Z", "max_forks_repo_path": "Chapter 03/lin_reg_inverse.py", "max_forks_repo_name": "bharlow058/Packt-TF-cook-book", "max_forks_repo_head_hexsha": "2b2ed98bccdc36a41ea3247c23c944a15b81d7b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 427, "max_forks_repo_forks_event_min_datetime": "2017-02-16T07:52:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:10:12.000Z", "avg_line_length": 25.4666666667, "max_line_length": 68, "alphanum_fraction": 0.7120418848, "include": true, "reason": "import numpy", "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307661011976, "lm_q2_score": 0.8856314647623015, "lm_q1q2_score": 0.8615695363480355}}
{"text": "import numpy as np\nimport scipy.sparse as spar\nimport scipy.linalg as la\nfrom scipy.sparse import linalg as sla\n\ndef adj_mat(datafile, n):\n    \"\"\" Parse the data stored in 'datafile' and form the\n    adjacency matrix of the corresponding graph.\n    'n' is the number of rows of the nxn sparse matrix formed. \"\"\"\n    adj = spar.dok_matrix((n,n))\n    with open(datafile, 'r') as f:\n        for L in f:\n            L = L.strip().split()\n            try:\n                x, y = int(L[0]), int(L[1])\n                adj[x, y] = 1\n            except:\n                continue\n    return adj\n\n\ndef page_rank_dense_lstsq(datafile, d, datasize, n=None):\n    \"\"\" Solve the page rank problem, given the data in 'datafile',\n    the dampening factor 'd', the size 'datasize' of the dataset,\n    and the number 'n' of nodes to include.\n    Have 'n' default to None.\n    Use the method involving least squares.\"\"\"\n    data = adj_mat(datafile, n)\n    A = np.asarray(data.tocsr()[:n, :n].todense())\n    #data is dense and is of type matrix\n    e = np.ones(n)\n    for i, v in enumerate(A.sum(1)):\n        if v == 0:\n            A[i] = e\n    \n    K = ((1./A.sum(1))[:,np.newaxis]*A).T\n    K *= - d\n    np.fill_diagonal(K, K.diagonal() + 1)\n    R = la.lstsq(K, (1-d)*e/float(n))\n    max_rank = R[0].max()\n    \n    return max_rank, np.where(R[0]==max_rank)[0]\n\ndef page_rank_dense_iter(datafile, d, datasize, n=None, tol=1E-5):\n    \"\"\" Solve the page rank problem, given the data in 'datafile',\n    the dampening factor 'd', the size 'datasize' of the dataset,\n    the number 'n' of nodes to include, and a tolerance 'tol'\n    to use to determine when to stop iterating.\n    Have 'n' default to None.\n    Use the iterative method described in the lab. \"\"\"\n    pass\n\ndef page_rank_dense_eig(datafile, d, datasize, n=None):\n    \"\"\" Solve the page rank problem, given the data in 'datafile',\n    the dampening factor 'd', the size 'datasize' of the dataset,\n    and the number 'n' of nodes to include.\n    Have 'n' default to None.\n    Use the eigenvalue method described in the lab. \"\"\"\n    pass\n  \ndef sparse_pr(datafile, d, datasize, n=None, tol=1e-5):\n    \"\"\" Solve the page rank problem, given the data in 'datafile',\n    the dampening factor 'd', the size 'datasize' of the dataset,\n    the number 'n' of nodes to include, and a tolerance 'tol'\n    to use to determine when to stop iterating.\n    Have 'n' default to None.\n    Use the iterative method described in the lab.\n    Use only sparse matrix operations. \"\"\"\n    \n    A = data.tocsc()[:n, :n]\n    s = A.sum(1)\n    diag = 1./s\n    sinks = s==0\n    diag[sinks] = 0\n    K = spar.spdiags(diag.squeeze(1), 0, n, n).dot(A).T\n    \n    d = .85\n    convDist = 1\n    Rinit = np.ones((n, 1))/float(n)\n    Rold = Rinit\n    while convDist > tol:\n        Rnew = d*K.dot(Rold) + (1-d)*Rinit + (d*Rold[sinks].sum())*Rinit\n        convDist = la.norm(Rnew-Rold)\n        Rold = Rnew\n        \n    max_rank = Rnew.max()\n    return max_rank, Rnew[Rnew==max_rank]\n", "meta": {"hexsha": "308582405ca2ab1a16fa5a753f81dd5327db03eb", "size": 2981, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/PageRank/pagerank.py", "max_stars_repo_name": "jessicaleete/numerical_computing", "max_stars_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-10-18T19:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:12:38.000Z", "max_issues_repo_path": "Labs/PageRank/pagerank.py", "max_issues_repo_name": "jessicaleete/numerical_computing", "max_issues_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/PageRank/pagerank.py", "max_forks_repo_name": "jessicaleete/numerical_computing", "max_forks_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-14T16:07:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-20T09:05:06.000Z", "avg_line_length": 33.875, "max_line_length": 72, "alphanum_fraction": 0.6068433412, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.9086179043564153, "lm_q1q2_score": 0.861510187760977}}
{"text": "import numpy as np\n\ndef divide(matrix2D): \n\n    r, c = matrix2D.shape \n    r2, c2 = r//2, c//2\n    return matrix2D[:r2, :c2], matrix2D[:r2, c2:], matrix2D[r2:, :c2], matrix2D[r2:, c2:] \n  \ndef strassen(x, y): #Code to multiply any 2^n Dimensional matrix\n\n    if len(x) == 1: \n        return x * y #Base case\n  \n\n    a, b, c, d = divide(x) \n    e, f, g, h = divide(y) \n  \n    p1 = strassen(a, f - h)   \n    p2 = strassen(a + b, h)         \n    p3 = strassen(c + d, e)         \n    p4 = strassen(d, g - e)         \n    p5 = strassen(a + d, e + h)         \n    p6 = strassen(b - d, g + h)   \n    p7 = strassen(a - c, e + f)   \n   \n    c11 = p5 + p4 - p2 + p6   \n    c12 = p1 + p2            \n    c21 = p3 + p4             \n    c22 = p1 + p5 - p3 - p7   \n   \n    c = np.vstack((np.hstack((c11, c12)), np.hstack((c21, c22))))  \n  \n    return c \n\n#sample\nA = np.random.rand(4,4)\nB = np.random.rand(4,4)\n\nprint(\"A =\",A)\nprint(\"B =\", B)\nprint(\"A*B =\",strassen(A,B))\n", "meta": {"hexsha": "c8c36187b0599f4e6db02b90eebb3ae856973e83", "size": 958, "ext": "py", "lang": "Python", "max_stars_repo_path": "Algorithms/Programs/Strassen-Algo.py", "max_stars_repo_name": "TeacherManoj0131/HacktoberFest2020-Contributions", "max_stars_repo_head_hexsha": "c7119202fdf211b8a6fc1eadd0760dbb706a679b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 256, "max_stars_repo_stars_event_min_datetime": "2020-09-30T19:31:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T18:09:15.000Z", "max_issues_repo_path": "Algorithms/Programs/Strassen-Algo.py", "max_issues_repo_name": "TeacherManoj0131/HacktoberFest2020-Contributions", "max_issues_repo_head_hexsha": "c7119202fdf211b8a6fc1eadd0760dbb706a679b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 293, "max_issues_repo_issues_event_min_datetime": "2020-09-30T19:14:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-06T02:34:47.000Z", "max_forks_repo_path": "Algorithms/Programs/Strassen-Algo.py", "max_forks_repo_name": "TeacherManoj0131/HacktoberFest2020-Contributions", "max_forks_repo_head_hexsha": "c7119202fdf211b8a6fc1eadd0760dbb706a679b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1620, "max_forks_repo_forks_event_min_datetime": "2020-09-30T18:37:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T20:54:22.000Z", "avg_line_length": 22.8095238095, "max_line_length": 90, "alphanum_fraction": 0.4634655532, "include": true, "reason": "import numpy", "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242009478238, "lm_q2_score": 0.888758803068433, "lm_q1q2_score": 0.8614954166196531}}
{"text": "import numpy as np\n# **The following class contains methods to calculate distance between two points using various techniques**\n\n# **Formula to calculate Eucledian distance:**\n#\n# <math>\\begin{align}D(x, y) = \\sqrt{ \\sum_i (x_i - y_i) ^ 2 }\\end{align}</math>\n\n# **Formula to calculate Manhattan Distance:**\n#\n# <math>\\begin{align}D(x, y) = \\sum_i |x_i - y_i|\\end{align}</math>\n\n# **Formula to calculate Hamming Distance:**\n#\n# <math>\\begin{align}D(x, y) = \\frac{1}{N} \\sum_i \\delta_{x_i, y_i}\\end{align}</math>\n\nclass distanceMetrics:\n    '''\n    Description:\n        This class contains methods to calculate various distance metrics\n    '''\n    def __init__(self):\n        '''\n        Description:\n            Initialization/Constructor function\n        '''\n        pass\n        \n    def euclideanDistance(self, vector1, vector2):\n        '''\n        Description:\n            Function to calculate Euclidean Distance\n                \n        Inputs:\n            vector1, vector2: input vectors for which the distance is to be calculated\n        Output:\n            Calculated euclidean distance of two vectors\n        '''\n        self.vectorA, self.vectorB = vector1, vector2\n        if len(self.vectorA) != len(self.vectorB):\n            raise ValueError(\"Undefined for sequences of unequal length.\")\n        distance = 0.0\n        for i in range(len(self.vectorA)-1):\n            distance += (self.vectorA[i] - self.vectorB[i])**2\n        return (distance)**0.5\n    \n    def manhattanDistance(self, vector1, vector2):\n        \"\"\"\n        Desription:\n            Takes 2 vectors a, b and returns the manhattan distance\n        Inputs:\n            vector1, vector2: two vectors for which the distance is to be calculated\n        Output:\n            Manhattan Distance of two input vectors\n        \"\"\"\n        self.vectorA, self.vectorB = vector1, vector2\n        if len(self.vectorA) != len(self.vectorB):\n            raise ValueError(\"Undefined for sequences of unequal length.\")\n        return np.abs(np.array(self.vectorA) - np.array(self.vectorB)).sum()\n    \n    def hammingDistance(self, vector1, vector2):\n        \"\"\"\n        Desription:\n            Takes 2 vectors a, b and returns the hamming distance\n            Hamming distance is meant for discrete-valued vectors, though it is a\n            valid metric for real-valued vectors.\n        Inputs:\n            vector1, vector2: two vectors for which the distance is to be calculated\n        Output:\n           Hamming Distance of two input vectors\n        \"\"\"\n        self.vectorA, self.vectorB = vector1, vector2\n        if len(self.vectorA) != len(self.vectorB):\n            raise ValueError(\"Undefined for sequences of unequal length.\")\n        return sum(el1 != el2 for el1, el2 in zip(self.vectorA, self.vectorB))\n\n\n", "meta": {"hexsha": "756aec6185a60044cf8906793eea6f1dbe73ad13", "size": 2782, "ext": "py", "lang": "Python", "max_stars_repo_path": "simple_kNN/distanceMetrics.py", "max_stars_repo_name": "chaitanyakasaraneni/simple-kNN", "max_stars_repo_head_hexsha": "eb9afc12bfd190c362939cc0a6db82ceccf459f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simple_kNN/distanceMetrics.py", "max_issues_repo_name": "chaitanyakasaraneni/simple-kNN", "max_issues_repo_head_hexsha": "eb9afc12bfd190c362939cc0a6db82ceccf459f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simple_kNN/distanceMetrics.py", "max_forks_repo_name": "chaitanyakasaraneni/simple-kNN", "max_forks_repo_head_hexsha": "eb9afc12bfd190c362939cc0a6db82ceccf459f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1298701299, "max_line_length": 108, "alphanum_fraction": 0.6135873472, "include": true, "reason": "import numpy", "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242018339898, "lm_q2_score": 0.888758794965684, "lm_q1q2_score": 0.8614954095530503}}
{"text": "#!/usr/bin/env python3\n\nimport csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler\nfrom math import sqrt\nimport argparse\n\n\ndef\t\ttrain(mileage, price, learning_rate, n_epochs):\n\tm = float(len(mileage))\n\ttheta0, theta1 = 0, 0\n\tfor _ in range(n_epochs):\n\t\tprice_estimate = mileage * theta1 + theta0\n\t\tdiff = price_estimate - price\n\t\ttmp_theta0 = np.sum(diff)*learning_rate/m\n\t\ttmp_theta1 = np.sum(diff*mileage)*learning_rate/m\n\t\ttheta0 -= tmp_theta0\n\t\ttheta1 -= tmp_theta1\n\treturn theta0, theta1\n\n\ndef\t\tmain():\n\t# Parse arguments\n\tmy_parser = argparse.ArgumentParser(description='Train a linear regression model on a univariate dataset.')\n\tmy_parser.add_argument('Path', metavar='path', type=str, help='The path to the csv file containing the data.')\n\tmy_parser.add_argument('-n', '-Number of epochs', type=int, default=1000)\n\tmy_parser.add_argument('-l', '-Learning rate', type=float, default=0.1)\n\targs = my_parser.parse_args()\n\tif (args.n < 1):\n\t\tprint(\"The number of epochs must be larger than zero.\")\n\t\texit(1)\n\tif (args.l <= 0):\n\t\tprint(\"The learning rate must be larger than zero.\")\n\t\texit(1)\n\n\t# Read csv file\n\ttry:\n\t\twith open(args.Path) as data_file:\n\t\t\tcsv_reader = csv.reader(data_file, delimiter=',')\n\t\t\tmileage, price = [], []\n\t\t\tcount = 0\n\t\t\tfor row in csv_reader:\n\t\t\t\tif (count):\n\t\t\t\t\tmileage.append(int(row[0]))\n\t\t\t\t\tprice.append(int(row[1]))\n\t\t\t\tcount += 1\n\texcept Exception as e:\n\t\tprint(f\"Can't open {args.Path} or it's not a valid csv file.\")\n\t\tprint(e)\n\t\texit(1)\n\tmileage = np.array(mileage)\n\tprice = np.array(price)\n\n\t# Data normalization\n\tmileage_scaler = MinMaxScaler()\n\tmileage = mileage.reshape(-1, 1)\n\tmileage_norm = mileage_scaler.fit_transform(mileage)\n\n\tprice_scaler = MinMaxScaler()\n\tprice = price.reshape(-1, 1)\n\tprice_norm = price_scaler.fit_transform(price)\n\n\t# Training\n\ttheta0_norm, theta1_norm = train(mileage_norm, price_norm, args.l, args.n)\n\tpredicted_price_norm = theta1_norm * mileage_norm + theta0_norm\n\n\t# Rescaling\n\tpredicted_price = price_scaler.inverse_transform(predicted_price_norm)\n\n\t# Calculating root mean squared error\n\trmse = sqrt(np.sum((predicted_price - price) * (predicted_price - price))/(count - 1))\n\tprint(f\"RMSE: {rmse}\")\n\n\t# Plotting\n\tplt.scatter(mileage, price)\n\tplt.plot(mileage, predicted_price, color='red')\n\tplt.xlabel(\"Mileage (in Km)\")\n\tplt.ylabel(\"Price (in Euros)\")\n\tplt.show()\n\n\t# Calculating real values of theta0 and theta1\n\ttheta0 = (theta0_norm - (theta1_norm * mileage.min()) / (mileage.max() - mileage.min())) * (price.max() - price.min()) + price.min()\n\ttheta1 = (theta1_norm / (mileage.max() - mileage.min())) * (price.max() - price.min())\n\n\t# Saving theta0 and theta1 to a file\n\tf = open(\"parameters.txt\", 'w')\n\tf.write(f\"{theta0}\\n{theta1}\\n\")\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "51a2adc53dae2b78dd6dfd1e590b00ccb893fb82", "size": 2815, "ext": "py", "lang": "Python", "max_stars_repo_path": "train.py", "max_stars_repo_name": "MedAymenF/ft_linear_regression", "max_stars_repo_head_hexsha": "3d6dcd1ad7f3f5f33777cc76a52d24f0b79cee91", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "train.py", "max_issues_repo_name": "MedAymenF/ft_linear_regression", "max_issues_repo_head_hexsha": "3d6dcd1ad7f3f5f33777cc76a52d24f0b79cee91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "train.py", "max_forks_repo_name": "MedAymenF/ft_linear_regression", "max_forks_repo_head_hexsha": "3d6dcd1ad7f3f5f33777cc76a52d24f0b79cee91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9468085106, "max_line_length": 133, "alphanum_fraction": 0.7055062167, "include": true, "reason": "import numpy", "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633822, "lm_q2_score": 0.9005297967961707, "lm_q1q2_score": 0.8614776006206561}}
{"text": "# A Gabriel's Horn, brought to you by PharaohCola13\n\nimport mpl_toolkits.mplot3d.axes3d as p3\nimport matplotlib.pyplot as plt\nfrom matplotlib import *\nfrom numpy import *\nfrom mpl_toolkits.mplot3d.art3d import *\nfrom matplotlib.animation import *\n\nname = \"Gabriel's-Horn\"\n\ndef shape(fig, alpha, color, edge_c, edge_w, grid, sides, edges, multi_pi, radius, height):\n\t# Definition of x\n\tdef x_(u, v):\n\t\tx = u\n\t\treturn x\n\n\t# Definition of y\n\tdef y_(u, v):\n\t\ty = (a * cos(v)) / u\n\t\treturn y\n\n\n\t# Definition of z\n\tdef z_(u, v):\n\t\tz = (a * sin(v)) /u\n\t\treturn z\n\n\ta = radius # changes radius of the entire thing\n\n\th = height\n\n\t# Value of the angles\n\ts = sides\n\tu = linspace(1, h, s + 1)\n\tv = linspace(0, 2 * pi, edges)\n\n\tu, v = meshgrid(u, v)\n\n\t# Symbolic representation\n\tx = x_(u, v)\n\ty = y_(u, v)\n\tz = z_(u, v)\n\n\t# Figure Properties\n\tax = p3.Axes3D(fig)\n\tax.set_facecolor('black')  # Figure background turns black\n\n\t# Axis Properties\n\tplt.axis(grid)  # Turns off the axis grid\n\tplt.axis('equal')\n\n\t# Axis Limits\n\tax.set_xlim(-4, 4)\n\tax.set_ylim(-4, 4)\n\tax.set_zlim(-4, 4)\n\n\t# Surface Plot\n\thorn = ax.plot_surface(x, y, z)\n\n\thorn.set_alpha(alpha)  # Transparency of figure\n\thorn.set_edgecolor(edge_c)  # Edge color of the lines on the figure\n\thorn.set_linewidth(edge_w)  # Line width of the edges\n\thorn.set_facecolor(color)  # General color of the figure\n", "meta": {"hexsha": "de2ae224494e286a9cb4b5b168092ca2722896c6", "size": 1350, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/GUI/compile_space/gabriel_horn.py", "max_stars_repo_name": "gitter-badger/GeoMetrics", "max_stars_repo_head_hexsha": "8f33a7da1db88ea49f10772c4bf63b357e9f066c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-10-19T12:35:27.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-19T12:35:27.000Z", "max_issues_repo_path": "src/GUI/compile_space/gabriel_horn.py", "max_issues_repo_name": "gitter-badger/GeoMetrics", "max_issues_repo_head_hexsha": "8f33a7da1db88ea49f10772c4bf63b357e9f066c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GUI/compile_space/gabriel_horn.py", "max_forks_repo_name": "gitter-badger/GeoMetrics", "max_forks_repo_head_hexsha": "8f33a7da1db88ea49f10772c4bf63b357e9f066c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7692307692, "max_line_length": 91, "alphanum_fraction": 0.6755555556, "include": true, "reason": "from numpy", "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.900529795461386, "lm_q1q2_score": 0.8614776004571305}}
{"text": "from numpy import *\n\ndef rmserr( set1, set2 ):\n    \"\"\"Compute and return RMS error for two sets of equal length involving the same set of samples.\"\"\"\n    tot = 0.\n    for i in range(len(set1)):\n        tot+= (set1[i] - set2[i])**2\n    return sqrt(tot/float(len(set1)))\n\n\ndef correl(x,y ):\n    \"\"\"For two data sets x and y of equal length, calculate and return r, the product moment correlation. \"\"\"\n    if len(x)!=len(y):\n        print(\"ERROR: Data sets have unequal length.\\n\")\n        raise LengthError\n\n\n    #Compute averages (try not to require numerical library)\n    avgx=sum(x)/float(len(x))\n    avgy=sum(y)/float(len(y))\n\n    #Compute standard deviations\n    sigmax_sq=0\n    for elem in x:\n        sigmax_sq+=(elem-avgx)**2\n    sigmax_sq=sigmax_sq/float(len(x))\n    sigmay_sq=0\n    for elem in y:\n        sigmay_sq+=(elem-avgy)**2\n    sigmay_sq=sigmay_sq/float(len(y))\n\n    sigmax=sqrt(sigmax_sq)\n    sigmay=sqrt(sigmay_sq)\n\n    #Compute numerator of r\n    num=0\n    for i in range(len(x)):\n        num+=(x[i]-avgx)*(y[i]-avgy)\n    #Compute denominator of r\n    denom=len(x)*sigmax*sigmay\n\n    corr = num/denom\n    return corr\n\n\ndef percent_within_half( x, y):\n    \"\"\"Takes two sets, x and y, of equal length, and returns the percentage of values within 0.5 units.\"\"\"\n\n    diff = x - y\n    indices = where( abs(diff) < 0.5 )\n    return 100.*float(len(indices[0]) )/float(len(x))\n", "meta": {"hexsha": "c7d6f29be6d613982fbb9066cf86ffe695f80784", "size": 1386, "ext": "py", "lang": "Python", "max_stars_repo_path": "uci-pharmsci/assignments/solubility/tools.py", "max_stars_repo_name": "inferential/drug-computing", "max_stars_repo_head_hexsha": "25ff2f04b2a1f7cb71c552f62e722edb26cc297f", "max_stars_repo_licenses": ["CC-BY-4.0", "MIT"], "max_stars_count": 103, "max_stars_repo_stars_event_min_datetime": "2017-10-21T18:49:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T22:05:21.000Z", "max_issues_repo_path": "uci-pharmsci/assignments/solubility/tools.py", "max_issues_repo_name": "inferential/drug-computing", "max_issues_repo_head_hexsha": "25ff2f04b2a1f7cb71c552f62e722edb26cc297f", "max_issues_repo_licenses": ["CC-BY-4.0", "MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2017-10-23T20:57:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T21:57:09.000Z", "max_forks_repo_path": "uci-pharmsci/assignments/solubility/tools.py", "max_forks_repo_name": "inferential/drug-computing", "max_forks_repo_head_hexsha": "25ff2f04b2a1f7cb71c552f62e722edb26cc297f", "max_forks_repo_licenses": ["CC-BY-4.0", "MIT"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2018-01-18T20:22:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:08:09.000Z", "avg_line_length": 26.6538461538, "max_line_length": 109, "alphanum_fraction": 0.6262626263, "include": true, "reason": "from numpy", "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.9005297874526778, "lm_q1q2_score": 0.8614775927957262}}
{"text": "import numpy as np\nimport math\n\ndef makeTranslation(x, y, z):\n    \"\"\"\n    return the 4x4 numpy array transpose of the \n    3x4 \n    \"\"\"\n    m = np.eye(4)\n    m[:3,3] = x,y,z\n    return m\n\ndef makeRotationX(theta):\n    c = math.cos(theta)\n    s = math.sin(theta)\n    m = np.eye(4)\n    m[1,1] = c\n    m[1,2] = -s\n    m[2,1] = s\n    m[2,2] = c\n    return m\n\ndef makeRotationY(theta):\n    c = math.cos(theta)\n    s = math.sin(theta)\n    m = np.eye(4)\n    m[0,0] = c\n    m[0,2] = s\n    m[2,0] = -s\n    m[2,2] = c\n    return m\n\ndef makeRotationZ(theta):\n    c = math.cos(theta)\n    s = math.sin(theta)\n    m = np.eye(4)\n    m[0,0] = c\n    m[0,1] = -s\n    m[1,0] = s\n    m[1,1] = c\n    return m\n\ndef makeQuaternionMatrix(x, y, z, w):\n    n = math.sqrt(x**2 + y**2 + z**2 + w**2)\n    qx = x/n\n    qy = y/n\n    qz = z/n\n    qw = w/n\n    m = np.eye(3)\n    m[0, 0] =  1 - 2*qy**2 - 2*qz**2\n    m[0, 1] = 2*qx*qy - 2*qz*qw\n    m[0, 2] = 2*qx*qz + 2*qy*qw\n    m[1, 0] = 2*qx*qy + 2*qz*qw\n    m[1, 1] = 1 - 2*qx**2 - 2*qz**2\n    m[1, 2] = 2*qy*qz - 2*qx*qw\n    m[2, 0] = 2*qx*qz - 2*qy*qw\n    m[2, 1] = 2*qy*qz + 2*qx*qw\n    m[2, 2] = 1 - 2*qx**2 - 2*qy**2\n    return m\n# end def\n\ndef applyQuaternion(coords, m3):\n    \"\"\" assume we are applying rows of vectors\n    [               \n    [x1, y1, z1],\n        ...             * m3.T \n    [xn, yn, zn]\n    ]\n    \"\"\"\n    return np.dot(coords, m3.T)\n# end def\n\ndef applyGeomStack(coords, stack):\n    pass\n# end def\n\ndef applyTransform(coords, m4):\n    \"\"\" assume we are applying rows of vectors\n    [               \n    [x1, y1, z1, 1.],\n        ...             * m4[:3, :].T \n    [xn, yn, zn, 1.]\n    ]\n\n    where m4 is the total 4x4 transfomation matrix\n    ['n11','n12', 'n13', 'n14',\n     'n21', 'n22', 'n23', 'n24',\n     'n31', 'n32', 'n33', 'n34',\n     'n41', 'n42', 'n43', 'n44'])\n    \"\"\"\n\n    rows, cols = coords.shape\n    # print(rows, cols, coords.dtype)\n    stacked_coords = np.hstack((coords, np.ones((rows, 1))))\n    m4x3 = m4[:3,:].T   # cut off last row so we end up with a (rows , 3) product \n    return np.dot(stacked_coords, m4x3)\n\n\n", "meta": {"hexsha": "f60032726ef265067770b469a6aeb8de6deb35c9", "size": 2082, "ext": "py", "lang": "Python", "max_stars_repo_path": "na2pdb/matrix.py", "max_stars_repo_name": "Wyss/na2pdb", "max_stars_repo_head_hexsha": "691cfd55556a746f9c4b5046cd2dba56e844efb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-10-21T18:12:13.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-26T16:51:46.000Z", "max_issues_repo_path": "na2pdb/matrix.py", "max_issues_repo_name": "Wyss/na2pdb", "max_issues_repo_head_hexsha": "691cfd55556a746f9c4b5046cd2dba56e844efb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "na2pdb/matrix.py", "max_forks_repo_name": "Wyss/na2pdb", "max_forks_repo_head_hexsha": "691cfd55556a746f9c4b5046cd2dba56e844efb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0303030303, "max_line_length": 82, "alphanum_fraction": 0.4740634006, "include": true, "reason": "import numpy", "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.978051746285132, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.8614651095277951}}
{"text": "import math \nimport numpy as np\nfrom skimage.metrics import structural_similarity\n\ndef psnr(label, outputs, max_val = 1.0):\n    \"\"\"\n    Computes Peak Signal to Noise Ratio \n    PSNR = 20 * log_10(max_val / sqrt(MSE))\n\n    Definitions\n        PSNR\n            Peak Signal to Noise Ratio (the higher the better)\n            https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio#Definition\n        \n        MSE\n            Mean Square Error\n\n    Inputs\n        :label: <torch.tensor> the ground truth image\n        :outputs: <torch.tensor> the resulting super resoluted image\n        :max_val: <float> the highest pixel value\n    \n    Outputs\n        :returns: psnr(label, outputs)\n    \"\"\"\n    label = label.cpu().detach().numpy()\n    outputs = outputs.cpu().detach().numpy()\n    img_diff = outputs - label\n    rmse = math.sqrt(np.mean((img_diff) ** 2))\n    if rmse == 0:\n        return 100\n    else:\n        PSNR = 20 * math.log10(max_val / rmse)\n        return PSNR\n    \ndef ssim(label, outputs):\n    \"\"\"\n    Calculates the Structural Similairty Index Measure \n    SSIM = L(x, y)^a C(x, y)^b S(x, y)^c\n\n    Definitions\n        SSIM\n            Structural Similairty Index Measure (the higher the better)\n            https://en.wikipedia.org/wiki/Structural_similarity\n    \n    Inputs\n        :label: <torch.tensor> the ground truth image\n        :outputs: <torch.tensor> the resulting super resoluted image\n    \n    Outputs\n        :returns: ssim(label, outputs)\n    \"\"\"\n    score, loss = structural_similarity(label, outputs, full=True, multichannel=True)\n    return score", "meta": {"hexsha": "bb5f366ba453c13eb1889198130a5436f91935ab", "size": 1575, "ext": "py", "lang": "Python", "max_stars_repo_path": "previous networks/srcnn/implementation/loss_functions.py", "max_stars_repo_name": "ATKatary/EVSR", "max_stars_repo_head_hexsha": "594b798ad76a68a3dbdc847ad4a0d9961bf9f6ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "previous networks/srcnn/implementation/loss_functions.py", "max_issues_repo_name": "ATKatary/EVSR", "max_issues_repo_head_hexsha": "594b798ad76a68a3dbdc847ad4a0d9961bf9f6ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "previous networks/srcnn/implementation/loss_functions.py", "max_forks_repo_name": "ATKatary/EVSR", "max_forks_repo_head_hexsha": "594b798ad76a68a3dbdc847ad4a0d9961bf9f6ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1666666667, "max_line_length": 85, "alphanum_fraction": 0.6203174603, "include": true, "reason": "import numpy", "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9817357205793904, "lm_q2_score": 0.8774767954920548, "lm_q1q2_score": 0.8614503141140868}}
{"text": "'''\ndata_normalization.py\nhttps://aimldl.blog.me/221627895429\n\nhttps://livebook.manning.com/book/deep-learning-with-python/chapter-3/190\n'''\nfrom keras.datasets import boston_housing\nimport numpy as np\n\n# Load data\n(train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()\nprint(f'train_data.shape = {train_data.shape}' )  # (404, 13)\nprint(f'test_data.shape = {test_data.shape}' )    # (102, 13)\nprint( train_data[0] )\n#[  1.23247   0.        8.14      0.        0.538     6.142    91.7\n#   3.9769    4.      307.       21.      396.9      18.72   ]\nprint( train_targets[0] )\n# 15.2\n\n# Prepare data\n#   Normalize the data with respect to the features\nmean = train_data.mean( axis=0 )\nstd  = train_data.std( axis=0 )\n\n# Option 1\nx_train = (train_data - mean) / std\nx_test  = (test_data - mean) / std\n\n# Option 2\ntrain_data -= mean\ntrain_data /= std\ntest_data  -= mean\ntest_data  /= std\n\nprint( 'Compare the normalized values.' )\nprint( x_train[0] )\nprint( train_data[0] )\n#Compare the normalized values.\n#[-0.27224633 -0.48361547 -0.43576161 -0.25683275 -0.1652266  -0.1764426\n#  0.81306188  0.1166983  -0.62624905 -0.59517003  1.14850044  0.44807713\n#  0.8252202 ]\n#[-0.27224633 -0.48361547 -0.43576161 -0.25683275 -0.1652266  -0.1764426\n#  0.81306188  0.1166983  -0.62624905 -0.59517003  1.14850044  0.44807713\n#  0.8252202 ]\n\nprint( x_test[0] )\nprint( test_data[0] )\n#[ 1.55369355 -0.48361547  1.0283258  -0.25683275  1.03838067  0.23545815\n#  1.11048828 -0.93976936  1.67588577  1.5652875   0.78447637 -3.48459553\n#  2.25092074]\n#[ 1.55369355 -0.48361547  1.0283258  -0.25683275  1.03838067  0.23545815\n#  1.11048828 -0.93976936  1.67588577  1.5652875   0.78447637 -3.48459553\n#  2.25092074]\n", "meta": {"hexsha": "69949d0fd3391b1729c1af0075a8de817897c86f", "size": 1722, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/en/archive/topics/temp/data_normalization.py", "max_stars_repo_name": "aimldl/coding", "max_stars_repo_head_hexsha": "70ddbfaa454ab92fd072ee8dc614ecc330b34a70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/en/archive/topics/temp/data_normalization.py", "max_issues_repo_name": "aimldl/coding", "max_issues_repo_head_hexsha": "70ddbfaa454ab92fd072ee8dc614ecc330b34a70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/en/archive/topics/temp/data_normalization.py", "max_forks_repo_name": "aimldl/coding", "max_forks_repo_head_hexsha": "70ddbfaa454ab92fd072ee8dc614ecc330b34a70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8888888889, "max_line_length": 83, "alphanum_fraction": 0.6800232288, "include": true, "reason": "import numpy", "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.9219218407544306, "lm_q1q2_score": 0.8614393082417702}}
{"text": "from scipy.stats import lognorm, norm\nimport numpy as np\n\n\ndef make_normal_from_interval(lb, ub, alpha):\n    ''' Creates a normal distribution SciPy object from intervals.\n\n    This function is a helper to create SciPy distributions by specifying the\n    amount of wanted density between a lower and upper bound. For example,\n    calling with (lb, ub, alpha) = (2, 3, 0.95) will create a Normal\n    distribution with 95% density between 2 a 3.\n\n    Args:\n        lb (float): Lower bound\n        ub (float): Upper bound\n        alpha (float): Total density between lb and ub\n\n    Returns:\n        scipy.stats.norm\n    \n    Examples:\n        >>> dist = make_normal_from_interval(-1, 1, 0.63)\n        >>> dist.mean()\n        0.0\n        >>> dist.std()\n        1.1154821104064199\n        >>> dist.interval(0.63)\n        (-1.0000000000000002, 1.0)\n\n    '''\n    z = norm().interval(alpha)[1]\n    mean_norm = (ub + lb) / 2\n    std_norm = (ub - lb) / (2 * z)\n    return norm(loc=mean_norm, scale=std_norm)\n\n\ndef make_lognormal_from_interval(lb, ub, alpha):\n    ''' Creates a lognormal distribution SciPy object from intervals.\n\n    This function is a helper to create SciPy distributions by specifying the\n    amount of wanted density between a lower and upper bound. For example,\n    calling with (lb, ub, alpha) = (2, 3, 0.95) will create a LogNormal\n    distribution with 95% density between 2 a 3.\n\n    Args:\n        lb (float): Lower bound\n        ub (float): Upper bound\n        alpha (float): Total density between lb and ub\n\n    Returns:\n        scipy.stats.lognorm\n    \n    Examples:\n        >>> dist = make_lognormal_from_interval(2, 3, 0.95)\n        >>> dist.mean()\n        2.46262863041182\n        >>> dist.std()\n        0.25540947842844575\n        >>> dist.interval(0.95)\n        (1.9999999999999998, 2.9999999999999996)\n\n    '''\n    z = norm().interval(alpha)[1]\n    mean_norm = np.sqrt(ub * lb)\n    std_norm = np.log(ub / lb) / (2 * z)\n    return lognorm(s=std_norm, scale=mean_norm)\n\n\nclass EmpiricalDistribution:\n    def __init__(self, observations, method='sequential'):\n        self.observations = np.array(observations)\n        self.method = 'sequential'\n        self.rvs = (self._sequential_rvs if method == 'sequential' else\n                    self._uniform_rvs)\n\n    def _sequential_rvs(self, size):\n        assert size <= len(self.observations)\n        return self.observations[:size]\n\n    def _uniform_rvs(self, size):\n        return np.random.choice(self.observations, size, replace=True)\n", "meta": {"hexsha": "1b12b652c022484f6f66f72fdda5f3745ed2eea6", "size": 2508, "ext": "py", "lang": "Python", "max_stars_repo_path": "covid_19/covid19/utils.py", "max_stars_repo_name": "ramonfontes/Mathematical-and-Statistical-Modeling-of-COVID19-in-Brazil", "max_stars_repo_head_hexsha": "0f93a195ad867f6d405c4a80469b535a05cf6687", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 248, "max_stars_repo_stars_event_min_datetime": "2020-03-18T02:55:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-03T16:25:15.000Z", "max_issues_repo_path": "covid_19/covid19/utils.py", "max_issues_repo_name": "ramonfontes/Mathematical-and-Statistical-Modeling-of-COVID19-in-Brazil", "max_issues_repo_head_hexsha": "0f93a195ad867f6d405c4a80469b535a05cf6687", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 163, "max_issues_repo_issues_event_min_datetime": "2020-03-18T02:57:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:19:35.000Z", "max_forks_repo_path": "covid_19/covid19/utils.py", "max_forks_repo_name": "ramonfontes/Mathematical-and-Statistical-Modeling-of-COVID19-in-Brazil", "max_forks_repo_head_hexsha": "0f93a195ad867f6d405c4a80469b535a05cf6687", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2020-03-18T14:39:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T00:13:33.000Z", "avg_line_length": 30.5853658537, "max_line_length": 77, "alphanum_fraction": 0.6315789474, "include": true, "reason": "import numpy,from scipy", "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214470715363, "lm_q2_score": 0.8933094096048376, "lm_q1q2_score": 0.8614374225527568}}
{"text": "import numpy as np\n\nclass PCA:\n\n    def __init__(self,n_components):\n        self.n_components=n_components\n        self.components=None\n        self.mean=None\n\n    def fit(self,X):\n        #mean\n        self.mean=np.mean(X,axis=0)\n        X=X-self.mean\n\n        #covariance\n        cov = np.cov(X.T)\n        #eigen values and eigen vectors\n        eigenvalues, eigenvectors = np.linalg.eig(cov)\n\n        #sort eigenvectors\n        eigenvectors=eigenvectors.T\n        idxs=np.argsort(eigenvalues)[::-1]\n        eigenvalues=eigenvalues[idxs]\n        eigenvectors=eigenvectors[idxs]\n\n        # store first n eigenvectors\n        self.components=eigenvectors[0:self.n_components]\n        return eigenvalues[0:self.n_components],self.components,self.mean,cov\n    def transform(self,X):\n        # project data on vector found\n        X=X-self.mean\n        return np.dot(X,self.components.T) \n    \n", "meta": {"hexsha": "55c1fcd341693288addadae25357f54e14927528", "size": 892, "ext": "py", "lang": "Python", "max_stars_repo_path": "app/src/main/python/PCA.py", "max_stars_repo_name": "VigneshTheBlaster/ML_calculator", "max_stars_repo_head_hexsha": "e03d4d3d666901c80ffba75de1168f6faaac5053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/src/main/python/PCA.py", "max_issues_repo_name": "VigneshTheBlaster/ML_calculator", "max_issues_repo_head_hexsha": "e03d4d3d666901c80ffba75de1168f6faaac5053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/src/main/python/PCA.py", "max_forks_repo_name": "VigneshTheBlaster/ML_calculator", "max_forks_repo_head_hexsha": "e03d4d3d666901c80ffba75de1168f6faaac5053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2352941176, "max_line_length": 77, "alphanum_fraction": 0.6266816143, "include": true, "reason": "import numpy", "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9835969679646669, "lm_q2_score": 0.8757869786798663, "lm_q1q2_score": 0.8614214168124529}}
{"text": "import numpy as np\nfrom numpy.linalg import inv,norm\nimport matplotlib.pyplot as plt\n\ndef solve_lambda_x(A,y,lambs_exponent=np.arange(-10,5,0.01)):\n    '''\n    Minimize the Lagrangian L(x,lambda) = || A*x - y||**2 + lambda*||x||**2 based on the idea of Tikhonov Regularization.\n    This program is used to roughly estimate the parameters x and the Lagrange multiplier lambda. \n    The L-curve method is applied to get the proper Lagrangian multiplier.\n\n    Usage:\n    estimate_lamb,estimate_x,log10_residual_norm,log10_solution_norm,curvature = solve_lambda_x(A,y) \n\n    Inputs:\n    A -> [float 2d array] Design matrix\n    y -> [float array] Measurements\n\n    Parameters:\n    lambs_exponent -> [optional, float 3d/4d array, default = np.arange(-10,5,0.01)] Exponent for lambda with base of 10\n    \n    Outputs:\n    estimate_lamb -> [float] Lagrange multiplier\n    estimate_x -> [float array] Estimated parameters\n    log10_residual_norm -> [float array] log10(||A*x-y||) with lambda taking 10**lambs_exponent\n    log10_solution_norm -> [float array] log10(||x||) with lambda taking 10**lambs_exponent\n    curvature -> [float array] curvature of the L-curve, where the ordinate of the curve is log10_solution_norm and the abscissa is log10_residual_norm.\n\n    For more information, please refer to \n    (1) [NumPy/SciPy Recipes for Data Science: Regularized Least Squares Optimization](https://www.researchgate.net/publication/274138835_NumPy_SciPy_Recipes_for_Data_Science_Regularized_Least_Squares_Optimization)\n    (2) [Choosing the Regularization Parameter](http://www2.compute.dtu.dk/~pcha/DIP/chap5.pdf)\n    '''  \n    np.seterr(divide='ignore',invalid='ignore')\n    m = A.shape[1]\n  \n    # set a series of Lagrangian multiplier       \n    log10_residual_norm,log10_solution_norm = [],[]\n    lambs = np.float_power(10,lambs_exponent)\n    for lamb in lambs:\n        x = np.dot(inv(np.dot(A.T,A)+lamb*np.eye(m)),np.dot(A.T,y))\n        residual_norm = norm(np.dot(A,x)-y)\n        solution_norm = norm(x)\n        log10_residual_norm.append(np.log10(residual_norm))\n        log10_solution_norm.append(np.log10(solution_norm))\n    log10_residual_norm = np.array(log10_residual_norm)\n    log10_solution_norm = np.array(log10_solution_norm)  \n    \n    # calculate the curvature of the L-curve\n    g1 = np.gradient(log10_solution_norm, log10_residual_norm)\n    g1[np.isnan(g1)] = -np.inf\n    g2 = np.gradient(g1,log10_residual_norm)\n    g2[np.isnan(g2)] = np.inf\n    curvature = np.abs(g2)/(1+g1**2)**1.5\n    curvature[np.isnan(curvature)] = 0\n    curvature[np.isinf(curvature)] = 0\n    index_curvature_max = np.argmax(curvature)\n    estimate_lamb = lambs[index_curvature_max]\n    estimate_x = np.dot(inv(np.dot(A.T,A)+estimate_lamb*np.eye(m)),np.dot(A.T,y))\n    return estimate_lamb,estimate_x,log10_residual_norm,log10_solution_norm,curvature\n\ndef L_curve(A,y,visible=None):\n    '''\n    Minimize the Lagrangian L(x,lambda) = || A*x - y||**2 + lambda*||x||**2 based on the idea of Tikhonov Regularization.\n    This program is used to accurately estimate the parameters x and the Lagrange multiplier lambda. \n    The final Lagrange multiplier is determained by the L-curve method. The L-curve can be visualized by outputing an image.\n\n    Usage:\n    accu_lamb,accu_x = L_curve(A,y) \n\n    Inputs:\n    A -> [float 2d array] Design matrix\n    y -> [float array] Measurements\n\n    Parameters:\n    visible -> [optional, str, default = None] If None, the visualization of L-vurve will be closed. If 'visible', the L-curve will be visualized by outputing an image.\n    \n    Outputs:\n    accu_lamb -> [float] Lagrange multiplier\n    accu_x -> [float array] Estimated parameters\n    \n    For more information, please refer to \n    (1) [NumPy/SciPy Recipes for Data Science: Regularized Least Squares Optimization](https://www.researchgate.net/publication/274138835_NumPy_SciPy_Recipes_for_Data_Science_Regularized_Least_Squares_Optimization)\n    (2) [Choosing the Regularization Parameter](http://www2.compute.dtu.dk/~pcha/DIP/chap5.pdf)\n    '''  \n    m = A.shape[1]\n            \n    # Estimate the Lagrange multiplier roughly  \n    appr_lamb,appr_x,log10_residual_norm,log10_solution_norm,appr_curvature = solve_lambda_x(A,y)\n    \n    # Estimate the Lagrange multiplier accurately\n    lambs_exponent = np.linspace(np.log10(appr_lamb)-2,np.log10(appr_lamb)+2,2000)\n    accu_lamb,accu_x,log10_residual_norm,log10_solution_norm,accu_curvature = solve_lambda_x(A,y,lambs_exponent)\n\n    if visible is not None:\n        fig_dir = 'figures/'\n        if not os.path.exists(fig_dir): os.makedirs(fig_dir) \n        # plot\n        plt.clf()\n        fig, (ax1, ax2) = plt.subplots(1, 2,dpi=200)\n        # make a little extra space between the subplots\n        fig.subplots_adjust(wspace=0.4)\n        ax1.plot(log10_residual_norm,log10_solution_norm)\n        ax1.set_xlabel(r'$\\log \\parallel A x_{\\lambda}-y \\parallel_2$')\n        ax1.set_ylabel(r'$\\log \\parallel x_{\\lambda} \\parallel_2$')\n        ax1.set_title('L-Curve')\n        ax2.plot(lambs_exponent,accu_curvature)\n        ax2.set_xlabel(r'$\\log \\parallel \\lambda \\parallel_2$')\n        ax2.set_ylabel('Curvature')\n        ax2.set_title('curvature of L-Curve')\n        plt.savefig(fig_dir+'L-Curve.png')\n    return accu_lamb,accu_x", "meta": {"hexsha": "8eea120f0dc26c68503da559482489dcaa4ef3c0", "size": 5262, "ext": "py", "lang": "Python", "max_stars_repo_path": "ggtools/gg/lcurve.py", "max_stars_repo_name": "richannan/GGTOOLS", "max_stars_repo_head_hexsha": "7909da988d90de50c82532d97121a3fbcfc0263a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2019-12-16T01:30:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T08:57:07.000Z", "max_issues_repo_path": "ggtools/gg/lcurve.py", "max_issues_repo_name": "richannan/GGTOOLS", "max_issues_repo_head_hexsha": "7909da988d90de50c82532d97121a3fbcfc0263a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-12-23T14:09:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T01:52:53.000Z", "max_forks_repo_path": "ggtools/gg/lcurve.py", "max_forks_repo_name": "richannan/GGTOOLS", "max_forks_repo_head_hexsha": "7909da988d90de50c82532d97121a3fbcfc0263a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2019-12-19T07:01:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T11:26:36.000Z", "avg_line_length": 47.8363636364, "max_line_length": 214, "alphanum_fraction": 0.7075256556, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995782141545, "lm_q2_score": 0.8918110555020057, "lm_q1q2_score": 0.8613999223561072}}
{"text": "import logging\n\nimport numpy as np\n\ndef sigmoid(z):\n    return 1 / (1 + np.exp(-z))\n\ndef propagate(w, b, X, Y):\n    m = X.shape[1]\n\n    # forward propagation\n    A = sigmoid(np.dot(w.T, X) + b)\n    cost = -(1/m) * np.sum(Y*np.log(A) + (1-Y)*np.log(1-A))\n\n    # backward propagation\n    dw = (1/m) * np.dot(X, (A - Y).T)\n    db = (1/m) * np.sum(A - Y)\n\n    cost = np.squeeze(cost)\n\n    grads = { \"dw\": dw, \"db\": db }\n\n    return grads, cost\n\ndef optimize(w, b, X, Y, iterations, learning_rate):\n    costs = []\n\n    for i in range(iterations):\n        grads, cost = propagate(w, b, X, Y)\n\n        w = w - (learning_rate * grads['dw'])\n        b = b - (learning_rate * grads['db'])\n\n        if i % 100 == 0:\n            logging.info(f\"iteration: {i}, cost: {cost}\")\n            costs.append(cost)\n\n        params = { \"w\": w, \"b\": b }\n\n        grads = { \"dw\": grads[\"dw\"], \"db\": grads[\"db\"] }\n\n    return params, grads, costs\n\ndef predict(w, b, X):\n    m = X.shape[1]\n    w = w.reshape(X.shape[0], 1)\n\n    Y_prediction = np.zeros((1,m))\n\n    A = sigmoid(np.dot(w.T, X) + b)\n\n    for i in range(A.shape[1]):\n        if A[0,i] > 0.5:\n            Y_prediction[0, i] = 1\n\n    return Y_prediction\n", "meta": {"hexsha": "54765c59745931bc7bd585bcb86f7561efd174e0", "size": 1188, "ext": "py", "lang": "Python", "max_stars_repo_path": "non_cat/functions.py", "max_stars_repo_name": "babasbot/non_cat", "max_stars_repo_head_hexsha": "89580f24751eedd2c10ec753ed01583935521483", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "non_cat/functions.py", "max_issues_repo_name": "babasbot/non_cat", "max_issues_repo_head_hexsha": "89580f24751eedd2c10ec753ed01583935521483", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "non_cat/functions.py", "max_forks_repo_name": "babasbot/non_cat", "max_forks_repo_head_hexsha": "89580f24751eedd2c10ec753ed01583935521483", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8421052632, "max_line_length": 59, "alphanum_fraction": 0.5033670034, "include": true, "reason": "import numpy", "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995772325382, "lm_q2_score": 0.8918110468756548, "lm_q1q2_score": 0.8613999131485023}}
{"text": "import numpy\nfrom matplotlib import pyplot\n\ndef euler_pc(f, x_end, y0, N):\n    x, dx = numpy.linspace(0, x_end, N+1, retstep=True)\n    y = numpy.zeros((len(y0),N+1))\n    y[:,0] = y0\n    for n in range(N):\n        fn = f(x[n], y[:,n])\n        yp = y[:,n] + dx * fn\n        y[:,n+1] = y[:,n] + dx / 2 * (fn + f(x[n+1], yp))\n    return x, dx, y\n\ndef ab2(f, x_end, y0, N):\n    x, dx = numpy.linspace(0, x_end, N+1, retstep=True)\n    y = numpy.zeros((len(y0),N+1))\n    fn = numpy.zeros((len(y0),N+1))\n    y[:,0] = y0\n    fn[:,0] = f(x[0], y[:,0])\n    x_epc, dx_epc, y_epc = euler_pc(f, dx, y0, 1)\n    y[:,1] = y_epc[:,1]\n    for n in range(1,N):\n        fn[:,n] = f(x[n], y[:,n])\n        y[:,n+1] = y[:,n] + dx * (3 * fn[:,n] - fn[:,n-1]) / 2\n    return x, dx, y\n\nif __name__==\"__main__\":\n\n    def f_sin(x, y):\n        return -numpy.sin(x)\n    print(\"Euler Predictor-Corrector\")\n    x, dx, y = euler_pc(f_sin, 0.5, [1], 5)\n    print(\"dx=\", dx, \"y(0.5)=\", y[0,-1])\n    x, dx, y = euler_pc(f_sin, 0.5, [1], 50)\n    print(\"dx=\", dx, \"y(0.5)=\", y[0,-1])\n    Npoints = 5*2**numpy.arange(1,10)\n    dx_all = 0.5/Npoints\n    errors = numpy.zeros_like(dx_all)\n    for i, N in enumerate(Npoints):\n        x, dx, y = euler_pc(f_sin, 0.5, [1], N)\n        errors[i] = abs(y[0,-1] - numpy.cos(0.5))\n        dx_all[i] = dx\n    pyplot.figure(figsize=(12,6))\n    pyplot.loglog(dx_all, errors, 'kx')\n    pyplot.loglog(dx_all, errors[0]*(dx_all/dx_all[0])**2, 'b-',\n                  label=r\"$\\propto \\Delta x^2$\")\n    pyplot.legend(loc='upper left')\n    pyplot.xlabel(r\"$\\Delta x$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.show()\n    \n    print(\"Adams-Bashforth 2\")\n    x, dx, y = ab2(f_sin, 0.5, [1], 5)\n    print(\"dx=\", dx, \"y(0.5)=\", y[0,-1])\n    x, dx, y = ab2(f_sin, 0.5, [1], 50)\n    print(\"dx=\", dx, \"y(0.5)=\", y[0,-1])\n    Npoints = 5*2**numpy.arange(1,10)\n    dx_all = 0.5/Npoints\n    errors = numpy.zeros_like(dx_all)\n    for i, N in enumerate(Npoints):\n        x, dx, y = ab2(f_sin, 0.5, [1], N)\n        errors[i] = abs(y[0,-1] - numpy.cos(0.5))\n        dx_all[i] = dx\n    pyplot.figure(figsize=(12,6))\n    pyplot.loglog(dx_all, errors, 'kx')\n    pyplot.loglog(dx_all, errors[0]*(dx_all/dx_all[0])**2, 'b-',\n                  label=r\"$\\propto \\Delta x^2$\")\n    pyplot.legend(loc='upper left')\n    pyplot.xlabel(r\"$\\Delta x$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.show()\n    ", "meta": {"hexsha": "19c2b5f010b2e816695c212db98d31a4beca155d", "size": 2361, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/tex/codes/lecture16.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Lectures/tex/codes/lecture16.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Lectures/tex/codes/lecture16.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 32.7916666667, "max_line_length": 64, "alphanum_fraction": 0.5120711563, "include": true, "reason": "import numpy", "num_tokens": 908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995713428387, "lm_q2_score": 0.8918110432813419, "lm_q1q2_score": 0.8613999044242578}}
{"text": "# Question 1, Lab 6\n# AB Satyaprakash, 180123062\n\n# imports \nfrom sympy.abc import t,y\nimport numpy as np\nimport sympy as sp\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# functions \ndef getEulerApproximation(f,X,Y,h):\n    for i in range(1,Y.shape[0]):\n        Y[i]=Y[i-1] + (f.subs({t:X[i-1], y:Y[i-1]})*h)\n\ndef getActualValues(g,X):\n    for i in range(X.shape[0]):\n        Z[i]=g.subs(t,X[i])\n\ndef phi(n, k, x, z):\n\n    prod = 1\n    for i in range(n):\n        if i != k:\n            prod = prod * (z - x[i])\n    \n    return prod \n\ndef lagrangeInterpolation(z, x, fx):\n\n    n = len(x)\n    l = np.empty(n)\n    for i in range(n):\n        l[i] = phi(n,i,x,z)/phi(n,i,x,x[i])\n\n    ans = np.dot(l, fx)\n\n    return ans\n\n# program body\n# t belongs to [1,2] and y(1)=-1, with h = 0.05\na, b, h = 1, 2, 0.05\nX = np.arange(a,b+h/2,h)\nY = np.zeros(X.shape[0])\nZ = np.zeros(X.shape[0])\nY[0] = -1\n\nf = 1/(t**2) - y/t - (y**2) # from question\ng = -1/t\n\ngetEulerApproximation(f,X,Y,h)\ngetActualValues(g,X)\n\nprint('(a)')\ntable={'Evaluate':[], 'Approx':[], 'Actual':[], 'Error':[]}\n\nfor i in range(X.shape[0]):\n    table['Evaluate'].append('y({})'.format(round(X[i],2)))\n    table['Approx'].append(Y[i])\n    table['Actual'].append(Z[i])\n    table['Error'].append(abs(Y[i]-Z[i]))\n\ndf = pd.DataFrame(table,columns=['Evaluate', 'Approx', 'Actual','Error'])\nprint(df)\n\nprint('\\n(b)')\nprint('(I)')\nx = 1.052\nintepolatedVal = lagrangeInterpolation(x,X,Y)\nprint('Estimated value of y({}) from interpolation ={}'.format(x,intepolatedVal))\nprint('Actual value of y = {}'.format(g.subs(t,x)))\nprint('The error between them = {}'.format(abs(intepolatedVal-g.subs(t,x))))\n\nprint('(II)')\nx = 1.555\nintepolatedVal = lagrangeInterpolation(x,X,Y)\nprint('Estimated value of y({}) from interpolation ={}'.format(x,intepolatedVal))\nprint('Actual value of y = {}'.format(g.subs(t,x)))\nprint('The error between them = {}'.format(abs(intepolatedVal-g.subs(t,x))))\n\nprint('(III)')\nx = 1.978\nintepolatedVal = lagrangeInterpolation(x,X,Y)\nprint('Estimated value of y({}) from interpolation ={}'.format(x,intepolatedVal))\nprint('Actual value of y = {}'.format(g.subs(t,x)))\nprint('The error between them = {}'.format(abs(intepolatedVal-g.subs(t,x))))\n\n# plotting the values in the table.\nplt.plot(X,Y, label='Euler Approximation')\nplt.plot(X,Z, label='Actual value')\nplt.xlabel('Value of t')\nplt.ylabel('Value of y')\nplt.title('Comparision between Euler Approx and Actual values of y')\nplt.legend()\nplt.show()\n", "meta": {"hexsha": "8b7f61555e1db352c94cd98910d4904652b93092", "size": 2475, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 6/Code/q3.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 6/Code/q3.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 6/Code/q3.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 25.78125, "max_line_length": 81, "alphanum_fraction": 0.6258585859, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995713428385, "lm_q2_score": 0.8918110353738529, "lm_q1q2_score": 0.8613998967864175}}
{"text": "#!/usr/bin/python\n#   X = GAUSS(N) returns N Legendre points X in (-1,1).\n#\n#   X, C = GAUSS(N) returns also a vector C of weights for\n#   Gauss-Legendre quadrature.\n#\n#   X, C = GAUSS(N, [A, B]) returns the nodes and weeights\n#   for the interval [A, B].\n\nimport numpy as np\n\ndef gauss(N, dom=[-1,1]):\n    x = np.zeros(shape=(N,1))\n    for k in range(N):\n        x[k] = -np.cos((0.5+k)*np.pi/N)\n    tol = 1e-10\n    dx = 1 + 0 *x\n    # Loop until convergence:\n    while np.linalg.norm(dx, np.inf) > tol:\n        # Recurrence relation for Legendre polynomials:\n        Pm2 = 1\n        Pm1 = x\n        for n in range(1,N):\n            P = ( (2*n+1)*Pm1*x - n*Pm2 ) / (n+1)\n            Pm2 = Pm1\n            Pm1 = P\n\n        # Derivative.  See NIST (18.9.17)\n        dPdx = -N * (x*P - Pm2) / (1 - x**2)\n\n        # Newton step:\n        dx = -P / dPdx;\n        # Newton update:\n        x = x + dx;\n\n    # Weights\n    c = 2 / ( (1-x**2) * dPdx**2 );\n\n    # Scale\n    a = dom[0];\n    b = dom[1];\n    x = .5*(b-a)*x + .5*(b+a);\n    c = .5*(b-a)*c;\n\n    return (x, c)\n\nif __name__ == \"__main__\":\n    x, c = gauss(5, [-1, 1])\n    print 'x = ', x\n    print 'c = ', c\n", "meta": {"hexsha": "1b7480ea2d31ed1e2587a94ffc2d989a9aa740ee", "size": 1157, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment_05/src/gauss.py", "max_stars_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_stars_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-28T18:36:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-28T18:36:55.000Z", "max_issues_repo_path": "assignment_05/src/gauss.py", "max_issues_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_issues_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment_05/src/gauss.py", "max_forks_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_forks_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-16T04:26:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-16T04:26:44.000Z", "avg_line_length": 22.6862745098, "max_line_length": 58, "alphanum_fraction": 0.4649956785, "include": true, "reason": "import numpy", "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.894789464699728, "lm_q1q2_score": 0.8613897581959332}}
{"text": "import numpy as np\n\ndef dot_product(vector1, vector2):\n    \"\"\" Implement dot product of the two vectors.\n    Args:\n        vector1: numpy array of shape (x, n)\n        vector2: numpy array of shape (n, x)\n\n    Returns:\n        out: numpy array of shape (x,x) (scalar if x = 1)\n    \"\"\"\n    out = None\n    ### YOUR CODE HERE\n    \n    if(len(np.shape(vector1))==1):\n        vector1.shape=(1,vector1.shape[0]);\n    if(len(np.shape(vector2))==1):\n        vector2.shape=(1,vector2.shape[0]);\n\n    input_size1=np.shape(vector1);\n\n    row=input_size1[0];\n    \n    out = np.ones((row,row));\n    \n    for i in range(row):\n        for j in range(row):\n            x1=vector1[i,];\n            x2=vector2.T[j];\n            out[i,j]=x1.dot(x2);\n\n    if(np.shape(out)==(1,1)):\n        out=out[0,0];\n        \n    ### END YOUR CODE\n    return out\n\ndef matrix_mult(M, vector1, vector2):\n    \"\"\" Implement (vector1.T * vector2) * (M * vector1)\n    Args:\n        M: numpy matrix of shape (x, n)\n        vector1: numpy array of shape (1, n)\n        vector2: numpy array of shape (n, 1)\n\n    Returns:\n        out: numpy matrix of shape (1, x)\n    \"\"\"\n    out = None\n    ### YOUR CODE HERE\n    x=vector1.T*vector2;\n    y=M*vector1;\n    out=x.T.dot(y.T);\n    ### END YOUR CODE\n\n    return out\n\ndef svd(matrix):\n    \"\"\" Implement Singular Value Decomposition\n    Args:\n        matrix: numpy matrix of shape (m, n)\n\n    Returns:\n        u: numpy array of shape (m, m)\n        s: numpy array of shape (k)\n        v: numpy array of shape (n, n)\n    \"\"\"\n    u = None\n    s = None\n    v = None\n    ### YOUR CODE HERE\n    u,s,v=np.linalg.svd(matrix,1,1);\n    ### END YOUR CODE\n\n    return u, s, v\n\ndef get_singular_values(matrix, n):\n    \"\"\" Return top n singular values of matrix\n    Args:\n        matrix: numpy matrix of shape (m, w)\n        n: number of singular values to output\n        \n    Returns:\n        singular_values: array of shape (n)\n    \"\"\"\n    singular_values = None\n    u, s, v = svd(matrix)\n    ### YOUR CODE HERE\n    singular_values=s[0:n];\n    ### END YOUR CODE\n    return singular_values\n\ndef eigen_decomp(matrix):\n    \"\"\" Implement Eigen Value Decomposition\n    Args:\n        matrix: numpy matrix of shape (m, )\n\n    Returns:\n        w: numpy array of shape (m, m) such that the column v[:,i] is the eigenvector corresponding to the eigenvalue w[i].\n    \"\"\"\n    w = None\n    v = None\n    ### YOUR CODE HERE\n    w,v=np.linalg.eig(matrix);\n    ### END YOUR CODE\n    return w, v\n\ndef get_eigen_values_and_vectors(matrix, num_values):\n    \"\"\" Return top n eigen values and corresponding vectors of matrix\n    Args:\n        matrix: numpy matrix of shape (m, m)\n        num_values: number of eigen values and respective vectors to return\n        \n    Returns:\n        eigen_values: array of shape (n)\n        eigen_vectors: array of shape (m, n)\n    \"\"\"\n    w, v = eigen_decomp(matrix)\n    eigen_values = []\n    eigen_vectors = []\n    ### YOUR CODE HERE\n    m=np.shape(matrix)[0];\n    value_sorted=np.argsort(w);\n    eigen_values=w[sorted(value_sorted[-num_values:])];\n    eigen_vectors=np.zeros((m,num_values));\n    for i in range(m):\n        for j in range(num_values):\n            eigen_vectors[i,j]=v[i,value_sorted[-1-j]];\n    ### END YOUR CODE\n    return eigen_values, eigen_vectors\n", "meta": {"hexsha": "2756c654acd8ae6b69a6d1c4f3506af63d731d55", "size": 3275, "ext": "py", "lang": "Python", "max_stars_repo_path": "Computer Vision/CS131/HW0/linalg.py", "max_stars_repo_name": "bayeslabs/AiGym", "max_stars_repo_head_hexsha": "30c126fc2e140f9f164ff3f20638242b230e7e52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2019-07-15T08:26:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T06:29:17.000Z", "max_issues_repo_path": "Computer Vision/CS131/HW0/linalg.py", "max_issues_repo_name": "bayeslabs/AiGym", "max_issues_repo_head_hexsha": "30c126fc2e140f9f164ff3f20638242b230e7e52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2020-03-24T17:18:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:54:37.000Z", "max_forks_repo_path": "Computer Vision/CS131/HW0/linalg.py", "max_forks_repo_name": "bayeslabs/AiGym", "max_forks_repo_head_hexsha": "30c126fc2e140f9f164ff3f20638242b230e7e52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-07-17T09:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T11:20:51.000Z", "avg_line_length": 25.1923076923, "max_line_length": 123, "alphanum_fraction": 0.5789312977, "include": true, "reason": "import numpy", "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976795, "lm_q2_score": 0.8947894583870633, "lm_q1q2_score": 0.8613897549936028}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time     : 2018/11/25 14:27\n# @Author   : Iydon\n# @File     : 7.3.py\n\nimport numpy as np\n\n\ndef jacobi_method(A, b, x0=None):\n    \"\"\"\n    A = L(ow) + D(iag) + U(pper)\n    |ρ(inv(D)*(L+U))| < 1\n    => convergent.\n    \"\"\"\n    A_,b_ = A.copy(),b.copy()\n    diag  = np.diag(A_)\n    shap  = A.shape\n    A_ = np.diag(diag) - A_\n    if x0 is not None:\n        x_ = x0.copy()\n    else:\n        x_ = np.zeros(b.shape)\n    for i in range(shap[0]):\n        A_[i,:] /= diag[i]\n        b_[i,:] /= diag[i]\n    while True:\n        yield x_\n        x_ = A_*x_ + b_\n\n\ndef gauss_seidel(A, b, x0=None):\n    \"\"\"\n    A = L(ow) + D(iag) + U(pper)\n    |ρ(inv(D-L)*U)| < 1\n    => convergent.\n    \"\"\"\n    A_,b_ = A.copy(),b.copy()\n    DL_   = np.tril(A_)\n    U_    = np.triu(A_, 1)\n    if x0 is not None:\n        x_ = x0.copy()\n    else:\n        x_ = np.zeros(b.shape)\n    invDL_ = np.linalg.inv(DL_)\n    A_ = np.matmul( invDL_, U_ )\n    b_ = np.matmul( invDL_, b_ )\n    while True:\n        yield x_\n        x_ = np.matmul(-A_, x_) + b_\n\n\nA  = np.matrix([[3.,-1,1],[3,6,2],[3,3,7]])\nb  = np.matrix([[1.],[0],[4]])\nx0 = np.matrix([[0.],[0],[0]])\nresult = jacobi_method(A, b, x0)\nt = 0\nfor r in result:\n    print(t, r.T)\n    t += 1\n    if t > 10: break\n\nresult = gauss_seidel(A, b, x0)\nt = 0\nfor r in result:\n    print(t, r.T)\n    t += 1\n    if t > 10: break\n", "meta": {"hexsha": "4c46f5c6b8b039fb6712cb89437eb2395b4601ae", "size": 1380, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/HW/7.3.py", "max_stars_repo_name": "Iydon/NumericalAnalysisNotes", "max_stars_repo_head_hexsha": "ef1e37b97522fce9837142d242676fdd16e74712", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-11-08T15:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-02T10:07:33.000Z", "max_issues_repo_path": "MA305/7.3.py", "max_issues_repo_name": "AllenYZB/homework", "max_issues_repo_head_hexsha": "65bd3372df197bec5e152a37cdc1f6f5432b7f3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-13T03:04:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:49:10.000Z", "max_forks_repo_path": "MA305/7.3.py", "max_forks_repo_name": "AllenYZB/homework", "max_forks_repo_head_hexsha": "65bd3372df197bec5e152a37cdc1f6f5432b7f3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-02T05:46:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T23:11:28.000Z", "avg_line_length": 20.0, "max_line_length": 43, "alphanum_fraction": 0.4710144928, "include": true, "reason": "import numpy", "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.9173026584553408, "lm_q1q2_score": 0.8613699613828301}}
{"text": "#!/usr/bin/python\n\n'''\nmjtsai1974@20180606, v1.0, MLE for https://mjtsai1974.github.io/DevBlog/2018/06/06/bayesian-ml-beyes-to-practice/\n\nhttp://www.astroml.org/book_figures/chapter3/fig_gaussian_distribution.html\n\ndist = scipy.stats.norm(...)\n\nWhere ... should be filled in with the desired distribution parameters Once we have defined the distribution parameters in this way, these distribution objects have many useful methods; for example:\n\n    dist.pmf(x) computes the Probability Mass Function at values x in the case of discrete distributions\n    dist.pdf(x) computes the Probability Density Function at values x in the case of continuous distributions\n    dist.rvs(N) computes N random variables distributed according to the given distribution\n'''\n\nimport numpy as np\nfrom scipy.stats import norm\nfrom matplotlib import pyplot as plt\n\n'''\n#----------------------------------------------------------------------\n# This function adjusts matplotlib settings for a uniform feel in the textbook.\n# Note that with usetex=True, fonts are rendered with LaTeX.  This may\n# result in an error if LaTeX is not installed on your system.  In that case,\n# you can set usetex to False.\nfrom astroML.plotting import setup_text_plots\nsetup_text_plots(fontsize=8, usetex=False)\n'''\n\n# Define the given measured weights and the prior(the most current value)\nprior = 14.2\nweights = [13.9, 14.1, 17.5]\nn = len(weights)\n\n# Define the distributions to be plotted\nmu = prior\nsample_variance = np.var(weights, ddof=1)\nsample_std_deviation = np.sqrt(sample_variance)\n\npopulation_variance = np.var(weights, ddof=0)\npopulation_std_deviation = np.sqrt(population_variance)\n\nsigma_values = [sample_std_deviation, population_std_deviation]\nlinestyles = ['-', '--', ':']\ncolours = ['red', 'blue']\ncolours_sample = ['black', 'purple', 'green']\nx_axis = np.linspace(mu - 2 * np.max(sigma_values), mu + 2 * np.max(sigma_values), 100) #use the \n\n# plot the distributions\nfig, ax = plt.subplots(figsize=(5, 3.75))\n\nfor sigma, ls, color in zip(sigma_values, linestyles, colours):\n    # create a gaussian / normal distribution\n    dist = norm(mu, sigma)\n\n    plt.plot(x_axis, dist.pdf(x_axis), ls=ls, c=color,\n             label=r'$\\mu=%.3f,\\ \\sigma=%.3f$' % (mu, sigma))\n\nplt.xlim(mu - 2 * np.max(sigma_values), mu + 2 * np.max(sigma_values))\nplt.ylim(0, 0.45)\n\nplt.xlabel('$x$')\nplt.ylabel(r'$p(x|\\mu,\\sigma)$')\nplt.title('Gaussian Distribution')\n\nplt.legend()\nplt.show()\n\n# plot the new distribution v.s. mother N(prior, sample_std_deviation)\nfig, ax = plt.subplots(figsize=(5, 3.75))\n\nmother_dist = norm(mu, sample_std_deviation)\nweight_sample_sigmas = []\n\nfor w in weights:\n    weight_sigma = 1/(mother_dist.pdf(w) * np.sqrt(2 * np.pi))\n    weight_sample_sigmas.append(weight_sigma)\n\n    print('P({0:5.3f}) of N({1:5.3f},{2:5.3f}) = {3:5.3f} for N({0:5.3f}), the std error {4:5.3f}'.format(w, prior, sample_std_deviation, mother_dist.pdf(w), weight_sigma))\n\n# plot the mother N(prior, sample_std_deviation)\nplt.plot(x_axis, mother_dist.pdf(x_axis), ls='-', c='red',\n             label=r'$\\mu=%.3f,\\ \\sigma=%.3f$' % (mu, sample_std_deviation))\n\n# plot the new N(w_sample, weight_sigma)\nfor w, sigma, ls, color in zip(weights, weight_sample_sigmas, linestyles, colours_sample):\n    dist = norm(w, sigma)  # create a gaussian / normal distribution\n\n    plt.plot(x_axis, dist.pdf(x_axis), ls=ls, c=color,\n             label=r'$\\mu=%.3f,\\ \\sigma=%.3f$' % (w, sigma))\n\nplt.xlim(mu - 2 * np.max(sigma_values), mu + 2 * np.max(sigma_values))\nplt.ylim(0, 0.45)\n\nplt.xlabel('$x$')\nplt.ylabel(r'$p(x|\\mu,\\sigma)$')\nplt.title('Gaussian Distribution')\n\nplt.legend()\nplt.show()\n\n# plot the new distribution v.s. mother N(prior, population_std_deviation)\nfig, ax = plt.subplots(figsize=(5, 3.75))\n\nmother_dist = norm(mu, population_std_deviation)\nweight_population_sigmas = []\n\nfor w in weights:\n    weight_sigma = 1/(mother_dist.pdf(w) * np.sqrt(2 * np.pi))\n    weight_population_sigmas.append(weight_sigma)\n\n    print('P({0:5.3f}) of N({1:5.3f},{2:5.3f}) = {3:5.3f} for N({0:5.3f}), the std error {4:5.3f}'.format(w, prior, population_std_deviation, mother_dist.pdf(w), weight_sigma))\n\n# plot the mother N(prior, sample_std_deviation)\nplt.plot(x_axis, mother_dist.pdf(x_axis), ls='-', c='blue',\n             label=r'$\\mu=%.3f,\\ \\sigma=%.3f$' % (mu, population_std_deviation))\n\n# plot the new N(w_sample, weight_sigma)\nfor w, sigma, ls, color in zip(weights, weight_population_sigmas, linestyles, colours_sample):\n    dist = norm(w, sigma)  # create a gaussian / normal distribution\n\n    plt.plot(x_axis, dist.pdf(x_axis), ls=ls, c=color,\n             label=r'$\\mu=%.3f,\\ \\sigma=%.3f$' % (w, sigma))\n\nplt.xlim(mu - 2 * np.max(sigma_values), mu + 2 * np.max(sigma_values))\nplt.ylim(0, 0.45)\n\nplt.xlabel('$x$')\nplt.ylabel(r'$p(x|\\mu,\\sigma)$')\nplt.title('Gaussian Distribution')\n\nplt.legend()\nplt.show()\n\n# MLE to ask for possible real weight with N(prior, sample std deviation)\nMLE_max = 0\nmu_max = 0\n\nmother_dist = norm(mu, sample_std_deviation)\n\nfor w, sigma in zip(weights, weight_sample_sigmas):\n    dist = norm(w, sigma)\n\n    MLE_now = 1.0\n\n    for j in range(len(weights)):\n        MLE_now = dist.pdf(weights[j]) * mother_dist.pdf(w) * MLE_now\n\n    if MLE_now > MLE_max:\n        MLE_max = MLE_now\n        mu_max = w\n\t\t\nprint('using N(prior, sample std deviation), the MLE for weight {0: 5.3f}'.format(mu_max))\n\n# MLE to ask for possible real weight with N(prior, population std deviation)\nMLE_max = 0\nmu_max = 0\n\nmother_dist = norm(mu, population_std_deviation)\n\nfor w, sigma in zip(weights, weight_sample_sigmas):\n    dist = norm(w, sigma)\n\n    MLE_now = 1.0\n\n    for j in range(len(weights)):\n        MLE_now = dist.pdf(weights[j]) * mother_dist.pdf(w) * MLE_now\n\n    if MLE_now > MLE_max:\n        MLE_max = MLE_now\n        mu_max = w\n\t\t\nprint('using N(prior, population std deviation), the MLE for weight {0: 5.3f}'.format(mu_max))", "meta": {"hexsha": "659738c048ba8087a1b6879f74416fe0421a49da", "size": 5899, "ext": "py", "lang": "Python", "max_stars_repo_path": "template/BayesInferForDogWeightByMLE_Prio.py", "max_stars_repo_name": "mjtsai1974/DevBlog", "max_stars_repo_head_hexsha": "f1429e28e7ea618a64f5e111be4d7f42ae616ce8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "template/BayesInferForDogWeightByMLE_Prio.py", "max_issues_repo_name": "mjtsai1974/DevBlog", "max_issues_repo_head_hexsha": "f1429e28e7ea618a64f5e111be4d7f42ae616ce8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "template/BayesInferForDogWeightByMLE_Prio.py", "max_forks_repo_name": "mjtsai1974/DevBlog", "max_forks_repo_head_hexsha": "f1429e28e7ea618a64f5e111be4d7f42ae616ce8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9022988506, "max_line_length": 198, "alphanum_fraction": 0.6867265638, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102542943774, "lm_q2_score": 0.8902942341267434, "lm_q1q2_score": 0.8612797714333708}}
{"text": "import math\n\nimport numpy as np\n\n\n# Calculates Rotation Matrix given euler angles.\ndef euler_angle_to_rotation_matrix(theta):\n    \"\"\"\n    Converts from theta [yaw, pitch, roll] to a rotation matrix\n    \"\"\"\n\n    R_x = np.array(\n        [\n            [1, 0, 0],\n            [0, math.cos(theta[0]), -math.sin(theta[0])],\n            [0, math.sin(theta[0]), math.cos(theta[0])],\n        ]\n    )\n\n    R_y = np.array(\n        [\n            [math.cos(theta[1]), 0, math.sin(theta[1])],\n            [0, 1, 0],\n            [-math.sin(theta[1]), 0, math.cos(theta[1])],\n        ]\n    )\n\n    R_z = np.array(\n        [\n            [math.cos(theta[2]), -math.sin(theta[2]), 0],\n            [math.sin(theta[2]), math.cos(theta[2]), 0],\n            [0, 0, 1],\n        ]\n    )\n\n    R = np.dot(R_z, np.dot(R_y, R_x))\n\n    return R\n\n\ndef rotation_matrix_to_euler_angle(R):\n    \"\"\"\n    Converts a rotation matrix to [yaw, pitch, roll]\n    \"\"\"\n    yaw = math.atan2(R[1, 0], R[0, 0])\n    pitch = math.atan2(-R[2, 0], math.sqrt(R[2, 1] ** 2 + R[2, 2] ** 2))\n    roll = math.atan2(R[2, 1], R[2, 2])\n\n    return yaw, pitch, roll\n\n\ndef static_transform_to_extrinsic(transform):\n    \"\"\"\n    Calculates the extrinsic matrix for a ROS static_transform_publisher\n\n    Parameters:\n    - transform: a list with [x, y, z yaw, pitch, roll]\n    \"\"\"\n    assert len(transform) == 6\n\n    x, y, z, yaw, pitch, roll = transform\n    rotation = euler_angle_to_rotation_matrix([yaw, pitch, roll])\n    translation = np.array([x, y, z]).reshape(-1, 1)\n    homogeneous = get_homogeneous_transformation(rotation, translation)\n    return homogeneous\n\n\ndef extrinsic_to_static_transform(mat):\n    \"\"\"Converts an extrinsic matrix into rotational and translational components.\n\n    Args:\n        mat (np.array): a 4x4 extrinsic matrix\n\n    Returns:\n        np.array: a 1x6 np.array of form x, y, z, yaw, pitch, roll\n    \"\"\"\n    x, y, z = mat[:3, 3]\n    yaw, pitch, roll = rotation_matrix_to_euler_angle(mat)\n\n    return np.array([x, y, z, yaw, pitch, roll])\n\n\ndef get_homogeneous_transformation(rotation, translation):\n    \"\"\"\n    Parameters:\n    - rotation: a 3x3 rotation np array\n    - translation: a 3x1 translation np array\n    \"\"\"\n    homogeneous = np.zeros((4, 4))\n    homogeneous[-1][-1] = 1\n    homogeneous[:3, :3] = rotation\n    homogeneous[:3, -1:] = translation\n    return homogeneous\n\n\ndef get_relative_transformation(a_to_base, b_to_base):\n    \"\"\"\n    Finds the relative transformation from a to b given transformations for both\n    relative to base_link.\n\n    See: https://stackoverflow.com/a/55169091/6942666 for more details\n\n    Parameters:\n    - a_to_base: 4x4 np.array representing homoegenous transformation of a to base_link\n    - b_to_base: 4x4 np.array representing homoegenous transformation of b to base_link\n    \"\"\"\n\n    base_to_a = np.linalg.inv(a_to_base)\n    return base_to_a @ b_to_base\n\n\nif __name__ == \"__main__\":\n    \"\"\"\n    <node pkg=\"tf\" type=\"static_transform_publisher\"\n        respawn=\"true\"\n        name=\"camera_static_transform_publisher\"\n        args=\"0.5080 0.0 0.1778 0 0.05 0 base_link camera 100\"\n    />\n\n    <node pkg=\"tf\" type=\"static_transform_publisher\"\n        respawn=\"true\"\n        name=\"velodyne_static_transform_publisher\"\n        args=\"0.4445 0.0 0.09525 0.0 0.06981 0.0 base_link velodyne 100\"\n    />\n\n    Camera static transform:\n    [[ 0.99875026  0.          0.04997917  0.508     ]\n    [ 0.          1.          0.          0.        ]\n    [-0.04997917  0.          0.99875026  0.1778    ]\n    [ 0.          0.          0.          1.        ]]\n\n    Velodyne static transform:\n    [[ 0.99756427  0.          0.06975331  0.4445    ]\n    [ 0.          1.          0.          0.        ]\n    [-0.06975331  0.          0.99756427  0.09525   ]\n    [ 0.          0.          0.          1.        ]]\n\n    Camera relative to Velodyne\n    [[ 0.99980379  0.          0.0198087  -0.05929486]\n    [ 0.          1.          0.          0.        ]\n    [-0.0198087   0.          0.99980379 -0.08562051]\n    [ 0.          0.          0.          1.        ]]\n\n    Overall camera to velodyne transform\n    Translation (x, y, z): -0.059294861111785835 0.0 -0.08562051124429254\n    Rotation (y, p, r): 0.0 0.019810000000000008 0.0\n    \"\"\"\n\n    print(\"Camera static transform: \")\n    # Add values for the camera to base here\n    camera_to_base = static_transform_to_extrinsic([0.5080, 0.0, 0.1778, 0, 0.05, 0])\n    print(camera_to_base)\n\n    print(\"Velodyne static transform: \")\n    # Add values for the velodyne to base here\n    velodyne_to_base = static_transform_to_extrinsic(\n        [0.4445, 0.0, 0.09525, 0.0, 0.06981, 0.0]\n    )\n    print(velodyne_to_base)\n\n    print(\"Camera relative to Velodyne\")\n    # Add values for the camera to velodyne here\n    camera_to_velodyne = get_relative_transformation(camera_to_base, velodyne_to_base)\n    print(camera_to_velodyne)\n\n    print(\"Overall camera to velodyne transform\")\n    x, y, z, yaw, pitch, roll = extrinsic_to_static_transform(camera_to_velodyne)\n    print(\"Translation (x, y, z):\", x, y, z)\n    print(\"Rotation (y, p, r):\", yaw, pitch, roll)\n", "meta": {"hexsha": "853d687d8f417fe6960b64e528274cbcafef296a", "size": 5095, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/universal_devkit/scripts/calculate_extrinsic_matrix.py", "max_stars_repo_name": "EricWiener/universal-devk", "max_stars_repo_head_hexsha": "09ecc32617cb7b61a106dbbb322a22d4969cd92b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-26T21:03:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T12:43:21.000Z", "max_issues_repo_path": "src/universal_devkit/scripts/calculate_extrinsic_matrix.py", "max_issues_repo_name": "EricWiener/universal-devk", "max_issues_repo_head_hexsha": "09ecc32617cb7b61a106dbbb322a22d4969cd92b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-03-06T17:55:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-19T23:31:19.000Z", "max_forks_repo_path": "src/universal_devkit/scripts/calculate_extrinsic_matrix.py", "max_forks_repo_name": "EricWiener/universal-devk", "max_forks_repo_head_hexsha": "09ecc32617cb7b61a106dbbb322a22d4969cd92b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-13T16:45:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T18:19:17.000Z", "avg_line_length": 29.9705882353, "max_line_length": 87, "alphanum_fraction": 0.5860647694, "include": true, "reason": "import numpy", "num_tokens": 1574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102571131692, "lm_q2_score": 0.8902942312159384, "lm_q1q2_score": 0.8612797711269823}}
{"text": "#################################\n## Preamble\n# import necessary modules/tools\nimport math\nimport numpy as np\nimport os\nimport pandas as pd\nimport scipy as sc\nimport sympy as sp\nimport sys\nfrom types import FunctionType\n#   #   #   #   #   #   #   #   #\n\n#################################\n## Universal Variables/Methods/Classes\n# common functions\ndef diagonality(matrix):\n\t\"\"\"Determines if matrix is strictly, diagonally dominant.\n\n\tParameters\n\t----------\n\tmatrix : array\n\t\tInput matrix to be tested.\n\n\tReturns\n\t-------\n\tis_strict_diagonal_matrix : boolean\n\t\tTruth value whether matrix is strictly, diagonally dominant.\n\n\tRaises\n\t------\n\tIndexError\n\t\tMatrix of interest must be square.\n\n\tWarnings\n\t--------\n\tWill print to console either if strictly, diagonally dominant, or if matrix, `A` is not strictly, diagonally dominant which could lead to poor solution of 'Ax = b'.\n\t\"\"\"\n\tmatrix_name, A = \"A\", np.array(matrix)\n\tif not(np.sum(np.shape(A)) - np.shape(A)[0] == np.shape(A)[0]):\n\t\traise IndexError(f\"ERROR! Matrix, {matrix_name} must be square!\")\n\ti, diags, long = 0, np.zeros_like(A), np.zeros_like(A)\n\twhile i < len(A):\n\t\tj = 0\n\t\twhile j < len(A):\n\t\t\taij = A[i][j]\n\t\t\tif i == j: long[i][j] = aij\n\t\t\telse: diags[i][j] = aij\n\t\t\tj += 1\n\t\ti += 1\n\tif np.sum(long) >= np.sum(diags):\n\t\tprint(f\"Information: Matrix, {matrix_name} is strictly, diagonally dominant.\")\n\t\tis_strict_diagonal_matrix = True\n\telse:\n\t\tis_strict_diagonal_matrix = False\n\t\tprint(f\"Warning! Matrix, {matrix_name} is not strictly, diagonally dominant. Solution may be inaccurate.\")\n\treturn is_strict_diagonal_matrix\n\ndef eigen_values(matrix):\n\t\"\"\"Directly finds eigenvalues of matrix by its determinant. Not recommended for large, sparse matrices.\n\n\tParameters\n\t----------\n\tmatrix : array\n\t\tMatrix of interest.\n\n\tReturns\n\t-------\n\tlambdas : array\n\t\tEigenvector containing roots.\n\n\tRaises\n\t------\n\tIndexError\n\t\tMatrix of interest must be square.\n\t\"\"\"\n\t# See Also\n\t# --------\n\tmatrix_name, A = \"A\", np.array(matrix)\n\tif not(np.sum(np.shape(A)) - np.shape(A)[0] == np.shape(A)[0]):\n\t\traise IndexError(f\"ERROR! Matrix, {matrix_name} must be square!\")\n\tsym_r = sp.Symbol(\"r\")\n\ti, identityA = 0, np.zeros_like(A)\n\twhile i < len(A):\n\t\tj = 0\n\t\twhile j < len(A[0]):\n\t\t\tif i == j: identityA[i][j] = 1\n\t\t\tj += 1\n\t\ti += 1\n\tlambda_identity = identityA*sym_r\n\tdeterminant = sp.det(sp.Matrix(A - lambda_identity))\n\troots = sp.solve(determinant)\n\tlambdas = []\n\tfor r in roots:\n\t\tr = complex(r)\n\t\tif np.imag(r) == 0: r = np.real(r)\n\t\tlambdas.append(r)\n\treturn lambdas\n# preceded by eigen_values\ndef spectral_radius(matrix):\n\t\"\"\"Finds the spectral radius of matrix.\n\n\tParameters\n\t----------\n\tmatrix : array\n\t\tMatrix of interest.\n\n\tReturns\n\t-------\n\trho : float\n\t\tSpectral radius.\n\n\tRaises\n\t------\n\tIndexError\n\t\tMatrix of interest must be square.\n\n\tSee Also\n\t--------\n\teigen_values() : Function to find eigenvector of A.\n\t\"\"\"\n\tmatrix_name, A = \"A\", np.array(matrix)\n\tif not(np.sum(np.shape(A)) - np.shape(A)[0] == np.shape(A)[0]):\n\t\traise IndexError(f\"ERROR! Matrix, {matrix_name} must be square!\")\n\trho = np.max(np.abs(eigen_values(A)))\n\treturn rho\n# preceded by spectral_radius\nclass norms:\n\tdef __init__(self, x, x0=[]):\n\t\t\"\"\"\n\t\tParameters\n\t\t----------\n\t\tx : array\n\t\t\tNewly approximated array.\n\n\t\tx0 : array, optional\n\t\t\tPreviously approximated array.\n\n\t\tYields\n\t\t------\n\t\tself.vec_name : string\n\t\t\tConnote symbol name as 'x'.\n\n\t\tself.x : array\n\t\t\tNewly approximated array.\n\n\t\tself.old_vec_name : string\n\t\t\tConnote symbol name as 'x0'.\n\n\t\tself.x0 : array\n\t\t\tPreviously approximated array.\n\n\t\tRaises\n\t\t------\n\t\tIndexError\n\t\t\tIf the input vectors are not the same length.\n\t\t\"\"\"\n\t\tself.vec_name, self.x = \"x\", np.array(x)\n\t\tself.old_vec_name, self.x0 = \"x0\", np.array(x0)\n\t\tif not(self.x0.shape[0] == 0 or len(x) == len(x0)):\n\t\t\traise IndexError(f\"ERROR! {self.vec_name}, and {self.old_vec_name} must be the same size!\")\n\n\tdef l_infinity(self):\n\t\t\"\"\"Maximum difference between absolute sum of i'th rows.\n\n\t\tReturns\n\t\t-------\n\t\tnorm : float\n\t\t\tScalar value.\n\n\t\tYields\n\t\t------\n\t\tself.norm : float\n\t\t\tScalar value.\n\n\t\tRaises\n\t\t------\n\t\tIndexError\n\t\t\tIf the input vectors are not the same length.\n\n\t\tNotes\n\t\t-----\n\t\tBest thought as \"actual\" distance between vectors.\n\n\t\tAlso calculates infinity norm of matrix(ces).\n\n\t\tExamples\n\t\t--------\n\t\t[x0] = (1, 1, 1)^(t)\n\n\t\t[x] = (1.2001, 0.99991, 0.92538)^(t)\n\n\t\t||x0 - x|| = max{|1 - 1.2001|, |1 - 0.99991|, |1 - 0.92538|}\n\n\t\t||x0 - x|| = 0.2001\n\t\t\"\"\"\n\t\tvec_name, x = self.vec_name, self.x\n\t\told_vec_name, x0 = self.old_vec_name, self.x0\n\t\t# initialize loop\n\t\tnorm_i = np.zeros_like(x)\n\t\tif x0.shape[0] == 0:\n\t\t\tif np.sum(x.shape) == x.shape[0]:\n\t\t\t\tfor i in range(x.shape[0]):\n\t\t\t\t\t# evaluate and store norm, ||.||\n\t\t\t\t\tnorm_i[i] = abs(x[i])\n\t\t\telif np.sum(x.shape) > x.shape[0]:\n\t\t\t\tnorm_ij = np.zeros_like(x)\n\t\t\t\tfor i in range(x.shape[0]):\n\t\t\t\t\tfor j in range(x.shape[1]):\n\t\t\t\t\t\t# evaluate and store norm, ||.||\n\t\t\t\t\t\tnorm_ij[i][j] = abs(x[i][j])\n\t\t\t\t\tnorm_i[i] = np.sum(norm_ij[i][:])\n\t\telif len(x) == len(x0):\n\t\t\tif np.sum(x0.shape) == x0.shape[0]:\n\t\t\t\tfor i in range(x0.shape[0]):\n\t\t\t\t\tnorm_i[i] = abs(x[i] - x0[i])\n\t\t\telif np.sum(x0.shape) > x0.shape[0]:\n\t\t\t\tif np.sum(x.shape) == np.sum(x0.shape):\n\t\t\t\t\tfor i in range(x0.shape[0]):\n\t\t\t\t\t\tfor j in range(x0.shape[1]):\n\t\t\t\t\t\t\tnorm_ij = np.zeros_like(x)\n\t\t\t\t\t\t\t# evaluate and store norm, ||.||\n\t\t\t\t\t\t\tnorm_ij[i][j] = abs(x[i][j] - x0[i][j])\n\t\t\t\t\t\tnorm_i[i] = np.sum(norm_ij[i][:])\n\t\t\t\telif np.sum(x.shape) == np.sum(x0.shape):\n\t\t\t\t\tfor i in range(x0.shape[0]):\n\t\t\t\t\t\t# evaluate and store norm, ||.||\n\t\t\t\t\t\tnorm_i[i] = abs(x[i] - x0[i])\n\t\telse:\n\t\t\traise IndexError(f\"ERROR! {vec_name}, and {old_vec_name} must be the same size!\")\n\t\t# if no errors, then evaluate norm\n\t\tself.norm = np.amax(norm_i)\n\t\t# return the l_infinity norm\n\t\treturn self.norm\n\n\tdef l_two(self):\n\t\t\"\"\"Square root of sum of differences squared along i'th row.\n\n\t\tReturns\n\t\t-------\n\t\tnorm : float\n\t\t\tScalar value.\n\n\t\tYields\n\t\t------\n\t\tself.norm : float\n\t\t\tScalar value.\n\n\t\tRaises\n\t\t------\n\t\tIndexError\n\t\t\tIf the input vectors are not the same length.\n\n\t\tSee Also\n\t\t--------\n\t\tspectral_radius() : Function to find the spectral radius of vector.\n\n\t\tExamples\n\t\t--------\n\t\t[x0] = (1, 1, 1)^(t)\n\n\t\t[x] = (1.2001, 0.99991, 0.92538)^(t)\n\n\t\t||x0 - x|| = sqrt[ (1 - 1.2001)^2 \\\n\t\t\t+ (1 - 0.99991)^2 + (1 - 0.92538)^2 ]\n\n\t\t||x0 - x|| = 0.21356\n\t\t\"\"\"\n\t\tvec_name, x = self.vec_name, self.x\n\t\told_vec_name, x0 = self.old_vec_name, self.x0\n\t\tif x0.shape[0] == 0:\n\t\t\t# initialize loop\n\t\t\tnorm_i = np.zeros_like(x)\n\t\t\tif np.sum(x.shape) == x.shape[0]:\n\t\t\t\tfor i in range(len(x)):\n\t\t\t\t\t# evaluate and store norm, ||.||\n\t\t\t\t\tnorm_i[i] += x[i]**2\n\t\t\t\tnorm = math.sqrt(np.sum(norm_i))\n\t\t\telif np.sum(x.shape) > x.shape[0]:\n\t\t\t\tx0 = np.reshape(x, (x.shape[0], x.shape[1]))\n\t\t\t\txt = np.reshape(x, (x.shape[1], x.shape[0]))\n\t\t\t\tnorm = math.sqrt(spectral_radius(x0*xt))\n\t\telif len(x) == len(x0):\n\t\t\tif np.sum(x0.shape) > x0.shape[0]:\n\t\t\t\tx0 = np.reshape(x0, (x0.shape[0], x0.shape[1]))\n\t\t\t\txt = np.reshape(x, (x0.shape[1], x0.shape[0]))\n\t\t\telse:\n\t\t\t\tx0 = np.reshape(x0, (len(x0), 1))\n\t\t\t\txt = np.reshape(x, (1, len(x0)))\n\t\t\t\t# xt = np.reshape(x, (1, x.shape[0]))\n\t\t\tnorm = math.sqrt(spectral_radius(x0*xt))\n\t\telse:\n\t\t\traise IndexError(f\"ERROR! {vec_name}, and {old_vec_name} must be the same size!\")\n\t\tself.norm = norm\n\t\treturn norm\n# preceded by norms.()l_infinity() and norms().l_two()\ndef condition_number(matrix, norm_type=\"l_two\"):\n\t\"\"\"Find the condition number of a given matrix and norm type.\n\n\tParameters\n\t----------\n\tmatrix : array\n\t\tInput matrix for analysis.\n\n\tnorm_type : string, optional\n\t\tSelects norm comparison which is 'l_two' by default.\n\n\tReturns\n\t-------\n\tk : float\n\t\tCondition number of matrix, A.\n\n\tWarnings\n\t--------\n\tWill output evaluation of condition number and show in console.\n\n\tSee Also\n\t--------\n\tnorms().l_two() : Method that yields the l_2 norm.\n\n\tnorms().l_infinity() : Method that yields the l_infinity norm.\n\t\"\"\"\n\tmatrix_name, A = \"A\", np.array(matrix)\n\ti, A_inv = 0, np.zeros_like(A)\n\twhile i < len(A):\n\t\tj = 0\n\t\twhile j < len(A):\n\t\t\taij = A[i][j]\n\t\t\tif aij != 0: A_inv[i][j] = 1/aij\n\t\t\tj += 1\n\t\ti += 1\n\tif norm_type == \"l_infinity\":\n\t\tnorm, abnorm = norms(A).l_infinity(), norms(A_inv).l_infinity()\n\telif norm_type == \"l_two\":\n\t\tnorm, abnorm = norms(A).l_two(), norms(A_inv).l_two()\n\tk = norm*abnorm\n\tprint(f\"Information: Condition Number K({matrix_name}) = {k}\")\n\treturn k\n\ndef make_array(domain, function, variable=sp.Symbol(\"x\")):\n\t\"\"\"Maps domain to range.\n\n\tParameters\n\t----------\n\tdomain : array\n\t\tCollection if input data.\n\n\tfunction : expression\n\t\tFunction that maps the domain to range.\n\n\tvariable : string, optional\n\t\tSympy symbol or string representation of variable to respect in function.\n\n\tReturns\n\t-------\n\tg : tuple\n\t\tMapped range from function.\n\n\tWarnings\n\t--------\n\tPrints to console the input expression, and that the expression was in fact used.\n\t\"\"\"\n\tif isinstance(function, (FunctionType, sp.Expr)):\n\t\tsym_function = sp.N(sp.sympify(function(variable)))\n\t\tfunction = sp.lambdify(variable, sym_function)\n\t\tprint(f\"Information: Input expression, {sym_function} used.\")\n\ti, X, g = 0, np.array(domain), np.zeros_like(domain)\n\twhile i < len(X):\n\t\tj = 0\n\t\tif np.sum(X.shape) > np.sum(X.shape[0]):\n\t\t\twhile j < len(X[0]):\n\t\t\t\tg[i][j] = (function(X[i][j]))\n\t\t\t\tj += 1\n\t\telse: g[i] = function(X[i])\n\t\ti += 1\n\treturn tuple(g)\n\ndef symmetry(matrix):\n\t\"\"\"Determines boolean truth value whether given matrix is symmetric.\n\n\tParameters\n\t----------\n\tmatrix : array\n\t\tMatrix of interest.\n\n\tReturns\n\t-------\n\tis_symmetric : bool\n\t\tTrue if symmetric, else False.\n\n\tRaises\n\t------\n\tIndexError\n\t\tMatrix of interest must be square.\n\n\tWarnings\n\t--------\n\tConsole print that A is either symmetric or asymmetric.\n\t\"\"\"\n\tmatrix_name, A = \"A\", np.array(matrix)\n\tif not(np.sum(np.shape(A)) - np.shape(A)[0] == np.shape(A)[0]):\n\t\traise IndexError(f\"ERROR! Matrix, {matrix_name} must be square!\")\n\ti, At, is_symmetric = 0, np.transpose(A), False\n\tfor ai in A:\n\t\tj = 0\n\t\tfor aj in ai:\n\t\t\tif aj == At[i][j]: is_symmetric = True\n\t\t\telse:\n\t\t\t\tis_symmetric = False\n\t\t\t\tprint(f\"Warning! Matrix, {matrix_name} is not symmetric.\")\n\t\t\t\treturn is_symmetric\n\t\t\tj += 1\n\t\ti += 1\n\tif is_symmetric: print(f\"Information: Matrix, {matrix_name} is symmetric.\")\n\treturn is_symmetric\n\ndef tridiagonality(matrix):\n\t\"\"\"Determine boolean truth value whether given matrix is tridiagonal.\n\n\tParameters\n\t----------\n\tmatrix : array\n\t\tMatrix of interest.\n\n\tReturns\n\t-------\n\tis_tridiagonal : bool\n\t\tTrue if tridiagonal, else False.\n\n\tRaises\n\t------\n\tIndexError\n\t\tMatrix of interest must be square.\n\n\tWarnings\n\t--------\n\tPrints to console that matrix is either tridiagonal or not.\n\t\"\"\"\n\tmatrix_name, A = \"A\", np.array(matrix)\n\tif not(np.sum(np.shape(A)) - np.shape(A)[0] == np.shape(A)[0]):\n\t\traise IndexError(f\"ERROR! Matrix, {matrix_name} must be square!\")\n\tdiagonals = np.diagflat(np.diag(A))\n\tabove = np.diagflat(np.diag(A, k=1), k=1)\n\tbelow = np.diagflat(np.diag(A, k=-1), k=-1)\n\tnon_A = A - (diagonals + above + below)\n\tif np.sum(non_A) != 0:\n\t\tis_tridiagonal = False\n\t\tprint(f\"Warning! Matrix, {matrix_name} is not tridiagonal.\")\n\telse:\n\t\tis_tridiagonal = True\n\t\tprint(f\"Information: Matrix, {matrix_name} is tridiagonal.\")\n\treturn is_tridiagonal\n#   #   #   #   #   #   #   #   #\n\n\n#################################\n## Specific Functions\n# --------------------\n# eigenvalue solvers\nclass DirectSolver:\n\tdef __init__(self, A, power, max_iter=100):\n\t\t\"\"\"\n\t\tParameters\n\t\t----------\n\t\tA : tuple\n\t\t\tCharacteristic matrix.\n\n\t\tpower : int\n\t\t\tSigned power to which function error must be within.\n\n\t\tmax_iter : int, optional\n\t\t\tMaximum iterations for which function may loop.\n\n\t\tYields\n\t\t------\n\t\tself.A : tuple\n\t\t\tEither input functions or matrix of characteristic values.\n\n\t\tself.tol : float\n\t\t\tSpecified tolerance to which method terminates.\n\n\t\tself.max_iter : int\n\t\t\tMaximum iterations allowed for method.\n\n\t\tself.is_diagonal : bool\n\t\t\tTruth value of whether matrix is diagonal.\n\n\t\tself.eigenvalues : tuple\n\t\t\tEigenvalues of characteristic matrix, A.\n\n\t\tself.spectral_radius : float\n\t\t\tSpectral radius of characteristic matrix, A.\n\n\t\tself.condition_number : float\n\t\t\tCondition number of characteristic matrix, A.\n\n\t\tRaises\n\t\t------\n\t\tIndexError\n\t\t\tMatrix of interest must be square.\n\n\t\tValueError\n\t\t\tIf iterations constraint is not an integer.\n\n\t\tWarnings\n\t\t--------\n\t\tNot recommended to use eigen_values() to find eigenvalues of characteristic matrix, A; therefore, do not use eigen_values() if matrix, A is a large, sparse matrix if desiring quick calculations.\n\n\t\tSee Also\n\t\t--------\n\t\teigen_values() : Function to find eigenvalues of A.\n\n\t\tspectral_radius() : Function that finds the spectral radius of characteristic matrix, A.\n\n\t\tNotes\n\t\t-----\n\t\tSpecified tolerance evaluated by `10**power`.\n\n\t\t`norm_type` may be either `'l_infinity'` or `'l_two'` but is 'l_infinity' by default.\n\n\t\tIf `self.is_diagonal` is True, then matrix is diagonal. Else, not diagonal.\n\t\t\"\"\"\n\t\tmatrix_name, A = \"A\", np.array(A)\n\t\tif np.sum(A.shape[0]) != np.sum(A.shape[1]): raise IndexError(f\"ERROR! Matrix, {matrix_name} must be square!\")\n\t\tif max_iter <= 0 or not isinstance(max_iter, (int, float)): raise ValueError(f\"ERROR! Maximum iterations, N must be an integer greater than zero. {max_iter} was given and not understood.\")\n\t\tself.A = A\n\t\tself.tol = float(10**power)\n\t\tself.max_iter = int(max_iter)\n\t\tself.is_diagonal = diagonality(A)\n\t\tself.is_tridiagonal = tridiagonality(A)\n\t\t# self.eigen_values = eigen_values(A)\n\t\t# self.spectral_radius = spectral_radius(A)\n\t\t# self.condition_number = condition_number(A, norm_type)\n\n\tdef power_method(self, x):\n\t\t\"\"\"Approximate the dominant eigenvalue and associated eigenvector of matrix, A given some non-zero vector, x.\n\n\t\tParameters\n\t\t----------\n\t\tx : array\n\t\t\tNumpy array.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.DataFrame : dataframe\n\t\t\tSummarized dataframe from iterations.\n\n\t\tYields\n\t\t------\n\t\tself.x : tuple\n\t\t\tInitial guess at eigenvector.\n\n\t\tself.iterations : tuple\n\t\t\tCollection of iterations through method.\n\n\t\tself.mu : tuple\n\t\t\tCollection of approximately largest eigenvalue.\n\n\t\tself.lambdas : tuple\n\t\t\tCollection of approximate eigenvectors.\n\n\t\tself.errors : tuple\n\t\t\tCollection of yielded norms.\n\n\t\tRaises\n\t\t------\n\t\tIndexError\n\t\t\tIf x is neither n x 1 nor 1 x n array.\n\t\t\"\"\"\n\t\tA, tol, N = self.A, self.tol, self.max_iter\n\t\tvec_name, x = \"x\", np.array(x)\n\t\tif np.sum(x.shape) - np.sum(x.shape[0]) > 1: raise IndexError(f\"Systems vector, {vec_name} must be n x 1 or 1 x n array!\")\n\t\tself.x = np.reshape(x,(len(x),1))\n\t\tmu = [norms(x).l_infinity()]\n\t\tx = x/mu[-1]\n\t\tk, eigenvectors, errors = 1, [x], [1]\n\t\twhile errors[-1] > tol and k <= N:\n\t\t\ty = np.matmul(A, x)\n\t\t\tfor yi in y:\n\t\t\t\tif np.abs(yi) == norms(y).l_infinity():\n\t\t\t\t\typ = float(yi)\n\t\t\tmu.append(yp)\n\t\t\teigenvectors.append(y/yp)\n\t\t\terrors.append(norms(x, eigenvectors[-1]).l_infinity())\n\t\t\tx = eigenvectors[-1]\n\t\t\tk += 1\n\t\tself.iterations = tuple(range(k))\n\t\tself.mu = tuple(mu)\n\t\tself.lambdas = tuple(eigenvectors)\n\t\tself.errors = tuple(errors)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Mu\": self.mu, \"Lambdas\": self.lambdas, \"Errors\": self.errors})\n\n\tdef inverse_power_method(self, x, q):\n\t\t\"\"\"Approximate eigenvalue closest to target, q and associated eigenvector of matrix, A given some non-zero vector, x.\n\n\t\tParameters\n\t\t----------\n\t\tx : array\n\t\t\tNumpy array.\n\n\t\tq : float\n\t\t\tTarget to which the closest eigenvalue of matrix will be found.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.DataFrame : dataframe\n\t\t\tSummarized dataframe from iterations.\n\n\t\tYields\n\t\t------\n\t\tself.x : tuple\n\t\t\tInitial guess at eigenvector.\n\n\t\tself.iterations : tuple\n\t\t\tCollection of iterations through method.\n\n\t\tself.mu : tuple\n\t\t\tCollection of approximately largest eigenvalue.\n\n\t\tself.lambdas : tuple\n\t\t\tCollection of approximate eigenvectors.\n\n\t\tself.errors : tuple\n\t\t\tCollection of yielded norms.\n\n\t\tRaises\n\t\t------\n\t\tIndexError\n\t\t\tIf x is neither n x 1 nor 1 x n array.\n\t\t\"\"\"\n\t\tA, tol, N = self.A, self.tol, self.max_iter\n\t\tvec_name, x = \"x\", np.array(x)\n\t\tif np.sum(x.shape) - np.sum(x.shape[0]) > 1: raise IndexError(f\"Systems vector, {vec_name} must be n x 1 or 1 x n array!\")\n\t\tself.x = np.reshape(x,(len(x),1))\n\t\tself.q = float(q)\n\t\tA = np.linalg.inv(A-q*np.identity(len(A)))\n\t\tmu = [1/norms(x).l_infinity() + q]\n\t\tk, eigenvectors, errors = 1, [x], [1]\n\t\twhile errors[-1] > tol and k <= N:\n\t\t\ty = np.matmul(A, x)\n\t\t\tfor yi in y:\n\t\t\t\tif np.abs(yi) == norms(y).l_infinity():\n\t\t\t\t\typ = float(yi)\n\t\t\tmu.append(1/yp + q)\n\t\t\teigenvectors.append(y/yp)\n\t\t\terrors.append(norms(x, x0=eigenvectors[-1]).l_infinity())\n\t\t\tx = eigenvectors[-1]\n\t\t\tk += 1\n\t\tself.iterations = tuple(range(k))\n\t\tself.mu = tuple(mu)\n\t\tself.lambdas = tuple(eigenvectors)\n\t\tself.errors = tuple(errors)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Mu\": self.mu, \"Lambdas\": self.lambdas, \"Errors\": self.errors})\n\n\tdef qr_algorithm(self):\n\t\t\"\"\"Approximate dominant eigenvalue and associated eigenvector of matrix, A.\n\n\t\tSource: https://www.youtube.com/watch?v=FAnNBw7d0vg\n\n\t\tReturns\n\t\t-------\n\t\tpandas.DataFrame : dataframe\n\t\t\tSummarized dataframe from iterations.\n\n\t\tYields\n\t\t------\n\t\tself.iterations : tuple\n\t\t\tCollection of iterations through method.\n\n\t\tself.lambdas : tuple\n\t\t\tCollection of approximate eigenvectors.\n\n\t\tself.errors : tuple\n\t\t\tCollection of yielded norms.\n\t\t\"\"\"\n\t\tA, tol, N = self.A, self.tol, self.max_iter\n\t\tk, eigenvectors, errors = 1, [np.diag(A)], [1]\n\t\twhile errors[-1] > tol and k <= N:\n\t\t\tQ = np.zeros_like(A, dtype=float)\n\t\t\tR = np.zeros_like(A, dtype=float)\n\t\t\tQI = []\n\t\t\tfor j in range(len(A[0])):\n\t\t\t\tai = np.array(np.zeros(len(A)))\n\t\t\t\tfor i in range(len(A)):\n\t\t\t\t\tai[i] = A[i][j]\n\t\t\t\tai_perp = 0\n\t\t\t\tfor i in range(j):\n\t\t\t\t\tR[i][j] = np.dot(ai, QI[i])\n\t\t\t\t\tai_perp += R[i][j]*QI[i]\n\t\t\t\tai -= ai_perp\n\t\t\t\tR[j][j] = np.sqrt(np.sum(ai**2))\n\t\t\t\tqi = ai/R[j][j]\n\t\t\t\tQI.append(qi)\n\t\t\t\ti = 0\n\t\t\t\tfor q in qi:\n\t\t\t\t\tQ[i][j] = q\n\t\t\t\t\ti += 1\n\t\t\tA = np.matmul(R, Q)\n\t\t\teigenvectors.append(np.diag(A))\n\t\t\terr = np.average([norms(np.diag(A, k=-1)).l_infinity(), norms(np.diag(A, k=1)).l_infinity()])\n\t\t\terrors.append(err)\n\t\t\tk += 1\n\t\tself.iterations = tuple(range(k))\n\t\tself.lambdas = tuple(eigenvectors)\n\t\tself.errors = tuple(errors)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Lambdas\": self.lambdas, \"Errors\": self.errors})\n\n\tdef steepest_descent(self, x, b):\n\t\t\"\"\"Approximate solution vector, x given matrix, A initial guess vector, x, and vector, b.\n\n\t\tParameters\n\t\t----------\n\t\tx : array\n\t\t\tNumpy array.\n\n\t\tb : array\n\t\t\tInput numpy array.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.DataFrame : dataframe\n\t\t\tSummarized dataframe from iterations.\n\n\t\tYields\n\t\t------\n\t\tself.x : tuple\n\t\t\tInitial guess at eigenvector.\n\n\t\tself.b : tuple\n\t\t\tInput numpy array.\n\n\t\tself.iterations : tuple\n\t\t\tCollection of iterations through method.\n\n\t\tself.lambdas : tuple\n\t\t\tCollection of approximate eigenvectors.\n\n\t\tself.errors : tuple\n\t\t\tCollection of yielded norms.\n\n\t\tRaises\n\t\t------\n\t\tIndexError\n\t\t\tIf x is neither n x 1 nor 1 x n array.\n\n\t\tIndexError\n\t\t\tIf b is neither n x 1 nor 1 x n array.\n\t\t\"\"\"\n\t\tA, tol, N = self.A, self.tol, self.max_iter\n\t\tvec_name, x = \"x\", np.array(x)\n\t\tif np.sum(x.shape) - np.sum(x.shape[0]) > 1: raise IndexError(f\"Systems vector, {vec_name} must be n x 1 or 1 x n array!\")\n\t\tself.x = np.reshape(x,(len(x),1))\n\t\tvec_name, b = \"b\", np.array(b)\n\t\tif np.sum(b.shape) - np.sum(b.shape[0]) > 1: raise IndexError(f\"Systems vector, {vec_name} must be n x 1 or 1 x n array!\")\n\t\tself.b = np.reshape(b,(len(b),1))\n\t\tk, eigenvectors, errors = 1, [x], [1]\n\t\twhile errors[-1] > tol and k <= N:\n\t\t\tr = b - np.matmul(A, x)\n\t\t\talpha = float(np.matmul(r.T, r)[0]/np.matmul(np.matmul(r.T, A), r)[0])\n\t\t\tx1 = x + alpha*r\n\t\t\teigenvectors.append(x1)\n\t\t\terrors.append(norms(x1, x).l_infinity())\n\t\t\tx = x1\n\t\t\tk += 1\n\t\tself.iterations = tuple(range(k))\n\t\tself.lambdas = tuple(eigenvectors)\n\t\tself.errors = tuple(errors)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Lambdas\": self.lambdas, \"Errors\": self.errors})\n\n\tdef conjugate_gradient(self, x, b, C=None):\n\t\t\"\"\"Approximate solution vector given matrix, A, initial guess vector, x, and vector, b.\n\n\t\tParameters\n\t\t----------\n\t\tx : array\n\t\t\tNumpy array.\n\n\t\tb : vector\n\t\t\tInput numpy array.\n\n\t\tC : None or matrix, optional\n\t\t\tPreconditioning matrix.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.DataFrame : dataframe\n\t\t\tSummarized dataframe from iterations.\n\n\t\tYields\n\t\t------\n\t\tself.x : tuple\n\t\t\tInitial guess at eigenvector.\n\n\t\tself.b : tuple\n\t\t\tInput numpy array.\n\n\t\tself.iterations : tuple\n\t\t\tCollection of iterations through method.\n\n\t\tself.lambdas : tuple\n\t\t\tCollection of approximate eigenvectors.\n\n\t\tself.errors : tuple\n\t\t\tCollection of yielded norms.\n\n\t\tRaises\n\t\t------\n\t\tIndexError\n\t\t\tIf x is neither n x 1 nor 1 x n array.\n\n\t\tIndexError\n\t\t\tIf b is neither n x 1 nor 1 x n array.\n\t\t\"\"\"\n\t\tA, tol, N = self.A, self.tol, self.max_iter\n\t\tvec_name, x = \"x\", np.array(x)\n\t\tif np.sum(x.shape) - np.sum(x.shape[0]) > 1: raise IndexError(f\"Systems vector, {vec_name} must be n x 1 or 1 x n array!\")\n\t\tself.x = np.reshape(x,(len(x),1))\n\t\tvec_name, b = \"b\", np.array(b)\n\t\tif np.sum(b.shape) - np.sum(b.shape[0]) > 1: raise IndexError(f\"Systems vector, {vec_name} must be n x 1 or 1 x n array!\")\n\t\tself.b = np.reshape(b,(len(b),1))\n\t\tself.C = C\n\t\tr0 = b - np.matmul(A, x)\n\t\tif type(C) == type(None):\n\t\t\tdo_precondition = True\n\t\t\tv0 = r0\n\t\telse:\n\t\t\tdo_precondition = False\n\t\t\tMinv = np.linalg.inv(C*np.transpose(C))\n\t\t\tv0 = np.matmul(Minv, r0)\n\t\tk, eigenvectors, errors = 1, [x], [1]\n\t\twhile errors[-1] > tol and k <= N:\n\t\t\tif do_precondition:\n\t\t\t\talpha = float(np.matmul(r0.T, r0)[0]/np.matmul(np.matmul(v0.T, A)[0], v0)[0])\n\t\t\telse:\n\t\t\t\talpha = float(np.matmul(np.matmul(r0.T, Minv), r0)[0]/np.matmul(np.matmul(v0.T, A), v0)[0])\n\t\t\tx1 = x + alpha*v0\n\t\t\teigenvectors.append(x1)\n\t\t\terrors.append(norms(x1, x).l_infinity())\n\t\t\tr1 = r0 - alpha*np.matmul(A, v0)\n\t\t\tif do_precondition:\n\t\t\t\ts1 = float(np.matmul(r1.T, r1)[0]/np.matmul(r0.T, r0)[0])\n\t\t\telse: s1 = float(np.matmul(np.matmul(r1.T, Minv)[0], r1)[0]/np.matmul(np.matmul(r0.T, Minv)[0], r0)[0])\n\t\t\tx, r0 = x1, r1\n\t\t\tif do_precondition: v0 = r1 + s1*v0\n\t\t\telse: v0 = np.matmul(Minv, r1) + s1*v0\n\t\t\tk += 1\n\t\tself.iterations = tuple(range(k))\n\t\tself.eigenvectors = tuple(eigenvectors)\n\t\tself.errors = tuple(errors)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Lambdas\": self.eigenvectors, \"Errors\": self.errors})\n# --------------------\n\n# --------------------\n# iterative techniques\nclass SingleVariableIteration:\n\tdef __init__(self, function, a, b, power=-6, variable=sp.Symbol(\"x\"), iter_guess=True, k=0):\n\t\t\"\"\"\n\t\tParameters\n\t\t----------\n\t\tfunction : expression\n\t\t\tInput function.\n\n\t\ta : float\n\t\t\tLeft-hand bound of interval.\n\n\t\tb : float\n\t\t\tRight-hand bound of interval.\n\n\t\tpower : float, optional\n\t\t\tSigned, specified power of tolerance until satisfying method.\n\n\t\tvariable : symbol, optional\n\t\t\tRespected variable in derivative. Assumed to be 'x' if not stated.\n\n\t\titer_guess : bool or integer, optional\n\t\t\tBoolean value of `True` by default. If integer, iterate for that integer.\n\n\t\tk : float, optional\n\t\t\tAbsolute maximum slope of function.\n\n\t\tYields\n\t\t------\n\t\tself.function : expression\n\t\t\tInput function.\n\n\t\tself.a : float\n\t\t\tLeft-hand bound of interval.\n\n\t\tself.b : float\n\t\t\tRight-hand bound of interval.\n\n\t\tself.tol : float\n\t\t\tTolerance to satisfy method.\n\n\t\tself.variable : symbol, optional\n\t\t\tRespected variable in derivative. Assumed to be `'x'` if not stated.\n\n\t\tself.iter_guess : bool or integer, optional\n\t\t\tBoolean value of `True` by default. If integer, iterate for that integer.\n\n\t\tself.k : float, optional\n\t\t\tAbsolute maximum slope of functon. Assumed 0 if not defined.\n\n\t\tRaises\n\t\t------\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\n\t\tNotes\n\t\t-----\n\t\tself.tol evaluated by: `10**power`.\n\t\t\"\"\"\n\t\tif isinstance(function, (FunctionType, sp.Expr)):\n\t\t\tsym_function = sp.N(sp.sympify(function(variable)))\n\t\t\tfunction = sp.lambdify(variable, sym_function)\n\t\t\tprint(f\"Information: Input expression, {sym_function} used.\")\n\t\t# elif isinstance(f, (sp.Expr)):\n\t\t# \tf = sp.lambdify(variable, f)\n\t\t# \tself.function = f\n\t\t# \tprint(\"sympy expression converted to lambda function.\")\n\t\telif isinstance(function, (str)):\n\t\t\tg = lambda x: eval(function)\n\t\t\tfunction = sp.lambdify(variable, g(variable))\n\t\t\tprint(\"String expression converted to lambda function.\")\n\t\telse: raise TypeError(\"Unknown input.\")\n\t\tself.function, self.variable = function, variable\n\t\tself.a, self.b, self.tol = float(a), float(b), float(10**power)\n\t\tself.iter_guess, self.k = iter_guess, k\n\n\tdef find_k(self):\n\t\t\"\"\"Find greatest integer for maximum iterations for tolerance.\n\n\t\tReturns\n\t\t-------\n\t\tk : float\n\t\t\tMaximum possible slope of input function.\n\n\t\tYields\n\t\t------\n\t\tself.k : float\n\t\t\tMaximum possible slope of input function.\n\n\t\tWarnings\n\t\t--------\n\t\tPrints to console the input expression, and that the expression was in fact used.\n\t\t\"\"\"\n\t\ta, b, variable = self.a, self.b, self.variable\n\t\tsym_function = sp.N(sp.sympify(self.function(variable)))\n\t\tfunction = sp.lambdify(variable, sym_function)\n\t\tprint(f\"Information: Input expression, {sym_function} used.\")\n\t\tk = self.k\n\t\t# determine form of derivative\n\t\tdf = sp.lambdify(variable, sp.diff(sym_function))\n\t\tfor alpha in np.linspace(a, b, 1000):\n\t\t\tdf_alpha = abs(df(alpha))\n\t\t\tif df_alpha > k: k = df_alpha\n\t\tself.k = k\n\t\treturn k\n\n\tdef max_iterations(self, method, p0=0):\n\t\t\"\"\"Find greatest integer for maximum iterations for tolerance.\n\n\t\tParameters\n\t\t----------\n\t\tmethod : string\n\t\t\tSelection of iterative method for iterations are needed.\n\n\t\tp0 : float, optional\n\t\t\tInitial guess for function solution.\n\n\t\tReturns\n\t\t-------\n\t\tmax_iter : integer\n\t\t\tMaximum number of iterations required for specified tolerance.\n\n\t\tYields\n\t\t------\n\t\tself.max_iter : integer\n\t\t\tMaximum number of iterations required for specified tolerance.\n\n\t\tRaises\n\t\t------\n\t\tValueError\n\t\t\tPrescribed method is not an available option.\n\n\t\tWarnings\n\t\t--------\n\t\tInforms user the maximum number of iterations for method.\n\n\t\tNotes\n\t\t-----\n\t\tWill round away from zero to higher integers.\n\n\t\tExamples\n\t\t--------\n\t\tIf `method == 'bisection'` & a=1, b=2, and tol=-3, then:\n\n\t\t`max_iter` >= -log(`tol`/(`b` - `a`))/log(2)\n\n\t\t`max_iter` >= -log((10**(-3)/(2 - 1))/log(2)\n\n\t\t`max_iter` >= 9.96\n\n\t\t`max_iter` = 10\n\n\t\tElse, if a=1, b=2, tol=-3, p0=1.5, nd k=0.9, then:\n\t\t`max_iter` >= log(`tol`/max('p0' - `a`, `b` - `p0`))/log(k)\n\n\t\t`max_iter` >= log(10**(-3)/max(1.5 - 1, 2 - 1.5))/log(0.9)\n\n\t\t`max_iter` >= log(10**(-3)/0.5)/log(0.9)\n\n\t\t`max_iter` >= 58.98\n\n\t\t`max_iter` >= 59\n\t\t\"\"\"\n\t\ta, b, tol, k = self.a, self.b, self.tol, self.k\n\t\tp0 = float(p0)\n\t\tif method == \"bisection\":\n\t\t\tmax_iter = math.ceil(-math.log(tol/(b - a))/math.log(2))\n\t\telif method in (\"fixed_point\", \"newton_raphson\", \"secant_method\", \"false_position\"):\n\t\t\tmax_iter = math.ceil(-math.log(tol/max(p0 - a, b - p0))/math.log(k))\n\t\telse: raise ValueError(f\"ERROR! I am sorry. The desired method must be: 'bisection', 'fixed_point', 'newton_raphson', 'secant_method', or 'false_position'.\")\n\t\tself.max_iter = max_iter\n\t\tprint(f\"Information: With the inputs, I will terminate the technique after so many iterations, N = {max_iter}\")\n\t\treturn max_iter\n\n\t# next 5 functions preceded by find_k & max_iterations\n\n\tdef bisection(self):\n\t\t\"\"\"Given f(x) in [a, b] find x within tolerance. Is a root-finding method: f(x) = 0.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.DataFrame : dataframe\n\t\t\tSummarized dataframe from iterations.\n\n\t\tYields\n\t\t------\n\t\tself.iterations : tuple\n\t\t\tCollection of iterations through method.\n\n\t\tself.approximations : tuple\n\t\t\tCollection of evaluated points, p.\n\n\t\tself.errors : tuple\n\t\t\tCollection of propogated error through method.\n\n\t\tRaises\n\t\t------\n\t\tValueError\n\t\t\tIf input for desired iterations was assigned not an integer.\n\n\t\tValueError\n\t\t\tIf initial guesses did not evaluate to have opposite signs.\n\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\n\t\tWarnings\n\t\t--------\n\t\tPrint to console if solution was found, or state that solution did not converge with given guess or prescribed tolerance.\n\n\t\tNotes\n\t\t-----\n\t\tRelying on the Intermediate Value Theorem, this is a bracketed, root-finding method. Generates a sequence {p_n}^{inf}_{n=1} to approximate a zero of f(x), p and converges by O(1 / (2**N)).\n\n\t\tExamples\n\t\t--------\n\t\tIf  f(x) = x**3 + 4*x**2 = 10\n\n\t\t=>  f(x) = x**3 + 4*x**2 - 10 = 0\n\t\t\"\"\"\n\t\tf, a, b, tol = self.function, self.a, self.b, self.tol\n\t\titer_guess = self.iter_guess\n\t\t# calculate if expression\n\t\tif isinstance(f, (FunctionType, sp.Expr)):\n\t\t\tsym_function = sp.N(sp.sympify(f(self.variable)))\n\t\t\tf = sp.lambdify(self.variable, sym_function)\n\t\t\t# check if f(a) and f(b) are opposite signs\n\t\t\tif f(a)*f(b) < 0:\n\t\t\t\tif iter_guess == True:\n\t\t\t\t\t# if left unassigned, guess\n\t\t\t\t\tN = self.max_iterations(\"bisection\")\n\t\t\t\telif isinstance(iter_guess, (int, float)):\n\t\t\t\t\t# if defined as integer, use\n\t\t\t\t\tN = int(iter_guess)\n\t\t\t\t# else, break for bad assignment\n\t\t\t\telse: raise ValueError(f\"ERROR! Maximum iterations, N must be an integer greater than zero. {iter_guess} was given and not understood.\")\n\t\t\t\t# initialize\n\t\t\t\tk, approximations, errors = 0, [f(a)], [1]\n\t\t\t\t# exit by whichever condition is TRUE first\n\t\t\t\twhile errors[-1] >= tol and k <= N:\n\t\t\t\t\tx = (b - a)/2\n\t\t\t\t\tp = a + x \t# new value, p\n\t\t\t\t\tapproximations.append(p)\n\t\t\t\t\tif f(a)*f(p) > 0: a = p \t# adjust next bounds\n\t\t\t\t\telse: b = p\n\t\t\t\t\terrors.append(abs(x)) \t# error of new value, p\n\t\t\t\t\tk += 1 \t# iterate to k + 1\n\t\t\t\tif k <= N: print(\"Congratulations! Solution found!\")\n\t\t\t\telse: print(\"Warning! Solution could not be found with initial guess or tolerance.\")\n\t\t\t\tself.iterations = tuple(range(k))\n\t\t\t\tself.approximations = tuple(approximations)\n\t\t\t\tself.errors = tuple(errors)\n\t\t\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Approximations\": self.approximations, \"Errors\": self.errors})\n\t\t\t# abort if f(a) is not opposite f(b)\n\t\t\telse: raise ValueError(f\"ERROR! Interval bounds, [a, b] = [{a}, {b}] must yield opposite signs in function, {sym_function}.\")\n\t\t# abort if not expression\n\t\telse: raise TypeError(\"ERROR! The input function must be an expression.\")\n\n\tdef false_position(self, p0, p1):\n\t\t\"\"\"Given f(x) and initial guesses, p0 and p1 in [a, b] find x within tolerance.\n\n\t\tRoot-finding problem: f(x) = 0. \n\n\t\t!!! Use lowest k !!!\n\n\t\tParameters\n\t\t----------\n\t\tp0 : float\n\t\t\tFirst initial guess.\n\n\t\tp1 : float\n\t\t\tSecond initial guess.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.DataFrame : dataframe\n\t\t\tSummarized dataframe from iterations.\n\n\t\tYields\n\t\t------\n\t\tself.iterations : tuple\n\t\t\tCollection of iterations through method.\n\n\t\tself.approximations : tuple\n\t\t\tCollection of evaluated points, p.\n\n\t\tself.errors : tuple\n\t\t\tCollection of propogated error through method.\n\n\t\tRaises\n\t\t------\n\t\tValueError\n\t\t\tIf input for desired iterations was assigned not an integer.\n\n\t\tValueError\n\t\t\tIf initial guesses did not evaluate to have opposite signs.\n\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\n\t\tWarnings\n\t\t--------\n\t\tPrint to console if solution was found, or state that solution did not converge with given guess or prescribed tolerance.\n\n\t\tNotes\n\t\t-----\n\t\tCheck that |g'(x)| <= (leading coefficient of g'(x)) for all x in [a, b].\n\n\t\tTheorem:\n\t\t1) Existence of a fixed-point:\n\t\t\tIf g in C[a,b] and g(x) in C[a, b] for all x in [a, b], then function, g has a fixed point in [a, b].\n\n\t\t2) Uniqueness of a fixed point:\n\t\t\tIf g'(x) exists on [a, b] and a positive constant, k < 1 exist with {|g'(x)| <= k  |  x in (a, b)}, then there is exactly one fixed-point, p in [a, b].\n\n\t\tConverges by O(linear) if g'(p) != 0, and O(quadratic) if g'(p) = 0 and g''(p) < M, where M = g''(xi) that is the error function.\n\n\t\tExamples \n\t\t--------\n\t\tIf  g(x) = x**2 - 2\n\n\t\tThen\tp = g(p) = p**2 - 2\n\n\t\t=>  p**2 - p - 2 = 0\n\t\t\"\"\"\n\t\tf, a, b, tol = self.function, self.a, self.b, self.tol\n\t\titer_guess, k = self.iter_guess, self.k\n\t\tp0, p1 = float(p0), float(p1)\n\t\tself.p0, self.p1 = p0, p1\n\t\t# calculate if expression\n\t\tif isinstance(f, (FunctionType, sp.Expr)):\n\t\t\tsym_function = sp.N(sp.sympify(f(self.variable)))\n\t\t\tf = sp.lambdify(self.variable, sym_function)\n\t\t\t# check if f(a) and f(b) are opposites signs\n\t\t\tif f(p0)*f(p1) < 0:\n\t\t\t\tif iter_guess == True and k == 0:\n\t\t\t\t\t# if left unassigned, guess\n\t\t\t\t\tN = self.max_iterations(\"false position\", p0=p0)\n\t\t\t\telif iter_guess == True and k != 0:\n\t\t\t\t\t# if left unassigned, guess\n\t\t\t\t\tN = self.max_iterations(\"false position\", k=k, p0=p0)\n\t\t\t\telif isinstance(iter_guess, (int, float)):\n\t\t\t\t\t# if defined as integer, use\n\t\t\t\t\tN = int(iter_guess)\n\t\t\t\t# else, break for bad assignment\n\t\t\t\telse: raise ValueError(f\"ERROR! Maximum iterations, N must be an integer greater than zero. {iter_guess} was given and not understood.\")\n\t\t\t\t# initialize\n\t\t\t\tk, approximations, errors = 0, [f(a)], [1]\n\t\t\t\t# exit by whichever condition is TRUE first\n\t\t\t\twhile errors[-1] >= tol and k <= N:\n\t\t\t\t\tq0, q1 = f(p0), f(p1)\n\t\t\t\t\tp = p1 - q1*(p1 - p0)/(q1 - q0) \t# new value, p\n\t\t\t\t\tapproximations.append(p)\n\t\t\t\t\terrors.append(abs(p - p0)) \t# error of new value, p\n\t\t\t\t\tif f(p)*q1 < 0: p0 = p1 \t# adjust next bounds\n\t\t\t\t\tp1 = p\n\t\t\t\t\tk += 1 \t# iterate to k + 1\n\t\t\t\tif k <= N: print(\"Congratulations! Solution found!\")\n\t\t\t\telse: print(\"Warning! Solution could not be found with initial guess or tolerance.\")\n\t\t\t\tself.iterations = tuple(range(k))\n\t\t\t\tself.approximations = tuple(approximations)\n\t\t\t\tself.errors = tuple(errors)\n\t\t\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Approximations\": self.approximations, \"Errors\": self.errors})\n\t\t\t# abort if f(a) is not opposite f(b)\n\t\t\telse: raise ValueError(f\"ERROR! Interval bounds, [a, b] = [{a}, {b}] must yield opposite signs in function, {sym_function}.\")\n\t\t# abort if not expression\n\t\telse: raise TypeError(\"ERROR! The input function must be an expression.\")\n\n\tdef fixed_point(self, p0):\n\t\t\"\"\"Given f(x) and initial guess, p0 in [a, b] find x within tolerance.\n\n\t\tRoot-finding problem: f(x) = 0. \n\n\t\t!!! Use lowest k !!!\n\n\t\tParameters\n\t\t----------\n\t\tp0 : float\n\t\t\tInitial guess.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.DataFrame : dataframe\n\t\t\tSummarized dataframe from iterations.\n\n\t\tYields\n\t\t------\n\t\tself.iterations : tuple\n\t\t\tCollection of iterations through method.\n\n\t\tself.approximations : tuple\n\t\t\tCollection of evaluated points, p.\n\n\t\tself.errors : tuple\n\t\t\tCollection of propogated error through method.\n\n\t\tRaises\n\t\t------\n\t\tValueError\n\t\t\tIf input for desired iterations was assigned not an integer.\n\n\t\tValueError\n\t\t\tIf initial guesses did not evaluate to have opposite signs.\n\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\n\t\tWarnings\n\t\t--------\n\t\tPrint to console if solution was found, or state that solution did not converge with given guess or prescribed tolerance.\n\n\t\tNotes\n\t\t-----\n\t\tCheck that |g'(x)| <= (leading coefficient of g'(x)) for all x in [a, b].\n\n\t\tTheorem:\n\t\t1) Existence of a fixed-point:\n\t\t\tIf g in C[a, b] and g(x) in C[a, b] for all x in [a, b], then function, g has a fixed point in [a, b].\n\n\t\t2) Uniqueness of a fixed point:\n\t\t\tIf g'(x) exists on [a, b] and a positive constant, k < 1 exist with {|g'(x)| <= k  |  x in (a, b)}, then there is exactly one fixed-point, `p` in [a, b].\n\n\t\tConverges by O(linear) if g'(p) != 0, and O(quadratic) if g'(p) = 0 and g''(p) < M, where M = g''(xi) that is the error function.\n\n\t\tExamples \n\t\t--------\n\t\tIf  g(x) = x**2 - 2\n\n\t\tThen\tp = g(p) = p**2 - 2\n\t\t\n\t\t=>  p**2 - p - 2 = 0\n\t\t\"\"\"\n\t\tf, a, b, tol = self.function, self.a, self.b, self.tol\n\t\titer_guess, k = self.iter_guess, self.k\n\t\tp0 = float(p0)\n\t\tself.p0 = p0\n\t\t# calculate if expression\n\t\tif isinstance(f, (FunctionType, sp.Expr)):\n\t\t\tsym_function = sp.N(sp.sympify(f(self.variable)))\n\t\t\tf = sp.lambdify(self.variable, sym_function)\n\t\t\tif iter_guess == True and k == 0:\n\t\t\t\t# if left unassigned, guess\n\t\t\t\tN = self.max_iterations(\"fixed point\", p0=p0)\n\t\t\telif iter_guess == True and k != 0:\n\t\t\t\t# if left unassigned, guess\n\t\t\t\tN = self.max_iterations(\"fixed point\", k=k, p0=p0)\n\t\t\telif isinstance(iter_guess, (int, float)):\n\t\t\t\t# if defined as integer, use\n\t\t\t\tN = int(iter_guess)\n\t\t\t# else, break for bad assignment\n\t\t\telse: raise ValueError(f\"ERROR! Maximum iterations, N must be an integer greater than zero. {iter_guess} was given and not understood.\")\n\t\t\t# initialize\n\t\t\tk, approximations, errors = 0, [f(a)], [1]\n\t\t\t# exit by whichever condition is TRUE first\n\t\t\twhile errors[-1] >= tol and k <= N:\n\t\t\t\tp = f(p0) \t# new value, p\n\t\t\t\tapproximations.append(p)\n\t\t\t\terrors.append(abs((p - p0)/p0)) # error of new value, p\n\t\t\t\tp0 = p \t# set future previous value\n\t\t\t\tk += 1 \t# iterate to k + 1\n\t\t\tif k <= N: print(\"Congratulations! Solution found!\")\n\t\t\telse: print(\"Warning! Solution could not be found with initial guess or tolerance.\")\n\t\t\tself.iterations = tuple(range(k))\n\t\t\tself.approximations = tuple(approximations)\n\t\t\tself.errors = tuple(errors)\n\t\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Approximations\": self.approximations, \"Errors\": self.errors})\n\t\t# abort if not expression\n\t\telse: raise TypeError(\"ERROR! The input function must be an expression.\")\n\n\tdef newton_raphson(self, p0):\n\t\t\"\"\"Given f(x) and initial guess, p0 in [a, b], find x within tolerance.\n\n\t\tRoot-finding problem: f(x) = 0. \n\n\t\t!!! Use lowest k !!!\n\n\t\tParameters\n\t\t----------\n\t\tp0 : float\n\t\t\tInitial guess.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.DataFrame : dataframe\n\t\t\tSummarized dataframe from iterations.\n\n\t\tYields\n\t\t------\n\t\tself.iterations : tuple\n\t\t\tCollection of iterations through method.\n\n\t\tself.approximations : tuple\n\t\t\tCollection of evaluated points, p.\n\n\t\tself.errors : tuple\n\t\t\tCollection of propogated error through method.\n\n\t\tRaises\n\t\t------\n\t\tValueError\n\t\t\tIf input for desired iterations was assigned not an integer.\n\n\t\tValueError\n\t\t\tIf initial guesses did not evaluate to have opposite signs.\n\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\n\t\tWarnings\n\t\t--------\n\t\tPrint to console if solution was found, or state that solution did not converge with given guess or prescribed tolerance.\n\n\t\tNotes\n\t\t-----\n\t\tf'(x) != 0.\n\n\t\tNot root-bracketed.\n\n\t\tInitial guess must be close to real solution; else, will converge to different root or oscillate (if symmetric).\n\n\t\tCheck that |g'(x)| <= (leading coefficient of g'(x)) for all x in [a, b].\n\n\t\tTechnique based on first Taylor polynomial expansion of f about p0 and evaluated at x = p. |p - p0| is assumed small; therefore, 2nd order Taylor term, the error, is small.\n\n\t\tNewton-Raphson has quickest convergence rate.\n\n\t\tThis method can be viewed as fixed-point iteration.\n\n\t\tTheorem:\n\t\t1) Existence of a fixed-point:\n\t\t\tIf g in C[a, b] and g(x) in C[a, b] for all x in [a, b], then function, g has a fixed point in [a, b].\n\n\t\t2) Uniqueness of a fixed point:\n\t\t\tIf g'(x) exists on [a, b] and a positive constant, `k` < 1 exist with {|g'(x)| <= k  |  x in (a, b)}, then there is exactly one fixed-point, `p` in [a, b].\n\n\t\tConverges by O(linear) if g'(p) != 0, and O(quadratic) if g'(p) = 0 and g''(p) < M, where M = g''(xi) that is the error function.\n\n\t\tExamples \n\t\t--------\n\t\tIf  g(x) = x**2 - 2\n\n\t\tThen\tp = g(p) = p**2 - 2\n\n\t\t=>  p**2 - p - 2 = 0\n\t\t\"\"\"\n\t\tf, a, b, tol = self.function, self.a, self.b, self.tol\n\t\titer_guess, k = self.iter_guess, self.k\n\t\tp0 = float(p0)\n\t\tself.p0 = p0\n\t\t# calculate if expression\n\t\tif isinstance(f,(FunctionType, sp.Expr)):\n\t\t\tsym_function = sp.N(sp.sympify(f(self.variable)))\n\t\t\tf = sp.lambdify(self.variable, sym_function)\n\t\t\t# determine form of derivative\n\t\t\tdf = sp.lambdify(self.variable, sp.diff(sym_function))\n\t\t\tif iter_guess == True and k == 0:\n\t\t\t\t# if left unassigned, guess\n\t\t\t\tN = self.max_iterations(\"newton raphson\", p0=p0)\n\t\t\telif iter_guess == True and k != 0:\n\t\t\t\t# if left unassigned, guess\n\t\t\t\tN = self.max_iterations(\"newton raphson\", k=k, p0=p0)\n\t\t\telif isinstance(iter_guess, int):\n\t\t\t\t# if defined as integer, use\n\t\t\t\tN = iter_guess\n\t\t\t# else, break for bad assignment\n\t\t\telse: raise ValueError(f\"ERROR! Maximum iterations, N must be an integer greater than zero. {iter_guess} was given and not understood.\")\n\t\t\t# initialize\n\t\t\tk, approximations, errors = 0, [f(a)], [1]\n\t\t\t# exit by whichever condition is TRUE first\n\t\t\twhile errors[-1] >= tol and k <= N:\n\t\t\t\tfp0 = f(p0)\n\t\t\t\tdfp0 = df(p0)\n\t\t\t\tp = p0 - (fp0/dfp0)\t # new value, p\n\t\t\t\tapproximations.append(p)\n\t\t\t\terrors.append(abs(p - p0)) \t# error of new value, p\n\t\t\t\tp0 = p \t# set future previous value\n\t\t\t\tk += 1 \t# iterate to k + 1\n\t\t\tif k <= N: print(\"Congratulations! Solution found!\")\n\t\t\telse: print(\"Warning! Solution could not be found with initial guess or tolerance.\")\n\t\t\tself.iterations = tuple(range(k+1))\n\t\t\tself.approximations = tuple(approximations)\n\t\t\tself.errors = tuple(errors)\n\t\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Approximations\": self.approximations, \"Errors\": self.errors})\n\t\t# abort if not expression\n\t\telse: raise TypeError(\"ERROR! The input function must be an expression.\")\n\n\tdef secant_method(self, p0, p1):\n\t\t\"\"\"Given f(x) and initial guesses, p0 and p1 in [a, b], find x within tolerance.\n\t\tRoot-finding problem: f(x) = 0. \n\n\t\t!!! Use lowest k !!!\n\n\t\tParameters\n\t\t----------\n\t\tp0 : float\n\t\t\tFirst initial guess.\n\n\t\tp1 : float\n\t\t\tSecond initial guess.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.DataFrame : dataframe\n\t\t\tSummarized dataframe from iterations.\n\n\t\tYields\n\t\t------\n\t\tself.iterations : tuple\n\t\t\tCollection of iterations through method.\n\n\t\tself.approximations : tuple\n\t\t\tCollection of evaluated points, p.\n\n\t\tself.errors : tuple\n\t\t\tCollection of propogated error through method.\n\n\t\tRaises\n\t\t------\n\t\tValueError\n\t\t\tIf input for desired iterations was assigned not an integer.\n\n\t\tValueError\n\t\t\tIf initial guesses did not evaluate to have opposite signs.\n\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\n\t\tWarnings\n\t\t--------\n\t\tPrint to console if solution was found, or state that solution did not converge with given guess or prescribed tolerance.\n\n\t\tNotes\n\t\t-----\n\t\tNot root-bracketed.\n\n\t\tBypasses need to calculate derivative (as in Newton-Raphson).\n\n\t\tCheck that |g'(x)| <= (leading coefficient of g'(x)) for all x in [a, b].\n\n\t\tTheorem:\n\t\t1) Existence of a fixed-point:\n\t\t\tIf g in C[a, b] and g(x) in C[a, b] for all x in [a, b], then function, g has a fixed point in [a, b].\n\n\t\t2) Uniqueness of a fixed point:\n\t\t\tIf g'(x) exists on [a, b] and a positive constant, `k` < 1 exist with {|g'(x)| <= k  |  x in (a, b)}, then there is exactly one fixed-point, `p` in [a, b].\n\n\t\tConverges by O(linear) if g'(p) != 0, and O(quadratic) if g'(p) = 0 and g''(p) < M, where M = g''(xi) that is the error function.\n\n\t\tExamples \n\t\t--------\n\t\tIf  g(x) = x**2 - 2\n\n\t\tThen\tp = g(p) = p**2 - 2\n\n\t\t=>  p**2 - p - 2 = 0\n\t\t\"\"\"\n\t\tf, a, b, tol = self.function, self.a, self.b, self.tol\n\t\titer_guess, k = self.iter_guess, self.k\n\t\tp0, p1 = float(p0), float(p1)\n\t\tself.p0, self.p1 = p0, p1\n\t\t# calculate if expression\n\t\tif isinstance(f, (FunctionType, sp.Expr)):\n\t\t\tsym_function = sp.N(sp.sympify(f(self.variable)))\n\t\t\tf = sp.lambdify(self.variable, sym_function)\n\t\t\t# check if f(a) and f(b) are opposite signs\n\t\t\tif f(p0)*f(p1) < 0:\n\t\t\t\tif iter_guess == True and k == 0:\n\t\t\t\t\t# if left unassigned, guess\n\t\t\t\t\tN = self.max_iterations(\"secant method\", p0=p0)\n\t\t\t\telif iter_guess == True and k != 0:\n\t\t\t\t\t# if left unassigned, guess\n\t\t\t\t\tN = self.max_iterations(\"secant method\", k=k, p0=p0)\n\t\t\t\telif isinstance(iter_guess, (int, float)):\n\t\t\t\t\t# if defined as integer, use\n\t\t\t\t\tN = (iter_guess)\n\t\t\t\t# else, break for bad assignment\n\t\t\t\telse: raise ValueError(f\"ERROR! Maximum iterations, N must be an integer greater than zero. {iter_guess} was given and not understood.\")\n\t\t\t\t# initialize\n\t\t\t\tk, approximations, errors = 0, [f(a)], [1]\n\t\t\t\t# exit by whichever condition is TRUE first\n\t\t\t\twhile errors[-1] >= tol and k <= N:\n\t\t\t\t\tq0, q1 = f(p0), f(p1)\n\t\t\t\t\t# new value, p\n\t\t\t\t\tp = p1 - q1*(p1 - p0)/(q1 - q0)\n\t\t\t\t\tapproximations.append(p)\n\t\t\t\t\terrors.append(abs(p - p0)) \t# error of new value\n\t\t\t\t\tp0, p1 = p1, p \t# set future previous values\n\t\t\t\t\tk += 1 \t# iterate to k + 1\n\t\t\t\tif k <= N: print(\"Congratulations! Solution found!\")\n\t\t\t\telse: print(\"Warning! Solution could not be found with initial guess or tolerance.\")\n\t\t\t\tself.iterations = tuple(range(k))\n\t\t\t\tself.approximations = tuple(approximations)\n\t\t\t\tself.errors = tuple(errors)\n\t\t\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Approximations\": self.approximations, \"Errors\": self.errors})\n\t\t\t# abort if f(a) is not opposite f(b)\n\t\t\telse: raise ValueError(f\"ERROR! Interval bounds, [a, b] = [{a}, {b}] must yield opposite signs in function, {sym_function}.\")\n\t\t# abort if not expression\n\t\telse: raise TypeError(\"ERROR! The input function must be an expression.\")\n\nclass MultiVariableIteration:\n\tdef __init__(self, A, x0, b, power=-6, max_iter=100, norm_type=\"l_infinity\"):\n\t\t\"\"\"\n\t\tParameters\n\t\t----------\n\t\tA : tuple\n\t\t\tEither input functions or matrix of characteristic values.\n\n\t\tx0 : tuple\n\t\t\tEither collection of symbols or initial guesses for system of equations.\n\n\t\tb : tuple\n\t\t\tInput vector.\n\n\t\tpower : float, optional\n\t\t\tSigned, specified power of tolerance until satisfying method.\n\n\t\tmax_iter : integer, optional\n\t\t\tNumber of iterations.\n\n\t\tnorm_type : string, optional\n\t\t\tString representation of desired norm function. `'l_infinity'` by default.\n\n\t\tYields\n\t\t------\n\t\tself.A : tuple\n\t\t\tEither input functions or matrix of characteristic values.\n\n\t\tself.x0 : tuple\n\t\t\tEither collection of symbols or initial guesses for system of equations.\n\n\t\tself.b : tuple\n\t\t\tInput vector.\n\n\t\tself.tol : float\n\t\t\tSpecified tolerance to which method terminates.\n\n\t\tself.max_iter : int\n\t\t\tMaximum iterations allowed for method.\n\n\t\tself.norm_type : string\n\t\t\tString representation of desired norm function.\n\n\t\tself.is_diagonal : bool\n\t\t\tTruth value of whether matrix is diagonal.\n\n\t\tself.is_symmetric : bool\n\t\t\tTruth value of whether matrix is symmetric.\n\n\t\tself.is_tridiagonal : bool\n\t\t\tTruth value of whether matrix is tridiagonal.\n\n\t\tself.eigen_values : tuple\n\t\t\tEigenvalues of characteristic matrix, A.\n\n\t\tself.spectral_radius : float\n\t\t\tSpectral radius of characteristic matrix, A.\n\n\t\tself.condition_number : float\n\t\t\tCondition number of characteristic matrix, A. \n\n\t\tRaises\n\t\t------\n\t\tIndexError\n\t\t\tMatrix of interest must be square.\n\n\t\tIndexError\n\t\t\tIf x0 is neither n x 1 nor 1 x n array.\n\n\t\tIndexError\n\t\t\tIf b is neither n x 1 nor 1 x n array.\n\n\t\tValueError\n\t\t\tIf iterations constraint is not an integer.\n\n\t\tValueError\n\t\t\tIf desired norm method was neither `'l_infinity'` nor `'l_two'`.\n\n\t\tWarnings\n\t\t--------\n\t\tNot recommended to use eigen_values() to find eigenvalues of characteristic matrix, A; therefore, if desiring quick calculations, do not use if matrix, A is a large, sparse matrix.\n\n\t\tSee Also\n\t\t--------\n\t\teigen_values() : Function to find eigenvalues of matrix, A.\n\n\t\tspectral_radius() : Function to find the spectral radius of characteristic matrix, A.\n\n\t\tNotes\n\t\t-----\n\t\tSpecified tolerance evaluated by: `10**power`.\n\n\t\tnorm_type may be either `'l_infinity'` or `'l_two'`. Is 'l_infinity' by default.\n\n\t\tIf `self.is_diagonal` is True, then matrix is diagonal. Else, not diagonal.\n\t\t\"\"\"\n\t\tmatrix_name, vec_name, sys_name = \"A\", \"x0\", \"b\"\n\t\tA, x0, b = np.array(A), np.array(x0), np.array(b)\n\t\tif np.sum(A.shape[0]) != np.sum(A.shape[1]): raise IndexError(f\"ERROR! Matrix, {matrix_name} must be square!\")\n\t\tif np.sum(x0.shape) - np.sum(x0.shape[0]) > 1: raise IndexError(f\"Systems vector, {vec_name} must be n x 1 or 1 x n array!\")\n\t\tif np.sum(b.shape) - np.sum(b.shape[0])> 1: raise IndexError(f\"Systems vector, {sys_name} must be n x 1 or 1 x n array!\")\n\t\tif max_iter <= 0 or not isinstance(max_iter, (int, float)): ValueError(f\"ERROR! Maximum iterations, N must be an integer greater than zero. {max_iter} was given and not understood.\")\n\t\tif norm_type != \"l_infinity\" and norm_type != \"l_two\": raise ValueError(\"ERROR! Desired norm type was not understood. Please choose 'l_infinity' or 'l_two'.\")\n\t\tn = len(x0)\n\t\tself.A = A\n\t\tself.x0 = np.reshape(x0,(n,1))\n\t\tself.b = np.reshape(b,(n,1))\n\t\tself.tol = float(10**power)\n\t\tself.max_iter = int(max_iter)\n\t\tself.norm_type = norm_type\n\t\tself.is_diagonal = diagonality(A)\n\t\tself.is_symmetric = symmetry(A)\n\t\tself.is_tridiagonal = tridiagonality(A)\n\t\t# self.eigen_values = eigen_values(A)\n\t\t# self.spectral_radius = spectral_radius(A)\n\t\t# self.condition_number = condition_number(A, norm_type)\n\n\tdef __find_xk(self, x):\n\t\treturn np.matmul(self.T, x) + self.c\n\n\tdef find_omega(self, omega=0):\n\t\t\"\"\"Given the characteristic matrix and solution vector, determine if prescribed omega is the optimum choice.\n\n\t\tParameters\n\t\t----------\n\t\tomega : float, optional\n\t\t\tRelaxation parameter.\n\n\t\tReturns\n\t\t-------\n\t\tomega : float\n\t\t\tIf found, is the optimum choice of omega.\n\n\t\tYields\n\t\t------\n\t\tself.user_omega : float\n\t\t\tSupplied/default omega.\n\n\t\tself.is_tridiagonal : bool\n\t\t\tTruth value of whether matrix, A is tridiagonal.\n\n\t\tself.best_omega : float\n\t\t\tIf found, is the optimum choice of omega.\n\n\t\tWarnings\n\t\t--------\n\t\tIf 0 < omega < 2, then method will converge regardless of choice for x0. Will inform user that matrix, A is not tridiagonal, but will proceed with calculation all the same. If matrix, A is poorly defined and not found to be positive definite, then user is informed but calculation proceeds. If an optimal omega cannot be found, then `self.best_omega` assigned from supplied/default omega.\n\n\t\tSee Also\n\t\t--------\n\t\ttridiagonality() : Determines if matrix, A is tridiagonal or not.\n\n\t\tspectral_radius() : Uses the spectral radius of Gauss-Seidel's T-matrix to calculate omega.\n\n\t\tNotes\n\t\t-----\n\t\tUnless specified, omega will be 0 and chosen, if possible.\n\t\t\"\"\"\n\t\tmatrix_name = \"A\"\n\t\tA, x0, omega = np.array(self.A), np.array(self.x0), float(omega)\n\t\tself.user_omega = omega\n\t\txn = sp.Matrix(np.reshape(np.zeros_like(x0), (len(x0), 1)))\n\t\txt = sp.Matrix(np.reshape(np.zeros_like(x0), (1, len(x0))))\n\t\ti = 0\n\t\tfor x in np.array(x0): xn[i], xt[i] = x, x; i += 1\n\t\ty = xt*sp.Matrix(A)*xn\n\t\tif y[0] > 0: state = True\n\t\telse: state = False\n\t\tif self.is_symmetric and state: theorem_6_22 = True\n\t\telse: theorem_6_22 = False\n\t\ti, theorem_6_25 = 1, True\n\t\twhile i <= len(A) and theorem_6_25 == True:\n\t\t\tAi = sp.Matrix(A[:i,:i])\n\t\t\tif sp.det(Ai) > 0: theorem_6_25 = True\n\t\t\telse : theorem_6_25 = False\n\t\t\ti += 1\n\t\tif theorem_6_22 or theorem_6_25:\n\t\t\tif 0 < omega and omega < 2: print(\"According to Ostrowski-Reich's Theorem, the successive relaxation technique will converge.\")\n\t\t\tif self.is_tridiagonal:\n\t\t\t\tD = np.diagflat(np.diag(A))\n\t\t\t\tL = np.diagflat(np.diag(A, k=-1), k=-1)\n\t\t\t\tU = np.diagflat(np.diag(A, k=1), k=1)\n\t\t\t\tDL = D - L\n\t\t\t\ti, DL_inv = 0, np.zeros_like(DL)\n\t\t\t\twhile i < len(DL_inv):\n\t\t\t\t\tj = 0\n\t\t\t\t\twhile j < len(DL_inv[0]):\n\t\t\t\t\t\tdl = DL[i][j]\n\t\t\t\t\t\tif dl != 0: DL_inv[i][j] = 1/(dl)\n\t\t\t\t\t\tj += 1\n\t\t\t\t\ti += 1\n\t\t\t\tTg = DL_inv*U\n\t\t\t\tomega = 2 / (1 + math.sqrt(1 - spectral_radius(Tg)))\n\t\t\t\tprint(f\"I believe {omega} would be the best choice.\")\n\t\t\telse:\n\t\t\t\tprint(f\"Warning! Matrix, {matrix_name} is not tridiagonal.\")\n\t\t\t\tprint(f\"Assigning supplied omega, {omega} as `self.best_omega`.\")\n\t\telse:\n\t\t\tprint(f\"Warning! Matrix, {matrix_name} is not positive definite.\")\n\t\t\tprint(f\"Assigning supplied omega, {omega} as `self.best_omega`.\")\n\t\tself.best_omega = omega\n\t\treturn omega\n\n\tdef gauss_seidel(self):\n\t\t\"\"\"Given A*x = b, use `self.norm_type` to find x via the Gauss-Seidel Method.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.DataFrame : dataframe\n\t\t\tSummarized dataframe from iterations.\n\n\t\tYields\n\t\t-------\n\t\tself.iterations : tuple\n\t\t\tRunning collection of iterations through method.\n\n\t\tself.approximations : tuple\n\t\t\tFinally evaluated solution.\n\n\t\tself.errors : tuple\n\t\t\tAggregate of yielded norms.\n\n\t\tWarnings\n\t\t--------\n\t\tPrints to console whether or not a solution was found within the specified tolerance with the supplied, initial guess.\n\n\t\tSee Also\n\t\t--------\n\t\tnorms.l_infinity() : Will find the l_infinity norm between x0 and xi.\n\n\t\tnorms.l_two() : Will find the l_2 norm between x0 and xi.\n\n\t\tNotes\n\t\t-----\n\t\tgauss_seidel():\n\t\t\t[x]_(k) = ( (D - L)^(-1) * U ) * [x]_(k - 1) + ( (D - L)^(-1) )*[b]\n\t\t\"\"\"\n\t\tA, x0, b, tol, N = self.A, self.x0, self.b, self.tol, self.max_iter\n\t\tnorm_type, norm = self.norm_type, tol*10\n\t\t# A = np.zeros((N, N))\n\t\t# np.fill_diagonal(A, ai)\n\t\t# A = A + np.diagflat(bi, 1)\n\t\t# A = A + np.diagflat(ci, -1)\n\t\t# x0 = np.zeros(N)\n\t\t# b = np.array(di)\n\t\t# A1, A2 = np.zeros((n, n)), np.zeros((n, n))\n\t\t# np.fill_diagonal(A1, np.diagonal(A))\n\t\t# A1 = A1 - np.tril(A, k=-1)\n\t\t# i = 0\n\t\t# while i < n:\n\t\t# \tj = 0\n\t\t# \twhile j <= i:\n\t\t# \t\ta1ij = A1[i][j]\n\t\t# \t\tif a1ij != 0:\n\t\t# \t\t\tA2[i][j] = 1/a1ij\n\t\t# \t\tj += 1\n\t\t# \ti += 1\n\t\t# self.T = np.matmul(A2, np.triu(A, k=1))\n\t\t# self.c = np.matmul(A2, b)\n\t\tk, n, approximations, errors = 1, len(x0), [x0], [norm]\n\t\twhile errors[-1] > tol and k <= N:\n\t\t\ti, xi = 0, np.zeros_like(x0)\n\t\t\twhile i < n:\n\t\t\t\tj, y1, y2 = 0, 0., 0.\n\t\t\t\twhile j <= i-1:\n\t\t\t\t\ty1 += A[i][j]*xi[j]\n\t\t\t\t\tj += 1\n\t\t\t\tj = i + 1\n\t\t\t\twhile j < n:\n\t\t\t\t\ty2 += A[i][j]*x0[j]\n\t\t\t\t\tj += 1\n\t\t\t\txi[i] = (-y1 - y2 + b[i])/A[i][i]\n\t\t\t\ti += 1\n\t\t\t# xi = self.__find_xk(x0)\n\t\t\tif norm_type == \"l_infinity\":\n\t\t\t\tnorm = norms(xi, x0).l_infinity()\n\t\t\telif norm_type == \"l_two\":\n\t\t\t\tnorm = norms(xi, x0).l_two()\n\t\t\tapproximations.append(xi)\n\t\t\terrors.append(norm)\n\t\t\tx0 = xi\n\t\t\tk += 1\n\t\tif k <= N: print(\"Congratulations! Solution found!\")\n\t\telse: print(\"Warning! Solution could not be found with initial guess or tolerance.\")\n\t\t# m, n = len(approximations[0]), len(approximations)\n\t\t# j, x = 0, np.zeros((m,n))\n\t\t# while j < n:\n\t\t# \ti = 0\n\t\t# \twhile i < m:\n\t\t# \t\tx[i][j] = float(approximations[j][i])\n\t\t# \t\ti += 1\n\t\t# \tj += 1\n\t\tself.iterations = tuple(range(k))\n\t\tself.approximations = tuple(approximations)\n\t\tself.errors = tuple(errors)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Approximations\": self.approximations, \"Error\": self.errors})\n\n\tdef jacobi(self):\n\t\t\"\"\"Given A*x = b, use `self.norm_type` to find x via the Jacobi Method.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.DataFrame : dataframe\n\t\t\tSummarized dataframe from iterations.\n\n\t\tYields\n\t\t-------\n\t\tself.iterations : tuple\n\t\t\tCollection of iterations through method.\n\n\t\tself.approximations : tuple\n\t\t\tCollection of approximated, iterative solutions.\n\n\t\tself.errors : tuple\n\t\t\tCollection of yielded norms.\n\n\t\tWarnings\n\t\t--------\n\t\tPrints to console whether or not a solution was found within the specified tolerance with the supplied, initial guess.\n\n\t\tSee Also\n\t\t--------\n\t\tnorms.l_infinity() : Will find the l_infinity norm between x0 and xi.\n\n\t\tnorms.l_two() : Will find the l_2 norm between x0 and xi.\n\n\t\tNotes\n\t\t-----\n\t\tjacobi():\n\t\t[x]_(k) = ( D^(-1)*(L + U) ) * [x]_(k - 1) + ( D^(-1) ) * [b]\n\t\t\"\"\"\n\t\tA, x0, b, tol, N = self.A, self.x0, self.b, self.tol, self.max_iter\n\t\tnorm_type, norm = self.norm_type, tol*10\n\t\tk, n, approximations, errors = 1, len(x0), [x0], [norm]\n\t\twhile errors[-1] > tol and k <= N:\n\t\t\ti, xi = 0, np.zeros_like(x0)\n\t\t\twhile i < n:\n\t\t\t\tj, y = 0, 0.\n\t\t\t\twhile j < n:\n\t\t\t\t\tif j != i:\n\t\t\t\t\t\ty += A[i][j]*x0[j]\n\t\t\t\t\tj += 1\n\t\t\t\txi[i] = (-y + b[i])/A[i][i]\n\t\t\t\ti += 1\n\t\t\tif norm_type == \"l_infinity\":\n\t\t\t\tnorm = norms(xi, x0).l_infinity()\n\t\t\telif norm_type == \"l_two\":\n\t\t\t\tnorm = norms(xi, x0).l_two()\n\t\t\tapproximations.append(xi)\n\t\t\terrors.append(norm)\n\t\t\tx0 = xi\n\t\t\tk += 1\n\t\tif k <= N: print(\"Congratulations! Solution found!\")\n\t\telse: print(\"Warning! Solution could not be found with initial guess or tolerance.\")\n\t\t# m, n = len(approximations[0]), len(approximations)\n\t\t# X_matrix, j = np.zeros((m,n)), 0\n\t\t# while j < n:\n\t\t# \ti = 0\n\t\t# \twhile i < m:\n\t\t# \t\tX_matrix[i][j] = float(approximations[j][i])\n\t\t# \t\ti += 1\n\t\t# \tj += 1\n\t\tself.iterations = tuple(range(k))\n\t\tself.approximations = tuple(approximations)\n\t\tself.errors = tuple(errors)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Approximations\": self.approximations, \"Error\": self.errors})\n\n\t# def newton_raphson(self, functions, symbols, x0, powers, max_iter=100, norm_type=None):\n\t# \t\"\"\"Given an array of functions, symbols, and initial guesses, employ the Newton-Raphson Method to find solution within tolerance.\n\n\t# \tRoot-finding problem: f(x) = 0. \n\n\t# \t!!! Use lowest k !!!\n\n\t# \tParameters\n\t# \t----------\n\n\t# \tfunctions\n\n\t# \tsymbols\n\n\t# \tx0\n\n\t# \tpowers\n\n\t# \tmax_iter\n\n\t# \tnomr_type\n\n\t# \tp0 : float\n\t# \t\tInitial guess.\n\n\t# \tk : float, optional\n\t# \t\tAbsolute maximum slope of function.\n\n\t# \tYields\n\t# \t-------\n\t# \tself.iterations : tuple\n\t# \t\tCollection of iterations through method.\n\n\t# \tself.approximations : tuple\n\t# \t\tCollection of approximated, iterative solutions.\n\n\t# \tself.errors : tuple\n\t# \t\tCollection of yielded norms.\n\n\t# \tRaises\n\t# \t------\n\t# \t__bad_iter : string\n\t# \tIf input for desired iterations was assigned not an integer.\n\n\t# \t__must_be_expression : string\n\t# \t\tIf input `f` was of array, list, tuple, etcetera...\n\n\t# \tWarns\n\t# \t-----\n\t# \t__solution_found : string\n\t# \t\tInform user that solution was indeed found.\n\n\t# \t__solution_not_found : string\n\t# \t\tIf initial guess or tolerance were badly defined.\n\n\t# \tNotes\n\t# \t-----\n\t# \tf'(x) != 0.\n\n\t# \tNot root-bracketed.\n\n\t# \tInitial guess must be close to real solution; else, will converge to different root or oscillate (if symmetric).\n\n\t# \tCheck that |g'(x)| <= (leading coefficient of g'(x)) for all x in [a, b].\n\n\t# \tTechnique based on first Taylor polynomial expansion of `f` about `p0` and evaluated at x = p. |p - p0| is assumed small; therefore, 2nd order Taylor term, the error, is small.\n\n\t# \tNewton-Raphson has quickest convergence rate.\n\n\t# \tThis method can be viewed as fixed-point iteration.\n\n\t# \tTheorem:\n\t# \t1) Existence of a fixed-point:\n\t# \t\tIf g in C[a, b] and g(x) in C[a, b] for all x in [a, b], then function, g has a fixed point in [a, b].\n\n\t# \t2) Uniqueness of a fixed point:\n\t# \t\tIf g'(x) exists on [a, b] and a positive constant, `k` < 1 exist with {|g'(x)| <= k  |  x in (a, b)}, then there is exactly one fixed-point, `p` in [a, b].\n\n\t# \tConverges by O(linear) if g'(p) != 0, and O(quadratic) if g'(p) = 0 and g''(p) < M, where M = g''(xi) that is the error function.\n\n\t# \tExamples \n\t# \t--------\n\t# \tIf  g(x) = x**2 - 2\n\n\t# \tThen\tp = g(p) = p**2 - 2\n\n\t# \t=>  p**2 - p - 2 = 0\n\t# \t\"\"\"\n\t# \tdef jacobian(g, sym_x, x):\n\t# \t\tn = len(x)\n\t# \t\tjacMatrix = np.zeros((n, n))\n\t# \t\tfor i in range(0, n):\n\t# \t\t\tfor j in range(0, n):\n\t# \t\t\t\tJ_ij = sp.diff(g[i](*sym_x), sym_x[j])\n\t# \t\t\t\ttemp = sp.lambdify(sym_x, J_ij)(*x)\n\t# \t\t\t\tif isinstance(temp, type(np.array([1]))): temp = temp[0]\n\t# \t\t\t\tjacMatrix[i][j] = temp\n\t# \t\treturn\n\t# \tnorm_type = self.norm_type\n\t# \tfunctions, x0, b, norm = self.A, self.x0, self.b, self.tol*10\n\t# \txi = np.zeros_like(x0)\n\t# \tX0, error = [], []\n\t# \tk, n = 0, len(x0)\n\t# \tfor symbol in symbols:\n\t# \t\tif isinstance(symbol, (str, type(sp.Symbol(\"x\")))): continue\n\t# \t\telse: raise TypeError(f\"All elements of `symbols` must be of type string or symbol: {symbol} was neither.\")\n\t# \tif max_iter <= 0 or not isinstance(max_iter, (int, float)): ValueError(f\"ERROR! Maximum iterations, N must be an integer greater than zero. {max_iter} was given and not understood.\")\n\t# \tif norm_type == None:\n\t# \t\ttol = []\n\t# \t\tfor p in powers: tol.append(10**p)\n\t# \telse: tol = 10**powers\n\t# \tfunctions, x0 = np.reshape(functions, (1, n))[0], np.reshape(x0, (n, 1))\n\t# \tX0.append(x0)\n\t# \terror.append(tol)\n\t# \tfor k in range(1, max_iter):\n\t# \t\tJ = jacobian(functions, symbols, x0)\n\t# \t\txk, g = np.zeros_like(x0), np.zeros_like(x0)\n\t# \t\tfor i in range(0, n): \n\t# \t\t\tg[i] = sp.lambdify(symbols, functions[i](*symbols))(*x0)\n\t# \t\ty0 = np.linalg.solve(J, -g)\n\t# \t\txk = x0 + y0\n\t# \t\tif norm_type == \"l_two\":\n\t# \t\t\tboolean = []\n\t# \t\t\tfor i in range(0, n-1):\n\t# \t\t\t\tif abs(xk[i] - x0[i])[0] <= tol[i]: boolean.append(1)\n\t# \t\t\t\telse: boolean.append(0)\n\t# \t\t\tx0 = xk\n\t# \t\t\tif sum(boolean) < n: continue\n\t# \t\t\telse: break\n\t# \t\telif norm_type == \"l_infinity\":\n\t# \t\t\tnorm = norms.l_infinity(xk, x0)\n\t# \t\t\terror.append(norm)\n\t# \t\t\tX0.append(xk)\n\t# \t\t\ttol_exit = 0\n\t# \t\t\tfor tl in tol:\n\t# \t\t\t\tif norm <= tl: tol_exit += 0\n\t# \t\t\t\telse: tol_exit += 1\n\t# \t\t\tif tol_exit == 0:\n\t# \t\t\t\tself.iterations = tuple(range(k))\n\t# \t\t\t\tself.approximations = tuple(X0)\n\t# \t\t\t\tself.errors = tuple(error)\n\t# \t\t\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Approximations\": self.approximations, \"Error\": self.errors})\n\t# \t\t\telse: x0 = xk\n\t# \t\telse: raise ValueError(\"ERROR! Desired norm type was not understood. Please choose 'l_infinity' or 'l_two'.\")\n\t# \treturn x0\n\n\tdef successive_relaxation(self, omega=None):\n\t\t\"\"\"Given A*x = b, use `self.norm_type` to find vector, x via the Successive Relaxtion Method. Is Successive Over-Relaxation if omega > 1, Successive Under-Relaxation if omega < 1, and is Gauss-Seidel if omega = 1.\n\n\t\tParameters\n\t\t----------\n\t\tomega : None or float, optional\n\t\t\tRelaxation parameter.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.DataFrame : dataframe\n\t\t\tSummarized dataframe from iterations.\n\n\t\tYields\n\t\t-------\n\t\tself.iterations : tuple\n\t\t\tCollection of iterations through method.\n\n\t\tself.approximations : tuple\n\t\t\tCollection of approximated, iterative solutions.\n\n\t\tself.errors : tuple\n\t\t\tCollection of yielded norms.\n\n\t\tWarnings\n\t\t--------\n\t\tPrints to console optimal choice of omega, regardless of assignment, and whether or not a solution was found within the specified tolerance with the supplied, initial guess.\n\n\t\tSee Also\n\t\t--------\n\t\tnorms.l_infinity() : Will find the l_infinity norm between x0 and xi.\n\n\t\tnorms.l_two() : Will find the l_2 norm between x0 and xi.\n\n\t\tfind_omega() : Will analyze system of equation to find an optimal omega, if possible, and inform user.\n\n\t\tgauss_seidel() : Technique is Gauss-Seidel's modified by omega.\n\n\t\tNotes\n\t\t-----\n\t\tgauss_seidel():\n\t\t\t[x]_(k) = ( (D - L)^(-1) * U ) * [x]_(k - 1) + ( (D - L)^(-1) )*[b]\n\n\t\tsuccessive_relaxation():\n\t\t\t[x]_(k) = ( (D - wL)^(-1) * ((1 - w)*D + w*U) ) * [x]_(k - 1) + w*( (D - w*L)^(-1) )*[b]\n\n\t\tomega will be analyzed independent of assigned value which will be used if not specified in assignment.\n\t\t\"\"\"\n\t\tif omega == None:\n\t\t\ttry: w = self.user_omega\n\t\t\texcept AttributeError:\n\t\t\t\ttry: w = self.best_omega\n\t\t\t\texcept AttributeError:\n\t\t\t\t\t# w = super().find_omega(A, x0)\n\t\t\t\t\tw = self.find_omega()\n\t\t\t\t\tprint(f\"Warning! Omega was not given; therefore, I attempted to choose one, {w}.\")\n\t\t\t\telse: print(f\"Warning! Using `self.best_omega` = {w}.\")\n\t\t\telse: print(f\"Warning! Using `self.user_omega` = {w}.\")\n\t\t\tif w <= 0: raise ValueError(\"Either a positive omega was not given, or I could not choose one.\")\n\t\telif omega != None and isinstance(omega, (int, float)):\n\t\t\t# omega = find_omega(A, x0, w)\n\t\t\tw = self.find_omega(omega=omega)\n\t\t\tprint(f\"Warning! omega = {omega} given. Which is not optimum: {w}\")\n\t\t\tw = omega\n\t\telse: raise ValueError(f\"ERROR! Either a positive omega was not given, or I could not choose one.\")\n\t\tA, x0, b, tol, N = self.A, self.x0, self.b, self.tol, self.max_iter\n\t\tnorm_type, norm = self.norm_type, tol*10\n\t\tk, n, approximations, errors = 0, len(x0), [x0], [norm]\n\t\twhile norm > tol and k <= N:\n\t\t\ti, xi = 0, np.zeros_like(x0)\n\t\t\t# xgs = super().gauss_seidel(x0)\n\t\t\txgs = self.gauss_seidel()[\"Approximations\"].values[-1]\n\t\t\twhile i < n:\n\t\t\t\txi[i] = (1 - w)*x0[i] + w*xgs[i]\n\t\t\t\ti += 1\n\t\t\tif norm_type == \"l_infinity\":\n\t\t\t\tnorm = norms(xi, x0).l_infinity()\n\t\t\telif norm_type == \"l_two\":\n\t\t\t\tnorm = norms(xi, x0).l_two()\n\t\t\tapproximations.append(xi)\n\t\t\terrors.append(norm)\n\t\t\tx0 = xi\n\t\t\tk += 1\n\t\tif k <= N: print(\"Congratulations! Solution found!\")\n\t\telse: print(\"Warning! Solution could not be found with initial guess or tolerance.\")\n\t\t# m, n = len(approximations[0]), len(approximations)\n\t\t# X_matrix, j = np.zeros((m,n)), 0\n\t\t# while j < n:\n\t\t# \ti = 0\n\t\t# \twhile i < m:\n\t\t# \t\tX_matrix[i][j] = float(approximations[j][i])\n\t\t# \t\ti += 1\n\t\t# \tj += 1\n\t\tself.iterations = tuple(range(k))\n\t\tself.approximations = tuple(approximations)\n\t\tself.errors = tuple(errors)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Approximations\": self.approximations, \"Error\": self.errors})\n# --------------------\n\n# --------------------\n# interpolations\nclass cubic_spline:\n\tdef __init__(self, domain, function):\n\t\tself.domain, self.function = domain, function\n\n\tdef clamped(self, variable=sp.Symbol(\"x\"), fp=0):\n\t\t\"\"\"Given a domain and range, construct a spline polynomial within interval by some condition.\n\n\t\tParameters\n\t\t----------\n\t\tX : array\n\t\t\tInput domain.\n\n\t\tf : array or expression\n\t\t\tDesired/Found range of interest.\n\n\t\tx : symbol\n\t\t\tRespected variable in derivative of equation. Assumed to be `'x'` if not stated.\n\n\t\tfp : array or expression\n\t\t\tDerivative at each point in `f`.\n\n\t\tReturns\n\t\t-------\n\t\tY : array\n\t\t\tFinally evaluated solutions.\n\n\t\tsplines_j : list\n\t\t\tAggregate of splines on each interval.\n\n\t\tspline : string\n\t\t\tTotally constructed spline polynomial.\n\n\t\tRaises\n\t\t------\n\t\tbad_X : string\n\t\t\tIf {`X`} is neither n x 1 nor 1 x n array.\n\n\t\tbad_f : string\n\t\t\tIf `f` is not an expression or function and is not an n x 1 or 1 x n array.\n\n\t\tbad_data : string\n\t\t\tIf {`X`} and {`f`} are of unequal length.\n\t\t\n\t\tbad_fp : string\n\t\t\tIf `fp` is not an expression or function and is not an n x 1 or 1 x n array.\n\n\t\tmissing_fp : string\n\t\t\tOutput message that derivative data or expression is missing.\n\n\t\tSee Also\n\t\t--------\n\t\tmake_array() : Translates input expression to array from given `X`.\n\n\t\tendpoint() : Relies on another technique to find derivatives at endpoints if not explicitly provided by data, `fp` nor an expression.\n\n\t\tmidpoint() : Finds the derivatives at points within the bounds of the endpoints.\n\n\t\tdiagonality() : Determines whether input matrix is strictly, diagonally dominant.\n\n\t\tNotes\n\t\t-----\n\t\t`fp` will be calculated if not specified.\n\n\t\tMethod uses many, low-ordered polynomials to fit larger data sets. This minimizes computational load, which conversely greatly increases for larger data sets that yield high-ordered polynomials.\n\n\t\tGeneral form: \n\t\tSj(x) = aj + bj(x - xj) + cj(x - xj)^2 + dj(x - xj)^3\n\n\t\tClamped splines fit the constructed polynomial to the given data and its der\n\t\tivatives at either endpoint.\n\n\t\tIf selected `condition` is `'natural'`, then `fp = 0`, because derivative is assumed to be straight line outside of data set.\n\n\t\tDefinitions of cubic spline conditions:\n\t\ta) S(x) is a cubic polynomial, Sj(x) on sub-interval [x_(j), x_(j + 1)] for each j = 0, 1, ..., n - 1;\n\n\t\tb) Sj(x_(j)) = f(x_(j)) and Sj(x_(j + 1)) = f(x_(j + 1)) for each j = 0, 1, ..., n - 1;\n\n\t\tc) S_(j + 1)(x_(j + 1)) = Sj(x_(j + 1)) for each j = 0, 1, ..., n - 2;\n\n\t\td) S_(j + 1)'(x_(j + 1)) = Sj'(x_(j + 1)) for each j = 0, 1, ..., n - 2;\n\n\t\te) One of the following conditions is satisfied:\n\t\t\t1) S''(x0) = S''(xn) = 0\t\t\t\t->  `'natural'`\n\t\t\t\n\t\t\t2) S'(x0) = f'(x0) and S'(xn) = f'(xn)  ->  `'clamped'`\n\t\t\"\"\"\n\t\tdef algorithm(g, gp):\n\t\t\tY, YP = np.array(g), np.array(gp)\n\t\t\t# STEP 1:   build list, h_i\n\t\t\ti, H = 0, np.zeros(n)\n\t\t\twhile i < n:\n\t\t\t\tH[i] = X[i+1] - X[i]\n\t\t\t\ti += 1\n\t\t\t# STEP 2:   define alpha list endpoints\n\t\t\tA, AP, ALPHA = Y, YP, np.zeros(m)\n\t\t\tALPHA[0] = 3*(A[1] - A[0])/H[0] - 3*AP[0]\n\t\t\tALPHA[n] = 3*AP[n] - 3*(A[n] - A[n-1])/H[n-1]\n\t\t\t# STEP 3:   build list, alpha_i\n\t\t\ti = 1\n\t\t\twhile i <= n-1:\n\t\t\t\tALPHA[i] = 3/H[i]*(A[i+1] - A[i]) - 3/H[i-1]*(A[i] - A[i-1])\n\t\t\t\ti += 1\n\t\t\t# Algorithm 6.7 to solve tridiagonal\n\t\t\t# STEP 4:   define l, mu, and z first points\n\t\t\tL, MU, Z, C = np.zeros(m), np.zeros(m), np.zeros(m), np.zeros(m)\n\t\t\tL[0], MU[0] = 2*H[0], 0.5\n\t\t\tZ[0] = ALPHA[0]/L[0]\n\t\t\t# STEP 5:   build lists l, mu, and z\n\t\t\ti = 1\n\t\t\twhile i <= n-1:\n\t\t\t\tL[i] = 2*(X[i+1] - X[i-1]) - H[i-1]*MU[i-1]\n\t\t\t\tMU[i] = H[i]/L[i]\n\t\t\t\tZ[i] = (ALPHA[i] - H[i-1]*Z[i-1])/L[i]\n\t\t\t\ti += 1\n\t\t\t# STEP 6:   define l, z, and c endpoints\n\t\t\tL[n] = H[n-1]*(2-MU[i-1])\n\t\t\tZ[n] = (ALPHA[n] - H[n-1]*Z[n-1])/L[n]\n\t\t\tC[n] = Z[n]\n\t\t\t# STEP 7:   build lists c, b, and d\n\t\t\ti, j, B, D = 1, 0, np.zeros(n), np.zeros(n)\n\t\t\twhile i <= n:\n\t\t\t\tj = n-i\n\t\t\t\tC[j] = Z[j] - MU[j]*C[j+1]\n\t\t\t\tB[j] = (A[j+1] - A[j])/H[j] - H[j]*(C[j+1] + 2*C[j])/3\n\t\t\t\tD[j] = (C[j+1] - C[j])/(3*H[j])\n\t\t\t\ti += 1\n\t\t\treturn Y, A, B, C, D\n\t\tsym_X, sym_function, sym_fp = \"self.X\", \"self.f\", \"fp\"\n\t\tbad_X = \"Input domain, \" + sym_X + \" was neither an n x 1 nor a 1 x n array.\"\n\t\tbad_f = \"Input range, \" + sym_function + \" was neither function nor expression and not an n x 1 or 1 x n array.\"\n\t\tbad_data = \"Arrays \" + sym_X + \" and \" + sym_function + \" must be of equal length.\"\n\t\tbad_fp = \"Derivative range was neither function nor expression and not an n x 1 or 1 x n array.\"\n\t\tbad_fp_data = \"Arrays \" + sym_X + \", \" + sym_function + \", and \" + sym_fp + \" must be of equal length.\"\n\t\tmissing_fp = \"Missing derivative data or expression.\"\n\t\tf, X = self.function, self.domain\n\t\tif np.sum(X.shape) > np.sum(X.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\tif not isinstance(f, (FunctionType, sp.Expr)):\n\t\t\tif np.sum(f.shape) > np.sum(f.shape[0]): raise ValueError(\"ERROR! \" + bad_f)\n\t\t\telif len(X) != len(f): raise ValueError(bad_data)\n\t\t\telse: g = f\n\t\telif isinstance(f, (FunctionType, sp.Expr)):\n\t\t\tg = make_array(X, f)\n\t\tif np.sum(fp.shape) != 0:\n\t\t\tif not isinstance(fp, (FunctionType, sp.Expr)):\n\t\t\t\tif np.sum(fp.shape) > np.sum(fp.shape[0]): raise ValueError(\"ERROR! \" + bad_fp)\n\t\t\t\telif len(X) != len(fp): raise ValueError(\"ERROR! \" + bad_fp_data)\n\t\t\t\telse: gp = fp\n\t\t\telif isinstance(fp, (FunctionType, sp.Expr)): gp = make_array(X, fp)\n\t\telif fp == 0:\n\t\t\tif isinstance(f,(FunctionType, sp.Expr)):\n\t\t\t\tsym_function = sp.N(sp.sympify(f(variable)))\n\t\t\t\tf = sp.lambdify(variable, sym_function)\n\t\t\t\tfp = sp.diff(sym_function)\n\t\t\t\tgp = make_array(X, fp)\n\t\t\telif not isinstance(f,(FunctionType, sp.Expr)):\n\t\t\t\tgp = []\n\t\t\t\tif len(X) > 2:\n\t\t\t\t\tgp.append(endpoint(X, f, X[1]-X[0], \"three\", \"left\"))\n\t\t\t\t\ti, n = 1, len(f) - 1\n\t\t\t\t\twhile i < n: \n\t\t\t\t\t\tgp.append(midpoint(X, f, X[i]-X[i-1], \"three\", i))\n\t\t\t\t\t\ti += 1\n\t\t\t\t\tgp.append(endpoint(X, f, X[-2]-X[-1], \"three\", \"right\"))\n\t\t\t\telif len(X) > 5:\n\t\t\t\t\tgp.append(endpoint(X, f, X[1]-X[0], \"five\", \"left\"))\n\t\t\t\t\ti, n = 1, len(X) - 1\n\t\t\t\t\twhile i < n: \n\t\t\t\t\t\tgp.append(midpoint(X, f, X[i]-X[i-1], \"five\", i))\n\t\t\t\t\t\ti += 1\n\t\t\t\t\tgp.append(endpoint(X, f, X[-2]-X[-1], \"five\", \"right\"))\n\t\t\telse: raise ValueError(\"ERROR! \" + missing_fp)\n\t\tm = len(X)\n\t\tn = m - 1\n\t\tY, A, B, C, D = algorithm(g, gp)\n\t\tj, splines_j = 0, []\n\t\twhile j <= n-1:\n\t\t\txj, aj, bj, cj, dj = X[j], A[j], B[j], C[j], D[j]\n\t\t\tsj = aj + bj*(variable - xj) + cj*(variable - xj)**2 + dj*(variable - xj)**3\n\t\t\tsplines_j.append(sj)\n\t\t\tj += 1\n\t\tspline = sp.simplify(sum(splines_j))\n\t\treturn Y, splines_j, spline\n\n\tdef natural(self, variable=sp.Symbol(\"x\")):\n\t\t\"\"\"Given a domain and range, construct a spline polynomial within interval by some condition.\n\n\t\tParameters\n\t\t----------\n\t\tX : array\n\t\t\tInput domain.\n\n\t\tf : array or expression\n\t\t\tDesired/Found range of interest.\n\n\t\tReturns\n\t\t-------\n\t\tY : array\n\t\t\tFinally evaluated solutions.\n\n\t\tsplines_j : list\n\t\t\tAggregate of splines on each interval.\n\n\t\tspline : string\n\t\t\tTotally constructed spline polynomial.\n\n\t\tRaises\n\t\t------\n\t\tbad_X : string\n\t\t\tIf {`X`} is neither n x 1 nor 1 x n array.\n\n\t\tbad_f : string\n\t\t\tIf `f` is not an expression or function and is not an n x 1 or 1 x n array.\n\n\t\tbad_data : string\n\t\t\tIf {`X`} and {`f`} are of unequal length.\n\n\t\tSee Also\n\t\t--------\n\t\tmake_array() : Translates input expression to array from given `X`.\n\n\t\tdiagonality() : Determines whether input matrix is strictly, diagonally dominant.\n\n\t\tNotes\n\t\t-----\n\t\tMethod uses many, low-ordered polynomials to fit larger data sets. This minimizes computational load, which conversely greatly increases for larger data sets that yield high-ordered polynomials.\n\n\t\tGeneral form: \n\t\tSj(x) = aj + bj(x - xj) + cj(x - xj)^2 + dj(x - xj)^3\n\n\t\tClamped splines fit the constructed polynomial to the given data and its der\n\t\tivatives at either endpoint.\n\n\t\tIf selected `condition` is `'natural'`, then `fp = 0`, because derivative is assumed to be straight line outside of data set.\n\n\t\tDefinitions of cubic spline conditions:\n\t\ta) S(x) is a cubic polynomial, Sj(x) on sub-interval [x_(j), x_(j + 1)] for each j = 0, 1, ..., n - 1;\n\n\t\tb) Sj(x_(j)) = f(x_(j)) and Sj(x_(j + 1)) = f(x_(j + 1)) for each j = 0, 1, ..., n - 1;\n\n\t\tc) S_(j + 1)(x_(j + 1)) = Sj(x_(j + 1)) for each j = 0, 1, ..., n - 2;\n\n\t\td) S_(j + 1)'(x_(j + 1)) = Sj'(x_(j + 1)) for each j = 0, 1, ..., n - 2;\n\n\t\te) One of the following conditions is satisfied:\n\t\t\t1) S''(x0) = S''(xn) = 0\t\t\t\t->  `'natural'`\n\t\t\t\n\t\t\t2) S'(x0) = f'(x0) and S'(xn) = f'(xn)  ->  `'clamped'`\n\t\t\"\"\"\n\t\tdef algorithm(g):\n\t\t\tY = g\n\t\t\t# STEP 1:   build list, h_i\n\t\t\tH, i = np.zeros(n), 0\n\t\t\twhile i < n:\n\t\t\t\tH[i] = X[i+1] - X[i]\n\t\t\t\ti += 1\n\t\t\t# STEP 2:   build list, alpha_i\n\t\t\tA, ALPHA = Y, np.zeros(m)\n\t\t\ti = 1\n\t\t\twhile i <= n-1:\n\t\t\t\tALPHA[i] = 3/H[i]*(A[i+1] - A[i]) - 3/H[i-1]*(A[i] - A[i-1])\n\t\t\t\ti += 1\n\t\t\t# Algorithm 6.7 to solve tridiagonal\n\t\t\t# STEP 3:   define l, mu, and z first points\n\t\t\tL, MU, Z, C = np.zeros(m), np.zeros(m), np.zeros(m), np.zeros(m)\n\t\t\tL[0], MU[0], Z[0] = 1, 0, 0\n\t\t\t# STEP 4:   build lists l, mu, and z\n\t\t\ti = 1\n\t\t\twhile i <= n-1:\n\t\t\t\tL[i] = 2*(X[i+1] - X[i-1]) - H[i-1]*MU[i-1]\n\t\t\t\tMU[i] = H[i]/L[i]\n\t\t\t\tZ[i] = (ALPHA[i] - H[i-1]*Z[i-1])/L[i]\n\t\t\t\ti += 1\n\t\t\t# STEP 5:   define l, z, and c endpoints\n\t\t\tL[n], Z[n], C[n] = 1, 0, 0\n\t\t\t# STEP 6:   build lists c, b, and d\n\t\t\ti, j, B, D = 1, 0, np.zeros(n), np.zeros(n)\n\t\t\twhile i <= n:\n\t\t\t\tj = n-i\n\t\t\t\tC[j] = Z[j] - MU[j]*C[j+1]\n\t\t\t\tB[j] = (A[j+1] - A[j])/H[j] - H[j]*(C[j+1] + 2*C[j])/3\n\t\t\t\tD[j] = (C[j+1] - C[j])/(3*H[j])\n\t\t\t\ti += 1\n\t\t\treturn Y, A, B, C, D\n\t\tsym_X, sym_function = \"self.X\", \"self.f\"\n\t\tbad_X = \"Input domain, \" + sym_X + \" was neither an n x 1 nor a 1 x n array.\"\n\t\tbad_f = \"Input range, \" + sym_function + \" was neither function nor expression and not an n x 1 or 1 x n array.\"\n\t\tbad_data = \"Arrays \" + sym_X + \" and \" + sym_function + \" must be of equal length.\"\n\t\tX, f = np.array(self.domain), self.function\n\t\tif np.sum(X.shape) > np.sum(X.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\tif not isinstance(f, (FunctionType, sp.Expr)):\n\t\t\tf = np.array(f)\n\t\t\tif np.sum(f.shape) > np.sum(f.shape[0]): raise ValueError(\"ERROR! \" + bad_f)\n\t\t\telif len(X) != len(f): raise ValueError(\"ERROR! \" + bad_data)\n\t\t\telse: g = f\n\t\telif isinstance(f, (FunctionType, sp.Expr)):\n\t\t\tg = make_array(X, f)\n\t\tm = len(X)\n\t\tn = m - 1\n\t\tY, A, B, C, D = algorithm(g)\n\t\tj, splines_j = 0, []\n\t\twhile j <= n-1:\n\t\t\txj, aj, bj, cj, dj = X[j], A[j], B[j], C[j], D[j]\n\t\t\tsj = aj + bj*(variable - xj) + cj*(variable - xj)**2 + dj*(variable - xj)**3\n\t\t\tsplines_j.append(sj)\n\t\t\tj += 1\n\t\tspline = sp.simplify(sum(splines_j))\n\t\treturn Y, splines_j, spline\n\ndef hermite(X, FX, x=sp.Symbol(\"x\"), FP=0):\n\t\"\"\"Given a domain and range, construct a Hermetic polynomial.\n\n\tParameters\n\t----------\n\tX : array\n\t\tInput domain.\n\n\tFX : array\n\t\tDesired/Found range of interest.\n\n\tx : symbol\n\t\tRespected variable in derivative of equation. Assumed to be `'x'` if not stated.\n\n\tFP : array or expression\n\t\tDerivative at each point in `FX`.\n\n\tReturns\n\t-------\n\tpolynomial : expression\n\t\tLambdified Hermetic polynomial.\n\n\tRaises\n\t------\n\tbad_X : string\n\t\tIf {`X`} is neither n x 1 nor 1 x n array.\n\n\tbad_FX : string\n\t\tIf {`FX`} is neither n x 1 nor 1 x n array.\n\n\tbad_data : string\n\t\tIf {`X`} and {`FX`} are of unequal length.\n\n\tbad_FP : string\n\t\tIf `FP` is not an expression or function and is not an n x 1 or 1 x n array.\n\n\tbad_FP_data : string\n\t\tIf {`X`}, {`FX`}, or {`FP`} are of unequal lengths.\n\n\tmissing_FP : string\n\t\tIf `FP = 0` and `FX` is not an expression, then missing derivative data or expression.\n\n\tWarns\n\t-----\n\tmade_poly : string\n\t\tDisplays the string form of the equation.\n\n\tSee Also\n\t--------\n\tmake_array() : Prints string that expression was used to make array.\n\n\tNotes\n\t-----\n\t`FP` calculated if not specified.\n\n\tSlow computation time for larger data sets.\n\n\tOscullating curve incorporates Taylor and Lagrangian polynomials to kiss the data and match each data point's derivatives. Which fits the curve to the shape of the data and its trend.\n\t\"\"\"\n\tsym_X, sym_FX, sym_FP = \"X\", \"FX\", \"FP\"\n\tbad_X = \"Input domain, \" + sym_X + \" was neither an n x 1 nor a 1 x n array.\"\n\tbad_FX = \"Input range, \" + sym_FX + \" was neither an n x 1 nor a 1 x n array.\"\n\tbad_data = \"Arrays \" + sym_X + \" and \" + sym_FX + \" must be of equal length.\"\n\tbad_FP = \"Derivative range was neither function nor expression and not an n x 1 or 1 x n array.\"\n\tbad_FP_data = \"Arrays \" + sym_X + \", \" + sym_FX + \", and \" + sym_FP + \" must be of equal length.\"\n\tmissing_FP = \"Missing derivative data or expression.\"\n\tmade_poly = \"I have found your requested polynomial! P = \"\n\tif np.sum(X.shape) > np.sum(X.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\tif not isinstance(FX, (FunctionType, sp.Expr)):\n\t\tif np.sum(FX.shape) > np.sum(FX.shape[0]): raise ValueError(\"ERROR! \" + bad_FX)\n\t\telif len(X) != len(FX): raise ValueError(\"ERROR! \" + bad_data)\n\telif isinstance(FX,(FunctionType, sp.Expr)): g = make_array(X, FX)\n\tif FP != 0:\n\t\tif not isinstance(FP, (FunctionType, sp.Expr)):\n\t\t\tif np.sum(FP.shape) > np.sum(FP.shape[0]): raise ValueError(\"ERROR! \" + bad_FP)\n\t\t\tif len(X) != len(FP): raise ValueError(\"ERROR! \" + bad_FP_data)\n\t\telif isinstance(FP,(FunctionType, sp.Expr)): FP = make_array(X, FP)\n\telif FP == 0:\n\t\tif isinstance(FX,(FunctionType, sp.Expr)):\n\t\t\tfp = sp.lambdify(x, sp.diff(FX(x)))\n\t\t\tgp = make_array(X, fp)\n\t\telse: print(\"Warning! \" + missing_FP)\n\tn = len(X)\n\ti, Q, Z = 0, np.zeros((2*n+1,2*n+1)), np.zeros((2*n+1,1))\n\twhile i < n:\n\t\tZ[2*i], Z[2*i + 1] = X[i], X[i]\n\t\tQ[2*i][0], Q[2*i + 1][0] = g[i], g[i]\n\t\tQ[2*i + 1][1] = gp[i]\n\t\tif i != 0: Q[2*i][1] = (Q[2*i][0] - Q[2*i - 1][0]) \\\n\t\t\t/ (Z[2*i] - Z[2*i - 1])\n\t\ti += 1\n\ti = 2\n\twhile i < 2*n + 1:\n\t\tj = 2\n\t\twhile j <= i:\n\t\t\tQ[i][j] = (Q[i][j - 1] - Q[i - 1][j - 1]) \\\n\t\t\t/ (Z[i] - Z[i - j])\n\t\t\tj += 1\n\t\ti += 1\n\ti, y, terms = 0, 1, []\n\twhile i < n:\n\t\tj, xi = 2*i, (x - X[i])\n\t\tqjj, qj1 = Q[j][j], Q[j + 1][j + 1]\n\t\tterms.append(qjj*y)\n\t\ty = y*xi\n\t\tterms.append(qj1*y)\n\t\ty = y*xi\n\t\ti += 1\n\tpolynomial = sp.lambdify(x, sp.simplify(sum(terms)))\n\tprint(\"Congratulations! \", made_poly + str(polynomial(x)))\n\treturn polynomial\n\ndef lagrange(X, Y, x=sp.Symbol(\"x\")):\n\t\"\"\"Given a domain and range, construct a Lagrangian polynomial.\n\n\tParameters\n\t----------\n\tX : array\n\t\tInput domain.\n\n\tY : array or expression\n\t\tDesired/Found range of interest.\n\n\tx : symbol\n\t\tRespected variable in derivative of equation. Assumed to be `'x'` if not stated.\n\n\tReturns\n\t-------\n\tyn : list\n\t\tAggregate of Lagrangian terms.\n\n\tsp.lambdify(x, polynomial) : expression\n\t\tLambdified Lagrangian polynomial.\n\n\tbound : list\n\t\tPropogation of error through construction.\n\n\tsum(bound)\n\t\tTotal error.\n\n\tRaises\n\t------\n\tbad_X : string\n\t\tIf {`X`} is neither n x 1 nor 1 x n array.\n\n\tbad_Y : string\n\t\tIf {`Y`} is neither n x 1 nor 1 x n array.\n\n\tbad_data : string\n\t\tIf {`X`} and {`Y`} are of unequal length.\n\n\tWarns\n\t-----\n\tmade_poly : string\n\t\tDisplays the string form of the equation.\n\n\tSee Also\n\t--------\n\tmake_array() : Prints string that expression was used to make array.\n\n\tNotes\n\t--------\n\tPolynomial will quickly begin to oscillate for larger data sets.\n\n\tFinds a polynomial of degree n-1.\n\n\tPolynomial is of the following form:\n\tP(x) = f(x0)L_(n,0)(x) + ... + f(xn)L_(n,n)(x), where\n\n\tL_(n,k) = prod_(i=0, i!=k)^(n) (x - xi)/(xk - xi)\n\n\tExamples\n\t--------\n\tA Lagrange polynomial between (2,4) and (5,1) would be found as follows:\n\tL_(0)(x) = (x - 5)/(2 - 5) = -(x - 5)/3\n\n\tL_(1)(x) = (x - 2)/(5 - 2) = (x - 2)/3\n\n\t=>  P(x)\t= (4)*(-(x - 5)/3) + (1)*((x - 2)/3)\n\t\t\t\t= -x + 6\n\t\"\"\"\n\tdef term(xk, yk, x):\n\t\tnum, den, L_k = [], [], []\n\t\tfor xl in X:\n\t\t\tif xl != xk:\n\t\t\t\tnum.append(x-xl)\n\t\t\t\tden.append(xk-xl)\n\t\tL_k = (np.divide(np.prod(num), np.prod(den)))\n\t\treturn L_k * yk\n\tdef error(n, xi, x):\n\t\ti, roots, g, xi_error = 0, [], [], []\n\t\twhile i <= n:\n\t\t\troot = X[i]\n\t\t\troots.append(x - root)\n\t\t\tg = np.prod(roots)\n\t\t\tk = 0\n\t\t\twhile k <= n:\n\t\t\t\txi = sp.simplify(sp.diff(xi))\n\t\t\t\tk += 1\n\t\t\tdxi = np.abs(xi.evalf(subs={x: root})/(math.factorial(k)))\n\t\t\txi_error.append(np.abs(dxi))\n\t\t\txi_err = np.max(xi_error)\n\t\t\tg_prime = sp.diff(g)\n\t\t\tr = sp.solve(g_prime)\n\t\t\tif i == 0:\n\t\t\t\tr = g_prime\n\t\t\t\tgx = g.evalf(subs={x: r})\n\t\t\telif i == 1:\n\t\t\t\tgx = g.evalf(subs={x: r[0]})\n\t\t\telse:\n\t\t\t\tR = []\n\t\t\t\tfor s in r:\n\t\t\t\t\tif not isinstance(s, complex):\n\t\t\t\t\t\tR.append(g.evalf(subs={x: s}))\n\t\t\t\tgx = np.amax(np.abs(R))\n\t\t\ti += 1\n\t\treturn np.abs(xi_err*gx)\n\tsym_X, sym_Y = \"X\", \"Y\"\n\tbad_X = \"Input domain, \" + sym_X + \" was neither an n x 1 nor a 1 x n array.\"\n\tbad_Y = \"Input range, \" + sym_Y + \" was neither an n x 1 nor a 1 x n array.\"\n\tbad_data = \"Arrays \" + sym_X + \" and \" + sym_Y + \" must be of equal length.\"\n\tmade_poly = \"I have found your requested polynomial! P = \"\n\tif np.sum(X.shape) > np.sum(X.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\tif not isinstance(Y,(FunctionType, sp.Expr)):\n\t\tif np.sum(Y.shape) > np.sum(Y.shape[0]): raise ValueError(\"ERROR! \" + bad_Y)\n\t\telif len(X) != len(Y): raise ValueError(\"ERROR! \" + bad_data)\n\telif isinstance(Y,(FunctionType, sp.Expr)): Y = make_array(X, Y)\n\tk, yn, bound = 0, [], []\n\tfor xk in X:\n\t\tyn.append(term(xk, Y[k], x))\n\t\tbound.append(error(k, sp.simplify(sum(yn)), x))\n\t\tk += 1\n\tpolynomial = sp.simplify(sum(yn))\n\tprint(\"Congratulations! \", made_poly, str(polynomial))\n\treturn yn, sp.lambdify(x, polynomial), bound, sum(bound)\n\nclass least_squares:\n\tdef linear(X_i, Y_i, n, variable=sp.Symbol(\"x\")):\n\t\t\"\"\"Given a domain and range, construct some polynomial.\n\n\t\tParameters\n\t\t----------\n\t\tX_i : array\n\t\t\tInput domain.\n\n\t\tY_i : array or expression\n\t\t\tDesired/Found range of interest.\n\n\t\tn : int\n\t\t\tDegree of polynomial.\n\n\t\tReturns\n\t\t-------\n\t\tP : expression\n\t\t\tLambdified linear least square polynomial.\n\n\t\tE : float\n\t\t\tTotal error.\n\n\t\tRaises\n\t\t------\n\t\tbad_X : string\n\t\t\tIf {`X_i`} is neither n x 1 nor 1 x n array.\n\n\t\tbad_Y : string\n\t\t\tIf {`Y_i`} is neither n x 1 nor 1 x n array.\n\n\t\tbad_data : string\n\t\t\tIf {`X_i`} and {`Y_i`} are of unequal length.\n\n\t\tbad_n : string\n\t\t\tIf prescribed `n` is not an integer or is zero.\n\n\t\tWarns\n\t\t-----\n\t\tmade_poly : string\n\t\t\tDisplays the string form of the equation.\n\t\t\"\"\"\n\t\tdef poly(X):\n\t\t\tterms, k = [], 0\n\t\t\tfor x in X:\n\t\t\t\tterms.append(x*(variable**k))\n\t\t\t\tk += 1\n\t\t\tp = sp.simplify(sum(terms))\n\t\t\terr, i = 0, 0\n\t\t\tfor x_i in X_i:\n\t\t\t\tpx = p.subs(variable, x_i)\n\t\t\t\terr += (Y_i[i] - px)**2\n\t\t\t\ti += 1\n\t\t\treturn p, err\n\t\tsym_X_i, sym_Y_i = \"X_i\", \"Y_i\"\n\t\tbad_X = \"Input domain, \" + sym_X_i + \" was neither an n x 1 nor a 1 x n array.\"\n\t\tbad_Y = \"Input range, \" + sym_Y_i + \" was neither an n x 1 nor a 1 x n array.\"\n\t\tbad_data = \"Arrays \" + sym_X_i + \" and \" + sym_Y_i + \" must be of equal length.\"\n\t\tbad_n = \"Degree of polynomial must be integer and non-zero.\"\n\t\tmade_poly = \"I have found your requested polynomial! P = \"\n\t\tif np.sum(X_i.shape) > np.sum(X_i.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\tif isinstance(Y_i, (FunctionType, sp.Expr)):\n\t\t\tY_i = make_array(X_i, Y_i)\n\t\tif np.sum(Y_i.shape) > np.sum(Y_i.shape[0]): raise ValueError(\"ERROR! \" + bad_Y)\n\t\tif len(X_i) != len(Y_i): raise ValueError(\"ERROR! \" + bad_data)\n\t\tif not isinstance(n,(int)) or n == 0: raise ValueError(\"ERROR! \" + bad_n)\n\t\tm = len(X_i)\n\t\tA, x = np.zeros((n+1, n+1)), np.zeros((n+1,1))\n\t\ti, b = 0, np.zeros_like(x)\n\t\twhile i <= n:\n\t\t\tj = 0\n\t\t\twhile j <= n:\n\t\t\t\ta_ij, k = 0, 0\n\t\t\t\twhile k < m:\n\t\t\t\t\ta_ij += (X_i[k])**(i + j)\n\t\t\t\t\tk += 1\n\t\t\t\tA[i][j] = a_ij\n\t\t\t\tj += 1\n\t\t\tb_i, k = 0, 0\n\t\t\twhile k < m:\n\t\t\t\tb_i += Y_i[k]*(X_i[k]**(i))\n\t\t\t\tk += 1\n\t\t\tb[i] = b_i\n\t\t\ti += 1\n\t\tx = np.transpose(np.linalg.solve(A, b))\n\t\tk, X, terms = 0, x[0], []\n\t\tfor x in X:\n\t\t\tterms.append(x*(variable**k))\n\t\t\tk += 1\n\t\tpolynomial = sp.simplify(sum(terms))\n\t\tprint(\"Congratulations! \", made_poly, str(polynomial))\n\t\tP = sp.lambdify(variable, polynomial)\n\t\ti, E = 0, 0\n\t\tfor x_i in X_i:\n\t\t\tE += (Y_i[i] - P(x_i))**2\n\t\t\ti += 1\n\t\treturn P, E\n\n\tdef power(X, Y):\n\t\t\"\"\"Given a domain and range, yield the coefficients for an equation of the form `y = A*(x^B)`.\n\n\t\tParameters\n\t\t----------\n\t\tX : array\n\t\t\tInput domain.\n\n\t\tY : array or expression\n\t\t\tDesired/Found range of interest.\n\n\t\tReturns\n\t\t-------\n\t\tA : float\n\t\t\tLeading coefficient.\n\n\t\tB : float\n\t\t\tExponent.\n\n\t\tRaises\n\t\t------\n\t\tbad_X : string\n\t\t\tIf {`X`} is neither n x 1 nor 1 x n array.\n\n\t\tbad_Y : string\n\t\t\tIf {`Y`} is neither n x 1 nor 1 x n array.\n\n\t\tbad_data : string\n\t\t\tIf {`X`} and {`Y`} are of unequal length.\n\n\t\tWarns\n\t\t-----\n\t\tmade_poly : string\n\t\t\tDisplays the string form of the equation.\n\t\t\"\"\"\n\t\tsym_X, sym_Y = \"X\", \"Y\"\n\t\tbad_X = \"Input domain, \" + sym_X + \" was neither an n x 1 nor a 1 x n array.\"\n\t\tbad_Y = \"Input range, \" + sym_Y + \" was neither an n x 1 nor a 1 x n array.\"\n\t\tbad_data = \"Arrays \" + sym_X + \" and \" + sym_Y + \" must be of equal length.\"\n\t\tbad_n = \"Degree of polynomial must be integer and non-zero.\"\n\t\tmade_poly = \"I have found your requested polynomial! P = \"\n\t\tX, Y = np.array(X), np.array(Y)\n\t\tif np.sum(X.shape) > np.sum(X.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\tif isinstance(Y, (FunctionType, sp.Expr)):\n\t\t\tY = make_array(X, Y)\n\t\tif np.sum(Y.shape) > np.sum(Y.shape[0]): raise ValueError(\"ERROR! \" + bad_Y)\n\t\tif len(X) != len(Y): raise ValueError(\"ERROR! \" + bad_data)\n\t\tn = len(X)\n\t\tq1, q2, q3, q4 = [], [], [], []\n\t\tfor i in range(n):\n\t\t\txi, yi = X[i], Y[i]\n\t\t\tq1.append(np.log(xi)*np.log(yi))\n\t\t\tq2.append(np.log(xi))\n\t\t\tq3.append(np.log(yi))\n\t\t\tq4.append(np.log(xi)**2)\n\t\tnum = n*np.sum(q1) - np.sum(q2)*np.sum(q3)\n\t\tden = n*np.sum(q4) - (np.sum(q2))**2\n\t\tb = num/den\n\t\ta = math.exp((np.sum(q3) - b*np.sum(q2))/n)\n\t\treturn a, b\n\ndef linear_interpolation(x0, y0, x1, y1, x):\n\treturn y0 + (x - x0)*(y1 - y0)/(x1 - x0)\n\ndef newton_difference(X, FX, x0, variable=sp.Symbol(\"x\"), direction=0):\n\t\"\"\"Given a domain and range, construct some polynomial by Newton's Divided Difference.\n\n\tParameters\n\t----------\n\tX : array\n\t\tInput domain.\n\n\tFX : array or expression\n\t\tDesired/Found range of interest.\n\n\tx0 : float\n\t\tPoint about which polynomial is evaluated.\n\n\tdirection : string\n\t\t`'forward'` or `'backward'` construction. Will be chosen automatically if not specified.\n\n\tReturns\n\t-------\n\tp : expression\n\t\tLambdified constructed polynomial.\n\n\tp(x0) : float\n\t\tEvaluation of `p` at `x`.\n\n\tRaises\n\t------\n\tbad_X : string\n\t\tIf {`X_i`} is neither n x 1 nor 1 x n array.\n\n\tbad_FX : string\n\t\tIf {`FX`} is neither n x 1 nor 1 x n array.\n\n\tbad_data : string\n\t\tIf {`X`} and {`FX`} are of unequal length.\n\n\tbad_direction : string\n\t\tIf `direction` is neither `'forward'` nor `'backward'`.\n\n\tWarns\n\t-----\n\tmade_poly : string\n\t\tDisplays the string form of the equation.\n\n\tSee Also\n\t--------\n\tmake_array() : Prints string that expression was used to make array.\n\n\tNotes\n\t-----\n\tDirection will be chosen if not specified.\n\n\tPolynomials best made with even spacing in `X`; although, this is not completely necessary.\n\t\"\"\"\n\tdef fterm(i, j):\n\t\tfij = (fxn[i][j] - fxn[i-1][j])/(fxn[i][0] - fxn[i-j][0])\n\t\treturn fij\n\tsym_X, sym_FX = \"X\", \"FX\"\n\tbad_X = \"Input domain, \" + sym_X + \" was neither an n x 1 nor a 1 x n array.\"\n\tbad_FX = \"Input range, \" + sym_FX + \" was neither an n x 1 nor a 1 x n array.\"\n\tbad_data = \"Arrays \" + sym_X + \" and \" + sym_FX + \" must be of equal length.\"\n\tbad_direction = \"Supplied direction was not understood. Please specify 'forward' or 'backward', or let me choose.\"\n\tmade_poly = \"I have found your requested polynomial! P = \"\n\tX, x0 = np.array(X), float(x0)\n\tif not isinstance(FX,(FunctionType, sp.Expr)):\n\t\tFX = np.array(FX)\n\t\tif np.sum(X.shape) > np.sum(X.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\tif np.sum(FX.shape) > np.sum(FX.shape[0]): raise ValueError(\"ERROR! \" + bad_FX)\n\t\tif len(X) != len(FX): raise ValueError(\"ERROR! \" + bad_data)\n\tif isinstance(FX,(FunctionType, sp.Expr)): FX = make_array(X, FX)\n\tif direction == 0:\n\t\tif x0 <= np.median(X): direction = \"forward\"\n\t\telse: direction = \"backward\"\n\telif direction != \"forward\" and direction != \"backward\": raise ValueError(bad_direction)\n\tm = len(X)\n\tn = m + 1\n\tfxn, coeff, term, poly = np.zeros((m,n)), [], [], []\n\tm, n = m - 1, n - 1\t # change m and n from length to index\n\tj, fxn[:,0], fxn[:,1] = 1, X, FX\n\twhile j < m:\n\t\ti = 1\n\t\twhile i < m:\n\t\t\tfk = fterm(i, j)\n\t\t\tfxn[i][j+1] = fk\n\t\t\tif direction == \"forward\" and i == j:\n\t\t\t\tcoeff.append(fk)\n\t\t\tif direction == \"backward\" and i == m - 1:\n\t\t\t\tcoeff.append(fk)\n\t\t\ti += 1\n\t\tj += 1\n\tfor c in coeff:\n\t\tk = coeff.index(c)\n\t\tterm.append(variable - X[k])\n\t\tpoly.append(c*np.prod(term))\n\tif direction == \"forward\": polynomial = sp.simplify(sum(poly) + FX[0])\n\tif direction == \"backward\": polynomial = sp.simplify(sum(poly) + FX[m])\n\tprint(\"Congratulations! \", made_poly, str(polynomial))\n\tp = sp.lambdify(variable, polynomial)\n\treturn p, p(x0)\n# --------------------\n\n# --------------------\n# numerical differentiation and integration\nclass simpson:\n\n\tdef open(f, X, h=0, a=0, b=0, variable=sp.Symbol(\"x\")):\n\t\t\"\"\"Find the integral of a function within some interval, using Simpson's Rule.\n\n\t\tParameters\n\t\t----------\n\t\tf : expression\n\t\t\tPolynomial equation that defines graphical curve.\n\n\t\tX : list\n\t\t\tDomain over which `f` is evaluated.\n\n\t\th : float\n\t\t\tStep-size through interval.\n\n\t\ta : float\n\t\t\tLeft-hand bound of interval.\n\n\t\tb : float\n\t\t\tRight-hand bound of interval.\n\n\t\tReturns\n\t\t-------\n\t\tXJ : list\n\t\t\tValues of domain at which `f` was analyzed.\n\n\t\tYJ : list\n\t\t\tEvaluations of `f` from domain.\n\n\t\tF : float\n\t\t\tTotal area under curve, `f`.\n\n\t\tRaises\n\t\t------\n\t\tbad_X : string\n\t\t\tIf {`X_i`} is neither n x 1 nor 1 x n array.\n\n\t\tbad_f : string\n\t\t\tIf {`f`} is not an expression.\n\n\t\tWarns\n\t\t-----\n\t\t__func_func : string\n\t\t\tEvaluate input expression for Newton difference approximation.\n\n\t\tNotes\n\t\t-----\n\t\t`X = 0` if not a list nor n x 1 or 1 x n array.\n\n\t\tUnless specified and if `X` is defined, `a` and `b` will be the minimum and maximum, respectively, of `X`.\n\n\t\tTheorem:\n\t\tLet f be in C4[a,b], n be even, h = (b-a)/n, and xj = a + jh for j = 0, 1, ..., n. There exists a mu in (a,b) for which the quadrature for n sub-intervals can be written with its error term as:\n\t\tint_(a)^(b)f(x)dx = h[f(a) + 2*[sum_(j=1)^(n/2 - 1){f(x_(2j))}] + 4*[sum_(j=1)^(n/2){f(x_(2j-1))}] + f(b)]/3 - (b-a)*(h^4)f''''(mu)/180.\n\n\t\tWhere: (b-a)*(h^4)f''''(mu)/180 -> O(h^4)\n\t\t\"\"\"\n\t\tX = np.array(X)\n\t\tsym_X, sym_function = \"X\", \"f\"\n\t\tbad_X = \"Input domain, \" + sym_X + \" was neither an n x 1 nor a 1 x n array.\"\n\t\tbad_f = \"Input range, \" + sym_function + \" must be expression, not list or tuple.\"\n\t\tif np.sum(X.shape) > np.sum(X.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\tif not isinstance(f,(FunctionType, sp.Expr)):\n\t\t\tif np.sum(f.shape) > np.sum(f.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\t\telse: raise ValueError(\"ERROR! \" + bad_f)\n\t\tif isinstance(f,(FunctionType, sp.Expr)):\n\t\t\tsym_function = sp.N(sp.sympify(f(variable)))\n\t\t\tf = sp.lambdify(variable, sym_function)\n\t\t\tprint(f\"Information: Input expression, {sym_function} used.\")\n\t\tif h == 0: h = X[1]-X[0]\n\t\tif a == 0: a = min(X)\n\t\tif b == 0: b = max(X)\n\t\th, a, b = float(h), float(a), float(b)\n\t\tn = math.ceil((b-a)/h)\n\t\tXJ1, XJ2, XJ, = [], [], []\n\t\tYJ1, YJ2, YJ, = [], [], []\n\t\tXJ.append(a); YJ.append(f(a))\n\t\tj, z1 = 1, 0\n\t\twhile j <= (n/2)-1:\n\t\t\txj = a + 2*j*h\n\t\t\tyj = f(xj)\n\t\t\tXJ1.append(xj); YJ1.append(yj)\n\t\t\tz1 += yj\n\t\t\tj += 1\n\t\tk, z2 = 1, 0\n\t\twhile k <= n/2:\n\t\t\txj = a + (2*k - 1)*h\n\t\t\tyj = f(xj)\n\t\t\tXJ2.append(xj); YJ2.append(yj)\n\t\t\tz2 += yj\n\t\t\tk += 1\n\t\tl = 0\n\t\twhile l < np.array(XJ1).shape[0]:\n\t\t\tXJ.append(XJ2[l]); YJ.append(YJ2[l])\n\t\t\tXJ.append(XJ1[l]); YJ.append(YJ1[l])\n\t\t\tl += 1\n\t\tXJ.append(XJ2[l]); YJ.append(YJ2[l])\n\t\tXJ.append(b); YJ.append(f(b))\n\t\tF = h/3*(f(a) + 2*z1 + 4*z2 + f(b))\n\t\treturn XJ, YJ, F\n\n\tdef closed(f, X, h=0, a=0, b=0, variable=sp.Symbol(\"x\")):\n\t\t\"\"\"Find the integral of a function within some interval, using Simpson's Rule.\n\n\t\tParameters\n\t\t----------\n\t\tf : expression\n\t\t\tPolynomial equation that defines graphical curve.\n\n\t\tX : list\n\t\t\tDomain over which `f` is evaluated.\n\n\t\th : float\n\t\t\tStep-size through interval.\n\n\t\ta : float\n\t\t\tLeft-hand bound of interval.\n\n\t\tb : float\n\t\t\tRight-hand bound of interval.\n\n\t\tReturns\n\t\t-------\n\t\tXJ : list\n\t\t\tValues of domain at which `f` was analyzed.\n\n\t\tYJ : list\n\t\t\tEvaluations of `f` from domain.\n\n\t\tF : float\n\t\t\tTotal area under curve, `f`.\n\n\t\tRaises\n\t\t------\n\t\tbad_X : string\n\t\t\tIf {`X_i`} is neither n x 1 nor 1 x n array.\n\n\t\tbad_f : string\n\t\t\tIf {`f`} is not an expression.\n\n\t\tWarns\n\t\t-----\n\t\t__func_func : string\n\t\t\tEvaluate input expression for Newton difference approximation.\n\n\t\tNotes\n\t\t-----\n\t\t`X = 0` if not a list nor n x 1 or 1 x n array.\n\n\t\tUnless specified and if `X` is defined, `a` and `b` will be the minimum and maximum, respectively, of `X`.\n\n\t\tTheorem:\n\t\tLet f be in C4[a,b], n be even, h = (b-a)/n, and xj = a + jh for j = 0, 1, ..., n. There exists a mu in (a,b) for which the quadrature for n sub-intervals can be written with its error term as:\n\t\tint_(a)^(b)f(x)dx = h[f(a) + 2*[sum_(j=1)^(n/2 - 1){f(x_(2j))}] + 4*[sum_(j=1)^(n/2){f(x_(2j-1))}] + f(b)]/3 - (b-a)*(h^4)f''''(mu)/180.\n\n\t\tWhere: (b-a)*(h^4)f''''(mu)/180 -> O(h^4)\n\t\t\"\"\"\n\t\tX = np.array(X)\n\t\tsym_X, sym_function = \"X\", \"f\"\n\t\tbad_X = \"Input domain, \" + sym_X + \" was neither an n x 1 nor a 1 x n array.\"\n\t\tother_bad_X = \"Input domain, \" + sym_X + \" must be only 4 elements!\"\n\t\tbad_f = \"Input range, \" + sym_function + \" must be expression, not list or tuple.\"\n\t\tif np.sum(X.shape) > np.sum(X.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\tif np.sum(X.shape[0]) != 4: raise ValueError(\"ERROR! \" + other_bad_X)\n\t\tif not isinstance(f,(FunctionType, sp.Expr)):\n\t\t\tf = np.array(f)\n\t\t\tif np.sum(f.shape) == np.sum(f.shape[0]) and np.sum(f.shape) == 4: Y = np.array(f)\n\t\t\telif np.sum(f.shape) > np.sum(f.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\t\telse: raise ValueError(\"ERROR! \" + bad_f)\n\t\tif h == 0: h = X[1]-X[0]\n\t\tif a == 0: a = min(X)\n\t\tif b == 0: b = max(X)\n\t\tif isinstance(f,(FunctionType, sp.Expr)): \n\t\t\tsym_function = sp.N(sp.sympify(f(variable)))\n\t\t\tf = sp.lambdify(variable, sym_function)\n\t\t\tprint(f\"Information: Input expression, {sym_function} used.\")\n\t\t\tY = make_array(X, f)\n\t\t\tif a < np.min(X): Y[0] = f(a)\n\t\t\tif b > np.max(X): Y[3] = f(b)\n\t\th, a, b = float(h), float(a), float(b)\n\t\tF = 3*h/8*(Y[0] + 3*(Y[1] + Y[2]) + Y[3])\n\t\treturn X, Y, F\n\nclass trapezoidal:\n\n\tdef open(f, X, h=0, a=0, b=0, variable=sp.Symbol(\"x\")):\n\t\t\"\"\"Find the integral of a function within some interval, using Trapezoidal Rule.\n\n\t\tParameters\n\t\t----------\n\t\tf : expression\n\t\t\tPolynomial equation that defines graphical curve.\n\n\t\tX : list\n\t\t\tDomain over which `f` is evaluated.\n\n\t\th : float\n\t\t\tStep-size through interval.\n\n\t\ta : float\n\t\t\tLeft-hand bound of interval.\n\n\t\tb : float\n\t\t\tRight-hand bound of interval.\n\n\t\tReturns\n\t\t-------\n\t\tXJ : list\n\t\t\tValues of domain at which `f` was analyzed.\n\n\t\tYJ : list\n\t\t\tEvaluations of `f` from domain.\n\n\t\tF : float\n\t\t\tTotal area under curve, `f`.\n\n\t\tRaises\n\t\t------\n\t\tbad_X : string\n\t\t\tIf {`X_i`} is neither n x 1 nor 1 x n array.\n\n\t\tbad_f : string\n\t\t\tIf {`f`} is not an expression.\n\n\t\tWarns\n\t\t-----\n\t\t__func_func : string\n\t\t\tEvaluate input expression for Newton difference approximation.\n\n\t\tNotes\n\t\t-----\n\t\t`X = 0` if not a list nor n x 1 or 1 x n array.\n\n\t\tUnless specified and if `X` is defined, `a` and `b` will be the minimum and maximum, respectively, of `X`.\n\n\t\tTheorem:\n\t\tLet f be in C2[a,b], h = (b-a)/n, and xj = a + jh for j = 0, 1, ..., n. There exists a mu in (a,b) for which the quadrature for n sub-intervals can be written with its error term as:\n\t\tint_(a)^(b)f(x)dx = h[f(a) + 2*[sum_(j=1)^(n - 1){f(xj)}] + f(b)]/2 - (b-a)*(h^2)f''(mu)/12.\n\n\t\tWhere: (b-a)*(h^2)f''(mu)/12 -> O(h^2)\n\t\t\"\"\"\n\t\tX = np.array(X)\n\t\tsym_X, sym_function = \"X\", \"f\"\n\t\tbad_X = \"Input domain, \" + sym_X + \" was neither an n x 1 nor a 1 x n array.\"\n\t\tbad_f = \"Input range, \" + sym_function + \" must be expression, not list or tuple.\"\n\t\tif np.sum(X.shape) > np.sum(X.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\tif not isinstance(f,(FunctionType, sp.Expr)):\n\t\t\tif np.sum(X.shape) > np.sum(X.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\t\telse: raise ValueError(\"ERROR! \" + bad_f)\n\t\tif isinstance(f,(FunctionType, sp.Expr)):\n\t\t\tsym_function = sp.N(sp.sympify(f(variable)))\n\t\t\tf = sp.lambdify(variable, sym_function)\n\t\t\tprint(f\"Information: Input expression, {sym_function} used.\")\n\t\tif h == 0: h = X[1]-X[0]\n\t\tif a == 0: a = min(X)\n\t\tif b == 0: b = max(X)\n\t\th, a, b = float(h), float(a), float(b)\n\t\tXJ, YJ = [], []\n\t\tXJ.append(a); YJ.append(f(a))\n\t\tj, n, z = 1, math.ceil((b-a)/h), 0\n\t\twhile j <= n-1:\n\t\t\tx_j = a + j*h\n\t\t\tXJ.append(x_j)\n\t\t\ty_j = f(x_j)\n\t\t\tYJ.append(y_j)\n\t\t\tz += y_j\n\t\t\tj += 1\n\t\tXJ.append(b); YJ.append(f(b))\n\t\tF = h/2*(f(a) + 2*z + f(b))\n\t\treturn XJ, YJ, F\n\n\tdef closed(f, X, h=0, a=0, b=0, variable=sp.Symbol(\"x\")):\n\t\t\"\"\"Find the integral of a function within some interval, using Trapezoidal Rule.\n\n\t\tParameters\n\t\t----------\n\t\tf : expression\n\t\t\tPolynomial equation that defines graphical curve.\n\n\t\tX : list\n\t\t\tDomain over which `f` is evaluated.\n\n\t\th : float\n\t\t\tStep-size through interval.\n\n\t\ta : float\n\t\t\tLeft-hand bound of interval.\n\n\t\tb : float\n\t\t\tRight-hand bound of interval.\n\n\t\tReturns\n\t\t-------\n\t\tXJ : list\n\t\t\tValues of domain at which `f` was analyzed.\n\n\t\tYJ : list\n\t\t\tEvaluations of `f` from domain.\n\n\t\tF : float\n\t\t\tTotal area under curve, `f`.\n\n\t\tRaises\n\t\t------\n\t\tbad_X : string\n\t\t\tIf {`X_i`} is neither n x 1 nor 1 x n array.\n\n\t\tbad_f : string\n\t\t\tIf {`f`} is not an expression.\n\n\t\tWarns\n\t\t-----\n\t\t__func_func : string\n\t\t\tEvaluate input expression for Newton difference approximation.\n\n\t\tNotes\n\t\t-----\n\t\t`X = 0` if not a list nor n x 1 or 1 x n array.\n\n\t\tUnless specified and if `X` is defined, `a` and `b` will be the minimum and maximum, respectively, of `X`.\n\n\t\tTheorem:\n\t\tLet f be in C2[a,b], h = (b-a)/n, and xj = a + jh for j = 0, 1, ..., n. There exists a mu in (a,b) for which the quadrature for n sub-intervals can be written with its error term as:\n\t\tint_(a)^(b)f(x)dx = h[f(a) + 2*[sum_(j=1)^(n - 1){f(xj)}] + f(b)]/2 - (b-a)*(h^2)f''(mu)/12.\n\n\t\tWhere: (b-a)*(h^2)f''(mu)/12 -> O(h^2)\n\t\t\"\"\"\n\t\tX = np.array(X)\n\t\tsym_X, sym_function = \"X\", \"f\"\n\t\tbad_X = \"Input domain, \" + sym_X + \" was neither an n x 1 nor a 1 x n array.\"\n\t\tother_bad_X = \"Input domain, \" + sym_X + \" must be only 2 elements!\"\n\t\tbad_f = \"Input range, \" + sym_function + \" must be expression, not list or tuple.\"\n\t\tif np.sum(X.shape) > np.sum(X.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\tif np.sum(X.shape[0]) != 2: raise ValueError(\"ERROR! \" + other_bad_X)\n\t\tif not isinstance(f,(FunctionType, sp.Expr)):\n\t\t\tf = np.array(f)\n\t\t\tif np.sum(f.shape) == np.sum(f.shape[0]) and np.sum(f.shape) == 2: Y = np.array(f)\n\t\t\telif np.sum(X.shape) > np.sum(X.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\t\telse: raise ValueError(\"ERROR! \" + bad_f)\n\t\tif h == 0: h = X[1]-X[0]\n\t\tif a == 0: a = min(X)\n\t\tif b == 0: b = max(X)\n\t\tif isinstance(f,(FunctionType, sp.Expr)): \n\t\t\tsym_function = sp.N(sp.sympify(f(variable)))\n\t\t\tf = sp.lambdify(variable, sym_function)\n\t\t\tprint(f\"Information: Input expression, {sym_function} used.\")\n\t\t\tY = make_array(X, f)\n\t\t\tif a < np.min(X): Y[0] = f(a)\n\t\t\tif b > np.max(X): Y[1] = f(b)\n\t\th, a, b = float(h), float(a), float(b)\n\t\tF = h/2*(Y[0] + Y[1])\n\t\treturn X, Y, F\n\ndef endpoint(X, Y, h, point_type, which_end):\n\t\"\"\"Find the derivative at an endpoint of data set.\n\n\tParameters\n\t----------\n\tX : list\n\t\tDomain of collected data.\n\n\tY : array or expression\n\t\tRange of collected data.\n\n\th : float\n\t\tStep-size through interval.\n\n\tpoint_type : string\n\t\tDetermines if 3 or 5 pt. method is used.\n\n\twhich_end : string\n\t\tDictates whether evaluated point is left or right most data point.\n\n\tReturns\n\t-------\n\tdY : float\n\t\tEvaluated derivative at point.\n\n\tRaises\n\t------\n\tbad_X : string\n\t\tIf {`X`} is neither n x 1 nor 1 x n array.\n\n\tbad_Y : string\n\t\tIf {`Y`} is not an expression.\n\n\tbad_data : string\n\t\tIf `X` and `Y` are of unequal length.\n\n\tSee Also\n\t--------\n\tmake_array() : Prints string that expression was used to make array.\n\n\tNotes\n\t-----\n\t5 point is more accurate than 3 point; however, round-off error increases.\n\t\"\"\"\n\tsym_X, sym_Y = \"X\", \"Y\"\n\tbad_X = \"Input domain, \" + sym_X + \" was neither an n x 1 nor a 1 x n array.\"\n\tbad_Y = \"Input range, \" + sym_Y + \" was neither an n x 1 nor a 1 x n array.\"\n\tbad_data = \"Arrays \" + sym_X + \" and \" + sym_Y + \" must be of equal length.\"\n\tif not isinstance(Y,(FunctionType, sp.Expr)):\n\t\tif np.sum(X.shape) > np.sum(X.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\tif np.sum(Y.shape) > np.sum(Y.shape[0]): raise ValueError(\"ERROR! \" + bad_Y)\n\t\tif len(X) != len(Y): raise ValueError(\"ERROR! \" + bad_data)\n\tif isinstance(Y,(FunctionType, sp.Expr)): Y = make_array(X, Y)\n\th, dY = float(h), 0\n\tif which_end == \"left\":\n\t\ti = 0\n\t\tif point_type == \"three\":\n\t\t\tdY = (-3*Y[i] + 4*Y[i+1] - Y[i+2])/(2*h)\n\t\tif point_type == \"five\":\n\t\t\tdY = (-25*Y[i] + 48*Y[i+1] \\\n\t\t\t\t- 36*Y[i+2] + 16*Y[i+3] \\\n\t\t\t\t\t- 3*Y[i+4])/(12*h)\n\tif which_end == \"right\":\n\t\ti = -1\n\t\tif point_type == \"three\":\n\t\t\tdY = (-3*Y[i] + 4*Y[i-1] - Y[i-2])/(2*h)\n\t\tif point_type == \"five\":\n\t\t\tdY = (-25*Y[i] + 48*Y[i-1] \\\n\t\t\t\t- 36*Y[i-2] + 16*Y[i-3] \\\n\t\t\t\t\t- 3*Y[i-4])/(12*h)\n\treturn dY\n\ndef gaussian_legendre(function, a, b):\n\treturn sc.integrate.quad(function, a, b)\n\ndef integrate(function, a, b):\n\treturn sc.integrate.quad(function, a, b)\n\ndef midpoint(X, Y, h, point_type, i):\n\t\"\"\"Find derivative information at some point within data set.\n\n\tParameters\n\t----------\n\tX : list\n\t\tDomain of collected data.\n\n\tY : array or expression\n\t\tRange of collected data.\n\n\th : float\n\t\tStep-size through interval.\n\n\tpoint_type : string\n\t\tDetermines if 3 or 5 pt. method is used.\n\n\ti : int\n\t\tIndex at which point is to be evaluated.\n\n\tReturns\n\t-------\n\tdY : float\n\t\tEvaluated derivative at point.\n\n\tRaises\n\t------\n\tbad_X : string\n\t\tIf {`X`} is neither n x 1 nor 1 x n array.\n\n\tbad_Y : string\n\t\tIf {`Y`} is not an expression.\n\n\tbad_data : string\n\t\tIf `X` and `Y` are of unequal length.\n\n\tbad_i : string\n\t\t`i` must be an integer and non-zero for indexing.\n\n\tbad_type : string\n\t\tIf `point_type` was not an acceptable option.\n\n\tSee Also\n\t--------\n\tmake_array() : Prints string that expression was used to make array.\n\n\tNotes\n\t-----\n\t5 point is more accurate than 3 point; however, round-off error increases.\n\t\"\"\"\n\tsym_X, sym_Y = \"X\", \"Y\"\n\tbad_X = \"Input domain, \" + sym_X + \" was neither an n x 1 nor a 1 x n array.\"\n\tbad_Y = \"Input range, \" + sym_Y + \" was neither an n x 1 nor a 1 x n array.\"\n\tbad_data = \"Arrays \" + sym_X + \" and \" + sym_Y + \" must be of equal length.\"\n\tbad_i = \"Index must be an integer.\"\n\tbad_type = \"I am sorry. The selected type was not understood. Please select: 'three', 'five', or '2nd_derivative'.\"\n\tif not isinstance(Y,(FunctionType, sp.Expr)):\n\t\tif np.sum(X.shape) > np.sum(X.shape[0]): raise ValueError(\"ERROR! \" + bad_X)\n\t\tif np.sum(Y.shape) > np.sum(Y.shape[0]): raise ValueError(\"ERROR! \" + bad_Y)\n\t\tif len(X) != len(Y): raise ValueError(\"ERROR! \" + bad_data)\n\tif isinstance(Y,(FunctionType, sp.Expr)): Y = make_array(X, Y)\n\tif not isinstance(i,int): raise ValueError(\"ERROR! \" + bad_i)\n\th, dY = float(h), 0\n\tif point_type == \"three\":\n\t\tdY = (Y[i+1] - Y[i-1])/(2*h)\n\tif point_type == \"five\":\n\t\tdY = (Y[i-2] - 8*Y[i-1] \\\n\t\t\t+ 8*Y[i+1] - Y[i+2])/(12*h)\n\tif point_type == \"2nd_derivative\":\n\t\tdY = (Y[i-1] - 2*Y[i] + Y[i+1])/(h**2)\n\telse: raise ValueError(\"ERROR! \" + bad_type)\n\treturn dY\n\ndef richard_extrapolation(function, x0, h, order, direction=0, variable=sp.Symbol(\"x\")):\n\t\"\"\"Results in higher-accuracy of derivative at point in function with lower-order formulas to minimize round-off error and increase O(h) of truncation error.\n\n\tParameters\n\t----------\n\tfunction : expression\n\t\tPolynomial over which derivative must be calculated.\n\n\tx0 : float\n\t\tPoint about which extrapolation centers\n\n\th : float\n\t\tStep-size through interval.\n\n\torder : int\n\t\tOrder for rate of convergence.\n\n\tdirection : string\n\t\t`'forward'` or `'backward'` construction.\n\n\tReturns\n\t-------\n\tp : expression\n\t\tLambdified constructed polynomial.\n\n\tp(x0) : float\n\t\tEvaluation of `p` at `x`.\n\n\tRaises\n\t------\n\tbad_function : string\n\t\tIf `function` is not an expression.\n\n\tbad_order : string\n\t\t`order` must be an integer and non-zero.\n\n\tbad_direction : string\n\t\tIf `direction` is neither `'forward'` nor `'backward'`.\n\n\tWarns\n\t-----\n\t__func_func : string\n\t\tEvaluate input expression for Newton difference approximation.\n\n\tSee Also\n\t--------\n\tnewton_difference() : Newton Difference method to build extrapolation for function's derivative and order of error.\n\t\"\"\"\n\tsym_function = \"function\"\n\tbad_function = \"Function, \" + sym_function + \" must be expression.\"\n\tbad_order = \"Expected integer.\"\n\tbad_direction = \"Supplied direction was not understood. Please specify 'forward' or 'backward'.\"\n\tmade_poly = \"I have found your requested polynomial! P = \"\n\tif not isinstance(function,(FunctionType, sp.Expr)): \n\t\traise TypeError(\"ERROR! \" + bad_function)\n\tif isinstance(function,(FunctionType, sp.Expr)):\n\t\tsym_function = sp.N(sp.sympify(function(variable)))\n\t\tfunction = sp.lambdify(variable, sym_function)\n\t\tprint(f\"Information: Input expression, {sym_function} used.\")\n\tif not isinstance(order,int): raise TypeError(\"ERROR! \" + bad_order)\n\tif direction != 0 and direction != \"forward\" and direction != \"backward\": raise ValueError(\"ERROR! \" + bad_direction)\n\tdef f(h):\n\t\tx = x0 + h\n\t\treturn x, function(x)\n\tx0, h = float(x0), float(h)\n\ti, X, FX = 0, [], []\n\twhile i < order:\n\t\tdx = h / (2**order) * (2**i)\n\t\tx_i, fx_i = f(dx)\n\t\tX.append(x_i); FX.append(fx_i)\n\t\ti += 1\n\tm = len(X)\n\tn = m + 1\n\treturn newton_difference(X, FX, x0, direction)\n# --------------------\n\n# --------------------\n# differential equations\nclass __ode(object):\n\t\"\"\"Assign common attributes to objects.\n\t\"\"\"\n\tdef __init__(self, function, a, b, alpha, variables=(sp.Symbol(\"t\"), sp.Symbol(\"y\")), steps=100):\n\t\t\"\"\"\n\t\tParameters\n\t\t----------\n\t\tfunction : expression\n\t\t\tTime derivative of function to approximate.\n\n\t\ta : float\n\t\t\tInitial time.\n\n\t\tb : float\n\t\t\tFinal time.\n\n\t\talpha : float\n\t\t\tInitial value at a.\n\n\t\tvariables : tuple, optional\n\t\t\tCollection of symbolic or string variables to respect in function.\n\n\t\tsteps : int or float, optional\n\t\t\tMaximum number of time steps to discretize domain.\n\n\t\tYields\n\t\t------\n\t\tself.function : expression\n\t\t\tTime derivative of function to approximate.\n\n\t\tself.a : float\n\t\t\tInitial time.\n\n\t\tself.b : float\n\t\t\tFinal time.\n\n\t\tself.alpha : float\n\t\t\tInitial value at a.\n\n\t\tself.variables : tuple, optional\n\t\t\tCollection of symbolic or string variables to respect in function.\n\n\t\tself.steps : int or float, optional\n\t\t\tMaximum number of time steps to discretize domain.\n\n\t\tRaises\n\t\t------\n\t\tValueError\n\t\t\tIf time steps constraint is not an integer.\n\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\n\t\tNotes\n\t\t-----\n\t\tMake sure the independent variable is the first element of `variables`!\n\t\t\"\"\"\n\t\tif steps <= 0 or not isinstance(steps, (int, float)): raise ValueError(f\"ERROR! Number of time steps, N must be an integer greater than zero. {steps} was given and not understood.\")\n\t\tif np.sum(np.array(function).shape) > 0:\n\t\t\tF = []\n\t\t\tfor f in function:\n\t\t\t\tif isinstance(f, (FunctionType, sp.Expr)):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(variables[0])))\n\t\t\t\t\t\tf = sp.lambdify(variables[0], sym_function)\n\t\t\t\t\t\tprint(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\t\texcept:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(*variables)))\n\t\t\t\t\t\tf = sp.lambdify(variables, sym_function)\n\t\t\t\t\t\tprint(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\telif isinstance(f, (str)):\n\t\t\t\t\tg = lambda x: eval(f)\n\t\t\t\t\tf = sp.lambdify(*variables, g(*variables))\n\t\t\t\t\tprint(\"String expression converted to lambda function.\")\n\t\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\t\t\tF.append(f)\n\t\t\tfunction = F\n\t\telse:\n\t\t\tif isinstance(function, (FunctionType, sp.Expr)):\n\t\t\t\tsym_function = sp.N(sp.sympify(function(*variables)))\n\t\t\t\tfunction = sp.lambdify(variables, sym_function)\n\t\t\t\tprint(f\"Information: Input expression, {sym_function} used.\")\n\t\t\telif isinstance(function, (str)):\n\t\t\t\tg = lambda x: eval(function)\n\t\t\t\tfunction = sp.lambdify(*variables, g(*variables))\n\t\t\t\tprint(\"String expression converted to lambda function.\")\n\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\tself.function = function\n\t\tself.a, self.b = a, b\n\t\tself.alpha = alpha\n\t\tself.variables = tuple(variables)\n\t\tself.steps = int(steps + 1)\n\nclass ivp(__ode):\n\t\"\"\"Class containing Initial Value Problem methods.\n\t\"\"\"\n\tdef __init__(self, function, a, b, alpha, variables=(sp.Symbol(\"t\"), sp.Symbol(\"y\")), steps=100):\n\t\t\"\"\"\n\t\tParameters\n\t\t----------\n\t\tfunction : expression\n\t\t\tTime derivative of function to approximate.\n\n\t\ta : float\n\t\t\tInitial time.\n\n\t\tb : float\n\t\t\tFinal time.\n\n\t\talpha : float\n\t\t\tInitial value at a.\n\n\t\tvariables : tuple, optional\n\t\t\tCollection of symbolic or string variables to respect in function.\n\n\t\tsteps : int or float, optional\n\t\t\tMaximum number of time steps to discretize domain.\n\n\t\tAttributes\n\t\t----------\n\t\tforward_euler()\n\n\t\timproved_euler()\n\n\t\tbackward_euler()\n\n\t\tcrank_nicholson()\n\n\t\trunge_kutta()\n\n\t\tYields\n\t\t------\n\t\tself.function : expression\n\t\t\tTime derivative of function to approximate.\n\n\t\tself.a : float\n\t\t\tInitial time.\n\n\t\tself.b : float\n\t\t\tFinal time.\n\n\t\tself.alpha : float\n\t\t\tInitial value at a.\n\n\t\tself.variables : tuple, optional\n\t\t\tCollection of symbolic or string variables to respect in function.\n\n\t\tself.steps : int or float, optional\n\t\t\tMaximum number of time steps to discretize domain.\n\n\t\tRaises\n\t\t------\n\t\tValueError\n\t\t\tIf time steps constraint is not an integer.\n\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\n\t\tNotes\n\t\t-----\n\t\tMake sure the independent variable is the first element of `variables`!\n\t\t\"\"\"\n\t\tsuper().__init__(function, a, b, alpha, variables=variables, steps=steps)\n\n\tdef forward_euler(self):\n\t\t\"\"\"March forward through time to approximate Initial Value Problem differential equation between endpoints a and b.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.Dataframe() : dataframe\n\t\t\tDataframe of method iterations and time domains, range of approximations for input function, and iterative increments.\n\n\t\tYields\n\t\t------\n\t\tself.step_size : float\n\t\t\tDomain step size.\n\n\t\tself.iterations : tuple\n\t\t\tCollection of steps through method.\n\n\t\tself.domain : tuple\n\t\t\tDiscretized domain between endpoints a and b for so many steps.\n\n\t\tself.range : tuple\n\t\t\tRange mapped from method through discretized domain between endpoints a and b for so many steps.\n\n\t\tself.increments : tuple\n\t\t\tCollection of increments between steps.\n\n\t\tRaises\n\t\t------\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\t\t\"\"\"\n\t\tif np.sum(np.array(self.function).shape) > 0:\n\t\t\tF = []\n\t\t\tfor f in self.function:\n\t\t\t\tif isinstance(f, (FunctionType, sp.Expr)):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(self.variables[0])))\n\t\t\t\t\t\tf = sp.lambdify(self.variables[0], sym_function)\n\t\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\t\texcept:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(*self.variables)))\n\t\t\t\t\t\tf = sp.lambdify(self.variables, sym_function)\n\t\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\telif isinstance(f, (str)):\n\t\t\t\t\tg = lambda x: eval(f)\n\t\t\t\t\tf = sp.lambdify(*self.variables, g(*self.variables))\n\t\t\t\t\t# print(\"String expression converted to lambda function.\")\n\t\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\t\t\tF.append(f)\n\t\t\tfunction = F\n\t\telse:\n\t\t\tif isinstance(self.function, (FunctionType, sp.Expr)):\n\t\t\t\ttry:\n\t\t\t\t\tsym_function = sp.N(sp.sympify(self.function(self.variables[0])))\n\t\t\t\t\tfunction = sp.lambdify(self.variables[0], sym_function)\n\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\texcept:\n\t\t\t\t\tsym_function = sp.N(sp.sympify(self.function(*self.variables)))\n\t\t\t\t\tfunction = sp.lambdify(self.variables, sym_function)\n\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\telif isinstance(self.function, (str)):\n\t\t\t\tg = lambda x: eval(self.function)\n\t\t\t\tfunction = sp.lambdify(*self.variables, g(*self.variables))\n\t\t\t\t# print(\"String expression converted to lambda function.\")\n\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\ta, b, alpha = self.a, self.b, self.alpha\n\t\tvariables, N = self.variables, self.steps\n\t\th, t, w0 = float((b - a)/N), a, alpha\n\t\tself.step_size = h\n\t\tY, increments = [w0], [0]\n\t\tfor i in range(1, N):\n\t\t\tw = w0 + h*function(t, w0)\n\t\t\tY.append(w)\n\t\t\tincrements.append(w - w0)\n\t\t\tt, w0 = a + i*h, w\n\t\tself.iterations = tuple(range(N))\n\t\tself.domain = tuple(np.arange(a, t+h, h))\n\t\tself.range = tuple(Y)\n\t\tself.increments = tuple(increments)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Domain\": self.domain, \"Range\": self.range, \"Increments\": self.increments})\n\n\tdef improved_euler(self):\n\t\t\"\"\"Approximate solution of Initial Value Problem differential equation given initial time, initial value, and final time.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.Dataframe() : dataframe\n\t\t\tDataframe of method iterations and time domains, range of approximations for input function, and iterative increments.\n\n\t\tYields\n\t\t------\n\t\tself.step_size : float\n\t\t\tDomain step size.\n\n\t\tself.iterations : tuple\n\t\t\tCollection of steps through method.\n\n\t\tself.domain : tuple\n\t\t\tDiscretized domain between endpoints a and b for so many steps.\n\n\t\tself.range : tuple\n\t\t\tRange mapped from method through discretized domain between endpoints a and b for so many steps.\n\n\t\tself.increments : tuple\n\t\t\tCollection of increments between steps.\n\n\t\tRaises\n\t\t------\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\n\t\tSee Also\n\t\t--------\n\t\trunge_kutta()\n\n\t\tNotes\n\t\t-----\n\t\tIs 2nd-Order Runge-Kutta method where endpoint a = b = 0.5 and lambda = 1.\n\t\t\"\"\"\n\t\tif np.sum(np.array(self.function).shape) > 0:\n\t\t\tF = []\n\t\t\tfor f in self.function:\n\t\t\t\tif isinstance(f, (FunctionType, sp.Expr)):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(self.variables[0])))\n\t\t\t\t\t\tf = sp.lambdify(self.variables[0], sym_function)\n\t\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\t\texcept:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(*self.variables)))\n\t\t\t\t\t\tf = sp.lambdify(self.variables, sym_function)\n\t\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\telif isinstance(f, (str)):\n\t\t\t\t\tg = lambda x: eval(f)\n\t\t\t\t\tf = sp.lambdify(*self.variables, g(*self.variables))\n\t\t\t\t\t# print(\"String expression converted to lambda function.\")\n\t\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\t\t\tF.append(f)\n\t\t\tfunction = F\n\t\telse:\n\t\t\tif isinstance(self.function, (FunctionType, sp.Expr)):\n\t\t\t\ttry:\n\t\t\t\t\tsym_function = sp.N(sp.sympify(self.function(self.variables[0])))\n\t\t\t\t\tfunction = sp.lambdify(self.variables[0], sym_function)\n\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\texcept:\n\t\t\t\t\tsym_function = sp.N(sp.sympify(self.function(*self.variables)))\n\t\t\t\t\tfunction = sp.lambdify(self.variables, sym_function)\n\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\telif isinstance(self.function, (str)):\n\t\t\t\tg = lambda x: eval(self.function)\n\t\t\t\tfunction = sp.lambdify(*self.variables, g(*self.variables))\n\t\t\t\t# print(\"String expression converted to lambda function.\")\n\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\ta, b, alpha = self.a, self.b, self.alpha\n\t\tvariables, N = self.variables, self.steps\n\t\th, t, w0 = float((b - a)/N), a, alpha\n\t\tself.step_size = h\n\t\tea, eb, lam = 1/2, 1/2, 1\n\t\tY, increments = [w0], [0]\n\t\tfor i in range(1, N):\n\t\t\tw = w0 + h*(ea*function(t, w0) + eb*function(t + lam*h, w0 + lam*h*function(t, w0)))\n\t\t\tY.append(w)\n\t\t\tincrements.append(np.abs(w - w0))\n\t\t\tt, w0 = a + i*h, w\n\t\tself.iterations = tuple(range(N))\n\t\tself.domain = tuple(np.arange(a, t+h, h))\n\t\tself.range = tuple(Y)\n\t\tself.increments = tuple(increments)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Domain\": self.domain, \"Range\": self.range, \"Increments\": self.increments})\n\n\tdef backward_euler(self):\n\t\t\"\"\"Use information at next time step to approximate Initial Value Problem differential equation between endpoints a and b.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.Dataframe() : dataframe\n\t\t\tDataframe of method iterations and time domains, range of approximations for input function, and iterative increments.\n\n\t\tYields\n\t\t------\n\t\tself.step_size : float\n\t\t\tDomain step size.\n\n\t\tself.iterations : tuple\n\t\t\tCollection of steps through method.\n\n\t\tself.domain : tuple\n\t\t\tDiscretized domain between endpoints a and b for so many steps.\n\n\t\tself.range : tuple\n\t\t\tRange mapped from method through discretized domain between endpoints a and b for so many steps.\n\n\t\tself.increments : tuple\n\t\t\tCollection of increments between steps.\n\n\t\tRaises\n\t\t------\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\n\t\tSee Also\n\t\t--------\n\t\tSingleVariableIteration.newton_raphson()\n\t\t\"\"\"\n\t\tif np.sum(np.array(self.function).shape) > 0:\n\t\t\tF = []\n\t\t\tfor f in self.function:\n\t\t\t\tif isinstance(f, (FunctionType, sp.Expr)):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(self.variables[0])))\n\t\t\t\t\t\tf = sp.lambdify(self.variables[0], sym_function)\n\t\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\t\texcept:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(*self.variables)))\n\t\t\t\t\t\tf = sp.lambdify(self.variables, sym_function)\n\t\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\telif isinstance(f, (str)):\n\t\t\t\t\tg = lambda x: eval(f)\n\t\t\t\t\tf = sp.lambdify(*self.variables, g(*self.variables))\n\t\t\t\t\t# print(\"String expression converted to lambda function.\")\n\t\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\t\t\tF.append(f)\n\t\t\tfunction = F\n\t\telse:\n\t\t\tif isinstance(self.function, (FunctionType, sp.Expr)):\n\t\t\t\ttry:\n\t\t\t\t\tsym_function = sp.N(sp.sympify(self.function(self.variables[0])))\n\t\t\t\t\tfunction = sp.lambdify(self.variables[0], sym_function)\n\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\texcept:\n\t\t\t\t\tsym_function = sp.N(sp.sympify(self.function(*self.variables)))\n\t\t\t\t\tfunction = sp.lambdify(self.variables, sym_function)\n\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\telif isinstance(self.function, (str)):\n\t\t\t\tg = lambda x: eval(self.function)\n\t\t\t\tfunction = sp.lambdify(*self.variables, g(*self.variables))\n\t\t\t\t# print(\"String expression converted to lambda function.\")\n\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\ta, b, alpha = self.a, self.b, self.alpha\n\t\tvariables, N = self.variables, self.steps\n\t\th, t, w0 = float((b - a)/N), a, alpha\n\t\tself.step_size = h\n\t\tY, increments = [w0], [0]\n\t\tfor i in range(1, N):\n\t\t\tt = a + i*h\n\t\t\t# w = w0 + h*function(t + h, w0 + h*function(t, w0))\n\t\t\tw = lambda x: x - (w0 + h*function(t + h, x))\n\t\t\tsys.stdout =  open(os.devnull, \"w\")\n\t\t\tfoo = SingleVariableIteration(w, t, t+h, iter_guess=100)\n\t\t\tw = foo.newton_raphson(w0)[\"Approximations\"].values[-1]\n\t\t\tsys.stdout = sys.__stdout__\n\t\t\tY.append(w)\n\t\t\tincrements.append(np.abs(w - w0))\n\t\t\t# t, w0 = a + i*h, w\n\t\t\tw0 = w\n\t\tself.iterations = tuple(range(N))\n\t\tself.domain = tuple(np.arange(a, t+h, h))\n\t\tself.range = tuple(Y)\n\t\tself.increments = tuple(increments)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Domain\": self.domain, \"Range\": self.range, \"Increments\": self.increments})\n\n\tdef trapezoidal(self, power=-6, M=100):\n\t\t\"\"\"Use information at next time step to approximate Initial Value Problem differential equation between endpoints a and b.\n\n\t\tParameters\n\t\t----------\n\t\tpower : int or float, optional\n\t\t\tSigned power to which function error must be within.\n\n\t\tM : int or float, optional\n\t\t\tMaximum iterations for Newton-Raphson loop.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.Dataframe() : dataframe\n\t\t\tDataframe of method iterations and time domains, range of approximations for input function, and iterative increments.\n\n\t\tYields\n\t\t------\n\t\tself.step_size : float\n\t\t\tDomain step size.\n\n\t\tself.iterations : tuple\n\t\t\tCollection of steps through method.\n\n\t\tself.domain : tuple\n\t\t\tDiscretized domain between endpoints a and b for so many steps.\n\n\t\tself.range : tuple\n\t\t\tRange mapped from method through discretized domain between endpoints a and b for so many steps.\n\n\t\tself.increments : tuple\n\t\t\tCollection of increments between steps.\n\n\t\tRaises\n\t\t------\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\t\t\"\"\"\n\t\tif np.sum(np.array(self.function).shape) > 0:\n\t\t\tF = []\n\t\t\tfor f in self.function:\n\t\t\t\tif isinstance(f, (FunctionType, sp.Expr)):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(self.variables[0])))\n\t\t\t\t\t\tf = sp.lambdify(self.variables[0], sym_function)\n\t\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\t\texcept:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(*self.variables)))\n\t\t\t\t\t\tf = sp.lambdify(self.variables, sym_function)\n\t\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\telif isinstance(f, (str)):\n\t\t\t\t\tg = lambda x: eval(f)\n\t\t\t\t\tf = sp.lambdify(*self.variables, g(*self.variables))\n\t\t\t\t\t# print(\"String expression converted to lambda function.\")\n\t\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\t\t\tF.append(f)\n\t\t\tfunction = F\n\t\telse:\n\t\t\tif isinstance(self.function, (FunctionType, sp.Expr)):\n\t\t\t\ttry:\n\t\t\t\t\tsym_function = sp.N(sp.sympify(self.function(self.variables[0])))\n\t\t\t\t\tfunction = sp.lambdify(self.variables[0], sym_function)\n\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\texcept:\n\t\t\t\t\tsym_function = sp.N(sp.sympify(self.function(*self.variables)))\n\t\t\t\t\tfunction = sp.lambdify(self.variables, sym_function)\n\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\telif isinstance(self.function, (str)):\n\t\t\t\tg = lambda x: eval(self.function)\n\t\t\t\tfunction = sp.lambdify(*self.variables, g(*self.variables))\n\t\t\t\t# print(\"String expression converted to lambda function.\")\n\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\ta, b, alpha = self.a, self.b, self.alpha\n\t\tvariables, N = self.variables, self.steps\n\t\th, t, w0, tol = float((b - a)/N), a, alpha, 10**power\n\t\tself.step_size = h\n\t\tfpy = sp.lambdify(variables, sp.diff(function(*variables), variables[0]))\n\t\tY, increments = [w0], [0]\n\t\tfor i in range(1, N):\n\t\t\tk1 = w0 + h*function(t, w0)/2\n\t\t\tj, wj0, FLAG = 1, k1, False\n\t\t\twhile FLAG == False:\n\t\t\t\twj1 = wj0 - (wj0 - h/2*function(t + h, wj0) - k1)/(\\\n\t\t\t\t\t1 - h/2*fpy(t + h, wj0))\n\t\t\t\tif np.abs(wj1 - wj0) <= tol:\n\t\t\t\t\tw = wj1\n\t\t\t\t\tFLAG = True\n\t\t\t\telse:\n\t\t\t\t\twj0 = wj1\n\t\t\t\t\tj += 1\n\t\t\t\t\tif j > M: FLAG = True\n\t\t\t# f = lambda x: x - h/2*function(t + h, x) - k1\n\t\t\t# foo = SingleVariableIteration(f, a, b, power, variable=variables, iter_guess=M)\n\t\t\t# w = foo.newton_raphson(k1)[\"Approximations\"][-1]\n\t\t\tY.append(w)\n\t\t\tincrements.append(np.abs(w - w0))\n\t\t\tt, w0 = a + i*h, w\n\t\tself.iterations = tuple(range(N))\n\t\tself.domain = tuple(np.arange(a, t+h, h))\n\t\tself.range = tuple(Y)\n\t\tself.increments = tuple(increments)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Domain\": self.domain, \"Range\": self.range, \"Increments\": self.increments})\n\n\tdef runge_kutta(self):\n\t\t\"\"\"Approximate solution of initial value problem.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.Dataframe() : dataframe\n\t\t\tDataframe of method iterations and time domains, range of approximations for input function, and iterative increments.\n\n\t\tYields\n\t\t------\n\t\tself.step_size : float\n\t\t\tDomain step size.\n\n\t\tself.iterations : tuple\n\t\t\tCollection of steps through method.\n\n\t\tself.domain : tuple\n\t\t\tDiscretized domain between endpoints a and b for so many steps.\n\n\t\tself.range : tuple\n\t\t\tRange mapped from method through discretized domain between endpoints a and b for so many steps.\n\n\t\tself.increments : tuple\n\t\t\tCollection of increments between steps.\n\n\t\tRaises\n\t\t------\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\t\t\"\"\"\n\t\tif np.sum(np.array(self.function).shape) > 0:\n\t\t\tF = []\n\t\t\tfor f in self.function:\n\t\t\t\tif isinstance(f, (FunctionType, sp.Expr)):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(self.variables[0])))\n\t\t\t\t\t\tf = sp.lambdify(self.variables[0], sym_function)\n\t\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\t\texcept:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(*self.variables)))\n\t\t\t\t\t\tf = sp.lambdify(self.variables, sym_function)\n\t\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\telif isinstance(f, (str)):\n\t\t\t\t\tg = lambda x: eval(f)\n\t\t\t\t\tf = sp.lambdify(*self.variables, g(*self.variables))\n\t\t\t\t\t# print(\"String expression converted to lambda function.\")\n\t\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\t\t\tF.append(f)\n\t\t\tfunction = F\n\t\telse:\n\t\t\tif isinstance(self.function, (FunctionType, sp.Expr)):\n\t\t\t\ttry:\n\t\t\t\t\tsym_function = sp.N(sp.sympify(self.function(self.variables[0])))\n\t\t\t\t\tfunction = sp.lambdify(self.variables[0], sym_function)\n\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\texcept:\n\t\t\t\t\tsym_function = sp.N(sp.sympify(self.function(*self.variables)))\n\t\t\t\t\tfunction = sp.lambdify(self.variables, sym_function)\n\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\telif isinstance(self.function, (str)):\n\t\t\t\tg = lambda x: eval(self.function)\n\t\t\t\tfunction = sp.lambdify(*self.variables, g(*self.variables))\n\t\t\t\t# print(\"String expression converted to lambda function.\")\n\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\ta, b, alpha = self.a, self.b, self.alpha\n\t\tvariables, N = self.variables, self.steps\n\t\th, t, w0 = float((b - a)/N), a, alpha\n\t\tself.step_size = h\n\t\tY, increments = [w0], [0]\n\t\tfor i in range(1, N):\n\t\t\tk1 = h*function(t, w0)\n\t\t\tk2 = h*function(t + h/2, w0 + k1/2)\n\t\t\tk3 = h*function(t + h/2, w0 + k2/2)\n\t\t\tk4 = h*function(t + h, w0 + k3)\n\t\t\tw = w0 + (k1 + 2*k2 + 2*k3 + k4) / 6\n\t\t\tY.append(w)\n\t\t\tincrements.append(w - w0)\n\t\t\tt, w0 = a + i*h, w\n\t\tself.iterations = tuple(range(N))\n\t\tself.domain = tuple(np.arange(a, t+h, h))\n\t\tself.range = tuple(Y)\n\t\tself.increments = tuple(increments)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Domain\": self.domain, \"Range\": self.range, \"Increments\": self.increments})\n\nclass bvp(__ode):\n\t\"\"\"Class containing Boundary Value Problem methods.\n\t\"\"\"\n\tdef __init__(self, function, a, b, alpha, beta, variables=(sp.Symbol(\"x\"), sp.Symbol(\"y\"), sp.Symbol(\"yp\")), steps=100):\n\t\t\"\"\"\n\t\tParameters\n\t\t----------\n\t\tfunction : expression\n\t\t\tTime derivative of function to approximate.\n\n\t\ta : float\n\t\t\tInitial time.\n\n\t\tb : float\n\t\t\tFinal time.\n\n\t\talpha : float\n\t\t\tInitial value at a.\n\n\t\tbeta : float\n\t\t\tInitial value at b.\n\n\t\tvariables : tuple, optional\n\t\t\tCollection of symbolic or string variables to respect in function.\n\n\t\tsteps : int or float, optional\n\t\t\tMaximum number of time steps to discretize domain.\n\n\t\tAttributes\n\t\t----------\n\t\tlinear_shooting_method()\n\n\t\tfinite_difference_method()\n\n\t\tYields\n\t\t------\n\t\tself.function : expression\n\t\t\tTime derivative of function to approximate.\n\n\t\tself.a : float\n\t\t\tInitial time.\n\n\t\tself.b : float\n\t\t\tFinal time.\n\n\t\tself.alpha : float\n\t\t\tInitial value at a.\n\n\t\tself.beta : float\n\t\t\tInitial value at b.\n\n\t\tself.variables : tuple, optional\n\t\t\tCollection of symbolic or string variables to respect in function.\n\n\t\tself.steps : int or float, optional\n\t\t\tMaximum number of time steps to discretize domain.\n\n\t\tRaises\n\t\t------\n\t\tValueError\n\t\t\tIf time steps constraint is not an integer.\n\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\n\t\tNotes\n\t\t-----\n\t\tMake sure the independent variable is the first element of `variables`!\n\t\t\"\"\"\n\t\tsuper().__init__(function, a, b, alpha, variables=variables, steps=steps)\n\t\tself.beta = beta\n\n\tdef linear_shooting_method(self):\n\t\t\"\"\"Solve a Boundary Value Problem differential equation with 2 Initial Value Problem differential equations.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.Dataframe() : dataframe\n\t\t\tDataframe of method iterations and time domains, range of approximations for input function, and iterative increments.\n\n\t\tYields\n\t\t------\n\t\tself.step_size : float\n\t\t\tDomain step size.\n\n\t\tself.iterations : tuple\n\t\t\tCollection of steps through method.\n\n\t\tself.domain : tuple\n\t\t\tDiscretized domain between endpoints a and b for so many steps.\n\n\t\tself.range : tuple\n\t\t\tRange mapped from method through discretized domain between endpoints a and b for so many steps.\n\n\t\tself.derivatives : tuple\n\t\t\tCollection of derivatives at each step.\n\n\t\tRaises\n\t\t------\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\t\t\"\"\"\n\t\t# Parameters\n\t\t# ----------\n\t\t# f : expression\n\t\t# \tEquation to which derivative will be made.\n\n\t\t# a : int or float\n\t\t# \tInitial time.\n\n\t\t# b : int or float\n\t\t# \tFinal time.\n\t\t\n\t\t# alpha : float\n\t\t# \tInitial value of solution y(t = a).\n\n\t\t# beta : float\n\t\t# \tInitial value of solution y(t = b).\n\n\t\t# h : float\n\t\t# \tDomain step-size.\n\n\t\t# Returns\n\t\t# -------\n\t\t# pandas.Dataframe() : dataframe\n\t\t# \tDataframe of method iterations and time domains & range of approximations for input function and its time derivative.\n\n\t\tif np.sum(np.array(self.function).shape) > 0:\n\t\t\tF = []\n\t\t\tfor f in self.function:\n\t\t\t\tif isinstance(f, (FunctionType, sp.Expr)):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(self.variables[0])))\n\t\t\t\t\t\tf = sp.lambdify(self.variables[0], sym_function)\n\t\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\t\texcept:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(*self.variables)))\n\t\t\t\t\t\tf = sp.lambdify(self.variables, sym_function)\n\t\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\telif isinstance(f, (str)):\n\t\t\t\t\tg = lambda x: eval(f)\n\t\t\t\t\tf = sp.lambdify(*self.variables, g(*self.variables))\n\t\t\t\t\t# print(\"String expression converted to lambda function.\")\n\t\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\t\t\tF.append(f)\n\t\t\tfunction = F\n\t\telse:\n\t\t\tif isinstance(self.function, (FunctionType, sp.Expr)):\n\t\t\t\ttry:\n\t\t\t\t\tsym_function = sp.N(sp.sympify(self.function(self.variables[0])))\n\t\t\t\t\tfunction = sp.lambdify(self.variables[0], sym_function)\n\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\texcept:\n\t\t\t\t\tsym_function = sp.N(sp.sympify(self.function(*self.variables)))\n\t\t\t\t\tfunction = sp.lambdify(self.variables, sym_function)\n\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\telif isinstance(self.function, (str)):\n\t\t\t\tg = lambda x: eval(self.function)\n\t\t\t\tfunction = sp.lambdify(*self.variables, g(*self.variables))\n\t\t\t\t# print(\"String expression converted to lambda function.\")\n\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\ta, b, alpha, beta = self.a, self.b, self.alpha, self.beta\n\t\tvariables, N = self.variables, self.steps\n\t\th = float((b - a)/N)\n\t\tself.step_size = h\n\t\tu1, u2, v1, v2 = [alpha], [0], [0], [1]\n\t\tp, q, r, ypp = function\n\t\tfor i in range(N):\n\t\t\tx = a + i*h\n\t\t\tk11 = h*u2[i]\n\t\t\tk12 = h*(p(x)*u2[i] + q(x)*u1[i] + r(x))\n\t\t\tk21 = h*(u2[i] + k12/2)\n\t\t\tk22 = h*(p(x + h/2)*(u2[i] + k12/2) + q(x + h/2)*(u1[i] + k11/2) + r(x + h/2))\n\t\t\tk31 = h*(u2[i] + k22/2)\n\t\t\tk32 = h*(p(x + h/2)*(u2[i] + k22/2) + q(x + h/2)*(u1[i] + k21/2) + r(x + h/2))\n\t\t\tk41 = h*(u2[i] + k32)\n\t\t\tk42 = h*(p(x + h)*(u2[i] + k32) + q(x + h)*(u1[i] + k31) + r(x + h))\n\t\t\tu1.append(u1[i] + (k11 + 2*k21 + 2*k31 + k41)/6)\n\t\t\tu2.append(u2[i] + (k12 + 2*k22 + 2*k32 + k42)/6)\n\t\t\t###############################\n\t\t\tk11 = h*v2[i]\n\t\t\tk12 = h*(p(x)*v2[i] + q(x)*v1[i])\n\t\t\tk21 = h*(v2[i] + k12/2)\n\t\t\tk22 = h*(p(x + h/2)*(v2[i] + k12/2) + q(x + h/2)*(v1[i] + k11/2))\n\t\t\tk31 = h*(v2[i] + k22/2)\n\t\t\tk32 = h*(p(x + h/2)*(v2[i] + k22/2) + q(x + h/2)*(v1[i] + k21/2))\n\t\t\tk41 = h*(v2[i] + k32)\n\t\t\tk42 = h*(p(x + h)*(v2[i] + k32) + q(x + h)*(v1[i] + k31))\n\t\t\tv1.append(v1[i] + (k11 + 2*k21 + 2*k31 + k41)/6)\n\t\t\tv2.append(v2[i] + (k12 + 2*k22 + 2*k32 + k42)/6)\n\t\tw1, w2 = [alpha], [(beta - u1[-1])/v1[-1]]\n\t\tfor i in range(1, N+1):\n\t\t\tw1.append(u1[i] + w2[0]*v1[i])\n\t\t\tw2.append(u2[i] + w2[0]*v2[i])\n\t\t\tx = a + i*h\n\t\t# return pd.DataFrame(data={\"Iterations\": range(N+1), \"Domain\": np.linspace(a, b, N+1), \"Range\": w1, \"W2\": w2})\n\t\tself.iterations = tuple(range(N+1))\n\t\tself.domain = tuple(np.linspace(a, b, N+1))\n\t\tself.range = tuple(w1)\n\t\tself.derivatives = tuple(w2)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Domain\": self.domain, \"Range\": self.range, \"Derivatives\": self.derivatives})\n\n\tdef finite_difference_method(self, solver_method=\"gauss_seidel\"):\n\t\t\"\"\"Solve a Boundary Value Problem differential equation with 2 Initial Value Problem differential equations.\n\n\t\tParameters\n\t\t----------\n\t\tsolver_method : str, optional\n\t\t\tUnless specified, system of equations will be solved by the 'gauss_seidel' method.\n\n\t\tReturns\n\t\t-------\n\t\tpandas.Dataframe() : dataframe\n\t\t\tDataframe of method iterations and time domains, range of approximations for input function, and iterative increments.\n\n\t\tYields\n\t\t------\n\t\tself.step_size : float\n\t\t\tDomain step size.\n\n\t\tself.iterations : tuple\n\t\t\tCollection of steps through method.\n\n\t\tself.domain : tuple\n\t\t\tDiscretized domain between endpoints a and b for so many steps.\n\n\t\tself.range : tuple\n\t\t\tRange mapped from method through discretized domain between endpoints a and b for so many steps.\n\n\t\tself.derivatives : tuple\n\t\t\tCollection of derivatives at each step.\n\n\t\tRaises\n\t\t------\n\t\tTypeError\n\t\t\tIf input expression cannot be understood as lambda or sympy expression nor as string.\n\n\t\tValueError\n\t\t\tPrescribed method is not an available option.\n\n\t\tSee Also\n\t\t--------\n\t\tMultiVariableIteration.gauss_seidel()\n\n\t\tMultiVariableIteration.successive_relaxation()\n\n\t\tMultiVariableIteration.jacobi()\n\t\t\"\"\"\n\t\t# Parameters\n\t\t# ----------\n\t\t# f : expression\n\t\t# \tEquation to which derivative will be made.\n\n\t\t# a : int or float\n\t\t# \tInitial time.\n\n\t\t# b : int or float\n\t\t# \tFinal time.\n\t\t\n\t\t# alpha : float\n\t\t# \tInitial value of solution y(t = a).\n\n\t\t# beta : float\n\t\t# \tInitial value of solution y(t = b).\n\n\t\t# h : float\n\t\t# \tDomain step-size.\n\n\t\t# Returns\n\t\t# -------\n\t\t# pandas.Dataframe() : dataframe\n\t\t# \tDataframe of method iterations and time domains & range of approximations for input function and its time derivative.\n\n\t\tif np.sum(np.array(self.function).shape) > 0:\n\t\t\tF = []\n\t\t\tfor f in self.function:\n\t\t\t\tif isinstance(f, (FunctionType, sp.Expr)):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(self.variables[0])))\n\t\t\t\t\t\tf = sp.lambdify(self.variables[0], sym_function)\n\t\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\t\texcept:\n\t\t\t\t\t\tsym_function = sp.N(sp.sympify(f(*self.variables)))\n\t\t\t\t\t\tf = sp.lambdify(self.variables, sym_function)\n\t\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\telif isinstance(f, (str)):\n\t\t\t\t\tg = lambda x: eval(f)\n\t\t\t\t\tf = sp.lambdify(*self.variables, g(*self.variables))\n\t\t\t\t\t# print(\"String expression converted to lambda function.\")\n\t\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\t\t\tF.append(f)\n\t\t\tfunction = F\n\t\telse:\n\t\t\tif isinstance(self.function, (FunctionType, sp.Expr)):\n\t\t\t\ttry:\n\t\t\t\t\tsym_function = sp.N(sp.sympify(self.function(self.variables[0])))\n\t\t\t\t\tfunction = sp.lambdify(self.variables[0], sym_function)\n\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\t\texcept:\n\t\t\t\t\tsym_function = sp.N(sp.sympify(self.function(*self.variables)))\n\t\t\t\t\tfunction = sp.lambdify(self.variables, sym_function)\n\t\t\t\t\t# print(f\"Information: Input expression, {sym_function} used.\")\n\t\t\telif isinstance(self.function, (str)):\n\t\t\t\tg = lambda x: eval(self.function)\n\t\t\t\tfunction = sp.lambdify(*self.variables, g(*self.variables))\n\t\t\t\t# print(\"String expression converted to lambda function.\")\n\t\t\telse: raise TypeError(\"Unknown input.\")\n\t\ta, b, alpha, beta = self.a, self.b, self.alpha, self.beta\n\t\tvariables, N = self.variables, self.steps\n\t\th = float((b - a)/N)\n\t\tself.step_size = h\n\t\tai, bi, ci, di = [], [], [], []\n\t\tp, q, r, ypp = function\n\t\tx = a + h\n\t\tai.append(2 + (h**2)*q(x))\n\t\tbi.append(-1 + (h/2)*p(x))\n\t\tdi.append(-(h**2)*r(x) + (1 + (h/2)*p(x))*alpha)\n\t\tfor i in range(2, N):\n\t\t\tx = a + i*h\n\t\t\tai.append(2 + (h**2)*q(x))\n\t\t\tbi.append(-1 + (h/2)*p(x))\n\t\t\tci.append(-1 - (h/2)*p(x))\n\t\t\tdi.append(-(h**2)*r(x))\n\t\tx = b - h\n\t\tai.append(2 + (h**2)*q(x))\n\t\tci.append(-1 - (h/2)*p(x))\n\t\tdi.append(-(h**2)*r(x) + (1 - (h/2)*p(x))*beta)\n\t\tA = np.zeros((N, N))\n\t\tnp.fill_diagonal(A, ai)\n\t\tA = A + np.diagflat(bi, 1)\n\t\tA = A + np.diagflat(ci, -1)\n\t\tx0 = np.zeros(N)\n\t\tc = np.array(di)\n\t\tfoo = MultiVariableIteration(A, x0, c, max_iter=1000)\n\t\tif solver_method == \"gauss_seidel\":\n\t\t\tfoo.gauss_seidel()\n\t\telif solver_method == \"successive_relaxation\":\n\t\t\tfoo.successive_relaxation()\n\t\telif solver_method == \"jacobi\":\n\t\t\tfoo.jacobi()\n\t\telse: raise ValueError(\"ERROR! The desired method must be: 'gauss_seidel', 'successive_relaxation', or 'jacobi'.\")\n\t\tapproximations = foo.approximations[-1]\n\t\tapproximations = np.insert(approximations, 0, alpha)\n\t\tapproximations = np.append(approximations, beta)\n\t\t# return pd.DataFrame(data={\"Iterations\": range(len(np.linspace(a, b, N+2))), \"Domain\": np.linspace(a, b, N+2), \"Range\": approximations}), foo.iterations, foo.errors\n\t\tself.iterations = tuple(range(N+2))\n\t\tself.domain = tuple(np.linspace(a, b, N+2))\n\t\tself.range = tuple(approximations)\n\t\treturn pd.DataFrame(data={\"Iterations\": self.iterations, \"Domain\": self.domain, \"Range\": self.range}), foo.iterations, foo.errors\n# --------------------\n#   #   #   #   #   #   #   #   #\n\n\n#################################\n## Test\n# test compile of module.\nclass test:\t\t\t\t\t # test class\n\tdef test():\t\t\t\t # test function\n\t\t\"\"\"Was the module loaded correctly?\n\n\t\tRaises\n\t\t------\n\t\tsuccess : string\n\t\t\tPrints a message of successful function call.\n\t\t\"\"\"\n\t\tsuccess = \"Test complete.\"\n\t\tsys.exit(success)\n#   #   #   #   #   #   #   #   #\n\n\n#################################\n## End of Code\n# test.test()\t # \"Test complete.\"\n#   #   #   #   #   #   #   #   #\nimport matplotlib.pyplot as plt\n\nn = 5 \t# grain growth exponent\nH_star = 10**5 \t# activation enthalpy [J/mol]\nk0 = 10**10 \t# growth rate constant [micro-m-n/s]\nR = 8.314462175 \t# universal gas constant [J/K-mol]\nT = 1000 \t# absolute temperature [K]\nd0 = 10 \t# initial grain size [micro-m]\nt = 10*60 \t# total experiment time [s]\n\nd_dot = lambda t, d: k0/(n*d**(n - 1))*sp.exp(-H_star/R/T)\n\ndef d_dot_analytical(t, d0, h):\n\tdomain, Y, increment = np.arange(h, t+h, h), [d0], [0]\n\td = lambda t, d0: (d0**n + k0*sp.exp(-H_star/R/T)*t)**(1/n)\n\tfor ti in domain:\n\t\tY.append(d(ti, d0))\n\t\tincrement.append(d(ti, d0) - d(ti - h, d0))\n\treturn pd.DataFrame(data={\"Iterations\": range(len(domain)+1), \"Domain\": np.arange(0, t+h, h), \"Range\": Y, \"Increments\": increment})\n\n\nfig, (ax1, ax2) = plt.subplots(1, 2)\nk, H = 1, (10, 5, 1)\nfor h in H:\n\tdf = d_dot_analytical(t, d0, h)\n\tprint(f\"{k}, h = {h}s: d = {df['Range'].values[-1]} for total change = {np.sum(df['Increments'].values)} in {df['Iterations'].values[-1]} time steps.\")\n\tax1.plot(df[\"Domain\"].values, df[\"Range\"].values, label=f\"{h} s\")\n\tax2.plot(df[\"Domain\"].values, df[\"Increments\"].values, label=f\"{h} s\")\n\tk += 1\nax1.set_xlabel(\"Time [s]\")\nax1.set_ylabel(\"Approximations [mu m]\")\nax1.legend()\nax2.set_xlabel(\"Time [s]\")\nax2.set_ylabel(\"Total Change [mu m]\")\nax2.legend()\n# plt.show()\n\nfig, (ax1, ax2) = plt.subplots(1, 2)\nk, H = 1, (10, 5, 1)\nfor h in H:\n\tfoo = ivp(d_dot, 0, t, d0, steps=t/h)\n\tdf = foo.backward_euler()\n\tprint(f\"{k}, h = {h}s: d = {df['Range'].values[-1]} for total change = {np.sum(df['Increments'].values)} in {df['Iterations'].values[-1]} time steps.\")\n\tax1.plot(df[\"Domain\"].values, df[\"Range\"].values, label=f\"{h} s\")\n\tax2.plot(df[\"Domain\"].values, df[\"Increments\"].values, label=f\"{h} s\")\n\tk += 1\ndf = d_dot_analytical(t, d0, h)\nax1.plot(df[\"Domain\"].values, df[\"Range\"].values, label=f\"Analytical\")\nax2.plot(df[\"Domain\"].values, df[\"Increments\"].values, label=f\"Analytical\")\nax1.set_xlabel(\"Time [s]\")\nax1.set_ylabel(\"Approximations [mu m]\")\nax1.legend()\nax2.set_xlabel(\"Time [s]\")\nax2.set_ylabel(\"Total Change [mu m]\")\nax2.legend()\nplt.show()", "meta": {"hexsha": "8e23a636b2f0ef9692892d3f5170e59e45cf3977", "size": 139902, "ext": "py", "lang": "Python", "max_stars_repo_path": "_.py", "max_stars_repo_name": "jmanthony3/joby_m_anthony_iii", "max_stars_repo_head_hexsha": "87ec9cbb29040ddff40541c7d86f58221751dcfe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_.py", "max_issues_repo_name": "jmanthony3/joby_m_anthony_iii", "max_issues_repo_head_hexsha": "87ec9cbb29040ddff40541c7d86f58221751dcfe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_.py", "max_forks_repo_name": "jmanthony3/joby_m_anthony_iii", "max_forks_repo_head_hexsha": "87ec9cbb29040ddff40541c7d86f58221751dcfe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4134782609, "max_line_length": 390, "alphanum_fraction": 0.6337579163, "include": true, "reason": "import numpy,import scipy,import sympy", "num_tokens": 44046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.967410256173572, "lm_q2_score": 0.8902942290328345, "lm_q1q2_score": 0.8612797681785073}}
{"text": "import numpy as np\nfrom sympy import cos, cosh, simplify, sinh, symbols\n\nfrom einsteinpy.symbolic import GenericVector, MetricTensor\n\n\ndef euclidean_space_metric():\n    symbolstr = \"e1 e2\"  # let angle between e1 & e2 be theta\n    syms = symbols(symbolstr)\n    th = symbols(\"theta\")\n    list2d = np.zeros((2, 2), dtype=int).tolist()\n    # defining the metric tensor when axis are not orthogonal\n    list2d[0][0] = list2d[1][1] = 1\n    list2d[1][0] = list2d[0][1] = cos(th)\n    metric = MetricTensor(list2d, syms, config=\"ll\")\n    return metric\n\n\ndef test_GenericVector_change_config_theoretical_test():\n    # https://en.wikipedia.org/wiki/Covariance_and_contravariance_of_vectors#Definition\n    a, b, th = symbols(\"a b theta\")\n    metric = euclidean_space_metric()\n    # defining a contravariant vector\n    cnvec = GenericVector([a, b], metric.syms, config=\"u\", parent_metric=metric)\n    covec = cnvec.change_config(\"l\")  # get contravariant vector\n    assert simplify(covec.tensor()[0] - (a + b * cos(th))) == 0\n    assert simplify(covec.tensor()[1] - (b + a * cos(th))) == 0\n\n\ndef test_GenericVector_check_ValueErrors():\n    a, b = symbols(\"a b\")\n    syms = symbols(\"e1 e2\")\n    # input a tensor with wring rank\n    try:\n        arr = [[a, b], [b, 1]]\n        v1 = GenericVector(arr, syms, \"l\")\n        boolstore = False\n    except ValueError:\n        boolstore = True\n    assert boolstore\n    # input a wrong length config\n    try:\n        arr = [a, b]\n        v2 = GenericVector(arr, syms, \"uu\")\n        boolstore = False\n    except ValueError:\n        boolstore = True\n    assert boolstore\n\n\ndef test_lorentz_transform():\n    def get_vector():\n        syms = symbols(\"t x y z\")\n        t, x, y, z = syms\n        return GenericVector([t, x, y, z], syms=syms, config=\"u\")\n\n    def get_lorentz_matrix():\n        list2d = [[0 for t1 in range(4)] for t2 in range(4)]\n        phi = symbols(\"phi\")\n        list2d[0][0], list2d[0][1], list2d[1][0], list2d[1][1] = (\n            cosh(phi),\n            -sinh(phi),\n            -sinh(phi),\n            cosh(phi),\n        )\n        list2d[2][2], list2d[3][3] = 1, 1\n        return list2d\n\n    t, x, phi = symbols(\"t x phi\")\n    v = get_vector().lorentz_transform(get_lorentz_matrix())\n    print(v.tensor())\n    assert simplify(v[0] - (t * cosh(phi) - x * sinh(phi))) == 0\n    assert simplify(v[1] - (x * cosh(phi) - t * sinh(phi))) == 0\n", "meta": {"hexsha": "a7f5f50c002d848066b20577eeba9afec9bb5926", "size": 2380, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/einsteinpy/tests/test_symbolic/test_vector.py", "max_stars_repo_name": "r0cketr1kky/einsteinpy", "max_stars_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-23T17:01:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-23T17:01:26.000Z", "max_issues_repo_path": "src/einsteinpy/tests/test_symbolic/test_vector.py", "max_issues_repo_name": "r0cketr1kky/einsteinpy", "max_issues_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/einsteinpy/tests/test_symbolic/test_vector.py", "max_forks_repo_name": "r0cketr1kky/einsteinpy", "max_forks_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1621621622, "max_line_length": 87, "alphanum_fraction": 0.6004201681, "include": true, "reason": "import numpy,from sympy", "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843812, "lm_q2_score": 0.8991213718636754, "lm_q1q2_score": 0.8612793962015591}}
{"text": "\n\"\"\"\n  Name     : c11_12_normal_random.py\n  Book     : Python for Finance (2nd ed.)\n  Publisher: Packt Publishing Ltd. \n  Author   : Yuxing Yan\n  Date     : 6/6/2017\n  email    : yany@canisius.edu\n             paulyxy@hotmail.com\n\"\"\"\nimport numpy as np\nfrom scipy import stats,random\n#\nnp.random.seed(12345)\nn=5000000\n\nret = random.normal(0,1,n)\nprint('mean    =', np.mean(ret))\nprint('std     =',np.std(ret))\nprint('skewness=',stats.skew(ret))\nprint('kurtosis=',stats.kurtosis(ret))\n", "meta": {"hexsha": "7898dc7e71864580362611b66b4922d5e3a5ddad", "size": 484, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter11/c11_12_normal_random.py", "max_stars_repo_name": "John-ye666/Python-for-Finance-Second-Edition", "max_stars_repo_head_hexsha": "dabef09bcdd7b0ec2934774741bd0a7e1950de73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 236, "max_stars_repo_stars_event_min_datetime": "2017-07-02T03:06:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:15:33.000Z", "max_issues_repo_path": "Chapter11/c11_12_normal_random.py", "max_issues_repo_name": "John-ye666/Python-for-Finance-Second-Edition", "max_issues_repo_head_hexsha": "dabef09bcdd7b0ec2934774741bd0a7e1950de73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter11/c11_12_normal_random.py", "max_forks_repo_name": "John-ye666/Python-for-Finance-Second-Edition", "max_forks_repo_head_hexsha": "dabef09bcdd7b0ec2934774741bd0a7e1950de73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 139, "max_forks_repo_forks_event_min_datetime": "2017-06-30T10:28:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T19:43:34.000Z", "avg_line_length": 22.0, "max_line_length": 41, "alphanum_fraction": 0.6446280992, "include": true, "reason": "import numpy,from scipy", "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9579122696813394, "lm_q2_score": 0.899121373891026, "lm_q1q2_score": 0.8612793959829569}}
{"text": "# Project Euler Problem 6 Solution\n#\n# Problem statement:\n# The sum of the squares of the first ten natural numbers is,\n# 1^2 + 2^2 + ... + 10^2 = 385. The square of the sum of the\n# first ten natural numbers is (1 + 2 + ... + 10)^2 = 55^2 = 3025.\n# Hence the difference between the sum of the squares of the\n# first ten natural numbers and the square of the sum is 3025 − 385 = 2640.\n# Find the difference between the sum of the squares of the first\n# one hundred natural numbers and the square of the sum.\n#\n# Solution description:\n# Simple algebraic manipulations show, that the required sum equals\n# 2*1*(2 + 3 + ... + n) + 2*2*(3 + 4 + 5 + ... + n) + 2*3*...\n# This approach is implemented directly as a function with n as input.\n# For some further utility, the function also takes another input m with\n# default value m = 1, which determines the starting point for the summation.\n#\n# Author: Philipp Schuette\n# Date: 2019/02/10\n# License: MIT (see ../LICENSE.md)\n\nimport time\n\nimport numpy as np\n\n\ndef calc_sums(m, n):\n\tsum1 = 0  # gets incremented towards the final value\n\tsum2 = int((n*(n + 1) - m*(m + 1))/2)  # stores intermediate sums\n\tfor i in range(m, n):\n\t\tsum1 += i*sum2\n\t\tsum2 -= (i + 1)\n\treturn 2*sum1\n\n\nif __name__ == \"__main__\":\n    # calculate result and time it\n    start = time.time()\n    target = 100\n    solution = calc_sums(1, target)\n    end = time.time()\n\n    # print result\n    print(\"expired: {}s, solution: {}\".format(\n    np.round(end - start, 5), solution))\n", "meta": {"hexsha": "2ae643a58c04467001164c54fbcedff0094b12f9", "size": 1490, "ext": "py", "lang": "Python", "max_stars_repo_path": "py_src/problem006.py", "max_stars_repo_name": "PhilippSchuette/projecteuler", "max_stars_repo_head_hexsha": "b74f76e8f27769d5cfc4227ccfb272d0a83ef587", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-09-24T14:14:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T01:57:12.000Z", "max_issues_repo_path": "py_src/problem006.py", "max_issues_repo_name": "PhilippSchuette/projecteuler", "max_issues_repo_head_hexsha": "b74f76e8f27769d5cfc4227ccfb272d0a83ef587", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2018-09-24T14:18:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-08T07:03:31.000Z", "max_forks_repo_path": "py_src/problem006.py", "max_forks_repo_name": "PhilippSchuette/projecteuler", "max_forks_repo_head_hexsha": "b74f76e8f27769d5cfc4227ccfb272d0a83ef587", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-03-01T14:22:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T01:57:53.000Z", "avg_line_length": 31.7021276596, "max_line_length": 77, "alphanum_fraction": 0.6644295302, "include": true, "reason": "import numpy", "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505204, "lm_q2_score": 0.9207896753475597, "lm_q1q2_score": 0.8612574157724194}}
{"text": "\nimport numpy as np\n\ndef NewtonRaphson(f, fprime, x0, max_iter = 100, prec = 1e-10, verbose=False):\n    \n    x = [x0]\n    x_val = x0\n        \n    for i in range(max_iter):\n        \n        val_i = f(x[i])\n        df = fprime(x[i])\n        epsilon = val_i/df\n        x_val = x_val - epsilon\n        x.append(x_val)\n        \n        if abs(epsilon) < prec:\n            print(abs(df))\n            return x_val, x\n    if verbose:\n        print(f\"This calculation did not converge after {max_iter} iterations\")\n    \n    return x_val, x\n\n\ndef NewtonRaphsonFact(f=None, fprime=None, x0=None, max_iter = 100, prec = 1e-10, verbose=False, **kwargs):\n    \n    x = [x0]\n    x_val = x0\n\n    for i in range(max_iter):\n        \n        val_i = f(x[i])\n        df = fprime(x[i])\n        epsilon = val_i/df\n        x_val = x_val - epsilon\n        x.append(x_val)\n        \n        if abs(epsilon) < prec:\n            return i\n    if verbose:\n        print(f\"This calculation did not converge after {max_iter} iterations\")\n    \n    return i\n\ndef mandelbrot(c, max_iter = 80, **kwargs):\n    z = 0\n    n = 0\n    while abs(z) <= 2 and n < max_iter:\n        z = z**2 + c\n        n += 1\n    return n\n\ndef CreateImageMap(function, function_args, bounds, max_iter = 80, width = 200, height = 200):\n    \n    re_start, re_end, im_start, im_end = bounds\n    if width > 1000:\n        print(f'width of {width} is too large. Your computer only has so many pixels.')\n        print(\"try zooming in with a smaller boundary to observe more detail\")\n        return\n        \n    if height > 1000:\n        print(f'height of {height} is too large. Your computer only has so many pixels.')\n        print(\"try zooming in with a smaller boundary to observe more detail\")\n        return\n    \n    X = np.zeros([width, height])\n    for x in range(0, width):\n        for y in range(0,height):\n            real = re_start + (x/width) * ( re_end - re_start)\n            imaginary = im_start + (y/width) * ( im_end - im_start)\n            guess = complex(real, imaginary)\n            try:\n                function_args['mult']\n            except KeyError:\n                function_args['mult'] = 1.1\n            \n            function_args['x0'] = guess\n            function_args['x1'] = function_args['mult'] * guess\n            function_args['c'] = guess\n            try:\n                m = function(**function_args)\n            except Exception as e:\n                print(e)\n                m = max_iter\n            color = 255 - int(m * 255 / max_iter)\n            \n            X[x,y] = color\n            \n    return X\n\ndef secantfact(function, x0, x1, max_iter = 200, prec = 1e-5, verbose = False, **kwargs):\n    \n    f1 = function(x0)\n    f = function(x1)\n    \n    if abs(f1) < abs(f):\n        rts = x0\n        x1 = x1\n        f1, f = f, f1\n    else:\n        rts = x1\n    for i in range(max_iter):\n        dx = (x0 - rts) * f / (f - f1)\n        x0 = rts\n        f1 = f\n        rts += dx\n        f = function(rts)\n        \n        if abs(dx) < prec or f == 0:\n            return i\n   \n    if verbose:\n         print(f\"This calculation did not converge after {max_iter} iterations\")\n    return i\n\n\ndef schroderfact(derivative, function, secondder, x0, prec = 1e-5, max_iter = 50, **kwargs):\n    check = 1\n    xim1 = x0\n    n = 0\n    while prec < check:\n        num = (function(xim1) * derivative(xim1))\n        dem = derivative(xim1)**2 - function(xim1) * secondder(xim1)\n        xi = xim1 - num / dem\n        n += 1\n        check = abs(xi - xim1)\n        xim1 = xi\n        # print(check)\n        if n == max_iter:\n            break\n    return  n \n\ndef halleyfact(derivative, function,seconder, x0, prec = 1e-5, max_iter = 100, **kwargs):\n    check = 1\n    xim1 = x0\n    n = 0\n    for i in range(max_iter):\n        \n        a = function(xim1) * seconder(xim1)\n        b = 2 * derivative(xim1) ** 2\n        c = 1 - a/b\n\n        d = derivative(xim1) * c\n        xi = xim1 - function(xim1) / d\n        n += 1\n        check = abs(xi - xim1)\n        xim1 = xi\n        eps = abs(function(xim1) / d)\n        \n        if eps < prec:\n            break\n\n    \n    return  n \n\ndef nderiv(func, x, eps=np.sqrt(np.finfo(float).eps)):\n    ''' Takes a vector of each component of a multivariate \n    function and returns its Jacobian matrix as computed by \n    finite differences'''\n    \n    N = len(x)\n\n    J = [[None for i in range(N)] for j in range(N)]\n    #xh is x + h in the derivative formula \n    xh = x\n    # very bad quick fix, will not work as a gradient \n    if isinstance(x[0], complex):\n        eps = complex(eps, eps)\n    for i in range(N):\n        temp = xh[i]\n        h = eps * temp\n        if h == 0: h = eps\n        xh[i] = temp + h # scootch that point over \n        # evalueat f(x+h)\n        f = func(xh)\n        \n        xh[i] = temp\n        fvec = func(x)\n        # forward difference formula\n        for j in range(N):\n            J[j][i] = (f[j] - fvec[j])/h\n\n    if len(x) == 1:\n        return J[0][0]\n            \n    return J \n", "meta": {"hexsha": "147b4c9aeb5d44f9f5ec7e7976603300c9567453", "size": 4995, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/fractals/scripts/fractalfuncs.py", "max_stars_repo_name": "lgfunderburk/mathscovery", "max_stars_repo_head_hexsha": "da9fcfd7f660835c663985c94645aec6dfd9f7bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/fractals/scripts/fractalfuncs.py", "max_issues_repo_name": "lgfunderburk/mathscovery", "max_issues_repo_head_hexsha": "da9fcfd7f660835c663985c94645aec6dfd9f7bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/fractals/scripts/fractalfuncs.py", "max_forks_repo_name": "lgfunderburk/mathscovery", "max_forks_repo_head_hexsha": "da9fcfd7f660835c663985c94645aec6dfd9f7bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-12T00:49:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-12T00:49:57.000Z", "avg_line_length": 26.5691489362, "max_line_length": 107, "alphanum_fraction": 0.5109109109, "include": true, "reason": "import numpy", "num_tokens": 1454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951703918909, "lm_q2_score": 0.8962513807543223, "lm_q1q2_score": 0.861254291475541}}
{"text": "import numpy as np\n\ndef gaussian(x,x0=0,sigma=1):\n    '''Numpy implementation of gaussian'''    \n    return np.exp(\n        -np.power((x - x0) / sigma, 2) / 2\n    ) / (np.sqrt(2 * np.pi) * sigma)\n\ndef cumulative_gaussian_lut(step:float=0.01, sigma_count:int=3):\n    '''\n    Cumulative and normalized gaussian Lookup table.\n\n    1. Function creates gaussian with x0 = 0.5 and sigma = 0.5 / 3 in range\n       from 0 to 1.\n       According to 3 sigma rule 99.7% values are in range from 0 to 1.\n    2. Calculates cumulative sum on gaussian\n    4. Normalize by max value\n\n    Arguments are in range [0;1) and values are in range [0;1].\n    Argument 0 has value 0.\n\n    Parameters\n    ==========\n    step: float, optional\n        Resolution of LUT. The smaller value, the less accuracy you get.\n        The bigger value, the more memory you use. 0.01-0.001 should be good.\n    sigma_count: int, optional\n        What multiple of sigma should the half of width be.\n        According the 1 sigma rule in range +- 1 sigma is 68.2% values.\n        According the 2 sigma rule in range +- 2 sigma is 95.4% values.\n        According the 3 sigma rule in range +- 3 sigma is 99.7% values.\n        According the 4 sigma rule in range +- 4 sigma is 99.994% values.\n        You may to use this parameter to control value change rate.\n        1 sigma - linear, 4 sigma - slow at begin and at end, fast in middle.\n\n    Returns\n    =======\n    Function for access to approximated value for given argument.\n    It accepts argument from range [0;1) (from 0 (inclusive) to 1 (exclusive)).\n    Returns 0 ir 1 if index out of bounds.\n    Return the nearest precalculated for given argument (range (0; 1]\n    from 0 (exclusive) to 1 (exclusive))).\n\n    Examples\n    ========\n    >>> lut = cumulative_reversed_gaussian_lut()\n    >>> lut(0)\n        0\n    >>> lut(0.5)\n        0.49881326466597947\n    >>> lut(0.25)\n        0.9339886741945999\n    '''\n    a = np.arange(0, 1, step)\n    width = 1\n    half_width = width / 2\n    x0 = half_width\n    sigma = half_width / sigma_count\n\n    gx = gaussian(a, x0=x0, sigma=sigma)\n    cs = np.cumsum(gx)\n    max_ = cs[len(cs) - 1]\n    normalized_cs = cs / max_\n\n    def get_value(x):\n        if x < 0:\n            return 0\n        elif x >= 1:\n            return 1\n        idx = int(x / step)\n        return normalized_cs[idx]\n    return get_value\n\nif __name__ == '__main__':\n    # Example usage. Draw gaussian plots and cumulative, normalized\n    # plots for different sigma.\n    \n    step = 0.001\n    lut_count = 4\n    r = range(1, lut_count + 1)\n    luts = [cumulative_gaussian_lut(step=step, sigma_count=i)\n                for i in r]\n    a = [i * step for i in range(0, int(1 / step))]\n\n    from matplotlib import pyplot as plt\n    plt.subplot(1, 2, 1)\n    for lut in luts:\n        plt.plot(a, [lut(i) for i in a])\n    plt.legend([\"%d sigma\" % (i,) for i in r])\n\n    plt.subplot(1, 2, 2)\n    for i in range(1, lut_count + 1):\n        sigma = 1 / i\n        g = gaussian(np.array(a), 0.5, sigma)\n        max_ = g.max()\n        g = g / max_\n        plt.plot(a, g)\n    plt.legend([\"%d sigma\" % (i,) for i in r])\n    plt.suptitle(('Cumulative, normalized gaussian'))\n    plt.show()\n\n", "meta": {"hexsha": "0fafa858c2277eb8ee3f66589459b6584d57e6c6", "size": 3193, "ext": "py", "lang": "Python", "max_stars_repo_path": "analog_noise_estimator/gaussian.py", "max_stars_repo_name": "gut-space/analog-noise-estimator", "max_stars_repo_head_hexsha": "1faaac363268522941e694a6caf1814c83a5e745", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-08T19:35:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-08T19:35:05.000Z", "max_issues_repo_path": "analog_noise_estimator/gaussian.py", "max_issues_repo_name": "gut-space/analog-noise-estimator", "max_issues_repo_head_hexsha": "1faaac363268522941e694a6caf1814c83a5e745", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analog_noise_estimator/gaussian.py", "max_forks_repo_name": "gut-space/analog-noise-estimator", "max_forks_repo_head_hexsha": "1faaac363268522941e694a6caf1814c83a5e745", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3039215686, "max_line_length": 79, "alphanum_fraction": 0.596617601, "include": true, "reason": "import numpy", "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920617, "lm_q2_score": 0.8962513689768735, "lm_q1q2_score": 0.8612542841670506}}
{"text": "import numpy as np\n\ndef decimal_to_binlist(decimal, digits): # ex) 6,3 --> [1,1,0]\n\n    bin_str = \"{:0{digits}b}\".format(decimal, digits=digits)\n    return  [int(s) for s in list(bin_str)]\n    \ndef binlist_to_decimal(bin_list): # ex) [0,1,1] --> 3\n\n    return int(\"\".join([str(i) for i in bin_list]), 2)\n\ndef make_hamming_matrix(r):\n\n    # parity check matrix (H)\n    A = []\n    for x in range(1,2**r):\n        bin_list = decimal_to_binlist(x, r)\n        if sum(bin_list) == 1: continue\n        A.append(bin_list)\n    A = np.array(A)\n    I_H = np.eye(r, dtype=int)\n    H = np.concatenate([A, I_H])\n    \n    # represent integer each row of H matrix (for error correction algorithm)\n    H_int = [binlist_to_decimal(row) for row in H]\n    \n    # generator matrix (G)\n    I_G = np.eye(2**r-r-1, dtype=int)\n    G = np.concatenate([I_G, A], 1)\n    \n    return G, H, H_int\n\ndef generate_data(k, N):  # random k-bits data\n\n    for _ in range(N):\n        yield np.random.randint(2, size=k)\n\ndef add_noise(d_in):  # bit flip to one bit (select randomly)\n\n    idx = np.random.randint(len(d_in))\n    err = np.array([1 if i == idx else 0 for i in range(len(d_in))])\n    d_out = (d_in + err) % 2\n    return d_out\n    \ndef correct_error(d_in, H_int):\n\n    d_out = d_in.copy()\n    p = (d_out @ H) % 2\n    x = binlist_to_decimal(p)\n    err_idx = H_int.index(x)\n    d_out[err_idx] = (d_out[err_idx] + 1) % 2  # bit flip (recover)\n    return d_out\n    \nif __name__ == '__main__':\n\n    r = 3\n    n = 2**r - 1\n    k = 2**r - r - 1\n    N = 10\n\n    G, H, H_int  = make_hamming_matrix(r)\n\n    print(\"* input(random) -> encode -> add noise(random 1-bit flip) -> correct -> decode:\")\n    err_count = 0\n    for x in generate_data(k, N):\n        y = (x @ G)%2\n        y_error = add_noise(y)\n        y_correct = correct_error(y_error, H_int)\n        x_correct = y_correct[0:k]  # decode (= extract 1st to k-th elements)\n        print(\"{0:} -> {1:} -> {2:} -> {3:} -> {4:}\".format(x,y,y_error,y_correct,x_correct))\n        \n        if sum((x+x_correct)%2) == 1: # if x != x_correct --> 1\n            err_count += 1\n\n    err_rate = err_count / N\n    print(\"* error rate = {0:} (count:{1:} / total:{2:})\".format(err_rate, err_count, N))\n", "meta": {"hexsha": "030d00f272eb119911f86c7a88c70f51bc481ff9", "size": 2205, "ext": "py", "lang": "Python", "max_stars_repo_path": "example/py/ErrorCorrection/hamming_code.py", "max_stars_repo_name": "samn33/qlazy", "max_stars_repo_head_hexsha": "b215febfec0a3b8192e57a20ec85f14576745a89", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2019-04-09T13:02:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T12:57:08.000Z", "max_issues_repo_path": "example/py/ErrorCorrection/hamming_code.py", "max_issues_repo_name": "samn33/qlazy", "max_issues_repo_head_hexsha": "b215febfec0a3b8192e57a20ec85f14576745a89", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-02-26T16:21:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T00:46:53.000Z", "max_forks_repo_path": "example/py/ErrorCorrection/hamming_code.py", "max_forks_repo_name": "samn33/qlazy", "max_forks_repo_head_hexsha": "b215febfec0a3b8192e57a20ec85f14576745a89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-01-28T05:38:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-30T12:19:19.000Z", "avg_line_length": 28.6363636364, "max_line_length": 93, "alphanum_fraction": 0.5714285714, "include": true, "reason": "import numpy", "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951703918909, "lm_q2_score": 0.8962513655129177, "lm_q1q2_score": 0.8612542768292872}}
{"text": "import numpy as np\n\ndef _fourDVR(start,stop,num):\n    \"\"\" \n    Calculate periodic Fourier (exponential) DVR grid and operators.\n    \n    Parameters\n    ----------\n    start : float\n        Grid start value\n    stop : float\n        Grid stop value. Must be larger than start\n    num : int\n        Number of grid points. Must be >= 3 and odd.\n\n    Returns\n    -------\n    grid : ndarray\n        Array of DVR grid points\n    D : ndarray\n        First derivative operator in DVR basis, shape (num, num)\n    D2 : ndarray (num,num)\n        Second derivative operator in DVR basis, shape (num, num)\n\n    \"\"\"\n    \n    if stop <= start:\n        raise ValueError(\"stop value must be larger than start value\")\n    if num < 3 :\n        raise ValueError(\"num must be >= 3\")\n    if num % 2 == 0:\n        raise ValueError(\"num must be odd\")\n        \n    \n    grid = np.linspace(start, stop, num+1)[0:num]\n    period = stop - start\n    \n    D = np.ndarray((num,num))\n    D2 = np.ndarray((num,num))\n    \n    for i in range(num):\n        for j in range(i,num):\n            delta = i - j \n            if delta == 0:\n                D[i,j] = 0\n                D2[i,j] = -(np.pi / period)**2 * (1/3.0) * (num**2 - 1)\n            else:\n                D[i,j] = (np.pi / period) * (-1)**delta / np.sin(np.pi*delta/num)\n                D[j,i] = -D[i,j]\n                \n                D2[i,j] = -2*(np.pi / period)**2 * (-1)**delta * np.cos(np.pi * delta / num) / (np.sin(np.pi*delta/num)**2)\n                D2[j,i] = +D2[i,j]\n    \n    return grid, D, D2\n\ndef _fourDVRwfs(q, start, stop, num):\n    \"\"\"\n    Calculate Fourier (exponential) DVR wavefunctions.\n\n    Parameters\n    ----------\n    q : ndarray\n        A 1D array of coordinate values.\n    start : float\n        DVR grid start value.\n    stop : float\n        DVR grid stop value.\n    num : int\n        The number of DVR grid points\n\n    Returns\n    -------\n    wfs : ndarray\n        A (`q`.size, `num`) shaped array with\n        the DVR wavefunctions evaluated at grid points `q`.\n\n    \"\"\"\n        \n    if np.ndim(q) != 1:\n        raise ValueError(\"q must be 1-dimensional\")\n    if stop <= start:\n        raise ValueError(\"stop value must be larger than start value\")\n    if num < 3 :\n        raise ValueError(\"num must be >= 3\")\n    if num % 2 == 0:\n        raise ValueError(\"num must be odd\")\n        \n    nq = q.size\n    \n    period = stop - start\n    \n    wfs = np.ndarray((nq,num), dtype = q.dtype)\n    \n    m = (num-1)//2 # max frequency\n    \n    for i in range(num): # DVR function at i^th grid point\n        t = 1\n        for k in range(1,m+1): # Calculate exponential sum as cosines explicitly\n            t += 2*np.cos(k*(q - start - i*period/num) * 2*np.pi/period)\n            \n        wfs[:,i] = t/np.sqrt(num*period)\n    \n    return wfs", "meta": {"hexsha": "534c2d33869956dc6aab0751f731c57b24609bc0", "size": 2786, "ext": "py", "lang": "Python", "max_stars_repo_path": "nitrogen/basis/fourDVR.py", "max_stars_repo_name": "bchangala/nitrogen", "max_stars_repo_head_hexsha": "94f8828a51aa536fe93fe6a8bdd8da04eb6fdce8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-02-09T04:09:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T20:47:27.000Z", "max_issues_repo_path": "nitrogen/basis/fourDVR.py", "max_issues_repo_name": "bchangala/nitrogen", "max_issues_repo_head_hexsha": "94f8828a51aa536fe93fe6a8bdd8da04eb6fdce8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nitrogen/basis/fourDVR.py", "max_forks_repo_name": "bchangala/nitrogen", "max_forks_repo_head_hexsha": "94f8828a51aa536fe93fe6a8bdd8da04eb6fdce8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-01T12:42:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:42:35.000Z", "avg_line_length": 27.0485436893, "max_line_length": 123, "alphanum_fraction": 0.5143575018, "include": true, "reason": "import numpy", "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147193720648, "lm_q2_score": 0.8856314828740728, "lm_q1q2_score": 0.8612010898860571}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy.polynomial.polynomial import Polynomial\nfrom scipy.interpolate import lagrange\n\n# Interpolate basis vector e1.\nplt.figure()\nx = np.linspace(0, 1, 5)\ne1 = np.array([1, 0, 0, 0, 0])\nx_fine = np.linspace(0, 1)\nprint(f\"x = {x}\")\n\npoly = lagrange(x, e1)\ncoef1 = poly.coef[::-1] # reverse order of coefficients\n\nplt.scatter(x, e1, color=\"red\", label=\"points and values\")\nplt.plot(x_fine, Polynomial(coef1)(x_fine), label=\"Lagrange polynomial\")\nplt.legend()\nplt.show()\n\n# Interpolate five basis vectors e1, e2, e3, e4, e5.\ne2 = np.array([0, 1, 0, 0, 0])\ne3 = np.array([0, 0, 1, 0, 0])\ne4 = np.array([0, 0, 0, 1, 0])\ne5 = np.array([0, 0, 0, 0, 1])\n\ncoef2 = lagrange(x, e2).coef[::-1] # reverse order of coefficients\ncoef3 = lagrange(x, e3).coef[::-1] # reverse order of coefficients\ncoef4 = lagrange(x, e4).coef[::-1] # reverse order of coefficients\ncoef5 = lagrange(x, e5).coef[::-1] # reverse order of coefficients\n\nplt.figure()\nplt.plot(x_fine, Polynomial(coef1)(x_fine), label=\"Lagrange polynomial of e1\")\nplt.plot(x_fine, Polynomial(coef2)(x_fine), label=\"Lagrange polynomial of e2\")\nplt.plot(x_fine, Polynomial(coef3)(x_fine), label=\"Lagrange polynomial of e3\")\nplt.plot(x_fine, Polynomial(coef4)(x_fine), label=\"Lagrange polynomial of e4\")\nplt.plot(x_fine, Polynomial(coef5)(x_fine), label=\"Lagrange polynomial of e5\")\nplt.legend()\nplt.show()\n\n# Interpolate arbitrary data vector y\ny = np.random.sample(5)*10-5\ncoef = lagrange(x, y).coef[::-1] # reverse order of coefficients\n\nplt.figure()\nplt.scatter(x, y, color=\"red\", label=\"points and values\")\nplt.plot(x_fine, Polynomial(coef1)(x_fine)*y[0] + Polynomial(coef2)(x_fine)*y[1] + Polynomial(coef3)(x_fine)*y[2] + Polynomial(coef4)(x_fine)*y[3] + Polynomial(coef5)(x_fine)*y[4], label=\"Sum\")\nplt.plot(x_fine, Polynomial(coef)(x_fine), label=\"Lagrange polynomial\", linestyle=\"--\")\nplt.legend()\nplt.show()", "meta": {"hexsha": "ca7b31cc04e979889f68be816c88824fc8f2ab34", "size": 1914, "ext": "py", "lang": "Python", "max_stars_repo_path": "ue/ue_07/problem_2.py", "max_stars_repo_name": "VoxelPi/compm", "max_stars_repo_head_hexsha": "745019d4e0d156910f19ed9168949f150356a349", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ue/ue_07/problem_2.py", "max_issues_repo_name": "VoxelPi/compm", "max_issues_repo_head_hexsha": "745019d4e0d156910f19ed9168949f150356a349", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-03-09T22:54:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:33:49.000Z", "max_forks_repo_path": "ue/ue_07/problem_2.py", "max_forks_repo_name": "VoxelPi/compm", "max_forks_repo_head_hexsha": "745019d4e0d156910f19ed9168949f150356a349", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.28, "max_line_length": 193, "alphanum_fraction": 0.7048066876, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147161743552, "lm_q2_score": 0.8856314662716159, "lm_q1q2_score": 0.8612010709095914}}
{"text": "\"\"\"\n\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef costfunction(X,y,theta):\n    m = np.size(y)\n\n    #Cost function in vectorized form\n    h = X @ theta\n    J = float((1./(2*m)) * (h - y).T @ (h - y));    \n    return J\n\n\ndef gradient_descent(X,y,theta,alpha = 0.0005,num_iters=1000):\n    #Initialisation of useful values \n    m = np.size(y)\n    J_history = np.zeros(num_iters)\n    theta_0_hist, theta_1_hist = [], [] #For plotting afterwards\n\n    for i in range(num_iters):\n        #Grad function in vectorized form\n        h = X @ theta\n\n        # update parameters by gradient descent\n        theta = theta - alpha * (1/m)* (X.T @ (h-y))\n\n        #Cost and intermediate values for each iteration\n        J_history[i] = costfunction(X,y,theta)\n        theta_0_hist.append(theta[0,0])\n        theta_1_hist.append(theta[1,0])\n\n    return theta,J_history, theta_0_hist, theta_1_hist\n\n#Creating the dataset (as previously)\nx = np.linspace(0,1,40)\nnoise = 1*np.random.uniform(  size = 40)\ny = np.sin(x * 1.5 * np.pi ) \ny_noise = (y + noise).reshape(-1,1)\nX = np.vstack((np.ones(len(x)),x)).T\n\n\n#Setup of meshgrid of theta values\nT0, T1 = np.meshgrid(np.linspace(-1,3,100),np.linspace(-6,2,100))\n\n#Computing the cost function for each theta combination\nzs = np.array(  [costfunction(X, y_noise.reshape(-1,1),np.array([t0,t1]).reshape(-1,1)) \n                     for t0, t1 in zip(np.ravel(T0), np.ravel(T1)) ] )\n#Reshaping the cost values    \nZ = zs.reshape(T0.shape)\n\n\n#Computing the gradient descent\ntheta_result,J_history, theta_0, theta_1 = gradient_descent(X,y_noise,np.array([0,-6]).reshape(-1,1),alpha = 0.3,num_iters=1000)\n\n#Angles needed for quiver plot\nanglesx = np.array(theta_0)[1:] - np.array(theta_0)[:-1]\nanglesy = np.array(theta_1)[1:] - np.array(theta_1)[:-1]\n\n\nfig = plt.figure(figsize = (16,8))\n\n#Surface plot\nax = fig.add_subplot(1, 2, 1, projection='3d')\nax.plot_surface(T0, T1, Z, rstride = 5, cstride = 5, cmap = 'jet', alpha=0.5)\nax.plot(theta_0,theta_1,J_history, marker = '*', color = 'r', alpha = .4, label = 'Gradient descent')\n\nax.set_xlabel('theta 0')\nax.set_ylabel('theta 1')\nax.set_zlabel('Cost function')\nax.set_title('Gradient descent: Root at {}'.format(theta_result.ravel()))\nax.view_init(45, 45)\n\n\n#Contour plot\nax = fig.add_subplot(1, 2, 2)\nax.contour(T0, T1, Z, 70, cmap = 'jet')\nax.quiver(theta_0[:-1], theta_1[:-1], anglesx, anglesy, scale_units = 'xy', angles = 'xy', scale = 1, color = 'r', alpha = .9)\n# plt.axis('equal')\nplt.show()", "meta": {"hexsha": "507a35e11e824c113a73bc2cab23fe06628f3db5", "size": 2550, "ext": "py", "lang": "Python", "max_stars_repo_path": "gradient-descent/main.py", "max_stars_repo_name": "zww-4855/Numerical-Computation", "max_stars_repo_head_hexsha": "3226d10f0d27a6fbe89fee4e5ca2e54ca0b88f28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-14T00:45:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T00:45:02.000Z", "max_issues_repo_path": "gradient-descent/main.py", "max_issues_repo_name": "zww-4855/Numerical-Computation", "max_issues_repo_head_hexsha": "3226d10f0d27a6fbe89fee4e5ca2e54ca0b88f28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gradient-descent/main.py", "max_forks_repo_name": "zww-4855/Numerical-Computation", "max_forks_repo_head_hexsha": "3226d10f0d27a6fbe89fee4e5ca2e54ca0b88f28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-27T17:05:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T17:05:56.000Z", "avg_line_length": 30.7228915663, "max_line_length": 128, "alphanum_fraction": 0.6537254902, "include": true, "reason": "import numpy", "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877658567787, "lm_q2_score": 0.8872046041554922, "lm_q1q2_score": 0.8611986550655425}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# ch9Python.py. Nonlinear regression.\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport statsmodels.api as sm\n\nx1 = [1.00,1.25,1.50,1.75,2.00,2.25,2.50,2.75,3.00,3.25,3.50,3.75,4.00]\ny = [3.34,4.97,4.15,5.40,5.21,4.56,3.69,5.86,4.58,6.94,5.57,5.62,6.87]\n\n# Convert data to vectors.   \nx1 = np.array(x1)\ny = np.array(y)\nn = len(y)\nx2 = x1**2 # define x2 as square of x1.\n\n###############################\n# Quadratic model. Repeated twice: 1) Vector-matrix, 2) Standard library.\n###############################\nymean = np.mean(y)\nones = np.ones(len(y)) # 1 x n vector\nXtr = [ones, x1, x2]   # 3 x n matrix\nX = np.transpose(Xtr)  # n x 3 matrix\ny = np.transpose(y)    # 1 x n vector\n\n# 1) Find slopes and intercept using vector-matrix notation.\nXdot = np.dot(Xtr,X)\nXdotinv = np.linalg.pinv(Xdot)\nXdotinvA = np.dot(Xdotinv,Xtr)\nparams = np.dot(XdotinvA,y)\n\nb0Quadratic = params[0] # 3.819\nb1Quadratic = params[1] # 0.212\nb2Quadratic = params[2] # 0.111\n\nprint('\\nQUADRATIC VECTOR-MATRIX PARAMETERS') \nprint('slope b1 = %6.3f' % b1Quadratic) \nprint('slope b2 = %6.3f' % b2Quadratic)\nprint('intercept b0 = %6.3f' % b0Quadratic)\n\n# 2) STANDARD LIBRARY Quadratic output.\nquadraticModel = sm.OLS(y, X).fit()\nprint('\\n\\nQUADRATIC MODEL SUMMARY') \nprint(quadraticModel.params)\nprint(quadraticModel.summary())\n\n###############################\n# Linear model (using standard library).\n###############################\nXtr = [ones, x1]\nX = np.transpose(Xtr)\nlinearModel = sm.OLS(y, X).fit()\nprint('\\n\\nLINEAR MODEL SUMMARY') \nprint(linearModel.params)\nprint(linearModel.summary())\n\nparams = linearModel.params\nb0LINEAR = params[0] # 3.225\nb1LINEAR = params[1] # 0.764\nyhatLINEAR = b1LINEAR * x1 + b0LINEAR\n\n###############################\n# PLOT DATA.\n###############################\nfig = plt.figure(1)\nfig.clear()\nyhatQuadratic = b1Quadratic * x1 + b2Quadratic * x2 + b0Quadratic\n\nplt.plot(x1, y, \"o\", label=\"Data\")\nplt.plot(x1, yhatQuadratic, \"b--\",label=\"Quadratic fit\")\nplt.plot(x1, yhatLINEAR, \"r--\",label=\"Linear fit\")\nplt.legend(loc=\"best\")\nplt.show()\n\n###############################\n# STANDARD LIBRARY: Results of extra sum of squares method.\n###############################\n# test hypothesis that x2=0\nhypothesis = '(x2 = 0)'\nf_test = quadraticModel.f_test(hypothesis)\nprint('\\nResults of extra sum of squares method:')\nprint('F df_num = %.3f df_denom = %.3f' \n% (f_test.df_num, f_test.df_denom))       # 1, 10\nprint('F partial = %.3f' % f_test.fvalue) # 1.127\nprint('p-value (that x2=0) = %.3f' % f_test.pvalue)   # 0.729\n\n###############################\n# END OF FILE.\n###############################", "meta": {"hexsha": "232b06e8c7d46a85e0de0fface10199fb57c29c3", "size": 2655, "ext": "py", "lang": "Python", "max_stars_repo_path": "PythonCode/Ch09/ch9Python.py", "max_stars_repo_name": "jgvfwstone/Regression", "max_stars_repo_head_hexsha": "483e8057f2cadcec43cf7475ef19a8f2113fed80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-20T15:40:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T11:40:38.000Z", "max_issues_repo_path": "PythonCode/Ch09/ch9Python.py", "max_issues_repo_name": "jgvfwstone/Regression", "max_issues_repo_head_hexsha": "483e8057f2cadcec43cf7475ef19a8f2113fed80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PythonCode/Ch09/ch9Python.py", "max_forks_repo_name": "jgvfwstone/Regression", "max_forks_repo_head_hexsha": "483e8057f2cadcec43cf7475ef19a8f2113fed80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5, "max_line_length": 73, "alphanum_fraction": 0.5992467043, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877717925422, "lm_q2_score": 0.8872045981907006, "lm_q1q2_score": 0.8611986545418289}}
{"text": "import math\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import optimize\nfrom methods import *\nfrom pprint import pprint\n\n\ndef FirstDerivateSchwefelsFunction(x):\n    result = []\n\n    x_list = x.getA()[0]\n\n    for i in x_list:\n        result.append(-(math.sin(math.sqrt(abs(i))) + (i**2*math.cos(math.sqrt(abs(i)))) / (2 * math.sqrt(abs(i)**3))))\n\n    return np.matrix([[x] for x in result])\n\n\ndef SecondDerivateSchwefelsFunction(x):\n    x_list = x.getA()[0]\n\n    result = [[0 for i in range(len(x_list))] for j in range(len(x_list))]\n\n    for ind, i in enumerate(x_list):\n        result[ind][ind] = ((i*math.pow(abs(i), 7/2)*math.sin(math.sqrt(abs(i)))-3*i**3*abs(i)*math.cos(math.sqrt(abs(i)))) / (4*math.pow(abs(i), 9/2)))\n\n    return np.matrix(result)\n\n\n#-------F(x)--------------\ndef F(x):\n    result = 0\n\n    for i in x:\n        result += i * math.sin(math.sqrt(abs(i)))\n\n    return -result\n\n#--------For x_i <= 500 restrictions-------------\ndef g_i_1(x_i : float):\n    return x_i -500\n\ndef g_i_1_plus(x_i : float):\n    return max(0,x_i -500)\n#------For x_i>= -500 restrictions---------------\ndef g_i_2(x_i : float):\n    return -x_i-500\n\ndef g_i_2_plus(x_i : float):\n    return max(0,-x_i-500)\n\n#------Q(x,c)-for penalization method----------------\n\ndef Q(c):\n    def Q_call(x):\n        f_x_eval = F(x)\n    \n        g_i_1_sum = 0\n        for variable in x:\n            g_i_1_sum +=g_i_1_plus(variable)\n        \n        g_i_2_sum = 0\n        for variable in x:\n            g_i_2_sum +=g_i_2_plus(variable)\n        \n        return f_x_eval + c * g_i_1_sum + c * g_i_2_sum\n    \n    return Q_call\n\n#------R(x,miu)- for barrier method-------------------\ndef R(miu):\n    def R_call(x):\n        f_x_eval = F(x)\n        \n        g_i_1_sum = 0\n        for variable in x:\n            g_i_1_sum -=1/g_i_1(variable)\n        \n        g_i_2_sum = 0\n        for variable in x:\n            g_i_2_sum -=1/g_i_2(variable)\n        \n        return f_x_eval + miu * g_i_1_sum + miu * g_i_2_sum\n    \n    return R_call\n\n#------Omega( chequear si un vector x cumple con las restricciones)-------\ndef omega(x):\n    # print(x)\n    for element in x:\n        # print(element)\n        if element<-500 or element>500:\n            return False\n    return True\n\n\n\n\ndef plot():\n    x = np.arange(-500, 500, 0.1)\n    y = [F([i]) for i in x]\n\n    plt.plot(x, y)\n    plt.show()\n\n\n\n#testing-------------------\nif __name__ == '__main__':\n    # plot()\n\n    # ans = Penalization_method(\"BFGS\", Q, omega, x0=np.array([770,770]), c0=1, alpha=1.5, epsilon=0.001, k_max=500)\n    ans = Barrier_method(\"BFGS\", R, x0=np.array([430,430]), miu_0=1, alpha=0.5, epsilon=0.001, k_max=500)\n    # print(\"Penalization Method\")\n    # pprint(ans)\n    # print()\n    # print(\"Barrier Method\")\n    print(F(ans[\"1.Result\"]))\n    pprint(ans)\n    # print()\n    # print(\"SQP Method\")\n    # print(SQP_method(F, x0=np.array([380,380]), bounds=[(-500, 500), (-500, 500)], k_max=500))", "meta": {"hexsha": "9cfdd3c33ee2631515db11e92e1a77bfb03fd994", "size": 2943, "ext": "py", "lang": "Python", "max_stars_repo_path": "LAB4/ej_17.py", "max_stars_repo_name": "codersUP/MO-Labs", "max_stars_repo_head_hexsha": "1df2639e762893a6c5c64fdeece1940b8f0b24e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LAB4/ej_17.py", "max_issues_repo_name": "codersUP/MO-Labs", "max_issues_repo_head_hexsha": "1df2639e762893a6c5c64fdeece1940b8f0b24e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LAB4/ej_17.py", "max_forks_repo_name": "codersUP/MO-Labs", "max_forks_repo_head_hexsha": "1df2639e762893a6c5c64fdeece1940b8f0b24e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9268292683, "max_line_length": 152, "alphanum_fraction": 0.5545361876, "include": true, "reason": "import numpy,from scipy", "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877675527112, "lm_q2_score": 0.8872045952083047, "lm_q1q2_score": 0.8611986478852562}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 31 11:04:56 2019\n\n@author: fietekrutein\n\nA script to find a new direction of an equality constrained \nconvex optimization problem using pure Newton's method\n\"\"\"\n\nimport numpy as np\n\n# functions as of example problem\n\ndef exp1(x):\n    return(np.exp(x[0] + 3*x[1] + x[2] - 0.1))\n    \ndef exp2(x):\n    return (np.exp(x[0] - 3*x[1] + 2*x[2] - 0.1))\n\ndef exp3(x):\n    return (np.exp(-x[0] - x[1] - 2*x[2] - 0.1))\n    \ndef obj(x):\n    return (exp1(x) + exp2(x) + exp3(x))\n\ndef grad(x):\n    i1 = exp1(x) + exp2(x) - exp3(x)\n    i2 = 3*exp1(x) - 3*exp2(x) - exp3(x)\n    i3 = exp1(x) + 2*exp2(x) - 2*exp3(x)\n    return (np.array([i1,i2,i3]))\n\ndef hess(x):\n    i11 = exp1(x) + exp2(x) + exp3(x)\n    i12 = 3*exp1(x) -3*exp2(x) + exp3(x)\n    i13 = exp1(x) + 2*exp2(x) + 2*exp3(x)\n    \n    i21 = 3*exp1(x) - 3*exp2(x) + exp3(x)\n    i22 = 9*exp1(x) + 9*exp2(x) + exp3(x)\n    i23 = 3*exp1(x) - 6*exp2(x) + 2*exp3(x)\n    \n    i31 = exp1(x) + 2*exp2(x) + 2*exp3(x)\n    i32 = 3*exp1(x) - 6*exp2(x) + 2*exp3(x)\n    i33 = exp1(x) + 4*exp2(x) + 4*exp3(x)\n    \n    return (np.array([[i11,i12,i13],\n                      [i21,i22,i23],\n                      [i31,i32,i33]]))\n\n# new direction search formulation\n\ndef NewDir(x, A):\n    g = grad(x)\n    h = hess(x)\n    h_inv = np.linalg.inv(h)\n    d = -np.dot(h_inv, g) + np.dot(np.dot(np.dot(h_inv, A.T), \n                  np.linalg.inv(np.dot(A, np.dot(h_inv, A.T)))), np.dot(A, np.dot(h_inv, g)))\n    return (d)\n\n# initialize example\nA = np.array([[1,2,0],\n              [4,0,5]])\nx = np.array([1,1,2/5])\n\n# execute algorithm\nNewDir(x,A)\n\n# check null space / whether decent direction\nxnew = x + NewDir(x,A)\nd2 = NewDir(x,A)\nnspace_t = np.dot(A,d2)\nnp.dot(grad(x).T, d2)\n", "meta": {"hexsha": "143c0d5f64901491bd15a76981e18fd1354b071b", "size": 1769, "ext": "py", "lang": "Python", "max_stars_repo_path": "Convex_eq_constrained_direction_search_Pure_Newton.py", "max_stars_repo_name": "singfie/ConvexOptimizationMethods", "max_stars_repo_head_hexsha": "b4cf8c2f9f0d142907eec850a61622ebcaa9638a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-15T04:48:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T13:27:58.000Z", "max_issues_repo_path": "Convex_eq_constrained_direction_search_Pure_Newton.py", "max_issues_repo_name": "singfie/ConvexOptimizationMethods", "max_issues_repo_head_hexsha": "b4cf8c2f9f0d142907eec850a61622ebcaa9638a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Convex_eq_constrained_direction_search_Pure_Newton.py", "max_forks_repo_name": "singfie/ConvexOptimizationMethods", "max_forks_repo_head_hexsha": "b4cf8c2f9f0d142907eec850a61622ebcaa9638a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-02T05:04:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-02T05:04:46.000Z", "avg_line_length": 23.9054054054, "max_line_length": 93, "alphanum_fraction": 0.5330695308, "include": true, "reason": "import numpy", "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138131620184, "lm_q2_score": 0.8807970685907242, "lm_q1q2_score": 0.8611674605537648}}
{"text": "#Find Bell Numbers\n\ndef BellNumber(index): \n    bell=[[0 for i in range(index+1)] for j in range(index+1)] \n    bell[0][0] = 1\n    for i in range(1,index+1): \n        bell[i][0]=bell[i-1][i-1]\n        for j in range(1,i+1): \n            bell[i][j]=bell[i-1][j-1]+bell[i][j-1] \n    return bell[index][0]\n\ndef MPmath(index,dps=30):\n    import mpmath\n    mpmath.mp.dps = dps\n    return int(mpmath.bell(index))\n\ndef DobinskiFormula(n):\n    from math import e\n    from math import factorial\n    try:\n        return round((1/e) * sum([(k**(n))/(factorial(k)) for k in range(1,1000)]))\n    except:\n        return \"inf\"\n    \ndef doTest(toPrint=False,toProgress=False,start=0,toEnd=1000,algo=\"s\"):\n    s=set()\n    KK=10000\n    from IPython.display import clear_output\n    for i in range(start,toEnd+1):\n        if(toProgress and (i<KK or (i>=KK and i%(KK/100)==0))):\n            clear_output(wait=True)\n            print(i,end=\"\\t\")\n        if(algo==\"s\"):\n            bell=BellNumber(i)\n        elif(algo==\"mpmath\"):\n            bell=MPmath(i)\n        elif(algo==\"dobinski\"):\n            bell=DobinskiFormula(i)\n        if(bell):\n            s.add(bell)\n            if(toPrint and not toProgress):\n                print(bell,end=\", \")\n        if(toProgress and (i<KK or (i>=KK and i%(KK/100)==0))):\n            print(s)\n    if(not toPrint):\n        return s\n  \n#BellNumber(2000)\n#MPmath(2000)\n#DobinskiFormula(4)\n#doTest(False,False,1,500) #7.97s\n#doTest(False,False,1,500,\"dobinski\") #2.95s\n#doTest(False,False,1,500,\"mpmath\") #1.73s", "meta": {"hexsha": "3d262ee269ac2309413bb4d7b6f168d67f070497", "size": 1525, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Number Theory/BellNumber.py", "max_stars_repo_name": "lonagi/pysasha", "max_stars_repo_head_hexsha": "e344afa03357b7c626c949aa31fac51574e97f48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Number Theory/BellNumber.py", "max_issues_repo_name": "lonagi/pysasha", "max_issues_repo_head_hexsha": "e344afa03357b7c626c949aa31fac51574e97f48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Number Theory/BellNumber.py", "max_forks_repo_name": "lonagi/pysasha", "max_forks_repo_head_hexsha": "e344afa03357b7c626c949aa31fac51574e97f48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7735849057, "max_line_length": 83, "alphanum_fraction": 0.5613114754, "include": true, "reason": "import mpmath", "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.9046505312448598, "lm_q1q2_score": 0.8611035781524409}}
{"text": "import numpy as np\n\n\nclass LogisticRegression:\n\n    # Initialize with features and labels\n    def __init__(self, X, Y):\n        self.X = X\n        self.Y = Y\n        self.w = np.ones(X.shape[1])\n        self.N = X.shape[0]\n\n    # average cost function\n    # w is the weights\n    # X is the design matrix\n    # y is the labels\n    def cost(self):\n        z = np.dot(self.X, self.w)\n        J = np.mean(self.Y * np.log1p(np.exp(-z)) + (1 - self.Y) * np.log1p(np.exp(z)))\n        return J\n\n    # logistic function on x\n    def logistic(self, x):\n        return 1 / (1 + np.exp(-x))\n\n    # gradient of logistic regression\n    def gradient(self, regularization):\n\n        # Calculate y_hat based on logistic func\n        y_hat = self.logistic(np.dot(self.X, self.w))\n\n        # Gradient of logistic descent\n        gradient = np.dot(self.X.T, y_hat - self.Y) / self.N\n\n        # L2 regularization\n        gradient[1:] += regularization * self.w[1:]\n\n        return gradient\n\n    # lr is the learning rate\n    # epochs is the number of iterations\n    # w is the weights to be learned, default value is 0 array\n    # eps is the termination condition, when the norm of the gradient is less than the value\n    def fit(self, lr=0.5, epochs=10000, regularization=0, verbose=False, eps=1e-2):\n\n        # Iterate epochs times, performing gradient descent\n        for epoch in range(epochs):\n            gradient = self.gradient(regularization)\n\n            # go down the gradient with given learning rate\n            self.w -= lr * gradient\n\n            # print details about the training if needed\n            if verbose:\n                # every 1000 epochs, print the cost\n                if epoch % 1000 == 0:\n                    print('iter: ', epoch, ' cost: ', self.cost())\n\n            if eps != None and np.linalg.norm(gradient) < eps:\n                #print('Reached min cost.')\n                break\n\n        return self.cost()\n\n    # X is a feature instance, default decision boundary = 0.5\n    def predict(self, X, boundary=0.5):\n\n        return (self.logistic(np.dot(X, self.w)) > boundary).astype(int)\n", "meta": {"hexsha": "1989e9a8ee59bdaa76de2b4cb54f114988b578da", "size": 2103, "ext": "py", "lang": "Python", "max_stars_repo_path": "project1/models/logistic_regression.py", "max_stars_repo_name": "DiscoBroccoli/logistic-regression-and-naive-Bayes-from-Scratch", "max_stars_repo_head_hexsha": "bcb24a9258ea004a3694e6eaa524b499c2584f96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project1/models/logistic_regression.py", "max_issues_repo_name": "DiscoBroccoli/logistic-regression-and-naive-Bayes-from-Scratch", "max_issues_repo_head_hexsha": "bcb24a9258ea004a3694e6eaa524b499c2584f96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project1/models/logistic_regression.py", "max_forks_repo_name": "DiscoBroccoli/logistic-regression-and-naive-Bayes-from-Scratch", "max_forks_repo_head_hexsha": "bcb24a9258ea004a3694e6eaa524b499c2584f96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4782608696, "max_line_length": 92, "alphanum_fraction": 0.5829767, "include": true, "reason": "import numpy", "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.9046505280315008, "lm_q1q2_score": 0.8611035726231057}}
{"text": "import math as ma\nimport numpy as np\nfrom numba import jit\n\n\n@jit(nopython=True)\ndef binomialTree (r, sigma, S0, T, K, M, call = True, European = True):\n    \"\"\"Price a vanilla option using the Cox, Ross and Rubinstein binomial tree method, based\n    on the algorithm presented in the Computational Finance script at the University of Kiel.\n\n    Keyword arguments:\n    r -- risk free rate\n    sigma -- annual volatility\n    S0 -- initial stock price\n    T -- maturity of the option\n    K -- strike price of the option\n    call -- boolean value to differentiate between call and put options (default: call)\n    European -- boolean value to differentiate between European and American options (default: European)\n    M -- number of periods\n    \"\"\"\n\n    # step 1: calibrate the lattice and the risk neutral probability\n    dt = T/M\n    alpha = ma.exp(r*dt)\n    beta = (ma.pow(alpha,-1)+alpha*ma.exp((sigma**2)*dt))/2\n    u = beta + ma.sqrt(beta**2-1)\n    d = ma.pow(u,-1)\n    q = (ma.exp(r*dt)-d)/(u-d)\n\n\n    # step 2: build two empty lattices & initialize the first entry of the stock prices\n    stockPrice = np.empty((M,M))\n    stockPrice[0,0] = S0\n\n    optionPrice = np.empty((M,M))\n\n    \n    # step 3: fill the lattice up with all possible stock prize realizations\n    for i in range(M+1):\n        for j in range(i+1):\n            stockPrice[j,i] = S0 * u**j * d**(i-j)\n\n    \n    # step 4: compute the option value for every row in the last column\n    if call == True:\n        for j in range(M+1):\n            optionPrice[j,M] = max(0, stockPrice[j,M]-K)\n\n    else:\n        for j in range(M+1):\n            optionPrice[j,M] = max(0, K-stockPrice[j,M])\n    \n\n    # step 5: compute the option value backwardly\n    if European == True:\n        for i in reversed(range(M)):\n            optionPrice[j,i] = ma.exp(-r*dt)*(q*optionPrice[j+1,i+1]+(1-q)*optionPrice[j,i+1])\n\n    else:\n        if call == True:\n            optionPrice[j,i] = max(max(0,stockPrice[j,i]-K), ma.exp(-r*dt)*(q*optionPrice[j+1,i+1]+(1-q)*optionPrice[j,i+1]))\n        else:\n            max(max(0,K-stockPrice[j,i]), ma.exp(-r*dt)*(q*optionPrice[j+1,i+1]+(1-q)*optionPrice[j,i+1]))\n\n\n    # step 6: return the option value at time t=0\n    return optionPrice[0,0]\n\n\n\n\n    \n\n\n\n", "meta": {"hexsha": "24eb7cb2678bf8b4004aa7d504b7f355edf2e7d4", "size": 2240, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/binomialTree.py", "max_stars_repo_name": "marvinsohn/numericalOptionPricing", "max_stars_repo_head_hexsha": "f0479ff0921800b2dd095ee483c4a77e74f46423", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/binomialTree.py", "max_issues_repo_name": "marvinsohn/numericalOptionPricing", "max_issues_repo_head_hexsha": "f0479ff0921800b2dd095ee483c4a77e74f46423", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/binomialTree.py", "max_forks_repo_name": "marvinsohn/numericalOptionPricing", "max_forks_repo_head_hexsha": "f0479ff0921800b2dd095ee483c4a77e74f46423", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4736842105, "max_line_length": 125, "alphanum_fraction": 0.6111607143, "include": true, "reason": "import numpy,from numba", "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426435557124, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.8610919485835359}}
{"text": "# Plot polynomial regression on 1d problem\n# Based on https://github.com/probml/pmtk3/blob/master/demos/linregPolyVsDegree.m\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pyprobml_utils import save_fig\n\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import MinMaxScaler \nimport sklearn.metrics \nfrom sklearn.metrics import mean_squared_error as mse\n\ndef make_1dregression_data(n=21):\n    np.random.seed(0)\n    xtrain = np.linspace(0.0, 20, n)\n    xtest = np.arange(0.0, 20, 0.1)\n    sigma2 = 4\n    w = np.array([-1.5, 1/9.])\n    fun = lambda x: w[0]*x + w[1]*np.square(x)\n    ytrain = fun(xtrain) + np.random.normal(0, 1, xtrain.shape) * \\\n        np.sqrt(sigma2)\n    ytest= fun(xtest) + np.random.normal(0, 1, xtest.shape) * \\\n        np.sqrt(sigma2)\n    return xtrain, ytrain, xtest, ytest\n\nxtrain, ytrain, xtest, ytest = make_1dregression_data(n=21)\n\n#Rescaling data\nscaler = MinMaxScaler(feature_range=(-1, 1))\nXtrain = scaler.fit_transform(xtrain.reshape(-1, 1))\nXtest = scaler.transform(xtest.reshape(-1, 1))\n\n\ndegs = np.arange(1, 21, 1)\nndegs = np.max(degs)\nmse_train = np.empty(ndegs)\nmse_test = np.empty(ndegs)\nytest_pred_stored = np.empty(ndegs, dtype=np.ndarray)\nytrain_pred_stored = np.empty(ndegs, dtype=np.ndarray)\nfor deg in degs:\n    model = LinearRegression()\n    poly_features = PolynomialFeatures(degree=deg, include_bias=False)\n    Xtrain_poly = poly_features.fit_transform(Xtrain)\n    model.fit(Xtrain_poly, ytrain)\n    ytrain_pred = model.predict(Xtrain_poly)\n    ytrain_pred_stored[deg-1] = ytrain_pred\n    Xtest_poly = poly_features.transform(Xtest)\n    ytest_pred = model.predict(Xtest_poly)\n    mse_train[deg-1] = mse(ytrain_pred, ytrain) \n    mse_test[deg-1] = mse(ytest_pred, ytest)\n    ytest_pred_stored[deg-1] = ytest_pred\n    \n# Plot MSE vs degree\nfig, ax = plt.subplots()\nmask = degs <= 15\nax.plot(degs[mask], mse_test[mask], color = 'r', marker = 'x',label='test')\nax.plot(degs[mask], mse_train[mask], color='b', marker = 's', label='train')\nax.legend(loc='upper right', shadow=True)\nplt.xlabel('degree')\nplt.ylabel('mse')\nsave_fig('polyfitVsDegree.pdf')\nplt.show()\n\n# Plot fitted functions\nchosen_degs = [1, 2, 14, 20]\nfor deg in chosen_degs:\n    fig, ax = plt.subplots()\n    ax.scatter(xtrain, ytrain)\n    ax.plot(xtest, ytest_pred_stored[deg-1])\n    ax.set_ylim((-10, 15))\n    plt.title('degree {}'.format(deg))\n    save_fig('polyfitDegree{}.pdf'.format(deg))\n    plt.show()\n    \n# Plot residuals\n#https://blog.minitab.com/blog/adventures-in-statistics-2/why-you-need-to-check-your-residual-plots-for-regression-analysis\nchosen_degs = [1, 2, 14, 20]\nfor deg in chosen_degs:\n    fig, ax = plt.subplots()\n    ypred =  ytrain_pred_stored[deg-1]\n    residuals = ytrain - ypred\n    ax.plot(ypred, residuals, 'o')\n    ax.set_xlabel('predicted y')\n    ax.set_ylabel('residual')\n    plt.title('degree {}. Predictions on the training set'.format(deg))\n    save_fig('polyfitDegree{}Residuals.pdf'.format(deg))\n    plt.show()\n\n\n# Plot fit vs actual\n# https://blog.minitab.com/blog/adventures-in-statistics-2/regression-analysis-how-do-i-interpret-r-squared-and-assess-the-goodness-of-fit  \nchosen_degs = [1, 2, 14, 20]\nfor deg in chosen_degs:\n    for train in [True, False]:\n        if train:\n            ytrue = ytrain\n            ypred = ytrain_pred_stored[deg-1]\n            dataset = 'Train'\n        else:\n            ytrue = ytest\n            ypred = ytest_pred_stored[deg-1]\n            dataset = 'Test'\n        fig, ax = plt.subplots()\n        ax.scatter(ytrue, ypred)\n        ax.plot(ax.get_xlim(), ax.get_ylim(), ls=\"--\", c=\".3\")\n        ax.set_xlabel('true y')\n        ax.set_ylabel('predicted y')\n        r2 = sklearn.metrics.r2_score(ytrue, ypred)\n        plt.title('degree {}. R2 on {} = {:0.3f}'.format(deg, dataset, r2))\n        save_fig('polyfitDegree{}FitVsActual{}.pdf'.format(deg, dataset))\n        plt.show()", "meta": {"hexsha": "f71133f82623f384ba4feeea0b52c7871bf3ea83", "size": 3948, "ext": "py", "lang": "Python", "max_stars_repo_path": "book/linreg_poly_vs_degree.py", "max_stars_repo_name": "tywang89/pyprobml", "max_stars_repo_head_hexsha": "82cfdcb8daea653cda8f77e8737e585418476ca7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-07T12:40:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-07T12:40:01.000Z", "max_issues_repo_path": "book/linreg_poly_vs_degree.py", "max_issues_repo_name": "tywang89/pyprobml", "max_issues_repo_head_hexsha": "82cfdcb8daea653cda8f77e8737e585418476ca7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book/linreg_poly_vs_degree.py", "max_forks_repo_name": "tywang89/pyprobml", "max_forks_repo_head_hexsha": "82cfdcb8daea653cda8f77e8737e585418476ca7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9380530973, "max_line_length": 140, "alphanum_fraction": 0.6783181358, "include": true, "reason": "import numpy", "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750453562491, "lm_q2_score": 0.9032941995446778, "lm_q1q2_score": 0.8610878190409894}}
{"text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#calculate the Sum of Squared Error\ndef error(m, b, data):\n    sum_of_squares = 0\n    for i in range(len(data)):\n        x = data[i, 0]\n        y = data[i, 1]\n        sum_of_squares += (y-(m*x + b))**2\n    return sum_of_squares/len(data)\n\ndef gradient(m, b, data):\n    m_final = 0\n    b_final = 0\n    N = len(data)\n    for i in range(len(data)):\n        x = data[i, 0]\n        y = data[i, 1]\n        b_final += -(2/N)*(y-(m*x+b))\n        m_final += -(2/N)*x*(y-(m*x+b))\n    return m_final, b_final\n\n\ndef gradient_descent(m, b, iterations, learning_rate, data):\n    for i in range(iterations):\n        m_final, b_final = gradient(m, b, data)\n        m = m - (learning_rate*m_final)\n        b = b - (learning_rate*b_final)\n    return m, b\n\n\ndef start():\n    pdata = pd.read_csv(\"../datasets/lactic.csv\", usecols=['X', 'Y'])\n    pdata = np.array(pdata)\n\n    #learning conditions\n    learning_rate = 0.001\n    iterations = 1000\n\n    #equation mx + b\n    m0 = 0            #initial values of coefficients\n    b0 = 0\n\n    input_val = []\n    output_val = []\n    for i in range(len(pdata)):\n        input_val.append(pdata[i,0])\n        output_val.append(pdata[i,1])\n\n\n    print(\"Initial value of coefficients y=mx+b:\\n \"\n          \"m = {0} b = {1} and error is {2} \\n\".format(m0, b0, error(m0, b0, pdata)))\n\n    print(\"Gradient descent...\\n\")\n    m, b = gradient_descent(m0, b0, iterations, learning_rate, pdata)\n\n    print(\"Final value of coefficients y=mx+b:\\n \"\n          \"m = {0} b = {1} and error is {2}\".format(m, b, error(m, b, pdata)))\n\n\n    #not the best way to represent fit line\n    #representation of linear regression results\n    y_vals = [m*x+b for x in range(20)]\n    x_vals = range(20)\n\n    plt.scatter(input_val, output_val)\n    plt.xlabel(\"Input\")\n    plt.ylabel(\"Output\")\n    plt.plot(x_vals, y_vals,color='blue', linewidth = 3)\n    plt.show()\n\n\n\nif __name__ == '__main__':\n    start()\n", "meta": {"hexsha": "22e0a0f1f2e9c6ad4f685de9603e88f6529f149a", "size": 1969, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine-learning-algorithms/linear-regression-2_0.py", "max_stars_repo_name": "zelzhan/Linear-algebra-with-python", "max_stars_repo_head_hexsha": "a58042c9f29f67aafcd2c1c4c1300a0e9223a650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "machine-learning-algorithms/linear-regression-2_0.py", "max_issues_repo_name": "zelzhan/Linear-algebra-with-python", "max_issues_repo_head_hexsha": "a58042c9f29f67aafcd2c1c4c1300a0e9223a650", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "machine-learning-algorithms/linear-regression-2_0.py", "max_forks_repo_name": "zelzhan/Linear-algebra-with-python", "max_forks_repo_head_hexsha": "a58042c9f29f67aafcd2c1c4c1300a0e9223a650", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2435897436, "max_line_length": 85, "alphanum_fraction": 0.5850685627, "include": true, "reason": "import numpy", "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561667674652, "lm_q2_score": 0.8887588045416601, "lm_q1q2_score": 0.8610794485490677}}
{"text": "from numpy import array, zeros, float, dot\nfrom copy import copy\n\ndef GaussJordan(A,b):\n\n    n,m = A.shape\n    C = zeros((n,m+1),float)\n    C[:,0:n],C[:,n] = A, b\n\n    for j in range(n):\n        # partial pivoting.\n        p = j\n        # look for alternate pivot by searching for largest element in column\n        for i in range(j+1,n):\n            if abs(C[i,j]) > abs(C[p,j]): p = i\n        if abs(C[p,j]) < 1.0e-16:\n            print \"matrix is singular\" # its determinant is 0.\n            return b\n        # swap rows to get largest magnitude element on the diagonal\n        C[p,:],C[j,:] = copy(C[j,:]),copy(C[p,:])\n\n        pivot = C[j,j]\n        C[j,:] = C[j,:] / pivot\n        for i in range(n):\n            if i == j: continue\n            C[i,:] = C[i,:] - C[i,j]*C[j,:]\n    I,x = C[:,0:n],C[:,n]\n    return x\n\n", "meta": {"hexsha": "9d83060a8425abc961119bc58f547d2e85d540e7", "size": 822, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assingment #1/GJ-1/algorithm.py", "max_stars_repo_name": "rezaghanbari/Numerical-Linear-algebra-Assignment-1", "max_stars_repo_head_hexsha": "014619a057d7371177a6ac6b33e20fe06adbe8b4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assingment #1/GJ-1/algorithm.py", "max_issues_repo_name": "rezaghanbari/Numerical-Linear-algebra-Assignment-1", "max_issues_repo_head_hexsha": "014619a057d7371177a6ac6b33e20fe06adbe8b4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assingment #1/GJ-1/algorithm.py", "max_forks_repo_name": "rezaghanbari/Numerical-Linear-algebra-Assignment-1", "max_forks_repo_head_hexsha": "014619a057d7371177a6ac6b33e20fe06adbe8b4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4, "max_line_length": 77, "alphanum_fraction": 0.4854014599, "include": true, "reason": "from numpy", "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561667674651, "lm_q2_score": 0.8887587993853654, "lm_q1q2_score": 0.8610794435533596}}
{"text": "from sympy import ( symbols, solve, diff, integrate, exp, sqrt, lambdify, Integral, ln, pprint, oo )\n\n# The clotting time of blood​ (in seconds) is a random variable with probability density function defined by\n\nx = symbols( 'x' )\nF = 1 / ( ln( 27 ) * x )\n\n# for x in ​[1, 27​].\n\na, b = 1, 27\n\ndef expected_value( f, var, a, b ):\n\treturn integrate( var * f, ( var, a, b ) )\n\ndef variance( f, var, a, b, mu ):\n\treturn integrate( ( ( var **2 ) * f ), ( var, a, b ) ) - mu**2\n\ndef std_dev( var ):\n\treturn sqrt( var )\n\ndef expected_value( f, var, a, b ):\n\treturn integrate( var * f, ( var, a, b ) )\n\nmu = round( expected_value( F, x, a, b ).evalf(), 2 )\nmu\n\n# Find the standard deviation of the distribution.\nvar = round( variance( F, x, a, b, mu ).evalf(), 2 )\nvar\n\nstdev = round( std_dev( var ), 2 )\nstdev\n\n# ind the probability that the value of the random variable is within one standard deviation of the mean.\nprob_within_1sd = integrate( F, ( x, mu - stdev, mu + stdev ) )\nround( prob_within_1sd.evalf(), 2 )\n\n# Find the median clotting time.\nmean = exp( ( ln( 27 ) /2 ).evalf() )\nround( mean, 2 )", "meta": {"hexsha": "8913f31a30299d25e75603ff4c84fad2a7be3fe6", "size": 1099, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Module 9/blood_clotting.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Module 9/blood_clotting.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Module 9/blood_clotting.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.475, "max_line_length": 108, "alphanum_fraction": 0.6287534122, "include": true, "reason": "from sympy", "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561676667174, "lm_q2_score": 0.8887587957022977, "lm_q1q2_score": 0.8610794407842152}}
{"text": "\"\"\"\n Purpose: The main purpose is to demonstrate how to find the running median, mode and \n          mean over a sequence (list) of integers or reals or a mix of integers and reals.\n          The secondary purpose, is to inspire Python programmers to explore some of\n          the powerful packages (e.g. collections) available to the Python community and \n          to learn more about list comprehension and lambda functions.\n    Note:        \n       1. Much of the code here has been taken from code posted to the web (e.g. stackoverflow)\n          by other Python programmers (e.g. Peter Otten)\n\n  Author: V. Stokes (vs@it.uu.se)  \n Version: 2013.03.06\n\n\"\"\"\nimport numpy as np\n\n#*******************************************************\n\nfrom collections import deque,Counter\nfrom bisect import insort, bisect_left\nfrom itertools import islice\n\ndef RunningMode(seq,N,M):\n    \"\"\"\n    Purpose: Find the mode for the points in a sliding window as it \n             is moved from left (beginning of seq) to right (end of seq)\n             by one point at a time.\n     Inputs:\n          seq -- list containing items for which a running mode (in a sliding window) is \n                 to be calculated\n            N -- length of sequence                      \n            M -- number of items in window (window size) -- must be an integer > 1\n     Otputs:\n        modes -- list of modes with size M - N + 1\n       Note:\n         1. The mode is the value that appears most often in a set of data.\n         2. In the case of ties it the last of the ties that is taken as the mode (this\n            is not by definition).\n    \"\"\"    \n    # Load deque with first window of seq \n    d = deque(seq[0:M]) \n\n    modes = [Counter(d).most_common(1)[0][0]]  # contains mode of first window\n\n    # Now slide the window by one point to the right for each new position (each pass through \n    # the loop). Stop when the item in the right end of the deque contains the last item in seq\n    for item in islice(seq,M,N):\n        old = d.popleft()                      # pop oldest from left\n        d.append(item)                         # push newest in from right\n        modes.append(Counter(d).most_common(1)[0][0])        \n    return modes    \n\ndef RunningMedian(seq, M):\n    \"\"\"\n     Purpose: Find the median for the points in a sliding window (odd number in size) \n              as it is moved from left to right by one point at a time.\n      Inputs:\n            seq -- list containing items for which a running median (in a sliding window) \n                   is to be calculated\n              M -- number of items in window (window size) -- must be an integer > 1\n      Otputs:\n         medians -- list of medians with size N - M + 1\n       Note:\n         1. The median of a finite list of numbers is the \"center\" value when this list\n            is sorted in ascending order. \n         2. If M is an even number the two elements in the window that\n            are close to the center are averaged to give the median (this\n            is not by definition)\n    \"\"\"   \n    seq = iter(seq)\n    s = []   \n    m = M // 2\n\n    # Set up list s (to be sorted) and load deque with first window of seq\n    s = [item for item in islice(seq,M)]    \n    d = deque(s)\n\n    # Simple lambda function to handle even/odd window sizes    \n    median = lambda : s[m] if bool(M&1) else (s[m-1]+s[m])*0.5\n\n    # Sort it in increasing order and extract the median (\"center\" of the sorted window)\n    s.sort()    \n    medians = [median()]   \n\n    # Now slide the window by one point to the right for each new position (each pass through \n    # the loop). Stop when the item in the right end of the deque contains the last item in seq\n    for item in seq:\n        old = d.popleft()          # pop oldest from left\n        d.append(item)             # push newest in from right\n        del s[bisect_left(s, old)] # locate insertion point and then remove old \n        insort(s, item)            # insert newest such that new sort is not required        \n        medians.append(median())  \n    return medians\n\ndef RunningMean(seq,N,M):\n    \"\"\"\n     Purpose: Find the mean for the points in a sliding window (fixed size) \n              as it is moved from left to right by one point at a time.\n      Inputs:\n          seq -- list containing items for which a mean (in a sliding window) is \n                 to be calculated (N items)\n            N -- length of sequence     \n            M -- number of items in sliding window\n      Otputs:\n        means -- list of means with size N - M + 1    \n\n    \"\"\"    \n    # Load deque (d) with first window of seq\n    d = deque(seq[0:M])\n    means = [np.mean(d)]             # contains mean of first window\n    # Now slide the window by one point to the right for each new position (each pass through \n    # the loop). Stop when the item in the right end of the deque contains the last item in seq\n    for item in islice(seq,M,N):\n        old = d.popleft()            # pop oldest from left\n        d.append(item)               # push newest in from right\n        means.append(np.mean(d))     # mean for current window\n    return means  \n\n#*** Start of test area *****************************************************\n#\n# Set random seed for repeatability\n#np.random.seed(7919) # the 1000th prime number\n\n# Try the following sequences\n#yn = np.random.random(18)*10 - 5\nyn = [3,2,-1.0,2.0,3.0,5.0,-5.0,6.0,-5.0,4.0,9.0,6.3,1.3,0.0,-7.0,1.3,-5.0]\n#yn = [3,2,-1.0,-1.0,-1.0,5.0,5.0]\n#yn = [5,5.0,5,5.0,5]\n#yn = [3,3,3,3,3,3,3]\n#yn = [3.,3.,3.,3.,3.,3.,3.]\n#yn = [-1,1,-1,1,-1,1]\n#yn = [3,2,-1.0,2.0]\n#yn = [5,3,2,2,-1]\n#yn = [-5.0,3.0,2.0,2.0,-1.0]\n\nN = len(yn)\n\n# Try the follwing window sizes\n#M = 1\n#M = 2\nM = 3\n#M = 4\n#M = 5\n#M = 6\nif M <= N and M >= 1:\n    print 'M = %2d,'%M,\n    print 'yn:'\n    print yn\n\n    means = RunningMean(yn,N,M)\n    print ' Means(%d):' %(N-M+1)\n    print means\n\n    medians = RunningMedian(yn,M)\n    print ' Medians(%d):' %(N-M+1)\n    print medians\n\n    modes = RunningMode(yn,N,M)\n    print ' Modes(%d):' %(N-M+1)\n    print modes\nelse:\n    print 'Window size (M=%d) out of range'%M\n", "meta": {"hexsha": "961a7fa0b44e4e262ad615ab4d079dce99b05ef6", "size": 6110, "ext": "py", "lang": "Python", "max_stars_repo_path": "recipes/Python/578480_Running_median_mean_and_mode/recipe-578480.py", "max_stars_repo_name": "tdiprima/code", "max_stars_repo_head_hexsha": "61a74f5f93da087d27c70b2efe779ac6bd2a3b4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2023, "max_stars_repo_stars_event_min_datetime": "2017-07-29T09:34:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T08:00:45.000Z", "max_issues_repo_path": "recipes/Python/578480_Running_median_mean_and_mode/recipe-578480.py", "max_issues_repo_name": "unhacker/code", "max_issues_repo_head_hexsha": "73b09edc1b9850c557a79296655f140ce5e853db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2017-09-02T17:20:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T17:49:37.000Z", "max_forks_repo_path": "recipes/Python/578480_Running_median_mean_and_mode/recipe-578480.py", "max_forks_repo_name": "unhacker/code", "max_forks_repo_head_hexsha": "73b09edc1b9850c557a79296655f140ce5e853db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 780, "max_forks_repo_forks_event_min_datetime": "2017-07-28T19:23:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T20:39:41.000Z", "avg_line_length": 37.4846625767, "max_line_length": 95, "alphanum_fraction": 0.5813420622, "include": true, "reason": "import numpy", "num_tokens": 1668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.9161096204605946, "lm_q1q2_score": 0.8610636606330105}}
{"text": "\"\"\"\nAuthor: Ali Hajimirza (ali@alihm.net)\nCopyright Ali Hajimirza, free for use under MIT license.\n\"\"\"\nimport numpy as np\n\n# Exponent function for estimating e\nexponent_func = np.vectorize(lambda x, std: np.exp((-1.0*x)/(2 * std)))\n\n# Performs the E step give a list of x values, a list of means and a matrix of estimated values \ndef E_step(x_list, mean_list, e_matrix):\n\t# Compute the standard deviation\n\tstd_list = get_std(x_list, mean_list, e_matrix)\n\testimated = list()\n\tfor i,std in enumerate(std_list):\n\t\testimated.append(exponent_func(np.square(x_list - mean_list[i]), std))\n\t# Calculating denominator\n\testimated = np.array(estimated).transpose()\n\tfor i, n in enumerate(estimated):\n\t\testimated[i] /= n.sum()\n\treturn estimated\n\n# Performs the M step give a list of x values, a list of means\ndef M_step(x_list, e_matrix):\n\t# Calculating numerator\n\tnumerator = np.dot(x_list, e_matrix)\n\t# Calculating denominator\n\tdenominator = e_matrix.sum(axis=0)\n\treturn np.divide(numerator, denominator)\n\n# Compute the standard deviation\ndef get_std(x_list, mean_list, e_matrix):\n\tx_vector = x_list[np.newaxis].transpose()\n\tvar = np.square(mean_list - x_vector) * e_matrix\n\treturn np.sqrt(var.sum(axis=0)/e_matrix.sum(axis=0))\n\n# Computes theta\ndef get_theta(e_matrix):\n\treturn e_matrix.sum(axis=0) / len(e_matrix)\n\n# Performs E-M for a number of steps\ndef simulate_E_M(x_list, e_matrix ,steps):\n\tmean_matrix = list()\n\tfor i in xrange(steps):\n\t\tmean_list = M_step(x_list, e_matrix)\n\t\tmean_matrix.append(mean_list)\n\t\te_matrix  = E_step(x_list, mean_list, e_matrix)\n\treturn np.array(mean_matrix).transpose()", "meta": {"hexsha": "61024c0f3abe021bbbbc16963c2f547671f3985d", "size": 1596, "ext": "py", "lang": "Python", "max_stars_repo_path": "algorithm/EM.py", "max_stars_repo_name": "Ali92hm/expectation-maximization", "max_stars_repo_head_hexsha": "5f64bd1d2f344544f77dcc65939919f34f3dd850", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-09-12T23:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T07:28:53.000Z", "max_issues_repo_path": "algorithm/EM.py", "max_issues_repo_name": "huanghesheng2012/expectation-maximization", "max_issues_repo_head_hexsha": "ba6586fdd5d6fe9d9eb8c907ca94a5b2f1c079db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorithm/EM.py", "max_forks_repo_name": "huanghesheng2012/expectation-maximization", "max_forks_repo_head_hexsha": "ba6586fdd5d6fe9d9eb8c907ca94a5b2f1c079db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2018-01-02T10:42:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-06T18:07:09.000Z", "avg_line_length": 33.25, "max_line_length": 96, "alphanum_fraction": 0.7462406015, "include": true, "reason": "import numpy", "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109756113862, "lm_q2_score": 0.9059898146721821, "lm_q1q2_score": 0.8610626636565676}}
{"text": "# Disable debbuging logs (to get rid of cuda warnings)\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nimport numpy as np\n\n'''\nUsing the convolution operation between two arrays.\nCheck: the equation of convultion\n'''\n# h = [2, 1, 0]\n# x = [3, 4, 5]\n\n# y = np.convolve(x, h)\n# print(y); # [6, 11, 14, 5, 0]\n\n'''\nNow we will experimante with methods of applying a kernel on the matrix.\n'''\n\n# 1) Padding(full) method\n\n'''\nThink of the kernel as a sliding window.\nWe have to come with the solution of padding zeros\non the input array. This is a very famous implementation and\nwill be easier to show how it works with a simple example\n'''\n\n# import numpy as np\n\n# x = [6, 2]\n# h = [1, 2, 5, 4]\n\n# y = np.convolve(x, h, \"full\")  #now, because of the zero padding, the final dimension of the array is bigger\n# print(y) # 6 14 34 34 8\n\n# 2) Padding (same)\n\n'''\nIn this approach, we just add the zero to the left (and top of the matrix in 2D).\nThat is, only the first 4 steps of \"full\" method.\n'''\n\nimport numpy as np\n\n# x = [6, 2]\n# h = [1, 2, 5, 4]\n\n# y = np.convolve(x, h, \"same\")  # it is same as zero padding, but with returns an ouput with the same length as max of x or h\n# print(y) # 6 14 34 34\n\n# 3) No padding (valid)\n\n'''\nIn the last case we only applied the kernel when we had\na comptaible position on the h array, in some cases you\nwant a dimensionality reduction. For this purpose, we ignore the\nsteps that would need padding (zeros before and after the array)\n'''\n\nx = [6, 2]\nh = [1, 2, 5, 4]\n\ny = np.convolve(x, h, \"valid\")\nprint(y) # 14 34 34\n\n'''\nValid returns output of length max(x, h) - min(x, h) + 1\nThis is to ensure that values outside of the boundary of 'h'\nwill not be used in the calculation of the convultion.\nIn the next example we will understand why we used the argument valid. \n'''\n\n", "meta": {"hexsha": "e874e98c28b6b17d6bb48cb5953dfb343e841b2a", "size": 1811, "ext": "py", "lang": "Python", "max_stars_repo_path": "3.Understanding Convolutions/0_1D.py", "max_stars_repo_name": "OwenGranot/Deep-Learning", "max_stars_repo_head_hexsha": "436cc00783c7aeef527f1f06b6550e6d0ab944e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3.Understanding Convolutions/0_1D.py", "max_issues_repo_name": "OwenGranot/Deep-Learning", "max_issues_repo_head_hexsha": "436cc00783c7aeef527f1f06b6550e6d0ab944e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.Understanding Convolutions/0_1D.py", "max_forks_repo_name": "OwenGranot/Deep-Learning", "max_forks_repo_head_hexsha": "436cc00783c7aeef527f1f06b6550e6d0ab944e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1466666667, "max_line_length": 126, "alphanum_fraction": 0.6753175041, "include": true, "reason": "import numpy", "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083139, "lm_q2_score": 0.9111797057909279, "lm_q1q2_score": 0.8610600005637071}}
{"text": "import numpy as np\nfrom checker.fault import get_fault\n\nnp.set_printoptions(suppress=True)\n\n\ndef seidel(matrix_a: list, vector_b: list, vector_x: list) -> list:\n    \"\"\"\n    Seidel algorithm part\n    :param matrix_a: start matrix\n    :param vector_b: start vector\n    :param vector_x: solution vector\n    :return:\n    \"\"\"\n    x_ = vector_x.copy()\n    n = len(matrix_a)\n    for j in range(0, n):\n        d = vector_b[j]\n\n        for i in range(0, n):\n            if j != i:\n                d -= matrix_a[j][i] * x_[i]\n        x_[j] = d / matrix_a[j][j]\n    return x_\n\n\ndef solve(matrix_a: list, vector_b: list, vector_x: list, eps=10 ** (-6)) -> list:\n    \"\"\"\n    Main function\n    :param matrix_a: start matrix\n    :param vector_b: start vector\n    :param vector_x: solution vector\n    :param eps: epsilon for comparing\n    :return:\n    \"\"\"\n    iterations = 0\n    tmp = 0\n    while True:\n        errors = []\n        new_x = seidel(matrix_a, vector_b, vector_x)\n        for i in range(len(vector_x)):\n            errors.append(abs(new_x[i] - vector_x[i]))\n        vector_x = new_x\n        if max(errors) < eps:\n            print(f'Last result: {vector_x}')\n            break\n        else:\n            if tmp < 3:\n                print(f'Temporary result: {vector_x}')\n                tmp += 1\n            print(f'Residual vector: {np.matrix(np.subtract(vector_b, np.dot(matrix_a, vector_x)), float)}')\n            iterations += 1\n    print(f'Iterations: {iterations}')\n    return vector_x\n\n\na = [[4.4944, 0.1764, 1.7956, 0.7744],\n     [0.1764, 15.6025, 3.4969, 0.1849],\n     [1.7956, 3.4969, 8.8804, 0.2116],\n     [0.7744, 0.1849, 0.2116, 19.7136]]\nb = [31.97212, 9.18339, 19.51289, 51.39451]\nx = [0 for _ in range(len(a[0]))]\nx = solve(a.copy(), b.copy(), x.copy())\nprint(f'Our solution: {x}')\nx_np = np.linalg.solve(a, b)\nprint(f'NumPy solution: {x_np}')\nprint(f'Residual vector: {np.matrix(np.subtract(b, np.dot(a, x)), int)}')\nprint(f'Residual vector for NumPy: {np.matrix(np.subtract(b, np.dot(a, x_np)), int)}')\nprint('Fault:', round(get_fault(x, x_np), 6))\n", "meta": {"hexsha": "fa0abb1d705367f711c0a220d44c98132d96aea2", "size": 2062, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab3/seidel.py", "max_stars_repo_name": "mezgoodle/numericalMethods_labs", "max_stars_repo_head_hexsha": "1631b50ae32ff1a81d63a2216a8015df4e2abb84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-02T11:24:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T11:24:46.000Z", "max_issues_repo_path": "Lab3/seidel.py", "max_issues_repo_name": "mezgoodle/numericalMethods_labs", "max_issues_repo_head_hexsha": "1631b50ae32ff1a81d63a2216a8015df4e2abb84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab3/seidel.py", "max_forks_repo_name": "mezgoodle/numericalMethods_labs", "max_forks_repo_head_hexsha": "1631b50ae32ff1a81d63a2216a8015df4e2abb84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4571428571, "max_line_length": 108, "alphanum_fraction": 0.5766246363, "include": true, "reason": "import numpy", "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.9111796979521252, "lm_q1q2_score": 0.861059997390649}}
{"text": "# calculate error\r\nimport numpy as np\r\n\r\n\r\n# mean square error\r\ndef mean_square_error(pred, target):\r\n    \"\"\"\r\n    Determine mean square error.\r\n    f(y_t, y) = sum((y_t-y)**2)/n\r\n        where, y_t = predicted value\r\n                y  = target value\r\n                n = number of values\r\n\r\n    :param pred: {array}, shape(n_samples,)\r\n            predicted values.\r\n    :param target: {array}, shape(n_samples,)\r\n            target values.\r\n    :return: mean square error.\r\n    \"\"\"\r\n    error = pred - target\r\n    square_error = error * error\r\n    return np.mean(square_error)\r\n\r\n\r\n# mean absolute error\r\ndef mean_absolute_error(pred, target):\r\n    \"\"\"\r\n    Determine mean absolute error.\r\n    f(y_t, y) = sum(abs(y_t-y))/n\r\n        where, y_t = predicted value\r\n                y  = target value\r\n                n = number of values\r\n\r\n    :param pred: {array}, shape(n_samples,)\r\n            predicted values.\r\n    :param target: {array}, shape(n_samples,)\r\n            target values.\r\n    :return: mean absolute error.\r\n    \"\"\"\r\n    abs_error = np.abs(pred - target)\r\n    return np.mean(abs_error)\r\n\r\n\r\n# mean log cosh error\r\ndef mean_log_cosh_error(pred, target):\r\n    \"\"\"\r\n    Determine mean log cosh error.\r\n    f(y_t, y) = sum(log(cosh(y_t-y)))/n\r\n        where, y_t = predicted value\r\n                y  = target value\r\n                n = number of values\r\n\r\n    :param pred: {array}, shape(n_samples,)\r\n            predicted values.\r\n    :param target: {array}, shape(n_samples,)\r\n            target values.\r\n    :return: mean log cosh error.\r\n    \"\"\"\r\n    error = pred - target\r\n    return np.mean(np.log(np.cosh(error)))\r\n\r\n\r\n# log loss function\r\ndef log_loss(pred, target):\r\n    \"\"\"\r\n    Determine mean log loss function.\r\n    :param pred: {array}, shape{n_samples,}\r\n            predicted values.\r\n    :param target: {array}, shape{n_samples,}\r\n            target values.\r\n    :return: mean log loss error.\r\n    \"\"\"\r\n    pred[pred == 0] = 0.00001\r\n    pred[pred == 1] = 0.99999\r\n    return -np.mean((target*np.log(pred) + (1-target)*np.log(1-pred)))\r\n\r\n\r\nerrors = {\"mean_square_error\": mean_square_error, \"mean_absolute_error\": mean_absolute_error,\r\n          \"mean_log_cosh_error\": mean_log_cosh_error, \"log_loss\": log_loss}\r\n", "meta": {"hexsha": "b830a7f2bc7ad6dfd4dad9453c7d3dc69a51b42e", "size": 2245, "ext": "py", "lang": "Python", "max_stars_repo_path": "ERROR.py", "max_stars_repo_name": "Snorlexing/Genetic-Algorithms-based-Neural-Network-hybrid-", "max_stars_repo_head_hexsha": "0d537574a1f6fe1058af31446c9a2d5454a55247", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-29T05:14:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-10T17:34:59.000Z", "max_issues_repo_path": "ERROR.py", "max_issues_repo_name": "Snorlexing/Genetic-Algorithms-based-Neural-Network-hybrid-", "max_issues_repo_head_hexsha": "0d537574a1f6fe1058af31446c9a2d5454a55247", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ERROR.py", "max_forks_repo_name": "Snorlexing/Genetic-Algorithms-based-Neural-Network-hybrid-", "max_forks_repo_head_hexsha": "0d537574a1f6fe1058af31446c9a2d5454a55247", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0625, "max_line_length": 94, "alphanum_fraction": 0.574610245, "include": true, "reason": "import numpy", "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542805873231, "lm_q2_score": 0.8976952900545975, "lm_q1q2_score": 0.8610282801189458}}
{"text": "import numpy as np\nimport scipy.stats as sp\n\n\ndef cosd(angle):\n    \n    return np.cos(np.pi * angle/180)\n\n\ndef sind(angle):\n    \n    return np.sin(np.pi * angle/180)\n\n\ndef tand(angle):\n    \n    return np.tan(np.pi * angle/180)\n\n\ndef arctand(angle):\n    \n    return np.arctan(angle) * 180/np.pi\n\n\ndef cart2pol(x, y):\n    \n    rho = np.sqrt(x**2 + y**2)\n    phi = np.arctan2(y, x)\n    \n    return phi, rho\n\n\ndef pol2cart(phi, rho):\n    \n    x = rho * np.cos(phi)\n    y = rho * np.sin(phi)\n    \n    return x, y\n\n\ndef iqr(data):\n    \"\"\"This function computes the iqr consistent with Matlab\"\"\"\n\n    # If 2-D array use only 1st row\n    if len(data.shape) > 1:\n        data_1d = data.flatten()\n    else:\n        data_1d = data\n\n    # Remove nan elements\n    idx = np.where(np.isnan(data_1d) == False)[0]\n    data_1d = data_1d[idx]\n\n    # Compute statistics\n    q25, q50, q75 = sp.mstats.mquantiles(data_1d, alphap=0.5, betap=0.5)\n    sp_iqr = q75 - q25\n    return sp_iqr\n\n\ndef azdeg2rad(angle):\n    direction = np.deg2rad(90-angle)\n    idx = np.where(direction < 0)[0]\n    if len(idx) > 0:\n        direction[idx] = direction[idx] + 2 * np.pi\n        \n    return direction\n\n\ndef rad2azdeg(angle):\n    if isinstance(angle, float):\n        deg = np.rad2deg(angle)\n        deg = 90 - deg\n        if deg < 0:\n            deg += 360\n            \n        return deg\n    else:\n        # Multiple values\n        deg = np.rad2deg(angle)\n        deg = 90 - deg\n        sub_zero = np.where(deg < 0)\n        deg[sub_zero] = deg[sub_zero] + 360\n        \n        return deg\n\n\ndef nandiff(values):\n    \n    final_values = []\n    for n in range(len(values) - 1):\n        \n        if np.isnan(values[n]):\n            final_values.append(np.nan)\n        else:\n            i = n + 1\n            while np.isnan(values[i]) and i < len(values) - 1:\n                i += 1\n            \n            final_values.append(values[i] - values[n])\n        \n    return np.array(final_values)\n\n\ndef get_object_values(list_in, item, checked=None):\n    if checked is not None:\n        working_list = list_in[checked is True]\n    else:\n        working_list = list_in\n\n    if working_list is list:\n        out = []\n        for obj in working_list:\n            temp = getattr(obj, item)\n            out.append(temp)\n    else:\n        out = getattr(working_list, item)\n    return np.array(out)\n\n\ndef sontek_3d_arrange(data_in):\n    r1 = np.squeeze(data_in[:, 0, :])\n    r2 = np.squeeze(data_in[:, 1, :])\n    r3 = np.squeeze(data_in[:, 2, :])\n    r4 = np.squeeze(data_in[:, 3, :])\n    new_array = np.array([r1, r2, r3, r4])\n    return new_array\n\n\ndef valid_number(data_in):\n    \"\"\"Check to see if data_in can be converted to float.\n\n    Parameters\n    ----------\n    data_in: str\n        String to be converted to float\n\n    Returns\n    -------\n    data_out: float\n        Returns a float of data_in or nan if conversion is not possible\n    \"\"\"\n\n    try:\n        data_out = float(data_in)\n    except ValueError:\n        data_out = np.nan\n    return data_out\n\n\ndef nans(shape, dtype=float):\n    a = np.empty(shape, dtype)\n    a.fill(np.nan)\n    return a\n", "meta": {"hexsha": "3cf028aeb78c643268f04f28184d6a5038c4ec72", "size": 3106, "ext": "py", "lang": "Python", "max_stars_repo_path": "MiscLibs/common_functions.py", "max_stars_repo_name": "usgsdsm/qrevpy", "max_stars_repo_head_hexsha": "e9f1586aa5ace81d4dc76134bacdd08e3007b82a", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MiscLibs/common_functions.py", "max_issues_repo_name": "usgsdsm/qrevpy", "max_issues_repo_head_hexsha": "e9f1586aa5ace81d4dc76134bacdd08e3007b82a", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MiscLibs/common_functions.py", "max_forks_repo_name": "usgsdsm/qrevpy", "max_forks_repo_head_hexsha": "e9f1586aa5ace81d4dc76134bacdd08e3007b82a", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1688311688, "max_line_length": 72, "alphanum_fraction": 0.5556986478, "include": true, "reason": "import numpy,import scipy", "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650673, "lm_q2_score": 0.9019206864156892, "lm_q1q2_score": 0.8610162535039061}}
{"text": "import numpy as np\n\n# Entropy and Gini Calculations\ndef entropy(y_labels):\n    _, fraud_count = np.unique(y_labels, return_counts=True)\n    p_i = fraud_count / fraud_count.sum() # probability (array) of each class\n    entropy = np.sum(p_i * -np.log2(p_i))\n    return entropy\n\ndef gini(y_labels):\n    _, fraud_count = np.unique(y_labels, return_counts=True)\n    p_i = fraud_count / fraud_count.sum() # probability (array) of each class\n    gini = 1 - np.sum(p_i**2)\n    return gini\n    \ndef total_entropy(partition_0, partition_1):\n    n = len(partition_0) + len(partition_1)\n    prob_part0 = len(partition_0) / n # probability of partition 0\n    prob_part1 = len(partition_1) / n # probabiltiy of partition 1 \n    tot_entropy = (prob_part0 * entropy(partition_0)\n        + prob_part1 * entropy(partition_1) )\n    return tot_entropy", "meta": {"hexsha": "e4ccbf9dccef932b8ffcdf5ddb97a8f9ab173e9e", "size": 831, "ext": "py", "lang": "Python", "max_stars_repo_path": "uncertainty.py", "max_stars_repo_name": "Unique-Divine/Banknote-Forgery-Classification", "max_stars_repo_head_hexsha": "e3b0bb9c356b36637c84ee453af80c505d0b1d27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "uncertainty.py", "max_issues_repo_name": "Unique-Divine/Banknote-Forgery-Classification", "max_issues_repo_head_hexsha": "e3b0bb9c356b36637c84ee453af80c505d0b1d27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "uncertainty.py", "max_forks_repo_name": "Unique-Divine/Banknote-Forgery-Classification", "max_forks_repo_head_hexsha": "e3b0bb9c356b36637c84ee453af80c505d0b1d27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-18T00:53:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-18T00:53:48.000Z", "avg_line_length": 37.7727272727, "max_line_length": 77, "alphanum_fraction": 0.7003610108, "include": true, "reason": "import numpy", "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9793540680555949, "lm_q2_score": 0.8791467643431002, "lm_q1q2_score": 0.8609959600773286}}
{"text": "import numpy\ndef zscore(X, m=None, s=None, in_place=False, limit_memory=False):\n\tif (m is not None) and (s is not None):\n\t\tif in_place:\n\t\t\tfor i in range(X.shape[0]):\n\t\t\t\tfor j in range(X.shape[1]):\n\t\t\t\t\tX[i, j] = (X[i, j] - m[j]) / s[j]\n\t\t\treturn (X, m, s)\n\t\treturn ((X - m)/s, m, s)\n\tif limit_memory:\n\t\tm, s = compute_mean_std_limit_space(X)\n\telse:\n\t\tm = numpy.mean(X, axis=0)\n\t\ts = numpy.std(X, axis=0)\n\treturn zscore(X, m, s, in_place)\n\ndef compute_mean_std_limit_space(X):\n\tm = numpy.mean(X, axis=0)\n\ts = numpy.zeros_like(m)\n\n\tfor j in range(X.shape[1]):\n\t\tfor i in range(X.shape[0]):\n\t\t\ts[j] += (X[i,j] - m[j]) ** 2\n\t\ts[j] /= X.shape[0]\n\ts = numpy.sqrt(s)\n\n\treturn (m, s)\n\n\n# if __name__ == '__main__':\n# \tt = [[0.8147, 0.1576, 0.6557, 0.7060],\n# \t\t[0.9058, 0.9706, 0.0357, 0.0318],\n# \t\t[0.1270, 0.9572, 0.8491, 0.2769],\n# \t\t[0.9134, 0.4854, 0.9340, 0.0462],\n# \t\t[0.6324, 0.8003, 0.6787, 0.0971],\n# \t\t[0.0975, 0.1419, 0.7577, 0.8235],\n# \t\t[0.2785, 0.4218, 0.7431, 0.6948],\n# \t\t[0.5469, 0.9157, 0.3922, 0.3171],\n# \t\t[0.9575, 0.7922, 0.6555, 0.9502],\n# \t\t[0.9649, 0.9595, 0.1712, 0.0344]]\n# \tt = numpy.asarray(t)\n\n# \tX, m, s = zscore(t)\n# \tprint X\n# \tprint m\n# \tprint s\n\n# \t# X, m, s = zscore(t, in_place=True)\n# \t# print X\n# \t# print m\n# \t# print s\n\n# \tX, m, s = zscore(t, limit_memory=True)\n# \tprint X\n# \tprint m\n# \tprint s\n\n# \t# X, m, s = zscore(t, in_place=True, limit_memory=True)\n# \t# print X\n# \t# print m\n# \t# print s\n", "meta": {"hexsha": "d8e46af2c3d402ece4345c2c36e73b585baa19e9", "size": 1429, "ext": "py", "lang": "Python", "max_stars_repo_path": "speech_kit/nnet_utils.py", "max_stars_repo_name": "imu-hupeng/calc_metric_2k", "max_stars_repo_head_hexsha": "8a0573b9c69a585c3441b9febb04e9fa55a4e6be", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "speech_kit/nnet_utils.py", "max_issues_repo_name": "imu-hupeng/calc_metric_2k", "max_issues_repo_head_hexsha": "8a0573b9c69a585c3441b9febb04e9fa55a4e6be", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "speech_kit/nnet_utils.py", "max_forks_repo_name": "imu-hupeng/calc_metric_2k", "max_forks_repo_head_hexsha": "8a0573b9c69a585c3441b9febb04e9fa55a4e6be", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0483870968, "max_line_length": 66, "alphanum_fraction": 0.5619314206, "include": true, "reason": "import numpy", "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.9284087936225137, "lm_q1q2_score": 0.8609722441525153}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nLinear Regression using two models:\r\n\r\nThere are few data files each of them having a set of values for two variables (say x & y) in the folder, one\r\npair per line in the data file. We are trying to determine if there is a linear relationship between\r\nthem.\r\n\r\n• Regression functions are in a module called regression_functions.py.\r\n\r\n• The two techniques used in the program are (1) Method of Least Squares that gives us a\r\nCoefficient of Determination about the linearity of the relationship and also allows us try and fit a\r\nline along a possible linear path (2) Pearson technique which gives us a Correlation Coefficient\r\nabout the linearity of the relationship\r\n\r\n\r\n• The four data files are in1, in2, in3 and in4. Run the program against a data file and observe the\r\nresults\r\n\r\nconditions:\r\n    \r\n• In order to plot the relationship of x and y, do the following:\r\n• (1) Plot x vs y as a scatter plot (2) Plot x vs f(x) as a line plot\r\n• Apply appropriate text in the plot for axes, title, as well as the coefficient of determination\r\n(from Least Squares) and Pearson coefficient (from Pearson). Your plots should also\r\ninclude meaningful information infer whether or not the visualization and numerical results agree with each\r\nother.\r\n\r\n@author: amith\r\n\"\"\"\r\nimport regression_functions as regress\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nfile1 = open('in1.txt', 'r')\r\nr_file1 = file1.readlines()\r\n\r\nfile2 = open('in2.txt', 'r')\r\nr_file2 = file2.readlines()\r\n\r\nfile3 = open('in3.txt', 'r')\r\nr_file3 = file3.readlines()\r\n\r\nfile4 = open('in4.txt', 'r')\r\nr_file4 = file4.readlines()\r\n\r\nfile_list = [r_file1, r_file2, r_file3, r_file4]\r\n\r\ndef main():\r\n    \r\n    for f in file_list:\r\n        print ('Input File: ')\r\n        x, y = np.loadtxt(f, delimiter=\",\", unpack=True, encoding=\"utf-8-sig\")\r\n        m, b = regress.compute_m_and_b(x, y)\r\n        fx, residual = regress.compute_fx_residual(x, y, m, b)\r\n        least_squares_r = regress.compute_sum_of_squared_residuals(residual)\r\n        sum_squares = regress.compute_total_sum_of_squares(y)\r\n        print()\r\n    \r\n        print(\"Data points: \", len(x))\r\n        print(\"Least Squares Method\")\r\n        print(\"--------------------\")\r\n        print(\"Coefficients: m =\", \"%8.6f\" % m, \"\\tb =\", \"%8.6f\" % b)\r\n    \r\n        print(\"Sum of Squared Residuals: %12.6f\" % least_squares_r)\r\n        print(\"Total Sum of Squares: %12.6f\" % sum_squares)\r\n        coeff_of_determination = (1 - (least_squares_r/sum_squares))\r\n        print(\"Coefficient of determination: %12.6f\" % coeff_of_determination)\r\n        print()\r\n        pearson_r = regress.compute_pearson_coefficient(x, y)\r\n        print(\"Pearson Method\")\r\n        print(\"--------------\")\r\n        print(\"Pearson Correlation Coefficient: %12.6f\" % pearson_r)\r\n        print(\"Predicted value of y (for x=80): %8.2f\" % (m*80 + b))\r\n        plt.figure()\r\n        plt.scatter(x, y, color='red')\r\n        plt.plot(x, fx, 'b')\r\n            \r\n        \r\n    return\r\n            \r\n\r\n    \r\nmain()\r\nplt.show()", "meta": {"hexsha": "a9a6b7b16a5c56b5cf6706ef92dbc42ab62f5859", "size": 3045, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear Regression/regression_simple.py", "max_stars_repo_name": "Amith2397/Data-Science-and-Analytics-", "max_stars_repo_head_hexsha": "8466d3e103fb2ec77152deefecdfb2ec24bfd2d3", "max_stars_repo_licenses": ["FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Linear Regression/regression_simple.py", "max_issues_repo_name": "Amith2397/Data-Science-and-Analytics-", "max_issues_repo_head_hexsha": "8466d3e103fb2ec77152deefecdfb2ec24bfd2d3", "max_issues_repo_licenses": ["FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear Regression/regression_simple.py", "max_forks_repo_name": "Amith2397/Data-Science-and-Analytics-", "max_forks_repo_head_hexsha": "8466d3e103fb2ec77152deefecdfb2ec24bfd2d3", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8235294118, "max_line_length": 110, "alphanum_fraction": 0.6476190476, "include": true, "reason": "import numpy", "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.9073122269997507, "lm_q1q2_score": 0.8609642364807233}}
{"text": "import numpy as np\n\n\ndef power_iteration(\n    input_matrix: np.ndarray,\n    vector: np.ndarray,\n    error_tol: float = 1e-12,\n    max_iterations: int = 100,\n) -> tuple[float, np.ndarray]:\n    \"\"\"\n    Power Iteration.\n    Find the largest eigenvalue and corresponding eigenvector\n    of matrix input_matrix given a random vector in the same space.\n    Will work so long as vector has component of largest eigenvector.\n    input_matrix must be either real or Hermitian.\n\n    Input\n    input_matrix: input matrix whose largest eigenvalue we will find.\n    Numpy array. np.shape(input_matrix) == (N,N).\n    vector: random initial vector in same space as matrix.\n    Numpy array. np.shape(vector) == (N,) or (N,1)\n\n    Output\n    largest_eigenvalue: largest eigenvalue of the matrix input_matrix.\n    Float. Scalar.\n    largest_eigenvector: eigenvector corresponding to largest_eigenvalue.\n    Numpy array. np.shape(largest_eigenvector) == (N,) or (N,1).\n\n    >>> import numpy as np\n    >>> input_matrix = np.array([\n    ... [41,  4, 20],\n    ... [ 4, 26, 30],\n    ... [20, 30, 50]\n    ... ])\n    >>> vector = np.array([41,4,20])\n    >>> power_iteration(input_matrix,vector)\n    (79.66086378788381, array([0.44472726, 0.46209842, 0.76725662]))\n    \"\"\"\n\n    # Ensure matrix is square.\n    assert np.shape(input_matrix)[0] == np.shape(input_matrix)[1]\n    # Ensure proper dimensionality.\n    assert np.shape(input_matrix)[0] == np.shape(vector)[0]\n    # Ensure inputs are either both complex or both real\n    assert np.iscomplexobj(input_matrix) == np.iscomplexobj(vector)\n    is_complex = np.iscomplexobj(input_matrix)\n    if is_complex:\n        # Ensure complex input_matrix is Hermitian\n        assert np.array_equal(input_matrix, input_matrix.conj().T)\n\n    # Set convergence to False. Will define convergence when we exceed max_iterations\n    # or when we have small changes from one iteration to next.\n\n    convergence = False\n    lamda_previous = 0\n    iterations = 0\n    error = 1e12\n\n    while not convergence:\n        # Multiple matrix by the vector.\n        w = np.dot(input_matrix, vector)\n        # Normalize the resulting output vector.\n        vector = w / np.linalg.norm(w)\n        # Find rayleigh quotient\n        # (faster than usual b/c we know vector is normalized already)\n        vectorH = vector.conj().T if is_complex else vector.T\n        lamda = np.dot(vectorH, np.dot(input_matrix, vector))\n\n        # Check convergence.\n        error = np.abs(lamda - lamda_previous) / lamda\n        iterations += 1\n\n        if error <= error_tol or iterations >= max_iterations:\n            convergence = True\n\n        lamda_previous = lamda\n\n    if is_complex:\n        lamda = np.real(lamda)\n\n    return lamda, vector\n\n\ndef test_power_iteration() -> None:\n    \"\"\"\n    >>> test_power_iteration()  # self running tests\n    \"\"\"\n    real_input_matrix = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]])\n    real_vector = np.array([41, 4, 20])\n    complex_input_matrix = real_input_matrix.astype(np.complex128)\n    imag_matrix = np.triu(1j * complex_input_matrix, 1)\n    complex_input_matrix += imag_matrix\n    complex_input_matrix += -1 * imag_matrix.T\n    complex_vector = np.array([41, 4, 20]).astype(np.complex128)\n\n    for problem_type in [\"real\", \"complex\"]:\n        if problem_type == \"real\":\n            input_matrix = real_input_matrix\n            vector = real_vector\n        elif problem_type == \"complex\":\n            input_matrix = complex_input_matrix\n            vector = complex_vector\n\n        # Our implementation.\n        eigen_value, eigen_vector = power_iteration(input_matrix, vector)\n\n        # Numpy implementation.\n\n        # Get eigenvalues and eigenvectors using built-in numpy\n        # eigh (eigh used for symmetric or hermetian matrices).\n        eigen_values, eigen_vectors = np.linalg.eigh(input_matrix)\n        # Last eigenvalue is the maximum one.\n        eigen_value_max = eigen_values[-1]\n        # Last column in this matrix is eigenvector corresponding to largest eigenvalue.\n        eigen_vector_max = eigen_vectors[:, -1]\n\n        # Check our implementation and numpy gives close answers.\n        assert np.abs(eigen_value - eigen_value_max) <= 1e-6\n        # Take absolute values element wise of each eigenvector.\n        # as they are only unique to a minus sign.\n        assert np.linalg.norm(np.abs(eigen_vector) - np.abs(eigen_vector_max)) <= 1e-6\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n    test_power_iteration()\n", "meta": {"hexsha": "4c6525b6e4af3f66b0fd20bb700d33811690c97b", "size": 4493, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_algebra/src/power_iteration.py", "max_stars_repo_name": "Leoriem-code/Python", "max_stars_repo_head_hexsha": "1400cb86ff7c656087963db41844e0ca503ae6d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2022-03-25T06:41:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T17:26:42.000Z", "max_issues_repo_path": "linear_algebra/src/power_iteration.py", "max_issues_repo_name": "Leoriem-code/Python", "max_issues_repo_head_hexsha": "1400cb86ff7c656087963db41844e0ca503ae6d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2022-02-19T19:41:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T20:53:39.000Z", "max_forks_repo_path": "linear_algebra/src/power_iteration.py", "max_forks_repo_name": "Leoriem-code/Python", "max_forks_repo_head_hexsha": "1400cb86ff7c656087963db41844e0ca503ae6d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-02-21T21:00:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T13:48:21.000Z", "avg_line_length": 34.8294573643, "max_line_length": 88, "alphanum_fraction": 0.6610282662, "include": true, "reason": "import numpy", "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.9073122282528898, "lm_q1q2_score": 0.8609642363591303}}
{"text": "#For Python 3\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nN = 1000 #global variable; number of \"partitions\" for the interval [-2,2]\n\ndef f(x,y):\n    \"\"\"\n    Takes in two numpy arrays that are result of meshgrid.\n    Returns a numpy array with points representing the iteration number for divergence\n    \"\"\"\n    max_iter = 100 #maximum number of interations\n    c = x + 1j*y\n    z = np.zeros((N,N),dtype=complex)\n    r = np.zeros((N,N),dtype=int) #return\n    mask = np.full((N,N), True, dtype=bool)\n    for i in range(0,max_iter,1):\n        z[mask] = z[mask]**2 + c[mask]  #z_i = z_i-1**2 + c\n        r[mask] = i #i is the iteration number at which point escapes (diverges)\n        #if point ever becomes larger than 2, the sequence will escape to infinity:\n        #https://en.wikipedia.org/wiki/Mandelbrot_set#Basic_properties\n        mask[np.abs(z) > 2] = False #points that diverge\n    return r, mask\n\ndef plot_set(bounds,plot_binary):\n    \"\"\"\n    Plots the Mandelbrot set with the given bounds\n    INPUT:\n    ::array:: bounds            #bounds of the plot\n    ::boolean:: plot_binary     #whether or not to plot binary (for colour plot, send False)\n    \"\"\"\n    x = np.linspace(bounds[0], bounds[1], N)\n    y = np.linspace(bounds[2], bounds[3], N)\n    #https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html\n    xv, yv = np.meshgrid(x,y)\n    vals, mandelbrot = f(xv, yv)\n    vals = np.flip(vals,0) #flip array vertically\n    mandelbrot = np.flip(mandelbrot,0)\n\n    font = {'fontname':'Times New Roman'} #https://stackoverflow.com/a/21323217\n    plt.figure(dpi=100)\n    plt.title('Mandelbrot Set')\n    plt.xticks(np.arange(0,N+1,N/4),np.arange(bounds[0],bounds[1]+1,(bounds[1]-bounds[0])/4)) #careful: arange works as [start, stop)\n    plt.yticks(np.arange(0,N+1,N/4),np.arange(bounds[3],bounds[2]-1,(bounds[2]-bounds[3])/4))\n    plt.xlabel('Re',**font)\n    plt.ylabel('Im',**font)\n    if plot_binary == False:\n        #for colormaps see https://matplotlib.org/examples/color/colormaps_reference.html\n        plt.imshow(vals, cmap='plasma_r') #_r to reverse colormap https://stackoverflow.com/a/3280732\n        cbar = plt.colorbar()\n        cbar.set_label('Number of Iterations for Divergence')\n    else:\n        plt.imshow(mandelbrot, cmap=plt.cm.gray)\n    plt.show()\n    return True\n\ndef plot_set_alternate(bounds):\n    \"\"\"\n    Similar to plot_set() but instead uses matplotlib.pyplot.contourf()\n    \"\"\"\n    x = np.linspace(bounds[0], bounds[1], N)\n    y = np.linspace(bounds[2], bounds[3], N)\n    #https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html\n    xv, yv = np.meshgrid(x,y)\n    vals, mandelbrot = f(xv, yv)\n    \n    font = {'fontname':'Times New Roman'} #https://stackoverflow.com/a/21323217\n    plt.figure(dpi=100)\n    plt.title('Mandelbrot Set')\n    plt.contourf(xv, yv, vals, levels=100, cmap='plasma_r')\n    plt.xlabel('Re',**font)\n    plt.ylabel('Im',**font)\n    plt.axes().set_aspect('equal')\n    plt.colorbar(label='Number of Iterations for Divergence')\n    plt.show()\n\n    return True\n\ndef main():\n    bounds1 = [-2,2,-2,2] #[xmin,xmax,ymin,ymax]\n    bounds2 = [-2,0,-1,1]\n    plot_set_alternate(bounds1)\n    plot_set(bounds2, False)\n    plot_set(bounds1, True)\n    plot_set(bounds2, True)\n    return True\n\nif __name__ == \"__main__\":\n    main()\n\n", "meta": {"hexsha": "5995244e762de613290e80d1100da0425f951664", "size": 3306, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment2_2020/question1_mandelbrot.py", "max_stars_repo_name": "mattleung10/CTA200", "max_stars_repo_head_hexsha": "a88e0a60f35143cbefa4ec9fc10b091664ef06f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment2_2020/question1_mandelbrot.py", "max_issues_repo_name": "mattleung10/CTA200", "max_issues_repo_head_hexsha": "a88e0a60f35143cbefa4ec9fc10b091664ef06f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment2_2020/question1_mandelbrot.py", "max_forks_repo_name": "mattleung10/CTA200", "max_forks_repo_head_hexsha": "a88e0a60f35143cbefa4ec9fc10b091664ef06f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9347826087, "max_line_length": 133, "alphanum_fraction": 0.6467029643, "include": true, "reason": "import numpy", "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429474, "lm_q2_score": 0.9073122125886486, "lm_q1q2_score": 0.8609642214950612}}
{"text": "\r\n\r\nimport random\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.stats import poisson\r\nfrom scipy.stats import norm\r\n\r\n# Helper function \r\ndef Poisson_value(mu):\r\n    r = random.uniform(0, 1)\r\n    values = list()\r\n    for i in range(1000):\r\n        values.append(poisson.pmf(i,mu))\r\n        if sum(values) > r: break\r\n    return  len(values)-1\r\n\r\n# Data gen\r\nN = 10000\r\nmu1 = [ Poisson_value(1.0)  for i in range(N)]\r\nmu10_3 =  [ Poisson_value(10.3)  for i in range(N)]\r\nmu102_1 = [ Poisson_value(102.1) for i in range(N)]\r\n\r\n# Interpolation\r\n\r\ndef extract(data):\r\n    counts = dict()\r\n    for i in mu1:\r\n        counts[i] = counts.get(i, 0) + 1\r\n    data = sorted(counts.items())\r\n    x_vals = [ v[0] for v in data ]\r\n    y_vals = [ v[1]/N for v in data ]\r\n    return x_vals , y_vals\r\n\r\n### Figure 1\r\nplot1 = plt.figure(1)\r\ndata = mu1\r\nx , y = extract(data)\r\nplt.hist(data, density = 1, bins = (max(x)+1), rwidth = 0.85 )\r\n\r\nmu , std = norm.fit(data)\r\np = norm.pdf(range(int(mu-4*std), int(mu+4*std)),mu,std)\r\nplt.plot(range(int(mu-4*std), int(mu+4*std)), p)\r\n\r\nplt.xlabel(\"Values\")\r\nplt.ylabel(\"Probability\")\r\nplt.title(\"Poisson deviates for $\\mu=1.0$\")\r\nplt.legend([\"Fit\", \"Normalized Data\"])\r\n\r\n### Figure 2\r\nplot2 = plt.figure(2)\r\ndata = mu10_3\r\nx , y = extract(data)\r\nplt.hist(data, density = 1, bins = (max(x)+1), rwidth = 0.85 )\r\n\r\nmu , std = norm.fit(data)\r\np = norm.pdf(range(int(mu-4*std), int(mu+4*std)),mu,std)\r\nplt.plot(range(int(mu-4*std), int(mu+4*std)), p)\r\n\r\nplt.xlabel(\"Values\")\r\nplt.ylabel(\"Probability\")\r\nplt.title(\"Poisson deviates for $\\mu=10.3$\")\r\nplt.legend([\"Normal Fit\", \"Normalized Data\"])\r\n\r\n### Figure 3\r\nplot3 = plt.figure(3)\r\ndata = mu102_1\r\nx , y = extract(data)\r\nplt.hist(data, density = 1, bins = (max(x)+1), rwidth = 0.85 )\r\n\r\nmu , std = norm.fit(data)\r\np = norm.pdf(range(int(mu-4*std), int(mu+4*std)),mu,std)\r\nplt.plot(range(int(mu-4*std), int(mu+4*std)), p)\r\n\r\nplt.xlabel(\"Values\")\r\nplt.ylabel(\"Probability\")\r\nplt.title(\"Poisson deviates for $\\mu=102.1$\")\r\nplt.legend([\"Normal Fit\", \"Normalized Data\"])\r\n\r\n\r\nplt.show()", "meta": {"hexsha": "4b60958f987f54039412249162280029ae467cd6", "size": 2055, "ext": "py", "lang": "Python", "max_stars_repo_path": "MontePartC.py", "max_stars_repo_name": "layanamich/monte_carlo", "max_stars_repo_head_hexsha": "04cc4e8d907cac24510e97c6e8896f7055cd5f40", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MontePartC.py", "max_issues_repo_name": "layanamich/monte_carlo", "max_issues_repo_head_hexsha": "04cc4e8d907cac24510e97c6e8896f7055cd5f40", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MontePartC.py", "max_forks_repo_name": "layanamich/monte_carlo", "max_forks_repo_head_hexsha": "04cc4e8d907cac24510e97c6e8896f7055cd5f40", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6875, "max_line_length": 63, "alphanum_fraction": 0.6145985401, "include": true, "reason": "from scipy", "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.9073122119620789, "lm_q1q2_score": 0.8609642182790619}}
{"text": "import numpy as np\n\nclass Bayes:    \n    @staticmethod\n    def mean(X):\n        return np.mean(X,axis=0)\n    \n    @staticmethod\n    def variance(X):\n        return np.mean((X-Bayes.mean(X))**2,axis=0)\n    \n    def gaussian(self,x,avg,var): \n        return (1./np.sqrt(2*np.pi*var)) * np.exp(-0.5*((x-avg)**2)/var)\n    \n    def fit(self,X,y):\n        c = len(set(y))\n        self.c = c\n        Xs = [X[y==i] for i in range(c)]\n        \n        #各个类别的均值、方差、所占比率\n        self.avgs = [Bayes.mean(X) for X in Xs]\n        self.vars = [Bayes.variance(X) for X in Xs]\n        self.percs = [len(y[y==i])/len(y) for i in range(c)]\n        \n    def predict(self,x):\n        if len(x.shape) == 1:\n            result = np.array(self.percs)\n            for i in range(self.c):\n                gaus = self.gaussian(x,self.avgs[i],self.vars[i])\n                for j in range(len(x)):\n                    result[i] *= gaus[j]\n            return np.argmax(result)\n        results = np.array([self.predict(x[i]) for i in range(len(x))])\n        return results\n    \n    def score(self,X,y):\n        y_pred = self.predict(X)\n        return np.sum(y_pred==y)/len(y)\n\nif __name__==\"__main__\":\n    from sklearn.datasets import load_iris\n    from sklearn.model_selection import train_test_split\n    iris = load_iris()\n    X,y = iris[\"data\"],iris[\"target\"]\n    X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=22)\n    # print(len(X_train))\n    # print(len(X_test))\n    bayes = Bayes()\n    bayes.fit(X_train,y_train)\n    # print(bayes.avgs)\n    # print(bayes.vars)\n    print(bayes.score(X_test,y_test))\n\n    from sklearn.naive_bayes import GaussianNB\n    clf = GaussianNB()\n    clf.fit(X_train, y_train)\n    print(clf.score(X_test,y_test))", "meta": {"hexsha": "fa31ecf8da3d4c1ca9421a53eb8fca160c799d09", "size": 1730, "ext": "py", "lang": "Python", "max_stars_repo_path": "NaiveBayes/bayes.py", "max_stars_repo_name": "QYHcrossover/ML-numpy", "max_stars_repo_head_hexsha": "863cc651ac38bc421e3b6e99f36a51267f0de0f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-07-01T02:35:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:19:44.000Z", "max_issues_repo_path": "NaiveBayes/bayes.py", "max_issues_repo_name": "QYHcrossover/ML-numpy", "max_issues_repo_head_hexsha": "863cc651ac38bc421e3b6e99f36a51267f0de0f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NaiveBayes/bayes.py", "max_forks_repo_name": "QYHcrossover/ML-numpy", "max_forks_repo_head_hexsha": "863cc651ac38bc421e3b6e99f36a51267f0de0f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-18T08:02:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T02:53:38.000Z", "avg_line_length": 30.350877193, "max_line_length": 73, "alphanum_fraction": 0.5641618497, "include": true, "reason": "import numpy", "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350252, "lm_q2_score": 0.8933094110250333, "lm_q1q2_score": 0.8609536942529988}}
{"text": "\nimport numpy as np\n\ndef sigmoid(Z):\n\n    # Sigmoid function\n    # g(Z) = 1 / (1 + e^{-Z})\n    # Z: shape [m,]\n\n    # Trick to prevent possible overflow of np.exp(-Z)\n    # Output will never to be exact 0\n    idx = (Z < -500)\n    Z[idx] = -500\n\n    return 1.0 / (1.0 + np.exp(-Z))\n\nclass LogisticRegressor(object):\n\n    def __init__(self, alpha, c, T = 1000, random_seed = 0, intercept = True):\n\n        # Initialize Logistic Regression\n        # alpha: learning rate.\n        # c: L2 regularization strength.\n\n        self.alpha = alpha\n        self.c = c\n        self.T = T\n        self.random_seed = random_seed\n        self.intercept = intercept\n\n\n    def fit(self, X, y):\n\n        np.random.seed(self.random_seed)\n\n        y = y.flatten()\n\n        if self.intercept == True:\n            X = np.insert(X, 0, np.ones(X.shape[0]), axis = 1)\n\n        # Weights initialization\n        self.theta = np.random.normal(0, 0.1, X.shape[1])\n\n        losses = list()\n        losses.append(self.logistic_regression_loss(X = X, y = y, theta = self.theta, c = self.c))\n\n        for i in range(self.T):\n\n            self.theta = self.logistic_regression_weight_update(X = X, y = y, theta = self.theta, alpha = self.alpha, c = self.c)\n            loss = self.logistic_regression_loss(X = X, y = y, theta = self.theta, c = self.c)\n            losses.append(loss)\n\n        losses = np.array(losses)\n\n        return losses\n\n\n    def logistic_regression_loss(self, X, y, theta, c):\n\n        # Loss function for logistic regression\n        # X: input feature matrix, shape [m,n].\n        # y: input target value, shape [m,1].\n        # c: L2 regularization strength.\n\n        h = sigmoid(Z = X.dot(theta))\n\n        # Trick to prevent h is exact 1 for np.log(1 - h)\n        idx = (h == 1.0)\n        h[idx] = 1.0 - 1e-15\n\n        loss_mean = 1.0 / X.shape[0] * (-np.sum(y * np.log(h) + (1 - y) * np.log(1 - h))) + c * np.sum((theta ** 2))\n\n        return loss_mean\n\n\n    def logistic_regression_weight_update(self, X, y, theta, alpha, c):\n    \n        # Weight update of gradient descent for logistic regression\n        # X: input feature matrix, shape [m,n].\n        # y: input target value, shape [m,1].\n        # alpha: learning rate.\n        # c: L2 regularization strength.\n        # theta: parameters for features in X, shape [n+1,1].\n\n        # Calculate activated values\n        h = sigmoid(Z = X.dot(theta))\n        # Update weigths\n        theta += alpha * ((1.0 / X.shape[0] * (y - h).dot(X)) - 2 * c * theta)\n\n        return theta\n\n\n    def predict(self, X, threshold = 0.5):\n\n        # threshold: predict 1 if above threshold.\n\n        if self.intercept == True:\n            X = np.insert(X, 0, np.ones(X.shape[0]), axis = 1)\n\n        probabilities = sigmoid(Z = np.dot(X, self.theta))\n\n        y_predicted = (probabilities > threshold).astype(int)\n\n        return y_predicted", "meta": {"hexsha": "f9b6404ede7898d34e2b7bc0431bf075b7d17e92", "size": 2870, "ext": "py", "lang": "Python", "max_stars_repo_path": "logistic_regressor.py", "max_stars_repo_name": "leimao/Logistic_Regression_Python", "max_stars_repo_head_hexsha": "a64ed85d0bea8010d85e9c1e056a3af09b2e43c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-03T19:39:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-03T19:39:22.000Z", "max_issues_repo_path": "logistic_regressor.py", "max_issues_repo_name": "leimao/Logistic_Regression_Python", "max_issues_repo_head_hexsha": "a64ed85d0bea8010d85e9c1e056a3af09b2e43c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logistic_regressor.py", "max_forks_repo_name": "leimao/Logistic_Regression_Python", "max_forks_repo_head_hexsha": "a64ed85d0bea8010d85e9c1e056a3af09b2e43c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5961538462, "max_line_length": 129, "alphanum_fraction": 0.5606271777, "include": true, "reason": "import numpy", "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350253, "lm_q2_score": 0.8933094103149354, "lm_q1q2_score": 0.8609536935686208}}
{"text": "#!/usr/bin/python\n\n'''\nmjtsai1974@20180606, v1.0, MLE for https://mjtsai1974.github.io/DevBlog/2018/06/06/bayesian-ml-beyes-to-practice/\n\nhttp://www.astroml.org/book_figures/chapter3/fig_gaussian_distribution.html\n\ndist = scipy.stats.norm(...)\n\nWhere ... should be filled in with the desired distribution parameters Once we have defined the distribution parameters in this way, these distribution objects have many useful methods; for example:\n\n    dist.pmf(x) computes the Probability Mass Function at values x in the case of discrete distributions\n    dist.pdf(x) computes the Probability Density Function at values x in the case of continuous distributions\n    dist.rvs(N) computes N random variables distributed according to the given distribution\n'''\n\nimport numpy as np\nfrom scipy.stats import norm\nfrom matplotlib import pyplot as plt\n\n'''\n#----------------------------------------------------------------------\n# This function adjusts matplotlib settings for a uniform feel in the textbook.\n# Note that with usetex=True, fonts are rendered with LaTeX.  This may\n# result in an error if LaTeX is not installed on your system.  In that case,\n# you can set usetex to False.\nfrom astroML.plotting import setup_text_plots\nsetup_text_plots(fontsize=8, usetex=False)\n'''\n\n# Define the given measured weights\nweights = [13.9, 14.1, 17.5]\nn = len(weights)\n\n# Define the distributions to be plotted\nmu = np.mean(weights)\nsample_variance = np.var(weights, ddof=1)\nsample_std_deviation = np.sqrt(sample_variance)\n\npopulation_variance = np.var(weights, ddof=0)\npopulation_std_deviation = np.sqrt(population_variance)\n\nsigma_values = [sample_std_deviation, population_std_deviation]\nlinestyles = ['-', '--']\ncolours = ['red', 'blue']\nx_axis = np.linspace(mu - 2 * np.max(sigma_values), mu + 2 * np.max(sigma_values), 100) #use the \n\n# plot the distributions\nfig, ax = plt.subplots(figsize=(5, 3.75))\n\nfor sigma, ls, color in zip(sigma_values, linestyles, colours):\n    # create a gaussian / normal distribution\n    dist = norm(mu, sigma)\n\n    plt.plot(x_axis, dist.pdf(x_axis), ls=ls, c=color,\n             label=r'$\\mu=%.3f,\\ \\sigma=%.3f$' % (mu, sigma))\n\nplt.xlim(mu - 2 * np.max(sigma_values), mu + 2 * np.max(sigma_values))\nplt.ylim(0, 0.45)\n\nplt.xlabel('$x$')\nplt.ylabel(r'$p(x|\\mu,\\sigma)$')\nplt.title('Gaussian Distribution')\n\nplt.legend()\nplt.show()\n\n# MLE to ask for possible real weight with max(sample std deviation, population std deviation)\nMLE_max = 0\nmu_max = mu\n\nfor i in range(len(x_axis)):\n    dist = norm(x_axis[i], np.max(sigma_values))\n\n    MLE_now = 1.0\n\n    for j in range(len(weights)):\n        MLE_now = dist.pdf(weights[j]) * MLE_now\n\n    if MLE_now > MLE_max:\n        MLE_max = MLE_now\n        mu_max = x_axis[i]\n\t\t\nprint('using np.max(sigma_values), the MLE for weight {0: 5.3f}'.format(mu_max))\n\n# MLE to ask for possible real weight with min(sample std deviation, population std deviation)\nMLE_max = 0\nmu_max = mu\n\nfor i in range(len(x_axis)):\n    dist = norm(x_axis[i], np.min(sigma_values))\n\n    MLE_now = 1.0\n\n    for j in range(len(weights)):\n        MLE_now = dist.pdf(weights[j]) * MLE_now\n\n    if MLE_now > MLE_max:\n        MLE_max = MLE_now\n        mu_max = x_axis[i]\n\t\t\nprint('using np.min(sigma_values), the MLE for weight {0: 5.3f}'.format(mu_max))", "meta": {"hexsha": "a613366a4a072e4dc7ab6964cc4ce9db4ff066ba", "size": 3283, "ext": "py", "lang": "Python", "max_stars_repo_path": "template/BayesInferForDogWeightByMLE.py", "max_stars_repo_name": "mjtsai1974/DevBlog", "max_stars_repo_head_hexsha": "f1429e28e7ea618a64f5e111be4d7f42ae616ce8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "template/BayesInferForDogWeightByMLE.py", "max_issues_repo_name": "mjtsai1974/DevBlog", "max_issues_repo_head_hexsha": "f1429e28e7ea618a64f5e111be4d7f42ae616ce8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "template/BayesInferForDogWeightByMLE.py", "max_forks_repo_name": "mjtsai1974/DevBlog", "max_forks_repo_head_hexsha": "f1429e28e7ea618a64f5e111be4d7f42ae616ce8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1862745098, "max_line_length": 198, "alphanum_fraction": 0.6975327444, "include": true, "reason": "import numpy,from scipy", "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350253, "lm_q2_score": 0.8933094096048376, "lm_q1q2_score": 0.8609536928842428}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n\r\nMake a simple 1D gaussian profile. \r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef gaussian_1D_profile(x_min, x_max, x_step, center, sigma, amplitude):\r\n    \"\"\"Function to create a 1D Gaussian distribution. \r\n    \r\n    Parameters\r\n    ----------\r\n    \r\n    x_min, x_max, x_step: float, float, float\r\n        Creates a sequence (1D ndarray) of points over which to compute the Gaussian\r\n    center: float\r\n        The center point of the gaussian profile\r\n    sigma: float\r\n        1/e-squared width of beam\r\n    amplitude: float \r\n        Amplitude at peak value\r\n        \r\n    Returns\r\n    -------\r\n    \r\n    x,y: ndarray\r\n        the gaussian profile amplitude values\r\n        \r\n    \"\"\"\r\n    \r\n    x = np.arange(x_min, x_max,x_step)  #create spatial array\r\n    d = 2*float(sigma)\r\n    y = amplitude*np.e**(-2*np.power((x-center)/d, 2))\r\n    \r\n    return x,y\r\n\r\n    # todo: learn how to do proper unit testing...heres some manual checks\r\n    # what if center > max(X)?  still works, just get the tail end\r\n    # what if center, sigma negative?  Since is getting squared, doesn't matter\r\n    # what if amplitude is neg or zero? Straight line at zero\r\n    # what if d = 0? Straight line\r\n    # what if the ndarray goes negative?  Is ok.\r\n    # What if the array is empty or null? should catch an error.\r\n\r\ndef plot_1d_gaussian(x,y,hold=True):  \r\n    \"\"\"Plot the gaussian profile.\r\n    \r\n    Parameters\r\n    ----------\r\n    \r\n    x: ndarray\r\n        X axis values\r\n    y: float\r\n        Y axis values \r\n        \r\n    \"\"\"   \r\n    plt.hold = hold\r\n    plt.plot(x,y)\r\n    plt.xlabel('X axis')\r\n    plt.ylabel('Amplitude')\r\n    plt.title('Gaussian 1D Profile')\r\n    plt.show() \r\n    \r\n    # todo: check if the hold true works or not\r\n    \r\n\r\nif __name__ == '__main__':\r\n    \r\n    x,y = gaussian_1D_profile(-50,50,.2, 0, 10, 1)\r\n    plot_1d_gaussian(x,y,True)\r\n\r\n\r\n", "meta": {"hexsha": "6184c8f7939bf7ea1a9e784b299f5c4ed5869650", "size": 1914, "ext": "py", "lang": "Python", "max_stars_repo_path": "gaussian1D_profile.py", "max_stars_repo_name": "jfblanchard/gaussian-beam", "max_stars_repo_head_hexsha": "bab00487e3bc19885abd1b26d759539ff07b0103", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gaussian1D_profile.py", "max_issues_repo_name": "jfblanchard/gaussian-beam", "max_issues_repo_head_hexsha": "bab00487e3bc19885abd1b26d759539ff07b0103", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gaussian1D_profile.py", "max_forks_repo_name": "jfblanchard/gaussian-beam", "max_forks_repo_head_hexsha": "bab00487e3bc19885abd1b26d759539ff07b0103", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8571428571, "max_line_length": 85, "alphanum_fraction": 0.5799373041, "include": true, "reason": "import numpy", "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799430946808, "lm_q2_score": 0.8933094103149354, "lm_q1q2_score": 0.8609536926392714}}
{"text": "import numpy as np\ndef gd(x_start, step, g):   \n    x = x_start\n    for i in range(20):\n        grad = g(x)\n        x -= grad * step\n        print '[ Epoch {0} ] grad = {1}, x = {2}'.format(i, grad, x)\n        if abs(grad) < 1e-6:\n            break;\n    return x\n\ndef f(x):\n    return x * x - 2 * x + 1\n\ndef g(x):\n    return 2 * x - 2\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nx = np.linspace(-5,7,100)\ny = f(x)\nplt.plot(x, y)\n\ngd(5,0.1,g)\n\ngd(5,100,g)\n\ngd(5,1,g)\n\ngd(4,1,g)\n\ndef f2(x):\n    return 4 * x * x - 4 * x + 1\ndef g2(x):\n    return 8 * x - 4\ngd(5,0.25,g2)\n\n", "meta": {"hexsha": "1ec82ddc0ea8ce692cf4d8edf9db212ecf6b4d08", "size": 577, "ext": "py", "lang": "Python", "max_stars_repo_path": "third_party/rl_example/ch3/3_1.py", "max_stars_repo_name": "jayhenry/rlpyt", "max_stars_repo_head_hexsha": "c4b4a5fe302b99751dbc440fcb75cbe5d9cc52e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-21T17:59:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-24T15:42:37.000Z", "max_issues_repo_path": "third_party/rl_example/ch3/3_1.py", "max_issues_repo_name": "jayhenry/rlpyt", "max_issues_repo_head_hexsha": "c4b4a5fe302b99751dbc440fcb75cbe5d9cc52e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/rl_example/ch3/3_1.py", "max_forks_repo_name": "jayhenry/rlpyt", "max_forks_repo_head_hexsha": "c4b4a5fe302b99751dbc440fcb75cbe5d9cc52e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.1842105263, "max_line_length": 68, "alphanum_fraction": 0.4956672444, "include": true, "reason": "import numpy", "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811601648193, "lm_q2_score": 0.891811044719067, "lm_q1q2_score": 0.8609375809986926}}
{"text": "import numpy as np\n\n\n# spearman coefficient rs\ndef spearman(R, Q):\n    \"\"\"\n    Calculate Spearman rank correlation coefficient between two vectors\n\n    Parameters\n    -----------\n        R : ndarray\n            First vector containing values\n        Q : ndarray\n            Second vector containing values\n\n    Returns\n    --------\n        float\n            Value of correlation coefficient between two vectors\n\n    Examples\n    ----------\n    >>> rS = spearman(R, Q)\n    \"\"\"\n\n    N = len(R)\n    denominator = N*(N**2-1)\n    numerator = 6*sum((R-Q)**2)\n    rS = 1-(numerator/denominator)\n    return rS\n\n\n# weighted spearman coefficient rw\ndef weighted_spearman(R, Q):\n    \"\"\"\n    Calculate Weighted Spearman rank correlation coefficient between two vectors\n\n    Parameters\n    -----------\n        R : ndarray\n            First vector containing values\n        Q : ndarray\n            Second vector containing values\n\n    Returns\n    --------\n        float\n            Value of correlation coefficient between two vectors\n\n    Examples\n    ---------\n    >>> rW = weighted_spearman(R, Q)\n    \"\"\"\n\n    N = len(R)\n    denominator = N**4 + N**3 - N**2 - N\n    numerator = 6 * sum((R - Q)**2 * ((N - R + 1) + (N - Q + 1)))\n    rW = 1 - (numerator / denominator)\n    return rW\n\n\n# pearson coefficient\ndef pearson_coeff(R, Q):\n    \"\"\"\n    Calculate Pearson correlation coefficient between two vectors\n\n    Parameters\n    -----------\n        R : ndarray\n            First vector containing values\n        Q : ndarray\n            Second vector containing values\n\n    Returns\n    --------\n        float\n            Value of correlation coefficient between two vectors\n\n    Examples\n    ----------\n    >>> corr = pearson_coeff(R, Q)\n    \"\"\"\n    \n    numerator = np.sum((R - np.mean(R)) * (Q - np.mean(Q)))\n    denominator = np.sqrt(np.sum((R - np.mean(R))**2) * np.sum((Q - np.mean(Q))**2))\n    corr = numerator / denominator\n    return corr", "meta": {"hexsha": "1330d79f8a5a2cf7ac789ba9913b46d0f6a6784a", "size": 1929, "ext": "py", "lang": "Python", "max_stars_repo_path": "distance_metrics_mcda/correlations.py", "max_stars_repo_name": "energyinpython/distance-metrics-for-mcda", "max_stars_repo_head_hexsha": "1a629a208f8445c6960dbaa20c5ad5ca3974e9a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distance_metrics_mcda/correlations.py", "max_issues_repo_name": "energyinpython/distance-metrics-for-mcda", "max_issues_repo_head_hexsha": "1a629a208f8445c6960dbaa20c5ad5ca3974e9a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distance_metrics_mcda/correlations.py", "max_forks_repo_name": "energyinpython/distance-metrics-for-mcda", "max_forks_repo_head_hexsha": "1a629a208f8445c6960dbaa20c5ad5ca3974e9a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1724137931, "max_line_length": 84, "alphanum_fraction": 0.5515811301, "include": true, "reason": "import numpy", "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811571768048, "lm_q2_score": 0.8918110454379297, "lm_q1q2_score": 0.8609375790279247}}
{"text": "from scipy.special import erf\nimport math\n\n# compute erf(1) by numerically doing the integral as a 3-point quadrature:\n# trapezoid (compound), Simpson's, and Gauss-Legendre\n#\n# erf(x) = 2/sqrt(pi) int_0^x exp(-y^2) dy\n#\n\n\n# analytic integral\ntrue = erf(1)\n\n\ndef f(y):\n    \"\"\" integrand \"\"\"\n    return (2.0/math.sqrt(math.pi))*math.exp(-y**2)\n\n\ndef x(z, a, b):\n    \"\"\" convert from [-1, 1] (the integration range of Gauss-Legendre)\n        to [a, b] (our general range) through a change of variables z\n        -> x \"\"\"\n\n    return 0.5*(b + a) + 0.5*(b - a)*z\n\n\n# integration limits\na = 0.0\nb = 1.0\n\n# we are doing 3-point quadrature for all methods.  delta is the width\n# of the slab\ndelta = 0.5\n\n\n# trapezoidal\ntrap = 0.5*delta*(f(a) + f(0.5*(a+b))) + 0.5*delta*(f(0.5*(a+b)) + f(b))\n\n# Simpson's\nsimp = (delta/3.0)*(f(a) + 4.0*f(0.5*(a+b)) + f(b))\n\n\n# Gauss-Legendre\n\n# we need to convert from [-1, 1] (the range in which the roots are\n# found) to [a, b] (the range in which our integrand is defined), so\n# convert the roots z1, z2, and z3\n\nz1 = -math.sqrt(3./5.)\nx1 = x(z1, a, b)\nw1 = 5./9.\n\nz2 = 0\nx2 = x(z2, a, b)\nw2 = 8./9.\n\nz3 = math.sqrt(3./5.)\nx3 = x(z3, a, b)\nw3 = 5./9.\n\n# 3-point Gauss-Legendre quadrature -- note the factor in the front\n# is a result of the change of variables from x -> z\nintegral = 0.5*(b-a)*( w1*f(x1) + w2*f(x2) + w3*f(x3) )\n\nprint \"erf(1) (exact):         \", true\nprint \"3-point trapezoidal:    \", trap, trap-true\nprint \"3-point Simpson's:      \", simp, simp-true\nprint \"3-point Gauss-Legendre: \", integral, integral-true\n\n", "meta": {"hexsha": "fd6d24f8ab358349e93f0d269459478f19c2b312", "size": 1557, "ext": "py", "lang": "Python", "max_stars_repo_path": "others/differentiation_integration/erf.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "others/differentiation_integration/erf.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/differentiation_integration/erf.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 21.9295774648, "max_line_length": 75, "alphanum_fraction": 0.6056518947, "include": true, "reason": "from scipy", "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813476288299, "lm_q2_score": 0.9005297887874625, "lm_q1q2_score": 0.8608896810649439}}
{"text": "import numpy as np\nmy_list = [1,2,3,4,5,6]\n\nprint(my_list)\n\n#creating single dimension array of vector by casting python list to numPy array\nnpvector = np.array(my_list)\n\nprint(npvector)\n\nmy_mat = [[1,2,3],[4,5,6],[7,8,9]]\n\nnptwodarray = np.array(my_mat)\n\nprint(nptwodarray)\n\nprint(np.arange(0,10))# python range like function to generate vector array\n\nprint(np.arange(0,10, 2))#with step\n\nprint(np.zeros(3))#generate single/vector array using zeros\n\nprint(np.zeros((3,3)))#generate 2d/matrix array using zeros or ones and passing arg as tuple\n\nprint(np.ones((3,3)))\n\nprint(np.linspace(0,5,10))\n\nprint(np.eye(3))\n\nprint(np.random.rand(5))\n\nprint(np.random.rand(3,3))\n\nprint(np.random.randn(3,3))\n\nprint(np.random.randn(3))\n\nprint(np.random.randint(0,10,3))\n\nrangearr = np.arange(0,25)\nprint(rangearr)\nprint(rangearr.reshape((5,5)))\nprint(rangearr.min())\nprint(rangearr.max())\nprint(rangearr.argmax())\nprint(rangearr.argmin())\n\nprint(\"Index and Selection\")\n#numpy indexing and selection\nindexarr = np.arange(0,11)\nprint(indexarr)\n#indexing\nprint(indexarr[7])\n#slicing\nprint(indexarr[2:4])\n#slicing will change original instance as below\nslice_of_arr = indexarr[0:5]\nprint(slice_of_arr)\nslice_of_arr[:] = 0\nprint(slice_of_arr)\nprint(indexarr)\n#to avoid use copy\nindexarr_copy = indexarr.copy()\nprint(indexarr)\nprint(indexarr_copy)\nindexarr_copy[:]=1\nprint(indexarr_copy)\nprint(indexarr)\n\narr_2d = np.array([[5,10,15], [20, 25, 30], [35, 40, 45]])\nprint(arr_2d)\nprint(arr_2d[1][1])\nprint(arr_2d[1,1])\n\n#grabbing sub matrix from matrix\nprint(arr_2d[:2,1:])\nprint(arr_2d[:2,:2])\n\n#boolean array using comparator operator\nnormal_arr = np.arange(1, 11)\nprint(normal_arr)\nbool_arr = normal_arr > 3\nprint(bool_arr)\n\n#grabbing from normal array from bool_arr\nprint(normal_arr[bool_arr])\nprint(normal_arr[normal_arr>4])\n\nnew_2d_array = np.arange(50).reshape(5,10)\nprint(new_2d_array)\nprint(new_2d_array[2:4,2:4]) #new_2d_array([from_row:to_row,from_col,to_col])\n\n#numpy operation\nprint(\"numpy operation\")\n\nop_arr = np.arange(0,10)\nprint(op_arr + op_arr)\nprint(op_arr - op_arr)\nprint(op_arr * op_arr)\nprint(op_arr / 2)\nprint(op_arr / op_arr)\n", "meta": {"hexsha": "c8f669862e7161ec4587eb2df813387e1e6c7b83", "size": 2130, "ext": "py", "lang": "Python", "max_stars_repo_path": "numPy.py", "max_stars_repo_name": "ingleashish/python-data-science-machine-learning", "max_stars_repo_head_hexsha": "46fb3daf8cccc4444cc92ab0d48f92604061d5c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numPy.py", "max_issues_repo_name": "ingleashish/python-data-science-machine-learning", "max_issues_repo_head_hexsha": "46fb3daf8cccc4444cc92ab0d48f92604061d5c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numPy.py", "max_forks_repo_name": "ingleashish/python-data-science-machine-learning", "max_forks_repo_head_hexsha": "46fb3daf8cccc4444cc92ab0d48f92604061d5c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6796116505, "max_line_length": 92, "alphanum_fraction": 0.7394366197, "include": true, "reason": "import numpy", "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.9304582564583618, "lm_q1q2_score": 0.8608878507805687}}
{"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nimport sympy\nfrom sympy.abc import x, y\n\n\nXMIN = -3\nXMAX = 3\nRADIUS = 1.0\nN = 25\n    \n    \ndef cylinder_stream_function(U=1, R=1):\n    r = sympy.sqrt(x**2 + y**2)\n    theta = sympy.atan2(y, x)\n    return U * (r - R**2 / r) * sympy.sin(theta)\n    \ndef velocity_field(psi):\n    \"\"\" u, v -> give U or V vector component for position X/Y \"\"\"\n    \n    u = sympy.lambdify((x, y), psi.diff(y), 'numpy')\n    v = sympy.lambdify((x, y), -psi.diff(x), 'numpy')\n    return u, v\n    \ndef plot_streamlines(ax, u, v, xlim=(-1, 1), ylim=(-1, 1)):\n    x0, x1 = xlim\n    y0, y1 = ylim\n    Y, X =  np.ogrid[y0:y1:25j, x0:x1:25j]\n    U = u(X,Y)\n    V = v(X,Y)\n    ax.streamplot(X, Y, u(X, Y), v(X, Y), density=2, color='cornflowerblue')\n    #ax.quiver(X,Y,u(X,Y),v(X,Y))\n    \ndef compute_components(domask):\n    \"\"\" Returns:\n    \n    x: 1-D array with x coordinates\n    y: 1-D array with y coordinates\n    u: 2-D array with x vector components\n    v: 2-D array with y vector components\n    \"\"\"\n    \n\n    \n    uf, vf = velocity_field(cylinder_stream_function(R=RADIUS))\n\n    y, x = np.ogrid[XMIN:XMAX:N*1j, XMIN:XMAX:N*1j]\n    \n    u = uf(x,y)\n    v = vf(x, y)\n    \n    xx, yy = np.mgrid[XMIN:XMAX:N*1j, XMIN:XMAX:N*1j]\n    \n    r = np.sqrt(xx**2 + yy**2)\n    \n    mask = r <= RADIUS\n    \n    if domask:\n        u[mask] = 0\n        v[mask] = 0\n    \n    x = x.reshape((N,))\n    y = y.reshape((N,))\n    \n    return x, y, u, v\n    \n\ndef makeplot(show=False):\n\n    x, y, u, v = compute_components(True)\n    \n    np.savetxt('streamlines_u.txt', u)\n    np.savetxt('streamlines_v.txt', v)\n    \n    if show:\n        mag = np.sqrt(u**2 + v**2)\n    \n        plt.figure(1)\n        plt.clf()\n        plt.axes(aspect=True)#, axisbg='#444444')\n    \n        print x.shape\n        plt.streamplot(x,y,u,v,color=mag,cmap='Blues',density=1.5, arrowsize=2)\n        plt.colorbar().set_label(\"Flow speed\")\n    \n        c = plt.Circle((0,0), radius=RADIUS, facecolor='#aaaacc', linewidth=0, zorder=10)\n        plt.gca().add_patch(c)\n        plt.xlim(-3,3)\n        plt.ylim(-3,3)\n    \n\n", "meta": {"hexsha": "edcd91508696a94a088834ff23ac8aa82183a12f", "size": 2097, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/stream.py", "max_stars_repo_name": "advancedplotting/aplot", "max_stars_repo_head_hexsha": "f00d6bdde8d2fa0736b2daf69ee81baba0b0e06f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-01-06T09:35:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:24:14.000Z", "max_issues_repo_path": "examples/stream.py", "max_issues_repo_name": "advancedplotting/aplot", "max_issues_repo_head_hexsha": "f00d6bdde8d2fa0736b2daf69ee81baba0b0e06f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/stream.py", "max_forks_repo_name": "advancedplotting/aplot", "max_forks_repo_head_hexsha": "f00d6bdde8d2fa0736b2daf69ee81baba0b0e06f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2015-09-01T18:33:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T21:53:02.000Z", "avg_line_length": 22.7934782609, "max_line_length": 89, "alphanum_fraction": 0.5417262756, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769063954521, "lm_q2_score": 0.8824278587245935, "lm_q1q2_score": 0.860876240531702}}
{"text": "from math import sin, pi\nfrom scipy.integrate import quad, dblquad, nquad\n\n# Quad Function:\n\nf = lambda x: x*sin(x)  # Equation to be integrated\na = 0                   # Lower limit\nb = pi/2                # Upper limit\n\nI,_ = quad(f, a, b)     # Neglects the 2nd return which is estimated abs error\n\nprint('I,_ = quad(f, ', a,', %f)' %b, sep='')\nprint('I   = %f' % I, end='\\n\\n')\n\n# DblQuad Function:\n\nfn = lambda x, y: x**2 * y + x * y**2   # Equation to be integrated\nax = 1                                  # Lower limit of inner integral\nbx = 2                                  # Upper limit of inner integral\nay = -1                                 # Lower limit of outer integral\nby = 1                                  # Upper limit of outer integral\n\nI,_ = dblquad(fn, ax, bx, lambda y:ay, lambda y:by)\n\nprint('I,_ = dblquad(fn, ', ax, ', ', bx, ', lambda y:', ay, \\\n      ', lambda y:', by, ')', sep='')\nprint('I   = %f' % I, end='\\n\\n')\n\n# NQuad Function:\n\nI,_ = nquad(f, [[0, pi/2]])\n\nprint('I,_ = nquad(f, [[0, pi/2]])')\nprint('I   = %f' % I, end='\\n\\n')\n\nI,_ = nquad(fn, [[ax, bx], [ay, by]])\n\nprint('I,_ = nquad(fn, [[',ax,', ',bx,'], [',ay,', ',by,']])', sep='')\nprint('I   = %f' % I)\n", "meta": {"hexsha": "ef58c156c00f2dc78a347cc14d5b1c7bde202be7", "size": 1202, "ext": "py", "lang": "Python", "max_stars_repo_path": "4. Numerical Integration (Quadrature)/0. Numerical Integration functions of SciPy.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4. Numerical Integration (Quadrature)/0. Numerical Integration functions of SciPy.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4. Numerical Integration (Quadrature)/0. Numerical Integration functions of SciPy.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.05, "max_line_length": 78, "alphanum_fraction": 0.4767054908, "include": true, "reason": "from scipy", "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140235181257, "lm_q2_score": 0.8902942275774318, "lm_q1q2_score": 0.8608379737018564}}
{"text": "import sympy as sp\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Symbolic function and derivatives\nh, t = sp.symbols('h t');\nh = sp.exp(3*t)*t**2;\nhp = h.diff(t);\n#hpp = hp.diff(t);\n\n# Taylor expansions around point t0\nt0 = 1;\nh0 = h.subs(t,t0);\nh1 = h0 + hp.subs({t:t0})*(t-t0);\n#h2 = h0 + hp.subs(t,t0)*(t-t0) + 1/2*hpp.subs(t,t0)*(t-t0)**2;\n\n# Direct Taylor expansion using sympy\nh5s = sp.series(h, t, t0, 6).removeO();\nprint(\"Taylor 5: \", h5s);\n\n# Convert symbolic to functions that can be evaluated\nlam_h = sp.lambdify(t, h, modules=['numpy']);\nlam_h1 = sp.lambdify(t, h1, modules=['numpy']);\nlam_h5s = sp.lambdify(t, h5s, modules=['numpy']);\n\n# Plots\nfig, ax = plt.subplots(1,1);\nt_vals = np.linspace(0.5, 1.5, 100);\nax.plot(t_vals, lam_h(t_vals), 'r');\nax.plot(t_vals, lam_h1(t_vals), 'g');\n#ax.plot(t_vals, lam_h5s(t_vals), 'b');\n\n# Symbolic plotting also probably works\n#sp.plot(h, h1, (t, 0, 1.5))\n", "meta": {"hexsha": "db1293daf7819f680969cefc00ca8440bd22a6f8", "size": 916, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/lab_taylorexp-1.py", "max_stars_repo_name": "maxnvdm/notebooks", "max_stars_repo_head_hexsha": "c719a43d02e330bdc25dceea33d5e6c2b156e02d", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-07-17T09:03:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T05:28:21.000Z", "max_issues_repo_path": "src/lab_taylorexp-1.py", "max_issues_repo_name": "maxnvdm/notebooks", "max_issues_repo_head_hexsha": "c719a43d02e330bdc25dceea33d5e6c2b156e02d", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lab_taylorexp-1.py", "max_forks_repo_name": "maxnvdm/notebooks", "max_forks_repo_head_hexsha": "c719a43d02e330bdc25dceea33d5e6c2b156e02d", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2017-08-21T12:06:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T16:52:18.000Z", "avg_line_length": 26.1714285714, "max_line_length": 63, "alphanum_fraction": 0.6451965066, "include": true, "reason": "import numpy,import sympy", "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971992476960077, "lm_q2_score": 0.885631484383387, "lm_q1q2_score": 0.860827140179638}}
{"text": "\nimport numpy as np \n\n'''\nProof of concept: Logits and softmax probability computations\n'''\n\ndef softmax(logits):\n    \n    softmax = []\n    q = 0\n    for i in logits:\n        softmax.append(np.exp(i) / sum(np.exp(logits)))\n        q += np.exp(i) / sum(np.exp(logits))\n    \n    return softmax, q\n\ndef logits_func(prob): \n    return np.log(prob / (1+prob))\n\nproba = [0.006382342879717207, 0.2564389982593307, 0.04506310418417042, 0.08901875647497302, 0.0920775142662204, \n        0.04941506219220917, 0.16701976595076282, 0.06772062316943511, 0.22686383262318108]\nlogits = [-5.053441047668457, -1.3600854873657227, -3.098912477493286, -2.4181292057037354, -2.384345531463623, \n        -3.006721019744873, -1.7888641357421875, -2.6915855407714844, -1.4826263189315796]\n\n\nsoftmax(logits)\n\nfor i in proba: \n    print(logits_func(i))\n\n\n\n\ndef logit2prob(logit):\n    return np.exp(logit) / (np.exp(logit) + 1)\n\n# x2 samples of > 0.5\nlogits = [-4.636117458343506, -4.46367883682251, -3.3428733348846436, 2.175978183746338, -4.3089518547058105, \n        -4.214722633361816, -5.114277362823486, 2.573429822921753, -4.526679039001465]\n\n\n\n\nfor i in logits: \n    print(logit2prob(i))\n", "meta": {"hexsha": "ba9198d8ed66321178eac7e3551fd42a4c98f5f6", "size": 1170, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/logits_probability.py", "max_stars_repo_name": "JKrse/LUKE_thesis", "max_stars_repo_head_hexsha": "00dcae049f6ef1fe92f1a77fdc13d373fdbca100", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-12T10:59:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-16T11:19:55.000Z", "max_issues_repo_path": "tests/logits_probability.py", "max_issues_repo_name": "JKrse/LUKE_thesis", "max_issues_repo_head_hexsha": "00dcae049f6ef1fe92f1a77fdc13d373fdbca100", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/logits_probability.py", "max_forks_repo_name": "JKrse/LUKE_thesis", "max_forks_repo_head_hexsha": "00dcae049f6ef1fe92f1a77fdc13d373fdbca100", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8936170213, "max_line_length": 113, "alphanum_fraction": 0.6923076923, "include": true, "reason": "import numpy", "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924761487654, "lm_q2_score": 0.8856314632529872, "lm_q1q2_score": 0.8608271189225254}}
{"text": "#=============================================================================#\n#\n#    File:   sieve_of_eratosthenes.py\n#    Author: Jack Morgan\n#    Date:   May 2021\n#    Description:\n#        Uses a sieve to find all of the prime numbers up to a limit\n#        Three versions, each faster than the last\n#\n#=============================================================================#\n\n\nimport numpy as np\nfrom time import time\nfrom math import sqrt, ceil\n\n# print the prime numbers up to limit\n# first version\ndef sieve_of_eratosthenes_1(limit):\n    possible_primes = [True for _ in range(limit)]\n    possible_primes[0] = possible_primes[1] = False\n    for index, isprime in enumerate(possible_primes):\n        if isprime:\n            yield index\n            for i in range(index**2, limit, index):\n                possible_primes[i] = False\n    return possible_primes\n\n\n#second version\ndef sieve_of_eratosthenes_2(limit):\n    possible_primes = np.ones(limit)\n    possible_primes[0:2:1] = 0\n    for (i, isprime) in enumerate(possible_primes):\n        if bool(isprime):\n            yield i\n            possible_primes[i*i:limit:i] = 0\n\n\n# third version\ndef sieve_of_eratosthenes_3(limit):\n    possible_primes = np.ones(limit, dtype=bool)\n    possible_primes[0:2:1] = False\n    for i in range(2, ceil(sqrt(limit))):\n        possible_primes[i*i:limit:i] = False\n    return np.flatnonzero(possible_primes)\n\n\ndef main():\n    limit = 1*10**6\n\n    start1 = time()\n    print(list(sieve_of_eratosthenes_1(limit)))\n    end1 = time()\n\n    start2 = time()\n    print(list(sieve_of_eratosthenes_2(limit)))\n    end2 = time()\n\n    start3 = time()\n    print(sieve_of_eratosthenes_3(limit))\n    end3 = time()\n\n    print(f'time 1: {end1-start1} seconds')\n    print(f'time 2: {end2-start2} seconds')\n    print(f'time 3: {end3-start3} seconds')\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "c4920c7d366a0d47b9edefb56c9981d33a585757", "size": 1867, "ext": "py", "lang": "Python", "max_stars_repo_path": "Prototypes/Algorithms/sieve_of_eratosthenes.py", "max_stars_repo_name": "jackm245/Visualising-and-Investigating-the-Riemann-Hypothesis", "max_stars_repo_head_hexsha": "6eff14b6503cb2faf3bd8b0785239b690bce368a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-01T19:07:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-18T07:34:42.000Z", "max_issues_repo_path": "Prototypes/Algorithms/sieve_of_eratosthenes.py", "max_issues_repo_name": "jackm245/Visualising-and-Investigating-the-Riemann-Hypothesis", "max_issues_repo_head_hexsha": "6eff14b6503cb2faf3bd8b0785239b690bce368a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Prototypes/Algorithms/sieve_of_eratosthenes.py", "max_forks_repo_name": "jackm245/Visualising-and-Investigating-the-Riemann-Hypothesis", "max_forks_repo_head_hexsha": "6eff14b6503cb2faf3bd8b0785239b690bce368a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2957746479, "max_line_length": 79, "alphanum_fraction": 0.5961435458, "include": true, "reason": "import numpy", "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.9184802429095672, "lm_q1q2_score": 0.8608095937344458}}
{"text": "import numpy as np\nfrom numpy import exp\nfrom numpy import polyfit\nfrom numpy import log\nimport matplotlib.pyplot as plt\n\nRImageDistance,RObjectDistance,Magnification,ObjectDistance = np.loadtxt(r\"2021.11.25 Lenses - Computing/lenses-experiment-a.csv\",delimiter=\",\",skiprows=1,unpack=True) \nfont = {'fontname':'CMU Serif'}                                                                             # Assign font parameters\nfontAxesTicks = {'size':7}\n\n\n    ## 1/s against 1/s'\npolyfitA,cov_polyfitA = np.polyfit(RObjectDistance,RImageDistance,1,cov=True)\nplt.xlabel(\"Object Distance¯¹ / m¯¹\", **font)                                                                        # Label axes, add titles and error bars\nplt.ylabel(\"Image Distance¯¹ / m¯¹\", **font)\nplt.xticks(**font, **fontAxesTicks)\nplt.yticks(**font, **fontAxesTicks)\nplt.title(\"Experiment A: 1/s against 1/s'\", **font)\nplt.plot(RObjectDistance,RImageDistance,'x')\nplt.plot(RObjectDistance, (polyfitA[0]*RObjectDistance+polyfitA[1]))\nplt.show()\nprint(polyfitA)\n\npolyfitB,cov_polyfitB = np.polyfit(RImageDistance,RObjectDistance,1,cov=True)\nplt.xlabel(\"Image Distance¯¹ / m¯¹\", **font)                                                                        # Label axes, add titles and error bars\nplt.ylabel(\"Object Distance¯¹ / m¯¹\", **font)\nplt.xticks(**font, **fontAxesTicks)\nplt.yticks(**font, **fontAxesTicks)\nplt.title(\"Experiment A: 1/s against 1/s'\", **font)\nplt.plot(RImageDistance,RObjectDistance,'x')\nplt.plot(RImageDistance, (polyfitB[0]*RImageDistance+polyfitB[1]))\nplt.show()\nprint(polyfitB)\n\n    ## M against s\n#polyfitB,cov_polyfitB = np.polyfit(b,h,1,cov=True)\nplt.xlabel(\"Object Distance / m\", **font)                                                                        # Label axes, add titles and error bars\nplt.ylabel(\"Magnification / no units\", **font)\nplt.xticks(**font, **fontAxesTicks)\nplt.yticks(**font, **fontAxesTicks)\nplt.title(\"Experiment A: M against s'\", **font)\n#plt.errorbar(f,e, yerr=((1/(f+0.1))-(1/(f-0.1))),xerr=(1/(e+0.1)-1/(e-0.1)),ls='',mew=1.5,ms=3,capsize=3)                         # Plots uncertainties in points\nplt.plot(ObjectDistance,Magnification,'x')\n#plt.plot(f, (polyfitA[0]*f+polyfitA[1]))\nplt.show()\n\n''' plt.plot(1/objectDistance, 1/imageDistance,'x')\npolyfitA,cov_polyfitA = np.polyfit(1/objectDistance,1/imageDistance,2,cov=True)    \n#plt.plot(1/objectDistance, (polyfitA[0]*(1/objectDistance)**2+polyfitA[1]*(1/objectDistance)+polyfitA))\nplt.xlabel(\"Time (t) / s\", **font)                                                                          # Label axes, add titles and error bars\nplt.ylabel(\"Natural Log of Voltage (ln V) / V\", **font)\nplt.xticks(**font, **fontAxesTicks)\nplt.yticks(**font, **fontAxesTicks)\n#plt.errorbar(distanceDS, grayValueDS,yerr=0,xerr=0,ls='',mew=1.5,ms=3,capsize=3)\nplt.title(\"Small Capacitor, Discharging (Linear)\", **font)\nplt.show() '''", "meta": {"hexsha": "ffca8dc5c2cf51ce08a78e4475c32f116c9cac6c", "size": 2890, "ext": "py", "lang": "Python", "max_stars_repo_path": "lenses-data-analysis.py", "max_stars_repo_name": "martin-he543/first-year-data-analysis", "max_stars_repo_head_hexsha": "cd316b57d5fb704aa1083ff6f6764e16a0617e53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-09T08:17:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T18:38:59.000Z", "max_issues_repo_path": "lenses-data-analysis.py", "max_issues_repo_name": "martin-he543/first-year-data-analysis", "max_issues_repo_head_hexsha": "cd316b57d5fb704aa1083ff6f6764e16a0617e53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lenses-data-analysis.py", "max_forks_repo_name": "martin-he543/first-year-data-analysis", "max_forks_repo_head_hexsha": "cd316b57d5fb704aa1083ff6f6764e16a0617e53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.6071428571, "max_line_length": 168, "alphanum_fraction": 0.6269896194, "include": true, "reason": "import numpy,from numpy", "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446502128797, "lm_q2_score": 0.8840392771633079, "lm_q1q2_score": 0.8607401127881159}}
{"text": "from scipy.integrate import odeint\nclass SIS:\n\n\tsets = ['S', 'I', 'N']\n\tparams = ['beta', 'gamma']\n\tequations = {\n\t\t'S' : lambda S,I,N,_S,_I,_N,beta,gamma: f' -({beta} * {S} * {_I}) / ({_N}) + {gamma} * {I}',\n\t\t'I' : lambda S,I,N,_S,_I,_N,beta,gamma: f' ({beta} * {S} * {_I}) / ({_N}) - {gamma} * {I}',\n\t\t'N' : lambda S,I,N,_S,_I,_N,beta,gamma: f' 0',\n\t}\n\n\t@staticmethod\n\tdef deriv(y, t, params):\n\t\tS, I, N = y\n\t\tbeta, gamma = params\n\t\tdSdt = -(beta * S * I) / (N) + gamma * I\n\t\tdIdt = (beta * S * I) / (N) - gamma * I\n\t\tdNdt = 0\n\t\treturn dSdt, dIdt, dNdt\n\n\t@staticmethod\n\tdef solve(y, t, params):\n\t\treturn odeint(SIS.deriv, y, t, args=(params,))\n", "meta": {"hexsha": "c015fb6c345e59629024bc5e8570e51d2c74de45", "size": 647, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/cmodel/repo/SIS.py", "max_stars_repo_name": "Maximiza-Atemoriza/meta-population-network-model", "max_stars_repo_head_hexsha": "7dfde8d92c50935a963c919227058c99fcd0c649", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cmodel/repo/SIS.py", "max_issues_repo_name": "Maximiza-Atemoriza/meta-population-network-model", "max_issues_repo_head_hexsha": "7dfde8d92c50935a963c919227058c99fcd0c649", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-17T20:59:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T20:59:51.000Z", "max_forks_repo_path": "tests/cmodel/SIS.py", "max_forks_repo_name": "Maximiza-Atemoriza/meta-population-network-model", "max_forks_repo_head_hexsha": "7dfde8d92c50935a963c919227058c99fcd0c649", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9583333333, "max_line_length": 94, "alphanum_fraction": 0.5285935085, "include": true, "reason": "from scipy", "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97364464868338, "lm_q2_score": 0.8840392695254318, "lm_q1q2_score": 0.8607401039994008}}
{"text": "\nimport numpy as np\nimport random\n\ndef inference (w,b,x):\n    pred_y=w*x+b\n    return pred_y\n\ndef gradient (pred_y,gt_y,x):\n    dw=(pred_y-gt_y)*x\n    db=pred_y-gt_y\n    return  dw, db\n\ndef theta_step_update (batch_x_list, batch_gt_y_list, w, b, lr):\n    avg_dw=0\n    avg_db=0\n    batch_size=len(batch_x_list)\n\n    for i in range (batch_size):\n        pred_y=inference(w,b,batch_x_list[i])\n        dw,db=gradient(pred_y,batch_gt_y_list[i],batch_x_list[i])\n        avg_dw+= dw\n        avg_db+= db\n    avg_dw/=batch_size\n    avg_db/=batch_size\n\n    #update simultanously\n    w=w-lr*avg_dw\n    b=b-lr*avg_db\n\n    return w,b\n\ndef loss_function (batch_x_list, batch_gt_y_list, w, b):\n    batch_size=len(batch_x_list)\n    sum_loss=0\n    for i in range (batch_size):\n        single_loss=(w*batch_x_list[i]+b-batch_gt_y_list[i])**2\n        sum_loss+=single_loss\n    J=sum_loss/2*batch_size\n    return J\n\ndef train(x_list, gt_y_list, batch_size,lr, maxIrr):\n    #initial setup: pick up a starting point for (w,b);\n    w=0\n    b=0\n    total_size=len(x_list)\n\n    # randomly choose batch size of samples from the whole data\n    # throw the batch into the iteration as training data for each round\n    for i in range (maxIrr):\n        batch_idx=np.random.choice(total_size,batch_size)\n        batch_x_list=[x_list[j] for j in batch_idx]\n        batch_gt_y_list=[gt_y_list[j] for j in batch_idx]\n        w,b=theta_step_update(batch_x_list,batch_gt_y_list,w,b,lr)\n        J=loss_function(batch_x_list,batch_gt_y_list,w,b)\n        print('w:{0}, b:{1}'.format(w, b))\n        print('loss: {0}'.format(J))\n    return w,b,J\n\ndef generate_data(num_samples):\n    w=random.randint(0,10)+random.random()\n    b=random.randint(0,5)+random.random()\n    x_list=[]\n    gt_y_list=[]\n    for i in range (num_samples):\n        x = random.randint(0, 100) * random.random()\n        y=w*x+b+random.random()* random.randint(-1, 1)\n        x_list.append(x)\n        gt_y_list.append(y)\n    return w,b,x_list,gt_y_list\n\ndef run(num_samples, batch_size,lr,maxIrr):\n    w0,b0,x_list,gt_y_list=generate_data(num_samples)\n    w,b,J=train(x_list, gt_y_list, batch_size,lr, maxIrr)\n    print ('original w: {0}, b:{1}'.format(w0,b0))\n    print ('estimated w: {0}, b:{1}'.format(w,b))\n    print ('final loss J: {0}'.format(J))\n\nif __name__=='__main__':\n    num_samples=100\n    batch_size=50\n    lr=0.001\n    maxIrr=10000\n    run(num_samples, batch_size,lr,maxIrr)\n\n\n", "meta": {"hexsha": "2d676510dacffb9d3240814e275e619188c6fdac", "size": 2420, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_regression/gd_v1.py", "max_stars_repo_name": "Mary-xl/cv_tools", "max_stars_repo_head_hexsha": "a673231b829b2059ede8819e69eb55ace522c524", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_regression/gd_v1.py", "max_issues_repo_name": "Mary-xl/cv_tools", "max_issues_repo_head_hexsha": "a673231b829b2059ede8819e69eb55ace522c524", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_regression/gd_v1.py", "max_forks_repo_name": "Mary-xl/cv_tools", "max_forks_repo_head_hexsha": "a673231b829b2059ede8819e69eb55ace522c524", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.816091954, "max_line_length": 72, "alphanum_fraction": 0.6561983471, "include": true, "reason": "import numpy", "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611654370414, "lm_q2_score": 0.8962513800615313, "lm_q1q2_score": 0.8607250198804489}}
{"text": "import numpy\nimport random\nimport time\n\ndef integral_function(x): \n    return(1/(numpy.cos(x) + 2))\n    # result: https://www.wolframalpha.com/input/?i=integrate+1%2F(cos(x)+%2B+2)+from+0+to+6\n\ndef monte_carlo(xmin, xmax, ymin, ymax, N):\n    whole_area = (xmax - xmin) * (ymax - ymin)\n    points = 0 \n\n    time_start = time.time()\n\n    for i in range(N):\n        x = xmin + (xmax - xmin) * random.random()\n        y = ymin + (ymax - ymin) * random.random()\n\n        if integral_function(x) > 0 and y > 0 and y <= integral_function(x):\n            points += 1\n\n    time_stop = time.time()\n    total_time = time_stop - time_start\n    result = whole_area * points / N\n    \n    return {'result': result, 'time': total_time, 'N': N}\n\n# define limits\nxmin = 0\nxmax = 6\nymin = 0\nx = numpy.linspace(xmin, xmax, 1000)\nymax = max(integral_function(x)) + 0.5 * max(integral_function(x))\nNmin = 100\nNmax = 10000\n\nwhile Nmin <= Nmax:\n    calc = monte_carlo(xmin, xmax, ymin, ymax, Nmin)\n    print(\"Result: \", calc['result'], \"Total time:\", calc['time'], \"N = \", calc['N']) \n    Nmin = Nmin * 10 \n", "meta": {"hexsha": "d530f0cb8e548102c8f4343cccd35c7a5e1cf2ec", "size": 1083, "ext": "py", "lang": "Python", "max_stars_repo_path": "monteCarlo.py", "max_stars_repo_name": "mikhail911/monteCarloIntegration", "max_stars_repo_head_hexsha": "dc2b01ca005a35d482b7401daf8df51d1aff5f71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "monteCarlo.py", "max_issues_repo_name": "mikhail911/monteCarloIntegration", "max_issues_repo_head_hexsha": "dc2b01ca005a35d482b7401daf8df51d1aff5f71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "monteCarlo.py", "max_forks_repo_name": "mikhail911/monteCarloIntegration", "max_forks_repo_head_hexsha": "dc2b01ca005a35d482b7401daf8df51d1aff5f71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4146341463, "max_line_length": 92, "alphanum_fraction": 0.6038781163, "include": true, "reason": "import numpy", "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.8962513759047848, "lm_q1q2_score": 0.8607250097876723}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 28 14:21:06 2019\n\n@author: alankar\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef derivative(func,x,*args): #function to find the derivative of the polynomial\n    h = 1e-4\n    derivative = (func(x + h,*args) - func(x-h,*args)) / (2*h)\n    return derivative\n\ndef NR(func,x0,tol,*args): #Newton Raphson\n    x_new = 0\n    x_old = x0\n    while(np.abs(x_new-x_old)>=tol):\n        x_new = x_old - func(x_old,*args)/derivative(func,x_old,*args)\n        x_old = x_new\n    return x_new\n\ndef f(x):\n    return 924*x**6-2772*x**5+3150*x**4-1680*x**3+420*x**2-42*x+1\n\nx = np.linspace(0,1,500)\nplt.plot(x,f(x))\nplt.xlabel(r'$x$',size=18)\nplt.ylabel(r'$f(x)=924x^6-2772x^5+3150x^4-1680x^3+420x^2-42x+1$',size=18)\nplt.grid()\n#plt.savefig('poly.png')\nplt.show()\n\nprint ('Roots are ')\nx0 = [0.03,0.17,0.38,0.62,0.83,0.97]\nfor i in range(len(x0)):\n    print( '%.10f'%NR(f,x0[i],1.e-10))\n\n\"\"\"\nOutput\n\nRoots are \n0.0335761962\n0.1693944272\n0.3806901845\n0.6193098155\n0.8306055728\n0.9664238038\n\"\"\"", "meta": {"hexsha": "a53541b9f87753f9bac62bb14fbb6193c8e328ab", "size": 1057, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw2/08/8.py", "max_stars_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_stars_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:47:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:05:39.000Z", "max_issues_repo_path": "hw2/08/8.py", "max_issues_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_issues_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw2/08/8.py", "max_forks_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_forks_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-21T17:33:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T02:58:56.000Z", "avg_line_length": 20.7254901961, "max_line_length": 80, "alphanum_fraction": 0.6357615894, "include": true, "reason": "import numpy", "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611597645271, "lm_q2_score": 0.8962513745192024, "lm_q1q2_score": 0.8607250094738128}}
{"text": "import numpy as np\r\nimport time\r\nimport pandas as pd\r\n\r\n\r\ndef main():\r\n    # initi conditions---------------------------------------------------------\r\n    A=2\r\n    B=0.01\r\n    t0=0.0\r\n    t_end=5\r\n    #--------------------------------------------------------------------------\r\n\r\n    # Analytic solution\r\n    analytic = lambda t_ini, y_ini, t, a, b: 1/(b/a+(1/y_ini-b/a)*np.exp(-a*(t-t_ini)))\r\n    #--------------------------------------------------------------------------\r\n    # ODE\r\n    f = lambda y: A*y-B*y*y\r\n    #--------------------------------------------------------------------------\r\n    # initial valuse\r\n    y0_list = np.array([8, 10, 12])\r\n    #y0_list = np.array([100, 190, 250])\r\n    #--------------------------------------------------------------------------\r\n\r\n    timesteps = np.array([0.05, 0.025, 0.0125, 0.00625, 0.003125])\r\n\r\n    # maps of 4th order for different time steps (A=2, B=0.01)\r\n    # M(0,:) is map for dt=0.05     (N=100)\r\n    # M(1,:) is map for dt=0.025    (N=200)\r\n    # M(2,:) is map for dt=0.0125   (N=400)\r\n    # M(3,:) is map for dt=0.00625  (N=800)\r\n    # M(4,:) is map for dt=0.003125 (N=1600)\r\n\r\n    Maps = np.array([[-9.74718510761581e-11,2.82830795154941e-7,-0.00057683855758959,1.1047522448889,0.0164019262867156],\r\n                    [-1.379332373516e-11,6.75987803436825e-8,-0.00026920890283235,1.05124251835198,0.00113151812515],\r\n                    [-1.83493448551926e-12,1.63316814751669e-8,-0.00012976106224663,1.0253132530535,7.43225401875509e-5],\r\n                    [-2.36633829318494e-13,3.99916101441112e-9,-6.36821468173527e-5,1.01257833218163,4.76237954022738e-6],\r\n                    [-3.00445936310731e-14,9.88470260129351e-10,-3.15443221011727e-5,1.00626956445964,3.0138672729979e-7]\r\n                    ])\r\n\r\n    #--------------------------------------------------------------------------\r\n    # resulting table\r\n    # result(:, 0) is N\r\n    # result(:, 1) is err_RK4\r\n    # result(:, 2) is err_TM4\r\n    # result(:, 3) is time_RK4\r\n    # result(:, 4) is time_TM4\r\n    # result(:, 5) is time_ratio = time_RK4/time_TM4\r\n    result = np.zeros((len(timesteps), 6))\r\n\r\n\r\n    for k, dt in enumerate(timesteps):  # for each time stemp dt\r\n        M = Maps[k, :]                 # get TM for this dt\r\n        N = int((t_end-t0)/dt)\r\n        t = np.arange(t0, t_end, dt)\r\n\r\n        result[k, 0] = N\r\n\r\n        for y0 in y0_list: # for each y0\r\n            # analytic solution------------------------------------------------\r\n            y_sol = analytic(t0, y0, t, A, B)\r\n            #------------------------------------------------------------------\r\n\r\n            # RK4 integration--------------------------------------------------\r\n            y_rk4 = np.zeros(N)\r\n\r\n            y_rk4[0]=y0\r\n            tic = time.time()\r\n            for i in range(N-1):\r\n                y = y_rk4[i]\r\n                k1 = f(y)\r\n                k2 = f(y+dt*k1/2)\r\n                k3 = f(y+dt*k2/2)\r\n                k4 = f(y+dt*k3)\r\n                y_rk4[i+1] = y + dt*(k1+2*k2+2*k3+k4)/6\r\n\r\n            elapsed_time = time.time()-tic\r\n            result[k, 3] += elapsed_time # time_RK4\r\n            #------------------------------------------------------------------\r\n\r\n            # Mapping----------------------------------------------------------\r\n            y_map = np.zeros(N)\r\n            y_map[0] = y0\r\n            tic = time.time()\r\n            for i in range(N-1):\r\n                y=y_map[i]\r\n                y2 = y*y\r\n                y_map[i+1] = (y2*(M[0]*y2 + M[2]) +\r\n                            y *(M[1]*y2 + M[3]) +\r\n                            M[4])\r\n\r\n            elapsed_time = time.time()-tic\r\n            result[k, 4] += elapsed_time # time_RK4\r\n            #------------------------------------------------------------------\r\n            result[k, 1] += np.abs(y_rk4 - y_sol).max() # err_RK4\r\n            result[k, 2] += np.abs(y_map - y_sol).max() # err_TM4\r\n\r\n    result[:, 1:] /= len(y0_list) # get average results\r\n    result[:, 5] = result[:, 3]/result[:, 4] # get time_ratio\r\n\r\n\r\n    result = pd.DataFrame(data=result[:,1:], index=result[:,0], columns=np.array(['err_RK4', 'err_TM4', 'time_RK4', 'time_TM4', 'time_ratio']))\r\n    return result\r\n\r\nif __name__ == \"__main__\":\r\n    print(main())", "meta": {"hexsha": "fae4bbc5cf5ab1ceb68f5571c1072ef17a7d880a", "size": 4273, "ext": "py", "lang": "Python", "max_stars_repo_path": "TM4.py", "max_stars_repo_name": "andiva/PopulationEquation", "max_stars_repo_head_hexsha": "3d6b4edc4ae72f3664214d7776278edf733690ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TM4.py", "max_issues_repo_name": "andiva/PopulationEquation", "max_issues_repo_head_hexsha": "3d6b4edc4ae72f3664214d7776278edf733690ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TM4.py", "max_forks_repo_name": "andiva/PopulationEquation", "max_forks_repo_head_hexsha": "3d6b4edc4ae72f3664214d7776278edf733690ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3113207547, "max_line_length": 144, "alphanum_fraction": 0.4022934706, "include": true, "reason": "import numpy", "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96036116089903, "lm_q2_score": 0.8962513710552469, "lm_q1q2_score": 0.8607250071639642}}
{"text": "# Create by Packetsss\n# Personal use is allowed\n# Commercial use is prohibited\n\nfrom timeit import default_timer as timer\nimport numpy as np\n\n\"\"\"\nHow many possible ways a traveller can travel through a N x M grid?\n\n1x1: [0]\n1 way\n\n1x2: [0, 0]\n1 way\n\n2x2: [0, 0]\n     [0, 0]\n2 ways\n\n\n2x3: [0, 0, 0] == 2 + 1\n     [0, 0, 0]\n3 ways\n\n3x3: [0, 0, 0]    [0, 0, 0]   [0, 0]\n     [0, 0, 0] == [0, 0, 0] + [0, 0] == 2 + 1 + 2 + 1\n     [0, 0, 0]                [0, 0]\n\n6 ways\n\n3x4: [0, 0, 0, 0]    [0, 0, 0]   [0, 0, 0, 0]\n     [0, 0, 0, 0] == [0, 0, 0] + [0, 0, 0, 0] == 6 + 3 + 1\n     [0, 0, 0, 0]    [0, 0, 0]\n\n \n\n\"\"\"\n\n\ndef grid_traveller(n, m):\n    if n == 0 or m == 0:\n        return 0\n    elif n < 2 and m < 2:\n        return min(n, m)\n    else:\n        return grid_traveller(n - 1, m) + grid_traveller(n, m - 1)\n\n\nstart = timer()\nprint(grid_traveller(13, 10))\nend = timer()\nprint(end - start)\n# Slow naive recursive solution\n\n\n### Memoized\nd = {}\ndef grid_traveller_topdown(n, m):\n    key = f\"{n}{m}\"\n    if n == 0 or m == 0:\n        return 0\n    elif n < 2 and m < 2:\n        return min(n, m)\n    elif key in d:\n        return d[key]\n    else:\n        d[key] = grid_traveller_topdown(n - 1, m) + grid_traveller_topdown(n, m - 1)\n        return d[key]\n\n\nstart = timer()\nprint(grid_traveller_topdown(13, 100))\nend = timer()\nprint(end - start)\n\n\n### Tabulation\ndef grid_traveller_bottom_up(n, m):\n    if n == 0 or m == 0:\n        return 0\n\n    lst = np.zeros((n + 1, m + 1))\n    lst[1:, 1] = 1\n    lst[1, 1:] = 1\n\n    for i in range(2, n + 1):\n        for j in range(2, m + 1):\n            lst[i, j] = lst[i - 1, j] + lst[i, j - 1]\n    return int(lst[-1, -1])\n\n\nstart = timer()\nprint(grid_traveller_bottom_up(13, 100))\nend = timer()\nprint(end - start)\n# 2x faster\n\n# best to use 0 for counting problems\ndef grid_traveller_bottom_up_1(n, m):\n    table = [[0 for _ in range(n + 1)] for _ in range(m + 1)]\n    # correct way to create a 2d array\n\n    table[1][1] = 1\n\n    # add the current value of i to it's right and bottom\n    for i in range(1, m + 1):\n        for j in range(1, n + 1):\n            cur = table[i][j]\n            if i < m:\n                table[i + 1][j] += cur\n            if j < n:\n                table[i][j + 1] += cur\n\n    return table[m][n]\n\n\nstart = timer()\nprint(grid_traveller_bottom_up_1(13, 100))\nend = timer()\nprint(end - start)\n", "meta": {"hexsha": "4fafbf2786d54bdd4107ebfce0813ce62813a816", "size": 2351, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python Tutorial Dynamic Programming/2_Grid_Traveller.py", "max_stars_repo_name": "PaulPan00/donkey_wrapper", "max_stars_repo_head_hexsha": "a03cf0f42f65625fbce792b06c98acd153c5d6c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-03-26T01:42:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-11T16:17:42.000Z", "max_issues_repo_path": "Python Tutorial Dynamic Programming/2_Grid_Traveller.py", "max_issues_repo_name": "packetsss/Python", "max_issues_repo_head_hexsha": "a03cf0f42f65625fbce792b06c98acd153c5d6c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python Tutorial Dynamic Programming/2_Grid_Traveller.py", "max_forks_repo_name": "packetsss/Python", "max_forks_repo_head_hexsha": "a03cf0f42f65625fbce792b06c98acd153c5d6c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-04-06T06:55:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-03T11:26:38.000Z", "avg_line_length": 19.2704918033, "max_line_length": 84, "alphanum_fraction": 0.5168013611, "include": true, "reason": "import numpy", "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957277806109987, "lm_q2_score": 0.8991213853793452, "lm_q1q2_score": 0.8607089472225117}}
{"text": "# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np, tensorflow as tf, seaborn as sns, arviz as az, tensorflow_probability as tfp\r\ntf.config.optimizer.set_jit(True)\r\ntfd, tfb = tfp.distributions, tfp.bijectors\r\n\r\ndef snsdistplot(data):\r\n\tg = sns.displot(data, bins = \"sqrt\", kde = True)\r\n\tg.fig.set_figwidth(8)\r\n\tg.fig.set_figheight(6)\r\n\treturn g\r\n\r\ndata = np.loadtxt(\"data/mixture_data.csv\")\r\nsnsdistplot(data)\r\n\r\nvar_name = [\"prob\", \"centers\", \"sigmas\"]\r\n\r\n@tfd.JointDistributionCoroutineAutoBatched\r\ndef mdl_batch():\r\n\tprob = yield tfd.Uniform(low = 0., high = 1., name = var_name[0])\r\n\tcenters = yield tfd.Normal(loc = [120., 190.], scale = [10.]*2, name = var_name[1])\r\n\tsigmas = yield tfd.Uniform(low = [0.]*2, high = [100.]*2, name = var_name[2])\r\n\tcategories = tfd.Categorical(probs = [prob, 1. - prob]) # assignments to a group\r\n\tvalues = tfd.Normal(loc = centers, scale = sigmas) # group\r\n\tmixture = tfd.MixtureSameFamily(mixture_distribution = categories, components_distribution = values)\r\n\tyield tfd.Sample(mixture, sample_shape = len(data), name = \"obs\")\r\n\r\n# a helper function in McMC chain\r\ndef trace_fn(current_state, kernel_results):\r\n\tmdr = kernel_results.inner_results.inner_results\r\n\treturn mdr.target_log_prob, mdr.leapfrogs_taken, mdr.has_divergence, mdr.energy, mdr.log_accept_ratio\r\n\r\n@tf.function(autograph = False, experimental_compile = True) # speed up a lot the McMC sampling\r\ndef run_mcmc( # pass numeric arguments as Tensors whenever possible\r\n\tinit_state, unconstraining_bijectors,\r\n\tnum_steps = 50000, burnin = 10000,\r\n\tnum_leapfrog_steps = 3, step_size = .5\r\n):\r\n\tkernel0 = tfp.mcmc.NoUTurnSampler(\r\n\t\ttarget_log_prob_fn = lambda *args: mdl_batch.log_prob(obs=data, *args),\r\n\t\tstep_size = step_size\r\n\t)\r\n\tkernel1 = tfp.mcmc.TransformedTransitionKernel(\r\n\t\tinner_kernel= kernel0,\r\n\t\tbijector = unconstraining_bijectors\r\n\t)\r\n\tkernel2 = tfp.mcmc.DualAveragingStepSizeAdaptation( # pkr = previous kernel results\r\n\t\tinner_kernel = kernel1,\r\n\t\tnum_adaptation_steps = int(0.8*burnin),\r\n\t\tstep_size_setter_fn = lambda pkr, new_step_size: pkr._replace(inner_results = pkr.inner_results._replace(step_size=new_step_size)),\r\n\t\tstep_size_getter_fn = lambda pkr: pkr.inner_results.step_size,\r\n\t\tlog_accept_prob_getter_fn = lambda pkr: pkr.inner_results.log_accept_ratio\r\n\t)\r\n\t# tf.get_logger().setLevel(\"ERROR\") # multiple chains\r\n\treturn tfp.mcmc.sample_chain( # ATTENTION: 2 values to unpack\r\n\t\tnum_results = num_steps,\r\n\t\tnum_burnin_steps = burnin,\r\n\t\tcurrent_state = init_state,\r\n\t\tkernel = kernel2,\r\n\t\ttrace_fn = trace_fn\r\n\t)\r\n\r\nnchain = 4\r\ninit_state = [mdl_batch.sample(nchain)._asdict()[_] for _ in var_name]\r\nunconstraining_bijectors = [tfb.Identity()]*len(var_name)\r\nsamples, sampler_stat = run_mcmc(init_state, unconstraining_bijectors)\r\n\r\n#%% using the pymc3 naming convention, with log_likelihood instead of lp so that ArviZ can compute loo and waic\r\nsample_stats_name = ['log_likelihood', 'tree_size', 'diverging', 'energy', 'mean_tree_accept']\r\n\r\nsample_stats = {k: v.numpy().T for k, v in zip(sample_stats_name, sampler_stat)}\r\nposterior = {k:np.swapaxes(v.numpy(), 1, 0) for k, v in zip(var_name, samples)}\r\naz_trace = az.from_dict(posterior = posterior, sample_stats = sample_stats)\r\n\r\nsnsdistplot(posterior[\"prob\"])\r\nsnsdistplot(posterior[\"centers\"][:, 0])\r\n\r\n# put the data into a tensor\r\ndatatf = tf.constant(data, dtype = tf.float32)[:, tf.newaxis]\r\n\r\n# This produces a cluster per MCMC chain\r\nrv_clusters_1 = tfd.Normal(posterior[\"centers\"][:, 0], posterior[\"sigmas\"][:, 0])\r\nrv_clusters_2 = tfd.Normal(posterior[\"centers\"][:, 1], posterior[\"sigmas\"][:, 1])\r\n\r\n# Compute the un-normalized log probabilities for each cluster\r\ncluster_1_log_prob = rv_clusters_1.log_prob(datatf) + tf.math.log(posterior[\"prob\"])\r\ncluster_2_log_prob = rv_clusters_2.log_prob(datatf) + tf.math.log(1. - posterior[\"prob\"])\r\n\r\n# Bayes rule to compute the assignment probability: P(cluster = 1 | data) ∝ P(data | cluster = 1) P(cluster = 1)\r\nlog_p_assign_1 = cluster_1_log_prob - tf.math.reduce_logsumexp(tf.stack([cluster_1_log_prob, cluster_2_log_prob], axis=-1), -1)\r\n\r\n# Average across the MCMC chain\r\nlog_p_assign_1bis = tf.math.reduce_logsumexp(log_p_assign_1, -1) - tf.math.log(tf.cast(log_p_assign_1.shape[-1], tf.float32))\r\n\r\np_assign_1 = tf.exp(log_p_assign_1bis)\r\np_assign = tf.stack([p_assign_1, 1 - p_assign_1], axis=-1)\r\n\r\nassign_trace = log_p_assign_1bis.numpy()[np.argsort(data)]\r\nplt.scatter(data[np.argsort(data)], assign_trace, cmap = \"RdBu\",c = (1 - assign_trace), s = 50)\r\nplt.title(\"Probability of data point belonging to cluster 0\")\r\nplt.ylabel(\"probability\")\r\nplt.xlabel(\"value of data point\")\r\n", "meta": {"hexsha": "bfca140a69c6077f216143107a34ccbaf7d0f107", "size": 4634, "ext": "py", "lang": "Python", "max_stars_repo_path": "orig TFP code forked/TFPchap3.py", "max_stars_repo_name": "phineas-pta/Bayesian-Methods-for-Hackers-using-PyStan", "max_stars_repo_head_hexsha": "d708faab0fdd43800e8726e2c6dd99452c8dcedb", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-18T08:01:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T08:01:32.000Z", "max_issues_repo_path": "orig TFP code forked/TFPchap3.py", "max_issues_repo_name": "phineas-pta/Bayesian-Methods-for-Hackers-using-PyStan", "max_issues_repo_head_hexsha": "d708faab0fdd43800e8726e2c6dd99452c8dcedb", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "orig TFP code forked/TFPchap3.py", "max_forks_repo_name": "phineas-pta/Bayesian-Methods-for-Hackers-using-PyStan", "max_forks_repo_head_hexsha": "d708faab0fdd43800e8726e2c6dd99452c8dcedb", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9902912621, "max_line_length": 134, "alphanum_fraction": 0.7328441951, "include": true, "reason": "import numpy", "num_tokens": 1324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158575, "lm_q2_score": 0.899121373891026, "lm_q1q2_score": 0.8607089307456366}}
{"text": "import numpy as np\n\n# Helper functions\ndef _predict(theta_0, theta_1, x):\n    return theta_1 * x + theta_0       # good old line equation from high school when we were all young and happy\n\n\ndef compute_mse(theta_0, theta_1, data):\n    \"\"\"\n    Calcula o erro quadratico medio\n    :param theta_0: float - intercepto da reta\n    :param theta_1: float -inclinacao da reta\n    :param data: np.array - matriz com o conjunto de dados, x na coluna 0 e y na coluna 1\n    :return: float - o erro quadratico medio\n    \"\"\"\n    n = len(data)\n\n    predicted = [_predict(theta_0, theta_1, element[0]) for element in data]\n    \n    square_error = lambda x, y: (x - y)**2\n    squared_errors = [square_error(predicted[i], data[i][1]) for i in range(n)]\n\n    mse = sum(squared_errors) / n\n\n    return mse\n\n\ndef step_gradient(theta_0, theta_1, data, alpha):\n    \"\"\"\n    Executa uma atualização por descida do gradiente  e retorna os valores atualizados de theta_0 e theta_1.\n    :param theta_0: float - intercepto da reta\n    :param theta_1: float -inclinacao da reta\n    :param data: np.array - matriz com o conjunto de dados, x na coluna 0 e y na coluna 1\n    :param alpha: float - taxa de aprendizado (a.k.a. tamanho do passo)\n    :return: float,float - os novos valores de theta_0 e theta_1, respectivamente\n    \"\"\"\n    n = len(data)\n\n    predicted = [_predict(theta_0, theta_1, element[0]) for element in data]\n\n    simple_error = lambda x, y: x - y\n    errors = [simple_error(predicted[i], data[i][1]) for i in range(n)]\n\n    # Both expressions below can be checked on page 14 of the second set of slides on week 7 (\"Otimizacao Continua.pdf\")\n    df_d0 = (2 * sum(errors)) / n\n    df_d1 = (2 * sum([errors[i] * data[i][0] for i in range(n)])) / n\n\n    new_theta_0 = theta_0 - alpha*df_d0\n    new_theta_1 = theta_1 - alpha*df_d1\n\n    return (new_theta_0 , new_theta_1)\n\n\ndef fit(data, theta_0, theta_1, alpha, num_iterations):\n    \"\"\"\n    Para cada época/iteração, executa uma atualização por descida de\n    gradiente e registra os valores atualizados de theta_0 e theta_1.\n    Ao final, retorna duas listas, uma com os theta_0 e outra com os theta_1\n    obtidos ao longo da execução (o último valor das listas deve\n    corresponder à última época/iteração).\n\n    :param data: np.array - matriz com o conjunto de dados, x na coluna 0 e y na coluna 1\n    :param theta_0: float - intercepto da reta\n    :param theta_1: float -inclinacao da reta\n    :param alpha: float - taxa de aprendizado (a.k.a. tamanho do passo)\n    :param num_iterations: int - numero de épocas/iterações para executar a descida de gradiente\n    :return: list,list - uma lista com os theta_0 e outra com os theta_1 obtidos ao longo da execução\n    \"\"\"\n    current_iteration = 1\n    all_theta_zeroes = []\n    all_theta_ones = []\n\n    while current_iteration <= num_iterations:\n        (cur_theta_zero, cur_theta_one) = step_gradient(theta_0, theta_1, data, alpha)\n\n        all_theta_zeroes.append(cur_theta_zero)\n        all_theta_ones.append(cur_theta_one)\n\n        theta_0 = cur_theta_zero\n        theta_1 = cur_theta_one\n\n        current_iteration += 1\n    \n    return (all_theta_zeroes, all_theta_ones)\n", "meta": {"hexsha": "72f7cc2adb2fef1a6d680d7883b91e9dc36a91b3", "size": 3161, "ext": "py", "lang": "Python", "max_stars_repo_path": "Trabalhos-IA/T3-Otimizacao/entrega/alegrete.py", "max_stars_repo_name": "lucsmelo/INF01048-IA", "max_stars_repo_head_hexsha": "25901f206b20d8916f9170b703e533d40685ca0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Trabalhos-IA/T3-Otimizacao/entrega/alegrete.py", "max_issues_repo_name": "lucsmelo/INF01048-IA", "max_issues_repo_head_hexsha": "25901f206b20d8916f9170b703e533d40685ca0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Trabalhos-IA/T3-Otimizacao/entrega/alegrete.py", "max_forks_repo_name": "lucsmelo/INF01048-IA", "max_forks_repo_head_hexsha": "25901f206b20d8916f9170b703e533d40685ca0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-14T22:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T22:22:57.000Z", "avg_line_length": 37.1882352941, "max_line_length": 120, "alphanum_fraction": 0.6880733945, "include": true, "reason": "import numpy", "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723353, "lm_q2_score": 0.8991213698363247, "lm_q1q2_score": 0.8607089301517784}}
{"text": "\"\"\"\nLinear System (Polynomial Interpolation)\n\"\"\"\n\nimport numpy as np \n\ndef swap_rows(Z, a, b):\n    \"\"\"\n    Swap two rows (a, b) from Z matrix (np.array)\n\n    Parameters\n    ----------\n        Z : np.array\n            matrix\n        a : int\n            index row from Z\n        b : int \n            index row from Z \n    \"\"\"\n    temp = np.copy(Z[a])\n    Z[a] = Z[b]\n    Z[b] = temp\n\ndef partial_pivoting(Z, row):\n    \"\"\"\n    Partial pivoting of Z matrix, starting at row param\n\n    Parameters\n    ----------\n        Z : np.array\n            matrix\n        row : int\n            index row from Z\n    \n    Returns\n    -------\n        pivot : int\n            pivot is the max value from Z(row:,row)\n    \"\"\"\n    pivot_row = np.argmax(np.abs(Z[row:, row])) + row\n    swap_rows(Z, row, pivot_row)\n    pivot = Z[row, row]\n    return pivot\n\ndef solve_sys(X, Y):\n    \"\"\"\n    Solve a linear system using Gauss Elimination\n\n    Parameters\n    ----------\n        X : list\n            list of x values\n        Y : list\n            list of y values\n\n    Returns\n    -------\n        list\n            returns the roots of linear system (X, Y)\n    \"\"\"\n    Z = np.copy(X)\n    Z = np.hstack([Z, np.transpose(np.array([Y]))])\n\n    for j in range(Z.shape[0] - 1):\n        pivot = partial_pivoting(Z, j)\n        for i in range(j + 1, Z.shape[0]):\n            if Z[i, j] != 0 : \n                m = pivot / Z[i, j]\n                Z[i, j:] = Z[j, j:] - (m * Z[i, j:])\n\n    A = np.zeros((X.shape[0], 1))\n    for k in range(Z.shape[0] - 1, -1, -1):\n        A[k] = (Z[k, Z.shape[1]-1] - (Z[k, Z.shape[1]-2:k:-1] @ A[A.shape[0]:k:-1])) / Z[k, k]\n    \n    return np.ndarray.tolist(np.transpose(A))[0]\n\ndef vandermond(X):\n    \"\"\"\n    Create a vandermond matrix(nxn) by x values  \n\n    Parameters\n    ----------\n        X : list\n            list of x values\n\n    Returns\n    -------\n        np.array\n            vandermond matrix\n    \"\"\"\n    n = len(X)\n    V = np.zeros((n, n))\n\n    for i in range(n):\n        V[i, :] = [X[i]**k for k in range(n)]\n\n    return V\n\ndef linsys(X, Y):\n    \"\"\"\n    Polynomial Interpolation using Gauss Elimination\n\n    Parameters\n    ----------\n        X : list\n            list of X values\n        Y : list\n            list of Y values\n    \n    Returns\n    -------\n        function\n            function of polynomial interpolation (using linear system)\n    \"\"\"\n    V = vandermond(X)\n    A = solve_sys(V, Y)\n\n    def f(x):\n       return sum([a*(x**p) for p, a in enumerate(A)])\n\n    return f\n    \n\n        \n\n\n    ", "meta": {"hexsha": "aafa5e980bddd7438c7303469dfe090718176876", "size": 2510, "ext": "py", "lang": "Python", "max_stars_repo_path": "interpolation/methods/linear_system.py", "max_stars_repo_name": "JNagasava/Polynomial-Interpolation", "max_stars_repo_head_hexsha": "0061286afcdefe3fef55e9297227bb58fed5ae77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "interpolation/methods/linear_system.py", "max_issues_repo_name": "JNagasava/Polynomial-Interpolation", "max_issues_repo_head_hexsha": "0061286afcdefe3fef55e9297227bb58fed5ae77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interpolation/methods/linear_system.py", "max_forks_repo_name": "JNagasava/Polynomial-Interpolation", "max_forks_repo_head_hexsha": "0061286afcdefe3fef55e9297227bb58fed5ae77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7637795276, "max_line_length": 94, "alphanum_fraction": 0.464940239, "include": true, "reason": "import numpy", "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812345563904, "lm_q2_score": 0.8887588038050466, "lm_q1q2_score": 0.8606573476515917}}
{"text": "import numpy as np\r\nimport scipy.io\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\nfrom featureNormalize import feature_normalize\r\nfrom PCA_algo import pca\r\nfrom projectData import project_data\r\nfrom recoverData import recover_data\r\n\r\n\r\n# In this exercise, we'll use principal component analysis (PCA) to perform dimensionality reduction.\r\n########### Implement PCA on 2D dataset ####################\r\nprint(f\"Plotting data example 1\")\r\ndata1 = scipy.io.loadmat(\"data/ex7data1.mat\")\r\nsns.scatterplot(data1[\"X\"][:, 0], data1[\"X\"][:, 1])\r\nplt.show()\r\n\r\ninput(\"Pause program, Press enter to continue\")\r\n\r\n# Implement PCA (Reduce from 2D to 1D -> k=1)\r\n# (1st compute the covariance matrix of dataset. 2nd use svd function to compute eigenvectors U1, U2,...\r\n# Un which are corresponding to principal component (main component) of variation (thành phần) dataset)\r\nX_norm, mu, std = feature_normalize(data1[\"X\"])\r\nU, S = pca(X_norm)\r\n\r\n# Visualize the dimensional reduction data resulted by PCA\r\n# Visualize original data\r\nprint(f\"\\nVisualize dimensional reduction data\")\r\ndata1 = scipy.io.loadmat(\"data/ex7data1.mat\")\r\nax = sns.scatterplot(data1[\"X\"][:, 0], data1[\"X\"][:, 1])\r\n# Compute & visualize compressed data (Z)\r\np1 = mu  # (1, 2)\r\np2 = mu + 1.5 * S[0] * U[:, 0].T  # (1, 2)\r\nax.plot((p1[0], p2[0]), (p1[1], p2[1]), \"k\")\r\n\r\np1 = mu\r\np2 = mu + 1.5 * S[1] * U[:, 1].T\r\nax.plot([p1[0], p2[0]], [p1[1], p2[1]], 'k')\r\nplt.title('Computed eigenvectors of the dataset')\r\nplt.show()\r\ninput(\"Pause program, Press enter to continue\")\r\n\r\n\r\n############ Dimensionality reduction with PCA ##############\r\nprint(f\"\\nReduce dimensionality of data from n-dim to K-dim\")\r\n# Checking correctness of reduction\r\nK = 1\r\nZ = project_data(X_norm, U, K)  # (m, K)\r\nprint(f\"Projection of the 1st example: {Z[0]}\")\r\nprint(f\"This value should be 1.481274\")\r\n\r\n# Reconstructing compressed data approximately to original data\r\nprint(f\"\\nReconstruct compressed data to approximately original data\")\r\nX_rec = recover_data(Z, U, K)\r\nprint(f\"Approximation of 1st example: {X_rec[0, 0]}, {X_rec[0, 1]}\")\r\nprint(f\"The result should be -1.047419 -1.047419\")\r\n\r\n# Visualize the projection\r\nax = sns.scatterplot(X_norm[:, 0], X_norm[:, 1], s=50)\r\nax = sns.scatterplot(X_rec[:, 0], X_rec[:, 1], s=50, color=\"r\")\r\nfor i in range(X_norm.shape[0]):\r\n    p1 = X_norm[i, :]\r\n    p2 = X_rec[i, :]\r\n    plt.plot([p1[0], p2[0]], [p1[1], p2[1]], \"k--\")\r\nplt.title(\"Normalized and projected data after applying PCA\")\r\nplt.show()\r\ninput(\"Pause program, Press enter to continue\")\r\n\r\n\r\n################## Face image dataset ######################\r\n# Loading faces data\r\nfaces_data = scipy.io.loadmat(\"data/ex7faces.mat\")\r\n# Visualize the first 100 pic of faces\r\nprint(\"\\nVisualize the first 100 pictures of faces\")\r\nrows = 7\r\ncols = 7\r\ncount = 0\r\nfig = plt.figure(figsize=(5, 5))\r\nfor row in range(rows):\r\n    for col in range(cols):\r\n        ax = fig.add_subplot(rows, cols, count+1)\r\n        ax.imshow(faces_data[\"X\"][count].reshape(32, 32).T, cmap=\"gray\")\r\n        ax.axis(\"off\")\r\n        count += 1\r\nplt.show()\r\ninput(\"Pause program, Press enter to continue\")\r\n\r\n\r\n# Normalize data X & compute svd() function\r\nX_norm, mu, std = feature_normalize(faces_data[\"X\"])  # X_norm: (5000, 1024) (5000 pic)\r\nU, S = pca(X_norm)\r\n\r\n# Apply PCA to data with K = 100\r\nK = 100\r\nZ = project_data(X_norm, U, K)  # (m, K)\r\n# Visualize the first 100 dimensional reduction pic of face\r\nprint(\"\\nDrawing 1st 100 pic of face with dimensional reduction to K = 100\")\r\nrows = 7\r\ncols = 7\r\ncount = 0\r\nfig = plt.figure(figsize=(5, 5))\r\nfor row in range(rows):\r\n    for col in range(cols):\r\n        ax = fig.add_subplot(rows, cols, count+1)\r\n        ax.imshow(Z[count, :].reshape(10, 10).T, cmap=\"gray\")\r\n        ax.axis(\"off\")\r\n        count += 1\r\nplt.show()\r\ninput(\"Pause program, Press enter to continue\")\r\n\r\n\r\n# Reconstructing from compressed image to original image\r\nX_rec = recover_data(Z, U, K)\r\nprint(\"\\nPlot the reconstructed image from compressed image (From 10*10 to 32*32)\")\r\nrows = 7\r\ncols = 7\r\ncount = 0\r\nfig = plt.figure(figsize=(5, 5))\r\nfor row in range(rows):\r\n    for col in range(cols):\r\n        ax = fig.add_subplot(rows, cols, count+1)\r\n        ax.imshow(X_rec[count, :].reshape(32, 32).T, cmap=\"gray\")\r\n        ax.axis(\"off\")\r\n        count += 1\r\nplt.show()\r\n\r\n", "meta": {"hexsha": "e2540d53729cc6855e6d59ae32a74f7d9e2e49c7", "size": 4323, "ext": "py", "lang": "Python", "max_stars_repo_path": "(Ex7)_Unsupervised_learning_AND_PCA_algorithm/main_PrincipalComponentAnalysis_PCA.py", "max_stars_repo_name": "HarryPham0123/Coursera_Machine_learning_AndrewNg", "max_stars_repo_head_hexsha": "ae1fa34969fa0dafd44aa6606f6749c09b447239", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-10T07:23:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T07:23:30.000Z", "max_issues_repo_path": "(Ex7)_Unsupervised_learning_AND_PCA_algorithm/main_PrincipalComponentAnalysis_PCA.py", "max_issues_repo_name": "HarryPham0123/Coursera_Machine_learning_AndrewNg", "max_issues_repo_head_hexsha": "ae1fa34969fa0dafd44aa6606f6749c09b447239", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "(Ex7)_Unsupervised_learning_AND_PCA_algorithm/main_PrincipalComponentAnalysis_PCA.py", "max_forks_repo_name": "HarryPham0123/Coursera_Machine_learning_AndrewNg", "max_forks_repo_head_hexsha": "ae1fa34969fa0dafd44aa6606f6749c09b447239", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7734375, "max_line_length": 105, "alphanum_fraction": 0.6449225075, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812327313545, "lm_q2_score": 0.8887587993853654, "lm_q1q2_score": 0.8606573417496387}}
{"text": "\"\"\"\ngolden_section_algorithm.py\n\nReturns the reduced uncertainty interval containing the minimizer of the function\nfunc - anonimous function\ninterval0 - initial uncertainty interval\nN_iter - number of iterations\n\"\"\"\n\nimport math\nimport numpy as np\n\ndef golden_section_algorithm_calc_N_iter(interval0, uncertainty_range_desired):\n    \n    N_iter = math.ceil(math.log(uncertainty_range_desired / (interval0[1] - interval0[0]), 0.618)); \n    \n    return N_iter;\n        \n    \ndef golden_section_algorithm(func, interval0, N_iter):\n    \n    rho = (3 - np.sqrt(5)) / 2;\n    left_limit = interval0[0];\n    right_limit = interval0[1];\n    \n    smaller = 'a';\n    a = left_limit + (1 - rho) * (right_limit - left_limit);\n    f_at_a = func(a);\n        \n    for iter_no in range(N_iter):\n        if (smaller == 'a'):\n            c = a;\n            f_at_c = f_at_a;\n            a = left_limit + rho * (right_limit - left_limit);\n            f_at_a = func(a);\n        else:\n            a = c;\n            f_at_a = f_at_c;\n            c = left_limit + (1 - rho) * (right_limit - left_limit);\n            f_at_c = func(c);          \n        if (f_at_a < f_at_c):\n            right_limit = c;\n            smaller = 'a';\n        else:\n            left_limit = a;\n            smaller = 'c';\n            \n    interval = (left_limit, right_limit);\n    return interval;\n", "meta": {"hexsha": "b6980fb0608d22d689e43b123d9af449a3000f0b", "size": 1350, "ext": "py", "lang": "Python", "max_stars_repo_path": "1d_unconstrained_optimization/golden_section_algorithm.py", "max_stars_repo_name": "almostdutch/numerical-optimization-algorithms", "max_stars_repo_head_hexsha": "cd6c1306cb04eccce62a74420323bda83058c1d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1d_unconstrained_optimization/golden_section_algorithm.py", "max_issues_repo_name": "almostdutch/numerical-optimization-algorithms", "max_issues_repo_head_hexsha": "cd6c1306cb04eccce62a74420323bda83058c1d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-02T10:07:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-03T10:23:46.000Z", "max_forks_repo_path": "1d_unconstrained_optimization/golden_section_algorithm.py", "max_forks_repo_name": "almostdutch/numerical-optimization-algorithms", "max_forks_repo_head_hexsha": "cd6c1306cb04eccce62a74420323bda83058c1d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 100, "alphanum_fraction": 0.5696296296, "include": true, "reason": "import numpy", "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812309063187, "lm_q2_score": 0.8887587993853654, "lm_q1q2_score": 0.8606573401276221}}
{"text": "from matplotlib.patches import Polygon\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# points at 2D\ndef plot_2D_points(points, polyg=False):\n    fig, ax = plt.subplots()\n    ax.spines['right'].set_color('none')\n    ax.spines['top'].set_color('none')\n    ax.xaxis.set_ticks_position('bottom')\n    ax.spines['bottom'].set_position(('data',0)) # set position of x spine to x=0\n    ax.yaxis.set_ticks_position('left')\n    ax.spines['left'].set_position(('data',0))   # set position of y spine to y=0\n\n    for point in points:\n        plt.scatter(point[0], point[1], color=\"g\")    \n        plt.text(point[0]+0.2, point[1]+0.2, f'({point[0]},{point[1]})' , fontsize=11)\n\n    if polyg == False:\n        plt.show()\n\n\n# draw triangle\ndef plot_triangle(points):\n    plot_2D_points(points, polyg=True)\n\n    triangle_points = np.array(points)\n    triangle_plot = plt.Polygon(triangle_points, color='g')\n    plt.gca().add_patch(triangle_plot)\n\n    plt.show()\n\n\n# calculate the area o a triangle\ndef calc_triangle_area(x0, y0, x1, y1, x2, y2):\n    return abs((x0 * (y1 - y2) + x1 * (y2 - y0) + x2 * (y0 - y1))/2)\n\n\n# check if point (0,0) is inside the triangle\ndef check_origin_in(x0, y0, x1, y1, x2, y2):\n    # calculate triangle areas for:\n    triangle_area1 = calc_triangle_area(x0, y0, x1, y1, 0, 0) # Point0, Point1, (0.0)\n    triangle_area2 = calc_triangle_area(x0, y0, 0, 0, x2, y2) # Point0,(0.0), Point2\n    triangle_area3 = calc_triangle_area(0, 0, x1, y1, x2, y2) # (0,0), Point1, Point2\n    triangle_area = calc_triangle_area(x0, y0, x1, y1, x2, y2)\n\n    if(triangle_area1 + triangle_area2 + triangle_area3 == triangle_area): \n        print('The interior of the triangle contains the origin (0, 0)')\n    else: \n        print('The interior of the triangle does not contain the origin (0, 0)')\n\n\n#check if 3 points form a triangle\ndef check_for_triangle(x0, y0, x1, y1, x2, y2):\n    # area of triangle\n    # if area is 0, the points are in the same straight line\n    triangle_area = calc_triangle_area(x0, y0, x1, y1, x2, y2)\n  \n    if (triangle_area != 0): \n        return True\n    else: \n        return False\n  \n\nif __name__ == \"__main__\":  \n\n    # read 3 points from user\n    print(\"Give 3 points.\")\n    points = list(tuple(map(int,input('Give a point: ').split())) for r in range(3)) \n\n    #check if these points form a triangle\n    if check_for_triangle(points[0][0], points[0][1],\n                        points[1][0], points[1][1],\n                        points[2][0], points[2][1]):           \n        print ('These points form a triangle')\n        check_origin_in(points[0][0], points[0][1],\n                        points[1][0], points[1][1],\n                        points[2][0], points[2][1])\n        plot_triangle(points)                \n    else:\n        print ('These points don\\'t form a triangle')\n        plot_2D_points(points)                    \n", "meta": {"hexsha": "23fa781deebd2941210f7d512b5cfae413a2c40e", "size": 2869, "ext": "py", "lang": "Python", "max_stars_repo_path": "Homework_1/exercise1.py", "max_stars_repo_name": "billsioros/computational-geometry", "max_stars_repo_head_hexsha": "398a92e3c08046f85eb3e95828afe62230b816fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homework_1/exercise1.py", "max_issues_repo_name": "billsioros/computational-geometry", "max_issues_repo_head_hexsha": "398a92e3c08046f85eb3e95828afe62230b816fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homework_1/exercise1.py", "max_forks_repo_name": "billsioros/computational-geometry", "max_forks_repo_head_hexsha": "398a92e3c08046f85eb3e95828afe62230b816fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5662650602, "max_line_length": 86, "alphanum_fraction": 0.6106657372, "include": true, "reason": "import numpy", "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812299938006, "lm_q2_score": 0.8887587949656841, "lm_q1q2_score": 0.8606573350366772}}
{"text": "# import modules\r\nimport numpy as np\r\n\r\n'''\r\n# Description.\r\nGiven a 2x1 vector, this function obtains the angle of the azimuth from\r\nx-axis in a counter clockwise sense.\r\nCoordiante system is with x in the abscisas and y in the ordinates  (i.e. \r\nx horizontal pointing to the right and y vertical pointing upwards).\r\n\r\n# Input(s).\r\nArray that representing a bi-dimensional vector (vector).\r\n\r\n# Output(s).\r\nAngle in radians representing the azimut of the vector (angleRad).\r\n \r\nExample: giving next array\r\nvector = np.array([3,-5]), is obtined  5.2528 radians\r\n---\r\nangleRad = azimuthangle(vector)\r\n'''\r\ndef azimuthangle(vector):\r\n    if vector[0] == 0:\r\n        if vector[1] >= 0:\r\n            angleRad = np.pi/2\r\n        else:\r\n            angleRad = 3*np.pi/2\r\n    else:\r\n        basicAngleRad = np.arctan(np.abs(vector[1])/np.abs(vector[0]))\r\n        if vector[0] >= 0:\r\n            if vector[1] >= 0: #case 1\r\n                angleRad = basicAngleRad\r\n            elif vector[1] < 0: #case 4\r\n                angleRad = 2*np.pi-basicAngleRad\r\n        elif vector[0] < 0:\r\n            if vector[1] >= 0: #case 2\r\n                angleRad = np.pi-basicAngleRad\r\n            elif vector[1] < 0: #case 3\r\n                angleRad = np.pi+basicAngleRad\r\n        else:\r\n            print(\"Error: bad number\")\r\n\r\n    return angleRad\r\n'''\r\nBSD 2 license.\r\n\r\nCopyright (c) 2016, Universidad Nacional de Colombia, Ludger O.\r\n   Suarez-Burgoa and Exneyder Andrés Montoya Araque.\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without\r\nmodification, are permitted provided that the following conditions are\r\nmet:  \r\n\r\n1. Redistributions of source code must retain the above copyright notice,\r\nthis list of conditions and the following disclaimer. \r\n\r\n2. Redistributions in binary form must reproduce the above copyright\r\nnotice, this list of conditions and the following disclaimer in the\r\ndocumentation and/or other materials provided with the distribution.  \r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\r\nIS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\r\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r\nPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\r\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n'''\r\n", "meta": {"hexsha": "8de0c88affc19168417267530b0f1d2737884a1b", "size": 2767, "ext": "py", "lang": "Python", "max_stars_repo_path": "functions/azimuthangle.py", "max_stars_repo_name": "eamontoyaa/CSS-pyProgram", "max_stars_repo_head_hexsha": "beb28a18cba4e4b2e6d8be556296aa6f8025defa", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2016-05-12T14:54:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T09:29:08.000Z", "max_issues_repo_path": "functions/azimuthangle.py", "max_issues_repo_name": "eamontoyaa/CSS-pyProgram", "max_issues_repo_head_hexsha": "beb28a18cba4e4b2e6d8be556296aa6f8025defa", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-02-27T17:34:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-17T08:44:26.000Z", "max_forks_repo_path": "functions/azimuthangle.py", "max_forks_repo_name": "eamontoyaa/CSS-pyProgram", "max_forks_repo_head_hexsha": "beb28a18cba4e4b2e6d8be556296aa6f8025defa", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-06-21T04:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T02:25:19.000Z", "avg_line_length": 37.3918918919, "max_line_length": 75, "alphanum_fraction": 0.6899168775, "include": true, "reason": "import numpy", "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812309063187, "lm_q2_score": 0.8887587846530938, "lm_q1q2_score": 0.8606573258611667}}
{"text": "\"\"\"\nThe purpose of this code is to explore the use of relaxation and over-\nrelaxation method on computing non-linear equations i.e. f(x) = x.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#Part a\n#Text Exercise 6.10 a\n#we can modify the number of loops to acheive different levels of accuracy\n#in our case we achieved 10^-6 by setting the number of loops to 15\nxa=1.0 #starting guess for x\nnumOfLoops = 15\nfor k in range(numOfLoops):\n    xa = 1 - np.exp(-2*xa) #given equation\n\nprint(\"part a answer\")\nprint(\"value of x with {} iterations:\".format(numOfLoops), xa)\nprint(\"value of 1 - exp(-2*x) with {} iterations:\".format(numOfLoops), 1 - np.exp(-2*xa))\n    \n#Text Exercise 6.10 b\n#similar as above, we first reset the variables and instead of a constant c\n#we generated a range of values from 0 to 300 with a stepsize of 0.01\nx=1.0 #Starting guess for value of x\nnumOfLoops = 15\nc = np.arange(0, 3, 0.01) #different values for c\nfor k in range(numOfLoops):\n    x = 1 - np.exp(-c*x)\n\n# plotting the results\nfig, graph = plt.subplots()\ngraph.plot(c, x)\ngraph.set(xlabel=\"c\", ylabel=\"x\",\n       title=\"Solutions of x for a range of c=(0, 3, 0.01) (Q3a)\")\ngraph.grid()\nfig.savefig(\"q3_A.png\")\nplt.show()\n\n\n#Part b\n#Text Exercise 6.11 b\ndef F(c):\n    \"\"\"\n    This function uses the similar method as above and find the iterations \n    when it approaches the convergence.\n    \"\"\"\n    sigdig = 10 ** -6 #Define the accuracy (number of significant digits) we want the solution to be accurate to\n    iterations = 1 #Starting value for iterations\n    def f(x):\n        return 1 - np.exp(-c*x) \n    # Define our error function given in textbook\n    # We need this so that when this value gets below the sigdigs we want it cuts off the iteration count\n    def error(x1, x2):\n        return (x1-x2)/(1 - 1/(c*np.exp(-c * x1)))\n\n    x1 = 1.0 # starting value\n    x2 = f(x1)\n    #We need a condition so that when the error is greater than the value we want\n    #It keeps running more iterations\n    while(abs(error(x1, x2)) > sigdig):\n        #This adds another Iteration\n        x1, x2 = x2, f(x2)\n        #This increases the iteration count tally\n        iterations += 1\n    print('The minimum number of iterations for an accuracy of 10**-6 = ', iterations)\n    print(\"value of x:\", x2)\n    print(\"value of 1 - np.exp(-c*x)  is:\", 1 - np.exp(-2*x2))\n\n#Text Exercise 6.11 c\ndef F_over(c, w):\n    \"\"\"\n    This function uses the over-relaxation method to increases the rate of\n    convergence by artifically increasing the gradient of f(x)\n    \"\"\"\n    sigdig = 10 ** -6\n    iterations = 1\n    def f(x):\n        return 1 - np.exp(-c*x)\n\n    def derivf(x):#This is the derivative of our function which we need for the over relax method\n        return c * np.exp(-c*x)\n\n    def error(x1, x2):# Error function for overrelaxation from text\n        return (x1 - x2)/(1 - 1/((1 + w)*derivf(x1) - w))\n\n    x1 = 1.0  # starting value\n    x2 = (1 + w) * f(x1) - w * x1\n    while abs(error(x1, x2)) > sigdig:\n        #when the error is above the desired value, we do another iterations as before\n        x1, x2 = x2, (1 + w) * f(x2) - w * x2\n        #We then add 1 to the iteration count\n        iterations += 1\n    print('When we set omega to be ', w,'the minimum number of iterations for an accuracy of 10**-6 is ', iterations)\n    print(\"value of x:\", x2)\n    print(\"value of 1 - exp(-2*x):\", 1 - np.exp(-2*x2))\n\nprint()\nprint(\"part b answer\")\nF(2)\nprint()\nF_over(2, 0.5)\n\n\n#Part c\n#reset the variables to desired accuracy and values\nsigfig = 10 ** -6\na = 1\nb = 2\ndef f(x, y):\n    \"\"\"\n    the derived equation from 6.12(b)\n    \"\"\"\n    return y*(a+x**2)\n\ndef g(x, y):\n    \"\"\"\n    the derived equation from 6.12(b)\n    \"\"\"\n    return b/(a+x**2)\n\ndef F(x,y):\n    \"\"\"\n    the rewritten equation from 6.12(c)\n    \"\"\"\n    return np.sqrt(b/y-a)\n\ndef G(x,y):\n    \"\"\"\n    the rewritten equation from 6.12(c)\n    \"\"\"\n    return x/(a+x**2)\n\ndef solution(f, g):\n    \"\"\"\n    This function uses the similar method as above and find the iterations \n    when it approaches the convergence.\n    \"\"\"\n    iterations = 1\n    def delta(x1, x2):\n        return (x1 - x2) / x1\n    x1 = 0.5\n    y1 = 0.5\n    x2 = f(x1, y1)\n    y2 = g(x1, y1)\n    #While the errors of x or y are higher than the desired value we need to do more iterations\n    while abs(delta(x1, x2)) > sigfig and abs(delta(y1, y2)) > sigfig:\n        #This allows our method to \"Fail gracefully\" as required\n        if iterations > 1000:\n            return 'error'\n        \n        x1, x2, y1, y2 = x2, f(x2, y2), y2, g(x2, y2)\n        iterations += 1\n    print('The number of iterations = ', iterations, 'the solution for x ~', x2, 'the solution for y ~', y2)\n    return [ x2, y2 ]\n\nprint()\nprint(\"part c answer\")\nprint(solution(F,G))\n", "meta": {"hexsha": "5d4b195759e7fc15f988507a6d529f4c4397ad6b", "size": 4765, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab4/Lab4_Q3.py", "max_stars_repo_name": "fancent/PHY407", "max_stars_repo_head_hexsha": "38ce8badb9537060becc255ec64e6de2968ca73c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-20T17:30:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-20T17:30:06.000Z", "max_issues_repo_path": "Lab4/Lab4_Q3.py", "max_issues_repo_name": "fancent/PHY407", "max_issues_repo_head_hexsha": "38ce8badb9537060becc255ec64e6de2968ca73c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab4/Lab4_Q3.py", "max_forks_repo_name": "fancent/PHY407", "max_forks_repo_head_hexsha": "38ce8badb9537060becc255ec64e6de2968ca73c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-12T14:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T14:21:13.000Z", "avg_line_length": 29.9685534591, "max_line_length": 117, "alphanum_fraction": 0.6228751312, "include": true, "reason": "import numpy", "num_tokens": 1474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.9099069987088003, "lm_q1q2_score": 0.8605911923414199}}
{"text": "\n# We use the process of normalization to modify the values in the feature vector so that we can measure them on a common scale. \n# In machine learning, we use many different forms of normalization. \n# Some of the most common forms of normalization aim to modify the values so that they sum up to 1 . L1 normalization ,\n# which refers to Least A bsolute Deviations , works by making sure that the sum of absolute values is 1 in each row. L2 normalization ,\n# which refers to least squares, works by making sure that the sum of squares is 1 .\n# In general, L1 normalization technique is considered more robust than L2 normalization technique.\n# L1 normalization technique is robust because it is resistant to outliers in the data.\n# A lot of times, data tends to contain outliers and we cannot do anything about it.\n# We want to use techniques that can safely and effectively ignore them during the calculations.\n# If we are solving a problem where outliers are important, then maybe L2 normalization becomes a better choice.\n\nimport numpy as np \nfrom sklearn import preprocessing\n\ninput_data = np.array(\n    [[5.1, -2.9, 3.3],\n    [-1.2, 7.8, -6.1],\n    [3.9, 0.4, 2.1],\n    [7.3, -9.9, -4.5]]\n)\n\n# Normalize data \ndata_normalized_l1 = preprocessing.normalize(input_data, norm='l1') \ndata_normalized_l2 = preprocessing.normalize(input_data, norm='l2')\nprint(\"\\nL1 normalized data:\\n\", data_normalized_l1) \nprint(\"\\nL2 normalized data:\\n\", data_normalized_l2)", "meta": {"hexsha": "474e292ff0e62f69f796757bb639b50c446d821f", "size": 1458, "ext": "py", "lang": "Python", "max_stars_repo_path": "preprocessing_data/normalization.py", "max_stars_repo_name": "donutloop/machine_learning_examples", "max_stars_repo_head_hexsha": "46192a57e2dd194925ae76d6bfb169cd2af142dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-10-08T18:24:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-08T18:24:40.000Z", "max_issues_repo_path": "preprocessing_data/normalization.py", "max_issues_repo_name": "donutloop/machine_learning_examples", "max_issues_repo_head_hexsha": "46192a57e2dd194925ae76d6bfb169cd2af142dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "preprocessing_data/normalization.py", "max_forks_repo_name": "donutloop/machine_learning_examples", "max_forks_repo_head_hexsha": "46192a57e2dd194925ae76d6bfb169cd2af142dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-09T06:50:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-09T06:50:48.000Z", "avg_line_length": 54.0, "max_line_length": 136, "alphanum_fraction": 0.7544581619, "include": true, "reason": "import numpy", "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018434079934, "lm_q2_score": 0.8824278726384089, "lm_q1q2_score": 0.8605452880715705}}
{"text": "\"\"\"\nBaby steps in Theano library\n\n\"\"\"\nimport numpy\nfrom matplotlib import pyplot as plt\nimport theano.tensor as T\nfrom theano import function\nfrom theano import pp\n\n\n'''\nthis is a brief insight of how the theano library works\n\neverything we do, every operation, instead of a usual for example \"x + y\" is declared differently\n\nvariables are first declared as Theano based ones and then we assemble an expression as theano function\n\nthe reason for this is that theano creates a C code in the backend to make an operation\n\nthen the operation's code is optimized by compiler\n\nfollowing code shows a baseline on how to create simple equations, though it may seem intuitive, it\ndoes things in quite unusual way \n'''\n\nx = T.dscalar('x')\ny = T.dscalar('y')\nz = x + y\nf = function([x, y], z)\nprint(f(2, 3))\nprint(numpy.allclose(f(16.3, 12.1), 28.4))\n\n'''\nhere we defined simple addition function in more steps than usual\n\nit's because theano acts on symbols to perform creation of C code that runs in background\n\nwe declare 2 \"scalars\" (numbers), assigned them to x and y, respectively, then we\nhinted the operation (addition) that gets stored in z variable.\n\na function declaration takes inputs and outputs, in our case it takes an array [x, y]\nand returns z. Z is evaluated as addition\n'''\n\nprint(pp(z))\n'''\nhere we see how theano assigned the operation\n'''\n\nprint(z.eval({x : 16.3, y : 12.1}))\n'''\nwe could also invoke the \"eval()\" from a z variable that had addition operation\n\"eval()\" takes a dictionary with names of variables and values to be assigned to them\n\neval() utimately imports a \"function()\", so we end up in the same situation, so it is\nslower the first time we invoke this, subsequent invocations are faster since it saves\n\"function()\" imported already\n\nthat way we don't need to import \"function()\", but importing and using it is more \nflexible than relyin on \"eval()\" itself\n'''\n\n'''\nAddition of two matrices is also very simple, the only difference is using \nT.dmatrix instead of T.dscalar\n'''\n\nx = T.dmatrix('x')\ny = T.dmatrix('y')\nz = x + y\nf2 = function([x, y], z)\n\n'''\nnow we do not assign the matrices to x and y directly, but instead we pass matrices \nto function as variables, invoking it like: \"f2([matrix_nr_1], [matrix_nr_2])\n\nhere we add, elementwise, 2 2-dimensional matrices\n'''\n\na1 = [[1, 2],\n      [3, 4]]\na2 = [[10, 20],\n      [30, 40]]\n\nresult = f2(a1, a2)\nprint(result)\n\n'''\nwe could also utilize numpy.array\n'''\na3 = numpy.array([[1, 2],\n                  [3, 4]])\na4 = numpy.array([[10, 20],\n                  [30, 40]])\n\nprint(f2(a3, a4))\n\n'''\nex1. modify the code at the bottom, \n\nimport theano\na = theano.tensor.vector() # declare variable\nout = a + a ** 10\n# build symbolic expression\nf = theano.function([a], out)\n# compile function\nprint(f([0, 1, 2]))\n\nto reflect the expression: a ** 2 + b ** 2 + 2 * a * b\n'''\n\nc = 16\nd = 13\n\nsample_result = [c**2 + d**2 + 2*c*d]\n\na = T.vector('a') # declare variable\nb = T.vector('b')\nadd = a + b\nout = T.power(add, 2)\n# build symbolic expression\nf3 = function([a, b], out)\n# compile function\nprint(f3([0, 1, 2], [0, 1, 2]))\n\nassert sample_result == f3([16], [13])\nprint(f3([16], [13]))\n\n'''\ncalculation more elaborate functions is also possible\nhere we calculate a result of a \"logistic\" function, sometimes referred to as \"sigmoid\"\n\n'''\n\nmatrix = T.dmatrix('matrix')\ns = 1/ (1+ T.exp(-matrix))\nsigmoid = function([matrix], s)\nX = numpy.linspace(-6, 6, 100)\nvalues = sigmoid([X])[0]\n\nprint(X)\nprint(values)\n\nplt.plot(X, values)\nplt.show()\n\n\n'''\nWe could also produce gradients.\nTheano provides efficient symbolic differentiaition, using T.grad as a macro\n\nlets compute a gradient of logistic function\n\nnote that we compute it for SCALAR values here!!!\n'''\n\nx2 = T.scalar('x2')\nsigm = 1/ (1+ T.exp(-x2))\nsigm_grad = T.grad(sigm, x2)\n# uncomment this if you copy code to another program, i already declared this above\n# X = numpy.linspace(-6, 6, 100)\n'''\nok we declared derivative (gradient) and a regular function, at the coordinate passed\nto the function\n\ntheano \"function()\" can also accept multiple outputs, not only multiple inputs\n\nhere we calculate the regular function output, as well as the derivative at the same point\n\nKNOWN PROBLEM: the result is a list of 0-dimensional arrays, which can't be accessed in regular way\nuse \"list[index].sum()\" to extract a desired value from it\n'''\n\nmultiple_sigmoid_outputs = function([x2], [sigm, sigm_grad])\n\nval_out = multiple_sigmoid_outputs(4)\nprint(val_out)\nprint(val_out[0].sum(), val_out[1].sum())\n\n'''\nok so we defined a derivative of a function at a single point, but what about computing\nwhole lists of points?\n\nyou have to wrap the result of a regular with the \"T.sum\" to make that happen\n'''\n\n\nx3 = T.matrix('x3')\nsigm2 = T.sum(1/ (1+ T.exp(-x3)))\nsigm2_grad = T.grad(sigm2, x3)\nlogistics = function([x3], [sigm2, sigm2_grad])\nvalues2 = logistics([X])\n\nprint(values2)\nY = values2[1][0]\nplt.plot(X, Y, c='red')\nplt.plot(X, values, c='blue')\nplt.show()\n\nprint(logistics.maker.fgraph.outputs)\npp(logistics.maker.fgraph.outputs[0])\n\n\n'''\nBack to the basics\n\nHow to set a default value for a variable in theano function?\n\nit isn't that hard as it looks, just use the \"In\" class\n\n\"In\" from theano accepts a variable and a \"value=\" which initializes default variable\nif not present\n\nYou can think of a \"In(variable_name, value=default_value)\" class as an \"Input\" to a function\n\nWe will also use a \"T.dscalars\" macro, which creates multiple variables in one line, unlike the\n\"T.dscalar\"\n'''\n\nfrom theano import In\n\nx5, y5 = T.dscalars('x5', 'y5')\nz5 = x5 + y5\nfunc5 = function([x5, In(y5, value=4)], z5)\nprint(func5(32))\nprint(func5(20, 56.7))\n\nassert func5(25) == 29\n\n\n'''\nand how to share a value between theano functions?\n\nyou can allocate memory space that will be accessible from any theano function, even after\nit finishes work\n\nthe additional \"set_value()\" and \"get_value()\" help show and modify shared varaible's contents without a need of creting\na function\n\nfunctions use shared variables in slightly different way than regular variables; we have to pass the in \"updates\" list\ndeclaring what we want to do with the variable\n'''\n\nfrom theano import shared\n\nstate = shared(0)\ninc = T.iscalar('inc')\naccumulator = function([inc], state, updates=[(state, state+inc)])\n\nprint(state.get_value())\naccumulator(1)\nprint(state.get_value())\naccumulator(300)\nprint(state.get_value())\nstate.set_value(-1)\naccumulator(3)\nprint(state.get_value())\n\ndecrementor = function([inc], state, updates=[(state, state-inc)])\ndecrementor(2)\nprint(state.get_value())\n\n\n\n", "meta": {"hexsha": "e1443586a698db700015f95be27668c234852712", "size": 6577, "ext": "py", "lang": "Python", "max_stars_repo_path": "theano_basics.py", "max_stars_repo_name": "Neuroszima/a_simple_network", "max_stars_repo_head_hexsha": "695593c9329c216b89199c81d7a9137f33fc0ecd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "theano_basics.py", "max_issues_repo_name": "Neuroszima/a_simple_network", "max_issues_repo_head_hexsha": "695593c9329c216b89199c81d7a9137f33fc0ecd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "theano_basics.py", "max_forks_repo_name": "Neuroszima/a_simple_network", "max_forks_repo_head_hexsha": "695593c9329c216b89199c81d7a9137f33fc0ecd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7255639098, "max_line_length": 120, "alphanum_fraction": 0.7077694998, "include": true, "reason": "import numpy,import theano,from theano", "num_tokens": 1784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.9173026499774933, "lm_q1q2_score": 0.8605436458901101}}
{"text": "import numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom mpl_toolkits.mplot3d import Axes3D\nimport math\nimport sys\nimport os\n\ndata_dir = sys.argv[1]\nout_dir = sys.argv[2]\ntest_set = os.path.join(sys.argv[1], 'q2test.csv')\nout = os.path.join(sys.argv[2], 'Q2c.txt')\noutfile = open(out, \"w\")\n\n# 2. Sampling and Stochastic Gradient\nprint(\"\\n################ 2. Sampling and Stochastic Gradient ################\", file=outfile)\n\n# (a) Sampling\n\nw = np.array([[3],[1],[2]])\nX1 = np.random.normal(3, 2, (int)(1e6))\nX2 = np.random.normal(-1, 2, (int)(1e6))\nnoise = np.random.normal(0, np.sqrt(2), int(1e6)).reshape(-1,1)\n\nX = np.column_stack((X1, X2))\nX = np.column_stack((np.ones(X.shape[0]), X))\nY = np.dot(X, w) + noise\nm = len(Y)\n\n\n# (b) Stochastic Gradient\n\ndef hw(theta, i, r):\n\tx = X[i*r:(i+1)*r,]\n\treturn np.dot(x, theta)\n\ndef Jw(h, i, r):\n\ty = Y[i*r:(i+1)*r,]\n\treturn (0.5/r)*np.sum((y - h)**2)\n\ndef dJw(h, i, r):\n\tx = X[i*r:(i+1)*r,]\n\ty = Y[i*r:(i+1)*r,]\n\treturn (1.0/r)*np.dot(x.T, (y - h))\n\ndef stochasticGradientDescent(x, y, r):\n\tb = (int)(m/r)\n\teta = 0.001\n\ttheta = np.zeros((x.shape[1], 1))\n\tthetaL = [theta]\n\tprevCost = 0\n\tconverged = False\n\titr = 0\n\twhile not converged:\n\t\tfor i in range(b):\n\t\t\th = hw(theta, i, r)\n\t\t\tcost = Jw(h, i, r)\n\t\t\ttheta = theta + eta*dJw(h, i, r)\n\t\t\tthetaL.append(theta)\n\t\titr += 1\n\t\terror = abs(cost - prevCost)\n\t\tprevCost = cost\n\t\tif error < 1e-7 or itr > 25000:\n\t\t\tconverged = True\n\n\treturn thetaL, itr, cost\n\nthetaL1, maxit1, cost1 = stochasticGradientDescent(X, Y, 1)\nthetaL2, maxit2, cost2 = stochasticGradientDescent(X, Y, 100)\nthetaL3, maxit3, cost3 = stochasticGradientDescent(X, Y, 10000)\nthetaL4, maxit4, cost4 = stochasticGradientDescent(X, Y, 1000000)\n\n# (c) Test Data\n\ndata = np.loadtxt(test_set, delimiter=',', skiprows=1)\nq2X1 = data[:,0]\nq2X2 = data[:,1]\nq2X = np.column_stack((q2X1, q2X2))\nq2X = np.column_stack((np.ones(q2X.shape[0]), q2X))\nq2Y = data[:,-1].reshape(-1,1)\nq2m = len(q2Y)\n\ndef testError(theta):\n\th = np.dot(q2X, theta)\n\treturn (0.5/q2m)*np.sum((q2Y - h)**2)\n\nerror1 = testError(thetaL1[-1])\nerror2 = testError(thetaL2[-1])\nerror3 = testError(thetaL3[-1])\nerror4 = testError(thetaL4[-1])\n\nprint('\\nFor r = 1 : Training Error = {}, Test Error = {}'.format(cost1, error1), file=outfile)\nprint('For r = 100 : Training Error = {}, Test Error = {}'.format(cost2, error2), file = outfile)\nprint('For r = 10000 : Training Error = {}, Test Error = {}'.format(cost3, error3), file=outfile)\nprint('For r = 1000000 : Training Error = {}, Test Error = {}'.format(cost4, error4), file=outfile)\n", "meta": {"hexsha": "99fc2e366febba202080f88f08d4fd8e9d1144c8", "size": 2616, "ext": "py", "lang": "Python", "max_stars_repo_path": "Q2c.py", "max_stars_repo_name": "sharique1006/Stochastic-Gradient-Descent", "max_stars_repo_head_hexsha": "0a2a9278ec2dfb8660c31a630f5933e13ffd6323", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Q2c.py", "max_issues_repo_name": "sharique1006/Stochastic-Gradient-Descent", "max_issues_repo_head_hexsha": "0a2a9278ec2dfb8660c31a630f5933e13ffd6323", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Q2c.py", "max_forks_repo_name": "sharique1006/Stochastic-Gradient-Descent", "max_forks_repo_head_hexsha": "0a2a9278ec2dfb8660c31a630f5933e13ffd6323", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.693877551, "max_line_length": 99, "alphanum_fraction": 0.6368501529, "include": true, "reason": "import numpy", "num_tokens": 942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551515780319, "lm_q2_score": 0.8918110555020056, "lm_q1q2_score": 0.8604684911353522}}
{"text": "## 2. Systems of equations as matrices ##\n\nimport numpy as np\n\n# Set the dtype to float to do float math with the numbers.\nmatrix = np.asarray([\n    [2, 1, 25],\n    [3, 2, 40]  \n], dtype=np.float32)\nmatrix[0] = matrix[0] * 2\nmatrix[0] = matrix[0] - matrix[1]\nmatrix[1] = matrix[1] - (matrix[0] * 3)\nmatrix[1] /= 2\nprint(matrix)\n\n## 4. Solving more complex equations ##\n\nimport numpy as np\n\nmatrix = np.asarray([\n    [1, 2, 0, 7],\n    [0, 3, 3, 11],\n    [1, 2, 2, 11]\n], dtype=np.float32)\nmatrix[2] = matrix[2] - matrix[0]\nmatrix[2] = matrix[2] / 2\nmatrix[1] = matrix[1] / 3\nmatrix[1] = matrix[1] - matrix[2]\nmatrix[0] = matrix[0] - 2 * matrix[1]\n\n## 5. Echelon form ##\n\nmatrix = np.asarray([\n    [0, 0, 0, 7],\n    [0, 0, 1, 11],\n    [1, 2, 2, 11],\n    [0, 5, 5, 1]\n], dtype=np.float32)\n\n# Swap the first and the third rows - first swap\nmatrix[[0,2]] = matrix[[2,0]]\nmatrix[[1,3]] = matrix[[3,1]]\nmatrix[[2,3]] = matrix[[3,2]]\n\n## 6. Reduced row echelon form ##\n\nA = np.asarray([\n        [0, 2, 1, 5],\n        [1, 2, 1, 8],\n        [3, 0, 1, 10],\n        ], dtype=np.float32)\n\n# First, we'll swap the second row with the first to get a non-zero coefficient in the first column\nA[[0,1]] = A[[1,0]]\n\n# The leading coefficient is already 1, so there's no need to divide\n# Now, we need to make sure that our 1 coefficient is the only coefficient in its column\n# We have to subtract three times the first row from the third row\nA[2] -= 3 * A[0]\n\n# Now, we move to row 2\n# We divide by 2 to get a one as the leading coefficient\nA[1] /= 2\n\n# We subtract 2 times the second row from the first to get rid of\n# the second column coefficient in the first row\nA[0] -= 2 * A[1]\n\n# And we'll add 6 times the second row to the third to eliminate the leading coefficient there\nA[2] += 6 * A[1]\n\n# Now, we can move to the third row where the leading coefficient is already 1\n# We just need to subtract half of the third from the second\nA[1] -= 0.5 * A[2]\n\n# We're finished, and our system is solved!\nprint(A)\n\n## 7. Inconsistency ##\n\nA = np.asarray([\n    [10, 5, 20, 60],\n    [3, 1, 0, 11],\n    [8, 2, 2, 30],\n    [0, 4, 5, 13]\n], dtype=np.float32)\n\nB = np.asarray([\n    [5, -1, 3, 14],\n    [0, 1, 2, 8],\n    [0, -2, 5, 1],\n    [0, 0, 6, 6]\n], dtype=np.float32)\n\nA_consistent,B_consistent = True,False\n\n## 8. Infinite solutions ##\n\nA = np.asarray([\n        [2, 4, 8, 20],\n        [4, 8, 16, 40],\n        [20, 5, 5, 10]\n], dtype=np.float32)\nA_infinite = True\n\nB = np.asarray([\n        [1, 1, 1, 4],\n        [3, -2, 5, 8],\n        [8, -4, 5, 10]\n        ], dtype=np.float32)\n        \nB_infinite = False", "meta": {"hexsha": "e9e006901a9e3a45c6fc05cad24298dbf6513a53", "size": 2582, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear Algebra/Solving systems of equations with matrices-55.py", "max_stars_repo_name": "vipmunot/Data-Analysis-using-Python", "max_stars_repo_head_hexsha": "34586d8cbbc336508c4a7a68abe14944f1096252", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Linear Algebra/Solving systems of equations with matrices-55.py", "max_issues_repo_name": "vipmunot/Data-Analysis-using-Python", "max_issues_repo_head_hexsha": "34586d8cbbc336508c4a7a68abe14944f1096252", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear Algebra/Solving systems of equations with matrices-55.py", "max_forks_repo_name": "vipmunot/Data-Analysis-using-Python", "max_forks_repo_head_hexsha": "34586d8cbbc336508c4a7a68abe14944f1096252", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0535714286, "max_line_length": 99, "alphanum_fraction": 0.5782339272, "include": true, "reason": "import numpy", "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551546097941, "lm_q2_score": 0.8918110440002044, "lm_q1q2_score": 0.8604684827415391}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: Ashutosh Vyas\n\nA function to compute cost for multivariate linear regression.\n\nThis function is used for the Optional Part of the Exercise 1: Linear Regression.\ncost_J = compute_cost(x_data, y_data, theta) computes the cost of using theta\nas the parameter for linear regression to fit the data points in x_data, y_data.\n\"\"\"\n\nimport numpy\n\n\ndef compute_cost_multi(x_data, y_data, theta, num_examples):\n    \"\"\"\n    Compute cost for single iteration of multivariate linear regression.\n\n    Given the multivariate hypothesis,\n    h(x) = theta0 + theta1*x1 + theta2*x2 = theta^transpose.x,\n    this function calculates the cost incurred for the given value of theta.\n    Thus computes J(theta)\n\n    Parameters\n    ----------\n    x_data : ndarray\n        X 2D array dataset with appended theta0 initalized as 1.\n    y_data : ndarray\n        A vector of actual values of y from the dataset.\n    theta : ndarray\n        theta0 (y-intercept) and theta1 (slope) of the linear model.\n    num_examples : scalar\n        Number of training examples.\n\n    Returns\n    -------\n    cost_J : scalar\n        Cost incurred as difference between hypothesis and actual value.\n        Represented as sum -of squared errors\n\n    \"\"\"\n\n    x_dot_theta = numpy.reshape(numpy.dot(x_data, theta), y_data.shape)  # calculating hypothesis\n    difference = x_dot_theta - y_data  # error = hypothesis - actual\n    squared = numpy.power(difference, 2.0)  # squared error\n    factor = (1.0/(2.0*num_examples))\n    cost_J = factor*numpy.sum(squared)  # sum of squared error\n    return cost_J\n", "meta": {"hexsha": "3a2855dce39cf7a420f0c0332cf1b5a45e0905a1", "size": 1616, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/ex1_linear_regression_uni_multi/lin_reg_funcs/compute_cost_multi.py", "max_stars_repo_name": "ashu-vyas-github/AndrewNg_MachineLearning_Coursera", "max_stars_repo_head_hexsha": "1be5124b07df61f7295dd1c5151b86b061bf50fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/ex1_linear_regression_uni_multi/lin_reg_funcs/compute_cost_multi.py", "max_issues_repo_name": "ashu-vyas-github/AndrewNg_MachineLearning_Coursera", "max_issues_repo_head_hexsha": "1be5124b07df61f7295dd1c5151b86b061bf50fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/ex1_linear_regression_uni_multi/lin_reg_funcs/compute_cost_multi.py", "max_forks_repo_name": "ashu-vyas-github/AndrewNg_MachineLearning_Coursera", "max_forks_repo_head_hexsha": "1be5124b07df61f7295dd1c5151b86b061bf50fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6862745098, "max_line_length": 97, "alphanum_fraction": 0.6943069307, "include": true, "reason": "import numpy", "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551505674444, "lm_q2_score": 0.8918110425624792, "lm_q1q2_score": 0.8604684777493304}}
{"text": "####################################################################################\n## PROBLEM1: Gradient Descent\n## Gradient descent is a popular optimization technique to solve many\n## machine learning problems. In this case, we will explore the gradient\n## descent algorithm to fit a line for the given set of 2-D points.\n## ref: https://tinyurl.com/yc4jbjzs\n## ref: https://spin.atomicobject.com/2014/06/24/gradient-descent-linear-regression/\n##\n##\n## input: directory of faces in ./data/1_points.csv/\n## function for reading points is provided\n##\n##\n## your task: fill the following functions:\n## evaluate_cost\n## evaluate_gradient\n## udpate_params\n## NOTE: do NOT change values of 'init_params' and 'max_iterations' in optimizer\n##\n##\n## output: cost after convergence (rmse, lower the better)\n##\n##\n## NOTE: all required modules are imported. DO NOT import new modules.\n## NOTE: references are given intline\n## tested on Ubuntu14.04, 22Oct2017, Abhilash Srikantha\n####################################################################################\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\ndef load_data(fname):\n    points = np.loadtxt(fname, delimiter=',') \n    y_ = points[:,1]\n    # append '1' to account for the intercept\n    x_ = np.ones([len(y_),2]) \n    x_[:,0] = points[:,0]\n    # display plot\n    #plt.plot(x_[:,0], y_, 'ro')\n    #plt.xlabel('x-axis')\n    #plt.ylabel('y-axis')\n    #plt.show()\n    print('data loaded. x:{} y:{}'.format(x_.shape, y_.shape))\n    return x_, y_\n\ndef evaluate_cost(x_,y_,params):\n    tempcost = 0\n    for i in range(len(y_)):\n        tempcost += (y_[i] - ((params[0] * x_[i,0]) + params[1])) ** 2 \n    return tempcost / float(10000)   \n\ndef evaluate_gradient(x_,y_,params):\n    m_gradient = 0\n    b_gradient = 0\n    N = float(len(y_))\n    for i in range(len(y_)):\n        m_gradient += -(2/N) * (x_[i,0] * (y_[i] - ((params[0] * x_[i,0]) + params[1])))\n        b_gradient += -(2/N) * (y_[i] - ((params[0] * x_[i,0]) + params[1]))\n    return [m_gradient,b_gradient]\n\ndef update_params(old_params, grad, alpha):\n    new_m = old_params[0] - (alpha * grad[0])\n    new_b = old_params[1] - (alpha * grad[1])\n    return [new_m,new_b]\n\n# initialize the optimizer\noptimizer = {'init_params':np.array([4.5,2.0]) , \n             'max_iterations':10000, \n             'alpha':0.69908, \n             'eps':0.0000001,\n             'inf':1e10}\n\n# load data\nx_, y_ = load_data(\"./data/1_points.csv\")\n\n# time stamp\nstart = time.time()\n\ntry:\n    # gradient descent\n    params = optimizer['init_params']\n    old_cost = 1e10\n    for iter_ in range(optimizer['max_iterations']):\n        # evaluate cost and gradient\n        cost = evaluate_cost(x_,y_,params)\n        grad = evaluate_gradient(x_,y_,params)\n        # display\n        if(iter_ % 10 == 0):\n            print('iter: {} cost: {} params: {}'.format(iter_, cost, params))\n        # check convergence\n        if(abs(old_cost - cost) < optimizer['eps']):\n            break\n        # udpate parameters\n        params = update_params(params,grad,optimizer['alpha'])\n        old_cost = cost\nexcept:\n    cost = optimizer['inf']\n\n# final output\nprint('time elapsed: {}'.format(time.time() - start))\nprint('cost at convergence: {} (lower the better)'.format(cost))\n", "meta": {"hexsha": "6c89d92128ebab7fdc69328b3863bcc7c5f99028", "size": 3265, "ext": "py", "lang": "Python", "max_stars_repo_path": "MachineLearning/gradient_descent.py", "max_stars_repo_name": "Sahil2rick/School-PythonProject", "max_stars_repo_head_hexsha": "e7a8c283446bf773c4456930f77c8c85c40f593c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MachineLearning/gradient_descent.py", "max_issues_repo_name": "Sahil2rick/School-PythonProject", "max_issues_repo_head_hexsha": "e7a8c283446bf773c4456930f77c8c85c40f593c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MachineLearning/gradient_descent.py", "max_forks_repo_name": "Sahil2rick/School-PythonProject", "max_forks_repo_head_hexsha": "e7a8c283446bf773c4456930f77c8c85c40f593c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6990291262, "max_line_length": 88, "alphanum_fraction": 0.593568147, "include": true, "reason": "import numpy", "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551515780318, "lm_q2_score": 0.8918110360927155, "lm_q1q2_score": 0.8604684724081986}}
{"text": "from numpy import sqrt\nimport matplotlib as pl\n'''\n@author: Arleigh Dickerson\n@see: p17 and 18 of Sauer's Numerical Analysis, example 0.6\n'''\n\n# square root of the result of b squared minus the quantity of 4 times a times c\ndef sqrtTerm(a, b, c): return sqrt((b ** 2) - (4 * a * c))\n\n# call to get x1 for a, b, c\ndef naiveX1(a, b, c): return (-b + sqrt((b ** 2) - (4 * a * c))) / (2 * a)\n\n# call to get x2 for a, b, c\n# copy and paste with - instead of +...\ndef naiveX2(a, b, c): return (-b - sqrt((b ** 2) - (4 * a * c))) / (2 * a)\n\n# second root (- part of eq) can be problematic if b is large compared to a or c\ndef naiveQuadratic(a, b, c):\n    # a tuple with both root values. Values will be identical if double root.\n    return (naiveX1(), naiveX2())\n\n# use if b and sqrt(bsquared minus 4ac) are nearly equal in magniture\n# and b is positive\ndef impl0dot13(a, b, c):\n    def x1(): return -(b + sqrtTerm(a, b, c)) / (2 * a)\n    def x2(): return -((2 * c) / (b + sqrtTerm(a, b, c)))\n    return (x1(), x2())\n\n# use if b and sqrt(bsquared minus 4ac) are nearly equal in magniture\n# and b is negative\ndef impl0dot14(a, b, c):\n    def x1(): return naiveX1(a, b, c)\n    def x2(): return ((2 * c) / (-b + sqrtTerm(a, b, c)))\n    return (x1(), x2())\n\ndef nearlyEqual(term0, term1) :\n    threshold = 0.001  # arbitrary (for now)\n    difference = abs(term0 - term1)\n    return difference < threshold\n", "meta": {"hexsha": "e263989906cd54054ac05f799112b2bdd4b99f01", "size": 1394, "ext": "py", "lang": "Python", "max_stars_repo_path": "Quadratic.py", "max_stars_repo_name": "arleighdickerson/NumericalAnalysis", "max_stars_repo_head_hexsha": "7b995e73c2036066ed6c5441371a7ea10fb2bb84", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Quadratic.py", "max_issues_repo_name": "arleighdickerson/NumericalAnalysis", "max_issues_repo_head_hexsha": "7b995e73c2036066ed6c5441371a7ea10fb2bb84", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Quadratic.py", "max_forks_repo_name": "arleighdickerson/NumericalAnalysis", "max_forks_repo_head_hexsha": "7b995e73c2036066ed6c5441371a7ea10fb2bb84", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0, "max_line_length": 80, "alphanum_fraction": 0.6147776184, "include": true, "reason": "from numpy", "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305297023093, "lm_q2_score": 0.8933094138654242, "lm_q1q2_score": 0.860462899905652}}
{"text": "from __future__ import print_function\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import stats\r\n\r\n\r\nnp.random.seed(3)\r\na = np.random.random(10)\r\nb = np.random.normal(size=10)\r\ntwo_samp = stats.ks_2samp(a,b)\r\n# since the p value is less than 0.05 I reject that the\r\n# two samples came from the same distribution\r\n# with a 95% confidence level.\r\n\r\n\r\n\r\nnp.random.seed(121)\r\nbinom_mars = stats.binom(100,0.0925)\r\nmars_rv = binom_mars.rvs(10)\r\nprint(np.mean(mars_rv))\r\nprint(binom_mars.cdf(10))\r\n\r\nx = np.arange(0,50,1)\r\nplt.figure()\r\nplt.plot(x, binom_mars.sf(x))\r\nplt.show()\r\n\r\n\r\nnp.random.seed(32332)\r\n# generate 1000 samples from the\r\nrv = stats.laplace.rvs(loc=75, scale=5, size=1000)\r\n\r\n# save the random variables as numpy array\r\nnp.save('Aluminum_youngs_moduli',rv)\r\n\r\n\r\n\r\n# fit a normal distribion\r\nnorm_param = stats.norm.fit(rv)\r\nlaplace_param = stats.laplace.fit(rv)\r\nmaxwell_param = stats.maxwell.fit(rv)\r\n# vonmises_param = stats.vonmises.fit(rv)\r\nlogistic_param = stats.logistic.fit(rv)\r\n\r\nx = np.linspace(10,150,200)\r\n\r\nplt.figure()\r\nplt.hist(rv, bins=21, normed=True)\r\nplt.plot(x, stats.norm.pdf(x, *norm_param), label='norm')\r\nplt.plot(x, stats.maxwell.pdf(x, *maxwell_param), label='maxwell_param')\r\n# plt.plot(x, stats.vonmises.pdf(x, *vonmises_param), label='vonmises_param')\r\nplt.plot(x, stats.logistic.pdf(x, *logistic_param), label='logistic_param')\r\nplt.plot(x, stats.laplace.pdf(x, *laplace_param), label='laplace')\r\nplt.legend()\r\nplt.show()\r\n\r\nplt.figure()\r\nplt.hist(rv, cumulative=True, bins=21, normed=True)\r\nplt.plot(x, stats.norm.cdf(x, *norm_param), label='norm')\r\nplt.plot(x, stats.maxwell.cdf(x, *maxwell_param), label='maxwell_param')\r\n# plt.plot(x, stats.vonmises.pdf(x, *vonmises_param), label='vonmises_param')\r\nplt.plot(x, stats.logistic.cdf(x, *logistic_param), label='logistic_param')\r\nplt.plot(x, stats.laplace.cdf(x, *laplace_param), label='laplace')\r\nplt.legend()\r\nplt.show()\r\n\r\n# ks_statistic\r\nks_norm = stats.kstest(rv, 'norm', norm_param)\r\nks_laplace = stats.kstest(rv, 'laplace', laplace_param)\r\nks_maxwell = stats.kstest(rv, 'maxwell', maxwell_param)\r\nks_logistic = stats.kstest(rv, 'logistic', logistic_param)\r\n\r\n# accept either the logistic or laplace!\r\n", "meta": {"hexsha": "b8958b758a403cf6e8e149884392ae3654fa4b96", "size": 2221, "ext": "py", "lang": "Python", "max_stars_repo_path": "lectures/lecture07/code/hw07.py", "max_stars_repo_name": "mateusza/Introduction-to-Python-Numerical-Analysis-for-Engineers-and-Scientist", "max_stars_repo_head_hexsha": "a27144cc8742e67af215e8de781bd208cc1f7436", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 101, "max_stars_repo_stars_event_min_datetime": "2017-11-28T15:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:59:49.000Z", "max_issues_repo_path": "lectures/lecture07/code/hw07.py", "max_issues_repo_name": "mateusza/Introduction-to-Python-Numerical-Analysis-for-Engineers-and-Scientist", "max_issues_repo_head_hexsha": "a27144cc8742e67af215e8de781bd208cc1f7436", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-12-16T19:41:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-16T19:41:39.000Z", "max_forks_repo_path": "lectures/lecture07/code/hw07.py", "max_forks_repo_name": "mateusza/Introduction-to-Python-Numerical-Analysis-for-Engineers-and-Scientist", "max_forks_repo_head_hexsha": "a27144cc8742e67af215e8de781bd208cc1f7436", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 54, "max_forks_repo_forks_event_min_datetime": "2017-12-15T19:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T23:36:55.000Z", "avg_line_length": 30.0135135135, "max_line_length": 78, "alphanum_fraction": 0.719045475, "include": true, "reason": "import numpy,from scipy", "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305328688783, "lm_q2_score": 0.8933094096048377, "lm_q1q2_score": 0.8604628986304509}}
{"text": "import solver.algorithms as alg\nimport numpy as np\n\ndef problem5(t0, tf, NA0, NB0, tau, n, returnlist=False):\n    \"\"\"Uses Euler's method to model the solution to a radioactive decay problem where dNA/dt = NB/tau - NA/tau and dNB/dt = NA/tau - NB/tau.\n\n    Args:\n        t0 (float): Start time\n        tf (float): End time\n        NA0 (int): Initial number of NA nuclei\n        NB0 (int): Initial number of NB nuclei\n        tau (float): Decay time constant\n        n (float): Number of points to sample at\n        returnlist (bool) = Controls whether the function returns the list of points or not. Defaults to false\n\n    Returns:\n        solution (list): Points on the graph of the approximate solution. Each element in the list has the form (t, array([NA, NB]))\n\n    In the graph, NA is green and NB is blue\n    \"\"\"\n    print(\"Problem 5: ~Radioactive Decay~ dNA/dt = NB/tau - NA/tau & dNB/dt = NA/tau - NB/tau.\")\n    N0 = np.array([NA0, NB0])\n    A = np.array([[-1/tau, 1/tau],[1/tau, -1/tau]])\n    def dN_dt(t, N):\n        return A @ N\n    h = (tf-t0)/(n-1)\n    print(\"Time step of %f seconds.\" % h)\n    solution = alg.euler(t0, tf, n, N0, dN_dt)\n    if returnlist:\n        return solution\n", "meta": {"hexsha": "405909191bce59aae4b9c8bda770ad73e18535ac", "size": 1193, "ext": "py", "lang": "Python", "max_stars_repo_path": "solver/problem5.py", "max_stars_repo_name": "suzannastep/eulers", "max_stars_repo_head_hexsha": "886da24546a490a11bc31ace4fbfa71536b129bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solver/problem5.py", "max_issues_repo_name": "suzannastep/eulers", "max_issues_repo_head_hexsha": "886da24546a490a11bc31ace4fbfa71536b129bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-21T22:07:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-21T22:07:51.000Z", "max_forks_repo_path": "solver/problem5.py", "max_forks_repo_name": "suzannastep/eulers", "max_forks_repo_head_hexsha": "886da24546a490a11bc31ace4fbfa71536b129bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4838709677, "max_line_length": 140, "alphanum_fraction": 0.6194467728, "include": true, "reason": "import numpy", "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305328688784, "lm_q2_score": 0.8933094010836643, "lm_q1q2_score": 0.8604628904225966}}
{"text": "\"\"\"\nCreated on Sat Apr 18 21:11:50 2020\n@author: Mohammad Asif Zaman\nDifferentiaion matrix operators in 1D and 2D\n-   First derivatives d/dx, d/dy\n-   Second derivatives d2/dx2, d2/dy2\nNotes:\n        - kron() is different in python compared to MATLAB. The matrix order is reveresed here.\n          MATLAB version:\n          Dx_2d = sp.kron(Dx_1d,Iy)\n          Dy_2d = sp.kron(Ix,Dy_1d)\n\"\"\"\n\nimport scipy.sparse as sp\n\ndef Diff_mat_1D(Nx):\n    \n    # First derivative\n    D_1d = sp.diags([-1, 1], [-1, 1], shape = (Nx,Nx)) # A division by (2*dx) is required later.\n    D_1d = sp.lil_matrix(D_1d)\n    D_1d[0,[0,1,2]] = [-3, 4, -1]               # this is 2nd order forward difference (2*dx division is required)\n    D_1d[Nx-1,[Nx-3, Nx-2, Nx-1]] = [1, -4, 3]  # this is 2nd order backward difference (2*dx division is required)\n    \n    # Second derivative\n    D2_1d =  sp.diags([1, -2, 1], [-1,0,1], shape = (Nx, Nx)) # division by dx^2 required\n    D2_1d = sp.lil_matrix(D2_1d)                  \n    D2_1d[0,[0,1,2,3]] = [2, -5, 4, -1]                    # this is 2nd order forward difference. division by dx^2 required. \n    D2_1d[Nx-1,[Nx-4, Nx-3, Nx-2, Nx-1]] = [-1, 4, -5, 2]  # this is 2nd order backward difference. division by dx^2 required.\n    \n    return D_1d, D2_1d\n\n\n\n\ndef Diff_mat_2D(Nx,Ny):\n    # 1D differentiation matrices\n    Dx_1d, D2x_1d = Diff_mat_1D(Nx)\n    Dy_1d, D2y_1d = Diff_mat_1D(Ny)\n\n\n    # Sparse identity matrices\n    Ix = sp.eye(Nx)\n    Iy = sp.eye(Ny)\n\n\n    \n    # 2D matrix operators from 1D operators using kronecker product\n    # First partial derivatives\n    Dx_2d = sp.kron(Iy,Dx_1d)\n    Dy_2d = sp.kron(Dy_1d,Ix)\n    \n    # Second partial derivatives\n    D2x_2d = sp.kron(Iy,D2x_1d)\n    D2y_2d = sp.kron(D2y_1d,Ix)\n    \n   \n    \n    # Return compressed Sparse Row format of the sparse matrices\n    return Dx_2d.tocsr(), Dy_2d.tocsr(), D2x_2d.tocsr(), D2y_2d.tocsr()", "meta": {"hexsha": "1840c632597b7d1bc2c4f8246632048087a32d60", "size": 1904, "ext": "py", "lang": "Python", "max_stars_repo_path": "diff_matrices.py", "max_stars_repo_name": "itrosen/hall-solver", "max_stars_repo_head_hexsha": "70ca5364b6c16bf62b7faa69ac30d14f972d7320", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "diff_matrices.py", "max_issues_repo_name": "itrosen/hall-solver", "max_issues_repo_head_hexsha": "70ca5364b6c16bf62b7faa69ac30d14f972d7320", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "diff_matrices.py", "max_forks_repo_name": "itrosen/hall-solver", "max_forks_repo_head_hexsha": "70ca5364b6c16bf62b7faa69ac30d14f972d7320", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2711864407, "max_line_length": 126, "alphanum_fraction": 0.6134453782, "include": true, "reason": "import scipy", "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305318133554, "lm_q2_score": 0.8933093989533708, "lm_q1q2_score": 0.8604628874277243}}
{"text": "import numpy as np\r\nimport pylab as pl\r\nimport random as rd\r\nimport time\r\n\r\n# Part a\r\n# First we use the 'random' package\r\n# Single seed used for generating a sequence of random numbers\r\nseed = 1\r\nrd.seed(seed)\r\n\r\nnum_sample = 10**5\r\n# Count the number of numbers generated\r\ncount = 0\r\n\r\n# Contains the numbers generated, starting the seed\r\nrannumrd = np.array([seed])\r\n\r\nwhile count < num_sample:\r\n    rannumrd = np.append(rannumrd, rd.random())\r\n    count = count + 1\r\n\r\npl.figure()\r\npl.hist(rannumrd, bins = np.linspace(0., 1., 100)) # 100 bins between 0 and 1\r\npl.xlabel(\"x\")\r\npl.ylabel(\"Number of counts in bin\")\r\npl.title(\"Distribution of 1e5 random numbers using 'random' package\")\r\n\r\n# Compare with 'numpy.random.uniform' for uniform deviation\r\n# numpy.seed does not allow seed dtype = float, must be integers\r\n# Also all numerical inputs below must be integers\r\nnp.random.seed(seed)\r\n\r\nrannumnp = np.array([seed])\r\nrannumnp = np.append(rannumnp, np.random.uniform(low = 0, high = 1, size = num_sample))\r\n\r\npl.figure()\r\npl.hist(rannumnp, bins = np.linspace(0., 1., 100)) # 100 bins\r\npl.xlabel(\"x\")\r\npl.ylabel(\"Number of counts in bin\")\r\npl.title(\"Distribution of 1e5 random numbers using 'numpy.random.uniform' package\")\r\n\r\n# Conclusion: random.random is a better method to use\r\n\r\n# Part b - transformation method\r\n# Transforming from uniform P(x) into the PDF given, integrating the PDF between \r\n# 0 and y and equating to x,\r\n# the relation between x and y was found to be y = cos^-1 (1 - 2*x)\r\n\r\n# Using x values computed from 'random' package in part a, compute corresponding y\r\nstart_time_trans = time.clock() # Records the start time\r\ny = np.arccos(1-2*rannumrd)\r\ntime_trans = time.clock() - start_time_trans # Records the end time and subtract from\r\n# start to check running time for this method\r\n\r\n# Plotting sine function to check\r\ncheck = np.linspace(0., np.pi, 500) # Used for plotting comparison function and predicted PDF\r\npl.figure()\r\n(count, bins, patches) = pl.hist(y, bins = np.linspace(0., np.pi, 100),\r\nnormed=True, label = \"Histogram of sinusoidal distribution\")\r\n# 100 bins between 0 and pi\r\npl.plot(check, 0.5*np.sin(check), 'r-', label = \"Predicted PDF\")\r\npl.xlabel(\"y\")\r\npl.ylabel(\"Normalised PDF\")\r\npl.legend()\r\npl.title(\"Distribution of 1e5 random numbers using a sinusoidal distribution\")\r\n\r\n# Part c - rejection method\r\n# PDF (y) takes the values of the sin function in part b and substitute into\r\n# the new PDF given.\r\nPDF = 2./np.pi*(np.sin(y))**2.\r\ncomp = np.linspace(0., np.pi, 10**5.+1.)\r\nPDFcomp = 2./np.pi*(np.sin(y))\r\n\r\n# Accept = array containing all accepted values\r\naccept = np.array([])\r\n# Counters to keep track of when to stop iterating\r\nnum_accept = 0.\r\nnum_trials = 0.\r\n\r\nstart_time_rej = time.clock() # Records the start time\r\nwhile num_accept < num_sample:\r\n    indexP = rd.randrange(PDF.size)\r\n    compval = rd.uniform(0, PDFcomp[indexP])\r\n    if PDF[indexP] >= compval:\r\n        accept = np.append(accept, y[indexP])\r\n        num_accept += 1.\r\n    num_trials += 1.\r\ntime_rej = time.clock() - start_time_rej # Records the end time and subtract from\r\n# start to check running time for this method\r\n\r\npl.figure()\r\n(count2, bins2, patches2) = pl.hist(accept, bins = np.linspace(0., np.pi, 100),\r\nnormed=True, label = \"Histogram of sine squared distribution\") # 100 bins between 0 and pi\r\npl.plot(check, 2./np.pi*(np.sin(check))**2, 'r-', label = \"Predicted PDF\")\r\npl.plot(check, 2./np.pi*(np.sin(check)), 'k-', label = \"Comparison function\")\r\npl.legend()\r\npl.xlabel(\"y\")\r\npl.ylabel(\"Normalised PDF\")\r\npl.title(\"Distribution of 1e5 random numbers using a sine squared distribution\")\r\n\r\n# Check measuring times\r\nprint(time_trans, time_rej, time_trans/time_rej)", "meta": {"hexsha": "ca785d25421db0af73b96a60574d4e49da568b4f", "size": 3710, "ext": "py", "lang": "Python", "max_stars_repo_path": "Random_5.py", "max_stars_repo_name": "adrielyeung/computational-physics", "max_stars_repo_head_hexsha": "c34c881b2e6ff29aebce6d0eb6d8d8404648ec71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-04T18:44:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-04T18:44:00.000Z", "max_issues_repo_path": "Random_5.py", "max_issues_repo_name": "adrielyeung/computational-physics", "max_issues_repo_head_hexsha": "c34c881b2e6ff29aebce6d0eb6d8d8404648ec71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Random_5.py", "max_forks_repo_name": "adrielyeung/computational-physics", "max_forks_repo_head_hexsha": "c34c881b2e6ff29aebce6d0eb6d8d8404648ec71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0194174757, "max_line_length": 94, "alphanum_fraction": 0.6978436658, "include": true, "reason": "import numpy", "num_tokens": 997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079558, "lm_q2_score": 0.904650538956921, "lm_q1q2_score": 0.8604513206883688}}
{"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.misc import comb\nfrom numpy.random import rand\n\n# Decasteljau's algorithm problem\ndef decasteljau(p,t):\n    \"\"\" Evaluates a Bezier curve with control points 'p' at time 't'.\n    The points in 'p' are assumed to be stored in its rows.\n    'p' is assumed to be 2-dimensional.\"\"\"\n    pass\n\n# Bernstein polynomial problem\ndef bernstein(i, n):\n    \"\"\" Returns the 'i'th Bernstein polynomial of degree 'n'.\"\"\"\n    pass\n\n# Coordinate function problem.\ndef bernstein_pt_aprox(X):\n    \"\"\" Returns the 'x' and 'y' coordinate functions for a 2-dimensional\n    Bezier curve with control points 'X'.\"\"\"\n    pass\n\n# plot demonstrating numerical instability in Bernstein polys.\ndef compare_plot(n, res=501):\n    \"\"\" Produces a plot showing a Bezier curve evaluated via\n    the Decasteljau algorithm and a Bezier curve evaluated using\n    Bernstein polynomials. Control points are chosen randomly.\n    Instability should be evident for moderately large values of 'n'.\"\"\"\n", "meta": {"hexsha": "645e2d0b2bfa7c0470acba106062058581b4ec51", "size": 1022, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/BSplines/bezier_solutions_template.py", "max_stars_repo_name": "jessicaleete/numerical_computing", "max_stars_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-10-18T19:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:12:38.000Z", "max_issues_repo_path": "Labs/BSplines/bezier_solutions_template.py", "max_issues_repo_name": "jessicaleete/numerical_computing", "max_issues_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/BSplines/bezier_solutions_template.py", "max_forks_repo_name": "jessicaleete/numerical_computing", "max_forks_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-14T16:07:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-20T09:05:06.000Z", "avg_line_length": 34.0666666667, "max_line_length": 72, "alphanum_fraction": 0.7279843444, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.904650530602188, "lm_q1q2_score": 0.8604513190062387}}
{"text": "import numpy as np\nimport scipy\n\n__all__ = ['slepian_filter','slepian_psd']\n\ndef slepian_filter(length, filter_band_length, order=None):    \n    ''' \n    Slepian filters bank.\n    \n    Parameters\n    --------------------\n    * length: int,\n        the length pf signal.\n    * filter_band_length: [int, int],\n        filter bandwidth with respect to length \n        (in points).\n    * order: int,\n        order of the filter.\n    \n    Returns\n    ------------------\n    * Matrix of filter windows: 2d ndarray,\n        base_band_ratio x order with Slepian \n        sequence in the colunms.\n    \n    Refernce\n    ---------------\n    [1a] P. Stoica, R.L. Moses, \n        Spectral analysis of signals \n        - New-York: Present-Hall, 2005.\n    [1b] http://www2.ece.ohio-state.edu/~randy/SAtext/ \n            - Dr.Moses Spectral Analysis of Signals: Resource Page.\n    \n    Examples\n    ---------------\n        h = slepian_filter(256,4,4)\n        plt.plot(h[:,1])\n        \n    '''\n    N = length\n    K = filter_band_length\n    \n    if(order is None): order = filter_band_length\n        \n    vect = K/N*np.sinc(K/N*np.arange(N)) \n    gamma = scipy.linalg.toeplitz(vect)\n    D,V=np.linalg.eig(gamma)\n\n    h=V[:,:order]\n    \n    if np.sum(h[:,1])<0:\n        h[:,1]=-h[:,1]\n    \n    return h\n    \n#---------------------------------------    \ndef slepian_psd(x, order, n_psd=None):\n    '''\n    Estimation of the pseudo-spectrum based on the \n        Slepian - Refil algorithm.\n      \n    Parameters\n    -------------------\n    * x: 1d ndarray.\n    * order: int, \n        order of the model.\n    * n_psd: int or None,\n        number of samples in psd.\n    \n    Returns\n    ------------------------\n    * pseudo-spectrum: 1d ndarray.\n      \n    Refernce\n   ------------------------\n    [1a] P. Stoica, R.L. Moses, \n        Spectral analysis of signals \n        - New-York: Present-Hall, 2005.\n    [1b] http://www2.ece.ohio-state.edu/~randy/SAtext/ \n         Dr.Moses Spectral Analysis of Signals: Resource Page.\n    \n    Examples\n    ------------------------\n    \n    See also\n    ------------------------\n    capone\n    \n    \n    '''\n    x=np.array(x) \n    N=x.shape[0]  \n    \n    if(n_psd is None):\n        n_psd=N\n    \n    h=slepian_filter(N,order,order)\n    \n    psd = np.zeros(n_psd)\n    \n    for i in np.arange(order):\n        sp   = np.fft.fft(x*h[:,i],n_psd)\n        psd += np.real(sp*np.conj(sp))# 0 imagenary part remain\n\n    return psd\n\n", "meta": {"hexsha": "c56aae19bb3e8b508f21ed53587a79c732fc4138", "size": 2437, "ext": "py", "lang": "Python", "max_stars_repo_path": "dsatools/_base/_classic_psd/_slepian.py", "max_stars_repo_name": "diarmaidocualain/dsatools", "max_stars_repo_head_hexsha": "50b9259e2846b5fdd3dc52206967b0ee8d0144de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2020-09-14T16:12:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T01:44:18.000Z", "max_issues_repo_path": "dsatools/_base/_classic_psd/_slepian.py", "max_issues_repo_name": "Jimmy-INL/dsatools", "max_issues_repo_head_hexsha": "5c811838bb3fb8ae00195d5f68e451bd23b3448c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-09-24T17:47:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T08:06:43.000Z", "max_forks_repo_path": "dsatools/_base/_classic_psd/_slepian.py", "max_forks_repo_name": "Jimmy-INL/dsatools", "max_forks_repo_head_hexsha": "5c811838bb3fb8ae00195d5f68e451bd23b3448c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-12-06T08:18:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T13:28:22.000Z", "avg_line_length": 22.7757009346, "max_line_length": 67, "alphanum_fraction": 0.4997948297, "include": true, "reason": "import numpy,import scipy", "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422158380862, "lm_q2_score": 0.9046505331728751, "lm_q1q2_score": 0.8604513126811546}}
{"text": "import numpy as np\nfrom scipy.stats import logistic\nimport matplotlib.pyplot as plt\n\nclass LogisticRegressioner(object):\n    def __init__(self, tol=1e-6):\n        self.tol = tol\n\n    def first_derivative(self, X, Y, w):\n        \"\"\"\n        Calculate the 1st derivative of log-loss function\n        \"\"\"\n        d, T = X.shape\n        sigma = logistic.cdf(np.multiply(-Y, np.dot(w.T, X)))\n        ret = np.multiply(sigma, Y)\n        ret = np.multiply(np.repeat(ret[np.newaxis, :], d, axis=0), X)\n        ret = np.sum(ret, axis=1)\n        return ret\n\n    def log_loss(self, X, Y, w):\n        L = np.log(logistic.cdf(np.multiply(Y, np.dot(w.T, X))))\n        L = np.sum(L)\n        L = -L\n        return L\n\n    def classifier_w(self, X, Y,eta=0.05):\n        \"\"\"\n        and returns a classification vector w \\in Rp obtained by gradient\n        descent on the logistic regression loss function\n        \"\"\"\n        X = X.T\n        d, T = X.shape\n        X = np.vstack([np.ones((T, )), X])  # add bias 1\n        d += 1\n        w = np.zeros(d)\n        t = 0\n        while True:\n            t += 1\n            w_ = w + eta*self.first_derivative(X, Y, w)\n            L_old, L_new = self.log_loss(X, Y, w_), self.log_loss(X, Y, w)\n            if np.abs(L_old - L_new) < self.tol: break\n            w = w_\n            if t % 300 == 1: yield w  # yield for trace the w\n\n        yield w\n\n    def test_sample(self):\n        X = np.array([\n            [2, 1],\n            [1, 20],\n            [1, 5],\n            [4, 1],\n            [1, 40],\n            [3, 30],\n        ])\n\n        Y = np.array([\n            -1,\n            -1,\n            -1,\n            1,\n            1,\n            1,\n        ])\n        ws = list(self.classifier_w(X, Y))\n        print ws[-1]\n", "meta": {"hexsha": "40d5c56e420714ab7ccc16d567e3e94303af1d68", "size": 1748, "ext": "py", "lang": "Python", "max_stars_repo_path": "scipy_util/regressions/logistic_regression.py", "max_stars_repo_name": "idf/sci_util_py", "max_stars_repo_head_hexsha": "53b4d961a1a8faeb444d2972ca7a2baf4a966f6e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scipy_util/regressions/logistic_regression.py", "max_issues_repo_name": "idf/sci_util_py", "max_issues_repo_head_hexsha": "53b4d961a1a8faeb444d2972ca7a2baf4a966f6e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-02-10T19:17:20.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-10T20:04:59.000Z", "max_forks_repo_path": "scipy_util/regressions/logistic_regression.py", "max_forks_repo_name": "idf/scipy_util", "max_forks_repo_head_hexsha": "53b4d961a1a8faeb444d2972ca7a2baf4a966f6e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0895522388, "max_line_length": 74, "alphanum_fraction": 0.4605263158, "include": true, "reason": "import numpy,from scipy", "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639653084244, "lm_q2_score": 0.8856314828740729, "lm_q1q2_score": 0.8604476353031142}}
{"text": "import numpy as np\nimport numpy.linalg as npla\n\ndef qr_iteration(A, tol):\n    # Your implementation goes here\n    \n    for i in range(A.shape[1] - 1, 0, -1):\n        while npla.norm(A[i - 1, :i - 1], ord=2) > tol:\n            sigma = A[i, i]\n            Q, R = npla.qr(A - sigma * np.diag(np.diag(np.ones(A.shape))))\n            A = np.dot(R, Q) + sigma * np.diag(np.diag(np.ones(A.shape)))\n    \n    return np.diag(A)\n\ndef main():\n\t\n\ttol = 10 ** (-16)\n\tA_1 = np.array([[2, 3, 2], [10, 3, 4], [3, 6, 1]])\n\teigenvalues_1 = qr_iteration(A_1.copy(), tol)\n\tprint(\"Matrix:\\n\", A_1)\n\tprint(\"\\n\")\n\tprint (\"Computed eigenvalues: \", eigenvalues_1)\n\tprint (\"Actual eigenvalues: \", np.linalg.eigvals(A_1))\n\n\tprint(\"\\n\\n\")\n\n\ttol = 10 ** (-16)\n\tA_2 = np.array([[6, 2, 1], [2, 3, 1], [1, 1, 1]])\n\teigenvalues_2 = qr_iteration(A_2.copy(), tol)\n\tprint(\"Matrix:\\n\", A_2)\n\tprint(\"\\n\")\n\tprint (\"Computed eigenvalues: \", eigenvalues_2)\n\tprint (\"Actual eigenvalues: \", np.linalg.eigvals(A_2))\n\nif __name__ == '__main__':\n\tmain()\n        \n\t", "meta": {"hexsha": "d2870e5af8a2f6d1d2678396f8061d6be75b494f", "size": 1017, "ext": "py", "lang": "Python", "max_stars_repo_path": "a3/problem_5.py", "max_stars_repo_name": "justachetan/scientific-computing", "max_stars_repo_head_hexsha": "e8493b5308c337ea8965a5f96cdd49def94801e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-04-30T14:03:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T19:19:13.000Z", "max_issues_repo_path": "a3/problem_5.py", "max_issues_repo_name": "justachetan/scientific-computing", "max_issues_repo_head_hexsha": "e8493b5308c337ea8965a5f96cdd49def94801e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "a3/problem_5.py", "max_forks_repo_name": "justachetan/scientific-computing", "max_forks_repo_head_hexsha": "e8493b5308c337ea8965a5f96cdd49def94801e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7631578947, "max_line_length": 74, "alphanum_fraction": 0.5703048181, "include": true, "reason": "import numpy", "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639644850629, "lm_q2_score": 0.885631470799559, "lm_q1q2_score": 0.8604476228427567}}
{"text": "\"\"\"\nAnkit Khandelwal\n15863\nExercise 10\n\"\"\"\n\nfrom math import exp\n\nimport numpy as np\n\ni = 3 * 10 ** -9\nVt = 0.05\nV = 5.\nR1 = 1000.\nR2 = 4000.\nR3 = 3000.\nR4 = 2000.\n\n\ndef f1(V1, V2):\n    return R2 * (V1 - V) + R1 * V1 + R1 * R2 * i * (exp((V1 - V2) / Vt) - 1)\n\n\ndef f2(V1, V2):\n    return R4 * (V2 - V) + R3 * V2 - R3 * R4 * i * (exp((V1 - V2) / Vt) - 1)\n\n\ndef df1_x(V1, V2):\n    return R2 + R1 + R1 * R2 * i * exp((V1 - V2) / Vt) / Vt\n\n\ndef df1_y(V1, V2):\n    return -R1 * R2 * i * exp((V1 - V2) / Vt) / Vt\n\n\ndef df2_x(V1, V2):\n    return -R3 * R4 * i * exp((V1 - V2) / Vt) / Vt\n\n\ndef df2_y(V1, V2):\n    return R4 + R3 + R3 * R4 * i * exp((V1 - V2) / Vt) / Vt\n\n\nx1 = 4.\ny1 = 2.\nf = np.zeros([2, 1])\nJ = np.zeros([2, 2])\nr1 = np.zeros([2, 1])\nr1[0, 0] = x1\nr1[1, 0] = y1\nd = np.ones([2, 1])\nwhile abs(d[0]) > 10 ** -7 and abs(d[1]) > 10 ** -7:\n    V1 = r1[0, 0]\n    V2 = r1[1, 0]\n    f[0, 0] = f1(V1, V2)\n    f[1, 0] = f2(V1, V2)\n    f1x = df1_x(V1, V2)\n    f1y = df1_y(V1, V2)\n    f2x = df2_x(V1, V2)\n    f2y = df2_y(V1, V2)\n    J[0, 0] = f2y\n    J[0, 1] = -f1y\n    J[1, 0] = -f2x\n    J[1, 1] = f1x\n    J = (1 / (f1x * f2y - f1y * f2x)) * J\n    d = np.dot(J, f)\n    r1 = r1 - d\n\nprint(\"V1 = \", r1[0, 0], \"V\\nV2 = \", r1[1, 0], \"V\")\nprint(\"V = V1 - V2 = \", r1[0, 0] - r1[1, 0], \"V\")\n", "meta": {"hexsha": "a47ae78045e594cf78dce77616e7f77452100f09", "size": 1281, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ankit Khandelwal_HW3/Exercise 10/exercise 10.py", "max_stars_repo_name": "ankit27kh/Computational-Physics-PH354", "max_stars_repo_head_hexsha": "d37c93e430a0f282251a814456890acb4a2961fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ankit Khandelwal_HW3/Exercise 10/exercise 10.py", "max_issues_repo_name": "ankit27kh/Computational-Physics-PH354", "max_issues_repo_head_hexsha": "d37c93e430a0f282251a814456890acb4a2961fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ankit Khandelwal_HW3/Exercise 10/exercise 10.py", "max_forks_repo_name": "ankit27kh/Computational-Physics-PH354", "max_forks_repo_head_hexsha": "d37c93e430a0f282251a814456890acb4a2961fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0422535211, "max_line_length": 76, "alphanum_fraction": 0.4457455113, "include": true, "reason": "import numpy", "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639694252315, "lm_q2_score": 0.8856314632529872, "lm_q1q2_score": 0.8604476198859483}}
{"text": "import math\nimport numpy\nfrom numpy import linalg\n\nclass HMM(object):\n\n    def __init__(self, \n        pi: numpy.ndarray, \n        T: numpy.matrix, \n        O: numpy.matrix,\n        states=None,\n        emissions=None):\n\n        \"\"\"\n        pi: initial probability distribution\n        T : transition probability matrix\n        O : emission probability matrix\n        states: list of state names\n        emissions: list of emission names\n        \"\"\"\n\n        self.pi = pi\n        assert(len(pi) == T.shape[0])\n        assert(sum(pi) == 1)\n\n        self.T = T\n        assert(T.shape[0] == T.shape[1])\n        assert(int(sum(T.A1)) == T.shape[0])\n\n        self.O = O\n        assert(O.shape[0] == T.shape[0])\n        assert(int(sum(O.A1)) == O.shape[0])\n\n        self.states = states\n        if self.states:\n            assert(len(self.states) == T.shape[0])\n        \n        self.emissions = emissions\n        if self.emissions:\n            assert(len(emissions) == O.shape[1])\n    \n    def allclose(self, A: numpy.matrix, B: numpy.matrix, **kwargs):\n        \"\"\"\n        Since `numpy.allclose` method doesn't work as expected\n        \"\"\"\n        return numpy.all(list(map(\n            lambda a,b: math.isclose(a, b, **kwargs), A.A1, B.A1 \n        )))\n\n    def stationary_dist(self, type: str, **kwargs):\n        \"\"\"\n        Given a transition probabilities matrix T, this function computes\n        the stationary distribution pi. One can choose two different methods:\n        - naive: power method; loop until T^k == T^(k+1), within a certain tolerance\n        (look at the method `numpy.allclose`)\n        - linear: solve a linear system pi' = (pi * T)', where pi is a row vector of\n        indipendent variables\n        It returns the array of stationary distribution and the power k+1 such that\n        T^k = T^(k+1), None if type is linear\n\n        **kwargs is the keyword argument accepted by `math.isclose` function\n        \"\"\"\n        # Check that T is a square matrix\n        # assert(reduce(operator.and_, [len(row) == len(T) for row in T]) == True)\n        assert(self.T.shape[0] == self.T.shape[1])\n        if type == 'naive':\n            T_k = self.T\n            T_k_1 = self.T ** 2\n            power = 2\n            while (not self.allclose(T_k, T_k_1, **kwargs)):\n                T_k = T_k_1\n                T_k_1 = T_k * self.T\n                power += 1\n            return numpy.array(T_k_1[0].flat), power\n        elif type == 'linear':\n            \"\"\"\n            The linear system that one might resolve is, \n            with pi a row vector of indipendent variables:\n            (pi * T)' = pi'\n            T' * pi' - pi' = 0\n            Since pi is the vector of indipendent variables, the operation (- pi')\n            is the same as subtract 1 from every element in the diagonal of T' * pi'.\n            In order to obtain a unique solution we must replace one of the equation\n            with sum(pi_i) = 1 for all i from 0 to n-1. In this case I choose the first one\n            \"\"\"\n            self.T = self.T.T\n            self.T[numpy.diag_indices_from(self.T)] -= 1\n            self.T[0,:] = numpy.ones(self.T.shape[0])\n            b = numpy.zeros(self.T.shape[0])\n            b[0] = 1\n            return linalg.solve(self.T, b), None\n        else:\n            raise Exception('Type unspecified')\n\n    def forward(self, observations):\n        f = self.pi\n        message_f = [f]\n        for obs in observations:\n            f = (f @ self.T @ numpy.diag(self.O[:, obs].T.A1)).A1\n            message_f.append(f / sum(f))\n        return message_f\n\n    def backward(self, observations):\n        b = [1, 1]\n        message_b = [b]\n        for i in range(len(observations)-1, -1, -1):\n            b = (self.T @ numpy.diag(self.O[:, observations[i]].T.A1) @ b).A1\n            message_b.append(b / sum(b))\n        return message_b\n\n    def smoothing(self, observations):\n        def normalized_hadamard(v1, v2):\n            res = numpy.multiply(v1, v2)\n            return res / sum(res)\n\n        return list(\n            map(normalized_hadamard, \n                self.forward(observations), \n                list(reversed(self.backward(observations)))\n            )\n        )\n\n    def viterbi(self, observations: list):\n        \"\"\"\n        Viterbi algorithm in matrix form\n        \"\"\"\n        # Compute initial probability given the first observation\n        S = numpy.matrix(numpy.diag(self.pi) @ numpy.diag(self.O[:, observations[0]].T.A1))\n        saved_max = []\n        for obs in observations[1:]:\n            # Get, for every cols, the row of the max value\n            amax = numpy.argmax(S, axis=0).A1\n            max_per_col = []\n            # Get max values per columns\n            for col in range(len(self.T)):\n                max_per_col.append(S[amax[col], col])\n            # 'Forward' pass\n            S = numpy.diag(max_per_col) @ self.T @ numpy.diag(self.O[:, obs].T.A1)\n            # Save where the maximum comes from (needed fro the 'backward' pass)\n            saved_max.append(amax)\n        # Get indices of the global max\n        row, col = numpy.unravel_index(numpy.argmax(S, axis=None), S.shape)\n        # Cols will be the state, row becomes col while running backward\n        sequence = [self.states[col] if self.states else col]\n        for i in range(len(saved_max)-1, -1, -1):\n            sequence.append(self.states[row] if self.states else row)\n            row = saved_max[i][row]\n        return list(reversed(sequence))\n\nif __name__ == \"__main__\":\n    pi = numpy.array([0.52, 0.48])\n    T = numpy.matrix([[0.6, 0.4], [0.17, 0.83]])\n    O = numpy.matrix([[1/10, 1/10, 1/10, 1/10, 1/10, 1/2], [1/6]*6])\n    \n    # pi = numpy.array([0.98, 0.02])\n    # T = numpy.matrix([[0.4, 0.6], [0.1, 0.9]])\n    # O = numpy.matrix([[0.8, 0.2], [0.1, 0.9]])\n    \n    # pi = numpy.array([.5, .5])\n    # T = numpy.matrix([[.7, .3], [.3, .7]])\n    # O = numpy.matrix([[.9, .1], [.2, .8]])\n\n    hmm = HMM(pi, T, O, ['Loaded', 'Fair'])\n    \n    print(hmm.viterbi([2,0,5,5,5,3]))\n    # print(hmm.viterbi([1, 0, 1]))\n    # print(hmm.forward([0, 0, 1, 0]))\n    # print(list(reversed(hmm.backward([0, 0, 1, 0]))))\n    print(hmm.smoothing([0, 0, 1, 0]))\n        \n\n", "meta": {"hexsha": "57074fde835cdf734a8feff1613b837fdb08d13b", "size": 6187, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/HMM.py", "max_stars_repo_name": "belerico/spqrisiko-abm", "max_stars_repo_head_hexsha": "f586b687f99a3195a0b4bef0bb001c318f764255", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HMM.py", "max_issues_repo_name": "belerico/spqrisiko-abm", "max_issues_repo_head_hexsha": "f586b687f99a3195a0b4bef0bb001c318f764255", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-30T22:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-30T22:08:14.000Z", "max_forks_repo_path": "src/HMM.py", "max_forks_repo_name": "belerico/spqrisiko-abm", "max_forks_repo_head_hexsha": "f586b687f99a3195a0b4bef0bb001c318f764255", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9709302326, "max_line_length": 91, "alphanum_fraction": 0.5367706481, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966101527047, "lm_q2_score": 0.9019206804839998, "lm_q1q2_score": 0.8604017554479426}}
{"text": "\"\"\"\nModule: libfmp.c2.c2_fourier\nAuthor: Frank Zalkow, Meinard Müller\nLicense: The MIT license, https://opensource.org/licenses/MIT\n\nThis file is part of the FMP Notebooks (https://www.audiolabs-erlangen.de/FMP)\n\"\"\"\nimport numpy as np\nfrom numba import jit\nimport librosa\n\n\n@jit(nopython=True)\ndef generate_matrix_dft(N, K):\n    \"\"\"Generates a DFT (discrete Fourier transfrom) matrix\n\n    Notebook: C2/C2_DFT-FFT.ipynb\n\n    Args:\n        N (int): Number of samples\n        K (int): Number of frequency bins\n\n    Returns:\n        dft (np.ndarray): The DFT matrix\n    \"\"\"\n    dft = np.zeros((K, N), dtype=np.complex128)\n    for n in range(N):\n        for k in range(K):\n            dft[k, n] = np.exp(-2j * np.pi * k * n / N)\n    return dft\n\n\n@jit(nopython=True)\ndef generate_matrix_dft_inv(N, K):\n    \"\"\"Generates an IDFT (inverse discrete Fourier transfrom) matrix\n\n    Notebook: C2/C2_STFT-Inverse.ipynb\n\n    Args:\n        N (int): Number of samples\n        K (int): Number of frequency bins\n\n    Returns:\n        dft (np.ndarray): The IDFT matrix\n    \"\"\"\n    dft = np.zeros((K, N), dtype=np.complex128)\n    for n in range(N):\n        for k in range(K):\n            dft[k, n] = np.exp(2j * np.pi * k * n / N) / N\n    return dft\n\n\n@jit(nopython=True)\ndef dft(x):\n    \"\"\"Compute the disrcete Fourier transfrom (DFT)\n\n    Notebook: C2/C2_DFT-FFT.ipynb\n\n    Args:\n        x (np.ndarray): Signal to be transformed\n\n    Returns:\n        X (np.ndarray): Fourier transform of x\n    \"\"\"\n    x = x.astype(np.complex128)\n    N = len(x)\n    dft_mat = generate_matrix_dft(N, N)/N\n    return np.dot(dft_mat, x)\n\n\n@jit(nopython=True)\ndef idft(X):\n    \"\"\"Compute the inverse discrete Fourier transfrom (IDFT)\n\n    Args:\n        X (np.ndarray): Signal to be transformed\n\n    Returns:\n        x (np.ndarray): Inverse Fourier transform of X\n    \"\"\"\n    X = X.astype(np.complex128)\n    N = len(X)\n    dft_mat = generate_matrix_dft_inv(N, N)\n    return np.dot(dft_mat, X)\n\n\n@jit(nopython=True)\ndef twiddle(N):\n    \"\"\"Generate the twiddle factors used in the computation of the fast Fourier transform (FFT)\n\n    Notebook: C2/C2_DFT-FFT.ipynb\n\n    Args:\n        N (int): Number of samples\n\n    Returns:\n        sigma (np.ndarray): The twiddle factors\n    \"\"\"\n    k = np.arange(N // 2)\n    sigma = np.exp(-2j * np.pi * k / N)\n    return sigma\n\n\n@jit(nopython=True)\ndef twiddle_inv(N):\n    \"\"\"Generate the twiddle factors used in the computation of the Inverse fast Fourier transform (IFFT)\n\n    Args:\n        N (int): Number of samples\n\n    Returns:\n        sigma (np.ndarray): The twiddle factors\n    \"\"\"\n    n = np.arange(N // 2)\n    sigma = np.exp(2j * np.pi * n / N)\n    return sigma\n\n\n@jit(nopython=True)\ndef fft(x):\n    \"\"\"Compute the fast Fourier transform (FFT)\n\n    Notebook: C2/C2_DFT-FFT.ipynb\n\n    Args:\n        x (np.ndarray): Signal to be transformed\n\n    Returns:\n        X (np.ndarray): Fourier transform of x\n    \"\"\"\n    x = x.astype(np.complex128)\n    N = len(x)\n    log2N = np.log2(N)\n    assert log2N == int(log2N), 'N must be a power of two!'\n    X = np.zeros(N, dtype=np.complex128)\n\n    if N == 1:\n        return x\n    else:\n        this_range = np.arange(N)\n        A = fft(x[this_range % 2 == 0])\n        B = fft(x[this_range % 2 == 1])\n        C = twiddle(N) * B\n        X[:N//2] = A + C\n        X[N//2:] = A - C\n        return X\n\n\n@jit(nopython=True)\ndef ifft_noscale(X):\n    \"\"\"Compute the inverse fast Fourier transform (IFFT) without the final scaling factor of 1/N\n\n    Args:\n        X (np.ndarray): Fourier transform of x\n\n    Returns:\n        x (np.ndarray): Inverse Fourier transform of X\n    \"\"\"\n    X = X.astype(np.complex128)\n    N = len(X)\n    log2N = np.log2(N)\n    assert log2N == int(log2N), 'N must be a power of two!'\n    x = np.zeros(N, dtype=np.complex128)\n\n    if N == 1:\n        return X\n    else:\n        this_range = np.arange(N)\n        A = ifft_noscale(X[this_range % 2 == 0])\n        B = ifft_noscale(X[this_range % 2 == 1])\n        C = twiddle_inv(N) * B\n        x[:N//2] = A + C\n        x[N//2:] = A - C\n        return x\n\n\n@jit(nopython=True)\ndef ifft(X):\n    \"\"\"Compute the inverse fast Fourier transform (IFFT)\n\n    Args:\n        X (np.ndarray): Fourier transform of x\n\n    Returns:\n        x (np.ndarray): Inverse Fourier transform of X\n    \"\"\"\n    return ifft_noscale(X) / len(X)\n\n\ndef stft_basic(x, w, H=8, only_positive_frequencies=False):\n    \"\"\"Compute a basic version of the discrete short-time Fourier transform (STFT)\n\n    Notebook: C2/C2_STFT-Basic.ipynb\n\n    Args:\n        x (np.ndarray): Signal to be transformed\n        w (np.ndarray): Window function\n        H (int): Hopsize (Default value = 8)\n        only_positive_frequencies (bool): Return only positive frequency part of spectrum (non-invertible)\n            (Default value = False)\n\n    Returns:\n        X (np.ndarray): The discrete short-time Fourier transform\n    \"\"\"\n    N = len(w)\n    L = len(x)\n    M = np.floor((L - N) / H).astype(int) + 1\n    X = np.zeros((N, M), dtype='complex')\n    for m in range(M):\n        x_win = x[m * H:m * H + N] * w\n        X_win = np.fft.fft(x_win)\n        X[:, m] = X_win\n\n    if only_positive_frequencies:\n        K = 1 + N // 2\n        X = X[0:K, :]\n    return X\n\n\ndef istft_basic(X, w, H, L):\n    \"\"\"Compute the inverse of the basic discrete short-time Fourier transform (ISTFT)\n\n    Notebook: C2/C2_STFT-Inverse.ipynb\n\n    Args:\n        X (np.ndarray): The discrete short-time Fourier transform\n        w (np.ndarray): Window function\n        H (int): Hopsize\n        L (int): Length of time signal\n\n    Returns:\n        x (np.ndarray): Time signal\n    \"\"\"\n    N = len(w)\n    M = X.shape[1]\n    x_win_sum = np.zeros(L)\n    w_sum = np.zeros(L)\n    for m in range(M):\n        x_win = np.fft.ifft(X[:, m])\n        # Avoid imaginary values (due to floating point arithmetic)\n        x_win = np.real(x_win)\n        x_win_sum[m * H:m * H + N] = x_win_sum[m * H:m * H + N] + x_win\n        w_shifted = np.zeros(L)\n        w_shifted[m * H:m * H + N] = w\n        w_sum = w_sum + w_shifted\n    # Avoid division by zero\n    w_sum[w_sum == 0] = np.finfo(np.float32).eps\n    x_rec = x_win_sum / w_sum\n    return x_rec, x_win_sum, w_sum\n\n\n@jit(nopython=True)\ndef stft(x, w, H=512, zero_padding=0, only_positive_frequencies=False):\n    \"\"\"Compute the discrete short-time Fourier transform (STFT)\n\n    Args:\n        x (np.ndarray): Signal to be transformed\n        w (np.ndarray): Window function\n        H (int): Hopsize (Default value = 512)\n        zero_padding (bool): Number of zeros to be padded after windowing and before the Fourier transform of a frame\n            (Note: The purpose of this step is to increase the frequency sampling.) (Default value = 0)\n        only_positive_frequencies (bool): Return only positive frequency part of spectrum (non-invertible)\n            (Default value = False)\n\n    Returns:\n        X (np.ndarray): The discrete short-time Fourier transform\n    \"\"\"\n\n    N = len(w)\n    x = np.concatenate((np.zeros(N // 2), x, np.zeros(N // 2)))\n\n    L = len(x)\n    M = int(np.floor((L - N) / H)) + 1\n\n    X = np.zeros((N + zero_padding, M), dtype=np.complex128)\n    zero_padding_vector = np.zeros((zero_padding, ), dtype=x.dtype)\n\n    for m in range(M):\n        x_win = x[m * H:m * H + N] * w\n        if zero_padding > 0:\n            x_win = np.concatenate((x_win, zero_padding_vector))\n        X_win = fft(x_win)\n        # Note: X_win = np.fft.fft(x_win) does not work in combination with @jit\n        X[:, m] = X_win\n\n    if only_positive_frequencies:\n        K = 1 + (N + zero_padding) // 2\n        X = X[0:K, :]\n    return X\n\n\n@jit(nopython=True)\ndef istft(X, w, H, L, zero_padding=0):\n    \"\"\"Compute the inverse discrete short-time Fourier transform (ISTFT)\n\n    Args:\n        X (np.ndarray): The discrete short-time Fourier transform\n        w (np.ndarray): Window function\n        H (int): Hopsize\n        L (int): Length of time signal\n        zero_padding (bool): Number of zeros to be padded after windowing and before the Fourier transform of a frame\n            (Default value = 0)\n\n    Returns:\n        x (np.ndarray): Reconstructed time signal\n    \"\"\"\n    N = len(w)\n    L = L + N\n    M = X.shape[1]\n    w_sum = np.zeros(L)\n    x_win_sum = np.zeros(L)\n    w_sum = np.zeros(L)\n    for m in range(M):\n        start_idx, end_idx = m * H, m * H + N + zero_padding\n        if start_idx > L:\n            break\n\n        x_win = ifft(X[:, m])\n        # Note: x_win = np.fft.ifft(X[:, m]) does not work in combination with @jit\n        if end_idx > L:\n            end_idx = L\n            x_win = x_win[:end_idx-start_idx]\n            cur_w = w[:end_idx-start_idx]\n        else:\n            cur_w = w\n\n        # Avoid imaginary values (due to floating point arithmetic)\n        x_win_real = np.real(x_win)\n        x_win_sum[start_idx:end_idx] = x_win_sum[start_idx:end_idx] + x_win_real\n        w_shifted = np.zeros(L)\n        w_shifted[start_idx:start_idx + len(cur_w)] = cur_w\n        w_sum = w_sum + w_shifted\n    # Avoid division by zero\n    w_sum[w_sum == 0] = np.finfo(np.float32).eps\n    x_rec = x_win_sum / w_sum\n    x_rec = x_rec[N // 2:-N // 2]\n    return x_rec\n\n\ndef stft_convention_fmp(x, Fs, N, H, pad_mode='constant', center=True, mag=False, gamma=0):\n    \"\"\"Compute the discrete short-time Fourier transform (STFT)\n\n    Notebook: C2/C2_STFT-FreqGridInterpol.ipynb\n\n    Args:\n        x (np.ndarray): Signal to be transformed\n        Fs (scalar): Sampling rate\n        N (int): Window size\n        H (int): Hopsize\n        pad_mode (str): Padding strategy is used in librosa (Default value = 'constant')\n        center (bool): Centric view as used in librosa (Default value = True)\n        mag (bool): Computes magnitude STFT if mag==True (Default value = False)\n        gamma (float): Constant for logarithmic compression (only applied when mag==True) (Default value = 0)\n\n    Returns:\n        X (np.ndarray): Discrete (magnitude) short-time Fourier transform\n    \"\"\"\n    X = librosa.stft(x, n_fft=N, hop_length=H, win_length=N,\n                     window='hann', pad_mode=pad_mode, center=center)\n    if mag:\n        X = np.abs(X)**2\n        if gamma > 0:\n            X = np.log(1 + gamma * X)\n    F_coef = librosa.fft_frequencies(sr=Fs, n_fft=N)\n    T_coef = librosa.frames_to_time(np.arange(X.shape[1]), sr=Fs, hop_length=H)\n    # T_coef = np.arange(X.shape[1]) * H/Fs\n    # F_coef = np.arange(N//2+1) * Fs/N\n    return X, T_coef, F_coef\n", "meta": {"hexsha": "485fed46c4b13f00f8388d82e6ad2cc76e551e2b", "size": 10419, "ext": "py", "lang": "Python", "max_stars_repo_path": "libfmp/c2/c2_fourier.py", "max_stars_repo_name": "arfon/libfmp", "max_stars_repo_head_hexsha": "86f39a323f948a5f104f768442359e93620b2bab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 55, "max_stars_repo_stars_event_min_datetime": "2020-12-14T08:33:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:36:41.000Z", "max_issues_repo_path": "libfmp/c2/c2_fourier.py", "max_issues_repo_name": "arfon/libfmp", "max_issues_repo_head_hexsha": "86f39a323f948a5f104f768442359e93620b2bab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-06-25T09:11:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-17T13:55:19.000Z", "max_forks_repo_path": "libfmp/c2/c2_fourier.py", "max_forks_repo_name": "arfon/libfmp", "max_forks_repo_head_hexsha": "86f39a323f948a5f104f768442359e93620b2bab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-06-30T08:34:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T15:59:17.000Z", "avg_line_length": 28.2357723577, "max_line_length": 117, "alphanum_fraction": 0.5952586621, "include": true, "reason": "import numpy,from numba", "num_tokens": 2994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832345, "lm_q2_score": 0.90192067257508, "lm_q1q2_score": 0.8604017420011015}}
{"text": "from sklearn.datasets import make_regression\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\n\n# Functions\ndef gram_schmidt(a):\n    q = []\n    for i in range(len(a)):\n        #orthogonalization\n        q_tilde = a[i]\n        for j in range(len(q)):\n            q_tilde = q_tilde - (q[j] @ a[i])*q[j]\n        #Test for dependennce\n        if np.sqrt(sum(q_tilde**2)) <= 1e-10:\n            print('Vectors are linearly dependent.')\n            print('GS algorithm terminates at iteration ', i+1)\n            return q\n        #Normalization\n        else:\n            q_tilde = q_tilde / np.sqrt(sum(q_tilde**2))\n            q.append(q_tilde)\n    print('Vectors are linearly independent.')\n    return q\n\ndef QR_factorization(A):\n    Q_transpose = np.array(gram_schmidt(A.T))\n    R = Q_transpose @ A\n    Q = Q_transpose.T\n    return Q, R\n\ndef back_subst(R,b_tilde):\n    n = R.shape[0]\n    x = np.zeros(n)\n    for i in reversed(range(n)):\n        x[i] = b_tilde[i]\n        for j in range(i+1,n):\n            x[i] = x[i] - R[i,j]*x[j]\n        x[i] = x[i]/R[i,i]\n    return x\n\ndef solve_via_backsub(A,b):\n    Q,R = QR_factorization(A)\n    b_tilde = Q.T @ b\n    x = back_subst(R,b_tilde)\n    return x\n\n#########\n\n# # Least squares problem\n# A = np.array([[2,0],[-1,1],[0,2]])\n# b = np.array([1,0,-1])\n# x_hat = np.array([1/3, -1/3])\n# r_hat = A @ x_hat - b\n# print(np.linalg.norm(r_hat))\n# x = np.array([1/2, -1/2]) #other value of x\n# r = A @ x - b\n# print(np.linalg.norm(r))\n# print(np.linalg.inv(A.T @ A) @ A.T @ b)\n# print(np.linalg.pinv(A) @ b)\n# print((A.T @ A) @ x_hat - A.T @ b) #Check that normal equations hold\n# # Principio da ortogonalidade\n# z = np.array([-1.1,2.3])\n# print(A @ z).T @ r_hat)\n# z = np.array([5.3, -1.2])\n# print((A @ z).T @ r_hat)\n\n# # Resolvendo problemas de quadrados mínimos\n# A = np.random.normal(size = (100,20))\n# b = np.random.normal(size = 100)\n# x1 = solve_via_backsub(A,b)\n# x2 = np.linalg.inv(A.T @ A) @ (A.T @ b)\n# x3 = np.linalg.pinv(A) @ b\n# print(np.linalg.norm(x1-x2))\n# print(np.linalg.norm(x2-x3))\n# print(np.linalg.norm(x3-x1))\n\n# Exemplo página 234\nn = 10 # número de lâmpadas\n# posições (x,y) das lâmpadas e altura acima do chão\nlamps = np.array([[4.1 ,20.4, 4],\n    [14.1, 21.3, 3.5],\n    [22.6, 17.1,6], \n    [5.5 ,12.3, 4.0], \n    [12.2, 9.7, 4.0], \n    [15.3, 13.8, 6],\n    [21.3, 10.5, 5.5], \n    [3.9 ,3.3, 5.0], \n    [13.1, 4.3, 5.0], \n    [20.3,4.2, 4.5]]) \n\nN = 25 # grid size\nm = N*N # Número de pixels\n# construct m x 2 matrix with coordinates of pixel centers\npixels = np.hstack([np.outer(np.arange(0.5,N,1),np.ones(N)).reshape(m,1), np.outer(np.ones(N),np.arange(0.5,N,1)).reshape(m,1)])\n# The m x n matrix A maps lamp powers to pixel intensities.\n# A[i,j] is inversely proportional to the squared distance of\n# lamp j to pixel i.\nA = np.zeros((m,n))\nfor i in range(m):\n    for j in range(n):\n        A[i,j] = 1.0 / (np.linalg.norm(np.hstack([pixels[i,:], 0]) - lamps[j,:])**2)\n\nA = (m / np.sum(A)) * A # scale elements of A\n# Least squares solution\nx = solve_via_backsub(A, np.ones(m))\nrms_ls = (sum((A @ x - 1)**2)/m)**0.5\nprint(rms_ls)\nimport matplotlib.pyplot as plt\nplt.ion()\nplt.hist(A @ x, bins = 25)\nplt.show()\nplt.pause(10)\n# Intensity if all lamp powers are one\nrms_uniform = (sum((A @ np.ones(n) - 1)**2)/m)**0.5\nprint(rms_uniform)\nplt.hist(A @ np.ones(n), bins = 25)\nplt.show()\nplt.pause(10)\n", "meta": {"hexsha": "95a7fbc65f87953eef22b53a260286b8a5ad6c3d", "size": 3415, "ext": "py", "lang": "Python", "max_stars_repo_path": "Algoritmos/AproximacaoMinimosQuadrados_CaduSantana.py", "max_stars_repo_name": "CaduSantana/hacktoberfest-2021-codigos", "max_stars_repo_head_hexsha": "c8bd520811e365fef170fb840246fbc90a3e434c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-10-30T22:07:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T21:45:27.000Z", "max_issues_repo_path": "Algoritmos/AproximacaoMinimosQuadrados_CaduSantana.py", "max_issues_repo_name": "CaduSantana/hacktoberfest-2021-codigos", "max_issues_repo_head_hexsha": "c8bd520811e365fef170fb840246fbc90a3e434c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-17T17:08:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-17T17:08:30.000Z", "max_forks_repo_path": "Algoritmos/AproximacaoMinimosQuadrados_CaduSantana.py", "max_forks_repo_name": "CaduSantana/hacktoberfest-2021-codigos", "max_forks_repo_head_hexsha": "c8bd520811e365fef170fb840246fbc90a3e434c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2021-10-16T20:32:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-19T21:15:44.000Z", "avg_line_length": 28.4583333333, "max_line_length": 128, "alphanum_fraction": 0.5841874085, "include": true, "reason": "import numpy", "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854146791214, "lm_q2_score": 0.8872045937171068, "lm_q1q2_score": 0.8603980748231659}}
{"text": "#! bin/usr/env python\n\nimport numpy as np\n\ndef make_diff_matrix(h,N):\n    \"\"\"This function takes in a value h which is the distance between 2 \n    sample points and the amount of points it would sample\n    N. It will then use these parameters to create an NxN matrix that is \n    used to creat N central difference\n    equations to get the derivative of a function.\"\"\"\n    D = np.zeros((N+1,N+1))\n    D[0][0] = -1.0/h\n    D[0][1] = 1.0/h\n    D[N][N-1] = -1.0/h\n    D[N][N] = 1.0/h\n    for i in range(1,N):\n        for j in range(1,N+1):\n            if (j==i-1):\n                D[i][j] = -1.0/(2.0*h)\n            elif (j==i+1):\n                D[i][j] = 1/(2.0*h)\n    return D\n\ndef vec_central_first_diff(f,a,b,N):\n    \"\"\"Takes a function and an array of equidistant inputs (all discrete)\n    and returns the derivative. Achieves this using a derivative matrix.\n    Takes args: function f, N sample intervals, [a,b]\"\"\"\n    x_i = np.linspace(a,b,N+1)\n    f_x = f(x_i)\n    l = vec_central_first_diff1(x_i, f_x)\n    return l\n\ndef vec_central_first_diff1(x_i, f_x):\n    \"\"\"This function takes in a list of points x_i and the function that is\n     produced by a function acting on x_i.\n    Then it takes the difference matrix defined above and applies it to the \n    function to get the derivative points of the\n    function.\"\"\"\n    N = len(x_i) - 1\n    h = x_i[1]-x_i[0]\n    D = make_diff_matrix(h,N)\n    d1 = np.dot(D,f_x)\n    return x_i, f_x, d1\n\ndef vec_central_second_diff1(x_i,f_x):\n    \"\"\"This function does almost the same thing as vec_central_first_diff1, \n    except this is to get the second derivative.\n    So the only difference here is that we multiply the difference matrix \n    to itself and then apply it to the function.\"\"\"\n    N = len(x_i) - 1\n    h = x_i[1] - x_i[0]\n    D = np.dot(make_diff_matrix(h,N), make_diff_matrix(h,N))\n    d1 = np.dot(D,f_x)\n    return x_i, f_x, d1\n\ndef vec_central_second_diff(f, a, b, N):\n    \"\"\"This is the application function for the second derivative function. \n    Takes in a mathematical function an interval\n    [a,b] and number of sample points N, and returns the second derivative.\"\"\"\n    x_i = np.linspace(a,b,N+1)\n    f_x = f(x_i)\n    l = vec_central_second_diff1(x_i, f_x)\n    return l\n\ndef vec_central_diff(f,a,b,N,order=1):\n    \"\"\"Application function for vcd. Takes in function f, interval [a,b] \n    and sample points N and the order of the derivatives\n    (default to 1).\"\"\"\n    x_i = np.linspace(a,b,N+1)\n    f_x = f(x_i)\n    l = vcd(x_i,f_x,order)\n    return l\n\n\ndef vcd(x_i,f_x,order):\n    \"\"\"Takes in list of points x_i, function points f_x and a derivative \n    order. Will iterate 'order' amount of times, multiplying the difference \n    matrix to itself every time and then applying D^(order) to the function \n    points f_x.\"\"\"\n    N = len(x_i) - 1\n    h = x_i[1] - x_i[0]\n    D = make_diff_matrix(h,N)\n    if order >= 2:\n        for i in range(1,order):\n            D = np.dot(make_diff_matrix(h,N),D)\n    d1 = np.dot(D, f_x)\n    return x_i, f_x, d1\n\ndef make_trap_matrix(h,N):\n    \"\"\"Takes in step size h and the number of partition points used for integration N.\n    Creates an NxN integration matrix which is a lower triangular matrix. With main \n    diagonal and first column equal to h/2 and the rest of the lower triangle equal to h.\n    \"\"\"\n    I = np.zeros((N+1,N+1))\n    for i in range(1,N+1):\n        for j in range(0,N+1):\n            if j==i:\n            \tI[i][j] = float(h)/2.0\n            elif j==i-1:\n                I[i][j] = float(h)/2.0\n            I[i][j] += I[i-1][j]\n    return I\n\ndef vec_trapz(f,a,b,N):\n    \"\"\"Parameters: Function, interval [a,b] and sample points N. Returns\n    integrated function\"\"\"\n    x_i = np.linspace(a,b,N+1)\n    f_x = f(x_i)\n    l = vt(x_i,f_x)\n    return l\n\ndef vt(x_i,f_x):\n    \"\"\"Takes in an array of points and a vectorized function. Creates the trapezoidal matrix and acts it onto the\n    vectorized function. Returns the input parameters and the integral\"\"\"\n    N = len(x_i) - 1\n    h = x_i[1] - x_i[0]\n    I = make_trap_matrix(h,N)\n    integral = np.dot(I,f_x)\n    return x_i, f_x, integral\n\ndef test_vectrapz():\n    \"\"\" testing the vect_trapz function with a moderately\n    high error tolerance\"\"\"\n    #On the interval from 0 to 10 the integral of x^3 = 2500\n    xCubedInt = 2500\n    a = vec_trapz(lambda x: x**3, 0,10,100)\n    l = a[2]\n    if(abs(l[100] - 2500) < 1):\n        return True\n    else:\n        return False\n", "meta": {"hexsha": "42f62f62a49117307df23c43875b12950d852b52", "size": 4446, "ext": "py", "lang": "Python", "max_stars_repo_path": "calculus.py", "max_stars_repo_name": "chapman-phys220-2016f/cw-06-saktill", "max_stars_repo_head_hexsha": "70a20ea049861329c1f6e7f56700d418c3411a66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "calculus.py", "max_issues_repo_name": "chapman-phys220-2016f/cw-06-saktill", "max_issues_repo_head_hexsha": "70a20ea049861329c1f6e7f56700d418c3411a66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calculus.py", "max_forks_repo_name": "chapman-phys220-2016f/cw-06-saktill", "max_forks_repo_head_hexsha": "70a20ea049861329c1f6e7f56700d418c3411a66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6818181818, "max_line_length": 113, "alphanum_fraction": 0.6239316239, "include": true, "reason": "import numpy", "num_tokens": 1347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854094395751, "lm_q2_score": 0.8872045907347108, "lm_q1q2_score": 0.8603980672823323}}
{"text": "\"\"\"Example implementation of the steepest descent algorithm using a hard coded obbjective function\n\n    F(X1, X2) = 5X1**2 + X2**2 + 4X1X2 - 14X1 - 6X2 + 20\n\n- At each step the value of X will be updated using\n    X_k+1 = X_k + alpha * del_F(Xk)\n\n- Initial guess of the minimiser is a point X_0 = [0, 0]\n- The value of alpha will be calculated using an exact line search\n\n    alpha = || gk || ** 2 / gk_T * A * gk\n\n    where gk is the gradient vector at point Xk and A is the hessian matrix\n\"\"\"\nimport math\nimport logging\nimport numpy as np\n\nlogging.basicConfig(level=logging.DEBUG)\nlog = logging.getLogger(__name__)\n\n\nclass GradientDescent:\n    def __init__(self, max_iterations=100, hessian_matrix=None, linear_terms=None):\n        self.Hessian: np.ndarray = hessian_matrix or np.array([[10, 4], [4, 2]])\n        self.LinearCoefficients = linear_terms or np.array([-14, -6])\n        self.Minimiser = np.array([0, 0])\n        self.CurrentIteration = 0\n        self.MaxIterations = max_iterations\n        self.Epsilon = math.pow(10, -6)  # Stop if magnitude of gradient is less than this value\n\n    @property\n    def __current_gradient_value(self):\n        gradient = self.del_f(self.Minimiser)\n        return np.sqrt(gradient.dot(gradient))\n\n    @staticmethod\n    def f(xk, decimal_places=3):\n        x1 = xk[0]\n        x2 = xk[1]\n        fn_value = 5*math.pow(x1, 2) + math.pow(x2, 2) + 4*x1*x2 - 14*x1 - 6*x2 + 20\n        return round(fn_value, decimal_places)\n\n    def del_f(self, xk: np.ndarray) -> np.ndarray:\n        gradient_vector = np.matmul(self.Hessian, xk)\n        if isinstance(self.LinearCoefficients, np.ndarray):\n            gradient_vector = np.add(gradient_vector, self.LinearCoefficients)\n        return gradient_vector\n\n    def exact_step_length(self, xk: np.ndarray, decimal_places=3) -> np.float64:\n        \"\"\"Get the step lengh by minimising f(x + ad_k) wrt to a\n\n        alpha(or lambda) = || gk || ** 2 / gk_T * A * gk\n        \"\"\"\n        gk = self.del_f(xk)\n        numerator = gk.dot(gk)\n        denominator = gk.dot(self.Hessian).dot(gk)\n        step_len = numerator/denominator\n        return round(step_len, decimal_places)\n\n    def _find_next_candidate(self):\n        \"\"\"Get next potential minimum using X_k+1 = X_k + alpha * del_F(Xk)\"\"\"\n        xk = self.Minimiser\n        dk = -1 * self.del_f(xk)\n        step_length = self.exact_step_length(xk)\n        x_k_plus1 = xk + (step_length * dk)\n        log.debug(f\"X**{self.CurrentIteration} = {xk} - {step_length} * {dk}\")\n        return x_k_plus1\n\n    def execute(self):\n        log.info('Gradient descent iteration started')\n        # self.__preview_config()\n        for k in range(self.MaxIterations):\n            log.debug(f\"-----------Iteration {k}--------------\")\n            self.CurrentIteration = k\n            self.Minimiser = self._find_next_candidate()\n            log.debug(f\"------Minimiser = {self.Minimiser}. Gradient = {self.__current_gradient_value}--------\\n\")\n            if self.__current_gradient_value <= self.Epsilon:\n                log.warning(f\"Iteration stopped at k={k}. Stopping condition reached!\")\n                break\n        log.info(f\"------Minimiser = {self.Minimiser}. Gradient = {self.__current_gradient_value}--------\")\n        log.info('Gradient descent completed successfully')\n        return self.Minimiser, self.f(self.Minimiser), round(self.__current_gradient_value, 3)\n", "meta": {"hexsha": "6d4854831a18ff129614b9dc69726228b6fe5cf1", "size": 3396, "ext": "py", "lang": "Python", "max_stars_repo_path": "gradientdescent.py", "max_stars_repo_name": "endeesa/optimization-algorithms", "max_stars_repo_head_hexsha": "bb2f18101e27bc28167c456ef842aef6a22b3fbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gradientdescent.py", "max_issues_repo_name": "endeesa/optimization-algorithms", "max_issues_repo_head_hexsha": "bb2f18101e27bc28167c456ef842aef6a22b3fbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gradientdescent.py", "max_forks_repo_name": "endeesa/optimization-algorithms", "max_forks_repo_head_hexsha": "bb2f18101e27bc28167c456ef842aef6a22b3fbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4285714286, "max_line_length": 114, "alphanum_fraction": 0.6325088339, "include": true, "reason": "import numpy", "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759489, "lm_q2_score": 0.9059898197488448, "lm_q1q2_score": 0.8603907828656917}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport cvxpy as cp\n\n\nS = np.loadtxt(\"S.txt\")\npMean = np.loadtxt(\"pbar.txt\")\nn = pMean.shape[0]\n\n#%%\n# What is the risk of the uniform portfolio?\n\nxU = np.ones(n)/n\nriskU = xU.T @ S @ xU\n\nprint(f\"uniform portfolio risk: {riskU**0.5}\")\n\n#%%\n# What is the risk of an optimal portfolio with no (additional) constraints?\nprint(\"min risk with expected return equals uniform portfolio\")\n\nx = cp.Variable(n)\nconstraints = \\\n[ \n    cp.sum(x) == 1, \n    pMean.T @ x == pMean.T @ xU \n]\n\nprob = cp.Problem(cp.Minimize(cp.quad_form(x, S)), constraints)\nprob.solve()\nassert prob.status == cp.OPTIMAL\nprint(f\"optimal risk {prob.value**0.5}\")\n\n#%%\n# What is the risk of a long-only portfolio 𝑥⪰0?\nprint(\"x >= 0\")\nprob = cp.Problem(cp.Minimize(cp.quad_form(x, S)), constraints + [x >= 0])\nprob.solve()\nassert prob.status == cp.OPTIMAL\nprint(f\"optimal risk {prob.value**0.5}\")\n\n#%%\n# What is the risk of a portfolio with a limit on total short position:  1𝑇(𝑥−)≤0.5 , where  (𝑥−)𝑖=max{−𝑥𝑖,0} ?\nprint(\"limit on short\")\nprob = cp.Problem(cp.Minimize(cp.quad_form(x, S)), constraints + [cp.sum(cp.neg(x)) <= 0.5])\nprob.solve()\nassert prob.status == cp.OPTIMAL\nprint(f\"optimal risk {prob.value**0.5}\")\n", "meta": {"hexsha": "7642438a8180f4fbb337e536a2f3a7092b5fbc73", "size": 1231, "ext": "py", "lang": "Python", "max_stars_repo_path": "Convex Optimization Problems/Simple Portfolio Optimization/solve.py", "max_stars_repo_name": "lpierezan/cvx_course", "max_stars_repo_head_hexsha": "5179a72d168c6e7c49e4fb5667b7b8f69393f3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-09T09:22:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T09:22:04.000Z", "max_issues_repo_path": "Convex Optimization Problems/Simple Portfolio Optimization/solve.py", "max_issues_repo_name": "lpierezan/cvx_course", "max_issues_repo_head_hexsha": "5179a72d168c6e7c49e4fb5667b7b8f69393f3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Convex Optimization Problems/Simple Portfolio Optimization/solve.py", "max_forks_repo_name": "lpierezan/cvx_course", "max_forks_repo_head_hexsha": "5179a72d168c6e7c49e4fb5667b7b8f69393f3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1224489796, "max_line_length": 111, "alphanum_fraction": 0.6685621446, "include": true, "reason": "import numpy,import cvxpy", "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104953173167, "lm_q2_score": 0.8902942304882371, "lm_q1q2_score": 0.8603896882642865}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 23 19:07:15 2019\n\n@author: marcus.bonifacio\n\"\"\"\n\nimport numpy as np\n\n\n\nprint('1) Faça um script para estimar o valor de π utilizando o método de Monte Carlo.')\n\nN = 10000000 #define quantidade de pontos\nx = np.random.rand(N) #gera números aleatórios de 0 a 1 \ny = np.random.rand(N)\ndeltax = (0.5-x)**2 #calcula a diferença das coordenadas do ponto para o centro do círculo\ndeltay = (0.5-y)**2\nd = np.sqrt(deltax + deltay) #calcula a distancia do ponto para o centro do círculo\n\ncirc = d[d <= 0.5] #seleciona os pontos dentro do círculo\n\nrazao = len(circ)/N #razão dos pontos dentro do círculo e todos os pontos\npi = 4*razao #aproxima pi\nprint('Valor aproximado de PI pelo método Monte Carlo =',pi)\n", "meta": {"hexsha": "1514630dc011d573e281eb058838ad3a944d2b26", "size": 745, "ext": "py", "lang": "Python", "max_stars_repo_path": "monte_carlo_method.py", "max_stars_repo_name": "MarcusLucinda/UFABC---Q1BCC", "max_stars_repo_head_hexsha": "4fcaf5f50ba6212c6c0d69e0b2e20658c100dd76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-17T17:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-17T17:40:09.000Z", "max_issues_repo_path": "monte_carlo_method.py", "max_issues_repo_name": "marcusbonifacio/UFABC---Q1BCC", "max_issues_repo_head_hexsha": "4fcaf5f50ba6212c6c0d69e0b2e20658c100dd76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "monte_carlo_method.py", "max_forks_repo_name": "marcusbonifacio/UFABC---Q1BCC", "max_forks_repo_head_hexsha": "4fcaf5f50ba6212c6c0d69e0b2e20658c100dd76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6538461538, "max_line_length": 90, "alphanum_fraction": 0.7087248322, "include": true, "reason": "import numpy", "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9664104962847373, "lm_q2_score": 0.8902942224835226, "lm_q1q2_score": 0.8603896813897355}}
{"text": "import cvxpy as cp\nimport numpy as np\nfrom numpy.linalg import pinv, inv, norm\nfrom scipy.linalg import eig\n\ndef alternative_minimization(X, alpha, beta, num_iters, dual=False):\n    \n    n = X.shape[0]\n    \n    \"\"\"\n    helper functions\n    \"\"\"\n    \n    def dual_helper(Y):\n        m = n * (n + 1) // 2\n\n        # position matrix\n        Q = np.zeros((n, n))\n        count = 0\n        for d in np.arange(0, n):\n            for i in np.arange(d, n):\n                j = i - d\n                Q[i, j] = count\n                count += 1\n        for d in np.arange(1, n):\n            for i in np.arange(0, n - d):\n                j = i + d\n                Q[i, j] = count\n                count += 1\n\n        # C = vec(Y @ Y.T)\n        YYt = Y @ Y.T\n        C = np.zeros(((n**2), 1))\n        for i in np.arange(0, n):\n            for j in np.arange(0, n):\n                loc = int(Q[i, j])\n                C[loc] = YYt[i, j] \n\n        # Duplication matrix M\n        nsqr = n ** 2\n        M1 = np.eye(m)\n        M2 = np.hstack((np.zeros((nsqr - m, n)), np.eye(m - n)))\n        M = np.vstack((M1, M2))\n\n        # Equality constraints matrix A\n        A1 = np.hstack((np.ones((1, n)), np.zeros((1, m - n))))\n        A2 = np.hstack((np.eye(n), np.zeros((n, m - n))))\n        for i in np.arange(0, n):\n            row = i\n            for j in np.arange(0, i):\n                col = int(Q[i, j])\n                A2[row, col] = 1\n            for j in np.arange(i + 1, n):\n                col = int(Q[j, i])\n                A2[row, col] = 1\n        A = np.vstack((A1, A2))\n\n        # vector b\n        b = np.vstack((n * np.ones((1, 1)), np.zeros((n, 1))))\n\n        # Inequality constraints matrix G\n        G = np.hstack((np.zeros((m - n, n)), np.eye(m - n)))\n\n        # vector h\n        h = np.zeros((m - n, 1))\n\n        P = 2 * beta * M.T @ M\n        q = (alpha * M.T @ C).squeeze()\n\n        return Q, P, q, G, h, A, b\n\n    def make_L(x, Q):\n        L = np.zeros((n, n))\n        for i in np.arange(0, n):\n            for j in np.arange(0, i + 1):\n                loc = int(Q[i, j])\n                L[i, j] = x[loc]\n\n        L = L + L.T - np.diag(np.diag(L))\n        return L\n    \n    \"\"\"\n    QP optimizations for L and Y\n    \"\"\"\n    \n    def optimize_L_primal(Y):\n        L = cp.Variable((n,n), symmetric=True)\n\n        obj = cp.Minimize(alpha * cp.trace(Y.T @ L @ Y) + beta * (cp.norm(L, p='fro')**2))\n\n        constraints = [cp.trace(L) == n]\n        constraints += [L >> 0]\n        constraints += [L @ np.ones((n)) == np.zeros((n))]\n        for i in range(n):\n            for j in range(i+1,n):\n                constraints += [L[i,j] <= 0]\n\n        prob = cp.Problem(obj, constraints)\n\n        p_star = prob.solve()\n        print(f\"primal value is {p_star}\")\n        L_opt = L.value\n        return L_opt\n\n    def optimize_L_dual(Y):\n        Q, P, q, G, h, A, b = dual_helper(Y)\n\n        lam = cp.Variable((G.shape[0]))\n        nu = cp.Variable((A.shape[0]))\n\n        Pinv = pinv(P)\n        r = q + G.T @ lam + A.T @ nu\n\n        obj_dual = cp.Maximize((-0.5) * cp.quad_form(r, Pinv) - h.T @ lam - b.T @ nu)\n\n        constraints_dual = [lam >= 0]\n\n        prob_dual = cp.Problem(obj_dual, constraints_dual)\n\n        p_dual_star = prob_dual.solve()\n        print(f\"dual value is {p_dual_star}\")\n        lam_opt, nu_opt = lam.value, nu.value\n\n        x = - Pinv @ (r.value)\n        L_opt = make_L(x, Q)\n        return L_opt\n\n    def optimize_Y(L):\n        Y_opt = inv(np.eye(n) + alpha * L) @ X\n\n        return Y_opt\n    \n    \"\"\"\n    alternate minimization algorithm\n    \"\"\"\n    \n    Y_iter = X\n    obj_old_val = np.inf\n    for idx_iter in np.arange(num_iters):\n        \n        print(f\"iteration #{idx_iter}\")\n        \n        if dual is True:\n            L_iter = optimize_L_dual(Y_iter)\n        else:\n            L_iter = optimize_L_primal(Y_iter)\n        \n        Y_iter = optimize_Y(L_iter)\n        \n        obj_val = norm(X - Y_iter, 'fro')**2 + alpha * np.trace(Y_iter.T @ L_iter @ Y_iter) + beta * (norm(L_iter, 'fro')**2);\n\n        print(f\"iteration-{idx_iter}: obj value = {obj_val}\")\n\n        if np.abs(obj_old_val - obj_val) < 1e-4:\n            break\n        else:\n            obj_old_val = obj_val\n\n    return L_iter, Y_iter\n", "meta": {"hexsha": "4850d7a269da5592ba3d83c6c56edf944596c722", "size": 4226, "ext": "py", "lang": "Python", "max_stars_repo_path": "alternative_minimization.py", "max_stars_repo_name": "Eashwar-S/Convex-Optimization", "max_stars_repo_head_hexsha": "4549e4b3fa8f2d594c8b61cff8b703c2fc54237a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "alternative_minimization.py", "max_issues_repo_name": "Eashwar-S/Convex-Optimization", "max_issues_repo_head_hexsha": "4549e4b3fa8f2d594c8b61cff8b703c2fc54237a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "alternative_minimization.py", "max_forks_repo_name": "Eashwar-S/Convex-Optimization", "max_forks_repo_head_hexsha": "4549e4b3fa8f2d594c8b61cff8b703c2fc54237a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4125, "max_line_length": 126, "alphanum_fraction": 0.4578797918, "include": true, "reason": "import numpy,from numpy,from scipy,import cvxpy", "num_tokens": 1247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104962847373, "lm_q2_score": 0.8902942144788077, "lm_q1q2_score": 0.860389673653895}}
{"text": "import numpy as np\r\nfrom numpy import linalg as LA\r\nfrom numpy import diag\r\nfrom numpy import zeros\r\nA=np.array([[-5,-5,-1,0,0,0,500,500,100],[0,0,0,-5,-5,-1,500,500,100],\r\n           [-150,-5,-1,0,0,0,30000,1000,200],[0,0,0,-150,-5,-1,12000,400,80],\r\n           [-150,-150,-1,0,0,0,33000,33000,220],[0,0,0,-150,-150,-1,12000,12000,80],\r\n           [-5,-150,-1,0,0,0,500,15000,100],[0,0,0,-5,-150,-1,1000,30000,200]])\r\nprint(\"The A matrix:\\n{}\".format(A))\r\nA_T=A.transpose()\r\nprint(\"The transpose of the A matrix is: \\n{}\".format(A_T))\r\nA1=A.dot(A_T)\r\nA2=A_T.dot(A)\r\n#To find the eigen vectors and eigenvalues of the A^T*A and A*A^T.\r\nw1, v1 = LA.eig(A1)\r\nw2, v2 = LA.eig(A2)\r\n#Taking the absolute values of the eigen values to keep them postive\r\nw= abs(w2)\r\nprint(\"The adjusted eigen values : \\n{}\".format(w))\r\nU=v1\r\nprint(\"The Eigen Vector U is: \\n{}\".format(U))\r\n#transpose of the V eigen vector matrix\r\nV_T=v2.transpose()\r\nprint(\"Eigen vectors 2\\n{}\".format(v2))\r\nprint(\"The transpose of Eigen Vector V is: \\n{}\".format(V_T))\r\n#Sigma Matrix matrix can be formed using the square root of eigenvalues of A^T*A\r\n#Sigma matrix is a diagonal matrix with the squareroot of the eigen values\r\nsig=np.sqrt(w)\r\nprint(\"The eigenvectors considered for the Sigma matrix are: \\n{}\".format(sig))\r\n#To form the Sigma diagonal matrix\r\nSigma = zeros((A.shape[0], A.shape[1]))\r\nprint(Sigma)\r\nfor i in range(len(Sigma)):\r\n    Sigma[i][i]= sig[i]\r\nprint(\"The Sigma Matrix(Diagonal Matrix) is : \\n{}\".format(Sigma))\r\n#SVD of A= U*Sigma*V'\r\nSVD=U.dot(Sigma.dot(V_T))\r\nprint(\"The SVD of Matrix A is:\")\r\nprint(SVD)\r\n#To find the Homography matrix\r\nH=v2[:,-1]\r\nH1=np.reshape(H,(3,3))\r\nprint(\"The Homography matrix H is:\")\r\nprint(H1)\r\n", "meta": {"hexsha": "442617a6242889cf282335b1070744c0f5c0c4a3", "size": 1712, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/Homework1_Q3.py", "max_stars_repo_name": "namangupta98/ENPM673_HW1", "max_stars_repo_head_hexsha": "c6a6304221d8601e82bfdc33d492db5477f519d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/Homework1_Q3.py", "max_issues_repo_name": "namangupta98/ENPM673_HW1", "max_issues_repo_head_hexsha": "c6a6304221d8601e82bfdc33d492db5477f519d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Homework1_Q3.py", "max_forks_repo_name": "namangupta98/ENPM673_HW1", "max_forks_repo_head_hexsha": "c6a6304221d8601e82bfdc33d492db5477f519d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0444444444, "max_line_length": 85, "alphanum_fraction": 0.6559579439, "include": true, "reason": "import numpy,from numpy", "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104904802131, "lm_q2_score": 0.8902942159342104, "lm_q1q2_score": 0.8603896698926771}}
{"text": "# using higher order derivatives to find extrema values\n\nfrom sympy import Symbol, solve, Derivative\n\nx = Symbol( 'x' )\nf = x**5 - 30*x**3 + 50*x\n\nd1 = Derivative( f, x ).doit()\n\ncritical_points = solve( d1 )\n\ncritical_points\n\nA = critical_points[ 2 ]\nB = critical_points[ 0 ]\nC = critical_points[ 1 ]\nD = critical_points[ 3 ]\n\nd2 = Derivative( f, x, 2 ).doit()\n\nd2.subs( { x: B } ).evalf()\nd2.subs( { x: C } ).evalf()\nd2.subs( { x: A } ).evalf()\nd2.subs( { x: D } ).evalf()\n\nx_min = -5\nx_max = 5\n\nf.subs( { x: C } ).evalf()\nf.subs( { x: A } ).evalf()\n\nf.subs( { x: x_min } ).evalf()\nf.subs( { x: x_max } ).evalf()\n\n", "meta": {"hexsha": "cc03014fa92c6e81f56440623627d91897a85091", "size": 616, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/DoingMathInPython/ch_07/extrema_derivative.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DoingMathInPython/ch_07/extrema_derivative.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DoingMathInPython/ch_07/extrema_derivative.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.6, "max_line_length": 55, "alphanum_fraction": 0.5876623377, "include": true, "reason": "from sympy", "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407137099625, "lm_q2_score": 0.8840392863287585, "lm_q1q2_score": 0.8603830259742468}}
{"text": "# define: Sigmoid function version 1\n# date: 2021.12.23.\n# Resource: 밑바닥부터 시작하는 인공지능(사이토고키, 2017)\n\ndef sigmoid(x):\n\treturn 1 / (1+ np.exp(-x)) # exp is function to caculate the exponential of all elements in the input array. \n\nif __name__ == '__main__':\n\timport numpy as np\n\timport matplotlib.pylab as plt\n\t\n\tx = np.arange(-5.0, 5.0, 0.1)\n\ty = sigmoid(x)\n\n\tplt.plot(x, y)\n\tplt.ylim(-0.1, 1.1)\n\tplt.show()\n\n", "meta": {"hexsha": "90640e34fa6cd5eff4562f6e40c5c35a988c6280", "size": 406, "ext": "py", "lang": "Python", "max_stars_repo_path": "Reference/Sigmoid_function_1.py", "max_stars_repo_name": "iSeonHwan/Generating_Dictionary_Programe", "max_stars_repo_head_hexsha": "10d973de56483c64bf0dcde9052f5af74bff88dd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Reference/Sigmoid_function_1.py", "max_issues_repo_name": "iSeonHwan/Generating_Dictionary_Programe", "max_issues_repo_head_hexsha": "10d973de56483c64bf0dcde9052f5af74bff88dd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Reference/Sigmoid_function_1.py", "max_forks_repo_name": "iSeonHwan/Generating_Dictionary_Programe", "max_forks_repo_head_hexsha": "10d973de56483c64bf0dcde9052f5af74bff88dd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3684210526, "max_line_length": 110, "alphanum_fraction": 0.6674876847, "include": true, "reason": "import numpy", "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862454, "lm_q2_score": 0.8947894710123925, "lm_q1q2_score": 0.8603703293770807}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef numeric_better(x, h):\n    return (np.cos(x + h) - np.cos(x - h)) / (2 * h)\n\n\ndef numeric_worse(x, h):\n    return (np.cos(x + h) - np.cos(x)) / h\n\n\n# line 1 points\nx = 1\ndistances = [10 ** (-i) for i in range(1, 16)]\nreal_y = -np.sin(x)\nnumeric_better_y = [abs(numeric_better(x, distance) - real_y) for distance in distances]\nnumeric_worse_y = [abs(numeric_worse(x, distance) - real_y) for distance in distances]\n\nplt.plot(distances, numeric_worse_y, label=\"real derivative\")\nplt.plot(distances, numeric_better_y, label=\"numeric derivative\")\n\n# plt.loglog(x, real_y, label=\"real derivative\")\n\n# # plotting the line 1 points\n# line 2 points\n# plotting the line 2 points\nplt.xlabel(\"h\")\n# Set the y axis label of the current axis.\nplt.ylabel(\"f`(x)\")\n# Set a title of the current axes.\nplt.title(\"Two or more lines on same plot with suitable legends \")\n# show a legend on the plot\nplt.legend()\n# Display a figure.\nplt.show()\n", "meta": {"hexsha": "9c058af124a61693e2b6971a1b289503453c2755", "size": 979, "ext": "py", "lang": "Python", "max_stars_repo_path": "derivative_calculator.py", "max_stars_repo_name": "shimonuri/numeric-exercise", "max_stars_repo_head_hexsha": "83ab8b03c880f50bd71e4c85b69a778d343a3010", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "derivative_calculator.py", "max_issues_repo_name": "shimonuri/numeric-exercise", "max_issues_repo_head_hexsha": "83ab8b03c880f50bd71e4c85b69a778d343a3010", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "derivative_calculator.py", "max_forks_repo_name": "shimonuri/numeric-exercise", "max_forks_repo_head_hexsha": "83ab8b03c880f50bd71e4c85b69a778d343a3010", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4594594595, "max_line_length": 88, "alphanum_fraction": 0.6976506639, "include": true, "reason": "import numpy", "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338079816758, "lm_q2_score": 0.8947894682067639, "lm_q1q2_score": 0.8603703247067482}}
{"text": "# Summary Statistics and More:\n# mean, median, stdevs, min, max, quantiles, sum, product, etc.\n\n# Summing Values in NumPy Arrays\nimport numpy as np\nL = np.random.random(100)\nbig_array = np.random.rand(1000000)\n\nsum(L)                  # Python   sum. 1D  arrs only\nnp.sum(L)               # NP ufunc sum. 2D+ arrs\nsum(L) == np.sum(L)\n\nnp.sum(big_array)\nbig_array.sum()\n# Generally, we prefer calling from object instance syntax.\n\n# Minimum and Maximum\nbig_array.min(), big_array.max()\n\n# Multi-Dimensional Aggregates\n# For 2D arrays, we often want aggregates organized along rows or columns.\n# We can toggle 'axis' argument of methods to perform this.\nA = np.random.random((3, 4))\nA\nA.sum()\n\n# NOTE: Axis controls dimension to collapse, and returns the complement.\nA.min(axis=0)   # collapse row --> return min of cols\nA.max(axis=1)   # collapse col --> return max of rows\n\n# Most NumPy agg funcs have a NaN-safe equivalents (ignore NaN values).\nA.sum; np.nansum(A)\n\n\n# Partial List of Aggregation Functions:\nnp.sum\nnp.prod\nnp.mean\nnp.std\nnp.var          # compute variance (max-min)\nnp.min\nnp.max \nnp.argmin       # return index of min value\nnp.argmax       # return index of max value\nnp.median\nnp.percentile\nnp.any          # evaluate whether any elements are true\nnp.all          # evaluate whether all elements are true\n\n\n# Example: Get Average Height of US Presidents\n# !head -4 data/president_heights.csv\nimport pandas as pd\ndata = pd.read_csv('data/president_heights.csv')\nheights = np.array(data['height(cm)'])\n\nheights.mean()\nheights.std()\nheights.min()\nheights.max()\n\nnp.percentile(heights, 25)\nnp.median(heights)\nnp.percentile(heights, 75)\n\n## we can also visualize with Matplotlib\n# %matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn; seaborn.set()\nplt.hist(heights)\nplt.title('Height Distribution of US Presidents')\nplt.xlabel('height (cm)')\nplt.ylabel('number')", "meta": {"hexsha": "8aa73bc5ca8ba3aefa53d193971b9ba366b88b43", "size": 1891, "ext": "py", "lang": "Python", "max_stars_repo_path": "2.4-aggregations.py", "max_stars_repo_name": "pgiardiniere/notes-PythonDataScienceHandbook", "max_stars_repo_head_hexsha": "ddb6662d2fbeedd5b6b09ce4d8ddee55813ec589", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-05-01T02:23:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-04T03:26:39.000Z", "max_issues_repo_path": "2.4-aggregations.py", "max_issues_repo_name": "pgiardiniere/notes-PythonDataScienceHandbook", "max_issues_repo_head_hexsha": "ddb6662d2fbeedd5b6b09ce4d8ddee55813ec589", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2.4-aggregations.py", "max_forks_repo_name": "pgiardiniere/notes-PythonDataScienceHandbook", "max_forks_repo_head_hexsha": "ddb6662d2fbeedd5b6b09ce4d8ddee55813ec589", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.904109589, "max_line_length": 74, "alphanum_fraction": 0.7117927023, "include": true, "reason": "import numpy", "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338057771058, "lm_q2_score": 0.894789454880027, "lm_q1q2_score": 0.8603703099200143}}
{"text": "import numpy as np\n\n### Functions for you to fill in ###\n\n\n\ndef polynomial_kernel(X, Y, c, p):\n    \"\"\"\n        Compute the polynomial kernel between two matrices X and Y::\n            K(x, y) = (<x, y> + c)^p\n        for each pair of rows x in X and y in Y.\n\n        Args:\n            X - (n, d) NumPy array (n datapoints each with d features)\n            Y - (m, d) NumPy array (m datapoints each with d features)\n            c - a coefficient to trade off high-order and low-order terms (scalar)\n            p - the degree of the polynomial kernel\n\n        Returns:\n            kernel_matrix - (n, m) Numpy array containing the kernel matrix\n    \"\"\"\n    return np.power((X @ Y.T + c), p)\n\n\n\ndef rbf_kernel(X, Y, gamma):\n    \"\"\"\n        Compute the Gaussian RBF kernel between two matrices X and Y::\n            K(x, y) = exp(-gamma ||x-y||^2)\n        for each pair of rows x in X and y in Y.\n\n        Args:\n            X - (n, d) NumPy array (n datapoints each with d features)\n            Y - (m, d) NumPy array (m datapoints each with d features)\n            gamma - the gamma parameter of gaussian function (scalar)\n\n        Returns:\n            kernel_matrix - (n, m) Numpy array containing the kernel matrix\n    \"\"\"\n    n = X.shape[0]\n    m = Y.shape[0]\n    K = np.zeros((n,m))\n    for i in range(n):\n        for j in range(m):\n            K[i,j] = np.exp(-gamma * (np.linalg.norm(X[i] - Y[j]) ** 2))\n    return K\n    # np.vectorize\n    # n = X.shape[0]\n    # m = Y.shape[0]\n    # a = np.mat((X@X.T).diagonal())\n    # a = np.tile(a.T, (1,m))\n\n    # b = np.mat((Y@Y.T).diagonal())\n    # b = np.tile(b, (n,1))\n\n    # k = a + b\n    # k -= 2*(X @ np.transpose(Y))\n\n    # return np.exp(-gamma * k)\n", "meta": {"hexsha": "bde4cdfc52bd463bc94c2f2e1b1e74c02a48c5a6", "size": 1700, "ext": "py", "lang": "Python", "max_stars_repo_path": "courses/MITx/MITx 6.86x Machine Learning with Python-From Linear Models to Deep Learning/project2/mnist/part1/kernel.py", "max_stars_repo_name": "xunilrj/sandbox", "max_stars_repo_head_hexsha": "f92c12f83433cac01a885585e41c02bb5826a01f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-04-01T17:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:23:23.000Z", "max_issues_repo_path": "courses/MITx/MITx 6.86x Machine Learning with Python-From Linear Models to Deep Learning/project2/mnist/part1/kernel.py", "max_issues_repo_name": "xunilrj/sandbox", "max_issues_repo_head_hexsha": "f92c12f83433cac01a885585e41c02bb5826a01f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_forks_repo_path": "courses/MITx/MITx 6.86x Machine Learning with Python-From Linear Models to Deep Learning/project2/mnist/part1/kernel.py", "max_forks_repo_name": "xunilrj/sandbox", "max_forks_repo_head_hexsha": "f92c12f83433cac01a885585e41c02bb5826a01f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-09-20T01:07:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-22T14:55:38.000Z", "avg_line_length": 28.3333333333, "max_line_length": 82, "alphanum_fraction": 0.5276470588, "include": true, "reason": "import numpy", "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069627, "lm_q2_score": 0.9111797124237604, "lm_q1q2_score": 0.8603148016006728}}
{"text": "import scipy.io\r\nimport os\r\nimport numpy as np\r\nimport numpy.matlib\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom toolbox.pcaPmtk import *\r\n\r\ndata_path = os.path.join(\"..\", \"bigData\", \"olivettiFaces\", \"olivettiFaces.mat\")\r\nmat = scipy.io.loadmat(data_path)\r\n\r\nX = mat['faces'].T\r\ny = np.matlib.repmat(np.arange(1, 41), 10, 1).flatten(order='F')\r\n\r\nn, d = X.shape\r\nh, w = 64, 64\r\nname = 'faces'\r\n\r\nperm = np.random.permutation(n)\r\n\r\nf, ax_arr = plt.subplots(2, 2)\r\nfor i in range(2):\r\n    for j in range(2):\r\n        ax_arr[i, j].imshow(X[perm[i*2+j], :].reshape(h, w).T, cmap=\"gray\")\r\n        ax_arr[i, j].axis('off')\r\nf.suptitle(\"pcaImages-%s-images\" % name)\r\nplt.show()\r\n\r\nXC = X - np.mean(X, axis=0)\r\nprint('Performing PCA.... stay tuned')\r\n\r\nV, Z, evals, _, mu = pcaPmtk(X)\r\n\r\nf, ax_arr = plt.subplots(2, 2)\r\nfor i in range(2):\r\n    for j in range(2):\r\n        if i == 0 and j == 0:\r\n            ax_arr[i, j].imshow(mu.reshape(h, w).T, cmap=\"gray\")\r\n            ax_arr[i, j].axis('off')\r\n            ax_arr[i, j].set_title('mean')\r\n        else:\r\n            idx = i*2+j-1\r\n            ax_arr[i, j].imshow(V[:, idx].reshape(h, w).T, cmap=\"gray\")\r\n            ax_arr[i, j].axis('off')\r\n            ax_arr[i, j].set_title('principal basis %d' % idx)\r\nf.suptitle(\"pcaImages-%s-basis\" % name)\r\nplt.show()\r\n\r\n# Plot reconstructed image\r\nndx = 125\r\nKs = [5, 10, 20, np.linalg.matrix_rank(XC)]\r\n\r\nf, ax_arr = plt.subplots(2, 2)\r\nfor ki in range(len(Ks)):\r\n    k = Ks[ki]\r\n    Xrecon = np.dot(Z[ndx, 0:k], V[:, 0:k].T) + mu\r\n    i = ki//2\r\n    j = ki%2\r\n    ax_arr[i, j].imshow(Xrecon.reshape(h, w).T, cmap=\"gray\")\r\n    ax_arr[i, j].axis('off')\r\n    ax_arr[i, j].set_title('Using %d bases' % k)\r\nf.suptitle(\"pcaImages-%s-reconImages\" % name)\r\nplt.show()\r\n\r\nKs = []\r\nKs += range(1, 10)\r\nKs += range(10, 50, 5)\r\nKs += range(50, np.linalg.matrix_rank(XC), 25)\r\nmse = []\r\n\r\nfor ki in range(len(Ks)):\r\n    k = Ks[ki]\r\n    Xrecon = np.dot(Z[:, 0:k], V[:, 0:k].T) + mu\r\n    err = Xrecon - X\r\n    mse.append(np.sqrt(np.mean(np.power(err, 2))))\r\nplt.plot(Ks, mse, '-o')\r\nplt.ylabel(\"mse\")\r\nplt.xlabel(\"K\")\r\nplt.title('reconstruction error')\r\nplt.show()\r\n\r\nplt.plot(np.cumsum(evals)/np.sum(evals), 'ko-')\r\nplt.show()\r\n", "meta": {"hexsha": "13c49a4ebaf4fee30490426360277eb3bab568a0", "size": 2199, "ext": "py", "lang": "Python", "max_stars_repo_path": "practice/demos/pcaImageDemo.py", "max_stars_repo_name": "colinzuo/MLAPP_Solution", "max_stars_repo_head_hexsha": "6d4bab23455169310547462fe2fc2cb71a915ef0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-07-22T18:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T18:07:49.000Z", "max_issues_repo_path": "practice/demos/pcaImageDemo.py", "max_issues_repo_name": "colinzuo/MLAPP_Solution", "max_issues_repo_head_hexsha": "6d4bab23455169310547462fe2fc2cb71a915ef0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practice/demos/pcaImageDemo.py", "max_forks_repo_name": "colinzuo/MLAPP_Solution", "max_forks_repo_head_hexsha": "6d4bab23455169310547462fe2fc2cb71a915ef0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1785714286, "max_line_length": 80, "alphanum_fraction": 0.562528422, "include": true, "reason": "import numpy,import scipy", "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768525822309, "lm_q2_score": 0.9111797063939127, "lm_q1q2_score": 0.8603147873198057}}
{"text": "\"\"\"Estimate pi using a parallel Monte Carlo simulation.\r\n\r\n   Implements an MPI version of a parallel Monte Carlo simulation for estimating pi.\r\n   MPI's default channel is used.\r\n\r\n   Usage:\r\n        python monte_carlo_pi.py [total_num_trials]\r\n        \r\n        Options:\r\n               -total_num_trials    the total number of trials ( (x,y) points) for the simulation.\r\n                                    By default it is set to 1 million since a (probabilistic) precision of 3 decimal digits\r\n                                    requires 10^(2*3) trials (1 million trials).\r\n                                    see https://stackoverflow.com/questions/18139934/can-a-monte-carlo-pi-calculation-be-used-for-a-world-record\r\n\r\n\"\"\"\r\n\r\nfrom mpi4py import MPI\r\nimport numpy as np\r\nfrom sys import argv\r\n\r\ndef random_points_generator(trials_per_node=0):\r\n    \"\"\"Evaluate if a pair (x,y) drawn from an uniform distribution falls inside the unit circle.\r\n\r\n    Given a random distribution between 0 and 1, it evaluates if a pair (x,y) of random points\r\n    falls inside the unit circle. If that's the case, a counter is incremented.\r\n\r\n    Args:\r\n        trials_per_node (int): the number of trials/drawns for this node/process.\r\n\r\n    Returns:\r\n        int: a counter who keeps track of the overall number of points fallen inside the circle.\r\n    \r\n    \"\"\"\r\n    points_fallen_inside_circle = 0\r\n    # draw a pair (x,y) from an uniform distribution\r\n    # between 0 and 1 for each trial\r\n    # NOTE: each child process has its own seed\r\n    # since np.random.seed() hasn't been invoked\r\n    # This is good for randomness but terrible for\r\n    # reproducibility (which we don't consider in this project)\r\n    for _ in range(trials_per_node):\r\n        x = np.random.uniform(0,1)\r\n        y = np.random.uniform(0,1)\r\n        # if (x,y) falls inside the unit circle\r\n        # increment the counter by 1\r\n        if (x*x+y*y) <= 1.0:\r\n            points_fallen_inside_circle += 1\r\n\r\n    return points_fallen_inside_circle\r\n\r\nif __name__ == \"__main__\":\r\n    # Check if the number of trials has been supplied via\r\n    # the CLI. If not, use 1 million as default value.\r\n    total_num_trials = int(argv[1]) if len(argv) > 1 else 1e6\r\n    # MPI_Init() is automatically invoked\r\n    # when MPI module is imported\r\n    # Rename default channel for convenience\r\n    comm = MPI.COMM_WORLD\r\n    # Get the number of nodes on comm channel\r\n    num_nodes = comm.Get_size()\r\n    # Get their rank\r\n    rank = comm.Get_rank()\r\n    # Print a start checkpoint if I am the master node\r\n    if rank == 0:\r\n        print(\"Start\", flush=True)\r\n    # Compute number of trials per node\r\n    trials_per_node = np.ceil(total_num_trials / num_nodes).astype(int)\r\n    # Sync all nodes here to start a 'more accurate' time measurement\r\n    comm.Barrier()\r\n    # Init send (i.e. elapsed_buff) and receive (i.e. longest_elapsed_buff) buffer for MAX reduction\r\n    # as a one dimensional zero-filled arrays\r\n    elapsed_buff         = np.zeros(1,dtype=np.float64)\r\n    longest_elapsed_buff = np.zeros(1,dtype=np.float64)\r\n    # Get start time\r\n    start = MPI.Wtime()\r\n    # Compute (x,y) random points which fall inside the circle\r\n    points_in_circle_per_node = random_points_generator(trials_per_node)\r\n    # Record the time when the function is done\r\n    finish = MPI.Wtime()\r\n    # Compute the time delta\r\n    elapsed_buff[0] = (finish - start)\r\n\r\n    #######################################################################################\r\n    # If needed, print the wall-clock time for each processor\r\n    # print(\"Processor {0} finished in {1:.6f}s.\".format(rank,elapsed_buff[0]), flush=True)\r\n    #######################################################################################\r\n\r\n    # Do a MAX reduction to record the slowest processor\r\n    comm.Reduce([elapsed_buff, MPI.DOUBLE],[longest_elapsed_buff, MPI.DOUBLE],op=MPI.MAX,root=0)\r\n    # Get rid of the array, just need a number\r\n    longest_elapsed = longest_elapsed_buff[0]\r\n    # Init send (i.e. points_in_buff) and receive (i.e. tot_points_in_buff) buffer\r\n    # for SUM reduction\r\n    points_in_buff     = np.zeros(1,dtype=np.int32)\r\n    tot_points_in_buff = np.zeros(1,dtype=np.int32)\r\n    # Store points_in_circle_per_node in the buffer\r\n    points_in_buff[0] = points_in_circle_per_node\r\n    # Do a SUM reduction to retrieve the total number of points fallen\r\n    # inside the circle\r\n    comm.Reduce([points_in_buff, MPI.INT],[tot_points_in_buff, MPI.INT],op=MPI.SUM,root=0)\r\n    # Get rid of the array, just need a number\r\n    tot_points_in = tot_points_in_buff[0]\r\n    # Master node estimates pi\r\n    if rank == 0:\r\n        # print the slowest processor\r\n        print(\"Slowest processor wall-clock time: {:.6f}s\".format(longest_elapsed), flush=True)\r\n        print(\"End\", flush=True)\r\n\r\n        ############################################################################\r\n        # If needed, print the estimated pi and the estimation error\r\n        # estimate pi according to 4*(total points in the circle) / overall trials)\r\n        # estimated_pi = 4*(tot_points_in / total_num_trials)\r\n        # compute the error\r\n        # error_pi = np.abs(np.pi - estimated_pi)\r\n        # print(\"DEBUG: Pi is approximately: {:.6f}\".format(estimated_pi))\r\n        # print(\"DEBUG: Error is: {:.6f}\".format(error_pi))\r\n        ############################################################################\r\n\r\n    # No need to MPI_Finalize() since mpi4py\r\n    # implements an exit hook who does the job for us\r\n", "meta": {"hexsha": "56c43c26560570cc707f3c3ac3e06174521ccffe", "size": 5542, "ext": "py", "lang": "Python", "max_stars_repo_path": "core/algos/monte_carlo_pi.py", "max_stars_repo_name": "Nico769/HPCA-Project-Code", "max_stars_repo_head_hexsha": "08059ac63ffa4c70d3326d167e0e7d9313698a9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-21T06:48:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T06:48:50.000Z", "max_issues_repo_path": "core/algos/monte_carlo_pi.py", "max_issues_repo_name": "Nico769/HPCA-Project-Code", "max_issues_repo_head_hexsha": "08059ac63ffa4c70d3326d167e0e7d9313698a9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/algos/monte_carlo_pi.py", "max_forks_repo_name": "Nico769/HPCA-Project-Code", "max_forks_repo_head_hexsha": "08059ac63ffa4c70d3326d167e0e7d9313698a9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-12T14:13:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-12T14:13:30.000Z", "avg_line_length": 45.8016528926, "max_line_length": 145, "alphanum_fraction": 0.6174666185, "include": true, "reason": "import numpy", "num_tokens": 1277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238083, "lm_q2_score": 0.9111797021730191, "lm_q1q2_score": 0.8603147861970772}}
{"text": "import numpy as np                         # Linear algebra library\nimport matplotlib.pyplot as plt            # library for visualization\nfrom sklearn.decomposition import PCA      # PCA library\nimport pandas as pd                        # Data frame library\nimport math                                # Library for math functions\nimport random                              # Library for pseudo random numbers\n\nn = 1  # The amount of the correlation\nx = np.random.uniform(1,2,1000) # Generate 1000 samples from a uniform random variable\ny = x.copy() * n # Make y = n * x\n\n# PCA works better if the data is centered\nx = x - np.mean(x) # Center x. Remove its mean\ny = y - np.mean(y) # Center y. Remove its mean\n\ndata = pd.DataFrame({'x': x, 'y': y}) # Create a data frame with x and y\nplt.scatter(data.x, data.y) # Plot the original correlated data in blue\n\npca = PCA(n_components=2) # Instantiate a PCA. Choose to get 2 output variables\n\n# Create the transformation model for this data. Internally, it gets the rotation \n# matrix and the explained variance\npcaTr = pca.fit(data)\n\nrotatedData = pcaTr.transform(data) # Transform the data base on the rotation matrix of pcaTr\n# # Create a data frame with the new variables. We call these new variables PC1 and PC2\ndataPCA = pd.DataFrame(data = rotatedData, columns = ['PC1', 'PC2']) \n\n# Plot the transformed data in orange\nplt.scatter(dataPCA.PC1, dataPCA.PC2)\nplt.show()\n\nprint('Eigenvectors or principal component: First row must be in the direction of [1, n]')\nprint(pcaTr.components_)\n\nprint()\nprint('Eigenvalues or explained variance')\nprint(pcaTr.explained_variance_)\n\nimport matplotlib.lines as mlines\nimport matplotlib.transforms as mtransforms\n\nrandom.seed(100)\n\nstd1 = 1     # The desired standard deviation of our first random variable\nstd2 = 0.333 # The desired standard deviation of our second random variable\n\nx = np.random.normal(0, std1, 1000) # Get 1000 samples from x ~ N(0, std1)\ny = np.random.normal(0, std2, 1000)  # Get 1000 samples from y ~ N(0, std2)\n#y = y + np.random.normal(0,1,1000)*noiseLevel * np.sin(0.78)\n\n# PCA works better if the data is centered\nx = x - np.mean(x) # Center x \ny = y - np.mean(y) # Center y\n\n#Define a pair of dependent variables with a desired amount of covariance\nn = 1 # Magnitude of covariance. \nangle = np.arctan(1 / n) # Convert the covariance to and angle\nprint('angle: ',  angle * 180 / math.pi)\n\n# Create a rotation matrix using the given angle\nrotationMatrix = np.array([[np.cos(angle), np.sin(angle)],\n                 [-np.sin(angle), np.cos(angle)]])\n\n\nprint('rotationMatrix')\nprint(rotationMatrix)\n\nxy = np.concatenate(([x] , [y]), axis=0).T # Create a matrix with columns x and y\n\n# Transform the data using the rotation matrix. It correlates the two variables\ndata = np.dot(xy, rotationMatrix) # Return a nD array\n\n# Print the rotated data\nplt.scatter(data[:,0], data[:,1])\nplt.show()\n\nplt.scatter(data[:,0], data[:,1]) # Print the original data in blue\n\n# Apply PCA. In theory, the Eigenvector matrix must be the \n# inverse of the original rotationMatrix. \npca = PCA(n_components=2)  # Instantiate a PCA. Choose to get 2 output variables\n\n# Create the transformation model for this data. Internally it gets the rotation \n# matrix and the explained variance\npcaTr = pca.fit(data)\n\n# Create an array with the transformed data\ndataPCA = pcaTr.transform(data)\n\nprint('Eigenvectors or principal component: First row must be in the direction of [1, n]')\nprint(pcaTr.components_)\n\nprint()\nprint('Eigenvalues or explained variance')\nprint(pcaTr.explained_variance_)\n\n# Print the rotated data\nplt.scatter(dataPCA[:,0], dataPCA[:,1])\n\n# Plot the first component axe. Use the explained variance to scale the vector\nplt.plot([0, rotationMatrix[0][0] * std1 * 3], [0, rotationMatrix[0][1] * std1 * 3], 'k-', color='red')\n# Plot the second component axe. Use the explained variance to scale the vector\nplt.plot([0, rotationMatrix[1][0] * std2 * 3], [0, rotationMatrix[1][1] * std2 * 3], 'k-', color='green')\n\nplt.show()\n\nnPoints = len(data)\n\n# Plot the original data in blue\nplt.scatter(data[:,0], data[:,1])\n\n#Plot the projection along the first component in orange\nplt.scatter(data[:,0], np.zeros(nPoints))\n\n#Plot the projection along the second component in green\nplt.scatter(np.zeros(nPoints), data[:,1])\n\nplt.show()\n\n", "meta": {"hexsha": "2b6ba5e87ab00ba722f0e171e9b5421eddc3ec87", "size": 4324, "ext": "py", "lang": "Python", "max_stars_repo_path": "word_embedding/pca.py", "max_stars_repo_name": "junyaogz/pp4nlp", "max_stars_repo_head_hexsha": "9f403352dcce1874d32ba775a02cbacda0904966", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "word_embedding/pca.py", "max_issues_repo_name": "junyaogz/pp4nlp", "max_issues_repo_head_hexsha": "9f403352dcce1874d32ba775a02cbacda0904966", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "word_embedding/pca.py", "max_forks_repo_name": "junyaogz/pp4nlp", "max_forks_repo_head_hexsha": "9f403352dcce1874d32ba775a02cbacda0904966", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7355371901, "max_line_length": 105, "alphanum_fraction": 0.7039777983, "include": true, "reason": "import numpy", "num_tokens": 1120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191309994467, "lm_q2_score": 0.9005297887874624, "lm_q1q2_score": 0.8602933352635538}}
{"text": "\"\"\"\nlooking at wallis product for pi/2\n\"\"\"\n\n# import libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# close all plots\nplt.close('all')\n\n# generate numbers and sequences via an upper bound\nub = 100\nnum = np.append(np.repeat(np.arange(2,ub,2),2),ub)\nden = np.insert(np.repeat(np.arange(3,ub+1,2),2),0,1)\n\n# empty lists for two methods\nwallis1, wallis2, wallis3 = [], [], []\n\n### method 1 - calculate numerator, then denominator, then divide ###\n\n# iterate through arrays and calculate\nfor i in range(len(num)):\n    wallis1.append(np.prod(num[:i+1])/np.prod(den[:i+1]))\n\n### method 2 - calculate num/denom of each term, then multiply ###\n\n# iterate through arrays and calculate\nfor i in range(len(num)):\n    wallis2.append(np.prod(num[:i+1]/den[:i+1]))\n\n### method 3 - using production summation definition ###\n\n# start with the first term of the series\nwallis3_val = 4.0/3.0\n\n# now start iterations from n=2\nfor n in range(2, ub):\n    wallis3_val *= (4*n**2)/(4*n**2-1)\n    wallis3.append(wallis3_val)\n\n\n### create figures\n\nfig,ax = plt.subplots()\nplt.rcParams.update({'font.size': 18})\nax.plot(wallis1,label='Method 1')\nax.plot(wallis2,label='Method 2',color='g')\nax.plot(wallis3,label='Method 3',color='r')\nax.set_xlabel('# of Iterations $(n)$')\nax.set_ylabel('Value')\nax.axhline(np.pi/2.0,color='k',linestyle='--',label=r'$\\pi/2$')\nax.axhline(0,color='k',linewidth=0.8)\nax.axvline(0,color='k',linewidth=0.8)\nplt.legend()\nax.set_title('Wallis Product')\nplt.tight_layout()", "meta": {"hexsha": "76b17ec93a438c6073698fd264d846333af93583", "size": 1486, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/codes/wallis_product.py", "max_stars_repo_name": "josephfogarty/josephfogarty.github.io", "max_stars_repo_head_hexsha": "53b92be323722d71b0c56bfd5db310caad800b6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/codes/wallis_product.py", "max_issues_repo_name": "josephfogarty/josephfogarty.github.io", "max_issues_repo_head_hexsha": "53b92be323722d71b0c56bfd5db310caad800b6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/codes/wallis_product.py", "max_forks_repo_name": "josephfogarty/josephfogarty.github.io", "max_forks_repo_head_hexsha": "53b92be323722d71b0c56bfd5db310caad800b6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0701754386, "max_line_length": 69, "alphanum_fraction": 0.6870794078, "include": true, "reason": "import numpy", "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152282, "lm_q2_score": 0.9073122176012061, "lm_q1q2_score": 0.8602721936118446}}
{"text": "\"\"\"\nExample:\nLet's concider the problem\n15x1 + 8x2 + 80x3 -> min        (1)\nsubjected to\nx1 + 2x2 + 3x3 <= 15              (2)\n8x1 +  15x2 +  80x3 <= 80      (3)\n8x1  + 80x2 + 15x3 <=150      (4)\n100x1 +  10x2 + x3 >= 800     (5)\n80x1 + 8x2 + 15x3 = 750         (6)\nx1 + 10x2 + 100x3 = 80           (7)\nx1 >= 4                                     (8)\n-8 >= x2 >= -80                        (9)\n\"\"\"\n\nfrom numpy import *\nfrom openopt import LP\nf = array([15,8,80])\nA = mat('1 2 3; 8 15 80; 8 80 15; -100 -10 -1') # numpy.ndarray is also allowed\nb = [15, 80, 150, -800] # numpy.ndarray, matrix etc are also allowed\nAeq = mat('80 8 15; 1 10 100') # numpy.ndarray is also allowed\nbeq = (750, 80)\n\nlb = [4, -80, -inf]\nub = [inf, -8, inf]\np = LP(f, A=A, Aeq=Aeq, b=b, beq=beq, lb=lb, ub=ub)\n#or p = LP(f=f, A=A, Aeq=Aeq, b=b, beq=beq, lb=lb, ub=ub)\n\n#r = p.minimize('glpk') # CVXOPT must be installed\n#r = p.minimize('lpSolve') # lpsolve must be installed\nr = p.minimize('pclp') \n#search for max: r = p.maximize('glpk') # CVXOPT & glpk must be installed\n#r = p.minimize('nlp:ralg', ftol=1e-7, xtol=1e-7, goal='min', plot=1) \n\nprint('objFunValue: %f' % r.ff) # should print 204.48841578\nprint('x_opt: %s' % r.xf) # should print [ 9.89355041 -8.          1.5010645 ]\n", "meta": {"hexsha": "9c925d21cdecb4d8227a57882bba1f271f59aada", "size": 1258, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/python2.7/site-packages/openopt/examples/lp_1.py", "max_stars_repo_name": "wangyum/anaconda", "max_stars_repo_head_hexsha": "6e5a0dbead3327661d73a61e85414cf92aa52be6", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-01-23T16:23:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T16:14:06.000Z", "max_issues_repo_path": "lib/python2.7/site-packages/openopt/examples/lp_1.py", "max_issues_repo_name": "wangyum/anaconda", "max_issues_repo_head_hexsha": "6e5a0dbead3327661d73a61e85414cf92aa52be6", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-04-24T06:46:25.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-24T06:46:25.000Z", "max_forks_repo_path": "lib/python2.7/site-packages/openopt/examples/lp_1.py", "max_forks_repo_name": "wangyum/anaconda", "max_forks_repo_head_hexsha": "6e5a0dbead3327661d73a61e85414cf92aa52be6", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2016-05-30T13:35:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T22:24:29.000Z", "avg_line_length": 34.0, "max_line_length": 79, "alphanum_fraction": 0.5413354531, "include": true, "reason": "from numpy", "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502202, "lm_q2_score": 0.9073122132152183, "lm_q1q2_score": 0.8602721881240307}}
{"text": "from __future__ import division;\nimport numpy as np;\nfrom matplotlib import pyplot as plt;\nfrom matplotlib import colors\nimport matplotlib as mpl;\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import mlab;\nfrom matplotlib import gridspec;\nimport pandas as pd\nfrom IPython.display import display\nimport sklearn;\nfrom sklearn.kernel_ridge import KernelRidge;\n\nfrom notebook.services.config import ConfigManager\ncm = ConfigManager()\ncm.update('livereveal', {\n              'theme': 'simple',\n              'transition': 'none',\n              'start_slideshow_at': 'selected',\n});\n\ndef regression_example_draw(degree1, degree2, degree3, ifprint):\n    x = np.linspace(0, 2*np.pi, 13);\n    # np.random.randn generates gaussian samples\n    y = np.sin(x) + np.random.randn(x.shape[0]) * 0.2;\n    xx = np.linspace(0, 2*np.pi, 100);\n    plt.figure(figsize=(12,7.5))\n    plt.subplot(221)\n    plt.plot(xx, np.sin(xx), \"g\", linestyle='--'); plt.hold(True)\n    plt.plot(x, y, \"or\"); plt.hold(False)\n    plt.legend(['True Curve','Data']); plt.title('Data and True Curve');\n\n    # Here were are going to take advantage of numpy's 'polyfit' function\n    # This implements a \"polynomial fitting\" algorithm\n    # coeffs are the optimal coefficients of the polynomial\n    coeffs = np.polyfit(x, y, degree1); # 0 is the degree of the poly\n    # We construct poly(), the polynomial with \"learned\" coefficients\n    poly = np.poly1d(coeffs);\n    plt.subplot(222)\n    plt.plot(xx, np.sin(xx), \"g\", linestyle='--'); plt.hold(True)\n    plt.plot(x, y, \"or\");\n    plt.plot(xx, poly(xx), color='b', linestyle='-'); plt.hold(False)\n    plt.legend(['True Curve','Data','Learned Curve']); plt.title(str(degree1)+'th Order Polynomial')\n    exprsn1=''\n    for i in range(degree1+1):\n        if i>0 and coeffs[i]>0:\n            exprsn1 += '+%.3fx^%d' %(coeffs[i], i)\n        elif i==0:\n            exprsn1 += '%.3f' %(coeffs[i])\n        else:\n            exprsn1 += '%.3fx^%d' %(coeffs[i], i)\n\n    coeffs = np.polyfit(x, y, degree2); # Now let's try degree = 1\n    poly = np.poly1d(coeffs);\n    plt.subplot(223)\n    plt.plot(xx, np.sin(xx), \"g\", linestyle='--'); plt.hold(True)\n    plt.plot(x, y, \"or\");\n    plt.plot(xx, poly(xx), color='b', linestyle='-'); plt.hold(False)\n    plt.legend(['True Curve','Data','Learned Curve']); plt.title(str(degree2)+'th Order Polynomial')\n    exprsn2 = ''\n    for i in range(degree2+1):\n        if i>0 and coeffs[i]>0:\n            exprsn2 += '+%.3fx^%d' %(coeffs[i], i)\n        elif i==0:\n            exprsn2 += '%.3f' %(coeffs[i])\n        else:\n            exprsn2 += '%.3fx^%d' %(coeffs[i], i)\n\n    coeffs = np.polyfit(x, y, degree3); # Now degree = 3\n    poly = np.poly1d(coeffs);\n    plt.subplot(224)\n    plt.plot(xx, np.sin(xx), \"g\", linestyle='--'); plt.hold(True)\n    plt.plot(x, y, \"or\");\n    plt.plot(xx, poly(xx), color='b', linestyle='-'); plt.hold(False)\n    plt.legend(['True Curve','Data','Learned Curve']); plt.title(str(degree3)+'th Order Polynomial')\n    plt.show()\n    exprsn3 = ''\n    for i in range(degree3+1):\n        if i>0 and coeffs[i]>0:\n            exprsn3 += '+%.3fx^%d' %(coeffs[i], i)\n        elif i==0:\n            exprsn3 += '%.3f' %(coeffs[i])\n        else:\n            exprsn3 += '%.3fx^%d' %(coeffs[i], i)\n\n    if ifprint:\n        print('The expression for the first polynomial is y=' + exprsn1)\n        print('The expression for the second polynomial is y=' + exprsn2)\n        print('The expression for the third polynomial is y=' + exprsn3)\n\ndef set_nice_plot_labels(axs):\n    axs[0].set_title(r\"$ \\phi_j(x) = x^j$\", fontsize=18, y=1.08);\n    axs[0].set_xlabel(\"Polynomial\", fontsize=18);\n    axs[1].set_title(r\"$ \\phi_j(x) = \\exp\\left( - \\frac{(x-\\mu_j)^2}{2s^2} \\right)$\", fontsize=18, y=1.08);\n    axs[1].set_xlabel(\"Gaussian\", fontsize=18);\n    axs[2].set_title(r\"$ \\phi_j(x) = (1  + \\exp\\left(\\frac{\\mu_j-x}{s}\\right))^{-1}$\", fontsize=18, y=1.08);\n    axs[2].set_xlabel(\"Sigmoid\", fontsize=18);\n\ndef basis_function_plot():\n    x = np.linspace(-1,1,100);\n    f, axs = plt.subplots(1, 3, sharex=True, figsize=(12,4));\n    for j in range(8):\n        axs[0].plot(x, np.power(x,j));\n        axs[0].hold(True)\n        axs[1].plot(x, np.exp( - (x - j/7 + 0.5)**2 / 2*5**2 ));\n        axs[1].hold(True)\n        axs[2].plot(x, 1 / (1 + np.exp( - (x - j/5 + 0.5) * 5)) );\n        axs[2].hold(True)\n    axs[0].hold(False)\n    axs[1].hold(False)\n    axs[2].hold(False)\n\n    set_nice_plot_labels(axs) # I'm hiding some helper code that adds labels\n", "meta": {"hexsha": "a8b9c41d650bba2eab78976381766f713613a5aa", "size": 4487, "ext": "py", "lang": "Python", "max_stars_repo_path": "lecture04_linear-regression-part1/Lec04.py", "max_stars_repo_name": "xipengwang/umich-eecs445-f16", "max_stars_repo_head_hexsha": "298407af9fd417c1b6daa6127b17cb2c34c2c772", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 97, "max_stars_repo_stars_event_min_datetime": "2016-09-11T23:15:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T08:03:24.000Z", "max_issues_repo_path": "lecture04_linear-regression-part1/Lec04.py", "max_issues_repo_name": "eecs445-f16/umich-eecs445-f16", "max_issues_repo_head_hexsha": "298407af9fd417c1b6daa6127b17cb2c34c2c772", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture04_linear-regression-part1/Lec04.py", "max_forks_repo_name": "eecs445-f16/umich-eecs445-f16", "max_forks_repo_head_hexsha": "298407af9fd417c1b6daa6127b17cb2c34c2c772", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 77, "max_forks_repo_forks_event_min_datetime": "2016-09-12T20:50:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T14:41:23.000Z", "avg_line_length": 39.3596491228, "max_line_length": 108, "alphanum_fraction": 0.5921551148, "include": true, "reason": "import numpy", "num_tokens": 1380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.9161096072908429, "lm_q1q2_score": 0.8602496536044095}}
{"text": "import numpy as np\n\nclass DataCreator(object):\n    '''\n    Creates random datapoints (x,y) of the underlying function\n        y = f + N(0,noise^2)\n    with \n        f = sin(5/2*x)*son(3/2*x)\n    and\n        noise = 0.15 + 0.25*(1-sin(5/2*x))^2\n\n    '''\n    def __init__(self,num_samples, x_min=0, x_max=2*np.pi,random_seed=42):\n        np.random.seed(random_seed)\n        self.num_samples = num_samples\n        self.x_min = x_min\n        self.x_max = x_max\n    \n    '''\n    call to sample new data points\n    '''\n    def create_datapoints(self):\n        self.x = np.linspace(self.x_min,self.x_max,num=self.num_samples)\n        self.f = np.sin(5*self.x/2)*np.sin(3*self.x/2)\n        self.noise = 0.15 + 0.25*(1-np.sin(5*self.x/2))**2\n        self.y = self.f+np.random.randn(self.num_samples)*self.noise\n\n        self.f = self.f.reshape(self.num_samples,1)\n        self.noise = self.noise.reshape(self.num_samples,1)\n        self.x = self.x.reshape(self.num_samples,1)\n        self.y = self.y.reshape(self.num_samples,1)\n\n    def get_data(self):\n        return self.x, self.y, self.f, self.noise\n\n    '''\n    get normalized samples\n    '''\n    def get_normalized_data(self):\n        mux = np.mean(self.x)\n        sigx = np.std(self.x)\n        muy = np.mean(self.y)\n        sigy = np.std(self.y)\n\n        return (self.x-mux)/sigx, (self.y-muy)/sigy, mux, sigx, muy, sigy\n", "meta": {"hexsha": "4d61ca882212366cd145e485177158165fb9d168", "size": 1368, "ext": "py", "lang": "Python", "max_stars_repo_path": "DataCreator.py", "max_stars_repo_name": "bmaag90/code_uncertainty", "max_stars_repo_head_hexsha": "c872b8379e1a9ed27a18088ad227c362274e8bd7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DataCreator.py", "max_issues_repo_name": "bmaag90/code_uncertainty", "max_issues_repo_head_hexsha": "c872b8379e1a9ed27a18088ad227c362274e8bd7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DataCreator.py", "max_forks_repo_name": "bmaag90/code_uncertainty", "max_forks_repo_head_hexsha": "c872b8379e1a9ed27a18088ad227c362274e8bd7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7391304348, "max_line_length": 74, "alphanum_fraction": 0.5862573099, "include": true, "reason": "import numpy", "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692311915196, "lm_q2_score": 0.880797081106935, "lm_q1q2_score": 0.8602474080404447}}
{"text": "from math import pi, sqrt\nimport math\nimport numpy as np\nimport pandas as pd\nnp.set_printoptions(suppress=True)\n\ndef EMalgorithm(x, K, conv):\n    # Function takes in the dataset, number of clusters and thee precision you want to converge with 10^-conv\n    D = len(x[0]) # the Dimensions/# of features\n    N = len(x)  # number of observations\n    # Initializing Parameters\n    x_col = np.matrix(np.mean(x, axis=0)).T # mean of column/feature\n    sd_col = np.matrix(np.std(x, axis=0, ddof=1)).T # std dev of column/feature\n    randn = np.random.randn(1,K) # 1xK random array\n    # compute Initial Values\n    mu_k = np.array(x_col*np.ones(K) + np.matmul(sd_col,randn))\n    sd_k = np.mean(sd_col)*np.ones(K)\n    p_k = [1/K]*K\n\n\n    p_kn_1 = 0 #previous place holder for convergence \n    condition = True\n    i = 0\n    while condition:\n        print()\n        print(\"iteration: \", i+1)\n        p_kn = E_Step(x,K, D, mu_k,sd_k, p_k) # run the E_step Function\n        print(\"p_kn: \",p_kn)\n        condition = np.any(np.abs((p_kn-p_kn_1))>(10**-conv)) #update the loop condition\n        p_kn_1 = p_kn # update the prev matrix\n        mu_k, sd_k, p_k = M_Step(x,p_kn, K,D,N) # run the M_step Function\n        print(\"mu_k: \",mu_k)\n        print(\"sd_k: \",sd_k)\n        print(\"p_k: \", p_k)\n        i+=1\n    \n    return \n\ndef E_Step(x, K, D, mu_k, sd_k, p_k):\n    # Function takes dataset, # of clusters, Dimensions, mean of cluster, std dev of cluster, p_k\n    \n    g = [None]*K \n    k = 0 # cluster counter\n    while k < K:\n        g[k] = (x-mu_k[:,k])\n        g[k] = np.linalg.norm(g[k],axis=1)**2\n        g[k] = -1/2* (g[k]/(sd_k[k]**2))\n        g[k] = np.exp(g[k])\n        g[k] = 1/(((np.sqrt(2*math.pi))*sd_k[k]))**D * g[k]\n        k+=1\n    g = np.asarray(g) #format to array\n   \n    k=0\n    p_kn =[None]*K \n    while k<K:\n        p_kn[k] = p_k[k]*g[k]\n        k+=1\n    p_kn = np.asarray(p_kn)\n    \n    p_kn = p_kn / np.sum(p_kn, axis=0)\n\n    return p_kn\n\ndef M_Step(x,p_kn, K, D, N):\n    # Function takes dataset, probability of observation being in a cluster matrix, # clusters, Dimensions, # of observations\n\n    k = 0\n    mu_i = [None]*K\n    while k<K:\n        mu_i[k] = np.matmul(p_kn[k],x)/np.sum(p_kn[k])\n        k+=1\n    mu_i= np.asarray(mu_i).T\n\n    k = 0\n    sd_i = [None]*K\n    while k<K:\n        norm = (x-mu_i[:,k])\n        norm = np.linalg.norm(norm,axis=1)**2\n        norm = np.sum(norm*p_kn[k])\n        sd_i[k] = np.sqrt(1/D * norm/sum(p_kn[k]))\n        k+=1\n\n    p_i = 1/N * np.sum(p_kn, axis=1)\n    \n    return mu_i, sd_i, p_i\n\n\nif __name__ == \"__main__\":\n    Iris = pd.read_csv(\"iris.csv\",header=0)\n    IrisMatrix = Iris.to_numpy()\n    IrisMatrix = IrisMatrix[:,0:4]\n    IrisMatrix = IrisMatrix.astype(float)\n    # print(IrisMatrix)\n\n    x = np.array([[1,2],[4,2],[1,3],[4,3]])\n    # run the Expectation maximization algorithm EMalgorithm(Data, # of clusters, 10^-precision value)\n    # EMalgorithm(x,2,6)\n    EMalgorithm(IrisMatrix,3,6)\n\n    ", "meta": {"hexsha": "d39813c1a8bc73911b1d127f6316c2ca181bac2a", "size": 2955, "ext": "py", "lang": "Python", "max_stars_repo_path": "Algorithms for Data Science/Homework 3/Homework3_Q1_Q2.py", "max_stars_repo_name": "ZohaibZ/DataScience", "max_stars_repo_head_hexsha": "ba06c724293f8674375827bdf2d4f42d32788ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Algorithms for Data Science/Homework 3/Homework3_Q1_Q2.py", "max_issues_repo_name": "ZohaibZ/DataScience", "max_issues_repo_head_hexsha": "ba06c724293f8674375827bdf2d4f42d32788ebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Algorithms for Data Science/Homework 3/Homework3_Q1_Q2.py", "max_forks_repo_name": "ZohaibZ/DataScience", "max_forks_repo_head_hexsha": "ba06c724293f8674375827bdf2d4f42d32788ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.55, "max_line_length": 125, "alphanum_fraction": 0.5766497462, "include": true, "reason": "import numpy", "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.967899295134923, "lm_q2_score": 0.8887588008585925, "lm_q1q2_score": 0.8602290168959911}}
{"text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\n# return the matrix A with the correct coefficients\ndef generate_coef(n):\n\tmat = np.zeros((n ** 2, n ** 2));\n\tfor i in range(n):\n\t\tfor j in range(n):\n\t\t\tni = i * n + j\n\t\t\t# dx\n\t\t\tif i < n - 1:\n\t\t\t\tmat.itemset(ni, (i + 1) * n + j, 1)\n\t\t\tif i > 0:\n\t\t\t\tmat.itemset(ni, (i - 1) * n + j, 1)\n\t\t\t\t\n\t\t\t# dy\n\t\t\tif j < n - 1:\n\t\t\t\tmat.itemset(ni, i * n + j + 1, 1)\n\t\t\tif j > 0:\n\t\t\t\tmat.itemset(ni, i * n + j - 1, 1)\n\t\t\t\t\n\t\t\tmat.itemset(ni, ni, -4);\n\treturn -((n + 1) ** 2) * mat\n\n# create a n * n matrix from a value function\ndef func_to_matrix(f, n):\n\treturn np.fromfunction(lambda i, j: f(i/(n - 1), j/(n - 1)), (n, n))\n\n# create a vector of size n² from a matri of size n * n\ndef matrix_to_vector(m):\n\treturn m.flatten().T\n\n# create a matrix of size n * n from a vector of size n²\ndef vector_to_matrix(v):\n\tn = int(np.sqrt(v.size))\n\treturn v.reshape((n, n))\n\n# show the imge corresponding to the given function\ndef show_image(f, solver, N, title):\n\tA = generate_coef(N)\n\n\tb = matrix_to_vector(func_to_matrix(f, N))\n\tprint(\"b = \")\n\tprint(b)\n\t\n\tx = vector_to_matrix(solver(A, b))\n\tprint(\"x = \")\n\tprint(x)\n\t\n\tplt.imshow(x, cmap='hot', extent=(0, 1, 0, 1), interpolation='bilinear')\n\tplt.title(title)\n\tplt.show()\n\n# the function f defining the initial heat of a point radiator\ndef point_radiator(i, j):\n\treturn np.where((i - 0.5) ** 2 + (j - 0.5) ** 2 < 0.01, 1, 0)\n\n# the function f defining the initial heat of a point radiator\ndef wall_radiator(i, j):\n\treturn np.where(i < 0.0001, 1, 0)\n\n\ndef test_equation():\n        N = 32\n        show_image(point_radiator, np.linalg.solve, N, \"Radiateur Point\")\n        show_image(wall_radiator, np.linalg.solve, N, \"Radiateur Mur\")\n\n\nif __name__ == '__main__':\n        test_equation()\n", "meta": {"hexsha": "988dff47dc76ac164b3eb00fc36044ad5953a24d", "size": 1771, "ext": "py", "lang": "Python", "max_stars_repo_path": "Partie_tests/eq_chaleur_npsolver.py", "max_stars_repo_name": "ImadProjects/Resolution-de-systemes-lineaires", "max_stars_repo_head_hexsha": "d37a80e29f780be57f1e88502c8c8fa20d5a511e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Partie_tests/eq_chaleur_npsolver.py", "max_issues_repo_name": "ImadProjects/Resolution-de-systemes-lineaires", "max_issues_repo_head_hexsha": "d37a80e29f780be57f1e88502c8c8fa20d5a511e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Partie_tests/eq_chaleur_npsolver.py", "max_forks_repo_name": "ImadProjects/Resolution-de-systemes-lineaires", "max_forks_repo_head_hexsha": "d37a80e29f780be57f1e88502c8c8fa20d5a511e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9436619718, "max_line_length": 73, "alphanum_fraction": 0.6137775268, "include": true, "reason": "import numpy", "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992914310605, "lm_q2_score": 0.8887587920192298, "lm_q1q2_score": 0.8602290050485377}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef SD(A,b,x0):\n    \"\"\"\n    Parameters:\n    A - Input Matrix\n    b - vector\n    x0 - Initial solution\n    \"\"\"\n    x = x0\n    count = 0\n    r = np.ones_like(b)\n    while(np.linalg.norm(r)>1e-6):\n        r = b - A*x\n        alpha = np.transpose(r)*r/(np.transpose(r)*A*r)\n        print(alpha)\n        x_next = x + alpha*r\n        x = x_next\n        count +=1\n    return x,count\n\ndef CG(A,b,x0):\n    \"\"\"\n    Parameters:\n    A - Input matrix\n    b - Vector\n    x0 - Initial Solution\n    \"\"\"\n    assert np.all(A == np.transpose(A)) ,print('error conjugate gradient method cannot be used since Matrix is not Positive Semi Definite')\n    x = x0\n    count = 0\n    r = np.ones_like(b)\n    d = np.ones_like(b)\n    while(np.linalg.norm(r)>1e-6):\n        r = b - A*x\n        alpha = np.transpose(r)*r/(np.transpose(d)*A*d)\n        x = x + alpha*d\n        r_next = r - alpha*A*d\n        beta = np.transpose(r_next)*r_next/(np.transpose(r)*r)\n        d = r_next + beta*d\n        r = r_next\n        count+=1\n    return x,count\n\nA = np.array([[3,2],[2,6]])\nb = np.array([2,-8])\nx0 = np.array([-3,-3])\n\nvalue = SD(A,b,x0)\ncg = CG(A,b,x0)\nprint(value)\nprint(cg)\n", "meta": {"hexsha": "f4f929c1ffef6c95693e5f266fcc89593dcc6620", "size": 1196, "ext": "py", "lang": "Python", "max_stars_repo_path": "scicomp optmization.py", "max_stars_repo_name": "AbinavRavi/Scientific-Computing-2", "max_stars_repo_head_hexsha": "23b6c2e54283a4700bc69d0b1da552ea45d6fd39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scicomp optmization.py", "max_issues_repo_name": "AbinavRavi/Scientific-Computing-2", "max_issues_repo_head_hexsha": "23b6c2e54283a4700bc69d0b1da552ea45d6fd39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scicomp optmization.py", "max_forks_repo_name": "AbinavRavi/Scientific-Computing-2", "max_forks_repo_head_hexsha": "23b6c2e54283a4700bc69d0b1da552ea45d6fd39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1481481481, "max_line_length": 139, "alphanum_fraction": 0.5384615385, "include": true, "reason": "import numpy", "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992914310605, "lm_q2_score": 0.888758786126321, "lm_q1q2_score": 0.8602289993447955}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\ndef power_negative_3_solution(t: float, x0: float):\n    \"\"\"\n    This function implements the solution to the differential equation\n\n    x' = -x^3\n\n    with initial condition x(t=0) = x0.\n    \"\"\"\n    return np.sqrt(1.0 / (2.0 * t + 1.0 / x0**2))\n\ndef power_negative_1_solution(t: float, x0: float):\n    \"\"\"\n    This function implements the solution to the differential equation\n\n    x' = -x\n\n    with initial condition x(t=0) = x0.\n    \"\"\"\n    return x0 * np.exp(-t)\n\n\nif __name__ == \"__main__\":\n    # Get the time points for the x-axis\n    ts = np.linspace(0.0, 10.0, 1000)\n\n    # Get the solution of the differential equation x'=-x^3 evaluated at these points\n    x_pm3 = power_negative_3_solution(ts, x0=10.)\n    \n    # Get the solution to the differential equation x'=-x evaluated at these points\n    x_pm1 = power_negative_1_solution(ts, x0=10.)\n\n    # Plot the solutions for comparison\n    plt.plot(ts, x_pm3, label=r'$\\dot{x}=-x^3$')\n    plt.plot(ts, x_pm1, label=r'$\\dot{x}=-x$')\n    \n    # Cosmetics\n    plt.title(r\"Comparisons of the solutions to the DE's $\\dot{x}=-x^3$ and $\\dot{x}=-x$\")\n    plt.xlabel(\"t (a.u.)\")\n    plt.ylabel(\"x (a.u.)\")\n    plt.legend()\n    plt.show()", "meta": {"hexsha": "c85c0c9f5f1266a997db6b311a4e14beb114e9b5", "size": 1236, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch2/ex2_4_9.py", "max_stars_repo_name": "FractalArt/chaos_exercises", "max_stars_repo_head_hexsha": "ce86858ceb887560a30f6fd313d920a18f2da5c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-17T18:28:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T18:28:50.000Z", "max_issues_repo_path": "ch2/ex2_4_9.py", "max_issues_repo_name": "FractalArt/chaos_exercises", "max_issues_repo_head_hexsha": "ce86858ceb887560a30f6fd313d920a18f2da5c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch2/ex2_4_9.py", "max_forks_repo_name": "FractalArt/chaos_exercises", "max_forks_repo_head_hexsha": "ce86858ceb887560a30f6fd313d920a18f2da5c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0909090909, "max_line_length": 90, "alphanum_fraction": 0.6318770227, "include": true, "reason": "import numpy", "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.974821163419856, "lm_q2_score": 0.8824278772763471, "lm_q1q2_score": 0.8602093699606426}}
{"text": "# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\n\nimport numpy as np\n\n__all__ = [\n    'log_likelihood',\n    'logistic_sigmoid'\n]\n\n\ndef log_likelihood(X, y, w):\n    \"\"\"Compute the log-likelihood function.\n\n    Computes the log-likelihood function over the training data.\n    The key to the log-likelihood is that the log of the product of\n    likelihoods becomes the sum of logs. That is (in pseudo-code),\n\n        np.log(np.product([f(i) for i in range(N)]))\n\n    is equivalent to:\n\n        np.sum([np.log(f(i)) for i in range(N)])\n\n    The log-likelihood function is used in computing the gradient for\n    our loss function since the derivative of the sum (of logs) is equivalent\n    to the sum of derivatives, which simplifies all of our math.\n\n    Parameters\n    ----------\n    X : np.ndarray, shape=(n_samples, n_features)\n        The training data.\n\n    y : np.ndarray, shape=(n_samples,)\n        The target vector of 1s or 0s.\n\n    w : np.ndarray, shape=(n_features,)\n        The vector of feature weights (coefficients)\n\n    References\n    ----------\n    .. [1] For a very thorough explanation of the log-likelihood function, see\n           https://www.coursera.org/learn/ml-classification/lecture/1ZeTC/very-optional-expressing-the-log-likelihood\n    \"\"\"\n    weighted = X.dot(w)\n    return (y * weighted - np.log(1. + np.exp(weighted))).sum()\n\n\ndef logistic_sigmoid(x):\n    \"\"\"The logistic function.\n\n    Compute the logistic (sigmoid) function over a vector, ``x``.\n\n    Parameters\n    ----------\n    x : np.ndarray, shape=(n_samples,)\n        A vector to transform.\n    \"\"\"\n    return 1. / (1. + np.exp(-x))\n", "meta": {"hexsha": "3953d58d5f9f9fb68a199032d0880e9516418bf3", "size": 1633, "ext": "py", "lang": "Python", "max_stars_repo_path": "packtml/utils/extmath.py", "max_stars_repo_name": "cicorias/supv-ml-py", "max_stars_repo_head_hexsha": "f7e030206efe5bb2c49433ae18e115ca0fcfc5cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-22T22:12:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T16:28:14.000Z", "max_issues_repo_path": "packtml/utils/extmath.py", "max_issues_repo_name": "cicorias/supv-ml-py", "max_issues_repo_head_hexsha": "f7e030206efe5bb2c49433ae18e115ca0fcfc5cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packtml/utils/extmath.py", "max_forks_repo_name": "cicorias/supv-ml-py", "max_forks_repo_head_hexsha": "f7e030206efe5bb2c49433ae18e115ca0fcfc5cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2018-05-31T20:42:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T08:00:14.000Z", "avg_line_length": 26.7704918033, "max_line_length": 117, "alphanum_fraction": 0.642988365, "include": true, "reason": "import numpy", "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620585273154, "lm_q2_score": 0.8962513821399044, "lm_q1q2_score": 0.8601880714805463}}
{"text": "\nfrom statistics import mean\nimport numpy as np\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\n\n\nxs = [1,2,3,4,5,6]\nys = [5,4,6,5,6,7]\n\n# plt.plot(xs,ys)\n# plt.show()\n\n# Since above are not np array they are just a python array, to change them which will give us\n# more powerful way to iterate over then values in the array,\n\nxs = np.array(xs, dtype = np.float64)  # you can also specify the data-type into your array\nys = np.array(ys, dtype = np.float64)\n\n\n# first we need a function to calculate the slop as\n\ndef best_fit_slop(xs,ys):\n\n    m = ( ((mean(xs)*mean(ys)) - mean(xs*ys)) /\n          (mean(xs)**2-mean(xs**2)))\n\n# remember the PEMDAS the order of the operations in computing\n    return m\n\nm = best_fit_slop(xs,ys)\nprint(m)\n", "meta": {"hexsha": "ca05983d4fef7f6ee3e2f232ee77379a6ab2f65e", "size": 762, "ext": "py", "lang": "Python", "max_stars_repo_path": "Machine_Learning_Old_Files/[8] linear regression P.1.py", "max_stars_repo_name": "Ghasak/PracticalMachineLeanring", "max_stars_repo_head_hexsha": "b16095c889be3a14a27e83fe6311581b456cefd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Machine_Learning_Old_Files/[8] linear regression P.1.py", "max_issues_repo_name": "Ghasak/PracticalMachineLeanring", "max_issues_repo_head_hexsha": "b16095c889be3a14a27e83fe6311581b456cefd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:46:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:10:34.000Z", "max_forks_repo_path": "Machine_Learning_Old_Files/[8] linear regression P.1.py", "max_forks_repo_name": "Ghasak/PracticalMachineLeanring", "max_forks_repo_head_hexsha": "b16095c889be3a14a27e83fe6311581b456cefd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4117647059, "max_line_length": 94, "alphanum_fraction": 0.686351706, "include": true, "reason": "import numpy", "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620585273154, "lm_q2_score": 0.8962513731336204, "lm_q1q2_score": 0.8601880628366566}}
{"text": "\"\"\"\nThe Monty Hall Problem [http://en.wikipedia.org/wiki/Monty_Hall_problem] is a probability brain teaser that has a\nrather unintuitive solution.\n\nThe gist of it, taken from Wikipedia:\nSuppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others,\ngoats. You pick a door, say No. 1 [but the door is not opened], and the host, who knows what's behind the doors, opens\nanother door, say No. 3, which has a goat. He then says to you, \"Do you want to pick door No. 2?\" Is it to your\nadvantage to switch your choice? (clarification: the host will always reveal a goat)\n\nYour task is to write a function that will compare the strategies of switching and not switching over many random\nposition iterations. Your program should output the proportion of successful choices by each strategy. Assume that if\nboth unpicked doors contain goats the host will open one of those doors at random with equal probability.\n\nIf you want to, you can for simplicity's sake assume that the player picks the first door every time. The only aspect\nof this scenario that needs to vary is what is behind each door.\n\nThanks to SleepyTurtle for posting this idea at /r/dailyprogrammer_ideas! Do you have a problem you think would be good\nfor us! Head on over there and post it!\n\"\"\"\n\nimport numpy as np\nimport numpy.random as nprnd\nimport time\n\nTRIALS = 1000000\ndoors = [1, 0, 0]\n\nstart_time = time.time()\nkeep = 0\nswitch = 0\nfor _ in range(TRIALS):\n    \"\"\" permutes doors to create random combination of doors and then runs the keep and switch scenarios simultaneously.\n    in the case of initially selecting the correct door, the choice of removing one of the other doors does not matter,\n    so it just chooses the first one.\n    \"\"\"\n    perm = nprnd.permutation(doors)\n    keep += perm[0]\n\n    zero = np.where(perm[1:] == 0)[0]\n    perm = np.delete(perm, zero[0]+1)\n    switch += perm[1]\n\nprint('Kept:         {}%'.format(100*keep/TRIALS))\nprint('Switched:     {}%'.format(100*switch/TRIALS))\nprint('Elapsed time: {}'.format(time.time()-start_time))\n\nstart_time = time.time()\nkeep = 0\nswitch = 0\nfor _ in range(TRIALS):\n    \"\"\" optimization so that it doesn't actually simulate the monty hall problem. instead it is based on the realization\n    that if the permutation's first door is correct, the keep scenario always wins and if the first is incorrect the\n    switch scenario always wins. Time reduced to less than half of the above method.\n    \"\"\"\n    perm = nprnd.permutation(doors)\n    if perm[0]:\n        keep += 1\n    else:\n        switch += 1\n\nprint('Kept:     {}%'.format(100*keep/TRIALS))\nprint('Switched: {}%'.format(100*switch/TRIALS))\nprint('Elapsed time: {}'.format(time.time()-start_time))\n", "meta": {"hexsha": "ffe84a780d17fb9b213674f808d79666ae625258", "size": 2736, "ext": "py", "lang": "Python", "max_stars_repo_path": "DailyProgrammer/20120507A.py", "max_stars_repo_name": "DayGitH/Python-Challenges", "max_stars_repo_head_hexsha": "bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-23T18:59:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T13:16:09.000Z", "max_issues_repo_path": "DailyProgrammer/20120507A.py", "max_issues_repo_name": "DayGitH/Python-Challenges", "max_issues_repo_head_hexsha": "bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DailyProgrammer/20120507A.py", "max_forks_repo_name": "DayGitH/Python-Challenges", "max_forks_repo_head_hexsha": "bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0923076923, "max_line_length": 120, "alphanum_fraction": 0.7247807018, "include": true, "reason": "import numpy", "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482725, "lm_q2_score": 0.9196425278741989, "lm_q1q2_score": 0.8601844337212442}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nMake a simple 2D Gaussian profile.  One example is in the representation of an\r\nideal laser beam.\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport gaussian1D_profile as gp\r\n\r\n\r\n\r\n\r\ndef gaussian_2D_profile(x_min, x_max, x_step, y_min, y_max, y_step,\r\n                        xc, yc, sigma_x, sigma_y, amplitude):\r\n    \"\"\"Function to produce a 2D Gaussian profile.\r\n    \r\n    Parameters\r\n    ----------\r\n    \r\n    x_min, x_max, x_step: float, float, float\r\n        Creates a sequence (1D ndarray) of x points over which to compute the Gaussian\r\n    y_min, y_max, y_step: float, float, float\r\n        Creates a sequence (1D ndarray) of y points over which to compute the Gaussian        \r\n    xc,yc: float, float\r\n        The center points in x and y of the gaussian profile\r\n    sigma_x, sigma_y: float, float\r\n        1/e-squared width of beam in the x and y axis respectively\r\n    amplitude: float \r\n        Amplitude at peak value\r\n        \r\n    Returns\r\n    -------\r\n    \r\n    Z: ndarray\r\n        The 2D gaussian profile amplitude values\r\n        \r\n    \"\"\"\r\n\r\n    idx = np.arange(x_min, x_max, x_step)\r\n    idy = np.arange(y_min, y_max, y_step)\r\n\r\n    d0x = 2*sigma_x  #beam diameter (1/e-squared) is 2 * standard deviation\r\n    d0y = 2*sigma_y\r\n\r\n    x = amplitude * np.e**(-2*np.power((idx-xc)/d0x,2))\r\n    y = amplitude * np.e**(-2*np.power((idy-yc)/d0y,2))\r\n\r\n\r\n    plt.plot(idx, x, label='x')\r\n    plt.plot(idy, y, label='y')\r\n    plt.title('Gaussian 1D Profiles in x and y')\r\n    plt.legend()\r\n    plt.show()\r\n\r\n    #now 2d...can just multiply the two 1D curves together\r\n    X,Y = np.meshgrid(idx,idy)\r\n    \r\n    #Z = np.e**(-2*(((X-xc)/d0x)**2 * ((Y-yc)/d0y)**2))  #interesting star type pattern\r\n\r\n    # The following methods are equivalent e^x * e^y = e^(x+y)\r\n    #Z = np.e**(-2*np.power((X-xc)/d0x,2))*np.e**(-2*np.power((Y-yc)/d0y,2)) #1.92ms per loop\r\n    #Z = np.e**(-2*((X-xc)/d0x)**2) * np.e**(-2*((Y-yc)/d0y)**2) # 1.03ms per loop\r\n    Z = np.e**(-2*(((X-xc)/d0x)**2 + ((Y-yc)/d0y)**2))          # 586us per loop (4x faster)\r\n    \r\n    return Z\r\n\r\n\r\ndef plot_2d_gaussian(Z):\r\n    \"\"\"Plot the gaussian profile as a 2D image and contour lines.\r\n    \r\n    Parameters\r\n    ----------\r\n    \r\n    Z: ndarray\r\n        2D Gaussian values\r\n        \r\n    \"\"\"   \r\n    \r\n    plt.figure()\r\n    #plt.axis('off')\r\n    plt.imshow(Z,extent=(-50,50,-50,50))\r\n    plt.contour(Z)\r\n    plt.title('2D Gaussian Profile')\r\n    plt.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n    Z = gaussian_2D_profile(-50,50,1,-50,50,1, 0, 0, 10, 5, 1)\r\n    plot_2d_gaussian(Z)\r\n    \r\n    \r\n    \r\n    ", "meta": {"hexsha": "ba9c70f730aebb46b998768298633887d3211cb4", "size": 2670, "ext": "py", "lang": "Python", "max_stars_repo_path": "gaussian2D_profile.py", "max_stars_repo_name": "jfblanchard/gaussian-beam", "max_stars_repo_head_hexsha": "bab00487e3bc19885abd1b26d759539ff07b0103", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gaussian2D_profile.py", "max_issues_repo_name": "jfblanchard/gaussian-beam", "max_issues_repo_head_hexsha": "bab00487e3bc19885abd1b26d759539ff07b0103", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gaussian2D_profile.py", "max_forks_repo_name": "jfblanchard/gaussian-beam", "max_forks_repo_head_hexsha": "bab00487e3bc19885abd1b26d759539ff07b0103", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8125, "max_line_length": 95, "alphanum_fraction": 0.5647940075, "include": true, "reason": "import numpy", "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846703886661, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.8601437234510577}}
{"text": "\"\"\" This module implements the Fourier transforms on linear grids.\r\n\r\nThe following code approximates the continuous Fourier transform (FT) on\r\nequidistantly spaced grids. While this is usually associated with\r\n'just doing a fast Fourier transform (FFT)', surprisingly, much can be done\r\nwrong.\r\n\r\nThe reason is that the correct expressions depend on the grid location. In\r\nfact, the FT can be calculated with one DFT but in general it requires a prior\r\nand posterior multiplication with phase factors.\r\n\r\nThe FT convention we are going to use here is the following::\r\n\r\n    Ẽ(w) = 1/2pi ∫ E(t) exp(+i w t) dt\r\n    E(t) =       ∫ Ẽ(w) exp(-i t w) dw\r\n\r\nwhere w is the angular frequency. We can approximate these integrals by their\r\nRiemann sums on the following equidistantly spaced grids::\r\n\r\n    t_k = t_0 + k Δt, k=0, ..., N-1\r\n    w_n = w_0 + n Δw, n=0, ..., N-1\r\n\r\nand define E_k = E(t_k) and Ẽ_n = Ẽ(w_n) to obtain::\r\n\r\n    Ẽ_n = Δt/2pi ∑_k E_k exp(+i w_n t_k)\r\n    E_k = Δw     ∑_n Ẽ_n exp(-i t_k w_n).\r\n\r\nTo evaluate the sum using the FFT we can expand the exponential to obtain::\r\n\r\n    Ẽ_n = Δt/2pi exp(+i n t_0 Δw) ∑_k [E_k exp(+i t_k w_0) ] exp(+i n k Δt Δw)\r\n    E_k = Δw     exp(-i t_k w_0)  ∑_n [Ẽ_n exp(-i n t_0 Δw)] exp(-i k n Δt Δw)\r\n\r\nAdditionally, we have to require the so-called reciprocity relation for\r\nthe grid spacings::\r\n\r\n          !\r\n    Δt Δw = 2pi / N = ζ     (reciprocity relation)\r\n\r\nThis is what enables us to use the DFT/FFT! Now we look at the definition of\r\nthe FFT in NumPy::\r\n\r\n     fft[x_m] -> X_k =     ∑_m exp(-2pi i m k / N)\r\n    ifft[X_k] -> x_m = 1/N ∑_k exp(+2pi i k m / N)\r\n\r\nwhich gives the final expressions::\r\n\r\n    Ẽ_n = Δt N/2pi r_n   ifft[E_k s_k  ]\r\n    E_k = Δw       s_k^*  fft[Ẽ_n r_n^*]\r\n\r\n    with r_n = exp(+i n t_0 Δw)\r\n         s_k = exp(+i t_k w_0)\r\n\r\nwhere ^* means complex conjugation. We see that the array to be transformed\r\nhas to be multiplied with an appropriate phase factor before and after\r\nperforming the DFT. And those phase factors mainly depend on the starting\r\npoints of the grids: w_0 and t_0. Note also that due to our sign convention\r\nfor the FT we have to use ifft for the forward transform and vice versa.\r\n\r\nTrivially, we can see that for ``w_0 = t_0 = 0`` the phase factors vanish and\r\nthe FT is approximated well by just the DFT. However, in optics these\r\ngrids are unusual.\r\nFor ``w_0 = l Δw`` and ``t_0 = m Δt``, where l, m are integers (i.e., w_0 and\r\nt_0 are multiples of the grid spacing), the phase factors can be\r\nincorperated into the DFT. Then the phase factors can be replaced by circular\r\nshifts of the input and output arrays.\r\n\r\nThis is exactly what the functions (i)fftshift are doing for one specific\r\nchoice of l and m, namely for::\r\n\r\n    t_0 = -floor(N/2) Δt\r\n    w_0 = -floor(N/2) Δw.\r\n\r\nIn this specific case only we can approximate the FT by::\r\n\r\n    Ẽ_n = Δt N/2pi fftshift(ifft(ifftshift(E_k)))\r\n    E_k = Δw       fftshift( fft(ifftshift(Ẽ_n))) (no mistake!)\r\n\r\nWe see that the ifftshift _always_ has to appear on the inside. Failure to do\r\nso will still be correct for even N (here fftshift is the same as ifftshift)\r\nbut will produce wrong results for odd N.\r\n\r\nAdditionally you have to watch out not to violate the assumptions for the\r\ngrid positions. Using a symmetrical grid, e.g.,::\r\n\r\n    x = linspace(-1, 1, 128)\r\n\r\nwill also produce wrong results, as the elements of x are not multiples of the\r\ngrid spacing (but shifted by half a grid point).\r\n\r\nThe main drawback of this approach is that circular shifts are usually far more\r\ntime- and memory-consuming than an elementwise multiplication, especially for\r\nhigher dimensions. In fact I see no advantage in using the shift approach at\r\nall. But for some reason it got stuck in the minds of people and you find the\r\nnotion of having to re-order the output of the DFT everywhere.\r\n\r\nLong story short: here we are going to stick with multiplying the correct\r\nphase factors. The code tries to follow the notation used above.\r\n\r\nGood, more comprehensive expositions of the issues above can be found in\r\n[Briggs1995]_ and [Hansen2014]_. For the reason why the first-order\r\napproximation to the Riemann integral suffices, see [Trefethen2014]_.\r\n\"\"\"\r\nimport numpy as np\r\n# scipy.fftpack is still faster than numpy.fft (should change in numpy 1.17)\r\nimport scipy.fftpack as fft\r\nfrom . import io\r\nfrom .lib import twopi, sqrt2pi\r\n_fft_backend = 'scipy'\r\ntry:\r\n    import pyfftw\r\n    _fft_backend = 'pyfftw'\r\nexcept ImportError:\r\n    pass\r\n\r\n\r\nclass FourierTransformBase(io.IO):\r\n    \"\"\" This class implements the Fourier transform on linear grids.\r\n\r\n    This simple implementation is mainly for educational use.\r\n\r\n    Attributes\r\n    ----------\r\n    N : int\r\n        Size of the grid\r\n    dt : float\r\n        Temporal spacing\r\n    dw : float\r\n        Frequency spacing (angular frequency)\r\n    t0 : float\r\n        The first element of the temporal grid\r\n    w0 : float\r\n        The first element of the frequency grid\r\n    t : 1d-array\r\n        The temporal grid\r\n    w : 1d-array\r\n        The frequency grid (angular frequency)\r\n    \"\"\"\r\n    _io_store = ['N', 'dt', 'dw', 't0', 'w0']\r\n\r\n    def __init__(self, N, dt=None, dw=None, t0=None, w0=None):\r\n        \"\"\" Creates conjugate grids and calculates the Fourier transform.\r\n\r\n        Parameters\r\n        ----------\r\n        N : int\r\n            Array size\r\n        dt : float, optional\r\n            The temporal grid spacing. If ``None`` will be calculated by the\r\n            reciprocity relation ``dt = 2 * pi / (N * dw)``. Exactly one of\r\n            ``dt`` or ``dw`` has be provided.\r\n        dw : float, optional\r\n            The spectral grid spacing. If ``None`` will be calculated by the\r\n            reciprocity relation ``dw = 2 * pi / (N * dt)``. Exactly one of\r\n            ``dt`` or ``dw`` has be provided.\r\n        t0 : float, optional\r\n            The first element of the temporal grid. If ``None`` will be\r\n            ``t0 = -floor(N/2) * dt``.\r\n        w0 : float, optional\r\n            The first element of the spectral grid. If ``None`` will be\r\n            ``w0 = -floor(N/2) * dw``.\r\n        \"\"\"\r\n        if dw is None and dt is not None:\r\n            dw = np.pi / (0.5 * N * dt)\r\n        elif dt is None and dw is not None:\r\n            dt = np.pi / (0.5 * N * dw)\r\n        else:\r\n            raise ValueError(\"Exactly one of the grid spacings has to be \"\r\n                             \"provided!\")\r\n\r\n        if t0 is None:\r\n            t0 = -np.floor(0.5 * N) * dt\r\n        if w0 is None:\r\n            w0 = -np.floor(0.5 * N) * dw\r\n        self.N = N\r\n        self.dt = dt\r\n        self.dw = dw\r\n        self.t0 = t0\r\n        self.w0 = w0\r\n        self._post_init()\r\n\r\n    def _post_init(self):\r\n        \"\"\" Hook to initialize an object from storage.\r\n        \"\"\"\r\n        # calculate the grids\r\n        n = k = np.arange(self.N)\r\n        self.t = self.t0 + k * self.dt\r\n        self.w = self.w0 + n * self.dw\r\n        # pre-calculate the phase factors\r\n        # TODO: possibly inaccurate for large t0, w0\r\n        self._fr = self.dt * self.N / twopi * np.exp(1.0j * n * self.t0 *\r\n                                                     self.dw)\r\n        self._fs = np.exp(1.0j * self.t * self.w0)\r\n        # complex conjugate of the above\r\n        self._br = np.exp(-1.0j * n * self.t0 * self.dw)\r\n        self._bs = self.dw * np.exp(-1.0j * self.t * self.w0)\r\n\r\n    def forward_at(self, x, w):\r\n        \"\"\" Calculates the forward Fourier transform of `x` at the\r\n        frequencies `w`.\r\n\r\n        This function calculates the Riemann sum directly and has quadratic\r\n        runtime. However, it can evaluate the integral at arbitrary\r\n        frequencies, even if they are non-equidistantly spaced. Effectively,\r\n        it performs a trigonometric interpolation.\r\n        \"\"\"\r\n        Dnk = self.dt / twopi * np.exp(1.0j * w[:, None] * self.t[None, :])\r\n        return Dnk @ x\r\n\r\n    def backward_at(self, x, t):\r\n        \"\"\" Calculates the backward Fourier transform of `x` at the\r\n        times `t`.\r\n\r\n        This function calculates the Riemann sum directly and has quadratic\r\n        runtime. However, it can evaluate the integral at arbitrary\r\n        times, even if they are non-equidistantly spaced. Effectively,\r\n        it performs a trigonometric interpolation.\r\n        \"\"\"\r\n        Dkn = self.dw * np.exp(-1.0j * t[:, None] * self.w[None, :])\r\n        return Dkn @ x\r\n\r\n\r\n# =============================================================================\r\n# Fourier backend selection\r\n# =============================================================================\r\nif _fft_backend == \"scipy\":\r\n    class FourierTransform(FourierTransformBase):\r\n\r\n        def forward(self, x, out=None):\r\n            \"\"\" Calculates the (forward) Fourier transform of ``x``.\r\n\r\n            For n-dimensional arrays it operates on the last axis, which has\r\n            to match the size of `x`.\r\n\r\n            Parameters\r\n            ----------\r\n            x : ndarray\r\n                The array of which the Fourier transform will be calculated.\r\n            out : ndarray or None, optional\r\n                A location into which the result is stored. If not provided or\r\n                None, a freshly-allocated array is returned.\r\n            \"\"\"\r\n            if out is None:\r\n                out = np.empty(x.shape, dtype=np.complex128)\r\n            out[:] = self._fr * fft.ifft(self._fs * x)\r\n            return out\r\n\r\n        def backward(self, x, out=None):\r\n            \"\"\" Calculates the backward (inverse) Fourier transform of ``x``.\r\n\r\n            For n-dimensional arrays it operates on the last axis, which has\r\n            to match the size of `x`.\r\n\r\n            Parameters\r\n            ----------\r\n            x : ndarray\r\n                The array of which the Fourier transform will be calculated.\r\n            out : ndarray or None, optional\r\n                A location into which the result is stored. If not provided or\r\n                None, a freshly-allocated array is returned.\r\n            \"\"\"\r\n            if out is None:\r\n                out = np.empty(x.shape, dtype=np.complex128)\r\n            out[:] = self._bs * fft.fft(self._br * x)\r\n            return out\r\n\r\nelif _fft_backend == \"pyfftw\":\r\n    class FourierTransform(FourierTransformBase):\r\n\r\n        def _post_init(self):\r\n            super()._post_init()\r\n            # do not need the additional N factor\r\n            n = np.arange(self.N)\r\n            self._fr = self.dt / twopi * np.exp(1.0j * n * self.t0 * self.dw)\r\n            # create the aligned arrays\r\n            a = self._field = pyfftw.empty_aligned(self.N, dtype=\"complex128\")\r\n            b = self._spectrum = pyfftw.empty_aligned(self.N,\r\n                                                      dtype=\"complex128\")\r\n            # instantiate the FFTW objects\r\n            self._fft = pyfftw.FFTW(b, a, direction=\"FFTW_FORWARD\")\r\n            self._ifft = pyfftw.FFTW(a, b, direction=\"FFTW_BACKWARD\")\r\n\r\n        def forward(self, x, out=None):\r\n            \"\"\" Calculates the (forward) Fourier transform of ``x``.\r\n\r\n            For n-dimensional arrays it operates on the last axis, which has\r\n            to match the size of `x`.\r\n\r\n            Parameters\r\n            ----------\r\n            x : ndarray\r\n                The array of which the Fourier transform will be calculated.\r\n            out : ndarray or None, optional\r\n                A location into which the result is stored. If not provided or\r\n                None, a freshly-allocated array is returned.\r\n            \"\"\"\r\n            if out is None:\r\n                out = np.empty(x.shape, dtype=np.complex128)\r\n            f, s = self._field, self._spectrum\r\n            if x.ndim == 1:\r\n                # fast code path for single dimension\r\n                f[:] = x\r\n                f *= self._fs\r\n                self._ifft.execute()\r\n                s *= self._fr\r\n                out[:] = s\r\n            else:\r\n                # implicitly work along last axis and return copy\r\n                for idx in np.ndindex(x.shape[:-1]):\r\n                    f[:] = x[idx]\r\n                    f *= self._fs\r\n                    self._ifft.execute()\r\n                    s *= self._fr\r\n                    out[idx] = s\r\n            return out\r\n\r\n        def backward(self, x, out=None):\r\n            \"\"\" Calculates the backward (inverse) Fourier transform of ``x``.\r\n\r\n            For n-dimensional arrays it operates on the last axis, which has\r\n            to match the size of `x`.\r\n\r\n            Parameters\r\n            ----------\r\n            x : ndarray\r\n                The array of which the Fourier transform will be calculated.\r\n            out : ndarray or None, optional\r\n                A location into which the result is stored. If not provided or\r\n                None, a freshly-allocated array is returned.\r\n            \"\"\"\r\n            if out is None:\r\n                out = np.empty(x.shape, dtype=np.complex128)\r\n            f, s = self._field, self._spectrum\r\n            if x.ndim == 1:\r\n                # fast code path for single dimension\r\n                s[:] = x\r\n                s *= self._br\r\n                self._fft.execute()\r\n                f *= self._bs\r\n                out[:] = f\r\n            else:\r\n                # implicitly work along last axis and return copy\r\n                for idx in np.ndindex(x.shape[:-1]):\r\n                    s[:] = x[idx]\r\n                    s *= self._br\r\n                    self._fft.execute()\r\n                    f *= self._bs\r\n                    out[idx] = f\r\n            return out\r\n\r\n\r\nclass Gaussian:\r\n    \"\"\" This class can be used for testing the Fourier transform.\r\n    \"\"\"\r\n\r\n    def __init__(self, dt, t0=0.0, phase=0.0):\r\n        \"\"\" Instantiates a shifted Gaussian function.\r\n\r\n        The Gaussian is calculated by::\r\n\r\n            f(t) = exp(-0.5 (t - t0)^2 / dt^2) * exp(1.0j * phase)\r\n\r\n        Its Fourier transform is::\r\n\r\n            F(w) = dt/sqrt(2pi) exp(-0.5 * (w + phase)^2 * dt^2 +\r\n                                     1j * t0 * w)\r\n\r\n        Parameters\r\n        ----------\r\n        dt : float\r\n            The standard deviation of the temporal amplitude distribution.\r\n        t0 : float\r\n            The center of the temporal amplitude distribution.\r\n        phase : float\r\n            The linear phase coefficient of the temporal distribution.\r\n        \"\"\"\r\n        self.dt = dt\r\n        self.t0 = t0\r\n        self.phase = phase\r\n\r\n    def temporal(self, t):\r\n        \"\"\" Returns the temporal distribution.\r\n        \"\"\"\r\n        arg = (t - self.t0) / self.dt\r\n        return np.exp(-0.5 * arg**2) * np.exp(1.0j * self.phase * t)\r\n\r\n    def spectral(self, w):\r\n        \"\"\" Returns the spectral distribution.\r\n        \"\"\"\r\n        w = w + self.phase\r\n        arg = w * self.dt\r\n        return (self.dt * np.exp(-0.5 * arg**2) * np.exp(1.0j * self.t0 * w) /\r\n                sqrt2pi)\r\n", "meta": {"hexsha": "1471f78311a2eba4e37cac3176a9d15825e588a1", "size": 14947, "ext": "py", "lang": "Python", "max_stars_repo_path": "pypret/fourier.py", "max_stars_repo_name": "liam-clink/pypret", "max_stars_repo_head_hexsha": "c84e954efc12137c6b5ade4fae920d60a15d4875", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2019-03-16T18:38:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T14:25:30.000Z", "max_issues_repo_path": "pypret/fourier.py", "max_issues_repo_name": "liam-clink/pypret", "max_issues_repo_head_hexsha": "c84e954efc12137c6b5ade4fae920d60a15d4875", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-24T21:32:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-03T12:46:28.000Z", "max_forks_repo_path": "pypret/fourier.py", "max_forks_repo_name": "liam-clink/pypret", "max_forks_repo_head_hexsha": "c84e954efc12137c6b5ade4fae920d60a15d4875", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-07-23T22:03:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T08:50:52.000Z", "avg_line_length": 38.0330788804, "max_line_length": 80, "alphanum_fraction": 0.5547601525, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.8991213820004279, "lm_q1q2_score": 0.8601302673075388}}
{"text": "# -*- coding:utf-8 -*-\n\n\"\"\"Strassen算法求矩阵乘法\n\"\"\"\n\nimport numpy as np\n\n\ndef strassen(A, B):\n    \"\"\"Strassen算法求矩阵乘法\n\n    Args:\n        A(np.array): 矩阵1\n        B(np.array): 矩阵2\n\n    Return:\n        C(np.array): 矩阵乘法结果\n    \"\"\"\n    n, _ = A.shape\n\n    if n == 1:\n        C = np.array(A[0, 0] * B[0, 0])\n        return C\n    else:\n        A11 = A[0:n//2, 0:n//2]\n        A12 = A[0:n//2, n//2:]\n        A21 = A[n//2:, 0:n//2]\n        A22 = A[n//2:, n//2:]\n        B11 = B[0:n//2, 0:n//2]\n        B12 = B[0:n//2, n//2:]\n        B21 = B[n//2:, 0:n//2]\n        B22 = B[n//2:, n//2:]\n\n        S1 = B12 - B22\n        S2 = A11 + A12\n        S3 = A21 + A22\n        S4 = B21 - B11\n        S5 = A11 + A22\n        S6 = B11 + B22\n        S7 = A12 - A22\n        S8 = B21 + B22\n        S9 = A11 - A21\n        S10 = B11 + B12\n\n        P1 = strassen(A11, S1)\n        P2 = strassen(S2, B22)\n        P3 = strassen(S3, B11)\n        P4 = strassen(A22, S4)\n        P5 = strassen(S5, S6)\n        P6 = strassen(S7, S8)\n        P7 = strassen(S9, S10)\n\n        C11 = P5 + P4 - P2 + P6\n        C12 = P1 + P2\n        C21 = P3 + P4\n        C22 = P5 + P1 - P3 - P7\n\n        C = np.vstack((np.hstack((C11, C12)), np.hstack((C21, C22))))\n        return C\n\n\nif __name__ == '__main__':\n    A = np.array([\n        [1, 2, 3, 4],\n        [4, 3, 2, 1],\n        [1, 3, 5, 7],\n        [7, 5, 3, 1],\n    ])\n    B = np.array([\n        [2, 4, 6, 8],\n        [8, 6, 4, 2],\n        [1, 2, 3, 4],\n        [4, 3, 2, 1],\n    ])\n\n    print(strassen(A, B))\n", "meta": {"hexsha": "d64051a4b6a6b8810c7285ac768ad37dbe2d00cb", "size": 1501, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter4/Strassen.py", "max_stars_repo_name": "TreezzZ/Introduction_to_Algorithms", "max_stars_repo_head_hexsha": "049818689c8b2b4732f718ada4f044d0d563c7ca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter4/Strassen.py", "max_issues_repo_name": "TreezzZ/Introduction_to_Algorithms", "max_issues_repo_head_hexsha": "049818689c8b2b4732f718ada4f044d0d563c7ca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter4/Strassen.py", "max_forks_repo_name": "TreezzZ/Introduction_to_Algorithms", "max_forks_repo_head_hexsha": "049818689c8b2b4732f718ada4f044d0d563c7ca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4935064935, "max_line_length": 69, "alphanum_fraction": 0.3784143904, "include": true, "reason": "import numpy", "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342049451596, "lm_q2_score": 0.89912137659416, "lm_q1q2_score": 0.8601302632473518}}
{"text": "#!/usr/bin/python\n#   X = FEJER(N) returns N Chebyshev points X in (-1,1).\n#\n#   X, W = FEJER(N) returns also a vector W of weights for\n#   Fejer quadrature.\n#\n#   X, W = FEJER(N, [A, B]) returns the nodes and weights\n#   for the interval [A, B].\n\nimport numpy as np\n\ndef fejer(N, dom=[-1,1]):\n    t = np.zeros(shape=(N,1))\n    x = np.zeros(shape=(N,1))\n    for k in range(N):\n        t[k] = (0.5+k)*np.pi/N;\n        x[k] = -np.cos(t[k])\n\n    # Weights\n    V_trans = np.zeros(shape=(N,N))\n    for j in range(N):\n        for k in range(N):\n            V_trans[j][k] = np.cos(j*t[k]);\n    rhs = np.zeros(shape=(N,1))\n    for j in range(0, N, 2):\n        rhs[j] = 2./(1.-j*j);\n    c = np.linalg.solve(V_trans, rhs);\n\n    # Scale\n    a = dom[0];\n    b = dom[1];\n    x = .5*(b-a)*x + .5*(b+a);\n    c = .5*(b-a)*c;\n\n    return (x, c)\nif __name__ == \"__main__\":\n    x, c = fejer(5, [-1, 1])\n    print 'x = ', x\n    print 'c = ', c\n", "meta": {"hexsha": "3da1943e1191354efdc3dd1e3904baa7e78c99ef", "size": 924, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment_05/src/fejer.py", "max_stars_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_stars_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-28T18:36:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-28T18:36:55.000Z", "max_issues_repo_path": "assignment_05/src/fejer.py", "max_issues_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_issues_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment_05/src/fejer.py", "max_forks_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_forks_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-16T04:26:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-16T04:26:44.000Z", "avg_line_length": 23.1, "max_line_length": 58, "alphanum_fraction": 0.4891774892, "include": true, "reason": "import numpy", "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.8991213759183765, "lm_q1q2_score": 0.8601302614892404}}
{"text": "\"\"\"\"\n    This program calculates the inverse of a matrix by many ways.\n    Marina von Steinkirch, spring/2013 (based on Mike Zingale's codes)\n\n\"\"\"\n\n\nimport numpy as npy\nfrom scipy import linalg \nfrom inverseGauss import inverseGauss\nfrom inverseNewton import inverseNewton\n\n\n\n\ndef main():\n    A = npy.array([ [4, 3, 4, 10], [2, -7, 3, 0], [-2, 11, 1, 3], [3, -4, 0, 2] ], dtype=npy.float64)\n    \n    \"\"\"\n    print \"\\nInverse matrix calculated by the Numpy API:\"\n    AinvNpy = linalg.inv(A)\n    print \"NumPy: A . Ainv = \\n\", npy.dot(A, AinvNpy)\n    print \"NumPy: Ainv = \\n\", AinvNpy\n    \n\n    print \"\\nInverse matrix calculated by the Gauss method:\"    \n    AinvGauss = inverseGauss(A)\n    print \"Gauss: A . Ainv = \\n\", npy.dot(A, AinvGauss)\n    print \"Gauss: Ainv = \\n\", AinvGauss\n    \n    \"\"\"\n    \n    print \"\\nInverse matrix calculated by the Newton method:\"\n    AinvNewton, error, nIter = inverseNewton(A)\n    print \"Newtow: A . Ainv = \\n\", npy.dot(A, AinvNewton)\n    print \"Newtow: Ainv = \\n\", AinvNewton\n    print \"Number of iterations: \", nIter\n    print \"Error from Numpy API results: \", error\n    \n\n    print \"\\nDone!\"\n\n\nif __name__ == \"__main__\":\n    main()", "meta": {"hexsha": "fb48702cfcef61f313acf6e43026709825b8e333", "size": 1166, "ext": "py", "lang": "Python", "max_stars_repo_path": "homework3_linear_algebra_FFT/matrix_inverse/main.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "homework3_linear_algebra_FFT/matrix_inverse/main.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework3_linear_algebra_FFT/matrix_inverse/main.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 25.9111111111, "max_line_length": 101, "alphanum_fraction": 0.6234991424, "include": true, "reason": "import numpy,from scipy", "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341962906709, "lm_q2_score": 0.8991213671331905, "lm_q1q2_score": 0.860130246415229}}
{"text": "\nimport numpy as np\nimport operator as op\nfrom functools import reduce\n\ndef ncr(n, r):\n    \"\"\"n choose r\"\"\"\n    r = min(r, n - r)  # This works since it's symmetric\n    \n    numer = reduce(op.mul, range(n, n - r, -1), 1)\n    denom = reduce(op.mul, range(1, r + 1), 1)\n    return numer / denom\n\ndef bernstein_poly(i, n, t):\n    \"\"\"\n     The Bernstein polynomial of n, i as a function of t\n    \"\"\"\n    return ncr(n, i) * (t ** (n - i)) * (1 - t)**i\n    \ndef compute_bezier_points(points, n_times=25):\n    \"\"\"\n        Returns a list of points that can be used to construct a bezier curve.\n    \"\"\"\n    n_points = len(points)\n    x_points, y_points = np.array([p[0] for p in points]), np.array([p[1] for p in points])\n\n    t = np.linspace(0.0, 1.0, n_times)\n    polynomial_array = np.array([bernstein_poly(i, n_points-1, t) for i in range(0, n_points)])\n\n    x_vals, y_vals = np.dot(x_points, polynomial_array), np.dot(y_points, polynomial_array)\n\n    return [(x, y) for x, y in zip(x_vals, y_vals)]\n\ndef colour_linear_interpolation(col_a, col_b, t):\n    \"\"\"\n        Linearly interpolates between two colours. \n    \"\"\"\n    col = tuple([a + (b - a) * t for a, b in zip(col_a, col_b)])\n    return col\n\ndef map_from_to(x, a, b, c, d):\n    \"\"\"\n        Maps a value x from a-b to c-d.\n    \"\"\"\n    return (x - a) / (b - a) * (d - c) + c", "meta": {"hexsha": "e17a1819d59e78cc88beda39e7be6c4c4fc04b30", "size": 1325, "ext": "py", "lang": "Python", "max_stars_repo_path": "sim_assets/ext.py", "max_stars_repo_name": "AvanaPY/SimSims", "max_stars_repo_head_hexsha": "6f74ed93f642a4238f98969a3f34ea8bccd83a87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sim_assets/ext.py", "max_issues_repo_name": "AvanaPY/SimSims", "max_issues_repo_head_hexsha": "6f74ed93f642a4238f98969a3f34ea8bccd83a87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sim_assets/ext.py", "max_forks_repo_name": "AvanaPY/SimSims", "max_forks_repo_head_hexsha": "6f74ed93f642a4238f98969a3f34ea8bccd83a87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4444444444, "max_line_length": 95, "alphanum_fraction": 0.5909433962, "include": true, "reason": "import numpy", "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290905469752, "lm_q2_score": 0.885631484383387, "lm_q1q2_score": 0.8600624979890062}}
{"text": "import numpy as np\nimport math\n\ndef factorial(n):\n\tfact = 1\n\tfor i in range(1,n+1):\n\t\tfact *= i\n\treturn fact\n\n\nsummation = 1\nfor i in range(1,7):\n\tval = (-1)**i * (math.pi/3)**(2*i) / factorial(2*i)\n\tsummation += val\n\tprint \"val: \", val\n\tprint \"summation: \", summation\n\nprint \"Final summation: \", summation", "meta": {"hexsha": "fac9c750399ab9234fed559dd4099ba95aa7ee3b", "size": 306, "ext": "py", "lang": "Python", "max_stars_repo_path": "class_hw/cos_taylor_pi_by_4.py", "max_stars_repo_name": "sowmyamanojna/BT2020-Numerical-methods-in-Biology", "max_stars_repo_head_hexsha": "7d4b25cba624e7b657357010f23e721f127ea635", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "class_hw/cos_taylor_pi_by_4.py", "max_issues_repo_name": "sowmyamanojna/BT2020-Numerical-methods-in-Biology", "max_issues_repo_head_hexsha": "7d4b25cba624e7b657357010f23e721f127ea635", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "class_hw/cos_taylor_pi_by_4.py", "max_forks_repo_name": "sowmyamanojna/BT2020-Numerical-methods-in-Biology", "max_forks_repo_head_hexsha": "7d4b25cba624e7b657357010f23e721f127ea635", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0, "max_line_length": 52, "alphanum_fraction": 0.6339869281, "include": true, "reason": "import numpy", "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290930537121, "lm_q2_score": 0.8856314738181875, "lm_q1q2_score": 0.8600624899488788}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport pandas as pd\n\ndef entangled_two_circles(number_of_points_per_class, plot = True):\n    '''\n    Creates the dataset of two circles in R^3, a blue and a red one, each inside of the other.\n    Inputs: number of points in each class of the dataset, if plot is true, shows the dataset in R^3\n    Outputs: (dataset in 3 coordinates, labels of the dataset)\n    '''\n    theta = np.linspace(0,2*np.pi,number_of_points_per_class)\n    x_1 = np.cos(theta)\n    y_1 = np.sin(theta)\n    z_1 = np.zeros(len(theta))\n\n    x_2 = np.zeros(len(theta))\n    y_2 = np.cos(theta)+np.ones(len(theta))\n    z_2 = np.sin(theta)\n\n    x = np.concatenate((x_1, x_2))\n    y = np.concatenate((y_1, y_2))\n    z = np.concatenate((z_1, z_2))\n\n    target = np.concatenate((np.zeros(len(x_1)), np.ones(len(x_2))))\n\n    x = np.reshape(x,(-1,1))\n    y = np.reshape(y,(-1,1))\n    z = np.reshape(z,(-1,1))\n    data = np.concatenate((x,y,z), axis = 1)\n\n    if plot == True:\n        fig = plt.figure()\n        ax = Axes3D(fig)\n\n        scatter = ax.scatter(x_1,y_1,z_1, c= 'r')\n        scatter = ax.scatter(x_2,y_2,z_2, c= 'b')\n        plt.show()\n    \n    return (data, target)\n\ndef entangled_four_circles(number_of_points_per_class, plot = True):\n    '''\n    Creates the dataset of four circles in R^3, two blue and two larger red one, each entangled inside the other.\n    Inputs: 4*(number of points) in each class of the dataset, if plot is true, shows the dataset in R^3\n    Outputs: (dataset in 3 coordinates, labels of the dataset)\n    '''\n    theta = np.linspace(0,2*np.pi,number_of_points_per_class)\n    \n    x_r1 = 1/2*np.cos(theta)\n    y_r1 = 1/2*np.sin(theta)+np.ones(len(theta))\n    z_r1 = np.zeros(len(theta))\n\n    x_r2 = 1/2*np.cos(theta)\n    y_r2 = 1/2*np.sin(theta)-np.ones(len(theta))\n    z_r2 = np.zeros(len(theta))\n\n    x_r = np.concatenate((x_r1, x_r2))\n    y_r = np.concatenate((y_r1, y_r2))\n    z_r = np.concatenate((z_r1, z_r2))\n\n    x_b1 = 1/3*np.ones(len(theta))\n    y_b1 = np.cos(theta)\n    z_b1 = np.sin(theta)\n\n    x_b2 = -1/3*np.ones(len(theta))\n    y_b2 = np.cos(theta)\n    z_b2 = np.sin(theta)\n\n    x_b = np.concatenate((x_b1, x_b2))\n    y_b = np.concatenate((y_b1, y_b2))\n    z_b = np.concatenate((z_b1, z_b2))\n    \n    x = np.concatenate((x_r, x_b))\n    y = np.concatenate((y_r, y_b))\n    z = np.concatenate((z_r, z_b))\n    \n    target = np.concatenate((np.zeros(len(x_r)), np.ones(len(x_b))))\n\n    x = np.reshape(x,(-1,1))\n    y = np.reshape(y,(-1,1))\n    z = np.reshape(z,(-1,1))\n    data = np.concatenate((x,y,z), axis = 1)\n    \n    if plot == True:\n        fig = plt.figure()\n        ax = Axes3D(fig)\n\n        scatter = ax.scatter(x_r,y_r,z_r, c= 'r',  alpha = 0.5)\n        scatter = ax.scatter(x_b,y_b,z_b, c= 'b')\n        \n    return (data, target)\n\ndef circle_inside_torus(number_of_points_per_class, plot = True):\n    '''\n    Creates a dataset of a circle of radius 2 inside a torus of inner radius 1 and outter radius 3 of number_of_points_per_class\n    in each of these manifolds. If plot = True, it plots both the surface and the scatter plot for the torus sampled data\n    Inputs: number_of_points_per_class; plot = True\n    '''\n    theta_circle = np.linspace(0,2*np.pi,number_of_points_per_class) \n    x_circle = 2*np.cos(theta_circle)\n    y_circle = 2*np.sin(theta_circle)\n    z_circle = np.zeros(len(theta_circle))\n    x_circle = np.reshape(x_circle,(-1,1))\n    y_circle = np.reshape(y_circle,(-1,1))\n    z_circle = np.reshape(z_circle,(-1,1))\n    data_circle = np.concatenate((x_circle,y_circle,z_circle), axis = 1)\n    \n    theta_torus = 2*np.pi*np.random.rand(round(number_of_points_per_class**1/2)) #takes the square root so that each class has the same\n    #number of instances\n    phi_torus = 2*np.pi*np.random.rand(round(number_of_points_per_class**1/2))\n    c, a = 2, 1\n    x_torus = (c + a*np.cos(theta_torus)) * np.cos(phi_torus)\n    y_torus = (c + a*np.cos(theta_torus)) * np.sin(phi_torus)\n    z_torus = a * np.sin(theta_torus)\n    x_torus = np.reshape(x_torus,(-1,1))\n    y_torus = np.reshape(y_torus,(-1,1))\n    z_torus = np.reshape(z_torus,(-1,1))\n    data_torus = np.concatenate((x_torus,y_torus,z_torus), axis = 1)\n    \n    \n    data =  np.concatenate((data_circle, data_torus), axis = 0)\n    target = np.concatenate((np.zeros(number_of_points_per_class),np.ones(len(data_torus))), axis = 0)\n\n    if plot == True:\n        n = 100 #we will make 100 points so to make the surface plot visible\n        theta_plot = np.linspace(0,2*np.pi,n)\n        phi_plot = np.linspace(0, 2*np.pi, n)\n        theta_plot, phi_plot = np.meshgrid(theta_plot, phi_plot)\n        c, a = 2, 1\n        x_torus_plot = (c + a*np.cos(theta_plot)) * np.cos(phi_plot)\n        y_torus_plot = (c + a*np.cos(theta_plot)) * np.sin(phi_plot)\n        z_torus_plot = a * np.sin(theta_plot)\n        \n        fig = plt.figure(figsize = [10,10])\n        ax = fig.add_subplot(1, 2, 1, projection='3d')\n        ax.scatter(x_circle,y_circle,z_circle, c= 'r',alpha=1)\n        ax.plot_surface(x_torus_plot, y_torus_plot, z_torus_plot,\n                                  color='b', alpha =0.4, rstride=5, cstride=5, edgecolors='w')\n        ax.set_zlim(-3,3)\n\n        ax = fig.add_subplot(1, 2, 2, projection='3d')\n        ax.scatter(x_circle,y_circle,z_circle, c= 'r',alpha=1)\n        ax.scatter(x_torus, y_torus, z_torus,\n                                  color='b', alpha =0.4)\n        ax.set_zlim(-3,3)\n\n    return (data, target)\n\ndef swiss_roll(number_of_points_per_class, plot = True):\n    '''\n    Creates a dataset of a swiss roll of number_of_class points of half of its is in class red and half in class blue. \n    If plot = True, it plots both the scatter plot for the sampled data\n    Inputs: number_of_points_per_class; plot = True\n    '''\n    #makes the cross section of the swiss roll (ie. spiral)\n    theta_blue = np.linspace(0, 5*np.pi, round(number_of_points_per_class/10))\n    theta_red = np.linspace(5*np.pi, 10*np.pi, round(number_of_points_per_class/10))\n    \n    x_blue =  theta_blue*np.cos(theta_blue)\n    y_blue =  theta_blue*np.sin(theta_blue)\n    z_blue = np.zeros(len(x_blue))\n\n    x_red =  theta_red*np.cos(theta_red)\n    y_red =  theta_red*np.sin(theta_red)\n    z_red = np.zeros(len(x_red))\n    \n    #reshape arrays\n    x_blue = np.reshape(x_blue,(-1,1))\n    y_blue = np.reshape(y_blue,(-1,1))\n    z_blue = np.reshape(z_blue,(-1,1))\n    \n    x_red = np.reshape(x_red,(-1,1))\n    y_red = np.reshape(y_red,(-1,1))\n    z_red = np.reshape(z_red,(-1,1))\n\n    \n    blue_coord = np.concatenate((x_blue, y_blue, z_blue), axis = 1)\n    red_coord = np.concatenate((x_red, y_red, z_red), axis = 1)\n    \n    #lifts the spiral to the swiss roll by making 9 extra layers of points\n    for i in range(1, 10):\n        z_new = i*np.ones(len(x_blue))\n        z_new = np.reshape(z_new, (-1,1))\n        \n        new_blue_cord = np.concatenate((x_blue, y_blue, z_new), axis = 1)\n        new_red_cord = np.concatenate((x_red, y_red, z_new), axis = 1)\n        \n        blue_coord = np.concatenate((blue_coord, new_blue_cord), axis = 0)\n        red_coord = np.concatenate((red_coord, new_red_cord), axis = 0)\n      \n    #makes dataset and target\n    data = np.concatenate((red_coord, blue_coord), axis = 0)\n    \n    target_red = np.zeros(len(red_coord))\n    target_blue = np.ones(len(blue_coord))\n    target = np.concatenate((target_red, target_blue), axis = 0)\n    if plot == True:\n        fig = plt.figure()\n        ax = Axes3D(fig)\n\n        scatter = ax.scatter(blue_coord[:,0],blue_coord[:,1],blue_coord[:,2], c = 'b')\n        scatter = ax.scatter(red_coord[:,0],red_coord[:,1],red_coord[:,2], c = 'r')\n        plt.show()\n    \n    \n    return (data, target)", "meta": {"hexsha": "415f7549156c1f7ebe578facd6a1c7417c8db1fe", "size": 7753, "ext": "py", "lang": "Python", "max_stars_repo_path": "datasets.py", "max_stars_repo_name": "HLovisiEnnes/NetVisu", "max_stars_repo_head_hexsha": "d240c028e646e9f35e2c39cf7389f0c9155b39fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "datasets.py", "max_issues_repo_name": "HLovisiEnnes/NetVisu", "max_issues_repo_head_hexsha": "d240c028e646e9f35e2c39cf7389f0c9155b39fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "datasets.py", "max_forks_repo_name": "HLovisiEnnes/NetVisu", "max_forks_repo_head_hexsha": "d240c028e646e9f35e2c39cf7389f0c9155b39fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2740384615, "max_line_length": 135, "alphanum_fraction": 0.626854121, "include": true, "reason": "import numpy", "num_tokens": 2328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214491222695, "lm_q2_score": 0.8918110569397306, "lm_q1q2_score": 0.8599925307713838}}
{"text": "import numpy as np\n\n\nclass LogisticRegression:\n    def __init__(self, alpha=0.01, iteration=1500, intercept=True):\n        self.alpha=alpha\n        self.iteration=iteration\n        self.intercept=intercept\n        \n        \n\n    def sigmoid(self,x):\n        return 1 / (1+np.exp(-x))\n\n    def fit(self, x, y):\n        self.m = len(x)\n        self.n = np.size(x,1)\n        if self.intercept :\n            x = np.hstack((np.ones((len(x),1)), x))\n\n        self.theta=np.zeros(x.shape[1])\n                 \n        for _ in range(self.iteration):\n            self.z=np.dot(x, self.theta)\n            self.h=self.sigmoid(self.z)\n            grad=np.dot(x.T, (self.h-y)) / y.size\n            self.theta = self.alpha * grad\n\n         \n\n    def loss(self, y):\n        return ((-y*np.log(self.h))- ((1-y)*np.log(1-self.h))/self.m)\n\n    def predict_prob(self, x):\n        if self.intercept :\n            x = np.hstack((np.ones((len(x),1)), x))\n        return self.sigmoid(np.dot(x, self.theta))  \n\n    def predict(self, x, threshold=0.5):\n        return self.predict_prob(x)>= threshold\n\n\n\n\n", "meta": {"hexsha": "93e43f6f124b6155c618e94a874d2d3a8e96633c", "size": 1081, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/logistic.py", "max_stars_repo_name": "nilavya2000/pyflow", "max_stars_repo_head_hexsha": "4e48ac82e8489d216cd0c04ded2888e713f6ca42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-31T09:50:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-02T20:40:21.000Z", "max_issues_repo_path": "model/logistic.py", "max_issues_repo_name": "nilavya2000/pyflow", "max_issues_repo_head_hexsha": "4e48ac82e8489d216cd0c04ded2888e713f6ca42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-02T20:37:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-02T20:37:05.000Z", "max_forks_repo_path": "model/logistic.py", "max_forks_repo_name": "nilavya2000/monster", "max_forks_repo_head_hexsha": "4e48ac82e8489d216cd0c04ded2888e713f6ca42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0222222222, "max_line_length": 69, "alphanum_fraction": 0.5263644773, "include": true, "reason": "import numpy", "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214470715363, "lm_q2_score": 0.8918110504699678, "lm_q1q2_score": 0.8599925227035863}}
{"text": "# coding=utf-8\r\n\"\"\"Hermite and Bezier curves using python, numpy and matplotlib\"\"\"\r\n\r\nimport numpy as np\r\n#import matplotlib.pyplot as plt\r\n#from mpl_toolkits.mplot3d import Axes3D\r\n\r\n__author__ = \"Daniel Calderon\"\r\n__license__ = \"MIT\"\r\n\r\n\r\ndef generateT(t):\r\n    return np.array([[1, t, t**2, t**3]]).T\r\n\r\n\r\ndef hermiteMatrix(P1, P2, T1, T2):\r\n    \r\n    # Generate a matrix concatenating the columns\r\n    G = np.concatenate((P1, P2, T1, T2), axis=1)\r\n    \r\n    # Hermite base matrix is a constant\r\n    Mh = np.array([[1, 0, -3, 2], [0, 0, 3, -2], [0, 1, -2, 1], [0, 0, -1, 1]])    \r\n    \r\n    return np.matmul(G, Mh)\r\n\r\n\r\ndef bezierMatrix(P0, P1, P2, P3):\r\n    \r\n    # Generate a matrix concatenating the columns\r\n    G = np.concatenate((P0, P1, P2, P3), axis=1)\r\n\r\n    # Bezier base matrix is a constant\r\n    Mb = np.array([[1, -3, 3, -1], [0, 3, -6, 3], [0, 0, 3, -3], [0, 0, 0, 1]])\r\n    \r\n    return np.matmul(G, Mb)\r\n\r\n\r\ndef catmullRomMatrix(P0, P1, P2, P3):\r\n    # Generate a matrix concatenating the columns\r\n    G = np.concatenate((P0, P1, P2, P3), axis=1)\r\n\r\n    # Camull-Rom base matrix is a constant\r\n    Mcr = 1/2*np.array([[0, -1, 2, -1], [2, 0, -5, 3], [0, 1, 4, -3], [0, 0, -1, 1]])\r\n\r\n    return np.matmul(G, Mcr)    \r\n\r\n\r\ndef plotCurve(ax, curve, label, color=(0,0,1)):\r\n\r\n    xs = curve[:, 0]\r\n    ys = curve[:, 1]\r\n    zs = curve[:, 2]\r\n\r\n    ax.plot(xs, ys, zs, label=label, color=color)\r\n\r\n\r\n# M is the cubic curve matrix, N is the number of samples between 0 and 1\r\ndef evalCurve(M, N):\r\n    # The parameter t should move between 0 and 1\r\n    ts = np.linspace(0.0, 1.0, N)\r\n\r\n    # The computed value in R3 for each sample will be stored here\r\n    curve = np.ndarray(shape=(N, 3), dtype=float)\r\n\r\n    for i in range(len(ts)):\r\n        T = generateT(ts[i])\r\n        curve[i, 0:3] = np.matmul(M, T).T\r\n\r\n    return curve\r\n\r\ndef evalCurveTime(M, t):\r\n    T = generateT(t)\r\n    curve_point = np.matmul(M, T)\r\n    return curve_point\r\n\r\n\r\ndef matricesCRCurve(points):\r\n    control_points = [points[0], points[len(points)-1]]\r\n    matrices = []\r\n\r\n    for i in range(len(points)-3):\r\n        Mcr = catmullRomMatrix(points[i], points[i+1], points[i+2], points[i+3])\r\n        matrices += [Mcr]\r\n    return matrices\r\n\r\n\r\ndef evalCRCurveTime(t, matrices, times):\r\n    N_curves = len(matrices)\r\n    curve_point = evalCurveTime(matrices[0], t)\r\n\r\n    for i in range(N_curves):\r\n        if times[i] <= t <= times[i+1]:\r\n            normalized_t = (t-times[i]) / (times[i+1]-times[i])\r\n            curve_point = evalCurveTime(matrices[i], normalized_t)\r\n\r\n    return curve_point\r\n\r\nif __name__ == \"__main__\":\r\n\r\n    # Number of samples to plot\r\n    N = 500\r\n\r\n    # Setting up the matplotlib display for 3D\r\n    fig = plt.figure()\r\n    ax = fig.gca(projection='3d')\r\n\r\n    \"\"\"\r\n    Example for Catmull-Rom curve\r\n    \"\"\"\r\n\r\n    P0 = np.array([[-0.3, -0.25, 1]]).T*25\r\n    P1 = np.array([[-0.5, 0.25, 1.15]]).T*25\r\n    P2 = np.array([[-0.15, 0.15, 1]]).T*25\r\n    P3 = np.array([[0, 0.5, 0.75]]).T*25\r\n    P4 = np.array([[0.15, 0.15, 1]]).T*25\r\n    P5 = np.array([[0.4, 0.25, 1.15]]).T*25\r\n    P6 = np.array([[0.15, -0.15, 1]]).T*25\r\n    P7 = np.array([[0.4, -0.5, 0.75]]).T*25\r\n    P8 = np.array([[0, -0.25, 1]]).T*25\r\n    P9 = np.array([[-0.4, -0.5, 1.15]]).T*25\r\n    P10 = np.array([[-0.25, -0.15, 1]]).T*25\r\n    P11 = np.array([[-0.5, 0.25, 1.15]]).T*25\r\n    P12 = np.array([[-0.15, 0.25, 1]]).T*25\r\n\r\n    \r\n    points = [P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12]\r\n    times = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\r\n    matrices = matricesCRCurve(points)\r\n\r\n    catmullRomCurve = np.ndarray(shape=(N, 3), dtype=float)\r\n    ts = np.linspace(0.0, len(times)-1, N)\r\n\r\n    for i in range(N):\r\n        catmullRomCurve[i, 0:3] = evalCRCurveTime(ts[i], matrices, times).T\r\n        #if 0<= ts[i] <= 1:\r\n        #    T = generateT(ts[i])\r\n        #    catmullRomCurve[i, 0:3] = np.matmul(matrices[0], T).T\r\n\r\n        #elif 1 <= ts[i] <= 2:\r\n        #    T = generateT(ts[i]-1)\r\n        #    catmullRomCurve[i, 0:3] = np.matmul(matrices[1], T).T\r\n        \r\n        #elif 2 <= ts[i] <= 3:\r\n        #    T = generateT(ts[i]-2)\r\n        #    catmullRomCurve[i, 0:3] = np.matmul(matrices[2], T).T\r\n\r\n        #elif 3 <= ts[i] <= 4:\r\n        #    T = generateT(ts[i]-3)\r\n        #    catmullRomCurve[i, 0:3] = np.matmul(matrices[3], T).T\r\n\r\n    plotCurve(ax, catmullRomCurve, \"Catmull-Rom curve\")\r\n\r\n    ax.set_xlabel('x')\r\n    ax.set_ylabel('y')\r\n    ax.set_zlabel('z')\r\n    ax.legend()\r\n    \r\n    plt.show()", "meta": {"hexsha": "40e863117d2c6440d2d53ee0d4859cd4238d4cc3", "size": 4513, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tareas/Tarea_2/grafica/ex_curves.py", "max_stars_repo_name": "ElTapia/computacion-grafica", "max_stars_repo_head_hexsha": "8d6ec5e1bd2426093f253da9a197a7b74bb656a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tareas/Tarea_2/grafica/ex_curves.py", "max_issues_repo_name": "ElTapia/computacion-grafica", "max_issues_repo_head_hexsha": "8d6ec5e1bd2426093f253da9a197a7b74bb656a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tareas/Tarea_2/grafica/ex_curves.py", "max_forks_repo_name": "ElTapia/computacion-grafica", "max_forks_repo_head_hexsha": "8d6ec5e1bd2426093f253da9a197a7b74bb656a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5632911392, "max_line_length": 86, "alphanum_fraction": 0.5340128518, "include": true, "reason": "import numpy", "num_tokens": 1653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214470715363, "lm_q2_score": 0.8918110468756548, "lm_q1q2_score": 0.8599925192375132}}
{"text": "import numpy as np\n\ndef gaussian2d(shape=(3,3),sigma=0.5):\n    \"\"\"\n    2D gaussian mask - should give the same result as MATLAB's\n    fspecial('gaussian',[shape],[sigma])\n    \"\"\"\n    m,n = [(ss-1.)/2. for ss in shape]\n    y,x = np.ogrid[-m:m+1,-n:n+1]\n    h = np.exp( -(x*x + y*y) / (2.*sigma*sigma) )\n    h[ h < np.finfo(h.dtype).eps*h.max() ] = 0\n    sumh = h.sum()\n    if sumh != 0:\n        h /= sumh\n    return h\n", "meta": {"hexsha": "e6a7ee4552b412d29fa8e5fa7625c97fa4d77385", "size": 417, "ext": "py", "lang": "Python", "max_stars_repo_path": "gaussian2d.py", "max_stars_repo_name": "lesseradmin/raisr", "max_stars_repo_head_hexsha": "2f903351310638ebfd4503d49527b7bda1ce6463", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 546, "max_stars_repo_stars_event_min_datetime": "2017-06-10T13:34:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:25:37.000Z", "max_issues_repo_path": "gaussian2d.py", "max_issues_repo_name": "lesseradmin/raisr", "max_issues_repo_head_hexsha": "2f903351310638ebfd4503d49527b7bda1ce6463", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2017-09-05T13:26:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T12:40:42.000Z", "max_forks_repo_path": "gaussian2d.py", "max_forks_repo_name": "lesseradmin/raisr", "max_forks_repo_head_hexsha": "2f903351310638ebfd4503d49527b7bda1ce6463", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 172, "max_forks_repo_forks_event_min_datetime": "2017-06-15T02:17:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T09:09:25.000Z", "avg_line_length": 26.0625, "max_line_length": 62, "alphanum_fraction": 0.5227817746, "include": true, "reason": "import numpy", "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214450208032, "lm_q2_score": 0.8918110360927155, "lm_q1q2_score": 0.8599925070104271}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Discrete Fourier Transform (1D)\ndef DFT1D(f):\n  n = f.shape[0]\n  F = np.zeros(f.shape, dtype=np.complex64)\n  # For each frequency u=0..n-1\n  for u in np.arange(n):\n    # For each element of `f` x=0..n-1\n    for x in np.arange(n):\n      F[u] += f[x] * np.exp(-1j * (2 * np.pi) * (u * x) / n)\n  # Normalize the fourer\n  return F / np.sqrt(n)\n\n# Faster Discrete Fourier Transform (1D)\ndef fasterDFT1D(f):\n  n = f.shape[0]\n  F = np.zeros(f.shape, dtype=np.complex64)\n  x = np.arange(n)\n  # For each frequency u=0..n-1\n  for u in np.arange(n):\n    F[u] += f[x] * np.exp(-1j * (2 * np.pi) * (u * x) / n)\n  # Normalize the fourer\n  return F / np.sqrt(n)\n\n# Define a signal\nt = np.arange(0, 1, 0.005)\nf = 1 * np.sin(t * (2 * np.pi) * 2) + 0.6 * np.cos(t * (2 * np.pi) * 8) + \\\n    0.4 * np.cos(t * (2 * np.pi) * 16)\n\n# Computing DFT1D of `f`\nF = DFT1D(f)\n\nfq = np.arange(200)\nplt.figure(figsize=(10, 4))\n\n# Plot the magnitude of the DFT\nplt.plot(fq, np.abs(F), 'r')\nplt.savefig('dft_magnitude.png')\n\n# Due to the symmetric property of the sine and cosine functions (which are\n# similar in shape, but shifted), the Fourier Transform is also symmetric with\n# respect to its central coefficient. One interpretation is that both the\n# positive and negative frequency sinusoids are 90 degrees out of phase, but\n# the magnitude of their response will be the same. In other words, they both\n# respond to real signals in the same way.\n\n# Plot only part of the frequencies\nlimit = 32\n\nfq = np.arange(limit)\nplt.figure(figsize=(10, 4))\n\n# Plot the magnitude of the DFT\nplt.plot(fq, np.abs(F[:limit]), 'r')\nplt.savefig('dft_magnitude_limit.png')\n", "meta": {"hexsha": "c1d35752df73e469b906763929fb8e1fd3fccd7f", "size": 1681, "ext": "py", "lang": "Python", "max_stars_repo_path": "other-exercises/fourier/fourier1d.py", "max_stars_repo_name": "brenov/ip-usp", "max_stars_repo_head_hexsha": "06f9f16229a4587e38a3ae89fbe3394d5f1572fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "other-exercises/fourier/fourier1d.py", "max_issues_repo_name": "brenov/ip-usp", "max_issues_repo_head_hexsha": "06f9f16229a4587e38a3ae89fbe3394d5f1572fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "other-exercises/fourier/fourier1d.py", "max_forks_repo_name": "brenov/ip-usp", "max_forks_repo_head_hexsha": "06f9f16229a4587e38a3ae89fbe3394d5f1572fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9827586207, "max_line_length": 78, "alphanum_fraction": 0.6502082094, "include": true, "reason": "import numpy", "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241974031598, "lm_q2_score": 0.8872046026642944, "lm_q1q2_score": 0.8599888894099564}}
{"text": "#Import the Libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\n#%matplotlib inline\n\n\n#Function to genertae Loss Function (y)\ndef gen_y(a):\n    u=np.sin(a/10)*(5*(np.cos(a+10))-np.cos(a/2000))\n    return u+20*np.sin(a)\n\n#The derivative function\ndef der(a):\n    u=(np.sin(a/10)*((np.sin(a/2000)/2000)-5*np.sin(a/10)))\n    v=(np.cos(a/10)*(5*np.cos(a+10)- np.cos(a/200)))/10 \n    return u + v + (20*np.cos(a))\n\ndef Gradient_Descent(W,W_prev=0,eta=0.004,tol=0.004,epochs=1):\n    #Base Condition, from Equation 2\n    if(W-W_prev<tol):\n        print(f'Returning after {epochs} number of epochs')\n        return W\n    # We calculate the gradient value at W\n    g=der(W) \n    # We memorize the the W \n    W_prev=W\n    # We update the weight with the help of the previous one \n    # eta is the learning rate and tol is the tolerance\n    W=W_prev-eta*g \n    #Itertaive Process and we also count the number of epochs \n    return Gradient_Descent(W,W_prev,epochs=epochs+1)\n\n##################################  MAIN #######################################################\n\n#Generate loss Function\nx=np.linspace(15,25,500)\ny=gen_y(x)\n\n#Visulaize the plot\nfig,ax=plt.subplots(nrows=1,ncols=2,figsize=(14,8))\nax[0].plot(x,y,color='r',linewidth=3)\nax[0].set_xlabel('Weight',color='g',fontsize=20)\nax[0].set_ylabel('Loss',color='r',fontsize=20)\nax[0].set_title('Loss Function',fontsize=25,color='b')\n\n#Choose a random starting point and use the gradient descent function to reach the minima\nstart=15.25\nbest_weight=np.round(Gradient_Descent(start),2)\nprint(f'The optimal weight is {best_weight}')\n#To plot iterations \nx_plot=np.linspace(start+0.1,best_weight-0.3,152)\n\n##A Visual Plot of our excercise \nax[1].plot(x,y,color='r',linewidth=3)\nax[1].scatter(best_weight,gen_y(best_weight),linewidth=16,label='Optimal Wight',color='blue')\nax[1].scatter(start,gen_y(start),linewidth=16,label='Start',color='orange')\nax[1].scatter(x_plot,gen_y(x_plot),linewidth=16,label='Iteration',color='#FDDF00',alpha=0.3)\nax[1].set_xlabel('Weight',color='g',fontsize=20)\nax[1].set_ylabel('Loss',color='r',fontsize=20)\nax[1].set_title('Finding Minima with Gradient Descent',fontsize=25,color='b')\nax[1].legend(markerscale=0.2)\nplt.tight_layout()\n\n\n\n", "meta": {"hexsha": "6c33cf6e4dfdd237f4a941ab3a661d778b23ccc3", "size": 2222, "ext": "py", "lang": "Python", "max_stars_repo_path": "gradientDescent.py", "max_stars_repo_name": "aamir09/Machine-Learning-", "max_stars_repo_head_hexsha": "02de995643207b3d2c59e7169bb3239067b0fba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-28T07:16:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T07:16:01.000Z", "max_issues_repo_path": "gradientDescent.py", "max_issues_repo_name": "aamir09/Machine-Learning-", "max_issues_repo_head_hexsha": "02de995643207b3d2c59e7169bb3239067b0fba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gradientDescent.py", "max_forks_repo_name": "aamir09/Machine-Learning-", "max_forks_repo_head_hexsha": "02de995643207b3d2c59e7169bb3239067b0fba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6666666667, "max_line_length": 96, "alphanum_fraction": 0.6773177318, "include": true, "reason": "import numpy", "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242000616579, "lm_q2_score": 0.8872045907347108, "lm_q1q2_score": 0.8599888802049541}}
{"text": "import math\n\nimport numpy as np\nimport utils\n\n\ndef execute(data, max_iterations, clusters, epsilon):\n    # Number of features\n    features = len(data[0])\n    # Number of rows\n    rows = len(data)\n    # create the first membership matrix\n    u_matrix = []\n    # fuzzy constant\n    fc = 2.00\n\n    # create the membershipo metric using random numbers\n    for i in range(rows):\n        vals = np.random.rand(clusters)\n        s = sum(vals)\n        memb = [v / s for v in vals]\n        u_matrix.append(memb)\n\n    # iteration counter\n    iteration = 0\n    cntrs = []\n    old_cntrs = []\n\n    # Check if the number of iterations has reached the maximum or if the iterations have converged\n    while (iteration < max_iterations) and (check_iteration(old_cntrs, cntrs, epsilon)):\n        old_cntrs = cntrs\n        # calcualte the Centroids\n        cntrs = get_centroids(data, u_matrix, clusters, fc)\n        # calculate the membership matrix\n        u_matrix = calculate_membership_matrix(data, cntrs, u_matrix, fc)\n        iteration += 1\n\n    return u_matrix, cntrs\n\n\n# Check if the iterations have converged\ndef check_iteration(c1, c2, epsilon):\n    if not c1 or not c2:\n        return True\n    distances = [utils.distance(c1[i], c2[i]) for i in range(len(c1))]\n    return not (np.amax(distances) < epsilon)\n\n\ndef get_centroids(data, membership, clusters, fuzzy_constant):\n    centroids = []\n    # Separate the memberships by cluster number\n    mem = zip(*membership)\n\n    for i in range(clusters):\n        #  The cluster i memberships for every row\n        mm = mem[i]\n        # elevate every membership by the fuzzy constant\n        mm_prod = [u ** fuzzy_constant for u in mm]\n        denominator = sum(mm_prod)\n\n        numerator = []\n        # In every column calculate the ith centroid\n        for j in range(len(data[0])):\n            temp = []\n            for k in range(len(data)):\n                # uij**m * xi\n                temp.append(mm_prod[k] * data[k][j])\n            numerator.append(temp)\n\n        numerator = [sum(x) for x in numerator]\n        centroid = []\n        # Calculate the centroid\n        for n in numerator:\n            centroid.append(n / denominator)\n        centroids.append(centroid)\n\n    return centroids\n\n\n# Calculate a new membership function using the centroids\ndef calculate_membership_matrix(data, centroids, membership, fuzzy_constant):\n    u_matrix = membership\n    fc = 2 / (fuzzy_constant - 1)\n    for i in range(len(data)):\n        # Calculate the distance of the row with the centroids\n        distances = [utils.distance(data[i], centroids[k]) for k in range(len(centroids))]\n        for k in range(len(centroids)):\n            den = sum([math.pow(float(distances[k] / distances[c]), fc) for c in range(len(centroids))])\n            u_matrix[i][k] = float(1 / den)\n    return u_matrix\n\n\n# Calculate which cluster is the one with the highest membership for every row\ndef get_labels(rows, membership):\n    labels = []\n    for i in range(rows):\n        max_membership = -1\n        max_mem_index = -1\n        for j in range(len(membership[i])):\n            if membership[i][j] > max_membership:\n                max_membership = membership[i][j]\n                max_mem_index = j\n        labels.append(max_mem_index)\n    return labels\n\n", "meta": {"hexsha": "b1e0f73b29b0c1f0fcda2614c1550c7ef531bb62", "size": 3272, "ext": "py", "lang": "Python", "max_stars_repo_path": "fuzzyCmeans.py", "max_stars_repo_name": "felialois/iml_kmeans", "max_stars_repo_head_hexsha": "18bf7e81fd0815b77520a9e12bb7a00a275d681e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fuzzyCmeans.py", "max_issues_repo_name": "felialois/iml_kmeans", "max_issues_repo_head_hexsha": "18bf7e81fd0815b77520a9e12bb7a00a275d681e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fuzzyCmeans.py", "max_forks_repo_name": "felialois/iml_kmeans", "max_forks_repo_head_hexsha": "18bf7e81fd0815b77520a9e12bb7a00a275d681e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8679245283, "max_line_length": 104, "alphanum_fraction": 0.6243887531, "include": true, "reason": "import numpy", "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241965169939, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.8599888756146575}}
{"text": "# SETUP begin...\r\r\r\r# install necessary libraries first\r\r# if requirements not already satisfied\r\r    # pip install pyprimes\r\r    # pip install pycryptodome\r\r\r\r# import necessary modules \r\rimport random\r\rimport pyprimes\r\rimport warnings\r\rfrom Crypto.Hash import SHA3_256 # for hash\r\rimport os.path # for GenerateorRead\r\rimport string # for generating random string in fixed range\r\rimport sympy # check if the number is prime\r\rimport sys # for path \r\r\r\r# will be utilized in the implementation, taken from homeworks provided before\r\rdef egcd(a, b):\r\r    x,y, u,v = 0,1, 1,0\r\r    while a != 0:\r\r        q, r = b//a, b%a\r\r        m, n = x-u*q, y-v*q\r\r        b,a, x,y, u,v = a,r, u,v, m,n\r\r    gcd = b\r\r    return gcd, x, y\r\r\r\rdef modinv(a, m):\r\r    if a < 0:\r\r        a = a+m\r\r    gcd, x, y = egcd(a, m)\r\r    if gcd != 1:\r\r        return None  # modular inverse does not exist\r\r    else:\r\r      return x % m\r\r\r\rdef random_prime(bitsize):\r\r    warnings.simplefilter('ignore')\r\r    chck = False\r\r    while chck == False:\r\r        p = random.randrange(2**(bitsize-1), 2**bitsize-1)\r\r        chck = pyprimes.isprime(p)\r\r    warnings.simplefilter('default')    \r\r    return p\r\r\r\rdef large_DL_Prime(q, bitsize):\r\r    warnings.simplefilter('ignore')\r\r    chck = False\r\r    while chck == False:\r\r        k = random.randrange(2**(bitsize-1), 2**bitsize-1)\r\r        p = k*q+1\r\r        chck = pyprimes.isprime(p) and (p.bit_length() == 2048)\r\r    warnings.simplefilter('default')    \r\r    return p\r\r# will be utilized in the implementation, taken from homeworks provided before\r\r\r\r# generates public parameters q,p,g\r\r# generate random primes such that q|p-1 \r\r# algorithm for choosing the generator:\r\r  # choose a random alpha \r\r  # try a random alpha raised to the power ((p-1)) % q mod(p)\r\r  # if anything other than 1, it's the generator of Z*p with q elements\r\r\r\rdef Param_Generator(sizeq,sizep): # qsize = 224-bit, psize = 2048-bit\r\r  q = random_prime(sizeq)\r\r  diff = sizep - sizeq # determine the range for generation of p \r\r  p = large_DL_Prime(q, diff) # discrete log prime \r\r  hold = (p)//q\r\r  g = 1\r\r  while g == 1:\r\r      alpha1 = random.randrange(1, p)\r\r      g = pow(alpha1, hold, p)\r\r  return q, p, g\r\r\r\r# generate public and private keys for the users \r\r# generates private key -> secret k integer such that 0 < k < q-1 \r\r# computes public key by taking modulo p of g^k which is beta \r\r\r\rdef KeyGen(q,p,g): \r\r  alpha = random.randint(1,q-2) # private\r\r  beta = pow(g,alpha,p) # public \r\r  return alpha, beta\r\r\r\r# signature generation \r\r# signature = (s,r)\r\r  # hash function is 256-bit SHA \r\r    # take modulo q after hashing -> get h value \r\r  # select j (random integer) such that range = [1,q-2]\r\r  # compute r such that (g^j(mod(p))) mod(q) is r  -> signature part1\r\r  # compute s such that k*r - j*h (mod(q)) is s -> signature part2 (remember that k is the secret key)\r\r  # plaintext = m\r\r\r\rdef SignGen(m,q,p,g,alpha): \r\r  hashval = SHA3_256.new() # create new SHA object here\r\r  hashval.update(m) # hash here\r\r  hold = hashval.digest() \r\r  h = int.from_bytes(hold, byteorder='big') # conversion from bytes to integer\r\r  k = random.randint(1,q-2)\r\r  r = pow(g,k,p) % q  \r\r  s = ((alpha*r)-(k*h)) % q \r\r  return s,r # returning as a tuple or by comma is essentially the same thing post-function call\r\r\r\r# signature verification \r\r  # now (s,r) is the signature for m \r\r  # carry out the same procedure as above with SHA encryption\r\r  # take modulo inverse of h in modulo q and equate this to v\r\r  # compute z1 such that s*v mod(q) is z1\r\r  # compute z2 such that r*v mod(q) is z2\r\r  # finally, compute (((g^-z1)*(beta^z2)) mod(p)) mod(q) and equate this to u\r\r\r\r  # only verify the signature if u = r\r\r\r\r# Signature verification\r\rdef SignVer(m,s,r,q,p,g,beta):\r\r  hashval = SHA3_256.new() # create new SHA object here\r\r  hashval.update(m) # hash here\r\r  hold = hashval.digest()\r\r  h = int.from_bytes(hold, byteorder='big') % q # conversion from bytes to integer\r\r  v = modinv(h,q)\r\r  z1 = (s*v) % q\r\r  z2 = (r*v) % q\r\r  u = ((modinv(pow(g,z1,p),p)*pow(beta,z2,p)) % p) % q\r\r  if(u == r):\r\r    return 0\r\r  else:\r\r    return random.randint(1,42) # return an arbitrary value for failure\r\r\r# read the file\r\r# if exists, read public parameters from the file\r\r# else, create public parameters and write them to pubparams.txt\r\rdef GenerateOrRead(filename):\r\r    if os.path.isfile(filename) == True:   #if we can reach the file open it \r\r            file = open(filename, 'r+')\r    \r            if os.stat(filename).st_size == 0:      #if file is empty generate new parameters\r\r                q, p, g = Param_Generator(224, 2048)\r\r                file.write(str(q) + '\\n' + str(p) + '\\n' + str(g))  #write the new  parameters to file\r\r                file.close()\r\r                return int(q), int(p), int(g)\r\r\r            else:     #if file is not empty\r                \r                file = open(filename, 'r+')   #open the file\r\r                txt_info = file.readlines()  #read each line\r\r                j = 0\r\r                while(j != len(txt_info)):    #set each line to the parameters with respect to their order\r\r                    q = int(txt_info[j])\r\r                    p = int(txt_info[j+1])\r\r                    g = int(txt_info[j+2])\r\r                    return q, p, g\r\r                \r    else:       #if we can't reach the file open new files for reading and writing\r\r        file = open(filename,'w+')\r\r        q, p, g = Param_Generator(224, 2048)\r\r        file.write(str(q) + '\\n' + str(p) + '\\n' + str(g))  #write the new  parameters to file\r\r        file.close()\r\r        return int(q), int(p), int(g)\r    \r\r\r# return a random combination of lowercase letters, uppercase letters and digits\r\rdef random_string(str_size):\r\r    randomized = \"\".join(random.choices(string.ascii_lowercase + string.digits + string.ascii_uppercase, k = str_size))\r\r    return randomized\r\r\r\r# SETUP end...\r\r", "meta": {"hexsha": "3fee77ec7f9013d9bf224035485dcd02a01d30cc", "size": 5916, "ext": "py", "lang": "Python", "max_stars_repo_path": "Proof-of-Work-DSA/DS.py", "max_stars_repo_name": "kaanguney/Cryptography", "max_stars_repo_head_hexsha": "42e64f01aab7b3e6fd107bb1135d30839b567683", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Proof-of-Work-DSA/DS.py", "max_issues_repo_name": "kaanguney/Cryptography", "max_issues_repo_head_hexsha": "42e64f01aab7b3e6fd107bb1135d30839b567683", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Proof-of-Work-DSA/DS.py", "max_forks_repo_name": "kaanguney/Cryptography", "max_forks_repo_head_hexsha": "42e64f01aab7b3e6fd107bb1135d30839b567683", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 5916.0, "max_line_length": 5916, "alphanum_fraction": 0.6048005409, "include": true, "reason": "import sympy", "num_tokens": 1883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242009478238, "lm_q2_score": 0.8872045847699185, "lm_q1q2_score": 0.8599888752093471}}
{"text": "import numpy as np\nimport load_data as ld\nfrom evaluators import *\n\nclass LogisticRegression():\n    \"\"\"\n    Class for performing logistic regression.\n    \"\"\"\n    def __init__(self, learning_rate = 0.7, max_iter = 1000):\n        self.learning_rate = learning_rate\n        self.max_iter = max_iter\n        self.theta = []\n        self.no_examples = 0\n        self.no_features = 0\n        self.X = None\n        self.Y = None\n        \n    def add_bias_col(self, X):\n        bias_col = np.ones((X.shape[0], 1))\n        return np.concatenate([bias_col, X], axis=1)\n              \n    def hypothesis(self, X):\n        return 1 / (1 + np.exp(-1.0 * np.dot(X, self.theta)))\n\n    def cost_function(self):\n        \"\"\"\n        We will use the binary cross entropy as the cost function. https://en.wikipedia.org/wiki/Cross_entropy\n        \"\"\"\n        predicted_Y_values = self.hypothesis(self.X)\n        cost = (-1.0/self.no_examples) * np.sum(self.Y * np.log(predicted_Y_values) + (1 - self.Y) * (np.log(1-predicted_Y_values)))\n        return cost\n        \n    def gradient(self):\n        predicted_Y_values = self.hypothesis(self.X)\n        grad = (-1.0/self.no_examples) * np.dot((self.Y-predicted_Y_values), self.X)\n        return grad\n        \n    def gradient_descent(self):\n        for iter in range(1,self.max_iter):\n            cost = self.cost_function()\n            delta = self.gradient()\n            self.theta = self.theta - self.learning_rate * delta\n            print(\"iteration %s : cost %s \" % (iter, cost))\n        \n    def train(self, X, Y):\n        self.X = self.add_bias_col(X)\n        self.Y = Y\n        self.no_examples, self.no_features = np.shape(X)\n        self.theta = np.ones(self.no_features + 1)\n        self.gradient_descent()\n  \n    def classify(self, X):\n        X = self.add_bias_col(X)\n        predicted_Y = self.hypothesis(X)\n        predicted_Y_binary = np.round(predicted_Y)\n        return predicted_Y_binary\n\nto_bin_y = { 1: { 'Iris-setosa': 1, 'Iris-versicolor': 0, 'Iris-virginica': 0 },\n             2: { 'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 0 },\n             3: { 'Iris-setosa': 0, 'Iris-versicolor': 0, 'Iris-virginica': 1 }\n             }\n\nX_train, y_train, X_test, y_test = ld.iris()\n\nY_train = np.array([to_bin_y[3][x] for x in y_train])\nY_test = np.array([to_bin_y[3][x] for x in y_test])\n\nprint(\"training Logistic Regression Classifier\")\nlr = LogisticRegression()\nlr.train(X_train, Y_train)\nprint(\"trained\")\npredicted_Y_test = lr.classify(X_test)\nf1 = f1_score(predicted_Y_test, Y_test, 1)\nprint(\"F1-score on the test-set for class %s is: %s\" % (1, f1))\n\n# from sklearn.linear_model import LogisticRegression\n# logistic = LogisticRegression()\n# logistic.fit(X_train,Y_train)\n# predicted_Y_test = logistic.predict(X_test)\n# f1 = f1_score(predicted_Y_test, Y_test, 1)\n# print(\"F1-score on the test-set for class %s is: %s\" % (1, f1))\n", "meta": {"hexsha": "20d9b910bf3f43798f9c5a6d2176eb782f4240c2", "size": 2890, "ext": "py", "lang": "Python", "max_stars_repo_path": "siml/logistic_regression.py", "max_stars_repo_name": "hrokr/siml", "max_stars_repo_head_hexsha": "60e40d10f18412a127d0f599433d929d04c6ddce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 381, "max_stars_repo_stars_event_min_datetime": "2016-11-14T03:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:19:43.000Z", "max_issues_repo_path": "siml/logistic_regression.py", "max_issues_repo_name": "Xiaowang2020/siml", "max_issues_repo_head_hexsha": "2b14b14f221035890add3cdc9ae06787216b3ef5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2018-03-05T20:18:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-30T08:16:08.000Z", "max_forks_repo_path": "siml/logistic_regression.py", "max_forks_repo_name": "Xiaowang2020/siml", "max_forks_repo_head_hexsha": "2b14b14f221035890add3cdc9ae06787216b3ef5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 228, "max_forks_repo_forks_event_min_datetime": "2016-12-18T18:21:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T16:08:03.000Z", "avg_line_length": 35.243902439, "max_line_length": 132, "alphanum_fraction": 0.6173010381, "include": true, "reason": "import numpy", "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241982893259, "lm_q2_score": 0.8872045832787205, "lm_q1q2_score": 0.8599888714052613}}
{"text": "\"\"\"\nDescription: Numpy implementation of loss functions and their derivatives\nauthor: syedmohsinbukhari@googlemail.com\n\"\"\"\n\nimport numpy as np\n\n\nclass Losses:\n    def __init__(self):\n        self.target = None\n        self.achieved = None\n\n    def forward(self, target, achieved):\n        pass\n\n    def backward(self):\n        pass\n\n\nclass SSELoss(Losses):\n    def forward(self, target, achieved):\n        assert np.shape(target) == np.shape(achieved), 'Shape of target and achieved is not same'\n\n        self.target = target\n        self.achieved = achieved\n\n        sse_loss = np.multiply(np.power(np.subtract(self.target, self.achieved), 2), 0.5)\n        return sse_loss\n\n    def backward(self):\n        assert np.shape(self.target) == np.shape(self.achieved), \"Shape of target and achieved is not same\"\n        assert self.achieved is not None, \"Need to compute loss before computing gradient\"\n        assert self.target is not None, \"Need to compute loss before computing gradient\"\n\n        sse_grad = np.subtract(self.achieved, self.target)\n\n        return sse_grad\n", "meta": {"hexsha": "70bc50b550ae71077887db2e3844bd5c24082015", "size": 1072, "ext": "py", "lang": "Python", "max_stars_repo_path": "experiments/backprop_numpy/losses.py", "max_stars_repo_name": "syedmohsinbukhari/neat", "max_stars_repo_head_hexsha": "8dcbf792c7022fa8b6ba98290d50580c61adcd53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/backprop_numpy/losses.py", "max_issues_repo_name": "syedmohsinbukhari/neat", "max_issues_repo_head_hexsha": "8dcbf792c7022fa8b6ba98290d50580c61adcd53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-06-26T13:14:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-26T12:19:29.000Z", "max_forks_repo_path": "experiments/backprop_numpy/losses.py", "max_forks_repo_name": "the3eyes/neat", "max_forks_repo_head_hexsha": "8dcbf792c7022fa8b6ba98290d50580c61adcd53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4871794872, "max_line_length": 107, "alphanum_fraction": 0.6725746269, "include": true, "reason": "import numpy", "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.8933094110250333, "lm_q1q2_score": 0.8599649503196022}}
{"text": "import numpy as np\nfrom scipy.stats import norm\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Function to estimate point of intersection of normal curves of two classes, at the point of intersection diff\n# is zero or a point where the difference changes it sign\n\n\ndef intersection(f, g, x):\n    d = f - g\n    for i in range(len(d) - 1):\n        if d[i] == 0. or d[i] * d[i + 1] < 0.:\n            x_ = x[i]\n            return x_\n\n\ndef FisherLDA(ds, s):\n    row, col = ds.shape\n    ds_0 = ds[ds[col-1] == 0].iloc[:, 0:-1].values\n    ds_1 = ds[ds[col-1] == 1].iloc[:, 0:-1].values\n    m0 = np.mean(ds_0, axis=0)\n    m1 = np.mean(ds_1, axis=0)\n    SW_0 = np.cov(np.transpose(ds_0))\n    SW_1 = np.cov(np.transpose(ds_1))\n    SW = SW_0 + SW_1\n    SW_inv = np.linalg.inv(SW)\n    w = np.dot(SW_inv, (m1-m0))\n    wT = np.transpose(w)\n    y_0 = []\n    y_1 = []\n    for i in range(len(ds_0)):\n        y_0.append(np.dot(wT, ds_0[i, :]))\n    for i in range(len(ds_1)):\n        y_1.append(np.dot(wT, ds_1[i, :]))\n\n    fig1, ax1 = plt.subplots()\n    ax1.scatter(y_0, np.zeros(np.shape(y_0)), s=1,\n                color='r', label=\"Points in Class 0\")\n    ax1.scatter(y_1, np.zeros(np.shape(y_1)), s=1,\n                color='g', label=\"Points in Class 1\")\n    ax1.legend(loc='upper right')\n    plt.title(\"One Dimension transformation for dataset \"+str(s))\n\n    mu_0 = np.mean(y_0)\n    std_0 = np.std(y_0)\n    xmin, xmax = plt.xlim()\n    x = np.linspace(xmin, xmax, 10000)\n    p_0 = norm.pdf(x, mu_0, std_0)\n    fig2, ax2 = plt.subplots()\n    ax2.set_xlim([-15, 20])\n    ax2.set_ylim([0, 0.7])\n    ax2.plot(x, p_0, 'k', linewidth=2, color='red', label=\"Class 0\")\n    mu_1 = np.mean(y_1)\n    std_1 = np.std(y_1)\n    x = np.linspace(xmin, xmax, 10000)\n    p_1 = norm.pdf(x, mu_1, std_1)\n    ax2.plot(x, p_1, 'k', linewidth=2, color='green', label=\"Class 1\")\n    ax2.legend(loc='upper right')\n    intr = intersection(p_0, p_1, x)\n    misclass = 0\n    if mu_0 < intr:\n        for y in y_0:\n            if y > intr:\n                misclass = misclass+1\n        for y in y_1:\n            if y < intr:\n                misclass = misclass+1\n    else:\n        for y in y_0:\n            if y < intr:\n                misclass = misclass+1\n        for y in y_1:\n            if y > intr:\n                misclass = misclass+1\n    plt.title(\"Normal curve for dataset \"+str(s)+\"\\nThreshold is \"+str(intr))\n    print(\"Threshold values is\", intr)\n    print(\"Accuracy :\", 100-(misclass*100/row))\n    plt.show()\n\n\ndef main():\n    ds1 = pd.read_csv(\"./../../datasets/a1_d1.csv\", header=None)\n    ds2 = pd.read_csv(\"./../../datasets/a1_d2.csv\", header=None)\n    FisherLDA(ds1, 1)\n    FisherLDA(ds2, 2)\n\n\nmain()\n\n", "meta": {"hexsha": "418159ba3ee807e0e7204a5a594745d82211a948", "size": 2685, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Fischers_Discriminant/fisher_discr.py", "max_stars_repo_name": "RikilG/Machine-Learning", "max_stars_repo_head_hexsha": "d5726cdd49f59b1a49a5df5c87c9515722b5e9fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Fischers_Discriminant/fisher_discr.py", "max_issues_repo_name": "RikilG/Machine-Learning", "max_issues_repo_head_hexsha": "d5726cdd49f59b1a49a5df5c87c9515722b5e9fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Fischers_Discriminant/fisher_discr.py", "max_forks_repo_name": "RikilG/Machine-Learning", "max_forks_repo_head_hexsha": "d5726cdd49f59b1a49a5df5c87c9515722b5e9fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5054945055, "max_line_length": 111, "alphanum_fraction": 0.5590316574, "include": true, "reason": "import numpy,from scipy", "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.89330940889474, "lm_q1q2_score": 0.8599649492254752}}
{"text": "import sys\nif 'autograd.numpy' not in sys.modules:\n    import numpy as np\nfrom qubiter.BitVector import *\n\n\nclass HadamardTransform:\n    \"\"\"\n    This class contains only static methods and no constructor. Its\n    functions are related to the Hadamard Transform.\n\n    \"\"\"\n\n    @staticmethod\n    def ht(num_qbits, in_arr):\n        \"\"\"\n        This function calculates the Hadamard transform of in_arr. Let H be\n        the 2 dimensional Hadamard matrix and let ht be the num_bit-fold\n        tensor product of H. Then this function returns the matrix product\n        ht*in_arr = out_arr. in_arr and out_arr both have the same shape (\n        2^num_qbits,).\n\n        Parameters\n        ----------\n        num_qbits : int\n            The number of bits. The dimension of the Hadamard tranform is\n            2^num_qbits\n\n        in_arr : np.ndarray\n            Input array.\n\n        Returns\n        -------\n        np.ndarray\n\n        \"\"\"\n        length = (1 << num_qbits)\n        half_len = (length >> 1)\n        assert len(in_arr) == length, \\\n            \"in_arr for Hadamard Transform has wrong length\"\n        prev_arr = np.zeros(length, dtype=float)\n        root2 = np.sqrt(2)\n        out_arr = np.copy(in_arr)\n        for beta in range(num_qbits):\n            prev_arr[:] = out_arr[:]\n            for k in range(half_len):\n                x = prev_arr[2*k]\n                y = prev_arr[2*k+1]\n                out_arr[k] = (x + y)/root2\n                out_arr[half_len+k] = (x - y)/root2\n        return out_arr\n\n    @staticmethod\n    def hadamard_mat(num_qbits, is_quantum=True):\n        \"\"\"\n        This function return a numpy array with the num_qbits-fold tensor\n        product of the 2 dim Hadamard matrix H. If is_quantum=True (False,\n        resp.), it returns a complex (real, resp.) array.\n\n        Parameters\n        ----------\n        num_qbits : int\n        is_quantum : bool\n\n        Returns\n        -------\n\n        \"\"\"\n        num_rows = (1 << num_qbits)\n        norma = np.sqrt(num_rows)\n        if is_quantum:\n            ty = complex\n        else:\n            ty = float\n        mat = np.full((num_rows, num_rows),\n                      fill_value=1/norma, dtype=ty)\n        bvec = BitVector(num_qbits, 0)\n        for j in range(num_rows):\n            for k in range(num_rows):\n                bvec.dec_rep = j & k\n                if bvec.get_num_T_bits() % 2 == 1:\n                    mat[j, k] = - mat[j, k]\n        return mat\n\n\nif __name__ == \"__main__\":\n    def main():\n        num_qbits = 3\n        length = 1 << num_qbits\n        in_arr = np.random.rand(length) - 0.5\n        out_arr = HadamardTransform.ht(num_qbits, in_arr)\n        in_arr1 = HadamardTransform.ht(num_qbits, out_arr)\n        # print(\"in_arr=\", in_arr)\n        # print(\"out_arr=\", out_arr)\n        err = np.linalg.norm(in_arr-in_arr1)\n        print(\"error=\", err)\n\n        print(HadamardTransform.hadamard_mat(2))\n    main()\n", "meta": {"hexsha": "65b9346d7fe308a9eb0c61f7acab2af8a532b01d", "size": 2919, "ext": "py", "lang": "Python", "max_stars_repo_path": "qubiter/HadamardTransform.py", "max_stars_repo_name": "artiste-qb-net/qubiter", "max_stars_repo_head_hexsha": "af0340584d0b47d6b18d3dd28cd9b55a08cb507c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 129, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:50:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:53:03.000Z", "max_issues_repo_path": "qubiter/HadamardTransform.py", "max_issues_repo_name": "artiste-qb-net/qubiter", "max_issues_repo_head_hexsha": "af0340584d0b47d6b18d3dd28cd9b55a08cb507c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:38:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-02T19:40:27.000Z", "max_forks_repo_path": "qubiter/HadamardTransform.py", "max_forks_repo_name": "artiste-qb-net/qubiter", "max_forks_repo_head_hexsha": "af0340584d0b47d6b18d3dd28cd9b55a08cb507c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2016-03-28T07:48:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T14:49:28.000Z", "avg_line_length": 29.19, "max_line_length": 75, "alphanum_fraction": 0.5491606715, "include": true, "reason": "import numpy", "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.8933094032139577, "lm_q1q2_score": 0.8599649456700368}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import cm\n\nalpha, beta = 0.4, 0.5\ndef f(x1, x2):\n    return alpha * np.log(x1) + beta * np.log(x2)\n\np1, p2, m = 1.0, 1.2, 4\ndef budget_line(x1):\n    return (m - p1 * x1) / p2\n\nx1star = (alpha / (alpha + beta)) * (m / p1)\nx2star = budget_line(x1star)\nmaxval = f(x1star, x2star)\n\nxgrid = np.linspace(1e-2, 4, 50)\nygrid = xgrid\n\n# === plot value function === #\nfig, ax = plt.subplots(figsize=(8,6))\nx, y = np.meshgrid(xgrid, ygrid)\n\nif 1:\n    ax.plot(xgrid, budget_line(xgrid), 'k-', lw=2, alpha=0.8)\n    #ax.fill_between(xgrid, xgrid * 0.0, budget_line(xgrid), facecolor='blue', alpha=0.3)\n\nif 0:  # Annotate with text\n    ax.text(1, 1, r'$p_1 x_1 + p_2 x_2 < m$', fontsize=16)\n\n    ax.annotate(r'$p_1 x_1 + p_2 x_2 = m$', \n             xy=(2, budget_line(2)),  \n             xycoords='data',\n             xytext=(40, 40),\n             textcoords='offset points',\n             fontsize=16,\n             arrowprops=dict(arrowstyle=\"->\"))\n\nif 1:  # Add maximizer\n    ax.annotate(r'$(x_1^*, x_2^*)$', \n             xy=(x1star, x2star),  \n             xycoords='data',\n             xytext=(30, 30),\n             textcoords='offset points',\n             fontsize=16,\n             arrowprops=dict(arrowstyle=\"->\"))\n    ax.plot([x1star], [x2star],  'ro', alpha=0.6)\n\n\nif 1:  # Plot with contours\n    #points = [-10, -2, -1, 0, 0.4, 0.6, 0.8, 1.0, 1.2, 4]\n    points = [-10, -2, -1, 0, 0.6, 1.0, 1.2, 4]\n    ax.contourf(x, y, f(x, y), points, cmap=cm.jet, alpha=0.5)\n    cs = ax.contour(x, y, f(x, y), points, colors='k', linewidth=2, alpha=0.7,\n            antialias=True)\n    plt.clabel(cs, inline=1, fontsize=12)\n\nax.set_xlim(0, 4)\nax.set_ylim(0, 4)\nax.set_xticks((0.0, 1.0, 2.0, 3.0))\nax.set_yticks((1.0, 2.0, 3.0))\nax.set_xlabel(r'$x_1$', fontsize=16)\nax.set_ylabel(r'$x_2$', fontsize=16)\nplt.show()\n\n\n", "meta": {"hexsha": "8f94367de62d40f7ed53efde97edfcc0912a709e", "size": 1864, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/budget_set.py", "max_stars_repo_name": "abhishekchand23/econ-2125-8013", "max_stars_repo_head_hexsha": "94e509d6d62ddb7b20388a71144fea03ac37b9f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2015-02-18T01:15:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T10:23:01.000Z", "max_issues_repo_path": "code/budget_set.py", "max_issues_repo_name": "jstac/econ-2125-8013", "max_issues_repo_head_hexsha": "94e509d6d62ddb7b20388a71144fea03ac37b9f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/budget_set.py", "max_forks_repo_name": "jstac/econ-2125-8013", "max_forks_repo_head_hexsha": "94e509d6d62ddb7b20388a71144fea03ac37b9f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2015-02-08T01:22:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-18T10:23:03.000Z", "avg_line_length": 27.8208955224, "max_line_length": 89, "alphanum_fraction": 0.5574034335, "include": true, "reason": "import numpy", "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.8933094060543487, "lm_q1q2_score": 0.8599649455344578}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nMaking array of zeros without numpy: https://stackoverflow.com/questions/4056768/how-to-declare-array-of-zeros-in-python-or-an-array-of-a-certain-size\r\n\"\"\"\r\nfrom pylab import *\r\nfrom numpy import *\r\nimport scipy as sp\r\nimport time\r\n\r\nC = array([[4,12,-16],[12,37,-43],[-16,-43,98]]) # Test matrix from wikipedia page\r\nrandom.seed(20)\r\n\r\nn = 300\r\nE = random.rand(n,n)*random.random()\r\n#D = 0.5*(D+transpose(D))\r\nE = matmul(E,transpose(E)) # Generating random positive definite matrix\r\n\r\nprint('Randomly generated matrix E is',E)\r\n\r\ntest = linalg.cholesky(E)\r\n\r\ndef choleskymanual(A): \r\n#    L=[[0]]*len(A) # Numpy independent method\r\n#    for i in range(len(A)):\r\n#        L[i]=L[i]*len(A)\r\n    L = zeros((len(A),len(A)))\r\n    for i in range(len(A)):\r\n        for j in range(i+1):\r\n            lsum=0\r\n            for k in range(j):\r\n                lsum+=sum(L[i,k]*conj(L[j,k]))\r\n            if i>j:\r\n                L[i,j]=(1/L[j,j])*(A[i,j]-lsum)\r\n            else:\r\n                L[j,j]=sqrt(A[j,j]-lsum)\r\n    return L\r\n\r\ndef cmLDL(A): \r\n    L = zeros((len(A),len(A)))\r\n    D = zeros((len(A),len(A)))\r\n    for i in range(len(A)):\r\n        for j in range(i+1):\r\n            lsum=0\r\n            lsum2=0 # Require seperate sums as the calculations for elements of D and L use different elements from matrix L\r\n            for k in range(j):\r\n                lsum+=L[j,k]*conj(L[j,k])*D[k,k]\r\n                lsum2+=L[i,k]*conj(L[j,k])*D[k,k]\r\n            D[j,j]=A[j,j]-lsum\r\n#            if i>j:\r\n            L[i,j]=(1/D[j,j])*(A[i,j]-lsum2)\r\n    return L,D\r\n\r\n\r\nL=choleskymanual(E)\r\nLD,D=cmLDL(E)\r\n#print(L)\r\nLs=conj(transpose(L))\r\nLDs=conj(transpose(LD))\r\nAnew=matmul(L,Ls)\r\nADnew=matmul(LD,matmul(D,LDs))\r\n\r\nprint('L matrix from LL decomposition:',L)\r\nprint('L matrix from LDL decomposition:',LD)\r\nprint('Diagonal elements from D matrix from LDL decomposition:',diag(D))\r\n\r\n#%%\r\n\"\"\"\r\n1st Application: Matrix Inversion\r\n\"\"\"\r\nstart = time.time()\r\n# How to get inverse: [A]][Ainv]=[LL*][Ainv]=I\r\n# Print statements for troubleshooting\r\ndef cholinverse(A):\r\n    L=choleskymanual(A)\r\n    Ls=conj(transpose(L))\r\n    I = identity((len(L)))\r\n    U = zeros([len(A),len(A)])\r\n    Ainv = zeros([len(A),len(A)])\r\n    for i in range(len(U)):\r\n        for j in range(i+1):\r\n            if i==j:\r\n                U[i,i]=(I[i,i]/L[i,i])\r\n                Ainv[i,i]=(U[i,i]/Ls[i,i])\r\n#    print(U)\r\n#    print(Ainv)\r\n    for i in range(len(U)):\r\n#        print('i=',i)\r\n#        lsum=0\r\n        for j in range(i+1):\r\n#            print('j=',j)\r\n            lsum=0\r\n            for k in range(i):\r\n                lsum+=L[i,k]*U[k,j]\r\n#                print('k=',k)\r\n#                print(lsum)\r\n#            print(lsum)\r\n#            print(U)\r\n            if i>j:\r\n                U[i,j]=(-lsum)/L[i,i]\r\n    for i in range(len(U)-1,-1,-1):\r\n#        print('i=',i)\r\n#        lsum=0\r\n        for j in range(i,-len(U),-1):\r\n#            print('j=',j)\r\n            lsum=0\r\n            for k in range(i-1,-len(U),-1):\r\n                lsum+=Ls[i,k]*Ainv[k,j]\r\n#                print('k=',k)\r\n#                print(lsum)\r\n#            print(lsum)\r\n#            print(Ainv)\r\n#            if i>j:\r\n            Ainv[i,j]=(U[i,j]-lsum)/Ls[i,i]\r\n            Ainv[j,i]=(U[i,j]-lsum)/Ls[i,i]\r\n    return U,Ainv\r\n\r\nAI = linalg.inv(E)\r\nSA  = cholinverse(E)\r\nprint('The matrix inversion from numpy.linalg is')\r\nprint(AI)\r\nprint('The matrix inversion from manual method is')\r\nprint(SA[1])\r\n\r\nratioinv=AI/SA[1]\r\nratioinvf=array([])\r\nfor i in range(len(ratioinv)):\r\n    o=mean(ratioinv[i])\r\n    ratioinvf=append(ratioinvf,o)\r\n\r\nratioinvf=mean(ratioinvf)\r\n\r\nprint('The average ratio between the numpy and manual method at n =',n,' for matrix inversion is',ratioinvf)\r\n\r\n#%%\r\n\"\"\"\r\n2nd Application: Monte-Carlo Simulation - Corellating unrelated random variables\r\n\"\"\"\r\n\r\nranvar = random.normal(0,1,(n,100000)) # Generating n amount of variables for 2 variables from a gaussian distribution\r\n#ranvar[1]=ranvar[1]*10000\r\n#random.seed(40)\r\n#ranvar1 = random.normal(0,1,100000)\r\n#random.seed(60)\r\n#ranvar2 = random.normal(0,1,100000)*10000\r\n#ranvart=zeros(2,dtype=object)\r\n#ranvart[0],ranvart[1]=muarray,ranvar2\r\n#Imat = [[0.6,1],[1,0.4]]\r\n\r\n#covmat = matmul(transpose(C),C)\r\ncovmat = matmul(transpose(E),E)\r\n\r\nL = choleskymanual(covmat)\r\n\r\nxcorr = dot(L,ranvar)\r\n#xstd = sqrt(diag(covmat))\r\n\r\nplot(abs(xcorr[0]),abs(xcorr[n-2]),'.')\r\ngrid()\r\nxlabel('Correlated data set for variable x0')\r\nylabel('Correlated data set for variable x%s'%(n-2))\r\ntitle('Correlation between correlated variables x0 and x%s'%(n-2))\r\nfigure()\r\nplot(ranvar[0],ranvar[n-1],'.')\r\ngrid()\r\nxlabel('Uncorrelated data set for variable x0')\r\nylabel('Uncorrelated data set for variable x%s'%(n-2))   \r\ntitle('Correlation between uncorrelated variables x0 and x%s'%(n-2))\r\n#%%\r\n\"\"\"\r\n3rd Application: Least-Squares\r\n\r\nBecause I've already computed the inverse of the matrix via Cholesky, I can simply take Ax=b -> x=Ainvb to get the system of unknown variables x\r\n\"\"\"\r\n#B=[0,1,2] # Use for C matrix or other random 3x3 matrix\r\nB = random.rand(n,1)\r\n\r\nX = matmul(cholinverse(E)[1],B)\r\nprint('The linear equation for a solution')\r\nprint(B)\r\nprint('via matrix inversion from cholesky gives vector x =')\r\nprint(X)\r\n\r\n\"\"\"\r\nOr I  can use linalg.solve\r\n\"\"\"\r\nX = linalg.solve(E,B)\r\nprint('The linear equation for a solution')\r\nprint(B)\r\nprint('via linalg.solve from cholesky gives vector x =')\r\nprint(X)\r\n\r\n\r\n\"\"\"\r\nOr I can calculate it more explicitly.\r\n\r\nThis is a modification of the cholinverse function since they both use back/forward substitution\r\nAx=b -> A*Ax=A*b -> (LLs)x=A*b -> (L)u=A*b\r\n\"\"\"\r\n\r\ndef cholLS(A,b):\r\n    posdef = matmul(transpose(A),A)\r\n    newb=matmul(transpose(A),b)\r\n    L=choleskymanual(posdef)\r\n    Ls=conj(transpose(L))\r\n    U = zeros([len(b)])\r\n    X = zeros([len(b)])\r\n    for i in range(len(A)):\r\n        U[i]=(newb[i]-dot((L[i]),U))/L[i,i]\r\n    for i in range(len(A)-1,-1,-1):\r\n        X[i]=(U[i]-dot(Ls[i],X))/Ls[i,i]\r\n    return X\r\n\r\nprint('The linear equation for a solution')\r\nprint(B)\r\n\r\nY = cholLS(E,B)\r\n\r\nprint('via least squares linear regression from cholesky gives vector x =')\r\nprint(Y)\r\n\r\nratiols=transpose(X)/Y\r\nratiolsf=array([])\r\nfor i in range(len(ratiols)):\r\n    o=mean(ratiols[i])\r\n    ratiolsf=append(ratiolsf,o)\r\n\r\nratiolsf=mean(ratiolsf)\r\n\r\nprint('The average ratio between the numpy and manual method at n =',n,' for matrix inversion is',ratioinvf)\r\nprint('The average ratio between the numpy and manual method at n =',n,' for least squares is',ratiolsf)\r\n\r\nend = time.time()\r\nprint('Total time taken to run code = ',end - start)", "meta": {"hexsha": "1ba8d4b1fdfad9d537fd8b243d85dbb2397fca8d", "size": 6637, "ext": "py", "lang": "Python", "max_stars_repo_path": "cholesky.py", "max_stars_repo_name": "ErichEF/choleskycipher", "max_stars_repo_head_hexsha": "d6396fdf29a25885390c29a4a4a14674e5ac20d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cholesky.py", "max_issues_repo_name": "ErichEF/choleskycipher", "max_issues_repo_head_hexsha": "d6396fdf29a25885390c29a4a4a14674e5ac20d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cholesky.py", "max_forks_repo_name": "ErichEF/choleskycipher", "max_forks_repo_head_hexsha": "d6396fdf29a25885390c29a4a4a14674e5ac20d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4849785408, "max_line_length": 151, "alphanum_fraction": 0.5785746572, "include": true, "reason": "from numpy,import scipy", "num_tokens": 1974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.8933094032139577, "lm_q1q2_score": 0.8599649428000897}}
{"text": "import numpy as np\n\nif __name__ == \"__main__\":\n    # initializing matrices\n    x = np.array([[1, 2], [4, 5]])\n    y = np.array([[7, 8], [9, 10]])\n\n    # element wise addition\n    print(\"The element wise addition of matrix is : \")\n    print(np.add(x, y))\n\n    # element wise subtraction\n    print(\"The element wise subtraction of matrix is : \")\n    print(np.subtract(x, y))\n\n    # element wise division\n    print(\"The element wise division of matrix is : \")\n    print(np.divide(x, y))\n\n    # element wise multiplication\n    print(\"The element wise multiplication of matrix is : \")\n    print(np.multiply(x, y))\n\n    # matrix multiplication\n    print(\"Matrix multiplication is : \")\n    print(np.dot(x, y))\n\n    # matrix transpose\n    print(\"Matrix transpose is : \")\n    print(np.transpose(x))\n\n    # matrix inverse\n    print(\"Matrix inverse is : \")\n    print(np.linalg.inv(x))", "meta": {"hexsha": "f1e1a326fd8554623057ad4fd4af5dd13cc10c6b", "size": 873, "ext": "py", "lang": "Python", "max_stars_repo_path": "matrix_operations_numpy.py", "max_stars_repo_name": "njanirudh/LinearAlgebra", "max_stars_repo_head_hexsha": "fbedfc633551903e855193458e63456c4c873240", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matrix_operations_numpy.py", "max_issues_repo_name": "njanirudh/LinearAlgebra", "max_issues_repo_head_hexsha": "fbedfc633551903e855193458e63456c4c873240", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-23T04:26:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-23T04:26:16.000Z", "max_forks_repo_path": "matrix_operations_numpy.py", "max_forks_repo_name": "njanirudh/LinearAlgebra", "max_forks_repo_head_hexsha": "fbedfc633551903e855193458e63456c4c873240", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6764705882, "max_line_length": 60, "alphanum_fraction": 0.6231386025, "include": true, "reason": "import numpy", "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9763105231864132, "lm_q2_score": 0.8807970826714614, "lm_q1q2_score": 0.8599314606040409}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nx_data = [ 338., 333., 328., 207., 226., 25., 179., 60., 208.,  606. ]\ny_data = [ 640., 633., 619., 393., 428., 27., 193., 66., 226., 1591. ]\n# y_data = w * x_data + bias \n\nx = np.arange(-200, -100, 1) # bias\ny = np.arange(-5, 5, 0.1) # weight\nZ = np.zeros((len(x), len(y)))\nX, Y = np.meshgrid(x, y)\n\nfor i in range(len(x)):\n    for j in range((len(y))):\n        b = x[i]\n        w = y[j]\n        Z[j][i] = 0\n        for n in range(len(x_data)):\n           Z[j][i] = Z[j][i] +(y_data[n] - b - w*x_data[n])**2\n        Z[j][i] = Z[j][i]/len(x_data)\n        \nb = -129 # intialize b\nw = -4 # intialize w\nlr = 0.0000001 # learning rate\niteration = 100000\n\n# Store intial values for plotting\nb_history = [b]\nw_history = [w]\n\n# Iteration\nfor i in range(iteration):\n    b_grad = 0.0\n    w_grad = 0.0\n    for n in range(len(x_data)):\n        b_grad = b_grad - 2.0*(y_data[n] - b - w*x_data[n])*1.0\n        w_grad = w_grad - 2.0*(y_data[n] - b - w*x_data[n])*x_data[n]\n    \n    # Update parameters\n    b = b - lr * b_grad\n    w = w - lr * w_grad\n    \n    # Store the parameters for plotting\n    b_history.append(b)\n    w_history.append(w)\n\n# plot the figure\nplt.contour(x, y, Z, 50, alpha=0.5, cmap=plt.get_cmap('jet'))\nplt.plot([-188.4], [2.67], 'x', ms=12, markeredgewidth=3, color='orange')\nplt.plot(b_history, w_history, 'o-', ms=3, lw=1.5, color='black')\nplt.xlim(-200, -100)\nplt.ylim(-5,5)\nplt.xlabel(r'$b$', fontsize=16)\nplt.ylabel(r'$w$', fontsize=16)\nplt.show()\n\n## Change Learning_Rate to Learning_Rate*10\nb = -129 # intialize b\nw = -4 # intialize w\nlr = 0.000001 # learning rate\niteration = 100000\n\n# Store intial values for plotting\nb_history = [b]\nw_history = [w]\n\n# Iteration\nfor i in range(iteration):\n    b_grad = 0.0\n    w_grad = 0.0\n    for n in range(len(x_data)):\n        b_grad = b_grad - 2.0*(y_data[n] - b - w*x_data[n])*1.0\n        w_grad = w_grad - 2.0*(y_data[n] - b - w*x_data[n])*x_data[n]\n    \n    # Update parameters\n    b = b - lr * b_grad\n    w = w - lr * w_grad\n    \n    # Store the parameters for plotting\n    b_history.append(b)\n    w_history.append(w)\n\n# plot the figure\nplt.contour(x, y, Z, 50, alpha=0.5, cmap=plt.get_cmap('jet'))\nplt.plot([-188.4], [2.67], 'x', ms=12, markeredgewidth=3, color='orange')\nplt.plot(b_history, w_history, 'o-', ms=3, lw=1.5, color='black')\nplt.xlim(-200, -100)\nplt.ylim(-5,5)\nplt.xlabel(r'$b$', fontsize=16)\nplt.ylabel(r'$w$', fontsize=16)\nplt.show()\n\n## Change Learning_Rate to Learning_Rate*10\nb = -129 # intialize b\nw = -4 # intialize w\nlr = 0.00001 # learning rate\niteration = 100000\n\n# Store intial values for plotting\nb_history = [b]\nw_history = [w]\n\n# Iteration\nfor i in range(iteration):\n    b_grad = 0.0\n    w_grad = 0.0\n    for n in range(len(x_data)):\n        b_grad = b_grad - 2.0*(y_data[n] - b - w*x_data[n])*1.0\n        w_grad = w_grad - 2.0*(y_data[n] - b - w*x_data[n])*x_data[n]\n    \n    # Update parameters\n    b = b - lr * b_grad\n    w = w - lr * w_grad\n    \n    # Store the parameters for plotting\n    b_history.append(b)\n    w_history.append(w)\n\n# plot the figure\nplt.contour(x, y, Z, 50, alpha=0.5, cmap=plt.get_cmap('jet'))\nplt.plot([-188.4], [2.67], 'x', ms=12, markeredgewidth=3, color='orange')\nplt.plot(b_history, w_history, 'o-', ms=3, lw=1.5, color='black')\nplt.xlim(-200, -100)\nplt.ylim(-5,5)\nplt.xlabel(r'$b$', fontsize=16)\nplt.ylabel(r'$w$', fontsize=16)\nplt.show()\n\n    ## Using adagrad to solve the problem\n'''\nIf increasing the iteration to speed up the rate of convergence, that would spped down actually.\nCause it have to calculate gradient at each iteration, but that would cost lots of time.\nTherefore, we modify the learning rate, and change improve rate of convergence at meantime.\n'''\nb = -129\nw = -4\nlr = 1\niteration = 100000\n\nb_lr = 0.0\nw_lr = 0.0\n\n# Store initial values for plotting\nw_history = [w]\nb_history = [b]\n\n# Iteration\nfor i in range(iteration):\n    b_grad = 0.0\n    w_grad = 0.0\n    for n in range(len(x_data)):\n        b_grad = b_grad - 2.0*(y_data[n] - b - w*x_data[n])*1.0\n        w_grad = w_grad - 2.0*(y_data[n] - b - w*x_data[n])*x_data[n]\n    \n    # Add\n    b_lr = b_lr + b_grad ** 2\n    w_lr = w_lr + w_grad ** 2\n    \n    # Update parameters\n    b = b - lr /np.sqrt(b_lr) * b_grad\n    w = w - lr /np.sqrt(w_lr) * w_grad\n    \n    # Store the parameters for plotting\n    b_history.append(b)\n    w_history.append(w)\n\n# plot the figure\nplt.contour(x, y, Z, 50, alpha=0.5, cmap=plt.get_cmap('jet'))\nplt.plot([-188.4], [2.67], 'x', ms=12, markeredgewidth=3, color='orange')\nplt.plot(b_history, w_history, 'o-', ms=3, lw=1.5, color='black')\nplt.xlim(-200, -100)\nplt.ylim(-5,5)\nplt.xlabel(r'$b$', fontsize=16)\nplt.ylabel(r'$w$', fontsize=16)\nplt.show()", "meta": {"hexsha": "2521380b2f29db139cf0c0b42f69b6e934fb8c95", "size": 4720, "ext": "py", "lang": "Python", "max_stars_repo_path": "Demo/GD.py", "max_stars_repo_name": "the-Quert/iNLPfun", "max_stars_repo_head_hexsha": "89bcb8f2b8fe0025581fd5fe2cc24ff0c1b5cde2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-07-21T11:15:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:05:11.000Z", "max_issues_repo_path": "Demo/GD.py", "max_issues_repo_name": "the-Quert/iNLPfun", "max_issues_repo_head_hexsha": "89bcb8f2b8fe0025581fd5fe2cc24ff0c1b5cde2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Demo/GD.py", "max_forks_repo_name": "the-Quert/iNLPfun", "max_forks_repo_head_hexsha": "89bcb8f2b8fe0025581fd5fe2cc24ff0c1b5cde2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-21T11:15:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-17T23:02:56.000Z", "avg_line_length": 26.9714285714, "max_line_length": 96, "alphanum_fraction": 0.6069915254, "include": true, "reason": "import numpy", "num_tokens": 1658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122768904645, "lm_q2_score": 0.8976952825278492, "lm_q1q2_score": 0.8599133320400809}}
{"text": "import numpy as np\nimport scipy as sp\nfrom matplotlib import pyplot as plt\n\nimport shapes\n\n#Prob 1\n\ndef polarZ(z):\n\tif(z == 0):\n\t\treturn (0,0)\n\telse :\n\t\ta = z.real\n\t\tb = z.imag\n\t\treturn( sp.hypot(a,b), sp.arctan(b/a))\n\n\n#Prob 2\n\ndef fFunc(z):\n\treturn (3*z - 4)/(z-2)\n\t\ndef gFunc(z):\n\treturn z**2 - 2\ndef confMap(shape,mapfunc):\n\tshapemapped = [None]*len(shape)\n\tfor i in range(0,len(shape)):\n\t\tshapemapped[i] = mapfunc(shape[i])\n\t\n\tplt.scatter(sp.real(shape),sp.imag(shape),color='r')\n\tplt.scatter(sp.real(shapemapped),sp.imag(shapemapped),color='b')\n\tplt . show ()\n\n'''\nExamples:\n\ntriangle = shapes.genRTriangle(1.,1.,0.,0.,100)\nconfMap(triangle,fFunc)\n\nbox = shapes.genBox(1.,1.,0.,0.,400)\nconfMap(box,gFunc)\n\ncircle = shapes.genCircle(1.,1.,0.,0.,400)\nconfMap(circle,gFunc)\n'''\n\n#Prob 3\n\ndef testHolo(func,a,b,r,tol):\n\tcircle = shapes.genCircle(r,a,b,400)\n\tvals = func(circle)\n\tdiff = max(vals) - min(vals)\n\tif(diff < tol ):\n\t\treturn \"differentiable\"\n\telse:\n\t\treturn \"not differentiable {0}\".format(diff)\n#my solution apparently didn't work, it says that all the functions are not differentiable\n\nprint testHolo(lambda z: sp.real(z),1,1,0.01,1)\nprint testHolo(lambda z: sp.absolute(z),1,1,0.01,1)\nprint testHolo(lambda z: sp.conj(z),1,0,0.01,1)\nprint testHolo(lambda z: z*sp.real(z),0,0,0.01,1)\nprint testHolo(lambda z: z*sp.real(z),1,1,0.01,1)\nprint testHolo(lambda z: sp.exp(z),0,np.pi,0.01,1)\n\nprint testHolo(lambda z: sp.sin(sp.real(z))*sp.cosh(sp.imag(z))+\n\tsp.cos(sp.real(z))*sp.sinh(sp.imag(z))*1j ,0,np.pi,0.01,1)\nprint testHolo(lambda z: sp.sin(sp.real(z))*sp.cosh(sp.imag(z))\n\t-sp.cos(sp.real(z))*sp.sinh(sp.imag(z))*1j,0,np.pi,0.01,1)\n\n\n\n", "meta": {"hexsha": "391454e6b406276d20d0a18d28a8a1e593d8bb02", "size": 1652, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/ConformalMaps/solutions.py", "max_stars_repo_name": "jessicaleete/numerical_computing", "max_stars_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-10-18T19:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:12:38.000Z", "max_issues_repo_path": "Labs/ConformalMaps/solutions.py", "max_issues_repo_name": "jessicaleete/numerical_computing", "max_issues_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/ConformalMaps/solutions.py", "max_forks_repo_name": "jessicaleete/numerical_computing", "max_forks_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-14T16:07:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-20T09:05:06.000Z", "avg_line_length": 22.6301369863, "max_line_length": 90, "alphanum_fraction": 0.6700968523, "include": true, "reason": "import numpy,import scipy", "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828602, "lm_q2_score": 0.8976952866333484, "lm_q1q2_score": 0.8599133305797909}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nInterpolaciones de diferente orden para la funcion\r\n\r\n  2*exp(x) + sin(3*x)\r\n\r\n\"\"\"\r\nfrom __future__ import division, print_function\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.interpolate import lagrange\r\nimport sympy as sym\r\n\r\nplt.rcParams[\"axes.spines.right\"] = False\r\nplt.rcParams[\"axes.spines.top\"] = False\r\nplt.rcParams[\"mathtext.fontset\"] = \"cm\"\r\n\r\n\r\ndef base_lagrange(x_datos, var, cont):\r\n    \"\"\"Crea un polinomio base de Lagrange para los datos x\"\"\"\r\n    prod = sym.prod((var - x_datos[i])/(x_datos[cont] - x_datos[i])\r\n                    for i in range(len(x_datos)) if i != cont)\r\n\r\n    return sym.lambdify(var, sym.simplify(prod), \"numpy\")\r\n\r\n\r\ndef deriv_base_lagrange(x_datos, var, cont):\r\n    \"\"\"Crea un polinomio base de Lagrange para los datos x\"\"\"\r\n    prod = sym.prod((var - x_datos[i])/(x_datos[cont] - x_datos[i])\r\n                    for i in range(len(x_datos)) if i != cont)\r\n    return sym.lambdify(var, sym.simplify(prod.diff(var)), \"numpy\")\r\n\r\n\r\nfun = lambda x: 2*np.exp(x) + np.sin(3*x)\r\ngrad = lambda x: 2*np.exp(x) + 3*np.cos(3*x)\r\nx = np.linspace(-1, 1, 101) \r\ny = fun(x)\r\ndy = grad(x)\r\n\r\nplt.close(\"all\")\r\nplt.figure(figsize=(5, 6))\r\n\r\nnpts = [2, 3, 5]\r\nfor cont in range(3):\r\n    ax = plt.subplot(3, 2, 2*cont + 1)\r\n    if cont==0:\r\n        plt.title(\"Interpolación\")\r\n    x_inter = np.linspace(-1, 1, npts[cont])\r\n    y_inter = fun(x_inter)\r\n    f_inter = lagrange(x_inter, y_inter)\r\n    plt.plot(x, y)\r\n    plt.plot(x, f_inter(x), linestyle=\"dashed\",\r\n             label=\"Orden {}\".format(npts[cont] - 1))\r\n    plt.plot(x_inter, y_inter, \"ok\")\r\n    plt.ylabel(\"$y$\", fontsize=14)\r\n    plt.legend(frameon=False)\r\n    if cont != 2:\r\n        ax.xaxis.set_ticks([])\r\n        ax.spines[\"bottom\"].set_color(\"none\")\r\n    if cont == 2:\r\n        plt.xlabel(\"$x$\", fontsize=14)\r\n\r\nfor cont in range(3):\r\n    ax = plt.subplot(3, 2, 2*cont + 2)\r\n    if cont==0:\r\n        plt.title(\"Funciones base\")\r\n    for cont_base in range(npts[cont]):\r\n        x_inter = np.linspace(-1, 1, npts[cont])\r\n        base = base_lagrange(x_inter, sym.symbols(\"x\"), cont_base)\r\n        y_base = base(x)\r\n        plt.plot(x, y_base)\r\n        plt.ylim(-0.6, 1.2)\r\n        plt.yticks(np.linspace(-0.5, 1, 4))\r\n        plt.ylabel(\"$y$\", fontsize=14)\r\n    if cont != 2:\r\n        ax.xaxis.set_ticks([])\r\n        ax.spines[\"bottom\"].set_color(\"none\")\r\n    if cont == 2:\r\n        plt.xlabel(\"$x$\", fontsize=14)\r\n\r\nplt.tight_layout()\r\nplt.savefig(\"interp_multiple.pdf\", bbox_inches=\"tight\", transparent=True)\r\n\r\n\r\n#%% Derivadas\r\nplt.figure(figsize=(5, 2.5))\r\nplt.subplot(122)\r\nplt.title(\"Funciones base\")\r\nx_inter = np.linspace(-1, 1, 5)\r\ny_inter = fun(x_inter)\r\ndy_inter = np.zeros_like(x)\r\nfor cont_base in range(5):\r\n    deriv_base = deriv_base_lagrange(x_inter, sym.symbols(\"x\"), cont_base)\r\n    y_base = deriv_base(x)\r\n    dy_inter += y_base * y_inter[cont_base]\r\n    plt.plot(x, y_base)\r\n    plt.xlabel(\"$x$\", fontsize=14)\r\n    plt.ylabel(\"$y$\", fontsize=14)\r\n\r\nplt.subplot(121)\r\nplt.title(\"Derivadas\")\r\nplt.plot(x, dy)\r\nplt.plot(x, dy_inter, linestyle=\"dashed\")\r\nplt.plot(x_inter, grad(x_inter), \"ok\")\r\nplt.xlabel(\"$x$\", fontsize=14)\r\nplt.ylabel(\"$y$\", fontsize=14)\r\nplt.tight_layout()\r\nplt.savefig(\"interp_multiple_deriv.pdf\", bbox_inches=\"tight\", transparent=True)\r\n#plt.show()", "meta": {"hexsha": "3962786c94d8c33c14cfa60b1ea6503c11000ae4", "size": 3332, "ext": "py", "lang": "Python", "max_stars_repo_path": "notas_de_clase/img/metodos/interpolacion_multiple.py", "max_stars_repo_name": "AppliedMechanics-EAFIT/Mod_Temporal", "max_stars_repo_head_hexsha": "6a0506d906ed42b143b773777e8dc0da5af763eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-02-20T18:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-19T22:44:44.000Z", "max_issues_repo_path": "notas_de_clase/img/metodos/interpolacion_multiple.py", "max_issues_repo_name": "AppliedMechanics-EAFIT/Mod_Temporal", "max_issues_repo_head_hexsha": "6a0506d906ed42b143b773777e8dc0da5af763eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-04-15T00:22:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-04T17:03:54.000Z", "max_forks_repo_path": "notas_de_clase/img/metodos/interpolacion_multiple.py", "max_forks_repo_name": "AppliedMechanics-EAFIT/Mod_Temporal", "max_forks_repo_head_hexsha": "6a0506d906ed42b143b773777e8dc0da5af763eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-14T18:17:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-27T06:37:05.000Z", "avg_line_length": 30.5688073394, "max_line_length": 80, "alphanum_fraction": 0.6092436975, "include": true, "reason": "import numpy,from scipy,import sympy", "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957912274487423, "lm_q2_score": 0.8976952818435994, "lm_q1q2_score": 0.8599133292274305}}
{"text": "import numpy as np\r\nimport sys\r\n\r\nmatrix = None\r\ndef main():\r\n    global matrix\r\n    matrix = np.array([[1,1,-1],[6,2,2],[-3,4,1]],dtype=float)\r\n    aug_matrix = np.concatenate((matrix,identity_matrix(3)),axis=1)\r\n    #gaussian2(aug_matrix) #gaussian elimination with maximum pivoting\r\n    LUdecomp(matrix) #LU decompose a square matrix\r\n\r\ndef identity_matrix(n):\r\n    m = np.empty([n,n],dtype=float)\r\n    for i in range (0,n):\r\n        for j in range (0,n):\r\n            if(i==j): m[i][j] = 1\r\n            else: m[i][j] = 0\r\n    \r\n    return m\r\n\r\ndef gaussian2(m):\r\n    print()\r\n    print(\"Gaussian Elimination 2.0:\")\r\n    print()\r\n\r\n    for j in range (0,m.shape[0]):\r\n        max_pivot_row = j\r\n        max_pivot = m[j][j]\r\n        for a in range (1, m.shape[0]-j):\r\n            if(m[j+a][j]>max_pivot):\r\n                max_pivot_row = j+a\r\n                print(\"maximum pivoting: R\",(j+1),\"<->\",\"R\",(max_pivot_row+1))\r\n                print()\r\n        \r\n        m[[j,max_pivot_row]] = m[[max_pivot_row,j]]\r\n       \r\n        if(m[j][j]==0):\r\n            print(\"no unique solution\")\r\n            break\r\n\r\n        for i in range (j+1, m.shape[0]):\r\n            c = (m[i][j])/(m[j][j])\r\n            if(c==0): \r\n                print(\"c==0!!\")\r\n                continue\r\n            for a in range (0, m[j].shape[0]):\r\n                m[i][a]=m[i][a]-c*(m[j][a])\r\n    \r\n            print(\"row operation: R\",(i+1),\"-\",c,\"*R\",(j+1))\r\n            print(m)\r\n            print()\r\n\r\ndef LUdecomp(m):\r\n    L = identity_matrix(m.shape[0])\r\n\r\n    for j in range (0, m.shape[0]):\r\n        for i in range (j+1, m.shape[0]):\r\n            c = (m[i][j])/(m[j][j])\r\n            if(c==0): \r\n                continue\r\n            for a in range (0, m[j].shape[0]):\r\n                m[i][a]=m[i][a]-c*(m[j][a])\r\n            L[i][j] = c\r\n\r\n            print(\"row operation: R\",(i+1),\"-\",c,\"*R\",(j+1))\r\n            print(m)\r\n            print()\r\n    \r\n    print(\"matrix L is:\")\r\n    print(L)\r\n    print(\"matrix U is:\")\r\n    print(m)\r\n\r\nmain()", "meta": {"hexsha": "21c982b629a7b99b2d178390a39704639885bd4c", "size": 2023, "ext": "py", "lang": "Python", "max_stars_repo_path": "matrix_calc.py", "max_stars_repo_name": "akiraminase/numerical_methods", "max_stars_repo_head_hexsha": "1d1dc856fd398a8e7e5f629c1ec3c3350dda4cd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matrix_calc.py", "max_issues_repo_name": "akiraminase/numerical_methods", "max_issues_repo_head_hexsha": "1d1dc856fd398a8e7e5f629c1ec3c3350dda4cd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matrix_calc.py", "max_forks_repo_name": "akiraminase/numerical_methods", "max_forks_repo_head_hexsha": "1d1dc856fd398a8e7e5f629c1ec3c3350dda4cd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3378378378, "max_line_length": 79, "alphanum_fraction": 0.4369747899, "include": true, "reason": "import numpy", "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347816221828, "lm_q2_score": 0.8824278726384089, "lm_q1q2_score": 0.8598684113717353}}
{"text": "from numpy import *\nfrom newton import *\nfrom quasi_newton import *\nfrom steepest_descent import *\nfrom conjugate_gradient import *\n\nif __name__ == '__main__':\n  def f(x): return 100 * math.pow(x[1] - math.pow(x[0], 2), 2) + math.pow(1 - x[0], 2)\n  def df_dx1(x): return 400*math.pow(x[0], 3) - 400*x[0]*x[1] + 2*x[0] - 2\n  def df_dx2(x): return 200*x[1] - 200*math.pow(x[0], 2)\n  def fd(x): return array([ df_dx1(x), df_dx2(x) ])\n  \n  def df_dx1_dx1(x): return 1200*math.pow(x[0], 2) - 400*x[1] + 2\n  def df_dx1_dx2(x): return-400*x[0]\n  \n  def fdd(x):\n    return array([\n        [df_dx1_dx1(x), df_dx1_dx2(x)],\n        [df_dx1_dx2(x), 200]])\n  \n  def print_error(i, direction, alpha, x):\n    opt = f(array([1,1]))\n    print(\"%d, %.20f\" % (i, f(x)-opt))\n  \n  def print_gradient(i, direction, alpha, x):\n    print(\"%d, %.20f\" % (i, linalg.norm(fd(x))))\n  \n  def print_all(i, direction, alpha, x):\n    print(\"iteration %d: \\t direction: %s \\t alpha: %.7f \\t x: %s\"\n        % (i, [\"%.7f\" % _ for _ in direction], alpha, [\"%.7f\" % _ for _ in x]))\n  \n  x = array([0, 0])\n  precision = 10e-6\n  max_iterations = 100\n  callback = print_all\n  \n  print(\"steepest descent:\")\n  steepest_descent(f, fd, x, max_iterations, precision, callback)\n  \n  print(\"\\nnewton:\")\n  newton(f, fd, fdd, x, max_iterations, precision, callback)\n  \n  print(\"\\nquasi newton:\")\n  quasi_newton(f, fd, x, max_iterations, precision, callback)\n  \n  print(\"\\nconjugate gradient:\")\n  conjugate_gradient(f, fd, x, max_iterations, precision, callback)\n  \n", "meta": {"hexsha": "0c9020f6e3a785fac0cee8cecd74bd7ea27dc394", "size": 1515, "ext": "py", "lang": "Python", "max_stars_repo_path": "Computational Mathematics | Python/Rosenbrock.py", "max_stars_repo_name": "Anirban166/Quadratics", "max_stars_repo_head_hexsha": "9e031625fb2ff62087c1592fee89d58528193a33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-09-16T06:37:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T11:34:58.000Z", "max_issues_repo_path": "Computational Mathematics | Python/Rosenbrock.py", "max_issues_repo_name": "Anirban166/Quadratics", "max_issues_repo_head_hexsha": "9e031625fb2ff62087c1592fee89d58528193a33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Computational Mathematics | Python/Rosenbrock.py", "max_forks_repo_name": "Anirban166/Quadratics", "max_forks_repo_head_hexsha": "9e031625fb2ff62087c1592fee89d58528193a33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-10-11T15:00:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-15T16:56:14.000Z", "avg_line_length": 30.9183673469, "max_line_length": 86, "alphanum_fraction": 0.6118811881, "include": true, "reason": "from numpy", "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.974434783107032, "lm_q2_score": 0.8824278680004706, "lm_q1q2_score": 0.8598684081626392}}
{"text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom scipy.stats import geom\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef testGeom():# {{{\n    \"\"\"\n    Geometric Distribution (discrete)\n\n    Notes\n    -----\n        伯努利事件进行k次, 第一次成功的概率\n\n    为什么是几何分布呢, 为什么不叫几毛分布?\n    与几何数列有关 (乘积倍数)\n\n    p: 成功的概率\n    q: 失败的概率(1-p)\n    k: 第一次成功时的经历的次数 (前k-1次是失败的)\n        geom.pmf(k, p), (1-p)**(k-1)*p)\n    \"\"\"\n\n    # 准备数据: 已知 p. \n    # X轴: 第k次才成功\n    # Y轴: 概率\n    p = 0.4\n    xs = np.arange(geom.ppf(0.01, p), geom.ppf(0.99, p), step = 1)\n\n    # E(X) = 1/p, D(X) = (1-p)/p**2 \n    mean, var, skew, kurt = geom.stats(p, moments='mvsk')\n    print(\"mean: %.2f, var: %.2f, skew: %.2f, kurt: %.2f\" % (mean, var, skew, kurt))\n\n    fig, axs = plt.subplots(2, 2)\n\n    # 显示pmf1\n    ys = geom.pmf(xs, p)\n    axs[0][0].plot(xs, ys, 'bo', markersize=5, label='geom pmf')\n    axs[0][0].vlines(xs, 0, ys, colors='b', linewidth=5, alpha=0.5, label='vline pmf')\n    axs[0][0].legend(loc='best', frameon=False)\n\n    # 显示pmf2\n    ys = (1-p)**(xs-1)*p\n    axs[0][1].plot(xs, ys, 'bo', markersize=5, label='geom pmf')\n    axs[0][1].vlines(xs, 0, ys, colors='b', linewidth=5, alpha=0.5, label='vline pmf')\n    axs[0][1].legend(loc='best', frameon=False)\n    axs[0][1].set_title('ys = (1-p)**(xs-1)*p')\n\n    # 显示cdf P(X<=x)\n    ys = geom.cdf(xs, p)\n    axs[1][0].plot(xs, ys, 'bo', markersize=5, label='geom cdf')\n    axs[1][0].legend(loc='best', frameon=False)\n    print(np.allclose(xs, geom.ppf(ys, p))) # ppf:y-->x cdf:x-->y\n\n    # 生成随机数据(random variables)\n    data = geom.rvs(p, size=1000)\n    import sys\n    sys.path.append(\"../../thinkstats\")\n    import Pmf\n    pmf = Pmf.MakePmfFromList(data)\n    xs, ys = pmf.Render()\n    axs[1][1].plot(xs, ys, 'bo', markersize=5, label='rvs-pmf')\n\n    plt.show()\n\n# }}}\n\n\nif __name__ == \"__main__\":\n   testGeom() \n", "meta": {"hexsha": "b848b45262a4dcdde71004f0dc4e268e4329f824", "size": 1824, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/learn/scipy/stats/Geo.py", "max_stars_repo_name": "qrsforever/workspace", "max_stars_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-06-07T03:20:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-07T09:14:26.000Z", "max_issues_repo_path": "python/learn/scipy/stats/Geo.py", "max_issues_repo_name": "qrsforever/workspace", "max_issues_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/learn/scipy/stats/Geo.py", "max_forks_repo_name": "qrsforever/workspace", "max_forks_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3333333333, "max_line_length": 86, "alphanum_fraction": 0.5520833333, "include": true, "reason": "import numpy,from scipy", "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100817, "lm_q2_score": 0.9099070133672954, "lm_q1q2_score": 0.8598573101385852}}
{"text": "import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\ndf = pd.read_csv(\"china_gdp.csv\")\r\ndf.head(10)\r\n\r\nplt.figure(figsize=(8,5))\r\nx_data, y_data = (df[\"Year\"].values, df[\"Value\"].values)\r\nplt.plot(x_data, y_data, 'ro')\r\nplt.ylabel('GDP')\r\nplt.xlabel('Year')\r\nplt.show()\r\n\r\nX = np.arange(-5.0, 5.0, 0.1)\r\nY = 1.0 / (1.0 + np.exp(-X))\r\n\r\nplt.plot(X,Y)\r\nplt.ylabel('Dependent Variable')\r\nplt.xlabel('Indepdendent Variable')\r\nplt.show()\r\n\r\n\r\ndef sigmoid(x, Beta_1, Beta_2):\r\n    y = 1 / (1 + np.exp(-Beta_1 * (x - Beta_2)))\r\n    return y\r\n\r\nbeta_1 = 0.10\r\nbeta_2 = 1990.0\r\n\r\n#logistic function\r\nY_pred = sigmoid(x_data, beta_1 , beta_2)\r\n\r\n#plot initial prediction against datapoints\r\nplt.plot(x_data, Y_pred*15000000000000.)\r\nplt.plot(x_data, y_data, 'ro')\r\n\r\n# Lets normalize our data\r\nxdata =x_data/max(x_data)\r\nydata =y_data/max(y_data)\r\n\r\nfrom scipy.optimize import curve_fit\r\npopt, pcov = curve_fit(sigmoid, xdata, ydata)\r\n#print the final parameters\r\nprint(\" beta_1 = %f, beta_2 = %f\" % (popt[0], popt[1]))\r\n\r\nx = np.linspace(1960, 2015, 55)\r\nx = x/max(x)\r\nplt.figure(figsize=(8,5))\r\ny = sigmoid(x, *popt)\r\nplt.plot(xdata, ydata, 'ro', label='data')\r\nplt.plot(x,y, linewidth=3.0, label='fit')\r\nplt.legend(loc='best')\r\nplt.ylabel('GDP')\r\nplt.xlabel('Year')\r\nplt.show()\r\n\r\n# PRACTICE: Accuracy Test\r\n\r\n# split data into train/test\r\nmsk = np.random.rand(len(df)) < 0.8\r\ntrain_x = xdata[msk]\r\ntest_x = xdata[~msk]\r\ntrain_y = ydata[msk]\r\ntest_y = ydata[~msk]\r\n\r\n# build the model using train set\r\npopt, pcov = curve_fit(sigmoid, train_x, train_y)\r\n\r\n# predict using test set\r\ny_hat = sigmoid(test_x, *popt)\r\nprint(y_hat)\r\n\r\n# evaluation\r\nprint(\"Mean absolute error: %.2f\" % np.mean(np.absolute(y_hat - test_y)))\r\nprint(\"Residual sum of squares (MSE): %.2f\" % np.mean((y_hat - test_y) ** 2))\r\nfrom sklearn.metrics import r2_score\r\nprint(\"R2-score: %.2f\" % r2_score(y_hat , test_y) )", "meta": {"hexsha": "a01335eddc6cd00b60aa14f24eb8900192768532", "size": 1902, "ext": "py", "lang": "Python", "max_stars_repo_path": "NonLinearRegression.py", "max_stars_repo_name": "OlawuyiSola/ml-implementation", "max_stars_repo_head_hexsha": "882615762690e78c77a19c097203ba7d8491fd99", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NonLinearRegression.py", "max_issues_repo_name": "OlawuyiSola/ml-implementation", "max_issues_repo_head_hexsha": "882615762690e78c77a19c097203ba7d8491fd99", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NonLinearRegression.py", "max_forks_repo_name": "OlawuyiSola/ml-implementation", "max_forks_repo_head_hexsha": "882615762690e78c77a19c097203ba7d8491fd99", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3846153846, "max_line_length": 78, "alphanum_fraction": 0.6603575184, "include": true, "reason": "import numpy,from scipy", "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102589923635, "lm_q2_score": 0.8887588023318196, "lm_q1q2_score": 0.8597943831455684}}
{"text": "import numpy as np\n\ndef nb_path_maze(maze):\n\t\"\"\"\n\tGiven a maze with 0 as paths and 1 as walls, beginning at top left,\n\twith only possibilities to go down or right. Return the number of possible paths.\n\n\tO(n) time and space\n\t\"\"\"\n\tI,J = maze.shape\n\tsheet = np.zeros((I,J))\n\n\tsheet[0,0] = 1\n\n\tfor i in range(I):\n\t\tfor j in range(J):\n\t\t\tif maze[i,j] == 0 and (i,j) != (0,0) :\n\t\t\t\tsheet[i,j] = sheet[max(0,i-1),j] + sheet[i,max(0,j-1)]\n\n\treturn sheet[i,j]\n\nmaze = np.array(\n\t[[0,1,0],\n\t [0,0,1],\n\t [0,0,0]]\n\t)\nprint(maze)\nprint(f\"{nb_path_maze(maze)}, expected 2\") \n\nmaze = np.array(\n\t[[0,1,0,0],\n\t [0,0,0,0],\n\t [1,0,1,0],\n\t [0,0,0,0]]\n\t)\nprint(maze)\nprint(f\"{nb_path_maze(maze)}, expected 2\") \n\nmaze = np.array(\n\t[[0,0,1,0],\n\t [0,0,0,0],\n\t [1,0,1,0],\n\t [0,0,0,0]]\n\t)\nprint(maze)\nprint(f\"{nb_path_maze(maze)}, expected 4\") \n\nmaze = np.array(\n\t[[0,0,0,0],\n\t [0,0,1,0],\n\t [0,1,0,0],\n\t [0,0,0,0]]\n\t)\nprint(maze)\nprint(f\"{nb_path_maze(maze)}, expected 2\") \n", "meta": {"hexsha": "8f4c64d304fae3d9939dd1465f7bba920627fcb2", "size": 948, "ext": "py", "lang": "Python", "max_stars_repo_path": "algopro/nb_paths_in_maze.py", "max_stars_repo_name": "Mifour/Algorithms", "max_stars_repo_head_hexsha": "77cfafc49bc0130da0f6041b169a15053f81af87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algopro/nb_paths_in_maze.py", "max_issues_repo_name": "Mifour/Algorithms", "max_issues_repo_head_hexsha": "77cfafc49bc0130da0f6041b169a15053f81af87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algopro/nb_paths_in_maze.py", "max_forks_repo_name": "Mifour/Algorithms", "max_forks_repo_head_hexsha": "77cfafc49bc0130da0f6041b169a15053f81af87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.9285714286, "max_line_length": 82, "alphanum_fraction": 0.5727848101, "include": true, "reason": "import numpy", "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102589923637, "lm_q2_score": 0.8887587875995482, "lm_q1q2_score": 0.859794368893418}}
{"text": "import numpy as np\n\n\ndef euclidean(u, v):\n    \"\"\"\n    Calculates the euclidean distance between vectors u an v\n\n    precondition:\n        u.shape == v.shape\n\n    :param u: vector of numbers\n    :param v: vector of numbers\n    :return: euclidean distance between u and v\n    \"\"\"\n\n    if u.shape != v.shape:\n        raise ValueError(\"The size of u and v differs\")\n\n    return np.sqrt(np.power(u - v, 2).sum())\n\n\ndef manhattan(u, v):\n    \"\"\"\n    Calculates the manhattan distance (also known as taxicab geometry) between\n    vectors u an v.\n\n    precondition:\n        u.shape == v.shape\n\n    :param u: vector of numbers\n    :param v: vector of numbers\n    :return: manhattan distance between u and v\n    \"\"\"\n\n    if u.shape != v.shape:\n        raise ValueError(\"The size of u and v differs\")\n\n    return np.abs(u - v).sum()\n\n\ndef cosine(u, v):\n    \"\"\"\n    Calculates the cosine distance (1 - cosine similarity) between two vectors\n\n    precondition:\n        u.shape == v.shape\n\n    :param u: vector of numbers\n    :param v: vector of numbers\n    :return: cosine distance between u and v\n    \"\"\"\n\n    if u.shape != v.shape:\n        raise ValueError(\"The size of u and v differs\")\n\n    return 1 - u.dot(v) / np.sqrt(u.dot(u)*v.dot(v))\n", "meta": {"hexsha": "9eac053cb03f47247fefe3b1e91a3a09670a3a8c", "size": 1230, "ext": "py", "lang": "Python", "max_stars_repo_path": "archive/2018/ml/distances.py", "max_stars_repo_name": "TamaraMaggioni/IntroduccionAprendizajeAutomatico", "max_stars_repo_head_hexsha": "d9fb1fbb0a694fe00d4229baea78a69a465b941b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2018-06-17T14:59:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T19:32:35.000Z", "max_issues_repo_path": "archive/2018/ml/distances.py", "max_issues_repo_name": "TamaraMaggioni/IntroduccionAprendizajeAutomatico", "max_issues_repo_head_hexsha": "d9fb1fbb0a694fe00d4229baea78a69a465b941b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "archive/2018/ml/distances.py", "max_forks_repo_name": "TamaraMaggioni/IntroduccionAprendizajeAutomatico", "max_forks_repo_head_hexsha": "d9fb1fbb0a694fe00d4229baea78a69a465b941b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 68, "max_forks_repo_forks_event_min_datetime": "2018-06-01T23:53:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T02:29:03.000Z", "avg_line_length": 21.5789473684, "max_line_length": 78, "alphanum_fraction": 0.6146341463, "include": true, "reason": "import numpy", "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102571131692, "lm_q2_score": 0.8887587839164801, "lm_q1q2_score": 0.8597943636602297}}
{"text": "import numpy as np\nimport time\n\n\ndef monte_carlo(func, low, high, scale_coefficient=None, random_generator=None, sample_numbers=None, density_func=None):\n    start_time = time.time()\n    integral_func = func\n    if density_func is not None:\n        integral_func = lambda x: func(x) / density_func(x)\n\n    if sample_numbers is None:\n        sample_numbers = int(np.abs((high - low) * 1000))\n\n    if random_generator is None:\n        random_generator = lambda n: (high - low) * np.random.rand(n) + low\n\n    if scale_coefficient is None:\n        scale_coefficient = high - low\n\n    random_x = random_generator(sample_numbers)\n    func_values = integral_func(random_x)\n    integral_value = scale_coefficient * np.mean(func_values)\n    value_error = scale_coefficient * np.std(func_values) / np.sqrt(sample_numbers)\n\n    end_time = time.time()\n\n    return integral_value, value_error, (end_time - start_time)\n\n\nif __name__ == \"__main__\":\n    func = lambda x: np.exp(-(x ** 2))\n    low = 0\n    high = 2\n    sample_numbers = 10 ** np.arange(3, 9)\n\n    for sample in sample_numbers:\n        simple_sampling_value, simple_sampling_error, simple_sampling_runtime = monte_carlo(\n            func, low, high, sample_numbers=sample)\n\n        random_generator_1 = lambda n: -np.log(np.exp(-low) - (np.exp(-low) - np.exp(-high)) * np.random.rand(n))\n        density_func_1 = lambda x: np.exp(-x)\n        scale_coefficient_1 = np.exp(-low) - np.exp(-high)\n        important_sampling_value_1, important_sampling_error_1, important_sampling_runtime_1 = monte_carlo(\n            func, low, high, scale_coefficient_1, random_generator_1, sample, density_func_1)\n\n        random_generator_2 = lambda n: np.tan((np.arctan(high) - np.arctan(low)) * np.random.rand(n))\n        density_func_2 = lambda x: 1 / (x ** 2 + 1)\n        scale_coefficient_2 = np.arctan(high) - np.arctan(low)\n        important_sampling_value_2, important_sampling_error_2, important_sampling_runtime_2 = monte_carlo(\n            func, low, high, scale_coefficient_2, random_generator_2, sample, density_func_2)\n\n        print(f'Sample Numbers: {sample}:')\n\n        print(f'Simple Sampling:\\n'\n              f'\\tvalue: {simple_sampling_value}\\n'\n              f'\\terror: {simple_sampling_error}\\n'\n              f'\\ttime: {simple_sampling_runtime}')\n\n        print(f'Important Sampling: g(x) = e^(-x)\\n'\n              f'\\tvalue: {important_sampling_value_1}\\n'\n              f'\\terror: {important_sampling_error_1}\\n'\n              f'\\ttime: {important_sampling_runtime_1}')\n\n        print(f'Important Sampling: g(x) = 1 / (x^2 + 1)\\n'\n              f'\\tvalue: {important_sampling_value_2}\\n'\n              f'\\terror: {important_sampling_error_2}\\n'\n              f'\\ttime: {important_sampling_runtime_2}')\n\n        print(end='\\n')\n", "meta": {"hexsha": "9c14131c344a722ed57c1cea86d9d27fa3cd3d43", "size": 2783, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW6/q2.py", "max_stars_repo_name": "sina-moammar/2020-Fall-Computational-Physics", "max_stars_repo_head_hexsha": "f03e95b0a97022b628175fd06c301aecfdcf60af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW6/q2.py", "max_issues_repo_name": "sina-moammar/2020-Fall-Computational-Physics", "max_issues_repo_head_hexsha": "f03e95b0a97022b628175fd06c301aecfdcf60af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW6/q2.py", "max_forks_repo_name": "sina-moammar/2020-Fall-Computational-Physics", "max_forks_repo_head_hexsha": "f03e95b0a97022b628175fd06c301aecfdcf60af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7571428571, "max_line_length": 120, "alphanum_fraction": 0.6579231046, "include": true, "reason": "import numpy", "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.9046505447409666, "lm_q1q2_score": 0.8597898118972574}}
{"text": "import numpy as np\nfrom math import *\nimport matplotlib.pyplot as plt\n\n''' The problem is: dy/dt = f(t,y).'''\n\ndef f(t, y):\n    return 0.5*y\n\n# We will use RK4 to compute some intiall values needed to Adams-Bashforth Method\n## a,b: edges of the interval, w0:ititial value, h:step\ndef RungeKutta4(a, b, w0, h):\n    n = ceil((b-a) / h)\n\n    w, t = np.zeros(n+1), np.zeros(n+1)\n    w[0], t[0] = w0, a\n\n    for i in range(n):\n        k1 = h*f(t[i], w[i])\n        k2 = h*f(t[i] + h/2, w[i] + k1/2)\n        k3 = h*f(t[i] + h/2, w[i] + k2/2)\n        k4 = h*f(t[i] + h, w[i] + k3)\n        w[i+1] = w[i] + 1/6*(k1 + 2*k2 + 2*k3 + k4)\n        t[i+1] = t[i] + h\n\n    return w, t\n\n# a,b: edges of the interval, w0,w1,w2,w3:ititial value, h:step\ndef AdamsBashforth(a, b, w0, w1, w2, w3, h):\n    n = ceil((b-a) / h)\n\n    w, t = np.zeros(n+1), np.zeros(n+1)\n    t[0], t[1], t[2], t[3] = a, a+h, a+2*h, a+3*h\n    w[0], w[1], w[2], w[3] = w0, w1, w2, w3\n\n    for i in range(3, n):\n        w[i+1] = w[i] + h/24*(55*f(t[i],w[i]) - 59*f(t[i-1],w[i-1]) + 37*f(t[i-2],w[i-2]) - 9*f(t[i-3],w[i-3]))\n        t[i+1] = t[i] + h\n\n    return w, t\n\nif __name__ == '__main__':\n\n    a, b, w0, h = 0, 2, 1, 0.2\n    w = RungeKutta4(a, b, w0, h)[0]\n    print(\"\\n\", AdamsBashforth(a, b, w0, w[1], w[2], w[3], h)[0])\n\n    # Visualization\n    x = np.linspace(0, 2, 100)\n\n    y = np.zeros(len(x))\n\n    for j in range(len(x)):\n        y[j] = exp(0.5*x[j])\n\n    plt.plot(x, y, color=\"black\", label=\"Solution\")\n    plt.plot(AdamsBashforth(a, b, w0, w[1], w[2], w[3], h)[1], AdamsBashforth(a, b, w0, w[1], w[2], w[3], h)[0], label=\"Adams-Bashforth\")\n    plt.xlabel(\"t\")\n    plt.ylabel(\"y\")\n    plt.legend()\n    plt.show()\n\n", "meta": {"hexsha": "cb7507daa7a1740413d77aae340dc56f9542a163", "size": 1681, "ext": "py", "lang": "Python", "max_stars_repo_path": "Differential-Equations/Adams-Bashforth-Method.py", "max_stars_repo_name": "AlexTsagas/Computational-Physics", "max_stars_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Differential-Equations/Adams-Bashforth-Method.py", "max_issues_repo_name": "AlexTsagas/Computational-Physics", "max_issues_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Differential-Equations/Adams-Bashforth-Method.py", "max_forks_repo_name": "AlexTsagas/Computational-Physics", "max_forks_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6825396825, "max_line_length": 137, "alphanum_fraction": 0.49256395, "include": true, "reason": "import numpy", "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410982634296, "lm_q2_score": 0.9046505370289059, "lm_q1q2_score": 0.859789805838286}}
{"text": "import numpy as np\n\ndef sigmoid(z):\n    \"\"\"\n    Return:\n    s -- sigmoid(z)\n    \"\"\"\n    \n    \n    s = 1./(1+np.exp(-z))\n    \n    return s\n\ndef RELU(z):\n    \"\"\"\n    Return:\n    s -- RELU(z)\n    \"\"\"\n    s = np.maximum(z,0)\n    return s\ndef Parametric_RELU(z, a):\n    \"\"\"\n    z -- vector\n    a -- parameter int\n    Return:\n    s -- Parametric_RELU(z)\n    \"\"\"\n    s = np.maximum(z, z*a )\n    return s\n\ndef Leaky_RELU(z):\n    \"\"\"\n    Return:\n    s -- RELU(z)\n    \"\"\"\n    # s = np.where( z>0 , z, 0.01*z)\n    s = np.maximum(z, z*0.01 )\n    return s\n\ndef Tanh(z):\n    \"\"\"\n    Return:\n    s -- tanh(z)\n    \"\"\"\n    s = (np.exp(z) - np.exp(-z))/(np.exp(z) + np.exp(-z))\n\n    return s\n\ndef Silu(z):\n    \"\"\"\n    Return:\n    s -- sigmoid(z)*z\n    \"\"\"\n    s = z*sigmoid(z)\n\n    return s\n\n\n", "meta": {"hexsha": "25a08b632c36bb59266aa07f42aa2425c6ee5409", "size": 775, "ext": "py", "lang": "Python", "max_stars_repo_path": "Victor/Day3.py", "max_stars_repo_name": "dyofficial/100-Days-of-Code", "max_stars_repo_head_hexsha": "28a4334212b6d1679aaa8dda9906bc2640a0a973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2022-01-11T14:00:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T02:49:44.000Z", "max_issues_repo_path": "Victor/Day3.py", "max_issues_repo_name": "dyofficial/100-Days-of-Code", "max_issues_repo_head_hexsha": "28a4334212b6d1679aaa8dda9906bc2640a0a973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2022-01-11T17:08:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T17:03:15.000Z", "max_forks_repo_path": "Victor/Day3.py", "max_forks_repo_name": "dyofficial/100-Days-of-Code", "max_forks_repo_head_hexsha": "28a4334212b6d1679aaa8dda9906bc2640a0a973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 57, "max_forks_repo_forks_event_min_datetime": "2022-01-11T15:54:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T04:37:42.000Z", "avg_line_length": 13.1355932203, "max_line_length": 57, "alphanum_fraction": 0.4322580645, "include": true, "reason": "import numpy", "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068041, "lm_q2_score": 0.9046505376715775, "lm_q1q2_score": 0.8597897988251532}}
{"text": "# Gradient descent method of univariate linear regression.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass LinearRegression:\n    def __init__(self):\n        self._X = None\n        self._y = None\n        self._beta0 = 0.\n        self._beta1 = 0.\n        self._correlation = 0.\n\n    def _mean(self, arr):\n        return np.mean(arr)\n\n    def _diff(self, arr, num):\n        return np.subtract(arr, num)\n\n    def _run_epoch(self, X, y, num_epochs, lr):\n        curr_error = 0.\n        n = len(y)\n        for i in range(num_epochs):\n            curr_prediction = self.predict(X)\n            curr_error = self._rmse_error(y, curr_prediction)\n            beta0_grad = (2. / n) * np.sum(np.subtract(curr_prediction, y))\n            beta1_grad = (2. / n) * np.sum(np.dot(np.subtract(curr_prediction, y), X))\n\n            self._beta0 -= lr * beta0_grad\n            self._beta1 -= lr * beta1_grad\n\n            print('Loss at {} epoch: {}'.format((i + 1), round(curr_error, 5)))\n        return curr_error\n\n    def fit(self, X, y, num_epochs, lr, seed=np.random.randint(0, 1000000)):\n        self._X = X\n        self._y = y\n        self._compute_correlation()\n        np.random.seed(seed)\n        self._beta0 = np.random.uniform(-0.1, 0.1)\n        self._beta1 = np.random.uniform(-0.1, 0.1)\n        rmse_error = self._run_epoch(self._X, self._y, num_epochs, lr)\n        return rmse_error\n\n    def _rmse_error(self, y, y_pred):\n        return np.sqrt(np.mean(np.subtract(y, y_pred) ** 2))\n\n    def predict(self, input):\n        return np.add(self._beta0, np.dot(self._beta1, input))\n\n    def weight_coefficients(self, decimal=4):\n        return round(self._beta0, decimal), round(self._beta1, decimal)\n\n    def _compute_correlation(self):\n        sum_x = np.sum(self._X)\n        sum_y = np.sum(self._y)\n        sum_xy = np.sum(np.multiply(self._X, self._y))\n        sum_xsquare = np.sum(np.multiply(self._X, self._X))\n        sum_ysquare = np.sum(np.multiply(self._y, self._y))\n        n = len(self._X)\n        self._correlation = (n * sum_xy - sum_x * sum_y) / np.sqrt(((n * sum_xsquare - sum_x ** 2) * (n * sum_ysquare - sum_y ** 2)))\n\n    def correlation(self, decimal=4):\n        return round(self._correlation, decimal)\n\n    def plot_regression(self, X, y):\n        plt.scatter(X, y, color=\"red\", marker=\"x\", s=20)\n\n        y_pred = self._beta0 + np.multiply(self._beta1, X)\n\n        plt.plot(X, y_pred, color=\"green\")\n\n        plt.xlabel('X')\n        plt.ylabel('y')\n\n        plt.show()\n\n\ndef main():\n    linear_reg = LinearRegression()\n    X = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n    y = np.array([6, 8, 9, 11, 13, 16, 17, 19, 20, 24])\n\n    rmse_error = linear_reg.fit(X, y, 200, 0.03, seed=12345)\n    weights = linear_reg.weight_coefficients()\n    print 'Weight coefficients for y = mx + c: m = {}, c = {}\\n'.format(weights[1], weights[0])\n    print 'Correlation between X and y: {}\\n'.format(linear_reg.correlation())\n    print 'Root mean-squared error for training: {}\\n'.format(rmse_error)\n\n    test_y = [3, 5, 10]\n    print 'Prediction of {}: {}'.format(test_y, (linear_reg.predict(test_y)))\n    linear_reg.plot_regression(X, y)\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "4e4d592dc5c8819c83ebee3f281010436f376bc7", "size": 3184, "ext": "py", "lang": "Python", "max_stars_repo_path": "code_module/gradient_descent/linear_regression_univariate.py", "max_stars_repo_name": "krayush07/linear-regression", "max_stars_repo_head_hexsha": "fa3ce58e60fcad8d67216f548d4c69fc311fa9ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code_module/gradient_descent/linear_regression_univariate.py", "max_issues_repo_name": "krayush07/linear-regression", "max_issues_repo_head_hexsha": "fa3ce58e60fcad8d67216f548d4c69fc311fa9ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code_module/gradient_descent/linear_regression_univariate.py", "max_forks_repo_name": "krayush07/linear-regression", "max_forks_repo_head_hexsha": "fa3ce58e60fcad8d67216f548d4c69fc311fa9ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4897959184, "max_line_length": 133, "alphanum_fraction": 0.5961055276, "include": true, "reason": "import numpy", "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.905989815306765, "lm_q1q2_score": 0.859709375885681}}
{"text": "\r\n# arrays\r\n# python has inbuilt arrays and well as numpy arrays\r\n# we just use numpy array as the inbuilt ones are less flexible\r\nl=[546,375,254,651,781,569,454,564]\r\n\r\nimport numpy as np\r\na=np.array(l)\r\n# if we convert a list with multiple data types (such as int, string, boolean, etc.)\r\n# the numpy.array() function will convery all elements into a string, so it becomes an array of strings\r\n# so data type of all elements in an array are same\r\n\r\nprint(a)\r\n\r\n# when you slice an array you dont create a copy of an array\r\n# so any modification to the slice of an array will be reflected in the actual array\r\na=[1,2,3,4]\r\na=np.array(a) # array([1, 2, 3, 4])\r\nb=a[0:2]\r\nb[:]=111 # array([1, 2])\r\n# now, b becomes array([111, 111])\r\n# but c also becomes array([111, 111,   3,   4])\r\n\r\n# lets say we have an array a\r\na=[1,2,3,4]\r\nnp.where(a == np.max(a))\r\n# numpy.where() function iterates over a bool array, and for every True, it yields corresponding the element array x, and for every False, it yields corresponding item from array y. So, it returns an array of elements from x where the condition is True and elements from y elsewhere. \r\n# in our example we get (array([x,y,z,..], dtype=int64),) as output\r\n# this means, max value of the array exists at following indices array([x,y,z,..],)\r\n# if max value exists in muliple places then all indices where it exists will be returned\r\n\r\n# building your first matrix\r\nimport numpy as np\r\na=np.arange(0,20)\r\nnp.reshape(a,(5,4),order='F') # order is optional, if not specified then 'C' is the default order\r\n# we could also do\r\na.reshape(5,4)\r\n# C (default behavior) - matrix gets filled row by row, similar to C\r\n# F - matrix gets filled column by column, similar to Fortran\r\n\r\n# INDEXING\r\n# MULTI DIMENTIONAL LIST  -  CONVERT INTO A NUMPY ARRAY AND THEN INDEXING\r\nL= [ [1,2,3], [4,5,6] , [7,8,9] ] # this list has 3 rows and 3 columns\r\nL=np.array(L)\r\nL[1,1] # returns 5\r\nL[0,:] # returns first row; we could also just say L[0]\r\nL[:,0] # returns first column\r\n\r\n# Dictionary is quite useful in matrix indexing, example\r\nm=np.array([[1,2,3],[4,5,6],[7,8,9]])\r\ncol_names={'age':0,'weight':1,'height':2}\r\nrow_names={'vivek':0,'ale':1,'neety':2}\r\n# now we can get weight of ale using actual indexes or dict indexes\r\nm[1,1] # 5\r\nm[row_names['ale'],col_names['weight']] # 5\r\n\r\n# arithmetic operation is element by element \r\n# division by zero shows a warning, and the result of div by zero is nan\r\n# result can be rounded using matrix.round method\r\nA=np.array([[1,2,3],[4,5,6],[7,8,9]])\r\nB=np.array([[1,2,3],[4,5,6],[7,8,9]])\r\nA+B\r\nA-B\r\nA*B\r\nnp.matrix.round(A/B)\r\nA**B\r\n\r\n# visualization\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n# in jupyter notebook we need to specify %matplotlib inline\r\nplt.rcParams['figure.figsize']=8,4 # just need to set it once, can alter the size of plots\r\n\r\nplt.plot(m[0], c='Blue',ls='--',marker='s',ms=17,label='vivek') # c is color, ls - line style, marker='s' - square marker, marker size=17\r\nplt.plot(m[1], c='Magenta',ls='--',marker='s',ms=17,label='ale')\r\nplt.plot(m[2], c='Green',ls='--',marker='s',ms=17,label='neety')\r\nplt.legend(loc='upper left', bbox_to_anchor=(1,1))\r\nplt.xticks([0,1,2],['age','weight','height'],rotation='vertical') #xticks replaces 0,1,2 in x-axis with 'age','weight','height'. We could also specify [0,1,2] using range function like list(range(0,3))\r\nplt.show()\r\n\r\n\r\n\r\n# Covariance matrix\r\ndata = np.array([[45,37,42,35,39],\r\n                [38,31,26,28,33],\r\n                [10,15,17,21,12]])\r\ncovMatrix = np.cov(data,bias=True)\r\nsns.heatmap(covMatrix, annot=True, fmt='g')\r\n\r\n# Create a Correlation Matrix using Pandas\r\ndf = pd.DataFrame({'A': [45,37,42,35,39],\r\n        'B': [38,31,26,28,33],\r\n        'C': [10,15,17,21,12]})\r\ncorrMatrix=df.corr()\r\nsns.heatmap(corrMatrix, annot=True)\r\n\r\n", "meta": {"hexsha": "936484e9deb181b259b02ef957be396307c9944e", "size": 3808, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python-Programming/04-numpy a-z.py", "max_stars_repo_name": "vivekparasharr/Learn-Programming", "max_stars_repo_head_hexsha": "1ae07ef5143bff3c504978e1d375698820f59af0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python-Programming/04-numpy a-z.py", "max_issues_repo_name": "vivekparasharr/Learn-Programming", "max_issues_repo_head_hexsha": "1ae07ef5143bff3c504978e1d375698820f59af0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python-Programming/04-numpy a-z.py", "max_forks_repo_name": "vivekparasharr/Learn-Programming", "max_forks_repo_head_hexsha": "1ae07ef5143bff3c504978e1d375698820f59af0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2577319588, "max_line_length": 285, "alphanum_fraction": 0.6670168067, "include": true, "reason": "import numpy", "num_tokens": 1210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.9059898159413478, "lm_q1q2_score": 0.8597093738702315}}
{"text": "#!/bin/env python3\n# -*- coding:utf-8 -*-\n\n# def p(date):\n#     print(date)\n\ndef create_array():\n    from numpy import arange, uint16, array\n\n    a = arange(5)\n    print(\"a = \",a,\" a.dtype = \",a.dtype,\" a.shape  = \",a.shape)\n\n    m = array([arange(5),arange(10)])\n    print(\"m = \",m,\" m.dtype = \",m.dtype,\" m.shape  = \",m.shape)\n\n    t = arange(7, dtype = uint16)\n    print(\"t = \",t,\" t.dtype = \",t.dtype)\n\ndef array_property():\n    from numpy import arange\n    \n    a = arange(27).reshape(3,3,3)\n    print(\"a = \", a)\n    print(\"a.ndim = \",a.ndim)\n    print(\"a.size = \",a.size)\n    a.resize(3,9)\n    # print(\"a.resize = \", a.resize(3,9))\n    print(\"a = \", a)\n    print(\"a.T = \", a.T)\n    # p(\"a.T = \", a.T)\n\ndef lissajout():\n    import sys\n    from matplotlib.pyplot import plot,show\n    from numpy import linspace,pi,sin\n    \n    a = float(sys.argv[1] )\n    b = float(sys.argv[2] )\n    \n    t = linspace(-pi, pi, 201)\n    x = sin(a + t + pi / 2)\n    y = sin(b * t)\n    plot(x,y)\n    show()\n\ndef fourier():\n    from numpy.fft import fft, ifft\n    from matplotlib.pyplot import plot, show\n    from numpy import linspace, pi, cos, abs, all\n\n    x = linspace(0, 2 * pi, 30)\n    wave = cos(x)\n    transformed = fft(wave)\n    print(all(abs(ifft(transformed) -wave) < 10 ** -9))\n    plot(transformed)\n    show()\n\n    \ndef fourier2():\n    from numpy.fft import fft, ifft\n    from matplotlib.pyplot import plot, show\n    import numpy as np\n\n    x = np.linspace(0, 2 * np.pi, 30)\n    wave = np.cos(x)\n    transformed = fft(wave)\n    print(np.all(np.abs(ifft(transformed) -wave) < 10 ** -9))\n    plot(transformed)\n    show()\n\ndef plot_sinc():\n    from numpy import sinc, linspace\n    from matplotlib.pyplot import plot, show\n\n    x = linspace(0, 4, 100)\n    vals = sinc(x)\n\n    plot(x, vals)\n    show()\n\ndef plot_sinc2d():\n    from numpy import linspace, outer, sinc\n    from matplotlib.pyplot import imshow, show\n\n    x = linspace(0, 4, 100)\n    xx = outer(x,x)\n    vals = sinc(xx)\n\n    print(\"x = \", x, \" xx = \", xx, \"vals = \", vals)\n    imshow(vals)\n    show()\n\ndef kaiser():\n    from numpy import kaiser\n    from matplotlib.pyplot import plot, show\n\n    window = kaiser(42,14)\n    plot(window)\n    show()\n    \nif __name__ == '__main__':\n    # create_array()\n    # array_property()\n    # lissajout()\n    # print(sin(4))  # undefined\n    # fourier()\n    # fourier2()\n    # plot_sinc()\n    # plot_sinc2d()\n    kaiser()\n", "meta": {"hexsha": "11b7173114193a1da61a1c5b48d58fbc8791581c", "size": 2410, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python3/numpy_use/simple_array.py", "max_stars_repo_name": "combofish/chips-get", "max_stars_repo_head_hexsha": "6005f24d09edda3f1f54c6603205b2f854ec3b3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-01T01:56:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T01:56:51.000Z", "max_issues_repo_path": "Python3/numpy_use/simple_array.py", "max_issues_repo_name": "combofish/chips-get", "max_issues_repo_head_hexsha": "6005f24d09edda3f1f54c6603205b2f854ec3b3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python3/numpy_use/simple_array.py", "max_forks_repo_name": "combofish/chips-get", "max_forks_repo_head_hexsha": "6005f24d09edda3f1f54c6603205b2f854ec3b3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-26T03:32:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T05:29:46.000Z", "avg_line_length": 21.7117117117, "max_line_length": 64, "alphanum_fraction": 0.5643153527, "include": true, "reason": "import numpy,from numpy", "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.954647415574754, "lm_q2_score": 0.9005297881200701, "lm_q1q2_score": 0.8596884348769057}}
{"text": "import numpy as np\n\n#x should be [.....,1] for the bias term\ndef logit(x,theta):\n    return 1/(1+1/np.exp(x@theta))\n\ndef get_single_loss(x,y,theta,epsilon):\n    return y*np.log(max(logit(x,theta),epsilon))+(1-y)*np.log(max(1-logit(x,theta),epsilon))\n\ndef get_gradient(x,y,theta):\n    return y*x-x*logit(x,theta)\n\ndef get_loss(X,Y,theta,epsilon):\n    n=len(X[0])\n    loss=[]\n    for i in range(n):\n        loss.append(get_single_loss(X[i],Y[i],theta,epsilon))\n    return loss\n\nclass logistic_model:\n    def __init__(self):\n        self.theta=[]\n\n\n\n    def fit(self,X,Y,lr=0.01,limit=10000,epsilon=1e-4,verbose=True):\n\n\n        #initialize weights\n\n        n=len(X[0])\n        self.theta=np.random.rand(n)\n        # e is scalar\n        k=0\n        while k<limit:\n            for i in range(n):\n#                 print(X[i]@self.theta)\n#                 print(logit(X[i],self.theta))\n                self.theta=self.theta+lr*get_gradient(X[i],Y[i],self.theta)\n                k+=1\n                if k>limit:\n                    break\n#             print(X[0]@self.theta)\n#             print(logit(X[0],self.theta))\n#             print(get_gradient(X[0],Y[0],self.theta))\n#             print(logit(X[8],self.theta))\n            if verbose:\n                print(sum(get_loss(X,Y,self.theta,epsilon)))\n#             print(self.theta[:5])\n        return\n\n\n    def predict(self,X):\n        n=len(X)\n        res=[]\n        for i in range(n):\n            ind=logit(X[i],self.theta)\n            res.append(ind)\n        return res\n", "meta": {"hexsha": "f55941c5922206a2e822affdebfa237e66ca1e23", "size": 1521, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/logistic_regression.py", "max_stars_repo_name": "YichengPu/Relics", "max_stars_repo_head_hexsha": "95752a5ab62dae68bb261714709c66b260957cbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/logistic_regression.py", "max_issues_repo_name": "YichengPu/Relics", "max_issues_repo_head_hexsha": "95752a5ab62dae68bb261714709c66b260957cbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-05T02:48:53.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-03T20:18:24.000Z", "max_forks_repo_path": "models/logistic_regression.py", "max_forks_repo_name": "YichengPu/Relics", "max_forks_repo_head_hexsha": "95752a5ab62dae68bb261714709c66b260957cbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.35, "max_line_length": 92, "alphanum_fraction": 0.5266272189, "include": true, "reason": "import numpy", "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147153749275, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.8596527961412682}}
{"text": "from sympy import *\nfrom quaternion_R_utils import *\n\nfx,fy,cx,cy = symbols('fx fy cx cy');\npx, py, pz = symbols('px py pz')\nq0, q1, q2, q3 = symbols('q0 q1 q2 q3')\ntie_px, tie_py, tie_pz = symbols('tie_px tie_py tie_pz'); \nu_kp, v_kp = symbols('u_kp v_kp')\n\nposition_symbols = [px, py, pz]\nquaternion_symbols = [q0, q1, q2, q3]\ntie_point_symbols = [tie_px, tie_py, tie_pz]\nall_symbols = position_symbols + quaternion_symbols + tie_point_symbols\n\nRT_wc = matrix44FromQuaternion(px, py, pz, q0, q1, q2, q3)\nR_cw=RT_wc[:-1,:-1].transpose()\nT_wc=Matrix([px, py, pz]).vec()\nT_cw=-R_cw*T_wc\n\npoint_global=Matrix([tie_px, tie_py, tie_pz]).vec()\npoint_local = R_cw * point_global + T_cw;\ns = 1.0 / point_local[2];\nu = s * fx * point_local[0] + cx;\nv = s * fy * point_local[1] + cy;\nu_delta = u_kp - u;\nv_delta = v_kp - v;\n\nobs_eq = Matrix([u_delta, v_delta]).vec()\nobs_eq_jacobian = obs_eq.jacobian(all_symbols)\n\nprint(obs_eq)\nprint(obs_eq_jacobian)\n\nwith open(\"perspective_camera_quaternion_wc_jacobian.h\",'w') as f_cpp:  \n    f_cpp.write(\"inline void observation_equation_perspective_camera_quaternion_wc(Eigen::Matrix<double, 2, 1> &delta, double fx, double fy, double cx, double cy, double px, double py, double pz, double q0, double q1, double q2, double q3, double tie_px, double tie_py, double tie_pz, double u_kp, double v_kp)\\n\")\n    f_cpp.write(\"{\")\n    f_cpp.write(\"delta.coeffRef(0,0) = %s;\\n\"%(ccode(obs_eq[0,0])))\n    f_cpp.write(\"delta.coeffRef(1,0) = %s;\\n\"%(ccode(obs_eq[1,0])))\n    f_cpp.write(\"}\")\n    f_cpp.write(\"\\n\")\n    f_cpp.write(\"inline void observation_equation_perspective_camera_quaternion_wc_jacobian(Eigen::Matrix<double, 2, 10, Eigen::RowMajor> &j, double fx, double fy, double cx, double cy, double px, double py, double pz, double q0, double q1, double q2, double q3, double tie_px, double tie_py, double tie_pz)\\n\")\n    f_cpp.write(\"{\")\n    for i in range (2):\n        for j in range (10):\n            f_cpp.write(\"j.coeffRef(%d,%d) = %s;\\n\"%(i,j, ccode(obs_eq_jacobian[i,j])))\n    f_cpp.write(\"}\")\n    \n  \n\n", "meta": {"hexsha": "b45e2e20b5349885c910bdad6b6423b00ea6a975", "size": 2036, "ext": "py", "lang": "Python", "max_stars_repo_path": "codes/perspective_camera_quaternion_wc_jacobian.py", "max_stars_repo_name": "michalpelka/observation_equations", "max_stars_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "codes/perspective_camera_quaternion_wc_jacobian.py", "max_issues_repo_name": "michalpelka/observation_equations", "max_issues_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/perspective_camera_quaternion_wc_jacobian.py", "max_forks_repo_name": "michalpelka/observation_equations", "max_forks_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.72, "max_line_length": 314, "alphanum_fraction": 0.6876227898, "include": true, "reason": "from sympy", "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.9219218364639714, "lm_q1q2_score": 0.8596490651909448}}
{"text": "import argparse\nfrom math import pi\nimport numpy as np\nimport os\nimport pandas as pd\n\nMIN_RADIUS = 0.5\nMAX_RADIUS = 2.0\nMIN_HEIGHT = 0.5\nMAX_HEIGHT = 2.0\nADDED_ERROR = 0.1\nNUM_DECIMALS = 1\n\n\ndef generate_cylinder_df(size):\n    \"\"\"Generate a dataframe of cylinders where the radius and height of\n    each cylinder are both in the range 0.5 to 2.0 and the volume equals\n    (pi * r^2) * h. Then add up to a 10% error (uniformly distributed) to\n    the volume, followed by rounding off radius, height and volume to the\n    nearest 0.1.\n    \"\"\"\n\n    # Generate radiuses and heights\n    radius = np.random.uniform(MIN_RADIUS, MAX_RADIUS, size=size)\n    height = np.random.uniform(MIN_HEIGHT, MAX_HEIGHT, size=size)\n\n    # Calculate the correct volumes with those radiuses and heights\n    volume = (pi * radius ** 2) * height\n\n    # Add the error to the volumes\n    volume = volume * np.random.uniform(\n        1 - ADDED_ERROR,\n        1 + ADDED_ERROR,\n        size=size)\n\n    # Then round off radius, height and volume\n    radius = np.round(radius, decimals=NUM_DECIMALS)\n    height = np.round(height, decimals=NUM_DECIMALS)\n    volume = np.round(volume, decimals=NUM_DECIMALS)\n\n    df = pd.DataFrame({\n        'volume': volume,\n        'radius': radius,\n        'height': height, })\n\n    return df\n\n\nif __name__ == '__main__':\n    if ('get_ipython' not in dir()) & ('PYCHARM_HOSTED' not in os.environ):\n        # i.e. if run from the command line\n\n        # Handle command line arguments\n        parser = argparse.ArgumentParser()\n        parser.add_argument(\n            '--filename',\n            type=str,\n            help='the filename to save the cylinders to',\n            required=True)\n        parser.add_argument(\n            '--size',\n            type=int,\n            help='the number of cylinders to generate',\n            required=True)\n        # parser.add_argument(\n        #     '--job-dir',\n        #     help='this model ignores this field, but it is required by gcloud',\n        #     default='junk')\n        args = parser.parse_args()\n        arguments = args.__dict__\n        # arguments.pop('job_dir', None)\n\n        # Generate cylinders and write them to file\n        generate_cylinder_df(arguments['size']).to_csv(\n            arguments['filename'],\n            index=False)\n\n        print('saved {} cylinders to {}'.format(\n            arguments['size'],\n            arguments['filename']))\n\n    else:  # if run from a notebook or IDE\n        files_to_generate = {\n            'input/cylinders_train.csv': 8000,\n            'input/cylinders_eval.csv': 1000,\n            'input/cylinders_test.csv': 1000,}\n\n        for filename, size in files_to_generate.items():\n            generate_cylinder_df(size=size).to_csv(\n                filename,\n                index=False)\n\n            print('saved {} cylinders to {}'.format(\n                size,\n                filename))\n", "meta": {"hexsha": "abcaac2bc9e401798bc0d11984fbb745fb0d6060", "size": 2893, "ext": "py", "lang": "Python", "max_stars_repo_path": "courses/machine_learning/deepdive/03_tensorflow/d_traineval_challenge_exercise/generate_cylinders.py", "max_stars_repo_name": "harmtemolder/training-data-analyst", "max_stars_repo_head_hexsha": "04986ca36478befd7a80a4b0cbf4137ef918450d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "courses/machine_learning/deepdive/03_tensorflow/d_traineval_challenge_exercise/generate_cylinders.py", "max_issues_repo_name": "harmtemolder/training-data-analyst", "max_issues_repo_head_hexsha": "04986ca36478befd7a80a4b0cbf4137ef918450d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "courses/machine_learning/deepdive/03_tensorflow/d_traineval_challenge_exercise/generate_cylinders.py", "max_forks_repo_name": "harmtemolder/training-data-analyst", "max_forks_repo_head_hexsha": "04986ca36478befd7a80a4b0cbf4137ef918450d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1354166667, "max_line_length": 81, "alphanum_fraction": 0.6007604563, "include": true, "reason": "import numpy", "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.8962513765975758, "lm_q1q2_score": 0.8596433506244944}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import simps\nfrom numpy import trapz\nfrom scipy.integrate import quad\nx1= np.array([0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0])  \ny1=np.array([0.0,0.5,2.0,4.05,8.0,12.5,18.0,24.5,32.0,40.5,50.0])  \nh=0.1 ; a=x1[0] ; b=x1[9]\nn=int((b-a)/h) ; S=0.5*(y1[0]+y1[10]) ; S1 = y1[0]+y1[10] \nfor i in range(1,10):\n       if i%2 == 0:\n           S1 = S1 + 2 * y1[i]\n       else:\n           S1 = S1 + 4 * y1[i]\n       S+= y1[i]\nIntegral = S1 * h/3 ; Power = S * h\nprint(\"Power using trapezoidal and simpson\",(\"%f\"%Power,\"%f\"%Integral))\ndef trap(f,a,b,n):\n    h=(b-a)/n\n    S=0.5*(f(a)+f(b))\n    for i in range(1,n):\n        S+= f(a+i*h)\n    Integral = S * h\n    return Integral\ndef simpson(f,a,b,n):\n    h=(b-a)/n\n    S = f(a) + f(b)\n    for i in range(1,n):       \n        if i%2 == 0:\n            S = S + 2 * f(a + i*h)\n        else:\n            S = S + 4 * f(a + i*h)\n    Integral = S * h/3\n    return Integral\n     \ndef integration(f,a,b,n):\n    print(\"a =\",a,\"; b =\" ,b, \" ; Number of intervals =\",n)\n    h=(b-a)/n\n    x = np.linspace(a,b,n+1)\n    y = f(x)\n    inte , err = quad(f, a, b)   #absolute value taken for comparing my results \n    Integral_trap= trap(f,a,b,n)\n    Integral_simp=simpson(f,a,b,n)\n    print(\"Integral using scipy function (Quad) = \",inte) \n    print(\"Integral (using composite trapezoidal formula) = %f\" %Integral_trap)\n    print(\"Error in composite trapezoidal (by subtracting from the one i got from inbuilt quad)= \",abs(Integral_trap-inte))   \n    print(\"Integral (using composite simpson formula) = %f\" %Integral_simp)\n    print(\"Error in composite simpson (by subtracting from the one i got from inbuilt quad) = \",abs(Integral_simp-inte))\n    y_data_2,y_data,y_data_3=[],[],[]\n    geo= np.array([10**i for i in range(4) ])\n    n_array=np.arange(30,400,2)\n    h_array=(b-a)/n_array\n    for n in n_array:\n        x_data=np.linspace(a,b,n+1)\n        y_data.append(trap(f,a,b,n))\n        y_data_2.append(simpson(f,a,b,n))\n    d=[inte]*len(h_array)\n    y_data_3=np.array(d)\n    plt.plot(h_array,y_data,label=\"Trapezoidal rule\")\n    plt.scatter(h_array,y_data,label=\"Trapezoidal rule\")\n    plt.plot(h_array,y_data_2,label=\"Simpson's rule\")\n    plt.scatter(h_array,y_data_2,label=\"Trapezoidal rule\")\n    plt.plot(h_array,y_data_3,linestyle='--',label=\"scipy's simpson implementation\")\n    plt.xlabel(\"h\")\n    plt.ylabel(\"I(h)\")\n    plt.title(\"I(h) vs h plot [Convergence Test]\")\n    plt.legend()\n    plt.grid()\n    plt.xscale('log')\n    plt.show()\nf = lambda x : x*x\nintegration(f,0,10,100)\n", "meta": {"hexsha": "c8b42223320bebc50b669179bc435f3ee6d41f26", "size": 2582, "ext": "py", "lang": "Python", "max_stars_repo_path": "MP2_A1.py", "max_stars_repo_name": "pawan3091/pawan", "max_stars_repo_head_hexsha": "81f97bc50e844981831e5320e983d3dc6da629e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MP2_A1.py", "max_issues_repo_name": "pawan3091/pawan", "max_issues_repo_head_hexsha": "81f97bc50e844981831e5320e983d3dc6da629e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MP2_A1.py", "max_forks_repo_name": "pawan3091/pawan", "max_forks_repo_head_hexsha": "81f97bc50e844981831e5320e983d3dc6da629e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3698630137, "max_line_length": 126, "alphanum_fraction": 0.5914020139, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542864252023, "lm_q2_score": 0.8962513752119936, "lm_q1q2_score": 0.859643348249066}}
{"text": "import numpy as np\n\nfrom network.my_types import Data\n\n# Activation Functions\n\n\ndef null(_: float) -> float:\n    \"\"\"\n    Function that always returns 0\n    :param _: Input value to function\n    :type _: int\n    :return: Always 0\n    :rtype: int\n    \"\"\"\n    return 0\n\n\ndef sigmoid(x: float) -> float:\n    \"\"\"\n    Implementation of the Sigmoid activation function\n    :param x: Input value to function\n    :type x: float\n    :return: sigmoid(x)\n    :rtype: float\n    \"\"\"\n    return 1 / (1 + np.exp(-x))\n\n\ndef gaussian(x: float) -> float:\n    \"\"\"\n    Implementation of the Gaussian activation function\n    :param x: Input value to function\n    :type x: float\n    :return: gaussian(x)\n    :rtype: float\n    \"\"\"\n    return np.exp(-(x**2/2))\n\n\ndef identity(x: float) -> float:\n    \"\"\"\n    Identity function to be used in place of no activation function\n    :param x: Input value to function\n    :type x: float\n    :return: x\n    :rtype: float\n    \"\"\"\n    return x\n\n\n# Training Functions\ndef cubic(x: float) -> float:\n    \"\"\"\n    Cubic training function\n    :param x: Input value to function\n    :type x: float\n    :return: x^3\n    :rtype: float\n    \"\"\"\n    return x ** 3\n\n\ndef xor(x1: int, x2: int) -> int:\n    \"\"\"\n    xor training function\n    :param x1: Input value to function\n    :param x2: Input value to function\n    :type x1: int\n    :type x2: int\n    :return: x1 XOR x2\n    :rtype: int\n    \"\"\"\n    return x1 ^ x2\n\n\ndef complex_train(x1: float, x2: float) -> float:\n    \"\"\"\n    complex training function\n    :param x1: Input value to function\n    :param x2: Input value to function\n    :type x1: float\n    :type x2: float\n    :return: 1.9{ 1.35 + e^x1-x2 sin[13(x1 -0.6)^2]sin[7x2] }\n    :rtype: int\n    \"\"\"\n    return 1.9 * (1.35 + np.exp(x1 - x2) * np.sin(13*((x1-0.6)**2)) * np.sin(7*x2))\n\n\n# Error Functions\ndef mean_squared_error(predictions: Data, ground_truth: Data) -> float:\n    \"\"\"\n    Function to take the MSE (Mean Squared Error) of two equal length lists of output vectors.\n    Commonly used to take get the MSE of predictions from a network and the ground truth. All vectors in the list must\n    have equal length. While the order of the supplied lists doesn't matter, they are named for clarity and convention.\n    :param predictions: The predictions from a network\n    :type predictions: Data\n    :param ground_truth: The ground truths to compare against\n    :type ground_truth: Data\n    :return: The MSE (Mean Squared Error) of all supplied samples\n    :rtype: float\n    \"\"\"\n    # Ensure arguments are of the same length\n    if len(ground_truth) != len(predictions):\n        raise ValueError(f\"Number of predictions ({len(predictions)}) does not match ground \"\n                         f\"truth ({len(ground_truth)})\")\n\n    # As the function accepts single vectors or lists of vectors, make the arguments conform to expectations\n    if type(predictions[0]) == int:\n        predictions = [predictions]\n    if type(ground_truth[0]) == int:\n        ground_truth = [ground_truth]\n\n    # Create a list of the absolute summed error between corresponding vectors\n    per_sample_error = [sum(np.absolute(np.array(x) - np.array(y))) for x, y in zip(ground_truth, predictions)]\n\n    # Square error between samples and take the mean\n    return sum(np.array(per_sample_error) ** 2) / len(ground_truth)\n", "meta": {"hexsha": "ff7ba2e94cbfb7c6c9303d461faf37b45c9b9f0e", "size": 3307, "ext": "py", "lang": "Python", "max_stars_repo_path": "network/functions.py", "max_stars_repo_name": "JeromeIllgner/bioInspired", "max_stars_repo_head_hexsha": "37017e413f53dd3a2f5a64007853a58a93308cd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "network/functions.py", "max_issues_repo_name": "JeromeIllgner/bioInspired", "max_issues_repo_head_hexsha": "37017e413f53dd3a2f5a64007853a58a93308cd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "network/functions.py", "max_forks_repo_name": "JeromeIllgner/bioInspired", "max_forks_repo_head_hexsha": "37017e413f53dd3a2f5a64007853a58a93308cd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7899159664, "max_line_length": 119, "alphanum_fraction": 0.6434835198, "include": true, "reason": "import numpy", "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542805873232, "lm_q2_score": 0.8962513759047847, "lm_q1q2_score": 0.8596433436813523}}
{"text": "#Una caja contiene n_total transistores de los cuales n_funciona\n#funcionan correctamente y n_no_funciona no funcionan\n#correctamente. Los transistores se van probando uno a uno para ver si\n#funcionan. Una vez se prueba un transistor se retira de la caja y no\n#se devuelve. Sea N_1 el número de pruebas que se hicieron hasta\n#encontrar el primer transistor dañado y N_2 el número de pruebas\n#realizadas hasta encontrar el segundo transistor dañado. Escriba una\n#función de Python que encuentre la probabilidad conjunta de N_1 y N_2\n#usando un método Monte Carlo usando un número total de diez mil\n#iteraciones.  \n\n#La función debe llamarse probabilidad_conjunta.  La función toma como\n#entrada dos variables enteras n_funciona y n_no_funciona (en ese\n#orden). La función debe devolver un array bidimensional de numpy\n#(i.e. con filas y columnas). En cada dirección el array tiene\n#dimensión n_total+1. Al calificar la entrega vamos a llamar a la\n#función de la siguiente manera: \n\n# p = probabilidad_conjunta(n_funciona, n_no_funciona)\n\n# print(p[N_1, N_2])\n\n#donde n_funciona, n_no_funciona, N_1, y N_2 son variables enteras que\n#se inicializan al momento de calificar. \n\n# La función debe estar en un archivo llamado\n# \"ApellidoNombre_Ejercicio09.py\" donde Apellido y Nombre\n# debe reemplazarlos con su apellido y nombre.  Suba ese archivo como\n# respuesta a esta actividad. \n\n#Al ejecutar \"python ApellidoNombre_Ejercicio09.py\" o al\n#llamar la funci ón no se debe producir ningún error. \n\n# Solamente puede utilizar las funciones y métodos vistas en clase\n# (videos o clases sincrónicas, o que ya se encuentren en el\n# repositorio) . \n\nimport numpy as np\n\n\ndef probabilidad_conjunta(n_funciona, n_no_funciona):\n    funciona = 0\n    no_funciona = 1\n\n    transistores = np.array(n_funciona*[funciona] + n_no_funciona*[no_funciona])\n\n    n_total = n_funciona + n_no_funciona\n    probabilidad = np.zeros([n_total+1, n_total+1])\n    n_realizaciones = 100000\n    for i in range(n_realizaciones):\n        np.random.shuffle(transistores)\n    \n        intentos = np.arange(len(transistores))+1\n\n        intentos_sin_funcionar = intentos[transistores==no_funciona]\n\n        N_1 = intentos_sin_funcionar[0]\n        N_2 = intentos_sin_funcionar[1]\n        \n        probabilidad[N_1, N_2] += 1\n\n    probabilidad /= n_realizaciones\n    return probabilidad\n", "meta": {"hexsha": "12caed7e1b0403cc13e6d9c40f951b73b9217bae", "size": 2345, "ext": "py", "lang": "Python", "max_stars_repo_path": "Metodos Computacionales Uniandes/Code/ejercicio_09.py", "max_stars_repo_name": "aess14/Cursos-Uniandes", "max_stars_repo_head_hexsha": "be016b25f2f49788235fbe91ec577fd16b9ad613", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Metodos Computacionales Uniandes/Code/ejercicio_09.py", "max_issues_repo_name": "aess14/Cursos-Uniandes", "max_issues_repo_head_hexsha": "be016b25f2f49788235fbe91ec577fd16b9ad613", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Metodos Computacionales Uniandes/Code/ejercicio_09.py", "max_forks_repo_name": "aess14/Cursos-Uniandes", "max_forks_repo_head_hexsha": "be016b25f2f49788235fbe91ec577fd16b9ad613", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.640625, "max_line_length": 80, "alphanum_fraction": 0.7603411514, "include": true, "reason": "import numpy", "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188345, "lm_q2_score": 0.9136765187126079, "lm_q1q2_score": 0.8595775044600222}}
{"text": "# Inverse Kinematics \n# Analytical Solution \n# Given in \"Intro to Robotics by craig\" p.109\n\nimport numpy as np\n\ndef R3robot_IK(T_0N, output_unit='deg', solution1or2=1):\n    \"\"\"\n    TODO\n    \"\"\"\n\n    # constants\n    L1 = 4 # m\n    L2 = 3 # m\n    L3 = 2 # m\n\n    # 3 parameters for Planar Robots\n    # x, y, phi\n    cos_phi = T_03[0,0]\n    sin_phi = T_03[0,1]\n    phi = np.arccos(cos_phi)\n    x = T_03[0,3]\n    y = T_03[1,3]\n    if x==0 and y==0:\n        return \"theta 1 is arbitrary for (x,y)=(0,0)\"\n    cos_theta2 = (x**2 + y**2 - L1**2 - L2**2) / (2*L1*L2)\n    if cos_theta2<-1 or cos_theta2>1:\n        return \"solution does not exist\"\n    if solution1or2==1: # first solution\n        sin_theta2 = (1 - (cos_theta2**2))**0.5\n        theta2 = np.arctan2(sin_theta2, cos_theta2)\n        k2 = L2*sin_theta2\n    elif solution1or2==2: # seconds solution\n        sin_theta2 = -1*(1 - (cos_theta2**2))**0.5\n        theta2 = np.arctan2(sin_theta2, cos_theta2) # second solution\n        k2 = L2*sin_theta2\n    k1 = L1 + L2*cos_theta2\n    theta1 = np.arctan2(y,x) - np.arctan2(k2,k1)\n    theta3 = phi - theta1 - theta2\n\n    if output_unit.lower()==\"deg\":\n        return np.rad2deg(theta1), np.rad2deg(theta2), np.rad2deg(theta3)\n    return theta1, theta2, theta3\n\nif __name__ == \"__main__\":\n    from R3robot_FK import R3robot_FK\n    # T_03 = R3robot_FK(10,20,30,unit='deg')\n    # print(T_03)\n    T_03 = np.array([[1,0,0,9],[0,1,0,0],[0,0,1,0],[0,0,0,1]])\n    print(R3robot_IK(T_03,solution1or2=2))\n", "meta": {"hexsha": "f8db16661d4952f633ffe467dcaf5cd8647b490d", "size": 1489, "ext": "py", "lang": "Python", "max_stars_repo_path": "3R_robot_kinematics/R3robot_IK.py", "max_stars_repo_name": "parthp08/Robot_Kinematics", "max_stars_repo_head_hexsha": "49ce354cba81dfc3a04a9a53760fc0b847fc880a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3R_robot_kinematics/R3robot_IK.py", "max_issues_repo_name": "parthp08/Robot_Kinematics", "max_issues_repo_head_hexsha": "49ce354cba81dfc3a04a9a53760fc0b847fc880a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3R_robot_kinematics/R3robot_IK.py", "max_forks_repo_name": "parthp08/Robot_Kinematics", "max_forks_repo_head_hexsha": "49ce354cba81dfc3a04a9a53760fc0b847fc880a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1960784314, "max_line_length": 73, "alphanum_fraction": 0.5936870383, "include": true, "reason": "import numpy", "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561676667173, "lm_q2_score": 0.8872046041554923, "lm_q1q2_score": 0.8595736527183572}}
{"text": "import numpy as np\nimport scipy\n\ndef question_1_1(l=84):\n    A = np.zeros((l, l))\n    b = np.zeros(l)\n\n    for i in range(l):\n        A[i, i] = 6\n        if i != 0: A[i, i-1] = 8\n        if i != l-1: A[i, i+1] = 1\n\n        if i == 0: b[i] = 7\n        elif i == l-1: b[i] = 14\n        else: b[i] = 15\n\n    A = A.astype(np.float64)\n    b = b.astype(np.float64)\n    x = np.ones(l)\n    return A, b, x\n\ndef question_1_2_1(l=100):\n    A = np.zeros((l, l))\n    for i in range(l):\n        A[i, i] = 10\n        if i != 0: A[i, i-1] = 1\n        if i != l-1: A[i, i+1] = 1\n    b = np.random.rand(100)\n    x = scipy.linalg.solve(A, b) # scipy as the ground truth\n    return A, b, x\n    \n\ndef question_1_2_2(l=40):\n    A = np.zeros((l, l))\n    b = np.zeros(l)\n    for i in range(l):\n        for j in range(l):\n            A[i, j] = 1 / (i + j + 1);\n            b[i] += A[i, j]\n    x = np.ones(l)\n    return A, b, x\n\ndef question_4_1(n=100, a=1/2, epsilon=1):\n    def get_res(x):\n        return (1-a)/(1-np.e**(-1/epsilon))*(1-np.e**(-x/epsilon))+a*x\n    h = 1 / n\n    A = np.zeros((n-1, n-1))\n    b = np.zeros(n-1)\n    x = np.zeros(n-1)\n    for i in range(n-1):\n        b[i] = a * h**2\n        if i == n-2: b[i] -= epsilon + h # x[-1] = 0, x[n] = 1\n        x[i] = get_res((i+1)*h)\n        for j in range(n):\n            if i>0: A[i, i-1] = epsilon\n            A[i, i] = - (2 * epsilon + h)\n            if i<n-2: A[i, i+1] = epsilon + h\n    return A, b, x\n    \ndef question_6_1(a=[3, -5, 1]):\n    n = len(a)\n    A = np.zeros((n,n))\n    A[n-1, 0] = 1\n    A[n-1, n-1] = -a[n-1]\n    for i in range(1, n):\n        A[0, i] = -a[i-1]\n        if i > 1: A[i-1, i] = 1\n    return A\n\n", "meta": {"hexsha": "f2844e9ff05fa221917ead876e7ca6e525303406", "size": 1660, "ext": "py", "lang": "Python", "max_stars_repo_path": "laive/questions.py", "max_stars_repo_name": "ashawkey/laive", "max_stars_repo_head_hexsha": "3cc62967ea16e0bb81eff01c2489d15c44f60696", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "laive/questions.py", "max_issues_repo_name": "ashawkey/laive", "max_issues_repo_head_hexsha": "3cc62967ea16e0bb81eff01c2489d15c44f60696", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "laive/questions.py", "max_forks_repo_name": "ashawkey/laive", "max_forks_repo_head_hexsha": "3cc62967ea16e0bb81eff01c2489d15c44f60696", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7142857143, "max_line_length": 70, "alphanum_fraction": 0.4259036145, "include": true, "reason": "import numpy,import scipy", "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561703644736, "lm_q2_score": 0.8872045952083047, "lm_q1q2_score": 0.8595736464432812}}
{"text": "import numpy as np\nimport math\nimport scipy.stats as stats\n\n'''\nModule for misc. statistical methods \nfor time series data\n'''\n\n# Detrends the target values of a time series\n# by subtracting the residuals resulting\n# from linear regression. \n# Returns a 3-tuple\n# containing the vector of the detrended time series,\n# and the slope and intercept of the regression line\ndef detrend(x,y):\n\tresult = stats.linregress(x,y)\n\tslope = result[0]\n\tintercept = result[1]\n\tdetrended = []\n\tfor val in range(len(y)):\n\t\tpred = slope*val+intercept\n\t\tresidual = y[val]-pred\n\t\tdetrended.append(residual)\n\treturn (detrended,slope,intercept)\n\n# Applies a linear trend to a series of data points\n# i.e. a[z] = y[z] + trend\n#           = y[z] + slope*x[z] + intercept\ndef reapplyTrend(x,y,slope,intercept):\n\trev = np.zeros(len(y))\n\tfor dex in range(len(y)):\n\t\trev[dex] = y[dex] + (slope*x[dex]+intercept)\n\treturn rev\n\n# Performs linear regression on univariate time\n# series repr. by xTrain,yTrain, and then makes predictions\n# for xTest\n# Returns a 1-d vector representing predictions\ndef predictLinearRegression(xTrain,yTrain,xTest):\n\tresult = stats.linregress(xTrain,yTrain)\n\tslope = result[0]\n\tintercept = result[1]\n\tpredict = np.zeros(len(xTest))\n\tfor x in range(len(xTest)):\n\t\tpredict[x] = slope*xTest[x]+intercept\n\treturn predict\n\n# Performs linear regression on univariate time\n# series repr. by xTrain,yTrain, and then makes predictions\n# for xTest\n# Returns a 1-d vector representing predictions\ndef predictPolyRegression(xTrain,yTrain,xTest,deg):\n\tcoeff = np.polyfit(xTrain,yTrain,deg)\n\tpredict = np.zeros(len(xTest))\n\tfor x in range(len(xTest)):\n\t\tfor c in range(len(coeff)):\n\t\t\tpredict[x] += coeff[c]*math.pow(xTest[x],len(coeff)-c-1)\n\treturn predict\n\n# Computes the Mean Squared Error for predicted values against\n# actual values\ndef meanSquareError(actual,pred):\n\tif (not len(actual) == len(pred) or len(actual) == 0):\n\t\treturn -1.0\n\ttotal = 0.0\n\tfor x in range(len(actual)):\n\t\ttotal += math.pow(actual[x]-pred[x],2)\n\treturn total/len(actual)\n\n# Computes Normalized Root Mean Square Error (NRMSE) for\n# predicted values against actual values\ndef normRmse(actual,pred):\n\tif (not len(actual) == len(pred) or len(actual) == 0):\n\t\treturn -1.0\n\tsumSquares = 0.0\n\tmaxY = actual[0]\n\tminY = actual[0]\n\tfor x in range(len(actual)):\n\t\tsumSquares += math.pow(pred[x]-actual[x],2.0)\n\t\tmaxY = max(maxY,actual[x])\n\t\tminY = min(minY,actual[x])\n\treturn math.sqrt(sumSquares/len(actual))/(maxY-minY)\n\n# Computes Mean Absolute Percent Error (MAPE) for predicted\n# values against actual values\ndef mape(actual,pred):\n\tif (not len(actual) == len(pred) or len(actual) == 0):\n\t\treturn -1.0\n\ttotal = 0.0\n\tfor x in range(len(actual)):\n\t\ttotal += abs((actual[x]-pred[x])/actual[x])\n\treturn total/len(actual)\n\n# Estimates missing data denoted by <targ> in\n# a list of lists <data> by averaging the neighboring\n# values if they exist, otherwise the mean of the entire\n# list (i.e. if a missing value is at the start or end of\n# a list)\ndef estimateMissing(data,targ):\n    for x in range(len(data)):\n        for y in range(len(data[x])):\n            if (data[x][y] == targ):\n                if (y > 0 and y < len(data[x])-1):\n                    data[x][y] = (data[x][y-1]+data[x][y+1])/2.0\n                else:\n                    data[x][y] = np.mean(data[x])", "meta": {"hexsha": "200ac7fcef0a445b747c10af2bb595e0d39cf9eb", "size": 3328, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/statistics.py", "max_stars_repo_name": "anruly/Load-Forecasting", "max_stars_repo_head_hexsha": "839efa1a937d999e8f0ec854b5d374e6eba03f9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2015-06-04T13:26:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T11:02:58.000Z", "max_issues_repo_path": "src/statistics.py", "max_issues_repo_name": "anruly/Load-Forecasting", "max_issues_repo_head_hexsha": "839efa1a937d999e8f0ec854b5d374e6eba03f9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-07T22:41:20.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-23T01:21:34.000Z", "max_forks_repo_path": "src/statistics.py", "max_forks_repo_name": "anruly/Load-Forecasting", "max_forks_repo_head_hexsha": "839efa1a937d999e8f0ec854b5d374e6eba03f9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34, "max_forks_repo_forks_event_min_datetime": "2016-06-24T18:08:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T05:37:41.000Z", "avg_line_length": 31.1028037383, "max_line_length": 64, "alphanum_fraction": 0.6853966346, "include": true, "reason": "import numpy,import scipy", "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561730622295, "lm_q2_score": 0.8872045922259088, "lm_q1q2_score": 0.8595736459472297}}
{"text": "import matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\n\nimport numpy as np\nfrom scipy.stats import norm\n\n# Create an array of points to use as the x-coordinates for plotting the normal distribution\nx_min = norm.ppf(0.00005) # we will plot 99.99 % of the normal curve.\nx_max = norm.ppf(0.99995)\nx = np.linspace(x_min, x_max, 201)\n\nplt.style.use('seaborn-whitegrid')\n\n# paramaters for the normal distribution\nmu = 2\nsigma = 3\n\n# how to translate between different scales on the x-axis'\ndef toZscore(x):\n    return ((x - mu) / sigma)\n\ndef fromZscore(x):\n    return ((sigma * x) + mu)\n\n# get a reference to a frozen version of the normal function with the loc and scale paramaters set.\nn = norm(loc=mu, scale=sigma)\n\n# Rebuild the array of points to use as the x-coordinates for plotting the normal distribution\nx_min = n.ppf(0.000005) # we will plot 99.999 % of the normal curve.\nx_max = n.ppf(0.999995)\nx = np.linspace(x_min, x_max, 201)\n\n# create a figure and an axes\nfig, ax = plt.subplots()\nfig.set_figheight(6)\nfig.set_figwidth(8)\n\n# Create an Axes object that shares an x axis with the ax Axes that we just created above.\nax2 = ax.twinx()\n\n# format that axis as a percentage.\nax2.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))\n\n# the second curve we want to plot, the CDF.\nax2.plot(x,\n         n.cdf(x),\n         label='Cumulative Distribution\\n Function norm.cdf(x, loc={}, scale={})'.format(mu, sigma),\n         lw=2,\n         color='green'\n        )\n\n# plot our normal function.\nax.plot(x,\n        n.pdf(x),\n        label='Normal Distribution\\n norm.pdf(x, loc={}, scale={})'.format(mu, sigma)\n       )\n\n# add our points of interest\nax.plot(fromZscore(-1.96),\n        n.pdf(fromZscore(-1.96)),\n        color='red',\n        marker='o',\n        alpha=0.5\n       )\nax.plot(fromZscore(1.96),\n        n.pdf(fromZscore(1.96)),\n        color='red',\n        marker='o',\n        alpha=0.5\n       )\n# add vertical lines\nax.vlines(x=[fromZscore(-1.96), fromZscore(1.96)],\n          ymin=[0, 0],\n          ymax=[n.pdf(fromZscore(-1.96)), n.pdf(fromZscore(1.96))],\n          color='red',\n          alpha=0.5\n         )\n\n# add axis labels, title and legend\nax.set_xlabel('X')\nax.set_ylabel('Probability')\nax.set_title('The Normal (Gaussian) Distribution')\n\n# customize our legend\nfig.legend(\n    fontsize='small',\n    loc='upper left',\n    framealpha=0.5,\n    bbox_to_anchor=(0.15, 0.85) # note that here the coordinates are relative the the whole figure\n)\n\n# add some text.  By default the xy are in the axes coordinates\n# but that can be changed with transformations\nax.text(-3.3*sigma, \n        n.pdf(fromZscore(-1.96)),\n        '$(-1.96\\sigma, {0:.2})$'.format(n.pdf(fromZscore(-1.96)))\n       )\nax.text(2.1 * sigma + mu,\n        n.pdf(1.96*sigma + mu),\n        '$(1.96\\sigma, {0:.2})$'.format(n.pdf(fromZscore(1.96)))\n       )\n\n# add fill below the normal curve\n# create an array of x-values to plot against\nx2=np.linspace(x_min, n.ppf(0.025))\nax.fill_between(x2, n.pdf(x2), alpha=0.75, facecolor='lightblue')\n\n# add annotation.  By default the xy are in the axes coordinates\n# but that can be changed with transformations\ntext_string ='This area is equal to\\nthe value of the CDF at\\n'\ntext_string += 'the right boundary.\\nIn this case the right\\nboundary is at $-1.96\\sigma$\\n'\ntext_string += 'where $\\sigma$ = {} and the\\n area is $2.50\\%$ of the\\n area under the curve.'.format(sigma)\nax.annotate(\n    text_string,\n    xy=(-2.1*sigma + mu, n.pdf(fromZscore(-1.96))/3),\n    xytext=(2*sigma + mu,0.05),\n    arrowprops=dict(arrowstyle='->'))\n\n# add a horizontal line from the CDF to the right axis and a point at the intersection\nax2.hlines(y=n.cdf(fromZscore(-1.96)),\n           xmin=-1.96*sigma + mu,\n           xmax=x_max,\n           color='green',\n           alpha=0.5\n          )\n# add our dot\nax2.plot(fromZscore(-1.96), n.cdf(fromZscore(-1.96)), marker='o', color='green', alpha=0.4)\n\n# add text to highlight the value of the CDF at -0.96\nax2.text(x_max,0.04, '$2.5\\%$'.format(n.cdf(fromZscore(-1.96))))\n\n# adjust the transparency and color of the grids for each axex object\nax.grid(visible=True, color='blue', alpha=.2)\nax2.grid(visible=True, color='green', alpha=0.2)\n\n# add a vertical dashed line at the mean, -sigma and sigma.\nax.vlines(x=mu, ymin=0, ymax=n.pdf(mu), linestyle='dotted')\nax.vlines(x=[mu-sigma, mu+sigma], ymin=0, ymax=n.pdf(mu+sigma), linestyle='dotted')\nax.text(mu+0.02, \n        n.pdf(mu)/12,\n        '$\\mu$ = {}'.format(mu)\n       )\nax.text(mu+sigma+0.02, \n        n.pdf(mu)/12,\n        '$\\mu + \\sigma$'\n       )\nax.text(mu-sigma+0.02, \n        n.pdf(mu)/12,\n        '$\\mu - \\sigma$'\n       )\n\n# add an additional x-axis\n# shift the original axes object up\nfig.subplots_adjust(bottom=0.2)\nax3 = ax.secondary_xaxis(-0.08, functions=(toZscore, fromZscore))\nax3.set_xlabel('Standard Deviations')\nax3.xaxis.set_label_coords(-.11,-0.1)\nax3.set_xticks([x for x in range(-4,6)], minor=True)\nax3.tick_params(length = 10, which='major', direction='in')\nax3.tick_params(length= 10, which='minor', direction='inout')\n# add tics to our primary x axis\nax.tick_params(length = 10, which='major', direction='in')\nax.tick_params(length= 5, which='minor', direction='inout')\nax.set_xticks([x for x in range(-10,16)], minor=True)\n\n# move our initial x-axis label off the the left.\nax.xaxis.set_label_coords(-0.02, -0.025)\n\n\n#plt.show()\nplt.savefig('figure_3.png', bbox_inches='tight')\n", "meta": {"hexsha": "ee899698de803b90c58ba501720c2f17e0c23c78", "size": 5414, "ext": "py", "lang": "Python", "max_stars_repo_path": "final.py", "max_stars_repo_name": "grtyvr/Matplotlib_using_normal_dist_part_2", "max_stars_repo_head_hexsha": "47c683c4a58c96c1b3e090cd36fa3e761320d12a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "final.py", "max_issues_repo_name": "grtyvr/Matplotlib_using_normal_dist_part_2", "max_issues_repo_head_hexsha": "47c683c4a58c96c1b3e090cd36fa3e761320d12a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "final.py", "max_forks_repo_name": "grtyvr/Matplotlib_using_normal_dist_part_2", "max_forks_repo_head_hexsha": "47c683c4a58c96c1b3e090cd36fa3e761320d12a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.476744186, "max_line_length": 108, "alphanum_fraction": 0.6533062431, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235895, "lm_q2_score": 0.907312213841788, "lm_q1q2_score": 0.8595703974857357}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 11 17:30:16 2020\r\n\r\n@author: Dilay Ercelik\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pickle\r\n\r\n\r\n# Loads python pickle file\r\nwith open('c10p1.pickle', 'rb') as f:\r\n    data = pickle.load(f)\r\n    \r\n\r\nc10p1 = data['c10p1']\r\n\r\n\r\nprint('Code for Question 1:', '\\n')\r\n\r\n# Given the input correlation matrix Q:\r\nQ = np.array([[0.2, 0.1],[0.1, 0.3]])\r\n\r\n# Calculates the eigenvalues ev and the eigenvectors e of the matrix Q:\r\nev, e = np.linalg.eig(Q)\r\n\r\nprint(ev)\r\nprint(e)\r\n\r\n\r\n# If we allow learning to go on for a long period of time,\r\n# w becomes the principal eigenvector of matrix Q\r\n# i.e. the eigenvector e of Q with the greater corresponding eigenvalue ev\r\n\r\n# Finds the index of the greatest eigenvalue of the 2 eigenvectors of Q\r\nmax_ev_index = ev.argmax()\r\n\r\n\r\n# Prints the expected w for a learning for a long period of time\r\nw_long_learning = 2 * e[:, max_ev_index] \r\n\r\nprint('If we allow learning to go on for a long period of time, w = {}'.format(w_long_learning))\r\n\r\n\r\n\r\n# Question 1 is not related to Questions 7-8-9\r\n\r\nprint('Code for Question 7:', '\\n')\r\n\r\n\r\ndef normal(data):\r\n    \"\"\"\r\n    Performs a \"zero-mean centering step\", or normalisation, on the input data\r\n\r\n    Parameters\r\n    ----------\r\n    data : float\r\n        Input data (x, y).\r\n\r\n    Returns\r\n    -------\r\n    normal_data : float\r\n        Normalised input data.\r\n\r\n    \"\"\"\r\n    mean = np.mean(data, axis = 0)\r\n    \r\n    normal_data = data - mean\r\n    \r\n    return normal_data\r\n\r\n\r\n# Creates our_normal_data from the raw data c10p1\r\nour_normal_data = normal(c10p1)\r\n\r\n\r\n# Visualisation of our_normal_data\r\n# To make sure our transformed data is zero-mean centered\r\nplt.figure(1)\r\nplt.scatter(our_normal_data[:, 0], our_normal_data[:, 1], c = 'r', marker = 'o')\r\nplt.title('Oja\\'s rule: data cloud centered around (0,0)')\r\nplt.xlabel('u1 (input 1)')\r\nplt.ylabel('u2 (input 2)')\r\n                     \r\n    \r\n# Implements the update rule for Oja's rule\r\neta = 1\r\nalpha = 1\r\ndelta_t = 0.01\r\n\r\n# Creates our random first w value: w_zero\r\nw_zero = w = np.random.rand(2) \r\n\r\n# Implementing the updating rule to update w for a number of iterations (e.g. 500).\r\n# Oja's rule for updating w\r\nfor step in np.arange(0, 500, 1):\r\n    \r\n    plt.figure(1)\r\n    u = our_normal_data[np.remainder(step, our_normal_data.shape[0]), :]\r\n    v = u @ w     # @ is used for matrix multiplication\r\n    w = w + delta_t * eta * (v * u - alpha * v * v * w)\r\n    plt.plot(v, marker = '^',  c = 'g')\r\n    plt.plot(w[0], w[1], marker = '*', c = 'b')\r\n   \r\n    \r\n\r\n\r\n# Calculates the correlation matrix C (formula given in the quiz)\r\n# Because our_normal_data is mean_centered, C is also its covariance matrix.\r\n# our_normal_data.shape[0] gives the number M of lines (the number of samples in our_normal_data)\r\nC = np.dot(our_normal_data.T, our_normal_data) / our_normal_data.shape[0]\r\n\r\n# Prints the correlation/covariance matrix C of our_normal_data\r\nprint('This is the correlation/covariance matrix C of our mean-centered data (our_normal_data): {}'.format(C), '\\n')\r\n\r\n# Calculates the eigenvalues ev and the eigenvectors e of the matrix C:\r\nev, e = np.linalg.eig(C)\r\n\r\n# Prints eigenvalues (ev) and eigenvectors (e: 2D vectors) of \r\n# the correlation matrix C of the mean-centered data (our_normal_data)\r\nprint('The eigenvalues of the correlation/covariance matrix C of our_normal_data are {} and {}'.format(ev[0], ev[1]), '\\n')\r\n\r\nprint('The eigenvectors of the correlation/covariance matrix C of our_normal_data are {} and {}'.format(e[0], e[1]), '\\n')\r\n\r\n\r\n# Answer to Question 7:\r\n## \"The correlation matrix C has only one principal eigenvector,\r\n## but there two vectors of length 1/alpha that are parallel to this eigenvector.\r\n## w can converge to either of these two vectors.\"\r\n\r\n### Note to myself:\r\n# The eigenvector corresponding to the eigenvalue of largest magnitude is called the principal eigenvector.\r\n\r\n\r\n    \r\nprint('Code for Question 8:', '\\n')   \r\n\r\n# Creates our_normal_data with adjusted mean: data2, not zero-mean centered\r\nconstants = [2, 2]\r\ndata2 = our_normal_data + np.tile(constants, (our_normal_data.shape[0], 1))\r\n\r\n\r\n# Visualisation of data2\r\nplt.figure(2)\r\nplt.scatter(data2[:, 0], data2[:, 1], marker = 'o',  c = 'r')\r\nplt.title('Oja\\'s rule: data2 cloud')\r\nplt.xlabel('u1 (input 1)')\r\nplt.ylabel('u2 (input 2)')\r\n\r\n\r\n# Creates our random first w value for the second data (not zero-mean centered data)\r\nw2 = w_zero \r\n\r\n# Implementing the updating rule to update w for a number of iterations (e.g. 500).\r\n# Oja's rule for updating w\r\nfor step in np.arange(0, 500, 1):\r\n    \r\n    plt.figure(2)\r\n    u = data2[np.remainder(step, data2.shape[0]), :]\r\n    v = u @ w2\r\n    w2 = w2 + delta_t * eta * (v * u - alpha * v * v * w2)\r\n    plt.plot(v, marker = '^',  c = 'g')\r\n    plt.plot(w2[0], w2[1], marker = '*',  c = 'b')\r\n    \r\n\r\n# Answer to question 8:\r\n## \"The two vectors that w (w2) converges to in different runs of the algorithm\r\n## are parallel to the vector that points roughly towards the mean of the data (data2).\"\r\n    \r\n \r\n\r\nprint('Code for Question 9:', '\\n')   \r\n\r\n# Visualisation \r\nplt.figure(3)\r\nplt.scatter(our_normal_data[:, 0], our_normal_data[:, 1], marker = 'o',  c = 'r')\r\nplt.title('Data cloud for Hebb Rule')\r\nplt.xlabel('u1 (input 1)')\r\nplt.ylabel('u2 (input 2)')\r\n\r\n# Creates our random first w value for the third data (our_normal_data with Hebb Rule)\r\nw3 = w_zero \r\n\r\n# Implementing the updating rule to update w for a number of iterations (e.g. 500).\r\n# Hebb rule for updating w\r\n\r\nfor step in np.arange(0, 500, 1):\r\n    \r\n    plt.figure(3)\r\n    u = our_normal_data[np.remainder(step, our_normal_data.shape[0]), :]\r\n    v = u @ w3\r\n    plt.plot(v, marker='^',  c='b')\r\n    w3 = w3 + delta_t * eta * (v * u)  # Hebb Rule\r\n    plt.plot(v, marker = '^',  c = 'g')\r\n    plt.plot(w3[0], w3[1], marker = '*',  c = 'b')\r\n\r\n    \r\n    \r\nplt.show()\r\n    \r\n \r\n# Answer to Question 9:\r\n## \"The vectors found by the Hebb learning rule have the same direction \r\n## as those found by Oja's rule (on our_normal_data, in Question 7),\r\n## but the length (of w3) grows without bound as a function of the number of iterations.\r\n    \r\n    \r\n    ", "meta": {"hexsha": "11045af6eeb8a50277876f588792b29ae6db457a", "size": 6212, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week 7/quiz_7.py", "max_stars_repo_name": "dilayercelik/CompNeuro_Washington", "max_stars_repo_head_hexsha": "edbd12e69531f840f119e5b26786e4ac6c9c1855", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week 7/quiz_7.py", "max_issues_repo_name": "dilayercelik/CompNeuro_Washington", "max_issues_repo_head_hexsha": "edbd12e69531f840f119e5b26786e4ac6c9c1855", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week 7/quiz_7.py", "max_forks_repo_name": "dilayercelik/CompNeuro_Washington", "max_forks_repo_head_hexsha": "edbd12e69531f840f119e5b26786e4ac6c9c1855", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.580952381, "max_line_length": 124, "alphanum_fraction": 0.6439150032, "include": true, "reason": "import numpy", "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666345, "lm_q2_score": 0.9073122144683576, "lm_q1q2_score": 0.8595703940354863}}
{"text": "import numpy as np\nfrom scipy.linalg import hilbert\n\ndef cholesky(A):\n\t# return np.linalg.cholesky(A)\n\tn = A.shape[0]\n\tL = np.zeros_like(A)\n\tfor k in range(n):\n\t\tL[k, k] = (A[k, k] - ((L[k, :k] ** 2).sum() if k > 0 else 0)) ** .5\n\t\tfor i in range(k + 1, n):\n\t\t\tL[i, k] = (A[i, k] - L[i, :k].dot(L[k, :k])) / L[k, k]\n\treturn L\n\ndef solve(n, delta=0):\n\tprint('n =', n, ', delta =', delta)\n\tH = hilbert(n)\n\tx = np.zeros(n) + 1 + delta\n\tb = H.dot(x)\n\tL = cholesky(H)\n\t# Hx = b, H = LL'\n\t# LL'x = b\n\t# x = L'^-1 L^-1 b\n\txp = np.linalg.solve(L.T, np.linalg.solve(L, b))\n\tr = b - H.dot(xp)\n\tdx = xp - x\n\tprint('||r||_inf:', abs(r).max())\n\tprint('||dx||_inf:', abs(dx).max())\n\ndef gen36():\n\tprint('t36 result'.center(30, '-'))\n\tsolve(10)\n\tsolve(10, 1e-7)\n\tsolve(8)\n\tsolve(12)\n\tprint('end t36'.center(30, '-')+'\\n')\n\nif __name__ == '__main__':\n\tgen36()\n", "meta": {"hexsha": "c00e6be55e3793a40198174fd35416ca0cb50f88", "size": 844, "ext": "py", "lang": "Python", "max_stars_repo_path": "数值分析/t36.py", "max_stars_repo_name": "jasnzhuang/Personal-Homework", "max_stars_repo_head_hexsha": "edf633ce94f22a646786b85e133797339cf9fc3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 463, "max_stars_repo_stars_event_min_datetime": "2019-10-25T04:28:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:03:44.000Z", "max_issues_repo_path": "数值分析/t36.py", "max_issues_repo_name": "1002753959/Undergraduate", "max_issues_repo_head_hexsha": "95e6e95a98f53e350d628edacad0042382c6a464", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-28T08:05:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-28T08:26:34.000Z", "max_forks_repo_path": "数值分析/t36.py", "max_forks_repo_name": "1002753959/Undergraduate", "max_forks_repo_head_hexsha": "95e6e95a98f53e350d628edacad0042382c6a464", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 201, "max_forks_repo_forks_event_min_datetime": "2019-04-10T07:17:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-15T09:46:30.000Z", "avg_line_length": 21.641025641, "max_line_length": 69, "alphanum_fraction": 0.528436019, "include": true, "reason": "import numpy,from scipy", "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629194, "lm_q2_score": 0.9111797045849583, "lm_q1q2_score": 0.8595591702338459}}
{"text": "\"\"\"\nOptimizer Module\n\"\"\"\n\nimport numpy as np\n\ndef derivative(f, x, epsilon = 1e-10):\n    \"\"\"\n    Calculate derivative of f at x\n\n    ...\n\n    Parameters\n    ---\n    f : Function to calculate derivative for\n    x : Value at which to calculate derivative\n    epsilon(optional): Adjustable precision\n\n    Returns\n    ---\n    value: Derivative of f at x\n    \"\"\"\n\n    x_ = x + epsilon\n    value = (f(x_) - f(x)) / epsilon\n\n    return value\n\ndef newton_method(f, x_init = 0, epsilon = 1e-10):\n    \"\"\"\n    Newton Raphson Optimizer\n\n    ...\n\n    Parameters\n    ---\n    f: Function to calculate root for\n    x_init(optional) : initial value of x\n    epsilon(optional): Adjustable precision\n\n    Returns\n    ---\n    x: Value of root\n    \"\"\"\n    prev_value = x_init + 2 * epsilon\n    value = x_init\n\n    iterations = 0\n    while abs(prev_value - value) > epsilon:\n        prev_value = value\n\n        f_dash = derivative(f, value)\n        value = value - f(value) / f_dash\n\n        iterations += 1\n\n    print(f\"Newton Method converged in {iterations} iterations\")\n\n    return value\n\n    ", "meta": {"hexsha": "5ddb7485e0277fe7cd91bdb42ecf9bfd1d8bbdeb", "size": 1075, "ext": "py", "lang": "Python", "max_stars_repo_path": "Part-9-NewtonMethod/tools/optimizers.py", "max_stars_repo_name": "SakshayMahna/Robotics-Mechanics", "max_stars_repo_head_hexsha": "3fa4b5860c4c9b4e22bd8799c0edc08237707aef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Part-9-NewtonMethod/tools/optimizers.py", "max_issues_repo_name": "SakshayMahna/Robotics-Mechanics", "max_issues_repo_head_hexsha": "3fa4b5860c4c9b4e22bd8799c0edc08237707aef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Part-9-NewtonMethod/tools/optimizers.py", "max_forks_repo_name": "SakshayMahna/Robotics-Mechanics", "max_forks_repo_head_hexsha": "3fa4b5860c4c9b4e22bd8799c0edc08237707aef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-16T08:18:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T08:18:52.000Z", "avg_line_length": 17.6229508197, "max_line_length": 64, "alphanum_fraction": 0.5953488372, "include": true, "reason": "import numpy", "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211324, "lm_q2_score": 0.9111797142327147, "lm_q1q2_score": 0.8595591677249758}}
{"text": "##### BT: y = 4 + 3x\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nnp.random.seed(2)\n\nX = np.random.rand(1000, 1)\ny = 4 + 3*X + 0.2 * np.random.rand(1000, 1)     # noise added\n\n# Building Xbar\nmatrixOne = np.ones((X.shape[0], 1))\nXbar = np.concatenate((matrixOne, X), axis = 1)\nprint Xbar\n\n\ndef grad(w):\n    \"\"\" Dao ham \"\"\"\n    N = Xbar.shape[0]\n    return 1/N * Xbar.T.dot(Xbar.dot(w) - y)\n\ndef cost(w):\n    \"\"\" Cost function \"\"\"\n    N = Xbar.shape[0]\n    return .5/N*np.linalg.norm(y - Xbar.dot(w), 2)**2\n\n\nA = np.dot(Xbar.T, Xbar)\nb = np.dot(Xbar.T, y)\nw_lr = np.dot(np.linalg.pinv(A), b)\n\nprint('Solution found by formula: w = ',w_lr.T)\n\n\ndef numerical_grad(w, cost):\n    eps = 1e-4\n    g = np.zeros_like(w)\n    for i in range(len(w)):\n        w_p = w.copy()\n        w_n = w.copy()\n        w_p[i] += eps\n        w_n[i] -= eps\n        g[i] = (cost(w_p) - cost(w_n))/(2*eps)\n    return g\n\ndef check_grad(w, cost, grad):\n    w = np.random.rand(w.shape[0], w.shape[1])\n    grad1 = grad(w)\n    grad2 = numerical_grad(w, cost)\n    return True if np.linalg.norm(grad1 - grad2) < 1e-6 else False\n\nprint( 'Checking gradient...', check_grad(np.random.rand(2, 1), cost, grad))\n\ndef myGD(w_init, grad, eta):\n    w = [w_init]\n    temp = 0\n    for it in range(100):\n        w_new = w[-1] - eta*grad(w[-1])\n        temp += 1\n        if np.linalg.norm(grad(w_new))/len(w_new) < 1e-3:\n            break\n        w.append(w_new)\n    return (w, temp)\n\nw_init = np.array([[2], [1]])\n(w1, it1) = myGD(w_init, grad, 1)\nprint('Solution found by GD: w = ', w1[-1].T, ',\\nafter %d iterations.' %(it1+1))\n\n\n# Display result\nw = w_lr\nw_0 = w[0][0]\nw_1 = w[1][0]\nx0 = np.linspace(0, 1, 2, endpoint=True)\ny0 = w_0 + w_1*x0\n\n# Draw the fitting line\nplt.plot(X.T, y.T, 'b.')     # data\nplt.plot(x0, y0, 'y', linewidth = 2)   # the fitting line\nplt.axis([0, 1, 0, 10])\nplt.show()", "meta": {"hexsha": "de665c5542a4aad72673f7b13fecbe512864d122", "size": 1875, "ext": "py", "lang": "Python", "max_stars_repo_path": "3_gradient_descent/gd_linear_regression.py", "max_stars_repo_name": "nguyenthieu95/machine_learning", "max_stars_repo_head_hexsha": "40595a003815445a7a9fef7e8925f71d19f8fa30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-30T20:10:07.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-30T20:10:07.000Z", "max_issues_repo_path": "3_gradient_descent/gd_linear_regression.py", "max_issues_repo_name": "ThieuNv/machine_learning", "max_issues_repo_head_hexsha": "40595a003815445a7a9fef7e8925f71d19f8fa30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3_gradient_descent/gd_linear_regression.py", "max_forks_repo_name": "ThieuNv/machine_learning", "max_forks_repo_head_hexsha": "40595a003815445a7a9fef7e8925f71d19f8fa30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-23T15:30:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T15:30:16.000Z", "avg_line_length": 22.8658536585, "max_line_length": 81, "alphanum_fraction": 0.5674666667, "include": true, "reason": "import numpy", "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.9111797009670495, "lm_q1q2_score": 0.8595591624671289}}
{"text": "# estimate delta, gamma, theta, veta\n\"\"\"\n  Name     : c10_39_greeks.py\n  Book     : Python for Finance (2nd ed.)\n  Publisher: Packt Publishing Ltd. \n  Author   : Yuxing Yan\n  Date     : 6/6/2017\n  email    : yany@canisius.edu\n             paulyxy@hotmail.com\n\"\"\"\n\nfrom scipy import log,exp,sqrt,stats\n#\ntiny=1e-9\nS=40\nX=40\nT=0.5\nr=0.01\nsigma=0.2\n\ndef bsCall(S,X,T,r,sigma):\n    d1=(log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T))\n    d2 = d1-sigma*sqrt(T)\n    return S*stats.norm.cdf(d1)-X*exp(-r*T)*stats.norm.cdf(d2)\n\ndef delta1(S,X,T,r,sigma):\n    d1=(log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T))\n    return stats.norm.cdf(d1)\n\ndef delta2(S,X,T,r,sigma):\n    s1=S\n    s2=S+tiny\n    c1=bsCall(s1,X,T,r,sigma)\n    c2=bsCall(s2,X,T,r,sigma)\n    delta=(c2-c1)/(s2-s1)\n    return delta\n\nprint(\"delta (close form)=\", delta1(S,X,T,r,sigma))\nprint(\"delta (tiny number)=\", delta2(S,X,T,r,sigma))\n", "meta": {"hexsha": "4d30a063cae7d730862e5ed43de2c287c45e0817", "size": 891, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter10/c10_38_greeks.py", "max_stars_repo_name": "John-ye666/Python-for-Finance-Second-Edition", "max_stars_repo_head_hexsha": "dabef09bcdd7b0ec2934774741bd0a7e1950de73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 236, "max_stars_repo_stars_event_min_datetime": "2017-07-02T03:06:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:15:33.000Z", "max_issues_repo_path": "Chapter10/c10_38_greeks.py", "max_issues_repo_name": "John-ye666/Python-for-Finance-Second-Edition", "max_issues_repo_head_hexsha": "dabef09bcdd7b0ec2934774741bd0a7e1950de73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter10/c10_38_greeks.py", "max_forks_repo_name": "John-ye666/Python-for-Finance-Second-Edition", "max_forks_repo_head_hexsha": "dabef09bcdd7b0ec2934774741bd0a7e1950de73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 139, "max_forks_repo_forks_event_min_datetime": "2017-06-30T10:28:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T19:43:34.000Z", "avg_line_length": 22.275, "max_line_length": 62, "alphanum_fraction": 0.6116722783, "include": true, "reason": "from scipy", "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.9111797003640646, "lm_q1q2_score": 0.8595591575445329}}
{"text": "import numpy as np\n\n### Function def\ndef sigmoid(x):\n    \"\"\"Sigmoid function\"\"\"\n    return 1 / (1 + np.exp(-x))\n\ndef stable_log(x):\n    \"\"\"A more stable version of the log\"\"\"\n    eps = 1e-15\n    return np.log(x + eps)\n\n### Loss functions\ndef compute_loss_ls(y, tx, w):\n    \"\"\"Computes the loss of the least squares\"\"\"\n    N = len(y)\n    e = y - tx @ w\n    loss = 1/(2*N) * e.T @ e\n    \n    return loss\n\ndef compute_loss_ce(y, tx, w):\n    \"\"\"Computes the cross entropy loss for the sigmoid function\"\"\"\n    eps = 1e-15\n    N = len(y)\n    Z = tx @ w\n    y_ = sigmoid(Z)\n    pos_mask = y > 0\n\n    loss = -(1/N) * (stable_log(y_[pos_mask]).sum() + stable_log(1 - y_[~pos_mask]).sum())\n    \n    return loss\n\ndef compute_loss_reg_ce(y, tx, w, lambda_):\n    \"\"\"Loss of the regularised cross entropy\"\"\"\n    return compute_loss_ce(y, tx, w)  + lambda_/2 * np.linalg.norm(w)**2\n\n### Gradient of loss functions\ndef compute_gradient_ls(y, tx, w):\n    '''Gradient of least squares'''\n    N = len(y)\n    e = y - tx @ w\n    gradient = -(1/N) * tx.T @ e\n    \n    return gradient\n\ndef compute_gradient_logreg(y, tx, w):\n    '''Gradient of logistic regression with cross entropy loss'''\n    \n    N = len(y)\n    e = sigmoid(tx @ w) - y\n    gradient = tx.T @ e\n    \n    return gradient\n\ndef compute_gradient_reg_logreg(y, tx, w, lambda_):\n    '''Gradient of regularised logistic regression with cross entropy loss'''\n    usual_grad = compute_gradient_logreg(y, tx, w)\n    \n    return usual_grad + lambda_*w\n", "meta": {"hexsha": "c94ff6853db29160dddda94b3f83690a21c1cb98", "size": 1486, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/cost.py", "max_stars_repo_name": "Nacho114/ml-project-1", "max_stars_repo_head_hexsha": "d6e368f56e1ff4a89d1aba84dac2907d61ac0e7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cost.py", "max_issues_repo_name": "Nacho114/ml-project-1", "max_issues_repo_head_hexsha": "d6e368f56e1ff4a89d1aba84dac2907d61ac0e7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cost.py", "max_forks_repo_name": "Nacho114/ml-project-1", "max_forks_repo_head_hexsha": "d6e368f56e1ff4a89d1aba84dac2907d61ac0e7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-01T08:31:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T08:31:10.000Z", "avg_line_length": 24.3606557377, "max_line_length": 90, "alphanum_fraction": 0.6036339166, "include": true, "reason": "import numpy", "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138138113965, "lm_q2_score": 0.8791467580102418, "lm_q1q2_score": 0.8595539296741185}}
{"text": "import numpy as np\nfrom autodiff import jacobian, sin\ndef linfit(x, y, yerr=None):\n    \"\"\"\n    Solves the linear least squares. That is solves the linear system\n\n    A*p=y where A = [x 1]\n\n    Using the QR-decomposition A=QR, the optimal b can be estimated as\n    p = R^(-1)*Q^T*y\n    \"\"\"\n\n\n    N = len(x)\n    #If no errors specified, just set them all to 1\n    if yerr is None:\n        yerr = np.ones((N,1), dtype=np.float64)\n    yerr = yerr.reshape(N,1)\n\n\n    x = x.reshape(N,1)\n    #W = np.matrix(np.diag(1/(yerr.flatten())))\n\n    A = np.matrix(np.hstack((x,np.ones((N,1)))))\n    #We want to calculate W*A, but W is just a diagonal matrix. If we just elementwise multiply the diagonal and A, this will be much faster\n    #Q, R = np.linalg.qr(W*A)\n    Q, R = np.linalg.qr(np.multiply(yerr,A))\n\n    #Create these as matricies to make the multiplication prettier\n    Q, R, y = np.matrix(Q), np.matrix(R), y.reshape(N,1)\n\n    #Again, W*y is horribly inefficient. Just multiply yerr and y elementwise. Since they both are ndarrays, we can just * them to do this\n    #p = R**(-1)*Q.T*W*y\n    p = (R**(-1)*Q.T)*(yerr*y)\n\n\n    chi2 = float(sum(np.power((y-x*p[0]+p[1]),2)/(yerr**2)))\n    dof = N-1\n    chi2_red = chi2/dof\n\n    return {'p':p, 'chi2_red':chi2_red, 'f': lambda x: f(x, p)}\n\ndef nonlinfit(f, x, y, p, yerr=None, tol=1e-11, maxiter=50):\n    \"\"\"\n    Finds the best parameters using least squares\n\n    If J is the jacobian, W the weight, and Q*R=WJ the qr-decomposition, then the update vector p' is\n    p' = R^-1 * Q^T* (y-f(x,p)).\n    \n    This is then used to update the estimate for the parameter p_i+1 = p_i + p'\n    \"\"\"\n\n    if isinstance(f, str):\n        f = eval('lambda x,p: '+ f)\n\n    N = len(x)\n    num_param = len(p)\n\n    #Convert all input to numpy arrays of specific type and shape\n    y = np.asarray(y, dtype=np.float64).reshape(N, 1)\n    x = np.asarray(x, dtype=np.float64).reshape(N, 1)\n    p = np.asarray(p, dtype=np.float64).reshape(num_param,1)\n    \n\n    #If no errors specified, just set them all to 1\n    if yerr is None:\n        yerr = np.ones((N,1), dtype=np.float64)\n    yerr = yerr.reshape(N,1)\n\n\n    chi2 = sum(np.power((y-f(x,p)),2)/(yerr**2))\n    dof = N-num_param\n    chi2_red = chi2/dof\n\n    for _ in range(maxiter):\n        delta_y = y-f(x,p)\n        J = jacobian(f, x, p)\n        \n        #We want to calculate W*J, but W is just a diagonal matrix. If we just elementwise multiply the diagonal and J, this will be much faster\n        #Q, R = np.linalg.qr(W*J)\n        Q, R = np.linalg.qr(np.multiply(yerr,J))\n\n        #Create these as matricies to make multiplication prettier\n        Q, R, J = np.matrix(Q), np.matrix(R), np.matrix(J)\n        \n        #Again, W*delta_y is horribly inefficient. Just multiply yerr and delta_y elementwise. Since they both are ndarrays, we can just * them to do this\n        #p = p + R**(-1)*Q.T*W*delta_y\n        p = p + (R**(-1)*Q.T) * (yerr*delta_y)\n\n        #p need to be in the right format\n        p=np.asarray(p)\n        \n        #Check for convergence\n        chi2_tmp = float(sum(np.power((y-f(x,p)),2)/(yerr**2)))\n        chi2_red_tmp = chi2_tmp/(N-num_param)\n        diff = abs(chi2_red-chi2_red_tmp)\n        print(\"reduced chi2 = %0.4E   diff = %0.4E\"%(chi2_red_tmp, diff))\n        if diff<tol:\n            print(\"Converged!\")\n            return {'p':p, 'chi2_red':chi2_red_tmp, 'f': lambda x: f(x, p)}\n        \n        #Update chi2 value, and print progress\n        chi2_red = chi2_red_tmp\n\n\n    print(\"Hit max number of iterations without converging!!\")\n    return {'p':p, 'chi2_red':chi2_red_tmp, 'f': lambda x: f(x, p)}\n\nif __name__ == \"__main__\":\n    def f(x,p):\n        return p[0]*(x**2) + p[1]*x+p[2]*sin(x)\n\n    x = np.arange(0,100,1/10)\n    y = f(x,[3,5,1000]) + np.random.normal(0,1,len(x))\n\n    pp=nonlinfit(f,x,y,[2,7,1000])\n\n", "meta": {"hexsha": "aad25084f6d80e7c7435b879e838f0c25d354d52", "size": 3822, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyfitting/fit.py", "max_stars_repo_name": "jeppe742/pyfitting", "max_stars_repo_head_hexsha": "d6dcfa182fb26f9e41c2eb9ddf5073fc4be332c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyfitting/fit.py", "max_issues_repo_name": "jeppe742/pyfitting", "max_issues_repo_head_hexsha": "d6dcfa182fb26f9e41c2eb9ddf5073fc4be332c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyfitting/fit.py", "max_forks_repo_name": "jeppe742/pyfitting", "max_forks_repo_head_hexsha": "d6dcfa182fb26f9e41c2eb9ddf5073fc4be332c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3898305085, "max_line_length": 154, "alphanum_fraction": 0.5915750916, "include": true, "reason": "import numpy", "num_tokens": 1223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.8991213860551287, "lm_q1q2_score": 0.8595432788332783}}
{"text": "import numpy as np\nimport pandas as pd\nfrom scipy.optimize import root\nfrom scipy.integrate import odeint\nfrom __future__ import division\nfrom scipy import *\nfrom pylab import *\nimport matplotlib.pyplot as plt\n#%matplotlib inline\n\n\nxo = 0.5\ngamma = 0.8\nyr = 0.1 #kg kgCO2 −1\nTAO = 15\n\n\n# en la matriz parametros se define cada conbinación (xk, A) como una fila de la matriz\nparametros = np.array([[0.1, 1],[0.3, 2],[0.4, 4]])\nparametros\n\n\ndef intervalosExtraccion(tao, xk, A):\n    tao1 = (xo - xk) / (gamma * A * yr)\n    tao2 = tao1 + xk / (gamma * A * yr) * np.log(xk / xo + (1 - xk / xo) * np.exp(xo / xk * A))\n    zk = xk / (A * xo) * np.log((xo * np.exp(gamma * A * yr / xk * (tao - tao1)) - xk) / (xo - xk))\n\n    return tao1, tao2, zk\n\n\n\ndef modeloLack(tao, xk, A):\n    \n    tao1, tao2, zk = intervalosExtraccion(tao, xk, A)\n    \n    if tao <= tao1 and tao < tao2:\n        e = gamma * yr* tao * (1- np.exp(- A))\n        print(\"tao < tao1 and tao < tao2\")\n        return e\n    if tao > tao1 and tao <= tao2:\n        zk = xk / (A * xo) * np.log((xo * np.exp(gamma * A * yr / xk * (tao - tao1)) - xk) / (xo - xk))\n        e = gamma * yr * (tao - tao1 * np.exp(- A * (1 - zk)))\n        print(\"tao >= tao1 and tao < tao2\")\n        return e\n    if tao > tao2:\n        e = xo - xk / A * np.log(1 + xk / xo * (np.exp(xo / xk * A) - 1) * np.exp(gamma * A * yr / xk * (tao1 - tao)))\n        print(\"tao >= tao2\")\n        return e\n\n\nrendimiento = [[modeloLack(tao, xk, A) for tao in np.linspace(0,TAO)] for xk, A in parametros]\n\n\n\ndef graficarLack():\n\n\tTao = np.linspace(0,TAO)\n\t# plt.plot(Tao, caso1[2],label=\"xk=0.3\")\n\t# plt.plot(Tao,caso2[2],label=\"xk=0.1\")\n\t# plt.plot(Tao,caso3[2],label=\"xk=0.4\")\n\t\n\tplt.plot(Tao, rendimiento[0],label=\"xk=0.3\")\n\tplt.plot(Tao, rendimiento[1],label=\"xk=0.1\")\n\tplt.plot(Tao, rendimiento[2],label=\"xk=0.4\")\n\tplt.title(\"Modelo Lack\")\n\tplt.xlabel(\" $tao $ \")\n\tplt.ylabel(\"Rendimiento e\")\n\tplt.legend()\n\n\treturn 0\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "01d5b5ff9683354d9782ac930360b7391e7d6dc7", "size": 1959, "ext": "py", "lang": "Python", "max_stars_repo_path": "modelos.py", "max_stars_repo_name": "pysg/sepy", "max_stars_repo_head_hexsha": "9b81a2064719eb30d8f05a3e6504687f9f68f578", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modelos.py", "max_issues_repo_name": "pysg/sepy", "max_issues_repo_head_hexsha": "9b81a2064719eb30d8f05a3e6504687f9f68f578", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modelos.py", "max_forks_repo_name": "pysg/sepy", "max_forks_repo_head_hexsha": "9b81a2064719eb30d8f05a3e6504687f9f68f578", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5274725275, "max_line_length": 118, "alphanum_fraction": 0.5671260847, "include": true, "reason": "import numpy,from scipy", "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813463747181, "lm_q2_score": 0.8991213853793453, "lm_q1q2_score": 0.8595432725492482}}
{"text": "# -*- coding: UTF-8 -*- \nimport os\nimport numpy as np \ndef zeroMean(dataMat):        \n\tmeanVal = np.mean(dataMat, axis = 0) \n\tnewData = dataMat - meanVal  \n\treturn newData,meanVal \n\ndef eigValPct(eigVals,percentage):  \n    sortArray = np.sort(eigVals) \n    sortArray = sortArray[-1::-1] \n    arraySum = np.sum(sortArray)  \n    tmpSum = 0  \n    num = 0  \n    for i in sortArray:  \n        tmpSum += i  \n        num += 1  \n        if tmpSum >= arraySum * percentage:  \n            return num  \n\n\ndef pca(dataMat,percentage=0.95):\n\tmeanRemoved, meanVals = zeroMean(dataMat) \n\tcovMat = np.cov(meanRemoved,rowvar=0)  \n\teigVals, eigVects = np.linalg.eig(np.mat(covMat))  \n\tk = eigValPct(eigVals,percentage) \n\teigValInd = np.argsort(eigVals)  \n\teigValInd = eigValInd[-1:-(k+1):-1] \n\tredEigVects = eigVects[:,eigValInd] \n\tlowDDataMat = meanRemoved * redEigVects \n\treconMat = (lowDDataMat * redEigVects.T) + meanVals \n\treturn lowDDataMat, reconMat\n\ndef readData(filename):\n\twith open(filename, 'r') as f:\n\t\tf.readline()\n\t\tstringArr = [line.strip().split('\\t')[1:] for line in f.readlines()]\n\t\tdataArr = [map(float, line) for line in stringArr]\n\t\treturn np.mat(dataArr).T\ndef format(value):\n    return \"%.5f\" % value\n\t\t\ndef writeData(filename, feature):\n\tfeature = np.array(feature)\n\tformatted = [[format(v) for v in r] for r in feature]\n\twith open(filename, 'w') as f:\n\t\tfor i in range(feature.shape[0]):\n\t\t\tfor j in range(feature.shape[1]):\n\t\t\t\tf.write(formatted[i][j])\n\t\t\t\tf.write('\\t')\n\t\t\tf.write('\\n')\n\ndef check(filename):\n\twith open(filename, 'r') as f:\n\t\tf.readline()\n\t\ttypes = [line.strip().split('\\t')[1] for line in f.readlines()]\n\tclassType = list()\n\tfor type in types:\n\t\tif type not in classType:\n\t\t\tclassType.append(type)\n\treturn classType\n\t\n\nif __name__ == '__main__':\n\tfilename = '../data/microarray.original.txt'\n\t#filename = '../data/finalData.txt'\n\t#filename = '../data/processedData_0.95.txt'\n\tlabelfile = '../data/E-TABM-185.sdrf.txt'\n\tclassType = check(labelfile)\n\tprint \"The number of class is {}\".format(len(classType))\n\tprint classType\n\tfeature = readData(filename)\n\tprint \"Finish reading the data. The number is {}. The dimensions of feature are {}\".format(feature.shape[0], feature.shape[1])\n\tfilename = '../data/processedData_0.85.txt'\n\tnew_feature, _ = pca(feature, 0.85)\n\tprint \"Feature is reduced to {} dimensions.\".format(new_feature.shape[1])\n\twriteData(filename, new_feature)\n\tprint \"New feature has been written. The number is {}. The new dimensions are {}\".format(new_feature.shape[0], new_feature.shape[1])\n", "meta": {"hexsha": "9f1afba36886357deadf88033efedcc9b45a721a", "size": 2534, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/dimReduce.py", "max_stars_repo_name": "ZhengtianXu/Gene_Chip", "max_stars_repo_head_hexsha": "f7b8e84bdaf8963923de16443fac22ce11df5714", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2017-11-24T00:22:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T06:11:57.000Z", "max_issues_repo_path": "src/dimReduce.py", "max_issues_repo_name": "ZhengtianXu/Gene_Chip", "max_issues_repo_head_hexsha": "f7b8e84bdaf8963923de16443fac22ce11df5714", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dimReduce.py", "max_forks_repo_name": "ZhengtianXu/Gene_Chip", "max_forks_repo_head_hexsha": "f7b8e84bdaf8963923de16443fac22ce11df5714", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-06-24T09:04:35.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-24T09:04:35.000Z", "avg_line_length": 32.0759493671, "max_line_length": 133, "alphanum_fraction": 0.6708760852, "include": true, "reason": "import numpy", "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813513911654, "lm_q2_score": 0.8991213691605412, "lm_q1q2_score": 0.859543261554769}}
{"text": "import numpy as np\n\n\ndef forrester(x: np.ndarray):\n    \"\"\"The forrester function.\n\n    Parameters\n    ----------\n    x : np.ndarray of shape (n_samples, 1)\n        The input locations.\n\n    Returns\n    -------\n    np.ndarray of shape (n_samples,)\n        The function values at `x`.\n    \"\"\"\n    return ((6 * x - 2) ** 2 * np.sin(12 * x - 4)).flatten()\n\n\ndef bohachevsky(x: np.ndarray):\n    \"\"\"The bohachevsky function.\n\n    Parameters\n    ----------\n    x : np.ndarray of shape (n_samples, 2)\n        The input locations.\n\n    Returns\n    -------\n    np.ndarray of shape (n_samples,)\n        The function values at `x`.\n    \"\"\"\n    x1 = x[:, 0]\n    x2 = x[:, 1]\n\n    return (\n        x1 ** 2\n        + 2 * x2 ** 2\n        - 0.3 * np.cos(3 * np.pi * x1)\n        - 0.4 * np.cos(4 * np.pi * x2)\n        + 0.7\n    )\n", "meta": {"hexsha": "3f284f70a2f354259e0f747bcf876004cd3ea0a1", "size": 812, "ext": "py", "lang": "Python", "max_stars_repo_path": "bopy/benchmark_functions.py", "max_stars_repo_name": "TomPretty/bopy", "max_stars_repo_head_hexsha": "940ad1f2935219304495f5b129cc8dde22b49f4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-06T13:43:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-06T13:43:25.000Z", "max_issues_repo_path": "bopy/benchmark_functions.py", "max_issues_repo_name": "TomPretty/bopy", "max_issues_repo_head_hexsha": "940ad1f2935219304495f5b129cc8dde22b49f4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2020-02-14T21:52:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-04T20:40:13.000Z", "max_forks_repo_path": "bopy/benchmark_functions.py", "max_forks_repo_name": "TomPretty/bopy", "max_forks_repo_head_hexsha": "940ad1f2935219304495f5b129cc8dde22b49f4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-12T11:43:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-06T13:43:27.000Z", "avg_line_length": 18.8837209302, "max_line_length": 60, "alphanum_fraction": 0.4827586207, "include": true, "reason": "import numpy", "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426412951847, "lm_q2_score": 0.8824278633625322, "lm_q1q2_score": 0.8595223667821072}}
{"text": "# nelder-mead for multimodal function optimization\nfrom scipy.optimize import minimize\nfrom numpy.random import rand\nfrom numpy import exp\nfrom numpy import sqrt\nfrom numpy import cos\nfrom numpy import e\nfrom numpy import pi\n\n# objective function\ndef objective(v):\n\tx, y = v\n\treturn -20.0 * exp(-0.2 * sqrt(0.5 * (x**2 + y**2))) - exp(0.5 * (cos(2 * pi * x) + cos(2 * pi * y))) + e + 20\n\n# define range for input\nr_min, r_max = -5.0, 5.0\n# define the starting point as a random sample from the domain\npt = r_min + rand(2) * (r_max - r_min)\n# perform the search\nresult = minimize(objective, pt, method='nelder-mead')\n# summarize the result\nprint('Status : %s' % result['message'])\nprint('Total Evaluations: %d' % result['nfev'])\n# evaluate solution\nsolution = result['x']\nevaluation = objective(solution)\nprint('Solution: f(%s) = %.5f' % (solution, evaluation))\n", "meta": {"hexsha": "809c4adc712d38290cf284e7efcb91e063e28096", "size": 861, "ext": "py", "lang": "Python", "max_stars_repo_path": "Books/code/chapter_12/12_optimize_ackley.py", "max_stars_repo_name": "Mikma03/Optimization_in_Machine_Learning", "max_stars_repo_head_hexsha": "257d0455d4ae0b4fc7a762eda841a16611c49000", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-30T11:07:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:07:28.000Z", "max_issues_repo_path": "Books/code/chapter_12/12_optimize_ackley.py", "max_issues_repo_name": "Mikma03/Optimization_in_Machine_Learning", "max_issues_repo_head_hexsha": "257d0455d4ae0b4fc7a762eda841a16611c49000", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Books/code/chapter_12/12_optimize_ackley.py", "max_forks_repo_name": "Mikma03/Optimization_in_Machine_Learning", "max_forks_repo_head_hexsha": "257d0455d4ae0b4fc7a762eda841a16611c49000", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.75, "max_line_length": 111, "alphanum_fraction": 0.6922183508, "include": true, "reason": "from numpy,from scipy", "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426405416754, "lm_q2_score": 0.8824278602705732, "lm_q1q2_score": 0.8595223631054897}}
{"text": "import sympy\nfrom sympy.utilities import lambdify\n\n# f(x) = (x**2 -2x)e**(3-x)\n\nx = sympy.symbols('x')\n\nf = (x**2 - 2*x)*sympy.exp(3 - x)\n\n# differentiate\nfp = sympy.simplify(sympy.diff(f))  # (x*(2 - x) + 2*x - 2)*exp(3 - x)\n\n# Check differentiate mually\nfp2 = (2*x - 2)*sympy.exp(3 - x) - (x**2 - 2*x)*sympy.exp(3 - x)\nsympy.simplify(fp2 - fp) == 0  # True\n\n# integrate\nF = sympy.integrate(f, x)  # -x**2*exp(3 - x)\n\n# This converts a SymPy expression to a numerical expression that uses the NumPy\n# equivalents of the SymPy standard functions to evaluate the expressions numerically\nlam_f = lambdify(x, f)\nlam_fp = lambdify(x, fp)\n", "meta": {"hexsha": "872f422f66b41e6a22df28c6d314e62eb074b77c", "size": 634, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapter3/usingSymPy.py", "max_stars_repo_name": "onggieoi/python-math", "max_stars_repo_head_hexsha": "7cc6193516c4e4b4a05a90d9cac9285cfce2bea6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-08T09:32:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T09:32:30.000Z", "max_issues_repo_path": "chapter3/usingSymPy.py", "max_issues_repo_name": "onggieoi/python-math", "max_issues_repo_head_hexsha": "7cc6193516c4e4b4a05a90d9cac9285cfce2bea6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter3/usingSymPy.py", "max_forks_repo_name": "onggieoi/python-math", "max_forks_repo_head_hexsha": "7cc6193516c4e4b4a05a90d9cac9285cfce2bea6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4166666667, "max_line_length": 85, "alphanum_fraction": 0.6482649842, "include": true, "reason": "import sympy,from sympy", "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9833429629196684, "lm_q2_score": 0.8740772286044095, "lm_q1q2_score": 0.8595176917964724}}
{"text": "# coding: utf-8\n# linear_regression/regression.py\nimport numpy as np\nimport matplotlib as plt\nimport time\n\n# compute execution time\ndef exeTime(func):\n    def newFunc(*args, **args2):\n        t0 = time.time()\n        back = func(*args, **args2)\n        return back, time.time() - t0\n    return newFunc\n\n# h(x)\ndef h(theta, x):\n    return (theta.T*x)[0,0]\n\n# cost function\ndef J(theta, X, y):\n    m = len(X)\n    return (X*theta-y).T*(X*theta-y)/(2*m)\n\n# gradient descent optimizer function\n@exeTime\ndef gradientDescentOptimizer(rate, maxLoop, epsilon, X, y):\n    \"\"\"\n    Args:\n    rate: learning rate\n    maxLoop: maximum iteration number\n    epsilon: precision\n\n    Returns:\n        (theta, errors, thetas), timeConsumed\n    \"\"\"\n    m,n = X.shape\n    # initialize theta\n    theta = np.zeros((n,1))\n    count = 0\n    converged = False\n    error = float('inf')\n    errors = []\n    thetas = {}\n    for j in range(n):\n        thetas[j] = [theta[j,0]]\n    while count<=maxLoop:\n        if(converged):\n            break\n        count = count + 1\n        for j in range(n):\n            ############################################\n            # YOUR CODE HERE!\n            # deriv = ??\n            deriv = -(X*theta-y).T*X[:, j]/m\n            ############################################\n            theta[j,0] = theta[j,0]+rate*deriv\n            thetas[j].append(theta[j,0])\n        error = J(theta, X, y)\n        errors.append(error[0,0])\n        if(error < epsilon):\n            converged = True\n    return theta,errors,thetas\n\n# standarize function\ndef standarize(X):\n    m, n = X.shape\n    # normalize each feature\n    for j in range(n):\n        features = X[:,j]\n        meanVal = features.mean(axis=0)\n        std = features.std(axis=0)\n        if std != 0:\n            X[:, j] = (features-meanVal)/std\n        else:\n            X[:, j] = 0\n    return X\n", "meta": {"hexsha": "437d84d309f70082d866d88580dde2568e86fb8a", "size": 1854, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear regression/regression.py", "max_stars_repo_name": "kayzhang/LearningML", "max_stars_repo_head_hexsha": "afdfbd73d97ac93b98be29643a5e2f674d4e221b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear regression/regression.py", "max_issues_repo_name": "kayzhang/LearningML", "max_issues_repo_head_hexsha": "afdfbd73d97ac93b98be29643a5e2f674d4e221b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear regression/regression.py", "max_forks_repo_name": "kayzhang/LearningML", "max_forks_repo_head_hexsha": "afdfbd73d97ac93b98be29643a5e2f674d4e221b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0779220779, "max_line_length": 59, "alphanum_fraction": 0.5124056095, "include": true, "reason": "import numpy", "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799472560582, "lm_q2_score": 0.8918110360927155, "lm_q1q2_score": 0.859509593327808}}
{"text": "from statistics import mean\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport random\n\nstyle.use('ggplot')\n\n# XS = np.array([1, 2, 3, 4, 5, 6, 1, 4], dtype=np.float64)\n# YS = np.array([5, 4, 6, 5, 6, 7, 1, 4], dtype=np.float64)\n\n\n# noinspection PyPep8Naming,PyShadowingNames\ndef best_fit_slope_finder(features, labels):\n    m = (((mean(XS) * mean(YS)) - mean(XS * YS)) /\n         ((mean(XS) ** 2) - (mean(XS * XS))))\n    return m\n\n\ndef y_intercept_finder(features, labels):\n    b = (mean(YS) - m * mean(XS))\n    return b\n\n\ndef squared_error(point, line):\n    return sum((line - point) ** 2)\n\n\ndef coefficient_of_determination(point, line):\n    global y_mean_line\n    y_mean_line = [mean(point) for i in point]\n    squared_error_regression = squared_error(point, line)\n    squared_error_y_mean = squared_error(point, y_mean_line)\n    return 1 - (squared_error_regression / squared_error_y_mean)\n\n\n# noinspection PyPep8Naming,PyPep8Naming\ndef create_dataSet(hm, variance, step=2, correlation=False):\n    val = 1\n    # noinspection PyPep8Naming\n    YS = []\n    for i in range(hm):\n        data = val + random.randrange(-variance, variance)\n        YS.append(data)\n        if correlation and correlation == 'pos':\n            val += step\n        elif correlation and correlation == 'neg':\n            val -= step\n    XS = [i for i in range(len(YS))]\n    return np.array(XS, dtype=np.float64), np.array(YS, dtype=np.float64)\n\n\nXS, YS = create_dataSet(1000, 500, 7, correlation='pos')\n\nm = best_fit_slope_finder(XS, YS)\n\nb = y_intercept_finder(XS, YS)\n\n# Gets coordinates for best fit line plot\nregression_line = []\nfor i in XS:\n    ordinate = (m * i + b)\n    regression_line.append(ordinate)\n\n# Predictions\npredict_x = np.array([120, 30, 92], dtype=np.float64)\npredictions = []\nfor j in predict_x:\n    predict_ordinate = (m * predict_x + b)\n    predictions.append(predict_ordinate)\n\nr_squared = coefficient_of_determination(YS, regression_line)\n\n# Output:\nprint('Slope = ', m, 'Y intercept = ', b, 'Ordinates =', regression_line, 'Predict_Ordinates = ',\n      predictions, 'R^2 = ', r_squared, sep='\\n')\n\nplt.scatter(XS, YS, color='b', label='data')\nplt.scatter(predict_x, predict_ordinate, color='g', label='prediction')\nplt.plot(XS, regression_line, label='regression_line')\nplt.plot(YS, y_mean_line, label='y_mean_line')\nplt.legend(loc=4)\nplt.show()\n", "meta": {"hexsha": "a21d00b946a78b1b86a9bc048187c025fdf8ab90", "size": 2384, "ext": "py", "lang": "Python", "max_stars_repo_path": "LinearRegression/RegressionTheory/BestFitSlope.py", "max_stars_repo_name": "paramkpr/MessingWithML", "max_stars_repo_head_hexsha": "aa5a811cb8171cc3798f3fe8b26ae16e8ea8a8b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-08T11:46:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-08T11:53:49.000Z", "max_issues_repo_path": "LinearRegression/RegressionTheory/BestFitSlope.py", "max_issues_repo_name": "psrth/MessingWithML", "max_issues_repo_head_hexsha": "92ad9efd18decd020cfcffb56bc84de16f9aaf02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LinearRegression/RegressionTheory/BestFitSlope.py", "max_forks_repo_name": "psrth/MessingWithML", "max_forks_repo_head_hexsha": "92ad9efd18decd020cfcffb56bc84de16f9aaf02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-04-30T07:01:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-26T11:03:08.000Z", "avg_line_length": 28.380952381, "max_line_length": 97, "alphanum_fraction": 0.6757550336, "include": true, "reason": "import numpy", "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811611608242, "lm_q2_score": 0.8902942188450159, "lm_q1q2_score": 0.8594732667633703}}
{"text": "import math\nimport numpy as np\n\nfrom awesomediff.core import variable\n\ndef sin(x):\n    \"\"\"\n        Helper function that calculates the sin of a variable or number.\n\n        INPUTS:\n            x : awesomediff.variable object or a number.\n\n        OUTPUT:\n            awesomediff.variable\n    \"\"\"\n    \n    try:\n        # Assume object is a variable:\n        val = x.val\n        der = x.der\n    except:\n        # If not, treat it as a constant.\n        try:\n            float(x)\n        except:\n            raise ValueError(\"{} is not a number.\".format(x))\n        val = x\n        der = 0  # Derivative of a constant is zero.\n    # Calculate new value an derivative:\n    new_val = np.sin(val)\n    new_der = np.cos(val)*der\n    # Return variable with new value an derivative:\n    return variable(val=new_val,der=new_der)\n\ndef cos(x):\n    \"\"\"\n        Helper function that calculates the sin of a variable or number.\n\n        INPUTS:\n            x : awesomediff.variable object or a number.\n\n        OUTPUT:\n            awesomediff.variable\n    \"\"\"\n    \n    try:\n        # Assume object is a variable:\n        val = x.val\n        der = x.der\n    except:\n        # If not, treat it as a constant.\n        try:\n            float(x)\n        except:\n            raise ValueError(\"{} is not a number.\".format(x))\n        val = x\n        der = 0  # Derivative of a constant is zero.\n    # Calculate new value an derivative:\n    new_val = np.cos(val)\n    new_der = -np.sin(val)*der\n    # Return variable with new value an derivative:\n    return variable(val=new_val,der=new_der)\n\ndef tan(x):\n    \"\"\"\n        Helper function that calculates the sin of a variable or number.\n\n        INPUTS:\n            x : awesomediff.variable object or a number.\n\n        OUTPUT:\n            awesomediff.variable\n    \"\"\"\n    \n    try:\n        # Assume object is a variable:\n        val = x.val\n        der = x.der\n    except:\n        # If not, treat it as a constant.\n        try:\n            float(x)\n        except:\n            raise ValueError(\"{} is not a number.\".format(x))\n        val = x\n        der = 0  # Derivative of a constant is zero.\n    # Calculate new value an derivative:\n    new_val = np.tan(val)\n    new_der = ((1/np.cos(val))**2)*der\n    # Return variable with new value an derivative:\n    return variable(val=new_val,der=new_der)\n\ndef arcsin(x):\n    \"\"\"\n        Helper function that calculates the arcsine of a variable or number.\n\n        INPUTS:\n            x : awesomediff.variable object or a number.\n\n        OUTPUT:\n            awesomediff.variable\n    \"\"\"\n    try:\n        # Assume object is a variable:\n        val = x.val\n        der = x.der\n    except:\n        # If not, treat it as a constant.\n        try:\n            float(x)\n        except:\n            raise ValueError(\"{} is not a number.\".format(x))\n        val = x\n        der = 0  # Derivative of a constant is zero.\n    # Calculate new value an derivative:\n    new_val = np.arcsin(val)\n    if(np.isnan(new_val)):\n        raise ValueError(\"Please enter a number on the unit circle.\")\n\n    # if (np.sqrt(1-val**2)==0):\n    #     new_der = 0\n    # else:\n    #     new_der = 1/np.sqrt(1-val**2)*der\n    # print(\"new val\", new_val)\n    new_der = 1/np.sqrt(1-val**2)*der\n    # Return variable with new value an derivative:\n    return variable(val=new_val,der=new_der)\n\ndef arccos(x):\n    \"\"\"\n        Helper function that calculates the arccos of a variable or number.\n\n        INPUTS:\n            x : awesomediff.variable object or a number.\n\n        OUTPUT:\n            awesomediff.variable\n    \"\"\"\n    try:\n        # Assume object is a variable:\n        val = x.val\n        der = x.der\n    except:\n        # If not, treat it as a constant.\n        try:\n            float(x)\n        except:\n            raise ValueError(\"{} is not a number.\".format(x))\n        val = x\n        der = 0  # Derivative of a constant is zero.\n    # Calculate new value an derivative:\n    new_val = np.arccos(val)\n    # print(\"new val\", new_val)\n    if(np.isnan(new_val)):\n        raise ValueError(\"Please enter a number on the unit circle.\")\n\n    # if (np.sqrt(1-val**2)==0):\n    #     new_der = 0\n    # else:\n    #     new_der = -1/np.sqrt(1-val**2)*der\n\n    new_der = -1/np.sqrt(1-val**2)*der\n    # Return variable with new value an derivative:\n    return variable(val=new_val,der=new_der)\n\ndef arctan(x):\n    \"\"\"\n        Helper function that calculates the arctan of a variable or number.\n\n        INPUTS:\n            x : awesomediff.variable object or a number.\n\n        OUTPUT:\n            awesomediff.variable\n    \"\"\"\n    try:\n        # Assume object is a variable:\n        val = x.val\n        der = x.der\n    except:\n        # If not, treat it as a constant.\n        try:\n            float(x)\n        except:\n            raise ValueError(\"{} is not a number.\".format(x))\n        val = x\n        der = 0  # Derivative of a constant is zero.\n    # Calculate new value an derivative:\n    new_val = np.arctan(val)\n    if(np.isnan(new_val)):\n        raise ValueError(\"Please enter a number on the unit circle.\")\n    new_der = 1/(1+val**2)*der\n    # Return variable with new value an derivative:\n    return variable(val=new_val,der=new_der)\n\ndef log(x):\n    \"\"\"\n        Helper function that calculates the natural log of a variable or number.\n\n        INPUTS:\n            x : AutoDiff.variable object or a number.\n\n        OUTPUT:\n            AutoDiff.variable\n    \"\"\"\n    try:\n        # x.val = np.log(x.val)\n        # x.der = (1/x.val)*x.der\n        new_val = np.log(x.val)\n        new_der = (1/x.val)*x.der\n        # return x\n        return variable(val=new_val,der=new_der)\n    except:\n        new_val = np.log(x)\n        new_der = 0\n        return variable(val=new_val,der=new_der)\n\ndef logb(x, b):\n    \"\"\"\n        Helper function that calculates the log of a variable or number with any base.\n\n        INPUTS:\n            x : AutoDiff.variable object or a number.\n            b: a number\n\n        OUTPUT:\n            AutoDiff.variable\n    \"\"\"   \n    try:\n        new_val = np.log(x.val)/np.log(b)\n        new_der = (1/(np.log(b)*x.val))*x.der\n        return variable(val=new_val,der=new_der)\n    except:\n        new_val = np.log(x)/np.log(b)\n        new_der = 0\n        return variable(val=new_val,der=new_der)\n\ndef sqrt(x):\n    \"\"\"\n        Helper function that calculates the square root of a variable or number.\n\n        INPUTS:\n            x : AutoDiff.variable object or a number.\n\n        OUTPUT:\n            AutoDiff.variable\n    \"\"\"\n    try:\n        new_val = np.sqrt(x.val)\n        new_der = (0.5/np.sqrt(x.val))*x.der\n        return variable(val=new_val,der=new_der)\n    except:\n        new_val = np.sqrt(x)\n        new_der = 0\n        return variable(val=new_val,der=new_der)\n\ndef exp(x):\n    \"\"\"\n        Helper function that calculates the exponential of a variable or number.\n\n        INPUTS:\n            x : AutoDiff.variable object or a number.\n\n        OUTPUT:\n            AutoDiff.variable\n    \"\"\"\n    try:\n        new_val = np.exp(x.val)\n        new_der = np.exp(x.val)*x.der\n        return variable(val=new_val,der=new_der)\n    except:\n        new_val = np.exp(x)\n        new_der = 0\n        return variable(val=new_val,der=new_der)\n\n\ndef sinh(x):\n    \"\"\"\n        Helper function that calculates hyperbolic sine of a variable or number\n        \n        INPUTS:\n            x : AutoDiff.variable object or a number.\n\n        OUTPUT:\n            AutoDiff.variable\n    \"\"\"\n    return (exp(x) - exp(-x)) / 2\n\ndef cosh(x):\n    \"\"\"\n        Helper function that calculates hyperbolic cosine of a variable or number\n        \n        INPUTS:\n            x : AutoDiff.variable object or a number.\n\n        OUTPUT:\n            AutoDiff.variable\n    \"\"\"\n    return (exp(x) + exp(-x)) / 2\n\n\ndef tanh(x):\n    \"\"\"\n        Helper function that calculates hyperbolic tangent of a variable or number\n        \n        INPUTS:\n            x : AutoDiff.variable object or a number.\n\n        OUTPUT:\n            AutoDiff.variable\n    \"\"\"\n    return sinh(x) / cosh(x)\n    \ndef logistic(x, L=1, k=1, x0=1):\n    \"\"\"\n        Helper function that calculates the logistic of a variable or number.\n\n        INPUTS:\n            x : AutoDiff.variable object or a number.\n\n        OUTPUT:\n            AutoDiff.variable\n    \"\"\"\n    try:\n        val = x.val\n        der = x.der\n        logistic = L/(1+np.exp(-k*(val-x0)))\n        new_val = logistic\n        new_der = logistic*(1-logistic)*der\n        return variable(val=new_val,der=new_der)\n    except:\n        new_val = L/(1+np.exp(-k*(x-x0)))\n        new_der = 0\n        return variable(val=new_val,der=new_der)  \n\n\n\n\n", "meta": {"hexsha": "0f54020ceaa0dc055440441e9f4c20205e160ffb", "size": 8601, "ext": "py", "lang": "Python", "max_stars_repo_path": "awesomediff/func.py", "max_stars_repo_name": "awesomediff/cs207-FinalProject", "max_stars_repo_head_hexsha": "f49efd0d9ba64e41fda4e014d93c7aaceaf9292b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "awesomediff/func.py", "max_issues_repo_name": "awesomediff/cs207-FinalProject", "max_issues_repo_head_hexsha": "f49efd0d9ba64e41fda4e014d93c7aaceaf9292b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2019-10-28T20:51:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-10T08:55:57.000Z", "max_forks_repo_path": "awesomediff/func.py", "max_forks_repo_name": "awesomediff/cs207-FinalProject", "max_forks_repo_head_hexsha": "f49efd0d9ba64e41fda4e014d93c7aaceaf9292b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3716814159, "max_line_length": 86, "alphanum_fraction": 0.5533077549, "include": true, "reason": "import numpy", "num_tokens": 2110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075722839014, "lm_q2_score": 0.8933094067644466, "lm_q1q2_score": 0.8594597446405139}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # **IDS575: Machine Learning and Statistical Methods**\n# ## [Linear Regression and Gradient Descent (PA)]\n# \n# \n\n# ## Import Libraries\n# * See various conventions and acronyms.\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_boston\n\n\n# ## Load the data\n# * Verify Python type for the dataset.\n\n# In[2]:\n\n\nHousingDataset = load_boston()\nprint(type(HousingDataset))\nprint(HousingDataset.keys())\n\n\n# ## Verify basic data statistics\n# * Count the number of features. (i.e., attributes)\n# * Count the number of examples. (i.e., instances and labels)\n# * Print out the description of each feature.\n\n# In[14]:\n\n\ndef printBasicStats(dataset):\n    print(dataset['feature_names'])\n    print(len(dataset['feature_names']), type(dataset['feature_names']))  \n    print(dataset['data'].shape, dataset['target'].shape)\n    print(dataset['DESCR'])\n\nprintBasicStats(HousingDataset)\n\n\n# ## Convert the dataset to a DataFrame\n# *   Not necessarily useful. (scikit-learn works well with default libraries such as list, numpy array, and scipy's sparse matrix)\n# *   But using pandas provides more intuitive excel or R-like views.\n\n# In[15]:\n\n\ndef getDataFrame(dataset):\n    featureColumns = pd.DataFrame(dataset.data, columns=dataset.feature_names)\n    targetColumn = pd.DataFrame(dataset.target, columns=['Target'])\n    return featureColumns.join(targetColumn)\n\nDataFrame = getDataFrame(HousingDataset)\nprint(DataFrame)\n\n\n# ## Data inspection\n# * See correlations between features.\n# * Check the quantiles with the highest-correlated feature.\n# \n\n# In[16]:\n\n\nprint(DataFrame.corr())\nDataFrame[['RM', 'Target']].describe()\n\n\n# ## Data cleaning\n# * Target could have some outliers because the maximum price is almost doubled to 50.0 though 75% of the data less than 25.0. \n# * We can remove excessively expensive houses.\n\n# In[17]:\n\n\nDf = DataFrame[DataFrame.Target < 22.5328 + 2*9.1971]\nDf[['RM', 'Target']].describe()\n\n\n# * Rescale the data (different from Gaussian regularization).\n# \n\n# In[18]:\n\n\ndef rescaleVector(x):\n    min = x.min()\n    max = x.max()\n    return pd.Series([(element - min)/(max - min) for element in x])\n\nx_rescale = rescaleVector(Df.RM)\ny_rescale = rescaleVector(Df.Target)\nprint(x_rescale.min(), x_rescale.max())\nprint(y_rescale.min(), x_rescale.max())\n\n\n# * Plot the correlation between RM and Target.\n# * Observe the linear relationship (excluding some outliers).\n# \n# \n\n# In[19]:\n\n\ndef drawScatterAndLines(x, y, lines=[], titles={'main':None, 'x':None, 'y':None}):\n    plt.figure(figsize=(20, 5))\n    plt.rcParams['figure.dpi'] = 200\n    plt.style.use('seaborn-whitegrid')\n    plt.scatter(x, y, label='Data', c='blue', s=6)\n    for (x_line, y_line) in lines:\n        plt.plot(x_line, y_line, c='red', lw=3, label='Regression')\n    plt.title(titles['main'], fontSize=14)\n    plt.xlabel(titles['x'], fontSize=11)\n    plt.ylabel(titles['y'], fontSize=11)\n    plt.legend(frameon=True, loc=1, fontsize=10, borderpad=.6)\n    plt.tick_params(direction='out', length=6, color='black', width=1, grid_alpha=.6)\n    plt.show()\n\ndrawScatterAndLines(x_rescale, y_rescale, titles={'main':'correlation', 'x':'Avg # of Rooms', 'y':'Hosue Price'})\n\n\n# ## Toy Linear Regression \n# * Use only a single feature RM to fit house price.\n# * This could be called Simple Linear Regression.\n# * Plot the regression line.\n# \n\n# In[20]:\n\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\ndef toyLinearRegression(df, feature_name, target_name):\n  # This function performs a simple linear regression.\n  # With a single feature (given by feature_name)\n  # With a rescaling (for stability of test)\n    x = rescaleVector(df[feature_name])\n    y = rescaleVector(df[target_name])\n    x_train = x.values.reshape(-1, 1)\n    y_train = y.values.reshape(-1, 1)\n    lr = LinearRegression()\n    lr.fit(x_train, y_train)\n    y_train_pred = lr.predict(x_train)\n  \n  # Return training error and (x_train, y_train, y_train_pred)\n    return mean_squared_error(y_train, y_train_pred), (x_train, y_train, y_train_pred)\n\nToyTrainingError, (x_rescale_train, y_rescale_train, y_rescale_train_pred) = toyLinearRegression(Df, 'RM', 'Target')\nprint('training error = %.4f' % ToyTrainingError)\ndrawScatterAndLines(x_rescale_train, y_rescale_train, lines=[(x_rescale_train, y_rescale_train_pred)], titles={'main':'correlation', 'x':'RM', 'y':'Target'})\n\n\n# ## Main Linear Regression \n# * Use all of multi-variate features to fit house price.\n# * This could be called Multiple Linear Regression.\n\n# In[21]:\n\n\nfrom sklearn.model_selection import train_test_split\ndef splitTrainTest(df, size):\n    X, y = df.drop('Target', axis=1), df.Target\n    X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=size, test_size=X.shape[0] - size, random_state=0)\n    return (X_train, y_train), (X_test, y_test)\n\n(X_train, y_train), (X_test, y_test) = splitTrainTest(Df, 350)\nLR = LinearRegression()\nLR.fit(X_train, y_train)\nprint(LR.coef_)\ny_train_pred = LR.predict(X_train)\ny_test_pred = LR.predict(X_test)\n\n\n# ## Measure training and test accuracy\n# * Use Mean Squared Error.\n\n# In[13]:\n\n\nfrom sklearn.metrics import mean_squared_error\nprint('Training error = %.4f' % mean_squared_error(y_train, y_train_pred))\nprint('Test error = %.4f' % mean_squared_error(y_test, y_test_pred))\n\n\n# # Programming Assignment (PA)\n# * Implement predict().\n# * Implement batchGradientDescent().\n# * Implement stocGradientDescent().\n# * Implement normalEquation().\n# * Play with testYourCode() that compares your implementations against scikit-learn's results. **Do not change alpha and epoch options separately provided to bgd and sgd for single-feature simple linear regression.**\n# * Once everything is done, then compare your implementations against scikit-learn's results using the entire features. **Now play with different alpha and epoch values, reporting your comparative impressions among bgd, sgd, and normal equations.**\n\n# In[26]:\n\n\nclass MyLinearRegression:  \n    theta = None\n    \n    def fit(self, X, y, option, alpha, epoch):\n        X = np.concatenate((np.array(X), np.ones((X.shape[0], 1), dtype=np.float64)), axis=1)\n        y = np.array(y)       \n        if option.lower() in ['bgd', 'gd']:\n            # Run batch gradient descent.\n            self.theta = self.batchGradientDescent(X, y, alpha, epoch)      \n        elif option.lower() in ['sgd']:\n      # Run stochastic gradient descent.\n            self.theta = self.stocGradientDescent(X, y, alpha, epoch)\n        else:\n      # Run solving the normal equation.      \n            self.theta = self.normalEquation(X, y)\n        \n    def predict(self, X):\n        X = np.concatenate((np.array(X), np.ones((X.shape[0], 1), dtype=np.float64)), axis=1)\n        y_pred = np.array([])\n        if isinstance(self.theta, np.ndarray):\n            theta = self.theta\n            for x in X:\n        # TO-DO: #############################################     \n                y_pred = np.dot(X, self.theta) \n      ######################################################\n            return y_pred\n        return None\n\n    def batchGradientDescent(self, X, y, alpha=0.00001, epoch=100000):\n        (m, n) = X.shape      \n        theta = np.zeros((n, 1), dtype=np.float64)\n        for iter in range(epoch):\n            if (iter % 1000) == 0:\n                print('- currently at %d epoch...' % iter) \n        y_size = y.size\n        for j in range(n):\n         # TO-DO: ############################################# \n            theta[j] = theta[j] - (alpha * (sum([(np.dot(X[i], theta) - y[i]) * X[i][j] for i in range(m)])[0]) / m)\n        ######################################################\n        return theta\n\n    def stocGradientDescent(self, X, y, alpha=0.000001, epoch=10000):\n        (m, n) = X.shape\n        theta = np.zeros((n, 1), dtype=np.float64)\n        for iter in range(epoch):\n            if (iter % 100) == 0:\n                print('- currently at %d epoch...' % iter)\n        for i in range(m):\n            for j in range(n):\n            # TO-DO: ############################################# \n                theta[j] = theta[j] - alpha * (np.dot(X[i], theta) - y[i]) * X[i][j]\n          ######################################################    \n        return theta\n\n    def normalEquation(self, X, y):\n        # TO-DO: ############################################# \n        theta = np.dot(np.linalg.inv(np.dot(np.transpose(X), X)), np.dot(np.transpose(X), y))\n    \n    ######################################################\n        return theta\n\n    @staticmethod\n    def toyLinearRegression(df, feature_name, target_name, option, alpha, epoch):\n        # This function performs a simple linear regression.\n    # With a single feature (given by feature_name)\n    # With a rescaling (for stability of test)\n        x = rescaleVector(df[feature_name])\n        y = rescaleVector(df[target_name])\n        x_train = x.values.reshape(-1, 1)\n        y_train = y.values.reshape(-1, 1)\n\n    # Perform linear regression.    \n        lr = MyLinearRegression()\n        lr.fit(x_train, y_train, option, alpha, epoch)\n        y_train_pred = lr.predict(x_train)\n    \n    # Return training error and (x_train, y_train, y_train_pred)\n        return mean_squared_error(y_train, y_train_pred), (x_train, y_train, y_train_pred)\n\n\n\n# In[27]:\n\n\ndef testYourCode(df, feature_name, target_name, option, alpha, epoch):\n    trainError0, (x_train0, y_train0, y_train_pred0) = toyLinearRegression(df, feature_name, target_name)\n    trainError1, (x_train1, y_train1, y_train_pred1) = MyLinearRegression.toyLinearRegression(df, feature_name, target_name, option, alpha, epoch)\n    drawScatterAndLines(x_train0, y_train0, lines=[(x_train0, y_train_pred0)], titles={'main':'Linear Regression', 'x':feature_name, 'y':target_name})\n    drawScatterAndLines(x_train1, y_train1, lines=[(x_train1, y_train_pred1)], titles={'main':'Linear Regression', 'x':feature_name, 'y':target_name})\n    return trainError0, trainError1\n\nTrainError0, TrainError1 = testYourCode(Df, 'DIS', 'Target', option='sgd', alpha=0.001, epoch=500)\nprint(\"Scikit's training error = %.6f / My training error = %.6f --> Difference = %.4f\" % (TrainError0, TrainError1, np.abs(TrainError0 - TrainError1)))\nTrainError0, TrainError1 = testYourCode(Df, 'RM', 'Target', option='bgd', alpha=0.1, epoch=5000)\nprint(\"Scikit's training error = %.6f / My training error = %.6f --> Difference = %.4f\" % (TrainError0, TrainError1, np.abs(TrainError0 - TrainError1)))\n\n\n# In[28]:\n\n\nMyLR = MyLinearRegression()\nMyLR.fit(X_train, y_train.values.reshape(-1, 1), option='sgd', alpha=0.000001, epoch=10000)\nprint(MyLR.theta)\ny_train_pred = MyLR.predict(X_train)\ny_test_pred = MyLR.predict(X_test)\n\nprint('Training error = %.4f' % mean_squared_error(y_train, y_train_pred))\nprint('Test error = %.4f' % mean_squared_error(y_test, y_test_pred))\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "600228e3cbcacb607fcb22f8da4ff83911e9a1ca", "size": 10951, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear Regression and Gradient Descent.py", "max_stars_repo_name": "kavyacherukuri/kavya", "max_stars_repo_head_hexsha": "5e30f9e2c610115b9071a7c1700bf76b144c86ea", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Linear Regression and Gradient Descent.py", "max_issues_repo_name": "kavyacherukuri/kavya", "max_issues_repo_head_hexsha": "5e30f9e2c610115b9071a7c1700bf76b144c86ea", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear Regression and Gradient Descent.py", "max_forks_repo_name": "kavyacherukuri/kavya", "max_forks_repo_head_hexsha": "5e30f9e2c610115b9071a7c1700bf76b144c86ea", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.329153605, "max_line_length": 249, "alphanum_fraction": 0.645785773, "include": true, "reason": "import numpy", "num_tokens": 2819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362486, "lm_q2_score": 0.9161096107264305, "lm_q1q2_score": 0.8594244287014697}}
{"text": "\n# coding: utf-8\n\n# In[ ]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#Defining the function to integrate\ndef func(x):\n    return (np.exp(-2*x))*(np.cos(10*x))\n\n#Defining the integral\ndef func_integral(x):\n    return (np.exp(-2*x))*(5*np.sin(10*x) - np.cos(10*x))/(52)\n\n\n# TRAPEZOID METHOD\n\n#This is the core program of the Trapezoid Method\ndef trapezoid_core(f,x,h):\n    return 0.5*h*(f(x+h) + f(x))\n\n#Wrapper function for the Trapezoid Method\ndef trapezoid_method(f,a,b,N):\n    #f == function to integrate\n    #a == lower limit of integration\n    #b == upper limit of integration\n    #N == number of function evaluations to use\n    \n    #define x values to perform trapezoid rule\n    x = np.linspace(a,b,N)\n    h = x[1]-x[0]\n    \n    #define the value of the integral\n    Fint = 0.0\n    \n    #perform the integral using the trapezoid method\n    for i in range(0, len(x)-1,1):\n        Fint += trapezoid_core(f,x[i],h)\n        \n    #return the answer\n    return Fint\n\n#SIMPSON'S METHOD\n\n#This is the core program of Simpson's Method\ndef simpson_core(f,x,h):\n    return h*( f(x) + 4*f(x+h) + f(x+2*h))/3.\n\n#Wrapper function for Simpson's Method\ndef simpsons_method(f,a,b,N):\n    #f == function to integrate\n    #a == lower limit of integration\n    #b == upper limit of integration\n    #N == number of function evaluations to use\n    \n    '''Note the number of chunks will be N-1\n        so if N is odd, then we don't need to\n        adjust the last segment'''\n    \n    #Define x values to perform simpson's rule\n    x = np.linspace(a,b,N)\n    h = x[1]-x[0]\n\n    #define the value of the integral\n    Fint = 0.0\n    \n    #perform the integral using simpson's method\n    for i in range(0,len(x)-2,2):\n        Fint += simpson_core(f,x[i],h)\n        \n    #apply simpson's rule over the last interval\n    #if N is even\n    if((N%2)==0):\n        Fint += simpson_core(f,x[-2],0.5*h)\n        \n    return Fint\n\n# ROMBERG INTEGRATION\n\n#This is the Romberg Core\ndef romberg_core(f,a,b,i):\n    \n    #we need the difference b-a\n    h = b-a\n    \n    #and the increment between new func evals\n    dh = h/2.**(i)\n    \n    #we need the cofactor\n    K = h/2.**(i+1)\n    \n    #and the function evaluations\n    M = 0.0\n    for j in range(2**i):\n        M += f(a + 0.5*dh + j*dh)\n        \n    #return the answer\n    return K*M\n\n#Wrapper function for Romberg\ndef romberg_integration(f,a,b,tol):\n    \n    #define an iteration variable\n    i = 0\n    \n    #define a maximum number of iterations\n    imax = 1000\n    \n    #define an error estimate, set to a large value\n    delta = 100.0*np.fabs(tol)\n    \n    #set an array of integral answers\n    I = np.zeros(imax,dtype=float)\n    \n    #get the zeroth romberg iteration\n    I[0] = 0.5*(b-a)*(f(a) + f(b))\n    \n    #iterate by 1\n    i += 1\n    \n    while(delta>tol):\n        \n        #find this romberg iteration\n        I[i] = 0.5*I[i-1] + romberg_core(f,a,b,i)\n        \n        #compute the new fractional error estimate\n        delta = np.fabs( (I[i]-I[i-1])/I[i])\n        \n        print(i,I[i],I[i-1],delta)\n        \n        if(delta>tol):\n            \n            #iterate\n            i+=1\n            \n            #if we've reached the maximum iterations\n            if(i>imax):\n                print(\"Max iterations reached.\")\n                raise StopIteration('Stopping iterations after ',i)\n                \n    #return the answer\n    return I[i]\n\n#Print Answers:\n\nprint(\"Answer:\")\nAnswer = func_integral(np.pi)-func_integral(0)\nprint(Answer)\nprint(\"Trapezoid:\")\nprint(trapezoid_method(func,0,1,10))\nprint(\"Simpson's Method:\")\nprint(simpsons_method(func,0,1,10))\nprint(\"Romberg:\")\ntolerance = 1.0e-6\nRI = romberg_integration(func,0,1,tolerance)      \nprint(RI, (RI-Answer)/Answer, tolerance)\n\n", "meta": {"hexsha": "8b148da57f737c544a8fc3957c9cdcf1629a21ca", "size": 3791, "ext": "py", "lang": "Python", "max_stars_repo_path": "ASTR119_HW4_AngelBanda.py", "max_stars_repo_name": "abanda97/astr-119-HW-4", "max_stars_repo_head_hexsha": "cee0d5d7fd9d45c7218615beb3c1fb52e33b5bbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ASTR119_HW4_AngelBanda.py", "max_issues_repo_name": "abanda97/astr-119-HW-4", "max_issues_repo_head_hexsha": "cee0d5d7fd9d45c7218615beb3c1fb52e33b5bbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-11-06T08:36:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-06T08:39:28.000Z", "max_forks_repo_path": "ASTR119_HW4_AngelBanda.py", "max_forks_repo_name": "abanda97/astr-119-HW-4", "max_forks_repo_head_hexsha": "cee0d5d7fd9d45c7218615beb3c1fb52e33b5bbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4012345679, "max_line_length": 67, "alphanum_fraction": 0.5919282511, "include": true, "reason": "import numpy", "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240160063031, "lm_q2_score": 0.9161096107264306, "lm_q1q2_score": 0.8594244271166501}}
{"text": "\"\"\"\nAuthor: michealowen\nLast edited: 2019.11.14,Thursday\n计算距离\n\"\"\"\n#encoding=UTF-8\n\nimport numpy as np\n\ndef euclidean_distance(x_1,x_2):\n    '''\n    计算x_1和x_2中的向量的欧几里得(L2)距离\n    compute the L2-distances of the vectors in x_1,x_2\n    \n    Params:\n        x_1:array-like, shape: (n_samples_X, n_features)\n        x_2:array-like, shape: (n_samples_X, n_features)\n    Returns:\n        distance:array-like, shape: (n_samples_X,1)\n    '''\n    x_1 = check_array(x_1)\n    x_2 = check_array(x_2)\n    return np.sum(np.power(x_1-x_2,2),axis=1).reshape(-1,1)\n\n\ndef manhattan_distance(x_1,x_2):\n    '''\n    计算x_1和x_2中的向量的曼哈顿距离(L1)距离\n    compute the L1-distances of the vectors in x_1,x_2\n\n    Params:\n        x_1:array-like, shape: (n_samples_X, n_features)\n        x_2:array-like, shape: (n_samples_X, n_features)\n    Returns:\n        distance:array-like, shape: (n_samples_X,1)\n    '''\n    x_1 = check_array(x_1)\n    x_2 = check_array(x_2)\n    return np.sum(np.abs(x_1-x_2,2),axis=1).reshape(-1,1)\n\ndef check_array(x):\n    '''\n    to change the type of x to np.ndarray if isinstance(x,np.ndarray) != True\n    ''' \n    if not isinstance(x,np.ndarray):\n        x = np.array(x)\n    return x\n\n\nif __name__ == '__main__':\n    print(manhattan_distance([1,1],[2,2]))\n", "meta": {"hexsha": "139a52cd99e855670f671ade36be6c870ccb8c94", "size": 1248, "ext": "py", "lang": "Python", "max_stars_repo_path": "metrics/distance.py", "max_stars_repo_name": "michealowen/MachingLearning", "max_stars_repo_head_hexsha": "9dcc908f2d3e468390e5abb7f051b449b0ecb455", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-09-11T07:02:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-17T10:40:02.000Z", "max_issues_repo_path": "metrics/distance.py", "max_issues_repo_name": "michealowen/MachingLearning", "max_issues_repo_head_hexsha": "9dcc908f2d3e468390e5abb7f051b449b0ecb455", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "metrics/distance.py", "max_forks_repo_name": "michealowen/MachingLearning", "max_forks_repo_head_hexsha": "9dcc908f2d3e468390e5abb7f051b449b0ecb455", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0, "max_line_length": 77, "alphanum_fraction": 0.6418269231, "include": true, "reason": "import numpy", "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322215, "lm_q2_score": 0.9086179000259899, "lm_q1q2_score": 0.8593719667261686}}
{"text": "# ###################################\n# author: Gonzalo Salazar\n# course: Python for Data Science and Machine Learning Bootcamp\n# purpose: lecture notes\n# description: Section 22 - Principal Component Analysis\n# datasets: breast cancer diagnoses from sklearn\n# ###################################\n\n## PCA (aka general factor analysis) ###\n# An unsupervised statistical technique used to examine the interrelations among a set of\n# variables in order to identify the underlying structure of those variables. Where regression\n# determines a line of best fit to a data set, factor analysis determines several orthogonal \n# lines of best fit to the data set.\n# The components are a linear transformation that chooses a variable system for the data set\n# such that the greatest variance of the data set comes to lie on the first axis, the second\n# greatest variance on the second axis, and so on ... This process allows us to reduce the number\n# of variables used in an analysis.\n# \n# Note that components are uncorrelated, since in the sample space they are orthogonal to each other!\n# \n# PROS: \n#   When we have a large number of variables in a data set, we can compress the amount of explained\n#   variation to just a few components\n# \n# CONS:\n#   Interpreting the components\n\n# %% \n#import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n#%matplotlib inline\n\n# %%\n# Loading and visualizing data\ncancer = load_breast_cancer()\ncancer.keys()\nprint(cancer['DESCR'])\n\ndf = pd.DataFrame(cancer['data'],columns = cancer['feature_names'])\ndf.head()\n\n# %% \n# Scaling everything to have a single unit variance\nscaler = StandardScaler()\nscaler.fit(df)\nscaled_data = scaler.transform(df)\n\n# %% \n# Performing the PCA\npca = PCA(n_components = 2)  # number of component we want to keep are two\npca.fit(scaled_data)\nx_pca = pca.transform(scaled_data)  # transforms the data to its first principle component\n\n# Checking dimensions before and after transformation\nprint('Data dimensions')\nprint('Scaled data: ',str(scaled_data.shape))\nprint('Transformed data: ', str(x_pca.shape))\n\n# %%\n# Checking how the data looks like in 2D\nplt.figure(figsize=(8,6))\nplt.scatter(x_pca[:,0],x_pca[:,1],c=cancer['target'],cmap='plasma')\nplt.xlabel('First Principle Component')\nplt.ylabel('Second Principle Component')\nplt.show()\n\n# %% \n# Showing how each variable was combined to get a component, where each row represents a component\n# and each column represents the weigth of each column\npca.components_\n\ndf_comp = pd.DataFrame(pca.components_, columns=cancer['feature_names'])\nsns.set_style('darkgrid')\nplt.figure(figsize=(12,6))\nsns.heatmap(df_comp,cmap='Greens')\n\n# We can now use the x_pca to fit a classification algorithm. So we can do something like a logistic\n# regression on x_pca instead of doing a logistic regression on the entire data frame of features.\n# Since data seems to be very well separated, SVMs may actually be a good choice for this.", "meta": {"hexsha": "83ee4165a5ac4af0a6896a51f22726130bbac45a", "size": 3108, "ext": "py", "lang": "Python", "max_stars_repo_path": "Udemy_Py_DataScience_ML/Sec22_PCA.py", "max_stars_repo_name": "gonzalosc2/LearningPython", "max_stars_repo_head_hexsha": "0210d4cbbb5e154f12007b8e8f825fd3d0022be0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Udemy_Py_DataScience_ML/Sec22_PCA.py", "max_issues_repo_name": "gonzalosc2/LearningPython", "max_issues_repo_head_hexsha": "0210d4cbbb5e154f12007b8e8f825fd3d0022be0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Udemy_Py_DataScience_ML/Sec22_PCA.py", "max_forks_repo_name": "gonzalosc2/LearningPython", "max_forks_repo_head_hexsha": "0210d4cbbb5e154f12007b8e8f825fd3d0022be0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5647058824, "max_line_length": 101, "alphanum_fraction": 0.749034749, "include": true, "reason": "import numpy", "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.8947894654011352, "lm_q1q2_score": 0.859321047722574}}
{"text": "from aerosandbox.numpy.array import array, length\nimport numpy as _onp\n\n\ndef finite_difference_coefficients(\n        x: _onp.ndarray,\n        x0: float = 0,\n        derivative_degree: int = 1,\n) -> _onp.ndarray:\n    \"\"\"\n    Computes the weights (coefficients) in compact finite differece formulas for any order of derivative\n    and to any order of accuracy on one-dimensional grids with arbitrary spacing.\n\n    (Wording above is taken from the paper below, as are docstrings for parameters.)\n\n    Modified from an implementation of:\n\n        Fornberg, Bengt, \"Generation of Finite Difference Formulas on Arbitrarily Spaced Grids\". Oct. 1988.\n        Mathematics of Computation, Volume 51, Number 184, pages 699-706.\n\n        PDF: https://www.ams.org/journals/mcom/1988-51-184/S0025-5718-1988-0935077-0/S0025-5718-1988-0935077-0.pdf\n\n        More detail: https://en.wikipedia.org/wiki/Finite_difference_coefficient\n\n    Args:\n\n        derivative_degree: The degree of the derivative that you are interested in obtaining. (denoted \"M\" in the\n        paper)\n\n        x: The grid points (not necessarily uniform or in order) that you want to obtain weights for. You must\n        provide at least as many grid points as the degree of the derivative that you're interested in, plus 1.\n\n            The order of accuracy of your derivative depends in part on the number of grid points that you provide.\n            Specifically:\n\n                order_of_accuracy = n_grid_points - derivative_degree\n\n            (This is in general; can be higher in special cases.)\n\n            For example, if you're evaluating a second derivative and you provide three grid points, you'll have a\n            first-order-accurate answer.\n\n            (x is denoted \"alpha\" in the paper)\n\n        x0: The location that you are interested in obtaining a derivative at. This need not be on a grid point.\n\n    Complexity is O(derivative_degree * len(x) ^ 2)\n\n    Returns: A 1D ndarray corresponding to the coefficients that should be placed on each grid point. In other words,\n    the approximate derivative at `x0` is the dot product of `coefficients` and the function values at each of the\n    grid points `x`.\n\n    \"\"\"\n    ### Check inputs\n    if derivative_degree < 1:\n        return ValueError(\"The parameter derivative_degree must be an integer >= 1.\")\n    expected_order_of_accuracy = length(x) - derivative_degree\n    if expected_order_of_accuracy < 1:\n        return ValueError(\"You need to provide at least (derivative_degree+1) grid points in the x vector.\")\n\n    ### Implement algorithm; notation from paper in docstring.\n    N = length(x) - 1\n\n    delta = _onp.zeros(\n        shape=(\n            derivative_degree + 1,\n            N + 1,\n            N + 1\n        ),\n        dtype=\"O\"\n    )\n\n    delta[0, 0, 0] = 1\n    c1 = 1\n    for n in range(1,\n                   N + 1):  # TODO make this algorithm more efficient; we only need to store a fraction of this data.\n        c2 = 1\n        for v in range(n):\n            c3 = x[n] - x[v]\n            c2 = c2 * c3\n            # if n <= M: # Omitted because d is initialized to zero.\n            #     d[n, n - 1, v] = 0\n            for m in range(min(n, derivative_degree) + 1):\n                delta[m, n, v] = (\n                                         (x[n] - x0) * delta[m, n - 1, v] - m * delta[m - 1, n - 1, v]\n                                 ) / c3\n        for m in range(min(n, derivative_degree) + 1):\n            delta[m, n, n] = (\n                    c1 / c2 * (\n                    m * delta[m - 1, n - 1, n - 1] - (x[n - 1] - x0) * delta[m, n - 1, n - 1]\n            )\n            )\n        c1 = c2\n\n    coefficients_object_array = delta[derivative_degree, -1, :]\n\n    coefficients = array([*coefficients_object_array])  # Reconstructs using aerosandbox.numpy to intelligently type\n\n    return coefficients\n", "meta": {"hexsha": "bc89e62cbfb93b457ea268a4eaaa6f5a07197a1c", "size": 3858, "ext": "py", "lang": "Python", "max_stars_repo_path": "aerosandbox/numpy/finite_difference_operators.py", "max_stars_repo_name": "raihaan123/AeroSandbox", "max_stars_repo_head_hexsha": "1e7c78f04b066415f671237a4833ba98901bb9ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 322, "max_stars_repo_stars_event_min_datetime": "2019-05-29T20:40:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:46:45.000Z", "max_issues_repo_path": "aerosandbox/numpy/finite_difference_operators.py", "max_issues_repo_name": "raihaan123/AeroSandbox", "max_issues_repo_head_hexsha": "1e7c78f04b066415f671237a4833ba98901bb9ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55, "max_issues_repo_issues_event_min_datetime": "2019-07-14T09:52:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:02:21.000Z", "max_forks_repo_path": "aerosandbox/numpy/finite_difference_operators.py", "max_forks_repo_name": "raihaan123/AeroSandbox", "max_forks_repo_head_hexsha": "1e7c78f04b066415f671237a4833ba98901bb9ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 68, "max_forks_repo_forks_event_min_datetime": "2019-06-02T09:57:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T15:03:47.000Z", "avg_line_length": 38.58, "max_line_length": 117, "alphanum_fraction": 0.6127527216, "include": true, "reason": "import numpy", "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611631680358, "lm_q2_score": 0.8947894604912848, "lm_q1q2_score": 0.8593210470679095}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 21 15:36:06 2022\n\n@author: bobrokerson\n\"\"\"\n# part of code from task #1\n\nfrom math import sin, exp\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef func(x):\n    return sin(x / 5.) * exp(x / 10.) + 5. * exp(-x/ 2.)\n\n\nxarr = np.arange(1., 31.)\nprint(xarr)\nprint(\"x:\", xarr.shape)\nyarr = np.array([func(x) for x in xarr])\nprint(yarr)\nprint(\"y:\", yarr.shape)\n\nplt.plot(xarr, yarr)\nplt.grid(True)\nplt.axis([0, 30, -15, 5])\nplt.show()\n\n\n# 1.Теперь рассмотрим функцию h(x) = int(f(x)) на том же отрезке [1, 30], т.е. теперь каждое значение f(x) приводится к типу int и функция принимает только целые значения.\n# 2.Такая функция будет негладкой и даже разрывной, а ее график будет иметь ступенчатый вид. Убедитесь в этом, построив график h(x) с помощью matplotlib.\n# 3.Попробуйте найти минимум функции h(x) с помощью BFGS, взяв в качестве начального приближения x=30. Получившееся значение функции – ваш первый ответ в этой задаче.\n# 4.Теперь попробуйте найти минимум h(x) на отрезке [1, 30] с помощью дифференциальной эволюции. Значение функции h(x) в точке минимума – это ваш второй ответ в этом задании. Запишите его через пробел после предыдущего.\n# 5.Обратите внимание на то, что полученные ответы различаются. Это ожидаемый результат, ведь BFGS использует градиент (в одномерном случае – производную) и явно не пригоден для минимизации рассмотренной нами разрывной функции. Попробуйте понять, почему минимум, найденный BFGS, именно такой (возможно в этом вам поможет выбор разных начальных приближений).\n# 6.Выполнив это задание, вы увидели на практике, чем поиск минимума функции отличается от глобальной оптимизации, и когда может быть полезно применить вместо градиентного метода оптимизации метод, не использующий градиент. Кроме того, вы попрактиковались в использовании библиотеки SciPy для решения оптимизационных задач, и теперь знаете, насколько это просто и удобно.\n\nfrom scipy.optimize import minimize\nfrom scipy.optimize import differential_evolution\n\ndef funcnew(x): \n    return int(func(x))\n\nxarrnew = np.arange(1., 31., 0.01)\nprint(xarrnew)\nprint(\"x:\", xarrnew.shape)\nyarrnew = np.array([funcnew(x) for x in xarrnew])\nprint(yarrnew)\nprint(\"y:\", yarrnew.shape)\n\n# create plot\nplt.plot(xarrnew, yarrnew)\nplt.grid(True)\nplt.axis([0, 30, -15, 5])\nplt.show()\n\n\nminFuncnewVal1 = minimize(funcnew, 30, method = 'BFGS')\nprint(\"Min f(x) BFGS method: \", round(minFuncnewVal1.fun, 3), \"for x = \", minFuncnewVal1.x)\nprint(\"Number: \", minFuncnewVal1.nit)\n\nminValR2 = np.zeros( (2) )\nminValR2 [0] = round(minFuncnewVal1.fun, 2)\nprint(minValR2)\n\n# searching min h(x)\n\nbounds = [(1, 30)]\nminFuncnewVal2 = differential_evolution(funcnew, bounds)\nprint(\"Min f(x) BFGS method: \", round(minFuncnewVal2.fun, 3), \"for x = \", minFuncnewVal2.x)\nprint(\"Number: \", minFuncnewVal2.nit)\n\nminValR2[1] = round(minFuncnewVal2.fun, 2)\nprint (minValR2)\n\nwith open(\"docvalue3.txt\", \"w\") as file:\n    for item in minValR2:\n        file.write(str(item) + ' ')\n        S\n", "meta": {"hexsha": "f740bd521c46102471b2ba19e01976bf20455c3a", "size": 3024, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment/min_nonsmooth_fun.py", "max_stars_repo_name": "bobrokerson/libraries", "max_stars_repo_head_hexsha": "996509d341af7108a24053eb88431ec6afbb0f25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment/min_nonsmooth_fun.py", "max_issues_repo_name": "bobrokerson/libraries", "max_issues_repo_head_hexsha": "996509d341af7108a24053eb88431ec6afbb0f25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment/min_nonsmooth_fun.py", "max_forks_repo_name": "bobrokerson/libraries", "max_forks_repo_head_hexsha": "996509d341af7108a24053eb88431ec6afbb0f25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3333333333, "max_line_length": 371, "alphanum_fraction": 0.7328042328, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678382, "lm_q2_score": 0.9196425317283919, "lm_q1q2_score": 0.8593095345940056}}
{"text": "# Question 3 Algorithm 2 (efficient) Lab Assignment 03\n# @AB Satyaprakash, 180123062\n\n# imports\nfrom math import exp, sqrt\nimport numpy as np\nimport time\n\n# Initialising a dictionary -- C++ equivalent to map<>\nMap = {}\n# functions ---------------------------------------------------------------------------\n\n\ndef recursion(n, K, S, T, r, sig, M, u, d, p, q, dt, upCnt):\n    if (n, upCnt) in Map:\n        return Map[(n, upCnt)]\n\n    if n == M:\n        Map[(n, upCnt)] = max(S - K, 0)\n        return max(S - K, 0)\n\n    up = recursion(n + 1, K, S * u, T, r, sig, M, u, d, p, q, dt, upCnt+1)\n    dn = recursion(n + 1, K, S * d, T, r, sig, M, u, d, p, q, dt, upCnt)\n    pc = (exp(-r * dt)) * (p * up + q * dn)\n    Map[(n, upCnt)] = pc\n    return pc\n\n\n# -------------------------------------------------------------------------------------\n# Given Initial Values -- and taking K = 100\nS0, K, T, r, sig = 100, 100, 1, 0.08, 0.2\n# Can handle values of M as much as 500 ..\nMlist = [5, 10, 25, 50, 100, 500]\n\nfor M in Mlist:\n    dt = T/M\n\n    u = exp(sig*sqrt(dt)+(r-sig*sig/2)*dt)\n    d = exp(-sig*sqrt(dt)+(r-sig*sig/2)*dt)\n    p = (exp(r*dt)-d)/(u-d)\n    q = 1-p\n    Map.clear()\n    loopbackOptionPrice = recursion(0, S0, S0, T, r, sig, M, u, d, p, q, dt, 0)\n    print('The initial european call option price for M = {} is {}'.format(M, loopbackOptionPrice))\n\n# Test computation time for M = 15: -----------------------------------------------------\ndt = T/M\nu = exp(sig*sqrt(dt)+(r-sig*sig/2)*dt)\nd = exp(-sig*sqrt(dt)+(r-sig*sig/2)*dt)\np = (exp(r*dt)-d)/(u-d)\nq = 1-p\nMap.clear()\nstart = time.time()\ntimeTempPrice = recursion(0, S0, S0, T, r, sig, M, u, d, p, q, dt, 0)\nend = time.time()\n\nprint('Computational time for M = 15 is {}s'.format(end-start))\n\n# Question 3 algorithm 2 ends -------------------------------------------------------------\n", "meta": {"hexsha": "d68ef0bae015c0519c134211d184ce3c25682c9e", "size": 1841, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 374 (Financial Engg. Lab)/Lab 3/180123062_AB_q3_2.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 374 (Financial Engg. Lab)/Lab 3/180123062_AB_q3_2.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 374 (Financial Engg. Lab)/Lab 3/180123062_AB_q3_2.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 30.6833333333, "max_line_length": 99, "alphanum_fraction": 0.4807170016, "include": true, "reason": "import numpy", "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395168021653, "lm_q2_score": 0.9196425245706047, "lm_q1q2_score": 0.8593095312660073}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import special as sp\n\n# https://mail.python.org/pipermail/scipy-dev/2016-February/021252.html\ndef qfunc(arg):\n    return 0.5 - 0.5 * sp.erf(arg / 1.414)\n\n\nsamples = 2 * (np.random.randn(1, 10000)[0]) + 2\nmean_samples = np.mean(samples)\nstd_samples = np.std(samples)\nz1 = (2 - mean_samples) / std_samples\nz2 = (6 - mean_samples) / std_samples\nprobability = qfunc(z1) - qfunc(z2)\nprint(probability)\n\nprobability_less_than_a = 1 - qfunc(z1)\nprint(\"P(X<a):\", probability_less_than_a)\n\nprobability_higher_than_b = qfunc(z2)\nprint(\"P(X>b):\", probability_higher_than_b)\n\n\nprobability_total = probability + probability_higher_than_b + probability_less_than_a\nprint(\"P(X<a) + P(a<X<b) + P(X>b):\", probability_total)\n", "meta": {"hexsha": "1eec659f6be3b3773e66d59078b03fead81266e6", "size": 769, "ext": "py", "lang": "Python", "max_stars_repo_path": "sim1/q5.py", "max_stars_repo_name": "Rafael-Ramblas/EEL7417-Fundamentos", "max_stars_repo_head_hexsha": "d5dcc366b59ced2029088782ec15a905107e7097", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sim1/q5.py", "max_issues_repo_name": "Rafael-Ramblas/EEL7417-Fundamentos", "max_issues_repo_head_hexsha": "d5dcc366b59ced2029088782ec15a905107e7097", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sim1/q5.py", "max_forks_repo_name": "Rafael-Ramblas/EEL7417-Fundamentos", "max_forks_repo_head_hexsha": "d5dcc366b59ced2029088782ec15a905107e7097", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4814814815, "max_line_length": 85, "alphanum_fraction": 0.7321196359, "include": true, "reason": "import numpy,from scipy", "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9830850892111576, "lm_q2_score": 0.8740772335247532, "lm_q1q2_score": 0.8592922950971238}}
{"text": "import numpy as np\nimport sympy as sp\n\n\ndef eigenstuff(R):\n    # Calculate their eigenvalues, eigenvectors, and\n    #  conditioning numbers\n\n    eigenvalues, eigenvectors = np.linalg.eig(R)\n    conditioning_number = max(eigenvalues) / min(eigenvalues)\n\n    # Setando a precisão para 3 pro print ficar mais bonito.\n    np.set_printoptions(precision=3)\n\n    print(f'A matriz R:')\n    print(R)\n    print('\\n')\n    print(f'Autovalores de R: {eigenvalues}')\n    print(f'Autovetores de R:')\n    print(eigenvectors)\n    print(f'Número de condicionamento de R: {conditioning_number:.3f}')\n\n\ndef symbolic_eigevalues(R):\n\n    print('\\n')\n    print(f'Autovalores e suas multiplicidades:')\n    print(R.eigenvals())\n\n\ndef symbolic_eigenstuff(R):\n    print('\\n')\n    print('Autovalores, multiplicidade e autoveores:')\n    print(R.eigenvects())\n\n\ndef symbolic_diagonalize(R):\n    P, D = R.diagonalize()\n    print('\\n \\n')\n    print('Diagonalização da matriz R:')\n    print(P)\n    print(D)\n    print(P**-1)\n", "meta": {"hexsha": "8a1792434c3cfac080c73b4ab12e768cf8a7e838", "size": 991, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/utils/eigen.py", "max_stars_repo_name": "mesquita/adaptativos", "max_stars_repo_head_hexsha": "533c59f69d544597bf51235b1fa893631ac74aec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/utils/eigen.py", "max_issues_repo_name": "mesquita/adaptativos", "max_issues_repo_head_hexsha": "533c59f69d544597bf51235b1fa893631ac74aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/utils/eigen.py", "max_forks_repo_name": "mesquita/adaptativos", "max_forks_repo_head_hexsha": "533c59f69d544597bf51235b1fa893631ac74aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5227272727, "max_line_length": 71, "alphanum_fraction": 0.6690211907, "include": true, "reason": "import numpy,import sympy", "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924777713886, "lm_q2_score": 0.8840392802184581, "lm_q1q2_score": 0.8592795304267741}}
{"text": "\"\"\"\nThe prime HP reached starting from a number , concatenating its prime factors, and repeating until a prime is reached.\nIf you have doubts, refer the article here [http://mathworld.wolfram.com/HomePrime.html]\n\nwrite a function to calculate the HP of a given number.\n\nAlso write a function to compute the Euclid-Mullin sequence [http://mathworld.wolfram.com/Euclid-MullinSequence.html].\n\"\"\"\n\nimport numpy as np\n\n\ndef is_prime(n):\n    \"\"\"https://stackoverflow.com/questions/15285534/isprime-function-for-python-language\"\"\"\n    if n == 2 or n == 3: return True\n    if n < 2 or n%2 == 0: return False\n    if n < 9: return True\n    if n%3 == 0: return False\n    r = int(n**0.5)\n    f = 5\n    while f <= r:\n        if n%f == 0: return False\n        if n%(f+2) == 0: return False\n        f +=6\n    return True\n\n\ndef factorize(n):\n    active_num = n\n\n    factors = []\n    n = 2\n    while active_num != 1:\n        if active_num % n == 0:\n            active_num /= n\n            factors.append(str(n))\n        else:\n            n += 1\n    return factors\n\n\ndef home_prime(n):\n    while not is_prime(n):\n        n = int(''.join(factorize(n)))\n    return n\n\n\ndef euclid_mullin(n):\n    e_m = []\n    for i in range(n):\n        e_m.append(int(factorize(np.prod(e_m)+1)[0]))\n        print(e_m)\n    return e_m\n\nif __name__ == '__main__':\n    print(home_prime(5))\n    euclid_mullin(9)", "meta": {"hexsha": "9957be370fe2831158fc3eff54394252dc896517", "size": 1368, "ext": "py", "lang": "Python", "max_stars_repo_path": "DailyProgrammer/20120430C.py", "max_stars_repo_name": "DayGitH/Python-Challenges", "max_stars_repo_head_hexsha": "bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-23T18:59:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T13:16:09.000Z", "max_issues_repo_path": "DailyProgrammer/20120430C.py", "max_issues_repo_name": "DayGitH/Python-Challenges", "max_issues_repo_head_hexsha": "bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DailyProgrammer/20120430C.py", "max_forks_repo_name": "DayGitH/Python-Challenges", "max_forks_repo_head_hexsha": "bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0, "max_line_length": 118, "alphanum_fraction": 0.6052631579, "include": true, "reason": "import numpy", "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399069145609, "lm_q2_score": 0.8856314828740729, "lm_q1q2_score": 0.8592750075043449}}
{"text": "\"\"\"\nCreated on Fri Feb 18 09:50:30 2022\n\n@author: udaytalwar\n\"\"\"\n\n'''\nReferences:\n\nASX Portfolio on YouTube\nPaul Wilmott's \"The Mathematics of Financial Derivatives: A Student Introduction\"\n\n'''\n\nimport scipy.stats as stats\nimport math as m \nimport numpy as np\n\n#calculating option price using Black-Scholes \n\ndef d(S, K, sigma, r, t):\n    \n    '''\n    S = Current Price\n    K = Strike Price\n    sigma = Volatility\n    r = annualized risk-free rate\n    t = time to expiration\n    \n    returns d1, d2 for option price calculation using Black Scholes\n    '''\n    d1 = (m.log(S/K) + (r + (sigma**2/2))*t) * (1/(sigma*m.sqrt(t)))\n    \n    d2 = d1 - sigma*m.sqrt(t)\n    \n    return d1, d2\n\ndef option_price(S, K, sigma, r, t, flag, d1 = 0, d2 = 0):\n    \n    '''\n    S = Current Price\n    K = Strike Price\n    sigma = Volatility\n    r = annualized risk-free rate\n    t = time to expiration\n    flag = 'Call' or 'Put'\n    \n    returns option price according to Black Scholes\n    '''\n    \n    if d1 == 0 and d2 == 0:\n    \n        d1, d2 = d(S, K, sigma, r, t)\n        \n        if flag == 'Call':\n            \n            price = stats.norm.cdf(d1)*S - stats.norm.cdf(d2)*K*m.exp(-r*t)\n            \n        elif flag == 'Put':\n            \n            price = stats.norm.cdf(-d2)*K*m.exp(-r*t) - stats.norm.cdf(-d1)*S\n            \n        return price \n\n    else: \n        \n        if flag == 'Call':\n            \n            price = stats.norm.cdf(d1)*S - stats.norm.cdf(d2)*K*m.exp(-r*t)\n            \n        elif flag == 'Put':\n            \n            price = stats.norm.cdf(-d2)*K*m.exp(-r*t) - stats.norm.cdf(-d1)*S\n            \n        return price  \n    \n#calculating option price using Monte Carlo Approximation\n\ndef option_price_MC(S, K, sigma, r, t, flag, steps, paths, error = False):\n\n    '''\n    S = Current Price\n    K = Strike Price\n    sigma = Volatility\n    r = annualized risk-free rate\n    t = time to expiration\n    flag = 'Call' or 'Put'\n    steps = number of steps per path \n    paths = number of paths to simulate\n    error = False, if true returns (price, approximation error)\n    \n    returns expected option price from simulation\n\n    '''\n        \n    timestep = t/steps \n    \n    nudt = (r - 0.5*sigma**2)*timestep\n    \n    volsdt = vol*m.sqrt(timestep)\n    \n    lnS = m.log(S)\n    \n    random_matr = np.random.normal(size=(steps,paths))\n\n    delta_lnSt = nudt + volsdt*random_matr\n    \n    lnSt = lnS + np.cumsum(delta_lnSt, axis = 0)\n    \n    lnSt = np.concatenate( (np.full(shape = (1,paths), fill_value = lnS), lnSt))\n    \n    ST = np.exp(lnSt)\n    \n    if flag == 'Call':    \n        price = np.maximum(0, ST - K)\n    \n    elif flag == 'Put':\n        price = np.maximum(0, K - ST)\n    \n    initial_price = np.exp(-r*t)*np.sum(price[-1])/paths\n    \n    err = np.sqrt(np.sum((price[-1]-initial_price)**2)/(paths-1))\n    \n    SE = err/m.sqrt(paths)\n    \n    if error == True: \n        \n        return initial_price, SE\n\n    else:\n        return initial_price\n\n#calculating option price using Binomial Trees\n\ndef option_price_BT(S, K, sigma, r, t, flag, steps):\n\n    '''\n    S = Current Price\n    K = Strike Price\n    sigma = Volatility\n    r = annualized risk-free rate\n    t = time to expiration\n    flag = 'Call' or 'Put'\n    steps = number of steps per path \n    \n    returns option price using Binomial Trees\n    '''\n\n    \n    timestep = t/steps #equivalent to dt, a discrete time step to iterate through\n    \n    \n    #the formulas for A, d, u and p are described in Wilmott's book \n    \n    A = (1.0/2.0)*(m.exp(-r*timestep)+m.exp((r+sigma**2)*timestep))\n    \n    d = A - m.sqrt(A**2 - 1)\n    \n    u = A + m.sqrt(A**2 - 1)\n    \n    p = (m.exp(r*timestep)-d)/(u-d)\n\n    #discount function to discount the final value back to our initial value ie current option price\n    discount = m.exp(-r*timestep)\n\n    #price at node (i,j) at timestep i is = start price * d^(i-j)*u^(i) where j is the number of the node at the \n    # given time step, where we count from the bottom of the tree up to the top\n\n    price = S * d ** (np.arange(steps,-1,-1)) * u **(np.arange(0, steps+1, 1))\n    \n        #price - K for Call, K - price for put\n    if flag == 'Call':\n    \n        price = np.maximum(price - K, np.zeros(steps+1))\n    \n    elif flag == 'Put':\n        \n        price = np.maximum(K - price, np.zeros(steps+1))\n    \n        #apply the discount function to iteratively arrive at initial value\n        \n    for j in np.arange(steps, 0, -1):\n        \n        # formula below also given in Wilmott's book \n        \n        price = discount * (p * price[1:j+1] + (1-p) * price[0:j])\n    \n    return price[0]\n    \n\nt = 30.0/365.0\nS0 = 100\nK = 100\nflag = 'Put'\nvol = (0.4/30.0)*np.sqrt(365)\nr = 0.015\n\nsteps = 20\npaths = 10000\nsteps_bt = 500\n\nprint('Price according to B-S = ',str(round(option_price(S0, K, vol, r, t, flag), 3)))\n\nprint('Price according to Monte Carlo = ',str(round(option_price_MC(S0, K, vol, r, t, flag, steps, paths), 3)))\n\nprint('Price according to Binomial Tree= ',str(round(option_price_BT(S0, K, vol, r, t, flag, steps_bt), 3)))\n", "meta": {"hexsha": "407e049e379500d9a0b2718bd4390d2b19758a93", "size": 5069, "ext": "py", "lang": "Python", "max_stars_repo_path": "OptionPricing.py", "max_stars_repo_name": "ta1war/Option-Pricing", "max_stars_repo_head_hexsha": "d170ce38296cdaa406ca4dc27c1801009cf4e909", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "OptionPricing.py", "max_issues_repo_name": "ta1war/Option-Pricing", "max_issues_repo_head_hexsha": "d170ce38296cdaa406ca4dc27c1801009cf4e909", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OptionPricing.py", "max_forks_repo_name": "ta1war/Option-Pricing", "max_forks_repo_head_hexsha": "d170ce38296cdaa406ca4dc27c1801009cf4e909", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4879227053, "max_line_length": 113, "alphanum_fraction": 0.5628329059, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399034724604, "lm_q2_score": 0.885631470799559, "lm_q1q2_score": 0.8592749927407372}}
{"text": "# Fast Fourier Transform is an algorithm to efficiently multiply polynomials among many other applications\r\n# Fast Fourier Transform is a divide and conquer that splits the X(n) sequence of values recursively\r\n# performs DFT on pairs of elements and then combines the results\r\n\r\nimport numpy as np\r\n\r\n\r\n# O(N^2) DFT calculation\r\ndef dft(x):\r\n    x = np.asarray(x, dtype=float)\r\n    N = x.shape[0]\r\n    n = np.arange(N)\r\n    k = n.reshape((N, 1))\r\n    M = np.exp(-2j * np.pi * k * n / N)\r\n    return np.dot(M, x)\r\n\r\n\r\n# D&C FFT: You can think of FFT as a method to apply DFT recursively by split domain space\r\n# that utilizes specific value points that achieve further reduction in computations needed.\r\ndef fft(x):\r\n    x = np.asarray(x, dtype=float)\r\n    N = x.shape[0]\r\n    if N % 2 > 0:\r\n        raise ValueError(\"must be a power of 2\")\r\n    elif N <= 2:\r\n        return dft(x)\r\n    else:\r\n        X_even = fft(x[::2])\r\n        X_odd = fft(x[1::2])\r\n        terms = np.exp(-2j * np.pi * np.arange(N) / N)\r\n        return np.concatenate([X_even + terms[:int(N / 2)] * X_odd,\r\n                               X_even + terms[int(N / 2):] * X_odd])\r\n\r\n\r\n# Another function to compute the Fourier Transform.\r\n# This time, we make use of vector operations instead of recursion.\r\n\r\ndef fft_v(x):\r\n    x = np.asarray(x, dtype=float)\r\n    N = x.shape[0]\r\n    if np.log2(N) % 1 > 0:\r\n        raise ValueError(\"must be a power of 2\")\r\n\r\n    N_min = min(N, 2)\r\n\r\n    n = np.arange(N_min)\r\n    k = n[:, None]\r\n    M = np.exp(-2j * np.pi * n * k / N_min)\r\n    X = np.dot(M, x.reshape((N_min, -1)))\r\n\r\n    while X.shape[0] < N:\r\n        X_even = X[:, :int(X.shape[1] / 2)]\r\n        X_odd = X[:, int(X.shape[1] / 2):]\r\n        terms = np.exp(-1j * np.pi * np.arange(X.shape[0])\r\n                       / X.shape[0])[:, None]\r\n        X = np.vstack([X_even + terms * X_odd,\r\n                       X_even - terms * X_odd])\r\n    return X.ravel()\r\n\r\n\r\nimport time\r\n\r\n\r\ndef main():\r\n    # Validate results\r\n    x = np.random.random(1024)\r\n    np.allclose(dft(x), np.fft.fft(x))\r\n\r\n    # timeit\r\n\r\n    t0 = time.time()\r\n    dft(x)\r\n    t1 = time.time()\r\n    print(t1 - t0)\r\n\r\n    t0 = time.time()\r\n    np.fft.fft(x)\r\n    t1 = time.time()\r\n    print(t1 - t0)\r\n\r\n    # Validate results\r\n    x = np.random.random(1024)\r\n    np.allclose(fft(x), np.fft.fft(x))\r\n\r\n    # timeit\r\n    t0 = time.time()\r\n    dft(x)\r\n    t1 = time.time()\r\n    print(t1 - t0)\r\n\r\n    t0 = time.time()\r\n    fft(x)\r\n    t1 = time.time()\r\n    print(t1 - t0)\r\n\r\n    t0 = time.time()\r\n    np.fft.fft(x)\r\n    t1 = time.time()\r\n    print(t1 - t0)\r\n\r\n    # Validate results\r\n    x = np.random.random(1024)\r\n    np.allclose(fft_v(x), np.fft.fft(x))\r\n\r\n    # timeit\r\n    t0 = time.time()\r\n    fft(x)\r\n    t1 = time.time()\r\n    print(t1 - t0)\r\n\r\n    t0 = time.time()\r\n    fft_v(x)\r\n    t1 = time.time()\r\n    print(t1 - t0)\r\n\r\n    t0 = time.time()\r\n    np.fft.fft(x)\r\n    t1 = time.time()\r\n    print(t1 - t0)\r\n\r\n\r\nif __name__ == '__main__':\r\n    main()\r\n", "meta": {"hexsha": "cfee8c9617e64d460190c350a89c366ae2c78011", "size": 2994, "ext": "py", "lang": "Python", "max_stars_repo_path": "divide_and_conqure/Fast_Fourier_Transform.py", "max_stars_repo_name": "YaserMarey/algos_catalog", "max_stars_repo_head_hexsha": "89617df4d286789e61a0c3e99c6a5265da1f0257", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-02T11:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-02T11:14:12.000Z", "max_issues_repo_path": "divide_and_conqure/Fast_Fourier_Transform.py", "max_issues_repo_name": "YaserMarey/algos_catalog", "max_issues_repo_head_hexsha": "89617df4d286789e61a0c3e99c6a5265da1f0257", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "divide_and_conqure/Fast_Fourier_Transform.py", "max_forks_repo_name": "YaserMarey/algos_catalog", "max_forks_repo_head_hexsha": "89617df4d286789e61a0c3e99c6a5265da1f0257", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1451612903, "max_line_length": 107, "alphanum_fraction": 0.5303941216, "include": true, "reason": "import numpy", "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702398991698343, "lm_q2_score": 0.8856314617436728, "lm_q1q2_score": 0.8592749801438141}}
{"text": "import matplotlib.pyplot as plt\r\nimport numpy\r\n\r\ndef calc_mean(list_values):\r\n\tpre_mean = 0\r\n\tfor x in list_values:\r\n\t\tpre_mean = pre_mean + x\r\n\t\t\r\n\treturn (pre_mean / len(list_values))\r\n\t\r\n\t\r\ndef sum_of_squared_errors(list_values, mean):\r\n\tsse = 0\r\n\tfor x in list_values:\r\n\t\tsse = sse + (x-mean)**2\r\n\t\t\r\n\treturn sse\r\n\t\r\n\t\r\ndef sum_of_multiplied_xy(list_values_x, list_values_y, x_mean, y_mean):\r\n\tsmxy = 0\r\n\tfor i in range(0, len(list_values_x)):\r\n\t\tsmxy = smxy + (list_values_x[i] - x_mean)*(list_values_y[i] - y_mean)\r\n\t\t\r\n\treturn smxy\r\n\t\r\n\t\r\ndef cov(x, y):\r\n    x_mean = calc_mean(x)\r\n    y_mean = calc_mean(y)\r\n    data = [(x[i] - x_mean) * (y[i] - y_mean)\r\n            for i in range(len(x))]\r\n    return sum(data) / (len(data) - 1)\r\n\t\r\n\t\r\ndef var(values, average):\r\n    variance = 0\r\n    for number in values:\r\n        variance += (average - number) ** 2\r\n    return variance / len(values)\r\n\t\r\n\t\r\n\r\nif __name__ == \"__main__\":\r\n\tx_values = [1, 4, 4, 5]\r\n\ty_values = [3, 6, 8, 2]\r\n\tx_mean = calc_mean(x_values)\r\n\ty_mean = calc_mean(y_values)\r\n\t\r\n\t\r\n\tSSE = sum_of_squared_errors(y_values, y_mean) #changes made here\r\n\tSMXY = sum_of_multiplied_xy(x_values, y_values, x_mean, y_mean)\r\n\t\r\n\tslope = SSE / SMXY\r\n\tslope_2 = cov(x_values, y_values) / var(x_values, x_mean)\r\n\t\r\n\tb = y_mean - (slope_2 * x_mean)\r\n\t\r\n\tprint(\"m = %.2f\\nb = %.2f\" % (slope_2, b))\r\n\t\r\n\tplt.plot(x_values, y_values, \"ro\")\r\n\tx = numpy.array(x_values)\r\n\ty = slope_2*x+b\r\n\tplt.plot(x, y)\r\n\t#plt.axis([0, 6, 0, 5])\r\n\tplt.show()\r\n\t\r\n\t\r\n\t\r\n\t", "meta": {"hexsha": "fbfe9c0eda48f70705704e55cea3937099b02256", "size": 1508, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_regression.py", "max_stars_repo_name": "johannalbers/algorithms", "max_stars_repo_head_hexsha": "a5d9f485a555d465ba00a99de6ce7bec32284a07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_regression.py", "max_issues_repo_name": "johannalbers/algorithms", "max_issues_repo_head_hexsha": "a5d9f485a555d465ba00a99de6ce7bec32284a07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_regression.py", "max_forks_repo_name": "johannalbers/algorithms", "max_forks_repo_head_hexsha": "a5d9f485a555d465ba00a99de6ce7bec32284a07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5428571429, "max_line_length": 72, "alphanum_fraction": 0.6100795756, "include": true, "reason": "import numpy", "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773708026035287, "lm_q2_score": 0.8791467643431002, "lm_q1q2_score": 0.8592523786723112}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\n# 42. Ten pregnant women were given an injection of pitocin to induce labor. Their\n# systolic blood pressures immediately before and after the injection were:\n\nbefore = [134, 122, 132, 130, 128, 140, 118, 127, 125, 142]\nafter = [140, 130, 135, 126, 134, 138, 124, 126, 132, 144]\n\n# vamos a implementar un metodo de shuffling. para hacer esto la hipotesis nula\n# es que ambas series de datos vienen de la misma distribucion. \n# la estadistica que vamos a calcular es el promedio de las diferencias.\n\nn_mc = 10000\nn = len(before)\nmu_mc = np.zeros(n_mc)\ndatos = np.array(before+after)\nfor i in range(n_mc):\n    np.random.shuffle(datos)\n    new_before = datos[:n]\n    new_after = datos[n:]\n    mu_mc[i] = np.mean(new_before - new_after)\n\nmu = np.mean(np.array(before) - np.array(after))\np_value = np.count_nonzero(np.abs(mu_mc)>np.abs(mu))/n_mc\nif p_value<0.05:\n    H = 'SI'\nelse:\n    H = 'NO'\nprint('Problema 42. p-value: {:.2f}. La droga {} tiene un efecto en la presion'.format(p_value, H))\n\nplt.figure()\nplt.hist(mu_mc, bins=20)\nplt.axvline(mu, color='red')\nplt.savefig(\"tmp_42.png\")\n\n# 43. A question of medical importance is whether jogging leads to a\n#reduction in one’s pulse rate. To test this hypothesis, 8 nonjogging\n#volunteers agreed to begin a 1-month jogging program. After the month\n#their pulse rates were determined and compared with their earlier\n#values. If the data are as follows, can we conclude that jogging has\n#had an effect on the pulse rates?  \n\n\nbefore = [74,86,98,102,78,84,79,70] \nafter = [70,85,90,110,71,80,69,74]\n\n# vamos a implementar un metodo de shuffling. para hacer esto la hipotesis nula\n# es que ambas series de datos vienen de la misma distribucion. \n# la estadistica que vamos a calcular es el promedio de las diferencias\n\nn_mc = 10000\nn = len(before)\nmu_mc = np.zeros(n_mc)\ndatos = np.array(before+after)\nfor i in range(n_mc):\n    np.random.shuffle(datos)\n    new_before = datos[:n]\n    new_after = datos[n:]\n    mu_mc[i] = np.mean(new_before - new_after)\n\nmu = np.mean(np.array(before) - np.array(after))\np_value = np.count_nonzero(np.abs(mu_mc)>np.abs(mu))/n_mc\nif p_value<0.05:\n    H = 'SI'\nelse:\n    H = 'NO'\nprint('Problema 43. p-value: {:.2f}. Correr {} tiene un efecto en el pulso'.format(p_value, H))\n\nplt.figure()\nplt.hist(mu_mc, bins=20)\nplt.axvline(mu, color='red')\nplt.savefig(\"tmp_43.png\")\n\n#67. In the\n#nineteenseventies,theU.S.VeteransAdministration(Murphy,1977)con-\n#ducted an experiment comparing coronary artery bypass surgery with\n#medical drug therapy as treatments for coronary artery disease. The\n#experiment involved 596 patients, of whom 286 were randomly assigned\n#to receive surgery, with the remaining 310 assigned to drug\n#therapy. A total of 252 of those receiving surgery, and a total of\n#270 of those receiving drug therapy were still alive three years\n#after  Use these data to test the hypothesis that the survival\n#probabilities are equal.\n\n\nN_cirugia = 286\nN_droga = 310\nN_sobrevive_cirugia = 252\nN_sobrevive_droga = 270\n\n# Vamos a tomar como la probabilidad de supervivencia global\n# p_sobre = (N_sobrevive_cirugia+N_sobreviev_droga)/(N_cirugia+N_droga). \n# Si las probabilidades de supervivencia son iguales, entonce la\n# p_sobrevive para cualquiera de los casos (cirugia, droga) debe ser \n# consistente con p_sobre.\n# Vamos a generar entonces numeros aleatorios con la probabilidad\n# p_sobre y compararlo con el N_sobrevive_cirugia observado.\n\n\nn_mc  = 10000\np_sobre = (N_sobrevive_cirugia + N_sobrevive_droga)/(N_cirugia + N_droga)\n\nn_sobre_mc = np.zeros(n_mc)\nfor i in range(n_mc):\n    r = np.random.random(N_cirugia) \n    n_sobre_mc[i] = np.count_nonzero(r<p_sobre)\n\ndelta = np.abs(np.mean(n_sobre_mc) - N_sobrevive_cirugia)\np_value = np.count_nonzero(np.abs(n_sobre_mc - np.mean(n_sobre_mc))>delta)/n_mc\n\nif p_value<0.05:\n    H = 'NO'\nelse:\n    H = 'SI'\nprint('Problema 67. p-value: {:.2f}. Las probabilidades de supervivencia {} son iguales.'.format(p_value, H))\n\nplt.figure()\nplt.hist(n_sobre_mc, bins=20)\nplt.axvline(N_sobrevive_cirugia, color='red')\nplt.savefig(\"tmp_67.png\")\n\n\n#69 The following table gives the number\n#of fatal accidents o fU.S.commercialairline carriers in the 16 years from\n#1980 to 1995. Do these data disprove, at the 5 percent level of\n#significance, the hypothesis that the mean number of accidents in a\n#year is greater than or equal to 4.5? What is the p-value? (Hint:\n#First formulate a model for the number of accidents.) \n\naccidentes = [0, 4, 4, 4, 1, 4, 2, 4, 3, 11, 6, 4, 4, 1, 4, 2]\n\n# Se espera que el numero de accidentes anuales siga una distribucion \n# possoniana de parametro lambda. Dado que par esta distribucion el \n# valor medio es lambda, entonces vamos a comparar la suma total del \n# numero de accidentes observados con el numero total de accidentes\n# esperados si lambda fuera 4.5. \n\nn_mc = 10000\nn_acc = len(accidentes)\nn_tot_acc_mc = np.zeros(n_mc)\n\nfor i in range(n_mc):\n    n_tot_acc_mc[i] = np.sum(np.random.poisson(lam=4.5, size=n_acc))\n\n\np_1 = np.count_nonzero(n_tot_acc_mc<np.sum(accidentes))/n_mc\np_2 = np.count_nonzero(n_tot_acc_mc>np.sum(accidentes))/n_mc\np_value = 2.0*np.min([p_1, p_2])\n                           \n\nif p_value<0.05:\n    H = 'NO'\nelse:\n    H = 'SI'\nprint('Problema 69. p-value: {:.2f}. El numero promedio de accidentes {} es mayor o igual que 4.5.'.format(p_value, H))\n\nplt.figure()\nplt.hist(n_tot_acc_mc, bins=20)\nplt.axvline(np.sum(accidentes), color='red')\nplt.savefig(\"tmp_69.png\")\n\n\n", "meta": {"hexsha": "9bf2a9310772eb38be4bafbc537bed6b96cc2464", "size": 5501, "ext": "py", "lang": "Python", "max_stars_repo_path": "Metodos Computacionales Uniandes/Code/ejercicio_31.py", "max_stars_repo_name": "aess14/Cursos-Uniandes", "max_stars_repo_head_hexsha": "be016b25f2f49788235fbe91ec577fd16b9ad613", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Metodos Computacionales Uniandes/Code/ejercicio_31.py", "max_issues_repo_name": "aess14/Cursos-Uniandes", "max_issues_repo_head_hexsha": "be016b25f2f49788235fbe91ec577fd16b9ad613", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Metodos Computacionales Uniandes/Code/ejercicio_31.py", "max_forks_repo_name": "aess14/Cursos-Uniandes", "max_forks_repo_head_hexsha": "be016b25f2f49788235fbe91ec577fd16b9ad613", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3393939394, "max_line_length": 119, "alphanum_fraction": 0.7298672969, "include": true, "reason": "import numpy", "num_tokens": 1717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422269175634, "lm_q2_score": 0.9032942138630786, "lm_q1q2_score": 0.8591612701354784}}
{"text": "# you should fill in the functions in this file,\n# do NOT change the name, input and output of these functions\n\nimport numpy as np\nimport time\nimport matplotlib.pyplot as plt\n\n# first function to fill, compute distance matrix using loops\ndef compute_distance_naive(X):\n    N = X.shape[0]      # num of rows\n    D = X[0].shape[0]   # num of cols\n    \n    M = np.zeros([N,N])\n    for i in range(N):\n        for j in range(N):\n            xi = X[i,:]    # take ith row\n            xj = X[j,:]    # take jth row\n\n            dist = np.sqrt(np.sum((xi-xj)*(xi-xj)))  # a placetaker line\n\n            M[i,j] = dist\n\n    return M\n\n# second function to fill, compute distance matrix without loops\ndef compute_distance_smart(X):\n    N = X.shape[0]  # num of rows\n    D = X[0].shape[0]  # num of cols\n\n    # use X to create M\n    M = np.zeros([N, N])\n    A = np.zeros((N, N))\n    B = np.zeros((N, N))\n    C = np.zeros((N, N))\n\n    xiSum = np.sum(np.multiply(X,X), axis=1)   # row vector of length N. Sum over rows\n\n    A = np.transpose((xiSum, ) * N)   # clone vector xisum to a matrix of size NxN\n    #A = (xiSum * np.ones([N,1]))\n\n    #Xtr = np.transpose(X)\n\n    #B = np.dot(X, Xtr)\n    B = np.inner(X,X)\n    C = np.transpose(A)\n\n    Sum = np.add(np.add(A, -2 * B), C)\n\n    M = np.sqrt(abs(Sum))   # M = sqrt(A - 2*B + C)\n\n    return M\n\n# third function to fill, compute correlation matrix using loops\ndef compute_correlation_naive(X):\n    N = X.shape[0]  # num of rows\n    D = X[0].shape[0]  # num of cols\n\n    # use X to create M\n    M = np.zeros([D, D])\n\n    for i in range(D):\n        for j in range(D):\n            xi = X[:, i]   # take ith column\n            xj = X[:, j]   # take jth column\n            xih = xi - np.sum(xi).astype(float) / N   # xi - mui\n            xjh = xj - np.sum(xj).astype(float) / N   # xj - muj\n            sij = (np.dot(xih, xjh)).astype(float) / (N-1)    # covariance at i row j column\n\n            stdi = np.sqrt(np.dot(xih, xih).astype(float) / (N - 1))  # sigmai\n            stdj = np.sqrt(np.dot(xjh, xjh).astype(float) / (N - 1))  # sigmaj\n            corr = sij.astype(float) / stdi / stdj # a placetaker line,\n                    #  you have to change it to correlation between xi and xj\n            M[i, j] = corr\n\n    return M\n\n# fourth function to fill, compute correlation matrix without loops\ndef compute_correlation_smart(X):\n    N = X.shape[0]  # num of rows\n    D = X[0].shape[0]  # num of cols\n\n    # use X to create M\n    M = np.zeros([D, D])\n\n    mu = (np.sum(X, axis=0)).astype(float) / N    #mean vector. column sum of column vectors\n\n    MatrixMu = mu * np.ones([N,1])    #matrix with  mu\n\n    Xmu = X - MatrixMu\n\n    S = (np.dot(np.transpose(Xmu),Xmu)).astype(float) / (N-1)     #covariance matrix\n\n    varvector = (np.sum(np.multiply(Xmu, Xmu),axis=0)).astype(float) / (N-1)     #variance vector\n\n    std = np.sqrt(varvector)    #std vector\n\n    Denom = np.outer(std, std)     #denominator matrix\n\n    M = np.multiply(S, np.power(Denom, -1))\n\n    return M\n\ndef main():\n    print 'starting comparing distance computation .....'\n    np.random.seed(100)\n    params = range(10,141,10)   # different param setting\n    nparams = len(params)       # number of different parameters\n\n    perf_dist_loop = np.zeros([10,nparams])  # 10 trials = 10 rows, each parameter is a column\n    perf_dist_cool = np.zeros([10,nparams])\n    perf_corr_loop = np.zeros([10,nparams])  # 10 trials = 10 rows, each parameter is a column\n    perf_corr_cool = np.zeros([10,nparams])\n\n\n    counter = 0\n\n    for ncols in params:\n        nrows = ncols * 10\n\n        print \"matrix dimensions: \", nrows, ncols\n\n        for i in range(10):\n            X = np.random.rand(nrows, ncols)   # random matrix\n\n            # compute distance matrices\n            st = time.time()\n            dist_loop = compute_distance_naive(X)\n            et = time.time()\n            perf_dist_loop[i,counter] = et - st              # time difference\n\n            st = time.time()\n            dist_cool = compute_distance_smart(X)\n            et = time.time()\n            perf_dist_cool[i,counter] = et - st\n\n            assert np.allclose(dist_loop, dist_cool, atol=1e-06) # check if the two computed matrices are identical all the time\n\n            # compute correlation matrices\n            st = time.time()\n            corr_loop = compute_correlation_naive(X)\n            et = time.time()\n            perf_corr_loop[i,counter] = et - st              # time difference\n\n            st = time.time()\n            corr_cool = compute_correlation_smart(X)\n            et = time.time()\n            perf_corr_cool[i,counter] = et - st\n\n            assert np.allclose(corr_loop, corr_cool, atol=1e-06) # check if the two computed matrices are identical all the time\n\n        counter = counter + 1\n\n    mean_dist_loop = np.mean(perf_dist_loop, axis = 0)    # mean time for each parameter setting (over 10 trials)\n    mean_dist_cool = np.mean(perf_dist_cool, axis = 0)\n    std_dist_loop = np.std(perf_dist_loop, axis = 0)      # standard deviation\n    std_dist_cool = np.std(perf_dist_cool, axis = 0)\n\n    plt.figure(1)\n    plt.errorbar(params, mean_dist_loop[0:nparams], yerr=std_dist_loop[0:nparams], color='red',label = 'Loop Solution for Distance Comp')\n    plt.errorbar(params, mean_dist_cool[0:nparams], yerr=std_dist_cool[0:nparams], color='blue', label = 'Matrix Solution for Distance Comp')\n    plt.xlabel('Number of Cols of the Matrix')\n    plt.ylabel('Running Time (Seconds)')\n    plt.title('Comparing Distance Computation Methods')\n    plt.legend()\n    plt.savefig('CompareDistanceCompFig.pdf')\n    # plt.show()    # uncomment this if you want to see it right way\n    print \"result is written to CompareDistanceCompFig.pdf\"\n\n    mean_corr_loop = np.mean(perf_corr_loop, axis = 0)    # mean time for each parameter setting (over 10 trials)\n    mean_corr_cool = np.mean(perf_corr_cool, axis = 0)\n    std_corr_loop = np.std(perf_corr_loop, axis = 0)      # standard deviation\n    std_corr_cool = np.std(perf_corr_cool, axis = 0)\n\n    plt.figure(2)\n    plt.errorbar(params, mean_corr_loop[0:nparams], yerr=std_corr_loop[0:nparams], color='red',label = 'Loop Solution for Correlation Comp')\n    plt.errorbar(params, mean_corr_cool[0:nparams], yerr=std_corr_cool[0:nparams], color='blue', label = 'Matrix Solution for Correlation Comp')\n    plt.xlabel('Number of Cols of the Matrix')\n    plt.ylabel('Running Time (Seconds)')\n    plt.title('Comparing Correlation Computation Methods')\n    plt.legend()\n    plt.savefig('CompareCorrelationCompFig.pdf')\n    # plt.show()    # uncomment this if you want to see it right way\n    print \"result is written to CompareCorrelationCompFig.pdf\"\n\nif __name__ == \"__main__\": main()\n", "meta": {"hexsha": "5b9d461d4e6a820492d69265af2072fce03a6f62", "size": 6711, "ext": "py", "lang": "Python", "max_stars_repo_path": "ComputeMatrices.py", "max_stars_repo_name": "Tsyrema/Computing-the-Distance-Matrix-and-the-Covariance-Matrix-of-Data", "max_stars_repo_head_hexsha": "e1e4f11fd98c2f812912c626c482813b0b945ebc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ComputeMatrices.py", "max_issues_repo_name": "Tsyrema/Computing-the-Distance-Matrix-and-the-Covariance-Matrix-of-Data", "max_issues_repo_head_hexsha": "e1e4f11fd98c2f812912c626c482813b0b945ebc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ComputeMatrices.py", "max_forks_repo_name": "Tsyrema/Computing-the-Distance-Matrix-and-the-Covariance-Matrix-of-Data", "max_forks_repo_head_hexsha": "e1e4f11fd98c2f812912c626c482813b0b945ebc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0806451613, "max_line_length": 144, "alphanum_fraction": 0.6119803308, "include": true, "reason": "import numpy", "num_tokens": 1895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476944, "lm_q2_score": 0.9032942067038784, "lm_q1q2_score": 0.8591612608240541}}
{"text": "from __future__ import division  # floating point division\nimport math\nimport numpy as np\n\n\ndef mean(numbers):\n    return sum(numbers)/float(len(numbers))\n \ndef stdev(numbers):\n    avg = mean(numbers)\n    variance = sum([pow(x-avg,2) for x in numbers])/float(len(numbers)-1)\n    return math.sqrt(variance)\n    \ndef sigmoid(xvec):\n    \"\"\" Compute the sigmoid function \"\"\"\n    # Cap -xvec, to avoid overflow\n    # Undeflow is okay, since it get set to zero\n    xvec[xvec < -100] = -100\n\n    vecsig = 1.0 / (1.0 + np.exp(np.negative(xvec)))\n \n    return vecsig\n\ndef dsigmoid(xvec):\n    \"\"\" Gradient of standard sigmoid 1/(1+e^-x) \"\"\"\n    vecsig = sigmoid(xvec)\n    return vecsig * (1 - vecsig)\n\ndef l2(vec):\n    \"\"\" l2 norm on a vector \"\"\"\n    return np.linalg.norm(vec)\n\ndef dl2(vec):\n    \"\"\" Gradient of l2 norm on a vector \"\"\"\n    return vec\n\ndef l1(vec):\n    \"\"\" l1 norm on a vector \"\"\"\n    return np.linalg.norm(vec, ord=1)\n\ndef threshold_probs(probs):\n    \"\"\" Converts probabilities to hard classification \"\"\"\n    classes = np.ones(len(probs),)\n    classes[probs < 0.5] = 0\n    return classes\n                          \n\ndef logsumexp(a):\n    \"\"\"\n    Compute the log of the sum of exponentials of input elements.\n    Modified scipys logsumpexp implemenation for this specific situation\n    \"\"\"\n\n    awithzero = np.hstack((a, np.zeros((len(a),1))))\n    maxvals = np.amax(awithzero, axis=1)\n    aminusmax = np.exp((awithzero.transpose() - maxvals).transpose())\n\n    # suppress warnings about log of zero\n    with np.errstate(divide='ignore'):\n        out = np.log(np.sum(aminusmax, axis=1))\n\n    out = np.add(out,maxvals)\n\n    return out\n\ndef update_dictionary_items(dict1, dict2):\n    \"\"\" Replace any common dictionary items in dict1 with the values in dict2 \n    There are more complicated and efficient ways to perform this task,\n    but we will always have small dictionaries, so for our use case, this simple\n    implementation is acceptable.\n    \"\"\"\n    for k in dict1:\n        if k in dict2:\n            dict1[k]=dict2[k]\n", "meta": {"hexsha": "faa0ef30bce08ad385321d6f05cfe57d2b67ba28", "size": 2030, "ext": "py", "lang": "Python", "max_stars_repo_path": "A2/utilities.py", "max_stars_repo_name": "bgod2/MachineLearning", "max_stars_repo_head_hexsha": "55e0daf650cc2387ac269f6ff201fdbe8de7d010", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A2/utilities.py", "max_issues_repo_name": "bgod2/MachineLearning", "max_issues_repo_head_hexsha": "55e0daf650cc2387ac269f6ff201fdbe8de7d010", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A2/utilities.py", "max_forks_repo_name": "bgod2/MachineLearning", "max_forks_repo_head_hexsha": "55e0daf650cc2387ac269f6ff201fdbe8de7d010", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0666666667, "max_line_length": 80, "alphanum_fraction": 0.642364532, "include": true, "reason": "import numpy", "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422172230208, "lm_q2_score": 0.9032942125614059, "lm_q1q2_score": 0.8591612601403782}}
{"text": "\nimport numpy as np\nfrom scipy import linalg\nimport matplotlib.pyplot as plt\n\n\ndef auto_corr(x, nlags, demean=True):\n    \"\"\"\n    autocorrelation like statsmodels\n    https://stackoverflow.com/a/51168178\n    \"\"\"\n\n    var=np.var(x)\n\n    if demean:\n        x -= np.mean(x)\n\n    corr = np.full(nlags+1, np.nan, np.float64)\n    corr[0] = 1.\n\n    for l in range(1, nlags+1):\n        corr[l] = np.sum(x[l:]*x[:-l])/len(x)/var\n\n    return corr\n\n\ndef pac_yw(x, nlags):\n    \"\"\"partial autocorrelation according to ywunbiased method\"\"\"\n\n    pac = np.full(nlags+1, fill_value=np.nan, dtype=np.float64)\n    pac[0] = 1.\n\n    for l in range(1, nlags+1):\n        pac[l] = ar_yw(x, l)[-1]\n\n    return pac\n\n\ndef ar_yw(x, order=1, adj_needed=True, demean=True):\n    \"\"\"Performs autoregressor using Yule-Walker method.\n    Returns:\n        rho : np array\n        coefficients of AR\n    \"\"\"\n    x = np.array(x, dtype=np.float64)\n\n    if demean:\n        x -= x.mean()\n\n    n = len(x)\n    r = np.zeros(order+1, np.float64)\n    r[0] = (x ** 2).sum() / n\n    for k in range(1, order+1):\n        r[k] = (x[0:-k] * x[k:]).sum() / (n - k * adj_needed)\n    R = linalg.toeplitz(r[:-1])\n\n    rho = np.linalg.solve(R, r[1:])\n    return rho\n\n\n\ndef plot_autocorr(\n        x,\n        axis=None,\n        plot_marker=True,\n        show=True,\n        legend=None,\n        title=None,\n        xlabel=None,\n        vlines_colors=None,\n        hline_color=None,\n        marker_color=None,\n        legend_fs=None\n):\n\n    if not axis:\n        _, axis = plt.subplots()\n\n    if plot_marker:\n        axis.plot(x, 'o', color=marker_color, label=legend)\n        if legend:\n            axis.legend(fontsize=legend_fs)\n    axis.vlines(range(len(x)), [0], x, colors=vlines_colors)\n    axis.axhline(color=hline_color)\n\n    if title:\n        axis.set_title(title)\n    if xlabel:\n        axis.set_xlabel(\"Lags\")\n\n    if show:\n        plt.show()\n\n    return axis\n\ndef ccovf_np(x, y, unbiased=True, demean=True):\n    n = len(x)\n    if demean:\n        xo = x - x.mean()\n        yo = y - y.mean()\n    else:\n        xo = x\n        yo = y\n    if unbiased:\n        xi = np.ones(n)\n        d = np.correlate(xi, xi, 'full')\n    else:\n        d = n\n    return (np.correlate(xo, yo, 'full') / d)[n - 1:]\n\n\ndef ccf_np(x, y, unbiased=True):\n    \"\"\"cross correlation between two time series\n    # https://stackoverflow.com/a/24617594\n    \"\"\"\n    cvf = ccovf_np(x, y, unbiased=unbiased, demean=True)\n    return cvf / (np.std(x) * np.std(y))\n", "meta": {"hexsha": "620b037c3c80d45a7c4341c92d992d707c910762", "size": 2472, "ext": "py", "lang": "Python", "max_stars_repo_path": "ai4water/eda/utils.py", "max_stars_repo_name": "csiro-hydroinformatics/AI4Water", "max_stars_repo_head_hexsha": "cdb18bd4bf298f77b381f1829045a1e790146985", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-10-13T08:23:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-22T04:36:21.000Z", "max_issues_repo_path": "ai4water/eda/utils.py", "max_issues_repo_name": "csiro-hydroinformatics/AI4Water", "max_issues_repo_head_hexsha": "cdb18bd4bf298f77b381f1829045a1e790146985", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-15T02:42:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-15T02:51:07.000Z", "max_forks_repo_path": "ai4water/eda/utils.py", "max_forks_repo_name": "csiro-hydroinformatics/AI4Water", "max_forks_repo_head_hexsha": "cdb18bd4bf298f77b381f1829045a1e790146985", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-23T04:45:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-26T10:12:34.000Z", "avg_line_length": 20.9491525424, "max_line_length": 64, "alphanum_fraction": 0.5546116505, "include": true, "reason": "import numpy,from scipy", "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.9032941982430049, "lm_q1q2_score": 0.8591612527765601}}
{"text": "import numpy as np\n\na = np.arange(24)\n\nprint(a)\n# [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]\n\nprint(a.shape)\n# (24,)\n\nprint(a.ndim)\n# 1\n\na_4_6 = a.reshape([4, 6])\n\nprint(a_4_6)\n# [[ 0  1  2  3  4  5]\n#  [ 6  7  8  9 10 11]\n#  [12 13 14 15 16 17]\n#  [18 19 20 21 22 23]]\n\nprint(a_4_6.shape)\n# (4, 6)\n\nprint(a_4_6.ndim)\n# 2\n\na_2_3_4 = a.reshape([2, 3, 4])\n\nprint(a_2_3_4)\n# [[[ 0  1  2  3]\n#   [ 4  5  6  7]\n#   [ 8  9 10 11]]\n# \n#  [[12 13 14 15]\n#   [16 17 18 19]\n#   [20 21 22 23]]]\n\nprint(a_2_3_4.shape)\n# (2, 3, 4)\n\nprint(a_2_3_4.ndim)\n# 3\n\n# a_5_6 = a.reshape([5, 6])\n# ValueError: cannot reshape array of size 24 into shape (5,6)\n\nprint(a.reshape(4, 6))\n# [[ 0  1  2  3  4  5]\n#  [ 6  7  8  9 10 11]\n#  [12 13 14 15 16 17]\n#  [18 19 20 21 22 23]]\n\nprint(a.reshape(2, 3, 4))\n# [[[ 0  1  2  3]\n#   [ 4  5  6  7]\n#   [ 8  9 10 11]]\n# \n#  [[12 13 14 15]\n#   [16 17 18 19]\n#   [20 21 22 23]]]\n\nprint(np.reshape(a, [4, 6]))\n# [[ 0  1  2  3  4  5]\n#  [ 6  7  8  9 10 11]\n#  [12 13 14 15 16 17]\n#  [18 19 20 21 22 23]]\n\nprint(np.reshape(a, [2, 3, 4]))\n# [[[ 0  1  2  3]\n#   [ 4  5  6  7]\n#   [ 8  9 10 11]]\n# \n#  [[12 13 14 15]\n#   [16 17 18 19]\n#   [20 21 22 23]]]\n\n# print(np.reshape(a, [5, 6]))\n# ValueError: cannot reshape array of size 24 into shape (5,6)\n\nprint(a.reshape(4, 6))\n# [[ 0  1  2  3  4  5]\n#  [ 6  7  8  9 10 11]\n#  [12 13 14 15 16 17]\n#  [18 19 20 21 22 23]]\n\n# print(np.reshape(a, 4, 6))\n# ValueError: cannot reshape array of size 24 into shape (4,)\n\nprint(a.reshape([4, 6], order='C'))\n# [[ 0  1  2  3  4  5]\n#  [ 6  7  8  9 10 11]\n#  [12 13 14 15 16 17]\n#  [18 19 20 21 22 23]]\n\nprint(a.reshape([4, 6], order='F'))\n# [[ 0  4  8 12 16 20]\n#  [ 1  5  9 13 17 21]\n#  [ 2  6 10 14 18 22]\n#  [ 3  7 11 15 19 23]]\n\nprint(a.reshape([2, 3, 4], order='C'))\n# [[[ 0  1  2  3]\n#   [ 4  5  6  7]\n#   [ 8  9 10 11]]\n# \n#  [[12 13 14 15]\n#   [16 17 18 19]\n#   [20 21 22 23]]]\n\nprint(a.reshape([2, 3, 4], order='F'))\n# [[[ 0  6 12 18]\n#   [ 2  8 14 20]\n#   [ 4 10 16 22]]\n# \n#  [[ 1  7 13 19]\n#   [ 3  9 15 21]\n#   [ 5 11 17 23]]]\n\nprint(np.reshape(a, [4, 6], order='F'))\n# [[ 0  4  8 12 16 20]\n#  [ 1  5  9 13 17 21]\n#  [ 2  6 10 14 18 22]\n#  [ 3  7 11 15 19 23]]\n\n# print(a.reshape([4, 6], 'F'))\n# TypeError: 'list' object cannot be interpreted as an integer\n\nprint(np.reshape(a, [4, 6], 'F'))\n# [[ 0  4  8 12 16 20]\n#  [ 1  5  9 13 17 21]\n#  [ 2  6 10 14 18 22]\n#  [ 3  7 11 15 19 23]]\n\nprint(a.reshape([4, -1]))\n# [[ 0  1  2  3  4  5]\n#  [ 6  7  8  9 10 11]\n#  [12 13 14 15 16 17]\n#  [18 19 20 21 22 23]]\n\nprint(a.reshape([2, -1, 4]))\n# [[[ 0  1  2  3]\n#   [ 4  5  6  7]\n#   [ 8  9 10 11]]\n# \n#  [[12 13 14 15]\n#   [16 17 18 19]\n#   [20 21 22 23]]]\n\n# print(a.reshape([2, -1, -1]))\n# ValueError: can only specify one unknown dimension\n\n# print(a.reshape([2, -1, 5]))\n# ValueError: cannot reshape array of size 24 into shape (2,newaxis,5)\n\na = np.arange(8)\nprint(a)\n# [0 1 2 3 4 5 6 7]\n\na_2_4 = a.reshape([2, 4])\nprint(a_2_4)\n# [[0 1 2 3]\n#  [4 5 6 7]]\n\nprint(np.shares_memory(a, a_2_4))\n# True\n\na[0] = 100\nprint(a)\n# [100   1   2   3   4   5   6   7]\n\nprint(a_2_4)\n# [[100   1   2   3]\n#  [  4   5   6   7]]\n\na_2_4[0, 0] = 0\nprint(a_2_4)\n# [[0 1 2 3]\n#  [4 5 6 7]]\n\nprint(a)\n# [0 1 2 3 4 5 6 7]\n\na_2_4_copy = a.reshape([2, 4]).copy()\nprint(a_2_4_copy)\n# [[0 1 2 3]\n#  [4 5 6 7]]\n\nprint(np.shares_memory(a, a_2_4_copy))\n# False\n\na[0] = 100\nprint(a)\n# [100   1   2   3   4   5   6   7]\n\nprint(a_2_4_copy)\n# [[0 1 2 3]\n#  [4 5 6 7]]\n\na_2_4_copy[0, 0] = 200\nprint(a_2_4_copy)\n# [[200   1   2   3]\n#  [  4   5   6   7]]\n\nprint(a)\n# [100   1   2   3   4   5   6   7]\n\na = np.arange(6).reshape(2, 3)\nprint(a)\n# [[0 1 2]\n#  [3 4 5]]\n\na_step = a[:, ::2]\nprint(a_step)\n# [[0 2]\n#  [3 5]]\n\nprint(a_step.reshape(-1))\n# [0 2 3 5]\n\nprint(np.shares_memory(a_step, a_step.reshape(-1)))\n# False\n\nnp.info(a)\n# class:  ndarray\n# shape:  (2, 3)\n# strides:  (24, 8)\n# itemsize:  8\n# aligned:  True\n# contiguous:  True\n# fortran:  False\n# data pointer: 0x7fb49bf71950\n# byteorder:  little\n# byteswap:  False\n# type: int64\n\nnp.info(a_step)\n# class:  ndarray\n# shape:  (2, 2)\n# strides:  (24, 16)\n# itemsize:  8\n# aligned:  True\n# contiguous:  False\n# fortran:  False\n# data pointer: 0x7fb49bf71950\n# byteorder:  little\n# byteswap:  False\n# type: int64\n\nnp.info(a_step.reshape(-1))\n# class:  ndarray\n# shape:  (4,)\n# strides:  (8,)\n# itemsize:  8\n# aligned:  True\n# contiguous:  True\n# fortran:  True\n# data pointer: 0x7fb49e162210\n# byteorder:  little\n# byteswap:  False\n# type: int64\n\na = np.arange(8).reshape(2, 4)\nprint(a)\n# [[0 1 2 3]\n#  [4 5 6 7]]\n\na_step = a[:, ::2]\nprint(a_step)\n# [[0 2]\n#  [4 6]]\n\nprint(a_step.reshape(-1))\n# [0 2 4 6]\n\nprint(np.shares_memory(a_step, a_step.reshape(-1)))\n# True\n\nnp.info(a)\n# class:  ndarray\n# shape:  (2, 4)\n# strides:  (32, 8)\n# itemsize:  8\n# aligned:  True\n# contiguous:  True\n# fortran:  False\n# data pointer: 0x7fb49e0e1c40\n# byteorder:  little\n# byteswap:  False\n# type: int64\n\nnp.info(a_step)\n# class:  ndarray\n# shape:  (2, 2)\n# strides:  (32, 16)\n# itemsize:  8\n# aligned:  True\n# contiguous:  False\n# fortran:  False\n# data pointer: 0x7fb49e0e1c40\n# byteorder:  little\n# byteswap:  False\n# type: int64\n\nnp.info(a_step.reshape(-1))\n# class:  ndarray\n# shape:  (4,)\n# strides:  (16,)\n# itemsize:  8\n# aligned:  True\n# contiguous:  False\n# fortran:  False\n# data pointer: 0x7fb49e0e1c40\n# byteorder:  little\n# byteswap:  False\n# type: int64\n", "meta": {"hexsha": "cabd0ef9c18b55894f3df62603f91de2f905c778", "size": 5408, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebook/numpy_reshape.py", "max_stars_repo_name": "vhn0912/python-snippets", "max_stars_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 174, "max_stars_repo_stars_event_min_datetime": "2018-05-30T21:14:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:59:37.000Z", "max_issues_repo_path": "notebook/numpy_reshape.py", "max_issues_repo_name": "vhn0912/python-snippets", "max_issues_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-08-10T03:22:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-12T20:31:17.000Z", "max_forks_repo_path": "notebook/numpy_reshape.py", "max_forks_repo_name": "vhn0912/python-snippets", "max_forks_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53, "max_forks_repo_forks_event_min_datetime": "2018-04-27T05:26:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T07:59:37.000Z", "avg_line_length": 17.0599369085, "max_line_length": 75, "alphanum_fraction": 0.5371671598, "include": true, "reason": "import numpy", "num_tokens": 2799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.9525741232882134, "lm_q1q2_score": 0.8591462977206389}}
{"text": "import scipy.optimize\n\ndef newton(f, fp, x0, delta=1e-4):\n\tcnt = 0\n\tx = x0\n\tprint('x0 = %.10lf' % x0)\n\twhile abs(f(x)) > delta or abs(x - x0) > delta:\n\t\ts = f(x) / fp(x)\n\t\tx0, x = x, x - s\n\t\tlbd = 1\n\t\twhile abs(f(x)) >= abs(f(x0)):\n\t\t\tx = x0 - lbd * s\n\t\t\tlbd /= 2\n\t\tcnt += 1\n\t\tprint('x%d = %.10lf, lambda = %.10lf' % (cnt, x, lbd))\n\treturn x\n\ndef gen22():\n\tdef func1(x):\n\t\treturn x**3 - x - 1\n\tdef func1p(x):\n\t\treturn 3*x*x - 1\n\tdef func2(x):\n\t\treturn -x**3 + 5 * x\n\tdef func2p(x):\n\t\treturn -3*x*x + 5\n\t\n\tprint('t22 result'.center(30, '-'))\n\tx = newton(func1, func1p, 0.6)\n\tprint('final result: x = %.10lf, f(x) = %.10lf' % (x, func1(x)))\n\tprint('scipy gives: %.10lf' % (scipy.optimize.fsolve(func1, 0.6)))\n\tx = newton(func2, func2p, 1.35)\n\tprint('final result: x = %.10lf, f(x) = %.10lf' % (x, func2(x)))\n\tprint('scipy gives: %.10lf' % (scipy.optimize.fsolve(func2, 1.35)))\n\tprint('end t22'.center(30, '-')+'\\n')\n\nif __name__ == '__main__':\n\tgen22()\n", "meta": {"hexsha": "ff754f74d979ed69c01b54b002003b4f7d1308a8", "size": 951, "ext": "py", "lang": "Python", "max_stars_repo_path": "数值分析/t22.py", "max_stars_repo_name": "jasnzhuang/Personal-Homework", "max_stars_repo_head_hexsha": "edf633ce94f22a646786b85e133797339cf9fc3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 463, "max_stars_repo_stars_event_min_datetime": "2019-10-25T04:28:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:03:44.000Z", "max_issues_repo_path": "数值分析/t22.py", "max_issues_repo_name": "1002753959/Undergraduate", "max_issues_repo_head_hexsha": "95e6e95a98f53e350d628edacad0042382c6a464", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-28T08:05:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-28T08:26:34.000Z", "max_forks_repo_path": "数值分析/t22.py", "max_forks_repo_name": "1002753959/Undergraduate", "max_forks_repo_head_hexsha": "95e6e95a98f53e350d628edacad0042382c6a464", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 201, "max_forks_repo_forks_event_min_datetime": "2019-04-10T07:17:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-15T09:46:30.000Z", "avg_line_length": 24.3846153846, "max_line_length": 68, "alphanum_fraction": 0.5488958991, "include": true, "reason": "import scipy", "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741322079104, "lm_q2_score": 0.9019206673024666, "lm_q1q2_score": 0.8591462969760266}}
{"text": "###____________________ Interpolation & Curve Fitting ______________________###\n\n# Based on: pybonacci.org/2013/08/15/ajuste-e-interpolacion-unidimensionales-basicos-en-python-con-scipy/\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n# plt.ion()\n\n###____________________________ Interpolation  _____________________________###\n#_______________________ Airplane Polar Data _______________________#\n# Supongamos que tenemos una serie de puntos que representan los datos de un \n# cierto experimento. Como ejemplo, vamos a cargar los datos de la polar de un \n# avión que están en el archivo polar.dat.\n\ndatos = np.loadtxt(\"../data/polar.dat\")\nC_L = datos[0]\nC_D = datos[1]\n\n# Representamos los datos # (pista: usar `mew=2`, \"marker edge width 2\", para que las cruces se vean mejor):\nplt.plot(C_D, C_L, '^', mew=2, label=\"Datos reales\")\nplt.xlabel(\"$C_D$\")\nplt.ylabel(\"$C_L$\")\nplt.legend()\nplt.show()\n\n# Identify the stall region # Hallando el índice del máximo valor de 𝐶𝐿 podemos descartar los datos fuera de la región de entrada en pérdida, y para eso necesitamos la función np.argmax\n    # tip: argmax function: finds index of max value of a set of data\nidx_stall = np.argmax(C_L)\n# Identify the C_L_MAX\nprint((C_L[idx_stall]))\n\n# Representamos los datos dentro y fuera del modelo\nplt.plot(C_D[:idx_stall + 1], C_L[:idx_stall + 1], '^', mew=2, label=\"Datos reales\")\nplt.plot(C_D[idx_stall + 1:], C_L[idx_stall + 1:], 'x', mfc='none', label=\"Fuera del modelo\")\nplt.xlabel(\"$C_D$\")\nplt.ylabel(\"$C_L$\")\nplt.legend(loc=4)\nplt.show()\n\n# Hay dos cosas que nos pueden interesar:\n    # Como solo tenemos puntos intermedios, no tenemos posibilidad de evaluar, \n    # por ejemplo, CL para un CD que no esté en los datos. Si interpolamos la \n    # curva ya podemos hacerlo. Sabemos que, fuera de la región de entrada en \n    # pérdida, la polar tiene forma parabólica. Si ajustamos la curva podemos hallar \n    # el CD0 y el k\n\n### Interpolation ###\nfrom scipy import interpolate\n# ## easy example with sin(x) ##\nx_i = [0.0, 0.9, 1.8, 2.7, 3.6, 4.4, 5.3, 6.2, 7.1, 8.0]\ny_i = [0.0, 0.8, 1.0, 0.5, -0.4, -1.0, -0.8, -0.1, 0.7, 1.0]\nplt.plot(x_i, y_i, 'd', mew=2)\nplt.show()\n\n# # Para crear una función interpolante utilizaremos el objeto InterpolatedUnivariateSpline \n# # del paquete interpolate. A este objeto solo hay que pasarle los puntos de \n# # interpolación y el grado, y generará un spline.\nf_interp = interpolate.InterpolatedUnivariateSpline(x_i, y_i, k=2)\n# # ¿Cómo obtengo los puntos desde aquí? El resultado que hemos obtenido es una \n# # función y admite como argumento la x.\nprint(f_interp(np.pi / 2))\n\nx = np.linspace(0, 8)\ny_interp = f_interp(x)\n\nplt.plot(x_i, y_i, 'x', mew=2)\nplt.plot(x, y_interp)\nplt.show()\n\n## Exercise: Crear una función interpolante 𝐶𝐷=𝑓(𝐶𝐿) usando splines de grado 2 \n# y representarla. Utiliza solo los datos que resultan de haber eliminado la región \n# de entrada en pérdida. y ten en cuenta que la 𝑥 y la 𝑦 para este caso están \n# cambiadas de sitio. ##\n# 1. Crea un polinomio interpolante usando los valores que encajan en el modelo parabólico.\n# 2. Crea un dominio de CL entre C_L.min() y C_L.max().\n# 3. Halla los valores interpolados de CD en ese dominio.\n# 4. Representa la función y los puntos.\nf_C_D = interpolate.InterpolatedUnivariateSpline(C_L[:idx_stall + 1], C_D[:idx_stall + 1], k=2) # I put CL first because if im taking a parabolic I am acc seeing the graph rotated 90 deg\nC_L_domain = np.linspace(C_L.min(), C_L.max())\nC_D_domain = f_C_D(C_L_domain)\n\nwith plt.style.context('seaborn-notebook'):\n    plt.title('Interpolated Polar Data', fontsize = 25)\n    plt.plot(C_D[:idx_stall + 1], C_L[:idx_stall + 1], '^', mew=2, label=\"Datos reales\")\n    # plt.plot(C_D[idx_stall + 1:], C_L[idx_stall + 1:], 'x', mfc='none', label=\"Fuera del modelo\")\n    plt.plot(C_D_domain, C_L_domain, label=\"Interpolated data\", color=\"purple\")\n    plt.xlabel(\"$C_D$\")\n    plt.ylabel(\"$C_L$\")\n    plt.legend(loc=4)\n    plt.grid()\n    plt.show()\n\n#_______________________ Runge Phenomenon _______________________#\ndef runge(x):\n    return 1 / (1 + x ** 2)\n\n# Número de nodos\nN = 11  # Nodos de interpolación\n\n# Seleccionamos los nodos\nxp = np.linspace(-5, 5, N)   # -5, -4, -3, ..., 3, 4, 5\nfp = runge(xp)\n\n# Seleccionamos la x para interpolar\nx = np.linspace(-5, 5, 200)\n# Calculamos el pol interp de Lagrange\nlag_pol = interpolate.lagrange(xp, fp)\ny = lag_pol(x)\n\nwith plt.style.context('seaborn-notebook'):\n    plt.plot(x, y, label='interpolation')\n    plt.plot(xp, fp, 'o', label='samples')\n    plt.plot(x, runge(x), label='real')\n    plt.legend(loc='upper center')\n    plt.show()\n\n# importamos el polinomio de chebychev #\nfrom numpy.polynomial import chebyshev\nN = 11  # Nodos de interpolación\n\ncoeffs_cheb = [0] * N + [1]  # Solo queremos el elemento 11 de la serie\n\nT11 = chebyshev.Chebyshev(coeffs_cheb, [-5, 5])\nxp_ch = T11.roots()\n\nfp = runge(xp_ch)\n\nx = np.linspace(-5, 5, 200)\n\nlag_pol = interpolate.lagrange(xp_ch, fp)\n# lag_pol = interpolate.InterpolatedUnivariateSpline(xp_ch, fp, k=2) # Just to check\n\ny = lag_pol(x)\nwith plt.style.context('seaborn-notebook'):\n    plt.plot(x, y, label='interpolation')\n    plt.plot(xp_ch, fp, 'o', label='samples')\n    plt.plot(x, runge(x), label='real')\n    plt.legend()\n    plt.show()\n    \n###_______________________________ Fitting _________________________________###\n # El ajuste funciona de manera totalmente distinta: obtendremos una curva que no\n # tiene por qué pasar por ninguno de los puntos originales, pero que a cambio \n # tendrá una expresión analítica simple.\nfrom scipy.optimize import curve_fit\n# # ## easy example with random quadratic function ##\n#  # Vamos otra vez a generar unos datos para ver cómo funcionaría, del tipo:\n#  # $$y(x) = x^2 - x + 1 + \\text{Ruido}$$\nx_i = np.linspace(-2, 3, num=10)\ny_i = x_i ** 2 - x_i + 1 + 0.5 * np.random.randn(10) # np.random.randn(10) Creates an array with 10 components that are random numbers\nplt.plot(x_i, y_i, 'x', mew=2)\nplt.show()\n\n#  # Vamos a utilizar la función polynomial.polyfit, que recibe los puntos de \n#  # interpolación y el grado del polinomio. El resultado serán los coeficientes \n#  # del mismo, en orden de potencias crecientes.\ndef poldeg2(x, a, b, c):\n    return a * x**2 + b * x + c\n\nval, cov = curve_fit(poldeg2, x_i, y_i)\na, b, c = val\n\nx = np.linspace(-2, 3)\n\ny_fit = poldeg2(x, a, b, c)\n\nwith plt.style.context('seaborn-notebook'):\n    l, = plt.plot(x, y_fit)\n    plt.plot(x_i, y_i, 'x', mew=2, c=l.get_color())\n    plt.grid()\n    plt.show()\n\n## Exercise: Si modelizamos la polar como: CD=CD0+k*CL**2, \n# hallar los coeficientes CD0 y k ##\ndef model(x, A, C):\n    return A*x**2 + C\n\npopt, lqdata = curve_fit(model, C_L[:idx_stall+1], C_D[:idx_stall+1])\nA, B = popt\n# To compute one standard deviation errors on the parameters use:\nperr = np.sqrt(np.diag(lqdata))\n\nx = np.linspace(-1.5, 1.5, 50)\ny = model(x, A, B)\n\nwith plt.style.context('seaborn-notebook'):\n    plt.plot(y, x)\n    plt.plot(C_D[:idx_stall + 1], C_L[:idx_stall + 1], 'x', mew=2, label=\"Datos reales\")\n    plt.plot(C_D[idx_stall + 1:], C_L[idx_stall + 1:], 'o', mfc='none', label=\"Fuera del modelo\")\n    plt.xlabel(\"$C_D$\")\n    plt.ylabel(\"$C_L$\")\n    plt.legend(loc=4)\n    plt.grid()  \n    plt.show()\n\n", "meta": {"hexsha": "9eef68645f69d44b68ee753e1fbaf3e825695012", "size": 7231, "ext": "py", "lang": "Python", "max_stars_repo_path": "MyScripts/033-SciPy.py", "max_stars_repo_name": "diegoomataix/Curso_AeroPython", "max_stars_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MyScripts/033-SciPy.py", "max_issues_repo_name": "diegoomataix/Curso_AeroPython", "max_issues_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MyScripts/033-SciPy.py", "max_forks_repo_name": "diegoomataix/Curso_AeroPython", "max_forks_repo_head_hexsha": "c2cf71a938062bc70dbbf7c2f21e09653fa2cedd", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8928571429, "max_line_length": 186, "alphanum_fraction": 0.6925736413, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 2311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.9046505395995927, "lm_q1q2_score": 0.8591189056618965}}
{"text": "'''\nk-Means python implementation\n'''\n\nimport pandas as pd\nimport numpy as np \nimport random as rd\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets \nfrom collections import defaultdict\nimport seaborn as sns\n\n\ndef euclidean_distance(center,point):\n    dist = np.linalg.norm(center-point)\n    return dist\n\n### K-Means Algorithm\n\ndef kmeans(data,k,iters) :\n    \n    ##Step 1: Choose number K of clusters \n    K = k\n    \n    ##Step 2: Select K random points from the data as centroids\n    \n    random_indices = np.random.choice(len(data), size=K, replace=False)\n    centroids = data[random_indices,:]\n    \n    ##Step 3: Assign all points to the closest cluster centroid  \n    \n    counter_1 = 0 #count number of iters where centroids don't change\n    iteration = 0\n    while True:\n        \n        # for every point calculate distance from every centroid\n        distances = defaultdict(dict)\n        \n        for i,center in enumerate(centroids):\n            for j,point in enumerate(data):\n                distances[j][i] = euclidean_distance(center,point)\n        \n        # assign every point to the closest centroid\n        points = {}\n        for i in range(len(data)):\n            points[i] = list({k: v for k, v in sorted(distances[i].items(), key=lambda item: item[1])}.keys())[0]\n        \n        # group points of every centroid  \n        cluster_points = {}\n        for i in range(K):\n             cluster_points[i] = list({k for (k,v) in points.items() if v==i})        \n        \n        ##Step 4: Recompute the centroids of newly transformed clusters as the mean of their points\n        centroids_cached = [tuple(c) for c in centroids]\n        centroids = []\n        for i in range(K):\n            centroids.append(np.array([data[i] for i in cluster_points[i]]).transpose().mean(axis=1))\n\n        ##Step 5: Repeat steps 3,4 until a stopping criterion is met (max iterations or centroids remain the same for 3 iterations)\n        \n        if ([tuple(c) for c in centroids] == centroids_cached and counter_1==3):\n            break\n            return centroids,cluster_points\n        elif ([tuple(c) for c in centroids] == centroids_cached and counter_1<3):\n            counter_1 +=1\n            \n        if iteration == iters:\n            break\n        else:\n            iteration += 1\n            \n    points = np.array([tup[1] for tup in points.items()]) #return cluster indices per point\n\n    return centroids, cluster_points, points\n\n        \n### Find K using Elbow Method\n\ndef inertia (centroids,cluster_points,data):\n    cost=0\n    for i,centroid in enumerate(centroids):\n        for point in cluster_points[i]:\n            cost += euclidean_distance(centroid,data[point])\n    return cost\n\ndef elbow_method(data,k):\n    \n    cost_list = []\n    for k in range(1, k+1):\n      \n        centroids, cluster_points,points = kmeans(data, k,iters = 20)\n        cost = inertia(centroids, cluster_points,data)\n        cost_list.append(cost)\n        \n    sns.lineplot(x=range(1,k+1), y=cost_list, marker='o')\n    plt.xlabel('k')\n    plt.ylabel('WCSS')\n    plt.show()\n  \nif __name__ == \"__main__\":\n    \n    X, y = datasets.make_blobs(n_samples=100, centers=3, n_features=3,random_state=0)\n    K=3\n    iters = 20\n    centroids, cluster_points,points = kmeans(X,K,iters)\n", "meta": {"hexsha": "62b5ab3eefc205d1fbbf54406fa3ee7ed069af07", "size": 3283, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python implementations/K-Means.py", "max_stars_repo_name": "Tasosk92/Machine-Learning", "max_stars_repo_head_hexsha": "d147c0744de02eb76b69585e5ce256b795b5ed10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python implementations/K-Means.py", "max_issues_repo_name": "Tasosk92/Machine-Learning", "max_issues_repo_head_hexsha": "d147c0744de02eb76b69585e5ce256b795b5ed10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python implementations/K-Means.py", "max_forks_repo_name": "Tasosk92/Machine-Learning", "max_forks_repo_head_hexsha": "d147c0744de02eb76b69585e5ce256b795b5ed10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9716981132, "max_line_length": 131, "alphanum_fraction": 0.6180322875, "include": true, "reason": "import numpy", "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535723, "lm_q2_score": 0.9046505402422644, "lm_q1q2_score": 0.8591189036949172}}
{"text": "# quadrature.py\n# -------------------------------------------------------------------------\n# Integrate two functions using quad.\n# ------------------------------------------------------------------------- \nimport numpy as np\nfrom scipy.integrate import quad\n\n#%% Integrate a built-in function.\nupper_limit = np.linspace(0,3*np.pi,16)\ncos_integral = np.zeros(upper_limit.size)\nfor i in range(upper_limit.size):\n    cos_integral[i], error = quad(np.cos, 0, upper_limit[i])\n\n#%% Now integrate a user-defined function.\ndef integrand(x): return np.exp(-x**2/2)\n\nupper_limit = np.linspace(0, 5, 51)\ngauss_integral = np.zeros(upper_limit.size)\nfor i in range(upper_limit.size):\n    gauss_integral[i], error = quad(integrand, 0, upper_limit[i])\n", "meta": {"hexsha": "c6e9a71f9a7a9d79269a637f8a10f6da1aeee521", "size": 738, "ext": "py", "lang": "Python", "max_stars_repo_path": "quadrature.py", "max_stars_repo_name": "jmkinder1/code-samples", "max_stars_repo_head_hexsha": "9c6cd3c6f16579a6c1f5210779b8ec6ad53fbdba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-07-17T05:19:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T05:39:50.000Z", "max_issues_repo_path": "quadrature.py", "max_issues_repo_name": "jmkinder1/code-samples", "max_issues_repo_head_hexsha": "9c6cd3c6f16579a6c1f5210779b8ec6ad53fbdba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quadrature.py", "max_forks_repo_name": "jmkinder1/code-samples", "max_forks_repo_head_hexsha": "9c6cd3c6f16579a6c1f5210779b8ec6ad53fbdba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-12-26T23:41:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T22:18:41.000Z", "avg_line_length": 35.1428571429, "max_line_length": 76, "alphanum_fraction": 0.5840108401, "include": true, "reason": "import numpy,from scipy", "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780477, "lm_q2_score": 0.9046505261034853, "lm_q1q2_score": 0.8591188915564042}}
{"text": "# Question 5 Lab Assignment 2\n# AB Satyaprakash - 180123062\n\n# imports ----------------------------------------------------------------------\nfrom math import erf, pow\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# functions --------------------------------------------------------------------\n\n\ndef f(x):\n    return erf(x)\n\n\ndef monomialBasis(X, F):\n    xArrayNN = []\n    for x in X:\n        row = []\n        for i in range(X.shape[0]):\n            row.append(pow(x, i))\n        xArrayNN.append(row)\n    xArrayNN = np.array(xArrayNN)\n    A = np.linalg.solve(xArrayNN, F)\n    A = np.flip(A)\n    return A\n\n\ndef lagrangeBasis(X, F):\n    L = []  # to store a list of all li(x) polynomials\n    for x in X:\n        l = np.array([1])\n        for i in range(X.shape[0]):\n            if(X[i] != x):\n                l = np.polymul(l, np.array([1, -X[i]]))\n                const = x-X[i]\n                l = l/const\n        L.append(l)\n    A = L[0]*F[0]\n    for i in range(1, len(L)):\n        A += L[i]*F[i]\n    return A\n\n\ndef newtonBasis(X, F):\n    N = []  # to store a list of all Nj(x) polynomials\n    temp = np.array([1])\n    for i in range(X.shape[0]):\n        N.append(temp)\n        temp = np.polymul(temp, np.array([1, -X[i]]))\n\n    xArrayNN = []\n    for j in range(X.shape[0]):\n        row = []\n        for i in range(X.shape[0]):\n            if(i > j):\n                row.append(0)\n            else:\n                row.append(np.polyval(N[i], X[j]))\n        xArrayNN.append(row)\n    xArrayNN = np.array(xArrayNN)\n    A = np.linalg.solve(xArrayNN, F)\n\n    newtonPoly = A[0]*N[0]\n    for i in range(1, A.shape[0]):\n        newtonPoly = np.polyadd(newtonPoly, A[i]*N[i])\n    return newtonPoly\n\n\n# ------------------------------------------------------------------------------\n# Prepare the inputs X and F. Here X = [x0,x1,...,xn] and F = [f0,f1,...,fn]\n# Given X = [1,1.2,1.4...,3] in question\nX = np.arange(1, 3.2, 0.2)\nF = np.zeros(X.shape[0])\nfor i in range(X.shape[0]):\n    F[i] = f(X[i])\n\n# Compute the interpolating polynomial P(f[x1, . . . , xn]) using:\n# (i) Monomial basis\npxMonomial = monomialBasis(X, F)\nprint('The interpolating polynomial using monomial basis is \\n{}\\n'.format(np.poly1d(pxMonomial)))\n\n# (ii) Lagrange basis\npxLagrange = lagrangeBasis(X, F)\nprint('The interpolating polynomial using lagrange basis is \\n{}\\n'.format(np.poly1d(pxLagrange)))\n\n# (iii) Newton basis\npxNewton = newtonBasis(X, F)\nprint('The interpolating polynomial using newton basis is \\n{}\\n'.format(np.poly1d(pxNewton)))\n\n# Plot the error for each of the 3 cases with z = (0 : 0.01 : 4) (here, 0.01 is step size)\nZ = np.arange(0, 4.01, 0.01)\nerrMonomial, errLagrange, errNewton = [], [], []\nfor z in Z:\n    errMonomial.append(abs(f(z)-np.polyval(pxMonomial, z)))\n    errLagrange.append(abs(f(z)-np.polyval(pxLagrange, z)))\n    errNewton.append(abs(f(z)-np.polyval(pxNewton, z)))\n\nplt.plot(Z, errMonomial, color='red')\nplt.title('Error between erf and the interpolating polynomial using Monomial Basis vs Z values')\nplt.xlabel('Z values - 0: 0.01 : 4')\nplt.ylabel('Error between erf and the interpolating polynomial')\nplt.show()\n\nplt.plot(Z, errLagrange, color='green')\nplt.title('Error between erf and the interpolating polynomial using Lagrange Basis vs Z values')\nplt.xlabel('Z values - 0: 0.01 : 4')\nplt.ylabel('Error between erf and the interpolating polynomial')\nplt.show()\n\nplt.plot(Z, errNewton, color='blue')\nplt.title('Error between erf and the interpolating polynomial using Newton Basis vs Z values')\nplt.xlabel('Z values - 0: 0.01 : 4')\nplt.ylabel('Error between erf and the interpolating polynomial')\nplt.show()\n\nprint(\n    'As we can see from the plots, the error value becomes very high as we move out of the range [1 3] - especially towards 4')\nprint(\n    'So it is not recommended to use polynomial interpolation to approximate erf at points outside [1 3]')\n\n# Error between Monomial and Newton bases\nerrMonoNewton = []\nZ = np.arange(1, 3.001, 0.001)\nfor z in Z:\n    errMonoNewton.append(abs(np.polyval(pxMonomial, z)-np.polyval(pxNewton, z)))\nplt.plot(Z, errMonoNewton)\nplt.title('Error of the interpolating polynomial between using Monomial and Newton Bases vs Z values')\nplt.xlabel('Z values - 1: 0.001 : 3')\nplt.ylabel('Error the interpolating polynomials')\nplt.show()\n\n# Error between Lagrange and Newton bases\nerrLangNewton = []\nZ = np.arange(1, 3.001, 0.001)\nfor z in Z:\n    errLangNewton.append(abs(np.polyval(pxLagrange, z)-np.polyval(pxNewton, z)))\nplt.plot(Z, errLangNewton)\nplt.title('Error of the interpolating polynomial between using Lagrange and Newton Bases vs Z values')\nplt.xlabel('Z values - 1: 0.001 : 3')\nplt.ylabel('Error the interpolating polynomials')\nplt.show()\n\n# Find the one with max errors\nZ = np.arange(1, 3.001, 0.001)\nerrMonomial, errLagrange, errNewton = [], [], []\nfor z in Z:\n    errMonomial.append(abs(f(z)-np.polyval(pxMonomial, z)))\n    errLagrange.append(abs(f(z)-np.polyval(pxLagrange, z)))\n    errNewton.append(abs(f(z)-np.polyval(pxNewton, z)))\n", "meta": {"hexsha": "3f6ad5289b806862f8131bcbd773754ed0e70eda", "size": 5004, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 2/Code/q5.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 2/Code/q5.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 2/Code/q5.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 33.1390728477, "max_line_length": 127, "alphanum_fraction": 0.6175059952, "include": true, "reason": "import numpy", "num_tokens": 1443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176863577751, "lm_q2_score": 0.9099070017626537, "lm_q1q2_score": 0.8591131390716975}}
{"text": "import numpy as np\n\ndef lower_triangular_solve(A,b0):\n    \"\"\"\n    Solve the system  A x = b  where A is assumed to be lower triangular,\n    i.e. A(i,j) = 0 for j > i, and the diagonal is assumed to be nonzero,\n    i.e. A(i,i) \\= 0.\n    \n    ARGUMENTS:  A   lower triangular n x n array\n                b0   right hand side column n-vector\n                \n    RETURNS:    x   column n-vector solution    \n    \"\"\"\n\n    #Check that A is lower triangular\n    if not np.allclose(A,np.tril(A)):\n        print \"Error: The input array is not lower triangular!\"\n        return None\n\n    #Get n-dimension\n    n = len(b0)\n    \n    #Copy vector b0 and convert to float\n    b = np.copy(b0).astype(float)\n\n    #Initialise x\n    x = np.zeros([n,1])\n    \n    #Loop through the remaining rows, calculating the solution components\n    #in turn by backward substitution\n    \n    for i in xrange(n):\n        for j in xrange(i):\n            b[i] = b[i] - A[i,j]*x[j]\n        x[i] = b[i] / A[i,i]\n\n    return x\n\n\ndef upper_triangular_solve(A,b0):\n    \"\"\"\n    Solve the system  A x = b  where A is assumed to be upper triangular,\n    i.e. A(i,j) = 0 for j < i, and the diagonal is assumed to be nonzero,\n    i.e. A(i,i) \\= 0.\n    \n    ARGUMENTS:  A   upper triangular n x n array\n                b0   right hand side column n-vector\n                \n    RETURNS:    x   column n-vector solution\n                count   number of operations in the inner loop\n    \"\"\"\n\n    #Check that A is upper triangular\n    if not np.allclose(A,np.triu(A)):\n        print \"Error: The input array is not upper triangular!\"\n        return None\n\n    #Get n-dimension\n    n = len(b0)\n    \n    #Copy vector b0 and covert to float\n    b = np.copy(b0).astype(float)\n\n    #Initialise x & count\n    x = np.zeros([n,1])\n    count = 0\n\n    #Loop through the remaining rows, calculating the solution components\n    #in turn by backward substitution\n    \n    for i in xrange(n-1,-1,-1):\n        for j in xrange(i+1,n):\n            b[i] = b[i] - A[i,j]*x[j]\n            count += 1\n        x[i] = b[i] / A[i,i]\n\n    return x,count\n\ndef gauss_elimination(A,b,**args):\n    \"\"\"\n    Reduce the system  A x = b  to upper triangular form, assuming that\n    the diagonal is nonzero, i.e. A(i,i) \\= 0.\n    \n    ARGUMENTS:  A   n x n matrix\n                b   right hand side column n-vector\n                \n                print  (optional) prints elimination steps\n    \n    RETURNS:    A   upper triangular n x n matrix\n                b   modified column n-vector\n                count   count the number of operations in the inner loop\n    \"\"\"\n    #Get dimensions\n    n = len(b)\n    \n    #Make sure entries are set to float\n    A = A.astype(float)\n    b = b.astype(float)\n\n    #Initalizing\n    count = 0\n\n    #Loop through the rows (i) of the system\n    for i in xrange(n-1):\n        #Print solution information\n        if 'print' in args:\n            print 'Eliminate column %d\\n' %i\n            raw_input('Press key to continue')\n\n        #Pick out the diagonal entry (and assume that it isn't zero\n        r = 1. / A[i,i]\n        \n        #Loop through the rows (j) of the system below row i\n        for j in xrange(i+1,n):\n            #Calculate the multiplier for that row for elimination\n            d = r * A[j,i]\n \n            #Loop through the elements of row j which have yet to be set to zero\n            for k in xrange(i,n):\n                #For column k, subtract the scaled element in row i from row j.\n                A[j,k] = A[j,k] - d*A[i,k]\n                count += 1\n\n            #Subtract scalded right hand side of row i from row j\n            b[j] = b[j] - d*b[i]\n        \n        if 'print' in args:\n            print A\n            print b\n        \n    return A,b,count\n\ndef gauss_elimination_pivot(A,b):\n    \"\"\"\n    Reduce the system  A x = b  to upper triangular form, making use of\n    row pivoting.\n    \n    ARGUMENTS:  A   n x n matrix\n                b   right hand side column n-vector\n    \n    RETURNS:    A   upper triangular n x n matrix\n                b   modified column n-vector    \n    \"\"\"\n    #Get dimensions\n    n = len(b)\n    \n    #Make sure entries are set to float\n    A = A.astype(float)\n    b = b.astype(float)\n\n    #Loop through the rows (i) of the system.\n    for i in range(n-1):\n        #Find the value and position of the largest entry in\n        #column i on or below the diagonal\n        amax = abs(A[i,i])\n        kmax = -1\n        for k in xrange(i+1,n):\n            bmax = abs(A[k,i])\n            if bmax > amax:\n                amax = bmax\n                kmax = k\n\n        #If an entry below the diagonal is larger than the one on the \n        #diagonal then swap the rows\n        if kmax > i:\n            temp = np.copy(A[i,:])\n            A[i,:] = A[kmax,:]\n            A[kmax,:] = temp[:]\n\n            tempb = np.copy(b[i])\n            b[i] = b[kmax]\n            b[kmax] = tempb;\n\n        #%% Now carry out the usual elimination process\n        A,b = gauss_elimination(A,b)\n    \n    return A,b\n\ndef gauss_elim_count(n):\n    \"\"\"\n    Solve a nxn example system A x = b by first using Gaussian Elimination\n    and solving the resulting upper triangular system, but return the number\n    of operations executed by Elimination and the backward substitution.\n\n    ARGUMENTS:  n   dimension of system\n\n    RETURNS:    count1 operations in forward elimination (GE)\n                count2 operations in the backward substitution\n    \"\"\"\n\n    #Create a matrix of size nxn\n    A = np.random.rand(n,n)\n    #Create a column vector of size n\n    b0 = np.random.rand(n,1)\n\n    A, b0, count1 = gauss_elimination(A, b0)\n    x, count2 = upper_triangular_solve(A, b0)\n\n    return count1, count2\n\ndef test_gauss_elim_count():\n    \"\"\"\n    Prints a table that displays the amount of operations, count1 & count2,\n    (and other related measurements) returned by gauss_elim_count. This is\n    done for n = [2,4,8,16,32,64,128,256,512,1024].\n    \"\"\"\n\n    n_list = [2,4,8,16,32,64,128,256,512,1024]\n    # Non-existent values for n < 2 hence set initially to infinity\n    # so that the ratios would equal 0 (but don't have any meaning)\n    prev_count1 = float(\"inf\")\n    prev_count2 = float(\"inf\")\n\n    #Prints the header of the table\n    print \"{:^10} {:^10} {:^15} {:^10} {:^15}\" \\\n        .format(\"n\", \"Forward Elim\", \"Ratio\", \"Backward Subs\", \"Ratio\")\n\n\n    for n in n_list:\n        count1, count2 = gauss_elim_count(n)\n\n        ratio1 = float(count1)/prev_count1\n        ratio2 = float(count2)/prev_count2\n\n        #Prints the entries of the table\n        print \"{:5} {:11} {:15f} {:13} {:15f}\"\\\n            .format(n, count1, ratio1, count2, ratio2)\n\n        prev_count1 = count1\n        prev_count2 = count2\n\n\n\n\ntest_gauss_elim_count()\n\ndef lu_factorise(A):\n    \"\"\"\n    LU factorise the matrix A into a lower triangular matrix L and an\n    upper triangular matrix U.\n\n    ARGUMENTS:  A   n x n matrix\n\n    RETURNS:    L   lower triangular matrix\n                U   upper triangular matrix\n    \"\"\"\n\n    #Get matrix dimension\n    n = len(A)\n\n    #Make sure A entries are float\n    A = A.astype(float)\n\n    #Initialise L to be the n x n identity matrix I and U to be the \n    #n x n zero matrix\n    L = np.eye(n,dtype=float)\n    U = np.zeros([n,n],dtype=float)\n    \n    #Loop through the column of the matrix\n    for j in xrange(n-1):\n        #Compute the elements of U on and above the diagonal in column j\n        #using previously computed elements of L and U.\n        U[0,j] = A[0,j]\n        for i in xrange(1,j+1):\n            U[i,j] = A[i,j] - np.dot(L[i,:i],U[:i,j])\n            \n        #Compute the elements of L below the diagonal in column j using\n        #previously computed elements of L and U\n        r = 1. / U[j,j]\n\n        for i in xrange(j+1,n):\n            L[i,j] = r*( A[i,j] - np.dot(L[i,:j],U[:j,j]))\n\n    \n    #For column n there are no entries of L to be computed s only compute\n    #the % elemens of U on and above the diagonal in column n, again using\n    #previously computed elements of L and U       \n    U[0,-1] = A[0,-1]\n    for i in xrange(1,n):\n        U[i,-1] = A[i,-1] - np.dot(L[i,:i],U[:i,-1])\n    \n    return L,U\n\ndef gauss_seidel(A,u,b,n_iterations):\n    \"\"\"\n    Solve the system A u = b using a Gauss-Seidel iteration\n\n    ARGUMENTS:  A   k x k matrix\n                u   k-vector storing initial estimate\n                b   k-vector storing right-hand side\n                n_iterations\n                    integer number of iterations to carry out\n   \n    RESULTS:    u   k-vector storing solution    \n    \"\"\"\n\n    #Get dimension\n    k = len(A)\n\n    #Make sure matrix A is float\n    A = A.astype(float)\n\n    for i in xrange(n_iterations):\n        for j in xrange(k):\n            u[j] = u[j] + (b[j] - np.dot(A[j,:],u))/A[j,j]\n        print u\n    \n    return u\n\ndef jacobi(A,u,b,n_iterations):\n    \"\"\"\n    Solve the system A u = b using a Jacobi iteration\n    \n    ARGUMENTS:  A   k x k matrix\n                u   k-vector storing initial estimate\n                b   k-vector storing right-hand side\n                n_iterations\n                    integer number of iterations to carry out\n    \n    RESULTS:    u   k-vector storing solution\n    \"\"\"\n\n    #Get dimension\n    k = len(A)\n\n    #Make sure matrix A is float\n    A = A.astype(float)   \n\n    r = np.zeros([k,1])\n    for i in xrange(n_iterations):\n        r = (b - np.dot(A,u))\n        for j in xrange(k):\n            r[j] = r[j] / A[j,j]\n        \n        u = u + r\n    \n    return u\n\ndef jacobi2(A,u,b,n_iterations):\n    \"\"\"\n    Solve the system A u = b using a Jacobi iteration\n    \n    ARGUMENTS:  A   k x k matrix\n                u   k-vector storing initial estimate\n                b   k-vector storing right-hand side\n                n_iterations\n                    integer number of iterations to carry out\n    \n    RESULTS:    u   k-vector storing solution\n    \"\"\"\n\n    #Get dimension\n    k = len(A)\n\n    #Make sure matrix A is float\n    A = A.astype(float)   \n\n    unew = np.zeros([k,1])\n    for i in xrange(n_iterations):\n         for j in xrange(k):\n            unew[j] = u[j] + (b[j] - np.dot(A[j,:],u)) / A[j,j]\n    \n         u = np.copy(unew)\n    \n    return u\n\ndef gauss_seidel_new(A,u,b,tol):\n    \"\"\"\n    Solve the system A u = b using a Gauss-Seidel iteration\n    \n    ARGUMENTS:  A   k x k matrix\n                u   k-vector storing initial estimate\n                b   k-vector storing right-hand side\n                tol real number providing the required convergence tolerance\n    \n    RESULTS:    u   k-vector storing solution\n    \"\"\"\n\n    #Get dimension\n    k = len(A)\n\n    #Make sure matrix A is float\n    A = A.astype(float)      \n\n    #Set the maximum number of iterations\n    maxit = 1000\n\n    #Initialise the iteration counter\n    it = 0\n\n    #Initialise diffRMS to exceed tol for the first iteration\n    diffRMS = 2*tol\n\n    while ((diffRMS > tol) and (it < maxit)):\n        uold = u\n        for j in xrange(k):\n            u[j] = u[j] + (b[j] - np.dot(A[j,:],u))/A[j,j]\n        \n        diffRMS = 0\n        for j in xrange(k):\n            diffRMS = diffRMS + (u[j] - uold[j])**2\n            \n        it += 1\n        diffRMS = np.sqrt(diffRMS)\n\n    if (difffRMS) > tol:\n        print 'Warning! Iteration has not converged'\n\n    \n    return u\n\ndef jacobi_new(A,u,b,tol):\n    \"\"\"\n    Solve the system A u = b using a Jacobi iteration\n    \n    ARGUMENTS:  A   k x k matrix\n                u   k-vector storing initial estimate\n                b   k-vector storing right-hand side\n                tol real number providing the required convergence tolerance\n    \n    RESULTS:    u   k-vector storing solution\n    \"\"\"\n    #Get dimension\n    k = len(A)\n\n    #Make sure matrix A is float\n    A = A.astype(float)      \n\n    #Set the maximum number of iterations\n    maxit = 1000\n\n    #Initialise the iteration counter\n    it = 0\n\n    #Initialise diffRMS to exceed tol for the first iteration\n    diffRMS = 2*tol\n\n    unew = np.zeros([k,1])\n    while ((diffRMS > tol) and (it < maxit)):\n        for j in xrange(k):\n            unew[j] = u[j] + (b[j] - np.dot(A[j,:],u)) / A[j,j]\n            \n        diffRMS = 0\n        for j in xrange(k):\n            diffRMS = diffRMS + (unew[j] - u[j])**2\n            \n        it += 1\n        diffRMS = np.sqrt(diffRMS)\n        print it,diffRMS\n        u = np.copy(unew)\n\n    if (diffRMS) > tol:\n        print 'Warning! Iteration has not converged'  \n        \n    return u\n", "meta": {"hexsha": "8e9c5332253967afa93e4dbdacca663c1e93279c", "size": 12418, "ext": "py", "lang": "Python", "max_stars_repo_path": "year2/python/comp2941_(heat_and_matrix_equations)/matrixsolve.py", "max_stars_repo_name": "OthmanEmpire/university", "max_stars_repo_head_hexsha": "3405e1463e82ca2e6f7deef05c3b1ba0ab9c1278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-05-21T17:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-21T17:23:50.000Z", "max_issues_repo_path": "year2/python/comp2941_(heat_and_matrix_equations)/matrixsolve.py", "max_issues_repo_name": "OthmanEmpire/university_code", "max_issues_repo_head_hexsha": "3405e1463e82ca2e6f7deef05c3b1ba0ab9c1278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "year2/python/comp2941_(heat_and_matrix_equations)/matrixsolve.py", "max_forks_repo_name": "OthmanEmpire/university_code", "max_forks_repo_head_hexsha": "3405e1463e82ca2e6f7deef05c3b1ba0ab9c1278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2324561404, "max_line_length": 80, "alphanum_fraction": 0.5511354485, "include": true, "reason": "import numpy", "num_tokens": 3358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653855, "lm_q2_score": 0.9099070029841949, "lm_q1q2_score": 0.8591131359372342}}
{"text": "import numpy as np\r\n\r\na=np.array([[1,2,3,4],[5,6,7,8]])\r\nprint(a)\r\n# Get dimensions\r\nprint(a.ndim)\r\n#Get shape\r\nprint(a.shape)\r\nb= np.array([3,4,5,6],dtype='int16')\r\nprint(a*b)\r\n\r\nprint(b.ndim)\r\nprint(b.dtype)\r\n\r\nprint(b.itemsize)\r\nprint(b.nbytes)\r\n\r\n\r\n\r\na=np.array([[1,2,3,4,5,6,7],[8,9,10,11,12,13,14]])\r\nprint(a)\r\nprint(a.shape)\r\n\r\nprint(a[0,5])\r\nprint(a[0,:])\r\nprint(a[:,3])\r\nprint(a[0,1:7:2])\r\na[1,:]=22\r\nprint(a)\r\n\r\n\r\n\r\nb= np.array([[[1,2],[3,4]],[[5,6],[7,8]]])\r\nprint(b)\r\nprint(b[0,1,1])\r\nprint(b[:,1,:])\r\n\r\n\r\n\r\n# Initialize all zero matrix\r\n\r\na=np.zeros((2,3))\r\nprint(a)\r\n\r\nb=np.ones((2,2))\r\nprint(b)\r\n\r\n# initalize with any random value\r\n\r\nb=np.full((2,2),98,dtype='float32')\r\nprint(b)\r\n#full_like method\r\nb=np.full_like(b,4)\r\nprint(b)\r\n\r\n\r\n\r\n# initialize random decimal numbers\r\nb=np.random.rand(4,2)\r\nprint(b)\r\n\r\nb= np.random.random_sample(b.shape)\r\nprint(b)\r\n\r\n\r\nb=np.random.randint(-2,20,size=(3,3))\r\nprint(b)\r\n\r\n\r\n# identity matrix\r\n\r\nb=np.identity(5)\r\nprint(b)\r\n\r\n#Repeat an array\r\n\r\na=np.array([1,2,3])\r\na=np.repeat(a,3)\r\nprint(a)\r\n\r\n\r\n\r\na=np.array([[1,2,3],[4,5,6]])\r\na=np.array([[1,2,3]])\r\na=np.repeat(a,4,axis=0)\r\nprint(a)\r\n\r\n\r\n# print\r\n# [[1. 1. 1. 1. 1.]\r\n# [1. 0. 0. 0. 1.]\r\n# [1. 0. 9. 0. 1.]\r\n# [1. 0. 0. 0. 1.]\r\n# [1. 1. 1. 1. 1.]]\r\n\r\na=np.ones((5,5))\r\nb=np.zeros((3,3))\r\nb[1,1]=9\r\na[1:4,1:4]=b\r\nprint(a)\r\n\r\n\r\n# Coping array \r\na=np.array([1,2,3])\r\n#b=a\r\nb=a.copy()\r\nb[0]=100\r\nprint(b)\r\nprint(a)\r\n\r\n#Mathematics\r\n\r\na=np.array([1,2,3,4])\r\na=a+2\r\na=a*2\r\n\r\na=np.sin(a)\r\nprint(a)\r\n\r\n# Linear algebra\r\n\r\na=np.ones((2,4))\r\nprint(a)\r\nb=np.full((4,2),2)\r\nprint(b)\r\n\r\nprint(np.matmul(a,b))\r\n\r\n# finding determinant\r\na=np.identity(3)\r\na=np.linalg.det(a)\r\nprint(a)\r\n\r\n\r\n#Statistic\r\n\r\na= np.array([[1,2,3],[4,5,6]])\r\na=np.max(a,axis=0)\r\n#a=np.min(a)\r\n\r\na=np.sum(a)\r\nprint(a)\r\n\r\n#Reorganizing arrays\r\n\r\na=np.array([1,2,3,4])\r\na=a.reshape((2,2))\r\nprint(a)\r\n\r\n\r\n#Vertical stack\r\nv1= np.array([1,2,3,4])\r\nv2=np.array([5,6,7,8])\r\na=np.vstack([v2,v1])\r\nprint(a)\r\n\r\n# horizontal stack\r\n\r\na=np.hstack([v1,v2])\r\nprint(a)\r\n\r\n\r\n\r\nimport os\r\n# Load data from file\r\n#os.chdir('C:\\\\USMAN FILES\\\\Data Science\\\\Numpy')\r\n\r\na=np.genfromtxt('data.txt', delimiter=\",\")\r\nprint(a)\r\nprint(a.astype('int32'))\r\n\r\n# Advance indexing & boolean masking\r\n\r\nprint(np.any(a<20,axis=0))\r\nprint(\"\\n\")\r\n\r\n\r\n\r\n\r\nprint(~((a>10) & (a<20) | (a==20)))\r\nprint(\"\\n\")\r\nprint((a>10) & (a<20) | (a==20))\r\n#print values greater check\r\nprint(a[a>20])\r\n# index a list in numpy\r\na=np.array([1,2,3,4,5,6,7,8,9])\r\nprint(a[[2,5,7]])\r\n\r\n\r\na=np.ones((6,5))\r\n\r\nb=np.array([[11,12],[16,17]])\r\n\r\na[2:4,0:2]=b\r\nprint(a)\r\nprint(\"\\n\")\r\n\r\n#c=np.identity(4)\r\n\r\nc=np.array([2,8,14,20])\r\n\r\na[[0,1,2,3],[1,2,3,4]]=c\r\n\r\n#a[0,1]=c[0]\r\n#a[1,2]=c[1]\r\n#a[2,3]=c[2]\r\n#a[3,4]=c[3]\r\n\r\nprint(a)\r\nprint(\"\\n\")\r\nd=np.array([4,5,24,25,29,30])\r\n#a[0,3]=d[0]\r\n#a[0,4]=d[1]\r\n#a[4,3]=d[2]\r\n#a[4,4]=d[3]\r\n#a[5,3]=d[4]\r\n#a[5,4]=d[5]\r\na[[0,0,4,4,5,5],[3,4,3,4,3,4]]=d\r\nprint(a)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "eb32a6f82bc9a80517942d0e4f7bb2e9391d8e97", "size": 2958, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/numpyyy.py", "max_stars_repo_name": "usmanhaider1995/Numpy", "max_stars_repo_head_hexsha": "af88f53c9d7c19d0c3af38d73606a6c42dba0f03", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/numpyyy.py", "max_issues_repo_name": "usmanhaider1995/Numpy", "max_issues_repo_head_hexsha": "af88f53c9d7c19d0c3af38d73606a6c42dba0f03", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/numpyyy.py", "max_forks_repo_name": "usmanhaider1995/Numpy", "max_forks_repo_head_hexsha": "af88f53c9d7c19d0c3af38d73606a6c42dba0f03", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.0734693878, "max_line_length": 51, "alphanum_fraction": 0.529749831, "include": true, "reason": "import numpy", "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460244, "lm_q2_score": 0.9184802518352773, "lm_q1q2_score": 0.859097301223153}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\ntask 1.4 Unit circles\n\n# ToDo: Implement it in three dimensions\n# L_p norm\n# https://www.youtube.com/watch?v=SXEYIGqXSxk\n# unit circle:\n# https://www.youtube.com/watch?v=qTbDQ9gkKJg\n\"\"\"\n\nimport pylab\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom auxiliar import *\n\n\n@save_figure(\"out/unityball.png\")\ndef unitball(p):\n    \"\"\"\n    \"\"\"\n\n    # x points created in the order of quadrants\n    q1 = np.linspace(1.0, 0.0, 1000)\n    q2 = np.linspace(0.0, -1.0, 1000)\n    q3 = q2[::-1]\n    q4 = q1[::-1]\n\n    plt.xlim(-1.5, 1.5)\n    plt.ylim(-1.5, 1.5)\n    plt.axhline(0, color='black')\n    plt.axvline(0, color='black')\n\n    # draw quadrants\n    y1 =  (1 - np.abs(q1) ** p) ** (1.0/p)\n    y2 =  (1 - np.abs(q2) ** p) ** (1.0/p)\n    y3 = -(1 - np.abs(q3) ** p) ** (1.0/p)\n    y4 = -(1 - np.abs(q4) ** p) ** (1.0/p)\n\n    x = np.concatenate(( q1, q2, q3, q4))\n    y = np.concatenate(( y1, y2, y3, y4))\n\n    plt.plot(x, y, label = \"p = \" + str(p))\n    plt.legend(loc='upper right')\n    # plt.savefig(\"out/unityball.png\", bbox_inches=\"tight\", pad_inches=0)\n    # plt.show()\n    # plt.close()\n    return plt\n\n\nunitball(0.5)\n\n\n# By picking any two vectors; i.e. (x1, y1) = (0, 1) and (x2, y2) = (1, 0). Then\n# by calculating there norms,  we will find that this will be equal to 1.\np = 0.5\nv1_x = 0\nv1_y = 1\nprint(\"Norm of v1: \", (np.abs(v1_x) ** p + np.abs(v1_y) ** p) ** (1.0/p))\nv2_x = 1\nv2_y = 0\nprint(\"Norm of v2: \", (np.abs(v2_x) ** p + np.abs(v2_y) ** p) ** (1.0/p))\n# But by calculating the norm of v1 + v2 = (0, 1) + (1, 0) = (1, 1); This will\n# be equal 4.\nv3_x = 1\nv3_y = 1\nprint(\"Norm of (v1 + v2): \", (np.abs(v3_x) ** p + np.abs(v3_y) ** p) ** (1.0/p))\n# This result is larger than the summation of norm(v1) and norm(v2) and does not\n# satisfy the property of norm for: norm(v1 + v2) <= norm(v1) + norm(v2).\n# As a conclusion, this is not really a norm.\n", "meta": {"hexsha": "df5436be0a12452c30865bd01579f7384844eda4", "size": 1888, "ext": "py", "lang": "Python", "max_stars_repo_path": "01/task14.py", "max_stars_repo_name": "omartrinidad/pattern-recognition-bit", "max_stars_repo_head_hexsha": "ba3eb4e541fff2b1aedbaa4420d7a8cea8100dc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "01/task14.py", "max_issues_repo_name": "omartrinidad/pattern-recognition-bit", "max_issues_repo_head_hexsha": "ba3eb4e541fff2b1aedbaa4420d7a8cea8100dc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01/task14.py", "max_forks_repo_name": "omartrinidad/pattern-recognition-bit", "max_forks_repo_head_hexsha": "ba3eb4e541fff2b1aedbaa4420d7a8cea8100dc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2222222222, "max_line_length": 80, "alphanum_fraction": 0.5730932203, "include": true, "reason": "import numpy", "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.9184802440252811, "lm_q1q2_score": 0.8590972939181002}}
{"text": "import pandas as pd\n#%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom scipy import integrate\nimport numpy as np\ndef simpe_harmonic(X, t, cons):  #simple harmonic oscillator\n    k,m = cons\n    x, y = X\n    dotx = y\n    dot2x = -k*x/m\n    return np.array([dotx, dot2x])\ndef damped_harmonic(X, t, cons):  #damped oscillator\n    k,m,b = cons\n    x, y = X\n    dotx = y\n    doty = -k*x-b*dotx\n    return np.array([dotx, doty])\ndef simple_pendulum(X, t, cons):  #Simple Pendulum\n    g,L = cons\n    x, y = X\n    dotx = y\n    doty = -g*x/L\n    return np.array([dotx, doty])\ndef RK2(func, X0, t,cons):\n    dt = t[1] - t[0]\n    nt = len(t)\n    X  = np.zeros([nt, len(X0)])\n    X[0] = X0\n    for i in range(nt-1):\n        k1 =dt* func(X[i], t[i], cons)\n        k2 = dt*func(X[i] +  k1, t[i] + dt, cons)\n        X[i+1] = X[i] + (k1 +  k2 )/2\n    return X, t\n\n\nif __name__ == \"__main__\":\n    k = 1; m = 1; cons=(k,m); t_p = 2*np.pi*np.sqrt(m/k); tmin=0; tmax=7*t_p; Nt = 1000; x0 = [2,0] \n    t = np.linspace(tmin,tmax,Nt)\n    Xrk2 = RK2(simpe_harmonic, x0, t, cons)\n    x,y= Xrk2[0].T\n    t=Xrk2[1]\n    tdimless=t/t_p\n    #Plotting\n    \n    plt.title('Simple Harmonic Oscillator', fontsize=20)    \n    plt.plot(tdimless,x,color='black',label=\"Displacement\");plt.plot(tdimless,y,color='brown',label=\"Velocity\")\n    plt.grid(); plt.legend()\n    plt.show()\n#Damped Harmonic Oscillator\n    k = 1; m = 1; t_p = 2*np.pi*np.sqrt(m/k); tmin=0; tmax=30*t_p; Nt = 1000; x0 = [1,0]\n    t = np.linspace(tmin,tmax,Nt)\n    tdimless=t/t_p; dis=[];vel=[];time=[]\n    ba=[0.15,2,5]\n    for b in ba:\n        cons=(m,k,b)\n        Xrk2=RK2(damped_harmonic,x0,tdimless, cons)\n        x,y= Xrk2[0].T\n        tdimless=Xrk2[1]\n        dis.append(x)\n        vel.append(y)\n    fig, axs = plt.subplots(3,figsize=(11,15))\n    fig.suptitle('Damped Harmonic Oscillator', fontsize=20)\n    axs[0].plot(tdimless,dis[0],label = \"displacement\")\n    axs[0].set(xlabel=\"time \",title=\"Underdamped, b = 0.15\")\n    axs[0].plot(tdimless,vel[0],label = \"velocity\")\n    axs[0].plot(tdimless,1/2*k*dis[0]**2)\n    axs[0].grid(); axs[0].legend()\n    axs[1].plot(tdimless,dis[1],label = \"displacement\")\n    axs[1].set(xlabel=\"time \",title=\"Critically Damped, b = 2\")\n    axs[1].plot(tdimless,vel[1],label = \"velocity\")\n    axs[1].plot(tdimless,1/2*k*dis[1]**2)\n    axs[1].grid(); axs[1].legend()\n    axs[2].plot(tdimless,dis[2],label = \"displacement\")\n    axs[2].plot(tdimless,1/2*k*dis[2]**2)\n    axs[2].set(xlabel=\"time \",title=\"Overdamped, b =5\")\n    axs[2].plot(tdimless,vel[2],label = \"velocity\")\n    axs[2].grid(); axs[2].legend()\n    plt.show()\n#Simple pendulum\n    g = 9.8; L = 1; cons=(g,L); t_p = 2*np.pi*np.sqrt(L/g); tmin=0; tmax=7*t_p; Nt = 1000; x0 = [2,0] \n    t = np.linspace(tmin,tmax,Nt)\n    Xrk2 = RK2(simple_pendulum, x0, t, cons)\n    x,y= Xrk2[0].T\n    t=Xrk2[1]\n    tdimless=t/t_p\n#Plotting    \n    plt.title('Simple Pendulum', fontsize=20)    \n    plt.plot(tdimless,x,color='black',label=\"Angular Displacement\");plt.plot(tdimless,y,color='brown',label=\"Angular Velocity\")\n    plt.grid(); plt.legend()\n    plt.show()\n", "meta": {"hexsha": "b6c465182398046c1e11f4c27fb7fb0ca8ab70af", "size": 3086, "ext": "py", "lang": "Python", "max_stars_repo_path": "ppt/MP Lab Practicals/2nd_order_diff_using_rk2/rk2.py", "max_stars_repo_name": "hinton024/Mathematical-Physics", "max_stars_repo_head_hexsha": "fabe34d0fb1492ad177c9e7be99e1dbe718fda69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ppt/MP Lab Practicals/2nd_order_diff_using_rk2/rk2.py", "max_issues_repo_name": "hinton024/Mathematical-Physics", "max_issues_repo_head_hexsha": "fabe34d0fb1492ad177c9e7be99e1dbe718fda69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ppt/MP Lab Practicals/2nd_order_diff_using_rk2/rk2.py", "max_forks_repo_name": "hinton024/Mathematical-Physics", "max_forks_repo_head_hexsha": "fabe34d0fb1492ad177c9e7be99e1dbe718fda69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9120879121, "max_line_length": 127, "alphanum_fraction": 0.5852235904, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377284730285, "lm_q2_score": 0.8962513800615313, "lm_q1q2_score": 0.8590907619849971}}
{"text": "# todo: Outlier detection and removal using z-score and standard deviation in python pandas\n\n# todo: import library\nimport pandas as pd\nimport matplotlib\nfrom matplotlib import pyplot as plt\nfrom scipy.stats import norm\nimport numpy as np\n\n# get_ipython().run_line_magic('matplotlib', 'inline')\nmatplotlib.rcParams['figure.figsize'] = (10, 6)\n\n# todo: We are going to use heights dataset from kaggle.com.\n#  Dataset has heights and weights both but I have removed weights to make it simple\n\n# todo: load dataset\ndf = pd.read_csv(\"heights.csv\")\ndf.sample(5)\n\n# todo: plotting histogram for visualization of height data\nplt.hist(df.height, bins=20, rwidth=0.8)\nplt.xlabel('Height (inches)')\nplt.ylabel('Count')\nplt.show()\n\n# todo: Plot bell curve along with histogram for our dataset using scipy.stats.norm\nplt.hist(df.height, bins=20, rwidth=0.8, density=True)\nplt.xlabel('Height (inches)')\nplt.ylabel('Count')\nrng = np.arange(df.height.min(), df.height.max(), 0.1)\nplt.plot(rng, norm.pdf(rng, df.height.mean(), df.height.std()))\n\n# todo: mean and std of normal distribution-\ndf.height.mean()\ndf.height.std()\n\n# todo: Outlier detection and removal using 3 standard deviation\n# One of the ways we can remove outliers is remove any data points that are beyond 3 standard deviation from mean.\n# Which means we can come up with following upper and lower bounds\n\n# todo: creating uppper  and lower limit for outlier using mean and std\nupper_limit = df.height.mean() + 3 * df.height.std()\nprint(upper_limit)\nlower_limit = df.height.mean() - 3 * df.height.std()\nprint(lower_limit)\n\n# todo: Here are the outliers that are beyond 3 std dev from mean\nprint(df[(df.height > upper_limit) | (df.height < lower_limit)])\n\n# Above the heights on higher end is **78 inch** which is around **6 ft 6 inch**. Now that is quite unusual height.\n# There are people who have this height but it is very uncommon and it is ok if you remove those data points.\n# Similarly on lower end it is **54 inch** which is around **4 ft 6 inch**.\n# While this is also a legitimate height you don't find many people having this height\n# so it is safe to consider both of these cases as outliers\n\n# todo: Now remove these outliers and generate new dataframe\ndf_no_outlier_std_dev = df[(df.height < upper_limit) & (df.height > lower_limit)]\ndf_no_outlier_std_dev.head()\nprint(df_no_outlier_std_dev.shape)\nprint(df.shape)\n\n# Above shows original dataframe data 10000 data points. Out of that we removed 7 outliers (i.e. 10000-9993)\n\n# todo: (2) Outlier detection and removal using Z Score\n# Z score is a way to achieve same thing that we did above in part (1)\n# Z score indicates how many standard deviation away a data point is.\n# For example in our case mean is 66.37 and standard deviation is 3.84.\n# If a value of a data point is 77.91 then Z score for that is 3 because\n# it is 3 standard deviation away (77.91 = 66.37 + 3 * 3.84)\n\n# todo: Calculate the Z Score\n# Z = (X - mean)/std\ndf['zscore'] = (df.height - df.height.mean()) / df.height.std()\ndf.head(5)\n# Above for first record with height 73.84, z score is 1.94. This means 73.84 is 1.94 standard deviation away from mean.\n# if Z is the above 3 or below -3 then that height is outlier.\n\n# todo: Get data points that has z score higher than 3 or lower than -3.\n# Another way of saying same thing is get data points that are more than 3 standard deviation away**\nprint(df[df['zscore'] > 3])\nprint(df[df['zscore'] < -3])\n\n# todo: Here is the list of all outliers\nprint(df[(df.zscore < -3) | (df.zscore > 3)])\n\n# todo: Remove the outliers and produce new dataframe\ndf_no_outliers = df[(df.zscore > -3) & (df.zscore < 3)]\ndf_no_outliers.head()\nprint(df_no_outliers.shape)\nprint(df.shape)\n# Above shows original dataframe data 10000 data points. Out of that we removed 7 outliers (i.e. 10000-9993)\n\n# (1) Remove outliers using percentile technique first. Use [0.001, 0.999] for lower and upper bound percentiles\n# (2) After removing outliers in step 1, you get a new dataframe.\n# (3) On step(2) dataframe, use 4 standard deviation to remove outliers\n# (4) Plot histogram for new dataframe that is generated after step (3). Also plot bell curve on same histogram\n# (5) On step(2) dataframe, use zscore of 4 to remove outliers.\n# This is quite similar to step (3) and you will get exact same result\n", "meta": {"hexsha": "253af8232aa8848e60455b7746c0962c99e8563b", "size": 4309, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/Machine Learning/Code Basics/Feature Engineering/2 Using Standard deviation and Z_score for remove outlier.py", "max_stars_repo_name": "omkarsutar1255/Python-Data", "max_stars_repo_head_hexsha": "169d0c54b23d9dd5a7f1aea41ab385121c3b3c63", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/Machine Learning/Code Basics/Feature Engineering/2 Using Standard deviation and Z_score for remove outlier.py", "max_issues_repo_name": "omkarsutar1255/Python-Data", "max_issues_repo_head_hexsha": "169d0c54b23d9dd5a7f1aea41ab385121c3b3c63", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/Machine Learning/Code Basics/Feature Engineering/2 Using Standard deviation and Z_score for remove outlier.py", "max_forks_repo_name": "omkarsutar1255/Python-Data", "max_forks_repo_head_hexsha": "169d0c54b23d9dd5a7f1aea41ab385121c3b3c63", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5252525253, "max_line_length": 120, "alphanum_fraction": 0.7384543978, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197139, "lm_q2_score": 0.896251371748038, "lm_q1q2_score": 0.8590907508315371}}
{"text": "from numpy import *\r\nimport numpy as np\r\nfrom math import *\r\nfrom matplotlib.pyplot import *\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.patches import Patch\r\n\r\n\r\n'''\r\nWrite down the function that we need to solve for \r\nx' = t^{-2}(tx-x^2)\r\n'''\r\n\r\ndef f(t,x):\r\n    return (t**(-2))*(t*x - (x**2))\r\n\r\n'''\r\nanother derivative of the function function\r\n''' \r\n\r\ndef dfx(t,x):\r\n    return (1/np.power(t,2))*(t-2*x)\r\n\r\n\r\n\r\n# analytical solution\r\n\r\n\r\n\r\n\r\n# backward Euler \r\ndef beuler(t0, tn, n, x0):\r\n    #h = abs(tn - t0)/n\r\n    t = linspace(t0, tn, n+1)\r\n    x = zeros(n+1)\r\n    x[0] = x0\r\n\r\n    for k in range(0,n):\r\n        err = 1\r\n        zold = x[k] + h*f(t[k], x[k])\r\n        I = 0\r\n\r\n        while err > 10**(-10) and I < 5:\r\n            F = x[k] + h*f(t[k+1], zold) - zold\r\n            dF = h*dfx(t[k+1], zold)-1\r\n            znew = zold - F/dF\r\n            err = abs(znew- zold)\r\n            I += 1\r\n        x[k+1] = znew\r\n    return x\r\n\r\n\r\n\r\n\r\ndef RK4(t0,tn,n,x0):\r\n    #h = abs(tn-t0)/n\r\n    t = linspace(t0, tn, n+1)\r\n    x = zeros(n+1)\r\n    x[0] = x0\r\n    for i in range(0,n):\r\n        K1 = f(t[i], x[i])\r\n        K2 = f(t[i]+h/2, x[i]+K1*h/2)\r\n        K3 = f(t[i] + h/2, x[i]+K2*h/2)\r\n        K4 = f(t[i] + h, x[i]+K3*h)\r\n\r\n        x[i+1] = x[i] + h*(K1+2*K2+ 2*K3+K4)/6\r\n    return x\r\n\r\n\r\n\r\ndef AdBash3(t0,tn,n,x0):\r\n    #h = abs(tn-t0)/n\r\n    t = linspace(t0, tn, n+1)\r\n    x = zeros(n+1)\r\n\r\n    x[0:3] = RK4(t0, t0+2*h,2,x0)\r\n    K1 = f(t[1], x[1])\r\n    K2 = f(t[0], x[0])\r\n\r\n    for i in range(2,n):\r\n        K3= K2\r\n        K2= K1\r\n        K1 = f(t[i], x[i])\r\n\r\n        # prediction_resul\r\n        x[i+1] = x[i] + h*(23*K1 - 16*K2+5*K3)/12\r\n    return x\r\n\r\n\r\n\r\n\r\n\r\ndef PreCorr3(t0,tn,n,x0):\r\n    #h = abs(tn-t0)/n\r\n    t = linspace(t0, tn, n+1)\r\n    x = zeros(n+1)\r\n\r\n    x[0:3] = RK4(t0, t0+2*h,2,x0)\r\n    K1 = f(t[1], x[1])\r\n    K2 = f(t[0], x[0])\r\n\r\n    for i in range(2,n):\r\n        K3= K2\r\n        K2= K1\r\n        K1 = f(t[i], x[i])\r\n\r\n        # prediction_resul\r\n        x[i+1] = x[i] + h*(23*K1 - 16*K2+5*K3)/12\r\n    \r\n\r\n        K0 = f(t[i+1],x[i+1])\r\n\r\n        # correctorical\r\n\r\n        x[i+1] = x[i] + h*(9*K0 + 19*K1 - 5*K2 + K3)/24\r\n\r\n    return x\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nfg = 1\r\nn= 200\r\nt0 = 1\r\nh = 0.01\r\ntn = 3 \r\nx0 = 2    \r\nt = linspace(t0, tn , n+1)\r\nxe = AdBash3(t0,tn, n, x0)\r\nxb = beuler(t0,tn,n,x0)\r\nxpc = PreCorr3(t0, tn, n,x0)\r\n\r\n\r\n\r\n# print\r\n#exact = sol(t0, tn ,n , x0)\r\n\r\n\r\n\r\nplot(t,xe,'o',color='yellow',label ='Adam Bashforth 3')\r\nplot(t, xb, '--', color='red', label ='Backward Euler')\r\nplot(t,xpc,'cyan',label='Predictor Corrector')\r\n#plot(t,(t* (1/2 + log(t))**(-1)),'blue',label ='Exact Solution')\r\n\r\n#t = linspace(t0, tn, 401)\r\n#xsol = sol(t,t0,x0)\r\n\r\n#plot(t,xsol, color='green', label='Exact')\r\n\r\n##title('n = %d' %n)\r\nt = t0\r\nexact = []\r\ntime = []\r\nwhile(t<=tn):\r\n    \r\n    m = (t* (1/2 + log(t))**(-1)) \r\n    \r\n    t = t+0.006666666666666821\r\n    exact.append(m)\r\n    time.append(t)\r\n\r\n\r\nplt.plot(time,exact,'blue',label='Exact')\r\n#axis([0,tn, -60,40])\r\nlegend(loc='upper right')\r\nplt.savefig('ADM.png')", "meta": {"hexsha": "065a14b1c26820f1e9af2816d6e55dd4bcfd281a", "size": 3051, "ext": "py", "lang": "Python", "max_stars_repo_path": "PSET2/Lecture 3/ADM/ADM.py", "max_stars_repo_name": "MonitSharma/Computational-Methods-in-Physics", "max_stars_repo_head_hexsha": "e3b2db36c37dd5f64b9a37ba39e9bb267ba27d85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PSET2/Lecture 3/ADM/ADM.py", "max_issues_repo_name": "MonitSharma/Computational-Methods-in-Physics", "max_issues_repo_head_hexsha": "e3b2db36c37dd5f64b9a37ba39e9bb267ba27d85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PSET2/Lecture 3/ADM/ADM.py", "max_forks_repo_name": "MonitSharma/Computational-Methods-in-Physics", "max_forks_repo_head_hexsha": "e3b2db36c37dd5f64b9a37ba39e9bb267ba27d85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0532544379, "max_line_length": 66, "alphanum_fraction": 0.4552605703, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661028358093, "lm_q2_score": 0.9005297794439688, "lm_q1q2_score": 0.8590748841837539}}
{"text": "\"\"\" Orbital Mechanics for Engineering Students Problem 1.21\r\nQuestion:\r\nNumerically solve the system\r\n    xDot + 0.5*y - z = 0\r\n    -0.5*x + yDot + 1/sqrt(2)*z = 0\r\n    0.5*x - 1/sqrt(2)*y + zDot = 0\r\nfor x, y, and z at t = 20, if the initial conditions at t=0 are:\r\n    - x = 1\r\n    - y = z = 0\r\nNote: the answer in the book is likely wrong, I cannot see anything wrong\r\nwith my working yet it yields a different answer.\r\nWritten by: J.X.J. Bannwarth\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom orbitutils.solvers import rkf45, rk14\r\n\r\n\r\n# Differential equations\r\ndef rates(t, Y):\r\n    F = np.zeros(Y.shape)\r\n    F[0] = -0.5*Y[1] + Y[2]\r\n    F[1] = 0.5*Y[0] - Y[2]/np.sqrt(2.)\r\n    F[2] = -0.5*Y[0] + Y[1]/np.sqrt(2.)\r\n    return F\r\n\r\n\r\n# Title\r\nprint(\"Orbital Mechanics for Engineering Students Problem 1.21\")\r\n\r\n# Parameters\r\ntSpan = np.array([0., 20.])\r\nY0 = np.array([1., 0., 0.])\r\n\r\n# Solve numerically\r\ny, t = rkf45(rates, Y0, tSpan)\r\ny, t = rk14(rates, Y0, tMax=20, h=1e-4)\r\n\r\n# Show answer\r\nprint(f\"x({t[-1]:.3f}) = {y[-1,0]:.3f}\")\r\nprint(f\"y({t[-1]:.3f}) = {y[-1,1]:.3f}\")\r\nprint(f\"z({t[-1]:.3f}) = {y[-1,2]:.3f}\")\r\n\r\n# Plot answer\r\nplt.figure()\r\nplt.plot(t, y[:, 0], label=\"x\")\r\nplt.plot(t, y[:, 1], label=\"y\")\r\nplt.plot(t, y[:, 2], label=\"z\")\r\nplt.xlabel(\"Time (-)\")\r\nplt.ylabel(\"Value (-)\")\r\nplt.legend()\r\nplt.show()\r\n", "meta": {"hexsha": "dc550ac2dcf660bf336e8289bfd298ccedc416f3", "size": 1351, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapter1/problem_1_21.py", "max_stars_repo_name": "JBannwarth/OrbitalMechanics", "max_stars_repo_head_hexsha": "fe3c36eba7cadf977804fb2ad866e0e28a96aab5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-29T13:34:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-29T13:34:48.000Z", "max_issues_repo_path": "chapter1/problem_1_21.py", "max_issues_repo_name": "JBannwarth/OrbitalMechanics", "max_issues_repo_head_hexsha": "fe3c36eba7cadf977804fb2ad866e0e28a96aab5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-06T21:17:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-07T00:52:39.000Z", "max_forks_repo_path": "chapter1/problem_1_21.py", "max_forks_repo_name": "JBannwarth/OrbitalMechanics", "max_forks_repo_head_hexsha": "fe3c36eba7cadf977804fb2ad866e0e28a96aab5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4905660377, "max_line_length": 74, "alphanum_fraction": 0.5743893412, "include": true, "reason": "import numpy", "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007596, "lm_q2_score": 0.9005297807787537, "lm_q1q2_score": 0.8590748807427752}}
{"text": "# =============================================================================\r\n# \r\n# Explicit Finite Difference Method Code to Solve the 1D Linear Transport Equation\r\n# Adapted by: Cameron Armstrong (2019)\r\n# Source: Lorena Barba, 12 Steps to NS in Python\r\n# Institution: Virginia Commonwealth University\r\n# \r\n# =============================================================================\r\n\r\n# Required Modules\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nimport time\r\n\r\nxl = 2                                      # x length\r\nnx = 600                                    # number of grid points\r\nx = np.linspace(0,xl,nx)                    # x grid \r\ndx = xl/(nx-1)                              # x stepsize\r\nnt = 350                                    # number of timesteps\r\ndt = 0.0025                                 # time stepsize\r\nc = 1                                       # wave speed\r\ng = .01                                     # gaussian variance parameter (peak width)\r\ntheta = x/(0.5*xl)                          # gaussian mean parameter (peak position)\r\ncfl = round(c*dt/dx,2)                      # cfl condition 2 decimal places\r\n\r\n# Fun little CFL condition check and print report\r\nif cfl >= 1:\r\n    print('Hold your horses! The CFL is %s, which is over 1' %(cfl))\r\nelse:\r\n    print('CFL = %s' %(cfl))\r\n\r\n# Array Initialization\r\nu = np.ones(nx)                             # initializing solution array\r\nun = np.ones(nx)                            # initializing temporary solution array\r\nu = (1/(2*np.sqrt(np.pi*(g))))*np.exp(-(1-theta)**2/(4*g)) # initial condition (IC) as a gaussian\r\nui = u.copy()\r\nplt.plot(x,u); # plots IC\r\n\r\n# BDS/Upwind with inner for-loop with example on process timing\r\nstart = time.process_time()\r\nfor n in range(nt):\r\n    un = u.copy()\r\n    for i in range(1,nx-1):\r\n        u[i] = un[i] - c*dt/(dx)*(un[i]-un[i-1])\r\n        # periodic BC's\r\n        u[0] = u[nx-2] \r\n        u[nx-1] = u[1]\r\n\r\nend = time.process_time()\r\nprint(end-start)\r\n\r\n# # BDS/Upwind with vectorization\r\n# for n in range(nt):\r\n#     un = u.copy()\r\n#     u[1:-1] = un[1:-1] - c*dt/(dx)*(un[1:-1]-un[:-2])\r\n#     # periodic BC's\r\n#     u[0] = u[nx-2]\r\n#     u[nx-1] = u[1]\r\n\r\n# # CDS with inner for-loop\r\n#for n in range(nt):\r\n#    un = u.copy()\r\n#    for i in range(1,nx-1):\r\n#        u[i] = un[i] - c*dt/(2*dx)*(un[i+1]-un[i-1])\r\n#        # periodic BC's\r\n#        u[0] = u[nx-2]\r\n#        u[nx-1] = u[1]\r\n\r\n# # CDS with vectorization\r\n#for n in range(nt):\r\n#    un = u.copy()\r\n#    u[1:-1] = un[1:-1] - c*dt/(2*dx)*(un[2:]-un[:-2])\r\n#    # periodic BC's\r\n#    u[0] = u[nx-2]\r\n#    u[nx-1] = u[1]\r\n\r\nplt.plot(x,u); \r\n\r\n\r\n", "meta": {"hexsha": "8afc13e213c403a3dacc0931aa5029c3a13cf2e0", "size": 2656, "ext": "py", "lang": "Python", "max_stars_repo_path": "lineartransporteqn.py", "max_stars_repo_name": "killacamron/CFDcourse21", "max_stars_repo_head_hexsha": "5ae59303d042819e0246e793271f420de8e1bbdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lineartransporteqn.py", "max_issues_repo_name": "killacamron/CFDcourse21", "max_issues_repo_head_hexsha": "5ae59303d042819e0246e793271f420de8e1bbdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lineartransporteqn.py", "max_forks_repo_name": "killacamron/CFDcourse21", "max_forks_repo_head_hexsha": "5ae59303d042819e0246e793271f420de8e1bbdb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2, "max_line_length": 98, "alphanum_fraction": 0.4608433735, "include": true, "reason": "import numpy", "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832346, "lm_q2_score": 0.9005297794439687, "lm_q1q2_score": 0.8590748771122764}}
{"text": "# %%[markdown]\n# First we load and configure the libraries we need:\n# %%\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Make numpy print 4 significant digits for prettiness\nnp.set_printoptions(precision=4, suppress=True)\nnp.random.seed(5)\n\n# %%[markdown]\n# Here is a set of data, made out of random numbers, that we will use as a pretend time series, \n# or a single line of data from one plane of an image.\n\n\n# %%\nn_points = 40\n\nx_vals = np.arange(n_points)\ny_vals = np.random.normal(size=n_points)\nplt.bar(x_vals, y_vals)\n\n# %%[markdown]\n# ## The Gaussian kernel\n# The ‘kernel’ for smoothing, defines the shape of the function that \n# is used to take the average of the neighboring points. A Gaussian \n# kernel is a kernel with the shape of a Gaussian (normal distribution) \n# curve. Here is a standard Gaussian, with a mean of 0 and a \n# σ (=population standard deviation) of 1.\n\n\n# %%\nx = np.arange(-6, 6, 0.1)  # x from -6 to 6 in steps of 0.1\ny = 1 / np.sqrt(2 * np.pi) * np.exp(-x ** 2 / 2.)\nplt.plot(x, y)\n\n\n# %%[markdown]\n# In the standard statistical way, we have defined the width of the \n# Gaussian shape in terms of σ. However, when the Gaussian is used \n# for smoothing, it is common for imagers to describe the width of \n# the Gaussian with another related measure, the Full Width at Half \n# Maximum (FWHM).\n#\n# The FWHM is the width of the kernel, at half of the maximum of the \n# height of the Gaussian. Thus, for the standard Gaussian above, the \n# maximum height is ~0.4. The width of the kernel at 0.2 (on the Y axis) \n# is the FWHM. As x = -1.175 and 1.175 when y = 0.2, the FWHM is roughly 2.35.\n#\n# The FWHM is related to sigma by the following formulae (in Python):\n\n# %%\ndef sigma2fwhm(sigma):\n    return sigma * np.sqrt(8 * np.log(2))\n\n\ndef fwhm2sigma(fwhm):\n    return fwhm / np.sqrt(8 * np.log(2))\n\n", "meta": {"hexsha": "36219616e50b6642e2473ec2f9796c48c61ad268", "size": 1833, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/smooth/gaussian_smoothing.py", "max_stars_repo_name": "jiaweiM/plot-note", "max_stars_repo_head_hexsha": "5b4147795aa03665fd51df7558b79f927101fbbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/smooth/gaussian_smoothing.py", "max_issues_repo_name": "jiaweiM/plot-note", "max_issues_repo_head_hexsha": "5b4147795aa03665fd51df7558b79f927101fbbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/smooth/gaussian_smoothing.py", "max_forks_repo_name": "jiaweiM/plot-note", "max_forks_repo_head_hexsha": "5b4147795aa03665fd51df7558b79f927101fbbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.55, "max_line_length": 96, "alphanum_fraction": 0.6993998909, "include": true, "reason": "import numpy", "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.9263037282594921, "lm_q1q2_score": 0.8590200800681198}}
{"text": "'''Matrix Symmetry\n\nAuthor: Andrei-Claudiu Roibu, 2019\n\nThis code has been created to compare the speed difference between a numpy dot product and a slow dot product. This code was written in support of my learning.\n\nThe original code comes from these two sources: \n\n    # https://deeplearningcourses.com/c/deep-learning-prerequisites-the-numpy-stack-in-python\n    # https://www.udemy.com/deep-learning-prerequisites-the-numpy-stack-in-python\n\nDescription:\n\nThis code tests if a matrix is symmetric. This is done either manually, and using numpy functions.\n\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef symmetric_test(array):\n    \"\"\" Simple symmetry test\n\n    Function wrapper which calls to check if a matrix is symmetric.\n\n    Args:\n        array (np.array): Array to be tested if symmetric\n    Returns:\n        (bool): Truth value indicating if array is symmetric\n    \"\"\"\n\n    return np.all(array == array.T)\n\ndef symmetric_check(array, truth):\n    \"\"\" Symmetric assertion checker\n\n    This function checks if an array is symmetric or not.\n\n    Args:\n        array (np.array): Array to be tested if symmetric\n        truth (bool): Truth value indicating if array is symmetric or not\n    \"\"\"\n    print(\"Testing: \", '\\n', array)\n    assert(symmetric_test(array) == truth)\n\nif __name__ == '__main__':\n    A = np.zeros((3, 3))\n    symmetric_check(A, True)\n\n    A = np.eye(3)\n    symmetric_check(A, True)\n\n    A = np.random.randn(3, 2)\n    A = A.dot(A.T)\n    symmetric_check(A, True)\n\n    A = np.array([[1, 2, 3], [2, 4, 5], [3, 5, 6]])\n    symmetric_check(A, True)\n\n    A = np.random.randn(3, 2)\n    symmetric_check(A, False)\n\n    A = np.random.randn(3, 3)\n    symmetric_check(A, False)\n\n    A = np.arange(9).reshape(3, 3)\n    symmetric_check(A, False)", "meta": {"hexsha": "75ebd2026330436fb590a09c0ba3039a82714cf6", "size": 1767, "ext": "py", "lang": "Python", "max_stars_repo_path": "simple_exercises/Matrix_Symmetry.py", "max_stars_repo_name": "AndreiRoibu/basic_numpy", "max_stars_repo_head_hexsha": "4bcaf2a5b628937f481de9d5b7a7c9061c1eb816", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simple_exercises/Matrix_Symmetry.py", "max_issues_repo_name": "AndreiRoibu/basic_numpy", "max_issues_repo_head_hexsha": "4bcaf2a5b628937f481de9d5b7a7c9061c1eb816", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simple_exercises/Matrix_Symmetry.py", "max_forks_repo_name": "AndreiRoibu/basic_numpy", "max_forks_repo_head_hexsha": "4bcaf2a5b628937f481de9d5b7a7c9061c1eb816", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3731343284, "max_line_length": 159, "alphanum_fraction": 0.6734578381, "include": true, "reason": "import numpy", "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.9273632891223317, "lm_q1q2_score": 0.8590200702783182}}
{"text": "\"\"\"\nSpace derivatives approximation using differentiation matrices\n\nImplements differentiation matrices for:\n    - Finite Differences of second and fourth order of accuracy \n    - Chebyshev differentiation matrix\n\nDetails in: Trefethen, L. N. (2000). Spectral methods in MATLAB. Society for industrial and applied mathematics.\nhttps://doi.org/10.1137/1.9780898719598\n\"\"\"\nimport numpy as np\nimport scipy as sp\nfrom scipy.linalg import circulant, toeplitz\nfrom scipy.sparse import csr_matrix\n\n# First derivative with Finite Difference Matrix\ndef FD1Matrix(N, h, acc=2, sparse=False):\n    \"\"\"\n    Compute first derivative using Finite Difference Matrix\n    with O(h^acc) of accuracy.\n    \n    Parameters\n    ----------\n    N : int\n        Number of nodes.\n    h : float\n        Step size.\n    acc\t: int\n        Order of accuracy (2 or 4)\n    sparse : boolean\n        If true, return sparse matrix.\n            \n    Returns\n    -------\n    D1 : (N, N) ndarray\n        Finite difference dense matrix; or\n    sD1 : sparse-like\n        Finite difference sparse matrix.\n    \"\"\"\n    d1 = np.zeros(N)\n\n    if acc == 2: # Coefficients for second order\n        d1[1] = -1/2\n        d1[-1] = 1/2\n    elif acc == 4: # Coefficients for fourth order\n        d1[1] = -2/3\n        d1[2] = 1/12\n        d1[-1] = 2/3\n        d1[-2] = -1/12\n    \n    D1 = circulant(d1) # Central difference inside the domain\n    \n    # Finite difference at boundary. \n    # To keep accuracy, it uses forward and backward coefficients of second or fourth order\n    if acc == 2:\n        D1[0,:3] = np.array([-3/2, 2, -1/2]) # Forward difference at left boundary\n        D1[-1,-3:] = np.array([1/2, -2, 3/2]) # Backward difference at right boundary\n    elif acc == 4:\n        D1[0,:5] = np.array([-25/12\t, 4, -3, 4/3, -1/4]) # Forward difference at left boundary\n        D1[-1,-5:] = np.array([1/4, -4/3, 3, -4, 25/12]) # Backward difference at right boundary\n\n    D1 = D1 / h # Include step\n    \n    if sparse: \n        D1 = csr_matrix(D1)\n\n    return D1\n    \n# Second derivative with Finite Difference Matrix\ndef FD2Matrix(N, h, acc=2, sparse=False):\n    \"\"\"\n    Compute second derivative using Finite Difference Matrix\n    with O(h^acc) of accuracy.\n    \n    Parameters\n    ----------\n    N : int\n        Number of nodes.\n    h : float\n        Step size.\n    acc : int\n        Order of accuracy (2 or 4)\n    sparse : boolean\n        If true, return sparse matrix.\n            \n    Returns\n    -------\n    D2 : (N, N) ndarray\n        Finite difference dense matrix; or\n    sD2 : sparse-like\n        Finite difference sparse matrix.\n    \"\"\"\n    d2 = np.zeros(N)\n    \n    if acc == 2:\n        d2[0] = -2\n        d2[1] = 1\n        d2[-1] = 1\n    elif acc == 4:\n        d2[0] = -5/2\n        d2[1] = 4/3\n        d2[2] = -1/12\n        d2[-1] = 4/3\n        d2[-2] = -1/12\n\n    D2 = circulant(d2) \n    \n    if acc == 2:\n        D2[0,:4] = np.array([2, -5, 4, -1]) # Forward difference at left boundary\n        D2[-1,-4:] = np.array([-1, 4, -5, 2]) # Backward difference at right boundary\n    elif acc == 4:\n        D2[0,:6] = np.array([15/4, -77/6, 107/6, -13, 61/12, -5/6]) # Forward difference at left boundary\n        D2[-1,:6] = np.array([-5/6, 61/12, -13, 107/6, -77/6, 15/4]) # Backward difference at right boundary\n    \n    D2 = D2 / (h ** 2)\n    \n    if sparse: D2 = csr_matrix(D2)\n    \n    return D2\n\n# Chebyshev differentiation matrix\ndef chebyshevMatrix(N):\n    \"\"\"\n    Compute derivative using Chebyshev differentiation Matrix.\n    \n    Parameters\n    ----------\n    N : int\n        Number of nodes.\n            \n    Returns\n    -------\n    D2 : (N+1, N+1) ndarray\n        Chebyshev differentation matrix\n    x : (N+1) array\n        Chebyshev x domain\n    \"\"\"\n    if N == 0:\n        D = 0\n        x = 1\n        return D, x\n    x = np.cos(np.pi * np.arange(N + 1) / N)\n    c = np.hstack((2, np.ones(N - 1), 2)) * ((-1.)**np.arange(N + 1))\n    X = np.tile(x, (N + 1, 1)).T\n    dX = X - X.T\n    D = np.outer(c, 1./c) / (dX + np.eye(N + 1))\n    D = D - np.diag(np.sum(D.T, axis=0))\n    return D, x", "meta": {"hexsha": "dcd32fc212eedcfddf983378eb6d4f0afc58ebb4", "size": 4058, "ext": "py", "lang": "Python", "max_stars_repo_path": "wildfire/numerical/space/diffmat.py", "max_stars_repo_name": "dsanmartin/ngen-kutral", "max_stars_repo_head_hexsha": "4e724b8108a698dec25aa122b831f42c9b91ba9a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wildfire/numerical/space/diffmat.py", "max_issues_repo_name": "dsanmartin/ngen-kutral", "max_issues_repo_head_hexsha": "4e724b8108a698dec25aa122b831f42c9b91ba9a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wildfire/numerical/space/diffmat.py", "max_forks_repo_name": "dsanmartin/ngen-kutral", "max_forks_repo_head_hexsha": "4e724b8108a698dec25aa122b831f42c9b91ba9a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-12T18:46:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-12T18:46:06.000Z", "avg_line_length": 27.4189189189, "max_line_length": 112, "alphanum_fraction": 0.5512567767, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96323053709097, "lm_q2_score": 0.8918110418436166, "lm_q1q2_score": 0.8590196288186843}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nif __name__ == \"__main__\":\n    t = [0.000, 0.375, 0.475, 1.450, 2.050]\n    s = [0.411, 0.330, 0.320, 0.300, 0.410]\n    t0 = 0.621\n    star = '*' * 15\n\n    # ********* Q1 *********\n    print('\\n', '*' * 12, 'Q1', '*' * 12)\n    start = -0.1\n    stop = 2.2\n    steps = 0.005\n    tt = [np.round(step, 3) for step in np.arange(start, stop, steps)]\n    print(f\"t_min: {start}, dt: {steps}, t_max:{stop}\")\n\n    # ********* Q2 *********\n    print('\\n', '*' * 12, 'Q2', '*' * 12)\n    a_mat = np.empty((0, 3))\n    for i in t:\n        a_mat = np.append(a_mat, np.array([[1, i, i ** 2]]), axis=0)\n    x_cap = np.linalg.inv(np.transpose(a_mat).dot(a_mat)).dot(np.transpose(a_mat).dot(s))\n    x_cap = np.round(x_cap, 6)\n    print(f\"x_cap: {x_cap}\")\n    ss_second_poly = [np.round(np.array([1, t, t ** 2]).dot(x_cap), 6) for t in tt]\n    print('Plot 1')\n    plt.gcf().number\n    plt.figure(1)\n    plt.plot(t, s, 'ro', tt, ss_second_poly, 'b-')\n    plt.legend(['Points', '2nd Order Polynomial'], loc='best')\n    plt.title('2nd Order Polynomial')\n    plt.xlabel('t')\n    plt.ylabel('s')\n\n    # ********* Q3 *********\n    print('\\n', '*' * 12, 'Q3', '*' * 12)\n    s0_second_poly = np.round(np.array([1, t0, t0 ** 2]).dot(x_cap), 6)\n    print(f\"s0 second order polynomial: {s0_second_poly}\")\n\n    # ********* Q4 *********\n    print('\\n', '*' * 12, 'Q4', '*' * 12)\n    v = a_mat.dot(x_cap) - np.array(s)\n    u = 3\n    n = len(s)\n    rms = np.sqrt((np.transpose(v).dot(v)) / (n - u))\n    rms = np.round(rms, 6)\n    print(f\"rmse: {rms}\")\n\n    # ********* Q5 *********\n    print('\\n', '*' * 12, 'Q5', '*' * 12)\n    di = np.empty((0, 1))\n    for i in range(len(t)):\n        di = np.append(di, 1 / (0.000001 + abs(t0 - t[i])))\n    s0_idw = di.dot(s) / sum(di)\n    s0_idw = np.round(s0_idw, 6)\n    print(f\"s0_idw: {s0_idw}\")\n\n    di = np.empty((0, 1))\n    ss_idw = np.empty((0, 1))\n    for ti in tt:\n        for i in range(len(t)):\n            di = np.append(di, 1 / (0.000001 + abs(ti - t[i])))\n        ss_idw = np.append(ss_idw, np.round(di.dot(s) / sum(di), 6))\n        di = np.empty((0, 1))\n    print('Plot 2')\n    plt.figure(2)\n    plt.plot(t, s, 'ro', tt, ss_idw, 'g-')\n    plt.legend(['Points', 'IDW'], loc='best')\n    plt.title('IDW')\n    plt.xlabel('t')\n    plt.ylabel('s')\n\n    # ********* Q6 *********\n    print('\\n', '*' * 12, 'Q6', '*' * 12)\n    di = np.empty((0, 1))\n    for i in range(len(t)):\n        di = np.append(di, 1 / (0.000001 + abs(t0 - t[i])) ** 2)\n    s0_isdw = di.dot(s) / sum(di)\n    s0_isdw = np.round(s0_isdw, 6)\n    print(f\"s0_isdw: {s0_isdw}\")\n\n    di = np.empty((0, 1))\n    ss_isdw = np.empty((0, 1))\n    for ti in tt:\n        for i in range(len(t)):\n            di = np.append(di, 1 / (0.000001 + abs(ti - t[i])) ** 2)\n        ss_isdw = np.append(ss_isdw, np.round(di.dot(s) / sum(di), 6))\n        di = np.empty((0, 1))\n    print('Plot 3')\n    plt.figure(3)\n    plt.plot(t, s, 'ro', tt, ss_isdw, 'y-')\n\n    plt.legend(['Points', 'ISDW'], loc='best')\n    plt.title('ISDW')\n    plt.xlabel('t')\n    plt.ylabel('s')\n\n    print('Plot 4')\n    plt.figure(4)\n    plt.plot(t, s, 'ro', tt, ss_idw, 'g-', tt, ss_isdw, 'y-')\n    plt.legend(['Points', 'IDW', 'ISDW'], loc='best')\n    plt.title('IDW & ISDW')\n    plt.xlabel('t')\n    plt.ylabel('s')\n\n    # ********* Q7 *********\n    print('\\n', '*' * 12, 'Q7', '*' * 12)\n    d0 = np.round(np.mean(s), 6)\n    print(f\"d0: {d0}\")\n    a_mat = np.empty((0, 2))\n    for ti in t:\n        a_mat = np.append(a_mat, np.array([[1, ti]]), axis=0)\n    ss_ll = np.empty((0, 1))\n    for ti in tt:\n        p = np.zeros([5, 5])\n        for i in range(len(t)):\n            d = np.abs(ti - t[i])\n            p[i][i] = np.exp(-((d ** 2) / (2 * (d0 ** 2))))\n        x_cap = np.linalg.inv(np.transpose(a_mat).dot(p).dot(a_mat)).dot(np.transpose(a_mat).dot(p).dot(s))\n        a0_mat = np.empty((0, 2))\n        a0_mat = np.append(a0_mat, np.array([[1, ti]]), axis=0)\n        ss_ll = np.append(ss_ll, a0_mat.dot(x_cap))\n    print('Plot 5')\n    plt.figure(5)\n    plt.plot(t, s, 'ro', tt, ss_ll, 'c-')\n    plt.legend(['Points', 'LLP'], loc='best')\n    plt.title('Local Linear Interpolation -- d0=0.3542')\n    plt.xlabel('t')\n    plt.ylabel('s')\n\n    d0 = 0.1\n    ss_ll_small = np.empty((0, 1))\n    for ti in tt:\n        p = np.zeros([5, 5])\n        for i in range(len(t)):\n            d = np.abs(ti - t[i])\n            p[i][i] = np.exp(-((d ** 2) / (2 * (d0 ** 2))))\n        x_cap = np.linalg.inv(np.transpose(a_mat).dot(p).dot(a_mat)).dot(np.transpose(a_mat).dot(p).dot(s))\n        a0_mat = np.empty((0, 2))\n        a0_mat = np.append(a0_mat, np.array([[1, ti]]), axis=0)\n        ss_ll_small = np.append(ss_ll_small, a0_mat.dot(x_cap))\n    print('Plot 6')\n    plt.figure(6)\n    plt.plot(t, s, 'ro', tt, ss_ll_small, 'c-')\n    plt.legend(['Points', 'LLP'], loc='best')\n    plt.title('Local Linear Interpolation - d0=0.1')\n    plt.xlabel('t')\n    plt.ylabel('s')\n\n    d0 = 6\n    ss_ll_big = np.empty((0, 1))\n    for ti in tt:\n        p = np.zeros([5, 5])\n        for i in range(len(t)):\n            d = np.abs(ti - t[i])\n            p[i][i] = np.exp(-((d ** 2) / (2 * (d0 ** 2))))\n        x_cap = np.linalg.inv(np.transpose(a_mat).dot(p).dot(a_mat)).dot(np.transpose(a_mat).dot(p).dot(s))\n        a0_mat = np.empty((0, 2))\n        a0_mat = np.append(a0_mat, np.array([[1, ti]]), axis=0)\n        ss_ll_big = np.append(ss_ll_big, a0_mat.dot(x_cap))\n    print('Plot 7')\n    plt.figure(7)\n    plt.plot(t, s, 'ro', tt, ss_ll_big, 'c-')\n    plt.legend(['Points', 'LLP'], loc='best')\n    plt.title('Local Linear Interpolation - d0=5')\n    plt.xlabel('t')\n    plt.ylabel('s')\n\n    # ********* Q8 *********\n    print('\\n', '*' * 12, 'Q8', '*' * 12)\n    nearest_num_t0 = np.abs(np.array(tt) - t0)\n    t0_index = np.where(nearest_num_t0 == np.min(nearest_num_t0))\n    s0_ll = np.round(ss_ll[t0_index][0], 6)\n    print(f\"s0_ll: {s0_ll}\")\n\n    plt.show()\n", "meta": {"hexsha": "cc484f1398d1a8b6b6615118e8409d8ad18b4195", "size": 5910, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "mhgzadeh/gsm-second-assignment", "max_stars_repo_head_hexsha": "468ff109e6dd2d26e37d9f741fc409011c20a4d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.py", "max_issues_repo_name": "mhgzadeh/gsm-second-assignment", "max_issues_repo_head_hexsha": "468ff109e6dd2d26e37d9f741fc409011c20a4d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "mhgzadeh/gsm-second-assignment", "max_forks_repo_head_hexsha": "468ff109e6dd2d26e37d9f741fc409011c20a4d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.202247191, "max_line_length": 107, "alphanum_fraction": 0.4947546531, "include": true, "reason": "import numpy", "num_tokens": 2117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551566309689, "lm_q2_score": 0.8902942173896131, "lm_q1q2_score": 0.859004966567101}}
{"text": "# By\n# ████████╗██╗   ██╗ █████╗ ███╗   ██╗    ██╗  ██╗ ██████╗ \n# ╚══██╔══╝██║   ██║██╔══██╗████╗  ██║    ██║  ██║██╔═══██╗\n#    ██║   ██║   ██║███████║██╔██╗ ██║    ███████║██║   ██║\n#    ██║   ██║   ██║██╔══██║██║╚██╗██║    ██╔══██║██║   ██║\n#    ██║   ╚██████╔╝██║  ██║██║ ╚████║    ██║  ██║╚██████╔╝\n#    ╚═╝    ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═══╝    ╚═╝  ╚═╝ ╚═════╝ \n\n# Email: ttuan.ho@outlook.com                                                         \n\n\nfrom scipy.stats import norm, binom, poisson, expon, uniform\nfrom scipy import stats\nimport numpy as np\n\n\"\"\"\nEx2\n\"\"\"\n\ndata = np.array([15.2,14.2,14.0,12.2,14.4,12.5,14.3,14.2,13.5,11.8,15.2])\n# a) Construct a 99% two-sided confidence interval on the mean temperature.\n# % matlab verson:\n# tCrit=tinv(0.995,10)\ntCrit = stats.t.ppf(0.995,10)\n\n# interval  is :\nnp.mean(data) + np.std(data) / ((len(data))**(1/2)) * tCrit * np.array([-1,1])\n\n\n# c) Suppose that we wanted to be 95% confident that the error in estimating the mean temperature is\n# less than 0.4°C. What sample size should be used?\n# % matlab verson:\n# tStar = tinv(0.975,10)\n# s / sqrt(n) * tStar < 0.4\n\n\"\"\"\nEx3:\nThe wall thickness of 25 glass 2-litre bottles was measured by a quality-control engineer. \nThe sample mean was m = 4.05 millimetres, and the sample standard deviation was s = 0.08 \nmillimetre. Find a 95% lower confidence bound for mean wall thickness. Interpret the interval \nyou have obtained. Assume the normal distribution for wall thickness.\n\"\"\"\n\nm = 4.05\nn = 25\nalpha = 0.05\ns = 0.08\n\ntStar = stats.t.ppf(0.95,n-1)\n\n# The lower bound is:\nfloat(m) - s / ((float(n))**(1/2)) * tStar\n\n\"\"\"\nEx6:\nThe article “Repeatability and Reproducibility for Pass/Fail data” (J. of Testing and Eval., 1997, \n151-153) reported that in n = 48 trials in a particular laboratory, 16 resulted in ignition of a \nparticular type of substrate by a lighted cigarette. Find a 95% approximate confidence interval for \nπ, the true long-run proportion (or probability) of all such trials that would result in ignition.\n\"\"\"\nn = float(48)\nk = float(16)\npHat = 16/48\n\nprint(f\"Checking if the the sample is large enough:\")\nprint(f\"n*pHat*(1-pHat)>5={n*pHat*(1-pHat)>5}\")\n\n# tStar = norm.ppf(0.975)\ntStar = 1.96\nprint(f\"95% CI for pi:\")\nres = pHat + (tStar * ((pHat*(1-pHat)/n)**(1/2)) * np.array([-1,1]))\nprint(f\"{res}\")\n\n\n", "meta": {"hexsha": "b4a3c54e706d4f04b3119b4a60001395bf33a4dc", "size": 2324, "ext": "py", "lang": "Python", "max_stars_repo_path": "week_05_Confidence_intervals_for_means_and_proportions/Exercise_5.py", "max_stars_repo_name": "ttuanho/MATH_2859", "max_stars_repo_head_hexsha": "2a98346c4e908d9373998f670303720390505233", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week_05_Confidence_intervals_for_means_and_proportions/Exercise_5.py", "max_issues_repo_name": "ttuanho/MATH_2859", "max_issues_repo_head_hexsha": "2a98346c4e908d9373998f670303720390505233", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week_05_Confidence_intervals_for_means_and_proportions/Exercise_5.py", "max_forks_repo_name": "ttuanho/MATH_2859", "max_forks_repo_head_hexsha": "2a98346c4e908d9373998f670303720390505233", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9866666667, "max_line_length": 100, "alphanum_fraction": 0.5636833046, "include": true, "reason": "import numpy,from scipy", "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551525886193, "lm_q2_score": 0.8902942166619119, "lm_q1q2_score": 0.8590049622660942}}
{"text": "\"\"\"\nSolution to the stride diagonal exercise\n=========================================\n\nSolution showing how to use as_strided to stride in diagonal.\n\n\"\"\"\n\nimport numpy as np\nfrom numpy.lib.stride_tricks import as_strided\n\n#\n# Part 1\n#\n\nx = np.array([[1, 2, 3],\n              [4, 5, 6],\n              [7, 8, 9]], dtype=np.int32)\n\nx_diag = as_strided(x, shape=(3,), strides=((3+1)*x.itemsize,))\nx_supdiag = as_strided(x[0,1:], shape=(2,), strides=((3+1)*x.itemsize,))\nx_subdiag = as_strided(x[1:,0], shape=(2,), strides=((3+1)*x.itemsize,))\n\nprint(x_diag)\nprint(x_supdiag)\nprint(x_subdiag)\n\n#\n# Mini-exercise: (assume C memory order)\n#\n# 0. How to pick diagonal entries of the matrix\n#\n# 1. How to pick the super-diagonal entries [2, 6]\n#\n# 2. The sub-diagonal entries [4, 8]\n#\n# 99. Can you generalize this for any stride and shape combinations\n#     in the initial array?\n#\n#     If you can, tell me, and maybe numpy.trace can be made faster :)\n#\n\n\n#\n# Part 2\n#\n\n# Compute the tensor trace\n\nx = np.arange(5*5*5*5).reshape(5,5,5,5)\n\ns = 0\nfor i in range(5):\n    for j in range(5):\n        s += x[j,i,j,i]\n\n# by striding and using .sum()\n\ny = as_strided(x, shape=(5, 5), strides=((5*5*5+5)*x.itemsize,\n                                         (5*5+1)*x.itemsize))\ns2 = y.sum()\n\nassert s == s2\n", "meta": {"hexsha": "1cb76c681c852a68695bb307e4f72dac526a7006", "size": 1292, "ext": "py", "lang": "Python", "max_stars_repo_path": "advanced/advanced_numpy/examples/stride-diagonals-answer.py", "max_stars_repo_name": "zmoon/scipy-lecture-notes", "max_stars_repo_head_hexsha": "75a89ddedeb48930dbdb6fe25a76e9ef0587ae21", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2538, "max_stars_repo_stars_event_min_datetime": "2015-01-01T04:58:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:06:05.000Z", "max_issues_repo_path": "advanced/advanced_numpy/examples/stride-diagonals-answer.py", "max_issues_repo_name": "zmoon/scipy-lecture-notes", "max_issues_repo_head_hexsha": "75a89ddedeb48930dbdb6fe25a76e9ef0587ae21", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 362, "max_issues_repo_issues_event_min_datetime": "2015-01-18T14:16:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T16:24:34.000Z", "max_forks_repo_path": "advanced/advanced_numpy/examples/stride-diagonals-answer.py", "max_forks_repo_name": "zmoon/scipy-lecture-notes", "max_forks_repo_head_hexsha": "75a89ddedeb48930dbdb6fe25a76e9ef0587ae21", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1127, "max_forks_repo_forks_event_min_datetime": "2015-01-05T14:39:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:38:39.000Z", "avg_line_length": 20.1875, "max_line_length": 72, "alphanum_fraction": 0.5882352941, "include": true, "reason": "import numpy,from numpy", "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.9252299643080207, "lm_q1q2_score": 0.8589916414011691}}
{"text": "import numpy as np\n\n\"\"\"\nA2-Part-4: Implement the inverse discrete Fourier transform (IDFT)\n\nWrite a function that implements the inverse discrete Fourier transform (IDFT). Given a frequency \nspectrum X of length N, the function should return its IDFT x, also of length N. Assume that the \nfrequency index of the input spectrum ranges from 0 to N-1.\n\nThe input argument to the function is a numpy array X of the frequency spectrum and the function should return \na numpy array of the IDFT of X.\n\nRemember to scale the output appropriately.\n\nEXAMPLE: If you run your function using X = np.array([1 ,1 ,1 ,1]), the function should return the following numpy \narray x: array([  1.00000000e+00 +0.00000000e+00j,   -4.59242550e-17 +5.55111512e-17j,\n    0.00000000e+00 +6.12323400e-17j,   8.22616137e-17 +8.32667268e-17j])\n\nNotice that the output numpy array is essentially [1, 0, 0, 0]. Instead of exact 0 we get very small\nnumerical values of the order of 1e-15, which can be ignored. Also, these small numerical errors are \nmachine dependent and might be different in your case.\n\nIn addition, an interesting test of the IDFT function can be done by providing the output of the DFT of \na sequence as the input to the IDFT. See if you get back the original time domain sequence.\n\n\"\"\"\ndef IDFT(X):\n    \"\"\"\n    Input:\n        X (numpy array) = frequency spectrum (length N)\n    Output:\n        The function should return a numpy array of length N \n        x (numpy array) = The N point IDFT of the frequency spectrum X\n    \"\"\"\n    ## Your code here\n    N = X.shape[-1]\n    x = np.zeros(N, dtype=np.complex)\n\n    for n in range(N):\n        s = np.exp(1j * 2 * np.pi * n / N * np.arange(N))\n        x[n] = X.dot(s)\n    x /= N\n\n    return x\n\n", "meta": {"hexsha": "3194beaa463dfbbc13e0012e94813eea1d924760", "size": 1731, "ext": "py", "lang": "Python", "max_stars_repo_path": "A2/A2Part4.py", "max_stars_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_stars_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A2/A2Part4.py", "max_issues_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_issues_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A2/A2Part4.py", "max_forks_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_forks_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6304347826, "max_line_length": 115, "alphanum_fraction": 0.7001733102, "include": true, "reason": "import numpy", "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.9284088040219143, "lm_q1q2_score": 0.8589916340808484}}
{"text": "# solutions.py\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# Problem 1: Implement this function.\ndef Newtons_method(f, x0, Df, iters=15, tol=.002):\n    '''\n    Use Newton's method to approximate a zero of a function.\n    Inputs:\n        f (function): A function handle. Should represent a function \n            from R to R.\n        x0 (float): Initial guess.\n        Df (function): A function handle. Should represent the derivative\n             of f.\n        iters (int): Maximum number of iterations before the function\n            returns. Defaults to 15.\n        tol (float): The function returns when the difference between\n            successive approximations is less than tol.\n    Returns:\n        A tuple (x, converged, numiters) with\n        x (float): the approximation for a zero of f\n        converged (bool): a Boolean telling whether Newton's method converged\n        numiters (int): the number of iterations the method computed\n    '''\n    xold = x0\n    for numiters in range(1,iters+1):\n        xnew = xold-f(xold)*1./Df(xold)\n        if abs(xnew-xold)<tol:\n            return xnew,True,numiters\n        else:\n            xold = xnew\n    return xnew,False,numiters\n        \n\n# Problem 2.1: Implement this function.\ndef problemTwoOne():\n    '''\n    Return a tuple of the number of iterations to get five digits of accuracy\n    for f = cos(x) with x_0 = 1 and x_0 = 2.\n    '''\n    f = lambda x : np.cos(x)\n    df = lambda x: -1*np.sin(x)\n    iter1 = Newtons_method(f,1,df,tol=.00001)\n    iter2 = Newtons_method(f,2,df,tol=.00001)\n    return iter1[2],iter2[2]\n\n# Problem 2.2: Implement this function.\ndef problemTwoTwo():\n    '''\n    Plot f(x) = sin(x)/x - x on [-4,4].  Return the zero of this function to\n    7 digits of accuracy.\n    '''\n    f = lambda x : (1.*np.sin(x))/x - x\n    df = lambda x : -1*(x**2+np.sin(x)-x*np.cos(x))/(x**2)\n    x = np.linspace(-4,4,num=100)\n    plt.plot(x,f(x))\n    plt.show()\n    xnew,converged,numiters = Newtons_method(f,1,df,tol = .0000001)\n    return xnew\n\n# Problem 2.3: Implement this function.\ndef problemTwoThree():\n    '''\n    Return a tuple of\n    1. The number of iterations to get five digits of accuracy for f(x) = x^9\n        with x_0 = 1.\n    2. A string with the reason to why you think the convergence is slow for \n        this function.\n    '''\n    f = lambda x : x**9\n    df = lambda x : 9*x**8\n    xnew,converged,numiters = Newtons_method(f,1,df,iters=3000,tol=1e-5)\n    return numiters,\"The derivative is very close to zero so it will converge slowly\"\n    \n\n# Problem 2.4: Implement this function.\ndef problemTwoFour():\n    '''\n    Return a string as to what happens and why for the function f(x) = x^(1/3) where\n    x_0 = .01.\n    '''\n    f = lambda x: np.sign(x)*np.power(np.abs(x), 1./3)\n    df = lambda x :1./3./np.power(np.abs(x), 2./3)\n    xnew,converged,numiters = Newtons_method(f,.01,df)\n    return \"The values are getting further and further away from the correct value so it never converges.  Because the derivative at the root is infinity.\"\n\n# Problem 3 (Optional): Modify the function Newtons_method() to calculate the numerical\n# derivative of f using centered coefficients.\n\ndef Newtons_method_II(f, x0, Df=None, iters=15, tol=.002):\n    \n    if Df == None:\n        h = 1e-5\n        Df = lambda x: .5 * (f(x+h) - f(x-h))/h\n        \n    xold = x0\n    for numiters in range(1,iters+1):\n        xnew = xold-f(xold)*1./Df(xold)\n        if abs(xnew-xold)<tol:\n            return xnew,True,numiters\n        else:\n            xold = xnew\n    return xnew,False,numiters\n\n\n# Problem 4: Implement this function.\ndef plot_basins(f, Df, roots, xmin, xmax, ymin, ymax, numpoints=1000,iters=15, colormap='brg'):\n    '''\n    Plot the basins of attraction of f.\n    INPUTS:\n        f (function): Should represent a function from C to C.\n        Df (function): Should be the derivative of f.\n        roots (array): An array of the zeros of f.\n        xmin, xmax, ymin, ymax (float,float,float,float): Scalars that define the domain\n            for the plot.\n        numpoints (int): A scalar that determines the resolution of the plot. Defaults to 100.\n        iters (int): Number of times to iterate Newton's method. Defaults to 15.\n        colormap (str): A colormap to use in the plot. Defaults to 'brg'.\n    '''\n    xreal = np.linspace(xmin,xmax,numpoints)\n    ximag = np.linspace(ymin,ymax,numpoints)\n    Xreal,Ximag = np.meshgrid(xreal,ximag)\n    Xold = Xreal + 1j*Ximag\n    for numiters in xrange(iters):\n        x = Xold - 1.* f(Xold)/Df(Xold)\n        Xold = x\n\n    convergedarray = np.zeros(Xold.shape)\n    for i in range(Xold.shape[0]):\n        for j in range(Xold.shape[1]):\n            convergedarray[i,j] = np.abs(roots-x[i,j]).argmin()\n    plt.pcolormesh(Xreal,Ximag,convergedarray,cmap=colormap)\n    plt.show()\n    \n\n# Problem 5: Implement this function.\ndef problemFive():\n    '''\n    Run plot_basins() on the function x^3-1 on the domain [-1.5,1.5]x[-1.5,1.5].\n    '''\n    f = lambda x : x**3 - 1\n    Df = lambda x : 3*x**2\n    roots = np.array([1,-1j**(1./3),1j**(2./3)])\n    xmin = -1.5\n    xmax = 1.5\n    ymin = -1.5\n    ymax = 1.5\n    plot_basins(f,Df,roots,xmin,xmax,ymin,ymax)\n\ndef testing():\n    f = lambda x : x**3-x\n    Df = lambda x : 3*x**2 - 1\n    roots = np.array([0,1,-1])\n    xmin = -1.5\n    xmax = 1.5\n    ymin = -1.5\n    ymax = 1.5\n    plot_basins(f,Df,roots, xmin,xmax,ymin,ymax)\n\nif __name__ == '__main__':\n    print problemTwoOne()\n    print problemTwoTwo()\n    print problemTwoThree()\n    print problemTwoFour()\n    print problemFive()\n    print testing()", "meta": {"hexsha": "255adb52c2925c08b72cf8d9c7321acd65947929", "size": 5573, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol1B/NewtonsMethod/solutionsFull.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vol1B/NewtonsMethod/solutionsFull.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vol1B/NewtonsMethod/solutionsFull.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 33.5722891566, "max_line_length": 155, "alphanum_fraction": 0.6158263054, "include": true, "reason": "import numpy", "num_tokens": 1683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436405, "lm_q2_score": 0.8991213806488609, "lm_q1q2_score": 0.8589478583120316}}
{"text": "\nimport scipy.linalg\nimport numpy as np\nfrom numba import jit\n\n@jit\ndef sym_decorrelation_jit(W):\n    \"\"\" Symmetric decorrelation \"\"\"\n    K = np.dot(W, W.T)\n    s, u = np.linalg.eigh(K) \n    W = (u @ np.diag(1.0/np.sqrt(s)) @ u.T) @ W\n    return W\n\ndef g_logcosh_jit(wx,alpha):\n    \"\"\"derivatives of logcosh\"\"\"\n    return np.tanh(alpha * wx)\ndef gprime_logcosh_jit(wx,alpha):\n    \"\"\"second derivatives of logcosh\"\"\"\n    return alpha * (1-np.square(np.tanh(alpha*wx)))\n# exp\ndef g_exp_jit(wx,alpha):\n    \"\"\"derivatives of exp\"\"\"\n    return wx * np.exp(-np.square(wx)/2)\ndef gprime_exp_jit(wx,alpha):\n    \"\"\"second derivatives of exp\"\"\"\n    return (1-np.square(wx)) * np.exp(-np.square(wx)/2)\n\n\ndef fastICA_jit(X, f,alpha=None,n_comp=None,maxit=200, tol=1e-04):\n    \"\"\"FastICA algorithm for several units\"\"\"\n    n,p = X.shape\n    #check if n_comp is valid\n    if n_comp is None:\n        n_comp = min(n,p)\n    elif n_comp > min(n,p):\n        print(\"n_comp is too large\")\n        n_comp = min(n,p)\n       \n    #centering\n    #by subtracting the mean of each column of X (array).\n    X = X - X.mean(axis=0)[None,:]\n    X = X.T\n \n    #whitening\n    s = np.linalg.svd(X @ (X.T) / n)\n    D = np.diag(1/np.sqrt(s[1]))\n    k = D @ (s[0].T)\n    k = k[:n_comp,:]\n    X1 = k @ X\n   \n    # initial random weght vector\n    w_init = np.random.normal(size=(n_comp, n_comp))\n    W = sym_decorrelation_jit(w_init)\n \n    lim = 1\n    it = 0\n   \n    # The FastICA algorithm\n    while lim > tol and it < maxit :\n        wx = W @ X1\n        if f ==\"logcosh\":\n            gwx = g_logcosh_jit(wx,alpha)\n            g_wx = gprime_logcosh_jit(wx,alpha)\n        elif f ==\"exp\":\n            gwx = g_exp_jit(wx,alpha)\n            g_wx = gprimeg_exp_jit(wx,alpha)\n        else:\n            print(\"doesn't support this approximation negentropy function\")\n        W1 = np.dot(gwx,X1.T)/X1.shape[1] - np.dot(np.diag(g_wx.mean(axis=1)),W)\n        W1 = sym_decorrelation_jit(W1)\n        it = it +1\n        lim = np.max(np.abs(np.abs(np.diag(W1 @ W.T))) - 1.0)\n        W = W1\n \n    S = W @ X1\n    A = scipy.linalg.pinv2(W @ k)   \n    return{'X':X1.T,'A':A.T,'S':S.T}", "meta": {"hexsha": "4af09cf6e84d6b1ef2e2c71ef4fb581be93b249f", "size": 2128, "ext": "py", "lang": "Python", "max_stars_repo_path": "Source/fastICA_jit.py", "max_stars_repo_name": "Liwen-ZHANG/fastica_lz", "max_stars_repo_head_hexsha": "68b33d37b96f63265fbd5f179d9b633cb76342f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-05-01T10:28:10.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-01T10:28:10.000Z", "max_issues_repo_path": "Source/fastICA_jit.py", "max_issues_repo_name": "Liwen-ZHANG/fastica_lz", "max_issues_repo_head_hexsha": "68b33d37b96f63265fbd5f179d9b633cb76342f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/fastICA_jit.py", "max_forks_repo_name": "Liwen-ZHANG/fastica_lz", "max_forks_repo_head_hexsha": "68b33d37b96f63265fbd5f179d9b633cb76342f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6363636364, "max_line_length": 80, "alphanum_fraction": 0.5676691729, "include": true, "reason": "import numpy,import scipy,from numba", "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110589, "lm_q2_score": 0.8991213820004279, "lm_q1q2_score": 0.8589478527405922}}
{"text": "\"\"\"\nFEniCS tutorial demo program: Poisson equation with Dirichlet conditions.\nTest problem is chosen to give an exact solution at all nodes of the mesh.\n\n  -Laplace(u) = f    in the unit square\n            u = u_D  on the boundary\n\n  u_D = 1 + x^2 + 2y^2\n    f = -6\n\"\"\"\n#%%\nfrom __future__ import print_function\nfrom fenics import *\n\n# Create mesh and define function space\nmesh = UnitSquareMesh(8, 8)\nV = FunctionSpace(mesh, 'P', 1)\n\n# Define boundary condition\nu_D = Expression('1 + x[0]*x[0] + 2*x[1]*x[1]', degree=2)\n\ndef boundary(x, on_boundary):\n    return on_boundary\n\nbc = DirichletBC(V, u_D, boundary)\n\n# Define variational problem\nu = TrialFunction(V)\nv = TestFunction(V)\nf = Constant(-6.0)\na = dot(grad(u), grad(v))*dx\nL = f*v*dx\n\n# Compute solution\nu = Function(V)\nsolve(a == L, u, bc)\n\n# Plot solution and mesh\nplot(u)\nplot(mesh)\n\n# Save solution to file in VTK format\nvtkfile = File('poisson/solution.pvd')\nvtkfile << u\n\n# Compute error in L2 norm\nerror_L2 = errornorm(u_D, u, 'L2')\n\n# Compute maximum error at vertices\nvertex_values_u_D = u_D.compute_vertex_values(mesh)\nvertex_values_u = u.compute_vertex_values(mesh)\nimport numpy as np\nerror_max = np.max(np.abs(vertex_values_u_D - vertex_values_u))\n\n# Print errors\nprint('error_L2  =', error_L2)\nprint('error_max =', error_max)\n\n# Hold plot\n#interactive()\n", "meta": {"hexsha": "c309c298956eb4115faffcda3bd2af76d9083c0e", "size": 1324, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/Tutorial_ft01_poisson.py", "max_stars_repo_name": "stevengogogo/ProgrammableAging", "max_stars_repo_head_hexsha": "91fcd1c988f6e00959dee3d435f0f141c6076349", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-07T12:00:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-07T12:00:59.000Z", "max_issues_repo_path": "tutorials/Tutorial_ft01_poisson.py", "max_issues_repo_name": "stevengogogo/ProgrammableAging", "max_issues_repo_head_hexsha": "91fcd1c988f6e00959dee3d435f0f141c6076349", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/Tutorial_ft01_poisson.py", "max_forks_repo_name": "stevengogogo/ProgrammableAging", "max_forks_repo_head_hexsha": "91fcd1c988f6e00959dee3d435f0f141c6076349", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7049180328, "max_line_length": 74, "alphanum_fraction": 0.7024169184, "include": true, "reason": "import numpy", "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9615338079816756, "lm_q2_score": 0.8933094053442511, "lm_q1q2_score": 0.858947194226504}}
{"text": "# Given two data sets with test scores vs hours of study\r\n# We can run a linear regression to predict test score for a given hour and see the graph\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# the checkError method goes over the list of data once and returns a sum of errors\r\ndef checkError(x, y, theta):\r\n    N = len(x)\r\n    y_hat = np.zeros(N)\r\n    sumError = 0\r\n    for i in range(0, N):\r\n        y_hat[i] = theta[0] + theta[1] * x[i]\r\n        sumError += (y_hat[i] - y[i]) **2\r\n    return y_hat, theta, sumError\r\n\r\n# the tain method goes over the list of data, finds error and runs gradient descent for correction of error\r\ndef train(iterCount, learn_rate, x, y):\r\n    theta = np.zeros(2)\r\n    N = len(x)\r\n    y_hat = np.zeros(N)\r\n    for c in range(0, iterCount):\r\n        sumError = 0\r\n        for i in range(0, N):\r\n            y_hat[i] = theta[0] + theta[1] * x[i]\r\n            sumError += (y_hat[i] - y[i]) **2\r\n        theta = gradientDescent(x, y, theta, learn_rate)\r\n    return y_hat, theta, sumError\r\n\r\n# gradientDescent method adjusts theta parameters and returns a rectified theta\r\ndef gradientDescent(x, y, theta, l_rate):\r\n    M = len(x)\r\n    y_hat = np.zeros(M)\r\n    for i in range(0, M):\r\n        y_hat[i] = theta[0] + theta[1] * x[i]\r\n        theta[0] = theta[0] - (l_rate * (1/M) * (y_hat[i] - y[i]))\r\n        theta[1] = theta[1] - (l_rate * (1/M) * (y_hat[i] - y[i]) * x[i])\r\n    return theta\r\n\r\n# predict method predicts a y values for a given x value and rectified theta parameters\r\ndef predict(x, theta):\r\n    print(\"Theta used for prediction: \", theta)\r\n    y = theta[0] + theta[1] * x\r\n    return y\r\n\r\n# readData method reads data from file in columns and loads the columns in x and y data arrays\r\ndef readData(file_name, delim=','):\r\n    points = np.genfromtxt(file_name, delimiter=delim)\r\n    y = points[:,0]\r\n    x = points[:,1]\r\n    return x, y\r\n\r\n# main method runs the steps of linear regression in sequence \r\ndef main():\r\n    #train model on data\r\n    iterCount = 100\r\n    learn_rate = 0.0001\r\n\r\n    # test scores are loaded in y while hours of study are loaded in x\r\n    y, x = readData(\"input/test_score_vs_hour_studied.csv\")\r\n    theta = np.zeros(2)\r\n\r\n    print(\"Initial theta: \", theta)\r\n    \r\n    y_hat, theta, err = checkError(x, y, theta)\r\n    print(\"Initial Error: {0}  theta: [{1}, {2}]\".format(err, theta[0], theta[1]))\r\n    \r\n    y_hat, theta, err = train(iterCount, learn_rate, x, y)\r\n    print(\"Afer {0} iterations, Error: {1}  theta: [{2}, {3}]\".format(iterCount, err, theta[0], theta[1]))\r\n    \r\n    # plot actual values of x and y\r\n    plt.subplot(1,2,1)\r\n    plt.scatter(x, y)\r\n    plt.xlabel('x')\r\n    plt.ylabel('y')\r\n\r\n    # plot actual values of x against predicted values of y\r\n    plt.subplot(1,2,2)\r\n    plt.scatter(x, y_hat)\r\n    plt.plot(x, y_hat)\r\n    plt.xlabel('x')\r\n    plt.ylabel('y_hat')\r\n    plt.show()\r\n\r\n    print(predict(53, theta))\r\n\r\n\r\nif True:\r\n    main()\r\n", "meta": {"hexsha": "a2bd5331ba8a24656ab508a5a66a4d234c659f35", "size": 2946, "ext": "py", "lang": "Python", "max_stars_repo_path": "UniLinReg.py", "max_stars_repo_name": "psengupta1973/machine_learning_py", "max_stars_repo_head_hexsha": "98dfda55693353e641ed150b66fcab8170593c8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-06T09:18:10.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-06T09:18:10.000Z", "max_issues_repo_path": "UniLinReg.py", "max_issues_repo_name": "psengupta1973/MachineLearning_py", "max_issues_repo_head_hexsha": "98dfda55693353e641ed150b66fcab8170593c8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UniLinReg.py", "max_forks_repo_name": "psengupta1973/MachineLearning_py", "max_forks_repo_head_hexsha": "98dfda55693353e641ed150b66fcab8170593c8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7333333333, "max_line_length": 108, "alphanum_fraction": 0.6028513238, "include": true, "reason": "import numpy", "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338057771059, "lm_q2_score": 0.8933094010836642, "lm_q1q2_score": 0.8589471881604428}}
{"text": "# Problem: https://projecteuler.net/problem=286\n\n\"\"\"\n    . At each distance x, there are two possibilities:\n        1. P(scoring at distance x) = 1 - x/q\n        2. P(not scoring at distance x) = x/q\n    . We can use dynamic programming/memoization to calculate the probability of scoring exactly 20 points:\n        DP[x][j] = DP[x-1][j-1] * (1 - x/q) + DP[x-1][j] * x/q\n        where DP[x][j] -> the number of ways of scoring exactly j points after trying to score at distances from 1 to x.\n    OR we can find a close form function of calculating the probability of scoring exactly 20 points:\n        Let f(q) = product_{k from 1 to 50} [k/q + (1-k/q) * x]\n                 = (1/q + (1-1/q) * x) * (2/q + (1-2/q) * x) * ... * (50/q + (1-50/q) * x)\n        Then the probability of scoring exactly 20 points is the coefficient of x^20.\n        For simplicity, let p = 1/q.\n    . Either way, we use binary search to find q within (50, +inf)  (or p in (0, 50)) such that the probability = 0.02\n\"\"\"\n\nfrom sage.all import *\nfrom decimal import *\n\ngetcontext().prec = 12\n\nN = 50\n\n\nif __name__ == \"__main__\":\n    var('x')\n    var('p')\n\n    f = 1\n    for i in range(1, N+1):\n        f = f * (i*p + (1-i*p)*x)\n    \n    g = f.expand()\n    h = g.coefficient(x**20)\n\n    target = 0.02\n    lowerbound = Rational('0')       # switch to Rational() for higher precision\n    upperbound = Rational('1/50')\n    count = 0                        # count the number of time we have the correct value\n    stop_threshold = 50              # this is the stopping criteria\n                                     # if the count of the number of time we have the correct value is higher than stop_threshold, the algorithm will stop\n    tol = 10**-12                    # the algorithm will see values in [target-tol, target+tol] to be the same as target\n\n    # binary search for p\n    while True:\n        m = (lowerbound + upperbound) / 2\n        new_val = h(p=m)\n        if abs(new_val - target) < tol:\n            count = count + 1\n            if count == stop_threshold:\n                break\n        else:\n            count = 0\n        # this is a monotically increasing polynomial for p in [0, 1/50]\n        # so we'll move the upperbound to the middle if the current value is bigger than the target value\n        if new_val > target:\n            upperbound = m\n        else:\n            lowerbound = m\n    q = float(1/m)\n\n    print(\"{:.10f}\".format(q))", "meta": {"hexsha": "1114c629114c644ff324fa50b5bda0000a5abf3b", "size": 2428, "ext": "py", "lang": "Python", "max_stars_repo_path": "3rd_100/problem286.py", "max_stars_repo_name": "takekoputa/project-euler", "max_stars_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3rd_100/problem286.py", "max_issues_repo_name": "takekoputa/project-euler", "max_issues_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rd_100/problem286.py", "max_forks_repo_name": "takekoputa/project-euler", "max_forks_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-02T12:08:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T12:08:46.000Z", "avg_line_length": 38.5396825397, "max_line_length": 154, "alphanum_fraction": 0.5679571664, "include": true, "reason": "from sage", "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.9241418283357703, "lm_q1q2_score": 0.8589347504962073}}
{"text": "# Question: https://projecteuler.net/problem=239\n\n\"\"\"\n . There are 25 primes between 1 and 100. So, if we want exactly 22 primes displaced, there are always 3 primes that are in the correct places.\n . The number of arrangements having exactly 3 primes at their correct place is,\n    C(25, 3) * n_derangements\n  where C(25, 3) is the number of ways of choosing 3 primes to be fixed in their correct positions,\n    and n_derangements is the number of ways of constructing an arrangments of the other 97 numbers such that, none of each of the other 22 primes would be at its correct place. (we don't care about non-primes)\n . To find n_derangements, we use the inclusion-exclusion principle.\n . Let F(m) be number of arrangments that at least m primes would be at correct positions.\n     F(m) = C(22, m) * factorial(97-m)\n   where C(22, m) is the number of ways of choosing m primes to be fixed at their correct positions,\n     and factorial(97-m) is the number of ways of arranging the other 97-m numbers.\n . We have, n_derangements = F(0) - F(1) + F(2) - ... (Principle of inclusion and exclusion)\n\"\"\"\n\nfrom sage.all import *\n\nN = 100\nN_PRIMES = len(prime_range(N))\nN_DISPLACED_PRIMES = 22\nN_FIXED_PRIMES = N_PRIMES - N_DISPLACED_PRIMES\n\nif __name__ == \"__main__\":\n    ans = binomial(N_PRIMES, N_FIXED_PRIMES)\n\n    # Principle of inclusion and exclusion\n    n_remaining_positions = N - N_FIXED_PRIMES\n    n_derangements = 0 # number of ways of rearranging the other 97 numbers so that none of the displaced primes are in their correct position.\n    for k in range(N_DISPLACED_PRIMES + 1):\n        n_ways_having_at_least_k_primes_inplaced = factorial(n_remaining_positions - k) # fix the k primes, place other numbers randomly\n        n_tuples_of_k_primes = binomial(22, k)\n        if k % 2 == 1:\n            n_derangements -= n_ways_having_at_least_k_primes_inplaced * n_tuples_of_k_primes\n        else:\n            n_derangements += n_ways_having_at_least_k_primes_inplaced * n_tuples_of_k_primes\n\n    ans *= n_derangements\n\n    ans = ans / factorial(N)\n\n    print(float(ans))\n", "meta": {"hexsha": "a97f738ded456274950a5f9acf124acff01a64d7", "size": 2077, "ext": "py", "lang": "Python", "max_stars_repo_path": "3rd_100/problem239.py", "max_stars_repo_name": "takekoputa/project-euler", "max_stars_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3rd_100/problem239.py", "max_issues_repo_name": "takekoputa/project-euler", "max_issues_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rd_100/problem239.py", "max_forks_repo_name": "takekoputa/project-euler", "max_forks_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-02T12:08:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T12:08:46.000Z", "avg_line_length": 48.3023255814, "max_line_length": 210, "alphanum_fraction": 0.7284545017, "include": true, "reason": "from sage", "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104914476339, "lm_q2_score": 0.8887588045416601, "lm_q1q2_score": 0.8589058330755174}}
{"text": "# activation.py\n'''\nAll the most common activations, along with their prime.\nUse the function get_activation to pass the activation-type as text\nand get the activation and prime back.\n'''\n\n# Things to fix\n'''\nNothing yet.\n'''\n\n# Importing dependencies\nimport numpy as np\n\n# Activations\ndef sigmoid(X, act_clip=100):\n    X = np.clip(X, -act_clip, act_clip)\n    return np.divide(1,np.add(1,np.exp(-X)))\ndef sigmoid_prime(X, act_clip=100):\n    X = np.clip(X, -act_clip, act_clip)\n    return sigmoid(X)*(1-sigmoid(X))\ndef ReLU(X):\n    return np.maximum(X, 0, X)\ndef ReLU_prime(X):\n    return 1 * (X > -1e-05)\ndef tanh(X, act_clip=100):\n    X = np.clip(X, -act_clip, act_clip)\n    return np.tanh(X)\ndef tanh_prime(X, act_clip=100):\n    X = np.clip(X, -act_clip, act_clip)\n    return 1/(np.square(np.cosh(X)))\ndef arctan(X):\n    return np.arctan(X)\ndef arctan_prime(X):\n    return 1/(np.power(X,2)+1.)\ndef sine(X):\n    return np.sin(X)\ndef sine_prime(X):\n    return np.cos(X)\ndef getActivation(act='tanh'):\n    if act.lower() == 'sigmoid': return sigmoid, sigmoid_prime\n    if act.lower() == 'relu': return ReLU, ReLU_prime\n    if act.lower() == 'tanh': return tanh, tanh_prime\n    if act.lower() == 'arctan': return arctan, arctan_prime\n    if act.lower() == 'sine': return sine, sine_prime\n", "meta": {"hexsha": "df8044527dd418749433806785c0c8ed8c473266", "size": 1286, "ext": "py", "lang": "Python", "max_stars_repo_path": "neural_net/necessities/activation.py", "max_stars_repo_name": "mariusbrataas/pistachio", "max_stars_repo_head_hexsha": "7e0fbba04aa8b5d61e304384898be69a66cc0d15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-27T09:32:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T17:53:28.000Z", "max_issues_repo_path": "neural_net/necessities/activation.py", "max_issues_repo_name": "mariusbrataas/pistachio", "max_issues_repo_head_hexsha": "7e0fbba04aa8b5d61e304384898be69a66cc0d15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neural_net/necessities/activation.py", "max_forks_repo_name": "mariusbrataas/pistachio", "max_forks_repo_head_hexsha": "7e0fbba04aa8b5d61e304384898be69a66cc0d15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3617021277, "max_line_length": 67, "alphanum_fraction": 0.6632970451, "include": true, "reason": "import numpy", "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104904802131, "lm_q2_score": 0.8887588038050466, "lm_q1q2_score": 0.8589058315038426}}
{"text": "\"\"\"\nA fact that I like is that base-exp(1) is the most efficient base for encoding\nin terms of the number of total distinct states you have to have access to.\n\nTo see this, we simply consider the number of nodes in a tree with branching\nfactor b needed to encode all states at the leaves.\n\nReferences:\n    https://en.m.wikipedia.org/wiki/Radix_economy\n    https://en.wikipedia.org/wiki/Ternary_computer\n    https://en.wikipedia.org/wiki/Decimal_computer\n\"\"\"\nimport numpy as np\nimport kwplot\nimport pandas as pd\n\n# amount_of_information = np.arange(10)\n\namount_of_information = 1_000_000  # we have 1_000_000 bits\n\n\nbase = np.arange(2, 16)\n\nmin_base = 2\nmax_base = 16\nbase = np.linspace(min_base, max_base, min(100, min_base * (max_base - 2) + 1)).round()\nbase = np.unique(np.hstack([base, [0.1, 0.2, 0.3, 0.5, 0.8, 0.9, 1.1, 1.5, 1.9, 2.0, 3.0, 8, 10, 16, np.exp(1), np.pi, np.pi * 2]]))\n# It doesn't make much sense to have a base < 2, and the analysis of the\n# function in this case is out of scope of this tutorial\nbase = base[base >= 2]\nbase.sort()\n\n# First let's consider the integer case (as that is what we can actually\n# realize with bits)\ndf = pd.DataFrame({'base': base})\ndf['tree_height'] = np.log(amount_of_information) / np.log(df['base'])\ndf['number_of_nodes'] = df['tree_height'] * df['base']\n\n\nsns = kwplot.autosns()\nax = sns.lineplot(data=df, x='base', y='number_of_nodes', marker='o')\nax.set_title('Nodes in a decision tree with base-b')\n", "meta": {"hexsha": "7a51d1ab2bc423fea483bb662ade45ae1541b74d", "size": 1456, "ext": "py", "lang": "Python", "max_stars_repo_path": "learn/efficiency_of_base_encodings.py", "max_stars_repo_name": "Erotemic/misc", "max_stars_repo_head_hexsha": "6f8460a690d05e7e0117becc6cae9902cbe2cedd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-04-29T21:07:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T08:46:08.000Z", "max_issues_repo_path": "learn/efficiency_of_base_encodings.py", "max_issues_repo_name": "Erotemic/misc", "max_issues_repo_head_hexsha": "6f8460a690d05e7e0117becc6cae9902cbe2cedd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "learn/efficiency_of_base_encodings.py", "max_forks_repo_name": "Erotemic/misc", "max_forks_repo_head_hexsha": "6f8460a690d05e7e0117becc6cae9902cbe2cedd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-04-07T12:26:21.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-07T12:26:21.000Z", "avg_line_length": 33.8604651163, "max_line_length": 132, "alphanum_fraction": 0.706043956, "include": true, "reason": "import numpy", "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639686018701, "lm_q2_score": 0.8840392909114836, "lm_q1q2_score": 0.8589007218779442}}
{"text": "from math import sqrt, exp, log, sin, pi\nfrom sympy import Symbol, Limit, Derivative, solve, sympify, S, simplify, lambdify, pprint, init_printing, symbols\nfrom fractions import Fraction\n\ninit_printing( order = 'rev-lex', use_unicode = True )\n\n# 4.2.1\n\n# Suppose f (x) = (4x 3 + 3) (1 − x 2 ). \n# What is the equation of the line tangent to f at the point (1, 0)?\n\nx0 = 1\ny0 = 0\n\nFx = ( 4*x**3 + 3 ) * ( 1 - x ** 2 )\nx = Symbol( 'x' )\nDx = Derivative( Fx, x ).doit()\n\nm = Dx.subs( { x: x0 } )\nx1 = Fx.subs( { x: x0 } )\n\n# 4.2.2\n\n# Suppose f (x) = (x 2 − 2x) (3x + 2).\n# What is the equation of the line normal to f\n# (i.e., the line perpendicular to the tangent line)\n# at the point (1, −5)?\n\nx0 = 1\ny0 = -5\n\nFx = ( x ** 2 - 2*x ) * ( 3*x + 2 )\nx = Symbol( 'x' )\nDx = Derivative( Fx, x ).doit()\n\nm = Dx.subs( { x: x0 } )\nm1 = -1/m\n\n# Line\ny = m1 * ( x - x0 ) + y0\n\n# 4.2.3\n\n# Find the derivative: f(x) = ( x -2 ) / x^2\n\nFx = ( x - 2 ) / x ** 2\nx = Symbol( 'x' )\nDerivative( Fx, x ).doit()\n\n# 4.2.4\n\n# Find the derivative: f(x) = x^2 + 1 / x + 1\n\nFx = ( x ** 2 + 1 ) / ( x + 1 )\nx = Symbol( 'x' )\nDerivative( Fx, x ).doit()\n\n# 4.2.5\n\n# Find the derivative:\n# v(x) =  ( x + 2 ) ^ 1/2 / ( x - 3 ) ^ 1/3\n\nVx = ( ( x + 2 ) ** 1/2 ) / ( ( x - 3 ) ** 1/3 )\nx = Symbol( 'x' )\nDerivative( Vx, x ).doit()\n\n# 4.2.6\n\n# Find the derivative:\n# f(x) = ( x + 2 ) ^ 4/3 / 2x\nFx = ( x + 2 ) ** 4/3 / 2*x\nx = Symbol( 'x' )\nDerivative( Fx, x ).doit()\n\n# 4.2.7\n\n# Find the derivative:\n# h(x) = ( 2*x**4 + 3*x + 7 ) * ( x**5 - 3*x**2 )\nFx = ( 2*x**4 + 3*x + 7 ) * ( x**5 - 3*x**2 )\nx = Symbol( 'x' )\nDerivative( Fx, x ).doit()\n\n# 4.2.8\n\n# Suppose f (x) = (3x − x 2 ) (2x − x 2 ). \n# Find the equation of the line tangent to f at the point (1, 2).\n\nx0 = 1\ny0 = 2\n\nFx = ( 3 * x - x**2 ) * ( 2 * x - x**2 )\nx = Symbol( 'x' )\nDx = Derivative( Fx, x ).doit()\n\nm = Dx.subs( { x: x0 } )\n\n# Line\ny = m1 * ( x - x0 ) + y0\n\n# 4.2.9\n\n# Find the derivative:\n# f(x) = ( t + 3 ) ** 1/2 / ( t - 3 ) ** 3/2\nFx = ( t + 3 ) ** 1/2 / ( t - 3 ) ** 3/2\nx = Symbol( 'x' )\nDerivative( Fx, x ).doit()\n", "meta": {"hexsha": "e2bc3d4512c59d9b60fc8a917099ecdd7ddae447", "size": 2055, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Mathematics/Calculus/Differential/ch_04/4.2.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Mathematics/Calculus/Differential/ch_04/4.2.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Mathematics/Calculus/Differential/ch_04/4.2.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2056074766, "max_line_length": 114, "alphanum_fraction": 0.4851581509, "include": true, "reason": "from sympy", "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971563964485063, "lm_q2_score": 0.8840392924390587, "lm_q1q2_score": 0.8589007197226618}}
{"text": "from typing import Union\n\nimport numpy as np\nimport numpy.linalg\nimport scipy.linalg\n\n\ndef norm(A: np.ndarray,\n         p: Union[int, str]) -> float:\n    \"\"\"\n    Calculates the induced p-norm of matrix A.\n\n    :param A: matrix to calculate the norm for\n    :param p: either the number for L1, L2, ..., Lp norm or \"inf\" string for\n    the infinity norm\n    :return: p-norm of matrix A\n    \"\"\"\n    A = A.astype(np.float)\n\n    if p == 1:\n        return np.max(np.sum(np.abs(A), axis=0))\n    elif p == \"inf\":\n        return np.max(np.sum(np.abs(A), axis=1))\n\n    xs = np.random.randn(A.shape[0], 1000)\n\n    # compute the norms and normalized A\n    norm_xs = np.sum(np.abs(xs) ** p, axis=0) ** (1 / p)\n    normalized_xs = xs / norm_xs\n\n    # apply A to normalized vectors, i.e. calculate Ax\n    Ax = A.dot(normalized_xs)\n\n    # compute norms of Ax vectors\n    norm_Ax = np.sum(np.abs(Ax) ** p, axis=0) ** (1 / p)\n\n    # get the highest norm\n    p_norm = np.max(norm_Ax)\n\n    return p_norm\n\n\nif __name__ == '__main__':\n    A = np.array([[1, 2],\n                  [3, 4]])\n\n    print(\"My:\", norm(A, 1), \", library:\", np.linalg.norm(A, ord=1))\n    print(\"My:\", norm(A, 2), \", library:\", np.linalg.norm(A, ord=2))\n    print(\"My:\", norm(A, \"inf\"), \", library:\", np.linalg.norm(A, ord=np.inf))\n", "meta": {"hexsha": "954b947570b24750f42a6c08395129f91c3533bd", "size": 1283, "ext": "py", "lang": "Python", "max_stars_repo_path": "matrix_norms.py", "max_stars_repo_name": "j-adamczyk/Matrix_algorithms", "max_stars_repo_head_hexsha": "2b06b4cfd741919724b2e88eb17da35909341ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-13T13:06:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-13T13:06:32.000Z", "max_issues_repo_path": "matrix_norms.py", "max_issues_repo_name": "j-adamczyk/Matrix_algorithms", "max_issues_repo_head_hexsha": "2b06b4cfd741919724b2e88eb17da35909341ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matrix_norms.py", "max_forks_repo_name": "j-adamczyk/Matrix_algorithms", "max_forks_repo_head_hexsha": "2b06b4cfd741919724b2e88eb17da35909341ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-10T17:33:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T17:33:49.000Z", "avg_line_length": 25.66, "max_line_length": 77, "alphanum_fraction": 0.5767731878, "include": true, "reason": "import numpy,import scipy", "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639686018701, "lm_q2_score": 0.884039278690883, "lm_q1q2_score": 0.8589007100048489}}
{"text": "import numpy as np\n\nimport matplotlib.pyplot as plt\n\ndef calc_pca(data, samples, classes=None):\n    exit = []\n    previous = []\n    mean = np.mean(data, axis = 0)\n    mean_sub = data - mean\n    cov = np.cov(mean_sub, rowvar = 0)\n    eigen_values, eigen_vectors = np.linalg.eig(np.mat(cov))\n    eigen_values_sorted = np.argsort(-eigen_values)\n    for num_eigen in samples:\n        eigen_values_filtered = eigen_values_sorted[:num_eigen]\n        eigen_vectors_filtered = eigen_vectors[:,eigen_values_filtered]\n        data_matrix = mean_sub * eigen_vectors_filtered\n        reconstructed = (data_matrix * eigen_vectors_filtered.T) + mean\n        exit.append((num_eigen, reconstructed.real, eigen_vectors_filtered.T.real))\n        if classes is not None:\n            for i in classes:\n                mean_class = np.mean(classes[i], axis = 0)\n                mean_sub_class = classes[i] - mean_class\n                data_matrix_class = mean_sub_class * eigen_vectors_filtered\n                reconstructed_class = (data_matrix_class * eigen_vectors_filtered.T) + mean_class\n                exit.append((num_eigen, reconstructed_class.real, None))\n    return exit\n\ndef print_pca(data):\n    for row in data:\n        for j in range(row[0]):\n            plt.subplot(5,4,j+1)\n            reshaped = np.array(row[1][j]).reshape(28,28)\n            plt.imshow(reshaped, cmap='gray')\n            plt.axis('off')\n        plt.show()\n        if row[2] is not None:\n            for j in range(row[0]):\n                plt.subplot(5,4,j+1)\n                reshaped = np.array(row[2][j]).reshape(28,28)\n                plt.imshow(reshaped, cmap='gray')\n                plt.axis('off')\n            plt.show()\n\n\ndef read_data(filename):\n    with open(filename, 'r') as f:\n        lines = f.readlines()\n\n    num_points = len(lines)\n    dim_points = 28 * 28\n    data = np.empty((num_points, dim_points))\n    labels = np.empty(num_points)\n\n    for ind, line in enumerate(lines):\n        num = line.split(',')\n        labels[ind] = int(num[0])\n        data[ind] = [ int(x) for x in num[1:] ]\n\n    return (data, labels)\n\ntrain_images, train_labels = read_data(\"C:/Users/suagrawa/Desktop/Spring_2019_IIIT/Monsoon 2019/SMAI Assignments/Assignment-1/sample_train.csv\")\ntest_images, test_labels = read_data(\"C:/Users/suagrawa/Desktop/Spring_2019_IIIT/Monsoon 2019/SMAI Assignments/Assignment-1/sample_test.csv\")\n\nnum_classes = 10\nsamples = [2, 5, 10, 20]\nclasses = {}\nfor i in range(num_classes):\n    classes[i] = []\nfor i, image in enumerate(train_images):\n    classes[train_labels[i]].append(image)\nfor i in range(num_classes):\n    values = calc_pca(classes[i], samples)\n    print_pca(values)\nvalues = calc_pca(train_images, samples, classes)\nprint_pca(values)\n#one_of_each = {}\n#for i in classes:\n#\tone_of_each[i] = [classes[i][0]]\n#values = calc_pca(train_images, samples, one_of_each)\n#print_pca(values)", "meta": {"hexsha": "6e06ed7ea38fe099355f3298b328e743a08be772", "size": 2880, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignments_SMAI/ws.py", "max_stars_repo_name": "sum-coderepo/HadoopApp", "max_stars_repo_head_hexsha": "0e8d48c5d541b5935c9054fb1335d829d67d7b59", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-26T23:58:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-01T20:45:30.000Z", "max_issues_repo_path": "Assignments_SMAI/ws.py", "max_issues_repo_name": "sum-coderepo/HadoopApp", "max_issues_repo_head_hexsha": "0e8d48c5d541b5935c9054fb1335d829d67d7b59", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignments_SMAI/ws.py", "max_forks_repo_name": "sum-coderepo/HadoopApp", "max_forks_repo_head_hexsha": "0e8d48c5d541b5935c9054fb1335d829d67d7b59", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0, "max_line_length": 144, "alphanum_fraction": 0.6427083333, "include": true, "reason": "import numpy", "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971563964485063, "lm_q2_score": 0.8840392741081574, "lm_q1q2_score": 0.8589007019130187}}
{"text": "import sympy\nfrom sympy import *\nimport random\n\ndef choose_modulus(k,l,m):\n\tp1 = find_prime(k,l)\n\tp2 = find_prime(k,l)\n\t#while not (log(p1,2) + m < log(p2, 2)):\n\t#\tp1 = find_prime(k,l)\n\t#\tp2 = find_prime(k,l)\n\t#\tprint(p1, p2)\n\tprint(p1, p2)\n\tprint(log(p1,2)+m < log(p2,2))\n\treturn p1,p2\n\ndef choose_encryption_key_old(m):\n\te = random.randrange(2,m)\n\twhile not gcd(e, totient(m)) == 1:\n\t\te = random.randrange(2,m)\n\treturn e\n\ndef choose_encryption_key(p1,p2):\n\tm = p1*p2\n\te = random.randrange(2, p1*p2)\n\twhile not gcd(e, (p1-1)*(p2-1)) == 1:\n\t\te = random.randrange(2, p1*p2)\n\treturn e\n\ndef compute_decryption_key(e, p1, p2):\n\t# d = e inverse mod phi(m) m = p1*p2\n\t#phi(m) = (p1-1)*(p2-1)\n\td = inv_mod(e, (p1-1)*(p2-1))\n\treturn d\n\ndef RSA_encrypt(P, e, m):\n\treturn power_mod(P,e,m)\n\ndef RSA_decrypt(C, d, m):\n\treturn power_mod(C,d,m)\n\ndef RSA_crack(C, e, m):\n\treturn power_mod(C, inv_mod(e,totient(m)), m)\n\ndef power_mod(a, b, m):\n\t#replace with better version for large numbers\n\t#return ((a%m)**(b%m))%m\n\treturn pow(a,b,m)\n\ndef string_to_int(s):\n\treturn int.from_bytes(s.encode(),'big')\n\ndef int_to_string(n):\n\treturn n.to_bytes((n.bit_length()+7)//8,'big').decode()\n\ndef find_prime(k, l):\n\tx = random.randrange(2**k+2, 2**l-1)\n\twhile (not isprime(x)):\n\t\tx = random.randrange(2**k+2, 2**l-1)\n\treturn x\n\ndef mod_inv_old(a,m):\n\t#replace with euclid's algorithm - will be using large numbers\n\tfor i in range(0,m):\n\t\tif (i*a)%m == 1:\n\t\t\treturn i\n\treturn -1\n\ndef xgcd(b, n):\n    \"\"\" Return g, x0, y0\n        such that x0*b + y0*n = g\n        and g is the gcd of (b,n)\"\"\"\n    x0, x1, y0, y1 = 1, 0, 0, 1\n    while n != 0:\n        q, b, n = b // n, n, b % n\n        x0, x1 = x1, x0 - q * x1\n        y0, y1 = y1, y0 - q * y1\n    return b, x0, y0\n\n\ndef inv_mod(b, n):\n    \"\"\" Return the modular inverse of b mod n\n     or None if gcd(b,n) > 1 \"\"\"\n    g, x, _ = xgcd(b, n)\n    if g == 1:\n        return x % n", "meta": {"hexsha": "d58a858e2e6b6e99acb944dd3f59e5fad83a35ff", "size": 1896, "ext": "py", "lang": "Python", "max_stars_repo_path": "Cryptography/Extra Files/isabelleRSA.py", "max_stars_repo_name": "swethapraba/SeniorYearCSElectives", "max_stars_repo_head_hexsha": "67b989ffecd5cf7508258783b0ec26468cdf94fc", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cryptography/Extra Files/isabelleRSA.py", "max_issues_repo_name": "swethapraba/SeniorYearCSElectives", "max_issues_repo_head_hexsha": "67b989ffecd5cf7508258783b0ec26468cdf94fc", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cryptography/Extra Files/isabelleRSA.py", "max_forks_repo_name": "swethapraba/SeniorYearCSElectives", "max_forks_repo_head_hexsha": "67b989ffecd5cf7508258783b0ec26468cdf94fc", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3058823529, "max_line_length": 63, "alphanum_fraction": 0.5917721519, "include": true, "reason": "import sympy,from sympy", "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854120593483, "lm_q2_score": 0.8856314723088732, "lm_q1q2_score": 0.8588724823057879}}
{"text": "from numpy import *\n\ndef gaussian(x, amp=1, loc=0, width=1):\n  out_ = amp*exp(-(x-loc)**2/(2*width**2))\n  if isinstance(out_,ndarray):\n    out_[isnan(out_)] = 0\n  elif isnan(out_):\n    out_ = 0\n  return out_\n\ndef normalized_gaussian(x,loc=0,width=1):\n  amp = 1/(width*sqrt(2*pi))\n  return gaussian(x,amp=amp,loc=loc,width=width)\n\ndef IRF(x_,t_,celerity=1, loc=1,width=1):\n  i__ = empty([len(t_),len(x_)])\n  for i,t in enumerate(t_):\n    i__[i,:] = normalized_gaussian(x_,loc=loc + celerity*t,width=width)\n  return i__\n\ndef fundamental_solution(x_,t_,diffusivity=1,celerity=1):\n  out__ = empty([len(t_),len(x_)])\n  for i,t in enumerate(t_):\n    for j,x in enumerate(x_):\n      amp = x / (2*t*sqrt(pi*t*diffusivity))\n      loc = celerity*t\n      width = sqrt(2*diffusivity*t)\n      out__[i,j] = gaussian(x,amp=amp,loc=loc,width=width)\n  out__[0,:] = 0\n  return out__\n\ndef H(A, **kwargs):\n  '''Returns the conjugate (Hermitian) transpose of a matrix.'''\n  return transpose(A, **kwargs).conj()\n\ndef mdot(*args):\n  '''\n  Left-to-right associative matrix multiplication of multiple 2D ndarrays.\n  '''\n  try:\n    ret = args[0]\n    for a in args[1:]:\n      ret = dot(ret, a)\n  except:\n    raise\n  return ret\n", "meta": {"hexsha": "cfdbce9e0915f6b46986146a7ea658ae789bfe27", "size": 1200, "ext": "py", "lang": "Python", "max_stars_repo_path": "runoff_contaminant_model/common.py", "max_stars_repo_name": "anil-ganti/runoff_contaminant_model", "max_stars_repo_head_hexsha": "46dc13ebf14578e9ddc2b6d722ff84d86c5cdb4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "runoff_contaminant_model/common.py", "max_issues_repo_name": "anil-ganti/runoff_contaminant_model", "max_issues_repo_head_hexsha": "46dc13ebf14578e9ddc2b6d722ff84d86c5cdb4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "runoff_contaminant_model/common.py", "max_forks_repo_name": "anil-ganti/runoff_contaminant_model", "max_forks_repo_head_hexsha": "46dc13ebf14578e9ddc2b6d722ff84d86c5cdb4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5319148936, "max_line_length": 74, "alphanum_fraction": 0.6366666667, "include": true, "reason": "from numpy", "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969785409439575, "lm_q2_score": 0.885631470799559, "lm_q1q2_score": 0.8588724785219233}}
{"text": "# PACKAGE\n# Here are the imports again, just in case you need them.\n# There is no need to edit or submit this cell.\nimport numpy as np\nimport numpy.linalg as la\nfrom readonly.PageRankFunctions import *\nnp.set_printoptions(suppress=True)\n# GRADED FUNCTION\n# Complete this function to provide the PageRank for an arbitrarily sized internet.\n# I.e. the principal eigenvector of the damped system, using the power iteration method.\n# (Normalisation doesn't matter here)\n# The functions inputs are the linkMatrix, and d the damping parameter - as defined in this worksheet.\ndef pageRank(linkMatrix, d) :\n    n = linkMatrix.shape[0] \n    M = d * linkMatrix + ((1-d) / n) * np.ones([n, n]) \n    r = 100 * np.ones(n) / n \n    lastR = r\n    r = M @ r\n    i = 0\n    while la.norm(lastR - r) > 0.01 :\n        lastR = r\n        r = M @ r\n        i += 1\n    print(str(i) + \" iterations to convergence.\")\n    r\n    return r\n\n", "meta": {"hexsha": "dd78fb1363ff18a965c54698fe8a69d27af5ae89", "size": 911, "ext": "py", "lang": "Python", "max_stars_repo_path": "pagerank.py", "max_stars_repo_name": "MichelML/Mathematics-for-Machine-Learning-Linear-Algebra", "max_stars_repo_head_hexsha": "c0deedb024ffb0360328fa15473c989db317c9b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2018-04-29T10:27:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T15:15:44.000Z", "max_issues_repo_path": "pagerank.py", "max_issues_repo_name": "MichelML/Mathematics-for-Machine-Learning-Linear-Algebra", "max_issues_repo_head_hexsha": "c0deedb024ffb0360328fa15473c989db317c9b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-15T12:16:54.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-15T12:16:54.000Z", "max_forks_repo_path": "pagerank.py", "max_forks_repo_name": "MichelML/Mathematics-for-Machine-Learning-Linear-Algebra", "max_forks_repo_head_hexsha": "c0deedb024ffb0360328fa15473c989db317c9b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2018-07-21T15:42:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T14:34:04.000Z", "avg_line_length": 32.5357142857, "max_line_length": 102, "alphanum_fraction": 0.6641053787, "include": true, "reason": "import numpy", "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969785412932606, "lm_q2_score": 0.8856314662716159, "lm_q1q2_score": 0.8588724772243284}}
{"text": "import numpy as np\n\n# Matriz de 10 zeros:\nm = np.zeros(10).reshape(1, 10)\nprint(m)\nprint()\n\n# Matriz de 10 ones:\nm = np.ones(10).reshape(1, 10)\nprint(m)\nprint()\n\n# Matriz de 10 cincos:\nm = (np.ones(10) * 5).reshape(1, 10)\n# ou\nm = (np.zeros(10) + 5).reshape(1, 10)\n# ou \nm = np.linspace(5, 5, 10).reshape(1, 10)\nprint(m)\nprint()\n\n# Array de inteiros de 10 a 50\na = np.arange(10, 51)\nprint(a)\nprint()\n\n# Array de números pares de 10 a 50\nbooleanValues = a % 2 == 0\na2 = a[booleanValues]\nprint(a2)\n# ou \na2 = np.arange(10, 51, 2)\nprint()\n\n# Matriz de 3x3 com valores de 0 a 8\nm = np.arange(0, 9).reshape(3, 3)\nprint(m)\nprint()\n\n# Matriz identidade de 3x3\nm = np.eye(3)\nprint(m)\nprint()\n\n# Gerar números aleatorios entre 0 e 1\nn = np.random.rand(1)\nprint(n)\nprint()\n\n# Gerar array de 25 números aleatorios de uma distribuição normal\nn = np.random.randn(25)\nprint(n)\nprint()\n\n# Matriz 10x10 ?\nm = (np.arange(0, 100) / 100).reshape(10, 10)\nprint(m)\nprint()\n\n# Array igualmente espaçado com tamanho 20 de 0 e 1 ?\nprint(np.linspace(0, 1, 20))\n\nprint()\nprint(' ----------------------- ')\n# Slice array 5x5 ignorando 2 primeiras linhas e 1 coluna\nm = np.arange(1, 26).reshape(5, 5)\nprint(m)\nprint()\n\nprint(m[2:5, 1:5])\n# ou\n# print(m[2:, 1:])\nprint()\n\n# Acessar o elemento de valor 20\nprint(m[3][4])\n# ou\nprint(m[3, 4])\n# ou\nprint(m[3, -1])\nprint()\n\n# Retornar [2, 7, 12]\nprint(m[:3, 1:2])\n# ou\n# print(m[0:3, 1])\n# ou\n# print(m[:3, 1])\nprint()\n\n# Retornar [21, 22, 23, 24, 24]\nprint(m[4, :])\n# ou\n# print(m[-1, :])\n# ou\n# print(m[4])\nprint()\n\nprint(m[3:, :5])\n\nprint()\nprint(' ----------------------- ')\n# Obter a soma dos valores \nprint(m.sum())\nprint(np.sum(m))\nprint()\n\n# Obter o desvio padrão\nprint(np.std(m))\nprint()\n\n# Soma de todas as colunas\nprint(np.sum(m, axis=0))\n# ou\n# m.sum(axis=0)", "meta": {"hexsha": "80c6386f7128127263bd24c37724a6b0b9e6091c", "size": 1787, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy/np-excercises.py", "max_stars_repo_name": "augustoscher/python-excercises", "max_stars_repo_head_hexsha": "502fb3c15597033ba19e32f871be12d347a9aa2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy/np-excercises.py", "max_issues_repo_name": "augustoscher/python-excercises", "max_issues_repo_head_hexsha": "502fb3c15597033ba19e32f871be12d347a9aa2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy/np-excercises.py", "max_forks_repo_name": "augustoscher/python-excercises", "max_forks_repo_head_hexsha": "502fb3c15597033ba19e32f871be12d347a9aa2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.5391304348, "max_line_length": 65, "alphanum_fraction": 0.6071628428, "include": true, "reason": "import numpy", "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.9173026561945815, "lm_q1q2_score": 0.8588567178352984}}
{"text": "import numpy as np\nimport numpy.linalg as LA\n\n# マスの数(0からNまで)\nN = 4\n\n# 遷移行列Mを作る\nM = np.zeros((N + 1, N + 1))\nfor i in range(N + 1):\n    if i in (0, N):\n        M[i][i] = 1.0\n    else:\n        M[i + 1][i] = 0.5\n        M[i - 1][i] = 0.5\n\n\n# Mのべき乗を計算し、M^{\\infty}がどうなりそうか見てみる\nnp.set_printoptions(precision=3)\nMinf = M\nfor _ in range(100):\n    Minf = M@Minf\nprint(Minf)\n\n# 固有ベクトルを求め、Mを対角化する\nw, P = LA.eig(M)\nPinv = LA.inv(P)\nD = np.diag(w)\nprint(\"D=\")\nprint(D)\nprint(\"P^-1MP=\")\nprint(Pinv@M@P)\n\n# M^{\\infty}を求める\nDinf = np.diag([1, 1, 0, 0, 0])\nMinf = P@Dinf@Pinv\nprint(Minf)\n\n# 1のマスから始めた場合\na = (np.array([0, 1, 0, 0, 0]))\nprint(Pinv@a)\n\n# 2のマスから始めた場合\na = (np.array([0, 0, 1, 0, 0]))\nprint(Pinv@a)\n", "meta": {"hexsha": "ac158129f585ad1e864b1c0094c91de2fd5d1e88", "size": 692, "ext": "py", "lang": "Python", "max_stars_repo_path": "articles/markov_eigenvalue/eigen.py", "max_stars_repo_name": "kaityo256/zenn-content", "max_stars_repo_head_hexsha": "f28bc572c51a82053b3b0e110b4722bf1402abb7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-05-27T01:51:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T09:50:04.000Z", "max_issues_repo_path": "articles/markov_eigenvalue/eigen.py", "max_issues_repo_name": "kaityo256/zenn-content", "max_issues_repo_head_hexsha": "f28bc572c51a82053b3b0e110b4722bf1402abb7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-04-09T06:52:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:26:10.000Z", "max_forks_repo_path": "articles/markov_eigenvalue/eigen.py", "max_forks_repo_name": "kaityo256/zenn-content", "max_forks_repo_head_hexsha": "f28bc572c51a82053b3b0e110b4722bf1402abb7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-09-05T02:21:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T23:53:02.000Z", "avg_line_length": 15.3777777778, "max_line_length": 34, "alphanum_fraction": 0.563583815, "include": true, "reason": "import numpy", "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407152622596, "lm_q2_score": 0.8824278680004707, "lm_q1q2_score": 0.8588147294201289}}
{"text": "import numpy as np \r\nimport statsmodels.api as sm \r\nimport math\r\nimport matplotlib.pyplot as plt \r\nfrom scipy.integrate import quad\r\nimport sys\r\nimport os\r\nimport logging\r\nfrom brd_mod.brdgeo import *\r\nfrom brd_mod.brdecon import *\r\n\r\n\r\ndef dot(x, y):\r\n\t'''\r\n\tDot product between two vector-like arrays\r\n\t'''\r\n\tif len(x) != len(y):\r\n\t\tprint(\"Array sizes are not equal.\")\r\n\t\treturn\r\n\r\n\tsum = 0\r\n\tfor i in range(0, len(x)):\r\n\t\tsum += (x[i]*y[i])\r\n\r\n\treturn sum\r\n\r\ndef sum(x):\r\n\t'''\r\n\tCalculates sum of array\r\n\t'''\r\n\ttotal= 0\r\n\tfor i in range(0, len(x)):\r\n\t\ttotal += x[i]\r\n\r\n\treturn total\r\n\r\ndef mean(x):\r\n\t'''\r\n\tCalculates the mean value of an array\r\n\t'''\r\n\treturn sum(x)/len(x)\r\n\r\ndef square(x):\r\n\t'''\r\n\tSquares each value of an array\r\n\t'''\r\n\tseries= []\r\n\tfor i in range(0, len(x)):\r\n\t\tseries.append(x[i]**2)\r\n\r\n\treturn series\r\n\r\ndef variance(x):\r\n\t'''\r\n\tCalculates population variance of an array\r\n\t'''\r\n\tsample= mean(x)\r\n\tses= []\r\n\tfor i in range(0, len(x)):\r\n\t\tses.append((x[i]-sample)**2)\r\n\r\n\treturn sum(ses)/(len(x))\r\n\r\ndef covariance(x, y):\r\n\t'''\r\n\tCalculates co-variance between two arrays\r\n\t'''\r\n\tif len(x) != len(y):\r\n\t\tprint(\"Array sizes are not equal.\")\r\n\t\treturn\r\n\r\n\tx_mean= mean(x)\r\n\ty_mean= mean(y)\r\n\tx_ses= []\r\n\ty_ses= []\r\n\tfor i in range(0, len(x)):\r\n\t\tx_ses.append(x[i]-x_mean)\r\n\t\ty_ses.append(y[i]-y_mean)\r\n\r\n\treturn dot(x_ses, y_ses)/len(x)\r\n\r\ndef std_dev(x):\r\n\t'''\r\n\tCalculates population standard deviation\r\n\tof an array\r\n\t'''\r\n\treturn math.sqrt(variance(x))\r\n\r\ndef median(x):\r\n\t'''\r\n\tCalculates the median value of an array\r\n\t'''\r\n\tx.sort()\r\n\tn= len(x)\r\n\tif n < 1:\r\n\t\tprint(\"List too short.\")\r\n\t\treturn\r\n\r\n\tif n % 2 ==1:\r\n\t\treturn x[n//2]\r\n\r\n\telse:\r\n\t\treturn sum(x[n//2-1:n//2+1])/2.0\r\n\r\ndef corr_coef(x, y):\r\n\t'''\r\n\tCalculates Pearson Correlation Coefficient\r\n\tof an array\r\n\t'''\r\n\tif len(x) != len(y):\r\n\t\tprint(\"Array sizes are not equal.\")\r\n\t\treturn\r\n\t\r\n\tx_mean= mean(x)\r\n\ty_mean= mean(y)\r\n\tlength= len(x)\r\n\txx_arr= []\r\n\tyy_arr= []\r\n\tfor i in range(0, len(x)):\r\n\t\txx_arr.append((x[i]**2)-length*(x_mean**2))\r\n\t\tyy_arr.append((y[i]**2)-length*(y_mean**2))\r\n\t\t\r\n\tss_xy = ((dot(x, y))-(length*x_mean*y_mean))\r\n\tss_xx= sum(xx_arr)\r\n\tss_yy= sum(yy_arr)\r\n\r\n\treturn (length*dot(x, y) - sum(x)*sum(y))/math.sqrt(( \\\r\n\t\tlength*sum(square(x))-sum(x)**2)*(length*sum(square(y))-sum(y)**2))\r\n\r\ndef cointegration_strength(data1, data2):\r\n\t'''\r\n\tRuns Cointegration Test on Two Datasets\r\n\tdata1= data series 1\r\n\tdata2= data series 2\r\n\tReturns t-stat and p-value of Cointegration\r\n\t'''\r\n\tdata1= series_to_array(data1).flatten()\r\n\tdata2= series_to_array(data2).flatten()\r\n\r\n\tif len(data1) != len(data2):\r\n\t\treturn \"Sizes do not Match\"\r\n\r\n\treturn ts.coint(data1, data2)[:2]\r\n\r\ndef norm_pdf(x, mean=0, std=1):\r\n\t'''\r\n\tProbability density function using\r\n\tnormal distribution with pre-specified\r\n\tmean and standard deviation (default: standard\r\n\tnormal distribution)\r\n\t'''\r\n\texpo= -(x-mean)**2/(2*std**2)\r\n\tprefix= 1/math.sqrt(2*math.pi*std**2)\r\n\treturn prefix*math.exp(expo)\r\n\r\ndef error_func(t):\r\n\t'''\r\n\tIntegrand for cumulative distribution function\r\n\tfor normal distribution\r\n\t'''\r\n\treturn math.exp(-t**2)\r\n\r\ndef norm_cdf(x, mean=0, std=1):\r\n\t'''\r\n\tCumulative distribution function using\r\n\tnormal distribution with pre-specified\r\n\tmean and standard deviation (default: standard\r\n\tnormal distribution)\r\n\t'''\r\n\tinp= (x-mean)/(std*math.sqrt(2))\r\n\tinteg =quad(error_func, 0, inp)[0]\r\n\treturn (1/2)*(1+(2/math.sqrt(math.pi))*integ)\r\n\r\ndef skewness(x):\r\n\t'''\r\n\tCalculates skewness of an array from a \r\n\tstandard normal distribution\r\n\t'''\r\n\tx_mean= mean(x)\r\n\tlength= len(x)\r\n\tx_cu= []\r\n\tfor i in range(0, len(x)):\r\n\t\tx_cu.append(math.pow(x[i]-x_mean, 3))\r\n\r\n\treturn sum(x_cu)/(math.pow(std_dev(x),3))\r\n\r\ndef kurtosis(x):\r\n\t'''\r\n\tCalculates kurtosis of an array from a\r\n\tstandard normal distribution\r\n\t'''\r\n\tx_mean= mean(x)\r\n\tlength= len(x)\r\n\tx_qu= []\r\n\tfor i in range(0, len(x)):\r\n\t\tx_qu.append(math.pow(x[i]-x_mean, 4))\r\n\r\n\treturn sum(x_qu)/(length*math.pow(std_dev(x), 4))\r\n\r\ndef step_generation(x_min=-3, x_max=3, step=0.0001):\r\n\t'''\r\n\tGenerates an array of higher resolution\r\n\tbetween two boundaries and a specified \r\n\tstep value\r\n\t'''\r\n\tn = int(round((x_max - x_min)/float(step)))\r\n\treturn([x_min + step*i for i in range(n+1)])\r\n\r\ndef plot_norm(mean=0, std=1, pdf=True, x_min=-3, x_max=3, step=0.0001):\r\n\t'''\r\n\tPlots a normal distribution from a \r\n\tpre-specified mean and standard deviation\r\n\tusing two boundaries and a specified step\r\n\tvalue\r\n\t'''\r\n\tx_list= step_generation(x_min, x_max, step)\r\n\ty_list= []\r\n\tfor x in x_list:\r\n\t\tif pdf:\r\n\t\t\ty_list.append(norm_pdf(x, mean, std))\r\n\t\telse:\r\n\t\t\ty_list.append(norm_cdf(x, mean, std))\r\n\r\n\tplt.plot(x_list, y_list)\r\n\tplt.show()\r\n\r\ndef boxcox_transformation(data, param):\r\n\t'''\r\n\tBoxCox Transformation on Dataset:\r\n\tlog(y_t) if param=0\r\n\t(y_t^param-1)/param otherwise\r\n\t'''\r\n\treturn data.apply(boxcox_aux, args=(param,))\r\n\r\ndef boxcox_aux(param, value):\r\n\t'''\r\n\tAuxillary Function to Apply BoxCox to Individual Data\r\n\t'''\r\n\tif param ==0:\r\n\t\treturn math.log(value)\r\n\telse:\r\n\t\treturn (math.pow(value, param)-1)/float(param)\r\n \r\ndef reverse_boxcox_transformation(data, param):\r\n\t'''\r\n\tBoxCox Transformation on Dataset:\r\n\tlog(y_t) if param=0\r\n\t(y_t^param-1)/param otherwise\r\n\t'''\r\n\treturn data.apply(reverse_boxcox_aux, args=(param,))\r\n\r\ndef reverse_boxcox_aux(param, value):\r\n\t'''\r\n\tAuxillary Function to Apply Reverse BoxCox to Individual Data\r\n\t'''\r\n\tif param ==0:\r\n\t\treturn math.exp(value)\r\n\telse:\r\n\t\ttry:\r\n\t\t\tbase= (param*value)+1\r\n\t\t\texpo= 1/param\r\n\t\t\treturn math.pow(base, expo)\r\n\t\texcept:\r\n \t\t\tprint(\"Negative Value Encountered, Reverse Transformation Failed.\")\r\n \t\t\treturn -1\r\n\r\ndef back_transform(data, param):\r\n\t'''\r\n\tBack-Transforms Mean for Box-Cox Transformation\r\n\t'''\t\r\n\tvar= data.var()\r\n\treturn data.apply(back_transform_aux, args=(param, var,))\r\n\r\ndef back_transform_aux(param, var, value):\r\n\t'''\r\n\tAuxillary Function to Back-Transform Mean for Individual Data\r\n\t'''\r\n\tif param==0:\r\n\t\treturn math.exp(value)*(1+(var/2))\r\n\telse:\r\n\t\ttry:\r\n\t\t\tbase= (param*value+1)\r\n\t\t\texpo= 1/param\r\n\t\t\texpart= math.pow(base, expo)\r\n\t\t\tvarnum= var*(1-param)\r\n\t\t\tvarden= 2*math.pow(base, 2)\r\n\t\t\treturn expart*(1+(varnum/varden))\r\n\t\texcept:\r\n\t\t\tprint(\"Negative Value Encountered, Reverse Transformation Failed.\")\r\n\t\t\treturn -1\r\n\r\ndef log_transformation(data):\r\n\t'''\r\n\tBasic function to take log of each data point\r\n\t'''\r\n\treturn data.apply(math.log)\r\n\r\ndef set_union(x, y):\r\n\t'''\r\n\tReturns array that represents the sorted union\r\n\tof two input arrays\r\n\t'''\r\n\ttemp= x\r\n\tfor i in y:\r\n\t\ttry:\r\n\t\t\tval= temp.index(i)\r\n\r\n\t\texcept:\r\n\t\t\ttemp.append(i)\r\n\r\n\ttemp.sort()\r\n\treturn temp\r\n\r\ndef set_intersection(x, y):\r\n\t'''\r\n\tReturns array that represents the sorted intersection\r\n\tof two input arrays\r\n\t'''\r\n\ttemp= []\r\n\tfor i in x:\r\n\t\ttry:\r\n\t\t\tval= y.index(i)\r\n\t\t\tif val > -1:\r\n\t\t\t\ttemp.append(i)\r\n\t\texcept:\r\n\t\t\tpass\r\n\r\n\ttemp.sort()\r\n\treturn temp", "meta": {"hexsha": "82648d010e9cf1dd2d39c437b2e1b60c32e28a48", "size": 6875, "ext": "py", "lang": "Python", "max_stars_repo_path": "brd_mod/brdstats.py", "max_stars_repo_name": "benrdavison/brd_mod", "max_stars_repo_head_hexsha": "d496c5faece564f3758c25ed99a8240cde0ccf81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "brd_mod/brdstats.py", "max_issues_repo_name": "benrdavison/brd_mod", "max_issues_repo_head_hexsha": "d496c5faece564f3758c25ed99a8240cde0ccf81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "brd_mod/brdstats.py", "max_forks_repo_name": "benrdavison/brd_mod", "max_forks_repo_head_hexsha": "d496c5faece564f3758c25ed99a8240cde0ccf81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.896656535, "max_line_length": 72, "alphanum_fraction": 0.6397090909, "include": true, "reason": "import numpy,from scipy,import statsmodels", "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407183668539, "lm_q2_score": 0.8824278602705732, "lm_q1q2_score": 0.8588147246366584}}
{"text": "\"\"\"\n==================================================\nUsing histograms to plot a cumulative distribution\n==================================================\n\nThis shows how to plot a cumulative, normalized histogram as a\nstep function in order to visualize the empirical cumulative\ndistribution function (CDF) of a sample. We also show the theoretical CDF.\n\nA couple of other options to the ``hist`` function are demonstrated.\nNamely, we use the ``normed`` parameter to normalize the histogram and\na couple of different options to the ``cumulative`` parameter.\nThe ``normed`` parameter takes a boolean value. When ``True``, the bin\nheights are scaled such that the total area of the histogram is 1. The\n``cumulative`` kwarg is a little more nuanced. Like ``normed``, you\ncan pass it True or False, but you can also pass it -1 to reverse the\ndistribution.\n\nSince we're showing a normalized and cumulative histogram, these curves\nare effectively the cumulative distribution functions (CDFs) of the\nsamples. In engineering, empirical CDFs are sometimes called\n\"non-exceedance\" curves. In other words, you can look at the\ny-value for a given-x-value to get the probability of and observation\nfrom the sample not exceeding that x-value. For example, the value of\n225 on the x-axis corresponds to about 0.85 on the y-axis, so there's an\n85% chance that an observation in the sample does not exceed 225.\nConversely, setting, ``cumulative`` to -1 as is done in the\nlast series for this example, creates a \"exceedance\" curve.\n\nSelecting different bin counts and sizes can significantly affect the\nshape of a histogram. The Astropy docs have a great section on how to\nselect these parameters:\nhttp://docs.astropy.org/en/stable/visualization/histogram.html\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed(19680801)\n\nmu = 200\nsigma = 25\nn_bins = 50\nx = np.random.normal(mu, sigma, size=100)\n\nfig, ax = plt.subplots(figsize=(8, 4))\n\n# plot the cumulative histogram\nn, bins, patches = ax.hist(x, n_bins, density=True, histtype='step',\n                           cumulative=True, label='Empirical')\n\n# Add a line showing the expected distribution.\ny = ((1 / (np.sqrt(2 * np.pi) * sigma)) *\n     np.exp(-0.5 * (1 / sigma * (bins - mu))**2))\ny = y.cumsum()\ny /= y[-1]\n\nax.plot(bins, y, 'k--', linewidth=1.5, label='Theoretical')\n\n# Overlay a reversed cumulative histogram.\nax.hist(x, bins=bins, density=True, histtype='step', cumulative=-1,\n        label='Reversed emp.')\n\n# tidy up the figure\nax.grid(True)\nax.legend(loc='right')\nax.set_title('Cumulative step histograms')\nax.set_xlabel('Annual rainfall (mm)')\nax.set_ylabel('Likelihood of occurrence')\n\nplt.show()\n\n#############################################################################\n#\n# .. admonition:: References\n#\n#    The use of the following functions, methods, classes and modules is shown\n#    in this example:\n#\n#    - `matplotlib.axes.Axes.hist` / `matplotlib.pyplot.hist`\n", "meta": {"hexsha": "68151d027c445cf3a26f16b50632946022860433", "size": 2951, "ext": "py", "lang": "Python", "max_stars_repo_path": "matplotlib-3.4.3/matplotlib-3.4.3/examples/statistics/histogram_cumulative.py", "max_stars_repo_name": "JohnLauFoo/clc_packages_Yu", "max_stars_repo_head_hexsha": "259f01d9b5c02154ce258734d519ae8995cd0991", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-13T17:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T17:21:44.000Z", "max_issues_repo_path": "matplotlib-3.4.3/matplotlib-3.4.3/examples/statistics/histogram_cumulative.py", "max_issues_repo_name": "JohnLauFoo/clc_packages_Yu", "max_issues_repo_head_hexsha": "259f01d9b5c02154ce258734d519ae8995cd0991", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matplotlib-3.4.3/matplotlib-3.4.3/examples/statistics/histogram_cumulative.py", "max_forks_repo_name": "JohnLauFoo/clc_packages_Yu", "max_forks_repo_head_hexsha": "259f01d9b5c02154ce258734d519ae8995cd0991", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.987804878, "max_line_length": 78, "alphanum_fraction": 0.6892578787, "include": true, "reason": "import numpy", "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.9425067211996142, "lm_q1q2_score": 0.8587929940870505}}
{"text": "# -*- coding: utf-8 -*-\r\n\r\n\" In this pyfile we will give the solution of linear equation system in details. That is, not only the final result will be given, but also the L, U matrix and the determination of A will be listed here for your convinience. \"\r\n\r\nimport numpy as np\r\n\r\n\"\"\" Input: Ax=b \r\nA = np.array([[1,3,5],\r\n              [2,5,2],\r\n              [9,3,4]\r\n              ]) # Here input your coefficient matrix\r\nb = np.array([10,24,31]) # Here input the vector\r\n\"\"\"\r\n\r\ndef check(A):\r\n    row = A.shape[0]\r\n    col = A.shape[1]\r\n    if row!=col:\r\n        print(\"Input error: A is not a square matrix\")\r\n        return 0\r\n    else:\r\n        if np.linalg.det(A)==0:\r\n            print(\"The determination of A is equal to zero\")\r\n            return 0\r\n        else:\r\n            if row == 1:\r\n                print(\"The dimension of matrix is 1\")\r\n                return 0\r\n            else:\r\n                return row\r\ndef Decomposition(A):\r\n    if check(A) == 0:\r\n        print(\"Error\")\r\n    else:\r\n        print(\"det(A)=%r\"%np.linalg.det(A))\r\n        dim = check(A)\r\n        L = np.eye(dim)    \r\n        U = np.zeros_like(A)\r\n        U[0,:]=A[0,:]\r\n        L[1:,0]=A[1:,0]/U[0,0]\r\n        for r in range(1,dim):\r\n            for l in range(1,r):\r\n                L[r,l]=1/U[l,l]*(A[r,l]-L[r,:l]@U[:l,l])\r\n            for u in range(r,dim):\r\n                U[r,u]=A[r,u]-L[r,:r]@U[:r,u]\r\n    print(\"L=\\n\",L,\"\\n\",\"U=\\n\",U)\r\n    return L,U\r\n\r\n#Decomposition(A)\r\n\r\ndef Solve(A,b):\r\n    L,U = Decomposition(A)\r\n    y = np.linalg.solve(L,b)\r\n    x = np.linalg.solve(U,y)\r\n    print(\"y=\\n\",y,\"\\n\",\"x=\\n\",x)\r\n    return y,x\r\n\r\n#Solve(A,b)\r\n    \r\n\r\n    \r\n\r\n", "meta": {"hexsha": "f5977e30505a1ccf9d930b233a9d5fc3964362ed", "size": 1660, "ext": "py", "lang": "Python", "max_stars_repo_path": "LU.py", "max_stars_repo_name": "DickLiTQ/NumAnalysis", "max_stars_repo_head_hexsha": "6f0adb1717842dbde822d45d5a5e3a89b489061e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-01-23T05:19:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T02:17:36.000Z", "max_issues_repo_path": "LU.py", "max_issues_repo_name": "DickLiTQ/NumAnalysis", "max_issues_repo_head_hexsha": "6f0adb1717842dbde822d45d5a5e3a89b489061e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LU.py", "max_forks_repo_name": "DickLiTQ/NumAnalysis", "max_forks_repo_head_hexsha": "6f0adb1717842dbde822d45d5a5e3a89b489061e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-01-20T06:45:56.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-28T02:11:41.000Z", "avg_line_length": 26.3492063492, "max_line_length": 227, "alphanum_fraction": 0.4722891566, "include": true, "reason": "import numpy", "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762055074521, "lm_q2_score": 0.894789454880027, "lm_q1q2_score": 0.858784966074665}}
{"text": "#!/usr/bin/env python3\n\n\"\"\"Serial example code for estimating the value of π.\n\nWe can estimate the value of π by a stochastic algorithm. Consider a\ncircle of radius 1, inside a square that bounds it, with vertices at\n(1,1), (1,-1), (-1,-1), and (-1,1). The area of the circle is just π,\nwhereas the area of the square is 4. So, the fraction of the area of the\nsquare which is covered by the circle is π/4.\n\nA point selected at random uniformly from the square thus has a\nprobability π/4 of being within the circle.\n\nWe can estimate π by examining a large number of randomly-selected\npoints from the square, and seeing what fraction of them lie within the\ncircle. If this fraction is f, then our estimate for π is π ≈ 4f.\n\nThanks to symmetry, we can compute points in one quadrant, rather\nthan within the entire unit square, and arrive at identical results.\n\"\"\"\n\nimport numpy as np\nimport sys\nimport datetime\n\n\ndef inside_circle(total_count):\n    \"\"\"Single-processor task for a group of samples.\n\n    Generates uniform random x and y arrays of size total_count, on the\n    interval [0,1), and returns the number of the resulting (x,y) pairs\n    which lie inside the unit circle.\n    \"\"\"\n\n    x = np.float64(np.random.uniform(size=total_count))\n    y = np.float64(np.random.uniform(size=total_count))\n\n    radii = np.sqrt(x*x + y*y)\n\n    count = len(radii[np.where(radii<=1.0)])\n\n    return count\n\n\nif __name__ == '__main__':\n    \"\"\"Main executable.\n\n    This function runs the 'inside_circle' function with a defined number\n    of samples. The results are then used to estimate π.\n\n    An estimate of the required memory, elapsed calculation time, and\n    accuracy of calculating π are also computed.\n    \"\"\"\n\n    if len(sys.argv) > 1:\n        n_samples = int(sys.argv[1])\n    else:\n        n_samples = 8738128 # trust me, this number is not random :-)\n\n    # Time how long it takes to estimate π.\n    start_time = datetime.datetime.now()\n    counts = inside_circle(n_samples)\n    my_pi = 4.0 * counts / n_samples\n    elapsed_time = (datetime.datetime.now() - start_time).total_seconds()\n\n    # Memory required is dominated by the size of x, y, and radii from\n    # inside_circle(), calculated in MiB\n    size_of_float = np.dtype(np.float64).itemsize\n    memory_required = 3 * n_samples * size_of_float / (1024**2)\n\n    # accuracy is calculated as a percent difference from a known estimate\n    # of π.\n    pi_specific = np.pi\n    accuracy = 100*(1-my_pi/pi_specific)\n\n    # Uncomment either summary format for verbose or terse output\n    # summary = \"{:d} core(s), {:d} samples, {:f} MiB memory, {:f} seconds, {:f}% error\"\n    summary = \"{:d},{:d},{:f},{:f},{:f}\"\n    print(summary.format(1, n_samples, memory_required, elapsed_time,\n                         accuracy))\n", "meta": {"hexsha": "c5289c84b9dc6594686afba8a1383939f61a2fd1", "size": 2770, "ext": "py", "lang": "Python", "max_stars_repo_path": "files/pi-serial.py", "max_stars_repo_name": "mbareford/hpc-intro", "max_stars_repo_head_hexsha": "183482adb7f52e206f36590c34ae41bc192dd430", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 77, "max_stars_repo_stars_event_min_datetime": "2018-01-10T20:17:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-23T06:08:48.000Z", "max_issues_repo_path": "files/pi-serial.py", "max_issues_repo_name": "mbareford/hpc-intro", "max_issues_repo_head_hexsha": "183482adb7f52e206f36590c34ae41bc192dd430", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 189, "max_issues_repo_issues_event_min_datetime": "2018-02-05T14:51:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-07T22:43:57.000Z", "max_forks_repo_path": "files/pi-serial.py", "max_forks_repo_name": "tkphd/hpc-intro", "max_forks_repo_head_hexsha": "1dcf9cd41c252ad82aea283cf8cd5af29579acf2", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 70, "max_forks_repo_forks_event_min_datetime": "2018-01-25T09:21:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-28T16:47:39.000Z", "avg_line_length": 34.1975308642, "max_line_length": 88, "alphanum_fraction": 0.6906137184, "include": true, "reason": "import numpy", "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.9136765145991261, "lm_q1q2_score": 0.8587767488807111}}
{"text": "from math import pi, exp\nimport scipy\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nsns.set_theme()\n\n# Q4\n\"\"\"\n\nImportance Sampling\n\n\"\"\"\n\nl = [100, 500, 1000, 2000, 3000, 5000, 10000]\nsigma = 2\n\np = np.vectorize(lambda x: 0.5 * exp(-np.abs(x)))  # target distribution\ng = np.vectorize(\n    lambda x: (1 / (sigma * np.sqrt(2 * pi))) * exp(-0.5 * ((x / sigma) ** 2))\n)  # proposed distribution\n\n\ndef expec(func, arr):  # for expectation\n    f = (func(arr) * p(arr)) / g(arr)\n    return np.var(f), np.mean(f)\n\n\nfuncs = {\n    1: np.vectorize(lambda x: x),\n    2: np.vectorize(lambda x: x ** 2),\n    5: np.vectorize(lambda x: x ** 5),\n}\n\nresults = np.zeros((len(l) * len(funcs), 6), dtype=object)\nfor i, points in enumerate(l):\n    z = np.random.default_rng().normal(\n        0, sigma, size=(points, 1)\n    )  # proposed is normal\n    for j, (key, val) in enumerate(funcs.items()):\n        var_estimate, truth = expec(val, z)\n        true_val = scipy.stats.laplace.moment(\n            key, 0, 1\n        )  # expectation == moment\n        results[(i * len(funcs)) + j] = [\n            points,\n            f\"E[x^{key}]\",\n            true_val,\n            truth,\n            abs(truth - true_val),\n            var_estimate\n        ]\n\nresults = pd.DataFrame(\n    results, columns=[\"Points\", \"Expectation\", \"Truth\", \"Result\", \"Error\", \"Variance\"]\n).infer_objects()\nresults = results.sort_values(\n    [\"Expectation\", \"Points\"], ascending=[True, True]\n)\n\nresults.groupby([\"Expectation\"]).apply(print)\n# results.groupby([\"Expectation\"]).apply(lambda df : print(df.to_latex(index=False)))\n", "meta": {"hexsha": "9cb9a0cffdd864e7a52d0d98552adc0dad39f0b4", "size": 1590, "ext": "py", "lang": "Python", "max_stars_repo_path": "q4.py", "max_stars_repo_name": "gajrajgchouhan/Statistical-Simulation-Project", "max_stars_repo_head_hexsha": "c819dd7ee3fa607b5ebf38756cb2e2cd2bb3e038", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "q4.py", "max_issues_repo_name": "gajrajgchouhan/Statistical-Simulation-Project", "max_issues_repo_head_hexsha": "c819dd7ee3fa607b5ebf38756cb2e2cd2bb3e038", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "q4.py", "max_forks_repo_name": "gajrajgchouhan/Statistical-Simulation-Project", "max_forks_repo_head_hexsha": "c819dd7ee3fa607b5ebf38756cb2e2cd2bb3e038", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.84375, "max_line_length": 86, "alphanum_fraction": 0.586163522, "include": true, "reason": "import numpy,import scipy", "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633822, "lm_q2_score": 0.8976953030553434, "lm_q1q2_score": 0.858766026972}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"Python file for all cost related methods\"\"\"\n\nimport numpy as np\n\n\ndef calculate_mse(y, tx, w):\n    \"\"\"Calculate the mse for vector e.\"\"\"\n    e = y - tx.dot(w)\n    return 1/2*np.mean(e**2)\n\n\ndef calculate_mae(y, tx, w):\n    \"\"\"Calculate the mae for vector e.\"\"\"\n    e = y - tx.dot(w)\n    return np.mean(np.abs(e))\n\n\ndef compute_loss(y, tx, w, error='mse'):\n    \"\"\"Calculate the loss.\n    You can calculate the loss using mse or mae.\n    \"\"\"\n    if error is 'mse':\n        return calculate_mse(y, tx, w)\n    elif error is 'mae':\n        return calculate_mae(y, tx, w)\n    else:\n        raise NotImplementedError\n\n\ndef calculate_rmse(y, tx, w):\n    \"\"\" Calculate rmse for given data and weights \"\"\"\n    return np.sqrt(calculate_mse(y, tx, w) * 2)\n\n\ndef loss_logistic(y, tx, w):\n    \"\"\"compute the cost by negative log likelihood.\"\"\"\n    loss = 0\n    N = len(y)\n    for index in range(len(tx)):\n        e = np.dot(np.transpose(tx[index, :]), w)\n        loss += np.log(1 + np.exp(e)) - y[index] * e\n    return loss / N\n\n\ndef get_loss_function(error='mse'):\n    \"\"\"\n    Return the loss function reference according to error\n    Serve the model.py\n    :param error:\n    :return:\n    \"\"\"\n    if error is 'mse':\n        return calculate_mse\n    elif error is 'mae':\n        return calculate_mae\n    elif error is 'rmse':\n        return calculate_rmse\n    elif error is 'logistic':\n        return loss_logistic\n", "meta": {"hexsha": "d9579db51939e83e6cbe7828b8abbca220a2dded", "size": 1428, "ext": "py", "lang": "Python", "max_stars_repo_path": "projects/project1/scripts/costs.py", "max_stars_repo_name": "kcyu1993/ML_course_kyu", "max_stars_repo_head_hexsha": "99671281bcf83cbcd75d1c57772bdfdf79d28aff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/project1/scripts/costs.py", "max_issues_repo_name": "kcyu1993/ML_course_kyu", "max_issues_repo_head_hexsha": "99671281bcf83cbcd75d1c57772bdfdf79d28aff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/project1/scripts/costs.py", "max_forks_repo_name": "kcyu1993/ML_course_kyu", "max_forks_repo_head_hexsha": "99671281bcf83cbcd75d1c57772bdfdf79d28aff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4098360656, "max_line_length": 57, "alphanum_fraction": 0.5959383754, "include": true, "reason": "import numpy", "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088043, "lm_q2_score": 0.8976952893703477, "lm_q1q2_score": 0.8587660183199471}}
{"text": "# CELL 0\n\n# Import necessary libraries.\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Problem Statement: -\n\n# We'll create a model that predicts crop yeilds for apples (target variable) by looking at the average\n# temperature, rainfall and humidity (input variables or features) in different regions.\n\n# Here's the training data:\n# Temp Rain Humidity Prediction\n# 73   67   43       56\n# 91   88   64       81\n# 87   134  58       119\n# 102  43   37       22\n# 69   96   70       103\n\n# In a linear regression model, each target variable is estimated to be a weighted sum of the input\n# variables, offset by some constant, known as a bias:\n\n# yeild_apple = w11 * temp + w12 * rainfall + w13 * humidity + b1\n\n# It means that the yield of apples is a linear or planar function of the temperature, rainfall & humidity.\n\n# Our objective: Find a suitable set of weights and biases using the training data, to make accurate predictions.\n\n# CELL 1\n\n# The training data can be represented using 2 matrices (inputs and targets),\n# each with one row per observation and one column for variable.\n\n# Input (temp, rainfall, humidity)\nX = np.array([[73, 67, 43], \n              [91, 88, 64], \n              [87, 134, 58], \n              [102, 43, 37], \n              [69, 96, 70]], dtype='float32')\n\n# Target (apples)\nY = np.array([[56], \n                    [81], \n                    [119], \n                    [22], \n                    [103]], dtype='float32')\n\n# CELL 2\n# Before we build a model, we need to convert inputs and targets to PyTorch tensors.\n\n# Linear Regression Model (from scratch)\n\n# The weights and biases can also be represented as matrices, initialized with random values.\n# The first row of w and the first element of b are use to predict the first target\n# variable i.e. yield for apples, and similarly the second for oranges.\n\n# The model is simply a function that performs a matrix multiplication of the input x and\n# the weights w (transposed) and adds the bias w0 (replicated for each observation).\n\nmu = np.mean(X, 0)\nsigma = np.std(X, 0)\n# Normalizing the input\nX = (X - mu) / sigma\nX = np.hstack((np.ones((Y.size, 1)), X))\nprint(X.shape)\n\n# CELL 3\n\n# Weights and biases\nrg = np.random.default_rng(12)\nw = rg.random((1, 4))\nprint(w)\n\n# Because we've started with random weights and biases, the model does not perform a good\n# job of predicting the target varaibles.\n\n# Loss Function We can compare the predictions with the actual targets, using the following method:\n# Calculate the difference between the two matrices (preds and targets).\n# Square all elements of the difference matrix to remove negative values.\n# Calculate the average of the elements in the resulting matrix.\n# The result is a single number, known as the mean squared error (MSE).\n\n# CELL 4\n\n# MSE loss function\ndef mse(t1, t2):\n    diff = t1 - t2\n    return np.sum(diff * diff) / diff.size\n\n# Compute error\npreds = model(X,w)\ncost_initial = mse(preds, Y)\nprint(\"Cost before regression: \", cost_initial)\n\n# CELL 5\n\n# Compute gradient\n\n# Define the model\ndef model(x, w):\n    return x @ w.T\n\ndef gradient_descent(X, y, w, learning_rate, n_iters):\n    J_history = np.zeros((n_iters, 1))\n    for i in range(n_iters):\n        h = model(X, w)\n        diff = h - y\n        delta = (learning_rate/Y.size)*(X.T@diff)\n        new_w = w - delta.T\n        w = new_w\n        J_history[i] = mse(h, y)\n    return (J_history, w)\n\n\n# CELL 6\n\n# Train for multiple iteration\n# To reduce the loss further, we repeat the process of adjusting the weights\n# and biases using the gradients multiple times. Each iteration is called an epoch.\n\nn_iters = 500\nlearning_rate = 0.01\n\ninitial_cost = mse(model(X, w), Y)\n\nprint(\"Initial cost is: \", initial_cost, \"\\n\")\n\n(J_history, optimal_params) = gradient_descent(X, Y, w, learning_rate, n_iters)\n\nprint(\"Optimal parameters are: \\n\", optimal_params, \"\\n\")\n\nprint(\"Final cost is: \", J_history[-1])\n\n\n# CELL 7\n\nplt.plot(range(len(J_history)), J_history, 'r')\n\nplt.title(\"Convergence Graph of Cost Function\")\nplt.xlabel(\"Number of Iterations\")\nplt.ylabel(\"Cost\")\nplt.show()\n\n# CELL 8\n\n\n# Calculate error\npreds = model(X, optimal_params)\ncost_final = mse(preds, Y)\n# Print predictions\nprint(\"Prediction:\\n\", preds)\n# Comparing predicted with targets\nprint(\"Targets:\\n\", Y)\n\n# CELL 9\n\nprint(\"Cost after linear regression: \", cost_final)\nprint(\"Cost reduction percentage: {} %\".format(((cost_initial- cost_final)/cost_initial)*100))", "meta": {"hexsha": "2c4d9cd1e923d99c99f16263c5ea6a26dc3be051", "size": 4445, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab5/Lab_5_1_Linear_Regression_Scratch.py", "max_stars_repo_name": "devangpatelmks/094_DevangPatel", "max_stars_repo_head_hexsha": "0da5bf92616284271118db2eab976d8555880f11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab5/Lab_5_1_Linear_Regression_Scratch.py", "max_issues_repo_name": "devangpatelmks/094_DevangPatel", "max_issues_repo_head_hexsha": "0da5bf92616284271118db2eab976d8555880f11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab5/Lab_5_1_Linear_Regression_Scratch.py", "max_forks_repo_name": "devangpatelmks/094_DevangPatel", "max_forks_repo_head_hexsha": "0da5bf92616284271118db2eab976d8555880f11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1329113924, "max_line_length": 113, "alphanum_fraction": 0.6791901012, "include": true, "reason": "import numpy", "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.8976952941600964, "lm_q1q2_score": 0.8587660173526319}}
{"text": "###\n# Introduction to Data Science Homework Assignment # 1\n# Student: Alan Fernandez, aefernandez@wpi.edu\n# Date: 08/29/18\n# Course: DS501, Introduction to Data Science (Grad Level)\n# Worcester Polytechnic Institute (WPI), Worcester, MA\n###\n\nimport numpy as np\n#-------------------------------------------------------------------------\n'''\n    Problem 3: PageRank algorithm (version 1) \n    In this problem, we implement a simplified version of the pagerank algorithm, which doesn't consider about sink node problem or sink region problem.\n    You could test the correctness of your code by typing `nosetests -v test3.py` in the terminal.\n'''\n\n#--------------------------\ndef compute_P(A):\n    '''\n        compute the transition matrix P from addjacency matrix A. P[j][i] represents the probability of moving from node i to node j.\n        Input: \n                A: adjacency matrix, a (n by n) numpy matrix of binary values. If there is a link from node i to node j, A[j][i] =1. Otherwise A[j][i]=0 if there is no link.\n        Output: \n                P: transition matrix, a (n by n) numpy matrix of float values.  P[j][i] represents the probability of moving from node i to node j.\n    The values in each column of matrix P should sum to 1.\n    '''\n    #########################################\n    ## INSER YOUR CODE HERE\n\n    # sum of each column of A\n    column_sum = A.sum(axis = 0)\n\n    # create a diagonal matrix\n    D = np.diag(column_sum.getA1())\n\n    # normalize each column of A\n\n    # Invert the diagonal matrix to divide the adjacency matrix by the sum of the columns.\n    D = np.linalg.inv(D)\n\n    # Multiply the matrices to execute the division. This returns the transition matrix.\n    P = A * D\n\n    #########################################\n    return P\n\n\n#--------------------------\ndef random_walk_one_step(P, x_i):\n    '''\n        compute the result of one step random walk.\n        Input:\n                P: transition matrix, a (n by n) numpy matrix of float values.  P[j][i] represents the probability of moving from node i to node j.\n                x_i: pagerank scores before the i-th step of random walk. a numpy vector of shape (n by 1).\n        Output:\n                x_i_plus_1: pagerank scores after the i-th step of random walk. a numpy vector of shape (n by 1).\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n    x_i_plus_1 = np.dot(P, x_i)\n\n\n    #########################################\n    return x_i_plus_1\n\n\n#--------------------------\n#--------------------------\ndef random_walk(P, x_0, max_steps=10000):\n    '''\n        compute the result of multiple-step random walk. The random walk should stop if the score vector x no longer change (converge) after one step of random walk, or the number of iteration reached max_steps.\n        Input:\n                P: transition matrix, a (n by n) numpy matrix of float values.  P[j][i] represents the probability of moving from node i to node j.\n                x_0: the initial pagerank scores. a numpy vector of shape (n by 1).\n                max_steps: the maximium number of random walk steps. an integer value.\n        Output:\n                x: the final pagerank scores after multiple steps of random walk. a numpy vector of shape (n by 1).\n                n_steps: the number of steps actually used (for example, if the vector x no longer changes after 3 steps of random walk, return the value 3.\n        Hint: you could use np.allclose(x, previous_x) function to determine when to stop the random walk iterations.\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n    x_old = x_0\n    n_steps = 0\n    while n_steps < max_steps:\n        n_steps += 1\n        x_new = random_walk_one_step(P, x_old)\n        if np.allclose(x_new, x_old):\n            break\n        x_old = x_new\n\n    #########################################\n\n    return x_old, n_steps\n\n\n#--------------------------\ndef pagerank_v1(A):\n    ''' \n        A simplified version of PageRank algorithm.\n        Given an adjacency matrix A, compute the pagerank score of all the nodes in the network. \n        Here we ignore the issues of sink nodes and sink regions in the network.\n        Input: \n                A: adjacency matrix, a numpy matrix of binary values. If there is a link from node i to node j, A[j][i] =1. Otherwise A[j][i]=0 if there is no link.\n        Output: \n                x: the ranking scores, a numpy vector of float values, such as np.array([[.3], [.5], [.7]])\n    '''\n\n    # compute the transition matrix from adjacency matrix\n    P = compute_P(A)\n\n    # initialize the score vector with all one values\n    num_nodes, _ = A.shape # get the number of nodes (n)\n    x_0 =  np.ones((num_nodes,1)) # create an all-one vector of shape (n by 1)\n    \n    # random walk\n    x, n_steps = random_walk(P, x_0)\n\n    return x\n\n", "meta": {"hexsha": "a3345a2660cddd8d416cc3a7549d2f4e1db9d30e", "size": 4862, "ext": "py", "lang": "Python", "max_stars_repo_path": "Homework_1/problem3.py", "max_stars_repo_name": "aefernandez/DS501", "max_stars_repo_head_hexsha": "15799c8690c2f934d8e710db060e2b9e1b6afc8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homework_1/problem3.py", "max_issues_repo_name": "aefernandez/DS501", "max_issues_repo_head_hexsha": "15799c8690c2f934d8e710db060e2b9e1b6afc8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homework_1/problem3.py", "max_forks_repo_name": "aefernandez/DS501", "max_forks_repo_head_hexsha": "15799c8690c2f934d8e710db060e2b9e1b6afc8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1818181818, "max_line_length": 211, "alphanum_fraction": 0.585767174, "include": true, "reason": "import numpy", "num_tokens": 1136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724488, "lm_q2_score": 0.8976952893703477, "lm_q1q2_score": 0.8587660172100767}}
{"text": "import numpy as np\nimport math\n\ndef ReadPrecision():\n    return float(input())\n\ndef ReadMatrixAndVec():\n    matrixSize = int(input())\n\n    matrix = [list(map(float, input().split())) for i in range(matrixSize)]\n    vec = list(map(float, input().split()))\n\n    return matrix, vec\n\ndef TransformSLAU(matrix, vec):\n    newMatrix = [[-matrix[i][j] / matrix[i][i] for j in range(len(matrix))] for i in range(len(matrix))]\n    for i in range(len(matrix)):\n        newMatrix[i][i] = 0\n\n    newVec = [vec[i] / matrix[i][i] for i in range(len(matrix))]\n\n    return newMatrix, newVec\n\ndef CalcNorm(matrix):\n    return np.linalg.norm(matrix, np.inf)\n\ndef IsClosePrec(a, b):\n    print(\"eps_k {}, user_eps {}\".format(a, b))\n    return a <= b\n\ndef CalcCurPrec(firstVec, secondVec, coeff):\n    lul = CalcNorm(secondVec - firstVec)\n\n    return lul * coeff\n\ndef zeidelCoeff(upperDiagMtx, mtx):\n    return CalcNorm(upperDiagMtx) / (1 - CalcNorm(mtx))\n\ndef SolveSLAU(matrix, vec, prec, isJacobi):\n    mtxT, vecT = TransformSLAU(matrix, vec)\n\n    if isJacobi and CalcNorm(mtxT) >= 1:\n        print(\"unsolvable with Jacobi\\'s method\")\n        (\"Sorry\", \"Nothing\")\n    \n    origVec = np.matrix(vecT.copy()).transpose()\n    matrixInNP = np.matrix(mtxT)\n    solFirst = origVec.copy()\n    solSecond = solFirst.copy()\n    matrixNorm = CalcNorm(matrix)\n    iterCounter = 0\n    \n    coeff = matrixNorm / (1 - matrixNorm)  if isJacobi else zeidelCoeff(np.triu(matrixInNP), matrixInNP)\n\n    while True:\n        if isJacobi:\n            solSecond = origVec + matrixInNP @ solFirst\n        else:\n            for i in range(len(origVec)):\n                solSecond[i][0] = origVec.item(i, 0) + math.fsum([matrixInNP.item(i, j) * solFirst.item(j, 0) for j in range(len(origVec))])\n\n        if (IsClosePrec(CalcCurPrec(solFirst, solSecond, coeff), prec)):\n            break\n\n        solFirst = solSecond.copy()\n        iterCounter += 1\n\n    return solSecond, iterCounter\n\nif __name__ == \"__main__\":\n    precision = ReadPrecision()\n    matrix, vec = ReadMatrixAndVec()\n\n    print(\"Solving SLAU with Jacobi:\")\n    resJac, jacIters = SolveSLAU(matrix, vec, precision, isJacobi=True)\n\n    print(\"Solving SLAU with Zeidel:\")\n    resZeid, zeidIters = SolveSLAU(matrix, vec, precision, isJacobi=False)\n    print(\"\\nepsilon is {}\".format(precision))\n    print(\"Jacobi method result:\\n{}\\n in {} iterations\".format(resJac, jacIters))\n    print(\"Zeidel method result:\\n{}\\n in {} iterations\".format(resZeid, zeidIters))\n\n    print(\"Original vector:\\n{}\\nOriginal vector after Jacobi:\\n{}\\nOriginal vector after Zeidel:\\n{}\".format(np.matrix(vec).transpose(),\n                                                                                                              np.matrix(matrix) @ resJac,\n                                                                                                              np.matrix(matrix) @ resZeid))\n\n", "meta": {"hexsha": "5fea78171fb0a61f61d36240cf4d573e615707c7", "size": 2893, "ext": "py", "lang": "Python", "max_stars_repo_path": "6th_semester/NumMethods/1_lab/task3.py", "max_stars_repo_name": "mehakun/Labs", "max_stars_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-03-06T16:08:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-02T22:11:00.000Z", "max_issues_repo_path": "6th_semester/NumMethods/1_lab/task3.py", "max_issues_repo_name": "mehakun/Labs", "max_issues_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6th_semester/NumMethods/1_lab/task3.py", "max_forks_repo_name": "mehakun/Labs", "max_forks_repo_head_hexsha": "0d42c97e8671d31b9cb49093686df7b8d4d62cfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2528735632, "max_line_length": 140, "alphanum_fraction": 0.5990321466, "include": true, "reason": "import numpy", "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633822, "lm_q2_score": 0.8976952852648488, "lm_q1q2_score": 0.8587660099530044}}
{"text": "import numpy as np\nimport cvxpy as cp\nimport pandas as pd\n\n\ndef integer_probs(p,m,n):\n    \"\"\"\n    We want to allocate an integer vector in a way that each element\n    get's atleast m, total items is n and the probabilities are as \n    close to p as possible.\n    \"\"\"\n    x = cp.Variable(len(p),integer=True)\n    constraints = [m <= x, x <= n, sum(x) == n]\n    #objective = cp.Minimize(cp.sum_squares((x-m)/(n-m*len(p)) - p))\n    objective = cp.Minimize(cp.sum_squares(x/n - p))\n    problm = cp.Problem(objective, constraints)\n    _ = problm.solve()\n    return x.value\n\ndef integer_probs_v2(p,m,n):\n    \"\"\"\n    We want to allocate an integer vector in a way that each element\n    get's atleast m, total items is n and the probabilities are as \n    close to p as possible.\n    \"\"\"\n    x = cp.Variable(len(p))\n    constraints = [m <= x, x <= n, sum(x) == n]\n    objective = cp.Minimize(cp.sum_squares(x/n - p))\n    problm = cp.Problem(objective, constraints)\n    _ = problm.solve()\n    h = redistribute(x.value)\n    return h\n\ndef integer_probs_v3(p,m,n):\n    x = cp.Variable(len(p),integer=True)\n    z = cp.Variable()\n    objective = cp.Minimize(z)\n    constraints = [m <= x, x <= n, sum(x) == n, \\\n                (x-m)/(n-m*len(p))-p<=z, p-(x-m)/(n-m*len(p))<=z]\n                #(x)/(n)-p<=z, p-(x)/(n)<=z]                \n    problm = cp.Problem(objective, constraints)\n    _ = problm.solve()\n    return x.value\n\ndef redistribute(x_value):\n    \"\"\"\n    Given an array of floats, converts them into ints. Does\n    this by taking the excess fractional part and re-distributing\n    it in the same proportion.\n    \"\"\"\n    vals = x_value // 1\n    excess = int(sum(x_value % 1))\n    excess_vals_unif = np.ones(len(x_value))* excess//len(x_value)\n    excess_vals_nonunif = np.concatenate((np.ones(excess % len(x_value)),\\\n                        np.zeros(len(x_value)-excess%len(x_value)))\\\n                        ,axis=0)\n    h = vals + excess_vals_unif + excess_vals_nonunif\n    return h\n\n\ndef tst_optimizn(m=2,excess=40):\n    p=np.random.rand(200)\n    p=np.sort(p)\n    p=p/sum(p)\n    n=m*len(p)+excess\n    x2 = integer_probs(p,m,n)\n    x3 = integer_probs_v3(p,m,n)\n    df = pd.DataFrame()\n    df[\"p\"]=p\n    df[\"x3\"]=x3\n    df[\"prct_x3\"] = x3/sum(x3)\n    df[\"x2\"]=x2\n    df[\"prct_x2\"] = x2/sum(x2)\n    return df\n\n", "meta": {"hexsha": "59bd65954804409b2dbf467c892e1f87439c2e4d", "size": 2309, "ext": "py", "lang": "Python", "max_stars_repo_path": "optimizn/problems/int_allocn.py", "max_stars_repo_name": "ryu577/optimizn", "max_stars_repo_head_hexsha": "dd36be81dbbde54f12b96a4e8129701f3ba3dcef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optimizn/problems/int_allocn.py", "max_issues_repo_name": "ryu577/optimizn", "max_issues_repo_head_hexsha": "dd36be81dbbde54f12b96a4e8129701f3ba3dcef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimizn/problems/int_allocn.py", "max_forks_repo_name": "ryu577/optimizn", "max_forks_repo_head_hexsha": "dd36be81dbbde54f12b96a4e8129701f3ba3dcef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3815789474, "max_line_length": 74, "alphanum_fraction": 0.5924642702, "include": true, "reason": "import numpy,import cvxpy", "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992960608886, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.8587246973907858}}
{"text": "def cells():\n    '''\n    # 3/ Problem solutions\n    '''\n\n    '''\n    '''\n\n    from sympy import *\n    init_printing()\n\n    '''\n    '''\n\n\n    '''\n    '''\n\n    '''\n    ## P3.1\n    '''\n\n    '''\n    '''\n\n    AUG = Matrix([\n        [1, 5,   25],\n        [2, 1,   32]])\n    AUG\n\n    '''\n    '''\n\n    AUG.rref()\n\n    '''\n    '''\n\n\n    '''\n    '''\n\n    '''\n    ## P3.2\n    \n    In the above solution we showed how to build `AUG` matrix directly.\n    This time, we'll build `AUG` by row-joining (`row_join`) a matrix of coefficients and a vector of constants.\n    '''\n\n    '''\n    '''\n\n    A = Matrix([\n        [3,       3],\n        [2,  S(3)/2]])\n    A\n\n    '''\n    '''\n\n    b = Matrix([6,5])  # b is a column vector\n    b\n\n    '''\n    '''\n\n    # row-join A and b to obtain the augmented matrix\n    AUG = A.row_join(b)\n    AUG\n\n    '''\n    '''\n\n    '''\n    ### a) Alice\n    \n    Let's obtain the matrix `AUGA` which is the result after Alice's row operation.\n    '''\n\n    '''\n    '''\n\n    AUGA = AUG.copy()  # make a copy of AUG\n    AUGA[0,:] = AUGA[0,:]/3\n    AUGA\n\n    '''\n    '''\n\n    AUGA[1,:] = AUGA[1,:] - 2*AUGA[0,:]\n    AUGA\n\n    '''\n    '''\n\n    AUGA[1,:] = -2*AUGA[1,:]\n    AUGA\n\n    '''\n    '''\n\n    AUGA[0,:] = AUGA[0,:] - AUGA[1,:]\n    AUGA\n\n    '''\n    '''\n\n    '''\n    ### b) Bob\n    '''\n\n    '''\n    '''\n\n    AUGB = AUG.copy()\n    AUGB[0,:] = AUGB[0,:] - AUGB[1,:]\n    AUGB\n\n    '''\n    '''\n\n    AUGB[1,:] = AUGB[1,:] - 2*AUGB[0,:]\n    AUGB\n\n    '''\n    '''\n\n    AUGB[1,:] = -1*S(2)/3*AUGB[1,:]\n    AUGB\n\n    '''\n    '''\n\n    AUGB[0,:] = AUGB[0,:] - S(3)/2*AUGB[1,:]\n    AUGB\n\n    '''\n    '''\n\n\n    '''\n    '''\n\n    '''\n    ### c) Charlotte\n    '''\n\n    '''\n    '''\n\n    AUGC = AUG.copy()\n    AUGC[0,:], AUGC[1,:] = AUGC[1,:], AUGC[0,:]\n    AUGC\n\n    '''\n    '''\n\n    AUGC[0,:] = AUGC[0,:]/2\n    AUGC\n\n    '''\n    '''\n\n    AUGC[1,:] = AUGC[1,:] - 3*AUGC[0,:]\n    AUGC\n\n    '''\n    '''\n\n    AUGC[1,:] = S(4)/3*AUGC[1,:]\n    AUGC\n\n    '''\n    '''\n\n    AUGC[0,:] = AUGC[0,:] - S(3)/4*AUGC[1,:]\n    AUGC\n\n    '''\n    '''\n\n\n    '''\n    '''\n\n    '''\n    ## P3.3\n    '''\n\n    '''\n    '''\n\n    # define agmented matrices for three systems of eqns. with unique sol'ns\n    AUGA = Matrix([\n            [ -1, -2, -2],\n            [  3, 3, 0]])\n    \n    AUGB = Matrix([\n            [ 1, -1, -2,  1],\n            [-2,  3,  3, -1],\n            [-1,  0,  1,  2]])\n    \n    AUGC = Matrix([\n            [ 2, -2,  3, 2],\n            [ 1, -2, -1, 0],\n            [-2,  2,  2, 1]])\n\n    '''\n    '''\n\n    AUGA\n\n    '''\n    '''\n\n    AUGA.rref()\n\n    '''\n    '''\n\n    AUGB\n\n    '''\n    '''\n\n    AUGB.rref()\n\n    '''\n    '''\n\n    AUGC\n\n    '''\n    '''\n\n    AUGC.rref()\n\n    '''\n    '''\n\n\n    '''\n    '''\n\n    '''\n    ## P3.4\n    \n    These three systems of equations have infinitely many solutions.\n    '''\n\n    '''\n    '''\n\n    '''\n    ### P3.4 a)\n    '''\n\n    '''\n    '''\n\n    AUGA = Matrix([\n        [ -1, -2,  -2],\n        [  3,  6,   6]])\n    AUGA\n\n    '''\n    '''\n\n    AUGA.rref()\n\n    '''\n    '''\n\n    AUGA[0:2,0:2].nullspace()\n\n    '''\n    '''\n\n    # the solutions to the sytem of equations represented by AUGA\n    # is of the form    point + nullspace\n    point = AUGA.rref()[0][:,2]\n    nullspace = AUGA[0:2,0:2].nullspace()\n\n    '''\n    '''\n\n    # the point is also called he particular solution\n    point\n\n    '''\n    '''\n\n    # if the augmented matrix AUGA is [A|b], then the point satisfies A*point = b\n    print( AUGA[0:2,0:2]*point == AUGA[:,2] )\n    AUGA[0:2,0:2]*point\n\n    '''\n    '''\n\n    '''\n    #### Finding the null space\n    '''\n\n    '''\n    '''\n\n    # the nullspace of A is one dimensional and spanned by\n    n = nullspace[0]\n    n\n    # every vector n in the nullspace of A satisfies  A*n=0\n\n    '''\n    '''\n\n    # so solution to A*x=b is any (point+s*n) where s is any real number\n    # since  A*(point+s*n) = A*point + sA*n = A*point + 0 = b.\n    # Let's verify claim for values of s in the range -5,-4,-3,-2,-1,0,1,2,3,4,5\n    for s in range(-5,6):\n        print( AUGA[0:2,0:2]*(point + s*n), \n               AUGA[0:2,0:2]*(point + s*n) == AUGA[:,2] )\n\n    '''\n    '''\n\n    '''\n    ### P3.4 b)\n    '''\n\n    '''\n    '''\n\n    AUGB = Matrix([\n            [ 1, -1, -2,   1],\n            [-2,  3,  3,  -1],\n            [-1,  2,  1,   0]])\n    AUGB\n\n    '''\n    '''\n\n    AUGB.rref()\n\n    '''\n    '''\n\n    point_B = AUGB.rref()[0][:,3]\n    nullspace_B = AUGB[0:3,0:3].nullspace()[0]\n    s = symbols('s')\n    point_B + s*nullspace_B\n\n    '''\n    '''\n\n    '''\n    ### P3.4 c)\n    '''\n\n    '''\n    '''\n\n    AUGC = Matrix([\n            [ 2, -2, 3,  2],\n            [ 0,  0, 5,  3],\n            [-2,  2, 2,  1]])\n    AUGC\n\n    '''\n    '''\n\n    AUGC.rref()\n\n    '''\n    '''\n\n    constants = AUGC.rref()[0][:,3]\n    \n    # construct point_C by placing the constants into the location of the pivots\n    pivots = AUGC.rref()[1]\n    point_C = zeros(3,1)\n    for idx, pivot in enumerate(pivots):\n        point_C[pivot] = constants[idx]\n    \n    nullspace_C = AUGC[0:3,0:3].nullspace()[0]\n    s = symbols('s')\n    point_C + s*nullspace_C\n\n    '''\n    '''\n\n\n    '''\n    '''\n\n", "meta": {"hexsha": "6acd4174ee2d5b1dc1bca66229230dc2e5dfb580", "size": 5067, "ext": "py", "lang": "Python", "max_stars_repo_path": "aspynb/chapter03_problems.py", "max_stars_repo_name": "minireference/noBSLAnotebooks", "max_stars_repo_head_hexsha": "3d6acb134266a5e304cb2d51c5ac4dc3eb3949b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 116, "max_stars_repo_stars_event_min_datetime": "2016-04-20T13:56:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:55:08.000Z", "max_issues_repo_path": "aspynb/chapter03_problems.py", "max_issues_repo_name": "minireference/noBSLAnotebooks", "max_issues_repo_head_hexsha": "3d6acb134266a5e304cb2d51c5ac4dc3eb3949b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-01T17:00:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T19:34:09.000Z", "max_forks_repo_path": "aspynb/chapter03_problems.py", "max_forks_repo_name": "minireference/noBSLAnotebooks", "max_forks_repo_head_hexsha": "3d6acb134266a5e304cb2d51c5ac4dc3eb3949b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2017-02-04T05:22:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T00:06:50.000Z", "avg_line_length": 12.8604060914, "max_line_length": 112, "alphanum_fraction": 0.3692520229, "include": true, "reason": "from sympy", "num_tokens": 1757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.9086178994073576, "lm_q1q2_score": 0.8586391056791995}}
{"text": "# -*- coding: utf-8 -*-\n\n# Raivo Laanemets\n# rlaanemt@ut.ee\n\n# A note: getA1() is used to transform matrix row into array.\n\nimport sys\nimport random\nimport numpy\nimport time\n\n# Solves linear system Kx = b.\n# when is_unit is set to True then the\n# procedure expects lower triangular matrix as L\n# otherwise it expects lower unit triangular matrix as L.\n# Might destructively update input matrix!\n\ndef solveL(L, b, is_unit=False):\n    # If unit triangular matrix is assumed, set 1's in\n    # the matrix main diagonal.\n    if is_unit:\n        L += numpy.diag(numpy.matrix(-L.diagonal() + 1).getA1())\n    # Solve with forward subsitution.\n    x = numpy.array(numpy.zeros(len(b), dtype=float))\n    x[0] = b[0] / L[0, 0]\n    for i in xrange(1, len(b)):\n        x[i] = (b[i] - sum((L[i, 0:i]).getA1() * x[0:i])) / L[i, i]\n    return x\n\n# Solves linear system Kx = b.\n# Expects upper triangular matrix as L.\n\ndef solveU(L, b):\n    # Transforms the matrix L into suitable form to use with solveL.\n    # Might be inefficient.\n    # [::-1] reverses the array.\n    return solveL(numpy.fliplr(numpy.flipud(L)), b[::-1])[::-1]\n\n# Taken from pseudoalgorithm:\n# http://www.math.vt.edu/people/wapperom/class_home/4445/alg_ludoolittle.pdf\n\n# Compared to one on our lecture slides:\n# 1. It gives name of the algorithm (Doolittle's) so\n# I can ask someone about it.\n# 2. Checks if factorization is possible at all\n# instead of quitely producing bogus results.\n# 3. Gives L and U matrixes I actually know how to use.\n\n# Returns a pair (L, U) as the decomposition result.\n\ndef gauss_decomp(a):\n    n = len(a)\n    l = numpy.matrix(numpy.zeros((n, n), dtype=float))\n    u = numpy.matrix(numpy.zeros((n, n), dtype=float))\n    for i in xrange(n):\n        if a[i, i] == 0:\n            # It's *not* normal termination condition.\n            # Lecture slides will lead to bogus algorithm?\n            raise Exception(\"Factorization not possible\");\n        l[i, i] = 1.0\n        for j in xrange(i, n):\n            u[i, j] = a[i, j]\n            for k in xrange(i):\n                u[i, j] = u[i, j] - l[i, k] * u[k, j]\n        for j in xrange(i + 1, n):\n            l[j, i] = a[j, i]\n            for k in xrange(i):\n                l[j, i] = l[j, i] - l[j, k] * u[k, i]\n            l[j, i] = l[j, i] / float(u[i, i])\n        \n    return (l, u)\n\n# Based on http://en.wikipedia.org/wiki/LU_decomposition#Solving_linear_equations\n# Did not find this part from lecture slides.\n\n# Solves Ax = b for each b in bs.\n# Does not compute errors.\n\ndef solve_all(A, bs):\n    (L, U) = gauss_decomp(A)\n    xs = map(lambda b: solve_lu(L, U, b), bs)\n    return xs\n\ndef solve_single(A, b):\n    (L, U) = gauss_decomp(A)\n    return solve_lu(L, U, b);\n\ndef solve_lu(L, U, b):\n    y = solveL(L, b)\n    x = numpy.matrix(solveU(U, y))\n    # Consistent with numpy.linalg.solve output.\n    x.shape = (len(b), 1)\n    return numpy.matrix(x)\n\ndef main(argv):\n    A = numpy.matrix([[3, 1, 2], [0, -2, -2], [1, 5, 3]], dtype=float)\n    b = numpy.array([1, 1, 2], dtype=float)\n\n    print \"A\\n\", A\n    print \"b\\n\", b\n    print \"solveL\\n\", solveL(A.copy(), b)\n    print \"solveL with unit\\n\", solveL(A.copy(), b, is_unit=True)\n    print \"solveU\\n\", solveU(A.copy(), b)\n    (l, u) = gauss_decomp(A)\n    print \"gauss, L\\n\", l\n    print \"gauss, U\\n\", u\n    print \"gauss, LU (must be equal to A)\\n\", l * u\n    \n    # Testing with the example from http://en.wikipedia.org/wiki/System_of_linear_equations\n    A = numpy.matrix([[3, 2, -1], [2, -2, 4], [-1, 0.5, -1]], dtype=float)\n    b = numpy.array([1, -2, 0], dtype=float)\n    print \"A\\n\", A\n    print \"b\\n\", b\n    print \"solve\\n\", solve_single(A, b)\n\nif __name__ == \"__main__\":\n    main(sys.argv[1:])\n", "meta": {"hexsha": "6ccfb453521cec8d5d99ac30870f162072fd1f5d", "size": 3682, "ext": "py", "lang": "Python", "max_stars_repo_path": "2009/scientific-computing/prax6/src/RLPrax6_1.py", "max_stars_repo_name": "rla/old-code", "max_stars_repo_head_hexsha": "06aa69c3adef8434992410687d466dc42779e57b", "max_stars_repo_licenses": ["Ruby", "MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-11-08T10:01:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-10T00:00:58.000Z", "max_issues_repo_path": "2009/scientific-computing/prax6/src/RLPrax6_1.py", "max_issues_repo_name": "rla/old-code", "max_issues_repo_head_hexsha": "06aa69c3adef8434992410687d466dc42779e57b", "max_issues_repo_licenses": ["Ruby", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2009/scientific-computing/prax6/src/RLPrax6_1.py", "max_forks_repo_name": "rla/old-code", "max_forks_repo_head_hexsha": "06aa69c3adef8434992410687d466dc42779e57b", "max_forks_repo_licenses": ["Ruby", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9411764706, "max_line_length": 91, "alphanum_fraction": 0.5953286257, "include": true, "reason": "import numpy", "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.9086178913651384, "lm_q1q2_score": 0.8586391023020085}}
{"text": "#T# prime factorization consists of finding the prime numbers that multiplied together produce a given number, in the case that the given number is prime itself then the two prime factors are 1 and itself\n\n#T# define a function to calculate the prime factors of a number recursively\ndef func1(num1):\n    num1 = int(num1)\n\n#T# create a list to store the prime number gotten in each recursion\n    list1 = []\n\n#T# create the range of numbers from 2 to num1, num1 is included in case it is prime\n    list2 = range(2, num1 + 1)\n\n#T# check the numbers in the range for the first prime number\n    for it1 in list2:\n\n#T# if num1 is divisible by it1 then it1 is prime because it's the first number (after 1) by which num1 is divisible\n        if (num1 % it1 == 0):\n            list1.append(it1)\n\n#T# recurse to find and append the first prime factor of the quotient num1/it1 which is smaller than num1, so that recursion can end\n            list1 += func1(num1/it1)\n\n#T# skip the remaining iterations of the for loop, this guarantees that no other factors of num1 are included, which may not be prime\n            break\n    return list1\n\n#T# check the prime factors of a number\nnum1 = 60\nlist1 = func1(num1) # [2, 2, 3, 5]\n\n#T# the multiplicity of the prime factors can be calculated by counting the amount of repetitions of each prime factor, for this the unique function from the numpy package is used\nimport numpy as np\n\ntuple1 = np.unique(list1, return_counts = True)\n# (array([2, 3, 5]), array([2, 1, 1])) #| the multiplicity of each prime number is in the second array", "meta": {"hexsha": "4f452cee16ce924dd576485d037a9d2ebef6ff12", "size": 1564, "ext": "py", "lang": "Python", "max_stars_repo_path": "Math/A01_Arithmetics_basics/Programs/S02/Prime_factorization.py", "max_stars_repo_name": "Polirecyliente/SGConocimiento", "max_stars_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Math/A01_Arithmetics_basics/Programs/S02/Prime_factorization.py", "max_issues_repo_name": "Polirecyliente/SGConocimiento", "max_issues_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/A01_Arithmetics_basics/Programs/S02/Prime_factorization.py", "max_forks_repo_name": "Polirecyliente/SGConocimiento", "max_forks_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6857142857, "max_line_length": 204, "alphanum_fraction": 0.7199488491, "include": true, "reason": "import numpy", "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211604938802, "lm_q2_score": 0.8807970904940926, "lm_q1q2_score": 0.8586196419150846}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef gaussian(x, mean, std):\n    return 1/(np.sqrt(2*np.pi*std**2))*np.exp(-0.5*(((x - mean)**2)/(std**2)))\n\nmy_a, my_sigma_a = 40, 8 \nmy_b, my_sigma_b = 20, 2 \n\nn = 10000\na_normal = np.random.default_rng().normal(my_a, my_sigma_a, n)\nb_normal = np.random.default_rng().normal(my_b, my_sigma_b, n)   \n\n# Linearized Method\nmy_sum_ab_l, my_sigma_sum_ab_l = sum_ab(a=my_a, b=my_b, sigma_a=my_sigma_a, sigma_b=my_sigma_b)\nmy_x = np.linspace(20, 100, 1000)\nmy_sum_ab_PDF = gaussian(x=my_x, mean=my_sum_ab_l, std=my_sigma_sum_ab_l)\n\n# Monte Carlo estimation\nmy_sum_ab_mc =  a_normal + b_normal\nmy_sum_ab_mc_mean = my_sum_ab_mc.mean()\nmy_sigma_sum_ab_mc_std = my_sum_ab_mc.std()\n \nfig, ax = plt.subplots()\nax.hist(my_sum_ab_mc, bins='auto', color='#c7ddf4', edgecolor='k', density=True, label= r'a+b sample distribution by MC ($\\mu_{a+b} = $' + \"{:.0f}\".format(my_sum_ab_mc_mean) + r'  - 1$\\sigma_{a+b} = $' + \"{:.0f}\".format(my_sigma_sum_ab_mc_std) + ')')\nax.plot(my_x, my_sum_ab_PDF, color='#ff464a', linestyle='--', label=r'a+b PDF by linearized error propagation ($\\mu_{a+b} = $' + \"{:.0f}\".format(my_sum_ab_l) + r'  - 1$\\sigma_{a+b} = $' + \"{:.0f}\".format(my_sigma_sum_ab_l) + ')')\nax.set_xlabel('a + b')\nax.set_ylabel('Probability Density')\nax.legend(title='Error Propagation')\nax.set_ylim(0,0.07)\n\nfig.tight_layout()\n\n\n", "meta": {"hexsha": "c0599d6dbcfa905bbd0bfeec0759ba7446de9619", "size": 1370, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/chapter_10/listing_10_15.py", "max_stars_repo_name": "guinslym/python_earth_science_book", "max_stars_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80, "max_stars_repo_stars_event_min_datetime": "2021-04-19T10:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:34:47.000Z", "max_issues_repo_path": "code/chapter_10/listing_10_15.py", "max_issues_repo_name": "guinslym/python_earth_science_book", "max_issues_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/chapter_10/listing_10_15.py", "max_forks_repo_name": "guinslym/python_earth_science_book", "max_forks_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2021-04-25T03:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:06:19.000Z", "avg_line_length": 39.1428571429, "max_line_length": 250, "alphanum_fraction": 0.6927007299, "include": true, "reason": "import numpy", "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211597623863, "lm_q2_score": 0.8807970889295664, "lm_q1q2_score": 0.8586196397456536}}
{"text": "from sympy import *\nx, C, D = symbols('x C D')\ni, j = symbols('i j', integer=True, positive=True)\npsi_i = (1-x)**(i+1)\npsi_j = psi_i.subs(i, j)\nintegrand = diff(psi_i, x)*diff(psi_j, x)\nintegrand = simplify(integrand)\nA_ij = integrate(integrand, (x, 0, 1))\nA_ij = simplify(A_ij)\nprint(('A_ij:', A_ij))\nf = 2\nb_i = integrate(f*psi_i, (x, 0, 1)) - \\\n      integrate(diff(D*x, x)*diff(psi_i, x), (x, 0, 1)) - \\\n      C*psi_i.subs(x, 0)\nb_i = simplify(b_i)\nprint(('b_i:', b_i))\nN = 1\nA = zeros(N+1, N+1)\nb = zeros(N+1)\nprint(('fresh b:', b))\nfor r in range(N+1):\n    for s in range(N+1):\n        A[r,s] = A_ij.subs(i, r).subs(j, s)\n    b[r,0] = b_i.subs(i, r)\nprint(('A:', A))\nprint(('b:', b[:,0]))\nc = A.LUsolve(b)\nprint(('c:', c[:,0]))\nu = sum(c[r,0]*psi_i.subs(i, r) for r in range(N+1)) + D*x\nprint(('u:', simplify(u)))\nprint((\"u'':\", simplify(diff(u, x, x))))\nprint(('BC x=0:', simplify(diff(u, x).subs(x, 0))))\nprint(('BC x=1:', simplify(u.subs(x, 1))))\n", "meta": {"hexsha": "acf33e530328cdbb18eb1c20fec3f8ee3c18adbb", "size": 956, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/u_xx_2_CD.py", "max_stars_repo_name": "mbarzegary/finite-element-intro", "max_stars_repo_head_hexsha": "47ef0a3592b823ae71a874ee35850114f16b6d8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-01-26T13:18:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T15:20:11.000Z", "max_issues_repo_path": "src/u_xx_2_CD.py", "max_issues_repo_name": "mbarzegary/finite-element-intro", "max_issues_repo_head_hexsha": "47ef0a3592b823ae71a874ee35850114f16b6d8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/u_xx_2_CD.py", "max_forks_repo_name": "mbarzegary/finite-element-intro", "max_forks_repo_head_hexsha": "47ef0a3592b823ae71a874ee35850114f16b6d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-05T23:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T10:22:29.000Z", "avg_line_length": 28.1176470588, "max_line_length": 59, "alphanum_fraction": 0.5533472803, "include": true, "reason": "from sympy", "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97482115683641, "lm_q2_score": 0.8807970732843033, "lm_q1q2_score": 0.8586196219171288}}
{"text": "\"\"\"Sample library demonstrates PCA algorithm using by two approaches:\nSVD and eigenvector.\"\"\"\n\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\n\n\ndef __calc_pc__(eig_val: np.array, pca_energy: float) -> np.array:\n    \"\"\"Helper function for calculating # of principal components.\n    @:arg eig_val - input vector of eig values of N x 1 size (N features per sample).\n    @:arg pca_energy - PCA energy, from 0.0 to 1.0.\n    @:return # of principal components.\"\"\"\n\n    denom = sum(eig_val)\n    num, k = 0, 0\n    for k in range(eig_val.shape[0]):\n        num += eig_val[k]\n        if (num / denom) >= pca_energy:\n            break\n\n    return k\n\n\ndef pca_svd(x: np.array, pca_energy=0.98, pc=None) -> np.array:\n    \"\"\"PCA using by SVD.\n    @:arg x - input matrix of M x N size (M samples with N features per sample).\n    @:arg pca_energy - PCA energy, from 0.0 to 1.0.\n    @:arg pc- number of principal components, unsigned integer from 1 to N features per sample\n    @:return tuple (x_reduced, u_reduced) where\n    x_reduced is a reduced matrix of M x K size (K<=N),\n    and u_reduced is a matrix of transformation x -> x_reduced.\"\"\"\n\n    # Mean normalization and feature scaling\n    x_std = StandardScaler().fit_transform(x)\n\n    # Calc covariance matrix of M x M size\n    cov_mat = np.cov(x_std.T)\n\n    # Calc SVD\n    u, s, v = np.linalg.svd(cov_mat)\n\n    # Calc K principal components\n    if not pc:\n        pc = __calc_pc__(s, pca_energy)\n\n    # Reduce N x M matrix to N x K (K <= M)\n    u_reduced = u[:, :pc]\n    x_reduced = np.dot(x_std, u_reduced)\n\n    return x_reduced, u_reduced\n\n\ndef pca_eig(x: np.array, pca_energy=0.98, pc=None) -> np.array:\n    \"\"\"PCA using by eigenvector.\n    @:arg x - input matrix of M x N size (M samples with N features per sample).\n    @:arg pca_energy - PCA energy, from 0.0 to 1.0.\n    @:arg pc- number of principal components, unsigned integer from 1 to N features per sample\n    @:return tuple (x_reduced, u_reduced) where\n    x_reduced is a reduced matrix of M x K size (K<=N),\n    and u_reduced is a matrix of transformation x -> x_reduced.\"\"\"\n\n    # Mean normalization and feature scaling\n    x_std = StandardScaler().fit_transform(x)\n\n    # Calc covariance matrix of M x M size\n    cov_mat = np.cov(x_std.T)\n\n    # Calc eigenvectors and eigenvalues of covariance matrix\n    eig_val_sc, eig_vec_sc = np.linalg.eig(cov_mat)\n\n    # Calc K principal components\n    if not pc:\n        pc = __calc_pc__(-np.sort(-eig_val_sc), pca_energy)\n\n    # Reduce N x M matrix to N x K (K <= M)\n    u_reduced = eig_vec_sc[:, :pc]\n    x_reduced = np.dot(x_std, u_reduced)\n\n    return x_reduced, u_reduced\n", "meta": {"hexsha": "1fc04c04feb64592e6e8ebe1e8f65679f36af96f", "size": 2645, "ext": "py", "lang": "Python", "max_stars_repo_path": "pcalib/pcalib.py", "max_stars_repo_name": "onidzelskyi/pca_lib", "max_stars_repo_head_hexsha": "c3fd4ff4965f18b7e4988ed80f4ae6b8e8a49e7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcalib/pcalib.py", "max_issues_repo_name": "onidzelskyi/pca_lib", "max_issues_repo_head_hexsha": "c3fd4ff4965f18b7e4988ed80f4ae6b8e8a49e7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcalib/pcalib.py", "max_forks_repo_name": "onidzelskyi/pca_lib", "max_forks_repo_head_hexsha": "c3fd4ff4965f18b7e4988ed80f4ae6b8e8a49e7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0625, "max_line_length": 94, "alphanum_fraction": 0.6646502836, "include": true, "reason": "import numpy", "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122768904644, "lm_q2_score": 0.8962513745192024, "lm_q1q2_score": 0.8585301948318976}}
{"text": "# Solving Ax = b using conjugate gradient method\r\n# Equation: Equation 1: x - y = -10\r\n#           Equation 2: 2x + 3y = 15\r\n# A = [1,-1; 2,3] and b = [-10; 15]\r\n\r\nimport numpy as np\r\n\r\nA = np.zeros((2,2))         # Define A matrix\r\nA[0,0] = 1.0\r\nA[0,1] = -1.0\r\nA[1,0] = 2.0\r\nA[1,1] = 3.0\r\n\r\nb = np.zeros((2,1))         # Define b vector\r\nb[0] = -10.0\r\nb[1] = 15.0\r\n\r\nres = np.ones((2,1))        # Define the residue res = b - Ax\r\nres[0] = 10\r\nres[1] = 10\r\n\r\nx = np.ones((2,1))          # Initial guess solution\r\nx[0] = 0\r\nx[1] = 0\r\n\r\nres = b - np.dot(A, x)\r\ntemp = np.dot(np.transpose(res),A)\r\ntemp0 = np.dot(temp,res)\r\nalp = (np.dot((np.transpose(res)), res)) / float(temp0)     # Magnitude of search direction\r\nx = x + alp*res\r\np = res                     # Initial search direction is same as residue\r\ncount = 0\r\nwhile res[0] > 0.001 or res[1] > 0.001:\r\n    res = b - np.dot(A, x)\r\n    temp1 = np.dot(np.transpose(p),A)\r\n    temp2 = np.dot(temp1,res)\r\n    temp3 = np.dot(np.transpose(p),A)\r\n    temp4 = np.dot(temp3,p)\r\n    beta = temp2/float(temp4)\r\n\r\n    p = res - beta*p        # Subsequent search directions\r\n    temp5 = np.dot(np.transpose(p),res)\r\n    temp6 = np.dot(np.transpose(p),A)\r\n    temp7 = np.dot(temp6, p)\r\n    alp = temp5/float(temp7)\r\n\r\n    x = x + alp*p\r\n    count = count+1         # Counts number of iterations\r\n\r\nprint (\"Actual solution is: \")\r\nprint (np.dot(np.linalg.inv(A),b))\r\n\r\nprint (\"Iterative Solution x is:  \")\r\nprint (x)\r\n\r\nprint (\"The final residue is:   \")\r\nprint (res)\r\n\r\nprint (\"Number of iterations are:   \")\r\nprint (count)\r\n", "meta": {"hexsha": "a058b05fa973d1c2d93e693f3f984204661f6fa6", "size": 1566, "ext": "py", "lang": "Python", "max_stars_repo_path": "Conjugate_Gradient_Method.py", "max_stars_repo_name": "soumyasen1809/CFD_NPTEL_IITKGP", "max_stars_repo_head_hexsha": "b747955650b37fbdb9a006f2292deb1b78fae6b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-17T21:54:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:18:10.000Z", "max_issues_repo_path": "Conjugate_Gradient_Method.py", "max_issues_repo_name": "soumyasen1809/CFD_NPTEL_IITKGP", "max_issues_repo_head_hexsha": "b747955650b37fbdb9a006f2292deb1b78fae6b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Conjugate_Gradient_Method.py", "max_forks_repo_name": "soumyasen1809/CFD_NPTEL_IITKGP", "max_forks_repo_head_hexsha": "b747955650b37fbdb9a006f2292deb1b78fae6b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6721311475, "max_line_length": 92, "alphanum_fraction": 0.5478927203, "include": true, "reason": "import numpy", "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.8962513745192024, "lm_q1q2_score": 0.8585301926781683}}
{"text": "def ode45(f, tspan, y0, tol=1e-6):\n    '''\n    tt, yy = ode45(f, tspan, y0, tol)\n    ODE324 - ODE IVP sovler by Dr Hale and TW324 class 2017\n    INPUTS:  A function handle f = @(t,y) ... such that dy/dt = f(t,y)\n             The times span tspan(1) < t <tspane(end)\n             The initial condition y(tspan(1)) - y0\n             The required accuracy, tol.\n    OUTPUTS: The selected time steps tt, and solution values yy.\n    '''\n\n    # Initial step size\n    h = np.sqrt(tol);\n\n    # Initialise solver\n    t    = tspan[0];\n    tend = tspan[1];\n    yn   = y0;\n    flag = 0;\n\n    # Storage\n    tt = t;\n    yy = yn;\n\n    # Loop through time:\n    while (t < tend):\n\n        # RK stages\n        s1 = f(t, yn)\n        s2 = f(t + (0.25)*h, yn + (0.25)*h * s1)\n        s3 = f(t + (3./8.)*h, yn + (3./32.)*h*s1 + (9./32.)*h*s2)\n        s4 = f(t + (12./13.)* h, yn + (1932./2197)*h*s1 - \\\n             (7200./2197.)*h*s2 + (7296./2197.)*h*s3)\n        s5 = f(t + h, yn  + (439./216.)*h*s1 - 8.0*h*s2 + \\\n             (3680./513.)*h*s3 - (845./4104.)*h*s4)\n        s6 = f(t + .5 * h, yn - (8./27.)*h*s1 + 2.0*h*s2 - \\\n             (3544./2565.)*h*s3 + (1859.0/4104.0)*h*s4 - (11./40.)*h*s5)\n        p  = 5;\n        yn1 = yn + h*((16.0/135.0)*s1 + (6656.0/12825.0)*s3 +\\\n             (28561.0/56430.0)*s4 - (9.0/50.)*s5 + (2./55.)*s6) ;\n        # Error estimate\n        err = h * abs((1.0/360.0)*s1 - (128.0/4275.0)*s3 - \\\n              (2197.0/75240.0)*s4 + (1.0/50.0)*s5 + (2.0/55.0)*s6) ;\n\n        # Step size adjust\n        hnew = 0.8*(tol*np.min(np.abs(yn1)/err))**(1.0/(p+1.0)) * h;\n        hnew = min(hnew, 2.0*h);           # Don't let h grow too fast.\n\n        if (np.abs(err) > tol):            # Error is too large!\n            if (flag == 0):                # Try the new time step\n                flag = 1;                  # Set flag to remember failure\n            else:                          # Time step failed\n                hnew = h/2.0;              # Take half of old one\n        else:                              # Error is small enough!\n            # Store solution and move to next time\n            yn = yn1\n            t = t + h;\n            yy = np.hstack((yy, yn1));\n            tt = np.hstack((tt, t));\n            # Successful step. Set flag to happy.\n            flag = 0;\n\n        # Choose next step (ensure we finish at the end of the interval!)\n        h = min(hnew, tend - t);\n\n    # Transpose for convenience\n    tt = tt.T\n    yy = yy.T\n    return (tt, yy)\n\ndef ode23(f, tspan, y0, tol=1e-6):\n    '''\n    tt, yy = ode23(f, tspan, y0, tol)\n    ODE324 - ODE IVP sovler by Dr Hale and TW324 class 2017\n    INPUTS:  A function handle f = @(t,y) ... such that dy/dt = f(t,y)\n             The times span tspan(1) < t <tspane(end)\n             The initial condition y(tspan(1)) - y0\n             The required accuracy, tol.\n    OUTPUTS: The selected time steps tt, and solution values yy.\n    '''\n\n    # Initial step size\n    h = np.sqrt(tol);\n\n    # Initialise solver\n    t    = tspan[0];\n    tend = tspan[1];\n    yn   = y0;\n    flag = 0;\n\n    # Storage\n    tt = t;\n    yy = yn;\n\n    # Loop through time:\n    while (t < tend):\n\n        s1 = f(t, yn)\n        s2 = f(t + h, yn + h * s1)\n        s3 = f(t + h/2.0, yn + (h/4.0)*(s1 + s2))\n        p  = 3\n        yn1 = yn + (h/6.0)*(s1 + 4.0*s3 + s2)\n        err = h/3.0 * abs(s1 - 2.0*s3 + s2)           # Error estimate\n\n        # Step size adjust\n        hnew = 0.8*(tol*np.min(np.abs(yn1)/err))**(1.0/(p+1.0)) * h;\n        hnew = min(hnew, 2.0*h);           # Don't let h grow too fast.\n\n        if (np.abs(err) > tol):            # Error is too large!\n            if (flag == 0):                # Try the new time step\n                flag = 1;                  # Set flag to remember failure\n            else:                          # Time step failed\n                hnew = h/2.0;              # Take half of old one\n        else:                              # Error is small enough!\n            # Store solution and move to next time\n            yn = yn1\n            t = t + h;\n            yy = np.hstack((yy, yn1));\n            tt = np.hstack((tt, t));\n            # Successful step. Set flag to happy.\n            flag = 0;\n        # Choose next step (ensure we finish at the end of the interval!)\n        h = min(hnew, tend - t);\n    # Transpose for convenience\n    tt = tt.T\n    yy = yy.T\n    return (tt, yy)\n\ndef plot_functions(tt, yy):\n    # Plot first component of solution\n    plt.subplot(211)\n    plt.plot(tt, yy, 'm-', lw=4.0)\n    plt.title('First component of solution')\n    # Plot time steps as a function of time\n    dtt = tt[2:-1] - tt[1:-2]\n    plt.subplot(212)\n    plt.plot(tt[2:-1], dtt, 'c-', lw=4.0)\n    plt.yscale('log')\n    plt.ylabel('Time steps')\n    plt.title('No. of time steps = %s'%(np.size(tt)-1))\n    plt.show()\n\nif __name__ == \"__main__\":\n    import numpy as np\n    import numpy.linalg as npla\n    import matplotlib.pyplot as plt\n\n    # making use of ODE23\n    tt, yy = ode23(lambda t, y: y**2 - y**3, [0, 2.0/0.001], y0=0.001)\n    plot_functions(tt, yy)\n\n    # making use of ODE45\n    tt, yy = ode45(lambda t, y: y**2 - y**3, [0, 2.0/0.001], y0=0.001)\n    plot_functions(tt, yy)\n", "meta": {"hexsha": "5638ac5f645215bcc40e408c7f7a8c24ec2db8ca", "size": 5188, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment_06/src/question02.py", "max_stars_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_stars_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-28T18:36:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-28T18:36:55.000Z", "max_issues_repo_path": "assignment_06/src/question02.py", "max_issues_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_issues_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment_06/src/question02.py", "max_forks_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_forks_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-16T04:26:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-16T04:26:44.000Z", "avg_line_length": 33.4709677419, "max_line_length": 73, "alphanum_fraction": 0.4666538165, "include": true, "reason": "import numpy", "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874228, "lm_q2_score": 0.8962513655129178, "lm_q1q2_score": 0.8585301840509376}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport math\nimport numpy as np\n\n\ndef calculate_variance(X, axis=0, ddof=0):\n    \"\"\"\n    can use np.var(X, axis=axis, ddof=ddof)\n    ddof: Delta Degrees of Freedom, 贝塞尔修正,\n    https://dfrieds.com/math/bessels-correction\n    \"\"\"\n    mean = np.ones(np.shape(X)) * X.mean(axis)\n    n_samples = np.shape(X)[axis]\n    n_samples -= ddof\n    return (np.sum((X - mean) * (X - mean), axis=axis) / n_samples)\n\n\ndef get_element_count(y):\n    labels = y\n    if isinstance(y, np.ndarray):\n        labels = y.flatten().tolist()\n    counts = {}\n    for label in labels:\n        counts[label] = counts.get(label, 0) + 1\n    return counts, len(labels)\n\n\ndef calculate_entropy(y):\n    \"\"\"\n    $$H(label)=-\\sum_{i}^{|label|}p_{i}log_{2}(p_{i})$$\n    \"\"\"\n    counts, y_len = get_element_count(y)\n    entropy = 0\n    for label in counts:\n        p = float(counts[label]) / y_len\n        entropy += -p * math.log(p, 2)\n    return entropy\n\n\ndef calculate_info_gain(y, y_split_parts):\n    total_entropy = calculate_entropy(y)\n    conditional_entropy = 0\n    for y_sub in y_split_parts:\n        p = float(len(y_sub)) / len(y)\n        conditional_entropy += p * calculate_entropy(y_sub)\n    info_gain = total_entropy - conditional_entropy\n    return info_gain\n\n\ndef calculate_info_gain_ratio(y, y_split_parts):\n    info_gain = calculate_info_gain(y, y_split_parts)\n    split_info = 0\n    for y_sub in y_split_parts:\n        p = float(len(y_sub)) / len(y)\n        split_info += -p * math.log(p, 2)\n    return info_gain / split_info\n", "meta": {"hexsha": "57af50bef5010daf8d6142c02a5dd32ba92e2ee3", "size": 1551, "ext": "py", "lang": "Python", "max_stars_repo_path": "mle/utils/data_operation.py", "max_stars_repo_name": "chaoswork/MachineLearningEssentials", "max_stars_repo_head_hexsha": "4ac237720152b53ae7f69e3d33b03f55e76c9061", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mle/utils/data_operation.py", "max_issues_repo_name": "chaoswork/MachineLearningEssentials", "max_issues_repo_head_hexsha": "4ac237720152b53ae7f69e3d33b03f55e76c9061", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mle/utils/data_operation.py", "max_forks_repo_name": "chaoswork/MachineLearningEssentials", "max_forks_repo_head_hexsha": "4ac237720152b53ae7f69e3d33b03f55e76c9061", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2881355932, "max_line_length": 67, "alphanum_fraction": 0.6286266925, "include": true, "reason": "import numpy", "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.8962513627417531, "lm_q1q2_score": 0.858530181396405}}
{"text": "import numpy as np\n\n\ndef sigmoid(x):\n    return 1.0 / (1 + np.exp(-x))\n\n\ndef _insert_bias(x):\n    if x.ndim == 1:\n        x = x[:, np.newaxis]\n    x = np.hstack((np.ones((x.shape[0], 1)), x))\n    return x\n\n\nclass LogisticRegression(object):\n    def __init__(self, alpha, max_iter, lamd=0):\n        self.alpha = alpha\n        self.max_iter = max_iter\n        self.lamd = lamd\n\n    def fit(self, x, y, intercept_adapt=True):\n        if intercept_adapt:\n            x = _insert_bias(x)\n        self.x = x\n        self.y = y\n\n        self.w = np.random.normal(1, 0.1, (self.x.shape[1],))\n        self.loss = []\n        self.w_list = []\n        for _ in range(self.max_iter):\n            dw = self.gradient(self.w)\n            self.w -= self.alpha * dw\n            self.w_list.append(self.w)\n            self.loss.append(self.cost(self.x, self.y, False))\n        return self.loss, self.w_list\n\n    def predict(self, x, intercept_adapt=True):\n        if intercept_adapt:\n            x = _insert_bias(x)\n        return sigmoid(x.dot(self.w))\n\n    def gradient(self, w):\n        err = self.predict(self.x, False) - self.y\n        dw = self.x.T.dot(err) / self.y.shape[0]\n        dw[1:] += self.lamd / self.y.shape[0] * w[1:]\n        return dw\n\n    def cost(self, x, y, intercept_adapt=True):\n        p = self.predict(x, intercept_adapt)\n        h = y * np.log(p) + (1-y) * np.log(1-p)\n        return -np.mean(h) + self.lamd/2.0/y.shape[0]*np.sum(self.w[1:]**2)\n\n\nclass MutiLogisticRegression(LogisticRegression):\n    def __init__(self, k, *args, **kwargs):\n        self.k = k\n        super(MutiLogisticRegression, self).__init__(*args, **kwargs)\n\n    def fit(self, x, y, intercept_adapt=True):\n        if intercept_adapt:\n            x = _insert_bias(x)\n        self.x = x\n        self.y = y\n        self.w = np.random.normal(1, 0.1, size=(self.k, self.x.shape[1]))\n        self.loss = []\n        self.w_list = []\n        for _ in range(self.max_iter):\n            dw = self.gradient(self.w)\n            self.w -= self.alpha * dw\n            self.w_list.append(self.w)\n            self.loss.append(self.cost(self.x, self.y, False))\n        return self.loss, self.w_list\n\n    def gradient(self, w):\n        err = self.predict(self.x, False) - self.y\n        dw = err.T.dot(self.x) / self.y.shape[0]\n        dw[1:] += self.lamd / self.y.shape[0] * w[1:]\n        return dw\n\n    def predict(self, x, intercept_adapt=True):\n        if intercept_adapt:\n            x = _insert_bias(x)\n        return sigmoid(x.dot(self.w.T))\n\n    def cost(self, x, y, intercept_adapt=True):\n        p = self.predict(x, intercept_adapt)\n        h = y * np.log(p) + (1-y) * np.log(1-p)\n        return -np.mean(h, axis=0) + self.lamd/self.y.shape[0]*np.sum(self.w**2, axis=1)\n\n", "meta": {"hexsha": "4c498cb459612e94a15310eafa8bf743500ec5bc", "size": 2743, "ext": "py", "lang": "Python", "max_stars_repo_path": "logistic_regression.py", "max_stars_repo_name": "ShadowAZL/ml_learn", "max_stars_repo_head_hexsha": "25790bd0511a585c830f69c7d096dbcea07e40ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "logistic_regression.py", "max_issues_repo_name": "ShadowAZL/ml_learn", "max_issues_repo_head_hexsha": "25790bd0511a585c830f69c7d096dbcea07e40ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logistic_regression.py", "max_forks_repo_name": "ShadowAZL/ml_learn", "max_forks_repo_head_hexsha": "25790bd0511a585c830f69c7d096dbcea07e40ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4777777778, "max_line_length": 88, "alphanum_fraction": 0.5497630332, "include": true, "reason": "import numpy", "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321452198369, "lm_q2_score": 0.8902942370375484, "lm_q1q2_score": 0.8585298315438876}}
{"text": "import numpy as np\n\ndef X(theta):\n    '''X-rotation'''\n    return np.array([[np.cos(theta/2),-1j*np.sin(theta/2)],[-1j*np.sin(theta/2),np.cos(theta/2)]])\ndef Z(theta):\n    '''Z-rotation'''\n    return np.array([[np.exp(-1j*theta/2),0],[0,np.exp(1j*theta/2)]])\n\t\ndef angles_of_3_Euler_pulses(U):\n    '''We now convert our unitary into three pulses with rotation angles 𝛼, 𝛽 and 𝛾'''\n    x_1=np.real(U[0,0])\n    x_2=np.imag(U[0,0])\n    x_3=np.real(U[0,1])\n    x_4=np.imag(U[0,1])\n\n    if x_1==0:\n        theta_x2_x1=np.inf\n    else:\n        theta_x2_x1=x_2/x_1\n    if x_2==0:\n        theta_x3_x2=np.inf\n    else:\n        theta_x3_x2=x_3/x_2\n    if x_4==0:\n        theta_x3_x4=np.inf\n    else:\n        theta_x3_x4=x_3/x_4\n        \n    alpha=np.arctan(-theta_x2_x1)+np.arctan(theta_x3_x4)\n    gamma=np.arctan(-theta_x2_x1)-np.arctan(theta_x3_x4)\n    beta=2*np.arctan((theta_x3_x2*np.sin((alpha+gamma)/2))/(np.sin((alpha-gamma)/2)))\n    U_optimal_pulse_1=np.matmul(X(beta),Z(gamma))\n    U_optimal_pulse=np.matmul(Z(alpha),U_optimal_pulse_1)\n    print('\\n The overall rotation using optimal pulse sequence is the same: \\n')\n    print(U_optimal_pulse)\n    return alpha,beta,gamma\n\t\ndef mainfunc(list_of_rotation_type,list_of_rotation_angle):\n    '''Main function where we first make combined unitary before dividing it into pulses'''\n    ### generating combination U\n    U=np.array([[1,0],[0,1]])\n    for i in range(len(list_of_rotation_type)):\n        if list_of_rotation_type[i]=='X':\n            U_x=X(list_of_rotation_angle[i]*(np.pi/180))\n            U=np.matmul(U,U_x)\n        else:\n            U_z1=Z(np.pi/2)\n            U_x=X(list_of_rotation_angle[i]*(np.pi/180))\n            U_z2=Z(-np.pi/2)\n            U_y=np.matmul(U_z1,np.matmul(U_x,U_z2))\n            U=np.matmul(U,U_y)\n    print('\\n The overall rotation using input pulse sequence is: \\n')\n    print(U)\n    ### Identifying three pulses now\n    alpha,beta,gamma= angles_of_3_Euler_pulses(U)\n    print('\\n And the optimal pulse sequence is:\\n')\n    print('Z ( ',alpha*(180/np.pi),' ) X (',beta*(180/np.pi),') Z (',gamma*(180/np.pi),')')", "meta": {"hexsha": "fe2783839dadbcfa06e54acb10d7a7e9f8b0985b", "size": 2093, "ext": "py", "lang": "Python", "max_stars_repo_path": "Part2_function_file.py", "max_stars_repo_name": "Asadquantum/OQC_test", "max_stars_repo_head_hexsha": "11925d8572281031c07dab8721eefa34739402a5", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Part2_function_file.py", "max_issues_repo_name": "Asadquantum/OQC_test", "max_issues_repo_head_hexsha": "11925d8572281031c07dab8721eefa34739402a5", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Part2_function_file.py", "max_forks_repo_name": "Asadquantum/OQC_test", "max_forks_repo_head_hexsha": "11925d8572281031c07dab8721eefa34739402a5", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0862068966, "max_line_length": 98, "alphanum_fraction": 0.6235069279, "include": true, "reason": "import numpy", "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321448096903, "lm_q2_score": 0.8902942304882371, "lm_q1q2_score": 0.8585298215767347}}
{"text": "import numpy as np\nimport numpy.linalg as ln\nfrom numpy.linalg.linalg import norm\nimport numpy.random as rn\nimport matplotlib.pyplot as plt\n\ndef getTranspose(matrix):\n    tMatrix = [[0 for j in range(len(matrix))] for i in range(len(matrix[0]))]\n    for i in range(len(matrix)):\n        for j in range(len(matrix[0])):\n            tMatrix[j][i] = matrix[i][j]\n    return tMatrix\n\ndef backSub(matrix,right):\n    x = np.zeros_like(right,float)\n    for i in range(len(matrix)-1,-1,-1):\n        temp = right[i][0]\n        for j in range(len(matrix[i])-1, i, -1):\n            temp = temp - matrix[i][j] * x[j]\n        x[i] = temp / (matrix[i][i])\n    return x\n\ndef thinQR(a,b):\n    q,r = ln.qr(a,mode='reduced')\n    nB = np.dot(getTranspose(q), b)\n    x = backSub(r,nB)\n    return x\n\ndef normEq(a,b):\n    aTa = np.dot(getTranspose(a),a)\n    atB = np.dot(getTranspose(a),b) \n    # try:\n    #     r = ln.cholesky(aTa)\n    # except:\n    #     print(\"> Not positive definite\\n\\n\\n\\n\\n\")\n    #     return None\n    y = ln.solve(aTa,atB)\n    return y# ln.solve(getTranspose(r),y)\n\ndef errFunc(xPoints, fun, poly):\n    tempT = 0\n    tempB = 0\n    for i in xPoints:\n        tempT = tempT + np.power((fun(i) - np.polyval(poly,i)),2)\n        tempB = tempB + np.power(fun(i),2)\n    return np.sqrt(tempT/tempB)\n\n\ndef main():\n    # Part 1\n    xPoints = np.linspace(-1,1,33)\n    func = lambda x: np.sin(2*np.pi*x)+ np.cos(3*np.pi*x)\n    yPoints = func(xPoints)\n    trueTable = [[t,func(t)] for t in xPoints]\n    a = [[np.power(trueTable[i][0],t) for t in range(7)] for i in range(len(trueTable))]\n    b = [[t[1]] for t in trueTable]\n    c = np.flip(thinQR(a,b))\n    trainR = [np.polyval(c,i)for i in xPoints]\n\n    # plt.xlabel(\"x\")\n    # plt.ylabel('y')\n    # plt.plot(xPoints,yPoints,'bo-',label=\"Function\")\n    # plt.plot(xPoints,trainR,'ro-',label=\"PolyEval\")\n    # plt.legend()\n    # plt.title(\"Part 1\")\n    # plt.show()\n\n    # Part Two\n    xTesting = rn.uniform(-1,1,100)\n    yTesting = func(xTesting)\n    testTable = [[t,func(t)] for t in xTesting]\n\n    neE = []\n    qrE = []\n    for d in range(1,32):\n        a = [[np.power(trueTable[i][0],t) for t in range(d)] for i in range(len(trueTable))]\n        b = [[t[1]] for t in trueTable]\n        qrC = np.flip(thinQR(a,b))\n        neC = np.flip(normEq(a,b))\n        neE.append(errFunc(xPoints,func,neC))\n        qrE.append(errFunc(xPoints,func,qrC))\n        # qrE.append(ln.norm(yTesting- np.polyval(qrC,xTesting))/ln.norm(yTesting))\n        # neE.append(ln.norm(yTesting- np.polyval(neC,xTesting))/ln.norm(yTesting))\n    \n\n    finalX = np.arange(1,32)\n    plt.semilogy(finalX,neE,'ro-',label=\"Normal Equaiton\")\n    plt.semilogy(finalX,qrE,'bx-',label=\"QR Equation\")\n    plt.xlabel(\"Degree\")\n    plt.ylabel(\"error\")\n    plt.legend()\n    plt.show()\n            \n\n\n\n\nmain()", "meta": {"hexsha": "85e1d00b933e674c31acf75bdc02487ca6986084", "size": 2804, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW9/homeworkScript.py", "max_stars_repo_name": "kai-handelman/NumericalAnalysisHomework", "max_stars_repo_head_hexsha": "2153dc39405168cabbf5c33c1238e64ceb96adf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW9/homeworkScript.py", "max_issues_repo_name": "kai-handelman/NumericalAnalysisHomework", "max_issues_repo_head_hexsha": "2153dc39405168cabbf5c33c1238e64ceb96adf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW9/homeworkScript.py", "max_forks_repo_name": "kai-handelman/NumericalAnalysisHomework", "max_forks_repo_head_hexsha": "2153dc39405168cabbf5c33c1238e64ceb96adf1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.612244898, "max_line_length": 92, "alphanum_fraction": 0.5798858773, "include": true, "reason": "import numpy,from numpy", "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214480969029, "lm_q2_score": 0.8902942304882371, "lm_q1q2_score": 0.8585298215767346}}
{"text": "from context import fe621\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.linalg import cholesky\nfrom scipy.stats import norm\n\n\n# Asset basket data\ninit_prices = np.array([100, 101, 98])\nmu_vec = np.array([0.03, 0.06, 0.02])\nsigma_vec = np.array([0.05, 0.2, 0.15])\ncorr_mat = np.array([[1.0, 0.5, 0.2],\n                     [0.5, 1.0, -0.4],\n                     [0.2, -0.4, 1.0]])\n\n# Performing Cholesky decomposition\nL = cholesky(corr_mat, lower=True)\n\n# Defining simulation parameters\ndt = 1 / 365\nttm = 100 / 365\nsim_count = 1000\neval_count = int(ttm / dt)\nrf = 0.06\n\n# Defining process function\nst = lambda x, volatility, mu: (mu * dt) + (volatility * np.sqrt(dt) * x)\n\n# NOTE: See the following link for how I figured out correlating the random\n#       variables with the Cholesky decomposition of the correlation matrix.\n# https://scipy-cookbook.readthedocs.io/items/CorrelatedRandomSamples.html\n\ndef partB():\n    \"\"\"Solution to 3(b)\n    \"\"\"\n\n    # Defining simulation function\n    def sim_func(x: np.array) -> np.array:\n        # Correlating random variables\n        x = np.dot(L, x)\n\n        return np.array([init_prices[i] * np.exp(np.cumsum(\n            st(x[i], sigma_vec[i], mu_vec[i])))\n            for i in range(0, 3)])\n\n    # Running simulation\n    sim_results = fe621.monte_carlo.monteCarloSkeleton(\n        sim_count=sim_count,\n        eval_count=eval_count,\n        sim_func=sim_func,\n        sim_dimensionality=3\n    )\n\n    # Reshaping as per question specs\n    # (rows: time step, col: simulation, z: asset)\n    sim_results = np.swapaxes(sim_results, 0, 1)  # sims to columns\n    sim_results = np.swapaxes(sim_results, 0, 2)  # assets to z, time to row\n\n    # Importing required packages for plotting\n    # Note: Doing this here so I can use the debugger in other sections\n    #       without the python-framework macOS installation issue\n\n    # Importing plotting libs\n    from mpl_toolkits.mplot3d import Axes3D\n    import matplotlib.pyplot as plt\n\n    # Isolating data for each axis\n    fig = plt.figure()\n    ax = fig.gca(projection='3d')\n\n    # Simulation number\n    sim = 1\n\n    x_vals = sim_results[:, sim, 0]\n    y_vals = sim_results[:, sim, 1]\n    z_vals = sim_results[:, sim, 2]\n    # Plotting surface\n    ax.plot(x_vals, y_vals, z_vals)\n\n    # Formatting plot\n    ax.set_xlabel('Asset 1 Price ($)')\n    # Setting y label\n    ax.set_ylabel('Asset 2 Price ($)')\n    # Setting z label\n    ax.set_zlabel('Asset 3 Price ($)')\n\n    # Setting plot dimensions to tight\n    plt.tight_layout()\n\n    # Saving to file\n    plt.savefig(fname='Homework 4/bin/correlated_bm_path.png')\n\n    # Closing plot\n    plt.close()\n\n\ndef partC():\n    \"\"\"Solution to 3(c)\n    \"\"\"\n    \n    strike = 100\n    a_weights = np.array([1 / 3] * 3)\n\n    # Defining simulation function\n    def sim_func(x: np.array) -> float:\n        # Correlating random variables\n        x = np.dot(L, x)\n\n        # Computing terminal asset prices for each of the 3 correlated assets\n        term_prices = np.array([init_prices[i] * np.exp(np.sum(\n            st(x[i], sigma_vec[i], mu_vec[i])))\n            for i in range(0, 3)])\n        \n        # Computing weighted basket price, and comparing to strike price\n        term_price = np.sum(np.multiply(term_prices, a_weights))\n\n        # Computing both put and call prices; returning\n        call_price = np.exp(-1 * rf * ttm) * np.maximum(term_price - strike, 0)\n        put_price = np.exp(-1 * rf * ttm) * np.maximum(strike - term_price, 0)\n\n        return np.array([call_price, put_price])\n\n    # Running simulation\n    sim_results = fe621.monte_carlo.monteCarloSkeleton(\n        sim_count=sim_count,\n        eval_count=eval_count,\n        sim_func=sim_func,\n        sim_dimensionality=3\n    )\n\n    # Output dictionary\n    output = dict()\n\n    # Iterating over option types, computing MC stats for each\n    for idx, opt_type in zip([0, 1], ['European Call', 'European Put']):\n        output[opt_type] = fe621.monte_carlo.monteCarloStats(sim_results.T[idx])\n\n    # Building output dataframe, formatting and saving to CSV\n    out_df = pd.DataFrame(output)\n    out_df.index = ['Estimate', 'Standard Deviation', 'Standard Error']\n    out_df.to_csv('Homework 4/bin/q3_basket_option.csv')\n\n\ndef partD():\n    \"\"\"Solution to 3(d)\n    \"\"\"\n    \n    # Simulation constants\n    strike = 100\n    a_weights = np.array([1 / 3] * 3)\n    barrier = 104\n\n    # Defining simulation function\n    def sim_func(x: np.array) -> float:\n        # Correlating random variables\n        x = np.dot(L, x)\n\n        # Computing asset prices for each of the 3 correlated assets\n        asset_prices = np.array([init_prices[i] * np.exp(np.cumsum(\n            st(x[i], sigma_vec[i], mu_vec[i])))\n            for i in range(0, 3)])\n\n        # Condition 1 - testing asset 2 against barrier\n        if np.any(np.greater(asset_prices[1], barrier)):\n            # Option value is equal to EU call on asset 2\n            return np.exp(-1 * rf * ttm) * np.maximum(0,\n                asset_prices[1][-1] - strike)\n        \n        # Condition 2 - testing max of asset 2 against max of asset 3\n        if (np.max(asset_prices[1]) > np.max(asset_prices[2])):\n            # Option value is (asset 2 term price ^2 - K)+\n            return np.exp(-1 * rf * ttm) * np.maximum(0,\n                np.power(asset_prices[1][-1], 2) - strike)\n        \n        # Condition 3 - testing average price of asset 2 against asset 3\n        if (np.mean(asset_prices[1]) > np.mean(asset_prices[2])):\n            # Option value is (avg asset 2 price - K)+\n            return np.exp(-1 * rf * ttm) * np.maximum(0,\n                np.mean(asset_prices[1]) - strike)\n        \n        # Otherwise, option is vanilla call option on the basket (same as (c))\n        term_price = np.sum(np.multiply(asset_prices[:, -1], a_weights))\n        return np.exp(-1 * rf * ttm) * np.maximum(term_price - strike, 0)\n\n    # Running simulation\n    sim_results = fe621.monte_carlo.monteCarloSkeleton(\n        sim_count=sim_count,\n        eval_count=eval_count,\n        sim_func=sim_func,\n        sim_dimensionality=3\n    )\n\n    # Building output dataframe with stats, formatting and saving to CSV\n    out_df = pd.Series(fe621.monte_carlo.monteCarloStats(sim_results))\n    out_df.index = ['Estimate', 'Standard Deviation', 'Standard Error']\n    out_df.to_csv('Homework 4/bin/q3_exotic_option_mc.csv')\n\n\nif __name__ == '__main__':\n    # 3(b)\n    # partB()\n\n    # 3(c)\n    # partC()\n\n    # 3(d)\n    partD()\n", "meta": {"hexsha": "9030ba467880229f0e74b6246bd9b4e90131e100", "size": 6457, "ext": "py", "lang": "Python", "max_stars_repo_path": "Homework 4/question_solutions/question_3.py", "max_stars_repo_name": "rukmal/FE-621-Homework", "max_stars_repo_head_hexsha": "9c7cef7931b58aed54867acd8e8cf1928bc6d2dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-04-29T04:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T07:49:08.000Z", "max_issues_repo_path": "Homework 4/question_solutions/question_3.py", "max_issues_repo_name": "rukmal/FE-621-Homework", "max_issues_repo_head_hexsha": "9c7cef7931b58aed54867acd8e8cf1928bc6d2dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homework 4/question_solutions/question_3.py", "max_forks_repo_name": "rukmal/FE-621-Homework", "max_forks_repo_head_hexsha": "9c7cef7931b58aed54867acd8e8cf1928bc6d2dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-23T07:32:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T07:32:44.000Z", "avg_line_length": 30.8947368421, "max_line_length": 80, "alphanum_fraction": 0.6210314387, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214470715362, "lm_q2_score": 0.8902942159342104, "lm_q1q2_score": 0.8585298066290965}}
{"text": "import math\r\nimport time                         # import time to use for performance analysis\r\nimport numpy as np                  # import numpy for array space\r\nimport matplotlib.pyplot as plt     # import matplotlib for graphing functions\r\nfrom scipy.integrate import odeint  # import scipy to use the ordinary differencial equation integral function\r\n\r\n# Ordinary Differential Equation\r\ndef dy_dx(y, x):                    # takes inputs y and x\r\n    return 3*x + 2*y      # returns the function y/(e^x - 1)\r\n\r\n\r\n# Runge-Kutta Forumla based off the formula used in class\r\ndef rungeKutta(y, x, h):                                # takes y, x, and h inputs\r\n    k1 = dy_dx(y, x)                                    # solves k1 using the differential equation function\r\n    k2 = dy_dx(y + ((0.5 * h) * k1), x + 0.5 * h)       # solves k2 based on the answer from k1 using the differential equation function\r\n    k3 = dy_dx(y + ((0.5 * h) * k2), x + 0.5 * h)       # solves k3 based on the answer from k2 using the differential equation function\r\n    k4 = dy_dx(y + (h * k3), x + h)                     # solves k4 based on the answer from k3 using the differential equation function\r\n\r\n    t4 = (1.0 / 6.0) * (k1 + (2 * k2) + (2 * k3) + k4)  # solves for t4 by taking a 6th of k1 + 2*k2 + 2*k3 + k4\r\n\r\n    y = y + (t4 * h)                                    # solves for y by taking the initial y value and adding it to t4*h\r\n    return y                                            # returns y\r\n\r\n# initial variable values\r\ny = 4\r\n           # initial y value of 5 as outlined in the assignment\r\nx = 0           # initial x value of 1 as outlined in the assignment\r\nh = 0.02        # initial h value of 0.02 as outlined in the assignment\r\nn = 2000        # initial n value of 2000 chosen between 1000 or 2000 as outlined in the assignment\r\n\r\n# Runge-Kutta x and y arrays \r\nxsr = []        # x-space runge-kutta array to store the values of x for the runge-kutta function\r\nysr = []        # y-space runge-kutta array to store the values of y for the runge-kutta function\r\n\r\n# ODEint x and y arrays, solution, and time analysis\r\ntso = time.time()                               # time start for ODEint function solution\r\n\r\nxso = np.linspace(0.0, 0.2 , 30)       # x-space ODEint from 1 to n*h (40) plus 1 with a step size of n\r\nyso = odeint(dy_dx, y, xso)                     # y-space ODEint useing the odeint function from scicpy to find the y-space\r\n\r\nteo = time.time()                               # time end fore ODEint function solution\r\ntto = teo - tso                                 # total time the ODEint function to solve\r\n\r\n# graphing ODEint\r\nplt.title(\"ODE Function Analysis\")          # set the title of the graph\r\nplt.xlabel(\"x\")                                             # set the x label on the graph\r\nplt.ylabel(\"y\")                                             # set the y label on the graph\r\nplt.plot(xso, yso, 'g-', label = \"ODEint\", linewidth = 2)   # set the ODE line to be red and label it\r\n\r\nplt.legend()                                                # shows the legend on the graph\r\nplt.savefig('Exact Solution1.png')                                                  # displays the graph\r\n\r\n# Runge-Kutta solution and time analysis\r\ntsr = time.time()                               # time start for runge-kutta function solution\r\n\r\nwhile (x <= 0.2):                           # for loop to run the runge-kutta function n number of times\r\n    xsr.append(x)                               # append the x value to the x-space runge-kutta array\r\n    ysr.append(y)                               # append the y value to the y-space runge-kutta array\r\n    \r\n    y = rungeKutta(y, x, h)                     # update the y value using the rungeKutta function\r\n    \r\n    x += h                                      # update the x value by moving one step forward (0.02)\r\n\r\nter = time.time()                               # time end for runge-kutta function solution\r\nttr = ter - tsr                                 # total time the runge-kutta function to solve\r\n\r\ntd = ttr - tto                                  # time difference between ODEint and runge-kutta function\r\n\r\n# graphing runge-kutta\r\nplt.title(\"Runge-Kutta Function Analysis\")          # set the title of the graph\r\nplt.xlabel(\"x\")                                             # set the x label on the graph\r\nplt.ylabel(\"y\")                                             # set the y label on the graph\r\nplt.plot(xsr, ysr, 'b--', label = \"Runge Kutta\")             # set the runge-kutta to be blue and label it\r\n\r\nplt.legend()                                                # shows the legend on the graph\r\nplt.savefig('Runge_Kutta1.png')                                                  # displays the graph\r\n\r\n# solutions\r\nprint(\"\\nODEint Solution:            \", yso[-1])    # ODEint function solution\r\nprint(\"Runge-Kutta Solution:        \", ysr[-1])     # Runge-Kutta function solution\r\n\r\n# Print statement for time difference\r\nprint(\"\\nODEint Time:         \", tto)               # print the ODEint time\r\nprint(\"Runge Kutta Time:    \", ttr)                 # print the runge-kutta time\r\nprint(\"ODEint is \", td, \" seconds faster\\n\\n\")      # print the difference between ODEint and runge-kutta\r\n\r\n# error calculation\r\nerror = 0                                                           # initial error value of 0\r\nerrorRange = []                                                     # array to store error over xn\r\nerrorSpace = np.linspace(0.0,0.2, 30)                   # error space for error analysis\r\nfor i in range(len(ysr)):                                   # for loop to run through every x values\r\n    error += (np.abs(ysr[i] - yso[i])/yso[i]) * 100                 # sum all the error values using the percentage error formula\r\n    errorRange.append((np.abs(ysr[i] - yso[i])/yso[i]) * 100)\r\n    print(\"Percent Error at x =\", i, \":\", (np.abs(ysr[i] - yso[i])/yso[i]) * 100)   # print error at each x value\r\n\r\nprint(\"\\nAverage Error Percent:\", error/((int)(n * h) + 1), \"\\n\")     # print the total error divided by the total number of x values\r\n\r\n# graphing error\r\n#plt.title(\"Error Analysis\")                                     # set the title of the graph\r\n#plt.xlabel(\"xn\")                                                # set the x label on the graph\r\n#plt.ylabel(\"error\")                                             # set the y label on the graph\r\n#plt.plot(errorSpace, errorRange, label = \"Error over Xn\")       # create the line and label it\r\n#plt.legend()                                                    # shows the legend on the graph\r\n#plt.show()                                                      # displays the graph\r\n#\r\n# graphing both functions\r\nplt.title(\"Runge-Kutta and ODE Function Analysis\")          # set the title of the graph\r\nplt.xlabel(\"x\")                                             # set the x label on the graph\r\nplt.ylabel(\"y\")                                             # set the y label on the graph\r\nplt.plot(xso, yso, 'r-', label = \"ODEint\", linewidth = 2)   # set the ODE line to be red and label it\r\nplt.plot(xsr, ysr, 'bo', label = \"Runge Kutta\")             # set the runge-kutta to be blue and label it\r\nplt.legend()                                                # shows the legend on the graph\r\nplt.savefig('Comparison1.png')  ", "meta": {"hexsha": "e6bbebca12b8bf8e8ea3ef87f040de20819ab102", "size": 7360, "ext": "py", "lang": "Python", "max_stars_repo_path": "PSET2/P2/rk4_1.py", "max_stars_repo_name": "MonitSharma/Computational-Methods-in-Physics", "max_stars_repo_head_hexsha": "e3b2db36c37dd5f64b9a37ba39e9bb267ba27d85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PSET2/P2/rk4_1.py", "max_issues_repo_name": "MonitSharma/Computational-Methods-in-Physics", "max_issues_repo_head_hexsha": "e3b2db36c37dd5f64b9a37ba39e9bb267ba27d85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PSET2/P2/rk4_1.py", "max_forks_repo_name": "MonitSharma/Computational-Methods-in-Physics", "max_forks_repo_head_hexsha": "e3b2db36c37dd5f64b9a37ba39e9bb267ba27d85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.1327433628, "max_line_length": 137, "alphanum_fraction": 0.5248641304, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731169394881, "lm_q2_score": 0.8918110461567923, "lm_q1q2_score": 0.858522519524825}}
{"text": "#ZADANIE 1\n#Napisz program realizujacy poszukiwanie miejsc zerowych\n#funkcji a) – b). Wykorzystaj metode siecznych oraz metodę Newtona-\n#Raphsona. Stworz odpowiednie funkcje implementujace wymienione\n#metody poszukiwania miejsc zerowych. Dobierz odpowiednio obszary\n#wyszukiwania. Wykonaj analize bledow. Opisz w sprawozdaniu wnioski.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef fxA(x):\n    return 7 * x**5 + 9 * x**2 + 3 * x\n\ndef fxB(x):\n    return (1 / ((x - 0.3)**2 + 0.01)) - (1 / ((x - 0.8)**2 + 0.04))\n\ndef secant(fx, a, b, err):\n    fb = fx(b)\n    while np.absolute(fb) > err:\n        midPoint = b - (b - a) * fb / (fb-fx(a))\n        a = b\n        b = midPoint\n        fb = fx(b)\n    return b\n\ndef newton_raphson(fx, x0, err):\n    x = x0\n    h = 0.1e-5\n    while np.absolute(fx(x)) > err:\n        d1fx = (fx(x + h / 2.0) - fx(x - h / 2.0)) / h\n        x = x - fx(x) / d1fx\n    return x\n\nprint(\"Test metody siecznych - funkcja A\")\nprint(\"x1 = \", secant(fxA, -3., -1., 0.0001))\nprint(\"x2 = \", secant(fxA, 0., 1., 0.0001))\nprint(\"x3 = \", secant(fxA, 1., 2., 0.0001))\n\nprint(\"\\nTest metody newton_raphson - funkcja A\")\nprint(\"x1 = \", newton_raphson(fxA, -2., 0.0001))\nprint(\"x2 = \", newton_raphson(fxA, 0., 0.0001))\nprint(\"x3 = \", newton_raphson(fxA, 1.5, 0.0001))\n\nx = np.arange(-3, 3, 0.1)\nplt.plot(x, fxA(x), 'r.')\nplt.grid(True)\nplt.show()\n\nprint(\"\\nTest metody siecznych - funkcja B\")\nprint(\"x1 = \", secant(fxB, -3., -1., 0.0001))\nprint(\"x2 = \", secant(fxB, 0., 1., 0.0001))\nprint(\"x3 = \", secant(fxB, 1., 2., 0.0001))\n\nprint(\"\\nTest metody newton_raphson - funkcja B\")\nprint(\"x1 = \", newton_raphson(fxB, -2., 0.0001))\nprint(\"x2 = \", newton_raphson(fxB, 0., 0.0001))\nprint(\"x3 = \", newton_raphson(fxB, 1.5, 0.0001))\n\nx = np.arange(-3, 3, 0.1)\nplt.plot(x, fxB(x), 'r.')\nplt.grid(True)\nplt.show()\n\n#Program umozliwia znalezienie miejsc zerowych funkcji na trzy sposoby:\n#- metody graficznej,\n#- metody siecznych,\n#- metody Newthona-Raphsona.\n#Przedstawione w programie metody znalezienia miejsc zerowych nie sa idealne.\n#Metody siecznych i Newthona-Raphsona nie zwracają dokladnych wartosci miejsc zerowych.", "meta": {"hexsha": "148175b56e28247e26d802142381963b5a50e038", "size": 2126, "ext": "py", "lang": "Python", "max_stars_repo_path": "MN_lab_9/MN_lab9_zad_1.py", "max_stars_repo_name": "matbocz/kurs-mn-python-pwsz-elblag", "max_stars_repo_head_hexsha": "629d778be7c5d3b6cc217b7ba48e2e0d55ccdf36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MN_lab_9/MN_lab9_zad_1.py", "max_issues_repo_name": "matbocz/kurs-mn-python-pwsz-elblag", "max_issues_repo_head_hexsha": "629d778be7c5d3b6cc217b7ba48e2e0d55ccdf36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MN_lab_9/MN_lab9_zad_1.py", "max_forks_repo_name": "matbocz/kurs-mn-python-pwsz-elblag", "max_forks_repo_head_hexsha": "629d778be7c5d3b6cc217b7ba48e2e0d55ccdf36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8115942029, "max_line_length": 87, "alphanum_fraction": 0.632173095, "include": true, "reason": "import numpy", "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971129093889291, "lm_q2_score": 0.8840392741081575, "lm_q1q2_score": 0.8585162592272017}}
{"text": "import copy\nimport math\nimport numpy as np\nfrom sympy import *\nimport matplotlib.pyplot as plt\nx,t = symbols('x t')\n\ndef graficotrap(f,a,b):\n    fig, ax = plt.subplots()\n    z = np.arange(a,b+0.001,0.001)\n\n    y = lambdify(x, f, \"numpy\")\n\n    pontos = [[a,b],[y(a), y(b)]]\n\n    ax.fill_between([a,b],pontos[1], color=\"red\")\n    ax.plot(z,y(z), \"black\")\n    ax.plot(pontos[0],pontos[1])\n    plt.show()\n\n\ndef  trapezio(f, a, b):\n    h = b - a\n    print(\"O valor de h é \", h)\n    deriv = h/2*(f.subs(x,a)+f.subs(x,b))\n    exact = integrate(f, (x, a, b))\n    print(\"Pela Regra do Trapézio, temos que a integral\")\n    pprint(Integral(f, (x, a, b)), use_unicode=True)\n    print(\"é aproximadamente\", deriv)\n\n    print(\"\\nComo comparação, o valor exato da integral\")\n    pprint(Integral(f, (x, a, b)), use_unicode=True)\n    print(\"é\", exact)\n\n    f = diff(f, x, 2)\n    maior = abs(f.subs(x,a))\n    if abs(f.subs(x,b)) > maior:\n        maior = abs(f.subs(x,b))\n    E = (-h**3/12)*maior\n    print(\"\\nLimitante\")\n    print(\"|E| <=\", abs(E))\n\n# def f(x): return log(x)+x\n# trapezio(f(x), 0.5, 1)\n# graficotrap(f(x), 0.5, 1)\n\ndef trapezio_gen(f, a, b, n):\n    h = (b - a)/n\n    print(\"O valor de h é\", h)\n    xk = np.linspace(a,b,n+1)\n    fx = 0\n    for i in range(len(xk)):\n        if i == 0 or i == len(xk)-1:\n            fx += f.subs(x, xk[i])\n        else:\n            fx += 2*f.subs(x, xk[i])\n    deriv = (h/2)*fx\n    exact = integrate(f, (x, a, b))\n    print(\"Pela Regra do Trapézio, temos que a integral\")\n    pprint(Integral(f, (x, a, b)), use_unicode=True)\n    print(\"é aproximadamente\", deriv)\n\n    print(\"\\nComo comparação, o valor exato da integral\")\n    pprint(Integral(f, (x, a, b)), use_unicode=True)\n    print(\"é\", exact)\n\n    f = diff(f, x, 2)\n    maior = abs(f.subs(x,a))\n    if abs(f.subs(x,b)) > maior:\n        maior = abs(f.subs(x,b))\n    E = (h**2/12)*maior*(b-a)\n    print(\"\\nLimitante\")\n    print(\"|E| <=\", abs(E))\n\n\n# def f(x): return sqrt(x)\n# a = 1\n# b = 4\n# n = 6\n# trapezio_gen(f(x), a, b, n)\n# graficotrap(f(x),a, b)\n\ndef simpson13(f, a, b, n):\n    h = (b - a)/n\n    xk = np.linspace(a,b,n+1)\n    fx = 0\n    for i in range(len(xk)):\n        if i == 0 or i == len(xk)-1:\n            fx += f.subs(x, xk[i])\n        elif i % 2 == 0:\n            fx += 2*f.subs(x, xk[i])\n        else:\n            fx += 4*f.subs(x, xk[i])\n    deriv = (h/3)*fx\n    exact = integrate(f, (x, a, b)).evalf()\n\n    print(\"Pela Regra 1/3 de Simpson, temos que a integral\")\n    pprint(Integral(f, (x, a, b)), use_unicode=True)\n    print(\"é aproximadamente\", deriv)\n\n    print(\"\\nComo comparação, o valor exato da integral\")\n    pprint(Integral(f, (x, a, b)), use_unicode=True)\n    print(\"é\", exact)\n\n    f = diff(f, x, 4)\n    maior = abs(f.subs(x,a))\n    if abs(f.subs(x,b)) > maior:\n        maior = abs(f.subs(x,b))\n    E = (h**4/180)*maior*(b-a)\n    print(\"\\nLimitante\")\n    print(\"|E| <=\", abs(E.evalf()))\n\ndef calc_parabola_vertex(x1, y1, x2, y2, x3, y3):\n    denom = (x1-x2) * (x1-x3) * (x2-x3);\n    A     = (x3 * (y2-y1) + x2 * (y1-y3) + x1 * (y3-y2)) / denom;\n    B     = (x3*x3 * (y1-y2) + x2*x2 * (y3-y1) + x1*x1 * (y2-y3)) / denom;\n    C     = (x2 * x3 * (x2-x3) * y1+x3 * x1 * (x3-x1) * y2+x1 * x2 * (x1-x2) * y3) / denom;\n    return A,B,C\n\ndef graficoSimpson(f,a,b,n):\n    xk = np.linspace(a,b,n+1)\n    fx = []\n    y = []\n    for j in range(n-1):\n        for i in range(len(xk)):\n            fx.append(f.subs(x,xk[i]))\n        A,B,C = calc_parabola_vertex(xk[j],fx[j],xk[j+1],fx[j+1],xk[j+2],fx[j+2])\n        y.append(A*x**2 + B*x + C)\n\n    fig, ax = plt.subplots()\n    z = []\n    w = []\n    for i in range(n-1):\n        z.append(np.arange(xk[i],xk[i+2]+0.001,0.001))\n\n        w.append(lambdify(x, y[i], \"numpy\"))\n        ax.plot(z[i],w[i](z[i]))\n\n    n = np.arange(a,b+0.001,0.001)\n    m = []\n    for i in range(len(n)):\n        m.append(f.subs(x,n[i]))\n    ax.plot(n,m)\n    plt.show()\n\ndef simpson_tabela13(a,b,n,y):\n    h = (b - a)/n\n    xk = np.linspace(a,b,n+1)\n    fx = 0\n    for i in range(len(xk)):\n        if i == 0 or i == len(xk)-1:\n            fx += y[i]\n        elif i % 2 == 0:\n            fx += 2*y[i]\n        else:\n            fx += 4*y[i]\n    deriv = (h/3)*fx\n    print(\"O valor da integral é aproximadamente\", deriv)\n\n# def f(x): return x*exp(x)+1\n# a = 0\n# b = 3\n# n = 4\n# simpson13(f(x), a, b, n)\n# graficoSimpson(f(x), a, b, n)\n# a = 0\n# b = 6\n# n = 6\n# y = [0.21,0.32,0.42,0.51,0.82,0.91,1.12]\n# simpson_tabela13(a,b,n,y)\n\ndef simpson38(f,a,b,n):\n    h = (b-a)/n\n    xk = np.linspace(a,b,n+1)\n    fx = 0\n    for i in range(len(xk)):\n        if i == 0 or i == len(xk)-1:\n            fx += f.subs(x,xk[i])\n        elif i % 3 == 0:\n            fx += 2*f.subs(x,xk[i])\n        else:\n            fx += 3*f.subs(x,xk[i])\n    deriv = (3/8)*h*fx\n    exact = integrate(f, (x, a, b)).evalf()\n\n    print(\"Pela Regra 1/3 de Simpson, temos que a integral\")\n    pprint(Integral(f, (x, a, b)), use_unicode=True)\n    print(\"é aproximadamente\", deriv)\n\n    print(\"\\nComo comparação, o valor exato da integral\")\n    pprint(Integral(f, (x, a, b)), use_unicode=True)\n    print(\"é\", exact)\n\n    f = diff(f, x, 4)\n    maior = abs(f.subs(x,a))\n    if abs(f.subs(x,b)) > maior:\n        maior = abs(f.subs(x,b))\n    E = (h**4/80)*maior*(b-a)\n    print(\"\\nLimitante\")\n    print(\"|E| <=\", abs(E.evalf()))\n\ndef simpson_tabela38(a,b,n,y):\n    h = (b - a)/n\n    xk = np.linspace(a,b,n+1)\n    fx = 0\n    for i in range(len(xk)):\n        if i == 0 or i == len(xk)-1:\n            fx += y[i]\n        elif i % 3 == 0:\n            fx += 2*y[i]\n        else:\n            fx += 3*y[i]\n    deriv = (3/8)*h*fx\n    print(\"O valor da integral é aproximadamente\", deriv)\n\n# def f(x): return log(x+9)\n# a = 1\n# b = 7\n# n = 6\n# simpson38(f(x), a,b,n)\n# a = 0\n# b = 6\n# n = 6\n# y = [0.21,0.32,0.42,0.51,0.82,0.91,1.12]\n# simpson_tabela38(a,b,n,y)\n\ndef quadGauss(f, a, b, n):\n    table = [[[0.5773502692, 1],[-0.5773502692, 1]],\n             [[0.7745966692, 0.5555555556],[0, 0.8888888889],[-0.7745966692, 0.555555556]],\n             [[0.8611363116, 0.3478548451],[0.3399810436, 0.6521451549],[-0.3399810436, 0.6521451549],[0.8611363116, 0.3478548451]],\n             [[0.9061798459, 0.2369268850],[0.5384693101, 0.4786286705],[0, 0.5688888889],[-0.5384693101, 0.4786286705],[-0.9061798459, 0.2369268850]]]\n    \n    g = f.subs(x, ((1/2)*((b-a)*t+a+b)))\n    expr = lambdify(t, g, \"numpy\")\n    if n > 2:\n        soma = 0\n        for i in range(n):\n            soma += table[n-2][i][1]*expr(table[n-2][i][0])\n        result = ((b-a)/2)*soma\n    else:\n        soma = 0\n        for i in range(n):\n            soma += expr(table[n-2][i][0])\n        result = ((b-a)/2)*soma\n    print(\"O valor aproximado da integral\")\n    pprint(Integral(f, (x, a, b)), use_unicode=True)\n    print(\"é\", result)\n\n# def f(x): return x**2*log(x)\n# def f(x): return exp(-x**2)\n# def f(x): return sqrt(x)\n# def f(x): return sin(x)/x\n# def f(x): return exp(x)\n# def f(x): return exp(-x**2/2)\n# a = -1\n# b = 1\n# n = 3\n# quadGauss(f(x), a, b, n)\n", "meta": {"hexsha": "b35ff9f9b83daf3e985c9537bce7688c7703c624", "size": 6988, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lista5.py", "max_stars_repo_name": "EnzoItaliano/calculoNumericoEmPython", "max_stars_repo_head_hexsha": "be3161b823955620be71e0f94a3421288fd28ef0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-28T21:23:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-28T21:23:00.000Z", "max_issues_repo_path": "Lista5.py", "max_issues_repo_name": "EnzoItaliano/calculoNumericoEmPython", "max_issues_repo_head_hexsha": "be3161b823955620be71e0f94a3421288fd28ef0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lista5.py", "max_forks_repo_name": "EnzoItaliano/calculoNumericoEmPython", "max_forks_repo_head_hexsha": "be3161b823955620be71e0f94a3421288fd28ef0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9806949807, "max_line_length": 151, "alphanum_fraction": 0.5060103034, "include": true, "reason": "import numpy,from sympy", "num_tokens": 2711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488963, "lm_q2_score": 0.9019206844384594, "lm_q1q2_score": 0.8585051361178875}}
{"text": "import numpy as np\r\n\r\n# Global variables\r\nNMAX = 100\r\nERROR = 100\r\nTOLERANCE = 0.00001\r\nOP = 1\r\n\r\n\r\n# This Function is in charge of choosing the approximation criterion\r\ndef fe(a, b, op, f):\r\n    if op == 1:\r\n        return abs(f(a))\r\n    elif op == 2:\r\n        return abs(b - a)\r\n\r\n    elif op == 3:\r\n        return abs(b - a) / b\r\n\r\n\r\ndef regula_falsi(lower_end, upper_end, error, f, test):\r\n    # Assignment of interval values\r\n    a = lower_end\r\n    b = upper_end\r\n\r\n    # Error and initial number of iterations\r\n    error = 100\r\n    niter = 0\r\n\r\n    # Evaluation of the functions at the ends of the intervals\r\n    fa = f(lower_end)\r\n    fb = f(upper_end)\r\n\r\n    # Middle value\r\n    m = lower_end - fa * (upper_end - lower_end) / (fb - fa)\r\n\r\n    # Value of the function evaluated at the middle value\r\n    fm = f(m)\r\n    if not test:\r\n        print(\"# iter\\t\\t a \\t\\t f(a) \\t\\t b \\t\\t f(b) \\t\\t m \\t\\t f(m)  \\t\\t error\")\r\n        print(\r\n            \"{0} \\t\\t {1:6.4f} \\t {2:6.4f} \\t {3:6.4f} \\t {4:6.4f} \\t {5:6.4f} \\t {6:6.4f} \\t {7:6.4f}\".format(\r\n                niter, lower_end, fa, upper_end, fb, m, fm, error\r\n            )\r\n        )\r\n\r\n    # Cycle in charge of executing the iterations\r\n    while error > TOLERANCE and niter < NMAX:\r\n        m = lower_end - fa * (upper_end - lower_end) / (fb - fa)\r\n        if np.sign(fa) == np.sign(fm):\r\n            lower_end = m\r\n            fa = f(lower_end)\r\n        else:\r\n            upper_end = m\r\n            fb = f(upper_end)\r\n        m = lower_end - fa * (upper_end - lower_end) / (fb - fa)\r\n        fm = f(m)\r\n        error = fe(lower_end, upper_end, OP, f)\r\n        niter += 1\r\n        if not test:\r\n            print(\r\n                \"{0} \\t\\t {1:6.4f} \\t {2:6.4f} \\t {3:6.4f} \\t {4:6.4f} \\t {5:6.4f} \\t {6:6.4f} \\t {7:6.4f}\".format(\r\n                    niter, lower_end, fa, upper_end, fb, m, fm, error\r\n                )\r\n            )\r\n    if not test:\r\n        print(\r\n            \"The root of the function between [{0:6.4f},{1:6.4f}] is: {2:6.6f}\".format(\r\n                a, b, m\r\n            )\r\n        )\r\n    else:\r\n        return m\r\n\r\n\r\ndef f_test_1(x):\r\n    return np.cos(x) - x * (np.exp(x))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    lower_end = 0\r\n    upper_end = 2\r\n    regula_falsi(lower_end, upper_end, ERROR, f_test_1, False)\r\n\r\n\r\n# Tests\r\ndef test_1():\r\n    lower_end = 0\r\n    upper_end = 2\r\n    assert regula_falsi(lower_end, upper_end, ERROR,\r\n                        f_test_1, True) == 0.5177551702890896\r\n", "meta": {"hexsha": "1d86133896f568006635b030756514322bcb7d6e", "size": 2485, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/regulaFalsi.py", "max_stars_repo_name": "Youngermaster/ST0256-Numerical-Analysis", "max_stars_repo_head_hexsha": "cc8e53f0df9cceec88b2e0d52a6e534cc25295ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-16T01:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T01:50:36.000Z", "max_issues_repo_path": "Python/regulaFalsi.py", "max_issues_repo_name": "Youngermaster/ST0256-Numerical-Analysis", "max_issues_repo_head_hexsha": "cc8e53f0df9cceec88b2e0d52a6e534cc25295ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/regulaFalsi.py", "max_forks_repo_name": "Youngermaster/ST0256-Numerical-Analysis", "max_forks_repo_head_hexsha": "cc8e53f0df9cceec88b2e0d52a6e534cc25295ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0108695652, "max_line_length": 116, "alphanum_fraction": 0.4985915493, "include": true, "reason": "import numpy", "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833653, "lm_q2_score": 0.9019206679615432, "lm_q1q2_score": 0.8585051192025162}}
{"text": "## exercise 0.4.5\nimport numpy as np\n\n# Setup two ararys\nx = np.arange(1,6)\ny = np.arange(2,12,2)\n# Have a look at them by typing 'x' and 'y' in the console\n\n# There's a difference between matrix multiplication and elementwise \n# multiplication, and specifically in Python its also important if you \n# are using the multiply operator \"*\" on an array object or a matrix object!\n\n# Use the * operator to multiply the two arrays:\nx*y\n\n# Now, convert the arrays into matrices - \nx = np.asmatrix(np.arange(1,6))\ny = np.asmatrix(np.arange(2,12,2))\n# Again, have a look at them by typing 'x' and 'y' in the console\n\n# Try using the * operator just as before now:\nx*y \n# You should now get an error - try to explain why.\n\n# array and matrix are two data structures added by NumPy package to the list of\n# basic data structures in Python (lists, tuples, sets). We shall use both \n# array and matrix structures extensively throughout this course, therefore \n# make sure that you understand differences between them \n# (multiplication, dimensionality) and that you are able to convert them one \n# to another (asmatrix(), asarray() functions). \n# Generally speaking, array objects are used to represent scientific, numerical, \n# N-dimensional data. matrix objects can be very handy when it comes to \n# algebraic operations on 2-dimensional matrices.\n\n# The ambiguity can be circumvented by using explicit function calls:\nnp.transpose(y)             # transposition/transpose of y\ny.transpose()               # also transpose\ny.T                         # also transpose\n\nnp.multiply(x,y)            # element-wise multiplication\n\nnp.dot(x,y.T)               # matrix multiplication\nx @ y.T                     # also matrix multiplication\n\n\n# There are various ways to make certain type of matrices.\na1 = np.array([[1, 2, 3], [4, 5, 6]])   # define explicitly\na2 = np.arange(1,7).reshape(2,3)        # reshape range of numbers\na3 = np.zeros([3,3])                    # zeros array\na4 = np.eye(3)                          # diagonal array\na5 = np.random.rand(2,3)                # random array\na6 = a1.copy()                          # copy\na7 = a1                                 # alias\nm1 = np.matrix('1 2 3; 4 5 6; 7 8 9')   # define matrix by string\nm2 = np.asmatrix(a1.copy())             # copy array into matrix\nm3 = np.mat(np.array([1, 2, 3]))        # map array onto matrix\na8 = np.asarray(m1)                     # map matrix onto array\n  \n# It is easy to extract and/or modify selected items from arrays/matrices. \n# Here is how you can index matrix elements:\nm = np.matrix('1 2 3; 4 5 6; 7 8 9')\nm[0,0]\t\t# first element\nm[-1,-1]\t# last element\nm[0,:]\t\t# first row\nm[:,1]\t\t# second column\nm[1:3,-1]\t# view on selected rows&columns\n\n# Similarly, you can selectively assign values to matrix elements or columns:\nm[-1,-1] = 10000\nm[0:2,-1] = np.matrix('100; 1000')\nm[:,0] = 0\n\n# Logical indexing can be used to change or take only elements that \n# fulfil a certain constraint, e.g.\nm2[m2>0.5]          # display values in m2 that are larger than 0.5\nm2[m2<0.5] = 0      # set all elements that are less than 0.5 to 0 \n\n#Below, several examples of common matrix operations, \n# most of which we will use in the following weeks.\n# First, define two matrices:\nm1 = 10 * np.mat(np.ones([3,3]))\nm2 = np.mat(np.random.rand(3,3))\n\nm1+m2               # matrix summation\nm1*m2               # matrix product\nnp.multiply(m1,m2)  # element-wise multiplication\nm1>m2               # element-wise comparison\nm3 = np.hstack((m1,m2))    # combine/concatenate matrices horizontally \n# note that this is not equivalent to e.g. \n#   l = [m1, m2]\n# in which case l is a list, and l[0] is m1\nm4 = np.vstack((m1,m2))    # combine/concatenate matrices vertically \nm3.shape            # shape of matrix\nm3.mean()           # mean value of all the elements\nm3.mean(axis=0)     # mean values of the columns\nm3.mean(axis=1)     # mean values of the rows\nm3.transpose()      # transpose, also: m3.T\nm2.I                # compute inverse matrix\n", "meta": {"hexsha": "cdeec27eeebc2eda350717664f6ff24ba51dbed1", "size": 4013, "ext": "py", "lang": "Python", "max_stars_repo_path": "02_assignment/toolbox/Toolbox_Python02450/Scripts/ex0_4_5.py", "max_stars_repo_name": "LukaAvbreht/ML_projects", "max_stars_repo_head_hexsha": "8b36acdeb017ce8a57959c609b96111968852d5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "02_assignment/toolbox/Toolbox_Python02450/Scripts/ex0_4_5.py", "max_issues_repo_name": "LukaAvbreht/ML_projects", "max_issues_repo_head_hexsha": "8b36acdeb017ce8a57959c609b96111968852d5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02_assignment/toolbox/Toolbox_Python02450/Scripts/ex0_4_5.py", "max_forks_repo_name": "LukaAvbreht/ML_projects", "max_forks_repo_head_hexsha": "8b36acdeb017ce8a57959c609b96111968852d5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5353535354, "max_line_length": 81, "alphanum_fraction": 0.6461500125, "include": true, "reason": "import numpy", "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.9032942151647513, "lm_q1q2_score": 0.8585007401051051}}
{"text": "from scipy.optimize import rosen\nimport numpy as np\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nimport matplotlib.pyplot as plot\n\n\ndef rosenbrock(x):\n    \"\"\"The `Rosenbrock function <https://en.wikipedia.org/wiki/Rosenbrock_function>`_ is a non-convex function \n    used as a performance test problem for optimization algorithms. The function is defined by: \n\n    .. math ::\n\n        f(x,y) = (a-x)^2 + b(y-x^2)^2\n    \n    The global minimum is inside a long, narrow, parabolic shaped flat valley. To find the valley is trivial. \n    To converge to the global minimum, is difficult.\n    \n    `See more info <https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.rosen.html>`_\n\n    Args:\n        x (np.array or list): 1-D array of points at which the Rosenbrock function is to be computed.\n\n    Returns:\n        float: The value of the Rosenbrock function.\n\n    Examples:\n        >>> rosenbrock([1, 1])\n        0.0\n        >>> rosenbrock([0, 0])\n        1.0\n        >>> rosenbrock([1, 0])\n        100.0\n        >>> rosenbrock([0, 1])\n        101.0\n    \"\"\"\n    # return 100.0 * (x[1] - x[0] ** 2) ** 2 + (1.0 - x[0]) ** 2\n    return rosen(x)\n\n\ndef ackley(x):\n    \"\"\"`Ackley function <https://en.wikipedia.org/wiki/Ackley_function>`_\n\n    The Ackley function is a non-convex function used as a performance test problem for optimization algorithms. \n\n    Args:\n        x (np.array or list): array of two components ``(x_0, x_1)``.\n\n    Returns:\n        float: The value of the Ackley function.\n    \"\"\"\n    arg1 = -0.2 * np.sqrt(0.5 * (x[0] ** 2 + x[1] ** 2))\n    arg2 = 0.5 * (np.cos(2.0 * np.pi * x[0]) + np.cos(2.0 * np.pi * x[1]))\n    return -20.0 * np.exp(arg1) - np.exp(arg2) + 20.0 + np.e\n\n\ndef plot_function2D(x, y, z):\n    \"\"\"Plot 2D function with matplotlib\n    \n    Args:\n        x (np.array): X value.\n        y (np.array): Y value.\n        z (np.array): function value.\n    \n    Examples::\n\n        >> s = 0.05\n        >> X = np.arange(-2, 2.+s, s)\n        >> Y = np.arange(-2, 6.+s, s)\n        >> X, Y = np.meshgrid(X, Y)\n        >> f = rosenbrock([X, Y])\n        >> plot_function2D(X, Y, f)\n    \"\"\"\n    fig = plot.figure()\n    ax = fig.gca(projection=\"3d\")\n    surf = ax.plot_surface(\n        x, y, z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False\n    )\n    ax.zaxis.set_major_locator(LinearLocator(10))\n    ax.zaxis.set_major_formatter(FormatStrFormatter(\"%.02f\"))\n    fig.colorbar(surf, shrink=0.5, aspect=5)\n    plot.show()\n", "meta": {"hexsha": "1712fdc4f67482a1cf4598af66bc53804e09ebe6", "size": 2522, "ext": "py", "lang": "Python", "max_stars_repo_path": "optimization/functions.py", "max_stars_repo_name": "miguelgfierro/pybase", "max_stars_repo_head_hexsha": "de8e4f11ed5c655e748178e65195c7e70a9c98af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-02-07T21:36:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T22:37:04.000Z", "max_issues_repo_path": "optimization/functions.py", "max_issues_repo_name": "miguelgfierro/pybase", "max_issues_repo_head_hexsha": "de8e4f11ed5c655e748178e65195c7e70a9c98af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2019-05-18T23:58:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-09T16:45:35.000Z", "max_forks_repo_path": "optimization/functions.py", "max_forks_repo_name": "miguelgfierro/pybase", "max_forks_repo_head_hexsha": "de8e4f11ed5c655e748178e65195c7e70a9c98af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-10-06T06:10:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-08T12:58:46.000Z", "avg_line_length": 30.3855421687, "max_line_length": 113, "alphanum_fraction": 0.594369548, "include": true, "reason": "import numpy,from scipy", "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205502, "lm_q2_score": 0.90329420279886, "lm_q1q2_score": 0.8585007270836754}}
{"text": "import numpy as np\nfrom sklearn.linear_model import LinearRegression\n\nfrom visualization.linear_plots import plot_line\n\n\ndef ols_sklearn(feature, y_values):\n    \"\"\"\n    Solve Ordinary Least Squares using scikit-learn's LinearRegression\n    \"\"\"\n    estimator = LinearRegression()\n    # note that the intercept is built inside LinearRegression\n    estimator.fit(feature.reshape(-1, 1), y_values)\n    slope = estimator.coef_[0]\n    intercept = estimator.intercept_\n    return slope, intercept\n\n\ndef ols_numpy(feature, y_values):\n    \"\"\"\n    Solve Ordinary Least Squares using numpy.linalg.lstsq\n\n    Fits a line `y = mx + c`.\n    We can rewrite the line equation as `y = Ap`,\n    where A = [[x 1]] and p = [[m], [c]].\n\n    \"\"\"\n    ones = np.ones(y_values.shape[0])\n    matrix = np.vstack((feature, ones)).T\n    slope, intercept = np.linalg.lstsq(matrix, y_values, rcond=None)[0]\n    return slope, intercept\n\n\ndef ols_closed_form(feature, y_values):\n    \"\"\"\n    Compute the closed form of linear regression\n\n    slope = (A - B) / (C - D)\n    intercept = [ sum(output) / N ] - slope * [ sum(feature) / N ]\n\n    where,\n        A = sum(feature * output)\n        B = [sum(feature) * sum(output)] * 1/N\n        C = sum(feature^2)\n        D = sum(feature)^2 * 1/N\n\n    Returns: the intercept and slope values as a tuple\n\n    \"\"\"\n    size = feature.shape[0]\n    sum_features = np.sum(feature)\n    sum_squared_features = np.sum(feature * feature)\n    sum_output = np.sum(y_values)\n\n    # calculate slope\n    numerator = np.sum(feature * y_values) - (sum_features * sum_output) / size\n    denominator = sum_squared_features - (sum_features * sum_features) / size\n    slope = numerator / denominator\n\n    # use this computed slope to compute the intercept:\n    intercept = np.mean(y_values) - slope * np.mean(feature)\n    return slope, intercept\n\n\ndef regression_prediction(input_feature, intercept, slope):\n    \"\"\"\n    Calculate the predicted values based on the liner regression model\n\n    Returns:\n        the estimated value\n    \"\"\"\n    return intercept + slope * input_feature\n\n\ndef gds_form(feature, y_values, step_size: float = 1e-2, tolerance: float = 1e-3, max_iter: int = 1e2):\n    slope, intercept = ols_closed_form(feature, y_values)\n    magnitude = np.inf\n    iteration = 0\n    while magnitude > tolerance and iteration < max_iter:\n        predictions = regression_prediction(feature, intercept, slope)\n\n        # Compute the prediction errors (prediction - Y)\n        residual_errors = predictions - y_values\n\n        # Update the intercept\n        # The derivative of the cost for the intercept\n        # is the sum of the errors\n        intercept -= step_size * np.sum(residual_errors)\n\n        # Update the slope\n        # The derivative of the cost for the slope\n        # is the sum of the product of the errors and the input\n        partial = np.sum(feature * residual_errors)\n        slope -= step_size * partial\n\n        # Compute the magnitude of the gradient\n        magnitude = np.sqrt(sum(residual_errors ** 2, partial ** 2))\n        iteration += 1\n\n    return slope, intercept\n\n\nif __name__ == \"__main__\":\n    feature_data = np.array([0, 1, 2, 3])\n    y_data = np.array([-1, 0.2, 0.9, 2.1])\n    # feature_data = np.array([0, 1, 2, 3, 4])\n    # y_data = np.array([1, 3, 7, 13, 21])\n    # feature_data = np.array([0, 1, 2, 3, 4])\n    # y_data = np.array([1, 2, 3, 4, 5])\n\n    m, c = ols_numpy(feature_data, y_data)\n    print(f\"numpy based: ({m:.2f}, {c:.2f})\")\n\n    m, c = ols_sklearn(feature_data, y_data)\n    print(f\"sklearn based: ({m:.2f}, {c:.2f})\")\n\n    m, c = ols_closed_form(feature_data, y_data)\n    print(f\"closed form: ({m:.2f}, {c:.2f})\")\n\n    m, c = gds_form(feature_data, y_data)\n    print(f\"gds_form: ({m:.2f}, {c:.2f})\")\n\n    plot_line(feature_data, y_data, m, c)\n", "meta": {"hexsha": "1e7a984acd3d392603356315e522045710e46ae6", "size": 3791, "ext": "py", "lang": "Python", "max_stars_repo_path": "basic_ml/src/regression/least_squares/simple_linear_regression.py", "max_stars_repo_name": "jmetzz/ml-laboratory", "max_stars_repo_head_hexsha": "26b1e87bd0d80efa4f15280f7f32ad46d59efc1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-10T16:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T16:55:35.000Z", "max_issues_repo_path": "basic_ml/src/regression/least_squares/simple_linear_regression.py", "max_issues_repo_name": "jmetzz/ml-laboratory", "max_issues_repo_head_hexsha": "26b1e87bd0d80efa4f15280f7f32ad46d59efc1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2022-03-12T01:06:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:30:22.000Z", "max_forks_repo_path": "basic_ml/src/regression/least_squares/simple_linear_regression.py", "max_forks_repo_name": "jmetzz/ml-laboratory", "max_forks_repo_head_hexsha": "26b1e87bd0d80efa4f15280f7f32ad46d59efc1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5725806452, "max_line_length": 103, "alphanum_fraction": 0.6402004748, "include": true, "reason": "import numpy", "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953275038719013, "lm_q2_score": 0.9005297927918167, "lm_q1q2_score": 0.8584525730912438}}
{"text": "\"\"\" Correlation tests.\n\nAuthor:\n    \n    C.M. Gosmeyer\n\nDate:\n\n    Apr 2018\n\nReferences:\n\n    \"Introduction to Statistical Problem Solving in Geography\", \n    J.C. McGrew, Jr., A.J. Lembo, Jr., C.B. Monroe\n\n\"\"\"\n\nimport numpy as np\n\nclass PearsonCorrelation(object):\n    \"\"\" Determines if an association exists between two variables.\n\n    Requirements\n    ------------\n    1. Randaom sample of paired variables.\n    2. Variables have a linear association.\n    3. Variables are measured at interval or ratio scale.\n    4. Variables are bivariate normally distributed.\n\n    Null Hypthothesis\n    -----------------\n    H0 : PopulationCorrelationCoefficient = 0 \n        No correlation exists in the populations of the two variables.\n\n    Test Statistic\n    --------------\n\n        t = SampleCorrelationCoefficient / StandardErrorCorrelationEstimate\n\n    where\n\n        StandardErrorCorrelationEstimate =  sqrt(1 - SampleCorrelationCoefficient^2) / sqrt(NumberPairs - 2)\n    \"\"\"\n    def __init__(self, xs=[], ys=[], Z_x=None, Z_y=None):\n        \"\"\"\n        Parameters\n        ----------\n        xs : array\n            The X values.\n        ys : array\n            The Y values.\n        Z_x : array\n            [Optional in place of 'xs'] The Z-scores of X variable.\n        Z_y : array\n            [Optional in place of 'ys'] The Z-score of Y variable.\n        \"\"\"\n        self.xs = np.asarray(xs)\n        self.ys = np.asarray(ys)\n        self.Z_x = Z_x\n        self.Z_y = Z_y\n        self.n = len(self.xs)\n\n        self.t = None\n        self.r = self.correlation_coefficient()\n        self.standard_error = self.standard_error()\n        self.test_statistic()\n        self.test_stat = self.t\n\n    def correlation_coefficient(self):\n        if Z_x != None and Z_y != None:\n            r = sum( [self.Z_x[i]*self.Z_x[i] for i in range(len(self.Z_x))] ) / len(self.Z_x)\n        else:\n            sum_xy = sum( [self.xs[i]*self.ys[i] for i in range(self.n)] )\n            sum_x = sum( [self.xs[i] for i in range(self.n)] )\n            sum_y = sum( [self.ys[i] for i in range(self.n)] )\n            sum_x2 = sum( [self.xs[i]**2 for i in range(self.n)] )\n            sum_y2 = sum( [self.ys[i]**2 for i in range(self.n)] )\n            r = (sum_xy - (sum_x*sum_y / float(self.n))) / \\\n                (np.sqrt(sum_x2-((sum_x)**2/float(self.n)))*np.sqrt(sum_y2-((sum_y)**2/float(self.n))))\n\n        return r\n\n    def standard_error(self):\n        standard_error = np.sqrt((1-self.r**2)/(float(self.n)-2.))\n        return standard_error\n\n    def test_statistic(self):\n        self.t = self.r / self.standard_error\n\nclass SpearmanRankCorrelation(object):\n    \"\"\" Determines if an association exists between two variables.\n\n    Requirements\n    ------------\n    1. Randaom sample of paired variables.\n    2. Variables have a monotonically increasing or decreasing \n       association.\n    3. Variables are measured at ordinal scale or downgraded from\n       interval/ratio to ordinal.\n\n    Null Hypthothesis\n    -----------------\n    H0 : PopulationCorrelationCoefficient = 0\n        No relationship exists between the two variables in the \n        population.\n\n    Test Statistic\n    --------------\n\n        Z_rs = SampleCorrelationCoefficient * sqrt(NumberPairedValues - 1)\n\n        where\n\n        SampleCorrelationCoefficient = 1 - (6*(sum(DifferenceInRanksOfVariables)) / \n                                            (NumberPairedValues^3 - NumberPairedValues))\n\n    Notes\n    -----\n    1. Assumption that using Z distribution.\n    2. Assumption that the number of rank ties does not exceed 25% of data.\n    \"\"\"\n    def __init__(self, x_ranks, y_ranks):\n        \"\"\"\n        Parameters\n        ----------\n        x_ranks : array\n            Ranks of the X variable.\n        y_ranks : array\n            Ranks of the Y variable.\n        \"\"\"\n        self.x_ranks = x_ranks\n        self.y_ranks = y_ranks\n        self.n = len(x_ranks)\n        \n        self.Z_rs = None\n        rs = self.correlation_coefficient()\n        self.test_statistic()\n        self.test_stat = self.Z_rs\n\n    def correlation_coefficient(self):\n        sum_diffs = sum( [(self.x_ranks[i]-self.y_ranks[i])**2 for i in range(self.n)] )\n        rs = 1.0 - ((6*sum_diffs) / (self.n**3 - self.n))\n        return rs\n\n    def test_statistic(self):\n        self.Z_rs = self.rs * np.sqrt(self.n - 1.0)\n\n", "meta": {"hexsha": "83cf59111038f31c7da81b50666f5b6504aab2c5", "size": 4348, "ext": "py", "lang": "Python", "max_stars_repo_path": "stats/relationships/correlation_tests.py", "max_stars_repo_name": "cgosmeyer/learning_statistics", "max_stars_repo_head_hexsha": "f92e00b5f8481cb5933789f9ce9a699ddff2733d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stats/relationships/correlation_tests.py", "max_issues_repo_name": "cgosmeyer/learning_statistics", "max_issues_repo_head_hexsha": "f92e00b5f8481cb5933789f9ce9a699ddff2733d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stats/relationships/correlation_tests.py", "max_forks_repo_name": "cgosmeyer/learning_statistics", "max_forks_repo_head_hexsha": "f92e00b5f8481cb5933789f9ce9a699ddff2733d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3783783784, "max_line_length": 108, "alphanum_fraction": 0.5791168353, "include": true, "reason": "import numpy", "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013547, "lm_q2_score": 0.9005297847831081, "lm_q1q2_score": 0.8584525690429591}}
{"text": "\"\"\"Examples of how to samples from the inverse cdf function.\"\"\"\nimport typing as t\n\nimport numpy as np\n\n\ndef sample_exp(lambda_: float,\n               num_inst: int = 1,\n               random_state: t.Optional[int] = None) -> np.ndarray:\n    r\"\"\"Sample from the exponential distribution using the inverse cdf.\n\n    The c.d.f. of exponential distribution is\n    \\[\n    F(x; \\lambda) =\n        \\begin{cases}\n            1 - e^{-\\lambda x} & \\text{if } x \\geq 0 \\\\\n            0 & \\text{if } x < 0\n        \\end{cases}\n    \\]\n    Thus, its inverse is\n    $$\n    F^{-1}(x; \\lambda) = -\\frac{\\log(1 - x)}{\\lambda}\n    $$\n    if $x \\sim \\text{Uniform(0, 1)}$, then 1 - x and x\n    has the same distribution and, therefore, we can\n    replace 1 - x for x, which yields:\n    $$\n    F^{-1}(x; \\lambda) = -\\frac{\\log(x)}{\\lambda}\n    $$\n\n    Drawing random samples $x \\sim \\text{Uniform(0, 1)}$,\n    we can use any version of the $F^{-1}$ to draw samples\n    from the exponential function.\n    \"\"\"\n    if lambda_ <= 0:\n        raise ValueError(\"'lambda_' must be a positive value.\")\n\n    if random_state is not None:\n        np.random.seed(random_state)\n\n    uniform_samples = np.random.uniform(size=num_inst)\n\n    return -np.log(uniform_samples) / lambda_\n\n\ndef sample_laplace(loc: float = 0,\n                   scale: float = 1,\n                   num_inst: int = 1,\n                   random_state: t.Optional[int] = None) -> np.ndarray:\n    \"\"\"Draw samples from laplace distribution.\"\"\"\n    if random_state is not None:\n        np.random.seed(random_state)\n\n    uniform_samples = np.random.uniform(size=num_inst)\n    _aux = uniform_samples - 0.5\n\n    return loc - scale * np.sign(_aux) * np.log(1 - 2 * np.abs(_aux))\n\n\ndef _test_exp():\n    import matplotlib.pyplot as plt\n    import scipy.stats\n\n    vals = np.linspace(-1, 6, 100)\n\n    samples = sample_exp(0.5, num_inst=1000)\n    plt.subplot(1, 2, 1)\n    plt.plot(vals, scipy.stats.expon(scale=1 / 0.5).pdf(vals))\n    plt.hist(samples, bins=64, density=True)\n\n    samples = sample_exp(3.0, num_inst=1000)\n    plt.subplot(1, 2, 2)\n    plt.plot(vals, scipy.stats.expon(scale=1 / 3.0).pdf(vals))\n    plt.hist(samples, bins=64, density=True)\n\n    plt.show()\n\n\ndef _test_laplace():\n    import matplotlib.pyplot as plt\n    import scipy.stats\n\n    vals = np.linspace(-4, 4, 100)\n    samples = sample_laplace(loc=0, scale=1, num_inst=1000, random_state=16)\n    plt.subplot(1, 2, 1)\n    plt.plot(vals, scipy.stats.laplace(loc=0, scale=1).pdf(vals))\n    plt.hist(samples, bins=64, density=True)\n\n    vals = np.linspace(-10, 20, 100)\n    samples = sample_laplace(loc=6, scale=3, num_inst=1000, random_state=32)\n    plt.subplot(1, 2, 2)\n    plt.plot(vals, scipy.stats.laplace(loc=6, scale=3).pdf(vals))\n    plt.hist(samples, bins=64, density=True)\n\n    plt.show()\n\n\nif __name__ == \"__main__\":\n    _test_exp()\n    _test_laplace()\n", "meta": {"hexsha": "6dcfc25d4b5ceca10f368cdfc40f91bc4984613a", "size": 2861, "ext": "py", "lang": "Python", "max_stars_repo_path": "dist_sampling_and_related_stats/inverse_cdf_sampling.py", "max_stars_repo_name": "FelSiq/statistics-related", "max_stars_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-13T02:09:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-13T02:09:08.000Z", "max_issues_repo_path": "dist_sampling_and_related_stats/inverse_cdf_sampling.py", "max_issues_repo_name": "FelSiq/statistics-related", "max_issues_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dist_sampling_and_related_stats/inverse_cdf_sampling.py", "max_forks_repo_name": "FelSiq/statistics-related", "max_forks_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3267326733, "max_line_length": 76, "alphanum_fraction": 0.6099265991, "include": true, "reason": "import numpy,import scipy", "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288018, "lm_q2_score": 0.9005297807787537, "lm_q1q2_score": 0.8584525664211137}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\n\n# def f(x):\n#    return 2*x**2\n\n\ndef f(x):\n    return 5*x**3 + 2*x**2 - 5*x + 7\n\n\nx = np.arange(-10, 10, 0.001)\ny = f(x)\n\nplt.plot(x, y)\n\ncolors = ['k', 'g', 'r', 'b', 'c', 'k', 'g', 'r', 'b', 'c']\n\n\ndef approximate_tangent_line(x, approximate_derivative):\n    return (approximate_derivative*x) + b\n\n\nfor i in np.arange(0, 10, 2):\n    # The point and the \"close enough\" point\n    p2_delta = 0.0001\n    x1 = i\n    x2 = x1+p2_delta\n\n    y1 = f(x1)\n    y2 = f(x2)\n\n    print((x1, y1), (x2, y2))\n\n    # Derivative approximation and y-intercept for the tangent line\n    approximate_derivative = (y2-y1)/(x2-x1)\n    b = y2 - approximate_derivative*x2\n    toPlot = [x1-0.9, x1, x1+0.9]\n\n    plt.scatter(x1, y1, c=colors[abs(i)])\n    plt.plot([point for point in toPlot],\n             [approximate_tangent_line(point, approximate_derivative)\n              for point in toPlot],\n             c=colors[abs(i)])\n\n    print('Approximate derivative fot f(x)',\n          f'where x = {x1} is {approximate_derivative}')\n\nplt.show()\n\n# https://nnfs.io/but\n# https://nnfs.io/ch7\n", "meta": {"hexsha": "7097c7a7f1b3087988cd201a8e61c8f952af764a", "size": 1114, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter 7 - Derivatives/multi_numerical_derivative.py", "max_stars_repo_name": "benricok/pyNeural", "max_stars_repo_head_hexsha": "5fc5710359e3a8d16d9bbb83679854bb07a817ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter 7 - Derivatives/multi_numerical_derivative.py", "max_issues_repo_name": "benricok/pyNeural", "max_issues_repo_head_hexsha": "5fc5710359e3a8d16d9bbb83679854bb07a817ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 7 - Derivatives/multi_numerical_derivative.py", "max_forks_repo_name": "benricok/pyNeural", "max_forks_repo_head_hexsha": "5fc5710359e3a8d16d9bbb83679854bb07a817ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6296296296, "max_line_length": 69, "alphanum_fraction": 0.5888689408, "include": true, "reason": "import numpy", "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899575269305, "lm_q2_score": 0.8887588038050466, "lm_q1q2_score": 0.8584517511121501}}
{"text": "#Investigating asymmetry in particle collisions\n\nimport scipy as sp\nimport numpy as np\nfrom scipy import *\nfrom numpy import *\nfrom matplotlib import pyplot as plt\nimport scipy.optimize as spo\n\n#Task 1\nprint \"Task 1\"\n# PART 1\n# plotting the functions of sigmaA and sigmaB as a function of COM energy\n\n# step 1; writing out some predefined parameters to minimize mistypes\nk=1000000.0    #constant of the collider     \nMz=91.0        #mass of the Z boson in GeV      \nGz=2.5        #width of Z boson defined as per equation \nrs=0.14      #the parameter r describes the measurements at peak of cross-section for Z production \njs=-0.033    #j parameters describe energy dependance of total and forward and backward cross-sections   \nra=0.0027         \nja=0.81 \n\n\n# step 2; defining the functions sigmaA and sigmaS with the squared COM \n#energy as its argument\ndef sigS(S):\n    result= ((4/3)*pi)*((1/S)+(((S*rs)+(S-Mz**2)*-js)/((S-Mz**2)**2+((Mz**2)*(Gz**2)))))\n    return result\n    \ndef sigA(S):\n    result2= (pi)*(((S*ra)+(S-Mz**2)*ja)/((S-Mz**2)**2+((Mz**2)*(Gz**2))))\n    return result2\n    \n#step 3; a linear space of COM energies within the accelerators range (20-140GeV),was created-\ne = np.linspace(20, 140, 100)\n# squaring all the COM energies to get S values,\ns = e*e\n\n#step 4; the function SigmaS was performed on the numerical array S, \n# and the results were labelled B\nB = sigS(s)\nprint \"COM energies squared- s values\", s\nprint \"SigS(s)\", B\n\n#step 5; the function SigmaA was performed on the numerical array S, \n# and the results were labelled C\nC= sigA(s)\nprint \"COM energies sqaured- s values\", s\nprint \"SigA(s)\", C\n\n# step 6; plot the functions SigmaA(s) and SigmaS(s) \n# against the COM energies, e\n#plt.plot(e, B, 'r-')\n#plt.plot (e, C, 'b-')\n#plt.legend(('sigma-S', 'sigma-A'),loc='upper right')\n#plt.xlabel(\"COM energy/ GeV\")\n#plt.ylabel(\"Sigma-A and Sigma-S values/ GeV^-2\")\n#plt.show()\n#plt.savefig(\"task1plot1.png\")\n#plt.clf()\n\n# PART 2\n# Plotting of Total Muon Pairs Produced per Day as \n# a Function of COM Energy\n\n# step 1; the expression for DNu/Dcos(theta)\n# was integrated between -0.95 and 0.95 (the range of angles), \n#in order to obtain an expression for the number of muon pairs as a function of COM energy\n\n\n#step 2; the function for Number of muon pairs \n# with the argument, s (COM energy squared) is defined in python\ndef Nu(x):\n    result=2*1000000*sigS(x)*((0.95)+((0.95**3)/3))\n    return result\n\n#step 3; the function was carried out on the predefined s values\nD= Nu(s)\nprint s\nprint D\n\n# step 4; the aqcuired expression for of Nu as a function of \n# COM energy was plotted.\n\nplt.plot(e, D, 'r-')\nplt.xlabel(\"COM energy / GeV\")\nplt.ylabel(\"Number of muon pairs produced\")\nplt.show()\nplt.savefig(\"task1plot2.png\")\nplt.clf()\n\n\n#Task 2\nprint \"Task 2\"\n#simulating the number of muons detected per cos theta bin for an accelerator \n#operating at a fixed COM energy.\n#step 1; fix COM energy as 90.0 GeV, then s=8100 GeV^2\nsqrtS =90\nsfixed=sqrtS**2\n\n#step 2; calculate sigma A and sigma S parameters for s=8100 GeV^2\nSS= sigS(sfixed)\nprint \"Sigma-S values\", SS\nSA= sigA(sfixed)\nprint \"Sigma-A values\", SA\n\n#step 3; set dcos(theta) as 0.01\n#separate the data points into cos theta bins of width 0.01\ndt= 0.01\ncost = np.arange(-0.95, 0.95, dt)\n\n#step 4; define the expression for the Expected value of muon pairs per \n#cos theta bin\n#this is DNu/Dcos(theta) \n\ndef dNu(theta):\n    result3 =dt*k*(SS*(1+theta**2)+SA*theta)\n    return result3\n    \n#step 5; calculate expected number of muons per cos theta bin\nD= dNu(cost)\nprint \"cos theta values\", cost\nprint \"expected number of muon pairs\", D\n\n#step 6; plot expected number of muons as a function of cos theta \nplt.plot(cost, D, 'r-')\nplt.xlabel(\"cos theta\")\nplt.ylabel(\"Expected number of muon pairs\")\nplt.show()\nplt.savefig(\"task2plot1.png\")\n\n#step 7; find the number of data points in D\nN= len(D)\n\n#step 8; smear using a Poisson random number generator, \n#with mean D, and the number of trials as the number of D values\nE = np.random.poisson(D,N)\nprint \"smeared data with poisson noise\", E\n\n#step 9; plot the smeared data as a histogram. \n#The red line is the expected value, D\n\nplt.bar(cost,E,width=1e-2)\nplt.plot(cost, D, 'r-')\nplt.ylabel(\"Number of muon pairs\")\nplt.legend(('expected value', 'smeared data'),loc='upper right')\nplt.show()\nplt.savefig(\"task2plot2.png\")\nplt.clf()\n\n#step 10; calculate the error in the experimental values\n#this is a counting experiment following Poisson distribution\n#thus the error= square root of counts for each interval\n\nerr=(E)**0.5\nprint \"Error\", err\n\n#step 11; Add these as error bars to the graph\nplt.plot(cost, E, 'b-')\nplt.xlabel(\"cos theta\")\nplt.ylabel(\"(Experimental) Number of muon pairs\")\nplt.errorbar(cost, E, xerr=0, yerr= err)\nplt.show()\nplt.savefig(\"task2plot3.png\")\nplt.clf()\n\n#Task 3\nprint \"Task 3\"\n\n#Part 1- plotting the actual ratios of SigmaA/SigmaS for comparison\ne=np.linspace(20, 140, 190)\ns=e*e\nSS= sigS(s)\nSA= sigA(s)\nratio1= (SA/SS)\n\nplt.plot(e, ratio1, 'r-')\nplt.xlabel(\"Center of Mass Energies/ GeV\")\nplt.ylabel(\"ratio of Sigma-A/Sigma-S\")\nplt.show()\nplt.savefig(\"task3plot1.png\")\nplt.clf()\n\n#Part 2- fitting the ratio and plotting as a function of COM energies and bin widths\n#step 1; define function for data fitting-\ndef fitfunc(x,a,s):\n    func= k*(s*(1+x**2)+a*x)\n    return func\n#step 2; create array of ratios\nAratios= np.array([], dtype=float)\nAerr=np.array([], dtype=float)\n\n#step 3;create loop that goes through values of e and fits for the ratio \nfor q in e:\n    s=q*q\n    SS=sigS(s)\n    SA= sigA(s)\n    D=dNu(cost)\n    E=np.random.poisson(D,len(D))\n    err=(E)**0.5\n    x=np.arange(-0.95, 0.95, dt)\n    y= np.array([E], dtype=np.float)\n    y_err= err\n    initial_guess=[SA,SS]\n    po,po_cov= spo.curve_fit(fitfunc,cost,E,initial_guess,y_err)\n    ratio2 =po[0]/po[1]\n    rerr= sp.sqrt(((po_cov[0,0])/po[0])**2+((po_cov[1,1])/po[1])**2) #adding errors in quadrature to get error in ratio\n    Aratios= np.append(Aratios, ratio2, axis=None)\n    Aerr= np.append(Aerr, rerr, axis=None)\n\n#step 4;plot\nplt.plot(e,Aratios, 'b-')\nplt.errorbar(e,Aratios, xerr=0, yerr= Aerr)\nplt.xlabel(\"Center of Mass Energies/ GeV\")\nplt.ylabel(\"ratio of Sigma-A/Sigma-S\")\nplt.show()\nplt.savefig(\"task3plot2.png\")\nplt.clf()\n\n#step5; effect of bin width on ratio\n#fix COM energy\nsqrtS= 90.0\ns= sqrtS**2 \n\n  \n#step 6; calculating simulated data with poisson noise\ndef dNu(dt,theta):\n    result3 =dt*k*(SS*(1+theta**2)+SA*theta)\n    return result3\n\ndt=np.array([0.01,0.05,0.1])\nfor x in dt:\n    print \"bin width=\", x\n    cost = np.arange(-0.95, 0.95, x)\n    D= dNu(x,cost)\n    E=np.random.poisson(D,len(D))\n    err=(E)**0.5\n\n#step 7; define function for data fitting-\n    def fitfunc(x,a,s):\n        func= k*(s*(1+x**2)+a*x)\n        return func\n    x=np.arange(-0.95, 0.95, x)\n    y= np.array([E], dtype=np.float)\n    y_err= err\n\n#step 8; make an initial guess and use curve fitting function \n# to guess parameters and their uncertainties\n    initial_guess=[-0.004637,0.042374]\n    po,po_cov= spo.curve_fit(fitfunc,cost,E,initial_guess,y_err)\n\n    #step 9; print parameters and uncertainties\n    print \"Values with errors;\"\n    print \"sigma a=\", po[0], \"+/-\", sp.sqrt(po_cov[0,0])\n    print \"sigma s=\", po[1], \"+/-\", sp.sqrt(po_cov[1,1])\n\n    #step 10; calulate experimental ratio of SigmaA/Sigma S\n    ratio2 =po[0]/po[1]\n    rerr= sp.sqrt(((po_cov[0,0])/po[0])**2+((po_cov[1,1])/po[1])**2)\n    print \"ratio from fitted results\", ratio2 \n    print \"uncertainty in ratio\", rerr\n\n", "meta": {"hexsha": "9de24f1d9feebbee734d40ffe91fad99027d26c0", "size": 7509, "ext": "py", "lang": "Python", "max_stars_repo_path": "ProjectB.py", "max_stars_repo_name": "anishakadri/ZAsymmetry", "max_stars_repo_head_hexsha": "bf8a44b05ab0e771718bef90decb21d1afa20ec8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProjectB.py", "max_issues_repo_name": "anishakadri/ZAsymmetry", "max_issues_repo_head_hexsha": "bf8a44b05ab0e771718bef90decb21d1afa20ec8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProjectB.py", "max_forks_repo_name": "anishakadri/ZAsymmetry", "max_forks_repo_head_hexsha": "bf8a44b05ab0e771718bef90decb21d1afa20ec8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4431818182, "max_line_length": 119, "alphanum_fraction": 0.6833133573, "include": true, "reason": "import numpy,from numpy,import scipy,from scipy", "num_tokens": 2386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244553, "lm_q2_score": 0.8887588038050466, "lm_q1q2_score": 0.858451748494889}}
{"text": "#T# repeating decimals can be converted into fractions, and when starting with a fraction, the repeating part of its repeating decimal can be found if the fraction is a repeating decimal\n\n#T# to work with repeating decimals and fractions, the sympy package is used\nimport sympy\n\n#T# create a repeating decimal, any repeating decimal has two parts, an unique part (which may be zero), and a repeating part\nnum1 = 894.57    #| unique part of the repeating decimal number\nnum2 = 448132653 #| repeating part of the repeating decimal number\n#| the repeating decimal itself is 894.57448132653448132653448132653448132653\n\n#T# get the amount of digits after decimal point in the unique number\nnum1_1 = len(str(num1).split('.')[1]) # 2\n\n#T# get the amount of digits in the repeated number\nnum2_1 = len(str(num2))               # 9\n\n#T# the calculation of the fraction is based on subtracting the repeating part of the number to get rid of it, and for this, two multiples of the number are created and the smaller is subtracted from the larger one, after this the fraction can be found\n\n#T# calculate the numerator, it's all the unique digits and one time the repeated digits, both put to the left of the decimal point, minus the unique digits also put to the left of the decimal point\nnum3 = int(num1*10**(num1_1 + num2_1) + num2 - num1*10**num1_1)\n# 89457448132653 - 89457 == 89457448043196\n\n#T# calculate the denominator, it's the subtraction of the powers of ten that were needed to create the numerator\nnum4 = int(10**(num1_1 + num2_1) - 10**num1_1)\n# 100000000000 - 100 == 99999999900\n\n#T# create a fraction with the numerator and denominator, using the Rational constructor\nnum5 = sympy.Rational(num3, num4) # 2484929112311/2777777775\n\n#T# now to do the opposite process, long division is used to calculate the remainder and quotient in iterations, once a remainder repeats itself in the iterations, that means that the repeating part of the decimal number is found\n\n#T# create a list to store the quotients, and one to store the remainders of the iterations\nlist1 = []\nlist2 = []\n\n#T# create the numerator and the denominator of the fraction whose repeating part wants to be found\nnum1 = 2484929112311\nnum2 = 2777777775\n\n#T# create the loop to do the long division\nbool1 = False\nwhile bool1 == False:\n    num3 = num1//num2 #| quotient of the iteration\n    num4 = num1%num2  #| remainder of the iteration\n    if num4 in list2:\n        bool1 = True\n    list1.append(num3)\n    list2.append(num4)\n    num1 = 10*num4    #| dividend for the next iteration\n\n#T# list1 contains the quotients of each iteration, and list2 the remainders of each iteration\nlist1 # [894, 5, 7, 4, 4, 8, 1, 3, 2, 6, 5, 3]\nlist2 # [1595781461, 2068925735, 1244812925, 1337018150, 2259070400, 368481800, 907040225, 737068925, 1815133700, 1484670350, 957814625, 1244812925] #| the remainder 1244812925 is repeated at index 2 and at the last element\n\n#T# get the index with the first occurrence of the remainder, the second occurrence is always the last element in list2\nnum5 = list2.index(num4) # 2\n\n#T# the index is augmented by 1 to avoid repeating the remainder, because num5 is supposed to signal the index from which all remainders are unique\nnum5 += 1 # 3\n\n#T# cast the elements in list1 into a list of strings, to concatenate the numbers\nlist3 = [str(it1) for it1 in list1]\n\n#T# the result is shown as int1.unique1(repeating1) where int1 is the integer part, unique1 is the unique part of the decimals, and repeating1 is inside parentheses to indicate the repeating part of the decimal number\nstr1 = list3[0] + '.' + ''.join(list3[1:num5]) + '(' + ''.join(list3[num5:]) + ')' # '894.57(448132653)'", "meta": {"hexsha": "6c2588f1d4fe788a9a4c827b8af0de05f0238960", "size": 3670, "ext": "py", "lang": "Python", "max_stars_repo_path": "Math/A01_Arithmetics_basics/Programs/S02_3/Repeating_decimals.py", "max_stars_repo_name": "Polirecyliente/SGConocimiento", "max_stars_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Math/A01_Arithmetics_basics/Programs/S02_3/Repeating_decimals.py", "max_issues_repo_name": "Polirecyliente/SGConocimiento", "max_issues_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/A01_Arithmetics_basics/Programs/S02_3/Repeating_decimals.py", "max_forks_repo_name": "Polirecyliente/SGConocimiento", "max_forks_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.4615384615, "max_line_length": 252, "alphanum_fraction": 0.748773842, "include": true, "reason": "import sympy", "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899575269305, "lm_q2_score": 0.8887587986487518, "lm_q1q2_score": 0.8584517461316872}}
{"text": "# -*- coding: utf-8 -*-\nimport numpy as np\n\n\ndef bgd(X, Y, alpha=0.01, epsilon=1e-8, trace=True):\n    m = len(X)\n    _X = np.column_stack((np.ones(m), X))\n    m, n = np.shape(_X)\n    theta, sse2, cnt = np.ones(n), 0, 0\n    Xt = _X.T\n    while True:\n        loss = np.dot(_X, theta) - Y\n        # sse = np.sum(loss ** 2) / (2 * m)\n        # sse = loss.T.dot(loss) / (2 * m)\n        sse = np.dot(loss.T, loss) / (2 * m)\n        if abs(sse - sse2) < epsilon:\n            break\n        else:\n            sse2 = sse\n\n        if trace:\n            print(\"[ Epoch {0} ] theta = {1}, loss = {2}, error = {3})\".format(cnt, theta, loss, sse))\n\n        gradient = np.dot(Xt, loss) / m\n        theta -= alpha * gradient\n        cnt += 1\n    return theta\n\n\nif __name__ == '__main__':\n    import matplotlib.pyplot as plt\n\n    X = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n    Y = [1.99, 3.89, 5.80, 7.83, 9.80, 11.77, 13.80, 15.75, 17.71]\n\n    b, a = bgd(X, Y, 0.05, 1e-6)\n\n    print('y = {0} * x + {1}'.format(a, b))\n\n    x = np.array(X)\n    plt.plot(x, Y, 'o', label='Original data', markersize=5)\n    plt.plot(x, a * x + b, 'r', label='Fitted line')\n    plt.show()\n\n    x = [(0., 3), (1., 3), (2., 3), (3., 2), (4., 4)]\n    y = [95.364, 97.217205, 75.195834, 60.105519, 49.342380]\n\n    _theta = bgd(x, y, 0.1, 1e-8)\n    print('theta = {0}'.format(_theta))\n\n\n", "meta": {"hexsha": "a563debb746ed94de2ff5a0616606fb5f4750581", "size": 1333, "ext": "py", "lang": "Python", "max_stars_repo_path": "03-algorithms/05-linear-regression/code-practice/batch_gradient_descent.py", "max_stars_repo_name": "jameszhan/notes-ml", "max_stars_repo_head_hexsha": "c633d04e5443eab71bc3b27fff89d57b89d1786c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "03-algorithms/05-linear-regression/code-practice/batch_gradient_descent.py", "max_issues_repo_name": "jameszhan/notes-ml", "max_issues_repo_head_hexsha": "c633d04e5443eab71bc3b27fff89d57b89d1786c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "03-algorithms/05-linear-regression/code-practice/batch_gradient_descent.py", "max_forks_repo_name": "jameszhan/notes-ml", "max_forks_repo_head_hexsha": "c633d04e5443eab71bc3b27fff89d57b89d1786c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6346153846, "max_line_length": 102, "alphanum_fraction": 0.4748687172, "include": true, "reason": "import numpy", "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995733060719, "lm_q2_score": 0.8887587839164801, "lm_q1q2_score": 0.8584517301569515}}
{"text": "import numpy as np\n\n'''\nTraining\nFor each target value vj:\n    P'(vj) = estimate P(vj)\n    for each attribute value ai of each attribute a:\n        P(ai | vj) = estimate P(ai | vj)\n\nClassifying\nvnb = argmax[vj in V] P(vj) * PRODUCT(ai in x) P(ai | vj)\n'''\n\n\ndef naive_bayes_learn(examples):\n    target_classes = set([ ex[-1] for ex in examples ]) # get the different target values\n    print(\"target classes\\n\", target_classes)\n\n    # For each target value vj\n    target_probabilities = {}\n    for target_value in target_classes:\n        number_of_occurencens = 0\n        for ex in examples:\n            if ex[-1] == target_value:\n                number_of_occurencens += 1\n        # P(vj) = estimate p(vj)\n        target_probabilities[target_value] = number_of_occurencens / len(examples)\n    print(\"target probabilities\\n\", target_probabilities)\n\n    # for each attribute value ai of each attribute a\n    attribute_values = {} # {ai = [v1, v2, ,..,vn]}\n    for ex in examples:\n        ex = ex[:-1] # remove target from example\n        for ai_idx, ai in enumerate(ex): \n            attribute_value = attribute_values.get(ai_idx, [])\n            attribute_value.append(ai)\n            attribute_values[ai_idx] = attribute_value\n    for ai in attribute_values:\n        attribute_values[ai] = list(set(attribute_values.get(ai, []))) # remove duplicates\n    print(\"attribute values\\n\", attribute_values)\n\n    # P(ai | vj) = estimate p(ai |vj) # count how many ai with class vj over total examples\n    attribute_target_probability = {}\n    for a in attribute_values:\n        for ai in attribute_values[a]:\n            for vj in target_classes:\n                count = 0\n                for ex in examples:\n                    if ex[a] == ai and ex[-1] == vj:\n                        count += 1\n                #    P(ai | vj)   =    P(ai ^ vj)            /     p(vj)\n                probability_ai_vj = (count / len(examples)) / target_probabilities[vj]\n                key = str(a)+\".\"+str(ai)+\"|\"+str(vj)\n                attribute_target_probability[key] = probability_ai_vj\n    print(\"Attribute_target_probability: \\n\", attribute_target_probability)\n\n    return target_classes, target_probabilities, attribute_target_probability\n\n\ndef naive_bayes_classify_new_instance(x, target_classes, target_probs, ai_target_probs):\n    probs = {}\n    for vj in target_classes:\n        p = None\n        for a, ai in enumerate(x[:-1]):\n            key = str(a)+\".\"+str(ai)+\"|\"+str(vj)\n            if p == None:\n                p = ai_target_probs[key]\n            else:\n                p *= ai_target_probs[key]\n        p *= target_probs[vj]\n        probs[vj] = p\n\n    print(\"New case probability\\n\", probs)\n    return max(probs)\n\n\nif __name__ == \"__main__\":\n    data = np.loadtxt(\"data/data.txt\", dtype=str, comments=\"#\", delimiter=\", \")\n    tc, tp, atp  = naive_bayes_learn(data)\n\n    new_case = [\"overcast\", \"true\", \"low\", \"yes\"]\n    target = naive_bayes_classify_new_instance(new_case, tc, tp, atp)\n    print(\"Prediction is: \", target)", "meta": {"hexsha": "cb082726f8a315d77fa56dc150c137336f951b32", "size": 3023, "ext": "py", "lang": "Python", "max_stars_repo_path": "Simple_Naive_Bayes_Learn/naive_bayes_learn.py", "max_stars_repo_name": "skaugvoll/Algorithms", "max_stars_repo_head_hexsha": "ac0d18ec066f17f13a38edb402d53c1f3abe6803", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Simple_Naive_Bayes_Learn/naive_bayes_learn.py", "max_issues_repo_name": "skaugvoll/Algorithms", "max_issues_repo_head_hexsha": "ac0d18ec066f17f13a38edb402d53c1f3abe6803", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Simple_Naive_Bayes_Learn/naive_bayes_learn.py", "max_forks_repo_name": "skaugvoll/Algorithms", "max_forks_repo_head_hexsha": "ac0d18ec066f17f13a38edb402d53c1f3abe6803", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.421686747, "max_line_length": 91, "alphanum_fraction": 0.6027125372, "include": true, "reason": "import numpy", "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983309, "lm_q2_score": 0.9046505402422645, "lm_q1q2_score": 0.8584385133501403}}
{"text": "# Newton root finding methods tests\n\nfrom math import sin, cos, exp, log\n\nfrom newton import newton, newton_aitken, newton_chord, newton_secant\nimport numpy as np\n\n\n# Get machine precision\neps = np.finfo(float).eps\n\n################################################################################\n\nprint('-----------------------------------------------------------------------')\nprint(' f(x) = 2^x-cos(x+3)^2+exp(x+2)')\nf  = lambda x: 2**x-(cos(x+3))**2+exp(x+2)\nf1 = lambda x: 2**x*log(2)+2*cos(x+3)*sin(x+3)+exp(x+2)\nprint('> Newton plain')\nx, steps = newton(0, f, f1, eps, 1000, 1)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\nprint('> Newton chords')\nx, steps = newton_chord(0, f, f1, eps, 1000)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\nprint('> Newton secant')\nx, steps = newton_secant(0, f, f1, eps, 1000)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n\n################################################################################\n\nprint('-----------------------------------------------------------------------')\nprint(' f(x) = log(sin(x+4)-cos(x-1))-exp(3*x-x^2)')\nf  = lambda x: log(sin(x+4)-cos(x-1))-exp(3*x-x**2)\nf1 = lambda x: (cos(x+4)+sin(x-1))/(sin(x+4)-cos(x-1))-exp(3*x-x**2)*(3-2*x)\nprint('> Newton plain')\nx, steps = newton(4, f, f1, eps, 100, 1)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n\n################################################################################\n\nprint('-----------------------------------------------------------------------')\n# 90 iterations to converge... too many for a quadratic method,\n# Maybe the root has multiplicity > 1?\nprint(' f(x) = (4+log(x))*x*(log(x))^3')\nf  = lambda x: (4+log(x))*x*(log(x))**3\nf1 = lambda x: (log(x)**2)*((log(x)**2)+8*log(x)+12)\nprint('> Plain Newton')\nx, steps = newton(4, f, f1, eps, 100, 1)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n# With Aitken acceleration: 5 iterations\nprint('> Aitken acceleration')\nx, steps = newton_aitken(4, f, f1, eps, 100)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n# The root multiplicity should be 3, lets test the plain Newton method with\n# known root multiplicity: 6 iterations\nprint('> Passing the root multiplicity to plain Newton (m=3)')\nx, steps = newton(4, f, f1, eps, 100, 3)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n# Quasi-Newton method: chords\nprint('> Newton chords')\nx, steps = newton_chord(4, f, f1, eps, 5000)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n# Quasi-Newton method: secant\nprint('> Newton secant')\nx, steps = newton_secant(4, f, f1, eps, 5000)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n\n################################################################################\n\nprint('-----------------------------------------------------------------------')\n# The following function root computation with the plain Newton method is\n# very inefficient. With 5000 steps the method converges with an error ~5E-7.\n# Indeed the root has infinite multiplicity.\nprint('> Infinite multiplicity root')\nprint(' f(x) = sin(x-1)-0.5*sin(2*(x-1))')\nf  = lambda x: sin(x-1)-0.5*sin(2*(x-1))\nf1 = lambda x: cos(x-1)-0.5*x*cos(2*(x-1))\nprint('> Newton plain')\nx, steps = newton(3, f, f1, eps, 5000, 1)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n# Same experiment but with Aitken acceleration\nprint('> Aitken acceleration')\nx, steps = newton_aitken(3, f, f1, eps, 5000)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n# Quasi-Newton method: chord\nprint('> Newton chord')\nx, steps = newton_chord(3, f, f1, eps, 5000)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n# Quasi-Newton method: secant\nprint('> Newton secant')\nx, steps = newton_secant(3, f, f1, eps, 5000)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n\n################################################################################\n\nprint('-----------------------------------------------------------------------')\n# Even with a not so small error tolerance the plain Newton method takes too\n# many steps to converge.\nprint(' f(x) = (3*x-9)^7')\nf  = lambda x: (3*x-9)**7\nf1 = lambda x: 7*x*(3*x-9)**6\nprint('> Newton plain')\nx, steps = newton(8, f, f1, 1e-11, 300, 1)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n# The root multiplicity is clearly 7\nprint('> Passing the root multiplicity to plain Newton (m=7)')\nx, steps = newton(8, f, f1, 1e-11, 300, 7)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n# Quasi-Newton method: chord\nprint('> Newton chord')\nx, steps = newton_chord(8, f, f1, 1e-11, 5000)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n# Quasi-Newton method: secant\nprint('> Newton secant')\nx, steps = newton_secant(8, f, f1, 1e-11, 5000)\nprint(\" x = {}\\n steps = {}\\n error = {}\".format(x, steps, abs(f(x))))\n", "meta": {"hexsha": "2f3838de7ebc6287b365890f8f69b03e62e0a01f", "size": 5026, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/newton_test.py", "max_stars_repo_name": "davxy/numeric", "max_stars_repo_head_hexsha": "1e8b44a72e1d570433a5ba81ae0795a750ce5921", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-03T17:02:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T04:09:34.000Z", "max_issues_repo_path": "python/newton_test.py", "max_issues_repo_name": "davxy/numeric", "max_issues_repo_head_hexsha": "1e8b44a72e1d570433a5ba81ae0795a750ce5921", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/newton_test.py", "max_forks_repo_name": "davxy/numeric", "max_forks_repo_head_hexsha": "1e8b44a72e1d570433a5ba81ae0795a750ce5921", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3275862069, "max_line_length": 80, "alphanum_fraction": 0.5179068842, "include": true, "reason": "import numpy", "num_tokens": 1532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537142, "lm_q2_score": 0.9046505318875316, "lm_q1q2_score": 0.8584385041153169}}
{"text": "# Python function that calculates the local extreme point of curvature (vortex)\n# point in a specified interval of a unimodal function.\n# Simply change the maxF variable to the function\n# you'd like to test and set the parameters of max_grs.\n# ---WORKS ONLY FOR ONE VARIABLE FUNCTIONS----\n# ---  IT IS RECOMMENDED TO  USE 'x' AS THE VARIABLE---\n\"\"\"\n# References\nhttps://en.wikipedia.org/wiki/Golden-section_search\nhttps://en.wikipedia.org/wiki/Vertex\n\"\"\"\n\n\nimport numpy as np\nfrom matplotlib import pyplot as plt  # import module to plot the result\n\ntarget_function = (\n    lambda x: x ** 3 - 6 * x ** 2 + 4 * x + 12\n)  # type the function of interest here\n\n\ndef max_golden_search(\n    func_to_max, upper: float, lower: float, tol: float = 1e-8\n) -> float:\n\n    \"\"\"\n    Function in python that calculates the maximum\n    point of function in a specified interval\n        :param func_to_max : the function to maximize (target_function)\n        :param upper: upper boundary of interval\n        :param lower: lower boundary of interval\n        :param tol: set an appropriate tolerance value\n        :returns maximum of specified interval\n    >>> max_golden_search(target_function, -2, 4)\n    count = 43\n    0.3670068499227286\n    >>> max_golden_search(target_function, 'm', 4)\n    Traceback (most recent call last):\n            ...\n    ValueError: give numerical values for upper, lower limits\n    \"\"\"\n\n    if type(upper) is str or type(lower) is str:\n        raise ValueError(\"give numerical values for upper, lower limits\")\n\n    inv_gr = (np.sqrt(5) - 1) * 0.5  # ~ 0.618, this is the inverse golden ratio\n    d_max = (upper - lower) * inv_gr  # # Sets initial value for d\n    q1 = lower + d_max  # Sets initial value for q1\n    q2 = upper - d_max  # and q2\n\n    count = 0  # Creates a count variable with initial value zero\n\n    while (\n        abs(upper - lower) > tol\n    ):  # Sets the tolerance condition. Will stop running once |u -l| < tol\n\n        if func_to_max(q1) > func_to_max(q2):\n            lower = q2\n        else:\n            upper = q1\n        d_max = (upper - lower) * inv_gr\n        q1 = lower + d_max\n        q2 = upper - d_max\n        count += 1  # Adds one to the count per iteration\n\n    print(\"count =\", count)  # Prints the count number\n\n    return (q1 + q2) * 0.5  # Returns the midpoint of the\n    # final interval as the maximum point in the range\n\n\nmax_point = max_golden_search(target_function, -2, 4)\n\n\ndef plot_point(\n    maximum_point: float = max_point,\n    x_axis_linspace: np.linspace = np.linspace(-5, 5, 200),\n) -> None:\n    \"\"\"\n    Plots function and maximum point\n    \"\"\"\n    fmt = \"bo\"  # format string for the color of the point\n    plt.plot(x_axis_linspace, target_function(x_axis_linspace))\n    plt.plot(maximum_point, target_function(maximum_point), fmt)\n    plt.show()\n\n\nif __name__ == \"__main__\":\n\n    import doctest\n\n    doctest.testmod()\n", "meta": {"hexsha": "9aea781d92443535e214aa7b130c47c2a23d9d17", "size": 2887, "ext": "py", "lang": "Python", "max_stars_repo_path": "maths/max.py", "max_stars_repo_name": "Stav-Kr/Python", "max_stars_repo_head_hexsha": "3131e764bc7ba5cf3d82ef514022035d26fccc51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "maths/max.py", "max_issues_repo_name": "Stav-Kr/Python", "max_issues_repo_head_hexsha": "3131e764bc7ba5cf3d82ef514022035d26fccc51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maths/max.py", "max_forks_repo_name": "Stav-Kr/Python", "max_forks_repo_head_hexsha": "3131e764bc7ba5cf3d82ef514022035d26fccc51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0430107527, "max_line_length": 80, "alphanum_fraction": 0.6560443367, "include": true, "reason": "import numpy", "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.904650527388829, "lm_q1q2_score": 0.8584384985395468}}
{"text": "import numpy as np\nimport sympy as sp\nimport typing\nimport vorpy.symbolic\n\ndef directional_derivative (\n    V:np.ndarray,\n    f:typing.Any,\n    X:np.ndarray,\n    *,\n    post_process_o:typing.Optional[typing.Callable[[typing.Any],typing.Any]]=sp.simplify,\n) -> np.ndarray:\n    \"\"\"\n    This returns the directional derivative of f along V in coordinates X.\n\n    If post_process_o is not None, will call post_process_o on each component of the result.\n    The default for post_process_o is sympy.simplify.\n    \"\"\"\n    if V.shape != X.shape:\n        raise TypeError(f'expected vector field V to have the same shape as coordinates X, but V.shape = {V.shape} and X.shape = {X.shape}')\n\n    V_flat = V.reshape(-1)\n    f_flat = np.reshape(f, -1)\n    X_flat = X.reshape(-1)\n    df_flat = vorpy.symbolic.differential(f_flat, X_flat)\n    assert df_flat.shape == f_flat.shape + X_flat.shape\n    V_dot_df = np.dot(df_flat, V_flat).reshape(np.shape(f))\n\n    # For some reason, the result of sp.simplify(V_dot_df) is class\n    # 'sympy.tensor.array.dense_ndim_array.ImmutableDenseNDimArray'\n    # so instead call sp.simplify on each element of the result so\n    # that it is a numpy.ndarray.  If the order of the result is\n    # zero, then extract the single, scalar element.\n    if post_process_o is not None:\n        V_dot_df = np.vectorize(post_process_o)(V_dot_df)\n\n    # TODO: test on scalar expressions f, as this [()] expression may not work in that case\n    if V_dot_df.shape == ():\n        return V_dot_df[()]\n    else:\n        return V_dot_df\n\ndef lie_bracket (A, B, X):\n    \"\"\"\n    Compute the Lie bracket of vector fields A and B with respect to coordinates X.\n\n    A formula for [A,B], i.e. the Lie bracket of vector fields A and B, is\n\n        J__B_reshaped*A - J__A_reshaped*B\n\n    where J_V is the Jacobian matrix of the vector field V.\n\n    See https://en.wikipedia.org/wiki/Lie_bracket_of_vector_fields#In_coordinates\n    See https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant\n    \"\"\"\n\n    if A.shape != B.shape or A.shape != X.shape:\n        raise TypeError(f'The shapes of A, B, and X must all be equal, but instead got A.shape = {A.shape}, B.shape = {B.shape}, X.shape = {X.shape}')\n\n    # Flatten the shapes out for computing and contracting the Jacobian matrices.\n    A_reshaped = A.reshape(-1)\n    B_reshaped = B.reshape(-1)\n    X_reshaped = X.reshape(-1)\n    # Compute the Jacobian matrices of (the reshaped versions of) A and B\n    J__A_reshaped = vorpy.symbolic.differential(A_reshaped, X_reshaped)\n    J__B_reshaped = vorpy.symbolic.differential(B_reshaped, X_reshaped)\n    # Reshape the result into the original shape of the vector fields and coordinates.\n    return (np.dot(J__B_reshaped,A_reshaped) - np.dot(J__A_reshaped,B_reshaped)).reshape(X.shape)\n\n", "meta": {"hexsha": "e56ec21a762c2f3c6c4c8aa9787fb8820c50a432", "size": 2780, "ext": "py", "lang": "Python", "max_stars_repo_path": "vorpy/manifold/__init__.py", "max_stars_repo_name": "vdods/vorpy", "max_stars_repo_head_hexsha": "68b6525ae43d99f451cf85ce254ffb0311521320", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-07-08T14:41:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-11T17:33:57.000Z", "max_issues_repo_path": "vorpy/manifold/__init__.py", "max_issues_repo_name": "vdods/vorpy", "max_issues_repo_head_hexsha": "68b6525ae43d99f451cf85ce254ffb0311521320", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vorpy/manifold/__init__.py", "max_forks_repo_name": "vdods/vorpy", "max_forks_repo_head_hexsha": "68b6525ae43d99f451cf85ce254ffb0311521320", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7142857143, "max_line_length": 150, "alphanum_fraction": 0.6996402878, "include": true, "reason": "import numpy,import sympy", "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517106286378, "lm_q2_score": 0.8933094074745443, "lm_q1q2_score": 0.8584272032333182}}
{"text": "import numpy as np\n\na.size\na.itemsize\na.size * a.itemsize\n\na = np.arange(10,50)\n\na = a[::-1]\n\na = np.arange(0,9).reshape(3,3)\n\nnp.nonzero(a)\n\nnp.eye(3)\n\nprint(a.min(), a.max())\n\nprint(a.mean())\n\na = np.zeros((10,10))\na = np.pad(a, 1, constant_values=1)\n\na = np.ones((10,10))\na[1:-1,1:-1] = 0\n\nnp.diag([1,2,3,4], -1)\n\na[::2,1::2] = 1\na[1::2,::2] = 1\n\nnp.unravel_index(99, (6,7,8))\n\nnp.tile([[1,0],[0,1]], (4,4))\n\nz = (a - a.mean())/a.std()\n\nnp.dtype([(\"r\", np.ubyte),(\"g\", np.ubyte),(\"b\", np.ubyte),(\"a\", np.ubyte)])\n\na = np.random.rand(5,3)\nb = np.random.rand(3,2)\na @ b\n\na[(a > 3) & (a < 8)] *= -1\n\nnp.where(a > 0, np.ceil(a), np.floor(a))\n\nnp.sqrt(-1)\nnp.emath.sqrt(-1)\n\ndate = np.datetime64\nnow = date('today')\nnp.timedelta64(1, 'D') + now\nnp.timedelta64(-1, 'D') + now\nnp.arange('2016-07', '2016-08', dtype='datetime64[D]')\n\nnp.trunc(a)\n\n\nnp.tile(np.arange(0,5),(5,1))\n\nnp.fromiter(range(10), int)\n\nnp.linspace(0,1,10)\n\na.sort()\n\n\nnp.add.reduce(a)\n\n\nnp.allclose(a,b)\nnp.array_equal(a,b)\n\na[a.argmax()] = 0\n\nZ = np.zeros((5,5), [('x',float),('y',float)])\nZ['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),\n                             np.linspace(0,1,5))\nprint(Z)\n\n\nnp.subtract.outer(x,y)\n\n\narr = np.add.outer(x,y)\n\n\nZ = np.zeros(10, [ ('position', [ ('x', float, 1),\n                                  ('y', float, 1)]),\n                   ('color',    [ ('r', float, 1),\n                                  ('g', float, 1),\n                                  ('b', float, 1)])])\n\nZ[0]['position']['x']\n\nimport scipy.spatial\nscipy.spatial.distance.cdist(x,x)\n\nX,Y = np.atleast_2d(x[:,0], x[:,1])\nnp.sqrt((X-X.T)**2 + (Y-Y.T)**2)\n\na[:] = a.view(int)\n\nfrom io import StringIO\n\ns = StringIO(\"\"\"1, 2, 3, 4, 5\n6,  ,  , 7, 8\n ,  , 9,10,11\"\"\")\n\nnp.genfromtxt(s,delimiter=',', filling_values=0)\n\n\nlist(np.ndenumerate(np.random.rand(3,4)))\nlist(np.ndindex((3,4)))\n\n\na - a.mean(1).reshape(-1,1)\na - a.mean(1,keepdims=True)\n\n\na.sum((-1,-2))\n\nnp.diag(A @ B)\nnp.einsum('ij, ji -> i',A,B)  # diagonal\n\nnp.einsum('ij, ji',A,B)  # Trace of result\n", "meta": {"hexsha": "09d79ba41fd969ec56b8ec89c5dc077730cc6b13", "size": 2029, "ext": "py", "lang": "Python", "max_stars_repo_path": "100_Numpy_exercises.py", "max_stars_repo_name": "danielfleischer/numpy-100", "max_stars_repo_head_hexsha": "7fcfc1cfbe1f1884ec211d24b7963f66a244c9e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-27T10:58:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:58:34.000Z", "max_issues_repo_path": "100_Numpy_exercises.py", "max_issues_repo_name": "danielfleischer/numpy-100", "max_issues_repo_head_hexsha": "7fcfc1cfbe1f1884ec211d24b7963f66a244c9e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "100_Numpy_exercises.py", "max_forks_repo_name": "danielfleischer/numpy-100", "max_forks_repo_head_hexsha": "7fcfc1cfbe1f1884ec211d24b7963f66a244c9e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.8515625, "max_line_length": 75, "alphanum_fraction": 0.5160177427, "include": true, "reason": "import numpy,import scipy", "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.9196425355825848, "lm_q1q2_score": 0.8584226829551929}}
{"text": "import random as r\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.linalg as linalg\nimport math\ndef in_1d_boundary(position, boundary):\n    return position > boundary[0] and position < boundary[1]\n\ndef run_1d_trial(steps, boundary):\n    \"\"\"\n    steps: number of steps to take\n    boundary: set of points that consititute a boundary (doesn't make sense with more than 2)\n\n    Runs trial for one dimension starting from 0 WLOG since we have control over the boundary.\n    Returns a map from square -> number of times we reached that square\n    \"\"\"\n    starting_point = 0\n    seen_squares = {starting_point: 1} #includes starting square \n    take_step = lambda : (-2) *(r.random() < 0.5) + 1 # take a step left (-1) with p = 1/2 and right (+ 1) with p = 1/2\n    current_sq = starting_point\n    for step in range(steps):\n        step_vector = take_step()\n        current_sq += step_vector\n        if not in_1d_boundary(current_sq, boundary):\n            break\n        seen_squares[current_sq] = seen_squares.setdefault(current_sq, 0) + 1 #increase square count by 1\n    \n    return current_sq, seen_squares \n\ndef combine_freq_dists(f1, f2):\n    new_f = {}\n    for coord in f1:\n        new_f[coord] = new_f.setdefault(coord, 0) + f1[coord]\n    \n    for coord in f2:\n        new_f[coord] = new_f.setdefault(coord, 0) + f2[coord]\n    \n\n    return new_f\n    \ndef visualize_data(results):\n    exit_points = {}\n\n    total_frequencies = {}\n    for i, r in enumerate(results): \n        exit_point, freq_dist = r\n        exit_points[exit_point] = exit_points.setdefault(exit_point, 0) + 1\n        total_frequencies = combine_freq_dists(total_frequencies, freq_dist)\n\n \n    x_coords = []\n    freqs = []\n    for f in total_frequencies:\n        x_coords.append(f)\n        freqs.append(total_frequencies[f])\n    \n    plt.plot(x_coords, freqs)\ndef run_sim(trials, steps, boundary):\n    \"\"\"\n    trials: Number of trials to run in the simulation\n    steps: Number of steps to run per trial\n    \"\"\"\n    trial_results = []\n    for trial in range(trials):\n        trial_results.append(run_1d_trial(steps, boundary))\n        print(f\"Trial {trial}: \", run_1d_trial(steps, boundary))\n    # post processing of results\n    visualize_data(trial_results)\n\n\ndef markov_processes():\n    n = 9 \n    m = np.zeros((n, n))\n    m[0, 1] = .5\n    m[n-1, n-2] = .5\n    for i in range(1, n-1):\n        m[i, i-1] = .5\n        m[i, i+1] = .5\n    print(m)\n    p_m = linalg.matrix_power(m, 10000)\n    np.set_printoptions(precision=4)\n    print(p_m)\n    v = np.zeros(n)\n    v[n//2] = 1\n    res = p_m@v\n    print(res)\n    print(\"end probability: \", res[n//2] )\n\ndef what_step_exit(s, b):\n    pos = 0\n    for i in range(0, len(s), 2):\n        if s[i:i+2] == '00':\n            pos += 1\n        elif s[i:i+2] == '01':\n            pos -= 1\n        if pos >= b:\n            return i + 1\n    return len(s)\n\ndef out_before(s, b):\n    # 00 -> u 01 -> d,10 -> l, 01 -> r\n    pos = 0\n    for i in range(0, len(s)-2, 2):\n        if s[i:i+2] == '00':\n            pos += 1\n        elif s[i:i+2] == '01': \n            pos -= 1\n\n        if pos >= b:\n            return True\n\n    return False\n\ndef out_at_end(s, b):\n    pos = 0\n    for i in range(0, len(s), 2):\n        if s[i:i+2] == '00':\n            pos += 1\n        elif s[i:i+2] == '01':\n            pos -= 1\n    return pos >= b\n\ndef counting(s, b):\n    # a word is a binary number. 0 represents down, 1 represents up\n    words = []\n    for i in range(4**s):\n        words.append(format(i, f\"0{2*s}b\"))\n\n    #print(words)\n    #eliminate all words that would exit before the final step\n    valid_words = []\n    double_check = {}\n    for w in words:\n        if not out_before(w, b):\n            valid_words.append(w)\n    \n    #find all words that escape on the last step\n    escaped_words = []\n    for w in valid_words:\n        if out_at_end(w, b):\n            escaped_words.append(w)\n    \n    print(f\"Valid Words {len(valid_words)} \")#, valid_words)\n    print(f\"Escaped Words {len(escaped_words)}\")#, escaped_words) \n    print(f\"Probability Escaping on step {s}: \", len(escaped_words)/len(valid_words)) \n\nmemo = {}\ndef compute_number_paths_out(s, d):\n    \"\"\"\n    Computes number of paths out in exactly s steps, when the boundary is d steps away.\n\n    Recurrence: C(s, d) = C(s-1, d-1) + 2C(s-1, d) + C(s-1, d+1)\n    \n    The recurrence is for a random walk in 2d, where the boundary\n    is the half plane that is d steps away.\n\n    Base Cases: \n        C(s, d) = 0 if s < d // less steps than to boundary then obviously can't reach it\n        C(s, d) = 0 if d = 0 // we have already hit the boundary and and there are steps left\n        C(s, d) = 1 if s= d // there is only one path that exactly hits the boundary (going straight there)\n \n    Using memoization should lead to a runtime of O(s^2)\n    O(1) work on each state, O(s)O(d) states is an overcount since s < d requires no recursion\n    \"\"\"\n    memo[(0, 0)] = 1\n    for s_i in range(s+1):\n        for d_i in range(d+s_i+1):\n            if (s_i, d_i) not in memo:\n                if (s_i < d_i):\n                    memo[(s_i, d_i)] = 0\n                elif d_i == 0:\n                    memo[(s_i, d_i)] = 0\n                elif s_i == d_i:\n                    memo[(s_i, d_i)] = 1\n                else:\n                    memo[(s_i, d_i)] = memo[(s_i - 1, d_i -1)] + 2*memo[(s_i - 1, d_i)] + memo[(s_i - 1, d_i + 1)]\n    return memo[(s, d)] \n    # if (s, d) in memo:\n    #     return memo[(s, d)]\n    \n    # if (d > s): \n    #     return 0\n    # if (d == 0): \n    #     return 0\n    # if (s == d): \n    #     return 1\n\n    # c = lambda x, y : compute_number_paths_out(x, y)\n    # ans = c(s-1, d-1) + 2*c(s-1, d) + c(s-1, d+1)\n    # memo[(s, d)] = ans\n    # return ans\n\ndef nCr(n, r):\n    # f = math.factorial\n    return math.comb(n, r)#f(n)//(f(n-r)*f(r))\n\ndef closed_form_paths_out(s, d):\n    #rn only works for d = 2\n    #compute row (2(s-1)) column 2(s-1)/2 + 1 in pascals triangle\n    # print(\"computing s, d\", s, d)\n    current_row = 2*(s-1)\n    offset = d-1\n    midpoint = current_row//2\n    total_num_out_with_ob = nCr(current_row, midpoint + offset) \n    # extra paths are the entry immeadiatly above and to the right (but for some reason pascals goes by 2)\n    extra_paths = nCr(current_row, current_row//2 + offset +2) if (current_row >= midpoint + offset + 2 ) else 0\n    # print(extra_paths)\n    return total_num_out_with_ob - extra_paths\n\ndef correction(n, val):\n    print(f\"(n, val) {(n, val)}\")\n    if (n == 0):\n        return val\n    if (n==1): \n        return 2*val\n    return 2*correction(n-1, val) + ((n%2) + 1)*val\n\nmemo_tot_paths = {}\ndef compute_number_paths(s, d):\n    \"\"\"\n    Computes total number of paths of length s, that do not exit early\n\n    Recurrence: C(s, d) = C(s-1, d-1) + 2C(s-1, d) + C(s-1, d+1)\n    \n    The recurrence is for a random walk in 2d, where the boundary\n    is the half plane that is d steps away.\n\n    Base Cases: \n        C(s, d) = (4)^s if s <= d // all paths are viable none will leave early \n        C(s, d) = 0 if d = 0 // we have already hit the boundary and and there are steps left\n \n    Using memoization should lead to a runtime of O(s^2)\n    O(1) work on each state, O(s)O(d) states is an overcount since s < d requires no recursion\n    \"\"\"\n    memo_tot_paths[(0, 0)] = 1\n    for s_i in range(s+1):\n        for d_i in range(d+s_i+1):\n            if (s_i, d_i) not in memo_tot_paths:\n                if (s_i <= d_i):\n                    memo_tot_paths[(s_i, d_i)] = (4)**s_i\n                elif d_i == 0:\n                    memo_tot_paths[(s_i, d_i)] = 0\n                else:\n                    memo_tot_paths[(s_i, d_i)] = memo_tot_paths[(s_i - 1, d_i -1)] + 2*memo_tot_paths[(s_i - 1, d_i)] + memo_tot_paths[(s_i - 1, d_i + 1)]\n    return memo_tot_paths[(s, d)] \n\ndef probability_leaving(s, d):\n    total_probability = 0\n    for i in range(1,s+1):\n        # extra_paths = sum([compute_number_paths_out(j, d) for j in range(1, i-1)])\n        total_probability += compute_number_paths_out(i, d)/1#(4**i)#(compute_number_paths(i, d) + extra_paths)\n    return total_probability\n\ndef ev_half_plane(d, epochs):\n    ev = 0\n    end_epoch = d+epochs\n    # print(sum([closed_form_paths_out(s, d)/4**s for s in range(d, end_epoch)]))\n    for s in range(d, d+epochs+1):\n        #extra_paths = sum([compute_number_paths_out(j, d) for j in range(1, s-1)])\n        paths_out = closed_form_paths_out(s, d)\n        total_paths = 4**s\n        #print(f\"greater: {paths_out < total_paths} s: {s} paths out: {paths_out} total_paths: {total_paths}\")\n        ev += (s*paths_out)/(total_paths)#(4**(end_epoch))\n\n    return ev\n\ndef pascals_triangle(d):\n\n    for i in range(d):\n        row = \"\"\n        for j in range(i+1):\n            row += str(nCr(i, j)) + \" \"\n        row = row[:-1]\n        print(row)\n\nimport sys\nif __name__ == \"__main__\":\n    trials = int(sys.argv[1]) if len(sys.argv) > 1 else 10 \n    bound = 2 \n    pascals_triangle(20)\n    # ev = ev_half_plane(bound, trials)\n    # print(ev)\n    # for steps in range(bound, bound+trials):\n    #     cf_paths_out = closed_form_paths_out(steps, bound)\n    #     num_paths_out = compute_number_paths_out(steps, bound)\n    #     num_paths = compute_number_paths(steps, bound)\n    #     prob_leave = probability_leaving(steps, bound)\n    #     # counting(steps, bound)\n    #     print(f\"CF paths out: {cf_paths_out} Paths Out: {num_paths_out} diff {cf_paths_out - num_paths_out}\")\n    #     # print(f\"Probability of leaving in under {steps} steps: {prob_leave}\")\n    \n    #markov_processes()\n    # b_1d = (float(\"-inf\"), 7)\n    # trials = 1\n    # steps = 10\n    # run_sim(trials, steps, b_1d)", "meta": {"hexsha": "da7273d77c57a50d8cfb7b4e00b8de801793a0b6", "size": 9655, "ext": "py", "lang": "Python", "max_stars_repo_path": "walks.py", "max_stars_repo_name": "collinwarner/Random_Walks_Z-2", "max_stars_repo_head_hexsha": "2008e4a1b77c8828ce1fdae7bf2365ed68828573", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "walks.py", "max_issues_repo_name": "collinwarner/Random_Walks_Z-2", "max_issues_repo_head_hexsha": "2008e4a1b77c8828ce1fdae7bf2365ed68828573", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "walks.py", "max_forks_repo_name": "collinwarner/Random_Walks_Z-2", "max_forks_repo_head_hexsha": "2008e4a1b77c8828ce1fdae7bf2365ed68828573", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6182432432, "max_line_length": 154, "alphanum_fraction": 0.5783531849, "include": true, "reason": "import numpy", "num_tokens": 2961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.9124361527383703, "lm_q1q2_score": 0.8584105732903013}}
{"text": "# Import all libraries for this portion of the blog post\nfrom scipy.integrate import quad\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\ndef print_normal_distribution():\n    # print standard normal distribution\n\n    x = np.linspace(-4, 4, num=100)\n    constant = 1.0 / np.sqrt(2*np.pi)\n    pdf_normal_distribution = constant * np.exp((-x**2) / 2.0)\n    fig, ax = plt.subplots(figsize=(10, 5))\n    ax.plot(x, pdf_normal_distribution)\n    ax.set_ylim(0)\n    ax.set_title('Standardized Normal Distribution', size=20)\n    ax.set_ylabel('Probability Density', size=20)\n    plt.show()\n\n\ndef normal_p_density(x):\n    c = 1.0 / np.sqrt(2*np.pi)\n    return c * np.exp((-x**2) / 2.0)\n\n\ndef calculate_p_from_z(z):\n    \"\"\"\n    two tails\n    \"\"\"\n    p1, _ = quad(normal_p_density, np.NINF, -z)\n    p2, _ = quad(normal_p_density, z, np.Inf)\n    return p1 + p2\n\n\ndef get_z_table():\n    std_normal_table = pd.DataFrame(data=[],\n                                    index=np.round(np.arange(0, 3.5, .1), 2),\n                                    columns=np.round(np.arange(0.00, .1, 0.01), 2)\n                                    )\n    for i in std_normal_table.index:\n        for c in std_normal_table.columns:\n            z = np.round(i + c, 2)\n            value, _ = quad(normal_p_density, np.NINF, z)\n            std_normal_table.loc[i, c] = value\n\n    std_normal_table.index = std_normal_table.index.astype(str)\n    std_normal_table.columns = [str(column).ljust(4, '0') for column in std_normal_table.columns]\n    return std_normal_table\n\n\nif __name__ == \"__main__\":\n    # print z distribution\n    # print_normal_distribution()\n\n    # calculate cumulative distribution\n    # print(calculate_p_from_z(3), '\\n')\n\n    # print z-table for approximating  p-value by hand\n    print(get_z_table().to_markdown())\n", "meta": {"hexsha": "dd4002aed1bf8bee809d0770bfd9fb530b9551e0", "size": 1815, "ext": "py", "lang": "Python", "max_stars_repo_path": "common/z_table.py", "max_stars_repo_name": "jiz148/z-test", "max_stars_repo_head_hexsha": "d68c6f895bca3ec97fd5adbfb663cd6c3817e69a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "common/z_table.py", "max_issues_repo_name": "jiz148/z-test", "max_issues_repo_head_hexsha": "d68c6f895bca3ec97fd5adbfb663cd6c3817e69a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common/z_table.py", "max_forks_repo_name": "jiz148/z-test", "max_forks_repo_head_hexsha": "d68c6f895bca3ec97fd5adbfb663cd6c3817e69a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7540983607, "max_line_length": 97, "alphanum_fraction": 0.6231404959, "include": true, "reason": "import numpy,from scipy", "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993027, "lm_q2_score": 0.9099070121457543, "lm_q1q2_score": 0.8583585716537351}}
{"text": "# %%\r\n\"\"\"In this code we wanna calculate the inverse of a matrix in numpy.\"\"\"\r\nimport numpy as np\r\n# %%\r\na = np.arange(1, 5).reshape((2, 2))\r\na\r\n# %%\r\nb = np.linalg.inv(a)\r\n# %%\r\na.dot(b)\r\n# %%\r\nhelp(np.allclose)\r\n# %%\r\nnp.eye(2)\r\n# %%\r\nnp.allclose(a.dot(b), np.eye(2))\r\n# %%\r\nc = np.array([1, 2, 3, 4])\r\nc\r\n\"\"\"\r\n\"np.linalg.inv(c) will raise an error. for inversing a matrix in\r\nit should be at least 2d.\r\n\"\"\"\r\n# %%\r\nhelp(np.linalg.inv)\r\n# %%\r\nhelp(np.allclose)\r\n", "meta": {"hexsha": "2161e40018a04511df4bca18eac2aaef5a86df28", "size": 463, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumPy/24_InverseOfAMatrix.py", "max_stars_repo_name": "ErfanRasti/PythonCodes", "max_stars_repo_head_hexsha": "5e4569b760b60c9303d5cc68650a2448c9065b6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-01T09:59:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T09:59:22.000Z", "max_issues_repo_path": "NumPy/24_InverseOfAMatrix.py", "max_issues_repo_name": "ErfanRasti/PythonCodes", "max_issues_repo_head_hexsha": "5e4569b760b60c9303d5cc68650a2448c9065b6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumPy/24_InverseOfAMatrix.py", "max_forks_repo_name": "ErfanRasti/PythonCodes", "max_forks_repo_head_hexsha": "5e4569b760b60c9303d5cc68650a2448c9065b6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.5357142857, "max_line_length": 72, "alphanum_fraction": 0.555075594, "include": true, "reason": "import numpy", "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.9099070090919013, "lm_q1q2_score": 0.8583585702221204}}
{"text": "import numpy as np\n\n# CHANGEME:\nsetval = [\"c_1\", \"c_2\", \"c_2\"]\nC = [[1, 0.3, 0.2], [0.3, 1, 0.1], [0.2, 0.1, 1]]\nS = [0.2, 0.4, 0.3]\n\nprint(\"The correlation matrix C:\")\n\nprint(f\"     {'   '.join([str(i) for i in setval])}\")\nfor rl, row in zip(setval, C):\n    print('%s [%s]' % (rl, ' '.join('%04s' % i for i in row)))\n\nprint(\"- \" * 10)\n\nassert len(C) == 3\nfor i in C:\n    assert len(i) == 3\n\ninv_c = [3*[None] for _i in range(3)]\n\nprint(\"The Leibniz formula for the determinant of a 3 × 3 matrix:\")\nprint(\"detC = c_11​⋅(c_22​⋅c_33​ − c_32​⋅c_23​) − c_12​⋅(c_21​⋅c_33 ​− c_31​⋅c_23​) + c_13​⋅(c_21​⋅c_32​ − c_31​⋅c_22​)\\n\")\n\ndet = (C[0][0] * ((C[1][1]*C[2][2]) - (C[2][1]*C[1][2]))) - (C[0][1] * ((C[1][0] *\n                                                                         C[2][2]) - (C[2][0]*C[1][2]))) + (C[0][2] * ((C[1][0]*C[2][1]) - (C[2][0]*C[1][1])))\nprint(f\"{C[0][0]} * ({C[1][1]}*{C[2][2]} - {C[2][1]}*{C[1][2]}) - \", end=\"\")\nprint(f\"{C[0][1]} * ({C[1][0]}*{C[2][2]} - {C[2][0]}*{C[1][2]}) + \", end=\"\")\nprint(f\"{C[0][2]} * ({C[1][0]}*{C[2][1]} - {C[2][0]}*{C[1][1]}) = \")\n\nprint(f\"{C[0][0]} * ({C[1][1]*C[2][2]:.3f} - {C[2][1]*C[1][2]:.3f}) - \", end=\"\")\nprint(f\"{C[0][1]} * ({C[1][0]*C[2][2]:.3f} - {C[2][0]*C[1][2]:.3f}) + \", end=\"\")\nprint(f\"{C[0][2]} * ({C[1][0]*C[2][1]:.3f} - {C[2][0]*C[1][1]:.3f}) = \")\n\nprint(f\"{C[0][0]} * ({(C[1][1]*C[2][2]) - (C[2][1]*C[1][2]):.3f}) - \", end=\"\")\nprint(f\"{C[0][1]} * ({(C[1][0]*C[2][2]) - (C[2][0]*C[1][2]):.3f}) + \", end=\"\")\nprint(f\"{C[0][2]} * ({(C[1][0]*C[2][1]) - (C[2][0]*C[1][1]):.3f}) = \")\n\nprint(f\"{C[0][0] * ((C[1][1]*C[2][2]) - (C[2][1]*C[1][2])):.3f} - \", end=\"\")\nprint(f\"{C[0][1] * ((C[1][0]*C[2][2]) - (C[2][0]*C[1][2])):.3f} + \", end=\"\")\nprint(f\"{C[0][2] * ((C[1][0]*C[2][1]) - (C[2][0]*C[1][1])):.3f} = {det:.3f}\")\n\nprint(\"- \" * 10)\n\nprint(f\"The invered correlation matrix at C_ij is (-1)^(i+j) * (new C_ij) / detC\")\nprint(f\"Example C_12 = (-1)^(1+2) * (C_21*C_33 - C_31*C23) / detC\")\n\nfor i in range(3):\n    for j in range(3):\n        adj = [[n for ii, n in enumerate(row) if ii != i]\n               for jj, row in enumerate(C) if jj != j]\n        d = adj[0][0]*adj[1][1] - adj[0][1]*adj[1][0]\n        print(\n            f\"C_{i+1}{j+1}\\t= (-1)^({i+1}+{j+1}) * ({adj[0][0]}*{adj[1][1]} - {adj[0][1]}*{adj[1][0]}) / {det:.3f}\")\n        sgn = (-1)**(i+j)\n        inv_c[i][j] = sgn * d / det\n        print(\n            f\"\\t= {'-' if (-1)**(i+j) < 0 else ''}{adj[0][0]*adj[1][1] - adj[0][1]*adj[1][0]:.3f} / {det:.3f} = {inv_c[i][j]:.3f}\")\n\n\nprint(\"\\nThe invered correlation matrix C:\")\n\nprint(f\"     {'     '.join([str(i) for i in setval])}\")\nfor rl, row in zip(setval, inv_c):\n    print('%s [%s]' % (rl, ' '.join(f\"{i:.3f}\" for i in row)))\n\nprint(\"- \" * 10)\n\nc = 0\nfor row in inv_c:\n    if c == 1:\n        print(\"SC^(-1)\\t= \", end=\"\")\n    else:\n        print(\" \\t  \", end=\"\")\n    print('[%s]' % (' '.join(f\"{i:.3f}\" for i in row)), end=\"\")\n    c+=1\n    if c == 2: \n        print(' * [%s] = ' % (' '.join(f\"{i:.3f}\" for i in S)))\n    else: \n        print()\nprint()\nsc_inv = []\nfor i in range(len(inv_c[0])):  # this loops through columns of the matrix\n    total = 0\n    for j in range(len(S)):  # this loops through vector coordinates & rows of matrix\n        total += S[j] * inv_c[j][i]\n        print(f\"({S[j]} * {inv_c[j][i]:.3f}) + \", end=\"\")\n    print(f\" = {total:.3f}\")\n    sc_inv.append(total)\nprint()\nprint('SC^(-1) = [%s]' % (' '.join(f\"{i:.3f}\" for i in sc_inv)))\nprint(\"- \" * 10)\n\n\nc = 0\nfor row in S:\n    if c == 1:\n        print('SC^(-1) * S^T\\t= ', end=\"\")\n    else:\n        print(\"\\t\\t  \", end=\"\")\n    print(row, end=\"\")\n    c+=1\n    if c == 2: \n        print(' * [%s] = %f' % (' '.join(f\"{i:.3f}\" for i in sc_inv), np.array(S).T.dot(sc_inv)))\n    else: \n        print()\n\n", "meta": {"hexsha": "00a178947c2e9e0c8789f28224761bea5103080d", "size": 3755, "ext": "py", "lang": "Python", "max_stars_repo_path": "03_anomaly/ides-score.py", "max_stars_repo_name": "StoneSwine/IMT4204-IDS_software", "max_stars_repo_head_hexsha": "f6a39d88fd44b71134408197da9dd27b872bd550", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "03_anomaly/ides-score.py", "max_issues_repo_name": "StoneSwine/IMT4204-IDS_software", "max_issues_repo_head_hexsha": "f6a39d88fd44b71134408197da9dd27b872bd550", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "03_anomaly/ides-score.py", "max_forks_repo_name": "StoneSwine/IMT4204-IDS_software", "max_forks_repo_head_hexsha": "f6a39d88fd44b71134408197da9dd27b872bd550", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7685185185, "max_line_length": 157, "alphanum_fraction": 0.4207723036, "include": true, "reason": "import numpy", "num_tokens": 1742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.9099070054272775, "lm_q1q2_score": 0.8583585682143366}}
{"text": "#Import stuff\nimport numpy as np\nimport matplotlib.pyplot as pp\n\na = 0.5 #A parameter defined in the problem statement\n\ndef initial_guess(x): #A function defining our initial guess\n    return 1 + 2*x\n\ndef phi(x):  #A function defined in the problem statement\n    return 20*np.pi*x*x*x\n\ndef phiprime(x):  #The derivative of the above function\n    return 60*np.pi*x*x\n\ndef phidoubleprime(x):  #The derivative of the derivative of the two-above function\n    return 120*np.pi*x\n\ndef f(x):  #u''(x) = f(x), which is this f\n    return -20. + a*phidoubleprime(x)*np.cos(phi(x)) - a*(phiprime(x))**2 *np.sin(phi(x))\n\ndef true_solution(x):  #The analytic solution\n    return 1 + 12*x - 10*x*x + a*np.sin(phi(x))\n\n\nn_grid = 255 #Number of interior grid points\nh = 1./float(n_grid+1) #size of grid spacing\nu_0 = 1. #Left boundary condition\nu_1 = 3. #Right boundary condition\nepsilon = 1e-3  #The error tolerance I want to be within the true value before saying I've converged\n\niter_max = 50000 #Set a maximum number of iterations before quitting\n\n\n#In what follows, we are trying to solve the matrix equation A u = b\n\nA_diagonal = -2.  #The diagonol elements of my A matrix\nA_offdiagonal = 1. #The off-diagonol elements of my tridiagonol A matrix\n\n\nu = np.zeros(n_grid) #the solution vector\n\nx_binedges = [] #This list will store the x-values of the edges of the cells\nfor i in range(n_grid):\n    x_binedges.append(float(i+1)/float(n_grid+1))\n\n#initialize the solution vector:\nfor i in range(n_grid):\n    u[i] = initial_guess(x_binedges[i])\n\nb = np.zeros(n_grid)  #The RHS vector\n\nfor i in range(n_grid): #Initialize this\n    b[i] = f(x_binedges[i])*h*h\n\nb[0] = b[0] - u_0 #Add LHS boundary condition to b\nb[n_grid-1] = b[n_grid-1] - u_1 #Add RHS boundary condition to b\n\ntrue_sol = np.zeros(n_grid) #Make a vector to store the values of the true solution\n\nfor i in range(n_grid): #Calculate values of true solution\n    true_sol[i] = true_solution(x_binedges[i])\n\n#Next two lines is to plot the true solution\nx_toplot = np.linspace(0,1,200)\npp.plot(x_toplot,true_solution(x_toplot),label=\"True Solution\",lw=4)\n\n#Begin the iteration\nfor k in range(iter_max):\n    for i in range(len(u)):\n\n        if i==0:  #If we're on the first row, only add A[i][i+1]\n            summation = A_offdiagonal * u[i+1]\n        elif i== (len(u)-1): #If we're on the last row, only add A[i][i-1]\n            summation = A_offdiagonal * u[i-1]\n        else:  #Only need to add two elements together\n            summation = A_offdiagonal * u[i+1] + A_offdiagonal * u[i-1]\n        u[i] = 1./A_diagonal * (b[i] - summation) #Update u based on Jacobi algorithm\n\n    #check for convergence\n    numconverge = 0 #count the number of elements of u which have converged\n    for i in range(len(u)):\n        if abs(u[i] - true_sol[i]) < epsilon: #If converged within epsilon\n                numconverge += 1\n\n    if numconverge == len(u):  #If all the elements of x have converged\n        print \"Converged!  After %d loops\" % (k+1)\n        break\n\n    #Plot the 20th, 100th, and 1000th iteration\n    if k==(20-1) or k==(100-1) or k==(1000-1):\n        s = str(k+1) + \" iterations\"\n        pp.plot(x_binedges,u,label=s,lw=2.5)\n\n\nelse: #If for loop completes with convergence not being acheived\n    print \"Convergence not achieved after %d number of iterations\" % (k+1)\n\n#Plot the final solution and save te figure\npp.plot(x_binedges,u,label='final iteration', lw=2.5)\npp.xlabel(\"x\")\npp.ylabel(\"u(x)\")\npp.legend(loc='best')\npp.xlim(0,1)\npp.savefig('problem1a.pdf')\n", "meta": {"hexsha": "38f3806608243c01bc236205787fad1d0218785f", "size": 3516, "ext": "py", "lang": "Python", "max_stars_repo_path": "p1/basicsolver.py", "max_stars_repo_name": "joshuawallace/num_hw4", "max_stars_repo_head_hexsha": "bc56ba155d2679a5c8cbdbbca13c402770e88af6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "p1/basicsolver.py", "max_issues_repo_name": "joshuawallace/num_hw4", "max_issues_repo_head_hexsha": "bc56ba155d2679a5c8cbdbbca13c402770e88af6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "p1/basicsolver.py", "max_forks_repo_name": "joshuawallace/num_hw4", "max_forks_repo_head_hexsha": "bc56ba155d2679a5c8cbdbbca13c402770e88af6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1698113208, "max_line_length": 100, "alphanum_fraction": 0.6763367463, "include": true, "reason": "import numpy", "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650673, "lm_q2_score": 0.8991213874066956, "lm_q1q2_score": 0.8583439099359373}}
{"text": "import numpy as np\n\n\n'''\nProblem 1.2\n'''\n\ndef expo_func(omega, t):\n    return np.exp(-1*omega*(t + np.abs(t)))\n\ndef first_forward(t, wdt, omega=1.):\n    # For convenience, set omega = 1\n    dt = wdt / omega\n    # Evaluate\n    tdt = t + dt\n    expf = expo_func(omega, t)\n    expf_plus = expo_func(omega, tdt)\n    # Finite difference, forward\n    dexpdt_forward = (expf_plus-expf)/dt\n    return dexpdt_forward\n\ndef first_backward(t, wdt, omega=1.):\n    # For convenience, set omega = 1\n    dt = wdt / omega\n    # Evaluate\n    tdt = t - dt\n    expf = expo_func(omega, t)\n    expf_neg = expo_func(omega, tdt)\n    # Finite difference, forward\n    dexpdt_back = (expf-expf_neg)/dt\n    return dexpdt_back\n\ndef second_centered(t, wdt, omega=1.):\n    # For convenience, set omega = 1\n    dt = wdt / omega\n    # Evaluate\n    tdtp = t + dt\n    tdtn = t - dt\n    expf_pos = expo_func(omega, tdtp)\n    expf_neg = expo_func(omega, tdtn)\n    # Finite difference, forward\n    dexpdt_second = (expf_pos-expf_neg)/(2*dt)\n    return dexpdt_second\n\n'''\nProblem 1.2\n'''\n\ndef sinh_func(k, x):\n    return np.sinh(k*x)\n\ndef sinh_first_forward(x, kdx, k=1.):\n    dx = kdx / k\n    # Evaluate\n    xdx = x + dx\n    expf = sinh_func(k, x)\n    expf_plus = sinh_func(k, xdx)\n    # Finite difference, forward\n    dexpdt_forward = (expf_plus-expf)/dx\n    return dexpdt_forward\n\ndef sinh_first_backward(x, kdx,k=1.):\n    dx = kdx / k\n    # Evaluate\n    xdx = x - dx\n    expf = sinh_func(k, x)\n    expf_neg = sinh_func(k, xdx)\n    # Finite difference, forward\n    dexpdt_forward = (expf-expf_neg)/dx\n    return dexpdt_forward\n\ndef sinh_second_center(x, kdx,k=1.):\n    dx = kdx / k\n    # Evaluate\n    xdxn = x - dx\n    xdxp = x + dx\n    sinh_pos = sinh_func(k, xdxp)\n    sinh_neg = sinh_func(k, xdxn)\n    # Finite difference, forward\n    dfdx_second = (sinh_pos-sinh_neg)/(2*dx)\n    return dfdx_second\n\ndef sinh_fourth(x, kdx,k=1.):\n    dx = kdx / k\n    # Evaluate\n    xdxn = x - dx\n    xdxp = x + dx\n    xdxn2 = x - 2*dx\n    xdxp2 = x + 2*dx\n    sinh_pos = sinh_func(k, xdxp)\n    sinh_neg = sinh_func(k, xdxn)\n    sinh_pos2 = sinh_func(k, xdxp2)\n    sinh_neg2 = sinh_func(k, xdxn2)\n    # Finite difference, forward\n    dfdx_fourth = (4./3) * (sinh_pos-sinh_neg)/2/dx - (1/3)*(sinh_pos2-sinh_neg2)/4/dx\n    return dfdx_fourth\n\n'''\nProblem 1.8\n'''\n\ndef sin_func(omega, t, A=1., sigma=1e-5):\n    # Noise\n    noise = 2*np.random.random(np.atleast_1d(t).size) - 1\n    Ap = A * (1 + noise * sigma)\n    if not isinstance(t, np.ndarray):\n        Ap = Ap[0]\n    return Ap*np.sin(omega*t)\n\ndef sin_first_forward(t, omegadt, omega=1., sigma=1e-5):\n    dt = omegadt / omega\n    # Evaluate\n    tdt = t + dt\n    f = sin_func(omega, t, sigma=sigma)\n    f_plus = sin_func(omega, tdt, sigma=sigma)\n    # Finite difference, forward\n    dfdt_forward = (f_plus-f)/dt\n    return dfdt_forward\n\ndef sin_first_backward(t, omegadt,omega=1., sigma=1e-5):\n    dt = omegadt / omega\n    # Evaluate\n    tdt = t - dt\n    f = sin_func(omega, t, sigma=sigma)\n    f_neg = sin_func(omega, tdt, sigma=sigma)\n    # Finite difference, forward\n    dfdt_back = (f-f_neg)/dt\n    return dfdt_back\n\ndef sin_second_center(t, omegadt,omega=1., sigma=1e-5):\n    dt = omegadt / omega\n    tdtp = t + dt\n    tdtn = t - dt\n    f_neg = sin_func(omega, tdtn, sigma=sigma)\n    f_pos = sin_func(omega, tdtp, sigma=sigma)\n    dfdt_second = (f_pos-f_neg)/dt/2\n    return dfdt_second\n\n", "meta": {"hexsha": "28472e4e49e3405700c37e2183c8e16721f120f1", "size": 3393, "ext": "py", "lang": "Python", "max_stars_repo_path": "os_classes/ocea257/chapter1.py", "max_stars_repo_name": "profxj/os_classes", "max_stars_repo_head_hexsha": "8435e985c8e33a3e736a5c330866054e8ffcbed7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "os_classes/ocea257/chapter1.py", "max_issues_repo_name": "profxj/os_classes", "max_issues_repo_head_hexsha": "8435e985c8e33a3e736a5c330866054e8ffcbed7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-04-04T18:28:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-07T17:26:15.000Z", "max_forks_repo_path": "os_classes/ocea257/chapter1.py", "max_forks_repo_name": "profxj/os_classes", "max_forks_repo_head_hexsha": "8435e985c8e33a3e736a5c330866054e8ffcbed7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4100719424, "max_line_length": 86, "alphanum_fraction": 0.6206896552, "include": true, "reason": "import numpy", "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456935, "lm_q2_score": 0.8991213806488609, "lm_q1q2_score": 0.8583439058048842}}
{"text": "# Collection of simple optimization algorithms from the Computational Economics course\n#\n# by Fedor Iskhakov, 2020\n\nimport numpy as np\n\ndef bisection(f,a=0,b=1,tol=1e-6,maxiter=100,callback=None):\n    '''Bisection method for solving equation f(x)=0\n    on the interval [a,b], with given tolerance and number of iterations.\n    Callback function is invoked at each iteration if given.\n    '''\n    if f(a)*f(b)>0:\n        raise ValueError('Function has the same sign at the bounds')\n    for i in range(maxiter):\n        err = abs(b-a)\n        if err<tol: break\n        x = (a+b)/2\n        a,b = (x,b) if f(a)*f(x)>0 else (a,x)\n        if callback != None: callback(err=err,x=x,iter=i)\n    else:\n        raise RuntimeError('Failed to converge in %d iterations'%maxiter)\n    return x\n\n\ndef newton(fun,grad,x0,tol=1e-6,maxiter=100,callback=None):\n    '''Newton method for solving equation f(x)=0\n    with given tolerance and number of iterations.\n    Callback function is invoked at each iteration if given.\n    '''\n    for i in range(maxiter):\n        x1 = x0 - fun(x0)/grad(x0)\n        err = abs(x1-x0)\n        if callback != None: callback(err=err,x0=x0,x1=x1,iter=i)\n        if err<tol: break\n        x0 = x1\n    else:\n        raise RuntimeError('Failed to converge in %d iterations'%maxiter)\n    return (x0+x1)/2\n\n\ndef solve_sa(F,x0,tol=1e-6,maxiter=100,callback=None):\n    '''Computes the solution of fixed point equation x = F(x)\n    with given initial value x0 and algorithm parameters\n    Method: successive approximations\n    '''\n    for i in range(maxiter):  # main loop\n        x1 = F(x0)  # update approximation\n        err = np.amax(abs(x0-x1))  # allow for x to be array\n        if callback != None: callback(iter=i,err=err,x=x1,x0=x0)\n        if err<tol:  \n            break  # break out if converged\n        x0 = x1  # get ready to the next iteration\n    else:\n        raise RuntimeError('Failed to converge in %d iterations'%maxiter)\n    return x1\n\n\ndef newton2(fun,grad,x0,tol=1e-6,maxiter=100,callback=None):\n    '''Newton method for solving equation f(x)=0, x is vector of 2 elements,\n    with given tolerance and number of iterations.\n    Callback function is invoked at each iteration if given.\n    '''\n    # conversion to array function of array argument\n    npfun = lambda x: np.asarray(fun(x[0],x[1]))\n    npgrad = lambda x: np.asarray(grad(x[0],x[1]))\n    for i in range(maxiter):\n        x1 = x0 - np.linalg.inv(npgrad(x0)) @ npfun(x0)  # matrix version\n        err = np.amax(np.abs(x1-x0))  # vector version\n        if callback != None: callback(iter=i,err=err,x0=x0,x1=x1,fun=fun)\n        if err<tol: break\n        x0 = x1\n    else:\n        raise RuntimeError('Failed to converge in %d iterations'%maxiter)\n    return (x0+x1)/2\n    \n\n# def grid_search(fun,bounds=(0,1),ngrid=10):\n#     '''Grid search between given bounds over given number of points'''\n#     grid = np.linspace(*bounds,ngrid)\n#     func = fun(grid)\n#     i = np.argmax(func)  # index of the element attaining maximum\n#     return grid[i]\n\n", "meta": {"hexsha": "3954809982e16afec51f36e2a9e46c4680c517e8", "size": 3031, "ext": "py", "lang": "Python", "max_stars_repo_path": "_static/include/optim.py", "max_stars_repo_name": "Kebatotkulov/CompEcon", "max_stars_repo_head_hexsha": "a73f23c397cf167fb432082eb205fd0714a7a788", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2020-11-17T04:03:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:49:31.000Z", "max_issues_repo_path": "_static/include/optim.py", "max_issues_repo_name": "Kebatotkulov/CompEcon", "max_issues_repo_head_hexsha": "a73f23c397cf167fb432082eb205fd0714a7a788", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_static/include/optim.py", "max_forks_repo_name": "Kebatotkulov/CompEcon", "max_forks_repo_head_hexsha": "a73f23c397cf167fb432082eb205fd0714a7a788", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2020-11-17T05:31:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:09:13.000Z", "avg_line_length": 36.0833333333, "max_line_length": 86, "alphanum_fraction": 0.637743319, "include": true, "reason": "import numpy", "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474220263198, "lm_q2_score": 0.8991213725394589, "lm_q1q2_score": 0.8583439003835607}}
{"text": "# Project Euler Problem 9 Solution\n#\n# Problem statement:\n# A Pythagorean triplet is a set of three natural numbers,\n# a < b < c, for which, a^2 + b^2 = c^2. For example,\n# 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one\n# Pythagorean triplet for which a + b + c = 1000. Find the\n# product abc.\n#\n# Solution description:\n# --\n#\n# Author: Daniel Schuette\n# Date: 2018/02/12\n# License: MIT (see ../LICENSE.md)\nimport time\n\nimport numpy as np\n\n\ndef pythagorean_triplet(a, b, c):\n    \"\"\"\n    Tests whether a^2 + b^2 = c^2.\n    \"\"\"\n    return a**2 + b**2 == c**2\n\n\ndef find_triplet(n):\n    \"\"\"\n    Finds a Pythagorean triplet for which\n    a + b + c = n and returns the product a*b*c.\n    \"\"\"\n    i, j, k = 0, 0, 0\n    for i in range(1, n):\n        for j in range(1, n):\n            k = np.sqrt(i**2 + j**2)\n            if pythagorean_triplet(i, j, k) and (i+j+k) == n:\n                return i*j*k\n\n\nif __name__ == \"__main__\":\n    # calculate result\n    start = time.time()\n    solution = find_triplet(1000)\n    end = time.time()\n\n    # print result\n    print(f\"Solution: {solution}\")\n    print(f\"Elapsed time: {(end - start):.5f}s\")\n", "meta": {"hexsha": "0f62f1192354a9a40f207e801b0dd4790d79a756", "size": 1138, "ext": "py", "lang": "Python", "max_stars_repo_path": "py_src/problem009.py", "max_stars_repo_name": "PhilippSchuette/projecteuler", "max_stars_repo_head_hexsha": "b74f76e8f27769d5cfc4227ccfb272d0a83ef587", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-09-24T14:14:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T01:57:12.000Z", "max_issues_repo_path": "py_src/problem009.py", "max_issues_repo_name": "PhilippSchuette/projecteuler", "max_issues_repo_head_hexsha": "b74f76e8f27769d5cfc4227ccfb272d0a83ef587", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2018-09-24T14:18:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-08T07:03:31.000Z", "max_forks_repo_path": "py_src/problem009.py", "max_forks_repo_name": "PhilippSchuette/projecteuler", "max_forks_repo_head_hexsha": "b74f76e8f27769d5cfc4227ccfb272d0a83ef587", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-03-01T14:22:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T01:57:53.000Z", "avg_line_length": 22.76, "max_line_length": 61, "alphanum_fraction": 0.5729349736, "include": true, "reason": "import numpy", "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.9059898248255074, "lm_q1q2_score": 0.8583175911914812}}
{"text": "import numpy as np\nfrom numpy.linalg import norm\n\nfrom random import normalvariate\nfrom math import sqrt\n\n\ndef random_unit_vector(n):\n    unnormalized = [normalvariate(0, 1) for _ in range(n)]\n    the_norm = sqrt(sum(x * x for x in unnormalized))\n    return [x / the_norm for x in unnormalized]\n\n\ndef svd_1d(A, epsilon=1e-10):\n    '''Compute the one-dimensional SVD.\n\n    Arguments:\n        A: an n-by-m matrix\n        epsilon: a tolerance\n\n    Returns:\n        the top singular vector of A.\n    '''\n\n    n, m = A.shape\n    x = random_unit_vector(min(n, m))\n    last_v = None\n    current_v = x\n\n    if n > m:\n        B = np.dot(A.T, A)\n    else:\n        B = np.dot(A, A.T)\n\n    iterations = 0\n    while True:\n        iterations += 1\n        last_v = current_v\n        current_v = np.dot(B, last_v)\n        current_v = current_v / norm(current_v)\n\n        if abs(np.dot(current_v, last_v)) > 1 - epsilon:\n            print(\"converged in {} iterations!\".format(iterations))\n            return current_v\n\n\ndef svd(A, k=None, epsilon=1e-10):\n    '''Compute the singular value decomposition of a matrix A using\n    the power method.\n\n    Arguments:\n        A: an n-by-m matrix\n        k: the number of singular values to compute\n           If k is None, compute the full-rank decomposition.\n        epsilon: a tolerance factor\n\n    Returns:\n        A tuple (S, u, v), where S is a list of singular values,\n        u is an n-by-k matrix containing the left singular vectors,\n        v is a k-by-m matrix containnig the right-singular-vectors\n    '''\n    A = np.array(A, dtype=float)\n    n, m = A.shape\n    svd_so_far = []\n    if k is None:\n        k = min(n, m)\n\n    for i in range(k):\n        matrix_for_1d = A.copy()\n\n        for singular_value, u, v in svd_so_far[:i]:\n            matrix_for_1d -= singular_value * np.outer(u, v)\n\n        if n > m:\n            v = svd_1d(matrix_for_1d, epsilon=epsilon)  # next singular vector\n            u_unnormalized = np.dot(A, v)\n            sigma = norm(u_unnormalized)  # next singular value\n            u = u_unnormalized / sigma\n        else:\n            u = svd_1d(matrix_for_1d, epsilon=epsilon)  # next singular vector\n            v_unnormalized = np.dot(A.T, u)\n            sigma = norm(v_unnormalized)  # next singular value\n            v = v_unnormalized / sigma\n\n        svd_so_far.append((sigma, u, v))\n\n    singular_values, us, vs = [np.array(x) for x in zip(*svd_so_far)]\n    return singular_values, us.T, vs\n", "meta": {"hexsha": "dbd9fcbd45dc2581d283082209b9711b30414194", "size": 2460, "ext": "py", "lang": "Python", "max_stars_repo_path": "singular-value-decomposition/svd.py", "max_stars_repo_name": "dawidvdh/programmers-introduction-to-mathematics", "max_stars_repo_head_hexsha": "2345a118f055bb7f98140ee58d5332c6691e1fc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2915, "max_stars_repo_stars_event_min_datetime": "2018-10-29T12:42:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:12:12.000Z", "max_issues_repo_path": "singular-value-decomposition/svd.py", "max_issues_repo_name": "dawidvdh/programmers-introduction-to-mathematics", "max_issues_repo_head_hexsha": "2345a118f055bb7f98140ee58d5332c6691e1fc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2018-12-04T23:58:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T16:22:41.000Z", "max_forks_repo_path": "singular-value-decomposition/svd.py", "max_forks_repo_name": "dawidvdh/programmers-introduction-to-mathematics", "max_forks_repo_head_hexsha": "2345a118f055bb7f98140ee58d5332c6691e1fc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 272, "max_forks_repo_forks_event_min_datetime": "2018-11-04T06:53:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T17:31:45.000Z", "avg_line_length": 27.6404494382, "max_line_length": 78, "alphanum_fraction": 0.5959349593, "include": true, "reason": "import numpy,from numpy", "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763574, "lm_q2_score": 0.9149009497722478, "lm_q1q2_score": 0.8582905516655931}}
{"text": "import numpy as np\nfrom numpy import linalg as la\nfrom typing import Union\n\n\ndef mahalanobis_dist(data, x):\n    \"\"\"Compute mahalanobis distance of point x to data.\"\"\"\n    C = np.cov(data.T)\n    mu = np.mean(data, axis=0)\n    IC = la.inv(C)\n    dx = x - mu\n    return np.sqrt(dx.T@IC@dx)\n\ndef mahalanobis_cont(d1, d2):\n    \"\"\"Compute mahalanobis distance for continuous variables.\"\"\"\n    mu1 = np.mean(d1, axis=0)\n    mu2 = np.mean(d2, axis=0)\n    C = np.cov(np.concatenate([d1, d2]).T)\n    IC = la.inv(C)\n    dmu = mu1-mu2\n    return np.sqrt(dmu.T@IC@dmu)\n\ndef mahalanobis_bin(d1, d2):\n    \"\"\"Compute mahalanobis distance for binary variables.\n    If for one of the groups the estimated probabilitiy is zero\n        result is the absolute difference between probabilities,\n    if both est. probs are zero result is zero,\n    else: result is given by (p1-p2)*np.log(p1/p2)\n    in the last step we sum over variables.\n        \"\"\"\n    d1 = d1.to_numpy()\n    d2 = d2.to_numpy()\n    p1 = np.sum(d1, axis=0)/len(d1)\n    p2 = np.sum(d2, axis=0)/len(d2)\n    logarg = np.divide(p1, p2, out=np.ones_like(p1), where=((p1!=0) & (p2!=0)))\n    result = (p1-p2)*np.log(logarg,out=np.zeros_like(p1), \n                            where=((p1!=0) & (p2!=0)))\n    zero_one_mask = np.logical_xor(p1==0, p2==0)\n    result[zero_one_mask] = np.abs(p1[zero_one_mask]-p2[zero_one_mask])\n    return np.sum(result)\n\n\ndef gen_mahalanobis(df, g1:Union[None, list]=None, g2:Union[None, list]=None)->float:\n    \"\"\"Takes dataframe and computes generalised mahalanobis distance between the two groups. \n    Given in the paper:\n        Barhen, Avner, and J. J. Daudin. \n        \"Generalization of the Mahalanobis distance in the mixed case.\" \n        Journal of Multivariate Analysis 53.2 (1995): 332-342.\n    By default the two groups are exposed==1 and exposed==0\n    Optinally one can pass two lists of indices g1 and g2.\n    \"\"\"\n    bin_var_cols = [k for k in df.keys() if k.startswith('b')]\n    cont_var_cols = [k for k in df.keys() if k.startswith('x')]\n    if isinstance(g1, type(None)) or isinstance(g2, type(None)):    \n        df1_c = df[cont_var_cols][df.exposed==0]\n        df2_c = df[cont_var_cols][df.exposed==1]\n        df1_b = df[bin_var_cols][df.exposed==0]\n        df2_b = df[bin_var_cols][df.exposed==1]        \n    else:\n        df1_c = df.loc[g1][cont_var_cols]\n        df2_c = df.loc[g2][cont_var_cols]\n        df1_b = df.loc[g1][bin_var_cols]\n        df2_b = df.loc[g2][bin_var_cols]   \n    Jc = mahalanobis_cont(df1_c, df2_c)\n    Jb = mahalanobis_bin(df1_b, df2_b)\n    return Jb + Jc\n", "meta": {"hexsha": "cb07b11d4eb452e3ae4f170cca264f55f0be4091", "size": 2573, "ext": "py", "lang": "Python", "max_stars_repo_path": "opmatch/util/mdm.py", "max_stars_repo_name": "kirilklein/opmatch", "max_stars_repo_head_hexsha": "6cff35422d92f36a6ce93bff40003cb35b2768d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "opmatch/util/mdm.py", "max_issues_repo_name": "kirilklein/opmatch", "max_issues_repo_head_hexsha": "6cff35422d92f36a6ce93bff40003cb35b2768d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "opmatch/util/mdm.py", "max_forks_repo_name": "kirilklein/opmatch", "max_forks_repo_head_hexsha": "6cff35422d92f36a6ce93bff40003cb35b2768d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4029850746, "max_line_length": 93, "alphanum_fraction": 0.6338904003, "include": true, "reason": "import numpy,from numpy", "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347831070321, "lm_q2_score": 0.880797068590724, "lm_q1q2_score": 0.8582793004935119}}
{"text": "# Calculating the Value of Pi using Random Numbers (0,1)\n# Joao Pinheiro\n# Import packages\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# User input\nn = input('Insert the number of random points: ')\nprint('The number of random points is ' + n)\n\n# The function to calculate pi\ndef calc_pi(n):\n    NumPointsCircle = 0 \n    NumTotalPoints  = 0\n    for _ in range(n):\n        x = random.uniform(0,1)\n        y = random.uniform(0,1)\n        Distance = np.sqrt( x**2 + y**2 ) # Euclidian distance\n        if Distance <= 1:\n            NumPointsCircle += 1\n        NumTotalPoints += 1\n    # pi / 4 = Number of Points in Circule / Number of Total Points\n    pi = 4 * ( NumPointsCircle / NumTotalPoints )    \n\n    return pi    \n\nprint( 'The value of pi is: ' + str(calc_pi( int(n) )) )\n", "meta": {"hexsha": "a0665cb15f2f33d0b6124183734e9f25a5fd47de", "size": 798, "ext": "py", "lang": "Python", "max_stars_repo_path": "CC_002_PiValueFromRandomNumbers.py", "max_stars_repo_name": "joaomh/Coding-Challenge-Py", "max_stars_repo_head_hexsha": "615eab0309fbefddebfcf6216dcccbafcf986543", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CC_002_PiValueFromRandomNumbers.py", "max_issues_repo_name": "joaomh/Coding-Challenge-Py", "max_issues_repo_head_hexsha": "615eab0309fbefddebfcf6216dcccbafcf986543", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CC_002_PiValueFromRandomNumbers.py", "max_forks_repo_name": "joaomh/Coding-Challenge-Py", "max_forks_repo_head_hexsha": "615eab0309fbefddebfcf6216dcccbafcf986543", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5172413793, "max_line_length": 67, "alphanum_fraction": 0.6303258145, "include": true, "reason": "import numpy", "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9838471651778591, "lm_q2_score": 0.8723473829749844, "lm_q1q2_score": 0.8582564997902625}}
{"text": "from __future__ import annotations\nfrom typing import Union\nimport numpy as np\n\n\nclass PCA:\n    \"\"\"PCA - Principal Component Analysis\n    Parameters:\n    -----------\n    n_components: int = 2\n        Number of components to keep.\n    \"\"\"\n    def __init__(self, n_components: int = 2):\n        self.n_components = n_components\n        self.eigenvalues = None\n        self.eigenvectors = None\n        self.mean = None\n        self.std = None\n\n    def fit(self, X: Union[list, np.ndarray]) -> PCA:\n        # subtract off the mean to center the data\n        self.mean = X.mean(axis=0)\n        X = X - self.mean\n\n        covariance_matrix = np.cov(X, rowvar=False)\n\n        eigenvalues, eigenvectors = np.linalg.eig(covariance_matrix)\n\n        idx = eigenvalues.argsort()[::-1]\n        eigenvalues = eigenvalues[idx][:self.n_components]\n        eigenvectors = np.atleast_1d(eigenvectors[:, idx])[:, :self.n_components]\n\n        self.eigenvalues = eigenvalues\n        self.eigenvectors = eigenvectors\n\n        return self\n\n    def fit_transform(self, X: Union[list, np.ndarray]) -> np.ndarray:\n        self.fit(X)\n        return self.transform(X)\n\n    def transform(self, X: Union[list, np.ndarray]) -> np.ndarray:\n        X = X - self.mean\n\n        # Project the data onto principal components\n        X_transformed = np.dot(X, self.eigenvectors)\n\n        return X_transformed\n\n    @property\n    def explained_variance_ratio_(self):\n        return self.eigenvalues / np.sum(self.eigenvalues)\n\n\nif __name__ == '__main__':\n    # source: https://scikit-learn.org/stable/auto_examples/decomposition/plot_pca_iris.html\n    import matplotlib.pyplot as plt\n    from mpl_toolkits.mplot3d import Axes3D\n    from sklearn import datasets\n\n    np.random.seed(5)\n\n    centers = [[1, 1], [-1, -1], [1, -1]]\n    iris = datasets.load_iris()\n    X = iris.data\n    y = iris.target\n\n    fig = plt.figure(1, figsize=(4, 3))\n    plt.clf()\n    ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)\n\n    plt.cla()\n    pca = PCA(n_components=3)\n    pca.fit(X)\n    X = pca.transform(X)\n\n    for name, label in [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)]:\n        ax.text3D(X[y == label, 0].mean(),\n                X[y == label, 1].mean() + 1.5,\n                X[y == label, 2].mean(), name,\n                horizontalalignment='center',\n                bbox=dict(alpha=.5, edgecolor='w', facecolor='w'))\n    # Reorder the labels to have colors matching the cluster results\n    y = np.choose(y, [1, 2, 0]).astype(float)\n    ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=plt.cm.nipy_spectral,\n            edgecolor='k')\n\n    ax.w_xaxis.set_ticklabels([])\n    ax.w_yaxis.set_ticklabels([])\n    ax.w_zaxis.set_ticklabels([])\n\n    plt.show()", "meta": {"hexsha": "ab4aadfbf46be0a6f7ed1d7cf4242983508b8b97", "size": 2722, "ext": "py", "lang": "Python", "max_stars_repo_path": "Algorithms/principal_component_analysis/code/principal_component_analysis.py", "max_stars_repo_name": "TannerGilbert/Machine-Learning-Explained", "max_stars_repo_head_hexsha": "5309f44a38ce862f3f177e8d5de2e60eea44637b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-09-14T18:55:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T22:14:30.000Z", "max_issues_repo_path": "Algorithms/principal_component_analysis/code/principal_component_analysis.py", "max_issues_repo_name": "TannerGilbert/Machine-Learning-Explained", "max_issues_repo_head_hexsha": "5309f44a38ce862f3f177e8d5de2e60eea44637b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Algorithms/principal_component_analysis/code/principal_component_analysis.py", "max_forks_repo_name": "TannerGilbert/Machine-Learning-Explained", "max_forks_repo_head_hexsha": "5309f44a38ce862f3f177e8d5de2e60eea44637b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-02-06T15:34:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T23:16:07.000Z", "avg_line_length": 29.5869565217, "max_line_length": 92, "alphanum_fraction": 0.6039676708, "include": true, "reason": "import numpy", "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576265, "lm_q2_score": 0.8947894703109853, "lm_q1q2_score": 0.8582411548521833}}
{"text": "import numpy as np\n\nclass Hamming:\n    \"\"\"Hamming encoding of strings: {1,0}*\n\n    r = number of parity bits per block\n    m = number of data bits per block = 2^r - r - 1\n    n = number of total bits per block = 2^r - 1\n\n    reference: http://www-math.mit.edu/~djk/18.310/18.310F04/matrix_hamming_codes.html\n    \"\"\"\n\n    def __init__(self, r):\n        self.r = r\n        self.m = 2**r - r - 1\n        self.n = 2**r - 1\n\n        num_digits = len(np.binary_repr(self.n))\n\n        # non systematic h\n        h = np.matrix([[int(x) for x in np.binary_repr(i, num_digits)] for i in range(1, self.n+1)])\n        h = h.T\n\n        # convert last r cols to identity matrix through swapping columns (systematic)\n        for i in range(r):\n            x = 2**i - 1\n            y = self.n - 1 - i\n            h[:,[x,y]] = h[:,[y,x]]\n\n\n        g = np.concatenate((np.identity(self.m, dtype=int), h[:,:self.m].T), axis=1)\n\n        self.decoding_matrix = h\n        self.encoding_matrix = g\n\n    def encode(self, s):\n        \"\"\"Encodes a string of {1,0}* with length a multiple of m\"\"\"\n        if len(s) % self.m != 0:\n            print(\"Error: encode input string length must be multiple of m\")\n            return None\n        s_array = np.array(list(s), dtype=int)\n        s_array_split = np.split(s_array, indices_or_sections=len(s)/self.m)\n        s_array_mult = [np.remainder(np.dot(x, self.encoding_matrix), 2) for x in s_array_split]\n        out_s = np.concatenate(s_array_mult, axis=1)\n        flattened = np.ravel(out_s)\n        return \"\".join([str(x) for x in flattened.tolist()])\n\n    def decode(self, s):\n        \"\"\"Encodes a string of {1,0}* with length a multiple of n\"\"\"\n        if len(s) % self.n != 0:\n            print(\"Error: decode input string length must be multiple of n\")\n            return None\n\n        syndrome_mapping = {}\n        d = self.decoding_matrix.T\n        for i in range(len(d)):\n            curr_num_s = \"\".join([str(x) for x in d[i].tolist()[0]])\n            curr_num = int(curr_num_s, 2)\n            syndrome_mapping[curr_num] = i\n\n        s_array = np.array(list(s), dtype=int)\n        s_array_split = np.split(s_array, indices_or_sections=len(s)/self.n)\n        s_array_mult = [np.remainder(np.dot(self.decoding_matrix, x), 2) for x in s_array_split]\n\n        out = \"\"\n        for i in range(len(s_array_mult)):\n            curr_num_s = \"\".join([str(x) for x in s_array_mult[i].tolist()[0]])\n            curr_num = int(curr_num_s, 2)\n            curr_out = s_array_split[i].tolist()            \n            if curr_num != 0:\n                incorrect = syndrome_mapping[curr_num]\n                curr_out[incorrect] = 1-curr_out[incorrect]\n            out += \"\".join([str(x) for x in curr_out[:self.m]])\n        return out\n\n", "meta": {"hexsha": "d1fb495e82294702e7cb3c9fc61a6b8ef8034322", "size": 2751, "ext": "py", "lang": "Python", "max_stars_repo_path": "hamming.py", "max_stars_repo_name": "limartinyk/error-correction-py", "max_stars_repo_head_hexsha": "9bcc0d1a1bd181a84a23af470a1ff1f45f08e354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hamming.py", "max_issues_repo_name": "limartinyk/error-correction-py", "max_issues_repo_head_hexsha": "9bcc0d1a1bd181a84a23af470a1ff1f45f08e354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hamming.py", "max_forks_repo_name": "limartinyk/error-correction-py", "max_forks_repo_head_hexsha": "9bcc0d1a1bd181a84a23af470a1ff1f45f08e354", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1973684211, "max_line_length": 100, "alphanum_fraction": 0.5637949836, "include": true, "reason": "import numpy", "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542805873231, "lm_q2_score": 0.8947894738180211, "lm_q1q2_score": 0.8582411540370334}}
{"text": "import numpy\r\nnumpy.random.seed(42)\r\n\r\nprint(\"Nonlinear equations \\n\")\r\n\r\nEPS = 10.0 ** -5\r\n\r\ndef input():\r\n    #expr = numpy.poly1d([1.0, 1.0, 0.0])\r\n    #expr = numpy.poly1d(numpy.poly([1.0, 2.0, 3.0]))\r\n    #expr = numpy.poly1d(numpy.poly([1.0, 1.0, 1.0]))\r\n    #expr = numpy.poly1d(numpy.poly([0.0, 0.0, 1.0]))\r\n    \r\n    expr = numpy.poly1d([1.0, 38.4621, 364.594, 914.196])\r\n    \r\n    #expr = numpy.poly1d([1.0, -6.4951, -31.2543, 23.1782])\r\n    \r\n    return (expr)\r\n\r\n(f) = input()\r\nprint(f)\r\n\r\n\r\ndef SturmSeq(f):\r\n    arr = []\r\n    arr.append(f)\r\n    arr.append(numpy.polyder(f))\r\n\r\n    while True:\r\n        fn = -numpy.polydiv(arr[-2], arr[-1])[1]\r\n        if (fn.order > 0 or abs(fn[0]) > 0.0):\r\n            arr.append(fn)\r\n        else:\r\n            break\r\n    \r\n    return arr\r\n\r\ndef N(stseq, x):\r\n    if (abs(f(x)) < EPS):\r\n        raise ValueError(\"Number in N() is a root\")\r\n    ans = 0\r\n    for i in range(1, len(stseq)):\r\n        if (stseq[i](x) == 0.0):\r\n            raise ValueError(\"SturmSeq[i] is zero\")\r\n        if(stseq[i-1](x) * stseq[i](x) < 0):\r\n            ans += 1\r\n    return ans\r\n\r\ndef GetBounds(f, a, b):\r\n    if ((abs(f(a)) < EPS) or (abs(f(b)) < EPS)):\r\n        raise ValueError(\"Bounds contain root\")\r\n    if (N(Sturm, a) - N(Sturm, b) == 0):\r\n        return []\r\n    if (N(Sturm, a) - N(Sturm, b) > 1):\r\n        while True:\r\n            M = a + (b - a) / (1.5 + numpy.random.random())\r\n            if (abs(f(M)) > EPS):\r\n                break\r\n        return GetBounds(f, a, M) + GetBounds(f, M, b)\r\n    if (b - a < EPS):\r\n        print(\"Warning: Bounds are too small\")\r\n    return [(a, b)]\r\n\r\nSturm = SturmSeq(f)\r\n\r\nprint(\"Amount of roots on [-10, 10]:\")\r\nprint(N(Sturm, -10) - N(Sturm, 10))\r\n    \r\nbounds = GetBounds(f, -10, 10)\r\nprint(\"Roots are in bounds:\")\r\nprint(bounds)\r\n\r\n\r\niters = 0\r\n\r\ndef BinarySearch(L, R):\r\n    global iters\r\n    iters += 1\r\n    M = (L + R) / 2\r\n    if (R - L < EPS):\r\n        return M\r\n    #if (abs(f(M)) < EPS):\r\n    #    return M\r\n    if (f(L) * f(M) <= 0):\r\n        return BinarySearch(L, M)\r\n    elif (f(R) * f(M) <= 0):\r\n        return BinarySearch(M, R)\r\n    else:\r\n        raise RuntimeError(\"Something went wrong in BinarySearch\")\r\n\r\ndef SecantFirst(L, R):\r\n    global iters\r\n    fder2 = numpy.polyder(f, 2)\r\n    if (f(R) * fder2(R) > 0):\r\n        (oldx, x) = (R, L)\r\n    elif (f(L) * fder2(L) > 0):\r\n        (oldx, x) = (L, R)\r\n    else:\r\n        raise ValueError(\"Bad bounds in first Secant method\")\r\n    t = oldx\r\n    while (abs(x - oldx) > EPS):\r\n    #while (abs(f(x)) > EPS):\r\n        iters += 1\r\n        oldx = x\r\n        x = x - f(x) * (t - x) / (f(t) - f(x))\r\n        if (not (numpy.isfinite(x))):\r\n            raise RuntimeError(\"Something went wrong, and x is not a number\")\r\n    if ((x < L) or (R < x)):\r\n        raise RuntimeError(\"Something went wrong, and x is not in [L, R]\")\r\n    return x\r\n    \r\ndef SecantSecond(L, R):\r\n    global iters\r\n    (x, oldx) = (L, R)\r\n    while (abs(x - oldx) > EPS):\r\n    #while (abs(f(x)) > EPS):\r\n        iters += 1\r\n        oldx = x\r\n        x = L - f(L) * (R - L) / (f(R) - f(L))\r\n        if (not (numpy.isfinite(x))):\r\n            raise RuntimeError(\"Something went wrong, and x is not a number\")\r\n        if (f(L) * f(x) <= 0):\r\n            R = x\r\n        elif (f(R) * f(x) <= 0):\r\n            L = x\r\n        else:\r\n            raise RuntimeError(\"Something went wrong in second Secant method\")\r\n    if ((x < L) or (R < x)):\r\n        raise RuntimeError(\"Something went wrong, and x is not in [L, R]\")\r\n    return x\r\n    \r\ndef Newton(L, R):\r\n    global iters\r\n    fder = numpy.polyder(f)\r\n    fder2 = numpy.polyder(f, 2)\r\n    if (f(L) * fder2(L) > 0):\r\n        (oldx, x) = (R, L)\r\n    elif (f(R) * fder2(R) > 0):\r\n        (oldx, x) = (L, R)\r\n    else:\r\n        raise ValueError(\"Bad bounds in Newton method\")\r\n    while (abs(x - oldx) > EPS):\r\n    #while (abs(f(x)) > EPS):\r\n        iters += 1\r\n        oldx = x\r\n        x = x - f(x) / fder(x)\r\n        if (not (numpy.isfinite(x))):\r\n            raise RuntimeError(\"Something went wrong, and x is not a number\")\r\n    if ((x < L) or (R < x)):\r\n        raise RuntimeError(\"Something went wrong, and x is not in [L, R]\")\r\n    return x\r\n\r\n\r\nnumpy.set_printoptions(suppress = True, precision = 4, floatmode = \"fixed\")\r\n\r\ndef test(method):\r\n    global iters\r\n    for i in range(len(bounds)):\r\n        iters = 0\r\n        try:\r\n            str = method(*bounds[i])\r\n            if  (not str is None):\r\n                str = \"{:.4f}\".format(str)\r\n            print(\"{} via {} method (with {} iterations)\".format(str, method.__name__, iters))\r\n        except Exception as ex:\r\n            print(\"ERROR: {} - in {} method (with {} iterations)\".format(ex, method.__name__, iters))\r\n\r\nprint()\r\ntest(BinarySearch)\r\nprint()\r\ntest(SecantFirst)\r\nprint()\r\ntest(SecantSecond)\r\nprint()\r\ntest(Newton)\r\nprint()\r\n\r\nprint(\"Check:\")\r\nprint(f.r)\r\n", "meta": {"hexsha": "9ddf8177c22872c8204701477cb89304c67c0f80", "size": 4893, "ext": "py", "lang": "Python", "max_stars_repo_path": "4 term/MNA/Lab 3/Lab3.py", "max_stars_repo_name": "mrojaczy/Labs", "max_stars_repo_head_hexsha": "21cd2ad3ddf8fa3b64cf253d147a4a04ad0667ab", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-15T17:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-15T17:11:23.000Z", "max_issues_repo_path": "4 term/MNA/Lab 3/Lab3.py", "max_issues_repo_name": "Asphobel/Labs", "max_issues_repo_head_hexsha": "ee827143b32b691dd7736ba4888a4a9625b4694a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4 term/MNA/Lab 3/Lab3.py", "max_forks_repo_name": "Asphobel/Labs", "max_forks_repo_head_hexsha": "ee827143b32b691dd7736ba4888a4a9625b4694a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1833333333, "max_line_length": 102, "alphanum_fraction": 0.4884528919, "include": true, "reason": "import numpy", "num_tokens": 1551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542887603537, "lm_q2_score": 0.8947894661025424, "lm_q1q2_score": 0.8582411539498407}}
{"text": "# -*- coding: utf-8 -*-\nimport numpy as np\nimport math,cmath\n\ndef computecorrelation(x,y):\n    x_bar=np.mean(x)\n    y_bar=np.mean(y)\n    SSR=0\n    Varx=0\n    Vary=0\n    for i in range(0,len(x)):\n        SSR+=(x[i]-x_bar)*(y[i]-y_bar)\n        Varx+=(x[i]-x_bar)**2\n        Vary+=(y[i]-y_bar)**2\n    SST=cmath.sqrt(Varx*Vary)\n    return SSR/SST\n\ndef belog(x):\n    logx = []\n    for i in x:\n        if(i > 0):\n            logx.append(math.log(i,10))\n        elif(i < 0):\n            logx.append(0)\n    return logx\n\ndef polyfot(x,y,degree):\n    result={}\n    coef=np.polyfit(x,y,degree)#算出各个回归系数\n    result[\"polynomial\"]=coef.tolist()\n    p=np.poly1d(coef)#拟合一条线\n    y_hat=p(x)\n    y_bar=np.mean(y)\n    SSR=np.sum((y_hat-y_bar)**2)\n    SST=np.sum((y-y_bar)**2)\n    result[\"determination\"]=SSR/SST\n    return result[\"determination\"]\ndef rmse(x,y):\n    z = []\n    for i in range(len(x)):\n        z.append((x[i] - y[i])**2)\n    z_bar = np.mean(z)\n    return np.sqrt(z_bar)\ndef mae(x,y):    \n    z = []\n    for i in range(len(x)):\n        z.append(abs(x[i] - y[i]))\n    return np.mean(z)\ndef get_stastics(y1,y2):\n    mae1 = mae(y1,y2)\n    rmse1 = rmse(y1,y2)\n    cor = computecorrelation(y1,y2)\n    print('The MAE is: ',mae1)\n    print('The RMSE is: ',rmse1)\n    print('The correlation parameter is: ',cor)\n    return\ndef vdot(v1,v2):\n    v3 = 0\n    if(len(v1) == len(v2)):\n        for i in range(len(v1)):\n            v3 += v1[i] * v2[i]\n    return v3\n\ndef vcross(v1,v2):\n    v3 = [0,0,0]\n    if(len(v1) == len(v2)):\n        v3[0] = v1[1] * v2[2] - v1[2] * v2[1]\n        v3[1] = v1[2] * v2[0] - v1[0] * v2[2]\n        v3[2] = v1[0] * v2[1] - v1[1] * v2[0]\n        return v3\n    return v3\n\ndef zscore(mean,std,av):\n    import numpy as np\n    import math\n    stdav = []\n    for i in range(len(mean)):\n        if std[i] < 1e-15:\n            temp = 0\n        else:\n            temp = (av[i] - mean[i])/(math.sqrt(std[i]))\n        stdav.append(temp)\n    return np.array(stdav)\n\ndef list_split(lists,clist):\n    l1 = []\n    l2 = []\n    nl = [ i for i in range(0,len(lists))]\n    for i in clist:\n        l1.append(lists[i])\n    for i in nl:\n        if i not in clist:\n            l2.append(lists[i])\n    l1 = np.array(l1)\n    l2 = np.array(l2)\n    return l1,l2\n    \ndef train_test_split(x_data,y_data,train_size=0.8,test_size=0.2, random_state=0):\n    import random\n    random.seed(random_state)\n    nx = len(x_data)\n    ny = len(y_data)\n    x_train = []\n    x_test = []\n    y_train = []\n    y_test = []\n    if nx == ny:\n        if train_size <= 1 and test_size <= 1:\n            n1 = int(nx * train_size)\n            n2 = int(nx * test_size)\n            nlist = [i for i in range(0,nx)]\n            clist = random.sample(nlist,n1)\n            x_train, x_test = list_split(x_data,clist)\n            y_train, y_test = list_split(y_data,clist)\n            return x_train,x_test,y_train,y_test\n        else:\n            nlist = [i for i in range(0,nx)]\n            clist = random.sample(nlist,train_size)\n            x_train, x_test = list_split(x_data,clist)\n            y_train, y_test = list_split(y_data,clist)\n            return x_train,x_test,y_train,y_test\n    else:\n        return 0\n\n\nif __name__ == '__main__':\n    v1 = [1,2,3]\n    v2 = [4,5,6]\n    v3 = vcross(v1,v2)\n    print(vdot(v1,v2))\n    print(v3)\n    \n    x_data = [[1,2],[3,4],[5,6],[7,8],[9,10]]\n    y_data = [1,2,3,4,5]\n    x1,x2,y1,y2 = train_test_split(x_data,y_data,train_size=0.8,test_size=0.2,random_state=23)\n    print(x1)\n    print(y1)\n    ", "meta": {"hexsha": "c1c19e8ff22deb8cd5570862be4bb770532648a2", "size": 3499, "ext": "py", "lang": "Python", "max_stars_repo_path": "MatAI/Auxilfunction.py", "max_stars_repo_name": "xinming365/ANNCM", "max_stars_repo_head_hexsha": "a65f1401acef26e290f8f2365ae06c86181ef04b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-20T10:22:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T10:22:21.000Z", "max_issues_repo_path": "MatAI/Auxilfunction.py", "max_issues_repo_name": "xinming365/ANNCM", "max_issues_repo_head_hexsha": "a65f1401acef26e290f8f2365ae06c86181ef04b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MatAI/Auxilfunction.py", "max_forks_repo_name": "xinming365/ANNCM", "max_forks_repo_head_hexsha": "a65f1401acef26e290f8f2365ae06c86181ef04b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-19T03:47:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-19T03:47:21.000Z", "avg_line_length": 25.3550724638, "max_line_length": 94, "alphanum_fraction": 0.5298656759, "include": true, "reason": "import numpy", "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542829224748, "lm_q2_score": 0.8947894689081711, "lm_q1q2_score": 0.8582411514171989}}
{"text": "import numpy as np\n# 矩阵乘法的几何意义 https://zhuanlan.zhihu.com/p/64606322\n# 矩阵乘法  矩阵积 点积  matrix product\na = np.array([[4, 5], [6, 7]])\nb = np.arange(4).reshape((2, 2))\nprint(a)\n# [[4 5]\n#  [6 7]]\nprint(b)\n# [[0 1]\n#  [2 3]]\n# 矩阵乘法\nc_dot = np.dot(a,b)\nprint(c_dot)\n# [[10 19]\n#  [14 27]]\nc_dot_2 = a.dot(b)\n# [[10 19]\n#  [14 27]]\nprint(a @ b)\n\nprint(a * b)\n\"\"\"\na1,1 * b1,1 + a1,2 * b2,1 + a1,n * bn,1  ,  a1,1 * b1,2 + a1,2 * b2,2 + a1,n * bn,2\na2,1 * b1,1 + a2,2 * b2,1 + a2,n * bn,1  ,  a2,1 * b1,2 + a2,2 * b2,2 + a2,n * bn,2\n= A 的行数 ，B的列数\n= [\n[4*0+5*2,4*1+5*3],\n[6*0+7*2,6*1+7*3]\n]\n\"\"\"\n\na = np.array([[1, 2], [3, 4]])\nb = np.array([[5, 6], [7, 8]])\nprint(np.inner(a, b)) # 内积 Inner product\nprint(np.dot(a, b)) # 点积 Dot product\nprint(np.cross(a, b)) # 叉积  cross product\nprint(np.outer(a, b)) # 外积 outer product\nprint(a*b)\nprint(a@b) # 等于 np.dot(a, b)\n\na = np.array([3, 1])\nb = np.array([2, -1])\nprint(np.inner(a, b)) # 内积 Inner product\nprint(np.dot(a, b))    # 点积 Dot product\nprint(np.cross(a, b)) # 叉积  cross product\nprint(np.outer(a, b)) # 外积 outer product\nprint(a*b)\nprint(a@b)\n# 向量的点积=内积\n\nprint(np.linalg.det([[3,2],[1,-1]])) # 行列式 = 叉积\n\n\n\n", "meta": {"hexsha": "bb33aa5aeee13f03aa32d1d0b24e029e33ae3b9e", "size": 1142, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy/tutorial/01_dot.py", "max_stars_repo_name": "kingreatwill/penter", "max_stars_repo_head_hexsha": "2d027fd2ae639ac45149659a410042fe76b9dab0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-01-04T07:37:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T05:19:58.000Z", "max_issues_repo_path": "numpy/tutorial/01_dot.py", "max_issues_repo_name": "kingreatwill/penter", "max_issues_repo_head_hexsha": "2d027fd2ae639ac45149659a410042fe76b9dab0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-06-05T22:42:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-24T07:18:54.000Z", "max_forks_repo_path": "numpy/tutorial/01_dot.py", "max_forks_repo_name": "kingreatwill/penter", "max_forks_repo_head_hexsha": "2d027fd2ae639ac45149659a410042fe76b9dab0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-10-19T04:53:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T05:20:01.000Z", "avg_line_length": 20.3928571429, "max_line_length": 83, "alphanum_fraction": 0.5429071804, "include": true, "reason": "import numpy", "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542805873231, "lm_q2_score": 0.8947894682067639, "lm_q1q2_score": 0.858241148654972}}
{"text": "# Chapter 4: Granger Causality Test\n\nIn the first three chapters, we discussed the classical methods for both univariate and multivariate time series forecasting. We now introduce the notion of causality and its implications on time series analysis in general. We also describe a test for the linear VAR model discussed in the previous chapter.\n\nPrepared by: Carlo Vincienzo G. Dajac\n\n## Notations\n\nIf $A_t$ is a stationary stochastic process, let $\\overline A_t$ represent the set of *past* values ${A_{t-j}, \\; j=1,2,\\ldots,\\infty}$ and $\\overline{\\overline A}_t$ represent the set of *past and present* values ${A_{t-j}, \\; j=0,1,\\ldots,\\infty}$. Further, let $\\overline A(k)$ represent the set ${A_{t-j}, \\; j=k,k+1,\\ldots,\\infty}$.\n\nDenote the optimum, unbiased, least-squares predictor of $A_t$ using the set of values $B_t$ by $P_t (A|B)$. Thus, for instance, $P_t (X|\\overline X)$ will be the optimum predictor of $X_t$ using only past $X_t$. The predictive error series will be denoted by $\\varepsilon_t(A|B) = A_t - P_t(A|B)$. Let $\\sigma^2 (A|B)$ be the variance of $\\varepsilon_t(A|B)$.\n\nLet $U_t$ be all the information in the universe accumulated since time $t-1$ and let $U_t - Y_t$ denote all this information *apart* from the specified series $Y_t$, which is another stationary time series that is different from $X_t$.\n\n## Definitions\n\n### Causality\n\nIf $\\sigma^2 (X|U) < \\sigma^2 (X| \\overline{U-Y})$, we say that $Y$ is causing $X$, denoted by $Y_t \\implies X_t$. We say that $Y_t$ is causing $X_t$ if we are **able to predict** $X_t$ using all available information than if the information apart from $Y_t$ had been used.\n\n### Feedback\nIf $\\sigma^2 (X|\\overline U) < \\sigma^2 (X| \\overline{U-Y})$ and $\\sigma^2 (Y|\\overline U) < \\sigma^2 (Y| \\overline{U-X})$, we say that feedback is occurring, which is denoted by $Y_t \\iff X_t$, i.e., feedback is said to occur when $X_t$ is causing $Y_t$ and also $Y_t$ is causing $X_t$.\n\n### Instantaneous Causality\nIf $\\sigma^2 (X|\\overline U, \\overline{\\overline Y}) < \\sigma^2 (X| \\overline U)$, we say that instantaneous causality $Y_t \\implies X_t$ is occurring. In other words, the current value of $X_t$ is better \"predicted\" if the present value of $Y_t$ is included in the \"prediction\" than if it is not.\n\n### Causality Lag\nIf $Y_t \\implies X_t$, we define the (integer) causality lag $m$ to be the least value of $k$ such that $\\sigma^2 (X|U-Y(k)) < \\sigma^2 (X|U-Y(k+1))$. Thus, knowing the values $Y_{t-j}, \\; j=0,1,\\ldots,m-1$ will be of no help in improving the prediction of $X_t$\n\n## Assumptions\n\n* $X_t$ and $Y_t$ are stationary.\n* $P_t (A|B)$ is already optimized.\n\n## Testing for Granger Causality\n\nWe will be first building VAR models for our examples in this section. In addition to the steps outlined in the previous chapter, we will just call built-in Granger causality test function and configure it accordingly.\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pandas.plotting import lag_plot\nfrom statsmodels.tsa.vector_ar.var_model import VAR\nfrom statsmodels.tsa.stattools import adfuller, kpss, grangercausalitytests\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n### Example 1: Ipo Dam Dataset\n\nWe will use the Ipo dataset in this example. It contains daily measurements of the following variables: rainfall (in millimeters), Oceanic Niño Index (ONI), NIA release flow (in cubic meters per second), and dam water level (in meters), respectively.\n\nipo_df = pd.read_csv('../data/Ipo_dataset.csv', index_col='Time');\nipo_df = ipo_df.dropna()\nipo_df.head()\n\nfig,ax = plt.subplots(4, figsize=(15,8), sharex=True)\nplot_cols = ['Rain', 'ONI', 'NIA', 'Dam']\nipo_df[plot_cols].plot(subplots=True, legend=False, ax=ax)\nfor a in range(len(ax)): \n    ax[a].set_ylabel(plot_cols[a])\nax[-1].set_xlabel('')\nplt.tight_layout()\nplt.show()\n\n#### Causality between Rainfall and Ipo Dam Water Level\n\nFor this example, we will focus on the Rain and Dam time series.\n\ndata_df = ipo_df.drop(['ONI', 'NIA'], axis=1)\ndata_df.head()\n\nWe look at the lag plots to quickly check for stationarity.\n\ndef lag_plots(data_df):\n    f, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))\n\n    lag_plot(data_df[data_df.columns[0]], ax=ax1)\n    ax1.set_title(data_df.columns[0]);\n\n    lag_plot(data_df[data_df.columns[1]], ax=ax2)\n    ax2.set_title(data_df.columns[1]);\n\n    ax1.set_ylabel('$y_{t+1}$');\n    ax1.set_xlabel('$y_t$');\n    ax2.set_ylabel('$y_{t+1}$');\n    ax2.set_xlabel('$y_t$');\n\n    plt.tight_layout()\n\nlag_plots(data_df)\n\n**Result:** Dam does not look stationary. Rainfall lag plot is inconclusive.\n\nWe use KPSS and ADF tests discussed in the previous chapter to conclusively check for stationarity.\n\ndef kpss_test(data_df):\n    test_stat, p_val = [], []\n    cv_1pct, cv_2p5pct, cv_5pct, cv_10pct = [], [], [], []\n    for c in data_df.columns: \n        kpss_res = kpss(data_df[c].dropna(), regression='ct')\n        test_stat.append(kpss_res[0])\n        p_val.append(kpss_res[1])\n        cv_1pct.append(kpss_res[3]['1%'])\n        cv_2p5pct.append(kpss_res[3]['2.5%'])\n        cv_5pct.append(kpss_res[3]['5%'])\n        cv_10pct.append(kpss_res[3]['10%'])\n    kpss_res_df = pd.DataFrame({'Test statistic': test_stat, \n                               'p-value': p_val, \n                               'Critical value - 1%': cv_1pct,\n                               'Critical value - 2.5%': cv_2p5pct,\n                               'Critical value - 5%': cv_5pct,\n                               'Critical value - 10%': cv_10pct}, \n                             index=data_df.columns).T\n    kpss_res_df = kpss_res_df.round(4)\n    return kpss_res_df\n\nkpss_test(data_df)\n\n**Result:** Rain is stationary, while Dam is not.\n\ndef adf_test(data_df):\n    test_stat, p_val = [], []\n    cv_1pct, cv_5pct, cv_10pct = [], [], []\n    for c in data_df.columns: \n        adf_res = adfuller(data_df[c].dropna())\n        test_stat.append(adf_res[0])\n        p_val.append(adf_res[1])\n        cv_1pct.append(adf_res[4]['1%'])\n        cv_5pct.append(adf_res[4]['5%'])\n        cv_10pct.append(adf_res[4]['10%'])\n    adf_res_df = pd.DataFrame({'Test statistic': test_stat, \n                               'p-value': p_val, \n                               'Critical value - 1%': cv_1pct,\n                               'Critical value - 5%': cv_5pct,\n                               'Critical value - 10%': cv_10pct}, \n                             index=data_df.columns).T\n    adf_res_df = adf_res_df.round(4)\n    return adf_res_df\n\nadf_test(data_df)\n\n**Result:** Both data are stationary.\n\nSince both the lag plot and KPSS test indicate that Dam is not stationary, we apply differencing first before building our VAR model.\n\ndata_df['Dam'] = data_df['Dam'] - data_df['Dam'].shift(1)\ndata_df = data_df.dropna()\n\nWe again look at the lag plots and apply the KPSS and ADF tests.\n\nlag_plots(data_df)\n\nkpss_test(data_df)\n\nadf_test(data_df)\n\n**Result:** All three conclusively agree that both data are now stationary.\n\nWe next split the data into train and test sets for the VAR model.\n\ndef splitter(data_df):\n    end = round(len(data_df)*.8)\n    train_df = data_df[:end]\n    test_df = data_df[end:]\n    return train_df, test_df\n\ntrain_df, test_df = splitter(data_df)\n\nWe then select the VAR order $p$ by computing the different multivariate information criteria (AIC, BIC, HQIC), and FPE.\n\ndef select_p(train_df):\n    aic, bic, fpe, hqic = [], [], [], []\n    model = VAR(train_df) \n    p = np.arange(1,60)\n    for i in p:\n        result = model.fit(i)\n        aic.append(result.aic)\n        bic.append(result.bic)\n        fpe.append(result.fpe)\n        hqic.append(result.hqic)\n    lags_metrics_df = pd.DataFrame({'AIC': aic, \n                                    'BIC': bic, \n                                    'HQIC': hqic,\n                                    'FPE': fpe}, \n                                   index=p)    \n    fig, ax = plt.subplots(1, 4, figsize=(15, 3), sharex=True)\n    lags_metrics_df.plot(subplots=True, ax=ax, marker='o')\n    plt.tight_layout()\n    print(lags_metrics_df.idxmin(axis=0))\n\nselect_p(train_df)\n\n**Result:** We see that BIC has the lowest value at $p=8$ while HQIC  at $p=11$. Although both AIC and FPE have the lowest value at $p=21$, their plots also show an elbow. We can thus select the number of lags to be 8 (also for computational efficiency). \n\nWe now fit the VAR model with the chosen order.\n\np = 8\nmodel = VAR(train_df)\nvar_model = model.fit(p)\n\nWe can finally test the variables for Granger Causality\n\ndef granger_causation_matrix(data, variables, p, test = 'ssr_chi2test', verbose=False):    \n    \"\"\"Check Granger Causality of all possible combinations of the time series.\n    The rows are the response variables, columns are predictors. The values in the table \n    are the P-Values. P-Values lesser than the significance level (0.05), implies \n    the Null Hypothesis that the coefficients of the corresponding past values is \n    zero, that is, the X does not cause Y can be rejected.\n\n    data      : pandas dataframe containing the time series variables\n    variables : list containing names of the time series variables.\n    \"\"\"\n    df = pd.DataFrame(np.zeros((len(variables), len(variables))), columns=variables, index=variables)\n    for c in df.columns:\n        for r in df.index:\n            test_result = grangercausalitytests(data[[r, c]], p, verbose=False)\n            p_values = [round(test_result[i+1][0][test][1],4) for i in range(p)]\n            if verbose: print(f'Y = {r}, X = {c}, P Values = {p_values}')\n            min_p_value = np.min(p_values)\n            df.loc[r, c] = min_p_value\n    df.columns = [var + '_x' for var in variables]\n    df.index = [var + '_y' for var in variables]\n    return df\n\ngranger_causation_matrix(train_df, train_df.columns, p)  \n\n**Recall:** If a given p-value is < significance level (0.05), then, the corresponding X series (column) causes the Y (row).\n\n**Results:** For this particular example, we can say that rainfall Granger causes changes in the dam water level. This means that rainfall data improves changes in dam water level prediction performance.\n\nOn the other hand, changes in dam water level does not Granger cause rainfall. This means that changes in dam water level data does not improve rainfall prediction performance.\n\n#### Causality between NIA Release Flow and Ipo Dam Water Level\n\nIn this next example, we now focus on the NIA and Dam time series.\n\ndata_df = ipo_df.drop(['ONI', 'Rain'], axis=1)\ndata_df.head()\n\nWe first check for stationarity by looking at the lag plots and applying the KPSS and ADF tests.\n\nlag_plots(data_df)\n\nkpss_test(data_df)\n\nadf_test(data_df)\n\n**Result:** All three conclusively show that both data are not stationary.\n\nWe apply differencing and recheck for stationarity.\n\ndata_df['NIA'] = data_df['NIA'] - data_df['NIA'].shift(1)\ndata_df['Dam'] = data_df['Dam'] - data_df['Dam'].shift(1)\ndata_df = data_df.dropna()\n\nlag_plots(data_df)\n\nkpss_test(data_df)\n\nadf_test(data_df)\n\n**Result:** All three conclusively agree that both data are now stationary.\n\nWe next split the data and select the lag order $p$.\n\ntrain_df, test_df = splitter(data_df)\n\nselect_p(train_df)\n\nWe select $p=8$ with the same reasons as before. We finally fit our VAR model and test for Granger Causality.\n\np = 8\nmodel = VAR(train_df)\nvar_model = model.fit(p)\n\ngranger_causation_matrix(train_df, train_df.columns, p)  \n\n**Recall:** If a given p-value is < significance level (0.05), then, the corresponding X series (column) causes the Y (row).\n\n**Result:** For this particular example, we can say that changes in NIA release flow Granger causes changes in the dam water level. Conversely, changes in dam water level also Granger causes changes in the NIA release flow. This is an example of the feedback mentioned in an earlier section above. This means that NIA release flow data improves changes in dam water level prediction performance, and dam water level data also improves changes in NIA release flow prediction performance.\n\n### Example 2: Causality for La Mesa Dam\n\nWe now do the same steps for the La Mesa dataset.\n\nlamesa_df = pd.read_csv('../data/La Mesa_dataset.csv', index_col='Time');\nlamesa_df = lamesa_df.dropna()\nlamesa_df.head()\n\nfig,ax = plt.subplots(4, figsize=(15,8), sharex=True)\nplot_cols = ['Rain', 'ONI', 'NIA', 'Dam']\nlamesa_df[plot_cols].plot(subplots=True, legend=False, ax=ax)\nfor a in range(len(ax)): \n    ax[a].set_ylabel(plot_cols[a])\nax[-1].set_xlabel('')\nplt.tight_layout()\nplt.show()\n\n#### Causality between Rainfall and La Mesa Dam Water Level\n\nIn this next example, we first consider the Rain and Dam time series.\n\ndata_df = lamesa_df.drop(['ONI', 'NIA'], axis=1)\ndata_df.head()\n\nWe first check for stationarity by looking at the lag plots and applying the KPSS and ADF tests.\n\nlag_plots(data_df)\n\nkpss_test(data_df)\n\nadf_test(data_df)\n\n**Result:** All three conclusively show that again Rain is stationary, while Dam is not.\n\nWe apply differencing and recheck for stationarity.\n\ndata_df['Dam'] = data_df['Dam'] - data_df['Dam'].shift(1)\ndata_df = data_df.dropna()\n\nlag_plots(data_df)\n\nkpss_test(data_df)\n\nadf_test(data_df)\n\n**Result:** All three conclusively agree that both data are now stationary.\n\nWe next split the data and select the lag order $p$.\n\ntrain_df, test_df = splitter(data_df)\n\nselect_p(train_df)\n\nWe select $p=7$. We finally fit our VAR model and test for Granger Causality.\n\np = 7\nmodel = VAR(train_df)\nvar_model = model.fit(p)\n\ngranger_causation_matrix(train_df, train_df.columns, p)  \n\n**Recall:** If a given p-value is < significance level (0.05), then, the corresponding X series (column) causes the Y (row).\n\n**Result:** For this particular example, we can say that rainfall Granger causes changes in the dam water level. Conversely, changes in dam water level also Granger causes rainfall. This is another example of feedback. This means that rainfall data improves changes in dam water level prediction performance, and dam water level data also improves rainfall prediction performance.\n\n#### Causality between NIA Release Flow and La Mesa Dam Water Level\n\nIn this next example, we now focus on the NIA and Dam time series.\n\ndata_df = lamesa_df.drop(['ONI', 'Rain'], axis=1)\ndata_df.head()\n\nWe first check for stationarity by looking at the lag plots and applying the KPSS and ADF tests.\n\nlag_plots(data_df)\n\nkpss_test(data_df)\n\nadf_test(data_df)\n\n**Result:** All three conclusively show that both data are not stationary.\n\nWe apply differencing and recheck for stationarity.\n\ndata_df['NIA'] = data_df['NIA'] - data_df['NIA'].shift(1)\ndata_df['Dam'] = data_df['Dam'] - data_df['Dam'].shift(1)\ndata_df = data_df.dropna()\n\nlag_plots(data_df)\n\nkpss_test(data_df)\n\nadf_test(data_df)\n\n**Result:** All three conclusively agree that both data are now stationary.\n\nWe next split the data and select the lag order $p$.\n\ntrain_df, test_df = splitter(data_df)\n\nselect_p(train_df)\n\nWe select $p=14$. We finally fit our VAR model and test for Granger Causality.\n\np = 14\nmodel = VAR(train_df)\nvar_model = model.fit(p)\n\ngranger_causation_matrix(train_df, train_df.columns, p)  \n\n**Recall:** If a given p-value is < significance level (0.05), then, the corresponding X series (column) causes the Y (row).\n\n**Result:** We see that, unlike for Ipo Dam, changes in NIA release flow and changes in the dam water level do NOT Granger cause one another for La Mesa Dam. This means that NIA release flow data does NOT improve changes in dam water level prediction performance, and dam water level data also does NOT improve changes in NIA release flow prediction performance.\n\n### Exercises\n\nAs exercises, the reader can test for Granger Causality between other pairs of variables from both the Ipo and La Mesa datasets, as well as from the Angat dataset.\n\n### Example 3: Jena Climate Data\n\nWe look back at the Jena climate dataset and explore which variables are Granger causal to another.\n\ntrain_df = pd.read_csv('../data/train_series_datetime.csv',index_col=0).set_index('Date Time')\nval_df = pd.read_csv('../data/val_series_datetime.csv',index_col=0).set_index('Date Time')\ntest_df = pd.read_csv('../data/test_series_datetime.csv',index_col=0).set_index('Date Time')\ntrain_df.index = pd.to_datetime(train_df.index)\nval_df.index = pd.to_datetime(val_df.index)\ntest_df.index = pd.to_datetime(test_df.index)\n\ntrain_val_df = pd.concat([train_df, val_df])\njena_df = pd.concat([train_df, val_df, test_df])\njena_df.head()\n\n#### Causality between Pressure and Temperature\n\nIn this next example, we first consider the p and T time series.\n\ndata_df = jena_df.iloc[:,:2]\ndata_df.head()\n\nWe first check for stationarity by looking at the lag plots and applying the KPSS and ADF tests.\n\nlag_plots(data_df)\n\nkpss_test(data_df)\n\nadf_test(data_df)\n\n**Result:** All three conclusively show that both data are not stationary.\n\nWe apply differencing and recheck for stationarity.\n\ndata_df['p (mbar)'] = data_df['p (mbar)'] - data_df['p (mbar)'].shift(1)\ndata_df['T (degC)'] = data_df['T (degC)'] - data_df['T (degC)'].shift(1)\ndata_df = data_df.dropna()\n\nlag_plots(data_df)\n\nkpss_test(data_df)\n\nadf_test(data_df)\n\n**Result:** All three conclusively agree that both data are now stationary.\n\nWe next split the data and select the lag order $p$.\n\ntrain_df, test_df = splitter(data_df)\n\nselect_p(train_df)\n\nWe select $p=30$. We finally fit our VAR model and test for Granger Causality.\n\np = 30\nmodel = VAR(train_df)\nvar_model = model.fit(p)\n\ngranger_causation_matrix(train_df, train_df.columns, p)  \n\n**Recall:** If a given p-value is < significance level (0.05), then, the corresponding X series (column) causes the Y (row).\n\n**Result:** For this particular example, we can say that changes in pressure Granger causes changes in temperature. Conversely, changes in temperature also Granger causes pressure. This is another example of feedback. This means that pressure data improves changes in temperature prediction performance, and temperature data also improves pressure prediction performance.\n\n## Summary\n\nWe have introduced the notion of causality in this chapter, and discussed its implications on time series analysis. We also applied the Granger Causality Test for linear VAR models for several datasets, seeing different examples of causality between the variables explored.\n\nCausality will be revisited in a later chapter, in particular addressing the limitations of the method discussed in this chapter and discussing causality for nonlinear models.\n\n## References\n\nThe contents of this notebook are compiled from the following references:\n\n* [Granger, C. (1969). Investigating Causal Relations by Econometric Models and Cross-spectral Methods. Econometrica, 37(3), 424-438.](https://www.jstor.org/stable/1912791)\n* [Toda, Hiro Y. & Yamamoto, Taku (1995). Statistical inference in vector autoregressions with possibly integrated processes. Journal of Econometrics, 66(1-2), 225-250.](https://ideas.repec.org/a/eee/econom/v66y1995i1-2p225-250.html)\n* [Hood, M., Kidd, Q., & Morris, I. (2008). Two Sides of the Same Coin? Employing Granger Causality Tests in a Time Series Cross-Section Framework. Political Analysis, 16(3), 324-344.](https://www.jstor.org/stable/25791939)\n* [Testing for Granger Causality Using Python](https://rishi-a.github.io/2020/05/25/granger-causality.html)", "meta": {"hexsha": "b2cf3dcadc0b5c000483fb20decb9d06eecd3434", "size": 19295, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/04_GrangerCausality/04_GrangerCausality.py", "max_stars_repo_name": "phdinds-aim/time_series_handbook", "max_stars_repo_head_hexsha": "9d22cf901c094035934359e2cbe98183b0cb41e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-02-15T12:27:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T21:50:02.000Z", "max_issues_repo_path": "_build/jupyter_execute/04_GrangerCausality/04_GrangerCausality.py", "max_issues_repo_name": "leolorenzoii/time_series_handbook", "max_issues_repo_head_hexsha": "88e5763886043104f916ccd4b13c719f181603c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-08T07:56:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-30T11:34:35.000Z", "max_forks_repo_path": "_build/jupyter_execute/04_GrangerCausality/04_GrangerCausality.py", "max_forks_repo_name": "leolorenzoii/time_series_handbook", "max_forks_repo_head_hexsha": "88e5763886043104f916ccd4b13c719f181603c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2021-02-04T16:36:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T14:53:04.000Z", "avg_line_length": 40.4507337526, "max_line_length": 486, "alphanum_fraction": 0.7089401399, "include": true, "reason": "import numpy,from statsmodels", "num_tokens": 5127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.9343951639111113, "lm_q1q2_score": 0.8582235023351902}}
{"text": "# -*- coding: UTF-8 -*-\n#!/usr/bin/python3\nimport numpy as np\n\ndef GENP(A, b):\n    '''\n    Gaussian elimination with no pivoting.\n    % input: A is an n x n nonsingular matrix\n    %        b is an n x 1 vector\n    % output: x is the solution of Ax=b.\n    % post-condition: A and b have been modified. \n    '''\n    n =  len(A)\n    if b.size != n:\n        raise ValueError(\"Invalid argument: incompatible sizes between A & b.\", b.size, n)\n\n    for pivot_row in range(n-1):\n        for row in range(pivot_row+1, n):\n            multiplier = A[row][pivot_row]/A[pivot_row][pivot_row]\n\n            A[row][pivot_row] = multiplier\n            for col in range(pivot_row + 1, n):\n                A[row][col] = A[row][col] - multiplier*A[pivot_row][col]\n\n            b[row] = b[row] - multiplier*b[pivot_row]\n\n    #print(A)\n    #print(b)\n    x = np.zeros(n)\n    k = n-1\n    x[k] = b[k]/A[k,k]\n    while k >= 0:\n        x[k] = (b[k] - np.dot(A[k,k+1:],x[k+1:]))/A[k,k]\n        k = k-1\n    return x\n\ndef GEPP(A, b):\n    '''\n    Gaussian elimination with partial pivoting.\n    % input: A is an n x n nonsingular matrix\n    %        b is an n x 1 vector\n    % output: x is the solution of Ax=b.\n    % post-condition: A and b have been modified. \n    '''\n    n =  len(A)\n    if b.size != n:\n        raise ValueError(\"Invalid argument: incompatible sizes between A & b.\", b.size, n)\n\n    for k in range(n-1):\n        maxindex = abs(A[k:,k]).argmax() + k\n        if A[maxindex, k] == 0:\n            raise ValueError(\"Matrix is singular.\")\n\n        if maxindex != k:\n            A[[k,maxindex]] = A[[maxindex, k]]\n            b[[k,maxindex]] = b[[maxindex, k]]\n        for row in range(k+1, n):\n            multiplier = A[row][k]/A[k][k]\n\n            A[row][k] = multiplier\n            for col in range(k + 1, n):\n                A[row][col] = A[row][col] - multiplier*A[k][col]\n\n            b[row] = b[row] - multiplier*b[k]\n    #print(A)\n    #print(b)\n    x = np.zeros(n)\n    k = n-1\n    x[k] = b[k]/A[k,k]\n    while k >= 0:\n        x[k] = (b[k] - np.dot(A[k,k+1:],x[k+1:]))/A[k,k]\n        k = k-1\n    return x\n\nif __name__ == \"__main__\":\n    '''\n    A = np.array([[1.,-1.,1.,-1.],[1.,0.,0.,0.],[1.,1.,1.,1.],[1.,2.,4.,8.]])\n    b = np.array([[14.],[4.],[2.],[2.]])    \n    '''\n    #generate matrix A\n    A = np.zeros((84,84))\n    A[0][0]=6\n    A[0][1]=1\n    A[83][82]=8\n    A[83][83]=6\n    col = 0\n    for row in range(1, 83):\n        A[row][col]  =8\n        A[row][col+1]=6\n        A[row][col+2]=1\n        col=col+1\n    #print(A)\n\n    #generate matrix A\n    b = np.zeros((84, 1))\n    b[0]=7\n    b[83]=14\n    for row in range(1, 83):\n        b[row]=15\n    #print(b)\n\n    print(\"Gaussian elimination with no pivoting.\")\n    print(GENP(np.copy(A), np.copy(b)))\n\n    print(\"Gaussian elimination with partial pivoting.\")\n    print(GEPP(A,b))", "meta": {"hexsha": "e661a788461710cce309124dfa750a4437fd2920", "size": 2823, "ext": "py", "lang": "Python", "max_stars_repo_path": "gaussian_elim.py", "max_stars_repo_name": "zhouyium/HomworkForNLA", "max_stars_repo_head_hexsha": "05395e934f520ad93cb41fc378863aad976ca149", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gaussian_elim.py", "max_issues_repo_name": "zhouyium/HomworkForNLA", "max_issues_repo_head_hexsha": "05395e934f520ad93cb41fc378863aad976ca149", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gaussian_elim.py", "max_forks_repo_name": "zhouyium/HomworkForNLA", "max_forks_repo_head_hexsha": "05395e934f520ad93cb41fc378863aad976ca149", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6320754717, "max_line_length": 90, "alphanum_fraction": 0.4948636203, "include": true, "reason": "import numpy", "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.897695292107347, "lm_q1q2_score": 0.8581799596120787}}
{"text": "'''\nGenerating meshes\n\nIn order to visualize two-dimensional arrays of data, it is necessary to understand how to generate and manipulate 2-D arrays. Many Matplotlib plots support arrays as input and in particular, they support NumPy arrays. The NumPy library is the most widely-supported means for supporting numeric arrays in Python.\n\nIn this exercise, you will use the meshgrid function in NumPy to generate 2-D arrays which you will then visualize using plt.imshow(). The simplest way to generate a meshgrid is as follows:\n\nimport numpy as np\nY,X = np.meshgrid(range(10),range(20))\nThis will create two arrays with a shape of (20,10), which corresponds to 20 rows along the Y-axis and 10 columns along the X-axis. In this exercise, you will use np.meshgrid() to generate a regular 2-D sampling of a mathematical function.\n\nINSTRUCTIONS\n100XP\nImport the numpy and matplotlib.pyplot modules using the respective aliases np and plt.\nGenerate two one-dimensional arrays u and v using np.linspace(). The array u should contain 41 values uniformly spaced beween -2 and +2. The array v should contain 21 values uniformly spaced between -1 and +1.\nConstruct two two-dimensional arrays X and Y from u and v using np.meshgrid(). The resulting arrays should have shape (41,21).\nAfter the array Z is computed using X and Y, visualize the array Z using plt.pcolor() and plt.show().\nSave the resulting figure as 'sine_mesh.png'.\n'''\n# Import numpy and matplotlib.pyplot\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Generate two 1-D arrays: u, v\nu = np.linspace(-2, 2, 41)\nv = np.linspace(-1, 1, 21)\n\n# Generate 2-D arrays from u and v: X, Y\nX,Y = np.meshgrid(u, v)\n\n# Compute Z based on X and Y\nZ = np.sin(3*np.sqrt(X**2 + Y**2)) \n\n# Display the resulting image with pcolor()\nplt.pcolor(Z)\nplt.show()\n\n# Save the figure to 'sine_mesh.png'\nplt.savefig('sine_mesh.png')\n", "meta": {"hexsha": "3533c379d6d66aad0972fd259044a57b762c5397", "size": 1867, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data Science With Python/13-introduction-to-data-visualization-with-python/02-plotting-2d-arrays/01-generating-meshes.py", "max_stars_repo_name": "aimanahmedmoin1997/DataCamp", "max_stars_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-12T04:49:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T00:40:28.000Z", "max_issues_repo_path": "Data Science With Python/13-introduction-to-data-visualization-with-python/02-plotting-2d-arrays/01-generating-meshes.py", "max_issues_repo_name": "aimanahmedmoin1997/DataCamp", "max_issues_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science With Python/13-introduction-to-data-visualization-with-python/02-plotting-2d-arrays/01-generating-meshes.py", "max_forks_repo_name": "aimanahmedmoin1997/DataCamp", "max_forks_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-11-06T17:43:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T21:08:16.000Z", "avg_line_length": 46.675, "max_line_length": 312, "alphanum_fraction": 0.7584359936, "include": true, "reason": "import numpy", "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813451206062, "lm_q2_score": 0.8976952927915968, "lm_q1q2_score": 0.8581799535113471}}
{"text": "import numpy as np\nimport pandas\nfrom ggplot import *\n\n\"\"\"\nIn this question, you need to:\n1) implement the compute_cost() and gradient_descent() procedures\n2) Select features (in the predictions procedure) and make predictions.\n\n\"\"\"\n\ndef normalize_features(df):\n    \"\"\"\n    Normalize the features in the data set.\n    \"\"\"\n    mu = df.mean()\n    sigma = df.std()\n    \n    if (sigma == 0).any():\n        raise Exception(\"One or more features had the same value for all samples, and thus could \" + \\\n                         \"not be normalized. Please do not include features with only a single value \" + \\\n                         \"in your model.\")\n    df_normalized = (df - df.mean()) / df.std()\n\n    return df_normalized, mu, sigma\n\ndef compute_cost(features, values, theta):\n    \"\"\"\n    Compute the cost function given a set of features / values, \n    and the values for our thetas.\n    \n    This can be the same code as the compute_cost function in the lesson #3 exercises,\n    but feel free to implement your own.\n    \"\"\"\n    m = len(values)\n    sum_of_square_errors = np.square(np.dot(features, theta) - values).sum()\n    cost = sum_of_square_errors / (2*m)\n    return cost\n\ndef gradient_descent(features, values, theta, alpha, num_iterations):\n    \"\"\"\n    Perform gradient descent given a data set with an arbitrary number of features.\n    \n    This can be the same gradient descent code as in the lesson #3 exercises,\n    but feel free to implement your own.\n    \"\"\"\n    \n    m = len(values)\n    cost_history = []\n\n    for i in range(num_iterations):\n        cost = compute_cost(features,values,theta)\n        cost_history.append(cost)\n        theta = theta + (alpha/m)*np.dot((values - np.dot(features,theta)),features)\n\n    return theta, pandas.Series(cost_history)\n\ndef predictions(dataframe):\n    '''\n    The NYC turnstile data is stored in a pandas dataframe called weather_turnstile.\n    Your prediction should have a R^2 value of 0.40 or better.\n    You need to experiment using various input features contained in the dataframe. \n    '''\n    # print dataframe # see which fields we can use\n    \n    # Select Features (try different features!)\n    features = dataframe[['rain', 'precipi', 'Hour', 'meantempi']]\n    \n    # Add UNIT to features using dummy variables\n    dummy_units = pandas.get_dummies(dataframe['UNIT'], prefix='unit')\n    features = features.join(dummy_units)\n    \n    # Values\n    values = dataframe['ENTRIESn_hourly']\n    m = len(values)\n\n    features, mu, sigma = normalize_features(features)\n    features['ones'] = np.ones(m) # Add a column of 1s (y intercept)\n    \n    # Convert features and values to numpy arrays\n    features_array = np.array(features)\n    values_array = np.array(values)\n\n    # Set values for alpha, number of iterations.\n    alpha = 0.1 # please feel free to change this value\n    num_iterations = 75 # please feel free to change this value\n\n    # Initialize theta, perform gradient descent\n    theta_gradient_descent = np.zeros(len(features.columns))\n    theta_gradient_descent, cost_history = gradient_descent(features_array, \n                                                            values_array, \n                                                            theta_gradient_descent, \n                                                            alpha, \n                                                            num_iterations)\n    \n    plot = None\n    \n    predictions = np.dot(features_array, theta_gradient_descent)\n    return predictions, plot\n\n\ndef plot_cost_history(alpha, cost_history):\n   \"\"\"This function is for viewing the plot of your cost history.\n   You can run it by uncommenting this\n\n       plot_cost_history(alpha, cost_history) \n\n   call in predictions.\n   \n   If you want to run this locally, you should print the return value\n   from this function.\n   \"\"\"\n   cost_df = pandas.DataFrame({\n      'Cost_History': cost_history,\n      'Iteration': range(len(cost_history))\n   })\n   return ggplot(cost_df, aes('Iteration', 'Cost_History')) + \\\n      geom_point() + ggtitle('Cost History for alpha = %.3f' % alpha )\n\n\n\n", "meta": {"hexsha": "d0603a9846fc7ca13d54b4b3c3af04b91497a22e", "size": 4094, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapter3/subwayRegress.py", "max_stars_repo_name": "mmisamore/intro-data-science", "max_stars_repo_head_hexsha": "9010ab91d916bcf3eb31729a245d5057bc6c5917", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter3/subwayRegress.py", "max_issues_repo_name": "mmisamore/intro-data-science", "max_issues_repo_head_hexsha": "9010ab91d916bcf3eb31729a245d5057bc6c5917", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter3/subwayRegress.py", "max_forks_repo_name": "mmisamore/intro-data-science", "max_forks_repo_head_hexsha": "9010ab91d916bcf3eb31729a245d5057bc6c5917", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5573770492, "max_line_length": 106, "alphanum_fraction": 0.6375183195, "include": true, "reason": "import numpy", "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813501370535, "lm_q2_score": 0.8976952880018481, "lm_q1q2_score": 0.8581799534356779}}
{"text": "from typing import Tuple, Optional\n\nimport numpy as np\n\n\n__all__ = [\n    \"sigmoid\",\n    \"tanh\",\n    \"relu\",\n    \"softmax\",\n]\n\n\ndef sigmoid(x: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Applies the element-wise sigmoid function.\n\n    Parameters:\n        x (np.ndarray): Input array.\n\n    Returns:\n        Function output.\n    \"\"\"\n    return 1 / (1 + np.exp(-x))\n\n\ndef tanh(x: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Applies the element-wise hyperbolic tangent function. Note that this function is a\n    simple wrapper around `numpy.tanh()`.\n\n    Parameters:\n        x (np.ndarray): Input array.\n\n    Returns:\n        Function output.\n    \"\"\"\n    return np.tanh(x)\n\n\ndef relu(x: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Applies the element-wise rectified linear unit function.\n\n    Parameters:\n        x (np.ndarray): Input array.\n    \n    Returns:\n        Function output.\n    \"\"\"\n    return x * (x > 0)\n\n\ndef softmax(x: np.ndarray, axis: Optional[int] = None) -> np.ndarray:\n    \"\"\"\n    Applies a softmax function along the argument dimension `axis`.\n\n    Parameters:\n        x (np.ndarray): Input array.\n        axis (Optional[int]): A dimension along which softmax will be computed.\n    \n    Returns:\n        Function output.\n    \"\"\"\n    e_x = np.exp(x - np.max(x))\n    return e_x / e_x.sum(axis=axis, keepdims=True)\n", "meta": {"hexsha": "42496e95990b107e3e6c655616a92a710743b7ca", "size": 1312, "ext": "py", "lang": "Python", "max_stars_repo_path": "npnn/functional.py", "max_stars_repo_name": "jinyeom/npnn", "max_stars_repo_head_hexsha": "f7a465a5a1bb912e3481e6e77ad311e3752d281d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "npnn/functional.py", "max_issues_repo_name": "jinyeom/npnn", "max_issues_repo_head_hexsha": "f7a465a5a1bb912e3481e6e77ad311e3752d281d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "npnn/functional.py", "max_forks_repo_name": "jinyeom/npnn", "max_forks_repo_head_hexsha": "f7a465a5a1bb912e3481e6e77ad311e3752d281d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5820895522, "max_line_length": 86, "alphanum_fraction": 0.5952743902, "include": true, "reason": "import numpy", "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813463747182, "lm_q2_score": 0.8976952845805988, "lm_q1q2_score": 0.8581799467875967}}
{"text": "import numpy as np\nimport sys\n\n'''\nv0.3 Dec. 17, 2017\n    - refactor > rename functions by adding \"_rad\"\n    - refactor > add function comment\nv0.2 Dec. 10, 2017\n    - fix bug: calc_gamma_rad() was too complicated\n        _+ use arctan2()\n    - add Test_group_run_random()\nv0.1 Dec. 09, 2017\n    - add Test_group_run_axes()\n    - add calc_gamma_rad()\n    - add calc_beta_rad()\n'''\n\n\ndef calc_beta_rad(pvec):\n    '''\n    polar angle [0, pi]\n    '''\n    return np.arccos(pvec[2])  # arccos:[0, pi]\n\n\ndef calc_gamma_rad(pvec):\n    '''\n    azimuth angle [0, 2pi]\n    '''\n    gamma = np.arctan2(pvec[1], pvec[0])\n    if gamma < 0.0:\n        gamma += 2 * np.pi\n    return gamma\n\n\ndef Test_group_run_axes():\n    pvecs = [\n        [0, 0, 1],  # z direction\n        [0, 0, -1],  # z direction\n        [0, 1, 0],  # y direction\n        [0, -1, 0],  # y direction\n        [1, 0, 0],  # x direction\n        [-1, 0, 0],  # x direction\n        ]\n    for elem in pvecs:\n        beta_rad = calc_beta_rad(elem)\n        gamma_rad = calc_gamma_rad(elem)\n\n        fmt = \"{0} \\tbeta:{1:.5f} gamma:{2:.5f}\"\n        msg = fmt.format(elem, beta_rad, gamma_rad)\n        print(msg)\n\n\ndef Test_calc_xyz(beta_rad, gamma_rad):\n    rad = 1.0  # radius\n    resx = rad * np.cos(gamma_rad) * np.sin(beta_rad)\n    resy = rad * np.sin(gamma_rad) * np.sin(beta_rad)\n    resz = rad * np.cos(beta_rad)\n    return resx, resy, resz\n\n\ndef Test_group_run_random():\n    bt_stp = np.pi / 4.0  # beta step\n    gm_stp = np.pi / 4.0  # gamma step\n    for bt_in in np.arange(0.0, np.pi, bt_stp):\n        for gm_in in np.arange(0.0, 2 * np.pi, gm_stp):\n            # print(bt_in, gm_in)\n            wrk = Test_calc_xyz(bt_in, gm_in)\n            bt_out = calc_beta_rad(wrk)\n            gm_out = calc_gamma_rad(wrk)\n            if abs(gm_in - gm_out) > sys.float_info.epsilon:\n                print(\"%+.5e\" % (gm_in - gm_out), end=' ')\n                print(\"NG:\", end=\" \")\n            else:\n                continue\n            msg = ','.join(\"%+.5f\" % elem for elem in wrk)\n            print(msg, end=' -- ')\n            fmt = \"b{0:.5f} b{1:.5f} g{2:.5f} g{3:.5f}\"\n            msg = fmt.format(bt_in, bt_out, gm_in, gm_out)\n            print(msg)\n\n\nif __name__ == '__main__':\n    Test_group_run_random()\n    #Test_group_run_axes()\n", "meta": {"hexsha": "fe0c5efa6b23203c63206531f61eb9442520da95", "size": 2282, "ext": "py", "lang": "Python", "max_stars_repo_path": "polarAzimuthCalc_171209.py", "max_stars_repo_name": "yasokada/ADDA_pySpherepts_171217", "max_stars_repo_head_hexsha": "ae1688c788811c616c0594f4d2c1eeca7643b797", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "polarAzimuthCalc_171209.py", "max_issues_repo_name": "yasokada/ADDA_pySpherepts_171217", "max_issues_repo_head_hexsha": "ae1688c788811c616c0594f4d2c1eeca7643b797", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "polarAzimuthCalc_171209.py", "max_forks_repo_name": "yasokada/ADDA_pySpherepts_171217", "max_forks_repo_head_hexsha": "ae1688c788811c616c0594f4d2c1eeca7643b797", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5348837209, "max_line_length": 60, "alphanum_fraction": 0.5381244522, "include": true, "reason": "import numpy", "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322215, "lm_q2_score": 0.9073122276263202, "lm_q1q2_score": 0.8581370601081368}}
{"text": "from lega.shen_basis import shen_function, mass_matrix, stiffness_matrix,\\\n    shen_basis\nfrom scipy.linalg import eigh\nfrom sympy.plotting import plot\nfrom sympy import Symbol\n\n# Visualize the eigenfunctions of -u'' = lmnda u in (-1, 1) with u(-1)=u(1)=0\n# Are they in some sense similar to sines(k*pi*x) and cos(k*pi/2*x) which solve\n# the problem?\n\nn = 10\nbasis = shen_basis(10)\n\n# Solve the eigenvalue problem to get coeffs of the new basis\nA = stiffness_matrix(n)\nM = mass_matrix(n)\nlmbdas, V = eigh(A.toarray(), M.toarray())\n\n# Make the new basis\nAbasis = [shen_function(v) for v in V.T]\n\nprint 'eigenvalues', lmbdas\n\n# Plot the basis for comparison\nx = Symbol('x')\nf_fA = iter(zip(basis, Abasis))\n\nf, fA = next(f_fA)\np = plot(f, (x, -1, 1), show=False)\np[0].line_color = 'red'\np_ = plot(fA, (x, -1, 1), show=False)\np_[0].line_color = 'blue'\np.append(p_[0])\n\nfor f, fA in f_fA:\n    p_ = plot(f, (x, -1, 1), show=False)\n    p_[0].line_color = 'red'\n    p.append(p_[0])\n\n    p_ = plot(fA, (x, -1, 1), show=False)\n    p_[0].line_color = 'blue'\n    p.append(p_[0])\n\np.show()\n\n# Some questions, what are the approximation properties of Abasis? And how does\n# the transformation between function and its series look? And, is there a\n# clever way to get the eigenvalues and eigenvectors\n", "meta": {"hexsha": "686c5e622ace98abbafbc2a8990f13106b66d95d", "size": 1286, "ext": "py", "lang": "Python", "max_stars_repo_path": "sandbox/A_shen_basis.py", "max_stars_repo_name": "MiroK/lega", "max_stars_repo_head_hexsha": "ceb684ad639521e4a6e679188761984e2caa5611", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-07-14T01:19:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-10T14:00:45.000Z", "max_issues_repo_path": "sandbox/A_shen_basis.py", "max_issues_repo_name": "MiroK/lega", "max_issues_repo_head_hexsha": "ceb684ad639521e4a6e679188761984e2caa5611", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sandbox/A_shen_basis.py", "max_forks_repo_name": "MiroK/lega", "max_forks_repo_head_hexsha": "ceb684ad639521e4a6e679188761984e2caa5611", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2448979592, "max_line_length": 79, "alphanum_fraction": 0.6804043546, "include": true, "reason": "from scipy,from sympy", "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877692486438, "lm_q2_score": 0.8840392863287585, "lm_q1q2_score": 0.8581261227746256}}
{"text": "from numpy import conj, dot\n# tool for evaluating operators\n\nclass OperatorChecker():\n    def check_hermitian(operator):\n        '''\n        check_hermitian(operator)\n\n        Description:\n            - this function takes a 2 by 2 operator matrix and checks to see if it is hermitian (equal to its transposed conjugate)\n            - this is useful because all qbit operators corresponding to quantum logic gates must be hermitian\n\n        Parameters:\n            - operator <type 'list'>: matrix representing the quantum operator\n            \n        Returns:\n            - hermitian <type 'bool'>: boolean value storing if the passed matrix is hermitian\n\n        Example:\n            >>> oc = qonic_misc.OperatorChecker\n            >>> pauli_z = [[1, 0], [0, -1]] # pauli z gate\n            >>> print(oc.check_hermitian(pauli_z)) # check to see if the pauli z gate is hermitian\n            True\n\n        '''\n    \n        # check all 4 of the elements of the matrix to test for hermitianarity (hermitiary, hermitianary, i dont know...)\n        element00 = (operator[0][0]) == conj(operator[0][0])\n        element01 = (operator[0][1]) == conj(operator[1][0])\n        element10 = (operator[1][0]) == conj(operator[0][1])\n        element11 = (operator[1][1]) == conj(operator[1][1])\n\n        # if all 4 of the above conditions are true, then the operator matrix is hermitian\n        return (element00 and element01 and element10 and element11)\n\n\n    def check_unitary(operator):\n        '''\n        check_unitary(operator)\n\n        Description:\n            - this function takes a 2 by 2 operator matrix and checks to see if it is unitary (produces the identity matrix when multiplied by its transposed conjugate)\n            - this is useful because all qbit operators corresponding to quantum logic gates must be unitary\n\n        Parameters:\n            - operator <type 'list'>: matrix representing the quantum operator\n            \n        Returns:\n            - unitary <type 'bool'>: boolean value storing if the passed matrix is unitary\n\n        Example:\n            >>> oc = qonic_misc.OperatorChecker\n            >>> pauli_z = [[1, 0], [0, -1]] # pauli z gate\n            >>> print(oc.check_unitary(pauli_z) # check to see if the pauli z gate is unitary\n            True\n\n        '''\n\n        # define the transposed conjugate of the passed operator\n        trans_conj = [[conj(operator[0][0]), conj(operator[1][0])], [conj(operator[0][1]), conj(operator[1][1])]] \n\n        # get the product of the two matricies\n        product = dot(operator, trans_conj)\n\n        # round to 10 decimal points to avoid small errors causing the function to return false\n        for i in range(2):\n            for j in range(2):\n                product[i][j] = round(product[i][j], 10)\n\n        # check to see if the product is equal to the identity matrix, and return the result\n        return product.tolist() == [[1, 0], [0, 1]]\n", "meta": {"hexsha": "8fedfb506952bf80afc73a40e01ec67e866ffc8e", "size": 2923, "ext": "py", "lang": "Python", "max_stars_repo_path": "source_dir/qonic_misc/OperatorChecker.py", "max_stars_repo_name": "Qonic-Team/qonic-misc", "max_stars_repo_head_hexsha": "03154781df6a35e4689b57052e579beb9990626a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-26T18:41:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T18:41:01.000Z", "max_issues_repo_path": "source_dir/qonic_misc/OperatorChecker.py", "max_issues_repo_name": "Qonic-Team/qonic-misc", "max_issues_repo_head_hexsha": "03154781df6a35e4689b57052e579beb9990626a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source_dir/qonic_misc/OperatorChecker.py", "max_forks_repo_name": "Qonic-Team/qonic-misc", "max_forks_repo_head_hexsha": "03154781df6a35e4689b57052e579beb9990626a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-26T18:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T18:41:15.000Z", "avg_line_length": 40.5972222222, "max_line_length": 168, "alphanum_fraction": 0.6113581936, "include": true, "reason": "from numpy", "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.972414716174355, "lm_q2_score": 0.88242786954645, "lm_q1q2_score": 0.858085846309352}}
{"text": "from scipy import eye, dot\n\ndef rowswap(n, j, k):\n    \"\"\"Swaps two rows\n        INPUTS: n -> matrix size\n        j, k -> the two rows to swap\"\"\"\n    out = eye(n)\n    out[j,j]=0\n    out[k,k]=0\n    out[j,k]=1\n    out[k,j]=1\n    return out\n    \ndef cmult(n, j, const):\n    \"\"\"Multiplies a row by a constant\n    INPUTS: n -> array size\n            j -> row\n            const -> constant\"\"\"\n    out = eye(n)\n    out[j,j]=const\n    return out\n    \ndef cmultadd(n, j, k, const):\n    \"\"\"Multiplies a row (k) by a constant and adds the result to another row (j)\"\"\"\n    out = eye(n)\n    out[j,k] = const\n    return out\n    \ndef ref(A):\n    \"\"\"Performs a naive row reduction on A\"\"\"\n    \n    n = min(A.shape)\n    ref = A.astype(float).copy()\n    for a in xrange(n):\n        for b in xrange(a,n):\n            if ref[a,a] != 0:\n                ref = dot(cmultadd(n, b, a, -ref[b, a]/ref[a, a]), ref)\n            else: continue\n        ref = dot(cmult(n, a, 1.0/ref[a,a]), ref)\n        \n    return ref\n\ndef LU(A):\n    rows, cols = A.shape\n    U = A.copy()\n    L = eye(rows, rows)\n    for i in range(rows):\n        for j in range(i+1,rows):\n            E = cmultadd(rows,j,i,-U[j,i]/U[i,i])\n            F = cmultadd(rows,j,i,U[j,i]/U[i,i])\n            U = dot(E,U)\n            L = dot(L,F)\n    return (L,U)\n\ndef LU_det(A):\n    \"\"\"Find the determinant of a matrix using the LU factorization\"\"\"\n    U = LU(A)[1]\n    det = 1\n    for i in range(U.shape[0]):\n        det *= U[i,i]\n    return det", "meta": {"hexsha": "d231be894d6b0f23bbd982ccb3117997d1131b93", "size": 1475, "ext": "py", "lang": "Python", "max_stars_repo_path": "Algorithms/ElemMatrices/Elem_Matrices.py", "max_stars_repo_name": "jasongrout/numerical_computing", "max_stars_repo_head_hexsha": "fa29838af62417703c65f680b167e81828de01c5", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Algorithms/ElemMatrices/Elem_Matrices.py", "max_issues_repo_name": "jasongrout/numerical_computing", "max_issues_repo_head_hexsha": "fa29838af62417703c65f680b167e81828de01c5", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Algorithms/ElemMatrices/Elem_Matrices.py", "max_forks_repo_name": "jasongrout/numerical_computing", "max_forks_repo_head_hexsha": "fa29838af62417703c65f680b167e81828de01c5", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-21T23:06:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T23:06:27.000Z", "avg_line_length": 24.1803278689, "max_line_length": 83, "alphanum_fraction": 0.493559322, "include": true, "reason": "from scipy", "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561694652215, "lm_q2_score": 0.8856314783461303, "lm_q1q2_score": 0.8580495216682531}}
{"text": "\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nts = np.arange(100)\ntis = np.array([25, 50, 75])\nlr_list = []\nlr0 = 1\ngamma = 0.9\nfor t in ts:\n    passed_num_thresholds = sum(t > tis)\n    lr = lr0 * np.power(gamma, passed_num_thresholds)\n    lr_list.append(lr)\n    \nplt.figure()\nplt.plot(lr_list)\nplt.title('piecewise constant')\nplt.savefig('../figures/lr_piecewise_constant.pdf', dpi=300)\nplt.show()\n\n\nts = np.arange(100)\nlam = 0.999\nlr0 = 1\nlr_list = lr0 * np.exp(-lam*ts)\n\nplt.figure()\nplt.plot(lr_list)\nplt.title('exponential decay')\nplt.savefig('../figures/lr_exp_decay.pdf', dpi=300)\nplt.show()\n\n\nts = np.arange(100)\nalpha = 0.5\nbeta = 1\nlr0 = 1\nlr_list = lr0 * np.power(beta*ts + 1, -alpha)\n\nplt.figure()\nplt.plot(lr_list)\nplt.title('polynomial decay')\nplt.savefig('../figures/lr_poly_decay.pdf', dpi=300)\nplt.show()", "meta": {"hexsha": "7dd6b4b910104a96b6936cde2e53b0f2efbd48ce", "size": 830, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/learning_rate_plot.py", "max_stars_repo_name": "VaibhaviMishra04/pyprobml", "max_stars_repo_head_hexsha": "53208f571561acd25e8608ac5d1eb5e2610f6cc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-22T05:43:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T08:40:16.000Z", "max_issues_repo_path": "scripts/learning_rate_plot.py", "max_issues_repo_name": "Rebeca98/pyprobml", "max_issues_repo_head_hexsha": "2a4b9a267f64720cbba35dfa41af3e995ea006ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-19T12:25:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T12:25:26.000Z", "max_forks_repo_path": "scripts/learning_rate_plot.py", "max_forks_repo_name": "Rebeca98/pyprobml", "max_forks_repo_head_hexsha": "2a4b9a267f64720cbba35dfa41af3e995ea006ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-21T01:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T01:18:07.000Z", "avg_line_length": 18.0434782609, "max_line_length": 60, "alphanum_fraction": 0.6819277108, "include": true, "reason": "import numpy", "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350252, "lm_q2_score": 0.8902942377652497, "lm_q1q2_score": 0.8580477307371273}}
{"text": "from scipy.misc import derivative\n\nf = lambda x: 0.1*x**5 - 0.2*x**3 + 0.1*x - 0.2\n\ndx = 0.01       # Step size, equal differences of x, ∆x\n# dx = 0.001    # Smaller step size gives less error\nx0 = 0.1        # Find derivatives of f(x) at point x\n\n# Derivative Function:\ny1 = derivative(f, x0, dx, 1)   # n = 1 for 1st derivative\ny2 = derivative(f, x0, dx, 2)   # n = 2 for 2nd derivative\n\nprint('derivative(f, ', x0,', ', dx,', 1) = %f' % y1, sep='')\nprint('derivative(f, ', x0,', ', dx,', 2) = %f' % y2, sep='')\n\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~ Plotting the function ~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nfrom numpy import linspace\nfrom matplotlib.pyplot import plot, xlabel, ylabel, legend, grid, show\n\nX = linspace(-1, 1)             # Divides from -1 to 1 into 50 points\n\n# Central Differences Approximation :\nDFC1 = derivative(f, X, dx, 1)\nDFC2 = derivative(f, X, dx, 2)\n\n# pyplot.\nplot(X,f(X),'-k', X,DFC1,'--b', X,DFC2,'-.r')\nxlabel('x')\nylabel('y, y\\', y\\'\\'')\nlegend(['f(x)', 'f\\'(x)', 'f\\'\\'(x)'])\ngrid()\nshow()\n", "meta": {"hexsha": "d8ef1d41fabbf98ff77cd2f7c2636c0b0ecf1214", "size": 1010, "ext": "py", "lang": "Python", "max_stars_repo_path": "3. Numerical Differentiation/0. Numerical Differentiation function of SciPy.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3. Numerical Differentiation/0. Numerical Differentiation function of SciPy.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3. Numerical Differentiation/0. Numerical Differentiation function of SciPy.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8571428571, "max_line_length": 76, "alphanum_fraction": 0.5544554455, "include": true, "reason": "from numpy,from scipy", "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799451753697, "lm_q2_score": 0.8902942217558213, "lm_q1q2_score": 0.8580477162337738}}
{"text": "import numpy as np\nfrom numba import jit\n\n@jit(nopython=True)\ndef interp1d(grid, vals, x):\n    \"\"\"\n    Linearly interpolate (grid, vals) to evaluate at x.\n\n    Parameters\n    ----------\n        grid and vals are numpy arrays, x is a float\n\n    Returns\n    -------\n        a float, the interpolated value\n\n    \"\"\"\n\n    a, b, G = np.min(grid), np.max(grid), len(grid)\n\n    s = (x - a) / (b - a)\n\n    q_0 = max(min(int(s * (G - 1)), (G - 2)), 0)\n    v_0 = vals[q_0]\n    v_1 = vals[q_0 + 1]\n\n    λ = s * (G - 1) - q_0\n\n    return (1 - λ) * v_0 + λ * v_1\n\n\n@jit(nopython=True)\ndef interp1d_vectorized(grid, vals, x_vec):\n    \"\"\"\n    Linearly interpolate (grid, vals) to evaluate at x_vec.\n\n    All inputs are numpy arrays.\n\n    Return value is a numpy array of length len(x_vec).\n    \"\"\"\n\n    out = np.empty_like(x_vec)\n\n    for i, x in enumerate(x_vec):\n        out[i] = interp1d(grid, vals, x)\n\n    return out\n\n\n", "meta": {"hexsha": "407e9b8582ea873aca7bc49f75f3096eea2df798", "size": 909, "ext": "py", "lang": "Python", "max_stars_repo_path": "day3/applications/job_search/lininterp.py", "max_stars_repo_name": "fkazemian/columbia_mini_course", "max_stars_repo_head_hexsha": "5f7188b0e8eab6e90eed23fd0b7f11483c6b68a6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2018-02-20T16:12:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T21:13:21.000Z", "max_issues_repo_path": "day3/applications/job_search/lininterp.py", "max_issues_repo_name": "fkazemian/columbia_mini_course", "max_issues_repo_head_hexsha": "5f7188b0e8eab6e90eed23fd0b7f11483c6b68a6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-04-23T01:07:57.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-23T01:08:17.000Z", "max_forks_repo_path": "day3/applications/job_search/lininterp.py", "max_forks_repo_name": "fkazemian/columbia_mini_course", "max_forks_repo_head_hexsha": "5f7188b0e8eab6e90eed23fd0b7f11483c6b68a6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 32, "max_forks_repo_forks_event_min_datetime": "2018-03-26T14:01:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T10:32:47.000Z", "avg_line_length": 18.18, "max_line_length": 59, "alphanum_fraction": 0.5577557756, "include": true, "reason": "import numpy,from numba", "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075755433747, "lm_q2_score": 0.8918110490322426, "lm_q1q2_score": 0.8580181662272046}}
{"text": "import numpy as np\n#-------------------------------------------------------------------------\n'''\n    Problem 3: PageRank algorithm (version 1)\n    In this problem, we implement a simplified version of the pagerank algorithm, which doesn't consider about sink node problem or sink region problem.\n    You could test the correctness of your code by typing `nosetests -v test3.py` in the terminal.\n'''\n\n#--------------------------\ndef compute_P(A):\n    '''\n        compute the transition matrix P from addjacency matrix A. P[j][i] represents the probability of moving from node i to node j.\n        Input:\n                A: adjacency matrix, a (n by n) numpy matrix of binary values. If there is a link from node i to node j, A[j][i] =1. Otherwise A[j][i]=0 if there is no link.\n        Output:\n                P: transition matrix, a (n by n) numpy matrix of float values.  P[j][i] represents the probability of moving from node i to node j.\n    The values in each column of matrix P should sum to 1.\n    '''\n    #########################################\n    ## INSER YOUR CODE HERE\n\n    np.seterr(divide='ignore', invalid='ignore')\n    # create a diagonal matrix\n    np.fill_diagonal(A, 0)\n\n    # sum of each column of A\n    colsums = A.sum(axis=0)\n\n    # normalize each column of A\n    P = A / colsums\n\n    #########################################\n    return P\n\n\n\n#--------------------------\ndef random_walk_one_step(P, x_i):\n    '''\n        compute the result of one step random walk.\n        Input:\n                P: transition matrix, a (n by n) numpy matrix of float values.  P[j][i] represents the probability of moving from node i to node j.\n                x_i: pagerank scores before the i-th step of random walk. a numpy vector of shape (n by 1).\n        Output:\n                x_i_plus_1: pagerank scores after the i-th step of random walk. a numpy vector of shape (n by 1).\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n    x_i_plus_1 = np.dot(P, x_i)\n\n\n\n    #########################################\n    return x_i_plus_1\n\n\n#--------------------------\ndef random_walk(P, x_0, max_steps=10000):\n    '''\n        compute the result of multiple-step random walk. The random walk should stop if the score vector x no longer change (converge) after one step of random walk, or the number of iteration reached max_steps.\n        Input:\n                P: transition matrix, a (n by n) numpy matrix of float values.  P[j][i] represents the probability of moving from node i to node j.\n                x_0: the initial pagerank scores. a numpy vector of shape (n by 1).\n                max_steps: the maximium number of random walk steps. an integer value.\n        Output:\n                x: the final pagerank scores after multiple steps of random walk. a numpy vector of shape (n by 1).\n                n_steps: the number of steps actually used (for example, if the vector x no longer changes after 3 steps of random walk, return the value 3.\n        Hint: you could use np.allclose(x, previous_x) function to determine when to stop the random walk iterations.\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n    x = x_0\n\n    for n_steps in range(1, max_steps+1):\n        previous_x = x\n        x = random_walk_one_step(P, previous_x)\n        if np.allclose(x, previous_x):\n            break\n\n    #########################################\n\n    return x, n_steps\n\n\n#--------------------------\ndef pagerank_v1(A):\n    '''\n        A simplified version of PageRank algorithm.\n        Given an adjacency matrix A, compute the pagerank score of all the nodes in the network.\n        Here we ignore the issues of sink nodes and sink regions in the network.\n        Input:\n                A: adjacency matrix, a numpy matrix of binary values. If there is a link from node i to node j, A[j][i] =1. Otherwise A[j][i]=0 if there is no link.\n        Output:\n                x: the ranking scores, a numpy vector of float values, such as np.array([[.3], [.5], [.7]])\n    '''\n\n    # compute the transition matrix from adjacency matrix\n    P = compute_P(A)\n\n    # initialize the score vector with all one values\n    num_nodes, _ = A.shape # get the number of nodes (n)\n    x_0 =  np.ones((num_nodes,1)) # create an all-one vector of shape (n by 1)\n\n    # random walk\n    x, n_steps = random_walk(P, x_0)\n\n    return x\n\n", "meta": {"hexsha": "5eba28ee22c2c98add5489c4afdef1e60d1703f1", "size": 4388, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw1/problem3.py", "max_stars_repo_name": "rahul-pande/ds501", "max_stars_repo_head_hexsha": "063453de9bf7bc634422a6710d36715175cbeebf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw1/problem3.py", "max_issues_repo_name": "rahul-pande/ds501", "max_issues_repo_head_hexsha": "063453de9bf7bc634422a6710d36715175cbeebf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw1/problem3.py", "max_forks_repo_name": "rahul-pande/ds501", "max_forks_repo_head_hexsha": "063453de9bf7bc634422a6710d36715175cbeebf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8909090909, "max_line_length": 211, "alphanum_fraction": 0.5777119417, "include": true, "reason": "import numpy", "num_tokens": 1018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075777163567, "lm_q2_score": 0.8918110418436167, "lm_q1q2_score": 0.8580181612488624}}
{"text": "'''\n@author: Professor\n'''\n# import RootFinders as R\n\nfrom numpy import ceil, log2\nfrom math import fabs\n\n# -------------------------------------------\n\ndef bisection(f,a,b,tol=1e-9):\n\tfa, fb = f(a), f(b)\n\tN = int( ceil( log2((b-a)/tol ) ) )\n\t\n\tx = []  # empty list\n\t\n\tfor i in range(N):\n\t\tc = (b+a)/2\n\t\tx.append(c)\n\t\tfc = f(c)\n\t\tif fa*fc < 0:  # x* is in [a,c]\n\t\t\tb, fb = c, fc\n\t\telse:\n\t\t\ta, fa = c, fc\n\t\t\t\n\tx.append((b+a)/2)\n\treturn x\n\t\n# ----------------------------------------------\n\ndef newton(f,fp,x0,tol=1e-10,maxIt=50):\n\tdx, fx = 100, 100\n\titer = 0\n\txa = []\n\txa.append(x0)\n\tx = x0\n\t\n\twhile fabs(dx)>tol or fabs(fx)>tol and iter<=maxIt:\n\t\tfx, fpx = f(x), fp(x)\n\t\tdx = -fx/fpx\n\t\tprint(dx)\n\t\tx += dx\n\t\titer += 1\n\t\txa.append(x)\n\t\t\n\treturn xa\n\t\n# ----------------------------------------------\n\nfrom pylab import *\n\ndef newtonSystem(f,J,x0,tol=1e-10,maxIt=50):\n\t\n\tN = len(x0)\n\tdx, fx = ones((N,)), ones((N,))\n\titer = 0\n\txa = []\n\txa.append(x0)\n\tx = x0\n\t\n\twhile norm(dx,inf)>tol or norm(fx,inf)>tol and iter<=maxIt:\n\t\tfx, fpx = f(x), J(x)\n#\t\tdx = -fx/fpx\n\t\tdx = solve(fpx,-fx)\n\t\tx += dx\n\t\titer += 1\n\t\txa.append(x)\n\t\t\n\treturn xa\n", "meta": {"hexsha": "d04dce6e94a049d80f354aa9d5ddb18f2f19eef1", "size": 1130, "ext": "py", "lang": "Python", "max_stars_repo_path": "RootFinders.py", "max_stars_repo_name": "arleighdickerson/NumericalAnalysis", "max_stars_repo_head_hexsha": "7b995e73c2036066ed6c5441371a7ea10fb2bb84", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RootFinders.py", "max_issues_repo_name": "arleighdickerson/NumericalAnalysis", "max_issues_repo_head_hexsha": "7b995e73c2036066ed6c5441371a7ea10fb2bb84", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RootFinders.py", "max_forks_repo_name": "arleighdickerson/NumericalAnalysis", "max_forks_repo_head_hexsha": "7b995e73c2036066ed6c5441371a7ea10fb2bb84", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.1428571429, "max_line_length": 60, "alphanum_fraction": 0.4734513274, "include": true, "reason": "from numpy", "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075755433747, "lm_q2_score": 0.8918110432813419, "lm_q1q2_score": 0.8580181606942194}}
{"text": "# -*- coding: utf-8 -*-\nimport numpy as np\n# PCA\n# X: 观测矩阵\n# newX: 待转换的新样本\nX = np.array([[1,2,3],[2,3,5],[5,6,7],[2,3,2]])  # 4个变量,3个特征\nnewX = np.array([[2,1,3]])\n\n# 首先使用sklearn做PCA转换, 与下面进行对比\nfrom sklearn.decomposition import PCA\npca = PCA(n_components=3)\npca.fit(X)\nprint pca.transform(newX)\nradio = pca.explained_variance_ratio_\nprint(radio)\n\nprint (\"================\")\n#  自己实现\n# sklearn api均已行为一个样本, 下面计算使用列作为一个样本\nX = X.T\n##(1)计算协方差矩阵 :\n #   先把观测矩阵化为平均偏差形式: B = X - Xbar\n #   在计算平均偏差下的协方差矩阵: varX= B * B.T *(1/n).\nXbar = (1.0/4)*np.sum(X,axis=1,keepdims=True)\nprint Xbar\nB = X-Xbar # 平均偏差形式\nvarX = np.dot(B,B.T)*(1.0/4)  # 协方差矩阵 = (1/n)* B*B.T\n\n##(2)计算协方差矩阵的特征向量,后从大到小排列,得到解\nprint \"协方差矩阵的特征值:\"\neigVal = np.linalg.eig(varX)[0]  # 特征值 , 已按照从大到小排列 [  7.47698648e+00   1.56366740e-16   7.10513523e-01]\n# eigVal = eigVal.reshape(3,1)\nprint(eigVal)\nprint(\"第一个主成分占总方差的: %s\" % (eigVal[0]/np.sum(eigVal)))  # 对比radio[0]\np = np.linalg.eig(varX)[1]  # 特征向量矩阵\nindex = np.argsort(-eigVal) # 特征值从大到小排序的序号\nprint \"协方差矩阵特征向量: \"\np = p[:,index]  # 安札特征值从大到小排序后的特征向量重组矩阵\nprint p\n# 如下为p的每一列,即协方差矩阵对应的特征向量, 每个特征向量都是原观测矩阵的Feature的一个线性组合\n# sklearn中n_components属性为取前n特征向量, 对feature线性组合后的结果\n# [[ -5.29168529e-01  -4.69020967e-01  -7.07106781e-01]\n#  [ -5.29168529e-01  -4.69020967e-01   7.07106781e-01]\n# [ -6.63295813e-01   7.48357311e-01  -1.26760092e-16]]\n\nprint (\"my methods :\")   # 取得的值与sklearn一致\nprint np.dot(p.T,(Xbar-newX.T))\n# [[ 2.41662535]\n#  [-1.41421356]\n#  [ 0.47161626]]", "meta": {"hexsha": "925d93cc5fa942f7d3409c79b909e36945273b36", "size": 1463, "ext": "py", "lang": "Python", "max_stars_repo_path": "ml/datahandle/PCA.py", "max_stars_repo_name": "lj72808up/AI_handcraft", "max_stars_repo_head_hexsha": "31c48b91eccf2a64a9fb2a24f1829045c1252358", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ml/datahandle/PCA.py", "max_issues_repo_name": "lj72808up/AI_handcraft", "max_issues_repo_head_hexsha": "31c48b91eccf2a64a9fb2a24f1829045c1252358", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ml/datahandle/PCA.py", "max_forks_repo_name": "lj72808up/AI_handcraft", "max_forks_repo_head_hexsha": "31c48b91eccf2a64a9fb2a24f1829045c1252358", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.26, "max_line_length": 103, "alphanum_fraction": 0.6609706083, "include": true, "reason": "import numpy", "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298657, "lm_q2_score": 0.8918110418436166, "lm_q1q2_score": 0.8580181602799177}}
{"text": "import numpy as np\n\n\nclass Utils(object):\n    @staticmethod\n    def sigmoid(array):\n        return 1 / (1 + np.exp(array))\n\n    @staticmethod\n    def sigmoid_derivative(array):\n        sigmoid_value = 1 / (1 + np.exp(array))\n        return np.multiply(sigmoid_value, 1 - sigmoid_value)\n\ndef softmax(x):\n    \"\"\"\n    对输入x的每一行计算softmax。\n    该函数对于输入是向量（将向量视为单独的行）或者矩阵（M x N）均适用。\n    代码利用softmax函数的性质: softmax(x) = softmax(x + c)\n    参数:\n    x -- 一个N维向量，或者M x N维numpy矩阵.\n    返回值:\n    x -- 在函数内部处理后的x\n    \"\"\"\n    orig_shape = x.shape\n\n    # 根据输入类型是矩阵还是向量分别计算softmax\n    if len(x.shape) > 1:\n        # 矩阵\n        tmp = np.max(x, axis=1)  # 得到每行的最大值，用于缩放每行的元素，避免溢出\n        x -= tmp.reshape((x.shape[0], 1))  # 利用性质缩放元素\n        x = np.exp(x)  # 计算所有值的指数\n        tmp = np.sum(x, axis=1)  # 每行求和\n        x /= tmp.reshape((x.shape[0], 1))  # 求softmax\n    else:\n        # 向量\n        tmp = np.max(x)  # 得到最大值\n        x -= tmp  # 利用最大值缩放数据\n        x = np.exp(x)  # 对所有元素求指数\n        tmp = np.sum(x)  # 求元素和\n        x /= tmp  # 求somftmax\n    return x\n\n# def softmax(x):\n#     max = np.max(x)\n#     return np.exp(x - max) / sum(np.exp(x - max))\n\n\ndef der_softmax_cross_entropy(act_array, pre_array):\n    # y_act = onehot(num_class,label_array)\n    y_act = act_array\n    y_hat = pre_array\n    return y_hat - y_act\n\n\ndef sigmoid(x):\n    \"\"\"sigmoid函数\"\"\"\n    if x.any() >= 0:  # 对sigmoid函数的优化，避免了出现极大的数据溢出\n        return 1.0 / (1 + np.exp(-x))\n    else:\n        return np.exp(x) / (1 + np.exp(x))\n\n\ndef der_sigmoid(x):\n    \"\"\"sigmoid函数的导数\"\"\"\n    return sigmoid(x) * (1 - sigmoid(x))\n\n\ndef tanh(x):\n    \"\"\"tanh函数\"\"\"\n    return ((np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)))\n\n\ndef der_tanh(x):\n    \"\"\"tanh函数的导数\"\"\"\n    return 1 - tanh(x) * tanh(x)\n\n\ndef relu(x):\n    \"\"\"relu函数\"\"\"\n    temp = np.zeros_like(x)\n    if_bigger_zero = (x > temp)\n    return x * if_bigger_zero\n\n\ndef der_relu(x):\n    \"\"\"relu函数的导数\"\"\"\n    temp = np.zeros_like(x)\n    if_bigger_equal_zero = (x >= temp)\n    return if_bigger_equal_zero * np.ones_like(x)\n\n\ndef onehot(num_class, label_array):\n    return np.eye(num_class)[label_array]\n", "meta": {"hexsha": "7d29019d70158b246b288d5688bf2a1d52a2bb4b", "size": 2088, "ext": "py", "lang": "Python", "max_stars_repo_path": "Utils.py", "max_stars_repo_name": "yqstar/DeepLearningFromScratch", "max_stars_repo_head_hexsha": "dc03767fcf424d13e9b9f68362a05cfb141a5208", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-18T00:46:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-18T00:46:31.000Z", "max_issues_repo_path": "Utils.py", "max_issues_repo_name": "yqstar/DeepLearningFromScratch", "max_issues_repo_head_hexsha": "dc03767fcf424d13e9b9f68362a05cfb141a5208", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Utils.py", "max_forks_repo_name": "yqstar/DeepLearningFromScratch", "max_forks_repo_head_hexsha": "dc03767fcf424d13e9b9f68362a05cfb141a5208", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2127659574, "max_line_length": 64, "alphanum_fraction": 0.56848659, "include": true, "reason": "import numpy", "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135442, "lm_q2_score": 0.9111797136297299, "lm_q1q2_score": 0.8580161643057842}}
{"text": "import numpy as np\r\nimport nanalysis as na\r\nimport support\r\nimport matplotlib.pyplot as plt\r\nfrom support import BaseFunction\r\n\r\n\r\n \r\n\r\nclass Lotka_volterra( BaseFunction ):\r\n    \"\"\"\r\n    :param r1, r2 : float : intrinsic rate of natural increase\r\n    :param K1, K2 : float : carrying capacity\r\n    :param a      : float : \r\n    :param b      : float :\r\n    :return dx/dt, dy/dt : float\r\n    \"\"\"\r\n    def __init__( self, r1 = 1, r2 = 2,  K1 = 80, K2 = 70, a = 0.7, b = 1.1 ):\r\n        \r\n        self.r1 = r1\r\n        self.r2 = r2\r\n        self.K1 = K1\r\n        self.K2 = K2\r\n        self.a = a\r\n        self.b = b\r\n\r\n       \r\n\r\n    def get_values( self, x, y, t ):\r\n\r\n        return self.r1 * x * ( 1 - ( x + self.a * y ) /self.K1 ), self.r2 * y * ( 1 - (self.b *  x + y ) / self.K2  )\r\n    \r\n    def get_linelist( self ):\r\n\r\n        return  [[ -1 / self.a, self.K1 / self.a ], [ -self.b, self.K2 ] ]\r\n    \r\n    \r\n\r\nclass Fujita_model( BaseFunction ):\r\n    \r\n    def __init__( self,  r = 0.1, a = 0.3, b = 0.1, c = 0.3 ):\r\n        \r\n        self.r = r\r\n        self.a = a\r\n        self.b = b\r\n        self.c = c\r\n\r\n        \r\n\r\n    def get_values( self, x, y, t ):\r\n\r\n        return self.r * x * ( 1 - self.a * x - self.b * y), -self.c * y + x \r\n    \r\n    def get_linelist( self ):\r\n\r\n        return [ [ - self.a / self.b, 1 / self.b ], [ 1 / self.c, 0 ] ]\r\n\r\n    \r\n\r\nif __name__ == '__main__':\r\n\r\n    \r\n    ps = support.get_base_args()\r\n    args = ps.parse_args()\r\n\r\n    graph_n = args.equation_number\r\n    ad = args.argdict\r\n    \r\n    sp   = args.spoint\r\n    ep   = args.epoint\r\n\r\n    hl   = args.hline\r\n    vl   = args.vline\r\n    llist  =  args.line \r\n    pp   =  args.pointplot \r\n    initial_value = args.initial_value\r\n     \r\n    saveoff = support.offsaving( args.savefigoff )\r\n    \r\n    graph = { 1: Lotka_volterra , 4: Fujita_model}\r\n    \r\n    if ad:\r\n        function = graph[ graph_n ](**ad)\r\n    else:\r\n        function = graph[ graph_n ]()\r\n    linelist =  function.get_linelist()\r\n    \r\n    if llist:\r\n        linelist.append(llist)\r\n    \r\n    \r\n    t, xpoints, ypoints = function.get_values_rungekutta( sp = sp, ep = ep, initial_value = initial_value )\r\n    \r\n    na.graph_plot( t, xpoints  ,ypoints , chapter = 2, function = function, hlines = hl, vlines = vl, linelist = linelist , savefigOn = saveoff, graph_n = graph_n, N = 1000, pointplot = pp)\r\n", "meta": {"hexsha": "f28b755a11b5eaaf357cd7ae55b10c8b6757b312", "size": 2363, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/chapter2.py", "max_stars_repo_name": "yosuke-tt/introduction_to_mathematical_biology", "max_stars_repo_head_hexsha": "1e7c8a40a7fd998dd0c00ef84d3d0fa41d3650fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/chapter2.py", "max_issues_repo_name": "yosuke-tt/introduction_to_mathematical_biology", "max_issues_repo_head_hexsha": "1e7c8a40a7fd998dd0c00ef84d3d0fa41d3650fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/chapter2.py", "max_forks_repo_name": "yosuke-tt/introduction_to_mathematical_biology", "max_forks_repo_head_hexsha": "1e7c8a40a7fd998dd0c00ef84d3d0fa41d3650fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8736842105, "max_line_length": 190, "alphanum_fraction": 0.5116377486, "include": true, "reason": "import numpy", "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135442, "lm_q2_score": 0.9111797039819735, "lm_q1q2_score": 0.8580161552209342}}
{"text": "\r\n\"\"\"\r\nSupport library for computing nonlinearities and derivatives.\r\n\r\nRequires numpy.\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\n\r\ndef sigmoid(X):\r\n    \"\"\"\r\n    INPUT:\r\n    X: a numpy matrix \r\n    \r\n    OUTPUT:\r\n    A numpy matrix after element-wise application of sigmoid\r\n    \"\"\"\r\n    Y = 1.0 / (1.0 + np.exp(-X))\r\n    return Y\r\n\r\ndef deriv_sigmoid(X):\r\n    \"\"\"\r\n    INPUT:\r\n    X: a numpy matrix \r\n    \r\n    OUTPUT:\r\n    A numpy matrix giving the element-wise derivation of sigmoid(X) wrt X\r\n    \"\"\"\r\n    Y = (1.0 - sigmoid(X)) * sigmoid(X)\r\n    return Y\r\n\r\ndef positivecosine(X):\r\n    \"\"\"\r\n    INPUT:\r\n    X: a numpy matrix \r\n    \r\n    OUTPUT:\r\n    A numpy matrix after element-wise application of cosine\r\n    \"\"\"\r\n    Y = 1.0 + np.cos(X)\r\n    return Y\r\n\r\ndef deriv_positivecosine(X):\r\n    \"\"\"\r\n    INPUT:\r\n    X: a numpy matrix \r\n    \r\n    OUTPUT:\r\n    A numpy matrix giving the element-wise derivation of cosine(X) wrt X\r\n    \"\"\"\r\n    Y = -np.sin(X)\r\n    return Y\r\n\r\n\r\ndef positivesine(X):\r\n    \"\"\"\r\n    INPUT:\r\n    X: a numpy matrix \r\n    \r\n    OUTPUT:\r\n    A numpy matrix after element-wise application of sine\r\n    \"\"\"\r\n    Y = 1.0 + np.sin(X)\r\n    return Y\r\n\r\ndef deriv_positivesine(X):\r\n    \"\"\"\r\n    INPUT:\r\n    X: a numpy matrix \r\n    \r\n    OUTPUT:\r\n    A numpy matrix giving the element-wise derivation of sin(X) wrt X\r\n    \"\"\"\r\n    Y = np.cos(X)\r\n    return Y\r\n\r\ndef negexp(X):\r\n    \"\"\"\r\n    INPUT:\r\n    X: a numpy matrix \r\n    \r\n    OUTPUT:\r\n    A numpy matrix after element-wise application of sine\r\n    \"\"\"\r\n    Y = np.exp(-X)\r\n    return Y\r\n\r\ndef deriv_negexp(X):\r\n    \"\"\"\r\n    INPUT:\r\n    X: a numpy matrix \r\n    \r\n    OUTPUT:\r\n    A numpy matrix giving the element-wise derivation of sin(X) wrt X\r\n    \"\"\"\r\n    Y = -np.exp(-X)\r\n    return Y\r\n\r\n\r\n\r\ndef softReLU(X,epsilon=0):\r\n    \"\"\"\r\n    INPUT:\r\n    X: a numpy matrix \r\n    \r\n    OUTPUT:\r\n    A numpy matrix after element-wise application of rectifier linear unit\r\n    \"\"\"\r\n    Y = X.copy()\r\n    Y[Y<0] = epsilon\r\n    return Y\r\n\r\ndef deriv_softReLU(X,epsilon=0):\r\n    \"\"\"\r\n    INPUT:\r\n    X: a numpy matrix \r\n    \r\n    OUTPUT:\r\n    A numpy matrix giving the element-wise derivation of softReLU(X) wrt X\r\n    \"\"\"\r\n    Y = np.ones(X.shape)\r\n    Y[X<0] = 0\r\n    return Y\r\n\r\n\r\ndef softabsolute(X, epsilon=1e-8):\r\n    \"\"\"\r\n    INPUT:\r\n    X: a numpy matrix\r\n    epsilon: epsilon machine to compute soft-absolute value \r\n    \r\n    OUTPUT:\r\n    A numpy matrix after element-wise application of soft-absolute value\r\n    \"\"\"\r\n    Y = np.sqrt(X**2 + epsilon) \r\n    return Y\r\n\r\ndef deriv_softabsolute(X, epsilon=1e-8):\r\n    \"\"\"\r\n    INPUT:\r\n    X: a numpy matrix\r\n    epsilon: epsilon machine to compute soft-absolute value \r\n    \r\n    OUTPUT:\r\n    A numpy matrix giving the element-wise derivation of softabsolute(X) wrt X\r\n    \"\"\"\r\n    Y = X / softabsolute(X, epsilon)\r\n    return Y", "meta": {"hexsha": "5adbf989a508c5567f799c21116d18721ee0bc13", "size": 2833, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/nonlinearities.py", "max_stars_repo_name": "EldarFeatel/PSF", "max_stars_repo_head_hexsha": "e19f2d922231b191bbbbeef1c86f411e1b9284a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-24T04:41:37.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-24T04:41:37.000Z", "max_issues_repo_path": "utils/nonlinearities.py", "max_issues_repo_name": "EldarFeatel/PSF", "max_issues_repo_head_hexsha": "e19f2d922231b191bbbbeef1c86f411e1b9284a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/nonlinearities.py", "max_forks_repo_name": "EldarFeatel/PSF", "max_forks_repo_head_hexsha": "e19f2d922231b191bbbbeef1c86f411e1b9284a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0134228188, "max_line_length": 79, "alphanum_fraction": 0.5538298623, "include": true, "reason": "import numpy", "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811631528337, "lm_q2_score": 0.8887588038050467, "lm_q1q2_score": 0.8579910077796371}}
{"text": "import numpy as np\n\ndef dichoto(function, p0, max_depth=10,  eps=1e-10):\n    a,b=p0\n    i=0\n    while i < max_depth:\n        c=0.5*(a+b) \n        if np.abs(function(c))<=eps:\n            return c\n        if(function(c)<0):\n            a=c  \n        if(function(c)>0):\n            b=c\n        i=i+1\n    return c\n\n\n# Find the the golden ratio\nf = lambda x : x**2-1-x\nx = dichoto(f, (1, 2))\nprint(\"The golden ratio is : {}\".format(x))\n\n# Find the the solution\nf = lambda x : np.tan(x)-1\nx = dichoto(f, (0.5, 3.15/4), )\nprint(\"The solution to tan(x)=1 is : {}\".format(x))\n\n# Find the the solution\nf = lambda x : (x-2)**2\nx = dichoto(f, (1, 3), )\nprint(\"The solution to (x-2)^2=0 is : {}\".format(x))", "meta": {"hexsha": "3f180df87fafc8c8cca54dec787dc460820829d7", "size": 694, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/dichoto.py", "max_stars_repo_name": "ParadiseLab/Numerical_Methods", "max_stars_repo_head_hexsha": "5f6c86503ded6b77c36ee2103eee683deea63d3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/dichoto.py", "max_issues_repo_name": "ParadiseLab/Numerical_Methods", "max_issues_repo_head_hexsha": "5f6c86503ded6b77c36ee2103eee683deea63d3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/dichoto.py", "max_forks_repo_name": "ParadiseLab/Numerical_Methods", "max_forks_repo_head_hexsha": "5f6c86503ded6b77c36ee2103eee683deea63d3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3870967742, "max_line_length": 52, "alphanum_fraction": 0.5273775216, "include": true, "reason": "import numpy", "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811621568289, "lm_q2_score": 0.8887588023318196, "lm_q1q2_score": 0.8579910054722034}}
{"text": "import numpy as np\n#computes the logistic regression log-likelihood for data z and parameter th\n#input: z = N x D numpy array, th = length D numpy array\n#output: length N numpy array of log_likelihoods\ndef log_likelihood(z, th):\n  if len(z.shape) == 1:\n    m = -(th*z).sum()\n    if m < 100:\n      m = -np.log1p(np.exp(m))\n    else:\n      m = -m\n    return m \n  else:\n    m = -(th*z).sum(axis=1)\n    idcs = m < 100\n    m[idcs] = -np.log1p(np.exp(m[idcs]))\n    m[np.logical_not(idcs)] = -m[np.logical_not(idcs)]\n    return m\n\n#computes the gradient of the logistic regression log-likelihood\n# z is data, one row per vector; th is the parameter\n#input: z = N x D numpy array, th = length D numpy array, idx = optional gradient component index\n#output: (if idx = None): N x D array of gradients  (if idx = integer) N x 1 array of gradient components\ndef grad_log_likelihood(z, th, idx=None):\n  if len(z.shape) == 1:\n    m = -(th*z).sum()\n    if m < 100:\n      m = np.exp(m)/(1.+np.exp(m))\n    else:\n      m = 1.\n    return m*z\n  else:\n    m = -(th*z).sum(axis=1)\n    idcs = m < 100\n    m[idcs] = np.exp(m[idcs])/(1.+np.exp(m[idcs]))\n    m[np.logical_not(idcs)] = 1.\n    if idx is None:\n      return m[:, np.newaxis]*z\n    return m*z[:, idx]\n\n#computes the log prior for parameter th\n#input: th = length D numpy array\n#output: log prior density value, scalar\ndef log_prior(th):\n  return -0.5*th.shape[0]*np.log(2.*np.pi) - 0.5*(th**2).sum()\n\n#computes the log prior gradient for parameter th\n#input: th = length D numpy array\n#output: length D numpy gradient array\ndef grad_log_prior(th):\n  return -th\n\n#computes the log joint probability for data z and parameter th, where the data are weighted by wts\n#input: Z = N x D numpy array, th = length D numpy array, wts = length N numpy array of nonnegative values\n#output: weighted log joint, scalar\ndef log_joint(Z, th, wts):\n  return (wts*log_likelihood(Z, th)).sum() + log_prior(th)\n\n#same as above; outputs length D numpy array gradient\ndef grad_log_joint(z, th, wts):\n  return grad_log_prior(th) + (wts[:, np.newaxis]*grad_log_likelihood(z, th)).sum(axis=0)\n\n#same as above; outputs D x D numpy array Hessian\ndef hess_log_joint(z, th):\n  es = np.exp(-(th*z).sum(axis=1))\n  H_log_like = -(z.T).dot((es/(1.+es)**2)[:, np.newaxis]*z)\n  H_log_prior = -np.eye(th.shape[0])\n  return H_log_like + H_log_prior\n\n\n", "meta": {"hexsha": "3042632cd9c59e54db28c0d0350db04b7e1390d7", "size": 2350, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/simple_logistic_regression/model.py", "max_stars_repo_name": "raifthenerd/bayesian-coresets", "max_stars_repo_head_hexsha": "6fc31ba4f2c46a3a1d4b04f035a38f9b852c50bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-30T15:56:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-30T15:56:34.000Z", "max_issues_repo_path": "examples/simple_logistic_regression/model.py", "max_issues_repo_name": "raifthenerd/bayesian-coresets", "max_issues_repo_head_hexsha": "6fc31ba4f2c46a3a1d4b04f035a38f9b852c50bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/simple_logistic_regression/model.py", "max_forks_repo_name": "raifthenerd/bayesian-coresets", "max_forks_repo_head_hexsha": "6fc31ba4f2c46a3a1d4b04f035a38f9b852c50bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0985915493, "max_line_length": 106, "alphanum_fraction": 0.6553191489, "include": true, "reason": "import numpy", "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811621568289, "lm_q2_score": 0.8887587934924569, "lm_q1q2_score": 0.8579909969388492}}
{"text": "import numpy as np \n\nx = np.array([1,2,3])\ny = np.array([4,5,6])\nprint(x,\"\\n\", y)\n\n#Different ways to get the dot product\n\n#1\nimport numpy as np\n\nx = np.array([1,2,3])\ny = np.array([4,5,6])\ndot_Product = 0\n\nfor i in range (3): \n  dot_Product += x[i]*y[i]\nprint(dot_Product)\n\n\n#2\ndot = 0\nfor i , j in zip(x,y): \n  dot += (i*j)\nprint(\"\\nDot Product = \", dot)\n\n\n#3\nprint(\"\\nDot Product = \", sum(x*y))\n\n#4\nprint(\"\\nDot Product = \", np.dot(x,y))\n\n\n#calculating The angle between two vectors: \n\n# dot product = magnitue * magnitude * cos of angle\n\n\n#2\ncosangle = np.dot(x,y) / (np.linalg.norm(x) * np.linalg.norm(y))\nprint(\"\\nangle =\",np.arccos(cosangle))\n\n#Creating an ideneity Matrix\nprint(np.eye((3)))\n", "meta": {"hexsha": "5dd35344d42e83ad9691131cf59cc7ac2eb2fdaa", "size": 699, "ext": "py", "lang": "Python", "max_stars_repo_path": "1.Numpy/numpy_linearalgebra.py", "max_stars_repo_name": "utkrist-karky/Deep-Learning-Prerequisite", "max_stars_repo_head_hexsha": "d56993af21babaf36893b7b19a3ba85e48440e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-27T20:37:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T20:37:05.000Z", "max_issues_repo_path": "1.Numpy/numpy_linearalgebra.py", "max_issues_repo_name": "utkrist-karky/Deep-Learning-Prerequisite", "max_issues_repo_head_hexsha": "d56993af21babaf36893b7b19a3ba85e48440e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1.Numpy/numpy_linearalgebra.py", "max_forks_repo_name": "utkrist-karky/Deep-Learning-Prerequisite", "max_forks_repo_head_hexsha": "d56993af21babaf36893b7b19a3ba85e48440e91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-08T14:45:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T14:45:33.000Z", "avg_line_length": 15.1956521739, "max_line_length": 64, "alphanum_fraction": 0.6194563662, "include": true, "reason": "import numpy", "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158575, "lm_q2_score": 0.8962513786759491, "lm_q1q2_score": 0.8579615480400917}}
{"text": "import numpy as np\n\ndef Brownian(seed, N):\n    \"\"\"Generates Brownian Motion.\n    :param seed:   random seed to use\n    :param N:      increments\n    :return W:     brownian motion\n    :return b:     brownian increments\n    \"\"\"\n    np.random.seed(seed)                         \n    dt = 1./N\n    b = np.random.normal(0., 1., int(N))*np.sqrt(dt)\n    W = np.cumsum(b)\n    return W, b\n\ndef GBM(So, mu, sigma, W, N):    \n    \"\"\"Generates Geometric Brownian Motion.\n    :param So:       starting price\n    :param mu:       drift coefficient\n    :param sigma:    diffusion coefficient\n    :param W:        Brownian Motion\n    :param N:        increments to predict - **N = len(W)**\n    :return S:       Geometric Brownian Motion (S(t))\n    :return t:       all time-steps\n    \"\"\"\n    t = np.linspace(0.,1.,N+1)\n    S = []\n    S.append(So)\n    for i in range(1,int(N+1)):\n        drift = (mu - 0.5 * sigma**2) * t[i]\n        diffusion = sigma * W[i-1]\n        S_temp = So*np.exp(drift + diffusion)\n        S.append(S_temp)\n    return S, t\n\ndef GBM_step(mu, S, N, sigma, W):\n    \"\"\"Calculates dS over time T\n    :param mu: drift\n    :param S:  true price - an iterable?\n    :param N:  \n    :param sigma: diffusion\n    :param W: brownian\n    :return dS: GBM step\n    \"\"\"\n    dt = 1./N\n    dS = []\n    for i in range(1,int(N)):\n        dS.append(mu*S[i]*dt + sigma*S[i]*W[i])\n    S = np.cumsum(dS)\n    return S\n\ndef sentiment_GBM(P, S, mu, sigma, alpha, W, N):\n    \"\"\"Applies weighted sentiment to GBM\n    :param :\n    :return :\n    \"\"\"\n    dt = 1./N\n    dP = []\n    for i in range(int(N)):\n        dP.append(mu*P[i]*dt + sigma*P[i]*W[i] + alpha*S[i])\n    P = np.cumsum(dP)\n    return P\n\ndef daily_returns(close, N):\n    \"\"\"Calculates daily returns, then drift and diffusion from those returns.\n    :param close:       iterable of closing prices as [n, price]\n    :param N:           increments to predict\n    :return returns:    daily returns\n    :return mu:         drift\n    :return sigma:      diffusion\n    \"\"\"\n    returns = []\n    for i in range(0, len(close)-1):\n        today = close[i+1]\n        yesterday = close[i]\n        r = (today - yesterday) / yesterday\n        returns.append(r)\n    mu = np.mean(returns)*(N*1.) # drift\n    sigma = np.std(returns)*np.sqrt(N*1.)#diffusion\n    return mu, sigma\n\n", "meta": {"hexsha": "09b3761018b1cc5b7d31315a130425ca48b2b5f1", "size": 2300, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/models/gbm.py", "max_stars_repo_name": "brandonmalexander/btc_prediction", "max_stars_repo_head_hexsha": "f5ed6292ca300f0d62f2ee2f1a9c46e55e731e79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/models/gbm.py", "max_issues_repo_name": "brandonmalexander/btc_prediction", "max_issues_repo_head_hexsha": "f5ed6292ca300f0d62f2ee2f1a9c46e55e731e79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/gbm.py", "max_forks_repo_name": "brandonmalexander/btc_prediction", "max_forks_repo_head_hexsha": "f5ed6292ca300f0d62f2ee2f1a9c46e55e731e79", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0487804878, "max_line_length": 77, "alphanum_fraction": 0.5469565217, "include": true, "reason": "import numpy", "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.8962513738264114, "lm_q1q2_score": 0.8579615423053626}}
{"text": "import sys\r\nsys.path.append('../../utils')\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport scipy.optimize as opt\r\nimport data_preprocessing as Preprocessing\r\nfrom pandas.io.parsers import read_csv\r\n\r\n\r\ndef load_csv(file_name):\r\n    values = read_csv(file_name, header=None).values\r\n\r\n    return values.astype(float)\r\n\r\ndef gradient(thetas, XX, Y):\r\n    H = h(thetas, XX)\r\n    grad = (1/len(Y)) * np.dot(XX.T, H-Y)\r\n\r\n    return grad\r\n\r\ndef cost(thetas, X, Y):\r\n    m = np.shape(X)[0]\r\n    H = h(thetas, X)\r\n\r\n    c = (-1/(len(X))) * (np.dot(Y.T, np.log(H)) + np.dot((1-Y).T, np.log(1-H)))\r\n\r\n    return c\r\n\r\ndef sigmoid(Z):\r\n    return 1/(1 + np.e**(-Z))\r\n\r\ndef h(thetas, X):\r\n    return np.c_[sigmoid(np.dot(X, thetas))]\r\n\r\ndef show_border(thetas, X, Y):\r\n    x1_min, x1_max = X[:, 1].min(), X[:, 1].max()\r\n    x2_min, x2_max = X[:, 2].min(), X[:, 2].max()\r\n\r\n    xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max),\r\n    np.linspace(x2_min, x2_max))\r\n\r\n    H = sigmoid(np.c_[np.ones((xx1.ravel().shape[0], 1)),\r\n    xx1.ravel(),\r\n    xx2.ravel()].dot(thetas))\r\n\r\n    H = H.reshape(xx1.shape)\r\n\r\n    plt.figure()\r\n\r\n    positives = np.where(Y == 1)\r\n    negatives = np.where(Y == 0)\r\n    plt.scatter(X[positives, 1], X[positives, 2], marker='+', color='blue')\r\n    plt.scatter(X[negatives, 1], X[negatives, 2], color='red')\r\n\r\n    plt.contour(xx1, xx2, H, [0.5], linewidths=1, colors='b')\r\n    plt.savefig(\"images/regresion_logistic_border.png\")\r\n    plt.show()\r\n    plt.close()\r\n\r\ndef evaluate(thetas, X, Y):\r\n    result = h(thetas, X)\r\n    passed_missed = np.logical_and((result >= 0.5), (Y == 0)).sum()\r\n    failed_missed = np.logical_and((result < 0.5), (Y == 1)).sum()\r\n\r\n    errors = (passed_missed + failed_missed)\r\n\r\n    return (result.shape[0] - errors) / (result.shape[0])\r\n\r\ndef train(X, Y, verbose = True):\r\n    XOnes = Preprocessing.addInitialOnes(X)\r\n    thetas = np.zeros((XOnes.shape[1], 1), dtype=float)\r\n    result = opt.fmin_tnc(func=cost, x0=thetas, fprime=gradient, args=(XOnes, Y), disp = 5 if verbose else 0)\r\n    thetas = result[0]\r\n\r\n    return thetas\r\n\r\ndef main():\r\n    # DATA PREPROCESSING\r\n    data = load_csv(\"data/ex2data1.csv\")\r\n    X, Y, m, n = Preprocessing.separate_data(data)\r\n    thetas = train(X, Y)\r\n\r\n    print(\"Accuracy: \", evaluate(thetas, X, Y)*100, \"%\")\r\n    show_border(thetas, X, Y)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n", "meta": {"hexsha": "ddb34a83f4f084685b8257331a3b52a300e47333", "size": 2389, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/regression/regresion_logistic.py", "max_stars_repo_name": "dimart10/machine-learning", "max_stars_repo_head_hexsha": "0f33bef65a9335c0f7fed680f1112419bae8fabc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/regression/regresion_logistic.py", "max_issues_repo_name": "dimart10/machine-learning", "max_issues_repo_head_hexsha": "0f33bef65a9335c0f7fed680f1112419bae8fabc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/regression/regresion_logistic.py", "max_forks_repo_name": "dimart10/machine-learning", "max_forks_repo_head_hexsha": "0f33bef65a9335c0f7fed680f1112419bae8fabc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5444444444, "max_line_length": 110, "alphanum_fraction": 0.5914608623, "include": true, "reason": "import numpy,import scipy", "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158575, "lm_q2_score": 0.8962513717480382, "lm_q1q2_score": 0.8579615414081564}}
{"text": "import matplotlib.pyplot as mplt\nimport numpy as np\n\ndef f(x):\n    return x**2.0\n\ndef oneDGradient(vals, dx):\n\n    n = len(vals)\n    grad = [0.0] * n\n\n    #forward difference for outer bounds\n    grad[0] = (vals[1] - vals[0]) / dx\n    for i in range(1, n - 1):\n        #central difference now that data is available\n        grad[i] = (vals[i + 1] - vals[i - 1]) / (2.0 * dx)\n    #forward difference for outer bounds\n    grad[n - 1] = (vals[n - 1] - vals[n - 2]) / dx\n\n    return grad\n\n#########################################\n\n#dimensions\nNx = 21;       # Number of X-grid points\ndx = 1.0;      # x coordinate grid spacing \n\n########## sanity check against numpy ##\n\n#establish X axis\nX = np.arange(0, Nx, dx)\n#compute function LUT\nfx = X**2.0\n#compute derivative in 1D\ndFdX = np.gradient(fx, dx)\n\n########## my implementation ##########\n\ntestData = [0.0] * Nx \n\nx = 0\nfor i in range(Nx):\n    #function LUT\n    testData[i] = f(x)\n    #x axis\n    x += dx\n\n#computer gradient\ngradientData = oneDGradient( testData, dx )\n\n#########################################\n \nfig, (ax1, ax2) = mplt.subplots(2)\n\nax1.plot(testData, label = 'my implementation')\nax1.plot(gradientData)\nax1.legend( bbox_to_anchor = (1.0, 1), loc = 'upper right' )\n\nax2.plot(fx, label = 'numpy implementation')\nax2.plot(dFdX)\nax2.legend( bbox_to_anchor = (1.0, 1), loc = 'upper right' )\n\nmplt.show()\n\n", "meta": {"hexsha": "0381667bc30ab05e11999b9a3f7cafd6987cae5b", "size": 1368, "ext": "py", "lang": "Python", "max_stars_repo_path": "simplePhysics/DiscreteGradient/1D/oneDimensionalGradient.py", "max_stars_repo_name": "shmillo/SimplePythonExamples", "max_stars_repo_head_hexsha": "1ed23af998220448c510cebc03af5ccdbd37a131", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simplePhysics/DiscreteGradient/1D/oneDimensionalGradient.py", "max_issues_repo_name": "shmillo/SimplePythonExamples", "max_issues_repo_head_hexsha": "1ed23af998220448c510cebc03af5ccdbd37a131", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simplePhysics/DiscreteGradient/1D/oneDimensionalGradient.py", "max_forks_repo_name": "shmillo/SimplePythonExamples", "max_forks_repo_head_hexsha": "1ed23af998220448c510cebc03af5ccdbd37a131", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0461538462, "max_line_length": 60, "alphanum_fraction": 0.5687134503, "include": true, "reason": "import numpy", "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.8962513703624558, "lm_q1q2_score": 0.8579615389893949}}
{"text": "# Takes in a list of Y values\n# Returns a list of 0's and 1's\n# 1 means the matching value in Y is an outlier\nimport numpy as np\n\n\ndef zscore(points, threshold=3):\n    dataset = [y for x, y in points]\n    mean = np.mean(dataset)\n    std = np.std(dataset)\n    outliers = []\n    for y in dataset:\n        z_score = (y - mean) / std\n        if np.abs(z_score) > threshold:\n            outliers.append(1)\n        else:\n            outliers.append(0)\n    return outliers\n\n\n# inter quartile range\ndef IQR(points):\n    dataset = [y for x, y in points]\n    outliers = []\n    sorted_data = sorted(dataset)\n    q1, q3 = np.percentile(sorted_data, [25, 75])\n    iqr = q3 - q1\n    lower_bound = q1 - (1.5 * iqr)\n    upper_bound = q3 + (1.5 * iqr)\n\n    for data in dataset:\n        if data > upper_bound or data < lower_bound:\n            outliers.append(1)\n        else:\n            outliers.append(0)\n    return outliers\n\n\ndef _seperate(data, outlier_list):\n    output = ([], [])\n    for e, outlier in zip(data, outlier_list):\n        if outlier == 1:\n            output[1].append(e)\n        else:\n            output[0].append(e)\n    return output\n\n\n# Take points as a list of pairs\n# returns a pair of lists with ([good points],[outliers])\ndef calc_outliers(points, method):\n    if \"zscore\" in method:\n        return _seperate(points, zscore(points))\n    elif \"IQR\" in method:\n        return _seperate(points, IQR(points))\n    return (points, [])\n", "meta": {"hexsha": "15a11bf741c856ad183f2efdf8544e12da8ed5a7", "size": 1437, "ext": "py", "lang": "Python", "max_stars_repo_path": "our_tools/outliers.py", "max_stars_repo_name": "filipp-g/magneto", "max_stars_repo_head_hexsha": "06be4badd37d412be094e917bb44b8ab15ae79b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "our_tools/outliers.py", "max_issues_repo_name": "filipp-g/magneto", "max_issues_repo_head_hexsha": "06be4badd37d412be094e917bb44b8ab15ae79b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-10-20T17:11:40.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-20T17:13:13.000Z", "max_forks_repo_path": "our_tools/outliers.py", "max_forks_repo_name": "filipp-g/magneto", "max_forks_repo_head_hexsha": "06be4badd37d412be094e917bb44b8ab15ae79b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-19T01:52:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-19T01:52:20.000Z", "avg_line_length": 25.2105263158, "max_line_length": 57, "alphanum_fraction": 0.5929018789, "include": true, "reason": "import numpy", "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777975782054, "lm_q2_score": 0.8962513648201267, "lm_q1q2_score": 0.8579615325914716}}
{"text": "#! /usr/bin/env python\nimport numpy as np\n\n\ndef multi_variate_normal(x, mu, sigma=None, log=True, inv_sigma=None):\n\t\"\"\"\n\tMultivariatve normal distribution PDF\n\n\t:param x: data, np.array([nb_samples, nb_dim])\n\t:param mu: mean, np.array([nb_dim])\n\t:param sigma: covariance matrix, np.array([nb_dim, nb_dim])\n\t:param log: compute the loglikelihood if true\n\t:return: pdf of the data for the given Gaussian distribution\n\t\"\"\"\n\tdx = x - mu\n\tif sigma.ndim == 1:\n\t\tsigma = sigma[:, None]\n\t\tdx = dx[:, None]\n\t\tinv_sigma = np.linalg.inv(sigma) if inv_sigma is None else inv_sigma\n\t\tlog_lik = -0.5 * np.sum(np.dot(dx, inv_sigma) * dx, axis=1) - 0.5 * np.log(np.linalg.det(2 * np.pi * sigma))\n\telse:\n\t\tinv_sigma = np.linalg.inv(sigma) if inv_sigma is None else inv_sigma\n\t\tlog_lik = -0.5 * np.einsum('...j,...j', dx, np.einsum('...jk,...j->...k', inv_sigma, dx)) - 0.5 * np.log(np.linalg.det(2 * np.pi * sigma))\n\n\treturn log_lik if log else np.exp(log_lik)\n", "meta": {"hexsha": "e448f941e3c9f7481eb3ea2ac38ae599ff9c9d1b", "size": 944, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/utils.py", "max_stars_repo_name": "NoemieJaquier/TME", "max_stars_repo_head_hexsha": "5ac5c008364c322ae57b9e4156e6582ec5137786", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-29T16:45:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:45:45.000Z", "max_issues_repo_path": "utils/utils.py", "max_issues_repo_name": "NoemieJaquier/TME", "max_issues_repo_head_hexsha": "5ac5c008364c322ae57b9e4156e6582ec5137786", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/utils.py", "max_forks_repo_name": "NoemieJaquier/TME", "max_forks_repo_head_hexsha": "5ac5c008364c322ae57b9e4156e6582ec5137786", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3076923077, "max_line_length": 140, "alphanum_fraction": 0.6684322034, "include": true, "reason": "import numpy", "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138118632621, "lm_q2_score": 0.8774767826757123, "lm_q1q2_score": 0.8579211700113819}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nThis problem was asked by Facebook.\r\n\r\nThere is an N by M matrix of zeroes. Given N and M, write a function to count the number of ways of starting at the top-left corner and getting to the bottom-right corner. You can only move right or down.\r\n\r\nFor example, given a 2 by 2 matrix, you should return 2, since there are two ways to get to the bottom-right:\r\n\r\nRight, then down\r\nDown, then right\r\nGiven a 5 by 5 matrix, there are 70 ways to get to the bottom-right.\r\n\"\"\"\r\n\r\nfrom scipy.special import comb\r\n\r\ndef f(m,n):        \r\n    k=min(m-1,n-1) #since matrix is transposable, can also use max w/ same result.\r\n    n=(m-1)+(n-1)\r\n    print(comb(n,k))\r\n\r\n\r\n#test:\r\n\r\nf(2,2)\r\n#2\r\nf(5,5)\r\n#70\r\n\r\n\r\n#test transposition\r\nf(10,4)\r\n#220\r\n\r\nf(4,10)\r\n#220\r\n\r\n#solve time : 5 minutes", "meta": {"hexsha": "c5aa546547b64fa9434bdafcdb383ff7f08fa140", "size": 804, "ext": "py", "lang": "Python", "max_stars_repo_path": "DCP_62.py", "max_stars_repo_name": "sgorlick/dailycodingproblem.com-solns", "max_stars_repo_head_hexsha": "b7e006070fab3c69b0e6a95bd1ce51e642d7f0a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DCP_62.py", "max_issues_repo_name": "sgorlick/dailycodingproblem.com-solns", "max_issues_repo_head_hexsha": "b7e006070fab3c69b0e6a95bd1ce51e642d7f0a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DCP_62.py", "max_forks_repo_name": "sgorlick/dailycodingproblem.com-solns", "max_forks_repo_head_hexsha": "b7e006070fab3c69b0e6a95bd1ce51e642d7f0a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7297297297, "max_line_length": 205, "alphanum_fraction": 0.6504975124, "include": true, "reason": "from scipy", "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611608990299, "lm_q2_score": 0.8933094110250331, "lm_q1q2_score": 0.8578996630140295}}
{"text": "# Daniel J. Rodriguez\n# https://github.com/danieljoserodriguez\n\nimport numpy as np\n\n\n# A straight line function where activation is proportional to input\n# ( which is the weighted sum from neuron ).\n\n# In mathematics, an identity function, also called an identity relation or\n# identity map or identity transformation, is a function that always returns\n# the same value that was used as its argument.\n#\n# https://en.wikipedia.org/wiki/Identity_function\ndef identity(x):\n    return x\n\n\n# derivative identity\ndef d_identity(x):\n    return 1.0\n\n\n# bent identity\n#\n# The Heaviside step function, or the unit step function, usually denoted by\n# H or θ (but sometimes u, 1 or 𝟙), is a discontinuous function, named after\n# Oliver Heaviside (1850–1925), whose value is zero for negative arguments\n# and one for positive arguments\ndef bent_identity(x):\n    return ((np.sqrt(((x ** 2.0) + 1.0)) - 1.0) / 2.0) + x\n\n\n# derivative bent identity\ndef d_bent_identity(x):\n    return (x / (2.0 * np.sqrt((x ** 2.0) + 1.0))) + 1.0\n\n\n# also called heaviside step\n#\n# https://en.wikipedia.org/wiki/Heaviside_step_function\ndef binary_step(x):\n    return 1.0 if x >= 0.0 else 0.0\n\n\ndef perceptron(weights, bias, inputs):\n    return 1.0 if (np.dot(weights, inputs) + bias) > 0.0 else 0.0\n\n\ndef smooth_perceptron(weights, bias, inputs):\n    return np.dot(weights, inputs) + bias\n\n\n# Sigmoid takes a real value as input and outputs another value between 0 and 1.\n# It’s easy to work with and has all the nice properties of activation functions:\n# it’s non-linear, continuously differentiable, monotonic, and has a fixed output range.\n#\n# https://en.wikipedia.org/wiki/Logistic_function\ndef sigmoid(x):\n    return 1.0 / (1.0 + np.exp(-x))\n\n\n# derivative sigmoid\ndef d_sigmoid(x):\n    s = sigmoid(x)\n    return s * (1.0 - s)\n\n\n# Tanh squashes a real-valued number to the range [-1, 1]. It’s non-linear. But unlike\n# Sigmoid, its output is zero-centered. Therefore, in practice the tanh non-linearity\n# is always preferred to the sigmoid non-linearity.\n#\n# https://en.wikipedia.org/wiki/Hyperbolic_function#Hyperbolic_tangent\ndef tanh(x):\n    return np.tanh(x)\n\n\n# derivative hyperbolic tangent\ndef d_tanh(x):\n    return 1.0 - tanh(x) ** 2.0\n\n\n# arc tangent\n# https://en.wikipedia.org/wiki/Inverse_trigonometric_functions\ndef arc_tan(x):\n    return np.arctan(x)\n\n\n# derivative arc tangent\ndef d_arc_tan(x):\n    return 1.0 / ((x ** 2.0) + 1.0)\n\n\n# Inverse hyperbolic sine\n# https://en.wikipedia.org/wiki/Inverse_hyperbolic_functions#Inverse_hyperbolic_sine\ndef ar_sinh(x):\n    return np.log(x + np.sqrt((x ** 2.0) + 1.0))\n\n\n# derivative of Inverse hyperbolic sine\ndef d_ar_sinh(x):\n    return 1.0 / (np.sqrt((x ** 2.0) + 1.0))\n\n\n# elliot sig also called soft sign\n# https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.7204\ndef elliot_sig(x):\n    return x / (1.0 + abs(x))\n\n\n# derivative elliot sig / soft sign\ndef d_elliot_sig(x):\n    return 1.0 / ((1.0 + abs(x)) ** 2.0)\n\n\n# inverse square root unit\n# https://arxiv.org/abs/1710.09967\ndef isru(x, alpha):\n    return x / np.sqrt((x + (alpha * (x ** 2.0))))\n\n\n# derivative inverse square root unit\ndef d_isru(x, alpha):\n    return x / (np.sqrt(1.0 + (alpha * (x ** 2.0))) ** 3.0)\n\n\n# inverse square root linear unit\n# https://arxiv.org/abs/1710.09967\ndef isrlu(x, alpha):\n    return x / (np.sqrt(1.0 + (alpha * (x ** 2.0)))) if x < 0.0 else x\n\n\n# derivative inverse square root linear unit\ndef d_isrlu(x, alpha):\n    return ((1.0 / np.sqrt(1.0 + alpha * (x ** 2.0))) ** 3.0) if x < 0.0 else 1.0\n\n\n# square non-linearity\n# https://ieeexplore.ieee.org/document/8489043\ndef sqnl(x):\n    if x > 2.0:\n        return 1.0\n    elif 0.0 <= x <= 2.0:\n        return x - ((x ** 2.0) / 4.0)\n    elif -2.0 <= x < 0.0:\n        return x + ((x ** 2.0) / 4.0)\n    elif x < -2.0:\n        return -1.0\n\n\n# derivative square non-linearity\ndef d_sqnl(x):\n    return (1.0 - (x / 2.0)), (1.0 + (x / 2.0))\n\n\n# A recent invention which stands for Rectified Linear Units. The formula is deceptively\n# simple: max(0,z). Despite its name and appearance, it’s not linear and provides the\n# same benefits as Sigmoid but with better performance.\n#\n# https://en.wikipedia.org/wiki/Rectifier_(neural_networks)\ndef relu(x):\n    return x if x >= 0.0 else 0.0\n\n\n# derivative rectified linear units\ndef d_relu(x):\n    return 1.0 if x >= 0.0 else 0.0\n\n\n# bipolar relu\n# https://arxiv.org/abs/1709.04054\ndef brelu(x, index):\n    return relu(x) if index % 2.0 == 0.0 else -relu(-x)\n\n\n# derivative bipolar relu\ndef d_brelu(x, index):\n    return d_relu(x) if index % 2.0 == 0.0 else -d_relu(-x)\n\n\n# LeakyRelu is a variant of ReLU. Instead of being 0 when z<0, a leaky ReLU allows a\n# small, non-zero, constant gradient α (Normally, α=0.01). However, the consistency\n# of the benefit across tasks is presently unclear.\n#\n# https://pdfs.semanticscholar.org/367f/2c63a6f6a10b3b64b8729d601e69337ee3cc.pdf\ndef leaky_relu(x):\n    return x if x >= 0.0 else 0.01 * x\n\n\n# derivative leaky relu\ndef d_leaky_relu(x):\n    return 1.0 if x >= 0.0 else 0.01\n\n\n# parametric relu makes the coefficient of leakage into a parameter that is\n# learned along with other neural network parameters - alpha\n#\n# https://arxiv.org/abs/1502.01852\ndef prelu(x, alpha):\n    return x if x >= 0.0 else alpha * x\n\n\n# derivative parametric relu\ndef d_prelu(x, alpha):\n    return 1.0 if x >= 0.0 else alpha\n\n\n# randomized leaky relu\n# https://arxiv.org/abs/1505.00853\ndef rrelu(x, alpha):\n    return x if x >= 0.0 else alpha * x\n\n\n# derivative randomized leaky relu\ndef d_rrelu(x, alpha):\n    return 1.0 if x >= 0.0 else alpha\n\n\n# Exponential Linear Unit or its widely known name ELU is a function that tend to\n# converge cost to zero faster and produce more accurate results. Different to other\n# activation functions, ELU has a extra alpha constant which should be positive number\n#\n# ELU is very similar to RELU except negative inputs. They are both in identity\n# function form for non-negative inputs. On the other hand, ELU becomes smooth\n# slowly until its output equal to -α whereas RELU sharply smooths.\n#\n# https://arxiv.org/abs/1511.07289\ndef elu(x, alpha):\n    return x if x > 0.0 else alpha * ((np.e ** 2.0) - 1.0)\n\n\n# derivative exponential linear unit\ndef d_elu(x, alpha):\n    return 1.0 if x > 0.0 else elu(x, alpha) + alpha\n\n\n# scaled exponential linear unit\n# https://en.wikipedia.org/wiki/Activation_function#cite_note-20\ndef selu(x, alpha):\n    # d = 1.0507\n    # if x >= 0:\n    #     return x * d\n    # else:\n    #     return d * alpha * ((np.e ** 2) - 1)\n    pass\n\n\n# derivative scaled exponential linear unit\ndef d_selu(x, alpha):\n    pass\n\n\n# s-shaped relu\n# https://arxiv.org/abs/1512.07030\ndef srelu():\n    pass\n\n\n# derivative s-shaped relu\ndef d_srelu():\n    pass\n\n\n# adaptive piecewise linear\n# https://arxiv.org/abs/1412.6830\ndef apl(x, alpha):\n    # return np.maximum(0, x) + np.sum(alpha * np.max(0, -x + ))\n    pass\n\n\n# derivative apl\ndef d_apl():\n    pass\n\n\n# gaussian error linear units\n# https://arxiv.org/abs/1606.08415\ndef gelu(x):\n    # return (x * (1 + (x / np.sqrt(2)))) / 2\n    pass\n\n\n# derivative gaussian error linear units\ndef d_gelu():\n    pass\n\n\n# Softmax function calculates the probabilities distribution of the event over ‘n’ different\n# events. In general way of saying, this function will calculate the probabilities of each\n# target class over all possible target classes. Later the calculated probabilities will be\n# helpful for determining the target class for the given inputs.\n#\n# https://en.wikipedia.org/wiki/Softmax_function\ndef soft_max(x):\n    return np.exp(x) / np.sum(np.exp(x), axis=0)\n\n\n# derivative soft max\ndef d_soft_max(output, trues):\n    temp = output - trues\n    return temp / len(trues)\n\n\n# soft plus\n# http://proceedings.mlr.press/v15/glorot11a/glorot11a.pdf\ndef soft_plus(x):\n    return np.log(1.0 + (np.e ** x))\n\n\n# derivative soft plus\ndef d_soft_plus(x):\n    return 1.0 / (1.0 + (np.e ** -x))\n\n\n# soft exponential\n# https://arxiv.org/abs/1602.01321\ndef soft_exponential(x, alpha):\n    if alpha < 0.0:\n        return -((np.log(1.0 - alpha * (x + alpha))) / alpha)\n    elif alpha > 0.0:\n        return ((np.e ** (alpha * x)) / alpha) + alpha\n    elif alpha == 0.0:\n        return x\n\n\n# derivative soft exponential\ndef d_soft_exponential(x, alpha):\n    return 1.0 / (1.0 - alpha * (alpha + x)) if alpha < 0.0 else np.e ** (alpha * x)\n\n\n# soft clipping\n# https://arxiv.org/abs/1810.11509\ndef soft_clipping(x, alpha):\n    return (1.0 / alpha) * (np.log10((1.0 + (np.e ** (alpha * x))) / (1.0 + (np.e ** (alpha * (x - 1.0))))))\n\n\n# derivative soft clipping\ndef d_soft_clipping(x, p):\n    a = np.cosh((p * x) / 2.0) ** (-1.0)\n    b = np.cosh((p / 2.0) * (1.0 - x)) ** (-1.0)\n    return 0.5 * np.sinh(p / 2.0) * a * b\n\n\ndef gaussian_radial_basis(x, c, s):\n    return np.exp(-1.0 / (2.0 ** (s ** 2.0)) * (x - c) ** 2.0)\n\n\n# improvement over relu for deeper networks\ndef swish(x):\n    # return x * (1 + np.exp(-x)) ** -1\n    return x / ((np.e ** -x) + 1.0)\n\n\n# derivative swish\ndef d_swish(x):\n    return ((np.e ** x) * ((np.e ** x) + x + 1.0)) / (((np.e ** x) + 1.0) ** 2.0)\n\n\n# sinusoid \n# https://arxiv.org/abs/1405.2262\ndef sinusoid(x):\n    return np.sin(x)\n\n\n# derivative sinusoid\ndef d_sinusoid(x):\n    return np.cos(x)\n\n\n# sinc\n# https://en.wikipedia.org/wiki/Sinc_function\ndef sinc(x):\n    return 1.0 if x == 0.0 else np.sin(x) / x\n\n\n# derivative sinc\ndef d_sinc(x):\n    return 0.0 if x == 0.0 else (np.cos(x) / x) - (np.sin(x) / (x ** 2.0))\n\n\n# gaussian\n# https://en.wikipedia.org/wiki/Gaussian_function\ndef gaussian(x):\n    return np.e ** (-x ** 2.0)\n\n\n# derivative gaussian\ndef d_gaussian(x):\n    return -2.0 * x * np.e ** (-x ** 2.0)\n\n\n# gradient relu\ndef gradient_relu(a, x):\n    _relu = relu(x)\n    return np.multiply(a, np.int64(_relu > 0.0))", "meta": {"hexsha": "3ff08dd9b3f54f3716f06282a4e618bebf7046f9", "size": 9775, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine-learning-gists/1dcba4601f0c083e3c86177b54c6f706f3552061/snippet.py", "max_stars_repo_name": "qwbjtu2015/dockerizeme", "max_stars_repo_head_hexsha": "9039beacf281ea7058d721784ed4eff054453b09", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "machine-learning-gists/1dcba4601f0c083e3c86177b54c6f706f3552061/snippet.py", "max_issues_repo_name": "qwbjtu2015/dockerizeme", "max_issues_repo_head_hexsha": "9039beacf281ea7058d721784ed4eff054453b09", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "machine-learning-gists/1dcba4601f0c083e3c86177b54c6f706f3552061/snippet.py", "max_forks_repo_name": "qwbjtu2015/dockerizeme", "max_forks_repo_head_hexsha": "9039beacf281ea7058d721784ed4eff054453b09", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.746835443, "max_line_length": 108, "alphanum_fraction": 0.6568797954, "include": true, "reason": "import numpy", "num_tokens": 3155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361157495521, "lm_q2_score": 0.8933094074745445, "lm_q1q2_score": 0.8578996565638916}}
{"text": "from sympy import *\nimport math\nfrom numpy import arange\n\n\nclass FixedPointIteration:\n\n    num_of_iteration = 0\n    root\n\n    def __init__(self, function_formula, initial_x, max_iterations, precision, x=Symbol('x')):\n        self.function_formula = function_formula\n        self.initial_x = initial_x\n        self.X = x\n        self.max_iterations = max_iterations\n        if max_iterations == 0:\n            self.max_iterations = 50\n        self.precision = precision\n        if precision == 0:\n            self.precision = 0.0001\n\n    def compute_root(self):\n\n        try:\n            # create the table\n            table = [['i', 'Xi', 'relative_error']]\n            row = [0, self.initial_x, None]\n            table.append(row)\n\n            i = 0\n            # if the initial guess is the root\n            if self.function_formula.evalf(subs={self.X: self.initial_x}) < 1e-10 \\\n                    and self.function_formula.evalf(subs={self.X: self.initial_x}) > -1e-10:\n                FixedPointIteration.root = self.initial_x\n                return [table], self.initial_x, true\n\n            while True:\n\n                i = i + 1\n\n                iterative_x = float(self.function_formula.evalf(subs={self.X: self.initial_x}))\n\n                # if the root is zero\n                if iterative_x == 0.0:\n                    if self.function_formula.evalf(subs={self.X: iterative_x}) < 1e-10 \\\n                            and self.function_formula.evalf(subs={self.X: iterative_x}) > -1e-10:\n\n                        return [table], iterative_x, true\n                    else:\n                        relative_error = 1.0\n                else:\n                    relative_error = (iterative_x - self.initial_x) / iterative_x\n\n                # add Row to the table\n                row = [i, iterative_x, math.fabs(relative_error)]\n                table.append(row)\n\n                # break when reach max iteration or precision\n                if (math.fabs(relative_error) <= self.precision) | (i >= self.max_iterations):\n                    break\n\n                self.initial_x = iterative_x\n\n                if iterative_x < 1e-10 and iterative_x > -1e-10:\n                    break\n\n            final_table = [table]\n            print (final_table)\n            FixedPointIteration.root = iterative_x\n            return final_table, iterative_x, true\n        except:\n            return [[[]]], 0.0, false\n\n\n    # to do call to check if root\n    def is_root(self):\n        try:\n            if self.function_formula.evalf(subs={self.X: FixedPointIteration.root}) < 1e-1 \\\n                    and self.function_formula.evalf(subs={self.X: FixedPointIteration.root}) > -1e-1:\n                return true\n            else:\n                return false\n        except:\n            return false\n\n    def get_x_y(self):\n\n        a = []\n        b = []\n\n        for x in range(-50, 50, 1):\n            y = self.function_formula.evalf(subs={self.X: x})\n            a.append(x)\n            b.append(y)\n        return a, b\n\n", "meta": {"hexsha": "4f1f2d9c6f893b48800d3674e4b2efac6cd91b96", "size": 3024, "ext": "py", "lang": "Python", "max_stars_repo_path": "methods/Fixed_point_iteration_method.py", "max_stars_repo_name": "Magho/Determine-roots-of-equations-project", "max_stars_repo_head_hexsha": "81f451dc8999ccf46183575adc160e8eff69e581", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "methods/Fixed_point_iteration_method.py", "max_issues_repo_name": "Magho/Determine-roots-of-equations-project", "max_issues_repo_head_hexsha": "81f451dc8999ccf46183575adc160e8eff69e581", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "methods/Fixed_point_iteration_method.py", "max_forks_repo_name": "Magho/Determine-roots-of-equations-project", "max_forks_repo_head_hexsha": "81f451dc8999ccf46183575adc160e8eff69e581", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-12T22:42:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-12T22:42:40.000Z", "avg_line_length": 31.175257732, "max_line_length": 101, "alphanum_fraction": 0.525462963, "include": true, "reason": "from numpy,from sympy", "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.9086178919837706, "lm_q1q2_score": 0.8578959900166179}}
{"text": "# variance calculator python\n# https://www.google.com/search?q=variance+calculator+python&oq=variance+calculator+py&aqs=chrome.1.69i57j0j0i22i30.3719j0j7&sourceid=chrome&ie=UTF-8\n\nimport numpy as np\nfrom statistics import variance, stdev\n\nresults = [-14.82381293, -0.29423447, -13.56067979, -1.6288903, -0.31632439,\n           0.53459687, -1.34069996, -1.61042692, -4.03220519, -0.24332097]\n# # way 1\n# print(np.var(results, ddof=1))\n# print(np.std(results, ddof=1))\na = np.array([[1, 2], [3, 4]])\n# print(a)\n# print(np.var(a))\n# print(np.var(a, ddof=1))\n# print(np.var(a, axis=0))\n# print(np.var(a, axis=1))\n\n# way 2\nm = sum(results) / len(results)\nvar_res = sum((xi-m)**2 for xi in results)/(len(results)-1)\n# print(var_res)\n\n# way 3: not need ddof\n# print(variance(results))\n# print(stdev(results))\n", "meta": {"hexsha": "9f31d9f503058682dd665f3bad75fe60f7d48ea3", "size": 802, "ext": "py", "lang": "Python", "max_stars_repo_path": "davidgoliath/project/modelling/12_variance.py", "max_stars_repo_name": "spideynolove/Other-repo", "max_stars_repo_head_hexsha": "34066f177994415d031183ab9dd219d787e6e13a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "davidgoliath/project/modelling/12_variance.py", "max_issues_repo_name": "spideynolove/Other-repo", "max_issues_repo_head_hexsha": "34066f177994415d031183ab9dd219d787e6e13a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "davidgoliath/project/modelling/12_variance.py", "max_forks_repo_name": "spideynolove/Other-repo", "max_forks_repo_head_hexsha": "34066f177994415d031183ab9dd219d787e6e13a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7037037037, "max_line_length": 149, "alphanum_fraction": 0.680798005, "include": true, "reason": "import numpy", "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.9019206837793828, "lm_q1q2_score": 0.8578548414274278}}
{"text": "# --------------\nimport pandas as pd\r\nimport numpy as np\r\nimport math\r\n\r\n\r\n#Code starts here\r\nclass complex_numbers:\r\n    '''\r\n    The Complex Number Class\r\n    \r\n    Attributes:\r\n    real: real part of complex number\r\n    imag: imaginary part of complex number\r\n    '''\r\n    \r\n    def __init__(self,real,imag):\r\n        self.real=real\r\n        self.imag=imag\r\n    \r\n    def __repr__(self):\r\n        if self.real == 0.0 and self.imag == 0.0:\r\n            return \"0.00\"\r\n        if self.real == 0:\r\n            return \"%.2fi\" % self.imag\r\n        if self.imag == 0:\r\n            return \"%.2f\" % self.real\r\n        return \"%.2f %s %.2fi\" % (self.real, \"+\" if self.imag >= 0 else \"-\", abs(self.imag))\r\n    \r\n    def __add__(self,other):\r\n        '''\r\n        '+' operator overloading\r\n        complex number addition\r\n        \r\n        params:\r\n        other:- other complex number for addition\r\n        \r\n        return:\r\n        result of addition \r\n        '''\r\n        a=self.real+other.real\r\n        b=self.imag+other.imag\r\n        return complex_numbers(a,b)\r\n    \r\n    def __sub__(self,other):\r\n        '''\r\n        '-' operator overloading\r\n        complex number subtraction\r\n        \r\n        params:\r\n        other:- other complex number for subtraction\r\n        \r\n        return: \r\n        result of subtraction \r\n        '''\r\n        a=self.real-other.real\r\n        b=self.imag-other.imag\r\n        return complex_numbers(a,b)\r\n    \r\n    def __mul__(self,other):\r\n        '''\r\n        '*' operator overloading\r\n        complex number multiplication\r\n        \r\n        params:\r\n        other:- other complex number for multiplication\r\n        \r\n        return: \r\n        result of multiplication \r\n        '''\r\n        a=self.real*other.real - self.imag*other.imag\r\n        b=self.real*other.imag + self.imag*other.real\r\n        return complex_numbers(a,b)\r\n    \r\n    def __truediv__(self,other):\r\n        '''\r\n        '/' operator overloading\r\n        complex number division\r\n        \r\n        params:\r\n        other:- other complex number for division\r\n        \r\n        return: \r\n        result of division \r\n        '''\r\n        a=(self.real*other.real+self.imag*other.imag)/(other.real*other.real+other.imag*other.imag)\r\n        b=(self.imag*other.real-self.real*other.imag)/(other.real*other.real+other.imag*other.imag)\r\n        return complex_numbers(a,b)\r\n    \r\n    def absolute(self):\r\n        '''\r\n        Absolute value of Complex number\r\n        \r\n        return:\r\n        absolute value\r\n        '''\r\n        return np.sqrt((self.real**2)+(self.imag**2))\r\n    \r\n    def argument(self):\r\n        '''\r\n        argument value of Complex number\r\n        \r\n        return:\r\n        argument value\r\n        '''\r\n        return math.degrees(math.atan(self.imag/self.real))\r\n    \r\n    def conjugate(self):\r\n        '''\r\n        conjugate value of Complex number\r\n        \r\n        return:\r\n        conjugate value\r\n        '''\r\n        a,b=self.real,self.imag*-1\r\n        return complex_numbers(a,b)\r\n\r\n\r\ncomp_1=complex_numbers(3,5)\r\nprint(comp_1)\r\ncomp_2=complex_numbers(4,4)\r\nprint(comp_2)\r\ncomp_sum=comp_1+comp_2\r\nprint(comp_sum)\r\ncomp_diff=comp_1-comp_2\r\nprint(comp_diff)\r\ncomp_prod=comp_1*comp_2\r\nprint(comp_prod)\r\ncomp_quot=comp_1/comp_2\r\nprint(comp_quot)\r\ncomp_abs=comp_1.absolute()\r\nprint(comp_abs)\r\ncomp_conj=comp_1.conjugate()\r\nprint(comp_conj)\r\ncomp_arg=comp_1.argument()\r\nprint(comp_arg)\n\n\n", "meta": {"hexsha": "c9129dc07ce6f8b0182d80b8534fef6bb822232d", "size": 3416, "ext": "py", "lang": "Python", "max_stars_repo_path": "code.py", "max_stars_repo_name": "kalpeshsnaik09/complex--number-calculator", "max_stars_repo_head_hexsha": "907c30d3fad30d513220d84585dfa4e4bad7d6e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code.py", "max_issues_repo_name": "kalpeshsnaik09/complex--number-calculator", "max_issues_repo_head_hexsha": "907c30d3fad30d513220d84585dfa4e4bad7d6e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code.py", "max_forks_repo_name": "kalpeshsnaik09/complex--number-calculator", "max_forks_repo_head_hexsha": "907c30d3fad30d513220d84585dfa4e4bad7d6e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5755395683, "max_line_length": 100, "alphanum_fraction": 0.5471311475, "include": true, "reason": "import numpy", "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.9019206752113866, "lm_q1q2_score": 0.8578548320289436}}
{"text": "import numpy as np\nimport pandas as pd\nfrom scipy.optimize import minimize\n\n\nclass F_class:\n    def __init__(self, a, A, B):\n        self.a = a\n        self.A = A\n        self.B = B\n\n    def calc(self, x):\n        res = np.zeros(x.shape)\n\n        bigger_idx = x > self.a\n        smaller_idx = x <= self.a\n\n        res[bigger_idx] = np.power(x[bigger_idx], 2) * self.A\n        res[smaller_idx] = np.power(x[smaller_idx], 2) * self.B\n\n        return res\n\n\na = 0\nA = 1\nB = -1\n\nf = F_class(a, A, B)\nX = np.arange(-5, 5)\nY = f.calc(X)\nD = pd.DataFrame(columns=['X', 'Y'], data=np.array([X, Y]).T)\n\n\ndef sum_of_squares(params, X, Y):\n    a, A, B = params\n    model = F_class(a, A, B)\n    y_pred = model.calc(X)\n    obj = np.sqrt(((y_pred - Y) ** 2).sum())\n    return obj\n\n\n# perform fit to find optimal parameters\n# initial value is a guess\ninitial_guess = [0., 0., 0.]  # a, A, B\nres = minimize(sum_of_squares, x0=initial_guess, args=(X, Y), tol=1e-5, method=\"Powell\")\na_pred, A_pred, B_pred = res.x\n\nprint(\"Estimated values:\")\nprint(f\"a = {a_pred:>.3f}\")\nprint(f\"A = {A_pred:>.3f}\")\nprint(f\"B = {B_pred:>.3f}\")\n\nmodel = F_class(a_pred, A_pred, B_pred)\nY_pred = model.calc(X)\nMSE = np.sqrt(((Y_pred - Y) ** 2).sum())\nprint(f\"MSE: {MSE}\")\n", "meta": {"hexsha": "4f538d5789ca75b0f06a3a845c5d6a5c513a1de3", "size": 1233, "ext": "py", "lang": "Python", "max_stars_repo_path": "4.0.2.py", "max_stars_repo_name": "GuysBarash/MLBook", "max_stars_repo_head_hexsha": "ca388186ab224afda92224adf50277ae331964bd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4.0.2.py", "max_issues_repo_name": "GuysBarash/MLBook", "max_issues_repo_head_hexsha": "ca388186ab224afda92224adf50277ae331964bd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4.0.2.py", "max_forks_repo_name": "GuysBarash/MLBook", "max_forks_repo_head_hexsha": "ca388186ab224afda92224adf50277ae331964bd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6315789474, "max_line_length": 88, "alphanum_fraction": 0.5847526358, "include": true, "reason": "import numpy,from scipy", "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140235181257, "lm_q2_score": 0.8872045981907006, "lm_q1q2_score": 0.8578505677203524}}
{"text": "from sympy import *\n\n\ndef lagrange_interpolate(points: list, simplify_result=True, verbose=False):\n    \"\"\"拉格朗日插值\n\n    Args:\n        points: list, [(x1, y1), (x2, y2), ..., (xn, yn)]\n        simplify_result: bool, 化简最终结果, default True\n        verbose: bool, 输出每一步的结果, default False\n\n    Returns: \n        L: sympy object of Symbol('x'), 插值多项式 $L(x)$\n    \"\"\"\n    x = Symbol('x')\n    L = 0  # 插值多项式\n    for i, point in enumerate(points):\n        xi, yi = point\n        li = 1\n        for j in range(len(points)):\n            if j == i:\n                continue\n            xj, yj = points[j]\n            li *= (x - xj) / (xi - xj)\n        L += yi * li\n        if verbose:\n            print(f\"l_{i}(x) = \", simplify(yi * li))\n\n    if simplify_result:\n        L = simplify(L)\n    return L\n", "meta": {"hexsha": "f19a2fdcce22198e8b6c4b5cf53f6c72aa30ba72", "size": 784, "ext": "py", "lang": "Python", "max_stars_repo_path": "ex3/src/lagrange_interpolate.py", "max_stars_repo_name": "cdfmlr/NumericalAnalysis", "max_stars_repo_head_hexsha": "b752af60c1f3202d53cc3c76e66419a885250ed9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex3/src/lagrange_interpolate.py", "max_issues_repo_name": "cdfmlr/NumericalAnalysis", "max_issues_repo_head_hexsha": "b752af60c1f3202d53cc3c76e66419a885250ed9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex3/src/lagrange_interpolate.py", "max_forks_repo_name": "cdfmlr/NumericalAnalysis", "max_forks_repo_head_hexsha": "b752af60c1f3202d53cc3c76e66419a885250ed9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-15T01:34:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-15T01:34:35.000Z", "avg_line_length": 24.5, "max_line_length": 76, "alphanum_fraction": 0.4948979592, "include": true, "reason": "from sympy", "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140206578809, "lm_q2_score": 0.8872045937171068, "lm_q1q2_score": 0.8578505608571494}}
{"text": "\"\"\" Rosembrock function \"\"\"\n\nimport numpy as np\n\n\ndef function(x: np.array, n: int = 100) -> float:\n    \"\"\" Compute the evaluation for Extended Rosembrock function with n=100\n        Args:\n        x: Array of length=n with x's parameters\n        n: Rosembrock, n = 100\n\n        Returns:\n            Evaluation of f(X)\n    \"\"\"\n    ans = 0.0\n    for i in range(n-1):\n        ans += 100 * (x[i+1] - x[i]**2)**2 + (1 - x[i])**2\n    return ans\n\n\ndef gradient(x: np.array, n: int = 100) -> np.array:\n    \"\"\" Compute the gradient evaluation for Extended Rosembrock function with n=2\n        Args:\n        x: Array of length=n with x's parameters\n        n: Rosembrock, n = 100\n\n        Returns:\n            Gradient of f(x1, ..., xn), array with lenght=n\n    \"\"\"\n    # grad = np.zeros(n, dtype=np.float64)\n    # for i in range(n-1):\n    #     grad[i] = -400 * x[i+1] * x[i] + 400 * x[i]**3 + 2 * x[i] -2\n    # grad[n-1] = 200 * (x[n-1] - x[n-2]**2)\n    # return grad\n    grad = np.array([-400*(x[1]-x[0]**2)*x[0]-2*(1-x[0])])\n\n    for i in range(1, n-1):\n        grad = np.append(grad, [200*(x[i]-x[i-1]**2)-400*(x[i+1]-x[i]**2)*x[i]-2*(1-x[i])])\n\n    grad = np.append(grad, [200*(x[99] - x[98]**2)])\n\n    return grad\n\n\ndef hessian(x: np.array, n: int = 100) -> np.array:\n    \"\"\" Compute the Hessian evaluation for Extended Rosembrock function with n=2\n        Args:\n        x: Array of length=n with x's parameters\n\n        Returns:\n            Hessian of f(x1, ..., xn), Matrix with size=nxn\n    \"\"\"\n    hess = np.zeros((n, n), dtype=np.float64)\n    for i in range(n-1):\n        hess[i][i] = -400 * x[i+1] + 1200 * x[i]**2 + 2\n        hess[i][i] += 200 if i != 0 else 0\n        hess[i][i+1] = hess[i+1][i] = -400 * x[i]\n    hess[n-1][n-1] = 200.0\n    return hess\n", "meta": {"hexsha": "5bc168093bf440319c99ed135a699dd0608e8df4", "size": 1758, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tarea 9/src/rosembrock.py", "max_stars_repo_name": "EsauPR/CIMAT-Numerical-Optimization", "max_stars_repo_head_hexsha": "d7e932d4f1a6fe275492c4bc28044ef101ee69cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tarea 9/src/rosembrock.py", "max_issues_repo_name": "EsauPR/CIMAT-Numerical-Optimization", "max_issues_repo_head_hexsha": "d7e932d4f1a6fe275492c4bc28044ef101ee69cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tarea 9/src/rosembrock.py", "max_forks_repo_name": "EsauPR/CIMAT-Numerical-Optimization", "max_forks_repo_head_hexsha": "d7e932d4f1a6fe275492c4bc28044ef101ee69cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3, "max_line_length": 91, "alphanum_fraction": 0.5170648464, "include": true, "reason": "import numpy", "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140235181256, "lm_q2_score": 0.8872045817875224, "lm_q1q2_score": 0.8578505518598892}}
{"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n##########################################################################################\n# author: Nikolas Schnellbaecher\n# contact: khx0@posteo.net\n# date: 2021-04-11\n# file: create_samples.py\n# tested with python 3.7.6\n##########################################################################################\n# description:\n# Creates (1) fully correlated and (2) fully independent normally distributed\n# random samples using inverse transform sampling (ITS).\n##########################################################################################\n\nimport os\nimport datetime\nimport numpy as np\nimport scipy\nfrom scipy.stats import norm\n\ntoday = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n\nBASEDIR = os.path.dirname(os.path.abspath(__file__))\nRAWDIR = os.path.join(BASEDIR, 'raw')\nOUTDIR = os.path.join(BASEDIR, 'out')\n\nos.makedirs(RAWDIR, exist_ok = True)\n\ndef inverseTransformSamplingJoint(n_samples, mu1, sigma1, mu2, sigma2):\n    u = np.random.uniform(size = n_samples)\n    x1 = norm.ppf(u, loc = mu1, scale = sigma1)\n    x2 = norm.ppf(u, loc = mu2, scale = sigma2)\n    return x1, x2\n\nif __name__ == '__main__':\n\n    print(\"using np.__version__ =\", np.__version__)\n    print(\"using scipy.__version__ =\", scipy.__version__)\n\n    # set parameters\n    n_samples = 20000\n\n    mu1, sigma1 = 87.25, 8.124\n    mu2, sigma2 = 125.75, 11.25\n\n    seed_value = 987654321\n\n    ######################################################################################\n    # 01 - Create fully correlated Gaussian samples using the inverse transform method\n    samples = np.zeros((n_samples, 2))\n\n    np.random.seed(seed_value)\n\n    samples[:, 0], samples[:, 1] = \\\n        inverseTransformSamplingJoint(n_samples, mu1, sigma1, mu2, sigma2)\n    outname = f'GaussianSamples_correlated_seed_{seed_value:d}.txt'\n    np.savetxt(os.path.join(RAWDIR, outname), samples, fmt = '%.8f')\n\n    ######################################################################################\n    # 02 - Create two independent Gaussian random realizations\n\n    np.random.seed(seed_value) # reset the seed value\n\n    samples = np.zeros((n_samples, 2))\n    samples[:, 0] = norm.rvs(loc = mu1, scale = sigma1, size = n_samples)\n    samples[:, 1] = norm.rvs(loc = mu2, scale = sigma2, size = n_samples)\n    outname = f'GaussianSamples_uncorrelated_seed_{seed_value:d}.txt'\n    np.savetxt(os.path.join(RAWDIR, outname), samples, fmt = '%.8f')\n", "meta": {"hexsha": "9319d15e7b3ccca45de51d4790d30c41a32432d3", "size": 2450, "ext": "py", "lang": "Python", "max_stars_repo_path": "mpl_correlation2d_with_marginals/create_samples.py", "max_stars_repo_name": "khx0/mpl-benchmarks", "max_stars_repo_head_hexsha": "848a2626ea057a91deb1556c6fc6ad1da3b23e64", "max_stars_repo_licenses": ["Python-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-02-08T22:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T19:38:32.000Z", "max_issues_repo_path": "mpl_correlation2d_with_marginals/create_samples.py", "max_issues_repo_name": "khx0/mpl-benchmarks", "max_issues_repo_head_hexsha": "848a2626ea057a91deb1556c6fc6ad1da3b23e64", "max_issues_repo_licenses": ["Python-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mpl_correlation2d_with_marginals/create_samples.py", "max_forks_repo_name": "khx0/mpl-benchmarks", "max_forks_repo_head_hexsha": "848a2626ea057a91deb1556c6fc6ad1da3b23e64", "max_forks_repo_licenses": ["Python-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5072463768, "max_line_length": 90, "alphanum_fraction": 0.5632653061, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.949669363129097, "lm_q2_score": 0.9032942119105696, "lm_q1q2_score": 0.8578308389433102}}
{"text": "import numpy as np\nfrom problem3 import compute_P,random_walk\n\n#-------------------------------------------------------------------------\n'''\n    Problem 4: Solving sink-node problem in PageRank\n    In this problem, we implement the pagerank algorithm which can solve the sink node problem.\n    You could test the correctness of your code by typing `nosetests test4.py` in the terminal.\n'''\n\n#--------------------------\ndef compute_S(A):\n    '''\n        compute the transition matrix S from addjacency matrix A, which solves sink node problem by filling the all-zero columns in A.\n        S[j][i] represents the probability of moving from node i to node j.\n        If node i is a sink node, S[j][i] = 1/n.\n        Input:\n                A: adjacency matrix, a (n by n) numpy matrix of binary values. If there is a link from node i to node j, A[j][i] =1. Otherwise A[j][i]=0 if there is no link.\n        Output:\n                S: transition matrix, a (n by n) numpy matrix of float values.  S[j][i] represents the probability of moving from node i to node j.\n    The values in each column of matrix S should sum to 1.\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n    shape = set(np.shape(A))\n    assert len(shape) == 1\n    n = shape.pop()\n\n    P = compute_P(A)\n    colsums = P.sum(axis=0)\n    sink_nodes = np.asarray(np.isnan(colsums))\n    sink_nodes = sink_nodes.reshape((n,))\n\n    from copy import deepcopy\n    S = deepcopy(P)\n\n    if sink_nodes.any():\n        S[:, sink_nodes] = 1/n\n\n    #########################################\n    return S\n\n\n\n#--------------------------\ndef pagerank_v2(A):\n    '''\n        A simplified version of PageRank algorithm, which solves the sink node problem.\n        Given an adjacency matrix A, compute the pagerank score of all the nodes in the network.\n        Input:\n                A: adjacency matrix, a numpy matrix of binary values. If there is a link from node i to node j, A[j][i] =1. Otherwise A[j][i]=0 if there is no link.\n        Output:\n                x: the ranking scores, a numpy vector of float values, such as np.array([[.3], [.5], [.7]])\n    '''\n\n    # Initialize the score vector with all one values\n    num_nodes, _ = A.shape\n    x_0 =  np.asmatrix(np.ones((num_nodes,1)))\n\n    # compute the transition matrix from adjacency matrix\n    S = compute_S(A)\n\n    # random walk\n    x, n_steps = random_walk(S,x_0)\n\n    return x\n\n", "meta": {"hexsha": "9a663c8885b469ea8f7e3511dc95e3848d0a3158", "size": 2420, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw1/problem4.py", "max_stars_repo_name": "rahul-pande/ds501", "max_stars_repo_head_hexsha": "063453de9bf7bc634422a6710d36715175cbeebf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw1/problem4.py", "max_issues_repo_name": "rahul-pande/ds501", "max_issues_repo_head_hexsha": "063453de9bf7bc634422a6710d36715175cbeebf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw1/problem4.py", "max_forks_repo_name": "rahul-pande/ds501", "max_forks_repo_head_hexsha": "063453de9bf7bc634422a6710d36715175cbeebf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0724637681, "max_line_length": 173, "alphanum_fraction": 0.5818181818, "include": true, "reason": "import numpy", "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693617046216, "lm_q2_score": 0.9032942047513692, "lm_q1q2_score": 0.8578308308577166}}
{"text": "#!/usr/local/bin/python3\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.spatial import distance as sd\n\n\nclass Clusterers:\n    def __init__(self, data_path):\n        self._data_path = data_path\n        self._points = list()\n        self._clusters = list()\n        self._centroids = list()\n        self.load_data()\n\n    def load_data(self):\n        with open(self._data_path, 'r') as f:\n            lines = f.readlines()\n            for line in lines:\n                point_str = line.strip(\"\\n\").split(\"\\t\")\n                self._points.append([float(point_str[0]), float(point_str[1])])\n            self._points = np.array(self._points)\n        # print(np.average(self._points, axis=0))\n\n    ''' ################# Following is implementation for K-means clustering ################# '''\n    def k_means(self, init_centroids):\n        cent = init_centroids\n        # print(self.mink_dist(cent[0], cent[1], 3))\n        print(\"=============  (a) Euclidean  ==============\")\n        self.k_means_train(init_centroids, self.eucl_dist)\n        print(\"=============  (b) Cityblock  ==============\")\n        self.k_means_train(init_centroids, self.city_dist)\n        print(\"=============  (c) Minkovski  ==============\")\n        self.k_means_train(init_centroids, self.mink_dist)\n        return\n\n    def k_means_train(self, init_cents, dist_m):\n        # num_clusters = len(init_cents)\n        self._centroids = list(init_cents)\n        self._clusters.clear()\n\n        loss = 1000\n        epoch = 0\n        while loss > 0:\n            epoch += 1\n            print(\"=============  epoch\", epoch, \"==============\")\n            pre_obj = self.k_means_obj_func(dist_m)\n            # assign points\n            self.print_centroids()\n            self.k_means_assign(dist_m)\n            # update centroids\n            self.k_means_update()\n            self.print_clusters()\n            obj = self.k_means_obj_func(dist_m)\n            print(\"result of pre_obj func:\", pre_obj)\n            print(\"result of obj func:\", obj)\n            loss = abs(pre_obj - obj)\n            print(\"loss:\", loss)\n        print(\"amount of epoch:\", epoch)\n\n        return self._clusters\n\n    def k_means_assign(self, dist_m):\n        cents = self._centroids\n        self._clusters = [np.zeros([0,2]) for i in range(len(cents))]\n        # for cent in cents:\n        #     self._clusters.append(np.array([cent]))\n        for point in self._points:\n            min_dist = 1000\n            min_ind = 0\n            for cent_ind in range(len(cents)):\n                dist = dist_m(point, cents[cent_ind])\n                if dist < min_dist:\n                    min_dist = dist\n                    min_ind = cent_ind\n            # print(point, self._clusters[min_ind][0], min_dist)\n            self._clusters[min_ind] = np.append(self._clusters[min_ind], np.array([point]), axis=0)\n        return self._clusters\n\n    def k_means_update(self):\n        self._centroids.clear()\n        for clst in self._clusters:\n            # print(clst[1:])\n            self._centroids.append(np.average(clst[:], axis = 0))\n            # print(self._centroids)\n        return self._centroids\n\n    def k_means_obj_func(self, dist_m):\n        # res = 0\n        # for clst_i in range(len(self._clusters)):\n        #     cent = self._clusters[clst_i][0]\n        #     res += sum(dist_m(cent, self._clusters[clst_i][i]) for i in range(1, len(self._clusters[clst_i])))\n        # return res\n        return sum( sum(dist_m(self._clusters[clst_i][0], self._clusters[clst_i][i]) for i in range(1, len(self._clusters[clst_i]))) for clst_i in range(len(self._clusters)))\n\n    ''' ################# Following is implementation for Hierarchical clustering ################# '''\n    def hierarchical(self):\n        self._clusters.clear()\n        # print pair-wise proximity matrix for original points\n        print(\"======================= a. initial proximity matrix & clusters =======================\")\n        pdist = self.hier_pdist()\n        self.hier_show_prox_mat(self._points, pdist, \"[Point-Point Proximities]\", True, \"p\")\n        dists = self.hier_init_clusters()\n        self.print_clusters()\n        self._clusters.clear()\n\n        # complete linkage\n        print(\"======================= b. complete linkage  =======================\")\n        dists = self.hier_init_clusters(self.hier_dist_complete)\n        self.hier_show_prox_mat(self._clusters, dists, \"[Cluster-Cluster Proximities]\", True)\n        while len(self._clusters)>1:\n            dists = self.hier_update(dists, self.hier_dist_complete)\n            self.hier_show_prox_mat(self._clusters, dists, \"[Cluster-Cluster Proximities]\", True)\n        self._clusters.clear()\n\n        # single linkage\n        print(\"======================= c. single linkage  =======================\")\n        dists = self.hier_init_clusters(self.hier_dist_single)\n        self.hier_show_prox_mat(self._clusters, dists, \"[Cluster-Cluster Proximities]\", True)\n        while len(self._clusters)>1:\n            dists = self.hier_update(dists, self.hier_dist_single)\n            self.hier_show_prox_mat(self._clusters, dists, \"[Cluster-Cluster Proximities]\", True)\n        self._clusters.clear()\n\n        # group average\n        print(\"======================= d. group average =======================\")\n        dists = self.hier_init_clusters(self.hier_dist_group)\n        self.hier_show_prox_mat(self._clusters, dists, \"[Cluster-Cluster Proximities]\", True)\n        while len(self._clusters)>1:\n            dists = self.hier_update(dists, self.hier_dist_group)\n            self.hier_show_prox_mat(self._clusters, dists, \"[Cluster-Cluster Proximities]\", True)\n        self._clusters.clear()\n\n        return \n\n    def hier_init_clusters(self, dist_m = None):\n        # initialize 5 separations (0-3, 4-7, 8-11, 12-15, 16-19)\n        # self._clusters = [np.zeros([0,2]) for i in range(5)]\n        # for clst_i in range(len(self._clusters)):\n        #     for p_i in range(clst_i * 4, clst_i * 4 + 4):\n        #         self._clusters[clst_i] = np.append(self._clusters[clst_i], np.array([self._points[p_i]]), axis=0)\n        #         # print(np.array([self._points[p_i]]))\n\n        # initialize 5 separations using single-linkage\n        for point in self._points:\n            self._clusters.append(np.array([point]))\n        pdist = self.hier_pdist()\n        dists = self.hier_update(pdist, self.hier_dist_single)\n        while len(self._clusters) != 5:\n            dists = self.hier_update(dists, self.hier_dist_single)\n        if dist_m:\n            # dists = dist_m(pdist)\n            dists = dist_m()\n            return dists\n        return\n\n    def hier_update(self, dists, merge_m):\n        self.hier_merge(dists)\n        # return merge_m(dists)\n        return merge_m()\n\n    def hier_merge(self, dists):\n        # merge clusters based on a certain linkage method\n        min_ind = np.argmin(dists)\n        # self.print_clusters()\n        num_clst = len(self._clusters)\n        for clst_1 in range(num_clst-1):\n            for clst_2 in range(clst_1+1, num_clst):\n                if min_ind == self.hier_rcl(clst_1, clst_2, num_clst):\n                    print(\"[Notes] 'c%02d'\" % clst_2, \"will be merged into 'c%02d'\" % clst_1)\n                    # found the closest cluster pair\n                    # print(clst_1, clst_2)\n                    clusters = list() \n                    for clst_i in range(num_clst):\n                        if clst_i == clst_2:\n                            clusters[clst_1] = np.append(clusters[clst_1], self._clusters[clst_2], axis=0)\n                            continue\n                        clusters.append(self._clusters[clst_i])\n                    self._clusters = clusters\n                    break\n        # self.print_clusters()\n        return self._clusters\n\n    def hier_pdist(self):\n        return sd.pdist(self._points)\n\n    # def hier_dist_single(self, pdist):\n    def hier_dist_single(self):\n        clusters = self._clusters\n        dists = np.zeros([0])\n        for clst_1 in range(len(clusters)-1):\n            for clst_2 in range(clst_1 + 1, len(clusters)):\n                min_dist = np.min(sd.cdist(clusters[clst_1], clusters[clst_2]))\n                dists = np.append(dists, np.array([min_dist]))\n                # print(clst_1, clst_2, min_dist)\n        return dists\n\n    # def hier_dist_complete(self, pdist):\n    def hier_dist_complete(self):\n        clusters = self._clusters\n        dists = np.zeros([0])\n        for clst_1 in range(len(clusters)-1):\n            for clst_2 in range(clst_1 + 1, len(clusters)):\n                max_dist = np.max(sd.cdist(clusters[clst_1], clusters[clst_2]))\n                dists = np.append(dists, np.array([max_dist]))\n        return dists\n\n    # def hier_dist_group(self, pdist):\n    def hier_dist_group(self):\n        clusters = self._clusters\n        dists = np.zeros([0])\n        for clst_1 in range(len(clusters)-1):\n            for clst_2 in range(clst_1 + 1, len(clusters)):\n                avg_dist = np.average(sd.cdist(clusters[clst_1], clusters[clst_2]))\n                dists = np.append(dists, np.array([avg_dist]))\n        return dists\n\n    def hier_show_prox_mat(self, clusters, pdist, title, if_print = False, label = 'c'):\n        if if_print:\n            num_p = len(clusters)\n            # print table header\n            print(title)\n            if label == \"p\":\n                print(\"             \", end=\"\")\n            else:\n                print(\"    \", end=\"\")\n            for i in range(num_p):\n                print(\" %s%02d \" % (label, i), end=\"\")\n            print()\n            # print matrix\n            row = 0\n            for i in sd.squareform(pdist):\n                col = 0\n                if label == \"p\":\n                    print(\"%s%02d[%.1f,%.1f] \" % (label, row, clusters[row][0], clusters[row][1]), end=\"\")\n                else:\n                    print(\"%s%02d \" % (label, row), end=\"\")\n                for j in i:\n                    if row == col:\n                        print(\"0.00 \", end=\"\")\n                    else: \n                        print(\"%.2f \" % pdist[self.hier_rcl(row,col,num_p)], end=\"\")\n                        # if j == pdist[self.hier_rcl(row,col,num_p)]:\n                        #     print('true ', end=\"\")\n                    col += 1\n                row += 1\n                print()\n        return pdist\n\n    # get dist from condensed pdist, based on #row, #col and len\n    def hier_rcl(self, i, j, l):\n        if i < j:\n            res = (i*(l-2)+j-i*(i-1)/2-1) \n        elif i > j:\n            res = (j*(l-2)+i-j*(j-1)/2-1) \n        # print(res)\n        return int(res)\n\n    ''' ################# Following is implementation for SOM clustering ################# '''\n    def som(self, init_centroids, a = 0.3, a_nb = 0.2, size_nb = 3, loss_threshold = 1e-16, learning_rate_threshold = 1e-10):\n        # self.display_points(init_centroids)\n\n        self._clusters.clear()\n        centroids = init_centroids\n        print(\"[b] before training:\\n\", centroids)\n        epoch = 0\n        while True:\n            epoch += 1\n            pre_centroids = np.array(centroids)\n            centroids = self.som_train(self._points, centroids, a, a_nb, size_nb, epoch)\n            loss = np.linalg.norm(pre_centroids - centroids)\n            print(\"loss: \", loss)\n            if loss <= loss_threshold:\n                break\n        print(\"after training:\\n\", centroids, \"\\nround: \", epoch)\n        self._clusters = self.som_assign(self._points, centroids)\n        self.print_clusters()\n\n        print(\"======================================\")\n\n        centroids = init_centroids\n        print(\"[c] before training:\\n\", centroids)\n        epoch = 0\n        pre_loss = 0\n        while True:\n            epoch += 1\n            pre_centroids = np.array(centroids)\n            # TODO: epoch from 0 or 1?\n            a -= 0.02\n            a_nb -= 0.02\n            centroids = self.som_train(self._points, centroids, a, a_nb, size_nb, epoch)\n            loss = np.linalg.norm(pre_centroids - centroids)\n            pre_loss = loss\n            print(\"loss: \", loss)\n            if loss <= loss_threshold or a <= learning_rate_threshold or a_nb <= learning_rate_threshold:\n                break\n        print(\"after training:\\n\", centroids, \"\\nround: \", epoch, \", a=\", a, \", a_nb=\", a_nb)\n        self._clusters = self.som_assign(self._points, centroids)\n        self.print_clusters()\n\n        return self._clusters\n\n    def som_train(self, examples, centroids, a, a_nb, size_nb, cur_round):\n        # print(\"round: \", cur_round)\n        for example in examples:\n            # select winner centroid\n            min_dist = 1000\n            closest_cent = 0\n            for ind in range(len(centroids)):\n                dist = self.eucl_dist(centroids[ind], example)\n                if dist < min_dist:\n                    min_dist = dist\n                    closest_cent = ind\n            # print(closest_cent, centroids[closest_cent], min_dist) \n            # look for winner's neighbours\n            nb_inds = list()\n            for nb_i in range(len(centroids)):\n                if nb_i != closest_cent:\n                    nb_inds.append(nb_i)\n            # update winner\n            centroids[closest_cent] += a * ( example - centroids[closest_cent] )\n            # update winner's neighbours\n            for i in range(size_nb):\n                centroids[nb_inds[i]] += a_nb * (example - centroids[nb_inds[i]])\n        return centroids\n\n    def som_assign(self, examples, centroids):\n        self._clusters = list()\n        # create clusters\n        for ind in range(len(centroids)):\n            self._clusters.append(np.array([centroids[ind]]))\n        for example in examples:\n            min_dist = 1000\n            closest_cent = 0\n            for ind in range(len(centroids)):\n                dist = self.eucl_dist(centroids[ind], example)\n                if dist < min_dist:\n                    min_dist = dist\n                    closest_cent = ind\n            # print(closest_cent, min_dist)\n            self._clusters[closest_cent] = np.append(self._clusters[closest_cent], np.array([example]), axis=0)\n        return self._clusters\n\n    # a special case of minkovski-distance with 2 as lambda \n    def eucl_dist(self, vec1, vec2):\n        # return self.mink_dist(vec1, vec2, 2)\n        return np.linalg.norm(vec1 - vec2)\n\n    # a special case of minkovski-distance with 1 as lambda \n    def city_dist(self, vec1, vec2):\n        # return self.mink_dist(vec1, vec2, 1)\n        return sum(abs(vec1[dim] - vec2[dim]) for dim in range(len(vec1)))\n\n    def mink_dist(self, vec1, vec2, lmd = 3):\n        return (sum((abs(vec1[dim] - vec2[dim]) ** lmd) for dim in range(len(vec1))) ** (1 / lmd))\n\n    def display_points(self, points):\n        plt.plot(points)\n        plt.show()\n\n    def display_clusters(self):\n        # plot self._clusters\n        return self._clusters\n\n    def print_clusters(self):\n        cluster_num = 0\n        for cluster in self._clusters:\n            cluster_num += 1\n            print(\"cluster\", cluster_num)\n            print(cluster)\n\n    def print_centroids(self):\n        cent_num = 0\n        for cent in self._centroids:\n            cent_num += 1\n            print(\"centroid\", cent_num, \":\", cent)\n\ndef main():\n    # configuration\n    data_path = \"./data_points\"\n    # create my clusterers\n    my_clusterers = Clusterers(data_path)\n\n    # run k-means\n    init_centroids_kmeans = np.array([[1.8, 2.3], [2.3, 1.4]])\n    lambda_kmeans_mink = 3\n    my_clusterers.k_means(init_centroids_kmeans)\n\n    # run hierarchical\n    my_clusterers.hierarchical()\n\n    # run som\n    init_centroids_som = np.array([[1, 3.1], [2, 2.2], [1.5, 2.1], [3.1, 1.1]])\n    my_clusterers.som(init_centroids_som)\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "6cc0d5d1cc9e40d896ec62783a0f07c2d7e9d6b5", "size": 15806, "ext": "py", "lang": "Python", "max_stars_repo_path": "dm/2_3_4_clustering.py", "max_stars_repo_name": "gypleon/codesCloud", "max_stars_repo_head_hexsha": "bc779fd3485b925ff5e5345e725a97d6ce262a2b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dm/2_3_4_clustering.py", "max_issues_repo_name": "gypleon/codesCloud", "max_issues_repo_head_hexsha": "bc779fd3485b925ff5e5345e725a97d6ce262a2b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dm/2_3_4_clustering.py", "max_forks_repo_name": "gypleon/codesCloud", "max_forks_repo_head_hexsha": "bc779fd3485b925ff5e5345e725a97d6ce262a2b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7135678392, "max_line_length": 174, "alphanum_fraction": 0.5464380615, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.9005297894548548, "lm_q1q2_score": 0.8578213754426564}}
{"text": "import numpy as np\nimport matplotlib.pylab as plt\n\ndef funcion(x):\n    return x**5 - 2*(x**4) - 10*(x**3) + 20*(x**2) + 9*x - 18\n\nxx=np.linspace(-3.5,3.5,100)\n\nplt.figure()\nplt.plot(xx,funcion(xx))\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.title('Gráfica de la función')\nplt.grid()\nplt.savefig('NRpoli.pdf')\nplt.close()\n\ndef NR(x,funcion,precision=1*(10**-5)):\n    N=0\n    dx=3**-1\n    for i in range(10000):\n        F=funcion(x)\n        if(abs(F)<precision):\n            break\n        df= (funcion(x+(dx/2))-funcion(x-(dx/2)))/dx\n        dx=-F/df\n        x+=dx\n        N+=1\n    return x,N\n\n# x_guess = -3\nprint('')\n\nxmenos3,Nmenos3=NR(-3,funcion)\n\nprint('Con un x_guess inicial de -3 el valor de la raíz X0r da: ',xmenos3,'y el valor de f(X0r) da: ',funcion(xmenos3))\n\n# x_guess = -1\nprint('')\n\nxmenos1,Nmenos1=NR(-1,funcion)\n\nprint('Con un x_guess inicial de -1 el valor de la raíz X1r da: ',xmenos1,'y el valor de f(X1r) da: ',funcion(xmenos1))\n\n\n# Número de iteraciones\n\nxx2=np.linspace(-4,4,1000)\nNs=np.zeros(len(xx2))\nraices=np.zeros(len(xx2))\n\nfor i in range(len(xx2)):\n    raiz,N=NR(xx2[i],funcion,precision=1*(10**-10))\n    Ns[i]=N\n    raices[i]=raiz\n    \nplt.figure()\nplt.scatter(xx2,Ns,s=15)\nplt.xlabel('X_guess')\nplt.ylabel('No. Iteraciones')\nplt.title('Número de iteraciones')\nplt.grid()\nplt.savefig('NR_itera.pdf')\nplt.close()\n\nplt.figure()\nplt.scatter(xx2,raices,s=15)\nplt.xlabel('X_guess')\nplt.ylabel('Raíz')\nplt.title('Raíces encontradas')\nplt.grid()\nplt.savefig('NRxguess.pdf')\nplt.close()\n\nprint('')\nprint('Se puede observar claramente que los puntos de X_guess en los que el método necesita una mayor cantidad de iteraciones (Gráfica NR_itera.pdf) está correlacionado con las partes de la función (Gráfica NRpoli.pdf) en las que su derivada es cercana a cero. Esto se debe a que el método busca puntos en el eje x que se crucen con la pendiente de la funcion de x0, lo que significa que esos nuevos puntos de x serán muy lejanos del x0 y el método necesitará mucho más tiempo para encontrar una raíz en la que la función de 0.')\nprint('')\nprint('Además, se puede observar que también hay una correlación con los tramos de X_guess (Gráfica NRxguess.pdf) en los que la raiz encontrada es variable. Esto se da por la misma razón de que la distancia entre nuevos puntos de x y el x anterior es muy grande y los ceros encontrados son de una parte lejana de la función.')\n", "meta": {"hexsha": "2cbe0be47fabe6e5c8089a072f802efdbf8fd67b", "size": 2380, "ext": "py", "lang": "Python", "max_stars_repo_path": "CendalesLuis_hw1/NR.py", "max_stars_repo_name": "LuisCendales/M-todos_Computacionales", "max_stars_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CendalesLuis_hw1/NR.py", "max_issues_repo_name": "LuisCendales/M-todos_Computacionales", "max_issues_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CendalesLuis_hw1/NR.py", "max_forks_repo_name": "LuisCendales/M-todos_Computacionales", "max_forks_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1265822785, "max_line_length": 529, "alphanum_fraction": 0.6878151261, "include": true, "reason": "import numpy", "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574129515172, "lm_q2_score": 0.9005297787765765, "lm_q1q2_score": 0.8578213701205877}}
{"text": "# %%\n\n#!/anaconda3/bin/python\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D  # for surface plot\n\n\n# %%\ndef featureNormaliz(X):\n    X_norm = X\n    mu = np.mean(X, axis=0)\n    sigma = np.std(X, axis=0, ddof=1)  # ddof=1 除法使用N-1\n    X_norm = (X - mu) / sigma\n    return X_norm, mu, sigma\n\n\ndef gradientDescentMulti(X, y, theta, alpha, num_iters):\n    m = len(y)\n    n = np.size(X, axis=1)\n    J_history = np.zeros([num_iters, 1])\n    for iter in np.arange(1, num_iters + 1):\n        delta = 1 / m * (X.T.dot(X).dot(theta) - X.T.dot(y).reshape(n, 1))\n        theta = theta - alpha * delta\n        J_history[iter - 1] = computeCostMulti(X, y, theta)\n    return theta, J_history\n\n\ndef computeCostMulti(X, y, theta):\n    m = len(y)\n    J = sum((X.dot(theta) - y.reshape(m, 1))**2) / 2 / m\n    return J\n\n\ndef normalEqn(X,y):\n    theta = np.linalg.pinv(X.T.dot(X)).dot(X.T).dot(y) # pinv(X' * X) * X' * y\n    return theta\n\n\ndata = pd.read_csv('ex1data2.txt', header=-1)\ndata = np.asarray(data)\nX = data[:, (0, 1)]\ny = data[:, 2]\nm = len(y)\n\n#   %% ================ Part 1: Feature Normalization ================\n\n#   对所有特征做归一化\n\nX, mu, sigma = featureNormaliz(X)\n\n#   在第一行添加1，用于thete0的计算\nX = np.append(np.ones((m, 1)), X, axis=1)\n\n#   %% ================ Part 2: Gradient Descent ================\nalpha = 0.1\nnum_iters = 50\ntheta = np.zeros((3, 1))  #  如果要扩展至任意维度也是可以的，这里已经有提示了n\n\ntheta, J_history0_01 = gradientDescentMulti(X, y, theta, alpha, num_iters)\n\nalpha = 0.3\nnum_iters = 50\ntheta = np.zeros((3, 1))  #  如果要扩展至任意维度也是可以的，这里已经有提示了n\n\ntheta, J_history0_03 = gradientDescentMulti(X, y, theta, alpha, num_iters)\n\nalpha =  1\nnum_iters = 50\n\ntheta = np.zeros((3, 1))\ntheta, J_history0_1 = gradientDescentMulti(X, y, theta, alpha, num_iters)\n\nfig, ax = plt.subplots()\n\nax.plot(J_history0_01, 'r-')\nax.hold\nax.plot(J_history0_03, 'g-')\nax.hold\nax.plot(J_history0_1, 'b-')\n\nax.set(xlabel='Number of iterations', ylabel='Cost J')\nplt.legend(('alpha = 0.01','alpha = 0.03','alpha = 0.1'))\n\nplt.show()\n\n# %% ================ Part 3: Normal Equations ================\n\ndata = pd.read_csv('ex1data2.txt', header=-1)\ndata = np.asarray(data)\nX = data[:, (0, 1)]\ny = data[:, 2]\nm = len(y)\n\nX = np.append(np.ones((m, 1)), X, axis=1)\n\ntheta = normalEqn(X,y)\n\nprint(theta)\n\n# %% ", "meta": {"hexsha": "b540533d1374a32060de5fbc7a551085557b29d7", "size": 2321, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear_Regression/ex1_multi.py", "max_stars_repo_name": "yeli7068/machine-learning-in-python3", "max_stars_repo_head_hexsha": "1353c410f5ba96bc444ec0faa78044741db78afb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Linear_Regression/ex1_multi.py", "max_issues_repo_name": "yeli7068/machine-learning-in-python3", "max_issues_repo_head_hexsha": "1353c410f5ba96bc444ec0faa78044741db78afb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear_Regression/ex1_multi.py", "max_forks_repo_name": "yeli7068/machine-learning-in-python3", "max_forks_repo_head_hexsha": "1353c410f5ba96bc444ec0faa78044741db78afb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5339805825, "max_line_length": 78, "alphanum_fraction": 0.6010340371, "include": true, "reason": "import numpy", "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.9005297794439688, "lm_q1q2_score": 0.857821368331437}}
{"text": "# solutions.py\n\"\"\"Volume 1A: Linear Systems. Solutions file.\"\"\"\n\nimport numpy as np\nfrom time import time\nfrom scipy import sparse\nfrom scipy import linalg as la\nfrom scipy.sparse import linalg as spla\nfrom matplotlib import pyplot as plt\n\n\n# Problem 1\ndef ref(A):\n    \"\"\"Reduce the square matrix A to REF. You may assume that A is invertible\n    and that a 0 will never appear on the main diagonal. Avoid operating on\n    entries that you know will be 0 before and after a row operation.\n    \"\"\"\n    A = np.array(A, dtype=np.float, copy=True)\n    m,n = A.shape\n    for j in xrange(n):\n        for i in xrange(j+1, m):\n            A[i,j:] -= A[j,j:] * A[i,j] / A[j,j]\n    return A\n\n\n# Problem 2\ndef lu(A):\n    \"\"\"Compute the LU decomposition of the square matrix A. You may assume the\n    decomposition exists and requires no row swaps.\n\n    Returns:\n        L ((n,n) ndarray): The lower-triangular part of the decomposition.\n        U ((n,n) ndarray): The upper-triangular part of the decomposition.\n    \"\"\"\n    m, n = A.shape\n    U = np.array(A, dtype=np.float, copy=True)\n    L = np.eye(n)\n    for j in xrange(n):\n        for i in xrange(j+1, m):\n            L[i,j] = U[i,j]/U[j,j]\n            U[i,j:] -= L[i,j]*U[j,j:]\n    return L,U\n\n\n# Problem 3\ndef solve(A, b):\n    \"\"\"Use the LU decomposition and back substitution to solve the linear\n    system Ax = b. You may assume that A is invertible (hence square).\n    \"\"\"\n    m, n = A.shape\n    L, U = lu(A)\n\n    # First solve Ly = Pb (assume P = I).\n    y = np.zeros(n)\n    for k in xrange(n):\n        y[k] = b[k] - np.dot(L[k,:k], y[:k])\n\n    # Now solve Ux = y.\n    x = np.zeros(n)\n    for k in reversed(xrange(n)):\n        x[k] = (y[k] - np.dot(U[k,k:], x[k:])) / U[k,k]\n\n    return x\n\n\n# Problem 4\ndef prob4(N=11):\n    \"\"\"Time different scipy.linalg functions for solving square linear systems.\n    Plot the system size versus the execution times. Use log scales if needed.\n    \"\"\"\n    domain = 2**np.arange(1,N+1)\n    inv, solve, lu_factor, lu_solve = [], [], [], []\n\n    for n in domain:\n        A = np.random.random((n,n))\n        b = np.random.random(n)\n\n        start = time()\n        la.inv(A).dot(b)\n        inv.append(time()-start)\n\n        start = time()\n        la.solve(A, b)\n        solve.append(time()-start)\n\n        start = time()\n        x = la.lu_factor(A)\n        la.lu_solve(x, b)\n        lu_factor.append(time()-start)\n\n        start = time()\n        la.lu_solve(x, b)\n        lu_solve.append(time()-start)\n\n    plt.subplot(121)\n    plt.plot(domain, inv, '.-', lw=2, label=\"la.inv()\")\n    plt.plot(domain, solve, '.-', lw=2, label=\"la.solve()\")\n    plt.plot(domain, lu_factor, '.-', lw=2,\n                                    label=\"la.lu_factor() and la.lu_solve()\")\n    plt.plot(domain, lu_solve, '.-', lw=2, label=\"la.lu_solve() alone\")\n    plt.xlabel(\"n\"); plt.ylabel(\"Seconds\")\n    plt.legend(loc=\"upper left\")\n\n    plt.subplot(122)\n    plt.loglog(domain, inv, '.-', basex=2, basey=2, lw=2)\n    plt.loglog(domain, solve, '.-', basex=2, basey=2, lw=2)\n    plt.loglog(domain, lu_factor, '.-', basex=2, basey=2, lw=2)\n    plt.loglog(domain, lu_solve, '.-', basex=2, basey=2, lw=2)\n    plt.xlabel(\"n\")\n\n    plt.suptitle(\"Problem 4 Solution\")\n    plt.show()\n\n\n# Problem 5\ndef prob5(n):\n    \"\"\"Return a sparse n x n tridiagonal matrix with 2's along the main\n    diagonal and -1's along the first sub- and super-diagonals.\n    \"\"\"\n    return sparse.diags([2,-1,2], [-1,0,1], shape=(n,n))\n\n\n# Problem 6\ndef prob6(N=10):\n    \"\"\"Time regular and sparse linear system solvers. Plot the system size\n    versus the execution times. As always, use log scales where appropriate.\n    \"\"\"\n    domain = 2**np.arange(2,N+1)\n    solve, spsolve = [], []\n\n    for n in domain:\n        A = prob5(n).tocsr()\n        b = np.random.random(n)\n\n        start = time()\n        spla.spsolve(A, b)\n        spsolve.append(time()-start)\n\n        A = A.toarray()\n        start = time()\n        la.solve(A, b)\n        solve.append(time()-start)\n\n    plt.subplot(121)\n    plt.plot(domain, spsolve, '.-', lw=2, label=\"spla.spsolve()\")\n    plt.plot(domain, solve, '.-', lw=2, label=\"la.solve()\")\n    plt.xlabel(\"n\"); plt.ylabel(\"Seconds\")\n    plt.legend(loc=\"upper left\")\n\n    plt.subplot(122)\n    plt.loglog(domain, spsolve, '.-', basex=2, basey=2, lw=2)\n    plt.loglog(domain, solve, '.-', basex=2, basey=2, lw=2)\n    plt.xlabel(\"n\")\n\n    plt.suptitle(\"Problem 6 Solution\")\n    plt.show()\n\n\n# Additional Material =========================================================\n\ndef ref_fast(A):\n    \"\"\"Alternate REF using an outer product. Fast, but not very intuitive.\"\"\"\n    for i in xrange(A.shape[0]):\n        A[i+1:,i:] -= np.outer(A[i+1:,i]/A[i,i], A[i,i:])\n\ndef lu2_fast(A):\n    \"\"\"Alternative LU decomposition using an outer product.\"\"\"\n    U = A.copy()\n    L = np.eye(A.shape[0])\n    for i in xrange(A.shape[0]-1):\n        L[i+1:,i] = U[i+1:,i] / U[i,i]\n        U[i+1:,i:] -= np.outer(L[i+1:,i], U[i,i:])\n    return L, U\n\ndef lu_inplace(A):\n    \"\"\"Compute the LU decomposition of the square matrix A *IN PLACE*.\"\"\"\n    for j in xrange(A.shape[0]-1):\n        for i in xrange(j+1, A.shape[0]):\n            A[i,j] /= A[j,j]\n            A[i,j+1:] -= A[i,j] * A[j,j+1:]\n\ndef lu_det(A):\n    \"\"\"Compute det(A) using the LU decomposition (via la.lu_factor()).\"\"\"\n    lu, piv = la.lu_factor(A)\n\n    # Determine if there were an even or odd number of row swaps.\n    s = (piv != np.arange(A.shape[0])).sum() % 2\n    return ((-1)**s) * lu.diagonal().prod()\n\ndef cholesky(A):\n    L = np.zeros_like(A)\n    for i in xrange(A.shape[0]):\n        for j in xrange(i):\n            L[i,j]=(A[i,j] - np.inner(L[i,:j], L[j,:j])) / L[j,j]\n        sl = L[i,:i]\n        L[i,i] = sqrt(A[i,i] - np.inner(sl, sl))\n    return L\n\ndef cholesky_inplace(A):\n    for i in xrange(A.shape[0]):\n        A[i,i+1:] = 0.\n        for j in range(i):\n            A[i,j] = (A[i,j] - np.inner(A[i,:j],A[j,:j])) / A[j,j]\n        sl = A[i,:i]\n        A[i,i] = sqrt(A[i,i] - np.inner(sl, sl))\n\ndef cholesky_solve(A, B):\n    for j in xrange(A.shape[0]):\n        B[j] /= A[j,j]\n        for i in xrange(j+1, A.shape[0]):\n            B[i] -= A[i,j] * B[j]\n    for j in xrange(A.shape[0]-1, -1, -1):\n        B[j] /= A[j,j]\n        for i in xrange(j):\n            B[i] -= A[j,i] * B[j]\n\n\n", "meta": {"hexsha": "35a8100fa6196732663fdfcea4330d281ddc2f48", "size": 6280, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol1A/LinearSystems/solutions.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vol1A/LinearSystems/solutions.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vol1A/LinearSystems/solutions.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 28.8073394495, "max_line_length": 79, "alphanum_fraction": 0.5472929936, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.921921834855049, "lm_q1q2_score": 0.8578097874946612}}
{"text": "from numpy import *\r\nfrom scipy import *\r\nfrom pylab import *\r\n\r\nimport numpy.random as random\r\n\r\nimport pdb\r\n\r\nion()\r\n\r\ni = 1j\r\n\r\ndef my_slow_fft(f):\r\n    # a slow ifft that **CAN'T** interpolate!\r\n    N = len(f)\r\n    F = zeros(N, dtype=complex)\r\n    for k in range(N):\r\n        for n in range(N):\r\n            F[k] += f[n]*e**(-2.0*pi*i*k*n/N)\r\n    return F\r\n    \r\ndef my_slow_ifft(F):\r\n    # a slow ifft that **CAN'T** interpolate!\r\n    N = len(F)\r\n    f = zeros(N, dtype=complex)\r\n    for n in range(N):\r\n        for k in range(N):\r\n            f[n] += F[k]*e**(2.0*pi*i*k*n/N)\r\n    return (1.0/N)*f\r\n\r\ndef my_slow_ifft_interp(F,t):\r\n    # a slow ifft that **CAN'T** interpolate!\r\n    N = len(F)\r\n    f = zeros(len(t), dtype=complex)\r\n    for n in range(len(t)):\r\n        for k in range(N):\r\n            f[n] += F[k]*e**(2.0*pi*i*k*t[n])\r\n    return (1.0/N)*f\r\n    \r\ndef my_correct_slow_ifft_interp(F,t):\r\n    # an ifft that **CAN** interpolate\r\n    N = len(F)\r\n    f = zeros(len(t), dtype=complex)\r\n    for n in range(len(t)):\r\n        for k in range(int(N/2)):\r\n            f[n] += F[k]*e**(2.0*pi*i*k*t[n])\r\n        for k in range(int(N/2),N):\r\n            f[n] += F[k]*e**(-2.0*pi*i*(N-k)*t[n])\r\n    return (1.0/N)*f\r\n    \r\nif __name__ == \"__main__\":\r\n    # Sample measurements\r\n    ts = linspace(0,1,num=21)\r\n    f = zeros(len(ts))\r\n    hf = int(len(ts)/2)\r\n    f[0:hf] = ts[0:hf]\r\n    #f[hf:] = e**-ts[hf:] + 0.5 - e**-0.5\r\n    f[hf:] = 1.0/ts[hf:] - 1.5\r\n    #f = ts*(ts-1)\r\n    #f = sin(ts*(2.*pi)) + cos(ts*(2.*pi))#-1.0*ts**2#exp(ts)\r\n    \r\n    F = fftshift(fft(f))\r\n    F_unshifted = fft(f)\r\n    ff = fftshift(ifftshift(f))\r\n    \r\n    # plot where we are so far\r\n    # this includes F^-1{F(f)} for now\r\n    figure(1)\r\n    plot(ts,f, 'bo-',markerfacecolor='none', mec='blue')\r\n    #ylim(-0.6,0.6)\r\n    title(\"Original Function\")\r\n    \r\n    figure(2)\r\n    plot(ts,F.real,ts,F.imag)\r\n    legend(('real', 'imaginary'))\r\n    title(\"Shifted Fourier Transform\")\r\n    \r\n    figure(22)\r\n    plot(ts,F_unshifted.real,ts,F_unshifted.imag)\r\n    legend(('real', 'imaginary'))\r\n    title(\"Unshifted Fourier Transform\")\r\n    \r\n    figure(3)\r\n    plot(ts,ff)\r\n    #ylim(-0.6,0.6)\r\n    title(\"Getting Back The Original\")\r\n    \r\n    # now interpolate\r\n    # new timestamps, m samples between former samples. \r\n    Nf = len(ts)\r\n    \r\n    t = linspace(0,1,num=len(ts)*3)\r\n    \r\n    Fs = my_slow_fft(f)\r\n    fm = my_slow_ifft(Fs)\r\n    \r\n    # using the Fourier Coefficients \"sas-is\"\r\n    fwi = my_slow_ifft_interp(F_unshifted,t)\r\n    fci = my_correct_slow_ifft_interp(F_unshifted,t)\r\n    \r\n    figure(4)\r\n    plot(ts,Fs.real,ts,Fs.imag)\r\n    legend(('real', 'imaginary'))\r\n    title(\"My Unshifted Fourier Transform\")\r\n\r\n    figure(5)\r\n    plot(ts,f, 'bo-',markerfacecolor='none', mec='blue')\r\n    plot(ts,fm,'g^-',markerfacecolor='none', mec='green')\r\n    #ylim(-0.6,0.6)\r\n    title(\"Original Using My Inverse\")\r\n    \r\n    figure(500)\r\n    plot(ts,f, 'bo-',markerfacecolor='none', mec='blue')\r\n    plot(ts[:-1],my_correct_slow_ifft_interp(fft(f[:-1]),ts[:-1]),'g^-',markerfacecolor='none', mec='green')\r\n    #ylim(-0.6,0.6)\r\n    title(\"Original Using My Inverse Interp \")\r\n\t\r\n    figure(6)\r\n    plot(ts,f, 'bo-',markerfacecolor='none', mec='blue')\r\n    plot(t,fwi,'go-',markerfacecolor='none', mec='green')\r\n    #ylim(-0.6,0.6)\r\n    legend(('original', 'interpolatation'))\r\n    title(\"Interpolating with Fourier Coefficients, No Change\")\r\n    \r\n    figure(7)\r\n    plot(ts,f,'bo-',markerfacecolor='none', mec='blue')\r\n    plot(t[:-1],my_correct_slow_ifft_interp(fft(f[:-1]),t[:-1]),'g^-',markerfacecolor='none', mec='green')\r\n    #ylim(-0.6,0.6)\r\n    legend(('original', 'interpolatation'))\r\n    title(\"Interpolating with Fourier Coefficients Accounting for Aliasing\")\r\n    \r\n    show()", "meta": {"hexsha": "050f8352eccdc4afe6542ff28524482cae2c11ce", "size": 3780, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/int_fourier.py", "max_stars_repo_name": "dantaylor688/dantaylor688.github.io", "max_stars_repo_head_hexsha": "f430224693c94a7469826f88b88bd9b1460e1cc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/int_fourier.py", "max_issues_repo_name": "dantaylor688/dantaylor688.github.io", "max_issues_repo_head_hexsha": "f430224693c94a7469826f88b88bd9b1460e1cc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/int_fourier.py", "max_forks_repo_name": "dantaylor688/dantaylor688.github.io", "max_forks_repo_head_hexsha": "f430224693c94a7469826f88b88bd9b1460e1cc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6363636364, "max_line_length": 109, "alphanum_fraction": 0.5476190476, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551958, "lm_q2_score": 0.9046505408849362, "lm_q1q2_score": 0.8577485074618199}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport seaborn as sns\nfrom scipy.stats import t,norm,uniform\nfrom matplotlib.offsetbox import AnchoredText\nplt.style.use('ggplot')\n\n\ndef Markov_Monte_Carlo(x0, delta, num_samples):\n    \"\"\"\n    Returns samples from t-distribution\n    using Metropolis-Hastings algorithim\n    and an uniform distribution.\n    \"\"\"\n    X = np.zeros(num_samples)  # Samples\n    X[0] = x0\n    for i in range(1,num_samples):\n        r = np.random.uniform(-delta,delta)\n        y = X[i-1] + r\n        acc_ratio = min(np.log(t.pdf(y,2))-np.log(t.pdf(X[i-1],2)), 0)  # Acceptance ratio\n        u = np.random.uniform(0,1)\n        if np.log(u) <= acc_ratio:\n            X[i] = y\n        else:\n            X[i] = X[i-1] \n    return X\n\n\ndef MCMC_Plots(x0, delta_vec, num_samples):\n    half = len(delta_vec)//2\n    fig1 = plt.figure(figsize=(16,6), constrained_layout=True)\n    gs1 = fig1.add_gridspec(2,3)\n    ax = {}\n    for i, delta in enumerate(delta_vec[:half+1]):  \n        ax[i] = fig1.add_subplot(gs1[0, i]) \n        samples = Markov_Monte_Carlo(x0, delta, num_samples)\n        x = np.linspace(-8,8,num_samples)\n        z = t.pdf(x,2)\n        ax[i].plot(x, z, label='true density', color='cornflowerblue')\n        sns.kdeplot(samples, label='MCMC simulation', color='orchid', ax=ax[i])\n        ax[i].legend(fontsize=8)\n        at = AnchoredText('$\\delta$={}'.format(delta), loc='center left', frameon=True)\n        ax[i].add_artist(at)\n        ax[0].set_ylabel('Density')\n        ax[i].set_xlim([-8,8])\n    for i, delta in enumerate(delta_vec[half+1:]):  \n        ax[i] = fig1.add_subplot(gs1[1, i]) \n        samples = Markov_Monte_Carlo(x0, delta, num_samples)\n        x = np.linspace(-8,8,num_samples)\n        z = t.pdf(x,2)\n        ax[i].plot(x, z, label='true density', color='cornflowerblue')\n        sns.kdeplot(samples, label='MCMC simulation', color='orchid', ax=ax[i])\n        ax[i].legend(fontsize=8)\n        at = AnchoredText('$\\delta$={}'.format(delta), loc='center left', frameon=True)\n        ax[i].add_artist(at)\n        ax[0].set_ylabel('Density') \n        ax[i].set_xlim([-8,8])\n        \n        \ndef Quotient(n, mu, sigma, c):\n    return t.pdf(n,2)/(c*norm.pdf(n, mu, sigma))\n\n\ndef Supremum(mu, sigma):\n    x = np.linspace(-10,10,100)\n    q = norm.pdf(x, mu, sigma) / t.pdf(x,2)\n    c = max(q)\n    return c \n\n\ndef Rejection_Sampling1(mu, sigma, num_sim):\n    \"\"\"\n    Returns samples of a t-distribution using\n    rejection sampling method and a fixed \n    prob of acceptance. Candidate density is\n    a normal distribution.\n    \"\"\"\n    c = Supremum(mu, sigma)\n    sample1 = []\n    for i in range(num_sim):  \n        u = np.random.uniform(0,1)    \n        n = np.random.normal(mu, sigma)    \n        if u <= Quotient(n, mu, sigma, c):\n            sample1.append(n) \n    return [c, sample1]\n\n\ndef Rejection_Sampling2(mu, sigma, c0, num_sim):\n    \"\"\"\n    An alternative method. Prob of acceptance\n    is updated during the simulations.\n    \"\"\"\n    \n    c_list = []\n    sample2 = []\n    c = c0   \n    for i in range(num_sim):   \n        u = np.random.uniform(0,1)    \n        n = np.random.normal(mu, sigma)     \n        if u <= Quotient(n, mu, sigma, c):  \n            sample2.append(n) \n            c = max(c, norm.pdf(n, mu, sigma)/t.pdf(n,2))  \n            c_list.append(c)       \n    return [c_list, sample2]  \n\n\ndef Rejection_Comparison_Plots(mu, var_vec, c0, num_sim):\n    \n     \"\"\"It compares both methods for rejection sampling.\"\"\"\n        \n    fig, ax = plt.subplots(len(var_vec),2, figsize=(12,10))\n    x = np.linspace(-8,8,num_sim)\n    for i, v in enumerate(var_vec):\n        [c, sample1] = Rejection_Sampling1(mu, np.sqrt(v), num_sim)\n        [c_list, sample2] = Rejection_Sampling2(mu, np.sqrt(v), c0, num_sim)\n        ax[i,0].plot(x, t.pdf(x,2), label='true density', color='black')\n        sns.kdeplot(sample1, label='first approach', color='cornflowerblue', ax=ax[i,0])\n        sns.kdeplot(sample2, label='alternative method', color='orchid', ax=ax[i,0])\n        ax[0,0].set_title('KDE plots')\n        ax[i,0].legend(fontsize=10)\n        ax[-1,0].set_xlabel('x', fontsize=14)\n        ax[i,0].set_xlim([-8,8])\n        ax[i,0].text(-6,0.2,'Candidate density:\\n$\\mu=0,\\;\\sigma^2$={}'.format(v))\n        ax[i,1].axhline(y=c, label='4', color='r', linestyle='--', alpha=0.6)\n        ax[i,1].plot(np.arange(len(c_list)), c_list, label='5', color='b', alpha=0.6)\n        ax[0,1].set_title('Plots for $c$', fontsize=12)\n        ax[i,1].legend(['$c$ in the first approach','$c$ in the second approach'], fontsize=10)\n        ax[-1,1].set_xlabel('steps', fontsize=14)\n        ax[i,1].set_xlim(0,50)\n        plt.suptitle('Rejection sampling method with fixed $c$ and its alternative', y=1.05)\n        plt.tight_layout()\n        \n        \ndef MCMC_Rejection_Plots(x0, delta, mu, v, s:list):\n    \n    \"\"\"It compares Monte-Carlo Narkov chain with rejection sampling method.\"\"\"\n    \n    fig, ax = plt.subplots(len(s), figsize=(10,10))\n    for i, num_samples in enumerate(s):\n        first_mathod = Markov_Monte_Carlo(x0, delta, num_samples)\n        [c, second_method] = Rejection_Sampling1(mu, np.sqrt(v), num_samples)\n        x = np.linspace(-8,8,num_samples) \n        ax[i].plot(x, t.pdf(x,2), label='1', color='black')\n        sns.kdeplot(first_mathod, label='1', color='cornflowerblue', ax=ax[i])\n        sns.kdeplot(second_method, label='2', color='orchid', ax=ax[i])\n        ax[i].legend(['true density','MCMC','rejection sampling'], fontsize=10)\n        ax[i].text(-6,0.25,'number of simulations={}'.format(num_samples), fontsize=12)\n        ax[i].set_ylabel('KDE', fontsize=14)\n        ax[i].set_xlim([-8,8])\n        plt.suptitle('Comparison between MCMC and rejection sampling,\\n for MCMC:'\\\n                     r' $\\delta=1$ and for rejection sampling: $\\mu=0,\\,\\sigma^2=3$'\\\n                     ' and $c\\approx1.25$', y=1.05)\n        plt.tight_layout()  \n      \n    \n# An Example\nx0 = 0\ndelta = 1  \nmu = 0   \nv = 3\ns = [5000, 10000, 50000]\n\nMCMC_Rejection_Plots(x0, delta, mu, v, s)        \n", "meta": {"hexsha": "b5128e640d7a1a6b8dc1991f7c2b278e7f6773cb", "size": 6139, "ext": "py", "lang": "Python", "max_stars_repo_path": "py files/Markov chain Monte Carlo.py", "max_stars_repo_name": "mdaneshv/Stochastic-Simulations", "max_stars_repo_head_hexsha": "2c96b37f96bb2547cdeb9d74b1d9a067db002560", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-30T02:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-30T08:32:49.000Z", "max_issues_repo_path": "py files/Markov chain Monte Carlo.py", "max_issues_repo_name": "mdaneshv/Stochastic-Simulations", "max_issues_repo_head_hexsha": "2c96b37f96bb2547cdeb9d74b1d9a067db002560", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "py files/Markov chain Monte Carlo.py", "max_forks_repo_name": "mdaneshv/Stochastic-Simulations", "max_forks_repo_head_hexsha": "2c96b37f96bb2547cdeb9d74b1d9a067db002560", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.325443787, "max_line_length": 95, "alphanum_fraction": 0.590649943, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802362, "lm_q2_score": 0.904650530602188, "lm_q1q2_score": 0.8577485043387871}}
{"text": "\"\"\"\nAuthor : Achintya Gupta\nDate Created : 22-09-2020\n\"\"\"\n\n\"\"\"\nProblem Statement\n------------------------------------------------\nQ)  The following iterative sequence is defined for the set of positive integers:\n                n → n/2 (n is even)\n                n → 3n + 1 (n is odd)\n    Using the rule above and starting with 13, we generate the following sequence:\n    13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1\n    It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem),\n    it is thought that all starting numbers finish at 1.\n    Which starting number, under one million, produces the longest chain?\n    NOTE: Once the chain starts the terms are allowed to go above one million.\n\"\"\"\nfrom utils import timing_decorator, find_factors\nimport numpy as np\n\nchain_mapping={}\n\ndef get_chainlen(num):\n    global chain_mapping\n    chain_len=0\n    chain=[num]\n    while num!=1:\n        if num in chain_mapping:\n            return len(chain)+chain_mapping[num]-1\n        if num%2==0:\n            num=int(num/2)\n        else:\n            num=int(3*num+1)\n        chain.append(num)\n    chain_len = len(chain)\n    for i in range(len(chain)):\n        if i not in chain_mapping:\n            chain_mapping[chain[i]] = len(chain[i:])\n    return chain_len\n\n@timing_decorator\ndef logest_collatz(N=1e6):\n    num = 0\n    cno = 0\n    clen = 0\n    \n    for i in range(1,int(N)):\n        curr_clen = get_chainlen(i)\n        if curr_clen>clen:\n            cno = i\n            clen=curr_clen\n    print(f'Starting number with longest collatz chain under < {N} is {cno}, with chain length of {clen}')\n\nlogest_collatz()", "meta": {"hexsha": "704f725887d32cd25ff7a5c4c8ed4fc99854c605", "size": 1684, "ext": "py", "lang": "Python", "max_stars_repo_path": "solutions/solution14.py", "max_stars_repo_name": "ag-ds-bubble/projEuler", "max_stars_repo_head_hexsha": "eac7fc0159f1324065c471ef814c88f38284934a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solutions/solution14.py", "max_issues_repo_name": "ag-ds-bubble/projEuler", "max_issues_repo_head_hexsha": "eac7fc0159f1324065c471ef814c88f38284934a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solutions/solution14.py", "max_forks_repo_name": "ag-ds-bubble/projEuler", "max_forks_repo_head_hexsha": "eac7fc0159f1324065c471ef814c88f38284934a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6181818182, "max_line_length": 147, "alphanum_fraction": 0.6116389549, "include": true, "reason": "import numpy", "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545392102523, "lm_q2_score": 0.904650527388829, "lm_q1q2_score": 0.8577485039426669}}
{"text": "'''\nlogsumexp.py\n\nProvides a numerically implementation of logsumexp function,\nsuch that no matter what 1-dimensional input array is provided,\nwe return a finite floating point answer that does not overflow or underflow.\n\nReferences\n----------\nSee the math here:\nhttps://www.cs.tufts.edu/comp/135/2020f/hw2.html#logsumexp\n'''\n\nimport numpy as np\n\n# No other imports allowed\n\ndef my_logsumexp(scores_N):\n    ''' Compute logsumexp on provided array in numerically stable way.\n\n    This function only handles 1D arrays.\n    The equivalent scipy function can handle arrays of many dimensions.\n\n    Args\n    ----\n    scores_N : 1D NumPy array, shape (N,)\n        An array of real values\n\n    Returns\n    -------\n    a : float\n        Result of the logsumexp computation\n\n    Examples\n    --------\n    >>> _ = np.seterr(all='raise') # Make any numerical issue raise error\n\n    # Example 1: an array without overflow trouble, so you get the basic idea\n    >>> easy_arr_N = np.asarray([0., 1., 0.1])\n\n    # Show that your code does OK on Example 1\n    >>> easy_ans = my_logsumexp(easy_arr_N)\n    >>> print(\"%.5f\" % (easy_ans))\n    1.57349\n\n    # Show that naive implementation does OK on Example 1\n    >>> naive_ans = np.log(np.sum(np.exp(easy_arr_N)))\n    >>> print(\"%.5f\" % (naive_ans))\n    1.57349\n\n    # Example 2: an array where overflow would occur in bad implementation\n    >>> tough_arr_N = [1000., 1001., 1002.]\n\n    # Show that naive implementation suffers from overflow on Example 2\n    >>> naive_ans = np.log(np.sum(np.exp(tough_arr_N)))\n    Traceback (most recent call last):\n    ...\n    FloatingPointError: overflow encountered in exp\n\n    # Show that your implementation does well on Example 2\n    >>> ans_that_wont_overflow = my_logsumexp(tough_arr_N)\n    >>> np.isfinite(ans_that_wont_overflow)\n    True\n    >>> print(\"%.5f\" % (ans_that_wont_overflow))\n    1002.40761\n    '''\n    scores_N = np.asarray(scores_N, dtype=np.float64)\n\n    # TODO compute logsumexp in numerically stable way\n    # See math on HW2 instructions page for the correct approach\n    return 0.0", "meta": {"hexsha": "6a92e47f1d9410425cd975ace57202af0f3b81e2", "size": 2074, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw2/logsumexp.py", "max_stars_repo_name": "ypark12/comp135-20f-assignments", "max_stars_repo_head_hexsha": "653ac71d59230563ec60276678569b313e744d1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-09-09T21:44:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-06T11:42:58.000Z", "max_issues_repo_path": "hw2/logsumexp.py", "max_issues_repo_name": "ypark12/comp135-20f-assignments", "max_issues_repo_head_hexsha": "653ac71d59230563ec60276678569b313e744d1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw2/logsumexp.py", "max_forks_repo_name": "ypark12/comp135-20f-assignments", "max_forks_repo_head_hexsha": "653ac71d59230563ec60276678569b313e744d1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2020-09-11T19:16:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T19:43:57.000Z", "avg_line_length": 29.2112676056, "max_line_length": 77, "alphanum_fraction": 0.6759884282, "include": true, "reason": "import numpy", "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.9161096124442243, "lm_q1q2_score": 0.8577396986393395}}
{"text": "###################Tools and metrics##################\n\n'''The functions in this python module compute \nalgebric metrics from adjacency matrices used in MANIA'''\n\nimport numpy as num\n\ndef AR(A):\n\t# Computes Assymetry ratio\n\tB=A-A.transpose()\n\ttotal_edges=sum(sum(A-num.diag(num.diag(A))))\n\teu=float(sum(sum(abs(B))))/2\n\tif total_edges==0:\n\t\treturn 1.0\n\treturn eu/total_edges\n\ndef NAR(A):\n\t# Computes the normalized asymmetry ratio\n\tl1,l2=num.shape(A)\n\tif l1!=l2:\n\t\tprint 'Error: Input matrix not square'\n\t\treturn None\n\tl=l1\n\ttotal_edges=sum(sum(A-num.diag(num.diag(A))))\n\tAR_rand=1-(float(total_edges)/(l*(l-1)))\n\tif AR_rand==0:\n\t\treturn float('inf')\n\treturn AR(A)/AR_rand\n\ndef sim(A1,A2,mode='jac'):\n\t# Jaccard similarity on edges\n\tl1,l2=num.shape(A1)\n\tif l1!=l2:\n\t\tprint 'Error: Input matrix not square'\n\t\treturn None\n\tl=l1\n\tl1,l2=num.shape(A1)\n\tif l1!=l or l2!=l:\n\t\tprint 'Error: Matrices must be of the same size'\n\t\treturn None\n\tif mode=='jac':\n\t\tP=A1+A2\n\t\tP=P-num.diag(num.diag(P))\n\t\tP[P>0]=1\n\t\tS=A1*A2\n\t\tS=S-num.diag(num.diag(S))\n\t\treturn float(sum(sum(S)))/sum(sum(P))\n\telse:\n\t\tS=A1*A2\n\t\tS=S-num.diag(num.diag(S))\n\t\tA1=A1-num.diag(num.diag(A1))\n\t\tA2=A2-num.diag(num.diag(A2))\n\t\tdenom=min(sum(sum(A1)),sum(sum(A2)))\n\t\treturn float(sum(sum(S)))/denom\n\ndef density(A):\n\t# returns the density of edges in A\n\tl1,l2=num.shape(A)\n\tif l1!=l2:\n\t\tprint 'Error: Input matrix not square'\n\t\treturn None\n\tl=l1\n\ttotal_edges=sum(sum(A-num.diag(num.diag(A))))\n\treturn float(total_edges)/(l*(l-1))\n", "meta": {"hexsha": "90da6ac1771a43918a2c80c42f5d65eb5bd14e3a", "size": 1487, "ext": "py", "lang": "Python", "max_stars_repo_path": "mania/utils.py", "max_stars_repo_name": "kamalshadi/mania", "max_stars_repo_head_hexsha": "2270bf5e1b8bb1a867513806d45f2fb5f7b1f427", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-24T23:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-24T23:30:20.000Z", "max_issues_repo_path": "mania/utils.py", "max_issues_repo_name": "kamalshadi/mania", "max_issues_repo_head_hexsha": "2270bf5e1b8bb1a867513806d45f2fb5f7b1f427", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mania/utils.py", "max_forks_repo_name": "kamalshadi/mania", "max_forks_repo_head_hexsha": "2270bf5e1b8bb1a867513806d45f2fb5f7b1f427", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8769230769, "max_line_length": 57, "alphanum_fraction": 0.6583725622, "include": true, "reason": "import numpy", "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966098909522, "lm_q2_score": 0.8991213691605411, "lm_q1q2_score": 0.8577313049842695}}
{"text": "# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as st\n\ndef gauss(mu,std,n=1000):\n    noise = np.random.normal(mu,std,n)\n    x = np.linspace(mu-3*std,mu+3*std,n)\n    y = st.norm.pdf(x,mu,std)\n    \n    #Timeseries\n    plt.figure()\n    plt.title(f\"Gaussian Time Series   μ={mu}   σ={std}\")\n    plt.xlabel(\"Index\")\n    plt.ylabel(\"Value\")\n    plt.plot(range(len(noise)),noise)\n    plt.savefig(f\"Gaussian_Timeseries_{mu}_{std}.pdf\")\n    plt.savefig(f\"Gaussuan_Timeseries_{mu}_{std}.png\")\n    \n    #Histogram\n    plt.figure()\n    plt.title(f\"Gaussian   μ={mu}   σ={std}   bins={int(n/30)}\")\n    plt.xlabel(\"Value\")\n    plt.ylabel(\"Probability\")\n    plt.hist(noise,bins=int(n/30),density=True,label='Data')\n    plt.plot(x,y,color='red',label='Gaussian')\n    plt.legend()\n    plt.savefig(f\"Gaussian_{mu}_{std}.pdf\")\n    plt.savefig(f\"Gaussian_{mu}_{std}.png\")\n\ndef poisson(mu,n=1000):\n    noise = np.random.poisson(mu,n)    \n    bins = np.arange(min(noise),max(noise)+1,1)\n    \n    #Timeseries\n    plt.figure()\n    plt.title(f\"Poisson Time Series   μ={mu}\")\n    plt.xlabel(\"Index\")\n    plt.ylabel(\"Value\")\n    plt.plot(range(len(noise)),noise)\n    plt.savefig(f\"Poisson_Timeseries_{mu}.pdf\")\n    plt.savefig(f\"Poisson_Timeseries_{mu}.png\")\n    \n    \n    #Sharp Histogram\n    x = np.arange(0,max(noise),0.01)\n    y = st.poisson.pmf(x,mu)\n    \n    plt.figure()\n    plt.title(f\"Poisson Sharp   μ={mu}   n={1000}\")\n    plt.xlabel(\"Value\")\n    plt.ylabel(\"Probability\")\n    plt.hist(noise,bins=bins,align='left',density=True,label='Data')\n    plt.xticks(bins)\n    plt.plot(x,y,color='red',label='Poisson')\n    plt.legend()\n    plt.savefig(f\"Poisson_Sharp_{mu}.pdf\")\n    plt.savefig(f\"Poisson_Sharp_{mu}.png\")\n    \n    #Fuzzy Histogram\n    x = np.arange(0,max(noise),1)\n    y = st.poisson.pmf(x,mu)\n    \n    plt.figure()\n    plt.title(f\"Poisson Fuzzy   μ={mu}   n={1000}\")\n    plt.xlabel(\"Value\")\n    plt.ylabel(\"Probability\")\n    plt.hist(noise,bins=bins,align='left',density=True,label='Data')\n    plt.xticks(bins)\n    plt.plot(x,y,color='red',label='Poisson')\n    plt.legend()\n    plt.savefig(f\"Poisson_Fuzzy_{mu}.pdf\")\n    plt.savefig(f\"Poisson_Fuzzy_{mu}.png\")\n\n#1\ngauss(0,1)\n\n#2\ngauss(10.345,2.338)\n\n#3\npoisson(2)\n\n#4\npoisson(3.45)", "meta": {"hexsha": "d273c5f15ddfbf0dd55e7d2eec74cfac5bb99aac", "size": 2270, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW2/HW2.py", "max_stars_repo_name": "wjwainwright/PHYS689", "max_stars_repo_head_hexsha": "55cf63681109171762ca06c7e499dd8984b3f130", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW2/HW2.py", "max_issues_repo_name": "wjwainwright/PHYS689", "max_issues_repo_head_hexsha": "55cf63681109171762ca06c7e499dd8984b3f130", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW2/HW2.py", "max_forks_repo_name": "wjwainwright/PHYS689", "max_forks_repo_head_hexsha": "55cf63681109171762ca06c7e499dd8984b3f130", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3953488372, "max_line_length": 68, "alphanum_fraction": 0.622907489, "include": true, "reason": "import numpy,import scipy", "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.8991213678089741, "lm_q1q2_score": 0.8577313025181843}}
{"text": "# # https://www.geeksforgeeks.org/implement-sigmoid-function-using-numpy/\nimport copy\nimport numpy as np\nnp.random.seed(0)\n\n# compute sigmoid nonlinearity\ndef sigmoid(x):\n    output = 1/(1+np.exp(-x))\n    return output\n\n# convert output of sigmoid function to its derivative\ndef sigmoid_output_to_derivative(output):\n    return output*(1-output)\n\n\n\n# sigmoid_test = sigmoid([22,44])\n\nimport matplotlib.pyplot as plt \nimport numpy as np \nimport math \n  \n# x = np.linspace(-10, 10, 100)\nx =1\n\nx = [-1,0,0.5,1]\n# x = [-1.33,0.33,0.533,1.33]\n# z = 1/(1 + np.exp(-x)) \n\n# for val in x:\n#     print(val,sigmoid(val))\n\nfor val in x:\n    print(val,sigmoid(val),sigmoid_output_to_derivative(sigmoid(val)))\n\n\n\n# 1 0.7310585786300049\n# 0.5 0.6224593312018546\n# 0 0.5\n# -1 0.2689414213699951\n\n# plt.plot(x, z) \n# plt.xlabel(\"x\") \n# plt.ylabel(\"Sigmoid(X)\") \n  \n# plt.show() ", "meta": {"hexsha": "6ff8c32883c24d13faa7542d4ff231aa28ada1af", "size": 862, "ext": "py", "lang": "Python", "max_stars_repo_path": "sigmoid_alignment.py", "max_stars_repo_name": "timothyyu/nn-p", "max_stars_repo_head_hexsha": "8f0e38e8dcced8451bdd85906cad971db9cc282a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sigmoid_alignment.py", "max_issues_repo_name": "timothyyu/nn-p", "max_issues_repo_head_hexsha": "8f0e38e8dcced8451bdd85906cad971db9cc282a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sigmoid_alignment.py", "max_forks_repo_name": "timothyyu/nn-p", "max_forks_repo_head_hexsha": "8f0e38e8dcced8451bdd85906cad971db9cc282a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-18T16:09:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-18T16:09:04.000Z", "avg_line_length": 18.3404255319, "max_line_length": 73, "alphanum_fraction": 0.6693735499, "include": true, "reason": "import numpy", "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660936744719, "lm_q2_score": 0.8991213705121083, "lm_q1q2_score": 0.8577313015666734}}
{"text": "import numpy as np \r\nimport scipy.optimize as op \r\nimport scipy.linalg as la\r\nimport numdifftools as nd \r\nfrom matplotlib import pyplot as plt\r\nfrom mpl_toolkits import mplot3d\r\nfrom time import perf_counter\r\n\r\n#returns the minimum of a multivariable function using gradient descent\r\ndef gradient_descent(f, xk, delta = 0.01, plot=False, F = None, axlim = 10):\r\n    \"\"\"\r\n    f: multivariable function with 1 array as parameter\r\n    xk : a vector to start descent\r\n    delta : precision of search\r\n    plot : option to plot the results or not\r\n    F : the function f expressed with 2 arrays in argument (X,Y) representing the colomns xk[0] and xk[1] for ploting issues. used only if plot == True\r\n    axlim : limit of the plot 3 axis (x,y,z)\r\n    \"\"\"\r\n    if plot : ax = plt.axes(projection='3d')\r\n    A = []\r\n    t = perf_counter()\r\n    dk = nd.Gradient(f)(xk)\r\n    while la.norm(dk) > delta :\r\n        if plot and len(A) < 10 : A.append(xk)\r\n        xt = xk\r\n        phi = lambda s : f(xk - s * dk)\r\n        alpha = op.newton(phi, 1)\r\n        xk -= alpha * dk\r\n        if plot and len(A) < 10 : A.append(xk)\r\n        dk = nd.Gradient(f)(xk)\r\n        if la.norm(xk - xt) < delta : break\r\n    t = perf_counter() - t\r\n    print(\"execution time: \",t)\r\n    if plot :\r\n        for u in A:\r\n            ax.scatter(u[0], u[1], f(u), c = 'b', s = 50)\r\n        ax.scatter(xk[0], xk[1], f(xk), c = 'r', s = 50,label=\"optimum\")\r\n        x = np.arange(-axlim, axlim, axlim/100)\r\n        y = np.arange(-axlim, axlim, axlim/100)\r\n        X, Y = np.meshgrid(x, y)\r\n        Z = F(X,Y)\r\n        ax.set_xlabel('x', labelpad=20)\r\n        ax.set_ylabel('y', labelpad=20)\r\n        ax.set_zlabel('z', labelpad=20)\r\n        surf = ax.plot_surface(X, Y, Z, cmap = plt.cm.cividis)\r\n        plt.legend()\r\n        plt.title(\"optimizition with Gradient Descent\")\r\n        plt.show()\r\n    return xk\r\n\r\n#returns the minimum of a multivariable function using conjugate gradient\r\ndef conjugate_gradient(f, x, plot=False, F = None,axlim = 10):\r\n    \"\"\"\r\n    f: multivariable function with 1 array as parameter\r\n    x : a vector to start descent\r\n    plot : option to plot the results or not\r\n    F : the function f expressed with 2 arrays in argument (X,Y) representing the colomns x[0] and x[1] for ploting issues. used only if plot == True\r\n    axlim : limit of the plot 3 axis (x,y,z)\r\n    \"\"\"\r\n    if plot : ax = plt.axes(projection='3d')\r\n    A = []\r\n    t = perf_counter()\r\n    d = -nd.Gradient(f)(x)\r\n    q = nd.Hessian(f)(x)\r\n    n = len(x)\r\n    for k in range(1, n):\r\n        if plot and len(A) < int(n/3) : A.append(x)\r\n        alpha = (d.T@d)/(d.T@q@d)\r\n        x += alpha * d\r\n        beta = (nd.Gradient(f)(x).T@q@d)/(d.T@q@d)\r\n        d = beta * d - nd.Gradient(f)(x)\r\n    t = perf_counter() - t\r\n    print(\"execution time: \",t)\r\n    if plot :\r\n        for u in A:\r\n            ax.scatter(u[0], u[1], f(u), c = 'b', s = 50)\r\n        ax.scatter(x[0], x[1], f(x), c = 'r', s = 50,label=\"optimum\")\r\n        x = np.arange(-axlim, axlim, axlim/100)\r\n        y = np.arange(-axlim, axlim, axlim/100)\r\n        X, Y = np.meshgrid(x, y)\r\n        Z = F(X,Y)\r\n        ax.set_xlabel('x', labelpad=20)\r\n        ax.set_ylabel('y', labelpad=20)\r\n        ax.set_zlabel('z', labelpad=20)\r\n        surf = ax.plot_surface(X, Y, Z, cmap = plt.cm.cividis)\r\n        plt.legend()\r\n        plt.title(\"optimizition with Conjugate Gradient\")\r\n        plt.show()\r\n    return x\r\n\r\n#verifies if a function is defined positive at a point x\r\ndef is_pos_def(f, x):\r\n    \"\"\"\r\n    f: multivariable function with 1 array as parameter\r\n    x : a vector where to verify if f is definite positive\r\n    \"\"\"\r\n    m = nd.Hessian(f)(x)\r\n    return np.all(np.linalg.eigvals(m) > 0)\r\n\r\n#returns the minimum of a multivariable function using Newton descent\r\ndef newton_descent(f, x, delta = 0.01, plot=False, F = None, axlim = 10):\r\n        \"\"\"\r\n    f: multivariable function with 1 array as parameter\r\n    x : a vector to start descent\r\n    delta : precision of search\r\n    plot : option to plot the results or not\r\n    F : the function f expressed with 2 arrays in argument (X,Y) representing the colomns x[0] and x[1] for ploting issues. used only if plot == True\r\n    axlim : limit of the plot axis (x,y,z)\r\n    \"\"\"\r\n    d = -la.inv(nd.Hessian(f)(x))@nd.Gradient(f)(x)\r\n    m = nd.Hessian(f)(x)\r\n    if la.det(m) == 0:\r\n        return ValueError\r\n    else :\r\n        if plot : ax = plt.axes(projection='3d')\r\n        A = []\r\n        t = perf_counter()\r\n        while la.norm(d) > delta:\r\n            if plot and len(A) < 10 : A.append(x)\r\n            phi = lambda s : f(x - s * d)\r\n            alpha = op.newton(phi, 1)\r\n            x -= alpha * d\r\n            dt = nd.Hessian(f)(x)\r\n            if is_pos_def(f, x) : d = -la.inv(nd.Hessian(f)(x))@nd.Gradient(f)(x)\r\n            else :\r\n                u = la.eigvals(f)(x)\r\n                epsilon = min(u)\r\n                n = len(x)\r\n                d = -la.inv((epsilon * np.identity(n) + nd.Hessian(f)(x))) @ nd.Gradient(f)(x)\r\n        t = perf_counter() - t\r\n        print(\"execution time: \",t)\r\n        if plot :\r\n            for u in A:\r\n                ax.scatter(u[0], u[1], f(u), c = 'b', s = 50)\r\n            ax.scatter(x[0], x[1], f(x), c = 'r', s = 50,label=\"optimum\")\r\n            x = np.arange(-axlim, axlim, axlim/100)\r\n            y = np.arange(-axlim, axlim, axlim/100)\r\n            X, Y = np.meshgrid(x, y)\r\n            Z = F(X,Y)\r\n            ax.set_xlabel('x', labelpad=20)\r\n            ax.set_ylabel('y', labelpad=20)\r\n            ax.set_zlabel('z', labelpad=20)\r\n            surf = ax.plot_surface(X, Y, Z, cmap = plt.cm.cividis)\r\n            plt.legend()\r\n            plt.title(\"optimizition with Newton descent\")\r\n            plt.show()\r\n    return x\r\n\r\n", "meta": {"hexsha": "e5f9f12898e992a2d676c925cd7ce7bb5b45277f", "size": 5769, "ext": "py", "lang": "Python", "max_stars_repo_path": "multivar/gradient.py", "max_stars_repo_name": "HamzaBamohammed/hambam-unconstraint-optimization", "max_stars_repo_head_hexsha": "f710f31883ec60d231ec6e8bf168805f7d455a98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-02-19T03:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T00:03:14.000Z", "max_issues_repo_path": "multivar/gradient.py", "max_issues_repo_name": "HamzaBamohammed/hambam-unconstraint-optimization", "max_issues_repo_head_hexsha": "f710f31883ec60d231ec6e8bf168805f7d455a98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multivar/gradient.py", "max_forks_repo_name": "HamzaBamohammed/hambam-unconstraint-optimization", "max_forks_repo_head_hexsha": "f710f31883ec60d231ec6e8bf168805f7d455a98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7181208054, "max_line_length": 152, "alphanum_fraction": 0.5432483966, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399060540359, "lm_q2_score": 0.8840392939666336, "lm_q1q2_score": 0.8577302015262628}}
{"text": "import numpy as np\r\nimport random\r\nimport csv\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef loadDataset(filename, split, trainingSet=[] , testSet=[]):\r\n    with open(filename, 'r') as csvfile:\r\n        lines = csv.reader(csvfile)\r\n        dataset = list(lines)\r\n        for x in range(len(dataset)):\r\n            for y in range(2):\r\n                dataset[x][y] = float(dataset[x][y])\r\n            if random.random() < split:\r\n                trainingSet.append(dataset[x])\r\n            else:\r\n                testSet.append(dataset[x])\r\n\r\n\r\ndef pca(X,n): \r\n\r\n    #1st Step : subtract mean \r\n    avg = np.mean(X,axis=0)\r\n    avg = np.tile(avg,(X.shape[0],1)) \r\n    X -= avg; \r\n    #print(avg)\r\n\r\n    #2nd Step : covariance matrix \r\n    C = np.dot(X.transpose(),X)/(X.shape[0]-1)\r\n\r\n    #3rd Step : Eigen Value, Eigen Vector \r\n    eig_values,eig_vecs = np.linalg.eig(C)\r\n\r\n    #4rd Step : Select n개의 PC \r\n    idx = np.argsort(eig_values)[-n:][::-1]\r\n    eig_values = eig_values[idx] \r\n    eig_vecs = eig_vecs[:,idx] \r\n    \r\n    #print(eig_values.argsort())\r\n    #print(eig_values.argsort()[-n:])\r\n    #print(idx)\r\n    #print(eig_values)\r\n    #print(eig_vecs)\r\n \r\n    #5th Step : new coordinate in new space \r\n    Y = np.dot(X,eig_vecs) \r\n\r\n    #6th Step : reconstruction \r\n    rec=np.dot(eig_vecs,Y.transpose())\r\n    Score=np.linalg.norm(X.transpose()-rec,axis=0)     \r\n    #print(rec)\r\n    #print(Score)\r\n    \r\n    return (X.transpose(), rec, Score.transpose(), eig_vecs, eig_values) \r\n\r\n\r\ndef main():\r\n\r\n\t# prepare data\r\n    trainingSet=[]\r\n    testSet=[]\r\n    split = 0.8\r\n    random.seed(100)\r\n    loadDataset('ex_pca5.csv', split, trainingSet, testSet)\r\n    #print('Train set: ' + repr(len(trainingSet)))\r\n    #print('Test set: ' + repr(len(testSet)))\r\n\r\n    # n=PC개수 (Hyper parameter)  \r\n    n=1\r\n    trainX=np.array(trainingSet)\r\n    pca_result=pca(trainX[:,:-1].astype(np.float),n)\r\n\r\n   # print('pca result:',pca_result)\r\n\r\n    x=pca_result[0][0]\r\n    y=pca_result[0][1]\r\n    Score=pca_result[2]*100\r\n\r\n    print('Eigen Value : ', pca_result[4])\r\n    print('Eigen Vector : ', pca_result[3])    \r\n    print('Data X : ', np.transpose(pca_result[0])[:10])\r\n    print('Reconstruction : ', np.transpose(pca_result[1])[:10])\r\n    print('Novelty Score : ', np.transpose(pca_result[2])[:10])\r\n        \r\n    x_rec=pca_result[1][0]\r\n    y_rec=pca_result[1][1]\r\n    \r\n    plt.figure(figsize=(6, 6), dpi=80)\r\n    plt.scatter(x,y,s=Score);\r\n    plt.scatter(x_rec,y_rec,s=20);\r\n    plt.xticks(np.arange(-3,3,0.5))\r\n    plt.yticks(np.arange(-3,3,0.5))\r\n         \r\nmain()", "meta": {"hexsha": "9670515c727ebff16ea9d56e53fc430289771a1c", "size": 2560, "ext": "py", "lang": "Python", "max_stars_repo_path": "03 Novelty Detection/Tutorial 09 - Distance and reconstruction-based novelty detection/PCA/PCA_ND.py", "max_stars_repo_name": "KateYeon/Business-Anlaytics", "max_stars_repo_head_hexsha": "454c1cb1b88499e94eeb5e8a7a32309afb7165e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "03 Novelty Detection/Tutorial 09 - Distance and reconstruction-based novelty detection/PCA/PCA_ND.py", "max_issues_repo_name": "KateYeon/Business-Anlaytics", "max_issues_repo_head_hexsha": "454c1cb1b88499e94eeb5e8a7a32309afb7165e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "03 Novelty Detection/Tutorial 09 - Distance and reconstruction-based novelty detection/PCA/PCA_ND.py", "max_forks_repo_name": "KateYeon/Business-Anlaytics", "max_forks_repo_head_hexsha": "454c1cb1b88499e94eeb5e8a7a32309afb7165e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2340425532, "max_line_length": 74, "alphanum_fraction": 0.569140625, "include": true, "reason": "import numpy", "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399026119353, "lm_q2_score": 0.8840392832736084, "lm_q1q2_score": 0.8577301881085109}}
{"text": "# https://projecteuler.net/problem=14\n# Run with: 'python solve14.py'\n# using Python 3.6.9\n# by Zack Sargent\n\n# Prompt:\n\n# The following iterative sequence is defined for the set of positive integers:\n#   n → n/2 (n is even)\n#   n → 3n + 1 (n is odd)\n# Using the rule above and starting with 13, we generate the following sequence:\n#   13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1\n# It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms.\n# Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.\n# Which starting number, under one million, produces the longest chain?\n# NOTE: Once the chain starts the terms are allowed to go above one million.\n\n# numba is only used to improve performance.\n# remove lines 20 and 22 if you don't want it.\nfrom numba import njit\n\n@njit\ndef collatz_sequence(n: int, length: int) -> int:\n    length += 1\n    if n == 1:\n        return length\n    elif n % 2 == 0:\n        return collatz_sequence(n / 2, length)\n    else:\n        return collatz_sequence((3*n)+1, length)\n\nmax_num: int = 0\nmax_size: int = 0\n\nGOAL: int = 1_000_000\n# divide by 1.5 to limit the range we check\nfor i in range(round(GOAL // 1.5), GOAL + 1):\n    size = collatz_sequence(i, 0)\n    if size > max_size:\n        max_size = size\n        max_num = i\n\nprint(max_num)\n# -> 837799 \n", "meta": {"hexsha": "53457a54114942ff605bfda53966faa49c39c8a3", "size": 1362, "ext": "py", "lang": "Python", "max_stars_repo_path": "solutions/014/solve14.py", "max_stars_repo_name": "zsarge/ProjectEuler", "max_stars_repo_head_hexsha": "751b19df53483d517e6bf71ccc5fb9918ff50322", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solutions/014/solve14.py", "max_issues_repo_name": "zsarge/ProjectEuler", "max_issues_repo_head_hexsha": "751b19df53483d517e6bf71ccc5fb9918ff50322", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solutions/014/solve14.py", "max_forks_repo_name": "zsarge/ProjectEuler", "max_forks_repo_head_hexsha": "751b19df53483d517e6bf71ccc5fb9918ff50322", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-07T18:45:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T18:45:07.000Z", "avg_line_length": 30.2666666667, "max_line_length": 109, "alphanum_fraction": 0.6688693098, "include": true, "reason": "from numba", "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399060540358, "lm_q2_score": 0.8840392771633079, "lm_q1q2_score": 0.8577301852230055}}
{"text": "## module gaussNodes\r\n''' x,A = gaussNodes(m,tol=10e-9)\r\n    Returns nodal abscissas {x} and weights {A} of\r\n    Gauss-Legendre m-point quadrature.\r\n'''\r\nimport math\r\nimport numpy as np\r\n\r\ndef gaussNodes(m,tol=10e-9):\r\n\r\n    def legendre(t,m):\r\n        p0 = 1.0; p1 = t\r\n        for k in range(1,m):\r\n            p = ((2.0*k + 1.0)*t*p1 - k*p0)/(1.0 + k )\r\n            p0 = p1; p1 = p\r\n        dp = m*(p0 - t*p1)/(1.0 - t**2)\r\n        return p,dp\r\n\r\n    A = np.zeros(m)   \r\n    x = np.zeros(m)   \r\n    nRoots = int((m + 1)/2)         # Number of non-neg. roots\r\n    for i in range(nRoots):\r\n        t = math.cos(math.pi*(i + 0.75)/(m + 0.5))# Approx. root\r\n        for j in range(30): \r\n            p,dp = legendre(t,m)    # Newton-Raphson\r\n            dt = -p/dp; t = t + dt  # method         \r\n            if abs(dt) < tol:\r\n                x[i] = t; x[m-i-1] = -t\r\n                A[i] = 2.0/(1.0 - t**2)/(dp**2) # Eq.(6.25)\r\n                A[m-i-1] = A[i]\r\n                break\r\n    return x,A\r\n", "meta": {"hexsha": "581774ba9df2ab0b8420e1b3e75160ca81222c48", "size": 1001, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/book/gaussNodes.py", "max_stars_repo_name": "krontzo/nume.py", "max_stars_repo_head_hexsha": "9d1e576fb3474333a8e2cf4f26f4236ee4f9deea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/book/gaussNodes.py", "max_issues_repo_name": "krontzo/nume.py", "max_issues_repo_head_hexsha": "9d1e576fb3474333a8e2cf4f26f4236ee4f9deea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/book/gaussNodes.py", "max_forks_repo_name": "krontzo/nume.py", "max_forks_repo_head_hexsha": "9d1e576fb3474333a8e2cf4f26f4236ee4f9deea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3333333333, "max_line_length": 65, "alphanum_fraction": 0.4255744256, "include": true, "reason": "import numpy", "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399043329856, "lm_q2_score": 0.884039278690883, "lm_q1q2_score": 0.8577301851836439}}
{"text": "import numpy as np\n\ndef polykernel(x1, x2, offset=0, degree=2):\n    \"\"\"\n    polynomial kernel of the form:\n    k(x1, x2) = ((x1' * x2) + offset) ^ degree\n    \"\"\"\n    return (np.dot(x1, x2) + offset)**degree\n\ndef rbf(x1, x2, sigma=1):\n    \"\"\"\n    rbf kernel. sigma is the smoothing parameter\n    k(x1, x2) = exp(-||x1 - x2||^2 / 2 * sigma^2)\n    \"\"\"\n    return np.exp(-(np.linalg.norm(x1 - x2) / (2 * sigma**2)))\n", "meta": {"hexsha": "0199d3e733b4ed25dbc7d031baf9a1684ead1c12", "size": 412, "ext": "py", "lang": "Python", "max_stars_repo_path": "Scripts/CSAN/src/kernel.py", "max_stars_repo_name": "iamkakadong/BrainResearch", "max_stars_repo_head_hexsha": "7b7295756f5e5449616f9186023d75caa1e58188", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Scripts/CSAN/src/kernel.py", "max_issues_repo_name": "iamkakadong/BrainResearch", "max_issues_repo_head_hexsha": "7b7295756f5e5449616f9186023d75caa1e58188", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scripts/CSAN/src/kernel.py", "max_forks_repo_name": "iamkakadong/BrainResearch", "max_forks_repo_head_hexsha": "7b7295756f5e5449616f9186023d75caa1e58188", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.75, "max_line_length": 62, "alphanum_fraction": 0.5485436893, "include": true, "reason": "import numpy", "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924810166349, "lm_q2_score": 0.8824278571786139, "lm_q1q2_score": 0.8577132422172338}}
{"text": "from time import perf_counter\r\nfrom math import sqrt, ceil, log\r\nfrom matplotlib import pyplot as plt\r\nimport numpy as np\r\n\r\n#unrestricted search with fixed step\r\ndef usfs(f, a, b, p = 0.01, plot=False):\r\n    \"\"\"\r\n    f: monovariable function\r\n    a : start of search interval\r\n    b : end of search interval\r\n    p : step size\r\n    plot : a parameter to choose either to plot or not the results\r\n    \"\"\"\r\n    if plot :\r\n        X = np.linspace(a,b,1000)\r\n        plt.plot(X, f(X))\r\n    t = perf_counter()\r\n    iter = 0\r\n    A = []\r\n    while f(a) > f(a + p) and a <= b :\r\n        iter += 1\r\n        a += p\r\n        if plot and len(A) < 10 : A.append(a)\r\n    t = perf_counter() - t\r\n    print(\"time execution: \",t)\r\n    if plot :\r\n        for e in A :\r\n            plt.plot(e,f(e),\"o\")\r\n    if a > b : \r\n        plt.plot(a-p, f(a-p),\"s\",label=\"optimum\")\r\n        plt.show()\r\n        return a - p\r\n    if plot : \r\n        plt.plot(a,f(a),\"s\",label=\"optimum\")\r\n        plt.title(\"optimization with fixed step search\")\r\n        plt.legend()\r\n        plt.show()\r\n    return a\r\n\r\n#unrestricted search with accelerated step\r\ndef usas(f, a, b, p = 0.01, plot=False):\r\n    \"\"\"\r\n    f: monovariable function\r\n    a : start of search interval\r\n    b : end of search interval\r\n    p : step size\r\n    plot : a parameter to choose either to plot or not the results\r\n    \"\"\"\r\n    t = perf_counter()\r\n    it , step = a, 0\r\n    A = []\r\n    while  step != p :\r\n        if it > b : it  -= step / 2\r\n        step , i1, i2 = p, f(it), f(it + p)\r\n        while i1 > i2 and it < b :\r\n            if plot and len(A) < 10 : A.append(it)\r\n            it += step\r\n            i1 = i2\r\n            step *= 2\r\n            i2 = f(it + step)\r\n    t = perf_counter() - t\r\n    print(\"time execution: \",t)\r\n    if plot :\r\n        plt.plot(it,i1,\"s\",label=\"optimum\")\r\n        X = np.linspace(a,b,1000)\r\n        plt.plot(X,f(X))\r\n        for e in A :\r\n            plt.plot(e,f(e),\"o\")\r\n        plt.legend()\r\n        plt.title(\"optimization with accelerated step search\")\r\n        plt.show()\r\n    return it\r\n\r\n#exhaustive search\r\ndef bf(f, a, b, n = 1000, plot=False):\r\n    \"\"\"\r\n    f: monovariable function\r\n    a : start of search interval\r\n    b : end of search interval\r\n    n : number of divisions of the interval\r\n    plot : a parameter to choose either to plot or not the results\r\n    \"\"\"\r\n    t = perf_counter()\r\n    p = (b - a) / (n - 1)\r\n    it = a\r\n    L = []\r\n    A = []\r\n    while a <= b :\r\n        L.append(f(a))\r\n        a += p\r\n        if plot : A.append(a)\r\n    t = perf_counter() - t\r\n    print(\"time execution: \",t)\r\n    if plot : \r\n        plt.plot(it + L.index(min(L))*p,f(it + L.index(min(L))*p),\"s\",label=\"optimum\")\r\n        X = np.linspace(a,b,1000)\r\n        plt.plot(X,f(X))\r\n        for e in A :\r\n            plt.plot(e,f(e),\"o\")\r\n        plt.legend()\r\n        plt.title(\"optimization with Brute Force method\")\r\n        plt.show()\r\n    return it + L.index(min(L))*p\r\n\r\n#binary search\r\ndef bs(f, a, b, e = 0.01, delta = 0.001, plot=False):\r\n    \"\"\"\r\n    f: monovariable function\r\n    a : start of search interval\r\n    b : end of search interval\r\n    e : search precision\r\n    delta : a factor relied to the binary search\r\n    plot : a parameter to choose either to plot or not the results\r\n    \"\"\"\r\n    t = perf_counter()\r\n    A = []\r\n    mid = (a + b) / 2\r\n    n = ceil(log((b - a - delta) / (2 * e * (b - a) - delta)) * (2 / log(2)))\r\n    if n%2 : n+=1\r\n    if plot : \r\n        X = np.linspace(a,b,1000)\r\n        plt.plot(X,f(X))\r\n    for i in range(n) :\r\n        y1, y2 = f(mid - (delta / 2)), f(mid + (delta / 2))\r\n        if y2 > y1 : b = mid + (delta / 2)\r\n        else : a = mid - (delta / 2)\r\n        mid = (a + b) / 2\r\n        if plot : A.append(mid)\r\n    t = perf_counter() - t\r\n    print(\"time execution: \",t)\r\n    if plot : \r\n        plt.plot(mid,f(mid),\"s\",label=\"optimum\")\r\n        for u in A :\r\n            plt.plot(u,f(u),\"o\")\r\n        plt.legend()\r\n        plt.title(\"optimization with Binary Search method\")\r\n        plt.show()\r\n    return mid\r\n\r\n#interval halving method\r\ndef halv(f, a, b, e = 0.01, plot=False):\r\n    \"\"\"\r\n    f: monovariable function\r\n    a : start of search interval\r\n    b : end of search interval\r\n    e : search precision\r\n    plot : a parameter to choose either to plot or not the results\r\n    \"\"\"\r\n    t = perf_counter()\r\n    A = [[],[],[]]\r\n    n = ceil((2 * log(2 * e))/ log(1 / 2)) + 1\r\n    if (n%2)==0 : n += 1\r\n    if plot :\r\n        X = np.linspace(a,b,1000)\r\n        plt.plot(X,f(X))\r\n    for i in range(n):\r\n        x0, x1, x2 = (a+b)/2, (a+b)/3, (2*(a+b))/3\r\n        y0, y1, y2 = f(x0), f(x1), f(x2)\r\n        if plot :\r\n            A[0].append(x0)\r\n            A[1].append(x1)\r\n            A[2].append(x2)\r\n        if y1 < y0 < y2 : b = x0\r\n        elif y1 > y0 > y2 :\ta = x0 \r\n        else :\r\n            a = x1\r\n            b = x2\r\n    t = perf_counter() - t\r\n    print(\"time execution: \",t)\r\n    if plot :\r\n        plt.plot((a+b)/2, f((a+b)/2),\"s\",color=\"yellow\",label=\"optimum\")\r\n        for i in range(n):\r\n            plt.plot(A[0][i],f(A[0][i]),\"o\",color='red')\r\n            plt.plot(A[1][i],f(A[1][i]),\"o\",color='blue')\r\n            plt.plot(A[2][i],f(A[2][i]),\"o\",color='green')\r\n        plt.legend()\r\n        plt.title(\"optimization with Interval Halving method\")\r\n        plt.show()\r\n    return (a + b) / 2\r\n\r\n#fibonacci method\r\ndef fibo(f, a, b, n = 20, plot=False):\r\n    \"\"\"\r\n    f: monovariable function\r\n    a : start of search interval\r\n    b : end of search interval\r\n    n : number of iterations (deepth)\r\n    plot : a parameter to choose either to plot or not the results\r\n    \"\"\"\r\n    A = [[],[]]\r\n    if plot :\r\n        X = np.linspace(a,b,1000)\r\n        plt.plot(X,f(X))\r\n    t = perf_counter()\r\n    f0, f1, f2 = 1, 1, 2\r\n    for i in range(n-2) :\r\n        f0 = f1\r\n        f1 = f2\r\n        f2 = f1 + f0\r\n    c = a + (f0 / f2) * (b - a)\r\n    d = a + (f1 / f2) * (b - a)\r\n    y1 = f(c)\r\n    y2 = f(d)\r\n    for i in range(n):\r\n        if plot and len(A[0]) < 10 : \r\n            A[0].append(c)\r\n            A[1].append(d)\r\n        if y1 < y2 :\r\n            b = d\r\n            d = c\r\n            c = a + (b - d)\r\n            y2 = y1\r\n            y1 = f(c)\r\n        else :\r\n            a = c\r\n            c = d\r\n            d = a + (b - c)\r\n            y1 = y2\r\n            y2 = f(d)\r\n    t = perf_counter() - t\r\n    print(\"time execution: \",t)\r\n    if plot :\r\n        plt.plot(c,f(c),\"s\",label=\"optimum\")\r\n        for i in range(len(A[0])):\r\n            plt.plot(A[0][i],f(A[0][i]),\"o\",color='red')\r\n            plt.plot(A[1][i],f(A[1][i]),\"o\",color='blue')\r\n        plt.legend()\r\n        plt.title(\"optimization with Fibonacci method\")\r\n        plt.show()\r\n    return c\r\n\r\n#golden ratio method\r\ndef golden(f, a, b, e = 0.01, plot=False):\r\n    \"\"\"\r\n    f: monovariable function\r\n    a : start of search interval\r\n    b : end of search interval\r\n    e : search precision\r\n    plot : a parameter to choose either to plot or not the results\r\n    \"\"\"\r\n    A = [[],[]]\r\n    if plot and len(A[0]) < 10 :\r\n        X = np.linspace(a,b,1000)\r\n        plt.plot(X,f(X))\r\n    t = perf_counter()\r\n    phi = (sqrt(5) - 1) / 2\r\n    Ln = 1\r\n    f0, f1, f2 = 1, 1, 2\r\n    for i in range(100) :\r\n        f0 = f1\r\n        f1 = f2\r\n        f2 = f1 + f0\r\n    c = a + (f0 / f2) * (b - a)\r\n    d = a + (f1 / f2) * (b - a)\r\n    y1 = f(c)\r\n    y2 = f(d)\r\n    while Ln > e:\r\n        if plot : \r\n            A[0].append(c)\r\n            A[1].append(d)\r\n        if y1 < y2 :\r\n            b = d\r\n            d = c\r\n            c = a + (b - d)\r\n            y2 = y1\r\n            y1 = f(c)\r\n        else :\r\n            a = c\r\n            c = d\r\n            d = a + (b - c)\r\n            y1 = y2\r\n            y2 = f(d)\r\n        Ln *= phi\r\n    t = perf_counter() - t\r\n    print(\"time execution: \",t)\r\n    if plot :\r\n        plt.plot(c,f(c),\"s\",label=\"optimum\")\r\n        for i in range(len(A[0])):\r\n            plt.plot(A[0][i],f(A[0][i]),\"o\",color='red')\r\n            plt.plot(A[1][i],f(A[1][i]),\"o\",color='blue')\r\n        plt.title(\"optimization with Golden section\")\r\n        plt.legend()\r\n        plt.show()\r\n    return c\r\n", "meta": {"hexsha": "f03591e88352c46c7be14a89dc04674a3ae03c1c", "size": 8149, "ext": "py", "lang": "Python", "max_stars_repo_path": "unidim/elimination.py", "max_stars_repo_name": "HamzaBamohammed/hambam-unconstraint-optimization", "max_stars_repo_head_hexsha": "f710f31883ec60d231ec6e8bf168805f7d455a98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-02-19T03:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T00:03:14.000Z", "max_issues_repo_path": "unidim/elimination.py", "max_issues_repo_name": "HamzaBamohammed/hambam-unconstraint-optimization", "max_issues_repo_head_hexsha": "f710f31883ec60d231ec6e8bf168805f7d455a98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unidim/elimination.py", "max_forks_repo_name": "HamzaBamohammed/hambam-unconstraint-optimization", "max_forks_repo_head_hexsha": "f710f31883ec60d231ec6e8bf168805f7d455a98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.493006993, "max_line_length": 87, "alphanum_fraction": 0.4569885876, "include": true, "reason": "import numpy", "num_tokens": 2524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.9207896758909757, "lm_q1q2_score": 0.8576810598956695}}
{"text": "import numpy as np\n\n\n__all__ = ['cart2pol', 'pol2cart', 'cart2sphere', 'sphere2cart']\n\n\ndef _fix_angle(a):\n    while a > np.pi:\n        a -= np.pi\n    while a < -np.pi:\n        a += np.pi\n    return a\n\n\ndef cart2pol(x, y):\n    r = np.sqrt(x ** 2 + y ** 2)\n    ang = np.arctan2(y, x)\n    return r, ang\n\n\ndef pol2cart(r, ang):\n    x = r * np.cos(ang)\n    y = r * np.sin(ang)\n    return x, y\n\n\ndef cart2sphere(x, y, z):\n    r = np.sqrt(x**2 + y**2 + z**2)\n    # theta = np.arctan2(np.sqrt(x**2 + y**2), z)\n    theta = np.arccos(z / r)\n    phi = np.arctan2(y, x)\n    return r, theta, phi\n\n\ndef sphere2cart(r, theta, phi):\n    theta = _fix_angle(theta)\n    phi = _fix_angle(phi)\n    x = r * np.sin(theta) * np.cos(phi)\n    y = r * np.sin(theta) * np.sin(phi)\n    z = r * np.cos(theta)\n    return x, y, z\n", "meta": {"hexsha": "a775b850e5e54fffcc4532f9dfb9d1dd62f0903b", "size": 799, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/api/coords.py", "max_stars_repo_name": "SqrtMinusOne/SEM6_OpenGL_CourseWork", "max_stars_repo_head_hexsha": "cf4bda4b989f0c09fe91f676d4094feb75aa54e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-01-09T13:10:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T20:45:18.000Z", "max_issues_repo_path": "src/api/coords.py", "max_issues_repo_name": "SqrtMinusOne/GeoTIFF-3d", "max_issues_repo_head_hexsha": "cf4bda4b989f0c09fe91f676d4094feb75aa54e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/api/coords.py", "max_forks_repo_name": "SqrtMinusOne/GeoTIFF-3d", "max_forks_repo_head_hexsha": "cf4bda4b989f0c09fe91f676d4094feb75aa54e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0238095238, "max_line_length": 64, "alphanum_fraction": 0.5269086358, "include": true, "reason": "import numpy", "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.975576914206421, "lm_q2_score": 0.8791467738423874, "lm_q1q2_score": 0.8576752967596866}}
{"text": "# Code was created by M. Heriyanto, 2020/01/13\r\n# https://github.com/ezygeo-ai/machine-learning-and-geophysical-inversion/blob/master/scripts/derrivatives_in_python.py\r\n\r\nimport sympy as sym\r\n# https://scipy-lectures.org/packages/sympy.html\r\n\r\n# === example\r\nx = sym.Symbol('x')\r\ny = sym.Symbol('y')\r\n\r\nprint(sym.diff(3*x**2 + 3*y, x))\r\nprint(sym.diff(3*x**2 + 3*y, y))\r\n\r\n\r\ndef func(vx, vy):\r\n    return 3*vx**2 + 3*vy\r\n\r\n\r\nprint(sym.diff(func(x, y), x))\r\nprint(sym.diff(func(x, y), y))\r\n\r\n# === SP case\r\nx = sym.Symbol('x')\r\nx0 = sym.Symbol('x0')\r\nalpa = sym.Symbol('alpa')\r\nh = sym.Symbol('h')\r\nK = sym.Symbol('K')\r\n\r\n\r\n# forward function\r\ndef func_SP(vx, vx0, va, vh, vk):\r\n    return vk * (((vx-vx0)*sym.cos(va)-vh*sym.sin(va))/((vx-vx0)**2 + vh**2)**3/2)\r\n\r\n\r\n# x0\r\nprint(sym.diff(func_SP(x, x0, alpa, h, K), x0))\r\n\r\n# alpa\r\nprint(sym.diff(func_SP(x, x0, alpa, h, K), alpa))\r\n\r\n# h\r\nprint(sym.diff(func_SP(x, x0, alpa, h, K), h))\r\n\r\n# K\r\nprint(sym.diff(func_SP(x, x0, alpa, h, K), K))\r\n", "meta": {"hexsha": "d1ec74da2ecabb277e0c1b58f48f86e5d357ffd5", "size": 992, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/derrivatives_in_python.py", "max_stars_repo_name": "ezygeo-ai/machine-learning-and-geophysical-inversion", "max_stars_repo_head_hexsha": "a77fde655f4050a115a226e672668af3c7b68e29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-10-07T03:34:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T11:10:03.000Z", "max_issues_repo_path": "scripts/derrivatives_in_python.py", "max_issues_repo_name": "ezygeo-ai/machine-learning-and-geophysical-inversion", "max_issues_repo_head_hexsha": "a77fde655f4050a115a226e672668af3c7b68e29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-19T09:12:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-19T09:12:32.000Z", "max_forks_repo_path": "scripts/derrivatives_in_python.py", "max_forks_repo_name": "ezygeo-ai/machine-learning-and-geophysical-inversion", "max_forks_repo_head_hexsha": "a77fde655f4050a115a226e672668af3c7b68e29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-07-24T08:03:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:55:01.000Z", "avg_line_length": 21.5652173913, "max_line_length": 120, "alphanum_fraction": 0.595766129, "include": true, "reason": "import sympy", "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812327313546, "lm_q2_score": 0.8856314828740729, "lm_q1q2_score": 0.8576289071312923}}
{"text": "import numpy as np\nimport re\nimport random\n\nH_matrix = np.mat([\n    [1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1],\n    [0 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 1],\n    [0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1],\n    [0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1],\n])\n\nG_matrix = np.mat([\n    [1 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],\n    [1 , 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],\n    [0 , 1 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],\n    [1 , 1 , 0 , 1 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],\n    [1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0],\n    [0 , 1 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 0 , 0],\n    [1 , 1 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 1 , 0 , 0 , 0 , 0],\n    [0 , 0 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 0 , 0],\n    [1 , 0 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0],\n    [0 , 1 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 1 , 0],\n    [1 , 1 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 1]\n])\n\ndef hamming_encode(data: str) -> str:\n    d = []\n    for x in data:\n        d.append(int(x))\n    res = (np.mat(d) * G_matrix) % 2\n    return re.sub(r'[^0-1]', '', str(res))\n    # return str(res).replace(' ', '').replace('[', '').replace(']', '')\n\ndef error_occur(data: str) -> str:\n    tmp = random.randint(0, 14)\n    return data[:tmp] + ('0' if data[tmp] == '1' else '1') + data[tmp + 1:]\n\ndef hamming_decode(data: str, error = False) -> str:\n    if error:\n        data = error_occur(data)\n    d = []\n    for x in data:\n        d.append(int(x))\n    diff = (np.mat(d) * H_matrix.T) % 2\n    diff = int(re.sub(r'[^0-1]', '', str(diff)[::-1]), 2)\n    if diff != 0:\n        diff -= 1\n        data = data[:diff] + ('0' if data[diff] == '1' else '1') + data[diff + 1:]\n    return data[2] + data[4:7] + data[8:]\n\nif __name__ == \"__main__\":\n    file_lines = []\n    f = open('lab2_data/hamming_15_11.txt')\n    file_lines = f.readlines()\n    f.close()\n    print (len(file_lines))\n    for line in file_lines:\n        data = line.split(',')\n        data[0], data[1] = data[0].strip(), data[1].strip()\n        assert (hamming_encode(data[0]) == data[1])\n        assert (hamming_decode(data[1]) == data[0])\n        assert (hamming_decode(data[1], True) == data[0])", "meta": {"hexsha": "e576348fe2ef825a6fe8fb1f32f58e39236ca106", "size": 2316, "ext": "py", "lang": "Python", "max_stars_repo_path": "hamming_15_11_mat.py", "max_stars_repo_name": "s0uthwood/channel-code-lab", "max_stars_repo_head_hexsha": "f6b573f4f89bc268cb53850ece607a526546d982", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hamming_15_11_mat.py", "max_issues_repo_name": "s0uthwood/channel-code-lab", "max_issues_repo_head_hexsha": "f6b573f4f89bc268cb53850ece607a526546d982", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hamming_15_11_mat.py", "max_forks_repo_name": "s0uthwood/channel-code-lab", "max_forks_repo_head_hexsha": "f6b573f4f89bc268cb53850ece607a526546d982", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3548387097, "max_line_length": 82, "alphanum_fraction": 0.4080310881, "include": true, "reason": "import numpy", "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773708019443872, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.8576201883371315}}
{"text": "\"\"\"\r\nExercise 2\r\nImplement the Gradient Descent\r\nYour challenge is to implement a generic prgram using the gradient\r\ndescent algorithm to find the minimum value of a single-variable\r\nfunction specified as input by the user. The program should also create\r\na graph of the function and show all the intermediate values it found\r\nbefore finding the minimum.\r\n\"\"\"\r\n\r\nfrom sympy import Derivative, Symbol, sympify, solve\r\nfrom sympy.core.sympify import SympifyError\r\nimport matplotlib.pyplot as plt\r\n\r\nepsilon = 1e-6\r\nstep_size = 1e-4\r\n\r\n\r\ndef grad_descent(init_val, function, x):\r\n\r\n    if not solve(function):\r\n        print(\"Cannot continue, solution for {0}=0 does not exist\".format(function))\r\n        return None\r\n\r\n    x_new = init_val - step_size * function.subs({x: init_val}).evalf()\r\n    x_old = init_val\r\n\r\n    x_traversed = []\r\n\r\n    while abs(x_old - x_new) > epsilon:\r\n        x_traversed.append(x_new)\r\n        x_old = x_new\r\n        x_new = x_old - step_size * function.subs({x: x_old}).evalf()\r\n\r\n    return x_new, x_traversed\r\n\r\n\r\ndef frange(start, final, interval):\r\n\r\n    numbers = []\r\n    while start < final:\r\n        numbers.append(start)\r\n        start += interval\r\n\r\n    return numbers\r\n\r\n\r\ndef create_plot(x_traversed, function, var):\r\n    x_val = frange(-10, 10, 0.01)\r\n    y_val = [function.subs({var: x}) for x in x_val]\r\n    plt.plot(x_val, y_val, \"black\")\r\n\r\n    y_traversed = [function.subs({var: x}) for x in x_traversed]\r\n    plt.plot(x_traversed, y_traversed, \"green\")\r\n\r\n    plt.legend([\"Function\", \"Intermediate points\"])\r\n    plt.show()\r\n\r\n\r\ndef validate_function(function):\r\n\r\n    try:\r\n        return sympify(function)\r\n    except SympifyError:\r\n        print(\"Invalid function entered\")\r\n        sys.exit(1)\r\n\r\n    return None\r\n\r\n\r\ndef main():\r\n    function = input(\"Provide a function of one variable: \")\r\n    function = validate_function(function)\r\n\r\n    variable = input(\"Enter the variable to differentiate with respect to: \")\r\n    variable = Symbol(variable)\r\n\r\n    init_val = input(\"Enter the initial value of the variable: \")\r\n    init_val = float(init_val)\r\n\r\n    derivative = Derivative(function, variable).doit()\r\n    var_min, x_traversed = grad_descent(init_val, derivative, variable)\r\n\r\n    if var_min:\r\n        print(\"{} : {}\".format(variable.name, var_min))\r\n        create_plot(x_traversed, function, variable)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n", "meta": {"hexsha": "f5226e05530648a0ba3e71a17541c3fa86afcc10", "size": 2408, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Chapter7/Exercise2.py", "max_stars_repo_name": "djeada/Doing-Math-with-Python", "max_stars_repo_head_hexsha": "6b5fb4018224032f805314d367f810c127246ccf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Chapter7/Exercise2.py", "max_issues_repo_name": "djeada/Doing-Math-with-Python", "max_issues_repo_head_hexsha": "6b5fb4018224032f805314d367f810c127246ccf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Chapter7/Exercise2.py", "max_forks_repo_name": "djeada/Doing-Math-with-Python", "max_forks_repo_head_hexsha": "6b5fb4018224032f805314d367f810c127246ccf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4615384615, "max_line_length": 85, "alphanum_fraction": 0.6582225914, "include": true, "reason": "from sympy", "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773708052400945, "lm_q2_score": 0.8774767762675405, "lm_q1q2_score": 0.8576201834000883}}
{"text": "#Author: Daniel Moraes dos Santos\nimport numpy as np\nimport algebra\n\n\ndef multiply_matrix(A, B):\n    if A.shape[1] != B.shape[0]:\n        raise NameError('deu ruim')\n\n    C = np.zeros(shape=(A.shape[0], B.shape[1]))\n\n    for i in range(C.shape[0]):\n        for j in range(C.shape[1]):\n            for k in range(B.shape[0]):\n                C[i, j] += A[i, k] * B[k, j]\n\n    return C\n\n\ndef transpose_matrix(A):\n    t = np.zeros(shape=(A.shape[1], A.shape[0]))\n\n    for i in range(t.shape[0]):\n        for j in range(t.shape[1]):\n            t[i, j] = A[j, i]\n\n    return t\n\n\ndef generate_A(points):\n    A = np.zeros(shape=(len(points), k + 1))\n\n    for i, point in enumerate(points):\n        for j in range(k + 1):\n            A[i, j] = point[0] ** abs(k - j)\n\n    return A\n\n\ndef generate_b(points):\n    b = np.zeros(shape=(len(points), 1))\n\n    for i, point in enumerate(points):\n        b[i, 0] = point[1]\n\n    return b\n\n\nif __name__ == '__main__':\n    points_list = [(-2., -3.), (-1., 0.), (1., 0.), (2., -3.), (2., -1.), (4., 0.), (5., 2.)]\n    # points_list = [(-2., 0.), (-1., 4.), (0., 5.), (1., 4.), (2., 0.)] # ex 1\n    # points_list = [(-4, 0), (3, 0), (0, 0), (-3, -576), (4, -576), (-1, 144), (2, 144)] # ex 2\n    # points_list = [(0., 1.), (2., 1.), (2., 5.), (6., 2.), (6., 4.), (6., 6.)] # ex 3\n\n    k = 3  # ax3+bx2+cx1+d=y\n    # k = 4\n    # k = 6\n    # k = 2\n\n    A = generate_A(points_list)\n    b = generate_b(points_list)\n    print A\n    print b\n\n    At = transpose_matrix(A)\n\n    An = multiply_matrix(At, A)\n    bn = multiply_matrix(At, b)\n    # An = At.dot(A)\n    # bn = At.dot(b)\n\n    print An\n    print bn\n\n    solver = algebra.Algebra()\n\n    print solver.solve_system(An, bn)\n", "meta": {"hexsha": "28404f850f614f3d36453f12c7542fcb9947790d", "size": 1700, "ext": "py", "lang": "Python", "max_stars_repo_path": "Trabalho 6 (Daniel M.)/polynomial_interpolation.py", "max_stars_repo_name": "danielbibit/CalculoNumerico-UFG", "max_stars_repo_head_hexsha": "9ab030ba75353ca39d1f72090f1a65d7516ffa8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Trabalho 6 (Daniel M.)/polynomial_interpolation.py", "max_issues_repo_name": "danielbibit/CalculoNumerico-UFG", "max_issues_repo_head_hexsha": "9ab030ba75353ca39d1f72090f1a65d7516ffa8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Trabalho 6 (Daniel M.)/polynomial_interpolation.py", "max_forks_repo_name": "danielbibit/CalculoNumerico-UFG", "max_forks_repo_head_hexsha": "9ab030ba75353ca39d1f72090f1a65d7516ffa8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7948717949, "max_line_length": 96, "alphanum_fraction": 0.4894117647, "include": true, "reason": "import numpy", "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067252, "lm_q2_score": 0.9059898114992677, "lm_q1q2_score": 0.8576069401654102}}
{"text": "import numpy as np\nfrom scipy import linalg as la\nfrom scipy import optimize as opt\nfrom matplotlib import pyplot as plt\n\n# Problem 1\ndef conjugateGradient(b,x0,Q,tol = .0001):\n    \"\"\"Use the Conjugate Gradient Method to find the solution to the linear\n    system Qx = b.\n    \n    Parameters:\n        b  ((n, ) ndarray)\n        x0 ((n, ) ndarray): An initial guess for x.\n        Q  ((n,n) ndarray): A positive-definite square matrix.\n        tol (float)\n    \n    Returns:\n        x ((n, ) ndarray): The solution to the linear systm Qx = b, according\n            to the Conjugate Gradient Method.\n    \"\"\"\n    xk = x0\n    rk = Q.dot(x0)-b\n    dk = -rk\n    k = 0\n    while la.norm(rk) > tol:\n        alphak = rk.T.dot(rk)/dk.T.dot(Q.dot(dk))\n        xk1 = xk + alphak*dk\n        rk1 = rk + alphak*Q.dot(dk)\n        betak1 = rk1.T.dot(rk1)/rk.T.dot(rk)\n        dk1 = -rk1 + betak1*dk\n        k = k+1\n        xk = xk1\n        rk = rk1\n        dk = dk1\n    return xk1\n\n# Problem 2\ndef prob2(filename = 'linregression.txt'):\n    \"\"\"Use conjugateGradient() to solve the linear regression problem with\n    the data from linregression.txt.\n    Return the solution x*.\n    \"\"\"\n    data = np.loadtxt(filename)\n    m,n = data.shape\n    b = data[:,0]\n    A = np.column_stack((np.ones(m),data[:,1:]))\n    x0 = np.random.random(n)\n    return conjugateGradient(A.T.dot(b),x0,A.T.dot(A))\n\n    '''Correct Answer:\n    [   -3482258.6159527,   15.06187214,    -0.03581918,    -2.0202298\n        -1.03322686,        -0.05110411,    1829.15145504               ]\n\n    or\n\n    [ -3.48225866e+06   1.50618728e+01  -3.58191800e-02  -2.02022981e+00\n      -1.03322687e+00  -5.11041030e-02   1.82915148e+03 ]\n    '''\n\n# Problem 3\ndef prob3(filename = 'logregression.txt'):\n    \"\"\"Use scipy.optimize.fmin_cg() to find the maximum likelihood estimate\n    for the data in logregression.txt.\n    \"\"\"\n    def objective(b):\n        return (np.log(1+np.exp(x.dot(b))) - y*(x.dot(b))).sum()\n    \n    data = np.loadtxt(filename)\n    m,n = data.shape\n    y = data[:,0]\n    x = np.empty_like(data)\n    x[:,0] = np.ones_like(data[:,0])\n    x[:,1:] = data[:,1:]\n    y = data[:,0]\n\n    guess = np.ones(4)\n    b = opt.fmin_cg(objective, guess)\n    \n    return b\n\n    '''Correct Answer:\n    [-0.41307717, 0.92181585, 0.21007539, -0.55791808]\n    '''\n    \nif __name__ == '__main__':\n    n = 10\n    A = np.random.random((n,n))\n    Q = A.T.dot(A)\n    b = np.random.random(n)\n    x0 = np.random.random(n)\n    x = conjugateGradient(b, x0, Q)\n    # np.set_printoptions(suppress=True)\n    if not np.allclose(x, la.solve(Q,b)):\n        raise ValueError(\"Problem 1 Failed\")\n    print prob2()\n    print prob3()\n    np.set_printoptions()\n    # test()", "meta": {"hexsha": "91aca2edd6991953dc11f1584571f4d3d60504ab", "size": 2694, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol2B/ConjugateGradient/solutions.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vol2B/ConjugateGradient/solutions.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vol2B/ConjugateGradient/solutions.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 27.4897959184, "max_line_length": 77, "alphanum_fraction": 0.5723830735, "include": true, "reason": "import numpy,from scipy", "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.909907012756525, "lm_q1q2_score": 0.8575934737202586}}
{"text": "import math\r\nimport numpy as np\r\nfrom random import randint\r\n\r\n\r\ndef PrimeGen(n=10000):\r\n    \"\"\" Returns  a list of primes < n. Used Robert William method of high speed prime generation. \"\"\"\r\n    assert n>=2\r\n    sieve = np.ones(n/2, dtype=np.bool)\r\n    for i in range(3,int(n**0.5)+1,2):\r\n        if sieve[i/2]:\r\n            sieve[i*i/2::i] = False\r\n    return np.r_[2, 2*np.nonzero(sieve)[0][1::]+1]\r\n\r\ndef lcm(p,q):\r\n    ''' Computes LCM between two Integers p,q'''\r\n    return (p*q)/math.gcd(p,q)\r\n\r\ndef extended_gcd(aa, bb):\r\n    lastremainder, remainder = abs(aa), abs(bb)\r\n    x, lastx, y, lasty = 0, 1, 1, 0\r\n    while remainder:\r\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\r\n        x, lastx = lastx - quotient*x, x\r\n        y, lasty = lasty - quotient*y, y\r\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\r\n\r\ndef modinv(a, m):\r\n    g, x, y = extended_gcd(a, m)\r\n    if g != 1:\r\n        raise ValueError\r\n    return x % m\r\n\r\ndef mult_inverse(e, lamda):\r\n    ''' Using the Euclidian extended algorithm '''\r\n    d = 0\r\n    x1 = 0\r\n    x2 = 1\r\n    y1 = 1\r\n    temp_lamda = lamda \r\n    \r\n    while e > 0:\r\n        temp1 = temp_lamda/e\r\n        temp2 = temp_lamda - temp1 * e\r\n        temp_lamda = e\r\n        e = temp2\r\n        \r\n        x = x2- temp1* x1\r\n        y = d - temp1 * y1\r\n        \r\n        x2 = x1\r\n        x1 = x\r\n        d = y1\r\n        y1 = y\r\n\r\n    if temp_lamda == 1:\r\n        return d + lamda\r\n\r\ndef keyGen():\r\n    ''' Generate  Keypair '''\r\n    i_p=randint(0,20)\r\n    i_q=randint(0,20)\r\n    # Instead of Asking the user for the prime Number which in case is not feasible,\r\n    # generate two numbers which is much highly secure as it chooses higher primes\r\n    while i_p==i_q:\r\n        continue\r\n    primes=PrimeGen(100)\r\n    p=primes[i_p]\r\n    q=primes[i_q]\r\n    #computing n=p*q as a part of the RSA Algorithm\r\n    n=p*q\r\n    #Computing lamda(n), the Carmichael's totient Function.\r\n    # In this case, the totient function is the LCM(lamda(p),lamda(q))=lamda(p-1,q-1)\r\n    # On the Contrary We can also apply the Euler's totient's Function phi(n)\r\n    #  which sometimes may result larger than expected\r\n    lamda_n=int(lcm(p-1,q-1))\r\n    e=randint(1,lamda_n)\r\n    #checking the Following : whether e and lamda(n) are co-prime\r\n    while math.gcd(e,lamda_n)!=1:\r\n        e=randint(1,lamda_n)\r\n    #Determine the modular Multiplicative Inverse\r\n    d=modinv(e,lamda_n)\r\n    #return the Key Pairs\r\n    # Public Key pair : (e,n), private key pair:(d,n)\r\n    return ((e,n),(d,n))\r\n\r\ndef encrypt(pk,message):\r\n    \"\"\" Perform RSA Encryption Algorithm\"\"\"\r\n    key, n = pk\r\n    #Convert each letter in the plaintext to numbers based on the character using a^b mod m\r\n    cipher = [(ord(char) ** key) % n for char in message]\r\n    #Return the array of bytes\r\n    return cipher\r\n\r\ndef decrypt(pk,cipher):\r\n    '''Perform RSA Decryption Algorithm '''\r\n    key, n = pk\r\n    #Generate the plaintext based on the ciphertext and key using a^b mod m\r\n    message = [chr((int(char) ** key) % n) for char in cipher]\r\n    #Return the array of bytes as a string\r\n    return ''.join(message)\r\n\r\n\r\n\r\n    \r\n    \r\n        \r\n\r\n\r\n\r\n\r\n\r\n    ", "meta": {"hexsha": "e993f0ba7042b080dad028c3157ec82efcf1418a", "size": 3228, "ext": "py", "lang": "Python", "max_stars_repo_path": "rsa.py", "max_stars_repo_name": "harsha0795/pyCrypt", "max_stars_repo_head_hexsha": "c688e585bfe101ac2b2687af149dd629632557dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-06-07T15:11:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T19:38:00.000Z", "max_issues_repo_path": "rsa.py", "max_issues_repo_name": "harsha0795/pyCrypt", "max_issues_repo_head_hexsha": "c688e585bfe101ac2b2687af149dd629632557dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rsa.py", "max_forks_repo_name": "harsha0795/pyCrypt", "max_forks_repo_head_hexsha": "c688e585bfe101ac2b2687af149dd629632557dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5663716814, "max_line_length": 102, "alphanum_fraction": 0.5802354399, "include": true, "reason": "import numpy", "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.983085087724427, "lm_q2_score": 0.8723473647220786, "lm_q1q2_score": 0.8575916855739775}}
{"text": "import numpy as np\n\n# Mathematical source for both Haar and Schauder(-Faber) bases: https://en.wikipedia.org/wiki/Haar_wavelet\n\n# Numpy implementation of Haar wavelet generation on [0,1]\ndef haar_wavelet(time_grid):\n    index_set1 = np.where( (0   <= time_grid) & (time_grid < 0.5) )\n    index_set2 = np.where( (0.5 <= time_grid) & (time_grid < 1  ) )\n    wavelet = np.zeros_like( time_grid )\n    wavelet[ index_set1 ] = 1\n    wavelet[ index_set2 ] = -1\n    return wavelet\n\ndef haar_basis_element(n, k, time_grid):\n    return (2.0**(0.5*n)) * haar_wavelet( (2**n)*time_grid- k)\n\n\n# Returns a total of 2**n_max basis functions corresponding to\n#   the Haar wavelets (n,k) corresponding to\n#   n=0, ..., n_max-1 and \n#   k=0, ..., 2**n - 1\ndef haar_basis( n_max, time_grid):\n    basis = []\n    # Constant function\n    basis.append( np.ones_like(time_grid) )\n    # The next ones (n>0)\n    for n in range(n_max):\n        basis = basis + [ haar_basis_element(n,k, time_grid) for k in range(2**n)]\n    return basis\n    \n\n# Numpy implementation of Schauder basis generation on [0,1]\n\n# Schauder elements are integrals of the Haar elements\ndef schauder_basis_element(n, k, time_grid):\n    haar_element =  haar_basis_element(n, k, time_grid)\n    element = np.zeros_like( haar_element )\n    element[1:] = (2**(1+0.5*n)) * 0.5* ( haar_element[:-1] + haar_element[1:] )* (time_grid[1:] - time_grid[:-1])\n    return element.cumsum()\n\ndef schauder_basis( n_max, time_grid):\n    basis = []\n    # Constant function\n    basis.append( np.ones_like(time_grid) )\n    # Identity map\n    basis.append( np.copy(time_grid) )\n    # The next ones (n>0)\n    for n in range(n_max):\n        basis = basis + [ schauder_basis_element(n,k, time_grid) for k in range(2**n)]\n    return basis", "meta": {"hexsha": "1a155572294bd291ae80b93a0c02d1ade703f0b5", "size": 1757, "ext": "py", "lang": "Python", "max_stars_repo_path": "fiberedae/utils/wavelets.py", "max_stars_repo_name": "LieGroupie/FiberedAE", "max_stars_repo_head_hexsha": "0796591fc89d9630c64cc29375c35ca24a30d277", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-03-21T02:27:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T23:47:03.000Z", "max_issues_repo_path": "fiberedae/utils/wavelets.py", "max_issues_repo_name": "LieGroupie/FiberedAE", "max_issues_repo_head_hexsha": "0796591fc89d9630c64cc29375c35ca24a30d277", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-20T01:04:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-20T01:04:31.000Z", "max_forks_repo_path": "fiberedae/utils/wavelets.py", "max_forks_repo_name": "LieGroupie/FiberedAE", "max_forks_repo_head_hexsha": "0796591fc89d9630c64cc29375c35ca24a30d277", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-18T21:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T07:07:05.000Z", "avg_line_length": 35.14, "max_line_length": 114, "alphanum_fraction": 0.6579396699, "include": true, "reason": "import numpy", "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.8976953003183444, "lm_q1q2_score": 0.8575854930604527}}
{"text": "import numpy as np\n#import matplotlib.pyplot as plt \n\ndef Gradient_descent(x,y):\n  m = 0\n  c = 0\n  L = 0.0001  # The learning Rate\n  epochs = 1000  #The number of iterations to perform gradient descent\n  n = len(X) # Number of elements in X\n  for i in range(epochs): \n    Y_pred = m*X + c  # The current predicted value of Y\n    D_m = (-2/n) * sum(X * (Y - Y_pred))  # Derivative wrt m\n    D_c = (-2/n) * sum(Y - Y_pred)  # Derivative wrt c\n    m = m - L * D_m  # Update m\n    c = c - L * D_c  # Update c\n  # print(m,c,i)\n  # print('Independent ',X)\n  # print('Dependent ',Y)\n  print('predicted values ',Y_pred)\n\n\nif __name__ == '__main__':\n  X = np.array([1,2,4,3,5])\n  Y = np.array([1,3,3,2,5])    \n  Gradient_descent(X,Y)\n\n''' \nAfter completing the gradient descent algorithms we found the optimal m & c respectively .\nm = 0.7652159238030152 c = 0.21788387785300492 \n'''\n", "meta": {"hexsha": "32b4bf93a1a9a1b3e0a3b7411b1207566814e026", "size": 874, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear regression/GradientDescent.py", "max_stars_repo_name": "profHajal/ML-practice", "max_stars_repo_head_hexsha": "1333b7ce2fa32eb53f6805c808e2e564a1d4e41a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-03T18:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T18:57:24.000Z", "max_issues_repo_path": "Linear regression/GradientDescent.py", "max_issues_repo_name": "profHajal/ML-practice", "max_issues_repo_head_hexsha": "1333b7ce2fa32eb53f6805c808e2e564a1d4e41a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear regression/GradientDescent.py", "max_forks_repo_name": "profHajal/ML-practice", "max_forks_repo_head_hexsha": "1333b7ce2fa32eb53f6805c808e2e564a1d4e41a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-07-29T09:49:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T15:24:11.000Z", "avg_line_length": 28.1935483871, "max_line_length": 90, "alphanum_fraction": 0.6224256293, "include": true, "reason": "import numpy", "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446517423792, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.8575833581503096}}
{"text": "from typing import List\nimport sympy as sp\nfrom sympy.matrices.dense import MutableDenseMatrix\n\nimport logging\nlogging.basicConfig(level=logging.WARN)\n\nclass InverseSolver:\n\n    def __init__(self,mat) -> None:\n        self.mat: MutableDenseMatrix = mat\n        self.dim = self.mat.shape[0]\n        self.course: List[MutableDenseMatrix] = []\n        self.is_Invertible = False if self.mat.det() == 0 else True #可逆标志\n\n    def getCourse(self) -> List[MutableDenseMatrix]:\n        if self.is_Invertible == False:\n            raise Exception('矩阵不可逆')\n\n        self.course.clear()\n        mat = self.mat.copy()\n        AE: MutableDenseMatrix = mat.row_join(sp.eye(self.dim)) #将原矩阵与单位矩阵连接，用Gauss-Jordan消元法求逆\n        self.course.append(AE)\n\n        #Gauss消元\n        for pivot_rowInd in range(self.dim-1): #最后一行不用选主元\n            pivot = AE[pivot_rowInd, pivot_rowInd]\n            #选主元，如果待消元的列不为0，则选为主元，否则选最开始一行的元素为主元\n            if pivot == 0:\n                for rowInd in range(pivot_rowInd+1, self.dim):\n                    if AE[rowInd, pivot_rowInd] != 0:\n                        AE = AE.elementary_row_op(op=\"n<->m\", row1=pivot_rowInd, row2=rowInd)\n                        self.course.append(AE.copy())\n                        break\n            #用主元所在的行消元\n            for rowInd in range(pivot_rowInd+1, self.dim):\n                if AE[rowInd, pivot_rowInd] != 0:\n                    k = -sp.Rational(AE[rowInd, pivot_rowInd], pivot)\n                    AE = AE.elementary_row_op(op='n->n+km', k=k, row1=rowInd, row2=pivot_rowInd)\n                    self.course.append(AE.copy())\n\n        #Jordan消元\n        for pivot_rowInd in range(self.dim-1, 0, -1): #第一行不用选主元\n            pivot = AE[pivot_rowInd, pivot_rowInd]\n            #先将主元化为1\n            if pivot != 1:\n                AE = AE.elementary_row_op(op='n->kn', k=sp.Rational(1, pivot), row=pivot_rowInd)\n                self.course.append(AE.copy())\n            #用主元所在的行消元\n            for rowInd in range(pivot_rowInd-1, -1, -1):\n                if AE[rowInd, pivot_rowInd] != 0:\n                    k = -AE[rowInd, pivot_rowInd]\n                    AE = AE.elementary_row_op(op='n->n+km', k=k, row1=rowInd, row2=pivot_rowInd)\n                    self.course.append(AE.copy())\n        return self.course\n\n    def getInverse(self) -> MutableDenseMatrix:\n        return self.mat.inv()\n\nif __name__ == '__main__':\n    mat = sp.Matrix([[1,0,0],[0,1,0],[0,0,3]])\n    logging.info(mat)\n    solver = InverseSolver(mat)\n    co = solver.getInverse()\n    logging.info(co)\n    logging.info(mat.inv())", "meta": {"hexsha": "19e3115f50508dce261665583601526002749192", "size": 2543, "ext": "py", "lang": "Python", "max_stars_repo_path": "lam/inverse/inverse.py", "max_stars_repo_name": "HelloMrGeorge/LinearAlgebraMachine", "max_stars_repo_head_hexsha": "78a002347341eb2612e8d9222e60663e06aad449", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2022-01-24T13:57:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T04:32:10.000Z", "max_issues_repo_path": "lam/inverse/inverse.py", "max_issues_repo_name": "HelloMrGeorge/LinearAlgebraMachine", "max_issues_repo_head_hexsha": "78a002347341eb2612e8d9222e60663e06aad449", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-09-27T07:15:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T14:56:37.000Z", "max_forks_repo_path": "lam/inverse/inverse.py", "max_forks_repo_name": "HelloMrGeorge/LinearAlgebraMachine", "max_forks_repo_head_hexsha": "78a002347341eb2612e8d9222e60663e06aad449", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5303030303, "max_line_length": 96, "alphanum_fraction": 0.5713723948, "include": true, "reason": "import sympy,from sympy", "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305370909698, "lm_q2_score": 0.8902942159342104, "lm_q1q2_score": 0.8575585757832934}}
{"text": "## 1. Individual Values ##\n\nimport pandas as pd\nhouses = pd.read_table('AmesHousing_1.txt')\n\nimport matplotlib.pyplot as plt\n\nhouses['SalePrice'].plot.kde(xlim = (houses['SalePrice'].min(),\n                                    houses['SalePrice'].max()\n                                    )\n                            )\n\nst_dev = houses['SalePrice'].std(ddof = 0)\nmean = houses['SalePrice'].mean()\nplt.axvline(mean, color = 'Black', label = 'Mean')\nplt.axvline(mean + st_dev, color = 'Red', label = 'Standard deviation')\nplt.axvline(220000, color = 'Orange', label = '220000')\nplt.legend()\nvery_expensive = False\n\n## 2. Number of Standard Deviations ##\n\ndistance = 220000 - houses['SalePrice'].mean()\nst_devs_away = distance / houses['SalePrice'].std(ddof=0)\nprint(distance)\nprint(st_devs_away)\n\n## 3. Z-scores ##\n\nmin_val = houses['SalePrice'].min()\nmean_val = houses['SalePrice'].mean()\nmax_val = houses['SalePrice'].max()\ndef z_score(value, array, bessel = 0):\n    mean = sum(array) / len(array)\n    \n    from numpy import std\n    st_dev = std(array, ddof = bessel)\n    \n    distance = value - mean\n    z = distance / st_dev\n    \n    return z\n\nmin_z = z_score(min_val, houses['SalePrice'])\nmean_z = z_score(mean_val, houses['SalePrice'])\nmax_z = z_score(max_val, houses['SalePrice'])\n\n## 4. Locating Values in Different Distributions ##\n\ndef z_score(value, array, bessel = 0):\n    mean = sum(array) / len(array)\n    \n    from numpy import std\n    st_dev = std(array, ddof = bessel)\n    \n    distance = value - mean\n    z = distance / st_dev\n    \n    return z\n\nnorth_ames = houses[houses['Neighborhood']=='NAmes']\nCollege_creek = houses[houses['Neighborhood']=='CollgCr']\nold_town = houses[houses['Neighborhood']=='OldTown']\nedwards = houses[houses['Neighborhood']=='Edwards']\nsomerset = houses[houses['Neighborhood']=='Somerst']\n\nnorth_ames_z = z_score(200000,north_ames['SalePrice'])\nCollege_creek_z = z_score(200000, College_creek['SalePrice'])\nold_town_z = z_score(200000, old_town['SalePrice'])\nedwards_z = z_score(200000, edwards['SalePrice'])\nsomerset_z = z_score(200000, somerset['SalePrice'])\nprint('north_ames ' + str(north_ames_z))\nprint('College_creek '+ str(College_creek_z))\nprint('old_town ' + str(old_town_z))\nprint('edwards ' + str(edwards_z))\nprint('somerset '+ str(somerset_z))\n\nbest_investment = 'College Creek'\n\n## 5. Transforming Distributions ##\n\nmean = houses['SalePrice'].mean()\nst_dev = houses['SalePrice'].std(ddof = 0)\nhouses['z_prices'] = houses['SalePrice'].apply(\n    lambda x: ((x - mean) / st_dev)\n    )\n\nz_mean_price = houses['z_prices'].mean()\nprint(z_mean_price)\nz_stdev_price = houses['z_prices'].std(ddof=0)\nprint(z_stdev_price)\n\nmean = houses['Lot Area'].mean()\nst_dev = houses['Lot Area'].std(ddof=0)\nhouses['z_area'] = houses['Lot Area'].apply(\n    lambda x: ((x - mean)/st_dev)\n    )\nz_mean_area = houses['z_area'].mean()\nz_stdev_area = houses['z_area'].std(ddof=0)\nprint(z_mean_area)\nprint(z_stdev_area)\n\n## 6. The Standard Distribution ##\n\nfrom numpy import std, mean\npopulation = [0,8,0,8]\nmean_pop = mean(population)\nstdev_pop = std(population, ddof = 0)\n\nstandardized_pop = []\nfor value in population:\n    z = (value - mean_pop) / stdev_pop\n    standardized_pop.append(z)\n    \nmean_z = mean(standardized_pop)\nstdev_z = std(standardized_pop, ddof = 0)\n\n## 7. Standardizing Samples ##\n\nfrom numpy import std, mean\nsample = [0,8,0,8]\n\nx_bar = mean(sample)\ns = std(sample, ddof = 1)\n\nstandardized_sample = []\nfor value in sample:\n    z = (value - x_bar) / s\n    standardized_sample.append(z)\nstdev_sample = std(standardized_sample, ddof = 1)\n\n## 8. Using Standardization for Comparisons ##\n\nmean_index1 = houses['index_1'].mean()\nstdev_index1 = houses['index_1'].std(ddof = 0)\nhouses['z_1'] = houses['index_1'].apply(lambda x: \n                                      (x - mean_index1) / stdev_index1\n                                     )\n\nmean_index2 = houses['index_2'].mean()\nstdev_index2 = houses['index_2'].std(ddof = 0)\nhouses['z_2'] = houses['index_2'].apply(lambda x: \n                                      (x - mean_index2) / stdev_index2\n                                     )\n\nprint(houses[['z_1', 'z_2']].head(2))\nbetter = 'first'\n\n## 9. Converting Back from Z-scores ##\n\nmean = 50\nst_dev = 10\nhouses['transformed'] = houses['z_merged'].apply(\n                                lambda z: (z * st_dev + mean)\n                                )\nmean_transformed = houses['transformed'].mean()\nstdev_transformed = houses['transformed'].std(ddof = 0)", "meta": {"hexsha": "7d2c25f0ae7aab22f516855e0aba18663bb1da75", "size": 4499, "ext": "py", "lang": "Python", "max_stars_repo_path": "5. Probability and Statistics/statistics-intermediate/Z-scores-309.py", "max_stars_repo_name": "bibekuchiha/dataquest", "max_stars_repo_head_hexsha": "c7d8a2966fe2eee864442a59d64309033ea9993e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5. Probability and Statistics/statistics-intermediate/Z-scores-309.py", "max_issues_repo_name": "bibekuchiha/dataquest", "max_issues_repo_head_hexsha": "c7d8a2966fe2eee864442a59d64309033ea9993e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5. Probability and Statistics/statistics-intermediate/Z-scores-309.py", "max_forks_repo_name": "bibekuchiha/dataquest", "max_forks_repo_head_hexsha": "c7d8a2966fe2eee864442a59d64309033ea9993e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6560509554, "max_line_length": 71, "alphanum_fraction": 0.6432540565, "include": true, "reason": "from numpy", "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305307578324, "lm_q2_score": 0.8902942152065091, "lm_q1q2_score": 0.8575585694439936}}
{"text": "# zeros\n# The zeros tool returns a new array with a given shape and type filled with 0's.\n\n# import numpy\n# print numpy.zeros((1,2))   # Default type is float\n# #Output : [[ 0.  0.]]\n\n# print numpy.zeros((1,2), dtype = numpy.int)   # Type changes to int\n# #Output : [[0 0]]\n\n# ones\n# The ones tool returns a new array with a given shape and type filled with 1's.\n\n# import numpy\n# print numpy.ones((1,2))   # Default type is float\n# #Output : [[ 1.  1.]]\n\n# print numpy.ones((1,2), dtype = numpy.int) #Type changes to int\n\n# #Output : [[1 1]]\n\n# Task\n# You are given the shape of the array in the form of space-separated integers, each integer representing the size\n# of different dimensions, your task is to print an array of the given shape and integer type using the tools numpy.zeros\n# and numpy.ones.\n\n# Input Format\n# A single line containing the space-separated integers.\n\nimport numpy as np\n\nabc = list(map(int, input().split()))\n\nprint(np.array(np.zeros(abc), dtype=np.int))\nprint(np.array(np.ones(abc), dtype=np.int))\n\n\n# Output Format\n# First, print the array using the numpy.zeros tool\n# and then print the array with the numpy.ones tool.\n\n# Sample Input 0\n# 3 3 3\n\n# Sample Output 0\n# [[[0 0 0]\n#   [0 0 0]\n#   [0 0 0]]\n\n#  [[0 0 0]\n#   [0 0 0]\n#   [0 0 0]]\n\n#  [[0 0 0]\n#   [0 0 0]\n#   [0 0 0]]]\n# [[[1 1 1]\n#   [1 1 1]\n#   [1 1 1]]\n\n#  [[1 1 1]\n#   [1 1 1]\n#   [1 1 1]]\n\n#  [[1 1 1]\n#   [1 1 1]\n#   [1 1 1]]]\n\n# Explanation 0\n# Print the array built using numpy.zeros and numpy.ones tools\n# and you get the result as shown.\n", "meta": {"hexsha": "1ec63023784a8d77a319b42e9c0cabd3a431c5a2", "size": 1539, "ext": "py", "lang": "Python", "max_stars_repo_path": "NEW_PRAC/HackerRank/Python/NumpyZerosAndOnes.py", "max_stars_repo_name": "side-projects-42/INTERVIEW-PREP-COMPLETE", "max_stars_repo_head_hexsha": "627a3315cee4bbc38a0e81c256f27f928eac2d63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-03-11T00:25:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T00:19:23.000Z", "max_issues_repo_path": "NEW_PRAC/HackerRank/Python/NumpyZerosAndOnes.py", "max_issues_repo_name": "side-projects-42/INTERVIEW-PREP-COMPLETE", "max_issues_repo_head_hexsha": "627a3315cee4bbc38a0e81c256f27f928eac2d63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 160, "max_issues_repo_issues_event_min_datetime": "2021-04-26T19:04:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T20:18:37.000Z", "max_forks_repo_path": "NEW_PRAC/HackerRank/Python/NumpyZerosAndOnes.py", "max_forks_repo_name": "side-projects-42/INTERVIEW-PREP-COMPLETE", "max_forks_repo_head_hexsha": "627a3315cee4bbc38a0e81c256f27f928eac2d63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-04-26T19:43:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T08:36:29.000Z", "avg_line_length": 21.375, "max_line_length": 121, "alphanum_fraction": 0.6302794022, "include": true, "reason": "import numpy", "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.9196425399873764, "lm_q1q2_score": 0.8575237311062218}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nprint(\"Formally we say that the Taylor series of a function is its representation as a power series. Let's see what this really means.\")\n\nprint(\"\\nConsider the cosine function from trigonometry. It has a nice smooth shape but if I asked you the cosine of some random number you'd probably have only a rough idea what the answer is. Traditionally it had to be worked out geometrically.\")\n\nprint(\"\\nWe can be more clever than that. There is one that we know for sure: cos(0) = 1. We will make an approximation starting with this requirement that approx(0) = 1.\")\n\nprint(\"\\nWhat should be used to make the approximation? Polynomials are very easy to evaluate and they can take lots of different shapes.\")\n\nprint(\"\\nSo lets start with the simplest polynomial... a horizontal line. There aren't many options here.\")\n\n\nprint(\"\\nObviously this isn't a very good quality approximation.\")\n\nprint(\"\\nTo make a better approximation we need to fit the curve of the cosine function. Fortunately that is a well known concept in calculus: the derivate.\")\n\nprint(\"\\nSo lets check the derivative of cos(0)... its zero. Our approximation also has a derivative of zero so we're matching!\")\n\nprint(\"\\n(Of course that means our approximation isn't any better.)\")\n\nprint(\"\\nBut the derivative doesn't tell the whole story. Lets check the second derivative of cos(0). That is -1!\")\n\nprint(\"\\nSo now we need to change our polynomial to give it a second derivative that is equal to -1. In order to have a second derivative it will have to be quadratic.\")\n\nprint(\"\\nSince polynomials are so well behaved this isn't a hard requirement to match. The power rule tells us that the second derivative of a quadratic polynomial is 2b, where b is the second coefficient. To make 2b = -1 we just have to say that b = -1/2.\")\n\nprint(\"\\nWe can continue in this way as long as desired. All of the odd terms will have a derivative of zero and so don't contribute. But each even term will make the approximation better.\")\n\n\nx = np.linspace(-5,5,100)\ny = np.cos(x)\n\napprox1 = [1]*len(x)\napprox2 = [1-(i**2)/2 for i in x]\napprox3 = [1-(i**2)/2+(i**4)/24 for i in x]\napprox4 = [1-(i**2)/2+(i**4)/24-(i**6)/720 for i in x]\n\nfig = plt.figure()\nax=fig.add_axes([0,0,1,1])\nax.set_axis_off()\n\nplt.ylim(-2,2)\nplt.plot(x,y)\nplt.plot(x,approx1)\nplt.title(\"First Approximation: 1\")\n\nfig = plt.figure()\nax=fig.add_axes([0,0,1,1])\nax.set_axis_off()\n\nplt.ylim(-2,2)\nplt.plot(x,y)\nplt.plot(x,approx2)\nplt.title(\"Second Approximation: 1 - (x^2)/2\")\n\nfig = plt.figure()\nax=fig.add_axes([0,0,1,1])\nax.set_axis_off()\n\nplt.ylim(-2,2)\nplt.plot(x,y)\nplt.plot(x,approx3)\nplt.title(\"Third Approximation: 1-(x^2)/2 + (x^4)/24\")\n\nfig = plt.figure()\nax=fig.add_axes([0,0,1,1])\nax.set_axis_off()\n\nplt.ylim(-2,2)\nplt.plot(x,y)\nplt.plot(x,approx4)\nplt.title(\"Fourth Approximation: 1-(x^2)/2 + (x^4)/24 - (x^6)/720\")", "meta": {"hexsha": "f924eacdb7b4201e1d457526739feb6ce68e6226", "size": 2896, "ext": "py", "lang": "Python", "max_stars_repo_path": "Visualization/TaylorSeriesOfSinFunction.py", "max_stars_repo_name": "SymmetricChaos/FiniteFields", "max_stars_repo_head_hexsha": "65258e06b7f04ce15223c1bc0c2384ef5e9cec1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-22T15:03:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-22T15:03:59.000Z", "max_issues_repo_path": "Visualization/TaylorSeriesOfSinFunction.py", "max_issues_repo_name": "SymmetricChaos/NumberTheory", "max_issues_repo_head_hexsha": "65258e06b7f04ce15223c1bc0c2384ef5e9cec1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Visualization/TaylorSeriesOfSinFunction.py", "max_forks_repo_name": "SymmetricChaos/NumberTheory", "max_forks_repo_head_hexsha": "65258e06b7f04ce15223c1bc0c2384ef5e9cec1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1351351351, "max_line_length": 258, "alphanum_fraction": 0.7220303867, "include": true, "reason": "import numpy", "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551515780318, "lm_q2_score": 0.8887588038050466, "lm_q1q2_score": 0.8575235103616284}}
{"text": "from os import stat\nimport numpy as np\nimport cv2 # OpenCV\nimport math\n\nfrom numpy.linalg.linalg import qr\n\nclass Rotations:\n    def __init__(self):\n\n        return\n\n    @staticmethod\n    def rot_mat_2_quat(R):\n        \"\"\"\n        Convert a rotation from rotation matrix to quaternion representation. Assumes that the columns of the rotation matrix are orthonomal!\n        \"\"\"\n\n        i, j, k = 0, 1, 2\n        if R[1,1] > R[0,1]:\n            i, j, k = 1, 2, 0\n\n        if R[2,2] > R[i,i]:\n            i, j, k = 2, 0, 1\n\n        t = R[i,i] - (R[j,j] + R[k,k]) + 1\n        q = np.array([0, 0, 0, 0])\n        q[0] = R[k,j] - R[j,k]\n        q[i+1] = t\n        q[j+1] = R[i,j] + R[j,i]\n        q[k+1] = R[k,i] + R[i,k]\n        q = np.multiply(q, 0.5 / math.sqrt(t))\n\n        return q\n\n    @staticmethod\n    def quat_2_rot_mat(q):\n        \"\"\"\n        Convert a rotation from rotation matrix to quaternion representation.\n        \"\"\"\n\n        s = np.linalg.norm(q) # s = 1 if the quaternion has unit length\n\n        R = np.zeros((3,3))\n        R[0,0] = 1 - 2 * s * (q[2]**2 + q[3]**2)\n        R[0,1] = 2 * s * (q[1]*q[2] - q[3]*q[0])\n        R[0,2] = 2 * s * (q[1]*q[3] + q[2]*q[0])\n        R[1,0] = 2 * s * (q[1]*q[2] + q[3]*q[0])\n        R[1,1] = 1 - 2 * s * (q[1]**2 + q[3]**2)\n        R[1,2] = 2 * s * (q[2]*q[3] - q[1]*q[0])\n        R[2,0] = 2 * s * (q[1]*q[3] - q[2]*q[0])\n        R[2,1] = 2 * s * (q[2]*q[3] + q[1]*q[0])\n        R[2,2] = 1 - 2 * s * (q[1]**2 + q[2]**2)\n\n        R = Rotations.orthonormal_mat(R)\n\n        return R\n\n    @staticmethod\n    def rot_mat_2_angle_axis(rot_mat):\n        theta = math.acos((np.trace(rot_mat) - 1) / 2)\n\n        return 1 / (2 * math.sin(theta)) * np.array([rot_mat[2,1] - rot_mat[1,2], rot_mat[0,2] - rot_mat[2,0], rot_mat[1,0] - rot_mat[0,1]]).reshape((3,1))\n\n    @staticmethod\n    def orthonormal_mat(mat):\n        # Perform SVD on rotation matrix to make the rows and columns orthonormal\n        U, _, V_transpose = np.linalg.svd(mat, full_matrices=True)\n        return np.matmul(U, V_transpose)", "meta": {"hexsha": "dbdfaa3d6944e0ffd51c93b2ea3bcbecd39f5f4c", "size": 2040, "ext": "py", "lang": "Python", "max_stars_repo_path": "tools/geometry/rotations.py", "max_stars_repo_name": "nicholaspalomo/VisionAlgosCourseETHZ", "max_stars_repo_head_hexsha": "dfaa442a274a3ded15833a44a60a012b4fd27654", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-07-29T02:26:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T10:50:40.000Z", "max_issues_repo_path": "tools/geometry/rotations.py", "max_issues_repo_name": "nicholaspalomo/VisionAlgosCourseETHZ", "max_issues_repo_head_hexsha": "dfaa442a274a3ded15833a44a60a012b4fd27654", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-27T10:28:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-04T02:07:23.000Z", "max_forks_repo_path": "tools/geometry/rotations.py", "max_forks_repo_name": "nicholaspalomo/VisionAlgosCourseETHZ", "max_forks_repo_head_hexsha": "dfaa442a274a3ded15833a44a60a012b4fd27654", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-07-29T02:27:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T10:50:42.000Z", "avg_line_length": 29.5652173913, "max_line_length": 155, "alphanum_fraction": 0.487745098, "include": true, "reason": "import numpy,from numpy", "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338090839606, "lm_q2_score": 0.8918110454379296, "lm_q1q2_score": 0.8575064715030815}}
{"text": "'''\nA robot is located at the top-left corner of a m x n grid \n(marked 'Start' in the diagram below).\n\nThe robot can only move either down or right at any point in time. \nThe robot is trying to reach the bottom-right corner of the \ngrid (marked 'Finish' in the diagram below).\n\nHow many possible unique paths are there?\n\nNote: m and n will be at most 100.\n\nExample 1:\n\nInput: m = 3, n = 2\nOutput: 3\nExplanation:\nFrom the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n1. Right -> Right -> Down\n2. Right -> Down -> Right\n3. Down -> Right -> Right\n\nExample 2:\n\nInput: m = 7, n = 3\nOutput: 28\n'''\nimport numpy as np\n\nclass Solution(object):\n    def uniquePaths(self, m, n):\n        \"\"\"\n        :type m: int\n        :type n: int\n        :rtype: int\n        \"\"\"\n        grid = np.array([[0 for i in range(m)] for j in range(n)])\n        grid[0, :] = 1\n        grid[:, 0] = 1\n        for i in range(1, m):\n            for j in range(1, n):\n                grid[j, i] = grid[j-1, i] + grid[j, i-1]\n        print(grid)\n        return grid[n-1, m-1]\n\nsol = Solution()\nm, n = [7,3]\nprint(sol.uniquePaths(m, n))\n", "meta": {"hexsha": "dc22e98966cc00a09d5e56f4648913233df9dcb5", "size": 1133, "ext": "py", "lang": "Python", "max_stars_repo_path": "top_400/dp/62_unique_paths.py", "max_stars_repo_name": "Fernadoo/LeetCode", "max_stars_repo_head_hexsha": "05d703672d55f46c3b2603429b8ae83502ec62c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "top_400/dp/62_unique_paths.py", "max_issues_repo_name": "Fernadoo/LeetCode", "max_issues_repo_head_hexsha": "05d703672d55f46c3b2603429b8ae83502ec62c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "top_400/dp/62_unique_paths.py", "max_forks_repo_name": "Fernadoo/LeetCode", "max_forks_repo_head_hexsha": "05d703672d55f46c3b2603429b8ae83502ec62c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1224489796, "max_line_length": 87, "alphanum_fraction": 0.587819947, "include": true, "reason": "import numpy", "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338123908151, "lm_q2_score": 0.8918110418436166, "lm_q1q2_score": 0.8575064709961174}}
{"text": "import numpy as np\n\nx = np.array([[1, 3, 5], [7, 9, 11]])\ny = np.array([[1, 2], [3, 4], [5, 6]])\n\nprint(np.dot(x, y)) #行列積\n\n'''\n[[ 35  44]\n [ 89 116]]\n'''\n\nprint(x.dot(y)) #行列積\n\n'''\n[[ 35  44]\n [ 89 116]]\n'''\n\nprint(x @ y) #行列積\n\n'''\n[[ 35  44]\n [ 89 116]]\n'''", "meta": {"hexsha": "ac0b7729dd7cf1eed0a52cfde5934a6c557068ae", "size": 259, "ext": "py", "lang": "Python", "max_stars_repo_path": "appendix/mult_1.py", "max_stars_repo_name": "skillup-ai/tettei-engineer", "max_stars_repo_head_hexsha": "d3f8a36c068db44391afcf4727ccbb7c456852c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2021-02-10T11:10:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T13:27:50.000Z", "max_issues_repo_path": "appendix/mult_1.py", "max_issues_repo_name": "skillup-ai/tettei-engineer", "max_issues_repo_head_hexsha": "d3f8a36c068db44391afcf4727ccbb7c456852c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "appendix/mult_1.py", "max_forks_repo_name": "skillup-ai/tettei-engineer", "max_forks_repo_head_hexsha": "d3f8a36c068db44391afcf4727ccbb7c456852c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-02-10T12:14:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T00:55:22.000Z", "avg_line_length": 10.36, "max_line_length": 38, "alphanum_fraction": 0.4208494208, "include": true, "reason": "import numpy", "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338079816756, "lm_q2_score": 0.891811044719067, "lm_q1q2_score": 0.8575064698288409}}
{"text": "import torch\nimport numpy as np\n\ndef decayconst(tau, dt):\n    if type(tau) == torch.Tensor:\n        return torch.exp(-dt/tau)\n    return float(np.exp(-dt/tau))\n\ndef sigmoid_project(value, bounds, framework = torch):\n    return bounds[0] + (bounds[1]-bounds[0])/(1 + framework.exp(-value))\n\ndef expfilt(target, filtered, alpha):\n    return alpha*filtered + (1 - alpha)*target\n\n# Sunflower seed pattern:\n# https://stackoverflow.com/questions/28567166/uniformly-distribute-x-points-inside-a-circle\nphi = (np.sqrt(5)+1)/2 # The golden ratio\ndef sunflower(n, alpha=1):\n    '''\n    Returns a sunflower seed pattern of n points. alpha>1 causes truncation of\n    radii at the outer edge, making a smoother boundary.\n    '''\n    b = torch.tensor(np.round(alpha * np.sqrt(n)))\n    k = torch.arange(1,n+1)\n    r = torch.sqrt(k-1/2) / torch.sqrt(n - (b+1)/2)\n    r[r>1] = 1\n    theta = 2*np.pi*k / phi**2\n    return r, theta\n\ndef broadcast_outer(a,b):\n    assert a.dim() == b.dim() == 1\n    a = a.reshape(-1,1).expand(-1,len(b))\n    b = b.reshape(1,-1)\n    return a,b\n\ndef polar_dist(r1, th1, r2, th2):\n    r1,r2 = broadcast_outer(r1,r2)\n    th1,th2 = broadcast_outer(th1,th2)\n    return torch.sqrt(r1**2 + r2**2 - 2*r1*r2*torch.cos(th1-th2))\n\ndef cartesian(r, theta):\n    return r*theta.cos(), r*theta.sin()\n", "meta": {"hexsha": "3c7283ac78432313abd4406bdd03fff64bfd180b", "size": 1297, "ext": "py", "lang": "Python", "max_stars_repo_path": "cantata/util.py", "max_stars_repo_name": "kernfel/cantata", "max_stars_repo_head_hexsha": "ec0a7944efa88b9dc8eac50d2df8aa00b6c87481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cantata/util.py", "max_issues_repo_name": "kernfel/cantata", "max_issues_repo_head_hexsha": "ec0a7944efa88b9dc8eac50d2df8aa00b6c87481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cantata/util.py", "max_forks_repo_name": "kernfel/cantata", "max_forks_repo_head_hexsha": "ec0a7944efa88b9dc8eac50d2df8aa00b6c87481", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1627906977, "max_line_length": 92, "alphanum_fraction": 0.6407093292, "include": true, "reason": "import numpy", "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.961533804674821, "lm_q2_score": 0.8918110360927155, "lm_q1q2_score": 0.8575064585852228}}
{"text": "import tkinter\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import svm\n\n## HELPER FUNCTIONS ##\n\ndef plot_decision_function(model, ax, sv=True):\n    ## Create a grid to evaluate the model\n    xx, yy = np.meshgrid(np.linspace(-4, 4, 100),\n                         np.linspace(-4, 4, 100))\n    ## Evaluate the model\n    Z = model.decision_function(np.c_[xx.ravel(), yy.ravel()])\n    Z = Z.reshape(xx.shape)\n    \n    ## Plot the margin\n    ax = plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='darkred')\n    ax = plt.contourf(xx, yy, Z, levels=[0, Z.max()], colors='palevioletred')\n    \n    ax = plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), 0, 6), cmap=plt.cm.PuBu)\n    \n    if sv:\n        ax = plt.scatter(model.support_vectors_[:, 0],\n                       model.support_vectors_[:, 1],\n                       s=300, linewidth=1, facecolors='none', edgecolors='black')\n\n\ndef plot_new_observations(X_train, X_new, anomaly, ax):\n    _ = plt.scatter(X_train[:,0], X_train[:,1],\n                    axes=ax, color='w', s=40, edgecolors='k',\n                    label='Training data')\n\n    _ = plt.scatter(X_new[:,0], X_new[:,1], axes=ax,\n                    color='violet', s=40, edgecolors='k',\n                    label='New regular observations')\n\n    _ = plt.scatter(anomaly[:,0], anomaly[:,1], axes=ax,\n                    color='gold', s=40, edgecolors='k',\n                    label='New abnormal observations')\n\n    _ = ax.legend()\n    _ = ax.set_xlim([-4, 4])\n    _ = ax.set_ylim([-4, 4])\n\n\nn_points = 200\n\n## generate a cluster of points for the training \nnp.random.seed(42)\nX_train = 0.5 * np.random.randn(n_points, 2)\n\n## Plot\nfig, ax = plt.subplots(figsize=(12,8))\n_ = plt.scatter(X_train[:,0], X_train[:,1], axes=ax, color='w', s=40, edgecolors='k')\n_ = ax.set_xlim([-4, 4])\n_ = ax.set_ylim([-4, 4])\n\n\nmodel = svm.OneClassSVM(nu=0.05, kernel=\"rbf\", gamma=0.7)\nmodel.fit(X_train)\n\nfig, ax = plt.subplots(figsize=(12,8))\n\n## Plot the decision function\nplot_decision_function(model, ax, sv=True)\n\n## Add the training points\n_ = plt.scatter(X_train[:,0], X_train[:,1], axes=ax,\n                color='w', s=40, edgecolors='k',label='Training data')\n_ = ax.legend()\n\n\n## Compute the empirical error \ny_train = model.predict(X_train)\nerr_emp_1 = y_train[y_train == -1].size\nprint(\"Training error = {}/{}\".format(err_emp_1, n_points))\n\n\n## Reduce nu, i.e. weight more the slack variables\nmodel = svm.OneClassSVM(nu=0.005, kernel=\"rbf\", gamma=0.7)\nmodel.fit(X_train)\n\nfig, ax = plt.subplots(figsize=(12,8))\n\n## Plot the decision function\nplot_decision_function(model, ax, sv=True)\n\n## Add the training points\n_ = plt.scatter(X_train[:,0], X_train[:,1], axes=ax,\n                color='w', s=40, edgecolors='k',label='Training data')\n_ = ax.legend()\n\n## Compute the empirical error \ny_train = model.predict(X_train)\nerr_emp_2 = y_train[y_train == -1].size\nprint(\"Training error = {}/{}\".format(err_emp_2, n_points))\n# Training error = 5/200\n\n\"\"\"\nAs we can see from the picture above, by reducing $\\nu$ we are increasing the weight of the slack variables (because $C \\sim 1/\\nu$). This leads to a reduction of the error but increase the risk of overfitting.\n\"\"\"\n\nnew_observation = 25\nnew_anomaly = 10\n\n## Generate new observation from the same distribution\nnp.random.seed(42)\nX_new = 0.5 * np.random.randn(new_observation, 2)\n\n## Generate outliers\nanomaly = np.random.uniform(low=-3, high=3, size=(new_anomaly, 2))\n\n## Plot\nfig, ax = plt.subplots(figsize=(12,8))\nplot_new_observations(X_train, X_new, anomaly, ax)\n\ny_new = model.predict(X_new)\ny_anomaly = model.predict(anomaly)\n\nerr_new = y_new[y_new == -1].size\nerr_anomaly = y_anomaly[y_anomaly == -1].size\n\nprint(\"Fraction of new regular observations misclassified = {}/{}\".format(err_new, new_observation))\nprint(\"Fraction of new abnormal observations correctly classified = {}/{}\".format(err_anomaly, new_anomaly))\n\nfig, ax = plt.subplots(figsize=(12,8))\n\n## Plot the decision function\nplot_decision_function(model, ax, sv=False)\nplot_new_observations(X_train, X_new, anomaly, ax)\n# Fraction of new regular observations misclassified = 0/25\n# Fraction of new abnormal observations correctly classified = 10/10\n\n# Let's try to make the problem a little bit more complex, i.e. use two clusters as positive examples\n\n## generate two cluster for the training \nnp.random.seed(42)\nX_train1 = 0.5 * np.random.randn(n_points//2, 2)+1.5\nX_train2 = 0.5 * np.random.randn(n_points//2, 2)-1.5\n\nX_train = np.r_[X_train1, X_train2]\n\n## Plot\nfig, ax = plt.subplots(figsize=(12,8))\n_ = plt.scatter(X_train[:,0], X_train[:,1], axes=ax, color='w', s=40, edgecolors='k')\n_ = ax.set_xlim([-4, 4])\n_ = ax.set_ylim([-4, 4])\n\nmodel = svm.OneClassSVM(nu=0.06, kernel=\"rbf\", gamma=0.5)\nmodel.fit(X_train)\n\nfig, ax = plt.subplots(figsize=(12,8))\n\n## Plot the decision function\nplot_decision_function(model, ax, sv=True)\n\n## Add the training points\n_ = plt.scatter(X_train[:,0], X_train[:,1], axes=ax,\n                color='w', s=40, edgecolors='k',label='Training data')\n_ = ax.legend()\n\n## Compute the empirical error \ny_train = model.predict(X_train)\nerr_emp_1 = y_train[y_train == -1].size\nprint(\"Training error = {}/{}\".format(err_emp_1, n_points))\n\nnew_observation = 50\nnew_anomaly = 20\n\n## Generate new observation from the same distribution\nnp.random.seed(42)\nX_new_1 = 0.5 * np.random.randn(new_observation//2, 2)+1.5\nX_new_2 = 0.5 * np.random.randn(new_observation//2, 2)-1.5\nX_new = np.r_[X_new_1, X_new_2]\n\n## Generate outliers\nanomaly = np.random.uniform(low=-4, high=4, size=(new_anomaly, 2))\n\n## Plot\nfig, ax = plt.subplots(figsize=(12,8))\nplot_new_observations(X_train, X_new, anomaly, ax)\n\n\ny_new = model.predict(X_new)\ny_anomaly = model.predict(anomaly)\n\nerr_new = y_new[y_new == -1].size\nerr_anomaly = y_anomaly[y_anomaly == -1].size\n\nprint(\"Fraction of new regular observations misclassified = {}/{}\".format(err_new, new_observation))\nprint(\"Fraction of new abnormal observations correctly classified = {}/{}\".format(err_anomaly, new_anomaly))\n\nfig, ax = plt.subplots(figsize=(12,8))\n\n## Plot the decision function\nplot_decision_function(model, ax, sv=False)\nplot_new_observations(X_train, X_new, anomaly, ax)\n# Fraction of new regular observations misclassified = 2/50\n# Fraction of new abnormal observations correctly classified = 18/20\n\n# We can try to move the cluster closer\n\nnp.random.seed(42)\nX_train1 = 0.5 * np.random.randn(n_points//2, 2)+0.9\nX_train2 = 0.5 * np.random.randn(n_points//2, 2)-0.9\n\nX_train = np.r_[X_train1, X_train2]\n\n## Plot\nfig, ax = plt.subplots(figsize=(12,8))\n_ = plt.scatter(X_train[:,0], X_train[:,1], axes=ax, color='w', s=40, edgecolors='k')\n_ = ax.set_xlim([-4, 4])\n_ = ax.set_ylim([-4, 4])\n\n\nmodel = svm.OneClassSVM(nu=0.05, kernel=\"rbf\", gamma=0.1)\nmodel.fit(X_train)\n\nfig, ax = plt.subplots(figsize=(12,8))\n\n## Plot the decision function\nplot_decision_function(model, ax, sv=True)\n\n## Add the training points\n_ = plt.scatter(X_train[:,0], X_train[:,1], axes=ax,\n                color='w', s=40, edgecolors='k',label='Training data')\n_ = ax.legend()\n\n## Compute the empirical error \ny_train = model.predict(X_train)\nerr_emp_1 = y_train[y_train == -1].size\nprint(\"Training error = {}/{}\".format(err_emp_1, n_points))\n\n# If we want to try to separate the two cluster we need to increase the value of gamma and $\\nu$ but this increase the errors a lot.\n\nmodel = svm.OneClassSVM(nu=0.3, kernel=\"rbf\", gamma=1)\nmodel.fit(X_train)\n\nfig, ax = plt.subplots(figsize=(12,8))\n\n## Plot the decision function\nplot_decision_function(model, ax, sv=True)\n\n## Add the training points\n_ = plt.scatter(X_train[:,0], X_train[:,1], axes=ax,\n                color='w', s=40, edgecolors='k',label='Training data')\n_ = ax.legend()\n\n## Compute the empirical error \ny_train = model.predict(X_train)\nerr_emp_1 = y_train[y_train == -1].size\nprint(\"Training error = {}/{}\".format(err_emp_1, n_points))\n\n", "meta": {"hexsha": "d377e82f102e7da986806e4ec7dbd13d276f86b9", "size": 7895, "ext": "py", "lang": "Python", "max_stars_repo_path": "projects/novelty/anomaly_1.py", "max_stars_repo_name": "futureseadev/hgwxx7", "max_stars_repo_head_hexsha": "282b370afc7d9c277e6c1f5b31282f14f9236f7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-06-21T09:44:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T18:37:41.000Z", "max_issues_repo_path": "projects/novelty/anomaly_1.py", "max_issues_repo_name": "futureseadev/hgwxx7", "max_issues_repo_head_hexsha": "282b370afc7d9c277e6c1f5b31282f14f9236f7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:55:52.000Z", "max_forks_repo_path": "projects/novelty/anomaly_1.py", "max_forks_repo_name": "praveentn/hgwxx7", "max_forks_repo_head_hexsha": "282b370afc7d9c277e6c1f5b31282f14f9236f7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-06-25T16:40:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:37:42.000Z", "avg_line_length": 31.0826771654, "max_line_length": 210, "alphanum_fraction": 0.674350855, "include": true, "reason": "import numpy", "num_tokens": 2260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.9149009607937929, "lm_q1q2_score": 0.8574550519163437}}
{"text": "from sympy import *\nfrom datetime import datetime\n\nif __name__ == \"__main__\":\n    \"\"\"使用SymPy进行方程求解\"\"\"\n    x = Symbol('x')\n    # str = '100 * (1 + x)**3 - 200'\n    str = '5000 * (1 + x)**1 + 5000*(1 + x)**1.6 + 5000*(1 + x)**1.2 - 15000'\n    print(solve(str, x))\n    # print(solve(str, x)[0].evalf())\n    # print(solve(str, x))\n    # print(solve(2 ** x - 4, x))\n", "meta": {"hexsha": "8e506d9c60fcb18f6f8c8f528ae55534fac16a92", "size": 361, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/learn/sympy_learn.py", "max_stars_repo_name": "CatTiger/vnpy", "max_stars_repo_head_hexsha": "7901a0fb80a5b44d6fc752bd4b2b64ec62c8f84b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/learn/sympy_learn.py", "max_issues_repo_name": "CatTiger/vnpy", "max_issues_repo_head_hexsha": "7901a0fb80a5b44d6fc752bd4b2b64ec62c8f84b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-21T02:42:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-21T02:42:32.000Z", "max_forks_repo_path": "tests/learn/sympy_learn.py", "max_forks_repo_name": "CatTiger/vnpy", "max_forks_repo_head_hexsha": "7901a0fb80a5b44d6fc752bd4b2b64ec62c8f84b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7692307692, "max_line_length": 77, "alphanum_fraction": 0.512465374, "include": true, "reason": "from sympy", "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357622402971, "lm_q2_score": 0.8757869916479466, "lm_q1q2_score": 0.8574267849281841}}
{"text": "# https://docs.sympy.org/latest/tutorial/basic_operations.html\n\nfrom sympy import *\nx, y, z = symbols(\"x y z\")\n\nexpr = cos(x) + 1\nprint(expr)\nprint(expr.subs(x, y))\n\nprint(expr.subs(x, 0))\n\nexpr = x**y\nprint(expr)\nexpr = expr.subs(y, x**y)\nprint(expr)\nexpr = expr.subs(y, x**x)\nprint(expr)\n\nexpr = sin(2*x) + cos(2*x)\nprint(expr)\nprint(type(expr))\nprint(expand_trig(expr))\nprint(expr.subs(sin(2*x), 2*sin(x)*cos(x)))\n\n# \"SymPy expressions are immutable\"\n\nexpr = cos(x)\nprint(expr)\nprint(expr.subs(x, 0))\nprint(expr)\nprint(x)\n\nexpr = x**3 + 4*x*y - z\nprint(expr)\nprint(expr.subs([(x, 2), (y, 4), (z, 0)]))\n\nexpr = x**4 - 4*x**3 + 4*x**2 - 2*x + 3\nprint(expr)\nreplacements = [(x**i, y**i) for i in range(5) if i % 2 == 0]\nprint(replacements)\nprint(expr.subs(replacements))\n\n# why not just do a simple loop?\n\nreplacements=[]\n\nfor i in range(5):\n    if i % 2 == 0:\n        replacements.append((x**i, y**i))\n        \nprint(replacements)\nprint(expr.subs(replacements))\n       \nstr_expr = \"x**2 + 3*x - 1/2\"\nprint(type(str_expr))\nprint(str_expr)\nexpr = sympify(str_expr)\nprint(type(expr))\nprint(expr)\nprint(expr.subs(x, 2))\n\nexpr = sqrt(8)\nprint(expr)\nprint(expr.evalf())\n\n# substitute variable for number and\n# evaluate to float\n\nexpr = cos(2*x)\nprint(expr)\nprint(expr.evalf(subs={x: 2.4}))\n\nimport numpy \na = numpy.arange(10) \nexpr = sin(x)\nprint(expr)\nf = lambdify(x, expr, \"numpy\") \nprint(f(a))\nprint(type(f))\n\nf = lambdify(x, expr, \"math\")\nprint(f(0.1))\n\ndef mysin(x):\n    \"\"\"\n    My sine. Note that this is only accurate for small x.\n    \"\"\"\n    return x\n    \nf = lambdify(x, expr, {\"sin\":mysin})\nprint(f(0.1))\n\n\n\n", "meta": {"hexsha": "24999508cffffd95983475dc43f6bc6302a3ef00", "size": 1613, "ext": "py", "lang": "Python", "max_stars_repo_path": "c6.py", "max_stars_repo_name": "bobbydurrett/sympytutorial", "max_stars_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c6.py", "max_issues_repo_name": "bobbydurrett/sympytutorial", "max_issues_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c6.py", "max_forks_repo_name": "bobbydurrett/sympytutorial", "max_forks_repo_head_hexsha": "071b2f0de8b6934556ab1e48d180e424bcbd7345", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.9789473684, "max_line_length": 62, "alphanum_fraction": 0.6249225046, "include": true, "reason": "import numpy,from sympy", "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.907312226373181, "lm_q1q2_score": 0.8574052543838165}}
{"text": "import numpy as np\n\ndef euclidean_distance(a, b):\n    \"\"\"\n    Calculate the Euclidean distance of two vectors\n    \"\"\"\n    distance = 0\n    for x, y in zip(a, b):\n        distance += (x - y) ** 2\n\n    return sqrt(distance)\n\n\ndef snake_distance(a, b):\n    \"\"\"\n    Calculate the Manhattan distance of two vectors.\n    \"\"\"\n    distance = 0\n    for x, y in zip(a, b):\n        distance += (x - y)\n\n    return distance\n\n\ndef chebyshev_distance(a, b):\n    \"\"\"\n    Calculate the Chebyshev distance of two vectors.\n    \"\"\"\n    distances = []\n    for x, y in zip(a, b):\n        distances.append(abs(x - y))\n    distance = max(distances)\n\n    return distance\n\n\ndef entropy(feature_data):\n    \"\"\"\n    Example playTennis entropy([\"yes\",\"yes\",\"yes\",\"yes\",\"yes\",\"yes\",\"yes\",\"yes\",\"yes\",\"no\",\"no\",\"no\",\"no\",\"no\"])\n    Calculates the entropy for a feature data.\n    \"\"\"\n    if len(feature_data) == 0:\n        return 1.02\n    data_and_uniqe = np.unique(feature_data, return_inverse=True)\n    pi = np.bincount(data_and_uniqe[1]).astype(np.float64)\n    return np.sum(- pi/len(feature_data) * np.log2(pi/len(feature_data)))\n\n\ndef information_gain(sample, labels):\n    \"\"\"\n    sample = [31, 34, 32, 20, 11, 10, 8, 23, 7, 21, 23]\n    labels = [0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1]\n    # we will sort the first array, and also the second one\n    # labels = [1, 1, 1, 1, 1, | 0, 0, | 1, | 0, 0, 0]\n    # we calculate the information gain from each split and we return the\n    # higher value\n    \"\"\"\n\n    global_entropy = entropy(labels)\n    cardinality = float(sample.shape[0])\n\n    indexes = np.argsort(sample)\n    flag = labels[indexes][0]\n\n    splits_indexes = {}\n\n    for pos, element in enumerate(labels[indexes]):\n\n        # adjacent examples with different classes, for example: 1.0 and 0.0\n        if flag != element:\n            mean = (sample[indexes][pos] - sample[indexes][pos-1])/2.0\n            split = sample[indexes][pos - 1] + mean\n            splits_indexes[pos] = str(split)\n            flag = element\n\n    # get best split\n    best_gain = ('0', 0.0)\n\n    for index in splits_indexes:\n\n        # < less-than split\n        # index is the same as cardinality of subsets\n        total =+ (index/cardinality) * entropy(labels[indexes][:index])\n        # >= more-equal-than split\n        total += ((cardinality - index)/cardinality) * entropy(labels[indexes][index:])\n\n        gain = global_entropy - total\n\n        if gain > best_gain[1]:\n            best_gain = (splits_indexes[index], gain)\n\n    # a tuple of the split value and the gain\n    return best_gain\n", "meta": {"hexsha": "c445156d166aee8e0a0ed7564b9410de936ea6f0", "size": 2546, "ext": "py", "lang": "Python", "max_stars_repo_path": "schiffsdiebe/utils/__init__.py", "max_stars_repo_name": "omartrinidad/schiffsdiebe", "max_stars_repo_head_hexsha": "5ee70bf1ee3bb36cdb1ed62396aa0b3690c1c7da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "schiffsdiebe/utils/__init__.py", "max_issues_repo_name": "omartrinidad/schiffsdiebe", "max_issues_repo_head_hexsha": "5ee70bf1ee3bb36cdb1ed62396aa0b3690c1c7da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "schiffsdiebe/utils/__init__.py", "max_forks_repo_name": "omartrinidad/schiffsdiebe", "max_forks_repo_head_hexsha": "5ee70bf1ee3bb36cdb1ed62396aa0b3690c1c7da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.085106383, "max_line_length": 112, "alphanum_fraction": 0.5934799686, "include": true, "reason": "import numpy", "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104914476339, "lm_q2_score": 0.8872045877523147, "lm_q1q2_score": 0.85740382166431}}
{"text": "# Monte Carlo Valuation of a European Option in a Black-Scholes World\r\n# With implementation of Delta-based control variate method\r\n# by Michal Lyskawinski\r\n# 10/31/2016\r\n\r\nfrom math import *\r\nimport numpy as np\r\nimport random\r\nfrom scipy.stats import norm\r\n\r\n\r\ndef CBS(S, K, T, r, sigma,t, option):\r\n\r\n    t2t = T-t # time to maturity\r\n    # Calculations for the solution to BSM equation\r\n    dplus = (1 / (sigma * sqrt(t2t))) * ((log(S / K)) + (r + ((sigma ** 2) / 2)) * t2t)\r\n    dminus = (1 / (sigma * sqrt(t2t))) * ((log(S / K)) + (r - (sigma ** 2) / 2) * t2t)\r\n\r\n    # Calculating price of Call and Put\r\n    if option == 'Call':\r\n        return S * norm.cdf(dplus) - K * exp(-r * t2t) * norm.cdf(dminus)\r\n    elif option == 'Put':\r\n        return K * exp(-r * t2t) * norm.cdf(-dminus) - S * norm.cdf(-dplus)\r\n\r\n\r\n# Initialize parameters\r\nS = 100\r\nr = 0.06\r\nsig = 0.2\r\nT = 1\r\nK = 100\r\nN = 10\r\nM = 100\r\ndiv = 0.03  # In percentage\r\noption = 'Call'\r\n\r\n# Precompute constants\r\ndt = T/N\r\nnu = r - div - 0.5*(sig**2)\r\nnudt = nu*dt\r\nsigsdt = sig*sqrt(dt)\r\nerddt = exp((r-div)*dt)\r\n\r\nbeta1 = -1\r\n\r\nsum_CT = 0\r\nsum_CT2 = 0\r\n\r\nfor j in range(1,M): # For each simulation\r\n\r\n    St = S\r\n    cv = 0\r\n\r\n    for i in range(1,N): # For each time step\r\n        t = (i-1)*dt\r\n        delta = CBS(St,K,T,r,sig,t,option)\r\n        eps = np.random.normal(0, 1)\r\n        Stn = St*exp(nudt+sigsdt*eps)\r\n        cv1 = cv + delta*(Stn-St*erddt)\r\n        St = Stn\r\n\r\n\r\n    if option == 'Call':\r\n        CT = max(0, St - K) + beta1*cv1\r\n        sum_CT = sum_CT + CT\r\n        sum_CT2 = sum_CT2 + CT*CT\r\n    elif option == 'Put':\r\n        CT = max(0, K - St) + beta1*cv1\r\n        sum_CT = sum_CT + CT\r\n        sum_CT2 = sum_CT2 + CT * CT\r\n    else:\r\n        break\r\n\r\n\r\nValue = sum_CT/M*exp(-r*T)\r\nSD = sqrt((sum_CT2 - sum_CT*sum_CT/M)*exp(-2*r*T)/(M-1))\r\nSE = SD/sqrt(M)\r\n\r\n\r\nprint('The Value of European',option,'Option is',Value)\r\nprint('The Standard Deviation of this Option is',SD)\r\nprint('The Standard Error in this case is',SE)\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "d7919242b41242b27a14b6bce98f915d36320f15", "size": 2021, "ext": "py", "lang": "Python", "max_stars_repo_path": "DELTA.py", "max_stars_repo_name": "lawyertechie/Quant-Projects", "max_stars_repo_head_hexsha": "0b5f53b9d1ea8403e29606b762a5d82f26c3dda2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2019-03-23T14:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T10:22:45.000Z", "max_issues_repo_path": "DELTA.py", "max_issues_repo_name": "Michalos88/Quant-Projects", "max_issues_repo_head_hexsha": "0b5f53b9d1ea8403e29606b762a5d82f26c3dda2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DELTA.py", "max_forks_repo_name": "Michalos88/Quant-Projects", "max_forks_repo_head_hexsha": "0b5f53b9d1ea8403e29606b762a5d82f26c3dda2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-03-30T17:41:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T07:44:05.000Z", "avg_line_length": 22.9659090909, "max_line_length": 88, "alphanum_fraction": 0.5512122712, "include": true, "reason": "import numpy,from scipy", "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9828232904845686, "lm_q2_score": 0.8723473829749844, "lm_q1q2_score": 0.8573633253810763}}
{"text": "import numpy as np\nimport scipy.optimize as op\n\ndef Sigmoid(z):\n    return 1/(1 + np.exp(-z))\n\ndef Gradient(theta,x,y):\n    m , n = x.shape\n    theta = theta.reshape((n,1))\n    y = y.reshape((m,1))\n    sigmoid_x_theta = Sigmoid(x.dot(theta))\n    grad = ((x.T).dot(sigmoid_x_theta-y))/m\n    return grad.flatten()\n\ndef CostFunc(theta,x,y):\n    m,n = x.shape; \n    theta = theta.reshape((n,1))\n    y = y.reshape((m,1))\n    term1 = np.log(Sigmoid(x.dot(theta)))\n    term2 = np.log(1-Sigmoid(x.dot(theta)))\n    term1 = term1.reshape((m,1))\n    term2 = term2.reshape((m,1))\n    term = y * term1 + (1 - y) * term2\n    J = -((np.sum(term))/m)\n    return J\n\n'''\n# intialize X and y\nX = np.array([[1,2,3],[1,3,4]])\ny = np.array([[1],[0]])\n\nm , n = X.shape\ninitial_theta = np.zeros(len(n))\nResult = op.minimize(fun = CostFunc, \n                                x0 = initial_theta), \n                                args = (X, y),\n                                method = 'TNC',\n                                jac = Gradient)\noptimal_theta = Result.x\n'''\n\ndef optimize(X, y, theta):\n    Result = op.minimize(fun = CostFunc, x0 = theta, args=(X, y), method='TNC', jac= Gradient, options={'maxiter': 400})\n    return Result.x", "meta": {"hexsha": "7932277183285d1348aee76d0ed5da865b6935ac", "size": 1211, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine-learning/coursera_exercises/ex2/in_python/exercises/advOptimize.py", "max_stars_repo_name": "pk-ai/training", "max_stars_repo_head_hexsha": "86b0d6c74853565eab08e76054ce96083ebfd45e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-01T10:07:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-01T10:07:03.000Z", "max_issues_repo_path": "machine-learning/coursera_exercises/ex2/in_python/exercises/advOptimize.py", "max_issues_repo_name": "pktippa/ai-training", "max_issues_repo_head_hexsha": "86b0d6c74853565eab08e76054ce96083ebfd45e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-09-27T14:42:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T03:35:18.000Z", "max_forks_repo_path": "machine-learning/coursera_exercises/ex2/in_python/exercises/advOptimize.py", "max_forks_repo_name": "pktippa/ai-training", "max_forks_repo_head_hexsha": "86b0d6c74853565eab08e76054ce96083ebfd45e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5227272727, "max_line_length": 120, "alphanum_fraction": 0.529314616, "include": true, "reason": "import numpy,import scipy", "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9808759593358227, "lm_q2_score": 0.8740772400852111, "lm_q1q2_score": 0.8573613514021897}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np \nfrom scipy.stats import norm, lognorm\n\ncolors = ['#342a77', '#ff464a', '#4881e9']\nnormal_mu = [0,0.5,1]\nnormal_sigma = [0.5,0.4,0.3]\nx = np.arange(0.001, 7, .001) # for the log-normal PDF\nx1 = np.arange(-2.5, 2.5, .001)  # for the normal PDF\n\nfig, (ax1, ax2) = plt.subplots(nrows = 2, ncols = 1, figsize = (8,9))\n\nfor mu_n, sigma_n, color in zip(normal_mu, normal_sigma, colors):   \n     lognorm_pdf = lognorm.pdf(x, s=sigma_n, scale=np.exp(mu_n))\n     r = lognorm.rvs(s=sigma_n, scale=np.exp(mu_n), size=15000)\n     ax1.plot(x, lognorm_pdf, color=color, label=r\"$\\mu_n$ = \" + str(mu_n) + r\" - $\\sigma_n$ = \" + str(sigma_n))\n     ax1.hist(r, bins='auto', density=True, color=color, edgecolor='#000000', alpha=0.5)\n     logr= np.log(r)\n     normal_pdf = norm.pdf(x1, loc= mu_n, scale = sigma_n)\n     ax2.plot(x1, normal_pdf, color=color, label=r\"$\\mu_n$ = \" + str(mu_n) + r\" - $\\sigma_n$ = \" + str(sigma_n))\n     ax2.hist(logr, bins='auto', density=True, color=color, edgecolor='#000000', alpha=0.5)\n     my_mu = logr.mean()\n     ax2.axvline(x=my_mu, color=color, linestyle=\"--\", label=r\"calculated $\\mu_n$ = \" + str(round(my_mu,3)))\n     my_sigma = logr.std()\n     print(\"Expected mean: \" + str(mu_n) + \" - Calculated mean: \" + str(round(my_mu,3)))\n     print(\"Expected std.dev.: \" + str(sigma_n) + \" - Calculated std.dev.: \" + str(round(my_sigma,3)))\n     \nax1.legend(title=\"log-normal distributions\")   \nax1.set_xlabel('x')  \nax1.set_ylabel('Probability Density')  \nax2.legend(title=\"normal distributions\") \nax2.set_xlabel('ln(x)') \nax2.set_ylabel('Probability Density')  \n\nfig.tight_layout()\n\n\n\n\n\n", "meta": {"hexsha": "b58d1a45be1aebc43e4739ace1fd4871b99adf81", "size": 1652, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/chapter_09/listing_09_04.py", "max_stars_repo_name": "guinslym/python_earth_science_book", "max_stars_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80, "max_stars_repo_stars_event_min_datetime": "2021-04-19T10:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:34:47.000Z", "max_issues_repo_path": "code/chapter_09/listing_09_04.py", "max_issues_repo_name": "guinslym/python_earth_science_book", "max_issues_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/chapter_09/listing_09_04.py", "max_forks_repo_name": "guinslym/python_earth_science_book", "max_forks_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2021-04-25T03:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:06:19.000Z", "avg_line_length": 40.2926829268, "max_line_length": 112, "alphanum_fraction": 0.6398305085, "include": true, "reason": "import numpy,from scipy", "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018419665619, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.8573455516661028}}
{"text": "\n\nimport sys\n\nprint(sys.version)\n\n# We import NumPy into Python\nimport numpy as np\n\n# We create a 1D ndarray that contains only integers\nx = np.array([1, 2, 3, 4, 5])\n\n# Let's print the ndarray we just created using the print() command\nprint('x = ', x)\nprint(type(x))\n\n\nabc = np.array(['a','b','c','d','e','f','g','h','i','j'])\nprint(\"x: \", x)\nprint(\"shape: \", x.shape)\nprint(\"size: \", x.size)\nprint(\"type: \", x.dtype)\n\n\nx = np.zeros((5,2))\nprint(\"x: \", x)\nprint(\"shape: \", x.shape)\nprint(\"size: \", x.size)\nprint(\"type: \", x.dtype)\n\n\n# Using the Built-in functions you learned about in the\n# previous lesson, create a 4 x 4 ndarray that only\n# contains consecutive even numbers from 2 to 32 (inclusive)\n\nx = np.arange(2,33,2).reshape((4,4))\nprint(x)\n\n\n\n\n# Create a 5 x 5 ndarray with consecutive integers from 1 to 25 (inclusive).\n# Afterwards use Boolean indexing to pick out only the odd numbers in the array\n\n# Create a 5 x 5 ndarray with consecutive integers from 1 to 25 (inclusive).\nX = np.arange(25).reshape((5,5))\n\nprint(X)\n# Use Boolean indexing to pick out only the odd numbers in the array\nY = X[X % 2 != 0]\nprint(Y)\n\n\n\nimport numpy as np\n\n# Use Broadcasting to create a 4 x 4 ndarray that has its first\n# column full of 1s, its second column full of 2s, its third\n# column full of 3s, etc.. \n\n# Do not change the name of this array. \n# Please don't print anything from your code! The TEST RUN button below will print your array. \n\n\nX = np.zeros((4,4)) + np.arange(1,5)\nprint(X)", "meta": {"hexsha": "942b3a27143a70c6ef65f0effef121b3b60c879a", "size": 1489, "ext": "py", "lang": "Python", "max_stars_repo_path": "workingWithNumpy.py", "max_stars_repo_name": "bavShehata/workingWithPython", "max_stars_repo_head_hexsha": "3f77d93adb9918f7861b4b49a41012e0e234953a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "workingWithNumpy.py", "max_issues_repo_name": "bavShehata/workingWithPython", "max_issues_repo_head_hexsha": "3f77d93adb9918f7861b4b49a41012e0e234953a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "workingWithNumpy.py", "max_forks_repo_name": "bavShehata/workingWithPython", "max_forks_repo_head_hexsha": "3f77d93adb9918f7861b4b49a41012e0e234953a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5606060606, "max_line_length": 95, "alphanum_fraction": 0.6749496306, "include": true, "reason": "import numpy", "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.9184802523931341, "lm_q1q2_score": 0.8573377652050149}}
{"text": "import numpy as np\nimport torch\nimport matplotlib.pyplot as plt\n\ndef gaussian(x, mu, sig , plot_pref=False):\n    '''\n    A gaussian function (normalized similarly to scipy's function)\n    RH 2021\n    \n    Args:\n        x (np.ndarray): 1-D array of the x-axis of the kernel\n        mu (float): center position on x-axis\n        sig (float): standard deviation (sigma) of gaussian\n        plot_pref (boolean): True/False or 1/0. Whether you'd like the kernel plotted\n        \n    Returns:\n        gaus (np.ndarray): gaussian function (normalized) of x\n        params_gaus (dict): dictionary containing the input params\n    '''\n\n    gaus = 1/(np.sqrt(2*np.pi)*sig)*np.exp((-((x-mu)/sig) **2)/2)\n\n    if plot_pref:\n        plt.figure()\n        plt.plot(x , gaus)\n        plt.xlabel('x')\n        plt.title(f'$\\mu$={mu}, $\\sigma$={sig}')\n    \n    params_gaus = {\n        \"x\": x,\n        \"mu\": mu,\n        \"sig\": sig,\n    }\n\n    return gaus , params_gaus\n\n\ndef generalised_logistic_function(x, a=0, k=1, b=1, v=1, q=1, c=1):\n    '''\n    Generalized logistic function\n    See: https://en.wikipedia.org/wiki/Generalised_logistic_function\n     for parameters and details\n    RH 2021\n\n    Args:\n        a: the lower asymptote\n        k: the upper asymptote when C=1\n        b: the growth rate\n        v: > 0, affects near which asymptote maximum growth occurs\n        q: is related to the value Y (0). Center positions\n        c: typically takes a value of 1\n\n    Returns:\n        output:\n            Logistic function\n     '''\n    return a + (k-a) / (c + q*np.exp(-b*x))**(1/v)\n\n\ndef bounded_exponential(x, bounds=[1/10,10], base=2):\n    \"\"\"\n    Bounded exponential function\n    Computes an exponential function where when\n     x is 0, the output is bounds[0], and when\n     x is 1, the output is bounds[1]. The relative\n     probability of outputting bounds[0[ over bounds[1]\n     is base.\n    Useful for randomly sampling over large ranges of\n     values with an exponential resolution.\n    RH 2021\n\n    Args:\n        x (float or np.ndarray): \n            Float or 1-D array of the x-axis\n        bounds (list):\n            List of two floats, the lower and upper\n             bounds\n        base (float):  \n            The relative probability of outputting\n             bounds[0] over bounds[1]\n    \n    Returns:\n        output (float or np.ndarray):\n            The bounded exponential output\n    \"\"\"\n    \n    range_additive = bounds[1] - bounds[0]\n\n    return (((base**x - 1)/(base-1)) * range_additive) + bounds[0]\n\n\ndef polar2real(mag, angle):\n    \"\"\"\n    Converts a polar coordinates to real coordinates\n    RH 2021\n\n    Args:\n        mag (float or np.ndarray or torch.Tensor):\n            Magnitude of the polar coordinates\n        angle (float or np.ndarray or torch.Tensor):\n            Angle of the polar coordinates\n    \n    Returns:\n        output (float or np.ndarray or torch.Tensor):\n    \"\"\"\n    if type(mag) is torch.Tensor:\n        exp = torch.exp\n    else:\n        exp = np.exp\n    return mag * exp(1j*angle)\n\ndef real2polar(x):\n    \"\"\"\n    Converts a real coordinates to polar coordinates\n    RH 2021\n\n    Args:\n        x (float or np.ndarray or torch.Tensor):\n            Real coordinates\n        \n    Returns:\n        Magnitude (float or np.ndarray or torch.Tensor):\n            Magnitude of the polar coordinates\n        Angle (float or np.ndarray or torch.Tensor):\n            Angle of the polar coordinates\n    \"\"\"\n    if type(x) is torch.Tensor:\n        abs, angle = torch.abs, torch.angle\n    else:\n        abs, angle = np.abs, np.angle\n    return abs(x), angle(x)", "meta": {"hexsha": "69190c515a337ec46a18aaa6b3bb07533e3a5572", "size": 3583, "ext": "py", "lang": "Python", "max_stars_repo_path": "math_functions.py", "max_stars_repo_name": "akshay-jaggi/basic_neural_processing_modules", "max_stars_repo_head_hexsha": "96dd6b0a507b730aa1883109a87e7e22636dd50d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-07T23:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T23:32:58.000Z", "max_issues_repo_path": "math_functions.py", "max_issues_repo_name": "akshay-jaggi/basic_neural_processing_modules", "max_issues_repo_head_hexsha": "96dd6b0a507b730aa1883109a87e7e22636dd50d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math_functions.py", "max_forks_repo_name": "akshay-jaggi/basic_neural_processing_modules", "max_forks_repo_head_hexsha": "96dd6b0a507b730aa1883109a87e7e22636dd50d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-06T05:23:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T05:23:17.000Z", "avg_line_length": 27.3511450382, "max_line_length": 85, "alphanum_fraction": 0.5922411387, "include": true, "reason": "import numpy", "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639686018701, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.8573351289495139}}
{"text": "#Modified Euler / Heuns method:\n#Runge Kutta Second (2) Order Method\nimport numpy as np \n\n\ndef dy(ynew,xnew,y,x,h):\n    dyvalue = x**2 + y**2\n    return dyvalue\n #Note: change the derivative function based on question!!!!!!  Example: y-x\n\ny0 = 2.3  #float(input\"what is the y(0)?\")\n\nh = 0.1  #float(input\"h?\")\n\nx_final = 1.2 #float(input\"x_final\")\n\n#initiating input variables\nx = 1\ny = y0\n# remember to change yn+1 and xn+1 values if you already know them!!!\nynew = 0\nxnew = 0\ni = 0\n\n#####################################################\niterations = x_final/h\n\nwhile x <= x_final:\n    k1 = dy(ynew,xnew,y,x,h)\n    k2 = dy(ynew,xnew,y+k1*h,x+h,h)\n    xnew = x + h \n    ynew = y + (h/2)*(k1+k2)\n    print(\"iteration:        ____            \")\n    print(i)\n    print(\"\\n\")\n    print(\"x = \")\n    print(xnew)\n    print(\"\\n\")\n    print(\"y = \")\n    print(ynew)\n    x = xnew\n    y = ynew\n    i+=1\n\n", "meta": {"hexsha": "f46e2001cdec89b7df411e7d641360d64a01b440", "size": 892, "ext": "py", "lang": "Python", "max_stars_repo_path": "Modified euler or heuns method.py", "max_stars_repo_name": "pramotharun/Numerical-Methods-with-Python", "max_stars_repo_head_hexsha": "bd5676bcc4ac5defd13608728df2387b5fdcdfcb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Modified euler or heuns method.py", "max_issues_repo_name": "pramotharun/Numerical-Methods-with-Python", "max_issues_repo_head_hexsha": "bd5676bcc4ac5defd13608728df2387b5fdcdfcb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modified euler or heuns method.py", "max_forks_repo_name": "pramotharun/Numerical-Methods-with-Python", "max_forks_repo_head_hexsha": "bd5676bcc4ac5defd13608728df2387b5fdcdfcb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8222222222, "max_line_length": 76, "alphanum_fraction": 0.5369955157, "include": true, "reason": "import numpy", "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854138058637, "lm_q2_score": 0.8840392893839085, "lm_q1q2_score": 0.8573284080758155}}
{"text": "\"\"\"数学分析\"\"\"\n\nimport math\n\ntry:\n    import sympy\n    import sympy.abc\n    from sympy import oo  # oo是无穷大\n    # from sympy.abc import x\nexcept ImportError as e:\n    print(e)\n\n\n# 另一种实现方法\n# def fourier_odd(fx, x_tuple=(sympy.abc.x, 0, sympy.pi), T=0, silent=False):\n#     x = x_tuple[0]\n#     a = x_tuple[1]\n#     b = x_tuple[2]\n\n\ndef fourier_odd(fx, x=sympy.abc.x, a=0, b=sympy.pi, T=0, silent=False):\n    \"\"\"\n    计算奇延拓Fourier级数的Fourier系数,[0,b]区间,T周期(默认2b)\n    \"\"\"\n    from sympy import pi\n    n = sympy.Symbol('n', integer=True, positive=True)  # 定义符号n 为正整数\n\n    if T == 0:\n        T = 2 * b\n\n    a0 = 0\n    an = 0\n    bn = sympy.simplify(sympy.integrate(fx * sympy.sin(2 * pi * n * x / T), (x, a, b)) * 4 / T)\n\n    if not silent:\n        print(f\"{a0/2=}\")\n        print(f\"{an=}\")\n        print(f\"{bn=}\")\n    return [a0, an, bn]\n\n\ndef fourier_even(fx, x=sympy.abc.x, a=0, b=sympy.pi, T=0, silent=False):\n    \"\"\"计算偶延拓Fourier级数的Fourier系数,[0,b]区间,T周期(默认2b)\"\"\"\n    from sympy import pi\n    n = sympy.Symbol('n', integer=True, positive=True)  # 定义符号n 为正整数\n\n    if T == 0:\n        T = 2 * b\n\n    a0 = sympy.simplify(sympy.integrate(fx, (x, a, b)) * 4 / T)\n    an = sympy.simplify(sympy.integrate(fx * sympy.cos(2 * pi * n * x / T), (x, a, b)) * 4 / T)\n    bn = 0\n\n    if not silent:\n        print(f\"{a0/2=}\")\n        print(f\"{an=}\")\n        print(f\"{bn=}\")\n    return [a0, an, bn]\n\n\ndef fourier_series(fx, x=sympy.abc.x, a=-sympy.pi, b=sympy.pi, T=0, silent=False):\n    \"\"\"\n    计算Fourier级数的Fourier系数,[a,b]区间,T周期(默认b-a)\n\n    如果不加参数x=sympy.abc.x(即x=sympy.symbols('x')，没有限定条件)，则fx中其他的x会因与此函数中的x不是同一个x对象而导致计算错误\n\n    注:sympy.fourier_series(1+x)或sympy.fourier_series(1+x, (x,-pi,pi))会得到\n    FourierSeries(x + 1, (x, -pi, pi), (1, SeqFormula(Piecewise((2*sin(_n*pi)/_n, (_n > -oo) & (_n < oo) & Ne(_n, 0)), (2*pi, True))*cos(_n*x)/pi, (_n, 1, oo)), SeqFormula(Piecewise((-2*pi*cos(_n*pi)/_n + 2*sin(_n*pi)/_n**2, (_n > -oo) & (_n < oo) & Ne(_n, 0)), (0, True))*sin(_n*x)/pi, (_n, 1, oo))))\n    这一串看不懂的东西，不如我这个好用\n\n    \"\"\"\n    from sympy import pi\n    n = sympy.Symbol('n', integer=True, positive=True)  # 定义符号n 为正整数\n\n    if T == 0:\n        T = b - a\n\n    a0 = sympy.simplify(sympy.integrate(fx, (x, a, b)) * 2 / T)\n    an = sympy.simplify(sympy.integrate(fx * sympy.cos(2 * pi * n * x / T), (x, a, b)) * 2 / T)\n    bn = sympy.simplify(sympy.integrate(fx * sympy.sin(2 * pi * n * x / T), (x, a, b)) * 2 / T)\n\n    if not silent:\n        print(f\"{a0/2=}\")\n        print(f\"{an=}\")\n        print(f\"{bn=}\")\n    return [a0, an, bn]\n\n\ndef generalized_fourier(fx, phi_nx, phi_0x=0, x=sympy.abc.x, a=-sympy.pi, b=sympy.pi, silent=False):\n    \"\"\"广义Fourier级数,phi_0x=0时不单独计算a0\"\"\"\n\n    a0 = sympy.integrate(fx * phi_0x, (x, a, b))\n    a0 = sympy.simplify(a0)\n\n    an = sympy.integrate(fx * phi_nx, (x, a, b))\n    an = sympy.simplify(an)\n\n    if not silent:\n        print(f\"{a0=}\")\n        print(f\"{an=}\")\n    return [a0, an]\n\n\ndef fourier_transform(fx, x=sympy.abc.x, silent=False):\n    r\"\"\"Fourier变换\n\n    .. math:: F(k) = \\int_{-\\infty}^\\infty f(x) e^{- i x k} \\mathrm{d} x.\n    \"\"\"\n    k = sympy.symbols('k', real=True)\n    # 无用 fx.subs(x, x1)  # 将fx中的 默认x 替换成 x1(实数x),若fx原来就是实数x也不会报错\n    Fk = sympy.integrate(fx * sympy.exp(-sympy.I * k * x), (x, -oo, oo))\n    if not silent:\n        print(Fk)\n    return Fk\n\n\ndef fourier_transform_inverse(Fk, k=sympy.abc.k, silent=False):\n    r\"\"\"Fourier变换的逆变换\n\n        .. math:: F(k) = \\int_{-\\infty}^\\infty f(x) e^{- i x k} \\mathrm{d} x.\n        \"\"\"\n    x = sympy.symbols('x', real=True)\n    fx = sympy.integrate(Fk * sympy.exp(sympy.I * k * x), (k, -oo, oo)) / (2 * sympy.pi)\n    if not silent:\n        print(fx)\n    return fx\n\n\n\ndef dot_product2(fx, gx, x=sympy.abc.x, a=-1, b=1, silent=True):\n    \"\"\"积分形式的内积\"\"\"\n    from sympy import integrate\n    o1 = integrate(fx * gx, (x, a, b))\n    if not silent:\n        print(f\"fx*gx={o1}\")\n    return o1\n\n\ndef schmidt_orthogonalization(fix: list, n, e: list, x=sympy.abc.x, a=-1, b=1):\n    \"\"\"施密特正交化,输出为列表,n=len(fix),手动选择积分区间[a,b]\"\"\"\n    from sympy import sqrt\n    # dot_product=dot_product2 #另一种实现方法,手动选择内积\n\n    if n == 1:\n        e[0] = fix[0] / sqrt(dot_product2(fix[0], fix[0], x, a, b))\n    else:\n        schmidt_orthogonalization(fix, n - 1, e, x, a, b)\n        e[n - 1] = fix[n - 1]\n        for j in range(0, n - 1):\n            e[n - 1] -= dot_product2(fix[n - 1], e[j], x, a, b) * e[j]\n        e[n - 1] /= sqrt(dot_product2(e[n - 1], e[n - 1], x, a, b))\n\n\ndef schmidt(fix: list, n, e: list, dot_product=dot_product2, x=sympy.abc.x):\n    \"\"\"施密特正交化,输出在e列表,n=len(fix),手动选择内积dot_product\"\"\"\n    from sympy import sqrt\n\n    if n == 1:\n        e[0] = fix[0] / sqrt(dot_product(fix[0], fix[0], x))\n    else:\n        schmidt(fix, n - 1, e, dot_product, x)\n        e[n - 1] = fix[n - 1]\n        for j in range(0, n - 1):\n            e[n - 1] -= dot_product(fix[n - 1], e[j], x) * e[j]\n        e[n - 1] /= sqrt(dot_product(e[n - 1], e[n - 1], x))\n\n\ndef schmidt_orthogonalization_list(fix: list, n, x=sympy.abc.x, a=-1, b=1, silent=True):\n    \"\"\"施密特正交化,输出为列表,n=len(fix),手动选择积分区间[a,b]\"\"\"\n    e = []\n    for i in range(0, n):\n        e.append(None)\n    schmidt_orthogonalization(fix, n, e, x, a, b)\n    if not silent:\n        print(e)\n    return e\n\n\ndef schmidt_list(fix: list, n, dot_product=dot_product2, x=sympy.abc.x, silent=True):\n    \"\"\"施密特正交化,输出为列表,n=len(fix),手动选择内积dot_product\"\"\"\n    e = []\n    for i in range(0, n):\n        e.append(None)\n    schmidt(fix, n, e, dot_product, x)\n    if not silent:\n        print(e)\n    return e\n\n\ndef convolution1(ft, gx_t, silent=True):\n    \"\"\"卷积,核心算法\"\"\"\n    from sympy import integrate\n    t = sympy.symbols('t', real=True)\n    o1 = integrate(ft * gx_t, (t, -oo, oo))\n    if not silent:\n        print(f\"(f*g)(x)={o1}\")\n    return o1\n\n\ndef convolution(fx: str, gx: str):\n    \"\"\"卷积\"\"\"\n    t = sympy.symbols('t', real=True)\n    ft1 = fx.replace('x', 't')\n    gx_t1 = gx.replace('x', '(x-t)')\n    exec(\"ft2=\" + ft1)\n    exec(\"gx_t2=\" + gx_t1)\n    o1 = [None]  # 必须用引用类型(比如列表),否则报错\n    exec(\"o1[0]=convolution1(ft2, gx_t2)\")\n    return o1[0]\n\n\ndef legrendre(n, x=sympy.abc.x):\n    \"\"\"勒让德多项式\"\"\"\n    pnx = 1 / (2 ** n * sympy.factorial(n)) * sympy.diff((x * x - 1) ** n, x, n)\n    # print(pnx)\n    return pnx\n\n\ndef legrendre_list(n, x=sympy.abc.x):\n    \"\"\"勒让德多项式表\"\"\"\n    l1 = []\n    for i in range(0, n):\n        l1.append(legrendre(i, x))\n    print(l1)  # [1, x, (3*x**2 - 1)/2, x*(5*x**2 - 3)/2, (8*x**4 + 24*x**2*(x**2 - 1) + 3*(x**2 - 1)**2)/8]\n    return l1\n\n\ndef laplace_transform(ft, t=sympy.abc.t, silent=False):\n    r\"\"\"Laplace变换\n\n    .. math:: F(p) = \\int_{0}^\\infty f(x) e^{-pt} \\mathrm{d} t.\n    \"\"\"\n    p = sympy.symbols('p')\n    Fp = sympy.integrate(ft * sympy.exp(-p * t), (t, 0, oo))\n    if not silent:\n        print(Fp)\n    return Fp\n\n\nif __name__ == '__main__':\n    x,t = sympy.symbols(\"x,t\")  # sympy.symbols(\"x\")等价于sympy.abc.x\n    fourier_even(1 + x, x)\n    fourier_odd(1 + x, x)\n    fourier_series(1 + x, x, 0, sympy.pi)\n    fourier_transform(sympy.sin(x), x)\n    laplace_transform(1)\n    laplace_transform(t ** 2, t)\n    # 输出结果中Piecewise表示分段函数,Ne(n,0)表示n!=0,True表示除去前面(Ne(n,0))的情况(即n==0)\n    # 已修复n的类型,不会输出上述结果了\n\n", "meta": {"hexsha": "318b7e73dd1e981bd38274371b52b55fa2962e74", "size": 7118, "ext": "py", "lang": "Python", "max_stars_repo_path": "PCILib/PCImathLib/analysis/__init__.py", "max_stars_repo_name": "HyperPh/PCILib", "max_stars_repo_head_hexsha": "c27f6ffae54d8c55e97e3875983b7ef2d924f1a9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-04T14:28:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-04T14:28:50.000Z", "max_issues_repo_path": "PCILib/PCImathLib/analysis/__init__.py", "max_issues_repo_name": "HyperPh/PCILib", "max_issues_repo_head_hexsha": "c27f6ffae54d8c55e97e3875983b7ef2d924f1a9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PCILib/PCImathLib/analysis/__init__.py", "max_forks_repo_name": "HyperPh/PCILib", "max_forks_repo_head_hexsha": "c27f6ffae54d8c55e97e3875983b7ef2d924f1a9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3585657371, "max_line_length": 301, "alphanum_fraction": 0.5491711155, "include": true, "reason": "import sympy,from sympy", "num_tokens": 3030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897517488946, "lm_q2_score": 0.9111797045849583, "lm_q1q2_score": 0.8572285280751141}}
{"text": "''' Good students always try to solve exercise on their own first and then look at the ready made solution\n    I know you are an awesome student !! :)\n    Hence you will look into this code only after you have done your due diligence.\n    If you are not an awesome student who is full of laziness then only you will come here\n    without writing single line of code on your own. In that case anyways you are going to\n    face my anger with fire and fury !!!\n'''\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\nimport math\n\ndef predict_using_sklean():\n    df = pd.read_csv(\"test_scores.csv\")\n    r = LinearRegression()\n    r.fit(df[['math']],df.cs)\n    return r.coef_, r.intercept_\n\ndef gradient_descent(x,y):\n    m_curr = 0\n    b_curr = 0\n    iterations = 1000000\n    n = len(x)\n    learning_rate = 0.0002\n\n    cost_previous = 0\n\n    for i in range(iterations):\n        y_predicted = m_curr * x + b_curr\n        cost = (1/n)*sum([value**2 for value in (y-y_predicted)])\n        md = -(2/n)*sum(x*(y-y_predicted))\n        bd = -(2/n)*sum(y-y_predicted)\n        m_curr = m_curr - learning_rate * md\n        b_curr = b_curr - learning_rate * bd\n        if math.isclose(cost, cost_previous, rel_tol=1e-20):\n            break\n        cost_previous = cost\n        print (\"m {}, b {}, cost {}, iteration {}\".format(m_curr,b_curr,cost, i))\n\n    return m_curr, b_curr\n\nif __name__ == \"__main__\":\n    df = pd.read_csv(\"test_scores.csv\")\n    x = np.array(df.math)\n    y = np.array(df.cs)\n\n    m, b = gradient_descent(x,y)\n    print(\"Using gradient descent function: Coef {} Intercept {}\".format(m, b))\n\n    m_sklearn, b_sklearn = predict_using_sklean()\n    print(\"Using sklearn: Coef {} Intercept {}\".format(m_sklearn,b_sklearn))\n\n", "meta": {"hexsha": "a6ddaa95c84eeddbab7ca60295ff111abb026d31", "size": 1762, "ext": "py", "lang": "Python", "max_stars_repo_path": "Program's_Contributed_By_Contributors/AI-Summer-Course/py-master/ML/3_gradient_descent/Exercise/ex_gradient_descent.py", "max_stars_repo_name": "SDGraph/Hacktoberfest2k21", "max_stars_repo_head_hexsha": "8f8aead15afa10ea12e1b23ece515a10a882de28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Program's_Contributed_By_Contributors/AI-Summer-Course/py-master/ML/3_gradient_descent/Exercise/ex_gradient_descent.py", "max_issues_repo_name": "SDGraph/Hacktoberfest2k21", "max_issues_repo_head_hexsha": "8f8aead15afa10ea12e1b23ece515a10a882de28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Program's_Contributed_By_Contributors/AI-Summer-Course/py-master/ML/3_gradient_descent/Exercise/ex_gradient_descent.py", "max_forks_repo_name": "SDGraph/Hacktoberfest2k21", "max_forks_repo_head_hexsha": "8f8aead15afa10ea12e1b23ece515a10a882de28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6296296296, "max_line_length": 106, "alphanum_fraction": 0.6538024972, "include": true, "reason": "import numpy", "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.911179711217791, "lm_q1q2_score": 0.8572285259955407}}
{"text": "\"\"\"Measurements using spatial objects.\"\"\"\nimport numpy as np\n\nfrom skspatial.objects import Points\nfrom skspatial.objects import Vector\nfrom skspatial.typing import array_like\n\n\ndef area_triangle(point_a: array_like, point_b: array_like, point_c: array_like) -> np.float64:\n    \"\"\"\n    Return the area of a triangle defined by three points.\n\n    The points are the vertices of the triangle. They must be 3D or less.\n\n    Parameters\n    ----------\n    point_a, point_b, point_c : array_like\n        The three vertices of the triangle.\n\n    Returns\n    -------\n    np.float64\n        The area of the triangle.\n\n    References\n    ----------\n    http://mathworld.wolfram.com/TriangleArea.html\n\n    Examples\n    --------\n    >>> from skspatial.measurement import area_triangle\n\n    >>> area_triangle([0, 0], [0, 1], [1, 0])\n    0.5\n\n    >>> area_triangle([0, 0], [0, 2], [1, 1])\n    1.0\n\n    >>> area_triangle([3, -5, 1], [5, 2, 1], [9, 4, 2]).round(2)\n    12.54\n\n    \"\"\"\n    vector_ab = Vector.from_points(point_a, point_b)\n    vector_ac = Vector.from_points(point_a, point_c)\n\n    # Normal vector of plane defined by the three points.\n    vector_normal = vector_ab.cross(vector_ac)\n\n    return 0.5 * vector_normal.norm()\n\n\ndef volume_tetrahedron(\n    point_a: array_like,\n    point_b: array_like,\n    point_c: array_like,\n    point_d: array_like,\n) -> np.float64:\n    \"\"\"\n    Return the volume of a tetrahedron defined by four points.\n\n    The points are the vertices of the tetrahedron. They must be 3D or less.\n\n    Parameters\n    ----------\n    point_a, point_b, point_c, point_d : array_like\n        The four vertices of the tetrahedron.\n\n    Returns\n    -------\n    np.float64\n        The volume of the tetrahedron.\n\n    References\n    ----------\n    http://mathworld.wolfram.com/Tetrahedron.html\n\n    Examples\n    --------\n    >>> from skspatial.measurement import volume_tetrahedron\n\n    >>> volume_tetrahedron([0, 0], [3, 2], [-3, 5], [1, 8])\n    0.0\n\n    >>> volume_tetrahedron([0, 0, 0], [2, 0, 0], [1, 1, 0], [0, 0, 1]).round(3)\n    0.333\n\n    >>> volume_tetrahedron([0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]).round(3)\n    0.167\n\n    \"\"\"\n    vector_ab = Vector.from_points(point_a, point_b)\n    vector_ac = Vector.from_points(point_a, point_c)\n    vector_ad = Vector.from_points(point_a, point_d)\n\n    vector_cross = vector_ac.cross(vector_ad)\n\n    # Set the dimension to 3 so it matches the cross product.\n    vector_ab = vector_ab.set_dimension(3)\n\n    return 1 / 6 * abs(vector_ab.dot(vector_cross))\n\n\ndef area_signed(points: array_like) -> float:\n    \"\"\"\n    Return the signed area of a simple polygon given the 2D coordinates of its veritces.\n\n    The signed area is computed using the shoelace algorithm. A positive area is\n    returned for a polygon whose vertices are given by a counter-clockwise\n    sequence of points.\n\n    Parameters\n    ----------\n    points : array_like\n         Input 2D points.\n\n    Returns\n    -------\n    area_signed : float\n        The signed area of the polygon.\n\n    Raises\n    ------\n    ValueError\n        If the points are not 2D.\n        If there are fewer than three points.\n\n    References\n    ----------\n    https://en.wikipedia.org/wiki/Shoelace_formula\n    https://alexkritchevsky.com/2018/08/06/oriented-area.html\n    https://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area#Python\n\n    Examples\n    --------\n    >>> from skspatial.measurement import area_signed\n\n    >>> area_signed([[0, 0], [1, 0], [0, 1]])\n    0.5\n\n    >>> area_signed([[0, 0], [0, 1], [1, 0]])\n    -0.5\n\n    >>> area_signed([[0, 0], [0, 1], [1, 2], [2, 1], [2, 0]])\n    -3.0\n\n    \"\"\"\n    points = Points(points)\n    n_points = points.shape[0]\n\n    if points.dimension != 2:\n        raise ValueError(\"The points must be 2D.\")\n\n    if n_points < 3:\n        raise ValueError(\"There must be at least 3 points.\")\n\n    X = points[:, 0]\n    Y = points[:, 1]\n\n    indices = np.arange(n_points)\n    indices_offset = indices - 1\n\n    return 0.5 * np.sum(X[indices_offset] * Y[indices] - X[indices] * Y[indices_offset])\n", "meta": {"hexsha": "5734ff239f75d4da135de67fa5cae261afaea2a2", "size": 4045, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/skspatial/measurement.py", "max_stars_repo_name": "CristianoPizzamiglio/scikit-spatial", "max_stars_repo_head_hexsha": "95ca2d4f2948cf6a69ec4bc7236b70fd66db1de5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/skspatial/measurement.py", "max_issues_repo_name": "CristianoPizzamiglio/scikit-spatial", "max_issues_repo_head_hexsha": "95ca2d4f2948cf6a69ec4bc7236b70fd66db1de5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/skspatial/measurement.py", "max_forks_repo_name": "CristianoPizzamiglio/scikit-spatial", "max_forks_repo_head_hexsha": "95ca2d4f2948cf6a69ec4bc7236b70fd66db1de5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8159509202, "max_line_length": 95, "alphanum_fraction": 0.6195302843, "include": true, "reason": "import numpy", "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783526, "lm_q2_score": 0.9111797069968974, "lm_q1q2_score": 0.8572285235372353}}
{"text": "import numpy as np\nfrom numba import jit, njit, vectorize, guvectorize\n\n@njit\ndef haversine(lat1, lon1, lat2, lon2):\n    \"\"\"\n    Haversine distance in kilometers between two points given in degrees.\n    r = 6371.009, 2r = 12742.018\n    Because the haversine distance assumes a spherical Earth, it will only\n    be accurate within ~0.5%. The mean earth radius is used (6371km).\n    \"\"\"\n    λ1 = np.radians(lat1)\n    λ2 = np.radians(lat2)\n    φ1 = np.radians(lon1)\n    φ2 = np.radians(lon2)\n    Δλ = λ2 - λ1\n    Δφ = φ2 - φ1\n    return 12742.018 * np.arcsin(np.sqrt(\n        np.sin(Δλ/2.0)**2 + (np.cos(λ1) * np.cos(λ2) * np.sin(Δφ/2.0)**2)))\n\n\n@guvectorize([(\"void(float64[:], float64[:], float64[:], float64[:],\"\n               \" float64[:])\")],\n             \"(n),(n),(n),(n)->(n)\")\ndef haversine_elementwise(lat1, lon1, lat2, lon2, res):\n    \"\"\" Elementwise haversine distance between vectors\n        of latitudes and longitudes\n\n        lat1, lon1: vectors for latitude and longitude of locations\n        lat2, lon2: vectors for latitude and longitude of locations\n    \"\"\"\n    for i in range(lat1.shape[0]):\n        res[i] = haversine(lat1[i], lon1[i], lat2[i], lon2[i])\n\n\n@guvectorize([\"void(float64, float64, float64[:], float64[:], float64[:])\"],\n             \"(),(),(n),(n)->(n)\")\ndef haversine_vector(lat1, lon1, latcol, loncol, res):\n    \"\"\" Haversine distance between a fixed lat/lon and vectors of lat/lon\n    lat1, lon1: Fixed latitude and longitude\n    latvec, lonvec: vector of latitudes and longitudes\n    \"\"\"\n    for i in range(latcol.shape[0]):\n        res[i] = haversine(lat1, lon1, latcol[i], loncol[i])\n\n\n@guvectorize([(\"void(float64[:], float64[:], float64[:], float64[:],\"\n               \" float64[:,:])\")],\n             \"(n),(n),(m),(m)->(n,m)\")\ndef haversine_outer_product(lat1, lon1, lat2, lon2, res):\n    \"\"\" Haversine distance between vectors of latitudes and longitudes\n        (outer product)\n\n        lat1, lon1: vectors for latitude and longitude of locations\n        lat2, lon2: vectors for latitude and longitude of locations\n    \"\"\"\n    for i in range(lat1.shape[0]):\n        for j in range(lat2.shape[0]):\n            res[i, j] = haversine(lat1[i], lon1[i], lat2[j], lon2[j])\n", "meta": {"hexsha": "4cc3b12cca651cc1e7a6ace5c7b749721288ff7a", "size": 2210, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/mhealth/location/distance.py", "max_stars_repo_name": "pymhealth/pymhealth", "max_stars_repo_head_hexsha": "db09bf60203938ee8ee9cb340ea281c5fe60fcab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mhealth/location/distance.py", "max_issues_repo_name": "pymhealth/pymhealth", "max_issues_repo_head_hexsha": "db09bf60203938ee8ee9cb340ea281c5fe60fcab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mhealth/location/distance.py", "max_forks_repo_name": "pymhealth/pymhealth", "max_forks_repo_head_hexsha": "db09bf60203938ee8ee9cb340ea281c5fe60fcab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8333333333, "max_line_length": 76, "alphanum_fraction": 0.6095022624, "include": true, "reason": "import numpy,from numba", "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992942089575, "lm_q2_score": 0.8856314798554445, "lm_q1q2_score": 0.8572020842813193}}
{"text": "import numpy as np\nfrom scipy.stats import norm\nimport matplotlib.pyplot as plt\n\n\ndef calc_d1(St, K, r, s, T, t=0, q=0):\n    return (np.log(St / K) + (r - q + 0.5 * s ** 2) * (T - t)) \\\n           / (s * np.sqrt(T - t))\n\n\ndef calc_d2(d1, s, T, t=0):\n    return d1 - s * np.sqrt(T - t)\n\ndef problem2a():\n    T_final = 5\n    Ts = np.arange(dt, T_final, dt)\n\n    mus_c = []\n    sgs_c = []\n    for T in Ts:\n        d1 = calc_d1(St, K, r, sg, T, q=q)\n        d2 = calc_d2(d1, sg, T)\n        delta = np.exp(-q * T) * norm.cdf(d1)\n        gamma = norm.pdf(d1) * np.exp(-q * T) / (St * sg * np.sqrt(T))\n        theta = -(St * norm.pdf(d1) * sg * np.exp(-q * T)) / (2 * np.sqrt(T)) \\\n                + q * St * norm.cdf(d1) * np.exp(-q * T) \\\n                - r * K * np.exp(-r * T) * norm.cdf(d2)\n        Ct = St * np.exp(-q * T) * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)\n        mu_call = (1. / Ct) * (theta + mu * St * delta + 0.5 * sg ** 2 * St ** 2 * gamma)\n        sg_call = (1. / Ct) * sg  * St * delta\n        mus_c.append(mu_call)\n        sgs_c.append(sg_call)\n    plt.figure()\n    plt.plot(Ts, mus_c)\n    plt.ylabel('Price')\n    plt.xlabel('Time to maturity')\n    plt.figure()\n    plt.plot(Ts, sgs_c)\n    plt.ylabel('Price')\n    plt.xlabel('Time to maturity')\n    plt.show()\n\ndef problem2b():\n    T = 1\n    Sts = np.arange(0.01, 100, 0.1)\n    mus_c = []\n    sgs_c = []\n    for St in Sts:\n        d1 = calc_d1(St, K, r, sg, T, q=q)\n        d2 = calc_d2(d1, sg, T)\n        delta = np.exp(-q * T) * norm.cdf(d1)\n        gamma = norm.pdf(d1) * np.exp(-q * T) / (St * sg * np.sqrt(T))\n        theta = -(St * norm.pdf(d1) * sg * np.exp(-q * T)) / (2 * np.sqrt(T)) \\\n                + q * St * norm.cdf(d1) * np.exp(-q * T) \\\n                - r * K * np.exp(-r * T) * norm.cdf(d2)\n        Ct = St * np.exp(-q * T) * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)\n        mu_call = (1. / Ct) * (theta + mu * St * delta + 0.5 * sg ** 2 * St ** 2 * gamma)\n        sg_call = (1. / Ct) * sg  * St * delta\n        mus_c.append(mu_call)\n        sgs_c.append(sg_call)\n    plt.figure()\n    plt.plot(Sts, mus_c)\n    plt.ylabel('Price')\n    plt.xlabel('Stock Price')\n    plt.figure()\n    plt.plot(Sts, sgs_c)\n    plt.ylabel('Price')\n    plt.xlabel('Stock Price')\n    plt.show()\n\nif __name__ == '__main__':\n\n    K = 50\n    sg = 0.5\n    mu = 0.15\n    q = 0.08\n    r = 0.13\n    St = 50\n    dt = 1 / 252.\n\n    # problem2a()\n    problem2b()\n", "meta": {"hexsha": "fe2bc911217270e209ac456a607bdbdbd66aa74d", "size": 2432, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/black_scholes/black_scholes.py", "max_stars_repo_name": "TechnicalConsultant123/financial-maths", "max_stars_repo_head_hexsha": "b29d6cd4c0afdc89d69c4db9d11adb2ff64089e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-05-02T19:18:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-08T15:56:23.000Z", "max_issues_repo_path": "Python/black_scholes/black_scholes.py", "max_issues_repo_name": "qrana/financial-maths", "max_issues_repo_head_hexsha": "b29d6cd4c0afdc89d69c4db9d11adb2ff64089e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/black_scholes/black_scholes.py", "max_forks_repo_name": "qrana/financial-maths", "max_forks_repo_head_hexsha": "b29d6cd4c0afdc89d69c4db9d11adb2ff64089e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-15T14:51:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T23:52:38.000Z", "avg_line_length": 29.3012048193, "max_line_length": 89, "alphanum_fraction": 0.4703947368, "include": true, "reason": "import numpy,from scipy", "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992923570262, "lm_q2_score": 0.8856314798554444, "lm_q1q2_score": 0.8572020826411906}}
{"text": "import numpy as np \r\nimport math \r\n\r\n\"\"\"Pauli Gates X, Y, Z\"\"\"\r\nX = np.array([[0,1],[1,0]])\r\nY = np.array([[0,-1j],[-1j,0]])\r\nZ = np.array([[1,0],[0,-1]])\r\n\r\n\"\"\"Hadamard Gate H\"\"\"\r\nH = (1/np.sqrt(2))*np.array([[1,1],[1,-1]])\r\n\r\n\"\"\"Phase Gate S\"\"\"\r\nS = np.array([[1,0],[0,-1j]])\r\n\r\n\"\"\"π/8 Gate T\"\"\"\r\nT_pi = np.array([[1,0],[0,math.e**((math.pi/4)*1j)]])\r\n\r\n\"\"\"T dagger\"\"\"\r\nT_dag = np.array([[1,0],[0,math.e**((math.pi/4)*-1j)]])\r\n\r\n\"\"\"Controlled NOT, CNOT\"\"\"\r\ncnot = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]])\r\n\r\n\"\"\"SWAP Gate swap\"\"\"\r\nswap = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]])\r\n\r\n# \"\"\"Controlled Z cZ\"\"\"\r\n# cz = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]])\r\n\r\n\"\"\"Controlled Phase Gate cS\"\"\"\r\ncs = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,-1j]])\r\n\r\n\"\"\"Double Controlled NOT or Toffoli, ccNOT\"\"\"\r\nccnot = np.array([[1,0,0,0,0,0,0,0],[0,1,0,0,0,0,0,0],[0,0,1,0,0,0,0,0],[0,0,0,1,0,0,0,0],[0,0,0,0,1,0,0,0],[0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,1,0]])\r\n\r\n\"\"\"Controlled Swap, Fredkin Gate, cSwap\"\"\"\r\ncswap = np.array([[1,0,0,0,0,0,0,0],[0,1,0,0,0,0,0,0],[0,0,1,0,0,0,0,0],[0,0,0,1,0,0,0,0],[0,0,0,0,1,0,0,0],[0,0,0,0,0,0,1,0],[0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1]])\r\n\r\n\"\"\"Controlled Pauli Z\"\"\"\r\ncz = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,-1]])\r\n\r\n\"\"\"Square root of NOT\"\"\"\r\nsqrt_not = np.array([[(1+1j)/2 , (1-1j)/2],[(1-1j)/2 , (1+1j)/2]])\r\n\r\n\"\"\"P\"\"\"\r\np = np.array([[1,0],[0,1j]])\r\n", "meta": {"hexsha": "fe2c7f657af34119e1cda24182a8d92971fafb04", "size": 1433, "ext": "py", "lang": "Python", "max_stars_repo_path": "QGates.py", "max_stars_repo_name": "MadhavJivrajani/QuantumComputing", "max_stars_repo_head_hexsha": "3aeaafa0a64e060d29a9823251967b5f4d8ff0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-07-13T21:09:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-01T10:33:47.000Z", "max_issues_repo_path": "QGates.py", "max_issues_repo_name": "MadhavJivrajani/QuantumComputing", "max_issues_repo_head_hexsha": "3aeaafa0a64e060d29a9823251967b5f4d8ff0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-17T18:54:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-18T17:04:38.000Z", "max_forks_repo_path": "QGates.py", "max_forks_repo_name": "MadhavJivrajani/QuantumComputing", "max_forks_repo_head_hexsha": "3aeaafa0a64e060d29a9823251967b5f4d8ff0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4893617021, "max_line_length": 164, "alphanum_fraction": 0.4794138172, "include": true, "reason": "import numpy", "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992951349231, "lm_q2_score": 0.8856314662716159, "lm_q1q2_score": 0.8572020719536055}}
{"text": "import numpy as np\nimport imageio\nimport math\n\ndef hough_line(img, angle_step=1, lines_are_white=True, value_threshold=5):\n    \"\"\"\n    Hough transform for lines\n    Input:\n    img - 2D binary image with nonzeros representing edges\n    angle_step - Spacing between angles to use every n-th angle\n                 between -90 and 90 degrees. Default step is 1.\n    lines_are_white - boolean indicating whether lines to be detected are white\n    value_threshold - Pixel values above or below the value_threshold are edges\n    Returns:\n    accumulator - 2D array of the hough transform accumulator\n    theta - array of angles used in computation, in radians.\n    rhos - array of rho values. Max size is 2 times the diagonal\n           distance of the input image.\n    \"\"\"\n    # Rho and Theta ranges\n    thetas = np.deg2rad(np.arange(-90.0, 90.0, angle_step))\n    width, height = img.shape\n    diag_len = int(round(math.sqrt(width * width + height * height)))\n    rhos = np.linspace(-diag_len, diag_len, diag_len * 2)\n\n    # Cache some resuable values\n    cos_t = np.cos(thetas)\n    sin_t = np.sin(thetas)\n    num_thetas = len(thetas)\n\n    # Hough accumulator array of theta vs rho\n    accumulator = np.zeros((2 * diag_len, num_thetas), dtype=np.uint8)\n    # (row, col) indexes to edges\n    are_edges = img > value_threshold if lines_are_white else img < value_threshold\n    y_idxs, x_idxs = np.nonzero(are_edges)\n\n    # Vote in the hough accumulator\n    for i in range(len(x_idxs)):\n        x = x_idxs[i]\n        y = y_idxs[i]\n\n        for t_idx in range(num_thetas):\n            # Calculate rho. diag_len is added for a positive index\n            rho = diag_len + int(round(x * cos_t[t_idx] + y * sin_t[t_idx]))\n            accumulator[rho, t_idx] += 1\n\n    return accumulator, thetas, rhos\n\n\ndef show_hough_line(img, accumulator, thetas, rhos, save_path=None):\n    import matplotlib.pyplot as plt\n\n    fig, ax = plt.subplots(1, 2, figsize=(10, 10))\n\n    ax[0].imshow(img, cmap=plt.cm.gray)\n    ax[0].set_title('Input image')\n    ax[0].axis('image')\n\n    ax[1].imshow(\n        accumulator, cmap='jet',\n        extent=[np.rad2deg(thetas[-1]), np.rad2deg(thetas[0]), rhos[-1], rhos[0]])\n    ax[1].set_aspect('equal', adjustable='box')\n    ax[1].set_title('Hough transform')\n    ax[1].set_xlabel('Angles (degrees)')\n    ax[1].set_ylabel('Distance (pixels)')\n    ax[1].axis('image')\n\n    # plt.axis('off')\n    if save_path is not None:\n        plt.savefig(save_path, bbox_inches='tight')\n    plt.show()\n\n\nif __name__ == '__main__':\n    imgpath = 'imgs/binary_crosses.png'\n    img = imageio.imread(imgpath)\n    if img.ndim == 3:\n        img = rgb2gray(img)\n    accumulator, thetas, rhos = hough_line(img)\nshow_hough_line(img, accumulator, save_path='imgs/output.png')\n", "meta": {"hexsha": "f6586a1f94165dd3d06c6be85346843e57dc9b7f", "size": 2760, "ext": "py", "lang": "Python", "max_stars_repo_path": "hough.py", "max_stars_repo_name": "OttoBismark/HoughPython", "max_stars_repo_head_hexsha": "d6d7709e7e13690b9a7a31856223abfa365da97a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hough.py", "max_issues_repo_name": "OttoBismark/HoughPython", "max_issues_repo_head_hexsha": "d6d7709e7e13690b9a7a31856223abfa365da97a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hough.py", "max_forks_repo_name": "OttoBismark/HoughPython", "max_forks_repo_head_hexsha": "d6d7709e7e13690b9a7a31856223abfa365da97a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0740740741, "max_line_length": 83, "alphanum_fraction": 0.6586956522, "include": true, "reason": "import numpy", "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992914310605, "lm_q2_score": 0.8856314692902446, "lm_q1q2_score": 0.8572020715950768}}
{"text": "#! /usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n#======================================================================\r\n#\r\n# GradientDescent.py - \r\n#\r\n# Created by skywind on 2019/03/14\r\n# Last Modified: 2019/03/14 21:00:27\r\n#\r\n#======================================================================\r\nfrom __future__ import print_function, unicode_literals\r\nimport sys\r\nimport time\r\n\r\n\r\n#----------------------------------------------------------------------\r\n# GradientDescent\r\n#----------------------------------------------------------------------\r\ndef GradientDescent(x, y, theta, alpha, iterations, limit):\r\n    rows = len(x)\r\n    if rows == 0:\r\n        raise ValueError('Data size must great than zero.')\r\n    cols = len(x[0])\r\n    theta = [ t for t in theta ]\r\n    for count in range(iterations):\r\n        # iterate feature columns\r\n        update = [ 1.0 ] * cols\r\n        for j in range(cols):\r\n            # calculate derivation\r\n            derivation = 0\r\n            for i in range(rows):\r\n                h = sum([ x[i][n] * theta[n] for n in range(cols) ])\r\n                derivation += (h - y[i]) * x[i][j]\r\n            derivation = derivation / float(rows)\r\n            update[j] = theta[j] - alpha * derivation\r\n        # update theta\r\n        theta = update\r\n        # calculate error\r\n        error = 0\r\n        for i in range(rows):\r\n            h = sum([ x[i][n] * theta[n] for n in range(cols) ])\r\n            error += (h - y[i]) * (h - y[i])\r\n        error = error / float(rows)\r\n        if error < limit:\r\n            break\r\n    return theta\r\n\r\n\r\n#----------------------------------------------------------------------\r\n# GradientDescent\r\n#----------------------------------------------------------------------\r\ndef GradientStep(x, y, theta, alpha):\r\n    cols = len(x)\r\n    if cols == 0:\r\n        raise ValueError('Feature size must great than zero.')\r\n    h = sum([ x[n] * theta[n] for n in range(cols) ])\r\n    update = [ 1.0 ] * cols\r\n    for j in range(cols):\r\n        derivation = (h - y) * x[j]\r\n        update[j] = theta[j] - alpha * derivation\r\n    return update\r\n\r\n\r\n#----------------------------------------------------------------------\r\n# Increamental GradientDescent\r\n#----------------------------------------------------------------------\r\ndef GradientDescent2(x, y, theta, alpha, iterations, limit):\r\n    rows = len(x)\r\n    if rows == 0:\r\n        raise ValueError('Data size must great than zero.')\r\n    cols = len(x[0])\r\n    for count in range(iterations):\r\n        for i in range(rows):\r\n            theta = GradientStep(x[i], y[i], theta, alpha)\r\n        # calculate error\r\n        error = 0\r\n        for i in range(rows):\r\n            h = sum([ x[i][n] * theta[n] for n in range(cols) ])\r\n            error += (h - y[i]) * (h - y[i])\r\n        error = error / float(rows)\r\n        if error < limit:\r\n            break\r\n    return theta\r\n\r\n\r\n#----------------------------------------------------------------------\r\n# numpy\r\n#----------------------------------------------------------------------\r\ndef GradientDescent3(x, y, theta, alpha, iterations, limit):\r\n    rows = len(x)\r\n    if rows == 0:\r\n        raise ValueError('Data size must great than zero.')\r\n    import numpy\r\n    x = numpy.array(x)\r\n    y = numpy.array(y)\r\n    theta = numpy.array([ t for t in theta ])\r\n    t = x.transpose()\r\n    for count in range(iterations):\r\n        h = numpy.dot(x, theta)\r\n        error = h - y\r\n        derivation = numpy.dot(t, error) / float(rows)\r\n        theta = theta - float(alpha) * derivation\r\n        # update error\r\n        e = numpy.dot(x, theta) - y\r\n        s = sum(e * e) / float(rows)\r\n        if s < limit:\r\n            break\r\n    return theta\r\n\r\n\r\n#----------------------------------------------------------------------\r\n# test \r\n#----------------------------------------------------------------------\r\ndef TestGD(proc, x, y, alpha, maxiter, limit = 0.0001):\r\n    k = [ 1 ] * len(x[0])\r\n    t = time.time()\r\n    k = proc(x, y, k, alpha, maxiter, limit)\r\n    t = time.time() - t\r\n    print('GradientDescent time:', t)\r\n    print('Theta:', k)\r\n    error = 0\r\n    X = [[3.1, 5.5], [3.3, 5.9], [3.5, 6.3], [3.7, 6.7], [3.9, 7.1]]\r\n    Y = [9.5, 10.2, 10.9, 11.6, 12.3]\r\n    for i in range(len(X)):\r\n        h = sum([ X[i][n] * k[n] for n in range(len(k)) ])\r\n        error += (h - Y[i]) * (h - Y[i])\r\n        print(Y[i], h)\r\n    error /= len(X)\r\n    print('error', error)\r\n    print()\r\n    return 0\r\n\r\n\r\n\r\n#----------------------------------------------------------------------\r\n# Samples\r\n#----------------------------------------------------------------------\r\nX = [[1.1, 1.5], [1.3, 1.9], [1.5, 2.3], [1.7, 2.7], [1.9, 3.1], \r\n    [2.1, 3.5], [2.3, 3.9], [2.5, 4.3], [2.7, 4.7], [2.9, 5.1]]\r\nY = [2.5, 3.2, 3.9, 4.6, 5.3, 6, 6.7, 7.4, 8.1, 8.8]\r\n\r\nTestGD(GradientDescent, X, Y, 0.1, 50000)\r\nTestGD(GradientDescent2, X, Y, 0.1, 50000)\r\nTestGD(GradientDescent3, X, Y, 0.1, 50000)\r\n\r\n\r\n", "meta": {"hexsha": "465c66126dca22d8cd157d71a09dbd202aa08280", "size": 4935, "ext": "py", "lang": "Python", "max_stars_repo_path": "GradientDescent.py", "max_stars_repo_name": "skywind3000/ml", "max_stars_repo_head_hexsha": "d3ac3d6070b66d84e25537915ee634723ddb8c51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-03-25T02:14:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T20:46:10.000Z", "max_issues_repo_path": "GradientDescent.py", "max_issues_repo_name": "skywind3000/ml", "max_issues_repo_head_hexsha": "d3ac3d6070b66d84e25537915ee634723ddb8c51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GradientDescent.py", "max_forks_repo_name": "skywind3000/ml", "max_forks_repo_head_hexsha": "d3ac3d6070b66d84e25537915ee634723ddb8c51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-06T04:44:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T01:27:55.000Z", "avg_line_length": 33.5714285714, "max_line_length": 72, "alphanum_fraction": 0.401621074, "include": true, "reason": "import numpy", "num_tokens": 1289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.9019206699387733, "lm_q1q2_score": 0.8571953051074062}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 26 08:20:48 2019\n\n@author: MAHDI\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\ndef GetY(solution , xval):\n    Y=0.0\n    for i in range(len(solution)):\n        Y = Y+ xval**i * solution[i]\n    return Y\ndef DrawPolinomial(solution,mycolor,mylabel):\n    x= np.linspace(0.0,11,100)\n#    print(x)\n    #y=np.array( [GetY(solution,xval) for xval in x])\n    y=GetY(solution,x)\n#    print(y)\n    plt.plot(x,y,color=mycolor,label=mylabel)\ndef PolinomialRegression(x,y,n,m):\n    \"\"\"\n    m= order of polinomial\n    \"\"\"\n# =============================================================================\n#     if n<m+1:\n#         return \"impossible\"\n# =============================================================================\n    a=np.zeros((m+1,m+1))\n    b=np.zeros((m+1))\n#    print(a,b)\n    for i in range(m+1):\n        sum = np.sum(x**i)\n        xid=0\n        yid=i\n        while yid>=0:\n            a[xid][yid]=sum\n            xid = xid +1\n            yid = yid -1\n    for i in range(m+1,m+m+1):\n        sum= np.sum(x**i)\n        xid=i-m\n        yid=m\n        while xid<=m:\n            a[xid][yid]=sum\n            xid = xid +1\n            yid = yid -1\n#    print(a)\n    for i in range(m+1):\n        sum = np.sum([(xx**i) * yy for (xx,yy) in zip(x,y) ])\n#        print(sum)\n        b[i]=sum\n#    print(b)\n    sol = np.linalg.solve(a,b)\n    return sol\ndef PrintSolution(Solution,x,y):\n    print('----------============----------')\n    print('Order of polynomial',len(Solution)-1)\n    for i in range(len(Solution)):\n        print('a',i,' = ',Solution[i],sep='')\n    print('Regression coefficient:',RegressionCoefficient(Solution,x,y))\n    print('----------============----------')\ndef RegressionCoefficient(Solution, x,y):\n    yavg = np.sum(y) / len(y)\n#    print(yavg)\n    St = np.sum(np.array([(yval-yavg)*(yval-yavg) for yval in y]))\n#    print(St)\n    Sr = np.sum(np.array([(yval - GetY(Solution,xval))*(yval - GetY(Solution,xval)) for (xval,yval) in zip(x,y)]))\n    return np.sqrt(1.0-Sr/St)\n\nif __name__ == '__main__':\n    file = open('data.txt', 'r+')\n    data = [list(map(float,line.split(' '))) for line in file.readlines() ]\n#    print(data)\n    x= [dat[0] for dat  in data]\n    y= [dat[1] for dat  in data]\n    x=np.array(x)\n    y=np.array(y)\n    assert(len(x)==len(y))\n    n=len(x)\n# =============================================================================\n#     for i in zip(x,y):\n#         print(i)\n# =============================================================================\n    plt.figure(figsize=(15,15))\n    plt.scatter(x,y,s=0.5,color = 'purple',label='original data')\n    sol1 = PolinomialRegression(x,y,n,1)\n    DrawPolinomial(sol1,'red','First order fit')\n    \n    sol2 = PolinomialRegression(x,y,n,2)\n    DrawPolinomial(sol2,'black','Second order fit')\n    \n    sol3 = PolinomialRegression(x,y,n,3)\n    DrawPolinomial(sol3,'green','Third order fit')\n    \n    plt.legend(loc='best',title='Curve Fitting Example')\n    \n# =============================================================================\n#     sol100=PolinomialRegression(x,y,n,100)\n#     DrawPolinomial(sol100,'pink','100th Order fit')\n# =============================================================================\n    \n    PrintSolution(sol1,x,y)\n    PrintSolution(sol2,x,y)\n    PrintSolution(sol3,x,y)\n#    PrintSolution(sol100,x,y)\n# =============================================================================\n#     print(sol1)\n#     print(RegressionCoefficient(sol1,x,y))\n#     \n#     print(sol2)\n#     print(RegressionCoefficient(sol2,x,y))\n#     print(sol3)\n#     print(RegressionCoefficient(sol3,x,y))\n# =============================================================================\n        ", "meta": {"hexsha": "9c262bb07d71c2dec2b9ce2e8303bbb0ecf6d567", "size": 3736, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numerical/Offline 3 on Curve Fitting/1705003.py", "max_stars_repo_name": "mahdihasnat/2-1-kodes", "max_stars_repo_head_hexsha": "1526de08f1bce66dbe428a8b27fedaca1ec75004", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numerical/Offline 3 on Curve Fitting/1705003.py", "max_issues_repo_name": "mahdihasnat/2-1-kodes", "max_issues_repo_head_hexsha": "1526de08f1bce66dbe428a8b27fedaca1ec75004", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numerical/Offline 3 on Curve Fitting/1705003.py", "max_forks_repo_name": "mahdihasnat/2-1-kodes", "max_forks_repo_head_hexsha": "1526de08f1bce66dbe428a8b27fedaca1ec75004", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2068965517, "max_line_length": 114, "alphanum_fraction": 0.4630620985, "include": true, "reason": "import numpy", "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.9005297881200701, "lm_q1q2_score": 0.8571811942850256}}
{"text": "import numpy as np\n\nEPSILON = 1e-10\n\ndef _error(actual: np.ndarray, predicted: np.ndarray):\n    \"\"\" Simple error \"\"\"\n    return actual - predicted\n\ndef me(actual: np.ndarray, predicted: np.ndarray):\n    \"\"\" Mean Error \"\"\"\n    return np.mean(_error(actual, predicted))\n\ndef _percentage_error(actual: np.ndarray, predicted: np.ndarray):\n    \"\"\"\n    Percentage error\n\n    Note: result is NOT multiplied by 100\n    \"\"\"\n    return _error(actual, predicted) / (actual + EPSILON)\n\ndef mae(actual: np.ndarray, predicted: np.ndarray):\n    \"\"\" Mean Absolute Error \"\"\"\n    return np.mean(np.abs(_error(actual, predicted)))\n\ndef mse(actual: np.ndarray, predicted: np.ndarray):\n    \"\"\" Mean Squared Error \"\"\"\n    return np.mean(np.square(_error(actual, predicted)))\n\ndef rmse(actual: np.ndarray, predicted: np.ndarray):\n    \"\"\" Root Mean Squared Error \"\"\"\n    return np.sqrt(mse(actual, predicted))\n\n", "meta": {"hexsha": "c3b085b5156ba269e753d9bd59a00fafdce1e73a", "size": 887, "ext": "py", "lang": "Python", "max_stars_repo_path": "benchmarks.py", "max_stars_repo_name": "EmmanuelOgbewe/squant", "max_stars_repo_head_hexsha": "6e6621dfeaac09dbf674427a0a3f0398d15051d3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmarks.py", "max_issues_repo_name": "EmmanuelOgbewe/squant", "max_issues_repo_head_hexsha": "6e6621dfeaac09dbf674427a0a3f0398d15051d3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks.py", "max_forks_repo_name": "EmmanuelOgbewe/squant", "max_forks_repo_head_hexsha": "6e6621dfeaac09dbf674427a0a3f0398d15051d3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8787878788, "max_line_length": 65, "alphanum_fraction": 0.6741826381, "include": true, "reason": "import numpy", "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488963, "lm_q2_score": 0.9005297801113612, "lm_q1q2_score": 0.8571811854321285}}
{"text": "\"\"\"\nauralib module containing various window functions for signal processing.\n\nAuthor:   Wes Hamlyn\nCreated:  24-Mar-2020\nLast Mod: 24-Mar-2020\n\"\"\"\n\nimport numpy as np\n\ndef papoulis(nsamp, normed=True):\n    \"\"\"\n    Calculate a time-domain Papoulis (a.k.a Bohman) window\n\n    Input:\n    ------\n        nsamp = number of samples to include in the window\n    \n    Output:\n    -------\n        w = window amplitudes\n        \n    Reference:\n    ----------\n        https://prod-ng.sandia.gov/techlib-noauth/access-control.cgi/2017/174042.pdf\n        page: 84\n    \"\"\"\n    \n    tmin = -0.5\n    tmax = 0.5\n    dt = (tmax-tmin)/(nsamp-1)\n\n    t = np.arange(nsamp)*dt + tmin\n    \n    w = (np.pi**2)/4 * (1-2*np.abs(t))*np.cos(2*np.pi*np.abs(t)) + \\\n        np.pi/4*np.sin(2*np.pi*np.abs(t))\n    \n    if normed:\n        w = w / w.max()\n        \n    return w\n\n\ndef cosine(nsamp, taper_len):\n    \"\"\"\n    Calculate a time-domain window with cosine tapers at each end\n    \n    nsamp = total length of window operator\n    nsamp_taper = length of cosine taper in samples at ends of window\n    \"\"\"\n    \n    # build cosine ramp from zero to one\n    x = np.linspace(-np.pi, 0.0, taper_len)\n    costaper = 0.5*(np.cos(x)+1)\n    \n    # make window with ones everwhere and add cosine tapers to ends\n    w = np.ones(nsamp)\n    w[0:taper_len] = costaper\n    w[-taper_len:] = costaper[-1::-1]\n    \n    return w\n\n\n", "meta": {"hexsha": "186164f47387ede709dd0657ed4b72e4c4702bc5", "size": 1385, "ext": "py", "lang": "Python", "max_stars_repo_path": "auralib/win.py", "max_stars_repo_name": "whamlyn/auralib", "max_stars_repo_head_hexsha": "01d64e25018fa249b3f901700428e9cb211d803c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2016-09-12T23:10:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-06T01:29:45.000Z", "max_issues_repo_path": "auralib/win.py", "max_issues_repo_name": "kwinkunks/auralib", "max_issues_repo_head_hexsha": "8300bb0c4d20156b9539df6d6c5e380f52572c4c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-12-02T01:56:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-27T23:55:58.000Z", "max_forks_repo_path": "auralib/win.py", "max_forks_repo_name": "kwinkunks/auralib", "max_forks_repo_head_hexsha": "8300bb0c4d20156b9539df6d6c5e380f52572c4c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-11-09T20:30:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T23:45:43.000Z", "avg_line_length": 21.640625, "max_line_length": 84, "alphanum_fraction": 0.5776173285, "include": true, "reason": "import numpy", "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.9005297754396142, "lm_q1q2_score": 0.8571811785258615}}
{"text": "# usage of regressions to find coefficients of formula to sum terms `i^m` from 0 to n\nimport numpy as np\nfrom numpy.linalg import inv\n\ndef plot(y,z):\n  import matplotlib.pyplot as plt\n\n  plt.plot(y, '.')\n  plt.plot(z)\n  plt.show()\n\n# solve Ordinary Least Squares\ndef solveOLS(X, Y):\n  Z = inv(X.T*X)\n  return Z*X.T*Y\n\n# generate `n` samples\nn = 15\n\n# exponent\nm = 8\n\nx = np.arange(0,n,1)\n\n# theory\nz = .5*x*(x+1)\n\n# generate output function\ny = np.cumsum(x**m)\n# format output\ny.shape = (n,1)\nY = np.asmatrix(y)\n\n# prepare matrix\nX = np.ones((n,1))\n\nx.shape = (n,1)\n\n# add column of input until m+1 (inclusive)\nfor i in range(1, m+2):\n  X = np.append(X, x**i, axis =1)\n\nX = np.asmatrix(X)\nr = solveOLS(X, Y)\nprint r\nprint np.cumsum(r)\n\n# m=0: (1,   1)\n# m=1: (0, 1/2, 1/2)\n# m=2: (0, 1/6, 1/2, 1/3)\n# m=3: (0,   0, 1/4, 1/2,  1/4)\n# m=4: (0,   -1/30,   0, 1/3,  1/2, 1/5)  \n# m=5: (0,   0,   0,   0, 5/12, 1/2, 1/6)\n# \n# sum always 1!!? (except for 0)", "meta": {"hexsha": "bbc48f1fe8f179c34c4d85a42c02e6690e2a0de9", "size": 951, "ext": "py", "lang": "Python", "max_stars_repo_path": "regressionForSumofn.py", "max_stars_repo_name": "jboissard/mathExperiments", "max_stars_repo_head_hexsha": "350a5053fc5d8411b77ea7d084180ef5a8ba24b0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-07-08T10:56:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-14T16:26:00.000Z", "max_issues_repo_path": "regressionForSumofn.py", "max_issues_repo_name": "jboissard/mathExperiments", "max_issues_repo_head_hexsha": "350a5053fc5d8411b77ea7d084180ef5a8ba24b0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "regressionForSumofn.py", "max_forks_repo_name": "jboissard/mathExperiments", "max_forks_repo_head_hexsha": "350a5053fc5d8411b77ea7d084180ef5a8ba24b0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.2909090909, "max_line_length": 85, "alphanum_fraction": 0.5751840168, "include": true, "reason": "import numpy,from numpy", "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9845754470129647, "lm_q2_score": 0.8705972751232808, "lm_q1q2_score": 0.8571687013227732}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 26 16:48:41 2019\n\n@author: alankar\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef quad_solve1(a,b,c):\n    D = b**2-4*a*c\n    return np.array([(-b+np.sqrt(D))/(2*a),(-b-np.sqrt(D))/(2*a)])\n\ndef quad_solve2(a,b,c):\n    D = b**2-4*a*c\n    return np.array([(2*c)/(-b-np.sqrt(D)),(2*c)/(-b+np.sqrt(D))])\n\nprint('Using form 1:')\nprint('Roots are:',end=' ')\nprint(quad_solve1(.001, 1000, .001))\nprint('Using form 2:')\nprint('Roots are:',end=' ')\nprint(quad_solve2(.001, 1000, .001))\n\n\"\"\"\nThe two functions differ in their results. This happens when $b^2>>|4ac|$. In either of the two\nformulae, finding one of the roots involve subtracting two nearly equal quantities (Discriminant is almost $b^2$).\nThis results in loss of numerical precision corresponding to that root. So in one formula if Root 1 is more accurate\nthan Root 2, then in the other formula, Root2 is more accurate than Root 1. Now the question is which root is more accurate\nin which formula?\nWell that depends on the sign of $b$ in $ax^2+bx+c=0$\nWhen $b>0$, $-b-\\sqrt{b^2-4ac}$ doesn't involve subtracting two nearly equal quantities. So Root 2 of quad_solve1 and\nRoot 1 of quad_solve2 gives accurate results.\nConverse happens for $b<0$\n\nLets code this in the following function:\n\"\"\"\n\ndef quad_solve_acc(a,b,c):\n    if b>0:\n        return np.array([quad_solve2(a,b,c)[0],quad_solve1(a,b,c)[1]])\n    else:\n        return np.array([quad_solve1(a,b,c)[10],quad_solve2(a,b,c)[1]])\n    \nprint('Accurate Roots are:',end=' ')\nprint(quad_solve_acc(.001, 1000, .001))\n\nx = -np.linspace(0,14,100)*1e-7\nplt.plot(x,0.001*x**2+1000*x+0.001)\nplt.grid()\nplt.show()", "meta": {"hexsha": "b7ec4bb47b6ac643e6037a8fdd0a29c1a30b61e0", "size": 1691, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw2/02/2.py", "max_stars_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_stars_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:47:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:05:39.000Z", "max_issues_repo_path": "hw2/02/2.py", "max_issues_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_issues_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw2/02/2.py", "max_forks_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_forks_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-21T17:33:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T02:58:56.000Z", "avg_line_length": 32.5192307692, "max_line_length": 123, "alphanum_fraction": 0.6759314015, "include": true, "reason": "import numpy", "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875641, "lm_q2_score": 0.9032942164664239, "lm_q1q2_score": 0.8571514769167565}}
{"text": "\"\"\"\nExample 2 - Multi Variable Linear Regression\n\nNOTE: The example and sample data is being taken from the \"Machine Learning course by Andrew Ng\" in Coursera.\n\nProblem:\n  Suppose you are the CEO of a restaurant franchise and are considering\n  different cities for opening a new outlet. The chain already has trucks\n  in various cities and you have data for profits and populations from\n  the cities. You would like to use this data to help you select which\n  city to expand to next.\n\n  The file 'data/linear_reg/ex1data1.txt' contains the dataset for our\n  linear regression problem. The first column is the population of a city\n  and the second column is the profit of a food truck in that city.\n  A negative value for profit indicates a loss.\n\"\"\"\n\n# initial imports\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom models.data_preprocessing import feature_normalize, add_bias_unit\nfrom models.linear_regression import gradient_descent, normal_equation\n\nplt.ion()\n\n# ----------------Loading X and y matrix ---------------\nprint('Loading data ...')\n\ndata = np.loadtxt('data/ex1data2.txt', delimiter=',')\nX = data[:, :-1]  # 47x2\ny = data[:, -1, None]  # 47x1\nm = y.size  # 47\n\n# printing first 5 elements\nprint(X[0:5, :])\n\n# ----------------Feature Normalization -----------------\nprint(\"Normalizing the features\")\nX, mu, sigma = feature_normalize(X)\n\n# adding intercept term to X\nX = add_bias_unit(X)\n\nprint('Running gradient descent ...')\n\n# Choose some alpha value\nalpha = 0.03\nnum_iters = 400\n\n# Init Theta and Run Gradient Descent\ntheta = np.zeros((X.shape[1], 1))\ntheta, J_history = gradient_descent(X, y, theta, alpha, num_iters)\n\n# Plot the convergence graph\nfig = plt.figure(\"Covariance Graph\")\nax = fig.subplots()\nax.plot(range(J_history.size), J_history, lw=2)\nax.set_xlabel('Number of iterations')\nax.set_ylabel('Cost J')\nfig.show()\n\n# Display gradient descent's result\nprint('Theta computed from gradient descent: ')\nprint(theta)\n\n# Estimate the price of a 1650 sq-ft, 3 br house\n\ntest_data = np.array([1650, 3]).reshape(1, 2)\ntest_data, _, __ = feature_normalize(test_data, mu, sigma)\ntest_data = add_bias_unit(test_data)\nprice = test_data.dot(theta)\n\n# ============================================================\n\nprint('Predicted price of a 1650 sq-ft, 3 br house (using gradient descent): {}'.format(price))\n\n# ================Normal Equations ================\n\nprint('Solving with normal equations...')\n\n# ----------------Loading X and y matrix ---------------\nprint('Loading data ...')\n\ndata = np.loadtxt('data/ex1data2.txt', delimiter=',')\nX = data[:, :-1]  # 47x2\ny = data[:, -1, None]  # 47x1\nm = y.size  # 47\n\n# Add intercept term to X\nX = add_bias_unit(X)\n\n# Calculate the parameters from the normal equation\ntheta = normal_equation(X, y)\n\n# Display normal equation's result\nprint('Theta computed from the normal equations: ')\nprint(theta)\n\n# Estimate the price of a 1650 sq-ft, 3 br house\ntest_data = np.array([1650, 3]).reshape(1, 2)\ntest_data = add_bias_unit(test_data)\nprice = test_data.dot(theta)\n\nprint('Predicted price of a 1650 sq-ft, 3 br house (using normal equations): {}'.format(price))\n\n# bloking matplotlib figures for obervations\nplt.ioff()\nplt.show()\n", "meta": {"hexsha": "d9d38764919946e387654a926fe825ebde79e87b", "size": 3200, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear_Regression/Scripts/multi_variable_linear_regression.py", "max_stars_repo_name": "Mr-MayankThakur/Machine-learning-Implementations-with-Numpy", "max_stars_repo_head_hexsha": "453bb15c9089d42b52ff0ff09d8c66def137ec4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Linear_Regression/Scripts/multi_variable_linear_regression.py", "max_issues_repo_name": "Mr-MayankThakur/Machine-learning-Implementations-with-Numpy", "max_issues_repo_head_hexsha": "453bb15c9089d42b52ff0ff09d8c66def137ec4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear_Regression/Scripts/multi_variable_linear_regression.py", "max_forks_repo_name": "Mr-MayankThakur/Machine-learning-Implementations-with-Numpy", "max_forks_repo_head_hexsha": "453bb15c9089d42b52ff0ff09d8c66def137ec4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0909090909, "max_line_length": 109, "alphanum_fraction": 0.6896875, "include": true, "reason": "import numpy", "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.9032942067038785, "lm_q1q2_score": 0.8571514637381671}}
{"text": "import numpy as np\n\nnp.array([1, 2])\n\n# Exercice 2.3\n\nprint(\"Question 1 \\n\")\n\nA, x = np.array([[1, 2, 3], [4, 5, 6]]), np.array([1, 2, 3])\n\nprint(A.shape, x.shape)\nprint(A.size, x.size)\nprint(A.ndim, x.ndim)\nprint(A.dtype, x.dtype)\nprint(A.sum(), x.sum())\nprint(A.prod(), x.prod())\n\nprint(\"\\n Question2 \\n\")\n\nnbColsA, nbLignesA = A.shape\n\nprint(nbColsA, nbLignesA)\n\nprodLignesA = A.prod(axis=1)\nprodColA = A.prod(axis=0)\n\nprint(prodLignesA, prodColA)\n\nprint(\"\\nQuestion 3\\n\")\n\nprint(A*x)\n# Multiplie chaque ligne de A par x (coefficient à coefficient)\n\n\nprint(A.dot(x))\n# Fait la multiplication matricielle pour A et x\n\nprint(np.dot(A, x))\n# Fait la multiplication matricielle pour A et x\n\n# Exercice 2.3\nprint(\"\\nExercice 2.3\\n\")\nA, B, C, D = np.array([[7, 0], [-1, 5], [-1, 2]]), np.array([[1, 4], [-4, 0]]), np.array([7, 3]), np.array([8, 2])\n\nprint(\"A x B=\", np.dot(A, B))\nprint(\"A x C=\", np.dot(A, C))\nprint(\"C x D=\", np.dot(C, D))\nprint(\"D x C=\", np.dot(D, C))\nprint(\"D x B X C=\", np.dot(np.dot(D, B), C))\nprint(\"AT x A=\", np.dot(A.T, A))\nprint(\"A x AT=\", np.dot(A, A.T))\n\n# Exercice 2.4\nprint(\"\\nExercice 2.4\")\n\nv1 = np.arange(1, 17, 1)\nv2 = np.arange(0.0, 2.1, 0.2)\nv3 = np.array([2**x for x in range(7)])\n\nprint(v1)\nprint(v2)\nprint(v3)\n\nprint(\"\\nQuestion 2\\n\")\n# Sûrement à refaire, en fonction du cours\nA = np.array([[y**x for x in range(9)]for y in [2, 3, 5]])\nB = np.array([np.arange(.0, 1.1, .2) for x in range(4)])\nC = np.array([[y for x in range(7)] for y in [.0, .5, 1.]])\n\nprint(A)\nprint(B)\nprint(C)\n\n\nprint(\"\\nQuestion 3\\n\")\n\nA = np.array([[1 if (x == 0 or x == 9) else (1 if (y == 0 or y == 9) else (1 if x == y else 0)) for x in range(10)] for y in range(10)])\n\nprint(A)\n\nprint(\"\\nQuestion 4\\n\")\n\nL = np.array([[2 if i == j else (-1 if (i == j - 1 or i == j + 1) else 0) for j in range(10)] for i in range(10)])\n\nprint(L)\n\nprint(\"\\nQuestion 5\\n\")\n\nT = np.array([[1 if ((i + j) % 2 == 0) else 0 for j in range(10)] for i in range(10)])\n\nprint(T)\n", "meta": {"hexsha": "86929a7f63e379563538f824bf798a9567a5ef42", "size": 1965, "ext": "py", "lang": "Python", "max_stars_repo_path": "Math208_Python/TP2/TP2.py", "max_stars_repo_name": "emilienlemaire/DL2MI_TP", "max_stars_repo_head_hexsha": "6810d6e8a7fbd73c319b8c13196486ab30e2f746", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Math208_Python/TP2/TP2.py", "max_issues_repo_name": "emilienlemaire/DL2MI_TP", "max_issues_repo_head_hexsha": "6810d6e8a7fbd73c319b8c13196486ab30e2f746", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math208_Python/TP2/TP2.py", "max_forks_repo_name": "emilienlemaire/DL2MI_TP", "max_forks_repo_head_hexsha": "6810d6e8a7fbd73c319b8c13196486ab30e2f746", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3586956522, "max_line_length": 136, "alphanum_fraction": 0.586259542, "include": true, "reason": "import numpy", "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172572644806, "lm_q2_score": 0.9032942008463507, "lm_q1q2_score": 0.85715145557003}}
{"text": "# My Gauss Siedel Program implemented in Python submitted to GeeksforGeeks: (under review)\n\nimport numpy as np\n\n# Iteration Limit.\nLimit = 10\n\"\"\"\nCo-efficients of matrix considered : (LHS vectors)\n[[10., -1., 2., 0.],[-1., 11., -1., 3.],[2., -1., 10., -1.],[0., 3., -1., 8.]]=A\nCorresponding constants of equation on other side: (RHS vector)\n[6., 25., -11., 15.]=B\n-> We will solve for Ax=B, where x=[x1,x2,x3,x4]\n\"\"\"\n\n# Initialize the matrix we want to perform Gauss Siedel Method on.\nA = np.array([[10., -1., 2., 0.],\n              [-1., 11., -1., 3.],\n              [2., -1., 10., -1.],\n              [0., 3., -1., 8.]])\n# Initialize the RHS column vector.\nb = np.array([6., 25., -11., 15.])\n\nprint(\"System of equations:\")\n# Displaying in matrix form, x1*(co-efficient) + x2*(co-efficient) +...\nfor i in range(A.shape[0]):\n    row = [\"{0:3g}*x{1}\".format(A[i, j], j + 1) for j in range(A.shape[1])]\n    print(\"[{0}] = [{1:3g}]\".format(\" + \".join(row), b[i]))\n\n# Returning array of zeros for RHS vector (b) for initial approximation.\nx = np.zeros_like(b)\nfor it_count in range(1, Limit):\n    x_new = np.zeros_like(x)\n    # Display solution-vector/approximate values of x1,x2,x3,x4 for each iteration.\n    print(\"Iteration {0}: {1}\".format(it_count, x))\n    for i in range(A.shape[0]):\n        s1 = np.dot(A[i, :i], x_new[:i])\n        s2 = np.dot(A[i, i + 1:], x[i + 1:])\n        x_new[i] = (b[i] - s1 - s2) / A[i, i]\n     \n     # Using tolerance limit to reach closer approximation to answer and checking if desired accuracy is obtained. (considering relative tolerance/error limit=1e-8, and checking between arrays x and new x) if desired accuracy is obtained, break.\n\n    if np.allclose(x, x_new, rtol=1e-8):\n        break\n    x = x_new\n    \n# Solution to our matrix, vector x=[x1,x2,x3,x4]\nprint(\"Solution: {0}\".format(x))\nerror = np.dot(A, x) - b\n# Approximation error.\nprint(\"Error: {0}\".format(error))\n", "meta": {"hexsha": "bff53fcaf86e4e1fa2d52b5cdc3521cb58309612", "size": 1910, "ext": "py", "lang": "Python", "max_stars_repo_path": "Computational Mathematics | Python/Gauss_Siedel.py", "max_stars_repo_name": "Anirban166/Quadratics", "max_stars_repo_head_hexsha": "9e031625fb2ff62087c1592fee89d58528193a33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-09-16T06:37:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T11:34:58.000Z", "max_issues_repo_path": "Computational Mathematics | Python/Gauss_Siedel.py", "max_issues_repo_name": "Anirban166/Quadratics", "max_issues_repo_head_hexsha": "9e031625fb2ff62087c1592fee89d58528193a33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Computational Mathematics | Python/Gauss_Siedel.py", "max_forks_repo_name": "Anirban166/Quadratics", "max_forks_repo_head_hexsha": "9e031625fb2ff62087c1592fee89d58528193a33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-10-11T15:00:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-15T16:56:14.000Z", "avg_line_length": 37.4509803922, "max_line_length": 245, "alphanum_fraction": 0.5989528796, "include": true, "reason": "import numpy", "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.9086179062123119, "lm_q1q2_score": 0.8571424995943082}}
{"text": "import numpy as _np\n\n\ndef euler(f, initial, interval, h):\n    \"\"\"This function solves the differential equation using Euler's method and initial\n    value condition.\n\n    Parameters\n    ----------\n    f : function\n        function form of the differential equation to be solved\n    initial : tuple\n        tuple of the initial values\n    interval : tuple\n        tuple of the interval in which the differential eq\n    h : float\n        step size for each iteration\n\n    Returns\n    -------\n    ts : 1d array\n        array of t's\n    ys : 1d array\n        array of corresponding y's\n\n    \"\"\"\n    a, b = interval\n    ts = _np.arange(a, b + h, h)\n    ys = _np.zeros_like(ts)\n\n    if initial[0] != interval[0]:\n        print(\"The point for initial value doesn't match the start of interval\")\n        return None, None\n\n    ys[0] = initial[1]\n\n    for i in range(len(ts) - 1):\n        ys[i + 1] = ys[i] + f(ys[i], ts[i]) * h\n\n    return ts, ys\n\n\ndef midpoint_euler(f, initial, interval, h):\n    \"\"\"This function solves the differential equation using Ralstone's method and initial\n    value condition.\n\n    Parameters\n    ----------\n    f : function\n        function form of the differential equation to be solved\n    initial : tuple\n        tuple of the initial values\n    interval : tuple\n        tuple of the interval in which the differential eq\n    h : float\n        step size for each iteration\n\n    Returns\n    -------\n    ts : 1d array\n        array of t's\n    ys : 1d array\n        array of corresponding y's\n\n    \"\"\"\n    A = 0.5\n    B1 = 0.0\n    B2 = 1\n    a, b = interval\n    ts = _np.arange(a, b + h, h)\n    ys = _np.zeros_like(ts)\n\n    if initial[0] != interval[0]:\n        print(\"The point for initial value doesn't match the start of interval\")\n        return None, None\n\n    ys[0] = initial[1]\n\n    for i in range(len(ts) - 1):\n        p_i = f(ys[i], ts[i])\n        q_i = f(ys[i] + A * h * p_i, ts[i] + h * A)\n        ys[i + 1] = ys[i] + (B1 * p_i + B2 * q_i) * h\n\n    return ts, ys\n\n\ndef heun(f, initial, interval, h):\n    \"\"\"This function solves the differential equation using Heun's method and initial\n    value condition.\n\n    Parameters\n    ----------\n    f : function\n        function form of the differential equation to be solved\n    initial : tuple\n        tuple of the initial values\n    interval : tuple\n        tuple of the interval in which the differential eq\n    h : float\n        step size for each iteration\n\n    Returns\n    -------\n    ts : 1d array\n        array of t's\n    ys : 1d array\n        array of corresponding y's\n\n    \"\"\"\n    A = 1\n    B1 = 0.5\n    B2 = 0.5\n    a, b = interval\n    ts = _np.arange(a, b + h, h)\n    ys = _np.zeros_like(ts)\n\n    if initial[0] != interval[0]:\n        print(\"The point for initial value doesn't match the start of interval\")\n        return None, None\n\n    ys[0] = initial[1]\n\n    for i in range(len(ts) - 1):\n        p_i = f(ys[i], ts[i])\n        q_i = f(ys[i] + A * h * p_i, ts[i] + h * A)\n        ys[i + 1] = ys[i] + (B1 * p_i + B2 * q_i) * h\n\n    return ts, ys\n\n\ndef ralstone(f, initial, interval, h):\n    \"\"\"This function solves the differential equation using Ralstone's method and initial\n    value condition.\n\n    Parameters\n    ----------\n    f : function\n        function form of the differential equation to be solved\n    initial : tuple\n        tuple of the initial values\n    interval : tuple\n        tuple of the interval in which the differential eq\n    h : float\n        step size for each iteration\n\n    Returns\n    -------\n    ts : 1d array\n        array of t's\n    ys : 1d array\n        array of corresponding y's\n\n    \"\"\"\n    A = 2 / 3\n    B1 = 0.25\n    B2 = 0.75\n    a, b = interval\n    ts = _np.arange(a, b + h, h)\n    ys = _np.zeros_like(ts)\n\n    if initial[0] != interval[0]:\n        print(\"The point for initial value doesn't match the start of interval\")\n        return None, None\n\n    ys[0] = initial[1]\n\n    for i in range(len(ts) - 1):\n        p_i = f(ys[i], ts[i])\n        q_i = f(ys[i] + A * h * p_i, ts[i] + h * A)\n        ys[i + 1] = ys[i] + (B1 * p_i + B2 * q_i) * h\n\n    return ts, ys\n\n\ndef rk3(f, initial, interval, h):\n    \"\"\"This function solves the differential equation using 3rd order Runga-Kutta\n    method and initial value condition.\n\n    Parameters\n    ----------\n    f : function\n        function form of the differential equation to be solved\n    initial : tuple\n        tuple of the initial values\n    interval : tuple\n        tuple of the interval in which the differential eq\n    h : float\n        step size for each iteration\n\n    Returns\n    -------\n    ts : 1d array\n        array of t's\n    ys : 1d array\n        array of corresponding y's\n\n    \"\"\"\n    a, b = interval\n    ts = _np.arange(a, b + h, h)\n    ys = _np.zeros_like(ts)\n\n    if initial[0] != interval[0]:\n        print(\"The point for initial value doesn't match the start of interval\")\n        return None, None\n\n    ys[0] = initial[1]\n\n    for i in range(len(ts) - 1):\n        p_i = f(ys[i], ts[i])\n        q_i = f(ys[i] + 0.5 * h * p_i, ts[i] + h * 0.5)\n        r_i = f(ys[i] - p_i * h + 2 * q_i * h, ts[i] + h)\n        ys[i + 1] = ys[i] + (p_i + 4 * q_i + r_i) * h / 6\n\n    return ts, ys\n\n\ndef rk4(f, initial, interval, h):\n    \"\"\"This function solves the differential equation using 4th order Runga-Kutta\n    method and initial value condition.\n\n    Parameters\n    ----------\n    f : function\n        function form of the differential equation to be solved\n    initial : tuple\n        tuple of the initial values\n    interval : tuple\n        tuple of the interval in which the differential eq\n    h : float\n        step size for each iteration\n\n    Returns\n    -------\n    ts : 1d array\n        array of t's\n    ys : 1d array\n        array of corresponding y's\n\n    \"\"\"\n    a, b = interval\n    ts = _np.arange(a, b + h, h)\n    ys = _np.zeros_like(ts)\n\n    if initial[0] != interval[0]:\n        print(\"The point for initial value doesn't match the start of interval\")\n        return None, None\n\n    ys[0] = initial[1]\n\n    for i in range(len(ts) - 1):\n        p_i = f(ys[i], ts[i])\n        q_i = f(ys[i] + 0.5 * h * p_i, ts[i] + h * 0.5)\n        r_i = f(ys[i] + 0.5 * h * q_i, ts[i] + h * 0.5)\n        s_i = f(ys[i] + h * r_i, ts[i] + h)\n        ys[i + 1] = ys[i] + (p_i + 2 * q_i + 2 * r_i + s_i) * h / 6\n\n    return ts, ys\n\n", "meta": {"hexsha": "f227d20e209021dbe4b35485ac219088c885c8f8", "size": 6313, "ext": "py", "lang": "Python", "max_stars_repo_path": "ODE.py", "max_stars_repo_name": "MASTERAMARJEET/Numerical_Method", "max_stars_repo_head_hexsha": "186ae125f2991afec570c86da55640d80d282de5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ODE.py", "max_issues_repo_name": "MASTERAMARJEET/Numerical_Method", "max_issues_repo_head_hexsha": "186ae125f2991afec570c86da55640d80d282de5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ODE.py", "max_forks_repo_name": "MASTERAMARJEET/Numerical_Method", "max_forks_repo_head_hexsha": "186ae125f2991afec570c86da55640d80d282de5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3745173745, "max_line_length": 89, "alphanum_fraction": 0.5548867416, "include": true, "reason": "import numpy", "num_tokens": 1860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.9086179055936797, "lm_q1q2_score": 0.8571424946691921}}
{"text": "\"\"\"Gell-Mann matrices.\"\"\"\nfrom scipy.sparse import csr_matrix\n\nimport numpy as np\n\n\ndef gell_mann(ind: int, is_sparse: bool = False) -> np.ndarray:\n    r\"\"\"\n    Produce a Gell-Mann operator [WikGM]_.\n\n    Generates the 3-by-3 Gell-Mann matrix indicated by the value of\n    :code:`ind`.  When :code:`ind = 0` gives the identity matrix, while values\n    1 through 8 each indicate one of the other 8 Gell-Mann matrices.\n\n    The 9 Gell-Mann matrices are defined as follows:\n\n    .. math::\n        \\begin{equation}\n            \\begin{aligned}\n                \\lambda_0 = \\begin{pmatrix}\n                                1 & 0 & 0 \\\\\n                                0 & 1 & 0 \\\\\n                                0 & 0 & 1\n                            \\end{pmatrix}, \\quad\n                \\lambda_1 = \\begin{pmatrix}\n                                0 & 1 & 0 \\\\\n                                1 & 0 & 0 \\\\\n                                0 & 0 & 0\n                            \\end{pmatrix}, \\quad &\n                \\lambda_2 = \\begin{pmatrix}\n                                0 & -i & 0 \\\\\n                                i & 0 & 0 \\\\\n                                0 & 0 & 0\n                            \\end{pmatrix},  \\\\\n                \\lambda_3 = \\begin{pmatrix}\n                                1 & 0 & 0 \\\\\n                                0 & -1 & 0 \\\\\n                                0 & 0 & 0\n                            \\end{pmatrix}, \\quad\n                \\lambda_4 = \\begin{pmatrix}\n                                0 & 0 & 1 \\\\\n                                0 & 0 & 0 \\\\\n                                1 & 0 & 0\n                            \\end{pmatrix}, \\quad &\n                \\lambda_5 = \\begin{pmatrix}\n                                0 & 0 & -i \\\\\n                                0 & 0 & 0 \\\\\n                                i & 0 & 0\n                            \\end{pmatrix},  \\\\\n                \\lambda_6 = \\begin{pmatrix}\n                                0 & 0 & 0 \\\\\n                                0 & 0 & 1 \\\\\n                                0 & 1 & 0\n                            \\end{pmatrix}, \\quad\n                \\lambda_7 = \\begin{pmatrix}\n                                0 & 0 & 0 \\\\\n                                0 & 0 & -i \\\\\n                                0 & i & 0\n                            \\end{pmatrix}, \\quad &\n                \\lambda_8 = \\frac{1}{\\sqrt{3}} \\begin{pmatrix}\n                                                    1 & 0 & 0 \\\\\n                                                    0 & 1 & 0 \\\\\n                                                    0 & 0 & -2\n                                                \\end{pmatrix}.\n                \\end{aligned}\n            \\end{equation}\n\n    Examples\n    ==========\n\n    The Gell-Mann matrix generated from :code:`idx = 2` yields the following\n    matrix:\n\n    .. math::\n\n        \\lambda_2 = \\begin{pmatrix}\n                            0 & -i & 0 \\\\\n                            i & 0 & 0 \\\\\n                            0 & 0 & 0\n                    \\end{pmatrix}\n\n    >>> from toqito.matrices import gell_mann\n    >>> gell_mann(2)\n    [[ 0.+0.j, -0.-1.j,  0.+0.j],\n     [ 0.+1.j,  0.+0.j,  0.+0.j],\n     [ 0.+0.j,  0.+0.j,  0.+0.j]]\n\n    References\n    ==========\n    .. [WikGM] Wikipedia: Gell-Mann matrices,\n        https://en.wikipedia.org/wiki/Gell-Mann_matrices\n\n    :param ind: An integer between 0 and 8 (inclusive).\n    :param is_sparse: Boolean to determine whether matrix is sparse.\n    \"\"\"\n    if ind == 0:\n        gm_op = np.identity(3)\n    elif ind == 1:\n        gm_op = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 0]])\n    elif ind == 2:\n        gm_op = np.array([[0, -1j, 0], [1j, 0, 0], [0, 0, 0]])\n    elif ind == 3:\n        gm_op = np.array([[1, 0, 0], [0, -1, 0], [0, 0, 0]])\n    elif ind == 4:\n        gm_op = np.array([[0, 0, 1], [0, 0, 0], [1, 0, 0]])\n    elif ind == 5:\n        gm_op = np.array([[0, 0, -1j], [0, 0, 0], [1j, 0, 0]])\n    elif ind == 6:\n        gm_op = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0]])\n    elif ind == 7:\n        gm_op = np.array([[0, 0, 0], [0, 0, -1j], [0, 1j, 0]])\n    elif ind == 8:\n        gm_op = np.array([[1, 0, 0], [0, 1, 0], [0, 0, -2]]) / np.sqrt(3)\n    else:\n        raise ValueError(\"Gell-Mann index values can only be values from 0 to \" \"8 (inclusive).\")\n\n    if is_sparse:\n        gm_op = csr_matrix(gm_op)\n\n    return gm_op\n", "meta": {"hexsha": "68ffebcb0380fc47a542e40c7f453f2c39b6ce8f", "size": 4368, "ext": "py", "lang": "Python", "max_stars_repo_path": "toqito/matrices/gell_mann.py", "max_stars_repo_name": "paniash/toqito", "max_stars_repo_head_hexsha": "ab67c2a3fca77b3827be11d1e79531042ea62b82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2020-01-28T17:02:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T18:02:15.000Z", "max_issues_repo_path": "toqito/matrices/gell_mann.py", "max_issues_repo_name": "paniash/toqito", "max_issues_repo_head_hexsha": "ab67c2a3fca77b3827be11d1e79531042ea62b82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 82, "max_issues_repo_issues_event_min_datetime": "2020-05-31T20:09:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:13:59.000Z", "max_forks_repo_path": "toqito/matrices/gell_mann.py", "max_forks_repo_name": "paniash/toqito", "max_forks_repo_head_hexsha": "ab67c2a3fca77b3827be11d1e79531042ea62b82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2020-04-02T16:07:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T13:39:22.000Z", "avg_line_length": 36.0991735537, "max_line_length": 97, "alphanum_fraction": 0.3431776557, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240211961401, "lm_q2_score": 0.9136765292901317, "lm_q1q2_score": 0.8571418997301912}}
{"text": "#!usr/bin/python\n\"\"\"\nauthor  : Bhekimpilo Ndhlela\nauthor  : 18998712\nmodule  : Applied Mathematics(Numerical Methods) TW324\ntask    : computer assignment 05 question 2\nsince   : Friday-27-04-2018\n\"\"\"\n\ndef composite_midpoint(f, m, a=0.0, b=1.0):\n    h = (b - a) / m\n    return h * sum([f((a+h/2.0) + i*h) for i in xrange(0, m)])\n\ndef composite_trapezium(f, m, a=0.0, b=1.0):\n    h = (b - a) / m\n    return h/2.0 * (f(a) + f(b) + 2 * sum([ f(a + i * h) for i in xrange(1, m)]))\n\ndef composite_simpson(f, m, a=0.0, b=1.0):\n    sum = float(f(a) + f(b))\n    h   = (b-a) / (2*m)\n    oddSum, evenSum = 0.0, 0.0\n\n    for i in range(1, m): #evaluating all odd values of n (not first and last)\n        oddSum += f(2 * h * i + a)\n    sum += oddSum * 2\n    for i in range(1,m+1): #evaluating all even values of n (not first and last)\n        evenSum += f(h * (-1 + 2 * i) + a)\n    sum += evenSum * 4\n    return sum * h / 3\n\ndef debug(abs_err_cm, abs_err_ct, abs_err_cs, debug=True):\n    if debug == True:\n        print(\"DEBUG MODE STATUS = <ON>\")\n        print(\"Composite Midpoint\\tComposite trapezium\\tComposite_Simpson\")\n        for m, t, s in zip(abs_err_cm, abs_err_ct, abs_err_cs):\n                print \"{:.20f}     \".format(m), \\\n                      \"{:.20f}     \".format(t), \\\n                      \"{:.20f}     \".format(s)\n\ndef plot_abs_errs(abs_err_cm, abs_err_ct, abs_err_cs):\n    plt.title(\"|xc-x| of: The Composite Midpoint, Simpson & \\\n              Trapezium Methods against h\")\n    plt.ylabel(\"Composite Midpoint vs Composite Simpson vs Composite Trapezium\")\n    plt.xlabel(\"Number of Points\")\n    plt.xscale('log')\n    plt.yscale('log')\n    plt.plot(M, abs_err_cm, 'k-', label=\"Composite Midpoint\")\n    plt.plot(M, abs_err_ct, 'r-', label=\"Composite Trapezium\")\n    plt.plot(M, abs_err_cs, 'b-', label=\"Composite Simpson\")\n    plt.legend(bbox_to_anchor=(.95, .9))\n    plt.show()\n\nif __name__ == \"__main__\":\n    import matplotlib.pyplot as plt\n    from math import (exp, pi, sin)\n    from scipy import (integrate, special)\n    from numpy import (abs, array, linspace)\n\n    f = lambda x : exp(sin(2 * pi * x))\n    I = integrate.quad(f, 0.0, 1.0)[0]\n    M = linspace(3, 19, 5)\n\n    abs_err_cm = [abs(composite_midpoint(f, int(m)) - I) for m in M]\n    abs_err_ct = [abs(composite_trapezium(f, int(m)) - I) for m in M]\n    abs_err_cs = [abs(composite_simpson(f, int(m)) - I) for m in M]\n    debug(abs_err_cm, abs_err_ct, abs_err_cs, debug=True)\n    plot_abs_errs(abs_err_cm, abs_err_ct, abs_err_cs)\nelse:\n    from sys import exit\n    exit(\"USAGE: python question2.py\")\n", "meta": {"hexsha": "7a8bdddfd9e7051d66a3d94146e3e1aba47a1226", "size": 2571, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment_05/src/question2.py", "max_stars_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_stars_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-28T18:36:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-28T18:36:55.000Z", "max_issues_repo_path": "assignment_05/src/question2.py", "max_issues_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_issues_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment_05/src/question2.py", "max_forks_repo_name": "BhekimpiloNdhlela/TW324NumericalMethods", "max_forks_repo_head_hexsha": "face751cdd3ac9566ccae554e54ac15e951d2f7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-16T04:26:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-16T04:26:44.000Z", "avg_line_length": 36.2112676056, "max_line_length": 81, "alphanum_fraction": 0.6001555815, "include": true, "reason": "from numpy,from scipy", "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164656, "lm_q2_score": 0.9136765145991261, "lm_q1q2_score": 0.8571418764645412}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# 평균 제곱 오차 mean squared error\r\ndef mean_squared_error(y,t):\r\n    return 0.5 * np.sum((y-t)**2)\r\n\r\ny = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0]\r\nt = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]\r\n\r\n# print(mean_squared_error(np.array(y), np.array(t)))\r\n\r\ny = [0.1, 0.05, 0.1, 0.0, 0.05, 0.1, 0.0, 0.6, 0.0, 0.0]\r\n# print(mean_squared_error(np.array(y), np.array(t)))\r\n\r\n# 교차 엔트로피 오차 cross entropy error\r\nx = np.arange(0.001, 1.0, 0.001)\r\ny = np.log(x)\r\n\r\n# plt.plot(x, y)\r\n# plt.ylim(-5.0, 0.0) # y축의 범위 지정\r\n# plt.show()\r\n\r\ndef cross_entropy_error(y,t):\r\n    delta = 1e-7\r\n    return -np.sum(t * np.log(y + delta)) # 아주 작은 값 delta를 더하는 이유 : np.log에 함수 0을 입력하면 -inf(무한)가 되어 계산 x\r\n\r\nt = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]\r\ny = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0]\r\n\r\n# print(cross_entropy_error(np.array(y), np.array(t)))\r\n\r\ny = [0.1, 0.05, 0.1, 0.0, 0.05, 0.1, 0.0, 0.6, 0.0, 0.0]\r\n# print(cross_entropy_error(np.array(y), np.array(t)))\r\n\r\n# 미니 배치 학습\r\n\r\nimport sys, os\r\nsys.path.append(os.pardir)\r\nfrom dataset.mnist import load_mnist\r\n\r\n(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)\r\n\r\nprint(x_train.shape)\r\nprint(t_train.shape)\r\n\r\ntrain_size = x_train.shape[0]\r\nbatch_size = 10\r\nbatch_mask = np.random.choice(train_size, batch_size)\r\n# 훈련 데이터에서 무작위로 10장만 꺼내기? np.random.choice() 사용\r\n# np.random.choice(60000,10)은 0에서 60000 미만의 수 중 무작위로 10개를 골라냄\r\nx_batch = x_train[batch_mask]\r\nt_batch = t_train[batch_mask]\r\n\r\n# (배치용) 교차 엔트로피 오차 구현하기\r\ndef cross_entropy_error(y, t):\r\n    if y.ndim == 1:\r\n        t = t.reshape(1, t.size)\r\n        y = y.reshape(1, y.size)\r\n\r\n    batch_size = y.shape[0]\r\n    return -np.sum(t * np.log(y)) / batch_size\r\n\r\n", "meta": {"hexsha": "4d20925e71d462c5421ee45b4a4b0120db9ffbb1", "size": 1741, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch04/practice_4.py", "max_stars_repo_name": "jihyunis/-", "max_stars_repo_head_hexsha": "8575e74ced7842bc8ebf1af1b683a4976941cec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch04/practice_4.py", "max_issues_repo_name": "jihyunis/-", "max_issues_repo_head_hexsha": "8575e74ced7842bc8ebf1af1b683a4976941cec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch04/practice_4.py", "max_forks_repo_name": "jihyunis/-", "max_forks_repo_head_hexsha": "8575e74ced7842bc8ebf1af1b683a4976941cec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.203125, "max_line_length": 105, "alphanum_fraction": 0.6059735784, "include": true, "reason": "import numpy", "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122732859021, "lm_q2_score": 0.8947894703109853, "lm_q1q2_score": 0.8571298156178841}}
{"text": "###\n# Introduction to Data Science Homework Assignment # 1\n# Student: Alan Fernandez, aefernandez@wpi.edu\n# Date: 08/29/18\n# Course: DS501, Introduction to Data Science (Grad Level)\n# Worcester Polytechnic Institute (WPI), Worcester, MA\n###\n\nimport numpy as np\n\nfrom problem3 import random_walk\nfrom problem4 import compute_S\n\n#-------------------------------------------------------------------------\n'''\n    Problem 5: Solving sink-region problem in PageRank\n    In this problem, we implement the pagerank algorithm which can solve both the sink node problem and sink region problem.\n    We will consider a random surfer model where a user has 2 options at every timestep: (option 1) randomly follow a link on the page or (option 2) randomly go to any page in the graph. \n    The probabilities are as follows:\n        Randomly follow a link: alpha, for example, 0.95\n        Randomly go to any page in the graph: (1 - alpha), for example, 0.05\n    You could test the correctness of your code by typing `nosetests test5.py` in the terminal.\n'''\n\n#--------------------------\ndef compute_G(A, alpha = 0.95):\n    '''\n        compute the pagerank transition Matrix G from addjacency matrix A, which solves both the sink node problem and the sing region problem.\n        G[j][i] represents the probability of moving from node i to node j.\n        If node i is a sink node, S[j][i] = 1/n.\n        Input: \n                A: adjacency matrix, a (n by n) numpy matrix of binary values. If there is a link from node i to node j, A[j][i] =1. Otherwise A[j][i]=0 if there is no link.\n                alpha: a float scalar value, which is the probability of choosing option 1 (randomly follow a link on the page)\n        Output: \n                G: the transition matrix, a (n by n) numpy matrix of float values.  G[j][i] represents the probability of moving from node i to node j.\n    The values in each column of matrix G should sum to 1.\n    '''\n    #########################################\n    ## INSERT YOUR CODE HERE\n    # Generate the new matrix with equal probabilities for every node\n    n = A.shape[0]\n\n    equal_probability_matrix = np.zeros(list(A.shape))\n    equal_probability_matrix.fill(1/n)\n\n    # Compute the transitional matrix with the sink node problem solved\n    S = compute_S(A)\n\n    # Combine the two matrices to form the final transitional matrix\n    G = equal_probability_matrix * (1-alpha) + S * alpha\n\n    #########################################\n    return G\n\n\n\n#--------------------------\ndef pagerank(A, alpha = 0.95):\n    ''' \n        The final PageRank algorithm, which solves both the sink node problem and sink region problem.\n        Given an adjacency matrix A, compute the pagerank score of all the nodes in the network. \n        Input: \n                A: adjacency matrix, a numpy matrix of binary values. If there is a link from node i to node j, A[j][i] =1. Otherwise A[j][i]=0 if there is no link.\n                alpha: a float scalar value, which is the probability of choosing option 1 (randomly follow a link on the page)\n        Output: \n                x: the ranking scores, a numpy vector of float values, such as np.array([[.3], [.5], [.7]])\n    '''\n    \n    # Initialize the score vector with all one values\n    num_nodes, _ = A.shape # get the number of nodes (n)\n    x_0 =  np.ones((num_nodes,1)) # create an all-one vector of shape (n by 1)\n\n    # compute the transition matrix from adjacency matrix\n    G = compute_G(A, alpha)\n\n    # random walk\n    x, n_steps = random_walk(G,x_0)\n    return x\n\n\n", "meta": {"hexsha": "c70a1c2b73c7d4c16d6b069838ef4bd0c88f9ca5", "size": 3544, "ext": "py", "lang": "Python", "max_stars_repo_path": "Homework_1/problem5.py", "max_stars_repo_name": "aefernandez/DS501", "max_stars_repo_head_hexsha": "15799c8690c2f934d8e710db060e2b9e1b6afc8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homework_1/problem5.py", "max_issues_repo_name": "aefernandez/DS501", "max_issues_repo_head_hexsha": "15799c8690c2f934d8e710db060e2b9e1b6afc8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homework_1/problem5.py", "max_forks_repo_name": "aefernandez/DS501", "max_forks_repo_head_hexsha": "15799c8690c2f934d8e710db060e2b9e1b6afc8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7530864198, "max_line_length": 187, "alphanum_fraction": 0.6337471783, "include": true, "reason": "import numpy", "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957912273285902, "lm_q2_score": 0.8947894668039496, "lm_q1q2_score": 0.8571298122584514}}
{"text": "import numpy\nfrom matplotlib import pyplot\n\ndef euler_pc(f, x_end, y0, N):\n    x, dx = numpy.linspace(0, x_end, N+1, retstep=True)\n    y = numpy.zeros((len(y0),N+1))\n    y[:,0] = y0\n    for n in range(N):\n        fn = f(x[n], y[:,n])\n        yp = y[:,n] + dx * fn\n        y[:,n+1] = y[:,n] + dx / 2 * (fn + f(x[n+1], yp))\n    return x, dx, y\n\ndef ab2(f, x_end, y0, N):\n    x, dx = numpy.linspace(0, x_end, N+1, retstep=True)\n    y = numpy.zeros((len(y0),N+1))\n    fn = numpy.zeros((len(y0),N+1))\n    y[:,0] = y0\n    fn[:,0] = f(x[0], y[:,0])\n    x_epc, dx_epc, y_epc = euler_pc(f, dx, y0, 1)\n    y[:,1] = y_epc[:,1]\n    for n in range(1,N):\n        fn[:,n] = f(x[n], y[:,n])\n        y[:,n+1] = y[:,n] + dx * (3 * fn[:,n] - fn[:,n-1]) / 2\n    return x, dx, y\n\ndef milne(f, x_end, y0, N):\n    x, dx = numpy.linspace(0, x_end, N+1, retstep=True)\n    y = numpy.zeros((len(y0),N+1))\n    fn = numpy.zeros((len(y0),N+1))\n    y[:,0] = y0\n    fn[:,0] = f(x[0], y[:,0])\n    x_epc, dx_epc, y_epc = euler_pc(f, dx, y0, 1)\n    y[:,1] = y_epc[:,1]\n    for n in range(1,N):\n        fn[:,n] = f(x[n], y[:,n])\n        yp = y[:,n] + dx * (3 * fn[:,n] - fn[:,n-1]) / 2 #AB2 predictor\n        fp = f(x[n+1], yp)\n        y[:,n+1] = y[:,n-1] + dx * (fp + 4 * fn[:,n] + fn[:,n-1]) / 3\n    return x, dx, y\n\nif __name__==\"__main__\":\n\n    def f_exp(x, y):\n        return -y\n    \n    x, dx, y_ab2 = ab2(f_exp, 30, [1], 3000)\n    pyplot.figure(figsize=(12,6))\n    pyplot.plot(x, y_ab2[0,:])\n    pyplot.ylim(-1.1,1.1)\n    pyplot.xlabel(r\"$x$\")\n    pyplot.ylabel(\"Adams-Bashforth 2\")\n    pyplot.show()\n    \n    x, dx, y_milne = milne(f_exp, 30, [1], 3000)\n    pyplot.figure(figsize=(12,6))\n    pyplot.plot(x, y_milne[0,:])\n    pyplot.ylim(-1.1,1.1)\n    pyplot.xlabel(r\"$x$\")\n    pyplot.ylabel(\"Milne\")\n    pyplot.show()\n    ", "meta": {"hexsha": "24a4f30c4d8fd41e22c58e5cd4921c6ded8fb485", "size": 1794, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/tex/codes/lecture18.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Lectures/tex/codes/lecture18.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Lectures/tex/codes/lecture18.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 28.935483871, "max_line_length": 71, "alphanum_fraction": 0.4793756968, "include": true, "reason": "import numpy", "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122732859021, "lm_q2_score": 0.8947894632969137, "lm_q1q2_score": 0.8571298088990188}}
{"text": "import matplotlib\nmatplotlib.rcParams = matplotlib.rc_params_from_file('../../../matplotlibrc')\n\nimport numpy as np\nimport numpy.linalg as la\nfrom matplotlib import pyplot as plt\n\n\ndef mc_circle():\n    np.random.seed(42)\n    points = np.random.rand(2, 500).T\n    points = 4*(points-.5)\n    pointsNorm = np.hypot(points[:,0],points[:,1]) <= 1\n    InCircle = points[pointsNorm]\n    OutCircle = points[~pointsNorm]\n    plt.plot(InCircle[:,0], InCircle[:,1], 'r.')\n    plt.plot(OutCircle[:,0], OutCircle[:,1], 'b.')\n\n    # Plot the circle\n    theta = np.linspace(0, 2*np.pi, 50)\n    plt.plot(np.cos(theta),np.sin(theta),'k')\n\n    plt.axes().set_aspect('equal')\n    plt.axis([-2, 2, -2, 2])\n\n    plt.savefig(\"figures/MC_Circle.pdf\")\n    plt.clf()\n\ndef prob1(N=10000):\n    \"\"\"Return an estimate of the volume of the unit sphere using Monte\n    Carlo Integration.\n\n    Input:\n        N (int, optional) - The number of points to sample. Defaults\n            to 10000.\n\n    \"\"\"\n    points = np.random.rand(3, N)\n    points = points*2 - 1\n    radiusMask = la.norm(points,axis=0)\n    radiusMask[radiusMask>1] = 0\n    numInSphere = np.count_nonzero(radiusMask)\n    return 8.*numInSphere/N\n\ndef mc_error_plot(numIters=50):\n    actual = 4.1887902047863905\n\n    N = [i*1000 for i in xrange(1,51)]\n    N = [50,100,500] + N\n    errors = []\n\n    for n in N:\n        meanErr = 0.\n        for i in xrange(numIters):\n            I = prob1(n)\n            err = np.abs(I - actual)/actual\n            meanErr += err\n        errors.append(meanErr/float(numIters))\n\n    plt.plot(N,errors,label='Error')\n    plt.plot(N,[1./n**0.5 for n in N],'r--',label=r'$1/\\sqrt{N}$')\n    plt.ylim([0,max(errors)])\n    plt.xlim([0,max(N)])\n    plt.xlabel(r'$N$')\n    plt.ylabel('Relative error')\n    plt.legend()\n\n    plt.savefig(\"figures/MC_error_2.pdf\")\n    plt.clf()\n\n\nif __name__ == \"__main__\":\n    #mc_circle()\n    mc_error_plot()\n", "meta": {"hexsha": "8da1b67e178418ce42639d99e7767b4927f55070", "size": 1895, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol1B/MonteCarlo1-Integration/plots.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vol1B/MonteCarlo1-Integration/plots.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vol1B/MonteCarlo1-Integration/plots.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 25.2666666667, "max_line_length": 77, "alphanum_fraction": 0.6031662269, "include": true, "reason": "import numpy", "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.9343951675649261, "lm_q1q2_score": 0.8571231786486787}}
{"text": "import numpy as np\nfrom sympy import *\nimport matplotlib.pyplot as plt\nimport time\n\ndef actual_result(func, val):\n\tx = Symbol('x')\n\tdfunc = diff(func, 'x')\n\tx = val\n\treturn eval(str(dfunc))\n\ndef two_point(func, x, h):\n\tfuncx = eval(str(func))\n\tx = x+h\n\tfuncxh = eval(str(func))\n\treturn (funcxh - funcx)/h\n\ndef three_point(func, x, h):\n\tx = x+h\n\tfuncxh = eval(str(func))\n\tx = x-2*h\n\tfuncxmh = eval(str(func))\n\treturn (funcxh - funcxmh)/(2*h)\n\ndef plot(Result2Point,Result3Point,Error2Point,Error3Point):\n\tplt.plot(Result2Point, 'k--',label= \"2 Point\")\n\tplt.plot(Result3Point,'k:',label= \"3 Point\")\n\tplt.plot(Error2Point,'k',label= \"2 Point Error\")\n\tplt.plot(Error3Point,'k',label= \"3 Point Error\")\n\n\tlegend = plt.legend(loc='upper center', shadow=True)\n\tframe = legend.get_frame()\n\tframe.set_facecolor('0.90')\n\n\tplt.show()\n\ndef differenceMethods(x,y,z):\n\treturn 0\n\ndef main():\n\tx = Symbol('x')\n\tResult2Point= []\n\tResult3Point= []\n\tError2Point = []\n\tError3Point = []\n\n\t## User input \n\tfunc = sin(x)\n\txval = 0.0\n\th=[0.1,0.01,0.001]\n\n\tstart = time.time()\n\tactualResult = actual_result(func, xval)\n\tfor item in h:\n\t\tResult2Point.append(two_point(func, xval, item))\n\t\tResult3Point.append(three_point(func, xval, item))\n\n\tError2Point = np.asarray(Result2Point) - actualResult\n\tError3Point = np.asarray(Result3Point) - actualResult\n\n\tend = time.time()\n\ttimeElapsed = end-start\n\tprint (\"Elapsed time: %f\" % timeElapsed)\n\n\n\tplot(Result2Point, Result3Point, Error2Point, Error3Point)\n\t\n\t\n\t#print actual_result(func, xval)\n\nif __name__ =='__main__':\n\tmain()\n\t\n", "meta": {"hexsha": "f9f2c0af924aeb275cca91c0e617efa512a5d3dc", "size": 1548, "ext": "py", "lang": "Python", "max_stars_repo_path": "differencemethods.py", "max_stars_repo_name": "nguyenvu2589/Numerical", "max_stars_repo_head_hexsha": "23eee7d31a8871d5d53871ebc9950866cf11ad23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "differencemethods.py", "max_issues_repo_name": "nguyenvu2589/Numerical", "max_issues_repo_head_hexsha": "23eee7d31a8871d5d53871ebc9950866cf11ad23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "differencemethods.py", "max_forks_repo_name": "nguyenvu2589/Numerical", "max_forks_repo_head_hexsha": "23eee7d31a8871d5d53871ebc9950866cf11ad23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9189189189, "max_line_length": 60, "alphanum_fraction": 0.6879844961, "include": true, "reason": "import numpy,from sympy", "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.9173026624116694, "lm_q1q2_score": 0.8571231703433803}}
{"text": "# pylint: disable=invalid-name\n\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\n# CUSTOMIZABLE: Collect/Prepare data\ndatapoint_size = 1000\nbatch_size = 1000\nsteps = 10000\nactual_W1 = 2\nactual_W2 = 5\nactual_b = 7\nlearn_rate = 0.001\nlog_file = \"logs/feature_2\"\n\n# Model linear regression y = Wx + b\nx = tf.placeholder(tf.float32, [None, 2], name=\"x\")\nW = tf.Variable(tf.zeros([2, 1]), name=\"W\")\nb = tf.Variable(tf.zeros([1]), name=\"b\")\nwith tf.name_scope(\"Wx_b\") as scope:\n    product = tf.matmul(x, W)\n    y = product + b\n\n# Add summary ops to collect data\nW_hist = tf.summary.histogram(\"weights\", W)\nb_hist = tf.summary.histogram(\"biases\", b)\ny_hist = tf.summary.histogram(\"y\", y)\n\ny_ = tf.placeholder(tf.float32, [None, 1])\n\n# Cost function sum((y_-y)**2)\nwith tf.name_scope(\"cost\") as scope:\n    cost = tf.reduce_mean(tf.square(y_ - y))\n    cost_sum = tf.summary.scalar(\"cost\", cost)\n\n# Training using Gradient Descent to minimize cost\nwith tf.name_scope(\"train\") as scope:\n    train_step = tf.train.GradientDescentOptimizer(learn_rate).minimize(cost)\n\nall_xs = []\nall_ys = []\nfor i in range(datapoint_size):\n    # Create fake data for y = 2.x_1 + 5.x_2 + 7\n    x_1 = i % 10\n    x_2 = np.random.randint(datapoint_size / 2) % 10\n    y = actual_W1 * x_1 + actual_W2 * x_2 + actual_b\n    # Create fake data for y = W.x + b where W = [2, 5], b = 7\n    all_xs.append([x_1, x_2])\n    all_ys.append(y)\n\nall_xs = np.array(all_xs)\nall_ys = np.transpose([all_ys])\n\nsess = tf.Session()\n\n# Merge all the summaries and write them out to logs\nmerged = tf.summary.merge_all()\nwriter = tf.summary.FileWriter(log_file, sess.graph)\n\ninit = tf.init = tf.global_variables_initializer()\nsess.run(init)\n\nfor i in range(steps):\n    if datapoint_size == batch_size:\n        batch_start_idx = 0\n    elif datapoint_size < batch_size:\n        raise ValueError(\"datapoint_size: %d, must be greater than batch_size: %d\" % (\n            datapoint_size, batch_size))\n    else:\n        batch_start_idx = (i * batch_size) % (datapoint_size - batch_size)\n\n    batch_end_idx = batch_start_idx + batch_size\n    batch_xs = all_xs[batch_start_idx:batch_end_idx]\n    batch_ys = all_ys[batch_start_idx:batch_end_idx]\n    xs = np.array(batch_xs)\n    ys = np.array(batch_ys)\n    all_feed = {x: all_xs, y_: all_ys}\n\n    # Record summary data, and the accuracy every 10 steps\n    if i % 10 == 0:\n        result = sess.run(merged, feed_dict=all_feed)\n        writer.add_summary(result, i)\n    else:\n        feed = {x: xs, y_: ys}\n        sess.run(train_step, feed_dict=feed)\n    print(\"After %d iteration:\" % i)\n    print(\"W: %s\" % sess.run(W))\n    print(\"b: %f\" % sess.run(b))\n    print(\"cost: %f\" % sess.run(cost, feed_dict=all_feed))\n\n# close the writer when you're done using it\nwriter.flush()\nwriter.close()\n\n# Step 9: output the values of w and b\nw_value, b_value = sess.run([W, b])\n\n# NOTE: W should be close to actual_W1, actual_W2, and b should be close\n# to actual_b\n# NOTE: Run tensorboard --logdir=path/to/log-directory to visualize\n", "meta": {"hexsha": "8b66f3bc26bc880e64e587bf1d1392a1306d0a16", "size": 3030, "ext": "py", "lang": "Python", "max_stars_repo_path": "hello_world/linear_regression_multi_feature.py", "max_stars_repo_name": "shanaka-desoysa/tensorflow", "max_stars_repo_head_hexsha": "0effc668f42b64bd0712240ab2f5e8a8be42960f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hello_world/linear_regression_multi_feature.py", "max_issues_repo_name": "shanaka-desoysa/tensorflow", "max_issues_repo_head_hexsha": "0effc668f42b64bd0712240ab2f5e8a8be42960f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hello_world/linear_regression_multi_feature.py", "max_forks_repo_name": "shanaka-desoysa/tensorflow", "max_forks_repo_head_hexsha": "0effc668f42b64bd0712240ab2f5e8a8be42960f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7058823529, "max_line_length": 86, "alphanum_fraction": 0.6749174917, "include": true, "reason": "import numpy", "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464602, "lm_q2_score": 0.8991213725394589, "lm_q1q2_score": 0.857109962414181}}
{"text": "from numpy import quantile, corrcoef\nfrom numpy.random import seed, normal\n\n# Correlation arising from selection (see start of Chapter 6).\nseed(5)\nN = 200  # The number of grant proposals.\nP = 0.1  # The proportion of proposals that get accepted.\nnews = normal(size=N)\ntrust = normal(size=N)\n# Simulate the selection process by finding the top 10% of combined scores.\nscore = news + trust\naccepted_score = quantile(score, 1 - P)\nselected = score >= accepted_score\n# Find that the correlation coefficient of truly uncorrelated values now ...\ncorrelation_coef = corrcoef(news[selected], trust[selected])\nrounded_correlation_coef = round(correlation_coef[0][1], 2)\nprint(f\"The apparent correlation is {rounded_correlation_coef}.\")\n", "meta": {"hexsha": "1b2705c736ba6ece95389919fa75ac5146d4f436", "size": 728, "ext": "py", "lang": "Python", "max_stars_repo_path": "grant_correlation/grant_correlation.py", "max_stars_repo_name": "minster-hatter/stats-rethink", "max_stars_repo_head_hexsha": "afd2c1a53d87b124598dc873805f85f48ac2d536", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grant_correlation/grant_correlation.py", "max_issues_repo_name": "minster-hatter/stats-rethink", "max_issues_repo_head_hexsha": "afd2c1a53d87b124598dc873805f85f48ac2d536", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grant_correlation/grant_correlation.py", "max_forks_repo_name": "minster-hatter/stats-rethink", "max_forks_repo_head_hexsha": "afd2c1a53d87b124598dc873805f85f48ac2d536", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4444444444, "max_line_length": 76, "alphanum_fraction": 0.7692307692, "include": true, "reason": "from numpy", "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9805806557900713, "lm_q2_score": 0.8740772450055545, "lm_q1q2_score": 0.8571032381187255}}
{"text": "# plots.py\nimport matplotlib\nmatplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc')\n\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom scipy import linalg as la\nfrom scipy import optimize as opt\n\ndef newtonsMethod1d(f, df, ddf, x, niter=10):   # Keep!\n    '''\n    Perform Newton's method to minimize a function from R to R.\n    Inputs:\n        f -- objective function (twice differentiable)\n        df -- first derivative\n        ddf -- second derivative\n        x -- initial guess\n        niter -- integer, giving the number of iterations\n    Returns:\n        the approximated minimizer\n    '''\n    for i in xrange(niter):\n        x = x-df(x)/ddf(x)\n    return x, f(x)\n\ndef myFunc(x):   # Keep!\n    return 4*x**2 - 13*x + 40 + 6*np.sin(4*x)\ndef myDFunc(x):   # Keep!\n    return 8*x - 13+24*np.cos(4*x)\ndef myDDFunc(x):   # Keep!\n    return 8-96*np.sin(4*x)\n\ndef newton():  # Keep!\n    x1,f1 = newtonsMethod1d(myFunc, myDFunc, myDDFunc, 1, niter=200)\n    x2,f2 = newtonsMethod1d(myFunc, myDFunc, myDDFunc, 4, niter=200)\n    dom = np.linspace(-10,10,100)\n    plt.plot(dom, myFunc(dom))\n    plt.plot(x1, f1, '*')\n    plt.plot(x2, f2, '*')\n    plt.annotate('Global Minimum', xy=(x1, f1), xytext=(-4, 200),\n                arrowprops=dict(facecolor='black', shrink=0.1),)\n    plt.annotate('Local Minimum', xy=(x2,f2), xytext=(2, 175),\n                    arrowprops=dict(facecolor='black', shrink=0.1),)\n    plt.savefig('newton.pdf')\n    plt.clf()\n\nnewton()\n", "meta": {"hexsha": "da87687f9a152fb4a3e5a910f729cff76d38184c", "size": 1485, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol2B/1-d_Optimization/plots.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vol2B/1-d_Optimization/plots.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vol2B/1-d_Optimization/plots.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9375, "max_line_length": 74, "alphanum_fraction": 0.6175084175, "include": true, "reason": "import numpy,from scipy", "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.8902942283051332, "lm_q1q2_score": 0.8570623149886387}}
{"text": "import numpy as np\n\n\n# This file contains the suggested examples from Section 9.3.2\n# they all assume the input x is of the correct dimension, and a column vector\n\ndef obj_quadratic_r2(x, gamma=2):\n    \"\"\" This is the objective function:\n    f(x) = 1/2 * (x_1^2 + gamma*x_2^2)\n\n    Args:\n        x: input, a 2x1 numpy array\n        gamma: defaults to 2, can be used to control the condition number of\n            the sublevel sets of the function.\n            condition number = max(gamma, 1/gamma)\n    \"\"\"\n    _A = np.array(\n        [[1, 0],\n         [0, gamma]], dtype=float\n    )\n    return 0.5 * x.T @ _A @ x\n\n\ndef obj_quadratic_r2_jac(x, gamma=2):\n    \"\"\" This is the objective function:\n    f(x) = 1/2 * (x_1^2 + gamma*x_2^2)\n\n    Args:\n        x: input, a 2x1 numpy array\n        gamma: defaults to 2, can be used to control the condition number of\n            the sublevel sets of the function.\n            condition number = max(gamma, 1/gamma)\n    \"\"\"\n    _A = np.array(\n        [[1, 0],\n         [0, gamma]], dtype=float\n    )\n    return _A @ x\n\n\ndef obj_nonquadratic_r2(x):\n    \"\"\" This is the objective function:\n    f(x) = exp(x_1 + 3x_2 - 0.1) + exp(x_1 - 3x_2 - 0.1) + exp(-x_1 - 0.1)\n\n    Args:\n        x: input, a 2x1 numpy array. Recommend keeping inputs reasonably small.\n    \"\"\"\n    x1, x2 = x.flatten()\n    return np.exp(x1+3*x2-0.1) + np.exp(x1-3*x2-0.1) + np.exp(-x1-0.1)\n", "meta": {"hexsha": "9192cf4937c98e3aac2db811a32883d350c9d965", "size": 1396, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/examples_9_3_2.py", "max_stars_repo_name": "bbaudry/optimisation", "max_stars_repo_head_hexsha": "24faf6f81fff29dfd9a856bdfaeee6d592038765", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-16T15:49:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T15:49:55.000Z", "max_issues_repo_path": "examples/examples_9_3_2.py", "max_issues_repo_name": "bbaudry/optimisation", "max_issues_repo_head_hexsha": "24faf6f81fff29dfd9a856bdfaeee6d592038765", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-18T09:53:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-19T08:55:20.000Z", "max_forks_repo_path": "examples/examples_9_3_2.py", "max_forks_repo_name": "bbaudry/optimisation", "max_forks_repo_head_hexsha": "24faf6f81fff29dfd9a856bdfaeee6d592038765", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-15T10:13:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T10:13:36.000Z", "avg_line_length": 27.92, "max_line_length": 79, "alphanum_fraction": 0.579512894, "include": true, "reason": "import numpy", "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.89029422102812, "lm_q1q2_score": 0.8570623089366738}}
{"text": "import numpy as np\n\n\nclass Distance:\n\n    @staticmethod\n    def euclidian_distance(item_1, item_2):\n        return np.sqrt(np.sum((item_1 - item_2) ** 2))\n\n    @staticmethod\n    def hamming_distance(item_1, item_2):\n        return np.sum(np.abs(item_1 - item_2))/len(item_1)\n\n    @staticmethod\n    def manhattan_distance(item_1, item_2):\n        return np.sum(np.abs(item_1 - item_2))\n\n    @staticmethod\n    def minkowski_distance(item_1, item_2, p):\n        return np.sum((item_1 - item_2) ** p)**(1/p)\n", "meta": {"hexsha": "5e34fa440ab11dfb2ae15244496b2bad6e7bc6d5", "size": 504, "ext": "py", "lang": "Python", "max_stars_repo_path": "helper/distance.py", "max_stars_repo_name": "aldeebhasan/metaheurestic_learn", "max_stars_repo_head_hexsha": "862b31b82a61b957eef8133f40f25fb46e91c613", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "helper/distance.py", "max_issues_repo_name": "aldeebhasan/metaheurestic_learn", "max_issues_repo_head_hexsha": "862b31b82a61b957eef8133f40f25fb46e91c613", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "helper/distance.py", "max_forks_repo_name": "aldeebhasan/metaheurestic_learn", "max_forks_repo_head_hexsha": "862b31b82a61b957eef8133f40f25fb46e91c613", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0, "max_line_length": 58, "alphanum_fraction": 0.6507936508, "include": true, "reason": "import numpy", "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214460461697, "lm_q2_score": 0.8887587868629345, "lm_q1q2_score": 0.8570491585339045}}
{"text": "from scipy.integrate import simps\r\nfrom scipy.integrate import trapz\r\nfrom scipy.integrate import romb\r\nimport numpy as np\r\n\r\ndef f(x):\r\n    \"\"\"\r\n    \"\"\"\r\n    return 1\r\n\r\ndef g(x):\r\n    \"\"\"\r\n    Function taken from https://www.math.duke.edu/vigre/pruv/studentwork/atwood.nearsing.pdf\r\n    \"\"\"\r\n\r\n    a = 10e-3\r\n\r\n    return f(x)* np.log(x**2 + a**2)\r\n\r\ndef simpson(f, a, b, n):\r\n    \"\"\"\r\n    Simpson composite rule\r\n    \"\"\"\r\n    h=(b-a)/n\r\n    k=0.0\r\n    x=a + h\r\n    for i in range(1,n/2 + 1):\r\n        k += 4.*f(x)\r\n        x += 2.*h\r\n\r\n    x = a + 2.*h\r\n    for i in range(1,n/2):\r\n        k += 2.*f(x)\r\n        x += 2.*h\r\n    return (h/3.)*(f(a)+f(b)+k)\r\n\r\n\r\n\r\n# Computing integral using less interval\r\n# Correct answer is -3.99372\r\n\r\nI = -3.99372\r\n\r\ni1 = simpson(g, -1., 1., 2**5+ 1)\r\n\r\ni2 = simpson(g, -1., 1., 2**10+1)\r\n\r\n\r\nprint 'Reference answer is ' + str(I)\r\nprint 'Previous code answer is ' + str(i1)\r\n\r\nprint 'Current code answer is ' + str(i2)\r\n\r\nprint 'Previous code absolute error is ' + str(np.abs(I-i1))\r\n\r\nprint 'Current code absolute error is ' + str(np.abs(I-i2))\r\n\r\n\r\n", "meta": {"hexsha": "de46824ef9f5ced8a567c16a00e0e4e3609db4f6", "size": 1090, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/NemohImproved/test/simpson.py", "max_stars_repo_name": "NREL/OpenWARP", "max_stars_repo_head_hexsha": "ca49c4cbde17e0cead69bd9e55a81d5c0fafe4df", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2015-06-22T07:35:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T05:10:09.000Z", "max_issues_repo_path": "source/NemohImproved/test/simpson.py", "max_issues_repo_name": "rhydar/Test", "max_issues_repo_head_hexsha": "32dd54af2c3657d0c49177395d5b1c1f7bd8e127", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2015-07-30T20:01:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-28T17:29:18.000Z", "max_forks_repo_path": "source/NemohImproved/test/simpson.py", "max_forks_repo_name": "rhydar/Test", "max_forks_repo_head_hexsha": "32dd54af2c3657d0c49177395d5b1c1f7bd8e127", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2016-04-01T07:45:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-06T08:33:33.000Z", "avg_line_length": 18.4745762712, "max_line_length": 93, "alphanum_fraction": 0.5321100917, "include": true, "reason": "import numpy,from scipy", "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096791, "lm_q2_score": 0.9046505370289059, "lm_q1q2_score": 0.8570487672490149}}
{"text": "#%%\n'''\nreproduction of https://ipython-books.github.io/134-simulating-a-stochastic-differential-equation/\n\nStochastic differential equations (SDEs) model dynamical systems that are subject to noise. \nIn this recipe, we simulate an Ornstein-Uhlenbeck process, which is a solution of the Langevin equation. \nThe Ornstein-Uhlenbeck process is stationary, Gaussian, and Markov, which makes it a good candidate to represent stationary random noise.\nWe will simulate this process with a numerical method called the Euler-Maruyama method. \n'''\n#%%\nimport numpy as np\nimport matplotlib.pyplot as plt\n#%%\nb = 0.5\nsigma = 1.\n#%%\ndt = .001  # Time step.\nT = 1.  # Total time.\nn = int(T / dt)  # Number of time steps.\nt = np.linspace(0., T, n)  # Vector of times.\n#%%\nx = np.zeros(n)\n#%%\n'''\ndiscretized stochastic differential equation and process\nx_{t+1} = x_t + (-b * x_t) * dt + sigma * (dt)^1/2 * N(0, 1)\n\nwhere \nb = 1/2, sigma = 1\nx_{t+1} = x_t + (-1/2 * x_t) * dt + 1 * (dt)^1/2 * N(0, 1)\nand (-1/2 * x_t) = score function of N(0, 1)\nand distribution of x_T converges to N(0, \\sigma^2 / 2b) = N(0, 1)\n'''\nfor i in range(n - 1):\n    x[i + 1] = x[i] + (-b * x[i]) * dt + sigma * np.sqrt(dt) * np.random.randn()\n#%%\nfig, ax = plt.subplots(1, 1, figsize=(8, 4))\nax.plot(t, x, lw=2)\nax.set_title('simulation of langevin equation')\n#%%\nntrials = 10000\nX = np.zeros(ntrials)\n# We create bins for the histograms.\nbins = np.linspace(-3., 3., 100)\nfig, ax = plt.subplots(1, 1, figsize=(8, 4))\nfor i in range(n):\n    # We update the process independently for all trials\n    X += (-b * X) * dt + sigma * np.sqrt(dt) * np.random.randn(ntrials)\n    # We display the histogram for a few points in time (10000 points of process)\n    if i in (5, 50, 900):\n        hist, _ = np.histogram(X, bins=bins, density=True)\n        ax.plot((bins[1:] + bins[:-1]) / 2, hist,\n                {5: '-', 50: '-.', 900: '--', }[i],\n                label=f\"t={i * dt:.2f}\")\nhist, _ = np.histogram(np.random.randn(X.shape[0]), bins=bins, density=True)\nax.plot((bins[1:] + bins[:-1]) / 2, hist, ':', label='N(0,1)')\nax.legend()\n#%%\n# '''\n# numerical solution\n# '''\n# np.random.seed(520)\n# ntrials = 10000\n# # true\n# X = np.zeros(ntrials)\n# fig, ax = plt.subplots(1, 1, figsize=(8, 4))\n# for i in range(n):\n#     X += (-b * X) * dt + sigma * np.sqrt(dt) * np.random.randn(ntrials)\n# hist, _ = np.histogram(np.random.randn(X.shape[0]), density=True)\n# ax.plot(hist, '-.', label='N(0,1)')\n\n# # solution\n# X0 = np.random.normal(0, 1, (ntrials, ))\n# X = np.exp(-b * T) * X0 + np.sum(sigma * np.exp(-b * (T - dt)) * np.random.normal(0, dt, (ntrials, ntrials)), axis=1)\n# hist, _ = np.histogram(X, density=True)\n# ax.plot(hist, '-', label='solution')\n# ax.legend()\n#%%\n'''\nThe error of the Euler-Maruyama method is of order sqrt(dt). The Milstein method is a more precise numerical scheme, of order dt.\n'''\n#%%", "meta": {"hexsha": "0a4e4b65963889775c7cb54bc9132c81c75c8631", "size": 2864, "ext": "py", "lang": "Python", "max_stars_repo_path": "ncsn/src/sde_example.py", "max_stars_repo_name": "an-seunghwan/generative", "max_stars_repo_head_hexsha": "edba5999677e80178f0a3ecd091f1800396ebcef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-06-02T04:48:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T10:19:07.000Z", "max_issues_repo_path": "ncsn/src/sde_example.py", "max_issues_repo_name": "an-seunghwan/generative", "max_issues_repo_head_hexsha": "edba5999677e80178f0a3ecd091f1800396ebcef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ncsn/src/sde_example.py", "max_forks_repo_name": "an-seunghwan/generative", "max_forks_repo_head_hexsha": "edba5999677e80178f0a3ecd091f1800396ebcef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9268292683, "max_line_length": 137, "alphanum_fraction": 0.6187150838, "include": true, "reason": "import numpy", "num_tokens": 947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.9241418173671895, "lm_q1q2_score": 0.8570152013985822}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n# for math\nimport numpy as np\n# for physical cosntants\nimport scipy.constants as const\n# for plots\nimport matplotlib.pyplot as plt\n\n# charge settings\nN_1 = -1\nN_2 = 1\nN_3 = -1\nN_4 = 1\n\n# coulomb constant\nk_C = 1 / (4 * np.pi * const.epsilon_0)\n\n# charges\nq_1 = N_1 * const.e\nq_2 = N_2 * const.e\nq_3 = N_3 * const.e\nq_4 = N_4 * const.e\n\n\n# position of the charged points\nq_1_x = 0.5\nq_1_y = 0.5\nq_2_x = 0.5\nq_2_y = - 0.5\nq_3_x = -0.5\nq_3_y = -0.5\nq_4_x = -0.5\nq_4_y = 0.5\n\n\n\nprint('charges')\nprint('q_1 = ', q_1, 'x = ', q_1_x, 'y = ', q_1_y)\nprint('q_2 = ', q_2, 'x = ', q_2_x, 'y = ', q_2_y)\nprint('q_3 = ', q_3, 'x = ', q_3_x, 'y = ', q_3_y)\nprint('q_4 = ', q_4, 'x = ', q_4_x, 'y = ', q_4_y)\n\n\n\n\n# Meshgrid\nsize = 1\ns = (size / 2)\nn_s = 100\nx, y = np.meshgrid(np.linspace(-s, s, n_s), \n                   np.linspace(-s, s, n_s))\n\n# radius\nr_1 = np.sqrt((q_1_x - x)**2 + (q_1_y - y)**2)\nr_2 = np.sqrt((q_2_x - x)**2 + (q_2_y - y)**2)\nr_3 = np.sqrt((q_3_x - x)**2 + (q_3_y - y)**2)\nr_4 = np.sqrt((q_4_x - x)**2 + (q_4_y - y)**2)\n\n# helper varables\nk_1 = q_1 / (r_1*r_1*r_1)\nk_2 = q_2 / (r_2*r_2*r_2)\nk_3 = q_3 / (r_3*r_3*r_3)\nk_4 = q_4 / (r_4*r_4*r_4)\n\n\n# https://www.geeksforgeeks.org/how-to-plot-a-simple-vector-field-in-matplotlib/\n\n# Directional vectors\nE_x = k_C * (k_1 * (q_1_x - x) + k_2 * (q_2_x - x) + k_3 * (q_3_x - x) + k_4 * (q_4_x - x));\nE_y = k_C * (k_1 * (q_1_y - y) + k_2 * (q_2_y - y) + k_3 * (q_3_y - y) + k_4 * (q_4_y - y));\n  \n# Plotting Vector Field with QUIVER\nplt.quiver(x, y, E_x, E_y, color='g')\nplt.title('Vector Field')\n\n# Setting x, y boundary limits\nboundary = 1\nplt.xlim(-boundary, boundary)\nplt.ylim(-boundary, boundary)\n  \n# Show plot with gird\nplt.grid()\nplt.show()\n\n# Depict illustration\nplt.figure(figsize=(10, 10))\nplt.streamplot(x,y,E_x,E_y, density=1.4, linewidth=None, color='#A23BEC')\nplt.plot(q_1_x,q_1_y,'-or')\nplt.plot(q_2_x,q_2_y,'-og')\nplt.plot(q_3_x,q_3_y,'-ob')\nplt.plot(q_4_x,q_4_y,'-oc')\nplt.title('Electromagnetic Field')\n  \nboundary = 0.6\nplt.xlim(-boundary, boundary)\nplt.ylim(-boundary, boundary)\n\n# Show plot with gird\nplt.grid()\nplt.show()\n", "meta": {"hexsha": "782ade7beee99ad872b26aa15efee6ba66e7de90", "size": 2177, "ext": "py", "lang": "Python", "max_stars_repo_path": "electric_field_between_two_charged_points.py", "max_stars_repo_name": "polymurph/Electrical-Calculations", "max_stars_repo_head_hexsha": "d9685aeaa813b5da647479ede1e6b41d6185a68f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "electric_field_between_two_charged_points.py", "max_issues_repo_name": "polymurph/Electrical-Calculations", "max_issues_repo_head_hexsha": "d9685aeaa813b5da647479ede1e6b41d6185a68f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "electric_field_between_two_charged_points.py", "max_forks_repo_name": "polymurph/Electrical-Calculations", "max_forks_repo_head_hexsha": "d9685aeaa813b5da647479ede1e6b41d6185a68f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5377358491, "max_line_length": 92, "alphanum_fraction": 0.609095085, "include": true, "reason": "import numpy,import scipy", "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211634198561, "lm_q2_score": 0.8791467659263148, "lm_q1q2_score": 0.8570108731770941}}
{"text": "from math import factorial\n\nimport matplotlib.pylab as plt\nfrom numpy import ones, copy, cos, tan\nfrom numpy import sqrt, pi, exp, linspace, zeros\n\n\ndef gaussxw(N):\n    # Initial approximation to roots of the Legendre polynomial\n    a = linspace(3, 4 * N - 1, N) / (4 * N + 2)\n    x = cos(pi * a + 1 / (8 * N * N * tan(a)))\n\n    # Find roots using Newton's method\n    epsilon = 1e-15\n    delta = 1.0\n    while delta > epsilon:\n        p0 = ones(N, float)\n        p1 = copy(x)\n        for k in range(1, N):\n            p0, p1 = p1, ((2 * k + 1) * x * p1 - k * p0) / (k + 1)\n        dp = (N + 1) * (p0 - x * p1) / (1 - x * x)\n        dx = p1 / dp\n        x -= dx\n        delta = max(abs(dx))\n\n    # Calculate the weights\n    w = 2 * (N + 1) * (N + 1) / (N * N * (1 - x * x) * dp * dp)\n\n    return x, w\n\n\ndef gaussxwab(N, a, b):\n    x, w = gaussxw(N)\n    return 0.5 * (b - a) * x + 0.5 * (b + a), 0.5 * (b - a) * w\n\n\ndef H(n, x):\n    def H_iter(a, b, count):\n        if count == 0:\n            return b\n        else:\n            return H_iter(2 * x * a - 2 * (count - 1) * b, a, count - 1)\n\n    return H_iter(2 * x, 1, n)\n\n\ndef wave_func(n, x):\n    return (1 / (sqrt((2 ** n) * factorial(n) * sqrt(pi)))) * exp(-0.5 * (x ** 2)) * H(n, x)\n\n\nN = 200\nd = linspace(-4, 4, N)\ny = zeros([N, 4], float)\nfor j in range(0, 4, 1):\n    for i in range(0, N, 1):\n        y[i, j] = wave_func(j, d[i])\ny2 = []\nd2 = linspace(-10, 10, 500)\nfor m in range(0, 500, 1):\n    y2.append(wave_func(30, d2[m]))\nf1 = plt.figure(1)\nplt.plot(d2, y2, 'b-', label=r\"$\\psi_{30}$\", linewidth=1)\nplt.xlabel(\"x\")\nplt.ylabel(r\"$\\psi(x)$\")\nf2 = plt.figure(2)\nplt.plot(d, y[:, 0], label=r\"$\\psi_0$\")\nplt.plot(d, y[:, 1], label=r\"$\\psi_1$\")\nplt.plot(d, y[:, 2], label=r\"$\\psi_2$\")\nplt.plot(d, y[:, 3], label=r\"$\\psi_3$\")\nplt.xlabel(\"x\")\nplt.ylabel(r\"$\\psi(x)$\")\nplt.show()\n", "meta": {"hexsha": "4f97302750ebebe149b78c16c517c0b296a9ed67", "size": 1832, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ankit Khandelwal_HW2/exercise 5/exercise 5a.py", "max_stars_repo_name": "ankit27kh/Computational-Physics-PH354", "max_stars_repo_head_hexsha": "d37c93e430a0f282251a814456890acb4a2961fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ankit Khandelwal_HW2/exercise 5/exercise 5a.py", "max_issues_repo_name": "ankit27kh/Computational-Physics-PH354", "max_issues_repo_head_hexsha": "d37c93e430a0f282251a814456890acb4a2961fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ankit Khandelwal_HW2/exercise 5/exercise 5a.py", "max_forks_repo_name": "ankit27kh/Computational-Physics-PH354", "max_forks_repo_head_hexsha": "d37c93e430a0f282251a814456890acb4a2961fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.095890411, "max_line_length": 92, "alphanum_fraction": 0.4945414847, "include": true, "reason": "from numpy", "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692277960746, "lm_q2_score": 0.8774767970940975, "lm_q1q2_score": 0.857004585826865}}
{"text": "# Copyright 2017 Battelle Energy Alliance, LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# from https://en.wikipedia.org/wiki/Test_functions_for_optimization\n#\n# takes any number of input parameters x[i]\n# returns value in \"ans\"\n# optimal minimum at f(1,1,...,1,1) = 0, only minimum for up to 3 inputs\n# note for 4 to 7 inputs, a second local minima exists near (-1,1,...,1), and it gets complicated after that\n# parameter range is -inf <= x[i] <= inf\n\nimport numpy as np\n\ndef evaluate2d(X,Y):\n  return 100*(Y-X*X)**2 + (X-1)**2\n\ndef evaluate(*args):#xs):\n  xs = np.array(args)\n  return np.sum( 100.*(xs[1:] - xs[:-1]**2)**2 + (xs[:-1] - 1.)**2 )\n\ndef run(self,Inputs):\n  self.ans = evaluate(Inputs.values())\n\n", "meta": {"hexsha": "805ee9805e5843c2fde4fcfa631dac6a4a249c10", "size": 1210, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/framework/AnalyticModels/optimizing/rosenbrock.py", "max_stars_repo_name": "rinelson456/raven", "max_stars_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 159, "max_stars_repo_stars_event_min_datetime": "2017-03-24T21:07:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:44:40.000Z", "max_issues_repo_path": "tests/framework/AnalyticModels/optimizing/rosenbrock.py", "max_issues_repo_name": "rinelson456/raven", "max_issues_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1667, "max_issues_repo_issues_event_min_datetime": "2017-03-27T14:41:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:50:06.000Z", "max_forks_repo_path": "tests/framework/AnalyticModels/optimizing/rosenbrock.py", "max_forks_repo_name": "rinelson456/raven", "max_forks_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 95, "max_forks_repo_forks_event_min_datetime": "2017-03-24T21:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T17:30:22.000Z", "avg_line_length": 35.5882352941, "max_line_length": 108, "alphanum_fraction": 0.7074380165, "include": true, "reason": "import numpy", "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920617, "lm_q2_score": 0.8918110555020057, "lm_q1q2_score": 0.8569873573475801}}
{"text": "import numpy as np\nimport matplotlib.pyplot as pyplot\nimport scipy.spatial.distance as sd\nimport sys\nimport os\nimport copy\n\nsys.path.append(os.path.dirname(os.getcwd())+\"/code_material_python\")\nfrom helper import *\nfrom graph_construction.generate_data import *\n\n\ndef build_similarity_graph(X, var=1, eps=0, k=0):\n  \"\"\"     Computes the similarity matrix for a given dataset of samples.\n\n   Input\n   X:\n       (n x m) matrix of m-dimensional samples\n   k and eps:\n       controls the main parameter of the graph, the number\n       of neighbours k for k-nn, and the threshold eps for epsilon graphs\n   var:\n       the sigma value for the exponential function, already squared\n\n\n   Output\n   W:\n       (n x n) dimensional matrix representing the adjacency matrix of the graph\n   similarities:\n       (n x n) dimensional matrix containing\n       all the similarities between all points (optional output)\n  \"\"\"\n\n  assert eps + k != 0, \"Choose either epsilon graph or k-nn graph\"\n\n  if eps:\n    print(\"Constructing eps-Graph ...\")\n  else:\n    print(\"Constructing k-NN Graph ...\")\n\n  # euclidean distance squared between points\n  dists = sd.squareform(sd.pdist(X))**2\n  similarities = np.exp(-dists/(2*var))\n\n  if eps:\n    W = similarities * (similarities-eps>=0)\n    print(\"eps-Graph constructed !\")\n    return W, similarities\n\n  if k:\n    W = similarities.copy()\n    for i in range(W.shape[0]):\n      W[i,i] = 0\n      kNearestNodes = np.argsort(-W[i,:])\n      kIdx = kNearestNodes[k:]\n      W[i,kIdx] = 0\n    print(\"k-NN Graph constructed !\")\n    return np.maximum(W, W.T), similarities\n\n\ndef plot_similarity_graph(X, Y, eps=0.1, k=0, var=1):\n\n    W, similarities = build_similarity_graph(X, var, eps=eps, k=k)\n    plot_graph_matrix(X,Y,W)\n\n\ndef how_to_choose_epsilon(gen_param):\n\n    # the number of samples to generate\n    num_samples = 100\n    gen_param =   gen_param\n    [X, Y] = worst_case_blob(num_samples,gen_param)\n\n    var =  0.5\n\n    dists = sd.squareform(sd.pdist(X))**2\n    similarities = np.exp(-dists/(2*var))\n\n    # Building the max spanning tree\n    max_tree = max_span_tree(similarities)\n    A = similarities*max_tree\n    # Finding the optimal epsilon\n    eps = np.min(A[np.where(max_tree>0)])\n    print(\"Best epsilon found: \", eps)\n\n    plot_similarity_graph(X, Y, eps=eps, var=var)\n    return eps\n\nhow_to_choose_epsilon(2)\n[X,Y] = blobs(200,2,0.2)\n[X, Y] = worst_case_blob(100,3)\n[X, Y] = two_moons(200,1,2)\nplot_similarity_graph(X, Y, eps=eps, k=0, var=0.5)\nplot_similarity_graph(X, Y, eps=0, k=10, var=0.5)\n", "meta": {"hexsha": "0414d1e342bfe2a9875c89d0e06b2bd7b437de40", "size": 2524, "ext": "py", "lang": "Python", "max_stars_repo_path": "Spectral Clustering/code_material_python/graph_construction/func.py", "max_stars_repo_name": "AmineKheldouni/Graphs-Machine-Learning", "max_stars_repo_head_hexsha": "1b34ef38516d46e8ca61b1a8093e6c8fb76fe031", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-17T12:40:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-17T12:40:53.000Z", "max_issues_repo_path": "Spectral Clustering/code_material_python/graph_construction/func.py", "max_issues_repo_name": "AmineKheldouni/Graphs-Machine-Learning", "max_issues_repo_head_hexsha": "1b34ef38516d46e8ca61b1a8093e6c8fb76fe031", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Spectral Clustering/code_material_python/graph_construction/func.py", "max_forks_repo_name": "AmineKheldouni/Graphs-Machine-Learning", "max_forks_repo_head_hexsha": "1b34ef38516d46e8ca61b1a8093e6c8fb76fe031", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5684210526, "max_line_length": 80, "alphanum_fraction": 0.6727416799, "include": true, "reason": "import numpy,import scipy", "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517095103498, "lm_q2_score": 0.8918110540642805, "lm_q1q2_score": 0.8569873569632973}}
{"text": "# Plot error surface for linear regression model.\n# Based on https://github.com/probml/pmtk3/blob/master/demos/contoursSSEdemo.m\n\nimport superimport\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pyprobml_utils as pml\n\nfrom mpl_toolkits.mplot3d import axes3d, Axes3D \n\nnp.random.seed(0)\n\nN = 21\nx = np.linspace(0.0, 20, N)\nX0 = x.reshape(N,1)\nX = np.c_[np.ones((N,1)), X0]\nw = np.array([-1.5, 1/9.])\ny =  w[0]*x + w[1]*np.square(x)\ny = y + np.random.normal(0, 1, N) * 2\n\nw = np.linalg.lstsq(X, y, rcond=None)[0]\nW0, W1 = np.meshgrid(np.linspace(-8,0,100), np.linspace(-0.5,1.5,100))\n\nSS = np.array([sum((w0*X[:,0] + w1*X[:,1] - y)**2) for w0, w1 in zip(np.ravel(W0), np.ravel(W1))])\nSS = SS.reshape(W0.shape)\n\nplt.figure()\nplt.contourf(W0, W1, SS)\npml.savefig('linregHeatmapSSE.pdf')\nplt.colorbar()\nplt.show()\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nsurf = ax.plot_surface(W0, W1, SS)\npml.savefig('linregSurfSSE.pdf')\nplt.show()\n\nfig,ax = plt.subplots()\nCS = plt.contour(W0, W1, SS, levels=np.linspace(0,2000,10), cmap='jet')\nplt.plot(w[0], w[1],'x')\npml.savefig('linregContoursSSE.pdf')\nplt.show()", "meta": {"hexsha": "69b6c93c869582bb28f80428de4006d78a876565", "size": 1133, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/linreg_contours_sse_plot.py", "max_stars_repo_name": "vipavlovic/pyprobml", "max_stars_repo_head_hexsha": "59a2edc682d0163955db5e2f27491ad772b60141", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4895, "max_stars_repo_stars_event_min_datetime": "2016-08-17T22:28:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:07:15.000Z", "max_issues_repo_path": "scripts/linreg_contours_sse_plot.py", "max_issues_repo_name": "vipavlovic/pyprobml", "max_issues_repo_head_hexsha": "59a2edc682d0163955db5e2f27491ad772b60141", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 446, "max_issues_repo_issues_event_min_datetime": "2016-09-17T14:35:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:59:33.000Z", "max_forks_repo_path": "scripts/linreg_contours_sse_plot.py", "max_forks_repo_name": "vipavlovic/pyprobml", "max_forks_repo_head_hexsha": "59a2edc682d0163955db5e2f27491ad772b60141", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1160, "max_forks_repo_forks_event_min_datetime": "2016-08-18T23:19:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:44:07.000Z", "avg_line_length": 25.75, "max_line_length": 98, "alphanum_fraction": 0.6725507502, "include": true, "reason": "import numpy", "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517028006207, "lm_q2_score": 0.8918110504699678, "lm_q1q2_score": 0.8569873475255259}}
{"text": "import scipy as sp\r\n\r\nw = sp.poly1d([1, 2, 3, 4])\r\n\r\n# metoda trapezow\r\na = 1\r\nb = 3\r\n\r\n\r\ndef ctN(a, b, Np):\r\n    x = sp.linspace(a, b, Np + 1)\r\n    y = w(x)\r\n    dx = x[1] - x[0]\r\n\r\n    return (sum(y[1:-1]) + (y[0] + y[-1]) / 2) * dx\r\n\r\n\r\ndef ctS(a, b, Np):\r\n    x = sp.linspace(a, b, Np + 1)\r\n    y = w(x)\r\n    dx = x[1] - x[0]\r\n\r\n    return sum((y[1:] + y[:-1]) / 2) * dx\r\n\r\n\r\ndef cS(a, b, Np):\r\n    x = sp.linspace(a, b, Np + 1)\r\n    y = w(x)\r\n    dx = x[1] - x[0]\r\n    return (y[0] + y[-1] + 2 * sum(y[2:-1:2]) + 4 * sum(y[1:-1:2])) * dx / 3\r\n\r\n\r\n\"\"\"metoda newtona\"\"\"\r\n\r\n\r\ndef It38(a, b, Np):\r\n    x = sp.linspace(a, b, Np + 1)\r\n    y = w(x)\r\n    dx = x[1] - x[0]\r\n    return (y[0] + y[-1] + 2 * sum(y[3:-3:3]) + 3 * sum(y[1:Np:3]) + 3 * sum(y[2:-1:3])) * 3 * dx / 8\r\n\r\n\r\ndef cw(a, b):\r\n    tmp = w.integ()\r\n    return tmp(b) - tmp(a)\r\n\r\n\r\nlp = [12, 24, 36, 60, 90]\r\nwd = cw(a, b)\r\n\"\"\"\r\nfor i in range(len(lp)):\r\n    print(\"wartosc dokladna: {}\".format(wd))\r\n    c1 = ctN(a,b,lp[i])\r\n    b1= (c1-wd)/wd\r\n    c2 = ctN(a, b, lp[i]*2)\r\n    b2 = (c2 - wd) / wd\r\n    cr= 4*c2/3-c1/3\r\n    br=(cr-wd)/wd\r\n    print('liczby podzialu: {} i {}\\nc1 = {}, b1 = {:6.2e}\\nc = {}, b2 = {:6.2e}\\n cr = {}, br = {:6.2e}'.format(lp[1],lp[i]*2,c1,b1,c2,b2,cr,br))\r\n\"\"\"\r\nfor i in range(len(lp)):\r\n    print(\"wartosc dokladna: {}\".format(wd))\r\n    c1 = It38(a, b, lp[i])\r\n    b1 = (c1 - wd) / wd\r\n    c2 = It38(a, b, lp[i] * 2)\r\n    b2 = (c2 - wd) / wd\r\n    cr = 10 * c2 / 15 - c1 / 15\r\n    br = (cr - wd) / wd\r\n    print('liczby podzialu: {} i {}\\nc1 = {}, b1 = {:6.2e}\\nc = {}, b2 = {:6.2e}\\n cr = {}, br = {:6.2e}\\n\\n'.format(\r\n        lp[1],\r\n        lp[\r\n            i] * 2,\r\n        c1, b1,\r\n        c2, b2,\r\n        cr,\r\n        br))\r\n", "meta": {"hexsha": "14ccb667358d4d85d3f00072ffca05e046dd3a7b", "size": 1726, "ext": "py", "lang": "Python", "max_stars_repo_path": "trapezium-integration.py", "max_stars_repo_name": "gunater/Numerical-methods", "max_stars_repo_head_hexsha": "4cf676b7d3996b7e70c6f4b50b15acc330a0d763", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trapezium-integration.py", "max_issues_repo_name": "gunater/Numerical-methods", "max_issues_repo_head_hexsha": "4cf676b7d3996b7e70c6f4b50b15acc330a0d763", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trapezium-integration.py", "max_forks_repo_name": "gunater/Numerical-methods", "max_forks_repo_head_hexsha": "4cf676b7d3996b7e70c6f4b50b15acc330a0d763", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4155844156, "max_line_length": 147, "alphanum_fraction": 0.399188876, "include": true, "reason": "import scipy", "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737735, "lm_q2_score": 0.891811041124754, "lm_q1q2_score": 0.8569873425344338}}
{"text": "# You have an N by N board. Write a function that, given N, returns the\n# number of possible arrangements of the board where N queens can be\n# placed on the board without threatening each other, i.e. no two\n# queens share the same row, column, or diagonal.\n\n\nimport numpy as np\n\n\ndef place_queen(board, queen_row):\n    if queen_row in board:\n        return False\n\n    queen_col = len(board)\n    for col, row in enumerate(board):\n        if abs(row - queen_row) == abs(col - queen_col):\n            return False\n    return True\n\n\ndef queens_on_board(N, board = []):\n    if N == len(board):\n        return 1\n\n    variations = 0\n    for row in range(N):\n        if place_queen(board, row):\n            variations += queens_on_board(N, board + [row])\n    return variations\n\n\n# Driver code:\nresult = queens_on_board(4)\nprint(result)\n\nresult = queens_on_board(1)\nprint(result)\n\nresult = queens_on_board(2)\nprint(result)\n\nresult = queens_on_board(10)\nprint(result)", "meta": {"hexsha": "5370dfbb24ad4ba3ff19fb54b1bd11f2d3975ba1", "size": 957, "ext": "py", "lang": "Python", "max_stars_repo_path": "P38_queens.py", "max_stars_repo_name": "bdemin/daily-coding-problem", "max_stars_repo_head_hexsha": "f364df4c41dd31b376ff92d599208356375566e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "P38_queens.py", "max_issues_repo_name": "bdemin/daily-coding-problem", "max_issues_repo_head_hexsha": "f364df4c41dd31b376ff92d599208356375566e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P38_queens.py", "max_forks_repo_name": "bdemin/daily-coding-problem", "max_forks_repo_head_hexsha": "f364df4c41dd31b376ff92d599208356375566e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2558139535, "max_line_length": 71, "alphanum_fraction": 0.670846395, "include": true, "reason": "import numpy", "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517106286378, "lm_q2_score": 0.8918110375304408, "lm_q1q2_score": 0.8569873420723774}}
{"text": "import scipy as sp\nimport scipy.linalg as la\nimport numpy as np\n'''\nU,s,Vh = la.svd(A)\nS = sp.diag(s)\nS = S*(S>tol)\nr = sp.count_nonzero(S)\nB = sp.dot(U,sp.sqrt(S))\nC = sp.dot(sp.sqrt(S),Vh)\nB = B[:,0:r]\nC = C[0:r,:]\n'''\n\n#Problem 3\n#When I feed the second example matrix into my function, \n#it comes out with \"almost\" the correct Drazin Inverse,\n#but the top two rows are 1/2 of what they should be.\n#The other matricies come out right\ndef drazin(A,tol):\n    CB = A.copy()\n    \n    Bs = []\n    Cs = []\n    k = 1\n    \n    while( not (sp.absolute(CB)<tol).all() and sp.absolute(la.det(CB)) < tol):\n        U,s,Vh = la.svd(CB)\n        S = sp.diag(s)\n        S = S*(S>tol)\n        r = sp.count_nonzero(S)\n        B = sp.dot(U,sp.sqrt(S))\n        C = sp.dot(sp.sqrt(S),Vh)\n        B = B[:,0:r]\n        Bs.append(B)\n        C = C[0:r,:]\n        Cs.append(C)\t\n        CB = sp.dot(C,B)\n        k+=1\n    \n    D = sp.eye(A.shape[0])\n    for B in Bs:\n        D = sp.dot(D,B)\n    if( (sp.absolute(CB)<tol).all() ):\n        D = sp.dot( D,CB)\n    else:\n        D = sp.dot( D,np.linalg.matrix_power(CB,-(k+1)))\n    for C in reversed(Cs):\n        D = sp.dot(D,C)\n    return D\n", "meta": {"hexsha": "5062ce690aaa1571c2998c35d2f84ef8f3fc9683", "size": 1161, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/DrazinInverse/drazin.py", "max_stars_repo_name": "jessicaleete/numerical_computing", "max_stars_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-10-18T19:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:12:38.000Z", "max_issues_repo_path": "Labs/DrazinInverse/drazin.py", "max_issues_repo_name": "jessicaleete/numerical_computing", "max_issues_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/DrazinInverse/drazin.py", "max_forks_repo_name": "jessicaleete/numerical_computing", "max_forks_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-14T16:07:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-20T09:05:06.000Z", "avg_line_length": 22.7647058824, "max_line_length": 78, "alphanum_fraction": 0.5167958656, "include": true, "reason": "import numpy,import scipy", "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737735, "lm_q2_score": 0.8918110368115783, "lm_q1q2_score": 0.8569873383896802}}
{"text": "import matplotlib.pyplot as plt\nfrom numpy import arange, ones, zeros\nfrom numpy import sum as npsum\n\nfrom scipy.optimize import least_squares\nfrom scipy.special import gamma\n\nfrom autocorrelation import autocorrelation\n\n\ndef FitFractionalIntegration(dx, l_, d0):\n    # Fit of a fractional integration process on X\n    #  INPUTS\n    #  x         : [vector] (1 x t_end) data dx=diff[x]\n    #  l_        : [scalar] fractional integration process is approximated considering the first l_ terms of its Taylor expansion\n    #  d0        : [scalar] initial guess for the parameter d\n    # OUTPUTS\n    # d          : [scalar] estimate of d (where d+1 is the order of the fractional integration process)\n    # epsFI      : [vector] (1 x t_end) residuals of the fractional integration process fit\n    #             The operator (1+L)**{d} is computed by means of its Taylor expansion truncated at order l_(see the note below)\n    # coeff      : [vector] (l_+1 x 1) first l_+1 coefficients (including coeff_0=1) are considered in the Taylor expansion\n    #Note: If L is the lag operator the residuals are defined as eps = (1-L)**(1+d)X =(1-L)**d dX , where (1-L)**{d} \\approx \\sum_l=0**{l_} coeff_l L**l\n\n    # options\n    # if exist(OCTAVE_VERSION,builtin) == 0\n    #     options = optimoptions(lsqnonlin, TolX, 10**-9, TolFun, 10**-9, MaxFunEvals, 1200, MaxIter, 400, Display, off)\n    # else:\n    #     options = optimset(TolX, 10**-9, TolFun, 10**-9, MaxFunEvals, 1200, MaxIter, 400, Display, off)\n\n    lb = -0.5\n    ub = 0.5\n    res = least_squares(objective,d0,args=(dx,l_),bounds=(lb,ub),ftol=1e-9,xtol=1e-9)\n    d, exitFlag, resNorm = res.x, res.status, None\n    epsFI, coeff = FractIntegrProcess(d,dx,l_+1)\n\n    return d, epsFI, coeff, exitFlag, resNorm\n\n\ndef objective(d, dx, l_):\n    eps, _ = FractIntegrProcess(d,dx,l_)\n    F = npsum(autocorrelation(eps,10)**2)\n    return F\n\n\ndef FractIntegrProcess(d,x,l_):\n    # estimate a fractional integration process\n    #Compute the first l_ coeff and the approximated residuals of a Fractional Integration Process of order d+1\n\n    t_ = x.shape[0]\n    l = arange(1,l_)\n    coeff = ones((1,l_))\n    coeff[0,1:l_] = (-1)**l*gamma(1+d)/gamma(l+1)/gamma(1+d-l)\n\n    eps = zeros((1,t_-l_+1))\n    for t in range(l_,t_):\n        if t==l_:\n            LX = x[t-1::-1]\n        else:\n            LX = x[t-1:t-l_-1:-1]\n        eps[0,t-l_] = coeff@LX.T\n    return eps, coeff\n\n", "meta": {"hexsha": "a5352634df629218bbe8929cbd2ee4aab84497eb", "size": 2408, "ext": "py", "lang": "Python", "max_stars_repo_path": "functions_legacy/FitFractionalIntegration.py", "max_stars_repo_name": "dpopadic/arpmRes", "max_stars_repo_head_hexsha": "ddcc4de713b46e3e9dcb77cc08c502ce4df54f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-04-10T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T08:20:42.000Z", "max_issues_repo_path": "functions_legacy/FitFractionalIntegration.py", "max_issues_repo_name": "dpopadic/arpmRes", "max_issues_repo_head_hexsha": "ddcc4de713b46e3e9dcb77cc08c502ce4df54f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions_legacy/FitFractionalIntegration.py", "max_forks_repo_name": "dpopadic/arpmRes", "max_forks_repo_head_hexsha": "ddcc4de713b46e3e9dcb77cc08c502ce4df54f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-08-13T22:02:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T17:49:12.000Z", "avg_line_length": 38.2222222222, "max_line_length": 152, "alphanum_fraction": 0.6411960133, "include": true, "reason": "from numpy,from scipy", "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474220263198, "lm_q2_score": 0.8976952859490985, "lm_q1q2_score": 0.8569824904964869}}
{"text": "import numpy as np\n\n\n\nEXAMPLE=3\n\n\nif EXAMPLE==1:\n    '''\n    The trasition matrix defines the Markov Chain. If you change to higher dimentions and want to start from\n    a state diferent from 0, then you should change the dimension of variables v and state, accordingly.\n    '''\n    Transition=np.array([\\\n                [0.5,0.3,0.1,0.1],\\\n                [0.05,0.45,0.4,0.1],\\\n                [0.25,0.35,0.3,0.1],\\\n                [0.4,0.1,0.25,0.25]\n                ])#Reminder: the sum of each row sums up to 1.\n\nif EXAMPLE==2:\n    '''\n    The trasition matrix defines the Markov Chain. If you change to higher dimentions and want to start from\n    a state diferent from 0, then you should change the dimension of variables v and state, accordingly.\n    '''\n    Transition=np.array([\\\n                [0.2,0.7,0.1],\\\n                [0,0,1],\\\n                [1,0,0]\\\n                ])#Reminder: the sum of each row sums up to 1.\n\n\n'''\nGenerate a random Markov Chain (with N_dim #states) and see if it reaches equilibrium (the most probable scenario is that it will, since I generate random rows\nwith numbers that add up to 1)\n'''\nN_dim=5\nif EXAMPLE==3:\n    Transition=np.random.dirichlet(np.ones(N_dim),N_dim)\n\n\n\n#=============================================================Begin\n#Number of steps in both the Iteration and Simulation.\nN_tot=5000\n#Doing the following you start at state 0 automatically.\nlen_T=len(Transition[0])\ninit_s=np.zeros(len_T)\ninit_s[0]=1\n\n\n'''\nIterative solution to w.P=w.\nIteratively find w^{(n)}=w^{(0)}.P^{(n+1)}.\n'''\n#v=[1,0,0,0]#play around with this (the final result should not change as long as the v.v=1)\nv=init_s[:]#start at state 0 automatically\n\n'''\nSimulation.\nSimulate the Markov Chain\n'''\n#state=[1,0,0,0]#This is the initial sate vector, which indicates the current state. e.g [1,0,0] indicates that the system is in state 0 (I start counting from 0).\nstate=init_s[:]#start at state 0 automatically\n_visits=np.zeros(len(state))\n\n\n\n\n\nfor i in np.arange(N_tot):\n\n    '''\n    Iterative solution:\n    Calculate v^{(n+1)}=P^{T}v^{(n)}\n    '''\n    v=np.dot(Transition.T,v)\n\n    '''\n    Simulation:\n    The next state in the simulation is determined by the multinomial distribution,\n    which is included in numpy ( you can find how to samlpe from the multinomial in misc/multinomial.py ).\n    '''\n    state= np.random.multinomial(1,np.dot(Transition.T,state))\n    _visits+=state#Fortunately, all notations click together. Since states are defined in \"binary\", we can add them up to obtain the number of visits for each state.\n\n\n\nprint( \"iterative=\", v)\n\ns=np.array(_visits)/float(N_tot)\nprint( 'simulation=', s)#probabilities is the fraction of visits over time.\n\n\nprint( r\"Maximum discrepancy:\" , np.max(np.abs(v-s))/np.max(np.abs(v)) , r\"%\" )\n\n#=============================================================Done\n\n#\n", "meta": {"hexsha": "ec5515df8992324f94ab6b876adbb6319a63229e", "size": 2859, "ext": "py", "lang": "Python", "max_stars_repo_path": "Monte_Carlo/Markov-Chain/Discrete_Markov-chain.py", "max_stars_repo_name": "dkaramit/ASAP", "max_stars_repo_head_hexsha": "afade2737b332e7dbf0ea06eb4f31564a478ee40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Monte_Carlo/Markov-Chain/Discrete_Markov-chain.py", "max_issues_repo_name": "dkaramit/ASAP", "max_issues_repo_head_hexsha": "afade2737b332e7dbf0ea06eb4f31564a478ee40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Monte_Carlo/Markov-Chain/Discrete_Markov-chain.py", "max_forks_repo_name": "dkaramit/ASAP", "max_forks_repo_head_hexsha": "afade2737b332e7dbf0ea06eb4f31564a478ee40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-15T02:03:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T02:03:01.000Z", "avg_line_length": 28.8787878788, "max_line_length": 165, "alphanum_fraction": 0.6257432669, "include": true, "reason": "import numpy", "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474142844409, "lm_q2_score": 0.8976952852648487, "lm_q1q2_score": 0.8569824828934213}}
{"text": "'''\nWrite a short Python function that takes a positive integer n and returns\nthe sum of the squares of all the positive integers smaller than n.\n'''\n\nimport numpy as np\n\ndef squaresum(a: int):\n    arr = np.arange(a) * np.arange(a)\n    arr = np.sum(arr)\n    return arr\n\n\n'''\nWrite a short Python function that takes a positive integer n and returns\nthe sum of the squares of all the odd positive integers smaller than n.\n'''\n\ndef squaresumodds(a: int):\n    arr = np.arange(a) * np.arange(a)\n    i = 0\n    res = []\n    while i < len(arr):\n        if bool(arr[i]&(1<<0)):\n            res.append(1)\n        else:\n            res.append(0)\n        i += 1\n    arr = arr * np.array(res)\n    arr = np.sum(arr)\n    return arr\n\n'''\nThe sum of the squares of the first ten natural numbers is,\n\nThe square of the sum of the first ten natural numbers is,\n\nHence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is .\n\nFind the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.\n\n'''\ndef sumsquaredif(a: int):\n    sum_squares = squaresum(a)\n    arr = np.arange(a)\n    arr = np.sum(arr)*np.sum(arr)\n    return (arr - sum_squares)\n\n\ndef main():\n    a = 101\n    print('a vector: ', np.arange(a))\n    print('sum of squares of a: ', squaresum(a))\n    print('sum of squares of odds of a: ', squaresumodds(a))\n    print('difference between sum of squares: ', sumsquaredif(a))\n\nif __name__=='__main__':\n    main()", "meta": {"hexsha": "0535a2317c18294a96793e5f70d7a1410b3d50cc", "size": 1506, "ext": "py", "lang": "Python", "max_stars_repo_path": "square_sum.py", "max_stars_repo_name": "marchcarax/Exercises_python", "max_stars_repo_head_hexsha": "f63a9f214750c5327cad792bfdcd3813b4659718", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "square_sum.py", "max_issues_repo_name": "marchcarax/Exercises_python", "max_issues_repo_head_hexsha": "f63a9f214750c5327cad792bfdcd3813b4659718", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "square_sum.py", "max_forks_repo_name": "marchcarax/Exercises_python", "max_forks_repo_head_hexsha": "f63a9f214750c5327cad792bfdcd3813b4659718", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9655172414, "max_line_length": 118, "alphanum_fraction": 0.6507304117, "include": true, "reason": "import numpy", "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290930537121, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.8569513826433458}}
{"text": "#!/usr/bin/env python3\n\"\"\"\nMarkov Module\n\"\"\"\nimport numpy as np\n\n\ndef markov_chain(P, s, t=1):\n    \"\"\"\n    Determines the probability of a markov chain being in a particular state\n    after a specified number of iterations:\n\n    P is a square 2D numpy.ndarray of shape (n, n) representing the transition\n    matrix\n        P[i, j] is the probability of transitioning from state i to state j\n        n is the number of states in the markov chain\n    s is a numpy.ndarray of shape (1, n) representing the probability of\n    starting in each state\n    t is the number of iterations that the markov chain has been through\n\n    Returns: a numpy.ndarray of shape (1, n) representing the probability of\n    being in a specific state after t iterations, or None on failure\n    \"\"\"\n    if type(P) is not np.ndarray or len(P.shape) != 2:\n        return None\n    if type(s) is not np.ndarray or len(s.shape) != 2:\n        return None\n    if P.shape[0] != P.shape[1] or s.shape[0] != 1:\n        return None\n    if P.shape[0] != s.shape[1]:\n        return None\n    if type(t) is not int or t <= 0:\n        return None\n    if np.sum(P, axis=1).all() != 1:\n        return None\n    if np.sum(s) != 1:\n        return None\n\n    st = np.linalg.matrix_power(P, t)\n    sm = np.matmul(s, st)\n    return sm\n", "meta": {"hexsha": "1741ea99e8b4305d4c2c5c4cc261165207f200f5", "size": 1284, "ext": "py", "lang": "Python", "max_stars_repo_path": "unsupervised_learning/0x02-hmm/0-markov_chain.py", "max_stars_repo_name": "kyeeh/holbertonschool-machine_learning", "max_stars_repo_head_hexsha": "8e4894c2b036ec7f4750de5bf99b95aee5b94449", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unsupervised_learning/0x02-hmm/0-markov_chain.py", "max_issues_repo_name": "kyeeh/holbertonschool-machine_learning", "max_issues_repo_head_hexsha": "8e4894c2b036ec7f4750de5bf99b95aee5b94449", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unsupervised_learning/0x02-hmm/0-markov_chain.py", "max_forks_repo_name": "kyeeh/holbertonschool-machine_learning", "max_forks_repo_head_hexsha": "8e4894c2b036ec7f4750de5bf99b95aee5b94449", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5714285714, "max_line_length": 78, "alphanum_fraction": 0.6331775701, "include": true, "reason": "import numpy", "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899575269305, "lm_q2_score": 0.88720460564669, "lm_q1q2_score": 0.8569505517711091}}
{"text": "from math import *\n\nimport scipy.constants as sc\n\n\ndef simpsons_rule(f, a, b):\n    c = (a + b) / 2.0\n    h3 = abs(b - a) / 6.0\n    return h3 * (f(a) + 4.0 * f(c) + f(b))\n\n\ndef recursive_asr(f, a, b, eps, whole):\n    c = (a + b) / 2.0\n    left = simpsons_rule(f, a, c)\n    right = simpsons_rule(f, c, b)\n    if abs(left + right - whole) <= 15 * eps:\n        return left + right + (left + right - whole) / 15.0\n    return recursive_asr(f, a, c, eps / 2.0, left) + recursive_asr(f, c, b, eps / 2.0, right)\n\n\ndef adaptive_simpsons_rule(f, a, b, eps):\n    return recursive_asr(f, a, b, eps, simpsons_rule(f, a, b))\n\n\ndef f(x):\n    return x ** 3 / (exp(x) - 1)\n\n\nAns = adaptive_simpsons_rule(f, 0 + 10 ** -10, 100, 10 ** -10)\n\nstefan = Ans * sc.Boltzmann ** 4 / 4 / pi ** 2 / sc.speed_of_light ** 2 / sc.hbar ** 3\nprint(stefan, 'value from program')\nprint(sc.Stefan_Boltzmann, 'Actural value')\n", "meta": {"hexsha": "4b6b692acd364302f74dd3c603601070b72fb688", "size": 888, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ankit Khandelwal_HW2/exercise 4/exercise 4.py", "max_stars_repo_name": "ankit27kh/Computational-Physics-PH354", "max_stars_repo_head_hexsha": "d37c93e430a0f282251a814456890acb4a2961fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ankit Khandelwal_HW2/exercise 4/exercise 4.py", "max_issues_repo_name": "ankit27kh/Computational-Physics-PH354", "max_issues_repo_head_hexsha": "d37c93e430a0f282251a814456890acb4a2961fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ankit Khandelwal_HW2/exercise 4/exercise 4.py", "max_forks_repo_name": "ankit27kh/Computational-Physics-PH354", "max_forks_repo_head_hexsha": "d37c93e430a0f282251a814456890acb4a2961fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1176470588, "max_line_length": 93, "alphanum_fraction": 0.5765765766, "include": true, "reason": "import scipy", "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899577232538, "lm_q2_score": 0.8872046026642944, "lm_q1q2_score": 0.8569505506322038}}
{"text": "\"\"\"\nMapping between Ternary and Cartesian Coordinates.\n\nFunctions for converting ternary coordinates into cartesian system used in Matplotlib and vice-versa. All the values will be scaled so that the side length of the triangle is equal to one.\n\"\"\"\n\nimport numpy as np\n\n# Define constants to avoid code repetitions\n_sqrt3 = np.sqrt(3.)\n_half_sqrt3 = _sqrt3 / 2.\n\n# Ternary to Cartesian Mapping\ndef ternaryToCartesian(coordinates):\n    \"\"\"\n    Maps ternary coordinates to cartesian coordinates.\n\n    Consider an equilateral ternary plot where a = 1 is placed at (0,0) and b = 1 is placed at (1,0). Then c = 1 will be at (1/2, sqrt(3)/2).\n    The 3-tuple (a,b,c) will have the cartesian coordinates (b+c/2, sqrt(3)c/2, z), where a+b+c = 1.\n\n    Parameters\n    ----------\n    coordinates: list / tuple / numpy array of size three\n                 The coordinates to be converted from ternary to cartesian\n\n    Returns\n    -------\n    numpy array of size two\n    \"\"\"\n    return(np.array([(coordinates[1] + coordinates[2] / 2.), (_half_sqrt3 * coordinates[2])]))\n\n# Cartesian to Ternary Mapping\ndef cartesianToTernary(coordinates, sigma = 1.):\n    \"\"\"\n    Maps cartesian coordinates to ternary coordinates.\n\n    Mapping from cartesian to ternary coordinates requires an additional equation. If the sum of the ternary coordinates is known (say n), one can use the equations\n    for ternary to cartesian mapping and a+b+c = n to get (x-y/sqrt(3), 2y/sqrt(3), n-a-b)\n\n    Parameters\n    ----------\n    coordinates: list / tuple / numpy array of size two\n                The coordinates to be converted from cartesian to ternary\n\n    sigma: Real\n            Sum of (a, b, c) that the ternary coordinates should sum to.\n\n    Returns\n    -------\n    numpy array of size three\n    \"\"\"\n    c = coordinates[1] / _half_sqrt3\n    b = coordinates[0] - c / 2.\n    a = sigma - (b + c)\n    return(np.array([a,b,c]))\n", "meta": {"hexsha": "4b6db08f5cb702686ee3f3af71932435087e8d2a", "size": 1896, "ext": "py", "lang": "Python", "max_stars_repo_path": "framework/CoordinateMap.py", "max_stars_repo_name": "parikshitbajpai/TernaryPrism", "max_stars_repo_head_hexsha": "8a152d2fc1ccab2a0f04ef5ab8edcc6ba86c7beb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "framework/CoordinateMap.py", "max_issues_repo_name": "parikshitbajpai/TernaryPrism", "max_issues_repo_head_hexsha": "8a152d2fc1ccab2a0f04ef5ab8edcc6ba86c7beb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-10-16T16:56:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T21:53:48.000Z", "max_forks_repo_path": "framework/CoordinateMap.py", "max_forks_repo_name": "parikshitbajpai/TernaryPrism", "max_forks_repo_head_hexsha": "8a152d2fc1ccab2a0f04ef5ab8edcc6ba86c7beb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8571428571, "max_line_length": 188, "alphanum_fraction": 0.664556962, "include": true, "reason": "import numpy", "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995742876886, "lm_q2_score": 0.8872046026642944, "lm_q1q2_score": 0.8569505480195199}}
{"text": "import numpy as np\n\ndef tilde_w(w, dt):\n    return (2./dt)*np.arcsin(w*dt/2.)\n\ndef plot_frequency_approximations():\n    w = 1  # relevant value in a scaled problem\n    stability_limit = 2./w\n    dt = np.linspace(0.2, stability_limit, 111)  # time steps\n    series_approx = w + (1./24)*dt**2*w**3\n    P = 2*np.pi/w  # one period\n    num_timesteps_per_period = P/dt  # more instructive\n    import scitools.std as plt\n    plt.plot(num_timesteps_per_period, tilde_w(w, dt), 'r-',\n             num_timesteps_per_period, series_approx, 'b--',\n             legend=('exact discrete frequency', '2nd-order expansion'),\n             xlabel='no of time steps per period',\n             ylabel='numerical frequency')\n    plt.savefig('discrete_freq.png')\n    plt.savefig('discrete_freq.pdf')\n\nplot_frequency_approximations()\n", "meta": {"hexsha": "54758dd94cd18241d898effafc6ee6f1cfa0b6a0", "size": 811, "ext": "py", "lang": "Python", "max_stars_repo_path": "fdm-devito-notebooks/01_vib/src-vib/vib_plot_freq.py", "max_stars_repo_name": "devitocodes/devito_book", "max_stars_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-07-17T13:19:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-27T05:21:09.000Z", "max_issues_repo_path": "fdm-jupyter-book/notebooks/01_vib/src-vib/vib_plot_freq.py", "max_issues_repo_name": "devitocodes/devito_book", "max_issues_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 73, "max_issues_repo_issues_event_min_datetime": "2020-07-14T15:38:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-25T11:54:59.000Z", "max_forks_repo_path": "fdm-jupyter-book/notebooks/01_vib/src-vib/vib_plot_freq.py", "max_forks_repo_name": "devitocodes/devito_book", "max_forks_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-27T05:21:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T05:21:14.000Z", "avg_line_length": 35.2608695652, "max_line_length": 72, "alphanum_fraction": 0.65351418, "include": true, "reason": "import numpy", "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899570361222, "lm_q2_score": 0.8872046056466901, "lm_q1q2_score": 0.8569505474166353}}
{"text": "import numpy as np\nfrom sklearn import linear_model, datasets\nimport matplotlib.pyplot as plt\n\ndef onehot(y):\n    n = len(np.unique(y))\n    m = y.shape[0]\n    b = np.zeros((m, n))\n    for i in xrange(m):\n        b[i, y[i]] = 1\n    return b\n\n\ndef softmax(X):\n    return (np.exp(X).T / np.sum(np.exp(X), axis=1)).T\n\n\ndef h_func(theta, X):\n    h = np.dot(np.c_[np.ones(X.shape[0]), X], theta)\n    return softmax(h)\n\n\ndef h_gradient(theta, X, y, lam=0.1):\n    n = X.shape[0]\n    y_mat = onehot(y)\n    preds = h_func(theta, X)\n    return -1./n * np.dot(np.c_[np.ones(n), X].T, y_mat - preds) + lam * theta\n\n\ndef softmax_cost_func(theta, X, y, lam=0.1):\n    n = X.shape[0]\n    y_mat = onehot(y)\n    return -1./n * np.sum(y_mat * np.log(h_func(theta, X))) + lam/2. * np.sum(theta * theta)\n\n\n# gradient descent\ndef softmax_grad_desc(theta, X, y, lr=.01, converge_change=.0001, max_iter=100, lam=0.1):\n    # normalize\n    #X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)\n\n    cost_iter = []\n    cost = softmax_cost_func(theta, X, y, lam=lam)\n    cost_iter.append([0, cost])\n    change_cost = 1\n    i = 1\n    while change_cost > converge_change and i < max_iter:\n        pre_cost = cost\n        theta -= lr * h_gradient(theta, X, y)\n        cost = softmax_cost_func(theta, X, y)\n        cost_iter.append([i, cost])\n        change_cost = abs(pre_cost - cost)\n        i += 1\n    return theta, np.array(cost_iter)\n\n\ndef softmax_pred_val(theta, X):\n    probs = h_func(theta, X)\n    preds = np.argmax(probs, axis=1)\n    return probs, preds\n\n\ndef softmax_regression():\n    # Load the diabetes dataset\n    dataset = datasets.load_digits()\n\n    # Use all the features\n    X = dataset.data[:, :]\n    y = dataset.target[:, None]\n\n    # Gradiend Descent\n    theta = np.random.rand(X.shape[1]+1, len(np.unique(y)))\n    fitted_val, cost_iter = softmax_grad_desc(theta, X, y, lr=0.01, max_iter=1000, lam=0.1)\n    probs, preds = softmax_pred_val(fitted_val, X)\n\n    #print(fitted_val)\n    print(cost_iter[-1,:])\n    print('Accuracy: {}'.format(np.mean(preds[:, None] == y)))\n\n    plt.plot(cost_iter[:, 0], cost_iter[:, 1])\n    plt.ylabel(\"Cost\")\n    plt.xlabel(\"Iteration\")\n    plt.show()\n\n\ndef main():\n    softmax_regression()\n\nif __name__ == \"__main__\":\n    main()", "meta": {"hexsha": "49647c2456cb6435be8ce55c5af7582b6101dc9f", "size": 2242, "ext": "py", "lang": "Python", "max_stars_repo_path": "week1/class1_softmax_regression.py", "max_stars_repo_name": "RichardTMR/homework", "max_stars_repo_head_hexsha": "83920fef57e36ea1181b92940d3cbd986168186e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week1/class1_softmax_regression.py", "max_issues_repo_name": "RichardTMR/homework", "max_issues_repo_head_hexsha": "83920fef57e36ea1181b92940d3cbd986168186e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week1/class1_softmax_regression.py", "max_forks_repo_name": "RichardTMR/homework", "max_forks_repo_head_hexsha": "83920fef57e36ea1181b92940d3cbd986168186e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.191011236, "max_line_length": 92, "alphanum_fraction": 0.6057091882, "include": true, "reason": "import numpy", "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995713428385, "lm_q2_score": 0.8872046041554922, "lm_q1q2_score": 0.8569505468471826}}
{"text": "\n#!/usr/bin/python3\n# reflection.py\n\nimport sys\nimport os\nimport numpy as np\n\nclass Reflection:\n    \"\"\"\n    Class for calculating the reflection of a, through the orthogonal matrix of v. \n    \n    ...\n    \n    Attributes\n    ----------\n    v: numpy array \n        vector, shape(m,1), to initialize the Housholder transformation matrix.\n    \n    Methods\n    -------\n    __mul__(a)\n        Transforms the vector a using the Housholder transformation \n        H = I - 2((vv(T)) / |v|**2).\n    \"\"\"\n    \n    def __init__(self, v): \n        \"\"\"\n        Vector v shape(m,1), to initialize the Housholder transformation.\n        \"\"\"\n\n        self.v = v \n        \n    def __mul__(self, a):\n        \"\"\"  \n        Transforms the vector a using the Housholder transformation H = I - 2((vv(T)) / |v|**2).\n        \n        Calculate the matrix product for the \n        reflection of vector a orthogonal matrix H.\n        The dimension of a needs to be bigger or equal \n        to the dimesion of v.\n        If the dimension of v is smaller than the dimension of a, \n        v can be filled with zeros.\n        \n        Parameters\n        ----------\n        a: numpy array\n            vector, shape(m,1) input vector to be transformed.\n            \n        Returns\n        -------\n        reflection: numpy array\n            vector, shape(m,1), a reflected through H.\n        \"\"\"\n        \n        if len(a) < len(self.v):\n            raise Exception('Length of a is smaller than length of v!')\n        elif len(a) > len(self.v):\n            differenceav = (len(a) - len(self.v))\n            add = np.zeros(differenceav)\n            velong = np.insert(self.v,0,add).reshape(len(a),1) # add zeros at the end\n            self.v = velong\n        else:\n            self.v = self.v\n            \n        gamma = ((np.linalg.norm(self.v))**2)/2\n        vvtrans = self.v * np.transpose(self.v)\n        H =  np.identity((len(a))) - (vvtrans/gamma)\n        reflection = np.dot(H,a)\n        \n        return(reflection) \n", "meta": {"hexsha": "24a8e2443091eb433a4c9222d56ff256d24cd5e7", "size": 1993, "ext": "py", "lang": "Python", "max_stars_repo_path": "package/reflection.py", "max_stars_repo_name": "karempudi/householder", "max_stars_repo_head_hexsha": "8342367bf7477185e47f6452d010d5de1d5c756d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-14T19:56:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T19:56:00.000Z", "max_issues_repo_path": "package/reflection.py", "max_issues_repo_name": "karempudi/householder", "max_issues_repo_head_hexsha": "8342367bf7477185e47f6452d010d5de1d5c756d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "package/reflection.py", "max_forks_repo_name": "karempudi/householder", "max_forks_repo_head_hexsha": "8342367bf7477185e47f6452d010d5de1d5c756d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-14T19:58:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T19:58:57.000Z", "avg_line_length": 27.6805555556, "max_line_length": 96, "alphanum_fraction": 0.5283492223, "include": true, "reason": "import numpy", "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995762509216, "lm_q2_score": 0.8872045966995027, "lm_q1q2_score": 0.8569505439999194}}
{"text": "\n\"\"\"\nimplementation of gradient descent\nn the solution of the linear equation\nhttps://en.wikipedia.org/wiki/Gradient_descent#Solution_of_a_linear_system\n\"\"\"\n\nimport numpy as np\nfrom tqdm import trange\n\n\ndef cost_function(y_true, y_pred):\n    \"\"\"Computes the cost of linear regression\n    \"\"\"\n    n, _ = y_true.shape\n    cost = 1 / (2 * n) * np.sum((y_true - y_pred) ** 2)\n    return cost\n\ndef normalize(X):\n    \"\"\"Returns a normalized version of X where\n    the mean value of each feature is 0\n    and the standard deviation is 1\n    \"\"\"\n    # calculate mean value along zero axis\n    X_mean = np.mean(X, axis=0)\n    # calculate standard deviation along zero axis\n    X_std = np.std(X, axis=0)\n    # Standard scaler\n    # z = (x - mu) / sigma\n    X_norm = (X - X_mean) / X_std\n    return X_norm, X_std\n\ndef gradient_descent(X, y, theta=None, alpha=0.05, num_epoch=10, verbose=True):\n    \"\"\"Performs gradient descent to learn theta\n    by taking n steps\n    \"\"\"\n    n, m = X.shape\n    if theta is None:\n        # set theta as random weights\n        theta = np.random.rand(m + 1, 1)\n    # add intercept value to X\n    X0 = np.concatenate([np.ones((n, 1)), X], axis=1)\n    # set dict with costs values\n    cost = {}\n    t = trange(num_epoch)\n    for epoch in t:\n        # set new theta value\n        # theta = theta - alpha * 1 / m * X' * (X * theta - y)\n        theta = theta - alpha * 1 / n * X0.T @ (X0 @ theta - y)\n        # calculate predicted value with new theta\n        y_pred = X0 @ theta\n        # calculate cost value\n        cost[epoch] = cost_function(y, y_pred)\n        if verbose:\n            t.set_description(\n                \"epoch: {:4d} cost: {:.4f}\".format(epoch, cost[epoch]))\n    return theta\n\ndef inverse_transform(theta_normalize, X, X_std):\n    \"\"\"transform theta normilize to original feature space\n    \"\"\"\n    n = X_std.shape[0]\n    # rescale theta\n    theta_rescaled = (theta_normalize.flatten()[1:] / X_std).reshape((n, 1))\n    # get predictions\n    y_pred = X @ theta_rescaled\n    # calculate mean bias values\n    theta_0 = (y - y_pred).mean()\n    # concatenate\n    theta = np.concatenate([[[theta_0]], theta_rescaled], axis=0)\n    return theta\n\nif __name__ in '__main__':\n    # set X vector\n    X = np.array([\n        [-1, 0],\n        [1, 100],\n        [2, 200],\n        [3, 300],\n        [4, 400],\n        [5, 500],\n    ])\n    # set y based on equation y = 5 + X0 * 20 + X1 * 1\n    theta_true = np.array([\n        [5.], [20.], [1.]\n        ])\n    y = X @ theta_true[1:, :] + theta_true[0, :]\n    print(\"X:\\n{}\".format(X))\n    print(\"y:\\n{}\".format(y))\n    # transfom all components in X to normalize view\n    # for proper working of the gradient descent\n    X_normalize, X_std = normalize(X)\n    # obtaine theta (normalize) vector using gradient descent algorithm\n    theta_normilize = gradient_descent(\n        X_normalize, y, alpha=0.1, num_epoch=10000, verbose=True)\n    # convert theta normilize to original feature space\n    theta = inverse_transform(theta_normilize, X, X_std)\n    print(\"\\n\\n\")\n    print(\"theta:\\n{}\".format(theta))\n    print(\"theta_true:\\n{}\".format(theta_true))\n", "meta": {"hexsha": "479b01db42da9cce5589f54c22747b9584d73702", "size": 3117, "ext": "py", "lang": "Python", "max_stars_repo_path": "lin_model/gradient_descent.py", "max_stars_repo_name": "dsysoev/fun-with-tensorflow", "max_stars_repo_head_hexsha": "3be8ea9dcb7960b946c5b2430b63e2cf981e5437", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lin_model/gradient_descent.py", "max_issues_repo_name": "dsysoev/fun-with-tensorflow", "max_issues_repo_head_hexsha": "3be8ea9dcb7960b946c5b2430b63e2cf981e5437", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-12T01:03:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T01:03:22.000Z", "max_forks_repo_path": "lin_model/gradient_descent.py", "max_forks_repo_name": "dsysoev/fun-with-tensorflow", "max_forks_repo_head_hexsha": "3be8ea9dcb7960b946c5b2430b63e2cf981e5437", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8613861386, "max_line_length": 79, "alphanum_fraction": 0.6047481553, "include": true, "reason": "import numpy", "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241991754918, "lm_q2_score": 0.8840392802184581, "lm_q1q2_score": 0.8569206673374351}}
{"text": "import numpy as np \r\nimport matplotlib.pyplot as plt\r\nplt.style.use('seaborn-whitegrid')\r\n\r\n\r\n\r\ndef f(x) :\r\n   \r\n    s = np.power(x,3)  - x - 1\r\n    \r\n    return s\r\n\r\n\r\ndef f_p(x):\r\n    \r\n    s = 3*np.power(x,2)  - 1\r\n    \r\n    return s\r\n\r\n\r\n\r\ndef Newton_Raphson(x0,Tol,Nmax) :\r\n    \r\n    x=x0 - f(x0)/f_p(x0)\r\n    e=abs(x-x0)\r\n    n=1\r\n    while n < Nmax and e > Tol :\r\n          x0 = x\r\n          x = x0 - f(x0)/f_p(x0)\r\n          e=abs(x-x0)\r\n          n += 1\r\n          \r\n          \r\n    return x,n,f(x)\r\n\r\n\r\n#------------ MAIN PROGRAMME -------------#\r\n    \r\nx0=1.5 ;Tol=10**(-8) ;Nmax=100\r\nx,n,fx = Newton_Raphson(x0,Tol,Nmax)\r\n\r\nprint ('Approximate Solution is ' , x )\r\nprint ('number of steps is ' , n)\r\nprint ('Value at approximate solution is ' , fx)\r\n\r\nt=np.linspace(0,2,100)\r\ny=f(t)\r\n\r\nplt.plot(t,y,'grey')\r\nplt.legend(['f(x)'])\r\nplt.ylabel('y')\r\nplt.xlabel('x')\r\nplt.show()\r\n\r\n", "meta": {"hexsha": "bb45b90d93ca688b4a532448931727a5798ad103", "size": 890, "ext": "py", "lang": "Python", "max_stars_repo_path": "Newton-Rapshon.py", "max_stars_repo_name": "Michaellianeris/NSODE-Algorithms", "max_stars_repo_head_hexsha": "40788cc7b4fc889a2b0dfe72e88b0e417cafa001", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Newton-Rapshon.py", "max_issues_repo_name": "Michaellianeris/NSODE-Algorithms", "max_issues_repo_head_hexsha": "40788cc7b4fc889a2b0dfe72e88b0e417cafa001", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Newton-Rapshon.py", "max_forks_repo_name": "Michaellianeris/NSODE-Algorithms", "max_forks_repo_head_hexsha": "40788cc7b4fc889a2b0dfe72e88b0e417cafa001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.1818181818, "max_line_length": 49, "alphanum_fraction": 0.4775280899, "include": true, "reason": "import numpy", "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241965169939, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.856920656102925}}
{"text": "#################################################################################\n#        DERIVATIVE ERROR ESTIMATION AND THE RICHARDSON EXTRAPOLATION METHOD\n#    This program computes:\n#    1) the Richardson derivative of f(x) = sin(x) at x = 1 using an adaptative scheme,\n#    2) for a relative error < 1e-7,\n#                                                                          \n#    (Marina von Steinkirch, spring 2013)\n#\n#################################################################################\n\n\n\nimport math\nimport numpy\nimport pylab\n\n\n\n\"\"\" Functions \"\"\"\n\ndef func(x):\n    \"\"\" the function to be plotted \"\"\"\n    fx = numpy.sin(x)\n    return fx\n\n\ndef fprime(x):\n    \"\"\" the analytic derivative of func(x) \"\"\"\n    fp = numpy.cos(x)\n    return fp\n\n\ndef machine_precision():\n    \"\"\" calculates the machine precision, 2*eps\"\"\"\n    x = 1.0\n    eps = 1.0\n    while (not x + eps == x):\n        eps = eps/2.0\n    return 2.0*eps\n\n\ndef delta1(h, x):            \n    \"\"\" calculates the second-order centered difference \"\"\"\n    d1 = (func(x+h) - func(x-h))/(2.0*h)\n    return d1\n\n\ndef relative_error(fa, fn):            \n    \"\"\" calculates the relative error \"\"\"\n    e = abs( ( fa - fn ) / fa )\n    return e\n\n\ndef absolute_error(fa, fn):            \n    \"\"\" calculates the relative error \"\"\"\n    e = abs(  fa - fn  )\n    return e\n\n\ndef richardson_derivative(h, x):\n    \"\"\" calculate the derivative using delta1 for h and h/2 \"\"\"\n    d = delta1(h, x)\n    h = h/2\n    d1 = delta1(h, x)\n    f1 =  (4*d1-d)/3\n\n    # MZ -- why is there an h**2 here?  \n    epsilon = h*h*abs(d-d1) \n    return f1, epsilon\n\n\ndef printing(n, h, f1, fp, e, er, ea):\n    print \"\\n________________________________________________________________________________\"\n    print \"Iteration n = \", int(n)\n    print \"The distance between two points in this grid (h) is:    \", h            \n    print \"Calculated (Richardsob) Derivative of f(x)=sin(x) at x = 1:    \", f1\n    print \"Analytic First Derivative of f(x)=sin(x) at x = 1:    \", fp\n    print \"Truncated Error (from the Taylor approx):    \", e\n    print \"Relative Error:    \", er\n    print \"Absolute Error:    \", ea\n    return 0\n    \n    \n\"\"\" Variables \"\"\"\n\nCONST_EPS = 10**(-6)            # relative error\nCONST_XL = 0.0              # most left point\nCONST_XR = math.pi          # most right point: 3.14 > x=1,\nCONST_X = 1.0               # point where we are calculating the derivative\n\nh_array = []\ner_array = []\nea_array = []\nepsilon_array = []\n\n\nepsilon = 1.1*10**(-6) \nn = 0.0\n\n\n\n\"\"\" Main Program \"\"\"\nwhile (epsilon >= CONST_EPS):\n    n += 1\n    h = abs((CONST_XR - CONST_XL)/(2*float(n)))        # distance in the grid\n\n    # MZ -- the error you are asked to monitor is the error between \n    # the difference with h and the one with h/2\n    f1, epsilon = richardson_derivative(h, CONST_X)\n    error_r = relative_error(f1, fprime(CONST_X))\n    error_a = absolute_error(f1, fprime(CONST_X))\n\n    printing(int(n), h, f1, fprime(CONST_X), epsilon, error_r, error_a)\n    \n    h_array.append(h)\n    er_array.append(error_r)\n    ea_array.append(error_a)\n    epsilon_array.append(epsilon)\n\n\n\n\n\"\"\" Plotting the Errors vs h \"\"\"\npylab.loglog(h_array, er_array, 'go',  label=\"Relative Error\")\npylab.loglog(h_array, ea_array, 'r*',  label=\"Absolute Error\")\npylab.loglog(h_array, epsilon_array,'b--',  label=\"Truncated Error $O(h^4)$\")\n\nleg = pylab.legend(loc=4,labelspacing=0.1)\nltext = leg.get_texts()\npylab.setp(ltext, fontsize='small')\nleg.draw_frame(1)\n\npylab.xlabel('Log( Griding Distance h)')\npylab.ylabel('Log (Error)')\npylab.grid(True)\n\npylab.savefig(\"der_error.png\")\n\n\n\n\"\"\" Plotting the Errors vs n \"\"\"\npylab.clf()\npylab.cla()\nnlist = list(range(1, int(n)+1, 1))\npylab.loglog(nlist, er_array, 'go',  label=\"Relative Error\")\npylab.loglog(nlist, ea_array, 'r*',  label=\"Absolute Error\")\npylab.loglog(nlist, epsilon_array,'b--',  label=\"Truncated Error $O(h^4)$\")\n\nleg = pylab.legend(loc=1,labelspacing=0.1)\nltext = leg.get_texts()\npylab.setp(ltext, fontsize='small')\nleg.draw_frame(1)\n\npylab.xlabel('Log (Number of Steps n)')\npylab.ylabel('Log (Error)')\npylab.grid(True)\n\npylab.savefig(\"der_error2.png\")\n\n\n\n\n\nprint \"\\nMachine precision: \", machine_precision()\nprint \"Done!\"\n", "meta": {"hexsha": "416e3a11b976e457b10268b758c4e75756dd7e68", "size": 4207, "ext": "py", "lang": "Python", "max_stars_repo_path": "homework1_integration_differentiation/Q2/derivative_error_estimates.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "homework1_integration_differentiation/Q2/derivative_error_estimates.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework1_integration_differentiation/Q2/derivative_error_estimates.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 25.343373494, "max_line_length": 94, "alphanum_fraction": 0.5887806038, "include": true, "reason": "import numpy", "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.9059898235563418, "lm_q1q2_score": 0.8568863231186882}}
{"text": "#!/usr/bin/python3\n\n\"\"\"\nThe riddle:\nGiven an array of N integer numbers, where all the numbers appear an even \namount of time except for a single number that appears an odd amount of times.\nFind the number that appears an odd amount of times in the array, using O(1) memory space \nand O(N) running time efficiency. \n\nSome examples:\n[2,2,1] --> 1\n[14,14,14,14,4,4,4] --> 4\n[1,2,1,4,2,4,5,1,1] --> 5\n\n\"\"\"\n  \nimport numpy as np\n\nN = 2000\n\ndef solution(arr):\n  \"\"\" \n\tApply xor on all of the numbers, numbers that appear even amount of times cancel themselves\n\tusing xor and the only number that appear an odd amount of times stays. \t\n\n\t@param List[int] arr : the array as described in the riddle documentation.\n\t@return int : the unique odd number.\n  \"\"\"\n  if len(arr) == 0:\n    raise ValueError('Wrong input format')\n  stored = arr[0]   # O(1) space for integer storage\n  for number in arr[1:]:  # linear traverse (O(N))\n    stored ^= number\n  return stored\n \ndef generate_random_test_array(n=N):\n  \"\"\" returns a random array that fits the input requirements and the expected\n      solution for that generated array. \"\"\"\n  assert n > 1\n  half = np.random.randint(100, size=n//2)\n  odd = half[0]\n  full = np.hstack((half, half, [odd]))\n  np.random.shuffle(full)\n  return full, odd\n  \n \ndef test_solution():\n  if not solution([2,2,1]) == 1:\n    return False\n  if not solution([14,14,14,14,4,4,4]) == 4:\n    return False\n  if not solution([1,2,1,4,2,4,5,1,1]) == 5:\n    return False\n  for _ in range(10):\n    arr, expected = generate_random_test_array()\n    if not solution(arr) == expected:\n      return False\n  return True\n\n", "meta": {"hexsha": "68f656bdf29a4ddd062f6c99dfd265ee3468dc65", "size": 1620, "ext": "py", "lang": "Python", "max_stars_repo_path": "Company/find_odd_in_constant_space.py", "max_stars_repo_name": "jason71319jason/Interview-solved", "max_stars_repo_head_hexsha": "42ca93a68475952753d185c325cb55c79e2e55e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:21:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T23:55:15.000Z", "max_issues_repo_path": "Company/find_odd_in_constant_space.py", "max_issues_repo_name": "jason71319jason/Interview-solved", "max_issues_repo_head_hexsha": "42ca93a68475952753d185c325cb55c79e2e55e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 53, "max_issues_repo_issues_event_min_datetime": "2019-10-03T17:16:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-08T12:48:19.000Z", "max_forks_repo_path": "Company/find_odd_in_constant_space.py", "max_forks_repo_name": "jason71319jason/Interview-solved", "max_forks_repo_head_hexsha": "42ca93a68475952753d185c325cb55c79e2e55e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 96, "max_forks_repo_forks_event_min_datetime": "2019-10-03T18:12:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T19:41:06.000Z", "avg_line_length": 27.0, "max_line_length": 92, "alphanum_fraction": 0.6709876543, "include": true, "reason": "import numpy", "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.9059898146721821, "lm_q1q2_score": 0.8568863188682904}}
{"text": "import sympy\nfrom typing import Tuple\n\nx = sympy.symbols('x')\n\n\ndef bisection_root_finder(eqn: sympy.Basic, low: float, high: float, tolerance: float) -> Tuple[float, int, float]:\n    \"\"\"\n    Given a single-variable sympy equation with x as the defined symbol, the low end of an interval, the high end of the interval,\n    and the tolerance, it will calculate the root contained in the interval using the bisection method.\n    It returns a tuple containing the root and the iterations taken\n\n    If it takes more than 100 iterations, it breaks and returns early\n    \"\"\"\n    root = 0\n\n    if eqn.evalf(subs={x: root}) == 0:\n        return root\n    low_answer = eqn.evalf(subs={x: low})\n    high_answer = eqn.evalf(subs={x: high})\n\n    root = (low + high)/2\n    iterations = 0\n\n    while high-low > tolerance:\n        low_answer = eqn.evalf(subs={x: low})\n        high_answer = eqn.evalf(subs={x: high})\n\n        if low_answer*high_answer >= 0:  # They're both on the same side of the axis, this is an issue\n            return None\n        else:\n            mid = (low+high)/2\n            root = mid\n            if high_answer * eqn.evalf(subs={x: mid}) >= 0:\n                high = mid\n            else:\n                low = mid\n        iterations += 1\n        if iterations > 100:\n            break\n    return root, iterations\n\n\ndef newton_raphson_root_finder(equation: sympy.Basic, first_guess: float, tolerance: float) -> Tuple[float, int]:\n    \"\"\"\n    Given a single-variable sympy equation with x as the defined symbol, an initial guess, and a tolerance,\n    this function will return a tuple containing the root and the iterations taken to find the root.\n    It uses the Newton-Raphson method to find the root.\n    \"\"\"\n    error = 1_000  # Starting with a high initial error\n    x_o = first_guess\n    f = equation\n    f_prime = sympy.diff(equation, x)\n    iterations = 0\n    while error > tolerance:\n        root = x_o - f.evalf(subs={x: x_o}, chop=True) / f_prime.evalf(subs={x: x_o}, chop=True)\n        error = abs(root - x_o)\n        x_o = root\n        iterations += 1\n    return root, iterations\n\n\ndef secant_root_finder(eqn: sympy.Basic, x0: float, x1: float, tolerance: float) -> Tuple[float, int]:\n    \"\"\"\n    Given a sympy equation with x as the symbol, two initial guesses on the x-axis and a tolerance,\n    It will find the root using the secant method\n\n    Returns tuple containing root, number of iterations taken\n    \"\"\"\n    error = 1_000  # High initial error\n    iterations = 0\n\n    while error > tolerance:\n        # Calculating slope of the line between the two points\n        slope = (eqn.evalf(subs={x: x1}) - eqn.evalf(subs={x: x0})) / (x1 - x0)\n\n        # Calculating the next point\n        root = x0 - ((eqn.evalf(subs={x: x0}))/slope)\n\n        # Prep for next iteration\n        error = abs(x0 - root)\n        x0 = x1\n        x1 = root\n        iterations += 1\n    return root, iterations\n", "meta": {"hexsha": "e07a0497e95d411cf8ad0502abcc4e24a788601b", "size": 2916, "ext": "py", "lang": "Python", "max_stars_repo_path": "rootfinding.py", "max_stars_repo_name": "janine9vn/NumericalMethods", "max_stars_repo_head_hexsha": "1299bcb96cab2648203e8a9956d0a2caef407782", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rootfinding.py", "max_issues_repo_name": "janine9vn/NumericalMethods", "max_issues_repo_head_hexsha": "1299bcb96cab2648203e8a9956d0a2caef407782", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rootfinding.py", "max_forks_repo_name": "janine9vn/NumericalMethods", "max_forks_repo_head_hexsha": "1299bcb96cab2648203e8a9956d0a2caef407782", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-26T17:26:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-28T08:47:21.000Z", "avg_line_length": 33.9069767442, "max_line_length": 130, "alphanum_fraction": 0.6258573388, "include": true, "reason": "import sympy", "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768144, "lm_q2_score": 0.9059898121338507, "lm_q1q2_score": 0.8568863150834494}}
{"text": "from numpy import random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\n### Defining theta\ntheta = math.pi/4\n\n### Generates count number of random values in the range [0, 1]\ndef getU(count):\n\tu = []\n\tfor i in range(count):\n\t\tkey = random.rand()\n\t\tu.append(key)\n\n\treturn u\n\ndef getX(u):\n\tx = []\n\tfor t in u:\n\t\tres = 0.50 - 0.50*math.cos(math.pi*t)\n\t\tx.append(res)\n\t\n\treturn x\n\ndef getSampleMeanVariance(x):\n\tsum = 0.00\n\tfor i in x:\n\t\tsum += i\n\n\tavg = sum/(len(x))\n\n\tcnt = 0.00\n\tfor i in x:\n\t\tcnt += (i-avg)**2\n\n\tvariance = cnt/(len(x)-1)\n\treturn avg, variance\n\ndef plotCDF(data):\n\tdata_size = len(data)\n\n\tdata_set = sorted(set(data))\n\tbins = np.append(data_set, data_set[-1]+1)\n\n\tcounts, bin_edges = np.histogram(data, bins=bins, density=False)\n\n\tcounts = counts.astype(float)/data_size\n\n\tcdf = np.cumsum(counts)\n\n\tplt.plot(bin_edges[0:-1], cdf, linestyle='--', marker='o', color='b')\n\tplt.ylim((0, 1))\n\tplt.ylabel(\"CDF\")\n\tplt.grid(True)\n\n\tplt.show()\n\n# Plots y = (2/pi) arc sin(root(x))\ndef plotActualDistributionFunction():\n\tin_array = np.linspace(-1.00, 1.00, 10000) \n\tout_array = np.arcsin(in_array) \n\t  \n\t# print(\"in_array : \", in_array) \n\t# print(\"\\nout_arraywith arcsin : \", out_array) \n\t  \n\t# red for numpy.arcsin() \n\tplt.plot(in_array, out_array, \n\t            color = 'blue', marker = \"*\") \n\t              \n\tplt.title(\"Y = F(x)\") \n\tplt.xlabel(\"X\") \n\tplt.ylabel(\"Y\") \n\tplt.show() \n\ndef execute(cnt):\n\tprint(\"For input size of : \" + str(cnt))\n\tu = getU(cnt) \n\tu.sort()\n\t# print(u)\n\tx = getX(u)\n\t# print(x) \n\n\tsMean, sVariance = getSampleMeanVariance(x)\n\tprint(\"Sample Mean: \" + str(sMean)) \n\tprint(\"Sample Variance: \" + str(sVariance)) \n\tprint()\n\tplotCDF(x)\n\ndef main():\n\tplotActualDistributionFunction()\n\n\texecute(10)\n\texecute(100)\n\texecute(1000)\n\texecute(10000)\n\texecute(100000)\n\nif __name__ == '__main__':\n\tmain()\n\n\n\n\n\n\n", "meta": {"hexsha": "f46d97f3a2a9b1a2116e65d99395753c30566b98", "size": 1847, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab 02/180123019_Jay_Sabale_q3.py", "max_stars_repo_name": "ElProfesor18/MA-323_Monte_Carlo_Simulation", "max_stars_repo_head_hexsha": "24efd6ba1d50b00100d15ec2ef5d3fc5217f93a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab 02/180123019_Jay_Sabale_q3.py", "max_issues_repo_name": "ElProfesor18/MA-323_Monte_Carlo_Simulation", "max_issues_repo_head_hexsha": "24efd6ba1d50b00100d15ec2ef5d3fc5217f93a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab 02/180123019_Jay_Sabale_q3.py", "max_forks_repo_name": "ElProfesor18/MA-323_Monte_Carlo_Simulation", "max_forks_repo_head_hexsha": "24efd6ba1d50b00100d15ec2ef5d3fc5217f93a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.261682243, "max_line_length": 70, "alphanum_fraction": 0.6329182458, "include": true, "reason": "import numpy,from numpy", "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.9161096221783882, "lm_q1q2_score": 0.8568799426899668}}
{"text": "# -*- coding:utf-8 -*-\n# =========================================================================== #\n# Project : MLStudio                                                          #\n# File    : \\regression.py                                                    #\n# Python  : 3.8.3                                                             #\n# --------------------------------------------------------------------------- #\n# Author  : John James                                                        #\n# Company : nov8.ai                                                           #\n# Email   : jjames@nov8.ai                                                    #\n# URL     : https://github.com/nov8ai/MLStudio                                #\n# --------------------------------------------------------------------------- #\n# Created       : Thursday, July 16th 2020, 2:25:57 am                        #\n# Last Modified : Thursday, July 16th 2020, 2:25:58 am                        #\n# Modified By   : John James (jjames@nov8.ai)                                 #\n# --------------------------------------------------------------------------- #\n# License : BSD                                                               #\n# Copyright (c) 2020 nov8.ai                                                  #\n# =========================================================================== #\nimport math\nimport numpy as np\n\nfrom mlstudio.supervised.metrics.base import BaseRegressionMetric\n# --------------------------------------------------------------------------- #\nclass ResidualSumSquaredError(BaseRegressionMetric):    \n    \"\"\"Computes sum squared residuals given\"\"\"\n\n    _mode  = 'min'\n    _code = 'SSR'\n    _name  = 'residual_sum_squared_error'\n    _label  = \"Residual Sum Squared Error\"\n    \n    _best  = np.min\n    _better  = np.less\n    _worst  = np.Inf\n    _epsilon_factor  = -1\n\n    def __call__(self, y, y_pred, *args, **kwargs):\n        e = y - y_pred\n        return np.sum(e**2)  \n\nclass TotalSumSquaredError(BaseRegressionMetric):\n    \"\"\"Computes total sum of squares\"\"\"\n\n    \n    _mode  = 'min'\n    _code = \"SST\"\n    _name  = 'total_sum_squared_error'\n    _label  = \"Total Sum Squared Error\"\n    \n    _best  = np.min\n    _better  = np.less\n    _worst  = np.Inf\n    _epsilon_factor  = -1\n\n    \n    def __call__(self, y, y_pred, *args, **kwargs):\n        y_avg = np.mean(y)\n        e = y-y_avg                \n        return np.sum(e**2)\n\nclass R2(BaseRegressionMetric):\n    \"\"\"Computes coefficient of determination.\"\"\"\n\n    \n    _mode  = 'max'   \n    _code = \"R2\"\n    _name  = 'R2'\n    _label  = 'Coefficient of Determination (R2)'\n    \n    _best  = max\n    _better  = np.greater\n    _worst  = -np.Inf\n    _epsilon_factor  = 1\n\n    \n    def __call__(self, y, y_pred, *args, **kwargs):\n        self._ssr = ResidualSumSquaredError()\n        self._sst = TotalSumSquaredError()\n        r2 = 1 - (self._ssr(y, y_pred)/self._sst(y, y_pred))     \n        return r2\n\n\nclass AdjustedR2(BaseRegressionMetric):\n    \"\"\"Computes adjusted coefficient of determination.\"\"\"\n\n    \n    _mode  = 'max'   \n    _code = \"AR2\"\n    _name  = 'adjusted_r2'\n    _label  = \"Adjusted R2\"\n    \n    _best  = max\n    _better  = np.greater\n    _worst  = -np.Inf\n    _epsilon_factor  = 1\n\n    \n    def __call__(self, y, y_pred, n_features, *args, **kwargs):\n        r2_scorer = R2()\n        r2 = r2_scorer(y, y_pred)\n        n = y.shape[0]\n        p = n_features\n        ar2 = 1 - (1 - r2) * (n-1) / (n-p-1)\n        return ar2\n\nclass PercentVarianceExplained(BaseRegressionMetric):\n    \"\"\"Computes proportion of variance explained.\"\"\"\n\n    \n    _mode  = 'max'\n    _code = \"PVE\"\n    _name  = 'percent_variance_explained'\n    _label  = \"Percent Variance Explained\"\n    \n    _best  = max\n    _better  = np.greater\n    _worst  = -np.Inf\n    _epsilon_factor  = 1\n\n    \n    def __call__(self, y, y_pred, *args, **kwargs):\n        var_explained = 1 - (np.var(y-y_pred) / np.var(y))\n        return var_explained * 100                   \n\nclass MeanAbsoluteError(BaseRegressionMetric):\n    \"\"\"Computes mean absolute error given data and parameters.\"\"\"\n\n    \n    _mode  = 'min'\n    _code = \"MAE\"\n    _name  = 'mean_absolute_error'\n    _label  = \"Mean Absolute Error\"\n    \n    _best  = np.min\n    _better  = np.less\n    _worst  = np.Inf\n    _epsilon_factor  = -1\n    \n    def __call__(self, y, y_pred, *args, **kwargs):\n        e = abs(y-y_pred)\n        return np.mean(e)\n\n\nclass MeanSquaredError(BaseRegressionMetric):\n    \"\"\"Computes mean squared error given data and parameters.\"\"\"\n\n    \n    _mode  = 'min'\n    _code = \"MSE\"\n    _name  = 'mean_squared_error'\n    _label  = \"Mean Squared Error\"\n    \n    _best  = np.min\n    _better  = np.less\n    _worst  = np.Inf\n    _epsilon_factor  = -1\n    \n    def __call__(self, y, y_pred, *args, **kwargs):        \n        e = y - y_pred\n        return np.mean(e**2)\n\nclass NegativeMeanSquaredError(BaseRegressionMetric):\n    \"\"\"Computes negative mean squared error given data and parameters.\"\"\"\n\n    \n    _mode  = 'max'\n    _code = \"NMSE\"\n    _name  = 'negative_mean_squared_error'\n    _label  = \"Negative Mean Squared Error\"\n    \n    _best  = max\n    _better  = np.greater\n    _worst  = -np.Inf\n    _epsilon_factor  = 1\n\n    \n    def __call__(self, y, y_pred, *args, **kwargs):        \n        e = y - y_pred\n        return -np.mean(e**2)\n\nclass RootMeanSquaredError(BaseRegressionMetric):\n    \"\"\"Computes root mean squared error given data and parameters.\"\"\"\n\n    \n    _mode  = 'min'\n    _code = \"RMSE\"\n    _name  = 'root_mean_squared_error'\n    _label  = \"Root Mean Squared Error\"\n    \n    _best  = np.min\n    _better  = np.less\n    _worst  = np.Inf\n    _epsilon_factor  = -1\n    \n    def __call__(self, y, y_pred, *args, **kwargs):\n        e = y-y_pred\n        return np.sqrt(np.mean(e**2)) \n\nclass NegativeRootMeanSquaredError(BaseRegressionMetric):\n    \"\"\"Computes negative root mean squared error given data and parameters.\"\"\"\n\n    \n    _mode  = 'max'\n    _code = \"NRMSE\"\n    _name  = 'negative_root_mean_squared_error'\n    _label  = \"Negative Root Mean Squared Error\"\n    \n    _best  = max\n    _better  = np.greater\n    _worst  = -np.Inf\n    _epsilon_factor  = 1\n\n    \n    def __call__(self, y, y_pred, *args, **kwargs):\n        e = y-y_pred\n        return -np.sqrt(np.mean(e**2))\n\nclass MeanSquaredLogError(BaseRegressionMetric):\n    \"\"\"Computes mean squared log error given data and parameters.\"\"\"\n\n    \n    _mode  = 'min'\n    _code = \"MSLE\"\n    _name  = 'mean_squared_log_error'\n    _label  = \"Mean Squared Log Error\"\n    \n    _best  = np.min\n    _better  = np.less\n    _worst  = np.Inf\n    _epsilon_factor  = -1\n    \n    def __call__(self, y, y_pred, *args, **kwargs):\n        e = np.log(y+1)-np.log(y_pred+1)\n        y = np.clip(y, 1e-15, 1-1e-15)    \n        y_pred = np.clip(y_pred, 1e-15, 1-1e-15)    \n        e = np.log(y)-np.log(y_pred)\n        return np.mean(e**2)\n\nclass MedianAbsoluteError(BaseRegressionMetric):\n    \"\"\"Computes median absolute error given data and parameters.\"\"\"\n\n    \n    _mode  = 'min'\n    _code = \"MdAE\"\n    _name  = 'median_absolute_error'\n    _label  = \"Median Absolute Error\"\n    \n    _best  = np.min\n    _better  = np.less\n    _worst  = np.Inf\n    _epsilon_factor  = -1\n    \n    def __call__(self, y, y_pred, *args, **kwargs):        \n        return np.median(np.abs(y_pred-y))\n\nclass MeanAbsolutePercentageError(BaseRegressionMetric):\n    \"\"\"Computes mean absolute percentage given data and parameters.\"\"\"\n    _mode  = 'min'\n    _code = \"MAPE\"\n    _name  = 'mean_absolute_percentage_error'\n    _label  = \"Mean Absolute Percentage Error\"\n\n    _best  = np.min\n    _better  = np.less\n    _worst  = np.Inf\n    _epsilon_factor  = -1\n    \n    def __call__(self, y, y_pred, *args, **kwargs):        \n        return 100*np.mean(np.abs((y-y_pred)/y))\n\n", "meta": {"hexsha": "a47c082c07cc3e47962e1e7b49317147fa52278a", "size": 7797, "ext": "py", "lang": "Python", "max_stars_repo_path": "MLStudio/supervised/metrics/regression.py", "max_stars_repo_name": "j2slab/MLStudio", "max_stars_repo_head_hexsha": "7d7c4b1073617968c28f0e496020e4720b552451", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-13T01:07:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-13T01:07:23.000Z", "max_issues_repo_path": "MLStudio/supervised/metrics/regression.py", "max_issues_repo_name": "DecisionScients/MLStudio", "max_issues_repo_head_hexsha": "7d7c4b1073617968c28f0e496020e4720b552451", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-11T22:14:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-11T22:14:42.000Z", "max_forks_repo_path": "MLStudio/supervised/metrics/regression.py", "max_forks_repo_name": "decisionscients/MLStudio", "max_forks_repo_head_hexsha": "7d7c4b1073617968c28f0e496020e4720b552451", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7712177122, "max_line_length": 79, "alphanum_fraction": 0.5176349878, "include": true, "reason": "import numpy", "num_tokens": 2066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154281754899, "lm_q2_score": 0.8933094167058151, "lm_q1q2_score": 0.8568215519653539}}
{"text": "# This pattern is the same for more inputs and weights. Weights and inputs have the same length\n# inputs = [1, 2, 4]\n# weights = [0.2, 0.8, -0.5]\n# bias = 2\n\n# output = inputs[0] * weights[0] + inputs[1] * weights[1] + inputs[2] * weights[2] + bias\n\n# print(output)\n\n\n# With multiple layers\n# inputs = [1, 2, 3, 2.5]\n\n# weights1 = [0.2, 0.8, -0.5, 1]\n# weights2 = [0.5, -0.91, 0.26, -0.5]\n# weights3 = [-0.26, -0.27, 0.17, 0.87]\n\n# bias1 = 2\n# bias2 = 3\n# bias3 = 0.5\n\n# outputs = [\n#     # Neuron 1:\n#     inputs[0] * weights1[0]\n#     + inputs[1] * weights1[1]\n#     + inputs[2] * weights1[2]\n#     + inputs[3] * weights1[3]\n#     + bias1,\n#     # Neuron 2:\n#     inputs[0] * weights2[0]\n#     + inputs[1] * weights2[1]\n#     + inputs[2] * weights2[2]\n#     + inputs[3] * weights2[3]\n#     + bias2,\n#     # Neuron 3:\n#     inputs[0] * weights3[0]\n#     + inputs[1] * weights3[1]\n#     + inputs[2] * weights3[2]\n#     + inputs[3] * weights3[3]\n#     + bias3,\n# ]\n\n# print(outputs)\n\n\n# A more organized way\n# inputs = [1, 2, 3, 2.5]\n# weights = [[0.2, 0.8, -0.5, 1], [0.5, -0.91, 0.26, -0.5], [-0.26, -0.27, 0.17, 0.87]]\n# biases = [2, 3, 0.5]\n\n# # Output of current layer\n# layer_outputs = []\n# # For each neuron\n# for neuron_weights, neuron_bias in zip(weights, biases):\n#     # Zeroed output of given neuron\n#     neuron_output = 0\n#     # For each input and weight to the neuron\n#     for n_input, weight in zip(inputs, neuron_weights):\n#         # Multiply this input by associated weight\n#         # and add to the neuron’s output variable\n#         neuron_output += n_input * weight\n#     # Add bias\n#     neuron_output += neuron_bias\n#     # Put neuron’s result to the layer’s output list\n#     layer_outputs.append(neuron_output)\n\n# print(layer_outputs)\n\n\n# How to calculate a dot product\n# a = [1, 2, 3]\n# b = [2, 3, 4]\n\n# dot_product = a[0] * b[0] + a[1] * b[1] + a[2] * b[2]\n# print(dot_product)\n\n\n# With NumPy\n# import numpy as np\n\n# inputs = [1.0, 2.0, 3.0, 2.5]\n# weights = [0.2, 0.8, -0.5, 1.0]\n# bias = 2.0\n\n\n# outputs = np.dot(weights, inputs) + bias\n\n# print(outputs)\n\n\n# Three neurons\n# import numpy as np\n\n# inputs = [1.0, 2.0, 3.0, 2.5]\n# weights = [[0.2, 0.8, -0.5, 1], [0.5, -0.91, 0.26, -0.5], [-0.26, -0.27, 0.17, 0.87]]\n# biases = [2.0, 3.0, 0.5]\n\n\n# layer_outputs = np.dot(weights, inputs) + biases\n\n# print(layer_outputs)\n\n\n# import numpy as np\n\n# a = [1, 2, 3]\n# print(np.array([a]))\n\n\n# a = [1, 2, 3]\n# print(np.expand_dims(np.array(a), axis=0))\n\n\n# import numpy as np\n\n# a = [1, 2, 3]\n# b = [2, 3, 4]\n\n# a = np.array([a])\n# b = np.array([b]).T\n\n\n# print(np.dot(a, b))\n\n\n# import numpy as np\n\n# inputs = [[1.0, 2.0, 3.0, 2.5], [2.0, 5.0, -1.0, 2.0], [-1.5, 2.7, 3.3, -0.8]]\n# weights = [[0.2, 0.8, -0.5, 1.0], [0.5, -0.91, 0.26, -0.5], [-0.26, -0.27, 0.17, 0.87]]\n# biases = [2.0, 3.0, 0.5]\n\n# layer_outputs = np.dot(inputs, np.array(weights).T) + biases\n\n# print(layer_outputs)\n\n\n# import numpy as np\n# import nnfs\n\n# nnfs.init()\n\n# print(np.random.randn(2, 5))\n# print(np.zeros((2, 5)))\n\n\nimport numpy as np\nimport nnfs\n\nnnfs.init()\n\nn_inputs = 2\nn_neurons = 4\n\nweights = 0.01 * np.random.randn(n_inputs, n_neurons)\nbiases = np.zeros((1, n_neurons))\n\nprint(weights)\nprint(biases)\n", "meta": {"hexsha": "efa0179b4fce3e5546878e38551a6c823de55540", "size": 3213, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapters/2-coding-our-first-neurons/exampels.py", "max_stars_repo_name": "alvarlagerlof/nnfs", "max_stars_repo_head_hexsha": "5d6118b12e459af17db46700b1c3322d4278e4cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/2-coding-our-first-neurons/exampels.py", "max_issues_repo_name": "alvarlagerlof/nnfs", "max_issues_repo_head_hexsha": "5d6118b12e459af17db46700b1c3322d4278e4cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/2-coding-our-first-neurons/exampels.py", "max_forks_repo_name": "alvarlagerlof/nnfs", "max_forks_repo_head_hexsha": "5d6118b12e459af17db46700b1c3322d4278e4cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2075471698, "max_line_length": 95, "alphanum_fraction": 0.5617802677, "include": true, "reason": "import numpy", "num_tokens": 1320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154281754899, "lm_q2_score": 0.8933093946927837, "lm_q1q2_score": 0.8568215308514605}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 16 10:05:07 2019\n\n@author: amandaash\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt \nimport random as rand\n\n#first derivatives\nx = np.arange(-2*np.pi, 2*np.pi, 0.01)\nf_x = np.sin(x)\nf_prime_numpy = np.gradient(f_x, 0.01)\nf_prime = []\n\nfor step in range(len(list(x))):\n    if step >= 0:\n        derivative = (f_x[step]-f_x[step-1])/(x[step]-x[step-1])\n        f_prime.append(derivative)\n    else:\n        continue\nplt.title('first derivative sin(x)')\nplt.plot(x[1:], f_prime[1:], '.', label = 'forward difference', alpha = 0.2, color = 'b')\nplt.plot(x, f_prime_numpy, '.', label = 'numpy', alpha = 0.2, color = 'r')\nplt.plot(x, np.cos(x), '.', label = 'exact', alpha = 0.2, color = 'g')\nplt.legend()\nplt.savefig('first_derivative.pdf')\nplt.show()\n\nerror_forward = (np.cos(x)[1:] - f_prime[1:])/np.cos(x)[1:]\nplt.title('first derivative error forward difference')\nplt.plot(x[1:], error_forward, '.')\nplt.savefig('forward_diff_err.pdf')\nplt.show()\n\nerror_numpy = (np.cos(x) - f_prime_numpy)/(np.cos(x))\nplt.title('first derivative error numpy')\nplt.plot(x[:-1], error_numpy[:-1], '.')\nplt.savefig('grad_err.pdf')\nplt.show()\n\n#second derivatives \nf_prime_prime_numpy = np.gradient(f_prime_numpy, 0.01)\nf_prime_prime = []\nfor step in range(len(list(x))):\n    if step >= 0:\n        derivative = (f_prime[step]-f_prime[step-1])/(x[step]-x[step-1])\n        f_prime_prime.append(derivative)\n    else:\n        continue\nplt.title('second derivative sin(x)')\nplt.plot(x[2:], f_prime_prime[2:], '.', label = 'forward difference', alpha = 0.2, color = 'b')\nplt.plot(x, f_prime_prime_numpy, '.', label = 'numpy', alpha = 0.2, color = 'r')\nplt.plot(x, -np.sin(x), '.', label = 'exact', alpha = 0.2, color = 'g')\nplt.legend()\nplt.savefig('2nd_derivative.pdf')\nplt.show()\n\nerror_forward_2 = (-np.sin(x)[2:] - f_prime_prime[2:])/(-np.sin(x)[2:])\nplt.title('second derivative error forward difference')\nplt.plot(x[2:], error_forward_2, '.')\nplt.savefig('2nd_derivative_err_forward_diff.pdf')\nplt.show()\n\nerror_numpy_2 = (-np.sin(x) - f_prime_prime_numpy)/-np.sin(x)\nplt.title('second derivative error numpy')\nplt.plot(x[1:-2], error_numpy_2[1:-2], '.')\nplt.savefig('2nd_derivative_err_numpy.pdf')\nplt.show()\n\n#random noise\nepsilon_array = []\nfor n in range(len(list(x))):\n    epsilon_array.append(rand.random()*0.001)\nf_x = np.sin(x) + epsilon_array\nf_prime_numpy = np.gradient(f_x, 0.01)\nf_prime = []\n\nfor step in range(len(list(x))):\n    if step >= 0:\n        derivative = (f_x[step]-f_x[step-1])/(x[step]-x[step-1])\n        f_prime.append(derivative)\n    else:\n        continue\nplt.title('first derivative sin(x) + $\\epsilon$')\nplt.plot(x[1:], f_prime[1:], '.', label = 'forward difference', alpha = 0.2, color = 'b')\nplt.plot(x, f_prime_numpy, '.', label = 'numpy', alpha = 0.2, color = 'r')\nplt.plot(x, np.cos(x), '.', label = 'exact', alpha = 0.2, color = 'g')\nplt.legend()\nplt.savefig('noisy_derivative.pdf')\nplt.show()\n\nerror_forward = np.cos(x)[1:] - f_prime[1:]\nplt.title('first derivative error forward difference')\nplt.plot(x[1:], error_forward, '.')\nplt.show()\n\nerror_numpy = np.cos(x) - f_prime_numpy\nplt.title('first derivative error numpy')\nplt.plot(x[:-1], error_numpy[:-1], '.')\nplt.show()\n\n#second derivatives \nf_prime_prime_numpy = np.gradient(f_prime_numpy, 0.01)\nf_prime_prime = []\nfor step in range(len(list(x))):\n    if step >= 0:\n        derivative = (f_prime[step]-f_prime[step-1])/(x[step]-x[step-1])\n        f_prime_prime.append(derivative)\n    else:\n        continue\nplt.title('second derivative sin(x) + $\\epsilon$')\nplt.plot(x[2:], f_prime_prime[2:], '.', label = 'forward difference', alpha = 0.2, color = 'b')\nplt.plot(x, f_prime_prime_numpy, '.', label = 'numpy', alpha = 0.2, color = 'r')\nplt.plot(x, -np.sin(x), '.', label = 'exact', alpha = 0.2, color = 'g')\nplt.legend()\nplt.show()\n\nerror_forward_2 = -np.sin(x)[2:] - f_prime_prime[2:]\nplt.title('second derivative error forward difference')\nplt.plot(x[2:], error_forward_2, '.')\nplt.show()\n\nerror_numpy_2 = -np.sin(x) - f_prime_prime_numpy\nplt.title('second derivative error numpy')\nplt.plot(x[1:-2], error_numpy_2[1:-2], '.')\nplt.show()\n", "meta": {"hexsha": "013d99996bc5bcde1f5fa75c68defcd0cfe5d435", "size": 4185, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week 05/E8.py", "max_stars_repo_name": "aash7871/PHYS-3210", "max_stars_repo_head_hexsha": "7820e85259b5fbc2845feaa1068ef12afc13db77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week 05/E8.py", "max_issues_repo_name": "aash7871/PHYS-3210", "max_issues_repo_head_hexsha": "7820e85259b5fbc2845feaa1068ef12afc13db77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week 05/E8.py", "max_forks_repo_name": "aash7871/PHYS-3210", "max_forks_repo_head_hexsha": "7820e85259b5fbc2845feaa1068ef12afc13db77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-17T01:58:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T01:58:14.000Z", "avg_line_length": 32.1923076923, "max_line_length": 95, "alphanum_fraction": 0.6520908005, "include": true, "reason": "import numpy", "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542794197472, "lm_q2_score": 0.8933093954028816, "lm_q1q2_score": 0.8568215294465409}}
{"text": "import numpy as np\n\nversicolor_petal_length = [4.7, 4.5, 4.9, 4.0,  4.6, 4.5, 4.7, 3.3, 4.6, 3.9, 3.5, 4.2, 4.0,  4.7, 3.6, 4.4, 4.5, 4.1,\n     4.5, 3.9, 4.8, 4.0,  4.9, 4.7, 4.3, 4.4, 4.8, 5.0,  4.5, 3.5, 3.8, 3.7, 3.9, 5.1, 4.5, 4.5,\n     4.7, 4.4, 4.1, 4.0,  4.4, 4.6, 4.0,  3.3, 4.2, 4.2, 4.2, 4.3, 3.0,  4.1]\n\n# Array of differences to mean: differences\ndifference = versicolor_petal_length - np.mean(versicolor_petal_length)\n#print(difference)\n\n# Square the differences: diff_sq\ndiff_sq = difference **2\n\n# Compute the mean square difference: variance_explicit\nvariance_explicit = np.mean(diff_sq)\n\n# Compute the variance using NumPy: variance_np\nvariance_np = np.var(versicolor_petal_length) \n\n# Print the results\nprint(variance_explicit, variance_np)\n\nstandard_dev_exp = np.sqrt(variance_explicit)\nstandard_dev_np = np.std(versicolor_petal_length)\n\nprint(standard_dev_exp, standard_dev_np)", "meta": {"hexsha": "6ff7a3520d07c108fecf89841f0095974d5ea969", "size": 897, "ext": "py", "lang": "Python", "max_stars_repo_path": "Codes/EDA/variance.py", "max_stars_repo_name": "shohan4556/machine-learning-course-notes", "max_stars_repo_head_hexsha": "981f3d6e9861cbee0f4dec45b1d2e6a214d2a051", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-10-12T17:08:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-26T02:54:01.000Z", "max_issues_repo_path": "Codes/EDA/variance.py", "max_issues_repo_name": "shohan4556/machine-learning-course-notes", "max_issues_repo_head_hexsha": "981f3d6e9861cbee0f4dec45b1d2e6a214d2a051", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Codes/EDA/variance.py", "max_forks_repo_name": "shohan4556/machine-learning-course-notes", "max_forks_repo_head_hexsha": "981f3d6e9861cbee0f4dec45b1d2e6a214d2a051", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-10-30T03:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-11T20:53:47.000Z", "avg_line_length": 34.5, "max_line_length": 118, "alphanum_fraction": 0.6867335563, "include": true, "reason": "import numpy", "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452772, "lm_q2_score": 0.8962513772903669, "lm_q1q2_score": 0.8567996039722375}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# OBJECTIVE : The dataset contains detailed attributes for every player registered in the latest edition of FIFA 19 database. Our objective is to create Linear, Multiple and Polynomail Regression models to predict the potential of a player based on several attributes.\n\n# In[88]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt \nimport seaborn as sns\n\n\n# In[89]:\n\n\n# reading dataset \ndata=pd.read_csv(\"../../../input/karangadiya_fifa19/data.csv\")\n\n\n# In[90]:\n\n\n# displaying first 5 rows\ndata.head()\n\n\n# In[91]:\n\n\ndata.shape #(no. of rows, no. of columns)\n\n\n# In[92]:\n\n\ndata.describe()\n\n\n# In[93]:\n\n\n# finding any null values in data\ndata.isnull().any()\n\n\n# #  Linear Regression - Predicting Potential based on Age of the player\n\n# In[94]:\n\n\n# x = Age(independent variable)\nx=data.iloc[:,3] \n\n\n# In[95]:\n\n\nx.head()\n\n\n# In[96]:\n\n\nx.isnull().any()\n\n\n# In[97]:\n\n\n# y = Potential(dependent variable)\ny=data.iloc[:,8]\n\n\n# In[98]:\n\n\ny.head()\n\n\n# In[99]:\n\n\ny.isnull().any()\n\n\n# In[100]:\n\n\nplt.bar(data[\"Age\"],data[\"Potential\"])\nplt.xlabel(\"Age of Player\")\nprint()\n\n\n# In[101]:\n\n\n# splitting data into train and tet set\nfrom sklearn.model_selection import train_test_split\n\n\n# In[102]:\n\n\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=0)\n\n\n# In[103]:\n\n\nfrom sklearn.linear_model import LinearRegression\n\n\n# In[104]:\n\n\n# making object regressor of class LinearRegression\nregressor=LinearRegression()\n\n\n# I was facing errors with fitting the data so we reshape x_train and y_train by first converting them into ndarray.\n\n# In[105]:\n\n\ntype(x_train)\ntype(y_train)\n\n\n# In[106]:\n\n\nx_train=np.array(x_train)\ny_train=np.array(y_train)\n\n\n# In[107]:\n\n\ntype(x_train)\ntype(y_train)\n\n\n# In[108]:\n\n\nx_train=x_train.reshape(-1,1)\ny_train=y_train.reshape(-1,1)\n\n\n# In[109]:\n\n\n# fitting training set into object regressor\nregressor.fit(x_train,y_train)\n\n\n# To avoid error in prediting we reshape x_test also.\n\n# In[110]:\n\n\nx_test=np.array(x_test)\n\n\n# In[111]:\n\n\nx_test=x_test.reshape(-1,1)\n\n\n# In[112]:\n\n\n# Predicting y from test set\ny_pred= regressor.predict(x_test)\n\n\n# In[113]:\n\n\n# Visualising training dataset\nplt.scatter(x_train,y_train,color=\"red\")\nplt.xlabel(\"Age of Player\")\nplt.ylabel(\"Potential of Player\")\nplt.plot(x_train, regressor.predict(x_train),color=\"blue\") # To draw line of regression\nprint()\n\n\n# In[114]:\n\n\n# Visualising test dataset\nplt.scatter(x_test,y_test,color=\"red\")\nplt.xlabel(\"Age of Player\")\nplt.ylabel(\"Potential of Player\")\nplt.plot(x_train, regressor.predict(x_train),color=\"blue\")\nprint()\n\n\n# In[115]:\n\n\n# Finding intercept of linear regression line\nregressor.intercept_\n\n\n# In[116]:\n\n\n# Finding coefficient of linear regression line\nregressor.coef_\n\n\n# In[117]:\n\n\n# Finding mean squared error of linear regression model\nfrom sklearn.metrics import mean_squared_error\n\n\n# In[118]:\n\n\nmean_squared_error(y_test,y_pred)\n\n\n# # Multiple regression - Predicting potential based on age, agility, balance, stamina, strength, composure\n# \n\n# In[119]:\n\n\n# independent variables are - Age, Agility, Balance, stamina, Strength, Composure\nx=data.iloc[:,[3,66,68,71,72,79]]\n\n\n# In[120]:\n\n\nx.head()\n\n\n# In[121]:\n\n\n# checking if there are null values in x and then filling them. \nx.isnull().any()\n\n\n# In[122]:\n\n\nx=x.fillna(method='ffill')\n\n\n# In[123]:\n\n\nx.isnull().any()\n\n\n# In[124]:\n\n\n# dependent variable = Potential\ny=data.iloc[:,8]\n\n\n# In[125]:\n\n\ny.head()\n\n\n# In[126]:\n\n\ny.isnull().any()\n\n\n# In[127]:\n\n\nsns.lineplot(x=\"Potential\", y=\"Age\",data=data,label=\"Age\", ci= None)\nsns.lineplot(x=\"Potential\", y=\"Agility\",data=data,label=\"Agility\", ci= None)\nsns.lineplot(x=\"Potential\", y=\"Balance\",data=data,label=\"Balance\", ci= None)\nsns.lineplot(x=\"Potential\", y=\"Stamina\",data=data,label=\"Stamina\", ci= None)\nsns.lineplot(x=\"Potential\", y=\"Strength\",data=data,label=\"Strength\", ci= None)\nsns.lineplot(x=\"Potential\", y=\"Composure\",data=data,label=\"Composure\", ci= None)\n\n\n# In[128]:\n\n\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)\n\n\n# In[129]:\n\n\nregressor=LinearRegression()\n\n\n# In[130]:\n\n\nregressor.fit(x_train,y_train)\n\n\n# In[131]:\n\n\nregressor.predict(x_test)\n\n\n# In[132]:\n\n\n# Visualising Actual and predicted values of Potential of player\nplt.scatter(y_test,y_pred)\nplt.xlabel(\"Actual Potential\")\nplt.ylabel(\"Predicted Potential\")\nprint()\n\n\n# Seems like the actual and predicted values are very close to each other.\n\n# In[133]:\n\n\nregressor.intercept_\n\n\n# In[134]:\n\n\nregressor.coef_\n\n\n# Backward Elimination - Making optimal regression model by finding the statistical significance of all independent variables\n\n# In[135]:\n\n\n# let us take the significance level (SL)= 0.05\nimport statsmodels.formula.api as sm\n\n\n# In[136]:\n\n\n# fitting all variables in the model\nregressor_OLS=sm.OLS(endog=y,exog=x).fit()\n\n\n# In[137]:\n\n\n# Finding statistical summary of all variables\nregressor_OLS.summary()\n\n\n# As we see all the P- values are less than SL(0.05), that means all the variables are significant and none of them can be removed. \n# t-value shows the statistical significane of each variable.\n# F-static shows us how significant the fit is. \n# Adjusted- R is 0.986 that means our model explains 98.6% variables in dependent variables.\n\n# # Polynomial Regression - Predicting potential based on the age of player\n\n# In[138]:\n\n\n# independent variable= age\nx=data.iloc[:,3]\n\n\n# In[139]:\n\n\nx.head()\n\n\n# In[140]:\n\n\n# dependent variable = potential\ny=data.iloc[:,8]\n\n\n# In[141]:\n\n\ny.head()\n\n\n# In[142]:\n\n\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)\n\n\n# In[143]:\n\n\nx_train=np.array(x_train)\ny_train=np.array(y_train)\n\n\n# In[144]:\n\n\nx_train=x_train.reshape(-1,1)\ny_train=y_train.reshape(-1,1)\n\n\n# In[145]:\n\n\nlin_reg_1=LinearRegression()\n\n\n# In[146]:\n\n\nlin_reg_1.fit(x_train,y_train)\n\n\n# In[147]:\n\n\nx_test=np.array(x_test)\n\n\n# In[148]:\n\n\nx_test=x_test.reshape(-1,1)\n\n\n# In[149]:\n\n\ny_pred_1=lin_reg_1.predict(x_test)\n\n\n# In[150]:\n\n\n# Making polynomail regression model\nfrom sklearn.preprocessing import PolynomialFeatures\n\n\n# In[151]:\n\n\npoly_reg=PolynomialFeatures(degree=3)\n\n\n# In[152]:\n\n\nx=np.array(x)\n\n\n# In[153]:\n\n\nx=x.reshape(-1,1)\n\n\n# In[154]:\n\n\n# Making polynomial matrix of x of degree 3\nx_poly=poly_reg.fit_transform(x)\n\n\n# In[155]:\n\n\nx_poly\n\n\n# In[156]:\n\n\nx_poly_train,x_poly_test,y_train,y_test=train_test_split(x_poly,y,test_size=0.2, random_state=42)\n\n\n# In[157]:\n\n\n# Making another object to fit polynomial set\nlin_reg_2=LinearRegression()\n\n\n# In[158]:\n\n\nlin_reg_2.fit(x_poly_train,y_train)\n\n\n# In[159]:\n\n\ny_pred_2=lin_reg_2.predict(x_poly_test)\n\n\n# In[160]:\n\n\n# Visualizing Linear Regression Model\nplt.scatter(x_test,y_test,color='red')\nplt.xlabel(\"Age of Player\")\nplt.ylabel(\"Potential of Player\")\nplt.title(\"Linear Regression Curve \")\nplt.plot(x_train,lin_reg_1.predict(x_train),color='blue')\nprint()\n\n\n# In[161]:\n\n\n# Visualizing Polynomial Regression Model\nplt.scatter(x_test,y_test,color='red')\nplt.xlabel(\"Age of Player\")\nplt.ylabel(\"Potential of Player\")\nplt.title(\"Polynomial Regression Curve \")\nplt.plot(x_train,lin_reg_2.predict(poly_reg.fit_transform(x_train)),color='blue')\nprint()\n\n\n# In[162]:\n\n\nmean_squared_error(y_test,y_pred_2)\n\n\n# We can see the mean squared error of polynomail regression model < mean squared error of linear regression model. So polynomail regression model is more accurate.\n", "meta": {"hexsha": "4f11ee7416c953586a41f57e9a0d3523675fb21e", "size": 7355, "ext": "py", "lang": "Python", "max_stars_repo_path": "relancer-exp/original_notebooks/karangadiya_fifa19/fifa-2019-regression-model.py", "max_stars_repo_name": "Chenguang-Zhu/relancer", "max_stars_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-05T22:27:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T22:27:49.000Z", "max_issues_repo_path": "relancer-exp/original_notebooks/karangadiya_fifa19/fifa-2019-regression-model.py", "max_issues_repo_name": "Chenguang-Zhu/relancer", "max_issues_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "relancer-exp/original_notebooks/karangadiya_fifa19/fifa-2019-regression-model.py", "max_forks_repo_name": "Chenguang-Zhu/relancer", "max_forks_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.5701107011, "max_line_length": 268, "alphanum_fraction": 0.7118966689, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 1940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813551535005, "lm_q2_score": 0.8962513738264114, "lm_q1q2_score": 0.8567996029087593}}
{"text": "import numpy as np\r\nimport scipy as sp\r\nfrom scipy import spatial\r\n\r\n\r\ndef paired_points_matching(source, target):\r\n    \"\"\"\r\n    Calculates the transformation T that maps the source to the target\r\n    :param source: A N x 3 matrix with N 3D points\r\n    :param target: A N x 3 matrix with N 3D points\r\n    :return:\r\n        T: 4x4 transformation matrix mapping source onto target\r\n        R: 3x3 rotation matrix part of T\r\n        t: 1x3 translation vector part of T\r\n    \"\"\"\r\n\r\n    T = np.eye(4)\r\n    R = np.eye(3)\r\n    t = np.zeros((1, 3))\r\n\r\n    N = source.shape[0]\r\n\r\n    centroidSource = np.mean(source, axis=0)\r\n    centroidTarget = np.mean(target, axis=0)\r\n\r\n    srcCentrAlign = source - np.tile(centroidSource, (N, 1))\r\n    trgCentrAlign = target - np.tile(centroidTarget, (N, 1))\r\n\r\n    covMatrix = np.dot(srcCentrAlign.T, trgCentrAlign)\r\n\r\n    uMat, sMat, vMat = np.linalg.svd(covMatrix)\r\n\r\n    R = np.dot(vMat.T, uMat.T)\r\n\r\n    t = - (np.dot(R, centroidSource)) + centroidTarget\r\n\r\n    T[:3, :3] = R\r\n    T[:3, 3] = t\r\n\r\n    return T, R, t\r\n\r\n\r\ndef find_nearest_neighbor(src, dst):\r\n    \"\"\"\r\n    Finds the nearest neighbor of every point in src in dst\r\n    :param src: A N x 3 point cloud\r\n    :param dst: A N x 3 point cloud\r\n    :return: the\r\n    \"\"\"\r\n    tree = sp.spatial.KDTree(dst)\r\n    distance, index = tree.query(src)\r\n\r\n    return distance, index\r\n\r\n\r\ndef icp(source, target, init_pose=None, max_iterations=1000, tolerance=0.0001):\r\n    \"\"\"\r\n    Iteratively finds the best transformation that mapps the source points onto the target\r\n    :param source: A N x 3 point cloud\r\n    :param target: A N x 3 point cloud\r\n    :param init_pose: A 4 x 4 transformation matrix for the initial pose\r\n    :param max_iterations: default 10\r\n    :param tolerance: maximum allowed error\r\n        :return: A 4 x 4 rigid transformation matrix mapping source to target\r\n            the distances and the error\r\n    \"\"\"\r\n    # T = np.eye(4)\r\n    # distances = 0\r\n    # error = 0\r\n\r\n    # Your code goes here\r\n\r\n    src_init = np.dot(init_pose[:3, :3], source.T).T\r\n    src_init = src_init + np.tile(init_pose[:3, 3], (source.shape[0], 1))\r\n\r\n    tmp_trg = np.zeros_like(source)\r\n\r\n    if init_pose is None:\r\n        T = np.eye(4)\r\n    else:\r\n        T = init_pose\r\n\r\n    tmp_tol = np.inf\r\n    error = np.inf\r\n\r\n    k = 0\r\n\r\n    while tmp_tol > tolerance and k < max_iterations:\r\n        distance, idx = find_nearest_neighbor(src_init, target)\r\n        for ii, el in enumerate(idx):\r\n            tmp_trg[ii] = target[el]\r\n\r\n        T_tmp, R_tmp, t_tmp = paired_points_matching(src_init, tmp_trg)\r\n\r\n        src_init = np.dot(R_tmp, src_init.T).T\r\n        src_init = src_init + np.tile(t_tmp, (source.shape[0], 1))\r\n        T = np.dot(T_tmp, T)\r\n\r\n        err_tmp = error\r\n        error = np.sum(distance) / distance.shape[0]\r\n        error = np.sqrt(error)\r\n        tmp_tol = err_tmp - error\r\n\r\n        k += 1\r\n\r\n    print(\"Iterations: \", k)\r\n    return T, distance, error\r\n\r\n\r\ndef get_initial_pose(template_points, target_points):\r\n    \"\"\"\r\n    Calculates an initial rough registration\r\n    (Optionally you can also return a hand picked initial pose)\r\n    :param source:\r\n    :param target:\r\n    :return: A transformation matrix\r\n    \"\"\"\r\n    T = np.eye(4)\r\n\r\n    # Your code goes here\r\n\r\n    centr_tmpl = np.mean(template_points, axis=0)\r\n    centr_target = np.mean(target_points, axis=0)\r\n    t = centr_target - centr_tmpl\r\n\r\n    T[:3, 3] = t\r\n\r\n    return T\r\n", "meta": {"hexsha": "347b4d54a3a9876af0f8f72b40edf00aa52ea8d2", "size": 3462, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignments/registration/registration.py", "max_stars_repo_name": "nibill/BME-CAS", "max_stars_repo_head_hexsha": "7c7df4f1fbdd934dac0c07fb153df5957adba4cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignments/registration/registration.py", "max_issues_repo_name": "nibill/BME-CAS", "max_issues_repo_head_hexsha": "7c7df4f1fbdd934dac0c07fb153df5957adba4cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignments/registration/registration.py", "max_forks_repo_name": "nibill/BME-CAS", "max_forks_repo_head_hexsha": "7c7df4f1fbdd934dac0c07fb153df5957adba4cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8372093023, "max_line_length": 91, "alphanum_fraction": 0.6071634893, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.8962513696696647, "lm_q1q2_score": 0.8567995921909908}}
{"text": "import numpy as np\nfrom .integrate import Integrate\n\nclass Simpson(Integrate):\n    \"\"\"\n    Approximate the integral of f(x) from a to b by Simpson's rule.\n\n    Simpson's rule approximates the integral of f(x) dx by the sum:\n    (dx/3) sum(f(x_{2i-2} + 4f(x_{2i-1}) + f(x_{2i})) from i = 1 to N/2 where N is the number of periods.\n    dx = (b - a)/N\n    x_i = a + i*dx\n\n    Parameters\n    ----------\n    f : function\n        A single variable function f(x), ex: lambda x:np.exp(x**2)\n    \"\"\"\n    \n    \n    def __init__(self, f):\n        Integrate.__init__(self, f)\n        self.N = 250\n        \n        \n    def compute_integral(self, a, b, N=250):\n        \"\"\"\n        Parameters\n        ----------\n        a , b : numbers\n        Interval of integration [a,b] defult to [-1,1]\n        \n        N : even integer\n        Number of sub-intervals of [a,b]\n\n        Returns\n        -------\n        float\n            Approximation of the integral of f(x) from a to b using\n            Simpson's rule with N subintervals of equal length.\n\n        Examples\n        --------\n        >>> compute_integral(0,1,10), f = lambda x : 3*x**2\n        1.0\n        \"\"\"\n        self.a = a\n        self.b = b\n        self.N = N\n        \n        if self.N % 2 == 1:\n            raise ValueError(\"N must be an even integer.\")\n        dx = (self.b - self.a) / self.N\n        x = np.linspace(self.a, self.b, self.N+1)\n        y = [self.f(i) for i in x]\n        ans = dx/3 * np.sum(y[0:-1:2] + 4*y[1::2] + y[2::2])\n        return ans", "meta": {"hexsha": "39179389d275eac7e62f43f2541147b6e85736ce", "size": 1507, "ext": "py", "lang": "Python", "max_stars_repo_path": "simpson.py", "max_stars_repo_name": "NullOsama/Integrals", "max_stars_repo_head_hexsha": "3cff57c21f8307b7471173ba4c518a97efb100a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-30T18:47:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-30T18:47:38.000Z", "max_issues_repo_path": "simpson.py", "max_issues_repo_name": "NullOsama/Integrals", "max_issues_repo_head_hexsha": "3cff57c21f8307b7471173ba4c518a97efb100a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simpson.py", "max_forks_repo_name": "NullOsama/Integrals", "max_forks_repo_head_hexsha": "3cff57c21f8307b7471173ba4c518a97efb100a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9107142857, "max_line_length": 105, "alphanum_fraction": 0.4943596549, "include": true, "reason": "import numpy", "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102514755852, "lm_q2_score": 0.8856314813647587, "lm_q1q2_score": 0.8567689741017762}}
{"text": "import math\nimport numpy as np \n\ndef basic_sigmoid(x):\n    \"\"\"\n    Compute sigmoid of x.\n\n    Arguments:\n    x -- A scalar\n\n    Return:\n    s -- sigmoid(x)\n    \"\"\"\n    \n    s = 1 / (1+math.exp(-x))\n    \n    return s\n\n\ndef sigmoid(x):\n    \"\"\"\n    Compute the sigmoid of x\n\n    Arguments:\n    x -- A scalar or numpy array of any size\n\n    Return:\n    s -- sigmoid(x)\n    \"\"\"\n    \n    s = 1 / (1+np.exp(-x))\n    \n    return s    \n\n\ndef sigmoid_derivative(x):\n    \"\"\"\n    Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x.\n    You can store the output of the sigmoid function into variables and then use it to calculate the gradient.\n    \n    Arguments:\n    x -- A scalar or numpy array\n\n    Return:\n    ds -- Your computed gradient.\n    \"\"\"\n    \n    s = sigmoid(x) \n    ds =s * (1 - s)\n    \n    return ds\n\ndef image2vector(image):\n    \"\"\"\n    Argument:\n    image -- a numpy array of shape (length, height, depth)\n    \n    Returns:\n    v -- a vector of shape (length*height*depth, 1)\n    \"\"\"\n    \n    v = image.reshape((image.shape[0]*image.shape[1]*image.shape[2], 1))\n    \n    return v\n\ndef normalizeRows(x):\n    \"\"\"\n    Implement a function that normalizes each row of the matrix x (to have unit length).\n    \n    Argument:\n    x -- A numpy matrix of shape (n, m)\n    \n    Returns:\n    x -- The normalized (by row) numpy matrix. You are allowed to modify x.\n    \"\"\"\n    \n    x_norm = np.linalg.norm(x, ord = 2, axis = 1, keepdims = True)\n    \n    # Divide x by its norm.\n    x = x / x_norm\n    \n    return x    \n\ndef softmax(x):\n    \"\"\"Calculates the softmax for each row of the input x.\n\n    Your code should work for a row vector and also for matrices of shape (n, m).\n\n    Argument:\n    x -- A numpy matrix of shape (n,m)\n\n    Returns:\n    s -- A numpy matrix equal to the softmax of x, of shape (n,m)\n    \"\"\"\n    \n    # Apply exp() element-wise to x.\n    x_exp = np.exp(x)\n\n    # Create a vector x_sum that sums each row of x_exp. \n    x_sum =  np.sum(x_exp, axis = 1, keepdims = True)\n    \n    # Compute softmax(x) by dividing x_exp by x_sum. \n    s = x_exp / x_sum\n    \n    return s    \n\ndef any():\n    x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]\n    x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]\n\n    ### VECTORIZED DOT PRODUCT OF VECTORS ###\n    dot = np.dot(x1,x2)\n\n    ### VECTORIZED OUTER PRODUCT ###\n    outer = np.outer(x1,x2)\n\n    ### VECTORIZED ELEMENTWISE MULTIPLICATION ###\n    mul = np.multiply(x1,x2)\n\n    ### VECTORIZED GENERAL DOT PRODUCT ###\n    W = np.random.rand(3,len(x1))\n    dot = np.dot(W,x1)\n\ndef L1(yhat, y):\n    \"\"\"\n    Arguments:\n    yhat -- vector of size m (predicted labels)\n    y -- vector of size m (true labels)\n    \n    Returns:\n    loss -- the value of the L1 loss function defined above\n    \"\"\"\n    \n    loss =  np.sum(np.abs(yhat-y))\n    \n    return loss\n\ndef L2(yhat, y):\n    \"\"\"\n    Arguments:\n    yhat -- vector of size m (predicted labels)\n    y -- vector of size m (true labels)\n    \n    Returns:\n    loss -- the value of the L2 loss function defined above\n    \"\"\"\n    \n    loss = sum((y-yhat)**2)\n    \n    return loss\n\n# GRADED FUNCTION: propagate\n\ndef propagate(w, b, X, Y):\n    \"\"\"\n    Implement the cost function and its gradient for the propagation explained above\n\n    Arguments:\n    w -- weights, a numpy array of size (num_px * num_px * 3, 1)\n    b -- bias, a scalar\n    X -- data of size (num_px * num_px * 3, number of examples)\n    Y -- true \"label\" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples)\n\n    Return:\n    cost -- negative log-likelihood cost for logistic regression\n    dw -- gradient of the loss with respect to w, thus same shape as w\n    db -- gradient of the loss with respect to b, thus same shape as b\n    \n    Tips:\n    - Write your code step by step for the propagation. np.log(), np.dot()\n    \"\"\"\n    \n    m = X.shape[1]\n    \n    A = sigmoid(np.dot(w.T,X) + b)                         \n    cost = -1 / m * np.sum(Y*np.log(A)+(1-Y)*np.log(1-A), axis = 1, keepdims = True)\n    \n    dw = 1 / m * np.dot(X,(A-Y).T)\n    db = 1 / m * np.sum(A-Y)\n   \n    assert(dw.shape == w.shape)\n    assert(db.dtype == float)\n    cost = np.squeeze(cost)\n    assert(cost.shape == ())\n    \n    grads = {\"dw\": dw,\n             \"db\": db}\n    \n    return grads, cost\n\n\n    # GRADED FUNCTION: optimize\n\ndef optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):\n    \"\"\"\n    This function optimizes w and b by running a gradient descent algorithm\n    \n    Arguments:\n    w -- weights, a numpy array of size (num_px * num_px * 3, 1)\n    b -- bias, a scalar\n    X -- data of shape (num_px * num_px * 3, number of examples)\n    Y -- true \"label\" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples)\n    num_iterations -- number of iterations of the optimization loop\n    learning_rate -- learning rate of the gradient descent update rule\n    print_cost -- True to print the loss every 100 steps\n    \n    Returns:\n    params -- dictionary containing the weights w and bias b\n    grads -- dictionary containing the gradients of the weights and bias with respect to the cost function\n    costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve.\n    \n    Tips:\n    You basically need to write down two steps and iterate through them:\n        1) Calculate the cost and the gradient for the current parameters. Use propagate().\n        2) Update the parameters using gradient descent rule for w and b.\n    \"\"\"\n    \n    costs = []\n    \n    for i in range(num_iterations):\n        \n        grads, cost = propagate(w, b, X, Y)\n        \n        dw = grads[\"dw\"]\n        db = grads[\"db\"]\n        \n        w = w - learning_rate * dw\n        b = b - learning_rate * db\n        \n        if i % 100 == 0:\n            costs.append(cost)\n        \n        if print_cost and i % 100 == 0:\n            print (\"Cost after iteration %i: %f\" %(i, cost))\n    \n    params = {\"w\": w,\n              \"b\": b}\n    \n    grads = {\"dw\": dw,\n             \"db\": db}\n    \n    return params, grads, costs\n\n    def predict(w, b, X):\n    '''\n    Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)\n    \n    Arguments:\n    w -- weights, a numpy array of size (num_px * num_px * 3, 1)\n    b -- bias, a scalar\n    X -- data of size (num_px * num_px * 3, number of examples)\n    \n    Returns:\n    Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X\n    '''\n    \n    m = X.shape[1]\n    Y_prediction = np.zeros((1,m))\n    w = w.reshape(X.shape[0], 1)\n    \n    # Compute vector \"A\" predicting the probabilities of a cat being present in the picture\n    A = sigmoid(np.dot(w.T,X) + b)\n    \n    \n    for i in range(A.shape[1]):\n            \n        Y_prediction[0,i] = np.where(A[0,i]>0.5,1,0)\n                \n    \n    assert(Y_prediction.shape == (1, m))\n    \n    return Y_prediction", "meta": {"hexsha": "97ea9ffef8fd49a580ded669a1dd10014162c433", "size": 6957, "ext": "py", "lang": "Python", "max_stars_repo_path": "math/math.py", "max_stars_repo_name": "donutloop/machine_learning_examples", "max_stars_repo_head_hexsha": "46192a57e2dd194925ae76d6bfb169cd2af142dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-10-08T18:24:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-08T18:24:40.000Z", "max_issues_repo_path": "math/math.py", "max_issues_repo_name": "donutloop/machine_learning_examples", "max_issues_repo_head_hexsha": "46192a57e2dd194925ae76d6bfb169cd2af142dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/math.py", "max_forks_repo_name": "donutloop/machine_learning_examples", "max_forks_repo_head_hexsha": "46192a57e2dd194925ae76d6bfb169cd2af142dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-09T06:50:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-09T06:50:48.000Z", "avg_line_length": 25.5772058824, "max_line_length": 115, "alphanum_fraction": 0.5752479517, "include": true, "reason": "import numpy", "num_tokens": 1910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102524151827, "lm_q2_score": 0.8856314753275017, "lm_q1q2_score": 0.8567689690934092}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport numpy as np\n\n\nclass CoordinatesConverter:\n\n    @staticmethod\n    def cart2pol(x, y):\n        rho = np.sqrt(x ** 2 + y ** 2)\n        phi = np.arctan2(y, x)\n        return rho, phi\n\n    @staticmethod\n    def pol2cart(rho, phi):\n        x = rho * np.cos(phi)\n        y = rho * np.sin(phi)\n        return x, y\n", "meta": {"hexsha": "1403a6ac3f78a0d8aedc5e0201cbb8e4f36c954d", "size": 359, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/coordinates_converter.py", "max_stars_repo_name": "estanislaoledesma/genper", "max_stars_repo_head_hexsha": "5996b8bc199d8cecc74b7f6d03b67a4c356b4beb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-24T20:10:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T21:03:16.000Z", "max_issues_repo_path": "utils/coordinates_converter.py", "max_issues_repo_name": "estanislaoledesma/genper", "max_issues_repo_head_hexsha": "5996b8bc199d8cecc74b7f6d03b67a4c356b4beb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-09-24T19:25:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T00:49:07.000Z", "max_forks_repo_path": "utils/coordinates_converter.py", "max_forks_repo_name": "estanislaoledesma/genper", "max_forks_repo_head_hexsha": "5996b8bc199d8cecc74b7f6d03b67a4c356b4beb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8947368421, "max_line_length": 38, "alphanum_fraction": 0.5292479109, "include": true, "reason": "import numpy", "num_tokens": 107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102580527665, "lm_q2_score": 0.8856314647623016, "lm_q1q2_score": 0.8567689638653477}}
{"text": "import numpy as np\r\nfrom scipy import stats\r\n\r\n# generate data\r\nN = 10\r\na = np.random.randn(N) + 2 # mean 2, variance 1\r\nb = np.random.randn(N) # mean 0, variance 1\r\n\r\n# roll your own t-test:\r\nvar_a = a.var(ddof=1) # unbiased estimator, divide by N-1 instead of N\r\nvar_b = b.var(ddof=1)\r\ns = np.sqrt( (var_a + var_b) / 2 ) # balanced standard deviation\r\nt = (a.mean() - b.mean()) / (s * np.sqrt(2.0/N)) # t-statistic\r\ndf = 2*N - 2 # degrees of freedom\r\np = 1 - stats.t.cdf(np.abs(t), df=df) # one-sided test p-value\r\nprint(\"t:\\t\", t, \"p:\\t\", 2*p) # two-sided test p-value\r\n\r\n# built-in t-test:\r\nt2, p2 = stats.ttest_ind(a, b)\r\nprint(\"t2:\\t\", t2, \"p2:\\t\", p2)\r\n", "meta": {"hexsha": "2ea343880e2546ddfddd77a7e3f2d40f94b60411", "size": 660, "ext": "py", "lang": "Python", "max_stars_repo_path": "udemy/lazyprogrammer/ab-testing-python/ttest.py", "max_stars_repo_name": "balazssimon/ml-playground", "max_stars_repo_head_hexsha": "c2eba497bebc53e5a03807bdd8873c55f0ec73e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "udemy/lazyprogrammer/ab-testing-python/ttest.py", "max_issues_repo_name": "balazssimon/ml-playground", "max_issues_repo_head_hexsha": "c2eba497bebc53e5a03807bdd8873c55f0ec73e1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "udemy/lazyprogrammer/ab-testing-python/ttest.py", "max_forks_repo_name": "balazssimon/ml-playground", "max_forks_repo_head_hexsha": "c2eba497bebc53e5a03807bdd8873c55f0ec73e1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4285714286, "max_line_length": 71, "alphanum_fraction": 0.6075757576, "include": true, "reason": "import numpy,from scipy", "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102571131692, "lm_q2_score": 0.8856314617436728, "lm_q1q2_score": 0.8567689601129583}}
{"text": "import numpy as np\n\nfrom scipy.linalg import hilbert,lu\n\nn = 10\n\nH = hilbert(10)\n\n#------------------------Q1-----------------------------\nL = np.array([[0. for i in range(n)] for i in range(n)])\nfor i in range(0,n):\n\tL[i][i] = 1.\n\nU = np.array([[0. for i in range(0,n)] for i in range(n)])\nfor i in range(0,n):\n\tfor j in range(0,n):\n\t\tU[i][j] = H[i][j]\n\nfor i in range(n):\n    for j in range(i+1,n):\n        e = np.divide(U[j][i],U[i][i])\n        L[j][i] = e\n        to = np.array(U[i])\n        to = e * to\n        for k in range(n):\n            U[j][k] -= to[k]\n\nprint(\"L\")\nfor i in range(n):\n    for j in range(n):\n        print(\"%.12f\" % L[i][j], end=\" \")\n    print()\nprint(\"\\nU\")\n\nfor i in range(n):\n    for j in range(n):\n        if(i > j):\n            U[i][j] = 0.\n        print(\"%.12f\" % U[i][j], end=\" \")\n    print()\n\n#------------------------Q2-----------------------------\nb = np.array([1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0])\n\ny = np.array([0. for i in range(n)])\nx = np.array([0. for i in range(n)])\n\nfor i in range(n):\n    t = b[i]\n    for j in range(i):\n        t -= y[j] * L[i][j]\n    y[i] = t / L[i][i]\n\nfor i in range(n-1,-1,-1):\n    t = y[i]\n    for j in range(n-1,i-1,-1):\n        t -= x[j] * U[i][j]\n    x[i] = t / U[i][i]\n\nfor i in range(n):\n    print(\"x%2d = %.10f\" % (i+1,x[i]))\n#------------------------Q3------------------------------\n#Determinant of Upper-Triangular is the product of the diagonal components.\n#And, Determinant of Orignal Matrix and Matrix U is same.\n#So, we can obtain determinant by using the Matrix U.\n\ndet = 1.\n\nfor i in range(n):\n    det = np.multiply(det,U[i][i])\n\nprint(\"Det of H = \",det)\n\n#------------------------Q4------------------------------\n#[Hx1,Hx2, ... , Hxn] = [e1,e2, ... ,en]\ninv = [[],[],[],[],[],[],[],[],[],[]]\n\nfor p in range(n):\n    b_inv = np.array([0. for j in range(n)])\n    y_inv = np.array([0. for j in range(n)])\n    x_inv = np.array([0. for j in range(n)])\n    b_inv[p] = 1.\n    for i in range(n):\n        t = b_inv[i]\n        for j in range(i):\n            t -= y_inv[j] * L[i][j]\n        y_inv[i] = t / L[i][i]\n\n    for i in range(n-1,-1,-1):\n        t = y_inv[i]\n        for j in range(n-1,i-1,-1):\n            t -= x_inv[j] * U[i][j]\n        x_inv[i] = t / U[i][i]\n\n    for i in range(n):\n        inv[i].append(x_inv[i])\n\ninv = np.array(inv)\n\nprint(\"H^-1\")\n\nfor i in range(n):\n    for j in range(n):\n        print(\"%18.6f\" % inv[i][j], end=\" \")\n    print()", "meta": {"hexsha": "54c107097a195450131d17adc5ad68ad72a70c02", "size": 2439, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numerial_Analysis/3rd/python/3-3.py", "max_stars_repo_name": "RDCPP/Numerial_Analysis_Backup", "max_stars_repo_head_hexsha": "a28501ec3505584cb3dce41404f28d357ba8039d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numerial_Analysis/3rd/python/3-3.py", "max_issues_repo_name": "RDCPP/Numerial_Analysis_Backup", "max_issues_repo_head_hexsha": "a28501ec3505584cb3dce41404f28d357ba8039d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numerial_Analysis/3rd/python/3-3.py", "max_forks_repo_name": "RDCPP/Numerial_Analysis_Backup", "max_forks_repo_head_hexsha": "a28501ec3505584cb3dce41404f28d357ba8039d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2285714286, "max_line_length": 75, "alphanum_fraction": 0.4362443624, "include": true, "reason": "import numpy,from scipy", "num_tokens": 835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102524151826, "lm_q2_score": 0.8856314617436728, "lm_q1q2_score": 0.8567689559522736}}
{"text": "\n'''\nFinding the best fit linear slope for a dataset example\n'''\n\nfrom statistics import mean\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\n\nstyle.use('fivethirtyeight')\n\n\n# test data\nxs = np.array([1,2,3,4,5,6], dtype=np.float64)\nys = np.array([5,4,6,5,6,7], dtype=np.float64)\n\n\n# generate best fit slope based on averages and square means\ndef best_fit_slope_and_intercept(xs, ys):\n    m = ((mean(xs) * mean(ys)) - mean(xs * ys)) / ((mean(xs) ** 2) - mean(xs ** 2))\n    b = mean(ys) - m*mean(xs)\n\n    return m, b\n\n\n# y = mx + c\nm,b = best_fit_slope_and_intercept(xs, ys)\n\nregression_line = [(m * x) + b for x in xs] # create list of y values\n\n\n# predictions\npredict_x = 8\npredict_y = (m * predict_x) + b\n\n\n# plot\nplt.scatter(xs, ys)\nplt.scatter(predict_x, predict_y, color='g')\nplt.plot(xs, regression_line)\nplt.show()\n", "meta": {"hexsha": "c00bc499d6e4dc7e449723463e969d6e60c6f6d5", "size": 854, "ext": "py", "lang": "Python", "max_stars_repo_path": "Regression/Linear Regression/sklearn/best-fit-line.py", "max_stars_repo_name": "adam-bhaiji/machine-learning", "max_stars_repo_head_hexsha": "4ea97d6f802791077b8a19ccc2678cff8edcb630", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Regression/Linear Regression/sklearn/best-fit-line.py", "max_issues_repo_name": "adam-bhaiji/machine-learning", "max_issues_repo_head_hexsha": "4ea97d6f802791077b8a19ccc2678cff8edcb630", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Regression/Linear Regression/sklearn/best-fit-line.py", "max_forks_repo_name": "adam-bhaiji/machine-learning", "max_forks_repo_head_hexsha": "4ea97d6f802791077b8a19ccc2678cff8edcb630", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8604651163, "max_line_length": 83, "alphanum_fraction": 0.6721311475, "include": true, "reason": "import numpy", "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347912737017, "lm_q2_score": 0.879146761176671, "lm_q1q2_score": 0.8566711907261403}}
{"text": "'''\nDemonstration of how to execute some basic operations:\n    - Root finding\n    - Interpolation\n    - Integration \n    \nShows how the functions in the old \"ClimateUtilities.py\" can be replaced\nwith numpy and scipy routines.\n\nDependencies\n------------\nnumpy, matplotlib, scipy\n\nLicense\n-------\nBSD 3-clause (see https://www.w3.org/Consortium/Legal/2008/03-bsd-license.html)\n\n'''\n\nimport string\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#==============================================\n#---Section: Math utilities-------------------\n#==============================================\n\nif __name__ == '__main__':\n    \n    # Usage Examples:\n    # ===============\n    \n    # 1. Finding roots of a function (replaces the old \"newtSolv\")\n    # ------------------------------------------------------------\n    from scipy.optimize import newton\n    \n    def show_root(initial_guess, root):\n        '''Show initial guess and resulting root value'''\n        print('With initial guess {0}, we get the root {1}.'.format(\n            initial_guess, root) )\n        \n    # Example 1.1: Function without parameters\n    print('--- Example 1 ---')\n    def g(x):\n        return x*x - 1.\n    \n    initial_guess = 2.\n    root = newton(g, initial_guess)\n    show_root(initial_guess, root)\n\n    # Example 1.2: Function with parameters\n    print('--- Example 2 ---')\n    def g(x, a, b):\n        return a*x*x - b\n    \n    initial_guess = 2.\n    a, b = 1, 2\n    root = newton(g, initial_guess, args=(a, b))\n    show_root(initial_guess, root)\n    \n    initial_guess = 1.\n    root = newton(g, initial_guess, args=(a, b))\n    show_root(initial_guess, root)\n        \n    # 2. Interpolation (replaces the old \"interp\" and \"polint\")\n    # ---------------------------------------------------------    \n    from scipy.interpolate import interp1d\n    \n    # Generate some data\n    x = np.linspace(0, 10, num=11, endpoint=True)\n    y = np.cos(-x**2/9.0)\n    xnew = np.linspace(0, 10, num=41, endpoint=True)\n    \n    # Make a \"linear\" and a \"cubic\" interpolation object\n    f = interp1d(x, y)\n    f2 = interp1d(x, y, kind='cubic')\n    \n    # Calculate and plot the interpolated data\n    plt.plot(x, y, 'o', label='data')\n    plt.plot(xnew, f(xnew), '-', label='linear')\n    plt.plot(xnew, f2(xnew),'--', label='cubic')\n    plt.legend()\n    plt.show()\n\n\n    # 3. Romberg Integration (replaces the old \"romberg\")\n    # ---------------------------------------------------\n    from scipy.integrate import romberg\n    \n    # Define a function    \n    def f(x):\n        return x**2        \n    \n    # Integrate the function, from -1 to 2:\n    a, b = -1, 2\n    integral = romberg(f, a, b)\n    \n    print('The integral of f(x) between {0} and {1} is: {2}'.format(a, b, integral))", "meta": {"hexsha": "0b5f19642ab0b8734d0b30d0fea6cb0e9915e00e", "size": 2742, "ext": "py", "lang": "Python", "max_stars_repo_path": "cu_sp/math_demos.py", "max_stars_repo_name": "thomas-haslwanter/planetary_climate", "max_stars_repo_head_hexsha": "04f85820f748af14c24f7874144c93b0523ba712", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-07-04T04:35:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T14:26:30.000Z", "max_issues_repo_path": "cu_sp/math_demos.py", "max_issues_repo_name": "thomas-haslwanter/planetary_climate", "max_issues_repo_head_hexsha": "04f85820f748af14c24f7874144c93b0523ba712", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cu_sp/math_demos.py", "max_forks_repo_name": "thomas-haslwanter/planetary_climate", "max_forks_repo_head_hexsha": "04f85820f748af14c24f7874144c93b0523ba712", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-04T04:37:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-04T04:37:26.000Z", "avg_line_length": 27.9795918367, "max_line_length": 84, "alphanum_fraction": 0.5331874544, "include": true, "reason": "import numpy,from scipy", "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347883040039, "lm_q2_score": 0.8791467548438126, "lm_q1q2_score": 0.8566711819443825}}
{"text": "#! /usr/bin/env python\n\n\"\"\"\nFile: centered_diff.py\nCopyright (c) 2016 Austin Ayers\nLicense: MIT\n\nCourse: PHYS227\nAssignment: 3.18\nDate: Feb 11, 2016\nEmail: ayers111@mail.chapman.edu\nName: Austin Ayers\nDescription: Approxiates many derivatives\n\"\"\"\n\nimport sympy as sp\nimport math\n\ndef quad(x):\n    return (x**2)\ndef exponent(x):\n    return math.exp(x)\ndef exponent2(x):\n    return math.exp(-2*x**2)\ndef cosine(x):\n    return sp.cos(x)\ndef ln(x):\n    return sp.log(x)\n\ndef diff(f,x, h=1E-5):\n    \"\"\"\n    Approximates a derivative of a function at a point\n    \"\"\"\n    return ((f(x+h)-f(x-h))/(2*float(h)))\ndef test_diff():\n    print(diff(quad, 5))\n    assert(diff(quad, 5) - 10 < 0.00001)\n\ndef application():\n    print(\"error of e^x @ (x=0): \" + str(abs(diff(exponent, 0, .01) - 1)))\n    print(\"error of e^(-2x^2) @ (x=0): \" + str(abs(diff(exponent2, 0, .01))))\n    print(\"error of cos(x) @ (x=2pi): \" + str(abs(diff(cosine, 2*sp.pi, .01))))\n    print(\"error of ln(x) @ (x=1): \" + str(abs(diff(ln, 1, .01))))\n", "meta": {"hexsha": "f3b0f644fea616310476d1391e480ae20db1f807", "size": 1006, "ext": "py", "lang": "Python", "max_stars_repo_path": "centered_diff.py", "max_stars_repo_name": "chapman-phys227-2016s/hw-1-C0deMonkee", "max_stars_repo_head_hexsha": "cc83e78f047e08076bd9788b360dd4d163b2adbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "centered_diff.py", "max_issues_repo_name": "chapman-phys227-2016s/hw-1-C0deMonkee", "max_issues_repo_head_hexsha": "cc83e78f047e08076bd9788b360dd4d163b2adbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "centered_diff.py", "max_forks_repo_name": "chapman-phys227-2016s/hw-1-C0deMonkee", "max_forks_repo_head_hexsha": "cc83e78f047e08076bd9788b360dd4d163b2adbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8636363636, "max_line_length": 79, "alphanum_fraction": 0.6093439364, "include": true, "reason": "import sympy", "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.9073122132152183, "lm_q1q2_score": 0.856663198334137}}
{"text": "# -*- coding: utf-8 -*-\nimport numpy as np\nfrom playML.metrics import r2_score\n\nclass SimpleLinearRegression1(object):\n    \"\"\"\n    自己手写的简陋实现简单线性回归算法\n    \"\"\"\n    def __init__(self):\n        self.a_ = None\n        self.b_ = None\n\n    def fit(self, x_train, y_train):\n        \"\"\"\n\n        :param x_train:\n        :param y_train:\n        :return:\n        \"\"\"\n        assert x_train.ndim == 1, 'Simple Linear Regressor can only solve single feature training data.'\n        assert len(x_train) == len(y_train), 'the size of x_train must be equal to the size of y_train'\n\n        x_mean = np.mean(x_train)\n        y_mean = np.mean(y_train)\n\n        # 分子\n        numerator = 0.0\n\n        # 分母\n        denominator = 0.0\n\n        for x_i, y_i in zip(x_train, y_train):\n            numerator += (x_i - x_mean)*(y_i - y_mean)\n            denominator += (x_i - x_mean)**2\n\n        self.a_ = numerator / denominator\n        self.b_ = y_mean - self.a_ * x_mean\n\n        return self\n\n    def predict(self, x_predict):\n        assert x_predict.ndim == 1, 'Simple Linear Regressor can only solve single feature training data.'\n        assert self.a_ is not None and self.b_ is not None, 'must fit before predict'\n        return np.array([self._predict(x) for x in x_predict])\n\n    def _predict(self, x_single):\n        return self.a_ * x_single + self.b_\n\n    def __repr__(self):\n        return 'SimpleLinearRegression1()'\n\n\nclass SimpleLinearRegression2(object):\n    \"\"\"\n    自己手写的简陋实现简单线性回归算法，把for循环改为向量化运算，提升效率\n    \"\"\"\n    def __init__(self):\n        self.a_ = None\n        self.b_ = None\n\n    def fit(self, x_train, y_train):\n        \"\"\"\n\n        :param x_train:\n        :param y_train:\n        :return:\n        \"\"\"\n        assert x_train.ndim == 1, 'Simple Linear Regressor can only solve single feature training data.'\n        assert len(x_train) == len(y_train), 'the size of x_train must be equal to the size of y_train'\n\n        x_mean = np.mean(x_train)\n        y_mean = np.mean(y_train)\n\n        # 分子\n        numerator = (x_train - x_mean).dot(y_train - y_mean)\n\n        # 分母\n        denominator = (x_train - x_mean).dot(x_train - x_mean)\n\n        self.a_ = numerator / denominator\n        self.b_ = y_mean - self.a_ * x_mean\n\n        return self\n\n    def predict(self, x_predict):\n        assert x_predict.ndim == 1, 'Simple Linear Regressor can only solve single feature training data.'\n        assert self.a_ is not None and self.b_ is not None, 'must fit before predict'\n        return np.array([self._predict(x) for x in x_predict])\n\n    def _predict(self, x_single):\n        return self.a_ * x_single + self.b_\n\n    def score(self, x_test, y_test):\n        \"\"\"\n        根据测试数据集x_test和y_test 确定当前模型的准确度\n        :param x_test:\n        :param y_test:\n        :return:\n        \"\"\"\n        y_predict = self.predict(x_test)\n        return r2_score(y_test, y_predict)\n\n    def __repr__(self):\n        return 'SimpleLinearRegression2()'\n\n\nclass SimpleLinearRegression(SimpleLinearRegression2):\n    pass", "meta": {"hexsha": "74eeb13e77dbc978566d4272a62843aa16d8432d", "size": 2991, "ext": "py", "lang": "Python", "max_stars_repo_path": "c2_linear_regression/simple_linear_regression.py", "max_stars_repo_name": "Sea-Monster/MachineLearningClassicAlgorithm", "max_stars_repo_head_hexsha": "2aaad1965e7e4b8659b6296dfe938181825fa259", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2018-04-01T13:28:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T10:53:25.000Z", "max_issues_repo_path": "c2_linear_regression/simple_linear_regression.py", "max_issues_repo_name": "Sea-Monster/MachineLearningClassicAlgorithm", "max_issues_repo_head_hexsha": "2aaad1965e7e4b8659b6296dfe938181825fa259", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c2_linear_regression/simple_linear_regression.py", "max_forks_repo_name": "Sea-Monster/MachineLearningClassicAlgorithm", "max_forks_repo_head_hexsha": "2aaad1965e7e4b8659b6296dfe938181825fa259", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-09-03T23:08:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-10T00:37:06.000Z", "avg_line_length": 27.6944444444, "max_line_length": 106, "alphanum_fraction": 0.604480107, "include": true, "reason": "import numpy", "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.9196425245706047, "lm_q1q2_score": 0.8566125332006215}}
{"text": "import numpy as np\nfrom random import randint\n\nclass Ham_15_11:\n    \"\"\"\n    The class is used for hamming code [15,11,3]\n    \"\"\"\n\n    def __init__(self,sourceCode=None):\n        self._H = np.matrix([[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1],\n                             [0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],\n                             [0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],\n                             [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]])\n        self._G = np.matrix([[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n                             [1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n                             [0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n                             [1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],\n                             [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0],\n                             [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0],\n                             [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0],\n                             [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],\n                             [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0],\n                             [0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0],\n                             [1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1]])\n        self._sourceCode = sourceCode\n        self._codeRes = None\n    \n    def updateSourceCode(self,sourceCode):\n        if not isinstance(sourceCode, str):\n            raise TypeError(\"sourceCode: expected string, but got %r\" % type(sourceCode).__name__)\n        assert len(sourceCode) == 11\n        sourceCode = np.matrix([int(e) for e in list(sourceCode)])\n        self._sourceCode = sourceCode\n\n    def updateCodeRes(self, codeRes):\n        if not isinstance(codeRes, str):\n            raise TypeError(\"codeRes: expected string, but got %r\" % type(codeRes).__name__)\n        assert len(codeRes) == 15\n        codeRes = np.matrix([int(e) for e in list(codeRes)])\n        self._codeRes = codeRes\n    \n    def encode(self):\n        codeRes = self._sourceCode * self._G % 2\n        self._codeRes = codeRes\n        codeRes = codeRes.tolist()[0]\n        codeRes = ''.join([str(e) for e in codeRes])\n        return codeRes\n\n    def decode(self):\n        z = self._H * self._codeRes.T % 2\n        mul = np.matrix([1,2,4,8])\n        error = (mul * z).sum()\n        codeRes = self._codeRes.tolist()[0]\n        if not error == 0:\n            codeRes[error-1] = (codeRes[error-1]+1) % 2\n        codeRes = codeRes[2:3]+codeRes[4:7] + codeRes[8:]\n        return ''.join([str(e) for e in codeRes])\n\nif __name__ == '__main__':\n    ham = Ham_15_11()\n    with open('hamming_15_11.txt','w') as f:\n        for i in range(2**11):\n            sourceCode = bin(i).replace('0b','').rjust(11,'0')\n            sourceCode = sourceCode[::-1]\n            ham.updateSourceCode(sourceCode)\n            codeRes = ham.encode()\n            line = ''.join([sourceCode,', ',codeRes,'\\n'])\n            if i == 2**11-1:\n                line=line[:-1]\n            f.write(line)\n        f.close()\n    \n    #this part used to check decode\n    with open('hamming_15_11.txt', 'r') as f:\n        checkpoint = 0\n        for line in f:\n            codeRes = line.split(' ')[1].replace('\\n','')\n            ham.updateCodeRes(codeRes)\n            expectedAns = line.split(',')[0]\n            ans = ham.decode()\n            if not ans == expectedAns:\n                print('check failed in {} -> {},{} expected'.format(codeRes,ans,expectedAns))\n                exit(-1)\n            checkpoint += 1\n        print('%d points checked, decode test pass!!!' % checkpoint)\n        f.close()\n\n    #this part used to simulate error and check decode\n    with open('hamming_15_11.txt', 'r') as f:\n        checkpoint = 0\n        for line in f:\n            codeRes = line.split(' ')[1].replace('\\n','')\n            codeRes = [int(e) for e in codeRes]\n            errorP = randint(0, 14)\n            codeRes[errorP] = (codeRes[errorP]+1) % 2\n            codeRes = ''.join(str(e) for e in codeRes)\n            ham.updateCodeRes(codeRes)\n            expectedAns = line.split(',')[0]\n            ans = ham.decode()\n            if not ans == expectedAns:\n                print('check failed in {} -> {},{} expected'.format(codeRes,ans,expectedAns))\n                exit(-1)\n            checkpoint += 1\n        print('%d points checked, decode( with one error) test pass!!!' % checkpoint)\n\n\n", "meta": {"hexsha": "9bdb50e4198a7a2595e438576b0ca36783885ffd", "size": 4442, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab2_Chanelcode/MyCode/hamming_15_11.py", "max_stars_repo_name": "xiangsam/Information_Theory_Lab", "max_stars_repo_head_hexsha": "7204965d9693bc9f36f1f5f115a826e619eaa155", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab2_Chanelcode/MyCode/hamming_15_11.py", "max_issues_repo_name": "xiangsam/Information_Theory_Lab", "max_issues_repo_head_hexsha": "7204965d9693bc9f36f1f5f115a826e619eaa155", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab2_Chanelcode/MyCode/hamming_15_11.py", "max_forks_repo_name": "xiangsam/Information_Theory_Lab", "max_forks_repo_head_hexsha": "7204965d9693bc9f36f1f5f115a826e619eaa155", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5140186916, "max_line_length": 98, "alphanum_fraction": 0.4610535795, "include": true, "reason": "import numpy", "num_tokens": 1575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799410139921, "lm_q2_score": 0.888758801595206, "lm_q1q2_score": 0.856567905377094}}
{"text": "\"\"\"Ordinary least squares and related problems.\"\"\"\nfrom typing import Optional\n\nimport numpy as np\n\nfrom optimus.types import Function\n\n\nclass LeastSquares(Function):\n    \"\"\"Ordinary least squares of the form min ||Ax - b||^2.\"\"\"\n\n    is_c2 = True\n\n    def __init__(self, inputs: np.ndarray, targets: np.ndarray):\n        \"\"\"Initialize a least squares problem.\n\n        `inputs` is `A` (i.e. the matrix of features), and targets is\n        `b` (i.e. the vector of observed values).\"\"\"\n        self.inputs = inputs\n        self.targets = targets\n        self._cached_hessian: Optional[np.ndarray] = None\n\n    def __call__(self, parameters: np.ndarray) -> float:\n        difference_vector = self.inputs.dot(parameters) - self.targets\n        return np.dot(difference_vector, difference_vector)\n\n    def gradient(self, parameters: np.ndarray) -> np.ndarray:\n        return 2 * (self.inputs.dot(parameters) - self.targets).T.dot(self.inputs)\n\n    def partial_second_derivative(\n        self, parameters: np.ndarray, first_variable: int, second_variable: int\n    ) -> float:\n        # This is reasonable because the hessian is constant.\n        return self.hessian(parameters)[first_variable, second_variable]\n\n    def hessian(self, parameters: np.ndarray) -> np.ndarray:\n        if self._cached_hessian is None:\n            self._cached_hessian = self.inputs.T.dot(self.inputs)\n        return self._cached_hessian\n", "meta": {"hexsha": "ab64d09f358b8f84510bcffccee92893754c1f6d", "size": 1410, "ext": "py", "lang": "Python", "max_stars_repo_path": "optimus/function/least_squares.py", "max_stars_repo_name": "IanTayler/tao-exercises", "max_stars_repo_head_hexsha": "ecca88175d7716b5dcc0d6184e6e5d59323910a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-09-23T21:53:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T22:21:40.000Z", "max_issues_repo_path": "optimus/function/least_squares.py", "max_issues_repo_name": "IanTayler/tao-exercises", "max_issues_repo_head_hexsha": "ecca88175d7716b5dcc0d6184e6e5d59323910a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimus/function/least_squares.py", "max_forks_repo_name": "IanTayler/tao-exercises", "max_forks_repo_head_hexsha": "ecca88175d7716b5dcc0d6184e6e5d59323910a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.25, "max_line_length": 82, "alphanum_fraction": 0.6787234043, "include": true, "reason": "import numpy", "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350253, "lm_q2_score": 0.8887587949656841, "lm_q1q2_score": 0.8565679017615394}}
{"text": "import numpy as np\n\ndef index(a, weights = None):\n    \"\"\"\n    Compute the Gini Coefficient.\n    Thanks Gaëtan de Menten: https://stackoverflow.com/a/49571213/5890574\n\n    Parameters\n    ----------\n    a : array_like\n        1-D array containing the values of the distribution.\n    weights : array_like, optional\n        1-D array of integer weights associated with the values in `a`. Each value in\n        `a` contributes to the average according to its associated weight.\n        If `weights=None`, then all data in `a` are assumed to have a\n        weight equal to one.\n\n    Returns\n    -------\n    gini : float\n        Returns the Gini Coefficient of the distribution provided.\n    \"\"\"\n    a = np.asarray(a)\n    if weights is not None:\n        weights = np.asarray(weights)\n        sorted_indices = np.argsort(a)\n        sorted_x = a[sorted_indices]\n        sorted_w = weights[sorted_indices]\n        # Force float dtype to avoid overflows\n        cumw = np.cumsum(sorted_w, dtype=float)\n        cumxw = np.cumsum(sorted_x * sorted_w, dtype=float)\n        return (np.sum(cumxw[1:] * cumw[:-1] - cumxw[:-1] * cumw[1:]) /\n                (cumxw[-1] * cumw[-1]))\n    else:\n        sorted_x = np.sort(a)\n        n = len(a)\n        cumx = np.cumsum(sorted_x, dtype=float)\n        # The above formula, with all weights equal to 1 simplifies to:\n        return (n + 1 - 2 * np.sum(cumx) / cumx[-1]) / n\n", "meta": {"hexsha": "1ca5c3275d86bd3c6390d0b7e38bc8b1e323fe8b", "size": 1399, "ext": "py", "lang": "Python", "max_stars_repo_path": "inequalipy/gini.py", "max_stars_repo_name": "urutau-nz/inequipy", "max_stars_repo_head_hexsha": "01ad29a1b568d737c1ee2a9703db515a5b142043", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-31T08:56:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T08:56:46.000Z", "max_issues_repo_path": "inequalipy/gini.py", "max_issues_repo_name": "urutau-nz/inequipy", "max_issues_repo_head_hexsha": "01ad29a1b568d737c1ee2a9703db515a5b142043", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-11-05T09:27:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-05T09:28:03.000Z", "max_forks_repo_path": "inequalipy/gini.py", "max_forks_repo_name": "urutau-nz/inequipy", "max_forks_repo_head_hexsha": "01ad29a1b568d737c1ee2a9703db515a5b142043", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.975, "max_line_length": 85, "alphanum_fraction": 0.6040028592, "include": true, "reason": "import numpy", "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799399736476, "lm_q2_score": 0.8887587949656841, "lm_q1q2_score": 0.8565678980630784}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"Linear regression for machine learning\n\nThis file demonstrate knowledge of linear regression. By building the algorithm\nfrom scratch.The idea of linear regression is to take continuous data and find\nthe best fit of it to a line.\n\"y=mx+b\" is the equation of a line, and we need to figure out the\nbest slope (m) and y-intercept (b) to fit the line best.\n\nThis is for simple 2d regression.\n\nExample:\n\n        $ python howItWorksLinearRegression.py\n\nTodo:\n    *\n\"\"\"\nimport random\n\nfrom statistics import mean\n\nfrom matplotlib import style\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\nstyle.use('fivethirtyeight')\n\n# simple_x = np.array([1, 2, 3, 4, 5, 6], dtype=np.float64)\n# simple_y = np.array([5, 4, 6, 5, 6, 7], dtype=np.float64)\n\n\ndef create_dataset(howmany, variance, step=2, correlation=False):\n    # for test-data\n    val = 1\n    ys = []\n    for i in range(howmany):\n        y = val + random.randrange(-variance, variance)\n        ys.append(y)\n        if correlation and correlation == 'pos':\n            val += step\n        elif correlation and correlation == 'neg':\n            val -= step\n    xs = [i for i in range(len(ys))]\n    return np.array(xs, dtype=np.float64), np.array(ys, dtype=np.float64)\n\nsimple_x, simple_y = create_dataset(40, 10, 2, correlation='pos')\n\n\ndef best_fit_slope_and_intercept(xs, ys):\n    # Best fit m(slope)\n    m = (mean(xs) * mean(ys) - mean(xs * ys)) / (mean(xs)**2 - mean(xs**2))\n    # Best fit y(intercept)\n    b = mean(ys) - m * mean(xs)\n    return m, b\n\n\ndef squared_error(ys_orig, ys_line):\n    # Figuring out the squared_error that we need to calculate R^2\n    return sum((ys_line - ys_orig)**2)\n\n\ndef coefficient_of_determination(ys_orig, ys_line):\n    # Figuring out R^2 = 1 - (squared_error(y_hat) / squared_error(mean(y)))\n    y_mean_line = [mean(ys_orig) for y in ys_orig]  # line of mean(y)s\n    squared_error_regressionline = squared_error(ys_orig, ys_line)\n    squared_error_y_mean = squared_error(ys_orig, y_mean_line)\n    return 1 - (squared_error_regressionline / squared_error_y_mean)\n\nm, b = best_fit_slope_and_intercept(simple_x, simple_y)\nregression_line = [(m * x) + b for x in simple_x]  # \"y=mx+b\"\n\npredict_x = 8\npredict_y = (m * predict_x) + b\nr_squared = coefficient_of_determination(simple_y, regression_line)\n\nprint(r_squared)\n\nplt.scatter(simple_x, simple_y)\nplt.plot(simple_x, regression_line, color='g')\nplt.scatter(predict_x, predict_y, color='r')\nplt.show()\n", "meta": {"hexsha": "34337b3eb6f1fceaed766c7dc00953e5d69ddff2", "size": 2463, "ext": "py", "lang": "Python", "max_stars_repo_path": "Regression/SimpleLinearRegression/howItWorksLinearRegression.py", "max_stars_repo_name": "a-holm/MachinelearningAlgorithms", "max_stars_repo_head_hexsha": "a07cdddd079cd57ac77a17487a32c594e735baf8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Regression/SimpleLinearRegression/howItWorksLinearRegression.py", "max_issues_repo_name": "a-holm/MachinelearningAlgorithms", "max_issues_repo_head_hexsha": "a07cdddd079cd57ac77a17487a32c594e735baf8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-01T22:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T22:07:30.000Z", "max_forks_repo_path": "Regression/SimpleLinearRegression/howItWorksLinearRegression.py", "max_forks_repo_name": "a-holm/MachinelearningAlgorithms", "max_forks_repo_head_hexsha": "a07cdddd079cd57ac77a17487a32c594e735baf8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3214285714, "max_line_length": 79, "alphanum_fraction": 0.6898091758, "include": true, "reason": "import numpy", "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350252, "lm_q2_score": 0.888758786126321, "lm_q1q2_score": 0.8565678932423385}}
{"text": "# euclid norm\n# https://numpy.org/doc/stable/reference/generated/numpy.linalg.norm.html\nfrom numpy import linalg as la\nimport numpy as np\n\na = np.arange(9) - 4\n# print(np.arange(9))\n# print(a)\nb = a.reshape((3, 3))\n# print(b)\n'''\nprint(la.norm(a))\nprint(la.norm(b))\nprint(la.norm(b, 'fro'))\nprint(la.norm(a, np.inf))\nprint(la.norm(b, np.inf))\nprint(la.norm(a, -np.inf))\nprint(la.norm(b, -np.inf))\nprint(la.norm(a, 1))\nprint(la.norm(b, 1))\n# print(la.norm(a, -1))\nprint(la.norm(b, -1))\nprint(la.norm(a, 2))\nprint(la.norm(b, 2))\n# print(la.norm(a, -2))\nprint(la.norm(b, -2))\nprint(la.norm(a, 3))\n# print(la.norm(a, -3))\n'''\nc = np.array([[1, 2, 3], [-1, 1, 4]])\n# # using axis compute vector norms\n# print(la.norm(c, axis=0))\n# print(la.norm(c, axis=1))\n# print(la.norm(c, ord=1, axis=1))\n\n# using axis compute matrix norms\nm = np.arange(12).reshape(2, 3, -1)\n# print(la.norm(m, axis=(1, 2)))\n# print(m[0, :, :])\n# print(m[1, :, :])\n# print(la.norm(m[0, :, :]), la.norm(m[1, :, :]))\n\nm = np.arange(3) - 1\n# print(m)\n# print(m/la.norm(m))\n", "meta": {"hexsha": "a6db615ba2b299f42a34490dc0789866075d4bc3", "size": 1036, "ext": "py", "lang": "Python", "max_stars_repo_path": "davidgoliath/project/modelling/02_euclidnorm.py", "max_stars_repo_name": "spideynolove/Other-repo", "max_stars_repo_head_hexsha": "34066f177994415d031183ab9dd219d787e6e13a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "davidgoliath/project/modelling/02_euclidnorm.py", "max_issues_repo_name": "spideynolove/Other-repo", "max_issues_repo_head_hexsha": "34066f177994415d031183ab9dd219d787e6e13a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "davidgoliath/project/modelling/02_euclidnorm.py", "max_forks_repo_name": "spideynolove/Other-repo", "max_forks_repo_head_hexsha": "34066f177994415d031183ab9dd219d787e6e13a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5217391304, "max_line_length": 73, "alphanum_fraction": 0.5994208494, "include": true, "reason": "import numpy,from numpy", "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288128, "lm_q2_score": 0.8947894682067639, "lm_q1q2_score": 0.8565621001458854}}
{"text": "import numpy\n# reference: https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm\ndef line_low(x0, y0, x1, y1):\n    res = []\n    dx = x1 - x0\n    dy = y1 - y0\n    yi = 1\n    if dy < 0:\n        yi = -1\n        dy = -dy\n    D = 2*dy - dx\n    y = y0\n    for x in range(x0, x1 + 1):\n        res.append((x,y))\n        if D > 0:\n            y = y + yi\n            D = D - 2*dx\n        D = D + 2*dy\n    return res\n\ndef line_high(x0, y0, x1, y1):\n    res = []\n    dx = x1 - x0\n    dy = y1 - y0\n    xi = 1\n    if dx < 0:\n        xi = -1\n        dx = -dx\n    D = 2*dx - dy\n    x = x0\n\n    for y in range(y0, y1 + 1):\n        res.append((x,y))\n        if D > 0:\n            x = x + xi\n            D = D - 2*dy\n        D = D + 2*dx\n    return res\n\ndef bresenham_line(A, B):\n    x0 = int(A[0])\n    y0 = int(A[1])\n    x1 = int(B[0])\n    y1 = int(B[1])\n\n    if abs(y1 - y0) < abs(x1 - x0):\n        if x0 > x1:\n            return line_low(x1, y1, x0, y0)\n        else:\n            return line_low(x0, y0, x1, y1)\n    else:\n        if y0 > y1:\n            return line_high(x1, y1, x0, y0)\n        else:\n            return line_high(x0, y0, x1, y1)\n\n# reference: https://en.wikipedia.org/wiki/Midpoint_circle_algorithm\ndef bresenham_circle(C):\n    x0 = int(C[0])\n    y0 = int(C[1])\n    radius = int(C[2])\n    res = []\n    x = int(radius-1)\n    y = int(0)\n    dx = int(1)\n    dy = int(1)\n    err = int(dx - (radius << 1))\n\n    while (x >= y):\n        res.append((x0 + x, y0 + y))\n        res.append((x0 + y, y0 + x))\n        res.append((x0 - y, y0 + x))\n        res.append((x0 - x, y0 + y))\n        res.append((x0 - x, y0 - y))\n        res.append((x0 - y, y0 - x))\n        res.append((x0 + y, y0 - x))\n        res.append((x0 + x, y0 - y))\n\n        if (err <= 0):\n            y += 1\n            err += dy\n            dy += 2\n        \n        if (err > 0):\n            x -= 1\n            dx += 2\n            err += dx - (radius << 1)\n    \n    return res\n", "meta": {"hexsha": "eb7b8ba0de96855ce76d659ff6a1b42af34e98f1", "size": 1936, "ext": "py", "lang": "Python", "max_stars_repo_path": "SLAM/bresenham_algorithm.py", "max_stars_repo_name": "democheng/PythonRobotics", "max_stars_repo_head_hexsha": "0734c14ab7cd6daf9be307693b674e20a676bebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-10-09T09:26:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T08:37:33.000Z", "max_issues_repo_path": "SLAM/bresenham_algorithm.py", "max_issues_repo_name": "democheng/PythonRobotics", "max_issues_repo_head_hexsha": "0734c14ab7cd6daf9be307693b674e20a676bebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SLAM/bresenham_algorithm.py", "max_forks_repo_name": "democheng/PythonRobotics", "max_forks_repo_head_hexsha": "0734c14ab7cd6daf9be307693b674e20a676bebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-11-13T05:55:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T16:37:03.000Z", "avg_line_length": 21.5111111111, "max_line_length": 71, "alphanum_fraction": 0.4106404959, "include": true, "reason": "import numpy", "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778012346834, "lm_q2_score": 0.8947894731166139, "lm_q1q2_score": 0.8565620993930131}}
{"text": "import numpy as np\n\nfrom math import copysign, hypot\n\n\ndef gram_schmidt_process(A):\n    \"\"\"\n    Perform QR decomposition of matrix A using Gram-Schmidt process.\n    \"\"\"\n    (num_rows, num_cols) = np.shape(A)\n\n    # Initialize empty orthogonal matrix Q.\n    Q = np.empty([num_rows, num_rows])\n    cnt = 0\n\n    # Compute orthogonal matrix Q.\n    for a in A.T:\n        u = np.copy(a)\n        for i in range(0, cnt):\n            proj = np.dot(np.dot(Q[:, i].T, a), Q[:, i])\n            u -= proj\n\n        e = u / np.linalg.norm(u)\n        Q[:, cnt] = e\n\n        cnt += 1  # Increase columns counter.\n\n    # Compute upper triangular matrix R.\n    R = np.dot(Q.T, A)\n\n    return (Q, R)\n\n\ndef householder_reflection(A):\n    \"\"\"\n    Perform QR decomposition of matrix A using Householder reflection.\n    \"\"\"\n    (num_rows, num_cols) = np.shape(A)\n\n    # Initialize orthogonal matrix Q and upper triangular matrix R.\n    Q = np.identity(num_rows)\n    R = np.copy(A)\n\n    # Iterative over column sub-vector and\n    # compute Householder matrix to zero-out lower triangular matrix entries.\n    for cnt in range(num_rows - 1):\n        x = R[cnt:, cnt]\n\n        e = np.zeros_like(x)\n        e[0] = copysign(np.linalg.norm(x), -A[cnt, cnt])\n        u = x + e\n        v = u / np.linalg.norm(u)\n\n        Q_cnt = np.identity(num_rows)\n        Q_cnt[cnt:, cnt:] -= 2.0 * np.outer(v, v)\n\n        R = np.dot(Q_cnt, R)\n        Q = np.dot(Q, Q_cnt.T)\n\n    return Q, R\n\n\ndef givens_rotation(A):\n    \"\"\"\n    Perform QR decomposition of matrix A using Givens rotation.\n    \"\"\"\n    (num_rows, num_cols) = np.shape(A)\n\n    # Initialize orthogonal matrix Q and upper triangular matrix R.\n    Q = np.identity(num_rows)\n    R = np.copy(A)\n\n    # Iterate over lower triangular matrix.\n    (rows, cols) = np.tril_indices(num_rows, -1, num_cols)\n    for (row, col) in zip(rows, cols):\n\n        # Compute Givens rotation matrix and\n        # zero-out lower triangular matrix entries.\n        if R[row, col] != 0:\n            (c, s) = _givens_rotation_matrix_entries(R[col, col], R[row, col])\n\n            G = np.identity(num_rows)\n            G[[col, row], [col, row]] = c\n            G[row, col] = s\n            G[col, row] = -s\n\n            R = np.dot(G, R)\n            Q = np.dot(Q, G.T)\n\n    return Q, R\n\n\ndef _givens_rotation_matrix_entries(a, b):\n    \"\"\"\n    Compute matrix entries for Givens rotation.\n    \"\"\"\n    r = hypot(a, b)\n    c = a/r\n    s = -b/r\n\n    return c, s\n", "meta": {"hexsha": "2a11007c2f051f63cc71fe322d9dbfcbf45f1bbd", "size": 2445, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/estimation/linear_algebra_tools.py", "max_stars_repo_name": "PontusHultkrantz/statarb", "max_stars_repo_head_hexsha": "521017c6f099e1bd7ea0f31df918abd83a0c8be7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-19T17:02:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T20:20:11.000Z", "max_issues_repo_path": "src/estimation/linear_algebra_tools.py", "max_issues_repo_name": "PontusHultkrantz/statarb", "max_issues_repo_head_hexsha": "521017c6f099e1bd7ea0f31df918abd83a0c8be7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/estimation/linear_algebra_tools.py", "max_forks_repo_name": "PontusHultkrantz/statarb", "max_forks_repo_head_hexsha": "521017c6f099e1bd7ea0f31df918abd83a0c8be7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-04T09:32:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-04T09:32:24.000Z", "avg_line_length": 23.9705882353, "max_line_length": 78, "alphanum_fraction": 0.5644171779, "include": true, "reason": "import numpy", "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777975782055, "lm_q2_score": 0.894789473818021, "lm_q1q2_score": 0.8565620967926765}}
{"text": "# import modules\r\nimport numpy as np\r\n\r\n''' \r\n# Description.\r\nWith the extreme points of the defined slope, this function obtains the\r\nlower possible boundary in where a slip circle can be, i.e. obtains the\r\nmaximum depth computed from the slope toe.\r\n\r\n# Input(s).\r\nHeight of the slope (slopeHeight).\r\n\r\nSlope dip, can be given by an angle in gradians, angle in radians, a\r\nhorizontal distance value relative to a unitary vertical distance (i.e.\r\nhorz:1), or a bidimensional vector which represents a horizontal distance and\r\na vertical distance that not necessary representing the real slope distances \r\n[horzDist, vertDist], (slopeDip).\r\n\r\nCrown horizontal plane distance (crownDist).\r\n\r\nToe horizontal plane distance (toeDist).\r\n\r\n# Output(s):\r\nVertical distance from the slide--toe to downwards (toeDepth).\r\n\r\n# Example1: By giving next values:\r\nslopeHeight = 12; slopeDip = np.array([2.5, 1]); crownDist = 10.0;\\\r\ntoeDist = 10.0; it is obtained a toeDepth = 14.44.\r\n\r\n---\r\ntoeDepth = obtainmaxdepthdist(slopeHeight, slopeDip, crownDist, toeDist)\r\n'''\r\ndef obtainmaxdepthdist(slopeHeight, slopeDip, crownDist, toeDist):\r\n    \r\n    #Calculation assuming coordinates origin at the slip--toe\r\n    extremeToePointVec = np.array([toeDist, 0])\r\n    \r\n    #slope vertical projection (horizontal distance)\r\n    slopeDist = slopeHeight*slopeDip[0]/slopeDip[1]\r\n    \r\n    extremeCrownPointVec = np.array([-(slopeDist +crownDist), slopeHeight])\r\n    \r\n    #distance between the two extreme points\r\n    differenceVec = extremeToePointVec-extremeCrownPointVec\r\n    distExtrPts = np.sqrt(np.dot(differenceVec, differenceVec))\r\n    maximumCircleRadius = distExtrPts/2*distExtrPts/differenceVec[0]\r\n    \r\n    #the toe depth is the difference between the maximum--circle radius and the\r\n    #slope height\r\n    toeDepth = maximumCircleRadius-slopeHeight\r\n    \r\n    return toeDepth\r\n'''\r\nBSD 2 license.\r\n\r\nCopyright (c) 2016, Universidad Nacional de Colombia, Ludger O.\r\n   Suarez-Burgoa and Exneyder Andrés Montoya Araque.\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without\r\nmodification, are permitted provided that the following conditions are\r\nmet:  \r\n\r\n1. Redistributions of source code must retain the above copyright notice,\r\nthis list of conditions and the following disclaimer. \r\n\r\n2. Redistributions in binary form must reproduce the above copyright\r\nnotice, this list of conditions and the following disclaimer in the\r\ndocumentation and/or other materials provided with the distribution.  \r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\r\nIS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\r\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r\nPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\r\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n'''\r\n", "meta": {"hexsha": "a242d25f06277f190324edb43fcabf5e597c54ec", "size": 3303, "ext": "py", "lang": "Python", "max_stars_repo_path": "functions/obtainmaxdepthdist.py", "max_stars_repo_name": "eamontoyaa/CSS-pyProgram", "max_stars_repo_head_hexsha": "beb28a18cba4e4b2e6d8be556296aa6f8025defa", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2016-05-12T14:54:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T09:29:08.000Z", "max_issues_repo_path": "functions/obtainmaxdepthdist.py", "max_issues_repo_name": "eamontoyaa/CSS-pyProgram", "max_issues_repo_head_hexsha": "beb28a18cba4e4b2e6d8be556296aa6f8025defa", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-02-27T17:34:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-17T08:44:26.000Z", "max_forks_repo_path": "functions/obtainmaxdepthdist.py", "max_forks_repo_name": "eamontoyaa/CSS-pyProgram", "max_forks_repo_head_hexsha": "beb28a18cba4e4b2e6d8be556296aa6f8025defa", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-06-21T04:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T02:25:19.000Z", "avg_line_length": 39.7951807229, "max_line_length": 80, "alphanum_fraction": 0.7556766576, "include": true, "reason": "import numpy", "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.894789454880027, "lm_q1q2_score": 0.8565620797543481}}
{"text": "import numpy as np\n\n\ndef sigmoid_forward(x):\n    \"\"\"\n    Sigmoid function, sigmoid(x) = 1/(1+exp(-x))\n    :param x: input\n    :return: output and cache\n    \"\"\"\n    return 1 / (1 + np.exp(-x)), x\n\n\ndef sigmoid_backward(dout, cache):\n    \"\"\"\n    backward of sigmoid function, dx = x(x-1)\n    :param dout: grad of outputs\n    :param cache: cache stored before\n    :return: dx\n    \"\"\"\n    x = cache\n    return x * (x - 1) * dout\n\n\ndef tanh_forward(x):\n    \"\"\"\n    Tanh function, tanh(x) = (exp(x) - exp(-x))/ (exp(x) + exp(-x))\n    :param x: input\n    :return: output\n    \"\"\"\n    y = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))\n    return y, y\n\n\ndef tanh_backward(dout, cache):\n    \"\"\"\n    backward of tanh, dx = 1 - (tanh(x))^2\n    :param dout:\n    :param cache:\n    :return:\n    \"\"\"\n    tanh_x = cache\n    return (1 - tanh_x ** 2) * dout\n\n\ndef softmax_forward(x):\n    \"\"\"\n    Softmax function, softmax(x) = exp(x[i]) / sum(exp(x[i]))\n    :param x: input\n    :return: output\n    \"\"\"\n    temp = np.sum(np.exp(x))\n    return np.exp(x) / temp, x\n\n\ndef softmax_backward(dout, cache):\n    \"\"\"\n    backward of softmax, if i=j dx=x[j](1-x[j]) if i!=j dx=-x[i]x[j]\n    x.shape=(N, 1)\n    :param dout: grad of outputs\n    :return: grads of input\n    \"\"\"\n    x = cache\n    dx_1 = x * (1 - x)\n    # sum_x_2 = np.sum(np.dot(x.T, x), axis=0, keepdims=True)\n    # sum_x_2 -= x ** 2\n    dx = dx_1 * dout\n\n    return dx\n\n\ndef relu_forward(x):\n    \"\"\"\n    ReLu function, relu(x) = max(0, x)\n    :param x: input\n    :return: output and cache\n    \"\"\"\n    return np.maximum(0, x), x\n\n\ndef relu_backward(dout, cache):\n    x = cache\n    dx = dout\n    dx[x <= 0] = 0\n    return dx\n\n\ndef leaky_relu_forward(x, alpha=0.01):\n    \"\"\"\n    Leaky ReLu function, leaky_relu(x)=max(alpha * x, x)\n    :param x: input\n    :param alpha: hyperparameter of leaky relu\n    :return: output\n    \"\"\"\n    return np.maximum(alpha * x, x)\n\n\nif __name__ == '__main__':\n    # x = np.random.randn(1, 10)\n    # y, cache = relu_forward(x)\n    # dy = np.random.randn(1, 10)\n    # dx = relu_backward(dy, cache)\n    # print(dx)\n    x = np.ones((1, 2))\n    y = np.array([1,2]).reshape(1,2)\n    print(x[y<2])\n", "meta": {"hexsha": "85b68af88a49f4c7253c0ff6fca71006cc83fc8c", "size": 2160, "ext": "py", "lang": "Python", "max_stars_repo_path": "lhq_nn_lib/layers/activation_layer.py", "max_stars_repo_name": "lhq1208/DL_lib", "max_stars_repo_head_hexsha": "53c99157efcc36f2288a82eedad09cdecda579e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lhq_nn_lib/layers/activation_layer.py", "max_issues_repo_name": "lhq1208/DL_lib", "max_issues_repo_head_hexsha": "53c99157efcc36f2288a82eedad09cdecda579e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lhq_nn_lib/layers/activation_layer.py", "max_forks_repo_name": "lhq1208/DL_lib", "max_forks_repo_head_hexsha": "53c99157efcc36f2288a82eedad09cdecda579e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3773584906, "max_line_length": 68, "alphanum_fraction": 0.5430555556, "include": true, "reason": "import numpy", "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877717925421, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.8565619379556935}}
{"text": "import numpy as np\n\ng = list(range(10))\n\n# sum of array\ng_array = np.sum(g)\nprint(g_array)\n\n# Constructor of array\na = np.array([1,2,3,4])\n# a.shape = (4,)\nb = np.array([10,11,12,13])\n# a + b => array([11,13,15,17])\n\"\"\"\nIn normal python: a + b -> [1,2,3,4,10,11,12,13]\n\"\"\"\n\na.fill(1)\n# a = [1,1,1,1]\n\n##########################################################\n# Control the type of array\nb= np.array([1,2,3,4.0], dtype = int32)\n\nc = np.array([[10,11,12],[20,21,22]])\n\"\"\"\nc.dtype dtype('int64')\nc.ndim = 2\nc.shape = (2,3)\n\"\"\"\n# Transport matrix\nc.T = [[10,20],\n        [11,21],\n        [12,22]]\n\"\"\"\nc.size = 6\nc.nbytes = 48\nc[0,0] = 10  -> don't like in normal python c[0][0]\n\"\"\"\n\n##########################################################\n# Slicing:  var[lower:upper:step]\na = np.array([10,11,12,13,14])\n# a[::2] -> array([10,12,14])\n\na = [[0,1,2,3,4,5],\n    [10,11,12,13,14,15],\n    [20,21,22,23,24,25],\n    [30,31,32,33,34,35],\n    [40,41,42,43,44,45],\n    [50,51,52,53,54,55]]\n\n\"\"\"\na[0, 3:5] -> array([]3,4)\na[4:, 4:] -> array([44,45],[54,55])\na[:, 2]   -> array([2,12,22,32,42,52])\na[2::2, ::2]    -> array([20,22,24],[40,42,44])\n\"\"\"\n\n##########################################################\na = np.arange(25).reshape(5,5)\n\"\"\"\narray([[ 0,  1,  2,  3,  4],\n    [ 5,  6,  7,  8,  9],\n    [10, 11, 12, 13, 14],\n    [15, 16, 17, 18, 19],\n    [20, 21, 22, 23, 24]])\n\"\"\"\nred = a[:, ::2]\nyellow = a[4]\nblue = [1::2, 0:3:2]\n\n##########################################################\na = np.array([3,-1,-2,4,-6,8])\n\"\"\"\na < 0\n-> array([False,  True,  True, False,  True, False])\na[a<0]  -> array([-1,-2,-6])\n(a < 8).any()   -> true\n(a , 8).all()   -> false\n\n&(and) , |(or) , ~(not) , ^(xor)  -> bitwise operators\nand or not -> binary operators\n\n(a > 3) & (a < 8)   -> array([False,False,False,True,False,False])\n\na.nonzero(arr) -> get the array which is built with the numbers which are not equal 0\n\"\"\"\n", "meta": {"hexsha": "04b12291faf1c90dcb9485dd8e8344fa58c58553", "size": 1900, "ext": "py", "lang": "Python", "max_stars_repo_path": "Computerorietierte_Mathematik/selflearning_numpy.py", "max_stars_repo_name": "qiaw99/Data-Structure", "max_stars_repo_head_hexsha": "3b1cdce96d4f35329ccfec29c03de57378ef0552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-29T08:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-29T08:21:41.000Z", "max_issues_repo_path": "Computerorietierte_Mathematik/selflearning_numpy.py", "max_issues_repo_name": "qiaw99/Data-Structure", "max_issues_repo_head_hexsha": "3b1cdce96d4f35329ccfec29c03de57378ef0552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Computerorietierte_Mathematik/selflearning_numpy.py", "max_forks_repo_name": "qiaw99/Data-Structure", "max_forks_repo_head_hexsha": "3b1cdce96d4f35329ccfec29c03de57378ef0552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3483146067, "max_line_length": 85, "alphanum_fraction": 0.4436842105, "include": true, "reason": "import numpy", "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075733703925, "lm_q2_score": 0.8902942195727173, "lm_q1q2_score": 0.8565588111787944}}
{"text": "import numpy as np\nimport math\nfrom scipy import linalg as la\n\ndef gmres(A,b, k=100, tol=1e-8):\n    \"\"\"\n    Calculate approximate solution of Ax = b using GMRES algorithm.\n    Inputs:\n        A -- callable function that calculates Ax for any input vector x.\n        b -- numpy array of length m\n        k -- Maximum number of iterations of the GMRES algorithm. Defaults to 100.\n        tol -- Stop iterating if the residual is less than `tol'. Defaults to 1e-8.\n    Returns:\n        Return (y, res) where 'y' is an approximate solution to Ax=b and 'res'\n    is the residual.\n    \"\"\"\n    # initialization steps\n    m = b.size\n    Q = np.empty((m,k))\n    H = np.zeros((k+1,k))\n    bnorm = la.norm(b,2)\n    rhs = np.zeros(k+1)\n    rhs[0] = bnorm\n    Q[:,0] = b/bnorm\n\n    for j in xrange(k-1):\n        # Arnoldi iteration\n        q = A(Q[:,j])\n        for i in xrange(j+1):\n            H[i,j] = np.inner(Q[:,i],q)\n            q -= H[i,j]*Q[:,i]\n        H[j+1,j] = la.norm(q,2)\n        if H[j+1,j] > 1e-10:\n            # don't divide by zero!\n            q /= H[j+1,j]\n        Q[:,j+1] = q\n\n        # solve the least squares problem\n        y, r = la.lstsq(H[:j+2,:j+1], rhs[:j+2])[:2]\n\n        # compute the residual.\n        r = math.sqrt(r)/bnorm\n        if r < tol:\n            # if we are sufficiently close to solution, return\n            return Q[:,:j+1].dot(y), r\n    return Q[:,:j+1].dot(y.flatten()), r\n", "meta": {"hexsha": "2ebec9f3af32897d170104ecc67e979c5abb1f19", "size": 1409, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol1B/GMRES/GMRES_solutions.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vol1B/GMRES/GMRES_solutions.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vol1B/GMRES/GMRES_solutions.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 29.9787234043, "max_line_length": 83, "alphanum_fraction": 0.5287437899, "include": true, "reason": "import numpy,from scipy", "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075690244281, "lm_q2_score": 0.8902942195727173, "lm_q1q2_score": 0.8565588073096074}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import Normalize\n\n\ndef plot_column_vectors_2d(matrix):\n    \"\"\"\n    Plots column vectors from the supplied matrix in the 2D plane.  The matrix must have shape (2,X), where X >= 1.\n    :param matrix: a (2,X) matrix; x >= 1\n    :return: None.  Displays 2D plot.\n    \"\"\"\n    if matrix.shape[0] != 2:\n        raise ValueError(\"Matrix must have 2d column space\")\n\n    origin = np.zeros_like(matrix)\n\n    fig, ax = plt.subplots()\n\n    xmin, xmax = min(np.min(matrix[0]), 0), max(np.max(matrix[0]), 0)\n    ymin, ymax = min(np.min(matrix[1]), 0), max(np.max(matrix[1]), 0)\n\n    ax.axis(list(map(int, [xmin - 1, xmax + 1, ymin - 1, ymax + 1])))\n    ax.grid(True)\n\n    colors = np.linalg.norm(matrix, axis=0)\n    colormap = plt.get_cmap('jet')\n\n    norm = Normalize()\n    norm.autoscale(colors)\n\n    ax.quiver(origin[0], origin[1], matrix[0], matrix[1], scale=1, color=colormap(norm(colors)), angles='xy',\n              scale_units='xy')\n\n\ndef plot_column_vectors_with_transform_2d(matrix, transform):\n    \"\"\"\n    Displays a side-by-side plot of the column vectors in the supplied matrix and the column vectors in the transformed matrix matrix * transform.\n\n    The matrix must have shape (2,X), where X >= 1.\n    The transform must have shape (2,2)\n\n    :param matrix: a (2,X) matrix; x >= 1\n    :param transform: a (2,2) transformation matrix.\n    :return: None. Displays 2 2D subplots.\n    \"\"\"\n    if matrix.shape[0] != 2:\n        raise ValueError(\"Matrix must have 2d column space\")\n\n    if transform.shape != (2, 2):\n        raise ValueError(\"Transform matrix must have shape (2,2)\")\n\n    origin = np.zeros_like(matrix)\n\n    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))\n\n    colors = np.linalg.norm(matrix, axis=0)\n    colormap = plt.get_cmap('jet')\n\n    norm = Normalize()\n    norm.autoscale(colors)\n\n    trans_matrix = np.dot(transform, matrix)\n\n    xmin, xmax = min(np.min(matrix[0]), 0), max(np.max(matrix[0]), 0)\n    ymin, ymax = min(np.min(matrix[1]), 0), max(np.max(matrix[1]), 0)\n\n    ax1.axis(list(map(int, [xmin - 1, xmax + 1, ymin - 1, ymax + 1])))\n    ax1.set_title(\"$A$\")\n    ax1.grid(True)\n    ax1.quiver(origin[0], origin[1], matrix[0], matrix[1], color=colormap(norm(colors)), scale=1, angles='xy',\n               scale_units='xy')\n\n    xmin, xmax = min(np.min(trans_matrix[0]), 0), max(np.max(trans_matrix[0]), 0)\n    ymin, ymax = min(np.min(trans_matrix[1]), 0), max(np.max(trans_matrix[1]), 0)\n\n    ax2.axis(list(map(int, [xmin - 1, xmax + 1, ymin - 1, ymax + 1])))\n    ax2.set_title(\"$TA$\")\n    ax2.grid(True)\n    ax2.quiver(origin[0], origin[1], trans_matrix[0], trans_matrix[1], color=colormap(norm(colors)), scale=1,\n               angles='xy', scale_units='xy')\n", "meta": {"hexsha": "9c64d587750560cbf14d5ae5b281532b70f928f9", "size": 2763, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/linear_algebra/matrix_plot.py", "max_stars_repo_name": "skugele/linear-algebra", "max_stars_repo_head_hexsha": "06eb31045084a5b5a4e200818075eb6121dc8562", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/linear_algebra/matrix_plot.py", "max_issues_repo_name": "skugele/linear-algebra", "max_issues_repo_head_hexsha": "06eb31045084a5b5a4e200818075eb6121dc8562", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linear_algebra/matrix_plot.py", "max_forks_repo_name": "skugele/linear-algebra", "max_forks_repo_head_hexsha": "06eb31045084a5b5a4e200818075eb6121dc8562", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1111111111, "max_line_length": 146, "alphanum_fraction": 0.6257690916, "include": true, "reason": "import numpy", "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.9005297901222472, "lm_q1q2_score": 0.8565319049937808}}
{"text": "#These are the python libraries that are going to help us to create a plot\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n#This is the function that will be intergrated\r\ndef f(x):\r\n    #x**4-2*x+1\r\n    return x**4-2*x+1 \r\n\r\n#This 'Trapizoid_Rule' function will require a function,\r\n#'b' value so the lower limit of a integral\r\n#'a' value so the upper limit of a integral\r\n# The amount of NUMERICAL PLOTS.\r\n     \r\ndef Trapizoid_Rule(f, xmin, xmax, N):\r\n    #the area has been initially set to 0\r\n    area = 0\r\n    #h is the step size\r\n    h = (xmax-xmin)/N\r\n    \r\n    #the 'arange' function return evenly spaced numbers over a specified interval\r\n    #It takes in the a & b limit parameters and Amount of NUMERICAL PLOTS\r\n    npoints = np.arange(xmin, xmax, h)\r\n    del_dis = np.delete(npoints, 0)\r\n    area = h*((f(xmin)/2)+(f(xmax)/2)+sum(f(xmin+del_dis)))\r\n   \r\n    return area\r\n   \r\n#-----ENTER THE FOLLOWING----\r\n#Function f\r\n#upper limit (a)\r\n#lower limit (b)\r\n#Amount of NUMERICAL PLOTS\r\n    \r\ndef integrate(f,a,b,N):\r\n    \r\n    integral = Trapizoid_Rule(f,a,b,N)\r\n    integral2 = Trapizoid_Rule(f,a,b,N/2)\r\n    \r\n    x = np.linspace(a, b, int(N))\r\n    #size of graph\r\n    plt.figure(figsize=(14,7))\r\n    #graph plotting function\r\n    plt.plot(x,f(x),'--o',label=r'$f(x)$') \r\n    \r\n    #this function fills in the area between the a and b limits \r\n    plt.fill_between(x,f(x), where =[(x>=a)and(x<=b) for x in x],color= 'gray', alpha = '0.7')\r\n    \r\n    #this function produces lines from the NUMERICAL PLOTS to the x-axis     \r\n    plt.vlines(x, 0, f(x), color='purple', linestyle=':')\r\n    \r\n    ###aixs lines##############\r\n    plt.axhline(color='black')\r\n    plt.axvline(color = 'black')\r\n    ############################\r\n     \r\n    \r\n    ###These are the axis labels######\r\n    plt.ylabel(\"f(x)\",fontsize=16)\r\n    plt.xlabel(\"x\",fontsize = 16)\r\n    \r\n    #this is the little box that displayed the colour of the function\r\n    plt.legend(loc='upper right')\r\n    \r\n    plt.grid(color = 'gray', linewidth=1)\r\n    plt.show()\r\n\r\n    error = abs(integral-integral2)/3\r\n    return integral,error\r\n\r\n#This is the integrate function, the following parameters can be changed\r\n#first--function--\r\n#second--start time\r\n#third--end time\r\n#fourth--Numerical Plots    \r\nans,err_est = integrate(f,0,2,1000)\r\n#N=10, Error=0.10613333333333348\r\n#N=100, Error=0.001066613333333244\r\n#N=1000, Error=1.0666661333758043e-05\r\n\r\nprint('EXACT INTERGRAL=',ans,'||','ESTIMATED ERROR =',err_est)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n               \r\n                   \r\n                   \r\n                 \r\n    \r\n\r\n", "meta": {"hexsha": "3417ec96ef67c77cc693ee4287c8e1d726b54c4b", "size": 2590, "ext": "py", "lang": "Python", "max_stars_repo_path": "trapizoid.py", "max_stars_repo_name": "peteboi/Python-Scripts", "max_stars_repo_head_hexsha": "d84e352c41cff3f459d88c83bc81f6dc2f25ed05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trapizoid.py", "max_issues_repo_name": "peteboi/Python-Scripts", "max_issues_repo_head_hexsha": "d84e352c41cff3f459d88c83bc81f6dc2f25ed05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trapizoid.py", "max_forks_repo_name": "peteboi/Python-Scripts", "max_forks_repo_head_hexsha": "d84e352c41cff3f459d88c83bc81f6dc2f25ed05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9791666667, "max_line_length": 95, "alphanum_fraction": 0.5945945946, "include": true, "reason": "import numpy", "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422255326288, "lm_q2_score": 0.9005297794439688, "lm_q1q2_score": 0.8565318985787439}}
{"text": "# Question 2 Lab 03\n# AB Satyaprakash (180123062)\n\n# imports ----------------------------------------------------------------------\nimport numpy as np\n# ------------------------------------------------------------------------------\n# functions --------------------------------------------------------------------\n\n\ndef forwardDiff(fArray):\n    sz = len(fArray)\n    fdArray = [fArray]\n    for i in range(1, sz):\n        temp = []\n        for j in range(sz-i):\n            temp.append(fdArray[i-1][j+1]-fdArray[i-1][j])\n        fdArray.append(temp)\n    return fdArray\n\n\ndef newtonBDPoly(fArray, xArray):\n    sz = len(fArray)\n    xn, xn_1 = xArray[sz-1], xArray[sz-2]\n    h = xn-xn_1\n    # print(h)\n    v = np.array([1/h, -xn/h])\n    # print(v)\n    fdArray = forwardDiff(fArray)\n    # print(fdArray)\n    px = np.array([0])\n\n    for i in range(sz):\n        term = np.array([1])\n        for j in range(i):\n            term = np.polymul(term, np.polyadd(v, np.array([j])))\n            term = term/(j+1)\n        term = term*fdArray[i][sz-i-1]\n        px = np.polyadd(px, term)\n    return px\n\n\n# ------------------------------------------------------------------------------\n# (i) f(−1/3) if f(−0.75) = −0.07181250, f(−0.5) = −0.02475000, f(−0.25) = 0.33493750, f(0) = 1.10100000\nprint('Part (i)-----------------------------------------------------------------\\n')\nX = [-0.75, -0.5, -0.25, 0]\nF = [-0.07181250, -0.02475000, 0.33493750, 1.10100000]\nval = -1/3  # since we need to approximate f(1/3)\n# (A) Degree 1:\n\nxArray = [X[1], X[2]]\nfArray = [F[1], F[2]]\npx = newtonBDPoly(fArray, xArray)\nprint(\"Newton's interpolating polynomial of degree 1 using nodes: {}, {} is {}\".format(\n    xArray[0], xArray[1], np.poly1d(px)))\nprint(\"Approximated value of f({}) using the above is {}\".format(val, np.polyval(px, val)))\n\nprint('\\n')\n\n# (B) Degree 2:\n\nxArray = [X[0], X[1], X[2]]\nfArray = [F[0], F[1], F[2]]\npx = newtonBDPoly(fArray, xArray)\nprint(\"Newton's interpolating polynomial of degree 2 using nodes: {}, {}, {} is \\n{}\".format(\n    xArray[0], xArray[1], xArray[2], np.poly1d(px)))\nprint(\"Approximated value of f({}) using the above is {}\".format(val, np.polyval(px, val)))\n\nprint('\\n')\n\n# (C) Degree 3:\nxArray = [X[0], X[1], X[2], X[3]]\nfArray = [F[0], F[1], F[2], F[3]]\npx = newtonBDPoly(fArray, xArray)\nprint(\"Newton's interpolating polynomial of degree 3 using nodes: {}, {}, {}, {} is \\n{}\".format(\n    xArray[0], xArray[1], xArray[2], xArray[3], np.poly1d(px)))\nprint(\"Approximated value of f({}) using the above is {}\".format(val, np.polyval(px, val)))\n\n\n# (ii) f(0.25) if f(0.1) = −0.62049958 , f(0.2) = −0.28398668 , f(0.3) = 0.00660095, f(0.4) = 0.24842440\nprint('\\nPart (ii)--------------------------------------------------------------\\n')\nX = [0.1, 0.2, 0.3, 0.4]\nF = [-0.62049958, -0.28398668, 0.00660095, 0.24842440]\nval = 0.25  # since we need to approximate f(0.25)\n# (A) Degree 1:\n\nxArray = [X[1], X[2]]\nfArray = [F[1], F[2]]\npx = newtonBDPoly(fArray, xArray)\nprint(\"Newton's interpolating polynomial of degree 1 using nodes: {}, {} is {}\".format(\n    xArray[0], xArray[1], np.poly1d(px)))\nprint(\"Approximated value of f({}) using the above is {}\".format(val, np.polyval(px, val)))\n\nprint('\\n')\n\n# (B) Degree 2:\nxArray = [X[0], X[1], X[2]]\nfArray = [F[0], F[1], F[2]]\npx = newtonBDPoly(fArray, xArray)\nprint(\"Newton's interpolating polynomial of degree 2 using nodes: {}, {}, {} is \\n{}\".format(\n    xArray[0], xArray[1], xArray[2], np.poly1d(px)))\nprint(\"Approximated value of f({}) using the above is {}\".format(val, np.polyval(px, val)))\n\nprint('\\n')\n\n# (C) Degree 3:\nxArray = [X[0], X[1], X[2], X[3]]\nfArray = [F[0], F[1], F[2], F[3]]\npx = newtonBDPoly(fArray, xArray)\nprint(\"Newton's interpolating polynomial of degree 3 using nodes: {}, {}, {}, {} is \\n{}\".format(\n    xArray[0], xArray[1], xArray[2], xArray[3], np.poly1d(px)))\nprint(\"Approximated value of f({}) using the above is {}\".format(val, np.polyval(px, val)))\n\n\n# Question 2 ends --------------------------------------------------------------\n", "meta": {"hexsha": "5efc40bd48ab0f1c2d245ad844771c3563f10c61", "size": 4021, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 3/Code/q2.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 3/Code/q2.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 3/Code/q2.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 34.9652173913, "max_line_length": 104, "alphanum_fraction": 0.5200198955, "include": true, "reason": "import numpy", "num_tokens": 1328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.9005297841157157, "lm_q1q2_score": 0.8565318967863652}}
{"text": "# Author: Leland McInnes <leland.mcinnes@gmail.com>\n#\n# License: BSD 3 clause\n\n# still to do here:\n# add dot distance\n# change cosine to angular in the right fashion, since angular is the preferred input of annoy\n\nimport numpy as np\nimport numba\n\n\n@numba.njit(fastmath=True)\ndef euclidean(x, y):\n    \"\"\"Standard euclidean distance.\n\n    ..math::\n        D(x, y) = \\sqrt{\\sum_i (x_i - y_i)^2}\n    \"\"\"\n    result = 0.0\n    for i in range(x.shape[0]):\n        result += (x[i] - y[i]) ** 2\n    return np.sqrt(result)\n\n\n@numba.njit(fastmath=True)\ndef manhattan(x, y):\n    \"\"\"Manhattan, taxicab, or l1 distance.\n\n    ..math::\n        D(x, y) = \\sum_i |x_i - y_i|\n    \"\"\"\n    result = 0.0\n    for i in range(x.shape[0]):\n        result += np.abs(x[i] - y[i])\n\n    return result\n\n\n@numba.njit(fastmath=True)\ndef hamming(x, y):\n    result = 0.0\n    for i in range(x.shape[0]):\n        if x[i] != y[i]:\n            result += 1.0\n\n    return float(result) / x.shape[0]\n\n\n@numba.njit(fastmath=True)\ndef cosine(x, y):\n    result = 0.0\n    norm_x = 0.0\n    norm_y = 0.0\n    for i in range(x.shape[0]):\n        result += x[i] * y[i]\n        norm_x += x[i] ** 2\n        norm_y += y[i] ** 2\n\n    if norm_x == 0.0 or norm_y == 0.0:\n        return 1.0\n    else:\n        return 1.0 - (result / np.sqrt(norm_x * norm_y))\n\n\n# is correlation dot product / inner distance ?\n# if not, add dot product / innder distance :)\n@numba.njit(fastmath=True)\ndef correlation(x, y):\n    mu_x = 0.0\n    mu_y = 0.0\n    norm_x = 0.0\n    norm_y = 0.0\n    dot_product = 0.0\n\n    for i in range(x.shape[0]):\n        mu_x += x[i]\n        mu_y += y[i]\n\n    mu_x /= x.shape[0]\n    mu_y /= x.shape[0]\n\n    for i in range(x.shape[0]):\n        shifted_x = x[i] - mu_x\n        shifted_y = y[i] - mu_y\n        norm_x += shifted_x ** 2\n        norm_y += shifted_y ** 2\n        dot_product += shifted_x * shifted_y\n\n    if dot_product == 0.0:\n        return 1.0\n    else:\n        return 1.0 - (dot_product / np.sqrt(norm_x * norm_y))\n\n\nnamed_distances = {\n    # general minkowski distances\n    \"euclidean\": euclidean,\n    \"l2\": euclidean,\n    \"manhattan\": manhattan,\n    \"taxicab\": manhattan,\n    \"l1\": manhattan,\n    # Standardised/weighted distances\n    # Other distances\n    \"cosine\": cosine, # input to annoy = angular\n    # Binary distances\n    \"hamming\": hamming,\n    # \"dot\": dot,\n\n}\n", "meta": {"hexsha": "223963ea9439e06d368914ed3bd8edf526916bc0", "size": 2339, "ext": "py", "lang": "Python", "max_stars_repo_path": "openTSNE/annoy/distances.py", "max_stars_repo_name": "logichris/TSNE-multi-ann", "max_stars_repo_head_hexsha": "a62edf4470be238aa93f824bc92a4fb8b1681ccf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openTSNE/annoy/distances.py", "max_issues_repo_name": "logichris/TSNE-multi-ann", "max_issues_repo_head_hexsha": "a62edf4470be238aa93f824bc92a4fb8b1681ccf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openTSNE/annoy/distances.py", "max_forks_repo_name": "logichris/TSNE-multi-ann", "max_forks_repo_head_hexsha": "a62edf4470be238aa93f824bc92a4fb8b1681ccf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0720720721, "max_line_length": 94, "alphanum_fraction": 0.562206071, "include": true, "reason": "import numpy,import numba", "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079558, "lm_q2_score": 0.900529781446146, "lm_q1q2_score": 0.8565318942472249}}
{"text": "# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as pl\r\n\r\n#%% Q1 setup\r\ndef binomial(n, p, N):\r\n    return np.math.factorial(N)/(np.math.factorial(n)*np.math.factorial(N-n))*(p**n)*((1-p)**(N-n))\r\n\r\ndef uniform(n, p, N):\r\n    return 1/(N+1)\r\n\r\ndef KL(p, N, distp, distq):\r\n    kl = 0\r\n    for n in range(N):\r\n        kl -= distp(n, p, N)*np.log2(distq(n, p, N)/distp(n, p, N))\r\n    return kl\r\n\r\ndef align_yaxis(ax1, v1, ax2, v2):\r\n    \"\"\"adjust ax2 ylimit so that v2 in ax2 is aligned to v1 in ax1\"\"\"\r\n    _, y1 = ax1.transData.transform((0, v1))\r\n    _, y2 = ax2.transData.transform((0, v2))\r\n    inv = ax2.transData.inverted()\r\n    _, dy = inv.transform((0, 0)) - inv.transform((0, y1-y2))\r\n    miny, maxy = ax2.get_ylim()\r\n    ax2.set_ylim(miny+dy, maxy+dy)\r\n\r\n#%% Q1(c)\r\nKL_N10 = []\r\nKL_N100 = []\r\n\r\nfor p in np.linspace(0, 1, 1000):\r\n    KL_N10.append(KL(p, 10, uniform, binomial))\r\n    KL_N100.append(KL(p, 100, uniform, binomial))\r\n\r\nfig, ax = pl.subplots(1,1)\r\nax.plot(np.linspace(0, 1, 1000), KL_N10, 'b-', label=\"N=10\")\r\nax2 = ax.twinx()\r\nax2.plot(np.linspace(0, 1, 1000), KL_N100, 'r-', label=\"N=100\")\r\nax.set_xlabel(\"p\")\r\nax.set_ylabel(\"KL divergence (N=10)\")\r\nax2.set_ylabel(\"KL divergence (N=100)\")\r\nalign_yaxis(ax, 0, ax2, 0)\r\nax.legend()\r\nax2.legend()\r\n\r\n#%% Q1(d)\r\ndef poisson(n, p, N):\r\n    lam = p*N\r\n    return (lam**n)*(np.exp(-lam))/np.math.factorial(n)\r\n\r\nKL_lam_N10 = []\r\nKL_lam_N100 = []\r\n\r\nfor p in np.linspace(0, 1, 1000):\r\n    KL_lam_N10.append(KL(p, 10, poisson, binomial))\r\n    KL_lam_N100.append(KL(p, 100, poisson, binomial))\r\n    \r\nfig1, ax1 = pl.subplots(1,1)\r\nax1.plot(np.linspace(0, 1, 1000), KL_lam_N10, 'b-', label=\"N=10\")\r\nax3 = ax1.twinx()\r\nax3.plot(np.linspace(0, 1, 1000), KL_lam_N100, 'r-', label=\"N=100\")\r\nax1.set_xlabel(\"p\")\r\nax1.set_ylabel(\"KL divergence (N=10)\")\r\nax3.set_ylabel(\"KL divergence (N=10000)\")\r\nalign_yaxis(ax1, 0, ax3, 0)\r\nax1.legend(loc=0)\r\nax3.legend(loc=6)\r\n\r\n#%% Q5(a)\r\nimport math\r\ndef eff(N):\r\n    return np.log2(N)/math.ceil(np.log2(N))\r\n\r\nN_arr = []\r\n\r\nfor n in range(2,101):\r\n    N_arr.append(eff(n))\r\n\r\nfig2, ax4 = pl.subplots(1,1)\r\nax4.plot(np.arange(2, 101), N_arr, 'b-')\r\nax4.set_xlabel(r\"$N$\")\r\nax4.set_ylabel(r\"Efficiency\")\r\n\r\n#%%\r\nN_arr = np.array(N_arr)\r\nprint(np.arange(2,101)[np.argmin(N_arr)]) # N = 5 gives smallest efficiency\r\nprint(np.min(N_arr))\r\nprint(N_arr[-1])\r\n", "meta": {"hexsha": "15cb5eb58f68cbe18e3650e64391ce786f96e5b7", "size": 2372, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/info_ps3.py", "max_stars_repo_name": "adrielyeung/info-theory", "max_stars_repo_head_hexsha": "89863cf5d704c4c6396647d29d6e0446e8627c4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-06T19:01:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-06T19:01:13.000Z", "max_issues_repo_path": "code/info_ps3.py", "max_issues_repo_name": "adrielyeung/info-theory", "max_issues_repo_head_hexsha": "89863cf5d704c4c6396647d29d6e0446e8627c4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/info_ps3.py", "max_forks_repo_name": "adrielyeung/info-theory", "max_forks_repo_head_hexsha": "89863cf5d704c4c6396647d29d6e0446e8627c4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3555555556, "max_line_length": 100, "alphanum_fraction": 0.6037099494, "include": true, "reason": "import numpy", "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.9019206765295399, "lm_q1q2_score": 0.8565264383270638}}
{"text": "import numpy as np\r\n\r\na = np.array([20,30,40,50])     # [20 30 40 50]\r\nb = np.arange(4)        # [0 1 2 3]\r\nprint(a)\r\nprint(b)\r\n\r\nc = a-b\r\nprint(c)\r\n\r\n\"\"\" [20 30 40 50]\r\n    [0 1 2 3]\r\n    [20 29 38 47]\r\n    \"\"\"\r\n\r\nd = b**2    # [0 1 4 9]\r\nprint(d)\r\n\r\ne = 10 * np.sin(a)      # [ 9.12945251 -9.88031624  7.4511316  -2.62374854]\r\nprint(e)\r\n\r\nprint(e < 7)        # [False  True False  True]\r\nprint(a*b)     # [  0  30  80 150]\r\n\r\nprint(a@b)     # matris çarpımı sonucu : 260\r\nprint(a.dot(b)) # matris çarpımı sonucu : 260\r\n\r\nf = np.ones((2,4)) \r\n\r\n\"\"\" [[1. 1. 1. 1.]\r\n [1. 1. 1. 1.]] \"\"\"\r\n\r\ng = np.zeros((2,4))\r\n\r\n\"\"\" [[0. 0. 0. 0.]\r\n [0. 0. 0. 0.]] \"\"\"\r\n\r\nh = np.random.random((2,4))\r\n\r\n\"\"\" [[0.24448762 0.30569748 0.38721877 0.42359117]\r\n [0.74705078 0.64296611 0.87855028 0.44236936]] \"\"\"\r\n\r\ni = np.sum(b)     # 6\r\n\r\nj  = np.min(c)    # 20\r\n\r\nk = np.max(h)     # 0.8785502826111841\r\n\r\nl =np.sqrt(b)     # [0.         1.         1.41421356 1.73205081]\r\n\r\nprint(f)\r\nprint('----------------------')\r\nprint(g)\r\nprint('----------------------')\r\nprint(h)\r\nprint('----------------------')\r\nprint(i)\r\nprint('----------------------')\r\nprint(j)\r\nprint('----------------------')\r\nprint(k)\r\nprint('----------------------')\r\nprint(l)", "meta": {"hexsha": "bf065a2cb4db3b393996eeeeafef469438c0eaf4", "size": 1221, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data_Analysis-main/Numpy/basic_operations.py", "max_stars_repo_name": "bartubozkurt/data_analysis", "max_stars_repo_head_hexsha": "536d2bc9f75b9d8ff28cc2859a52498dd2f65627", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Data_Analysis-main/Numpy/basic_operations.py", "max_issues_repo_name": "bartubozkurt/data_analysis", "max_issues_repo_head_hexsha": "536d2bc9f75b9d8ff28cc2859a52498dd2f65627", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data_Analysis-main/Numpy/basic_operations.py", "max_forks_repo_name": "bartubozkurt/data_analysis", "max_forks_repo_head_hexsha": "536d2bc9f75b9d8ff28cc2859a52498dd2f65627", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.380952381, "max_line_length": 76, "alphanum_fraction": 0.4283374283, "include": true, "reason": "import numpy", "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.9019206745523101, "lm_q1q2_score": 0.8565264364493492}}
{"text": "\"\"\"\nSimulating a black body curve\n\n\"\"\"\n\nfrom scipy.optimize import curve_fit\nimport pylab as plt\nimport numpy as np\n\ndef blackbody_lam(lam, T):\n    \"\"\" Blackbody as a function of wavelength (um) and temperature (K).\n\n    returns units of erg/s/cm^2/cm/Steradian\n    \"\"\"\n    from scipy.constants import h,k,c\n    lam = 1e-6 * lam # convert to metres\n    return 2*h*c**2 / (lam**5 * (np.exp(h*c / (lam*k*T)) - 1))\n\nwa = np.linspace(0.1, 2, 100)   # wavelengths in um\nT1 = 5000.\nT2 = 8000.\ny1 = blackbody_lam(wa, T1)\ny2 = blackbody_lam(wa, T2)\nytot = y1 + y2\n\nnp.random.seed(1)\n\n# make synthetic data with Gaussian errors\n\nsigma = np.ones(len(wa)) * 1 * np.median(ytot)\nydata = ytot + np.random.randn(len(wa)) * sigma\n\n# plot the input model and synthetic data\n\nplt.figure()\nplt.plot(wa, y1, ':', lw=2, label='T1=%.0f' % T1)\nplt.plot(wa, y2, ':', lw=2, label='T2=%.0f' % T2)\nplt.plot(wa, ytot, ':', lw=2, label='T1 + T2\\n(true model)')\nplt.plot(wa, ydata, ls='steps-mid', lw=2, label='Fake data')\nplt.xlabel('Wavelength (microns)')\nplt.ylabel('Intensity (erg/s/cm$^2$/cm/Steradian)')\n\n# fit two blackbodies to the synthetic data\n\ndef func(wa, T1, T2):\n    return blackbody_lam(wa, T1) + blackbody_lam(wa, T2)\n\n# Note the initial guess values for T1 and T2 (p0 keyword below). They\n# are quite different to the known true values, but not *too*\n# different. If these are too far away from the solution curve_fit()\n# will not be able to find a solution. This is not a Python-specific\n# problem, it is true for almost every fitting algorithm for\n# non-linear models. The initial guess is important!\n\npopt, pcov = curve_fit(func, wa, ydata, p0=(1000, 3000), sigma=sigma)\n\n# get the best fitting parameter values and their 1 sigma errors\n# (assuming the parameters aren't strongly correlated).\n\nbestT1, bestT2 = popt\nsigmaT1, sigmaT2 = np.sqrt(np.diag(pcov))\n\nybest = blackbody_lam(wa, bestT1) + blackbody_lam(wa, bestT2)\n\nprint 'True model values'\nprint '  T1 = %.2f' % T1\nprint '  T2 = %.2f' % T2\n\nprint 'Parameters of best-fitting model:'\nprint '  T1 = %.2f +/- %.2f' % (bestT1, sigmaT1)\nprint '  T2 = %.2f +/- %.2f' % (bestT2, sigmaT2)\n\ndegrees_of_freedom = len(wa) - 2\nresid = (ydata - func(wa, *popt)) / sigma\nchisq = np.dot(resid, resid)\n\nprint degrees_of_freedom, 'dof'\nprint 'chi squared %.2f' % chisq\nprint 'nchi2 %.2f' % (chisq / degrees_of_freedom)\n\n# plot the solution\n\nplt.plot(wa, ybest, label='Best fitting\\nmodel')\nplt.legend(frameon=False)\n\nplt.show()", "meta": {"hexsha": "b519d748f1c8627226cbd9cbdd45b47fe3d5ea40", "size": 2460, "ext": "py", "lang": "Python", "max_stars_repo_path": "deprecated/atmosphere_effects/black_body.py", "max_stars_repo_name": "zhuchangzhan/SEAS", "max_stars_repo_head_hexsha": "d844ceecc54a475a5384925f45a2078eef3416ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-06T23:09:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-06T23:09:08.000Z", "max_issues_repo_path": "deprecated/atmosphere_effects/black_body.py", "max_issues_repo_name": "azariven/SEAS", "max_issues_repo_head_hexsha": "d844ceecc54a475a5384925f45a2078eef3416ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deprecated/atmosphere_effects/black_body.py", "max_forks_repo_name": "azariven/SEAS", "max_forks_repo_head_hexsha": "d844ceecc54a475a5384925f45a2078eef3416ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-04T17:32:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-04T17:32:31.000Z", "avg_line_length": 28.6046511628, "max_line_length": 71, "alphanum_fraction": 0.6780487805, "include": true, "reason": "import numpy,from scipy", "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561703644736, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.8565069159242228}}
{"text": "\"\"\"\nSome code for B-Spline curve\n\nS(x) = Sum_{j=0}^{n-1} c[j] * B[j,k;t](x)\n\nB[i,0](x) = 1 if t[i] <= x <= t[i+1], otherwise 0\nB[i,k](x) = (x - t[i]) / (t[i+k] - t[i]) * B[i, k-1](x) + (t[i+k+1] - x) / (t[i+k+1] - t[i+1]) * B[i+1, k-1](x)\n\nRef:\n[1] https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.BSpline.html\n\"\"\"\n\nfrom scipy.interpolate import BSpline\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef basic(x, i, k, t):\n    \"\"\"Basic elements in B-Spline\"\"\"\n    if k == 0:\n        return 1.0 if t[i] <= x < t[i + 1] else 0.0\n\n    if t[i + k] == t[i]:\n        c1 = 0.0\n    else:\n        c1 = (x - t[i]) / (t[i + k] - t[i]) * basic(x, i, k - 1, t)\n\n    if t[i + k + 1] == t[i + 1]:\n        c2 = 0.0\n    else:\n        c2 = (t[i + k + 1] - x) / (t[i + k + 1] - t[i + 1]) * basic(x, i + 1, k - 1, t)\n\n    return c1 + c2\n\n\ndef bspline(x, t, c, k):\n    \"\"\"B-Spline function\"\"\"\n    n = len(t) - k - 1\n    assert (n >= k + 1) and (len(c) >= n)\n    return sum(c[i] * basic(x, i, k, t) for i in range(n))\n\n\ndef main():\n    k = 2\n    t = [0, 1, 2, 3, 4, 5, 6]\n    c = [-1, 2, 0, -1]\n    sp1 = BSpline(t, c, k, True)  # if extrapolate is False, they are the same\n    print(f'BSpline(2.5) = {sp1(2.5)}, bspline(2.5) = {bspline(2.5, t, c, k)}')\n    xx = np.linspace(1.5, 4.5, 50)\n    xx_fine = np.linspace(1.5, 4.5, 500)\n\n    # figure, B-Spline basic function\n    fig = plt.figure('B-Spline Basic Function')\n    ax = fig.add_subplot(111)\n    ax.plot(xx_fine, [basic(x, 2, 0, t) for x in xx_fine], 'k-', label='degree = 0')\n    ax.plot(xx_fine, [basic(x, 2, 1, t) for x in xx_fine], 'b-', label='degree = 1')\n    ax.plot(xx_fine, [basic(x, 2, 2, t) for x in xx_fine], 'r-', label='degree = 2')\n    ax.grid(True)\n    ax.set_title('B-Spline Basic Function B[2, k]')\n    ax.legend(loc='best')\n    plt.show(block=False)\n\n    # figure: B-Spline\n    fig = plt.figure('B-Spline')\n    ax = fig.add_subplot(111)\n    ax.plot(xx, [bspline(x, t, c, k) for x in xx], 'r-', label='naive')\n    ax.plot(xx, sp1(xx), 'b.-', label='BSpline')\n    ax.grid(True)\n    ax.set_title('B-Spline')\n    ax.legend(loc='best')\n    plt.show(block=True)\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "acd282bc635669f931418311373a987c7415719a", "size": 2177, "ext": "py", "lang": "Python", "max_stars_repo_path": "math/bspline_curve.py", "max_stars_repo_name": "chengfzy/PythonStudy", "max_stars_repo_head_hexsha": "7e55c6ea9d3922a3b42b13a074eb679b6f2a4dc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-11T22:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T22:42:53.000Z", "max_issues_repo_path": "math/bspline_curve.py", "max_issues_repo_name": "chengfzy/PythonStudy", "max_issues_repo_head_hexsha": "7e55c6ea9d3922a3b42b13a074eb679b6f2a4dc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/bspline_curve.py", "max_forks_repo_name": "chengfzy/PythonStudy", "max_forks_repo_head_hexsha": "7e55c6ea9d3922a3b42b13a074eb679b6f2a4dc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-11T22:42:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T22:42:54.000Z", "avg_line_length": 28.6447368421, "max_line_length": 111, "alphanum_fraction": 0.5181442352, "include": true, "reason": "import numpy,from scipy", "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561676667173, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.8565069135393003}}
{"text": "# This function does the Gram-Schmidt process\n# It transforms a matrix into a matrix of orthonormal vectors\n\nimport numpy as np\nimport numpy.linalg as la\n\n\n# A => Matrix\ndef gsBasis(A):\n  verySmallNumber = 1e-14\n  B = np.array(A, dtype=np.float_)\n  \n  # loop over vectors in the matrix (column-wise)\n  for i in range(B.shape[1]):\n    # loop over all previous vectors before 'i'\n    for j in range(i):\n      # do the GS procedure\n      B[:,i] = B[:,i] - (B[:,i] @ B[:,j]) * B[:,j]\n\n    # if vector is linearly independent, normalize\n    if la.norm(B[:,i]) > verySmallNumber:\n      B[:, i] = B[:, i] / la.norm(B[:, i])\n    else:\n      B[:,i] = np.zeros_like(B[:,i])\n  \n  return B\n\n# Some matrix definition\nV = np.array([[1,0,2,6],\n              [0,1,8,2],\n              [2,8,3,1],\n              [1,-6,2,3]], dtype=np.float_)\n\n# A non-square matrix\nU = np.array([[3,2,3],\n              [2,5,-1],\n              [2,4,8],\n              [12, 2, 1]], dtype=np.float_)\n\nprint(gsBasis(V))\nNormed = gsBasis(V)\n\n# gsBasis on an orthonormal matrix returns itself\nprint(gsBasis(Normed))\n\ndef dimensions(A) :\n    return np.sum(la.norm(gsBasis(A), axis=0))\n\nprint(dimensions(V))\n\n\n# Now let's see what happens when we have one vector that is a linear combination of the others.\nC = np.array([[1,0,2],\n              [0,1,-3],\n              [1,0,2]], dtype=np.float_)\ngsBasis(C)", "meta": {"hexsha": "a27492a2ab0f35b32112952a373e4d9734b89471", "size": 1360, "ext": "py", "lang": "Python", "max_stars_repo_path": "gramSchmidtnorm.py", "max_stars_repo_name": "ptenteromano/Machine-Learning", "max_stars_repo_head_hexsha": "c73cddfa585b0da34cff2b8523dc0e14b866ef74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-30T23:24:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-30T23:24:34.000Z", "max_issues_repo_path": "gramSchmidtnorm.py", "max_issues_repo_name": "ptenteromano/Machine-Learning", "max_issues_repo_head_hexsha": "c73cddfa585b0da34cff2b8523dc0e14b866ef74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gramSchmidtnorm.py", "max_forks_repo_name": "ptenteromano/Machine-Learning", "max_forks_repo_head_hexsha": "c73cddfa585b0da34cff2b8523dc0e14b866ef74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-05T17:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-05T17:05:35.000Z", "avg_line_length": 24.2857142857, "max_line_length": 96, "alphanum_fraction": 0.5698529412, "include": true, "reason": "import numpy", "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561721629776, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.8565069041941654}}
{"text": "from scipy.stats import norm\nfrom scipy.integrate import quad\nimport numpy as np\n\n\ndef d2(n=2, method=\"exact\"):\n    \"\"\"\n    Computes the d2 statistic used for measuring\n    relative range standard deviation approximation.\n\n    The d2 statistic is often found in statistical process\n    control tables.\n\n    That is, standard deviation can be approximated by\n    R / d2 where R is the range of the data (max - min)\n    and d2 is computed as below.\n\n    See also:\n    https://v8doc.sas.com/sashtml/qc/chapc/sect9.htm\n\n    :param n:\n        Number of distributions considered for computing\n        d2. All are normal with mean=0 and std=1.\n    :param method:\n        Optional. Method to use. Default \"exact\".\n            - \"exact\" computes the exact infinite integral.\n            - \"random\" uses normal distributions generated\n              on the fly to compute d2.\n    :return:\n        d2:\n            the expectation value [that is, average here]\n            of the ranges of the distributions\n    \"\"\"\n    if method == \"exact\":\n        def f(x, n):\n            return 1 - (1 - norm.cdf(x)) ** n - (norm.cdf(x)) ** n\n\n        d2 = quad(f, -np.inf, np.inf, args=(n))[0]\n        return d2\n\n    elif method == \"random\":\n        x = {}\n        # slots to fill with normally distributed samples\n        for i in range(n):\n            x[i] = norm.rvs(size=100000, loc=0, scale=1)\n\n        x = np.vstack([x[i] for i in x])\n\n        maxs = np.amax(x, axis=0)\n        mins = np.amin(x, axis=0)\n\n        r = maxs - mins\n\n        d2 = np.average(r)\n        return d2\n\n", "meta": {"hexsha": "dee72a73fd96f72c992bef3634ed1930be874920", "size": 1557, "ext": "py", "lang": "Python", "max_stars_repo_path": "scipy/stats/d2.py", "max_stars_repo_name": "khavernathy/scipy", "max_stars_repo_head_hexsha": "f09a01721a3859240a8b69f42df8a45508da86d7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scipy/stats/d2.py", "max_issues_repo_name": "khavernathy/scipy", "max_issues_repo_head_hexsha": "f09a01721a3859240a8b69f42df8a45508da86d7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scipy/stats/d2.py", "max_forks_repo_name": "khavernathy/scipy", "max_forks_repo_head_hexsha": "f09a01721a3859240a8b69f42df8a45508da86d7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3157894737, "max_line_length": 66, "alphanum_fraction": 0.5844572897, "include": true, "reason": "import numpy,from scipy", "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147193720649, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.8565000357987549}}
{"text": "import rotation\nimport numpy as np\n\ndef sphericalToCartesian(rho, lat, lon):\n    phi = lat\n    the = lon\n    x = rho * np.cos(phi) * np.cos(the) \n    y = rho * np.cos(phi) * np.sin(the)\n    z = rho * np.sin(phi)\n    return np.array([[x],\n                    [y],\n                    [z]])\n\ndef cartesianToSpherical(x,y,z):\n    pho = np.sqrt(x**2 + y**2 + z**2)\n    lon = np.arctan2(y,x)\n    base = np.sqrt(x**2 + y**2)\n    lat = np.arctan2(z, base)\n\n    return (pho, (180/np.pi)*lat, (180/np.pi)*lon)\n    \ndef localToWorldMatrix(lat, lon):\n    lamda = lon * np.pi/180\n    phi = lat * np.pi/180\n    R = np.array([[-np.sin(lamda), -np.sin(phi) * np.cos(lamda), np.cos(phi) * np.cos(lamda)],\n                [np.cos(lamda), -np.sin(phi) * np.sin(lamda), np.cos(phi) * np.sin(lamda)],\n                [0, np.cos(phi), np.sin(phi)]])\n    return R\n\ndef worldToLocalMatrix(lat, lon):\n    # phi = lat\n    # the = lon\n    # R = rotation.RotX(180) * rotation.RotZ(90) * rotation.RotX(phi) * rotation.RotZ(the)\n    R = localToWorldMatrix(lat, lon)\n    return np.linalg.inv(R)\n\ndef pointWorldToLocal(p1_w, p0_w, R_wl):\n    return R_wl * (p1_w - p0_w)\n    \ndef pointLocalToWorld(p1_l, p0_w, R_lw):    \n    return R_lw * p1_l + p0_w\n\n# if __name__ == \"__main__\":\n#     R = localToWorldMatrix(30,60)\n#     print(R)\n    \n", "meta": {"hexsha": "fc71786293d7ebbd1e2b01fb1fcfee0f7740e395", "size": 1305, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/coord_transforms/transform.py", "max_stars_repo_name": "castacks/xplane_ros", "max_stars_repo_head_hexsha": "b945d8c6d535487b8f9d4710aec579d3406d3772", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2021-09-06T18:27:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T14:01:48.000Z", "max_issues_repo_path": "src/coord_transforms/transform.py", "max_issues_repo_name": "castacks/xplane_ros", "max_issues_repo_head_hexsha": "b945d8c6d535487b8f9d4710aec579d3406d3772", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-01T08:37:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T12:06:06.000Z", "max_forks_repo_path": "src/coord_transforms/transform.py", "max_forks_repo_name": "castacks/xplane_ros", "max_forks_repo_head_hexsha": "b945d8c6d535487b8f9d4710aec579d3406d3772", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-11T13:13:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T09:05:11.000Z", "avg_line_length": 27.7659574468, "max_line_length": 94, "alphanum_fraction": 0.554789272, "include": true, "reason": "import numpy", "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147169737826, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.8565000352077233}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Dec  2 13:39:48 2021\r\n\r\n@author: Oliver\r\n\r\n\"\"\"\r\n\r\n\r\n\"\"\"Roots of Equation Systems\"\"\"\r\nimport math\r\n\r\nimport numpy as np\r\n\r\n\"\"\"Finding roots of multi-variable equations\"\"\"\r\n\r\nx = 1.5\r\ny = 3.5\r\n\r\ndudx = lambda x, y: 2*x+y\r\ndvdx = lambda y: 3*y**2\r\ndudy = lambda x: x\r\ndvdy = lambda x, y: 1+6*x*y\r\n\r\na = np.array([[dudx(x,y),dudy(x)], [dvdx(y),dvdy(x,y)]]) # Jacobian Matrix\r\n\r\ninitial_u_guess = lambda x, y: x**2 + x*y - 10\r\ninitial_v_guess = lambda x, y: y + 3*x*y**2 -57\r\n\r\nx_new = x - ((initial_u_guess(x, y)*dvdy(x,y) - initial_v_guess(x, y)*x))/np.linalg.det(a)\r\ny_new = y - (initial_v_guess(x, y)*dudx(x,y) - (initial_u_guess(x, y)*dvdx(y)))/np.linalg.det(a)\r\nx_sol = 2\r\ny_sol = 3\r\ncounter = 0\r\nerror = 0\r\n\r\nwhile True:\r\n    counter += 1\r\n    x_new = x - ((initial_u_guess(x, y)*dvdy(x,y) - initial_v_guess(x, y)*x))/np.linalg.det(a)\r\n    y_new = y - (initial_v_guess(x, y)*dudx(x,y) - (initial_u_guess(x, y)*dvdx(y)))/np.linalg.det(a)\r\n\r\n    if x_sol - error<=x_new<=x_sol + error:\r\n        print(f'The solution has been found after {counter} iterations and the values are x: {x_new} and y: {y_new}')\r\n        break\r\n    if counter == 3:\r\n        print(f'The solution after {counter} iterations is: x: {x_new}, y: {y_new} with relative error in: x: {abs(x_new-x_sol)/x_sol} and y: {abs(y_new-y_sol)/y_sol}')\r\n    else:\r\n        x = x_new\r\n        y = y_new\r\n\r\n\"\"\"Roots of Polynomial Equations\"\"\"\r\n# Factorization of Polynomials\r\n\r\nf = [1,2,-24]\r\nguess = 4\r\nvalues =[f[0]]\r\nz = f[0]\r\nfor i in range(0,len(f)-2):\r\n    x = f[i+1] + z*guess\r\n    print(x)\r\n    z = x\r\n    values.append(x)\r\nprint(values)\r\n\r\n\"\"\"Polynomial Division\"\"\"\r\n\r\ndef expanded_synthetic_division(dividend, divisor):\r\n    \"\"\"Fast polynomial division by using Expanded Synthetic Division. \r\n    Also works with non-monic polynomials.\r\n\r\n    Dividend and divisor are both polynomials, which are here simply lists of coefficients. \r\n    E.g.: x**2 + 3*x + 5 will be represented as [1, 3, 5]\r\n    \"\"\"\r\n    out = list(dividend)  # Copy the dividend\r\n    normalizer = divisor[0]\r\n    for i in range(len(dividend) - len(divisor) + 1):\r\n        # For general polynomial division (when polynomials are non-monic),\r\n        # we need to normalize by dividing the coefficient with the divisor's first coefficient\r\n        out[i] /= normalizer\r\n\r\n        coef = out[i]\r\n        if coef != 0:  # Useless to multiply if coef is 0\r\n            # In synthetic division, we always skip the first coefficient of the divisor,\r\n            # because it is only used to normalize the dividend coefficients\r\n            for j in range(1, len(divisor)):\r\n                out[i + j] += -divisor[j] * coef\r\n\r\n    # The resulting out contains both the quotient and the remainder,\r\n    # the remainder being the size of the divisor (the remainder\r\n    # has necessarily the same degree as the divisor since it is\r\n    # what we couldn't divide from the dividend), so we compute the index\r\n    # where this separation is, and return the quotient and remainder.\r\n    separator = 1 - len(divisor)\r\n    return out[:separator], out[separator:]  # Return quotient, remainder.\r\n\r\nif __name__=='__main__':\r\n    print (\"POLYNOMINAL SYNTHETIC DIVISION\")\r\n    N = [1, 2, -24]\r\n    D = [1, -4]\r\n    print (\" %s /%s =\" % (N,D),)\r\n    print (\" %s remainder %s\" % expanded_synthetic_division(N, D))\r\n\r\n\"\"\"Muller's Technique - Finding Roots\"\"\"\r\n\r\ndef f(x):\r\n    return x**3 - 13*x - 12\r\n\r\ndef Muller(x_r, h, eps, maxit):\r\n    iter = 0\r\n    x2 = x_r\r\n    x1 = x_r + h * x_r\r\n    x0 = x_r - h * x_r\r\n    while True:\r\n        iter += 1\r\n        h0 = x1 - x0\r\n        h1 = x2 - x1\r\n        d0 = (f(x1) - f(x0)) / h0\r\n        d1 = (f(x2) - f(x1)) / h1\r\n        a = (d1 - d0) / (h1 + h0)\r\n        b = a * h1 + d1\r\n        c = f(x2)\r\n        rad = math.sqrt(abs(b**2 - 4*a*c))\r\n        if abs(b + rad) > abs(b - rad):\r\n            den = b + rad\r\n        else:\r\n            den = b - rad\r\n        dx_r = -2 * c / den\r\n        x_r = x2 + dx_r\r\n        print(f'Iteration: {iter}, Value of root: {x_r}, Error: {abs((x2/x_r*100)-100)}%')    \r\n        if (abs(dx_r) < eps * x_r or iter >= maxit):\r\n            break\r\n        x0 = x1\r\n        x1 = x2\r\n        x2 = x_r\r\n    return None\r\nx_r = 20\r\nh = 0.1\r\neps = 0.01\r\nmaxit = 10\r\n\r\nsolution = Muller(x_r, h, eps, maxit)\r\nprint(solution)\r\n\r\n", "meta": {"hexsha": "cd8f5e88cc29daae8b5e3cd98e5dbdf3b750f3af", "size": 4348, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lecture_8_Tasks.py", "max_stars_repo_name": "oliver779/Computational_Methods_Course", "max_stars_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lecture_8_Tasks.py", "max_issues_repo_name": "oliver779/Computational_Methods_Course", "max_issues_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lecture_8_Tasks.py", "max_forks_repo_name": "oliver779/Computational_Methods_Course", "max_forks_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1944444444, "max_line_length": 169, "alphanum_fraction": 0.5689972401, "include": true, "reason": "import numpy", "num_tokens": 1363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147129766448, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.8565000316870561}}
{"text": "# Нахождение прямой, проходящей через набор точек\n# Дмитрий Хизбуллин, 2021\n\nimport math\nimport numpy as np\nfrom typing import Optional, Any\nimport matplotlib.pyplot as plt\n\n\ndef generate_points(axis: Optional[Any] = None) -> np.ndarray:\n    \"\"\"\n    Функция, генерирующая массив точек, приблизительно лежащих на\n    отрезке прямой.\n\n    :param axis: Набор осей, на которых рисовать график\n    :return: Numpy массив формы [N, 2] точек на прямой\n    \"\"\"\n\n    # Давайте сгенерируем 10 точек, лежащих на прямой\n    num_points = 10\n    p_initial = np.array((-2, 3))\n    speed = 1.0\n    angle_degrees = -30\n    angle_radians = angle_degrees / 180 * math.pi\n    velocity = speed * np.array((math.cos(angle_radians),\n                                 math.sin(angle_radians)))\n    ideal_points = np.expand_dims(p_initial, 0) + \\\n                   np.outer(np.arange(0, num_points), velocity)\n    # и добавим немного шума, чтобы промоделировать реальные измерения\n    noise = 0.1 * np.random.randn(num_points, 2)\n    points = ideal_points + noise\n\n    if axis is not None:\n        for ax in axis:\n            ax.set_title(\"Входной набор точек\")\n            ax.plot(points[:, 0], points[:, 1], 'or')\n            ax.grid(True, linestyle='--')\n            ax.axis('equal')\n\n    return points\n\n\ndef least_squares(points: np.ndarray, axis: Optional[Any] = None) \\\n        -> np.ndarray:\n    \"\"\"\n    Функция для аппроксимации массива точек прямой, основанная на\n    методе наименьших квадратов.\n\n    :param points: Входной массив точек формы [N, 2]\n    :param axis: Набор осей, на которых рисовать график\n    :return: Numpy массив формы [N, 2] точек на прямой\n    \"\"\"\n\n    x = points[:, 0]\n    y = points[:, 1]\n    # Для метода наименьших квадратов нам нужно, чтобы X был матрицей,\n    # в которой первый столбец - единицы, а второй - x координаты точек\n    X = np.vstack((np.ones(x.shape[0]), x)).T\n    normal_matrix = np.dot(X.T, X)\n    moment_matrix = np.dot(X.T, y)\n    # beta_hat это вектор [перехват, наклон], рассчитываем его в\n    # в соответствии с формулой.\n    beta_hat = np.dot(np.linalg.inv(normal_matrix), moment_matrix)\n    intercept = beta_hat[0]\n    slope = beta_hat[1]\n    # Теперь, когда мы знаем параметры прямой, мы можем\n    # легко вычислить y координаты точек на прямой.\n    y_hat = intercept + slope * x\n    # Соберем x и y в единую матрицу, которую мы собираемся вернуть\n    # в качестве результата.\n    points_hat = np.vstack((x, y_hat)).T\n\n    if axis is not None:\n        for ax in axis:\n            ax.set_title(\"Метод наименьших квадратов\")\n            ax.plot(x, y, 'or')\n            ax.plot(x, y_hat, 'o-', mfc='none')\n            ax.grid(True, linestyle='--')\n            ax.axis('equal')\n\n    return points_hat\n\n\ndef ransac(points: np.ndarray,\n           min_inliers: int = 4,\n           max_distance: float = 0.15,\n           outliers_fraction: float = 0.5,\n           probability_of_success: float = 0.99,\n           axis: Optional[Any] = None) -> Optional[np.ndarray]:\n    \"\"\"\n    RANdom SAmple Consensus метод нахождения наилучшей\n    аппроксимирующей прямой.\n\n    :param points: Входной массив точек формы [N, 2]\n    :param min_inliers: Минимальное количество не-выбросов\n    :param max_distance: максимальное расстояние до поддерживающей прямой,\n                         чтобы точка считалась не-выбросом\n    :param outliers_fraction: Ожидаемая доля выбросов\n    :param probability_of_success: желаемая вероятность, что поддерживающая\n                                   прямая не основана на точке-выбросе\n    :param axis: Набор осей, на которых рисовать график\n    :return: Numpy массив формы [N, 2] точек на прямой,\n             None, если ответ не найден.\n    \"\"\"\n\n    # Давайте вычислим необходимое количество итераций\n    num_trials = int(math.log(1 - probability_of_success) /\n                     math.log(1 - outliers_fraction**2))\n\n    best_num_inliers = 0\n    best_support = None\n    for _ in range(num_trials):\n        # В каждой итерации случайным образом выбираем две точки\n        # из входного массива и называем их \"суппорт\"\n        random_indices = np.random.choice(\n            np.arange(0, len(points)), size=(2,), replace=False)\n        assert random_indices[0] != random_indices[1]\n        support = np.take(points, random_indices, axis=0)\n\n        # Здесь мы считаем расстояния от всех точек до прямой\n        # заданной суппортом. Для расчета расстояний от точки до\n        # прямой подходит функция векторного произведения.\n        # Особенность np.cross в том, что функция возвращает только\n        # z координату векторного произведения, а она-то нам и нужна.\n        cross_prod = np.cross(support[1, :] - support[0, :],\n                              support[1, :] - points)\n        support_length = np.linalg.norm(support[1, :] - support[0, :])\n        # cross_prod содержит знаковое расстояние, поэтому нам нужно\n        # взять модуль значений.\n        distances = np.abs(cross_prod) / support_length\n\n        # Не-выбросы - это все точки, которые ближе, чем max_distance\n        # к нашей прямой-кандидату.\n        num_inliers = np.sum(distances < max_distance)\n        # Здесь мы обновляем лучший найденный суппорт\n        if num_inliers >= min_inliers and num_inliers > best_num_inliers:\n            best_num_inliers = num_inliers\n            best_support = support\n\n    # Если мы успешно нашли хотя бы один суппорт,\n    # удовлетворяющий всем требованиям\n    if best_support is not None:\n        # Спроецируем точки из входного массива на найденную прямую\n        support_start = best_support[0]\n        support_vec = best_support[1] - best_support[0]\n        # Для расчета проекций отлично подходит функция\n        # скалярного произведения.\n        offsets = np.dot(support_vec, (points - support_start).T)\n        proj_vectors = np.outer(support_vec, offsets).T\n        support_sq_len = np.inner(support_vec, support_vec)\n        projected_vectors = proj_vectors / support_sq_len\n        projected_points = support_start + projected_vectors\n\n        if axis is not None:\n            for ax in axis:\n                ax.set_title(\"RANSAC\")\n                ax.scatter(best_support[:, 0], best_support[:, 1],\n                            s=200, facecolors='none', edgecolors='k', marker='s')\n                ax.plot(points[:, 0], points[:, 1], 'or')\n                ax.plot(projected_points[:, 0], projected_points[:, 1],\n                         'o-', mfc='none')\n                ax.grid(True, linestyle='--')\n                ax.axis('equal')\n    else:\n        projected_points = None\n\n    return projected_points\n\n\ndef pca(points: np.ndarray, axis: Optional[Any] = None) -> np.ndarray:\n    \"\"\"\n    Метод главных компонент (PCA) оценки направления\n    максимальной дисперсии облака точек.\n\n    :param points: Входной массив точек формы [N, 2]\n    :param axis: Набор осей, на которых рисовать график\n    :return: Numpy массив формы [N, 2] точек на прямой\n    \"\"\"\n\n    # Найдем главные компоненты.\n    # В первую очередь нужно центрировать облако точек, вычтя среднее\n    mean = np.mean(points, axis=0)\n    centered = points - mean\n    # Функция вычисления собственных значений и векторов np.linalg.eig\n    # требует ковариационную матрицу в качестве аргумента.\n    cov = np.cov(centered.T)\n    # Теперь мы можем посчитать главные компоненты, заданные\n    # собственными значениями и собственными векторами.\n    eigenval, eigenvec = np.linalg.eig(cov)\n    # Мы хотим параметризовать целевую прямую в координатной системе,\n    # заданной собственным вектором, собственное значение которого\n    # наиболее велико (направление наибольшей вариативности).\n    argmax_eigen = np.argmax(eigenval)\n    # Нам понадобятся проекции входных точек на наибольший собственный\n    # вектор.\n    loc_pca = np.dot(centered, eigenvec)\n    loc_maxeigen = loc_pca[:, argmax_eigen]\n    max_eigenval = eigenval[argmax_eigen]\n    max_eigenvec = eigenvec[:, argmax_eigen]\n    # Ре-параметризуем прямую, взяв за начало отрезка проекции\n    # первой и последней точки на прямую.\n    loc_start = mean + max_eigenvec * loc_maxeigen[0]\n    loc_final = mean + max_eigenvec * loc_maxeigen[-1]\n    linspace = np.linspace(0, 1, num=len(points))\n    # Получаем позиции точек, которые идут с одинаковым интервалом,\n    # таким образом удаляя шум измерений и вдоль траектории движения.\n    positions = loc_start + np.outer(linspace, loc_final - loc_start)\n\n    if axis is not None:\n        for ax in axis:\n            ax.set_title(\"PCA\")\n            ax.plot(points[:, 0], points[:, 1], 'or')\n            ax.plot(positions[:, 0], positions[:, 1], 'o-', mfc='none')\n            ax.grid(True, linestyle='--')\n            ax.axis('equal')\n\n    return positions\n\n\ndef main():\n    fig_all, axs = plt.subplots(2, 2)\n    fig_all.set_size_inches(10.0, 6.0)\n\n    fig, ax = plt.subplots(1, 1)\n    fig.set_size_inches(5.0, 3.0)\n    points = generate_points(axis=(axs[0, 0], ax))\n    fig.savefig('1_points.png', dpi=300)\n\n    fig, ax = plt.subplots(1, 1)\n    fig.set_size_inches(5.0, 3.0)\n    least_squares(points, axis=(axs[0, 1], ax))\n    fig.savefig('2_leastsq.png', dpi=300)\n\n    fig, ax = plt.subplots(1, 1)\n    fig.set_size_inches(5.0, 3.0)\n    ransac(points, axis=(axs[1, 0], ax))\n    fig.savefig('3_ransac.png', dpi=300)\n\n    fig, ax = plt.subplots(1, 1)\n    fig.set_size_inches(5.0, 3.0)\n    pca(points, axis=(axs[1, 1], ax))\n    fig.savefig('4_pca.png', dpi=300)\n\n    for ax in axs.flat:\n        ax.set(xlabel='x', ylabel='y')\n\n    for ax in axs.flat:\n        ax.label_outer()\n\n    fig_all.savefig('0_all.png', dpi=300)\n\n    plt.show()\n\n    print(\"Done!\")\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "ad8f9d60dcae3f5f49e9c841d09b528b5dd63506", "size": 9612, "ext": "py", "lang": "Python", "max_stars_repo_path": "ru/main.py", "max_stars_repo_name": "Obs01ete/bestfit", "max_stars_repo_head_hexsha": "62ccaa7e3024e896d3b1e4154c7b08ef2d6458e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-01-26T09:10:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T15:21:42.000Z", "max_issues_repo_path": "ru/main.py", "max_issues_repo_name": "Obs01ete/bestfit", "max_issues_repo_head_hexsha": "62ccaa7e3024e896d3b1e4154c7b08ef2d6458e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ru/main.py", "max_forks_repo_name": "Obs01ete/bestfit", "max_forks_repo_head_hexsha": "62ccaa7e3024e896d3b1e4154c7b08ef2d6458e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.111969112, "max_line_length": 81, "alphanum_fraction": 0.6393050354, "include": true, "reason": "import numpy", "num_tokens": 3129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.8991213847035617, "lm_q1q2_score": 0.8564797679413724}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr  8 16:49:15 2020\r\n\r\n@author: Mehul\r\n\"\"\"\r\nfrom statistics import mean\r\nimport numpy as np\r\nimport random\r\n\r\n#xs=np.array([1,2,3,4,5,6,7],dtype=np.float64)\r\n#ys=np.array([5,6,5,7,8,6,10],dtype=np.float64)\r\n\r\n\r\n#creating a dataset for testing\r\ndef create_dataset(hm,variance,step=2,correlation=False,which_type='pos'):\r\n\tval=1\r\n\tys=[]\r\n\tfor i in range(hm):\r\n\t\ty=val+random.randrange(-variance,variance)\r\n\t\tys.append(y)\r\n\t\tif correlation==True:\r\n\t\t\tif which_type=='pos':\r\n\t\t\t\tval+=step\r\n\t\t\telif which_type=='neg':\r\n\t\t\t\tval-=val   \r\n\txs=[i for i in range(len(ys))]\t\t\t   \r\n\treturn np.array(xs,dtype=np.float64),np.array(ys,dtype=np.float64)\r\n\t\r\n#defining a function to get the best fit slope\r\n#here we pass in the array of points in the function and get the slope anf the intercept \r\ndef best_fit_slope_and_intercept(xs,ys):\r\n\tm =(((mean(xs)*mean(ys))-mean(xs*ys))/((mean(xs)**2)-mean(xs*xs)))\r\n\tb=mean(ys)-m*mean(xs)\r\n\treturn m,b\r\n\r\n# defining function to predict the outcome from the model \r\ndef predict_outcome(x_predict,m,b):\r\n\ty=m*x_predict+b\r\n\treturn y\r\n\r\n#defining a function for measuring r-squared\r\ndef sum_of_squared_error(ys_original,ys_line):\r\n\treturn sum((ys_original-ys_line)**2)\r\n\r\ndef r_squared_value(ys_original,ys_line):\r\n\tys_mean=[mean(ys_original) for y in ys_original]\r\n\tsquared_error_regression_line=sum_of_squared_error(ys_original,ys_line)\r\n\tsquared_error_mean_line=sum_of_squared_error(ys_original,ys_mean)\r\n\treturn (1-(squared_error_regression_line/squared_error_mean_line))\r\n\r\n#getting dataset\r\nxs,ys=create_dataset(40,10,5,True,'pos')\r\n\t\r\n#getting the slope and the intercept\r\nm,b=best_fit_slope_and_intercept(xs,ys)\r\n\r\n#making the regression line list using list comprehension\r\nregression_line=[(m*x+b) for x in xs]\r\n\r\n#making prediction using the data \r\nx_predict=8\r\ny_predict=predict_outcome(x_predict,m,b)\r\n\r\n# r-squared and checking whether the best fit line really fits our  data well or not \r\n#We can have a best fit line for a poorly fit dataset also, the point is to have a metric\r\n#can actually tell us whether th line represents the actual relationship and explains a significant\r\n#percentage of the variation.\r\nr_squared=r_squared_value(ys,regression_line)\r\n\r\n#visualise the results\r\nfrom matplotlib import style\r\nimport matplotlib.pyplot as plt\r\nstyle.use('fivethirtyeight')\r\nplt.scatter(xs,ys,color='red')\r\nplt.plot(xs,regression_line)# this connects the points and gives us a line \r\nplt.scatter(x_predict,y_predict,s=100,color='green')\r\nplt.show()", "meta": {"hexsha": "91a27c912b6a967cfdb005718ddfb399bce6a611", "size": 2533, "ext": "py", "lang": "Python", "max_stars_repo_path": "Simple Linear Regression/Simple Linear Regression from scratch/linear_regression_from_scratch.py", "max_stars_repo_name": "mehulfollytobevice/MachineLearning", "max_stars_repo_head_hexsha": "452c4379f84dfb5ff68faa187b106d59f87a21f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-02-26T08:15:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-20T01:15:04.000Z", "max_issues_repo_path": "Simple Linear Regression/Simple Linear Regression from scratch/linear_regression_from_scratch.py", "max_issues_repo_name": "ManasSPatil/MachineLearning", "max_issues_repo_head_hexsha": "7d442907df4e8560bf5067d8bac660a3cb303393", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Simple Linear Regression/Simple Linear Regression from scratch/linear_regression_from_scratch.py", "max_forks_repo_name": "ManasSPatil/MachineLearning", "max_forks_repo_head_hexsha": "7d442907df4e8560bf5067d8bac660a3cb303393", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-10T15:31:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T03:06:26.000Z", "avg_line_length": 32.4743589744, "max_line_length": 100, "alphanum_fraction": 0.7378602448, "include": true, "reason": "import numpy", "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615412, "lm_q2_score": 0.899121375242593, "lm_q1q2_score": 0.8564797625607466}}
{"text": "# Python3 steven\n#https://en.wikipedia.org/wiki/Mandelbrot_set\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\n# MandelBrot eqaution： z:=z**2 + c\n\nZ0 = 0 + 0j #start value\n\ndef mandelbrot(N=10):  #generate madenlbrot series\n    sets=[]\n    c = complex(.1, .2)\n    a = c\n    while N>0:\n        print(abs(a),' ',end='')\n        sets.append(abs(a))\n        a = a**2 + c\n\n        N -= 1\n    return sets\n\ndef yieldMandelbrot(N):  #binay oper only yield >2.0\n    xvalues = np.linspace(-2, 2, N)\n    yvalues = np.linspace(-2, 2, N)\n    for u, x in enumerate(xvalues):\n        for v, y in enumerate(yvalues):\n            z = Z0\n            c = complex(x, y)\n            for _ in range(100):\n                z = z * z + c\n                if abs(z) > 2.0:\n                    yield v,u,abs(z)\n                    break\n\ndef yieldMandelbrotAll(N):\n    xvalues = np.linspace(-2, 2, N)\n    yvalues = np.linspace(-2, 2, N)\n    for u, x in enumerate(xvalues):\n        for v, y in enumerate(yvalues):\n            z = Z0\n            c = complex(x, y)\n            for _ in range(100):\n                z = z * z + c\n                if abs(z) > 2.0:\n                    break\n                yield v,u,abs(z)\n\ndef genMandelbrotColor(N=1000):  #color image,3 channels\n    M = np.zeros([N, N,3], int) # + 255\n    for v,u,z in yieldMandelbrotAll(N): #map z(0~2) to 0~255 pixsel value\n        #M[v, u, :] = int(z*256/2)\n        #M[v, u, 0] = int(z*256/2) #r channel\n        M[v, u, 1] = int(z*256/2) #g channel\n        #M[v, u, 2] = int(z*256/2) #b channel\n    return M\n\ndef genMandelbrotGray(N=1000):  #gray image[0~255]\n    M = np.zeros([N, N], int)\n    for v,u,z in yieldMandelbrotAll(N): #map z(0~2) to 0~255 pixsel value\n        M[v, u] = int(z*256/2) #M[v, u] = 1\n    return M\n\ndef genMandelbrot(N=1000):  #white&black two value[0,1] image\n    M = np.zeros([N, N], int)\n    if 1:\n        for v,u,_ in yieldMandelbrot(N):\n            M[v, u] = 1\n        return M\n    else:#First version\n        xvalues = np.linspace(-2, 2, N)\n        yvalues = np.linspace(-2, 2, N)\n        for u, x in enumerate(xvalues):\n            for v, y in enumerate(yvalues):\n                z = 0 + 0j\n                c = complex(x, y)\n                for _ in range(100):\n                    z = z * z + c\n                    if abs(z) > 2.0:\n                        M[v,u] = 1\n                        break\n        return M\n\ndef main():\n    N = 1000\n\n    print('number of parameter:', len(sys.argv))\n    print('parameters:', str(sys.argv))\n    if len(sys.argv)>1:\n        N = int(sys.argv[1])\n\n    #mandelbrot()\n    plt.imshow(genMandelbrot(N),cmap='gray')\n    #plt.imshow(genMandelbrotGray(N),cmap='gray')\n    #plt.imshow(genMandelbrotColor(N))\n    plt.title('Mandelbrot,N ='+str(N))\n    plt.show()\n\nif __name__=='__main__':\n    main()\n", "meta": {"hexsha": "940ab4a68a358c05ec0abac37cdcf3a67fce820b", "size": 2810, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/fractal/plotMandelbrotSet.py", "max_stars_repo_name": "StevenHuang2020/ML", "max_stars_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fractal/plotMandelbrotSet.py", "max_issues_repo_name": "StevenHuang2020/ML", "max_issues_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fractal/plotMandelbrotSet.py", "max_forks_repo_name": "StevenHuang2020/ML", "max_forks_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1, "max_line_length": 73, "alphanum_fraction": 0.4996441281, "include": true, "reason": "import numpy", "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.8991213772699435, "lm_q1q2_score": 0.8564797608603}}
{"text": "\"\"\"\nThis module provides basic utilities related to Point type,\nsuch as comparison function between two points.\n\"\"\"\nimport numpy as np\nfrom myConvexHull.dtype import Point\n\nY = 1\n\"A constant index to access the y value of a point.\"\nX = 0\n\"A constant index to access the x value of a point.\"\n\n\ndef less_than(a, b) -> bool:\n    # type: (Point, Point) -> bool\n    \"\"\"\n    Compares two points and returns true if the first point's\n    x value is less than the second point's x value or both\n    points have the same x value but the first point's y value\n    is less than the second point's y value.\n\n    Args:\n\n    `a`: the first `Point`\n\n    `b`: the second `Point`\n\n    Return:\n\n    `True` if the true condition is met, `False` otherwise.\n    \"\"\"\n    return a[X] < b[X] or (a[X] == b[X] and a[Y] < b[Y])\n\n\ndef greater_than(a, b) -> bool:\n    # type: (Point, Point) -> bool\n    \"\"\"\n    Compares two points and returns true if the first point's\n    x value is more than the second point's x value or both\n    points have the same x value but the first point's y value\n    is more than the second point's y value.\n\n    Args:\n\n    `a`: the first `Point`\n\n    `b`: the second `Point`\n\n    Return:\n\n    `True` if the true condition is met, `False` otherwise.\n    \"\"\"\n    return a[X] > b[X] or (a[X] == b[X] and a[Y] > b[Y])\n\n\ndef distance(a, b) -> float:\n    # type: (Point, Point) -> float\n    \"\"\"\n    Calculates the distance between two points.\n\n    Args:\n\n    `a`: the first `Point`\n\n    `b`: the second `Point`\n\n    Return:\n\n    The distance between the specified points.\n    \"\"\"\n    return np.sqrt((a[X] - b[X]) ** 2 + (a[Y] - b[Y]) ** 2)\n", "meta": {"hexsha": "6cc234edce2b2f148629fc87996d74caf3c45bfa", "size": 1636, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/myConvexHull/point_utils.py", "max_stars_repo_name": "Radenz/my-convex-hull", "max_stars_repo_head_hexsha": "e887d84dd646ae046b10633218d0bf9b266fb8f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/myConvexHull/point_utils.py", "max_issues_repo_name": "Radenz/my-convex-hull", "max_issues_repo_head_hexsha": "e887d84dd646ae046b10633218d0bf9b266fb8f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/myConvexHull/point_utils.py", "max_forks_repo_name": "Radenz/my-convex-hull", "max_forks_repo_head_hexsha": "e887d84dd646ae046b10633218d0bf9b266fb8f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7222222222, "max_line_length": 62, "alphanum_fraction": 0.6143031785, "include": true, "reason": "import numpy", "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741322079104, "lm_q2_score": 0.8991213671331906, "lm_q1q2_score": 0.8564797560464891}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Sep  9 09:22:42 2021\r\n\r\n@author: Diana Sofía Carrillo\r\n\"\"\"\r\nfrom numpy import *\r\n\r\ndef gaussseidel(a, b, x):\r\n    n = len(x)\r\n    for i in range(n):\r\n        s = 0\r\n        for j in range (n):\r\n            if i != j:\r\n                s = s + a[i][j]*x[j]\r\n        x[i] = (b[i] - s)/a[i][i]\r\n    return x\r\n\r\ndef gaussseideliteraciones(a, b, x, e, m):\r\n    n = len(x)\r\n    t = x.copy()\r\n    for k in range (m):\r\n        x = gaussseidel(a, b, x)\r\n        d = linalg.norm(array(x)-array(t), inf)\r\n        if d < e:\r\n            return [x, k]\r\n        else:\r\n            t = x.copy()\r\n    return [[],m]\r\n\r\na = [[5, 2, 0],[0, -13, 5],[1, 1, 7]]\r\nb = [45.34, -44.66, 16.2]\r\nx = [1, 1, 1]\r\ne = 10E-6\r\nm = 20 #Num máximo de iteraciones\r\n[x, k]=gaussseideliteraciones(a, b, x, e, m)\r\nprint(\"Solución:\", x)\r\nprint(\"Iteraciones:\", k)\r\n\r\ndef error_relativo(v_obtenido, a, b):\r\n    v_real = linalg.solve(a, b)\r\n    rta = linalg.norm(v_obtenido - v_real) / linalg.norm(v_real)\r\n    return rta\r\n\r\nprint (\"Error relativo:\", error_relativo(x, a, b))", "meta": {"hexsha": "4382050463ffb2763abf48ff08d87d8ce8c36104", "size": 1076, "ext": "py", "lang": "Python", "max_stars_repo_path": "Talleres/Taller02/gauss seidel.py", "max_stars_repo_name": "monotera/Analisis-numerico_-1057-_2130", "max_stars_repo_head_hexsha": "f0acf6856028be8a20e33efd11f70d0817fdeeb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Talleres/Taller02/gauss seidel.py", "max_issues_repo_name": "monotera/Analisis-numerico_-1057-_2130", "max_issues_repo_head_hexsha": "f0acf6856028be8a20e33efd11f70d0817fdeeb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Talleres/Taller02/gauss seidel.py", "max_forks_repo_name": "monotera/Analisis-numerico_-1057-_2130", "max_forks_repo_head_hexsha": "f0acf6856028be8a20e33efd11f70d0817fdeeb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9111111111, "max_line_length": 65, "alphanum_fraction": 0.4888475836, "include": true, "reason": "from numpy", "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224331, "lm_q2_score": 0.8991213698363247, "lm_q1q2_score": 0.856479753779227}}
{"text": "#Romberg Integration\r\n\r\n\"\"\"\r\nName - Suryabrata Das\r\n\r\nSem: V    \r\n\r\nCollege_Roll_NO: 703\r\n\r\nPaper-code: CMSA DSE-IB\r\n\r\nRegistration No: A01-1112-117-003-2018\r\n\r\nExamination roll_no: 2021151264\r\n\r\nSubject: Numerical Methods (DSE-I)\r\n\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\ndef f1(x):\r\n    f1 = np.sin(x)\r\n    return f1;\r\n\r\n# trapezoidal rule\r\ndef trapezoid(f,a,b,N):\r\n    h = (b-a)/N\r\n    xi = np.linspace(a,b,N+1)\r\n    fi = f(xi)\r\n    s = 0.0\r\n    for i in range(1,N):\r\n        s = s + fi[i]\r\n    s = (h/2)*(fi[0] + fi[N]) + h*s\r\n    return s\r\n\r\n# romberg method starts from here\r\n\r\ndef romberg(f,a,b,eps,nmax):\r\n# f ... function to be integrated\r\n# [a,b] ... integration interval\r\n# eps ... desired accuracy\r\n# nmax ... maximal order of Romberg method\r\n    Q = np.zeros((nmax,nmax),float)\r\n    converged = 0\r\n    for i in range(0,nmax):\r\n        N = 2**i\r\n        Q[i,0] = trapezoid(f,a,b,N)\r\n        for k in range(0,i):\r\n            n = k + 2\r\n            Q[i,k+1] = 1.0/(4**(n-1)-1)*(4**(n-1)*Q[i,k] - Q[i-1,k])\r\n        if (i > 0):\r\n            if (abs(Q[i,k+1] - Q[i,k]) < eps):\r\n                converged = 1\r\n\r\n                break\r\n            print(\"Integral Value: \",Q[i,k+1])\r\n# main program\r\na = 0.0;b = 1.0 # integration interval [a,b]\r\nromberg(f1,a,b,1.0e-12,10)\r\n\r\n\r\n\r\n", "meta": {"hexsha": "629dc1de237ca9fadafb97e32ad8c8772c87f215", "size": 1306, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numerical method_practical_problems/Romberg Integration.py", "max_stars_repo_name": "surya810/Numerical-method-notes", "max_stars_repo_head_hexsha": "6d9dc7aba56e3f9fb8923e3c6d271d8eefcb6fb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numerical method_practical_problems/Romberg Integration.py", "max_issues_repo_name": "surya810/Numerical-method-notes", "max_issues_repo_head_hexsha": "6d9dc7aba56e3f9fb8923e3c6d271d8eefcb6fb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numerical method_practical_problems/Romberg Integration.py", "max_forks_repo_name": "surya810/Numerical-method-notes", "max_forks_repo_head_hexsha": "6d9dc7aba56e3f9fb8923e3c6d271d8eefcb6fb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7301587302, "max_line_length": 69, "alphanum_fraction": 0.5160796325, "include": true, "reason": "import numpy", "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.8991213691605412, "lm_q1q2_score": 0.8564797531354932}}
{"text": "import numpy\nimport numpy.random\n\nfrom numpy import bincount,any,sqrt\nfrom numpy.random import randint\n\ndef birthday(num_people=88, num_trials=1000000, target_number=3):\n    \"\"\"\n    Solve the generalized birthday problem using Monte-Carlo simulation.\n\n    Given num_people in a room what is the probability that target_number\n    or more of them share the same birthday.\n\n    Assume years have 365 days\n\n    Returns mean, standard deviation of the estimate\n    \"\"\"\n    n=0\n    for i in range(num_trials):\n        m=bincount(randint(1,366,num_people))\n        if any(m>=target_number):\n            n=n+1\n    # Mean of the results\n    p=n/num_trials\n    # std of the results\n    # This works since all data is 0,1 then data**2 = 0,1 as well\n    q=sqrt(n*(1-p)/(num_trials-1))\n    return(p,q)\n\n\n# Return P(less than 3 people with same birthday)\n# Note this is 1-p(from above) and only works for 3 birthdays\ndef foo2(num_people=88, num_trials=1000000):\n    n=0\n    for i in range(num_trials):\n        m=bincount(randint(1,366,num_people))\n        if any(m>2):\n            n=n+1\n    p=1-n/num_trials\n    return(p)\n\nif __name__ == \"__main__\":\n    # Set this true to run some example code\n    if False:\n        www=[]\n        # Set random seed for reproducible results\n        numpy.random.seed(42)\n        for i in range(10):\n            www.append(birthday(87,1000000,3))\n            print(\"Completed trial\",i,\"of 0..9\")\n        www=numpy.array(www)\n\n", "meta": {"hexsha": "8dfaf03a740a564e68ac42574b6a6d85030ffbf5", "size": 1446, "ext": "py", "lang": "Python", "max_stars_repo_path": "riddler/birthday/birthday_problem.py", "max_stars_repo_name": "rgc-retired/math_puzzles", "max_stars_repo_head_hexsha": "0f96fc0f4d53f9ece53fb7af02c037067f710fac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "riddler/birthday/birthday_problem.py", "max_issues_repo_name": "rgc-retired/math_puzzles", "max_issues_repo_head_hexsha": "0f96fc0f4d53f9ece53fb7af02c037067f710fac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "riddler/birthday/birthday_problem.py", "max_forks_repo_name": "rgc-retired/math_puzzles", "max_forks_repo_head_hexsha": "0f96fc0f4d53f9ece53fb7af02c037067f710fac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2830188679, "max_line_length": 73, "alphanum_fraction": 0.6459197787, "include": true, "reason": "import numpy,from numpy", "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760639, "lm_q2_score": 0.8991213664574069, "lm_q1q2_score": 0.8564797493500079}}
{"text": "# coding:utf-8\n\n# 输入训练样本的特征以及目标值，分别存储在变量X_train与y_train之中。\nX_train = [[6], [8], [10], [14], [18]]\ny_train = [[7], [9], [13], [17.5], [18]]\n\n# 从sklearn.linear_model中导入LinearRegression。\nfrom sklearn.linear_model import LinearRegression\n\n# 使用默认配置初始化线性回归模型。\nregressor = LinearRegression()\n# 直接以披萨的直径作为特征训练模型。\nregressor.fit(X_train, y_train)\n\n# 导入numpy并且重命名为np。\nimport numpy as np\n\n# 在x轴上从0至25均匀采样100个数据点。\nxx = np.linspace(0, 26, 100)\nxx = xx.reshape(xx.shape[0], 1)\n# 以上述100个数据点作为基准，预测回归直线。\nyy = regressor.predict(xx)\n\n# 对回归预测到的直线进行作图。\nimport matplotlib.pyplot as plt\n\nplt.scatter(X_train, y_train)\nplt1, = plt.plot(xx, yy, label=\"Degree=1\")\nplt.axis([0, 25, 0, 25])\nplt.xlabel('Diameter of Pizza')\nplt.ylabel('Price of Pizza')\nplt.legend(handles=[plt1])\nplt.show()\n\n# 输出线性回归模型在训练样本上的R-squared值。\nprint 'The R-squared value of Linear Regressor performing on the training data is', regressor.score(X_train, y_train)\n\n# 从sklearn.preproessing中导入多项式特征产生器\nfrom sklearn.preprocessing import PolynomialFeatures\n\n# 使用PolynominalFeatures(degree=2)映射出2次多项式特征，存储在变量X_train_poly2中。\npoly2 = PolynomialFeatures(degree=2)\nX_train_poly2 = poly2.fit_transform(X_train)\n\n# 以线性回归器为基础，初始化回归模型。尽管特征的维度有提升，但是模型基础仍然是线性模型。\nregressor_poly2 = LinearRegression()\n\n# 对2次多项式回归模型进行训练。\nregressor_poly2.fit(X_train_poly2, y_train)\n\n# 从新映射绘图用x轴采样数据。\nxx_poly2 = poly2.transform(xx)\n\n# 使用2次多项式回归模型对应x轴采样数据进行回归预测。\nyy_poly2 = regressor_poly2.predict(xx_poly2)\n\n# 分别对训练数据点、线性回归直线、2次多项式回归曲线进行作图。\nplt.scatter(X_train, y_train)\n\nplt1, = plt.plot(xx, yy, label='Degree=1')\nplt2, = plt.plot(xx, yy_poly2, label='Degree=2')\n\nplt.axis([0, 25, 0, 25])\nplt.xlabel('Diameter of Pizza')\nplt.ylabel('Price of Pizza')\nplt.legend(handles=[plt1, plt2])\nplt.show()\n\n# 输出2次多项式回归模型在训练样本上的R-squared值。\nprint 'The R-squared value of Polynominal Regressor (Degree=2) performing on the training data is', regressor_poly2.score(\n    X_train_poly2, y_train)\n\n# 从sklearn.preprocessing导入多项式特征生成器。\nfrom sklearn.preprocessing import PolynomialFeatures\n\n# 初始化4次多项式特征生成器。\npoly4 = PolynomialFeatures(degree=4)\n\nX_train_poly4 = poly4.fit_transform(X_train)\n\n# 使用默认配置初始化4次多项式回归器。\nregressor_poly4 = LinearRegression()\n# 对4次多项式回归模型进行训练。\nregressor_poly4.fit(X_train_poly4, y_train)\n\n# 从新映射绘图用x轴采样数据。\nxx_poly4 = poly4.transform(xx)\n# 使用4次多项式回归模型对应x轴采样数据进行回归预测。\nyy_poly4 = regressor_poly4.predict(xx_poly4)\n\n# 分别对训练数据点、线性回归直线、2次多项式以及4次多项式回归曲线进行作图。\nplt.scatter(X_train, y_train)\nplt1, = plt.plot(xx, yy, label='Degree=1')\nplt2, = plt.plot(xx, yy_poly2, label='Degree=2')\n\nplt4, = plt.plot(xx, yy_poly4, label='Degree=4')\nplt.axis([0, 25, 0, 25])\nplt.xlabel('Diameter of Pizza')\nplt.ylabel('Price of Pizza')\nplt.legend(handles=[plt1, plt2, plt4])\nplt.show()\n\nprint 'The R-squared value of Polynominal Regressor (Degree=4) performing on the training data is', regressor_poly4.score(\n    X_train_poly4, y_train)\n\n# 准备测试数据。\nX_test = [[6], [8], [11], [16]]\ny_test = [[8], [12], [15], [18]]\n\n# 使用测试数据对线性回归模型的性能进行评估。\nregressor.score(X_test, y_test)\n\n# 使用测试数据对2次多项式回归模型的性能进行评估。\nX_test_poly2 = poly2.transform(X_test)\nregressor_poly2.score(X_test_poly2, y_test)\n\n# 使用测试数据对4次多项式回归模型的性能进行评估。\nX_test_poly4 = poly4.transform(X_test)\nregressor_poly4.score(X_test_poly4, y_test)\n\n# 从sklearn.linear_model中导入Lasso。\nfrom sklearn.linear_model import Lasso\n\n# 从使用默认配置初始化Lasso。\nlasso_poly4 = Lasso()\n# 从使用Lasso对4次多项式特征进行拟合。\nlasso_poly4.fit(X_train_poly4, y_train)\n\n# 对Lasso模型在测试样本上的回归性能进行评估。\nprint lasso_poly4.score(X_test_poly4, y_test)\n\n# 输出Lasso模型的参数列表。\nprint lasso_poly4.coef_\n\n# 回顾普通4次多项式回归模型过拟合之后的性能。\nprint regressor_poly4.score(X_test_poly4, y_test)\n\n# 回顾普通4次多项式回归模型的参数列表。\nprint regressor_poly4.coef_\n\n# 输出普通4次多项式回归模型的参数列表。\nprint regressor_poly4.coef_\n\n# 输出上述这些参数的平方和，验证参数之间的巨大差异。\nprint np.sum(regressor_poly4.coef_ ** 2)\n\n# 从sklearn.linear_model导入Ridge。\nfrom sklearn.linear_model import Ridge\n\n# 使用默认配置初始化Riedge。\nridge_poly4 = Ridge()\n\n# 使用Ridge模型对4次多项式特征进行拟合。\nridge_poly4.fit(X_train_poly4, y_train)\n\n# 输出Ridge模型在测试样本上的回归性能。\nprint ridge_poly4.score(X_test_poly4, y_test)\n\n# 输出Ridge模型的参数列表，观察参数差异。\nprint ridge_poly4.coef_\n\n# 计算Ridge模型拟合后参数的平方和。\nprint np.sum(ridge_poly4.coef_ ** 2)\n", "meta": {"hexsha": "5e7ed461f90c54063e7707bff02510d245ff39d6", "size": 4086, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter_3/Chapter_3_1_2.py", "max_stars_repo_name": "flytian/python_machinelearning", "max_stars_repo_head_hexsha": "004707c3e66429f102272a7da97e532255cca293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter_3/Chapter_3_1_2.py", "max_issues_repo_name": "flytian/python_machinelearning", "max_issues_repo_head_hexsha": "004707c3e66429f102272a7da97e532255cca293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter_3/Chapter_3_1_2.py", "max_forks_repo_name": "flytian/python_machinelearning", "max_forks_repo_head_hexsha": "004707c3e66429f102272a7da97e532255cca293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9146341463, "max_line_length": 122, "alphanum_fraction": 0.7748409202, "include": true, "reason": "import numpy", "num_tokens": 1777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452443, "lm_q2_score": 0.9032942034496964, "lm_q1q2_score": 0.8564624979198054}}
{"text": "'''\r\nWe are trying to solve an Ordinary Differential Equation\r\nusing the Euler's method. For this example we are taking\r\nthe example of:\r\n\r\ndy/dt = -ky : IVP => y = y0 for t = 0\r\n\r\nWe will solve this without using the scipy\r\nodeint package\r\n'''\r\n\r\n# import the basic libraries\r\nimport math\r\nimport numpy as np                # used for numerical analysis\r\nimport matplotlib.pyplot as plt   # used for plotting Graphs\r\n\r\n# initialize the problem\r\nx0 = -np.pi/2\r\nt =0\r\nx = x0\r\n#k ,t , y =  1, 0.0, 5.0\r\n#y0 = y\r\ntt, yy = [], []\r\ntf = 2                         # final value for the time\r\n\r\ndt = 0.1                         # step size\r\n#exact_sol = []\r\n# describing the equation in function\r\n\r\ndef f(t,x):\r\n    return -math.sin(t+x)\r\n\r\n\r\n# now thw Euler method\r\nexact_sol = []\r\nwhile t<= tf:\r\n    tt.append(t)\r\n    yy.append(x)\r\n    x = x+dt*f(t,x)\r\n    exact = -math.asin((1-t**2)/(1+t**2)) - t\r\n    exact_sol.append(exact)\r\n    #exact = -math.asin((1-t**2)/(1+t**2))\r\n    #exact_sol.append(exact)\r\n\r\n    t += dt\r\n\r\n\r\n# finding the Exact Result\r\n\r\n\r\n#time \r\nexact = -math.asin((1-t**2)/(1+t**2)) - t\r\n\r\n    \r\n#print(exact)\r\n# now the Plotting part\r\nprint(len(tt))\r\n\r\nplt.plot(tt,yy,'o', label=\"dt=%.4f\"%(dt))\r\nplt.plot(tt, exact_sol,'k', label=\"Exact Solution\")\r\nplt.xlabel(\"time\")\r\nplt.ylabel('y')\r\nplt.legend(loc='best')\r\n\r\n\r\n# plotting the absolute error\r\n\r\nplt.legend(loc='best')\r\n\r\nplt.title(\"ODE by Euler Method\")\r\nplt.savefig('decay-euler1.png')", "meta": {"hexsha": "599a48e673934c79f5e806b5ae8fa72d0884f290", "size": 1451, "ext": "py", "lang": "Python", "max_stars_repo_path": "PSET1/P1/euler.py", "max_stars_repo_name": "MonitSharma/Computational-Methods-in-Physics", "max_stars_repo_head_hexsha": "e3b2db36c37dd5f64b9a37ba39e9bb267ba27d85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PSET1/P1/euler.py", "max_issues_repo_name": "MonitSharma/Computational-Methods-in-Physics", "max_issues_repo_head_hexsha": "e3b2db36c37dd5f64b9a37ba39e9bb267ba27d85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PSET1/P1/euler.py", "max_forks_repo_name": "MonitSharma/Computational-Methods-in-Physics", "max_forks_repo_head_hexsha": "e3b2db36c37dd5f64b9a37ba39e9bb267ba27d85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4366197183, "max_line_length": 64, "alphanum_fraction": 0.5816678153, "include": true, "reason": "import numpy", "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611654370415, "lm_q2_score": 0.8918110569397307, "lm_q1q2_score": 0.8564607059922796}}
{"text": "\"\"\"\nA Monte Carlo simulation to compute size distortion in hypothesis testing in an OLS context\n\"\"\"\n\nimport numpy as np\nimport matplotlib as plt\n\n# generate artificial dataset (could use real data if available)\nnp.random.seed(0)\nn = 4  # the higher is n, the less wrong we are about using +/-1.96 as critical values,\n# the closer is the empirical size to 5%\nsigma_u = 30\nbeta = 7\nX = np.random.normal(0, 10, n).reshape((n, 1))\nu = np.random.normal(0, sigma_u, n).reshape((n, 1))\ny = X.dot(beta) + u\n\n# monte carlo simulation\nbeta_zero = 5\nXX_inv = np.linalg.inv(np.transpose(X).dot(X))\nA = XX_inv.dot(np.transpose(X))\nb = X.dot(beta_zero)\nnumber_of_rejections = 0\nreps = 100000\nfor m in range(1, reps + 1):\n    u_m = np.random.normal(0, sigma_u, n).reshape((n, 1))\n    y_m = b + u_m\n    betahat_m = A.dot(y_m)\n    uhat = y_m - X.dot(betahat_m)\n    s2_m = np.transpose(uhat).dot(uhat) / (n - 1)\n    t_m = (betahat_m - beta_zero) / np.sqrt(s2_m * XX_inv)\n    number_of_rejections += abs(t_m) > 1.96\nempirical_size = number_of_rejections / reps\nprint('The empirical size is %.10f' % empirical_size)\nprint('The size distortion is |theoretical-empirical|=|5%%-%.4f%%|=%.4f' % (empirical_size * 100,\n                                                                            abs(5 - empirical_size * 100)))\n", "meta": {"hexsha": "d0db293b8da429094fd520e9af6407c8d81852dc", "size": 1302, "ext": "py", "lang": "Python", "max_stars_repo_path": "sizedistortion_montecarlo.py", "max_stars_repo_name": "kmmate/intermed_econ", "max_stars_repo_head_hexsha": "27e61598bb859b61f112aa742d9547e2e0933e26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sizedistortion_montecarlo.py", "max_issues_repo_name": "kmmate/intermed_econ", "max_issues_repo_head_hexsha": "27e61598bb859b61f112aa742d9547e2e0933e26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sizedistortion_montecarlo.py", "max_forks_repo_name": "kmmate/intermed_econ", "max_forks_repo_head_hexsha": "27e61598bb859b61f112aa742d9547e2e0933e26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1891891892, "max_line_length": 107, "alphanum_fraction": 0.6428571429, "include": true, "reason": "import numpy", "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611654370414, "lm_q2_score": 0.8918110461567922, "lm_q1q2_score": 0.8564606956367641}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef _marchenko_pastur(x,gamma,sigma=1.0):\n    y=1/gamma\n    largest_eigenval = np.power(sigma*(1 + np.sqrt(1/gamma)),2)\n    smallest_eigenval= np.power(sigma*(1 - np.sqrt(1/gamma)),2)\n    mp = (1/(2*np.pi*sigma*sigma*x*y))*np.sqrt((largest_eigenval - x)*(x - smallest_eigenval))*(0 if (x>largest_eigenval or x<smallest_eigenval) else 1)\n    return mp\n\ndef marchenko_pastur(n,p,upper_bound=3,spacing=2000,sigma=1.0):\n    x_mp_dist = np.linspace(0,upper_bound,spacing)\n    y_mp_dist = [_marchenko_pastur(x,n/p,sigma=sigma) for x in x_mp_dist]\n\n    return x_mp_dist,y_mp_dist\n\ndef eigenval_histogram(X,bins=100):\n    p,n = X.shape\n    S = (1./n) * np.dot(X,X.T)\n    u,_ = np.linalg.eig(S)\n\n    hist_heights, hist_bins = np.histogram(u,bins=bins,density=True)\n    x = hist_bins[:-1]\n    y = hist_heights\n    col_widths = hist_bins[-1]/len(x)\n\n\n    return x,y,col_widths\n\ndef transform_to_zero_mean_and_unit_std(X):\n    m,n = X.shape\n    means = np.mean(X,axis=1).reshape(m,1)\n    mean_adjusted_X = np.subtract(X,means)\n    stds = np.std(mean_adjusted_X,axis=1).reshape(m,1)\n    mean_and_std_adjusted_X = np.divide(mean_adjusted_X,stds)\n    return mean_and_std_adjusted_X\n\ndef marchenko_pastur_comparison(X,axis,histogram_bins=100,dist_upper_bound=3,dist_spacing=2000,sigma=1.0,transform=True):\n    p,n = X.shape\n    x_mp, y_mp = marchenko_pastur(n,p,upper_bound=dist_upper_bound,spacing=dist_spacing,sigma=sigma)\n\n    if transform:\n        X_ = transform_to_zero_mean_and_unit_std(X)\n        x,y,w = eigenval_histogram(X_,bins=histogram_bins)\n    else:\n        x,y,w = eigenval_histogram(X,bins=histogram_bins)\n\n    axis.bar(x,y,width=w,color='b')\n    axis.plot(x_mp,y_mp,color='r')\n    axis.set_xlabel(r'$\\lambda$')\n    axis.set_title('Marchenko-Pastur Distribution Comparison')\n", "meta": {"hexsha": "7f66d02e0a22c7f21ac9329b62d21aafdac7330f", "size": 1828, "ext": "py", "lang": "Python", "max_stars_repo_path": "marchenko_pastur.py", "max_stars_repo_name": "markditsworth/dstk", "max_stars_repo_head_hexsha": "c30f07f198fa768db63cd93f388a5d5bdb704cb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "marchenko_pastur.py", "max_issues_repo_name": "markditsworth/dstk", "max_issues_repo_head_hexsha": "c30f07f198fa768db63cd93f388a5d5bdb704cb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "marchenko_pastur.py", "max_forks_repo_name": "markditsworth/dstk", "max_forks_repo_head_hexsha": "c30f07f198fa768db63cd93f388a5d5bdb704cb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1538461538, "max_line_length": 152, "alphanum_fraction": 0.7067833698, "include": true, "reason": "import numpy", "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611608990299, "lm_q2_score": 0.8918110440002045, "lm_q1q2_score": 0.8564606895186122}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport methods as mt\n\n#Comparaison à un pas donné des valeurs y calculées et des valeurs de la solution à ses points communs avec y. Retourne le maximum des écarts.\n\ndef step_error(y,a,b,sol):\n\th=(b-a)/len(y)\n\tif type(y[0]) is np.ndarray:\n\t\tsol_values=np.zeros((len(y),y[0].shape[0]))\n\telse:\n\t\tsol_values=np.zeros(len(y))\n\tfor i in range(len(y)):\n\t\tsol_values[i]=sol(a+i*h)\n\tif type(y[0]) is np.ndarray:\n\t\tdiff_values=[np.linalg.norm(y[i]-sol_values[i]) for i in range(len(y))]\n\telse:\n\t\tdiff_values=[abs(y[i]-sol_values[i]) for i in range(len(y))]\n\tdiff=max(diff_values)\n\treturn diff \n\t\n#Tabulation des écarts maximums pour différents pas (en croissance logarithmique), sur un intervalle [a,b], construisant le tableau de valeurs avec la méthode meth. f et y0 sont nécessaires pour l'exécution de meth_n_step.\n\t\ndef errors_over_n(sol,f,meth,y0,a,b):\n\tspace=[10,20,30,40,50,60,70,80,90,100,200,300,400,500,600,700,800,900,1000]\n\tdiffs=np.zeros(len(space))\n\tfor i in range(len(diffs)):\n\t\th=(b-a)/space[i]\n\t\ty=mt.meth_n_step(y0,a,space[i],h,f,meth)\n\t\tdiffs[i]=step_error(y,a,b,sol)\n\treturn diffs\n\t\n#Création de graphes d'erreurs pour les quatre méthodes sur le cas défini par sol, f, y0, et sur l'intervalle [a,b].\n\ndef plot_errors(sol,f,y0,a,b):\n\tdiffs_euler=errors_over_n(sol,f,mt.step_euler,y0,a,b)\n\tdiffs_middle=errors_over_n(sol,f,mt.step_middle,y0,a,b)\n\tdiffs_heun=errors_over_n(sol,f,mt.step_heun,y0,a,b)\n\tdiffs_rk4=errors_over_n(sol,f,mt.step_rk4,y0,a,b)\n\t\n\tplt.clf()\n\tX=[10,20,30,40,50,60,70,80,90,100,200,300,400,500,600,700,800,900,1000]\n\tplt.plot(X,diffs_euler,label=\"Méthode d'Euler\")\n\tplt.plot(X,diffs_middle,label=\"Méthode du point milieu\")\n\tplt.plot(X,diffs_heun,label=\"Méthode de Heun\")\n\tplt.plot(X,diffs_rk4,label=\"Méthode de Runge-Kutta d'ordre 4\")\n\tplt.legend()\n\t\n\tplt.xlabel(\"Pas\")\n\tplt.ylabel(\"Erreur relative maximale\")\n\tplt.title(\"Graphe de comparaison des erreurs entre les quatre méthodes\")\n\tplt.xscale(\"log\")\n\tplt.grid(True,which=\"both\",linestyle='-.')\n\tplt.show()\n\t\n\nif __name__=='__main__':\n\tf=lambda t,y: y/(1+t**2)\n\tsol=lambda t: np.exp(np.arctan(t))\n\ty0=1\n\ta=0\n\tb=5\n\tplot_errors(sol,f,y0,a,b)\n", "meta": {"hexsha": "ba9ea1b1b1d31b779e81bc851a7a3289ae7a48fc", "size": 2173, "ext": "py", "lang": "Python", "max_stars_repo_path": "graphe_erreur.py", "max_stars_repo_name": "ImadProjects/Resolution-approchee-d-equations-differentielles", "max_stars_repo_head_hexsha": "13e62484907d0490bfc836fd55c10af5a7ed6e09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "graphe_erreur.py", "max_issues_repo_name": "ImadProjects/Resolution-approchee-d-equations-differentielles", "max_issues_repo_head_hexsha": "13e62484907d0490bfc836fd55c10af5a7ed6e09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphe_erreur.py", "max_forks_repo_name": "ImadProjects/Resolution-approchee-d-equations-differentielles", "max_forks_repo_head_hexsha": "13e62484907d0490bfc836fd55c10af5a7ed6e09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.953125, "max_line_length": 222, "alphanum_fraction": 0.7192820985, "include": true, "reason": "import numpy", "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.9184802507195636, "lm_q1q2_score": 0.8564399540785249}}
{"text": "\"\"\"Example implementation of the conjugate gradient descent algorithm using a hard coded objective function\n\n    F(X1, X2) = 5X1**2 + X2**2 + 4X1X2 - 14X1 - 6X2 + 20\n\n- At each step the value of X will be updated using\n    X_k+1 = X_k + alpha * Pk\n\n    Where pk is the conjugate direction and alpha is the step length\n\"\"\"\nimport math\nimport logging\nimport numpy as np\n\nlogging.basicConfig(level=logging.DEBUG)\nlog = logging.getLogger(__name__)\n\n\nclass ConjugateGradientDescent:\n    def __init__(self, max_iterations=10, hessian_matrix=None, linear_terms=None):\n        self.Hessian: np.ndarray = hessian_matrix or np.array([[10, 4], [4, 2]])\n        self.LinearCoefficients = linear_terms or np.array([-14, -6])\n        self.ConstantTerm = 20\n        self.Minimiser = np.array([0, 0])\n        self.CurrentIteration = 0\n        self.MaxIterations = max_iterations\n        self.Epsilon = math.pow(10, -3)  # Stop if magnitude of gradient is less than this value\n        self._LastConjugate = None  # Track gradient in current iteration - 1 step\n\n    @property\n    def __current_gradient_value(self):\n        gradient = self.del_f(self.Minimiser)\n        return np.sqrt(gradient.dot(gradient))\n\n    def f(self, xk: np.ndarray, decimal_places=3):\n        \"\"\"Returns the function value calcultaed from the equivalent quadratic form\"\"\"\n        squared_terms = 0.5 * xk.dot(self.Hessian).dot(xk)\n        linear_terms = self.LinearCoefficients.dot(xk)\n        total_cost = squared_terms + linear_terms + self.ConstantTerm\n        return round(total_cost, decimal_places)\n\n    def del_f(self, xk: np.ndarray) -> np.ndarray:\n        gradient_vector = np.matmul(self.Hessian, xk)\n        if isinstance(self.LinearCoefficients, np.ndarray):\n            gradient_vector = np.add(gradient_vector, self.LinearCoefficients)\n        return gradient_vector\n\n    def conjugate_direction(self, gk: np.ndarray):\n        if self.CurrentIteration == 0:\n            self._LastConjugate = -1 * gk\n            return self._LastConjugate\n        gk_previous: np.ndarray = self._LastConjugate\n        bk = gk.dot(gk) / gk_previous.dot(gk_previous)\n        pk = (-1 * gk) + bk*gk_previous\n        self._LastConjugate = pk  # We will use this on next iteration as P_k-1\n        return pk\n\n    def exact_step_length(self, gk: np.ndarray, pk: np.ndarray, decimal_places=3) -> np.float64:\n        \"\"\"Get the step lengh by minimising f(x + ad_k) wrt to a\n\n        alpha(or lambda) = -gk * pk / pk * A * pk\n        \"\"\"\n        numerator = gk.dot(pk)\n        denominator = pk.dot(self.Hessian).dot(pk)\n        step_length = numerator/denominator\n        return round(step_length, decimal_places) * -1\n\n    def _find_next_candidate(self):\n        \"\"\"Get next potential minimum using X_k+1 = X_k + alpha * pk\"\"\"\n        xk = self.Minimiser\n        gk = self.del_f(xk)\n        pk = self.conjugate_direction(gk)\n        step_length = self.exact_step_length(gk, pk)\n        x_k_plus1 = xk + (step_length * pk)\n        log.debug(f\"X**{self.CurrentIteration} = {xk} - {step_length} * {pk}\")\n        return x_k_plus1\n\n    def execute(self):\n        log.info('Conjugate gradient descent iteration started')\n        for k in range(self.MaxIterations):\n            log.debug(f\"-----------Iteration {k}--------------\")\n            self.CurrentIteration = k\n            self.Minimiser = self._find_next_candidate()\n            log.debug(f\"------Minimiser = {self.Minimiser}. Gradient = {self.__current_gradient_value}--------\\n\")\n            if self.__current_gradient_value <= self.Epsilon:\n                log.warning(f\"Iteration stopped at k={k}. Stopping condition reached!\")\n                break\n        log.info(f\"------Minimiser = {self.Minimiser}. Gradient = {self.__current_gradient_value}--------\")\n        log.info('Conjugate gradient descent completed successfully')\n        return self.Minimiser, self.f(self.Minimiser), round(self.__current_gradient_value, 3)\n", "meta": {"hexsha": "6c353ab698ee030d211bf95601358ebcdc3a764b", "size": 3926, "ext": "py", "lang": "Python", "max_stars_repo_path": "conjugatedescent.py", "max_stars_repo_name": "endeesa/optimization-algorithms", "max_stars_repo_head_hexsha": "bb2f18101e27bc28167c456ef842aef6a22b3fbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "conjugatedescent.py", "max_issues_repo_name": "endeesa/optimization-algorithms", "max_issues_repo_head_hexsha": "bb2f18101e27bc28167c456ef842aef6a22b3fbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conjugatedescent.py", "max_forks_repo_name": "endeesa/optimization-algorithms", "max_forks_repo_head_hexsha": "bb2f18101e27bc28167c456ef842aef6a22b3fbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6222222222, "max_line_length": 114, "alphanum_fraction": 0.648242486, "include": true, "reason": "import numpy", "num_tokens": 994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.9111797160416689, "lm_q1q2_score": 0.8564299776645937}}
{"text": "import numpy as np\r\nimport pandas as pd\r\nfrom utils import regresiveSustitution, progressiveSustitution, swapRowsSpecial,regresiveSustitutions\r\nfrom utils import rowOps\r\nfrom utils import getMultipliers\r\nfrom utils import swapRows\r\nfrom utils import isSquared\r\n\r\n\r\ndef crout(A,b):\r\n\r\n    pivots = []\r\n\r\n    A = np.array(A).astype(float)\r\n    b = np.array(b).astype(float)\r\n\r\n    times = A[:, 0].size\r\n\r\n    U = np.zeros((times, times))\r\n    L = np.identity(times)\r\n    cont = 0\r\n\r\n    for d in range(0, times):\r\n        U[d, d] = 1\r\n\r\n    for d in range(0, times): #Etapas\r\n        #Calculo L\r\n        for j in range(d, times):\r\n            sum0 = sum([L[j, s] * U[s, d] for s in range(0, j)])\r\n            L[j, d] = A[j, d] - sum0\r\n        #Calculo U\r\n        for j in range(d+1, times):\r\n            sum1 = sum([L[d, s] * U[s, j] for s in range(0, d)])\r\n            U[d, j] = (A[d, j] - sum1) / L[d, d]\r\n        cont = cont+1\r\n        pivots.append({'status':'Step '+str(cont), 'matrixL': L.copy(), 'matrixU': U.copy()})\r\n\r\n    LB = np.concatenate([L, b], axis=1)\r\n    size = LB[:, 0].size\r\n\r\n    pro = progressiveSustitution(LB, size)\r\n    pro = np.array(pro).astype(float)\r\n\r\n    UB = np.concatenate([U, pro.reshape((U.shape[0], 1))], axis=1)\r\n    size2 = UB[:, 0].size\r\n    reg = regresiveSustitutions(UB, size2 - 1)\r\n    pivots.append({'status':'Results', 'reg': reg})\r\n\r\n    return pivots\r\n\r\n\r\ndef showSteps(steps):\r\n    for step in steps:\r\n        try:\r\n            print(pd.DataFrame(step).to_string(index=False, header=False)+\"\\n\")\r\n        except:\r\n            print(step)\r\n\r\ndef showTable(table):\r\n    result = \"\"\r\n    if('status' in table[-1]):\r\n        result = table[-1]\r\n        table.pop()\r\n    print(pd.DataFrame(table).to_string(index=False))\r\n    print(result)\r\n\r\nif __name__ == \"__main__\":\r\n    A = [[4, -1, 0, 3],[1, 15.5, 3, 8],[0, -1.3, -4, 1.1],[14, 5, -2, 30]]\r\n    B = [[1],[1],[1],[1]]\r\n\r\n    results = crout(A,B)\r\n\r\n    for r in range(0,len(results)-1):\r\n        print(results[r]['status'])\r\n        print(\"matrix L\")\r\n        showTable(results[r]['matrixL'])\r\n        print(\"matrix U\")\r\n        showTable(results[r]['matrixU'])\r\n\r\n    print(\"Results\")\r\n    print(results[len(results)-1]['reg'])\r\n\r\n\r\n\r\n\r\n\r\n    \r\n\r\n", "meta": {"hexsha": "8bb671a702855d1122cb7238c9d6364b63eca171", "size": 2244, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/crout.py", "max_stars_repo_name": "eechava6/NumericalAnalysisMethods", "max_stars_repo_head_hexsha": "3eeb06bdb20d97f13a09fd0ed71bce045173ffef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/crout.py", "max_issues_repo_name": "eechava6/NumericalAnalysisMethods", "max_issues_repo_head_hexsha": "3eeb06bdb20d97f13a09fd0ed71bce045173ffef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/crout.py", "max_forks_repo_name": "eechava6/NumericalAnalysisMethods", "max_forks_repo_head_hexsha": "3eeb06bdb20d97f13a09fd0ed71bce045173ffef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2134831461, "max_line_length": 102, "alphanum_fraction": 0.5325311943, "include": true, "reason": "import numpy", "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067253, "lm_q2_score": 0.9046505286741726, "lm_q1q2_score": 0.8563391795007013}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb  7 18:59:29 2022\n\n@author: Analabha Roy\n\"\"\"\n\nimport numpy as np\nfrom scipy.linalg import lu_factor, lu_solve\nA = np.array([[25., 5., 1.],\n              [64., 8., 1.],\n              [144., 12., 1.]])\n\nb = np.array([106.8,\n              177.2,\n              279.2])\n\nA_fact, piv = lu_factor(A.copy())\n\nprint(\"Decomposed L Matrix:\\n\", np.tril(A_fact, k=0))\nprint(\"\\n\\nDecomposed U Matrix:\\n\", np.triu(A_fact, k=1))\n\nx = lu_solve((A_fact.copy(), piv), b)\n\nprint(\"\\nSolution is x =\", x)\nprint(\"Solution is close?\", np.allclose(A @ x, b))\n\nid = np.eye(A.shape[0])\nA_inv = np.zeros_like(A)\n\nfor i, row in enumerate(id):\n    A_inv[:, i] = lu_solve((A_fact.copy(), piv), row)\n\nprint(\"\\n\\nInverse of matrix is:\\n\", A_inv)\nprint(\"Solution is close?\", np.allclose(A @ A_inv, id))\n", "meta": {"hexsha": "9f48429d1f0c5b197afcdf95b80a2684a1c0bd02", "size": 838, "ext": "py", "lang": "Python", "max_stars_repo_path": "03-Computational_Linear_Algebra/lu_decomp_ex.py", "max_stars_repo_name": "hariseldon99/msph402b", "max_stars_repo_head_hexsha": "20d2df0ca7c7216c504669ea1495a84de1b217d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "03-Computational_Linear_Algebra/lu_decomp_ex.py", "max_issues_repo_name": "hariseldon99/msph402b", "max_issues_repo_head_hexsha": "20d2df0ca7c7216c504669ea1495a84de1b217d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "03-Computational_Linear_Algebra/lu_decomp_ex.py", "max_forks_repo_name": "hariseldon99/msph402b", "max_forks_repo_head_hexsha": "20d2df0ca7c7216c504669ea1495a84de1b217d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6486486486, "max_line_length": 57, "alphanum_fraction": 0.5811455847, "include": true, "reason": "import numpy,from scipy", "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140235181256, "lm_q2_score": 0.885631470799559, "lm_q1q2_score": 0.8563294887850769}}
{"text": "import numpy as np\r\n\r\n\r\ndef gram_schmidt_factorization(matrix):\r\n    matrix = np.array(matrix)\r\n    m, n = matrix.shape\r\n    q = np.zeros((m, n))\r\n    r = np.zeros((n, n))\r\n    matrix = np.transpose(matrix)\r\n    r[0][0] = np.linalg.norm(matrix[0], 2)\r\n    q[:, 0] = matrix[0]/r[0][0]\r\n    for i in range(1, n):\r\n        q[:, i] = matrix[i]\r\n        for j in range(0, i):\r\n            r[j][i] = np.matmul(q[:, j], q[:, i])\r\n            q[:, i] = q[:, i] - (r[j][i] * q[:, j])\r\n        r[i][i] = np.linalg.norm(q[:, i], 2)\r\n        q[:, i] = q[:, i] / r[i][i]\r\n    return q, r\r\n\r\n\r\ndef system_solver(matrix, vector):\r\n    qr_decomposition = gram_schmidt_factorization(matrix)\r\n    q_matrix = qr_decomposition[0]\r\n    r_matrix = qr_decomposition[1]\r\n    redacted_vector = np.matmul(q_matrix.transpose(), np.array(vector).transpose())\r\n    r_matrix_inverse = np.linalg.inv(r_matrix)\r\n    x_vector = np.matmul(r_matrix_inverse, redacted_vector)\r\n    return x_vector\r\n\r\n\r\nif __name__ == '__main__':\r\n    coefficients_matrix = eval(input(\"enter A matrix like: [[1, 1, 1], [2, 2, 2], [3, 3, 3]\\n\"))\r\n    right_hand_side_vector = eval(input(\"enter b vector like: [1, 1, 1]\\n\"))\r\n    print(system_solver(coefficients_matrix, right_hand_side_vector))\r\n\r\n", "meta": {"hexsha": "e4edde1d8ef6ff26da72e9743811e8ec13f0a6d8", "size": 1243, "ext": "py", "lang": "Python", "max_stars_repo_path": "Gram-Schmidt QR.py", "max_stars_repo_name": "arash79/Numerical-methods", "max_stars_repo_head_hexsha": "f1dd455916c92d2c2a2e5909fa26cef67e39f346", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Gram-Schmidt QR.py", "max_issues_repo_name": "arash79/Numerical-methods", "max_issues_repo_head_hexsha": "f1dd455916c92d2c2a2e5909fa26cef67e39f346", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gram-Schmidt QR.py", "max_forks_repo_name": "arash79/Numerical-methods", "max_forks_repo_head_hexsha": "f1dd455916c92d2c2a2e5909fa26cef67e39f346", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5945945946, "max_line_length": 97, "alphanum_fraction": 0.5776347546, "include": true, "reason": "import numpy", "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426443092215, "lm_q2_score": 0.8791467785920306, "lm_q1q2_score": 0.8563264529557152}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn import datasets as skdata\n\n#We will use the iris dataset\niris_dataset = skdata.load_iris()\nX = iris_dataset.data # (150, 4)\ny = iris_dataset.target\n\n#Compute the mean\nmu = np.mean(X, axis=0)\n\n#Center the data\nB = X - mu\n\n#Compute the covariance matrix\nC = np.matmul(B.T, B)/(B.shape[0]) #(4, 150) x (150, 4) => (4, 4)\n\n#Eigen decomposition\nS, V = np.linalg.eig(C)\n\n#Select the top 3 dimentions\norder = np.argsort(S)[::-1]\nW = V[:, order][:, 0:3] #Transformation for projecting X to subspace\n\n#Project our data\nZ = np.matmul(B, W) #(150, 3)\n\n#Let's visualize our new feature space\ndata_split = (Z[np.where(y==0)[0], :], Z[np.where(y==1)[0], :], Z[np.where(y==2)[0], :])\ncolors = ('blue', 'red', 'green')\nlabels = ('Setosa', 'Versicolor', 'Virginica')\nmarkers = ('o', '^', '+')\n\nfig = plt.figure()\nfig.suptitle('Projected Iris Data')\nax = fig.add_subplot(1, 1, 1, projection='3d')\nax.set_xlabel('PC1')\nax.set_ylabel('PC2')\nax.set_zlabel('PC3')\n\nfor z, c, l, m in zip(data_split, colors, labels, markers):\n    ax.scatter(z[:, 0], z[:, 1], z[:, 2], c=c, label=l, marker=m)\n    ax.legend(loc='upper right')\n\nplt.show()\n\n#Recover our data\nX_hat = np.matmul(Z, W.T)+mu\nmse = np.mean((X-X_hat)**2) #0.005919048088406607\n\n#Seems like we recovered our data pretty well\n#Let's instead choose only two dimentions\nW_2 = V[:, 0:2] #Transformation for projecting X to subspace\n\n#Project our data\nZ_2 = np.matmul(B, W_2)\n\nX_hat_2 = np.matmul(Z_2, W_2.T)+mu\nmse = np.mean((X-X_hat_2)**2) # 0.02534107393239825\n\n#As we reduce more dimentions, we lose more information\n", "meta": {"hexsha": "1cc4577909b736a4e0a0ca4cfbf6d187a5d31b4c", "size": 1654, "ext": "py", "lang": "Python", "max_stars_repo_path": "PCA.py", "max_stars_repo_name": "Icetalon21/Data-Science", "max_stars_repo_head_hexsha": "05eea4a027b194b3cfb5ddae5f0640ddcd44c5c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PCA.py", "max_issues_repo_name": "Icetalon21/Data-Science", "max_issues_repo_head_hexsha": "05eea4a027b194b3cfb5ddae5f0640ddcd44c5c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PCA.py", "max_forks_repo_name": "Icetalon21/Data-Science", "max_forks_repo_head_hexsha": "05eea4a027b194b3cfb5ddae5f0640ddcd44c5c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-11T08:50:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-11T08:50:49.000Z", "avg_line_length": 25.84375, "max_line_length": 88, "alphanum_fraction": 0.6711003628, "include": true, "reason": "import numpy", "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.979667647844603, "lm_q2_score": 0.87407724336544, "lm_q1q2_score": 0.8563051970423152}}
{"text": "import data.warmUpExercise as a\nimport data.computeCost as cc\nimport data.gradientDescent as gd\nimport data.plotData as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n\n#============Part 1=================\nprint('Running warmUpExercise')\nprint('5x5 Identity Matrix')\nprint(a.warm())\n\n#==========Part 2===================\nprint('Plotting Data')\ndata = np.loadtxt('ex1data1.txt',delimiter =\",\")\nX = data[:,0]\ny = data[:,1]\nm = len(y)\n\npd.plotData(X,y)\n\n#================part 3====================\nprint('Gradient Descent')\nX_padded = np.column_stack((np.ones((m,1)),X))\ntheta = np.zeros((2,1))\n\niterations = 1500\nalpha = 0.01\n\nprint('testing functions')\nprint(cc.computeCost(X_padded,y,theta))\ntheta = gd.gradientDescent(X_padded,y,theta,alpha,iterations)\nprint(\"{:f}, {:f}\".format(theta[0,0], theta[1,0]))\n\n#plot linear fit\nplt.plot(X,X_padded.dot(theta),'-',label = 'Linear regression')\nplt.legend(loc = 'lower right')\nplt.draw()\n\n\n#predicts values for population size of 35000 and 70000\npredict1 = np.array([1,3.5]).dot(theta)\nprint(\"For population = 35000 we predict a profit of {:f}\".format(float(predict1*10000)))\npredict2 = np.array([1, 7]).dot(theta)\nprint('For population = 70,000, we predict a profit of {:f}'.format( float(predict2*10000) ))\n\n#================ part 4============================\nprint(\"j(theta_0,theta1)\")\ntheta0_vals = np.linspace(-10,10,100)\ntheta1_vals = np.linspace(-1,4,100)\n\nJ_vals = np.zeros((len(theta0_vals),len(theta1_vals)))\nfor i in range(len(theta0_vals)):\n    for j in range(len(theta1_vals)):\n        t = [[theta0_vals[i]],[theta1_vals[j]]]\n        J_vals[i,j] = cc.computeCost(X_padded,y,t)\n\nJ_vals = np.transpose(J_vals)\nfig = plt.figure()\nax = fig.gca(projection='3d')\ntheta0_vals, theta1_vals = np.meshgrid(theta0_vals, theta1_vals) # necessary for 3D graph\nsurf = ax.plot_surface(theta0_vals, theta1_vals, J_vals, cmap=cm.coolwarm, rstride=2, cstride=2)\nfig.colorbar(surf)\nplt.xlabel('theta_0')\nplt.ylabel('theta_1')\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n\ncset = plt.contour(theta0_vals, theta1_vals, J_vals, np.logspace(-2, 3, 20), cmap=cm.coolwarm)\nfig.colorbar(cset)\nplt.xlabel('theta_0')\nplt.ylabel('theta_1')\nplt.plot(theta[0,0], theta[1,0], 'rx', markersize=10, linewidth=2)\nplt.show()", "meta": {"hexsha": "49537dce688e92b2872292c90cc379829d535a0b", "size": 2322, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ex_1/ex1.py", "max_stars_repo_name": "Cognive-in/coursera_ML_Python", "max_stars_repo_head_hexsha": "f174d350321aab0ef9cd14a41e425f3e753fdaa5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ex_1/ex1.py", "max_issues_repo_name": "Cognive-in/coursera_ML_Python", "max_issues_repo_head_hexsha": "f174d350321aab0ef9cd14a41e425f3e753fdaa5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ex_1/ex1.py", "max_forks_repo_name": "Cognive-in/coursera_ML_Python", "max_forks_repo_head_hexsha": "f174d350321aab0ef9cd14a41e425f3e753fdaa5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1558441558, "max_line_length": 96, "alphanum_fraction": 0.6752799311, "include": true, "reason": "import numpy", "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574669, "lm_q2_score": 0.8933094167058151, "lm_q1q2_score": 0.856270780170828}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 28 7:33:03 2019\n\n@author: Parikshith.H\n\"\"\"\n\nimport numpy as np \n  \na = np.array([[1, 2], \n            [3, 4]]) \nb = np.array([[4, 3], \n            [2, 1]]) \n  \n# add arrays \nprint (\"Array sum:\\n\", a + b) \n# =============================================================================\n# #output:\n# Array sum:\n#  [[5 5]\n#  [5 5]]\n# =============================================================================\n\n  \n# multiply arrays (elementwise multiplication) \nprint (\"Array multiplication:\\n\", a*b) \n# =============================================================================\n# #output:\n# Array multiplication:\n#  [[4 6]\n#  [6 4]]\n# =============================================================================\n\n  \n# matrix multiplication \nprint (\"Matrix multiplication:\\n\", a.dot(b)) \n# =============================================================================\n# #output:\n# Matrix multiplication:\n#  [[ 8  5]\n#  [20 13]]\n# =============================================================================\n", "meta": {"hexsha": "89fb7f5926a2b949523e75bcf9b2946dc9841f06", "size": 1058, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_parikshith21/Day49.py", "max_stars_repo_name": "01coders/50-Days-Of-Code", "max_stars_repo_head_hexsha": "98928cf0e186ee295bc90a4da0aa9554e2918659", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python_parikshith21/Day49.py", "max_issues_repo_name": "01coders/50-Days-Of-Code", "max_issues_repo_head_hexsha": "98928cf0e186ee295bc90a4da0aa9554e2918659", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python_parikshith21/Day49.py", "max_forks_repo_name": "01coders/50-Days-Of-Code", "max_forks_repo_head_hexsha": "98928cf0e186ee295bc90a4da0aa9554e2918659", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6046511628, "max_line_length": 79, "alphanum_fraction": 0.2958412098, "include": true, "reason": "import numpy", "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377261041521, "lm_q2_score": 0.8933094096048377, "lm_q1q2_score": 0.8562707701900638}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[112]:\n\n\nimport numpy as np\nimport math\n\n\n# In[ ]:\n\n\n\n\n\n# # Criando Array\n\n# In[6]:\n\n\n#arrays podem ser mostrados como listas ou listas de listas e podem ser criados como listas. Quando criando um array nós\n#passamos uma lista como um argumento numpy array\n\na = np.array(['1','2','3'])\nprint(a)\n#pode imprimir o número de dimensões de uma lista usando o atributo \"ndim\"\nprint(a.ndim)\n\n\n# In[4]:\n\n\n#se inserirmos uma lista de listas, criamos então um array multi dimensional, por exemplo uma matrix\nb = np.array([[1,2,3], [4,5,6]])\nb\nb.ndim\n\n\n# In[5]:\n\n\n#podemos imprimir o comprimento do array usando o atributo \"shape\", que retorna uma tupla, no caso = 2 linhas 3 colunas\nb.shape\n\n\n# In[11]:\n\n\n#verificar o tipo de dados de um array \"dtype\"\nprint(a.dtype)\nprint(b.dtype)\n\n\n# In[17]:\n\n\n#floats também são aceitos em arrays numpy\nc = np.array([1.1, 5, 2.8])\nc.dtype.name\nc\n#ele converte automaticamente o 5 que era inteiro para um numero float sem perder precisão\n#ele tenta manter o tipo do dado homogêneo\n\n\n# In[18]:\n\n\n#as vezes sabemos o formato do array que queremos criar mas não sabemos o que colocar nele, o numpy oferece\n#funções para criar arrays com dados iniciais, tipo 0 e 1\n\n#criando dois arrays com o mesmo formato potém com dados diferentes\nd = np.zeros((2,3))\nprint(d)\n\ne = np.ones((2,3))\nprint(e)\n\n\n# In[21]:\n\n\n#criando um array com números aleatórios\nnp.random.randint(2,3)\n\n\n# In[24]:\n\n\n#ainda da pra criar uma sequência de números com a função arange().\n#o primeiro argumento é o número de partida, o segundo argumento é o número de parada e\n#o terceiro argumento é a diferença entre os números, o \"pulo\"\n\n#criando um array de números pares de 10 (incluso) até 50 (excluso)\nf = np.arange(10, 50, 2) #começa no dez (incluso) e termina no 50 (sem contar o 50), pulando de 2 em 2\nprint(f)\n\n\n# In[ ]:\n\n\n#se quisermos criar uma sequencia de floats, podemos usar o linspace(). nessa função,\n#o terceiro argumento não é a diferença entre um número e o outro (o pulo) e sim a quantidade de itens que queremos criar\nnp.linspace(0, 2, 15) #me gere 15 números entre 0 (incluso) e 2 (excluso)\n\n\n# # Operações com arrays\n\n# In[32]:\n\n\n#da pra fazer manipulações matematicas (adição, subtração, divisão...) assim como usar arrays booleanos (true, false)\n#da pra manipular matrizes como produto, transpor, inverter e tal\na = np.array([10, 20, 30, 40])\nb = np.array([1, 2, 3, 4])\n             \n#a menos b\nc = a - b\nprint(c)\n\n#a vezes b\nd = a * b \nprint(d)\n\n\n# In[11]:\n\n\n#com operações aritiméticas podemos converter o valor dos dados, tipo temperatura e distância\n\nfar = np.array([32, -16, 106, -30])\n\n#formua de conversão\n#((°F - 32) / 1.8)\n\ncel = ((far - 32) / 1.8)\ncel\n\n\n# In[13]:\n\n\n#usar booleano para checar se uma temperatura de um array é maior que 20°C\n#vai retornar True se for verdadeiro ou False se for falso\ncel > 20\n\n\n# In[14]:\n\n\n#usar módulo para checar se um número do array é par\ncel % 2 == 0\n\n\n# In[39]:\n\n\n#numpy suporta manipulação de matrizes\n#produto de matriz\n\nA = np.array([[1,2], [3,4]])\nB = np.array([[1,2], [3,4]])\n\n#A = np.array([[a, b], [c, d]])\n#B = np.array([[e, f], [g, h]])\n# o processo é: a*e + b*g, a*f + b*h\n#               c*e + d*g, c*f + d*h\n\nsoma1 = 1*1 + 2*3, 1*2 + 2*4\n\nsoma2 = 3*1 + 4*3, 3*2 + 4*4\n\nprint(A*B)\nprint('---')\nprint(A@B)\nprint('---')\nprint(soma1)\nprint('---')\nprint(soma2)\n\n\n# In[40]:\n\n\n#para ver o formato da matriz podemos fazer o .shape\nA.shape\n#(2, 2) --> duas linhas duas colunas\n\n\n# In[45]:\n\n\n#quando manipulando arrays de data types diferentes, ele vai colocar no final o resultado data type mais geral que existe,\n#isso é chamado upcasting\n\n#array integers\nar1 = np.array([[2, 4], [6, 8]])\n#array float\nar2 = np.array([[2.5, 4.5], [6.5, 8.5]])\n#somando os arrays\nar3 = ar1 + ar2\nprint(ar3)\nprint(ar3.dtype)\n\n\n# In[46]:\n\n\n#numpy tem funções como max, min, sum, mean\nprint(ar3.mean())\nprint(ar3.max())\nprint(ar3.min())\nprint(ar3.sum())\n\n\n# In[48]:\n\n\n#com arrays multidimensionais, podemos fazer a mesma coisa com cada linha e/ou coluna\n#criando um array de 15 elementos de 1 a 15 com dimensão 3x5\nquin = np.arange(1, 16, 1).reshape(3, 5)\nquin\n\n\n# # indexação, slicing e iteração\n\n# In[49]:\n\n\n#um array unidimensional funciona quase que como uma lista, para pegar um elemento usamos o [x]\nar = np.array([13,2,56,6,8,1,2])\nar[5]\n\n\n# In[53]:\n\n\n#já para um array multidimensional, usamos um index integer\nar2 = np.array([[2,3], [5,4], [1, 9], [2,5]])\nar2\n\n\n# In[58]:\n\n\n#para pegar o elemento, precisamos inserir o número da linha e o segundo o da coluna [x, y]\n#lemrbando que em python começa no 0\nar2[3,0]\n\n\n# In[75]:\n\n\n#para pegar mais de um elemento podemos colocá-los direto numa lista usando a função doa rray\nar3 = np.array([ar2[0,0], ar2[1,1], ar2[2,0], ar2[3,1]])\nprint(ar3)\nprint('---')\n#ou\nprint(ar2[[0,1,2,3], [0,1,0,1]]) #primeiro diz as linhas e depois quais colunas\n\n\n# ## Boolean indexing\n\n# In[78]:\n\n\n#para achar elementos maiores que 3\nprint(ar2 > 3)\n#retorna um array com verdadeiro ou falso\n\n\n# ## Slicing\n\n# In[81]:\n\n\n#slicing é uma forma de criar sub-arrays com base num array original\n#para um array unidimensional, ele funciona quase como uma lista\n#para fazer o slice, usa-se o sinal de pois pontos : . por exemplo, se colocarmos o :5 no index, nós teriamos\n# todos os elementos de 0 a 5 excluindo o 5\nar = np.array([1,2,3,4,5,6,7,8,9,10])\nprint(ar[:5])\n\n\n# In[82]:\n\n\n#daí se colocar dois números com os dois pontos, teríamos todos os elementos de x a y\n#[3:8] todos os elementos de 3(incluso) a 8 (excluso)\nprint(ar[3:8])\n\n\n# In[92]:\n\n\n#agora para arrays multimensionais\nar2 = np.array([[1,2,3,4], [5,6,7,8], [9, 10, 11,12]])\nprint(ar2)\n\n\n# In[87]:\n\n\n#se adicionarmos [:2] teriamos todos os elemntos da coluna zero e da coluna um\nprint(ar2[:2])\n#ou seja, ele tráz as linhas com todos os elementos e não os elementos individuais\n\n\n# In[88]:\n\n\n#se adicionar dois argumentos ar2[:2, 1:3] retorna as duas primeiras linhas e os elementos de 1 a 3 (excluso)\nprint(ar2[:2, 1:3])\n\n\n# In[94]:\n\n\n#assim, em arrays multidimensionais, o primeiro argumento é para selecionar colunas e o segundo argumento é para colunas\nar2\n\n\n# In[99]:\n\n\n#mudar um elemento num subarray muda ele também no array original, isso é chamado passado por referência\n#então, modoificando um sub array, vai modificar o original\n\nsub_ar2 = ar2[:2, 1:3]\n\nprint('sub_ar2 index [0,0] antes de mudar: ', sub_ar2[0,0])\nsub_ar2[0,0] = 50\nprint('sub_ar2 [0,0] depios de mudar: ', sub_ar2[0,0])\nprint('array original ar2 [0,1] depois de mudar: ', ar2[0,1])\nprint('---')\nprint(ar2)\n\n\n# In[105]:\n\n\nsub2_ar2 = sub_ar2\nsub2_ar2[0,1] = 5\nprint(sub2_ar2)\nprint('---')\nprint(ar2)\n\n\n# # trabalhando com datasets e numpy\n\n# # dataset de vinhos\n\n# In[115]:\n\n\n#carregabdo o arquivo csv, mas por algum acaso ele está com ponto e virgula ao invés de só a virgula separando\nwines = np.genfromtxt('winequality-red.csv', delimiter = ';', skip_header=1)\n\n\n# In[116]:\n\n\nwines\n\n\n# In[118]:\n\n\n#para selecionar a coluna da acidez, a primeira coluna, nós podemos buscar inserindo o index da coluna no array\n#lembrando que para arrays multidimensionais, o primeiro argumento é a linha e o segundo a coluna\n# se dermos só uma argumento, ele retorna uma lista simples\n\n#todas as linhas da primeira colun\nprint('um número para cortar: ',wines[:, 0]) #retorna a primeira coluna em forma de lista\n#para retornarmos o valor da primeira coluna mas na forma de linhas, onde cada valor está na sua linha:\nprint('0 a 1 para cortar: \\n', wines[:, 0:1]) #aqui retorna os valores na forma de uma única coluna\n\n\n# In[121]:\n\n\n#se for pra pegar o intervalo entre a primeira e a terceira coluna:\nwines[:, 0:3]\n\n\n# In[122]:\n\n\n#e se for pra buscar um número de colunas não consecutivas, tipo 0, 2, 4: criamos um array e colocamos esse array como\n#o segundo argumento da busca\nwines[:,[0,2,4]]\n\n\n# In[124]:\n\n\n#para fazer um resumo do dataset. se quisermos saber o valor médio da qualidade do vinho vermelho,\n#selecionamos a coluna de qualidade. o jeito mais apropriado de fazer isso é usando o valor -1 para buscar a última coluna\n#já que números negativos quer dizer que estamos buscando pelo final da lista\nwines[:, -1].mean()\n\n\n# # dataset de admissão escolar\n\n# In[153]:\n\n\ngraduate_admission = np.genfromtxt('Admission_Predict.csv', dtype=None, delimiter=\",\", skip_header=1,\n                                   names=(\"Serial_No\", 'GRE_Score', 'TOELF_Score', 'University_Rating', 'SOP',\n                                         'LOR', 'CGPA', 'Research', 'Chance_of Admit'))\ngraduate_admission.shape\n\n\n# In[154]:\n\n\n#podemos retornar uma coluna do array usando apenas o nome que demos aqui em cima\ngraduate_admission['CGPA'][0:5]\n\n\n# In[155]:\n\n\n#para deixar o valor numa escala de 0 a 4, podemos dividir o valor por 10 e multiplocar por 40\ngraduate_admission['CGPA'] = graduate_admission['CGPA'] / 10*4\n\n\n# In[156]:\n\n\ngraduate_admission['CGPA'][0:20]\n\n\n# In[157]:\n\n\n#usando boolean mask para descobrir quantos alunos tiveram experiência com pesquisa/research criando uma mascara booleana e\n#passando ela para o operador index do array\n\nlen(graduate_admission[graduate_admission['Research'] == 1])\n\n\n# In[159]:\n\n\n#identificar quandos alunos tem maiores chances de admissão >80% dos que tem menos chance de admissão <40%\n#primeiro usar a mascara booleana para pegar apenas aqueles alunos em que estamos interessados\n#baseado na sua chance de admissão, daí pegamos seu CGPA Score e imprimimos o valor médio\nprint(graduate_admission[graduate_admission['Chance_of_Admit']> 0.8]['GRE_Score'].mean())\nprint(graduate_admission[graduate_admission['Chance_of_Admit']< 0.4]['GRE_Score'].mean())\n\n\n# In[160]:\n\n\nprint(graduate_admission[graduate_admission['Chance_of_Admit']> 0.8]['CGPA'].mean())\nprint(graduate_admission[graduate_admission['Chance_of_Admit']< 0.4]['CGPA'].mean())\n\n", "meta": {"hexsha": "a8599a3f42c68bc390788fc6e78aa11ef22cdb59", "size": 9808, "ext": "py", "lang": "Python", "max_stars_repo_path": "Script Numpy.py", "max_stars_repo_name": "onativo/DataScience101", "max_stars_repo_head_hexsha": "68d42115e350371390e1fc851707598709efd4c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Script Numpy.py", "max_issues_repo_name": "onativo/DataScience101", "max_issues_repo_head_hexsha": "68d42115e350371390e1fc851707598709efd4c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Script Numpy.py", "max_forks_repo_name": "onativo/DataScience101", "max_forks_repo_head_hexsha": "68d42115e350371390e1fc851707598709efd4c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3681917211, "max_line_length": 123, "alphanum_fraction": 0.6932096248, "include": true, "reason": "import numpy", "num_tokens": 3200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.933430810103574, "lm_q1q2_score": 0.8562385646472619}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nBE523 Biosystems Analysis & Design\nHW2 - Problem 7. Bacteria growth, difference calculator\nhttps://mathinsight.org/bacteria_growth_initial_model_exercises Exercise 5\n\nCreated on Thu Jan 21 12:11:46 2021\n@author: eduardo\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm  # allows linear regression without intercept\n\n# Bacteria density data\n# B = [0.028, 0.047, 0.082, 0.141, 0.240, 0.381]  # Exercise 5\nB = np.array([0.022, 0.036, 0.060, 0.101, 0.169, 0.266])  # From problem 2\n\nsteps = len(B)  # Adjust the length of the vectors with the number of steps\ndB = np.zeros(steps)\ndt = 16  # time interval\n\nt = np.linspace(0, (steps-1)*dt, steps)  # actual time vector\n\nfor i in range(1, steps):\n    dB[i] = B[i] - B[i-1]  # compute the increment between time steps\n\n# Perform a linear regression with B and dB, then plot (dB vs B)\nmodel = sm.OLS(dB, B)  # No intercept by default, force through the origin\nresults = model.fit()\nslope = results.params[0]  # grow rate of population\nprint(\"slope=\", slope)\n\n# Figure 1, plotting dB vs B\nplt.figure(1)\nplt.plot(B, dB, 'kx', B, slope*B, 'b-')\nplt.legend(['data', 'linear regression $R^2$=%.3f' % results.rsquared], loc='best')\nplt.xlabel('B')\nplt.ylabel('dB')\nplt.savefig('p7_bacteria_linear2.png', dpi=300, bbox_inches='tight')\n\n# Generate an exponential equation ('exact solution')\ntdouble = np.log(2)/np.log(1+slope)*dt\nprint('tdouble =', tdouble)\nK = np.log(2)/tdouble\nBexp = B[0] * np.exp(K*t)\n\n# Make 'predictions' using the analytical solution to the linear dynamical system,\n# (also an exponential equation) in the form B(t) = B[0]*R^t with R>1\n# we don't need to know the previous value, each calculation is only dependant of the time 't'\nBmodel = B[0]*pow(slope+1, t/dt)\nprint(\"The population after %d steps is: %.3f\" % (steps, Bmodel[-1]))\n\n# Figure 2, plotting P (from data and model) vs t\nplt.figure(2)\nplt.plot(t, B, 'bx', t, Bmodel, 'r-', t, Bexp, 'k+')\nplt.legend(['data',\n            'numerical B=%g$\\cdot$(1+%.4f)$^t$' % (B[0], slope),\n            'exact B=%g$\\cdot$exp(%.4f$\\cdot$t)' % (B[0], K)],\n           loc='best')\nplt.xlabel('Time (minutes)')\nplt.ylabel('Bacteria population')\nplt.savefig('p7_bacteria_%dsteps2.png' % steps, dpi=300, bbox_inches='tight')\n", "meta": {"hexsha": "4093de74935662f0c3c14752ff7a4d3df7259723", "size": 2308, "ext": "py", "lang": "Python", "max_stars_repo_path": "p7_ex5_difference_calculator.py", "max_stars_repo_name": "eduardo-jh/HW02_Binary_Fission", "max_stars_repo_head_hexsha": "22a3cc619946ec875b13f26fbe788e23511844b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "p7_ex5_difference_calculator.py", "max_issues_repo_name": "eduardo-jh/HW02_Binary_Fission", "max_issues_repo_head_hexsha": "22a3cc619946ec875b13f26fbe788e23511844b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "p7_ex5_difference_calculator.py", "max_forks_repo_name": "eduardo-jh/HW02_Binary_Fission", "max_forks_repo_head_hexsha": "22a3cc619946ec875b13f26fbe788e23511844b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0625, "max_line_length": 94, "alphanum_fraction": 0.6737435009, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.9173026567597713, "lm_q1q2_score": 0.8562385577626694}}
{"text": "#Code for creating halton sampling in low n-dimensions\n# references : - https://gist.github.com/tupui/cea0a91cc127ea3890ac0f002f887bae\n#              - https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-34.php\n\nimport numpy as np\n\ndef primes (n):\n    #Defining prime numbers for base using sieve of erasthostenes\n    not_prime = []\n    prime = []\n    for i in range(2, n+1):\n        if i not in not_prime:\n            prime.append(i)\n            for j in range(i*i, n+1, i):\n                not_prime.append(j)\n    return prime\n\ndef vandercorput(n_sample,base=2):\n    #generate sample using van der corput sequence per dimension\n    sequence=[]\n    for i in range(0,n_sample):\n        f=1. ;   r=0.\n        while i > 0:\n            i, remainder = divmod(i, base)\n            f = f/base\n            r = r+f*remainder\n        sequence.append(r)\n    return sequence\n\ndef halton (dimension,n_sample):\n    # halton sequence general form of van der corput sequence in n-dimensions\n    big_number = 1000       # just an input for base, as long as dim <= len(base) the program won't error\n    base = primes(big_number)[:dimension]\n    #print(\"base = \",base)             # for debugging\n    sample = [vandercorput(n_sample + 1, dim) for dim in base] # looping van der corput for each dimension\n    sample = np.stack(sample, axis= -1)[1:]     #arrange the array\n    sample[1:n_sample,:] = sample[0:n_sample - 1,:]\n    sample[0,:] = 0\n    return sample\n\n\n", "meta": {"hexsha": "4dbd9e87e0f357468cb3db9b8191663d4c5b3c64", "size": 1473, "ext": "py", "lang": "Python", "max_stars_repo_path": "kadal/misc/sampling/haltonsampling.py", "max_stars_repo_name": "timjim333/KADAL", "max_stars_repo_head_hexsha": "8d190e7a28c83d5d1edffb3f85f1a629a481e47f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-07-31T09:59:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T07:47:32.000Z", "max_issues_repo_path": "kadal/misc/sampling/haltonsampling.py", "max_issues_repo_name": "timjim333/KADAL", "max_issues_repo_head_hexsha": "8d190e7a28c83d5d1edffb3f85f1a629a481e47f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-26T05:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T08:53:05.000Z", "max_forks_repo_path": "kadal/misc/sampling/haltonsampling.py", "max_forks_repo_name": "timjim333/KADAL", "max_forks_repo_head_hexsha": "8d190e7a28c83d5d1edffb3f85f1a629a481e47f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-01-26T09:33:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T04:40:56.000Z", "avg_line_length": 35.0714285714, "max_line_length": 106, "alphanum_fraction": 0.6252545825, "include": true, "reason": "import numpy", "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715436, "lm_q2_score": 0.896251377983158, "lm_q1q2_score": 0.8562060887120457}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef squareDistance(u, v):\n    diff = u - v\n    return diff.dot(diff)\n\n# We want to minimize intra-cluster variance (squard error)\ndef objective(X, R, M):\n    cost = 0\n    for k in range(len(M)):\n        for n in range(len(X)):\n            cost += R[n,k] * squareDistance(M[k], X[n])\n\n    return cost\n\ndef expDistance(p1, p2, beta):\n    return np.exp(-beta * squareDistance(p1, p2))\n\ndef plot_k_means(X, K, max_iter=20, beta=1.0):\n    N, D = X.shape\n\n    M = np.array(\n        X[np.random.choice(N, K, replace=False), :]\n    )\n\n    R = np.zeros((N, K))\n\n    costs = np.zeros(max_iter)\n    for i in range(max_iter):\n        # calculate responsibility for each point for each cluster\n        for k in range(K):\n            for n in range(N):\n                sumMeanDistances = np.array([\n                    expDistance(M[j], X[n], beta) for j in range(K)\n                ]).sum()\n\n                meanDistance = expDistance(M[k], X[n], beta)\n\n                softMax = meanDistance / sumMeanDistances\n\n                R[n,k] = softMax\n\n        # calculate the means for each cluster\n        for k in range(K):\n            M[k] = R[:,k].dot(X) / R[:,k].sum()\n\n        # calculate cost and break if it hasn't changed much\n        costs[i] = objective(X, R, M)\n        if i > 0 and np.abs(costs[i] - costs[i - 1]) < 0.1:\n            break\n\n    # pick K random RGB values to represent clusters\n    random_colors = np.random.random((K, 3))\n    # weight the color of a point based on its responsibility to each cluster.\n    colors = R.dot(random_colors)\n\n    plt.scatter(X[:,0], X[:,1], c=colors)\n    plt.show()\n\ndef generate_samples():\n    D = 2\n    s = 4 # distance between means\n\n    mean1 = np.array([0, 0])\n    mean2 = np.array([s, s])\n    mean3 = np.array([0, s])\n\n    samples = 900\n    data = np.zeros((samples, D))\n\n    # generate the dataset\n    data[:300, :] = np.random.randn(300, D) + mean1\n    data[300:600, :] = np.random.randn(300, D) + mean2\n    data[600:, :] = np.random.randn(300, D) + mean3\n\n    return data\n\ndef main():\n    data = generate_samples()\n\n    clusters = 3\n    plot_k_means(data, clusters)\n\n    # clusters = 5\n    # plot_k_means(data, clusters, max_iter=30)\n\n    # clusters = 5\n    # plot_k_means(data, clusters, max_iter=30, beta=0.3)\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "604399a196f321f3002b940976de631e869d9b29", "size": 2350, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/kmeans.py", "max_stars_repo_name": "kradical/cluster-analysis-udemy", "max_stars_repo_head_hexsha": "e2101bdb08ae3b9ed0ed8c4c1c488e3a75a1b7c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kmeans.py", "max_issues_repo_name": "kradical/cluster-analysis-udemy", "max_issues_repo_head_hexsha": "e2101bdb08ae3b9ed0ed8c4c1c488e3a75a1b7c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kmeans.py", "max_forks_repo_name": "kradical/cluster-analysis-udemy", "max_forks_repo_head_hexsha": "e2101bdb08ae3b9ed0ed8c4c1c488e3a75a1b7c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2688172043, "max_line_length": 78, "alphanum_fraction": 0.5680851064, "include": true, "reason": "import numpy", "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191246389617, "lm_q2_score": 0.8962513828326956, "lm_q1q2_score": 0.8562060865041897}}
{"text": "# reference: Liu, Y. and Durlofsky, L.J., 2020. 3D CNN-PCA: A Deep-Learning-Based. Parameterization for Complex Geomodels. arXiv preprint arXiv:2007.08478\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass PCA(object):\n    def __init__(self, nc=1, nr=1, l=1):\n        self.l = l\n        self.nc = nc\n        self.nr = nr\n        self.xm = np.zeros((nc, 1))\n        self.usig = np.zeros((nc, l))\n        self.data_matrix = None\n        self.sig = None\n        self.u = None\n\n    def construct_pca(self, x):\n        assert x.shape == (self.nc, self.nr)\n        self.data_matrix = x\n        self.xm = np.mean(x, axis=1)[:, None]\n        y = 1. / (np.sqrt(float(self.nr - 1.))) * (x - self.xm)\n        self.u, self.sig, _ = np.linalg.svd(y, full_matrices=False)\n        self.u = self.u[:, :self.l]\n        self.sig = self.sig[:self.l, None]\n        self.usig = np.dot(self.u, np.diag(self.sig[:, 0]))\n\n    def generate_pca_realization(self, xi, dim=None):\n        if dim is None:\n            assert xi.shape[0] == self.l\n            if xi.shape == (self.l, ):\n                xi = xi[:, None]\n            return self.usig.dot(xi) + self.xm\n        else:\n            assert xi.shape[0] == dim\n            if xi.shape == (dim, ):\n                xi = xi[:, None]\n            return self.usig[:, :dim].dot(xi) + self.xm\n\n    def get_xi(self, m, dim=None):\n        assert self.u is not None, \"Input or calculate U matrix to obtain reconstructed xi\"\n        assert m.shape[0] == self.nc\n\n        if m.shape == (self.nc, ):\n            m = m[:, None]\n        if dim is None:\n            xi = self.u.T.dot(m - self.xm) / self.sig\n        else:\n            xi = self.u[:, :dim].T.dot(m - self.xm) / self.sig[:dim]\n        return xi\n\n    def energy_plot(self, rel_energy, truncate_point):\n        plt.figure(figsize=(8, 4))\n        plt.subplot(1, 2, 1)\n        plt.plot(rel_energy)\n        plt.ylabel('Relative Energy', fontsize=12)\n        plt.xlabel('Number of principal components', fontsize=12)\n        plt.subplot(1, 2, 2)\n        plt.plot(rel_energy[:truncate_point])\n        plt.ylabel('Relative Energy', fontsize=12)\n        plt.xlabel('Number of principal components', fontsize=12)\n        plt.tight_layout()\n        plt.show()\n\n    def princ_component(self, tol=0.9):\n        cum_energy = np.cumsum(self.sig**2)\n        rel_energy = cum_energy / cum_energy[-1]\n        truncate_point = np.argmin(np.abs(rel_energy - tol)) + 1\n        print('Principle components: ', truncate_point)\n        return truncate_point, rel_energy\n", "meta": {"hexsha": "b29378c182516843f891b8a7585b61951d3a55ce", "size": 2529, "ext": "py", "lang": "Python", "max_stars_repo_path": "ESMDA_2D/src/pca.py", "max_stars_repo_name": "tang39/DLADA", "max_stars_repo_head_hexsha": "8e855997df6453a03028a7a01c300fa6aa8a4087", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ESMDA_2D/src/pca.py", "max_issues_repo_name": "tang39/DLADA", "max_issues_repo_head_hexsha": "8e855997df6453a03028a7a01c300fa6aa8a4087", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ESMDA_2D/src/pca.py", "max_forks_repo_name": "tang39/DLADA", "max_forks_repo_head_hexsha": "8e855997df6453a03028a7a01c300fa6aa8a4087", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1285714286, "max_line_length": 154, "alphanum_fraction": 0.5591142744, "include": true, "reason": "import numpy", "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436404, "lm_q2_score": 0.8962513627417531, "lm_q1q2_score": 0.8562060752917585}}
{"text": "from sys import *\r\nfrom sympy import *\r\nimport numpy as np\r\n#from sympy import Symbol, solve\r\nfrom sympy import init_printing\r\nfrom sympy.solvers.solveset import linsolve\r\nfrom sympy.polys.polyfuncs import horner\r\n\r\ndef symbolCIP(nOrder):\r\n    # Simple check\r\n    if nOrder % 2 == 0:\r\n        sys.exit(\"Order might be odd more than 3,\\n\"\r\n                 \"for issue 3, 5, 7, 9, etc.\")\r\n\r\n    # Set values\r\n    coeff = symbols('a0:%d' % (nOrder + 1))\r\n    xi, h = symbols('xi, h')\r\n    ucval = symbols('uC:%d' % (nOrder - 1))\r\n    urval = symbols('uR:%d' % (nOrder - 1))\r\n    ulval = symbols('uL:%d' % (nOrder - 1))\r\n\r\n    # Set interpolation polynomials\r\n    fpoly = sum(coeff[k] * xi ** k for k in range(nOrder+1))\r\n    dfpoly = []\r\n    for k in range(np.int((nOrder + 1)/2)):\r\n        dfpoly.append(fpoly.diff(xi, k))\r\n\r\n    # Set constrains\r\n    eqs_left = []\r\n    eqs_right = []\r\n    for k in range(np.int((nOrder + 1)/2)):\r\n        eqs_right.append(dfpoly[k].subs(xi, 0))\r\n        eqs_right.append(dfpoly[k].subs(xi,-h))\r\n        eqs_left.append(dfpoly[k].subs(xi, 0))\r\n        eqs_left.append(dfpoly[k].subs(xi, h))\r\n\r\n    # Solve system under constrains\r\n    # Right wave\r\n    vals_right = ucval + ulval\r\n    sys_eqns_right = [eqs_right[k] - vals_right[k] for k in range((nOrder+1))]\r\n    sol_right = linsolve(sys_eqns_right, coeff)\r\n    sol_right_list = list(sol_right)\r\n    print('Right wave:\\n', sol_right_list[0])\r\n    # Left wave\r\n    vals_left = ucval + urval\r\n    sys_eqns_left = [eqs_left[k] - vals_left[k] for k in range((nOrder+1))]\r\n    sol_left = linsolve(sys_eqns_left, coeff)\r\n    sol_left_list = list(sol_left)\r\n    print('Left wave:\\n', sol_left_list[0])\r\n    # print('LaTeX form:\\n', latex(sol_left_list[0]))\r\n    # print('Mathematica form:\\n', mathematica_code(sol_left_list[0]))\r\n    # print('C form:\\n', ccode(sol_left_list[0]))\r\n    # print('Octave form:\\n', octave_code(sol_left_list[0]))\r\n\r\n\r\ndef symboldeltaP3():\r\n    x, a, h, t, nu, c1, c2, c3, c4, ui, ui1, ri, ri1, uxx, u3x, rx, rxx, _uni \\\r\n        = symbols('x, a, h, t, nu, c1, c2, c3, c4, ui, ui1, ri, ri1, uxx, u3x, rx, rxx, _uni')\r\n    # Set interpolants\r\n    u = c1 + c2 * x + c3 * x ** 2 + c4 * x ** 3\r\n    du = u.diff(x)\r\n    print(du)\r\n    # Set constrains\r\n    eq01 = u.subs(x, 0)\r\n    eq02 = du.subs(x, 0)\r\n    eq03 = u.subs(x, -h)\r\n    eq04 = du.subs(x, -h)\r\n    # Solve system under constrains\r\n    sol = linsolve([eq01 - ui, eq02 - ri, eq03 - ui1, eq04 - ri1], (c1, c2, c3, c4))\r\n    # Get coefficients\r\n    sol_get = next(iter(sol))\r\n    c1_expr = sol_get[0].subs(ri, ri / h)\r\n    c2_expr = sol_get[1].subs(ri, ri / h)\r\n    c3_expr = sol_get[2].subs(ri, ri / h).subs(ri1, ri1 / h)\r\n    c4_expr = sol_get[3].subs(ri, ri / h).subs(ri1, ri1 / h)\r\n    print((\"c1 = {0}\".format(c1_expr)))\r\n    print((\"c2 = {0}\".format(c2_expr)))\r\n    print((\"c3 = {0}\".format(c3_expr)))\r\n    print((\"c4 = {0}\".format(c4_expr)))\r\n\r\n    # print(\"u = {0}\".format(u))\r\n    # nu = a * t / h\r\n    # Set constrains\r\n    ui = u.subs(x, 0)\r\n    ui1 = u.subs(x, -h)\r\n\r\n    ux = u.diff(x)\r\n    uxi = ux.subs(x, 0)\r\n\r\n    uxx = ux.diff(x)\r\n    uxxi = uxx.subs(x, 0)\r\n\r\n    u3x = uxx.diff(x)\r\n    u3xi = u3x.subs(x, 0)\r\n\r\n    r = h * u.diff(x)\r\n    ri = r.subs(x, 0)\r\n\r\n    rx = r.diff(x)\r\n    rxi = rx.subs(x, 0)\r\n\r\n    rxx = rx.diff(x)\r\n    rxxi = rxx.subs(x, 0)\r\n\r\n    # uxx = ux.diff(x)\r\n    # u3x = uxx.diff(x)\r\n\r\n    # print(\"ui = {0}, ui1 = {1}, ri = {2}, ri1 = {3}\".format(simplify(ui), simplify(ui1), ri, ri1))\r\n    #\r\n    # c1 = ui\r\n    # c2 = ri / h\r\n    #\r\n    # c3 = (3 * (ui1 - ui) + 2 * ri + ri1) / h**2\r\n    # c4 = (2 * (ui1 - ui) + ri + ri1) / h**3\r\n\r\n    # uxx = 2 * c3\r\n    # u3x = 6 * c4\r\n    #\r\n    # rx = h * 2 * c3\r\n    # rxx = h * 6 * c4\r\n\r\n    uni = ui - a * t * uxi + a**2 * t**2 / 2 * uxxi - a**3 * t**3 / 6 * u3xi\r\n    # uni = simplify(uni)\r\n    _uni = uni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(a * t / h, nu)\r\n    _uni = collect(expand(_uni), nu)\r\n    print(_uni)\r\n\r\n    rni = simplify(ri - a * t * rxi + a**2 * t**2 / 2 * rxxi)\r\n    _rni = rni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(a * t / h, nu)\r\n    print(collect(expand(_rni), nu))\r\n\r\ndef symbolDeltaP():\r\n    # # Simple check\r\n    # if nOrder % 2 == 0:\r\n    #     sys.exit(\"Order might be odd more than 3,\\n\"\r\n    #              \"for issue 3, 5, 7, 9, etc.\")\r\n    nOrder = 3\r\n    # Set values\r\n    coeff = symbols('с1:%d' % (nOrder + 2))\r\n    print(coeff)\r\n    x, a, h, t, nu, c1, c2, c3, c4, ui, ui1, ri, ri1, uxx, u3x, rx, rxx, _uni \\\r\n        = symbols('x, a, h, t, nu, c1, c2, c3, c4, ui, ui1, ri, ri1, uxx, u3x, rx, rxx, _uni')\r\n    # Set interpolants\r\n    u = c1 + c2 * x + c3 * x ** 2 + c4 * x ** 3\r\n    print(u)\r\n    u = sum(coeff[k] * x ** k for k in range(nOrder + 1))\r\n    du = u.diff(x)\r\n    print(u)\r\n    # Set constrains\r\n    eq01 = u.subs(x, 0)\r\n    eq02 = du.subs(x, 0)\r\n    eq03 = u.subs(x, -h)\r\n    eq04 = du.subs(x, -h)\r\n    # Solve system under constrains\r\n    sol = linsolve([eq01 - ui, eq02 - ri, eq03 - ui1, eq04 - ri1], (c1, c2, c3, c4))\r\n    # Get coefficients\r\n    sol_get = next(iter(sol))\r\n    c1_expr = sol_get[0].subs(ri, ri / h)\r\n    c2_expr = sol_get[1].subs(ri, ri / h)\r\n    c3_expr = sol_get[2].subs(ri, ri / h).subs(ri1, ri1 / h)\r\n    c4_expr = sol_get[3].subs(ri, ri / h).subs(ri1, ri1 / h)\r\n    print((\"c1 = {0}\".format(c1_expr)))\r\n    print((\"c2 = {0}\".format(c2_expr)))\r\n    print((\"c3 = {0}\".format(c3_expr)))\r\n    print((\"c4 = {0}\".format(c4_expr)))\r\n\r\n    # print(\"u = {0}\".format(u))\r\n    # nu = a * t / h\r\n    # Set constrains\r\n    ui = u.subs(x, 0)\r\n    ui1 = u.subs(x, -h)\r\n\r\n    ux = u.diff(x)\r\n    uxi = ux.subs(x, 0)\r\n\r\n    uxx = ux.diff(x)\r\n    uxxi = uxx.subs(x, 0)\r\n\r\n    u3x = uxx.diff(x)\r\n    u3xi = u3x.subs(x, 0)\r\n\r\n    r = h * u.diff(x)\r\n    ri = r.subs(x, 0)\r\n\r\n    rx = r.diff(x)\r\n    rxi = rx.subs(x, 0)\r\n\r\n    rxx = rx.diff(x)\r\n    rxxi = rxx.subs(x, 0)\r\n\r\n    # uxx = ux.diff(x)\r\n    # u3x = uxx.diff(x)\r\n\r\n    # print(\"ui = {0}, ui1 = {1}, ri = {2}, ri1 = {3}\".format(simplify(ui), simplify(ui1), ri, ri1))\r\n    #\r\n    # c1 = ui\r\n    # c2 = ri / h\r\n    #\r\n    # c3 = (3 * (ui1 - ui) + 2 * ri + ri1) / h**2\r\n    # c4 = (2 * (ui1 - ui) + ri + ri1) / h**3\r\n\r\n    # uxx = 2 * c3\r\n    # u3x = 6 * c4\r\n    #\r\n    # rx = h * 2 * c3\r\n    # rxx = h * 6 * c4\r\n\r\n    uni = ui - a * t * uxi + a**2 * t**2 / 2 * uxxi - a**3 * t**3 / 6 * u3xi\r\n    # uni = simplify(uni)\r\n    _uni = uni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(a * t / h, nu)\r\n    _uni = collect(expand(_uni), nu)\r\n    print(_uni)\r\n\r\n    rni = simplify(ri - a * t * rxi + a**2 * t**2 / 2 * rxxi)\r\n    _rni = rni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(a * t / h, nu)\r\n    print(collect(expand(_rni), nu))\r\n\r\n\r\n# def symboldeltaP5():\r\n#     x, a, h, tau, nu, ui, ui1, ri, ri1, u3x, u4x, u5x, rxi, rxi1, rxx, r3x, r4x \\\r\n#         = symbols('x, a, h, tau, nu, ui, ui1, ri, ri1, u3x, u4x, u5x, rxi, rxi1, rxx, r3x, r4x')\r\n#\r\n#     c1, c2, c3, c4, c5, c6 = symbols('c1, c2, c3, c4, c5, c6')\r\n#\r\n#     _uxi, _uxxi, _ux1i, _uxx1i = symbols('_uxi, _uxxi, _ux1i, _uxx1i')\r\n#\r\n#     u = c1 + c2 * x + c3 * x ** 2 + c4 * x ** 3 + c5 * x ** 4 + c6 * x ** 5\r\n#\r\n#     du = u.diff(x)\r\n#     ddu = du.diff(x)\r\n#     eq01 = u.subs(x, 0)\r\n#     eq02 = du.subs(x, 0)\r\n#     eq03 = u.subs(x, -h)\r\n#     eq04 = du.subs(x, -h)\r\n#     eq05 = ddu.subs(x, 0)\r\n#     eq06 = ddu.subs(x, -h)\r\n#     # Solve system under constrains\r\n#     sol = linsolve([eq01 - ui, eq02 - _uxi, eq03 - ui1, eq04 - _ux1i, eq05 - _uxxi, eq06 - _uxx1i],\r\n#                    (c1, c2, c3, c4, c5, c6))\r\n#\r\n#     sol_get = next(iter(sol))\r\n#     # c1_expr = sol_get[0].subs(ri, ri / h).subs(ri1, ri1 / h).subs(rxi, rxi / h**2).subs(rxi1, rxi1 / h**2)\r\n#     # c2_expr = sol_get[1].subs(ri, ri / h).subs(ri1, ri1 / h).subs(rxi, rxi / h**2).subs(rxi1, rxi1 / h**2)\r\n#     # c3_expr = sol_get[2].subs(ri, ri / h).subs(ri1, ri1 / h).subs(rxi, rxi / h**2).subs(rxi1, rxi1 / h**2)\r\n#     # c4_expr = sol_get[3].subs(ri, ri / h).subs(ri1, ri1 / h).subs(rxi, rxi / h**2).subs(rxi1, rxi1 / h**2)\r\n#     # c5_expr = sol_get[4].subs(ri, ri / h).subs(ri1, ri1 / h).subs(rxi, rxi / h**2).subs(rxi1, rxi1 / h**2)\r\n#     # c6_expr = sol_get[5].subs(ri, ri / h).subs(ri1, ri1 / h).subs(rxi, rxi / h**2).subs(rxi1, rxi1 / h**2)\r\n#     c1_expr = sol_get[0]\r\n#     c2_expr = sol_get[1].subs(_uxi, ri / h)\r\n#     c3_expr = sol_get[2].subs(_uxxi, rxi / h ** 2)\r\n#     c4_expr = sol_get[3].subs(h * _uxi, ri).subs(h * _ux1i, ri1).subs(h ** 2 * _uxxi, rxi).subs(h ** 2 * _uxx1i, rxi1)\r\n#     c5_expr = sol_get[4].subs(h * _uxi, ri).subs(h * _ux1i, ri1).subs(h ** 2 * _uxxi, rxi).subs(h ** 2 * _uxx1i, rxi1)\r\n#     c6_expr = sol_get[5].subs(h * _uxi, ri).subs(h * _ux1i, ri1).subs(h ** 2 * _uxxi, rxi).subs(h ** 2 * _uxx1i, rxi1)\r\n#     print(\"c1 = {0}\".format(c1_expr))\r\n#     print(\"c2 = {0}\".format(c2_expr))\r\n#     print(\"c3 = {0}\".format(c3_expr))\r\n#     print(\"c4 = {0}\".format(c4_expr))\r\n#     print(\"c5 = {0}\".format(c5_expr))\r\n#     print(\"c6 = {0}\".format(c6_expr))\r\n#\r\n#     # print(\"u = {0}\".format(u))\r\n#     # Set constrains\r\n#     ui = u.subs(x, 0)\r\n#\r\n#     ux = u.diff(x)\r\n#     uxi = ux.subs(x, 0)\r\n#\r\n#     uxx = ux.diff(x)\r\n#     uxxi = uxx.subs(x, 0)\r\n#\r\n#     u3x = uxx.diff(x)\r\n#     u3xi = u3x.subs(x, 0)\r\n#\r\n#     u4x = u3x.diff(x)\r\n#     u4xi = u4x.subs(x, 0)\r\n#\r\n#     u5x = u4x.diff(x)\r\n#     u5xi = u5x.subs(x, 0)\r\n#\r\n#     r = h * ux\r\n#     ri = r.subs(x, 0)\r\n#\r\n#     rx = r.diff(x)\r\n#     rxi = rx.subs(x, 0)\r\n#\r\n#     rxx = rx.diff(x)\r\n#     rxxi = rxx.subs(x, 0)\r\n#\r\n#     r3x = rxx.diff(x)\r\n#     r3xi = r3x.subs(x, 0)\r\n#\r\n#     r4x = r3x.diff(x)\r\n#     r4xi = r4x.subs(x, 0)\r\n#\r\n#     # uxx = ux.diff(x)\r\n#     # u3x = uxx.diff(x)\r\n#\r\n#     # print(\"ui = {0}, ui1 = {1}, ri = {2}, ri1 = {3}\".format(simplify(ui), simplify(ui1), ri, ri1))\r\n#     #\r\n#     # c1 = ui\r\n#     # c2 = ri / h\r\n#     #\r\n#     # c3 = (3 * (ui1 - ui) + 2 * ri + ri1) / h**2\r\n#     # c4 = (2 * (ui1 - ui) + ri + ri1) / h**3\r\n#\r\n#     # uxx = 2 * c3\r\n#     # u3x = 6 * c4\r\n#     #\r\n#     # rx = h * 2 * c3\r\n#     # rxx = h * 6 * c4\r\n#\r\n#     uni = (ui - a * tau * uxi + a**2 * tau**2 / 2 * uxxi - a**3 * tau**3 / 6\r\n#            * u3xi + a**4 * tau**4 / 24 * u4xi - a ** 5 * tau ** 5 / 120 * u5xi)\r\n#\r\n#     _uni = uni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr)\\\r\n#         .subs(c4, c4_expr).subs(c5, c5_expr).subs(c6, c6_expr).subs(a * tau / h, nu)\r\n#\r\n#     rni = ri - a * tau * rxi + a**2 * tau**2 / 2 * rxxi - a**3 * tau**3 / 6 * r3xi + a**4 * tau**4 / 24 * r4xi\r\n#\r\n#     _rni = rni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr)\\\r\n#         .subs(c4, c4_expr).subs(c5, c5_expr).subs(c6, c6_expr).subs(a * tau / h, nu)\r\n#\r\n#     rxni = rxi - a * tau * rxxi + a**2 * tau**2 / 2 * r3xi - a**3 * tau**3 / 6 * r4xi\r\n#\r\n#     _rxni = rxni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr)\\\r\n#         .subs(c4, c4_expr).subs(c5, c5_expr).subs(c6, c6_expr).subs(a * tau / h, nu) * h\r\n#\r\n#     print(simplify(_uni))\r\n#     print(simplify(_rni))\r\n#     print(simplify(_rxni))\r\n\r\n# def symboldeltaP7():\r\n#     x, a, h, tau, nu, c1, c2, c3, c4, c5, c6, c7, c8 = symbols('x, a, h, tau, nu, c1, c2, c3, c4, c5, c6, c7, c8')\r\n#\r\n#     ui, ui1, uxi, uxi1, uxxi, uxxi1, u3xi, u3xi1 = symbols('ui, ui1, ri, ri1, uxxi, uxx1i, u3xi, u3x1i')\r\n#\r\n#     ri, ri1, rxi, rxi1, rxxi, rxxi1 = symbols('ri, ri1, rxi, rxi1, rxxi, rxxi1')\r\n#\r\n#     u = c1 + c2 * x + c3 * x ** 2 + c4 * x ** 3 + c5 * x ** 4 + c6 * x ** 5 + c7 * x ** 6 + c8 * x ** 7\r\n#\r\n#     du = u.diff(x)\r\n#     ddu = du.diff(x)\r\n#     dddu = ddu.diff(x)\r\n#     eq01 = u.subs(x, 0)\r\n#     eq02 = du.subs(x, 0)\r\n#     eq03 = u.subs(x, -h)\r\n#     eq04 = du.subs(x, -h)\r\n#     eq05 = ddu.subs(x, 0)\r\n#     eq06 = ddu.subs(x, -h)\r\n#     eq07 = dddu.subs(x, 0)\r\n#     eq08 = dddu.subs(x, -h)\r\n#     # Solve system under constrains\r\n#     sol = linsolve([eq01 - ui, eq02 - uxi, eq03 - ui1, eq04 - uxi1, eq05 - uxxi, eq06 - uxxi1, eq07 - u3xi, eq08 - u3xi1],\r\n#                    (c1, c2, c3, c4, c5, c6, c7, c8))\r\n#     sol_get = next(iter(sol))\r\n#     c1_expr = sol_get[0]\r\n#     c2_expr = sol_get[1].subs(uxi, ri / h)\r\n#     c3_expr = sol_get[2].subs(uxxi, rxi / h ** 2)\r\n#     c4_expr = sol_get[3].subs(u3xi, rxxi / h ** 3)\r\n#     c5_expr = sol_get[4].subs(h * uxi, ri).subs(h * uxi1, ri1).subs(h ** 2 * uxxi, rxi)\\\r\n#         .subs(h ** 2 * uxxi1, rxi1).subs(h ** 3 * u3xi, rxxi).subs(h ** 3 * u3xi1, rxxi1)\r\n#     c6_expr = sol_get[5].subs(h * uxi, ri).subs(h * uxi1, ri1).subs(h ** 2 * uxxi, rxi)\\\r\n#         .subs(h ** 2 * uxxi1, rxi1).subs(h ** 3 * u3xi, rxxi).subs(h ** 3 * u3xi1, rxxi1)\r\n#     c7_expr = sol_get[6].subs(h * uxi, ri).subs(h * uxi1, ri1).subs(h ** 2 * uxxi, rxi)\\\r\n#         .subs(h ** 2 * uxxi1, rxi1).subs(h ** 3 * u3xi, rxxi).subs(h ** 3 * u3xi1, rxxi1)\r\n#     c8_expr = sol_get[7].subs(h * uxi, ri).subs(h * uxi1, ri1).subs(h ** 2 * uxxi, rxi)\\\r\n#         .subs(h ** 2 * uxxi1, rxi1).subs(h ** 3 * u3xi, rxxi).subs(h ** 3 * u3xi1, rxxi1)\r\n#\r\n#     print(\"c1 = {0}\".format(c1_expr))\r\n#     print(\"c2 = {0}\".format(c2_expr))\r\n#     print(\"c3 = {0}\".format(c3_expr))\r\n#     print(\"c4 = {0}\".format(c4_expr))\r\n#     print(\"c5 = {0}\".format(c5_expr))\r\n#     print(\"c6 = {0}\".format(c6_expr))\r\n#     print(\"c7 = {0}\".format(c7_expr))\r\n#     print(\"c8 = {0}\".format(c8_expr))\r\n#\r\n#\r\n#     # Set constrains\r\n#     ui = u.subs(x, 0)\r\n#\r\n#     ux = u.diff(x)\r\n#     uxi = ux.subs(x, 0)\r\n#\r\n#     uxx = ux.diff(x)\r\n#     uxxi = uxx.subs(x, 0)\r\n#\r\n#     u3x = uxx.diff(x)\r\n#     u3xi = u3x.subs(x, 0)\r\n#\r\n#     u4x = u3x.diff(x)\r\n#     u4xi = u4x.subs(x, 0)\r\n#\r\n#     u5x = u4x.diff(x)\r\n#     u5xi = u5x.subs(x, 0)\r\n#\r\n#     u6x = u5x.diff(x)\r\n#     u6xi = u6x.subs(x, 0)\r\n#\r\n#     u7x = u6x.diff(x)\r\n#     u7xi = u7x.subs(x, 0)\r\n#\r\n#     r = h * u.diff(x)\r\n#     ri = r.subs(x, 0)\r\n#\r\n#     rx = r.diff(x)\r\n#     rxi = rx.subs(x, 0)\r\n#\r\n#     rxx = rx.diff(x)\r\n#     rxxi = rxx.subs(x, 0)\r\n#\r\n#     r3x = rxx.diff(x)\r\n#     r3xi = r3x.subs(x, 0)\r\n#\r\n#     r4x = r3x.diff(x)\r\n#     r4xi = r4x.subs(x, 0)\r\n#\r\n#     r5x = r4x.diff(x)\r\n#     r5xi = r5x.subs(x, 0)\r\n#\r\n#     r6x = r5x.diff(x)\r\n#     r6xi = r6x.subs(x, 0)\r\n#\r\n#     # uxx = ux.diff(x)\r\n#     # u3x = uxx.diff(x)\r\n#\r\n#     # print(\"ui = {0}, ui1 = {1}, ri = {2}, ri1 = {3}\".format(simplify(ui), simplify(ui1), ri, ri1))\r\n#     #\r\n#     # c1 = ui\r\n#     # c2 = ri / h\r\n#     #\r\n#     # c3 = (3 * (ui1 - ui) + 2 * ri + ri1) / h**2\r\n#     # c4 = (2 * (ui1 - ui) + ri + ri1) / h**3\r\n#\r\n#     # uxx = 2 * c3\r\n#     # u3x = 6 * c4\r\n#     #\r\n#     # rx = h * 2 * c3\r\n#     # rxx = h * 6 * c4\r\n#\r\n#     uni = ui - a * tau * uxi + a**2 * tau**2 / 2 * uxxi - a**3 * tau**3 / 6 * u3xi + a**4 * tau**4 / 24 * u4xi \\\r\n#           - a ** 5 * tau ** 5 / 120 * u5xi + a ** 6 * tau ** 6 / 720 * u6xi - a ** 7 * tau ** 7 / 5040 * u7xi\r\n#\r\n#     rni = ri - a * tau * rxi + a**2 * tau**2 / 2 * rxxi - a**3 * tau**3 / 6 * r3xi + a**4 * tau**4 / 24 * r4xi \\\r\n#           - a ** 5 * tau ** 5 / 120 * r5xi + a ** 6 * tau ** 6 / 720 * r6xi\r\n#\r\n#     rxni = rxi - a * tau * rxxi + a**2 * tau**2 / 2 * r3xi - a**3 * tau**3 / 6 * r4xi \\\r\n#            + a**4 * tau**4 / 24 * r5xi - a ** 5 * tau ** 5 / 120 * r6xi\r\n#\r\n#     rxxni = rxxi - a * tau * r3xi + a**2 * tau**2 / 2 * r4xi - a**3 * tau**3 / 6 * r5xi \\\r\n#             + a**4 * tau**4 / 24 * r6xi\r\n#\r\n#     uni = uni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr)\\\r\n#         .subs(c4, c4_expr).subs(c5, c5_expr).subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(a * tau / h, nu)\r\n#\r\n#     rni = rni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr) \\\r\n#         .subs(c4, c4_expr).subs(c5, c5_expr).subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(a * tau / h, nu)\r\n#\r\n#     rxni = rxni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr) \\\r\n#         .subs(c4, c4_expr).subs(c5, c5_expr).subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr)\\\r\n#         .subs(a * tau / h, nu) * h\r\n#\r\n#     rxxni = rxxni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr) \\\r\n#         .subs(c4, c4_expr).subs(c5, c5_expr).subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr)\\\r\n#         .subs(a * tau / h, nu) * h ** 2\r\n#\r\n#     print(\"uni = {0}\".format(simplify(uni)))\r\n#     print(\"rni = {0}\".format(simplify(rni)))\r\n#     print(\"rxni = {0}\".format(simplify(rxni)))\r\n#     print(\"rxxni = {0}\".format(simplify(rxxni)))\r\n#\r\n#     # print(\"rx = {0}, с2 = {1}, с3 = {2}, с4 = {3}, с5 = {4}\".format(simplify(rx), simplify(c2), c3, c4, c5))\r\n\r\n# def symboldeltaP9():\r\n#     x, a, h, tau, nu, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10 \\\r\n#         = symbols('x, a, h, tau, nu, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10')\r\n#\r\n#     ui, ui1, uxi, uxi1, uxxi, uxxi1, u3xi, u3xi1, u4xi, u4xi1 \\\r\n#         = symbols('ui, ui1, ri, ri1, uxxi, uxx1i, u3xi, u3x1i, u4xi, u4xi1')\r\n#\r\n#     ri, ri1, rxi, rxi1, rxxi, rxxi1, r3xi, r3xi1 = symbols('ri, ri1, rxi, rxi1, rxxi, rxxi1, r3xi, r3xi1')\r\n#\r\n#     u = c1 + c2 * x + c3 * x ** 2 + c4 * x ** 3 + c5 * x ** 4 + c6 * x ** 5 + c7 * x ** 6 + c8 * x ** 7 \\\r\n#         + c9 * x ** 8 + c10 * x ** 9\r\n#\r\n#     du = u.diff(x)\r\n#     ddu = du.diff(x)\r\n#     d3u = ddu.diff(x)\r\n#     d4u = d3u.diff(x)\r\n#\r\n#     eq01 = u.subs(x, 0)\r\n#     eq02 = du.subs(x, 0)\r\n#     eq03 = u.subs(x, -h)\r\n#     eq04 = du.subs(x, -h)\r\n#     eq05 = ddu.subs(x, 0)\r\n#     eq06 = ddu.subs(x, -h)\r\n#     eq07 = d3u.subs(x, 0)\r\n#     eq08 = d3u.subs(x, -h)\r\n#     eq09 = d4u.subs(x, 0)\r\n#     eq10 = d4u.subs(x, -h)\r\n#\r\n#     # Solve system under constrains\r\n#\r\n#     sol = linsolve([eq01 - ui, eq02 - uxi, eq03 - ui1, eq04 - uxi1, eq05 - uxxi, eq06 - uxxi1, eq07 - u3xi,\r\n#                     eq08 - u3xi1, eq09 - u4xi, eq10 - u4xi1], (c1, c2, c3, c4, c5, c6, c7, c8, c9, c10))\r\n#\r\n#     sol_get = next(iter(sol))\r\n#\r\n#     c1_expr = sol_get[0]\r\n#     c2_expr = sol_get[1].subs(uxi, ri / h)\r\n#     c3_expr = sol_get[2].subs(uxxi, rxi / h ** 2)\r\n#     c4_expr = sol_get[3].subs(u3xi, rxxi / h ** 3)\r\n#     c5_expr = sol_get[4].subs(u4xi, r3xi / h ** 4)\r\n#     c6_expr = sol_get[5].subs(h * uxi, ri).subs(h * uxi1, ri1).subs(h ** 2 * uxxi, rxi) \\\r\n#         .subs(h ** 2 * uxxi1, rxi1).subs(h ** 3 * u3xi, rxxi).subs(h ** 3 * u3xi1, rxxi1).subs(h ** 4 * u4xi, r3xi)\\\r\n#         .subs(h ** 4 * u4xi1, r3xi1)\r\n#     c7_expr = sol_get[6].subs(h * uxi, ri).subs(h * uxi1, ri1).subs(h ** 2 * uxxi, rxi) \\\r\n#         .subs(h ** 2 * uxxi1, rxi1).subs(h ** 3 * u3xi, rxxi).subs(h ** 3 * u3xi1, rxxi1).subs(h ** 4 * u4xi, r3xi)\\\r\n#         .subs(h ** 4 * u4xi1, r3xi1)\r\n#     c8_expr = sol_get[7].subs(h * uxi, ri).subs(h * uxi1, ri1).subs(h ** 2 * uxxi, rxi) \\\r\n#         .subs(h ** 2 * uxxi1, rxi1).subs(h ** 3 * u3xi, rxxi).subs(h ** 3 * u3xi1, rxxi1).subs(h ** 4 * u4xi, r3xi)\\\r\n#         .subs(h ** 4 * u4xi1, r3xi1)\r\n#     c9_expr = sol_get[8].subs(h * uxi, ri).subs(h * uxi1, ri1).subs(h ** 2 * uxxi, rxi) \\\r\n#         .subs(h ** 2 * uxxi1, rxi1).subs(h ** 3 * u3xi, rxxi).subs(h ** 3 * u3xi1, rxxi1).subs(h ** 4 * u4xi, r3xi)\\\r\n#         .subs(h ** 4 * u4xi1, r3xi1)\r\n#     c10_expr = sol_get[9].subs(h * uxi, ri).subs(h * uxi1, ri1).subs(h ** 2 * uxxi, rxi) \\\r\n#         .subs(h ** 2 * uxxi1, rxi1).subs(h ** 3 * u3xi, rxxi).subs(h ** 3 * u3xi1, rxxi1).subs(h ** 4 * u4xi, r3xi)\\\r\n#         .subs(h ** 4 * u4xi1, r3xi1)\r\n#     print(\"c1 = {0}\".format(c1_expr))\r\n#     print(\"c2 = {0}\".format(c2_expr))\r\n#     print(\"c3 = {0}\".format(c3_expr))\r\n#     print(\"c4 = {0}\".format(c4_expr))\r\n#     print(\"c5 = {0}\".format(c5_expr))\r\n#     print(\"c6 = {0}\".format(c6_expr))\r\n#     print(\"c7 = {0}\".format(c7_expr))\r\n#     print(\"c8 = {0}\".format(c8_expr))\r\n#     print(\"c9 = {0}\".format(c9_expr))\r\n#     print(\"c10 = {0}\\n\".format(c10_expr))\r\n#\r\n#     # Set constrains\r\n#     ui = u.subs(x, 0)\r\n#\r\n#     ux = u.diff(x)\r\n#     uxi = ux.subs(x, 0)\r\n#\r\n#     uxx = ux.diff(x)\r\n#     uxxi = uxx.subs(x, 0)\r\n#\r\n#     u3x = uxx.diff(x)\r\n#     u3xi = u3x.subs(x, 0)\r\n#\r\n#     u4x = u3x.diff(x)\r\n#     u4xi = u4x.subs(x, 0)\r\n#\r\n#     u5x = u4x.diff(x)\r\n#     u5xi = u5x.subs(x, 0)\r\n#\r\n#     u6x = u5x.diff(x)\r\n#     u6xi = u6x.subs(x, 0)\r\n#\r\n#     u7x = u6x.diff(x)\r\n#     u7xi = u7x.subs(x, 0)\r\n#\r\n#     u8x = u7x.diff(x)\r\n#     u8xi = u8x.subs(x, 0)\r\n#\r\n#     u9x = u8x.diff(x)\r\n#     u9xi = u9x.subs(x, 0)\r\n#\r\n#     r = h * u.diff(x)\r\n#     ri = r.subs(x, 0)\r\n#\r\n#     rx = r.diff(x)\r\n#     rxi = rx.subs(x, 0)\r\n#\r\n#     rxx = rx.diff(x)\r\n#     rxxi = rxx.subs(x, 0)\r\n#\r\n#     r3x = rxx.diff(x)\r\n#     r3xi = r3x.subs(x, 0)\r\n#\r\n#     r4x = r3x.diff(x)\r\n#     r4xi = r4x.subs(x, 0)\r\n#\r\n#     r5x = r4x.diff(x)\r\n#     r5xi = r5x.subs(x, 0)\r\n#\r\n#     r6x = r5x.diff(x)\r\n#     r6xi = r6x.subs(x, 0)\r\n#\r\n#     r7x = r6x.diff(x)\r\n#     r7xi = r7x.subs(x, 0)\r\n#\r\n#     r8x = r7x.diff(x)\r\n#     r8xi = r8x.subs(x, 0)\r\n#\r\n#     uni = ui - a * tau * uxi + a ** 2 * tau ** 2 / 2 * uxxi - a ** 3 * tau ** 3 / 6 * u3xi + a ** 4 * tau ** 4 / 24 * u4xi \\\r\n#           - a ** 5 * tau ** 5 / 120 * u5xi + a ** 6 * tau ** 6 / 720 * u6xi - a ** 7 * tau ** 7 / 5040 * u7xi \\\r\n#           + a ** 8 * tau ** 8 / 40320 * u8xi - a ** 9 * tau ** 9 / 362880 * u9xi\r\n#\r\n#     rni = ri - a * tau * rxi + a ** 2 * tau ** 2 / 2 * rxxi - a ** 3 * tau ** 3 / 6 * r3xi + a ** 4 * tau ** 4 / 24 * r4xi \\\r\n#           - a ** 5 * tau ** 5 / 120 * r5xi + a ** 6 * tau ** 6 / 720 * r6xi - a ** 7 * tau ** 7 / 5040 * r7xi \\\r\n#           + a ** 8 * tau ** 8 / 40320 * r8xi\r\n#\r\n#     rxni = rxi - a * tau * rxxi + a ** 2 * tau ** 2 / 2 * r3xi - a ** 3 * tau ** 3 / 6 * r4xi \\\r\n#            + a ** 4 * tau ** 4 / 24 * r5xi - a ** 5 * tau ** 5 / 120 * r6xi + a ** 6 * tau ** 6 / 720 * r7xi \\\r\n#            - a ** 7 * tau ** 7 / 5040 * r8xi\r\n#\r\n#     rxxni = rxxi - a * tau * r3xi + a ** 2 * tau ** 2 / 2 * r4xi - a ** 3 * tau ** 3 / 6 * r5xi \\\r\n#             + a ** 4 * tau ** 4 / 24 * r6xi - a ** 5 * tau ** 5 / 120 * r7xi + a ** 6 * tau ** 6 / 720 * r8xi\r\n#\r\n#     r3xni = r3xi - a * tau * r4xi + a ** 2 * tau ** 2 / 2 * r5xi - a ** 3 * tau ** 3 / 6 * r6xi \\\r\n#             + a ** 4 * tau ** 4 / 24 * r7xi - a ** 5 * tau ** 5 / 120 * r8xi\r\n#\r\n#     uni = uni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr) \\\r\n#         .subs(c4, c4_expr).subs(c5, c5_expr).subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr)\\\r\n#         .subs(c10, c10_expr).subs(a * tau / h, nu)\r\n#\r\n#     rni = rni.subs(c2, c2_expr).subs(c3, c3_expr) \\\r\n#         .subs(c4, c4_expr).subs(c5, c5_expr).subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr)\\\r\n#         .subs(c10, c10_expr).subs(a * tau / h, nu)\r\n#\r\n#     rxni = rxni.subs(c2, c2_expr).subs(c3, c3_expr) \\\r\n#         .subs(c4, c4_expr).subs(c5, c5_expr).subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr)\\\r\n#         .subs(c10, c10_expr).subs(a * tau / h, nu) * h\r\n#\r\n#     rxxni = rxxni.subs(c2, c2_expr).subs(c3, c3_expr) \\\r\n#         .subs(c4, c4_expr).subs(c5, c5_expr).subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr)\\\r\n#         .subs(c10, c10_expr).subs(a * tau / h, nu) * h ** 2\r\n#\r\n#     r3xni = r3xni.subs(c2, c2_expr).subs(c3, c3_expr) \\\r\n#         .subs(c4, c4_expr).subs(c5, c5_expr).subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr)\\\r\n#         .subs(c10, c10_expr).subs(a * tau / h, nu) * h ** 3\r\n#\r\n#     print(\"uni = {0}\".format(simplify(uni)))\r\n#     print(\"rni = {0}\".format(simplify(rni)))\r\n#     print(\"rxni = {0}\".format(simplify(rxni)))\r\n#     print(\"rxxni = {0}\".format(simplify(rxxni)))\r\n#     print(\"r3xni = {0}\".format(simplify(r3xni)))\r\n\r\n\r\n# def get_derivative():\r\n#     t, x, y = symbols('t, x, y')\r\n#\r\n#     p = cos(2 * sqrt(2) * pi * t) * sin(2 * pi * x) * sin(2 * pi * y)\r\n#\r\n#     u = -1 / sqrt(2) * sin(2 * sqrt(2) * pi * t) * cos(2 * pi * x) * sin(2 * pi * y)\r\n#\r\n#     v = -1 / sqrt(2) * sin(2 * sqrt(2) * pi * t) * sin(2 * pi * x) * cos(2 * pi * y)\r\n#\r\n#     p_exp = exp(-(10 * (x ** 2 + (y + 0.7) ** 2)))\r\n#\r\n#     p_sin = 1 / pi * sin(pi * x) ** 2 * sin(pi * y) ** 2\r\n#\r\n#     rp = diff(p, x)\r\n#     ru = diff(u, x)\r\n#     rv = diff(v, x)\r\n#\r\n#     sp = diff(p, y)\r\n#     su = diff(u, y)\r\n#     sv = diff(v, y)\r\n#\r\n#     rp_exp = diff(p_exp, x)\r\n#     sp_exp = diff(p_exp, y)\r\n#\r\n#     rp_sin = diff(p_sin, x)\r\n#     sp_sin = diff(p_sin, y)\r\n#\r\n#     print(\"rp = {0}\\n\".format(rp))\r\n#     print(\"ru = {0}\\n\".format(ru))\r\n#     print(\"rv = {0}\\n\".format(rv))\r\n#\r\n#     print(\"sp = {0}\\n\".format(sp))\r\n#     print(\"su = {0}\\n\".format(su))\r\n#     print(\"sv = {0}\\n\".format(sv))\r\n#\r\n#     print(\"rp_exp = {0}\\n\".format(rp_exp))\r\n#     print(\"sp_exp = {0}\\n\".format(sp_exp))\r\n#\r\n#     print(\"rp_sin = {0}\\n\".format(rp_sin))\r\n#     print(\"sp_sin = {0}\\n\".format(sp_sin))\r\n\r\n# def two_dim_deltaP3():\r\n#     x, y, a, h, tau, nu, ui, ui1, ri, ri1, uxx, u3x, rx, rxx \\\r\n#         = symbols('x, y, a, h, tau, nu, ui, ui1, ri, ri1, uxx, u3x, rx, rxx')\r\n#\r\n#     c1, c2, c3, c4, c5, c6, c7, c8, c9, c10 = \\\r\n#         symbols('c1, c2, c3, c4, c5, c6, c7, c8, c9, c10')\r\n#\r\n#     phi_i_j1, phi_i1_j1, phi_i1_j, phi_i_j, r_i_j1, r_i_j, r_i1_j, s_i_j1, s_i_j, s_i1_j = \\\r\n#         symbols('phi_i_j1, phi_i1_j1, phi_i1_j, phi_i_j, r_i_j1, r_i_j, r_i1_j, s_i_j1, s_i_j, s_i1_j')\r\n#\r\n#     # p, u, v, rp, ru, rv, sp, su, sv = symbols('p, u, v, rp, ru, rv, sp, su, sv')\r\n#\r\n#     p = c1 + c2 * x + c3 * y + c4 * x * y + c5 * x ** 2 + c6 * y ** 2 + c7 * x ** 2 * y + c8 * x * y ** 2 \\\r\n#         + c9 * x ** 3 + c10 * y ** 3\r\n#\r\n#     u = c1 + c2 * x + c3 * y + c4 * x * y + c5 * x ** 2 + c6 * y ** 2 + c7 * x ** 2 * y + c8 * x * y ** 2 \\\r\n#         + c9 * x ** 3 + c10 * y ** 3\r\n#\r\n#     v = c1 + c2 * x + c3 * y + c4 * x * y + c5 * x ** 2 + c6 * y ** 2 + c7 * x ** 2 * y + c8 * x * y ** 2 \\\r\n#         + c9 * x ** 3 + c10 * y ** 3\r\n#\r\n#     # linear system of 10 equations\r\n#\r\n#     # eq01 = p.subs(x, 0).subs(y, h)\r\n#     # eq02 = p.subs(x, h).subs(y, h)\r\n#     # eq03 = p.subs(x, h).subs(y, 0)\r\n#     # eq04 = p.subs(x, 0).subs(y, 0)\r\n#     #\r\n#     # eq05 = p.diff(x).subs(x, 0).subs(y, h)\r\n#     # eq06 = p.diff(x).subs(x, h).subs(y, h)\r\n#     # eq07 = p.diff(x).subs(x, h).subs(y, 0)\r\n#     #\r\n#     # eq08 = p.diff(y).subs(x, 0).subs(y, h)\r\n#     # eq09 = p.diff(y).subs(x, h).subs(y, h)\r\n#     # eq10 = p.diff(y).subs(x, h).subs(y, 0)\r\n#\r\n#     eq01 = p.subs(x, -h).subs(y, 0)\r\n#     eq02 = p.subs(x, 0).subs(y, 0)\r\n#     eq03 = p.subs(x, 0).subs(y, -h)\r\n#     eq04 = p.subs(x, -h).subs(y, -h)\r\n#\r\n#     eq05 = p.diff(x).subs(x, -h).subs(y, 0)\r\n#     eq06 = p.diff(x).subs(x, 0).subs(y, 0)\r\n#     eq07 = p.diff(x).subs(x, 0).subs(y, -h)\r\n#\r\n#     eq08 = p.diff(y).subs(x, -h).subs(y, 0)\r\n#     eq09 = p.diff(y).subs(x, 0).subs(y, 0)\r\n#     eq10 = p.diff(y).subs(x, 0).subs(y, -h)\r\n#\r\n#     sol = linsolve([eq01 - phi_i1_j, eq02 - phi_i_j, eq03 - phi_i_j1, eq04 - phi_i1_j1, eq05 - r_i1_j, eq06 - r_i_j,\r\n#                     eq07 - r_i_j1, eq08 - s_i1_j, eq09 - s_i_j, eq10 - s_i_j1],\r\n#                    (c1, c2, c3, c4, c5, c6, c7, c8, c9, c10))\r\n#\r\n#     sol_get = next(iter(sol))\r\n#\r\n#     c1_expr = sol_get[0] #.subs(r_i_j1, r_i_j1 / h).subs(r_i1_j1, r_i1_j1 / h).subs(r_i1_j, r_i1_j / h)\\\r\n#        # .subs(s_i_j1, s_i_j1 / h).subs(s_i1_j1, s_i1_j1 / h).subs(s_i1_j, s_i1_j / h)\r\n#\r\n#     c2_expr = sol_get[1] #.subs(r_i_j1, r_i_j1 / h).subs(r_i1_j1, r_i1_j1 / h).subs(r_i1_j, r_i1_j / h)\\\r\n#        # .subs(s_i_j1, s_i_j1 / h).subs(s_i1_j1, s_i1_j1 / h).subs(s_i1_j, s_i1_j / h)\r\n#\r\n#     c3_expr = sol_get[2] #.subs(r_i_j1, r_i_j1 / h).subs(r_i1_j1, r_i1_j1 / h).subs(r_i1_j, r_i1_j / h)\\\r\n#        # .subs(s_i_j1, s_i_j1 / h).subs(s_i1_j1, s_i1_j1 / h).subs(s_i1_j, s_i1_j / h)\r\n#\r\n#     c4_expr = sol_get[3] #.subs(r_i_j1, r_i_j1 / h).subs(r_i1_j1, r_i1_j1 / h).subs(r_i1_j, r_i1_j / h)\\\r\n#        # .subs(s_i_j1, s_i_j1 / h).subs(s_i1_j1, s_i1_j1 / h).subs(s_i1_j, s_i1_j / h)\r\n#\r\n#     c5_expr = sol_get[4] #.subs(r_i_j1, r_i_j1 / h).subs(r_i1_j1, r_i1_j1 / h).subs(r_i1_j, r_i1_j / h)\\\r\n#        # .subs(s_i_j1, s_i_j1 / h).subs(s_i1_j1, s_i1_j1 / h).subs(s_i1_j, s_i1_j / h)\r\n#\r\n#     c6_expr = sol_get[5] #.subs(r_i_j1, r_i_j1 / h).subs(r_i1_j1, r_i1_j1 / h).subs(r_i1_j, r_i1_j / h)\\\r\n#         #.subs(s_i_j1, s_i_j1 / h).subs(s_i1_j1, s_i1_j1 / h).subs(s_i1_j, s_i1_j / h)\r\n#\r\n#     c7_expr = sol_get[6] #.subs(r_i_j1, r_i_j1 / h).subs(r_i1_j1, r_i1_j1 / h).subs(r_i1_j, r_i1_j / h)\\\r\n#        # .subs(s_i_j1, s_i_j1 / h).subs(s_i1_j1, s_i1_j1 / h).subs(s_i1_j, s_i1_j / h)\r\n#\r\n#     c8_expr = sol_get[7] #.subs(r_i_j1, r_i_j1 / h).subs(r_i1_j1, r_i1_j1 / h).subs(r_i1_j, r_i1_j / h)\\\r\n#         #.subs(s_i_j1, s_i_j1 / h).subs(s_i1_j1, s_i1_j1 / h).subs(s_i1_j, s_i1_j / h)\r\n#\r\n#     c9_expr = sol_get[8] #.subs(r_i_j1, r_i_j1 / h).subs(r_i1_j1, r_i1_j1 / h).subs(r_i1_j, r_i1_j / h)\\\r\n#         #.subs(s_i_j1, s_i_j1 / h).subs(s_i1_j1, s_i1_j1 / h).subs(s_i1_j, s_i1_j / h)\r\n#\r\n#     c10_expr = sol_get[9] #.subs(r_i_j1, r_i_j1 / h).subs(r_i1_j1, r_i1_j1 / h).subs(r_i1_j, r_i1_j / h)\\\r\n#         #.subs(s_i_j1, s_i_j1 / h).subs(s_i1_j1, s_i1_j1 / h).subs(s_i1_j, s_i1_j / h)\r\n#\r\n#     print(\"c1 = {0}\".format(c1_expr))\r\n#     print(\"c2 = {0}\".format(c2_expr))\r\n#     print(\"c3 = {0}\".format(c3_expr))\r\n#     print(\"c4 = {0}\".format(c4_expr))\r\n#     print(\"c5 = {0}\".format(c5_expr))\r\n#     print(\"c6 = {0}\".format(c6_expr))\r\n#     print(\"c7 = {0}\".format(c7_expr))\r\n#     print(\"c8 = {0}\".format(c8_expr))\r\n#     print(\"c9 = {0}\".format(c9_expr))\r\n#     print(\"c10 = {0}\\n\".format(c10_expr))\r\n#\r\n#     # first derivative in the x-direction\r\n#\r\n#     rp = p.diff(x)\r\n#     ru = u.diff(x)\r\n#     rv = v.diff(x)\r\n#\r\n#     # first derivative in the y-direction\r\n#\r\n#     sp = p.diff(y)\r\n#     su = u.diff(y)\r\n#     sv = v.diff(y)\r\n#\r\n#     # second and third derivative for p\r\n#\r\n#     p_xx = rp.diff(x)\r\n#     p_xy = rp.diff(y)\r\n#     p_yy = sp.diff(y)\r\n#\r\n#     p_3x = p_xx.diff(x)\r\n#     p_xxy = p_xx.diff(y)\r\n#     p_xyy = p_xy.diff(y)\r\n#     p_3y = p_yy.diff(y)\r\n#\r\n#     # second and third derivative for u\r\n#\r\n#     u_xx = ru.diff(x)\r\n#     u_xy = ru.diff(y)\r\n#     u_yy = su.diff(y)\r\n#\r\n#     u_3x = u_xx.diff(x)\r\n#     u_xxy = u_xx.diff(y)\r\n#     u_xyy = u_xy.diff(y)\r\n#     u_3y = u_yy.diff(y)\r\n#\r\n#     # second and third derivative for v\r\n#\r\n#     v_xx = rv.diff(x)\r\n#     v_xy = rv.diff(y)\r\n#     v_yy = sv.diff(y)\r\n#\r\n#     v_3x = v_xx.diff(x)\r\n#     v_xxy = v_xx.diff(y)\r\n#     v_xyy = v_xy.diff(y)\r\n#     v_3y = v_yy.diff(y)\r\n#\r\n#     # parameters values at the discrete point i\r\n#\r\n#     pi = p.subs(x, 0).subs(y, 0)\r\n#     ui = u.subs(x, 0).subs(y, 0)\r\n#     vi = v.subs(x, 0).subs(y, 0)\r\n#\r\n#     rpi = rp.subs(x, 0).subs(y, 0)  # first derivatives in the x-direction\r\n#     rui = ru.subs(x, 0).subs(y, 0)\r\n#     rvi = rv.subs(x, 0).subs(y, 0)\r\n#\r\n#     spi = sp.subs(x, 0).subs(y, 0)  # first derivatives in the y-direction\r\n#     sui = su.subs(x, 0).subs(y, 0)\r\n#     svi = sv.subs(x, 0).subs(y, 0)\r\n#\r\n#     p_xxi = p_xx.subs(x, 0).subs(y, 0)  # second derivatives\r\n#     print(\"p_xx = {0}\\n\".format(p_xxi.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(c5, c5_expr)\\\r\n#        .subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr).subs(c10, c10_expr)))\r\n#     p_xyi = p_xy.subs(x, 0).subs(y, 0)\r\n#     print(\"p_xy = {0}\\n\".format(\r\n#         p_xyi.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(c5, c5_expr) \\\r\n#         .subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr).subs(c10, c10_expr)))\r\n#     p_yyi = p_yy.subs(x, 0).subs(y, 0)\r\n#\r\n#     u_xxi = u_xx.subs(x, 0).subs(y, 0)\r\n#     u_xyi = u_xy.subs(x, 0).subs(y, 0)\r\n#     u_yyi = u_yy.subs(x, 0).subs(y, 0)\r\n#\r\n#     v_xxi = v_xx.subs(x, 0).subs(y, 0)\r\n#     v_xyi = v_xy.subs(x, 0).subs(y, 0)\r\n#     v_yyi = v_yy.subs(x, 0).subs(y, 0)\r\n#\r\n#     p_3xi = p_3x.subs(x, 0).subs(y, 0)  # third derivatives\r\n#\r\n#     p_xxyi = p_xxy.subs(x, 0).subs(y, 0)\r\n#     p_xyyi = p_xyy.subs(x, 0).subs(y, 0)\r\n#     p_3yi = p_3y.subs(x, 0).subs(y, 0)\r\n#\r\n#     u_3xi = u_3x.subs(x, 0).subs(y, 0)\r\n#     u_xxyi = u_xxy.subs(x, 0).subs(y, 0)\r\n#     u_xyyi = u_xyy.subs(x, 0).subs(y, 0)\r\n#     u_3yi = u_3y.subs(x, 0).subs(y, 0)\r\n#\r\n#     v_3xi = v_3x.subs(x, 0).subs(y, 0)\r\n#     v_xxyi = v_xxy.subs(x, 0).subs(y, 0)\r\n#     v_xyyi = v_xyy.subs(x, 0).subs(y, 0)\r\n#     v_3yi = v_3y.subs(x, 0).subs(y, 0)\r\n#\r\n#     pni = pi - tau * (rui + svi) + tau**2 / 2 * (p_xxi + p_yyi) - tau**3 / 6 * (u_3xi + u_xyyi + v_xxyi + v_3yi)\r\n#\r\n#     uni = ui - tau * rpi + tau**2 / 2 * (u_xxi + v_xyi) - tau**3 / 6 * (p_3xi + p_xyyi)\r\n#\r\n#     vni = vi - tau * spi + tau**2 / 2 * (u_xyi + v_yyi) - tau**3 / 6 * (p_xxyi + p_3yi)\r\n#\r\n#     # derivatives at the x-direction\r\n#\r\n#     rpni = rpi - tau * (u_xxi + v_xyi) + tau**2 / 2 * (p_3xi + p_xyyi)\r\n#\r\n#     runi = rui - tau * p_xxi + tau ** 2 / 2 * (u_3xi + v_xxyi)\r\n#\r\n#     rvni = rvi - tau * p_xyi + tau**2 / 2 * (u_xxyi + v_xyyi)\r\n#\r\n#     # derivatives at the y-direction\r\n#\r\n#     spni = spi - tau * (u_xyi + v_yyi) + tau**2 / 2 * (p_xxyi + p_3yi)\r\n#\r\n#     suni = sui - tau * p_xyi + tau**2 / 2 * (u_xxyi + v_xyyi)\r\n#\r\n#     svni = svi - tau * p_yyi + tau**2 / 2 * (u_xyyi + v_3yi)\r\n#\r\n#     _pni = pni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(c5, c5_expr)\\\r\n#        .subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr).subs(c10, c10_expr)\r\n#\r\n#     _uni = uni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(c5, c5_expr)\\\r\n#        .subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr).subs(c10, c10_expr).subs(tau / h, nu)\r\n#\r\n#     _vni = vni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(c5, c5_expr)\\\r\n#         .subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr).subs(c10, c10_expr).subs(tau / h, nu)\r\n#\r\n#     _rpni = rpni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(c5, c5_expr)\\\r\n#        .subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr).subs(c10, c10_expr).subs(tau / h, nu)\r\n#\r\n#     _runi = runi.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(c5, c5_expr)\\\r\n#        .subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr).subs(c10, c10_expr).subs(tau / h, nu)\r\n#\r\n#     _rvni = rvni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(c5, c5_expr)\\\r\n#         .subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr).subs(c10, c10_expr).subs(tau / h, nu)\r\n#\r\n#     _spni = spni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(c5, c5_expr)\\\r\n#        .subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr).subs(c10, c10_expr).subs(tau / h, nu)\r\n#\r\n#     _suni = suni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(c5, c5_expr)\\\r\n#        .subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr).subs(c10, c10_expr).subs(tau / h, nu)\r\n#\r\n#     _svni = svni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(c4, c4_expr).subs(c5, c5_expr)\\\r\n#        .subs(c6, c6_expr).subs(c7, c7_expr).subs(c8, c8_expr).subs(c9, c9_expr).subs(c10, c10_expr).subs(tau / h, nu)\r\n#\r\n#     print(simplify(_pni))\r\n#     # print(simplify(_uni))\r\n#     # print(simplify(_vni))\r\n#     print(simplify(_rpni))\r\n#     # print(simplify(_runi))\r\n#     # print(simplify(_rvni))\r\n#     print(simplify(_spni))\r\n#     # print(simplify(_suni))\r\n#     # print(simplify(_svni))\r\n\r\n# symbolCIP(3)\r\nsymbolDeltaP()", "meta": {"hexsha": "dd31d0de5ea9db40d63d8fbeaeb43bb477e0d8fa", "size": 35574, "ext": "py", "lang": "Python", "max_stars_repo_path": "symb_interp.py", "max_stars_repo_name": "iCFD/CIP-symbolic", "max_stars_repo_head_hexsha": "407423f8a8e3257d096ba7a3caa328f30c69eb91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "symb_interp.py", "max_issues_repo_name": "iCFD/CIP-symbolic", "max_issues_repo_head_hexsha": "407423f8a8e3257d096ba7a3caa328f30c69eb91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "symb_interp.py", "max_forks_repo_name": "iCFD/CIP-symbolic", "max_forks_repo_head_hexsha": "407423f8a8e3257d096ba7a3caa328f30c69eb91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2105263158, "max_line_length": 131, "alphanum_fraction": 0.4967954124, "include": true, "reason": "import numpy,from sympy", "num_tokens": 15773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399034724604, "lm_q2_score": 0.8824278772763471, "lm_q1q2_score": 0.8561667384700111}}
{"text": "#!/usr/bin/env python\n\nimport numpy as np\nfrom scipy.integrate import ode\n\n\n#\n# f[0] = d theta1/dt = omega1\n# f[1] = d theata2/dt = omega2\n# f[2] = d omega1/dt = -(g/l1)*theta1 - k*(theta1 - theta2)\n# f[3] = d omega2/dt = -(g/l2)*theta2 - k*(theta2 - theta1)\n#\n# y[0] = theta1\n# y[1] = theta2\n# y[2] = omega1\n# y[3] = omega2\n#\ndef functions(t, y, l1, l2, k):\n    g = 9.81\n    return [\n        y[2],\n        y[3],\n        -(g/l1)*y[0] - k*(y[0] - y[1]),\n        -(g/l2)*y[1] - k*(y[1] - y[0])\n    ]\n\n\ndef jacobian(t, y, l1, l2, k):\n    g = 9.81\n    return [\n        [0.0,                  0.0,  1.0,   0.0],\n        [0.0,                  0.0,  0.0,   1.0],\n        [-(g/l1) - k,            k,  0.0,   0.0],\n        [k,            -(g/l2) - k,  0.0,   0.0]\n    ]\n\n\ndef init_integrator(theta0_1, theta0_2, t0=0.0, l1=1.0, l2=1.0, k=0.1):\n    integrator = ode(functions, jacobian).set_integrator('dopri5',\n                                                         atol=1.0e-6,\n                                                         rtol=0.0)\n    integrator.set_initial_value([theta0_1, theta0_2, 0.0, 0.0], t0)\n    integrator.set_f_params(l1, l2, k)\n    integrator.set_jac_params(l1, l2, k)\n    return integrator\n\nif __name__ == '__main__':\n    from argparse import ArgumentParser\n    arg_parser = ArgumentParser(description='solved coupled pendulums')\n    arg_parser.add_argument('--theta0_1', type=float, default=0.0,\n                            help='initial theta of first pendulum')\n    arg_parser.add_argument('--theta0_2', type=float, default=0.0,\n                            help='initial theta of second pendulum')\n    arg_parser.add_argument('--l1', type=float, default=1.0,\n                            help='length of first pendulum')\n    arg_parser.add_argument('--l2', type=float, default=1.0,\n                            help='length of second pendulum')\n    arg_parser.add_argument('--k', type=float, default=0.5,\n                            help=\"Hooke's constant\")\n    arg_parser.add_argument('--t_max', type=float, default=10*2*np.pi,\n                            help='maximum time')\n    arg_parser.add_argument('--delta_t', type=float, default=0.01,\n                            help='delta t')\n    options = arg_parser.parse_args()\n    integrator = init_integrator(options.theta0_1, options.theta0_2, t0=0.0,\n                                 l1=options.l1, l2=options.l2, k=options.k)\n    while integrator.successful() and integrator.t < options.t_max:\n        integrator.integrate(integrator.t + options.delta_t)\n        print('{0:.3f}\\t{1:.5f}\\t{2:.5f}'.format(integrator.t,\n                                                 integrator.y[0],\n                                                 integrator.y[1]))\n", "meta": {"hexsha": "d61720e275b923b5c96ffccf78afd2e65f223443", "size": 2727, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/Numpy/coupled_pendulums.py", "max_stars_repo_name": "Gjacquenot/training-material", "max_stars_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "Python/Numpy/coupled_pendulums.py", "max_issues_repo_name": "Gjacquenot/training-material", "max_issues_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "Python/Numpy/coupled_pendulums.py", "max_forks_repo_name": "Gjacquenot/training-material", "max_forks_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 37.875, "max_line_length": 76, "alphanum_fraction": 0.5100843418, "include": true, "reason": "import numpy,from scipy", "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399094961359, "lm_q2_score": 0.8824278664544911, "lm_q1q2_score": 0.8561667332856738}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nw = np.array([0.15, 0.6])\neta = 0.01\n\nprint(w, eta)\n\nall_weights = []\nenergy = []\n\nwhile (w[0]+w[1]) < 1 and w[0] > 0 and w[1] > 0 :\n    f_w = - np.log(1 - w[0] - w[1]) - np.log(w[0]) - np.log(w[1])\n    energy.append(f_w)\n    \n    all_weights.append(w)\n    \n    grad = np.array([(1 / (1-w[0]-w[1])) - (1 / w[0]), (1 / (1-w[0]-w[1])) - (1 / w[1])])\n    \n    delta_w = eta * grad\n    new_w = w - delta_w\n    \n    if np.linalg.norm(w - new_w) < 0.001:\n        break\n    else:\n        w = new_w\n     \nall_weights = np.array(all_weights)\n\nplt.plot(all_weights[:, 0], all_weights[:, 1], '-o')\nplt.xlabel(\"X-axis\")\nplt.ylabel(\"Y-axis\")\nplt.title(\"Gradient Descent Weight Updates\")\nplt.show()\n\nplt.plot(range(len(energy)), energy)\nplt.xlabel(\"Number of Iterations\")\nplt.ylabel(\"Energy f(w)\")\nplt.title(\"Changes in Energy\")\nplt.show()\n\n\n\nw = np.array([0.15, 0.6])\neta = 0.01\n\nprint(f\"Initial Weight is: {w}\\nLearning Rate is: {eta}\")\n\nall_weights = []\nenergy = []\n\nH = np.empty((2, 2))\n\n\nwhile (w[0]+w[1]) < 1 and w[0] > 0 and w[1] > 0 :\n    f_w = - np.log(1 - w[0] - w[1]) - np.log(w[0]) - np.log(w[1])\n    energy.append(f_w)\n    \n    all_weights.append(w)\n    \n    grad = np.array([(1 / (1-w[0]-w[1])) - (1 / w[0]), (1 / (1-w[0]-w[1])) - (1 / w[1])])\n    \n    H[0,:] = [(1 / (1-w[0]-w[1])**2) + (1 / w[0]**2),\n              (1 / (1-w[0]-w[1])**2)]\n    H[1,:] = [(1 / (1-w[0]-w[1])**2),\n              (1 / (1-w[0]-w[1])**2) + (1 / w[1]**2)]\n    \n    delta_w = eta * np.matmul(np.linalg.inv(H), grad)\n    new_w = w - delta_w\n    \n    if np.linalg.norm(w - new_w) < 0.001:\n        break\n    else:\n        w = new_w\n        \n        \nall_weights = np.array(all_weights)\nplt.plot(all_weights[:, 0], all_weights[:, 1], '-o')\nplt.xlabel(\"X-axis\")\nplt.ylabel(\"Y-axis\")\nplt.title(\"Newton's Method Weight Updates\")\nplt.show()\n\nplt.plot(range(len(energy)), energy)\nplt.xlabel(\"Number of Iterations\")\nplt.ylabel(\"Energy f(w)\")\nplt.title(\"Changes in Energy for Newton's Method\")\nplt.show()", "meta": {"hexsha": "a5ed43b5734d5f4f8485c15ea9fe0ca5a7fddbac", "size": 2021, "ext": "py", "lang": "Python", "max_stars_repo_path": "gd_newtons.py", "max_stars_repo_name": "yashchitre03/Gradient-Descent-and-Newton-s-Method", "max_stars_repo_head_hexsha": "ee3a5d8c1a5fb279a91ef15843b4544c49f400d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gd_newtons.py", "max_issues_repo_name": "yashchitre03/Gradient-Descent-and-Newton-s-Method", "max_issues_repo_head_hexsha": "ee3a5d8c1a5fb279a91ef15843b4544c49f400d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gd_newtons.py", "max_forks_repo_name": "yashchitre03/Gradient-Descent-and-Newton-s-Method", "max_forks_repo_head_hexsha": "ee3a5d8c1a5fb279a91ef15843b4544c49f400d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9659090909, "max_line_length": 89, "alphanum_fraction": 0.5279564572, "include": true, "reason": "import numpy", "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399094961359, "lm_q2_score": 0.8824278649085118, "lm_q1q2_score": 0.8561667317857029}}
{"text": "# -*- coding: utf-8 -*-\nimport numpy as np\n\n\ndef h(x, theta):\n    return 1 / (1 + np.exp(-np.dot(x, theta)))\n\n\ndef cost(x, y, theta):\n    _h = h(x, theta)\n    if y == 1:\n        return -np.log(_h)\n    else:\n        return -np.log(1 - _h)\n\n\ndef J(X, Y, theta):\n    m, n = np.shape(X)\n    loss = 0\n    for k in range(m):\n        loss += cost(X[k], Y[k], theta)\n    return loss / m\n\n\ndef logistic_gd(X, Y, alpha=0.01, epsilon=1e-6, trace=True):\n    m = len(X)\n    _X = np.column_stack((np.ones(m), X))\n    m, n = np.shape(_X)\n    theta, j1, cnt = np.ones(n), 0, 0\n    Xt = _X.T\n\n    while True:\n        loss = h(_X, theta) - Y\n        gradient = np.dot(Xt, loss) / m\n        theta -= alpha * gradient\n\n        j = J(_X, Y, theta)\n\n        if trace:\n            print(\"[ Epoch {0} ] theta = {1}, loss = {2}, error = {3})\".format(\n                cnt, theta, loss, j))\n\n        if abs(j - j1) < epsilon:\n            break\n        else:\n            j1 = j\n\n        cnt += 1\n    return theta\n", "meta": {"hexsha": "7059d3fa07ea8cc763a673f8883107ca66fd4652", "size": 985, "ext": "py", "lang": "Python", "max_stars_repo_path": "03-algorithms/02-optimization/codebase/gradient_descent/logistic_gd.py", "max_stars_repo_name": "jameszhan/notes-ml", "max_stars_repo_head_hexsha": "c633d04e5443eab71bc3b27fff89d57b89d1786c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "03-algorithms/02-optimization/codebase/gradient_descent/logistic_gd.py", "max_issues_repo_name": "jameszhan/notes-ml", "max_issues_repo_head_hexsha": "c633d04e5443eab71bc3b27fff89d57b89d1786c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "03-algorithms/02-optimization/codebase/gradient_descent/logistic_gd.py", "max_forks_repo_name": "jameszhan/notes-ml", "max_forks_repo_head_hexsha": "c633d04e5443eab71bc3b27fff89d57b89d1786c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7, "max_line_length": 79, "alphanum_fraction": 0.4629441624, "include": true, "reason": "import numpy", "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399043329856, "lm_q2_score": 0.8824278664544912, "lm_q1q2_score": 0.8561667287295661}}
{"text": "import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport numpy.linalg as LA\r\n\r\ndef lin_lsq(x,y):\r\n    \"\"\"\r\n    This function returns the coefficients of the linear regression AND the corresponding linear polyonomial\r\n    of the given input data, x and y, in row or column vector form. It implements the linear version of the Method \r\n    of Least Squares. It also displays a table where each row contains the x and y coordinates of the data, the \r\n    linear function of the method of LSQ evaluated at that point and the absolute error of the best-fit linear \r\n    function and the data. We also display the total squared error at the end.\r\n    \"\"\"\r\n    n = np.prod(x.shape)\r\n    x = x.reshape(n,1) #if given otherwise, we turn x and y vectors to column vectors\r\n    y = y.reshape(n,1)\r\n    s_x = np.sum(x); s_xx = np.sum(x**2); s_y = np.sum(y); s_xy = np.sum(x*y)\r\n    S = np.array([[s_xx, s_x], [s_x, 4]], float)\r\n    d = np.array([s_xy, s_y], float)\r\n    try:\r\n        S_inv = LA.inv(S) # if LA.det(S)=0 then a LinAlgError exception will be raised\r\n    except LinAlgError:\r\n        print(\"\"\"With the given data, the system of normal equations of the Method of LSQ, does not have or \r\n                 has infinite solutions because the coefficient matrix, S, is singular, i.e. it doesnt have an inverse.\"\"\")\r\n        return None\r\n    else:\r\n        sol = LA.solve(S,d)\r\n        a = sol[0]; b = sol[1]\r\n        g = np.poly1d([a,b])\r\n        g_x = np.polyval(g,x).reshape(n,1)\r\n        err = y-g_x\r\n        print('|    x    |    y    |   g(x)  |   y-g(x) | \\n ----------------------------------------')\r\n        table = np.concatenate((x, y, g_x, err), axis=1)\r\n        for (x_i, y_i, g_xi, err_i) in table:\r\n            print(f'|  {x_i:5.2f}  |  {y_i:5.2f}  |  {g_xi:5.2f}  |  {err_i:6.2f}  |')\r\n        print(f\"Also the total squared error is {sum(err**2)[0]:.2f} \\n\")\r\n        return (a,b), g\r\n\r\n\r\nx = np.array([1, 3, 5, 7], int)\r\ny = np.array([2.5, 3.5, 6.35, 8.1], float)\r\n(a,b), g = lin_lsq(x,y)\r\nprint(f\"The coefficients of the linear polyonomial of the Method of LSQ are: a = {a:.2f} and b = {b:.2f}\")\r\nprint(g)\r\nt = np.linspace(0,10, num=1000)\r\ng_t = g(t)\r\nprint(g_t)\r\n\r\n# Creating the plot and editing some of its attributes for clarity. We will just copy and paste them for future use.\r\n# We also assign every modification to our plot to a dummy/garbage collecting variable; '_' to prevent unwanted outputs\r\n\r\nplt.figure(figsize=(10,5))\r\nplt.scatter(x, y , marker='*', c='red', s=80, label='Our Data')\r\nplt.plot(t, g_t, c='blue', linewidth='2.0', label=r'$g(x)=ax+b$')\r\nplt.xlabel('x', fontsize=14)\r\nplt.ylabel('y', fontsize=14)\r\nplt.grid(True)\r\naxes = plt.gca() #gca stands for get current axes\r\naxes.set_xlim([-0.5,10])\r\naxes.set_ylim([-0.5,10])\r\nplt.rcParams['xtick.labelsize']=18\r\nplt.rcParams['ytick.labelsize']=18 \r\nplt.legend(loc='best', fontsize=14) #Sets the legend box at the best location\r\nplt.axhline(0, color='black', lw=2)\r\nplt.axvline(0, color='black', lw=2)\r\n\r\nplt.show()\r\n\r\n", "meta": {"hexsha": "e9fb4546fd86561bfa825df875b7c18f1009d2c0", "size": 3006, "ext": "py", "lang": "Python", "max_stars_repo_path": "test.py", "max_stars_repo_name": "marandmath/Least-Squares-Method-Notes", "max_stars_repo_head_hexsha": "7013957361f4dc2649da9a4f3ce722346226dff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-23T19:39:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T19:39:58.000Z", "max_issues_repo_path": "test.py", "max_issues_repo_name": "marandmath/Least-Squares-Method-Notes", "max_issues_repo_head_hexsha": "7013957361f4dc2649da9a4f3ce722346226dff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test.py", "max_forks_repo_name": "marandmath/Least-Squares-Method-Notes", "max_forks_repo_head_hexsha": "7013957361f4dc2649da9a4f3ce722346226dff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2058823529, "max_line_length": 124, "alphanum_fraction": 0.6144377911, "include": true, "reason": "import numpy", "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812318188365, "lm_q2_score": 0.8840392878563336, "lm_q1q2_score": 0.8560870545505633}}
{"text": "# --------------\n# Code starts here\n\nimport numpy as np\n\n# Code starts here\n\n# Adjacency matrix\nadj_mat = np.array([[0,0,0,0,0,0,1/3,0],\n                   [1/2,0,1/2,1/3,0,0,0,0],\n                   [1/2,0,0,0,0,0,0,0],\n                   [0,1,0,0,0,0,0,0],\n                  [0,0,1/2,1/3,0,0,1/3,0],\n                   [0,0,0,1/3,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,1,1/3,0]])\n\n# Compute eigenvalues and eigencevectrs\neigenvalues,eigencevectors=np.linalg.eig(adj_mat)\n\n# Eigen vector corresponding to 1\neigen_1=abs(eigencevectors[:,0])/(np.linalg.norm(eigencevectors[:,0],1))\n\nprint(eigen_1)\n# most important page\npage=int(np.where(eigen_1 == eigen_1.max())[0])+1\n#page=eigen_1.where()\nprint(page)\n# Code ends here\n\n\n# --------------\n# Code starts here\n\n# Initialize stationary vector I\ninit_I=np.array([1,0,0,0,0,0,0,0]);\nprint(init_I)\nfor i in range(10):\n    init_I=abs(np.dot(adj_mat, init_I))/(np.linalg.norm(init_I,1))\nprint(init_I)\npower_page = np.where(np.max(init_I) == init_I)[0][0] + 1\n\nprint(power_page)\n# Perform iterations for power method\n\n\n\n\n# Code ends here\n\n\n# --------------\n# Code starts here\n\n# New Adjancency matrix\n# New Adjancency matrix\nnew_adj_mat = np.array([[0,0,0,0,0,0,0,0],\n                   [1/2,0,1/2,1/3,0,0,0,0],\n                  [1/2,0,0,0,0,0,0,0],\n                   [0,1,0,0,0,0,0,0],\n                   [0,0,1/2,1/3,0,0,1/2,0],\n                   [0,0,0,1/3,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,1,1/2,0]])\n\n# Initialize stationary vector I\nnew_init_I =np.array([1,0,0,0,0,0,0,0]);\n\n# Perform iterations for power method\nfor i in range(10):\n    new_init_I=abs(np.dot(new_adj_mat, new_init_I))/(np.linalg.norm(new_init_I,1))\n\nprint(new_init_I)\n\n\n# Code ends here\n\n\n# --------------\n# Alpha value\nalpha = 0.85\n\n# Code starts here\n\n# Modified adjancency matrix\nn=len(new_adj_mat)\nl=np.ones(new_adj_mat.shape).astype(float)\nG=np.dot(alpha,new_adj_mat)+np.dot((1-alpha)*(1/n),l)\n# Initialize stationary vector I\nfinal_init_I=np.array([1,0,0,0,0,0,0,0])\n# Perform iterations for power method\nfor i in range(1000):\n    final_init_I=abs(np.dot(G, final_init_I))/(np.linalg.norm(final_init_I,1))\nprint(final_init_I)\n\n# Code ends here\n\n\n", "meta": {"hexsha": "e12a9ba34b22965f5227ef199706c1492107fc22", "size": 2272, "ext": "py", "lang": "Python", "max_stars_repo_path": "PageRank-Calculation-using-Power-and-Eigen-formulae/code.py", "max_stars_repo_name": "kaushik0033/ga-learner-dsmp-repo", "max_stars_repo_head_hexsha": "def2e7ac05274de8e3f2173b3ce35c6c55362c91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PageRank-Calculation-using-Power-and-Eigen-formulae/code.py", "max_issues_repo_name": "kaushik0033/ga-learner-dsmp-repo", "max_issues_repo_head_hexsha": "def2e7ac05274de8e3f2173b3ce35c6c55362c91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PageRank-Calculation-using-Power-and-Eigen-formulae/code.py", "max_forks_repo_name": "kaushik0033/ga-learner-dsmp-repo", "max_forks_repo_head_hexsha": "def2e7ac05274de8e3f2173b3ce35c6c55362c91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9494949495, "max_line_length": 82, "alphanum_fraction": 0.5748239437, "include": true, "reason": "import numpy", "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812290812827, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.8560870491719081}}
{"text": "# Implementaion of k-Means Clustering algo for credit card fraud detection\n# https://github.com/llSourcell/k_means_clustering\n# Marker info - https://matplotlib.org/api/markers_api.html\n\nimport sys\nfrom pprint import pprint\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#np.random.seed(1)\ndatapath = 'k_means_clustering-master/durudataset.txt'\nno_of_clusters = 2\n\ndef data_process(datapath):\n    # preprocess the data\n    data = np.loadtxt(datapath)\n    num_rows, num_features = data.shape\n    \n    return data, num_rows, num_features\n\ndef plot(centroids, cluster_points, test_cluster={}):\n    # Plot the clustered datapoints and their centroid\n    colors = ['r', 'g', 'm', 'c', 'y', 'w']\n    fig, ax = plt.subplots()\n\n    for key in cluster_points.keys():\n        for point in cluster_points[key]:\n            ax.plot(point[0], point[1], (colors[key] + 'o'))\n\n    if test_cluster:\n        for key in test_cluster.keys():\n            for point in test_cluster[key]:\n                ax.plot(point[0], point[1], (colors[key] + 's'))\n        \n    for centroid in centroids:\n        ax.plot(centroid[0], centroid[1], 'ko')     # black dot\n    plt.show()\n\ndef euclidean(v):\n    # returns norm of a vector/matrix\n    return np.linalg.norm(v)\n\ndef clustering(data, belongs_to, k):\n    # returns k clusters of data points\n    cluster_points = {}\n    for i in range(k):\n        cluster_points[i] = []\n    for i, value in enumerate(belongs_to):\n        cluster_points[value].append(data[i])\n\n    return cluster_points\n\ndef kmeans(data, num_rows, num_features, k):\n    # k-Means algorithm\n    rand_no = np.random.choice(num_rows, k)\n    new_centroids = [data[i] for i in rand_no]\n    belongs_to = list(np.zeros(num_rows))\n    error = 1 \n    iterator = 0\n    \n    while error > 0:\n        centroids = new_centroids\n        for i, row in enumerate(data):\n            distance = []\n            for centroid in centroids:\n                distance.append(euclidean(row - centroid))\n            centroid_no = np.argmin(distance)\n            belongs_to[i] = centroid_no\n        \n        # calculate no. of datapoints in each cluster\n        # by calculating the frequency of items in belongs_to list\n        d = {x: belongs_to.count(x) for x in belongs_to}\n        cluster_counter = d.values()\n        \n        tmp_centroids = np.zeros((k, num_features))\n        for i, row in enumerate(data):\n            tmp_centroids[belongs_to[i]] += row\n        tmp_centroids = [tmp_centroids[i]/float(cluster_counter[i]) for i in range(k)]\n\n        new_centroids = tmp_centroids\n        sub = np.subtract(new_centroids, centroids)\n        error = euclidean(sub)\n        iterator += 1\n        new_centroids = [np.ndarray.tolist(i) for i in new_centroids]\n    \n    cluster_points = clustering(data, belongs_to, k)\n\n    return new_centroids, cluster_points, iterator\n\ndef inference(test_data, centroids):\n    # cluster new data points\n    belongs_to = list(np.zeros(test_data.shape[0]))\n    \n    for i, data in enumerate(test_data):\n        distance = []\n        for centroid in centroids:\n            distance.append(euclidean(data - centroid))\n        belongs_to[i] = np.argmin(distance)\n\n    return belongs_to\n\ndef main():\n    data, num_rows, num_features = data_process(datapath)\n    centroids, cluster_points, iterations = kmeans(data, num_rows, num_features, no_of_clusters)\n    \n    # Testing\n    test_data = np.array([[1.8,1.8], [0.2,0.2], [0.25,1.5]])\n    test_belongs = inference(test_data, centroids)\n    test_cluster = clustering(test_data, test_belongs, no_of_clusters)\n\n    # Graph plot\n    print \"Centroid of clusters: \"\n    pprint(centroids)\n    print \"No. of iterations: \", iterations\n    plot(centroids, cluster_points, test_cluster)\n\nif __name__ == '__main__':\n    main()\n\n\n'''\nResult-\nCentroid of clusters: \n[[1.5805824656617171, 1.5689741160857174],\n [0.2233106749885314, 0.28960446247509586]]\nNo. of iterations:  3\n'''", "meta": {"hexsha": "6376ba7324609540c64227479897c737aec75215", "size": 3914, "ext": "py", "lang": "Python", "max_stars_repo_path": "K-Means_Clustering/mycode.py", "max_stars_repo_name": "DillipKS/The-Math-of-Intelligence-course", "max_stars_repo_head_hexsha": "fc0f33e638fdbd05e93d54d38ed8493808f6ec74", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "K-Means_Clustering/mycode.py", "max_issues_repo_name": "DillipKS/The-Math-of-Intelligence-course", "max_issues_repo_head_hexsha": "fc0f33e638fdbd05e93d54d38ed8493808f6ec74", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "K-Means_Clustering/mycode.py", "max_forks_repo_name": "DillipKS/The-Math-of-Intelligence-course", "max_forks_repo_head_hexsha": "fc0f33e638fdbd05e93d54d38ed8493808f6ec74", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-08T07:58:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-08T07:58:13.000Z", "avg_line_length": 30.8188976378, "max_line_length": 96, "alphanum_fraction": 0.6502299438, "include": true, "reason": "import numpy", "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.963230536035447, "lm_q2_score": 0.8887587824432528, "lm_q1q2_score": 0.8560795984190256}}
{"text": "\"\"\"\n                        Eigendecomposition\nEigenvalues and eigenvectors are easy to find with Python and NumPy. Remember,\nan eigenvector of a square matrix  A  is a nozero vector  v  such that multiplication by  A\nalters only the scale of  v\n                                Av=λv\nThe scalar  λ  is known as the eigenvalue corresponding to this eigenvector.\n \"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.cm as cm\n\n# find the eigenvalues and eigenvectors for a simple square matrix\nA = np.diag(np.arange(1, 4))\n\"\"\"\n[[1 0 0]\n [0 2 0]\n [0 0 3]]\n\"\"\"\n\neigenvalues, eigenvectors = np.linalg.eig(A)\n\"\"\"\nEigenvalue's: [1. 2. 3.]\nEigenvectors:[[1. 0. 0.]\n              [0. 1. 0.]\n              [0. 0. 1.]]\n\"\"\"\n\n# the eigenvalue w[i] corresponds to the eigenvector v[:, i]\nprint('Eigenvalue: {}'.format(eigenvalues[1]))\nprint('Eigenvector: {}'.format(eigenvectors[:, 1]))\n\"\"\"\nEigenvalue: 2.0\nEigenvector: [0. 1. 0.]\n\"\"\"\n\n# verify eigendecomposition - should return original matrix\nmatrix = np.matmul(np.diag(eigenvalues), np.linalg.inv(eigenvectors))\noutput = np.matmul(eigenvectors, matrix).astype(np.int)\n\"\"\"\n[[1 0 0]\n [0 2 0]\n [0 0 3]]\n\"\"\"\n\n# plot the eigenvectors\norigin = [0,0,0]\n\nfig = plt.figure(figsize=(18,10))\nfig.suptitle('Effects of Eigenvalues and Eigenvectors')\nax1 = fig.add_subplot(121, projection='3d')\n\nax1.quiver(origin, origin, origin, eigenvectors[0, :], eigenvectors[1, :], eigenvectors[2, :], color = 'k')\nax1.set_xlim([-3, 3])\nax1.set_ylim([-3, 3])\nax1.set_zlim([-3, 3])\nax1.set_xlabel('X axis')\nax1.set_ylabel('Y axis')\nax1.set_zlabel('Z axis')\nax1.view_init(15, 30)\nax1.set_title(\"Before Multiplication\")\n\n# multiply original matrix by eigenvectors\nnew_eig = np.matmul(A, eigenvectors)\nax2 = plt.subplot(122, projection='3d')\n\n# plot the new vectors\nax2.quiver(origin, origin, origin, new_eig[0, :], new_eig[1, :], new_eig[2, :], color = 'k')\n\n# plot the eigenvalues for each vector (the amount the vector should be scaled by)\nax2.plot((eigenvalues[0]*eigenvectors[0]), (eigenvalues[1]*eigenvectors[1]), (eigenvalues[2]*eigenvectors[2]), 'rX')\nax2.set_title(\"After Multiplication\")\nax2.set_xlim([-3, 3])\nax2.set_ylim([-3, 3])\nax2.set_zlim([-3, 3])\nax2.set_xlabel('X axis')\nax2.set_ylabel('Y axis')\nax2.set_zlabel('Z axis')\nax2.view_init(15, 30)\n\n# check the png file for plot\nplt.savefig('eigen_vectors.png')\nplt.close(fig)\n", "meta": {"hexsha": "cf18a2c93eb36e56957a921ac417f3179811e63d", "size": 2412, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_algebra/eigen_decompostion.py", "max_stars_repo_name": "amoljagadambe/machine-Learning_Tutorials", "max_stars_repo_head_hexsha": "7e9dc49d269bad93d3c6377f05865307c77d35df", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_algebra/eigen_decompostion.py", "max_issues_repo_name": "amoljagadambe/machine-Learning_Tutorials", "max_issues_repo_head_hexsha": "7e9dc49d269bad93d3c6377f05865307c77d35df", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_algebra/eigen_decompostion.py", "max_forks_repo_name": "amoljagadambe/machine-Learning_Tutorials", "max_forks_repo_head_hexsha": "7e9dc49d269bad93d3c6377f05865307c77d35df", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0465116279, "max_line_length": 116, "alphanum_fraction": 0.679933665, "include": true, "reason": "import numpy", "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338057771058, "lm_q2_score": 0.890294230488237, "lm_q1q2_score": 0.8560479997027542}}
{"text": "import numpy as np\n\n\n#Importing the data\ndata = np.loadtxt('sample.txt', delimiter=\",\")\nclass LinearRegression(object):\n    #Setting some of our initial parameters\n    def __init__(self, alpha, theta):\n        self.alpha = alpha\n        self.theta = theta\n    #Cleaning the data to make it ready for the training\n    def Cleaningdata(self, data):\n        ones = np.ones((len(data),1))\n        #This needs to be modified before calibrated the method\n        x = np.concatenate((ones, data[:,0].reshape(-1,1)), axis=1)\n        y = data[:,1].reshape(-1,1)\n        return (x, y)\n    #Training the model using gradient descent\n    def train(self,x , y, m):\n        error = y.T - (self.theta @ x.T)\n        J = m * (error @ error.T)\n        dj = (m*-2) * ((error) @ x)\n        self.theta = self.theta - self.alpha * dj\n    #We can also train our model using the normal equation\n    def normalEquation(self, x, y):\n        self.theta = np.linalg.inv(x.T @ x) @ (x.T @ y)\n    #We can query a specific answer\n    def query(self, x):\n        return self.theta @ x\n\n#Example of a model\nmodel = LinearRegression(0.00000001, [10,10])\nx, y = model.Cleaningdata(data)\n\n#Setting our training loop\niteration = 0\nm = 1/len(data)\nwhile iteration < 100000:\n    iteration += 1\n    model.train(x,y,m)\n#Asking the model to answer a specific question\nanswer = model.query([100,23])\n\n#Example of model traning using the normal equation\nmodel.normalEquation(x,y)\n\n", "meta": {"hexsha": "310684c63b4973e22d9f09a5ed1f6e778d4e9cf6", "size": 1438, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear regression/LinearR_Model.py", "max_stars_repo_name": "wassimkha/Simple-linear-regression-algorithm", "max_stars_repo_head_hexsha": "4982d0e41f7d162bccef0fea777adb597de0746d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-27T22:42:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-27T22:42:52.000Z", "max_issues_repo_path": "Linear regression/LinearR_Model.py", "max_issues_repo_name": "wassimkha/Machine-Learning-Algorithms", "max_issues_repo_head_hexsha": "4982d0e41f7d162bccef0fea777adb597de0746d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear regression/LinearR_Model.py", "max_forks_repo_name": "wassimkha/Machine-Learning-Algorithms", "max_forks_repo_head_hexsha": "4982d0e41f7d162bccef0fea777adb597de0746d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5957446809, "max_line_length": 67, "alphanum_fraction": 0.6342141864, "include": true, "reason": "import numpy", "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862455, "lm_q2_score": 0.8902942239389252, "lm_q1q2_score": 0.8560479973308013}}
{"text": "import math\nimport sklearn.metrics\nimport pandas as pd\nimport numpy as  np\nimport matplotlib.pyplot as plt\n\ndef residuals(actual, predicted):\n    return actual - predicted\n\ndef sse(actual, predicted):\n    return (residuals(actual, predicted) **2).sum()\n\ndef mse(actual, predicted):\n    n = actual.shape[0]\n    return sse(actual, predicted) / n\n\ndef rmse(actual, predicted):\n    return math.sqrt(mse(actual, predicted))\n\ndef ess(actual, predicted):\n    return ((predicted - actual.mean()) ** 2).sum()\n\ndef tss(actual):\n    return ((actual - actual.mean()) ** 2).sum()\n\ndef regression_errors(actual, predicted):\n    return pd.Series({\n        'sse': sse(actual, predicted),\n        'ess': ess(actual, predicted),\n        'tss': tss(actual),\n        'mse': mse(actual, predicted),\n        'rmse': rmse(actual, predicted),\n    })\n\ndef baseline_mean_errors(actual):\n    predicted = actual.mean()\n    return {\n        'sse': sse(actual, predicted),\n        'mse': mse(actual, predicted),\n        'rmse': rmse(actual, predicted),\n    }\n\ndef better_than_baseline(actual, predicted):\n    rmse_baseline = rmse(actual, actual.mean())\n    rmse_model = rmse(actual, predicted)\n    return rmse_model < rmse_baseline\n\ndef model_significance(ols_model):\n    return {\n        'r^2 -- variance explained': ols_model.rsquared,\n        'p-value -- P(data|model == baseline)': ols_model.f_pvalue,\n    }\ndef plot_residuals(actual, predicted):\n    residuals = actual - predicted\n    plt.hlines(0, actual.min(), actual.max(), ls=':')\n    plt.scatter(actual, residuals)\n    plt.ylabel('residual ($y - \\hat{y}$)')\n    plt.xlabel('actual value ($y$)')\n    plt.title('Actual vs Residual')\n    plt.show()", "meta": {"hexsha": "437196361701d81e824691f641c02dc50460104b", "size": 1675, "ext": "py", "lang": "Python", "max_stars_repo_path": "evaluate.py", "max_stars_repo_name": "brandonjbryant/regression-exercises", "max_stars_repo_head_hexsha": "5f46c5e5fb62aa97b77b98c7e286d92dc3700f56", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "evaluate.py", "max_issues_repo_name": "brandonjbryant/regression-exercises", "max_issues_repo_head_hexsha": "5f46c5e5fb62aa97b77b98c7e286d92dc3700f56", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-11T22:13:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-11T22:26:26.000Z", "max_forks_repo_path": "evaluate.py", "max_forks_repo_name": "brandonjbryant/regression-exercises", "max_forks_repo_head_hexsha": "5f46c5e5fb62aa97b77b98c7e286d92dc3700f56", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9166666667, "max_line_length": 67, "alphanum_fraction": 0.647761194, "include": true, "reason": "import numpy", "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769113660688, "lm_q2_score": 0.8774767986961403, "lm_q1q2_score": 0.8560461050673662}}
{"text": "from statistics import mean\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\n\nstyle.use('fivethirtyeight')\n\nxs = np.array([1, 2, 3, 4, 5, 6], dtype=np.float64)\nys = np.array([5, 4, 6, 5, 6, 7], dtype=np.float64)\n\n# plt.scatter(xs, ys)\n# plt.show()\n\ndef best_fit_slope_and_intercept(xs, ys):\n    # least square method\n    m = ((mean(xs) * mean(ys)) - mean(xs*ys)) / (mean(xs)**2 - mean(xs**2))\n    b = mean(ys) - m*mean(xs)\n    return m, b\n\ndef squared_error(ys_orig, ys_line):\n    # calculate squared error\n    return sum((ys_line-ys_orig)**2)\n\ndef coefficient_of_determination(ys_orig, ys_line):\n    y_mean_line = [mean(ys_orig) for y in ys_orig]\n    squared_error_regr = squared_error(ys_orig, ys_line)\n    squared_error_y_mean = squared_error(ys_orig, y_mean_line)\n    return 1 - (squared_error_regr / squared_error_y_mean)\n\nm, b = best_fit_slope_and_intercept(xs, ys)\n\n# print (m, b)\nregression_line = [(m*x)+b for x in xs]\n# The line above is equal\n# for x in xs:\n#     regression_line.append((m*x)+b)\n\npredict_x = 8\npredict_y = (m*predict_x)+b\n\nr_squared = coefficient_of_determination(ys, regression_line)\nprint (r_squared)\n\nplt.scatter(xs, ys)\nplt.scatter(predict_x, predict_y, color='g')\nplt.plot(xs, regression_line)\nplt.show()\n", "meta": {"hexsha": "d073f8cce5bbaa6f9a8206f913274252e1641b82", "size": 1269, "ext": "py", "lang": "Python", "max_stars_repo_path": "machiane_learning_python/regression/lab04_best_fit_slope_and_squared_error.py", "max_stars_repo_name": "justin-changqi/machine_learning_practise", "max_stars_repo_head_hexsha": "52e4f6694e9e8ba3dfb57e2f3352641526c3e7d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "machiane_learning_python/regression/lab04_best_fit_slope_and_squared_error.py", "max_issues_repo_name": "justin-changqi/machine_learning_practise", "max_issues_repo_head_hexsha": "52e4f6694e9e8ba3dfb57e2f3352641526c3e7d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "machiane_learning_python/regression/lab04_best_fit_slope_and_squared_error.py", "max_forks_repo_name": "justin-changqi/machine_learning_practise", "max_forks_repo_head_hexsha": "52e4f6694e9e8ba3dfb57e2f3352641526c3e7d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4375, "max_line_length": 75, "alphanum_fraction": 0.7037037037, "include": true, "reason": "import numpy", "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769134963329, "lm_q2_score": 0.8774767874818408, "lm_q1q2_score": 0.8560460959962118}}
{"text": "# ------------- Machine Learning - Topic 2: Logistic Regression Multivariate\n\n## Initialization\nimport numpy as np\nfrom scipy.optimize import fmin, fmin_bfgs\nimport os, sys\nsys.path.append(os.getcwd() + os.path.dirname('/ml/ex2/'))\nfrom helpers import sigmoid, costFunctionReg, predict, plotData, plotDecisionBoundary, mapFeature\n\n# Load Data\n#  The first two columns contains the exam scores and the third column\n#  contains the label.\ndata = np.loadtxt('ml/ex2/ex2data2.txt', delimiter=\",\")\nX = data[:, :2]\ny = data[:, 2]\nplt, p1, p2 = plotData(X, y)\n\n# # Labels and Legend\nplt.xlabel('Microchip Test 1')\nplt.ylabel('Microchip Test 2')\nplt.legend((p1, p2), ('y = 1', 'y = 0'), numpoints=1, handlelength=0)\nplt.show(block=False) # prevents having to close the graph to move forward\ninput('Program paused. Press enter to continue.\\n')\n\n\n## =========== Part 1: Regularized Logistic Regression ============\n#  In this part, you are given a dataset with data points that are not\n#  linearly separable. However, you would still like to use logistic\n#  regression to classify the data points.\n#\n#  To do so, you introduce more features to use -- in particular, you add\n#  polynomial features to our data matrix (similar to polynomial\n#  regression).\n#\n\n# Add Polynomial Features\n\n# Note that mapFeature also adds a column of ones for us, so the intercept\n# term is handled\nX = mapFeature(X[:,0], X[:,1])\nm, n = X.shape\n\n# Initialize fitting parameters\ninitial_theta = np.zeros((n, 1))\n\n# Set regularization parameter lambda to 1\nlambda_reg = 0.1\n\n# Compute and display initial cost\n# gradient is too large to display in this exercise\ncost = costFunctionReg(initial_theta, X, y, lambda_reg)\n\nprint('Cost at initial theta (zeros): {:f}'.format(cost))\n# print('Gradient at initial theta (zeros):')\n# print(grad)\n\ninput('Program paused. Press enter to continue.\\n')\n\n\n## ============= Part 2: Regularization and Accuracies =============\n#  Optional Exercise:\n#  In this part, you will get to try different values of lambda and\n#  see how regularization affects the decision coundart\n#\n#  Try the following values of lambda (0, 1, 10, 100).\n#\n#  How does the decision boundary change when you vary lambda? How does\n#  the training set accuracy vary?\n\n# Initialize fitting parameters\ninitial_theta = np.zeros((n, 1))\n\n# Set regularization parameter lambda to 1 (you should vary this)\nlambda_reg = 1\n\n#  Run fmin_bfgs to obtain the optimal theta\n#  This function returns theta and the cost\nmyargs=(X, y, lambda_reg)\ntheta = fmin_bfgs(costFunctionReg, x0=initial_theta, args=myargs)\n\n# Plot Boundary\nplotDecisionBoundary(theta, X, y)\n\n# # Labels, title and Legend\nplt.xlabel('Microchip Test 1')\nplt.ylabel('Microchip Test 2')\nplt.title('lambda = {:f}'.format(lambda_reg))\n\n# % Compute accuracy on our training set\np = predict(theta, X)\n\nprint('Train Accuracy: {:f}'.format(np.mean(p == y) * 100))\n\ninput('Program paused. Press enter to continue.\\n')\n\n", "meta": {"hexsha": "1c1158891812e243a1b16147489a0a233e012dce", "size": 2938, "ext": "py", "lang": "Python", "max_stars_repo_path": "ml/ex2/ex2_reg.py", "max_stars_repo_name": "dpopadic/ml-res", "max_stars_repo_head_hexsha": "1fd746301b3ef10a96f78832cebb0c79c9327f1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ml/ex2/ex2_reg.py", "max_issues_repo_name": "dpopadic/ml-res", "max_issues_repo_head_hexsha": "1fd746301b3ef10a96f78832cebb0c79c9327f1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ml/ex2/ex2_reg.py", "max_forks_repo_name": "dpopadic/ml-res", "max_forks_repo_head_hexsha": "1fd746301b3ef10a96f78832cebb0c79c9327f1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-21T07:58:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T07:58:21.000Z", "avg_line_length": 30.6041666667, "max_line_length": 97, "alphanum_fraction": 0.7147719537, "include": true, "reason": "import numpy,from scipy", "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.9241418189341297, "lm_q1q2_score": 0.8560360123191928}}
{"text": "import numpy as np\n\n\ndef matrix_multiply(X, Y):\n    \"\"\" Matrix multiplication\n    Inputs:\n      - X: A numpy array of shape (N, M)\n      - Y: A numpy array of shape (M, K)\n    Output:\n      - out: A numpy array of shape (N, K)\n    \"\"\"\n    out = np.dot(X, Y)\n    return out\n\n\ndef matrix_rowmean(X, weights=np.empty(0)):\n    \"\"\" Calculate mean of each row.\n    In case of weights do weighted mean.\n    For example, for matrix [[1, 2, 3]] and weights [0, 1, 2]\n    weighted mean equals 2.6666 (while ordinary mean equals 2)\n    Inputs:\n      - X: A numpy array of shape (N, M)\n      - weights: A numpy array of shape (M,) or an emty array of shape (0,)\n    Output:\n      - out: A numpy array of shape (N,)\n    \"\"\"\n    if weights.size > 0:\n        out = np.average(X, weights=weights, axis=1)\n    else:\n        out = np.average(X, axis=1)\n    return out\n\ndef cosine_similarity(X, top_n=10, with_mean=True, with_std=True):\n    \"\"\" Calculate cosine similarity between each pair of row.\n    1. In case of with_mean: subtract mean of each row from row\n    2. In case of with_std: divide each row on it's std\n    3. Select top_n best elements in each row or set other to zero.\n    4. Compute cosine similarity between each pair of rows.\n    Inputs:\n      - X: A numpy array of shape (N, M)\n      - top_n: int, number of best elements in each row\n      - with_mean: bool, in case of subtracting each row's mean\n      - with_std: bool, in case of subtracting each row's std\n    Output:\n      - out: A numpy array of shape (N, N)\n\n    Example (with top_n=1, with_mean=True, with_std=True):\n        X = array([[1, 2], [4, 3]])\n        after mean and std transform:\n        X = array([[-1.,  1.], [ 1., -1.]])\n        after top n choice\n        X = array([[0.,  1.], [ 1., 0]])\n        cosine similarity:\n        X = array([[ 1.,  0.], [ 0.,  1.]])\n\n    \"\"\"\n    if with_mean:\n        X = X - np.mean(X, axis=1, keepdims=True)\n    if with_std:\n        X = X / np.std(X, axis=1, keepdims=True)\n    if top_n is not None:\n        X[np.arange(X.shape[0]).reshape(-1, 1),\n          np.argsort(X)[:, :-top_n]] = 0\n    out = np.dot(X, X.T) / (np.linalg.norm(X, axis=1, keepdims=True)\n                            * np.linalg.norm(X, axis=1, keepdims=True).T)\n    return out\n", "meta": {"hexsha": "32211ab00565c0347e6e7c127a9bcb1db056f1c9", "size": 2251, "ext": "py", "lang": "Python", "max_stars_repo_path": "intro_to_data_science/3_numpy_cython_numba/hw/numpy_functions.py", "max_stars_repo_name": "minemile/technosphere", "max_stars_repo_head_hexsha": "31363712f8087d667a1a04141edaac451193d31d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "intro_to_data_science/3_numpy_cython_numba/hw/numpy_functions.py", "max_issues_repo_name": "minemile/technosphere", "max_issues_repo_head_hexsha": "31363712f8087d667a1a04141edaac451193d31d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intro_to_data_science/3_numpy_cython_numba/hw/numpy_functions.py", "max_forks_repo_name": "minemile/technosphere", "max_forks_repo_head_hexsha": "31363712f8087d667a1a04141edaac451193d31d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5970149254, "max_line_length": 75, "alphanum_fraction": 0.5766326077, "include": true, "reason": "import numpy", "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551535992067, "lm_q2_score": 0.8872045996818986, "lm_q1q2_score": 0.8560239303000009}}
{"text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nplt.rcParams['figure.figsize'] = (20.0,10.0)\n\n#Reading data\n\ndata = pd.read_csv('data.csv')\nprint(data.shape)\n\nprint(data.head())\n\n#collecting the x and y values\nX = data['experience'].values\nY = data['salary'].values\n\n#to get the equation of the regression line y = mx + c ,\n#we need to find the value of slope first\n# m = Sum{ ([X-mean_x] * [Y - mean_y]) } / Sum { [X - mean_x]**2 }\n\n#calculating the mean\n\nmean_x =np.mean(X)\nmean_y =np.mean(Y)\n\n#collecting the total number of values so that we can minus the mean from everything\n\nn = len(X)\n\n# Lets consider m = numerator / denominator , we they each take the respective\n#positions as mentioned in l20 equation\n\nnumerator, denominator = 0 , 0\n\nfor i in range(n):\n\tnumerator += (X[i] - mean_x)*(Y[i] - mean_y)\n\tdenominator += (X[i]-mean_x)**2\n\n\n\n# lets get the value of m and c || y = mx + c\nm = numerator/denominator\n# from y = mx + c || c = y - mx\nc = mean_y - (m*mean_x)\n\n\nprint(\" m = {} and c = {} \".format(m,c))\n\n#plotting Values and regression line\n\nmax_x = np.max(X) + 10\nmin_x = np.min(X) - 10\n\n#calculating line values x and y\n\nx = np.linspace(min_x, max_x,100)\ny = m*x + c\n\n#Rsquared method , did'nt understand this part\n\nss_t , ss_r= 0,0\n\nfor i in range(n):\n\ty_pred = m + X[i]*c\n\tss_t += (Y[i] - mean_y)**2\n\tss_r += (Y[i]- y_pred)**2\n\nr2 = 1 -(ss_r/ss_t)\nprint(\"R2 = \",r2)\n\n#plotting line\n\nplt.plot(x,y, color =\"#58b970\", label= \"Regression Line\")\n\n#plotting scatter points\nplt.scatter(X, Y, c=\"#ef5423\", label=\"Scatter Plots\")\n\nplt.xlabel('Experience')\nplt.ylabel('Salary')\nplt.legend()\nplt.show()\nfrom sklearn import model_selection,linear_model\n\nexp_train , exp_test,salary_train , salary_test = model_selection.train_test_split(X,Y)\nreg = linear_model.LinearRegression()\nreg.fit(exp_train, salary_train)\n\nprint(\"From Calculation\")\nprint(\"Slope = \", m)\nprint(\"Intercept = \", c)\n\nprint(\"From Linear Regression\")\nprint(\"Slope = \", reg.coef_)\nprint(\"intercept  = \", reg.intercept_)\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "6f7639362c5497922aa0e0125910439777cc2117", "size": 2030, "ext": "py", "lang": "Python", "max_stars_repo_path": "code2.py", "max_stars_repo_name": "aswnss-m/Regression", "max_stars_repo_head_hexsha": "665463e111cb462c2c2fb9e8acdc23f69d90fcb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code2.py", "max_issues_repo_name": "aswnss-m/Regression", "max_issues_repo_head_hexsha": "665463e111cb462c2c2fb9e8acdc23f69d90fcb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code2.py", "max_forks_repo_name": "aswnss-m/Regression", "max_forks_repo_head_hexsha": "665463e111cb462c2c2fb9e8acdc23f69d90fcb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7962962963, "max_line_length": 87, "alphanum_fraction": 0.6724137931, "include": true, "reason": "import numpy", "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551525886193, "lm_q2_score": 0.8872045981907006, "lm_q1q2_score": 0.8560239279646131}}
{"text": "import numpy as np\nimport numpy.linalg as la\nimport matplotlib.pyplot as plt\n\n\nv1 = np.array([1,1])\nplt.plot([0, v1[0]], [0, v1[1]], 'b' , label='v', linewidth=2 )\nplt.plot([1,0],[0,0], 'g', label='ihat')\nplt.plot([0,0],[0,1], 'r', label='jhat')\n\n\nplt.legend()\nplt.axis('square')\nplt.axis((-0.5,1.5,-0.5,1.5))\nplt.grid()\nplt.show()\n\nTFM_Scale = np.array([[2,0], [0,3]])\nv2 = TFM_Scale @ v1\nprint(\"Scale along diagonal transform matrix \")\nprint(TFM_Scale)\nprint(v2)\n\nTFM_Rotate = np.array([[0,-1],[-1,0]])\nv3=TFM_Rotate @ v1\nprint(\"90 degrees clockwise rotation: \")\nprint(TFM_Rotate)\nprint(v3)\n\nTFM_Shear = np.array([[1,1],[0,1]])\nv4 = TFM_Shear @ v1\nprint(\"Shear along x-axis: \")\nprint(TFM_Shear)\nprint(v4)\n\n#Plot Transformation\nplt.plot([0, v1[0]], [0, v1[1]], label='v', linewidth=2)\nplt.plot([0, v2[0]], [0, v2[1]], label='Scale', linewidth=2)\nplt.plot([0, v3[0]], [0, v3[1]], label=\"Rotate\", linewidth=2)\nplt.plot([0, v4[0]], [0, v4[1]], label='Shear',  linewidth= 2)\n\n\nplt.legend()\nplt.axis('square')\nplt.axis((-3,4,-2,5))\nplt.grid()\nplt.show()\n\n\n", "meta": {"hexsha": "10fe559854fcc9dbdae6f543edadd8ad36b83bfd", "size": 1052, "ext": "py", "lang": "Python", "max_stars_repo_path": "linearTransformation.py", "max_stars_repo_name": "Ceasar15/Maths-For-Data-Science", "max_stars_repo_head_hexsha": "4c539d0930b4f8879cb4edfca3b2d58796f4e764", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-05T01:44:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-05T01:44:47.000Z", "max_issues_repo_path": "linearTransformation.py", "max_issues_repo_name": "Ceasar15/Maths-For-Data-Science", "max_issues_repo_head_hexsha": "4c539d0930b4f8879cb4edfca3b2d58796f4e764", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linearTransformation.py", "max_forks_repo_name": "Ceasar15/Maths-For-Data-Science", "max_forks_repo_head_hexsha": "4c539d0930b4f8879cb4edfca3b2d58796f4e764", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.04, "max_line_length": 63, "alphanum_fraction": 0.6226235741, "include": true, "reason": "import numpy", "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964855157641556, "lm_q2_score": 0.8872045922259088, "lm_q1q2_score": 0.8560239266924417}}
{"text": "# Univariate Linear Regression\n# Implementation using numpy, more efficient\n\nimport numpy as np\nfrom sklearn import datasets\n\ndef partial_derivative(theta, trainX, trainY, trainSize):\n    return (theta.dot(trainX) - trainY).dot(trainX.T) / trainSize\n\ndef fit(trainX, trainY, learningRate=0.1, threashold=1E-5):\n    theta = np.array([0, 1], dtype=float) # Initialize theta\n    trainSize = len(trainY)\n    derivative = partial_derivative(theta, trainX, trainY, trainSize)\n    while abs(derivative).max() > threashold: # While gradient doesn't converge\n        theta -= learningRate * derivative # Perform gradient descent\n        derivative = partial_derivative(theta, trainX, trainY, trainSize) # Update partial derivative\n    return theta\n\ndef standard_fit(trainX, trainY):\n    trainX = trainX[1, :] # Remove the extra bias term\n    model = np.polyfit(trainX, trainY, deg=1) # Degree of 1 (linear model)\n    return model\n\ndef accuracy(theta, testX, testY):\n    # Returns the R Squared value of the model\n    explained = theta.dot(testX)\n    mean = np.sum(testY) / len(testY)\n    totSumSquares = np.sum((testY - mean) ** 2)\n    resSumSquares = np.sum((testY - explained) ** 2)\n    accuracy = 1 - resSumSquares / totSumSquares\n    return accuracy\n\ndataset = datasets.load_diabetes()\ndata, target = dataset.data, dataset.target\ndataSize = len(data)\ndata = data[:, 2] # Take only one feature\ndata = np.vstack((np.ones(dataSize), data)) # Add an extra bias term\nseparation = int(dataSize * 0.8) # Percentage of training data set and testing data set\ntrainX, trainY = data[:, :separation], target[:separation]\ntestX, testY = data[:, separation:], target[separation:]\n\nhypothesis = standard_fit(trainX, trainY)\nprint('Fitted Model: y = {0}x {2} {1}'.format(hypothesis[0], abs(hypothesis[1]), ('-', '+')[hypothesis[1]>0]))\nacc = accuracy(hypothesis[::-1], testX, testY)\nprint('Standard Accuracy: {:.4f}\\n'.format(acc))\n\nhypothesis = fit(trainX, trainY, 1, 1E-6)\nprint('Fitted Model: y = {1}x {2} {0}'.format(abs(hypothesis[0]), hypothesis[1], ('-', '+')[hypothesis[0]>0]))\nacc = accuracy(hypothesis, testX, testY)\nprint('Fitted Accuracy: {:.4f}'.format(acc))\n", "meta": {"hexsha": "9d96c11278f662bb280ae007fb52f5064772b755", "size": 2151, "ext": "py", "lang": "Python", "max_stars_repo_path": "implementations/lin_reg_uni.py", "max_stars_repo_name": "yu-george/ml", "max_stars_repo_head_hexsha": "8eedc62df9e7f37312bba39fa45bb9e9c6361028", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "implementations/lin_reg_uni.py", "max_issues_repo_name": "yu-george/ml", "max_issues_repo_head_hexsha": "8eedc62df9e7f37312bba39fa45bb9e9c6361028", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "implementations/lin_reg_uni.py", "max_forks_repo_name": "yu-george/ml", "max_forks_repo_head_hexsha": "8eedc62df9e7f37312bba39fa45bb9e9c6361028", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1764705882, "max_line_length": 110, "alphanum_fraction": 0.6973500697, "include": true, "reason": "import numpy", "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551495568569, "lm_q2_score": 0.8872045966995028, "lm_q1q2_score": 0.8560239238360297}}
{"text": "import numpy as np\n\ndef stmul(A,B) :\n    # 에러 처리 부분은 생략하겠습니다. (e.g len(A)!=2^k)\n\n    n=len(A)\n\n    if 2<n :\n        A11=A[0:n//2,0:n//2]\n        A12=A[0:n//2,n//2:n]\n        A21=A[n//2:n,0:n//2]\n        A22=A[n//2:n,n//2:n]\n\n        B11=B[0:n//2,0:n//2]\n        B12=B[0:n//2,n//2:n]\n        B21=B[n//2:n,0:n//2]\n        B22=B[n//2:n,n//2:n]\n\n        M1=stmul(A11+A22,B11+B22)\n        M2=stmul(A21+A22,B11)\n        M3=stmul(A11,B12-B22)\n        M4=stmul(A22,B21-B11)\n        M5=stmul(A11+A12,B22)\n        M6=stmul(A21-A11,B11+B12)\n        M7=stmul(A12-A22,B21+B22)\n\n  \n        C11=M1+M4-M5+M7\n        C12=M3+M5\n        C21=M2+M4\n        C22=M1-M2+M3+M6\n\n        C=np.zeros((n,n))\n\n        C[0:n//2,0:n//2]=C11\n        C[0:n//2,n//2:n]=C12\n        C[n//2:n,0:n//2]=C21\n        C[n//2:n,n//2:n]=C22\n    \n    else :\n    \n        A11=A[0,0]\n        A12=A[0,1]\n        A21=A[1,0]\n        A22=A[1,1]\n\n        B11=B[0,0]\n        B12=B[0,1]\n        B21=B[1,0]\n        B22=B[1,1]\n\n        M1=(A11+A22)*(B11+B22)\n        M2=(A21+A22)*(B11)\n        M3=(A11)*(B12-B22)\n        M4=(A22)*(B21-B11)\n        M5=(A11+A12)*(B22)\n        M6=(A21-A11)*(B11+B12)\n        M7=(A12-A22)*(B21+B22)\n\n        C11=M1+M4-M5+M7\n        C12=M3+M5\n        C21=M2+M4\n        C22=M1-M2+M3+M6\n\n        C=np.zeros((n,n))\n\n        C[0,0]=C11\n        C[0,1]=C12\n        C[1,0]=C21\n        C[1,1]=C22\n\n    return C\n\n\nif __name__ == '__main__':\n    A=np.array([[1,0,2,1],[4,1,1,0],[0,1,3,0],[5,0,2,1]])\n    B=np.array([[0,1,0,1],[2,1,1,4],[2,0,1,1],[1,3,5,0]])\n\n    C=stmul(A,B)\n    print(C)\n\n    D=np.matmul(A,B)\n    print(D) #numpy 내장함수를 통해 행렬 A,B를 곱한 것이 strassen formula를 통해 구한 것과 동일함을 알 수 있다.\n", "meta": {"hexsha": "ae456b82cd77df8da025a2a7b6543268c81c7f6c", "size": 1656, "ext": "py", "lang": "Python", "max_stars_repo_path": "20-1/Algorithms/assign2/3.py", "max_stars_repo_name": "neulbo-187/graduate-course", "max_stars_repo_head_hexsha": "8b5b6781f8c61ec11e96955d2b07a791b360d6ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "20-1/Algorithms/assign2/3.py", "max_issues_repo_name": "neulbo-187/graduate-course", "max_issues_repo_head_hexsha": "8b5b6781f8c61ec11e96955d2b07a791b360d6ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "20-1/Algorithms/assign2/3.py", "max_forks_repo_name": "neulbo-187/graduate-course", "max_forks_repo_head_hexsha": "8b5b6781f8c61ec11e96955d2b07a791b360d6ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7142857143, "max_line_length": 82, "alphanum_fraction": 0.4263285024, "include": true, "reason": "import numpy", "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551505674444, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.856023914661097}}
{"text": "# 0452-qp-ls-lr-poly3.pg\n# Impelement QP for LS in the case of LR for POLY3\n# Sparisoma Viridi | https://github.com/dudung/bug\n# 20220215 Create this program.\n\n# abbreviations\n# QP quaratic programming\n# LS least square\n# LR linear regression\n# POLY3 polynomial function of 3rd order\n\n# import numpy\nimport os, sys\nimport numpy as np\n\n# open file, read lines and store them in a list, close file\nfn = '0452-a.txt'\nprint('file:', fn)\nwith open(os.path.join(sys.path[0], fn), 'r') as f:\n    lines = f.readlines()\n\n# create empty list\nx = [[]]\ny = [[]]\nA = []\n\n# iterate through lines but ommit the first element\nfor l in lines[1:]:\n    s = l.rstrip('\\n') \n    s = s.split('\\t')\n    xi = float(s[0])\n    yi = float(s[1])\n\n    x[0].append(xi)\n    y[0].append(yi)\n    \n    p0 = 1\n    p1 = xi\n    p2 = xi**2\n    p3 = xi**3\n    Ai = [p0, p1, p2, p3]\n    A.append(Ai)\n\n# create numpy array\nx = np.transpose(np.array(x))\ny = np.transpose(np.array(y))\nA = np.array(A)\n\n# find c via some temporary variables\nAT = np.transpose(A)\nATA = np.matmul(AT, A)\nATA_1 = np.linalg.inv(ATA)\nATA_1AT = np.matmul(ATA_1, AT)\nc = np.matmul(ATA_1AT, y)\n\n# print dimension of matrices\nprint()\nprint('y:', y.shape)\nprint('A:', A.shape)\nprint('AT:', AT.shape)\nprint('ATA:', ATA.shape)\nprint('ATA_1:', ATA_1.shape)\nprint('ATA_1AT:', ATA_1AT.shape)\nprint('c: ', c.shape)\n\n# print results\nprint()\nprint('c = ')\nprint(c)", "meta": {"hexsha": "73bffab44f55abb4a9ae7fe6cc9311988bde0222", "size": 1385, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercises/quad_prog/0452-qp-ls-lr-poly3.py", "max_stars_repo_name": "mahaamesha/fi3201-01-2021-2", "max_stars_repo_head_hexsha": "80c8fd74ae99c19c5421987c15f6a50985c3b69d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercises/quad_prog/0452-qp-ls-lr-poly3.py", "max_issues_repo_name": "mahaamesha/fi3201-01-2021-2", "max_issues_repo_head_hexsha": "80c8fd74ae99c19c5421987c15f6a50985c3b69d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercises/quad_prog/0452-qp-ls-lr-poly3.py", "max_forks_repo_name": "mahaamesha/fi3201-01-2021-2", "max_forks_repo_head_hexsha": "80c8fd74ae99c19c5421987c15f6a50985c3b69d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0724637681, "max_line_length": 60, "alphanum_fraction": 0.6339350181, "include": true, "reason": "import numpy", "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.9161096204605946, "lm_q1q2_score": 0.8560084010628826}}
{"text": "import numpy as np\r\n\r\ndef rmse(predictions, targets):\r\n    return np.sqrt(((predictions - targets) ** 2).mean())\r\n\r\ndef polar_to_cartesian(z,theta):\r\n    return z*np.exp(1j*np.deg2rad(theta))\r\n\r\ndef cartesian_to_polar(Z):\r\n    x = Z.real\r\n    y = Z.imag\r\n    z = np.sqrt(x**2 + y**2)\r\n    theta = np.arctan2(y, x)\r\n    return z,theta\r\n\r\ndef MAPE(predictions, targets): \r\n    targets, predictions = np.array(targets), np.array(predictions)\r\n    return np.mean(np.abs((targets - predictions) / targets)) * 100", "meta": {"hexsha": "798b03df42084618d844c6c2f1d23390dfe98d55", "size": 507, "ext": "py", "lang": "Python", "max_stars_repo_path": "logv3lpf/math_functions.py", "max_stars_repo_name": "Ignacio-Losada/Log-v-3LPF", "max_stars_repo_head_hexsha": "cd5eaae7c2128da220a126c990b20e153a2f4b87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-21T18:00:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T14:02:34.000Z", "max_issues_repo_path": "logv3lpf/math_functions.py", "max_issues_repo_name": "Ignacio-Losada/Log-v-3LPF", "max_issues_repo_head_hexsha": "cd5eaae7c2128da220a126c990b20e153a2f4b87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logv3lpf/math_functions.py", "max_forks_repo_name": "Ignacio-Losada/Log-v-3LPF", "max_forks_repo_head_hexsha": "cd5eaae7c2128da220a126c990b20e153a2f4b87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-03T16:29:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T16:29:45.000Z", "avg_line_length": 28.1666666667, "max_line_length": 68, "alphanum_fraction": 0.6370808679, "include": true, "reason": "import numpy", "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.8947894661025424, "lm_q1q2_score": 0.8559862083920317}}
{"text": "#encoding=utf-8\n\n\"\"\"\n1. Take the whole dataset consisting of dd-dimensional samples ignoring the class labels\n2. Compute the dd-dimensional mean vector (i.e., the means for every dimension of the whole dataset)\n3. Compute the scatter matrix (alternatively, the covariance matrix) of the whole data set\n4. Compute eigenvectors (ee1,ee2,...,eedee1,ee2,...,eed) and corresponding eigenvalues (λλ1,λλ2,...,λλdλλ1,λλ2,...,λλd)\n5. Sort the eigenvectors by decreasing eigenvalues and choose kk eigenvectors with the largest eigenvalues to form a d×kd×k dimensional\nmatrix WWWW(where every column represents an eigenvector)\n6. Use this d×kd×k eigenvector matrix to transform the samples onto the new subspace. This can be summarized by the mathematical\nequation: yy=WWT×xxyy=WWT×xx (where xxxx is a d×1d×1-dimensional vector representing one sample, and yyyy is the transformed\nk×1k×1-dimensional sample in the new subspace.)\n\"\"\"\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d import proj3d\n\nnp.random.seed(12)\n\nmu_vec1 = np.array([0,0,0])\ncov_mat1 = np.array([[1,0,0],[0,1,0],[0,0,1]])\nclass1_sample = np.random.multivariate_normal(mu_vec1, cov_mat1, 20).T\nassert class1_sample.shape == (3,20), \"The matrix has not the dimensions 3x20\"\n\nmu_vec2 = np.array([1,1,1])\ncov_mat2 = np.array([[1,0,0],[0,1,0],[0,0,1]])\nclass2_sample = np.random.multivariate_normal(mu_vec2, cov_mat2, 20).T\nassert class2_sample.shape == (3,20), \"The matrix has not the dimensions 3x20\"\n\n\n#\n# fig = plt.figure(figsize=(8,8))\n# ax = fig.add_subplot(111, projection='3d')\n# plt.rcParams['legend.fontsize'] = 10\n# ax.plot(class1_sample[0,:], class1_sample[1,:], class1_sample[2,:], 'o', markersize=8, color='blue', alpha=0.5, label='class1')\n# ax.plot(class2_sample[0,:], class2_sample[1,:], class2_sample[2,:], '^', markersize=8, alpha=0.5, color='red', label='class2')\n#\n# plt.title('Samples for class 1 and class 2')\n# ax.legend(loc='upper right')\n#\n# plt.show()\n\nall_samples = np.concatenate((class1_sample, class2_sample), axis=1)\nassert all_samples.shape == (3,40), \"The matrix has not the dimensions 3x40\"\n\nmean_x = np.mean(all_samples[0,:])\nmean_y = np.mean(all_samples[1,:])\nmean_z = np.mean(all_samples[2,:])\n\nmean_vector = np.array([[mean_x],[mean_y],[mean_z]])\n\nprint('Mean Vector:\\n', mean_vector)\n\n\"\"\"\nThe scatter matrix is computed by the following equation:\nS=∑k=1n(xxk−mm)(xxk−mm)T\nwhere mmmm is the mean vector\nmm=1n∑k=1nxxkmm=1n∑k=1nxxk\n\"\"\"\n\nscatter_matrix = np.zeros((3,3))\nfor i in range(all_samples.shape[1]):\n    scatter_matrix += (all_samples[:,i].reshape(3,1) - mean_vector).dot((all_samples[:,i].reshape(3,1) - mean_vector).T)\nprint('Scatter Matrix:\\n', scatter_matrix)\n\n\ncov_mat = np.cov([all_samples[0,:],all_samples[1,:],all_samples[2,:]])\nprint('Covariance Matrix:\\n', cov_mat)\n\n\n\n\"\"\"\n4 --\n\"\"\"\n# eigenvectors and eigenvalues for the from the scatter matrix\neig_val_sc, eig_vec_sc = np.linalg.eig(scatter_matrix)\n\n# eigenvectors and eigenvalues for the from the covariance matrix\neig_val_cov, eig_vec_cov = np.linalg.eig(cov_mat)\n\nfor i in range(len(eig_val_sc)):\n    eigvec_sc = eig_vec_sc[:,i].reshape(1,3).T\n    eigvec_cov = eig_vec_cov[:,i].reshape(1,3).T\n    assert eigvec_sc.all() == eigvec_cov.all(), 'Eigenvectors are not identical'\n\n    print('Eigenvector {}: \\n{}'.format(i+1, eigvec_sc))\n    print('Eigenvalue {} from scatter matrix: {}'.format(i+1, eig_val_sc[i]))\n    print('Eigenvalue {} from covariance matrix: {}'.format(i+1, eig_val_cov[i]))\n    print('Scaling factor: ', eig_val_sc[i]/eig_val_cov[i])\n    print(40 * '-')\n\n#\n# from matplotlib import pyplot as plt\n# from mpl_toolkits.mplot3d import Axes3D\n# from mpl_toolkits.mplot3d import proj3d\n# from matplotlib.patches import FancyArrowPatch\n#\n# class Arrow3D(FancyArrowPatch):\n#     def __init__(self, xs, ys, zs, *args, **kwargs):\n#         FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)\n#         self._verts3d = xs, ys, zs\n#\n#     def draw(self, renderer):\n#         xs3d, ys3d, zs3d = self._verts3d\n#         xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n#         self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))\n#         FancyArrowPatch.draw(self, renderer)\n#\n# fig = plt.figure(figsize=(7,7))\n# ax = fig.add_subplot(111, projection='3d')\n#\n# ax.plot(all_samples[0,:], all_samples[1,:], all_samples[2,:], 'o', markersize=8, color='green', alpha=0.2)\n# ax.plot([mean_x], [mean_y], [mean_z], 'o', markersize=10, color='red', alpha=0.5)\n# for v in eig_vec_sc.T:\n#     a = Arrow3D([mean_x, v[0]], [mean_y, v[1]], [mean_z, v[2]], mutation_scale=20, lw=3, arrowstyle=\"-|>\", color=\"r\")\n#     ax.add_artist(a)\n# ax.set_xlabel('x_values')\n# ax.set_ylabel('y_values')\n# ax.set_zlabel('z_values')\n#\n# plt.title('Eigenvectors')\n#\n# plt.show()\n\n\n# Make a list of (eigenvalue, eigenvector) tuples\neig_pairs = [(np.abs(eig_val_sc[i]), eig_vec_sc[:,i]) for i in range(len(eig_val_sc))]\n\n# Sort the (eigenvalue, eigenvector) tuples from high to low\neig_pairs.sort(key=lambda x: x[0], reverse=True)\n\n# Visually confirm that the list is correctly sorted by decreasing eigenvalues\nfor i in eig_pairs:\n    print(i[0])\n\n\nmatrix_w = np.hstack((eig_pairs[0][1].reshape(3,1), eig_pairs[1][1].reshape(3,1)))\nprint('Matrix W:\\n', matrix_w)\n\n\"\"\"\n6\n\"\"\"\ntransformed = matrix_w.T.dot(all_samples)\nassert transformed.shape == (2,40), \"The matrix is not 2x40 dimensional.\"\n\nplt.plot(transformed[0,0:20], transformed[1,0:20], 'o', markersize=7, color='blue', alpha=0.5, label='class1')\nplt.plot(transformed[0,20:40], transformed[1,20:40], '^', markersize=7, color='red', alpha=0.5, label='class2')\nplt.xlim([-4,4])\nplt.ylim([-4,4])\nplt.xlabel('x_values')\nplt.ylabel('y_values')\nplt.legend()\nplt.title('Transformed samples with class labels')\n\nplt.show()\n\n\nfrom matplotlib.mlab import PCA as mlabPCA\n\nmlab_pca = mlabPCA(all_samples.T)\n\nprint('PC axes in terms of the measurement axes scaled by the standard deviations:\\n', mlab_pca.Wt)\n\nplt.plot(mlab_pca.Y[0:20,0],mlab_pca.Y[0:20,1], 'o', markersize=7, color='blue', alpha=0.5, label='class1')\nplt.plot(mlab_pca.Y[20:40,0], mlab_pca.Y[20:40,1], '^', markersize=7, color='red', alpha=0.5, label='class2')\n\nplt.xlabel('x_values')\nplt.ylabel('y_values')\nplt.xlim([-4,4])\nplt.ylim([-4,4])\nplt.legend()\nplt.title('Transformed samples with class labels from matplotlib.mlab.PCA()')\n\nplt.show()\n\n\nfrom sklearn.decomposition import PCA as sklearnPCA\n\nsklearn_pca = sklearnPCA(n_components=2)\nsklearn_transf = sklearn_pca.fit_transform(all_samples.T)\n\nplt.plot(sklearn_transf[0:20,0],sklearn_transf[0:20,1], 'o', markersize=7, color='blue', alpha=0.5, label='class1')\nplt.plot(sklearn_transf[20:40,0], sklearn_transf[20:40,1], '^', markersize=7, color='red', alpha=0.5, label='class2')\n\nplt.xlabel('x_values')\nplt.ylabel('y_values')\nplt.xlim([-4,4])\nplt.ylim([-4,4])\nplt.legend()\nplt.title('Transformed samples with class labels from matplotlib.mlab.PCA()')\n\nplt.show()\n\n\n", "meta": {"hexsha": "8e5874bea5d28dfa7b90519256beeff81d3963e3", "size": 6962, "ext": "py", "lang": "Python", "max_stars_repo_path": "mlcode-python/basic/pca.py", "max_stars_repo_name": "compasses/elastic-spark", "max_stars_repo_head_hexsha": "bef6d70214029833c6a04b6c41fa68c0c23d785a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-11-02T04:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-02T04:38:59.000Z", "max_issues_repo_path": "mlcode-python/basic/pca.py", "max_issues_repo_name": "compasses/elastic-spark", "max_issues_repo_head_hexsha": "bef6d70214029833c6a04b6c41fa68c0c23d785a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mlcode-python/basic/pca.py", "max_forks_repo_name": "compasses/elastic-spark", "max_forks_repo_head_hexsha": "bef6d70214029833c6a04b6c41fa68c0c23d785a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3401015228, "max_line_length": 135, "alphanum_fraction": 0.7045389256, "include": true, "reason": "import numpy", "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620608291781, "lm_q2_score": 0.8918110519076928, "lm_q1q2_score": 0.8559264130491644}}
{"text": "__author__ = 'Randall'\n\n\"\"\"\n    DEMO: basisChebyshev\n    This script provides a few examples on using the basis classes.\n    Last updated: March 15, 2015.\n    Copyright (C) 2014 Randall Romero-Aguilar\n    Licensed under the MIT license, see LICENSE.txt\n\"\"\"\n\nfrom compecon import BasisChebyshev\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\"\"\"\n    EXAMPLE 1:\n        Using BasisChebyshev to interpolate a 1-D function with a Chebyshev basis\n        PROBLEM: Interpolate the function y = f(x) = 1 + sin(2*x) on the domain [0,pi], using 5 Gaussian nodes.\n\"\"\"\n\n# First, create the function f\nf = lambda x: 1 + np.sin(2 * x)\n\n# and the Chebyshev basis B. If the type of nodes is unspecified, Gaussian is computed by default\nF = BasisChebyshev(5, 0, np.pi, f=f)\n\n# Interpolation matrix and nodes: Obtain the interpolation matrix Phi, evaluated at the basis nodes.\n\n# The basis nodes are:\nxnodes = F.nodes\n\n# and the basis coefficients are\nc = F.c\n\n# Next plot the function f and its approximation. To evaluate the function defined by the basis B and coefficients c\n# at values xx we use the interpolation method:\n\n# We also plot the residuals, showing the residuals at the interpolating nodes (zero by construction)\nxx = np.linspace(F.a, F.b, 121)\nf_approx = F(xx)\nfxx = f(xx)\n\nplt.figure()\nplt.subplot(2, 1, 1)\nplt.plot(xx, fxx)\nplt.plot(xx, f_approx)\nplt.legend(['f = 1 + sin(2x)','approx.'])\nplt.title('Chebyshev approximation with 5 nodes')\n\nplt.subplot(2, 1, 2)\nplt.plot(xx, f_approx - fxx)\nplt.title('Residuals using 5 nodes')\n\n# Adjusting the number of nodes: to increase accuracy, we increase the number of nodes in B to 25.\nF = BasisChebyshev(25, 0, np.pi, f=f)\nplt.figure()\nplt.subplot(2,1,1)\nplt.plot(xx, f(xx))\nplt.plot(xx, F(xx))\nplt.legend(['f = 1 + sin(2x)','approx.'])\nplt.title('Chebyshev approximation with 25 nodes')\n\nplt.subplot(2,1,2)\nplt.plot(xx, F(xx) - f(xx), 'r')\nplt.title('Residuals using 25 nodes')\n\n# With previous basis, now compute derivative.\ndf = lambda x: 2 * np.cos(2 * x)\nplt.figure()\nplt.subplot(2, 1, 1)\nplt.plot(xx, df(xx))\nplt.plot(xx, F(xx, 1))  # notice the 1 in Phi(xx,1) to compute first derivative\nplt.legend(['df/dx = 2cos(2x)', 'approx.'])\nplt.title('Chebyshev approximation with 25 nodes')\n\nplt.subplot(2, 1, 2)\nplt.plot(xx, F(xx, 1) - df(xx), 'r')\nplt.title('Residuals using 25 nodes')\n\nplt.show()", "meta": {"hexsha": "1752f6cc64dd31f6835a269043cfacd35e61046c", "size": 2347, "ext": "py", "lang": "Python", "max_stars_repo_path": "compecon/demos/dem01_basis.py", "max_stars_repo_name": "daniel-schaefer/CompEcon-python", "max_stars_repo_head_hexsha": "d3f66e04a7e02be648fc5a68065806ec7cc6ffd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2016-12-14T13:21:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-23T21:04:34.000Z", "max_issues_repo_path": "compecon/demos/dem01_basis.py", "max_issues_repo_name": "daniel-schaefer/CompEcon-python", "max_issues_repo_head_hexsha": "d3f66e04a7e02be648fc5a68065806ec7cc6ffd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-09-10T04:48:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-31T01:36:46.000Z", "max_forks_repo_path": "compecon/demos/dem01_basis.py", "max_forks_repo_name": "daniel-schaefer/CompEcon-python", "max_forks_repo_head_hexsha": "d3f66e04a7e02be648fc5a68065806ec7cc6ffd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-02-25T08:10:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T09:49:16.000Z", "avg_line_length": 29.3375, "max_line_length": 116, "alphanum_fraction": 0.6996165317, "include": true, "reason": "import numpy", "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620539235895, "lm_q2_score": 0.891811054783143, "lm_q1q2_score": 0.8559264096504321}}
{"text": "# THIS...\n# IS.....\n# TRIGGGGGGGGG!\nprint('''\n\nCONSIDER THE FOLLOWING...\n\nImagine coordinates, x, and y\n\n            |y\n            |\n            |\n-----------------------------x\n            |\n            |\n            |\n\nWhat is the most glorious shape in the world?\nWhy, a circle of course!\n\nI can't draw a circle with my keyboard (O, is that right??)\nSo let's plot it\n\n\nOH, btw, we're making a circle with radius = 1\n\nThere's an EXTREMELY FANCY WAY to explain to your fellow mathematicians\nthat your circle has radius 1. You ready? The term is \"UNIT\".\n\nIt is a UNIT circle if it has radius 1.\n\n''')\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Create the x axis, from -1 to 1, including 1 (linspace does this auto)\n\nxs = np.linspace(-1,1,100)  # from -1 to 1, make 100 equally spaced points\n\nys = {'top':[], 'bot':[]}  # create a python dictionary holding the circle's ys\n\n# top half\n\nfor x in xs:\n\n    y_top = + np.sqrt( 1**2 - x**2)\n    y_bot = - np.sqrt( 1**2 - x**2)\n\n    ys['top'].append( y_top )\n    ys['bot'].append( y_bot )\n\nplt.plot(xs, ys['top'])\nplt.plot(xs, ys['bot'])\nplt.show()\n\nprint(\n'''\nNow, all that was a bit tedious wasn't it?\n\nWhat if...\n\nWhat if we could just say \"I WANT A UNIT CIRCLE THAT GOES AROUND ONCE\",\nand it would just... WORK?\n\nHmmm...\n\nIn 'polar' coordinates, instead of using x and y as our \"coordinates\",\nwe can just use \"r\" and \"theta\", or a \"radius\" and an \"angle\"........\n\nSo maybe we can just \"sweep\" over angles, and plot the radii?\n\nSomething like...\n'''\n\n\n''' What is the circumference of a circle?\n\n    ... I hope you remember...\n\n    It's 2 * pi * radius.... Since our radius is 1, what's the circumference?\n\n    2*pi. SO!\n\nAHA!\n\n What if we just define our angles as fractions of the circumference?\n (instead of using degrees)\n\n    So 0 degrees = 0 * 2*pi\n\n    So 45 degrees = (2*pi / 8) =     (pi / 4) <--> 45 deg\n\n    So 90 degrees = (2*pi / 4) =     (pi / 2) <--> 90 deg\n\n    So 180 deg = (2*pi / 2)    =      (pi)    <--> 180 deg\n\n    So 360 deg = (2*pi / 1)    =    (2*pi)    <--> 360 deg\n\n\n    ... FYI these new fancy fractional angles are called 'radians'\n'''\n)\n\nfrom numpy import pi\n\nangles = np.linspace(0, 2*pi, 100)\n\nprint('''\n\nOkay, now how do to translate our new polar coordinates into xs and ys?\n(We need to do this so we can plot...)\n\n''')\n\n# Here's how........\n\nxs = np.cos(angles)  # cosine maps an angle to an X value on the unit circle\nys = np.sin(angles)  # sine maps an angle to a Y value on the unit circle\n\n# tan = sin / cos ........ slope = y / x\n\nplt.plot(xs, ys)\nplt.show()\n\nprint(\n''' Well... That was easy. But what the heck is cos and sine?\n\n    The answer is best seen by drawing triangles inside of circles.\n\n    I shall explain on the white board...!\n\n    -----------------------------------------\n\n    SOH : sin = opposite/hypotenuse\n    CAH : cos = adjacent/hypotenuse\n    TOA : tan = opposite/adjacent\n\n    -----------------------------------------\n\n    Basically,\n\n    x = cos(angle) works because cosine = adjacent / hypotenuse = x / 1\n    y = sin(angle) works because cosine = opposite / hypotenuse = y / 1\n\n    if we draw the triangle like this:\n\n          /|\n    hyp  / |\n        /  | opposite side\n        ----\n        adj\n\n    where (angle) is measured between the adj and hypotenuse sides\n\n    Notice also that:\n\n        x**2 + y**2 = 1\n\n                which means that\n\n        cos(angle)**2 + sin(angle)**2 = 1    (for any angle)\n\n'''\n)\n\nprint(\n'''\n\nCongratulations!\nThat's basically all of the really important stuff about trigonometry!\n\n\nIf you ever want to get the ANGLE, and you know the LENGTH,\n\nuse angle = arccos(length) = acos(length), or\n    angle = arcsin(length) = asin(length), or\n    angle = arctan(length) = atan(length),\n\n    which will all work for a certain range of lengths (not all lengths...)\n\nSome extra tidbits:\n\n    - There are these things called \"trig identities\"...\n    - They are used like crazy in calculus and physics...\n    - Basically, they boil down to equivalent ways to say exactly the same thing\n    - If you want to see most of them, go here:\n        https://en.wikipedia.org/wiki/List_of_trigonometric_identities\n\n'''\n)\n", "meta": {"hexsha": "68952f0c9c656fe32223b5dbbd52dd4f9930ed2d", "size": 4162, "ext": "py", "lang": "Python", "max_stars_repo_path": "Math You Will Actually Use/Week8_HowToTrig.py", "max_stars_repo_name": "jonnyhyman/Programming-Classes", "max_stars_repo_head_hexsha": "f56a9cf90e3b8e4aafad99644f1ed7e87ba14995", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-12-15T01:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T05:23:45.000Z", "max_issues_repo_path": "Math You Will Actually Use/Week8_HowToTrig.py", "max_issues_repo_name": "jonnyhyman/Programming-Classes", "max_issues_repo_head_hexsha": "f56a9cf90e3b8e4aafad99644f1ed7e87ba14995", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math You Will Actually Use/Week8_HowToTrig.py", "max_forks_repo_name": "jonnyhyman/Programming-Classes", "max_forks_repo_head_hexsha": "f56a9cf90e3b8e4aafad99644f1ed7e87ba14995", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-02-15T12:47:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-28T03:01:19.000Z", "avg_line_length": 21.6770833333, "max_line_length": 80, "alphanum_fraction": 0.5985103316, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620608291781, "lm_q2_score": 0.8918110353738529, "lm_q1q2_score": 0.8559263971806121}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"AEOPDay3.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/drive/1EBz2EcAFR7wNNt5BtgNLWoT9kxSkqfy3\n\n# HackerRank Problems Continued\n\nTask 11: Mean, Var, and STD\n\"\"\"\n\nimport numpy as np\n\na = np.array([[1, 2], [3, 4]])\nprint(np.mean(a, axis = 1))\nprint(np.var(a, axis=0))\nprint(np.std(a, axis=None))\n\n\"\"\"Task 12 Dot and Cross\"\"\"\n\n## The dot tool returns the dot product of two arrays\n## The cross tool returns the cross product of two arrays.\nimport numpy as np\nA = np.array([[1, 2], [3, 4]])\nB = np.array([[1, 2], [3, 4]])\nprint(np.dot(A, B))\n#dot is just the matrix\n\n\"\"\"Task 13 Inner and Outer\"\"\"\n\n## The inner tool returns the inner product of two arrays.\n\nimport numpy\n\nA = numpy.array([0, 1])\nB = numpy.array([3, 4])\n\nprint(numpy.inner(A, B))   #Output : 4\n## The outer tool returns the outer product of two arrays.\nimport numpy\n\nA = numpy.array([0, 1])\nB = numpy.array([3, 4])\n\nprint(numpy.outer(A, B))    #Output : [[0 0]\n                            #          [3 4]]\n\nimport numpy as np\nA = np.array([0,1])\nB = np.array([2, 3])\n\nprint(np.inner(A, B))\nprint(np.outer(A, B))\n\n\"\"\"Task 14 Polynomials\"\"\"\n\nimport numpy as np\npoly = np.array([1.1, 2, 3])\nnp.polyval((poly), 0)\n\n\"\"\"The poly tool returns the coefficients of a polynomial with the given sequence of roots.\n - The polyint tool returns an antiderivative (indefinite integral) of a polynomial.\n - The roots tool returns the roots of a polynomial with the given coefficients.\n - The polyder tool returns the derivative of the specified order of a polynomial.\n - The polyval tool evaluates the polynomial at specific value. (used above)\n\"\"\"\n#print numpy.poly([-1, 1, 1, 10])        \n#Output : [  1 -11   9  11 -10]\n\n#why are the outputs that way? are they different points of intersection\n\n\"\"\"Task 15 Linear Algebra\"\"\"\n\nimport numpy as np\n\nA = np.array([[1.1, 1.1], [1.1, 1.1]])\nprint(np.linalg.det(A))\n\n\"\"\"# MatPlotLib\n\nVideo One: Creating + Customizing Plots\n\"\"\"\n\nimport matplotlib\n\nfrom matplotlib import pyplot as plt\n\n# print(plt.style.available)\nplt.style.use('fivethirtyeight')\n# Median Developer Salaries by Age\nages_x = [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]\n\ndev_y = [38496, 42000, 46752, 49320, 53200,\n         56000, 62316, 64928, 67317, 68748, 73752]\n\nplt.plot(ages_x, dev_y, color='k', linestyle = '--' ,label = 'All Devs')\n\n# Median Python Developer Salaries by Age\n## can remobe to keep axis py_dev_x = [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]\npy_dev_y = [45372, 48876, 53850, 57287, 63016,\n            65998, 70003, 70000, 71496, 75370, 83640]\n\nplt.plot(ages_x, py_dev_y, color = '#009000', marker = '*', linewidth=3, label = 'Python')\n\n# Median JavaScript Developer Salaries by Age\njs_dev_y = [37810, 43515, 46823, 49293, 53437,\n            56373, 62375, 66674, 68745, 68746, 74583]\n\nplt.plot(ages_x, js_dev_y, color = '#adad3b', marker = '.', label = 'JavaScript')\n\nplt.xlabel('Ages')\nplt.ylabel('Salary')\nplt.title('Median Salary (USD) by Age')\n\n# If you know the order of which color is which, or just add as new parameter in plt.plot\n# plt.legend(['All Devs','Python']), just legend better bc updates automatically\nplt.legend()\n# format string fmt = '[marker][line][color]'\n\n#plt.grid(True)\nplt.tight_layout()\n\nplt.savefig('plot.png')\n\nplt.show(ages_x, dev_y)\n\n\"\"\"Video 2: Bar Charts and Analyzing Data from CSV\"\"\"\n\nimport matplotlib\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nages_x = [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]\n\nx_indexes = np.arange(len(ages_x))\nwidth = 0.25\n\ndev_y = [38496, 42000, 46752, 49320, 53200,\n         56000, 62316, 64928, 67317, 68748, 73752]\n\nplt.bar(x_indexes - width, dev_y, width=width, color = \"#444444\", label = \"All Devs\") \n\n# Median Python Developer Salaries by Age\npy_dev_y = [45372, 48876, 53850, 57287, 63016,\n            65998, 70003, 70000, 71496, 75370, 83640]\n\nplt.bar(x_indexes, py_dev_y, width=width, color = \"#004400\", label = \"Python\") \n\n# Median JavaScript Developer Salaries by Age\njs_dev_y = [37810, 43515, 46823, 49293, 53437,\n            56373, 62375, 66674, 68745, 68746, 74583]\n\nplt.bar(x_indexes + width, js_dev_y, width=width, color = \"#440000\", label = \"JavaScript\") \n\nplt.xticks(ticks=x_indexes, labels = ages_x)\n\nplt.legend()\n\nimport matplotlib\nimport csv\nimport pandas as pd #open files neater\nimport numpy as np\nfrom collections import Counter\nfrom matplotlib import pyplot as plt\n\n'''with open('data.txt') as csv_file:\n  csv_reader = csv.DictReader(csv_file)'''\n\ndata = pd.read_csv('data.txt')\nids = data['Responder_id']\nlang_responses = data['LanguagesWorkedWith']\n\nlanguage_counter = Counter()\n\n      #replace row with response after use of pandas and cvs_reader with lang_responses\nfor response in lang_responses:   #row also replaced\n  language_counter.update(response.split(';'))\n                      #and remove 'LanguagesWorkedWith idk why\nlanguages =[]\npopularity = []\n\nfor item in language_counter.most_common(15):\n  languages.append(item[0])\n  popularity.append(item[1])\n\n#print(language_counter.most_common(15))\nlanguages.reverse()\npopularity.reverse()\nplt.barh(languages, popularity)\n\n\"\"\"Video 3 Pie Charts\"\"\"\n\nimport matplotlib \nfrom matplotlib import pyplot as plt \n\n# Language Popularity\nslices = [59219, 55466, 47544, 36443, 35917]\nlabels = ['JavaScript', 'HTML/CSS', 'SQL', 'Python', 'Java']\nexplode = [0, 0, 0, 0.1, 0]\n                                                                                      #ask to define percentages\nplt.pie(slices, labels = labels, explode = explode, shadow = True, startangle = 90, autopct = '%1.1f%%',colors = colors, wedgeprops = {'edgecolor' : 'black'})\n\nplt.title(\"My Awesome Pie Chart\")\nplt.show()\n\n\"\"\"Video 4 Stack Plots\"\"\"\n\nimport matplotlib\nfrom matplotlib import pyplot as plt\n\nplt.style.use(\"fivethirtyeight\")\n\n\nminutes = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nplayer1 = [8, 6, 5, 5, 4, 2, 1, 1, 0]\nplayer2 = [0, 1, 2, 2, 2, 4, 4, 4, 4]\nplayer3 = [0, 1, 1, 1, 2, 2, 3, 3, 4]\n\nlabels = ('Player 1', 'Player 2', 'Player 3')\nplt.stackplot(minutes, player1, player2, player3, labels= labels)\n\nplt.legend(loc = (0.07, 0.05))  #google matplotlib legend to adjust coordinates\n\nplt.title(\"My Awesome Stack Plot\")\nplt.tight_layout()\nplt.show()\n\n\"\"\"Filling Area on Line Plots\"\"\"\n\nimport pandas as pd\nimport matplotlib\nfrom matplotlib import pyplot as plt\n\ndata = pd.read_csv('data.csv')\nages = data['Age']\ndev_salaries = data['All_Devs']\npy_salaries = data['Python']\njs_salaries = data['JavaScript']\n\nplt.plot(ages, dev_salaries, color='#444444',\n         linestyle='--', label='All Devs')\n\nplt.plot(ages, py_salaries, label='Python')\n\noverall_median = 57287\n                                    #to change intensity of fill\nplt.fill_between(ages, py_salaries, overall_median, \n                 where = (py_salaries <= overall_median), \n                 interpolate = True, alpha = 0.25, )\nplt.fill_between(ages, py_salaries, overall_median, \n                 where = (py_salaries > overall_median), \n                 color = \"green\",alpha = 0.25)\n\nplt.legend()\n\nplt.title('Median Salary (USD) by Age')\nplt.xlabel('Ages')\nplt.ylabel('Median Salary (USD)')\n\nplt.tight_layout()\n\nplt.show()\n\n## TIMESTAMP: 11:30", "meta": {"hexsha": "66392cac9719ff46e49173c2740791d632d10fbc", "size": 7214, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tutorial and Exercises/aeopday3.py", "max_stars_repo_name": "isabel-peralta/AEOP-2020", "max_stars_repo_head_hexsha": "6122e1f828bb35abdae12111167d76bb7160dea0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tutorial and Exercises/aeopday3.py", "max_issues_repo_name": "isabel-peralta/AEOP-2020", "max_issues_repo_head_hexsha": "6122e1f828bb35abdae12111167d76bb7160dea0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tutorial and Exercises/aeopday3.py", "max_forks_repo_name": "isabel-peralta/AEOP-2020", "max_forks_repo_head_hexsha": "6122e1f828bb35abdae12111167d76bb7160dea0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0187265918, "max_line_length": 158, "alphanum_fraction": 0.6660659828, "include": true, "reason": "import numpy", "num_tokens": 2202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745211, "lm_q2_score": 0.8918110353738529, "lm_q1q2_score": 0.8559263920485454}}
{"text": "import sympy\n\nx = sympy.symbols('x')\n\nf = (x**2 - 2*x)*sympy.exp(3 - x)\n\nfp = sympy.simplify(sympy.diff(f)) # (x*(2 - x) + 2*x - 2)*exp(3 - x)\n\nfp2 = -(x**2 - 4*x + 2)*sympy.exp(3 - x)\n\nsympy.simplify(fp2 - fp) == 0  # True\n\n\nF = sympy.integrate(f, x)  # -x**2*exp(3 - x)\n", "meta": {"hexsha": "bf089ad07e7657d03418941a42831d5dcf128b64", "size": 272, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter 03/symbolic-calculus-using-sympy.py", "max_stars_repo_name": "arifmudi/Applying-Math-with-Python", "max_stars_repo_head_hexsha": "abeb6b0a9bcfa8b21092b9793d4e691cf5a146bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2020-07-23T14:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T07:00:17.000Z", "max_issues_repo_path": "Chapter 03/symbolic-calculus-using-sympy.py", "max_issues_repo_name": "arifmudi/Applying-Math-with-Python", "max_issues_repo_head_hexsha": "abeb6b0a9bcfa8b21092b9793d4e691cf5a146bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 03/symbolic-calculus-using-sympy.py", "max_forks_repo_name": "arifmudi/Applying-Math-with-Python", "max_forks_repo_head_hexsha": "abeb6b0a9bcfa8b21092b9793d4e691cf5a146bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2020-07-22T11:09:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T16:59:53.000Z", "avg_line_length": 18.1333333333, "max_line_length": 69, "alphanum_fraction": 0.5183823529, "include": true, "reason": "import sympy", "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668690081642, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.855918345556719}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSimulazione 8 Settembre 2020\r\n\r\nFunzione e radici\r\n\"\"\"\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport sympy as sym\r\nfrom scipy import optimize \r\nimport math\r\n\r\n# L'unico metodo a convergenza quadratica è Newton\r\ndef newton(fname, fpname, x0, m,  tol, nMaxIt):\r\n    xk = []\r\n    it = 0\r\n    if abs(fpname(x0)) <= np.spacing(1):\r\n        print(\"Derivata nulla in x0\")\r\n        return [], 0, []\r\n    else:\r\n        d = (fname(x0)/ fpname(x0))\r\n        x1 = x0 - d*m\r\n        xk.append(x1)\r\n        it += 1\r\n        while it < nMaxIt and abs(fname(x1)) >= tol and abs(d) >= tol * abs(x1):\r\n            x0 = x1\r\n            if abs(fpname(x0)) <= np.spacing(1):\r\n                print(\"Derivata nulla in x0\")\r\n                return x1, it, xk\r\n            d = (fname(x0)/ fpname(x0))\r\n            x1 = x0 - d*m\r\n            xk.append(x1)\r\n            it += 1\r\n            \r\n        if it == nMaxIt:\r\n            print(\"Numero massimo di iterazioni raggiunto\")\r\n        return x1, it, xk\r\n\r\n# Definisco Funzione e derivata \r\nx = sym.Symbol(\"x\")\r\nxx = np.linspace(1, 3, 100)\r\nfx = x - (2 * sym.sqrt(x - 1))\r\ndfx = sym.diff(fx, x, 1)\r\n\r\nf = sym.utilities.lambdify(x, fx, np)\r\nd = sym.utilities.lambdify(x, dfx, np)\r\n\r\n# Plotto la funzione per cercare le radici\r\nplt.plot(xx, f(xx))\r\nplt.title(\"Funzione\")\r\nplt.show()\r\n\r\n# Noto che la funzione vicino al 2 vale 0\r\nzero = optimize.fsolve(f, 2.0)\r\nprint(zero)\r\n\r\nx1, it, xks = newton(f, d, 3.0, 2.0, 1.e-12, 500)\r\nprint(\"La derivata nel punto è \", d(x1))\r\n# Stimo l'ordine di convergenza del metodo\r\nnumO = math.log(abs(xks[-2] - xks[-1]) / abs(xks[-3] - xks[-2]))\r\ndenO = math.log(abs(xks[-3] - xks[-2]) / abs(xks[-4] - xks[-3]))\r\nordine = numO / denO\r\nprint(f\"L'ordine di convergenza del metodo è {ordine}\")\r\n\r\nplt.semilogy(np.arange(it), xks)\r\nplt.title(\"Iterazioni\")\r\nplt.show()\r\n\r\n\"\"\"\r\n    Osservazioni: il metodo di Newton inizialmente con la radice \"2\" aveva un ordine\r\n    di convergenza pari a 1, quindi la radice ha molteplicità m, provando poi ad \r\n    implementare la versione modificata del metodo ho ottenuto un ordine di convergenza\r\n    pari a 2, utilizzando m = 2 dunque la radice ha molteplicità pari a 2\r\n    Inoltre il metodo non converge usando '1' come valore di innesco in quanto quest'ultimo\r\n    ha una derivata prossima allo 0\r\n\"\"\"", "meta": {"hexsha": "be550d322210e6f3602bb3d35a14706d06d0180f", "size": 2340, "ext": "py", "lang": "Python", "max_stars_repo_path": "simulazioni/08-Sett_2020-01-FunzioneERadici.py", "max_stars_repo_name": "luigi-borriello00/Metodi_SIUMerici", "max_stars_repo_head_hexsha": "cf1407c0ad432a49a96dcd08303213e48723c57a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-06-23T14:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T08:39:27.000Z", "max_issues_repo_path": "simulazioni/08-Sett_2020-01-FunzioneERadici.py", "max_issues_repo_name": "luigi-borriello00/Metodi_SIUMerici", "max_issues_repo_head_hexsha": "cf1407c0ad432a49a96dcd08303213e48723c57a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulazioni/08-Sett_2020-01-FunzioneERadici.py", "max_forks_repo_name": "luigi-borriello00/Metodi_SIUMerici", "max_forks_repo_head_hexsha": "cf1407c0ad432a49a96dcd08303213e48723c57a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7894736842, "max_line_length": 92, "alphanum_fraction": 0.5901709402, "include": true, "reason": "import numpy,from scipy,import sympy", "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920262, "lm_q2_score": 0.9073122182277757, "lm_q1q2_score": 0.8559107805536147}}
{"text": "# Necessary import(s)\nimport numpy as np\n\n# The helper methods used by the learning methods above are implemented below:\n\ndef compute_error_vector(y, tx, w):\n    \"\"\"\n    Computes the error vector that is defined as y - tx . w\n    Args:\n        y: labels \n        tx: features\n        w: weight vector\n    Returns:\n        error_vector: the error vector defined as y - tx.dot(w)\n    \"\"\"\n    return y - tx.dot(w)\n\ndef compute_mse(error_vector):\n    \"\"\"\n    Computes the mean squared error for a given error vector.\n    Args:\n        error_vector: error vector computed for a specific dataset and model\n    Returns:\n        mse: numeric value of the mean squared error\n    \"\"\"\n    return np.mean(error_vector ** 2) / 2\n\ndef compute_gradient(tx, error_vector):\n    \"\"\"\n    Computes the gradient for the mean squared error loss function.\n    Args:\n        y: labels\n        error_vector: error vector computed for a specific data set and model\n    Returns:\n        gradient: the gradient vector computed according to its definition\n    \"\"\"\n    return - tx.T.dot(error_vector) / error_vector.size\n\ndef build_polynomial(x, degree):\n    \"\"\"\n    Extends the feature matrix, x, by adding a polynomial basis of the given degree.\n    Args:\n        x: features\n        degree: degree of the polynomial basis\n    Returns:\n        augmented_x: expanded features based on a polynomial basis\n    \"\"\"\n    num_cols = x.shape[1] if len(x.shape) > 1 else 1\n    augmented_x = np.ones((len(x), 1))\n    for col in range(num_cols):\n        for degree in range(1, degree + 1):\n            if num_cols > 1:\n                augmented_x = np.c_[augmented_x, np.power(x[ :, col], degree)]\n            else:\n                augmented_x = np.c_[augmented_x, np.power(x, degree)]\n        if num_cols > 1 and col != num_cols - 1:\n            augmented_x = np.c_[augmented_x, np.ones((len(x), 1))]\n    return augmented_x\n\ndef compute_rmse(loss_mse): \n    \"\"\"\n    Computes the root mean squared error.\n    Args:\n        loss_mse: numeric value of the mean squared error loss\n    Returns:\n        loss_rmse: numeric value of the root mean squared error loss\n    \"\"\"\n    return np.sqrt(2 * loss_mse)\n    \ndef sigmoid(t):\n    \"\"\"\n    Applies the sigmoid function to a given input t.\n    Args:\n        t: the given input to which the sigmoid function will be applied.\n    Returns:\n        sigmoid_t: the value of sigmoid function applied to t\n    \"\"\"\n    return 1. / (1. + np.exp(-t))\n\ndef compute_logistic_loss(y, tx, w):\n    \"\"\"\n    Computes the loss as the negative log likelihood of picking the correct label.\n    Args:\n        y: labels \n        tx: features\n        w: weight vector\n    Returns:\n        loss: the negative log likelihood of picking the correct label\n    \"\"\"\n    tx_dot_w = tx.dot(w)\n    return np.sum(np.log(1. + np.exp(tx_dot_w)) - y * tx_dot_w)\n\ndef compute_logistic_gradient(y, tx, w):\n    \"\"\"\n    Computes the gradient of the loss function used in logistic regression.\n    Args:\n        y: labels \n        tx: features\n        w: weight vector\n    Returns:\n        logistic_gradient: the gradient of the loss function used in \n            logistic regression.\n    \"\"\"\n    return tx.T.dot(sigmoid(tx.dot(w)) - y)\n\ndef penalized_logistic_regression(y, tx, w, lambda_):\n    \"\"\"\n    Adds the penalization term (2-norm of w vector) on top of the normal\n    logistic loss. Computes the modified loss and gradient.\n    Args:\n        y: labels \n        tx: features\n        w: weight vector\n    Returns:\n        loss: the modified version of the normal logistic loss\n        logistic_gradient: the gradient of modified loss function used in \n            penalized logistic regression.\n    \"\"\"\n    loss = compute_logistic_loss(y, tx, w) + (lambda_ / 2) * w.T.dot(w)\n    gradient = compute_logistic_gradient(y, tx, w) + lambda_ * w\n    return loss, gradient\n\ndef cross_terms(x, x_initial):\n    \"\"\"\n    Adds the multiplication of different features as new features.\n    Args:\n        x: the given feature matrix\n        x_initial: the features whose multiplications will be added\n    Returns:\n        x_cross_terms: feature matrix with cross terms\n    \"\"\"\n    for col1 in range(x_initial.shape[1]):\n        for col2 in np.arange(col1 + 1, x_initial.shape[1]):\n            if col1 != col2:\n                x = np.c_[x, x_initial[:, col1] * x_initial[:, col2]]\n    return x\n\ndef log_terms(x, x_initial):\n    \"\"\"\n    Adds the logarithms of features as new features.\n    Args:\n        x: the given feature matrix\n        x_initial: the features whose logarithms will be added\n    Returns:\n        x_log_terms: feature matrix with logarithms\n    \"\"\"\n    for col in range(x_initial.shape[1]):\n        current_col = x_initial[:, col]\n        current_col[current_col <= 0] = 1\n        x = np.c_[x, np.log(current_col)]\n    return x\n\ndef sqrt_terms(x, x_initial):\n    \"\"\"\n    Adds the square roots of features as new features.\n    Args:\n        x: the given feature matrix\n        x_initial: the features whose square roots will be added\n    Returns:\n        x_sqrt_terms: feature matrix with square roots\n    \"\"\"\n    for col in range(x_initial.shape[1]):\n        current_col = np.abs(x_initial[:, col])\n        x = np.c_[x, np.sqrt(current_col)]\n    return x\n\ndef apply_trigonometry(x, x_initial):\n    \"\"\"\n    Adds the sin and cos of features as new features.\n    Args:\n        x: the given feature matrix\n        x_initial: the features whose sin and cos will be added\n    Returns:\n        x_sqrt_terms: feature matrix with sine values\n    \"\"\"\n    for col in range(x_initial.shape[1]):\n        x = np.c_[x, np.sin(x_initial[:, col])]\n        x = np.c_[x, np.cos(x_initial[:, col])]\n    return x\n\ndef feature_engineering(x, degree, has_angles = False):\n    \"\"\"\n    Builds a polynomial with the given degree from the initial features,\n    add the cross terms, logarithms and square roots of the initial features\n    as new features. Also includes the sine of features as an option.\n    Args:\n        x: features\n        degree: degree of the polynomial basis\n        has_angles: Boolean value to determine including sin and cos of features\n    Returns:\n        x_engineered: engineered features\n    \"\"\"\n    x_initial = x\n    x = build_polynomial(x, degree)\n    x = cross_terms(x, x_initial)\n    x = log_terms(x, x_initial)\n    x = sqrt_terms(x, x_initial)\n    if has_angles:\n        x = apply_trigonometry(x, x_initial)\n    return x", "meta": {"hexsha": "e9517f3ae16fa51d79b8f45b68d57e96782401fa", "size": 6399, "ext": "py", "lang": "Python", "max_stars_repo_path": "Scripts/helper_functions.py", "max_stars_repo_name": "efeacer/EPFL_ML_Project1", "max_stars_repo_head_hexsha": "bc7ba325a1bdcdcc257354ee684b97c7b1a70547", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-11T15:22:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-17T18:44:50.000Z", "max_issues_repo_path": "Scripts/helper_functions.py", "max_issues_repo_name": "efeacer/EPFL_ML_Project1", "max_issues_repo_head_hexsha": "bc7ba325a1bdcdcc257354ee684b97c7b1a70547", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scripts/helper_functions.py", "max_forks_repo_name": "efeacer/EPFL_ML_Project1", "max_forks_repo_head_hexsha": "bc7ba325a1bdcdcc257354ee684b97c7b1a70547", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.995, "max_line_length": 84, "alphanum_fraction": 0.6352555087, "include": true, "reason": "import numpy", "num_tokens": 1534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138559, "lm_q2_score": 0.907312221360624, "lm_q1q2_score": 0.8559107791736872}}
{"text": "import math\nimport numpy as np\n\ndef Rastrigin(n):\n    #f(x) = A*n + [sum (x_i² - A*cos(2*pi*x_i)) i = 1 .. n]\n    A = 10\n    def f(x):\n        return A*n + sum(map(lambda x: x**2-A*math.cos(2*math.pi*x), x))\n    def grad_f(x):\n        grad = []\n        for i in range(len(x)):\n            grad.append(2*x[i] + 2*math.pi*A*math.sin(2*math.pi*x[i]))\n        return np.array(grad)\n    def hess_f(x):\n        hess = [[2+(A*2*math.pi)**2*math.cos(2*math.pi*x[i]) if i==j else 0 for j in range(n)] for i in range(n)]\n        return np.array(hess)\n    return {\"function\": f, \"gradient\":grad_f, \"hessian\":hess_f, \"search_region\": None, \"global_minimum\":[0 for i in range(n)], \"name\":\"Rastrigin\"}\n\ndef Rosenbrock(n):\n    # f(x, y) = 100(y-x²)² + (1-x)²\n    if n != 2:\n        return None\n    def f(entry):\n        x, y = entry[0], entry[1]\n        return 100*(y-x**2)**2 + (1-x)**2\n    def grad_f(entry):\n        #return aprox_grad(f, entry)\n        x, y = entry[0], entry[1]\n        return np.array([2*(200*x**3-200*x*y+x-1), 200*(y-x**2)])\n    def hess_f(entry):\n        x, y = entry[0], entry[1]\n        return np.array([[-400*(y-x**2)+800*x**2+2, -400*x],[-400*x, 200]])\n    return {\"function\": f, \"gradient\": grad_f, \"hessian\": hess_f, \"search_region\": None, \"global_minimum\":[1 for i in range(n)], \"name\":\"Rosenbrock\"}\n\ndef Sphere(n):\n    # f(x) = sum x_i² i = 1 .. n\n    def f(x):\n        return sum(map(lambda it: it**2, x))\n    def grad_f(x):\n        grad = [2*x[i] for i in range(n)]\n        return np.array(grad)\n    def hess_f(x):\n        hess = [[2 if i==j else 0 for j in range(n)] for i in range(n)]\n        return np.array(hess)\n    return {\"function\": f, \"gradient\":grad_f, \"hessian\":hess_f, \"search_region\":None, \"global_minimum\":[0,0], \"name\":\"Sphere\"}\n\ndef Goldstein_price(n):\n    if n != 2:\n        return None\n    def f(entry):\n        x, y = entry[0], entry[1]\n        return (1+(x+y+1)**2*(19-14*x+3*x**2-14*y+6*x*y+3*y**2))*(30+(2*x-3*y)**2*(18-32*x+12*x**2+48*y-36*x*y+27*y**2))\n    def grad_f(entry):\n        return aprox_grad(f, entry)\n    return {\"function\": f, \"gradient\":grad_f, \"hessian\":None, \"search_region\": [-2,2], \"global_minimum\":[0,-1], \"name\":\"Goldstein price\"}\n \ndef aprox_deriv(f, x, h=10**(-4)):  # symetric difference quotient\n    dy = f(x+h) - f(x-h)\n    return dy/(2*h)\n\ndef aprox_grad(f, x):\n    grad = []\n    for i in range(len(x)):\n        fs = lambda inp: f([*x[0:i], inp, *x[(i+1):len(x)]])\n        grad.append(aprox_deriv(fs, x[i]))\n    #fs = [lambda inp: f([*x[0:i], inp, *x[(i+1):len(x)]]) for i in range(len(x))]\n    return np.array(grad)\n\ndef sph(x):\n    return x[0]**2+x[1]**2\n\nfns = [Rastrigin, Rosenbrock, Sphere, Goldstein_price]", "meta": {"hexsha": "7532ed912e7ed71acaff97d68590d9285432a12f", "size": 2680, "ext": "py", "lang": "Python", "max_stars_repo_path": "test_functions.py", "max_stars_repo_name": "gabriel-valle/minimizer", "max_stars_repo_head_hexsha": "eb3e42ca5fa4667c712ad2228a6c8af3bdb73185", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_functions.py", "max_issues_repo_name": "gabriel-valle/minimizer", "max_issues_repo_head_hexsha": "eb3e42ca5fa4667c712ad2228a6c8af3bdb73185", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_functions.py", "max_forks_repo_name": "gabriel-valle/minimizer", "max_forks_repo_head_hexsha": "eb3e42ca5fa4667c712ad2228a6c8af3bdb73185", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2222222222, "max_line_length": 149, "alphanum_fraction": 0.5440298507, "include": true, "reason": "import numpy", "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966410494349896, "lm_q2_score": 0.8856314783461303, "lm_q1q2_score": 0.855883554800313}}
{"text": "from statistics import mean\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nstyle.use('ggplot')\n\n\ndef create_dataset(hm,variance,step=2,correlation=False):\n    val = 1\n    ys = []\n    for i in range(hm):\n        y = val + random.randrange(-variance,variance)\n        ys.append(y)\n        if correlation and correlation == 'pos':\n            val+=step\n        elif correlation and correlation == 'neg':\n            val-=step\n\n    xs = [i for i in range(len(ys))]\n    \n    return np.array(xs, dtype=np.float64),np.array(ys,dtype=np.float64)\n\ndef best_fit_slope_and_intercept(xs,ys):\n    m = (((mean(xs)*mean(ys)) - mean(xs*ys)) /\n         ((mean(xs)*mean(xs)) - mean(xs*xs)))\n    \n    b = mean(ys) - m*mean(xs)\n\n    return m, b\n\n\ndef coefficient_of_determination(ys_orig,ys_line):\n    y_mean_line = [mean(ys_orig) for y in ys_orig]\n\n    squared_error_regr = sum((ys_line - ys_orig) * (ys_line - ys_orig))\n    squared_error_y_mean = sum((y_mean_line - ys_orig) * (y_mean_line - ys_orig))\n\n    print(squared_error_regr)\n    print(squared_error_y_mean)\n\n    r_squared = 1 - (squared_error_regr/squared_error_y_mean)\n\n    return r_squared\n\n\nxs, ys = create_dataset(40,40,2,correlation='pos')\nm, b = best_fit_slope_and_intercept(xs,ys)\nregression_line = [(m*x)+b for x in xs]\nr_squared = coefficient_of_determination(ys,regression_line)\nprint(r_squared)\n\nplt.scatter(xs,ys,color='#003F72', label = 'data')\nplt.plot(xs, regression_line, label = 'regression line')\nplt.legend(loc=4)\nplt.show()", "meta": {"hexsha": "160a31a0cce9732bab113ee01248f9a349670fab", "size": 1530, "ext": "py", "lang": "Python", "max_stars_repo_path": "Linear_regression_algorithm.py", "max_stars_repo_name": "DivyaKrishnani/Linear-Regression-Algorithm-from-scratch", "max_stars_repo_head_hexsha": "083922cb9967c235a768457283dc8995260c9508", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-24T21:57:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T21:57:26.000Z", "max_issues_repo_path": "Regression/lin_reg_classifier.py", "max_issues_repo_name": "SuperSaiyan-God/Machine-Learning", "max_issues_repo_head_hexsha": "cb6c3859c8091a43d8a7ffd8f8d8f3437ba7a172", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Regression/lin_reg_classifier.py", "max_forks_repo_name": "SuperSaiyan-God/Machine-Learning", "max_forks_repo_head_hexsha": "cb6c3859c8091a43d8a7ffd8f8d8f3437ba7a172", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-01T08:21:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T08:21:10.000Z", "avg_line_length": 27.3214285714, "max_line_length": 81, "alphanum_fraction": 0.6758169935, "include": true, "reason": "import numpy", "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104904802131, "lm_q2_score": 0.8856314647623015, "lm_q1q2_score": 0.8558835382456453}}
{"text": "import numpy as np\n\n\ndef compute_sides(coord):\n\n    ax = coord[0, 0]\n    ay = coord[1, 0]  # Coordinates of the point A\n    bx = coord[0, 1]\n    by = coord[1, 1]  # Coordinates of the point B\n    cx = coord[0, 2]\n    cy = coord[1, 2]  # Coordinates of the point C\n\n    ab = compute_length(ax, ay, bx, by)\n    bc = compute_length(bx, by, cx, cy)\n    ca = compute_length(cx, cy, ax, ay)\n    return ab, bc, ca\n\n\ndef compute_length(p1x, p1y, p2x, p2y):\n    return np.sqrt(np.power(p1x-p2x, 2)+np.power(p1y-p2y, 2))\n\n\ndef compute_area(coord):\n    \"\"\" make sure the triangle exists\"\"\"\n    [a, b, c] = sorted(compute_sides(coord))\n    if a + b - c < np.finfo(float).eps:\n        return 0\n    s = (a + b + c) / 2\n    return (s*(s-a)*(s-b)*(s-c)) ** 0.5\n\n\ndef circum_inside(coord):\n    ax = coord[0, 0]\n    ay = coord[1, 0]  # Coordinates of the point A\n    bx = coord[0, 1]\n    by = coord[1, 1]  # Coordinates of the point B\n    cx = coord[0, 2]\n    cy = coord[1, 2]  # Coordinates of the point C\n\n    d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by))\n\n    # Coordinates of the circumcenter\n    ux = ((ax * ax + ay * ay) * (by - cy) + (bx * bx + by * by)\n          * (cy - ay) + (cx * cx + cy * cy) * (ay - by)) / d\n    uy = ((ax * ax + ay * ay) * (cx - bx) + (bx * bx + by * by)\n          * (ax - cx) + (cx * cx + cy * cy) * (bx - ax)) / d\n\n    # Radius of the circle\n    r = np.sqrt((ax - ux)**2 + (ay - uy)**2)\n\n    # Determine whether or not the circumcircle is covered by the unit circle\n    area = compute_area(coord)\n    if np.sqrt(ux**2+uy**2) + r <= 1 and area > np.finfo(float).eps:\n        return True\n\n\ndef is_inside(a):\n    return a[0]**2 + a[1]**2 <= 1\n\n\nN = 10**6  # Number of Monte Carlo samples in both methods\n\n# Generate samples by rejecting/accepting\n\ncount = 0  # Initialize the number of desired groups\nk = 0\ndata_inside = np.zeros((2, 3))\n\nwhile k <= 3*N:\n    pt = np.random.uniform(-1, 1, 2)  # draw one point\n    if is_inside(pt):  # Determine if the point lies inside the unit circle\n        s = k % 3\n        data_inside[0, s] = pt[0]\n        data_inside[1, s] = pt[1]\n        if k % 3 == 2 and circum_inside(data_inside):\n            count += 1\n        k += 1\n\nper_rej = count / N\n\n# Generate samples by polar coordinates\nct = 0  # Initialize the number of desired groups\nfor i in range(N):\n    data_polar = np.array([np.sqrt(np.random.random(3)),\n                           np.random.uniform(-np.pi, np.pi, 3)])\n    # Tranform polar coornates to cartesian coordinates\n    sp = data_polar.copy()\n    sc = np.array([sp[0, :]*np.cos(sp[1, ]), sp[0, :]*np.sin(sp[1, ])])\n    if circum_inside(sc):\n        ct += 1\n\nper_polar = ct / N\n\nprint(\"The Monte Carlo method (N={}) tell the answer is:\".format(N))\nprint(\"polar     coordinates: {:.6f}\".format(per_polar))\nprint(\"Cartesian coordinates: {:.6}\".format(per_rej))\nprint(\"But formula 2*pi/15  : {:.6}\".format(2*np.pi/15))\n", "meta": {"hexsha": "64c7f21c80518ea5ea074edbbb4d481d98add071", "size": 2897, "ext": "py", "lang": "Python", "max_stars_repo_path": "00.Unsorted/CircleProblem.py", "max_stars_repo_name": "cuicaihao/Data_Science_Python", "max_stars_repo_head_hexsha": "ca4cb64bf9afc1011c192586362d0dd036e9441e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-04-26T12:11:41.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-09T19:37:57.000Z", "max_issues_repo_path": "00.Unsorted/CircleProblem.py", "max_issues_repo_name": "cuicaihao/Data_Science_Python", "max_issues_repo_head_hexsha": "ca4cb64bf9afc1011c192586362d0dd036e9441e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "00.Unsorted/CircleProblem.py", "max_forks_repo_name": "cuicaihao/Data_Science_Python", "max_forks_repo_head_hexsha": "ca4cb64bf9afc1011c192586362d0dd036e9441e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-10-09T19:37:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-23T11:31:16.000Z", "avg_line_length": 29.5612244898, "max_line_length": 77, "alphanum_fraction": 0.562996203, "include": true, "reason": "import numpy", "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.9005297874526776, "lm_q1q2_score": 0.8558733913302776}}
{"text": "import math\nfrom datetime import date, timedelta\nfrom scipy import special\nfrom sys import maxsize\nimport itertools\n\ndef sphere_volume(r):\n    \"\"\" a function that computes the volume of a sphere, given its radius r. \"\"\"\n    return 4/3*math.pi*r**3\n\n\ndef quadratic_equation(a, b, c):\n    \"\"\" a function that computes the real roots of a given quadratic equation a*X^2+b*X+c=0. \"\"\"\n    d = math.sqrt(b**2-4*a*c)\n\n    r1 = (-b+d)/(2*a)\n    r2 = (-b-d)/(2*a)\n\n    return (r1, r2)\n\n\ndef number_of_zeros(lst):\n    \"\"\"  a function that returns the number of zeros in a given simple list of numbers lst. \"\"\"\n    return len(list(filter(lambda x: x == 0, lst)))\n\n\ndef draw_pascal(n):\n    \"\"\" a function that takes an integer n as a parameter and prints the first n rows of the Pascal's triangle. \"\"\"\n    # Iterate through every line\n    # and print entries in it\n    for line in range(0, n):\n\n        # Every line has number of\n        # integers equal to line\n        # number\n        for i in range(0, line + 1):\n            print(bc(line, i), \" \", \"\")\n        # '/n'\n        print()\n\n\ndef euler():\n    \"\"\" returns the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0, where each \"_\" is a single digit.\"\"\"\n\n\ndef days(date1, date2):\n    \"\"\"a function that takes two dates, date1 and date2, in some format, and returns the number of days from date1 to date2, inclusive.\"\"\"\n\n    # this will give you a list containing all of the dates\n    numDays = [str(date1 + timedelta(days=x))\n               for x in range((date2-date1).days + 1)]\n\n    return \"\\n\".join(numDays)\n\n\ndef remove_consecutive_dups(lst):\n    \"\"\" return a copy of lst with consecutive duplicates of elements eliminated. For example, for lst = [a, a, a, a, b, c, c, a, a, d, e, e, e, e], the returned list is [a, b, c, a, d, e]. \"\"\"\n    return [v for i, v in enumerate(lst) if i == 0 or v != lst[i-1]]\n\n\ndef remove_dups(lst):\n    \"\"\" return a copy of lst with duplicates of elements eliminated. For example, for lst = [a, a, a, a, b, c, c, a, a, d, e, e, e, e], the returned list is [a, b, c, d, e]. \"\"\"\n    s = sorted(lst)\n    return [v for i, v in enumerate(s) if i == 0 or v != s[i-1]]\n\n\ndef replicate(lst, n):\n    \"\"\" Replicate each of the elements of lst a given number of times. For example, for lst = [a, b, c] and n = 3, the returned list is [a, a, a, b, b, b, c, c, c]. \"\"\"\n    def rep_helper(val, n):\n        i = 0\n        v = \"\"\n        while i < n:\n            v = v + val\n            i += 1\n        return v\n    list_of_lists = [list(rep_helper(a, n)) for a in lst]\n    return [val for sublist in list_of_lists for val in sublist]\n\n\ndef split_list(lst, n):\n    \"\"\" split lst into two parts with the first part having n elements, and return a list that contains these two parts. \"\"\"\n    return [ lst[:n+1], lst[n+2:] ]\n\ndef min_max_median(lst):\n    \"\"\" a function that takes a simple list of numbers lst as a parameter and returns a list with the min, max, and the median of lst. \"\"\"\n    s = sorted(lst)\n    n = len(s)\n    return [ s[0], s[-1], s[n//2] if n % 2 == 1  else (s[n//2 - 1] + s[n//2]) / 2]\n\n\ndef bc(n, k):\n    \"\"\" return the binomial coefficient \"n choose k\". Can you figure out a method that is less likely to cause an overflow than using the formula(n*(n-1)*...*(n-k+1))/(k*(k-1)*...*2)? \"\"\"\n\n    return special.binom(n, k)\n\n\ndef subsets(s, n):\n    \"\"\" return the set of n-element subsets of s. \"\"\"\n    return list(itertools.combinations(s, n)) \n\ndef max_subarray(arr):\n    \"\"\" return a contiguous subarray within arr which has the largest sum. \"\"\"\n    max_so_far = -maxsize - 1\n    max_ending_here = 0\n    max_itr = 0\n    min_itr = 0\n\n    for i in range(0, len(arr)):\n        max_ending_here = max_ending_here + arr[i]\n        if (max_so_far < max_ending_here):\n            max_so_far = max_ending_here\n            temp = i\n        if (temp > max_itr):\n            min_itr = max_itr\n            max_itr = temp\n\n        if max_ending_here < 0:\n            max_ending_here = 0\n    return arr[min_itr:max_itr + 1]\n", "meta": {"hexsha": "6504ee1343f4f21456d3702f92f175343709c3ef", "size": 4011, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "sedmo/python-challenge", "max_stars_repo_head_hexsha": "1b092d9ac24b4903e5884a33f077cfea911972db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-01T00:07:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-01T00:07:12.000Z", "max_issues_repo_path": "main.py", "max_issues_repo_name": "sedmo/python-challenge", "max_issues_repo_head_hexsha": "1b092d9ac24b4903e5884a33f077cfea911972db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "sedmo/python-challenge", "max_forks_repo_head_hexsha": "1b092d9ac24b4903e5884a33f077cfea911972db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.425, "max_line_length": 192, "alphanum_fraction": 0.6048366991, "include": true, "reason": "from scipy", "num_tokens": 1170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410972802222, "lm_q2_score": 0.9005297861178929, "lm_q1q2_score": 0.8558733900616835}}
{"text": "#-------------------------------------------------------------------------\n# Note: please don't use any additional package except the following packages\nimport numpy as np\nimport math\n#-------------------------------------------------------------------------\n'''\n    Problem 1: PCA\n    In this problem, you will implement a version of the principal component analysis method to reduce the dimensionality of data.\n    You could test the correctness of your code by typing `nosetests -v test1.py` in the terminal.\n\n    Notations:\n            ---------- input data ------------------------\n            n: the number of data instances (for example, # of images), an integer scalar.\n            p: the number of dimensions (for example, # of pixels in each image), an integer scalar.\n            X: the feature matrix, a float numpy matrix of shape n by p.\n            ---------- computed data ----------------------\n            mu: the average vector of matrix X, a numpy float matrix of shape 1 by p.\n                Each element mu[0,i] represents the average value in the i-th column of matrix X.\n            Xc: the centered matrix X, a numpy float matrix of shape n by p.\n                Each column has a zero mean value.\n            C:  the covariance matrix of matrix X, a numpy float matrix of shape p by p.\n            k:  the number of dimensions to reduce to (k should be smaller than p), an integer scalar\n            E:  the eigen vectors of matrix X, a numpy float matrix of shape p by p.\n                Each column of E corresponds to an eigen vector of matrix X.\n            v:  the eigen values of matrix X, a numpy float array of length p.\n                Each element corresponds to an eigen value of matrix X. E and v are paired.\n            Xp: the projected feature matrix with reduced dimensions, a numpy float matrix of shape n by k.\n             P: the projection matrix, a numpy float matrix of shape p by k.\n            -----------------------------------------------\n'''\n\n#--------------------------\ndef centering_X(X):\n    '''\n        Centering matrix X, so that each column has zero mean.\n        Input:\n            X:  the feature matrix, a float numpy matrix of shape n by p. Here n is the number of data records, p is the number of dimensions.\n        Output:\n            Xc:  the centered matrix X, a numpy float matrix of shape n by p.\n            mu:  the average row vector of matrix X, a numpy float matrix of shape 1 by p.\n        Note: please don't use the np.cov() function. There seems to be a bug in their code which will result in an error in later test cases.\n              Please implement this function only using basic numpy functions, such as np.mean().\n    '''\n\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n    n, p = X.shape\n\n    _1 = np.ones(n)\n\n    mu = 1/n * np.dot(_1, X)\n    Xc = X - mu\n\n    #########################################\n    return Xc, mu\n\n\n#--------------------------\ndef compute_C(Xc):\n    '''\n        Compute the covariance matrix C.\n        Input:\n            Xc:  the centered feature matrix, a float numpy matrix of shape n by p. Here n is the number of data records, p is the number of dimensions.\n        Output:\n            C:  the covariance matrix, a numpy float matrix of shape p by p.\n        Note: please don't use the np.cov() function here. Implement the function using matrix multiplication.\n    '''\n\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n    n, p = Xc.shape\n\n    C = 1 / (n-1) * np.dot(Xc.T, Xc)\n\n    #########################################\n    return C\n\n\n#--------------------------\ndef compute_eigen_pairs(C):\n    '''\n        Compute the eigen vectors and eigen values of C.\n        Input:\n            C:  the covariance matrix, a numpy float matrix of shape p by p.\n        Output:\n            E:  the eigen vectors of matrix C, a numpy float matrix of shape p by p. Each column of E corresponds to an eigen vector of matrix C.\n            v:  the eigen values of matrix C, a numpy float array of length p. Each element corresponds to an eigen value of matrix C. E and v are paired.\n        Hint: you could use np.linalg.eig() to compute the eigen vectors of a matrix.\n    '''\n\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n    v, E = np.linalg.eig(C)\n\n\n    #########################################\n    return E,v\n\n#--------------------------\ndef compute_P(E,v,k):\n    '''\n        Compute the projection matrix P by combining the eigen vectors with the top k largest eigen values.\n        Input:\n            E:  the eigen vectors of matrix X, a numpy float matrix of shape p by p. Each column of E corresponds to an eigen vector of matrix X.\n            v:  the eigen values of matrix X, a numpy float array of length p. Each element corresponds to an eigen value of matrix X. E and v are paired.\n            k:  the number of dimensions to reduce to (k should be smaller than p), an integer scalar\n        Output:\n            P: the projection matrix, a numpy float matrix of shape p by k.\n    '''\n\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n    select_indices = np.argsort(v)[::-1][:k]\n\n    top_k = v[select_indices]\n    P = E[:, select_indices]\n\n    #########################################\n    return P\n\n\n#--------------------------\ndef compute_Xp(Xc,P):\n    '''\n        Compute the projected feature matrix Xp by projecting data Xc using matrix P.\n        Input:\n            Xc:  the feature matrix after centering, a float numpy matrix of shape n by p. Here n is the number of data records, p is the number of dimensions.\n             P: the projection matrix, a numpy float matrix of shape p by k.\n        Output:\n            Xp: the feature matrix after projection (dimension reduced), a numpy float matrix of shape p by k.\n    '''\n\n    #########################################\n    ## INSERT YOUR CODE HERE\n    Xp = np.matmul(Xc, P)\n    #########################################\n    return Xp\n\n\n\n#--------------------------\ndef PCA(X, k=1):\n    '''\n        Compute PCA of matrix X.\n        Input:\n            X:  the feature matrix, a float numpy matrix of shape n by p. Here n is the number of data records, p is the number of dimensions.\n            k:  the number of dimensions to output (k should be smaller than p)\n        Output:\n            Xp: the feature matrix with reduced dimensions, a numpy float matrix of shape n by k.\n             P: the projection matrix, a numpy float matrix of shape p by k.\n        Note: in this problem, you cannot use existing package for PCA, such as scikit-learn\n    '''\n\n    #########################################\n    ## INSERT YOUR CODE HERE\n\n    # centering matrix X\n\n    Xc, _ = centering_X(X)\n\n    # compute covariance matrix C\n\n    C = compute_C(Xc)\n\n    # compute eigen pairs of L\n\n    E, v = compute_eigen_pairs(C)\n    # compute the projection matrix\n\n    # project the data into lower dimension using projection matrix P and centered data matrix X\n\n    P = compute_P(E, v, k)\n\n    Xp = compute_Xp(Xc, P)\n\n    #########################################\n    return Xp, P\n", "meta": {"hexsha": "529facf63f7dbf4dab771919addc950b9ef44ade", "size": 7154, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw4/problem1.py", "max_stars_repo_name": "rahul-pande/ds501", "max_stars_repo_head_hexsha": "063453de9bf7bc634422a6710d36715175cbeebf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw4/problem1.py", "max_issues_repo_name": "rahul-pande/ds501", "max_issues_repo_head_hexsha": "063453de9bf7bc634422a6710d36715175cbeebf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw4/problem1.py", "max_forks_repo_name": "rahul-pande/ds501", "max_forks_repo_head_hexsha": "063453de9bf7bc634422a6710d36715175cbeebf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3076923077, "max_line_length": 159, "alphanum_fraction": 0.5482247694, "include": true, "reason": "import numpy", "num_tokens": 1536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.9019206798249231, "lm_q1q2_score": 0.8558480990725115}}
{"text": "from mpmath import mp\nimport numpy\n\n\n\ndef bisection_search(f, low:float, high:float):\n    \"\"\"\n    A root finding method that does not rely on derivatives\n\n    :param f: a function f: X -> R\n    :param low: the lower bracket\n    :param high: the upper limit bracket\n    :return: the location of the root, e.g. f(mid) ~ 0\n    \"\"\"\n    # flip high and low if out of order\n    if f(high) < f(low):\n        low, high = high, low\n\n    # find mid point\n    mid = .5 * (low + high)\n\n    while True:\n\n        # bracket up\n        if f(mid) < 0:\n            low = mid\n        # braket down\n        else:\n            high = mid\n\n        # update mid point\n        mid = .5 * (high + low)\n\n        # break if condition met\n        if abs(high - low) < 10 ** (-(mp.dps / 2)):\n            break\n\n    return mid\n\n\ndef concave_max(f, low:float, high:float):\n    \"\"\"\n    Forms a lambda for the approximate derivative and finds the root\n\n    :param f: a function f: X -> R\n    :param low: the lower bracket\n    :param high: the upper limit bracket\n    :return: the location of the root f'(mid) ~ 0\n    \"\"\"\n    # create an approximate derivative expression\n    scale = high - low\n\n    h = mp.mpf('0.' + ''.join(['0' for i in range(int(mp.dps / 1.5))]) + '1') * scale\n    df = lambda x: (f(x + h) - f(x - h)) / (2.0 * h)\n\n    return bisection_search(df, low, high)\n\ndef chev_points(n:int, lower:float = -1, upper:float = 1):\n    \"\"\"\n    Generates a set of chebychev points spaced in the range [lower, upper]\n    :param n: number of points\n    :param lower: lower limit\n    :param upper: upper limit\n    :return: a list of multipressison chebychev points that are in the range [lower, upper]\n    \"\"\"\n    #generate chebeshev points on a range [-1, 1]\n    index = numpy.arange(1, n+1)\n    range_ = abs(upper - lower)\n    return [(.5*(mp.cos((2*i-1)/(2*n)*mp.pi)+1))*range_ + lower for i in index]\n\n\ndef remez(func, n_degree:int, lower:float=-1, upper:float=1, max_iter:int = 10):\n    \"\"\"\n    :param func: a function (or lambda) f: X -> R\n    :param n_degree: the degree of the polynomial to approximate the function f\n    :param lower: lower range of the approximation\n    :param upper: upper range of the approximation\n    :return: the polynomial coefficients, and an approximate maximum error associated with this approximation\n    \"\"\"\n    # initialize the node points\n\n    x_points = chev_points(n_degree + 2, lower, upper)\n\n    A = mp.matrix(n_degree + 2)\n    coeffs = numpy.zeros(n_degree + 2)\n\n    # place in the E column\n    mean_error = float('inf')\n\n    for i in range(n_degree + 2):\n        A[i, n_degree + 1] = (-1) ** (i + 1)\n\n    for i in range(max_iter):\n\n        # build the system\n        vander = numpy.polynomial.chebyshev.chebvander(x_points, n_degree)\n\n        for i in range(n_degree + 2):\n            for j in range(n_degree + 1):\n                A[i, j] = vander[i, j]\n\n        b = mp.matrix([func(x) for x in x_points])\n        l = mp.lu_solve(A, b)\n\n        coeffs = l[:-1]\n\n        # build the residual expression\n        r_i = lambda x: (func(x) - numpy.polynomial.chebyshev.chebval(x, coeffs))\n\n        interval_list = list(zip(x_points, x_points[1:]))\n        #         interval_list = [[x_points[i], x_points[i+1]] for i in range(len(x_points)-1)]\n\n        intervals = [upper]\n        intervals.extend([bisection_search(r_i, *i) for i in interval_list])\n        intervals.append(lower)\n\n        extermum_interval = [[intervals[i], intervals[i + 1]] for i in range(len(intervals) - 1)]\n\n        extremums = [concave_max(r_i, *i) for i in extermum_interval]\n\n        extremums[0] = mp.mpf(upper)\n        extremums[-1] = mp.mpf(lower)\n\n        errors = [abs(r_i(i)) for i in extremums]\n        mean_error = numpy.mean(errors)\n\n        if numpy.max([abs(error - mean_error) for error in errors]) < 0.000001 * mean_error:\n            break\n\n        x_points = extremums\n\n    return [float(i) for i in numpy.polynomial.chebyshev.cheb2poly(coeffs)], float(mean_error)\n\ndef c_code_gen(data_type, name, poly_coeffs, comments = None):\n    method_string = f'{data_type} {name} ({data_type} x)' + '{\\n'\n    \n    if comments is not None:\n        method_string += '\\t// ' + str(comments) + ' \\n\\n'\n    \n    data_type_converter = '' if data_type == 'double' else 'f'\n    \n    method_string += '\\n'.join([f'\\tconst {data_type} a_{i} = {str(val) + data_type_converter};' for i, val in enumerate(poly_coeffs)])\n    \n    horner = 'return a_0+'\n    for i in range(len(poly_coeffs)-2):\n        horner += f'x*(a_{i+1} +' \n    horner += f'x*a_{len(poly_coeffs)-1}' + ')'*(len(poly_coeffs)-2) + ';\\n}'\n    \n    return method_string + '\\n \\t' + horner\n", "meta": {"hexsha": "b8f038957dd2e04adc9fdf39d33f4e8090880f0d", "size": 4633, "ext": "py", "lang": "Python", "max_stars_repo_path": "remez_poly.py", "max_stars_repo_name": "DKenefake/OptimalPoly", "max_stars_repo_head_hexsha": "2d7cef7250dea945d366bb2e4105831825661dc4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-25T00:03:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T02:05:39.000Z", "max_issues_repo_path": "remez_poly.py", "max_issues_repo_name": "DKenefake/OptimalPoly", "max_issues_repo_head_hexsha": "2d7cef7250dea945d366bb2e4105831825661dc4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-25T00:11:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T20:37:33.000Z", "max_forks_repo_path": "remez_poly.py", "max_forks_repo_name": "DKenefake/OptimalPoly", "max_forks_repo_head_hexsha": "2d7cef7250dea945d366bb2e4105831825661dc4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8866666667, "max_line_length": 135, "alphanum_fraction": 0.5965896827, "include": true, "reason": "import numpy,from mpmath", "num_tokens": 1343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.90192067257508, "lm_q1q2_score": 0.8558480921930103}}
{"text": "import numpy as np\r\nimport math\r\n\r\n\r\ndef true(x, t, pro=1):\r\n\r\n    if pro == 1:\r\n        return np.cos(math.pi*t) * np.sin(math.pi*x)\r\n\r\n    elif pro == 2:\r\n        return np.sin(t) * np.sin(4*math.pi*x)\r\n\r\n\r\ndef ex3(h, tao, pro=1):\r\n    xmin = 0\r\n    xmax = 1\r\n    tmin = 0\r\n    tmax = 1\r\n    xs = np.arange(xmin, xmax+h, h)\r\n    ts = np.arange(tmin, tmax+tao, tao)\r\n    if pro == 1:\r\n        a = 1\r\n        def u0(_i):\r\n            _x =xs[_i]\r\n            return np.sin(math.pi*_x)\r\n        def ut0(_i):\r\n            return 0\r\n    elif pro == 2:\r\n        a = 1 / (16*math.pi**2)\r\n        def u0(_i):\r\n            return 0\r\n        def ut0(_i):\r\n            _x = xs[_i]\r\n            return np.sin(4*math.pi*_x)\r\n\r\n    r = a*tao / h\r\n    print(\"r={}\" .format(r), end=',')\r\n\r\n    U = np.zeros((len(ts), len(xs)))\r\n    print(\"网格节点数（时间层，空间层）:\",U.shape)\r\n\r\n    for x in xs:\r\n        i = list(xs).index(x)\r\n        U[0][i] = u0(i)\r\n    for x in xs:\r\n        i = list(xs).index(x)\r\n        U[1][i] = 0.5 * r**2 * (u0(i-1) + u0(i+1)) + (1 - r**2) * u0(i) + tao * ut0(i)\r\n    for k in ts[1:-1]:\r\n        ki = list(ts).index(k)\r\n        for j in xs[1:-1]:\r\n            ji = list(xs).index(j)\r\n            U[ki+1][ji] = r**2 * (U[ki][ji-1] + U[ki][ji+1]) + 2*(1-r**2)*U[ki][ji] - U[ki-1][ji]\r\n\r\n    #print(U)\r\n\r\n    UTrue = np.zeros((len(ts), len(xs)))\r\n    for x in xs:\r\n        for t in ts:\r\n            UTrue[list(ts).index(t)][list(xs).index(x)] = true(x, t, pro=pro)\r\n    #print(UTrue)\r\n\r\n    print(\"误差：\", np.linalg.norm(U - UTrue))\r\n\r\n'''\r\nprint(\"r > 1, 不稳定：\")\r\nex3(0.1, 0.2, pro=1)\r\nex3(0.05, 0.1, pro=1)\r\nex3(0.005, 0.01, pro=1)\r\n\r\nprint(\"r = 1\")\r\nex3(0.2, 0.2, pro=1)\r\nex3(0.1, 0.1, pro=1)\r\nex3(0.05, 0.05, pro=1)\r\nex3(0.01, 0.01, pro=1)\r\n\r\nprint(\"r < 1, 稳定：\")\r\nex3(0.2, 0.1, pro=1)\r\nex3(0.1, 0.05, pro=1)\r\nex3(0.01, 0.005, pro=1)\r\n'''\r\na2 = 16*math.pi**2\r\nprint(\"r > 1, 不稳定：\")\r\nex3(0.0012, 0.2, pro=2)\r\nex3(0.00063, 0.1, pro=2)\r\n#ex3(0.005, 0.01, pro=2)\r\n\r\nprint(\"r < 1, 稳定：\")\r\nex3(0.5, 0.5, pro=2)\r\nex3(0.25, 0.25, pro=2)\r\n#ex3(2/a2, 1, pro=2)\r\n", "meta": {"hexsha": "13b4d5a8e4d4d919f60d22abe719e6ccbf2d06be", "size": 2046, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/ex3.py", "max_stars_repo_name": "CYZhao0709/The-Numerical-Method-Of-Differential-Equation", "max_stars_repo_head_hexsha": "f916613298b92306044753a755da5e6843ef2fd9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-01T05:01:13.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-01T05:01:13.000Z", "max_issues_repo_path": "code/ex3.py", "max_issues_repo_name": "CYZhao0709/The-Numerical-Method-Of-Differential-Equation", "max_issues_repo_head_hexsha": "f916613298b92306044753a755da5e6843ef2fd9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/ex3.py", "max_forks_repo_name": "CYZhao0709/The-Numerical-Method-Of-Differential-Equation", "max_forks_repo_head_hexsha": "f916613298b92306044753a755da5e6843ef2fd9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4835164835, "max_line_length": 98, "alphanum_fraction": 0.4418377322, "include": true, "reason": "import numpy", "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833653, "lm_q2_score": 0.8991213847035617, "lm_q1q2_score": 0.8558405844020147}}
{"text": "#1.解一元二次方程\r\nimport math\r\na = float(input('a='))\r\nb = float(input('b='))\r\nc = float(input('c='))\r\nroot = pow(b , 2) - 4 * a * c\r\nif root > 0:\r\n    r1 = (-b + math.sqrt(root)) / (2 * a)\r\n    r2 = (-b - math.sqrt(root)) / (2 *a)\r\n    print(r1 ,r2)\r\nelif root == 0:\r\n    r1 = -b / 2 * a\r\n    print(r1)\r\nelse:\r\n    print('The equation has no real roots')\r\n\r\n\r\n\r\n\r\n#2.学习加法\r\nimport random\r\n\r\nnum1 = random.randint(0 , 100)\r\nnum2 = random.randint(0 , 100)\r\nprint(num1 , num2)\r\nsum_ = int(input('亲，请输入这两个整数的和：'))\r\nif num1 + num2 == sum_:\r\n    print('答案正确，你真棒！')\r\nelse:\r\n    print('答案错误，再试一次吧！')\r\n\r\n\r\n\r\n\r\n#3.找未来数据\r\ndef week(day,fut):\r\n    days = ['Sunday','Monday','Tuesday','Wendnesday','Thursday','Friday','Saturday']      #创建一个列表\r\n    a = days[day]\r\n    b = days[(day + fut) % 7]\r\n    print(\"Today is %s and the future day is %s\"%(a,b) )\r\n\r\ndef Start():\r\n    day = int(input(\"Enter today's day:\"))\r\n    fut = int(input(\"Enter the number of days elapsed since today:\"))\r\n    week(day,fut)\r\nStart()\r\n\r\n\r\n\r\n\r\n#4.对三个整数排序\r\na = int(input(\"请输入第一个整数：\"))\r\nb = int(input(\"请输入第二个整数：\"))\r\nc = int(input(\"请输入第三个整数：\"))\r\nd = [a,b,c]\r\nd.sort()     #升序sort()\r\nprint(d)\r\n\r\n\r\n\r\n\r\n#5.比较价钱\r\nmoney1 = float(input(\"请输入第一种大米的价钱：\"))\r\nweight1 = float(input(\"请输入第一种大米的重量：\"))\r\nmoney2 = float(input(\"请输入第二种大米的价钱：\"))\r\nweight2 = float(input(\"请输入第二种大米的重量：\"))\r\nper1 = money1 / weight1\r\nper2 = money2 / weight2\r\nif per1 > per2:\r\n    print('第二种包装价格更好')\r\nelif per1 < per2:\r\n    print('第一种包装价格更好')\r\nelse:\r\n    print('两种大米价格相同')\r\n\r\n\r\n\r\n\r\n#6.找出一个月中的天数\r\nyear = int(input('请输入年份：'))\r\nmonth = int(input('请输入月份：'))\r\nlist1 = [1,3,5,7,8,10,12]\r\nlist2 = [4,6,9,11]\r\nif month in list1:\r\n    print('%d年%d月份有31天'%(year,month))\r\nelif month in list2:\r\n    print('%d年%d月份有30天'%(year,month))\r\nelse:\r\n    if year % 400 == 0 and year % 4 ==0:\r\n        print('%d年%d月份有29天'%(year,month))\r\n    else:\r\n        print('%d年%d月份有28天'%(year,month))\r\n\r\n\r\n\r\n\r\n#7.头或尾\r\nimport numpy as np \r\nres = np.random.choice(['正面','反面'])\r\nprint(res)\r\nguess = input(\"请输入'正面','反面':\")\r\nif res == guess:\r\n    print('恭喜你，答对啦！')\r\nelse:\r\n    print('很遗憾，答错了!')\r\n\r\n\r\n\r\n\r\n#8.剪刀石头布\r\nimport random\r\ncomputer = random.randint(1,3)\r\nprint(computer)\r\nuser = int(input(\"请输入[1.石头 2.剪刀 3.布]\"))\r\nif computer != user:\r\n    if  computer == 1  and user == 2:\r\n        print('你输了，再来一局')\r\n    elif computer == 2 and user == 3:\r\n        print('你输了，再来一局')\r\n    elif computer == 3 and user == 1:\r\n        print('你输了，再来一局')\r\n    else:\r\n        print('你赢了，太棒了')\r\nelse :\r\n    print('平局，再来一局')\r\n\r\n\r\n\r\n\r\n#9.一周的星期几\r\nyear = int(input('请输入年份(eg.2008):'))\r\nmonth = int(input('请输入月份(1-12):'))\r\ndays = int(input('请输入月份的第几天(1-31):'))\r\nweek = ['Saturday','Sunday','Monday','Tuesday','Wendnesday','Thursday','Friday']\r\nif month == 1:\r\n    month = 13\r\n    year = year - 1\r\nif month ==2:\r\n    month = 14\r\n    year = year - 1\r\nh = int(days+((26*(month+1))//10)+(year%100)+((year%100)/4)+((year//100)/4)+5*year//100)%7\r\nday = week[h]\r\nprint('Day of the week is %s'%day)\r\n\r\n\r\n\r\n\r\n\r\n#10.选出一张牌\r\nimport numpy as np \r\ncard = np.random.choice(['Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King'])\r\ncolor = np.random.choice(['梅花','红桃','方块','黑桃'])\r\nprint('The card you picked is the %s of %s'%(card,color))\r\n\r\n\r\n\r\n\r\n#11.回文数\r\nnum = int(input('亲，请输入一个三位数：'))\r\na = num % 10 *100 + num // 10 % 10 *10 + num // 100\r\nif num == a:\r\n    print('%d是回文数'%num)\r\nelse:\r\n    print('%d不是回文数'%num)\r\n\r\n#或者\r\nnum = input('输入一个三位数：')\r\na = num[2]\r\nb = num[0]\r\nif a == b :\r\n    print('%r是回文数'%num)\r\nelse:\r\n    print('%r不是回文数'%num)\r\n\r\n\r\n\r\n\r\n#12.计算三角形的周长\r\na = int(input(\"请输入三角形的边长:\"))\r\nb = int(input(\"请输入三角形的边长:\"))\r\nc = int(input(\"请输入三角形的边长:\"))\r\nif a < b + c and b < a + c and c < b + a:\r\n    sum = a + b + c\r\n    print(\"三角形的周长是：%d\"%sum)\r\nelse:\r\n    print('亲，您输入的边长是不合法的哦！')\r\n\r\n\r\n\r\n\r\n#13.统计正数和负数的个数然后计算这些数的平均值\r\npositive_number = 0\r\nnegative_number = 0\r\nsum_number = 0\r\nfor i in range(100):\r\n    n = int(input('请输入整数:'))\r\n    if n != 0:\r\n        if n > 0:\r\n            positive_number += 1\r\n        else:\r\n            negative_number += 1\r\n    else:\r\n        break\r\n    sum_number += n\r\naverage_number = sum_number / (positive_number + negative_number)\r\nprint('您输入的正数有%d个，负数有%d个，平均值是%.2f'%(positive_number,negative_number,average_number))\r\n\r\n\r\n\r\n\r\n#14.计算未来学费\r\nmoney = 10000\r\nten_money = 0\r\nfor i in range(13):\r\n    money = money * (1 + 0.05)\r\n    if i == 9:\r\n        print(\"十年后的学费是:%d\"%money)\r\n    if i >= 9:\r\n        ten_money += money\r\nprint(\"十年后大学四年的总学费:%d\"%ten_money)\r\n\r\n\r\n\r\n\r\n#15.找出可以被5和6同时整除的数\r\ncount = 0\r\nfor i in range(100,700):\r\n    if i % 5 == 0 and i % 6 == 0:\r\n        print(i,end = \" \")\r\n        count += 1\r\n        if count % 10 == 0:\r\n            print()\r\n\r\n\r\n\r\n\r\n#16.找出最小的n满足n²>12000；找出最大的n满足n³<12000；\r\nn = 1\r\nwhile n ** 2 < 12000:\r\n    n += 1\r\nprint(n)\r\n\r\nn_ = 1\r\nwhile n_ ** 3 < 12000:\r\n    n_ += 1\r\nprint(n_-1)\r\n\r\n\r\n\r\n\r\n#17.演示消除错误（1+1/2+1/3+.....+1/n）\r\na = 0\r\nfor i in range(1,5001):\r\n    a += 1 / i\r\nprint('从左到右的和为：%r'%a)\r\n\r\nb = 0\r\nfor i in range(5000,0,-1):\r\n    b += 1 / i\r\nprint('从右到左的和为：%r'%b)\r\n\r\n\r\n\r\n\r\n#18.数列求和(1/3+3/5+5/7+9/11+11/13+....95/97+97/99)\r\n\r\nsum = 0\r\nfor i in range(1,99,2):\r\n    j = i + 2\r\n    sum += i / j\r\nprint(\"数列的和是:%f\"%sum)\r\n\r\n\r\n\r\n\r\n#19.计算∏=4（1-1/3+1/5-1/7+1/9-1/11+.....+(-1)**(i+1)/(2i-1)）\r\n\r\npi = 0\r\nfor i in range(1,100000):\r\n    pi += 4 * ((-1) ** (i + 1) / (2 * i - 1))\r\nprint('pi = %r '%pi)\r\n\r\n\r\n\r\n\r\n#20.完全数\r\nfor i in range(1,10000):     #i是在1~10000里的数\r\n    a = 0    #除了本身的和\r\n    for j in range(1,i):\r\n        if i % j == 0:    #j是i的本身\r\n            a += j\r\n    if a == i:\r\n        print(a,end = (\" \"))\r\n\r\n\r\n\r\n\r\n#21.组合(7*6/2=21,)\r\ncount = 0\r\nfor i in range(1,8,2):\r\n    for j in range(2,8):\r\n        if i != j :\r\n            count += 1\r\n            print(i,j,end = \"\\n\")\r\nprint(\"组合共有%d个数\"%count)\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "5a1e1394a0c0be392318832b9f4c21f175e06faa", "size": 5706, "ext": "py", "lang": "Python", "max_stars_repo_path": "homework-day2.py", "max_stars_repo_name": "zgx0815/python", "max_stars_repo_head_hexsha": "a71fab97494eacbab8d4ff6a7ec7c3e71a1eb0d8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework-day2.py", "max_issues_repo_name": "zgx0815/python", "max_issues_repo_head_hexsha": "a71fab97494eacbab8d4ff6a7ec7c3e71a1eb0d8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework-day2.py", "max_forks_repo_name": "zgx0815/python", "max_forks_repo_head_hexsha": "a71fab97494eacbab8d4ff6a7ec7c3e71a1eb0d8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.347266881, "max_line_length": 98, "alphanum_fraction": 0.5217315107, "include": true, "reason": "import numpy", "num_tokens": 2377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.8991213874066956, "lm_q1q2_score": 0.8558405832916933}}
{"text": "from ._integrand import Integrand\nfrom ..discrete_distribution import DigitalNetB2\nfrom ..true_measure import Uniform\nfrom numpy import *\n\n\nclass BoxIntegral(Integrand):\n    \"\"\"\n    $B_s(x) = \\\\left(\\\\sum_{j=1}^d x_j^2 \\\\right)^{s/2}$\n\n    >>> l1 = BoxIntegral(DigitalNetB2(2,seed=7), s=[7])\n    >>> x1 = l1.discrete_distrib.gen_samples(2**10)\n    >>> y1 = l1.f(x1)\n    >>> y1.shape\n    (1024, 1)\n    >>> y1.mean(0)\n    array([0.75156724])\n    >>> l2 = BoxIntegral(DigitalNetB2(5,seed=7), s=[-7,7])\n    >>> x2 = l2.discrete_distrib.gen_samples(2**10)\n    >>> y2 = l2.f(x2,compute_flags=[1,1])\n    >>> y2.shape\n    (1024, 2)\n    >>> y2.mean(0)\n    array([ 6.67548708, 10.52267786])\n\n    References:\n\n    [1] D.H. Bailey, J.M. Borwein, R.E. Crandall,Box integrals,\n    Journal of Computational and Applied Mathematics, Volume 206, Issue 1, 2007, Pages 196-208, ISSN 0377-0427, \n    https://doi.org/10.1016/j.cam.2006.06.010. (https://www.sciencedirect.com/science/article/pii/S0377042706004250) \n    \n    [2] https://www.davidhbailey.com/dhbpapers/boxintegrals.pdf\n    \"\"\"\n\n    def __init__(self, sampler, s=array([1,2])):\n        \"\"\"\n        Args:\n            sampler (DiscreteDistribution/TrueMeasure): A \n                discrete distribution from which to transform samples or a\n                true measure by which to compose a transform\n            s (list or ndarray): vectorized s parameter, len(s) is the number of vectorized integrals to evalute.\n        \"\"\"\n        self.parameters = ['s']\n        self.s = array([s]) if isscalar(s) else array(s)\n        self.dprime = len(self.s)\n        self.sampler = sampler\n        self.true_measure = Uniform(self.sampler, lower_bound=0., upper_bound=1.)\n        super(BoxIntegral,self).__init__() # output dimensions per sample\n\n    def g(self, t, **kwargs):\n        compute_flags = kwargs['compute_flags'] if 'compute_flags' in kwargs else ones(self.dprime,dtype=int)\n        n,d = t.shape\n        Y = zeros((n,self.dprime),dtype=float)\n        for j in range(self.dprime):\n            if compute_flags[j] == 1: \n                Y[:,j] = (t**2).sum(1)**(self.s[j]/2)\n        return Y\n    \n    def _spawn(self, level, sampler):\n        return BoxIntegral(sampler=sampler,s=self.s)\n", "meta": {"hexsha": "06af6a4b13848b4a551316b81a5dc67b07585002", "size": 2231, "ext": "py", "lang": "Python", "max_stars_repo_path": "qmcpy/integrand/box_integral.py", "max_stars_repo_name": "QMCSoftware/QMCSoftware", "max_stars_repo_head_hexsha": "dbd774d635eb269e77c48526b980f62c23214617", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2019-09-15T03:31:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T19:52:10.000Z", "max_issues_repo_path": "qmcpy/integrand/box_integral.py", "max_issues_repo_name": "QMCSoftware/QMCSoftware", "max_issues_repo_head_hexsha": "dbd774d635eb269e77c48526b980f62c23214617", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 152, "max_issues_repo_issues_event_min_datetime": "2019-10-06T17:26:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T04:17:04.000Z", "max_forks_repo_path": "qmcpy/integrand/box_integral.py", "max_forks_repo_name": "QMCSoftware/QMCSoftware", "max_forks_repo_head_hexsha": "dbd774d635eb269e77c48526b980f62c23214617", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2019-09-17T23:33:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-19T22:38:45.000Z", "avg_line_length": 36.5737704918, "max_line_length": 117, "alphanum_fraction": 0.6113850291, "include": true, "reason": "from numpy", "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632234212403, "lm_q2_score": 0.8991213874066956, "lm_q1q2_score": 0.855840582063915}}
{"text": "\"\"\"\nInferring a binomial proportion via grid approximation.\n\"\"\"\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn-darkgrid')\nimport numpy as np\nfrom hpd import hpd\n\n\ndef bern_grid(theta, p_theta, data, credib=.95):\n    \"\"\"\n    Bayesian updating for Bernoulli likelihood and prior specified on a grid.\n    Input arguments:\n     theta is a vector of theta values, all between 0 and 1.\n     p_theta is a vector of corresponding probability _masses_.\n     data is a vector of 1's and 0's, where 1 corresponds to a and 0 to b.\n     credib is the probability mass of the credible interval, default is 0.95.\n    Output:\n     p_theta_given_data is a vector of posterior probability masses over theta.\n     Also creates a three-panel graph of prior, likelihood, and posterior\n     probability masses with credible interval.\n    Example of use:\n     Create vector of theta values.\n     bin_width = 1/1000 \n     theta_grid = np.arange(0, 1+bin_width, bin_width)\n     Specify probability mass at each theta value.\n     > rel_prob = np.minimum(theta_grid, 1-theta_grid) relative prob at each theta\n     > prior = rel_prob / sum(rel_prob) probability mass at each theta\n     Specify the data vector.\n     data_vec = np.repeat([1, 0], [11, 3])  # 3 heads, 1 tail\n     Call the function.\n     > posterior = bern_grid( theta=theta_grid , p_theta=prior , data=data_vec )\n    \"\"\"\n\n# Create summary values of data\n    z = sum(data[data == 1])  # number of 1's in data\n    N = len(data)  # number of flips in data\n# Compute the likelihood of the data for each value of theta.\n    p_data_given_theta = theta**z * (1 - theta)**(N - z)\n# Compute the evidence and the posterior.\n    p_data = sum(p_data_given_theta * p_theta)\n    p_theta_given_data = p_data_given_theta * p_theta / p_data\n    # Determine the limits of the highest density interval\n    x = np.random.choice(theta, size=5000, replace=True, p=p_theta_given_data)\n    intervals = hpd(x, alpha=1-credib)\n\n# Plot the results.\n    plt.figure(figsize=(12, 12))\n    plt.subplots_adjust(hspace=0.7)\n\n#    # Plot the prior.\n    locx = 0.05\n    mean_theta = sum(theta * p_theta)  # mean of prior, for plotting\n    plt.subplot(3, 1, 1)\n    plt.plot(theta, p_theta)\n    plt.xlim(0, 1)\n    plt.ylim(0, np.max(p_theta)*1.2)\n    plt.xlabel(r'$\\theta$')\n    plt.ylabel(r'$P(\\theta)$')\n    plt.title('Prior')\n    plt.text(locx, np.max(p_theta)/2, r'mean($\\theta$;%5.2f)' % mean_theta)\n    # Plot the likelihood:\n    plt.subplot(3, 1, 2)\n    plt.plot(theta, p_data_given_theta)\n    plt.xlim(0, 1)\n    plt.ylim(0, np.max(p_data_given_theta)*1.2)\n    plt.xlabel(r'$\\theta$')\n    plt.ylabel(r'$P(D|\\theta)$')\n    plt.title('Likelihood')\n    plt.text(locx, np.max(p_data_given_theta)/2, 'data: z=%s, N=%s' % (z, N))\n    # Plot the posterior:\n    mean_theta_given_data = sum(theta * p_theta_given_data)\n    plt.subplot(3, 1, 3)\n    plt.plot(theta, p_theta_given_data)\n    plt.xlim(0, 1)\n    plt.ylim(0, np.max(p_theta_given_data)*1.2)\n    plt.xlabel(r'$\\theta$')\n    plt.ylabel(r'$P(\\theta|D)$')\n    plt.title('Posterior')\n    loc = np.linspace(0, np.max(p_theta_given_data), 5)\n    plt.text(locx, loc[1], r'mean($\\theta$;%5.2f)' % mean_theta_given_data)\n    plt.text(locx, loc[2], 'P(D) = %g' % p_data)\n    # Plot the HDI\n    plt.text(locx, loc[3],\n             'Intervals =%s' % ', '.join('%.3f' % x for x in intervals))\n    for i in range(0, len(intervals), 2):\n        plt.fill_between(theta, 0, p_theta_given_data,\n                         where=np.logical_and(theta > intervals[i],\n                                              theta < intervals[i+1]),\n                         color='blue', alpha=0.3)\n    plt.savefig('Figure_6.1.png')\n    plt.show()\n    return p_theta_given_data\n\n\n###Create vector of theta values.\nbin_width = 1/1000.\ntheta_grid = np.arange(0, 1+bin_width, bin_width)\n##Specify probability mass at each theta value.\nrel_prob = np.array([0.1] * len(theta_grid))  # uniform prior\nrel_prob = np.array([0.1] * len(theta_grid))  # uniform prior\nprior = rel_prob / sum(rel_prob)  # probability mass at each theta\n\n\n#### figure 6.2 ###\n#np.random.seed(123)\n#a = [0.1] * 50\n#b = np.linspace(0.1, 1, 50)\n#c = np.linspace(1, 0.1, 50)\n#d = [0.1] * 50\n#p_theta = np.concatenate((a, b, c, d))\n#prior = np.where(p_theta != 0 , p_theta / sum(p_theta), 0.)\n#width = 1. / len(p_theta)\n#theta_grid = np.arange(width/2 , (1-width/2)+width, width)\n\n### figure 6.3 ###\n#np.random.seed(123)\n#a = np.repeat([0], [50])\n#b = np.linspace(0, 1, 50)\n#c = (np.linspace(1, 0, 20))**2\n#d = np.random.uniform(size=3)\n#e = np.repeat([1], [20])\n#p_theta = np.concatenate((a, b, c, d, e))\n#prior = np.where(p_theta != 0 , p_theta / sum(p_theta), 0.)\n#width = 1. / len(p_theta)\n#theta_grid = np.arange(width/2 , (1-width/2)+width, width)\n\n###Specify the data vector.\ndata_vec = np.repeat([1, 0], [11, 3])  # 3 heads, 1 tail\n###Call the function.\nposterior = bern_grid(theta=theta_grid, p_theta=prior, data=data_vec)\n", "meta": {"hexsha": "7fa1f98172592461c7fb60245a3d2d29d99c9ef6", "size": 4928, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymc_code/06_BernGrid.py", "max_stars_repo_name": "xishansnow/bayesianPrincipal", "max_stars_repo_head_hexsha": "92789e0a35537565297845fb10837481965d655b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pymc_code/06_BernGrid.py", "max_issues_repo_name": "xishansnow/bayesianPrincipal", "max_issues_repo_head_hexsha": "92789e0a35537565297845fb10837481965d655b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymc_code/06_BernGrid.py", "max_forks_repo_name": "xishansnow/bayesianPrincipal", "max_forks_repo_head_hexsha": "92789e0a35537565297845fb10837481965d655b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3333333333, "max_line_length": 82, "alphanum_fraction": 0.6440746753, "include": true, "reason": "import numpy", "num_tokens": 1496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.8991213826762113, "lm_q1q2_score": 0.8558405787889194}}
{"text": "# test_10.py\n''' FUNCIONES\nEjemplo para el curso de métodos numéricos\npor Ing. Giancarlo Ortiz '''\n# Instalar módulos\n''' Las funciones en Python se definen con la palabra clave def, seguida del nombre de la función.\nSus parámetros se escriben entre parentesis y pueden incluir valores por defecto.\nOtra forma de escribir funciones, aunque menos utilizada, es con la palabra clave lambda.\nEl valor devuelto en las funciones con def será el dado con la instrucción return. '''\n\n# DECLARACIÓN:\n# Importar módulos que requieren instalación\nimport numpy as np\nfrom numpy import ndarray\nfrom numpy.core.records import array\n\n# Definiciones de nuevas funciones con la palabra clave Def\ndef _menor(A: ndarray, i: int, j: int) -> ndarray:\n    ''' Define el menor de la matriz A como Ă(i, j). \n    \n        ## Parámetros:\n            A (array): una matriz.\n            i (int): el primer indice.\n            j (int): el segundo indice.\n        \n        ## Devoluciones:\n            B (array): retorna el menor. \n    '''\n    B = np.delete(A, i-1, axis=0)\n    C = np.delete(B, j-1, axis=1)\n    return C\n\n\ndef _cofactor(A: ndarray, i: int, j: int) -> float:\n    ''' Define el cofactor A(i, j) de una matriz A dada. \n        \n        ## Parámetros:\n            A (array): una matriz.\n            i (int): el primer indice.\n            j (int): el segundo indice.\n        \n        ## Devoluciones:\n            B (float): retorna el cofactor. \n    '''\n    B = _menor(A, i, j)\n    C = pow(-1, i+j) * round(np.linalg.det(B), 3)\n    return C\n\n\ndef _matriz_de_cofactores(A: ndarray):\n    ''' Define la matriz de cofactores, que se obtiene de sustituir cada termino de A(i,j) por el C(i,j).\n    \n        ## Parámetros:\n            A (array): una matriz.\n        \n        ## Devoluciones:\n            B (array): la matriz de cofactores. \n    '''\n    filas = A.shape[0]\n    columnas = A.shape[1]\n    B = np.zeros_like(A)\n    for i in range(filas):\n        for j in range(columnas):\n            B[i, j] = _cofactor(A, i+1, j+1)\n    return B\n\n\ndef _matriz_adjunta(A: ndarray):\n    ''' Define la matriz de adjunta, que se obtiene de la transpuesta de la matriz de cofactores.\n    \n        ## Parámetros:\n            A (array): una matriz.\n        \n        ## Devoluciones:\n            B (array): la matriz adjunta. \n    '''\n    B = np.transpose(_matriz_de_cofactores(A))\n    return B\n\n\ndef _determinante(A: list) -> float:\n    ''' Define el determinante de una matriz A dada.\n    \n        ## Parámetros:\n            A (array): una matriz.\n        \n        ## Devoluciones:\n            B (float): el determinante de la matriz. \n    '''\n    filas = A.shape[0]\n    columnas = A.shape[1]\n    if (filas != columnas):\n        return f\"ERROR: Determinante no esta definido para matrices {filas}x{columnas}\"\n    if (filas == 1):\n        return A[0][0]\n    sum = 0\n    for i in range(filas):\n        C = pow(-1, i+2) * A[i][0]\n        M = _menor(A, i+1, 1)\n        D = C * _determinante(M)\n        sum = D + sum\n    return sum\n\n# Definiciones de nuevas funciones con la palabra clave Lambda\ncof = lambda A: _matriz_de_cofactores(A)\nadj = lambda A: _matriz_adjunta(A)\ndet = lambda A: _determinante(A)\ninv = lambda A: (1/det(A))*adj(A)\n\n# Asignación y llamado a funciones declaradas en el script\ndef _calcular_matrices(A):\n    ''' Imprimir en pantalla una demostración de la funcionalidad.\n    '''\n    # funciones definidas en el script\n    Matriz_Cofactores = cof(A)\n    Matriz_Adjunta = adj(A)\n    Matriz_Inversa = inv(A)              \n    return Matriz_Cofactores, Matriz_Adjunta, Matriz_Inversa\n\n# Función que no retorna ningún valor\ndef demo(Array):\n    ''' Imprimir en pantalla una demostración de la funcionalidad.\n    '''\n    M13 = _menor(Array, 1, 3)\n    C13 = _cofactor(Array, 1, 3)\n    \n    # Asignación multiple usando una función que retorna múltiples valores\n    Cof, Adj, Inv = _calcular_matrices(Array)\n\n    # función incorporada en NumPy para comparar\n    Inv_np = np.linalg.inv(Array)           \n    \n    # Salida Estándar\n    print(f\"--------------------------------------------------------\")\n    print(f\"Dada una matriz de entrada A en R³:\")\n    print(f\">>>\")\n    print(f\"\\n{Array}\\n\")\n    print(f\"--------------------------------------------------------\")\n    print(f\"Se tiene que cada matriz  Ă(i,j) se define como el menor\")\n    print(f\"que resulta  de eliminar  la i-ésima fila  y  la j-ésima\")\n    print(f\"columna, por ejemplo A₁₃ es:\")\n    print(f\">>>\")\n    print(f\"\\n{M13}\\n\")\n    print(f\"--------------------------------------------------------\")\n    print(f\"El cofactor se define como C(i,j) =(-1)²det(Ă(i,j)), por\")\n    print(f\"ejemplo C₁₃ es igual a {C13};  finalmente se tiene que la\")\n    print(f\"matriz de  cofactores de A en R³ definida como Cof(A) es\")\n    print(f\"aquella  que resulta de  reemplazar cada elemento por su\") \n    print(f\"cofactor:\")\n    print(f\">>>\")\n    print(f\"\\n{Cof}\\n\")\n    print(f\"--------------------------------------------------------\")\n    print(f\"Y la matriz adjunta  definida  como la transpuesta de la\")\n    print(f\"matriz de cofactores es Adj(A) =trs(Cof(A)) que resulta:\")\n    print(f\">>>\")\n    print(f\"\\n{Adj}\\n\")\n    print(f\"--------------------------------------------------------\")\n    print(f\"Finalmente dado que inv(A) = (1/det(A)).adj(A) se  tiene\")\n    print(f\"que la inversa definida en el script y la de NumPy son:\")\n    print(f\">>>\")\n    print(f\"\\n{Inv}\\n\")\n    print(f\">>>\")\n    print(f\"\\n{Inv_np}\\n\")\n\n# EJECUCIÓN:\n# Definición de un vector de prueba en R³ usando un tipo de dato de NumPy\nArray_de_prueba = np.array([[1, 1, 1], [-1, 2, -3], [3, 0, 2]])\ndemo(Array_de_prueba)\n", "meta": {"hexsha": "b7587aee5c5e1c38fe62e40fddeeeb956996be6b", "size": 5619, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/10_test.py", "max_stars_repo_name": "GiancarloBenavides/Metodos-Numericos", "max_stars_repo_head_hexsha": "c35eb538d33b8dd58eacccf9e8b9b59c605d7dba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-29T19:13:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-29T19:13:39.000Z", "max_issues_repo_path": "Python/10_test.py", "max_issues_repo_name": "GiancarloBenavides/Metodos-Numericos", "max_issues_repo_head_hexsha": "c35eb538d33b8dd58eacccf9e8b9b59c605d7dba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/10_test.py", "max_forks_repo_name": "GiancarloBenavides/Metodos-Numericos", "max_forks_repo_head_hexsha": "c35eb538d33b8dd58eacccf9e8b9b59c605d7dba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-12T20:22:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-12T20:22:40.000Z", "avg_line_length": 33.2485207101, "max_line_length": 105, "alphanum_fraction": 0.5767930237, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.8991213705121083, "lm_q1q2_score": 0.8558405708936919}}
{"text": "import numpy as np\n\n\ndef spherical_to_cartesian(inclination_radians: np.ndarray, azimuth_radians: np.ndarray, radius: np.ndarray = None):\n    \"\"\"convert spherical to 3D cartesian coordinates\n\n    spherical coordinates have to be specified as separate ndarrays of inclination angle (0 radians in zenith, pi\n    radians in nadir) and optionally a radial coordinate (which is otherwise implicitly assumed to be 1 for unit\n    vectors);\n\n    input array dimensions are arbitrary but must match between the different arrays;\n    returns tuple of cartesian coordinates in separate x, y and z arrays\"\"\"\n\n    if radius is None:\n        radius = 1\n\n    sin_theta = np.sin(inclination_radians)\n    x = radius * sin_theta * np.cos(azimuth_radians)\n    y = radius * sin_theta * np.sin(azimuth_radians)\n    z = radius * np.cos(inclination_radians)\n    return x, y, z\n\n\ndef cartesian_to_spherical(x: np.ndarray, y: np.ndarray, z: np.ndarray, normalized: bool = False, with_radius: bool = False):\n    \"\"\"convert (optionally normalized) 3D cartesian to spherical coordinates\n\n    spherical coordinates follow the inclination-azimuth convention: inclination angle theta goes from 0 radians in the\n    zenith (north pole) to pi radians at nadir (south pole), azimuth is circular from 0 to 2 pi radians, with 0 in x\n    direction\n\n    inputs are numpy ndarrays with arbitrary but matching dimensions; if normalized == True, inputs are assumed to be of\n    unit length; with_radius determines whether only inclination and azimuth, or if also the radial coordinate should be\n    returned in case the inputs are not normalized\n    returns spherical coordinates in separate arrays: inclination, azimuth [and radius, when with_radius == True]\n    \"\"\"\n\n    if not normalized:\n        radius = np.sqrt(x**2 + y**2 + z**2)\n        inv_radius = 1 / radius\n        x *= inv_radius\n        y *= inv_radius\n        z *= inv_radius\n    else:\n        radius = np.ones_like(x)\n\n    inclination = np.arccos(z)\n    azimuth = np.arctan2(y, x)\n\n    if with_radius:\n        return inclination, azimuth, radius\n    else:\n        return inclination, azimuth\n\n\ndef cartesian_to_plane_stereographic(x: np.ndarray, y: np.ndarray, z: np.ndarray):\n    \"\"\"convert 3D cartesian vectors on the unit sphere to 2D coordinates by transforming as:\n\n    x_2d = x / (1 + z)\n    y_2dr = y / (1 + z)\n\n    this corresponds to a stereographic projection from the lower pole (nadir), which maps the upper hemisphere (z > 0)\n    inside the unit circle in the x-y-plane\n\n    inputs numpy ndarrays with arbitrary but matching dimensions;\n    returns tuple x_par, y_par with same dimensions as inputs\"\"\"\n\n    inv_denom = 1. / (1 + z)\n    return x * inv_denom, y * inv_denom\n\n\ndef plane_to_cartesian_stereographic(x_2d: np.ndarray, y_2d: np.ndarray):\n    \"\"\"transform 2D coordinates from the x-y-plane to 3D cartesian coordinates on the unit sphere by means of a\n    stereographic projection from the lower pole, which maps 2D points from within the x-y unit circle to the upper\n    hemisphere\n\n    inputs: x_2d, y_2d: np.ndarrays with arbitrary but matching dimensions\n    returns 3-tuple of np.ndarrays x, y, z, where each array has the same shape as the inputs\"\"\"\n\n    len_sqr = x_2d ** 2 + y_2d ** 2\n    x = 2 * x_2d / (len_sqr + 1)\n    y = 2 * y_2d / (len_sqr + 1)\n    z = (1 - len_sqr) / (1 + len_sqr)\n\n    return x, y, z\n", "meta": {"hexsha": "412a63e9ec4ec8eb99a8ab9593fdc72a61a410c6", "size": 3363, "ext": "py", "lang": "Python", "max_stars_repo_path": "pysmtb/geometry.py", "max_stars_repo_name": "smerzbach/pysmtb", "max_stars_repo_head_hexsha": "d81dfdf90357a7b83a95c5d93bdfc9fd03fb7907", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-08T17:49:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T17:49:55.000Z", "max_issues_repo_path": "pysmtb/geometry.py", "max_issues_repo_name": "smerzbach/pysmtb", "max_issues_repo_head_hexsha": "d81dfdf90357a7b83a95c5d93bdfc9fd03fb7907", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-08T20:39:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-11T21:57:55.000Z", "max_forks_repo_path": "pysmtb/geometry.py", "max_forks_repo_name": "smerzbach/pysmtb", "max_forks_repo_head_hexsha": "d81dfdf90357a7b83a95c5d93bdfc9fd03fb7907", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-08T16:44:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-08T16:44:08.000Z", "avg_line_length": 39.5647058824, "max_line_length": 125, "alphanum_fraction": 0.7032411537, "include": true, "reason": "import numpy", "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632234212403, "lm_q2_score": 0.8991213718636752, "lm_q1q2_score": 0.8558405672690856}}
{"text": "\nimport numpy as np\n\n######################################################################################################\n# Scalars \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n######################################################################################################\n#\n# Scalars in NumPy are a bit more involved than in Python. \n# Instead of Python’s basic types like int, float, etc., NumPy lets you specify signed and unsigned types, as well as\n# different sizes. So instead of Python’s int, you have access to types like uint8, int8, uint16, int16, and so on.\n\nscalar = np.array(5)\nprint('Scalar = ', scalar, 'shape: ', scalar.shape)\n\nscalarSum = scalar + 11\nprint('Scalar sum: ', scalar, ' + 11 = ', scalarSum)\n\n\n######################################################################################################\n# Vectors \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n######################################################################################################\n#\n# To create a vector, you'd pass a Python list to the array function, like this:\n\nvector = np.array([1, 2, 3]) \nprint('Vector: ', vector, 'shape: ', vector.shape)\n\n# Access an element within the vector using indices, like this:\nprint('vector[1] = ', vector[1])\n\n# NumPy also supports advanced indexing techniques.\n# For example, to access the items from the second element onward, you would say:\nprint(vector[1:])\n\n\n######################################################################################################\n# Matrices \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n######################################################################################################\n#\n# You create matrices using NumPy's array function, just you did for vectors.\n# However, instead of just passing in a list, you need to supply a list of lists, where each list represents a row.\n# So to create a 3x3 matrix containing the numbers one through nine, you could do this:\n\nmatrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\nprint('Matrix: \\n', matrix)\nprint('Matrix shape: ', matrix.shape)\nprint('matrix[1][2] = ', matrix[1][2])\n\n\n######################################################################################################\n# Tensors \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n######################################################################################################\n#\n# Tensors are just like vectors and matrices, but they can have more dimensions. \n# For example, to create a 3x3x2x1 tensor, you could do the following:\n\ntensor = np.array([[[[1],[2]],[[3],[4]],[[5],[6]]],[[[7],[8]],\\\n    [[9],[10]],[[11],[12]]],[[[13],[14]],[[15],[16]],[[17],[18]]]])\n\nprint('Tensor: \\n', tensor)\nprint('Tensor shape: ', tensor.shape)\n\n# Access items just like with matrices, but with more indices. So t[2][1][1][0] will return 16.\nprint('tensor[2][1][1][0]', tensor[2][1][1][0])\n\n######################################################################################################\n# Element-wise operations\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n######################################################################################################\n# The Python way\n# Suppose you had a list of numbers, and you wanted to add 5 to every item in the list. \n# Without NumPy, you might do something like this:\n\np_values = [1, 2, 3, 4, 5]\nfor i in range(len(p_values)):\n    p_values[i] += 5\n\n# now values holds [6, 7, 8, 9, 10]\n\n# The NumPy way\n# In NumPy, we could do the following:\n\nnp_values = [1, 2, 3, 4, 5]\nnp_values = np.array(np_values) + 5\n\nprint('[1, 2, 3, 4, 5] + 5 == ', np_values)\n\n# now values is an ndarray that holds [6, 7, 8, 9, 10]\n\n# We should point out, NumPy actually has functions for things like adding, multiplying, etc.\n# But it also supports using the standard math operators. So the following two lines are equivalent:\n\nsome_array = np.array([1, 2, 3, 4, 5])\nnp_mult_1 = np.multiply(some_array, 5)\nnp_mult_2 = some_array * 5\n\nprint('[1, 2, 3, 4, 5] * 5 == ', np_mult_2)\n\n# Init with zeros:\nzero_matrix = np_mult_2 * 0\n\n# now every element in m is zero, no matter how many dimensions it has\nprint(np_mult_2, '* 0 == ', zero_matrix)\n\n\n######################################################################################################\n# Element-wise Matrix Operations \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n######################################################################################################\n#\n#The same functions and operators that work with scalars and matrices also work with other dimensions.\n# You just need to make sure that the items you perform the operation on have compatible shapes.\n#\n# Let's say you want to get the squared values of a matrix. \n# That's simply x = m * m (or if you want to assign the value back to m, it's just m *= m\n#\n# This works because it's an element-wise multiplication between two identically-shaped matrices.\n# (In this case, they are shaped the same because they are actually the same object.)\n#\n# Here's the example:\n\na = np.array([[1, 3], [5, 7]])\nprint('A:\\n', a)\n# displays the following result:\n# array([[1, 3],\n#        [5, 7]])\n\nb = np.array([[2, 4], [6, 8]])\nprint('B:\\n', b)\n# displays the following result:\n# array([[2, 4],\n#        [6, 8]])\n\nprint('A + B:\\n', a + b)\n# displays the following result\n#      array([[ 3,  7],\n#             [11, 15]])\n", "meta": {"hexsha": "354947a505e92711cfd9013d146723edcbd9def4", "size": 5228, "ext": "py", "lang": "Python", "max_stars_repo_path": "1-neural-networks/matrix-math-NumPy-refresher/demo.py", "max_stars_repo_name": "vanyaland/deep-learning-foundation", "max_stars_repo_head_hexsha": "05a0df56c8223547bd7e8b62653a67f265c8e5ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-04-18T13:48:30.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-02T13:32:16.000Z", "max_issues_repo_path": "1-neural-networks/matrix-math-NumPy-refresher/demo.py", "max_issues_repo_name": "ivan-magda/deep-learning-foundation", "max_issues_repo_head_hexsha": "05a0df56c8223547bd7e8b62653a67f265c8e5ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1-neural-networks/matrix-math-NumPy-refresher/demo.py", "max_forks_repo_name": "ivan-magda/deep-learning-foundation", "max_forks_repo_head_hexsha": "05a0df56c8223547bd7e8b62653a67f265c8e5ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4411764706, "max_line_length": 117, "alphanum_fraction": 0.4900535578, "include": true, "reason": "import numpy", "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.8991213664574069, "lm_q1q2_score": 0.8558405670341708}}
{"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n# Import Library of Numpy\nimport numpy as np  \n\n\n# Version of Numpy\nnp.__version__   \n\n#NumPy is an N-dimensional array type called ndarray\n#NumPy rank 1 array\nx1 = np.array([1, 2, 3, 4,5])\nprint ('x1 =', x1) \nprint ('------------------------------')\nprint ('type (x1) =', type (x1))\nprint ('------------------------------')\nprint ('x1.shape =', x1.shape)\nprint ('------------------------------')\nprint ('x1.size =', x1.size) # number of elements\nprint ('------------------------------')\nprint (x1[0],',',x1[1],',',x1[2],',',x1[3]) #Prints \"1 2 3 4\"\nprint ('------------------------------')\nx1[3] = 0\nprint (x1) # Change an element\n#A data type object (an instance of numpy.dtype class) describes how the bytes in the fixed-size block of memory corresponding to an array item should be interpreted.\n'''#int8 = Byte (-128 to 127)\n#int16 = Integer (-32768 to 32767)\n#int32 = Integer (-2147483648 to +2147483647)\n#int64 = Integer (-9223372036854775808 to +9223372036854775807)\n#Boolean = (True or False) stored as a byte\n#float = Shorthand for float64 : Double precision float: sign bit, 11 bits exponent, 52 bits mantissa\n#complex = Shorthand for complex128 : Complex number\n#int8, int16, int32, int64 can be replaced by equivalent string 'i1', 'i2','i4', etc. '''\n    \nx1a = np.array([1, 2, 3, 4] , dtype='float') #Desired data type of array, optional\n#x1a = np.array([1, 2, 3, 4] , dtype='i1')\n#x1a = np.array([1, 2, 3, 4] , dtype= complex)\nprint ('x1a =', x1a) \nprint ('------------------------------')\nprint ('type (x1a) =', type (x1a))\nprint ('------------------------------')\nprint ('x1a.dtype =', x1a.dtype)\nprint ('------------------------------')\nprint ('x1a.itemsize =', x1a.itemsize) # 8 byte\nprint ('------------------------------')\nprint ('x1a.size =', x1a.size)\nprint ('------------------------------')\nprint ('x1a.shape =', x1a.shape)\nprint ('------------------------------')\nx1b = np.array([[.25, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16]])\nprint (x1b.dtype) #dtype is float\nprint ('------------------------------')\nprint ('x1b.shape =', x1b.shape) #(4,4)\nprint ('------------------------------')\nx1ba = x1b [0:2,1:3]\nprint ('x1ba [0:2,1:3] : ', x1ba)\nprint ('------------------------------')\nprint ('x1b [0,2] : ', x1b [0,2])\nprint ('------------------------------')\nx1b [0,2] = 17\nprint ('x1b = ', x1b)\nprint ('------------------------------')\nprint ('x1ba : ', x1ba) # has changed   3=>17\nprint ('------------------------------')\nx1ba = +x1b [0:2,1:3] #x1ba dosen't depend on x1b\nx1b [0,2] = 125\nprint ('------------------------------')\nprint ('x1b = ', x1b)\nprint ('------------------------------')\nprint ('x1ba : ', x1ba) # dosen't change\nprint ('------------------------------')\nx1c = np.array([[.25, 2, 3, 4],[8],[9, 10, 11, 12],[13, 14, 15, 16]])\nprint ('x1c.shape =', x1c.shape) #(4,)\nprint ('------------------------------')\nx1d = x1a.copy()\nprint('x1d =',x1d)\nprint ('------------------------------')\nprint ('x1d is x1a =', x1d is x1a) # False\nprint ('------------------------------')\nprint('x1d.ndim =',x1d.ndim) # dimension\n\n# More than one dimension\n#NumPy rank 2 array\nx2 = np.array([[1,2,3,4],[4,3,2,1]])\nprint (x2) \nprint (type (x2))\nprint (x2.shape)\nprint (x2[0,0],',',x2[1,3])\n\n#Return a array setting values to zero\nx2a = np.zeros((4,2)) \nprint ('x2a =',x2a)\nx2b = np.zeros_like(x2)\nprint ('------------------------------')\nprint('x2b =',x2b)\nprint ('------------------------------')\nx2b1 = np.zeros((2,4,2)) \nprint('x2b1 =',x2b1)\nprint('x2b1.ndim = ',x2b1.ndim)\nprint ('------------------------------')\n#Return a array setting values to one\nx2c = np.ones((4,3))\nprint('x2c =',x2c)\nprint ('------------------------------')\nx2c = np.ones((4,3), dtype='i1')\nprint('x2c =',x2c)\nprint ('------------------------------')\nx2d = (4,3)\nx2e = np.ones(x2d, dtype='int')\nprint('x2e =',x2e)\nprint ('------------------------------')\n\n#numpy.full => Return a new array of given shape and type, filled with fill_value.\nx2f = np.full((3,3),0)\nprint('x2f =',x2f)\nprint ('------------------------------')\nx2g = np.full((2,2),1)\nprint('x2g =',x2g)\nprint ('------------------------------')\nx2h = np.full((7,),6)\nprint('x2h =',x2h)\nprint ('------------------------------')\nx2i = np.full((5,2),'test')\nprint('x2i =',x2i)\nprint ('------------------------------')\n\n#numpy.eye => Return a 2-D array with ones on the diagonal and zeros elsewhere\nx2j = np.eye(4)\nprint('x2j =',x2j)\nprint ('------------------------------')\nx2k = np.eye(2, dtype=int)\nprint('x2k =',x2k)\nprint ('------------------------------')\nx2l = np.eye(5, k=2, dtype=int)   # k => Index of the diagonal : 0 (the default) refers to the main diagonal\nprint('x2l =',x2l)\nprint ('------------------------------')\n\n# array filled with random values\nx2m = np.random.random((3,2))\nprint('x2m =',x2m)\nprint ('------------------------------')\n#Create an array of the given shape and populate it with random samples from a uniform distribution over\nx2n = np.random.rand(2,5) # 2,5 are the dimensions of the returned array\nprint('x2n =',x2n)\nprint ('------------------------------')\n#uniform([low, high, size]) \tDraw samples from a uniform distribution\nx2o = np.random.uniform(2,7,(2,2))\nprint('x2o =',x2o)\nprint ('------------------------------')\n#standard_normal([size]) \tDraw samples from a standard Normal distribution (mean=0, stdev=1)\nx2p = np.random.standard_normal((2,2))\nprint('x2p =',x2p)\nprint ('------------------------------')\n\n#numpy.arange(start,stop,step, dtype=None)\n#Return evenly spaced values within a given interval.\nx3 = np.arange(7)\nprint ('x3 =',x3)\nprint ('------------------------------')\nx3a = np.arange(7.0)\nprint ('x3a =',x3a)\nprint ('------------------------------')\nx3b = np.arange(4.5)\nprint ('x3b =',x3b)\nprint ('------------------------------')\nx3c = np.arange(4,19)\nprint ('x3c =',x3c)\nprint ('------------------------------')\nx3d = np.arange(4,19,3)   # 3 is step\nprint ('x3d =',x3d)\nprint ('------------------------------')\nx3e = np.arange(4,19,3, dtype=float)\nprint ('x3e =',x3e)\nprint ('------------------------------')\nx3f = np.arange(4,19,2.4)\nprint ('x3f =',x3f)\nprint ('------------------------------')\n#numpy.linspace (start, stop, num) => Return evenly spaced numbers over a specified interval\n#from numpy import pi\nx3g = np.linspace(3.0, 9.0, num=9)\nprint ('x3g =',x3g)\nprint ('------------------------------')\n\n# A matrix is a specialized 2-D array that retains its 2-D nature through operations\nx3 = np.matrix([[1,2],[3,4]]) # Or x2 = np.matrix('1 2; 3 4')\nprint(x3)\nprint (type (x3))\nprint (x3.shape)\nprint (x3[1,1], x3[0,1], x3[0,0], x3[1,0])\n\n#Computation on NumPy Arrays\n#Dot product of two arrays. Specifically,\n#   If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).\n#   If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.\n#  If either a or b is 0-D (scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred.\nx4 = np.dot(7,2)\nprint(\"x4 = \",x4)\nprint ('------------------------------')\nx5 = np.ones((2,3))\nprint(\"x5 = \",x5)\nprint ('------------------------------')\nx6 = np.array([[2,5],[3,7],[9,6]])\nx7 = np.dot(x5,x6)\nprint(\"x7 = \",x7)\nprint ('------------------------------')\nx8 = x5 @ x6\nprint(\"x8 = \",x8)\nprint ('------------------------------')\nx9 = np.array([[2,2],[4,4]])\nx10 = np.multiply(x9,x9)\nprint('x10 = ',x9,'*',x9,' = ',x10)\nprint ('------------------------------')\nprint('x9 * x9 = ',x9*x9)\nprint ('------------------------------')\nprint('x9 @ x9 = ',x9@x9)\nprint ('------------------------------')\n#numpy.prod => Return the product of array elements over a given axis\nx11 = np.prod (x9)\nprint(\"x11 = \",x11)\nprint ('------------------------------')\n#The product of an empty array is the neutral element 1\nx12 = np.prod([] , dtype='i1')\nprint(\"x12 = \",x12)\nprint ('------------------------------')\n# we can also specify the axis over which to multiply\nx13 = np.prod([[1, 2, 3],[4, 5, 6],[11, 10, 2]], axis=0)\nprint(\"x13 = \",x13)\nprint ('------------------------------')\n\n#Broadcasting => The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations\nx14 = np.array([1.0, 2.0, 3.0, 4.0])\nx15 = x14 + 7\nprint(\"x15 = \",x15)\nprint ('------------------------------')\nx16 = np.ones((4,4))\nx17 = x14 + x16\nprint(\"x17 = \",x17)\nprint ('------------------------------')\nx18 = np.ones((4,1))\nx19 = x14 + x18\nprint(\"x19 = \",x19)\nprint ('------------------------------')\n\n#numpy.sum => Sum of array elements over a given axis\nx20 = np.sum([1.5, 2.5])\nprint(\"x20 = \",x20)\nprint ('------------------------------')\nx21 = np.sum([[2,4],[6,8]])\nprint(\"x21 = \",x21)\nprint ('------------------------------')\nx22 = np.sum([[2,4],[6,8]], axis=0)\nprint(\"x22 = \",x22)\nprint ('------------------------------')\nx23 = np.sum([[2,4],[6,8]], axis=1)\nprint(\"x23 = \",x23)\nprint ('------------------------------')\n#numpy.cumsum => Return the cumulative sum of the elements along a given axis\na = np.array([[1,2,3], [7,8,9]])\nx24 = np.cumsum(a)\nprint(\"x24 = \",x24)\nprint ('------------------------------')\nx25 = np.cumsum(a, axis=0)  # sum over rows for each of the 3 columns\nprint(\"x25 = \",x25)\nprint ('------------------------------')\nx26 = np.cumsum(a, axis=1) # sum over columns for each of the 2 rows\nprint(\"x26 = \",x26)\nprint ('------------------------------')\n#numpy.subtract\nx27 = np.subtract(a,a)\nprint(\"x27 = \",x27)\nprint ('------------------------------')\n#numpy.divide => Returns a true division of the inputs\nx28 = np.divide(a,2)\nprint(\"x28 = \",x28)\nprint ('------------------------------')\nx29 = np.floor_divide(a,2)\nprint(\"x29 = \",x29)\nprint ('------------------------------')\nx30 = np.true_divide(a,2)\nprint(\"x30 = \",x30)\nprint ('------------------------------')\n\n#numpy.math\n'''\n1- sin(x, /[, out, where, casting, order, ...]) \tTrigonometric sine, element-wise.\n2- cos(x, /[, out, where, casting, order, ...]) \tCosine element-wise.\n3- tan(x, /[, out, where, casting, order, ...]) \tCompute tangent element-wise.\n4- arcsin(x, /[, out, where, casting, order, ...]) \tInverse sine, element-wise.\n5- arccos(x, /[, out, where, casting, order, ...]) \tTrigonometric inverse cosine, element-wise.\n6- arctan(x, /[, out, where, casting, order, ...]) \tTrigonometric inverse tangent, element-wise.\n7- hypot(x1, x2, /[, out, where, casting, ...]) \tGiven the “legs” of a right triangle, return its hypotenuse.\n8- arctan2(x1, x2, /[, out, where, casting, ...]) \tElement-wise arc tangent of x1/x2 choosing the quadrant correctly.\n9- degrees(x, /[, out, where, casting, order, ...]) \tConvert angles from radians to degrees.\n10- radians(x, /[, out, where, casting, order, ...]) \tConvert angles from degrees to radians.\n11- unwrap(p[, discont, axis]) \tUnwrap by changing deltas between values to 2*pi complement.\n12- deg2rad(x, /[, out, where, casting, order, ...]) \tConvert angles from degrees to radians.\n13- rad2deg(x, /[, out, where, casting, order, ...]) \tConvert angles from radians to degrees.\n14- Hyperbolic functions\n15- sinh(x, /[, out, where, casting, order, ...]) \tHyperbolic sine, element-wise.\n16- cosh(x, /[, out, where, casting, order, ...]) \tHyperbolic cosine, element-wise.\n17- tanh(x, /[, out, where, casting, order, ...]) \tCompute hyperbolic tangent element-wise.\n18- arcsinh(x, /[, out, where, casting, order, ...]) \tInverse hyperbolic sine element-wise.\n19- arccosh(x, /[, out, where, casting, order, ...]) \tInverse hyperbolic cosine, element-wise.\n20- arctanh(x, /[, out, where, casting, order, ...]) \tInverse hyperbolic tangent element-wise.\n21- Rounding\n22- around(a[, decimals, out]) \tEvenly round to the given number of decimals.\n23- round_(a[, decimals, out]) \tRound an array to the given number of decimals.\n24- rint(x, /[, out, where, casting, order, ...]) \tRound elements of the array to the nearest integer.\n25- fix(x[, out]) \tRound to nearest integer towards zero.\n26- floor(x, /[, out, where, casting, order, ...]) \tReturn the floor of the input, element-wise.\n27- ceil(x, /[, out, where, casting, order, ...]) \tReturn the ceiling of the input, element-wise.\n28- trunc(x, /[, out, where, casting, order, ...]) \tReturn the truncated value of the input, element-wise.\n29- Sums, products, differences\n30- prod(a[, axis, dtype, out, keepdims]) \tReturn the product of array elements over a given axis.\n31- sum(a[, axis, dtype, out, keepdims]) \tSum of array elements over a given axis.\n32- nanprod(a[, axis, dtype, out, keepdims]) \tReturn the product of array elements over a given axis treating Not a Numbers (NaNs) as ones.\n33- nansum(a[, axis, dtype, out, keepdims]) \tReturn the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.\n34- cumprod(a[, axis, dtype, out]) \tReturn the cumulative product of elements along a given axis.\n35- cumsum(a[, axis, dtype, out]) \tReturn the cumulative sum of the elements along a given axis.\n36- nancumprod(a[, axis, dtype, out]) \tReturn the cumulative product of array elements over a given axis treating Not a Numbers (NaNs) as one.\n37- nancumsum(a[, axis, dtype, out]) \tReturn the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.\n38- diff(a[, n, axis]) \tCalculate the n-th discrete difference along given axis.\n39- ediff1d(ary[, to_end, to_begin]) \tThe differences between consecutive elements of an array.\n40- gradient(f, *varargs, **kwargs) \tReturn the gradient of an N-dimensional array.\n41- cross(a, b[, axisa, axisb, axisc, axis]) \tReturn the cross product of two (arrays of) vectors.\n42- trapz(y[, x, dx, axis]) \tIntegrate along the given axis using the composite trapezoidal rule.\n43- Exponents and logarithms\n44- exp(x, /[, out, where, casting, order, ...]) \tCalculate the exponential of all elements in the input array.\n45- expm1(x, /[, out, where, casting, order, ...]) \tCalculate exp(x) - 1 for all elements in the array.\n46- exp2(x, /[, out, where, casting, order, ...]) \tCalculate 2**p for all p in the input array.\n47- log(x, /[, out, where, casting, order, ...]) \tNatural logarithm, element-wise.\n48- log10(x, /[, out, where, casting, order, ...]) \tReturn the base 10 logarithm of the input array, element-wise.\n49- log2(x, /[, out, where, casting, order, ...]) \tBase-2 logarithm of x.\n50- log1p(x, /[, out, where, casting, order, ...]) \tReturn the natural logarithm of one plus the input array, element-wise.\n51- logaddexp(x1, x2, /[, out, where, casting, ...]) \tLogarithm of the sum of exponentiations of the inputs.\n52- logaddexp2(x1, x2, /[, out, where, casting, ...]) \tLogarithm of the sum of exponentiations of the inputs in base-2.\n53- Other special functions\n54- i0(x) \tModified Bessel function of the first kind, order 0.\n55- sinc(x) \tReturn the sinc function.\n56- Floating point routines\n57- signbit(x, /[, out, where, casting, order, ...]) \tReturns element-wise True where signbit is set (less than zero).\n58- copysign(x1, x2, /[, out, where, casting, ...]) \tChange the sign of x1 to that of x2, element-wise.\n59- frexp(x[, out1, out2], / [[, out, where, ...]) \tDecompose the elements of x into mantissa and twos exponent.\n60- ldexp(x1, x2, /[, out, where, casting, ...]) \tReturns x1 * 2**x2, element-wise.\n61- nextafter(x1, x2, /[, out, where, casting, ...]) \tReturn the next floating-point value after x1 towards x2, element-wise.\n62- spacing(x, /[, out, where, casting, order, ...]) \tReturn the distance between x and the nearest adjacent number.\n63- Arithmetic operations\n64- add(x1, x2, /[, out, where, casting, order, ...]) \tAdd arguments element-wise.\n65- reciprocal(x, /[, out, where, casting, ...]) \tReturn the reciprocal of the argument, element-wise.\n66- negative(x, /[, out, where, casting, order, ...]) \tNumerical negative, element-wise.\n67- multiply(x1, x2, /[, out, where, casting, ...]) \tMultiply arguments element-wise.\n68- divide(x1, x2, /[, out, where, casting, ...]) \tDivide arguments element-wise.\n69- power(x1, x2, /[, out, where, casting, ...]) \tFirst array elements raised to powers from second array, element-wise.\n70- subtract(x1, x2, /[, out, where, casting, ...]) \tSubtract arguments, element-wise.\n71- true_divide(x1, x2, /[, out, where, ...]) \tReturns a true division of the inputs, element-wise.\n72- floor_divide(x1, x2, /[, out, where, ...]) \tReturn the largest integer smaller or equal to the division of the inputs.\n73- float_power(x1, x2, /[, out, where, ...]) \tFirst array elements raised to powers from second array, element-wise.\n74- fmod(x1, x2, /[, out, where, casting, ...]) \tReturn the element-wise remainder of division.\n75- mod(x1, x2, /[, out, where, casting, order, ...]) \tReturn element-wise remainder of division.\n76- modf(x[, out1, out2], / [[, out, where, ...]) \tReturn the fractional and integral parts of an array, element-wise.\n77- remainder(x1, x2, /[, out, where, casting, ...]) \tReturn element-wise remainder of division.\n78- divmod(x1, x2[, out1, out2], / [[, out, ...]) \tReturn element-wise quotient and remainder simultaneously.\n79- Handling complex numbers\n80- angle(z[, deg]) \tReturn the angle of the complex argument.\n81- real(val) \tReturn the real part of the complex argument.\n82- imag(val) \tReturn the imaginary part of the complex argument.\n83- conj(x, /[, out, where, casting, order, ...]) \tReturn the complex conjugate, element-wise.\n84- Miscellaneous\n85- convolve(a, v[, mode]) \tReturns the discrete, linear convolution of two one-dimensional sequences.\n86- clip(a, a_min, a_max[, out]) \tClip (limit) the values in an array.\n87- sqrt(x, /[, out, where, casting, order, ...]) \tReturn the positive square-root of an array, element-wise.\n88- cbrt(x, /[, out, where, casting, order, ...]) \tReturn the cube-root of an array, element-wise.\n89- square(x, /[, out, where, casting, order, ...]) \tReturn the element-wise square of the input.\n90- absolute(x, /[, out, where, casting, order, ...]) \tCalculate the absolute value element-wise.\n91- fabs(x, /[, out, where, casting, order, ...]) \tCompute the absolute values element-wise.\n92- sign(x, /[, out, where, casting, order, ...]) \tReturns an element-wise indication of the sign of a number.\n93- heaviside(x1, x2, /[, out, where, casting, ...]) \tCompute the Heaviside step function.\n94- maximum(x1, x2, /[, out, where, casting, ...]) \tElement-wise maximum of array elements.\n95- minimum(x1, x2, /[, out, where, casting, ...]) \tElement-wise minimum of array elements.\n96- fmax(x1, x2, /[, out, where, casting, ...]) \tElement-wise maximum of array elements.\n97- fmin(x1, x2, /[, out, where, casting, ...]) \tElement-wise minimum of array elements.\n98- nan_to_num(x[, copy]) \tReplace nan with zero and inf with finite numbers.\n99- real_if_close(a[, tol]) \tIf complex input returns a real array if complex parts are close to zero.\n100- interp(x, xp, fp[, left, right, period]) \tOne-dimensional linear interpolation.'''\n#numpy.reshape => Gives a new shape to an array without changing its data\nx31 = np.arange(8).reshape(4,2) # 4*2 = 8 (number of elements)\nprint(\"x31 = \",x31)\nprint ('------------------------------')\nx31a = np.arange(4).reshape(4) # reshape(4) => number of columns\nprint(\"x31a = \",x31a)\nprint ('------------------------------')\nx32 = np.math.inf #IEEE 754 floating point representation of (positive) infinity.\nprint(\"x32 = \",x32)\nprint ('------------------------------')\n#x33 = np.array([1]) / 0\n#print(\"x33 = \",x33)\n#print ('------------------------------')\nx34 = np.math.nan #not a number\nprint(\"x34 = \",x34)\nprint ('------------------------------')\n\n#Mask => Logic functions\n'''\nLogical operations:\nlogical_and(x1, x2, /[, out, where, ...]) \tCompute the truth value of x1 AND x2 element-wise.\nlogical_or(x1, x2, /[, out, where, casting, ...]) \tCompute the truth value of x1 OR x2 element-wise.\nlogical_not(x, /[, out, where, casting, ...]) \tCompute the truth value of NOT x element-wise.\nlogical_xor(x1, x2, /[, out, where, ...]) \tCompute the truth value of x1 XOR x2, element-wise.'''\n\nx35 = np.arange(18).reshape(3,2,3) # 3*2*3 = 9 (number of elements)\nprint(\"x35 = \",x35)\nprint(\"x35.ndim = \",x35.ndim) # ndim = 3\nprint ('------------------------------')\nx35a = np.arange(24).reshape(4,2,3)\nprint(\"x35a = \",x35a)\nprint(\"x35a.ndim = \",x35a.ndim) # ndim = 3\nprint ('------------------------------')\nx35b = np.arange(40).reshape(2,5,4)\nprint(\"x35b = \",x35b)\nprint(\"x35b.ndim = \",x35b.ndim) # ndim = 3\nprint ('------------------------------')\nx35c = np.arange(20).reshape(1,5,4)\nprint(\"x35c = \",x35c)\nprint(\"x35c.ndim = \",x35c.ndim) # ndim = 3\nprint ('------------------------------')\nx36 = x35 < 4\nprint(\"x36 = \",x36)\nprint ('------------------------------')\nx37 = x35 [x36]\nprint(\"x37 = \",x37)\nprint ('------------------------------')\nx38 = np.logical_and(x35>=2 , x35<5)\nprint(\"x38 = \",x38)\nprint ('------------------------------')\nx39 = x35 [x38]\nprint(\"x39 = \",x39)\nprint ('------------------------------')\n\n#other\n#NumPy.unique => Find the unique elements of an array\nx40 = np.unique([1, 1, 2, 2, 3, 3,4,4,4,5])\nprint(\"x40 = \",x40)\nprint ('------------------------------')\nx41 = np.unique(np.array(([[1, 1], [2, 2], [3,2], [4,5]]))) \nprint(\"x41 = \",x41)\nprint ('------------------------------')\nx42 = np.unique(np.array([[1, 2, 3], [1, 2, 3], [2, 3, 4]]), axis=0) #Return the unique rows of a 2D array\nprint(\"x42 = \",x42)\nprint ('------------------------------')\n#numpy.union1d =>  Find the union of two arrays\na = np.arange(12,27,2).reshape(2,4)\nprint(\"a = \",a)\nprint ('------------------------------')\nb = np.ones((2,3), dtype='1i')\nprint(\"b = \",b)\nprint ('------------------------------')\nc = np.arange(1,7).reshape(3,2)\nprint(\"c = \",c)\nprint ('------------------------------')\nx43 = np.union1d(b,c)\nprint(\"x43 = \",x43)\nprint ('------------------------------')\n# find the union of more than two arrays, use functools.reduce\nfrom functools import reduce\nx44 = reduce(np.union1d, (a,b,c))\nprint(\"x44 = \",x44)\nprint ('------------------------------')\n#numpy.intersect1d => Find the intersection of two arrays\nx45 = np.intersect1d(b,c)\nprint(\"x45 = \",x45)\nprint ('------------------------------')\nx46 = reduce(np.intersect1d, ([1, 3, 5, 3], [6, 1, 3, 1], [7, 3, 1, 2]))\nprint(\"x46 = \",x46)\nprint ('------------------------------')\n\n# numpy.sort => Return a sorted copy of an array\nx47 = np.array([[1,4,2,2],[3,1,4,5],[8,8,7,20]])\nx48 = np.sort(x47)\nprint(\"x48 = \",x48)\nprint ('------------------------------')\nx49 = np.sort(x47, axis=0)\nprint(\"x49 = \",x49)\nprint ('------------------------------')\nx50 = np.sort(x47, axis=1)\nprint(\"x50 = \",x50)\nprint ('------------------------------')\nx51 = np.sort(x47, axis=None)\nprint(\"x51 = \",x51)\nprint ('------------------------------')\n#Using tuple for numpy.ndarray\nx52 = np.array ((2,3,4,5))\nprint(\"x52 = \",x52)\nprint ('------------------------------')\nx53 = np.array (((2,3,4,5),(5,6,8,7)))\nprint(\"x53 = \",x53)\nprint ('------------------------------')\nprint(\"type (x53) : \",type (x53))\n\n#numpy.vstack => Stack arrays in sequence vertically (row wise)\nx54 = np.array([2, 4, 6])\nx55 = np.array([1, 3, 7])\nx56 = np.vstack((x54,x55)) #The numbe of column (x54,x55) is same\n#x56 = np.vstack([x54,x55])\nprint(\"x56 = \",x56)\nprint ('------------------------------')\nx57 = np.vstack((x55,x54))\nprint(\"x57 = \",x57)\nprint ('------------------------------')\n#numpy.hstack => Stack arrays in sequence horizontally (column wise)\nx58 = np.hstack((x54,x55))\nprint(\"x58 = \",x58)\n\n# numpy.ndarray and (for    in  )\nx59 = np.array([[2,85,79,34],[5,78,36,44],[12,0,1,99]])\nprint('x59 = ')\nfor x in x59:   #show the rows separately\n    print(x)\nprint ('------------------------------')\nx60 = x59.reshape(12)\nprint('x60 = ')\nfor x in x60:\n    print(x)\nprint ('------------------------------')\n#numpy.ravel => Return a contiguous flattened array.\nprint('x59 = ')\nfor x in np.ravel(x59):  #for x in x60.ravel()\n    print(x)\nprint ('------------------------------')\n#Iterating Over Arrays\nprint('x59 = ')\nfor x in np.nditer(x59):\n    print (x)\nprint ('------------------------------')\nx61 = iter(x59)\nfor x in x59:\n    print ('next(x61) = ',next(x61))\n    print ('.............')\nprint ('------------------------------')\nx62 = iter(x59)\nfor x in x59:\n    y = next(x62)\n    for z in y:\n        print (z)        \n        \nx63 = np.mean (x59)\nprint(\"mean = \",x63)\nprint ('------------------------------')\nx64 = np.var (x59)\nprint(\"var = \",x64)\nprint ('------------------------------')\nx65 = np.std (x59)\nprint(\"std = \",x65)\nprint ('------------------------------')\nx66 = np.median (x59)\nprint(\"median = \",x66)\nprint ('------------------------------')\n\n#numpy.polyval(p, x) => Evaluate a polynomial at specific values\n# ax^2+bx+c = 0\n# 2x^2+x+3 = 0\nx67 = np.array([2,1,3])\nprint ('x=2 => 2x^2+x+3 = 0, ', np.polyval(x67,2))\nprint ('------------------------------')\n# numpy.polyder => Return the derivative of the specified order of a polynomial\nprint ('np.polyder(x67) : ', np.polyder(x67))\nprint ('------------------------------')\n#numpy.polyint => Return an antiderivative (indefinite integral) of a polynomial\nprint ('np.polyint(x67) : ', np.polyint(x67))\nprint ('------------------------------')\n\n# Comparing Lists and Arrays\n\n# Make a list\nL_1 = [1, 2, 3, 4]\n# Make Equivalent Array\nA_1 = np.array ([1, 2, 3, 4])\n\n# print reverse of list\nL_1.reverse()\n\n#L_1 = L_1[::-1]\n\nfor e in L_1:\n\tprint (e)\n\nprint ('-----------------')\n\n# reverse the array\nA_1 = A_1[::-1]\n\nfor i in A_1:\n\tprint (i)\n\n\nprint ('-----------------')\n\n# insert an element into list\nL_1.append(5)\nprint (L_1)\n\nprint ('-----------------')\n\n#A_1.append(5)   # Error\n#print A_1\n\n#A_1 = A_1 + [6,7] # eRROR\n#print A_1  \n\n#print ('-----------------')\n\nL_1 = L_1 + [6,7]\nprint (L_1) \n\nprint ('-----------------')\n\nL_1 =  L_1 + L_1\nprint (L_1)\n\nL_2 = []\nfor i in L_1:\n\tL_2.append(i+i)\nprint (L_2)\n\nprint ('-----------------')\n\nA_1 = A_1+A_1\nprint (A_1)\n\nprint ('-----------------')\n\nA_1 = A_1 * 2\nprint (A_1)\n\nL_1 = L_1 * 2\nprint (L_1)\n\nprint ('-----------------')\n\nL_1 = [1, 2, 3, 4]\n#L_1 = L_1 **2 # Error\n#print (L_1)\n\nL_3 = []\nfor i in L_1:\n\tL_3.append(i * i)\nprint (L_3)\n\nprint ('-----------------')\n\nA_1 = np.array ([1, 2, 3, 4])\nA_1 = A_1 ** 2\nprint(A_1)\n\nprint ('-----------------')\n\nprint (np.sqrt(A_1))\nprint (np.log(A_1))\nprint (np.exp(A_1))\n\n# for the list u need use a for loop\nprint ('-----------------')\n\nx = np.array([1,2])\ny = np.array([2,1])\n\ndot = 0\n\nfor i, j in zip(x, y):\n\tdot += (i*j)\nprint(dot)\n\nprint (x*y)  # * ----> element by element multiplication\n\nprint (np.sum(x*y))\nprint ((x*y).sum())\nprint (np.dot(x,y))  #   dot ------> matrix multiplication\n# angle between x, y\nangle = np.arccos(x.dot(y)/(np.linalg.norm(x) * np.linalg.norm(y)))\nprint (angle)\n\nx = np.array([[1,2,3],[4,5,6]])\ny = np.array([[7,8],[9,10],[11,12]])\n\nprint(x.dot(y))\nprint (np.dot(x,y))\nprint(y.dot(x))\n# print (x*y)\n# print (np.sum(x*y))\n# print ((x*y).sum())\nprint ('-----------------')\n\n# Magnitude of the vector:  np.sqrt((x*x).sum())\nprint (np.linalg.norm(x))\n\nprint ('-----------------')\n\n# list of lists\nL = [[1, 2], [3, 4]]\n\nA = np.array ([[4, 5], [6, 7]])\n\n\nprint(L[0])\nprint(L[0][0])\nprint(A[0][0])\nprint(A[0,0])\n\nA_2 = np.matrix(L)\nprint(A_2)\nA_3 = np.array(A_2)\nprint (A_3)\n\nprint ('-----------------')\n\n# transpose\n\nprint (A_3.T)\n\n# matrix is -----> two-dimensional numpy array\n# vector is -----> one-dimensional array\n\nprint ('-----------------')\n\nZ_a = np.zeros(14)\nprint (Z_a)\n\nZ_a = np.zeros((14, 14))\nprint (Z_a)\n\nZ_a = np.ones((14, 14))\nprint (Z_a)\n\nZ_r = np.random.random ((14, 14))\nprint (Z_r)\n\n#Z_r = np.random.randn ((14, 14))\n#print (Z_r)\n\nZ_r = np.random.randn (14, 14)\nprint (Z_r)\n\nprint (Z_r.mean())\n\nprint (Z_r.var())\n\n\nprint ('-----------------')\n\n#inverse\nA_4 = np.array([[2, 4], [1, 3]])\nprint (A_4)\nA_4_inv = np.linalg.inv(A_4)\nprint(A_4_inv)\nprint (np.linalg.det(A_4))\nprint (np.diag(A_4))\n\n# 1, 2 go in the diagonal and everything else is 0.\nprint (np.diag ([8, 9]))\n\n# Compute the outer/inner product of two vectors\nx = np.array([4, 8])\ny = np.array([16, 32])\nprint (np.outer(x, y))\nprint (np.inner(x, y))\nprint (x.dot(y))\nprint (np.diag(A_4).sum())\nprint (np.trace(A_4))\n\nprint ('-----------------')\n\nX_r = np.random.randn(100, 4)  # 100 samples and 4 features\ncov = np.cov(X_r)\nprint (cov.shape)\n\n# covariance <--------> transpose\ncov = np.cov(X_r.T)   # 4 * 4\nprint (cov)\n\nprint ('-----------------')\n\n#Covariance is a Symmetricmatrix\n#eigenvalues, eigenvectors = np.eig(x) or np.eigh(x)\n#eigh -------> symmetric and Hermitian matrix\n#Symmetric means A = A**T\n#Hermitian means A = A**H\n#A**H = conjugate transpose of A\n\nprint (np.linalg.eigh(cov))\nprint (np.linalg.eig(cov))\n\nprint ('-----------------')\n", "meta": {"hexsha": "4cb16cbb4e28adf2e856f75cdc9def2961163ab0", "size": 28563, "ext": "py", "lang": "Python", "max_stars_repo_path": "Prerequisites_Numpy_Stack.py", "max_stars_repo_name": "Farhad-UPC/Deep_Learning", "max_stars_repo_head_hexsha": "a4da8159e53d5aaf68defb3d8201b6f3dc32632b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Prerequisites_Numpy_Stack.py", "max_issues_repo_name": "Farhad-UPC/Deep_Learning", "max_issues_repo_head_hexsha": "a4da8159e53d5aaf68defb3d8201b6f3dc32632b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Prerequisites_Numpy_Stack.py", "max_forks_repo_name": "Farhad-UPC/Deep_Learning", "max_forks_repo_head_hexsha": "a4da8159e53d5aaf68defb3d8201b6f3dc32632b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0643939394, "max_line_length": 166, "alphanum_fraction": 0.5538633897, "include": true, "reason": "import numpy,from numpy", "num_tokens": 8834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.9294404038127071, "lm_q1q2_score": 0.8558191241460983}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\nN = 50\n\nx_start, x_end = -2.0, 2.0\ny_start, y_end = -1.0, 1.0\n\nx = np.linspace(x_start, x_end, N)\ny = np.linspace(y_start, y_end, N)\n\nX, Y = np.meshgrid(x, y)\n\ngamma = 5.0\nx_vortex, y_vortex = 0.0, 0.0\n\n\ndef get_velocity_vortex(strength, xv, yv, X, Y):\n\n    u = + strength / (2 * np.pi) * (Y - yv) / ((X - xv)**2 + (Y - yv)**2)\n    v = - strength / (2 * np.pi) * (X - xv) / ((X - xv)**2 + (Y - yv)**2)\n\n    return u, v\n\n\ndef get_stream_function_vortex(strength, xv, yv, X, Y):\n\n    psi = strength / (4 * np.pi) * np.log((X - xv)**2 + (Y - yv)**2)\n\n    return psi\n\n\nu_vortex, v_vortex = get_velocity_vortex(gamma, x_vortex, y_vortex, X, Y)\n\npsi_vortex = get_stream_function_vortex(gamma, x_vortex, y_vortex, X, Y)\n\nsize = 10\nplt.figure(figsize=(size, (y_end - y_start) / (x_end - x_start) * size))\nplt.xlabel('x', fontsize=16)\nplt.ylabel('y', fontsize=16)\nplt.xlim(x_start, x_end)\nplt.ylim(y_start, y_end)\nplt.streamplot(X, Y, u_vortex, v_vortex, density=2,\n               linewidth=1, arrowsize=1, arrowstyle='->')\nplt.scatter(x_vortex, y_vortex, color='#CD2305', s=80, marker='o')\n\nplt.show()\n\nstrength_sink = -1.0\nx_sink, y_sink = 0.0, 0.0\n\n\ndef get_velocity_sink(strength, xs, ys, X, Y):\n\n    u = strength / (2 * np.pi) * (X - xs) / ((X - xs)**2 + (Y - ys)**2)\n    v = strength / (2 * np.pi) * (Y - ys) / ((X - xs)**2 + (Y - ys)**2)\n\n    return u, v\n\n\ndef get_stream_function_sink(strength, xs, ys, X, Y):\n\n    psi = strength / (2 * np.pi) * np.arctan2((Y - ys), (X - xs))\n\n    return psi\n\nu_sink, v_sink = get_velocity_sink(strength_sink, x_sink, y_sink, X, Y)\n\npsi_sink = get_stream_function_sink(strength_sink, x_sink, y_sink, X, Y)\n\nu = u_vortex + u_sink\nv = v_vortex + v_sink\npsi = psi_vortex + psi_sink\n\nsize = 10\nplt.figure(figsize=(size, (y_end - y_start) / (x_end - x_start) * size))\nplt.xlabel('x', fontsize=16)\nplt.ylabel('y', fontsize=16)\nplt.xlim(x_start, x_end)\nplt.ylim(y_start, y_end)\nplt.streamplot(X, Y, u, v, density=2, linewidth=1,\n               arrowsize=1, arrowstyle='->')\nplt.scatter(x_vortex, y_vortex, color='#CD2305', s=80, marker='o')\n\nplt.show()\n", "meta": {"hexsha": "6f42b7f13f00903a5fa04a214ca8d145be74338a", "size": 2132, "ext": "py", "lang": "Python", "max_stars_repo_path": "lessons/04_vortex.py", "max_stars_repo_name": "PabloRdrRbl/my-AeroPython", "max_stars_repo_head_hexsha": "c0c1ffac5edcb9e93c95e98807bbb5c00e9a6ec4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lessons/04_vortex.py", "max_issues_repo_name": "PabloRdrRbl/my-AeroPython", "max_issues_repo_head_hexsha": "c0c1ffac5edcb9e93c95e98807bbb5c00e9a6ec4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lessons/04_vortex.py", "max_forks_repo_name": "PabloRdrRbl/my-AeroPython", "max_forks_repo_head_hexsha": "c0c1ffac5edcb9e93c95e98807bbb5c00e9a6ec4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5057471264, "max_line_length": 73, "alphanum_fraction": 0.6210131332, "include": true, "reason": "import numpy", "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854146791214, "lm_q2_score": 0.8824278741843884, "lm_q1q2_score": 0.8557656818903226}}
{"text": "import copy\nimport generators\nimport math\nimport neighbor_states as ns\nimport numpy as np\nimport plotter\nimport random as rand\n\n\ndef get_matrix(cities):\n    n = len(cities)\n    result = np.zeros((n, n))\n\n    for x in range(n):\n        for y in range(n):\n            x1 = cities[x][0]\n            y1 = cities[x][1]\n            x2 = cities[y][0]\n            y2 = cities[y][1]\n            distance = np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n            result[x][y] = distance\n            result[y][x] = distance\n    return result\n\n\ndef path_distance(path, distances):\n    distance = 0\n    for i in range(len(path) - 1):\n        distance += distances[path[i][2]][path[i + 1][2]]\n    return distance\n\n\ndef travelling_salesman_problem(n, iterations, temperature, decay_rate, swap_type, low, high, distribution):\n    if distribution == \"uniform\":\n        path = generators.get_uniform_distribution_points(low, high, n)\n    elif distribution == \"normal\" or distribution == \"gaussian\":\n        path = generators.get_normal_distribution_points(low, high, n)\n    elif distribution == \"groups\" or distribution == \"9 groups\":\n        path = generators.get_9_groups_of_points(low, high, n)\n    else:\n        raise ValueError(\"Error: distribution argument was not uniform, normal or groups!\")\n\n    first_path = copy.copy(path)\n\n    if swap_type != \"consecutive\" and swap_type != \"arbitrary\":\n        raise ValueError(\"Error: swap type argument was not consecutive or arbitrary!\")\n\n    distances = get_matrix(path)\n\n    rand.shuffle(path)\n\n    best_path = path\n    min_distance = path_distance(best_path, distances)\n\n    iters = []\n    dists = []\n    temperatures = []\n\n    for i in range(iterations):\n        iters.append(i)\n\n        new_path = copy.copy(path)\n        if swap_type == \"consecutive\":\n            new_path = ns.consecutive_swap(new_path)\n        else:\n            new_path = ns.consecutive_swap(new_path)\n\n        old_path_distance = path_distance(path, distances)\n        new_path_distance = path_distance(new_path, distances)\n\n        dists.append(new_path_distance)\n\n        if new_path_distance < old_path_distance:\n            path = new_path\n            if new_path_distance < min_distance:\n                min_distance = new_path_distance\n        elif math.exp(-(new_path_distance - old_path_distance)/temperature) > rand.uniform(0, 1):\n            path = new_path\n\n        temperatures.append(temperature)\n        temperature *= decay_rate\n\n    distances_plot_data = (copy.copy(iters), dists)\n    temperatures_plot_data = (iters, temperatures)\n    return first_path, best_path, distances_plot_data, temperatures_plot_data\n\n\nn = 200\niterations = 500000\ntemperature = 1000\ndecay_rate = 0.99995\nswap_type = \"consecutive\"\nlow = 0\nhigh = 1\ndistribution = \"uniform\"\n\nfirst_path, best_path, distances_plot_data, temperatures_plot_data = travelling_salesman_problem(n, iterations, temperature, decay_rate, swap_type, low, high, distribution)\n\nplotter.plot_data(first_path, best_path, distances_plot_data, temperatures_plot_data)\n", "meta": {"hexsha": "c15ecbb686f6aadc4d7e1e63436d36887d403ee5", "size": 3030, "ext": "py", "lang": "Python", "max_stars_repo_path": "lab4_simulated_annealing/task_1/main.py", "max_stars_repo_name": "j-adamczyk/Numerical-Algorithms", "max_stars_repo_head_hexsha": "47cfa8154bab448d1bf87b892d83e45c68dd2e2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-03-16T11:23:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-16T21:04:01.000Z", "max_issues_repo_path": "lab4_simulated_annealing/task_1/main.py", "max_issues_repo_name": "j-adamczyk/Numerical-Algorithms", "max_issues_repo_head_hexsha": "47cfa8154bab448d1bf87b892d83e45c68dd2e2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab4_simulated_annealing/task_1/main.py", "max_forks_repo_name": "j-adamczyk/Numerical-Algorithms", "max_forks_repo_head_hexsha": "47cfa8154bab448d1bf87b892d83e45c68dd2e2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3, "max_line_length": 172, "alphanum_fraction": 0.6650165017, "include": true, "reason": "import numpy", "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854111860907, "lm_q2_score": 0.8824278772763471, "lm_q1q2_score": 0.8557656818065115}}
{"text": "import math\nimport numpy as np\n\n\ndef norm(vec: np.ndarray):\n    return math.sqrt(math.pow(vec[0], 2) + math.pow(vec[1], 2) + math.pow(vec[2], 2))\n\n\ndef dot(vec: np.ndarray, vec2: np.ndarray):\n    return vec[0] * vec2[0] + vec[1] * vec2[1] + vec[2] * vec2[2]\n\n\ndef normalize(vec: np.ndarray):\n    \"\"\"Returns a normalized vector of norm 1.\"\"\"\n    return vec / max(norm(vec), 1e-8)\n\n\ndef normalize_batch(vec: np.ndarray):\n    return vec / np.maximum(np.linalg.norm(vec, axis=-1), 1e-8)\n", "meta": {"hexsha": "ad74d41bbf54505541a6fd27f05aede6ee0d36e9", "size": 483, "ext": "py", "lang": "Python", "max_stars_repo_path": "util/linear_algebra.py", "max_stars_repo_name": "oxrock/DisasterBot", "max_stars_repo_head_hexsha": "36260e9ef8730edbae018ba87aa19aaad72c8814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-11-18T09:30:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T18:47:48.000Z", "max_issues_repo_path": "util/linear_algebra.py", "max_issues_repo_name": "oxrock/DisasterBot", "max_issues_repo_head_hexsha": "36260e9ef8730edbae018ba87aa19aaad72c8814", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-01-31T11:37:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T19:13:54.000Z", "max_forks_repo_path": "util/linear_algebra.py", "max_forks_repo_name": "oxrock/DisasterBot", "max_forks_repo_head_hexsha": "36260e9ef8730edbae018ba87aa19aaad72c8814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-11-17T20:02:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-01T15:07:13.000Z", "avg_line_length": 24.15, "max_line_length": 85, "alphanum_fraction": 0.6335403727, "include": true, "reason": "import numpy", "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854146791214, "lm_q2_score": 0.8824278680004707, "lm_q1q2_score": 0.8557656758932495}}
{"text": "import json\r\nimport math\r\nimport numpy as np\r\n\r\n\r\ndef compute_z(x, y):\r\n    theta = np.array([x, y, 0])\r\n    p = np.exp(theta) / np.sum(np.exp(theta))\r\n    return p[1]\r\n\r\n\r\nn = 111\r\nm = 111\r\n\r\nxs = np.linspace(-3, 3, n)\r\nys = np.linspace(-3, 3, m)\r\n\r\n\r\nX, Y = np.meshgrid(xs, ys)\r\nZ = np.empty_like(X)\r\n\r\nfor i in range(n):\r\n    for j in range(m):\r\n        x = X[i, j]\r\n        y = Y[i, j]\r\n        Z[i, j] = compute_z(x, y)\r\n\r\npoints = np.column_stack([X.ravel(), Y.ravel(), Z.ravel()])\r\n\r\n# by default, this point cloud would be displayed with Z facing up.\r\n# let's rotate it to make it prettier\r\n\r\ndef rotate3d_x(points, theta):\r\n    c = math.cos(theta)\r\n    s = np.sin(theta)\r\n\r\n    R = np.array([[1, 0, 0],\r\n                  [0, c, -s],\r\n                  [0, s, c]])\r\n    return np.dot(points, R)\r\n\r\ndef rotate3d_z(points, theta):\r\n    c = math.cos(theta)\r\n    s = np.sin(theta)\r\n\r\n    R = np.array([[c, -s, 0],\r\n                  [s, c, 0],\r\n                  [0, 0, 1]])\r\n    return np.dot(points, R)\r\n\r\npoints = rotate3d_z(points, np.pi / 4)\r\npoints = rotate3d_x(points, np.pi / 2.5)\r\n\r\ndata = {\r\n    'x': points[:, 0].tolist(),\r\n    'y': points[:, 1].tolist(),\r\n    'z': points[:, 2].tolist()\r\n}\r\n\r\ntemplate = f\"\"\"\\\r\nvar n = {n};\r\nvar m = {m};\r\nvar data = {json.dumps(data)};\r\n\"\"\"\r\n\r\nwith open('data.js', 'w')  as f:\r\n    print(template, file=f)\r\n", "meta": {"hexsha": "dcce31f13d4ad513f30e0b93d96059e45c808128", "size": 1358, "ext": "py", "lang": "Python", "max_stars_repo_path": "generate.py", "max_stars_repo_name": "vene/threedposts", "max_stars_repo_head_hexsha": "3f6774a6d9b1c5bfbe9f9054e16e629e0f5cb562", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "generate.py", "max_issues_repo_name": "vene/threedposts", "max_issues_repo_head_hexsha": "3f6774a6d9b1c5bfbe9f9054e16e629e0f5cb562", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generate.py", "max_forks_repo_name": "vene/threedposts", "max_forks_repo_head_hexsha": "3f6774a6d9b1c5bfbe9f9054e16e629e0f5cb562", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9705882353, "max_line_length": 68, "alphanum_fraction": 0.4948453608, "include": true, "reason": "import numpy", "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969785412932606, "lm_q2_score": 0.8824278571786139, "lm_q1q2_score": 0.8557656638571968}}
{"text": "![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true)\n\n<a href=\"https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Mathematics/FibonacciNumbers/fibonacci-numbers.ipynb&depth=1\" target=\"_parent\"><img src=\"https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true\" width=\"123\" height=\"24\" alt=\"Open in Callysto\"/></a>\n\n# Fibonacci Numbers\n\nThe **Fibonacci** sequence is the set of numbers that starts out like this:\n\n$$0,1,1,2,3,5,8,13,\\ldots.$$\n\nIt's easy to recognize the pattern here. Each number is the sum of the previous two numbers in the sequence. Except, of course, the first two number, 0 and 1, which we put in there to get things started. \n\nThis sequence, or pattern of numbers, goes on forever.\n\nThese numbers are most commonly known as the **Fibonacci numbers**, after the Italian mathematician **L. Fibonacci** (c. 1200 C.E.). However, these numbers were actually first described hundreds of years before, by Indian mathematicians. The first such mathematician for whom we have written records was **Virahanka** (c. 700 C.E.).\n\nIt is difficult to overcome the usage of a name adopted hundreds of years ago, and so in what follows we will refer to the Virahanka-Fibonacci numbers as the \"Fibonacci numbers.\"\n\n**Exercise 1:** Check out the following article about the \"so-called Fibonacci\" numbers in ancient India: https://www.sciencedirect.com/science/article/pii/0315086085900217\n\nFor an excellent exposition about the motivation, poetry, and linguistics of these early mathematicians, and to learn about some fascinating properties of these numbers, check out the following video:\n\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('LP253wHIoO8', start=2633)\n\nIt's convenient to label these numbers, so we write $F_0 = 0$, $F_1 = 1$ $F_2 = 2$ and so on. The list of numbers is thus  defined **recursively**  by the formula\n$$ \\qquad$$\n$$ F_n = F_{n-1} + F_{n-2}.$$\n\n\nWe can check the few numbers in the Fibonacci sequence are obtained by that formula, by computing:\n\n$$\\begin{eqnarray*}\nF_{2} &=&F_{1}+F_{0}=1+0=1 \\\\\nF_{3} &=&F_{2}+F_{1}=1+1=2 \\\\\nF_{4} &=&F_{3}+F_{2}=2+1=3 \\\\\nF_{5} &=&F_{4}+F_{3}=3+2=5 \\\\\nF_{6} &=&F_{5}+F_{4}=5+3=8 \\\\\nF_{7} &=&F_{6}+F_{5}=8+5=13 \\\\\n&&\\vdots\n\\end{eqnarray*}\n$$\n\nHere is a list of the first 40 Fibonacci numbers:\n\n$$\n\\begin{array}{rrrrrrrrrrrrrrr}\n0 &  & 1 &  & 1 &  & 2 &  & 3 &  & 5 &  & 8 &  & 13 \\\\ \n&  &  &  &  &  &  &  &  &  &  &  &  &  &  \\\\ \n21 &  & 34 &  & 55 &  & 89 &  & 144 &  & 233 &  & 377 &  & 610 \\\\ \n&  &  &  &  &  &  &  &  &  &  &  &  &  &  \\\\ \n987 &  & 1597 &  & 2584 &  & 4181 &  & 6765 &  & 10946 &  & 17711 &  & 28657\n\\\\ \n&  &  &  &  &  &  &  &  &  &  &  &  &  &  \\\\ \n46368 &  & 75025 &  & 121393 &  & 196418 &  & 317811 &  & 614229 &  & 832040\n&  & 1346269 \\\\ \n&  &  &  &  &  &  &  &  &  &  &  &  &  &  \\\\ \n2178309 &  & 3524578 &  & 5702887 &  & 9227465 &  & 14930352 &  & 24157817 & \n& 39088169 &  & 63245986%\n\\end{array}$$\n\n\n**Exercise 2:** Write a code that computes the first N Fibonacci numbers, saves them into an array, and displays them on the screen.\n\n**WAIT** -- before you read the next cell, try to do Exercise 2!\n\nN = 20   # Set the size of the list we will compute\n\nF=[0,1]  # The first two numbers in the list\nfor i in range(2, N):\n    F.append(F[i-1]+F[i-2])  # append the next item on the list\n\nprint('First',N,'Fibonacci numbers:',F)\n\n**For fun,** we can make a little widget to control how many numbers to print out. \n\nfrom ipywidgets import interact\n\ndef printFib(N=10):\n    F=[0,1]  # The first two numbers in the list\n    for i in range(2, N):\n        F.append(F[i-1]+F[i-2])  # append the next item on the list\n    print(F)\n    \ninteract(printFib, N=(10,100,10));\n\nBy moving the slider above, print out the first 100 Fibonacci numbers\n\nAs we can see, this sequence grows pretty fast. The Fibonacci numbers seem\nto have one more digit after about every five terms in the sequence.\n\n## How fast does it grow?\n\nOne of the ways to study the growth of a sequence is to look at ratios between consecutive terms. We  look at ratios of pairs of numbers in the Fibonacci sequence. \n\nThe first few values are\n\\begin{eqnarray}\nF_2/F_1 &=& 1 \\\\\nF_3/F_2 &=& 2/1 = 2 \\\\\nF_4/F_3 &=& 3/2 = 1.5 \\\\ \nF_5/F_4 &=& 5/3 = 1.666... \\\\ \nF_6/F_5  &=& 8/5 = 1.6 \\\\ \nF_7/F_6  &=& 13/8 = 1.625 \n\\end{eqnarray}\n\nSo the ratios are levelling out somewhere around 1.6. We observe that $1.6^5 \\approx 10$, which is why after every five terms in the Fibonacci sequence, we get another digit. This tells us we have roughly  **exponential growth,** where $F_n$ grows about as quickly as the exponential function $(1.6)^n$.\n\nWe can check this computation in Python. We use $ ** $ to take a power, as in the following cell. \n\n(1.6)**5\n\n## The Golden Ratio\n\nWe can print out a bunch of these ratios, and plot them, just to see that they do. The easiest way to do this is with a bit of Python code. Perhaps you can try this yourself.\n\n**Exercise 3** Write some code that computes the first N ratios $F_{n+1}/F_n$, save them it into an array, and displays them on the screen.\n\n**WAIT!** Don't read any further until you try the exercises.\n\n%matplotlib inline\nfrom matplotlib.pyplot import * \n\nN = 20\nF = [0,1]\nR = []\nfor i in range(2, N):\n    F.append(F[i-1]+F[i-2])  # append the next item on the list\n    R.append(F[i]/F[i-1])\n\n\nfigure(figsize=(10,6));\nplot(R,'o')\ntitle('The first '+str(N-2)+' Ratios $F_{n+1}/F_n$')\nxlabel('$n$')\nylabel('$Ratio$');\n\nprint('The first', N-2, 'ratios are:',R)\n\n\nWe see the numbers are levelling out at the value 1.6108034...  This number may be familiar to you. It is called the **Golden Ratio.** \n\nWe can compute the exact value by observing the ratios satisfy a nice algebraic equation:\n$$\n\\frac{F_{n+2}}{F_{n+1}}=\\frac{F_{n+1}+F_{n}}{F_{n+1}}=1+\\frac{F_{n}}{F_{n+1}}=1+\\frac{1}{\\frac{F_{n+1}}{F_{n}}},\n$$\nor more simply \n$$\\frac{F_{n+2}}{F_{n+1}}=1+\\frac{1}{\\frac{F_{n+1}}{F_{n}}}.$$\n\nAs $n$ gets larger and larger, the ratios $F_{n+2}/F_{n+1}$ and $F_{n+1}/F_{n}$ tend toward a final value, say $x$. This value must then solve the equation\n$$x=1+\\frac{1}{x}.$$\n\nWe rewrite this as a quadratic equation\n$$x^2=x+1$$ \nwhich we solve from the quadratic formula\n$$ x= \\frac{1 \\pm \\sqrt{1+4}}{2} = \\frac{1 \\pm \\sqrt{5}}{2}.$$\nIt is the positive solution $x= \\frac{1 + \\sqrt{5}}{2} = 1.6108034...$ which is called the Golden Ratio.\n\n\n\nThe **Golden ratio** comes up in art, geometry, and  Greek mythology as a perfect ratio that is pleasing to the eye (and to the gods). \n\nFor instance, the rectangle shown below is said to have the dimensions of the Golden ratio, because the big rectangle has the same shape as the smaller rectangle inside. Mathematically, we have the ratios of lengths\n$$ \\frac{a+b}{a} = \\frac{a}{b}.$$\n\n![Golden ratio rectangle](images/Golden2.png)\n\nWriting $x = \\frac{a}{b}$, the above equation simplifies to\n$$ 1 + \\frac{1}{x} = x,$$\nwhich is the same quadratic equation we saw for the limit of ratios of Fibonacci numbers.\n\nFor more information about the Golden ratio see\nhttps://en.wikipedia.org/wiki/Golden_ratio\n\n## A Formula for the Fibonacci Sequence $F_n$\n\nLet's give the Golden ratio a special name. In honour of the ancient Greeks who used it so much, we call it `phi:'\n$$ \\varphi = \\frac{1 + \\sqrt{5}}{2}. $$\nWe'll call the other quadratic root 'psi:'\n$$ \\psi = \\frac{1 - \\sqrt{5}}{2}. $$\nThis number $\\psi$ is called the **conjugate** of $\\varphi$ because it looks the same, except for the negative sign in front of the $\\sqrt{5}$.\n\nHere's something **amazing.** It turns out that we have a remarkable formula for the Fibonnaci numbers, in terms of these two Greek numbers. The formula says\n$$F_n = \\frac{\\varphi^n - \\psi^n}{\\sqrt{5}}.$$\n\n\n#### Wow!\n\nSeems amazing. And it is handy because now we can compute, say, the thousandth term in the sequence, $F_{1000}$ directly, without having to compute all the other terms that come before. \n\nBut, whenever someone gives you a formula, you should check it!\n\n**Exercise 4:** Write a piece of code to show that the formula above, with $\\varphi,\\psi$ does produce, say, the first 20 Fibonnaci numbers.\n\n**WAIT!** Don't go on until you try writing a program yourself, to compute the Fibonacci numbers using only powers of $\\varphi, \\psi$.\n\n## SOLUTION (don't peak!)\n\nfrom numpy import *  ## We need this to define square roots\nphi = (1 + sqrt(5))/2\npsi = (1 - sqrt(5))/2\nfor n in range(20):\n    print( (phi**n - psi**n)/sqrt(5) ) \n\n\nLooking at that computer output, it does seem to give Fibonacci numbers, with a bit of numerical error.\n\n## Checking the Math\n\nDoing math, though, we like exact answers and we want to know why. So WHY does this formula $(\\phi^n - \\psi^n)/\\sqrt{5}$ give Fibonacci numbers?\n\nWell, we can check, step by step.\n\nFor $n=0$, the formula gives \n$$\\frac{\\varphi^0 - \\psi^0}{\\sqrt{5}} = \\frac{1-1}{\\sqrt{5}} = 0,$$ which is $F[0]$, the first Fibonacci number. \n\nFor $n=1$, the formula gives \n$$\\frac{\\varphi^1 - \\psi^1}{\\sqrt{5}} =\n\\frac{\\frac{1 + \\sqrt{5}}{2} - \\frac{1 -\\sqrt{5}}{2} }{\\sqrt{5}} = \\frac{\\sqrt{5}}{\\sqrt{5}} = 1,$$ which is $F[1]$, the next Fibonacci number. \n\nFor $n=2$, it looks harder because we get the squares $\\varphi^2, \\psi^2$ in the formula. But then remember that both $\\varphi$ and $\\psi$ solve the quadratic $x^2 = x+1$, so we know $\\varphi^2 = \\phi +1$ and $\\psi^2 = \\psi +1$. So we can write\n$$\\frac{\\phi^2 - \\psi^2}{\\sqrt{5}} = \\frac{\\phi + 1 - \\psi -1}{\\sqrt{5}} = \\frac{\\phi - \\psi }{\\sqrt{5}} = 1,$$\nsince we already calculated this in the $n=1$ step. So this really is $F[2]=1$.\n\nFor $n=3,4,5,\\ldots$ again it might seem like it will be hard because of the higher powers. But multiplying the formulas $\\varphi^2 = \\varphi +1$ and $\\psi^2 = \\psi +1$ by powers of $\\phi$ and $\\psi$, we get\n\n$$\\begin{eqnarray*}\n\\varphi^2 &=& \\varphi +1,\\quad \\varphi^3 = \\varphi^2+\\varphi\n,\\quad \\varphi^4=\\varphi^3+\\varphi^2,\\qquad \\dots \\qquad %\n\\varphi^{n+2}=\\varphi^{n+1}+{\\varphi}^n,\\quad \\text{and} \\\\\n\\psi^2 &=&\\psi +1,\\quad \\psi^3=\\psi^2+\\psi ,\\quad \\psi^4=\\psi^3+\\psi^2,\\qquad \n\\dots \\qquad \\psi^{n+2}=\\psi^{n+1}+\\psi^n.\n\\end{eqnarray*}$$\n\nSo, assuming we know the generating formula already for $n$ and $n+1$ we can write the next term as\n$$\\frac{\\varphi^{n+2} - \\psi^{n+2}}{\\sqrt{5}} = \\frac{\\varphi^{n+1} +\\varphi^n - \\psi^{n+1} - \\psi^n}{\\sqrt{5}}\n= \\frac{\\varphi^{n+1} - \\psi^{n+1}}{\\sqrt{5}} + \\frac{\\varphi^{n} - \\psi^{n}}{\\sqrt{5}} = F[n+1] + F[n] = F[n+2].$$\n\nSo we do get $\\frac{\\varphi^{n+2} - \\psi^{n+2}}{\\sqrt{5}} = F[n+2]$, and the formula holds for all numbers n. \n\nThis method of verifying the formula for all n, based on previous values of n, is an example of **mathematical induction.**\n\n## Why did this work?\n\nWell, from the Golden ratio, we have the formula $\\varphi^2 = \\varphi + 1$, which then gives the formula $\\varphi^{n+2} = \\varphi^{n+1} + \\varphi^n$.  This looks a lot like the Fibonacci formula $$F[n+2] = F[n+1] + F[n].$$ Same powers of $\\psi$.\n\nIf we take ANY linear combination of powers of $\\varphi, \\psi$, such as\n$$f(n) = 3\\varphi^n + 4\\psi^n,$$\nwe will get a sequence that behaves like the Fibonacci sequence, with $f(n+2) = f(n+1) + f(n).$ To get the 'right' Fibonacci sequence, we just have to replace the 3 and 4 with the right coefficients.\n\n## From sequences to functions\n\nWouldn't it be fun to extend Fibonacci numbers to a function, defined for all numbers $x$?\n\nThe problems is the function \n$$F[x] = \\frac{\\varphi^x - \\psi^x}{\\sqrt{5}}$$\nis not defined for values of $x$ other than integers. \n\nThe issue is the term $\\psi^{x}=\\left( \\frac{1-\\sqrt{5}}{2}\\right) ^{x}$, which is the power of a negative number.\nWe don't really know how to define that. For instance, what is the square root of a negative number?\n\nTo\novercome this technical difficulty, we write\n\n$$\\psi ^{x}=\\left( -\\left( -\\psi \\right) \\right) ^{x}=\\left( -\\left( \\frac{%\n\\sqrt{5}-1}{2}\\right) \\right) ^{x}=\\left( -1\\right) ^{x}\\left( \\frac{\\sqrt{5}%\n-1}{2}\\right) ^{x}. $$\n\nNow the factor $\\left( \\frac{\\sqrt{5}-1}{2} \\right) ^{x}$ make sense since \nthe number inside the brackets is positive. We have localized the problem into the powers of $-1$ for the term $\\left(\n-1\\right) ^{x}$. We would like to replace this term  by a\ncontinuous function $m(x)$ such that it takes the values $\\pm1$ on the integers. That is,\n\n$$m(n) =1\\quad \\text{if }n\\text{ is even }\\quad\\text{and}\\quad m(n) =-1\\quad \\text{if }n\\text{ is odd.} $$\n\nThe cosine function works. That is\n\n$$m\\left( x\\right) =\\cos \\left( \\pi x\\right) \\qquad \\text{does the job.} $$\nThat is:\n$$\\cos \\left( n\\pi \\right) =1\\quad \\text{if }n\\text{ is even}\\quad\\text{ and}\\quad %\n\\cos \\left( n\\pi \\right) =-1\\quad \\text{if }n\\text{ is odd.}$$\n\nWhy this is a **good** choice would lead us to complex numbers and more!\n\nHence, we obtain the following closed formula for our function $F[x]:$\n\n$$\\begin{eqnarray*}\nF[x]  &=&\\frac{{\\varphi }^{x}-\\left( -1\\right) ^{x}\\left( -\\psi\n\\right) ^{x}}{{\\varphi -\\psi }}=\\frac{1}{\\sqrt{5}}\\left( {\\varphi }%\n^{x}-\\left( -1\\right) ^{x}\\left( -\\psi \\right) ^{x}\\right)  \\\\\n&=&\\frac{1}{\\sqrt{5}}\\left( \\left( \\frac{1+\\sqrt{5}}{2}\\right) ^{x}-\\cos\n\\left( \\pi x\\right) \\left( \\frac{\\sqrt{5}-1}{2}\\right) ^{x}\\right) .\n\\end{eqnarray*}$$\n\nLet's plot this function, and the Fibonacci sequence.\n\n\n## A plot of the continuous Fibonacci function\n\n%matplotlib inline\nfrom numpy import *\nfrom matplotlib.pyplot import *\n\nphi=(1+5**(1/2))/2\npsi=(5**(1/2)-1)/2\n\nx = arange(0,10)\ny = (pow(phi,x) - cos(pi*x)*pow(psi,x))/sqrt(5)\nxx = linspace(0,10)\nyy = (pow(phi,xx) - cos(pi*xx)*pow(psi,xx))/sqrt(5)\n\nfigure(figsize=(10,6));\nplot(x,y,'o',xx,yy);\ntitle('The continuous Fibonacci function')\nxlabel('$x$')\nylabel('$Fib(x)$');\n\n## A plot with negative values\n\nWell, with this general definition, we can even include negative numbers for $x$ in the function.\n\nLet's plot this too. \n\n%matplotlib inline\nfrom numpy import *\nfrom matplotlib.pyplot import *\n\nphi=(1+5**(1/2))/2\npsi=(5**(1/2)-1)/2\n\nx = arange(-10,10)\ny = (pow(phi,x) - cos(pi*x)*pow(psi,x))/sqrt(5)\nxx = linspace(-10,10,200)\nyy = (pow(phi,xx) - cos(pi*xx)*pow(psi,xx))/sqrt(5)\n\n\nfigure(figsize=(10,6));\nplot(x,y,'o',xx,yy);\ntitle('The Fibonacci function, extended to negative values')\nxlabel('$x$')\nylabel('$Fib(x)$');\n\n\nSo we see we can even get negative Fibonacci numbers!\n\n## The Golden Ratio and Continued Fractions\n\nWe have found that the Golden ratio ${\\varphi =}\\frac{{1+}\\sqrt{5}}{2}$\nsatisfies the identity\n\n$$\n{\\varphi =1+}\\frac{1}{{\\varphi }}.\n$$\n\nSubstituting for ${\\varphi }$ on the denominator in the right, we obtain\n\n$$\n{\\varphi =1+}\\frac{1}{{1+}\\frac{1}{{\\varphi }}}.\n$$\n\nSubstituting again for ${\\varphi }$ on the denominator in the right, we\nobtain\n\n$$\n{\\varphi =1+}\\frac{1}{{1+}\\dfrac{1}{{1+}\\frac{1}{{\\varphi }}}}.\n$$\n\nRepeating this again,\n\n$$\n{\\varphi =1+}\\frac{1}{{1+}\\dfrac{1}{{1+}\\dfrac{1}{{1+}\\frac{1}{{\\varphi }}}}}%\n.$$\n\nAnd again,\n\n$$\n{\\varphi =1+}\\frac{1}{{1+}\\dfrac{1}{{1+}\\dfrac{1}{{1+}\\dfrac{1}{{1+}\\frac{1}{%\n{\\varphi }}}}}}.\n$$\n\nAnd again,\n\n$$\n{\\varphi =1+}\\frac{1}{{1+}\\dfrac{1}{{1+}\\dfrac{1}{{1+}\\dfrac{1}{{1+}\\dfrac{1%\n}{{1+}\\frac{1}{{\\varphi }}}}}}}.\n$$\n\nWe see that this process can be $\\textit{continued indefinitely}$. This results\nin an $\\textit{infinite expansion of a fraction}$. These type of expressions are known as \n$\\textbf{continued fractions}$:\n\n$$\n{\\varphi =1+}\\frac{1}{{1+}\\dfrac{1}{{1+}\\dfrac{1}{{1+}\\dfrac{1}{{1+}\\dfrac{1%\n}{{1+}\\dfrac{1}{{1+}\\dfrac{1}{1+\\dfrac{1}{{\\vdots }}}}}}}}}.\n$$\n\nWe can approximate continued fractions with the finite fractions obtained by\nstopping the development at some point. In our case, we obtain the\napproximates\n\n$$\n1,~1+1,~1+\\frac{1}{1+1},~1+\\frac{1}{1+\\dfrac{1}{1+1}},~1+\\frac{1}{1+\\dfrac{1%\n}{1+\\dfrac{1}{1+1}}},~1+\\frac{1}{1+\\dfrac{1}{1+\\dfrac{1}{1+\\dfrac{1}{1+1}}}}%\n,\\dots \n$$\n\nExplicitly, these approximates are\n\n$$\n1,~2,~\\frac{3}{2},~\\frac{5}{3},~\\frac{8}{5},~\\frac{13}{8},\\dots \n$$\n\nThis looks like it is just the sequence of ratios $F_{n+1}/F_n$ we saw above!  How can we prove this is the case for all $n$?\n\nWe know that the sequence $R_{n} = F_{n+1}/F_n$ satisfies the recursive relation. \n\n$$\nR_{n}=\\frac{F_{n+1}}{F_{n}}=1+\\frac{F_{n-1}}{F_{n}}=1+\\frac{1}{R_{n-1}}%\n,\\qquad \\text{with}\\qquad R_{1}=1.\n$$\n\nThen, we can generate all the terms in the sequence $R_{n}$ by staring with $%\nR_{1}=1$, and then using the relation $R_{n+1}=1+\\frac{1}{R_{n}}:$\n\n$$\n\\begin{eqnarray*}\nR_{1} &=&1 \\\\\nR_{2} &=&1+\\frac{1}{R_{1}}=1+\\frac{1}{1}=2 \\\\\nR_{3} &=&1+\\frac{1}{R_{2}}=1+\\frac{1}{1+R_{1}}=1+\\frac{1}{1+1} \\\\\nR_{4} &=&1+\\frac{1}{R_{3}}=1+\\frac{1}{1+\\frac{1}{1+1}} \\\\\nR_{5} &=&1+\\frac{1}{R_{4}}=1+\\frac{1}{1+\\frac{1}{1+\\frac{1}{1+1}}} \\\\\n&&\\vdots \n\\end{eqnarray*}\n$$\n\nThis confirms that both the sequence of rations $R_{n}$ and the sequence of\napproximations to the continuous fraction of ${\\varphi }$ are the same\nsequence. $\\square $\n\nIn general, continued fractions are expressions of the form\n\n$$\na_{0}+\\frac{1}{a_{1}+\\dfrac{1}{a_{2}+\\dfrac{1}{a_{3}+\\dots }}}\n$$\n\nwhere $a_{0}$ is an integer and $a_{1},a_{2},a_{3},\\dots $ are positive\nintegers. These type of fractions are abbreviated by the notation\n\n$$\n\\left[ a_{0};a_{1},a_{2},a_{3},\\dots \\right] =a_{0}+\\frac{1}{a_{1}+\\dfrac{1}{%\na_{2}+\\dfrac{1}{a_{3}+\\dots }}}.\n$$\n\nFor example\n\n$$\n\\begin{eqnarray*}\n\\left[ 1;1,1,2\\right]  &=&1+\\frac{1}{1+\\dfrac{1}{1+\\dfrac{1}{1+1}}}=\\frac{8}{%\n5} \\\\\n&& \\\\\n\\left[ 1;1,1,1,1,\\dots \\right]  &=&{1+}\\frac{1}{{1+}\\dfrac{1}{{1+}\\dfrac{1}{%\n{1+}\\dfrac{1}{{1+}\\dfrac{1}{{1+}\\dfrac{1}{{1+}\\dfrac{1}{1+\\dfrac{1}{{\\vdots }%\n}}}}}}}}={\\varphi }\n\\end{eqnarray*}\n$$\n\nFor more information of continued fractions, see\nhttps://en.wikipedia.org/wiki/Continued_fraction \n\n\n\n## Conclusion\n\n### What have we learned?\n\n- a **sequence** is an ordered list of numbers, which may go on forever.\n- the **Fibonacci sequence** 0,1,1,2,3,5,8,13,... is a famous list of numbers, well-studied since antiquity.\n- each number in this sequence is the sum of the two coming before it in the sequence.\n- the sequence grows fast, increasing by a **factor** of about **10** for every **five** terms.\n- the **ratio** of pairs of Fibonacci numbers converges to the **Golden ratio,** known since the ancient Greeks as the number\n$$\\varphi = \\frac{1 + \\sqrt{5}}{2} \\approx 1.6108.$$\n- the Fibonacci numbers can be computed directly as the difference of powers of $\\varphi$ and its **conjugate,** $\\psi = \\frac{1 - \\sqrt{5}}{2}.$ This is sometimes faster than computing the whole list of Fibonnaci numbers.\n- this formula with powers of $\\varphi, \\psi$ is verified using **induction.**\n- The Fibonacci numbers can be **extended** to a **continuous function** $Fib(x)$, defined for all real numbers $x$ (including negatives). It **oscillates** (wiggles) on the negative x-axis.\n- The **Golden Ratio** can also be expressed a **continued fraction,** which is an infinite expansion of fractions with sub-fraction terms. Many interesting numbers come from interesting continued fraction forms.\n\n[![Callysto.ca License](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-bottom.jpg?raw=true)](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)", "meta": {"hexsha": "4ac8dfcf2b44be84884dc811ecad3fee94eba0e7", "size": 19314, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/curriculum-notebooks/Mathematics/FibonacciNumbers/fibonacci-numbers.py", "max_stars_repo_name": "BryceHaley/curriculum-jbook", "max_stars_repo_head_hexsha": "d1246799ddfe62b0cf5c389394a18c2904383437", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-18T18:19:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T18:19:40.000Z", "max_issues_repo_path": "_build/jupyter_execute/curriculum-notebooks/Mathematics/FibonacciNumbers/fibonacci-numbers.py", "max_issues_repo_name": "callysto/curriculum-jbook", "max_issues_repo_head_hexsha": "ffb685901e266b0ae91d1250bf63e05a87c456d9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/curriculum-notebooks/Mathematics/FibonacciNumbers/fibonacci-numbers.py", "max_forks_repo_name": "callysto/curriculum-jbook", "max_forks_repo_head_hexsha": "ffb685901e266b0ae91d1250bf63e05a87c456d9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7407407407, "max_line_length": 409, "alphanum_fraction": 0.6544993269, "include": true, "reason": "from numpy", "num_tokens": 6715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235895, "lm_q2_score": 0.9032942138630786, "lm_q1q2_score": 0.8557638204485185}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef computeCost(X, y, theta):\n\n    #COMPUTECOST Compute cost for linear regression\n    #   J = COMPUTECOST(X, y, theta) computes the cost of using theta as the\n    #   parameter for linear regression to fit the data points in X and y\n\n    # Initialize some useful values\n    m = len(y) # number of training examples\n    J = 0\n\t#\ttheta is an (n+1)-dimensional vector\n\t#\tX is an m x (n+1)-dimensional matrix\n\t#\ty is an m-dimensional vector\n    s = (X.dot(theta) - np.transpose([y]))**2\n    J = (1.0 / (2 * m)) * s.sum(axis=0)\n\n    return J\n\n\ndef gradientDescent(X, y, theta, alpha, num_iters):\n\n    # GRADIENTDESCENT Performs gradient descent to learn theta\n    #   theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by\n    #   taking num_iters gradient steps with learning rate alpha\n\n    # Initialize some useful values\n    m = len(y) # number of training examples\n    J_history = np.zeros((num_iters, 1))\n    for i in range(num_iters):\n        theta = theta - alpha * (1.0 / m) * np.transpose(X).dot(X.dot(theta) - np.transpose([y]))\n        J_history[i] = computeCost(X, y, theta)\n\n    return theta\n\n\ndef plotData(x, y):\n    # PLOTDATA Plots the data points x and y into a new figure\n    #   PLOTDATA(x,y) plots the data points and gives the figure axes labels of\n    #   population and profit.\n    plt.plot(x, y, 'rx', markersize=10, label='Training data')\n    plt.xlabel('Population of City in 10,000s')\n    plt.ylabel('Profit in $10,000s')\n    plt.show(block=False)  # prevents having to close the chart\n\n\ndef warmUpExercise(*args, **kwargs):\n    return np.identity(5)\n\n\n\ndef featureNormalize(X):\n\n    # FEATURENORMALIZE Normalizes the features in X\n    #   FEATURENORMALIZE(X) returns a normalized version of X where\n    #   the mean value of each feature is 0 and the standard deviation\n    #   is 1. This is often a good preprocessing step to do when\n    #   working with learning algorithms.\n    X_norm = X\n    mu = np.zeros((1, X.shape[1]))\n    sigma = np.zeros((1, X.shape[1]))\n    for i in range(X.shape[1]):\n    \tmu[:,i] = np.mean(X[:,i])\n    \tsigma[:,i] = np.std(X[:,i])\n    \tX_norm[:,i] = (X[:,i] - float(mu[:,i]))/float(sigma[:,i])\n\n    return X_norm, mu, sigma\n\n\ndef gradientDescentMulti(X, y, theta, alpha, num_iters):\n\n    # GRADIENTDESCENTMULTI Performs gradient descent to learn theta\n    #   theta = GRADIENTDESCENTMULTI(x, y, theta, alpha, num_iters) updates theta by\n    #   taking num_iters gradient steps with learning rate alpha\n\n    # Initialize some useful values\n    m = len(y) # number of training examples\n    J_history = np.zeros((num_iters, 1))\n\n    for i in range(num_iters):\n        theta = theta - alpha*(1.0 / m) * np.transpose(X).dot(X.dot(theta) - np.transpose([y]))\n        J_history[i] = computeCost(X, y, theta)\n\n    return theta, J_history\n\n\ndef normalEqn(X, y):\n    #   NORMALEQN(X,y) computes the closed-form solution to linear\n    #   regression using the normal equations.\n    theta = np.zeros((X.shape[1], 1))\n    theta = np.linalg.pinv(np.transpose(X).dot(X)).dot(np.transpose(X).dot(y))\n\n    return theta", "meta": {"hexsha": "329e00828b9f08bd9086736d20230d958d7bc296", "size": 3125, "ext": "py", "lang": "Python", "max_stars_repo_path": "ml/ex1/helpers.py", "max_stars_repo_name": "dpopadic/ml-res", "max_stars_repo_head_hexsha": "1fd746301b3ef10a96f78832cebb0c79c9327f1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ml/ex1/helpers.py", "max_issues_repo_name": "dpopadic/ml-res", "max_issues_repo_head_hexsha": "1fd746301b3ef10a96f78832cebb0c79c9327f1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ml/ex1/helpers.py", "max_forks_repo_name": "dpopadic/ml-res", "max_forks_repo_head_hexsha": "1fd746301b3ef10a96f78832cebb0c79c9327f1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-21T07:58:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T07:58:21.000Z", "avg_line_length": 32.8947368421, "max_line_length": 97, "alphanum_fraction": 0.65536, "include": true, "reason": "import numpy", "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522863, "lm_q2_score": 0.9032942001955142, "lm_q1q2_score": 0.8557638048161661}}
{"text": "from sympy import (sympify, factorial, var, cos, S, sin, Dummy, sqrt, pi, exp,\n        I, latex, symbols)\n\ndef Plm(l, m, z):\n    \"\"\"\n    Returns the associated Legendre polynomial P_{lm}(z).\n\n    The Condon & Shortley (-1)^m factor is included.\n    \"\"\"\n    l = sympify(l)\n    m = sympify(m)\n    z = sympify(z)\n    if m >= 0:\n        r = ((z**2-1)**l).diff(z, l+m)\n        return (-1)**m * (1-z**2)**(m/2) * r / (2**l * factorial(l))\n    else:\n        m = -m\n        r = ((z**2-1)**l).diff(z, l+m)\n        return factorial(l-m)/factorial(l+m) * (1-z**2)**(m/2) * r / (2**l * factorial(l))\n\n\ndef Plm_cos(l, m, theta):\n    \"\"\"\n    Returns the associated Legendre polynomial P_{lm}(cos(theta)).\n\n    The Condon & Shortley (-1)^m factor is included.\n    \"\"\"\n    l = sympify(l)\n    m = sympify(m)\n    theta = sympify(theta)\n    z = Dummy(\"z\")\n    r = ((z**2-1)**l).diff(z, l+m).subs(z**2-1, -sin(theta)**2).subs(z, cos(theta))\n    return (-1)**m * sin(theta)**m * r / (2**l * factorial(l))\n\ndef Ylm(l, m, theta, phi):\n    \"\"\"\n    Returns the spherical harmonics Y_{lm}(theta, phi) using the Condon & Shortley convention.\n    \"\"\"\n    l, m, theta, phi = sympify(l), sympify(m), sympify(theta), sympify(phi)\n    return sqrt((2*l+1)/(4*pi) * factorial(l-m)/factorial(l+m)) * Plm_cos(l, m, theta) * exp(I*m*phi)\n\ndef Zlm(l, m, theta, phi):\n    \"\"\"\n    Returns the real spherical harmonics Z_{lm}(theta, phi).\n    \"\"\"\n    l, m, theta, phi = sympify(l), sympify(m), sympify(theta), sympify(phi)\n    if m > 0:\n        return sqrt((2*l+1)/(2*pi) * factorial(l-m)/factorial(l+m)) * Plm_cos(l, m, theta) * cos(m*phi)\n    elif m < 0:\n        m = -m\n        return sqrt((2*l+1)/(2*pi) * factorial(l-m)/factorial(l+m)) * Plm_cos(l, m, theta) * sin(m*phi)\n    elif m == 0:\n        return sqrt((2*l+1)/(4*pi)) * Plm_cos(l, 0, theta)\n    else:\n        raise ValueError(\"Invalid m.\")\n\ndef Zlm_xyz(l, m, x, y, z):\n    \"\"\"\n    Returns the real spherical harmonics Z_{lm}(x, y, z).\n\n    It is assumed x**2 + y**2 + z**2 == 1.\n    \"\"\"\n    l, m, x, y, z = sympify(l), sympify(m), sympify(x), sympify(y), sympify(z)\n    if m > 0:\n        r = (x+I*y)**m\n        r = r.as_real_imag()[0]\n        return sqrt((2*l+1)/(2*pi) * factorial(l-m)/factorial(l+m)) * Plm(l, m, z) * r / sqrt(1-z**2)**m\n    elif m < 0:\n        m = -m\n        r = (x+I*y)**m\n        r = r.as_real_imag()[1]\n        return sqrt((2*l+1)/(2*pi) * factorial(l-m)/factorial(l+m)) * Plm(l, m, z) * r / sqrt(1-z**2)**m\n    elif m == 0:\n        return sqrt((2*l+1)/(4*pi)) * Plm(l, 0, z)\n    else:\n        raise ValueError(\"Invalid m.\")\n\n\nvar(\"theta phi\")\nx, y, z = symbols(\"x y z\", real=True)\nprint \"Spherical harmonics:\"\nprint\nprint \".. math::\"\nprint\nfor l in range(4):\n    for m in range(-l, l+1):\n        print r\"    Y_{%d,%d}(\\theta, \\phi) =\" % (l, m), \\\n            latex(Ylm(l, m, theta, phi))\n        print\n\nprint\nprint \"Real spherical harmonics:\"\nprint\nprint \".. math::\"\nprint\nfor l in range(4):\n    for m in range(-l, l+1):\n        print r\"    Z_{%d,%d}(\\theta, \\phi) =\" % (l, m), \\\n            latex(Zlm(l, m, theta, phi))\n        print\n\nprint\nprint \"Real spherical harmonics (using $x$, $y$ and $z$, assuming $x^2 + y^2 + z^2 = 1$):\"\nprint\nprint \".. math::\"\nprint\nfor l in range(4):\n    for m in range(-l, l+1):\n        print r\"    Z_{%d,%d}(x, y, z) =\" % (l, m), \\\n            latex(Zlm_xyz(l, m, x, y, z).simplify())\n        print\n", "meta": {"hexsha": "78113dc7097911f8ff281c2d7c0db85c382e0955", "size": 3376, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/math/code/spherical_harmonics.py", "max_stars_repo_name": "gfrubi/theoretical-physics", "max_stars_repo_head_hexsha": "acff91be8a82a84344afb53dabb9a593e80bcae9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 158, "max_stars_repo_stars_event_min_datetime": "2015-02-22T11:47:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T14:02:13.000Z", "max_issues_repo_path": "src/math/code/spherical_harmonics.py", "max_issues_repo_name": "ritzvik/theoretical-physics", "max_issues_repo_head_hexsha": "10d73c25fee98f9756792bef03d6d292873c9896", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2015-09-25T00:37:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-30T22:45:27.000Z", "max_forks_repo_path": "src/math/code/spherical_harmonics.py", "max_forks_repo_name": "ritzvik/theoretical-physics", "max_forks_repo_head_hexsha": "10d73c25fee98f9756792bef03d6d292873c9896", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2015-05-23T00:18:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T11:42:42.000Z", "avg_line_length": 30.1428571429, "max_line_length": 104, "alphanum_fraction": 0.5156990521, "include": true, "reason": "from sympy", "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096791, "lm_q2_score": 0.9032941988938413, "lm_q1q2_score": 0.8557637982150632}}
{"text": "########################################\n# Overview\n#\n# This file defines loss functions for \n# generalized linear models. These functions \n# are the negative log likelihoods using the \n# canonical links.\n########################################\nimport numpy as np\nfrom scipy.special import factorial, gamma\n\ndef SSE(Y, X, B):\n    Y_Hat = np.matmul(X, B)\n    Y_Hat.reshape([Y_Hat.shape[0],1])\n    loss = np.sum( np.power(Y - Y_Hat, 2))\n    \n    return loss\n\n########################################\n# Mathematical background\n# Step 1 Calculate eta\n# Step 2 Inverse link\n# step 3 Calculate negative log likelihood\n########################################\n\ndef neg_ll_gaussian(Y, X, B):\n    Y_Hat = np.matmul(X, B)\n    Y_Hat.reshape([Y_Hat.shape[0],1])\n    Y_Hat = Y_Hat # Inverse link\n    \n    n = X.shape[0]\n    p = X.shape[1]\n    sigma = np.sum(np.power(Y - Y_Hat, 2)) / (n-p)\n    \n    ll = -(n/2)*np.log(2*np.pi) - n*np.log(sigma) - (1/2*np.power(sigma, 2)) * np.sum(np.power(Y-Y_Hat,2))\n    ll = -1 * ll\n    \n    return ll\n\ndef neg_ll_poisson(Y, X, B):\n    Y_Hat = np.matmul(X, B)\n    Y_Hat.reshape([Y_Hat.shape[0],1])\n    Y_Hat = np.exp(Y_Hat) # Inverse link\n    \n    ll = Y * np.log(Y_Hat) - Y_Hat - np.log(factorial(Y))\n    ll = np.sum(ll)\n    ll = -1 * ll\n    \n    return ll\n\ndef neg_ll_bernoulli(Y, X, B):\n    Y_Hat = np.matmul(X, B)\n    Y_Hat.reshape([Y_Hat.shape[0],1])\n    Y_Hat = np.exp(Y_Hat) / (1 + np.exp(Y_Hat)) # Inverse link\n    \n    ll = Y * np.log(Y_Hat) + (1 - Y) * np.log(1 - Y_Hat)\n    ll = np.sum(ll)\n    ll = -1 * ll\n    \n    return ll\n\ndef neg_ll_gamma(Y, X, B):\n    Y_Hat = np.matmul(X, B)\n    Y_Hat.reshape([Y_Hat.shape[0],1])\n    Y_Hat = np.power(Y_Hat, -1) # Inverse link\n    \n    # Using method of moments estimate\n    # MLE does not have closed form.\n    # Don't want to write numerical method for MLE\n    n = X.shape[0]\n    p = X.shape[1]\n    numerator = np.power(Y - Y_Hat, 2)\n    denominator = np.power(Y_Hat, 2) * (n-p)\n    phi = np.sum(numerator / denominator)\n    \n    ll = -1 * np.log(Y) - np.log(gamma(1/phi)) + (1/phi) * (np.log(Y) - np.log(Y_Hat) - np.log(phi)) - Y/(Y_Hat * phi)\n    ll = np.sum(ll)\n    ll = -1 * ll\n    \n    return ll", "meta": {"hexsha": "fe8863304a3001f9197dbdfa831160c5cbd17dad", "size": 2177, "ext": "py", "lang": "Python", "max_stars_repo_path": "ML/glm_negative_log_likelihoods.py", "max_stars_repo_name": "gmcmacran/coord-descent-glm", "max_stars_repo_head_hexsha": "b284ae7056b334c0737a7476a2940782d2e8d73c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-28T23:45:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-28T23:45:42.000Z", "max_issues_repo_path": "ML/glm_negative_log_likelihoods.py", "max_issues_repo_name": "gmcmacran/coord-descent-glm", "max_issues_repo_head_hexsha": "b284ae7056b334c0737a7476a2940782d2e8d73c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ML/glm_negative_log_likelihoods.py", "max_forks_repo_name": "gmcmacran/coord-descent-glm", "max_forks_repo_head_hexsha": "b284ae7056b334c0737a7476a2940782d2e8d73c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2125, "max_line_length": 118, "alphanum_fraction": 0.5411116215, "include": true, "reason": "import numpy,from scipy", "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357604052423, "lm_q2_score": 0.8740772384450967, "lm_q1q2_score": 0.8557528737940095}}
{"text": "#--------#--------#--------#--------#--------#--------#--------#--------#--------#--------#\r\n#   QR Algorithm for obtaining eigenvalues and eigenvectors from tridiagonal matrices     #\r\n#                                      20/07/21                                           #    \r\n#--------#--------#--------#--------#--------#--------#--------#--------#--------#--------#\r\n\r\nimport numpy as np \r\nimport math \r\nfrom functools import reduce \r\n\r\n#Generates a rotation matrix\r\ndef generateRotationMatrix(shape, c_mat, s_mat, i_mat, j_mat):\r\n    matrixG = np.array(np.zeros((shape,shape)))\r\n    for i in range(0, shape):\r\n        for j in range(0, shape):\r\n            if (i == j) and (i == i_mat or j == j_mat): #Gkk = c for k == i,j\r\n                matrixG[i,j] = c_mat \r\n            elif (i == j) and (i != i_mat or j != j_mat): #Gkk = 1 for k != i,j\r\n                matrixG[i,j] = 1\r\n    matrixG[i_mat,j_mat] = s_mat\r\n    matrixG[j_mat,i_mat] = -s_mat\r\n    return matrixG\r\n\r\n#Triangularization function using rotation matrix\r\ndef givensRotation(matrixA):\r\n    QRResults = []\r\n    GMatrices = []\r\n    dimension = matrixA.shape[0]\r\n    matrixAk = matrixA\r\n    for i in range(1, dimension):\r\n        if matrixAk[i,i-1] != 0: \r\n            if abs(matrixAk[i-1,i-1]) > abs(matrixAk[i,i-1]): #Numerically stable\r\n                tau = (-matrixAk[i,i-1])/matrixAk[i-1,i-1]\r\n                c = 1/(math.sqrt(1+pow(tau,2)))\r\n                s = c*tau\r\n            else:\r\n                tau = (-matrixAk[i-1,i-1])/matrixAk[i,i-1]\r\n                s = 1/(math.sqrt(1+pow(tau,2)))\r\n                c = s*tau\r\n            G = generateRotationMatrix(dimension, c, s, i, i-1)\r\n            GMatrices.append(G)\r\n            matrixAk = np.matmul(G, matrixAk)\r\n    matrixR = matrixAk #Upper triangular\r\n    GMatricesTransp = [np.transpose(GMatrices[i]) for i in range(0, len(GMatrices))] \r\n    matrixQ = reduce(np.matmul, GMatricesTransp) #np.matmul of all transposed G matrices\r\n    QRResults = [matrixQ, matrixR]\r\n    return QRResults\r\n\r\n#QR Algorithm\r\ndef QRAlgorithm(A, desloc):\r\n    Ak = A\r\n    shape = A.shape[0] #Matrix A, k = 0\r\n    Vk = np.identity(shape) #Matrix V, k = 0, V0 = I\r\n    errval = 10e-6\r\n    k = 0 #Number of iterations\r\n    for m in range(1, shape): \r\n        while abs(Ak[m,m-1]) > errval: \r\n            if k == 0 or desloc == False: \r\n                mi = 0\r\n            else:\r\n                dk = (Ak[m-1,m-1] - Ak[m,m])/2 #dk = (alpha_n-1 + alpha_n)/2\r\n                if dk >= 0:\r\n                    sign = 1\r\n                else:\r\n                    sign = -1\r\n                mi = (Ak[m,m] + dk - (sign*np.sqrt(pow(dk,2)+pow(Ak[m,m-1],2)))) \r\n            QRArray = givensRotation((Ak - (np.identity(shape))*mi)) #QR Factorization\r\n            Qk = QRArray[0]\r\n            Rk = QRArray[1]\r\n            Ak = (np.matmul(Rk,Qk) + (np.identity(shape))*mi) #Updates the matrix\r\n            Vk = np.matmul(Vk,Qk) #Updates eigenvectors\r\n            k+=1\r\n    print(\"->\" + str(k) + \" Iteracoes do Algoritmo QR\")\r\n    results = [Ak,Vk]\r\n    return results ", "meta": {"hexsha": "158e0cc24920596b39bed056d91ac595353ca706", "size": 3067, "ext": "py", "lang": "Python", "max_stars_repo_path": "QR-Algorithm.py", "max_stars_repo_name": "Guilherme-AD/Numeric-Algorithms", "max_stars_repo_head_hexsha": "c76c76e664a19be8fcf9fbd4240c40cb999a78ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QR-Algorithm.py", "max_issues_repo_name": "Guilherme-AD/Numeric-Algorithms", "max_issues_repo_head_hexsha": "c76c76e664a19be8fcf9fbd4240c40cb999a78ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QR-Algorithm.py", "max_forks_repo_name": "Guilherme-AD/Numeric-Algorithms", "max_forks_repo_head_hexsha": "c76c76e664a19be8fcf9fbd4240c40cb999a78ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4459459459, "max_line_length": 96, "alphanum_fraction": 0.4773394196, "include": true, "reason": "import numpy", "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357585701874, "lm_q2_score": 0.8740772351648677, "lm_q1q2_score": 0.8557528689785684}}
{"text": "import numpy as np\n\ndef inverse_iteration(A, x, shift=2):\n\tdiff = 10000\n\tdiffn = 0\n\txn = None\n\txo = x\n\tlamda = 0\n\titers = 0\n\tA = A - shift * np.diag(np.diag(np.ones(A.shape)))\n\twhile(diff > 10**(-12)):\n\t\titers+=1\n\t\tyn = np.linalg.solve(A, xo)\n\t\txn = yn / np.linalg.norm(yn, ord=2)\n\t\tlamda = np.linalg.norm(yn, ord=2)\n\t\tdiff = np.linalg.norm((xn - xo), ord=2) / np.linalg.norm(xo, ord=2)\n\t\txo = xn\n\n\treturn 1/(lamda) + shift, xn, iters\n\nif __name__ == '__main__':\n\tprint(\"Inverse Iteration\")\n\tprint(\"-------------------\\n\\n\")\n\n\tseeds = [1, 89, 98, 23, 88, 91, 101, 11, 17, 19]\n\n\tfor i in range(10):\n\t\tA = np.array([[6, 2, 1], [2, 3, 1], [1, 1, 1]])\n\t\tnp.random.seed(seeds[i])\n\t\tprint('Seed:', seeds[i])\n\t\tx0 = np.random.random((3,))\n\t\tl, x, iters = inverse_iteration(A, x0)\n\t\tprint(\"Computed Eigenvalue:\", l)\n\t\tprint(\"Computed Eigenvector:\\n\\t\", x, \"'\\n\")\n\t\tprint(\"Number of iterations:\", iters)\n\t\tprint(\"\\n\\n\")\n\n\n", "meta": {"hexsha": "e6a9b1faf508461e27791634770b34cae35a467a", "size": 913, "ext": "py", "lang": "Python", "max_stars_repo_path": "a3/problem_3a.py", "max_stars_repo_name": "justachetan/scientific-computing", "max_stars_repo_head_hexsha": "e8493b5308c337ea8965a5f96cdd49def94801e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-04-30T14:03:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T19:19:13.000Z", "max_issues_repo_path": "a3/problem_3a.py", "max_issues_repo_name": "justachetan/scientific-computing", "max_issues_repo_head_hexsha": "e8493b5308c337ea8965a5f96cdd49def94801e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "a3/problem_3a.py", "max_forks_repo_name": "justachetan/scientific-computing", "max_forks_repo_head_hexsha": "e8493b5308c337ea8965a5f96cdd49def94801e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4102564103, "max_line_length": 69, "alphanum_fraction": 0.5772179628, "include": true, "reason": "import numpy", "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639636617014, "lm_q2_score": 0.8807970732843033, "lm_q1q2_score": 0.8557506957017238}}
{"text": "# for activation functions of Neural Networks\r\nimport numpy as np\r\n\r\n\r\n# activation function\r\ndef linear(x):\r\n    \"\"\"\r\n    Performs linear function on the input elements.\r\n    Linear function: f(x) = x\r\n\r\n    :param x: {array}, shape {n_samples,}\r\n            input to the function.\r\n    :return: {array}, shape {n_samples,}\r\n            output of linear function.\r\n    \"\"\"\r\n    return x\r\n\r\n\r\ndef logistic(x):\r\n    \"\"\"\r\n    Performs logistic function on the input elements.\r\n    Logistic function: f(x) = 1/(1+exp(-x))\r\n\r\n    :param x: {array}, shape {n_samples,}\r\n            input to the function.\r\n    :return: {array}, shape {n_samples,}\r\n            output of logistic function.\r\n    \"\"\"\r\n    return 1 / (1 + np.exp(-x))\r\n\r\n\r\ndef relu(x):\r\n    \"\"\"\r\n    Performs Rectified Linear Unit function on the input elements.\r\n    Rectified Linear Unit: f(x) = max(0,x)\r\n\r\n    :param x: {array}, shape {n_samples,}\r\n            input to the function.\r\n    :return: {array}, shape {n_samples,}\r\n            output of relu function.\r\n    \"\"\"\r\n    return np.maximum(x, 0)\r\n\r\n\r\ndef tanh(x):\r\n    \"\"\"\r\n    Performs Bipolar logistic function on the input elements.\r\n    Bipolar logistic function: f(x) = tanh(x) = (exp(x)-exp(-x))/(exp(x)+exp(-x))\r\n                                    = 2*(1/(1+exp(-2*x)) - 1\r\n    :param x: {array}, shape {n_samples,}\r\n            input to the function.\r\n    :return: {array}, shape {n_samples,}\r\n            output of tanh function.\r\n    \"\"\"\r\n    return 2 * logistic(x) - np.ones(x.shape)\r\n\r\n\r\ndef rbf(x):\r\n    \"\"\"\r\n    Performs Radial Basis function on the input elements.\r\n    Radial Basis function: f(x) = exp(-(x - mean_x)**2/(2*var_x)) / sqrt(2*pi*var_x)\r\n\r\n    :param x: {array}, shape {n_samples,}\r\n            input to the function.\r\n    :return: {array}, shape {n_samples,}\r\n            output of rbf function.\r\n    \"\"\"\r\n    mean_x = np.mean(x)\r\n    var_x = np.var(x)\r\n    z = (x - mean_x)\r\n    return np.exp(-z**2 / (2 * var_x)) / np.sqrt(2 * np.pi * var_x)\r\n\r\n\r\nactivations = {\"logistic\": logistic, \"relu\": relu,\r\n               \"tanh\": tanh, \"rbf\": rbf, \"linear\": linear}", "meta": {"hexsha": "73983c63547649d6e85a81cd85a0c3a6f299a25b", "size": 2108, "ext": "py", "lang": "Python", "max_stars_repo_path": "ACTIVATIONS.py", "max_stars_repo_name": "Snorlexing/Genetic-Algorithms-based-Neural-Network-hybrid-", "max_stars_repo_head_hexsha": "0d537574a1f6fe1058af31446c9a2d5454a55247", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-29T05:14:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-10T17:34:59.000Z", "max_issues_repo_path": "ACTIVATIONS.py", "max_issues_repo_name": "Snorlexing/Genetic-Algorithms-based-Neural-Network-hybrid-", "max_issues_repo_head_hexsha": "0d537574a1f6fe1058af31446c9a2d5454a55247", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ACTIVATIONS.py", "max_forks_repo_name": "Snorlexing/Genetic-Algorithms-based-Neural-Network-hybrid-", "max_forks_repo_head_hexsha": "0d537574a1f6fe1058af31446c9a2d5454a55247", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1066666667, "max_line_length": 85, "alphanum_fraction": 0.5483870968, "include": true, "reason": "import numpy", "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.8976952921073469, "lm_q1q2_score": 0.8557505143415068}}
{"text": "\"\"\"\nLast change: 30.07.2018\n\"\"\"\n\n# Some imports\nimport numpy as np\nimport math\nfrom scipy import stats\n\nclass Standardization:\n\n    def __init__(self):\n        pass\n\n    def standardize(self, x):\n\n        \"\"\"\n        Standardization: x_std = (x - x_mean) / std_dev\n\n        Inputs:\n        - x: input vector (has to be a row vector)\n\n        Returns:\n        - x_norm: standardized vector of the inputed vector\n        \"\"\"\n\n        mean = self.compute_mean(x)\n        std_dev = self.compute_standard_deviation(x)\n\n        x_norm = np.zeros_like(x)\n        for i in range(x.shape[1]):\n\n            x_norm[0, i] = (x[0, i] - mean) / std_dev\n\n        return x_norm\n\n    def compute_mean(self, x):\n\n        \"\"\"\n         Computes mean of the inputed vector.\n\n        Inputs:\n         - x: input vector (has to be a row vector)\n\n        Returns:\n        - mean: mean value of the inputed vector\n        \"\"\"\n\n        sm = np.sum(x)\n        ln = x.shape[1]\n\n        mean = sm / ln\n\n        return mean\n\n\n    def compute_standard_deviation(self, x):\n\n        \"\"\"\n        Computes standard deviation of the inputed vector.\n\n        Inputs:\n        - x: input vector (has to be a row vector)\n\n        Returns:\n        - std_dev: standard deviation of the inputed vector\n        \"\"\"\n\n        sm = np.sum(x)\n        mean = self.compute_mean(x)\n\n        summ = 0\n        for i in range(x.shape[1]):\n            summ = summ + (x[0, i] - mean)**2\n\n        std_dev = math.sqrt(summ/x.shape[1])\n\n        return std_dev\n\n\"\"\"\n# Test\n\n# Instantiate class\nobj = Normalization()\n\n# Generate random vector\nnp.random.seed(5)\nv = 10*np.random.random([1, 10])\nprint('Vector: ', v)\n\n# Compute mean\nmean = np.mean(v)\nprint('Mean: ', mean)\n\n# Compute manual mean\nmean_manual = obj.compute_mean(v)\nprint('Mean manual', mean_manual)\n\n# Compute standard deviation\nstd_dev = np.std(v)\nprint('Standard deviation: ', std_dev)\n\n# Compute manual standard deviation\nstd_dev_manual = obj.compute_standard_deviation(v)\nprint('Standard deviation manual', std_dev_manual)\n\n# Standardize\nstandard = stats.zscore(v, axis=1)\nprint('Standardized: ', standard)\n\n# Manual standardized\nstandard_manual = obj.standardize(v)\nprint('Standardized manual: ', standard_manual)\n\"\"\"", "meta": {"hexsha": "42820963c6292a0cd294b995a0be41c6ea7fb40d", "size": 2224, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/PyTorch/2_ConvNet/src/standardization.py", "max_stars_repo_name": "volmen3/Bachelors_Thesis", "max_stars_repo_head_hexsha": "4b5e7f1d79a3533e4b6e9efb27f931e2f541992f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/PyTorch/2_ConvNet/src/standardization.py", "max_issues_repo_name": "volmen3/Bachelors_Thesis", "max_issues_repo_head_hexsha": "4b5e7f1d79a3533e4b6e9efb27f931e2f541992f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/PyTorch/2_ConvNet/src/standardization.py", "max_forks_repo_name": "volmen3/Bachelors_Thesis", "max_forks_repo_head_hexsha": "4b5e7f1d79a3533e4b6e9efb27f931e2f541992f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5087719298, "max_line_length": 59, "alphanum_fraction": 0.6029676259, "include": true, "reason": "import numpy,from scipy", "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013548, "lm_q2_score": 0.8976952873175983, "lm_q1q2_score": 0.8557505133504885}}
{"text": "'''\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Taking user input ~~~~~~~~~~~~~~~~~~~~~~~~~~~\nwhile True:\n    try:\n        N = int(input(\"Enter the Number of Points: \"))\n        if N > 1: break\n        else: print(\"Number of Points must be greater than 1\")\n    except ValueError:\n        print(\"Enter a Natural Number greater than 1\")\nX, Y = [], []\nfor i in range(N):\n    while True:\n        try:\n            x = float(input(\"Enter the X coordinate of the point \"+str(i+1)+\": \"))\n        except ValueError:\n                print(\"Enter a Real Number\")\n                continue\n        else: break\n    X.append(x)\n    while True:\n        try:\n            y = float(input(\"Enter the Y coordinate of the point \"+str(i+1)+\": \"))\n        except ValueError:\n                print(\"Enter a Real Number\")\n                continue\n        else: break\n    Y.append(y)\nprint()\n'''\n\n# X = [0, 1, 2, 3, 4, 5]\n# Y = [2.1, 7.7, 13.6, 27.2, 40.9, 61.1]\n\nX = [3, 4, 5, 6, 7, 8]\nY = [0, 7, 17, 26, 35, 45]\n\nN = len(X)  # Number of data points\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~ Method 1: Using for loop ~~~~~~~~~~~~~~~~~~~~~~~~\n\nsumx = sumy = sumx2 = sumxy = 0 # Initial value of summation variables\nfor i in range(N):\n    sumx += X[i]\n    sumy += Y[i]\n    sumx2 += X[i]**2\n    sumxy += X[i]*Y[i]\nmeanx = sumx / N\nmeany = sumy / N\n\na1 = (N*sumxy - sumx*sumy) / (N*sumx2 - sumx**2)\na0 = meany - a1 * meanx\n\n# ~~~~~~~~~~~~~~~~~ Method 2: Using numpy array, sum, mean ~~~~~~~~~~~~~~~~~\n\nfrom numpy import array, mean\n\n# sum(X**2) requires X to be a numpy array as python list cannot be squared\nX = array(X, float)\n\n# a1 = (sum(X*Y) - mean(X)*sum(Y))/(sum(X**2) - N*mean(X)**2)\n# a0 = (mean(Y)*sum(X**2) - mean(X)*sum(X*Y))/(sum(X**2) - N*mean(X)**2)\n\na1 = (N*sum(X*Y) - sum(X)*sum(Y)) / (N*sum(X**2) - sum(X)**2)\na0 = mean(Y) - a1 * mean(X)\n\n\nprint(\"The straight line equation :\")\ns = \"-\" if a1<0 else \"+\"\na1 = -a1 if a1<0 else a1\nprint('y = %.3f %s %.3f x' %(a0, s, a1))\n\n\n'''\ny = a0 + a1 x + e    # where a0 = intercept, a1 = slope, y = mx+c\ne = y - a0 - a1 x    # e = true value of y ~ approximate value of a0+a1x\n\nCriteria for a best fit:\n∑ (ei) = ∑ (yi - a0 - a1 xi)\n\nSr = ∑ (ei)^2 = ∑ (yi - a0 - a1 xi)^2\n\n∂Sr/∂a0 = -2    ∑ (yi - a0 - a1 xi)\n∂Sr/∂a1 = -2 xi ∑ (yi - a0 - a1 xi)\n\n0 = ∑    yi - ∑ a0    - ∑ a1 xi\n0 = ∑ xi yi - ∑ a0 xi - ∑ a1 xi^2\n\n(∑ xi) a0 + (∑ xi^2) a1 = ∑ xi yi\n     n a0 + (∑ xi  ) a1 = ∑    yi    # ∑ a0 = n a0\n\nCross Multiplication:\na1 = ( n ∑ xi yi - ∑ xi ∑ yi ) / ( n ∑ xi^2 - (∑ xi)^2 )\n\na0 = ( ∑ yi - (∑ xi) a1 ) / n\n   = mean(y) - a1 mean(x)\n\nor,\na1 = ( n ∑ xi yi - ∑ xi ∑ yi )/n / ( n ∑ xi^2 - (∑ xi)^2 )/n\n   = ( ∑ xi yi - mean(x) ∑ yi ) / ( ∑ xi^2 - n mean(x)^2 )\na0 = ( ∑ xi^2 ∑ yi - ∑ xi ∑ xi yi )/n / ( n ∑ xi^2 - (∑ xi)^2 )/n\n   = ( mean(y) ∑ xi^2 - mean(x) ∑ xi yi ) / ( ∑ xi^2 - n mean(x)^2 )\n\n'''\n", "meta": {"hexsha": "a10747ecd9e75255ca3f3867c40b63cea8652a48", "size": 2797, "ext": "py", "lang": "Python", "max_stars_repo_path": "2. Interpolation and Curve Fitting/5. Linear (Least Squares) Regression or Fit.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2. Interpolation and Curve Fitting/5. Linear (Least Squares) Regression or Fit.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2. Interpolation and Curve Fitting/5. Linear (Least Squares) Regression or Fit.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8942307692, "max_line_length": 82, "alphanum_fraction": 0.4633535931, "include": true, "reason": "from numpy", "num_tokens": 1107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527684, "lm_q2_score": 0.9149009636941993, "lm_q1q2_score": 0.8557494314864124}}
{"text": "import numpy as np\n\ndef l2_norm(x, y=None):\n    if y is None:\n        return np.linalg.norm(x)\n    else:\n        return np.linalg.norm(x - y)\n\ndef mean(matrix, axis=0):\n    return np.average(matrix, axis=axis)\n\ndef get_centroid(matrix, centroid_method=mean):\n    return centroid_method(matrix)\n\ndef get_distance(x, y, distance_metric=l2_norm):\n    return distance_metric(x, y)\n\ndef rbf_kernel(x, y, sigma=1, norm=l2_norm):\n    return np.exp(-(norm(x, y) ** 2) / (2 * (sigma ** 2)))\n\ndef kernel_matrix(x, y, kernel=rbf_kernel, tuner=1):\n    m = x.shape[1]\n    n = y.shape[1]\n    mat = np.zeros((m, n))\n    for i in range(m):\n        for j in range(n):\n            mat[i, j] = kernel(x[:, i], y[:, j], tuner)\n    return mat\n", "meta": {"hexsha": "d33290d27c38c3f0b880336c2032ce0ca4a6aba1", "size": 722, "ext": "py", "lang": "Python", "max_stars_repo_path": "andmath/general_functions.py", "max_stars_repo_name": "andregerbaulet/andmath", "max_stars_repo_head_hexsha": "d6a349234c27315de99a1fa40bfb7cccbf28c12f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "andmath/general_functions.py", "max_issues_repo_name": "andregerbaulet/andmath", "max_issues_repo_head_hexsha": "d6a349234c27315de99a1fa40bfb7cccbf28c12f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "andmath/general_functions.py", "max_forks_repo_name": "andregerbaulet/andmath", "max_forks_repo_head_hexsha": "d6a349234c27315de99a1fa40bfb7cccbf28c12f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8965517241, "max_line_length": 58, "alphanum_fraction": 0.6052631579, "include": true, "reason": "import numpy", "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018398044143, "lm_q2_score": 0.8774767954920547, "lm_q1q2_score": 0.8557169853495336}}
{"text": "import math\nimport numpy as np\n\n\ndef cholensky(__A):\n    _A = np.array(__A)\n    # return np.linalg.cholesky(_A)\n    n = list(np.shape(_A))[0]\n    A = np.zeros([n, n], dtype='double')\n    for i in range(n):\n        for j in range(i+1):\n            A[i, j] = _A[i, j]\n    for j in range(n):\n        A[j, j] = np.sqrt(A[j, j] - np.linalg.norm(A[j, 0:j])**2)\n        for i in range(j+1, n):\n            tmp = 0\n            for k in range(j):\n                tmp += A[i, k] * A[j, k]\n            A[i, j] = (A[i, j] - tmp) / A[j, j]\n\n    return A\n\n\ndef cho_solve(A, _b):\n    n = list(np.shape(A))[0]\n    b = np.array(_b)\n    L = cholensky(A)\n    Lt = np.transpose(L)\n\n    y = np.zeros(n, dtype='double')\n    for i in range(n):\n        for j in range(n - 1 - i):\n            b[i + j + 1] -= b[i] * L[i + j + 1, i] / L[i, i]\n        y[i] = b[i] / L[i, i]\n\n    x = np.zeros(n, dtype='double')\n    for i in range(n):\n        for j in range(n - 1 - i):\n            y[n - 1 - (i + j + 1)] -= y[n-1 - i] * Lt[n - 1 - (i + j + 1), n - 1 - i] / Lt[n - 1 - i, n - 1 - i]\n        x[n - 1 - i] = y[n - 1 - i] / Lt[n - 1 - i, n - 1 - i]\n    return x\n\n\ndef hilbert(n):\n    ret = np.zeros([n, n])\n    for i in range(n):\n        for j in range(n):\n            ret[i][j] = 1.0 / (i + j + 1)\n\n    return ret\n\n\ndef my_sum(cb, max_count, dt):\n    sigma = dt(0.0)\n    n = dt(1.0)\n    while True:\n        sigma1 = sigma + dt(1) / dt(n)\n        cb(n, sigma)\n        if sigma1 == sigma:\n            break\n        if n == max_count:\n            break\n        n += dt(1)\n        sigma = sigma1\n    return sigma\n\n\ndef newton(f, df, x0, get_lambda, lambda0, epsilon, cb):\n    k = 0\n    x = x0\n    while True:\n        s = f(x) / df(x)\n        x1 = x - s\n        i = 0\n        y = f(x)\n        la = 1\n        while True:\n            y1 = f(x1)\n            if abs(y1) < abs(y):\n                break\n            la = get_lambda(lambda0, i)\n            x1 = x - la * s\n            i += 1\n        cb(k, la, y, y1, x, x1)\n        k += 1\n        if abs(x1 - x) <= epsilon:\n            break\n        x = x1\n\n\ndef iteration_solver(A, b, x0, threshold, cb, method='jacobi', omega=1):\n    x = x0\n    iter_count = 0\n    n = list(np.shape(b))[0]\n    if method == 'jacobi':\n        while True:\n            y = np.zeros(n, dtype='double')\n            for i in range(n):\n                a = np.dot(A[i], x) - A[i, i] * x[i]\n                new_xi = (b[i] - a) / A[i, i]\n                y[i] = new_xi\n            delta = np.linalg.norm(y - x)\n            if delta <= threshold:\n                break\n            if delta > 1e10:\n                break\n            cb(iter_count, x, y - x)\n            x = y\n            iter_count += 1\n        print('Total iter %d, delta %g' % (iter_count, delta))\n        return x\n    else:\n        while True:\n            y = np.array(x)\n            for i in range(n):\n                a = np.dot(A[i], x) - A[i, i] * x[i]\n                new_xi = (1 - omega) * x[i] + omega * (b[i] - a) / A[i, i]\n                x[i] = new_xi\n            delta = np.linalg.norm(y - x)\n            if delta <= threshold:\n                break\n            cb(iter_count, x, y - x)\n            iter_count += 1\n        print('Total iter %d, delta %g' % (iter_count, delta))\n        return x\n\n\ndef power(A, x0, threshold, cb):\n    u = x0\n    last_lambda1 = 0\n    i = 0\n    while True:\n        v = np.dot(A, u)\n        lambda1 = np.max(v)\n        u = v / lambda1\n        delta = abs(last_lambda1 - lambda1)\n        if delta < threshold:\n            break\n        cb(i, u, lambda1, delta)\n        last_lambda1 = lambda1\n        i += 1\n    return lambda1, u\n\n\ndef fitting(pts, n):\n    phi = []\n    for i in range(n):\n        phi.append(np.power(pts[0], i))\n\n    A = np.zeros((n, n), dtype='double')\n    for i in range(n):\n        for j in range(n):\n            A[i, j] = np.dot(phi[i], phi[j])\n\n    b = np.zeros(n, dtype='double')\n    for i in range(n):\n        b[i] = np.dot(phi[i], pts[1])\n\n    x = cho_solve(A, b)\n\n    return x\n    #  tt = 0\n    # For each point\n    #  for _ in range(list(np.shape(pts))[1]):\n    #      A = np.zeros((n, n), dtype='double')\n    #      for i in range(n):\n    #          for j in range(n):\n    #              A[i, j] = pts[0][i] * pts[0][j]\n    #      tt += np.linalg.norm(np.dot(A, x) - b) ** 2\n    #  d = np.sqrt(tt / list(np.shape(pts))[1])\n    #  return x, d\n", "meta": {"hexsha": "36be4e733df8a71f883d1b43f02aff71468b6591", "size": 4357, "ext": "py", "lang": "Python", "max_stars_repo_path": "libs.py", "max_stars_repo_name": "a1exwang/na_algorithms", "max_stars_repo_head_hexsha": "51cd066a86c0f41e6632dc67174444dde0e6065d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs.py", "max_issues_repo_name": "a1exwang/na_algorithms", "max_issues_repo_head_hexsha": "51cd066a86c0f41e6632dc67174444dde0e6065d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs.py", "max_forks_repo_name": "a1exwang/na_algorithms", "max_forks_repo_head_hexsha": "51cd066a86c0f41e6632dc67174444dde0e6065d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3313953488, "max_line_length": 112, "alphanum_fraction": 0.4197842552, "include": true, "reason": "import numpy", "num_tokens": 1436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889437, "lm_q2_score": 0.8933094145755219, "lm_q1q2_score": 0.8557120542103962}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef normal_pdf(x, mu, sigma):\n    pdf = 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (x - mu)**2 / (2 * sigma**2))\n    return pdf\n\nfig = plt.figure(figsize=(6,9))\n\n# Random sampling of a normal distribution\nmy_mu, my_sigma = 0, 0.1 # mean and standard deviation\n\nbit_generators = [np.random.MT19937(), np.random.Philox(), np.random.SFC64()]\nnames = ['Mersenne Twister PRNG (MT19937)', 'Philox (4x64) PRNG (Philox)', 'Chris Doty-Humphrey\\'s SFC PRNG (SFC64)']\nindexes = [1,2,3]\n\nfor bit_generator, name, index in zip(bit_generators, names, indexes):\n    sn = np.random.Generator(bit_generator).normal(loc = my_mu, scale = my_sigma, size = 10000)\n    ax = fig.add_subplot(3, 1, index)\n    ax.hist(sn, density=True, bins='auto', edgecolor='k', color='#c7ddf4', label=name)\n    my_xn = np.linspace(my_mu - 4 * my_sigma, my_mu + 4 * my_sigma, 1000)\n    my_yn = normal_pdf(x=my_xn, mu=my_mu, sigma=my_sigma)\n    ax.plot(my_xn, my_yn, linewidth=2, linestyle='--', color='#ff464a', label ='Target Normal PDF')\n    ax.set_ylim(0.0, 7.0)\n    ax.set_xlim(my_mu - 6 * my_sigma, my_mu + 6 * my_sigma)\n    ax.set_xlabel('x')\n    ax.set_ylabel('Probability Density')\n    ax.legend()\n\nfig.tight_layout()\n\n", "meta": {"hexsha": "7dc8e01bf00643ced8be0152c5917fa5f9a00459", "size": 1239, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/chapter_10/listing_10_14.py", "max_stars_repo_name": "guinslym/python_earth_science_book", "max_stars_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80, "max_stars_repo_stars_event_min_datetime": "2021-04-19T10:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:34:47.000Z", "max_issues_repo_path": "code/chapter_10/listing_10_14.py", "max_issues_repo_name": "guinslym/python_earth_science_book", "max_issues_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/chapter_10/listing_10_14.py", "max_forks_repo_name": "guinslym/python_earth_science_book", "max_forks_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2021-04-25T03:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:06:19.000Z", "avg_line_length": 38.71875, "max_line_length": 117, "alphanum_fraction": 0.6674737692, "include": true, "reason": "import numpy", "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798184, "lm_q2_score": 0.8933094067644466, "lm_q1q2_score": 0.8557120402880918}}
{"text": "def approx_first_derivative_no_main_block(f,x,h):\n    \"\"\"\n    Numerical differentiation by finite differences. Uses central point formula\n    to approximate first derivative of function.\n    Args:\n        f (function): function definition.\n        x (float): point where first derivative will be approximated\n        h (float): step size for central differences. Tipically less than 1\n    Returns:\n        df (float): approximation to first_derivative.\n    \"\"\"\n    df = (f(x+h) - f(x-h))/(2.0*h)\n    return df\n\ndef approx_second_derivative_no_main_block(f,x,h):\n    \"\"\"\n    Numerical differentiation by finite differences. Uses central point formula\n    to approximate second derivative of function.\n    Args:\n        f (function): function definition.\n        x (float): point where second derivative will be approximated\n        h (float): step size for central differences. Tipically less than 1\n    Returns:\n        ddf (float): approximation to second_derivative.\n    \"\"\"\n    ddf =(f(x+h) - 2.0*f(x) + f(x-h))/h**2\n    return ddf\n\n## Python libraries\nimport numpy as np\n\n## Parameters\nf = np.arctan\nx = 0.9\nh = 1e-6\n\n## Main code\nres_first_d = approx_first_derivative_no_main_block(f,x,h)\nres_second_d = approx_second_derivative_no_main_block(f,x,h)\n\nprint(res_first_d)\nprint(res_second_d)\n", "meta": {"hexsha": "8be48e4bc4ad1099bfaaa00be81ed3c3c1adb374", "size": 1295, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ejercicios_clase/1_Calc_diff_int_python/Ejemplo_bloque_main/central_finite_derivative_no_main_block.py", "max_stars_repo_name": "Roberto919/Propedeutico", "max_stars_repo_head_hexsha": "a836cb7a1417efc9ef08802bb049f116125c63cc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ejercicios_clase/1_Calc_diff_int_python/Ejemplo_bloque_main/central_finite_derivative_no_main_block.py", "max_issues_repo_name": "Roberto919/Propedeutico", "max_issues_repo_head_hexsha": "a836cb7a1417efc9ef08802bb049f116125c63cc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ejercicios_clase/1_Calc_diff_int_python/Ejemplo_bloque_main/central_finite_derivative_no_main_block.py", "max_forks_repo_name": "Roberto919/Propedeutico", "max_forks_repo_head_hexsha": "a836cb7a1417efc9ef08802bb049f116125c63cc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1162790698, "max_line_length": 79, "alphanum_fraction": 0.6942084942, "include": true, "reason": "import numpy", "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9808759671623988, "lm_q2_score": 0.8723473763375644, "lm_q1q2_score": 0.8556645764666896}}
{"text": "from numpy.random import rand\r\nfrom math import sqrt\r\nfrom sys import argv\r\n\r\ndef distance(array1, array2):\r\n\tassert len(array1) == len(array2), \"Arrays must be of the same dimension\"\r\n\treturn sqrt(sum([(array2[i] - array1[i])**2 for i in range(len(array1))]))\r\n\r\nif __name__ == '__main__':\r\n\tdim = int(argv[1])\r\n\tassert dim >= 2, \"Dimension must be greater than or equal to two\"\r\n\titerations = int(argv[2]) if len(argv) >= 3 else 10000\r\n\tassert iterations >= 10, \"Iterations must be greater than or equal to 10\"\r\n\tsum_dist = 0\r\n\tfor i in range(iterations):\r\n\t\tarray1 = rand(dim)\r\n\t\tarray2 = rand(dim)\r\n\t\tsum_dist += distance(array1, array2)\r\n\testimate = round(sum_dist / iterations, 5)\r\n\tprint(f\"With {iterations} iterations, the estimated distance between two points in a(n) {dim}-dimensional cube is {estimate}\")", "meta": {"hexsha": "2dde09fd2c2899a32018b0a0773eb35e2cfac7b0", "size": 815, "ext": "py", "lang": "Python", "max_stars_repo_path": "AvgDistPointsInHypercube.py", "max_stars_repo_name": "jpozin/Math-Projects", "max_stars_repo_head_hexsha": "2baf08f1b2595e2231dc2228af251638558e86b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AvgDistPointsInHypercube.py", "max_issues_repo_name": "jpozin/Math-Projects", "max_issues_repo_head_hexsha": "2baf08f1b2595e2231dc2228af251638558e86b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AvgDistPointsInHypercube.py", "max_forks_repo_name": "jpozin/Math-Projects", "max_forks_repo_head_hexsha": "2baf08f1b2595e2231dc2228af251638558e86b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.75, "max_line_length": 127, "alphanum_fraction": 0.6981595092, "include": true, "reason": "from numpy", "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9770226287518853, "lm_q2_score": 0.8757869997529961, "lm_q1q2_score": 0.855663716725399}}
{"text": "import math\nimport numpy as np\nfrom PIL import Image\n\ndef basic_sigmoid(x):\n    s = 1/(1+math.exp(-x))\n    return s\nprint(1, basic_sigmoid(10))\n\nx = np.array([1,2,3])\nprint(2, x+3)\n\ndef sigmoid(x):\n    s = 1/(1+np.exp(-x))\n    return s\nprint(3, sigmoid(x))\n\ndef sigmoid_derivative(x):\n    s = 1/(1+np.exp(-x))\n    ds = s*(1-s)\n    return ds\nprint(4, sigmoid_derivative(x))\n\ndef image2vector(image):\n    v = image.reshape((image.shape[0] * image.shape[1] * image.shape[2]), 1)\n    return v\nimage = np.array(Image.open(\"./icon_sample.JPG\"))\nprint(5, image2vector(image))\n\ndef normalizeRows(x):\n    x_norm = np.linalg.norm(x, axis=1, keepdims=True)\n    x = x/x_norm\n    return x\nx = np.array([\n    [0,3,4], [1,6,4]\n])\nprint(6, normalizeRows(x))\n\ndef softmax(x):\n    x_exp = np.exp(x)\n    x_sum = np.sum(x_exp, axis=1, keepdims=True)\n    s = x_exp/x_sum\n    return s\nx = np.array([\n    [1,2,3],\n    [4,5,6],\n    [7,8,9]\n])\nprint(7, softmax(x))", "meta": {"hexsha": "8cc56cc79a5ccb0307ad86f6d9494b7c13b19fb8", "size": 939, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_basic.py", "max_stars_repo_name": "qule/ProgrammingAssignmentOfDeeplearning", "max_stars_repo_head_hexsha": "4e283cd07cdf17f068f7b3da162eaa94ab28ee9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy_basic.py", "max_issues_repo_name": "qule/ProgrammingAssignmentOfDeeplearning", "max_issues_repo_head_hexsha": "4e283cd07cdf17f068f7b3da162eaa94ab28ee9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy_basic.py", "max_forks_repo_name": "qule/ProgrammingAssignmentOfDeeplearning", "max_forks_repo_head_hexsha": "4e283cd07cdf17f068f7b3da162eaa94ab28ee9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1632653061, "max_line_length": 76, "alphanum_fraction": 0.6017039404, "include": true, "reason": "import numpy", "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9770226267447513, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.8556637086325237}}
{"text": "# -*- coding: utf-8 -*-\n#\nimport math\n\nimport scipy.special\nimport sympy\n\n\ndef integrate_monomial_over_unit_simplex(k, symbolic=False):\n    \"\"\"The integrals of monomials over the standard triangle and tetrahedron are\n    given by\n\n    \\\\int_T x_0^k0 * x1^k1 = (k0!*k1!) / (2+k0+k1)!,\n    \\\\int_T x_0^k0 * x1^k1 * x2^k2 = (k0!*k1!*k2!) / (4+k0+k1+k2)!,\n\n    see, e.g.,\n    A set of symmetric quadrature rules on triangles and tetrahedra,\n    Linbo Zhang, Tao Cui and Hui Liu,\n    Journal of Computational Mathematics,\n    Vol. 27, No. 1 (January 2009), pp. 89-96,\n    <https://www.jstor.org/stable/43693493>.\n\n    See, e.g., <https://math.stackexchange.com/q/207073/36678> for a formula in\n    all dimensions.\n    \"\"\"\n    if symbolic:\n        return sympy.prod([sympy.gamma(kk + 1) for kk in k]) / sympy.gamma(\n            sum(k) + len(k) + 1\n        )\n    # exp-log to account for large values in numerator and denominator\n    # import scipy.special\n    return math.exp(\n        math.fsum([scipy.special.gammaln(kk + 1) for kk in k])\n        - scipy.special.gammaln(sum([kk + 1 for kk in k]) + 1)\n    )\n", "meta": {"hexsha": "3388f3d3f0e6ec409255e224eee574028cbf72b4", "size": 1103, "ext": "py", "lang": "Python", "max_stars_repo_path": "quadpy/nsimplex/helpers.py", "max_stars_repo_name": "gdmcbain/quadpy", "max_stars_repo_head_hexsha": "c083d500027d7c1b2187ae06ff2b7fbdd360ccc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-02T19:04:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-02T19:04:42.000Z", "max_issues_repo_path": "quadpy/nsimplex/helpers.py", "max_issues_repo_name": "gdmcbain/quadpy", "max_issues_repo_head_hexsha": "c083d500027d7c1b2187ae06ff2b7fbdd360ccc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quadpy/nsimplex/helpers.py", "max_forks_repo_name": "gdmcbain/quadpy", "max_forks_repo_head_hexsha": "c083d500027d7c1b2187ae06ff2b7fbdd360ccc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6388888889, "max_line_length": 80, "alphanum_fraction": 0.6237533998, "include": true, "reason": "import scipy,import sympy", "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992969868542, "lm_q2_score": 0.8840392939666335, "lm_q1q2_score": 0.8556610111390595}}
{"text": "import numpy as np\nimport pylab\nimport matplotlib.pyplot as plt\n\n\ndef lagranz_intrepolation(X,Y,x):\n   z =  0\n   for j in range(len(Y)):\n       p1 = 1\n       p2 = 1\n       for i in range(len(X)):\n           if i == j :\n             continue\n           else:\n             p1 = p1 * (x - X[i])\n             p2 = p2 * (X[j] - X[i])\n       z = z + Y[j]/p2*p1\n   return z\n\n\ndef newton_interpolation(x, y, u):\n    g = y[:]\n    s = g[0]\n    for i in range(len(y) - 1):\n        g = [(g[j + 1] - g[j]) / (x[j + i + 1] - x[j]) for j in range(len(g) - 1)]\n        s += g[0] * product(u - x[j] for j in range(i + 1))\n    return s\n\n\ndef product(a):\n    p = 1\n    for i in a: p *= i\n    return p\n\n\n\ndef main():\n    X = np.array([0,np.pi/6,np.pi/4,np.pi/3,np.pi/2])\n    Y = 4*np.sin(X)**2\n    x_in = np.sin(np.pi/7)\n    y_true = 4*np.sin(x_in)**2\n    xnew = np.linspace(np.min(X),np.max(X),100)\n    Y_lagranz = np.array([lagranz_intrepolation(X,Y,i) for i in xnew])\n    Y_newton = np.array([newton_interpolation(X,Y,i) for i in xnew])\n    y_newtwon = newton_interpolation(X,Y,x_in)\n    y_lagranz = lagranz_intrepolation(X,Y,x_in)\n    print(\"In newtwon : \" + str(y_true-y_newtwon))\n    print(\"In lagranz :\" + str(y_true-y_lagranz))\n    plt.plot(X,Y,'o')\n    plt.plot(xnew,Y_lagranz,'g')\n    plt.plot(xnew,Y_newton,'b')\n    plt.grid(True)\n    pylab.show()\nmain()", "meta": {"hexsha": "7661914588c45f63f488008cc96b9566905d0bbf", "size": 1345, "ext": "py", "lang": "Python", "max_stars_repo_path": "Calculus methods/1 part/lab4/lab.py", "max_stars_repo_name": "apletea/MMF_Labs", "max_stars_repo_head_hexsha": "bed898865d62e7f797e383e086a217654871afbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-08-06T15:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T08:11:39.000Z", "max_issues_repo_path": "Calculus methods/1 part/lab4/lab.py", "max_issues_repo_name": "apletea/MMF_Java_Labs", "max_issues_repo_head_hexsha": "bed898865d62e7f797e383e086a217654871afbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-11-04T13:56:10.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-04T13:56:10.000Z", "max_forks_repo_path": "Calculus methods/1 part/lab4/lab.py", "max_forks_repo_name": "apletea/MMF_Java_Labs", "max_forks_repo_head_hexsha": "bed898865d62e7f797e383e086a217654871afbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-05-30T13:56:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-30T13:56:38.000Z", "avg_line_length": 24.9074074074, "max_line_length": 82, "alphanum_fraction": 0.5308550186, "include": true, "reason": "import numpy", "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992932829918, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.855660998993467}}
{"text": "# Z-Test Assignement\n\n\"\"\"\nA sample of 400 male students is found to have a mean height of 171.38cms. Can it be reasonably regarded as a sample from a large population with mean height 171.17 and standard deviation 3.30cms\n\"\"\"\nprint(\"Assignment 1\")\nimport numpy as np\nn=400\nsMean=171.38\npMean=171.17\npStd=3.30\n\nzstatistics=(sMean - pMean)/(pStd/np.sqrt(n))\nprint(\"Zstatistics :\",zstatistics)\n\nfrom scipy.stats import norm\n\nzcritical_l=norm.ppf(q=0.05/2)\nzcritical_u=-zcritical_l\nprint(\"Critical Values are :\",zcritical_l,zcritical_u)\n\nif zstatistics<zcritical_l or zstatistics>zcritical_u:\n    print(\"Reject the Null Hypothesis\")\n    print(\"sample is not from the large population\")\nelse:\n    print(\"Fail to reject the Null Hypothesis\")\n    print(\"sample is from the large population\")\n\n    print(\"\\n\")\n\n\"\"\"\n2.A sample of 900 items has mean 3.4 and standard deviation 2.61. can the sample be regarded as drawn from a population with mean 3.25 at 1 percent level of significance\n\"\"\"\nprint(\"Assignment 2\")\nn=900\nsMean=3.4\npMean=3.25\npStd=2.61\n\nzstatistics=(sMean - pMean)/(pStd/np.sqrt(n))\nprint(\"Zstatistics :\",zstatistics)\n\nfrom scipy.stats import norm\n\nzcritical_l=norm.ppf(q=0.01/2)\nzcritical_u=-zcritical_l\nprint(\"Critical Values are :\",zcritical_l,zcritical_u)\n\nif zstatistics<zcritical_l or zstatistics>zcritical_u:\n    print(\"Reject the Null Hypothesis\")\n    print(\"sample is not from the large population\")\nelse:\n    print(\"Fail to reject the Null Hypothesis\")\n    print(\"sample is from the large population\")", "meta": {"hexsha": "3bba0ee47e322170b5e60e540d9f56bbb18fef01", "size": 1515, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/simplePrograms/z_test.py", "max_stars_repo_name": "BharathC15/NielitChennai", "max_stars_repo_head_hexsha": "c817aaf63b741eb7a8e4c1df16b5038a0b4f0df7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/simplePrograms/z_test.py", "max_issues_repo_name": "BharathC15/NielitChennai", "max_issues_repo_head_hexsha": "c817aaf63b741eb7a8e4c1df16b5038a0b4f0df7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/simplePrograms/z_test.py", "max_forks_repo_name": "BharathC15/NielitChennai", "max_forks_repo_head_hexsha": "c817aaf63b741eb7a8e4c1df16b5038a0b4f0df7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-11T08:04:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-11T08:04:43.000Z", "avg_line_length": 28.0555555556, "max_line_length": 195, "alphanum_fraction": 0.7491749175, "include": true, "reason": "import numpy,from scipy", "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992960608888, "lm_q2_score": 0.884039278690883, "lm_q1q2_score": 0.8556609955350815}}
{"text": "#%%\nimport numpy as np\n\n#%%\n# Example 1\nx = np.arange(1.0, 8 + 1, 1.0)\ny = np.array([6.9, 10.8, 9.3, 7.8, -0.7, -9.2, -22.1, -37.7])\n\nx_mean = np.mean(x)\ny_mean = np.mean(y)\n\nb1 = np.dot(y_mean - y, x_mean - x) / np.sum(np.power(x_mean - x, 2))\nb0 = y_mean - b1 * x_mean\nsigma_squared = (\n    1 / x.shape[0] * np.sum([(yi - b0 - b1 * xi) ** 2 for (xi, yi) in zip(x, y)])\n)\nprint(f\"b0 = {b0}\")\nprint(f\"b1 = {b1}\")\nprint(f\"sigma_squared = {sigma_squared}\")\n\n# %%\n# Example 2\nx = np.array([1.0, 3.0, 6.0, 10.0])\ny = np.array([1.1, 2.9, 6.1, 10.1])\n\nx_mean = np.mean(x)\ny_mean = np.mean(y)\n\nb1 = np.dot(y_mean - y, x_mean - x) / np.sum(np.power(x_mean - x, 2))\nb0 = y_mean - b1 * x_mean\nsigma_squared = (\n    1 / x.shape[0] * np.sum([(yi - b0 - b1 * xi) ** 2 for (xi, yi) in zip(x, y)])\n)\nprint(f\"b0 = {b0}\")\nprint(f\"b1 = {b1}\")\nprint(f\"sigma_squared = {sigma_squared}\")\n\n# %%\n# Example 3\nT_denominator = np.sqrt(np.sum([(yi - b0 - b1 * xi) ** 2 for (xi, yi) in zip(x, y)]))\nprint(T_denominator)\n\nsigma_prime = np.sqrt(\n    (\n        1\n        / (x.shape[0] - 2)\n        * np.sum([(yi - b0 - b1 * xi) ** 2 for (xi, yi) in zip(x, y)])\n    )\n)\nsx = np.sqrt(np.sum([(xi - x_mean) ** 2 for xi in x]))\nb0_distribution_denominator = sigma_prime * np.sqrt(\n    1 / x.shape[0] + x_mean ** 2 / sx ** 2\n)\nprint(b0_distribution_denominator)\nprint(T_denominator / b0_distribution_denominator)\n\nT = (b0 - 0.448) / T_denominator\nprint(T)\nprint(T * T_denominator / b0_distribution_denominator)\n", "meta": {"hexsha": "995e70f8abe276d491de7df61cee30723f3a9f4b", "size": 1475, "ext": "py", "lang": "Python", "max_stars_repo_path": "extras/cohort13.py", "max_stars_repo_name": "jamestiotio/pns", "max_stars_repo_head_hexsha": "1ff2988977619a547ca5b3f001f6d2a32871455c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extras/cohort13.py", "max_issues_repo_name": "jamestiotio/pns", "max_issues_repo_head_hexsha": "1ff2988977619a547ca5b3f001f6d2a32871455c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-04T16:22:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T16:22:50.000Z", "max_forks_repo_path": "extras/cohort13.py", "max_forks_repo_name": "jamestiotio/pns", "max_forks_repo_head_hexsha": "1ff2988977619a547ca5b3f001f6d2a32871455c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5833333333, "max_line_length": 85, "alphanum_fraction": 0.5715254237, "include": true, "reason": "import numpy", "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992923570261, "lm_q2_score": 0.8840392786908831, "lm_q1q2_score": 0.8556609922607215}}
{"text": "import numpy as np\n\n\ndef identity(z):\n    \"\"\"Identity function...\n    Args:\n        z (np.array)\n\n    Returns:\n        f(z) = z (np.array)\n    \"\"\"\n    return z\n\n\ndef dfdz_identity(z):\n    \"\"\"Derivative of the Identity function...\n    Args:\n        z (np.array)\n\n    Returns:\n        df(z)/dz = 1.0 (np.array)\n    \"\"\"\n    return np.ones_like(z)\n\n\ndef sigmoid(z):\n    \"\"\"Sigmoid function...\n    Args:\n        z (np.array)\n\n    Returns:\n        f(z) = 1 / (1 + exp(-z)) (np.array)\n    \"\"\"\n    return 1.0 / (1.0 + np.exp(-z))\n\n\ndef dfdz_sigmoid(z):\n    \"\"\"Derivative of the Sigmoid function...\n    Args:\n        z (np.array)\n\n    Returns:\n        df(z)/dz = f(z) * (1 - f(z)) (np.array)\n    \"\"\"\n    return sigmoid(z) * (1.0 - sigmoid(z))\n\n\ndef logistic(z):\n    \"\"\"Logistic function...\n    Args:\n        z (np.array)\n\n    Returns:\n        f(z) = 1 / (1 + exp(-z)) (np.array)\n    \"\"\"\n    return sigmoid(z)\n\n\ndef dfdz_logistic(z):\n    \"\"\"Derivative of the Logistic function...\n    Args:\n        z (np.array)\n\n    Returns:\n        df(z)/dz = f(z) * (1 - f(z)) (np.array)\n    \"\"\"\n    return sigmoid(z) * (1.0 - sigmoid(z))\n\n\ndef tanh(z):\n    \"\"\"Hyperbolic tangent function...\n    Args:\n        z (np.array)\n\n    Returns:\n        f(z) = 2.0 / (1.0 + np.exp(-2.0 * z)) - 1.0 (np.array)\n    \"\"\"\n    return 2.0 / (1.0 + np.exp(-2.0 * z)) - 1.0\n\n\ndef dfdz_tanh(z):\n    \"\"\"Derivative of the hyperbolic tangent function...\n    Args:\n        z (np.array)\n\n    Returns:\n        df(z)/dz = 1.0 - np.square(tanh(z)) (np.array)\n    \"\"\"\n    return 1.0 - np.square(tanh(z))\n\n\ndef softsign(z):\n    \"\"\"Softsign function...\n    Args:\n        z (np.array)\n\n    Returns:\n        f(z) = z / (1.0 + np.abs(z)) (np.array)\n    \"\"\"\n    return z / (1.0 + np.abs(z))\n\n\ndef dfdz_softsign(z):\n    \"\"\"Derivative of the softsign function...\n    Args:\n        z (np.array)\n\n    Returns:\n        df(z)/dz = None (np.array)\n    \"\"\"\n    raise RuntimeError('not implemented...')\n\n\ndef ReLU(z):\n    \"\"\"Rectified linear unit function...\n    Args:\n        z (np.array)\n\n    Returns:\n        f(z) = np.max(0, z) (np.array)\n    \"\"\"\n    return z * (z > 0)\n\n\ndef dfdz_ReLU(z):\n    \"\"\"Derivative of the rectified linear unit function...\n    Args:\n        z (np.array)\n\n    Returns:\n        df(z)/dz = 1 if x > 0 else 0 (np.array)\n    \"\"\"\n    return (z > 0)\n\n\ndef LReLU(z):\n    \"\"\"Leaky rectified linear unit function...\n    Args:\n        z (np.array)\n\n    Returns:\n        f(z) = z if z > 0 else 0.01 * z (np.array)\n    \"\"\"\n    return PReLU(z, 0.01)\n\n\ndef dfdz_LReLU(z):\n    \"\"\"Derivative of the leaky rectified linear unit function...\n    Args:\n        z (np.array)\n\n    Returns:\n        df(z)/dz = 1 if x > 0 else 0.01 (np.array)\n    \"\"\"\n    return dfdz_PReLU(z, 0.01)\n\n\ndef PReLU(z, alpha):\n    \"\"\"Parametric rectified linear unit function...\n    Args:\n        z (np.array)\n\n    Returns:\n        f(z) = z if z > 0 else alpha * z (np.array)\n    \"\"\"\n    return z * (z > 0) + alpha * z * (z <= 0)\n\n\ndef dfdz_PReLU(z, alpha):\n    \"\"\"Derivative of the parametric rectified linear unit function...\n    Args:\n        z (np.array)\n\n    Returns:\n        df(z)/dz = 1 if x > 0 else alpha (np.array)\n    \"\"\"\n    return 1.0 * (z > 0) + alpha * (z <= 0)\n", "meta": {"hexsha": "b06fc9d98daa38d99db09579ac3b175c04348759", "size": 3192, "ext": "py", "lang": "Python", "max_stars_repo_path": "MachineLearningLibrary/NeuralNetworks/NeuralNetworkUtilities.py", "max_stars_repo_name": "jeffcarter-github/MachineLearningLibrary", "max_stars_repo_head_hexsha": "b4b9f65351f456f709f32f3cdaf70a540c3bbc7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MachineLearningLibrary/NeuralNetworks/NeuralNetworkUtilities.py", "max_issues_repo_name": "jeffcarter-github/MachineLearningLibrary", "max_issues_repo_head_hexsha": "b4b9f65351f456f709f32f3cdaf70a540c3bbc7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MachineLearningLibrary/NeuralNetworks/NeuralNetworkUtilities.py", "max_forks_repo_name": "jeffcarter-github/MachineLearningLibrary", "max_forks_repo_head_hexsha": "b4b9f65351f456f709f32f3cdaf70a540c3bbc7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.9325842697, "max_line_length": 69, "alphanum_fraction": 0.501566416, "include": true, "reason": "import numpy", "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992923570262, "lm_q2_score": 0.8840392725805823, "lm_q1q2_score": 0.8556609863465658}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef sigmoid(val):\n    return 1/(1 + np.exp(-val))\n\ndef stable_coeff(rho, psi):\n    r = sigmoid(rho)\n    theta = np.pi * sigmoid(psi)\n\n    a_1 = -2*r*np.cos(theta)\n    a_2 = r**2\n    return a_1, a_2\n\ndef roots_polynomial(a_1, a_2):\n    delta = a_1**2 - 4 * a_2\n    delta = delta.astype(np.complex)\n    root_1 = (-a_1 + np.sqrt(delta))/2\n    root_2 = (-a_1 - np.sqrt(delta))/2\n    idx_real = delta > 0\n    return root_1, root_2, idx_real\n\n\nif __name__ == '__main__':\n\n    N = 100000\n    rho = np.random.randn(N)*1\n    psi = np.random.randn(N)*1\n\n    a_1, a_2 = stable_coeff(rho, psi)\n    r_1, r_2, idx_real = roots_polynomial(a_1, a_2)\n\n\n    fig, ax = plt.subplots()\n    ax.plot(a_1, a_2, '*')\n    ax.plot(a_1[idx_real], a_2[idx_real], 'k*')\n    ax.set_xlabel('a_1')\n    ax.set_ylabel('a_2')\n    ax.set_xlim([-2, 2])\n    ax.set_ylim([-2, 2])\n\n\n    fig, ax = plt.subplots()\n    ax.plot(np.real(r_1), np.imag(r_1), 'r*')\n    ax.plot(np.real(r_2), np.imag(r_2), 'r*')\n    ax.plot(np.real(r_1)[idx_real], np.imag(r_1)[idx_real], 'k*')\n    ax.plot(np.real(r_2)[idx_real], np.imag(r_2)[idx_real], 'k*')\n    ax.set_xlim([-1.2, 1.2])\n    ax.set_ylim([-1.2, 1.2])\n\n    perc_real = np.sum(idx_real) / N *100\n    print(f\"Real poles in {perc_real:.1f} cases\")\n", "meta": {"hexsha": "f7d718afb8adb98f58658bd36829e2136d64067e", "size": 1299, "ext": "py", "lang": "Python", "max_stars_repo_path": "test_code/stable_ocs_param.py", "max_stars_repo_name": "temcdrm/dynonet", "max_stars_repo_head_hexsha": "7c197c0912686111617667fe318fa848b9dde90e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2020-12-07T16:06:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:30:18.000Z", "max_issues_repo_path": "test_code/stable_ocs_param.py", "max_issues_repo_name": "temcdrm/dynonet", "max_issues_repo_head_hexsha": "7c197c0912686111617667fe318fa848b9dde90e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-04-28T20:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-14T10:23:33.000Z", "max_forks_repo_path": "test_code/stable_ocs_param.py", "max_forks_repo_name": "temcdrm/dynonet", "max_forks_repo_head_hexsha": "7c197c0912686111617667fe318fa848b9dde90e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-08-30T06:41:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T07:31:42.000Z", "avg_line_length": 24.0555555556, "max_line_length": 65, "alphanum_fraction": 0.5896843726, "include": true, "reason": "import numpy", "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992914310605, "lm_q2_score": 0.8840392725805823, "lm_q1q2_score": 0.8556609855279758}}
{"text": "from sympy import *\n\nax, bx, cx, dx, ay, by, cy, dy, t = symbols('ax bx cx dx ay by cy dy t')\nspeed_t = diff((3*ax*t**2 + 2*bx*t + cx)**2 + (3*ay*t**2 + 2*by*t + cy)**2, t )\nprint('speed by t expression: ')\nprint(speed_t)\nprint('\\n')\n\nconstant_speed_eq = integrate(speed_t**2, (t, 0, 1))\nprint('constant speed equation: ')\nprint(constant_speed_eq)\nprint('\\n')\n\n# p0 => t = 0; p1 => t = 1\np0x, p0y, p1x, p1y, p0dx, p0dy, p1dy_to_dx = symbols('p0x p0y p1x p1y p0dx p0dy p1dy_to_dx')\n\npoint0_x_eq = dx - p0x\npoint0_y_eq = dy - p0y\npoint1_x_eq = ax + bx + cx + dx - p1x\npoint1_y_eq = ay + by + cy + dy - p1y\n\npoint0_dx_eq = cx - p0dx\npoint0_dy_eq = cy - p0dy\n\npoint1_dy_to_dx_eq = 3*ay + 2*by + cy - p1dy_to_dx*(3*ax + 2*bx + cx)\n\nsolution = solve([constant_speed_eq, point0_x_eq, point0_y_eq, point1_x_eq, point1_y_eq, point0_dx_eq, point0_dy_eq, point1_dy_to_dx_eq], (ax, bx, cx, dx, ay, by, cy, dy))\n\nprint('solution: ')\nprint(solution)\nprint('\\n')\n", "meta": {"hexsha": "86f930d38fd7f8cc1d03bfc8d9041107f961db2a", "size": 948, "ext": "py", "lang": "Python", "max_stars_repo_path": "exp/bezier/test_quartic.py", "max_stars_repo_name": "NMinhNguyen/wordsandbuttons", "max_stars_repo_head_hexsha": "beba7f73c46f40790ad2482c2c0c04cfa5f626a4", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 367, "max_stars_repo_stars_event_min_datetime": "2018-01-29T17:45:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T03:50:52.000Z", "max_issues_repo_path": "exp/bezier/test_quartic.py", "max_issues_repo_name": "NMinhNguyen/wordsandbuttons", "max_issues_repo_head_hexsha": "beba7f73c46f40790ad2482c2c0c04cfa5f626a4", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-12-21T16:48:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-23T17:20:20.000Z", "max_forks_repo_path": "exp/bezier/test_quartic.py", "max_forks_repo_name": "NMinhNguyen/wordsandbuttons", "max_forks_repo_head_hexsha": "beba7f73c46f40790ad2482c2c0c04cfa5f626a4", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2018-02-18T11:52:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T09:46:53.000Z", "avg_line_length": 29.625, "max_line_length": 171, "alphanum_fraction": 0.6529535865, "include": true, "reason": "from sympy", "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9828232909876816, "lm_q2_score": 0.8705972633721708, "lm_q1q2_score": 0.8556432675123063}}
{"text": "# -*- coding: utf-8 -*-\nimport numpy as np\n\ndef cos_sim(a, b):\n\t\"\"\"Takes 2 vectors a, b and returns the cosine similarity according \n\tto the definition of the dot product\n\t\"\"\"\n\tdot_product = np.dot(a, b)\n\tnorm_a = np.linalg.norm(a)\n\tnorm_b = np.linalg.norm(b)\n\treturn dot_product / (norm_a * norm_b)\n\n# the counts we computed above\nsentence_m = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0]) \nsentence_h = np.array([0, 0, 1, 1, 1, 1, 0, 0, 0])\nsentence_w = np.array([0, 0, 0, 1, 0, 0, 1, 1, 1])\n\n# We should expect sentence_m and sentence_h to be more similar\nprint(cos_sim(sentence_m, sentence_m)) # 1.0\nprint(cos_sim(sentence_m, sentence_h)) # 0.5\nprint(cos_sim(sentence_m, sentence_w)) # 0.25\n", "meta": {"hexsha": "7af282cffd81d7ddb8657baaf09fd75fcdcb5331", "size": 687, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/cosine_similarity.py", "max_stars_repo_name": "muthusk07/cs-algorithms", "max_stars_repo_head_hexsha": "5e05de538e672cf49dd6c689a317c32959a67902", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 239, "max_stars_repo_stars_event_min_datetime": "2019-10-07T11:01:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T19:08:55.000Z", "max_issues_repo_path": "Python/cosine_similarity.py", "max_issues_repo_name": "muthusk07/cs-algorithms", "max_issues_repo_head_hexsha": "5e05de538e672cf49dd6c689a317c32959a67902", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 176, "max_issues_repo_issues_event_min_datetime": "2019-10-07T06:59:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-30T08:16:22.000Z", "max_forks_repo_path": "Python/cosine_similarity.py", "max_forks_repo_name": "muthusk07/cs-algorithms", "max_forks_repo_head_hexsha": "5e05de538e672cf49dd6c689a317c32959a67902", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 441, "max_forks_repo_forks_event_min_datetime": "2019-10-07T07:34:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T07:19:58.000Z", "avg_line_length": 31.2272727273, "max_line_length": 69, "alphanum_fraction": 0.672489083, "include": true, "reason": "import numpy", "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407168145568, "lm_q2_score": 0.879146761176671, "lm_q1q2_score": 0.8556214240327793}}
{"text": "from numpy import any, array, array_str, concatenate, dot, intersect1d\nfrom numpy import nonzero, ravel, setdiff1d, zeros\nfrom numpy.linalg import lstsq, norm\n\ndef active_constraints(A, b, x):\n    \"\"\"Return a set of active constraints\n    \"\"\"\n    dx = b - dot(A, x)\n    if any(dx > 0):\n        raise ValueError('x is infeasible')\n    return nonzero(dx == 0)[0]\n\ndef get_starting_point(A, b):\n    raise NotImplementedError('You need to provide x_0')\n\ndef get_dual_vars(G, f, A, x, W):\n    \"\"\"Compute lagrange multiplies for W\"\"\"\n    mu, res, rank, s = lstsq(A[W, :].T, dot(G, x) + f)\n    return mu\n\ndef quadprog(G, f, A, b, x_0=None, max_iter=1e6, tol=1e-4, verbose=True):\n    \"\"\"Solve convex QP via active set method\n\n    min 0.5 * x^T * G * x + f^T * x\n    s.t. A * x >= b\n\n    \"\"\"\n    # Compute a feasible starting point\n    if x_0 is None:\n        x = get_starting_point(A, b)\n    else:\n        x = x_0.copy()\n    m, n, k = x.size, A.shape[0], 0\n    # Set initial active-set of contraints\n    W = active_constraints(A, b, x)\n    while k < max_iter:\n       f_obj = dot(x.T, dot(G, x)) + dot(f.T, x)\n       if verbose:\n           print 'Iter: {0}\\tObj: {1}\\tW: {2:5}\\tx: {3}'.format(k,\n               array_str(ravel(f_obj), precision=3), array_str(W),\n               array_str(ravel(x), precision=3))\n       p = solve_qp_eq(G, f, A[W, :], b[W], x)\n       if norm(p) <= tol * m**2:\n           lmbda = get_dual_vars(G, f, A, x, W)\n           if all(lmbda >= 0):\n               # Global minimizer was found\n               if verbose:\n                   print 'Optimization finished\\n'\n               break\n           else:\n               # Remove most-violated constraint\n               j = lmbda.argmin()\n               W = setdiff1d(W, [W[j]])\n       else:\n           alpha, j = step_size(A, b, x, p, W)\n           x = x + alpha*p\n           if j is not None:\n               # Add a blocking constraint\n               W = concatenate((W, [j]), axis=0)\n       k += 1\n    if k == max_iter and verbose:\n        print 'Max number of iterations reached'\n    return x\n\ndef solve_qp_eq(G, f, C, d, x):\n    \"\"\"Solve QP with equality constraint\"\"\"\n    m, n = x.size, C.shape[0]\n    A = concatenate((concatenate((G, C.T), axis=1),\n                     concatenate((C, zeros((n, n))), axis=1)), axis=0)\n    b = concatenate((f + dot(G, x), dot(C, x) - d), axis=0)\n    lmbda, res, rank, s = lstsq(A, b)\n    return -lmbda[:m, :]\n\ndef step_size(A, b, x, p, W):\n    \"\"\"Compute minimum step size such that x + p is still in the polyhedron\"\"\"\n    num, den, alpha_min, block = b - dot(A, x), dot(A, p), 1, None\n    alpha = num / den\n    J = intersect1d(setdiff1d(range(A.shape[0]), W, assume_unique=True),\n                    nonzero(den < 0)[0])\n    if J.size != 0:\n        alpha_min = alpha[J].min()\n    alpha_hat = min(1, alpha_min)\n    # Check blocking constraints\n    if alpha_hat < 0:\n        raise ValueError('Got a negative alpha (step length)')\n    elif alpha_hat < 1:\n        block = nonzero(alpha_hat == alpha)[0][0]\n    return alpha_hat, block\n \ndef hw5_1b():\n    \"\"\"\n    Solve the following qp with active set method\n    min x_1^2 + 2*x_2^2 - 2*x_1 - 6*x_2 - 2*x_1*x_2\n    s.t. 0.5*x_1 + 0.5*x_2 <= 1; -1*x_1 + 2*x_2 <= 2; x_1>=0; x_2>= 0\n\n    Choose x_0 inside, in the boundary and as extrem point.\n    \"\"\"\n    G = array([[2, -2],[-2, 4]])\n    F = array([[-2],[-6]])\n    A = -1 * array([[0.5, 0.5], [-1, 2], [-1, 0], [0, -1]])\n    b = -1 * array([[1],[2],[0],[0]])\n    x_seed = [array([[1], [0.5]]), array([[0], [0]]), array([[0], [0.5]])]\n    for x_0 in x_seed:\n        x = quadprog(G, F, A, b, x_0)\n\nif __name__ == '__main__':\n    hw5_1b()\n", "meta": {"hexsha": "bb681736049369bcfd9ad97611a2c680028d05c8", "size": 3638, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw5/hw5_1.py", "max_stars_repo_name": "escorciav/amcs211", "max_stars_repo_head_hexsha": "04bb1c212bdadad3e7999ccfd96fe920bebd2899", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-05-20T01:03:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-30T17:28:27.000Z", "max_issues_repo_path": "hw5/hw5_1.py", "max_issues_repo_name": "escorciav/amcs211", "max_issues_repo_head_hexsha": "04bb1c212bdadad3e7999ccfd96fe920bebd2899", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw5/hw5_1.py", "max_forks_repo_name": "escorciav/amcs211", "max_forks_repo_head_hexsha": "04bb1c212bdadad3e7999ccfd96fe920bebd2899", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-02-01T19:36:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-11T02:21:24.000Z", "avg_line_length": 33.6851851852, "max_line_length": 78, "alphanum_fraction": 0.5302363936, "include": true, "reason": "from numpy", "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248259606259, "lm_q2_score": 0.9111797130267452, "lm_q1q2_score": 0.8556203714437924}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom welib.tools.signal import *\nfrom numpy.random import seed; seed(0)\n\n# --- Parameters\ndt    = 1\nn     = 10000\ncoeff = 0.95 # 1:full corr, 0: no-corr\nnMax  = 180\n# --- Create a correlated time series\ntvec = np.arange(0,n)*dt\nts   = correlated_signal(coeff, n)\n# --- Compute correlation coefficient\nR, tau = correlation(ts, nMax=nMax, dt=dt)\n\n# --- Plot\nfig,axes = plt.subplots(2, 1, sharey=False, figsize=(6.4,4.8)) # (6.4,4.8)\nfig.subplots_adjust(left=0.12, right=0.95, top=0.95, bottom=0.11, hspace=0.20, wspace=0.20)\nax=axes[0]\n# Plot time series\nax.plot(tvec,ts)\nax.set_xlabel('t [s]')\nax.set_ylabel('u [m/s]')\nax.tick_params(direction='in')\n# Plot correlation\nax=axes[1]\nax.plot(tau,  R              ,'-o', label='Computed')\nax.plot(tau, coeff**(tau/dt) ,'--' ,label=r'Theoretical -  c$^{\\tau/dt}$') # analytical coeff^n trend\nax.set_xlabel(r'$\\tau$ [s]')\nax.set_ylabel(r'$R(\\tau)$ [-]')\nax.set_title('Signal - Correlation coefficient')\nax.legend()\n\n\nif __name__=='__main__':\n    plt.show()\nif __name__ == '__test__':\n    pass\nif __name__==\"__export__\":\n    from welib.tools.repo import export_figs_callback\n    export_figs_callback(__file__)\n", "meta": {"hexsha": "931ffa8e2d93b1406201e2d30c925c927343d201", "size": 1202, "ext": "py", "lang": "Python", "max_stars_repo_path": "welib/tools/examples/ExampleCorrelation.py", "max_stars_repo_name": "moonieann/welib", "max_stars_repo_head_hexsha": "0e430ad3ca034d0d2d60bdb7bbe06c947ce08f52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2019-07-24T23:37:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T20:40:40.000Z", "max_issues_repo_path": "welib/tools/examples/ExampleCorrelation.py", "max_issues_repo_name": "moonieann/welib", "max_issues_repo_head_hexsha": "0e430ad3ca034d0d2d60bdb7bbe06c947ce08f52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "welib/tools/examples/ExampleCorrelation.py", "max_forks_repo_name": "moonieann/welib", "max_forks_repo_head_hexsha": "0e430ad3ca034d0d2d60bdb7bbe06c947ce08f52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-03-14T13:47:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:47:27.000Z", "avg_line_length": 27.9534883721, "max_line_length": 101, "alphanum_fraction": 0.6697171381, "include": true, "reason": "import numpy,from numpy", "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.904650541527608, "lm_q1q2_score": 0.8556196284788788}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\n# Plot 2D points\ndef displaypoints2d(points):\n  plt.figure(0)\n  plt.plot(points[0,:],points[1,:], '.b')\n  plt.xlabel('Screen X')\n  plt.ylabel('Screen Y')\n\n\n# Plot 3D points\ndef displaypoints3d(points):\n  fig = plt.figure(1)\n  ax = fig.add_subplot(111, projection='3d')\n  ax.scatter(points[0,:], points[1,:], points[2,:], 'b')\n  ax.set_xlabel(\"World X\")\n  ax.set_ylabel(\"World Y\")\n  ax.set_zlabel(\"World Z\")\n\n\ndef cart2hom(points):\n  \"\"\" Transforms from cartesian to homogeneous coordinates.\n\n  Args:\n    points: a np array of points in cartesian coordinates\n\n  Returns:\n    points_hom: a np array of points in homogeneous coordinates\n  \"\"\"\n\n  #\n  # You code here\n  #\n\n  # add an additional component and fill it with ones\n  return np.concatenate((points, np.ones((1, points.shape[1]))))\n\n\n\ndef hom2cart(points):\n  \"\"\" Transforms from homogeneous to cartesian coordinates.\n\n  Args:\n    points: a np array of points in homogenous coordinates\n\n  Returns:\n    points_hom: a np array of points in cartesian coordinates\n  \"\"\"\n\n  #\n  # You code here\n  #\n  \n  # Perform perspective division\n  res = points[:-1,:]/points[-1,:]\n  return res\n\n\n\n\ndef gettranslation(v):\n  \"\"\" Returns translation matrix T in homogeneous coordinates for translation by v.\n\n  Args:\n    v: 3d translation vector\n\n  Returns:\n    T: translation matrix in homogeneous coordinates\n  \"\"\"\n\n  #\n  # You code here\n  #\n\n  T = np.eye(4)\n  T[0:3,3] = v\n  return T\n\n\ndef getxrotation(d):\n  \"\"\" Returns rotation matrix Rx in homogeneous coordinates for a rotation of d degrees around the x axis.\n\n  Args:\n    d: degrees of the rotation\n\n  Returns:\n    Rx: rotation matrix\n  \"\"\"\n\n  #\n  # You code here\n  #\n  \n  r = np.radians(d)\n  Rx = np.eye(4)\n  Rx[1:3,1:3] = np.array([[np.cos(r), -np.sin(r)],[np.sin(r),np.cos(r)]])\n  return Rx\n\n\n\ndef getyrotation(d):\n  \"\"\" Returns rotation matrix Ry in homogeneous coordinates for a rotation of d degrees around the y axis.\n\n  Args:\n    d: degrees of the rotation\n\n  Returns:\n    Ry: rotation matrix\n  \"\"\"\n\n  #\n  # You code here\n  #\n\n  r = np.radians(d)\n  Ry = np.eye(4)\n  Ry[0:3:2, 0:3:2] = np.array([[np.cos(r),np.sin(r)],[-np.sin(r),np.cos(r)]])\n  return Ry\n\n\n\ndef getzrotation(d):\n  \"\"\" Returns rotation matrix Rz in homogeneous coordinates for a rotation of d degrees around the z axis.\n\n  Args:\n    d: degrees of the rotation\n\n  Returns:\n    Rz: rotation matrix\n  \"\"\"\n\n  #\n  # You code here\n  #\n  \n  r = np.radians(d)\n  Rz = np.eye(4)\n  Rz[0:2,0:2] = np.array([[np.cos(r),-np.sin(r)],[np.sin(r),np.cos(r)]])\n  return Rz\n\n\n\ndef getcentralprojection(principal, focal):\n  \"\"\" Returns the (3 x 4) matrix L that projects homogeneous camera coordinates on homogeneous\n  image coordinates depending on the principal point and focal length.\n  \n  Args:\n    principal: the principal point, 2d vector\n    focal: focal length\n\n  Returns:\n    L: central projection matrix\n  \"\"\"\n\n  #\n  # You code here\n  #\n\n  # l1-image_formation-v1 Seite 35\n\n  # [[f,0,px,0],\n  #  [0,f,py,0],\n  #  [0,0,1,0]] \n  \n  return np.array([[focal, 0.0, principal[0], 0.0],\n                    [0.0, focal, principal[1], 0.0],\n                    [0.0, 0.0, 1.0, 0.0]])\n\n\ndef getfullprojection(T, Rx, Ry, Rz, L):\n  \"\"\" Returns full projection matrix P and full extrinsic transformation matrix M.\n\n  Args:\n    T: translation matrix\n    Rx: rotation matrix for rotation around the x-axis\n    Ry: rotation matrix for rotation around the y-axis\n    Rz: rotation matrix for rotation around the z-axis\n    L: central projection matrix\n\n  Returns:\n    P: projection matrix\n    M: matrix that summarizes extrinsic transformations\n  \"\"\"\n\n  #\n  # You code here\n  #\n\n  # l1-image_formation-v1 Seite 39\n\n  # Model transformations\n  M = Rz.dot(Rx.dot(Ry.dot(T)))\n  # Full projection matrix\n  P = L.dot(M)\n  return P,M\n\ndef projectpoints(P, X):\n  \"\"\" Apply full projection matrix P to 3D points X in cartesian coordinates.\n\n  Args:\n    P: projection matrix\n    X: 3d points in cartesian coordinates\n\n  Returns:\n    x: 2d points in cartesian coordinates\n  \"\"\"\n\n  #\n  # You code here\n  #\n\n  return hom2cart(P.dot(cart2hom(X)))\n\n\n\n\n\ndef loadpoints():\n  \"\"\" Load 2D points from obj2d.npy.\n\n  Returns:\n    x: np array of points loaded from obj2d.npy\n  \"\"\"\n\n  #\n  # You code here\n  #\n\n  # Load arrays from ``.npy``\n  x = np.load('data/obj2d.npy')\n  return x\n\n\ndef loadz():\n  \"\"\" Load z-coordinates from zs.npy.\n\n  Returns:\n    z: np array containing the z-coordinates\n  \"\"\"\n\n  #\n  # You code here\n  #\n  z = np.load('data/zs.npy')\n  return z\n\n\ndef invertprojection(L, P2d, z):\n  \"\"\"\n  Invert just the projection L of cartesian image coordinates P2d with z-coordinates z.\n\n  Args:\n    L: central projection matrix\n    P2d: 2d image coordinates of the projected points\n    z: z-components of the homogeneous image coordinates\n\n  Returns:\n    P3d: 3d cartesian camera coordinates of the points\n  \"\"\"\n\n  #\n  # You code here\n  #\n\n  # Extract camera intrinsics\n  # l1-image_formation-v Seite 37\n  K = L[:,0:3]\n  # Account for unknown scale\n  # l1-image_formation-v1 Seite 24\n  P3d = z*(np.linalg.solve(K,cart2hom(P2d)))\n  return P3d\n\n\ndef inverttransformation(M, P3d):\n  \"\"\" Invert just the model transformation in homogeneous coordinates\n  for the 3D points P3d in cartesian coordinates.\n\n  Args:\n    M: matrix summarizing the extrinsic transformations\n    P3d: 3d points in cartesian coordinates\n\n  Returns:\n    X: 3d points after the extrinsic transformations have been reverted\n  \"\"\"\n  \n  #\n  # You code here\n  #\n\n  # extrinsic transformations\n  # l1-image_formation-v1 Seite 29\n\n  X = np.linalg.solve(M,cart2hom(P3d))\n  return X\n\n\n\n\ndef p3multiplecoice():\n  '''\n  Change the order of the transformations (translation and rotation).\n  Check if they are commutative. Make a comment in your code.\n  Return 0, 1 or 2:\n  0: The transformations do not commute.\n  1: Only rotations commute with each other.\n  2: All transformations commute.\n  '''\n\n  return -1", "meta": {"hexsha": "19148a6f140ac7a0dfaaae872ab869fe02bd52e8", "size": 5943, "ext": "py", "lang": "Python", "max_stars_repo_path": "CV1_assignment1/problem3_Loesung.py", "max_stars_repo_name": "cjy513203427/CV_Assignment", "max_stars_repo_head_hexsha": "ac837dcd67f0d237017ef0124210bf9da0151487", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CV1_assignment1/problem3_Loesung.py", "max_issues_repo_name": "cjy513203427/CV_Assignment", "max_issues_repo_head_hexsha": "ac837dcd67f0d237017ef0124210bf9da0151487", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CV1_assignment1/problem3_Loesung.py", "max_forks_repo_name": "cjy513203427/CV_Assignment", "max_forks_repo_head_hexsha": "ac837dcd67f0d237017ef0124210bf9da0151487", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1093247588, "max_line_length": 106, "alphanum_fraction": 0.6565707555, "include": true, "reason": "import numpy", "num_tokens": 1697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322215, "lm_q2_score": 0.9046505306021881, "lm_q1q2_score": 0.8556196236737543}}
{"text": "#------------------------------------------------------------------------------------------------------------#\n#Chapter 2 - Visualization with hierarchical clustering and t-SNE\n\n\n\n\n\n\n#------------------------------------------------------------------------------------------------------------#\n#Hierarchical clustering of the grain data\n\n# Perform the necessary imports\nfrom scipy.cluster.hierarchy import linkage, dendrogram\nimport matplotlib.pyplot as plt\n\n# Calculate the linkage: mergings\nmergings = linkage(samples, method='complete')\n\n# Plot the dendrogram, using varieties as labels\ndendrogram(mergings,\n           labels=varieties,\n           leaf_rotation=90,\n           leaf_font_size=6,\n)\nplt.show()\n\n#------------------------------------------------------------------------------------------------------------#\n\n#Hierarchies of stocks\n# Import normalize\nfrom sklearn.preprocessing import normalize\n\n# Normalize the movements: normalized_movements\nnormalized_movements = normalize(movements)\n\n# Calculate the linkage: mergings\nmergings = linkage(normalized_movements, method='complete')\n\n# Plot the dendrogram\ndendrogram(mergings,\n           labels=companies,\n           leaf_rotation=90,\n           leaf_font_size=6,\n)\n\nplt.show()\n\n\n#------------------------------------------------------------------------------------------------------------#\n#Different linkage, different hierarchical clustering!\n# Perform the necessary imports\nimport matplotlib.pyplot as plt\nfrom scipy.cluster.hierarchy import dendrogram, linkage\n\n# Calculate the linkage: mergings\nmergings = linkage(samples,method='single')\n\n# Plot the dendrogram\ndendrogram(mergings,\n           labels=country_names,\n           leaf_rotation=90,\n           leaf_font_size=6,\n)\nplt.xlabel('European Nations')\nplt.ylabel('Number of votes')\nplt.title('EuroVision 2017 Denogram ')\nplt.legend(loc='upper right')\nplt.show()\n\n\n\n\n#------------------------------------------------------------------------------------------------------------#\n\n#Extracting the cluster labels\n# Perform the necessary imports\nimport pandas as pd\nfrom scipy.cluster.hierarchy import fcluster\n\n# Use fcluster to extract labels: labels\nlabels = fcluster(mergings,6,criterion='distance')\n\n# Create a DataFrame with labels and varieties as columns: df\ndf = pd.DataFrame({'labels': labels, 'varieties': varieties})\n\n# Create crosstab: ct\nct = pd.crosstab(df['labels'],df['varieties'])\n\n# Display ct\nprint(ct)\n\n\n#------------------------------------------------------------------------------------------------------------#\n#t-SNE visualization of grain dataset\n# Import TSNE\nfrom sklearn.manifold import TSNE\n\n# Create a TSNE instance: model\nmodel = TSNE(learning_rate=200)\n\n# Apply fit_transform to samples: tsne_features\ntsne_features = model.fit_transform(samples)\n\n# Select the 0th feature: xs\nxs = tsne_features[:,0]\n\n# Select the 1st feature: ys\nys = tsne_features[:,1]\n\n# Scatter plot, coloring by variety_numbers\nplt.scatter(xs,ys,c=variety_numbers)\nplt.show()\n\n\n\n\n#------------------------------------------------------------------------------------------------------------#\n#A t-SNE map of the stock market\n\n# Import TSNE\nfrom sklearn.manifold import TSNE\n\n# Create a TSNE instance: model\nmodel = TSNE(learning_rate=50)\n\n# Apply fit_transform to normalized_movements: tsne_features\ntsne_features = model.fit_transform(normalized_movements)\n\n# Select the 0th feature: xs\nxs = tsne_features[:,0]\n\n# Select the 1th feature: ys\nys = tsne_features[:,1]\n\n# Scatter plot\nplt.scatter(xs,ys,alpha=0.5)\n\n# Annotate the points\nfor x, y, company in zip(xs, ys, companies):\n    plt.annotate(company, (x, y), fontsize=5, alpha=0.75)\nplt.show()\n\n\n#------------------------------------------------------------------------------------------------------------#\n\n\n#------------------------------------------------------------------------------------------------------------#\n\n\n\n#------------------------------------------------------------------------------------------------------------#\n\n\n#------------------------------------------------------------------------------------------------------------#\n\n\n\n#------------------------------------------------------------------------------------------------------------#\n\n\n\n\n#------------------------------------------------------------------------------------------------------------#\n\n\n\n\n\n#------------------------------------------------------------------------------------------------------------#\n\n\n\n\n\n#------------------------------------------------------------------------------------------------------------#\n\n\n\n\n\n#------------------------------------------------------------------------------------------------------------#\n\n\n\n\n\n#------------------------------------------------------------------------------------------------------------#", "meta": {"hexsha": "4d38dcfd4526b232c7c31d7eac4ebd4e2c54d5ba", "size": 4819, "ext": "py", "lang": "Python", "max_stars_repo_path": "Unsupervised Learning in Python/Chapter 2 - Visualization with hierarchical clustering and t-SNE.py", "max_stars_repo_name": "nabeelsana/DataCamp-courses", "max_stars_repo_head_hexsha": "f6208c44b2c21d0da87013b6ef624c75af8820f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 464, "max_stars_repo_stars_event_min_datetime": "2018-03-01T21:53:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:56:26.000Z", "max_issues_repo_path": "Unsupervised Learning in Python/Chapter 2 - Visualization with hierarchical clustering and t-SNE.py", "max_issues_repo_name": "citnan/datacamp-python-data-science-track", "max_issues_repo_head_hexsha": "383b644907cca1c14befb4706a32579bec01a134", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-02-28T14:34:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T05:10:33.000Z", "max_forks_repo_path": "Unsupervised Learning in Python/Chapter 2 - Visualization with hierarchical clustering and t-SNE.py", "max_forks_repo_name": "citnan/datacamp-python-data-science-track", "max_forks_repo_head_hexsha": "383b644907cca1c14befb4706a32579bec01a134", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 423, "max_forks_repo_forks_event_min_datetime": "2018-04-06T15:40:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T03:20:14.000Z", "avg_line_length": 25.7700534759, "max_line_length": 110, "alphanum_fraction": 0.4494708446, "include": true, "reason": "from scipy", "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474220263198, "lm_q2_score": 0.8962513828326955, "lm_q1q2_score": 0.8556040721087569}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"problem 2 class 4 offline\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/drive/10n45tcpjVcRcO65S-6hJK2_trgI091yp\n\"\"\"\n\n# libraries\nimport random \nimport math\nimport numpy as np \nimport matplotlib.pyplot as plt\nrandom.seed(10)\n\ndef integral(N):\n  A= 0\n  B = 8\n  # lists for storing the values\n  y1_values = []\n  y1_square_values =[]\n\n  y2_values =[]\n  y2_square_values =[]\n\n  count_1 = 0\n  count_2 = 0 \n\n  for i in range(1,N+1):\n    # x random value generation\n    x = random.uniform(A,B)\n    # calculating first area value\n    if x <=4 : \n      y1 = math.sqrt(4 * x)\n      y1_values.append(y1)\n      y1_square_values.append(y1*y1)\n      count_1 += 1 \n    else: \n      y2 = 8 - x\n      y2_values.append(y2)\n      y2_square_values.append(y2*y2)\n      count_2 += 1 \n\n  # calculate 0 to 4 area first part\n  y1_average = sum(y1_values) / len(y1_values)\n  y1_square_average = sum(y1_square_values) / len(y1_square_values)\n  area_1 = y1_average * ( 4-0 )\n  error_1 = ( (4-0) / math.sqrt(count_1) ) * math.sqrt(y1_square_average - y1_average**2)\n\n  # calculate 4 to 8 area second part\n  y2_average = sum(y2_values) / len(y2_values)\n  y2_square_average = sum(y2_square_values) / len(y2_square_values)\n  area_2 = y2_average * ( 8-4 )\n  error_2 = ( (8-4) / math.sqrt(count_2) ) * math.sqrt(y2_square_average - y2_average**2)\n\n  #total area and error\n  integral_value = area_1 + area_2 \n  error_estimate = error_1 + error_2 \n  \n  print(\"For number of sample points: \", N)\n  print(\"Integral Value: \", integral_value)\n  print(\"Estimated Error: \", error_estimate)\n  print(\"\")\n\nN = [100,1000,5000,10000]\nfor i in N:\n  integral(i)", "meta": {"hexsha": "642085bd5374073e7d8c5709a3728dd5a6420f81", "size": 1701, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignment 03 - Monte Carlo Intregral/problem2.py", "max_stars_repo_name": "lmottasin/Simulation_Lab", "max_stars_repo_head_hexsha": "e3b365f7bb7f6ac4b542f2c6bd721e4a77c056ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-13T04:44:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T20:21:11.000Z", "max_issues_repo_path": "Assignment 03 - Monte Carlo Intregral/problem2.py", "max_issues_repo_name": "lmottasin/Simulation_Lab", "max_issues_repo_head_hexsha": "e3b365f7bb7f6ac4b542f2c6bd721e4a77c056ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment 03 - Monte Carlo Intregral/problem2.py", "max_forks_repo_name": "lmottasin/Simulation_Lab", "max_forks_repo_head_hexsha": "e3b365f7bb7f6ac4b542f2c6bd721e4a77c056ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-06-30T11:16:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T18:32:46.000Z", "avg_line_length": 25.0147058824, "max_line_length": 89, "alphanum_fraction": 0.6690182246, "include": true, "reason": "import numpy", "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474233166328, "lm_q2_score": 0.8962513752119936, "lm_q1q2_score": 0.8556040659901183}}
{"text": "\"\"\"\nYou have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points.\n\nExample:\n\n    Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]\n    Output: 2\n    Explanation: The five points are show in the figure below. The red triangle is the largest.\n\n    https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/04/1027.png\n\nNotes:\n    1. 3 <= points.length <= 50.\n    2. No points will be duplicated.\n    3. -50 <= points[i][j] <= 50.\n    4. Answers within 10^(-6) of the true value will be accepted as correct.\n\"\"\"\n\nimport itertools\nimport numpy as np\n\n\nclass Solution:\n    def largestTriangleArea1(self, points):\n        def area(A, B, C):\n            x_1, y_1 = A\n            x_2, y_2 = B\n            x_3, y_3 = C\n            return 0.5 * abs(x_2 * y_3 - x_3 * y_2 - x_1 * y_3 + x_3 * y_1 + x_1 * y_2 - x_2 * y_1)\n        \n        return max(area(*selected) for selected in itertools.combinations(points, 3))\n\n    def largestTriangleArea2(self, points):\n        return max(\n            abs(np.linalg.det(np.hstack((np.array(selected), np.ones((3, 1)))))) * 0.5 for selected in itertools.combinations(points, 3)\n        )\n", "meta": {"hexsha": "83aa44c5cd805ee15e02cf66a6eee078b0275215", "size": 1172, "ext": "py", "lang": "Python", "max_stars_repo_path": "leetcode/0812_largest_triangle_area.py", "max_stars_repo_name": "chaosWsF/Python-Practice", "max_stars_repo_head_hexsha": "ff617675b6bcd125933024bb4c246b63a272314d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "leetcode/0812_largest_triangle_area.py", "max_issues_repo_name": "chaosWsF/Python-Practice", "max_issues_repo_head_hexsha": "ff617675b6bcd125933024bb4c246b63a272314d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "leetcode/0812_largest_triangle_area.py", "max_forks_repo_name": "chaosWsF/Python-Practice", "max_forks_repo_head_hexsha": "ff617675b6bcd125933024bb4c246b63a272314d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6756756757, "max_line_length": 136, "alphanum_fraction": 0.6083617747, "include": true, "reason": "import numpy", "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474246069458, "lm_q2_score": 0.8962513662057089, "lm_q1q2_score": 0.8556040585487367}}
{"text": "#regla de simpson compuesta\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x):\n    return (1/4)*x*(10-x)+ np.sin(np.pi*x)\na=0\nb=5\nN=5\nh=(b-a)/N\n\ndef simpson(f,a,b,N, h):\n    h = h / 2\n    Xi=np.array([a+h*i for i in range(2*N+1)])\n    Yi=f(Xi)\n    suma1=sum(np.array([Yi[2*i] for i in range(1,N)]))\n    suma2=sum(np.array([Yi[2*i+1] for i in range(N)]))\n    simpson= (h/3)*(f(a)+2*suma1+4*suma2+f(b))\n    print(simpson)\n    \n    return simpson\n\nprint(\"La aprox. de la integral por la regla de simpson compuesta es: \", simpson(f,a,b,N))\n\nXi= np.array([a+h*i for i in range(N)]) #para calcular la funcion\nYi= f(Xi)\n\nxi=np.linspace(a,b,100) #Para graficar muchos puntos para f(x) y sea suave\nyi=f(xi)\n\nplt.title(\"Funcion y funcion escalon usada para integrar\")\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.step(Xi,Yi,'r') #funcion escalon\nplt.plot(xi,yi,'b') #funcion f(x)\n\nfor j in range(len(Xi)):\n    plt.plot(Xi[j], Yi[j],'go') #puntos (xi,yi)\n\nplt.savefig(\"EjReglaDeSimpson.png\")\nplt.show()\n\n\n\nN = 10\nx = [1 * i for i in range(2*N+1)]\nn1 = len(x)\nn2 = len([x[2*i] for i in range(1,N)])\nn3 = len([x[2*i+1] for i in range(N)])\n\n\n\n\n\n", "meta": {"hexsha": "c47d4880a374d421e9a0a8841f179aae889209ec", "size": 1134, "ext": "py", "lang": "Python", "max_stars_repo_path": "codes/kondo/ej14-reglasimpson-.py", "max_stars_repo_name": "mlares/computacion2020", "max_stars_repo_head_hexsha": "185bfded8ef1670e80b1c2cdc1fceb365d962b0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "codes/kondo/ej14-reglasimpson-.py", "max_issues_repo_name": "mlares/computacion2020", "max_issues_repo_head_hexsha": "185bfded8ef1670e80b1c2cdc1fceb365d962b0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/kondo/ej14-reglasimpson-.py", "max_forks_repo_name": "mlares/computacion2020", "max_forks_repo_head_hexsha": "185bfded8ef1670e80b1c2cdc1fceb365d962b0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.25, "max_line_length": 90, "alphanum_fraction": 0.6172839506, "include": true, "reason": "import numpy", "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456936, "lm_q2_score": 0.8962513668985, "lm_q1q2_score": 0.8556040545843286}}
{"text": "import enum\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\n\n# 3. Calculate the logistic map function for l = 0.5, 2.5, 3.5, 4\n#    Xn+1 = l * Xn (1 - Xn)\n# 4. Compare the same statistical features of your RW (2) and the four\n#    different logistic map time series (3)\n\nLENGTH = 100\nl = np.asarray([0.5, 2.5, 3.5, 4])\nl_len = len(l)\n\nmeans = np.zeros((l_len, 1))\nvariances = np.zeros((l_len, 1))\nstrd_deviations = np.zeros((l_len, 1))\n\nensemble = np.zeros(LENGTH)\nensemble_mean = 0\nensemble_strd_dev = 0\n\n# Temporary storage for calculations\ntmp_arr = np.zeros((l_len, LENGTH))\n\nX = np.zeros((l_len, LENGTH))\n\nfor i in range(l_len):\n    # Initial value\n    X[i][0] = 0.3\n    for n in range(LENGTH - 1):\n        X[i][n+1] = l[i] * X[i][n] * (1 - X[i][n])\n\n    means[i] = np.mean(X[i])\n\n    # Standard deviation\n    tmp_arr[i] = np.subtract(X[i], means[i])\n    tmp_arr[i] = tmp_arr[i] * tmp_arr[i]\n    variances[i] = np.sum(tmp_arr[i]) / LENGTH\n\n    strd_deviations[i] = np.sqrt(np.sum(tmp_arr[i]) / (LENGTH - 1))\n    \n\n\nprint (\"Means\")\nprint (means)\nprint (\"Variances\")\nprint (variances)\nprint (\"Standard deviations\")\nprint (strd_deviations)\n\n\n# Calculate ensemble\nensemble = np.sum(X, axis=0)\nensemble = ensemble / l_len\n\n# Ensemble time-average mean\nensemble_mean = np.mean(ensemble)\n\n# Ensemble standard deviation\nensemble_tmp = np.subtract(ensemble, ensemble_mean)\nensemble_tmp = ensemble_tmp * ensemble_tmp\nensemble_strd_dev = np.sqrt(np.sum(ensemble_tmp) / (LENGTH - 1))\n\nprint (\"Ensemble mean: {}\".format(ensemble_mean))\nprint (\"Ensemble standard deviation: {}\".format(ensemble_strd_dev))\n\n# Logistic map functions\nfig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)\nax1.plot(X[0])\nax1.axhline(means[0], label='time-average', color='r', linestyle='-')\nax1.set_title(\"l = {}\".format(l[0]))\nax2.plot(X[1])\nax2.set_title(\"l = {}\".format(l[1]))\nax2.axhline(means[1], label='time-average', color='r', linestyle='-')\nax3.plot(X[2])\nax3.set_title(\"l = {}\".format(l[2]))\nax3.axhline(means[2], label='time-average', color='r', linestyle='-')\nax4.plot(X[3])\nax4.set_title(\"l = {}\".format(l[3]))\nax4.axhline(means[3], label='time-average', color='r', linestyle='-')\nplt.show()\n\n\n\n# Ensemble\n# Time-average mean\nplt.axhline(ensemble_mean, label='time-average', color='r', linestyle='-')\n# Ensemble average\nplt.plot(ensemble, color='b', label='Ensemble')\nplt.legend()\nplt.show()\n\nflatX = X.flatten()\nn, bins, patches = plt.hist(flatX, 25, facecolor='b')\nplt.grid(True)\nplt.show()", "meta": {"hexsha": "3303e657e4258e883a597adf886bf58ad0cfc6a0", "size": 2489, "ext": "py", "lang": "Python", "max_stars_repo_path": "logistic_map.py", "max_stars_repo_name": "jonarani/random_walk", "max_stars_repo_head_hexsha": "316556bac00d9ce0cf1034a3eea57ca8ead1c211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "logistic_map.py", "max_issues_repo_name": "jonarani/random_walk", "max_issues_repo_head_hexsha": "316556bac00d9ce0cf1034a3eea57ca8ead1c211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logistic_map.py", "max_forks_repo_name": "jonarani/random_walk", "max_forks_repo_head_hexsha": "316556bac00d9ce0cf1034a3eea57ca8ead1c211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6597938144, "max_line_length": 74, "alphanum_fraction": 0.6657292085, "include": true, "reason": "import numpy", "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541528387691, "lm_q2_score": 0.9086179031191509, "lm_q1q2_score": 0.8556038218158029}}
{"text": "# Databricks notebook source\n# MAGIC %md\n# MAGIC \n# MAGIC # [SDS-2.2, Scalable Data Science](https://lamastex.github.io/scalable-data-science/sds/2/2/)\n# MAGIC \n# MAGIC This is used in a non-profit educational setting with kind permission of [Adam Breindel](https://www.linkedin.com/in/adbreind).\n# MAGIC This is not licensed by Adam for use in a for-profit setting. Please contact Adam directly at `adbreind@gmail.com` to request or report such use cases or abuses. \n# MAGIC A few minor modifications and additional mathematical statistical pointers have been added by Raazesh Sainudiin when teaching PhD students in Uppsala University.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Archived YouTube video of this live unedited lab-lecture:\n# MAGIC \n# MAGIC [![Archived YouTube video of this live unedited lab-lecture](http://img.youtube.com/vi/eJBR6sm4p2g/0.jpg)](https://www.youtube.com/embed/eJBR6sm4p2g?start=0&end=2654&autoplay=1) [![Archived YouTube video of this live unedited lab-lecture](http://img.youtube.com/vi/TDisCsfbmYs/0.jpg)](https://www.youtube.com/embed/TDisCsfbmYs?start=0&end=2907&autoplay=1) [![Archived YouTube video of this live unedited lab-lecture](http://img.youtube.com/vi/-LLL3MUl9ps/0.jpg)](https://www.youtube.com/embed/-LLL3MUl9ps?start=0&end=2467&autoplay=1)\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC # Artificial Neural Network - Perceptron\n# MAGIC \n# MAGIC The field of artificial neural networks started out with an electromechanical binary unit called a perceptron.\n# MAGIC \n# MAGIC The perceptron took a weighted set of input signals and chose an ouput state (on/off or high/low) based on a threshold.\n# MAGIC \n# MAGIC <img src=\"http://i.imgur.com/c4pBaaU.jpg\">\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC (raaz) Thus, the perceptron is defined by:\n# MAGIC \n# MAGIC $$\n# MAGIC f(1, x\\_1,x\\_2,\\ldots , x\\_n \\, ; \\, w\\_0,w\\_1,w\\_2,\\ldots , w\\_n) =\n# MAGIC \\begin{cases}\n# MAGIC 1 & \\text{if} \\quad \\sum\\_{i=0}^n w\\_i x\\_i > 0 \\\\\\\\\n# MAGIC 0 & \\text{otherwise}\n# MAGIC \\end{cases}\n# MAGIC $$\n# MAGIC and implementable with the following arithmetical and logical unit (ALU) operations in a machine:\n# MAGIC \n# MAGIC  * n inputs from one \\\\(n\\\\)-dimensional data point: \\\\( x_1,x_2,\\ldots x_n \\, \\in \\, \\mathbb{R}^n\\\\)\n# MAGIC  * arithmetic operations\n# MAGIC    * n+1 multiplications\n# MAGIC    * n additions\n# MAGIC * boolean operations\n# MAGIC   * one if-then on an inequality\n# MAGIC * one output \\\\(o \\in \\\\{0,1\\\\}\\\\), i.e., \\\\(o\\\\) belongs to the set containing \\\\(0\\\\) and \\\\(1\\\\)\n# MAGIC * n+1 parameters of interest\n# MAGIC \n# MAGIC This is just a hyperplane given by a dot product of \\\\(n+1\\\\) known inputs and \\\\(n+1\\\\) unknown parameters that can be estimated. This hyperplane can be used to define a hyperplane that partitions \\\\(\\mathbb{R}^{n+1}\\\\), the real Euclidean space, into two parts labelled by the outputs \\\\(0\\\\) and \\\\(1\\\\).\n# MAGIC \n# MAGIC The problem of finding estimates of the parameters, \\\\( (\\hat{w}\\_0,\\hat{w}\\_1,\\hat{w}\\_2,\\ldots \\hat{w}\\_n) \\in \\mathbb{R}^{(n+1)} \\\\), in some statistically meaningful manner for a predicting task by using the training data given by, say \\\\(k\\\\) *labelled points*, where you know both the input and output:\n# MAGIC $$\n# MAGIC  \\left( ( \\, 1, x\\_1^{(1)},x\\_2^{(1)}, \\ldots x\\_n^{(1)}), (o^{(1)}) \\, ), \\, ( \\, 1, x\\_1^{(2)},x\\_2^{(2)}, \\ldots x\\_n^{(2)}), (o^{(2)}) \\, ), \\, \\ldots \\, , ( \\, 1, x\\_1^{(k)},x\\_2^{(k)}, \\ldots x\\_n^{(k)}), (o^{(k)}) \\, ) \\right) \\, \\in \\, (\\mathbb{R}^{n+1} \\times \\\\{ 0,1 \\\\} )^k\n# MAGIC $$\n# MAGIC is the machine learning problem here. \n# MAGIC \n# MAGIC Succinctly, we are after a random mapping, denoted below by \\\\( \\mapsto\\_{\\rightsquigarrow} \\\\), called the *estimator*:\n# MAGIC $$\n# MAGIC (\\mathbb{R}^{n+1} \\times \\\\{0,1\\\\})^k \\mapsto_{\\rightsquigarrow} \\, \\left( \\, \\mathtt{model}( (1,x\\_1,x\\_2,\\ldots,x\\_n) \\,;\\, (\\hat{w}\\_0,\\hat{w}\\_1,\\hat{w}\\_2,\\ldots \\hat{w}\\_n)) : \\mathbb{R}^{n+1} \\to \\\\{0,1\\\\} \\,  \\right)\n# MAGIC $$\n# MAGIC which takes *random* labelled dataset (to understand random here think of two scientists doing independent experiments to get their own training datasets) of size \\\\(k\\\\) and returns a *model*. These mathematical notions correspond exactly to the `estimator` and `model` (which is a `transformer`) in the language of Apache Spark's Machine Learning Pipleines we have seen before.\n# MAGIC \n# MAGIC We can use this `transformer` for *prediction* of *unlabelled data* where we only observe the input and what to know the output under some reasonable assumptions.  \n# MAGIC \n# MAGIC Of course we want to be able to generalize so we don't overfit to the training data using some *empirical risk minisation rule* such as cross-validation. Again, we have seen these in Apache Spark for other ML methods like linear regression and decision trees.\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC If the output isn't right, we can adjust the weights, threshold, or bias (\\\\(x_0\\\\) above)\n# MAGIC \n# MAGIC The model was inspired by discoveries about the neurons of animals, so hopes were quite high that it could lead to a sophisticated machine. This model can be extended by adding multiple neurons in parallel. And we can use linear output instead of a threshold if we like for the output.\n# MAGIC \n# MAGIC If we were to do so, the output would look like \\\\({x \\cdot w} + w_0\\\\) (this is where the vector multiplication and, eventually, matrix multiplication, comes in)\n# MAGIC \n# MAGIC When we look at the math this way, we see that despite this being an interesting model, it's really just a fancy linear calculation.\n# MAGIC \n# MAGIC And, in fact, the proof that this model -- being linear -- could not solve any problems whose solution was nonlinear ... led to the first of several \"AI / neural net winters\" when the excitement was quickly replaced by disappointment, and most research was abandoned.\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC ### Linear Perceptron\n# MAGIC \n# MAGIC We'll get to the non-linear part, but the linear perceptron model is a great way to warm up and bridge the gap from traditional linear regression to the neural-net flavor.\n# MAGIC \n# MAGIC Let's look at a problem -- the diamonds dataset from R -- and analyze it using two traditional methods in Scikit-Learn, and then we'll start attacking it with neural networks!\n\n# COMMAND ----------\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.metrics import mean_squared_error\n\ninput_file = \"/dbfs/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv\"\n\ndf = pd.read_csv(input_file, header = 0)\n\n# COMMAND ----------\n\nimport IPython.display as disp\npd.set_option('display.width', 200)\ndisp.display(df[:10])\n\n# COMMAND ----------\n\ndf2 = df.drop(df.columns[0], axis=1)\n\ndisp.display(df2[:3])\n\n# COMMAND ----------\n\ndf3 = pd.get_dummies(df2) # this gives a one-hot encoding of categorial variables\n\ndisp.display(df3[range(7,18)][:3])\n\n# COMMAND ----------\n\n# pre-process to get y\ny = df3.iloc[:,3:4].as_matrix().flatten()\ny.flatten()\n\n# preprocess and reshape X as a matrix\nX = df3.drop(df3.columns[3], axis=1).as_matrix()\nnp.shape(X)\n\n# break the dataset into training and test set with a 75% and 25% split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)\n\n# Define a decisoin tree model with max depth 10\ndt = DecisionTreeRegressor(random_state=0, max_depth=10)\n\n# fit the decision tree to the training data to get a fitted model\nmodel = dt.fit(X_train, y_train)\n\n# predict the features or X values of the test data using the fitted model\ny_pred = model.predict(X_test)\n\n# print the MSE performance measure of the fit by comparing the predicted versus the observed values of y \nprint(\"RMSE %f\" % np.sqrt(mean_squared_error(y_test, y_pred)) )\n\n# COMMAND ----------\n\nfrom sklearn import linear_model\n\n# Do the same with linear regression and not a worse MSE\nlr = linear_model.LinearRegression()\nlinear_model = lr.fit(X_train, y_train)\n\ny_pred = linear_model.predict(X_test)\nprint(\"RMSE %f\" % np.sqrt(mean_squared_error(y_test, y_pred)) )\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC Now that we have a baseline, let's build a neural network -- linear at first -- and go further.\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC ## Neural Network with Keras\n# MAGIC \n# MAGIC ### Keras is a High-Level API for Neural Networks and Deep Learning\n# MAGIC \n# MAGIC #### \"*Being able to go from idea to result with the least possible delay is key to doing good research.*\"\n# MAGIC Maintained by Francois Chollet at Google, it provides\n# MAGIC \n# MAGIC * High level APIs\n# MAGIC * Pluggable backends for Theano, TensorFlow, CNTK, MXNet\n# MAGIC * CPU/GPU support\n# MAGIC * The now-officially-endorsed high-level wrapper for TensorFlow; a version ships in TF\n# MAGIC * Model persistence and other niceties\n# MAGIC * JavaScript, iOS, etc. deployment\n# MAGIC * Interop with further frameworks, like DeepLearning4J, Spark DL Pipelines ...\n# MAGIC \n# MAGIC Well, with all this, why would you ever *not* use Keras? \n# MAGIC \n# MAGIC As an API/Facade, Keras doesn't directly expose all of the internals you might need for something custom and low-level ... so you might need to implement at a lower level first, and then perhaps wrap it to make it easily usable in Keras.\n# MAGIC \n# MAGIC Mr. Chollet compiles stats (roughly quarterly) on \"[t]he state of the deep learning landscape: GitHub activity of major libraries over the past quarter (tickets, forks, and contributors).\"\n# MAGIC \n# MAGIC (October 2017: https://twitter.com/fchollet/status/915366704401719296; https://twitter.com/fchollet/status/915626952408436736)\n# MAGIC <table><tr><td>__GitHub__<br>\n# MAGIC <img src=\"https://i.imgur.com/Dru8N9K.jpg\" width=600>\n# MAGIC   </td><td>__Research__<br>\n# MAGIC   <img src=\"https://i.imgur.com/i23TAwf.png\" width=600></td></tr></table>\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC ### We'll build a \"Dense Feed-Forward Shallow\" Network:\n# MAGIC (the number of units in the following diagram does not exactly match ours)\n# MAGIC <img src=\"https://i.imgur.com/84fxFKa.png\">\n# MAGIC \n# MAGIC Grab a Keras API cheat sheet from https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Keras_Cheat_Sheet_Python.pdf\n\n# COMMAND ----------\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\n# we are going to add layers sequentially one after the other (feed-forward) to our neural network model\nmodel = Sequential()\n\n# the first layer has 30 nodes (or neurons) with input dimension 26 for our diamonds data\n# we will use Nomal or Guassian kernel to initialise the weights we want to estimate\n# our activation function is linear (to mimic linear regression)\nmodel.add(Dense(30, input_dim=26, kernel_initializer='normal', activation='linear'))\n# the next layer is for the response y and has only one node\nmodel.add(Dense(1, kernel_initializer='normal', activation='linear'))\n# compile the model with other specifications for loss and type of gradient descent optimisation routine\nmodel.compile(loss='mean_squared_error', optimizer='adam', metrics=['mean_squared_error'])\n# fit the model to the training data using stochastic gradient descent with a batch-size of 200 and 10% of data held out for validation\nhistory = model.fit(X_train, y_train, epochs=10, batch_size=200, validation_split=0.1)\n\nscores = model.evaluate(X_test, y_test)\nprint()\nprint(\"test set RMSE: %f\" % np.sqrt(scores[1]))\n\n# COMMAND ----------\n\nmodel.summary() # do you understand why the number of parameters in layer 1 is 810? 26*30+30=810\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC Notes:\n# MAGIC \n# MAGIC * We didn't have to explicitly write the \"input\" layer, courtesy of the Keras API. We just said `input_dim=26` on the first (and only) hidden layer.\n# MAGIC * `kernel_initializer='normal'` is a simple (though not always optimal) *weight initialization*\n# MAGIC * Epoch: 1 pass over all of the training data\n# MAGIC * Batch: Records processes together in a single training pass\n# MAGIC \n# MAGIC How is our RMSE vs. the std dev of the response?\n\n# COMMAND ----------\n\ny.std()\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC Let's look at the error ...\n\n# COMMAND ----------\n\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\n\ndisplay(fig)\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC Let's set up a \"long-running\" training. This will take a few minutes to converge to the same performance we got more or less instantly with our sklearn linear regression :)\n# MAGIC \n# MAGIC While it's running, we can talk about the training.\n\n# COMMAND ----------\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nimport numpy as np\nimport pandas as pd\n\ninput_file = \"/dbfs/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv\"\n\ndf = pd.read_csv(input_file, header = 0)\ndf.drop(df.columns[0], axis=1, inplace=True)\ndf = pd.get_dummies(df, prefix=['cut_', 'color_', 'clarity_'])\n\ny = df.iloc[:,3:4].as_matrix().flatten()\ny.flatten()\n\nX = df.drop(df.columns[3], axis=1).as_matrix()\nnp.shape(X)\n\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)\n\nmodel = Sequential()\nmodel.add(Dense(30, input_dim=26, kernel_initializer='normal', activation='linear'))\nmodel.add(Dense(1, kernel_initializer='normal', activation='linear'))\n\nmodel.compile(loss='mean_squared_error', optimizer='adam', metrics=['mean_squared_error'])\nhistory = model.fit(X_train, y_train, epochs=250, batch_size=100, validation_split=0.1, verbose=2)\n\nscores = model.evaluate(X_test, y_test)\nprint(\"\\nroot %s: %f\" % (model.metrics_names[1], np.sqrt(scores[1])))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC After all this hard work we are closer to the MSE we got from linear regression, but purely using a shallow feed-forward neural network.\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC ### Training: Gradient Descent\n# MAGIC \n# MAGIC A family of numeric optimization techniques, where we solve a problem with the following pattern:\n# MAGIC \n# MAGIC 1. Describe the error in the model output: this is usually some difference between the the true values and the model's predicted values, as a function of the model parameters (weights)\n# MAGIC \n# MAGIC 2. Compute the gradient, or directional derivative, of the error -- the \"slope toward lower error\"\n# MAGIC \n# MAGIC 4. Adjust the parameters of the model variables in the indicated direction\n# MAGIC \n# MAGIC 5. Repeat\n# MAGIC \n# MAGIC <img src=\"https://i.imgur.com/HOYViqN.png\" width=500>\n# MAGIC \n# MAGIC #### Some ideas to help build your intuition\n# MAGIC \n# MAGIC * What happens if the variables (imagine just 2, to keep the mental picture simple) are on wildly different scales ... like one ranges from -1 to 1 while another from -1e6 to +1e6?\n# MAGIC \n# MAGIC * What if some of the variables are correlated? I.e., a change in one corresponds to, say, a linear change in another?\n# MAGIC \n# MAGIC * Other things being equal, an approximate solution with fewer variables is easier to work with than one with more -- how could we get rid of some less valuable parameters? (e.g., L1 penalty)\n# MAGIC \n# MAGIC * How do we know how far to \"adjust\" our parameters with each step?\n# MAGIC \n# MAGIC <img src=\"http://i.imgur.com/AvM2TN6.png\" width=600>\n# MAGIC \n# MAGIC What if we have billions of data points? Does it makes sense to use all of them for each update? Is there a shortcut?\n# MAGIC \n# MAGIC Yes: *Stochastic Gradient Descent*\n# MAGIC \n# MAGIC But SGD has some shortcomings, so we typically use a \"smarter\" version of SGD, which has rules for adjusting the learning rate and even direction in order to avoid common problems.\n# MAGIC \n# MAGIC What about that \"Adam\" optimizer? Adam is short for \"adaptive moment\" and is a variant of SGD that includes momentum calculations that change over time. For more detail on optimizers, see the chapter \"Training Deep Neural Nets\" in Aurélien Géron's book: *Hands-On Machine Learning with Scikit-Learn and TensorFlow* (http://shop.oreilly.com/product/0636920052289.do)\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC ### Training: Backpropagation\n# MAGIC \n# MAGIC With a simple, flat model, we could use SGD or a related algorithm to derive the weights, since the error depends directly on those weights.\n# MAGIC \n# MAGIC With a deeper network, we have a couple of challenges:\n# MAGIC \n# MAGIC * The error is computed from the final layer, so the gradient of the error doesn't tell us immediately about problems in other-layer weights\n# MAGIC * Our tiny diamonds model has almost a thousand weights. Bigger models can easily have millions of weights. Each of those weights may need to move a little at a time, and we have to watch out for underflow or undersignificance situations.\n# MAGIC \n# MAGIC __The insight is to iteratively calculate errors, one layer at a time, starting at the output. This is called backpropagation. It is neither magical nor surprising. The challenge is just doing it fast and not losing information.__\n# MAGIC \n# MAGIC <img src=\"http://i.imgur.com/bjlYwjM.jpg\" width=800>\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC ## Ok so we've come up with a very slow way to perform a linear regression. \n# MAGIC \n# MAGIC ### *Welcome to Neural Networks in the 1960s!*\n# MAGIC \n# MAGIC ---\n# MAGIC \n# MAGIC ### Watch closely now because this is where the magic happens...\n# MAGIC \n# MAGIC <img src=\"https://media.giphy.com/media/Hw5LkPYy9yfVS/giphy.gif\">\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC # Non-Linearity + Perceptron = Universal Approximation\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC ### Where does the non-linearity fit in?\n# MAGIC \n# MAGIC * We start with the inputs to a perceptron -- these could be from source data, for example.\n# MAGIC * We multiply each input by its respective weight, which gets us the \\\\(x \\cdot w\\\\)\n# MAGIC * Then add the \"bias\" -- an extra learnable parameter, to get \\\\({x \\cdot w} + b\\\\)\n# MAGIC     * This value (so far) is sometimes called the \"pre-activation\"\n# MAGIC * Now, apply a non-linear \"activation function\" to this value, such as the logistic sigmoid\n# MAGIC \n# MAGIC <img src=\"https://i.imgur.com/MhokAmo.gif\">\n# MAGIC \n# MAGIC ### Now the network can \"learn\" non-linear functions\n# MAGIC \n# MAGIC To gain some intuition, consider that where the sigmoid is close to 1, we can think of that neuron as being \"on\" or activated, giving a specific output. When close to zero, it is \"off.\" \n# MAGIC \n# MAGIC So each neuron is a bit like a switch. If we have enough of them, we can theoretically express arbitrarily many different signals. \n# MAGIC \n# MAGIC In some ways this is like the original artificial neuron, with the thresholding output -- the main difference is that the sigmoid gives us a smooth (arbitrarily differentiable) output that we can optimize over using gradient descent to learn the weights. \n# MAGIC \n# MAGIC ### Where does the signal \"go\" from these neurons?\n# MAGIC \n# MAGIC * In a regression problem, like the diamonds dataset, the activations from the hidden layer can feed into a single output neuron, with a simple linear activation representing the final output of the calculation.\n# MAGIC \n# MAGIC * Frequently we want a classification output instead -- e.g., with MNIST digits, where we need to choose from 10 classes. In that case, we can feed the outputs from these hidden neurons forward into a final layer of 10 neurons, and compare those final neurons' activation levels.\n# MAGIC \n# MAGIC Ok, before we talk any more theory, let's run it and see if we can do better on our diamonds dataset adding this \"sigmoid activation.\"\n# MAGIC \n# MAGIC While that's running, let's look at the code:\n\n# COMMAND ----------\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nimport numpy as np\nimport pandas as pd\n\ninput_file = \"/dbfs/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv\"\n\ndf = pd.read_csv(input_file, header = 0)\ndf.drop(df.columns[0], axis=1, inplace=True)\ndf = pd.get_dummies(df, prefix=['cut_', 'color_', 'clarity_'])\n\ny = df.iloc[:,3:4].as_matrix().flatten()\ny.flatten()\n\nX = df.drop(df.columns[3], axis=1).as_matrix()\nnp.shape(X)\n\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)\n\nmodel = Sequential()\nmodel.add(Dense(30, input_dim=26, kernel_initializer='normal', activation='sigmoid')) # <- change to nonlinear activation\nmodel.add(Dense(1, kernel_initializer='normal', activation='linear')) # <- activation is linear in output layer for this regression\n\nmodel.compile(loss='mean_squared_error', optimizer='adam', metrics=['mean_squared_error'])\nhistory = model.fit(X_train, y_train, epochs=2000, batch_size=100, validation_split=0.1, verbose=2)\n\nscores = model.evaluate(X_test, y_test)\nprint(\"\\nroot %s: %f\" % (model.metrics_names[1], np.sqrt(scores[1])))\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC ##### What is different here?\n# MAGIC \n# MAGIC * We've changed the activation in the hidden layer to \"sigmoid\" per our discussion.\n# MAGIC * Next, notice that we're running 2000 training epochs!\n# MAGIC \n# MAGIC Even so, it takes a looooong time to converge. If you experiment a lot, you'll find that ... it still takes a long time to converge. Around the early part of the most recent deep learning renaissance, researchers started experimenting with other non-linearities.\n# MAGIC \n# MAGIC (Remember, we're talking about non-linear activations in the hidden layer. The output here is still using \"linear\" rather than \"softmax\" because we're performing regression, not classification.)\n# MAGIC \n# MAGIC In theory, any non-linearity should allow learning, and maybe we can use one that \"works better\"\n# MAGIC \n# MAGIC By \"works better\" we mean\n# MAGIC \n# MAGIC * Simpler gradient - faster to compute\n# MAGIC * Less prone to \"saturation\" -- where the neuron ends up way off in the 0 or 1 territory of the sigmoid and can't easily learn anything\n# MAGIC * Keeps gradients \"big\" -- avoiding the large, flat, near-zero gradient areas of the sigmoid\n# MAGIC \n# MAGIC Turns out that a big breakthrough and popular solution is a very simple hack:\n# MAGIC \n# MAGIC ### Rectified Linear Unit (ReLU)\n# MAGIC \n# MAGIC <img src=\"http://i.imgur.com/oAYh9DN.png\" width=1000>\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC ### Go change your hidden-layer activation from 'sigmoid' to 'relu'\n# MAGIC \n# MAGIC Start your script and watch the error for a bit!\n\n# COMMAND ----------\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nimport numpy as np\nimport pandas as pd\n\ninput_file = \"/dbfs/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv\"\n\ndf = pd.read_csv(input_file, header = 0)\ndf.drop(df.columns[0], axis=1, inplace=True)\ndf = pd.get_dummies(df, prefix=['cut_', 'color_', 'clarity_'])\n\ny = df.iloc[:,3:4].as_matrix().flatten()\ny.flatten()\n\nX = df.drop(df.columns[3], axis=1).as_matrix()\nnp.shape(X)\n\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)\n\nmodel = Sequential()\nmodel.add(Dense(30, input_dim=26, kernel_initializer='normal', activation='relu')) # <--- CHANGE IS HERE\nmodel.add(Dense(1, kernel_initializer='normal', activation='linear'))\n\nmodel.compile(loss='mean_squared_error', optimizer='adam', metrics=['mean_squared_error'])\nhistory = model.fit(X_train, y_train, epochs=2000, batch_size=100, validation_split=0.1, verbose=2)\n\nscores = model.evaluate(X_test, y_test)\nprint(\"\\nroot %s: %f\" % (model.metrics_names[1], np.sqrt(scores[1])))\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC Would you look at that?! \n# MAGIC \n# MAGIC * We break $1000 RMSE around epoch 112\n# MAGIC * $900 around epoch 220\n# MAGIC * $800 around epoch 450\n# MAGIC * By around epoch 2000, my RMSE is < $600\n# MAGIC \n# MAGIC ...\n# MAGIC \n# MAGIC \n# MAGIC __Same theory; different activation function. Huge difference__\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC # Multilayer Networks\n# MAGIC \n# MAGIC If a single-layer perceptron network learns the importance of different combinations of features in the data...\n# MAGIC \n# MAGIC What would another network learn if it had a second (hidden) layer of neurons?\n# MAGIC \n# MAGIC It depends on how we train the network. We'll talk in the next section about how this training works, but the general idea is that we still work backward from the error gradient. \n# MAGIC \n# MAGIC That is, the last layer learns from error in the output; the second-to-last layer learns from error transmitted through that last layer, etc. It's a touch hand-wavy for now, but we'll make it more concrete later.\n# MAGIC \n# MAGIC Given this approach, we can say that:\n# MAGIC \n# MAGIC 1. The second (hidden) layer is learning features composed of activations in the first (hidden) layer\n# MAGIC 2. The first (hidden) layer is learning feature weights that enable the second layer to perform best \n# MAGIC     * Why? Earlier, the first hidden layer just learned feature weights because that's how it was judged\n# MAGIC     * Now, the first hidden layer is judged on the error in the second layer, so it learns to contribute to that second layer\n# MAGIC 3. The second layer is learning new features that aren't explicit in the data, and is teaching the first layer to supply it with the necessary information to compose these new features\n# MAGIC \n# MAGIC ### So instead of just feature weighting and combining, we have new feature learning!\n# MAGIC \n# MAGIC This concept is the foundation of the \"Deep Feed-Forward Network\"\n# MAGIC \n# MAGIC <img src=\"http://i.imgur.com/fHGrs4X.png\">\n# MAGIC \n# MAGIC ---\n# MAGIC \n# MAGIC ### Let's try it!\n# MAGIC \n# MAGIC __Add a layer to your Keras network, perhaps another 20 neurons, and see how the training goes.__\n# MAGIC \n# MAGIC if you get stuck, there is a solution in the Keras-DFFN notebook\n# MAGIC \n# MAGIC ---\n# MAGIC \n# MAGIC I'm getting RMSE < $1000 by epoch 35 or so\n# MAGIC \n# MAGIC < $800 by epoch 90\n# MAGIC \n# MAGIC In this configuration, mine makes progress to around 700 epochs or so and then stalls with RMSE around $560\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC ### Our network has \"gone meta\"\n# MAGIC \n# MAGIC It's now able to exceed where a simple decision tree can go, because it can create new features and then split on those\n# MAGIC \n# MAGIC ## Congrats! You have built your first deep-learning model!\n# MAGIC \n# MAGIC So does that mean we can just keep adding more layers and solve anything?\n# MAGIC \n# MAGIC Well, theoretically maybe ... try reconfiguring your network, watch the training, and see what happens.\n# MAGIC \n# MAGIC <img src=\"http://i.imgur.com/BumsXgL.jpg\" width=500>", "meta": {"hexsha": "b8d2a813a735da4f81c4c9dac43935748da67eb5", "size": 26913, "ext": "py", "lang": "Python", "max_stars_repo_path": "db/2/2/051_DLbyABr_02-Neural-Networks.py", "max_stars_repo_name": "chrislangst/scalable-data-science", "max_stars_repo_head_hexsha": "c7beee15c7dd14d27353c4864d927c1b76cd2fa9", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2017-07-25T06:48:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:23:36.000Z", "max_issues_repo_path": "db/2/2/051_DLbyABr_02-Neural-Networks.py", "max_issues_repo_name": "chrislangst/scalable-data-science", "max_issues_repo_head_hexsha": "c7beee15c7dd14d27353c4864d927c1b76cd2fa9", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2017-08-17T13:45:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T09:06:53.000Z", "max_forks_repo_path": "db/2/2/051_DLbyABr_02-Neural-Networks.py", "max_forks_repo_name": "chrislangst/scalable-data-science", "max_forks_repo_head_hexsha": "c7beee15c7dd14d27353c4864d927c1b76cd2fa9", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2017-08-18T17:04:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T14:30:51.000Z", "avg_line_length": 46.4017241379, "max_line_length": 541, "alphanum_fraction": 0.7252628841, "include": true, "reason": "import numpy", "num_tokens": 6945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.9086178913651384, "lm_q1q2_score": 0.8556038122353478}}
{"text": "import numpy as np\na = np.array([10,20,30,40])\nb = np.arange(4)\n\nprint(a,b)\nc = a+b\nprint(c)\n\n#b的平方 \nd = b ** 2\nprint(d)\n\ne = 10 * np.sin(a)\nprint(e)\n\nprint(b)\nprint(b<3)\n\naa = np.array([[1,1],\n               [0,1]])\nbb = np.arange(4).reshape(2,2)\nc = aa * bb\nc_dot = np.dot(aa,bb)\n# another write method\nc_dot_2 = aa.dot(bb)\nprint(aa)\nprint(bb)\nprint(c)\nprint(c_dot)\nprint(c_dot_2)\n\nf = np.random.random((2,4))\nprint(f)\nprint(np.sum(f,axis=1))\nprint(np.min(f,axis=0))\nprint(np.max(f,axis=1))\n\n\n\n", "meta": {"hexsha": "84c1e1f53d24cf4f628f7cacdaa13a44bbc79909", "size": 496, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_basic_operator.py", "max_stars_repo_name": "sunweiconfidence/numpydemo", "max_stars_repo_head_hexsha": "86dbf7d4cfb572e2e68fd6fb44a1ddbdc63cd847", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy_basic_operator.py", "max_issues_repo_name": "sunweiconfidence/numpydemo", "max_issues_repo_head_hexsha": "86dbf7d4cfb572e2e68fd6fb44a1ddbdc63cd847", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy_basic_operator.py", "max_forks_repo_name": "sunweiconfidence/numpydemo", "max_forks_repo_head_hexsha": "86dbf7d4cfb572e2e68fd6fb44a1ddbdc63cd847", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.4, "max_line_length": 30, "alphanum_fraction": 0.5947580645, "include": true, "reason": "import numpy", "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.8887587890727754, "lm_q1q2_score": 0.8555841917805024}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n#######################################\n#setting up \nprint (\"Lets getstarted with non linear regression\")\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.svm import SVR\nfrom sklearn.linear_model import LinearRegression\n\n\n#train data/model input\nx = np.array([[64], [128], [256],[512]])\ny = np.array([[38440.0], [158760.0],  [645160.0], [2601000.0]])\nyflat = np.array([38440.0, 158760.0,  645160.0, 2601000.0])\n\nx_log = np.array([[math.log(d,2)] for d in x])\n\n#here, we are giving an estimated model\nx_new = np.hstack([ x_log, x, x**2, x**3]) # if you take x**4 it might overfit\n\n\n# # Building Models\n# Lets build some sample models.\n\n\n#################################### building models\n#model 1 -- scikit linear regression\nmodel = LinearRegression()\nmodel.fit(x_new,y)\n\n#to hecking model\n#x.shape\n#x_new.shape\n#model.coef_\n#model.intercept_\n\n#test data \nxt = np.array([[256], [512], [1024], [2048],[4096], \n               [8*1024],[16*1024], [1024*32]\n              ])\nxt_log = np.array([[math.log(d,2)] for d in xt])\nx_target = np.hstack([xt_log, xt, xt**2, xt**3])\ny_pred = model.predict(x_target) #LinearRegression()--sklearn.linear_model\n\n\n#Model 2 SVR/POLY -- http://scikit-learn.org/stable/auto_examples/svm/plot_svm_regression.html\nsvr_poly = SVR(kernel='poly', C=1e3, degree=2, gamma='scale')\nmodel_poly = svr_poly.fit(x, yflat)\nxtest_large = np.array([[4096], [8192], [16384] ])\ny_poly = model_poly.predict(xtest_large)\n\n\n#Model 3 -- SVR LINEAR\n#svr_lin = SVR(kernel='linear', C=1e3)\n\n#Model 4, SVR RBF kernel\n#svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)\n#model_rbf  = svr_rbf.fit(x, yflat)\n#xtest2 = np.array([[512], [1024], [2048], [4096], [8192] ])\n#y_rbf = model_rbf.predict(xtest2)\n#plt.plot(xtest2, y_rbf, color='navy', lw=lw, label='RBF model')\n\n\n# ## Lets Plot our results and the source data\n# We can write the results to a file or plot using matplotlib\n\n\n\n############################ plotting\n\n#markers: ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']:#default o\n#linestyle: '-', '--', '-.', ':', '', (offset, on-off-seq), ...}\n\nlw, msize = 2, 10\nplt.xlabel('Problem Size')\nplt.ylabel('Kernel Iterations')\nplt.title('Iteration Estimation SVR vs. Linear')\n\n#our plots\nplt.scatter(x,y,marker=\"o\", label=\"Data\",\n          edgecolor='black', facecolor='none', s=50.0)\nplt.plot(xt,y_pred,'blue', label=\"LinearRegression\", marker=\"+\", linestyle=\"-.\", ms=msize)\nplt.plot(xtest_large, y_poly, color='black', lw=lw, linestyle=\"--\",label='Polynomial/Scaling SVR', marker=\"x\", ms=msize)\n\nplt.legend() #oldest last\nplt.show()\n", "meta": {"hexsha": "19117a4ee3ca5bb3501e6c8500407091e47fcc9e", "size": 2613, "ext": "py", "lang": "Python", "max_stars_repo_path": "regression-svr.py", "max_stars_repo_name": "summonersRift/obaida-machine-learning-models", "max_stars_repo_head_hexsha": "77d8f3232a20a9a302b345c1cec59d573ba2f85b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-10-01T17:41:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-23T17:50:13.000Z", "max_issues_repo_path": "regression-svr.py", "max_issues_repo_name": "summonersRift/obaida-machine-learning-models", "max_issues_repo_head_hexsha": "77d8f3232a20a9a302b345c1cec59d573ba2f85b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "regression-svr.py", "max_forks_repo_name": "summonersRift/obaida-machine-learning-models", "max_forks_repo_head_hexsha": "77d8f3232a20a9a302b345c1cec59d573ba2f85b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0333333333, "max_line_length": 120, "alphanum_fraction": 0.6333716035, "include": true, "reason": "import numpy", "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321452198369, "lm_q2_score": 0.8872045922259088, "lm_q1q2_score": 0.8555504207723501}}
{"text": "from statistics import mean\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom matplotlib import style\nimport random\n\n\nstyle.use(\"fivethirtyeight\")\n\n# xs = np.array([1, 2, 3, 4, 5, 6], dtype=np.float64)\n# ys = np.array([5, 4, 6, 5, 6, 7], dtype=np.float64)\n\n# hm = how many datapoints\n# variance = how variable do we want the dataset to be\n# step how far on average should we step up per point\ndef create_dataset(hm, variance, step=2, correlation=False):\n\tval = 1\n\tys = []\n\tfor i in range(hm):\n\t\ty = val + random.randrange(-variance, variance)\n\t\tys.append(y)\n\t\tif correlation and correlation == \"pos\":\n\t\t\tval += step\n\t\telif correlation and correlation == \"neg\":\n\t\t\tval -= step\n\n\txs = [i for i in range(len(ys))]\n\t\n\treturn np.array(xs, dtype=np.float64), np.array(ys, dtype=np.float64)\n\n\ndef best_fit_slope_and_intercept(xs, ys):\n\tm = ( ( ( mean(xs) * mean(ys) ) - mean(xs*ys) ) /\n\t\t( (mean(xs) ** 2) - mean(xs**2) ) \n\t\t)\n\tb = mean(ys) - m * mean(xs)\n\n\treturn m, b\n\n# Distance between the line in question and the points\ndef squared_error(ys_orig, ys_line):\n\n\treturn sum( (ys_line - ys_orig)**2 )\n\n\ndef coefficient_of_determination(ys_orig, ys_line):\n\ty_mean_line = [ mean(ys_orig) for y in ys_orig ]\n\tsquared_error_regr = squared_error(ys_orig, ys_line)\n\tsquared_error_y_mean = squared_error(ys_orig, y_mean_line)\n\n\treturn 1 - (squared_error_regr / squared_error_y_mean)\n\n# Lower the variance the better the accuracy\nxs, ys = create_dataset(40, 10, 2, correlation=\"pos\")\n\nm, b = best_fit_slope_and_intercept(xs, ys)\n\nregression_line = [(m*x) + b for x in xs]\n\n# Predict x = 8\npredict_x = 8\npredict_y = (m*predict_x) + b\n\n# plt.scatter(xs, ys)\n# plt.plot(xs, regression_line)\n# plt.show()\n\nr_squared = coefficient_of_determination(ys, regression_line)\n\n# Anything above 0 means the regression is more accurate.\n# squared error and cofficient of determination is a way to calculate \n# how good of a fit the best fit line is\nprint r_squared\n\n\n\n\n\n", "meta": {"hexsha": "d5748bb580c5f69d29b9923e99f9a33672d8019a", "size": 1949, "ext": "py", "lang": "Python", "max_stars_repo_path": "Sentdex/RegressionIntro/bestFit.py", "max_stars_repo_name": "paolo215/ML", "max_stars_repo_head_hexsha": "1106a6c297bf74197ac3ce46b60c60693376932f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sentdex/RegressionIntro/bestFit.py", "max_issues_repo_name": "paolo215/ML", "max_issues_repo_head_hexsha": "1106a6c297bf74197ac3ce46b60c60693376932f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sentdex/RegressionIntro/bestFit.py", "max_forks_repo_name": "paolo215/ML", "max_forks_repo_head_hexsha": "1106a6c297bf74197ac3ce46b60c60693376932f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3625, "max_line_length": 70, "alphanum_fraction": 0.7034376603, "include": true, "reason": "import numpy", "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214511730025, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.8555504141106632}}
{"text": "\nimport matplotlib.pyplot as plt\nfrom ipywidgets import interact, fixed\nimport numpy as np\nplt.style.use('seaborn-whitegrid')\nfrom mpl_toolkits.mplot3d import *\nfrom matplotlib import cm\nfrom scipy.optimize import minimize\n\n\n\n\nplt.style.use('bmh')\nplt.rcParams[\"figure.figsize\"] = [7,7]\nplt.rcParams[\"axes.spines.right\"] = False\nplt.rcParams[\"axes.spines.top\"] = False\nplt.rcParams[\"font.size\"] = 18\n\nALPHA = 1/2\n\n# Consumer choice\n\ndef budgetc(c0,p,I):\n    '''c1 as a function of c0 along budget line'''\n    return I - p*c0\n\ndef u(c, a=ALPHA):\n    '''Utility at c=(c[0], c[1])'''\n    return (c[0]**a)*(c[1]**(1-a))\n\ndef MU0(c, a=ALPHA):\n    '''MU of Cobb-Douglas'''\n    return  a*u(c,a)/c[0] \n\ndef MU1(c, a=ALPHA):\n    return  (1-a)*u(c,a)/c[1]\n\ndef indif(c0, ubar, a=ALPHA):\n    '''c1 as function of c0, implicitly defined by U(c0, c1) = ubar'''\n    return (ubar/(c0**a))**(1/(1-a))\n\ndef cd_demands(p,I,a =ALPHA):\n    '''Analytic solution for interior optimum'''\n    c0 = a * I/p\n    c1 = (1-a)*I\n    c = [c0,c1]\n    uopt = u(c,a)\n    return c, uopt\n\ndef consume_plot(p, I, a=ALPHA):\n    cmax = max(I, I/p)*1.1\n    c0 = np.linspace(0.1,cmax,num=100)\n    ce, uebar = cd_demands(p, I, a)\n    fig, ax = plt.subplots(figsize=(9,9))\n    ax.plot(c0, budgetc(c0, p, I), lw=2.5)\n    ax.fill_between(c0, budgetc(c0, p, I), alpha = 0.2)\n    ax.plot(c0, indif(c0, uebar, a), lw=2.5)\n    ax.vlines(ce[0],0,ce[1], linestyles=\"dashed\")\n    ax.hlines(ce[1],0,ce[0], linestyles=\"dashed\")\n    ax.plot(ce[0],ce[1],'ob')\n\n    ax.set_xlim(0, cmax)\n    ax.set_ylim(0, cmax)\n    ax.set_xlabel(r'$c_0$', fontsize=16)\n    ax.set_ylabel('$c_1$', fontsize=16)\n    ax.spines['right'].set_visible(False)\n    ax.spines['top'].set_visible(False)\n\ndef arb_plot(c0g, I, p):\n    cg = [c0g, I - c0g]\n    cmax = max(I, I/p)*1.1\n    c0 = np.linspace(0.1,cmax,num=100)\n    \n    '''Display characteristics of a guess along the constraint'''\n    fig, ax = plt.subplots(figsize=(9,9))\n    ax.plot(c0, budgetc(c0, p, I), lw=1)\n    ax.fill_between(c0, budgetc(c0, p, I), alpha = 0.2)\n    ax.plot(c0, indif(c0, u(cg)), lw=2.5)\n    ax.vlines(cg[0],0,cg[1], linestyles=\"dashed\")\n    ax.hlines(cg[1],0,cg[0], linestyles=\"dashed\")\n    ax.plot(cg[0],cg[1],'ob')\n    mu0pd, mu1pd = MU0(cg), MU1(cg)/p\n    if mu0pd > mu1pd:\n        inq = r'$>$'\n    elif mu0pd < mu1pd:\n        inq = r'$<$'\n    else:\n        inq =r'$=$'\n    ax.text(60, 120, r'$\\frac{MU_0}{p_0}$'+inq+r'$\\frac{MU_1}{p_1}$',fontsize=20)\n    utext = r'$({:5.1f}, {:5.1f}) \\ \\ U={:5.3f}$'.format(cg[0], cg[1], u(cg))\n    ax.text(60, 100, utext, fontsize=12)\n    ax.set_xlim(0, cmax)\n    ax.set_ylim(0, cmax)\n    ax.set_xlabel(r'$c_0$', fontsize=16)\n    ax.set_ylabel('$c_1$', fontsize=16)\n    ax.spines['right'].set_visible(False)\n    ax.spines['top'].set_visible(False)\n    ax.set_title('The No-Arbitrage argument')\n    plt.show()\n\n\n#\n\n\n## Ricardian model\n\ndef rppf(mplx, mply, lbar, show = True, title='Home'):\n    '''Plot a linear PPF diagram\n       show == False delays plt.show() to allow other elements to be plotted first'''\n    qy = mply*lbar - (mply/mplx) * QX\n    plt.plot(QX, qy, linewidth=2, label='PPF')\n    plt.axis([0,XMAX,0,YMAX])\n    plt.xlabel(NAMEX), plt.ylabel(NAMEY), plt.title(title)\n    plt.text(0.3*XMAX, 0.9*YMAX,\n             r'   $\\frac{MPL_Y}{MPL_X}=$'+'{:3.2f}'.format(mply/mplx))\n    if show: #use False for subplots\n        plt.show();\n\n## Linear Demand and Supply\n\n\ndef PD(Q, A, b):\n    return np.array(A - b * Q)\n\ndef PS(Q, F, c):\n    return np.array(F + c * Q)\n\ndef market(Q, A, b, F, c):\n    plt.figure(figsize=(7,7))\n    plt.plot(Q,PD(Q, A, b))\n    plt.plot(Q, PS(Q, F, c))\n    plt.show()\n    \n\nif __name__ == '__main__':\n    print('Running program tests')\n\n\n", "meta": {"hexsha": "f066e1a3bb37cd33e455e8277bbb1ebd3d8ee386", "size": 3710, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/intro/cd.py", "max_stars_repo_name": "jhconning/teaching", "max_stars_repo_head_hexsha": "d89d29465e97cbb3bcb99c82f20af68bb2361ace", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-02-03T06:04:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T07:14:28.000Z", "max_issues_repo_path": "notebooks/intro/cd.py", "max_issues_repo_name": "jhconning/teaching", "max_issues_repo_head_hexsha": "d89d29465e97cbb3bcb99c82f20af68bb2361ace", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-01T01:34:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-21T16:43:02.000Z", "max_forks_repo_path": "notebooks/intro/cd.py", "max_forks_repo_name": "jhconning/teaching", "max_forks_repo_head_hexsha": "d89d29465e97cbb3bcb99c82f20af68bb2361ace", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-09-02T15:19:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-18T16:31:37.000Z", "avg_line_length": 26.690647482, "max_line_length": 85, "alphanum_fraction": 0.5878706199, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.9184802390045688, "lm_q1q2_score": 0.8555299042762872}}
{"text": "import numpy as np\n\n\ndef get_pagerank(adj_matrix, DAMPING_FACTOR=0.15, EPSILON=0.001):\n    \"\"\"[summary]\n        pagerank values calculation\n\n    Arguments:\n        adj_matrix {[float[][]]} -- [[input Adjacent matrix lists like [[1, 0], [0, 1]]]\n\n    Keyword Arguments:\n        DAMPING_FACTOR {float} -- [factor of residual probability] (default: {0.15})\n        EPSILON {float} -- [factor of change comparision] (default: {0.01})\n\n    Returns:\n        [float[]] -- [pagerank values]\n    \"\"\"\n\n    # initialize\n    page_length = adj_matrix.shape[0]\n    pagerank = np.ones(page_length)\n    new_pagerank = np.ones(page_length)\n    escape = DAMPING_FACTOR / page_length\n\n    # normalize\n    normalize_adj_matrix = adj_matrix / np.linalg.norm(adj_matrix, ord=1, axis=1, keepdims=True)\n    normalize_adj_matrix = np.nan_to_num(normalize_adj_matrix)\n    is_coverage = False\n    while not is_coverage:\n        for node in range(page_length):\n            single_rank = escape + (1-DAMPING_FACTOR) * np.dot(normalize_adj_matrix.T, new_pagerank)[node]\n            new_pagerank[node] = single_rank\n\n        # normalize pagerank\n        normalize_pagerank = lambda x: x / sum(new_pagerank)\n        new_pagerank = normalize_pagerank(new_pagerank)\n\n        # check is coverage\n        diff = abs(sum(new_pagerank - pagerank))\n\n        if diff < EPSILON:\n            is_coverage = True\n        else:\n            pagerank = new_pagerank.copy()\n\n    return new_pagerank", "meta": {"hexsha": "c5f974dbbf4f749c12a16068559c8a7cb3fd7c45", "size": 1450, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pagerank.py", "max_stars_repo_name": "Sirius207/Link-Analysis", "max_stars_repo_head_hexsha": "22181c7f13de66a8e2dbc2485bd39e71ee54e2e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-12-30T02:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T11:40:26.000Z", "max_issues_repo_path": "src/pagerank.py", "max_issues_repo_name": "Sirius207/Link-Analysis", "max_issues_repo_head_hexsha": "22181c7f13de66a8e2dbc2485bd39e71ee54e2e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pagerank.py", "max_forks_repo_name": "Sirius207/Link-Analysis", "max_forks_repo_head_hexsha": "22181c7f13de66a8e2dbc2485bd39e71ee54e2e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-10T22:39:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-01T10:18:05.000Z", "avg_line_length": 31.5217391304, "max_line_length": 106, "alphanum_fraction": 0.6462068966, "include": true, "reason": "import numpy", "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517095103498, "lm_q2_score": 0.8902942363098473, "lm_q1q2_score": 0.8555297683491591}}
{"text": "\"\"\"\nBurak Himmetoglu, 2019\n\nLoss functions\n\"\"\"\n\nimport numpy as np\n\nEPS = 1e-5 # Clipping factor for probabilities\n\ndef mse(Y, yHat):\n    return np.mean( (Y-yHat)**2)\n\ndef binary_log_loss(Y, P):\n    \"\"\"\n    Compute negative log loss\n    \"\"\"\n    N = len(Y)\n    # Clip values very close to 1 or 0\n    P = np.clip(P, EPS, 1 - EPS)\n\n    # Negative log likelihood function\n    mask0 = (Y == 0) # label = 0 observations\n    mask1 = (Y == 1) # label = 1 observations\n\n    nll = -(np.log(P[mask1]).sum() + np.log(1-P[mask0]).sum())\n\n    return nll/N\n", "meta": {"hexsha": "c92245159bc4d79be33cb5ba3df526a65328922c", "size": 542, "ext": "py", "lang": "Python", "max_stars_repo_path": "mlbook/utils/losses.py", "max_stars_repo_name": "bhimmetoglu/mlrecipes", "max_stars_repo_head_hexsha": "1f456489b7915531b523b5dc98acc6d8b863a695", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mlbook/utils/losses.py", "max_issues_repo_name": "bhimmetoglu/mlrecipes", "max_issues_repo_head_hexsha": "1f456489b7915531b523b5dc98acc6d8b863a695", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mlbook/utils/losses.py", "max_forks_repo_name": "bhimmetoglu/mlrecipes", "max_forks_repo_head_hexsha": "1f456489b7915531b523b5dc98acc6d8b863a695", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6896551724, "max_line_length": 62, "alphanum_fraction": 0.5904059041, "include": true, "reason": "import numpy", "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9609517072737735, "lm_q2_score": 0.8902942370375485, "lm_q1q2_score": 0.8555297670572338}}
{"text": "import numpy as np\n\ndef polar_to_cartesion(r, phi):\n    '''\n    Two 1D vectors of polar r (radial) and phi (angular) coordinates\n    Function returns the Cartesian vectors\n    '''\n    x = r * np.cos(phi)\n    y = r * np.sin(phi)\n    return x, y\n\ndef cartesian_to_polar(x, y):\n    '''\n    Two 1d vectors of cartesian x and y coordinates\n    Function converts them to polar coordinates r and phi\n    '''\n    r = np.sqrt(np.square(x) + np.square(y))\n    phi = np.arctan2(y, x)\n    return r, phi\n\ndef cartesian_to_spherical_coords(vectors):\n    '''\n    N by 3 vectors of (x, y, z) are converted to spherical coordinates\n    '''\n    r = np.sqrt(np.sum(np.square(vectors), axis=-1))\n    theta = np.arctan(np.sqrt(np.square(vectors[:, 0]) + np.square(vectors[:, 1]))/vectors[:, 2])\n    phi = np.zeros(np.size(vectors[:, 0]))\n    phi[vectors[:, 0] != 0] = np.arctan(vectors[:, 1][vectors[:, 0] != 0]/vectors[:, 0][vectors[:, 0] !=0])\n#    theta = np.arctan(vectors[:, 1]/vectors[:, 2])\n#    phi = np.arccos(vectors[:, 0]/r)\n    phi[(vectors[:, 1] > 0) * (vectors[:, 0] < 0)] += np.pi # +y, -z\n    phi[(vectors[:, 1] < 0) * (vectors[:, 0] >= 0)] += 2*np.pi # -y, +z\n    phi[(vectors[:, 1] < 0) * (vectors[:, 0] < 0)] += np.pi # -y, -z\n    phi[(vectors[:, 1] > 0) * (vectors[:, 0] == 0)] = np.pi/2\n    phi[(vectors[:, 1] < 0) * (vectors[:, 0] == 0)] = 3*np.pi/2\n    phi[(vectors[:, 1] == 0) * (vectors[:, 0] <= 0)] = np.pi\n    theta[theta<0] += np.pi\n    return r, theta, phi\n\ndef spherical_to_cartesian_coords(vectors):\n    '''\n    N by 3 vectors of (r, theta, phi)\n    '''\n    x = vectors[:, 0] * np.sin(vectors[:, 1]) * np.cos(vectors[:, 2])\n    y = vectors[:, 0] * np.sin(vectors[:, 1]) * np.sin(vectors[:, 2])\n    z = vectors[:, 0] * np.cos(vectors[:, 1])\n    return x, y, z\n\ndef cartesian_to_spherical_vector_field(theta, phi, fx, fy, fz):\n    f_r = (np.sin(theta) * np.cos(phi) * fx + \n       np.sin(theta) * np.sin(phi) * fy + \n       np.cos(theta) * fz)\n    f_th = (np.cos(theta) * np.cos(phi) * fx + \n        np.cos(theta) * np.sin(phi) * fy - \n        np.sin(theta) * fz)\n    f_ph = (-np.sin(phi) * fx + \n        np.cos(phi) * fy)\n    return f_r, f_th, f_ph\n\ndef spherical_to_cartesian_vector_field(theta, phi, f_r, f_th, f_ph):\n    f_x = (np.sin(theta) * np.cos(phi) * f_r + \n           np.cos(theta) * np.cos(phi) * f_th - \n           np.sin(phi) * f_ph)\n    f_y = (np.sin(theta) * np.sin(phi) * f_r + \n           np.cos(theta) * np.sin(phi) * f_th +\n           np.cos(phi) * f_ph)\n    f_z = (np.cos(theta) * f_r - \n           np.sin(theta) * f_th)\n    return f_x, f_y, f_z\n\ndef field_magnitude(f, axis=-1):\n    f_mag = np.sqrt(np.sum(f * np.conj(f), axis=axis))\n    f_mag = np.real(f_mag)\n    return f_mag\n\ndef rotate_vector(xyz, angle, rotation_axis):\n    '''\n    xyz: a vectors to be rotated, length 3\n    angle: the angle by which to rotate xyz, in radians\n    rotation_axis: the axis around which to rotate xyz of length 3\n    '''\n    if np.count_nonzero(xyz) == 0:\n        raise ValueError('Input vector is the null vector')\n    term1_rot = xyz*np.cos(angle)\n    term2_rot = np.cross(rotation_axis, xyz, axis=0) * np.sin(angle)\n    term3_rot = rotation_axis * np.transpose(np.tensordot(rotation_axis, xyz, axes=(0,0)))*(1-np.cos(angle))\n    xyz_rot = term1_rot + term2_rot + term3_rot\n    return xyz_rot\n    \ndef rotate_vector_Nd(xyz, angle, rotation_axis):\n    '''\n    xyz: an array of vectors to be rotated, with N dimensions, of which the last has 3 elements\n    angle: the angle by which to rotate xyz, in radians\n    rotation_axis: the axis around which to rotate xyz, of length 3\n    '''\n    # Normalize rotation axis\n    rotation_axis = rotation_axis/np.sqrt(np.sum(np.square(rotation_axis)))\n    # Expand dimensions of rotation axis for broadcasting\n    rotation_axis = np.reshape(rotation_axis, (xyz.ndim-1)*[1]+[3])\n    # Calculate rotation vector (Rodrigues formula)\n    term1_rot = xyz*np.cos(angle)\n    term2_rot = np.cross(rotation_axis, xyz, axis=-1) * np.sin(angle)\n    term3_rot = rotation_axis * np.expand_dims(np.dot(xyz, np.squeeze(rotation_axis)), axis=-1)*(1-np.cos(angle))\n    xyz_rot = term1_rot + term2_rot + term3_rot\n    return xyz_rot\n\ndef expand_quadrant_symmetry(mag, quadrant_num):\n    '''\n    Uses symmetry to turn an array representing values in one quadrant of an\n    image into values for a whole image/array\n    quadrant_num = 1, 2, 3 ,4\n    quadrants: 1  2\n               3  4\n    assumes image should be reflected around two axes, removing double rows/columns of pixels caused by reflection\n    '''\n    if quadrant_num == 1:\n        Q1 = mag\n        Q2 = np.flip(Q1, axis = 1)[:, 1:]\n        Q3 = np.flip(Q1, axis = 0)[1:, :]\n        Q4 = np.flip(np.flip(Q1, axis = 1), axis=0)[1:, 1:]\n    elif quadrant_num == 2:\n        Q2 = mag\n        Q1 = np.flip(Q2, axis = 1)[:, :-1]\n        Q4 = np.flip(Q2, axis = 0)[1:, :]\n        Q3 = np.flip(np.flip(Q2, axis=1), axis=0)[1:, :-1]\n    elif quadrant_num == 3:\n        Q3 = mag\n        Q4 = np.flip(Q3, axis=1)[:, 1:]\n        Q1 = np.flip(Q3, axis=0)[:-1, :]\n        Q2 = np.flip(np.flip(Q3, axis=1), axis=0)[:-1, 1:]\n    elif quadrant_num == 4:\n        Q4 = mag\n        Q3 = np.flip(Q4, axis=1)[:, :-1]\n        Q2 = np.flip(Q4, axis = 0)[:-1, :]\n        Q1 = np.flip(np.flip(Q4, axis=1), axis=0)[:-1, :-1]\n    \n    Q12 = np.append(Q1, Q2, axis=1)\n    Q34 = np.append(Q3, Q4, axis=1)\n    total = np.append(Q12, Q34, axis=0)\n    return total\n", "meta": {"hexsha": "4e4a5071b4757c9ff7590ed563a4892c863ac861", "size": 5429, "ext": "py", "lang": "Python", "max_stars_repo_path": "coord_transforms.py", "max_stars_repo_name": "icbicket/CLFields", "max_stars_repo_head_hexsha": "eca760cde80a1256e4f1b89ca227a54184d87c80", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "coord_transforms.py", "max_issues_repo_name": "icbicket/CLFields", "max_issues_repo_head_hexsha": "eca760cde80a1256e4f1b89ca227a54184d87c80", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coord_transforms.py", "max_forks_repo_name": "icbicket/CLFields", "max_forks_repo_head_hexsha": "eca760cde80a1256e4f1b89ca227a54184d87c80", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5035460993, "max_line_length": 114, "alphanum_fraction": 0.5802173513, "include": true, "reason": "import numpy", "num_tokens": 1778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517095103498, "lm_q2_score": 0.8902942275774318, "lm_q1q2_score": 0.8555297599577295}}
{"text": "import sys\nimport numpy as np\n\ndef floyd_warshall(graph):\n    dist = graph.copy()\n\n    v = graph.shape[0]\n\n    for k in range(v):\n        for i in range(v):\n            for j in range(v):\n                if dist[i,k] + dist[k,j] < dist[i,j]: \n                    dist[i,j] = dist[i,k] + dist[k,j]\n\n    return dist    \n\ndef minDistance(dist, V, sptSet): \n    minimum = sys.maxint \n    for v in range(V): \n        if dist[v] < minimum and sptSet[v] == False: \n            minimum = dist[v] \n            min_index = v \n    return min_index\n\ndef dijkstra(g,V,src = 0):\n    graph = g.copy()\n    dist = [sys.maxint] * V \n    dist[src] = 0\n    sptSet = [False] * V \n    for cout in range(V): \n        u = minDistance(dist, V, sptSet) \n        sptSet[u] = True\n        \n        for v in range(V): \n            if(graph[u][v] > 0 and sptSet[v] == False\n                and dist[v] > dist[u] + graph[u][v]): \n                    dist[v] = dist[u] + graph[u][v]\n    \n    return np.asarray(dist)\n", "meta": {"hexsha": "e0014a8de0f2f2834c75b5d3a6461fc1241849e9", "size": 984, "ext": "py", "lang": "Python", "max_stars_repo_path": "football_lib/utils/graphPath_algorithms.py", "max_stars_repo_name": "RQuispeC/football-retrieval", "max_stars_repo_head_hexsha": "67a4ba1e45025ed0d19cb034729519ab79027ce0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-07-21T10:14:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-29T14:04:27.000Z", "max_issues_repo_path": "football_lib/utils/graphPath_algorithms.py", "max_issues_repo_name": "RQuispeC/football-retrieval", "max_issues_repo_head_hexsha": "67a4ba1e45025ed0d19cb034729519ab79027ce0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "football_lib/utils/graphPath_algorithms.py", "max_forks_repo_name": "RQuispeC/football-retrieval", "max_forks_repo_head_hexsha": "67a4ba1e45025ed0d19cb034729519ab79027ce0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6, "max_line_length": 54, "alphanum_fraction": 0.4847560976, "include": true, "reason": "import numpy", "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244553, "lm_q2_score": 0.8856314692902446, "lm_q1q2_score": 0.8554310574245263}}
{"text": "\"\"\"\nObjetivo: Resolver questão 3 do segundo laboratorio.\n\"\"\"\nfrom math import pow, pi, cos\nimport numpy as np\n\n\ndef cosseno(a):  # calcula o cosseno do angulo\n    soma = 0\n    for i in range(0, 30):\n        soma = soma + (pow(-1, i) * (pow(a, 2 * i) / fatorial(2 * i)))\n        # o primeiro elemento escolhe o sinal, o segundo o numero da expressão\n    return soma\n\n\ndef fatorial(n):  # calcula o fatorial de um numero qualquer\n    if n == 0:\n        return 1\n    else:\n        x = 1\n        for i in range(1, n + 1):\n            x = x * i\n        return x\n\n\n# usaremos numpy para gerar um lista onde o passo possa ser float, coisa que no for não se pode\nc = np.arange(0, pi + 0.00001, (pi / 100))  # +0.00001 para que o valor de pi tambem entre no array\n\ncossenos_aprox = [cosseno(i) for i in c]\n# gera uma lista onde cada item é valor de uma iteração do for aplicando a função\nprint(f'Valores aproximados = {cossenos_aprox}')\n\ncossenos_exatos = [cos(i) for i in c]  # lista com valores exatos dos cossenos\nprint(f'Valores exatos = {cossenos_exatos}')\n\nerro = abs(cossenos_exatos[-1] - cossenos_aprox[-1])\n# como o erro aumenta a cada iteração da nossa função, escolhendo o ultimo valor de cada lista, teremos o maior erro\n# possivel\nprint(f'Erro absoluto = {erro}')\n", "meta": {"hexsha": "57463e631d1a4386f477fd85ecb18d07b7cfbc3f", "size": 1268, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab2/q3.py", "max_stars_repo_name": "ViniciusRCortez/Monitoria-de-metodos-numericos-com-python", "max_stars_repo_head_hexsha": "85678fe8907752533d0dc97dc83550411ba079f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab2/q3.py", "max_issues_repo_name": "ViniciusRCortez/Monitoria-de-metodos-numericos-com-python", "max_issues_repo_head_hexsha": "85678fe8907752533d0dc97dc83550411ba079f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab2/q3.py", "max_forks_repo_name": "ViniciusRCortez/Monitoria-de-metodos-numericos-com-python", "max_forks_repo_head_hexsha": "85678fe8907752533d0dc97dc83550411ba079f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7, "max_line_length": 116, "alphanum_fraction": 0.6600946372, "include": true, "reason": "import numpy", "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.9059898286330041, "lm_q1q2_score": 0.8554146291395803}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nBE523 Biosystems Analysis & Design\nHW5 - Problem 1. Calculation of exponential K\nhttps://mathinsight.org/doubling_time_half_life_discrete\n\nCreated on Tue Jan 26 22:37:49 2021\n@author: eduardo\n\"\"\"\nimport statsmodels.api as sm  # allows linear regression without intercept\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Bacteria density data\nB = np.array([22.1, 23.4, 26.1, 27.5, 30.5, 34.4, 36.6])  # Exercise 4C\n\nsteps = len(B)  # Adjust the lengths of the vectors with the number of steps\ndB = np.zeros(steps)\nBexp = np.zeros(steps)\ndt = 5\nt = np.linspace(0, (steps-1)*dt, steps)  # time vector\n\nfor i in range(1, steps):\n    dB[i] = B[i] - B[i-1]  # compute the increment between time steps\n\nprint(B)\n\n# Perform a linear regression with B and dB, then plot (dB vs B)\nmodel = sm.OLS(dB, B)  # No intercept by default, force through the origin??\nresults = model.fit()\nslope = results.params[0]  # growth rate\nprint(\"slope=\", slope)\n\n# Figure 1, plotting dB vs B\nplt.figure(1)\nplt.plot(B, dB, 'bx', B, slope*B, 'r-')  # plot and linear eq.\nplt.legend(['data', 'linear regression $R^2$=%.2f' % results.rsquared], loc='best')\nplt.xlabel('B')\nplt.ylabel('dB')\n# plt.savefig('p1_growth_%dsteps_linear2.png' % steps, dpi=300, bbox_inches='tight')\n\n# Create the parameters for an exponential equation\ntdouble = np.log(2)/np.log(1+slope)*dt  # time to double population\nmu = np.log(2)/tdouble  # constant for exponential eq. with base on natural log\nprint('tdouble =', tdouble, 'mu=', mu)\n\n# Generate an exponential equation (exact solution)\nBexp = B[0] * np.exp(mu*t)\n\n# Generate predictions with the model: B(t+1) = B[0]*(r+1)^t (numerical solution)\nBmodel = B[0] * (1 + slope)**(t/dt)\n\n# Figure 2, plotting B vs t\nplt.figure(2)\nplt.plot(t, B, 'bx', t, Bmodel, 'r-', t, Bexp, 'k+')  # Plot data vs exponential growth eq.\nplt.legend(['data',\n            'equation B=%.2f*%.3f^t' % (B[0], slope+1),\n            'exponential B=%.2f * exp(%.3f*t)' % (B[0], mu)],\n           loc='best')\nplt.xlabel('time (min)')\nplt.ylabel('B')\nplt.savefig('p1_growth_%dsteps2.png' % steps, dpi=300, bbox_inches='tight')\n", "meta": {"hexsha": "628aa1f8d23b4cb4b41a74ad8eb89b0092b51529", "size": 2151, "ext": "py", "lang": "Python", "max_stars_repo_path": "p1_exponential_k2.py", "max_stars_repo_name": "eduardo-jh/HW05_Doubling_time_and_K", "max_stars_repo_head_hexsha": "1d1a5c748bd0bcfe98c3c0ea74c93f226b4ecbee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "p1_exponential_k2.py", "max_issues_repo_name": "eduardo-jh/HW05_Doubling_time_and_K", "max_issues_repo_head_hexsha": "1d1a5c748bd0bcfe98c3c0ea74c93f226b4ecbee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "p1_exponential_k2.py", "max_forks_repo_name": "eduardo-jh/HW05_Doubling_time_and_K", "max_forks_repo_head_hexsha": "1d1a5c748bd0bcfe98c3c0ea74c93f226b4ecbee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.609375, "max_line_length": 91, "alphanum_fraction": 0.6666666667, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452772, "lm_q2_score": 0.8947894731166139, "lm_q1q2_score": 0.8554020508427754}}
{"text": "import numpy as np\n\n# numpy.amin() 用于计算数组中的元素沿指定轴的最小值。\n# numpy.amax() 用于计算数组中的元素沿指定轴的最大值。\na = np.array([[3, 7, 5], [8, 4, 3], [2, 4, 9]])\nprint('我们的数组是：')\nprint(a)\nprint('\\n')\nprint('调用 amin() 函数：')\nprint(np.amin(a, 1))\nprint('\\n')\nprint('再次调用 amin() 函数：')\nprint(np.amin(a, 0))\nprint('\\n')\nprint('调用 amax() 函数：')\nprint(np.amax(a))\nprint('\\n')\nprint('再次调用 amax() 函数：')\nprint(np.amax(a, axis=0))\n\n# numpy.ptp()函数计算数组中元素最大值与最小值的差（最大值 - 最小值）。\na = np.array([[3, 7, 5], [8, 4, 3], [2, 4, 9]])\nprint('我们的数组是：')\nprint(a)\nprint('\\n')\nprint('调用 ptp() 函数：')\nprint(np.ptp(a))\nprint('\\n')\nprint('沿轴 1 调用 ptp() 函数：')\nprint(np.ptp(a, axis=1))\nprint('\\n')\nprint('沿轴 0 调用 ptp() 函数：')\nprint(np.ptp(a, axis=0))\n\n# numpy.percentile()\n# 百分位数是统计中使用的度量，表示小于这个值的观察值的百分比。 函数numpy.percentile()接受以下参数。\n#\n# numpy.percentile(a, q, axis)\n# 参数说明：\n#\n# a: 输入数组\n# q: 要计算的百分位数，在 0 ~ 100 之间\n# axis: 沿着它计算百分位数的轴\na = np.array([[10, 7, 4], [3, 2, 1]])\nprint('我们的数组是：')\nprint(a)\n\nprint('调用 percentile() 函数：')\n# 50% 的分位数，就是 a 里排序之后的中位数\nprint(np.percentile(a, 50))\n\n# axis 为 0，在纵列上求\nprint(np.percentile(a, 50, axis=0))\n\n# axis 为 1，在横行上求\nprint(np.percentile(a, 50, axis=1))\n\n# 保持维度不变\nprint(np.percentile(a, 50, axis=1, keepdims=True))\n\n# numpy.median()\n# numpy.median() 函数用于计算数组 a 中元素的中位数（中值）\na = np.array([[1, 2, 3], [3, 4, 5], [4, 5, 6]])\nprint('我们的数组是：')\nprint(a)\nprint('\\n')\nprint('调用 mean() 函数：')\nprint(np.mean(a))\nprint('\\n')\nprint('沿轴 0 调用 mean() 函数：')\nprint(np.mean(a, axis=0))\nprint('\\n')\nprint('沿轴 1 调用 mean() 函数：')\nprint(np.mean(a, axis=1))\n\n# numpy.average()\n# numpy.average() 函数根据在另一个数组中给出的各自的权重计算数组中元素的加权平均值。\n#\n# 该函数可以接受一个轴参数。 如果没有指定轴，则数组会被展开。\n#\n# 加权平均值即将各数值乘以相应的权数，然后加总求和得到总体值，再除以总的单位数。\n#\n# 考虑数组[1,2,3,4]和相应的权重[4,3,2,1]，通过将相应元素的乘积相加，并将和除以权重的和，来计算加权平均值。\na = np.array([1, 2, 3, 4])\nprint('我们的数组是：')\nprint(a)\nprint('\\n')\nprint('调用 average() 函数：')\nprint(np.average(a))\nprint('\\n')\n# 不指定权重时相当于 mean 函数\nwts = np.array([4, 3, 2, 1])\nprint('再次调用 average() 函数：')\nprint(np.average(a, weights=wts))\nprint('\\n')\n# 如果 returned 参数设为 true，则返回权重的和\nprint('权重的和：')\nprint(np.average([1, 2, 3, 4], weights=[4, 3, 2, 1], returned=True))\n\na = np.arange(6).reshape(3, 2)\nprint('我们的数组是：')\nprint(a)\nprint('\\n')\nprint('修改后的数组：')\nwt = np.array([3, 5])\nprint(np.average(a, axis=1, weights=wt))\nprint('\\n')\nprint('修改后的数组：')\nprint(np.average(a, axis=1, weights=wt, returned=True))\n\n# 标准差\n# 标准差是一组数据平均值分散程度的一种度量。\n#\n# 标准差是方差的算术平方根。\n#\n# 标准差公式如下：\n#\n# std = sqrt(mean((x - x.mean())**2))\n# 如果数组是 [1，2，3，4]，则其平均值为 2.5。 因此，差的平方是 [2.25,0.25,0.25,2.25]，并且再求其平均值的平方根除以 4，即 sqrt(5/4) ，结果为 1.1180339887498949。\nprint(np.std([1, 2, 3, 4]))\n# 方差\n# 统计中的方差（样本方差）是每个样本值与全体样本值的平均数之差的平方值的平均数，即 mean((x - x.mean())** 2)。\n#\n# 换句话说，标准差是方差的平方根。\n\nprint(np.var([1, 2, 3, 4]))\n", "meta": {"hexsha": "23d763484210748dc1e3071d5ef72b0504759ce4", "size": 2692, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy/4mathFuntion3.py", "max_stars_repo_name": "chenliangold4j/MyPyDictionnary", "max_stars_repo_head_hexsha": "3428333f42249f33732da71e420bdc41a412f594", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy/4mathFuntion3.py", "max_issues_repo_name": "chenliangold4j/MyPyDictionnary", "max_issues_repo_head_hexsha": "3428333f42249f33732da71e420bdc41a412f594", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy/4mathFuntion3.py", "max_forks_repo_name": "chenliangold4j/MyPyDictionnary", "max_forks_repo_head_hexsha": "3428333f42249f33732da71e420bdc41a412f594", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1968503937, "max_line_length": 114, "alphanum_fraction": 0.6285289747, "include": true, "reason": "import numpy", "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993888, "lm_q2_score": 0.8947894703109853, "lm_q1q2_score": 0.8554020492828127}}
{"text": "\"\"\"\nThe Commodity Channel Index (CMCI), developed by Donald Lambert,\nmeasures the variation of a security's price from its statistical mean.\n\nThe CMCI can be used to identify possible divergences that may indicate\na forthcoming trend for a selected security. A CMCI indicator falling\nbelow a value of -100 indicates an oversold condition. A buy signal is\ntriggered when the indicator crosses -100 from below. Similarly, a CCI\nvalue greater than 100 indicates an overbought condition. A sell signal\nis triggered when the indicator crosses 100 from above.\n\nCMCI Calculations\nCMCI=(HLC3 - N Period Simple MA of HLC3) /\n     (0.015 * N Period Mean Deviation of HLC3)\n\nwhere:\nHLC3 = (High + Low + Close) / 3\nN Period= Number of data points to use;\n\n\"\"\"\nimport numpy as np\n\n\ndef cmci(ohlcv, period=13):\n    \"\"\"\n    VALIDATION\n\n    Results are similar to Bloomberg data to the 4th digit after the decimal point.\n    But very different from TradingView data.\n    In some formulas, high and low are the highs and lows of the past N days.\n    \"\"\"\n    _ohlcv = ohlcv[['high', 'low', 'close']].copy(deep=True)\n    _ohlcv['hlc3'] = _ohlcv[['high', 'low', 'close']].mean(axis=1)\n    _ohlcv['hlc3_ma'] = _ohlcv['hlc3'].rolling(window=period, min_periods=period).mean()\n    _ohlcv['hlc3_mad'] = _ohlcv['hlc3'].rolling(window=period, min_periods=period).apply(\n        lambda x: np.fabs(x - x.mean()).mean())\n\n    indicator_values = (_ohlcv['hlc3'] - _ohlcv['hlc3_ma']) / (0.015 * _ohlcv['hlc3_mad'])\n    return indicator_values\n", "meta": {"hexsha": "74156dc7b4a6bf9de1492c7844d3483706c56a12", "size": 1512, "ext": "py", "lang": "Python", "max_stars_repo_path": "qrtt/technical/cmci.py", "max_stars_repo_name": "leopoldsw/qrtt", "max_stars_repo_head_hexsha": "271f23888847f9a0a9a7da360be22c5000b058ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qrtt/technical/cmci.py", "max_issues_repo_name": "leopoldsw/qrtt", "max_issues_repo_head_hexsha": "271f23888847f9a0a9a7da360be22c5000b058ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qrtt/technical/cmci.py", "max_forks_repo_name": "leopoldsw/qrtt", "max_forks_repo_head_hexsha": "271f23888847f9a0a9a7da360be22c5000b058ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8, "max_line_length": 90, "alphanum_fraction": 0.712962963, "include": true, "reason": "import numpy", "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.8947894724152068, "lm_q1q2_score": 0.8554020479279113}}
{"text": "# PA=LU factorization algorithm test\n\nimport numpy as np\nfrom palu_factor import palu_factor\nfrom triangular import triangular\n\n\nnp.set_printoptions(suppress=True, precision=5)\n# TEST: PA=LU factorization\n\n# Coefficient matrix\nA = np.matrix(' 0 41 53 12 62 26;'\n              '43 49 61 60 22 27;'\n              '65 25 56 38 43 43;'\n              '37  0 24 42 26 56;'\n              '26 28 41 15 42 24;'\n              '13 50 48 36 46 28 ', float)\nprint('A = \\n', A)\n# LU factorization (deep-copy of A because we need it or the \"check\")\nB, p = palu_factor(np.matrix(A))\nprint('B = \\n', B)\n# Extract lower part\nL = np.matrix(np.tril(B,-1) + np.identity(6))\nprint('L = \\n', L)\n# Extract upper part\nU = np.matrix(np.triu(B))\nprint('U = \\n', U)\n# Check\nif np.allclose(A[p], L*U) == False:\n    raise Exception('LU factorization test failure')\n\n# TEST: System Resolution\n# Ax = b => PAx = Pb => LUx = Pb\n# LUx = Pb\nb = np.matrix('33; 35; 2; 49; 53; 21')\n# Lk = Pb (note the permutation of b using the index vector p)\nk = triangular(L, b[p], 1)\n# Ux = k\nx = triangular(U, k, 0)\n# Check\nif np.allclose(b, A*x) == False:\n    raise Exception('System Resolution test failure')\n", "meta": {"hexsha": "86cffd090c1cf4523c2acb12791d04fcda2de29b", "size": 1163, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/palu_factor_test.py", "max_stars_repo_name": "davxy/numeric", "max_stars_repo_head_hexsha": "1e8b44a72e1d570433a5ba81ae0795a750ce5921", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-03T17:02:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T04:09:34.000Z", "max_issues_repo_path": "python/palu_factor_test.py", "max_issues_repo_name": "davxy/numeric", "max_issues_repo_head_hexsha": "1e8b44a72e1d570433a5ba81ae0795a750ce5921", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/palu_factor_test.py", "max_forks_repo_name": "davxy/numeric", "max_forks_repo_head_hexsha": "1e8b44a72e1d570433a5ba81ae0795a750ce5921", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0465116279, "max_line_length": 69, "alphanum_fraction": 0.6165090284, "include": true, "reason": "import numpy", "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.8947894717137996, "lm_q1q2_score": 0.8554020472573791}}
{"text": "from scipy.integrate import *\r\nimport math\r\nimport numpy as np\r\nfrom pylab import *\r\nimport matplotlib.pyplot as plt\r\n\r\n# Function to integrate\r\nfunction_map = lambda x: math.exp(-x**2)\r\n\r\ndef function(x):\r\n    return math.exp(-x**2)\r\n\r\ndef integrate(function, time, dt):\r\n    for t in np.nditer(time):\r\n        accum = dt * function\r\n    return accum\r\n\r\n# Integration bounds\r\nlower_bound = -5\r\nupper_bound = 5\r\nnumber_of_points = 500\r\n\r\n# Differential time element\r\nt = np.linspace(lower_bound, upper_bound, num = number_of_points)\r\ndt = t[1] - t[0]\r\n# print(\"dt:\", dt)\r\n\r\n# Scipy integration method\r\nscipy_result = quad(function_map, lower_bound, upper_bound)\r\nprint(\"Scipy Result\\n Value, Error:\", scipy_result)\r\n\r\n# My integration method\r\nf1 = np.vectorize(function)\r\nmy_result = integrate(f1(t), t, dt)\r\nintegrated_value = 0\r\nfor element in my_result:\r\n    integrated_value += element\r\n\r\n# print(my_result)\r\nprint(\"\\nMy result:\", integrated_value)\r\n\r\nerror = abs(scipy_result[0] - integrated_value)\r\nprint(\"\\nScipy result - my result:\", error)\r\n\r\n# print((pi)**0.5)      # Exact value\r\n\r\n# Plotting function\r\nplt.plot(t, f1(t), 'r--')\r\nplt.fill_between(t, f1(t), facecolor = 'blue', alpha = 1)\r\nxlabel('$x$')\r\nylabel('$f(x)$')\r\nplt.grid()\r\ntitle('$e^{-x^2}$')\r\nplt.show()\r\n\r\nerror_ydata = []\r\nindex = []\r\nconvergence_n = 52\r\n# Convergence plot error data generation\r\nfor n in range(2,convergence_n):\r\n    index += [n]\r\n    integrated_value2 = 0\r\n    integral_value = 0\r\n    number_of_points = n\r\n    t2 = np.linspace(lower_bound, upper_bound, num=number_of_points)\r\n    dt2 = t2[1] - t2[0]\r\n    f2 = np.vectorize(function)\r\n    my_result2 = integrate(f2(t2), t2, dt2)\r\n    for elements in my_result2:\r\n        integrated_value2 += elements\r\n        integral_value += elements\r\n    error_ydata += [integrated_value2]\r\n\r\n# Compute best value error:\r\nbest_error = abs(error_ydata[-1] - (pi**0.5))\r\nprint(\"\\nBest error from my method:\", best_error, 'N,', convergence_n)\r\nprint(\"Best value:\", integrated_value, 'N:', convergence_n )\r\n\r\n\r\n# Convergence plot\r\nplt.plot(index, error_ydata, 'b--')\r\nplt.axhline(y=pi**0.5, color='r', linestyle='-')\r\nplt.title(\"Convergence plot of methods\")\r\nxlabel('$N$ (Number of time partitions)')\r\nylabel('$\\int f(x) dx$')\r\nlegend(('My method convergence values', 'Exact solution, $\\pi^{1/2}$'), loc='best')\r\nplt.show()\r\n", "meta": {"hexsha": "d1e2a1a972a175a8cdffdeebc093da7de100cdb1", "size": 2353, "ext": "py", "lang": "Python", "max_stars_repo_path": "integration_methods.py", "max_stars_repo_name": "Ruchir555/Computational-Physics", "max_stars_repo_head_hexsha": "5edb23494d1d6eff18eee49ca156e47faaea9779", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "integration_methods.py", "max_issues_repo_name": "Ruchir555/Computational-Physics", "max_issues_repo_head_hexsha": "5edb23494d1d6eff18eee49ca156e47faaea9779", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "integration_methods.py", "max_forks_repo_name": "Ruchir555/Computational-Physics", "max_forks_repo_head_hexsha": "5edb23494d1d6eff18eee49ca156e47faaea9779", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7386363636, "max_line_length": 84, "alphanum_fraction": 0.662558436, "include": true, "reason": "import numpy,from scipy", "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.8947894604912848, "lm_q1q2_score": 0.8554020365288643}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 25 20:48:39 2017\n\n@author: ratnadeepb\n@License: MIT\n\"\"\"\n\n# System Import\nimport numpy as np\nimport sys\n\n# Local Import\nfrom InnerProductSpaces.norm import unit_vec\nfrom InnerProductSpaces.projection import proj\n\n'''\nGram Schmidt process of creating orthonormal basis from an arbitrary basis\n'''\n\ndef gram_schmidt(B):\n    try:\n        B = np.array(B, dtype=np.float16)\n    except:\n        sys.exit(\"Not a vector\")\n    \n    W = np.zeros_like(B)\n    \n    # Create and orthogonal basis\n    W[0] = B[0]\n    i = 1\n    while i < len(B):\n        p = 0\n        j = 1\n        while j < i:\n            p += proj(B[j], W[i - 1])\n            j += 1\n        W[i] = B[i] - p\n        i += 1\n    \n    # Normalise\n    U = np.zeros_like(W)\n    for ind, w in enumerate(W):\n        temp = unit_vec(w)\n        for s, u in enumerate(temp):\n            U[ind][s] = u\n    \n    return U\n\nif __name__ == \"__main__\":\n    B = [[0, 1, 1],\n         [2, 1, 0],\n         [-1, 0, -1]]\n    U = gram_schmidt(B)\n    print(U)\n    '''\n    U = [[0, 1/np.sqrt(2), 1/np.sqrt(2)],\n          [2/np.sqrt(6), 1/np.sqrt(6), -1/np.sqrt(6)],\n          [-1/np.sqrt(3), 1/np.sqrt(3), -1/np.sqrt(3)]]\n    '''", "meta": {"hexsha": "557ba56a6f63df7b70ddceae25c6bc1260e6d6ab", "size": 1226, "ext": "py", "lang": "Python", "max_stars_repo_path": "InnerProductSpaces/gram_schmidt.py", "max_stars_repo_name": "ratnadeepb/LinearAlgebra", "max_stars_repo_head_hexsha": "0f4399c15ba12a3e7c0e2a796c77efa66520e462", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "InnerProductSpaces/gram_schmidt.py", "max_issues_repo_name": "ratnadeepb/LinearAlgebra", "max_issues_repo_head_hexsha": "0f4399c15ba12a3e7c0e2a796c77efa66520e462", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "InnerProductSpaces/gram_schmidt.py", "max_forks_repo_name": "ratnadeepb/LinearAlgebra", "max_forks_repo_head_hexsha": "0f4399c15ba12a3e7c0e2a796c77efa66520e462", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0983606557, "max_line_length": 74, "alphanum_fraction": 0.5081566069, "include": true, "reason": "import numpy", "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.894789454880027, "lm_q1q2_score": 0.8554020334089384}}
{"text": "import math\nimport numpy\n\n# perform 5-point Gauss-Legendre quadrature on a degree 9 (2 N - 1)\n# polynomial, and compare to the compound Simpson's rule.\n\ndegree = 9\n\n\n# integrand\ndef f(x):\n    p = 0.0\n\n    n = 0\n    while (n <= degree):\n        p += x**n\n        n += 1\n\n    return p\n\n\n# analytic (true) integral\ndef true(a, b):\n    t = 0.0\n\n    n = 0\n    while (n <= degree):\n        t += (b**(n+1) - a**(n+1))/(n+1)\n        n += 1\n\n    return t\n\n\n# do a Simpson's integration by breaking up the domain [a,b] into N\n# slabs.  Note: N must be even, because we do a pair at a time\ndef simp(a,b,f,N):\n\n    xedge = numpy.linspace(a,b,N+1)\n\n    integral = 0.0\n\n    if not N%2 == 0:\n        sys.exit(\"ERROR: N must be even\")\n\n    delta = (xedge[1] - xedge[0])\n\n    n = 0\n    while n < N:\n        integral += (1.0/3.0)*delta*(f(xedge[n]) + \n                                     4.0*f(xedge[n+1]) + \n                                     f(xedge[n+2]))\n        n += 2\n\n    return integral\n\n\ndef x(z, a, b):\n    \"\"\" convert from [-1, 1] (the integration range of Gauss-Legendre)\n        to [a, b] (our general range) through a change of variables z\n        -> x \"\"\"\n\n    return 0.5*(b + a) + 0.5*(b - a)*z\n\n\n# integration limits\na = 0.0\nb = 1.0\n\n# we are doing 5-point quadrature for all methods.  delta is the width\n# of the slab (5 points = 4 slabs)\ndelta = (b - a)/4\n\n\n# Simpson's\nI_S = simp(a, b, f, 4)\n\n\n# Gauss-Legendre\n\n# we need to convert from [-1, 1] (the range in which the roots are\n# found) to [a, b] (the range in which our integrand is defined), so\n# convert the roots z1, z2, ...\n\nz1 = -math.sqrt(5.0 + 2.0*math.sqrt(10.0/7.0))/3.0\nx1 = x(z1, a, b)\nw1 = (322.0-13.0*math.sqrt(70.0))/900.0\n\nz2 = -math.sqrt(5.0 - 2.0*math.sqrt(10.0/7.0))/3.0\nx2 = x(z2, a, b)\nw2 = (322.0+13.0*math.sqrt(70.0))/900.0\n\nz3 = 0.0\nx3 = x(z3, a, b)\nw3 = 128.0/225.0\n\nz4 = math.sqrt(5.0 - 2.0*math.sqrt(10.0/7.0))/3.0\nx4 = x(z4, a, b)\nw4 = (322.0+13.0*math.sqrt(70.0))/900.0\n\nz5 = math.sqrt(5.0 + 2.0*math.sqrt(10.0/7.0))/3.0\nx5 = x(z5, a, b)\nw5 = (322.0-13.0*math.sqrt(70.0))/900.0\n\n\n# 5-point Gauss-Legendre quadrature -- note the factor in the front\n# is a result of the change of variables from x -> z\nintegral = 0.5*(b-a)*( w1*f(x1) + w2*f(x2) + w3*f(x3) + w4*f(x4) + w5*f(x5) )\n\nprint \"exact:                  \", true(a,b)\nprint \"5-point Simpson's:      \", I_S, I_S-true(a,b)\nprint \"5-point Gauss-Legendre: \", integral, integral-true(a,b)\n\n", "meta": {"hexsha": "ab5d582995e55d06473796523e6abc210a1033c0", "size": 2427, "ext": "py", "lang": "Python", "max_stars_repo_path": "others/differentiation_integration/gauss-poly.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "others/differentiation_integration/gauss-poly.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/differentiation_integration/gauss-poly.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 21.4778761062, "max_line_length": 77, "alphanum_fraction": 0.5467655542, "include": true, "reason": "import numpy", "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542817548989, "lm_q2_score": 0.8918110562208682, "lm_q1q2_score": 0.8553843930906047}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport xlrd\n\n\ndef gradient_descent(X, Y, alpha=0.01, converge_criteria=0.0001, max_epoch=10000):\n    converged = False\n    epoch = 0\n\n    # Number of datasets\n    m = X.shape[0]\n\n    # Initial thetas to 0\n    theta0 = 0\n    theta1 = 0\n\n    # Total error, J(theta)\n    J = (1.0 / (2.0 * m)) * sum([ (theta0 + theta1 * X[i] - Y[i]) ** 2 for i in range(m)])\n\n    while not converged:\n        # For each training sample, compute the gradient\n        gradient0 = (1.0 / m) * sum([(theta0 + theta1 * X[i] - Y[i]) for i in range(m)])\n        gradient1 = (1.0 / m) * sum([(theta0 + theta1 * X[i] - Y[i]) * X[i] for i in range(m)])\n\n        # Update the temporary thetas\n        tmp0 = theta0 - alpha * gradient0\n        tmp1 = theta1 - alpha * gradient1\n\n        # Update thetas\n        theta0 = tmp0\n        theta1 = tmp1\n\n        # Mean squared error\n        error = (1.0 / (2.0 * m)) * sum([(theta0 + theta1 * X[i] - Y[i]) ** 2 for i in range(m)])\n\n        print(\"Epoch = {0}, Cost = {1}\".format(epoch, error.item(0)))\n\n        if abs(J - error) <= converge_criteria:\n            print('Converged, epochs: ', epoch, '!!!')\n            converged = True\n\n        J = error  # Update error\n        epoch += 1  # Update epoch\n\n        if epoch == max_epoch:\n            print('Maximum number of epochs exceeded!')\n            converged = True\n\n    return theta0.item(0), theta1.item(0)\n\n\n''' \nStep 1: Read in data from the .xls file\n'''\nDATA_FILE = 'data/fire_theft.xls'\n\nbook = xlrd.open_workbook(DATA_FILE, encoding_override='utf-8')\nsheet = book.sheet_by_index(0)\n\nnumber_of_rows = len(list(sheet.get_rows()))\ndata = np.asarray([sheet.row_values(i) for i in range(1, number_of_rows)])\nnumber_of_samples = number_of_rows - 1\n\n'''\nStep 2: Compute the gradients\n'''\nX, Y = np.matrix(data.T[0]).T, np.matrix(data.T[1]).T\n\ntheta0, theta1 = gradient_descent(X, Y, alpha=0.001,\n                                  converge_criteria=0.0000001, max_epoch=300000)\n\nprint(\"theta0 = {0}, theta1 = {1}\".format(theta0, theta1))\n\n'''\nStep 3: Plot the results\n'''\n\n# Graphic display\nplt.plot(data.T[0], data.T[1], 'ro', label='Original data')\nplt.plot(data.T[0], theta0 + theta1 * data.T[0], 'b', label='Fitted line')\nplt.xlabel('fire per 1000 housing units')\nplt.ylabel('theft per 1000 population')\nplt.legend()\nplt.show()\n\n", "meta": {"hexsha": "ff68f7f344861c2258fb1b560c608dee91ae2655", "size": 2352, "ext": "py", "lang": "Python", "max_stars_repo_path": "day3/lab-guide-ans/lab2-problem6.py", "max_stars_repo_name": "WhatTheFar/practical-ai-bootcamp", "max_stars_repo_head_hexsha": "e2fe013390c00df0a5486795a737d7b777266f35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day3/lab-guide-ans/lab2-problem6.py", "max_issues_repo_name": "WhatTheFar/practical-ai-bootcamp", "max_issues_repo_head_hexsha": "e2fe013390c00df0a5486795a737d7b777266f35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day3/lab-guide-ans/lab2-problem6.py", "max_forks_repo_name": "WhatTheFar/practical-ai-bootcamp", "max_forks_repo_head_hexsha": "e2fe013390c00df0a5486795a737d7b777266f35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3488372093, "max_line_length": 97, "alphanum_fraction": 0.5948129252, "include": true, "reason": "import numpy", "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.891811053345418, "lm_q1q2_score": 0.8553843924151183}}
{"text": "\"\"\" Orbital Mechanics for Engineering Students Example 1.13\r\nQuestion:\r\nGiven:\r\n    - Position, velocity, and acceleration of the origin O (RO,VO,AO)\r\n    - Angular velocity and acceleration of moving frame (Omega, OmegaDot)\r\n    - Unit vectors of the moving frame (iHat, jHat, kHat)\r\n    - Absolute position, velocity, and acceleration of P (R,V,A)\r\nFind:\r\n    (a) The velocity Vrel of P relative to the moving frame\r\n    (b) The acceleration Arel of P relative to the moving frame\r\nWritten by: J.X.J. Bannwarth\r\n\"\"\"\r\nfrom numpy import array, cross, dot, vstack\r\nfrom numpy.linalg import inv\r\n\r\ndef PrintVec(v, name, unit = '', inertial=True):\r\n    if inertial:\r\n        print(f\"{name} = {v[0]:.4f} I + {v[1]:.4f} J + {v[2]:.4f} K {unit}\")\r\n    else:\r\n        print(f\"{name} = {v[0]:.4f} i + {v[1]:.4f} j + {v[2]:.4f} k {unit}\")\r\n\r\n# Title\r\nprint(\"Orbital Mechanics for Engineering Students Example 1.13\")\r\n\r\n# Origin\r\nRO = array([100.,200.,300.]) # m\r\nVO = array([-50.,30.,-10.]) # m/s\r\nAO = array([-15.,40.,25.]) # m/s^2\r\n\r\n# Moving frame\r\nOmega    = array([1.0,-0.4,0.6]) # rad/s\r\nOmegaDot = array([-1.0,0.3,-0.4]) # rad/s^2\r\n\r\n# Unit vectors\r\n# <>Hat = x*IHat + y*JHat + z*KHat\r\niHat = array([0.5571,0.7428,0.3714])\r\njHat = array([-0.06331,0.4839,-0.8728])\r\nkHat = array([-0.8280,0.4627,0.3166])\r\n\r\n# Construct DCM from unit vectors\r\nDCM = vstack((iHat,jHat,kHat))\r\n\r\n# Absolute values\r\nR = array([300.,-100.,150.]) # m\r\nV = array([70.,25.,-20]) # m/s\r\nA = array([7.5,-8.5,6.0]) # m/s^2\r\n\r\n# (a)\r\nprint(\"Inertial frame: (I,J,K), moving frame: (i,j,k)\")\r\nprint(\"(a)\")\r\nRrel = R - RO\r\nPrintVec(Rrel, \"R_rel\", \"m\")\r\n\r\nVrel = V - VO - cross(Omega,Rrel)\r\nPrintVec(Vrel, \"V_rel\", \"m/s\")\r\nPrintVec(dot(DCM,Vrel), \"V_rel\", \"m/s\", False)\r\n\r\n# (b)\r\nprint(\"b\")\r\nArel = A - AO - cross(OmegaDot,Rrel) - cross(Omega,cross(Omega,Rrel)) - 2*cross(Omega,Vrel)\r\nPrintVec(Arel, \"A_rel\", \"m/s^2\")\r\nPrintVec(dot(DCM,Arel), \"A_rel\", \"m/s^2\", False)\r\n", "meta": {"hexsha": "1e6938337ef0b3173625299626ace373c4b21c2a", "size": 1933, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapter1/example_1_13.py", "max_stars_repo_name": "JBannwarth/OrbitalMechanics", "max_stars_repo_head_hexsha": "fe3c36eba7cadf977804fb2ad866e0e28a96aab5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-29T13:34:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-29T13:34:48.000Z", "max_issues_repo_path": "chapter1/example_1_13.py", "max_issues_repo_name": "JBannwarth/OrbitalMechanics", "max_issues_repo_head_hexsha": "fe3c36eba7cadf977804fb2ad866e0e28a96aab5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-06T21:17:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-07T00:52:39.000Z", "max_forks_repo_path": "chapter1/example_1_13.py", "max_forks_repo_name": "JBannwarth/OrbitalMechanics", "max_forks_repo_head_hexsha": "fe3c36eba7cadf977804fb2ad866e0e28a96aab5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6825396825, "max_line_length": 92, "alphanum_fraction": 0.6006207967, "include": true, "reason": "from numpy", "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542817548989, "lm_q2_score": 0.8918110555020057, "lm_q1q2_score": 0.8553843924011045}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nVisualizing the Mandelbrot Set Using Python by Blake Sanie, Nov 29, 2020.\nhttps://medium.com/swlh/visualizing-the-mandelbrot-set-using-python-50-lines-f6aa5a05cf0f\n\nUse Python Numba for C-like performance, Jan 11, 2022.\nPart 2 of 4 Apply Anti-Aliasing.\n\"\"\"\n\nfrom numba import njit, int16\nfrom timeit import default_timer as timer\nimport numpy as np\nimport os, sys\n\njit_start = timer()\n\nsys.path.insert(0, os.path.dirname(__file__))\nfrom ex1 import width, height, precision, minX, maxY, xRange, yRange\nfrom ex1 import hsv_to_rgb, powerColor, save_image\n\n@njit('b1(u1[:], u1[:])', nogil=True)\ndef check_colors(c1, c2):\n    # return false if the colors are within tolerance\n    if abs(int16(c2[0]) - c1[0]) > 8: return True\n    if abs(int16(c2[1]) - c1[1]) > 8: return True\n    if abs(int16(c2[2]) - c1[2]) > 8: return True\n    return False\n\n@njit('i4(f8, f8)', nogil=True)\ndef mandel(x, y):\n    oldX = x\n    oldY = y\n    for i in range(precision + 1):\n        a = x*x - y*y # real component of z^2\n        b = 2 * x * y # imaginary component of z^2\n        x = a + oldX  # real component of new z\n        y = b + oldY  # imaginary component of new z\n        if x*x + y*y > 4:\n            break\n    return i\n\n@njit('void(u1[:,:,:])', nogil=True)\ndef mandelbrot1(pixels):\n    for row in range(height):\n        for col in range(width):\n            x = minX + col * xRange / width\n            y = maxY - row * yRange / height\n            i = mandel(x, y)\n            if i < precision:\n                distance = (i + 1) / (precision + 1)\n                pixels[row, col] = powerColor(distance, 0.2, 0.27, 1.0)\n\n@njit('void(u1[:,:,:], u1[:,:,:])', nogil=True)\ndef mandelbrot2(pixels1, pixels2):\n    aafactor = 7 # 7x7\n    aareach1 = int(aafactor / 2.0)\n    aareach2 = aareach1 + 1 if (aafactor % 2) else aareach1\n    aaarea = int(aafactor * aafactor)\n    aafactorinv = float(1.0 / aafactor)\n\n    for row in range(height):\n        c = np.empty((3,), dtype=np.int32)\n\n        for col in range(width):\n            c1 = pixels1[row, col]\n            count = False\n\n            # skip AA for colors within tolerance\n            if not count and col > 0:\n                count = check_colors(c1, pixels1[row, col - 1])\n            if not count and col + 1 < width:\n                count = check_colors(c1, pixels1[row, col + 1])\n            if not count and col > 1:\n                count = check_colors(c1, pixels1[row, col - 2])\n            if not count and col + 2 < width:\n                count = check_colors(c1, pixels1[row, col + 2])\n\n            if not count and row > 0:\n                count = check_colors(c1, pixels1[row - 1, col])\n            if not count and row + 1 < height:\n                count = check_colors(c1, pixels1[row + 1, col])\n            if not count and row > 1:\n                count = check_colors(c1, pixels1[row - 2, col])\n            if not count and row + 2 < height:\n                count = check_colors(c1, pixels1[row + 2, col])\n\n            if not count:\n                pixels2[row, col] = c1\n                continue\n\n            # compute AA\n            c[:] = c1\n\n            for yi in range(-aareach1, aareach2, 1):\n                y = maxY - (row + yi*aafactorinv) * yRange / height\n\n                for xi in range(-aareach1, aareach2, 1):\n                    if (xi | yi) == 0: continue\n                    x = minX + (col + xi*aafactorinv) * xRange / width\n\n                    i = mandel(x, y)\n                    if i < precision:\n                        distance = (i + 1) / (precision + 1)\n                        r, g, b = powerColor(distance, 0.2, 0.27, 1.0)\n                        c[0] += r; c[1] += g; c[2] += b\n\n            c2 = int(c[0]/aaarea), int(c[1]/aaarea), int(c[2]/aaarea)\n            pixels2[row, col] = c2\n\nif __name__ == '__main__':\n    print(\"     jit time {:.3f} seconds\".format(timer() - jit_start))\n    pixels1 = np.empty((height, width, 3), dtype=np.uint8)\n    pixels2 = np.empty((height, width, 3), dtype=np.uint8)\n\n    s = timer()\n    mandelbrot1(pixels1)\n    print(\"   mandelbrot {:.3f} seconds\".format(timer() - s))\n\n    s = timer()\n    mandelbrot2(pixels1, pixels2)\n    print(\"anti-aliasing {:.3f} seconds\".format(timer() - s))\n\n    save_image(pixels2, \"img2.png\", show_image=False)\n\n", "meta": {"hexsha": "d5f8b3e0a4c40513be0a23996207a7bef199c81b", "size": 4303, "ext": "py", "lang": "Python", "max_stars_repo_path": "demo/ex2.py", "max_stars_repo_name": "marioroy/mandelbrot-python", "max_stars_repo_head_hexsha": "ec77db4363582689365dca1a10baddbe1647f176", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-08T17:35:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T17:35:06.000Z", "max_issues_repo_path": "demo/ex2.py", "max_issues_repo_name": "marioroy/mandelbrot-python", "max_issues_repo_head_hexsha": "ec77db4363582689365dca1a10baddbe1647f176", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo/ex2.py", "max_forks_repo_name": "marioroy/mandelbrot-python", "max_forks_repo_head_hexsha": "ec77db4363582689365dca1a10baddbe1647f176", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1507936508, "max_line_length": 89, "alphanum_fraction": 0.5405531025, "include": true, "reason": "import numpy,from numba", "num_tokens": 1324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542794197472, "lm_q2_score": 0.8918110569397307, "lm_q1q2_score": 0.8553843916975905}}
{"text": "import numpy as np\n\nfrom numpy import linalg\n\nA = np.array([[3, -1, 4], [-1, 0, -1], [4, -1, 2]])\n\nv, B = linalg.eig(A)\n\ni = 0  # first eigenvalue/eigenvector pair\nlambda0 = v[i]\nprint(lambda0)\n# 6.823156164525971\nx0 = B[:, i]  # ith column of B\nprint(x0)\n# array([ 0.73271846, -0.20260301, 0.649672352])\n\nlinalg.norm(x0)  # 1.0  - eigenvalues are normalised.\n\n\nlhs = A @ x0\nrhs = lambda0*x0\nlinalg.norm(lhs - rhs)  # 2.8445583831733384e-15 - very small.\n\n", "meta": {"hexsha": "01de577623a2a165f17ce8ee2ac8be66a528003b", "size": 456, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter 01/eigenvalus-and-eigenvectors.py", "max_stars_repo_name": "arifmudi/Applying-Math-with-Python", "max_stars_repo_head_hexsha": "abeb6b0a9bcfa8b21092b9793d4e691cf5a146bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2020-07-23T14:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T07:00:17.000Z", "max_issues_repo_path": "Chapter 01/eigenvalus-and-eigenvectors.py", "max_issues_repo_name": "arifmudi/Applying-Math-with-Python", "max_issues_repo_head_hexsha": "abeb6b0a9bcfa8b21092b9793d4e691cf5a146bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 01/eigenvalus-and-eigenvectors.py", "max_forks_repo_name": "arifmudi/Applying-Math-with-Python", "max_forks_repo_head_hexsha": "abeb6b0a9bcfa8b21092b9793d4e691cf5a146bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2020-07-22T11:09:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T16:59:53.000Z", "avg_line_length": 19.0, "max_line_length": 62, "alphanum_fraction": 0.6381578947, "include": true, "reason": "import numpy,from numpy", "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211582993981, "lm_q2_score": 0.8774767922879692, "lm_q1q2_score": 0.8553829430389984}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr  2 22:01:04 2020\n\n@author: guanfang\n\"\"\"\n\nimport pandas as pds\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass LeastSquaresEstimation():\n    def __init__(self, method='OLS'):\n        self.method = method\n\n    def fit_line(self, x, y):\n        x = np.array(x).reshape(-1, 1)\n        # add a column which is all 1s to calculate bias of linear function\n        x = np.c_[np.ones(x.size).reshape(-1, 1), x]\n        y = np.array(y).reshape(-1, 1)\n        if self.method == 'OLS':\n            w = np.linalg.inv(x.transpose().dot(x)).dot(x.transpose()).dot(y)\n            b = w[0][0]\n            w = w[1][0]\n            return w, b\n\n    def fit_polynomial(self, x, y, d):\n        x_org = np.array(x).reshape(-1, 1)\n        # add a column which is all 1s to calculate bias of linear function\n        x = np.c_[np.ones(x.size).reshape(-1, 1), x_org]\n        x_org_d = x_org\n        for i in range(1, d):\n            x_org_d = x_org_d * x_org\n            x = np.c_[x, x_org_d]\n        y = np.array(y).reshape(-1, 1)\n        w = np.linalg.inv(x.transpose().dot(x)).dot(x.transpose()).dot(y)\n        return w\n\n\ndef polynomial(w, x, d):\n    w = np.array(w).reshape(-1, 1)\n    x = np.array(x).reshape(-1, 1)\n    x_org_d = x\n    X = np.ones(x.size).reshape(-1, 1)\n    X = np.c_[X, x_org_d]\n    for i in range(1, d):\n        x_org_d = x_org_d * x\n        X = np.c_[X, x_org_d]\n    return X.dot(w)\n\n\nif __name__ == '__main__':\n    data_file = pds.read_csv('/home/guanfang/Desktop/ML-master/Linear Regression/data/baby.csv')\n    lse = LeastSquaresEstimation()\n    x = data_file['male']\n    y = data_file['female']\n    #w, b = lse.fit_line(x, y)   # linear regression parameter x and y\n    weights_polynomial = lse.fit_polynomial(x, y, d=2)\n    # day_0 = x[0]\n    # day_end = list(x)[-1]\n    # days = np.array([day_0,day_end])\n\n    plt.scatter(x, y, c='r', s=30, label='y', marker='o', alpha=0.3)\n\n    plt.scatter(x, polynomial(weights_polynomial, x, d=2), c='b', marker='x', alpha=0.5)\n    plt.plot(x, polynomial(weights_polynomial, x, d=2), c=\"b\", label='polynomial', alpha=0.7)\n    plt.plot()\n    plt.xlabel('x')\n    plt.ylabel('y')\n    plt.legend()\n    plt.show()\n", "meta": {"hexsha": "265788aa068374837431101644a9ec0f200a0398", "size": 2228, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear regression_polynimial.py", "max_stars_repo_name": "sherlockguan/machine-learning-and-deep-learning-", "max_stars_repo_head_hexsha": "a34d8ab756dab8f0f220062ce708dee78c7b2f04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-17T09:35:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-17T09:35:50.000Z", "max_issues_repo_path": "linear regression_polynimial.py", "max_issues_repo_name": "sherlockguan/machine-learning-and-deep-learning-", "max_issues_repo_head_hexsha": "a34d8ab756dab8f0f220062ce708dee78c7b2f04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear regression_polynimial.py", "max_forks_repo_name": "sherlockguan/machine-learning-and-deep-learning-", "max_forks_repo_head_hexsha": "a34d8ab756dab8f0f220062ce708dee78c7b2f04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5205479452, "max_line_length": 96, "alphanum_fraction": 0.5713644524, "include": true, "reason": "import numpy", "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211597623861, "lm_q2_score": 0.8774767890838836, "lm_q1q2_score": 0.8553829411993261}}
{"text": "from sympy import *\r\nfrom math import pi\r\n\r\nfunction = sympify(input(\"Enter a function: \"))\r\nlower_bound, upper_bound = tuple(eval(input(\"Enter an interval: \")))\r\nevaluation_point = float(input(\"Enter the point that you want to evaluate the function in: \"))\r\norder = int(input(\"Enter the order of series: \"))\r\nassert lower_bound == - upper_bound\r\nperiod = (abs(lower_bound) + abs(upper_bound)) / 2\r\nx = symbols(\"x\")\r\na_0 = (1 / period) * integrate(function, (x, lower_bound, upper_bound)).doit(simplify=True)\r\n\r\n\r\ndef power_series(i):\r\n\r\n    def a_n(n):\r\n        n = n * pi / period\r\n        return (1 / period) * integrate(Mul(function, sympify(\"cos({} * x)\".format(n))), (x, lower_bound, upper_bound))\r\n\r\n    def b_n(n):\r\n        n = n * pi / period\r\n        return (1 / period) * integrate(Mul(function, sympify(\"sin({} * x)\".format(n))), (x, lower_bound, upper_bound))\r\n\r\n    freq = i * pi / period\r\n    return Add(Mul(a_n(i), sympify(\"cos({}*x)\".format(freq))), Mul(b_n(i),  sympify(\"sin({}*x)\".format(freq))))\r\n\r\n\r\nfourier_series = (1 / 2) * a_0 + sum([power_series(i) for i in range(1, order + 1)])\r\nprint(\"\\nfourier series of f(x) = {}:\\n\".format(function), fourier_series,\r\n      \"\\nevaluated value at x = {} is: \".format(evaluation_point), fourier_series.subs(x, evaluation_point).evalf())\r\n", "meta": {"hexsha": "2fca9cd0364be378974a6b95b3565c826cfc1b52", "size": 1301, "ext": "py", "lang": "Python", "max_stars_repo_path": "fourier series.py", "max_stars_repo_name": "arash79/Numerical-methods", "max_stars_repo_head_hexsha": "f1dd455916c92d2c2a2e5909fa26cef67e39f346", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fourier series.py", "max_issues_repo_name": "arash79/Numerical-methods", "max_issues_repo_head_hexsha": "f1dd455916c92d2c2a2e5909fa26cef67e39f346", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fourier series.py", "max_forks_repo_name": "arash79/Numerical-methods", "max_forks_repo_head_hexsha": "f1dd455916c92d2c2a2e5909fa26cef67e39f346", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9677419355, "max_line_length": 120, "alphanum_fraction": 0.6333589547, "include": true, "reason": "from sympy", "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211582993982, "lm_q2_score": 0.8774767890838836, "lm_q1q2_score": 0.8553829399155881}}
{"text": "import math\nimport numpy as np\n\ngauss = [\n        [-7,2,-3,4,-12],\n        [5,-1,14,-1,13],\n        [1,9,-7,13,31],\n        [-12,13,-8,-4,-32]\n        ]\n\nn = len(gauss)\n\ndef changeRows(majorRow,k):\n    for i in range(0,len(gauss)+1):\n        aux = gauss[k][i]\n        gauss[k][i] = gauss[majorRow][i]\n        gauss[majorRow][i]= aux\n\ndef pivoting(k):\n    major = math.fabs(gauss[k][k])\n    majorRow = k\n    for s in range(k+1,n):\n        if (math.fabs(gauss[s][k]) > major):\n            major = math.fabs(gauss[s][k])\n            majorRow = s\n        \n    if(major == 0):\n        print(\"division 0\")\n        return;\n    elif(majorRow != k):\n        changeRows(majorRow,k)\n\ndef elimination():\n    for k  in range(0,n-1):\n        pivoting(k)\n        for i  in range (k + 1, n):\n            multiplicator = gauss[i][k]/gauss[k][k]\n            for j in range (k,n + 1):\n                gauss[i][j] = gauss[i][j]-(multiplicator*gauss[k][j])\n\n    sustitution()\n\ndef sustitution():\n    n = len(gauss) -1\n    x = [i for i in range(n+1)]\n    x[len(x)-1] = gauss[n][n+1]/gauss[n][n]\n    print(x[len(x)-1])\n    \n    for i in range(0,n+1):\n        summation = 0\n        auxi = n - i \n        summation = 0\n        for p in range(auxi+1,n+1):\n            summation = summation + gauss[auxi][p]*x[p]\n        x[auxi]=(gauss[auxi][n+1]-summation)/gauss[auxi][auxi]\n    print(x)\n            \n\nelimination()\nfor i in gauss:\n    print(i)\n\n", "meta": {"hexsha": "aab2d7748451d333154fe61aafd4cd2da93d6fc6", "size": 1420, "ext": "py", "lang": "Python", "max_stars_repo_path": "EquationSystems/PartialPivoting/partialPivotingMethod.py", "max_stars_repo_name": "stivenramireza/numericalanalysis", "max_stars_repo_head_hexsha": "7f2fe2b43ac41bccf3c41d3f936522619d009927", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-19T17:18:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-21T04:01:07.000Z", "max_issues_repo_path": "EquationSystems/PartialPivoting/partialPivotingMethod.py", "max_issues_repo_name": "stivenramireza/numerical-methods", "max_issues_repo_head_hexsha": "7f2fe2b43ac41bccf3c41d3f936522619d009927", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EquationSystems/PartialPivoting/partialPivotingMethod.py", "max_forks_repo_name": "stivenramireza/numerical-methods", "max_forks_repo_head_hexsha": "7f2fe2b43ac41bccf3c41d3f936522619d009927", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-23T17:20:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-23T17:20:22.000Z", "avg_line_length": 22.5396825397, "max_line_length": 69, "alphanum_fraction": 0.4873239437, "include": true, "reason": "import numpy", "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290955604489, "lm_q2_score": 0.880797085800514, "lm_q1q2_score": 0.8553676773057323}}
{"text": "import numpy as np\n\n\ndef zakharov_func(x, d):\n    \"\"\"\n    Compute Zakharov function at a given point with given arguments.\n\n    Parameters\n    ----------\n    point : 1-D array with shape (d, )\n            A point used to evaluate the function.\n    d : integer\n        Dimension\n\n    Returns\n    -------\n    function value : float\n    \"\"\"\n    s_1 = np.sum(x ** 2)\n    s_2 = (0.5 * np.arange(1, d + 1)).T @  x\n    return s_1 + s_2 ** 2 + s_2 ** 4\n\n\ndef zakharov_grad(x, d):\n    \"\"\"\n    Compute Zakharov gradient at a given point with given arguments.\n\n    Parameters\n    ----------\n    point : 1-D array with shape (d, )\n            A point used to evaluate the function.\n    d : integer\n        Dimension\n\n    Returns\n    -------\n    grad : 1-D array with shape (d,)\n    \"\"\"\n    s_2 = (0.5 * np.arange(1, d + 1)).T @  x\n    grad = (2 * x + np.arange(1, d + 1) *\n            s_2 + 2 * np.arange(1, d + 1) * (s_2 ** 3))\n    return grad\n", "meta": {"hexsha": "64883d5c12f6bb7a79d20ed721658ce3945e4de3", "size": 933, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/metod_alg/objective_functions/zakharov.py", "max_stars_repo_name": "Megscammell/METOD-Algorithm", "max_stars_repo_head_hexsha": "7518145ec100599bddc880f5f52d28f9a3959108", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/metod_alg/objective_functions/zakharov.py", "max_issues_repo_name": "Megscammell/METOD-Algorithm", "max_issues_repo_head_hexsha": "7518145ec100599bddc880f5f52d28f9a3959108", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-17T09:03:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-17T09:03:17.000Z", "max_forks_repo_path": "src/metod_alg/objective_functions/zakharov.py", "max_forks_repo_name": "Megscammell/METOD-Algorithm", "max_forks_repo_head_hexsha": "7518145ec100599bddc880f5f52d28f9a3959108", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6976744186, "max_line_length": 68, "alphanum_fraction": 0.5155412647, "include": true, "reason": "import numpy", "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290947248701, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.8553676583374721}}
{"text": "from math import factorial as fac, sqrt\nfrom scipy.integrate import quad\nimport numpy as np\n\ndef integrand(t):\n    \"\"\"\n    Integrand of the cumulative function, used to compute phi(Z).\n    \"\"\"\n    return np.exp(-(t**2)/2)\n\ndef phi(z):\n    \"\"\"\n    Cumulative function as described in Wikipedia, for the computation\n    of the probability of a statistic being less than  Z.\n    \"\"\"\n    return (1/(sqrt(2*np.pi))) * quad(integrand, -np.inf, z)[0]\n\ndef complementary_cumulative(z):\n    \"\"\"\n    Returns the complementary cumulative probability for @param Z-score.\n    This gives the odds for an event X > Z in the Standard Normal Table.\n    \"\"\"\n    return 1 - phi(z)\n\ndef r_to_z(r, mu, std):\n    \"\"\"\n    Returns the Z-score of some value 'r', normalized with the Standard\n    Normal Table.\n    \"\"\"\n    return (r - mu) / std\n\ndef z_to_r(z, mu, std):\n    \"\"\"\n    Returns the 'r' value, corresponding to the original distribution,\n    given from a Z-score in the Standard Normal Table.\n    \"\"\"\n    return z*std + mu\n\ndef chance_exactly_k(k, n, p):\n    \"\"\"\n    Returns the success chance of an event with probability 'p' to\n    occur exactly 'k' in 'n' trials.\n    \"\"\"\n    return (fac(n)/(fac(k)*fac(n-k))) * p**k * (1-p)**(n-k)\n\ndef chance_exactly_once(n,p):\n    \"\"\"\n    Returns the chance of an event with probability 'p' to occur EXACLTY\n    once in 'n' trials.\n    \"\"\"\n    chance_exaclty_k(1,n,p)\n\ndef at_least_one_in_n(p, n):\n    \"\"\"\n    Returns the success probability of an event with independent \n    probability 'p' in 'n' trials.\n    to\n    \"\"\"\n    assert(p > 0 and p < 1 and n > 0)\n    return 1 - (1-p)**n\n\ndef at_least_one_with_prob(event_p, success_p, threshold=20000):\n    \"\"\"\n    Returns the number of trials needed for an independent event with \n    probability 'event_p' to occur at least one time with a probability\n    of 'success_p'.\n    \"\"\"\n    assert(event_p >0 and event_p < 1 and success_p > 0 and success_p < 1)\n    n = 1\n    while(at_least_one_in_n(event_p, n) < success_p):\n        n += 1\n    if n == threshold:\n        return -1\n    return n\n\n\ndef average_chance(p):\n    return 1/p\n\n\nif __name__ == \"__main__\":\n\n    w = 2**16\n    mu = 32774\n    std = 4730\n\n    print(\"mean = %d\"%(mu))\n    print(\"std = %d\"%(std))\n    mui = mu*1.2\n\n    print(\"For 20 increase, mean = %f\"%(mui))\n    z = r_to_z(mui,mu,std)\n    print(\"%d to z = %f)\"%(mui, z))\n    p = complementary_cumulative(z)\n    print(\"p( mu > %d ) = %f\"%(mui, p))\n    print(\"In average, event will occur after %f trials\"%(average_chance(p)))\n    print(\"The event will occur at least once, with 95 chance, after %d trials\"%(at_least_one_with_prob(p, 0.95)))\n    print(\"The event will occur at least once, with 99 chance, after %d trials\"%(at_least_one_with_prob(p, 0.99)))\n\n    print(\"\\n ================= \\n\")\n    mui = mu*1.435\n    print(\"For 30 increase, mean = %f\"%(mui))\n    z = r_to_z(mui,mu,std)\n    print(\"%d to z = %f)\"%(mui, z))\n    p = complementary_cumulative(z)\n    print(\"p( mu > %d ) = %f\"%(mui, p))\n    print(\"In average, event will occur after %f trials\"%(average_chance(p)))\n    print(\"The event will occur at least once, with 95 chance, after %d trials\"%(at_least_one_with_prob(p, 0.95)))\n    print(\"The event will occur at least once, with 99 chance, after %d trials\"%(at_least_one_with_prob(p, 0.99)))\n\n    print(\"\\n ================= \\n\")\n\n    moment1 = 0\n    p = 1/(2**16)\n    for i in range(2**16):\n        moment1 +=(i*p)\n    moment2 = 0\n    for i in range(2**16):\n        moment2 +=(i**2)*p\n    print(moment1, moment2, sqrt(moment2), sqrt(moment2)-moment1)\n\n    first_central=0\n    for i in range(2**16):\n        first_central += (i-moment1)*p\n\n    print(first_central)\n\n    second_central=0\n    for i in range(2**16):\n        second_central += ((i-first_central)**2)*p\n    print(second_central, sqrt(second_central))\n\n    print(\"==============\")\n    m = 0\n    p = 1/(2**16)\n    for i in range(2**16):\n        m +=(i**2 - i)\n    print(p*m, sqrt(p*m))\n\n    print(\"\\n ================= \\n\")\n\n    moment1 = 0\n    p = 1/(2**16)\n    for i in range(2**16):\n        moment1 +=(i*p)\n    moment2 = 0\n    for i in range(2**16):\n        moment2 +=(i**2)*p\n    print(sqrt(moment2- moment1**2))\n\n    print(\"\\n ================= Panario\\n\")\n\n    var = 0\n    for i in range(2**16):\n        var +=(p-2**15)**2\n    v = var*p\n\n    print(sqrt(v))\n", "meta": {"hexsha": "ca9225cc591498c337c068d55a4a237adf8244cf", "size": 4324, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/stats.py", "max_stars_repo_name": "lucasperin/WOTS", "max_stars_repo_head_hexsha": "88f09cf070839595190a3a495c4af8b0b8358172", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/stats.py", "max_issues_repo_name": "lucasperin/WOTS", "max_issues_repo_head_hexsha": "88f09cf070839595190a3a495c4af8b0b8358172", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/stats.py", "max_forks_repo_name": "lucasperin/WOTS", "max_forks_repo_head_hexsha": "88f09cf070839595190a3a495c4af8b0b8358172", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1949685535, "max_line_length": 114, "alphanum_fraction": 0.585106383, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241991754918, "lm_q2_score": 0.8824278680004707, "lm_q1q2_score": 0.8553586864796928}}
{"text": "import numpy as np\nfrom scipy.io import loadmat\nimport matplotlib.pyplot as plt \n\nmat = loadmat('E:\\lessons\\ML wu.n.g\\coursera-ml-py-master\\coursera-ml-py-master\\machine-learning-ex7\\ex7\\ex7data1.mat')\n#print(mat.keys())\n#print(mat)\nX = mat['X']    #(50, 2)\n#print(X.shape)\nplt.figure(figsize=(8,8))\n#facecolor is pots' color\nplt.scatter(X[:,0],X[:,1], facecolors = 'none', edgecolors = 'r')\n#plt.show()\n\n#====================implementing pca\n\ndef featureNormalize(X):\n    means = X.mean(axis = 0)\n    #std ddof = 1 标准差是除以n - 1（无偏估计）\n    stds = X.std(axis = 0, ddof = 1)\n    X_norm = (X - means) / stds\n    return X_norm, means, stds\n\ndef pca(X):\n    sigma = (X.T @ X) / len(X)\n    U, S, V = np.linalg.svd(sigma)\n    return U, S, V\n\nX_norm, means, stds = featureNormalize(X)\nU, S, V = pca(X_norm)\nprint(X_norm.shape)\n#change to 1d , get the 1st column\nprint(U.shape,S.shape,V.shape)\nprint(U[:,0])\nplt.scatter(X[:,0], X[:,1], facecolors='none', edgecolors='b')\n\nplt.plot([means[0], means[0] + 5*S[0]*U[0,0]], \n         [means[1], means[1] + 5*S[0]*U[0,1]],\n        c='r', linewidth=3, label='First Principal Component')\nplt.plot([means[0], means[0] + 1.5*S[1]*U[1,0]], \n         [means[1], means[1] + 1.5*S[1]*U[1,1]],\n        c='g', linewidth=3, label='Second Principal Component')\nplt.grid(True)\nplt.legend()\n#plt.show()\n\n#======================Dimensionality Reduction with PCA\n\n#======projectData\ndef projectData(X, U, K):\n    Z = X @ U[:,:K]\n    return Z\n\nZ = projectData(X_norm, U, 1) #Z[0] 1.481\n#print(Z)\n\n#======Reconstructing an approximaion of the data(重现数据维度)\n\ndef recData(Z, U, K):\n    X_rev = Z @ U[:,:K].T\n    return X_rev\n\nX_rec = recData(Z, U, 1) #rec[0] = [-1.04741,-1.04741...]\n#print(X_rec)\n\n#======Visualizing\n\nplt.figure(figsize=(8,8))\n#x,y比例相同？？\nplt.axis(\"equal\")\nplt.scatter(X_norm[:,0], X_norm[:,1], s = 50, facecolors = 'none',\n            edgecolors='b', label = 'Original Data')\nplt.scatter(X_rec[:,0], X_rec[:,1], s=30, facecolors='none', \n            edgecolors='r',label='PCA Reduced Data Points')\nplt.title(\"reduced dimension show\", fontsize = 20)\nplt.xlabel(\"x1(Normalized)\", fontsize = 14)\nplt.ylabel(\"x2(Normalized)\", fontsize = 14)\nplt.grid(True)\n\n#给对应的点连线\nfor x in range(X_norm.shape[0]):\n    plt.plot([X_norm[x,0],X_rec[x,0]],[X_norm[x,1],X_rec[x,1]], 'k--')\nplt.legend()\n#plt.show()\n\n#===========================Face Image Dataset\n'''\nRun PCA in face images\n'''\nfacemat = loadmat('E:\\lessons\\ML wu.n.g\\coursera-ml-py-master\\coursera-ml-py-master\\machine-learning-ex7\\ex7\\ex7faces.mat')\n#print(facemat.keys())\nX_face = facemat['X']   #(5000, 1024)\n#print(X_face.shape)\n\n#show the data\ndef displayData(X, row, col):\n    fig, axs = plt.subplots(row, col, figsize=(10,10))\n    for r in range(row):\n        for c in range(col):\n            axs[r][c].imshow(X[r * col + c].reshape(32, 32).T, cmap = 'Greys_r')\n            axs[r][c].set_xticks([])\n            axs[r][c].set_yticks([])\n\ndisplayData(X_face, 10, 10)\n\n#PCA\nX_face_norm, face_means, face_stds = featureNormalize(X_face)\n\nU_face, S_face, V_face = pca(X_face_norm) #U(1024,1024)  S(1024,)\nprint(U_face.shape, S_face.shape, V_face.shape)\n\ndisplayData(X_face_norm, 6, 6)\n#plt.show()\n\n'U 的意义？？？？？？？？'\ndisplayData(U_face[:,:100].T,10,10)\n#plt.show()\n\n#==================Dimension Redcution\n\nz_face = projectData(X_face_norm, U_face, K = 36)\nX_face_rec = recData(z_face, U_face, K = 36)\n\ndisplayData(X_face_rec, 10, 10)\nplt.show()", "meta": {"hexsha": "22d950f5451310a380d89a574778a0fb8e730883", "size": 3416, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine-learning-ex7/OWNS/PCA.py", "max_stars_repo_name": "airflier/ML-wu.n.g-exercise", "max_stars_repo_head_hexsha": "377d2c52c3aa8ef6eda238a5347f1d000b6a2061", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "machine-learning-ex7/OWNS/PCA.py", "max_issues_repo_name": "airflier/ML-wu.n.g-exercise", "max_issues_repo_head_hexsha": "377d2c52c3aa8ef6eda238a5347f1d000b6a2061", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "machine-learning-ex7/OWNS/PCA.py", "max_forks_repo_name": "airflier/ML-wu.n.g-exercise", "max_forks_repo_head_hexsha": "377d2c52c3aa8ef6eda238a5347f1d000b6a2061", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.328, "max_line_length": 123, "alphanum_fraction": 0.6150468384, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241956308277, "lm_q2_score": 0.8824278664544912, "lm_q1q2_score": 0.8553586818532272}}
{"text": "''' The following python code helps the user to convert Coordinates from polar system to Cartesian system, or vice-versa'''\n\nimport numpy as np\t\t\t\t\n\ndef pol2cart(r, theta):         #function for converting polar to cartesian coordinates.\n\tx = r*np.cos(theta)\n\ty = r*np.sin(theta)\n\treturn (x,y)\n\ndef cart2pol(x, y):             #function for converting cartesian to polar coordinates.\n\tr = np.sqrt( x**2 + y**2 )\n\ttheta = np.arctan2(y, x)\n\treturn (r,theta)\n\n\nchoice = input(\"Enter 1 for polar to cartesian conversion, or 2 for cartesian to polar conversion: \")\n\nif choice == '1' :\n    r, theta = input(\"Enter polar coordinates r, theta (will be computed in radian) : \").split()\n    print (\"Cartesian Coordinates are (x,y) = \",pol2cart(float(r), float(theta)))\n\nelif choice == '2':\n    x, y = input(\"Enter cartesian coordinantes x,y: \").split()\n    print (\"Polar Coordinates are (r,theta) = \",cart2pol(float(x),float(y))) \n# In case a number other than 1 or 2 is entered\nelse :                 \n    print (\"INVALID CHOICE, CHOICE MUST BE 1 OR 2\")\n", "meta": {"hexsha": "fb1ba8052e26a2aedb250816a24b42168a127797", "size": 1045, "ext": "py", "lang": "Python", "max_stars_repo_path": "week1/Solutions/Co-ordinates_conversion.py", "max_stars_repo_name": "veds12/QSTP-Robotics_Automation_using_ROS", "max_stars_repo_head_hexsha": "4c7d6499ef2238d7e125d99141f62573ce9df37f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2020-05-11T06:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T11:17:33.000Z", "max_issues_repo_path": "week1/Solutions/Co-ordinates_conversion.py", "max_issues_repo_name": "veds12/QSTP-Robotics_Automation_using_ROS", "max_issues_repo_head_hexsha": "4c7d6499ef2238d7e125d99141f62573ce9df37f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-05-12T07:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-21T06:28:47.000Z", "max_forks_repo_path": "week1/Solutions/Co-ordinates_conversion.py", "max_forks_repo_name": "veds12/QSTP-Robotics_Automation_using_ROS", "max_forks_repo_head_hexsha": "4c7d6499ef2238d7e125d99141f62573ce9df37f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-05-10T16:40:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T11:14:54.000Z", "avg_line_length": 37.3214285714, "max_line_length": 123, "alphanum_fraction": 0.6593301435, "include": true, "reason": "import numpy", "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242000616578, "lm_q2_score": 0.8824278571786139, "lm_q1q2_score": 0.8553586767717828}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef cart2pol(x, y):\n    rho = np.sqrt(x**2 + y**2)\n    phi = np.arctan2(y, x)\n    return(rho, phi)\n\ndef pol2cart(rho, phi):\n    x = rho * np.cos(phi)\n    y = rho * np.sin(phi)\n    return(x, y)\n\n################################\n#initial conditions\n\nx_0 = 10\ny_0 = -50\nv_int = 1/10\n\nr_0 = [(x_0, 0)]\nv_0 = [(0, v_int)]\n\nr = r_0\nv = v_0\n\nh = x_0*v_int\np = h**2\nE_0 = .5*v_int**2-1/x_0\na = -1/(2*E_0)\ne = (1-p/a)**.5\nP = 2*np.pi*a**(3/2)\nt = P/1000\n\n##############################################\n#Exact Solution\n\ntheta_ex = np.arange(0, 2*np.pi+.01, 0.01)\nr_ex = p/(1-e*np.cos((theta_ex)))\n\ntheta_comp = np.arange(0, 2*np.pi+.01, 0.1)\nr_comp = p/(1-e*np.cos((theta_comp)))\n\n\n\n#############################################################\n#Graphing\nfig=plt.figure(1)\n\n\n#Exact Solution\nax1=fig.add_subplot(221, projection='polar')\nax1.plot(theta_ex, r_ex)\nax1.set_rmax(.5)\nax1.set_rticks([3, 6, 9, 12])  # less radial ticks\nax1.set_rlabel_position(-22.5)  # get radial labels away from plotted line\nax1.grid(True)\nax1.set_title(\"Kepler Solution\", va='bottom')\n\n\n##############################################\n#Cromer Algorithm\n\nfor i in range(0,int(P*100)):\n\tr_mag = (r[len(r)-1][0]**2+r[len(r)-1][1]**2)**.5\n\tacc = np.asarray((-r[len(r)-1][0]/r_mag**3,-r[len(r)-1][1]/r_mag**3))\n\t\t\n\tv.append(tuple(map(sum, zip(v[len(v)-1],acc*t))))\n\tv_add = np.asarray(v[len(v)-1])\n\tr.append(tuple(map(sum, zip(r[len(r)-1],v_add*t))))\n\nr = np.asarray(r)\nl = []\n\nfor i in r:\n\tl.append(cart2pol(i[0],i[1]))\n\nx_val = [x[0] for x in l]\ny_val = [x[1] for x in l]\n\n\n\n##############################################\n#Graphing Cromer Algorithm \n\nax2=fig.add_subplot(222, projection='polar')\nax2.plot(y_val,x_val)\nax2.plot(theta_comp, r_comp, 'o', markerfacecolor='none', markeredgecolor='r')\nax2.set_rmax(.5)\nax2.set_rticks([3, 6, 9, 12])  # less radial ticks\nax2.set_rlabel_position(-22.5)  # get radial labels away from plotted line\nax2.grid(True)\nax2.set_title(\"Cromer Algorithm\", va='bottom')\n\n###################################################\n#Cromer Energy\n\nr_mag = []\nv_mag = []\nE_t = []\ntime = []\ntimePeriod = []\nE_rat = []\nfor i in r:\n\tr_mag.append((i[0]**2+i[1]**2)**.5)\nfor i in v:\n\tv_mag.append((i[0]**2+i[1]**2)**.5)\nfor i in range(len(r_mag)):\n\tE_t.append(.5*v_mag[i]**2-1/r_mag[i])\nfor i in range(0,int(P*100)+1):\n\tx = i*t\n\ttime.append(x)\nfor i in time:\n\tx = i/P\n\ttimePeriod.append(x)\nfor i in range(len(E_t)):\n\tE_rat.append(E_t[i]/E_0-1)\n\nE_rat = E_rat[450:550]\ntimePeriod = timePeriod[450:550]\n\nfig2, ax5 = plt.subplots()\nax5.set_ylabel('E(t)/E_0-1')\nax5.set_xlabel('Time/Period')\nax5.set_title(\"Energy Ratio\")\nax5.plot(timePeriod,E_rat)\n\n##############################################\n#Runge-Kutta\nx_0 = 10\ny_0 = -50\nv_int = 1/10\n\nr_0 = [(x_0, 0)]\nv_0 = [(0, v_int)]\n\nr = r_0\nv = v_0\n\nfor i in range(0,int(P*100)):\n\tr_mag = (r[len(r)-1][0]**2+r[len(r)-1][1]**2)**.5\n\tacc = np.asarray((-r[len(r)-1][0]/r_mag**3,-r[len(r)-1][1]/r_mag**3))\n\t\n\tv_add = np.asarray(v[len(v)-1])\n\tr_add = np.asarray(r[len(r)-1])\n\t\n\tr.append(tuple(map(sum, zip(r[len(r)-1],v_add*t,.5*t**2*acc))))\t\n\n\tr_2 = r_add+.5*t*v_add\n\tr_mag2 = ((r_add[0]+.5*t*v_add[0])**2+(r_add[1]+.5*t*v_add[1])**2)**.5\n\tacc_2 = np.asarray((-r_2[0]/r_mag2**3,-r_2[1]/r_mag2**3))\n\t\n\t\n\tv.append(tuple(map(sum, zip(v[len(v)-1],t*acc_2))))\n\t\t\nr = np.asarray(r)\nl = []\n\nfor i in r:\n\tl.append(cart2pol(i[0],i[1]))\n\nx_val = [x[0] for x in l]\ny_val = [x[1] for x in l]\n\n#Graphing \n\nax3=fig.add_subplot(223, projection='polar')\nax3.plot(y_val,x_val)\nax3.plot(theta_comp, r_comp, 'o', markerfacecolor='none', markeredgecolor='r')\nax3.set_rmax(.5)\nax3.set_rticks([3, 6, 9, 12])  # less radial ticks\nax3.set_rlabel_position(-22.5)  # get radial labels away from plotted line\nax3.grid(True)\nax3.set_title(\"Runge-Kutta\", va='bottom')\n\n###################################################\n#Runge-Kutta Energy\n\nr_mag = []\nv_mag = []\nE_t = []\ntime = []\ntimePeriod = []\nE_rat = []\nfor i in r:\n\tr_mag.append((i[0]**2+i[1]**2)**.5)\nfor i in v:\n\tv_mag.append((i[0]**2+i[1]**2)**.5)\nfor i in range(len(r_mag)):\n\tE_t.append(.5*v_mag[i]**2-1/r_mag[i])\nfor i in range(0,int(P*100)+1):\n\tx = i*t\n\ttime.append(x)\nfor i in time:\n\tx = i/P\n\ttimePeriod.append(x)\nfor i in range(len(E_t)):\n\tE_rat.append(E_t[i]/E_0-1)\n\nE_rat = E_rat[450:550]\ntimePeriod = timePeriod[450:550]\n# fig2, ax5 = plt.subplots()\nax5.plot(timePeriod,E_rat)\n\n\n\n\n##############################################\n#Velocity Verlet\nx_0 = 10\ny_0 = -50\nv_int = 1/10\n\nr_0 = [(x_0, 0)]\nv_0 = [(0, v_int)]\n\nr = r_0\nv = v_0\n\n\nfor i in range(0,int(P*100)):\n\tr_mag = (r[len(r)-1][0]**2+r[len(r)-1][1]**2)**.5\n\tacc = np.asarray((-r[len(r)-1][0]/r_mag**3,-r[len(r)-1][1]/r_mag**3))\n\tv_add = np.asarray(v[len(v)-1])\n\tr_add = np.asarray(r[len(r)-1])\n\t\n\tr.append(tuple(map(sum, zip(r[len(r)-1],v_add*t,.5*t**2*acc))))\n\t\n\tr_mag2 = (r[len(r)-1][0]**2+r[len(r)-1][1]**2)**.5\n\tacc_2 = np.asarray((-r[len(r)-1][0]/r_mag2**3,-r[len(r)-1][1]/r_mag2**3))\n\t\n\tv.append(tuple(map(sum, zip(v[len(v)-1],.5*t*acc,.5*t*acc_2))))\n\t\t\nr = np.asarray(r)\nl = []\n\nfor i in r:\n\tl.append(cart2pol(i[0],i[1]))\n\nx_val = []\ny_val = []\n\nx_val = [x[0] for x in l]\ny_val = [x[1] for x in l]\n\n\n#Graphing \nax4=fig.add_subplot(224, projection='polar')\nax4.plot(y_val,x_val)\nax4.plot(theta_comp, r_comp, 'o', markerfacecolor='none', markeredgecolor='r')\nax4.set_rmax(.5)\nax4.set_rticks([3, 6, 9, 12])  # less radial ticks\nax4.set_rlabel_position(-22.5)  # get radial labels away from plotted line\nax4.grid(True)\nax4.set_title(\"Velocity Verlet\", va='bottom')\n\n\n\n###################################################\n#Velocity Verlet Energy\n\nr_mag = []\nv_mag = []\nE_t = []\ntime = []\ntimePeriod = []\nE_rat = []\nfor i in r:\n\tr_mag.append((i[0]**2+i[1]**2)**.5)\nfor i in v:\n\tv_mag.append((i[0]**2+i[1]**2)**.5)\nfor i in range(len(r_mag)):\n\tE_t.append(.5*v_mag[i]**2-1/r_mag[i])\nfor i in range(0,int(P*100)+1):\n\tx = i*t\n\ttime.append(x)\nfor i in time:\n\tx = i/P\n\ttimePeriod.append(x)\nfor i in range(len(E_t)):\n\tE_rat.append(E_t[i]/E_0-1)\n\nE_rat = E_rat[450:550]\ntimePeriod = timePeriod[450:550]\n# fig2, ax5 = plt.subplots()\nax5.plot(timePeriod,E_rat)\n\nplt.legend(('Cromer', 'Runge-Kutta', 'Velocity Verlet'), loc='upper right')\nplt.show()\n#################################################################\n\n\n\n\n", "meta": {"hexsha": "4bc3827d7a7567370f9e699a9c06d14a4942c31c", "size": 6279, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW1/Full.py", "max_stars_repo_name": "nherbert25/Computational-Physics", "max_stars_repo_head_hexsha": "6fc01cf7bee566ca1e095877cc10d63bd678e21f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW1/Full.py", "max_issues_repo_name": "nherbert25/Computational-Physics", "max_issues_repo_head_hexsha": "6fc01cf7bee566ca1e095877cc10d63bd678e21f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW1/Full.py", "max_forks_repo_name": "nherbert25/Computational-Physics", "max_forks_repo_head_hexsha": "6fc01cf7bee566ca1e095877cc10d63bd678e21f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2847457627, "max_line_length": 78, "alphanum_fraction": 0.5648988692, "include": true, "reason": "import numpy", "num_tokens": 2266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241965169939, "lm_q2_score": 0.8824278571786139, "lm_q1q2_score": 0.8553586736438725}}
{"text": "from numpy import *\n#from pylab import *\n\ndef normgauss(x, sigma, x0=0):\n    return 1.0/sqrt(2*pi*sigma**2) * exp(-(x-x0)**2 / (2.0*sigma**2))\n\ndef FWHM_to_sigma(FWHM):\n    # from FWHM to sigma parameter:\n    return FWHM / sqrt(8.0 * log(2.0))\n\ndef rotxz(xp, zp, theta_deg):\n    theta = theta_deg * pi / 180.0\n    x = xp*cos(theta) - zp*sin(theta)\n    z = xp*sin(theta) + zp*cos(theta)\n    return x, z\n    \ndef gengauss(sigma, x0=0, threshold=0.001, npts = 200):\n    \"\"\" when gaussian drops below 0.001 of max amplitude, cut off x \"\"\"\n    cutoff = sqrt( -2.0 * sigma**2 * log( threshold ) )\n    x = linspace( x0 - cutoff, x0 + cutoff, npts )\n    y = normgauss( x, sigma, x0 )\n    return x, y\n\ndef plot_intersection():\n    pass\n\ndef gengaussFWHM(FWHM, x0=0, threshold=0.001, npts = 200):\n    sigma = FWHM_to_sigma(FWHM)\n    return gengauss(sigma, x0, threshold, npts)\n\n\n        \n#y_offset + amplitude * exp( - ( x - center )**2 * 4 * log(2) / FWHM**2 \n", "meta": {"hexsha": "951a49d610b8717e0609f7a3477deaae5cded026", "size": 951, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/gaussian_envelope.py", "max_stars_repo_name": "reflectometry/osrefl", "max_stars_repo_head_hexsha": "ddf55d542f2eab2a29fd6ffc862379820a06d5c7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-05-21T15:16:46.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-23T17:47:36.000Z", "max_issues_repo_path": "examples/gaussian_envelope.py", "max_issues_repo_name": "reflectometry/osrefl", "max_issues_repo_head_hexsha": "ddf55d542f2eab2a29fd6ffc862379820a06d5c7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/gaussian_envelope.py", "max_forks_repo_name": "reflectometry/osrefl", "max_forks_repo_head_hexsha": "ddf55d542f2eab2a29fd6ffc862379820a06d5c7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9705882353, "max_line_length": 72, "alphanum_fraction": 0.603575184, "include": true, "reason": "from numpy", "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692291542525, "lm_q2_score": 0.8757870029950159, "lm_q1q2_score": 0.8553542171184552}}
{"text": "from numpy import array,zeros,append\nimport numpy as np\n\ndef gausselim(A,b):\n   #AUGMENTED MATRIX\n    augA = np.c_[A,b]\n    p1 = augA [1,:] - augA [0,:] * (augA [1,0]/augA [0,0]) \n    p2 = augA [2,:] - augA [0,:] * (augA [2,0]/augA [0,0])\n    temp = append(augA[0,:],p1)\n    augA1 = append(temp,p2).reshape(3,4)  \n    p3 = augA1[2,:] - augA1[1,:] * (augA1[2,1]/augA1[1,1]) \n    augA2 = augA1.copy() \n    augA2[2] = p3\n    A = augA2[:,0:3]\n    b = augA2[:,-1]\n    print(\"A = \",A)\n    print(\"b = \",b)\n    # BACK SUBSTITUTION\n    x = zeros((3))\n    x[2] = b[2]/A[2,2]\n    x[1] = (b[1] - A[1,2] * x[2])/A[1,1] \n    x[0] = (b[0] - A[0,2] * x[2] - A[0,1] * x[1])/A[0,0]  \n    return x\n\nA = array([[5,-1,1],[-1,3,-1],[1,-1,4]])\nb = array([6,2,11])\nxg = gausselim(A,b)    \n    \nprint('x1 = %8.4f' % xg[0])\nprint('x2 = %8.4f' % xg[1])\nprint('x3 = %8.4f' % xg[2])\n", "meta": {"hexsha": "e66dd4ba0ba1810b3809c2d7a8ab3c31538951fb", "size": 854, "ext": "py", "lang": "Python", "max_stars_repo_path": "18_4.py", "max_stars_repo_name": "rursvd/pynumerical2", "max_stars_repo_head_hexsha": "4b2d33125b64a39099ac8eddef885e0ea11b237d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "18_4.py", "max_issues_repo_name": "rursvd/pynumerical2", "max_issues_repo_head_hexsha": "4b2d33125b64a39099ac8eddef885e0ea11b237d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "18_4.py", "max_forks_repo_name": "rursvd/pynumerical2", "max_forks_repo_head_hexsha": "4b2d33125b64a39099ac8eddef885e0ea11b237d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-03T01:34:19.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-03T01:34:19.000Z", "avg_line_length": 26.6875, "max_line_length": 59, "alphanum_fraction": 0.4660421546, "include": true, "reason": "import numpy,from numpy", "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692339078752, "lm_q2_score": 0.8757869965109764, "lm_q1q2_score": 0.8553542149488542}}
{"text": "# Import libraries\nfrom numpy import array, cos, sin, vstack\nfrom numpy.linalg import norm\nfrom lib.convert import rad2deg, deg2rad\nfrom lib.rotation import euler2dcm, dcm2euler, euler2quat, quat2euler, dcm2axis_ang, axis_ang2dcm, dcm2quat, \\\n    quat2dcm, qinv, qmult\n\n\n# euler angles (example)\nroll = deg2rad(10.0)\npitch = deg2rad(20.0)\nyaw = deg2rad(30.0)\n\n# euler to dcm\nC = euler2dcm(roll, pitch, yaw)\nprint(\"euler2dcm:\")\nprint(C, norm(C, 2))\n\n# dcm to euler\nroll, pitch, yaw = dcm2euler(C)\nprint(\"dcm2euler:\")\nprint(rad2deg(roll), rad2deg(pitch), rad2deg(yaw))\n\n# euler to quaternion\nq = euler2quat(roll, pitch, yaw)\nprint(\"euler2quat:\")\nprint(q, norm(q, 2))\n\n# quaternion to euler\nroll, pitch, yaw = quat2euler(q)\nprint(\"quat2euler:\")\nprint(rad2deg(roll), rad2deg(pitch), rad2deg(yaw))\n\n# dcm to axis_angle\ntheta, r = dcm2axis_ang(C)\nprint(\"DCM2axis_ang:\")\nprint(theta, r.T)\n\n# axis_angle to dcm\nC = axis_ang2dcm(theta, r)\nprint(\"axis_ang2DCM:\")\nprint(C, norm(C, 2))\n\n# DCM to quaternion\nq = dcm2quat(C)\nprint(\"dcm2quat:\")\nprint(q, norm(q, 2))\n\n# quaternion to DCM\nC = quat2dcm(q)\nprint(\"quat2dcm:\")\nprint(C, norm(C, 2))\n\n# Rotation by quaternions (full example)\n\n# Rotation angle\ntheta = deg2rad(30)\n\n# Rotation axis (normalized)\nr = array([[0],\n           [0],\n           [1]])\n\n# Point\np1 = array([[1],\n            [0],\n            [0]])\n\n# Point (quaternion representation)\np1q = vstack([0,\n              p1])\nprint(\"Point p1:\")\nprint(p1q, norm(p1q, 2))\n\n# Define rotation quaternion\nq = vstack([cos(theta/2),\n           sin(theta/2)*r])\nprint(\"Rotation quaternion:\")\nprint(q, norm(q, 2))\n\n# Rotate p1 to p2\np2q = qmult(qmult(q, p1q), qinv(q))\nprint(\"Point p2:\")\nprint(p2q, norm(p2q, 2))\n\n\n# Corresponding dcm rotation\n\n# Quaternion to dcm\nC = quat2dcm(q)\nprint(\"quat2dcm:\")\nprint(C, norm(C, 2))\n\n# Rotate p1 to p2\np2 = C@p1\nprint(\"Point p2:\")\nprint(p2, norm(p2, 2))\n", "meta": {"hexsha": "c842c80de244278902256aefd31cf6f8ed5add65", "size": 1878, "ext": "py", "lang": "Python", "max_stars_repo_path": "example_rotation.py", "max_stars_repo_name": "jggjevestad/NavLib", "max_stars_repo_head_hexsha": "d81fd6e3d4b733aaefd4c69cea6b5d44a06f820b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example_rotation.py", "max_issues_repo_name": "jggjevestad/NavLib", "max_issues_repo_head_hexsha": "d81fd6e3d4b733aaefd4c69cea6b5d44a06f820b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example_rotation.py", "max_forks_repo_name": "jggjevestad/NavLib", "max_forks_repo_head_hexsha": "d81fd6e3d4b733aaefd4c69cea6b5d44a06f820b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1632653061, "max_line_length": 110, "alphanum_fraction": 0.6602768903, "include": true, "reason": "from numpy", "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.972830769252026, "lm_q2_score": 0.8791467770088162, "lm_q1q2_score": 0.8552610353629261}}
{"text": "import numpy as np\nfrom scipy import linalg as lg\nfrom numpy import pi,sin,cos,tan,sqrt, e\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import odeint\n\n\n# units in MHz\nTRANSITON_FREQUENCY = 177\nBIG_OMEGA = 2\n\nDELTA = 3\n\n# BIG OMEGA IS NOT RABI FREQUENCY\n\n\n## density matrix (much faster)\ndef equation_system(r,t,Omega,w0,w):\n    rho_00, rho_01_r, rho_01_i = r\n\n    rhodot_00 = -2*rho_01_i * Omega*cos(w*t)\n\n    rhodot_01_r = -w0*rho_01_i\n\n    rhodot_01_i = +w0*rho_01_r + (2*rho_00 - 1) * Omega*cos(w*t)\n\n    return rhodot_00, rhodot_01_r, rhodot_01_i\n\n\n# solution\nt = np.linspace(0,1/BIG_OMEGA,2000) # time units in terms of microseconds\n\nr_init = np.array([1,0,0]) # initial starting state of the DEs\n\nw,w0 = 2*pi*TRANSITON_FREQUENCY,2*pi*177 # forced oscillation frequency vs energy level frequency\nOmega = 2*pi*BIG_OMEGA\n\nsolution = odeint(equation_system, r_init, t, args=(Omega,w,w0))\nfig, axes = plt.subplots(nrows=1)\naxes.plot(t,1-solution[:,0],lw=2,label=r\"$\\rho_{11}$\",color='C0')\n\nw0 = 2*pi*(177+DELTA) # forced oscillation frequency vs energy level frequency\nsolution = odeint(equation_system, r_init, t, args=(Omega,w,w0))\naxes.plot(t,1-solution[:,0],lw=2,label=f\"+{DELTA}\",color='C1')\n\nw0 = 2*pi*(177-DELTA) # forced oscillation frequency vs energy level frequency\nsolution = odeint(equation_system, r_init, t, args=(Omega,w,w0))\naxes.plot(t,1-solution[:,0],lw=2,label=f\"-{DELTA}\",color='C2')\n\n\n# predict analytic solution\namp_factor = 1/(1+(DELTA/BIG_OMEGA)**2)\ntime_factor = sqrt(1+(DELTA/BIG_OMEGA)**2) # YES I DID IT\n\nprediction = amp_factor*(sin(2*pi*time_factor*BIG_OMEGA/2*t))**2\naxes.plot(t,prediction, \"--\",lw=2,label=\"prediction\",color='C3')\n\naxes.margins(0,0.1)\nplt.legend()\nplt.show()\n\n\nfig, axes = plt.subplots(nrows=1)\nDELTAS = np.linspace(-20, 20, 60)\n# predict analytic solution\n\nprediction = []\n\nT = pi/BIG_OMEGA\n\nfor DELTA in DELTAS:\n    amp_factor = 1/(1+(DELTA/BIG_OMEGA)**2)\n    time_factor = sqrt(1+(DELTA/BIG_OMEGA)**2) # YES I DID IT\n    prediction.append(amp_factor*(sin(2*pi*time_factor*BIG_OMEGA/2*T))**2)\naxes.plot(DELTAS,prediction,lw=2)\n\naxes.margins(0,0.1)\nplt.show()\n\n\n", "meta": {"hexsha": "33c7be5e2310f54bc7ec5111b89822400fc7356a", "size": 2122, "ext": "py", "lang": "Python", "max_stars_repo_path": "Rabi Osc v2/solutionv2.py", "max_stars_repo_name": "itchono/Electric-Atoms", "max_stars_repo_head_hexsha": "6f72cc5c400f9a73b641cb21f317cdb4e98e7838", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Rabi Osc v2/solutionv2.py", "max_issues_repo_name": "itchono/Electric-Atoms", "max_issues_repo_head_hexsha": "6f72cc5c400f9a73b641cb21f317cdb4e98e7838", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rabi Osc v2/solutionv2.py", "max_forks_repo_name": "itchono/Electric-Atoms", "max_forks_repo_head_hexsha": "6f72cc5c400f9a73b641cb21f317cdb4e98e7838", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1975308642, "max_line_length": 97, "alphanum_fraction": 0.7097078228, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307684643189, "lm_q2_score": 0.8791467580102418, "lm_q1q2_score": 0.8552610161880182}}
{"text": "#!/usr/bin/env python\n#\n# Created: 20170227\n\n# Note: In a python program or function, if the first statement\n# encountered is a string literal like this, it will be taken as the\n# documentation (__doc__) of the program/function.\n\n\"\"\"\nmatmul1.py\n\nDemo program to read two matrices, performs multiplication, and prints\nthe output to standard output.\n\nThis program has some pedagogical value in demonstrating the effect of\nhand-crafting loops in python as opposed to using\nmatrix-multiplication kernel (canned routine).\n\n\"\"\"\n\nimport sys\nimport numpy\nfrom np_helper import loadmatrix1, printmatrix1\n\ndef matmul_manual(A, B):\n    \"\"\"Performs manual matrix multiplication with python.\n    Avoid doing this in python because of low performance!\n    \"\"\"\n    from numpy import asarray, sum\n    A = asarray(A)\n    B = asarray(B)\n    M, K = A.shape\n    N = B.shape[1]\n    assert A.shape[1] == B.shape[0]\n    # Caveat: works only if A & B dtypes are the same:\n    C = numpy.zeros((M,N), dtype=A.dtype)\n    for i in range(M):\n        for j in range(N):\n            Cij = 0\n            for k in range(K):\n                Cij += A[i,k] * B[k,j]\n            C[i,j] = Cij\n    return C\n\n\ndef matmul_vecdot(A, B):\n    \"\"\"Performs semi-manual matrix multiplication with python,\n    using dot product in the innnermost loop.\n    \"\"\"\n    from numpy import asarray, sum\n    A = asarray(A)\n    B = asarray(B)\n    M, K = A.shape\n    N = B.shape[1]\n    assert A.shape[1] == B.shape[0]\n    # Caveat: works only if A & B dtypes are the same:\n    C = numpy.zeros((M,N), dtype=A.dtype)\n    for i in range(M):\n        for j in range(N):\n            C[i,j] = sum(A[i,:] * B[:,j])\n    return C\n\n\n\ndef matmul_matdot(A, B):\n    \"\"\"Performs matrix multiplication with python using numpy.dot.\n\n    Note that numpy.dot is equivalent to matrix-matrix multiplication\n    for 2-D arrays; we explot this fact here!\n    \"\"\"\n    from numpy import asarray, sum\n    A = asarray(A)\n    B = asarray(B)\n    M, K = A.shape\n    N = B.shape[1]\n    assert A.shape[1] == B.shape[0]\n    C = numpy.dot(A, B)\n    return C\n\n\n\ndef matmul1(argv):\n    if len(argv) < 3:\n        print >> sys.stderr, \"Needs an input file name on arg1\"\n        sys.exit(1)\n\n    matfile1 = argv[1]\n    matfile2 = argv[2]\n    A = loadmatrix1(matfile1)\n    B = loadmatrix1(matfile2)\n    C = matmul_matdot(A,B)\n    printmatrix1(C, float_fmt=\" %12.6f\")\n    #printmatrix1(C)\n\nif __name__ == \"__main__\":\n    matmul1(sys.argv)\n", "meta": {"hexsha": "24cde844a7bda606a6ad23ef7a4864cac0da4d95", "size": 2439, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/matmul1.py", "max_stars_repo_name": "wirawan0/ODU-HPC-samples", "max_stars_repo_head_hexsha": "3c4f13664c5902a81fe77f8bd6761813d7cabf74", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/matmul1.py", "max_issues_repo_name": "wirawan0/ODU-HPC-samples", "max_issues_repo_head_hexsha": "3c4f13664c5902a81fe77f8bd6761813d7cabf74", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/matmul1.py", "max_forks_repo_name": "wirawan0/ODU-HPC-samples", "max_forks_repo_head_hexsha": "3c4f13664c5902a81fe77f8bd6761813d7cabf74", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-21T15:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T15:58:02.000Z", "avg_line_length": 25.1443298969, "max_line_length": 70, "alphanum_fraction": 0.6277162772, "include": true, "reason": "import numpy,from numpy", "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.9099070097026719, "lm_q1q2_score": 0.8552337455197901}}
{"text": "import numpy as np\n\ndef opt_mult_recurse(a,p,q):\n    if q-p<2:\n        return 0\n    minn = np.inf\n    for i in range(p+1,q):\n        minn = min(minn,\\\n            opt_mult_recurse(a,p,i)+opt_mult_recurse(a,i,q)\\\n                +a[p]*a[i]*a[q])\n    return minn\n\n\ndef opt_mult_top_dwn(a,p,q,m):\n    if q-p<2:\n        return 0\n    if m[p,q] < np.inf:\n        return m[p,q]\n    minn = np.inf\n    for i in range(p+1,q):\n        minn = min(minn,\\\n                opt_mult_top_dwn(a,p,i,m)+opt_mult_top_dwn(a,i,q,m)\\\n                    +a[p]*a[i]*a[q])\n    m[p,q] = minn\n    return m[p,q]\n\n\ndef opt_mult_top_dwn_v2(a,p,q,m,s):\n    if q-p<2:\n        return 0, s\n    if m[p,q] < np.inf:\n        return m[p,q], s\n    minn = np.inf; min_ix=0\n    for i in range(p+1,q):\n        minn1 = min(minn,\\\n                opt_mult_top_dwn_v2(a,p,i,m,s)[0]+\\\n                opt_mult_top_dwn_v2(a,i,q,m,s)[0]\\\n                    +a[p]*a[i]*a[q])\n        if minn1<minn:\n            minn = minn1; min_ix = i\n    m[p,q] = minn\n    s[p,q] = int(min_ix)\n    return m[p,q], s\n\n\ndef opt_mult_top_dwn_strt(a):\n    n = len(a)\n    m=np.ones((n,n+1))*np.inf\n    return opt_mult_top_dwn(a,0,len(a)-1,m)\n\n\ndef opt_mult_top_dwn_strt_v2(a):\n    n = len(a)\n    m=np.ones((n,n+1))*np.inf\n    s=np.zeros((n,n+1)).astype(int)\n    return opt_mult_top_dwn_v2(a,0,len(a)-1,m,s)\n\ndef print_opt_parenth(s,p,q):\n    if q-p<2:\n        print(\"A_\"+str(q)+' ',end='')\n    else:\n        print(\"(\",end='')\n        print_opt_parenth(s,p,s[p,q])\n        print_opt_parenth(s,s[p,q],q)\n        print(\")\",end='')\n\n\n# https://wbd.ms/share/v2/aHR0cHM6Ly93aGl0ZWJvYXJkLm1pY3Jvc29mdC5jb20vYXBpL3YxLjAvd2hpdGVib2FyZHMvcmVkZWVtLzA2YjJmZTQ0YWJkYTQ1ZjNiM2NkMTI0OWZmMjExYmY3X0JCQTcxNzYyLTEyRTAtNDJFMS1CMzI0LTVCMTMxRjQyNEUzRA==\ndef opt_mult_bottom_up(a):\n    # The number of matrices\n    n = len(a)-1\n    m = np.zeros((n,n+1))\n    for d_i in range(2,n+1):\n        for p in range(n):\n            q=p+d_i\n            if q>n:\n                break\n            minn = np.inf\n            for i in range(p+1,q):\n                minn=min(minn,m[p,i]+m[i,q]+a[p]*a[i]*a[q])\n            m[p,q] = minn\n    return int(m[0,n])\n\n\nif __name__==\"__main__\":\n    a = np.arange(4)+2\n    res = opt_mult_bottom_up(a)\n    print(res)\n    res = opt_mult_recurse(a,0,len(a)-1)\n    print(res)\n    res = opt_mult_top_dwn_strt(a)\n    print(\"Top down version: \" + str(res))\n    a = [30,35,15,5,10,20,25]\n    res=opt_mult_bottom_up(a)\n    print(res)\n    res = opt_mult_top_dwn_strt(a)\n    print(res)\n    res, s = opt_mult_top_dwn_strt_v2(a)\n    print(s)\n    print_opt_parenth(s,0,len(a)-1)\n\n", "meta": {"hexsha": "3f875268744a09a795a14a75bc3d24bf59b250bf", "size": 2597, "ext": "py", "lang": "Python", "max_stars_repo_path": "algorith/clr_book/ch15_dynamic_programming/matrix_chain_mult.py", "max_stars_repo_name": "ryu577/algorithms", "max_stars_repo_head_hexsha": "b42301c3279af1d225ea85e951ef0164c1f0ab8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algorith/clr_book/ch15_dynamic_programming/matrix_chain_mult.py", "max_issues_repo_name": "ryu577/algorithms", "max_issues_repo_head_hexsha": "b42301c3279af1d225ea85e951ef0164c1f0ab8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorith/clr_book/ch15_dynamic_programming/matrix_chain_mult.py", "max_forks_repo_name": "ryu577/algorithms", "max_forks_repo_head_hexsha": "b42301c3279af1d225ea85e951ef0164c1f0ab8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4607843137, "max_line_length": 202, "alphanum_fraction": 0.546399692, "include": true, "reason": "import numpy", "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766225, "lm_q2_score": 0.9099070029841949, "lm_q1q2_score": 0.8552337346105469}}
{"text": "'''\nOriginal credits: http://www.kostasalexis.com/lqr-control.html\nModifications by Avik De\n'''\n\nfrom __future__ import division, print_function\n \nimport autograd.numpy as np\nimport scipy.linalg\n \ndef lqr(A,B,Q,R, eigs=False):\n    \"\"\"Solve the continuous time lqr controller.\n        \n    dx/dt = A x + B u\n        \n    cost = integral x.T*Q*x + u.T*R*u\n    \"\"\"\n    #ref Bertsekas, p.151\n\n    #first, try to solve the ricatti equation\n    X = scipy.linalg.solve_continuous_are(A, B, Q, R)\n        \n    #compute the LQR gain\n    K = np.linalg.inv(R) @ (B.T @ X)\n    \n    if eigs:\n        eigVals, eigVecs = np.linalg.eig(A - B @ K)\n        return K, X, eigVals\n    else:\n        return K, X\n \ndef dlqr(A,B,Q,R, eigs=False):\n    \"\"\"Solve the discrete time lqr controller.\n        \n        \n    x[k+1] = A x[k] + B u[k]\n        \n    cost = sum x[k].T*Q*x[k] + u[k].T*R*u[k]\n    \"\"\"\n    #ref Bertsekas, p.151\n\n    #first, try to solve the ricatti equation\n    X = scipy.linalg.solve_discrete_are(A, B, Q, R)\n        \n    #compute the LQR gain\n    K = np.linalg.inv(B.T @ X @ B + R) @ (B.T @ X @ A)\n    \n    if eigs:\n        eigVals, eigVecs = np.linalg.eig(A - B @ K)\n        return K, X, eigVals\n    else:\n        return K, X\n\n", "meta": {"hexsha": "c0a2cd3e3ede224d5f5deb40c519d1150a55b08a", "size": 1224, "ext": "py", "lang": "Python", "max_stars_repo_path": "py/lqr.py", "max_stars_repo_name": "avikde/controlutils", "max_stars_repo_head_hexsha": "c7637065dd3275a7844a3a7f035c59c439e99095", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "py/lqr.py", "max_issues_repo_name": "avikde/controlutils", "max_issues_repo_head_hexsha": "c7637065dd3275a7844a3a7f035c59c439e99095", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-03-20T14:08:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-14T17:33:08.000Z", "max_forks_repo_path": "py/lqr.py", "max_forks_repo_name": "avikde/controlutils", "max_forks_repo_head_hexsha": "c7637065dd3275a7844a3a7f035c59c439e99095", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6666666667, "max_line_length": 62, "alphanum_fraction": 0.5539215686, "include": true, "reason": "import scipy", "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96741025335478, "lm_q2_score": 0.8840392924390585, "lm_q1q2_score": 0.8552286758740502}}
{"text": "import numpy as np \nimport matplotlib.pyplot as plt \n\n\n\n\nclass LinearRegression:\n    \n    def __init__(self,csv_file):\n        data = np.loadtxt(csv_file , delimiter = ',')\n        X = data[: , :-1]\n        self.y = data[: , -1]\n        self.X = np.insert(X,0,values = np.ones(X.shape[0]) , axis =1) \n        self.mu = np.mean(self.X[:,1:] , axis = 0)\n        self.sigma = np.std(self.X[:,1:] , axis = 0)\n        \n    \n    def head(self,n):\n        print(\"Feature Data Is\")\n        print(self.X[:n,:])\n        print(\"Target Data Is\")\n        print(np.array(self.y[:n]))\n        \n        \n    def normalise(self):\n        X_norm = (self.X[:,1:]-self.mu)/self.sigma\n        X_norm = np.insert(X_norm,0,values = np.ones(self.X.shape[0]) , axis =1) \n        return X_norm\n        \n        \n    def computeCost(self,theta):\n        \"\"\"m represents number of training examples\n           X is feature set with n features and is matrix of shape m*(n+1)\n           theta is parameter set of shape (n+1)*1\n           y is target data set of shape m*1\n           X*theta represents our predicted value \n           (X*theta-y)^2 is the squared error value\n           J is sum of all the squared errors over 2*m\n        \"\"\"\n        m = self.y.shape[0]\n        HTheta_X = np.dot(self.X,theta)\n        Error = HTheta_X-self.y\n        J = (np.sum(Error**2))/(2*m)\n        return J\n\n\n    \n    def gradientDescent(self,theta,alpha,iterations):\n        theta = theta.copy()\n        m = self.y.shape[0] \n        J_values = []\n\n        for num in range(iterations):\n            for j in range(theta.size):\n                Error = np.dot(self.X,theta)-self.y\n                Derivative = np.dot(Error, self.X[:,j])\n                theta[j] = theta[j] - (np.sum(Derivative))*(alpha/m)\n                \n            J_values.append(self.computeCost(theta))\n\n        return theta,J_values\n    \n    def predict_value(self,values,theta , norm=False):\n        if(norm == True):\n            values = (values-self.mu)/self.sigma\n        values = np.insert(values , 0 , np.ones(1) , axis = 0)\n        predict = np.dot(values,theta)\n        return predict\n\n\nif __name__ == '__main__':\n\n\n    LR = LinearRegression('ex1data2.txt')\n    LR.X = LR.normalise()\n    theta, J_history = LR.gradientDescent(np.zeros(LR.X.shape[1]), 0.15, 1000)\n    print(LR.predict_value([1650,3],theta , norm = True)) #Prediction for 1650 sq. feet and 3 bedrooms\n\n    '''For ex1data1 file , no need for normalisation'''\n    LR2 = LinearRegression('ex1data1.txt')\n    theta , J_history = LR2.gradientDescent(np.zeros(2) , 0.01 ,1500)\n    print(LR2.predict_value([7] , theta))\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "3d51423dce5bd0f3e41b9135050399d7cc7f4b91", "size": 2627, "ext": "py", "lang": "Python", "max_stars_repo_path": "LinearRegression/LinearRegression.py", "max_stars_repo_name": "ChetanTayal138/Machine-Learning-Algorithms", "max_stars_repo_head_hexsha": "96491b054542bb1967e90c12baaa8b8f06a639d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-02-20T15:30:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-17T14:15:22.000Z", "max_issues_repo_path": "LinearRegression/LinearRegression.py", "max_issues_repo_name": "ChetanTayal138/Machine-Learning-Algorithms", "max_issues_repo_head_hexsha": "96491b054542bb1967e90c12baaa8b8f06a639d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LinearRegression/LinearRegression.py", "max_forks_repo_name": "ChetanTayal138/Machine-Learning-Algorithms", "max_forks_repo_head_hexsha": "96491b054542bb1967e90c12baaa8b8f06a639d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.247311828, "max_line_length": 102, "alphanum_fraction": 0.5553863723, "include": true, "reason": "import numpy", "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102580527664, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.8552286726382959}}
{"text": "import numpy as np\nimport pymc3 as pm\nimport matplotlib.pyplot as plt\nfrom scipy.stats import binom\nfrom scipy.stats import mode\nimport seaborn as sns\nimport collections\n\nbirth1 = np.array(\n    [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1,\n     0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0,\n     1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1])\nbirth2 = np.array([0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0,\n                   1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n                   1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1,\n                   0, 0, 0, 1, 1, 1, 0, 0, 0, 0])\n\nboys = np.sum(birth1) + np.sum(birth2)\n\ng1 = collections.Counter(birth1)\ng2 = collections.Counter(birth2)\n\ngirls = g1[0]+g2[0]\nprint('overall boys:' + str(boys))\nprint('overall girls:' + str(girls))\n\nsize = len(birth1)+len(birth2)\n\npriors = np.random.uniform(0.,1.,size)\np_grid = np.linspace(0.,1.,size)\nlikehood = binom.pmf(boys,size, p=p_grid)\nposterior = likehood*priors\nposterior = posterior/posterior.sum()\nplt.plot(p_grid,posterior)\nplt.show()\n\nprint('maximum posteriori %f at prob = %f '%(max(posterior),p_grid[posterior == max(posterior)]))\n\n\n# likehood = binom.pmf(np.sum(birth2),len(birth2), p=p_grid)\n# posterior = likehood*posterior\n# posterior = posterior/posterior.sum()\n#\n# plt.plot(p_grid,posterior)\n# plt.show()\nsample_size=int(10000)\nsamples = np.random.choice(a=p_grid,p=posterior,size=sample_size)\nsns.kdeplot(samples)\nplt.show()\n\nprint('50% hpd: '+str(pm.hpd(samples,alpha=0.5)))\nprint('89% hpd: '+str(pm.hpd(samples,alpha=0.89)))\nprint('97% hpd: '+str(pm.hpd(samples,alpha=0.97)))\n\n#model fits well, max is around 111/200 as is the observation\ndummy_w = binom.rvs(n=200,p=samples,size=sample_size)\n_,(ax0,ax1) = plt.subplots(1,2)\nax0.plot(posterior)\nax1.hist(dummy_w,bins=50)\nplt.show()\nmeans = [(dummy_w == i).mean() for i in range(200)]\n\nprint('boys = %f from number of births %f '%(boys,size))\nplt.plot(means)\nplt.show()\n\ndummy_w = binom.rvs(n=100,p=samples,size=sample_size)\n_,(ax0,ax1) = plt.subplots(1,2)\nax0.plot(posterior)\nax1.hist(dummy_w,bins=50)\nplt.show()\nmeans = [(dummy_w == i).mean() for i in range(100)]\n\nprint('boys = %f from number of births %f '%(np.sum(birth1),len(birth1)))\nplt.plot(means)\nplt.show()\n\n#simulating boys(second born) folowing girls born first\ndummy_w = binom.rvs(n=g1[0],p=samples,size=sample_size)\n_,(ax0,ax1) = plt.subplots(1,2)\nax0.plot(posterior)\nax1.hist(dummy_w,bins=50)\nplt.show()\nmeans = [(dummy_w == i).mean() for i in range(200)]\n\nprint('boys = %f from number of births %f '%(boys,size))\nplt.plot(means)\nplt.show()\n\n\n\n\n#simulating 51 boys from 1st birth\nsize = len(birth1)\npriors = np.random.uniform(0.,1.,size)\np_grid = np.linspace(0.,1.,size)\nlikehood = binom.pmf(np.sum(birth1),size, p=p_grid)\nposterior = likehood*priors\nposterior = posterior/posterior.sum()\nplt.plot(p_grid,posterior)\nplt.show()\n\nsample_size=int(10000)\nsamples = np.random.choice(a=p_grid,p=posterior,size=sample_size)\nsns.kdeplot(samples)\nplt.show()\n\nprint('50% hpd: '+str(pm.hpd(samples,alpha=0.5)))\nprint('89% hpd: '+str(pm.hpd(samples,alpha=0.89)))\nprint('97% hpd: '+str(pm.hpd(samples,alpha=0.97)))\n\ndummy_w = binom.rvs(n=100,p=samples,size=sample_size)\n_,(ax0,ax1) = plt.subplots(1,2)\nax0.plot(posterior)\nax1.hist(dummy_w,bins=50)\nplt.show()\nmeans = [(dummy_w == i).mean() for i in range(100)]\n\nprint('boys = %f from number of births %f '%(np.sum(birth1),len(birth1)))\nplt.plot(means)\nplt.show()\n\n\n", "meta": {"hexsha": "3367a42c82057bbb8fd34a18fb3d0c408a6bb235", "size": 3728, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch3/hard.py", "max_stars_repo_name": "xSakix/bayesian_analyses", "max_stars_repo_head_hexsha": "14042e193507bae6d69caeb4035ac45ef9044176", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3/hard.py", "max_issues_repo_name": "xSakix/bayesian_analyses", "max_issues_repo_head_hexsha": "14042e193507bae6d69caeb4035ac45ef9044176", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/hard.py", "max_forks_repo_name": "xSakix/bayesian_analyses", "max_forks_repo_head_hexsha": "14042e193507bae6d69caeb4035ac45ef9044176", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.064516129, "max_line_length": 118, "alphanum_fraction": 0.6354613734, "include": true, "reason": "import numpy,from scipy,import pymc3", "num_tokens": 1588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102514755853, "lm_q2_score": 0.8840392878563335, "lm_q1q2_score": 0.8552286697793929}}
{"text": "import numpy as np\nfrom numpy import linalg as LA\nimport matplotlib.pyplot as plt\nfrom pdb import set_trace\nfrom scipy.linalg import eig\n\n\ndef get_laplacian(E, n_vertices, directed=False):\n    L = np.zeros((n_vertices, n_vertices))\n    for e in E:\n        if directed:\n            L[e[1]][e[1]] += 1\n            L[e[1]][e[0]] = -1\n        else:\n            L[e[1]][e[1]] += 1\n            L[e[0]][e[0]] += 1\n            L[e[1]][e[0]] = -1\n            L[e[0]][e[1]] = -1\n    return L\n\n\ndef get_cycle_graph(N):\n    n_vertices = N\n    E = []\n\n    for i in range(N-1):\n        E.append([i, i+1])\n    E.append([N-1, 0])\n\n    return E, n_vertices\n\n\ndef simulate_consensus(x_0, T, L, dt=0.001):\n    x_current = x_0\n    t = 0\n    ts = [t]\n    xs = x_0\n    converged = False\n    t_converged = np.inf\n    while t <= T:\n        x_next = x_current - np.matmul(L, x_current) * dt\n        xs = np.hstack((xs, x_next))\n        x_current = x_next\n        t += dt\n        ts.append(t)\n\n        if not converged and np.amax(x_current) - np.amin(x_current) <= 0.01:\n            converged = True\n            t_converged = t\n\n    return xs, np.array(ts), t_converged\n\n\ndef get_complete_graph(N):\n    n_vertices = N\n    E = []\n    for i in range(N):\n        for j in range(N-i-1):\n            E.append([i, j+i+1])\n\n    return E, n_vertices\n\n\ndef main():\n    # Exercise 1\n    E = [[0, 1], [1, 2], [2, 0]]\n    n_vertices = 3\n\n    laplacian = get_laplacian(E, n_vertices, False)\n    print(laplacian)\n    laplacian = get_laplacian(E, n_vertices, True)\n    print(laplacian)\n\n    num = [5, 15, 199]\n\n    for n in num:\n        E, n_vertices = get_cycle_graph(n)\n        laplacian = get_laplacian(E, n_vertices, False)\n        eigvals = LA.eigvals(laplacian)\n        eigvals = np.sort(eigvals)\n        print(\"C_{}: {}, {}, {}, {}\".format(n, eigvals[0], eigvals[1], eigvals[-2], eigvals[-1]))\n\n    # Exercise 2\n    x_0 = np.transpose(np.array([[10, 20, 12, 5, 30, 12, 15, 16, 25]]))\n    n_vertices = 9\n    E = [[0, 2], [1, 2], [2, 3], [2, 4], [2, 6], [4, 5], [4, 6], [4, 7], [5, 6], [6, 7], [6, 8]]\n    L = get_laplacian(E, n_vertices, False)\n    set_trace()\n    xs, ts, t_converge = simulate_consensus(x_0, 20, L)\n\n    # 2.b\n    plt.figure()\n    for i in range(xs.shape[0]):\n        plt.plot(ts, xs[i, :])\n    plt.title(\"Original Graph, t_converge = {}\".format(t_converge))\n    plt.xlabel('t / sec')\n    plt.ylabel('state')\n    plt.savefig('/home/bolun/Documents/swarmrobotics/series2/original_graph_sim.png')\n\n    # 2.c\n    E = [[0, 2], [1, 2], [2, 3], [4, 5], [4, 6], [4, 7], [5, 6], [6, 7], [6, 8]]\n    L = get_laplacian(E, n_vertices, False)\n    set_trace()\n    xs, ts, t_converge = simulate_consensus(x_0, 20, L)\n\n    plt.figure()\n    for i in range(xs.shape[0]):\n        plt.plot(ts, xs[i, :])\n    plt.title(\"Disconnected Graph, t_converge = {}\".format(t_converge))\n    plt.xlabel('t / sec')\n    plt.ylabel('state')\n    plt.savefig('/home/bolun/Documents/swarmrobotics/series2/disconnected_graph_sim.png')\n\n    # 2.d\n    E, n_vertices = get_complete_graph(9)\n    L = get_laplacian(E, n_vertices, False)\n    set_trace()\n    xs, ts, t_converge = simulate_consensus(x_0, 20, L)\n\n    plt.figure()\n    for i in range(xs.shape[0]):\n        plt.plot(ts, xs[i, :])\n    plt.title(\"Complete Graph, t_converge = {}\".format(t_converge))\n    plt.xlabel('t / sec')\n    plt.ylabel('state')\n    plt.savefig('/home/bolun/Documents/swarmrobotics/series2/complete_graph_sim.png')\n\n    # 2.e\n    E, n_vertices = get_cycle_graph(9)\n    L = get_laplacian(E, n_vertices, False)\n    set_trace()\n    xs, ts, t_converge = simulate_consensus(x_0, 20, L)\n\n    plt.figure()\n    for i in range(xs.shape[0]):\n        plt.plot(ts, xs[i, :])\n    plt.title(\"Cycle Graph, t_converge = {}\".format(t_converge))\n    plt.xlabel('t / sec')\n    plt.ylabel('state')\n    plt.savefig('/home/bolun/Documents/swarmrobotics/series2/cycle_graph_sim.png')\n\n    # Exercise 3\n    # 3.c\n    x_0 = np.transpose(np.array([[10, 5, 1, -5, -10]]))\n    n_vertices = 5\n    E = [[1, 0], [1, 2], [2, 4], [3, 2], [4, 1], [4, 3]]\n    L = get_laplacian(E, n_vertices, True)\n    vals, vl, vr = eig(L, left=True)\n    xs, ts, t_converge = simulate_consensus(x_0, 10, L)\n    plt.figure()\n    for i in range(xs.shape[0]):\n        plt.plot(ts, xs[i, :])\n    plt.title(\"Original Graph, t_converge = {}\".format(t_converge))\n    plt.xlabel('t / sec')\n    plt.ylabel('state')\n    plt.savefig('/home/bolun/Documents/swarmrobotics/series2/unchanged_graph_sim.png')\n\n    # 3.d\n    x_0 = np.transpose(np.array([[10, 5, 1, -5, -10]]))\n    n_vertices = 5\n    E = [[0, 4], [1, 0], [2, 4], [3, 2], [4, 1], [4, 3]]\n    L = get_laplacian(E, n_vertices, True)\n    vals, vl, vr = eig(L, left=True)\n    xs, ts, t_converge = simulate_consensus(x_0, 10, L)\n    plt.figure()\n    for i in range(xs.shape[0]):\n        plt.plot(ts, xs[i, :])\n    plt.title(\"Converge to Average Graph, t_converge = {}\".format(t_converge))\n    plt.xlabel('t / sec')\n    plt.ylabel('state')\n    plt.savefig('/home/bolun/Documents/swarmrobotics/series2/average_graph_sim.png')\n\n    # 3.e\n    x_0 = np.transpose(np.array([[10, 5, 1, -5, -10]]))\n    n_vertices = 5\n    E = [[0, 4], [1, 0], [2, 4], [3, 2], [4, 1]]\n    L = get_laplacian(E, n_vertices, True)\n    vals, vl, vr = eig(L, left=True)\n    xs, ts, t_converge = simulate_consensus(x_0, 30, L)\n    plt.figure()\n    for i in range(xs.shape[0]):\n        plt.plot(ts, xs[i, :])\n    plt.title(\"Leader Graph, t_converge = {}\".format(t_converge))\n    plt.xlabel('t / sec')\n    plt.ylabel('state')\n    plt.savefig('/home/bolun/Documents/swarmrobotics/series2/leader_graph_sim.png')\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "080c143ab396e3be231205a25dc963c03db86cb7", "size": 5630, "ext": "py", "lang": "Python", "max_stars_repo_path": "series2/code/series2.py", "max_stars_repo_name": "BolunDai0216/ConsensusControl", "max_stars_repo_head_hexsha": "12f36fa3a70897b9e6cbcdab19734ca8360211a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series2/code/series2.py", "max_issues_repo_name": "BolunDai0216/ConsensusControl", "max_issues_repo_head_hexsha": "12f36fa3a70897b9e6cbcdab19734ca8360211a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2/code/series2.py", "max_forks_repo_name": "BolunDai0216/ConsensusControl", "max_forks_repo_head_hexsha": "12f36fa3a70897b9e6cbcdab19734ca8360211a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4764397906, "max_line_length": 97, "alphanum_fraction": 0.5705150977, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 1947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102524151827, "lm_q2_score": 0.8840392832736084, "lm_q1q2_score": 0.8552286661766587}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jan  4 09:58:31 2021\r\n\r\n@author: Larisa\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport sympy as sym \r\nimport matplotlib.pyplot as plt\r\nimport math\r\n\r\n\r\n\r\n\r\n### Proceduri -> Ex1\r\ndef difFinProg(X, Y):\r\n    \"\"\"\r\n    x oarecare  ->  f'(x) = (f(x+h) - f(x)) / h\r\n    \r\n    pt discretizare xi  ->  f'(xi) = (f(xi+1) - f(xi)) / (xi+1 - xi), unde\r\n    xi + 1  => nodul i + 1 al vectorului x\r\n\r\n    \"\"\"\r\n    n = len(X)\r\n    df = np.zeros((n - 1, 1))\r\n    \r\n    for i in range(n - 1):\r\n        df[i] = (Y[i+1] - Y[i]) / (X[i+1] - X[i])\r\n    \r\n    return df\r\n\r\n\r\ndef difFinReg(X, Y):\r\n    \"\"\"\r\n    x oarecare  ->  f'(x) = (f(x) - f(x-h)) / h\r\n    \r\n    pt discretizare xi  ->  f'(xi) = (f(xi) - f(xi-1)) / (xi - xi-1), unde\r\n    xi-1  => nodul i-1 al vectorului x\r\n\r\n    \"\"\"\r\n    n = len(X)\r\n    df = np.zeros((n, 1))\r\n    \r\n    for i in range(1, n):\r\n        df[i] = (Y[i] - Y[i - 1]) / (X[i] - X[i - 1])\r\n    \r\n    return df\r\n\r\n\r\ndef difFinCen(X, Y):\r\n    \"\"\"\r\n    x oarecare  ->  f'(x) = (f(x+h) - f(x-h)) / (2*h)\r\n    \r\n    pt discretizare xi  ->  f'(xi) = (f(xi+1) - f(xi-1)) / (xi+1 - xi-1), unde\r\n    xi-1  => nodul i-1 al vectorului x\r\n\r\n    \"\"\"\r\n    n = len(X)\r\n    df = np.zeros((n - 1, 1))\r\n    \r\n    for i in range(1, n - 1):\r\n        df[i] = (Y[i + 1] - Y[i - 1]) / (X[i + 1] - X[i - 1])\r\n    \r\n    return df\r\n\r\n\r\n\r\n\r\n### Exercițiul 1\r\n\r\ndef f(x):\r\n    return np.sin(x)\r\n\r\na = 0\r\nb = np.pi\r\nn = 100\r\nx_graf = np.linspace(a, b, n)\r\ny_graf = f(x_graf)\r\n\r\nx = sym.symbols('x')\r\nf_expr = sym.sin(x)   \r\ndf = sym.diff(f_expr, x)\r\ndfFunc = sym.lambdify(x, df)\r\n\r\nplt.plot(x_graf, dfFunc(x_graf), linewidth = 2)\r\nplt.grid(True)\r\n\r\ndfaprox = difFinProg(x_graf, y_graf)\r\nplt.plot(x_graf[0:n-1], dfaprox, linewidth = 2)\r\nplt.show()\r\n\r\nerr = np.zeros((n - 1, 1))\r\nfor i in range(n - 1):\r\n    err[i] = abs(dfFunc(x_graf[i]) - dfaprox[i])\r\n\r\nplt.plot(x_graf[0:n-1], err, linewidth = 2)\r\nplt.grid(True)\r\nplt.show()\r\n\r\n# Pasul\r\nprint(x_graf[1] - x_graf[0])\r\n\r\n\r\n# Metoda Reg\r\ndfaprox2 = difFinReg(x_graf, y_graf)\r\nplt.plot(x_graf[1:n], dfaprox2[1:n], linewidth = 2)\r\nplt.grid(True)\r\nplt.show()\r\n\r\nerr = np.zeros((n, 1))\r\nfor i in range(1, n):\r\n    err[i] = abs(dfFunc(x_graf[i]) - dfaprox2[i])\r\n\r\nplt.plot(x_graf[1:n], err[1:n], linewidth = 2)\r\nplt.grid(True)\r\nplt.show()\r\n\r\n\r\n# Metoda Cen\r\ndfaprox3 = difFinCen(x_graf, y_graf)\r\nplt.plot(x_graf[1:n-1], dfaprox3[1:n-1], linewidth = 2)\r\nplt.grid(True)\r\nplt.show()\r\n\r\nerr = np.zeros((n-1, 1))\r\nfor i in range(1, n-1):\r\n    err[i] = abs(dfFunc(x_graf[i]) - dfaprox3[i])\r\n\r\nplt.plot(x_graf[1:n-1], err[1:n-1], linewidth = 2)\r\nplt.grid(True)\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n### Proceduri -> Ex2\r\ndef MetRichardson(phi, x, h, n):\r\n    \"\"\"\r\n    Parameters\r\n    ----------\r\n    phi : formula de aproximare a derivatei cu un ordin inferior.\r\n    x : punctul în care calculez derivata.\r\n    h : pasul.\r\n    n : ordinul de aproximare al derivatei (superior).\r\n\r\n    Returns\r\n    -------\r\n    df = derivata aproximativă\r\n\r\n    \"\"\"\r\n    Q = np.zeros((n, n))\r\n    for i in range(n):\r\n        Q[i, 0] = phi(x, h / 2 ** i)\r\n    \r\n    for i in range(1, n):\r\n        for j in range(1, i + 1):\r\n            Q[i, j] = Q[i, j - 1] + 1 / (2 ** j - 1) * (Q[i, j - 1] - Q[i - 1, j - 1])\r\n    \r\n    return Q[n - 1 , n - 1]\r\n\r\n\r\n\r\n# Exercițiul 2\r\ndef phi(x, h):\r\n    return (f(x + h) - f(x)) / h\r\n\r\n\r\ndf_richardson = np.zeros((n, 1))\r\nN = 3 # ordinul de aproximare la care dorim să ajungem cu met Richardson\r\n\r\nfor i in range(len(x_graf)):\r\n    # pas echidistant\r\n    df_richardson[i] = MetRichardson(phi, x_graf[i], x_graf[1] - x_graf[0], N)\r\n\r\nplt.plot(x_graf, df_richardson, linewidth = 2)\r\nplt.show()\r\n\r\nerr = np.zeros((n, 1))\r\nfor i in range(n):\r\n    err[i] = abs(dfFunc(x_graf[i]) - df_richardson[i])\r\nplt.plot(x_graf, err, linewidth = 2)\r\nplt.show()\r\n\r\n\r\n\r\n# d.\r\n# Aproximeaza a doua derivata si are ordinul de aproximare h^2\r\ndef phi2(x, h):\r\n    return (f(x + h) - 2 * f(x) + f(x - h)) / h ** 2\r\n\r\n\r\nN = 5 # eroarea creste din cauza rotunjirilor făcute de pc (erori interne)\r\nd2f_richardson = np.zeros((n, 1))\r\nfor i in range(len(x_graf)):\r\n    d2f_richardson[i] = MetRichardson(phi2, x_graf[i], (x_graf[1] - x_graf[0]), N - 1)\r\n\r\n\r\nplt.figure(9)\r\nplt.plot(x_graf, d2f_richardson, linewidth=3)\r\nplt.show()\r\n\r\nd2f = sym.diff(df, x)\r\nd2f_func = sym.lambdify(x, d2f)\r\n\r\nerr2 = np.zeros((n, 1))\r\nfor i in range(n):\r\n    err2[i] = np.abs(d2f_func(x_graf[i]) - d2f_richardson[i])\r\n\r\n\r\nplt.figure(10)\r\nplt.plot(x_graf, err2, linewidth=3)\r\nplt.show()\r\n        \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "f297f810d2d9d147f5a2ab86cfea7f55aa434fe9", "size": 4607, "ext": "py", "lang": "Python", "max_stars_repo_path": "Calcul Numeric (CN)/Laborator/Laborator 12/lab12.py", "max_stars_repo_name": "DLarisa/FMI-Materials-BachelorDegree", "max_stars_repo_head_hexsha": "138e1a20bc33617772e9cd9e4432fbae99c0250c", "max_stars_repo_licenses": ["W3C"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-02-12T02:05:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T14:44:43.000Z", "max_issues_repo_path": "Calcul Numeric (CN)/Laborator/Laborator 12/lab12.py", "max_issues_repo_name": "DLarisa/FMI-Materials-BachelorDegree-UniBuc", "max_issues_repo_head_hexsha": "138e1a20bc33617772e9cd9e4432fbae99c0250c", "max_issues_repo_licenses": ["W3C"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Calcul Numeric (CN)/Laborator/Laborator 12/lab12.py", "max_forks_repo_name": "DLarisa/FMI-Materials-BachelorDegree-UniBuc", "max_forks_repo_head_hexsha": "138e1a20bc33617772e9cd9e4432fbae99c0250c", "max_forks_repo_licenses": ["W3C"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.062962963, "max_line_length": 87, "alphanum_fraction": 0.5137833731, "include": true, "reason": "import numpy,import sympy", "num_tokens": 1708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780479, "lm_q2_score": 0.9005297774417915, "lm_q1q2_score": 0.8552055427874987}}
{"text": "import numpy as np\n\ndef hms2dec(h,m,s):\n  return 15*(h + (m/60) + (s/3600))\n\ndef dms2dec(d,m,s):\n  if d>=0:\n    return (d + (m/60) + (s/3600))\n  return (d - (m/60) - (s/3600))\n\ndef angular_dist(r1, d1, r2, d2):  \n  r1= np.radians(r1)\n  r2= np.radians(r2)\n  d1= np.radians(d1)\n  d2= np.radians(d2)\n  a = (np.sin(np.abs(d1 - d2)/2))**2\n  b = np.cos(d1)*np.cos(d2)*np.sin(np.abs(r1 - r2)/2)**2\n  d = np.degrees(2*np.arcsin(np.sqrt(a + b)))\n  return d\n\ndef import_bss():\n  cat = np.loadtxt('bss.dat', usecols=range(1, 7))\n  loaded = []\n  count = 1\n  for i in cat:\n    loaded.append((count, hms2dec(i[0],i[1],i[2]), dms2dec(i[3],i[4],i[5])))\n    count+=1\n  return loaded\n\ndef import_super():\n  cat = np.loadtxt('super.csv', delimiter=',', skiprows=1, usecols=[0, 1])\n  loaded = []\n  count = 1\n  for i in cat:\n    loaded.append((count, i[0], i[1]))\n    count+=1\n  return loaded\n\ndef find_closest(catalogue,target_ra, target_dec):\n  min_distance = 9999999\n  ID = 0\n  for i in catalogue:\n    distance = angular_dist(i[1], i[2], target_ra, target_dec)\n    if distance<min_distance:\n      min_distance = distance\n      ID = i[0]\n  return (ID,min_distance)\n\ndef crossmatch(bss_cat, super_cat, max_dist):\n  matches = []\n  no_matches = []\n  \n  for i in bss_cat:\n      best = (0,0,max_dist+1)\n      \n      for j in super_cat:\n        dist = angular_dist(i[1], i[2], j[1], j[2])\n        if dist<=best[2]:\n          best = (i[0],j[0],dist)\n          \n      if best[2]<=max_dist:\n         matches.append(best)\n      else:\n         no_matches.append(i[0])\n \n  return (matches, no_matches)\n\n\nif __name__ == '__main__':\n  bss_cat = import_bss()\n  super_cat = import_super()\n\n  max_dist = 40/3600\n  matches, no_matches = crossmatch(bss_cat, super_cat, max_dist)\n  print(matches[:3])\n  print(no_matches[:3])\n  print(len(no_matches))\n\n  max_dist = 5/3600\n  matches, no_matches = crossmatch(bss_cat, super_cat, max_dist)\n  print(matches[:3])\n  print(no_matches[:3])\n  print(len(no_matches))\n", "meta": {"hexsha": "375719f15e33adb3c62ac68dfa9857af401442e2", "size": 1967, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week2/Assignment1/cross_matcher.py", "max_stars_repo_name": "vinayak1998/Data_Driven_Astronomy", "max_stars_repo_head_hexsha": "1d0dd82b2e9066759c442807c30c70bef096d719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-21T07:31:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T05:25:44.000Z", "max_issues_repo_path": "Week2/Assignment1/cross_matcher.py", "max_issues_repo_name": "vinayak1998/Data_Driven_Astronomy", "max_issues_repo_head_hexsha": "1d0dd82b2e9066759c442807c30c70bef096d719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week2/Assignment1/cross_matcher.py", "max_forks_repo_name": "vinayak1998/Data_Driven_Astronomy", "max_forks_repo_head_hexsha": "1d0dd82b2e9066759c442807c30c70bef096d719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-24T21:12:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-18T12:26:45.000Z", "avg_line_length": 23.4166666667, "max_line_length": 76, "alphanum_fraction": 0.6034570412, "include": true, "reason": "import numpy", "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.8991213867309121, "lm_q1q2_score": 0.8551923130635504}}
{"text": "#!/bin/env python\n\n\"\"\"\nModule for approximating sqrt\n\"\"\"\n\n\ndef sqrt(x,debug=False):\n   \"\"\"\n   Module implementing newton's method for approximating sqrt\n   \"\"\"\n   from numpy import nan\n\n   if x == 0.:\n       return 0.\n   elif x<0:\n       print \"***Error, x must be positive\"\n       return nan\n   assert x>0, \"Should not get here!\"\n   s = 1.\n   kmax = 100\n   tol = 1.e-14\n\n   for k in range(kmax):\n       if debug:\n           print \"Before iteration {}, s = {:20.15f}\".format(k,s)\n       s0 = s\n       s = 0.5 * ( s + x/s )\n       delta_s = s - s0\n       if abs(delta_s/x) < tol:\n           break\n   if debug:\n       print \"After {} iterations, s = {:20.15f}\".format(k+1,s)\n   return s\n\n", "meta": {"hexsha": "48954812a3341edd82ea2390f940b2c076f68ca5", "size": 686, "ext": "py", "lang": "Python", "max_stars_repo_path": "ScientificComputing/mysqrt.py", "max_stars_repo_name": "mr-ice/pipython", "max_stars_repo_head_hexsha": "ea27af520946cb710cb717815be625489fc8a1a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ScientificComputing/mysqrt.py", "max_issues_repo_name": "mr-ice/pipython", "max_issues_repo_head_hexsha": "ea27af520946cb710cb717815be625489fc8a1a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ScientificComputing/mysqrt.py", "max_forks_repo_name": "mr-ice/pipython", "max_forks_repo_head_hexsha": "ea27af520946cb710cb717815be625489fc8a1a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0555555556, "max_line_length": 65, "alphanum_fraction": 0.5262390671, "include": true, "reason": "from numpy", "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.8991213799730775, "lm_q1q2_score": 0.8551923103715614}}
{"text": "#!/usr/bin/env python3\n\nimport numpy as np\n\nimport problems as pb\nimport plotter\n\n#################################################\n### Public Variables\n#################################################\n\nENABLE_ERRORS_CALCULATION = True\nENABLE_SOLUTION_PLOTTING = False\n\nENABLE_GRAPHS_VIEW = False\nSAVE_GRAPHS_IMAGE = True\n\n#################################################\n### Functions Definitions\n#################################################\n\ndef matrix_decomposition(a_matrix_diag, a_matrix_subdiag):\n    \"\"\"\n    Decompõe uma matrix A tridiagonal simétrica em três matrizes\n    L, D e Lt, retornando apenas dois vetores que representam as\n    matrizes L e D.\n    \"\"\"\n\n    array_size = len(a_matrix_diag)\n\n    l_matrix_array = np.zeros(array_size, dtype=float)\n    d_matrix_array = np.zeros(array_size, dtype=float)\n\n    l_matrix_array[0] = 0\n    d_matrix_array[0] = a_matrix_diag[0]\n\n    for i in range(1, array_size):\n        l_matrix_array[i] = a_matrix_subdiag[i] / d_matrix_array[i - 1]\n\n        d_matrix_array[i] = a_matrix_diag[i] - d_matrix_array[i - 1] * ((l_matrix_array[i])**2)\n\n    return l_matrix_array, d_matrix_array\n\n\n\ndef solve_system(a_matrix_diag, a_matrix_subdiag, b_array):\n    \"\"\"\n    Soluciona um sistema Ax = b, onde A é uma matrix tridiagonal\n    simétrica.\n\n    Para a resolução do sistema, é feita a decomposição de A para L*D*Lt.\n\n    É feita a divisão do problema em três sistemas menores:\n    L * y = b\n    D * z = y\n    Lt * x = z\n    \"\"\"\n\n    array_size = len(a_matrix_diag)\n\n    l_matrix_array, d_matrix_array = matrix_decomposition(a_matrix_diag, a_matrix_subdiag)\n\n    # First system solution -> L * y = b\n    y_array = np.zeros(array_size, dtype=float)\n\n    y_array[0] = b_array[0]\n\n    for i in range(1, array_size):\n        y_array[i] = b_array[i] - l_matrix_array[i] * y_array[i - 1]\n\n    # Second system solution -> D * z = y\n    z_array = np.zeros(array_size, dtype=float)\n\n    for i in range(0, array_size):\n        z_array[i] = y_array[i] / d_matrix_array[i]\n\n    # Third system solution -> Lt * x = z\n    x_array = np.zeros(array_size, dtype=float)\n\n    x_array[-1] = z_array[-1]\n\n    for i in reversed(range(0, array_size - 1)):\n        x_array[i] = z_array[i] - l_matrix_array[i + 1] * x_array[i + 1]\n\n    return x_array\n\n\n\ndef run(letter, task_result_dir):\n    \"\"\"\n    Soluciona o problema da equação de calor a partir de dois métodos implícitos,\n    Euler implícito e Crank-Nicolson.\n    \"\"\"\n\n    # Input parameters\n    method = (input(\"Qual método executar: Euler implícito ou (e) ou Crank-Nicolson (c)? \")).lower()\n\n    while method not in (\"e\", \"c\"):\n        print(\"Método não encontrado, escolha entre 'e' e 'c'\")\n        method = (input(\"Qual método executar: Euler implícitou (e) ou Crank-Nicolson (c)? \")).lower()\n\n    if method == \"e\":\n        method_name = \"EULER_IMP\"\n    else:\n        method_name = \"CN\"\n\n    N = int(input(\"Insira o valor de N: \"))\n    M = N\n\n    Δx = 1 / float(N)\n    Δt = Δx\n\n    λ = Δt / (Δx**2)\n\n    print(f\"N: {N}, λ: {λ}, Δx: {Δx} e Δt: {Δt}\")\n\n    # Resuls file\n    results_file_name = f\"{task_result_dir}/2{letter.capitalize()}_{method_name}_{N}_ERRORS.txt\"\n\n    if letter != \"c\" and ENABLE_ERRORS_CALCULATION == True:\n        results_file = open(results_file_name, 'w')\n\n    # A Matrix creation\n    if method == \"e\":\n        diag_value = 1 + 2 * λ\n        subdiag_value = -λ\n    else:\n        diag_value = 1 + λ\n        subdiag_value = -λ / 2\n\n    a_matrix_diag = np.full(N - 1, diag_value, dtype=float)\n    a_matrix_subdiag = np.full(N - 1, subdiag_value, dtype=float)\n\n    # B array creation\n    b_array = np.zeros(N - 1, dtype=float)\n\n    # Create and initializes scale array\n    scale_array = np.zeros(N + 1, dtype=float)\n\n    for i in range(0, N + 1):\n        scale_array[i] = i / N\n\n    # Create U matrix\n    U = pb.create_u(scale_array, scale_array, letter)\n\n    # Inside points calculation\n    for k in range(0, M):\n        # b array calculation\n        for i in range(1, N):\n            if method == \"e\":\n                b_array[i - 1] = U[k][i] + Δt * pb.heat_source(scale_array[k + 1], scale_array[i], N, letter)\n            else:\n                b_array[i - 1] = (U[k][i] + (λ / 2) * (U[k][i - 1] - 2 * U[k][i] + U[k][i + 1])\n                               + (Δt / 2) * (pb.heat_source(scale_array[k], scale_array[i], N, letter)\n                               + pb.heat_source(scale_array[k + 1], scale_array[i], N, letter)))\n\n        g1, g2 = pb.boundary_conditions(scale_array[k + 1], letter)\n\n        if method == \"e\":\n            b_array[0] += λ * g1\n            b_array[-1] += λ * g2\n        else:\n            b_array[0] += (λ / 2) * g1\n            b_array[-1] += (λ / 2) * g2\n\n        solution = solve_system(a_matrix_diag, a_matrix_subdiag, b_array)\n\n        for i in range(1, N):\n            U[k + 1][i] = solution[i - 1]\n\n    # Plotting u(t, x)\n    approx_image_name = f\"2{letter.capitalize()}_{method_name}_{N}_APPROX\"\n\n    plotter.u_2d_graph(U, scale_array, scale_array, 11, approx_image_name, ENABLE_GRAPHS_VIEW, SAVE_GRAPHS_IMAGE, task_result_dir)\n\n    plotter.u_3d_graph(U, scale_array, scale_array, N, approx_image_name, ENABLE_GRAPHS_VIEW, SAVE_GRAPHS_IMAGE, task_result_dir)\n\n    if letter != \"c\":\n        if ENABLE_SOLUTION_PLOTTING == True:\n            # Plotting the u solution\n            u_sol = np.zeros((M + 1, N + 1))\n\n            for k in range(0, M + 1):\n                for i in range(0, N + 1):\n                    u_sol[k][i] = pb.u_solution(scale_array[k], scale_array[i], letter)\n\n            sol_image_name = f\"2{letter.capitalize()}_{method_name}_{N}_SOL\"\n\n            plotter.u_2d_graph(u_sol, scale_array, scale_array, 11, sol_image_name, ENABLE_GRAPHS_VIEW, SAVE_GRAPHS_IMAGE, task_result_dir)\n\n            plotter.u_3d_graph(u_sol, scale_array, scale_array, N, sol_image_name, ENABLE_GRAPHS_VIEW, SAVE_GRAPHS_IMAGE, task_result_dir)\n\n        if ENABLE_ERRORS_CALCULATION == True:\n            if method == \"e\":\n                # Truncation error calculation\n                max_truncation_error = 0\n\n                for k in range(0, M):\n                    for i in range(1, N):\n                        first_term = (pb.u_solution(scale_array[k + 1], scale_array[i], letter)\n                                   - pb.u_solution(scale_array[k], scale_array[i], letter)) / Δt\n                        second_term = (pb.u_solution(scale_array[k + 1], scale_array[i - 1], letter)\n                                    - 2 * pb.u_solution(scale_array[k + 1], scale_array[i], letter)\n                                    + pb.u_solution(scale_array[k + 1], scale_array[i + 1], letter)) / (Δx**2)\n\n                        current_truncation_error = abs(first_term - second_term - pb.heat_source(scale_array[k + 1], scale_array[i], N, letter))\n\n                        if current_truncation_error > max_truncation_error:\n                            max_truncation_error = current_truncation_error\n\n                max_truncation_error_result = f\"O erro máximo de truncamento é {max_truncation_error}\"\n                print(max_truncation_error_result)\n                results_file.write(max_truncation_error_result + \"\\n\")\n\n            # Approximation error calculation for T = 1\n            max_approx_error = 0\n\n            for i in range(0, N):\n                current_approx_error = abs(pb.u_solution(scale_array[M], scale_array[i], letter) - U[M][i])\n\n                if current_approx_error > max_approx_error:\n                    max_approx_error = current_approx_error\n\n            max_approx_error_result = f\"O erro máximo de aproximação é {max_approx_error}\"\n            print(max_approx_error_result)\n            results_file.write(max_approx_error_result)\n\n        # End task\n        results_file.close()\n", "meta": {"hexsha": "00a9adbeebc8f93d3fa5d8af639e13f4c9eca1bc", "size": 7746, "ext": "py", "lang": "Python", "max_stars_repo_path": "EP1/task_two.py", "max_stars_repo_name": "LucasHaug/MAP3121", "max_stars_repo_head_hexsha": "90b69c5db20e6d56c0c3e3dd969d9e41d804e9be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EP1/task_two.py", "max_issues_repo_name": "LucasHaug/MAP3121", "max_issues_repo_head_hexsha": "90b69c5db20e6d56c0c3e3dd969d9e41d804e9be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EP1/task_two.py", "max_forks_repo_name": "LucasHaug/MAP3121", "max_forks_repo_head_hexsha": "90b69c5db20e6d56c0c3e3dd969d9e41d804e9be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6782608696, "max_line_length": 144, "alphanum_fraction": 0.5863671572, "include": true, "reason": "import numpy", "num_tokens": 2096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.8991213806488609, "lm_q1q2_score": 0.855192308523879}}
{"text": "import probayes as pb\nimport numpy as np\n\"\"\"\nConsider a disease with a prevalence 1\\% in a given population. \nOf those with the disease, 98\\% manifest a particular symptom,\nthat is present only in 10\\% of those without the disease. \nWhat is the probability someone with symptoms has the disease?\nAnswer: \\approx 9%\n\"\"\"\n\n# PARAMETERS\nprevalence = 0.01\nsym_if_dis = 0.98\nsym_if_undis = 0.1\n\n# SET UP RANDOM VARIABLES\ndis = pb.RV('dis', prob=prevalence)\nsym = pb.RV('sym')\n\n# SET UP STOCHASTIC CONDITION\nsym_given_dis = sym | dis\nsym_given_dis.set_prob(np.array([1-sym_if_undis, 1-sym_if_dis, \\\n                                 sym_if_undis,   sym_if_dis]).reshape((2,2)))\n\n# APPLY BAYES' RULE\np_dis = dis()\np_sym_given_dis = sym_given_dis()\np_dis_and_sym = p_dis * p_sym_given_dis\np_sym = p_dis_and_sym.marginal('sym')\np_dis_given_sym = p_dis_and_sym / p_sym\ninference = p_dis_given_sym({'dis': True, 'sym': True})\nprint(inference)\nassert abs(inference.prob-0.09) < 0.01, \\\n    \"Expected around 0.09 but evaluated {}\".format(inference.prob)\n", "meta": {"hexsha": "9f6522d63af3bb8a56f0e7bd58c44e039ae94e52", "size": 1039, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/checks/bern_bayes.py", "max_stars_repo_name": "Bhumbra/probayes", "max_stars_repo_head_hexsha": "e5ac193076e4188b9b38c0e18466223ab4d041f7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/checks/bern_bayes.py", "max_issues_repo_name": "Bhumbra/probayes", "max_issues_repo_head_hexsha": "e5ac193076e4188b9b38c0e18466223ab4d041f7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/checks/bern_bayes.py", "max_forks_repo_name": "Bhumbra/probayes", "max_forks_repo_head_hexsha": "e5ac193076e4188b9b38c0e18466223ab4d041f7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6857142857, "max_line_length": 77, "alphanum_fraction": 0.7170356112, "include": true, "reason": "import numpy", "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846628255123, "lm_q2_score": 0.8740772236840656, "lm_q1q2_score": 0.8551837497775944}}
{"text": "import numpy as np\n\n\ndef relu(x):\n    \"\"\"\n    Calculate element-wise Rectified Linear Unit (ReLU)\n    :param x: Input array\n    :return: Rectified output\n    \"\"\"\n    return np.maximum(x, 0)\n\n\ndef relu_bw(x):\n    \"\"\"\n    Calculate element-wise ReLU derivative\n    :param x: Input array\n    :return: For each element in x: 1 if x>0, 0 if x<0, N length array\n    \"\"\"\n    return np.greater(x, 0).astype(int)\n\n\ndef sigmoid(x):\n    \"\"\"\n    Calculate element-wise sigmoid\n    :param x: N length array\n    :return: Output 1/(1+exp(-x)), N length array\n    \"\"\"\n    return 1 / (1 + np.exp(-x))\n\n\ndef sigmoid_bw(x):\n    \"\"\"\n    Calculate element-wise sigmoid derivative\n    :param x: N length array\n    :return: Output sigm(x)*(1-sigm(x)), N length array\n    \"\"\"\n    return sigmoid(x) * (1 - sigmoid(x))\n\n\ndef softmax(x):\n    \"\"\"\n    Compute softmax for each value in x\n    :param x: N length array\n    :return: Softmax for ach value between 0-1, N length array\n    \"\"\"\n    max_val = 700\n    # this custom implementation gives overflow errors when used with momentum, so we clip...\n    np.clip(x, -max_val, max_val, out=x)\n    return np.exp(x) / np.sum(np.exp(x), axis=0)\n\n\ndef softmax_bw(softmax_output, label):\n    \"\"\"\n    Cross entropy error with softmax output, backpropagation of deritivative w.r.t the inputs to the softmax function.\n    dE/dzk = softmax_output_k - label_k\n    :param softmax_output: Softmax output vector of length 10.\n    :param label: One-hot encoded label vector of length 10. Example: [0 0 0 0 0 0 1 0 0 0] = 7\n    :return: softmax_output - label\n    \"\"\"\n    return softmax_output - label\n\n\ndef cross_entropy(predictions, label):\n    \"\"\"\n    Calculate the cross entropy.\n    :param predictions: Predicted values, N length array\n    :param label: One-hot encoded label vector. Example: [0 0 0 0 0 0 1 0 0 0] = 7\n    :return: Cross-entropy\n    \"\"\"\n    n = np.size(label)\n    eps = 1e-12 # for numerical stability\n    ce = -np.dot(label, np.log(predictions + eps)) / n\n    return ce\n\n", "meta": {"hexsha": "5c00cebd9d32db2037c9a8f193560878f78fdb25", "size": 1998, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment_1_multi_layer_perceptron/activation.py", "max_stars_repo_name": "langestefan/5LSH0_final_assignments", "max_stars_repo_head_hexsha": "b6765ea9e7b772b19866ebbc47712d6711060670", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment_1_multi_layer_perceptron/activation.py", "max_issues_repo_name": "langestefan/5LSH0_final_assignments", "max_issues_repo_head_hexsha": "b6765ea9e7b772b19866ebbc47712d6711060670", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment_1_multi_layer_perceptron/activation.py", "max_forks_repo_name": "langestefan/5LSH0_final_assignments", "max_forks_repo_head_hexsha": "b6765ea9e7b772b19866ebbc47712d6711060670", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.64, "max_line_length": 118, "alphanum_fraction": 0.6406406406, "include": true, "reason": "import numpy", "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.901920681802153, "lm_q1q2_score": 0.8551601858156749}}
{"text": "import numpy as np\n\n# Gradient based methods for linear systems\n\ndef compute_mse(y, tx, w):\n    \"\"\"\n    Compute the Mean Square Error as defined in class.\n    Takes as input the targeted y, the sample matrix X and the feature fector w.\n    \"\"\"\n    e = y - tx@w\n    mse = e.T.dot(e) /(2*len(e))\n    return mse\n\ndef least_squares(y, tx):\n    \"\"\"\n    Compute an esimated solution of the problem y = tx @ w, and the associated error. This method is equivalent \n    to the minimization problem of finding w such that |y-tx@w||^2 is minimal. Note that this methods provides the global optimum.\n    The error is the mean square error of the targeted y and the solution produced by the least square function.\n    Takes as input the targeted y, and the sample matrix X.\n    \"\"\"\n    w = np.linalg.solve (tx.T.dot(tx),tx.T.dot(y))\n    mse = compute_mse(y, tx, w)\n    return w, mse \n\ndef least_squares_gradient(y, tx, w):\n    \"\"\"\n    Compute the gradient of the mean square error with respect to w, and the current error vector e.\n    Takes as input the targeted y, the sample matrix w and the feature vector w. \n    This function is used when solving gradient based method, such that least_squares_GD() and least_squares_SGD().\n    \"\"\"  \n    e = y - tx.dot(w)\n    grad = -tx.T.dot(e) / len(e)\n    return grad, e\n\ndef least_squares_GD(y, tx, initial_w=None, max_iters=50, gamma=0.1):\n    \"\"\"\n    Compute an estimated solution of the problem y = tx @ w and the associated error using Gradient Descent. \n    This method is equivalent to the minimization problem of finding w such that |y-tx@w||^2 is minimal. Note that \n    this method may output a local minimum, while least_squares() provides the global minimum.\n    Takes as input:\n        * the targeted y\n        * the sample matrix w\n        * the initial guess for w, by default set as a vector of zeros\n        * the number of iterations for Gradient Descent\n        * the learning rate gamma\n    \"\"\"\n    # Define parameters to store w and loss\n    if np.all(initial_w == None): initial_w = np.zeros(tx.shape[1])  \n    ws = [initial_w] # Initial guess w0 generated randomly\n    losses = []\n    w = ws[0]\n    for n_iter in range(max_iters):\n        # compute loss, gradient\n        grad, err = least_squares_gradient(y, tx, w)\n        loss = compute_mse(y,tx,w)\n        # gradient w by descent update\n        w = w - gamma * grad\n        # store w and loss\n        ws.append(w)\n        losses.append(loss)\n        #if (n_iter % int(max_iters/5)) == 0:\n            #print(\"Gradient Descent({bi}/{ti}): loss={l}\".format(bi=n_iter, ti=max_iters,l=loss))\n    return w,loss\n\ndef batch_iter(y, tx, batch_size, num_batches=1, shuffle=True):\n    \"\"\"\n    Generate a minibatch iterator for a dataset.\n    Takes as input two iterables (here the output desired values 'y' and the input data 'tx')\n    Outputs an iterator which gives mini-batches of `batch_size` matching elements from `y` and `tx`.\n    Data can be randomly shuffled to avoid ordering in the original data messing with the randomness of the minibatches.\n    Example of use :\n    for minibatch_y, minibatch_tx in batch_iter(y, tx, 32):\n        <DO-SOMETHING>\n    \"\"\" \n    data_size = len(y)\n\n    if shuffle:\n        shuffle_indices = np.random.permutation(np.arange(data_size))\n        shuffled_y = y[shuffle_indices]\n        shuffled_tx = tx[shuffle_indices]\n    else:\n        shuffled_y = y\n        shuffled_tx = tx\n    for batch_num in range(num_batches):\n        start_index = batch_num * batch_size\n        end_index = min((batch_num + 1) * batch_size, data_size)\n        if start_index != end_index:\n            yield shuffled_y[start_index:end_index], shuffled_tx[start_index:end_index]\n\ndef least_squares_SGD(y, tx, initial_w=None, batch_size=1, max_iters=50, gamma=0.00005):\n    \"\"\"\n    Compute an estimated solution of the problem y = tx @ w and the associated error using Stochastic Gradient Descent. \n    Takes as input:\n        * the targeted y\n        * the sample matrix w\n        * the initial guess for w, by default set as a vector of zeros\n        * the batch_size, which is the number of samples on which the new gradient is computed. If set to 1 it corresponds\n        to Stochastic Gradient Descent, to the full number of samples it is identifical to least_squares_GD().\n        * the number of iterations for Gradient Descent\n        * the learning rate gamma\n    \"\"\"\n    # Define parameters to store w and loss\n    if np.all(initial_w == None): initial_w = np.zeros(tx.shape[1])\n    losses = []\n    w = initial_w\n    for n_iter in range(max_iters):\n        for y_batch, tx_batch in batch_iter(y, tx, batch_size=batch_size, num_batches=1):\n            # compute a stochastic gradient and loss\n            grad, _ = least_squares_gradient(y_batch, tx_batch, np.array(w))\n            # update w through the stochastic gradient update\n            w = w - gamma * grad\n            # calculate loss\n            loss = compute_mse(y, tx, w)\n            # store w and loss\n            losses.append(loss)\n\n        #if n_iter % int(max_iters/5) == 0:\n            #print(\"SGD({bi}/{ti}): loss={l}\".format(bi=n_iter, ti=max_iters - 1, l=loss))\n    return w,loss\n# RIDGE REGRESSION\n\ndef ridge_regression(y, tx, lambda_):\n    \"\"\"\n    Compute an esimated solution of the problem y = tx @ w , and the associated error. Note that this method\n    is a variant of least_square() but with an added regularization term lambda_. \n    This method is equivalent to the minimization problem of finding w such that |y-tx@w||^2 + lambda_*||w||^2 is minimal. \n    The error is the mean square error of the targeted y and the solution produced by the least square function.\n    Takes as input the targeted y, the sample matrix X and the regulariation term lambda_.\n    \"\"\"\n    x_t = tx.T\n    lambd = lambda_ * 2 * len(y)\n    w = np.linalg.solve (np.dot(x_t, tx) + lambd * np.eye(tx.shape[1]), np.dot(x_t,y)) \n    loss = compute_mse(y, tx, w)\n\n    return w,loss\n\n#LOGISTIC REGRESSION\n\ndef sigmoid(t):\n    \"\"\"\n    Apply the sigmoid function on t.\n    \"\"\"\n    return np.exp(t)/(1+np.exp(t))\n\ndef calculate_loss(y, tx, w):\n    \"\"\"\n    Compute the negative log likelihood as defined in class.\n    Takes as input the targeted y, the sample matrix X and the feature fector w.\n    \"\"\"\n    return np.sum(np.log(1+np.exp(tx@w))-y*(tx@w))\n\ndef calculate_gradient(y, tx, w):\n    \"\"\"\n    Compute the gradient of the negative log likelihood with respect to w, and the current error vector e.\n    Takes as input the targeted y, the sample matrix w and the feature vector w. \n    This function is used when solving gradient based method, such that logistic_regression() and reg_logistic_regression().\n    \"\"\"  \n    return tx.T@(sigmoid(tx@w)-y)\n\ndef learning_by_gradient_descent(y, tx, w, gamma):\n    \"\"\"\n    Compute one step of gradient descent for logistic regression.\n    Takes as input the targeted y, the sample matrix w, the feature w and the learning rate gamma.\n    Return the feature vector w and the error defined as the negative log likelihood.\n    \"\"\"\n    loss = calculate_loss(y,tx,w)\n    grad = calculate_gradient(y,tx,w)\n    w = w-gamma*grad\n    return w, loss\n\ndef logistic_regression(y, tx, initial_w=None, max_iters=100, gamma=0.009, batch_size=1):\n    \"\"\"\n    Compute an estimated solution of the problem y = sigmoid(tx @ w) and the associated error using Gradient Descent. \n    This method is equivalent to the minimization problem of finding w such that the negative log likelihood is minimal. Note that \n    this method may output a local minimum.\n    Takes as input:\n        * the targeted y\n        * the sample matrix w\n        * the initial guess for w, by default set as a vector of zeros\n        * the number of iterations for Stochastic Gradient Descent\n        * the learning rate gamma\n        * the batch_size, which is the number of samples on which the new gradient is computed. If set to 1 it corresponds\n        to Stochastic Gradient Descent, to the full number of samples it is Gradient Descent.\n    \"\"\"\n    # init parameters\n    if np.all(initial_w == None): initial_w = np.zeros(tx.shape[1])\n    threshold = 1e-8\n    losses = []\n    y = (1 + y) / 2\n    # build tx\n    w = initial_w\n\n    # start the logistic regression\n    for i in range(max_iters):\n        # get loss and update w.\n        for y_batch, tx_batch in batch_iter(y, tx, batch_size=batch_size, num_batches=1):\n            w, _ = learning_by_gradient_descent(y_batch, tx_batch, w, gamma)\n            # converge criterion\n            losses.append(calculate_loss(y,tx,w))\n            if len(losses) > 1 and np.abs(losses[-1] - losses[-2]) < threshold:\n                break\n            #if i % int(max_iters/5) == 0:\n                #print(losses[-1],i,'/{tot}'.format(tot=max_iters))\n\n    return w,losses[-1]\n\n\n    \n# Regularized LOGISTIC REGRESSION\n\ndef learning_by_penalized_gradient_descent(y, tx, w, gamma, lambda_):\n    \"\"\"\n    Compute one step of gradient descent for regularized logistic regression.\n    Takes as input the targeted y, the sample matrix w, the feature w and the learning rate gamma.\n    Return the feature vector w and the error defined as the negative log likelihood.\n    \"\"\"\n    loss = calculate_loss(y, tx, w) + lambda_ * np.squeeze(w.T.dot(w))\n    grad = calculate_gradient(y, tx, w) + 2 * lambda_ * w\n    w = w-gamma*grad\n    return w, loss\n\ndef reg_logistic_regression(y, tx, lambda_, initial_w=None, max_iters=100, gamma=0.009, batch_size=1):\n    \"\"\"\n    Compute an estimated solution of the problem y = sigmoid(tx @ w) and the associated error using Gradient Descent. \n    Note that this method is a variant of logistic_regression() but with an added regularization term lambda_. \n    This method is equivalent to the minimization problem of finding w such that the negative log likelihood is minimal. Note that \n    this method may output a local minimum.\n    Takes as input:\n        * the targeted y\n        * the sample matrix w\n        * the initial guess for w, by default set as a vector of zeros\n        * the number of iterations for Stochastic Gradient Descent\n        * the learning rate gamma\n        * the batch_size, which is the number of samples on which the new gradient is computed. If set to 1 it corresponds\n        to Stochastic Gradient Descent, to the full number of samples it is Gradient Descent.\n    \"\"\"\n    # init parameters\n    if np.all(initial_w == None): initial_w = np.zeros(tx.shape[1])\n    threshold = 1e-8\n    losses = []\n    y = (1 + y) / 2\n    # build tx\n    w = initial_w\n\n    # start the logistic regression\n    for iter in range(max_iters):\n        # get loss and update w.\n        for y_batch, tx_batch in batch_iter(y, tx, batch_size=batch_size, num_batches=1):\n            w, loss = learning_by_penalized_gradient_descent(y_batch, tx_batch, w, gamma, lambda_)\n            # converge criterion\n            loss = calculate_loss(y, tx, w) + lambda_ * np.squeeze(w.T.dot(w))\n            losses.append(loss)\n            if len(losses) > 1 and np.abs(losses[-1] - losses[-2]) < threshold:\n                break\n            #if iter % int(max_iters/5) == 0:\n                #print(losses[-1],iter,'/{tot}'.format(tot=max_iters))\n\n    return w,losses[-1]", "meta": {"hexsha": "190c771ff9ce2b283688da14dfa381d6eb514832", "size": 11198, "ext": "py", "lang": "Python", "max_stars_repo_path": "implementations.py", "max_stars_repo_name": "riccardocadei/Higgs-Boson-Challange-2020-EPFL", "max_stars_repo_head_hexsha": "76951443fc4e1489f0fb7e7b928056829818e207", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-18T09:51:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-19T09:46:59.000Z", "max_issues_repo_path": "implementations.py", "max_issues_repo_name": "riccardocadei/higgs-boson-classification", "max_issues_repo_head_hexsha": "76951443fc4e1489f0fb7e7b928056829818e207", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "implementations.py", "max_forks_repo_name": "riccardocadei/higgs-boson-classification", "max_forks_repo_head_hexsha": "76951443fc4e1489f0fb7e7b928056829818e207", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-01T13:44:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T13:44:08.000Z", "avg_line_length": 43.4031007752, "max_line_length": 131, "alphanum_fraction": 0.6602071799, "include": true, "reason": "import numpy", "num_tokens": 2793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152282, "lm_q2_score": 0.9019206824612297, "lm_q1q2_score": 0.8551601851192604}}
{"text": "from numpy import exp, cos, linspace, zeros_like\nimport matplotlib.pyplot as plt\nimport os, time, glob, math\n\ndef damped_vibrations(t, A, b, w):\n    return A*exp(-b*t)*cos(w*t)\n\ndef compute_vib(A, b, w, T, resolution=500):\n    \"\"\"Return filename of plot of the damped_vibration function.\"\"\"\n    t = linspace(0, T, resolution+1)\n    y = damped_vibrations(t, A, b, w)\n    plt.figure()  # needed to avoid adding curves in plot\n    plt.plot(t, y)\n    plt.title('A=%g, b=%g, w=%g' % (A, b, w))\n\n    # Make Matplotlib write to BytesIO file object and grab\n    # return the object's string\n    from io import BytesIO\n    figfile = BytesIO()\n    plt.savefig(figfile, format='png')\n    figfile.seek(0)  # rewind to beginning of file\n    import base64\n    figdata_png = base64.b64encode(figfile.getvalue())\n    figfile = BytesIO()\n    plt.savefig(figfile, format='svg')\n    figfile.seek(0)\n    figdata_svg = '<svg' + figfile.getvalue().split('<svg')[1]\n    figdata_svg = unicode(figdata_svg,'utf-8')\n    return figdata_png, figdata_svg\n\ndef gamma_density(x, a, h, A):\n    # http://en.wikipedia.org/wiki/Gamma_distribution\n    xA = x/float(A)\n    return abs(h)/(math.gamma(a)*A)*(xA)**(a*h-1)*exp(-xA**h)\n\ndef gamma_cumulative(x, a, h, A):\n    # Integrate gamma_density using the Trapezoidal rule.\n    # Assume x is array.\n    g = gamma_density(x, a, h, A)\n    r = zeros_like(x)\n    for i in range(len(r)-1):\n        r[i+1] = r[i] + 0.5*(g[i] + g[i+1])*(x[i+1] - x[i])\n    return r\n\ndef compute_gamma(a=0.5, h=2.0, A=math.sqrt(2), resolution=500):\n    \"\"\"Return plot and mean/st.dev. value of the gamma density.\"\"\"\n    gah = math.gamma(a + 1./h)\n    mean = A*gah/math.gamma(a)\n    stdev = A/math.gamma(a)*math.sqrt(\n        math.gamma(a + 2./h)*math.gamma(a) - gah**2)\n    x = linspace(0, 7*stdev, resolution+1)\n    y = gamma_density(x, a, h, A)\n    plt.figure()  # needed to avoid adding curves in plot\n    plt.plot(x, y)\n    plt.title('a=%g, h=%g, A=%g' % (a, h, A))\n    # Make Matplotlib write to BytesIO file object and grab\n    # return the object's string\n    from io import BytesIO\n    figfile = BytesIO()\n    plt.savefig(figfile, format='png')\n    figfile.seek(0)  # rewind to beginning of file\n    import base64\n    figdata_density_png = base64.b64encode(figfile.getvalue())\n    figfile = BytesIO()\n    plt.savefig(figfile, format='svg')\n    figfile.seek(0)\n    figdata_density_svg = '<svg' + figfile.getvalue().split('<svg')[1]\n    figdata_density_svg = unicode(figdata_density_svg,'utf-8')\n\n    y = gamma_cumulative(x, a, h, A)\n    plt.figure()\n    plt.plot(x, y)\n    plt.grid(True)\n    figfile = BytesIO()\n    plt.savefig(figfile, format='png')\n    figfile.seek(0)\n    figdata_cumulative_png = base64.b64encode(figfile.getvalue())\n    figfile = BytesIO()\n    plt.savefig(figfile, format='svg')\n    figfile.seek(0)\n    figdata_cumulative_svg = '<svg' + figfile.getvalue().split('<svg')[1]\n    figdata_cumulative_svg = unicode(figdata_cumulative_svg,'utf-8')\n    return figdata_density_png, figdata_cumulative_png, \\\n           figdata_density_svg, figdata_cumulative_svg, \\\n           '%.2f' % mean, '%.2f' % stdev\n", "meta": {"hexsha": "f1cb95e162cd311b27cc652d6ab99d8442de79a8", "size": 3115, "ext": "py", "lang": "Python", "max_stars_repo_path": "example files/flask_apps/gen/compute.py", "max_stars_repo_name": "nikku1234/InbreastData-Html-Page", "max_stars_repo_head_hexsha": "5f02b2e03e5f2f8f9fe9e2ce1b089b4dd2e36323", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-02T06:06:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-02T06:06:18.000Z", "max_issues_repo_path": "example files/flask_apps/gen/compute.py", "max_issues_repo_name": "nikku1234/InbreastData-Html-Page", "max_issues_repo_head_hexsha": "5f02b2e03e5f2f8f9fe9e2ce1b089b4dd2e36323", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-06-17T14:19:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:36:20.000Z", "max_forks_repo_path": "example files/flask_apps/gen/compute.py", "max_forks_repo_name": "nikku1234/InbreastData-Html-Page", "max_forks_repo_head_hexsha": "5f02b2e03e5f2f8f9fe9e2ce1b089b4dd2e36323", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2209302326, "max_line_length": 73, "alphanum_fraction": 0.6414125201, "include": true, "reason": "from numpy", "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152283, "lm_q2_score": 0.90192067059785, "lm_q1q2_score": 0.8551601738709431}}
{"text": "import numpy as np\n\n\ndef compute_cost(x, y, size, theta):\n    \"\"\"\n        Compute the cost function for linear regression.\n\n        Parameters\n        ----------\n        x : array_like\n            Shape (m, n+1), where m is the number of examples, and n is the number of features\n            including the vector of ones for the zeroth parameter.\n\n        y : array_like\n            Shape (m,), where m is the value of the function at each point.\n\n        size : int\n            Number of total training points.\n\n        theta : array_like\n            Shape (n+1, 1). Starting parameters of the regression function.\n\n        Returns\n        -------\n        cost : float\n            The value of the regression cost function.\n    \"\"\"\n\n    cost = np.sum((1 / (2 * size)) * (((np.dot(theta.T, x)) - y) ** 2))\n    return cost\n", "meta": {"hexsha": "ec568739ec3875d9cc214f07053a7d3d6e2e0102", "size": 822, "ext": "py", "lang": "Python", "max_stars_repo_path": "compute_cost.py", "max_stars_repo_name": "KevinKronk/linear-regression", "max_stars_repo_head_hexsha": "1f1eb4bfcb5603b29df499fb7bfb2ab4b8d2d791", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "compute_cost.py", "max_issues_repo_name": "KevinKronk/linear-regression", "max_issues_repo_head_hexsha": "1f1eb4bfcb5603b29df499fb7bfb2ab4b8d2d791", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compute_cost.py", "max_forks_repo_name": "KevinKronk/linear-regression", "max_forks_repo_head_hexsha": "1f1eb4bfcb5603b29df499fb7bfb2ab4b8d2d791", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5161290323, "max_line_length": 94, "alphanum_fraction": 0.5510948905, "include": true, "reason": "import numpy", "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9802808724687407, "lm_q2_score": 0.8723473614033683, "lm_q1q2_score": 0.8551454325322978}}
{"text": "\"\"\"\r\nDemonstrate Root Finding of Polynomials, Including Complex Roots\r\nLearning Example for Dr. Stanier's classes\r\nFile: E8_show_numpy_roots\r\n\r\nAuthor: Charles Stanier, charles-stanier@uiowa.edu\r\nDate:  August 27, 2019\r\nWritten/Tested In: Python 3.7.3\r\n\r\nProgram Objective: Demonstrate how to solve for the roots of a polynomial\r\nsuch as a parabola or a cubic equation\r\n\r\nModifications: none so far\r\n  \r\n\"\"\"\r\n\r\nimport numpy as np  # this is used for math functions\r\nimport pylab as pl  # this is used for plotting functions\r\n\r\n# let's make a polynomial - starting with a line\r\n\r\np_array = [ 2, 1]  # [ 2 1 ] would be y = 2x + 1.  slope 2 and crosses x=0 at y=1\r\n\r\n# and plot is from x -10 to 10\r\nx_array = np.linspace(-10,10,100)\r\ny_array = np.polyval(p_array,x_array)\r\n\r\npl.plot(x_array,y_array)\r\npl.plot([-10,10],[ 0,0 ]) # x=0 line\r\npl.plot([0,0],[-10,10]) # y=0 line\r\npl.xlim([-10,10])\r\npl.ylim([-10,10])\r\npl.show()\r\n\r\nr = np.roots(p_array)\r\n# print out the roots\r\nic=1 # counter\r\nfor rval in r:\r\n    print('Root ',ic,'x= ',rval)\r\n    ic+=1\r\n    \r\n# let's make a polynomial - now a parabola with real roots\r\n\r\np_array = [ 2, 1, -3 ]  # [ 2, 4, -3 ] would be y = 2x^2 + 4x - 3. \r\n\r\n# and plot is from x -10 to 10\r\ny_array = np.polyval(p_array,x_array)\r\n\r\npl.plot(x_array,y_array)\r\npl.plot([-10,10],[ 0,0 ]) # x=0 line\r\npl.plot([0,0],[-10,10]) # y=0 line\r\npl.xlim([-10,10])\r\npl.ylim([-10,10])\r\npl.show()\r\n\r\nr = np.roots(p_array)\r\n# print out the roots\r\nic=1 # counter\r\nfor rval in r:\r\n    print('Root ',ic,'x= ',rval)\r\n    ic+=1\r\n    \r\n# let's make a polynomial - now a parabola with complex conjugate roots\r\n\r\np_array = [ 2, 4, 3 ]  # [ 2, 4, 3 ] would be y = 2x^2 + 4x + 3.  \r\n\r\n# and plot is from x -10 to 10\r\ny_array = np.polyval(p_array,x_array)\r\n\r\npl.plot(x_array,y_array)\r\npl.plot([-10,10],[ 0,0 ]) # x=0 line\r\npl.plot([0,0],[-10,10]) # y=0 line\r\npl.xlim([-10,10])\r\npl.ylim([-10,10])\r\npl.show()\r\n\r\nr = np.roots(p_array)\r\n# print out the roots\r\nic=1 # counter\r\nfor rval in r:\r\n    print('Root ',ic,'x= ',rval)\r\n    ic+=1\r\n    \r\n# let's make a polynomial - now a cubic\r\n\r\np_array = [ 1, 2, 4, 3 ]  # [ 1, 2, 4, 3 ] would be y = x^3 + 2x^2 + 4x + 3.  \r\n\r\n# and plot is from x -10 to 10\r\ny_array = np.polyval(p_array,x_array)\r\n\r\npl.plot(x_array,y_array)\r\npl.plot([-10,10],[ 0,0 ]) # x=0 line\r\npl.plot([0,0],[-10,10]) # y=0 line\r\npl.xlim([-10,10])\r\npl.ylim([-10,10])\r\npl.show()\r\n\r\nr = np.roots(p_array)\r\n# print out the roots\r\nic=1 # counter\r\nfor rval in r:\r\n    print('Root ',ic,'x= ',rval)\r\n    ic+=1", "meta": {"hexsha": "364697432478a276d47a481fc8d2629acf976eb7", "size": 2506, "ext": "py", "lang": "Python", "max_stars_repo_path": "E8_show_numpy_roots.py", "max_stars_repo_name": "charles-stan/learn_python_Stanier", "max_stars_repo_head_hexsha": "740a7104fcbd739663d703d3770f9e31509300f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-04T14:53:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-29T18:16:15.000Z", "max_issues_repo_path": "E8_show_numpy_roots.py", "max_issues_repo_name": "charles-stan/learn_python_Stanier", "max_issues_repo_head_hexsha": "740a7104fcbd739663d703d3770f9e31509300f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "E8_show_numpy_roots.py", "max_forks_repo_name": "charles-stan/learn_python_Stanier", "max_forks_repo_head_hexsha": "740a7104fcbd739663d703d3770f9e31509300f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3300970874, "max_line_length": 82, "alphanum_fraction": 0.606943336, "include": true, "reason": "import numpy", "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778012346834, "lm_q2_score": 0.8933094159957173, "lm_q1q2_score": 0.8551452735666194}}
{"text": "import numpy as np\nfrom scipy.linalg import solve\n\ndef gauss_elim(A, b):\n    # don't destroy the old arrays\n    A = A.copy()\n    b = b.copy()\n    # there are n equations and variables\n    n = b.size\n    eq_num = n\n    var_num = n\n    # the equations are the rows and each column is a variable\n    # eliminate all variables i in 0..n-1 in the equations i+1..n-1\n    for var_index_to_elim in range(0, var_num):\n        # find the pivot (max abs) in the row below (and including the main diagonal\n        avl = A[var_index_to_elim:, var_index_to_elim]\n        best_index = np.argmax(np.abs(avl))\n        best_index_in_A = var_index_to_elim + best_index\n        # if no pivot != 0 was found fail\n        best_pivot_val = A[best_index_in_A, var_index_to_elim]\n        if best_pivot_val == 0.0:\n            raise ValueError(\"SINGULAR MATRIX\")\n        # swap pivot in A and b\n        best_row = A[best_index_in_A, :]\n        original_row = A[var_index_to_elim, :]\n        A[best_index_in_A, :] = best_row\n        A[var_index_to_elim, :] = original_row\n        # now is var_index_to_elim also the index of the equation to elimintate with\n        eq_index_to_elim_with = var_index_to_elim\n        # eliminate the variable `var_index_to_elim` in the equations var_index_to_elim+1..n-1\n        for eq_index_to_elim_in in range(var_index_to_elim + 1, eq_num):\n            # elimintate the variable var_index_to_elim in eq_index_to_elim_in\n            # I: equation to eliminate with = A[eq_index_to_elim_with, :]\n            eq_to_elim_with = A[eq_index_to_elim_with, :]\n            # II: equation to eliminate in = A[eq_index_to_elim_in, :]\n            eq_to_elim_in = A[eq_index_to_elim_in, :]\n            # the variable to use to elimintate with is at I[var_index_to_elim] =\n            # A[eq_index_to_elim_with, var_index_to_elim] = A[var_index_to_elim, var_index_to_elim]\n            # = coeff_to_elim_with\n            coeff_to_elim_with = eq_to_elim_with[var_index_to_elim]\n            # the variable to elimintate is at II[var_index_to_elim] = coeff_to_elim =\n            # A[eq_index_to_elim_in, var_index_to_elim]\n            coeff_to_elim = eq_to_elim_in[var_index_to_elim]\n            # alpha = coeff_to_elim/coeff_to_elim_with\n            alpha = coeff_to_elim/coeff_to_elim_with\n            # II <- II - alpha*I\n            eliminated_eq = eq_to_elim_in - alpha*eq_to_elim_with\n            # but the equation back\n            A[eq_index_to_elim_in, :] = eliminated_eq\n            # b[eq_index_to_elim_in] -= b[eq_index_to_elim_with]*alpha\n            b[eq_index_to_elim_in] -= alpha*b[eq_index_to_elim_with]\n    return A, b\n\n\ndef backsubst(A, b):\n    n = b.size\n    x = np.zeros(n)\n    for var_to_solve in range(n - 1, -1, -1):\n        other_subs = 0.0\n        for var_to_sub in range(var_to_solve + 1, n):\n            other_subs += x[var_to_sub]*A[var_to_solve, var_to_sub]\n        x[var_to_solve] = (b[var_to_solve] - other_subs)/A[var_to_solve, var_to_solve]\n    return x\n\nA = np.random.rand(3, 3)\nb = np.random.rand(3)\nprint(\"A:\")\nprint(A)\nprint(\"b:\")\nprint(b)\nA, b = gauss_elim(A, b)\nprint(\"Gaussian Elimination:\")\nprint(A)\nprint(b)\nx = backsubst(A, b)\nprint(\"solution x:\")\nprint(x)\nprint(\"solution using scipy:\")\nprint(solve(A, b))\n", "meta": {"hexsha": "da62c03f6c43bc19847c4f0865867866d8591e88", "size": 3240, "ext": "py", "lang": "Python", "max_stars_repo_path": "gauss.py", "max_stars_repo_name": "cosmo-jana/numerics-physics-stuff", "max_stars_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-16T16:35:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T16:35:35.000Z", "max_issues_repo_path": "gauss.py", "max_issues_repo_name": "cosmo-jana/numerics-physics-stuff", "max_issues_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gauss.py", "max_forks_repo_name": "cosmo-jana/numerics-physics-stuff", "max_forks_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5, "max_line_length": 99, "alphanum_fraction": 0.6524691358, "include": true, "reason": "import numpy,from scipy", "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777975782054, "lm_q2_score": 0.8933094167058151, "lm_q1q2_score": 0.855145270980014}}
{"text": "import numpy as np\n\ndef rotation_matrix2d_ccw(angle:float):\n    \"\"\"\n    Function that returns the 2d rotation matrix (counter-clockwise)\n\n    Args:\n    -----\n        angle(float)    : The angle passed in degrees\n    \n    Returns:\n    --------\n        rot_mat(np.ndarray) : The rotation matrix returned in (2,2) \n    \"\"\"\n    rot_mat = np.zeros((2,2))\n    angle2rad = np.pi/180\n\n    theta   = angle*angle2rad\n    costheta = np.cos(theta)\n    sintheta = np.sin(theta)\n    rot_mat[0,0] = costheta\n    rot_mat[0,1] = -sintheta\n    rot_mat[1,0] = sintheta\n    rot_mat[1,1] = costheta\n\n    return rot_mat\n\ndef rotation_matrix2d_cw(angle:float):\n    \"\"\"\n    Function that returns the 2d rotation matrix (clockwise)\n\n    Args:\n    -----\n        angle(float)    : The angle passed in degrees\n    \n    Returns:\n    --------\n        rot_mat(np.ndarray) : The rotation matrix returned in (2,2) \n    \"\"\"\n    rot_mat = rotation_matrix2d_ccw(angle)\n    rot_mat[1,0] = -rot_mat[1,0]\n    rot_mat[0,1] = -rot_mat[0,1]\n\n    return rot_mat\n\n", "meta": {"hexsha": "ec98fdd3bd81c1a836a881aab05fbb0de4382276", "size": 1020, "ext": "py", "lang": "Python", "max_stars_repo_path": "KMC/base/rotation.py", "max_stars_repo_name": "Yusheng-cai/KMC_python", "max_stars_repo_head_hexsha": "d139f47ad5f67e456adfe53228d2f1add3f2f6ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "KMC/base/rotation.py", "max_issues_repo_name": "Yusheng-cai/KMC_python", "max_issues_repo_head_hexsha": "d139f47ad5f67e456adfe53228d2f1add3f2f6ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KMC/base/rotation.py", "max_forks_repo_name": "Yusheng-cai/KMC_python", "max_forks_repo_head_hexsha": "d139f47ad5f67e456adfe53228d2f1add3f2f6ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1739130435, "max_line_length": 68, "alphanum_fraction": 0.5990196078, "include": true, "reason": "import numpy", "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.8933093975331751, "lm_q1q2_score": 0.8551452537152603}}
{"text": "from math import gamma  # * see also scipy.special\nfrom random import random\n\nimport numpy as np\nimport numpy.linalg as la\n\nfrom sdia_python.lab2.utils import get_random_number_generator\n\n\nclass BallWindow:\n    \"\"\"Creates a Ball window, meaning a volume around a center point with a radius\"\"\"\n\n    def __init__(self, center, radius=1.0):\n        \"\"\"Initialize the BallWindows from the center and the radius\n\n        Args:\n            center (list) : Gives the coordinates of the center\n            radius (float) : Gives the radius of the ball. Default to 1.\n        \"\"\"\n\n        self.center = np.array(center)\n        self.radius = radius\n\n    def __str__(self):\n        \"\"\"Display the BallWindow as a string\n\n        Returns:\n            string: BallWindows center and radius\n        \"\"\"\n\n        description = (\n            f\"BallWindow: center = {list(self.center)} & radius = {self.radius}\"\n        )\n        return description\n\n    def __len__(self):\n        \"\"\"Returns the dimension of the space of the BallWindow\n\n        Returns:\n            int: Size of the space containing the BallWindow\n        \"\"\"\n\n        return self.center.size\n\n    def __contains__(self, point):\n        \"\"\"Indicates whether the argument given is inside the Ball Window of not.\n        Assertion error if the dimension of the point is not equal to the dimension of the BallWindow\n\n        Args:\n            point (np.array): [list of coordinates]\n\n        Returns:\n            boolean: True if the point is inside, else returns False\n        \"\"\"\n\n        # ? readability: len(self) => self.dimension()\n        assert (\n            len(point) == self.dimension()\n        )  ##Test if the point has the same dimension\n        return la.norm(self.center - point) <= self.radius\n\n    def dimension(self):\n        \"\"\"Gives the dimension of the BallWindows, see __len__\n\n        Returns:\n            int: The dimension of the BallWindow\n        \"\"\"\n\n        return len(self)\n\n    def volume(self):\n        \"\"\"Gives the volume of the BallWindow\n\n        Returns:\n            int: The volume of the BallWindow\n        \"\"\"\n        n = self.dimension()\n        R = self.radius\n        return (np.pi ** (n / 2) * R ** (n)) / gamma(1 + n / 2)\n\n    def indicator_function(self, array_points):\n        \"\"\"Gives the result of the indicator function of the BallWindows given some points of the same dimension\n\n        Args:\n            args ([int]): 1 if the argument is inside the BallWindow, else 0\n        \"\"\"\n        # * same remarks as in BoxWindow.indicator_function\n        if array_points.ndim > 1:\n            return np.array([int(p in self) for p in array_points], dtype=int)\n        return int(array_points in self)\n\n    def rand(self, n=1, rng=None):\n        \"\"\"Generate ``n`` points uniformly at random inside the :py:class:`BallWindow`.\n\n        Args:\n            n (int, optional): Number of random points to generate. Defaults to 1.\n            rng (type, optional): Defaults to None.\n\n        Returns: Array which contains n points randomly uniformly generated\n\n        \"\"\"\n        dim = self.dimension()\n        r = self.radius\n        rng = get_random_number_generator(rng)\n\n        points_l = np.empty((n, dim))\n        for index in range(n):\n            # an array of dim normally distributed random variables\n            u = np.random.normal(0, 1, dim)\n            point_radius = r * random() ** (1.0 / dim)\n            points_l[index] = np.reshape(point_radius * u / la.norm(u), (1, 2))\n        return points_l + self.center\n", "meta": {"hexsha": "13c6682a2cece295bcbb39dd17d344080e099e6c", "size": 3517, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sdia_python/lab2/ball_window.py", "max_stars_repo_name": "AnnaMarizy/sdia-python", "max_stars_repo_head_hexsha": "e6012a5d19dd910ad4fb5ff9befe29a55f18eb5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sdia_python/lab2/ball_window.py", "max_issues_repo_name": "AnnaMarizy/sdia-python", "max_issues_repo_head_hexsha": "e6012a5d19dd910ad4fb5ff9befe29a55f18eb5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sdia_python/lab2/ball_window.py", "max_forks_repo_name": "AnnaMarizy/sdia-python", "max_forks_repo_head_hexsha": "e6012a5d19dd910ad4fb5ff9befe29a55f18eb5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1238938053, "max_line_length": 112, "alphanum_fraction": 0.5985214672, "include": true, "reason": "import numpy", "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.9124361551194692, "lm_q1q2_score": 0.8551450078437767}}
{"text": "\"\"\"\nProblem Statement:\nSay that you are a traveler on a 2D grid.\nYou begin in the top-left corner and your goal is to travel to the bottom-right corner. You may only move down or right.\nYou may only move down or right.\n\nIn how many ways can you travel to the goal on a grid with dimensions m*n?\n\"\"\"\nfrom functools import lru_cache, partial\nfrom utils.decorators import time_this\nimport numpy as np\n\n\nclass GridTraveller:\n    def __init__(self, m, n):\n        self.solutions = {\n            \"recursive\": partial(self.recursive, m, n),\n            \"dp_traverse_child\": partial(self.dp_traverse_child, m, n),\n            \"dp_reduce_grid\": partial(self.dp_reduce_grid, m, n),\n            \"dp_lru_cache\": partial(self.dp_lru_cache, m, n),\n            \"dp_tabulation\": partial(self.dp_tabulation, m, n),\n        }\n\n    @staticmethod\n    def recursive(m, n):\n        \"\"\"\n        Time complexity: O(2^(n+m))\n        Space Complexity: O(n+m)\n\n        :param m:\n        :param n:\n        :return:\n        \"\"\"\n        if m == 1 and n == 1:\n            return 1\n        if m == 0 or n == 0:\n            return 0\n        return GridTraveller.recursive(m - 1, n) + GridTraveller.recursive(m, n - 1)\n\n    @staticmethod\n    def dp_traverse_child(m, n, current=None, grid_value=None):\n        start = [0, 0]\n        goal = [m - 1, n - 1]\n        actions = ('d', 'r')\n        if current is None:\n            current = start\n            grid_value = {}\n        if tuple(current) in grid_value.keys():\n            return grid_value[tuple(current)]\n        value = 0\n        if current == goal:\n            return 1\n        for action in actions:\n            if action == \"d\":\n                child = [current[0] + 1, current[1]]\n            else:\n                child = [current[0], current[1] + 1]\n\n            if child == goal:\n                return 1\n            if child[0] >= m or child[1] >= n:\n                continue\n            else:\n                value += GridTraveller.dp_traverse_child(m, n, child, grid_value)\n\n        grid_value[tuple(current)] = value\n        return grid_value[tuple(current)]\n\n    @staticmethod\n    def dp_reduce_grid(m, n, grid_value=None):\n        \"\"\"\n        grid_traveller(m,n) == grid_traveller(n,m) (Symmetric)\n        Time Complexity: O(nm)\n        Space Complexity: O(nm)\n        \"\"\"\n        if grid_value is None:\n            grid_value = {}\n        value = grid_value.get((m, n))\n        if value:\n            return value\n        value = grid_value.get((n, m))\n        if value:\n            return value\n        if m == 1 and n == 1:\n            grid_value[(m, n)] = 1\n            return 1\n        if m == 0 or n == 0:\n            grid_value[(m, n)] = 0\n            return 0\n        grid_value[(m, n)] = GridTraveller.dp_reduce_grid(m - 1, n, grid_value) + GridTraveller.dp_reduce_grid(m, n - 1, grid_value)\n        return grid_value[(m, n)]\n\n    @staticmethod\n    @lru_cache\n    def dp_lru_cache(m, n):\n        if m == 1 and n == 1:\n            return 1\n        if m == 0 or n == 0:\n            return 0\n        return GridTraveller.dp_lru_cache(min(m - 1, n), max(m - 1, n)) + \\\n               GridTraveller.dp_lru_cache(min(m, n - 1), max(m, n - 1))\n\n    @staticmethod\n    def dp_tabulation(m, n, grid_value=None):\n        \"\"\"\n        grid_traveller(m,n) == grid_traveller(n,m) (Symmetric)\n        Time Complexity: O(nm)\n        Space Complexity: O(nm)\n        \"\"\"\n        grid_value_table = np.zeros((m + 1, n + 1), int)\n        grid_value_table[1][1] = 1\n\n        for i in range(m + 1):\n            for j in range(n + 1):\n                if i + 1 <= m:\n                    grid_value_table[i + 1][j] += grid_value_table[i][j]\n                if j + 1 <= n:\n                    grid_value_table[i][j + 1] += grid_value_table[i][j]\n        # print(grid_value_table)\n        return grid_value_table[m][n]\n\n    @staticmethod\n    @time_this()\n    def run(func):\n        print(f\"Solution: {func()}\")\n\n    def execute_all(self):\n\n        print(\"\\nSolutions to Grid Traveller\\n\")\n\n        for name, solution in self.solutions.items():\n            print(f'Algo-Name: {name} {\" -\" * 90}')\n            self.run(solution)\n            print('-' * 100)\n\n\nGridTraveller(10, 10).execute_all()\n", "meta": {"hexsha": "1ff5e090017ee390db07c30f2f2604964a6e8d86", "size": 4211, "ext": "py", "lang": "Python", "max_stars_repo_path": "problems/grid_traveller.py", "max_stars_repo_name": "shreyansh96/dynamic-programming", "max_stars_repo_head_hexsha": "1d0d50ce992d2b56054e860d460a02e9442c64ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-05T21:57:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-07T09:49:49.000Z", "max_issues_repo_path": "problems/grid_traveller.py", "max_issues_repo_name": "shreyansh96/dynamic-programming", "max_issues_repo_head_hexsha": "1d0d50ce992d2b56054e860d460a02e9442c64ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-17T16:51:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-17T16:51:54.000Z", "max_forks_repo_path": "problems/grid_traveller.py", "max_forks_repo_name": "shreyansh96/dynamic-programming", "max_forks_repo_head_hexsha": "1d0d50ce992d2b56054e860d460a02e9442c64ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-29T04:30:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-29T04:30:06.000Z", "avg_line_length": 30.5144927536, "max_line_length": 132, "alphanum_fraction": 0.527190691, "include": true, "reason": "import numpy", "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.9161096198879968, "lm_q1q2_score": 0.855124948876971}}
{"text": "'''\n2D Arithmetic\n100xp\nRemember how you calculated the Body Mass Index for all baseball players?\nnumpy was able to perform all calculations element-wise (i.e. element by element).\nFor 2D numpy arrays this isn't any different! You can combine matrices with single\nnumbers, with vectors, and with other matrices.\n\nExecute the code below in the IPython shell and see if you understand:\n\nimport numpy as np\nnp_mat = np.array([[1, 2],\n                   [3, 4],\n                   [5, 6]])\nnp_mat * 2\nnp_mat + np.array([10, 10])\nnp_mat + np_mat\nnp_baseball is coded for you; it's again a 2D numpy array with 3 columns representing\nheight, weight and age.\n\nInstructions\n-You managed to get hold of the changes in weight, height and age of all baseball players.\nIt is available as a 2D numpy array, updated. Add np_baseball and updated and print out the result.\n-You want to convert the units of height and weight. As a first step, create a numpy array\nwith three values: 0.0254, 0.453592 and 1. Name this array conversion.\n-Multiply np_baseball with conversion and print out the result.\n'''\n# baseball is available as a regular list of lists\n# updated is available as 2D numpy array\n\n# Import numpy package\nimport numpy as np\n\n# Create np_baseball (3 cols)\nnp_baseball = np.array(baseball)\n\n# Print out addition of np_baseball and updated\nprint(np_baseball + updated)\n\n# Create numpy array: conversion\nconversion = np.array([0.0254, 0.453592, 1.0])\n\n# Print out product of np_baseball and conversion\nprint(np_baseball * conversion)\n", "meta": {"hexsha": "84dc967b112f997831af3ceb06b10d90d4dca5c8", "size": 1527, "ext": "py", "lang": "Python", "max_stars_repo_path": "Intro to Python for Data Science/NumPy/2d-arithmetic.py", "max_stars_repo_name": "nazmusshakib121/Python-Programming", "max_stars_repo_head_hexsha": "3ea852641cd5fe811228f27a780109a44174e8e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-12T04:49:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T00:40:28.000Z", "max_issues_repo_path": "Intro to Python for Data Science/NumPy/2d-arithmetic.py", "max_issues_repo_name": "nazmusshakib121/Python-Programming", "max_issues_repo_head_hexsha": "3ea852641cd5fe811228f27a780109a44174e8e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Intro to Python for Data Science/NumPy/2d-arithmetic.py", "max_forks_repo_name": "nazmusshakib121/Python-Programming", "max_forks_repo_head_hexsha": "3ea852641cd5fe811228f27a780109a44174e8e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-11-06T17:43:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T21:08:16.000Z", "avg_line_length": 33.9333333333, "max_line_length": 99, "alphanum_fraction": 0.7465618861, "include": true, "reason": "import numpy", "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.9161096216057903, "lm_q1q2_score": 0.8551249403014336}}
{"text": "#Determining the Principal Axis of Inertia & the Principal Moments of Inertia from the Inertia Tensor\r\n\r\nimport numpy as np\r\nnp.set_printoptions(precision=4, suppress=True) #It is set to display & secure the output with 4 decimals\r\n\r\nI = np.array([[30,5,5],\r\n             [5,20,5],\r\n             [5,5,10]])\r\nprint(\"Inertia Tensor = \\n\",I)\r\n\r\nI_p, P = np.linalg.eig(I) #This function is used to calculate EigenValues & EigenVectors (I_p = EigenValues, P = EigenVectors)\r\n\r\nprint(\"Principal Moments of Inertia using EigenValues = \\n\",I_p)\r\nprint(\"Principal Axis of Inertia = \\n\",P.T)\r\n\r\n#Determining Principal Moment of Inertia vai Diagonalization\r\n\r\nI_pp = np.linalg.inv(P)@I@P # @ Operator represents the product of the matrix. (In NumPy * operator attention to become a product of the elements to each other.)\r\nI_pp = np.diag(I_pp) #Using the diag function and retrieve only the diagonal components.\r\nprint(\"Principal Moments of Inertia using Diagonalization = \\n\",I_pp)\r\n\r\n", "meta": {"hexsha": "edc404a6eea5a90f71b6b8f5270c9871524acc73", "size": 975, "ext": "py", "lang": "Python", "max_stars_repo_path": "Principal_Axis_and_Moment_of_Inertia.py", "max_stars_repo_name": "Official-Satyam-Tiwari/AdvancedMathematicalPhysics1", "max_stars_repo_head_hexsha": "846094c492540c5dc5cbb3e20991a550cb62d8ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Principal_Axis_and_Moment_of_Inertia.py", "max_issues_repo_name": "Official-Satyam-Tiwari/AdvancedMathematicalPhysics1", "max_issues_repo_head_hexsha": "846094c492540c5dc5cbb3e20991a550cb62d8ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Principal_Axis_and_Moment_of_Inertia.py", "max_forks_repo_name": "Official-Satyam-Tiwari/AdvancedMathematicalPhysics1", "max_forks_repo_head_hexsha": "846094c492540c5dc5cbb3e20991a550cb62d8ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3181818182, "max_line_length": 162, "alphanum_fraction": 0.7148717949, "include": true, "reason": "import numpy", "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.8976952893703477, "lm_q1q2_score": 0.8551213040073115}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nwhile True:\n    try:\n        print('-'*111) # for decoration purpose\n        x = input('<< TO CONTINUE PRESS \"ENTER\" OR TO KILL THE APPLICATION PRESS \"0\" >>     ')\n        if x == '':\n            print()\n            print('<< THIS APPLICATION CALCULATES ROOTS FOR A GIVEN QUADRATIC EQUATION >>')\n            print()\n            print('>>> THE EQUATION WILL BE IN FORM OF << a.X^2 + b.X + c >>')\n            print()\n            a = int(input('enter value of a: '))\n            b = int(input('enter value of b: '))\n            c = int(input('enter value of c: '))\n            d = ((b**2)-4*a*c)**(1/2)\n            discriminant = ((b**2)-4*a*c)\n\n            roots_1= ((-b)+d)/(2*a)\n            roots_2 = ((-b)-d)/(2*a)\n            root_declare = f'>>> The roots are  X = {roots_1}  and  X = {roots_2}.'\n            print()\n            print(f'>>> THE EQUATION IS ( {a}.X^2 + {b}.X + {c} ).')\n            print()\n            print(root_declare)\n            print()\n            print(f'>>> The value of discriminant is {discriminant}.')\n            print()\n\n            def root_indicator():                     # tell's root charateristic\n                if discriminant > 0:\n                    return('The roots of given equation are real.')\n                elif discriminant < 0:\n                    return('The roots of given equation are imaginary.')\n                elif discriminant == 0:\n                    return('There is one real root.')\n            print(f'>>> {root_indicator()}')\n            print()\n\n            print('')\n            plot_enable = input('<<< To show the plot press \" y \" OR To cancel plotting press ENTER >>>     ')\n            if plot_enable == 'y':\n                def plot_show():\n                    # 100 linearly spaced numbers\n                    x = np.linspace(-10**2,10**2,10**2)\n                    y = np.linspace(-10**2,10**2,10**2)\n\n                    # the function, which is y = x^2 here\n                    y = (a*(x**2))+(b*x)+c\n\n                    # setting the axes at the centre\n                    fig = plt.figure()\n                    ax = fig.add_subplot(1, 1, 1)\n                    ax.spines['left'].set_position('center')\n                    ax.spines['bottom'].set_position('zero')\n                    ax.spines['right'].set_color('none')\n                    ax.spines['top'].set_color('none')\n                    ax.xaxis.set_ticks_position('bottom')\n                    ax.yaxis.set_ticks_position('left')\n\n                    # plot the function\n                    plt.plot(x,y, 'r')\n\n                    # show the plot\n                    plt.show()\n                plot_show()\n            elif plot_enable == '':\n                print()\n                print('>>> Graphing Cancelled')\n        elif int(x) == 0:\n            break\n    except:\n        if a == 0:\n            print(f'>> a value must be larger than \"zero\" and enter numerals only.  <<')\n        else:\n            print()\n            print(f'>> Please check the entered value, enter numerals only. <<')", "meta": {"hexsha": "7cc5647c93f1a36fa753d575465a75c06f2e1188", "size": 3081, "ext": "py", "lang": "Python", "max_stars_repo_path": "quadratic_roots_calculator.py", "max_stars_repo_name": "vineeth-th/MyRep", "max_stars_repo_head_hexsha": "2e15748053e1ac28593580ce8fb73a1ff1ee4661", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quadratic_roots_calculator.py", "max_issues_repo_name": "vineeth-th/MyRep", "max_issues_repo_head_hexsha": "2e15748053e1ac28593580ce8fb73a1ff1ee4661", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quadratic_roots_calculator.py", "max_forks_repo_name": "vineeth-th/MyRep", "max_forks_repo_head_hexsha": "2e15748053e1ac28593580ce8fb73a1ff1ee4661", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.012987013, "max_line_length": 110, "alphanum_fraction": 0.4443362545, "include": true, "reason": "import numpy", "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.8976952866333484, "lm_q1q2_score": 0.8551213014001168}}
{"text": "import sys\nimport numpy as np\nimport time\nimport logging\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\n\nkmax = int(sys.argv[1])\nr = int(sys.argv[2])\namin = sys.argv[3]\namax = sys.argv[4]\n\ndef plotResults(k, tNaive, tList, tStrassen):\n    x = list(range(1, k+1))\n    a = sns.lineplot(x, tNaive, label=\"Naive\")\n    a = sns.lineplot(x, tList, label=\"List Comprehesion\")\n    a = sns.lineplot(x, tStrassen, label=\"Strassen\")\n    a.set(xlabel='Tamanho da entrada 2^x', ylabel='Tempo de execução médio (s)')\n    a.legend()\n    plt.show()\n\ndef MultiplyMatrix(A, B):\n    \"\"\"Multiply two matrices using naive algorithm\"\"\"\n    C = np.zeros((len(A), len(B)), dtype=int)\n    \n    for i in range(len(A)):\n        for j in range(len(B)):\n            for k in range(len(B)):\n                C[i][j] += A[i][k] * B[k][j]\n    return C\n\ndef addMatrix(A,B):\n    \"\"\"Add two matrices\"\"\"\n    return [[A[i][j] + B[i][j] for j in range(len(A))] for i in range(len(B))]\n\ndef subMatrix(A,B):\n    \"\"\"subtraction two matrices\"\"\"\n    return [[A[i][j] - B[i][j] for j in range(len(A))] for i in range(len(B))]\n\ndef Strassen(A, B):\n    \"\"\"Strassen Algorithm to squared matrices\"\"\"\n    if len(A) <= 2:\n        return  matrixMultiplicationListComprehesion(A, B)\n    else:\n        n = int(len(A)/2)\n\n        a11 = [[A[i][j] for j in range(len(A)) if j < n  ] for i in range(len(A)) if i < n]\n        a12 = [[A[i][j] for j in range(len(A)) if j >= n ] for i in range(len(A)) if i < n]\n        a21 = [[A[i][j] for j in range(len(A)) if j < n  ] for i in range(len(A)) if i >= n]\n        a22 = [[A[i][j] for j in range(len(A)) if j >= n ] for i in range(len(A)) if i >= n]\n\n        b11 = [[B[i][j] for j in range(len(B)) if j < n  ] for i in range(len(B)) if i < n]\n        b12 = [[B[i][j] for j in range(len(B)) if j >= n ] for i in range(len(B)) if i < n]\n        b21 = [[B[i][j] for j in range(len(B)) if j < n  ] for i in range(len(B)) if i >= n]\n        b22 = [[B[i][j] for j in range(len(B)) if j >= n ] for i in range(len(B)) if i >= n]\n\n        m1 = Strassen(addMatrix(a11,a22), addMatrix(b11,b22))\n        m2 = Strassen(addMatrix(a21,a22), b11)\n        m3 = Strassen(a11, subMatrix(b12, b22))\n        m4 = Strassen(a22, subMatrix(b21, b11))\n        m5 = Strassen(addMatrix(a11, a12), b22)\n        m6 = Strassen(subMatrix(a21, a11), addMatrix(b11, b12))\n        m7 = Strassen(subMatrix(a12, a22), addMatrix(b21, b22))\n\n        c11 = addMatrix(addMatrix(m1, m4), subMatrix(m7, m5))\n        c12 = addMatrix(m3, m5)\n        c21 = addMatrix(m2, m4)\n        c22 = addMatrix(subMatrix(m1, m2), addMatrix(m3, m6))\n        \n        C = np.concatenate((np.concatenate((c11, c12), axis=1), np.concatenate((c21, c22), axis=1)), axis = 0 )\n\n        return C\n\n\ndef matrixMultiplicationListComprehesion(A, B):\n    \"\"\"Multiply two squared matrices using list comprehesion\"\"\"\n    return [[sum([x*y for (x, y) in zip(row, col)]) for col in zip(*B)] for row in A]\n\nif __name__ == \"__main__\":\n    \n    tNaive = [0] * kmax \n    tList = [0] * kmax\n    tStrassen = [0] * kmax\n\n    format = \"%(asctime)s: %(message)s\"\n    logging.basicConfig(format=format, level=logging.INFO, datefmt=\"%Y-%m-%d %H:%M:%S\")\n\n    for n in range(1, kmax+1):\n        for _ in range(r):\n            A = np.random.randint(low = amin, high = amax, size = (2**n,2**n))\n            B = np.random.randint(low = amin, high = amax, size = (2**n,2**n))\n\n            start_time = time.time()\n            C = MultiplyMatrix(A,B)\n            end_time = time.time()\n            tNaive[n-1] += (end_time - start_time)\n\n            start_time = time.time()\n            D = matrixMultiplicationListComprehesion(A,B)\n            end_time = time.time()\n            tList[n-1] += (end_time - start_time)\n\n            start_time = time.time()\n            E = Strassen(A,B)\n            end_time = time.time()\n            tStrassen[n-1] += (end_time - start_time)\n\n        logging.debug(\"2^%d: {Naive: %f}, {List: %f}, {Strassen: %f}\", n, tNaive[n-1], tList[n-1], tStrassen[n-1])\n        logging.info(\"2^%d: Average {Naive: %f}, {List: %f}, {Strassen: %f}\", n, tNaive[n-1]/r, tList[n-1]/r, tStrassen[n-1]/r)\n \n    plotResults(kmax, [x/r for x in tNaive], [x/r for x in tList], [x/r for x in tStrassen])", "meta": {"hexsha": "b68477853dfb7fa0cdc9fb9f03ccd4c705ab00de", "size": 4219, "ext": "py", "lang": "Python", "max_stars_repo_path": "matriz.py", "max_stars_repo_name": "RaulBritto/Analysis-of-Algorithms", "max_stars_repo_head_hexsha": "866fdbe63369cd0253cfacaac65980be5eda1ff5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matriz.py", "max_issues_repo_name": "RaulBritto/Analysis-of-Algorithms", "max_issues_repo_head_hexsha": "866fdbe63369cd0253cfacaac65980be5eda1ff5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matriz.py", "max_forks_repo_name": "RaulBritto/Analysis-of-Algorithms", "max_forks_repo_head_hexsha": "866fdbe63369cd0253cfacaac65980be5eda1ff5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.009009009, "max_line_length": 127, "alphanum_fraction": 0.5570040294, "include": true, "reason": "import numpy", "num_tokens": 1373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760638, "lm_q2_score": 0.8976952845805988, "lm_q1q2_score": 0.8551213006533501}}
{"text": "import numpy as np\n\ndef NW_corner_rule(a, b):\n    \"\"\"\n    North-West Corner rule for discrete optimal transport:\n        Finding the vertex of the polytope of the feasible set U(a, b),\n        where the minimum is attained.\n\n    Reference: P44, Sec 3.4.2\n\n    @input a, b: np.ndarray, of shape (n, ) and (m, ), the source histogram and the target histogram\n    @return P: np.ndarray, of shape (n, m), one of the vertex of the polytope, P[i, j]: the flow from a[i] to b[j]\n\n    >>> a = np.array([0.2, 0.5, 0.3])\n    >>> b = np.array([0.5, 0.1, 0.4])\n    >>> NW_corner_rule(a, b)\n    array([[0.2, 0. , 0. ],\n           [0.3, 0.1, 0.1],\n           [0. , 0. , 0.3]])\n    \"\"\"\n    P = np.zeros((a.shape[0], b.shape[0]))\n    i = j = 0\n    r = a[0]\n    c = b[0]\n    while i < a.shape[0] and j < b.shape[0]:\n        P[i, j] = min(r, c)\n        r -= P[i, j]\n        c -= P[i, j]\n        if r == 0:\n            i += 1\n            if i < a.shape[0]:\n                r = a[i]\n        if c == 0:\n            j += 1\n            if j < b.shape[0]:\n                c = b[j]\n    return P\n\ndef compute_NW_solutions(a, b, sigma1, sigma2):\n    \"\"\"\n    compute an arbitrary NW solution by permutation\n\n    Reference: Page 45, Section 3.4.2\n\n    @param a, b: the source histogram and the target histogram\n    @param sigma1, sigma2: the permutation vector for a and b respectively\n    @return P_permutation: the permutated NW solution by\n        P_permutation = sigma1_inv(sigma2_inv(P, column), row)\n        where P is the transport matrix of sigma1(a) and sigma2(b)\n\n    >>> a = np.array([0.2, 0.5, 0.3])\n    >>> b = np.array([0.5, 0.1, 0.4])\n    >>> sigma1 = np.array([2, 0, 1])\n    >>> sigma2 = np.array([2, 1, 0])\n    >>> compute_NW_solutions(a, b, sigma1, sigma2)\n    array([[0., 0.1, 0.1],\n        [0.5, 0., 0.],\n        [0., 0., 0.3]])\n    \"\"\"\n    a = a[sigma1]\n    b = b[sigma2]\n    P = NW_corner_rule(a, b)\n    print(P)\n    sigma1_inv = np.argsort(sigma1)\n    sigma2_inv = np.argsort(sigma2)\n    P = P[:, sigma2_inv]\n    P = P[sigma1_inv, :]\n    return P\n\n\nif __name__ == \"__main__\":\n    import doctest\n    doctest.testmod()\n", "meta": {"hexsha": "2886a32b978cc2412917c789f1c93779eb6ef710", "size": 2111, "ext": "py", "lang": "Python", "max_stars_repo_path": "north_west_corner_rule.py", "max_stars_repo_name": "Orcuslc/Computational-Optimal-Transport", "max_stars_repo_head_hexsha": "aecc2976a22238c313d65e5d1fed34fcab3880f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "north_west_corner_rule.py", "max_issues_repo_name": "Orcuslc/Computational-Optimal-Transport", "max_issues_repo_head_hexsha": "aecc2976a22238c313d65e5d1fed34fcab3880f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "north_west_corner_rule.py", "max_forks_repo_name": "Orcuslc/Computational-Optimal-Transport", "max_forks_repo_head_hexsha": "aecc2976a22238c313d65e5d1fed34fcab3880f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-04T02:17:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T02:17:14.000Z", "avg_line_length": 28.527027027, "max_line_length": 114, "alphanum_fraction": 0.5229748934, "include": true, "reason": "import numpy", "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.8976952825278492, "lm_q1q2_score": 0.8551212999065835}}
{"text": "\"\"\"\nExercise 3\nFind the area enclosed by two curves between two points.\n\"\"\"\n\nfrom sympy import Integral, Symbol, SympifyError, sympify\n\n\ndef find_area(f1x, f2x, var, a, b):\n    return Integral(f1x - f2x, (var, a, b)).doit()\n\n\ndef validate_function(function):\n\n    try:\n        return sympify(function)\n    except SympifyError:\n        print(\"Invalid function entered\")\n        sys.exit(1)\n\n    return None\n\n\nif __name__ == \"__main__\":\n    f1 = input(\"Enter the upper function in one variable: \")\n    f1 = validate_function(f1)\n\n    f2 = input(\"Enter the lower upper function in one variable: \")\n    f2 = validate_function(f2)\n\n    variable = input(\"Enter the variable: \")\n    variable = Symbol(variable)\n\n    lower_bound = float(input(\"Enter the lower bound of the enclosed region: \"))\n    upper_bound = float(input(\"Enter the upper bound of the enclosed region: \"))\n\n    print(\n        \"Area enclosed by {} and {} is {} \".format(\n            f1, f2, find_area(f1, f2, variable, lower_bound, upper_bound)\n        )\n    )\n", "meta": {"hexsha": "6bf1b14fd523049bddce3ac6d6ece3c522429e39", "size": 1021, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Chapter7/Exercise3.py", "max_stars_repo_name": "djeada/Doing-Math-with-Python", "max_stars_repo_head_hexsha": "6b5fb4018224032f805314d367f810c127246ccf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Chapter7/Exercise3.py", "max_issues_repo_name": "djeada/Doing-Math-with-Python", "max_issues_repo_head_hexsha": "6b5fb4018224032f805314d367f810c127246ccf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Chapter7/Exercise3.py", "max_forks_repo_name": "djeada/Doing-Math-with-Python", "max_forks_repo_head_hexsha": "6b5fb4018224032f805314d367f810c127246ccf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3095238095, "max_line_length": 80, "alphanum_fraction": 0.6474045054, "include": true, "reason": "from sympy", "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298657, "lm_q2_score": 0.8887587957022977, "lm_q1q2_score": 0.8550815711416154}}
{"text": "import numpy as np\n\n\ndef calc_weights(x, y):\n    \"\"\"\n    Calculating weights in least square\n\n    Parameters\n    ----------\n    x: numpy.ndarray or shape (n_samples, n_features)\n        the data to be finding the weights for features.\n\n    y: numpy.ndarray or shape (n_samples, )\n        the target data of x.\n\n    Returns\n    -------\n    output: numpy.ndarray or shape (n_features, )\n        the weights of x\n    \"\"\"\n\n    x = np.array(x)\n    y = np.array(y)\n\n    mean_x = x.mean(axis=0)\n    mean_y = y.mean(axis=0)\n\n    distance_x = x - mean_x\n    distance_y = y - mean_y\n\n    distance_xy = distance_x * distance_y.reshape((distance_y.shape[0], 1))\n\n    x_square = (x - mean_x) ** 2\n\n    numerator = np.sum(distance_xy, axis=0)\n    denumerator = np.sum(x_square, axis=0)\n\n    output = numerator / denumerator\n\n    return output\n\n\ndef calc_intercept(X, y, slope):\n    \"\"\"\n    Calculating intercept in least square\n\n    Parameters\n    ----------\n    x: numpy.ndarray or shape (n_samples, n_features)\n        the data to be finding the weights for features.\n\n    y: numpy.ndarray or shape (n_samples, )\n        the target data of x.\n\n    slope: numpy.ndarray or shape (n_features, )\n        the weighted of x\n\n\n    Returns\n    -------\n    output: int\n        the result of calculating intercept in least square\n\n    \"\"\"\n\n    X = np.array(X)\n    y = np.array(y)\n\n    mean_y = y.mean(axis=0)\n    mean_x = X.mean(axis=0)\n\n    weighted_mean_x = slope * mean_x\n\n    summing_weighted_mean_x = np.sum(weighted_mean_x)\n\n    output = mean_y - summing_weighted_mean_x\n\n    return output\n\n\ndef calc_with_svd(a, b):\n    \"\"\"\n    Finding x with svd in equation ax = b.\n    where a and b are known.\n\n    Parameters\n    ----------\n    a: numpy.ndarray or shape (n, f)\n        The independent variables to be calculate with svd\n\n    b: numpy.ndarray or shape (n, )\n        The dependent variable of a\n\n    Returns\n    -------\n    x: numpy.ndarray or shape (f, )\n        Solved to find x of ax = b equation\n\n    \"\"\"\n    # change to numpy.array\n    a = np.array(a)\n    b = np.array(b)\n\n    # raises the error\n    if a.shape[0] != b.shape[0]:\n        raise ValueError(\"the rows of a and b supposed to be same\")\n    elif len(b.shape) != 1:\n        raise ValueError(\"for now the shape of b supposed to be (n, \")\n\n    # solving least square with svd\n    x, residuals, rank, s = np.linalg.lstsq(a, b, rcond=None)\n\n    return x\n", "meta": {"hexsha": "a69ab21308ac1aa0a65a2a78d89a6b99a72012e5", "size": 2401, "ext": "py", "lang": "Python", "max_stars_repo_path": "krmining/utils/least_square.py", "max_stars_repo_name": "SynitCool/keyar-mining", "max_stars_repo_head_hexsha": "c41c6696eec5efb10755b874169c87f43117eb38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-04T21:02:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T01:23:39.000Z", "max_issues_repo_path": "krmining/utils/least_square.py", "max_issues_repo_name": "SynitCool/keyar-mining", "max_issues_repo_head_hexsha": "c41c6696eec5efb10755b874169c87f43117eb38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "krmining/utils/least_square.py", "max_forks_repo_name": "SynitCool/keyar-mining", "max_forks_repo_head_hexsha": "c41c6696eec5efb10755b874169c87f43117eb38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0614035088, "max_line_length": 75, "alphanum_fraction": 0.6018325698, "include": true, "reason": "import numpy", "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075733703927, "lm_q2_score": 0.8887587934924569, "lm_q1q2_score": 0.8550815661186256}}
{"text": "import numpy as np\nfrom numpy import ndarray\n\n\ndef linear_score_function(n: int) -> ndarray:\n    \"\"\"\n    With the linear score function the \"points\" awarded scale linearly from first place\n    through last place. For example, improving from 2nd to 1st place has the same sized\n    benefit as improving from 5th to 4th place.\n\n    :param n: number of players\n    :return: array of the points to assign to each place (summing to 1)\n    \"\"\"\n    return np.array([(n - p) / (n * (n - 1) / 2) for p in range(1, n + 1)])\n\n\ndef create_exponential_score_function(base: float):\n    \"\"\"\n    With an exponential score function with base > 1, more points are awarded to the top\n    finishers and the point distribution is flatter at the bottom. For example, improving\n    from 2nd to 1st place is more valuable than improving from 5th place to 4th place. A\n    larger base value means the scores will be more weighted towards the top finishers.\n\n    :param base: base for teh exponential score function (> 1)\n    :return: a function that takes parameter n for number of players and returns an array\n    of the points to assign to each place (summing to 1)\n    \"\"\"\n    return lambda n: _exponential_score_template(n, base)\n\n\ndef _exponential_score_template(n: int, base: float) -> ndarray:\n    if base < 1:\n        raise ValueError(\"base must be >= 1\")\n    if base == 1:\n        return linear_score_function(n)  # it converges to this as base -> 1\n\n    out = np.array([base ** (n - p) - 1 for p in range(1, n + 1)])\n    return out / sum(out)", "meta": {"hexsha": "b64b67a42efd624e9bb62d2f69364783b6a7d869", "size": 1527, "ext": "py", "lang": "Python", "max_stars_repo_path": "multiBatelo/score_functions.py", "max_stars_repo_name": "Balavignesh/badminton-elo-dashboard", "max_stars_repo_head_hexsha": "df380afb26c89827111f7316df381408d7d19298", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multiBatelo/score_functions.py", "max_issues_repo_name": "Balavignesh/badminton-elo-dashboard", "max_issues_repo_head_hexsha": "df380afb26c89827111f7316df381408d7d19298", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multiBatelo/score_functions.py", "max_forks_repo_name": "Balavignesh/badminton-elo-dashboard", "max_forks_repo_head_hexsha": "df380afb26c89827111f7316df381408d7d19298", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1842105263, "max_line_length": 89, "alphanum_fraction": 0.6895874263, "include": true, "reason": "import numpy,from numpy", "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.8887587905460026, "lm_q1q2_score": 0.8550815603869341}}
{"text": "import numpy as np\nimport matplotlib .pyplot as plt\n\nN = 50\n\nX = np.linspace(0, 10, N)\nY = 0.5 * X + np.random.randn(N)\n# outlier\nY[-1] += 30\nY[-2] += 30\n\nplt.scatter(X, Y)\nplt.show()\n\nX = np.vstack([np.ones(N), X]).T\n\nw_ml = np.linalg.solve(X.T.dot(X), X.T.dot(Y))\ny_hat_ml = X.dot(w_ml)\nplt.scatter(X[:, 1], Y)\nplt.plot(X[:, 1], y_hat_ml)\nplt.show()\n\nl2 = 1000\nw_map = np.linalg.solve(l2 * np.eye(2) + X.T.dot(X), X.T.dot(Y))\ny_hat_map = X.dot(w_map)\nplt.scatter(X[:, 1], Y)\nplt.plot(X[:, 1], y_hat_ml, label='maxmimum likelihood')\nplt.plot(X[:, 1], y_hat_map, label='map')\nplt.legend()\nplt.show()\n", "meta": {"hexsha": "5524258730c2b435ae891266fb8e03d6c15d66a7", "size": 600, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_regression/l2_regularization.py", "max_stars_repo_name": "opplieam/Udemy-Lazy", "max_stars_repo_head_hexsha": "89e757152a87603d630593e13b0db4d5422222fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_regression/l2_regularization.py", "max_issues_repo_name": "opplieam/Udemy-Lazy", "max_issues_repo_head_hexsha": "89e757152a87603d630593e13b0db4d5422222fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_regression/l2_regularization.py", "max_forks_repo_name": "opplieam/Udemy-Lazy", "max_forks_repo_head_hexsha": "89e757152a87603d630593e13b0db4d5422222fc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3548387097, "max_line_length": 64, "alphanum_fraction": 0.615, "include": true, "reason": "import numpy", "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347816221828, "lm_q2_score": 0.8774767906859264, "lm_q1q2_score": 0.8550439049105745}}
{"text": "\"\"\"\nreference : https://en.wikipedia.org/wiki/PageRank\n\"\"\"\nimport numpy as np\n\ndef pr(adjacency_arr, N_iter = 20, d = 0.85):\n    M = np.zeros(adjacency_arr.shape)\n    for m in range(M.shape[0]):\n        M[:, m] = adjacency_arr[:, m] / adjacency_arr[:, m].sum()\n\n    e = np.ones(adjacency_arr.shape[0])*1.0 / adjacency_arr.shape[0]\n    v0 = e.copy()\n    for i in range(N_iter):\n        vn = np.dot(M, v0)*d + e*(1-d)\n        v0 = vn\n    return vn\n\n\nif __name__ == \"__main__\":\n\tadjacency_arr = np.array([[0, 0, 0, 0, 1],\n\t              [0.5, 0, 0, 0, 0],\n\t              [0.5, 0, 0, 0, 0],\n\t              [0, 1, 0.5, 0, 0],\n\t              [0, 0, 0.5, 1, 0]])\n\tprint(\"ground truth\\n\", [[0.25419178],\n\t       [0.13803151],\n\t       [0.13803151],\n\t       [0.20599017],\n\t       [0.26375504]])\n\tvn = pr(adjacency_arr, N_iter = 100, d = 0.85)\n\tprint(\"result\\n\", vn)", "meta": {"hexsha": "c91c1ebf0c3b4f598da6e81b1668662741ac35ce", "size": 855, "ext": "py", "lang": "Python", "max_stars_repo_path": "pagerank.py", "max_stars_repo_name": "chiechie/BasicAlgo", "max_stars_repo_head_hexsha": "1bbd686673c650a5c71ed0781d8081124841e282", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pagerank.py", "max_issues_repo_name": "chiechie/BasicAlgo", "max_issues_repo_head_hexsha": "1bbd686673c650a5c71ed0781d8081124841e282", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pagerank.py", "max_forks_repo_name": "chiechie/BasicAlgo", "max_forks_repo_head_hexsha": "1bbd686673c650a5c71ed0781d8081124841e282", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5806451613, "max_line_length": 68, "alphanum_fraction": 0.5052631579, "include": true, "reason": "import numpy", "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.976310526632796, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.855040062199177}}
{"text": "import numpy as np\nfrom scipy import integrate\n\nconturs_areas = np.array([194135, 136366, 79745, 38335, 18450, 9635, 3895])\nx = np.array([0,25,50,75,100,125,150])\n\nvol_traps = integrate.trapz(conturs_areas, x)\nvol_simps = integrate.simps(conturs_areas, x)\n\nprint('The trapezoidal rule returns a volume of {:.0f} cubic meters'.format(vol_traps))\nprint('The composite Simpson rule returns a volume of {:.0f} cubic meters'.format(vol_simps))\n\n'''\nOutput:\nThe trapezoidal rule returns a volume of 9538650 cubic meters\nThe composite Simpson rule returns a volume of 9431367 cubic meters   \n'''", "meta": {"hexsha": "84c16d03fbfd696481052b691dd5dc3e7094e8ec", "size": 588, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/chapter_07/listing_07_04.py", "max_stars_repo_name": "guinslym/python_earth_science_book", "max_stars_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80, "max_stars_repo_stars_event_min_datetime": "2021-04-19T10:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:34:47.000Z", "max_issues_repo_path": "code/chapter_07/listing_07_04.py", "max_issues_repo_name": "guinslym/python_earth_science_book", "max_issues_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/chapter_07/listing_07_04.py", "max_forks_repo_name": "guinslym/python_earth_science_book", "max_forks_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2021-04-25T03:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:06:19.000Z", "avg_line_length": 34.5882352941, "max_line_length": 93, "alphanum_fraction": 0.7585034014, "include": true, "reason": "import numpy,from scipy", "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9840936106207203, "lm_q2_score": 0.868826789824086, "lm_q1q2_score": 0.8550068926019945}}
{"text": "from math import *\nimport operator as op\nimport numpy as np\n\ndim  = 512\nk = 8\nq = 12289\nbound_CC = 34000    # Bound n*mu+beta to use in Cramer-Chernoff Ineq.\nn = 2 * dim / 2      # Number of samples in Cramer-Chernoff Ineq.\n\n\ncheck_each_y = True \n# Check each distribution phi_y (slower)\n#experimentally, they are always equal probably due to symmetries\n\n\nsubg_param = sqrt(k/2)\ntau = 17.6\n\n\nsubg_value = sqrt(bound_CC) * subg_param * tau\np_subg = exp(-tau**2/2 )\n\nprint \"#### \"\nprint \"#### Correctness check :\"\nprint \"#### \"\n\nprint \"target bound (before +e'')=\", subg_value\nprint \"target bound =\", subg_value + 2*k\nprint \"(sqrt(2)/2.) * 3q/4 =\", (sqrt(2)/2.) * 3*q/4.\nprint  \"Correct ?\", subg_value + 2*k < (sqrt(2)/2.) * 3*q/4.\nassert subg_value + 2*k < (sqrt(2)/2.) * 3*q/4.\n\n\nprint\nprint \"#### \"\nprint \"#### Lemma 6 Verification :\"\nprint \"#### \"\n\n\ndef rot(v):\n\treturn [-v[1],v[0]]\n\nif check_each_y:\n\ty_list = [\n\t\t[ 1, 1],\n\t\t[ 1,-1],\n\t\t[-1, 1],\n\t\t[-1,-1]\n\t]\nelse:\n\ty_list = [[ 1, 1]]\n\n### Construct the binomial law\nsupp = xrange(-k,k+1)\n\ndef binomial(n, r):\n    r = min(r, n-r)\n    if r == 0: return 1\n    numer = reduce(op.mul, xrange(n, n-r, -1))\n    denom = reduce(op.mul, xrange(1, r+1))\n    return numer//denom\n\ndef pdf_binom(x):\n\treturn binomial(2*k,x+k) / 2.**(2*k)\n\n\n\n\n\n# Union bound on each application of Chernoff-Cramer\nUnion_CC = 0. \n\nfor y in y_list:\n\tprint \"y=\",y\n\t### Construct a 4*4 matrix associated to y\n\tv1 = y\n\tv2 = rot(v1)\n\tmat = np.matrix([v1,v2])\n\n\n\t### Initialize a table to store the pdf of \\varphi_y\n\t### the range of the above distribution\n\tima = xrange(4 * (k*4)**2 )\n\tvarphi_y_Table = [0 for i in ima]\n\n\t### Brute force computation of the pdf of || x*y ||^2\n\ts = 0.\n\tfor x1 in supp:\n\t\tfor x2 in supp:\n\t\t\tx = np.array([x1,x2])\n\t\t\tmx = x * mat\n\t\t\ts = mx[0,0]**2 + mx[0,1]**2\n\t\t\tp = pdf_binom(x1) * pdf_binom(x2)\n\t\t\tvarphi_y_Table[s] += p                   ### The result is always a multiple of 4\n\n\tavg = sum([i*varphi_y_Table[i] for i in ima])\n\tprint \"varphi_y has average \",avg\n\n\tdef Moment(t):\n\t\treturn sum([varphi_y_Table[i] * exp(t*(i - avg)) for i in range(len(ima))])\n\n\n\n\tdef ChernoffCramer(n,t,bound):\n\t\tbeta = bound - n*avg\n\t\tp =  exp(- t*beta + n*log(Moment(t)))\n\t\treturn p\n\n\tt_CC = 0.0060\n\tp_CC = ChernoffCramer(n,t_CC,bound_CC)\n\n\tprint \"Chernoff-Cramer Bound\", p_CC, \" = 2^\", log(p_CC)/log(2)\n\t\n\tif check_each_y:\n\t\tUnion_CC += p_CC\n\n\nelse:\n\tUnion_CC = 4*p_CC\n\n\n\nprint\nprint \"#### \"\nprint \"#### Conclusion of Lemma 6 :\"\nprint \"#### \"\n\nprint \"with parameter k=\",k, \"and parameter n = \",n,\"(v has dimension 4n)\"\nprint \"The bound ||v||_2^2 <=\", bound_CC, \" fails with probability less than 2^\", log(Union_CC)/log(2)\n\nprint \"#### \"\nprint \"#### Corollary 1 :\"\nprint \"#### \"\n\nprint \"subgaussian parameter sigma = \", subg_param\nprint \"tailcut parameter tau = \", tau\nprint \"tailcut value ||v||* sigma * tau = \", subg_value\n\nprint \"sub-gaussian tail-bound (Lemma 5): 2^\", log(p_subg) /log(2)\nprint \"(failure proba per bit-agreement and per y)\"\nprint\nprint \"#### \"\nprint \"#### Conclusion of Corollary 1 :\"\nprint \"#### \"\nprint \"Partial bound ||(es'-e's )_i||_1 <=\", subg_value\n\nprint \"Final bound ||(es'-e's +e'')_i||_1 <=\", subg_value + 2*k\nprint \"fails with probability at most 2^\",\nprint log(Union_CC + 4 * 256 * p_subg)/log(2)\n\n", "meta": {"hexsha": "3721f0021bc7d7bfe081e4c5bccb1a4584b3fd18", "size": 3263, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/kem/newhopenist/upstream/scripts/failure-512k8.py", "max_stars_repo_name": "gabrielgauthier/liboqs-test", "max_stars_repo_head_hexsha": "1ead2e2b6e89a8dddcdf89393cc00cbbf37a6d23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kem/newhopenist/upstream/scripts/failure-512k8.py", "max_issues_repo_name": "gabrielgauthier/liboqs-test", "max_issues_repo_head_hexsha": "1ead2e2b6e89a8dddcdf89393cc00cbbf37a6d23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kem/newhopenist/upstream/scripts/failure-512k8.py", "max_forks_repo_name": "gabrielgauthier/liboqs-test", "max_forks_repo_head_hexsha": "1ead2e2b6e89a8dddcdf89393cc00cbbf37a6d23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4671052632, "max_line_length": 102, "alphanum_fraction": 0.612319951, "include": true, "reason": "import numpy", "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611643025387, "lm_q2_score": 0.8902942348544447, "lm_q1q2_score": 0.8550040079566523}}
{"text": "import numpy as np\n\n### Functions for you to fill in ###\n\n\ndef polynomial_kernel(X, Y, c, p):\n    \"\"\"\n        Compute the polynomial kernel between two matrices X and Y::\n            K(x, y) = (<x, y> + c)^p\n        for each pair of rows x in X and y in Y.\n\n        Args:\n            X - (n, d) NumPy array (n datapoints each with d features)\n            Y - (m, d) NumPy array (m datapoints each with d features)\n            c - a coefficient to trade off high-order and low-order terms (scalar)\n            p - the degree of the polynomial kernel\n\n        Returns:\n            kernel_matrix - (n, m) Numpy array containing the kernel matrix\n    \"\"\"\n    kernel_matrix = (np.inner(X, Y) + c) ** p\n    return kernel_matrix\n\n\ndef rbf_kernel(X, Y, gamma):\n    \"\"\"\n        Compute the Gaussian RBF kernel between two matrices X and Y::\n            K(x, y) = exp(-gamma ||x-y||^2)\n        for each pair of rows x in X and y in Y.\n\n        Args:\n            X - (n, d) NumPy array (n datapoints each with d features)\n            Y - (m, d) NumPy array (m datapoints each with d features)\n            gamma - the gamma parameter of gaussian function (scalar)\n\n        Returns:\n            kernel_matrix - (n, m) Numpy array containing the kernel matrix\n    \"\"\"\n    XT_X = np.mat([np.matmul(row, row.T) for row in X]).T\n    YT_Y = np.mat([np.matmul(row, row.T) for row in Y]).T\n\n    XTX_matrix = np.repeat(XT_X, Y.shape[0], axis=1)\n    YTY_matrix = np.repeat(YT_Y, X.shape[0], axis=1).T\n\n    distance_matrix = np.asarray(XTX_matrix + YTY_matrix - 2 * (np.matmul(X, Y.T)), dtype='float64')\n    kernel_matrix = np.exp(-gamma * distance_matrix)\n    return kernel_matrix\n", "meta": {"hexsha": "930b5c3aab0413fea1062437125a1d0d3e11fd83", "size": 1659, "ext": "py", "lang": "Python", "max_stars_repo_path": "mnist/part1/kernel.py", "max_stars_repo_name": "Jerimat/MITx-6.86-MachineLearning_EdX", "max_stars_repo_head_hexsha": "e454e0646cd923d689d3946ea2ff3432dec920ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-28T15:10:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T15:10:44.000Z", "max_issues_repo_path": "mnist/part1/kernel.py", "max_issues_repo_name": "Jerimat/MITx-6.86-MachineLearning_EdX", "max_issues_repo_head_hexsha": "e454e0646cd923d689d3946ea2ff3432dec920ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mnist/part1/kernel.py", "max_forks_repo_name": "Jerimat/MITx-6.86-MachineLearning_EdX", "max_forks_repo_head_hexsha": "e454e0646cd923d689d3946ea2ff3432dec920ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5625, "max_line_length": 100, "alphanum_fraction": 0.5907172996, "include": true, "reason": "import numpy", "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611654370414, "lm_q2_score": 0.8902942333990422, "lm_q1q2_score": 0.8550040075689815}}
{"text": "\"\"\"\nProblem 4\n\"\"\"\n\nimport numpy as np\n\n\ns_inf = np.pi/4\n\n\ndef term(n):\n    return (-1) ** n / (2 * n + 1)\n\n\ndef basic_sum(tol):\n    n = 0\n    val = 0\n    while True:\n        val += term(n)\n        if np.abs(s_inf - val) < tol:\n            return val, n\n        n += 1\n\n\ndef aitkin_sum(tol):\n    n = 0\n    while True:\n        sn2 = np.sum(term(np.arange(0, n+3)))\n        sn1 = sn2 - term(n+2)\n        sn0 = sn1 - term(n+1)\n        s_aitkin = sn0 - (sn1 - sn0)**2 / (sn2 - 2*sn1 + sn0)\n        if np.abs(s_inf - s_aitkin) < tol:\n            return s_aitkin, n\n        n += 1\n\n\nif __name__ == '__main__':\n    print(basic_sum(1e-7))\n    print(aitkin_sum(1e-7))\n\n", "meta": {"hexsha": "b8abf923a22624fbdef571d06842ad00eb86aba3", "size": 659, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/functions/summing_series.py", "max_stars_repo_name": "jacione/phys513", "max_stars_repo_head_hexsha": "a8e1d1de800b0372d013d69543e1619b0fb8e4e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/summing_series.py", "max_issues_repo_name": "jacione/phys513", "max_issues_repo_head_hexsha": "a8e1d1de800b0372d013d69543e1619b0fb8e4e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/summing_series.py", "max_forks_repo_name": "jacione/phys513", "max_forks_repo_head_hexsha": "a8e1d1de800b0372d013d69543e1619b0fb8e4e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.0731707317, "max_line_length": 61, "alphanum_fraction": 0.4779969651, "include": true, "reason": "import numpy", "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611597645271, "lm_q2_score": 0.8902942326713409, "lm_q1q2_score": 0.8550040018199186}}
{"text": "\"\"\"This module creates the contour plots for the bivariate normal distribution.\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import multivariate_normal\n\nfrom fig_config import OUTPUT_DIR\n\nplt.style.use(\"resources/grmpy.mplstyle\")\n\ny_min, y_max = -4, 4\n\nx = np.linspace(y_min, y_max, 100)\ny = np.linspace(y_min, y_max, 100)\nX, Y = np.meshgrid(x, y)\npos = np.dstack((X, Y))\n\nmean = np.tile(0.2, 2)\ncov = np.identity(2) * 2\n\nrv = multivariate_normal(mean, cov)\nrv.pdf(pos)\n\nax = plt.figure().add_subplot(111)\n\nlevels = np.linspace(0.1, 1.0, 10, endpoint=True)\ncns = plt.contourf(X, Y, rv.pdf(pos) / np.max(rv.pdf(pos)), levels=levels)\n\nax.set_ylabel(\"$Y_1$\")\nax.set_xlabel(\"$Y_0$\")\nax.set_ylim(y_min, y_max)\nax.set_xlim(y_min, y_max)\n\nax.set_yticklabels([])\nax.set_xticklabels([])\n\nplt.plot(\n    np.arange(y_min, y_max), np.arange(y_min, y_max), color=\"black\", linestyle=\"--\"\n)\n\nplt.colorbar(cns)\n\nax.text(3.3, 3.3, r\"$45^o$\")\n\nplt.savefig(OUTPUT_DIR + \"/fig-distribution-joint-potential.png\", dpi=300)\n\n# This plot shows the joint distribution of surplus and benefits.\nx = np.linspace(y_min, y_max, 100)\ny = np.linspace(y_min, y_max, 100)\nX, Y = np.meshgrid(x, y)\npos = np.dstack((X, Y))\n\nmean = np.tile(0.2, 2)\ncov = np.identity(2) * 2\n\nrv = multivariate_normal(mean, cov)\nrv.pdf(pos)\n\nax = plt.figure().add_subplot(111)\n\nlevels = np.linspace(0.1, 1.0, 10, endpoint=True)\ncns = plt.contourf(X, Y, rv.pdf(pos) / np.max(rv.pdf(pos)), levels=levels)\n\nax.set_ylabel(\"$B$\")\nax.set_xlabel(\"$S$\")\nax.set_ylim(y_min, y_max)\nax.set_xlim(y_min, y_max)\n\nax.set_yticklabels([\"\", \"\", \"\", \"\", 0])\nax.set_xticklabels([\"\", \"\", \"\", \"\", 0])\n\n\nplt.colorbar(cns)\n\nax.axvline(x=0, color=\"black\", linestyle=\"--\")\nax.axhline(y=0, color=\"black\", linestyle=\"--\")\n\nax.axvline(x=-0.5, color=\"lightgray\", linestyle=\"--\")\n\n\nax.text(x=-3.5, y=3.5, s=\"I\")\n\nax.text(x=3.5, y=3.5, s=\"II\")\n\nax.text(x=3.5, y=-3.5, s=\"III\")\n\nax.text(x=-3.5, y=-3.5, s=\"IV\")\n\nplt.savefig(OUTPUT_DIR + \"/fig-distribution-joint-surplus.png\", dpi=300)\n", "meta": {"hexsha": "164bbbcef511508d4edd90962365683e6eb9285f", "size": 2021, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/source/figures/scripts/fig-distribution-joint.py", "max_stars_repo_name": "OpenSourceEconomics/grmpy", "max_stars_repo_head_hexsha": "13a262fb615c79829eb4869cbb6693c9c51fb101", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2018-04-10T01:08:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:37:24.000Z", "max_issues_repo_path": "docs/source/figures/scripts/fig-distribution-joint.py", "max_issues_repo_name": "grmToolbox/grmpy", "max_issues_repo_head_hexsha": "13a262fb615c79829eb4869cbb6693c9c51fb101", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 127, "max_issues_repo_issues_event_min_datetime": "2017-08-02T13:29:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-27T19:42:07.000Z", "max_forks_repo_path": "docs/source/figures/scripts/fig-distribution-joint.py", "max_forks_repo_name": "OpenSourceEconomics/grmpy", "max_forks_repo_head_hexsha": "13a262fb615c79829eb4869cbb6693c9c51fb101", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2018-04-28T09:46:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-06T09:32:27.000Z", "avg_line_length": 22.7078651685, "max_line_length": 83, "alphanum_fraction": 0.6665017318, "include": true, "reason": "import numpy,from scipy", "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.8902942326713409, "lm_q1q2_score": 0.8550040008098772}}
{"text": "\"\"\"\n\nNombre del archivo: mandelbrot.py\nFecha de creación: 19/09/2019\nFecha de modificación: 20/09/2019\nAutores: Bryan Steven Biojó R.     1529879-2711\n         Joel Alexander Ramírez N. 1528879-2711\n\n\"\"\"\n\nimport numpy # Librería para computación científica.\nimport matplotlib.pyplot as plt # Librería para graficar.\nfrom numba import jit # Compilador de JIT que mejora la rapidez del código.\n\n# ******************************************* FUNCIÓN 1 *******************************************\n\n@jit\ndef mandelbrot1(Re, Im, maxIteraciones): # Primera función. Pinta z^2+C\n    z = 0.0j\n    c = complex(Re, Im)\n    \n    for i in range(maxIteraciones):\n        z = pow(z, 2) + c\n        \n        if((pow(z.real, 2) + pow(z.imag, 2)) >= 4):\n            return i\n\n    return maxIteraciones\n\n# ******************************************* GRÁFICA 1 *******************************************\n\nfilas = 2000\ncolumnas = 2000\n\nresultado = numpy.zeros([filas, columnas])\nfor fila_index, Re in enumerate(numpy.linspace(-2, 1, num = filas)):\n    for columna_index, Im in enumerate(numpy.linspace(-1, 1, num = columnas)):\n        resultado[fila_index, columna_index] = mandelbrot1(Re, Im, 100)\n\nplt.figure(dpi = 300)\nplt.imshow(resultado.T, cmap = 'gray', interpolation = 'bilinear', extent = [-2, 1, -1, 1])\nplt.xlabel('Eje Real')\nplt.ylabel('Eje Imaginario')\nplt.show()\n\n# ******************************************* FUNCIÓN 2 *******************************************\n\n@jit\ndef mandelbrot2(Re, Im, maxIteraciones): # Segunda función. Pinta z^3+C\n    z = 0.0j\n    c = complex(Re, Im)\n    \n    for i in range(maxIteraciones):\n        z = pow(z, 3) + c\n        \n        if((pow(z.real, 2) + pow(z.imag, 2)) >= 4):\n            return i\n\n    return maxIteraciones\n\n# ******************************************* GRÁFICA 2 *******************************************\n\nfilas = 2000\ncolumnas = 2000\n\nresultado = numpy.zeros([filas, columnas])\nfor fila_index, Re in enumerate(numpy.linspace(-2, 1, num = filas)):\n    for columna_index, Im in enumerate(numpy.linspace(-1.5, 1.5, num = columnas)):\n        resultado[fila_index, columna_index] = mandelbrot2(Re, Im, 100)\n\nplt.figure(dpi = 300)\nplt.imshow(resultado.T, cmap = 'hot', interpolation = 'bilinear', extent = [-2, 1, -1.5, 1.5])\nplt.xlabel('Eje Real')\nplt.ylabel('Eje Imaginario')\nplt.show()\n\n# ******************************************* FUNCIÓN 3 *******************************************\n\n@jit\ndef mandelbrot3(Re, Im, maxIteraciones): # Tecera función. Pinta z^5+C\n    z = 0.0j\n    c = complex(Re, Im)\n    \n    for i in range(maxIteraciones):\n        z = pow(z, 5) + c\n        \n        if((pow(z.real, 2) + pow(z.imag, 2)) >= 4):\n            return i\n\n    return maxIteraciones\n\n# ******************************************* GRÁFICA 3 *******************************************\n\nfilas = 2000\ncolumnas = 2000\n\nresultado = numpy.zeros([filas, columnas])\nfor fila_index, Re in enumerate(numpy.linspace(-2, 1, num = filas)):\n    for columna_index, Im in enumerate(numpy.linspace(-1, 1, num = columnas)):\n        resultado[fila_index, columna_index] = mandelbrot3(Re, Im, 100)\n\nplt.figure(dpi = 300)\nplt.imshow(resultado.T, cmap = 'winter', interpolation = 'bilinear', extent = [-2, 1, -1, 1])\nplt.xlabel('Eje Real')\nplt.ylabel('Eje Imaginario')\nplt.show()\n\n# ******************************************* FUNCIÓN 4 *******************************************\n\n@jit\ndef mandelbrot4(Re, Im, maxIteraciones): # Cuarta función. Pinta z^2+(1/C)\n    z = 0.0j\n    c = complex(Re, Im)\n    \n    for i in range(maxIteraciones):\n        z = pow(z, 2) + (1 / c)\n        \n        if((pow(z.real, 2) + pow(z.imag, 2)) >= 4):\n            return i\n\n    return maxIteraciones\n\n# ******************************************* GRÁFICA 4 *******************************************\n\nfilas = 2000\ncolumnas = 2000\n\nresultado = numpy.zeros([filas, columnas])\nfor fila_index, Re in enumerate(numpy.linspace(-2, 4, num = filas)):\n    for columna_index, Im in enumerate(numpy.linspace(-3, 3, num = columnas)):\n        resultado[fila_index, columna_index] = mandelbrot4(Re, Im, 100)\n\nplt.figure(dpi = 300)\nplt.imshow(resultado.T, cmap = 'Wistia', interpolation = 'bilinear', extent = [-2, 4, -3, 3])\nplt.xlabel('Eje Real')\nplt.ylabel('Eje Imaginario')\nplt.show()\n\n# ******************************************* FUNCIÓN 5 *******************************************\n\n@jit\ndef mandelbrot5(Re, Im, maxIteraciones): # Quinta función. Pinta z^7+(1/C)\n    z = 0.0j\n    c = complex(Re, Im)\n    \n    for i in range(maxIteraciones):\n        z = pow(z, 7) + (1 / c)\n        \n        if((pow(z.real, 2) + pow(z.imag, 2)) >= 4):\n            return i\n\n    return maxIteraciones\n\n# ******************************************* GRÁFICA 5 *******************************************\n\nfilas = 2000\ncolumnas = 2000\n\nresultado = numpy.zeros([filas, columnas])\nfor fila_index, Re in enumerate(numpy.linspace(-2, 2, num = filas)):\n    for columna_index, Im in enumerate(numpy.linspace(-2, 2, num = columnas)):\n        resultado[fila_index, columna_index] = mandelbrot5(Re, Im, 100)\n\nplt.figure(dpi = 300)\nplt.imshow(resultado.T, cmap = 'autumn', interpolation = 'bilinear', extent = [-2, 2, -2, 2])\nplt.xlabel('Eje Real')\nplt.ylabel('Eje Imaginario')\nplt.show()\n\n# ******************************************* FUNCIÓN 6 *******************************************\n\n@jit\ndef mandelbrot6(Re, Im, maxIteraciones): # Sexta función. Pinta z^2+(1/C^2)\n    z = 0.0j\n    c = complex(Re, Im)\n    \n    for i in range(maxIteraciones):\n        z = pow(z, 2) + (1 / (c * c))\n        \n        if((pow(z.real, 2) + pow(z.imag, 2)) >= 4):\n            return i\n\n    return maxIteraciones\n\n# ******************************************* GRÁFICA 6 *******************************************\n\nfilas = 2000\ncolumnas = 2000\n\nresultado = numpy.zeros([filas, columnas])\nfor fila_index, Re in enumerate(numpy.linspace(-2, 2, num = filas)):\n    for columna_index, Im in enumerate(numpy.linspace(-3, 1.5, num = columnas)):\n        resultado[fila_index, columna_index] = mandelbrot6(Re, Im, 100)\n\nplt.figure(dpi = 300)\nplt.imshow(resultado.T, cmap = 'bone', interpolation = 'bilinear', extent = [-2, 2, -3, 1.5])\nplt.xlabel('Eje Real')\nplt.ylabel('Eje Imaginario')\nplt.show()\n\n# ******************************************* FUNCIÓN 7 *******************************************\n\n@jit\ndef mandelbrot7(Re, Im, maxIteraciones): # Séptima función. Pinta z^2+C+(1/C)\n    z = 0.0j\n    c = complex(Re, Im)\n    \n    for i in range(maxIteraciones):\n        z = pow(z, 2) + c + (1 / c)\n        \n        if((pow(z.real, 2) + pow(z.imag, 2)) >= 4):\n            return i\n\n    return maxIteraciones\n\n# ******************************************* GRÁFICA 7 *******************************************\n\nfilas = 2000\ncolumnas = 2000\n\nresultado = numpy.zeros([filas, columnas])\nfor fila_index, Re in enumerate(numpy.linspace(-2, 2, num = filas)):\n    for columna_index, Im in enumerate(numpy.linspace(-3, 2, num = columnas)):\n        resultado[fila_index, columna_index] = mandelbrot7(Re, Im, 100)\n\nplt.figure(dpi = 300)\nplt.imshow(resultado.T, cmap = 'magma', interpolation = 'bilinear', extent = [-2, 2, -3, 2])\nplt.xlabel('Eje Real')\nplt.ylabel('Eje Imaginario')\nplt.show()\n\n# ******************************************* FUNCIÓN 8 *******************************************\n\n@jit\ndef mandelbrot8(Re, Im, maxIteraciones): # Octava función. Pinta [(z+C^2-1)/C^2]^2 \n    z = 0.0j\n    c = complex(Re, Im)\n    \n    for i in range(maxIteraciones):\n        z = pow(((z + (c * c) - 1) / (c * c)), 2)\n        \n        if((pow(z.real, 2) + pow(z.imag, 2)) >= 4):\n            return i\n\n    return maxIteraciones\n\n# ******************************************* GRÁFICA 8 *******************************************\n\nfilas = 2000\ncolumnas = 2000\n\nresultado = numpy.zeros([filas, columnas])\nfor fila_index, Re in enumerate(numpy.linspace(-2, 2, num = filas)):\n    for columna_index, Im in enumerate(numpy.linspace(-2, 2, num = columnas)):\n        resultado[fila_index, columna_index] = mandelbrot8(Re, Im, 100)\n\nplt.figure(dpi = 300)\nplt.imshow(resultado.T, cmap = 'binary', interpolation = 'bilinear', extent = [-2, 2, -2, 2])\nplt.xlabel('Eje Real')\nplt.ylabel('Eje Imaginario')\nplt.show()\n\n# ******************************************* FUNCIÓN 9 *******************************************\n\n@jit\ndef mandelbrot9(Re, Im, maxIteraciones): # Novena función. Pinta [z^2+(1/C) interseccción z^2+C (o eso parece).\n    z = 0.0j\n    c = complex(Re, Im)\n    \n    for i in range(maxIteraciones):\n        z = pow(z, 2) + (1 / c)\n        z = pow(z, 2) + c\n        \n        if((pow(z.real, 2) + pow(z.imag, 2)) >= 4):\n            return i\n\n    return maxIteraciones\n\n# ******************************************* GRÁFICA 9 *******************************************\n\nfilas = 2000\ncolumnas = 2000\n\nresultado = numpy.zeros([filas, columnas])\nfor fila_index, Re in enumerate(numpy.linspace(-2, 2, num = filas)):\n    for columna_index, Im in enumerate(numpy.linspace(-2, 2, num = columnas)):\n        resultado[fila_index, columna_index] = mandelbrot9(Re, Im, 100)\n\nplt.figure(dpi = 300)\nplt.imshow(resultado.T, cmap = 'Greens', interpolation = 'bilinear', extent = [-2, 2, -2, 2])\nplt.xlabel('Eje Real')\nplt.ylabel('Eje Imaginario')\nplt.show()\n\n# ******************************************* FUNCIÓN 10 ******************************************\n\n@jit\ndef mandelbrot10(Re, Im, maxIteraciones): # Décima función. Pinta z^3-z+C\n    z = 0.0j\n    c = complex(Re, Im)\n    \n    for i in range(maxIteraciones):\n        z = pow(z, 3) - z + c\n        \n        if((pow(z.real, 2) + pow(z.imag, 2)) >= 4):\n            return i\n\n    return maxIteraciones\n\n# ******************************************* GRÁFICA 10 ******************************************\n\nfilas = 2000\ncolumnas = 2000\n\nresultado = numpy.zeros([filas, columnas])\nfor fila_index, Re in enumerate(numpy.linspace(-2, 2, num = filas)):\n    for columna_index, Im in enumerate(numpy.linspace(-1, 1, num = columnas)):\n        resultado[fila_index, columna_index] = mandelbrot10(Re, Im, 100)\n\nplt.figure(dpi = 300)\nplt.imshow(resultado.T, cmap = 'YlOrBr', interpolation = 'bilinear', extent = [-2, 1, -1, 1])\nplt.xlabel('Eje Real')\nplt.ylabel('Eje Imaginario')\nplt.show()\n", "meta": {"hexsha": "10a5710f04a6f4c32818f9b3cecfaa8f6c1055a5", "size": 10230, "ext": "py", "lang": "Python", "max_stars_repo_path": "mandelbrot.py", "max_stars_repo_name": "bryansbr/proyectoVA", "max_stars_repo_head_hexsha": "6d8ab0af998f33a88fa84c028573ddbba1d151ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mandelbrot.py", "max_issues_repo_name": "bryansbr/proyectoVA", "max_issues_repo_head_hexsha": "6d8ab0af998f33a88fa84c028573ddbba1d151ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mandelbrot.py", "max_forks_repo_name": "bryansbr/proyectoVA", "max_forks_repo_head_hexsha": "6d8ab0af998f33a88fa84c028573ddbba1d151ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4769230769, "max_line_length": 111, "alphanum_fraction": 0.5187683284, "include": true, "reason": "import numpy,from numba", "num_tokens": 2921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611574955211, "lm_q2_score": 0.8902942319436397, "lm_q1q2_score": 0.8550039991009797}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# plotting Rosenbrock funtion\nx, y = np.meshgrid(np.linspace(-50, 50, 200),np.linspace(-500, 1000, 200))\nz = (1-x)**2 + 100*((y-x**2)**2)\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1, projection='3d')\nax.plot_surface(x, y, z, rstride=1, cstride=1, cmap = 'jet', alpha=0.7)\n\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Rosenbrock Function\", fontsize='small')\nplt.grid(color='silver', linestyle='-', linewidth=0.2)\nax.scatter(1, 1, marker='o', color='red')\nplt.tight_layout()\nplt.show()\n\n# plot the contour\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.contour(x, y, z, 200, cmap = 'jet')\n\nax.scatter(1, 1, marker='o', color='red')\n\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Rosenbrock Function\", fontsize='small')\nplt.grid(color='silver', linestyle='-', linewidth=0.2)\nplt.tight_layout()\nplt.show()\n\n# using autodiff to calculate the gradient and perform gradient descent\nfrom autograd import grad \nimport autograd.numpy as np\nimport numpy\n\ndef rosenbrock(x):\n    z = (1-x[0])**2 + 100*((x[1]-x[0]**2)**2)\n    return z\n# testing how to calculate the gradient!\ngradient = grad(rosenbrock)\n# it works!\ngradient(np.array([3., 5.]))\n\n# now doing regular gradient descent\nw = np.array([2., 3.])\ngamma = 10e-4\nepochs = 1000\ntrace_x = np.zeros(1 + epochs)\ntrace_y = np.zeros(1 + epochs)\ntrace_z = np.zeros(1 + epochs)\ntrace_x[0] = w[0]\ntrace_y[0] = w[1]\ntrace_z[0] = rosenbrock(w)\n\nfor e in range(epochs):\n  grad_eval = gradient(w)\n  w = w - gamma*grad_eval\n  trace_x[e+1] = w[0]\n  trace_y[e+1] = w[1]\n  trace_z[e+1] = rosenbrock(w)\n  #print(w)\nprint(trace_z)\n\n# plotting the trace\nimport numpy as nmp\nimport matplotlib.pyplot as plt\n\n# plotting Rosenbrock funtion\nx, y = nmp.meshgrid(nmp.linspace(-50, 50, 200),nmp.linspace(-500, 1000, 200))\nz = (1-x)**2 + 100*((y-x**2)**2)\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1, projection='3d')\nax.plot_surface(x, y, z, rstride=1, cstride=1, cmap = 'jet', alpha=0.7)\n\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Rosenbrock Function\", fontsize='small')\nplt.grid(color='silver', linestyle='-', linewidth=0.2)\nax.scatter(trace_x, trace_y, trace_z, marker='o', color='red')\nplt.tight_layout()\nplt.show()\n\n# plot the contour\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.contour(x, y, z, 200, cmap = 'jet')\nax.scatter(trace_x, trace_y, marker='o', color='red')\n\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Rosenbrock Function\", fontsize='small')\nplt.grid(color='silver', linestyle='-', linewidth=0.2)\nplt.tight_layout()\nplt.show()\n\n# now doing gradient descent with momentum\n# I used some code from http://people.duke.edu/~ccc14/sta-663-2018/notebooks/S09G_Gradient_Descent_Optimization.html\nbeta = 0.9\n#w = np.array([2., 3.])\nw = np.array([-2., 0.])\nv=0\ntrace_x = np.zeros(1 + epochs)\ntrace_y = np.zeros(1 + epochs)\ntrace_z = np.zeros(1 + epochs)\ntrace_x[0] = w[0]\ntrace_y[0] = w[1]\ntrace_z[0] = rosenbrock(w)\ngamma = 10e-3\nfor i in range(epochs):\n  v = beta*v + (1-beta)*gradient(w)\n  vc = v/(1+beta**(i+1))\n  w = w - gamma * vc\n  trace_x[i+1] = w[0]\n  trace_y[i+1] = w[1]\n  trace_z[i+1] = rosenbrock(w)\n  #print(w)\nprint(trace_z)\nprint(trace_x)\nprint(trace_y)\n\n# plotting the trace\nimport numpy as nmp\nimport matplotlib.pyplot as plt\n\n# plotting Rosenbrock funtion\nx, y = nmp.meshgrid(nmp.linspace(-5, 5, 200),nmp.linspace(-5, 5, 200))\nz = (1-x)**2 + 100*((y-x**2)**2)\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1, projection='3d')\nax.plot_surface(x, y, z, rstride=1, cstride=1, cmap = 'jet', alpha=0.7)\nax.view_init(elev=10, azim=60)\n\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Rosenbrock Function\", fontsize='small')\n#plt.grid(color='silver', linestyle='-', linewidth=0.2)\nax.scatter(trace_x, trace_y, trace_z, marker='x', color='red', s=10)\nplt.tight_layout()\nplt.show()\n\n# plot the contour\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.contour(x, y, z, 200, cmap = 'jet')\nax.plot(trace_x, trace_y, color='blue')\nax.scatter(trace_x, trace_y, marker='x', color='red', s=5)\nax.scatter(1, 1, marker='o', color='magenta', s=30)\n\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Rosenbrock Function\", fontsize='small')\nplt.grid(color='silver', linestyle='-', linewidth=0.2)\nplt.tight_layout()\nplt.show\n\n# plot the contour\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.scatter(trace_x, trace_y, marker='x', color='red', s=5)\n\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Rosenbrock Function\", fontsize='small')\nplt.grid(color='silver', linestyle='-', linewidth=0.2)\nplt.tight_layout()\nplt.show", "meta": {"hexsha": "d825cc0f8a65f436378c6dd895d826d0980488ea", "size": 4502, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW03/q2.py", "max_stars_repo_name": "AtoosaParsa/CS387-Assignments", "max_stars_repo_head_hexsha": "57dfd68dded486a61df247299d93ca0c804a6b98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW03/q2.py", "max_issues_repo_name": "AtoosaParsa/CS387-Assignments", "max_issues_repo_head_hexsha": "57dfd68dded486a61df247299d93ca0c804a6b98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW03/q2.py", "max_forks_repo_name": "AtoosaParsa/CS387-Assignments", "max_forks_repo_head_hexsha": "57dfd68dded486a61df247299d93ca0c804a6b98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3274853801, "max_line_length": 116, "alphanum_fraction": 0.671257219, "include": true, "reason": "import numpy", "num_tokens": 1525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611574955211, "lm_q2_score": 0.89029422102812, "lm_q1q2_score": 0.8550039886181385}}
{"text": "# Linear System Solvers\r\n#\r\n# Available Methods:\r\n# - LU (Own Implementation)\r\n# - LU_sparse (Own Implementation)\r\n# - LU_compiled (Own Implementation)\r\n# - LU_scipy_sparse (Scipy Implementation)\r\n# - QR (Own Implementation)\r\n# - QR_compiled (Own Implementation)\r\n# - QR_scipy (Scipy Implementation)\r\n# - scipy (Scipy Implementation)\r\n# - jacobi (Own Implementation)\r\n# - jacobi_compiled (Own Implementation)\r\n# - jacobi_sparse (Own Implementation)\r\n# - gauss_seidel (Own Implementation)\r\n# - gauss_seidel_compiled (Own Implementation)\r\n# - gauss_seidel_sparse (Own Implementation)\r\n# - sor (Own Implementation)\r\n# - sor_compiled (Own Implementation)\r\n# - sor_sparse (Own Implementation)\r\n#\r\n# Assignment 1 for ME4233\r\n# Author: Giovani Hidalgo Ceotto\r\n# Prof: Mengqi Zhang\r\n\r\nimport numpy as np\r\nfrom scipy.sparse import dia_matrix, csr_matrix, csc_matrix, lil_matrix, identity, tril, triu\r\nfrom scipy.sparse.linalg import splu\r\nfrom scipy.sparse.linalg import inv as sparse_inv\r\nfrom scipy.linalg import solve, inv, qr\r\nfrom numba import jit\r\n\r\n# Wrapper for all solvers\r\ndef solve_algebraic_system(A, b, method, initial_guess=0, true_solution=0, tol=1e-6, w=1):\r\n    \"\"\" Solves the algebraic system A*x = b, for the vector x.\r\n        \r\n        Parameters\r\n        ----------\r\n        A : array\r\n            Matrix A corresponding to the system A*x = b. Must be in sparse\r\n            format.\r\n        b : array\r\n            Column vector b corresponding to the system A*x = b.\r\n        method : string\r\n            Mehtod to be used. Available methods are: \r\n                - LU (Own Implementation)\r\n                - LU_sparse (Own Implementation)\r\n                - LU_compiled (Own Implementation)\r\n                - LU_scipy_sparse (Scipy Implementation)\r\n                - QR (Own Implementation)\r\n                - QR_compiled (Own Implementation)\r\n                - QR_scipy (Scipy Implementation)\r\n                - scipy (Scipy Implementation)\r\n                - jacobi (Own Implementation)\r\n                - jacobi_compiled (Own Implementation)\r\n                - jacobi_sparse (Own Implementation)\r\n                - gauss_seidel (Own Implementation)\r\n                - gauss_seidel_compiled (Own Implementation)\r\n                - gauss_seidel_sparse (Own Implementation)\r\n                - sor (Own Implementation)\r\n                - sor_compiled (Own Implementation)\r\n                - sor_sparse (Own Implementation)\r\n        initial_guess : array, optional\r\n            Initial solution used for iterative solvers.\r\n        true_solution : array, optional\r\n            If given, iterative solver residuals will be calculated considering\r\n            this.\r\n        tol : float, optional\r\n            Convergence tolerance for iterative solvers.\r\n        w : float, optiona\r\n            Relaxation parameter to be used with the SOR methods.\r\n\r\n        Returns\r\n        -------\r\n        x : array\r\n            Solution vector corresponding to A*x = b.\r\n        residue : array\r\n            Residue array given by iterative solver.        \r\n    \"\"\"\r\n    if method == \"LU\":\r\n        L_prime, U = LU_factorization(A.toarray())\r\n        return solve_upper_triangular_system(U, L_prime.dot(b))\r\n    elif method == \"LU_sparse\":\r\n        L_prime, U = LU_factorization_sparse(A)\r\n        return solve_upper_triangular_system(U.toarray(), L_prime.dot(b))\r\n    elif method == \"LU_compiled\":\r\n        L, U = LU_factorization_compiled(A.toarray())\r\n        y = solve_lower_triangular_system(L, b)\r\n        return solve_upper_triangular_system(U, y)\r\n    elif method == \"LU_scipy_sparse\":\r\n        LU = splu(csc_matrix(A))\r\n        return LU.solve(b)\r\n    elif method == \"QR\":\r\n        Q, R = QR_factorization(A.toarray())\r\n        return solve_upper_triangular_system(R, np.dot(Q.T, b))\r\n    elif method == \"QR_compiled\":\r\n        Q, R = QR_factorization_compiled(A.toarray())\r\n        return solve_upper_triangular_system(R, np.dot(Q.T, b))\r\n    elif method == \"QR_scipy\":\r\n        Q, R = qr(A.toarray())\r\n        return solve_upper_triangular_system(R, np.dot(Q.T, b))\r\n    elif method == \"jacobi\":\r\n        return jacobi(A.toarray(), b, initial_guess, true_solution, tol)\r\n    elif method == \"jacobi_compiled\":\r\n        return jacobi_compiled(A.toarray(), b, initial_guess, true_solution, tol)\r\n    elif method == \"jacobi_sparse\":\r\n        return jacobi_sparse(A, b, initial_guess, true_solution, tol)\r\n    elif method == \"gauss_seidel\":\r\n        return gauss_seidel(A.toarray(), b, initial_guess, true_solution, tol)\r\n    elif method == \"gauss_seidel_compiled\":\r\n        return gauss_seidel_compiled(A.toarray(), b, initial_guess, true_solution, tol)\r\n    elif method == \"gauss_seidel_sparse\":\r\n        return gauss_seidel_sparse(A, b, initial_guess, true_solution, tol)\r\n    elif method == \"sor\":\r\n        return sor(A.toarray(), b, initial_guess, true_solution, tol, w)\r\n    elif method == \"sor_compiled\":\r\n        return sor_compiled(A.toarray(), b, initial_guess, true_solution, tol, w)\r\n    elif method == \"sor_sparse\":\r\n        return sor_sparse(A, b, initial_guess, true_solution, tol, w)\r\n    elif method == \"scipy\":\r\n        return solve(A.toarray(), b)\r\n\r\n\r\n# Direct triangular system Solvers\r\ndef solve_upper_triangular_system(U, b):\r\n    \"\"\" Solves the linear algebraic equation U*x = b, where b is a column\r\n    vector, x is the unknown column vector and U is an upper triangular\r\n    matrix.\r\n\r\n    Parameters\r\n    ----------\r\n    U : array\r\n        Square upper triangular matrix.\r\n    b : array\r\n        Column vector with the same number of lines as U.\r\n    \r\n    Returns\r\n    -------\r\n    x : array\r\n        Column vector with the same number of lines as U which solves U*x=b.\r\n    \"\"\"\r\n    # Retrieve matrix dimension\r\n    n, m = U.shape\r\n\r\n    # Initialize solution vector x:\r\n    x = np.zeros(n)\r\n\r\n    # Iterate line by line, beginning from the last one.\r\n    for i in range(n-1, -1, -1):\r\n        x[i] = (b[i] - sum([U[i, j]*x[j] for j in range(i+1, n)]))/U[i, i]\r\n    \r\n    # Return the solution vector x\r\n    return x\r\n\r\ndef solve_lower_triangular_system(L, b):\r\n    \"\"\" Solves the linear algebraic equation L*y = b, where b is a column\r\n    vector, y is the unknown column vector and L is a lower triangular\r\n    matrix.\r\n\r\n    Parameters\r\n    ----------\r\n    L : array\r\n        Square lower triangular matrix.\r\n    b : array\r\n        Column vector with the same number of lines as L.\r\n    \r\n    Returns\r\n    -------\r\n    y : array\r\n        Column vector with the same number of lines as L which solves L*y=b.\r\n    \"\"\"\r\n    # Retrieve matrix dimension\r\n    n, m = L.shape\r\n\r\n    # Initialize solution vector y\r\n    y = np.zeros(n)\r\n\r\n    # Iterate line by line, beginning from the first one.\r\n    for i in range(n):\r\n        y[i] = (b[i] - sum([L[i, j]*y[j] for j in range(i)]))/L[i, i]\r\n    \r\n    # Return the solution vector y\r\n    return y\r\n\r\n\r\n# Factorization methods\r\ndef LU_factorization(A, return_L=False):\r\n    \"\"\" Decomposes the given A matrix into its LU factors, that is A=LU,\r\n    where L is a lower triangular matrix, with diagonal entries equal to 1 and\r\n    U is an upper triangular matrix. By default, it returns U and L^(-1).\r\n\r\n    Parameters\r\n    ----------\r\n    A : array\r\n        Matrix to be decomposed into A=LU. A must be a square matrix with no\r\n        diagonal entries equal to 0.\r\n    return_L : bool, optional\r\n        If True, returns U and L. If false, which it is by default, return U\r\n        and L^(-1).\r\n\r\n    Returns\r\n    -------\r\n    L : array\r\n        Lower triangular matrix with the same shape as A, equal to L^(-1) if \r\n        return_L is False. If return_L is true, equal to L.\r\n    U : array\r\n        Upper triangular matrix with the same shape as A.\r\n\r\n    \"\"\"\r\n    # Retrieve matrix dimension\r\n    n, m = A.shape\r\n\r\n    # Initialize L prime (L^(-1)) and U\r\n    L_prime = np.eye(n, n, dtype=np.float64)\r\n    U = A.copy()\r\n\r\n    # Iterate column by column, except for the last column\r\n    for j in range(m - 1):\r\n        # Create temporary L_1\r\n        L_temp = np.eye(n, n, dtype=np.float64)\r\n        L_temp[(j+1):, j] = U[(j+1):, j]/(-U[j, j])\r\n\r\n        # Multiply L_temp by current version of U to get new U\r\n        U = L_temp.dot(U)\r\n\r\n        # Multiply L_temp by current version of L_prime to get new L_prime\r\n        L_prime = L_temp.dot(L_prime)\r\n    \r\n    # Return L and U\r\n    if return_L:\r\n        return inv(L_prime), U\r\n    else:\r\n        return L_prime, U\r\n\r\ndef LU_factorization_sparse(A, return_L=False):\r\n    \"\"\" Decomposes the given A matrix into its LU factors, that is A=LU,\r\n    where L is a lower triangular matrix, with diagonal entries equal to 1 and\r\n    U is an upper triangular matrix. By default, it returns U and L^(-1). It\r\n    makes use of sparse properties to optimize speed.\r\n\r\n    Parameters\r\n    ----------\r\n    A : array\r\n        Matrix to be decomposed into A=LU. A must be a square matrix with no\r\n        diagonal entries equal to 0.\r\n    return_L : bool, optional\r\n        If True, returns U and L. If false, which it is by default, return U\r\n        and L^(-1).\r\n\r\n    Returns\r\n    -------\r\n    L : array\r\n        Lower triangular matrix with the same shape as A, equal to L^(-1) if \r\n        return_L is False. If return_L is true, equal to L.\r\n    U : array\r\n        Upper triangular matrix with the same shape as A.\r\n\r\n    \"\"\"\r\n    # Retrieve matrix dimension\r\n    n, m = A.shape\r\n\r\n    # Initialize L prime (L^(-1)) U\r\n    L_prime = identity(n, np.float64, 'csr')\r\n    U = csc_matrix(A)\r\n    L_temp1 = identity(n, np.float64, 'lil')\r\n\r\n    # Iterate column by column, except for the last column\r\n    for j in range(m - 1):\r\n        # Create temporary Ls\r\n        L_temp1[(j+1):, j] = U[(j+1):, j]/(-U[j, j])\r\n        L_temp2 = csr_matrix(L_temp1)\r\n\r\n        # Roll back L_temp1\r\n        L_temp1[(j+1):, j] = 0\r\n\r\n        # Multiply L_temp by current version of U to get new U\r\n        U = L_temp2.dot(U)\r\n\r\n        # Multiply L_temp by current version of L_prime to get new L_prime\r\n        L_prime = L_temp2.dot(L_prime)\r\n    \r\n    # Return L and U\r\n    if return_L:\r\n        return Inv(L_prime), U\r\n    else:\r\n        return L_prime, U\r\n\r\n@jit(nopython=True)\r\ndef LU_factorization_compiled(A):\r\n    \"\"\" Decomposes the given A matrix into its LU factors, that is A=LU,\r\n    where L is a lower triangular matrix, with diagonal entries equal to 1 and\r\n    U is an upper triangular matrix. The function is compiled the first time it\r\n    is ran by numba.\r\n\r\n    Parameters\r\n    ----------\r\n    A : array\r\n        Matrix to be decomposed into A=LU. A must be a square matrix with no\r\n        diagonal entries equal to 0 and in numpy format.\r\n    return_L : bool, optional\r\n        If True, returns U and L. If false, which it is by default, return U\r\n        and L^(-1).\r\n\r\n    Returns\r\n    -------\r\n    L : array\r\n        Lower triangular matrix with the same shape as A.\r\n    U : array\r\n        Upper triangular matrix with the same shape as A.\r\n\r\n    \"\"\"\r\n    # Retrieve matrix dimension\r\n    n, m = A.shape\r\n\r\n    # Initialize L and U\r\n    L = np.eye(n, n)\r\n    U = np.eye(n, n)\r\n\r\n    # Create first column of L and first row of U\r\n    L[:, 0] = A[:, 0]/A[0, 0]\r\n    U[0, :] = A[0, :]\r\n\r\n    # Iterate line by line, except for the first and last ones\r\n    for i in range(1, n):\r\n        #  Complete ith row of U and ith column of L\r\n        for j in range(i, n):\r\n            sum1 = 0\r\n            for k in range(i):\r\n                sum1 += L[i, k]*U[k, j]\r\n            U[i, j] = A[i, j] - sum1\r\n            sum2 = 0\r\n            for k in range(i):\r\n                sum2 += L[j, k]*U[k, i]\r\n            L[j, i] = (A[j, i] - sum2)/U[i, i]\r\n    \r\n    # Return L and U\r\n    return L, U\r\n\r\ndef QR_factorization(A):\r\n    \"\"\"Decomposes the given A matrix into its QR factors, that is A=QR,\r\n    where Q is a orthogonal matrix and R is an upper triangular matrix.\r\n\r\n    Parameters\r\n    ----------\r\n    A : array\r\n        Matrix to be decomposed into A=QR. A must be a square matrix with no\r\n        diagonal entries equal to 0.\r\n\r\n    Returns\r\n    -------\r\n    Q : array\r\n        Orthogonal matrix with the same shape as A.\r\n    R : array\r\n        Upper triangular matrix with the same shape as A.\r\n    \"\"\"\r\n    # Retrieve matrix dimension\r\n    n, m = A.shape\r\n\r\n    # Initialize Q and R matrix\r\n    Q = A.copy()\r\n    R = np.eye(n, n)\r\n\r\n    # Compute columns of Q matrix\r\n    for j in range(n):\r\n        # Subtract projections on previous columns\r\n        temp1 = Q[:, j]\r\n        temp2 = temp1 - sum([np.dot(temp1.T, Q[:, k])*Q[:, k] for k in range(j)])\r\n        # Normalize result\r\n        Q[:, j] = temp2/np.linalg.norm(temp2)\r\n\r\n    # Compute lines of R matrix\r\n    for i in range(n):\r\n        R[i, i:] = [np.dot(A[:, j], Q[:, i]) for j in range(i, n)]\r\n    \r\n    # Return Q and R\r\n    return Q, R\r\n\r\n@jit(nopython=True)\r\ndef QR_factorization_compiled(A):\r\n    \"\"\"Decomposes the given A matrix into its QR factors, that is A=QR,\r\n    where Q is a orthogonal matrix and R is an upper triangular matrix.\r\n\r\n    Parameters\r\n    ----------\r\n    A : array\r\n        Matrix to be decomposed into A=QR. A must be a square matrix with no\r\n        diagonal entries equal to 0.\r\n\r\n    Returns\r\n    -------\r\n    Q : array\r\n        Orthogonal matrix with the same shape as A.\r\n    R : array\r\n        Upper triangular matrix with the same shape as A.\r\n    \"\"\"\r\n    # Retrieve matrix dimension\r\n    n, m = A.shape\r\n\r\n    # Initialize Q and R matrix\r\n    Q = A.copy()\r\n    R = np.eye(n, n)\r\n\r\n    # Compute columns of Q matrix\r\n    for j in range(n):\r\n        # Subtract projections on previous columns\r\n        current_column = Q[:, j].copy()\r\n        for k in range(j):\r\n            reference_column = Q[:, k]\r\n            # Project current column on reference column\r\n            proj = 0\r\n            for l in range(n):\r\n                proj += current_column[l] * reference_column[l]\r\n            # Subtract projection from current column\r\n            current_column -= proj*reference_column\r\n        # Calculate norm\r\n        norm = 0.0\r\n        for k in range(n):\r\n            norm += current_column[k]**2\r\n        norm = (norm)**0.5\r\n        # Normalize result\r\n        Q[:, j] = current_column/norm\r\n\r\n    # Compute lines of R matrix\r\n    for i in range(n):\r\n        for j in range(i, n):\r\n            # Scalar projection of jth column from A into ith column from Q\r\n            proj = 0\r\n            A_column = A[:, j]\r\n            Q_column = Q[:, i]\r\n            for k in range(n):\r\n                proj += A_column[k] * Q_column[k]\r\n            R[i, j] = proj\r\n\r\n    # Return Q and R\r\n    return Q, R\r\n\r\n\r\n# Iterative Solvers\r\ndef jacobi(A, b, initial_guess, true_solution, tol):\r\n    \"\"\" Solves the algebraic system A*x=b using a jacobi iterative solver.\r\n\r\n    Parameters\r\n    ----------\r\n    A : array\r\n        Matrix A corresponding to the system A*x = b.\r\n    b : array\r\n        Column vector b corresponding to the system A*x = b.\r\n    initial_guess : array, optional\r\n        Initial solution.\r\n    true_solution : array, optional\r\n        Used for residual calculation\r\n    tol : float, optional\r\n        Convergence tolerance.\r\n\r\n    Returns\r\n    -------\r\n    x : array\r\n        Solution vector corresponding to A*x = b.\r\n    residue : array\r\n        Residue array.\r\n    \"\"\"\r\n    print(\"Initializing Jacobi Solver\", end='\\r')\r\n\r\n    # Retrieve matrix dimension\r\n    n, m = A.shape\r\n\r\n    # Flatten b\r\n    b = b.flatten()\r\n\r\n    # Initialize u\r\n    u = initial_guess.flatten()\r\n    u_true = true_solution.flatten()\r\n    u_new = u.copy()\r\n\r\n    # Initialize residue\r\n    res = np.linalg.norm(u - true_solution)\r\n    res_array = [res]\r\n\r\n    # Iterate\r\n    while res > tol:\r\n        print(\"Current Iteration and Residue: {:06d} - {:05.4E}\".format(len(res_array), res), end='\\r')\r\n        \r\n        for i in range(n):\r\n            sum_factor = 0\r\n            for j in range(i):\r\n                sum_factor += A[i, j] * u[j]\r\n            \r\n            for j in range(i + 1, n):\r\n                sum_factor += A[i, j] * u[j]\r\n\r\n            u_new[i] = (1/A[i, i]) * (b[i] - sum_factor)\r\n        \r\n        # Update u\r\n        u = u_new.copy()\r\n\r\n        res = np.linalg.norm(u - true_solution)\r\n        res_array += [res]\r\n    \r\n    print(\"\\nJacobi solver converged after \", len(res_array), \" iterations.\")\r\n    return u, res_array\r\n\r\n@jit(nopython=True)\r\ndef jacobi_compiled(A, b, initial_guess, true_solution, tol):\r\n    \"\"\" Solves the algebraic system A*x=b using a jacobi iterative solver.\r\n\r\n    Parameters\r\n    ----------\r\n    A : array\r\n        Matrix A corresponding to the system A*x = b.\r\n    b : array\r\n        Column vector b corresponding to the system A*x = b.\r\n    initial_guess : array, optional\r\n        Initial solution.\r\n    true_solution : array, optional\r\n        Used for residual calculation\r\n    tol : float, optional\r\n        Convergence tolerance.\r\n\r\n    Returns\r\n    -------\r\n    x : array\r\n        Solution vector corresponding to A*x = b.\r\n    residue : array\r\n        Residue array.\r\n    \"\"\"\r\n    # Retrieve matrix dimension\r\n    n, m = A.shape\r\n\r\n    # Flatten b\r\n    b = b.flatten()\r\n\r\n    # Initialize u\r\n    u = initial_guess.flatten()\r\n    u_true = true_solution.flatten()\r\n    u_new = u.copy()\r\n\r\n    # Initialize residue\r\n    res = np.linalg.norm(u - true_solution)\r\n    res_array = [res]\r\n\r\n    # Iterate\r\n    while res > tol:\r\n        for i in range(n):\r\n            sum_factor = 0\r\n            for j in range(i):\r\n                sum_factor += A[i, j] * u[j]\r\n            \r\n            for j in range(i + 1, n):\r\n                sum_factor += A[i, j] * u[j]\r\n\r\n            u_new[i] = (1/A[i, i]) * (b[i] - sum_factor)\r\n        \r\n        # Update u\r\n        u = u_new.copy()\r\n\r\n        # Update residue\r\n        res = np.linalg.norm(u - true_solution)\r\n        res_array += [res]\r\n\r\n    return u, res_array\r\n\r\ndef jacobi_sparse(A, b, initial_guess, true_solution, tol):\r\n    \"\"\" Solves the algebraic system A*x=b using a jacobi iterative solver.\r\n\r\n    Parameters\r\n    ----------\r\n    A : array\r\n        Matrix A corresponding to the system A*x = b. Should be in sparse\r\n        format.\r\n    b : array\r\n        Column vector b corresponding to the system A*x = b.\r\n    initial_guess : array, optional\r\n        Initial solution.\r\n    true_solution : array, optional\r\n        Used for residual calculation\r\n    tol : float, optional\r\n        Convergence tolerance.\r\n\r\n    Returns\r\n    -------\r\n    x : array\r\n        Solution vector corresponding to A*x = b.\r\n    residue : array\r\n        Residue array.\r\n    \"\"\"\r\n    # print(\"Initializing Jacobi Sparse Solver\", end='\\r')\r\n    # Retrieve matrix dimension\r\n    n, m = A.shape\r\n    \r\n    # Define D by extracting main diagonal from A\r\n    main_diagonal = A.diagonal()\r\n    D = dia_matrix(([main_diagonal], [0]), shape=(n, n), dtype=np.float64)\r\n\r\n    # Compute R\r\n    R = A - D\r\n\r\n    # Compute D^-1\r\n    D_inverse = dia_matrix(([1/main_diagonal], [0]), shape=(n, n), dtype=np.float64)\r\n\r\n    # Compute (D^-1)*b\r\n    D_inverse_dot_b =  D_inverse.dot(b.flatten())\r\n\r\n    # Compute -(D^-1)*R\r\n    D_inverse_dot_R = D_inverse.dot(R)\r\n\r\n    # Initialize u\r\n    u = initial_guess.flatten()\r\n    u_true = true_solution.flatten()\r\n\r\n    # Initialize residue\r\n    res = np.linalg.norm(u - true_solution)\r\n    res_array = [res]\r\n\r\n    # Iterate\r\n    while res > tol:\r\n        # print(\"Current Iteration and Residue: {:06d} - {:05.4E}\".format(len(res_array), res), end='\\r')\r\n\r\n        # Update u\r\n        u = D_inverse_dot_b - D_inverse_dot_R.dot(u)\r\n\r\n        # Update residue\r\n        res = np.linalg.norm(u - true_solution)\r\n        res_array += [res]\r\n    \r\n    # print(\"\\nJacobi solver converged after \", len(res_array), \" iterations.\")\r\n    return u, res_array\r\n\r\ndef gauss_seidel(A, b, initial_guess, true_solution, tol):\r\n    \"\"\" Solves the algebraic system A*x=b using a Gauss-Seidel iterative solver.\r\n\r\n    Parameters\r\n    ----------\r\n    A : array\r\n        Matrix A corresponding to the system A*x = b.\r\n    b : array\r\n        Column vector b corresponding to the system A*x = b.\r\n    initial_guess : array, optional\r\n        Initial solution.\r\n    true_solution : array, optional\r\n        Used for residual calculation\r\n    tol : float, optional\r\n        Convergence tolerance.\r\n\r\n    Returns\r\n    -------\r\n    x : array\r\n        Solution vector corresponding to A*x = b.\r\n    residue : array\r\n        Residue array.\r\n    \"\"\"\r\n    print(\"Initializing Gauss-Seidel Solver\", end='\\r')\r\n\r\n    # Retrieve matrix dimension\r\n    n, m = A.shape\r\n\r\n    # Flatten b\r\n    b = b.flatten()\r\n\r\n    # Initialize u\r\n    u = initial_guess.flatten()\r\n    u_true = true_solution.flatten()\r\n\r\n    # Initialize residue\r\n    res = np.linalg.norm(u - true_solution)\r\n    res_array = [res]\r\n\r\n    # Iterate\r\n    while res > tol:\r\n        print(\"Current Iteration and Residue: {:06d} - {:05.4E}\".format(len(res_array), res), end='\\r')\r\n        \r\n        for i in range(n):\r\n            sum_factor = 0\r\n            for j in range(i):\r\n                sum_factor += A[i, j] * u[j]\r\n            \r\n            for j in range(i + 1, n):\r\n                sum_factor += A[i, j] * u[j]\r\n\r\n            u[i] = (1/A[i, i]) * (b[i] - sum_factor)\r\n        \r\n        res = np.linalg.norm(u - true_solution)\r\n        res_array += [res]\r\n    \r\n    print(\"\\nGauss-Seidel solver converged after \", len(res_array), \" iterations.\")\r\n    return u, res_array\r\n\r\n@jit(nopython=True)\r\ndef gauss_seidel_compiled(A, b, initial_guess, true_solution, tol):\r\n    \"\"\" Solves the algebraic system A*x=b using a Gauss-Seidel iterative solver.\r\n    This function takes advantage of just in time compilation to speed up\r\n    evaluations.\r\n\r\n    Parameters\r\n    ----------\r\n    A : array\r\n        Matrix A corresponding to the system A*x = b.\r\n    b : array\r\n        Column vector b corresponding to the system A*x = b.\r\n    initial_guess : array, optional\r\n        Initial solution.\r\n    true_solution : array, optional\r\n        Used for residual calculation\r\n    tol : float, optional\r\n        Convergence tolerance.\r\n\r\n    Returns\r\n    -------\r\n    x : array\r\n        Solution vector corresponding to A*x = b.\r\n    residue : array\r\n        Residue array.\r\n    \"\"\"\r\n    # Retrieve matrix dimension\r\n    n, m = A.shape\r\n\r\n    # Flatten b\r\n    b = b.flatten()\r\n\r\n    # Initialize u\r\n    u = initial_guess.flatten()\r\n    u_true = true_solution.flatten()\r\n\r\n    # Initialize residue\r\n    res = np.linalg.norm(u - true_solution)\r\n    res_array = [res]\r\n\r\n    # Iterate\r\n    while res > tol:\r\n        for i in range(n):\r\n            sum_factor = 0\r\n            for j in range(i):\r\n                sum_factor += A[i, j] * u[j]\r\n            \r\n            for j in range(i + 1, n):\r\n                sum_factor += A[i, j] * u[j]\r\n\r\n            u[i] = (1/A[i, i]) * (b[i] - sum_factor)\r\n\r\n        # Update residue\r\n        res = np.linalg.norm(u - true_solution)\r\n        res_array += [res]\r\n\r\n    return u, res_array\r\n\r\ndef gauss_seidel_sparse(A, b, initial_guess, true_solution, tol):\r\n    \"\"\" Solves the algebraic system A*x=b using a Gauss-Seidel iterative solver.\r\n    This function makes use of the sparsity of the A matrix to speed up\r\n    function evaluation.\r\n\r\n    Parameters\r\n    ----------\r\n    A : array\r\n        Matrix A corresponding to the system A*x = b. Should be in sparse\r\n        format.\r\n    b : array\r\n        Column vector b corresponding to the system A*x = b.\r\n    initial_guess : array, optional\r\n        Initial solution.\r\n    true_solution : array, optional\r\n        Used for residual calculation\r\n    tol : float, optional\r\n        Convergence tolerance.\r\n\r\n    Returns\r\n    -------\r\n    x : array\r\n        Solution vector corresponding to A*x = b.\r\n    residue : array\r\n        Residue array.\r\n    \"\"\"\r\n    # print(\"Initializing Gauss-Seidel Sparse Solver\", end='\\r')\r\n    # Retrieve matrix dimension\r\n    n, m = A.shape\r\n    \r\n    # Compute L by extracting lower triangular matrix from A\r\n    L = tril(A)\r\n    \r\n    # Compute U by extracting upper triangular matrix from A\r\n    U = triu(A, k=1)\r\n\r\n    # Compute L^-1\r\n    L_inverse = sparse_inv(csc_matrix(L))\r\n\r\n    # Compute (L^-1)*b\r\n    L_inverse_dot_b =  L_inverse.dot(b.flatten())\r\n\r\n    # Compute -(L^-1)*U\r\n    L_inverse_dot_U = L_inverse.dot(U)\r\n\r\n    # Initialize u\r\n    u = initial_guess.flatten()\r\n    u_true = true_solution.flatten()\r\n\r\n    # Initialize residue\r\n    res = np.linalg.norm(u - true_solution)\r\n    res_array = [res]\r\n\r\n    # Iterate\r\n    while res > tol:\r\n        # print(\"Current Iteration and Residue: {:06d} - {:05.4E}\".format(len(res_array), res), end='\\r')\r\n\r\n        # Update u\r\n        u = L_inverse_dot_b - L_inverse_dot_U.dot(u)\r\n\r\n        # Update residue\r\n        res = np.linalg.norm(u - true_solution)\r\n        res_array += [res]\r\n    \r\n    # print(\"\\nGauss-Seidel solver converged after \", len(res_array), \" iterations.\")\r\n    return u, res_array\r\n\r\ndef sor(A, b, initial_guess, true_solution, tol, w):\r\n    \"\"\" Solves the algebraic system A*x=b using a Gauss-Seidel Successive\r\n    Over Relaxation iterative solver.\r\n\r\n    Parameters\r\n    ----------\r\n    A : array\r\n        Matrix A corresponding to the system A*x = b.\r\n    b : array\r\n        Column vector b corresponding to the system A*x = b.\r\n    initial_guess : array, optional\r\n        Initial solution.\r\n    true_solution : array, optional\r\n        Used for residual calculation\r\n    tol : float, optional\r\n        Convergence tolerance.\r\n    w : float\r\n        Relaxation parameter.\r\n\r\n    Returns\r\n    -------\r\n    x : array\r\n        Solution vector corresponding to A*x = b.\r\n    residue : array\r\n        Residue array.\r\n    \"\"\"\r\n    print(\"Initializing Gauss-Seidel SOR Solver\", end='\\r')\r\n\r\n    # Retrieve matrix dimension\r\n    n, m = A.shape\r\n\r\n    # Flatten b\r\n    b = b.flatten()\r\n\r\n    # Initialize u\r\n    u = initial_guess.flatten()\r\n    u_true = true_solution.flatten()\r\n\r\n    # Initialize residue\r\n    res = np.linalg.norm(u - true_solution)\r\n    res_array = [res]\r\n\r\n    # Iterate\r\n    while res > tol:\r\n        print(\"Current Iteration and Residue: {:06d} - {:05.4E}\".format(len(res_array), res), end='\\r')\r\n        \r\n        for i in range(n):\r\n            sum_factor = 0\r\n            for j in range(i):\r\n                sum_factor += A[i, j] * u[j]\r\n            \r\n            for j in range(i + 1, n):\r\n                sum_factor += A[i, j] * u[j]\r\n\r\n            u[i] = (1-w)*u[i] + w*(1/A[i, i]) * (b[i] - sum_factor)\r\n        \r\n        res = np.linalg.norm(u - true_solution)\r\n        res_array += [res]\r\n    \r\n    print(\"\\nGauss-Seidel Successive Over Relaxation solver converged after \", len(res_array), \" iterations.\")\r\n    return u, res_array\r\n\r\n@jit(nopython=True)\r\ndef sor_compiled(A, b, initial_guess, true_solution, tol, w):\r\n    \"\"\" Solves the algebraic system A*x=b using a Gauss-Seidel Successive\r\n    Over Relaxation iterative solver. This function takes advantage of just\r\n    in time compilation to speed up evaluations.\r\n\r\n    Parameters\r\n    ----------\r\n    A : array\r\n        Matrix A corresponding to the system A*x = b.\r\n    b : array\r\n        Column vector b corresponding to the system A*x = b.\r\n    initial_guess : array, optional\r\n        Initial solution.\r\n    true_solution : array, optional\r\n        Used for residual calculation\r\n    tol : float, optional\r\n        Convergence tolerance.\r\n    w : float\r\n        Relaxation parameter.\r\n\r\n    Returns\r\n    -------\r\n    x : array\r\n        Solution vector corresponding to A*x = b.\r\n    residue : array\r\n        Residue array.\r\n    \"\"\"\r\n    # Retrieve matrix dimension\r\n    n, m = A.shape\r\n\r\n    # Flatten b\r\n    b = b.flatten()\r\n\r\n    # Initialize u\r\n    u = initial_guess.flatten()\r\n    u_true = true_solution.flatten()\r\n\r\n    # Initialize residue\r\n    res = np.linalg.norm(u - true_solution)\r\n    res_array = [res]\r\n\r\n    # Iterate\r\n    while res > tol:\r\n        for i in range(n):\r\n            sum_factor = 0\r\n            for j in range(i):\r\n                sum_factor += A[i, j] * u[j]\r\n            \r\n            for j in range(i + 1, n):\r\n                sum_factor += A[i, j] * u[j]\r\n\r\n            u[i] = (1-w)*u[i] + w*(1/A[i, i]) * (b[i] - sum_factor)\r\n        \r\n        res = np.linalg.norm(u - true_solution)\r\n        res_array += [res]\r\n\r\n    return u, res_array\r\n\r\ndef sor_sparse(A, b, initial_guess, true_solution, tol, w):\r\n    \"\"\" Solves the algebraic system A*x=b using a Gauss-Seidel Successive\r\n    Over Relaxation iterative solver. This function makes use of the sparsity\r\n    of the A matrix to speed up function evaluation.\r\n\r\n    Parameters\r\n    ----------\r\n    A : array\r\n        Matrix A corresponding to the system A*x = b. Should be in sparse\r\n        format.\r\n    b : array\r\n        Column vector b corresponding to the system A*x = b.\r\n    initial_guess : array, optional\r\n        Initial solution.\r\n    true_solution : array, optional\r\n        Used for residual calculation\r\n    tol : float, optional\r\n        Convergence tolerance. \r\n    w : float\r\n        Relaxation parameter.\r\n\r\n    Returns\r\n    -------\r\n    x : array\r\n        Solution vector corresponding to A*x = b.\r\n    residue : array\r\n        Residue array.\r\n    \"\"\"\r\n    # print(\"Initializing Gauss-Seidel Successive Over Relaxation Sparse Solver\", end='\\r')\r\n    # Retrieve matrix dimension\r\n    n, m = A.shape\r\n\r\n    # Compute D by extracting main diagonal from A\r\n    main_diagonal = A.diagonal()\r\n    D = dia_matrix(([main_diagonal], [0]), shape=(n, n), dtype=np.float64)\r\n\r\n    # Compute L by extracting lower triangular matrix from A\r\n    L = tril(A, k=-1)\r\n    \r\n    # Compute U by extracting upper triangular matrix from A\r\n    U = triu(A, k=1)\r\n\r\n    # Compute (D + w*L)^-1\r\n    D_plus_w_L_inverse = sparse_inv(csc_matrix(D + w*L))\r\n\r\n    # Compute w*b\r\n    w_b =  w*b.flatten()\r\n\r\n    # Compute w*U + (w-1)*D\r\n    w_U_plus_w_minus_1_D = w*U + (w-1)*D\r\n\r\n    # Compute ((D + w*L)^-1)*(w*U + (w-1)*D)\r\n    D_plus_w_L_inverse_dot_w_U_plus_w_minus_1_D = D_plus_w_L_inverse.dot(w_U_plus_w_minus_1_D)\r\n\r\n    # Compute ((D + w*L)^-1)*w*b0\r\n    D_plus_w_L_inverse_dot_w_b = D_plus_w_L_inverse.dot(w_b)\r\n\r\n    # Initialize u\r\n    u = initial_guess.flatten()\r\n    u_true = true_solution.flatten()\r\n\r\n    # Initialize residue\r\n    res = np.linalg.norm(u - true_solution)\r\n    res_array = [res]\r\n\r\n    # Iterate\r\n    while res > tol:\r\n        # print(\"Current Iteration and Residue: {:06d} - {:05.4E}\".format(len(res_array), res), end='\\r')\r\n\r\n        # Update u\r\n        u = D_plus_w_L_inverse_dot_w_b - D_plus_w_L_inverse_dot_w_U_plus_w_minus_1_D.dot(u)\r\n\r\n        # Update residue\r\n        res = np.linalg.norm(u - true_solution)\r\n        res_array += [res]\r\n    \r\n    # print(\"\\nGauss-Seidel Successive Over Relaxation solver converged after \", len(res_array), \" iterations.\")\r\n    return u, res_array\r\n", "meta": {"hexsha": "8bab74e217985a7ffe807bfd31812e1d314af127", "size": 30821, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_system_solver.py", "max_stars_repo_name": "giovaniceotto/ME4233", "max_stars_repo_head_hexsha": "278152eaea4cbb644199a84938d0bb9a66842cb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_system_solver.py", "max_issues_repo_name": "giovaniceotto/ME4233", "max_issues_repo_head_hexsha": "278152eaea4cbb644199a84938d0bb9a66842cb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_system_solver.py", "max_forks_repo_name": "giovaniceotto/ME4233", "max_forks_repo_head_hexsha": "278152eaea4cbb644199a84938d0bb9a66842cb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-31T01:17:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T01:17:48.000Z", "avg_line_length": 30.4856577646, "max_line_length": 113, "alphanum_fraction": 0.573213069, "include": true, "reason": "import numpy,from scipy,from numba", "num_tokens": 7592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661028358093, "lm_q2_score": 0.896251377983158, "lm_q1q2_score": 0.8549934342158171}}
{"text": "\"\"\"\nStatic methods that all take a float parameter meant to be between 0 and 1 (but can be any), and return a float between\n0 and 1. Meant to be used as fill color value in order to have custom shadings. Some return a list of 3 floats\nfor rgb values.\n\"\"\"\nimport math\nfrom typing import Callable\n\nfrom scipy.stats import norm\n\n\n# import numpy as np\n\n\ndef _clamp(x: float, lower_limit: float = 0.0, upper_limit: float = 1.0) -> float:\n    if x > upper_limit:\n        return upper_limit\n    if x < lower_limit:\n        return lower_limit\n    return x\n\n\ndef zero(ratio: float) -> float:\n    return 0.0\n\n\ndef _power(exponent: float) -> Callable[[float], float]:\n    return lambda x: _clamp(x ** exponent)\n\n\ndef identity(ratio: float) -> float:\n    return _power(1.0)(ratio)\n\n\ndef square(ratio: float) -> float:\n    return _power(2)(ratio)\n\n\ndef cube(ratio: float) -> float:\n    return _power(3)(ratio)\n\n\ndef sinus(ratio: float) -> float:\n    return _clamp(math.sin(2 * ratio / math.pi))\n\n\ndef _gauss(mean: float = 0.5, sd: float = 0.3) -> Callable[[float], float]:\n    return lambda x: norm.cdf(x, mean, sd)\n\n\ndef gauss(ratio: float) -> float:\n    return _gauss()(ratio)\n\n\ndef gauss_heavy(ratio: float) -> float:\n    return _gauss(0.8, 0.4)(ratio)\n\n\ndef _logistic_curve(midpoint: float = 0.5, steepness: float = 1.0, max_value: float = 1.0) -> Callable[[float], float]:\n    return lambda x: max_value / (1 + math.e ** (-steepness * (x - midpoint)))\n\n\ndef logistic_curve(ratio: float) -> float:\n    return _logistic_curve(0.5, 5.0, 1.0)(ratio)\n\n\ndef smooth_step(ratio: float, edge_1: float = 0.0, edge_2: float = 1.0) -> float:\n    x = _clamp((ratio - edge_1) / (edge_2 - edge_1))\n    return x * x * (3 - 2 * x)\n\n\ndef smoother_step(ratio: float, edge_1: float = 0.0, edge_2: float = 1.0) -> float:\n    x = _clamp((ratio - edge_1) / (edge_2 - edge_1))\n    return x * x * x * (x * (x * 6 - 15) + 10)\n\n\ndef general_smooth_step(N, x):\n    x = _clamp(x, 0.0, 1.0)\n    result = 0\n\n    for i in range(N):\n        result += pascal_triangle(-N - 1, i) * pascal_triangle(2 * N + 1, N - i) * math.pow(x, N + i + 1)\n    return result\n\n\ndef pascal_triangle(a, b):\n    result = 1\n    for i in range(b):\n        result *= (a - i) / (i + 1)\n    return result\n", "meta": {"hexsha": "3e645813bff74fc3e31f44e1cdb8ba7fb0833f6c", "size": 2237, "ext": "py", "lang": "Python", "max_stars_repo_path": "interpolation.py", "max_stars_repo_name": "inadicis/geometry-art", "max_stars_repo_head_hexsha": "1af23e3ac90f7e4b426d631368ef2afbfe2451db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-13T00:39:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T00:39:38.000Z", "max_issues_repo_path": "interpolation.py", "max_issues_repo_name": "inadicis/geometry-art", "max_issues_repo_head_hexsha": "1af23e3ac90f7e4b426d631368ef2afbfe2451db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interpolation.py", "max_forks_repo_name": "inadicis/geometry-art", "max_forks_repo_head_hexsha": "1af23e3ac90f7e4b426d631368ef2afbfe2451db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5824175824, "max_line_length": 119, "alphanum_fraction": 0.6285203397, "include": true, "reason": "import numpy,from scipy", "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877675527112, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.8549789432146356}}
{"text": "\n\nfrom scipy.integrate import quad\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\n\n#-----------------------------------\n#INTEGRATION EXAMPLE\n#----------------------------------\n\n#ANTIDEVIATIVE OF x^2--> x^3/3\ndef integrand(x):\n    return x**2 \n\nprint(1/3-0,quad(integrand, 0, 1))\n\n\n\n#-----------------------------------\n#NORMAL DISTIBUTION ENTROPY\n#----------------------------------\n\ns=1; u=0\ndef p(x):\n\treturn np.exp(-0.5*((x-u)/s)**2)/(s*np.sqrt(2*3.1415))\n\ndef I(x): return -p(x)*np.log(p(x))\n\nS=quad(I, -20, 20)\nprint(S, np.log(2*3.1415*np.exp(1)*s)) #,np.exp(1))\n\n\n\n\n\n\n#-----------------------------------\n#KL DIVERGENCE AND CROSS ENTROPY\n#----------------------------------\n\nu1=0; s1=1\nu2=3; s2=1\n\n#INTEGRATION LIMITS\nx1=min(u1,u2)-4*max(s1,s2)\nx2=max(u1,u2)+4*max(s1,s2); print(x1,x2)\n\n#DEFINE TWO NORMAL DISTRIBUTINO\ndef p1(x): return np.exp(-0.5*((x-u1)/s1)**2)/(s1*np.sqrt(2*3.1415))\ndef p2(x): return np.exp(-0.5*((x-u2)/s2)**2)/(s2*np.sqrt(2*3.1415))\n\ndef I_S1(x): return -p1(x)*np.log(p1(x))  \t\t#P1 ENTROPY\ndef I_S2(x): return -p2(x)*np.log(p2(x))  \t\t#P2 ENTROPY\ndef I_CE(x): return -p1(x)*np.log(p2(x))  \t\t#CROSS ENTROPY\ndef I_KL(x): return -p1(x)*np.log(p2(x)/p1(x))  #D_KL\n\ndef plot(KLD,S1,S2,CE):\n\tfig = plt.figure(figsize=(20,12))\n\tax = fig.add_subplot(111)\n\tx=np.linspace(x1,x2,500)\n\tplt.plot(x, p1(x), label=\"p(x)\", linewidth=4)\n\tplt.plot(x, p2(x), label=\"q(x)\", linewidth=4)\n\tplt.plot(x, I_S1(x), label=\"I_S1\", linewidth=4)\n\t# plt.plot(x, I_S2(x), label=\"I_S2\", linewidth=4)\n\tplt.plot(x, I_CE(x), label=\"I_CE\", linewidth=4)\n\tplt.plot(x, I_KL(x), label=\"S1,S2,CE,KLD=\"+str(S1)+' '+str(S2)+' '+str(CE)+' '+str(KLD), linewidth=4)\n\tplt.legend(loc=\"best\")\n\tax.set_xlabel('x')\n\tax.set_ylabel('probablity density function')\n\tplt.show()\n\nS1=round(quad(I_S1, x1, x2)[0],3)\nS2=round(quad(I_S1, x1, x2)[0],3)\nKLD=round(quad(I_KL, x1, x2)[0],3)\nCE=round(quad(I_CE, x1, x2)[0],3)\nprint(CE,S1+KLD)\nplot(KLD,S1,S2,CE)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexit()\n\n#-----------------------------------\n#KL DIVERGENCE: MOVIE \n#----------------------------------\n\nfig = plt.figure(figsize=(20,12))\nax = fig.add_subplot(111)\n\nfor var in [15,1.42,3,4,5,6,7,8,9]:\n\tu1=0; s1=1\n\tu2=0; s2=var\n\n\t#INTEGRATION LIMITS\n\tx1=min(u1,u2)-4*max(s1,s2)\n\tx2=max(u1,u2)+4*max(s1,s2); print(x1,x2)\n\n\t#DEFINE TWO NORMAL DISTRIBUTINO\n\tdef p1(x): return np.exp(-0.5*((x-u1)/s1)**2)/(s1*np.sqrt(2*3.1415))\n\tdef p2(x): return np.exp(-0.5*((x-u2)/s2)**2)/(s2*np.sqrt(2*3.1415))\n\n\t#INTEGRAND\n\tdef I(x): return -p1(x)*np.log(p2(x)/p1(x))\n\n\tdef plot(KLD):\n\n\t\tx=np.linspace(x1,x2,500)\n\t\tax.clear()\n\n\t\tax.plot(x, p1(x), label=\"p(x)\", linewidth=4)\n\t\tax.plot(x, p2(x), label=\"q(x)\", linewidth=4)\n\t\tax.plot(x, I(x), label=\"p(x)log(p(x)/q(x)): KLD=\"+str(KLD), linewidth=4)\n\t\tax.legend(loc=\"best\")\n\t\tax.set_xlabel('x')\n\t\tax.set_ylabel('probablity density function')\n\t\tplt.pause(1)\n\n\n\tKLD=quad(I, x1, x2)[0]\n\tplot(KLD)\n\nplt.show()", "meta": {"hexsha": "9b7bea19597ffdf2d63e619f3db78ced1e094a6b", "size": 2881, "ext": "py", "lang": "Python", "max_stars_repo_path": "ANLY-501-INTRO/LAB10-rf/CODES/EXPLORE-ENTROPY.py", "max_stars_repo_name": "rexarski/ggtown-ds", "max_stars_repo_head_hexsha": "00bbb26e28b4431cf4aeff68ea0b3b9220af0b1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ANLY-501-INTRO/LAB10-rf/CODES/EXPLORE-ENTROPY.py", "max_issues_repo_name": "rexarski/ggtown-ds", "max_issues_repo_head_hexsha": "00bbb26e28b4431cf4aeff68ea0b3b9220af0b1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ANLY-501-INTRO/LAB10-rf/CODES/EXPLORE-ENTROPY.py", "max_forks_repo_name": "rexarski/ggtown-ds", "max_forks_repo_head_hexsha": "00bbb26e28b4431cf4aeff68ea0b3b9220af0b1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1838235294, "max_line_length": 102, "alphanum_fraction": 0.5598750434, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877684006775, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.8549789394055217}}
{"text": "import numpy as np\n\ndef func1(x):\n    # function f(x)= 10 + sum_i(-x_i^2)\n    # for 2D: f(x)= 10 - x1^2 - x2^2\n    return 10 + np.sum(-1*np.power(x, 2), axis=1)\n  \ndef mc_integrate(func, a, b, dim, n = 1000):\n    # Monte Carlo integration of given function over domain from a to b (for each parameter)\n    # dim: dimensions of function\n    \n    x_list = np.random.uniform(a, b, (n, dim))\n    print(x_list)\n    y = func(x_list)\n    print(y)\n    \n    y_mean =  y.sum()/len(y)\n    domain = np.power(b-a, dim)\n    \n    integ = domain * y_mean\n    \n    return integ\n\n# Examples\nprint(\"For f(x)= 10 - x1\\u00b2 - x2\\u00b2, integrated from -2 to 2 (for all x's)\")\nprint(f\"Monte Carlo solution for : {mc_integrate(func1, -2, 2, 2, 1000000): .3f}\")\nprint(f\"Analytical solution: 117.333\")\n\nprint(\"For f(x)= 10 - x1\\u00b2 - x2\\u00b2 - x3\\u00b2, integrated from -2 to 2 (for all x's)\")\nprint(f\"Monte Carlo solution: {mc_integrate(func1, -2, 2, 3, 1000000): .3f}\")\nprint(f\"Analytical solution: 384.000\")", "meta": {"hexsha": "c3bc7e7139775c629bdb118a7828dc37ff1454ba", "size": 989, "ext": "py", "lang": "Python", "max_stars_repo_path": "test.py", "max_stars_repo_name": "abhinavchawla/no-save-rrt", "max_stars_repo_head_hexsha": "dc5e5c37aa6ca1de6459a7676a49d211e63cff0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test.py", "max_issues_repo_name": "abhinavchawla/no-save-rrt", "max_issues_repo_head_hexsha": "dc5e5c37aa6ca1de6459a7676a49d211e63cff0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test.py", "max_forks_repo_name": "abhinavchawla/no-save-rrt", "max_forks_repo_head_hexsha": "dc5e5c37aa6ca1de6459a7676a49d211e63cff0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9032258065, "max_line_length": 93, "alphanum_fraction": 0.619817998, "include": true, "reason": "import numpy", "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561721629776, "lm_q2_score": 0.8824278741843884, "lm_q1q2_score": 0.8549456923922001}}
{"text": "import numpy as np\n\ndef heuristic_aux(x, y, x_g, y_g, name):\n  \"\"\"Admissible heuristics\n\n  Parameters\n  ----------\n  x, y: int\n    state coordinate\n  x_g, y_g: int\n    goal coordinate\n  name: str\n    heuristic function name\n\n  Return\n  ------\n  Float:\n    Corresponding heuristic value for a single coordinate\n  \"\"\"\n  if name == 'tiles-out':\n    return x != x_g or y != y_g\n  elif name == 'manhattan':\n    return abs(x-x_g) + abs(y-y_g)\n  elif name == 'euclidean':\n    return np.sqrt((x-x_g) ** 2 + (y-y_g) ** 2)\n  elif name == 'uniform-cost':\n    return 0\n\ndef heuristic(goal, state, name='euclidean'):\n  \"\"\"Heuristic function\n\n  Parameters\n  ----------\n  goal: list\n    Puzzle state we want to achieve\n  state: list\n    Current Puzzle state\n  name: str (Default: 'euclidean')\n    Name of heuristic function to use ∈ ['euclidean', 'manhattan', 'tiles-out', 'uniform-cost']\n\n  Returns\n  -------\n  One of\n    'Tiles-out': float\n      Number of tiles in the wrong position\n    'Manhattan': float\n      Sum of the horizontal and vertical distances between,\n      current position and desired position, i.e. ∑ |state - goal|\n    'Euclidean': float\n      Sum of the distance between tiles\n      ∑ √(x - x_g)² + (y - y_g)²\n  \"\"\"\n  size = int(np.sqrt(len(goal)))\n\n  coord_goal  = np.zeros((size ** 2, 2)) # in index i coordinates of tile i in goal\n  coord_state = np.zeros((size ** 2, 2)) # in index i coordinates of tile i in state\n  for x in range (size):\n    for y in range (size):\n      coord_goal[ goal[ x * size + y]] = [x, y]\n      coord_state[state[x * size + y]] = [x, y]\n\n  return np.sum([heuristic_aux(*coord_state[i], *coord_goal[i], name) for i in range(size ** 2)])\n", "meta": {"hexsha": "2fa96a8f26d72c05eb746cb6ff3b79ef5db53163", "size": 1673, "ext": "py", "lang": "Python", "max_stars_repo_path": "core/heuristics.py", "max_stars_repo_name": "mtrazzi/npuzzle", "max_stars_repo_head_hexsha": "25504817540605ba58c453d63ea5172b6b79b072", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/heuristics.py", "max_issues_repo_name": "mtrazzi/npuzzle", "max_issues_repo_head_hexsha": "25504817540605ba58c453d63ea5172b6b79b072", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/heuristics.py", "max_forks_repo_name": "mtrazzi/npuzzle", "max_forks_repo_head_hexsha": "25504817540605ba58c453d63ea5172b6b79b072", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5555555556, "max_line_length": 97, "alphanum_fraction": 0.6156604901, "include": true, "reason": "import numpy", "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561667674653, "lm_q2_score": 0.8824278772763472, "lm_q1q2_score": 0.8549456906267131}}
{"text": "from matplotlib import pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport math\nimport scipy.stats as stats\n\nfrom .. import samp\n\n\ndef samp_size(s_p, width, alpha):\n    \"\"\"\n    Input: s_p (sample proportion), width, alpha\n    Output: Estimated sample size\n    \"\"\"\n    z_cv = stats.norm.ppf(1 - alpha / 2)\n    return (z_cv * math.sqrt(s_p * (1 - s_p)) / width) ** 2\n\n\ndef con_level(s_p, n, alpha, show=True, Wilson=False, N=False, correction=True):\n    \"\"\"\n    Caution: np̂ > 5 and n(1 - p̂) > 5\n    Input: s_p, n, alpha, show=True, Wilson=False, N=False, correction=True\n    Output: {\"lat\": lat, \"lcl\": lcl, \"ucl\": ucl, \"z_cv\": z_cv}\n\n    Note:\n        z_cv = stats.norm.ppf(1 - alpha / 2)\n        lat = z_cv * math.sqrt(s_p * (1 - s_p)/n)\n        or for Wilson: lat = z_cv * math.sqrt(s_p * (1 - s_p)/(n + 4))\n\n    Just in case:\n    if there is no need for correction, but is is corrected\n    go through 'lat' and do:\n        lcl = s_p - lat\n        ucl = s_p + lat\n    \"\"\"\n    con_coef = 1 - alpha\n    z_cv = stats.norm.ppf(1 - alpha / 2)\n    if not Wilson and not samp.check5(n, s_p):\n        print('Not satisfying np̂ > 5 and n(1 - p̂) > 5...')\n    if Wilson:\n        # make sure that you have arrange s_p to (x + 2) / (n + 4)\n        lat = z_cv * math.sqrt(s_p * (1 - s_p)/(n + 4))\n    else:\n        lat = z_cv * math.sqrt(s_p * (1 - s_p)/n)\n\n    lcl = s_p - lat\n    ucl = s_p + lat\n\n    if N:\n        if n / N > 0.5 and correction:\n            print(\"Corrected...\")\n            fpcf = math.sqrt((N - n)/(N - 1))\n            lcl = s_p - lat * fpcf\n            ucl = s_p + lat * fpcf\n        elif correction:\n            print(\"Corrected...\")\n            fpcf = math.sqrt((N - n)/(N - 1))\n            lcl = s_p - lat * fpcf\n            ucl = s_p + lat * fpcf\n        if lcl < 0:\n            lcl = 0\n        if ucl < 0:\n            ucl = 0\n        result = f\"\"\"{con_coef * 100:.1f}% Confidence Interval: N [{lcl:.4f}, {ucl:.4f}] = [{N * lcl:.4f}, {N * ucl:.4f}]\np̂: {s_p:.4f}\nSample Size: {n}\nz_cv (Critical value): {z_cv:.4f}\n    \"\"\"\n    else:\n        if lcl < 0:\n            lcl = 0\n        if ucl < 0:\n            ucl = 0\n        result = f\"\"\"{con_coef * 100:.1f}% Confidence Interval: [{lcl:.4f}, {ucl:.4f}]\np̂: {s_p:.4f}\nSample Size: {n}\nz_cv (Critical value): {z_cv:.4f}\n    \"\"\"\n    if show:\n        print(result)\n    return {\"lat\": lat, \"lcl\": lcl, \"ucl\": ucl, \"z_cv\": z_cv}\n\n\ndef rejection_region_method(s_p, h0_p, nsize, alpha, option='left', precision=4, show=True, ignore=False):\n    \"\"\"\n    Input: s_p, h0_p, nsize, alpha, option='left', precision=4, show=True, ignore=False\n    Output: \n        if opt == 't':\n            return p_l, p_u\n        else:\n            return p_c\n    \"\"\"\n    opt = option.lower()[0]\n    if not samp.check5(nsize, h0_p):\n        print('Not satisfying np_0 > 5 and n(1 - p_0) > 5...')\n    if opt == 't':\n        option = 'Two-Tail Test'\n        z_cv = stats.norm.ppf(1 - alpha/2)\n        p_u = h0_p + z_cv * math.sqrt(h0_p * (1 - h0_p)/nsize)\n        p_l = h0_p - z_cv * math.sqrt(h0_p * (1 - h0_p)/nsize)\n        flag = s_p < p_l or s_p > p_u\n        if not ignore:\n            result = f'''======= The Rejection Region Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nz (Critical value) = {z_cv:.{precision}f}\n\nUsing {option}:\np̂ =  {s_p:.{precision}f}\np_l (Lower bound for the critical value) = {p_l:.{precision}f}\np_u (Upper bound for the critical value) = {p_u:.{precision}f}\nReject H_0 → {flag}\n            '''\n        else:\n            result = f'''======= The Rejection Region Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nz (Critical value) = {z_cv:.{precision}f}\n\nUsing {option}:\np_l (Lower bound for the critical value) = {p_l:.{precision}f}\np_u (Upper bound for the critical value) = {p_u:.{precision}f}\n            '''\n\n    else:\n        z_cv = stats.norm.ppf(1 - alpha)\n        if opt == 'l':\n            # left tail\n            option = 'One-Tail Test (left tail)'\n            p_c = h0_p - z_cv * math.sqrt(h0_p * (1 - h0_p)/nsize)\n            flag = s_p < p_c\n        elif opt == 'r':\n            option = 'One-Tail Test (right tail)'\n            p_c = h0_p + z_cv * math.sqrt(h0_p * (1 - h0_p)/nsize)\n            flag = s_p > p_c\n        if not ignore:\n            result = f'''======= The Rejection Region Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nz (Critical value) = {z_cv:.{precision}f}\n\nUsing {option}:\np̂ =  {s_p:.{precision}f}\np_c (Critical value) = {p_c:.{precision}f}\nReject H_0 → {flag}\n            '''\n        else:\n            result = f'''======= The Rejection Region Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nz (Critical value) = {z_cv:.{precision}f}\n\nUsing {option}:\np_c (Critical value) = {p_c:.{precision}f}\n            '''\n\n    if show:\n        print(result)\n\n    if opt == 't':\n        return p_l, p_u\n    else:\n        return p_c\n\n\ndef testing_statistic_method(s_p, h0_p, nsize, alpha, option='left', precision=4, ignore=False):\n    \"\"\"\n    Input: s_p, h0_p, nsize, alpha, option='left', precision=4, ignore=False\n    Output: z_stats, z_cv\n    \"\"\"\n    opt = option.lower()[0]\n    z_stats = (s_p - h0_p)/math.sqrt(h0_p * (1 - h0_p)/nsize)\n    if not samp.check5(nsize, h0_p):\n        print('Not satisfying np_0 > 5 and n(1 - p_0) > 5...')\n\n    if opt == 't':\n        z_cv = stats.norm.ppf(1 - alpha / 2)\n        option = 'Two-Tail Test'\n        flag = z_stats < -z_cv or z_stats > z_cv\n\n        if not ignore:\n            result = f'''======= Testing Statistic Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nz_cv (Critical value) = {z_cv:.{precision}f}\n\nUsing {option}:\nz_stats (Observed value) =  {z_stats:.{precision}f}\n-z_cv (Lower bound for the critical value) = {-z_cv:.{precision}f}\nz_cv (Upper bound for the critical value) = {z_cv:.{precision}f}\nReject H_0 → {flag}\n            '''\n        else:\n            result = f'''======= Testing Statistic Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nz_cv (Critical value) = {z_cv:.{precision}f}\n\nUsing {option}:\n-z_cv (Lower bound for the critical value) = {-z_cv:.{precision}f}\nz_cv (Upper bound for the critical value) = {z_cv:.{precision}f}\n            '''\n\n    else:\n        z_cv = stats.norm.ppf(1 - alpha)\n        if opt == 'l':\n            # left tail\n            option = 'One-Tail Test (left tail)'\n            z_cv = -z_cv\n            flag = z_stats < z_cv\n        elif opt == 'r':\n            option = 'One-Tail Test (right tail)'\n            flag = z_stats > z_cv\n\n        if not ignore:\n            result = f'''======= Testing Statistic Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nz_cv (Critical value) = {z_cv:.{precision}f}\n\nUsing {option}:\nz_stats (Observed value) =  {z_stats:.{precision}f}\nz_cv (Critical value) = {z_cv:.{precision}f}\nReject H_0 → {flag}\n            '''\n\n        else:\n            result = f'''======= Testing Statistic Method =======\nSignificant Level (alpha) = {alpha:.{precision}f}\nz_cv (Critical value) = {z_cv:.{precision}f}\n\nUsing {option}:\nz_cv (Critical value) = {z_cv:.{precision}f}\n            '''\n\n    print(result)\n\n    return z_stats, z_cv\n\n\ndef inter_p_value(p_value):\n    # interpretation\n    if p_value >= 0 and p_value < 0.01:\n        inter_p = 'Overwhelming Evidence'\n    elif p_value >= 0.01 and p_value < 0.05:\n        inter_p = 'Strong Evidence'\n    elif p_value >= 0.05 and p_value < 0.1:\n        inter_p = 'Weak Evidence'\n    elif p_value >= .1:\n        inter_p = 'No Evidence'\n    return inter_p\n\n\ndef p_value_method(s_p, h0_p, nsize, alpha, option='left', precision=4):\n    \"\"\"\n    Input: s_p, h0_p, nsize, alpha, option='left', precision=4\n    Output: z_cv, z_stats, p_value\n    \"\"\"\n    opt = option.lower()[0]\n    z_stats = (s_p - h0_p)/math.sqrt(h0_p * (1 - h0_p)/nsize)\n    if not samp.check5(nsize, h0_p):\n        print('Not satisfying np_0 > 5 and n(1 - p_0) > 5...')\n    if opt == 't':\n        # two-tail test\n        option = 'Two-Tail Test'\n        if s_p > h0_p:\n            p_value = stats.norm.sf(z_stats) * 2\n        else:\n            p_value = stats.norm.cdf(z_stats) * 2\n\n        z_cv = stats.norm.ppf(1 - alpha/2)\n        flag = p_value < alpha\n        sub_result = f'''Using {option}:\nDifference = {s_p - h0_p}\nz_cv (Critical value) = {-z_cv:.{precision}f}, {z_cv:.{precision}f}\nz_stats (Observed value) = {z_stats:.{precision}f}\np-value = {p_value:.{precision}f} ({inter_p_value(p_value)})\nReject H_0 → {flag}\n        '''\n    else:\n        if opt == 'l':\n            option = 'One-Tail Test (left tail)'\n            p_value = stats.norm.cdf(z_stats)\n            z_cv = -stats.norm.ppf(1 - alpha)\n        elif opt == 'r':\n            option = 'One-Tail Test (right tail)'\n            p_value = stats.norm.sf(z_stats)\n            z_cv = stats.norm.ppf(1 - alpha)\n        flag = p_value < alpha\n        sub_result = f'''Using {option}:\nDifference = {s_p - h0_p}\nz_cv (Critical value) = {z_cv:.{precision}f}\nz_stats (Observed value) = {z_stats:.{precision}f}\np-value = {p_value:.{precision}f} ({inter_p_value(p_value)})\nReject H_0 → {flag}\n        '''\n\n    result = f\"\"\"======= p-value Method =======\np̂ = {s_p:.{precision}f}\nNumber of Observation = {nsize:.{precision}f}\nHypothesized Proportion (H0 Mean) = {h0_p:.{precision}f}\nSignificant Level (alpha) = {alpha:.{precision}f}\n\n\"\"\" + sub_result\n\n    print(result)\n\n    return z_cv, z_stats, p_value\n", "meta": {"hexsha": "a1bec49b42eedcd38fa1225cd15b15dacf58bb79", "size": 9402, "ext": "py", "lang": "Python", "max_stars_repo_path": "mgt2001/hyp/p.py", "max_stars_repo_name": "derekdylu/mgt2001", "max_stars_repo_head_hexsha": "b228d5e75e75a2f3f170e35db1bea999b765bec8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-03-01T18:31:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T12:10:22.000Z", "max_issues_repo_path": "mgt2001/hyp/p.py", "max_issues_repo_name": "derekdylu/mgt2001", "max_issues_repo_head_hexsha": "b228d5e75e75a2f3f170e35db1bea999b765bec8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-18T09:30:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-18T09:30:27.000Z", "max_forks_repo_path": "mgt2001/hyp/p.py", "max_forks_repo_name": "derekdylu/mgt2001", "max_forks_repo_head_hexsha": "b228d5e75e75a2f3f170e35db1bea999b765bec8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-11T07:58:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-03T13:49:24.000Z", "avg_line_length": 31.1324503311, "max_line_length": 121, "alphanum_fraction": 0.5507338864, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561703644737, "lm_q2_score": 0.8824278695464501, "lm_q1q2_score": 0.854945686311655}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nx = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]\ny = [0.99, 2.3, 2.9, 4.01, 4.85, 5.80, 7.2]\nsize = 7\n\nplt.plot(x, y, 'go')\nplt.ylabel('some numbers')\n\n# Algorithm goes here\nxsum = 0\nx2sum = 0\nysum = 0\nxysum = 0    \nslope = 0\nintercept = 0\n\nfor i in range(size):\n    xsum = xsum + x[i]\n    ysum = ysum + y[i]\n    x2sum = x2sum + x[i]**2\n    xysum = xysum + x[i] * y[i]\n\nslope = (size * xysum - xsum * ysum) / (size * x2sum - xsum * xsum)\nintercept = (x2sum * ysum - xsum * xysum) / (x2sum * size - xsum * xsum)\ny_fit = []\n\nfor i in range(size):\n    y_fit.append(slope * x[i] + intercept)\n\nplt.plot(x, y_fit, 'r')\n\nplt.show()\n\n\n#t = np.arange(0., 5., 0.2)\n#plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')\n#plt.show()\n\n", "meta": {"hexsha": "a46d28d87cb7294ec6799ef3a5e1d9e560e7d084", "size": 764, "ext": "py", "lang": "Python", "max_stars_repo_path": "line_fitting.py", "max_stars_repo_name": "anicicn84/Least-squares-line-fitting-algorithm", "max_stars_repo_head_hexsha": "b86eec4f8c8f3f10547f7bebbcf0ef5dc36ad0f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "line_fitting.py", "max_issues_repo_name": "anicicn84/Least-squares-line-fitting-algorithm", "max_issues_repo_head_hexsha": "b86eec4f8c8f3f10547f7bebbcf0ef5dc36ad0f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "line_fitting.py", "max_forks_repo_name": "anicicn84/Least-squares-line-fitting-algorithm", "max_forks_repo_head_hexsha": "b86eec4f8c8f3f10547f7bebbcf0ef5dc36ad0f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6341463415, "max_line_length": 72, "alphanum_fraction": 0.5484293194, "include": true, "reason": "import numpy", "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561694652215, "lm_q2_score": 0.8824278649085118, "lm_q1q2_score": 0.8549456810246346}}
{"text": "import numpy as np \r\n\r\ndef CorBrownian(mu, E, sampleSize):\r\n    # Algorithm generates samples of increments from a correlated Brownian motion with a given mean and Variance-Covariance matrix (E). \r\n    # The algorithm uses the fact that if you have n independent brownian motions, the samples given by \"mu+ C*Z\" are distributed as N(mu,E), where mu is the vector of means and C is the square root of the Variance-Covariance matrix.\r\n    # For calculating the square root of the VarCovar matrix, the Cholesky decomposition is implemented.\r\n    # Arguments:\r\n    #     mu        = Array with n elements containing the mean of each BM  \r\n    #     E         = n x n numpy array with the Variance-Covariance matrix \r\n    #    sampleSize = integer representing the number of samples\r\n    # \r\n    # Returns:\r\n    #     sampleSize x n numpy array containing sampled increments for the correlated Brownian motion\r\n    #      \r\n    # Note: \r\n    #  The algorithm is not optimized for speed and no testing of inputs is implemented. If this would be usefull to you, let us know and we can extend the code.\r\n    #\r\n    # Example of use:\r\n    # import numpy as np \r\n    # mu = [1,2]\r\n    # VarCovar = np.matrix('1,0.8; 0.8,3')\r\n    # sampleSize = 5\r\n    # out = CorBrownian(mu,VarCovar, sampleSize)\r\n    # > [ 2.83211068  4.50021193]\r\n    #   [ 0.26392619  1.56450446]\r\n    #   [-0.25928109  0.97167124]\r\n    #   [ 1.52038489  1.76274556]]\r\n    #\r\n \r\n    def Cholesky(X):\r\n        # Cholesky–Banachiewicz algorithm decomposes a Hermitian matrix into a product of a lower triangular matrix and its conjugate transpose.\r\n        # Arguemnts:\r\n        #    X = n x n ndarray representing a Hermitian matrix that the user wants to decompose\r\n        # Returns:\r\n        #    n x n ndarray lower triangular matrix such that the matrix product between it and its conjugate transpose returns X\r\n        # \r\n        # More info on: https://en.wikipedia.org/wiki/Cholesky_decomposition#The_Cholesky.E2.80.93Banachiewicz_and_Cholesky.E2.80.93Crout_algorithms\r\n\r\n        L = np.zeros_like(X)\r\n        n = X.shape[0]\r\n\r\n        for i in range(0, n):\r\n            for j in range(0, i+1):\r\n                sum = 0\r\n                for k in range(0, j):\r\n                    sum = sum+ L[i,k]*L[j,k]\r\n                if (i==j):\r\n                    L[i,j] = np.sqrt(X[i,i]-sum)\r\n                else:\r\n                    L[i,j] = 1.0/L[j,j] * (X[i,j]-sum)\r\n        return L\r\n\r\n    dim = E.shape[0]                                         # Guess the number of Brownian motions (dimension) from the size of the Var-Covar matrix\r\n    Z = np.random.default_rng().normal(0, 1, (sampleSize, dim)) # Generate independent increments of a simpleSize dimensional Brownian motion\r\n    Y = np.zeros((sampleSize, dim))                          # Predefine the final output\r\n    L = Cholesky(E)                                          # Calculate the square root of the Var-Covar matrix\r\n\r\n    for iSample in range(sampleSize): # For each sample, calculate mu + L*Z\r\n        Y[iSample] = np.transpose(mu) +  L @ np.transpose(Z[iSample])     \r\n    return Y\r\n", "meta": {"hexsha": "ad3c8f18d24de4ab5431ac14f2b00f4bf3a54b46", "size": 3118, "ext": "py", "lang": "Python", "max_stars_repo_path": "CorBM.py", "max_stars_repo_name": "qnity/correlated_Brownian_Motion_Python", "max_stars_repo_head_hexsha": "db777a379655093e95f3d4be988fb4f9b7cde9dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-20T13:20:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T07:22:30.000Z", "max_issues_repo_path": "CorBM.py", "max_issues_repo_name": "qnity/correlated_Brownian_Motion_Python", "max_issues_repo_head_hexsha": "db777a379655093e95f3d4be988fb4f9b7cde9dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-20T09:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T09:59:16.000Z", "max_forks_repo_path": "CorBM.py", "max_forks_repo_name": "qnity/correlated_Brownian_Motion_Python", "max_forks_repo_head_hexsha": "db777a379655093e95f3d4be988fb4f9b7cde9dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-20T09:51:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T09:51:51.000Z", "avg_line_length": 51.1147540984, "max_line_length": 234, "alphanum_fraction": 0.5994227069, "include": true, "reason": "import numpy", "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147185726374, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.8548952611304461}}
{"text": "# PROJECT: Cross-Entropy Script\n# PROGRAMMER: Carlos Mertens - Udacity Student\n#\t\t\t\tUdacity Instructors (Machine Learning Engineer Nanodegree)\n# DATE CREATED: (DD/MM/YY) 10/01/2019\n# REVISED DATE: (DD/MM/YY)\n# PURPOSE: To show the algorithm to implement Cross-Entropy from the scratch.\n# USAGE: ...\n\nimport numpy as np\n\n\n# Write a function that takes as input two lists Y, P,\n# and returns the float corresponding to their cross-entropy.\ndef cross_entropy(y, p):\n    y = np.float_(y)\n    p = np.float_(p)\n    result = -np.sum(y * np.log(p) + (1 - y) * np.log(1 - p))\n    return result\n\n\ny = [1,0,1,1]\np = [0.4,0.6,0.1,0.5]\n\n# Call function to calculate the cross-entropy\nmy_cross_entropy = cross_entropy(y, p)\n\nprint(my_cross_entropy)\n", "meta": {"hexsha": "4d9965449c2176ffe07863a74beaaef1a7828a60", "size": 735, "ext": "py", "lang": "Python", "max_stars_repo_path": "Deep-Learning/Python-Scripts/cross_entropy.py", "max_stars_repo_name": "carlosmertens/MLND-Notes_and_Codes", "max_stars_repo_head_hexsha": "6ed4c877105af9de1e6f7a289d62c3ac34606710", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Deep-Learning/Python-Scripts/cross_entropy.py", "max_issues_repo_name": "carlosmertens/MLND-Notes_and_Codes", "max_issues_repo_head_hexsha": "6ed4c877105af9de1e6f7a289d62c3ac34606710", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Deep-Learning/Python-Scripts/cross_entropy.py", "max_forks_repo_name": "carlosmertens/MLND-Notes_and_Codes", "max_forks_repo_head_hexsha": "6ed4c877105af9de1e6f7a289d62c3ac34606710", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.25, "max_line_length": 77, "alphanum_fraction": 0.6911564626, "include": true, "reason": "import numpy", "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147209709197, "lm_q2_score": 0.879146761176671, "lm_q1q2_score": 0.8548952524621004}}
{"text": "import numpy as np\n\n\ndef mse(e):\n    return 1/2 * np.mean(e**2)\n\n\ndef rmse(e):\n    return np.sqrt(2 * mse(e))\n\n\ndef mae(e):\n    return np.mean(np.abs(e))\n\n\ndef sigmoid(z):\n    z = np.clip(z, -1000, 1000)\n    return 1.0 / (1 + np.exp(-z))\n\n\ndef compute_mse(y, tx, w):\n    \"\"\"Compute the loss by MSE (Mean Square Error).\"\"\"\n    e = y - tx.dot(w)\n    return mse(e)\n\n\ndef compute_rmse(y, tx, w):\n    \"\"\"Compute the loss by RMSE (Root Mean Square Error).\"\"\"\n    e = y - tx.dot(w)\n    return rmse(e)\n\n\ndef compute_mae(y, tx, w):\n    \"\"\"Compute the loss by MAE (Mean Absolute Error).\"\"\"\n    e = y - tx.dot(w)\n    return mae(e)\n\n\ndef compute_log_likelihood_error(y, tx, w):\n    \"\"\"Compute the loss of the log-likelihood cost function.\"\"\"\n    tx_dot_w = tx.dot(w)\n    return np.sum(np.log(1 + np.exp(tx_dot_w))) - y.dot(tx_dot_w)\n", "meta": {"hexsha": "e05b7be152ea137808b7b7e84da1781259d9e9c6", "size": 821, "ext": "py", "lang": "Python", "max_stars_repo_path": "project1/src/costs.py", "max_stars_repo_name": "errikos/ml-makarona", "max_stars_repo_head_hexsha": "5e0c9efe3405245119bf5aa9bd81a4ca5159eab1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project1/src/costs.py", "max_issues_repo_name": "errikos/ml-makarona", "max_issues_repo_head_hexsha": "5e0c9efe3405245119bf5aa9bd81a4ca5159eab1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project1/src/costs.py", "max_forks_repo_name": "errikos/ml-makarona", "max_forks_repo_head_hexsha": "5e0c9efe3405245119bf5aa9bd81a4ca5159eab1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-24T22:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-24T22:47:38.000Z", "avg_line_length": 19.0930232558, "max_line_length": 65, "alphanum_fraction": 0.5895249695, "include": true, "reason": "import numpy", "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97805174308637, "lm_q2_score": 0.8740772450055545, "lm_q1q2_score": 0.8548927730698147}}
{"text": "import numpy as np\r\n\r\n\r\ndef gaussian_elimination_with_pivot(m):\r\n\r\n    # forward elimination\r\n    n = len(m)\r\n    print(n)\r\n    for k in range(n):\r\n        max = -1e100\r\n        for r in range(k, n):\r\n            if max < abs(m[r][k]):\r\n                max_row = r\r\n                max = abs(m[r][k])\r\n        m[k], m[max_row] = m[max_row], m[k]\r\n        print(m)\r\n        for i in range(k+ 1, n):\r\n            m[i] = [m[i][j] - m[k][j] * m[i][k] / m[k][k] for j in range(n + 1)]\r\n\r\n    if m[n - 1][n - 1] == 0: raise ValueError('No unique solution')\r\n\r\n    print(m)\r\n\r\n    # backward substitution\r\n    x = [0] * n\r\n    for i in range(n - 1, -1, -1):\r\n        s = sum(m[i][j] * x[j] for j in range(i, n))\r\n        x[i] = (m[i][n] - s) / m[i][i]\r\n    return x\r\n\r\n\r\n'''\r\n# shorter way to pivot but cannot run in trinket\r\ndef pivot(m, n, i):\r\n  max_row = max(range(i, n), key=lambda r: abs(m[r][i]))\r\n  m[i], m[max_row] = m[max_row], m[i]\r\n'''\r\n\r\n\r\ndef pivot(m, n, i):\r\n    max = -1e100\r\n    for r in range(i, n):\r\n        if max < abs(m[r][i]):\r\n            max_row = r\r\n            max = abs(m[r][i])\r\n    m[i], m[max_row] = m[max_row], m[i]\r\n\r\n\r\nif __name__ == '__main__':\r\n    # m = [[0,-2,6,-10], [-1,3,-6,5], [4,-12,8,12]]\r\n    # m = [[1,-1,3,2], [3,-3,1,-1], [1,1,0,3]]\r\n    m = [[0.5, 1.1, 3.1, 6], [5, 0.96, 6.5, 0.96], [2, 4.5, 0.36, 0.02]]\r\n    print(gaussian_elimination_with_pivot(m))\r\n    print(len(m))\r\n\r\n    \"\"\"  \r\n    m = [[4,4,0,400], [-1,4,2,400], [0,-2,4,400]]   # aj Montri p80  [50, 50, 125]\r\n    print(gaussian_elimination_with_pivot(m))\r\n    \"\"\"\r\n\r\n", "meta": {"hexsha": "d9a7ef0b4bbe5617ed9bdf18009d796d1d50ff52", "size": 1570, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapter2/gaussian_elim.py", "max_stars_repo_name": "ElliotShang/numerical-analysis", "max_stars_repo_head_hexsha": "769610dc45cc4498b49f8311d7023b725c1c7bc2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter2/gaussian_elim.py", "max_issues_repo_name": "ElliotShang/numerical-analysis", "max_issues_repo_head_hexsha": "769610dc45cc4498b49f8311d7023b725c1c7bc2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter2/gaussian_elim.py", "max_forks_repo_name": "ElliotShang/numerical-analysis", "max_forks_repo_head_hexsha": "769610dc45cc4498b49f8311d7023b725c1c7bc2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.737704918, "max_line_length": 83, "alphanum_fraction": 0.4477707006, "include": true, "reason": "import numpy", "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.904650536386234, "lm_q1q2_score": 0.854889970024664}}
{"text": "#Problem sheet 1\n\nprint 'Problem Sheet 1'\n\nfrom gaussElimin import *\nimport numpy as np\nfrom scipy import linalg\n\nprint 'Q1a'\n#4v1-v2-v3-v4=v+\n#-v1+3v2+0v3-v4=0\n#-v1+0v2+3v3-v4=v+\n#-v1-v2-v3+4v4=0\nprint '4v1-v2-v3-v4=v+'\nprint '-v1+3v2+0v3-v4=0'\nprint '-v1+0v2+3v3-v4=v+'\nprint '-v1-v2-v3+4v4=0'\n\nprint 'Q1b'\nx=np.array([[4.0,-1.0,-1.0,-1.0],[-1.0,3.0,0.0,-1.0],[-1.0,0.0,3.0,-1.0],[-1.0,-1.0,-1.0,4.0]], dtype = float)\nprint x\ny=np.array([[5.0],[0.0],[5.0],[0.0]], dtype = float) #creates a matrix\nprint y\n\nz=gaussElimin(x,y)\nprint z\n\nprint 'Q1c - Using LuDecomposition of our matrix'\n\nfrom LUdecomp import *\n\nP,L,U=linalg.lu(x) #in this case P is just an identitiy matrix because its just 1\n\nprint 'The original matrix'\nprint (x)\nprint ''\nprint 'The L matrix'\nprint (L)\nprint ''\nprint 'The U matrix'\nprint (U)\nprint ''\n\nprint 'Q1D'\n\nx1=np.array([[5.0],[0.0],[5.0],[0.0]]) #vector b when vo is 0\nx2=np.array([[5.0],[1.0],[5.0],[1.0]]) #vector b when v0 is now 1\n\nprint 'original vector b when v0=0'\nprint x1\nprint \"Below are the vectors b where instead of V=0 V0=1:\"\nprint x2 \n\nx=np.array([[4.0,-1.0,-1.0,-1.0],[-1.0,3.0,0.0,-1.0],[-1.0,0.0,3.0,-1.0],[-1.0,-1.0,-1.0,4.0]])\n\nP,L,U=linalg.lu(x) \nk=gaussElimin(L,x2)#solves Lz=b where b is new vector and L is from part c, which redefines b when you use gaussElimin solving as Ux=z it puts in your new b in this case x2 and spits out your original answer\nJ=gaussElimin(U,k)\nM=gaussElimin(L,x1)\nN=gaussElimin(U,M)\nprint 'when v0=1'\nprint J #Solutions match\nprint 'When v0=0'\nprint M #Solutions match from before with part b\n", "meta": {"hexsha": "26f0388f3d032b5977f7a2a6febb899ef1de5086", "size": 1572, "ext": "py", "lang": "Python", "max_stars_repo_path": "ExamPrep/Assignments 2014-15/A1/problemsheet1.py", "max_stars_repo_name": "FHomewood/ScientificComputing", "max_stars_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_stars_repo_licenses": ["IJG"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ExamPrep/Assignments 2014-15/A1/problemsheet1.py", "max_issues_repo_name": "FHomewood/ScientificComputing", "max_issues_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_issues_repo_licenses": ["IJG"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ExamPrep/Assignments 2014-15/A1/problemsheet1.py", "max_forks_repo_name": "FHomewood/ScientificComputing", "max_forks_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_forks_repo_licenses": ["IJG"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1846153846, "max_line_length": 207, "alphanum_fraction": 0.6571246819, "include": true, "reason": "import numpy,from scipy", "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.9149009642742805, "lm_q1q2_score": 0.8548790402362385}}
{"text": "import numpy as np\n\n# ステップ関数の実装\ndef step_function(x):\n    return np.array(x > 0, dtype=np.int32)\n\n#シグモイド関数の実装\ndef sigmoid(x):\n    return 1 / (1 + np.exp(-x))\n\ndef sigmoid_grad(x):\n    return (1.0 - sigmoid(x)) * sigmoid(x)\n\n#ReLU関数の実装\ndef relu(x):\n    return np.maximum(0, x)\n\n#恒等関数(あくまでも例なので値を戻しているだけ)\ndef identity_function(x):\n    return x\n\n#この書き方ではオーバーフローの問題が出てくるので、このままでは利用できない\n#def softmax(a):\n#    exp_a = np.exp(a) #指数関数\n#    sum_exp_a = np.sum(exp_a) #指数関数の和\n#    y = exp_a / sum_exp_a\n#\n#    return y\n\n#ソフトマックス関数\n#※ソフトマックス関数はニューラルネットワークの学習時に使用するものであり、\n#  推論(分類)時には省略するのが一般的\ndef softmax(x):\n    #c = np.max(a)\n    #exp_a = np.exp(a - c) #オーバーフロー対策\n    #sum_exp_a = np.sum(exp_a)\n    #y = exp_a / sum_exp_a\n    #return y\n    x = x - np.max(x, axis=-1, keepdims=True)   # オーバーフロー対策\n    return np.exp(x) / np.sum(np.exp(x), axis=-1, keepdims=True)\n\n#2乗和誤差\ndef sum_squareed_error(y, t):\n    return 0.5 * np.sum((y - t)**2)\n\n#交差エントロピー誤差(バッチ対応版)\ndef cross_entropy_error(y, t):\n    if y.ndim == 1:\n        t = t.reshape(1, t.size)\n        y = y.reshape(1, y.size)\n        \n    # 教師データがone-hot-vectorの場合、正解ラベルのインデックスに変換\n    if t.size == y.size:\n        t = t.argmax(axis=1)\n             \n    batch_size = y.shape[0]\n    return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size\n\n#数値微分\ndef numerical_diff(f, x):\n    h = 1e-4 #0.0001\n    return (f(x + h) - f(x - h)) / (2 * h)\n\n#2次関数(簡単な微分)\ndef function_1(x):\n    return 0.01*x**2 + 0.1*x\n\n#偏微分\ndef function_2(x):\n    #return x[0]**2 + x[1]**2\n    #または return np.sum(x**2)\n    if x.ndim == 1:\n        return np.sum(x**2)\n    else:\n        return np.sum(x**2, axis=1)\n\n#勾配\ndef _numerical_gradient_no_batch(f, x):\n    h = 1e-4 #0.0001\n    grad = np.zeros_like(x) #Xと同じ形状の配列を生成\n\n    for idx in range(x.size):\n        tmp_val = x[idx]\n        # f(x + h)の計算\n        x[idx] = tmp_val + h\n        fxh1 = f(x)\n\n        # f(x - h)の計算\n        x[idx] = tmp_val - h\n        fxh2 = f(x)\n\n        grad[idx] = (fxh1 - fxh2) / (2 * h)\n        x[idx] = tmp_val #値を元に戻す\n\n    return grad\n\ndef numerical_gradient(f, x):\n    #if X.ndim == 1:\n    #    return _numerical_gradient_no_batch(f, X)\n    #else:\n    #    grad = np.zeros_like(X)\n    #    \n    #    for idx, x in enumerate(X):\n    #        grad[idx] = _numerical_gradient_no_batch(f, x)\n    #    \n    #    return grad\n    h = 1e-4 # 0.0001\n    grad = np.zeros_like(x)\n    \n    it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])\n    while not it.finished:\n        idx = it.multi_index\n        tmp_val = x[idx]\n        x[idx] = tmp_val + h\n        fxh1 = f(x) # f(x+h)\n        \n        x[idx] = tmp_val - h \n        fxh2 = f(x) # f(x-h)\n        grad[idx] = (fxh1 - fxh2) / (2*h)\n        \n        x[idx] = tmp_val # 値を元に戻す\n        it.iternext()   \n        \n    return grad\n\n#勾配降下法\n# f : 最適化したい関数\n# init_x : 初期値\n# lr : learning rate\n# step_num : 勾配法による繰り返しの数\ndef gradient_descent(f, init_x, lr=0.01, step_num=100):\n    x = init_x\n    x_history = []\n\n    for i in range(step_num):\n        x_history.append(x.copy())\n\n        grad = numerical_gradient(f, x)\n        x -= lr * grad\n\n    return x, np.array(x_history)\n\n\n", "meta": {"hexsha": "8dca6627c5e1cf239e5fd0c4ade01b8590d88dbd", "size": 3124, "ext": "py", "lang": "Python", "max_stars_repo_path": "algorithm/deep_learning/common_function.py", "max_stars_repo_name": "kake777/python_sample", "max_stars_repo_head_hexsha": "3e69c0e89a67f81ced56193524c2f69913262dda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algorithm/deep_learning/common_function.py", "max_issues_repo_name": "kake777/python_sample", "max_issues_repo_head_hexsha": "3e69c0e89a67f81ced56193524c2f69913262dda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorithm/deep_learning/common_function.py", "max_forks_repo_name": "kake777/python_sample", "max_forks_repo_head_hexsha": "3e69c0e89a67f81ced56193524c2f69913262dda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6944444444, "max_line_length": 75, "alphanum_fraction": 0.5560179257, "include": true, "reason": "import numpy", "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.9149009544128984, "lm_q1q2_score": 0.8548790276789322}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time     : 2018/10/31 17:03\n# @Author   : Iydon\n# @File     : 5.9.py\n\n\nimport numpy as np\n\ndef linspace(start, end, step=None):\n    \"\"\"\n    Args:\n        step: start:step:end\n    \"\"\"\n    length = (end-start)/step\n    return [start+i*step for i in range(int(length[0,0])+1)]\n\ndef runge_kutta(dy, dy0, start, end, step, order:int=2):\n    \"\"\"\n    Runge-Kutta Methods of Order Two.\n    \"\"\"\n    if order not in [1,2,3,4]:\n        raise ValueError\n    xs = linspace(start, end, step=step)\n    ys = [dy0 for i in xs]\n    for i in range(len(xs)-1):\n        k1 = step * dy(xs[i],ys[i])\n        if order<2:\n            ys[i+1] = ys[i] + k1\n        elif order<3:\n            k2 = step * dy(xs[i]+step/2,ys[i]+k1/2)\n            ys[i+1] = ys[i] + k2\n        elif order<4:\n            k2 = step * dy(xs[i]+step/2,ys[i]+k1/2)\n            k3 = step * dy(xs[i]+step,ys[i]-k1+2*k2)\n            ys[i+1] = ys[i] + (k1+4*k2+k3)/6\n        elif order<5:\n            k2 = step * dy(xs[i]+step/2,ys[i]+k1/2)\n            k3 = step * dy(xs[i]+step/2,ys[i]+k2/2)\n            k4 = step * dy(xs[i]+step,ys[i]+k3)\n            ys[i+1] = ys[i] + (k1+2*k2+2*k3+k4)/6\n    return ys\n\n\n\nt1,t2 = lambda t: -(2*t*t+1)*np.exp(2*t), lambda t: (t*t+2*t-4)*np.exp(2*t)\ndy    = lambda t,y: np.matrix([[t1(t[0,0])],[t2(t[1,0])]]) + np.matrix([[3,2],[4,1]])*y\ndy0   = np.matrix([[1],[1]])\nstart = np.matrix([[0],[0]])\nend   = np.matrix([[1],[1]])\nstep  = 0.2\nresult = runge_kutta(dy, dy0, start, end, step, order=4)\nprint(result)\nu1 = lambda t: np.exp(5*t)/3-np.exp(-t)/3+np.exp(2*t)\nu2 = lambda t: np.exp(5*t)/3+2*np.exp(-t)/3+t*t*np.exp(2*t)\nt  = [0, 0.2, 0.4, 0.6, 0.8, 1]\nprint([u1(i) for i in t])\nprint([u2(i) for i in t])\n\n\nt1,t2 = lambda t: np.cos(t)+4*np.sin(t), lambda t: -3*np.sin(t)\ndy    = lambda t,y: np.matrix([[t1(t[0,0])],[t2(t[1,0])]]) + np.matrix([[-4,-2],[3,1]])*y\ndy0   = np.matrix([[0],[-1]])\nstart = np.matrix([[0],[0]])\nend   = np.matrix([[2],[2]])\nstep  = 0.1\nresult = runge_kutta(dy, dy0, start, end, step, order=4)\nprint(result)\nu1 = lambda t: 2*np.exp(-t)-2*np.exp(-2*t)+np.sin(t)\nu2 = lambda t: -3*np.exp(-t)+2*np.exp(-2*t)\nt  = [i/10 for i in range(21)]\nprint([u1(i) for i in t])\nprint([u2(i) for i in t])\n", "meta": {"hexsha": "9875ab2c5b0fb7dbc5a2a0eaa3fc7b040fe810d2", "size": 2238, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/HW/5.9.py", "max_stars_repo_name": "Iydon/NumericalAnalysisNotes", "max_stars_repo_head_hexsha": "ef1e37b97522fce9837142d242676fdd16e74712", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-11-08T15:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-02T10:07:33.000Z", "max_issues_repo_path": "MA305/5.9.py", "max_issues_repo_name": "AllenYZB/homework", "max_issues_repo_head_hexsha": "65bd3372df197bec5e152a37cdc1f6f5432b7f3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-13T03:04:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:49:10.000Z", "max_forks_repo_path": "MA305/5.9.py", "max_forks_repo_name": "AllenYZB/homework", "max_forks_repo_head_hexsha": "65bd3372df197bec5e152a37cdc1f6f5432b7f3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-02T05:46:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T23:11:28.000Z", "avg_line_length": 30.2432432432, "max_line_length": 89, "alphanum_fraction": 0.5089365505, "include": true, "reason": "import numpy", "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377261041521, "lm_q2_score": 0.8918110490322425, "lm_q1q2_score": 0.8548345350539243}}
{"text": "import numpy as np\n\n# Helper function to calculate the sigmoid\ndef sigmoid(z):\n    sig = 1 / (1 + np.exp(-z))\n    \n    return sig\n\n# Helper function to initialize weights and bias with zero\ndef initialize_parameters(dimension):\n    weights = np.zeros((dimension, 1))\n    bias = 0\n    \n    return weights, bias\n\n# Helper function to do a single forward pass\ndef forward_propagate(X, Y, weights, bias):\n    # Get the number of training examples\n    m = X.shape[1]\n    \n    # Calculate the z\n    z = np.dot(weights.T, X) + bias\n    \n    # Calculate activation A using sigmoid activation\n    A = sigmoid(z)\n    \n    # Calculate for the cost\n    cost = (-1/m) * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))\n    \n    cost = np.squeeze(cost)\n    \n    return A, cost\n\n# Helper function to do a single backward pass\ndef backward_propagate(X, Y, A):\n    # Calculate for the derivatives\n    m = X.shape[1]\n    dz = A - Y\n    dw = (1/m) * np.dot(X, dz.T)\n    db = (1/m) * np.sum(dz)\n    \n    return dw, db\n\n# Helper function to optimize weights and bias using gradient descent algorithm\ndef gradient_descent(X, Y, weights, bias, iterations, learning_rate, print_cost=False):\n    costs = []\n    \n    for i in range(iterations):\n        # Compute for cost and gradient using propagate\n        A, cost = forward_propagate(X, Y, weights, bias)\n        dw, db = backward_propagate(X, Y, A)\n        \n        # Update weights and bias parameters\n        weights = weights - learning_rate * dw\n        bias = bias - learning_rate * db\n        \n        # Record cost\n        if i % 100 == 0:\n            costs.append(cost)\n        \n        # Print the cost every 100 iterations\n        if print_cost and i % 100 == 0:\n            print (\"Cost after iteration %i: %f\" %(i, cost))\n            \n    return weights, bias, dw, db, costs\n\ndef predict(X, weights, bias):\n    m = X.shape[1]\n    Y_pred = np.zeros((1, m))\n    \n    A = sigmoid(np.dot(weights.T, X) + bias)\n    \n    for i in range(A.shape[1]):\n        if A[0,i] <= 0.5:\n            Y_pred[0,i] = 0\n        else:\n            Y_pred[0,i] = 1\n    \n    return Y_pred\n", "meta": {"hexsha": "a43d86989ad3b2d404086069d1d58ee84b3993d6", "size": 2101, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils.py", "max_stars_repo_name": "louisalbertapas/logistic-regression", "max_stars_repo_head_hexsha": "b150f25600c0fbc128ba779f562efc841151fa14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils.py", "max_issues_repo_name": "louisalbertapas/logistic-regression", "max_issues_repo_head_hexsha": "b150f25600c0fbc128ba779f562efc841151fa14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils.py", "max_forks_repo_name": "louisalbertapas/logistic-regression", "max_forks_repo_head_hexsha": "b150f25600c0fbc128ba779f562efc841151fa14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2625, "max_line_length": 87, "alphanum_fraction": 0.5792479772, "include": true, "reason": "import numpy", "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377225508371, "lm_q2_score": 0.8918110375304408, "lm_q1q2_score": 0.8548345208601278}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul  9 08:04:05 2021\n\n@author: alessandro\n\"\"\"\n\nimport numpy as np\nimport sympy as sym\nfrom sympy.utilities.lambdify import lambdify\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import fsolve\n\nx = sym.symbols('x')\nfx = x - 2 * sym.sqrt(x - 1)\ndfx = sym.diff(fx, x, 1)\n\nf = lambdify(x, fx, np)\ndf = lambdify(x, dfx, np)\n\na = 1\nb = 3\nzero = 2\n\nxx = np.linspace(a, b, 100)\ny = f(xx)\nd = df(xx)\nplt.ylim((-1, 1))\nplt.plot(xx, y)\nplt.plot(xx, d)\nplt.plot([zero, ], f(np.array([zero])), 'o')\nplt.plot([zero, ], df(np.array([zero])), 'o')\nplt.plot(xx, 0*xx)\nplt.show()\n\n# Serve newton di grado due poichè la derivata prima vale zero in alpha\n# mentre la derivata seconda non si annulla\n\ndef newton(f, df, m, x0, tolx, tolf, nmax=2048):\n    def delta(x): return f(x) / df(x) if abs(df(x)) > np.spacing(1) else print(\"Derivata nulla\")\n    def prossimax(x): return x - m * delta(x)\n    \n    x = prossimax(x0)\n    fx = f(x)\n    it, xk = 1, [x]\n    while it < nmax and abs(fx) > tolf and abs(delta(x)) > tolx * abs(x):\n        x = prossimax(x)\n        xk.append(x)\n        fx = f(x)\n        it += 1\n    \n    return x, it, xk\n\nalpha, it, xk = newton(f, df, 2, 3, 1e-12, 1e-12)\nprint(alpha)\n\n# devo stabilire l'ordine di convergenza\n\ndef stimaordine(xk):\n    k = len(xk) - 4\n    n = np.log(np.abs(xk[k + 3] - xk[k + 2]) / np.abs(xk[k + 2] - xk[k + 1]))\n    d = np.log(np.abs(xk[k + 2] - xk[k + 1]) / np.abs(xk[k + 1] - xk[k]))\n    return n / d\n\nordine = stimaordine(xk)\nprint(f\"L'ordine è {ordine}\")\n\n# stampo le iterate\nplt.title(\"Iterazioni\")\nplt.semilogy(range(1, it + 1), xk, 'o')\nplt.semilogy(range(1, it + 1), xk)\n\n# provo a partire da x0 = 1\na = newton(f, df, 2, 1, 1e-12, 1e-12)\nprint(a)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "77f36b69f69e6b1e3d570e59a113041514d422e0", "size": 1768, "ext": "py", "lang": "Python", "max_stars_repo_path": "esercitazioni/2020_09_09_es_01.py", "max_stars_repo_name": "alemazzo/metodi_numerici", "max_stars_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-07-08T10:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T09:56:37.000Z", "max_issues_repo_path": "esercitazioni/2020_09_09_es_01.py", "max_issues_repo_name": "alemazzo/metodi_numerici", "max_issues_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "esercitazioni/2020_09_09_es_01.py", "max_forks_repo_name": "alemazzo/metodi_numerici", "max_forks_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4285714286, "max_line_length": 96, "alphanum_fraction": 0.5854072398, "include": true, "reason": "import numpy,from scipy,import sympy,from sympy", "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.9086179068309441, "lm_q1q2_score": 0.8548184172647068}}
{"text": "r\"\"\"\n\nNewton's method is a rather popular iterative root finding algorithm. Starting\nat an initial guess :math:`x_0` it tries to find better and better\napproximations of the root of a function :math:`f(x)`. For this it uses the\nfirst derivative :math:`f'(x)` of the function. The process\n\n.. math::\n\n    x_{n+1} = x_n - \\frac{f(x_n)}{f'(x_n)}\n\nis repeated until a value :math:`f(x_n)` is reached that is within a predefined\ntolerance to zero. For further information see the `Wikipedia`_ page.\n\nThe way it is supposed to work is as follows:\n\n>>> def f(x):\n...     return x**2 - 2\n...\n>>> def df_dx(x):\n...     return 2*x\n...\n>>> newtons_method_1d(f, df_dx, x0=4, tol=1e-8)  # doctest:+SKIP\n1.4142135623730951\n\nHence, implement a function following the given definition:\n\n.. autofunction:: newtons_method_1d\n\nStart by downloading the\n:exercise:`exercise template </exercises/newtons_method_1d.py>` and\nediting this file. You can run tests via\n\n.. code-block:: console\n\n    $ python newtons_method_1d.py test\n\nto check whether you got a correct solution. You can also take a look at\n:solution:`one possible solution </exercises/newtons_method_1d.py>`.\n\n.. _Wikipedia: https://en.wikipedia.org/wiki/Newton's_method\n\n\"\"\"\n\n\ndef newtons_method_1d(f, df_dx, x0, tol):\n    \"\"\"Return the root of `f` within `tol` by using Newton's method.\n\n    Parameters\n    ----------\n    f : callable[[float], float]\n        The function of which the root should be found.\n    df_dx : callable[[float], float]\n        The derivative of `f`.\n    x_0 : float\n        The initial guess for the algorithm.\n    tol : float\n        The tolerance of the method.\n\n    Returns\n    -------\n    float\n        The root of `f` within a tolerance of `tol`.\n\n    \"\"\"\n    # begin solution\n    x = x0\n    while abs(f(x)) > tol:\n        x -= f(x) / df_dx(x)\n    return x\n    # end solution\n\n# -----------------------------------------------------------------------------\n# In the following the tests for this exercise are given---do not modify them.\nimport sys\nimport pytest\nfrom numpy.testing import assert_allclose\n\n\n@pytest.mark.parametrize(\n    ('f', 'df_dx', 'x0', 'tol', 'expected'),\n    [\n        (lambda x: x**2 - 2, lambda x: 2*x, 4, 1e-8, 2**(1/2)),\n        (lambda x: x**2 - 2, lambda x: 2*x, -4, 1e-8, -2**(1/2)),\n        (lambda x: x**3 - 5, lambda x: 3*x**2, 4, 1e-8, 5**(1/3))\n    ])\ndef test_correct_result(f, df_dx, x0, tol, expected):\n    assert_allclose(\n        newtons_method_1d(f, df_dx, x0, tol),\n        expected,\n        rtol=0,\n        atol=tol)\n\n\nif __name__ == '__main__':\n    if len(sys.argv) == 2 and sys.argv[-1] == 'test':\n        pytest.main([__file__])\n", "meta": {"hexsha": "23b74f05e4c5352dd701d76ef5557f37d55e4c19", "size": 2646, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/exercises/newtons_method_1d.py", "max_stars_repo_name": "GauZen/python101", "max_stars_repo_head_hexsha": "36a9c9f87b006f522c4bad9deed481dcc0ab418a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-10T20:33:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-10T20:33:13.000Z", "max_issues_repo_path": "docs/exercises/newtons_method_1d.py", "max_issues_repo_name": "GauZen/python101", "max_issues_repo_head_hexsha": "36a9c9f87b006f522c4bad9deed481dcc0ab418a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/exercises/newtons_method_1d.py", "max_forks_repo_name": "GauZen/python101", "max_forks_repo_head_hexsha": "36a9c9f87b006f522c4bad9deed481dcc0ab418a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 79, "alphanum_fraction": 0.6160241875, "include": true, "reason": "from numpy", "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897525789547, "lm_q2_score": 0.9086179012632543, "lm_q1q2_score": 0.854818410518266}}
{"text": "\"\"\"\n sum\n\nThe sum tool returns the sum of array elements over a given axis.\n\nimport numpy\n\nmy_array = numpy.array([ [1, 2], [3, 4] ])\n\nprint numpy.sum(my_array, axis = 0)         #Output : [4 6]\nprint numpy.sum(my_array, axis = 1)         #Output : [3 7]\nprint numpy.sum(my_array, axis = None)      #Output : 10\nprint numpy.sum(my_array)                   #Output : 10\n\nBy default, the axis value is None. Therefore, it performs a sum over all the dimensions of the input array.\n\nprod\n\nThe prod tool returns the product of array elements over a given axis.\n\nimport numpy\n\nmy_array = numpy.array([ [1, 2], [3, 4] ])\n\nprint numpy.prod(my_array, axis = 0)            #Output : [3 8]\nprint numpy.prod(my_array, axis = 1)            #Output : [ 2 12]\nprint numpy.prod(my_array, axis = None)         #Output : 24\nprint numpy.prod(my_array)                      #Output : 24\n\nBy default, the axis value is None. Therefore, it performs the product over all the dimensions of the input array.\n\nTask\n\nYou are given a 2-D array with dimensions\nX.\nYour task is to perform the tool over axis and then find the\n\nof that result.\n\nInput Format\n\nThe first line of input contains space separated values of\nand .\nThe next lines contains\n\nspace separated integers.\n\nOutput Format\n\nCompute the sum along axis\n\n. Then, print the product of that sum.\n\nSample Input\n\n2 2\n1 2\n3 4\n\nSample Output\n\n24\n\nExplanation\n\nThe sum along axis\n= [ ]\nThe product of this sum =\n\"\"\"\n\nimport numpy\n\nN, M = map(int, input().split())\nA = numpy.array([input().split() for _ in range(N)],int)\nprint(numpy.prod(numpy.sum(A, axis=0), axis=0))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "2ce1a637199e155bf3dea663f08124be0305406e", "size": 1612, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numpy/Sum_and_Prod.py", "max_stars_repo_name": "NikolayVaklinov10/Python_Challenges", "max_stars_repo_head_hexsha": "a1052e1d527004bbb6072a3cbc802065469f66ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-01T23:57:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-01T23:58:16.000Z", "max_issues_repo_path": "Numpy/Sum_and_Prod.py", "max_issues_repo_name": "NikolayVaklinov10/Python_Challenges", "max_issues_repo_head_hexsha": "a1052e1d527004bbb6072a3cbc802065469f66ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numpy/Sum_and_Prod.py", "max_forks_repo_name": "NikolayVaklinov10/Python_Challenges", "max_forks_repo_head_hexsha": "a1052e1d527004bbb6072a3cbc802065469f66ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5217391304, "max_line_length": 114, "alphanum_fraction": 0.6637717122, "include": true, "reason": "import numpy", "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436404, "lm_q2_score": 0.8947894724152068, "lm_q1q2_score": 0.8548095034916665}}
{"text": "import numpy as np\n\n\ndef mean_square_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n    \"\"\"\n    Calculate MSE loss\n\n    Parameters\n    ----------\n    y_true: ndarray of shape (n_samples, )\n        True response values\n    y_pred: ndarray of shape (n_samples, )\n        Predicted response values\n\n    Returns\n    -------\n    MSE of given predictions\n    \"\"\"\n    squared_error = np.square(y_true-y_pred)\n    mean2 = np.sum(squared_error)/y_true.shape[0]\n    return mean2\n\n\ndef misclassification_error(y_true: np.ndarray, y_pred: np.ndarray, normalize: bool = True) -> float:\n    \"\"\"\n    Calculate misclassification loss\n\n    Parameters\n    ----------\n    y_true: ndarray of shape (n_samples, )\n        True response values\n    y_pred: ndarray of shape (n_samples, )\n        Predicted response values\n    normalize: bool, default = True\n        Normalize by number of samples or not\n\n    Returns\n    -------\n    Misclassification of given predictions\n    \"\"\"\n    t = y_pred * y_true\n    error_num = np.count_nonzero(t<0)\n    if normalize:\n      return float(error_num/y_true.shape[0])\n    else:\n        return error_num\n\n\ndef accuracy(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n    \"\"\"\n    Calculate accuracy of given predictions\n\n    Parameters\n    ----------\n    y_true: ndarray of shape (n_samples, )\n        True response values\n    y_pred: ndarray of shape (n_samples, )\n        Predicted response values\n\n    Returns\n    -------\n    Accuracy of given predictions\n    \"\"\"\n\n    true_predictions = np.count_nonzero(y_pred == y_true)\n    predictions = y_pred.shape[0]\n    return float(true_predictions)/predictions\n\n\n\ndef cross_entropy(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n    \"\"\"\n    Calculate the cross entropy of given predictions\n\n    Parameters\n    ----------\n    y_true: ndarray of shape (n_samples, )\n        True response values\n    y_pred: ndarray of shape (n_samples, )\n        Predicted response values\n\n    Returns\n    -------\n    Cross entropy of given predictions\n    \"\"\"\n    raise NotImplementedError()\n", "meta": {"hexsha": "fe1898320185fbdd88ee40eead3b66d6806ae89b", "size": 2046, "ext": "py", "lang": "Python", "max_stars_repo_path": "IMLearn/metrics/loss_functions.py", "max_stars_repo_name": "yuvalstn1/IML.HUJI", "max_stars_repo_head_hexsha": "1115082aa7a2742aa783f2ba87442b87fb30025b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IMLearn/metrics/loss_functions.py", "max_issues_repo_name": "yuvalstn1/IML.HUJI", "max_issues_repo_head_hexsha": "1115082aa7a2742aa783f2ba87442b87fb30025b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IMLearn/metrics/loss_functions.py", "max_forks_repo_name": "yuvalstn1/IML.HUJI", "max_forks_repo_head_hexsha": "1115082aa7a2742aa783f2ba87442b87fb30025b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5172413793, "max_line_length": 101, "alphanum_fraction": 0.6388074291, "include": true, "reason": "import numpy", "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715435, "lm_q2_score": 0.8947894661025424, "lm_q1q2_score": 0.8548094963227985}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef pca(x, varRetained = 0.95):\n    ''' varRetained is the original data variance retained in the new dataset. New number of dimensions\n     is computed based on the desired fraction of the original variance.\n    '''\n    n = x.shape[0]\n    d = x.shape[1]\n    sigma = 1.0/d*np.dot(x.T,x)\n    U, S, V = np.linalg.svd(sigma, full_matrices=True)\n    k = 0\n    total_var = np.sum(S)\n    var_cum_sums = np.array([np.sum(S[:i+1])/total_var*100 for i in range(d)])\n    k = len(var_cum_sums[var_cum_sums<(varRetained*100)])\n    U_reduced = U[:, : k]\n    return np.dot(x, U_reduced), k\n\nclass FLDA:\n    def fit(self, x, y):\n        n = x.shape[0]\n        x = np.concatenate([x, np.ones([n,1])], axis = 1)\n        classes = set(y)\n        n0= n1= 0\n        for i in y:\n            if(y==0):\n                M0 += x[i]\n                n0 += 1\n            else:\n                M1 += x[i]\n                n1 += 1\n        M0 = M0/n0\n        M1 = M1/n1\n        Sw = []\n        for i in y:\n            if(y==0):\n                Sw += np.dot((x[i] - M0), (x[i] - M0).T)\n            else:\n                Sw += np.dot((x[i] - M1), (x[i] - M1).T)\n        w = np.dot(np.linalg.inv(Sw), (M0- M1))\n        return w\n    def predict(self, x, w):\n        h = np.dot(w, x)\n        if(h>0):\n            return 0\n        else:\n            return 1\n", "meta": {"hexsha": "8262f7bcede04808a641cb7877ed8130db736f04", "size": 1372, "ext": "py", "lang": "Python", "max_stars_repo_path": "PA_3/models.py", "max_stars_repo_name": "nimRobotics/MLIP", "max_stars_repo_head_hexsha": "6d27497762a1d30b7fb5796e5a7bf22eccb776a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PA_3/models.py", "max_issues_repo_name": "nimRobotics/MLIP", "max_issues_repo_head_hexsha": "6d27497762a1d30b7fb5796e5a7bf22eccb776a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PA_3/models.py", "max_forks_repo_name": "nimRobotics/MLIP", "max_forks_repo_head_hexsha": "6d27497762a1d30b7fb5796e5a7bf22eccb776a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5833333333, "max_line_length": 103, "alphanum_fraction": 0.47303207, "include": true, "reason": "import numpy", "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191284552528, "lm_q2_score": 0.8947894689081711, "lm_q1q2_score": 0.8548094955882926}}
{"text": "# Author: Dimitrios Damopoulos\n# MIT license (see LICENCE.txt in the top-level folder)\n\n# TODO: documentation\n\nimport numpy as np\n\ndef sigmoid(z):\n    \"\"\"\n    Computes the sigmoid function\n\n    Args:\n        z (np.ndarray): the values where the sigmoid should be calculated on\n\n    Returns:\n        An np.ndarray with the same shape as the input `z' with the values of \n        sigmoid\n    \"\"\"\n    sigm = 1. / (1. + np.exp(-z))\n    return sigm\n\ndef cross_entropy(p_hat, p):\n    \"\"\"\n    Computer the cross entropy between two distributions\n\n    Args:\n        p_hat (np.ndarray of shape m,): The \"predicted\" probability distribution\n        p (np.ndarray of shape m,): The \"true\" probability distribution\n\n    Returns:\n        The cross-entropy between the two distributions\n    \"\"\"\n    # get values which are very close to zero a bit higher, in order to avoid\n    # NaNs in the computation of the logarithm later.\n    eps = np.finfo(float).eps\n    p_hat[p_hat < eps] = eps\n\n    ce = - np.log(p_hat).T.dot(p)\n    return ce\n\ndef cross_entropy_with_one_hot_vector(p_hat, p):\n    \"\"\"\n    Same as math_utils.cross-entropy, but for a \"true\" probability distribution\n    has arose for a binary random variable (i.e., a process that outputs True \n    or False for every sample. It should output the same as \n    math_utils.cross_entropy, but faster.\n\n    Args:\n        p_hat (np.ndarray of shape m,): The \"predicted\" probability distribution\n        p (np.ndarray of shape m,): The \"true\" probability distribution. Its \n            values are converted to binary before the computation of the \n            cross-entropy, by just comparing them with 0: anything above zero is \n            treated as have value \"1\" and the rest as having value \"0\"\n    \n    Returns:\n        The cross-entropy between the two distributions\n    \"\"\"\n    eps = np.finfo(float).eps\n    p1 = p > 0\n    p0 = np.logical_not(p1)\n    part1 = np.log(p_hat[p1] + eps).sum()\n    part0 = np.log(1. - p_hat[p0] + eps).sum()\n    \n    return -(part0 + part1)\n\ndef rmse(y_hat, y):\n    \"\"\" \n    Returns the Root Mean Square error between two series of measurements \n    \"\"\"\n    losses = y_hat - y\n    se = losses.T.dot(losses)\n    return np.sqrt(se / y.shape[0])\n\ndef gradient_of_rmse(y_hat, y, Xn):\n    \"\"\" \n    Returns the gradient of the Root Mean Square error with respect to the \n    parameters of the linear model that generated the prediction `y_hat'. \n    Hence, y_hat should have been generated by a linear process of the form\n    Xn.T.dot(theta)\n\n    Args:\n        \n       y_hat (np.array of shape N,): The predictions of the linear model\n       y (np.array of shape N,): The \"ground-truth\" values.\n\n    Returns:\n        The RMSE between y_hat and y\n    \"\"\"\n        \n    N = y.shape[0]\n    assert N > 0, ('At least one sample is required in order to compute the '\n                  'RMSE loss')\n   \n    losses = y - y_hat\n    gradient = - 2 * Xn.T.dot(losses) / N\n\n    return gradient\n", "meta": {"hexsha": "d80a2f78770916da8524bd0f958b2b07f8f64d70", "size": 2949, "ext": "py", "lang": "Python", "max_stars_repo_path": "single_neuron/math_utils.py", "max_stars_repo_name": "dimdamop/single-neuron", "max_stars_repo_head_hexsha": "fa649bcd2c7cc68b46c87e63e3c5869f772fecdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "single_neuron/math_utils.py", "max_issues_repo_name": "dimdamop/single-neuron", "max_issues_repo_head_hexsha": "fa649bcd2c7cc68b46c87e63e3c5869f772fecdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-02-21T19:16:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-21T20:12:33.000Z", "max_forks_repo_path": "single_neuron/math_utils.py", "max_forks_repo_name": "dimdamop/single-neuron", "max_forks_repo_head_hexsha": "fa649bcd2c7cc68b46c87e63e3c5869f772fecdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0918367347, "max_line_length": 81, "alphanum_fraction": 0.6378433367, "include": true, "reason": "import numpy", "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110587, "lm_q2_score": 0.8947894611926921, "lm_q1q2_score": 0.8548094859410298}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef f(x):\r\n    \"\"\"\"Returns the function where you're looking for zero spots\"\"\"\r\n    return np.sin(x)**2 + np.sin((x+1)**2)\r\n\r\n\r\nclass FindZeroSpot:\r\n    def __init__(self, func, x1=0.8, x2=1.2, precision=1e-3):\r\n        \"\"\"\r\n        :param func: defined function to examine\r\n        :param x1: the beginning of the area under investigation\r\n        :param x2: end of the area under investigation\r\n        :param precision: precision of searching for zero place\r\n        \"\"\"\r\n        N = 300\r\n        self.x_min = -5\r\n        self.x_max = 5\r\n        self.precision = precision\r\n        self.function = func\r\n        self.interval_list = [[x1, x2, 0]]\r\n\r\n        self.x_points = np.linspace(self.x_min, self.x_max, N)\r\n        self.y_points = self.function(self.x_points)\r\n\r\n    def steps(self, act_interval):\r\n        f1 = self.function(act_interval[0])\r\n        f2 = self.function(act_interval[1])\r\n        x0 = (act_interval[0] * f2 - act_interval[1] * f1) / (f2 - f1)\r\n        f0 = self.function(x0)\r\n\r\n        if f0 * f1 > 0:\r\n            return [x0, act_interval[1], x0]\r\n        else:\r\n            return [act_interval[0], x0, x0]\r\n\r\n    def count(self):\r\n        \"\"\"\r\n        counts the coordinates of the zero place\r\n        :return:x coordinate, y coordinate\r\n        \"\"\"\r\n\r\n        def new_interval(interval_list):\r\n            return interval_list.append(self.steps(interval_list[-1]))\r\n\r\n        def check_precision_condition(interval_list, precision):\r\n            new_interval(interval_list)\r\n            if abs(interval_list[-1][2] - interval_list[-2][2]) < precision:\r\n                return False\r\n            return True\r\n\r\n        while check_precision_condition(self.interval_list, self.precision):\r\n            pass\r\n\r\n        x_result = self.interval_list[-1][2]\r\n        y_result = self.function(x_result)\r\n        print(self.interval_list)\r\n        return x_result, y_result\r\n\r\n    def figure(self, x_result, y_result):\r\n        \"\"\"\r\n        draws a graph of functions, interval, point\r\n\r\n        :param x_result: x coordinate of the result\r\n        :param y_result: y coordinate of the result\r\n        :return: null\r\n        \"\"\"\r\n        fig = plt.figure()\r\n        ax = fig.add_subplot(111)\r\n        ax.plot(self.x_points, self.y_points, \"-b\")\r\n        ax.plot([self.x_points[0], self.x_points[-1]], [0, 0], '-k')\r\n        ax.plot([self.interval_list[0][0], self.interval_list[0][0]], [-0.5, 0.5], '-y')\r\n        ax.plot([self.interval_list[0][1], self.interval_list[0][1]], [-0.5, 0.5], '-y')\r\n        ax.plot(x_result, y_result, 'or')\r\n        plt.show()\r\n\r\n\r\nexample = FindZeroSpot(f)\r\nx, y = example.count()\r\nprint(\"coordinates of it \\nx:{:5.2f} y:{:5.2f}\".format(x, y))\r\nexample.figure(x, y)\r\n", "meta": {"hexsha": "e4606a395ac8fcbf6b1f96e45eff75fda605c60a", "size": 2780, "ext": "py", "lang": "Python", "max_stars_repo_path": "null-locations.py", "max_stars_repo_name": "gunater/Numerical-methods", "max_stars_repo_head_hexsha": "4cf676b7d3996b7e70c6f4b50b15acc330a0d763", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "null-locations.py", "max_issues_repo_name": "gunater/Numerical-methods", "max_issues_repo_head_hexsha": "4cf676b7d3996b7e70c6f4b50b15acc330a0d763", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "null-locations.py", "max_forks_repo_name": "gunater/Numerical-methods", "max_forks_repo_head_hexsha": "4cf676b7d3996b7e70c6f4b50b15acc330a0d763", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0952380952, "max_line_length": 89, "alphanum_fraction": 0.571942446, "include": true, "reason": "import numpy", "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191271831559, "lm_q2_score": 0.8947894597898776, "lm_q1q2_score": 0.8548094857391534}}
{"text": "#%% ================ Introduction: load packages ================\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nfrom featureNormalize import featureNormalize\nfrom gradientDescentMulti import gradientDescentMulti\nfrom normalEqn import normalEqn\n\n\n\n#%% ================ Part 1: Feature Normalization ================\n\nprint('\\n -------------------------- \\n')\nprint('Loading data ...')\n\n# Load Data\npath = 'ex1data2.txt'  \ndata = pd.read_csv(path, header=None, names=['HouseSize', 'NbOfBedrooms', 'Price'])  \ndata.head()  \n\n# Résumé des données\ndata.describe()  \n\n# set X (training data) and y (target variable)\nnbCol = data.shape[1]  \nX = data.iloc[:,0:nbCol-1]  \ny = data.iloc[:,nbCol-1:nbCol]  \n\n# convert from data frames to numpy arrays\nX = np.array(X.values)  \ny = np.array(y.values)\nm = X.shape[0]\n\n\n\n# Print out some data points\nprint('\\n -------------------------- \\n')\nprint('First 10 examples from the dataset:')\nprint(np.column_stack( (X[:10], y[:10]) ))\n\n\n# Scale features and set them to zero mean\nprint('\\n -------------------------- \\n')\nprint('Normalizing Features ...')\n\nX, mu, sigma = featureNormalize(X)\nprint('[mu] [sigma]')\nprint(mu, sigma)\n\n# Add intercept term to X\nX = np.concatenate((np.ones((m, 1)), X), axis=1)\n\n\n#%% ================ Part 2: Gradient Descent ================\n#\n# ====================== YOUR CODE HERE ======================\n# Instructions: We have provided you with the following starter\n#               code that runs gradient descent with a particular\n#               learning rate (alpha).\n#\n#               Your task is to first make sure that your functions -\n#               computeCost and gradientDescent already work with\n#               this starter code and support multiple variables.\n#\n#               After that, try running gradient descent with\n#               different values of alpha and see which one gives\n#               you the best result.\n#\n#               Finally, you should complete the code at the end\n#               to predict the price of a 1650 sq-ft, 3 br house.\n#\n#\n# Hint: At prediction, make sure you do the same feature normalization.\n#\n\nprint('\\n -------------------------- \\n')\nprint('Running gradient descent ...')\n\n# Choose some alpha value\nalpha = 0.01\nnum_iters = 400\n\n# Init Theta and Run Gradient Descent \nn = X.shape[1]\ntheta = np.zeros((n,1))\ntheta, cost_history, theta_history = gradientDescentMulti(X, y, theta, alpha, num_iters)\n\n# Plot the convergence graph\nfig = plt.figure()\nax = plt.gca()\nax.plot(np.arange(num_iters), cost_history, color=\"blue\", linewidth=2.0, linestyle=\"-\")  \nax.grid()\nax.set_xlabel('iteration number')  \nax.set_ylabel(r'Cost J($\\theta$)')  \nax.set_title('Error vs. Training Epoch (number of iters)')  \nfig.show()\nplt.show()\n\n\n# Display gradient descent's result\nprint('\\n -------------------------- \\n')\nprint('Theta computed from gradient descent: ')\nprint(theta)\n\n# Estimate the price of a 1650 sq-ft, 3 br house\nprice = np.array([[1, 1650, 3 ]]).dot(theta)\n\nprint('\\n -------------------------- \\n')\nprint('Predicted price of a 1650 sq-ft, 3 br house')\nprint(\"(using gradient descent):\\n $%f\\n\" % price)\n\n\n\n\n\n\n\n#%% ================ Part 3: Normal Equations ================\n\n# ====================== YOUR CODE HERE ======================\n# Instructions: The following code computes the closed form\n#               solution for linear regression using the normal\n#               equations. You should complete the code in\n#               normalEqn.py\n#\n#               After doing so, you should complete this code\n#               to predict the price of a 1650 sq-ft, 3 br house.\n#\nprint('\\n -------------------------- \\n')\nprint('Solving with normal equations...')\n\n# Load Data\ndata = np.loadtxt('ex1data2.txt', delimiter=',')\npath = 'ex1data2.txt'  \ndata = pd.read_csv(path, header=None, names=['HouseSize', 'NbOfBedrooms', 'Price'])  \ndata.head()  \n\n\n# set X (training data) and y (target variable)\nnbCol = data.shape[1]  \nX = data.iloc[:,0:nbCol-1]  \ny = data.iloc[:,nbCol-1:nbCol]  \n\n# convert from data frames to numpy arrays\nX = np.array(X.values)  \ny = np.array(y.values)\nm = X.shape[0]\n\n\n# Add intercept term to X\nX = np.concatenate((np.ones((m, 1)), X), axis=1)\n\n# Calculate the parameters from the normal equation\ntheta = normalEqn(X, y)\n\n# Display normal equation's result\nprint('Theta computed from the normal equations:')\nprint(' %s \\n' % theta)\n\n# Estimate the price of a 1650 sq-ft, 3 br house\nprice = np.array([[1, 1650, 3 ]]).dot(theta)\n\n\nprint(\"Predicted price of a 1650 sq-ft, 3 br house \")\nprint('(using normal equations):\\n $%f\\n' % price)\n\n# ============================================================\n", "meta": {"hexsha": "dd5b797ea166762b1ba38f6d58955069f8c98f5a", "size": 4674, "ext": "py", "lang": "Python", "max_stars_repo_path": "MachineLearning/TP1/ex1_multi.py", "max_stars_repo_name": "piwithy/ENSTA_MACHINE_LEARNING", "max_stars_repo_head_hexsha": "8a58b230f150ca7ceaf340086f15d0d3535d2859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MachineLearning/TP1/ex1_multi.py", "max_issues_repo_name": "piwithy/ENSTA_MACHINE_LEARNING", "max_issues_repo_head_hexsha": "8a58b230f150ca7ceaf340086f15d0d3535d2859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MachineLearning/TP1/ex1_multi.py", "max_forks_repo_name": "piwithy/ENSTA_MACHINE_LEARNING", "max_forks_repo_head_hexsha": "8a58b230f150ca7ceaf340086f15d0d3535d2859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6568047337, "max_line_length": 89, "alphanum_fraction": 0.5962772786, "include": true, "reason": "import numpy", "num_tokens": 1157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.9111797142327147, "lm_q1q2_score": 0.8547995743957614}}
{"text": "# Computational Solutions \n## Introduction to Linear Programming\n\nComputational environments provide organizations with the ability to implement solutions to complex time, in real time.  \n\n[Scikit Learn, Pulp, CPLEX, and Gurobi](https://medium.com/opex-analytics/optimization-modeling-in-python-pulp-gurobi-and-cplex-83a62129807a) are  Python packages which provide capabilities for Linear programming and optimization. \n\n\n!pip install pulp\n\n#Import some required packages. \nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n## Product mix problem - Farmers Fields\n\nProblem: How much of each brand to purchase to minimize total cost of fertilizer given following data?\n\nProduct resource requirements and unit profit:\n\nTwo brands of fertilizer available – Super-gro, Crop-quick.\n\nField requires at least 16 pounds of nitrogen and 24 pounds of phosphate.\n\nSuper-gro costs: `$6 per bag` \n\nCrop-quick: `$3 per bag`\n\n\nDecision Variables:\n\n$x_{1}$ = number of bags of Super-gro\n\n$x_{2}$ = number of bags of Crop-quick\n\n\nCost (Z) minimization \n\nZ = 6$x_{1}$ + 3$x_{2}$\n\n\nNitrogen Constraint\n\n2$x_{1}$ + 4$x_{2}$ >= 16\n\nPhosphate Constraint Check\n\n4$x_{1}$ + 3$x_{2}$ >= 24\n\nNon-negativitiy Constraint\n\n$x_{1}$ > 0\n\n$x_{2}$ > 0\n\n\n#Initialize the model as a minimization problem. \nimport pulp as pl\nopt_model = pl.LpProblem(\"MIPModel\", pl.LpMinimize)\n\n\n#Set the variables. Notice this is where we put \n# the \"non-negativity\" constraint\nx1 =pl.LpVariable(cat=pl.LpInteger, lowBound=0, name=\"$x_{1}$\") \nx2 =pl.LpVariable(cat=pl.LpInteger, lowBound=0, name=\"$x_{2}$\") \n\n#Set the objective function\nopt_model += 6 * x1 + 3 * x2 \n\n#Set the Constraints\nopt_model += 2 * x1  + 4* x2  >= 16\n\nopt_model += 4 * x1 + 3 * x2 >= 24\n\n## Review Model\n\nNow that we have created the model we can review it. \n\nopt_model\n\n## Markdown of output\nIf we copy the above text into a markdown cell you will see the implications of the varous models. \n\n\nMIPModel:\n\nMINIMIZE\n\n6*$x_{1}$ + 3*$x_{2}$ + 0\n\nSUBJECT TO\n\n_C1: 2 $x_{1}$ + 4 $x_{2}$ >= 16\n\n_C2: 4 $x_{1}$ + 3 $x_{2}$ >= 24\n\nVARIABLES\n\n0 <= $x_{1}$ Integer\n\n0 <= $x_{2}$ Integer\n\n\n## Solve\n\nWe now solve the system of equations with the solve command. \n\n#Solve the program\nopt_model.solve()\n\n\n## Check the Status\n\nHere are 5 status codes:\n* **Not Solved**: Status prior to solving the problem.\n* **Optimal**: An optimal solution has been found.\n* **Infeasible**: There are no feasible solutions (e.g. if you set the constraints x <= 1 and x >=2).\n* **Unbounded**: The constraints are not bounded, maximising the solution will tend towards infinity (e.g. if the only constraint was x >= 3).\n* **Undefined**: The optimal solution may exist but may not have been found.\n\npl.LpStatus[opt_model.status]\n\nfor variable in opt_model.variables():\n    print(variable.name,\" = \", variable.varValue)\n\n## Hurray! \nWe got the same answer as we did before. \n\n## Exercise\n\nSolve the LP problem for Beaver Creek Pottery using the maximization model type (`pl.LpMaximize`).\n\n\n### Product mix problem - Beaver Creek Pottery Company\nHow many bowls and mugs should be produced to maximize profits given labor and materials constraints?\n\nProduct resource requirements and unit profit:\n\nDecision Variables:\n\n$x_{1}$ = number of bowls to produce per day\n\n$x_{2}$ = number of mugs to produce per day\n\n\nProfit (Z)  Mazimization\n\nZ = 40$x_{1}$ + 50$x_{2}$\n\nLabor Constraint Check\n\n1$x_{1}$ + 2$x_{2}$ <= 40\n\nClay (Physicial Resource) Constraint Check\n\n4$x_{1}$ + 3$x_{2}$ <= 120\n\nNegative Production Constaint Check\n\n$x_{1}$ > 0\n\n$x_{2}$ > 0\n\n\n\n## Sensitivity Analysis\n\nfor name, c in opt_model.constraints.items():\n    print (name, \":\", c, \"\\t\", c.pi, \"\\t\\t\", c.slack)\n\n", "meta": {"hexsha": "64b81c313be346fe5bae73cb7740acaa3c99c7dd", "size": 3686, "ext": "py", "lang": "Python", "max_stars_repo_path": "site/_build/jupyter_execute/notebooks/computational.py", "max_stars_repo_name": "rpi-techfundamentals/website_fall_2020_qm", "max_stars_repo_head_hexsha": "517b24801286140af5f1e10ee9099cf5d0a28b7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "site/_build/jupyter_execute/notebooks/computational.py", "max_issues_repo_name": "rpi-techfundamentals/website_fall_2020_qm", "max_issues_repo_head_hexsha": "517b24801286140af5f1e10ee9099cf5d0a28b7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "site/_build/jupyter_execute/notebooks/computational.py", "max_forks_repo_name": "rpi-techfundamentals/website_fall_2020_qm", "max_forks_repo_head_hexsha": "517b24801286140af5f1e10ee9099cf5d0a28b7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4302325581, "max_line_length": 231, "alphanum_fraction": 0.7086272382, "include": true, "reason": "import numpy", "num_tokens": 1041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.91117969855511, "lm_q1q2_score": 0.8547995518067664}}
{"text": "import numpy as np\n\ndef kmeans(puntos, k):\n    \n    \"\"\"\n    K-means algorithm:\n    Input = A 2D matrix of coordinates we want to make a 2-means clustering.\n    Output = A 2x2 matrix with the resulting means\n    Process = Iteratively assign the coordinates to a certain mean. After all points are assigned, the clustering means are reestimated based on the           \n    points assigned to each of these means.\n    \"\"\"\n\n    eps = 0 # Tolerance for the while \n\n    # Initialization of variables, we initialize with data points\n    centroides = puntos[np.random.choice(puntos.shape[0], size=k, replace=False), :] # Initial means\n    new_centroides = np.zeros((centroides.shape)) \n    \n    aux_matrix = np.zeros((puntos.shape[0], k+1)) # Auxiliary matrix for calulations\n    \n    dif_norm = 1\n    \n    while dif_norm > eps:\n    \n        for idx in range(puntos.shape[0]):\n            aux_matrix[idx,0:k] = np.linalg.norm((puntos[idx,:]-centroides), ord=2, axis=1)\n\n            if len(np.where(aux_matrix[idx,0:k]==np.min(aux_matrix[idx,0:k]))[0]) == 1:\n                aux_matrix[idx, k] = np.where(aux_matrix[idx,0:k]==np.min(aux_matrix[idx,0:k]))[0]\n            else:\n                aux_matrix[idx, k] = np.where(aux_matrix[idx,0:k]==np.min(aux_matrix[idx,0:k]))[0][0]\n\n        for clu in range(k):\n            new_centroides[clu,:] = np.mean(puntos[aux_matrix[:,k]==clu], axis=0)\n\n        dif_norm = np.linalg.norm((centroides-new_centroides), ord=1)\n        centroides = new_centroides\n\n    return centroides \n", "meta": {"hexsha": "495f1774a06902cfa9964585f8c98d767cd01e0a", "size": 1512, "ext": "py", "lang": "Python", "max_stars_repo_path": "paquetes/entregas/shgarrido10/shgarrido10/unsupervised.py", "max_stars_repo_name": "nmejia10/mlandpp-uniandes", "max_stars_repo_head_hexsha": "f1c68f38078d954e1bce56c769214f66b6406470", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-06-27T13:49:43.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-27T18:18:17.000Z", "max_issues_repo_path": "paquetes/entregas/shgarrido10/shgarrido10/unsupervised.py", "max_issues_repo_name": "nmejia10/mlandpp-uniandes", "max_issues_repo_head_hexsha": "f1c68f38078d954e1bce56c769214f66b6406470", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-04T01:40:42.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-10T02:32:35.000Z", "max_forks_repo_path": "paquetes/entregas/shgarrido10/shgarrido10/unsupervised.py", "max_forks_repo_name": "nmejia10/mlandpp-uniandes", "max_forks_repo_head_hexsha": "f1c68f38078d954e1bce56c769214f66b6406470", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38, "max_forks_repo_forks_event_min_datetime": "2018-06-27T11:51:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-01T23:00:42.000Z", "avg_line_length": 37.8, "max_line_length": 159, "alphanum_fraction": 0.6316137566, "include": true, "reason": "import numpy", "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914018751051, "lm_q2_score": 0.8840392924390585, "lm_q1q2_score": 0.8547899849860857}}
{"text": "import numpy as np\nimport math as ma\n\ndef _normalize(v):\n    norm = np.linalg.norm(v)\n    if norm == 0.0:\n       return v\n    return v / norm\n\ndef writhe(curve):\n    '''\n    Returns writhe of given closed parametric curve.\n\n    Parameters\n    ----------\n    curve: np.array\n        An ``N`` by 3 array describing locations of endpoints of ``N`` linear segments approximating the curve. All locations should be distinct.\n\n    Returns\n    -------\n    float\n        Value of writhe for closed curve comprised of linear segments given.\n\n    Example\n    -------\n    >>> import numpy as np\n    >>> curve = np.array([[-1,0,-1],[1,0,1],[0,-1,1],[0,1,1]])\n    >>> pywrithe.writhe(curve)\n    0.366\n\n    '''\n    segments = np.transpose(np.array([np.roll(curve,1,axis=0),curve]),(1,0,2)) # (segment,begin/end,coordinate) order\n    n = len(segments)\n    omegas = np.zeros((n,n))\n    for i in range(n):\n        for j in range(n):\n            if i-j == 0 or i-j == 1 or i-j == -1 or i-j == n-1 or i-j == -n+1:\n                omegas[i][j] = 0\n            else:\n                segment_a = segments[i]\n                segment_b = segments[j]\n                r13 = segment_a[0] - segment_b[0]\n                r14 = segment_a[0] - segment_b[1]\n                r23 = segment_a[1] - segment_b[0]\n                r24 = segment_a[1] - segment_b[1]\n\n                r34 = segment_b[0] - segment_b[1]\n                r12 = segment_a[0] - segment_a[1]\n\n                n1 = _normalize(np.cross(r13,r14))\n                n2 = _normalize(np.cross(r14,r24))\n                n3 = _normalize(np.cross(r24,r23))\n                n4 = _normalize(np.cross(r23,r13))\n\n                d1 = np.clip(np.dot(n1,n2),-1,1)\n                d2 = np.clip(np.dot(n2,n3),-1,1)\n                d3 = np.clip(np.dot(n3,n4),-1,1)\n                d4 = np.clip(np.dot(n4,n1),-1,1)\n\n                a1 = ma.asin(d1)\n                a2 = ma.asin(d2)\n                a3 = ma.asin(d3)\n                a4 = ma.asin(d4)\n\n                omega_star = (a1+a2+a3+a4)\n\n                omega = omega_star * ma.copysign(1.0, np.dot( np.cross( r34, r12) , r13) )\n\n                omegas[i][j] = omega\n\n    #print(omegas)\n\n    return (1.0 / (4.0 * ma.pi)) * np.sum(omegas)\n\n\n\n", "meta": {"hexsha": "d85926f0b904818514fa4c9f3dea5b1548862764", "size": 2210, "ext": "py", "lang": "Python", "max_stars_repo_path": "pywrithe/writhe.py", "max_stars_repo_name": "RadostW/PyWrithe", "max_stars_repo_head_hexsha": "ead9e0ac1df082618c1ac95977bc69285a1f2b07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pywrithe/writhe.py", "max_issues_repo_name": "RadostW/PyWrithe", "max_issues_repo_head_hexsha": "ead9e0ac1df082618c1ac95977bc69285a1f2b07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pywrithe/writhe.py", "max_forks_repo_name": "RadostW/PyWrithe", "max_forks_repo_head_hexsha": "ead9e0ac1df082618c1ac95977bc69285a1f2b07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7012987013, "max_line_length": 145, "alphanum_fraction": 0.4909502262, "include": true, "reason": "import numpy", "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140254249554, "lm_q2_score": 0.8840392817460332, "lm_q1q2_score": 0.8547899805468433}}
{"text": "import math\r\nimport numpy as np\r\ndef derivative(f):\r\n    '''returns a function that is the derivative of f with respect to x'''\r\n    def dfdx(x):\r\n        epsilon = 1e-3\r\n        df = f(x+epsilon) - f(x-epsilon)\r\n        dx = 2*epsilon\r\n        return df/dx\r\n    return dfdx\r\ndef integrate(f,a,b):\r\n    '''returns definite integral of f(x) with respect to x from a to b\r\n    uses average of left, right, and trapezoidal riemann sum.\r\n    might not work with vertical asymptotes'''\r\n    epsilon = 1e-3\r\n    samples = ( max(a,b)-min(a,b) ) / epsilon\r\n    X = np.linspace(min(a,b),max(a,b),samples)\r\n    left = 0\r\n    for x in X[:-1]:\r\n        left += f(x) * epsilon\r\n    right = 0\r\n    for x in X[1:]:\r\n        right += f(x) * epsilon\r\n    trap = 0\r\n    for i in range(len(X)-1):\r\n        trap += .5 * ( f(X[i]) + f(X[i+1]) ) * epsilon\r\n    ans = (left+right+trap) / 3\r\n    if b > a:\r\n        return ans\r\n    return -1 * ans\r\ndef firstOrderODE(dydx,xi,yi,xf):\r\n    '''expects dydx(x,y) and (xi,yi) which is the initial condition\r\n    example: firstOrderODE(f(x,y),2,1)\r\n    uses euler approximation'''\r\n    ic = (xi,yi)\r\n    dx = .001\r\n    X = []\r\n    Y = []\r\n    x = ic[0]\r\n    y = ic[1]\r\n    while x < xf and y < 1e99:\r\n        dy = dydx(x,y)*dx\r\n        x += dx\r\n        y += dy\r\n    return y\r\nif __name__ == '__main__':\r\n    #for testing\r\n    def f(x,y):\r\n        return x+y\r\n    print(firstOrderODE(f,2,1,6))\r\n", "meta": {"hexsha": "c21075dbcbebdf1e4ad9a034a5174d629b393f76", "size": 1413, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/mylib/calculus.py", "max_stars_repo_name": "quasarbright/quasarbright.github.io", "max_stars_repo_head_hexsha": "942710adf4a2531d033023a6f750efeddf3e9050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-23T13:50:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-23T13:50:34.000Z", "max_issues_repo_path": "python/mylib/calculus.py", "max_issues_repo_name": "quasarbright/quasarbright.github.io", "max_issues_repo_head_hexsha": "942710adf4a2531d033023a6f750efeddf3e9050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2018-02-19T19:37:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T18:34:22.000Z", "max_forks_repo_path": "python/mylib/calculus.py", "max_forks_repo_name": "quasarbright/quasarbright.github.io", "max_forks_repo_head_hexsha": "942710adf4a2531d033023a6f750efeddf3e9050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-12-07T03:07:21.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-07T03:07:21.000Z", "avg_line_length": 27.7058823529, "max_line_length": 75, "alphanum_fraction": 0.52512385, "include": true, "reason": "import numpy", "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140235181256, "lm_q2_score": 0.8840392817460333, "lm_q1q2_score": 0.854789978861131}}
{"text": "# Exercise 6\n# Verify that the CDF inversion formula for the generation of exponential random variates of average value equal\n# to 2 actually generates exponential variates.\n# 1. Extract Ntr exponential random variates with the same average value equal to 2 using through the CDF inversion method.\n# 2. Draw a QQ-plot to compare your draws against the quantiles of the exponential distribution with the same average value.\n# 3. What happens if, instead, you draw your QQ-plot against the quantiles of an exponential distribution with a different average value?\n# And what if you increase (e.g., 2×, 4×, . . . ) the number of exponential draws? Discuss.\n\n# import\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom numpy import mean, min, max, median, quantile\nfrom scipy.stats import binom, norm, t as student, expon, poisson, chi2\nfrom math import sqrt, pow, floor, ceil, exp, log\nfrom statsmodels.api import qqplot\n\nNtr = 10000\n# use the inverted cdf: x = - ln(U) / mean\naverage = 2\nlam = 1 / average  # lambda = 1/avarage\nresults = -np.log(np.random.rand(Ntr)) / lam\nplt.hist(results, bins=20)\n\n# draw qq plot\nqqplot(results, dist=expon, scale=1 / lam, line='45')\n\n# draw qq against different average values: 5 and 0.5\nqqplot(results, dist=expon, scale=5, line='45')\nqqplot(results, dist=expon, scale=0.5, line='45')\n\n# try with more draws (x2, x4, x20)\nNtr_2 = Ntr * 2\nresults = -np.log(np.random.rand(Ntr_2)) / lam\nqqplot(results, dist=expon, scale=1 / lam, line='45')\n\nNtr_4 = Ntr * 4\nresults = -np.log(np.random.rand(Ntr_4)) / lam\nqqplot(results, dist=expon, scale=1 / lam, line='45')\n\nNtr_20 = Ntr * 20\nresults = -np.log(np.random.rand(Ntr_20)) / lam\nqqplot(results, dist=expon, scale=1 / lam, line='45')\n\nNtr_1_100 = Ntr // 100\nresults = -np.log(np.random.rand(Ntr_1_100)) / lam\nqqplot(results, dist=expon, scale=1 / lam, line='45')\n\nplt.show()", "meta": {"hexsha": "2fcbda4d01599b00bc8aaf91b4da495f16bb5d1a", "size": 1863, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW2/ex6.py", "max_stars_repo_name": "andreamatt/Simulation-homeworks", "max_stars_repo_head_hexsha": "d6e987a99498c0a30bfd8d3d9deeb3c0382a27be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW2/ex6.py", "max_issues_repo_name": "andreamatt/Simulation-homeworks", "max_issues_repo_head_hexsha": "d6e987a99498c0a30bfd8d3d9deeb3c0382a27be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW2/ex6.py", "max_forks_repo_name": "andreamatt/Simulation-homeworks", "max_forks_repo_head_hexsha": "d6e987a99498c0a30bfd8d3d9deeb3c0382a27be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8125, "max_line_length": 137, "alphanum_fraction": 0.7246376812, "include": true, "reason": "import numpy,from numpy,from scipy,from statsmodels", "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914018751051, "lm_q2_score": 0.8840392817460333, "lm_q1q2_score": 0.8547899746468497}}
{"text": "import numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\nfrom abc import ABC, abstractmethod # for later\n\ndef derive(y,t,N, beta, gamma):        \n    \"\"\"The SIR model differential equations.\"\"\"\n\n    S, I, R = y\n    dSdt = -beta * S * I / N\n    dIdt = beta * S * I / N - gamma * I \n    dRdt = gamma * I\n    return dSdt, dIdt, dRdt\n    \nclass SIR:\n    \n    def __init__(self, N=1000, I0=1, R0=0, beta=0.4, gamma=1./10, days=250):\n        \"\"\"Setup for the model.\n        \n        N:     Total population, N.\n        I0,R0: Initial number of infected and recovered individuals.\n        beta:  Contact rate, beta, \n        gamma: Mean recovery rate,(in 1/days).\n        t:     A grid of time points (in days)\n        \"\"\"\n        \n        self.N  = N\n        self.I0 = I0\n        self.R0 = R0\n        self.S = 0\n        self.I = 0\n        self.R = 0\n        self.beta = beta\n        self.gamma = gamma\n        self.t = np.linspace(0, days, days) \n    \n    def projection(self):\n        \"\"\"Expected change in the disease's distribution in the population. \"\"\"\n        \n        S0 = self.N - self.I0 - self.R0 # Everyone else, S0, is susceptible to infection initially.\n        # Initial conditions vector\n        y0 = S0, self.I0, self.R0\n        # Integrate the SIR equations over the time grid, t.\n        ret = odeint(derive, y0, self.t, args=(self.N, self.beta, self.gamma))\n        self.S, self.I, self.R = ret.T\n\n    def plot_projection(self):\n        \"\"\"Plot the data on three separate curves for S(t), I(t) and R(t)\"\"\"\n        \n        fig = plt.figure(facecolor='w')\n        ax = fig.add_subplot(111, facecolor='#dddddd', axisbelow=True)\n        ax.plot(self.t, self.S/1000, 'b', alpha=0.5, lw=2, label='Susceptible')\n        ax.plot(self.t, self.I/1000, 'r', alpha=0.5, lw=2, label='Infected')\n        ax.plot(self.t, self.R/1000, 'g', alpha=0.5, lw=2, label='Recovered with immunity')\n        ax.set_xlabel('Time /days')\n        ax.set_ylabel('Number (1000s)')\n        ax.set_ylim(0,1.2)\n        ax.yaxis.set_tick_params(length=0)\n        ax.xaxis.set_tick_params(length=0)\n        ax.grid(b=True, which='major', c='w', lw=2, ls='-')\n        legend = ax.legend()\n        legend.get_frame().set_alpha(0.5)\n        for spine in ('top', 'right', 'bottom', 'left'):\n            ax.spines[spine].set_visible(False)\n        plt.show()\n        \nclass City(SIR):\n    \n    def __init__(self, name, position, area, air, port):\n        super().__init__()\n        self.name = name\n        self.position = position\n        self.area = area\n        self.air = air\n        self.port = port\n    \n    def get_name(self):\n        return self.name\n    \n    def get_position(self):\n        return self.position\n    \n    def __str__(self):\n        return str(self.__dict__)", "meta": {"hexsha": "d4ec4129cbcc0c0819c88ddcbe7e1df0cc69da96", "size": 2784, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/City.py", "max_stars_repo_name": "DorenCalliku/distribution", "max_stars_repo_head_hexsha": "673063e51d1be725325969dfdab1b7f4e48b0fa6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/City.py", "max_issues_repo_name": "DorenCalliku/distribution", "max_issues_repo_head_hexsha": "673063e51d1be725325969dfdab1b7f4e48b0fa6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/City.py", "max_forks_repo_name": "DorenCalliku/distribution", "max_forks_repo_head_hexsha": "673063e51d1be725325969dfdab1b7f4e48b0fa6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1428571429, "max_line_length": 99, "alphanum_fraction": 0.5617816092, "include": true, "reason": "import numpy,from scipy", "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140235181257, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.854789968521894}}
{"text": "## Do prime factorization\nimport numpy as np\n    \ndef isprime(p):\n    \"\"\" returns boolean whether p > 1 is prime or not based on fermat test.\"\"\"\n    if p == 2 or p == 3:\n        return True\n    \n    elif (p % 2 == 0) or (p % 3 == 0):\n        return False\n    \n    else:\n        # fermat test\n        i = 0\n        k = 8   # amount of randomly picked numbers at max\n        a = 2   # always do the fermat test with base 2\n        while i < k:\n            if a**(p-1) % p == 1:   # fermat test successful\n                i += 1\n            else:                   # fermat test failed, hence no prime\n                return False\n                \n            # randomly pick new base\n            a = np.random.randint(2,p-1)\n                \n        return True\n\ndef prime_factors(N):\n    \"\"\" returns the prime factors of a given number N. Divides iteratively by an increasing sequence of prime numbers. \"\"\"\n    i = 2\n    factors = []\n    \n    if isprime(N):  # initial prime number test\n        factors.append(N)\n        return factors\n\n    while True: \n        while N/i % 1 == 0:\n            factors.append(i)\n            #print(i)\n            N = int(N/i)\n            if N == 1:\n                return factors\n                \n            if isprime(N):  # checks whether the new N might be prime\n                factors.append(N)\n                return factors\n    \n        i += 1\n        # to find the next prime number\n        while isprime(i) == False: \n            i += 1\n           \ndef primelist(N):\n    \"\"\" returns a list of the first N prime numbers. \"\"\"\n    \n    v = [2] # first prime number\n    i = 3   # start with prime 3\n    \n    # loop through all odd numbers and check whether they are prime based on isprime function\n    while len(v) < N:\n        if isprime(i):\n            v.append(i)\n            \n        i += 2\n    \n    return v\n    \n\n        ", "meta": {"hexsha": "109c7052babdc2453a22cb8f1f976064a1c375ce", "size": 1865, "ext": "py", "lang": "Python", "max_stars_repo_path": "project_euler/primetest.py", "max_stars_repo_name": "milankl/misc", "max_stars_repo_head_hexsha": "40c74d927e6d18b44a6edb51bffda85cafb347e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-04T11:43:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-04T11:43:34.000Z", "max_issues_repo_path": "project_euler/primetest.py", "max_issues_repo_name": "milankl/misc", "max_issues_repo_head_hexsha": "40c74d927e6d18b44a6edb51bffda85cafb347e1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project_euler/primetest.py", "max_forks_repo_name": "milankl/misc", "max_forks_repo_head_hexsha": "40c74d927e6d18b44a6edb51bffda85cafb347e1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-05-04T11:43:47.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-04T11:43:47.000Z", "avg_line_length": 26.6428571429, "max_line_length": 122, "alphanum_fraction": 0.4798927614, "include": true, "reason": "import numpy", "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9759464464059648, "lm_q2_score": 0.8757870013740061, "lm_q1q2_score": 0.8547212117994971}}
{"text": "## given probability of winning a best-of-three-set match and the assumption that sets are independent,\n## output the probability of winning a best-of-five-set match\n \n##One way to find the probability of winning an n-set match is to start with the probability of winning\n##a single set.  If we have an estimated probability of winning a best-of-three, e.g. from betting odds,\n##we need to work backwards to get the probability of winning a single set.\n##\n##If x is p(set win), the probability of winning a three-setter is:\n##    x^2 + 2(x^2)(1-x)\n##    x^2 is the p(winning in straight sets)\n##    (x^2)(1-x) is the p(winning two sets and losing one)\n##    and there are 2 permutations (LWW and WLW) that result in a three-set win\n##\n##Written another way, we have:\n##    p(three-set-win) = -2x^3 + 3x^2\n##    or: -2x^3 + 3x^2 - p(three-set-win) = 0\n##\n##The first line of the function solves the trinomial for the relevant root.  \n##The second line uses similar logic to generate the probability of winning a five-setter:\n##    x^3 --- p(straight-set-win)\n##    3(x^3)(1-x) --- p(four-set-win): three sets won, one set lost, three permutations\n##    6(x^3)(1-x)(1-x) --- p(five-set-win): two sets lost, six permutations (4c2)\n \nimport numpy\n \ndef fiveodds(p3):\n    p1 = numpy.roots([-2, 3, 0, -1*p3])[1]\n    p5 = (p1**3)*(4 - 3*p1 + (6*(1-p1)*(1-p1)))\n    return p5\n", "meta": {"hexsha": "d9c92481090e448a5c7d4606a730153ad59afb90", "size": 1368, "ext": "py", "lang": "Python", "max_stars_repo_path": "build_datasets/sackmann/fiveSetProb.py", "max_stars_repo_name": "JingyaXun/tennis_match_prediction", "max_stars_repo_head_hexsha": "6278a5f5898ca68341b80ed7f069b34ed1f61eb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2018-08-29T13:28:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T17:56:45.000Z", "max_issues_repo_path": "build_datasets/sackmann/fiveSetProb.py", "max_issues_repo_name": "JingyaXun/tennis_match_prediction", "max_issues_repo_head_hexsha": "6278a5f5898ca68341b80ed7f069b34ed1f61eb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-18T18:19:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T18:19:01.000Z", "max_forks_repo_path": "src/sackmann/fiveSetProb.py", "max_forks_repo_name": "jgollub1/tennis_match_prediction", "max_forks_repo_head_hexsha": "1ccf0ecd5ddb5d98da2d3610e4890fcab844dfcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-01-02T21:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T17:56:47.000Z", "avg_line_length": 45.6, "max_line_length": 104, "alphanum_fraction": 0.6652046784, "include": true, "reason": "import numpy", "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.974042647323258, "lm_q2_score": 0.8774767874818408, "lm_q1q2_score": 0.85469981304352}}
{"text": "import math\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\na = -5\nb = 5\nN = 9\nstep = (b - a) / N\n\n\ndef test_function1(x):\n    return 4.0 ** x\n\n\ndef test_function2(x):\n    return math.cos(x)\n\n\ndef get_chebyshev_nulls_points():\n    return np.array([(a + b) / 2 + (b - a) * math.cos((2 * k + 1) * math.pi / (2 * N)) / 2 for k in range(N)])\n\n\ndef get_equally_distant_points():\n    return np.array(np.arange(-step * (N // 2), step * (N // 2) + 1, step))\n\n\ndef calculate_separated_difference(x_array, y_array, i, j):\n    return (y_array[j+1] - y_array[j]) / (x_array[i+j+1] - x_array[j])\n\n\ndef generate_template_polynomial():\n    koef_template = \"fx.$\"\n    bracket_template = \"(x-x$)\"\n    polynomial = \"\"\n    for i in range(N):\n        polynomial += koef_template.replace(\"$\", str(i))\n        for j in range(i):\n            polynomial += \"*\" + bracket_template.replace(\"$\", str(j))\n        if i < N-1:\n            polynomial += \" + \"\n    return polynomial\n\n\ndef newton_polynomial(x_points, y_points):\n    polynomial = generate_template_polynomial()\n    # print(polynomial)\n    koef = [y_points[0]]\n    prev_separated_differences = y_points\n    for i in range(N-1):\n        separated_differences = []\n        for j in range(N-i-1):\n            separated_differences.append(calculate_separated_difference(x_points, prev_separated_differences, i, j))\n        koef.append(separated_differences[0])\n        prev_separated_differences = separated_differences\n    for i in range(N):\n        polynomial = polynomial.replace(f\"fx.{i}\", str(koef[i]))\n        polynomial = polynomial.replace(f\"x{i}\", str(x_points[i]))\n    print(polynomial)\n    return polynomial\n\n\nif __name__ == \"__main__\":\n    function = test_function2\n    chebyshev_points = get_chebyshev_nulls_points()\n    eq_d_points = get_equally_distant_points()\n    chebyshev_values = np.array([function(x) for x in chebyshev_points])\n    eq_d_values = np.array([function(x) for x in eq_d_points])\n\n    chebyshev_poly = newton_polynomial(chebyshev_points, chebyshev_values)\n    eq_d_poly = newton_polynomial(eq_d_points, eq_d_values)\n\n    x_new = np.arange(a, b, 0.1)\n    chebyshev_y = []\n    eq_d_y = []\n    for x in x_new:\n        chebyshev_y.append(eval(chebyshev_poly))\n        eq_d_y.append(eval(eq_d_poly))\n\n    fig, axs = plt.subplots(1, figsize=(8, 8))\n    axs.plot(x_new, eq_d_y, 'b', label='Equally distant')\n    axs.plot(x_new, chebyshev_y, 'g', label='Chebyshev')\n    axs.plot(x_new, np.array([function(x) for x in x_new]), 'r', label='Function')\n    fig.suptitle('Newton Polynomials')\n    plt.show()\n", "meta": {"hexsha": "bb4158462a303ea14116790cc434ee6b9b6cb562", "size": 2561, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumericalMethods/lab_4/main.py", "max_stars_repo_name": "fivard/Third_course", "max_stars_repo_head_hexsha": "fe0a331ab5e54ac31ccb0650b6b3a03ad3ab4cf9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NumericalMethods/lab_4/main.py", "max_issues_repo_name": "fivard/Third_course", "max_issues_repo_head_hexsha": "fe0a331ab5e54ac31ccb0650b6b3a03ad3ab4cf9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumericalMethods/lab_4/main.py", "max_forks_repo_name": "fivard/Third_course", "max_forks_repo_head_hexsha": "fe0a331ab5e54ac31ccb0650b6b3a03ad3ab4cf9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7790697674, "max_line_length": 116, "alphanum_fraction": 0.6493557204, "include": true, "reason": "import numpy", "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426405416754, "lm_q2_score": 0.8774767890838836, "lm_q1q2_score": 0.8546998086532968}}
{"text": "# some useful Activation function used in Deep Learning Algorithms\n\n# function 1 - Logistic Sigmoid\n\ndef logistic_sigmoid(x):\n    sigma = 1/(1 + exp(-x))\n    return sigma\n#range - (0,1)\n\n#function 2 - tanh function\n# precisely can be denoted as g(Z) = tanh(Z)\n\ndef tanh(x):\n    numerator = exp(x) - exp(-x)\n    denominator = exp(x) + exp(x)\n    result = numerator/denominator\n    return result\n# best suitable for symmeteric cases\n    \n# function 3 - ReLu\n\ndef relu(x):\n    ReLu = max(0,x)\n    return ReLu\n\n#range - [0,x)\n# also if x >= 0 derivative of ReLu will be 1 else it will be 0\n\n#function - 4 leaky_ReLu\n\ndef leaky_relu(x):\n    leaky_ReLu = max(0.01*x, x)\n    return leaky_ReLu\n# we can change multiplying factor in order to increase precision. Here it is 0.01 it can be taken as 0.0001\n# leaky_ReLu helps to gather some values which got vanished to 0 instead it provides them some negligible values\n\n#function - 5 Softplus\n\n#this function is introduced to overcome faults of leaky_ReLu\n#Also known as Smoothened or Softened function (presence of smooth curve instead of joint in Relu or Leaky ReLu)\n\nimport numpy as np\ndef softplus(x):\n    sfplus = np.log(1 + exp(x))\n    return sfplus\n\n#some more relation bw derivates of Activation function or bw Activation functions are included in other file.    \n", "meta": {"hexsha": "29b6fc6d77b2810e1bc43ba3a9049593fb15fbbb", "size": 1311, "ext": "py", "lang": "Python", "max_stars_repo_path": "Activation_Functions.py", "max_stars_repo_name": "akhilsinghyadav/Deep-Learning", "max_stars_repo_head_hexsha": "b3e4315289b8e8a5e4e4d92d386856285c38530f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Activation_Functions.py", "max_issues_repo_name": "akhilsinghyadav/Deep-Learning", "max_issues_repo_head_hexsha": "b3e4315289b8e8a5e4e4d92d386856285c38530f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Activation_Functions.py", "max_forks_repo_name": "akhilsinghyadav/Deep-Learning", "max_forks_repo_head_hexsha": "b3e4315289b8e8a5e4e4d92d386856285c38530f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3125, "max_line_length": 114, "alphanum_fraction": 0.7124332571, "include": true, "reason": "import numpy", "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.974042648076767, "lm_q2_score": 0.8774767810736692, "lm_q1q2_score": 0.8546998074628743}}
{"text": "from numpy import mgrid, sum\nimport cv2\n\ndef moments2e(image):\n  \"\"\"\n  This function calculates the raw, centered and normalized moments\n  for any image passed as a numpy array.\n\n  Further reading:\n  https://en.wikipedia.org/wiki/Image_moment\n  https://en.wikipedia.org/wiki/Central_moment\n  https://en.wikipedia.org/wiki/Moment_(mathematics)\n  https://en.wikipedia.org/wiki/Standardized_moment\n  http://opencv.willowgarage.com/documentation/cpp/structural_analysis_and_shape_descriptors.html#cv-moments\n\n  compare with:\n  import cv2\n  cv2.moments(image)\n\n  \"\"\"\n  assert len(image.shape) == 2 # only for grayscale images\n  x, y = mgrid[:image.shape[0],:image.shape[1]]\n  moments = {}\n  moments['mean_x'] = sum(x*image)/sum(image)\n  moments['mean_y'] = sum(y*image)/sum(image)\n\n  # raw or spatial moments\n  moments['m00'] = sum(image)\n  moments['m01'] = sum(x*image)\n  moments['m10'] = sum(y*image)\n  moments['m11'] = sum(y*x*image)\n  moments['m02'] = sum(x**2*image)\n  moments['m20'] = sum(y**2*image)\n  moments['m12'] = sum(x*y**2*image)\n  moments['m21'] = sum(x**2*y*image)\n  moments['m03'] = sum(x**3*image)\n  moments['m30'] = sum(y**3*image)\n\n  # central moments\n  # moments['mu01']= sum((y-moments['mean_y'])*image) # should be 0\n  # moments['mu10']= sum((x-moments['mean_x'])*image) # should be 0\n  moments['mu11'] = sum((x-moments['mean_x'])*(y-moments['mean_y'])*image)\n  moments['mu02'] = sum((y-moments['mean_y'])**2*image) # variance\n  moments['mu20'] = sum((x-moments['mean_x'])**2*image) # variance\n  moments['mu12'] = sum((x-moments['mean_x'])*(y-moments['mean_y'])**2*image)\n  moments['mu21'] = sum((x-moments['mean_x'])**2*(y-moments['mean_y'])*image)\n  moments['mu03'] = sum((y-moments['mean_y'])**3*image)\n  moments['mu30'] = sum((x-moments['mean_x'])**3*image)\n\n  # opencv versions\n  #moments['mu02'] = sum(image*(x-m01/m00)**2)\n  #moments['mu02'] = sum(image*(x-y)**2)\n\n  # wiki variations\n  #moments['mu02'] = m20 - mean_y*m10\n  #moments['mu20'] = m02 - mean_x*m01\n\n  # central standardized or normalized or scale invariant moments\n  moments['nu11'] = moments['mu11'] / sum(image)**(2/2+1)\n  moments['nu12'] = moments['mu12'] / sum(image)**(3/2+1)\n  moments['nu21'] = moments['mu21'] / sum(image)**(3/2+1)\n  moments['nu20'] = moments['mu20'] / sum(image)**(2/2+1)\n  moments['nu03'] = moments['mu03'] / sum(image)**(3/2+1) # skewness\n  moments['nu30'] = moments['mu30'] / sum(image)**(3/2+1) # skewness\n  return moments\n\nim = cv2.imread(\"fudge.png\", cv2.CV_LOAD_IMAGE_GRAYSCALE)\nprint moments2e(im)\n", "meta": {"hexsha": "80ffd3ecaeaae6aa9dafba26c374529e3358dd70", "size": 2519, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/fixtures/python/python.py", "max_stars_repo_name": "m0ose/image-moments", "max_stars_repo_head_hexsha": "ed84029afee6ae762f8b7bede8b3d4892afa037d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/fixtures/python/python.py", "max_issues_repo_name": "m0ose/image-moments", "max_issues_repo_head_hexsha": "ed84029afee6ae762f8b7bede8b3d4892afa037d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/fixtures/python/python.py", "max_forks_repo_name": "m0ose/image-moments", "max_forks_repo_head_hexsha": "ed84029afee6ae762f8b7bede8b3d4892afa037d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5072463768, "max_line_length": 108, "alphanum_fraction": 0.6538308853, "include": true, "reason": "from numpy", "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426450627306, "lm_q2_score": 0.8774767826757123, "lm_q1q2_score": 0.8546998063785857}}
{"text": "import pandas as pd\nimport numpy as np\nfrom datetime import datetime\nfrom scipy import optimize\nfrom scipy import integrate\n%matplotlib inline\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\ndef SIR_model(SIR,beta,gamma,N0):\n    '''Here's the simple SIR model\n        S - susceptible population; I - infected population; R - recovered population\n        beta - infection rate; gamma - recovery rate; N0 - Total population\n        And then the overall condition is as below\n        overall condition is that the sum of changes (differnces) sum up to 0\n        dS+dI+dR=0\n        S+I+R= N (constant size of population)\n\n     Parameters are:\n        SIR - numpy.ndarray; beta - float; gamma - float\n    '''\n\n    S,I,R = SIR\n    dS_dt=-beta*S*I/N0\n    dI_dt=beta*S*I/N0-gamma*I\n    dR_dt=gamma*I\n    return(dS_dt,dI_dt,dR_dt)\n\nif __name__ == '__main__':\n    pd_JH_data=pd.read_csv('data/processed/COVID_relational_confirmed.csv',sep=';',parse_dates=[0])\n    pd_JH_data=pd_JH_data.sort_values('date',ascending=True).copy()\n", "meta": {"hexsha": "3ec690293e70d2c61894c8d47d8266ff10fad69d", "size": 1028, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/features/build_features_sir.py", "max_stars_repo_name": "MJSRGithub/MJSR_Applied_Data_Science", "max_stars_repo_head_hexsha": "97f870aace22cb67056a0a1df0a91968763dd787", "max_stars_repo_licenses": ["FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/features/build_features_sir.py", "max_issues_repo_name": "MJSRGithub/MJSR_Applied_Data_Science", "max_issues_repo_head_hexsha": "97f870aace22cb67056a0a1df0a91968763dd787", "max_issues_repo_licenses": ["FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/features/build_features_sir.py", "max_forks_repo_name": "MJSRGithub/MJSR_Applied_Data_Science", "max_forks_repo_head_hexsha": "97f870aace22cb67056a0a1df0a91968763dd787", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.125, "max_line_length": 99, "alphanum_fraction": 0.6974708171, "include": true, "reason": "import numpy,from scipy", "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426465697488, "lm_q2_score": 0.8774767746654976, "lm_q1q2_score": 0.8546997998986684}}
{"text": "from sympy.abc import x\nimport sympy as sp\nimport numpy as np\n\n\ndef split(inte, n):\n    \"\"\" Split the interval into n subintervals.\n    \n    Args:\n        inte: list/ndarray, the interval to be splited\n        n: int, the number of interpolation points\n\n    Returns:\n        t: ndarray, the split of the given interval\n    \"\"\"\n    # endpoints of the interval\n    a, b = inte\n    # split\n    t = np.linspace(a, b, n+1)\n    return t\n\n\ndef second_order_difference(t, y):\n    \"\"\" Calculate the second order difference.\n\n    Args:\n        t: ndarray, the list of the three independent variables\n        y: ndarray, three values of the function at every t\n\n    Returns:\n        double: the second order difference of given points\n    \"\"\"\n    # claculate the first order difference\n    first_order_difference = (y[1:] - y[:-1]) / (t[1:] - t[:-1])\n    return (first_order_difference[1] - first_order_difference[0]) / (t[2] - t[0])\n\n\ndef cubic_spline_interpolation(t, y, diff_list):\n    \"\"\" Cubic spline interpoaltion with I boundary conditions.\n\n    \"\"\"\n    # number of the points\n    n = len(t)\n    # calculate the steps\n    h = t[1:] - t[:-1]\n\n    # initialize\n    D = np.zeros((n, n))\n    d = np.zeros(n)\n    # calculate the elements in matrix D\n    for i in range(n):\n        if i == 0:\n            D[0, 0] = 2\n            D[0, 1] = 1\n        elif i == n-1:\n            D[n-1, n-2] = 1\n            D[n-1, n-1] = 2\n        else:\n            D[i, i-1] = h[i-1] / (h[i-1] + h[i]) # mu\n            D[i, i] = 2\n            D[i, i+1] = h[i] / (h[i-1] + h[i])   # lambda\n\n    # calculate the elements in vector d\n    for i in range(n):\n        if i == 0:\n            # repeat node difference quotient\n            d[i] = 6 * ((y[1] - y[0])/(t[1] - t[0]) - diff_list[0]) / (t[1] - t[0])\n        elif i == n-1:\n            # repeat node difference quotient\n            d[i] = 6 * (diff_list[1] - (y[n-1] - y[n-2])/(t[n-1] - t[n-2])) / (t[n-1] - t[n-2])\n        else:\n            d[i] = 6 * second_order_difference(t[i-1:i+2], y[i-1:i+2])\n\n    # get M by solving the equation DM=d\n    M = np.linalg.solve(D, d)\n\n    # iteraton\n    S = []\n    for i in range(n-1):\n        s = M[i] * (t[i+1] - x)**3 / 6 / h[i]\n        s += M[i+1] * (x - t[i])**3 / 6 / h[i]\n        s += (y[i] - M[i] * h[i]**2 / 6) * (t[i+1] - x) / h[i]\n        s += (y[i+1] - M[i+1] * h[i]**2 / 6) * (x - t[i]) / h[i]\n        S.append((sp.simplify(s), sp.And(x>=t[i], x<=t[i+1])))\n\n    return sp.Piecewise(*S)\n\n\ndef f(x):\n    return 1 / (1 + x**2)\n\n\ndef draw_cubic_spline_interpolation(inte, func, n_lst):\n    \"\"\" Draw figure of the function's cubic spline interpolation for various endpoints.\n\n    Args:\n        inte: list/ndarray, the interpolation itnerval\n        func: function object, the function to be interpolated\n        n_lst: list/ndarray, list of the endpoints number\n    \"\"\"\n    # draw the original function fugure\n    fig = sp.plot(func(x), (x, -5, 5), line_color='r', label='Original Function', legend=True, show=False)\n    # control color\n    i = 0\n    colors_lst = ['b', 'y', 'g']\n\n    for n in n_lst:\n        t = split(inte, n)\n        y = cubic_spline_interpolation(t, func(t), [5/338, -5/338])\n        # output\n        print(f\"The interpoaltion polinomial with n={n} is:\")\n        print(y)\n        # draw\n        color = colors_lst[i]\n        i += 1\n        p = sp.plot(y, (x, -5, 5), line_color=color, label=f'n={n}', legend=True, show=False)\n        fig.extend(p)\n\n    # save figure\n    fig.save('cubic_spline_interpolation.png')\n\n\n\nif __name__ == '__main__':\n    inte = [-5, 5]\n    n_lst = [5, 10, 20]\n\n    draw_cubic_spline_interpolation(inte, f, n_lst)\n\n", "meta": {"hexsha": "8062ad18daaf9699d35406ec48b877f8b6be5ede", "size": 3631, "ext": "py", "lang": "Python", "max_stars_repo_path": "InterpolationAndFitting/cubic_spline_interpolation.py", "max_stars_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_stars_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "InterpolationAndFitting/cubic_spline_interpolation.py", "max_issues_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_issues_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "InterpolationAndFitting/cubic_spline_interpolation.py", "max_forks_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_forks_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9307692308, "max_line_length": 106, "alphanum_fraction": 0.530707794, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.9059898184796792, "lm_q1q2_score": 0.8546633008444566}}
{"text": "# one stock -> simple return is common but not for many\n# $$\n# \\frac{P_1 - P_0}{P_0} = \\frac{P_1}{P_0} - 1\n# $$\nimport numpy as np\nimport pandas as pd\nfrom pandas_datareader import data as wb\nimport matplotlib.pyplot as plt\n'''from AssetTypes.BaseAsset import BaseAsset\nfrom AssetTypes.EquityShare import EquityShare\nfrom AssetTypes.GovernmentBond import GovernmentBond'''\nPG = wb.DataReader('PG', data_source='yahoo', start='1995-1-1')\n# with iex key`\n# PG = wb.DataReader('PG', data_source='iex', start='2015-1-1')\n# csv\n# PG = pd.read_csv('Section-11_PG_1995-03_23_2017.csv')\n# PG = PG.set_index('Date')\n# calculate simple return\nPG['simple_return'] = (PG['Adj Close'] / PG['Adj Close'].shift(1)) - 1\nprint(PG['simple_return'])\n# plot simple return\nPG['simple_return'].plot(figsize=(8, 5))\n# plt.show()\n# Calculate the simple average daily return.\navg_returns_d = PG['simple_return'].mean()\n# Estimate the simple average annual return.\navg_returns_a = PG['simple_return'].mean() * 250\n# Print the simple percentage version of the result as a float with 2 digits after the decimal point.\nprint (str(round(avg_returns_a, 5) * 100) + ' %')\n# calculate log return\nPG['log_return'] = np.log(PG['Adj Close'] / PG['Adj Close'].shift(1))\nprint (PG['log_return'])\n# plot log return\nPG['log_return'].plot(figsize=(8, 5))\n# plt.show()\n# Calculate the log average daily return.\navg_returns_d = PG['log_return'].mean()\n# Estimate the log average annual return.\navg_returns_a = PG['log_return'].mean() * 250\n# Print the log percentage version of the result as a float with 2 digits after the decimal point.\nprint (str(round(avg_returns_a, 5) * 100) + ' %')\n#\nimport quandl\n#\nmydata_01 = quandl.get(\"FRED/GDP\")\nmydata_01.tail()\nmydata_01.head()\nmydata_01.to_csv('Section-10_57-ImportingandOrganizingYourDatainPython-PartIII-Data_01.csv')\nmydata_01 = pd.read_csv('Section-10_57-ImportingandOrganizingYourDatainPython-PartIII-Data_01.csv', index_col='Date')\nmydata_01.tail()\nmydata_01 = pd.read_csv('Section-10_57-ImportingandOrganizingYourDatainPython-PartIII-Data_01.csv')\nmydata_01.tail()\nmydata_01.set_index('Date')\nmydata_01.tail()\nmydata_02 = pd.read_csv('Section-10_57-ImportingandOrganizingYourDatainPython-PartIII-Data_02.csv', index_col='Date')\nmydata_02.head()\nmydata_02.tail()\nmydata_02.to_excel('Section-10_57-ImportingandOrganizingYourDatainPython-PartIII-Data_02.xlsx')\nmydata_02.info()\nmydata_03 = pd.read_excel('Section-10_57-ImportingandOrganizingYourDatainPython-PartIII-Data_03.xlsx')\nmydata_03.info()\nmydata_03.set_index('Year')\nmydata_03.info()\n########## Return of Indices\nimport numpy as np\nimport pandas as pd\nfrom pandas_datareader import data as wb\nimport matplotlib.pyplot as plt\ntickers = ['^DJI', '^GSPC', '^IXIC', '^GDAXI']\nind_data = pd.DataFrame()\nfor t in tickers:\n    ind_data[t] = wb.DataReader(t, data_source='yahoo', start='2000-1-1')['Adj Close']\nind_data.head()\nind_data.tail()\n# Normalize the data to 100 and plot the results on a graph. \n(ind_data / ind_data.iloc[0] * 100).plot(figsize=(15, 6));\nplt.show()\n# How would you explain the common and the different parts of the behavior of the three indices?\n# Obtain the simple returns of the indices.\nind_returns = (ind_data / ind_data.shift(1)) - 1\nind_returns.tail()\n# Estimate the average annual return of each index.\nannual_ind_returns = ind_returns.mean() * 250\nannual_ind_returns\n##########\n'''baseAsset: BaseAsset = EquityShare('PG')\nprint(baseAsset.ShortType)\nprint(baseAsset.AssetType)\nprint(baseAsset.AssetName)\nprint(baseAsset.getSimpleReturn(PG))'''\ntickers = ['PG', 'MSFT', 'F', 'GE']\nyahoo_df = pd.DataFrame()\niex_df = pd.DataFrame()\nfor t in tickers:\n    yahoo_df[t] = wb.DataReader(t, data_source='yahoo', start='1995-1-1')['Adj Close']\n    # iex_df[t] = wb.DataReader(t, data_source='iex', start='2002-1-1')['Close']\nyahoo_df = pd.read_csv('Section-12_PG_BEI.DE_2007_2017.csv', index_col='Date')\nyahoo_df.tail()\nyahoo_df.head()\n# newDataFrame.to_csv('Section-10_57-ImportingandOrganizingYourDatainPython-PartIII-example_01.csv')\n# newDataFrame.to_excel('Section-10_57-ImportingandOrganizingYourDatainPython-PartIII-example_01.xlsx')'''\nyahoo_df.iloc[0]\n(yahoo_df / yahoo_df.iloc[0] * 100).plot(figsize = (15, 6));\nyahoo_df.plot(figsize=(15,6))\nyahoo_df.loc['2007-01-03']\nyahoo_df.iloc[0]\n## Calculating the Return of a Portfolio of Securities\nsimple_returns = (yahoo_df / yahoo_df.shift(1)) - 1\nsimple_returns.head()\nweights = np.array([0.5, 0.5])\nnp.dot(simple_returns, weights)\nsimple_returns_anual = simple_returns.mean() * 250\nsimple_returns_anual\nnp.dot(simple_returns_anual, weights)\npfolio_1 = str(round(np.dot(simple_returns_anual, weights), 5) * 100) + ' %'\nprint (pfolio_1)\nweights_2 = np.array([0.75, 0.25])\npfolio_2 = str(round(np.dot(simple_returns_anual, weights_2), 5) * 100) + ' %'\nprint (pfolio_2)\n## Calculating the Risk of a Portfolio of Securities Section-11_MSFT_2000_2017.csv\nlog_returns = np.log(yahoo_df / yahoo_df.shift(1))\nlog_returns.head()\n# MSFT\nlog_returns['PG'].mean()\n# Annual risk: covariance\nlog_returns['PG'].mean()*250\n# Daily risk:\nlog_returns['PG'].std()\n# Annual risk: covariance\nlog_returns['PG'].std() * 250 ** 0.5\n# PG\nlog_returns['BEI.DE'].mean()\n# Annual risk: covariance\nlog_returns['BEI.DE'].mean()*250\n# Daily risk:\nlog_returns['BEI.DE'].std()\n# Annual risk: covariance\nlog_returns['BEI.DE'].std() * 250 ** 0.5\n# Repeat the process we went through in the lecture for these two stocks. How would you explain the difference between their means and their standard deviations?\nlog_returns[['PG', 'BEI.DE']].mean() * 250\n# Store the volatilities of the two stocks in an array called \"vols\".\nvolatilities = log_returns[['PG', 'BEI.DE']].std() * 250 ** 0.5\nvolatilities\n# ## Covariance and Correlation on returns\n# \\begin{eqnarray*}\n# Covariance Matrix: \\  \\   \n# \\Sigma = \\begin{bmatrix}\n#         \\sigma_{1}^2 \\ \\sigma_{12} \\ \\dots \\ \\sigma_{1I} \\\\\n#         \\sigma_{21} \\ \\sigma_{2}^2 \\ \\dots \\ \\sigma_{2I} \\\\\n#         \\vdots \\ \\vdots \\ \\ddots \\ \\vdots \\\\\n#         \\sigma_{I1} \\ \\sigma_{I2} \\ \\dots \\ \\sigma_{I}^2\n#     \\end{bmatrix}\n# \\end{eqnarray*}\n# variance on returns\nms_var = log_returns['PG'].var() \nms_var\nms_var_anual = log_returns['PG'].var() * 250\nms_var_anual\npg_var = log_returns['BEI.DE'].var() \npg_var\npg_var_anual = log_returns['BEI.DE'].var() * 250\npg_var_anual\n# covariance on returns\ncov_matrix = log_returns.cov()\ncov_matrix\ncov_matrix_anual = log_returns.cov() * 250\ncov_matrix_anual\n# correlation on returns no need x 252\ncorr_matrix = log_returns.corr()\ncorr_matrix\n# ## Calculating Portfolio Risk\n# Weigthing scheme:\nweights = np.array([0.25, 0.75])\n# Portfolio Variance:\npfolio_var = np.dot(weights.T, np.dot(log_returns.cov() * 250, weights))\npfolio_var\n# Portfolio Volatility:\npfolio_vol = (np.dot(weights.T, np.dot(log_returns.cov() * 250, weights))) ** 0.5\npfolio_vol\nprint (str(round(pfolio_vol, 5) * 100) + ' %')\n# systematic = un diversifiable risk\n# unsystematic = diversifiable risk = idiosyncratic -> diversification\n## Calculating Diversifiable and Non-Diversifiable Risk of a Portfolio\n# Diversifiable Risk:\nms_var_anual = log_returns['PG'].var() * 250\nms_var_anual\npg_var_anual = log_returns['BEI.DE'].var() * 250\npg_var_anual\ndiversifable_risk = pfolio_var - (weights[0] ** 2 * ms_var_anual) - (weights[1] ** 2 * pg_var_anual)\ndiversifable_risk\nprint (str(round(diversifable_risk*100, 3)) + ' %')\n# Non-Diversifiable Risk:\nn_dr_1 = pfolio_var - diversifable_risk\nn_dr_1\nn_dr_2 = (weights[0] ** 2 * ms_var_anual) + (weights[1] ** 2 * pg_var_anual)\nn_dr_2\nn_dr_1 == n_dr_2\n# regresssions\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\nimport statsmodels.api as sm \nimport matplotlib.pyplot as plt\ndata = pd.read_excel('Section-13_Housing.xlsx')\ndata[['House Price', 'House Size (sq.ft.)']]\n# univarate regression\nX = data['House Size (sq.ft.)']\nY = data['House Price']\nplt.scatter(X,Y)\nplt.axis([0, 2500, 0, 1500000])\nplt.ylabel('House Price')\nplt.xlabel('House Size (sq.ft)')\n# regression linear OLS\nX1 = sm.add_constant(X)\nreg = sm.OLS(Y, X1).fit()\nreg.summary()\n### Alpha, Beta, R^2:\nslope, intercept, r_value, p_value, std_err = stats.linregress(X,Y)\nline = intercept + slope * X\nplt.plot(X,line)\nprint(slope)\nprint(intercept)\nprint(r_value)\nprint(r_value**2)\nprint(p_value)\nprint(std_err)\ndata = pd.read_excel('Section-13_IQ_data.xlsx')\ndata[['IQ', 'Test 1']]\nX = data['Test 1']\nY = data['IQ']\nplt.scatter(X,Y)\nplt.axis([0, 120, 0, 150])\nplt.ylabel('IQ')\nplt.xlabel('Test 1')\n# regression linear OLS\nX1 = sm.add_constant(X)\nreg = sm.OLS(Y, X1).fit()\nreg.summary()\n### Alpha, Beta, R^2:\nslope, intercept, r_value, p_value, std_err = stats.linregress(X,Y)\nline = intercept + slope * X\nplt.plot(X,line)\nprint(slope)\nprint(intercept)\nprint(r_value)\nprint(r_value**2)\nprint(p_value)\nprint(std_err)\n####################\n# ## Obtaining the Efficient Frontier - Part I\n# *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).*\n# We are in the middle of a set of 3 Python lectures that will help you reproduce the Markowitz Efficient Frontier. Let’s split this exercise into 3 parts and cover the first part here. \n# Begin by loading data for Walmart and Facebook from the 1st of January 2014 until today.\nimport numpy as np\nimport pandas as pd\nfrom pandas_datareader import data as wb\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nassets = ['PG', '^GSPC']\n# assets = ['WMT', 'FB']\npf_data = pd.DataFrame()\n# for a in assets:\n#     pf_data[a] = wb.DataReader(a, data_source = 'yahoo', start = '2010-1-1')['Adj Close']\npf_data = pd.read_csv('Section-14_Markowitz_Data.csv', index_col = 'Date')\n# pf_data = pd.read_csv('Section-12_Walmart_FB_2014_2017.csv', index_col='Date')\npf_data.tail()\n(pf_data / pf_data.iloc[0] * 100).plot(figsize=(10, 5))\nlog_returns = np.log(pf_data / pf_data.shift(1))\nlog_returns.mean() * 250\nlog_returns.cov() * 250\nlog_returns.corr()\n# In[10]:\nnum_assets = len(assets)\nweights = np.random.random(num_assets)\nweights /= np.sum(weights)\nweights\nweights[0] + weights[1]\n# Now, estimate the expected Portfolio Return, Variance, and Volatility.\n# Expected Portfolio Return:\nnp.sum(weights * log_returns.mean()) * 250\n# Expected Portfolio Variance:\nnp.dot(weights.T, np.dot(log_returns.cov() * 250, weights))\n# Expected Portfolio Volatility:\nnp.sqrt(np.dot(weights.T,np.dot(log_returns.cov() * 250, weights)))\n# ***\n# The rest of this exercise will be a reproduction of what we did in the previous video.\n# 1)\tCreate two empty lists. Name them pf_returns and pf_volatilites.\npfolio_returns = []\npfolio_volatilities = []\n# 2)\tCreate a loop with 1,000 iterations that will generate random weights, summing to 1, and will append the obtained values for the portfolio returns and the portfolio volatilities to pf_returns and pf_volatilities, respectively.\nfor x in range (1000):\n    weights = np.random.random(num_assets)\n    weights /= np.sum(weights)\n    pfolio_returns.append(np.sum(weights * log_returns.mean()) * 250)\n    pfolio_volatilities.append(np.sqrt(np.dot(weights.T,np.dot(log_returns.cov() * 250, weights))))\n    \npfolio_returns, pfolio_volatilities\n# 3)\tTransform the obtained lists into NumPy arrays and reassign them to pf_returns and pf_volatilites. Once you have done that, the two objects will be NumPy arrays. \npfolio_returns = np.array(pfolio_returns)\npfolio_volatilities = np.array(pfolio_volatilities)\npfolio_returns, pfolio_volatilities\n# In[21]:\nportfolios = pd.DataFrame({'Return': pfolio_returns, 'Volatility': pfolio_volatilities})\nportfolios.head()\nportfolios.tail()\n# In[24]:\nportfolios.plot(x='Volatility', y='Return', kind='scatter', figsize=(10, 6));\nplt.xlabel('Expected Volatility')\nplt.ylabel('Expected Return')\n######### Section-14_87-ObtainingtheEfficientFrontier-PartIII-Solution_CSV\nimport numpy as np\nimport pandas as pd\nfrom pandas_datareader import data as wb\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nassets = ['WMT', 'FB']\npf_data = pd.read_csv('Section-14_Walmart_FB_2014_2017.csv', index_col='Date')\n# pf_data = pd.DataFrame()\n# for a in assets:\n#     pf_data[a] = wb.DataReader(a, data_source = 'yahoo', start = '2014-1-1')['Adj Close']\npf_data.tail()\n(pf_data / pf_data.iloc[0] * 100).plot(figsize=(10, 5))\nlog_returns = np.log(pf_data / pf_data.shift(1))\nlog_returns.mean() * 250\nlog_returns.cov() * 250\nlog_returns.corr()\n# In[10]:\nnum_assets = len(assets)\nweights = np.random.random(num_assets)\nweights /= np.sum(weights)\nweights\nweights[0] + weights[1]\n# Now, estimate the expected Portfolio Return, Variance, and Volatility.\n# Expected Portfolio Return:\nnp.sum(weights * log_returns.mean()) * 250\n# Expected Portfolio Variance:\nnp.dot(weights.T, np.dot(log_returns.cov() * 250, weights))\n# Expected Portfolio Volatility:\nnp.sqrt(np.dot(weights.T,np.dot(log_returns.cov() * 250, weights)))\n# The rest of this exercise will be a reproduction of what we did in the previous video.\n# 1)\tCreate two empty lists. Name them pf_returns and pf_volatilites.\npf_returns = []\npf_volatilities = []\n# 2)\tCreate a loop with 1,000 iterations that will generate random weights, summing to 1, and will append the obtained values for the portfolio returns and the portfolio volatilities to pf_returns and pf_volatilities, respectively.\nfor x in range (1000):\n    weights = np.random.random(num_assets)\n    weights /= np.sum(weights)\n    pf_returns.append(np.sum(weights * log_returns.mean()) * 250)\n    pf_volatilities.append(np.sqrt(np.dot(weights.T,np.dot(log_returns.cov() * 250, weights))))\n    \npf_returns, pf_volatilities\n# 3)\tTransform the obtained lists into NumPy arrays and reassign them to pf_returns and pf_volatilites. Once you have done that, the two objects will be NumPy arrays. \n# In[8]:\npf_returns = np.array(pf_returns)\npf_volatilities = np.array(pf_volatilities)\npf_returns, pf_volatilities\n# Now, create a dictionary, called portfolios, whose keys are the strings “Return” and “Volatility” and whose values are the NumPy arrays pf_returns and pf_volatilities. \n# In[9]:\nportfolios = pd.DataFrame({'Return': pf_returns, 'Volatility': pf_volatilities})\n# In[10]:\nportfolios.head()\nportfolios.tail()\n# Finally, plot the data from the portfolios dictionary on a graph. Let the x-axis represent the volatility data from the portfolios dictionary and the y-axis – the data about rates of return. <br />\n# Organize your chart well and make sure you have labeled both the x- and the y- axes.\nportfolios.plot(x='Volatility', y='Return', kind='scatter', figsize=(10, 6));\nplt.xlabel('Expected Volatility')\nplt.ylabel('Expected Return')\n# What do you think would happen if you re-created the Markowitz Efficient Frontier for 3 stocks? The code you have created is supposed to accommodate easily the addition of a third stock, say British Petroleum (‘BP’). Insert it in your data and re-run the code (you can expand the “Cell” list from the Jupyter menu and click on “Run All” to execute all the cells at once!). <br />\n# How would you interpret the obtained graph? \nassets = ['WMT', 'FB', 'BP']\npf_data = pd.DataFrame()\nfor a in assets:\n    pf_data[a] = wb.DataReader(a, data_source = 'yahoo', start = '2014-1-1')['Adj Close']\npf_data.head()\n# In[14]:\nlog_returns = np.log(pf_data / pf_data.shift(1))\n# In[15]:\nnum_assets = len(assets)\nnum_assets\nweights = np.random.random(num_assets)\nweights /= np.sum(weights)\nweights\nweights[0] + weights[1] + weights[2]\n# Expected Portfolio Return:\nnp.sum(weights * log_returns.mean()) * 250\n# Expected Portfolio Variance:\nnp.dot(weights.T, np.dot(log_returns.cov() * 250, weights))\n# Expected Portfolio Volatility:\nnp.sqrt(np.dot(weights.T,np.dot(log_returns.cov() * 250, weights)))\n# *****\npfolio_returns = []\npfolio_volatilities = []\n# 2)\tCreate a loop with 1,000 iterations that will generate random weights, summing to 1, and will append the obtained values for the portfolio returns and the portfolio volatilities to pf_returns and pf_volatilities, respectively.\nfor x in range (1000):\n    weights = np.random.random(num_assets)\n    weights /= np.sum(weights)\n    pfolio_returns.append(np.sum(weights * log_returns.mean()) * 250)\n    pfolio_volatilities.append(np.sqrt(np.dot(weights.T,np.dot(log_returns.cov() * 250, weights))))\n    \npfolio_returns, pfolio_volatilities\n# 3)\tTransform the obtained lists into NumPy arrays and reassign them to pf_returns and pf_volatilites. Once you have done that, the two objects will be NumPy arrays. \npfolio_returns = np.array(pfolio_returns)\npfolio_volatilities = np.array(pfolio_volatilities)\npfolio_returns, pfolio_volatilities\n# In[21]:\nportfolios = pd.DataFrame({'Return': pfolio_returns, 'Volatility': pfolio_volatilities})\nportfolios.head()\nportfolios.tail()\n# In[24]:\nportfolios.plot(x='Volatility', y='Return', kind='scatter', figsize=(10, 6));\nplt.xlabel('Expected Volatility')\nplt.ylabel('Expected Return')\n########## Section-14_87-ObtainingtheEfficientFrontier-PartIII-Solution-3companies_CSV\n#!/usr/bin/env python\n# coding: utf-8\n# ## Obtaining the Efficient Frontier - Part III\n# *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).*\n# We are in the middle of a set of 3 Python lectures that will help you reproduce the Markowitz Efficient Frontier. Lets split this exercise into 3 parts and cover the first part here. \n# Begin by loading data for Walmart and Facebook from the 1st of January 2014 until today.\nimport numpy as np\nimport pandas as pd\nfrom pandas_datareader import data as wb\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n# In[2]:\nassets = ['WMT', 'FB', 'BP']\n# pf_data = pd.DataFrame()\n# for a in assets:\n#     pf_data[a] = wb.DataReader(a, data_source = 'yahoo', start = '2014-1-1')['Adj Close']\npf_data = pd.read_csv('Section-14_87-WMT_FB_BP_2014_2017.csv', index_col='Date')\n# In[3]:\npf_data.head()\n# In[4]:\npf_data.tail()\n(pf_data / pf_data.iloc[0] * 100).plot(figsize=(10, 5))\nlog_returns = np.log(pf_data / pf_data.shift(1))\nlog_returns.mean() * 250\nlog_returns.cov() * 250\nlog_returns.corr()\n# In[10]:\nnum_assets = len(assets)\nweights = np.random.random(num_assets)\nweights /= np.sum(weights)\nweights\n# In[15]:\nweights[0] + weights[1] + weights[2]\n# Expected Portfolio Return:\nnp.sum(weights * log_returns.mean()) * 250\n# Expected Portfolio Variance:\nnp.dot(weights.T, np.dot(log_returns.cov() * 250, weights))\n# Expected Portfolio Volatility:\nnp.sqrt(np.dot(weights.T,np.dot(log_returns.cov() * 250, weights)))\n# The rest of this exercise will be a reproduction of what we did in the previous video.\n# 1)\tCreate two empty lists. Name them pf_returns and pf_volatilites.\npfolio_returns = []\npfolio_volatilities = []\n# 2)\tCreate a loop with 1,000 iterations that will generate random weights, summing to 1, and will append the obtained values for the portfolio returns and the portfolio volatilities to pf_returns and pf_volatilities, respectively.\nfor x in range (1000):\n    weights = np.random.random(num_assets)\n    weights /= np.sum(weights)\n    pfolio_returns.append(np.sum(weights * log_returns.mean()) * 250)\n    pfolio_volatilities.append(np.sqrt(np.dot(weights.T,np.dot(log_returns.cov() * 250, weights))))\npfolio_returns, pfolio_volatilities\n# In[20]:\npfolio_returns = []\npfolio_volatilities = []\nfor x in range (1000):\n    weights = np.random.random(num_assets)\n    weights /= np.sum(weights)\n    pfolio_returns.append(np.sum(weights * log_returns.mean()) * 250)\n    pfolio_volatilities.append(np.sqrt(np.dot(weights.T,np.dot(log_returns.cov() * 250, weights))))\n    \npfolio_returns = np.array(pfolio_returns)\npfolio_volatilities = np.array(pfolio_volatilities)\npfolio_returns, pfolio_volatilities\n# In[21]:\nportfolios = pd.DataFrame({'Return': pfolio_returns, 'Volatility': pfolio_volatilities})\nportfolios.head()\nportfolios.tail()\n# In[24]:\nportfolios.plot(x='Volatility', y='Return', kind='scatter', figsize=(10, 6));\nplt.xlabel('Expected Volatility')\nplt.ylabel('Expected Return')\n## Calculating the Beta of a Stock\n# *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).*\n# Load the data for Microsoft and S&P 500 for the period 1st of January 2012 – 31st of December 2016. \nimport numpy as np\nimport pandas as pd\nfrom pandas_datareader import data as wb\n# tickerList = ['PG', '^GSPC']\n# tickerList = ['MSFT', '^GSPC']\n# data = pd.DataFrame()\n# for t in tickerList:\n#     data[t] = wb.DataReader(t, data_source='yahoo', start='2012-1-1', end='2016-12-31')['Adj Close']\n#     data[t] = wb.DataReader(t, data_source='yahoo', start='2012-1-1', end='2016-12-31')['Adj Close']\ndata = pd.read_csv('Section-15_CAPM_Data.csv', index_col = 'Date')\ndata = pd.read_csv('Section-15_CAPM_Exercise_Data.csv', index_col = 'Date')\ndata.head()\n# Let S&P 500 act as the market. \n# *****\n# Calculate the beta of Microsoft.\nsec_returns = np.log( data / data.shift(1) )\n# In[3]:\ncov = sec_returns.cov() * 250\ncov\n# In[4]:\ncov_with_market = cov.iloc[0,1]\ncov_with_market\n# In[5]:\nmarket_var = sec_returns['^GSPC'].var() * 250\nmarket_var\n# ** Beta**\n# $$ \n# \\beta_{stock} = \\frac{\\sigma_{stock,market}}{\\sigma_{market}^2}\n# $$\nstock_beta = cov_with_market / market_var\nstock_beta\n## Calculating the Expected Return of a Stock (CAPM)\n# *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).*\n# Obtain data for Microsoft and S&P 500 for the period 1st of January 2012  31st of December 2016 from Yahoo Finance. \n# Let S&P 500 act as the market. \n# Calculate the beta of Microsoft.\n# In[1]:\nimport numpy as np\nimport pandas as pd\nfrom pandas_datareader import data as wb\n# tickerList = ['PG', '^GSPC']\n# tickerList = ['MSFT', '^GSPC']\n# data = pd.DataFrame()\n# for t in tickerList:\n#     data[t] = wb.DataReader(t, data_source='yahoo', start='2012-1-1', end='2016-12-31')['Adj Close']\ndata = pd.read_csv('Section-15_CAPM_Data.csv', index_col = 'Date')\n# data = pd.read_csv('Section-15_CAPM_Exercise_Data.csv', index_col = 'Date')\ndata.head()\nsec_returns = np.log( data / data.shift(1) )\n# In[3]:\ncov = sec_returns.cov() * 250\ncov\n# In[4]:\ncov_with_market = cov.iloc[0,1]\ncov_with_market\n# In[5]:\nmarket_var = sec_returns['^GSPC'].var() * 250\nmarket_var\n# **Beta:**\n### $$\n# \\beta_{pg} = \\frac{\\sigma_{pg,m}}{\\sigma_{m}^2}\n# $$\nstock_beta = cov_with_market / market_var\nstock_beta\n# Assume a risk-free rate of 2.5% and a risk premium of 5%. <br />\n# Estimate the expected return of Microsoft.\n# **Calculate the expected return of P&G (CAPM):**\n# ### $$\n# \\overline{r_{pg}} = r_f + \\beta_{pg}(\\overline{r_{m}} - r_f) \n# $$\nstock_expectedReturn = 0.025 + stock_beta * 0.05\nstock_expectedReturn\n## Estimating the Sharpe Ratio in Python\n# *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).*\n# Obtain data for Microsoft and S&P 500 for the period 1st of January 2012 – 31st of December 2016 from Yahoo Finance. \n# Let S&P 500 act as the market. \n# Calculate the beta of Microsoft.\n# Assume a risk-free rate of 2.5% and a risk premium of 5%.<br />\n# Estimate the expected return of Microsoft.\nimport numpy as np\nimport pandas as pd\nfrom pandas_datareader import data as wb\n# tickerList = ['PG', '^GSPC']\n# tickerList = ['MSFT', '^GSPC']\n# data = pd.DataFrame()\n# for t in tickerList:\n#     data[t] = wb.DataReader(t, data_source='yahoo', start='2012-1-1', end='2016-12-31')['Adj Close']\n# data = pd.read_csv('Section-15_CAPM_Exercise_Data.csv', index_col = 'Date')\ndata = pd.read_csv('Section-15_CAPM_Data.csv', index_col = 'Date')  \ndata.head()\nsec_returns = np.log( data / data.shift(1) )\n# In[3]:\ncov = sec_returns.cov() * 250\ncov\n# In[4]:\ncov_with_market = cov.iloc[0,1]\ncov_with_market\n# In[5]:\nmarket_var = sec_returns['^GSPC'].var() * 250\nmarket_var\n# ** Beta: **\n# $$ \n# \\beta_{pg} = \\frac{\\sigma_{pg,m}}{\\sigma_{m}^2}\n# $$\nstock_beta = cov_with_market / market_var\nstock_beta\n# **Calculate the expected return of P&G (CAPM):**\n# $$\n# \\overline{r_{pg}} = r_f + \\beta_{pg}(\\overline{r_{m}} - r_f) \n# $$\nstock_er = 0.025 + stock_beta * 0.05\nstock_er\n# Calculate the Sharpe ratio in Python.\n# **Sharpe ratio:**\n# $$\n# Sharpe = \\frac{\\overline{r_{pg}} - r_f}{\\sigma_{pg}}\n# $$\nSharpeRatio = (stock_er - 0.025) / (sec_returns['PG'].std() * 250 ** 0.5)\n#SharpeRatio = (stock_er - 0.025) / (sec_returns['MSFT'].std() * 250 ** 0.5)\nSharpeRatio\n## Monte Carlo - Predicting Gross Profit - Part I\n# *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).*\n# Imagine you are an experienced manager and you have forecasted revenues of \\$200mln, with an expected deviation of $10mln. You are convinced Cogs will be near 40% of the revenues, and their expected deviation is 20% of its own value. \n# Use NumPys random.random function to simulate the potential revenue stream for 250 iterations (which is the number of trading days in a year) and then the predicted Cogs value. \nimport numpy as np\nimport matplotlib.pyplot as plt\n# In[2]:\nrev_m = 170 # 200\nrev_stdev = 20 # 10\niterations = 1000 # 250\n# In[3]:\nrev = np.random.normal(rev_m, rev_stdev, iterations)\nrev\n# Plot the obtained data for revenues and Cogs on a graph and observe the behavior of the obtained values.\nplt.figure(figsize=(15, 6))\nplt.plot(rev)\nplt.show()\n# In[5]:\nCOGS = - (rev * np.random.normal(0.6,0.1)) # (0.4,0.2))\nplt.figure(figsize=(15, 6))\nplt.plot(COGS)\nplt.show()\n# Cogs mean:\nCOGS.mean()\n# Cogs std:\nCOGS.std()\n# ****\n# Based on the predicted revenue and Cogs values, estimate the expected Gross Profit of your company. \n# *Reminder: Be careful about estimating the gross profit. If you have stored the Cogs value as a negative number, the gross profit will equal revenues plus Cogs. If you have created Cogs as a positive value, then gross profit would be equal to revenues minus Cogs. Either way, you will obtain the same result for gross profit.* \nGross_Profit = rev + COGS\nGross_Profit\nplt.figure(figsize=(15, 6))\nplt.plot(Gross_Profit)\nplt.show()\n# What is the maximum and what is the minimum gross profit value you obtained?\nmax(Gross_Profit)\n# In[10]:\nmin(Gross_Profit)\n# What is its mean and standard deviation?\nGross_Profit.mean()\n# In[12]:\nGross_Profit.std()\n# Do you remember what a histogram is? Plot the gross profit data on a histogram. Use 20 bins directly to check the distribution of the data.\nplt.figure(figsize=(10, 6));\nplt.hist(Gross_Profit, bins = [40, 50, 60, 70, 80, 90, 100, 110, 120]);\nplt.show()\n# In[14]:\nplt.figure(figsize=(10, 6));\nplt.hist(Gross_Profit, bins = 20);\nplt.show()\n# ************\n# In all our analyses, we used estimations for either simple or logarithmic rates of return. <br/>\n# The formula for simple returns is\n# $$\n# \\frac{P_t - P_{t-1}}{P_{t-1}}\n# $$\n# while the formula for log returns is\n# $$\n# ln( \\frac{P_t}{P_{t-1}} )\n# $$\n# If our dataset is simply called \"data\", in Python, we could write the first formula as\n# *(data / data.shift(1)) - 1,*\n# and the second one as\n# *np.log(data / data.shift(1)).*\n# Instead of coding it this way, some professionals prefer using **Pandas.DataFrame.pct_change()** method, as it computes simple returns directly. We will briefly introduce it to you in this notebook document.\n# First, let's import NumPy, Pandas, and pandas_datareader.\nimport numpy as np  \nimport pandas as pd  \nfrom pandas_datareader import data as wb  \n# We will calculate returns of the Procter and Gamble stock, based on adjusted closing price data since the\n# 1st of January 2007.\n# 1st of January 2015.\ndata = pd.read_csv('Section-17_PG_2007_2017.csv', index_col = 'Date')\n# ticker = 'PG' \n# data = pd.DataFrame()\n# data[ticker] = wb.DataReader(ticker, data_source='yahoo', start='2007-1-1')['Adj Close']\n# data[ticker] = wb.DataReader(ticker, data_source='iex', start='2015-1-1')['close']\n# So far, we estimated simple returns in the following way.\ns_rets_1 = (data / data.shift(1)) - 1\ns_rets_1.head()\n# Observe the .pct_change() method can obtain an identical result.\ns_rets_2 = data.pct_change()\ns_rets_2.head()\n# Now, if you multiply the obtained values by 100, you will see the percentage change:\ns_rets_2.head() * 100\n# This means the close price on 2007-01-04 was 0.76% lower than the price on 2007-01-03, the price on 2007-01-05 was 0.85% lower than the price on 2007-01-04, and so on.\n# A few arguments can be used in the percentage change method. The most important one is 'period' as it specifies the difference between prices in the nominator. By default, it equals one, and that's why we obtained the same result for s_rets_1 and s_rets_2. Let's assume we would like to calculate simple returns with the following formula: \n# $$\n# \\frac{P_t - P_{t-2}}{P_{t-2}}\n# $$\n# Then, we should specify 'periods = 2' in parentheses:\ns_rets_3 = data.pct_change(periods=2)\ns_rets_3.head()\n# You can see there was no value obtained not only for the first, but also for the second observation. If we use the \"old\" formula, and not this method, *shift(2)* would lead us to the same output:\ns_rets_4 = (data / data.shift(2)) - 1\ns_rets_4.head()\n# Now, let's consider logarithmic returns. To this moment, we applied the following formula:\nlog_rets_1 = np.log(data / data.shift(1))\nlog_rets_1.tail()\n# You can calculate the same formula for log returns with the help of the .pct_change() method. Just be careful with the way you apply the formula! Mathematically, it will look like this:\n# $$\n# ln(\\frac{P_t}{P_{t-1}} ) = ln( \\frac{P_t - P_{t-1}}{P_{t-1}} + \\frac{P_{t-1}}{P_{t-1}}) = ln(\\ simple.returns + 1)\n# $$\n# In[9]:\nlog_rets_2 = np.log(data.pct_change() + 1)\nlog_rets_2.tail()\n# ***\n# The .pct_change() method is very popular. Whether you include it in your code or you go the other way around and type the formulas as we did in our analyses, you should obtain the correct value for the returns you need.\n########## 103\n## Monte Carlo - Forecasting Stock Prices - Part I\n# *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).*\n# Download the data for Microsoft (MSFT) from Yahoo Finance for the period 2000-1-1 until today.\n# Download the data for Microsoft (MSFT) from IEX for the period 2015-1-1 until today.\n# Forecasting Future Stock Prices  continued:\nimport numpy as np  \nimport pandas as pd  \nfrom pandas_datareader import data as wb  \nimport matplotlib.pyplot as plt  \nfrom scipy.stats import norm\nget_ipython().run_line_magic('matplotlib', 'inline')\n# In[2]:\n# ticker = 'PG'\n# ticker = 'MSFT'\n# data = pd.DataFrame()\n# data[ticker] = wb.DataReader(ticker, data_source='yahoo', start='2007-1-1')['Adj Close']\n# data[ticker] = wb.DataReader(ticker, data_source='iex', start='2015-1-1')['close']\ndata = pd.read_csv('Section-17_PG_2007_2017.csv', index_col = 'Date')\ndata = pd.read_csv('Section-17_MSFT_2000.csv', index_col = 'Date')\ndata.plot(figsize=(10, 6));\n# Use the .pct_change() method to obtain the log returns of Microsoft for the designated period.\nlog_returns = np.log(1 + data.pct_change())\nlog_returns.tail()\nlog_returns.plot(figsize = (10, 6))\n# Assign the mean value of the log returns to a variable, called U, and their variance to a variable, called var. \nu = log_returns.mean()\nu\n# In[7]:\nvar = log_returns.var()\nvar\n# Calculate the drift, using the following formula: \n# $$\n# drift = u - \\frac{1}{2} \\cdot var\n# $$\ndrift = u - (0.5 * var)\ndrift\n# Store the standard deviation of the log returns in a variable, called stdev.\nstdev = log_returns.std()\nstdev\n# ******\n# Use .values to transform the *drift* and the *stdev* objects into arrays. \ntype(drift)\ndrift.values\n# In[4]:\ntype(stdev)\n# In[12]:\nnp.array(drift)\ndrift.values\n# In[14]:\nstdev.values\n# Forecast future stock prices for every trading day a year ahead. So, assign 250 to t_intervals.\n# Lets examine 10 possible outcomes. Bind iterations to the value of 10.\nt_intervals = 250\nt_intervals = 1000\niterations = 10\n# Use the formula we have provided and calculate daily returns.\n# $$\n# r = drift + stdev \\cdot z\n# $$\n# $$\n# daily\\_returns = exp({drift} + {stdev} * z), \n# $$\n# $$\n# where\\  z = norm.ppf(np.random.rand(t\\_intervals, iterations)\n# $$\n# $$\n# daily\\_returns = e^{r}\n# $$\ndaily_returns = np.exp(drift.values + stdev.values * norm.ppf(np.random.rand(t_intervals, iterations)))\ndaily_returns\n# $$\n# S_t = S_0 \\mathbin{\\cdot} daily\\_return_t\n# $$\n# $$\n# S_{t+1} = S_t \\mathbin{\\cdot} daily\\_return_{t+1}\n# $$\n# $$...$$\n# $$\n# S_{t+999} = S_{t+998} \\mathbin{\\cdot} daily\\_return_{t+999}\n# $$\n# ***\n# Create a variable S0 equal to the last adjusted closing price of Microsoft. Use the iloc method.\nS0 = data.iloc[-1]\nS0\n# Create a variable price_list with the same dimension as the daily_returns matrix. \nprice_list = np.zeros_like(daily_returns)\nprice_list\nprice_list[0]\n# Set the values on the first row of the price_list array equal to S0.\nprice_list[0] = S0\nprice_list\n# Create a loop in the range (1, t_intervals) that reassigns to the price in time t the product of the price in day (t-1) with the value of the daily returns in t.\nfor t in range(1, t_intervals):\n    price_list[t] = price_list[t - 1] * daily_returns[t]\nprice_list\n# Finally, plot the obtained price list data.\nplt.figure(figsize=(10,6))\nplt.plot(price_list);\n\n", "meta": {"hexsha": "fb268576fefcaecb734cb42dc066c77a2eb4cc9d", "size": 33117, "ext": "py", "lang": "Python", "max_stars_repo_path": "script-InvestmentFundamentalsAndDataAnalytics.py", "max_stars_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_stars_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-04T11:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-10T15:36:42.000Z", "max_issues_repo_path": "script-InvestmentFundamentalsAndDataAnalytics.py", "max_issues_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_issues_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-03-30T16:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:37:21.000Z", "max_forks_repo_path": "script-InvestmentFundamentalsAndDataAnalytics.py", "max_forks_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_forks_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T11:26:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T11:26:16.000Z", "avg_line_length": 40.6343558282, "max_line_length": 381, "alphanum_fraction": 0.7246731286, "include": true, "reason": "import numpy,from scipy,import statsmodels", "num_tokens": 9663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.9184802356574272, "lm_q1q2_score": 0.8546075230892217}}
{"text": "\"\"\"\nEstimate Volatility\nCreate an exponential moving average model of volatility. Use the formula in your notes:\nwhere r_n is the nth daily return, and \\sigma_nσ is the nth estimate of the volatility.\n\\lambdaλ is a constant between 0 and 1 that defines how quickly weights on older data should decrease.\nA high value of \\lambdaλ (close to 1) will cause older data to matter relatively more in the calculation of \\sigma_nσ.\nA very low value of \\lambdaλ will mean that recent data matter more—in this case, the successive daily estimates of \\sigma_nσ\nthemselves will be volatile.\n\nPandas provides built-in exponentially weighted moving window functions with the .ewm method.\nConsider using .ewm().mean(), and be sure to properly specify the alpha parameter (hint: it is related to, but not equal to \\lambdaλ).\n\n** the ema function using (1-alpha), so since they pass us lambda we need to 1-lambda to get the method to work properly\n\nNote that .ewm().std() and .ewm().var() implement ewmvar(x) = ewma(x**2) - ewma(x)**2,\nwhich is slightly different than what you'll want to implement for this problem.\n\nOther resources.  \nhttps://knowledge.udacity.com/questions/413282\nhttps://knowledge.udacity.com/questions/157360\nhttps://knowledge.udacity.com/questions/381675\nhttps://knowledge.udacity.com/questions/43364\n\nResult\n\n0.004940582044719361\nMost recent volatility estimate: 0.004941\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport math\n\n\ndef estimate_volatility(prices, l):\n    \"\"\"Create an exponential moving average model of the volatility of a stock\n    price, and return the most recent (last) volatility estimate.\n\n    Parameters\n    ----------\n    prices : pandas.Series\n        A series of adjusted closing prices for a stock.\n\n    l : float\n        The 'lambda' parameter of the exponential moving average model. Making\n        this value smaller will cause the model to weight older terms less\n        relative to more recent terms.\n\n    Returns\n    -------\n    last_vol : float\n        The last element of your exponential moving averge volatility model series.\n\n    \"\"\"\n    # TODO: Implement the exponential moving average volatility model and return the last value.\n    # calculate log returns\n    returns = np.log(prices) - np.log(prices.shift(1))\n\n    # square log returns\n    returns_squared = returns ** 2\n\n    # take the ewm mean\n    result = returns_squared.ewm(alpha=1 - l).mean()\n\n    # take the square root of the results\n    ema = np.sqrt(result.iloc[-1])\n    print(ema)\n\n    return ema\n\n\ndef test_run(filename=\"data.csv\"):\n    \"\"\"Test run get_most_volatile() with stock prices from a file.\"\"\"\n    prices = pd.read_csv(filename, parse_dates=[\"date\"], index_col=\"date\", squeeze=True)\n    print(\"Most recent volatility estimate: {:.6f}\".format(estimate_volatility(prices, 0.7)))\n\n\nif __name__ == \"__main__\":\n    test_run()\n", "meta": {"hexsha": "dd716ab60e013cbe2c492bfe27147da7f916b3c4", "size": 2841, "ext": "py", "lang": "Python", "max_stars_repo_path": "quizes/estimate-volatility/volatility_estimation.py", "max_stars_repo_name": "babeal/udacity-ai-for-trading", "max_stars_repo_head_hexsha": "3f6ff7a5707edb44bc4dfdd434ec87f9ff5be595", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quizes/estimate-volatility/volatility_estimation.py", "max_issues_repo_name": "babeal/udacity-ai-for-trading", "max_issues_repo_head_hexsha": "3f6ff7a5707edb44bc4dfdd434ec87f9ff5be595", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quizes/estimate-volatility/volatility_estimation.py", "max_forks_repo_name": "babeal/udacity-ai-for-trading", "max_forks_repo_head_hexsha": "3f6ff7a5707edb44bc4dfdd434ec87f9ff5be595", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5125, "max_line_length": 134, "alphanum_fraction": 0.7272087293, "include": true, "reason": "import numpy", "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.9136765210631689, "lm_q1q2_score": 0.8546041451005842}}
{"text": "\n# coding: utf-8\n\n# ## Exercises\n# \n# This will be a notebook for you to work through the exercises during the workshop. Feel free to work on these at whatever pace you feel works for you, but I encourage you to work together! Edit the title of this notebook with your name because I will ask you to upload your final notebook to our shared github repository at the end of this workshop.\n# \n# Feel free to google the documentation for numpy, matplotlib, etc.\n# \n# Don't forget to start by importing any libraries you need.\n\n# In[3]:\n\n\nimport numpy as np\nimport astropy\nimport matplotlib.pyplot as plt\nfrom scipy import integrate\n\n\n# ### Day 1\n# \n# #### Exercise 1\n# \n#    A. Create an array with 10 evenly spaced values in logspace ranging from 0.1 to 10,000.\n# \n#    B. Print the following values: The first value in the array, the final value in the array, and the range of 5th-8th values.\n# \n#    C. Append the numbers 10,001 and 10,002 (as floats) to the array. Make sure you define this!\n# \n#    D. Divide your new array by 2.\n# \n#    E. Reshape your array to be 3 x 4. \n# \n#    F. Multiply your array by itself.\n#     \n#    G.  Print out the number of dimensions and the maximum value.\n\n# In[18]:\n\n\n# A\narray = np.logspace(np.log10(0.1),np.log10(10000),10)\nprint(array)\n\n# B\nprint(array[0])\nprint(array[-1])\nprint(array[5:8])\n\n# C\nnewarray = np.append(array,[10001., 10002.])\nprint(newarray)\n\n# D\nhalf = newarray/2\nprint(half)\n\n# E\nreshaped = newarray.reshape(3,4)\nprint(reshaped)\n\n# F\nmult = np.dot(newarray, newarray)\nprint(mult)\n\n# G\nprint(newarray.size)\nprint(np.max(newarray))\n\n\n# ### Day 2\n\n# #### Exercise 1\n# \n#    A. Create an array containing the values 4, 0, 6, 5, 11, 14, 12, 14, 5, 16.\n#    B. Create a 10x2 array of zeros.\n#    C. Write a for loop that checks if each of the numbers in the first array squared is less than 100. If the statement is true, change that row of your zeros array to equal the number and its square. Hint: you can change the value of an array by stating \"zerosarray[i] = [a number, a number squared]\". \n#    D. Print out the final version of your zeros array.\n#     \n# Hint: should you loop over the elements of the array or the indices of the array?\n\n# In[3]:\n\n\na = [4,0,6,5,11,14,12,14,5,16]\nb = np.zeros((10,2))\n\nfor i in range(len(a)):\n    if a[i]**2<100:\n        b[i]=[a[i],a[i]**2]\n        \nprint(b)\n\n\n# #### Exercise 2\n#     \n#    A. Write a function that takes an array of numbers and spits out the Gaussian distribution. Yes, there is a function for this in Python, but it's good to do this from scratch! This is the equation:\n#     \n# $$ f(x) = \\frac{1}{\\sigma \\sqrt{2\\pi}} \\exp{\\frac{-(x - \\mu)^2}{2\\sigma^2}} $$\n# \n#     (Pi is built into numpy, so call it as np.pi.)\n# \n#    B. Call the function a few different times for different values of mu and sigma, between -10 < x < 10.\n#     \n#    C. Plot each version, making sure they are differentiated with different colors and/or linestyles and include a legend. Btw, here's a list of the customizations available in matplotlib:\n#     \n#     https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.plot.html\n#     \n#     https://matplotlib.org/gallery/color/named_colors.html\n#     \n#    D. Save your figure.\n#     \n# If you have multiple lines with plt.plot(), Python will plot all of them together, unless you write plt.show() after each one. I want these all on one plot.\n\n# In[17]:\n\n\ndef gauss(sigma,x,mu):\n    f = (1/(sigma*np.sqrt(2*np.pi)))*np.exp(-(x-mu)**2/(2*sigma**2))\n    return f\n\nprint(gauss(1,1,1)) # just to test that it works\n\nx = np.linspace(-10,10,100)\na = gauss(1,x,1)\nb = gauss(2,x,2)\nc = gauss(4,x,3.5)\n\nfig = plt.figure()\nplt.plot(x,a,'r-',label='$\\sigma$=1, $\\mu$=1')\nplt.plot(x,b,'g--',label='$\\sigma$=2, $\\mu$=2')\nplt.plot(x,c,'b:',label='$\\sigma$=4, $\\mu$=3.5')\nplt.xlabel('x',fontsize=16)\nplt.ylabel('y',fontsize=16)\nplt.legend(loc=1,frameon=True)\nplt.title('Gaussian Function')\nfig.savefig('gaussian.jpg')\nplt.show()\n\n\n# ### Day 3\n# \n# #### Exercise 1\n# \n# There is a file in this directory called \"histogram_exercise.dat\" which consists of of randomly generated samples from a Gaussian distribution with an unknown $\\mu$ and $\\sigma$. Using what you've learned about fitting data, load up this file using np.genfromtxt, fit a Gaussian curve to the data and plot both the curve and the histogram of the data. As always, label everything, play with the colors, and choose a judicious bin size. \n# \n# Hint: if you attempt to call a function from a library or package that hasn't been imported, you will get an error.\n\n# In[54]:\n\n\nimport scipy.optimize as opt\nfrom scipy.stats import norm\n\ndata = np.genfromtxt('histogram_exercise.dat')\n\nmu,sigma = norm.fit(data)\nprint(mu,sigma)\nx = np.linspace(-2,10,1000)\npdf = norm.pdf(x,mu,sigma)\n\nplt.hist(data,bins=50,density=True,color='mediumblue',alpha=0.4,label='Data')\nplt.plot(x,pdf,'-g',label='Gaussian Fit')\nplt.xlabel('Data')\nplt.ylabel('Counts')\nplt.title('Fit results: $\\mu = 5.04, \\sigma = 1.93$')\nplt.legend(loc=0,frameon=True)\nplt.show()\n\n\n# #### Exercise 2\n# \n# Create a 1D interpolation along these arrays. Plot both the data (as points) and the interpolation (as a dotted line). Also plot the value of the interpolated function at x=325. What does the function look like to you?\n\n# In[33]:\n\n\nx = np.array([0., 50., 100., 150., 200., 250., 300., 350., 400., 450., 500])\ny = np.array([0., 7.071, 10., 12.247, 14.142, 15.811, 17.321, 18.708, 20., 21.213, 22.361])\n\nfrom scipy.interpolate import interp1d\n\ninterp = interp1d(x,y)\nxnew = np.linspace(0,500,1000)\nynew = interp(xnew)\n\nplt.plot(x,y,'.b',label='Data')\nplt.plot(xnew,ynew,':k',label='Interpolation')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Interpolation')\nplt.legend(loc=0,frameon=True)\nplt.show()\n\n\n# ### Day 4\n# \n# #### Exercise 1\n# \n# Let's practice some more plotting skills, now incorporating units. \n# \n# A. Write a function that takes an array of frequencies and spits out the Planck distribution. That's this equation:\n# \n# $$ B(\\nu, T) = \\frac{2h\\nu^3/c^2}{e^{\\frac{h\\nu}{k_B T}} - 1} $$\n# \n# This requires you to use the Planck constant, the Boltzmann constant, and the speed of light from astropy. Make sure they are all in cgs. \n#     \n# B. Plot your function in log-log space for T = 25, 50, and 300 K. The most sensible frequency range is about 10^5 to 10^15 Hz. Hint: if your units are correct, your peak values of B(T) should be on the order of 10^-10. Make sure everything is labelled. \n\n# In[22]:\n\n\nfrom astropy import constants as const\nfrom astropy import units as u\n\ndef planck(nu,T):\n    B = (2*const.h.cgs*nu**3/const.c.cgs**2)/(np.exp((const.h.cgs*nu)/(const.k_B.cgs*T))-1)\n    return B\n\nT = [25,50,300]\nstyle = ['b','g','r']\nfor i in range(len(T)):\n    x = np.logspace(5,15,20)\n    y = planck(x*u.Hz,T[i]*u.K)\n    plt.loglog(x,y,style[i],label=T[i]*u.K)\nplt.xlabel('Frequency (Hz)')\nplt.ylabel('Planck Distribution')\nplt.title('Planck Distribution for T = 25, 50, 300 K')\nplt.legend(loc=0,frameon=True)\nplt.show()\n\n\n# #### Exercise 2\n# \n# Let's put everything together now! Here's a link to the full documentation for FITSFigure, which will tell you all of the customizable options: http://aplpy.readthedocs.io/en/stable/api/aplpy.FITSFigure.html. Let's create a nice plot of M51 with a background optical image and X-ray contours overplotted.\n# \n# The data came from here if you're interested: http://chandra.harvard.edu/photo/openFITS/multiwavelength_data.html\n# \n# A. Using astropy, open the X-RAY data (m51_xray.fits). Flatten the data array and find its standard deviation, and call it sigma.\n# \n# B. Using aplpy, plot a colorscale image of the OPTICAL data. Choose a colormap that is visually appealing (list of them here: https://matplotlib.org/2.0.2/examples/color/colormaps_reference.html). Show the colorbar. \n# \n# C. Plot the X-ray data as contours above the optical image. Make the contours spring green with 80% opacity and dotted lines. Make the levels go from 2$\\sigma$ to 10$\\sigma$ in steps of 2$\\sigma$. (It might be easier to define the levels array before show_contours, and set levels=levels.)\n\n# In[51]:\n\n\nfrom astropy.io import fits\nimport aplpy\n\n#astropy\nhdulist = fits.open('m51_xray.fits')\nhdulist.info()\n\ndata = hdulist[0].data\ndata_flat = data.flatten()\nsigma = np.std(data_flat)\nprint('sigma =',sigma)\n\n\n#aplpy\nM51 = aplpy.FITSFigure('m51_optical_B.fits')\nM51.show_colorscale(cmap='cool')\nM51.show_colorbar()\n\nlvls = sigma*range(2,11,2)\nM51.show_contour('m51_xray.fits',levels=lvls,alpha=0.8,colors='springgreen')\nplt.show()\n\n", "meta": {"hexsha": "31c2379924844a7f434415cf1ee946bfac49c561", "size": 8531, "ext": "py", "lang": "Python", "max_stars_repo_path": "Exercises_Nolan_Day4.py", "max_stars_repo_name": "UTAustinTAURUS/day-1-exercises-nelauria", "max_stars_repo_head_hexsha": "18feadae948b8498b282d0ec9ded87c6caf865f9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Exercises_Nolan_Day4.py", "max_issues_repo_name": "UTAustinTAURUS/day-1-exercises-nelauria", "max_issues_repo_head_hexsha": "18feadae948b8498b282d0ec9ded87c6caf865f9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercises_Nolan_Day4.py", "max_forks_repo_name": "UTAustinTAURUS/day-1-exercises-nelauria", "max_forks_repo_head_hexsha": "18feadae948b8498b282d0ec9ded87c6caf865f9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.479704797, "max_line_length": 438, "alphanum_fraction": 0.6896026257, "include": true, "reason": "import numpy,import scipy,from scipy,import astropy,from astropy", "num_tokens": 2566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.9136765157744067, "lm_q1q2_score": 0.8546041434471027}}
{"text": "from scipy.integrate import quad\nfrom math import sin\nfrom numpy import arange\n\nleft = 0\nright = 1\nstep = 0.05\n\ndef legendre(n):\n\tif n == 0:\n\t\treturn lambda x: 1\n\telif n == 1:\n\t\treturn lambda x : x\n\treturn lambda x: (((2*n - 1) * x * legendre(n - 1)(x) - (n-1) * legendre(n - 2)(x)) / n)\n# def legendre(x, n):\n\t# if n == 0:\n\t\t# return 1\n\t# elif n == 1:\n\t\t# return x\n\t# return (((2*n - 1) * x * legendre(x, n - 1) - (n-1) * legendre(x, n - 2)) / n)\n\ndef f(x):\n\treturn sin(x)\n\nprint((right + left) / 2)\nprint((right - left) / 2)\n\n# def integrand(x, n):\n\n\t# t = (right + left) / 2 + (right - left) / 2 * x\n\t\n\n\t# t = (2*x-(right+left))/(right-left)\n\t# return f(t) * legendre(t, n)\n\t\n\n# def get_Ck(k):\n\t# return (2*k + 1) / 2 * quad(integrand, -1, 1, args=k)[0]\n\ndef scale(x):\n\treturn (2*x-(right+left))/(right-left)\n\t# return (2*x-(right+left))/(right-left)\n\nimport matplotlib.pyplot as plt\nxs = list(arange(left,right,step))\nys = list()\nnodes_len = len(xs)\nfor i in xs:\n\tys.append(f(i))\n\nscaled_xs = list()\nfor i in xs:\n\tscaled_xs.append(scale(i))\n\nlambdas = [legendre(i) for i in range(nodes_len)]\nprint(\"LAMBDAS\")\n# pre_cs = list()\n# for i in range(len(scaled_xs)):\n\t# pre_cs.append(lambdas[i](scaled_xs[i]))\n\ndef integ(x, ind):\n\tt1 = (right + left) / 2 + (right - left) / 2 * x\n\tt2 = (2*x-(right+left))/(right-left)\n\treturn f(t2) * lambdas[i](t1)\n\ncs = list()\nfor i in range(nodes_len):\n\tel = (2*i + 1) / 2 * quad(integ, -1, 1, args=i)[0]\n\tcs.append(el)\nprint(\"QUADS\")\n\ncsy = list()\n\ndef calc_pol(x):\n\tres = 0\n\tt1 = (right + left) / 2 + (right - left) / 2 * x\n\tt2 = (2*x-(right+left))/(right-left)\n\tfor i in range(nodes_len):\n\t\tres += cs[i] * lambdas[i](t1)\n\treturn res\n\nfor i in xs:\n\tty = calc_pol(i)\n\t# csy.append((right+left)/2+(right-left)/2*ty)\n\t# csy.append((2*ty-(right+left))/(right-left))\n\tcsy.append(ty)\n\nprint(\"DONE\")\n\nplt.plot(xs, ys, 'ro', xs, csy, 'b--')\nplt.axis([left, right, -1, 1])\nplt.show()\n\n\n# a = 2\n# b = 1\n# I = quad(integrand, 0, 1, args=(a,b))\n# print(I)", "meta": {"hexsha": "0f7304ec689a62751457b2aea56ad352d96c5a40", "size": 1979, "ext": "py", "lang": "Python", "max_stars_repo_path": "calc_methods5.py", "max_stars_repo_name": "Via-R/calculation_methods_labs", "max_stars_repo_head_hexsha": "d2f95bf7319a5f6a7b9e2c8f316edbb61cce638d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "calc_methods5.py", "max_issues_repo_name": "Via-R/calculation_methods_labs", "max_issues_repo_head_hexsha": "d2f95bf7319a5f6a7b9e2c8f316edbb61cce638d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calc_methods5.py", "max_forks_repo_name": "Via-R/calculation_methods_labs", "max_forks_repo_head_hexsha": "d2f95bf7319a5f6a7b9e2c8f316edbb61cce638d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.193877551, "max_line_length": 89, "alphanum_fraction": 0.5795856493, "include": true, "reason": "from numpy,from scipy", "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399051935108, "lm_q2_score": 0.8807970826714614, "lm_q1q2_score": 0.8545844779858796}}
{"text": "\"\"\"\nGaussian smoothing with Python.\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport math\n\n\ndef gaussian(sigma, x):\n    return (math.e ** (- (x ** 2 / (2 * sigma ** 2)))) / math.sqrt(2 * math.pi * sigma ** 2)\n\n\ndef gaussian_filter(sigma, filter_length=None):\n    \"\"\"\n    Given a sigma, return a 1-D Gaussian filter.\n    @param     sigma:         float, defining the width of the filter\n    @param     filter_length: optional, the length of the filter, has to be odd\n    @return    A 1-D numpy array of odd length,\n               containing the symmetric, discrete approximation of a Gaussian with sigma\n               Summation of the array-values must be equal to one.\n    \"\"\"\n    if filter_length is None:\n        # determine the length of the filter\n        filter_length = math.ceil(sigma * 5)\n        # make the length odd\n        filter_length = 2 * (int(filter_length) / 2) + 1\n\n    # make sure sigma is a float\n    sigma = float(sigma)\n\n    # create the filter\n    # length = 2*k + 1   =>   k = (length-1) / 2\n    k = ((filter_length - 1) / 2)\n    result = np.arange(-k, k + 1)\n\n    # do your best!\n    result = [gaussian(sigma, x) for x in result]\n    result /= sum(result)\n\n    # return the filter\n    return result\n\n\ndef test_gaussian_filter():\n    \"\"\"\n    Test the Gaussian filter on a known input.\n    \"\"\"\n    sigma = math.sqrt(1.0 / 2 / math.log(2))\n    f = gaussian_filter(sigma, filter_length=3)\n    correct_f = np.array([0.25, 0.5, 0.25])\n    error = np.abs(f - correct_f)\n\n    if np.sum(error) < 0.001:\n        print(\"Congratulations, the filter works!\")\n    else:\n        print(\"Still some work to do..\")\n\n\ndef gaussian_smooth1(img, sigma):\n    \"\"\"\n    Do gaussian smoothing with sigma.\n    Returns the smoothed image.\n    \"\"\"\n    result = np.zeros_like(img)\n\n    # get the filter\n    ffilter = gaussian_filter(sigma)\n\n    # smooth every color-channel\n    for c in range(3):\n        # smooth the 2D image img[:,:,c]\n        for row in range(img[:, :, c].shape[0]):\n            result[row, :, c] = np.convolve(img[row, :, c], ffilter, 'same')\n\n    return result\n\n\n# this part of the code is only executed if the file is run stand-alone\nif __name__ == '__main__':\n    # test the gaussian filter\n    test_gaussian_filter()\n\n    # read an image\n    img = cv2.imread('image.jpg')\n\n    # print the dimension of the image\n    print(img.shape)\n\n    # show the image, and wait for a key to be pressed\n    cv2.imshow('img', img)\n    # cv2.waitKey(0)\n\n    # smooth the image\n    smoothed_img = gaussian_smooth1(img, 2)\n\n    # show the smoothed image, and wait for a key to be pressed\n    cv2.imshow('smoothed_img', smoothed_img)\n    cv2.waitKey(0)\n", "meta": {"hexsha": "9df0b26dc1551ac76cc5ce900c3a6a11f07eb260", "size": 2649, "ext": "py", "lang": "Python", "max_stars_repo_path": "homework-assignments/1-smoothing_filter/smoothing1.py", "max_stars_repo_name": "arminnh/ma2-computer-vision", "max_stars_repo_head_hexsha": "9e931c87e097cd444ea292cdfff727636f003c36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework-assignments/1-smoothing_filter/smoothing1.py", "max_issues_repo_name": "arminnh/ma2-computer-vision", "max_issues_repo_head_hexsha": "9e931c87e097cd444ea292cdfff727636f003c36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework-assignments/1-smoothing_filter/smoothing1.py", "max_forks_repo_name": "arminnh/ma2-computer-vision", "max_forks_repo_head_hexsha": "9e931c87e097cd444ea292cdfff727636f003c36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.49, "max_line_length": 92, "alphanum_fraction": 0.6119290298, "include": true, "reason": "import numpy", "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399069145609, "lm_q2_score": 0.8807970811069351, "lm_q1q2_score": 0.8545844779838097}}
{"text": "import random as rd\nimport numpy as np\n\ndef genCluster(c, R, n):\n\t'''\n\tGenerate a cluster with:\n\t\tc :: center (two element tuple)\n\t\tR :: max radius(positive float)\n\t\tn :: number of points (positive int)\n\t'''\n\tpoints = np.empty([n,2])\n\tfor i in range(n):\n\t\tr = rd.uniform(0, R)\n\t\ttheta = rd.uniform(0, 2*np.pi)\n\t\tpoint = np.array([\n\t\t\tr*np.cos(theta) + c[0],\n\t\t\tr*np.sin(theta) + c[1]])\n\t\tpoints[i] = point\n\t\n\treturn points\n\ndef genClusters(c_vec, R_vec, n_vec):\n\n\tcluster_tup = tuple([genCluster(c_vec[i], R_vec[i], n_vec[i]) for i in range(len(c_vec))])\n\n\treturn np.concatenate(cluster_tup, axis=0)\n\ndef genPoisson(n):\n\t'''\n\tgenerate uniform random point cloud\n\tover [0,1]^2\n\t\tn :: number of points\n\t'''\n\tpoints = np.empty([n,2])\n\tfor i in range(n):\n\t\tpoint = np.array([\n\t\t\trd.uniform(0,1),\n\t\t\trd.uniform(0,1)])\n\t\tpoints[i] = point\n\n\treturn points\n\n# non-globular clusters\ndef genAnnulusCluster(c, R1, R2, n):\n\t'''\n\tGenerate an annulus cluster of points in [0,1]^2 with:\n\t\tc :: ring center\n\t\tR1 :: inner radius\n\t\tR2 :: outer radius\n\t'''\n\tpoints = np.empty([n,2])\n\tfor i in range(n):\n\t\tr = rd.uniform(R1, R2)\n\t\ttheta = rd.uniform(0, 2*np.pi)\n\t\tpoint = np.array([\n\t\t\tr*np.cos(theta) + c[0],\n\t\t\tr*np.sin(theta) + c[1]])\n\t\tpoints[i] = point\n\n\treturn points\n\n", "meta": {"hexsha": "82d649a804c483d0e7fdce3c189f49b7920bd2b6", "size": 1255, "ext": "py", "lang": "Python", "max_stars_repo_path": "Simple/src/simGenerate.py", "max_stars_repo_name": "jackmo375/Clustering", "max_stars_repo_head_hexsha": "f5fd3d045198993d7c87f12143fc75218e0f15cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Simple/src/simGenerate.py", "max_issues_repo_name": "jackmo375/Clustering", "max_issues_repo_head_hexsha": "f5fd3d045198993d7c87f12143fc75218e0f15cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Simple/src/simGenerate.py", "max_forks_repo_name": "jackmo375/Clustering", "max_forks_repo_head_hexsha": "f5fd3d045198993d7c87f12143fc75218e0f15cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2419354839, "max_line_length": 91, "alphanum_fraction": 0.6247011952, "include": true, "reason": "import numpy", "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970239909496136, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.854584471149858}}
{"text": "\"\"\"\nLogistic functions\n\nFunction List:\n1. logistic_sigmoid(x: float, a: float) -> float: calculate the normalized logistic sigmoid\n       with slope parameter a\n2. clipped_logistic_sigmoid(x: float, a: float) -> float: calculate the normalized logistic sigmoid\n       with slope parameter a clipped to a [0, 1] output range\n\"\"\"\nimport numpy as np\n\n\ndef logistic_sigmoid(x: float, a: float) -> float:\n    \"\"\"\n    Calculates the normalized logistic sigmoid as a function of x with parameterization on a\n\n    This function will be symmetric about 0.5\n\n    :param x: input value for calculation. Range: -inf to inf\n              will not clip at values to 0 and 1 outside of the 0 to 1 input range\n    :param a: value of the slope of the sigmoid. Values range from 0.5 for slope ~ 1 to\n              1.0 for slope ~ infinity. There's very little signal at a < 0.5\n    :return: the value of the normalized logistic sigmoid at x\n    \"\"\"\n\n    # set epsilon to be small. this is so we don't have divide by zero conditions\n    epsilon: float = 0.0001\n    # clip a to be between (0 + epsilon) and (1 - epsilon)\n    min_param_a: float = 0.0 + epsilon\n    max_param_a: float = 1.0 - epsilon\n    a = np.maximum(min_param_a, np.minimum(max_param_a, a))\n    # set a to be asymptotic at 1 and zero at 0\n    a = 1 / (1 - a) - 1\n\n    # calculate the numerator and denominator terms for the normalized sigmoid\n    A: float = 1.0 / (1.0 + np.exp(0 - ((x - 0.5) * a * 2.0)))\n    B: float = 1.0 / (1.0 + np.exp(a))\n    C: float = 1.0 / (1.0 + np.exp(0 - a))\n    y: float = (A - B) / (C - B)\n\n    return y\n\n\ndef clipped_logistic_sigmoid(x: float, a: float) -> float:\n    \"\"\"\n    Calculates the normalized logistic sigmoid as a function of x with parameterization on a\n\n    This function will be symmetric about 0.5\n\n    :param x: input value for calculation range: Range: -inf to inf, effective range 0 to 1\n              will output 0 for values below 0 and 1 for values above 1\n    :param a: value of the slope of the sigmoid. Values range from 0.5 for slope ~ 1 to\n              1.0 for slope ~ infinity. There's very little signal at a < 0.5\n    :return: the value of the normalized logistic sigmoid at x\n    \"\"\"\n\n    # clip values below zero and above one\n    x = np.maximum(x, 0.0)\n    x = np.minimum(x, 1.0)\n\n    # set epsilon to be small. this is so we don't have divide by zero conditions\n    epsilon: float = 0.0001\n    # clip a to be between (0 + epsilon) and (1 - epsilon)\n    min_param_a: float = 0.0 + epsilon\n    max_param_a: float = 1.0 - epsilon\n    a = np.maximum(min_param_a, np.minimum(max_param_a, a))\n    # set a to be asymptotic at 1 and zero at 0\n    a = 1 / (1 - a) - 1\n\n    # calculate the numerator and denominator terms for the normalized sigmoid\n    A: float = 1.0 / (1.0 + np.exp(0 - ((x - 0.5) * a * 2.0)))\n    B: float = 1.0 / (1.0 + np.exp(a))\n    C: float = 1.0 / (1.0 + np.exp(0 - a))\n    y: float = (A - B) / (C - B)\n\n    return y\n", "meta": {"hexsha": "6b177e62a880af96ffba39014db369c1953f2a0d", "size": 2944, "ext": "py", "lang": "Python", "max_stars_repo_path": "robogym/robot/utils/logistic_functions.py", "max_stars_repo_name": "0xflotus/robogym", "max_stars_repo_head_hexsha": "5ec2fcbda9828941fe3072792dd25fb5a915bbbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 288, "max_stars_repo_stars_event_min_datetime": "2020-11-12T21:39:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T23:27:50.000Z", "max_issues_repo_path": "robogym/robot/utils/logistic_functions.py", "max_issues_repo_name": "0xflotus/robogym", "max_issues_repo_head_hexsha": "5ec2fcbda9828941fe3072792dd25fb5a915bbbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-12-12T19:19:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T05:21:39.000Z", "max_forks_repo_path": "robogym/robot/utils/logistic_functions.py", "max_forks_repo_name": "0xflotus/robogym", "max_forks_repo_head_hexsha": "5ec2fcbda9828941fe3072792dd25fb5a915bbbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2020-11-12T22:31:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T20:34:48.000Z", "avg_line_length": 38.2337662338, "max_line_length": 99, "alphanum_fraction": 0.6348505435, "include": true, "reason": "import numpy", "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970239907775086, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.8545844681159962}}
{"text": "import math\r\nimport numpy as np\r\n\r\n#Lambda function for coefficient\r\ndef lambda_n(x):\r\n    if x == 0 :\r\n        return 1/math.sqrt(2)\r\n    else:\r\n        return 1\r\n\r\n#Summation part of 1d DCT\r\ndef summ_ct_1d(array, a_size, n):\r\n    summ = sum(map(lambda x: array[x] * math.cos( (n * math.pi / a_size) * (x + 1/2)), range(a_size)))\r\n    return summ\r\n\r\n#DCT 1d function\r\ndef dct_1d(array, a_size):\r\n    def mini_map(i):\r\n        return (2/a_size)**0.5 * lambda_n(i) * summ_ct_1d(array, a_size , i)\r\n    \r\n    output = list(map(mini_map, range(a_size)))\r\n    return output\r\n\r\n#DCT 1d function on an array of arrays\r\ndef dct2d_partial(array, a_size):\r\n    output = np.array(np.zeros([a_size,a_size]))\r\n    for i in range(a_size):\r\n        if i % 16 == 15:\r\n            print(\"1d dct progress : %d/%d\" % (i+1,a_size))\r\n        output[i] = dct_1d(array[i], a_size)\r\n    return output\r\n\r\n#DCT 2d function\r\ndef dct2d(array, a_size):\r\n    inter = dct2d_partial(array, a_size)\r\n    print(\"Progress : 50%\")\r\n    inter2 = dct2d_partial(np.transpose(inter), a_size)\r\n    print(\"Progress : 100%\")\r\n    return np.transpose(inter2)\r\n\r\n#Summation part of 1d iDCT \r\ndef summ_ict_1d(array, a_size, n):\r\n    summ = sum(map(lambda x: lambda_n(x) * array[x] * math.cos( (x * math.pi / a_size) * (n + 1/2)), range(a_size)))\r\n    return summ\r\n\r\n#iDCT 1d function\r\ndef idct_1d(array, a_size):\r\n    def mini_map(i):\r\n        return math.sqrt(2/a_size) * summ_ict_1d(array, a_size , i)\r\n\r\n    output = list(map(mini_map, range(a_size)))\r\n    return output\r\n\r\n#iDCT 1d function on an array of arrys    \r\ndef idct2d_partial(array, a_size):\r\n    output = np.array(np.zeros([a_size,a_size]))\r\n    for i in range(a_size):\r\n        if i % 16 == 15:\r\n            print(\"1d idct progress : %d/%d\" % (i+1,a_size))\r\n        array_r = array[i]\r\n        output_r = idct_1d(array_r, a_size)\r\n        for j in range(a_size):\r\n            output[i][j] = output_r[j]\r\n    return output\r\n\r\n#iDCT 2d function\r\ndef idct2d(array, a_size):\r\n    inter = idct2d_partial(array, a_size)\r\n    print(\"Progress : 50%\")\r\n    inter2 = idct2d_partial(np.transpose(inter), a_size)\r\n    print(\"Progress : 100%\")\r\n    return np.transpose(inter2)\r\n", "meta": {"hexsha": "5e05ef7d10ae4d499b12739861fb2eb71c491007", "size": 2186, "ext": "py", "lang": "Python", "max_stars_repo_path": "My Own Projects/Discrete Cosine Transform/DCTniDCT.py", "max_stars_repo_name": "Larvichee/StolenProjects", "max_stars_repo_head_hexsha": "50391655eed08c14388f7ddd05249cd0f2474c65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "My Own Projects/Discrete Cosine Transform/DCTniDCT.py", "max_issues_repo_name": "Larvichee/StolenProjects", "max_issues_repo_head_hexsha": "50391655eed08c14388f7ddd05249cd0f2474c65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "My Own Projects/Discrete Cosine Transform/DCTniDCT.py", "max_forks_repo_name": "Larvichee/StolenProjects", "max_forks_repo_head_hexsha": "50391655eed08c14388f7ddd05249cd0f2474c65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9452054795, "max_line_length": 117, "alphanum_fraction": 0.6061299177, "include": true, "reason": "import numpy", "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399069145609, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.8545844643221162}}
{"text": "from scipy import array, linspace\r\nfrom scipy import integrate\r\nfrom matplotlib.pyplot import *\r\n\r\ndef vector_field(X, t, r1, K1, c1, r2, K2, c2):\r\n    # Competing Species differential equations model\r\n    # from Section 9.4 of Boyce & DiPrima\r\n    # The differential equations are\r\n    #\r\n    #    dR\r\n    #    -- = r1*R*(1-R/K1) - c1*R*S\r\n    #    dt\r\n    #\r\n    #    dS\r\n    #    -- = r2*S*(1-S/K2) - c2*R*S\r\n    #    dt\r\n    R = X[0] # Rabbits density\r\n    S = X[1] # Sheep density\r\n    return array([r1*R*(1-R/K1) - c1*R*S,  r2*S*(1-S/K2) - c2*R*S])\r\n\r\n# set up our initial conditions\r\nR0 = 10.\r\nS0 = 20.\r\nX0 = array([R0, S0])\r\n\r\n# Parameters\r\nr1 = .3    # rabbit growth rate\r\nr2 = .2    # sheep growth rate\r\nc1 = .2    # inhibition of rabbits due to competition\r\nc2 = .1    # inhibition of sheep due to competition\r\nK1 = 30. # carrying capacity of rabbits\r\nK2 = 20. # carring capacity of sheep\r\n\r\n# choose the time's we'd like to know the approximate solution\r\nt = linspace(0., 60., 100)\r\n\r\n# and solve\r\nX = integrate.odeint(vector_field, X0, t, args=(r1,K1,c1,r2,K2,c2))\r\n\r\n# now, plot the solution curves\r\nfigure(1)\r\nplot(t, X[:,0], 'bx-', linewidth=2)\r\nplot(t, X[:,1], 'g+-', linewidth=2)\r\naxis([0,60,0,31])\r\nxlabel('Time (days)')\r\nylabel('Number')\r\n\r\nlegend(['Rabbits', 'Sheep'],loc=2)\r\n\r\nsavefig('CompetingSpecies2.png')\r\nshow()", "meta": {"hexsha": "f6ff9a909ef577191d96c9a9fd0d1e6d23626497", "size": 1339, "ext": "py", "lang": "Python", "max_stars_repo_path": "Basic ODE Models/Competing_Species.py", "max_stars_repo_name": "singhster96/Mini_Projs", "max_stars_repo_head_hexsha": "5ac4058febc5ba251d82c997be13c05929ce1697", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Basic ODE Models/Competing_Species.py", "max_issues_repo_name": "singhster96/Mini_Projs", "max_issues_repo_head_hexsha": "5ac4058febc5ba251d82c997be13c05929ce1697", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Basic ODE Models/Competing_Species.py", "max_forks_repo_name": "singhster96/Mini_Projs", "max_forks_repo_head_hexsha": "5ac4058febc5ba251d82c997be13c05929ce1697", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2549019608, "max_line_length": 68, "alphanum_fraction": 0.5929798357, "include": true, "reason": "from scipy", "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305360354471, "lm_q2_score": 0.8872045966995027, "lm_q1q2_score": 0.8545825592519746}}
{"text": "import numpy\nfrom functions import f\n\n# interpolation error by barycentric is \n# |f - p| <= (||f^(n+1)||_inf/(n+1)!) pi_{i=0}^{n} | x - x_i |\n\ndef centrix_weights(xnodes):\n    \"\"\"\n    computing the barycentric weights\n    w_j = 1/(pi*(x_j - x_i) { j \\= i})\n    Inputs : nodes x_j \n    output : weights w_j\n    \n    \"\"\"\n    weights = [0]*len(xnodes)\n    for j in range(len(xnodes)):\n        w = 1\n        for i in range(len(xnodes)):\n            if i != j:\n                w = w * (1/(xnodes[j] - xnodes[i]))\n        weights[j] = w\n    return weights\n\ndef evaluation(xnodes,weights,fvalues,value):\n    \"\"\"\n    Evaluating the barycentric interpolant p(x)\n    p(x) = \\sum_{j=0}^{n} ((w_j f(x_j))/(x-x_j))/ (\\sum_{j=0}^{n} w_j/(x-x_j))\n    where w_j = 1/(pi*(x_j - x_i) { j \\= i})\n    Inputs: nodes x_j, weights w_j, f(x_j) and the location of where teh interpolant should be evaluated\n    Output: p(x) at all the evaluation points\n    \"\"\"\n    num = 1\n    sum1 = 0\n    sum2 = 0\n    for j in range(len(xnodes)):\n        if value != xnodes[j]:\n            num = (weights[j]*fvalues[j])/(value - xnodes[j])\n            sum1 += num\n    for j in range(len(xnodes)):\n        if value != xnodes[j]:\n            num = (weights[j])/(value - xnodes[j])\n            sum2 += num\n    return sum1/sum2\n\n# vectorized versions\ndef vectorized_centric_weight(xnodes):\n    return 1/(xnodes[None, :] - xnodes[:, None] + eye(xnodes.size)).prod(axis=0)\n\n# the idenity matrix eye is included so that i =\\= j\ndef vectorized_evaluation(x, xnodes, ynodes, weights):\n    bary = weights[:, None]/(x[None, :] - xnodes[:, None] + eye(xnodes.size))\n    y = (bary*ynodes[:, None]).sum(axis=0)/bary.sum(axis=0)\n    return y\n", "meta": {"hexsha": "6257d1c0bf69e5c99a13a53b98127a9966041b8c", "size": 1687, "ext": "py", "lang": "Python", "max_stars_repo_path": "Polynomial-Interpolation/Lagrange_Polynomials.py", "max_stars_repo_name": "Robertboy18/Numerical-Algorithms-Implementation", "max_stars_repo_head_hexsha": "e1ea13137d42ccc2502c590559edba750db4592d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Polynomial-Interpolation/Lagrange_Polynomials.py", "max_issues_repo_name": "Robertboy18/Numerical-Algorithms-Implementation", "max_issues_repo_head_hexsha": "e1ea13137d42ccc2502c590559edba750db4592d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Polynomial-Interpolation/Lagrange_Polynomials.py", "max_forks_repo_name": "Robertboy18/Numerical-Algorithms-Implementation", "max_forks_repo_head_hexsha": "e1ea13137d42ccc2502c590559edba750db4592d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2407407407, "max_line_length": 104, "alphanum_fraction": 0.5666864256, "include": true, "reason": "import numpy", "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305318133554, "lm_q2_score": 0.8872045877523147, "lm_q1q2_score": 0.8545825468879108}}
{"text": "import numpy as np\n\n\n# This function calculates entropy on two variables\ndef calculateTwoClassEntropy(n, m):\n    return -(m / (m + n)) * np.log2(m / (m + n)) - (n / (m + n)) * np.log2(n / (m + n))\n\n\n# This function calculates entropy on many variables\ndef calculateMultiClassEntropy(P):\n    entropy = 0\n    # p1 = m / (m + n)\n    # p2 = n / (m + n)\n    for i in range(len(P)):\n        p_i = P[i] / sum(P)\n        entropy += p_i * np.log2(p_i)\n    return -1 * entropy\n\n\nprint(calculateTwoClassEntropy(4, 10))\n\nprint(calculateMultiClassEntropy([8, 3, 2]))\n", "meta": {"hexsha": "05d00cb6e086ebfc49119b600273ff079c52c6dc", "size": 554, "ext": "py", "lang": "Python", "max_stars_repo_path": "supervised-learning/decision-trees/entropy.py", "max_stars_repo_name": "gmendozah/intro-to-machine-learning-with-pytorch", "max_stars_repo_head_hexsha": "226730767d5e47590d5f71256577e604c43bf3f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-01-15T11:18:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T00:23:07.000Z", "max_issues_repo_path": "supervised-learning/decision-trees/entropy.py", "max_issues_repo_name": "gmendozah/intro-to-machine-learning-with-pytorch", "max_issues_repo_head_hexsha": "226730767d5e47590d5f71256577e604c43bf3f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "supervised-learning/decision-trees/entropy.py", "max_forks_repo_name": "gmendozah/intro-to-machine-learning-with-pytorch", "max_forks_repo_head_hexsha": "226730767d5e47590d5f71256577e604c43bf3f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-05T15:59:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T17:43:13.000Z", "avg_line_length": 24.0869565217, "max_line_length": 87, "alphanum_fraction": 0.5992779783, "include": true, "reason": "import numpy", "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9835969679646668, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.8545753944870645}}
{"text": "from argparse import ArgumentParser\nimport timeit\n\nimport numpy as np\n\n\ndef lr_decomp(A):\n    if A.ndim != 2:\n        raise ValueError('A must have 2 dimensions')\n    if A.shape[0] != A.shape[1]:\n        raise ValueError('A must be a square matrix')\n    A = np.copy(A)\n\n    n = A.shape[0]\n    for i in xrange(n - 1):\n        for j in xrange(i + 1, n):\n            c = -A[j, i] / A[i, i]\n            for k in xrange(i, n):\n                A[j, k] += A[i, k] * c\n            A[j, i] = -c\n\n    R = np.triu(A)\n    L = np.tril(A)\n    np.fill_diagonal(L, 1.)\n    return L, R\n\n\ndef cholesky_decomp(A):\n    if A.ndim != 2:\n        raise ValueError('A must have 2 dimensions')\n    if A.shape[0] != A.shape[1]:\n        raise ValueError('A must be a square matrix')\n\n    n = A.shape[0]\n    L = np.zeros(A.shape)\n    for i in xrange(n):\n        # diagonal elements\n        s = 0\n        for j in xrange(i):\n            s += np.square(L[i, j])\n        sqrt = np.sqrt(A[i, i] - s)\n        if np.isnan(sqrt):\n            raise ValueError('A is not a symmetric positive-definite matrix')\n        L[i, i] = sqrt\n\n        # elements in the rows below the current element (i,i)\n        for k in xrange(i + 1, n):\n            s = 0\n            for j in xrange(i):\n                s += L[k, j] * L[i, j]\n            L[k, i] = (A[k, i] - s) / L[i, i]\n    return L, L.T\n\n\ndef conjugate_gradients(A, b, x0, tol = 1e-3):\n    d_curr = r_curr = b - np.dot(A, x0)\n    x_curr = x0\n    while np.linalg.norm(r_curr) > tol * np.linalg.norm(b):\n        Ad = np.dot(A, d_curr)  # pre-calculate to avoid computing it twice\n\n        # Compute alpha such that x_curr + alpha * d_curr, i.e. going from x_curr in the search direction d_curr\n        # minimizes the distance between the solution in that single dimension.\n        alpha = np.dot(r_curr, r_curr) / np.dot(d_curr, Ad)\n        x_next = x_curr + alpha * d_curr\n\n        # Select the next search direction by computing the residual error first and then using the component of the\n        # error that is orthogonal to the current search direction as the new direction.\n        r_next = r_curr - alpha * Ad\n        beta = np.dot(r_next, r_next) / np.dot(r_curr, r_curr)\n        d_next = r_next + beta * d_curr\n\n        # Bookkeeping.\n        d_curr = d_next\n        r_curr = r_next\n        x_curr = x_next\n    return x_curr\n\n\ndef solve(L, R, b):\n    if L.shape != R.shape:\n        raise ValueError('L and R must have equal shapes')\n    if L.ndim != 2:\n        raise ValueError(\"L must have 2 dimensions\")\n    if L.shape[0] != L.shape[1]:\n        raise ValueError('L must be a square matrix')\n    if b.ndim != 1:\n        raise ValueError('b must be a vector')\n    if b.shape[0] != L.shape[0]:\n        raise ValueError('b must fit the dimension of L')\n    n = L.shape[0]\n\n    # Solve Ax = b where A = LR. Solve Ly = b first ...\n    y = np.zeros(b.shape)\n    y[0] = b[0] / L[0, 0]\n    for i in xrange(1, n):\n        s = 0\n        for j in xrange(i):\n            s += L[i, j] * y[j]\n        y[i] = (b[i] - s) / L[i, i]\n\n    # ... and then Rx = y.\n    x = np.zeros(b.shape)\n    x[n - 1] = y[n - 1] / R[n - 1, n - 1]\n    for i in xrange(n - 2, -1, -1):\n        s = 0\n        for j in xrange(n - 1, i, -1):\n            s += R[i, j] * x[j]\n        x[i] = (y[i] - s) / R[i, i]\n    return x\n\n\ndef main(args):\n    n_elems = args.n_elems\n\n    # Create random matrix A and matching vector b since we want to solve Ax = b.\n    A = np.random.random((n_elems, n_elems))\n    A = np.dot(A, A.T)  # make it s.p.d.\n    b = np.random.random(n_elems)\n\n    print('solving with LR decomposition ...')\n    start = timeit.default_timer()\n    L, R = lr_decomp(A)\n    x = solve(L, R, b)\n    duration = timeit.default_timer() - start\n    print('correct result' if np.allclose(np.dot(A, x), b) else 'wrong result')\n    print('done, took %fs' % duration)\n    print('')\n\n    print('solving with Cholesky decomposition ...')\n    start = timeit.default_timer()\n    L, R = cholesky_decomp(A)\n    x = solve(L, R, b)\n    duration = timeit.default_timer() - start\n    print('correct result' if np.allclose(np.dot(A, x), b) else 'wrong result')\n    print('done, took %fs' % duration)\n    print('')\n\n    print('solving with conjungate gradients ...')\n    start = timeit.default_timer()\n    x = conjugate_gradients(A, b, np.random.random(b.shape), tol=1e-5)\n    duration = timeit.default_timer() - start\n    print('correct result' if np.allclose(np.dot(A, x), b,  rtol=1e-2) else 'wrong result')\n    print('done, took %fs' % duration)\n\n\nif __name__ == '__main__':\n    parser = ArgumentParser()\n    parser.add_argument('--n-elems', type=int, default=100)\n    main(parser.parse_args())\n", "meta": {"hexsha": "e1e9641f6c8e67868e0332c48f147df81624e9c0", "size": 4663, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_eq.py", "max_stars_repo_name": "matthiasplappert/math-algorithms", "max_stars_repo_head_hexsha": "70bc7d85bb2106599f723a41426bfd4c9d26d580", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_eq.py", "max_issues_repo_name": "matthiasplappert/math-algorithms", "max_issues_repo_head_hexsha": "70bc7d85bb2106599f723a41426bfd4c9d26d580", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_eq.py", "max_forks_repo_name": "matthiasplappert/math-algorithms", "max_forks_repo_head_hexsha": "70bc7d85bb2106599f723a41426bfd4c9d26d580", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0866666667, "max_line_length": 116, "alphanum_fraction": 0.5584387733, "include": true, "reason": "import numpy", "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793907, "lm_q2_score": 0.8887587920192298, "lm_q1q2_score": 0.8545716246877787}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\ncsv = \"\"\"1896,4.47083333333333\n1900,4.46472925981123\n1904,5.22208333333333\n1908,4.1546786744085\n1912,3.90331674958541\n1920,3.5695126705653\n1924,3.8245447722874\n1928,3.62483706600308\n1932,3.59284275388079\n1936,3.53880791562981\n1948,3.6701030927835\n1952,3.39029110874116\n1956,3.43642611683849\n1960,3.2058300746534\n1964,3.13275664573212\n1968,3.32819844373346\n1972,3.13583757949204\n1976,3.07895880238575\n1980,3.10581822490816\n1984,3.06552909112454\n1988,3.09357348817\n1992,3.16111703598373\n1996,3.14255243512264\n2000,3.08527866650867\n2004,3.1026582928467\n2008,2.99877552632618\n2012,3.03392977050993\"\"\"\n\n\nif sys.version_info[0] >= 3:\n    import io # Python3\n    olympics = np.genfromtxt(io.BytesIO(csv.encode()), delimiter=\",\")\nelse:\n    from StringIO import StringIO  # Python2\n    olympics = np.genfromtxt(StringIO(csv), delimiter=',') #Python 2\n\n#print(olympics)\nx = olympics[:, 0:1] # two dimentional array, first : is to get all olympics[x], second is get olympics[x][0]\ny = olympics[:, 1:2]\n# print(x)\n# print(y)\n# plt.plot(x,y, 'rx')\n#plt.show()\nb = -0.4\n# print(len(x))\na = sum(y-b*x)/len(x)\nb = sum((y-a)*x)/sum(np.square(x))\nx_test = np.linspace(1890, 2020, 130)[:, None]\n# print(x_test)\nf_test = b*x_test + a\n# plt.plot(x_test, f_test, 'b-')\n# plt.plot(x, y, 'rx')\n#plt.show()\nSSR =  sum(np.square(y-a-b*x)) # over to you\n# print(SSR)\n\ndef iterativeSolution():\n    for i in np.arange(10000):\n        a = sum(y-b*x)/len(x) # np.mean(y-b*x)\n        b = sum((y-a)*x)/sum(np.square(x)) # ((y-a)*x).sum()/(x**2).sum()\n        SSR = sum(np.square(y-a-b*x))\n        if i % 500 == 0:\n            print('Iteration# ' ,i ,', training error SSR',SSR)\n    (a, b)\n    f_test = b*x_test + a\n    plt.plot(x_test, f_test, 'b-')\n    plt.plot(x, y, 'rx')\n    plt.show()\n\nX = np.hstack((np.ones_like(x), x))\n# print(X)\n\nw = np.linalg.solve(np.dot(X.T, X), np.dot(X.T, y)) # back to you\nprint(w)\n\na, b = w\nf_test = b*x_test + a\nplt.plot(x_test, f_test, 'b-')\nplt.plot(x, y, 'rx')\n\nSSR = sum(np.square(y-a-b*x)) # back to you\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#\n", "meta": {"hexsha": "c8cfdd1ef1ca3918eed008c80f3c9b280663f346", "size": 2090, "ext": "py", "lang": "Python", "max_stars_repo_path": "2_Linear_Polynomial_Regression/linearRegression.py", "max_stars_repo_name": "inverthermit/machine-learning-playboard", "max_stars_repo_head_hexsha": "aa265aa388fa44f59c733f7a3a7fa8fdf755fef5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-08-11T01:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-11T01:18:50.000Z", "max_issues_repo_path": "2_Linear_Polynomial_Regression/linearRegression.py", "max_issues_repo_name": "inverthermit/machine-learning-playboard", "max_issues_repo_head_hexsha": "aa265aa388fa44f59c733f7a3a7fa8fdf755fef5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2_Linear_Polynomial_Regression/linearRegression.py", "max_forks_repo_name": "inverthermit/machine-learning-playboard", "max_forks_repo_head_hexsha": "aa265aa388fa44f59c733f7a3a7fa8fdf755fef5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4901960784, "max_line_length": 109, "alphanum_fraction": 0.656937799, "include": true, "reason": "import numpy", "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724487, "lm_q2_score": 0.8933094103149354, "lm_q1q2_score": 0.8545703352977616}}
{"text": "\"\"\"\nImplementation of Linear Regression using Gradient Descent.\n\nLet m = #training examples, n = #number of features Sizes differ \na little bit from blog notation. It takes as input the following: \ny is R^(1 x m), X is R^(n x m), w is R^(n x 1)\n\nProgrammed by Aladdin Persson <aladdin.persson at hotmail dot com>\n*    2020-04-03 Initial coding\n*    2020-04-25 Updated comments, and small changes in code\n\"\"\"\n\nimport numpy as np\n\n\nclass LinearRegression:\n    def __init__(self, print_cost=False):\n        self.learning_rate = 0.01\n        self.total_iterations = 1000\n        self.print_cost = print_cost\n\n    def y_hat(self, X, w):\n        return np.dot(w.T, X)\n\n    def cost(self, yhat, y):\n        C = 1 / self.m * np.sum(np.power(yhat - y, 2))\n\n        return C\n\n    def gradient_descent(self, w, X, y, yhat):\n        dCdW = 2 / self.m * np.dot(X, (yhat - y).T)\n        w = w - self.learning_rate * dCdW\n\n        return w\n\n    def main(self, X, y):\n        # Add x1 = 1\n        ones = np.ones((1, X.shape[1]))\n        X = np.append(ones, X, axis=0)\n\n        self.m = X.shape[1]\n        self.n = X.shape[0]\n\n        w = np.zeros((self.n, 1))\n\n        for it in range(self.total_iterations + 1):\n            yhat = self.y_hat(X, w)\n            cost = self.cost(yhat, y)\n\n            if it % 2000 == 0 and self.print_cost:\n                print(f\"Cost at iteration {it} is {cost}\")\n\n            w = self.gradient_descent(w, X, y, yhat)\n\n        return w\n\n\nif __name__ == \"__main__\":\n    X = np.random.rand(1, 500)\n    y = 3 * X + 5 + np.random.randn(1, 500) * 0.1\n    regression = LinearRegression()\n    w = regression.main(X, y)\n", "meta": {"hexsha": "43573a7a773cf25a741b1cf76fd9bbed94db07e5", "size": 1630, "ext": "py", "lang": "Python", "max_stars_repo_path": "ML/algorithms/linearregression/linear_regression_gradient_descent.py", "max_stars_repo_name": "xuyannus/Machine-Learning-Collection", "max_stars_repo_head_hexsha": "6d5dcd18d4e40f90e77355d56a2902e4c617ecbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3094, "max_stars_repo_stars_event_min_datetime": "2020-09-20T04:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:59:46.000Z", "max_issues_repo_path": "ML/algorithms/linearregression/linear_regression_gradient_descent.py", "max_issues_repo_name": "xkhainguyen/Machine-Learning-Collection", "max_issues_repo_head_hexsha": "425d196e9477dbdbbd7cc0d19d29297571746ab5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 79, "max_issues_repo_issues_event_min_datetime": "2020-09-24T08:54:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:45:08.000Z", "max_forks_repo_path": "ML/algorithms/linearregression/linear_regression_gradient_descent.py", "max_forks_repo_name": "xkhainguyen/Machine-Learning-Collection", "max_forks_repo_head_hexsha": "425d196e9477dbdbbd7cc0d19d29297571746ab5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1529, "max_forks_repo_forks_event_min_datetime": "2020-09-20T16:21:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T21:16:25.000Z", "avg_line_length": 25.873015873, "max_line_length": 66, "alphanum_fraction": 0.5736196319, "include": true, "reason": "import numpy", "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633821, "lm_q2_score": 0.8933094039240554, "lm_q1q2_score": 0.8545703258706833}}
{"text": "import numpy as np\n\ndef softmax(x):\n\te_x = np.exp(x - np.max(x))\n\treturn e_x / e_x.sum(axis=0)\n\ndef linear(x):\n\treturn x\n\ndef relu(x):\n\treturn np.maximum(x, 0)\n\ndef sigmoid(x):\n\treturn 1 / (1 + np.exp(-x))\n\ndef elu(x,alpha=1):\n\tx[x<0]=alpha*np.expm1(x[x<0])\n\treturn x\n\ndef tanh(x):\n\treturn np.tanh(x)\n\ndef sin(x):\n\treturn np.sin(x)\n\nactivation_dict={\n\t'softmax':softmax,\n\t'linear':linear,\n\t'relu':relu,\n\t'elu':elu,\n\t'tanh':tanh,\n\t'sigmoid':sigmoid,\n\t'sin':sin\n}", "meta": {"hexsha": "d7743417b5a97767ef088b40f519f9459e87e29a", "size": 461, "ext": "py", "lang": "Python", "max_stars_repo_path": "mynn/activation.py", "max_stars_repo_name": "HashimHL/EvolveDNNRL", "max_stars_repo_head_hexsha": "a7d5bfad037af503a994f73f556e172bda825926", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-10T15:01:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-10T15:01:22.000Z", "max_issues_repo_path": "mynn/activation.py", "max_issues_repo_name": "HashimHL/EvolveDNNRL", "max_issues_repo_head_hexsha": "a7d5bfad037af503a994f73f556e172bda825926", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mynn/activation.py", "max_forks_repo_name": "HashimHL/EvolveDNNRL", "max_forks_repo_head_hexsha": "a7d5bfad037af503a994f73f556e172bda825926", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.5588235294, "max_line_length": 30, "alphanum_fraction": 0.6268980477, "include": true, "reason": "import numpy", "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068041, "lm_q2_score": 0.8991213833519948, "lm_q1q2_score": 0.8545348298817387}}
{"text": "# Computational Linear Algebra #4 Structured Gaussian Elimination\n# By: Nick Space Cowboy\n\nimport numpy as np\n\nclass Cowboy_Lin_Alg(object):\n\tdef solve_utri(self, Utri, b):\n\t\tn = len(Utri) # row dimension of the Utri matrix\n\t\tx = np.zeros_like(b, dtype=np.float64)\n\t\tfor i in range(n - 1, -1, -1):\t# loop to iterate through row index\n\t\t\tx[i] += b[i] / Utri[i,i]\n\t\t\tfor j in range(n-1, i, -1):\t# loop to iterate through the off diagonal Sum part\n\t\t\t\tx[i] += (- (Utri[i, j] * x[j])) / Utri[i,i]\n\t\treturn x\n\t\t\n\tdef SGE(self, A, b):\n\t\tn = len(A)\n\t\tl = np.zeros([n, n], dtype=np.float64)\n\t\tfor i in range(0, n, 1):\n\t\t\tfor j in range(i+1, n, 1):\n\t\t\t\tl[j,i] = A[j,i] / A[i,i]\n\t\t\t\tA[j] = A[j] - (l[j,i] * A[i])\n\t\t\t\tb[j] = b[j] - (l[j,i] * b[i])\n\t\treturn A, b\n\t\t\t\nif __name__ == \"__main__\":\t\t\n\tA = np.array(np.random.randint (0,100,(4,4)), dtype=np.float64)\n\tAc = A.copy()\n\tprint(\"A = \")\n\tprint(A)\n\tb = np.array(np.random.randint(0, 100, (4,1)), dtype=np.float64)\t\n\tprint(\"b = \")\n\tprint(b)\n\tcla = Cowboy_Lin_Alg()\n\tcla.SGE(A,b)\n\tx = cla.solve_utri(A, b)\n\tprint(\"U = \")\n\tprint(A)\n\tprint(\"c = \")\n\tprint(b)\n\tprint(\"x = \")\n\tprint(x)\n\tprint(\"Check Ax = \")\n\tprint(Ac.dot(x))\n", "meta": {"hexsha": "4cc3f6dad88e745abaa2a72a51c49e94ec854132", "size": 1160, "ext": "py", "lang": "Python", "max_stars_repo_path": "4_Structured_GE/struct_ge.py", "max_stars_repo_name": "nkphysics/Computational-Linear-Algebra-", "max_stars_repo_head_hexsha": "8e82585e25b58f73179c0b0ace63fcda9f480f07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-09T20:14:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T20:14:22.000Z", "max_issues_repo_path": "4_Structured_GE/struct_ge.py", "max_issues_repo_name": "nkphysics/Computational-Linear-Algebra-", "max_issues_repo_head_hexsha": "8e82585e25b58f73179c0b0ace63fcda9f480f07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4_Structured_GE/struct_ge.py", "max_forks_repo_name": "nkphysics/Computational-Linear-Algebra-", "max_forks_repo_head_hexsha": "8e82585e25b58f73179c0b0ace63fcda9f480f07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-12T12:27:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T12:27:21.000Z", "avg_line_length": 25.7777777778, "max_line_length": 82, "alphanum_fraction": 0.5775862069, "include": true, "reason": "import numpy", "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251321, "lm_q2_score": 0.8991213725394589, "lm_q1q2_score": 0.8545348246569447}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nfrom ggplot import *\n\n\"\"\"\nIn this question, you need to:\n1) implement the compute_cost() and gradient_descent() procedures\n2) Select features (in the predictions procedure) and make predictions.\n\"\"\"\n\n\ndef normalize_features(df):\n    \"\"\"\n    Normalize the features in the data set.\n    \"\"\"\n    mu = df.mean()\n    sigma = df.std()\n\n    if (sigma == 0).any():\n        raise Exception(\n            \"\"\"\" One or more features had the same value for all samples, and thus could not be normalized.\n            Please do not include features with only a single value in your model.\") \"\"\")\n\n    df_normalized = (df - df.mean()) / df.std()\n\n    return df_normalized, mu, sigma\n\n\ndef compute_cost(features, values, theta):\n    \"\"\"\n    Compute the cost function given a set of features / values, \n    and the values for our thetas.\n\n    This can be the same code as the compute_cost function in the lesson #3 exercises,\n    but feel free to implement your own.\n    \"\"\"\n    cost = np.sum(np.square(np.dot(features, theta) - values)) / (2 * len(values))\n    return cost\n\n\ndef gradient_descent(features, values, theta, alpha, num_iterations):\n    \"\"\"\n    Perform gradient descent given a data set with an arbitrary number of features.\n\n    This can be the same gradient descent code as in the lesson #3 exercises,\n    but feel free to implement your own.\n    \"\"\"\n    cost_history = []\n    for i in range(num_iterations):\n        predicted = np.dot(features, theta)\n        theta += alpha / len(values) * np.dot((values - predicted), features)\n        cost_history.append(compute_cost(features, values, theta))\n    return theta, pd.Series(cost_history)\n\n\ndef predictions(dataframe):\n    \"\"\"\n    The NYC turnstile data is stored in a pandas dataframe called weather_turnstile.\n    Using the information stored in the dataframe, let's predict the ridership of\n    the NYC subway using linear regression with gradient descent.\n\n    You can download the complete turnstile weather dataframe here:\n    https://www.dropbox.com/s/meyki2wl9xfa7yk/turnstile_data_master_with_weather.csv    \n\n    Your prediction should have a R^2 value of 0.40 or better.\n    You need to experiment using various input features contained in the dataframe. \n    We recommend that you don't use the EXITSn_hourly feature as an input to the \n    linear model because we cannot use it as a predictor: we cannot use exits \n    counts as a way to predict entry counts. \n\n    Note: Due to the memory and CPU limitation of our Amazon EC2 instance, we will\n    give you a random subet (~15%) of the data contained in \n    turnstile_data_master_with_weather.csv. You are encouraged to experiment with \n    this computer on your own computer, locally. \n\n\n    If you'd like to view a plot of your cost history, uncomment the call to \n    plot_cost_history below. The slowdown from plotting is significant, so if you \n    are timing out, the first thing to do is to comment out the plot command again.\n\n    If you receive a \"server has encountered an error\" message, that means you are \n    hitting the 30-second limit that's placed on running your program. Try using a \n    smaller number for num_iterations if that's the case.\n\n    If you are using your own algorithm/models, see if you can optimize your code so \n    that it runs faster.\n    \"\"\"\n    # Select Features (try different features!)\n    features = dataframe[['rain', 'precipi', 'Hour', 'meantempi']]\n\n    # Add UNIT to features using dummy variables\n    dummy_units = pd.get_dummies(dataframe['UNIT'], prefix='unit')\n    features = features.join(dummy_units)\n\n    # Values\n    values = dataframe['ENTRIESn_hourly']\n    m = len(values)\n\n    features, mu, sigma = normalize_features(features)\n    features['ones'] = np.ones(m)  # Add a column of 1s (y intercept)\n\n    # Convert features and values to numpy arrays\n    features_array = np.array(features)\n    values_array = np.array(values)\n\n    # Set values for alpha, number of iterations.\n    alpha = 0.1  # please feel free to change this value\n    num_iterations = 40  # please feel free to change this value\n\n    # Initialize theta, perform gradient descent\n    theta_gradient_descent = np.zeros(len(features.columns))\n    theta_gradient_descent, cost_history = gradient_descent(features_array,\n                                                            values_array,\n                                                            theta_gradient_descent,\n                                                            alpha,\n                                                            num_iterations)\n\n    # plot = None\n    # -------------------------------------------------\n    # Uncomment the next line to see your cost history\n    # -------------------------------------------------\n    plot = plot_cost_history(alpha, cost_history)\n    #\n    # Please note, there is a possibility that plotting\n    # this in addition to your calculation will exceed\n    # the 30 second limit on the compute servers.\n\n    pred = np.dot(features_array, theta_gradient_descent)\n    return pred, plot\n\n\ndef plot_cost_history(alpha, cost_history):\n    \"\"\"This function is for viewing the plot of your cost history.\n    You can run it by uncommenting this \n        plot_cost_history(alpha, cost_history)  \n    call in predictions.\n \n    If you want to run this locally, you should print the return value\n    from this function.\n    \"\"\"\n    cost_df = pd.DataFrame({\n        'Cost_History': cost_history,\n        'Iteration': range(len(cost_history))\n    })\n    return ggplot(cost_df, aes('Iteration', 'Cost_History')) + \\\n           geom_point() + ggtitle('Cost History for alpha = %.3f' % alpha)\n\n\n# PLOTTING RESIDUALS\n\ndef plot_residuals(turnstile_weather, predictions):\n    \"\"\"\n    Using the same methods that we used to plot a histogram of entries\n    per hour for our data, why don't you make a histogram of the residuals\n    (that is, the difference between the original hourly entry data and the predicted values).\n    Try different binwidths for your histogram.\n\n    Based on this residual histogram, do you have any insight into how our model\n    performed?  Reading a bit on this webpage might be useful:\n\n    http://www.itl.nist.gov/div898/handbook/pri/section2/pri24.htm\n    \"\"\"\n\n    plt.figure()\n    (turnstile_weather['ENTRIESn_hourly'] - predictions).hist(bins=100)\n    plt.title('Residuals')\n    plt.axis([-5000, 5000, 0, 40000])\n    return plt\n\n\ndef compute_r_squared(data, predictions):\n    \"\"\"\n    In exercise 5, we calculated the R^2 value for you. But why don't you try and\n    and calculate the R^2 value yourself.\n\n    Given a list of original data points, and also a list of predicted data points,\n    write a function that will compute and return the coefficient of determination (R^2)\n    for this data.  numpy.mean() and numpy.sum() might both be useful here, but\n    not necessary.\n\n    Documentation about numpy.mean() and numpy.sum() below:\n    http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html\n    http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html\n    \"\"\"\n\n    # your code here\n    r_squared = 1 - np.sum(np.square(data - predictions)) / np.sum(np.square(data - np.average(data)))\n\n    return r_squared\n\n\n\"\"\"\nIn this optional exercise, you should complete the function called \npredictions(turnstile_weather). This function takes in our pandas \nturnstile weather dataframe, and returns a set of predicted ridership values,\nbased on the other information in the dataframe.  \n\nIn exercise 3.5 we used Gradient Descent in order to compute the coefficients\ntheta used for the ridership prediction. Here you should attempt to implement \nanother way of computing the coeffcients theta. You may also try using a reference implementation such as: \nhttp://statsmodels.sourceforge.net/devel/generated/statsmodels.regression.linear_model.OLS.html\n\nOne of the advantages of the statsmodels implementation is that it gives you\neasy access to the values of the coefficients theta. This can help you infer relationships \nbetween variables in the dataset.\n\nYou may also experiment with polynomial terms as part of the input variables.  \n\nThe following links might be useful: \nhttp://en.wikipedia.org/wiki/Ordinary_least_squares\nhttp://en.wikipedia.org/w/index.php?title=Linear_least_squares_(mathematics)\nhttp://en.wikipedia.org/wiki/Polynomial_regression\n\nThis is your playground. Go wild!\n\nHow does your choice of linear regression compare to linear regression\nwith gradient descent computed in Exercise 3.5?\n\nYou can look at the information contained in the turnstile_weather dataframe below:\nhttps://s3.amazonaws.com/content.udacity-data.com/courses/ud359/turnstile_data_master_with_weather.csv\n\nNote: due to the memory and CPU limitation of our amazon EC2 instance, we will\ngive you a random subset (~10%) of the data contained in turnstile_data_master_with_weather.csv\n\nIf you receive a \"server has encountered an error\" message, that means you are hitting \nthe 30 second limit that's placed on running your program. See if you can optimize your code so it\nruns faster.\n\"\"\"\n\n\ndef predictions_ols(dataframe):\n    features = dataframe[['rain', 'precipi', 'Hour', 'meantempi']]\n    # Add UNIT to features using dummy variables\n    dummy_units = pd.get_dummies(dataframe['UNIT'], prefix='unit')\n    features = features.join(dummy_units)\n    # Values\n    values = dataframe['ENTRIESn_hourly']\n    m = len(values)\n\n    features, mu, sigma = normalize_features(features)\n    features['ones'] = np.ones(m)  # Add a column of 1s (y intercept)\n\n    # Convert features and values to numpy arrays\n    features_array = np.array(features)\n    values_array = np.array(values)\n\n    model = sm.OLS(values_array, features_array)\n    results = model.fit()\n\n    pred = np.dot(features_array, results.params)\n    return pred\n\n\nif __name__ == \"__main__\":\n    turnstile_weather = pd.read_csv('MTA_Subway_turnstile/turnstile_data_master_with_weather.csv')\n    pre = predictions(turnstile_weather)[0]\n    data = turnstile_weather['ENTRIESn_hourly']\n\n    print(predictions(turnstile_weather)[1])  # plot cost history\n\n    # plotting residuals\n    plot_residuals(turnstile_weather, pre).show()\n\n    # computing R^2\n    print(\"R^2 = \", compute_r_squared(data, pre))\n\n    # optional prediction: ordinary least squares (OLS)\n    pre_OLS = predictions_ols(turnstile_weather)\n    print(\"R^2 (OLS) = \", compute_r_squared(data, pre_OLS))\n    plot_residuals(turnstile_weather, pre).show()\n", "meta": {"hexsha": "e4b57b303e428da14835d9c8b744d334afb62cf7", "size": 10546, "ext": "py", "lang": "Python", "max_stars_repo_path": "L3_Data_Analysis/P3_linear_regression.py", "max_stars_repo_name": "angelmtenor/IDSFC", "max_stars_repo_head_hexsha": "3a08bca7d10604dbd3be256e2ee4d0caf6b90d81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "L3_Data_Analysis/P3_linear_regression.py", "max_issues_repo_name": "angelmtenor/IDSFC", "max_issues_repo_head_hexsha": "3a08bca7d10604dbd3be256e2ee4d0caf6b90d81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "L3_Data_Analysis/P3_linear_regression.py", "max_forks_repo_name": "angelmtenor/IDSFC", "max_forks_repo_head_hexsha": "3a08bca7d10604dbd3be256e2ee4d0caf6b90d81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.63003663, "max_line_length": 107, "alphanum_fraction": 0.7014033757, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 2330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.9005297927918167, "lm_q1q2_score": 0.8545282688664839}}
{"text": "import pandas as pd\nimport numpy as np\n\n# Create an empty dataframe\ndata = pd.DataFrame()\n\n# Create our target variable\ndata['Defective'] = ['No', 'No', 'No', 'Yes', 'Yes']\n\n# Create our feature variables\ndata['Branch'] = [5, 3, 9, 15, 16]\ndata['LOC'] = [15, 5, 20, 40, 35]\n\n# View the data\nprint(data)\n\ntest_defect = pd.DataFrame()\n\ntest_defect['Branch'] = [16]\ntest_defect['LOC'] = [39]\n\nprint()\nprint(test_defect)\n\nn_defective = data['Defective'][data['Defective'] == 'Yes'].count()\nn_non_defective = data['Defective'][data['Defective'] == 'No'].count()\ntotal_defect = data['Defective'].count()\n\n# Number of males divided by the total rows\nP_defective = n_defective/total_defect\n\n# Number of females divided by the total rows\nP_non_defective = n_non_defective/total_defect\n\n# Group the data by gender and calculate the means of each feature\ndata_means = data.groupby('Defective').mean()\n\n# View the values\nprint()\nprint(\"--------- Data Means -----------\")\nprint(data_means)\n\n# Group the data by gender and calculate the variance of each feature\ndata_variance = data.groupby('Defective').var()\n\n# View the values\nprint()\nprint(\"-------- Data Variance ----------\")\nprint(data_variance)\n\n# Means for male\ndefective_bc_mean = data_means['Branch'][data_variance.index == 'Yes'].values[0]\ndefective_loc_mean = data_means['LOC'][data_variance.index == 'Yes'].values[0]\n\n# Variance for male\ndefective_bc_variance = data_variance['Branch'][data_variance.index == 'Yes'].values[0]\ndefective_loc_variance = data_variance['LOC'][data_variance.index == 'Yes'].values[0]\n\n# Means for female\nnon_defective_bc_mean = data_means['Branch'][data_variance.index == 'No'].values[0]\nnon_defective_loc_mean = data_means['LOC'][data_variance.index == 'No'].values[0]\n\n# Variance for female\nnon_defective_bc_variance = data_variance['Branch'][data_variance.index == 'No'].values[0]\nnon_defective_loc_variance = data_variance['LOC'][data_variance.index == 'No'].values[0]\n\nprint()\nprint(defective_bc_mean, defective_loc_mean, defective_bc_variance, defective_loc_variance)\n\n# Create a function that calculates p(x | y):\ndef p_x_given_y(x, mean_y, variance_y):\n\n    # Input the arguments into a probability density function\n    p = 1/(np.sqrt(2*np.pi*variance_y)) * np.exp((-(x-mean_y)**2)/(2*variance_y))\n\n    # return p\n    return p\n\nprint()\na = P_defective *p_x_given_y(test_defect['Branch'][0], defective_bc_mean, defective_bc_variance) * \\\n    p_x_given_y(test_defect['LOC'][0], defective_bc_mean, defective_bc_variance)\n\nb = P_non_defective * p_x_given_y(test_defect['Branch'][0], non_defective_bc_mean, non_defective_bc_variance) *\\\n    p_x_given_y(test_defect['LOC'][0], non_defective_bc_mean, non_defective_bc_variance)\n\nif a > b:\n    print(\"Defect\")\nelse:\n    print(\"No-Defect\")", "meta": {"hexsha": "1028d1b04253f9c17ecf6a4cb6c5dc53bd759660", "size": 2764, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine_learning_bootcamp/new_bayes.py", "max_stars_repo_name": "pujahabibi/Naive-Bayes-Practice", "max_stars_repo_head_hexsha": "b97b651fab65a39addcfef59bc8c0e7058de4c36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "machine_learning_bootcamp/new_bayes.py", "max_issues_repo_name": "pujahabibi/Naive-Bayes-Practice", "max_issues_repo_head_hexsha": "b97b651fab65a39addcfef59bc8c0e7058de4c36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "machine_learning_bootcamp/new_bayes.py", "max_forks_repo_name": "pujahabibi/Naive-Bayes-Practice", "max_forks_repo_head_hexsha": "b97b651fab65a39addcfef59bc8c0e7058de4c36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0561797753, "max_line_length": 112, "alphanum_fraction": 0.7239507959, "include": true, "reason": "import numpy", "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812354689082, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.8545265965119777}}
{"text": "import numpy as np\nimport math\n\n\n\n# Compute the intersection distance between histograms x and y\n# Return 1 - hist_intersection, so smaller values correspond to more similar histograms\n# Check that the distance range in [0,1]\n\ndef dist_intersect(x,y):\n  s = 0\n  for q,v in zip(x,y):\n    s = s + min(q,v)\n\n  s = s/np.sum(x) + s/np.sum(y)\n  s = s/2\n\n  s = 1 - s\n  if s < 0:\n    s = 0\n\n  if s > 1:\n    s = 1\n\n  return s\n\n\n\n# Compute the L2 distance between x and y histograms\n# Check that the distance range in [0,sqrt(2)]\n\ndef dist_l2(x,y):   \n  s = 0\n  for q,v in zip(x,y):\n    s = s + pow(q - v,2)\n\n  if s < 0:\n    s = 0\n\n  if s > np.sqrt(2):\n    s = np.sqrt(2)\n\n  return s\n\n\n\n# Compute chi2 distance between x and y\n# Check that the distance range in [0,Inf]\n# Add a minimum score to each cell of the histograms (e.g. 1) to avoid division by 0\n\ndef dist_chi2(x,y):\n  s = 0\n  for q,v in zip(x,y):\n    if q+v != 0:\n      s = s + pow(q-v,2)/(q+v)\n    else :\n      s = s + pow(q-v,2)\n\n  if s < 0:\n    s = 0\n\n  return s\n\n\ndef get_dist_by_name(x, y, dist_name):\n  if dist_name == 'chi2':\n    return dist_chi2(x,y)\n  elif dist_name == 'intersect':\n    return dist_intersect(x,y)\n  elif dist_name == 'l2':\n    return dist_l2(x,y)\n  else:\n    assert False, 'unknown distance: %s'%dist_name\n  \n\n\n\n\n", "meta": {"hexsha": "a7faedd0bf070da19e17bb36894da873d5490d19", "size": 1289, "ext": "py", "lang": "Python", "max_stars_repo_path": "Homework_1/Identification/dist_module.py", "max_stars_repo_name": "arywatt/AML_2020_2021", "max_stars_repo_head_hexsha": "aea49968d564c554a6abd399a569ca0ef2955a0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homework_1/Identification/dist_module.py", "max_issues_repo_name": "arywatt/AML_2020_2021", "max_issues_repo_head_hexsha": "aea49968d564c554a6abd399a569ca0ef2955a0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homework_1/Identification/dist_module.py", "max_forks_repo_name": "arywatt/AML_2020_2021", "max_forks_repo_head_hexsha": "aea49968d564c554a6abd399a569ca0ef2955a0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.3164556962, "max_line_length": 87, "alphanum_fraction": 0.5942591156, "include": true, "reason": "import numpy", "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812354689082, "lm_q2_score": 0.882427872638409, "lm_q1q2_score": 0.8545265935177829}}
{"text": "import numpy as np\n\ndef sigmoid(z):\n    \"\"\"\n    Sigmoid activation function.\n        g(z) = 1 / (1 + e^-z)\n    \"\"\"\n    return 1/(1+np.exp(-z))\n\ndef tanh(z):\n    \"\"\"\n    Tanh activation function.\n        g(z) = tanh(z)\n    \"\"\"\n    return np.tanh(z)\n\ndef relu(z):\n    \"\"\"\n    Relu activation function.\n        g(z) = max(0, z)\n    \"\"\"\n    return z*(z > 0)\n\ndef softmax(z, axis=-1):\n    \"\"\"\n    Softmax activation function. Use at the output layer.\n        g(z) = e^z / sum(e^z)\n    \"\"\"\n    z_prime = z - np.max(z, axis=axis, keepdims=True)\n    return np.exp(z_prime) / np.sum(np.exp(z_prime), axis=axis, keepdims=True)\n\ndef sigmoid_grad(z):\n    \"\"\"\n    Sigmoid derivative.\n        g'(z) = g(z)(1-g(z))\n    \"\"\"\n    return z*(1-z)\n\ndef tanh_grad(z):\n    \"\"\"\n    Tanh derivative.\n        g'(z) = 1 - g^2(z).\n    \"\"\"\n    return 1 - z**2\n\ndef relu_grad(z):\n    \"\"\"\n    Relu derivative.\n        g'(z) = 0 if g(z) <= 0\n        g'(z) = 1 if g(z) > 0\n    \"\"\"\n    return 1*(z > 0)", "meta": {"hexsha": "d29828abd0d356523110ba3571caf2740ceaf73e", "size": 968, "ext": "py", "lang": "Python", "max_stars_repo_path": "nn_components/activations.py", "max_stars_repo_name": "giangtranml/framgia-training", "max_stars_repo_head_hexsha": "c7fb343bd43b1bceb241b447ff956febb99c94a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-06T09:39:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-06T09:39:42.000Z", "max_issues_repo_path": "nn_components/activations.py", "max_issues_repo_name": "giangtranml/framgia-training", "max_issues_repo_head_hexsha": "c7fb343bd43b1bceb241b447ff956febb99c94a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nn_components/activations.py", "max_forks_repo_name": "giangtranml/framgia-training", "max_forks_repo_head_hexsha": "c7fb343bd43b1bceb241b447ff956febb99c94a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6153846154, "max_line_length": 78, "alphanum_fraction": 0.4834710744, "include": true, "reason": "import numpy", "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.968381236381426, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.8545265868375265}}
{"text": "import numpy as np\n\n\ndef plane_coeff(x, y, z):\n    # Credit: amroamroamro gist on github\n    x = np.asarray(x)\n    y = np.asarray(y)\n    z = np.asarray(z)\n    A = np.c_[x.ravel(), y.ravel(), np.ones(z.ravel().size)]\n    C, _, _, _ = np.linalg.lstsq(A, z.ravel(), rcond=None)  # coefficients\n    return C\n\n\ndef cartesian_gradient(f, x, y):\n    \"\"\"\n    f : 2d array\n    x : 1d array (colums)\n    y : 1d array (rows)\n\n    \"\"\"\n    f = np.asarray(f)\n    x = np.asarray(x)\n    y = np.asarray(y)\n\n    nr, nc = f.shape\n    if (nr != len(y)) or (nc != len(x)):\n        raise ValueError(\"y and x are expected to be rows and columns respectively\")\n\n    dfdy = np.gradient(f, y, axis=0)\n    dfdx = np.gradient(f, x, axis=1)\n\n    return dfdx, dfdy\n\n\ndef spherical_polar_gradient(f, lon, lat, r=6371000.0):\n    \"\"\"\n    f : scalar array\n    lon : 1d array -180 to 180\n    lat : 1d array -90 to 90\n    Doesn't deal with the dateline...?\n    \"\"\"\n    f = np.asarray(f)\n    lon = np.deg2rad(np.asarray(lon))\n    lat = np.deg2rad(np.asarray(lat))\n\n    nr, nc = f.shape\n    if (nr != len(lat)) or (nc != len(lon)):\n        raise ValueError(\n            \"Latitude and longitude are expected to be rows and columns respectively\"\n        )\n\n    _, latg = np.meshgrid(lon, lat)\n\n    # Cosine because latitude from -pi/2 to pi/2. Not 0 to pi.\n    dfdlat = np.gradient(f, lat, axis=0) / r\n    dfdlon = np.gradient(f, lon, axis=1) / (r * np.cos(latg))\n\n    return dfdlon, dfdlat\n\n\ndef haversine(theta):\n    return 0.5 * (1 - np.cos(theta))\n\n\ndef archaversine(y):\n    return np.arccos(1 - 2 * y)\n\n\ndef haversine_distance(lon0, lat0, lon1, lat1, r=6371000.0):\n    \"\"\"Calculates the distance between longitude and latitude coordinates on a\n    spherical earth with radius using the Haversine formula.\n\n    Parameters\n    ----------\n    lon0 : 1d numpy array\n        Longitude values. [degrees]\n    lat0 : 1d numpy array\n        Latitude values. [degrees]\n    lon1 : 1d numpy array\n        Longitude values. [degrees]\n    lat1 : 1d numpy array\n        Latitude values. [degrees]\n\n    Returns\n    -------\n    dist : 1d numpy array\n        Distance between lon and lat positions. [m]\n\n    \"\"\"\n\n    lon0 = np.deg2rad(lon0)\n    lat0 = np.deg2rad(lat0)\n    lon1 = np.deg2rad(lon1)\n    lat1 = np.deg2rad(lat1)\n\n    dist = r * archaversine(\n        haversine(lat1 - lat0) + np.cos(lat1) * np.cos(lat2) * haversine(lon1 - lon0)\n    )\n\n    return dist\n\n\n# Projecting to UTM with pyproj: https://gist.github.com/twpayne/4409500\n", "meta": {"hexsha": "8ac4e8b07535c29a0b3756068ccacdfc3229ae3e", "size": 2486, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyobjmap/utils.py", "max_stars_repo_name": "jessecusack/pyobjmap", "max_stars_repo_head_hexsha": "e973a74c23a386363926a74723040285ee5c278a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyobjmap/utils.py", "max_issues_repo_name": "jessecusack/pyobjmap", "max_issues_repo_head_hexsha": "e973a74c23a386363926a74723040285ee5c278a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-08-11T23:49:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-11T23:55:03.000Z", "max_forks_repo_path": "pyobjmap/utils.py", "max_forks_repo_name": "jessecusack/pyobjmap", "max_forks_repo_head_hexsha": "e973a74c23a386363926a74723040285ee5c278a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9038461538, "max_line_length": 85, "alphanum_fraction": 0.5953338697, "include": true, "reason": "import numpy", "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812318188365, "lm_q2_score": 0.8824278680004707, "lm_q1q2_score": 0.8545265858055655}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 14 11:05:25 2021\r\n\r\n@author: Oscar\r\n\"\"\"\r\n\r\n\"Tutorial 10 \"\r\nimport math as m\r\nimport sympy as sp\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#%% Question 1: Deflection of a beam\r\n# A) use numerical integration to compute the deflection\r\n\r\n# Define the variables and equations\r\n\r\n# Length of beam\r\nL = 3 #m\r\n# interval size\r\ndelta_x = 0.125 #m\r\ninterval = L/delta_x\r\n# Modulus of Elasticity\r\nE = 2e11 # 200 Gpa ~ 2e5 MPa\r\n# Moment of inertia\r\nI = 3e-4 # m^4\r\n# Distributed load\r\nw0 = 250000 # 2.5N/cm or 250000N/m\r\n\r\n# Define Functions using Sympy\r\nx = sp.Symbol('x')\r\nf = (w0*(-5 * x**4 + (6 * L**2) * x**2 -L**4))/(120*E*I*L)\r\ntheta = sp.lambdify(x, f)\r\n\r\n# Function to perform calculations \r\ndef SimpsonsThird(lower_limit, upper_limit, interval): \r\n     \r\n    interval_size = (float(upper_limit - lower_limit) / interval) #dx or h`\r\n    sum = theta(lower_limit) + theta(upper_limit); \r\n       \r\n    # Calculates value till integral limit \r\n    for i in range(1, interval ):\r\n        \r\n        if (i % 3 == 0): \r\n            sum = sum + 2 * theta(lower_limit + i * interval_size) \r\n        else: \r\n            sum = sum + 3 * theta(lower_limit + i * interval_size) \r\n      \r\n    return ((float( 3 * interval_size) / 8 ) * sum ) \r\n  \r\nintegral_res = SimpsonsThird(0, L/2, 24) \r\nprint('The value of the deflection at the midpoint of the beam (x = 1.5 m) is ', integral_res)\r\n\r\n#%% Question 1B): Numerical differention to computed moment and shear\r\n\r\n# Moment = d/dx (theta)*EI\r\n# Shear =d/dx (Moment)\r\n\r\ng = sp.diff(f, x)\r\nMoment = sp.lambdify(x, g)\r\nsolution = Moment(3)*(E*I)\r\nprint('The Moment is %.2f' %solution, 'at x = 3 m.')\r\n\r\nv = sp.diff(f, x, 2)\r\nShear = sp.lambdify(x, v)\r\nforce = Shear(3)*E*I\r\nprint('The Shear is %.2f' %force, 'at x = 3 m ')\r\n\r\n", "meta": {"hexsha": "f0958e45eea70b903bb67961369ccd75b7f1e57f", "size": 1817, "ext": "py", "lang": "Python", "max_stars_repo_path": "Beams under UDL.py", "max_stars_repo_name": "oliver779/Computational_Methods_Course", "max_stars_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Beams under UDL.py", "max_issues_repo_name": "oliver779/Computational_Methods_Course", "max_issues_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Beams under UDL.py", "max_forks_repo_name": "oliver779/Computational_Methods_Course", "max_forks_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9571428571, "max_line_length": 95, "alphanum_fraction": 0.607044579, "include": true, "reason": "import numpy,import sympy", "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812345563902, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.854526585227064}}
{"text": "import numpy as np\r\nfrom scipy import integrate, optimize\r\nimport matplotlib.pyplot as plt\r\n\r\nG1, G2, k1, k2, alpha1, alpha2, N0 = np.array([3.0, 2.0, 1.0, 1.0, 0.5, 0.5, 3.0])\r\ndef f(Y, t):\r\n    y1, y2 = Y\r\n    return [G1*(N0 - (alpha1*y1) - (alpha2*y2))*y1 - k1*y1, G2*(N0 - (alpha1*y1) - (alpha2*y2))*y2 - k2*y2]\r\n\r\nm1, m2 = np.array([10, 10])\r\ny1 = np.linspace(-m1, m1, 20)\r\ny2 = np.linspace(-m2, m2, 20)\r\n\r\nY1, Y2 = np.meshgrid(y1, y2)\r\n\r\nt = 0\r\n\r\nu, v = np.zeros(Y1.shape), np.zeros(Y2.shape)\r\n\r\nNI, NJ = Y1.shape\r\n\r\nfor i in range(NI):\r\n    for j in range(NJ):\r\n        x = Y1[i, j]\r\n        y = Y2[i, j]\r\n        yprime = f([x, y], t)\r\n        u[i,j] = yprime[0]\r\n        v[i,j] = yprime[1]\r\n     \r\n\r\nQ = plt.quiver(Y1, Y2, u, v, color='r')\r\n\r\nplt.xlabel('$n_1$')\r\nplt.ylabel('$n_2$')\r\nplt.xlim([-m1, m1])\r\nplt.ylim([-m2, m2])\r\nplt.show()", "meta": {"hexsha": "e9cbba11453c3ce806cfaa49ec02844366e15107", "size": 846, "ext": "py", "lang": "Python", "max_stars_repo_path": "Basic ODE Models/Haken_Laser_Production.py", "max_stars_repo_name": "singhster96/Mini_Projs", "max_stars_repo_head_hexsha": "5ac4058febc5ba251d82c997be13c05929ce1697", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Basic ODE Models/Haken_Laser_Production.py", "max_issues_repo_name": "singhster96/Mini_Projs", "max_issues_repo_head_hexsha": "5ac4058febc5ba251d82c997be13c05929ce1697", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Basic ODE Models/Haken_Laser_Production.py", "max_forks_repo_name": "singhster96/Mini_Projs", "max_forks_repo_head_hexsha": "5ac4058febc5ba251d82c997be13c05929ce1697", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8648648649, "max_line_length": 108, "alphanum_fraction": 0.5189125296, "include": true, "reason": "import numpy,from scipy", "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812327313546, "lm_q2_score": 0.8824278556326343, "lm_q1q2_score": 0.8545265746340162}}
{"text": "import numpy as np\nfrom scipy.spatial.distance import cdist\n\nclass KMeans:\n    def __init__(\n            self,\n            k: int,\n            metric: str = \"euclidean\",\n            tol: float = 1e-6,\n            max_iter: int = 100,\n            n_restarts: int = 10):\n        \"\"\"\n        inputs:\n            k: int\n                the number of centroids to use in cluster fitting\n            metric: str\n                the name of the distance metric to use\n            tol: float\n                the minimum error tolerance from previous error during optimization to quit the model fit\n            max_iter: int\n                the maximum number of iterations before quitting model fit\n            n_restarts: int\n                the number of random initializations the algorithm will conduct\n        \"\"\"\n        assert(k > 0), \"k must be greater than 0\"\n        self._k = k\n        self._metric = metric\n        self._tol = tol\n        self._max_iter = max_iter\n        self._centroids = None\n        self._error = np.inf\n        self._n_restarts = n_restarts\n    \n    def fit(self, mat: np.ndarray):\n        \"\"\"\n        fits the kmeans algorithm onto a provided 2D matrix\n\n        inputs: \n            mat: np.ndarray\n                A 2D matrix where the rows are observations and columns are features\n        \"\"\"\n\n        # try n_restart initializations of the centroids\n        for j in range(self._n_restarts):\n            # initialize each centroid at a data point\n            centroids = mat[np.random.choice(mat.shape[0], self._k, replace = False)]\n            errors = np.zeros(self._max_iter)\n            it = 0\n            # run the EM algorithm for max_iter iterations\n            for it in range(self._max_iter): \n                distances = cdist(mat, centroids, self._metric) # compute distances from each point to each centroid\n                assignments = np.argmin(distances, axis = 1) # assign each point to closest centroid\n                # update centroid positions\n                for cluster in range(self._k):\n                    centroids[cluster, :] = np.mean(mat[assignments == cluster,:], axis = 0)\n                errors[it] = np.mean(np.linalg.norm(centroids[assignments,:] - mat, axis = 1))\n                if it > 0:\n                    if errors[it] - errors[it - 1] < self._tol: # optimization complete\n                        break\n            # if the lowest error was achieved, save the centroid positions and the error\n            if errors[it] < self._error:\n                self._centroids = centroids\n                self._error = errors[it]\n\n\n    def predict(self, mat: np.ndarray) -> np.ndarray:\n        \"\"\"\n        predicts the cluster labels for a provided 2D matrix\n\n        inputs: \n            mat: np.ndarray\n                A 2D matrix where the rows are observations and columns are features\n\n        outputs:\n            np.ndarray\n                a 1D array with the cluster label for each of the observations in `mat`\n        \"\"\"\n        distances = cdist(mat, self._centroids, self._metric)\n        return np.argmin(distances, axis = 1)\n\n    def get_error(self) -> float:\n        \"\"\"\n        returns the final squared-mean error of the fit model\n\n        outputs:\n            float\n                the squared-mean error of the fit model\n        \"\"\"\n        return self._error\n\n    def get_centroids(self) -> np.ndarray:\n        \"\"\"\n        returns the centroid locations of the fit model\n\n        outputs:\n            np.ndarray\n                a `k x m` 2D matrix representing the cluster centroids of the fit model\n        \"\"\"\n        return self._centroids\n", "meta": {"hexsha": "afe6b77967d132ce4ade77ad632cc865d8d07413", "size": 3625, "ext": "py", "lang": "Python", "max_stars_repo_path": "cluster/kmeans.py", "max_stars_repo_name": "thomas-mazumder/project5", "max_stars_repo_head_hexsha": "b8f2eda71dcfb550d030a2ee2d9b136005198aca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cluster/kmeans.py", "max_issues_repo_name": "thomas-mazumder/project5", "max_issues_repo_head_hexsha": "b8f2eda71dcfb550d030a2ee2d9b136005198aca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cluster/kmeans.py", "max_forks_repo_name": "thomas-mazumder/project5", "max_forks_repo_head_hexsha": "b8f2eda71dcfb550d030a2ee2d9b136005198aca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.25, "max_line_length": 116, "alphanum_fraction": 0.5583448276, "include": true, "reason": "import numpy,from scipy", "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632329799585, "lm_q2_score": 0.8976953003183444, "lm_q1q2_score": 0.854483150791934}}
{"text": "\"\"\"util \n\nsigmoid, binary_cross_entropy, softmax, cross_entropy, kappa are implemented.\n\n\"\"\"\nimport numpy as np \n\nEPS = 1e-20 \n\ndef _log(x): \n    \"\"\"_log \n\n    to prevent np.log_log(0), caluculate np.log(x + EPS) \n\n    Args:\n        x (array)\n\n    Returns:\n        array: same shape as x, log equals np.log(x + EPS)\n\n    \"\"\"\n    if np.any(x < 0):\n        print(\"log < 0\")\n        exit()\n    return np.log(x + EPS) \n\n\ndef sigmoid(logit): \n    \"\"\"sigmoid function \n\n    Args:\n        logit (array) : data\n\n    Returns:\n        array: same shape as logit \n\n    \"\"\"\n    prob = np.zeros_like(logit) \n    prob[logit >= 0] = 1/(1 + np.exp(-logit[logit >= 0])) \n    prob[logit < 0] = np.exp(logit[logit < 0])/(np.exp(logit[logit < 0]) + 1) \n    return prob \n\n\ndef binary_cross_entropy(target,pred):\n    \"\"\"binary cross entropy\n\n    Args:\n        target (2-D array) : shape = (N_samples,1), value should be 0 or 1 \n        pred (2-D array) : shape = (N_samples,1), value shoule be in (0,1)\n\n        or \n\n        target (2-D array) : shape = (N_samples,2), onehotencoding \n        pred (2-D array) : shape = (N_samples,2), value shoule be int (0,1)\n    \n    Returns:\n        float: mean of loss in records\n\n    \"\"\"\n    if target.shape[1] == 1:\n        loss = -target*_log(pred) - (1.0 - target)*_log(1.0 - pred) \n    else:\n        loss = target*_log(pred) \n        loss = -loss.sum(axis = 0)\n    return loss.mean()  \n\n\ndef softmax(x):\n    \"\"\"softmax function \n\n    Args:\n        x (2-D array) : shape = (N_samples,N_class) \n    \n    Returns:\n        2-D array: shape = (N_samples,N_class) \n\n    \"\"\"\n    \n    row_max = x.max(axis = 1).reshape(-1,1)\n    x -= row_max \n    ratio = np.exp(x) \n    total = ratio.sum(axis = 1).reshape(-1,1)\n    return ratio/total \n\n\ndef cross_entropy(target,pred):\n    \"\"\"cross entropy \n\n    Args:\n        target (2-D array) : shape = (N_samples,N_class) onehotencoding \n        pred (2-D array) : shape = (N_samples,N_class) value shouled be in (0,1) \n    \n    Returns:\n        float: mean of loss in records \n\n    \"\"\"\n    loss = target*_log(pred) \n    return -loss.mean()\n\n\ndef kappa(sigma):\n    \"\"\"kappa \n\n    this is used when approximating the inverse function of a probit function \n\n    Args:\n        sigma (array): sigma\n\n    Returns:\n        array: 1/sqrt(1 + \\pi*sigma/8)\n\n    \"\"\"\n    return (1 + np.pi*sigma/8)**(-0.5)", "meta": {"hexsha": "84dbdc5bf50d4e3ee16e95256ab50c4ca963d8e7", "size": 2346, "ext": "py", "lang": "Python", "max_stars_repo_path": "prml/utils/util.py", "max_stars_repo_name": "hedwig100/PRML", "max_stars_repo_head_hexsha": "992f2c07e88b2bad331e08303bdba84684f04d40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-19T09:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T09:44:11.000Z", "max_issues_repo_path": "prml/utils/util.py", "max_issues_repo_name": "hedwig100/PRML", "max_issues_repo_head_hexsha": "992f2c07e88b2bad331e08303bdba84684f04d40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prml/utils/util.py", "max_forks_repo_name": "hedwig100/PRML", "max_forks_repo_head_hexsha": "992f2c07e88b2bad331e08303bdba84684f04d40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-07T11:08:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T11:08:10.000Z", "avg_line_length": 20.7610619469, "max_line_length": 81, "alphanum_fraction": 0.5549872123, "include": true, "reason": "import numpy", "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8976952907388474, "lm_q1q2_score": 0.8544831367702396}}
{"text": "# Problem: https://projecteuler.net/problem=683\r\n\r\n\"\"\"\r\n. Same idea as problem 227.\r\n. Use the distance between the dice as a state.\r\n. Use Markov chain to track the probabilities.\r\n\r\n. E[(X_2)^2 +(X_3)^2 + ... + (X_n)^2] = E[(X_2)^2] + E[(X_3)^2] + ... + E[(X_n)^2] (linearity of expectation)\r\n\r\n. E(X^2) = [E(X)]^2 + Var(X)\r\n\r\n. Use the formula here to find Var(X) and E(X) from the fundamental matrix,\r\n    https://en.wikipedia.org/wiki/Absorbing_Markov_chain#Expected_number_of_steps\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\nN = 500\r\n\r\ndef E_X2(N):\r\n    ans = 0.0\r\n\r\n    T = np.zeros((N, N), dtype = np.double)\r\n\r\n\r\n    T[0][0] = 0\r\n    for delta in range(1, N):\r\n        # player 1 rolls [1,2], player 2 rolls [1,2]: delta doesn't change\r\n        # player 1 rolls [1,2], player 2 rolls [3,4]\r\n        T[delta][(delta-1)%N] += 4/36\r\n        # player 1 rolls [1,3], player 2 rolls [5,6]\r\n        T[delta][(delta-2)%N] += 4/36\r\n\r\n        # player 1 rolls [3,4], player 2 rolls [1,2]\r\n        T[delta][(delta+1)%N] += 4/36\r\n\r\n        # player 1 rolls [3,4], player 2 rolls [5,6]\r\n        T[delta][(delta-1)%N] += 4/36\r\n\r\n        # player 1 rolls [5,6], player 2 rolls [1,2]\r\n        T[delta][(delta+2)%N] += 4/36\r\n        # player 1 rolls [5,6], player 2 rolls [3,4]\r\n        T[delta][(delta+1)%N] += 4/36\r\n        # player 1 rolls [5,6], player 2 rolls [5,6]: delta doesn't change\r\n\r\n        T[delta][delta] += 1.0 - np.sum(T[delta])\r\n\r\n    fundamental_matrix = np.linalg.inv(np.eye(N) - T)\r\n\r\n    #t = fundamental_matrix.dot(np.ones((N,1)))\r\n    t = np.sum(fundamental_matrix, axis = 1)\r\n    E_steps_per_state = t-1\r\n    E2_X = E_steps_per_state*E_steps_per_state\r\n\r\n    V_steps_per_starting_state = (2*fundamental_matrix - np.eye(N)).dot(t) - t * t\r\n    V_X = V_steps_per_starting_state\r\n    \r\n    ans = np.sum(E2_X + V_X) / N\r\n\r\n    return ans\r\n\r\n\r\ndef G(N):\r\n    ans = 0.0\r\n    for i in range(2, N+1):\r\n        ans += E_X2(i)\r\n    return ans\r\n\r\nif __name__ == \"__main__\":\r\n    print(G(N))", "meta": {"hexsha": "7e999d7c689a815e9df196d24e93854f6b5e0fd6", "size": 1983, "ext": "py", "lang": "Python", "max_stars_repo_path": "7th_100/problem683_fundamental_matrix.py", "max_stars_repo_name": "takekoputa/project-euler", "max_stars_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "7th_100/problem683_fundamental_matrix.py", "max_issues_repo_name": "takekoputa/project-euler", "max_issues_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "7th_100/problem683_fundamental_matrix.py", "max_forks_repo_name": "takekoputa/project-euler", "max_forks_repo_head_hexsha": "6f434be429bd26f5d0f84f5ab0f5fa2bd677c790", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-02T12:08:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T12:08:46.000Z", "avg_line_length": 28.3285714286, "max_line_length": 110, "alphanum_fraction": 0.5537065053, "include": true, "reason": "import numpy", "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454896, "lm_q2_score": 0.8976952818435994, "lm_q1q2_score": 0.8544831344323344}}
{"text": "# Code for solving the 1+1 dimensional diffusion equation\n# du/dt = ddu/ddx on a rectangular grid of size L x (T*dt),\n# with with L = 1, u(x,0) = g(x), u(0,t) = u(L,t) = 0\n\nimport numpy, sys, math\nfrom  matplotlib import pyplot as plt\nimport numpy as np\n\ndef forward_step(alpha,u,uPrev,N):\n    \"\"\"\n    Steps forward-euler algo one step ahead.\n    Implemented in a separate function for code-reuse from crank_nicolson()\n    \"\"\"\n    \n    for x in xrange(1,N+1): #loop from i=1 to i=N\n        u[x] = alpha*uPrev[x-1] + (1.0-2*alpha)*uPrev[x] + alpha*uPrev[x+1]\n\ndef forward_euler(alpha,u,N,T):\n    \"\"\"\n    Implements the forward Euler sheme, results saved to\n    array u\n    \"\"\"\n\n    #Skip boundary elements\n    for t in xrange(1,T):\n        forward_step(alpha,u[t],u[t-1],N)\n\ndef tridiag(alpha,u,N):\n    \"\"\"\n    Tridiagonal gaus-eliminator, specialized to diagonal = 1+2*alpha,\n    super- and sub- diagonal = - alpha\n    \"\"\"\n    d = numpy.zeros(N) + (1+2*alpha)\n    b = numpy.zeros(N-1) - alpha\n\n    #Forward eliminate\n    for i in xrange(1,N):\n        #Normalize row i (i in u convention):\n        b[i-1] /= d[i-1];\n        u[i] /= d[i-1] #Note: row i in u = row i-1 in the matrix\n        d[i-1] = 1.0\n        #Eliminate\n        u[i+1] += u[i]*alpha\n        d[i] += b[i-1]*alpha\n    #Normalize bottom row\n    u[N] /= d[N-1]\n    d[N-1] = 1.0\n\n    #Backward substitute\n    for i in xrange(N,1,-1): #loop from i=N to i=2\n        u[i-1] -= u[i]*b[i-2]\n        #b[i-2] = 0.0 #This is never read, why bother...\n        \ndef backward_euler(alpha,u,N,T):\n    \"\"\"\n    Implements backward euler scheme by gaus-elimination of tridiagonal matrix.\n    Results are saved to u.\n    \"\"\"\n    for t in xrange(1,T):\n        u[t] = u[t-1].copy()\n        tridiag(alpha,u[t],N) #Note: Passing a pointer to row t, which is modified in-place\n\ndef crank_nicolson(alpha,u,N,T):\n    \"\"\"\n    Implents crank-nicolson scheme, reusing code from forward- and backward euler\n    \"\"\"\n    for t in xrange(1,T):\n        forward_step(alpha/2,u[t],u[t-1],N)\n        tridiag(alpha/2,u[t],N)\n\ndef g(x):\n    \"\"\"Initial condition u(x,0) = g(x), x \\in [0,1]\"\"\"\n    return numpy.sin(math.pi*x)\n\n# Number of integration points along x-axis\n    N       =   100\n# Step length in time\n    dt      =   0.01\n# Number of time steps till final time \n    T       =   100\n# Define method to use 1 = explicit scheme, 2= implicit scheme, 3 = Crank-Nicolson\n    method  =   2\n\n#dx = 1/float(N+1)\nu = numpy.zeros((T,N+2),numpy.double)\n(x,dx) = numpy.linspace (0,1,N+2, retstep=True)\nalpha = dt/(dx**2)\n\n#Initial codition\nu[0,:] = g(x)\nu[0,0] = u[0,N+1] = 0.0 #Implement boundaries rigidly\n\nif   method == 1:\n    forward_euler(alpha,u,N,T)\nelif method == 2:\n    backward_euler(alpha,u,N,T)\nelif method == 3:\n    crank_nicolson(alpha,u,N,T)\nelse:\n    print \"Please select method 1,2, or 3!\"\n    import sys\n    sys.exit(0)\n\n# add on how to make a movie of the results\n", "meta": {"hexsha": "0527cd62bc3d56a1166c8632c9c6bd91175930a4", "size": 2906, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/src/pde/pde/Programs/python/diffusion.py", "max_stars_repo_name": "kimrojas/ComputationalPhysicsMSU", "max_stars_repo_head_hexsha": "a47cfc18b3ad6adb23045b3f49fab18c0333f556", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 220, "max_stars_repo_stars_event_min_datetime": "2016-08-25T09:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:09:16.000Z", "max_issues_repo_path": "doc/src/pde/pde/Programs/python/diffusion.py", "max_issues_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_issues_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-04T12:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T12:55:10.000Z", "max_forks_repo_path": "doc/src/pde/pde/Programs/python/diffusion.py", "max_forks_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_forks_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 136, "max_forks_repo_forks_event_min_datetime": "2016-08-25T09:04:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:54:21.000Z", "avg_line_length": 27.6761904762, "max_line_length": 91, "alphanum_fraction": 0.5925671025, "include": true, "reason": "import numpy", "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632234212403, "lm_q2_score": 0.8976952859490985, "lm_q1q2_score": 0.854483128533561}}
{"text": "import numpy as np\n\n\n\n\ndef euclidean_distance(x1, x2):\n    return np.sqrt(np.sum((x1 - x2) ** 2))\n\n\nclass KMeans:\n    def __init__(self, K=2, max_iters=200):\n        self.K = K\n        self.max_iters = max_iters\n\n        self.clusters = [[] for _ in range(self.K)]\n        self.centroids = []\n\n    def fit(self, X):\n        self.X = X\n        self.n_samples, self.n_features = X.shape\n\n        random_sample_idxs = np.random.choice(self.n_samples, self.K, replace=False)\n        self.centroids = [self.X[idx] for idx in random_sample_idxs]\n\n        for _ in range(self.max_iters):\n            self.clusters = self._create_clusters(self.centroids)\n\n            centroids_old = self.centroids\n            self.centroids = self._get_centroids(self.clusters)\n            \n            if self._is_converged(centroids_old, self.centroids):\n                break\n\n        return self._get_cluster_labels(self.clusters),self.centroids\n\n    def _get_cluster_labels(self, clusters):\n        labels = np.empty(self.n_samples)\n\n        for cluster_idx, cluster in enumerate(clusters):\n            for sample_index in cluster:\n                labels[sample_index] = cluster_idx\n        return labels\n\n    def _create_clusters(self, centroids):\n        clusters = [[] for _ in range(self.K)]\n        for idx, sample in enumerate(self.X):\n            centroid_idx = self._closest_centroid(sample, centroids)\n            clusters[centroid_idx].append(idx)\n        return clusters\n\n    def _closest_centroid(self, sample, centroids):\n        distances = [euclidean_distance(sample, point) for point in centroids]\n        closest_index = np.argmin(distances)\n        return closest_index\n\n    def _get_centroids(self, clusters):\n        centroids = np.zeros((self.K, self.n_features))\n        for cluster_idx, cluster in enumerate(clusters):\n            cluster_mean = np.mean(self.X[cluster], axis=0)\n            centroids[cluster_idx] = cluster_mean\n        return centroids\n\n    def _is_converged(self, centroids_old, centroids):\n        distances = [\n            euclidean_distance(centroids_old[i], centroids[i]) for i in range(self.K)\n        ]\n        return sum(distances) == 0\n\n    def distance(self,x, cen):\n        Xs=x\n        cent=cen\n        dis=[]\n        for i in range(len(cent)):\n            summ=[]\n            for j in Xs[i]:\n                summ.append((j-cent[i]) ** 2)\n            dis.append(sum(summ))\n        return dis\n\n    def inertia_(self):\n        clus=self._get_cluster_labels(self.clusters)\n        cen=self.centroids\n        x=[]\n        uni=np.unique(clus)\n        for i in range(self.K):\n            a=[]\n            for j in range(len(clus)):\n                if clus[j]==uni[i]:\n                    a.append(self.X[j].tolist())\n            x.append(a)\n        s=sum(self.distance(x,cen))\n        return s\n", "meta": {"hexsha": "8dc37e48b03aa292c408823fa60616c2564e78ac", "size": 2823, "ext": "py", "lang": "Python", "max_stars_repo_path": "app/src/main/python/kmeans.py", "max_stars_repo_name": "VigneshTheBlaster/ML_calculator", "max_stars_repo_head_hexsha": "e03d4d3d666901c80ffba75de1168f6faaac5053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/src/main/python/kmeans.py", "max_issues_repo_name": "VigneshTheBlaster/ML_calculator", "max_issues_repo_head_hexsha": "e03d4d3d666901c80ffba75de1168f6faaac5053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/src/main/python/kmeans.py", "max_forks_repo_name": "VigneshTheBlaster/ML_calculator", "max_forks_repo_head_hexsha": "e03d4d3d666901c80ffba75de1168f6faaac5053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3548387097, "max_line_length": 85, "alphanum_fraction": 0.5887353879, "include": true, "reason": "import numpy", "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620596782468, "lm_q2_score": 0.8902942377652497, "lm_q1q2_score": 0.8544706313572509}}
{"text": "# A little library for the generation and attribute checking of\n# matrix of integers\n# author : Etienne THIERY\n\nfrom numpy import *\n\ndef symmetricPositiveDefinite(n, maxValue= 1):\n    ''' Generates a n x n random symmetric, positive-definite matrix.\n    The optionnal maxValue argument can be used to specify a maximum\n    absolute value for extradiagonal coefficients.\n    Diagonal coefficient will be inferior to 22 times maxValue in\n    absolute value.\n\n    Runs in O(n^2)'''\n    \n    # To generate such a matrix we use the fact that a symmetric \n    # diagonnaly dominant matrix is symmetric positive definite\n\n    # We first generate a random matrix\n    # with coefficients between -maxValue and +maxValue \n    A = random.random_integers(-maxValue, maxValue, (n, n))\n\n    # Then by adding to this matrix its transpose, we obtain \n    # a symmetric matrix\n    A = A + A.transpose()\n\n    # Finally we make sure it is strictly diagonnaly dominant by\n    # adding 2*n*maxValue times the identity matrix\n    A += 2*n*maxValue*eye(n)\n    return A\n\ndef symmetricSparsePositiveDefinite(n, nbZeros, maxValue= 1):\n    ''' Generates a n x n random symmetric, positive-definite matrix.\n    with around nbZeros null coefficients (more precisely nbZeros+-1)\n    nbZeros must be between 0 and n*(n-1)\n    The optionnal maxValue argument can be used to specify a maximum\n    absolute value for extradiagonal coefficients.\n    Diagonal coefficient will be inferior to 11 times maxValue in\n    absolute value.\n\n    Runs in O(n^2)'''\n    \n    # The algorithm is the same as in symmetricPositiveDefinite\n    # except that the matrix generated in the beginning is \n    # sparse symmetric\n\n    A = zeros((n,n))\n    currentNbZeros = n*(n-1)\n    while currentNbZeros > nbZeros:\n        i, j = random.randint(n, size=2)\n        if i != j and A[i,j] == 0:\n            while A[i,j] == 0:\n                A[i,j] = A[j,i] = random.randint(-maxValue, maxValue+1)\n            currentNbZeros -= 2 \n\n    # Then we make sure it is strictly diagonnaly dominant by\n    # adding n*maxValue times the identity matrix\n    A += n*maxValue*eye(n)\n    return A\n    \ndef isSymmetric(M):\n    ''' Returns true if and only if M is symmetric'''\n    return array_equal(M, M.transpose())\n\ndef isDefinitePositive(M):\n    ''' Returns true if and only if M is definite positive'''\n    # using the fact that if all its eigenvalues are positive, \n    # M is definite positive\n    # be careful, as eigvals use numerical methods, some eigenvalues\n    # which are in reality equal to zero can be found negative\n    eps = 1e-5\n    for ev in linalg.eigvals(M):\n        if ev <= 0-eps:\n            return False\n    return True\n", "meta": {"hexsha": "a526f84d8a01990342e9d3aea422a71f86bf7294", "size": 2672, "ext": "py", "lang": "Python", "max_stars_repo_path": "trunk/matgen.py", "max_stars_repo_name": "ethiery/heatEquationSolver", "max_stars_repo_head_hexsha": "c1fc4316b453974cd72a34eb551130e85842aef0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trunk/matgen.py", "max_issues_repo_name": "ethiery/heatEquationSolver", "max_issues_repo_head_hexsha": "c1fc4316b453974cd72a34eb551130e85842aef0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trunk/matgen.py", "max_forks_repo_name": "ethiery/heatEquationSolver", "max_forks_repo_head_hexsha": "c1fc4316b453974cd72a34eb551130e85842aef0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1578947368, "max_line_length": 71, "alphanum_fraction": 0.6788922156, "include": true, "reason": "from numpy", "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620562254526, "lm_q2_score": 0.8902942333990421, "lm_q1q2_score": 0.8544706240927277}}
{"text": "## 4/9/2018 Knapsack Bo Lin\r\nimport numpy as np\r\n\r\ndef knapsack_0_1(weight,value,max_weight):\r\n    num = len(weight) ## get the number of distinct items\r\n    dp = np.zeros((num,max_weight+1)) ## initialize dp matrix\r\n    ## transfer function dp[i][j]=max(f[i-1][j],f[i-1][j-weight[i]]+value[i])。\r\n    for i in range(num):\r\n        for j in range(max_weight+1):\r\n            if weight[i] > j:\r\n                dp[i][j] = dp[i-1][j]\r\n            else:\r\n                dp[i][j] =  max(dp[i-1][j],dp[i-1][j-weight[i]]+ value[i])\r\n    max_value = np.amax(dp).astype(int).astype(str)\r\n    return max_value,dp\r\n\r\ndef find_item(max_weight,dp,weight): ## find the item\r\n    j = max_weight\r\n    num = len(weight)\r\n    in_pack = np.zeros((1,num))## try to find which one is put in the pack\r\n    for i in reversed(range(num)):\r\n        if i != 0 and (dp[i][j] > dp[i-1][j]):\r\n            in_pack[0][i] = 1\r\n            j = j - weight[i]\r\n        if i == 0 and (dp[i][j] > 0):\r\n            in_pack[0][i] = 1\r\n    return in_pack\r\n\r\n#test\r\nweight = [1,2,2,3,4,5,6,3,5]\r\nvalue  = [3,5,2,2,4,3,4,9,4]\r\nmax_weight = 13\r\nmax_value,dp = knapsack_0_1(weight,value,max_weight)\r\nin_pack = find_item(max_weight,dp,weight)\r\n\r\nprint('The maximum value is ' + max_value)\r\nprint(dp)\r\nprint('Weight = ' , weight,'actual weight = ',np.sum(weight*in_pack))\r\nprint('Value = ',value,'actual value = ',np.sum(value*in_pack))\r\nprint('In_pack= ',in_pack)\r\n", "meta": {"hexsha": "24debdd156ecd768b18ea95f53debf9aaf4d0c8d", "size": 1421, "ext": "py", "lang": "Python", "max_stars_repo_path": "Dynamic Programming/0_1_Knapsack.py", "max_stars_repo_name": "BoLin/2018-Projects", "max_stars_repo_head_hexsha": "c0727a883c8b291380aa850f588b9239b6ded30d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-08-27T08:16:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-18T08:09:17.000Z", "max_issues_repo_path": "Dynamic Programming/0_1_Knapsack.py", "max_issues_repo_name": "BoLin/2018-Projects", "max_issues_repo_head_hexsha": "c0727a883c8b291380aa850f588b9239b6ded30d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dynamic Programming/0_1_Knapsack.py", "max_forks_repo_name": "BoLin/2018-Projects", "max_forks_repo_head_hexsha": "c0727a883c8b291380aa850f588b9239b6ded30d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-08-27T08:17:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-27T08:17:10.000Z", "avg_line_length": 34.6585365854, "max_line_length": 79, "alphanum_fraction": 0.5700211119, "include": true, "reason": "import numpy", "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762057376384, "lm_q2_score": 0.8902942304882371, "lm_q1q2_score": 0.8544706223237151}}
{"text": "import sympy as sp\nfrom IPython.display import display\nsp.init_printing()  # pretty printing\n\n# Define impulse and unit step as functions of t\nt = sp.symbols('t');\nimp = sp.DiracDelta(t);\nustep = sp.Heaviside(t);\n#ustep = sp.Piecewise( (0, t<1), (1, True));  # diff() doesn't give delta function?!\n\n# Setup differential equation\nx = sp.Function('x');  y = sp.Function('y');\nRC = sp.symbols('RC');#, real=True);\nlp1de = sp.Eq(y(t) + RC*sp.diff(y(t), t), x(t));\n#print(lp1de);  display(lp1de);\n\n# Generic solution\ny_sl0e = sp.dsolve(lp1de, y(t));\ny_sl0r = y_sl0e.rhs  # take only right hand side\n#print(y_sl0e);  display(y_sl0e);\n\n# Initial condition\na0 = sp.symbols('a0');\ncnd1 = sp.Eq(y_sl0r.subs(t, -1), a0);  # y(-1) = a0\n#cnd2 = sp.Eq(y_sl0r.diff(t).subs(t, -1), b0)  # y'(-1) = b0\n#print(cnd1);  display(cnd1);\n\n# Solve for C1:  magic brackets in solve() returns result as dictionary\nC1 = sp.symbols('C1')  # generic constants\nC1_sl = sp.solve([cnd1], (C1))\n#C1C2_sl = sp.solve([cnd1, cnd2], (C1, C2))\n#print(C1_sl);  display(C1_sl);\n\n# Substitute back for solution in terms of a0\ny_sl1 = y_sl0r.subs(C1_sl);\n#print(sp.Eq(y(t), y_sl1));  display(sp.Eq(y(t), y_sl1));\n\n# Set values for constants\ny_sl1s = y_sl1.subs({RC:1,a0:0}).doit()\n#print(sp.Eq(y(t), y_sl1s));  display(sp.Eq(y(t), y_sl1s));\n\n# Set input function and solve\ny_sl1sx = y_sl1s.subs({x(t):ustep}).doit()\nprint(sp.Eq(y(t), y_sl1sx));  display(sp.Eq(y(t), y_sl1sx))\n\n# Plot output\nsp.plot(y_sl1sx, (t,-4,8))\n", "meta": {"hexsha": "b15f0603ace9a614a537d2aaa6c92f8be8655ce5", "size": 1476, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/lab_symdiffeq-1.py", "max_stars_repo_name": "maxnvdm/notebooks", "max_stars_repo_head_hexsha": "c719a43d02e330bdc25dceea33d5e6c2b156e02d", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-07-17T09:03:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T05:28:21.000Z", "max_issues_repo_path": "src/lab_symdiffeq-1.py", "max_issues_repo_name": "maxnvdm/notebooks", "max_issues_repo_head_hexsha": "c719a43d02e330bdc25dceea33d5e6c2b156e02d", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lab_symdiffeq-1.py", "max_forks_repo_name": "maxnvdm/notebooks", "max_forks_repo_head_hexsha": "c719a43d02e330bdc25dceea33d5e6c2b156e02d", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2017-08-21T12:06:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T16:52:18.000Z", "avg_line_length": 30.75, "max_line_length": 84, "alphanum_fraction": 0.6531165312, "include": true, "reason": "import sympy", "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745211, "lm_q2_score": 0.8902942319436395, "lm_q1q2_score": 0.8544706216712198}}
{"text": "# By\n# ████████╗██╗   ██╗ █████╗ ███╗   ██╗    ██╗  ██╗ ██████╗ \n# ╚══██╔══╝██║   ██║██╔══██╗████╗  ██║    ██║  ██║██╔═══██╗\n#    ██║   ██║   ██║███████║██╔██╗ ██║    ███████║██║   ██║\n#    ██║   ██║   ██║██╔══██║██║╚██╗██║    ██╔══██║██║   ██║\n#    ██║   ╚██████╔╝██║  ██║██║ ╚████║    ██║  ██║╚██████╔╝\n#    ╚═╝    ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═══╝    ╚═╝  ╚═╝ ╚═════╝ \n\n# Email: ttuan.ho@outlook.com                                                         \n\n\nfrom scipy.stats import norm, binom, poisson, expon, uniform\nfrom scipy import stats\nimport numpy as np\nfrom scipy.stats import ttest_ind\nimport statsmodels.api as sm \nimport pylab as py\n\"\"\"\nEx\n\"\"\"\n\n\n\n\"\"\"\nEx3:\nConsider again the astronaut exercise (Exercise 4) from the week 5 exercises. The change in heart\nrate (in beats per minute) is as follows:\n15 32.5 49 26 8 28\na) Is there evidence that astronaut pulse rate has in fact increased under simulated weightlessness? Use a hypothesis test to answer this question, via Matlab’s ttest function.\nb) Is this consistent with your results from last week?\nc) Produce a normal quantile plot of the data. How reasonable is the normality assumption for these\ndata?\n\"\"\"\ndata=np.array([15,32.5,49,26,8,28])\nn = len(data)\nzeros = np.zeros((n,))\nm = np.mean(data)\ns = np.std(data, ddof=1)\n\n# % matlab version:\n# [h,p] = ttest(data, 0,'tail', 'right');p\n\n# stat, p = ttest_ind(data, zeros)\n# print('t=%.3f, p=%.3f' % (stat, p))\n\ntObs = (m - 0) / (s / ((n)**(1/2)))\n# % matlab version:\n# pValue = tcdf(t,n-1)\n# pValue in python\npValue = stats.t.sf(tObs, n-1)\nprint(f\"p-Value is {pValue}\")\n\n# produce qqplot of data\n# % matlab version:\n# qqplot(data)\nsm.qqplot(data)\npy.show()\n\n", "meta": {"hexsha": "0d4fad83ac4ebf7065fbf40d2768529419d12af0", "size": 1669, "ext": "py", "lang": "Python", "max_stars_repo_path": "week_07_hypothesis_testing/Exercise_7.py", "max_stars_repo_name": "ttuanho/MATH_2859", "max_stars_repo_head_hexsha": "2a98346c4e908d9373998f670303720390505233", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week_07_hypothesis_testing/Exercise_7.py", "max_issues_repo_name": "ttuanho/MATH_2859", "max_issues_repo_head_hexsha": "2a98346c4e908d9373998f670303720390505233", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week_07_hypothesis_testing/Exercise_7.py", "max_forks_repo_name": "ttuanho/MATH_2859", "max_forks_repo_head_hexsha": "2a98346c4e908d9373998f670303720390505233", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2881355932, "max_line_length": 176, "alphanum_fraction": 0.5212702217, "include": true, "reason": "import numpy,from scipy,import statsmodels", "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620596782468, "lm_q2_score": 0.890294223211224, "lm_q1q2_score": 0.8544706173888491}}
{"text": "\"\"\"\nThis module contains the functions needed for the trigonometric interpolation.\n\"\"\"\n\nfrom typing import Tuple\nimport numpy as np\nfrom numpy.typing import ArrayLike\nimport matplotlib.pyplot as plt\n\n\ndef e_complex_pow(power: float) -> complex:\n    r\"\"\"\n    Function which implements Euler's Formula for a real input number:\n    :math:`e^{j \\times power} = \\cos(power) + j \\times\\sin(power)` .\n\n    :param power: real number\n    :return: complex number\n    \"\"\"\n    return complex(np.cos(power), np.sin(power))\n\n\ndef get_complex_representation(points: ArrayLike) -> np.ndarray:\n    r\"\"\"\n    Function to calculate the Fourier coefficients of polynomial from its values,\n    provided as an input parameter.\n\n    Calculate following:\n       - nth root of unity which is a complex number: :math:`w = e^{{2\\pi i}/n}`\n       - discrete Fourier transformation matrix:\n       :math:`F = (w^{jk})_{0 \\leq j \\leq n-1, -(n-1)/2 \\leq k \\leq (n-1)/2}`\n\n       - discrete Fourier coefficients :math:`c_k = (1/n) \\times conjugate(F) \\times y`\n\n    :param points: polynomial values\n    :return: complex Fourier coefficients\n    \"\"\"\n    len_n = len(points)\n\n    y_s = np.array(points, dtype=np.complex_)\n\n    w_comp = e_complex_pow(2 * np.pi / len_n)\n    # Fourier-Matrix\n    f_matrix = np.array(\n        [\n            [w_comp ** (j * k) for j in range(len_n)]\n            for k in range(-(len_n - 1) // 2, (len_n - 1) // 2 + 1)\n        ]\n    )\n\n    ck_s = (1 / len_n) * (np.conj(f_matrix) @ y_s)  # Fourier-Coefficients\n    return ck_s\n\n\ndef get_sin_cos_representation(points: ArrayLike) -> Tuple[np.ndarray, np.ndarray]:\n    r\"\"\"\n    Function to calculate sine and cosine coefficients.\n\n    .. math::\n     a_0=2 \\times c_0  \\\\  a_k = c_k + c_{-k}  \\\\  b_k = j \\times (c_k - c_{-k})\n\n    :param points: polynomial values\n    :return: sine and cosine coefficients\n    \"\"\"\n    ck_s = get_complex_representation(points)\n    ck_zero_idx = (len(ck_s) - 1) // 2\n\n    # cosine coefficients\n    ak_s = [2 * ck_s[ck_zero_idx]] + [\n        ck_s[ck_zero_idx + n] + ck_s[ck_zero_idx - n] for n in range(1, ck_zero_idx + 1)\n    ]\n    # sine coefficients\n    bk_s = [complex(0)] + [\n        complex(0, ck_s[ck_zero_idx + n] - ck_s[ck_zero_idx - n])\n        for n in range(1, ck_zero_idx + 1)\n    ]\n\n    for n_len, _ in enumerate(ak_s):\n        if ak_s[n_len].imag < 1e-3:\n            ak_s[n_len] = ak_s[n_len].real\n\n        if bk_s[n_len].imag < 1e-3:\n            bk_s[n_len] = bk_s[n_len].real\n\n    return np.array(ak_s), np.array(bk_s)\n\n\ndef eval_sin_cos_representation(\n    t_period: float, a_coeff: np.ndarray, b_coeff: np.ndarray\n) -> float:\n    r\"\"\"\n    Function which calculates Fourier series from given period and coefficients.\n\n    :math:`f(x) = a_0/2 + \\sum_{n=1}^N(a_n\\cos(n \\times x) + b_n\\sin(n \\times x))`\n\n    :param t_period: parameter of function `f(x)` which represent the point in the period of time\n    :param a_coeff: cosine coefficients\n    :param b_coeff: sine coefficients\n    :return: Fourier series\n    \"\"\"\n    return a_coeff[0] / 2 + sum(\n        a_coeff[n] * np.cos(n * t_period) + b_coeff[n] * np.sin(n * t_period)\n        for n in range(1, len(a_coeff))\n    )\n\n\ndef plot_sin_cos_representation(\n    a_coeff: np.ndarray,\n    b_coeff: np.ndarray,\n    y_points: ArrayLike,\n    start: float = -10,\n    end: float = 10,\n) -> None:\n    \"\"\"\n    Function to plot trigonometric Fourier series.\n\n    :param a_coeff: cosine coefficients\n    :param b_coeff: sine coefficients\n    :param y_points: polynomial values\n    :param start: starting value of the sequence on x axis\n    :param end: end value of the sequence on x axis\n    \"\"\"\n    x_s = np.linspace(start, end, 5000)\n    y_s = [eval_sin_cos_representation(t, a_coeff, b_coeff) for t in x_s]\n\n    n_len = len(y_points)\n    x_points = np.array([(2 * np.pi * i) / n_len for i in range(n_len)])\n\n    plt.figure(figsize=(14, 7))\n    plt.plot(x_s, y_s)\n    plt.scatter(x_points, y_points, c=\"black\")\n    plt.show()\n", "meta": {"hexsha": "058cd6a1ea005984a02f77f224298fc76249ac74", "size": 3954, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/kosmos_signal_processing/interpolate/trig.py", "max_stars_repo_name": "kosmos-industrie40/kosmos-signal-processing", "max_stars_repo_head_hexsha": "8ee5121ddd7670e8fbcf92785edf05c52ef0bfb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kosmos_signal_processing/interpolate/trig.py", "max_issues_repo_name": "kosmos-industrie40/kosmos-signal-processing", "max_issues_repo_head_hexsha": "8ee5121ddd7670e8fbcf92785edf05c52ef0bfb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kosmos_signal_processing/interpolate/trig.py", "max_forks_repo_name": "kosmos-industrie40/kosmos-signal-processing", "max_forks_repo_head_hexsha": "8ee5121ddd7670e8fbcf92785edf05c52ef0bfb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9545454545, "max_line_length": 97, "alphanum_fraction": 0.6292362165, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620539235896, "lm_q2_score": 0.8902942188450159, "lm_q1q2_score": 0.8544706080749902}}
{"text": "# Please attribute to Llewelyn Richards-Ward,\n#llewelyn62@icloud.com\n#Use and distribute as you want.\nfrom mayavi import mlab\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numba as nb\nfrom scipy.integrate import odeint\n\n#Create figure\nmlab.figure(size=(900,800), bgcolor=(0,0,0), fgcolor=(1,1,1))\n#For a very basic  approach which shows the steps this commented\n#section can be used. eThe preferrend methods is to\n#use odeint and an array/function combination, as below.\n#Note the use of the Euler integration method.\n#=========================================\n#   # Integration time step\n# dt = 0.001\n#   # Lorenz ODE parameters\n# sigma = 10.0\n# r     = 28.0\n# b     = 8.0/3.0\n#   # Initial conditions\n# x = -.5\n# y =  .2\n# z =  2.17\n#   # Store the trajectory\n# TrajX = []\n# TrajY = []\n# TrajZ = []\n# Time  = []\n#\n#   # Integrate the Lorenz ODEs\n#   #Pretty basic approach -- in real examples would\n#   #use odeint and an array/function combination.\n# for t in np.arange(0.,50.,dt):\n# \tdxdt = sigma*(y - x)\n# \tdydt = r * x - y - x * z\n# \tdzdt = x * y - b * z\n# \tx = x + dxdt * dt\n# \ty = y + dydt * dt\n# \tz = z + dzdt * dt\n#\n# \tTrajX.append(x)\n# \tTrajY.append(y)\n# \tTrajZ.append(z)\n# \tTime.append(t)\n#=========================================\n\n# Lorenz paramters and initial conditions\nsigma, beta, rho = 10, 8/3, 28\n# #Very near C+ but not quite.\n# u0, v0, w0 = np.sqrt(beta*(rho-1))+.01,np.sqrt(beta*(rho-1))+.01,27\n# # Close to C+ but allowing of escape\n# u0, v0, w0 =7.3,7.3,27\n#Lorenz/Strogatz starting points\nu0, v0, w0 = 0,1, 0\n\n# Maximum time point and total number of time points\ntmax, n = 50, 100000\n#@nb.jit(nopython=False) #optimises for speed.\ndef deriv_lorenz(X, t, sigma, beta, rho):\n    \"\"\"The Lorenz equations.\"\"\"\n    x, y, z = X\n    dx_dt = -sigma*(x - y)\n    dy_dt = rho*x - y - x*z\n    dz_dt = -beta*z + x*y\n    return dx_dt, dy_dt, dz_dt\n\n# Integrate the Lorenz equations on the time grid t\n#Implements a detailed use of memory space for optimised accuracy, not\n#so much speed.\n#@nb.jit('float64(float64,float64,float64,float64,float64,float64,float64,float64)',nopython=False)\ndef int_f(u0=u0,v0=v0,w0=w0,sigma=sigma,beta=beta,rho=rho,tma=tmax,n=n):\n    t = np.linspace(0, tmax, n)\n    f = odeint(deriv_lorenz, (u0, v0, w0), t, args=(sigma, beta, rho))\n    return f\nx, y, z = int_f().T\nTime = np.linspace(0,tmax,n)\n\nmlab.plot3d(x,y,z,Time,colormap='Spectral',tube_radius=0.3)\nmlab.outline(opacity=.4)\nmlab.points3d(0,0,0,opacity=.5)\nmlab.text3d(0,0,0,'Origin')\nmlab.points3d(u0,v0,w0,opacity=.5)\nmlab.text3d(u0,v0,w0,'t_0')\nmlab.points3d(np.sqrt(beta*(rho-1)),np.sqrt(beta*(rho-1)),rho-1,opacity=.5)\nmlab.text3d(np.sqrt(beta*(rho-1))*1.2,np.sqrt(beta*(rho-1)),rho-1,'C+')\nmlab.points3d(-np.sqrt(beta*(rho-1)),-np.sqrt(beta*(rho-1)),rho-1,opacity=.5)\nmlab.text3d(-np.sqrt(beta*(rho-1))*1.2,-np.sqrt(beta*(rho-1)),rho-1,'C-')\nmlab.orientation_axes(xlabel='x',ylabel='y',zlabel='z')\n\n#plt.show()\n@mlab.animate(delay=50, ui=False)\ndef anim():\n    f = mlab.gcf()\n    while 1:\n        f.scene.camera.azimuth(2)\n        f.scene.render()\n        yield\n\na = anim() # Starts the animation.\n# mlab.savefig('Lorenz.png')\n", "meta": {"hexsha": "886a05fe4a609c5b7c07ca2cbba6563070e1b558", "size": 3144, "ext": "py", "lang": "Python", "max_stars_repo_path": "Strogatz/Lorenz attractor mayavi.py", "max_stars_repo_name": "yuchiaol/Non-linear-dynamics-Strogatz", "max_stars_repo_head_hexsha": "79e1171d4a88193d3da67c15f41212a96e6854dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 64, "max_stars_repo_stars_event_min_datetime": "2017-11-21T12:47:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:23:29.000Z", "max_issues_repo_path": "Strogatz/Lorenz attractor mayavi.py", "max_issues_repo_name": "Llewelyn62/Non-linear-dynamics-Strogatz", "max_issues_repo_head_hexsha": "79e1171d4a88193d3da67c15f41212a96e6854dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Strogatz/Lorenz attractor mayavi.py", "max_forks_repo_name": "Llewelyn62/Non-linear-dynamics-Strogatz", "max_forks_repo_head_hexsha": "79e1171d4a88193d3da67c15f41212a96e6854dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2017-11-21T20:11:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T00:00:30.000Z", "avg_line_length": 30.2307692308, "max_line_length": 99, "alphanum_fraction": 0.6361323155, "include": true, "reason": "import numpy,from scipy,import numba", "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810525948928, "lm_q2_score": 0.9019206745523101, "lm_q1q2_score": 0.8544625580144632}}
{"text": "import numpy as np\nfrom numpy import random as rnd\n\n#-------Neighbour generation----------\n\ndef boltz_move(state, temp, interval):\n    \"\"\"\n    The step length equals the square root of the current temperature.\n    The direction is uniformly random.\n    \"\"\"\n    \n    new_state = [0,0]\n    n = rnd.random()\n    if n < 0.5 :\n        new_state[0] = state[0] + np.sqrt(temp)\n        new_state[1] = state[1] + np.sqrt(temp)\n        return (clip(new_state[0], interval, state[0]), \n                clip(new_state[1], interval, state[1]))\n    else :\n        new_state[0] = state[0] - np.sqrt(temp)\n        new_state[1] = state[1] - np.sqrt(temp)\n        return (clip(new_state[0], interval, state[0]), \n                clip(new_state[1], interval, state[1]))\n\n\ndef clip(x, interval, state):\n    \"\"\"\n    If x is not in interval, \n    return a point chosen uniformly at random between the violated bound \n    and the previous state; \n    otherwise return x.\n    \"\"\"\n    \n    a,b = interval   \n    if x < a :\n        return rnd.uniform(a, state)    \n    if x > b :\n        return rnd.uniform(state, b)    \n    else: \n        return x\n    \n\n\n#---------Acceptance function--------------\n\ndef boltz_acceptance_prob(energy, new_energy, temperature):\n    \"\"\"Boltzmann Annealing\"\"\"\n    \n    delta_e = new_energy - energy   \n    if delta_e < 0 :\n        return 1\n    else:\n        return np.exp(- delta_e / temperature)\n\n\n#--------Cooling Procedures---------------\n\ndef boltz_cooling(initial_temp, k):\n    \"\"\"Boltzmann temperature decreasing.\"\"\"\n    if k <= 1:\n        return initial_temp\n    else:\n        return initial_temp / np.log(k)\n\ndef geom_cooling(temp, k,  alpha = 0.95):\n    \"\"\"Geometric temperature decreasing.\"\"\"\n    return temp * alpha\n\n#--------Stopping Condition------------\n\ndef tolerance(energies, tolerance, tolerance_iter) :\n    \"\"\"\n    The algorithm runs until the average change in value of the objective function \n    is less than the tolerance.\n    \"\"\"\n    \n    if len(energies) <= tolerance_iter :\n        return False\n    if avg_last_k_value(energies, tolerance_iter) < tolerance :\n        return True\n    else : \n        return False\n    \ndef objective_limit(energy, limit):\n    \"\"\"\n    The algorithm stops as soon as the current objective function value\n    is less or equal then limit.\n    \"\"\"\n    \n    if energy <= limit :\n        return True\n    else :\n        return False\n\n\ndef avg_last_k_value(energies, k):\n    \"\"\"\n    Compute the average of the last k absolute differences between the values of a list.\n    \"\"\"\n    \n    diff = []\n    L = len(energies)    \n    for i in range(L - 1,L - (k+1),-1):\n        diff.append(abs(energies[i]-energies[i-1]))\n    return np.mean(diff)\n\n\n\n#------------------------------------------------------\n#------------Simulated Anneanling algorithm------------\n#------------------------------------------------------\n\ndef SA(cooling, acceptance_prob, energy, move, interval, initial_temp = 100., \n       k_max = 1e10, tolerance_value = 1e-6, tolerance_iter = 10,\n       obj_fn_limit = -1e10, reann_tol = 100, verbose = False):\n    \n    #Step 1\n    states = []\n    energies = []\n    temperatures = []\n    s = (rnd.uniform(interval[0], interval[1]), rnd.uniform(interval[0], interval[1]))\n    k = 0\n    T = initial_temp\n    reann = False\n    exit_types = {0 :'Max Iter',\n            1 : 'Tolerance',\n            2 : 'Obj Limit',\n            3 : 'Temp Limit'}\n    _exit = 0\n    \n    if verbose:\n        dash = '-' * 70\n        print(\"\\n\")\n        print ('{:_^70}'.format('Simulated Annealing'))\n        print(\"Test function\", energy)\n        print(\"Initial state: {}\".format(s))\n        print(\"\\n\")\n    \n    \n    while True:\n        k += 1\n        \n        #Stopping criterion\n        if k == k_max :\n            if verbose :\n                print(dash)\n                print(\"MAX ITERATION EXIT\")\n                print(dash)\n            break           \n        \n        #Step 2\n        new_s = move(s, T, interval)\n        energy_s = energy(s)\n        energy_new_s = energy(new_s)\n        states.append(s)\n        energies.append(energy_s)\n        temperatures.append(T)\n        \n        #Step 3\n        T = cooling(T, k)\n        \n        #Stopping criteria\n        if T <= 0. :\n            if verbose :\n                print(dash)\n                print(\"TEMPERATURE EXIT\")\n                print(dash)\n            _exit = 3\n            break   \n        \n       \n        if tolerance(energies, tolerance_value, tolerance_iter) :\n            if verbose :\n                print(dash)\n                print(\"TOLERANCE EXIT\")\n                print(dash)\n            _exit = 1\n            break    \n        \n        \n        if objective_limit(energy_s, obj_fn_limit) :\n            if verbose :\n                print(dash)\n                print(\"OBJECTIVE FUNCTION LIMIT EXIT\")\n                print(dash)\n            _exit = 2\n            break\n        \n        #Reanniling Process\n        best_e = min(energies)\n        best_s = states[np.argmin(energies)]\n        \n        if energy_s > best_e + reann_tol :\n            if verbose :\n                print(dash)\n                print(\"REANNILING\")\n                print(dash)\n            energies = []\n            states = []\n            s = best_s\n            energy_s = best_e\n            T = initial_temp\n            k = 0\n            reann = True\n            continue\n        \n        #Step 4\n        if acceptance_prob(energy_s, energy_new_s, T) >= rnd.random() :\n            s = new_s\n    \n    return states, energies, temperatures, k, exit_types[_exit], reann\n\n", "meta": {"hexsha": "d6f28d6189a82b47a57fb6e58e95998044f87017", "size": 5558, "ext": "py", "lang": "Python", "max_stars_repo_path": "Simulated_annealing/algorithm.py", "max_stars_repo_name": "EleMisi/Projects", "max_stars_repo_head_hexsha": "faf75de5fe5fa5224572f7c0679ffc5937948933", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-27T02:30:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-04T14:27:34.000Z", "max_issues_repo_path": "Simulated_annealing/algorithm.py", "max_issues_repo_name": "EleMisi/Projects", "max_issues_repo_head_hexsha": "faf75de5fe5fa5224572f7c0679ffc5937948933", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Simulated_annealing/algorithm.py", "max_forks_repo_name": "EleMisi/Projects", "max_forks_repo_head_hexsha": "faf75de5fe5fa5224572f7c0679ffc5937948933", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0938967136, "max_line_length": 88, "alphanum_fraction": 0.5106153293, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809829, "lm_q2_score": 0.9019206771886166, "lm_q1q2_score": 0.8544625524724104}}
{"text": "import numpy as np\nfrom problem_3a import inverse_iteration\nfrom problem_3b import rayleigh_iter\n\ndef main():\n\tprint(\"Inverse Iteration\")\n\tprint(\"-------------------\\n\\n\")\n\t\n\tA = np.array([[6, 2, 1], [2, 3, 1], [1, 1, 1]])\n\tx0 = np.array([1, 4, 2])\n\tprint(\"Initial Array:\\n\\t\", x0, \"'\\n\")\n\tl, x, iters = inverse_iteration(A, x0)\n\t\n\tprint(\"Computed Eigenvalue:\", l)\n\tprint(\"Computed Eigenvector:\\n\\t\", x, \"'\\n\")\n\tprint(\"Number of iterations:\", iters)\n\n\tprint(\"\\n\\n\")\n\n\tprint(\"Rayleigh Quotient Iteration\")\n\tprint(\"------------------------------\\n\\n\")\n\n\n\tA = np.array([[6, 2, 1], [2, 3, 1], [1, 1, 1]])\n\tx0 = np.array([1, 4, 2])\n\tprint(\"Initial Array:\\n\\t\", x0, \"'\\n\")\n\tl_r, x_r, iters_r = rayleigh_iter(A, x0)\n\t\n\tprint(\"Computed Eigenvalue:\", l_r)\n\tprint(\"Computed Eigenvector:\\n\\t\", x_r, \"'\\n\")\n\tprint(\"Number of iterations:\", iters_r)\n\tprint(\"\\n\\n\")\n\n\tprint(\"Picking Rayleigh Quotient Iteration result as true value...\\n\\n\")\n\n\trel_err_vec = np.linalg.norm(x - x_r, ord=2) / np.linalg.norm(x_r, ord=2)\n\trel_err_val = np.abs(l - l_r) / np.abs(l_r)\n\n\tprint(\"Relative Error for Eigenvector:\", rel_err_vec)\n\tprint(\"Relative Error for Eigenvalue:\", rel_err_val)\n\n\nif __name__ == '__main__':\n\tmain()", "meta": {"hexsha": "6175006bcd77073323ee37f80bf43bea866194b1", "size": 1193, "ext": "py", "lang": "Python", "max_stars_repo_path": "a3/problem_3e.py", "max_stars_repo_name": "justachetan/scientific-computing", "max_stars_repo_head_hexsha": "e8493b5308c337ea8965a5f96cdd49def94801e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-04-30T14:03:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T19:19:13.000Z", "max_issues_repo_path": "a3/problem_3e.py", "max_issues_repo_name": "justachetan/scientific-computing", "max_issues_repo_head_hexsha": "e8493b5308c337ea8965a5f96cdd49def94801e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "a3/problem_3e.py", "max_forks_repo_name": "justachetan/scientific-computing", "max_forks_repo_head_hexsha": "e8493b5308c337ea8965a5f96cdd49def94801e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1136363636, "max_line_length": 74, "alphanum_fraction": 0.6169321039, "include": true, "reason": "import numpy", "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.90192067059785, "lm_q1q2_score": 0.854462551588203}}
{"text": "import numpy as np\n\n\ndef dct2(x):\n    \"\"\"\n    :param x: 1D input signal in the time domain.\n    :return: DCT(x) - 1D output signal in the frequency DCT domain.\n    \"\"\"\n    P = x.shape[-1]\n    X = np.zeros(P, dtype=float)\n    for k in range(P):\n        out = 0\n        if k == 0:\n            kk = 1. / np.sqrt(2.)\n        else:\n            kk = 1.\n        for n in range(P):\n            out += kk * x[n] * np.cos(np.pi * (n + .5) * k / P)\n        out *= np.sqrt(2. / P)\n        X[k] = out\n    return X\n\n\ndef dct1(Y):\n    N = Y.shape[-1]\n    y = np.zeros(N, dtype=float)\n    for n in range(N):\n        out = 0\n        for k in range(N):\n            if k == 0:\n                kk = 1. / 2.\n            else:\n                kk = 1.\n            out += kk * Y[k] * np.cos(np.pi * n * k / N)\n        y[n] = out\n    return y\n\n\ndef correlate(x, h):\n    \"\"\"\n    Cross-correlation of x and y via the DCT transform.\n\n    :param x: input signal x in the time domain\n    :param h: input filter y in the time domain\n    :return: the output of the correlation\n    \"\"\"\n    N = len(x)\n    L = len(h)\n    M = N + L - 1\n    P1 = max((L - 3), 0) // 2 + 1\n    P2 = max(P1 + 1, (N - 3) // 2 + 1)\n    # P2 = (N - 3) // 2\n    P = max(P2 + 1, 3 * M // 2 + 1)\n\n    x = np.pad(array=x, pad_width=(P1, P - P1 - N), mode='constant')\n    h = np.flip(h, axis=0)\n    h = np.pad(array=h, pad_width=(P2, P - P2 - L), mode='constant')\n    x = dct2(x)\n    h = dct2(h)\n    y = x * h\n    y = dct1(y)[P1 + P2:P1 + P2 + M]\n    return y\n\n\nif __name__ == \"__main__\":\n    x = np.array([1.0, -2.0, 3.0, -4.0, 2.0, -8.0, -1.0, 5.0], dtype=float)\n    # x = np.random.randn(21)\n    print(\"x: \", x)\n    h = np.array([1.0, -4.0, 2.0], dtype=float)\n    h_len = h.shape[-1]\n    pad = (h_len - 1) // 2\n    x_pad = np.pad(x, [pad, pad], mode=\"constant\")\n    expect = np.correlate(x_pad, h, mode='valid')\n    print(\"expect: \", expect)\n    result = correlate(x, h)\n    print(\"result: \", result)\n    assert np.testing.assert_allclose(actual=result, desired=expect)\n", "meta": {"hexsha": "822edac57dbb35039c3c3aa1a5458541800b2153", "size": 2009, "ext": "py", "lang": "Python", "max_stars_repo_path": "cnns/nnlib/dct/dct_correlation.py", "max_stars_repo_name": "adam-dziedzic/time-series-ml", "max_stars_repo_head_hexsha": "81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-25T13:19:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-25T13:19:46.000Z", "max_issues_repo_path": "cnns/nnlib/dct/dct_correlation.py", "max_issues_repo_name": "adam-dziedzic/time-series-ml", "max_issues_repo_head_hexsha": "81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cnns/nnlib/dct/dct_correlation.py", "max_forks_repo_name": "adam-dziedzic/time-series-ml", "max_forks_repo_head_hexsha": "81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7564102564, "max_line_length": 75, "alphanum_fraction": 0.4738675958, "include": true, "reason": "import numpy", "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731765, "lm_q2_score": 0.9173026556293917, "lm_q1q2_score": 0.8544330347514557}}
{"text": "'''\nImplementing the technique in \"A Smarter Way To Find Pitch\" by Philip McLeod\nand Geoff Wyvill, which is simple, elegant, and effective\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef estimateFundamentalFreq(x, doPlot = False):\n    #Step 1: Compute normalized squared difference function\n    #Using variable names in the paper\n    N = x.size\n    W = np.int(N/2)\n    t = W\n    corr = np.zeros(W)\n    #Do brute force f FFT because I'm lazy\n    #(fine because signals are small)\n    for Tau in np.arange(W):\n        xdelay = x[Tau::]\n        L = (W - Tau)/2\n        m = np.sum(x[int(t-L):int(t+L+1)]**2) + np.sum(xdelay[int(t-L):int(t+L+1)]**2)\n        r = np.sum(x[int(t-L):int(t+L+1)]*xdelay[int(t-L):int(t+L+1)])\n        corr[Tau] = 2*r/m\n\n    #Step 2: Find the ''key max''\n    #Compute zero crossings\n    zc = np.zeros(corr.size-1)\n    zc[(corr[0:-1] < 0)*(corr[1::] > 0)] = 1\n    zc[(corr[0:-1] > 0)*(corr[1::] < 0)] = -1\n\n    #Mark regions which are admissible for key maxes\n    #(regions with positive zero crossing to left and negative to right)\n    admiss = np.zeros(corr.size)\n    admiss[0:-1] = zc\n    for i in range(1, corr.size):\n        if admiss[i] == 0:\n            admiss[i] = admiss[i-1]\n\n    #Find all local maxes\n    maxes = np.zeros(corr.size)\n    maxes[1:-1] = (np.sign(corr[1:-1] - corr[0:-2])==1)*(np.sign(corr[1:-1] - corr[2::])==1)\n    maxidx = np.arange(corr.size)\n    maxidx = maxidx[maxes == 1]\n    maxTau = 0\n    if len(corr[maxidx]) > 0:\n        maxTau = maxidx[np.argmax(corr[maxidx])]\n\n    if doPlot:\n        plt.subplot(211)\n        plt.plot(x)\n        plt.title(\"Original Signal\")\n        plt.subplot(212)\n        plt.plot(corr)\n        plt.hold(True)\n        plt.plot(admiss*1.05, 'r')\n        plt.ylim([-1.1, 1.1])\n        plt.scatter(maxidx, corr[maxidx])\n        plt.scatter([maxTau], [corr[maxTau]], 100, 'r')\n        plt.title(\"Max Tau = %i, Clarity = %g\"%(maxTau, corr[maxTau]))\n    return (maxTau, corr)\n\nif __name__ == '__main__':\n    T = 60\n    NPeriods = 5\n    np.random.seed(50)\n    t = np.linspace(0, 2*np.pi*NPeriods, T*NPeriods)\n    slope = t[1] - t[0]\n    t = np.cumsum(np.random.rand(t.size)*2*slope)\n    x = np.cos(t) + np.cos(2*t)\n    f = estimateFundamentalFreq(x, True)\n", "meta": {"hexsha": "a8810e8ae3f28b6ccf5595e980a6b0cc4e077031", "size": 2239, "ext": "py", "lang": "Python", "max_stars_repo_path": "FundamentalFreq.py", "max_stars_repo_name": "ctralie/SlidingWindowVideoTDA", "max_stars_repo_head_hexsha": "d707a0c4727e068778d5c805f938556c91d6f1ce", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-05-09T12:21:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T10:14:23.000Z", "max_issues_repo_path": "FundamentalFreq.py", "max_issues_repo_name": "ctralie/GSPLib", "max_issues_repo_head_hexsha": "e027a60140ce7590e29520f6ea7f4e659180f4fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FundamentalFreq.py", "max_forks_repo_name": "ctralie/GSPLib", "max_forks_repo_head_hexsha": "e027a60140ce7590e29520f6ea7f4e659180f4fc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-05-23T07:00:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T11:32:36.000Z", "avg_line_length": 31.5352112676, "max_line_length": 92, "alphanum_fraction": 0.5743635552, "include": true, "reason": "import numpy", "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.9173026618464795, "lm_q1q2_score": 0.8544330318162157}}
{"text": "# encoding=utf8\r\n\r\n\r\n\"\"\"\r\nModule containing functions for calculating or approximating factorials.\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\nfrom decimal import Decimal, localcontext\r\n\r\n\r\ndef factorial(n, prec=100):\r\n    r\"\"\"\r\n    Function for calculating factorials using the standard approach as explained in the\r\n    Notes section. For factorials over 100, the decimal package is used to support the\r\n    resulting large integers.\r\n\r\n    Parameters\r\n    ----------\r\n    n : int\r\n        The desired integer to calculate the factorial.\r\n    prec : int default 100, optional\r\n        Defines level of precision for factorials over 100\r\n        for use by the decimal package\r\n\r\n    Returns\r\n    -------\r\n    int or Decimal\r\n        The computed factorial of the given integer.\r\n\r\n    Notes\r\n    -----\r\n    Factorials are denoted for a positive integer :math:`x` as :math:`x!` and are\r\n    defined as:\r\n\r\n    .. math::\r\n\r\n        x! = (x)(x - 1)(x - 2) \\cdots (2)(1)\r\n\r\n    For example, the factorial of 5 is written as:\r\n\r\n    .. math::\r\n\r\n        5! = (5)(4)(3)(2)(1) = 120\r\n\r\n    Examples\r\n    --------\r\n    >>> factorial(10)\r\n    3628800.0\r\n    >>> factorial(50)\r\n    3.0414093201713376e+64\r\n    # Factorials above 100 use the decimal package to handle the resulting large integers\r\n    >>> factorial(200)\r\n    Decimal('7.886578673647905035523632139321850622951359776871732632947425332443594499634033429203042840119846238E+374')\r\n\r\n    References\r\n    ----------\r\n    Press, W., Teukolsky, S., Vetterling, W., & Flannery, B. (2007). Numerical recipes (3rd ed.).\r\n        Cambridge: Cambridge University Press.\r\n\r\n    Weisstein, Eric W. \"Factorial.\" From MathWorld--A Wolfram Web Resource.\r\n        http://mathworld.wolfram.com/Factorial.html\r\n\r\n    \"\"\"\r\n    if n != np.floor(n):\r\n        n = np.floor(n)\r\n\r\n    factor = np.arange(1, n + 1)\r\n\r\n    if n > 100:\r\n        with localcontext() as ctx:\r\n            ctx.prec = prec\r\n            f = Decimal(1)\r\n            for i in reversed(factor):\r\n                f = Decimal(f) * i\r\n    else:\r\n        f = float(1)\r\n        for i in reversed(factor):\r\n            f = f * i\r\n\r\n    return int(f)\r\n\r\n\r\ndef stirlingln(n, keep_log=False, prec=100):\r\n    r\"\"\"\r\n    Approximates the factorial of n using the approximation\r\n    given by Ramanujan in his lost notebook (Ramanujan 1988,\r\n    as cited in Wikipedia). Computing the factorial in logarithmic\r\n    form is useful as it helps avoid overflow when n is large. As\r\n    values of n increase, the approximation given becomes more\r\n    exact.\r\n\r\n    Parameters\r\n    ----------\r\n    n : int\r\n        The desired integer to calculate the factorial.\r\n    keep_log : bool default False\r\n        If True, the approximation remains in logarithmic\r\n        form. If False, converts to exponent form before\r\n        returning the factorial approximation.\r\n    prec : int default 100, optional\r\n        Defines level of precision for factorials over 100.\r\n\r\n    Returns\r\n    -------\r\n    int or Decimal\r\n        The computed log factorial of the given integer.\r\n\r\n    Notes\r\n    -----\r\n    It is often useful to compute the logarithmic form of the\r\n    factorial and convert it to exponent form to avoid overflow.\r\n    The approximation is an alternative approach given by\r\n    Srinivasa Ramanujan (Ramanujan 1988).\r\n\r\n    .. math::\r\n\r\n        ln n! \\approx n ln n - n + \\frac{1}{6} ln(n(1 + 4n(1 + 2n))) + \\frac{1}{2} ln \\pi\r\n\r\n    Examples\r\n    --------\r\n    # Difference between actual factorial calculation and Stirling's Approximation\r\n    # for low values of n is practically zero\r\n    >>> (factorial(5) - stirlingln(5)) / stirlingln(5)\r\n    3.8020354295010749e-06\r\n    >>> stirlingln(50)\r\n    3.041409303897981e+64\r\n    >>> stirlingln(100)\r\n    9.3326215380340829e+157\r\n    # If the keep_log flag is set to True, the output remains in logarithmic form.\r\n    >>> stirlingln(100, True)\r\n    363.73937555488197\r\n\r\n    References\r\n    ----------\r\n    Stirling's approximation. (2017, March 8). In Wikipedia, The Free Encyclopedia.\r\n        From https://en.wikipedia.org/w/index.php?title=Stirling%27s_approximation&oldid=769328178\r\n\r\n    \"\"\"\r\n    if n != np.floor(n):\r\n        n = np.floor(n)\r\n\r\n    n = float(n)\r\n    if n > 100:\r\n        with localcontext() as ctx:\r\n            ctx.prec = prec\r\n            f = Decimal(n * np.log(n) - n + (1. / 6.) * np.log(n * (1. + 4. * n * (1. + 2. * n))) + .5 * np.log(np.pi))\r\n    else:\r\n        f = n * np.log(n) - n + (1. / 6.) * np.log(n * (1. + 4. * n * (1. + 2. * n))) + .5 * np.log(np.pi)\r\n\r\n    if keep_log is False:\r\n        return np.exp(f)\r\n\r\n    return f\r\n\r\n\r\ndef stirling(n, prec=100):\r\n    r\"\"\"\r\n    Approximates a factorial of an integer :math:`n` using Stirling's Approximation.\r\n    Specifically, the approximation is done using a method developed by Gosper.\r\n\r\n    Parameters\r\n    ----------\r\n    n : int\r\n        The desired integer to calculate the factorial.\r\n    prec\r\n        Defines level of precision for factorials over 100. Default 100. Optional\r\n\r\n    Returns\r\n    -------\r\n    int or Decimal\r\n        The computed factorial of the given integer.\r\n\r\n    Notes\r\n    -----\r\n    Stirling's approximation is a method of approximating a factorial :math:`n!`.\r\n    As the value of :math:`n` increases, the more exact the approximation becomes;\r\n    however, it still yields almost exact results for small values of :math:`n`.\r\n\r\n    The approximation used is given by Gosper, which is noted to be a better\r\n    approximation to :math:`n!` and also results in a very close approximation to\r\n    :math:`0! = 1`.\r\n\r\n    .. math::\r\n\r\n        n! \\approx \\sqrt{(2n + \\frac{1}{3})\\pi} n^n e^{-n}\r\n\r\n    Examples\r\n    --------\r\n    >>> stirling(0)\r\n    1.0233267079464885\r\n    >>> (factorial(5) - stirling(5)) / stirling(5)\r\n    0.00024981097589214563\r\n    >>> stirling(5)\r\n    119.9700301696855\r\n    >>> stirling(50)\r\n    3.0414009581300833e+64\r\n\r\n    References\r\n    ----------\r\n    Stirling's approximation. (2017, March 8). In Wikipedia, The Free Encyclopedia.\r\n        From https://en.wikipedia.org/w/index.php?title=Stirling%27s_approximation&oldid=769328178\r\n\r\n    Weisstein, Eric W. \"Stirling's Approximation.\" From MathWorld--A Wolfram Web Resource.\r\n        http://mathworld.wolfram.com/StirlingsApproximation.html\r\n\r\n    \"\"\"\r\n    if n != np.floor(n):\r\n        n = np.floor(n)\r\n\r\n    if n >= 100:\r\n        with localcontext() as ctx:\r\n            ctx.prec = prec\r\n            f = Decimal(np.sqrt((2. * n + 1. / 3.) * np.pi) * n ** n * np.exp(-n))\r\n    else:\r\n        f = np.sqrt((2. * n + 1. / 3.) * np.pi) * n ** n * np.exp(-n)\r\n\r\n    return f\r\n\r\n\r\ndef ramanujan(n, prec=100):\r\n    r\"\"\"\r\n    Approximates the factorial :math:`n!` given an integer :math:`n` using Ramanujan's formula.\r\n    Ramanujan's formula is just as or more accurate than several other factorial approximation\r\n    formulas.\r\n\r\n    Parameters\r\n    ----------\r\n    n\r\n        Integer to approximate factorial\r\n    prec\r\n        Defines level of precision for factorials over 100. Default 100. Optional\r\n\r\n    Returns\r\n    -------\r\n    int or Decimal\r\n        Factorial of :math:`n` as approximated by Ramanujan's formula.\r\n\r\n    Notes\r\n    -----\r\n    Ramanujan's formula is another factorial approximation method known for its accuracy\r\n    in comparison to other factorial approximation approaches including Stirling's and\r\n    Gosper's approximations. Ramanujan's formula is defined as:\r\n\r\n    .. math::\r\n\r\n        n! \\approx \\sqrt{\\pi} \\left(\\frac{n}{e}\\right)^n \\sqrt[6]{8n^3 + 4n^2 + n + \\frac{1}{30}}\r\n\r\n    Examples\r\n    --------\r\n    >>> ramanujan(10)\r\n    3628800.3116126074\r\n    >>> ramanujan(5)\r\n    120.00014706585664\r\n\r\n    References\r\n    ----------\r\n    Mortici, Cristinel. On Gosper's Formula for the Gamma Function. Valahia University of Targoviste,\r\n        Department of Mathematics. Retrieved from http://files.ele-math.com/articles/jmi-05-53.pdf\r\n\r\n    \"\"\"\r\n    if n != np.floor(n):\r\n        n = np.floor(n)\r\n\r\n    if n >= 100:\r\n        with localcontext() as ctx:\r\n            ctx.prec = prec\r\n            f = Decimal(\r\n                np.sqrt(np.pi) * n ** n * np.exp(-n) * (8. * n ** 3. + 4. * n ** 2. + n + 1. / 30.) ** (1. / 6.))\r\n    else:\r\n        f = np.sqrt(np.pi) * n ** n * np.exp(-n) * (8. * n ** 3. + 4. * n ** 2. + n + (1. / 30.)) ** (1. / 6.)\r\n\r\n    return f\r\n\r\n\r\ndef fallingfactorial(x, n):\r\n    r\"\"\"\r\n    Computes the falling factorial.\r\n\r\n    Parameters\r\n    ----------\r\n    x\r\n        Integer. The value will be rounded down if the value is not an integer.\r\n    n\r\n        Integer. The value will be rounded down if the value is not an integer.\r\n\r\n    Returns\r\n    -------\r\n    int or str\r\n        The falling factorial for an integer :math:`n`, :math:`(x)_{n}`. If x is a\r\n        str, the output is the symbolic representation of the falling factorial.\r\n\r\n    Notes\r\n    -----\r\n    The falling factorial, denoted as :math:`(x)_{n}` (or :math:`x^{\\underline{n}}`) is\r\n    defined as the following:\r\n\r\n    .. math::\r\n\r\n        (x)_n = x(x - 1) \\cdots (x - (n - 1))\r\n\r\n    The first few falling factorials are then:\r\n\r\n    ..math::\r\n\r\n        (x)_0 = 1\r\n        (x)_1 = x\r\n        (x)_2 = x(x - 1)\r\n        (x)_3 = x(x - 1)(x - 2)\r\n        (x)_4 = x(x - 1)(x - 2)(x - 3)\r\n\r\n    Examples\r\n    --------\r\n    >>> fallingfactorial(10, 5)\r\n    30240\r\n    >>> fallingfactorial(10, 2)\r\n    90\r\n    >>> fallingfactorial('x', 2)\r\n    'x*(x - 1)'\r\n    >>> fallingfactorial('a', 4)\r\n    'a*(a - 1)*(a - 2)*(a - 3)'\r\n\r\n    References\r\n    ----------\r\n    Falling and rising factorials. (2017, June 8). In Wikipedia, The Free Encyclopedia.\r\n        From https://en.wikipedia.org/w/index.php?title=Falling_and_rising_factorials&oldid=784512036\r\n\r\n    Weisstein, Eric W. \"Falling Factorial.\" From MathWorld--A Wolfram Web Resource.\r\n        http://mathworld.wolfram.com/FallingFactorial.html\r\n\r\n    \"\"\"\r\n    if n != np.floor(n):\r\n        n = np.floor(n)\r\n\r\n    if isinstance(x, str):\r\n        f = x\r\n\r\n        for i in np.arange(1, np.absolute(n)):\r\n            f = f + '*(' + str(x) + ' - ' + str(i) + ')'\r\n\r\n        if n < 0:\r\n            f = '1 /' + f\r\n\r\n    else:\r\n        if x != np.floor(x):\r\n            x = np.floor(x)\r\n\r\n        f = np.uint64(1.0)\r\n        for i in np.arange(np.absolute(n)):\r\n            f *= (x - i)\r\n\r\n        if n < 0:\r\n            f = 1 / f\r\n\r\n    return f\r\n\r\n\r\ndef risingfactorial(x, n):\r\n    r\"\"\"\r\n    Computes the rising factorial. Also known as the Pochhammer symbol.\r\n\r\n    Parameters\r\n    ----------\r\n    x\r\n        Integer. The value will be rounded down if the value is not an integer.\r\n    n\r\n        Integer. The value will be rounded down if the value is not an integer.\r\n\r\n    Returns\r\n    -------\r\n    int or str\r\n        The rising factorial for an integer :math:`n`, :math:`(x)_{n}`. If x is\r\n        a str, the output is the symbolic representation of the rising factorial.\r\n\r\n    Notes\r\n    -----\r\n    The rising factorial, :math:`x^{(n)}` (sometimes denoted \\langle x \\rangle_n ) is\r\n    also known as the Pochhammer symbol in other areas of mathematics.\r\n\r\n    The rising factorial is related to the gamma function :math:`\\Gamma (z)`.\r\n\r\n    .. math::\r\n\r\n        x^{(n)} \\equiv \\frac{\\Gamma (x + n)}{\\Gamma (n)}\r\n\r\n    where :math:`x^(0) = 1`.\r\n\r\n    The rising factorial is related to the falling factorial by:\r\n\r\n    .. math::\r\n\r\n        x^{(n)} = (-x)_n (-1)^n\r\n\r\n    Examples\r\n    --------\r\n    >>> risingfactorial(10, 6)\r\n    3603600\r\n    >>> risingfactorial('x', 4)\r\n    'x*(x + 1)*(x + 2)*(x + 3)'\r\n\r\n    References\r\n    ----------\r\n    Falling and rising factorials. (2017, June 8). In Wikipedia, The Free Encyclopedia.\r\n        From https://en.wikipedia.org/w/index.php?title=Falling_and_rising_factorials&oldid=784512036\r\n\r\n    Weisstein, Eric W. \"Rising Factorial.\" From MathWorld--A Wolfram Web Resource.\r\n        http://mathworld.wolfram.com/RisingFactorial.html\r\n\r\n    \"\"\"\r\n    if n != np.floor(n):\r\n        n = np.floor(n)\r\n\r\n    if isinstance(x, str):\r\n        f = x\r\n\r\n        for i in np.arange(1, np.absolute(n)):\r\n            f = f + '*(' + str(x) + ' + ' + str(i) + ')'\r\n\r\n        if n < 0:\r\n            f = '1 /' + f\r\n\r\n    else:\r\n        if x != np.floor(x):\r\n            x = np.floor(x)\r\n\r\n        f = np.uint64(1.0)\r\n\r\n        for i in np.arange(np.absolute(n)):\r\n            f *= (x + i)\r\n\r\n        if n < 0:\r\n            f = 1 / f\r\n\r\n    return f\r\n", "meta": {"hexsha": "5c3bd7a14c5cd75d8619395f3a21f94053a475d4", "size": 12364, "ext": "py", "lang": "Python", "max_stars_repo_path": "venv/lib/python3.8/site-packages/mathpy/combinatorics/factorial.py", "max_stars_repo_name": "sonakshibhalla/sonakshicode", "max_stars_repo_head_hexsha": "5242d1b128a6be3d184b5c64cf5f9448ccdc49be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "venv/lib/python3.8/site-packages/mathpy/combinatorics/factorial.py", "max_issues_repo_name": "sonakshibhalla/sonakshicode", "max_issues_repo_head_hexsha": "5242d1b128a6be3d184b5c64cf5f9448ccdc49be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "venv/lib/python3.8/site-packages/mathpy/combinatorics/factorial.py", "max_forks_repo_name": "sonakshibhalla/sonakshicode", "max_forks_repo_head_hexsha": "5242d1b128a6be3d184b5c64cf5f9448ccdc49be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2929061785, "max_line_length": 122, "alphanum_fraction": 0.5604173407, "include": true, "reason": "import numpy", "num_tokens": 3449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.909907002984195, "lm_q1q2_score": 0.8544252589069357}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef LR_1D_calculator(X,Y, xlabel=None, ylabel=None):\n    # We now solve the equation y = aX + b\n    X_mean = X.mean()\n    X_sum = X.sum()\n    Y_mean = Y.mean()\n    Y_sum = Y.sum()\n\n    denominator = X.dot(X) - X_mean * X_sum\n    a = ( X.dot(Y) - Y_mean * X_sum) / denominator\n    b = ( Y_mean * X.dot(X) - X_mean * X.dot(Y)) / denominator\n\n    Y_hat = a * X + b\n\n    plt.figure()\n    plt.scatter(X,Y)\n    plt.plot(X, Y_hat, 'r')\n    if xlabel is not None:\n        plt.xlabel(xlabel)\n    if ylabel is not None:\n        plt.ylabel(ylabel)\n    plt.show()\n\n    R2 = r2_calculator(Y, Y_hat)\n\n    return Y_hat, a, b, R2\n\ndef r2_calculator(Y, Y_hat):\n\n    # We also calculate the R^2 error:\n\n    d1 = Y - Y_hat\n    d2 = Y - Y.mean()\n    R2 = 1 - d1.dot(d1) / d2.dot(d2)\n    print(\"The R^2 is: \", R2)\n\n    return R2\n\n\nif __name__ == '__main__':\n\n    # We first load and visualise the data:\n\n    X = []\n    Y = []\n    for line in open('../large_files/data_1d.csv'):\n        x, y = line.split(',')\n        X.append(float(x))\n        Y.append(float(y))\n\n    X = np.array(X)\n    Y = np.array(Y)\n\n    plt.figure()\n    plt.scatter(X,Y)\n    plt.show()\n\n    LR_1D_calculator(X,Y)", "meta": {"hexsha": "dc82b7fcb556e5e3719f2e458243aed9a379ff13", "size": 1215, "ext": "py", "lang": "Python", "max_stars_repo_path": "one_dimensional_linear_regression/one_dimensional_linear_regression_solution.py", "max_stars_repo_name": "AndreiRoibu/LinearRegression", "max_stars_repo_head_hexsha": "fffb7b555e717836e9e449bcca68ef8d3d8c7918", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-28T12:49:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T12:49:40.000Z", "max_issues_repo_path": "one_dimensional_linear_regression/one_dimensional_linear_regression_solution.py", "max_issues_repo_name": "AndreiRoibu/LinearRegression", "max_issues_repo_head_hexsha": "fffb7b555e717836e9e449bcca68ef8d3d8c7918", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "one_dimensional_linear_regression/one_dimensional_linear_regression_solution.py", "max_forks_repo_name": "AndreiRoibu/LinearRegression", "max_forks_repo_head_hexsha": "fffb7b555e717836e9e449bcca68ef8d3d8c7918", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.25, "max_line_length": 62, "alphanum_fraction": 0.5547325103, "include": true, "reason": "import numpy", "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.975576912076157, "lm_q2_score": 0.8757869786798663, "lm_q1q2_score": 0.8543975562970112}}
{"text": "# add() is done between two elements : return an array\r\n# sum([]) happens over n elements : return an element\r\n\r\nimport numpy as np \r\n\r\narr1 = np.array([1, 2, 3])\r\narr2 = np.array([4, 5, 6])\r\n\r\nnewarr = np.add(arr1, arr2)\r\n\r\nprint(\"add():\", newarr)\r\n\r\nnewarr = np.sum([arr1, arr2])\r\n# note that sum([])\r\n\r\nprint(\"sum(): \", newarr)\r\n\r\n# Summation over an axis\r\n\r\nnewarr = np.sum([arr1, arr2], axis = 1)\r\n\r\nprint(\"sum() over an axis\", newarr)\r\n\r\n# cummulative sum : partially adding the elements in array\r\n\r\n# The partial sum of [1, 2, 3, 4] would be [1, 1+2, 1+2+3, 1+2+3+4] = [1, 3, 6, 10]\r\n\r\n# cumsum()\r\n\r\n# import numpy as np \r\n\r\narr = np.array([1, 2, 3])\r\n\r\nprint(\"cummulative Sum: \", np.cumsum(arr))", "meta": {"hexsha": "16e2ccd1be3991f2abe648187e2d09ae5b187bc3", "size": 703, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_summation.py", "max_stars_repo_name": "khinthandarkyaw98/Python_Practice", "max_stars_repo_head_hexsha": "9b431129c79315a57dae81048a22bf85c4b5132c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy_summation.py", "max_issues_repo_name": "khinthandarkyaw98/Python_Practice", "max_issues_repo_head_hexsha": "9b431129c79315a57dae81048a22bf85c4b5132c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy_summation.py", "max_forks_repo_name": "khinthandarkyaw98/Python_Practice", "max_forks_repo_head_hexsha": "9b431129c79315a57dae81048a22bf85c4b5132c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6764705882, "max_line_length": 84, "alphanum_fraction": 0.5931721195, "include": true, "reason": "import numpy", "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.9073122307591683, "lm_q1q2_score": 0.8543743344726434}}
{"text": "import scipy.sparse.linalg\nimport scipy.sparse as sp\nimport matplotlib.pylab as plt\nimport numpy as np\n\nN = 100\ne = np.ones(N, dtype=float)\nA = sp.spdiags([e, -2*e, e], [-1, 0, 1], N, N, format='csc')\n\nplt.spy(A)\nplt.show()\n\nL = 2*np.pi\nx = np.linspace(0, L, N+2)\nh = x[1] - x[0]\nfcos = 2 * np.cos(x) / np.exp(x)\nanalytical_cos = -np.sin(x) / np.exp(x)\nfsin = 2 * np.sin(x) / np.exp(x)\nanalytical_sin = np.cos(x) / np.exp(x)\n\n# Use sparse lu decomposition, matrix is tridiagonal so no fill-in\nsplu = sp.linalg.splu(A / h**2)\nfig, axs = plt.subplots(1, 2)\naxs[0].spy(splu.L)\naxs[0].set_title('L')\naxs[1].spy(splu.U)\naxs[1].set_title('U')\nplt.show()\n\n# Use decomposition to solve both problems\nfor f, a in zip([fcos, fsin], [analytical_cos, analytical_sin]):\n    b = f[1:-1]\n    b[0] -= a[0] / h**2\n    b[-1] -= a[-1] / h**2\n    v = splu.solve(b)\n    plt.plot(x[1:-1], v, label='solution')\n    plt.plot(x, a, label='analytical')\n    plt.legend()\n    plt.show()\n\nimport time\nnum = 100\ntimes = np.empty(num, dtype=float)\ntimes_dense = np.empty(num, dtype=float)\ntimes_dense[:] = np.nan\nNs = np.logspace(0.5, 6, num=num, dtype=int)\nfor i, N in enumerate(Ns):\n    e = np.ones(N, dtype=float)\n    A = sp.spdiags([e, -2*e, e], [-1, 0, 1], N, N, format='csc')\n\n    t0 = time.perf_counter()\n    AA = A @ A\n    t1 = time.perf_counter()\n    times[i] = t1 - t0\n\n    if N < 2000:\n        Adense = A.toarray()\n        t0 = time.perf_counter()\n        AA = Adense @ Adense\n        t1 = time.perf_counter()\n        times_dense[i] = t1 - t0\n\nplt.clf()\nplt.loglog(Ns, times, label='sparse @')\nplt.loglog(Ns, times_dense, label='dense @')\nplt.xlabel('N')\nplt.ylabel('time taken')\nplt.legend()\nplt.show()\n\ntimes = np.empty(num, dtype=float)\ntimes_dense = np.empty(num, dtype=float)\ntimes_dense[:] = np.nan\n\nfor i, N in enumerate(Ns):\n    e = np.ones(N, dtype=float)\n    A = sp.spdiags([e, -2*e, e], [-1, 0, 1], N, N, format='csc')\n\n    x = np.linspace(0, L, N+2)\n    h = x[1] - x[0]\n    fcos = 2 * np.cos(x) / np.exp(x)\n    analytical_cos = -np.sin(x) / np.exp(x)\n\n    A /= h**2\n\n    b = fcos[1:-1]\n    b[0] -= analytical_cos[0] / h**2\n    b[-1] -= analytical_cos[-1] / h**2\n\n    t0 = time.perf_counter()\n    splu = sp.linalg.splu(A)\n    v = splu.solve(b)\n    t1 = time.perf_counter()\n    times[i] = t1 - t0\n    if N < 2000:\n        Adense = A.toarray()\n        t0 = time.perf_counter()\n        lu = scipy.linalg.lu_factor(Adense)\n        v = scipy.linalg.lu_solve(lu, b)\n        t1 = time.perf_counter()\n        times_dense[i] = t1 - t0\n\nplt.clf()\nplt.loglog(Ns, times, label='sparse LU')\nplt.loglog(Ns, times_dense, label='dense LU')\nplt.xlabel('N')\nplt.ylabel('time taken')\nplt.legend()\nplt.show()\n\n\n", "meta": {"hexsha": "2ad026139405dd3f4f201b4b3a70b0f00c76ee16", "size": 2682, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/unit_2_4.py", "max_stars_repo_name": "tommylees112/scientific-computing", "max_stars_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-02-03T02:10:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T13:21:47.000Z", "max_issues_repo_path": "src/unit_2_4.py", "max_issues_repo_name": "tommylees112/scientific-computing", "max_issues_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-01T16:00:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T17:09:17.000Z", "max_forks_repo_path": "src/unit_2_4.py", "max_forks_repo_name": "tommylees112/scientific-computing", "max_forks_repo_head_hexsha": "08a4173287699c7012fdd01de949d299e38aa30c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-02-01T15:45:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T12:20:25.000Z", "avg_line_length": 23.9464285714, "max_line_length": 66, "alphanum_fraction": 0.5846383296, "include": true, "reason": "import numpy,import scipy", "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.907312221360624, "lm_q1q2_score": 0.8543743315649512}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n###\n# Name: Trevor Kling\n# Student ID: 002270716\n# Email: kling109@mail.chapman.edu\n# Course: PHYS220/MATH220/CPSC220 Fall 2018\n# Assignment: CW08\n###\n\nimport numpy as np\n\ndef s(T, t, n):\n    \"\"\"\n    Implements a summation of a sin-based function with defined constants T and t.  The sum is computed\n    up to a value n, and should converge to 1, -1, or 0 depending on the range t falls into.\n    0 < t < T/2: Converges to 1.\n    t = 0: Converges to 0.\n    -T/2 < t < 0: Converges to -1\n    \"\"\"\n    summationArray = np.arange(1, n+1)\n    def func(k):\n        return (((1)/(2*k - 1))*np.sin((2*(2*k - 1)*np.pi*t)/(T)))\n    summer = np.vectorize(func)\n    result = (4/np.pi)*np.sum(summer(summationArray))\n    return result\n\ndef f(T, t):\n    \"\"\"\n    Checks if t is between particular values, and returns what the above function will converge to at\n    infinity for the given t value.\n    \"\"\"\n    if 0 < t < (T/2):\n        return 1\n    elif t == 0:\n        return 0\n    elif -(T/2) < t < 0:\n        return -1\n    else:\n        print(\"That is not within the given range of [-T/2, T/2]\")\n        return None\n", "meta": {"hexsha": "ac34f646fcdad5054a1aea85cfba79a312a3d5a5", "size": 1151, "ext": "py", "lang": "Python", "max_stars_repo_path": "sinesum.py", "max_stars_repo_name": "chapman-phys220-2018f/cw08-poor-social-skills", "max_stars_repo_head_hexsha": "c98f43566cffc7a14c15b6d4dc6209d736ade065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sinesum.py", "max_issues_repo_name": "chapman-phys220-2018f/cw08-poor-social-skills", "max_issues_repo_head_hexsha": "c98f43566cffc7a14c15b6d4dc6209d736ade065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sinesum.py", "max_forks_repo_name": "chapman-phys220-2018f/cw08-poor-social-skills", "max_forks_repo_head_hexsha": "c98f43566cffc7a14c15b6d4dc6209d736ade065", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7674418605, "max_line_length": 103, "alphanum_fraction": 0.5899218071, "include": true, "reason": "import numpy", "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.8962513821399044, "lm_q1q2_score": 0.8543740757702919}}
{"text": "import numpy as np\n\ntemp_na = np.array([1, 2, 3, 4, 5, 6])\ntemp_na\n\ntemp_na.shape\n\n# 基本统计\ntemp_na.max()\ntemp_na.min()\ntemp_na.mean()\ntemp_na.sum()\n\n# np reshape 改变矩阵形状\ntemp_na = temp_na.reshape(2, 3)\ntemp_na\n\n# tensor 切片\n# 所有行的前面两列\ntemp_na[:, :2]\n\n# 矩阵计算\nnp.random([3, 5])\nna1 = np.random.rand(2, 3)\nna2 = np.random.rand(3, 5)\nna1\nna2\nnp.dot(na1, na2)\n\n# 创建各种矩阵\nzeroarray = np.zeros((2, 3))\nprint(zeroarray)\n\nonearray = np.ones((3, 4), dtype='int64')\nprint(onearray)\n\nemptyarray = np.empty((3, 4))\nprint(emptyarray)\n\narray = np.arange(10, 31, 5)\nprint(array)\n\n# 矩阵的na的属性\narray = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])\nprint(array)\n# 数组维度\nprint(array.ndim)\n# 数组形状\nprint(array.shape)\n# 数组元素个数\nprint(array.size)\n# 数组元素类型\nprint(array.dtype)\n\n# 改变na的形状\narray1 = np.arange(6).reshape([2, 3])\nprint(array1)\n\narray2 = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int64).reshape([3, 2])\nprint(array2)\n\n# 矩阵的计算\narr1 = np.array([[1, 2, 3], [4, 5, 6]])\narr2 = np.ones([2, 3], dtype=np.int64)\nprint(arr1)\nprint(arr2)\n\n# 矩阵的基本运算\nprint(arr1 + arr2)\nprint(arr1 - arr2)\nprint(arr1 * arr2)\nprint(arr1 / arr2)\n# 平方\nprint(arr1 ** 2)\n\n# 矩阵的乘法\narr3 = np.array([[1, 2, 3], [4, 5, 6]])\narr4 = np.ones([3, 2], dtype=np.int64)\nprint(arr3)\nprint(arr4)\nprint(np.dot(arr3, arr4))\n\n# np的其他统计分析函数\nprint(arr3)\nprint(np.sum(arr3, axis=1))  # axis=1,每一行求和 axie=0,每一列求和\nprint(np.max(arr3))\nprint(np.min(arr3))\nprint(np.mean(arr3))\nprint(np.argmax(arr3))\nprint(np.argmin(arr3))\n\n# 矩阵的转置\narr3_tran = arr3.transpose()\nprint(arr3_tran)\nprint(arr3.flatten())\n\n# 矩阵的索引和切片\narr5 = np.arange(0, 6).reshape([2, 3])\nprint(arr5)\nprint(arr5[1])\nprint(arr5[1][2])\nprint(arr5[1, 2])\nprint(arr5[1, :])\nprint(arr5[:, 1])\nprint(arr5[1, 0:2])\n", "meta": {"hexsha": "5304fb7419f8343a47b3446a5af5c8c6dcf5bc0e", "size": 1705, "ext": "py", "lang": "Python", "max_stars_repo_path": "learn/data_analysis/normal_data_analysis/numpy_learn.py", "max_stars_repo_name": "ArseneLupinhb/py_al", "max_stars_repo_head_hexsha": "e2e4d25a00cb13d68da26c17f86f9cf1e47a79e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-14T03:32:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-14T03:32:56.000Z", "max_issues_repo_path": "learn/data_analysis/normal_data_analysis/numpy_learn.py", "max_issues_repo_name": "ArseneLupinhb/py_al", "max_issues_repo_head_hexsha": "e2e4d25a00cb13d68da26c17f86f9cf1e47a79e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "learn/data_analysis/normal_data_analysis/numpy_learn.py", "max_forks_repo_name": "ArseneLupinhb/py_al", "max_forks_repo_head_hexsha": "e2e4d25a00cb13d68da26c17f86f9cf1e47a79e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.0849056604, "max_line_length": 73, "alphanum_fraction": 0.6463343109, "include": true, "reason": "import numpy", "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953275046683696, "lm_q2_score": 0.8962513620489619, "lm_q1q2_score": 0.8543740589975504}}
{"text": "import copy\r\nimport numpy as np\r\nimport numpy.linalg as la\r\nfrom scipy.optimize import linprog  # TODO: REMOVE\r\n\r\nfrom _errors import ConvergenceError\r\n\r\n\r\n# ======================================================================================================================\r\n# Root-finding Methods\r\n# ======================================================================================================================\r\ndef secant(fun, x0, x1, args=()):\r\n    # options ----------------------------------------------------------------------------------------------------------\r\n    max_it = 1000\r\n    tol = 1e-3\r\n\r\n    # initializing loop ------------------------------------------------------------------------------------------------\r\n    it = 0\r\n    root = x1\r\n\r\n    # iterating --------------------------------------------------------------------------------------------------------\r\n    while abs(x1 - x0) > tol and it < max_it:\r\n        f0 = fun(x0, *args)\r\n        f1 = fun(x1, *args)\r\n        root -= f1 * (root - x0) / (f1 - f0)\r\n\r\n        if root in (np.inf, np.nan):\r\n            raise ConvergenceError('division by zero')\r\n\r\n        x0 = x1\r\n        x1 = root\r\n        it += 1\r\n\r\n    return root\r\n\r\n\r\n# ======================================================================================================================\r\n# Least Squares Methods\r\n# ======================================================================================================================\r\ndef residual(f, x, y, p, args=()):\r\n    return y - f(x, *p, *args)\r\n\r\n\r\ndef lsq_obj(r):\r\n    return 0.5 * la.norm(r) ** 2.\r\n\r\n\r\ndef d_lsq_obj(r, j):\r\n    return j.T @ r\r\n\r\n\r\ndef jacobian_fd(x, p, f, args=()):\r\n    m = len(p)\r\n    j = [None for _ in range(0, m)]\r\n\r\n    eps = 1e-8\r\n    fx = f(x, *p, *args)\r\n\r\n    for i in range(0, m):\r\n        p_ = copy.deepcopy(list(p))\r\n        p_[i] += eps\r\n        j[i] = (f(x, *p_, *args) - fx) / eps\r\n\r\n    return np.asarray(j).T\r\n\r\n\r\ndef nl_lsq(fun, x, y, p0, jac=None, args=()):\r\n    # options ----------------------------------------------------------------------------------------------------------\r\n    max_it = 1000\r\n    max_it_bt = 100\r\n    tol = 1e-3\r\n    rho = 0.5\r\n    c = 1e-4\r\n\r\n    if jac is None:\r\n        jac = lambda xj, *pj: jacobian_fd(xj, pj, fun, args=args)\r\n\r\n    # initializing loop ------------------------------------------------------------------------------------------------\r\n    it = 0\r\n    converged = False\r\n    p = p0\r\n    res = residual(fun, x, y, p, args=args)\r\n    j = jac(x, *p, *args)\r\n    f = lsq_obj(res)\r\n    df = d_lsq_obj(res, j)\r\n\r\n    # iterating --------------------------------------------------------------------------------------------------------\r\n    while not converged and it < max_it:\r\n        # calculate optimized step\r\n        try:\r\n\r\n            q, r = la.qr(j)\r\n            dp = la.solve(r, q.T @ res)\r\n\r\n        except np.linalg.LinAlgError:\r\n            raise ConvergenceError('Unable to find a solution due to singular matrix issues')\r\n\r\n        # invoke backtracking\r\n        alpha = 1.\r\n        it_bt = 0\r\n\r\n        p_bt = p + dp\r\n        f_bt = lsq_obj(residual(fun, x, y, p_bt, args=args))\r\n        csdf = -c * np.dot(dp, df)\r\n\r\n        while f_bt >= (f + alpha * csdf) and it_bt < max_it_bt:\r\n            p_bt = p + alpha * dp\r\n            f_bt = lsq_obj(residual(fun, x, y, p_bt, args=args))\r\n\r\n            alpha *= rho\r\n            it_bt += 1\r\n\r\n        p = p_bt\r\n\r\n        # update parameters and check convergence\r\n        res = residual(fun, x, y, p, args=args)\r\n        f = lsq_obj(res)\r\n        j = jac(x, *p_bt, *args)\r\n        df = d_lsq_obj(res, j)\r\n\r\n        if la.norm(df, np.inf) < tol:\r\n            converged = True\r\n\r\n        it += 1\r\n\r\n    if it == max_it:\r\n        raise ConvergenceError('Solver failed to converge within maximum number of iterations')\r\n\r\n    return p\r\n\r\n\r\n# ======================================================================================================================\r\n# Linear Programming Methods\r\n# ======================================================================================================================\r\ndef lin_ip(A, g, b):\r\n    \"\"\"\r\n    TODO: NOT WORKING\r\n    # Algorithm 14.3, Page 411 Nocedal & Wright\r\n\r\n    Parameters\r\n    ----------\r\n    A : array_like\r\n        system matrix of the constraints\r\n    g : array_like\r\n        objective function multiplier\r\n    b : array_like\r\n        right-hand side of the constrains\r\n\r\n    Returns\r\n    -------\r\n    array_like\r\n        optimal solution vector\r\n    \"\"\"\r\n\r\n    converged = False\r\n    m, n = A.shape\r\n    max_iter = 10\r\n    iter_ = 0\r\n    eta = 0.99\r\n\r\n    # initial value correction heuristic -------------------------------------------------------------------------------\r\n    AA = A @ A.T\r\n    x_t = A.T @ la.solve(AA, b)\r\n    l_t = la.solve(AA, A @ g)\r\n    s_t = g - A.T @ l_t\r\n\r\n    dx = max(-1.5 * x_t.min(), 0.)\r\n    ds = max(-1.5 * s_t.min(), 0.)\r\n    x_h = x_t + dx\r\n    s_h = s_t + ds\r\n\r\n    xhsh = x_h.T @ s_h\r\n    dx_h = .5 * xhsh / (np.sum(s_h))\r\n    ds_h = .5 * xhsh / (np.sum(x_h))\r\n\r\n    x = x_h + dx_h\r\n    l = l_t\r\n    s = s_h + ds_h\r\n\r\n    # main loop --------------------------------------------------------------------------------------------------------\r\n    r_c = A.T @ l + s - g\r\n    r_b = A @ x - b\r\n    mu = (x.T @ s) / n\r\n\r\n    while (not converged) and (iter_ < max_iter):\r\n        iter_ = iter_ + 1\r\n\r\n        # KKT system\r\n        kkt = np.block([[np.zeros((n, n)), A.T, np.eye(n)],\r\n                        [A, np.zeros((m, m)), np.zeros((m, n))],\r\n                        [np.diag(s.flatten()), np.zeros((n, m)), np.diag(x.flatten())]])\r\n\r\n        rhs = np.vstack((-r_c, -r_b, -x * s))\r\n\r\n        # Solving for and extracting affine variables\r\n        # QR decompose KKT matrix, TODO: LDL decomposition instead\r\n        q, r = la.qr(kkt)\r\n        dv_aff = q @ la.solve(r.T, rhs)\r\n\r\n        dx_aff = dv_aff[:n]\r\n        ds_aff = dv_aff[(n + m):]\r\n\r\n        # Determining indices and corresponding alpha for affine variables\r\n        alpha_prim_aff = np.where(dx_aff < 0., -x / dx_aff, 1.).min()\r\n        alpha_dual_aff = np.where(ds_aff < 0., -s / ds_aff, 1.).min()\r\n\r\n        # Calculating affine mu, mu and sigma\r\n        mu_aff = ((x + alpha_prim_aff * dx_aff).T @ (s + alpha_dual_aff * ds_aff)) / n\r\n        sigma = (mu_aff / mu) ** 3. if mu > 1.e-10 else 0.\r\n\r\n        rhs = np.vstack((-r_c, -r_b, -x * s - dx_aff * ds_aff + sigma * mu))\r\n\r\n        # Solving for and extracting increments\r\n        dv = q @ la.solve(r.T, rhs)\r\n        dx = dv[:n]\r\n        dl = dv[n:(n + m)]\r\n        ds = dv[(n + m):]\r\n\r\n        # Determining indices and corresponding alpha for x and s\r\n        alpha_prim = np.where(dx < 0., eta * (-x / dx), 1.).min()\r\n        alpha_dual = np.where(ds < 0., eta * (-s / ds), 1.).min()\r\n\r\n        # updating x, l and s\r\n        x += alpha_prim * dx\r\n        l += alpha_dual * dl\r\n        s += alpha_dual * ds\r\n\r\n        print('X')\r\n        print(x)\r\n\r\n        # convergence check\r\n        r_c = A.T @ l + s - g\r\n        r_b = A @ x - b\r\n        mu = (x.T @ s) / n\r\n\r\n        converged = (la.norm(r_c, ord=np.inf) <= 1.e-9) and (la.norm(r_b, ord=np.inf) <= 1.e-9) and (abs(mu) <= 1.e-9)\r\n        print('CONVERGENCE')\r\n        print('rC', la.norm(r_c, ord=np.inf))\r\n        print('rA', la.norm(r_b, ord=np.inf))\r\n        print('mu', abs(mu))\r\n\r\n    return x\r\n\r\n\r\n# ======================================================================================================================\r\n# Quadratic Programming Methods\r\n# ======================================================================================================================\r\ndef nl_sqp(obj, con, x0, H0):\r\n    \"\"\"\r\n    Non-linear SQP solver for inequality constrained problems\r\n    TODO: Implement equality constraints\r\n    :param obj:\r\n    :param con:\r\n    :param x0:\r\n    :param H0:\r\n    :return:\r\n    \"\"\"\r\n    # Options ----------------------------------------------------------------------------------------------------------\r\n    tol = 1.0e-3\r\n    max_iter = 300\r\n    n = x0.shape[0]\r\n\r\n    # calculating objective function and constraint function using a numerical approximation for Jacobians\r\n    xeval = x0\r\n    f, df = obj(xeval)\r\n    c, dc = con(xeval)\r\n\r\n    m = c.size\r\n    mu = 100.\r\n\r\n    # assembling KKT system\r\n    A = np.zeros((n + m, 0))  # incorrect, assemble for equality constraints\r\n    b = np.zeros(0)  # incorrect, assemble for equality constraints\r\n    H = np.block([[np.zeros(H0.shape), np.zeros((H0.shape[0], m))], [np.zeros((m, H0.shape[1])),  np.eye(m) * 1e-6]])\r\n    g = np.block([np.zeros((df.shape[0], 1)), np.zeros((m, 1))])\r\n    y = np.zeros(0)\r\n\r\n    C = np.block([[np.zeros(dc.shape), np.zeros((m, m))], [np.zeros((m, n)), np.eye(m)]])\r\n    d = np.zeros(2 * m)\r\n    B = H0\r\n\r\n    z = np.abs(la.solve(dc, df))\r\n    s = np.ones(2 * m)\r\n    dLold = df - dc @ z\r\n\r\n    # Main loop iterations ---------------------------------------------------------------------------------------------\r\n    converged = (la.norm(dLold, ord=np.inf) < tol) and (la.norm(z * c, ord=np.inf) < tol)  # z * c element wise\r\n\r\n    rho = 0.5\r\n    iter = 0\r\n\r\n    while (not converged) and (iter < max_iter):\r\n        # Updating initial guess input for the PDPCIP algorithm\r\n        H[:n, :n] = B\r\n        g = np.block([df, mu * np.ones(m)])\r\n        # TODO: Missing the equality constrains here?\r\n        C[:m, :m] = dc\r\n        d[:m] = -c\r\n\r\n        zpad = np.block([z, np.ones(m)])\r\n        t = np.maximum(-(c + dc @ xeval), np.zeros(m))\r\n        xt = np.block([xeval, t])\r\n\r\n        # Sub problem: Solve constrained QP\r\n        p, y, z, _ = quad_ip(H, g, A, b, C, d, xt, y, s, zpad)\r\n\r\n        xeval = xt[:n]\r\n        z = z[:n]\r\n        p = p[:n]\r\n\r\n        # Take step\r\n        xeval += p\r\n\r\n        # Function evaluation\r\n        f, df = obj(xeval)\r\n        c, dc = con(xeval)\r\n        mu = (df.T @ p + 0.5 * p.T @ B @ p) / ((1. - rho) * la.norm(c, ord=1))\r\n\r\n        # Lagrangian gradient, z used for inequality constraints\r\n        dLnew = df - dc @ z\r\n\r\n        # BFGS Hessian update\r\n        q = dLnew - dLold\r\n        Bp = B @ p\r\n\r\n        if np.dot(p, q) >= 0.2 * np.dot(p, Bp):\r\n            theta = 1.\r\n        else:\r\n            theta = (0.8 * np.dot(p, Bp)) / (np.dot(p, Bp) - np.dot(p, q))\r\n\r\n        r = theta * q + (1. - theta) * Bp\r\n        r = r.reshape((r.shape[0], 1))\r\n        Bp = Bp.reshape((Bp.shape[0], 1))\r\n        B += r @ r.T / np.dot(p, r) - Bp @ Bp.T / np.dot(p, Bp)\r\n\r\n        dLold = dLnew\r\n        iter += 1\r\n        converged = (la.norm(dLold, np.inf) < tol) and (la.norm(z * c, np.inf) < tol)  # z * c piecewise\r\n\r\n    info = converged\r\n    zopt = z[:2]\r\n    xopt = xeval\r\n    return xopt, zopt, info\r\n\r\n\r\ndef quad_ip(H, g, A, b, C, d, x0, y0, s0, z0):\r\n    \"\"\"\r\n    Primal Dual Predictor Corrector Interior Point Algorithm.\r\n    :param H: \r\n    :param g: \r\n    :param A: \r\n    :param b: \r\n    :param C: \r\n    :param d:\r\n    :param x0:\r\n    :param y0:\r\n    :param s0:\r\n    :param z0:\r\n    :return: \r\n    \"\"\"\r\n    # Options ----------------------------------------------------------------------------------------------------------\r\n    epsilon = 1e-3\r\n    max_iter = 100\r\n\r\n    # Heuristic for initial point --------------------------------------------------------------------------------------\r\n    mc = z0.size\r\n    KKT0 = np.zeros((A.shape[1], A.shape[1]))\r\n\r\n    rL = H @ x0 + g - A @ y0 - C @ z0\r\n    rA = b - A.T @ x0\r\n    rC = s0 + d - C.T @ x0\r\n    rsz = s0 * z0  # element-wise\r\n\r\n    # assemble KKT matrix\r\n    H0 = H + (C @ np.diag((z0 / s0)) @ C.T)  # z0 / s0 element wise\r\n    KKT = np.block([[H0, -A], [-A.T, KKT0]])\r\n\r\n    # assemble RHS of KKT system\r\n    rL0 = rL - C @ np.diag((z0 / s0)) @ (rC - rsz / z0)  # z0 / s0 and rsz. / z0 elementwise\r\n    RHS = -np.block([rL0, rA])\r\n\r\n    # QR decompose KKT matrix, TODO: LDL decomposition instead\r\n    Q, R = la.qr(KKT)\r\n    affvec = Q @ la.solve(R.T, RHS)\r\n\r\n    xaff = affvec[:x0.shape[0]].T\r\n    zaff = -np.diag((z0 / s0)) @ C.T @ xaff + np.diag((z0 / s0)) @ (rC - rsz / z0)  # z0 / s0 and rsz / z0 element wise\r\n    saff = -rsz / z0 - np.diag((s0 / z0)) @ zaff  # rsz / z0 and s0 / z0 element wise element wise\r\n\r\n    x = x0\r\n    y = y0\r\n    z = np.maximum(np.ones(z0.shape), abs(z0 + zaff))\r\n    s = np.maximum(np.ones(s0.shape), abs(s0 + saff))\r\n    mu0 = np.dot(z, s) / mc\r\n    zdivs = z / s  # element wise\r\n\r\n    # Iterations -------------------------------------------------------------------------------------------------------\r\n    rL = H @ x + g - A @ y - C @ z\r\n    rA = b - A.T @ x\r\n    rC = s + d - C.T @ x\r\n    rsz = s * z  # element wise\r\n    mu = mu0\r\n\r\n    iter = 0\r\n    converged = convergence_check(rL, rA, rC, mu0, mu0, H, g, A, b, C, d, epsilon)\r\n\r\n    while (not converged) and (iter < max_iter):\r\n        # assemble KKT matrix\r\n        Hbar = H + (C @ np.diag(zdivs) @ C.T)\r\n        KKT = np.block([[Hbar, -A], [-A.T, KKT0]])\r\n\r\n        # assemble RHS of KKT system\r\n        rLbar = rL - C @ np.diag(zdivs) @ (rC - rsz / z)  # rsz / z element wise\r\n        RHS = np.block([-rLbar, -rA])\r\n\r\n        # QR decompose KKT matrix, TODO: LDL decomposition instead\r\n        # [L, D, p] = ldl(KKT, 'lower', 'vector')\r\n        # affvec = zeros(1, numel(RHS))\r\n        # affvec(p) = L'\\(D\\(L\\RHS(p)))\r\n        Q, R = la.qr(KKT)  # may need method='complete\r\n        affvec = Q @ la.solve(R.T, RHS)\r\n\r\n        xaff = affvec[:x.shape[0]].T\r\n        zaff = - np.diag(zdivs) @ C.T @ xaff + np.diag(zdivs) @ (rC - rsz / z)  # rsz / z element wise\r\n        saff = -(rsz / z) - np.diag(s / z) @ zaff  # rsz / z and s / z element wise\r\n\r\n        alphaaff1 = np.where(zaff < 0., -z / zaff, 1.).min()  # z / zaff element wise\r\n        alphaaff2 = np.where(saff < 0., -s / saff, 1.).min()  # s / saff element wise\r\n        alphaaff = np.minimum(alphaaff1, alphaaff2)\r\n\r\n        muaff = np.dot((z + alphaaff * zaff), (s + alphaaff * saff)) / mc\r\n        sigma = (muaff / mu) ** 3.\r\n\r\n        # assembling updated RHS of KKT system\r\n        rszbar = rsz + saff * zaff - sigma * mu  # saff * zaff element wise\r\n        rLbar = rL - C @ np.diag(zdivs) @ (rC - rszbar / z)  # rszbar / z element wise\r\n        RHS = np.block([-rLbar, -rA])\r\n\r\n        # TODO: LDL decomposition\r\n        # vec = np.zeros(numel(RHS), 1)\r\n        # vec(p) = L'\\(D\\(L\\RHS(p)))\r\n        vec = Q @ la.solve(R.T, RHS)\r\n\r\n        # calculate step size\r\n        dx = vec[:x.shape[0]]\r\n        dy = vec[x.shape[0] + 1:]\r\n        dz = -np.diag(zdivs) @ C.T  @ dx + np.diag(zdivs) @ (rC-rszbar / z)  # rszbar / z element wise\r\n        ds = -rszbar / z - np.diag(s / z) @ dz  # rszbar / z and s / z element wise\r\n\r\n        alpha1 = np.where(dz < 0., -z / dz, 1.).min()  # z / dz element wise\r\n        alpha2 = np.where(ds < 0., -s / ds, 1.).min()  # s / ds element wise\r\n        alpha = np.minimum(alpha1, alpha2)\r\n\r\n        # updating estimator with calculated step-size\r\n        alphabar = 0.995 * alpha\r\n        x = x + dx * alphabar\r\n        y = y + dy * alphabar\r\n        z = z + dz * alphabar\r\n        s = s + ds * alphabar\r\n\r\n        rL = H @ x + g - A @ y - C @ z\r\n        rA = b - A.T @ x\r\n        rC = s + d - C.T @ x\r\n        rsz = s * z  # element wise\r\n        mu = np.dot(z, s) / mc\r\n        zdivs = z / s  # element wise\r\n        converged = convergence_check(rL, rA, rC, mu, mu0, H, g, A, b, C, d, epsilon)\r\n        iter += 1\r\n\r\n    if converged:\r\n        xopt = x\r\n        yopt = y\r\n        zopt = z\r\n        sopt = s\r\n    else:\r\n        xopt = []\r\n        yopt = []\r\n        zopt = []\r\n        sopt = []\r\n\r\n    return xopt, yopt, zopt, sopt\r\n\r\n\r\ndef convergence_check(rL, rA, rC, mu, mu0, H, g, A, b, C, d, tol):\r\n    conv = False\r\n    rAcheck = True\r\n    rCcheck = True\r\n\r\n    # KKT system\r\n    kkt = np.block([H, g.reshape((g.shape[0], 1)), A, C])\r\n    rLcheck = la.norm(rL, ord=np.inf) <= tol * np.maximum(1., la.norm(kkt, ord=np.inf))\r\n\r\n    # equality constraints\r\n    eq = np.block([A.T, b.reshape((b.shape[0], 1))])\r\n    if eq.size:\r\n        rAcheck = la.norm(rA, ord=np.inf) <= tol * np.maximum(1., la.norm(eq, ord=np.inf))\r\n\r\n    # inequality constraints\r\n    ineq = np.block([np.eye(d.size), d.reshape((d.shape[0], 1)), C.T])\r\n    if ineq.size:\r\n        rCcheck = la.norm(rC, ord=np.inf) <= tol * np.maximum(1., la.norm(ineq, ord=np.inf))\r\n\r\n    muCheck = np.abs(mu) <= tol * 1e-2 * mu0\r\n\r\n    if rLcheck and rAcheck and rCcheck and muCheck:\r\n        conv = True\r\n\r\n    return conv\r\n\r\n\r\n# QUADRATIC TEST SCRIPT ------------------------------------------------------------------------------------------------\r\n#def func(x, a, b, c):\r\n#    return a * np.exp(-b * x) + c\r\n\r\n\r\n#def func_jac(x, a, b, c):\r\n#    return np.array([np.exp(-b * x), -a * x * np.exp(-b * x), np.repeat(1., x.size)]).T\r\n\r\n#xdata = np.linspace(0, 4, 50)\r\n#y = func(xdata, 2.5, 1.3, 0.5)\r\n#np.random.seed(1729)\r\n#y_noise = 0.2 * np.random.normal(size=xdata.size)\r\n#ydata = y + y_noise\r\n#p = nl_lsq(func, xdata, ydata, p0=np.asarray([1., 1., 1.]), jac=func_jac)\r\n\r\n\r\n# LINEAR TEST SCRIPT ---------------------------------------------------------------------------------------------------\r\n# n = 2                     # Number of variables and constraints (2 for contour plot)\r\n# A = np.random.rand(n, n)  # Generating A\r\n# k = 2                     # Index to put in zeros\r\n#\r\n# xp = abs(np.random.rand(n, 1))\r\n# xp[k:] = np.zeros((xp.size-k, 1))\r\n# sp = abs(np.random.rand(n, 1))\r\n# sp[:k-1] = np.zeros((sp.size-k + 1, 1))\r\n#\r\n# lp = np.random.rand(n, 1)   # Generating lambda\r\n#\r\n# g = A.T @ lp + sp      # Computing g\r\n# b = A @ xp             # Computing b\r\n\r\n# problem from: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html\r\n# A = np.zeros((2, 2))\r\n# A[0, :] = np.array([-3., 1.])\r\n# A[1, :] = np.array([1., 2.])\r\n#\r\n#\r\n# b = np.zeros((2, 1))\r\n# b[0, 0] = 6.\r\n# b[1, 0] = 4.\r\n#\r\n# g = np.zeros((2, 1))\r\n# g[0, 0] = -1.\r\n# g[1, 0] = 4.\r\n#\r\n# # Solving problem using Linear Programming Predictor-Correction IP algorithm\r\n# x_opt = lin_ip(A, g, b)\r\n# #print(x_opt)\r\n# obj = g.T @ x_opt\r\n# #print(obj)\r\n# print('OPTIMUM')\r\n# print(x_opt, obj)\r\n#\r\n# c = [-1, 4]\r\n# A = [[-3, 1], [1, 2]]\r\n# b = [6, 4]\r\n# #x0_bounds = (None, None)\r\n# #x1_bounds = (-3, None)\r\n# res = linprog(c, A_ub=A, b_ub=b)#, bounds=[x0_bounds, x1_bounds])\r\n# print(res)", "meta": {"hexsha": "dfbf34ae16b939c422ec9d972a99475bb7502e0a", "size": 18363, "ext": "py", "lang": "Python", "max_stars_repo_path": "alveus/optimize.py", "max_stars_repo_name": "FrederikLehn/alveus", "max_stars_repo_head_hexsha": "71a858d0cdd8a4bbd06a28eb35fa7a8a7bd4814b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "alveus/optimize.py", "max_issues_repo_name": "FrederikLehn/alveus", "max_issues_repo_head_hexsha": "71a858d0cdd8a4bbd06a28eb35fa7a8a7bd4814b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "alveus/optimize.py", "max_forks_repo_name": "FrederikLehn/alveus", "max_forks_repo_head_hexsha": "71a858d0cdd8a4bbd06a28eb35fa7a8a7bd4814b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2157894737, "max_line_length": 121, "alphanum_fraction": 0.4279801775, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.8962513689768735, "lm_q1q2_score": 0.8543740584633976}}
{"text": "# --------------\n#Importing header files\r\nimport pandas as pd\r\nimport scipy.stats as stats\r\nimport math\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom statsmodels.stats.weightstats import ztest\r\nfrom statsmodels.stats.weightstats import ztest\r\nfrom scipy.stats import chi2_contingency\r\n\r\nimport warnings\r\n\r\nwarnings.filterwarnings('ignore')\r\n#Sample_Size\r\nsample_size=2000\r\n\r\n#Z_Critical Score\r\nz_critical = stats.norm.ppf(q = 0.95)  \r\nprint('z_critical:', z_critical)\r\n# Critical Value\r\ncritical_value = stats.chi2.ppf(q = 0.95, # Find the critical value for 95% confidence*\r\n                      df = 6)   # Df = number of variable categories(in purpose) - 1\r\nprint('critical_value', critical_value)\r\n\r\n#Reading file\r\ndata=pd.read_csv(path)\r\ndata_sample=data.sample(n=2000, random_state=0)\r\nsample_mean=data_sample.installment.mean()\r\nprint('sample mean:', sample_mean)\r\n\r\nsample_std=data_sample.installment.std()\r\nprint('sample_std:', sample_std)\r\n\r\nmargin_of_error = z_critical * (sample_std/math.sqrt(sample_size))\r\nprint(\"Margin of error:\",margin_of_error)\r\n\r\nconfidence_interval = (sample_mean - margin_of_error, sample_mean + margin_of_error)\r\nprint(\"confidence interval:\", confidence_interval)\r\n\r\ntrue_mean = data.installment.mean()\r\nprint(\"True mean of data:\", true_mean)\r\n\r\n# CLT\r\nsample_size = np.array([20,50,100])\r\nfig, axes = plt.subplots(3,1, figsize=(10,20))\r\n\r\nfor i in range(len(sample_size)):\r\n    m = []\r\n    for j in range(1000):\r\n        mean = data['installment'].sample(sample_size[i]).mean()\r\n        m.append(mean)    \r\n    mean_series = pd.Series(m)\r\n    axes[i].hist(mean_series)\r\nplt.show()\r\n\r\ndata['int.rate'] = data['int.rate'].map(lambda x: str(x)[:-1])\r\ndata['int.rate'] = data['int.rate'].astype(float)/100\r\n\r\nz_statistic_1, p_value_1 = ztest(x1 = data[data['purpose'] == 'small_business']['int.rate'], value = data['int.rate'].mean(), alternative = 'larger')\r\n\r\nprint(\"z-statistic is:\", z_statistic_1)\r\nprint(\"p-value is:\", p_value_1)\r\n\r\nz_statistic_2, p_value_2 = ztest(x1 = data[data['paid.back.loan'] == 'No']['installment'], x2 = data[data['paid.back.loan'] == 'Yes']['installment'])\r\n\r\nprint(\"z-statistic 2 is:\", z_statistic_2)\r\nprint(\"p-value 2 is:\", p_value_2)\r\n\r\nyes = data[data['paid.back.loan'] == 'Yes']['purpose'].value_counts()\r\nno = data[data['paid.back.loan'] == 'No']['purpose'].value_counts()\r\nprint(yes)\r\nprint(no)\r\nobserved = pd.concat([yes.transpose(), no.transpose()], 1,keys=['Yes','No'])\r\nprint(observed)\r\n\r\nchi2, p, dof, ex = chi2_contingency(observed)\r\n\r\nprint(\"Critical value is:\", critical_value)\r\n\r\nprint(\"chi statistic is:\", chi2)\r\n\r\n\r\n\r\n#Code starts here\r\n\r\n\n\n\n", "meta": {"hexsha": "e8f7b954fc8481a93afe9ce7dcdca3c5c8bfdca4", "size": 2640, "ext": "py", "lang": "Python", "max_stars_repo_path": "Banking-Inferences/code.py", "max_stars_repo_name": "Mrinmoyee89/ga-learner-dscp-repo", "max_stars_repo_head_hexsha": "1d9ab7d217a214766b7c6adf48d652a9aef28564", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Banking-Inferences/code.py", "max_issues_repo_name": "Mrinmoyee89/ga-learner-dscp-repo", "max_issues_repo_head_hexsha": "1d9ab7d217a214766b7c6adf48d652a9aef28564", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Banking-Inferences/code.py", "max_forks_repo_name": "Mrinmoyee89/ga-learner-dscp-repo", "max_forks_repo_head_hexsha": "1d9ab7d217a214766b7c6adf48d652a9aef28564", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3333333333, "max_line_length": 150, "alphanum_fraction": 0.6863636364, "include": true, "reason": "import numpy,import scipy,from scipy,from statsmodels", "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446479186301, "lm_q2_score": 0.8774767970940975, "lm_q1q2_score": 0.8543505871634499}}
{"text": "\"\"\"\nProblem 12\nThe sequence of triangle numbers is generated by adding the natural numbers.\nSo the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.\n\nThe first ten terms would be:\n1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...\n\nLet us list the factors of the first seven triangle numbers:\n\n     1: 1\n     3: 1,3\n     6: 1,2,3,6\n    10: 1,2,5,10\n    15: 1,3,5,15\n    21: 1,3,7,21\n    28: 1,2,4,7,14,28\nWe can see that 28 is the first triangle number to have over five divisors.\n\nWhat is the value of the first triangle number to have over five hundred divisors?\n\"\"\"\nimport numpy as np\n\n\ndef generate_triangle_numbers(n):\n    # triangular numbers can be calculated with dynamic formula below\n    # instead of summing all numbers from 1 till n...\n    return int(n * (n + 1) / 2)\n\n\ndef number_of_divisors(n):\n    factors = set()\n\n    # a factor will always be a pair.\n    # the lesser of the pairs can never be greater than sqrt(n)\n    for i in range(1, int(np.sqrt(n) + 1)):\n        if n % i == 0:  # finds the \"lesser\" factors\n            factors.update([i])  # saves \"lesser\"\n            factors.update([n // i])  # saves floor division of \"lesser\" - complement in the 'pair'\n    return len(factors)\n\n\nj = 1\n\nwhile number_of_divisors(generate_triangle_numbers(j)) < 500:\n    j += 1\n\nprint('winner winnner: {0}'.format(generate_triangle_numbers(j)))\n", "meta": {"hexsha": "110b4952935e97e1cead364810217bdff39d4789", "size": 1353, "ext": "py", "lang": "Python", "max_stars_repo_path": "Solutions/Problem 12 - Highly divisible triangular number.py", "max_stars_repo_name": "ismand95/ProjectEuler", "max_stars_repo_head_hexsha": "a03c30af13ec331140374258db805196dc96fef3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Solutions/Problem 12 - Highly divisible triangular number.py", "max_issues_repo_name": "ismand95/ProjectEuler", "max_issues_repo_head_hexsha": "a03c30af13ec331140374258db805196dc96fef3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/Problem 12 - Highly divisible triangular number.py", "max_forks_repo_name": "ismand95/ProjectEuler", "max_forks_repo_head_hexsha": "a03c30af13ec331140374258db805196dc96fef3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.612244898, "max_line_length": 99, "alphanum_fraction": 0.6459719143, "include": true, "reason": "import numpy", "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446502128796, "lm_q2_score": 0.877476793890012, "lm_q1q2_score": 0.8543505860569598}}
{"text": "# Importing the libraries\nimport pandas as pd\nimport statistics \n\n#import scipy as statistics \n\ndata1 = [1, 2, 3, 4, 4, 5, 7, 9] \n\ndata1_mean = statistics.mean(data1) \n\n\nprint(\"Mean is :\", data1_mean) \nprint(\"Mean is : %.2f\" % (data1_mean))\nprint(\"Mean is : %.3f\" % (data1_mean))\nprint(\"Mean is : %.4f\" % (data1_mean))\nprint(\"Mean is : %.5f\" % (data1_mean))\nprint(\"Mean is : %.6f\" % (data1_mean))\n \ndata1_median = statistics.median(data1) \nprint(\"Median is :\", data1_mean) \ndata1_mode = statistics.mode(data1) \nprint(\"Mode is :\", data1_mode) \ndata1_stdev = statistics.stdev(data1) \nprint(\"Stdev is :\", data1_stdev) \ndata1_variance = statistics.variance(data1) \nprint(\"Variance is :\", data1_variance) \n\n\n\n# Importing the Salary .csv data set\nsalaryDS = pd.read_csv('Dummy_Salary_Data.csv')\nprint (salaryDS)\n\nexp = salaryDS.iloc[:, 0].values\nsalary = salaryDS.iloc[:, 1].values\n\nprint (\"exp: \", exp)\n\nexp_mean = statistics.mean(exp)\nexp_median = statistics.median(exp)\nexp_mode = statistics.mode(exp)\nexp_stdv = statistics.stdev(exp)\nexp_variance = statistics.variance(exp)\n\nprint (\"exp_mean: \", exp_mean)\nprint (\"exp_median: \", exp_median)\nprint (\"exp_mode: \", exp_mode)\nprint (\"exp_stdv: \", exp_stdv)\nprint (\"exp_variance: \", exp_variance)\n\n\nprint (\"salary: \", salary)\n\nsalary_mean = statistics.mean(salary)\nsalary_median = statistics.median(salary)\nsalary_mode = statistics.mode(salary)\nsalary_stdv = statistics.stdev(salary)\nsalary_variance = statistics.variance(salary)\n\nprint (\"salary_mean: \", salary_mean)\nprint (\"salary_median: \", salary_median)\nprint (\"salary_mode: \", salary_mode)\nprint (\"salary_stdv: \", salary_stdv)\nprint (\"salary_variance: \", salary_variance)\n\n\n\n# Importing the Titanic .csv data file\ntitanicDS = pd.read_csv('Dummy_Titanic_Data.csv')\nprint (titanicDS)\n\nage = titanicDS.iloc[:, 4].values\n\nticket_fare = gender = titanicDS.iloc[:, 7].values\n\nprint (\"age: \", age)\n\nage_mean = statistics.mean(age)\nage_median = statistics.median(age)\nage_mode = statistics.mode(age)\nage_stdv = statistics.stdev(age)\nage_variance = statistics.variance(age)\n\nprint (\"age_mean: \", age_mean)\nprint (\"age_median: \", age_median)\nprint (\"age_mode: \", age_mode)\nprint (\"age_stdv: \", age_stdv)\nprint (\"age_variance: \", age_variance)\n\nprint (\"ticket_fare: \", ticket_fare)\n\nticket_fare_mean = statistics.mean(ticket_fare)\nticket_fare_median = statistics.median(ticket_fare)\nticket_fare_mode = statistics.mode(ticket_fare)\nticket_fare_stdv = statistics.stdev(ticket_fare)\nticket_fare_variance = statistics.variance(ticket_fare)\n\nprint (\"ticket_fare_mean: \", ticket_fare_mean)\nprint (\"ticket_fare_median: \", ticket_fare_median)\nprint (\"ticket_fare_mode: \", ticket_fare_mode)\nprint (\"ticket_fare_stdv: \", ticket_fare_stdv)\nprint (\"ticket_fare_variance: \", ticket_fare_variance)\n", "meta": {"hexsha": "fafb4fa60d10fcb60a9e74fabaacfd4b54918ef6", "size": 2772, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data Analysis/Some Basic and Useful Statistical Calculations with Python Anaconda Spyder.py", "max_stars_repo_name": "csitedexperts/DataScienceA2Z", "max_stars_repo_head_hexsha": "9178c73be8adb6d6b5c142b0f2aa99471e5ca79b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-04-13T04:00:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-02T01:14:42.000Z", "max_issues_repo_path": "Data Analysis/Some Basic and Useful Statistical Calculations with Python Anaconda Spyder.py", "max_issues_repo_name": "csitedexperts/DSML_MadeEasy", "max_issues_repo_head_hexsha": "9af03a00fb026930c19737790f603a0b0ae40b7e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Analysis/Some Basic and Useful Statistical Calculations with Python Anaconda Spyder.py", "max_forks_repo_name": "csitedexperts/DSML_MadeEasy", "max_forks_repo_head_hexsha": "9af03a00fb026930c19737790f603a0b0ae40b7e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-03-30T18:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T16:30:34.000Z", "avg_line_length": 26.9126213592, "max_line_length": 55, "alphanum_fraction": 0.7417027417, "include": true, "reason": "import scipy", "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446502128796, "lm_q2_score": 0.8774767890838836, "lm_q1q2_score": 0.8543505813774985}}
{"text": "import scipy.stats\nimport numpy as np\n\n\ndef one_way_anova(*args):\n    \"\"\"One-way ANOVA to check if all groups have the same pop. mean.\n\n    ANOVA stands for `Analysis of Variance`.\n\n    Assumptions:\n        i.i.d. x_{(1, 1)}, ..., x_{(1, m)} ~ N(mu_1, sigma^{2})\n        i.i.d. x_{(2, 1)}, ..., x_{(2, m)} ~ N(mu_2, sigma^{2})\n        ...\n        i.i.d. x_{(n, 1)}, ..., x_{(n, m)} ~ N(mu_n, sigma^{2})\n\n        Note 1: all groups (1 to n) has the same number of samples `m`.\n        Note 2: all groups (1 to n) has the same pop. variance sigma^{2}.\n\n    Test statistic: w = msb / msw\n    where:\n        msb = m * var(group_means);\n        msw = mean(group_vars).\n\n    Null distribution: W ~ F(n - 1, n * (m - 1)), where F is the F-distribution,\n    `n` is the number of groups and `m` is the number of samples per group.\n\n    H0: mu_1 = mu_2 = ... = mu_n\n    HA: Exists at least a pair (i, j), 1 <= i, j <= n, such that mu_i != mu_j.\n    \"\"\"\n    assert len(set(map(len, args))) == 1\n\n    num_groups, num_inst_per_group = len(args), len(args[0])\n\n    group_means = list(map(np.mean, args))\n    group_vars = list(map(lambda arr: np.var(arr, ddof=1), args))\n\n    msb = num_inst_per_group * np.var(group_means, ddof=1)\n    msw = np.mean(group_vars)\n\n    null_dist = scipy.stats.f(num_groups - 1, num_groups * (num_inst_per_group - 1))\n\n    test_statistic = msb / msw\n    p_value = null_dist.sf(test_statistic)\n\n    return test_statistic, p_value\n\n\ndef f_test_for_equal_means(*args):\n    \"\"\"Also known as One-way ANOVA.\"\"\"\n    return one_way_anova(*args)\n\n\ndef _test():\n    for n_groups in (2, 5, 10, 20):\n        samples = [np.random.randn(50) for _ in range(n_groups)]\n        res = one_way_anova(*samples)\n        print(res)\n        assert np.allclose(res, scipy.stats.f_oneway(*samples))\n\n        samples[1] += 3 * np.random.random() - 1.5\n        res = one_way_anova(*samples)\n        print(res)\n        assert np.allclose(res, scipy.stats.f_oneway(*samples))\n\n\nif __name__ == \"__main__\":\n    _test()\n", "meta": {"hexsha": "328e0415d4099a1964263d7cb2d2179d019deb7f", "size": 2002, "ext": "py", "lang": "Python", "max_stars_repo_path": "statistical_tests/one_way_anova.py", "max_stars_repo_name": "FelSiq/statistics-related", "max_stars_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-13T02:09:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-13T02:09:08.000Z", "max_issues_repo_path": "statistical_tests/one_way_anova.py", "max_issues_repo_name": "FelSiq/statistics-related", "max_issues_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "statistical_tests/one_way_anova.py", "max_forks_repo_name": "FelSiq/statistics-related", "max_forks_repo_head_hexsha": "ee050202717fc368a3793b195dea03687026eb1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4411764706, "max_line_length": 84, "alphanum_fraction": 0.5934065934, "include": true, "reason": "import numpy,import scipy", "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97364464791863, "lm_q2_score": 0.8774767874818408, "lm_q1q2_score": 0.8543505778045274}}
{"text": "from typing import Tuple\n\nimport numpy as np\n\nfrom utils.common_types import *\n\n\ndef wedge_mask(img_dim: Tuple[int, int], wedge_width_ratio: float = 0.2) -> NumpyArray:\n    \n    \n    img_dimy, img_dimx = img_dim\n    \n    xx, yy = np.meshgrid(range(img_dimx), range(img_dimy))\n\n    xx = xx / img_dimx\n    yy = yy / img_dimy\n\n    xx = xx - 1/2\n    yy = yy - 1/2\n\n    mask = np.logical_or(\n        np.abs(xx) < wedge_width_ratio/2, np.abs(yy) < wedge_width_ratio/2\n    )\n\n    return mask[None, :, :]\n\ndef circle_mask(img_dim: Tuple[int, int], diameter_ratio: float = 0.5) -> NumpyArray:\n    \n    \n    img_dimy, img_dimx = img_dim\n    \n    xx, yy = np.meshgrid(range(img_dimx), range(img_dimy))\n\n    xx = xx / img_dimx\n    yy = yy / img_dimy\n\n    xx = xx - 1/2\n    yy = yy - 1/2\n\n    mask = xx**2 + yy**2 < (diameter_ratio/2) ** 2\n\n    return mask[None, :, :]\n\ndef circular_strip_mask(\n    img_dim: Tuple[int, int], \n    outer_diameter_ratio: float = 0.2, inner_diameter_ratio: float = 0.1\n) -> NumpyArray:\n\n    \n    outer_circle = circle_mask(img_dim, diameter_ratio=outer_diameter_ratio)\n    inner_circle = circle_mask(img_dim, diameter_ratio=inner_diameter_ratio)\n    \n    strip = np.logical_xor(outer_circle, inner_circle)\n\n    return strip\n\ndef rectangle_mask(\n    img_dim: Tuple[int, int], height_ratio: float = 0.3, width_ratio: float = 0.7\n) -> NumpyArray:\n    \n    \n    img_dimx, img_dimy = img_dim\n    \n    xx, yy = np.meshgrid(range(img_dimx), range(img_dimy))\n\n    xx = xx / img_dimx\n    yy = yy / img_dimy\n\n    xx = xx - 1/2\n    yy = yy - 1/2\n\n    mask = np.logical_and(\n        np.abs(xx) < width_ratio/2, np.abs(yy) < height_ratio/2\n    )\n\n    return mask[None, :, :]\n\ndef square_mask(img_dim: Tuple[int, int], width_ratio: float = 0.5) -> NumpyArray:\n    return rectangle_mask(img_dim, width_ratio, width_ratio)\n\n\ndef apply_mask(arr: NumpyArray, mask: NumpyArray) -> NumpyArray:\n    \n    \n    channels = arr.shape[-3]\n    \n    if channels != 1:\n        mask = np.concatenate([mask] * channels, axis=0)\n    \n    if len(arr.shape) == 3:\n        return arr[mask]\n\n    if len(arr.shape) == 4:\n        return arr[:, mask]\n    \n    assert False\n    \n    \n    \n    \n    \n    ", "meta": {"hexsha": "38de67c025edb75d3c41830e44959542ad5229e1", "size": 2180, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/masks.py", "max_stars_repo_name": "ozgurkara99/ISNAS-DIP", "max_stars_repo_head_hexsha": "bfe3c41459f8803de552a2549266074b84fe1e17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2022-03-28T19:00:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T19:30:52.000Z", "max_issues_repo_path": "utils/masks.py", "max_issues_repo_name": "ozgurkara99/ISNAS-DIP", "max_issues_repo_head_hexsha": "bfe3c41459f8803de552a2549266074b84fe1e17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/masks.py", "max_forks_repo_name": "ozgurkara99/ISNAS-DIP", "max_forks_repo_head_hexsha": "bfe3c41459f8803de552a2549266074b84fe1e17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3725490196, "max_line_length": 87, "alphanum_fraction": 0.6105504587, "include": true, "reason": "import numpy", "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446463891304, "lm_q2_score": 0.8774767826757122, "lm_q1q2_score": 0.8543505717829656}}
{"text": "import numpy as np\n\nclass PCA:\n    def __init__(self, threshold: float, n_components: int=None):\n        if threshold == None:\n            self.mode = 'number'\n            self.n_components = n_components\n        else:\n            self.mode = 'threshold'    \n            self.threshold = threshold\n        \n    def fit(self, X: np.array):\n        n_samples, n_dimensions = X.shape\n        self.mean_vector = X.mean(0)\n        self.A = X - self.mean_vector\n        Sigma = np.cov(self.A, rowvar=False)\n        eigen_values, eigen_vectors = np.linalg.eig(Sigma)\n        indices = np.argsort(eigen_values)[::-1]\n        eigen_values = eigen_values[indices]\n        eigen_vectors = eigen_vectors[:, indices]\n        \n        explained_variance_ratio = eigen_values / eigen_values.sum()\n        if self.mode == 'threshold':\n            cumulative_expl_var = np.cumsum(explained_variance_ratio)\n            self.n_components = np.where(cumulative_expl_var > self.threshold)[0][0]\n        self.explained_variance_ratio = explained_variance_ratio[:self.n_components]\n        self.eigen_values = eigen_values[:self.n_components]\n        self.eigen_vectors = eigen_vectors[:, :self.n_components]\n        \n    def transform(self) -> np.array:\n        return self.A @ self.eigen_vectors\n    \n    def fit_transform(self, X: np.array) -> np.array:\n        self.fit(X)\n        return self.transform()\n    \n    def reconstruct(self, X_hat) -> np.array:\n        return (X_hat @ self.eigen_vectors.T) + self.mean_vector\n", "meta": {"hexsha": "1f2150567486fc801bad635d9c4589817c4ac7f4", "size": 1502, "ext": "py", "lang": "Python", "max_stars_repo_path": "unsupervised-learning/dimensionality_reduction.py", "max_stars_repo_name": "booleangabs/Machine-Learning-With-Numpy", "max_stars_repo_head_hexsha": "6a493c67979290e0a1d03cc8fb97f78448bd2156", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unsupervised-learning/dimensionality_reduction.py", "max_issues_repo_name": "booleangabs/Machine-Learning-With-Numpy", "max_issues_repo_head_hexsha": "6a493c67979290e0a1d03cc8fb97f78448bd2156", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unsupervised-learning/dimensionality_reduction.py", "max_forks_repo_name": "booleangabs/Machine-Learning-With-Numpy", "max_forks_repo_head_hexsha": "6a493c67979290e0a1d03cc8fb97f78448bd2156", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5128205128, "max_line_length": 84, "alphanum_fraction": 0.6264980027, "include": true, "reason": "import numpy", "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9793540686581883, "lm_q2_score": 0.8723473730188542, "lm_q1q2_score": 0.8543369490492971}}
{"text": "from __future__ import print_function\nfrom scipy.spatial.distance import cdist\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed(11)\n\nmeans = [[2, 2], [8, 3], [3, 6]]\ncov = [[1, 0], [0, 1]]\nN = 500\n\nX0 = np.random.multivariate_normal(means[0], cov, N)\nX1 = np.random.multivariate_normal(means[1], cov, N)\nX2 = np.random.multivariate_normal(means[2], cov, N)\n\nX = np.concatenate((X0, X1, X2), axis = 0)\nK = 3\n\noriginal_label = np.asarray([0]*N + [1]*N + [2]*N).T\n\ndef kmeans_display(X, label):\n    K = np.amax(label) + 1\n    X0 = X[label == 0, :]\n    X1 = X[label == 1, :]\n    X2 = X[label == 2, :]\n\n    plt.plot(X0[:, 0], X0[:, 1], 'b^', markersize = 4, alpha = .8)\n    plt.plot(X1[:, 0], X1[:, 1], 'go', markersize = 4, alpha = .8)\n    plt.plot(X2[:, 0], X2[:, 1], 'rs', markersize = 4, alpha = .8)\n\n    plt.axis('equal')\n    plt.plot()\n    plt.show()\n\nkmeans_display(X, original_label)\n\ndef kmeans_init_centers(X, k):\n    # randomly pick k rows of X as initial centers\n    return X[np.random.choice(X.shape[0], k, replace=False)]\n\ndef kmeans_assign_labels(X, centers):\n    # calculate pairwise distances btw data and centers\n    D = cdist(X, centers)\n    # return index of the closest center\n    return np.argmin(D, axis = 1)\n\ndef kmeans_update_centers(X, labels, K):\n    centers = np.zeros((K, X.shape[1]))\n    for k in range(K):\n        # collect all points assigned to the k-th cluster\n        Xk = X[labels == k, :]\n        # take average\n        centers[k,:] = np.mean(Xk, axis = 0)\n    return centers\n\ndef has_converged(centers, new_centers):\n    # return True if two sets of centers are the same\n    return (set([tuple(a) for a in centers]) ==\n        set([tuple(a) for a in new_centers]))\n\ndef kmeans(X, K):\n    centers = [kmeans_init_centers(X, K)]\n    labels = []\n    it = 0\n    while True:\n        labels.append(kmeans_assign_labels(X, centers[-1]))\n        new_centers = kmeans_update_centers(X, labels[-1], K)\n        if has_converged(centers[-1], new_centers):\n            break\n        centers.append(new_centers)\n        it += 1\n    return (centers, labels, it)\n\n(centers, labels, it) = kmeans(X, K)\nprint('Centers found by our algorithm:')\nprint(centers[-1])\n\nkmeans_display(X, labels[-1])\n", "meta": {"hexsha": "ff4036aef49813f13b4e7bd5ffc65d907d3d0e96", "size": 2226, "ext": "py", "lang": "Python", "max_stars_repo_path": "ML_Basic/Kmean.py", "max_stars_repo_name": "ductnn/Python-tu", "max_stars_repo_head_hexsha": "8d0c16a7986cf573dbf7324375967a6bce45a7a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-18T11:40:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T11:40:40.000Z", "max_issues_repo_path": "ML_Basic/Kmean.py", "max_issues_repo_name": "ductnn/Python-tu", "max_issues_repo_head_hexsha": "8d0c16a7986cf573dbf7324375967a6bce45a7a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ML_Basic/Kmean.py", "max_forks_repo_name": "ductnn/Python-tu", "max_forks_repo_head_hexsha": "8d0c16a7986cf573dbf7324375967a6bce45a7a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1772151899, "max_line_length": 66, "alphanum_fraction": 0.6168014376, "include": true, "reason": "import numpy,from scipy", "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.9032942001955142, "lm_q1q2_score": 0.8543367991283353}}
{"text": "# Naive Implementation of SUTD ISTD 2021 50.034 Introduction to Probability and Statistics Midterm Exam Final Question\n# Created by James Raphael Tiovalen (2021)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng()\n\nLAMBDA = rng.uniform(0, 1)\nN = 1_000_000\nDATA_POINTS = 1_000_000\nBINS = 200\n\n# Assume that each call to rand() (i.e., each sample drawn) is independent and identically distributed (i.i.d.)\ndef rand(num_of_samples):\n    return rng.uniform(-LAMBDA, LAMBDA, num_of_samples)\n\n\n# As N -> +∞, this becomes approximately closer and closer to a normal distribution with mean 0 and variance (N * (LAMBDA ** 2)) / 3\n# These properties actually agree with the reformulated/reinterpreted Central Limit Theorem approximation in terms of sums of i.i.d. random variables\ndef gauss():\n    return np.sum(rand(N))\n\n\ndef main():\n    nums = np.array([gauss() for _ in np.arange(DATA_POINTS)])\n    actual = rng.normal(0, (LAMBDA * np.sqrt(N / 3)), DATA_POINTS)\n\n    # Capture and show all data points within three standard deviations from the mean (≈99.73%)\n    bins = np.linspace(\n        -3 * (LAMBDA * np.sqrt(N / 3)), 3 * (LAMBDA * np.sqrt(N / 3)), BINS\n    )\n\n    # Plot the collected data points to illustrate the normal distribution shape and compare with the actual normal distribution\n    plt.style.use(\"seaborn-deep\")\n    plt.hist(nums, bins, alpha=0.5, label=\"nums\")\n    plt.hist(actual, bins, alpha=0.5, label=\"actual\")\n    plt.legend(loc=\"upper right\")\n    plt.show()\n\n\nif __name__ == \"__main__\":\n    main()", "meta": {"hexsha": "9ec7549783a41cfcc35ab30ceb3bfcd3e63724ae", "size": 1545, "ext": "py", "lang": "Python", "max_stars_repo_path": "extras/gauss.py", "max_stars_repo_name": "jamestiotio/pns", "max_stars_repo_head_hexsha": "1ff2988977619a547ca5b3f001f6d2a32871455c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extras/gauss.py", "max_issues_repo_name": "jamestiotio/pns", "max_issues_repo_head_hexsha": "1ff2988977619a547ca5b3f001f6d2a32871455c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-04T16:22:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T16:22:50.000Z", "max_forks_repo_path": "extras/gauss.py", "max_forks_repo_name": "jamestiotio/pns", "max_forks_repo_head_hexsha": "1ff2988977619a547ca5b3f001f6d2a32871455c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9302325581, "max_line_length": 149, "alphanum_fraction": 0.7055016181, "include": true, "reason": "import numpy", "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.9032941982430049, "lm_q1q2_score": 0.8543367972816496}}
{"text": "\"\"\"\nDirectional filtering functions\n\"\"\"\nimport numpy as np\nfrom scipy.fftpack import fft2, ifft2, fftfreq, fftshift, ifftshift\n\ndef dff2d(z, dx, thetalow, thetahigh):\n    \"\"\"\n    Two-dimensional directional Fourier transform filter. \n    \n    Inputs:\n    ------\n        z: 2D complex array\n        dx: grid spacing\n        thetalow: low angle for filter (degrees CCW from E)\n        thetahigh: high angle for filter (degrees CCW from E)\n        \n    Outputs:\n    -----\n        zf: 2D filtered complex array\n    \"\"\"\n    \n    # 2D fourier transfrom\n    My, Mx = z.shape\n    Z = fft2(z)\n\n    # Compute zonal wavenumbers\n    k = fftfreq(Mx, dx/(2*np.pi))\n    dk = 1/(Mx*dx)\n\n    # Compute meridional wavenumbers\n    l = fftfreq(My, dx/(2*np.pi))\n    dl = 1/(My*dx)\n    \n    # Need to re-order the FFT output because positive frequencies are output first from the numpy DFT algorithm\n    k_r = fftshift(k)\n    l_r = fftshift(l)\n    \n    # Create a grid for the direction\n    Lx,Ly = np.meshgrid(k_r,l_r)\n    theta = np.angle(Lx + 1j*Ly)\n\n    thetadeg = np.mod(theta*180/np.pi,360)\n\n    # Create the filter matrix\n    H = np.zeros_like(thetadeg)\n    \n    if thetahigh > 360:\n        filter_idx1 = (thetadeg > thetalow) & (thetadeg < 360)\n        filter_idx2 = (thetadeg > 0) & (thetadeg < np.mod(thetahigh,360))\n        filter_idx = filter_idx1 | filter_idx2\n    else:\n        filter_idx = (thetadeg > thetalow) & (thetadeg < thetahigh)\n        \n    H[filter_idx] = 1\n\n    # Now reorder H into the original FFT ordering\n    H_r = ifftshift(H,axes=1)\n    H_r = ifftshift(H_r,axes=0)\n\n    # Finally, filter\n    zf = ifft2(Z*H_r)\n    \n    return zf\n \n\ndef hilbert_2d(z, dx, dy):\n    My, Mx = z.shape\n    Z = fft2(z)\n\n    # Compute zonal frequencies\n    k = fftfreq(Mx, dx/(2*np.pi))\n    dk = 1/(Mx*dx)\n\n    # Compute meridional frequencies\n    l = fftfreq(Mx, dx/(2*np.pi))\n    dl = 1/(My*dy)\n    \n    # Create filter matrices for each of the four quadrant\n    Z_posk_posl = np.zeros_like(Z)\n    Z_posk_posl[:My//2, :Mx//2] = Z[:My//2, :Mx//2] \n\n    z_posk_posl = ifft2(Z_posk_posl)\n\n    Z_posk_negl = np.zeros_like(Z)\n    Z_posk_negl[:My//2, Mx//2::] = Z[:My//2, Mx//2::] \n\n    z_posk_negl = ifft2(Z_posk_negl)\n\n    Z_negk_negl = np.zeros_like(Z)\n    Z_negk_negl[My//2::, Mx//2::] = Z[My//2::, Mx//2::] \n\n    z_negk_negl = ifft2(Z_negk_negl)\n\n    Z_negk_posl = np.zeros_like(Z)\n    Z_negk_posl[My//2::, :Mx//2] = Z[My//2::, :Mx//2] \n\n    z_negk_posl = ifft2(Z_negk_posl)\n    \n    return z_posk_posl, z_posk_negl, z_negk_negl, z_negk_posl\n", "meta": {"hexsha": "73c981002eac146c41028e5865af01ac8665df4e", "size": 2530, "ext": "py", "lang": "Python", "max_stars_repo_path": "iwatlas/filter2d.py", "max_stars_repo_name": "Yadidya5/iwatlas", "max_stars_repo_head_hexsha": "7cf2a8778b9ebefe564f93efe013d6d3743c94ec", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-12-24T08:24:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T07:06:47.000Z", "max_issues_repo_path": "iwatlas/filter2d.py", "max_issues_repo_name": "Yadidya5/iwatlas", "max_issues_repo_head_hexsha": "7cf2a8778b9ebefe564f93efe013d6d3743c94ec", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-12T05:40:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T07:25:27.000Z", "max_forks_repo_path": "iwatlas/filter2d.py", "max_forks_repo_name": "Yadidya5/iwatlas", "max_forks_repo_head_hexsha": "7cf2a8778b9ebefe564f93efe013d6d3743c94ec", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-31T10:20:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T07:06:52.000Z", "avg_line_length": 25.0495049505, "max_line_length": 112, "alphanum_fraction": 0.6019762846, "include": true, "reason": "import numpy,from scipy", "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773707999669627, "lm_q2_score": 0.8740772269642949, "lm_q1q2_score": 0.8542975585509974}}
{"text": "import numpy\nimport math\n\nfrom base.polynomial import Polynomial\nfrom base.matrix import Matrix\nfrom newtons_method import Newtons_method, get_roots\nfrom legendre_polynomial import Legendre\n\n\nclass GaussianQuad:\n    \"\"\"\n    Gaussian Quadrature is a numerical approximation technique to calculate the \n    the definite integral of a function.\n     - It utilises a weighted-sum of function values at prescribed points within the\n        definitive domain described by the integral\n     - To utilise this method, the definite interval needs to be translated to\n        the interval: [-1; 1]\n    \"\"\"\n\n    # Define the order of Gaussian Quadrature:\n    #   - n_order = number of points / order of gaussian quadrature\n    order = 1                     # Int (>= 1)\n    \n    # Define the legendre polynomials up to a point\n    legendre = []              # Legendre Polynomial for specified order\n\n    # Define the Quadrature Matrix:\n    #   - Size: Order x 2:\n    #       [n,0] = node position\n    #       [n,1] = node weight value\n    quadrature = []                 # Matrix (nx2)\n\n\n    def __init__(self, n_points) -> None:\n        self.order = n_points\n        self.quadrature = numpy.zeros((n_points, 2))\n        \n        if n_points == 1:   # If first simple case, avoid generating legendre polynomials\n            self.quadrature[0, 0] = 0\n            self.quadrature[0, 1] = 2\n        else:\n            # generate legendre equation polynomial of degree n\n            self.legendre = Legendre(n_points)\n            # Print Legendre polynomial info\n            #print(f\"legendre_polynomial:{self.legendre.co_array}, roots:{self.legendre.roots}\")\n            \n            # use legendre polynomial to \n            for i in range(n_points):\n                self.quadrature[i, 0] = self.legendre.roots[i]\n                self.quadrature[i, 1] = self.calculate_weight_function(i, self.legendre.roots[i])\n\n\n    def __str__(self) -> str:\n        ret_str = \"{}\\n\".format(self.order)\n        for i in range(self.order):\n            ret_str += \"{}:{},\\n\".format(self.quadrature[i,0], self.quadrature[i, 1])\n        return ret_str\n\n    # Calculate the weight value correlating to specified root of Legendre polynomial\n    def calculate_weight_function(self, i, root_i) -> float:\n        # w_i = 2/(1 - (x_i)^2) * 2/(P'n(x_i)^2)\n        #   - see https://en.wikipedia.org/wiki/Gaussian_quadrature for details on formula.\n        derivative = self.legendre.derive()\n        deriv_x_i = derivative.evaluate(root_i)\n        \n        # Print root info used for calculating corresponding weight values\n        #print(f\"i:{i}|root_i:{root_i}, dx_i:{deriv_x_i}, deriv:{repr(derivative)}\")\n        return 2/((1-root_i**2)*(deriv_x_i**2))\n\n    # Calulate definite integral (a numerical approximation) of a polynomial function\n    #  between limits a and b\n    #   - translates [a,b] limits to [-1,1]\n    #   - calculate the weighted sum of function values at each Gaussian point\n    def calculate_definite_integral(self, polynomial, a, b):\n        ba = (b - a)/2\n        ab = (a + b)/2\n        fret = 0.0\n        for p in range(self.gaussian.order):\n            val = ba*self.quadrature[p, 0] + ab\n            fret += self.quadrature[p, 1]*polynomial.evaluate(val)\n        fret *= ba\n        return fret\n\n# Tests for the Gaussian Quadrature method\ndef main():\n    # test function for legendre_polynomial + binomial_coefficient\n    n_test = 4\n    gquad = GaussianQuad(n_test)\n    print(\"n_test:\", gquad)\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "17f083417cf621bc2e75be46fbc1cacd72b5af8f", "size": 3522, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/numerical/gaussian_quadrature.py", "max_stars_repo_name": "JNMaree/solvdoku", "max_stars_repo_head_hexsha": "d7cbce8618b5a94db8781d88cf3db102e728f4f6", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/numerical/gaussian_quadrature.py", "max_issues_repo_name": "JNMaree/solvdoku", "max_issues_repo_head_hexsha": "d7cbce8618b5a94db8781d88cf3db102e728f4f6", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-04T21:01:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-29T21:12:23.000Z", "max_forks_repo_path": "src/numerical/gaussian_quadrature.py", "max_forks_repo_name": "JNMaree/solvdoku", "max_forks_repo_head_hexsha": "d7cbce8618b5a94db8781d88cf3db102e728f4f6", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4680851064, "max_line_length": 97, "alphanum_fraction": 0.6240772288, "include": true, "reason": "import numpy", "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843812, "lm_q2_score": 0.8918110540642804, "lm_q1q2_score": 0.8542767530686818}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nch5Python.py Statistical significance of regression.\n\"\"\"\nimport numpy as np\nfrom scipy import stats\nimport statsmodels.api as sm\n\nx = [1.00,1.25,1.50,1.75,2.00,2.25,2.50,2.75,3.00,3.25,3.50,3.75,4.00]\ny = [3.34,4.97,4.15,5.40,5.21,4.56,3.69,5.86,4.58,6.94,5.57,5.62,6.87]\n\n# Convert data to vectors.   \nx = np.array(x)\ny = np.array(y)\nn = len(y)\nxmean = np.mean(x)\nymean = np.mean(y)\n# Find zero mean versions of x and y.\nxzm = x - xmean\nyzm = y - ymean\ncovxy = np.sum(xzm * yzm)/n\nvarx = np.var(x)\nvary = np.var(y)\nprint(\"Variance of x = %0.3f.\" %varx) # 0.875\nprint(\"Variance of y = %0.3f.\" %vary) # 1.095\nprint(\"Covariance of x and y = %0.3f.\" %covxy) # 0.669 \n\n# Find slope b1.\nb1 = covxy/varx # 0.764\n# Find intercept b0.\nb0 = ymean - b1*xmean # 3.225\nprint('\\nslope b1 = %6.3f\\nintercept b0 = %6.3f.' % (b1, b0))\n\n# Find vertical projection of y onto best fitting line.\nyhat = b1*x + b0\n\nnumparams = 2 # number of parameters=2 (slope and intercept).\n\n# SLOPE\n# Find sem of slope.\nnum = ( (1/(n-numparams)) * sum((y-yhat)**2) )**0.5 # 0.831.\nden = sum((x-xmean)**2)**0.5 # 3.373\nsemslope = num/den\nprint('semslope = %6.3f.' % (semslope))\n\n\n# Find t-value of slope.\ntslope = b1/semslope # 3.101\n\n# Find p-value of slope.\n# two-tailed pvalue = Prob(abs(t)>tt).\npvalue = stats.t.sf(np.abs(tslope), n-numparams)*2 # 0.0101\nprint('\\nSLOPE:\\nt-statistic = %6.3f.' % tslope)\nprint('pvalue = %6.4f.\\m' % pvalue)\n\n# INTERCEPT\n# Find sem of intercept.\na = ( (1/(n-numparams)) * sum((y-yhat)**2) )**0.5 # 0.831\nb = ( (1/n) + xmean**2 / sum( xzm**2 ))**0.5 # 0.791\nsemintercept = a * b  # 0.658\nprint('\\na = %6.3f\\nb = %6.3f\\nsemintercept = a/b = %6.3f.'\n% (a, b, semintercept))\n\n# Find t-value of intercept.\ntintercept = b0 / semintercept\npintercept = stats.t.sf(np.abs(tintercept), n-numparams)*2  \nprint('\\nINTERCEPT:\\nt-statistic = %6.3f.'% tintercept)\nprint('pvalue = %6.4f.\\n'% pintercept)\n\n# Overall model fit to data.\n# Find coefficient of variation r2.\nr2 = covxy * covxy / (varx * vary)\nprint(\"coefficient of variation = %0.3f.\" %r2) # 0.466.\n\n# Find F ratio.\nA = r2 / (numparams-1)\nB = (1-r2) / (n-numparams)\nF = A/B # 9.617\nprint(\"F ratio = %0.4f.\" % F) \n\npfit = stats.f.sf(F, numparams-1, n-numparams)\nprint(\"p overall fit = %0.4f.\" % pfit) # 0.0101.\n\n# Run standard library regression method for comparison.\nones = np.ones(len(x))\nX = [ones, x]\nX = np.transpose(X)\ny = np.transpose(y)\nres_ols = sm.OLS(y, X).fit()\nprint(res_ols.summary()) # Print table of results.\n\n# END OF FILE.", "meta": {"hexsha": "556b826b0bd040bd05810e18f04be885db0b6a06", "size": 2538, "ext": "py", "lang": "Python", "max_stars_repo_path": "PythonCode/Ch05/ch5Python.py", "max_stars_repo_name": "jgvfwstone/Regression", "max_stars_repo_head_hexsha": "483e8057f2cadcec43cf7475ef19a8f2113fed80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-20T15:40:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T11:40:38.000Z", "max_issues_repo_path": "PythonCode/Ch05/ch5Python.py", "max_issues_repo_name": "jgvfwstone/Regression", "max_issues_repo_head_hexsha": "483e8057f2cadcec43cf7475ef19a8f2113fed80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PythonCode/Ch05/ch5Python.py", "max_forks_repo_name": "jgvfwstone/Regression", "max_forks_repo_head_hexsha": "483e8057f2cadcec43cf7475ef19a8f2113fed80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2903225806, "max_line_length": 70, "alphanum_fraction": 0.6280535855, "include": true, "reason": "import numpy,from scipy,import statsmodels", "num_tokens": 1024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889438, "lm_q2_score": 0.8918110425624792, "lm_q1q2_score": 0.854276745265554}}
{"text": "\"\"\"\nSimple implementation of classical MDS.\nSee http://www.stat.cmu.edu/~ryantibs/datamining/lectures/09-dim3-marked.pdf for more details.\n\"\"\"\n\nimport numpy as np\nimport numpy.linalg as linalg\n\ndef mds(D, dim=2):\n    \"\"\" Classical multidimensional scaling algorithm.\n        Given a matrix of interpoint distances D, find a set of low dimensional points\n        that have a similar interpoint distances.\n    \"\"\"\n    (n,n) = D.shape\n    A = (-0.5 * D**2)\n    M = np.ones((n,n))/n\n    I = np.eye(n)\n    B = np.dot(np.dot(I-M, A),I-M)\n    \n    '''Another way to compute inner-products matrix B\n    Ac = np.mat(np.mean(A, 1))\n    Ar = np.mat(np.mean(A, 0))\n    B = np.array(A - np.transpose(Ac) - Ar + np.mean(A))\n    '''\n    \n    [U,S,V] = linalg.svd(B)\n    Y = U * np.sqrt(S)\n    return (Y[:,0:dim], S)\n\ndef main():\n    \"\"\" @Todo: Adding simple test code for mds.\"\"\"\n    pass\n    \nif __name__ == '__main__':\n    main()", "meta": {"hexsha": "9e75ba9176a0f125d39c6ff8c5e9e9aa2b1b7f7c", "size": 916, "ext": "py", "lang": "Python", "max_stars_repo_path": "Dimensionality-Reduction/mds.py", "max_stars_repo_name": "ntduong/ML", "max_stars_repo_head_hexsha": "ef69b0ad6205e4a5a3067470d1d2a60009479de6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-10-12T23:24:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-19T13:09:30.000Z", "max_issues_repo_path": "Dimensionality-Reduction/mds.py", "max_issues_repo_name": "ntduong/ML", "max_issues_repo_head_hexsha": "ef69b0ad6205e4a5a3067470d1d2a60009479de6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dimensionality-Reduction/mds.py", "max_forks_repo_name": "ntduong/ML", "max_forks_repo_head_hexsha": "ef69b0ad6205e4a5a3067470d1d2a60009479de6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1714285714, "max_line_length": 94, "alphanum_fraction": 0.5927947598, "include": true, "reason": "import numpy", "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889437, "lm_q2_score": 0.8918110418436166, "lm_q1q2_score": 0.8542767445769466}}
{"text": "import numpy as np\n\nnp.random.seed(12)\nnum_observations = 5000\n\nx1 = np.random.multivariate_normal([0, 0], [[1, .75],[.75, 1]], num_observations)\nx2 = np.random.multivariate_normal([1, 4], [[1, .75],[.75, 1]], num_observations)\n\nsimulated_separableish_features = np.vstack((x1, x2)).astype(np.float32)\nsimulated_labels = np.hstack((np.zeros(num_observations),\n                              np.ones(num_observations)))\n\ndef sigmoid(z):\n    return 1 / (1 + np.exp(-z))\n\ndef log_likelihood(features, target, weights):\n    scores = np.dot(features, weights)\n    ll = np.sum( target*scores - np.log(1 + np.exp(scores)) )\n    return ll\n\ndef logistic_regression(features, target, num_steps, learning_rate, add_intercept = False):\n    if add_intercept:\n        intercept = np.ones((features.shape[0], 1))\n        features = np.hstack((intercept, features))\n        \n    weights = np.zeros(features.shape[1])\n    \n    for step in xrange(num_steps):\n        scores = np.dot(features, weights)\n        predictions = sigmoid(scores)\n\n        # Update weights with gradient\n        output_error_signal = target - predictions\n        gradient = np.dot(features.T, output_error_signal)\n        weights += learning_rate * gradient\n        \n        # Print log-likelihood every so often\n        if step % 10000 == 0:\n            print log_likelihood(features, target, weights)\n        \n    return weights\n\nweights = logistic_regression(simulated_separableish_features, simulated_labels,\n     num_steps = 300000, learning_rate = 5e-5, add_intercept=True)\n\ndata_with_intercept = np.hstack((np.ones((simulated_separableish_features.shape[0], 1)),\n                                 simulated_separableish_features))\nfinal_scores = np.dot(data_with_intercept, weights)\npreds = np.round(sigmoid(final_scores))\n\nprint 'Accuracy from scratch: {0}'.format((preds == simulated_labels).sum().astype(float) / len(preds))\nprint 'Accuracy from sk-learn: {0}'.format(clf.score(simulated_separableish_features, simulated_labels))", "meta": {"hexsha": "63b2cecc7a1ad5eee417b383248c7b9c6ade49c5", "size": 1995, "ext": "py", "lang": "Python", "max_stars_repo_path": "logistic_regression_sklearn/logistic_log_likeihood.py", "max_stars_repo_name": "nguyenductamlhp/tensorflow_demo", "max_stars_repo_head_hexsha": "7c4b55dff80dd435806a1b22dee6eb32ae39c02d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "logistic_regression_sklearn/logistic_log_likeihood.py", "max_issues_repo_name": "nguyenductamlhp/tensorflow_demo", "max_issues_repo_head_hexsha": "7c4b55dff80dd435806a1b22dee6eb32ae39c02d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logistic_regression_sklearn/logistic_log_likeihood.py", "max_forks_repo_name": "nguyenductamlhp/tensorflow_demo", "max_forks_repo_head_hexsha": "7c4b55dff80dd435806a1b22dee6eb32ae39c02d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-05T06:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-05T06:40:09.000Z", "avg_line_length": 38.3653846154, "max_line_length": 104, "alphanum_fraction": 0.6781954887, "include": true, "reason": "import numpy", "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874228, "lm_q2_score": 0.8918110382493034, "lm_q1q2_score": 0.8542767400623802}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 15 21:04:26 2017\n\n@author: Anastasios Tzavellas\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef f(x):\n    return np.exp(2 * x) - 1.\n\n\ndef L(x, i, xValues):\n    \"\"\"Evaluates ith degree\n    Lagrange Polynomial\"\"\"\n    xi = xValues[i]\n    product = 1.\n    for j, xj in enumerate(xValues):\n        if j != i:\n            product = product * (x - xj) / (xi - xj)\n    return product\n\n\ndef Lagrange(x, xValues, fValues):\n    \"\"\"Evaluates Lagrange Polynomial\"\"\"\n    val = 0.\n    for i, fi in enumerate(fValues):\n        val = val + L(x, i, xValues) * fi\n    return val\n\n\nxValues = np.array([1, 1.1, 1.2, 1.3, 1.4])\nfValues = f(xValues)\np = Lagrange(1.25, xValues, fValues)\nprint('Function Value f(1.25)=', f(1.25))\nprint('Lagrange polyn p(1.25)=', p)\n\nplt.close('all')\nx = np.arange(1.0, 1.41, 0.01)\nps = Lagrange(x, xValues, fValues)\nplt.plot(x, f(x), '.', label='f(x)')\nplt.plot(xValues, fValues, '*')\nplt.plot(x, ps, '-.', label='p(x)')\nplt.legend()\nplt.grid()\n", "meta": {"hexsha": "ae3996cee770fe100be37d9016e951ba8ca2de40", "size": 1016, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignment3/ex1.py", "max_stars_repo_name": "tzavellas/ComputationalPhysics", "max_stars_repo_head_hexsha": "7dd95d1a55faa4d467b9a96c7ee1933e88652370", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment3/ex1.py", "max_issues_repo_name": "tzavellas/ComputationalPhysics", "max_issues_repo_head_hexsha": "7dd95d1a55faa4d467b9a96c7ee1933e88652370", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment3/ex1.py", "max_forks_repo_name": "tzavellas/ComputationalPhysics", "max_forks_repo_head_hexsha": "7dd95d1a55faa4d467b9a96c7ee1933e88652370", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7346938776, "max_line_length": 52, "alphanum_fraction": 0.5875984252, "include": true, "reason": "import numpy", "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813392, "lm_q2_score": 0.8918110404058914, "lm_q1q2_score": 0.854276737842084}}
{"text": "# from sympy import\nfrom utils import r\n\n\ndef secant_method(fn, x1, x0, iter=1):\n    out_str = ''\n\n    if iter == 1:\n        out_str += f\"Secant method is given as:\\n\"\n        out_str += f\"$$ x_{{i+1}} = x_i - \\\\left[\\\\frac{{f(x_i)(x_{{i-1}} - x_{{i}})}}{{f(x_{{i-1}}) - f(x_{{i}})}}\\\\right] $$\\n\"\n\n    out_str += f\"\\\\textbf{{Iteration {iter}}}\\n\\n\"\n    out_str += f\"$$ x_{iter} = x_{iter - 1} - \\\\left[\\\\frac{{f(x_{iter - 1})(x_{{{iter - 2}}}-x_{iter - 1})}}{{f(x_{{{iter - 2}}}) - f(x_{{{iter - 1}}})}}\\\\right] $$\\n\"\n\n    out_str += f\"$$ f(x_{{{iter - 2}}}) = f({r(x0)}) = {r(fn(x0))} $$\\n\"\n    out_str += f\"$$ f(x_{{{iter - 1}}}) = f({r(x1)}) = {r(fn(x1))} $$\\n\"\n\n    out_str += f\"$$ x_{iter} = {r(x0)} - \\\\left[\\\\frac{{{r(fn(x1))}({r(x0)}-({r(x1)}))}}{{{r(fn(x0))} - ({r(fn(x1))}))}}\\\\right] $$\\n\"\n    x_val = fn(x0) * (x0 - x1) / (fn(x0) - fn(x1))\n    out_str += f\"$$ x_{iter} = {r(x0)} - ({r(x_val)}) $$\\n\"\n    x_val = x0 - x_val\n    out_str += f\"$$ x_{iter} = {r(x_val)} $$\\n\"\n\n    error = None\n    if iter > 1:\n        out_str += \"\\n\\\\textbf{Error}\\n\\n\"\n        out_str += f\"$$ \\\\text{{Error}} = \\\\frac{{\\\\left|\\\\text{{latest value}} - \\\\text{{previous value}}\\\\right|}}{{\\\\left|\\\\text{{latest value}}\\\\right|}} \\\\times 100 $$\\n\"\n        out_str += f\"$$ \\\\text{{Error}} = \\\\frac{{\\\\left|{r(x_val)} - ({r(x1)})\\\\right|}}{{\\\\left|{r(x_val)}\\\\right|}} \\\\times 100 $$\\n\"\n        error = abs(x_val - x1)/abs(x_val) * 100\n        out_str += f\"$$ \\\\text{{Error}} = {r(error, 2)} \\\\% $$\\n\"\n\n    if error is not None and error < 0.0001 or iter > 3:\n        return out_str\n\n    out_str += secant_method(fn, x_val, x1, iter+1)\n    return out_str\n\n\nif __name__ == '__main__':\n    from sympy import lambdify, sin, cos, symbols\n\n    x = symbols('x')\n    print(secant_method(lambdify(x, sin(x) + cos(1-x**2) - 1), 3, 1))\n", "meta": {"hexsha": "b984849a67996aa3ca98225b0450c137e10cc151", "size": 1814, "ext": "py", "lang": "Python", "max_stars_repo_path": "NC/secant.py", "max_stars_repo_name": "nmanumr/comsats-scripts", "max_stars_repo_head_hexsha": "ec7a38c705315170f689f26ce6f6c56bbd87d923", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-07-04T16:43:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T16:10:50.000Z", "max_issues_repo_path": "NC/secant.py", "max_issues_repo_name": "nmanumr/comsats-scripts", "max_issues_repo_head_hexsha": "ec7a38c705315170f689f26ce6f6c56bbd87d923", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NC/secant.py", "max_forks_repo_name": "nmanumr/comsats-scripts", "max_forks_repo_head_hexsha": "ec7a38c705315170f689f26ce6f6c56bbd87d923", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2272727273, "max_line_length": 175, "alphanum_fraction": 0.4851157663, "include": true, "reason": "from sympy", "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.9161096153072138, "lm_q1q2_score": 0.8542294437916181}}
{"text": "#! /usr/bin/env python\n\n\"\"\"\nFile: read_2columns.py\n\nCopyright (c) 2016 Taylor Patti\n\nLicense: MIT\n\nThis module demonstrates three different iteration techniques, lists and loops, \nvectorization with default summation, and vectorization wtih numpy sumation, \nthrough the implementation of a midpoint integration function.\n\n\"\"\"\n\nimport numpy as np\n\ndef midpointint(f, a, b, n):\n    \"\"\"Uses lists and for loop to iterate through a midpoint integration function\"\"\"\n    h = (b - a) / float(n)\n    sum = 0\n    for i in range(n):\n        sum = sum + h * f(a - (h /2) + (i+1) * h)\n    return sum\n\ndef midpointvecdefault(f, a, b, n):\n    \"\"\"Uses arrays and default summation for a midpoint integration function\"\"\"\n    h = (b - a) / float(n)\n    info = np.array([h * f(a - (h /2) + (i+1) * h) for i in range(n)])\n    return sum(info)\n\ndef midpointvec(f, a, b, n):\n    \"\"\"Uses arrays and numpy summation for a midpoint integration function\"\"\"\n    h = (b - a) / float(n)\n    info = np.array([h * f(a - (h /2) + (i+1) * h) for i in range(n)])\n    return np.sum(info)\n\ndef x_func(i):\n    \"\"\"The function x, for implementation in other functions.\"\"\"\n    return i\n\ndef test_midpointint_triangle():\n    \"\"\"Ensures proper integration of the straight line x from 1 to 3.\"\"\"\n    apt = (abs((midpointint(x_func, 1, 3, 1000)) - 4) <1e-6)\n    msg = 'Unsuccessful integration.'\n    assert apt, msg\n\ndef test_midpointvecdefault_triangle():\n    \"\"\"Ensures proper integration of the straight line x from 1 to 3.\"\"\"\n    apt = (abs(midpointvecdefault(x_func, 1, 3, 1000) - 4) <1e-6)\n    msg = 'Unsuccessful integration.'\n    assert apt, msg\n    \ndef test_midpointvec_triangle():\n    \"\"\"Ensures proper integration of the straight line x from 1 to 3.\"\"\"\n    apt = (abs(midpointvec(x_func, 1, 3, 1000) - 4) <1e-6)\n    msg = 'Unsuccessful integration.'\n    assert apt, msg", "meta": {"hexsha": "984af0d758afe9217fa3dda2cb684499c6fbc2c7", "size": 1839, "ext": "py", "lang": "Python", "max_stars_repo_path": "midpoint_vec.py", "max_stars_repo_name": "chapman-phys227-2016s/hw-2-patti102", "max_stars_repo_head_hexsha": "f82db5738f94a6fe2a4d2742dcd30583ac3c9cf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "midpoint_vec.py", "max_issues_repo_name": "chapman-phys227-2016s/hw-2-patti102", "max_issues_repo_head_hexsha": "f82db5738f94a6fe2a4d2742dcd30583ac3c9cf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "midpoint_vec.py", "max_forks_repo_name": "chapman-phys227-2016s/hw-2-patti102", "max_forks_repo_head_hexsha": "f82db5738f94a6fe2a4d2742dcd30583ac3c9cf5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7068965517, "max_line_length": 84, "alphanum_fraction": 0.6487221316, "include": true, "reason": "import numpy", "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.916109614162018, "lm_q1q2_score": 0.8542294410041714}}
{"text": "'''\nAre the Belmont Stakes results Normally distributed?\n100xp\n\nSince 1926, the Belmont Stakes is a 1.5 mile-long race of 3-year old thoroughbred horses.\nSecretariat ran the fastest Belmont Stakes in history in 1973. While that was the fastest\nyear, 1970 was the slowest because of unusually wet and sloppy conditions. With these two \noutliers removed from the data set, compute the mean and standard deviation of the Belmont\nwinners' times. Sample out of a Normal distribution with this mean and standard deviation\nusing the np.random.normal() function and plot a CDF. Overlay the ECDF from the winning\nBelmont times. Are these close to Normally distributed?\n\nNote: Justin scraped the data concerning the Belmont Stakes from the Belmont Wikipedia page.\n\nInstructions\n-Compute mean and standard deviation of Belmont winners' times with the two outliers removed.\nThe NumPy array belmont_no_outliers has these data.\n-Take 10,000 samples out of a normal distribution with this mean and standard deviation using\nnp.random.normal().\n-Compute the CDF of the theoretical samples and the ECDF of the Belmont winners' data, assigning\nthe results to x_theor, y_theor and x, y, respectively.\n-Hit submit to plot the CDF of your samples with the ECDF, label your axes and show the plot.\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nbelmont_no_outliers = np.array([148.51,  146.65,  148.52,  150.7,  150.42,  150.88,  151.57,\n                                147.54,  149.65,  148.74,  147.86,  148.75,  147.5,  148.26,\n                                149.71,  146.56,  151.19,  147.88,  149.16,  148.82,  148.96,\n                                152.02,  146.82,  149.97,  146.13,  148.1,  147.2,  146.,\n                                146.4,  148.2,  149.8,  147.,  147.2,  147.8,  148.2,\n                                149.,  149.8,  148.6,  146.8,  149.6,  149.,  148.2,\n                                149.2,  148.,  150.4,  148.8,  147.2,  148.8,  149.6,\n                                148.4,  148.4,  150.2,  148.8,  149.2,  149.2,  148.4,\n                                150.2,  146.6,  149.8,  149.,  150.8,  148.6,  150.2,\n                                149.,  148.6,  150.2,  148.2,  149.4,  150.8,  150.2,\n                                152.2,  148.2,  149.2,  151.,  149.6,  149.6,  149.4,\n                                148.6,  150.,  150.6,  149.2,  152.6,  152.8,  149.6,\n                                151.6,  152.8,  153.2,  152.4,  152.2])\n\n\ndef ecdf(data):\n    \"\"\"Compute ECDF for a one-dimensional array of measurements.\"\"\"\n\n    # Number of data points: n\n    n = len(data)\n\n    # x-data for the ECDF: x\n    x = np.sort(data)\n\n    # y-data for the ECDF: y\n    y = np.arange(1, n + 1) / n\n\n    return x, y\n\n\n# Seed random number generator\nnp.random.seed(42)\n\n# Compute mean and standard deviation: mu, sigma\nmu = np.mean(belmont_no_outliers)\nsigma = np.std(belmont_no_outliers)\n\n# Sample out of a normal distribution with this mu and sigma: samples\nsamples = np.random.normal(mu, sigma, 10000)\n\n# Get the CDF of the samples and of the data\nx_theor, y_theor = ecdf(samples)\nx, y = ecdf(belmont_no_outliers)\n\n# Plot the CDFs and show the plot\n_ = plt.plot(x_theor, y_theor)\n_ = plt.plot(x, y, marker='.', linestyle='none')\nplt.margins(0.02)\n_ = plt.xlabel('Belmont winning time (sec.)')\n_ = plt.ylabel('CDF')\nplt.show()\n", "meta": {"hexsha": "f0e703f65e70820c5d827c4a285ef5c4fe10a357", "size": 3341, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/4-thinking-probabilistically--continuous-variables/are-the-belmont-stakes-results-normally-distributed.py", "max_stars_repo_name": "aimanahmedmoin1997/DataCamp", "max_stars_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-12T04:49:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T00:40:28.000Z", "max_issues_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/4-thinking-probabilistically--continuous-variables/are-the-belmont-stakes-results-normally-distributed.py", "max_issues_repo_name": "aimanahmedmoin1997/DataCamp", "max_issues_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/4-thinking-probabilistically--continuous-variables/are-the-belmont-stakes-results-normally-distributed.py", "max_forks_repo_name": "aimanahmedmoin1997/DataCamp", "max_forks_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-11-06T17:43:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T21:08:16.000Z", "avg_line_length": 42.2911392405, "max_line_length": 96, "alphanum_fraction": 0.615683927, "include": true, "reason": "import numpy", "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.9161096084360387, "lm_q1q2_score": 0.8542294322257528}}
{"text": "import numpy as np\n\n'''\nSoftmax Function is used for MultiClass Classification. \nRecall that for binary classification, sigmoid function is used.\n\n*However, when n=2, given softmax, works actually the same as the sigmoid function.\n\nthe formula for softmax is:\nP(class_i) = e^(Z_i)/(e^Z_1 + e^Z_2 + ... + e^Z_n)\n'''\n\n# Write a function that takes as input a list of numbers, and returns\n# the list of values given by the softmax function.\ndef softmax(L):\n    # numerator - convert the list into exponents\n    expL = np.exp(L)\n    \n    # denominator - summation of the exponential values from the list\n    sumExpL = sum(expL)\n    \n    # we need answers for each of the classes or value in the list\n    result = []\n    for i in expL:\n        result.append(i*1.0/sumExpL)\n    return result\n", "meta": {"hexsha": "42445fe7712ec3d9394d6d51e14d856363ab9d8e", "size": 786, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lesson 3: Introduction to Neural Networks/2 Softmax.py", "max_stars_repo_name": "makeithappenlois/Udacity-AI", "max_stars_repo_head_hexsha": "c82c7abaf179730740fecae76d388b14cbb3917c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-03T17:36:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T18:24:14.000Z", "max_issues_repo_path": "Lesson 3: Introduction to Neural Networks/2 Softmax.py", "max_issues_repo_name": "makeithappenlois/Udacity-AI", "max_issues_repo_head_hexsha": "c82c7abaf179730740fecae76d388b14cbb3917c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lesson 3: Introduction to Neural Networks/2 Softmax.py", "max_forks_repo_name": "makeithappenlois/Udacity-AI", "max_forks_repo_head_hexsha": "c82c7abaf179730740fecae76d388b14cbb3917c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-03T16:30:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-08T15:03:14.000Z", "avg_line_length": 29.1111111111, "max_line_length": 83, "alphanum_fraction": 0.6921119593, "include": true, "reason": "import numpy", "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668662546613, "lm_q2_score": 0.870597266729631, "lm_q1q2_score": 0.8542011919669855}}
{"text": "import numpy as np\nfrom scipy import linalg\n\ndef QR(X):\n    \"\"\"Compute the Gram Schmidt of the column vectors in X\n\n    The formula: x_k := x_k-<x_k, q_1>*q_1  (k=2,...,n)\n    Then we normalize x_k\n    \n    label: QR\n    \"\"\"\n\n    #transpose so we are dealing with rows instead of columns\n    Q = X.T.copy()\n    nrows, ncols = X.shape\n    R = np.zeros((nrows, ncols))\n\n    for i in xrange(nrows):\n        R[i,i] = linalg.norm(Q[i])\n        Q[i] = Q[i]/R[i,i]\n        for j in xrange(i+1,nrows):\n            R[i,j] = Q[j].dot(Q[i])\n            Q[j] = Q[j]-(R[i,j]*Q[i])\n\n    return Q.T, R\n    \n    \ndef detQR(X):\n    \"\"\"Computes the determinant of X using the QR decomposition\n    This will give you the determinant up to, but without sign.\n    \n    The determinant of Q is +1 or -1 which may or may not change the sign of\n    the determinant of R\"\"\"\n    Q, R = QR(X)\n    return np.diagonal(R).prod()\n\ndef leastsq(A, b):\n    \"\"\"Compute a least squares solution using the QR Decomposition\"\"\"\n    Q, R = linalg.qr(A)\n    \n    #We solve the triangular system instead of inverting R\n    return linalg.solve_triangular(R, Q.T.dot(b))\n    \n    \ndef eigvv(A, niter=50):\n    Qlist = [A]\n    x0 = np.random.rand(A.shape[1])\n    for i in range(niter):\n        Q,R = QR(Qlist[-1])\n        A = Q.T.dot(A.dot(Q))        \n        Qlist.append(A)\n    \n    eigvals = np.diag(Qlist[-1])\n    \n    L = np.eye(Q.shape[0])    \n    for qm in Qlist:\n        L = L.dot(qm)\n       \n    return eigvals, x0, L\n", "meta": {"hexsha": "5ae6598daa4d6913d476027236d51dee3603ea70", "size": 1481, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/QR/qr.py", "max_stars_repo_name": "jessicaleete/numerical_computing", "max_stars_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-10-18T19:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:12:38.000Z", "max_issues_repo_path": "Labs/QR/qr.py", "max_issues_repo_name": "jessicaleete/numerical_computing", "max_issues_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/QR/qr.py", "max_forks_repo_name": "jessicaleete/numerical_computing", "max_forks_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-14T16:07:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-20T09:05:06.000Z", "avg_line_length": 24.6833333333, "max_line_length": 76, "alphanum_fraction": 0.5570560432, "include": true, "reason": "import numpy,from scipy", "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854164256365, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.8541841534669903}}
{"text": "import math\nimport numpy as np\n\ndef rigid_transform_3D(A, B):\n    \"\"\" given the coordinates of GCPs in source system in array A\n        and the coordinates in the destination system in array B\n    \"\"\"\n    centroid_A = np.mean(A, 0)\n    centroid_B = np.mean(B, 0)\n    N = A.shape[0]\n    H = (A - centroid_A).T.dot(B - centroid_B)\n    U, S, V = np.linalg.svd(H)\n    # rotation matrix\n    R = V.T.dot(U.T)\n    if np.linalg.det(R) < 0:\n        R[:,3] *= -1\n    # translation\n    t = -R.dot(centroid_A.T) + centroid_B.T\n    # scale\n    sc = np.linalg.norm(B - centroid_B, 2) / np.linalg.norm(A - centroid_A, 2)\n    return R, t, sc\n\nif __name__ == \"__main__\":\n\n    A = np.loadtxt('gcp.txt', delimiter=' ')\n    B = np.loadtxt('gcp_photo.txt', delimiter=' ')\n    R, t, sc = rigid_transform_3D(A, B)\n    print(R)\n    print(t)\n    print(sc)\n    # check\n    A2 = (R.dot(A.T)).T\n    for i in range(A2.shape[0]):\n        A2[i,:] = A2[i,:] + t\n    err = A2 - B\n    err = err * err\n    err = np.sum(err)\n    rmse = math.sqrt(err / A.shape[0])\n    print(\"RMSE: {:.3f}\".format(err))\n    print(\"If RMSE is near zero, the function is correct!\")\n", "meta": {"hexsha": "dfad866a0f78467c8a5eddf26647fe601adb8f3e", "size": 1126, "ext": "py", "lang": "Python", "max_stars_repo_path": "english/data_processing/lessons/code/rigid_transform_3D.py", "max_stars_repo_name": "hrutkabence/tutorials", "max_stars_repo_head_hexsha": "bd76294860804aee8ecda5e1445464506bf02ee0", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "english/data_processing/lessons/code/rigid_transform_3D.py", "max_issues_repo_name": "hrutkabence/tutorials", "max_issues_repo_head_hexsha": "bd76294860804aee8ecda5e1445464506bf02ee0", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "english/data_processing/lessons/code/rigid_transform_3D.py", "max_forks_repo_name": "hrutkabence/tutorials", "max_forks_repo_head_hexsha": "bd76294860804aee8ecda5e1445464506bf02ee0", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4634146341, "max_line_length": 78, "alphanum_fraction": 0.5657193606, "include": true, "reason": "import numpy", "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969785415552379, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.8541841496633177}}
{"text": "import numpy as np\n\n\ndef cosine_sim(vec1, vec2):\n    \"\"\"\n    Computes the cosine similarity between two vectors\n    :param vec1:\n    :param vec2:\n    :return:\n    \"\"\"\n    cos_sim = np.dot(vec1, vec2) / \\\n        (np.linalg.norm(vec1) * np.linalg.norm(vec2))\n    return cos_sim\n\n\ndef cosine_sim_matrix(matrix, vec):\n    \"\"\"\n    Computes the cosine similarities between a matrix and a vector\n    :param matrix:\n    :param vec:\n    :return:\n    \"\"\"\n    # cos_sim is array like\n    cos_sim = np.dot(matrix, vec) / \\\n        (np.linalg.norm(matrix, axis=1) * np.linalg.norm(vec))\n    return cos_sim\n", "meta": {"hexsha": "21f5678fc6ab15b1fd09d639440eaa6b1c2c8753", "size": 594, "ext": "py", "lang": "Python", "max_stars_repo_path": "dp-search/server/word_embedding/utils.py", "max_stars_repo_name": "flaxandteal/dp-search-app", "max_stars_repo_head_hexsha": "eecdd61435d8665ea18c9f084bfa6a3c23b00221", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dp-search/server/word_embedding/utils.py", "max_issues_repo_name": "flaxandteal/dp-search-app", "max_issues_repo_head_hexsha": "eecdd61435d8665ea18c9f084bfa6a3c23b00221", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dp-search/server/word_embedding/utils.py", "max_forks_repo_name": "flaxandteal/dp-search-app", "max_forks_repo_head_hexsha": "eecdd61435d8665ea18c9f084bfa6a3c23b00221", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-12T06:43:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T12:54:16.000Z", "avg_line_length": 22.0, "max_line_length": 66, "alphanum_fraction": 0.6161616162, "include": true, "reason": "import numpy", "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854103128328, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.8541841496001056}}
{"text": "#!/usr/bin/env python3\r\n# Copyright (c) 2018 Wei-Kai Lee. All rights reserved\r\n\r\n# coding=utf-8\r\n# -*- coding: utf8 -*-\r\n\r\n\r\nimport numpy as np\r\n\r\ndef dx(x):\r\n    return x[1:]-x[0:x.size-1]\r\ndef yave(y):\r\n    xszie = y.shape[-1]\r\n    return ( y[...,1::]+y[...,0:(xszie-1):] )/2\r\ndef myNumericalIntegration(x,y):\r\n    \"\"\"\r\n    myNumericalIntegration is a function to calculate the area of \r\n    a y = function(x) by trapezoid method.\r\n    x must be ascending.\r\n\r\n    >>> x = np.linspace(0,1,100, dtype=np.float64) \r\n    >>> y = x**2\r\n    >>> value = myNumericalIntegration(x,y)\r\n    >>> print(value)\r\n    0.33335033840084355\r\n    >>> x = np.linspace(0,1,1000, dtype=np.float64) \r\n    >>> y = x**2\r\n    >>> value = myNumericalIntegration(x,y)\r\n    >>> print(value)\r\n    0.3333335003338339\r\n    >>> x = np.linspace(0,1,10000, dtype=np.float64)  \r\n    >>> y = x**2\r\n    >>> value = myNumericalIntegration(x,y)\r\n    >>> print(value)\r\n    0.3333333350003337\r\n    \"\"\"\r\n    x = np.array(x)\r\n    y = np.array(y)\r\n    return np.einsum('...i,i->...',yave(y),dx(x))\r\ndef yave2(y):\r\n    xszie = y.shape[0]\r\n    return ( y[1::,...]+y[0:(xszie-1):,...] )/2\r\ndef myNumericalIntegration2(x,y):\r\n    x = np.array(x)\r\n    y = np.array(y)\r\n    return np.einsum('i...,i->...',yave2(y),dx(x))\r\ndef myTRAPEZOIDAL(fun,x0,x1,xPts=200):\r\n    \"\"\"\r\n    myTRAPEZOIDAL is a function to calclate the integration of function f from \r\n    x0 to x1 with equal spacing. (xPts: points of x)\r\n\r\n    >>> import numpy as np\r\n    >>> f = lambda x: [np.sin(x), np.cos(x)]\r\n    >>> Int, xList, yListList = myTRAPEZOIDAL(f,0,np.pi)\r\n    >>> print(Int)\r\n    [1.99995846e+00 9.02056208e-17]\r\n    >>> Int, xList, yListList = myTRAPEZOIDAL(f,0,np.pi,xPts=300)\r\n    >>> print(Int)\r\n    [1.99998160e+00 2.68882139e-16]\r\n    >>> Int, xList, yListList = myTRAPEZOIDAL(f,0,np.pi,xPts=400)\r\n    >>> print(Int)\r\n    [1.99998967e+00 1.02348685e-16]\r\n    >>> Int, xList, yListList = myTRAPEZOIDAL(f,0,np.pi,xPts=1000)\r\n    >>> print(Int)\r\n    [ 1.99999835e+00 -8.96418356e-16]\r\n    \"\"\"\r\n    xList = np.linspace(x0, x1, num=int(xPts) )\r\n    data = np.array(fun(xList))\r\n    Int = myNumericalIntegration(xList,data)\r\n    return Int, xList, data\r\ndef myFunIntegration(f, x0, x1, tol=1e-5, recursiveLim=1e4, xCountStart=100, intfun=myTRAPEZOIDAL):\r\n    \"\"\"\r\n    >>> import numpy as np\r\n    >>> f = lambda x: [np.sin(x), np.cos(x)]\r\n    >>> Sn, err, nodes, count =  myFunIntegration(f, 0, np.pi, tol=1e-5)\r\n    >>> print(Sn)\r\n    [1.99999934e+00 2.22044605e-16]\r\n    >>> print(err)\r\n    2.781470994472901e-06\r\n    >>> print(nodes.size)\r\n    17\r\n    >>> print(count)\r\n    8\r\n    >>> f = lambda x: [ x**2, x**3]\r\n    >>> Sn, err, nodes, count =  myFunIntegration(f, -2, 2, tol=1e-5)\r\n    >>> print(Sn)\r\n    [5.333334 0.      ]\r\n    >>> print(err)\r\n    4.433938502017287e-06\r\n    >>> print(count)\r\n    24\r\n    >>> print(nodes.size)\r\n    49\r\n    >>> f = lambda x: [ np.exp(x), np.exp(x**2)]\r\n    >>> Sn, err, nodes, count =  myFunIntegration(f, -2, 2, tol=1e-5)\r\n    >>> print(Sn)\r\n    [ 7.25372109 32.90525734]\r\n    >>> print(err)\r\n    5.414152568605779e-06\r\n    >>> print(count)\r\n    68\r\n    >>> print(nodes.size)\r\n    137\r\n    \"\"\"\r\n    S, xList, yListList = intfun(f, x0, x1, xPts=xCountStart)\r\n    Sn, err, nodes, count = recursive_integration1(f, x0, x1, S, tol=tol, recursiveLim=recursiveLim, xCountStart=xCountStart, intfun=intfun)\r\n    return Sn, err, nodes, count\r\n    \r\n    # S, xList, yListList = intfun(f, x0, x1, xPts=xCountStart)\r\n    # Sn, err, xList, count = recursive_integration2(f, x0, x1, S, xList, tol=tol, recursiveLim=recursiveLim)\r\n    # return Sn, err, count\r\n\r\n    # S, xList, yListList = intfun(f, x0, x1, xPts=xCountStart)\r\n    # Sn, err, xListNew, yListListNew, count, dxmin = recursive_integration3(f, S, xList, yListList, tol=tol, recursiveLim=recursiveLim, xCountStart=xCountStart, dxMin=dxMin)\r\n    # return Sn, err, xListNew, count\r\ndef recursive_integration1(f, x0, x1, S, tol=1e-3, recursiveLim=1e4, xCountStart=100, intfun=myTRAPEZOIDAL):\r\n    \"\"\" \r\n    f: function of f(x)\r\n    [a,b] : the interval of integration\r\n    S : the previous integration result\r\n    tol : the tolerance\r\n    \r\n    This is a subfunction of adapt_simpson.\r\n    \"\"\"\r\n    xc = float(x0+x1)/2\r\n    SL, xListL, dataL = intfun(f,x0,xc,xPts=xCountStart)\r\n    SR, xListR, dataR = intfun(f,xc,x1,xPts=xCountStart)\r\n    Sn = SL+SR\r\n    err = max( np.abs(Sn-S) )\r\n    if err <= tol or recursiveLim==1:\r\n        nodes = np.array([x0,xc,x1])\r\n        count = 1\r\n        return Sn, err, nodes, count\r\n    fac = 0.5\r\n    SL, err1, nodes1, countL = recursive_integration1(f, x0, xc, SL, tol=tol*fac, recursiveLim=recursiveLim-1, xCountStart=xCountStart, intfun=intfun)\r\n    SR, err2, nodes2, countR = recursive_integration1(f, xc, x1, SR, tol=tol*(1-fac), recursiveLim=recursiveLim-1, xCountStart=xCountStart, intfun=intfun)\r\n    err = err1 + err2\r\n    nodes = np.append(nodes1, nodes2[1::])\r\n    count = countL+1 if countL>=countR else countR+1 # countL+countR # countL+1 if countL>=countR else countR+1\r\n    Sn = SL+SR\r\n    return Sn, err, nodes, count\r\ndef myMidpointList_Integration2(f, xList, S):\r\n    # Mid point\r\n    xList = np.array(xList)\r\n    xList2 = (xList[0:xList.size-1]+xList[1:xList.size])/2\r\n    data = f(xList2)\r\n    # Sum\r\n    temptsum = np.einsum('...i,i->...', data, dx(xList) ) \r\n    Sn = (S+temptsum)/2\r\n    # Merge List\r\n    xListNew = np.zeros( xList.size+xList2.size, dtype=xList.dtype )\r\n    xListNew[0::2] = xList\r\n    xListNew[1::2] = xList2\r\n    return Sn, xListNew\r\ndef recursive_integration2(f, x0, x1, S, xList, tol=1e-5, recursiveLim=1e4):\r\n    \"\"\" \r\n    f: function of f(x)\r\n    [a,b] : the interval of integration\r\n    S : the previous integration result\r\n    tol : the tolerance\r\n    \r\n    This is a subfunction of adapt_simpson.\r\n    \"\"\"\r\n    Sn, xListNew = myMidpointList_Integration2(f, xList, S)\r\n    err = max( np.abs(Sn-S) )\r\n    if err <= tol or recursiveLim==1:\r\n        count = 1\r\n        return Sn, err, xListNew, count\r\n    Sn, err, xListNew, count = recursive_integration2(f, x0, x1, Sn, xList=xListNew, tol=tol, recursiveLim=recursiveLim-1)\r\n    count = count + 1\r\n    return Sn, err, xListNew, count\r\ndef myMidpointList_Integration3(f, xList, yListList):\r\n    # Mid point\r\n    xList = np.array(xList)\r\n    xList2 = (xList[0:xList.size-1]+xList[1:xList.size])/2\r\n    data = f(xList2)\r\n    # Sum\r\n    temptsum = np.einsum('...i,i->...', data, dx(xList) ) \r\n    # Merge x List\r\n    xListNew = np.zeros( xList.size+xList2.size, dtype=xList.dtype )\r\n    xListNew[0::2] = xList\r\n    xListNew[1::2] = xList2\r\n    # Merge y List\r\n    yListListNew = np.zeros( (yListList.shape[0], xListNew.size) , dtype=yListList.dtype)\r\n    yListListNew[:,0::2] = yListList\r\n    yListListNew[:,1::2] = data\r\n    # Sum\r\n    Sn = myNumericalIntegration(xListNew,yListListNew)\r\n    return Sn, xListNew, yListListNew\r\ndef recursive_integration3(f, S, xList, yListList, tol=1e-5, recursiveLim=1e4, xCountStart=100, dxMin=None):\r\n    \"\"\" \r\n    f: function of f(x)\r\n    [a,b] : the interval of integration\r\n    S : the previous integration result\r\n    tol : the tolerance\r\n    \r\n    This is a subfunction of adapt_simpson.\r\n    \"\"\"\r\n    indMid = int(len(xList)/2)\r\n    SL, xListL, yListListL = myMidpointList_Integration3(f, xList[:indMid+1:], yListList[:,:indMid+1:] )\r\n    SR, xListR, yListListR = myMidpointList_Integration3(f, xList[indMid::],   yListList[:,indMid::] )\r\n    Sn = SL+SR\r\n    err = max( np.abs(Sn-S) )\r\n    # End Case\r\n    xListNew = np.append( xListL, xListR[1::] )\r\n    dxmin = min(dx(xListNew))\r\n    if err <= tol or recursiveLim==1 or dxMin==None or dxmin<dxMin:\r\n        count = 1\r\n        yListListNew = np.append( yListListL, yListListR[:,1::] ) \r\n        return Sn, err, xListNew, yListListNew, count, dxmin\r\n    # Iterative Case\r\n    sL, sR = np.sum(SL), np.sum(SR)\r\n    fac = sL/(sL+sR) if (sL+sR)!=0 else 0.5\r\n    SL, errL, xListL, yListListL, countL, dxL = recursive_integration3(f, SL, xList=xListL, yListList=yListListL, tol=tol*fac, recursiveLim=recursiveLim-1, dxMin=dxMin)\r\n    SR, errR, xListR, yListListR, countR, dxR = recursive_integration3(f, SR, xList=xListR, yListList=yListListR, tol=tol*(1-fac), recursiveLim=recursiveLim-1, dxMin=dxMin)\r\n    Sn = SL+SR\r\n    err = errL + errR\r\n    count = countL+1 if countL>countR else countR+1 #countL+countR # countL+1 if countL>countR else countR+1\r\n    xListNew = np.append( xListL, xListR[1::] )\r\n    dxmin = dxL if dxL<dxR else dxR\r\n    yListListNew = np.append( yListListL, yListListR[:,1::] ) \r\n    return Sn, err, xListNew, yListListNew, count, dxmin\r\n\r\nif __name__ == '__main__':\r\n    import doctest\r\n    doctest.testmod()\r\n    \"\"\"\r\n    x = []\r\n    y = []\r\n    value = myNumericalIntegration(x,y)\r\n    \"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "f77dd12612e1640523b477b819c62e57dc3e4817", "size": 8768, "ext": "py", "lang": "Python", "max_stars_repo_path": "Help/myNumericalIntegration.py", "max_stars_repo_name": "d04943016/ColorScience", "max_stars_repo_head_hexsha": "b874d70c217249ec47a6017b47c5e3ca2008a6a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Help/myNumericalIntegration.py", "max_issues_repo_name": "d04943016/ColorScience", "max_issues_repo_head_hexsha": "b874d70c217249ec47a6017b47c5e3ca2008a6a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Help/myNumericalIntegration.py", "max_forks_repo_name": "d04943016/ColorScience", "max_forks_repo_head_hexsha": "b874d70c217249ec47a6017b47c5e3ca2008a6a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3817427386, "max_line_length": 175, "alphanum_fraction": 0.6067518248, "include": true, "reason": "import numpy", "num_tokens": 3036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.9046505421702797, "lm_q1q2_score": 0.8541501030141584}}
{"text": "import math\nimport pandas as pd\nimport numpy as np\nimport statistics\nimport matplotlib.pyplot as plt\n\na = 51749\nb = 1352\nm = 244944\nx0 = 3\n\n# Plots Histogram along side acutal distribution\ndef plotHistogram(sample, method):\n    hist, bins, _ = plt.hist(sample, density=True, bins=100)\n    \n    plt.title('Sample Distribution for N = {}, {}'.format(len(sample), method))\n    plt.show()\n\n\n### Generates x_i's from given recurrence\ndef generateX(a, curr, N):\n    x = []\n    x.append(curr);\n    for i in range (N-1):\n        prev = x[len(x)-1]\n        curr = (a*prev + b) % m\n        x.append(curr)\n\n    return x\n\n### Generates u_i's from given recurrence\ndef generateU(x):\n    ulist = []\n    for i in x:\n        ulist.append(i/m)\n    return ulist\n\ndef LCG(N):\n    curr = 3\n    x = generateX(a, curr, N)\n    ulist = generateU(x)\n\n    plotHistogram(ulist, 'Linear Congruence Generator')\n\ndef generateVC(N):\n    data = [i for i in range(N)]\n    \n    sample = []\n    for t in data:\n        binary = []\n        n = t\n\n        if n==0:\n            binary.append(0)\n\n        while n!=0:\n            bit = n%2\n            binary.append(bit)\n            n = n//2\n\n        curr = 0.00\n        temp = 1.00/2.00\n        for mult in binary:\n            curr += mult*temp\n            temp = temp/2\n\n        sample.append(curr)\n\n    df = pd.DataFrame()\n    df['N'] = pd.Series([i for i in range(N)])\n    df['Van der Corput(N)'] = pd.Series(sample)\n\n    return df\n\n\ndef generateHalton(N):\n    data = [i for i in range(N)]\n    \n    sampleX = []\n    sampleY = []\n    for t in data:\n        binary = []\n        ternary = []\n        \n        n = t\n        if n==0:\n            binary.append(0)\n\n        while n!=0:\n            bit = n%2\n            binary.append(bit)\n            n = n//2\n        \n        n = t\n        if n==0:\n            ternary.append(0)\n\n        while n!=0:\n            bit = n%3\n            ternary.append(bit)\n            n = n//3\n\n        curr = 0.00\n        temp = 1.00/2.00\n        for mult in binary:\n            curr += mult*temp\n            temp = temp/2.00\n        phi_2 = curr\n        \n        curr = 0.00\n        temp = 1.00/3.00\n        for mult in ternary:\n            curr += mult*temp\n            temp = temp/3.00\n        phi_3 = curr\n        \n        sampleX.append(phi_2)\n        sampleY.append(phi_3)\n\n    return sampleX, sampleY\n\ndef partA():\n    df1 = generateVC(25)\n    df2 = generateVC(1000)\n\n    print(\"The first 25 values of the Van der Corput sequence are: \")\n    print(df1)\n\n    xAxis = []\n    yAxis = []\n\n    for i in range(len(df2['Van der Corput(N)'])-1):\n        xAxis.append(df2['Van der Corput(N)'][i])\n        yAxis.append(df2['Van der Corput(N)'][i+1])\n\n    plt.plot(xAxis, yAxis)\n    plt.xlabel('x(i)')\n    plt.ylabel('x(i+1)')\n    plt.show()\n\n    df3 = generateVC(100)\n    plotHistogram(df3['Van der Corput(N)'], 'Van der Corput')\n    LCG(100)\n\n    df4 = generateVC(100000)\n    plotHistogram(df4['Van der Corput(N)'], 'Van der Corput')\n    LCG(100000)\n\n\ndef partB():\n    H_sample_X, H_sample_Y = generateHalton(100)\n\n    plt.plot(H_sample_X, H_sample_Y)\n    plt.title('Halton Sequence Actual')\n    plt.xlabel('phi_2(i)')\n    plt.ylabel('phi_3(i)')\n    plt.show()\n\n    plt.scatter(H_sample_X, H_sample_Y)\n    plt.title('Halton Sequence Scattered')\n    plt.xlabel('phi_2(i)')\n    plt.ylabel('phi_3(i)')\n    plt.show()\n\n    H_sample_X, H_sample_Y = generateHalton(10000)\n\n    plt.plot(H_sample_X, H_sample_Y)\n    plt.title('Halton Sequence Actual')\n    plt.xlabel('phi_2(i)')\n    plt.ylabel('phi_3(i)')\n    plt.show()\n\n    plt.scatter(H_sample_X, H_sample_Y)\n    plt.title('Halton Sequence Scattered')\n    plt.xlabel('phi_2(i)')\n    plt.ylabel('phi_3(i)')\n    plt.show()\n\n\ndef main():\n    partA()\n    partB()\n\n\nif __name__ == '__main__':\n    main()\n\n\n\n\n", "meta": {"hexsha": "5311d42f742962a5dad609a942f2771d4770295e", "size": 3785, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab 12/180123019_Jay_Sabale.py", "max_stars_repo_name": "ElProfesor18/MA-323_Monte_Carlo_Simulation", "max_stars_repo_head_hexsha": "24efd6ba1d50b00100d15ec2ef5d3fc5217f93a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab 12/180123019_Jay_Sabale.py", "max_issues_repo_name": "ElProfesor18/MA-323_Monte_Carlo_Simulation", "max_issues_repo_head_hexsha": "24efd6ba1d50b00100d15ec2ef5d3fc5217f93a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab 12/180123019_Jay_Sabale.py", "max_forks_repo_name": "ElProfesor18/MA-323_Monte_Carlo_Simulation", "max_forks_repo_head_hexsha": "24efd6ba1d50b00100d15ec2ef5d3fc5217f93a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8167539267, "max_line_length": 79, "alphanum_fraction": 0.5368560106, "include": true, "reason": "import numpy", "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.9046505312448598, "lm_q1q2_score": 0.8541500998037035}}
{"text": "__all__ = ['cholInvert']\nimport numpy as np\n\ndef cholInvert(A):\n    \"\"\"\n    Return the inverse of a symmetric matrix using the Cholesky decomposition. The log-determinant is\n    also returned\n    \n    Args:\n        A : (N,N) matrix\n    \n    Returns:\n        AInv: matrix inverse\n        logDeterminant: logarithm of the determinant of the matrix \n    \"\"\"\n    L = np.linalg.cholesky(A)\n    LInv = np.linalg.inv(L)\n    AInv = np.dot(LInv.T, LInv)\n    logDeterminant = -2.0 * np.sum(np.log(np.diag(LInv)))   # Why the minus sign?\n    return AInv, logDeterminant\n", "meta": {"hexsha": "a6e6df4e5cb3259da28f511add7eb3c19ccb7a05", "size": 559, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyiacsun/linalg/cholInvert.py", "max_stars_repo_name": "aasensio/pyiacsun", "max_stars_repo_head_hexsha": "56bdaca98461be7b927f8d5fbbc9e64517c889fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-10-30T17:38:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-04T19:11:34.000Z", "max_issues_repo_path": "pyiacsun/linalg/cholInvert.py", "max_issues_repo_name": "aasensio/pyiacsun", "max_issues_repo_head_hexsha": "56bdaca98461be7b927f8d5fbbc9e64517c889fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-10-15T21:55:46.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-16T19:04:54.000Z", "max_forks_repo_path": "pyiacsun/linalg/cholInvert.py", "max_forks_repo_name": "aasensio/pyiacsun", "max_forks_repo_head_hexsha": "56bdaca98461be7b927f8d5fbbc9e64517c889fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-10-18T17:20:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-10T00:47:36.000Z", "avg_line_length": 26.619047619, "max_line_length": 101, "alphanum_fraction": 0.633273703, "include": true, "reason": "import numpy", "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9715639669551472, "lm_q2_score": 0.8791467675095294, "lm_q1q2_score": 0.8541473209773529}}
{"text": "import numpy as np\n\n\ndef gaussian_1d(height: float = 1, mu: float = 0, sigma: float = 2, offset: float = 0):\n    \"\"\"\n    Return a parametrized 1D Gaussian function.\n\n    Parameters:\n        height: float\n            Distance between the lowest and peak value of the Gaussian.\n        mu: float\n            Expected value of the Gaussian.\n        sigma: float\n            Width of the Gaussian.\n        offset: float\n            Shifts the Gaussian `up` or `down` i.e. the background signal.\n    \"\"\"\n    return lambda x: offset + height * np.exp(-((x - mu) ** 2 / (2 * sigma ** 2)))\n\n\ndef gaussian_3d(\n    height: float = 1,\n    mu_z: float = 0,\n    mu_y: float = 0,\n    mu_x: float = 0,\n    sigma_z: float = 2,\n    sigma_y: float = 2,\n    sigma_x: float = 2,\n    offset: float = 0,\n):\n    \"\"\"\n    Return a parametrized 3D Gaussian function.\n\n    Parameters:\n        height: float\n            Distance between the lowest and peak value of the Gaussian.\n        mu_z: float\n            Expected value of the Gaussian in Z dimension.\n        mu_y: float\n            Expected value of the Gaussian in Y dimension.\n        mu_x: float\n            Expected value of the Gaussian in X dimension.\n        sigma_z: float\n            Width of the Gaussian in Z dimension.\n        sigma_y: float\n            Width of the Gaussian in Y dimension.\n        sigma_x: float\n            Width of the Gaussian in X dimension.\n        offset: float\n            Shifts the Gaussian `up` or `down` i.e. the background signal.\n    \"\"\"\n    return lambda z, y, x: offset + height * np.exp(\n        -(\n            ((z - mu_z) ** 2 / (2 * sigma_z ** 2))\n            + ((y - mu_y) ** 2 / (2 * sigma_y ** 2))\n            + ((x - mu_x) ** 2 / (2 * sigma_x ** 2))\n        )\n    )\n", "meta": {"hexsha": "f34e7ce149ed9d86192bf3abcaca0937089d89f2", "size": 1750, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/napari_psf_analysis/utils/gaussians.py", "max_stars_repo_name": "fmi-faim/napari-psf-measures", "max_stars_repo_head_hexsha": "6ec477b82edf1eb484f8ac79747e7aab54d7d270", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-30T19:19:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:19:11.000Z", "max_issues_repo_path": "src/napari_psf_analysis/utils/gaussians.py", "max_issues_repo_name": "fmi-faim/napari-psf-measures", "max_issues_repo_head_hexsha": "6ec477b82edf1eb484f8ac79747e7aab54d7d270", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-31T07:28:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:28:21.000Z", "max_forks_repo_path": "src/napari_psf_analysis/utils/gaussians.py", "max_forks_repo_name": "fmi-faim/napari-psf-measures", "max_forks_repo_head_hexsha": "6ec477b82edf1eb484f8ac79747e7aab54d7d270", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6610169492, "max_line_length": 87, "alphanum_fraction": 0.5445714286, "include": true, "reason": "import numpy", "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639669551474, "lm_q2_score": 0.8791467627598857, "lm_q1q2_score": 0.8541473163627703}}
{"text": "from statistics import mean \nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport random\n\nstyle.use('fivethirtyeight')\nxs = np.array([1,2,3,4,5,6], dtype= np.float64)\nys = np.array([5,4,6,5,6,7], dtype= np.float64)\n\ndef create_dataset(hm, varinace, step=2, correlation= False):\n\tval = 1 \n\tys = []\n\tfor i in range(hm):\n\t\ty = val + random.randrange(-varinace, varinace)\n\t\tys.append(y)\n\t\tif correlation and correlation == 'pos':\n\t\t\tval += step\n\t\telif correlation and correlation =='neg':\n\t\t\tval -= step\n\n\txs = [i for i in range (len(ys))]\n\treturn np.array(xs, dtype= np.float64), np.array(ys, dtype= np.float64)\n\ndef best_fit_slope_and_intercept(xs, ys):\n\tm = ( ((mean(xs) * mean(ys)) - mean(xs * ys)) / \n\t\t((mean(xs)**2) - mean(xs * xs)) ) \n\tb = mean(ys) - m * mean(xs)\n\treturn m,b\n\ndef squared_error(ys_orig, ys_line):\n\treturn sum((ys_line - ys_orig) **2)\n\ndef coeffiecent_of_determination(ys_orig, ys_line):\n\ty_mean_line = [mean(ys_orig) for y in ys_orig]\n\tsquared_error_regr = squared_error(ys_orig, ys_line)\n\tsquared_error_y_mean = squared_error(ys_orig, y_mean_line)\n\treturn 1- (squared_error_regr / squared_error_y_mean)\n\nxs, ys = create_dataset(40, 5, 2, correlation='pos')\n\nm,b = best_fit_slope_and_intercept(xs, ys)\n\nregression_line = [(m*x) + b for x in xs]\n\npredict_x = 8\npredict_y = (m*predict_x) + b\nr_squared = coeffiecent_of_determination(ys, regression_line)\nprint(r_squared)\n\nplt.scatter(xs,ys)\nplt.plot(xs, regression_line)\nplt.scatter(predict_x, predict_y, s = 100 ,color ='g')\nplt.show()", "meta": {"hexsha": "cbcc4b734cd1d3070b1a00a6396e4c2d229cb80b", "size": 1539, "ext": "py", "lang": "Python", "max_stars_repo_path": "Sentdex_Akash/Linear_regression_code.py", "max_stars_repo_name": "akash9182/My-Machine-Learning-work", "max_stars_repo_head_hexsha": "905622ff04b32a3fceba53811e2d73424ffdb6ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sentdex_Akash/Linear_regression_code.py", "max_issues_repo_name": "akash9182/My-Machine-Learning-work", "max_issues_repo_head_hexsha": "905622ff04b32a3fceba53811e2d73424ffdb6ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sentdex_Akash/Linear_regression_code.py", "max_forks_repo_name": "akash9182/My-Machine-Learning-work", "max_forks_repo_head_hexsha": "905622ff04b32a3fceba53811e2d73424ffdb6ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5, "max_line_length": 72, "alphanum_fraction": 0.706302794, "include": true, "reason": "import numpy", "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976795, "lm_q2_score": 0.8872046041554922, "lm_q1q2_score": 0.8540880197452099}}
{"text": "#!/usr/bin/python3\n\n\"\"\"\n    The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.\nThere are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.\nHow many circular primes are there below one million?\n\"\"\"\n\nimport numpy as np\n\ndef isprime(num: int) -> bool:\n    for i in range(2, int(np.sqrt(num))+1):\n        if num%i == 0:\n            return False\n    return True\n\ndef rotate(num: int) -> set:\n    rot = {num}\n    length = len(str(num))\n    k = 0\n    while k < length:\n        tmp = list(str(num))\n        dig = tmp[0]\n        tmp[:] = tmp[1:]\n        tmp.append(dig)\n        num = ''.join(tmp)\n        rot.add(int(num))\n        k = k + 1\n\n    return rot\n\ndef euler35() -> int:\n    tot = 0\n    c_primes = [2]\n    flag = False\n    for i in range(3, 10**6, 2):\n        if isprime(i):\n            flag = True\n            tmp = set()\n            cps = rotate(i)\n            for x in cps:\n                if isprime(x):\n                    tmp.add(x)\n                else:\n                    flag = False\n                    break\n        if flag:\n            c_primes.extend(list(tmp))\n\n    return len(set(c_primes))\n\ntot = euler35()\nprint(tot)\n", "meta": {"hexsha": "4400059a3e93b485f3924881b3fe16cd51c435bb", "size": 1240, "ext": "py", "lang": "Python", "max_stars_repo_path": "euler35.py", "max_stars_repo_name": "NasreenKhalid/project_euler", "max_stars_repo_head_hexsha": "175b81c974677e2596effb1316f09f23d8e5064a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-10-04T22:10:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-02T22:18:12.000Z", "max_issues_repo_path": "euler35.py", "max_issues_repo_name": "NasreenKhalid/project_euler", "max_issues_repo_head_hexsha": "175b81c974677e2596effb1316f09f23d8e5064a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-10-04T13:08:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-31T21:20:50.000Z", "max_forks_repo_path": "euler35.py", "max_forks_repo_name": "NasreenKhalid/project_euler", "max_forks_repo_head_hexsha": "175b81c974677e2596effb1316f09f23d8e5064a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2020-10-04T13:13:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T11:19:23.000Z", "avg_line_length": 22.962962963, "max_line_length": 125, "alphanum_fraction": 0.4983870968, "include": true, "reason": "import numpy", "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.8872046026642944, "lm_q1q2_score": 0.8540880183096737}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov  3 13:06:11 2021\r\n\r\n@author: Oliver\r\n\"\"\"\r\nimport numpy as np\r\nfrom scipy.integrate import quad\r\nimport matplotlib.pyplot as plt\r\n\r\n\"\"\"__________________REFERENCE SOLUTION________________\"\"\"\r\n\"\"\"DONE\"\"\"\r\n\r\ndef integrand(x):\r\n    return x**2+4*x-12\r\nans, err = quad(integrand, -10,10)\r\ndef integral(x):\r\n    return 1/3*x**3+2*x**2-12*x\r\nx= np.linspace(1,1000,8000)\r\nplt.plot(x,integral(x),'g',label ='reference')\r\nplt.legend()\r\nplt.show()\r\nprint(f'The analytical solution to the integral is: {ans}')\r\nprint()\r\n\r\n\r\n# Excercise 1: Implement the Midpoint/rectangular Rule code and execute\r\n# it to integrate the function x^2+4x-12 in the domain -10<x<10\r\n\r\n\r\n\"\"\"______________________________________________________________________\"\"\"\r\ndef calculate_dx(a,b,n):\r\n    return (b-a)/float(n)\r\n\"\"\"DONE\"\"\"\r\n\r\ndef rect_rule(f,a,b,n):\r\n    total = 0.0\r\n    dx = calculate_dx(a,b,n)\r\n    t = []\r\n    for i in range(0,n):\r\n        total += abs(f((a+(i*dx))))\r\n        t.append(total)\r\n    plt.plot(range(n),t)\r\n    plt.show()\r\n    return dx*total\r\n\r\ndef f(x):\r\n    return x**2+4*x-12\r\n\r\nprint(f' Excercise 1, midpoint/rectangular rule result: {rect_rule(f,-10,10,10000)}')\r\n\r\nprint(f'Analitycal - midpoint/rectangular rule result: {abs(rect_rule(f,-10,10,10000) - ans)}')\r\n\r\nprint(f'Relative error midpoint/rectangular result: {abs(ans - rect_rule(f,-10,10,10000) )/abs(rect_rule(f,-10,10,10000))}')\r\nprint()\r\n\r\n\r\n\"\"\"______________________________________________________________________\"\"\"\r\n\r\n#Excercise 2: Implement this trapezoid Rule code and execute it to integrate\r\n# the function x**2 +4*x-12 in the domain -10<x<10 (enter inputs first)\r\n\"\"\"NOT DONE PLOTTING\"\"\"\r\ndef trapz(f,a,b,N=50):\r\n    x = np.linspace(a,b,N) # N+1 points make N subintervals\r\n    print(x)\r\n    y = f(x)\r\n    y_right = y[1:] # right endpoints\r\n    y_left = y[:-1] # left endpoints\r\n    total = []\r\n    for i in range(N+1,1,-1):\r\n        dx = (b-a)/i\r\n        Z = (dx/2) *np.sum(y_right+y_left)\r\n        total.append(Z)\r\n    plt.plot(x,total,label = 'traps')\r\n    plt.legend()\r\n    plt.show()\r\n    # while i <= N:\r\n    #     k += 2\r\n    #     g.append((dx/2)*np.sum(f(k)+f(k+1))          \r\n    # plt.plot(range(N),g)\r\n    # plt.show\r\n    return Z\r\n\r\na= -10\r\nb= 10\r\nn= 10000\r\nprint(f' The trapezoidal rule result is: {trapz(f,a,b,n)}')\r\n\r\nprint(f'Analitycal - trapezoidal rule: {abs(trapz(f,a,b,n) - ans)}')\r\n\r\nprint(f'Relative error trapezoidal rule result: {abs(ans - trapz(f,a,b,n) )/abs(trapz(f,a,b,n))}')\r\nprint()\r\n\r\n\"\"\"______________________________________________________________________\"\"\"\r\n\r\n\r\n# Excercise 3: Implement this Simpson's One Third Rule code and execute it\r\n# to integrate the funciton x**2+4x-12 in the domain -10<x<10\r\n\"\"\"NOT DONE PLOTTING\"\"\"\r\ndef simps(f,a,b,N=50):\r\n    if N % 2 == 1:\r\n        raise ValueError(\"N must be an even integer\")\r\n    t=[]\r\n    x = np.linspace(a,b,N+1)\r\n    y = f(x)\r\n    for i in range(1,N+2,1):\r\n        dx = (b-a)/i\r\n        S = dx/3 * np.sum(y[0:-1:2] + 4*y[1::2] + y[2::2]) # s[i:j:k] - \"slice of s from i to j with step k\r\n        t.append(S)\r\n    plt.plot(x,t)\r\n    plt.show()\r\n    return S # y[2::2] - start at the 2nd element and skip through in steps of 2 each time\r\n\r\nf = lambda x: x**2+4*x-12\r\nsolution = simps(f,-10,10,10000)\r\n\r\nprint(f' The simpson one third rule solution: {solution}')\r\n\r\nprint(f'Analitycal - simpson one third rule: {abs(solution - ans)}')\r\n\r\nprint(f'Relative error simpson one third rule result: {abs(ans - solution )/abs(solution)}')\r\nprint()\r\n\r\n\"\"\"______________________________________________________________________\"\"\"\r\n\r\n\r\n# Exercise 4: Implement this Simpson’s three eightths Rule code and execute it to \r\n# integrate the function x2 +4x – 12 in the domain -10 < x < 10 (enter inputs first).\r\n\"\"\"DONE\"\"\"\r\ndef func(x): \r\n    return abs(x**2+4*x-12)\r\n\r\ndef calculate(lower_limit, upper_limit, interval_limit ): \r\n    interval_size = (float(upper_limit - lower_limit) / interval_limit) \r\n    sum = func(lower_limit) + func(upper_limit); \r\n    # Calculates value till integral limit \r\n    n=0\r\n    k = []\r\n    t = []\r\n    for i in range(1, interval_limit ): \r\n        if (i % 3 == 0): \r\n            k.append(n)\r\n            n +=1\r\n            sum = sum + 2 * func(lower_limit + i * interval_size)\r\n            t.append(sum)\r\n        else: \r\n            sum = sum + 3 * func(lower_limit + i * interval_size) \r\n    plt.plot(k,t,'r')\r\n    return ((float( 3 * interval_size) / 8 ) * sum ) \r\n\r\n# driver function \r\n\r\ninterval_limit = 10000\r\nlower_limit = -10\r\nupper_limit = 10\r\nintegral_res = calculate(lower_limit, upper_limit, interval_limit) \r\n\r\n# rounding the final answer to 6 decimal places \r\n\r\nprint (f' The simpson three eigthths rule solution: {round(integral_res, 6)}') \r\n\r\nprint(f'Analitycal - three eightths rule: {abs(round(integral_res, 6) - ans)}')\r\n\r\nprint(f'Relative error simpson three eightths rule result: {abs(ans - round(integral_res, 6) )/abs(round(integral_res, 6))}')\r\n\r\n# Plot the evolution of the integral value as a function of the number of \r\n# integration intervals for each technique (Hint: you will have to modify each \r\n# code to run for different values of N and plot the integral obtained for each \r\n# run). Use arrays to store values and matplotlib to plot Integral v. N).\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n    ", "meta": {"hexsha": "86cde4c0a1d319056b43c4ee487dafb7379bb988", "size": 5337, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week 6 Tutorial question 1.py", "max_stars_repo_name": "oliver779/Computational_Methods_Course", "max_stars_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week 6 Tutorial question 1.py", "max_issues_repo_name": "oliver779/Computational_Methods_Course", "max_issues_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week 6 Tutorial question 1.py", "max_forks_repo_name": "oliver779/Computational_Methods_Course", "max_forks_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0054347826, "max_line_length": 126, "alphanum_fraction": 0.626943976, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731083722524, "lm_q2_score": 0.8872046026642944, "lm_q1q2_score": 0.8540880126090054}}
{"text": "import math\nimport decimal as dec\nimport numpy as np\n\n\nclass MethodResult:\n    number_of_steps = 0\n    root = 0\n\n\ndef f1(x):\n    return dec.Decimal(math.cos(x) * math.cosh(x))\n\n\ndef f1der(x):\n    return dec.Decimal(math.cos(x) * math.sinh(x) - math.sin(x) * math.cosh(x))\n\n\ndef f2(x):\n    if math.isclose(x, 0.0, abs_tol=1e-9):\n        return dec.Decimal(10000000)\n    else:\n        return dec.Decimal(1/x) - dec.Decimal(math.tan(x))\n\n\ndef f2der(x):\n    return dec.Decimal(-1/x**2) - dec.Decimal(1 / math.cos(x)**2)\n\n\ndef f3(x):\n    return dec.Decimal(math.pow(2, -x) + math.pow(math.e, x) + 2*math.cos(x)) - 6\n\n\ndef f3der(x):\n    return dec.Decimal(math.pow(math.e, x) - math.pow(2, -x) * math.log(2, math.e) - 2 * math.sin(x))\n\n\ndef f4(x):\n    return dec.Decimal(x**3 - 3 * x + 1)\n\n\ndef f4der(x):\n    return dec.Decimal(3 * x**2 - 3)\n\n\ndef bisection(function, float_precision, result_precision, a, b):\n    f_a = function(a)\n    f_b = function(b)\n\n    if np.sign(f_a) == np.sign(f_b):\n        print(\"Function has same signs at \" + a + \" and \" + b + \"!\")\n        return None\n\n    dec.getcontext().prec = float_precision\n    error = dec.Decimal(b) - dec.Decimal(a)\n    number_of_steps = 0\n\n    while not math.isclose(error, 0, abs_tol=result_precision):\n        error = dec.Decimal(b) - dec.Decimal(a)\n        error = error / 2\n        c = dec.Decimal(a) + error\n        f_c = function(c)\n\n        number_of_steps += 1\n\n        if math.isclose(error, 0, abs_tol=result_precision):\n            result = MethodResult()\n            result.number_of_steps = number_of_steps\n            result.root = c\n            return result\n\n        if np.sign(f_a) != np.sign(f_c):\n            b = c\n        else:\n            a = c\n            f_a = f_c\n\n\ndef Newton_method(function, function_derivative, float_precision, max_iterations, result_precision, x):\n    dec.getcontext().prec = float_precision\n    x = dec.Decimal(x)\n\n    number_of_steps = 0\n\n    while (not math.isclose(function(x), 0, abs_tol=result_precision)) and (number_of_steps < max_iterations):\n        x = x - function(x) / function_derivative(x)\n        number_of_steps += 1\n\n    if number_of_steps == max_iterations:\n        print(\"Maximum number of iterations achieved!\")\n        result = MethodResult()\n        result.number_of_steps = number_of_steps\n        result.root = x\n        return result\n\n    result = MethodResult()\n    result.number_of_steps = number_of_steps\n    result.root = x\n    return result\n\n\ndef secant_method(function, float_precision, max_iterations, result_precision, a, b):\n    f_a = function(a)\n    f_b = function(b)\n\n    if np.sign(f_a) == np.sign(f_b):\n        print(\"Function has same signs at \" + a + \" and \" + b + \"!\")\n        return None\n\n    dec.getcontext().prec = float_precision\n\n    a_n = dec.Decimal(a)\n    b_n = dec.Decimal(b)\n\n    root = a_n - f_a * (b_n - a_n) / (f_b - f_a)\n    f_root = function(root)\n\n    number_of_steps = 1\n\n    while (not math.isclose(f_root, 0, abs_tol=result_precision)) and (number_of_steps < max_iterations):\n        f_a = function(a_n)\n        f_b = function(b_n)\n\n        root = a_n - f_a * (b_n - a_n) / (f_b - f_a)\n        f_root = function(root)\n\n        number_of_steps += 1\n\n        if np.sign(f_a) != np.sign(f_root):\n            b_n = root\n        elif np.sign(f_b) != np.sign(f_root):\n            a_n = root\n        elif math.isclose(f_root, 0, abs_tol=result_precision):\n            result = MethodResult()\n            result.number_of_steps = number_of_steps\n            result.root = root\n            return result\n\n    if number_of_steps == max_iterations:\n        print(\"Maximum number of iterations achieved!\")\n        result = MethodResult()\n        result.number_of_steps = number_of_steps\n        result.root = root\n        return result\n\n    result = MethodResult()\n    result.number_of_steps = number_of_steps\n    result.root = root\n    return result\n\n\nfor i in [math.pow(10, -7), math.pow(10, -15), math.pow(10, -33)]:\n    bisection_result = bisection(f1, 16, 1e-8, 1.5*math.pi, 2*math.pi)\n    Newton_method_result = Newton_method(f1, f1der, 16, 50, 1e-8, (1.5*math.pi+2*math.pi)/2)\n    secant_result = secant_method(f1, 16, 50, 1e-8, 1.5*math.pi, 2*math.pi)\n\n    print(\"Function f1, precision : \" + str(i))\n    print(str(bisection_result.root) + \" \" + str(bisection_result.number_of_steps))\n    print(str(Newton_method_result.root) + \" \" + str(Newton_method_result.number_of_steps))\n    print(str(secant_result.root) + \" \" + str(secant_result.number_of_steps))\n\n    print(\"\")\n\n    bisection_result = bisection(f2, 16, 1e-8, 0, math.pi/2)\n    Newton_method_result = Newton_method(f2, f2der, 16, 50, 1e-8, math.pi/4)\n    secant_result = secant_method(f2, 16, 50, 1e-8, 0, math.pi/2)\n\n    print(\"Function f2, precision : \" + str(i))\n    print(str(bisection_result.root) + \" \" + str(bisection_result.number_of_steps))\n    print(str(Newton_method_result.root) + \" \" + str(Newton_method_result.number_of_steps))\n    print(str(secant_result.root) + \" \" + str(secant_result.number_of_steps))\n\n    print(\"\")\n\n    bisection_result = bisection(f3, 16, 1e-8, 1, 3)\n    Newton_method_result = Newton_method(f3, f3der, 16, 50, 1e-8, 2)\n    secant_result = secant_method(f3, 16, 50, 1e-8, 1, 3)\n\n    print(\"Function f3, precision : \" + str(i))\n    print(str(bisection_result.root) + \" \" + str(bisection_result.number_of_steps))\n    print(str(Newton_method_result.root) + \" \" + str(Newton_method_result.number_of_steps))\n    print(str(secant_result.root) + \" \" + str(secant_result.number_of_steps))\n\n    print(\"\\n\")\n", "meta": {"hexsha": "7f8fdb78045bfb18a3fdc2d53e8306a5b46f5682", "size": 5546, "ext": "py", "lang": "Python", "max_stars_repo_path": "lab3_nonlinear_equations/main.py", "max_stars_repo_name": "j-adamczyk/Numerical-Algorithms", "max_stars_repo_head_hexsha": "47cfa8154bab448d1bf87b892d83e45c68dd2e2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-03-16T11:23:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-16T21:04:01.000Z", "max_issues_repo_path": "lab3_nonlinear_equations/main.py", "max_issues_repo_name": "j-adamczyk/Numerical-Algorithms", "max_issues_repo_head_hexsha": "47cfa8154bab448d1bf87b892d83e45c68dd2e2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab3_nonlinear_equations/main.py", "max_forks_repo_name": "j-adamczyk/Numerical-Algorithms", "max_forks_repo_head_hexsha": "47cfa8154bab448d1bf87b892d83e45c68dd2e2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9783783784, "max_line_length": 110, "alphanum_fraction": 0.6265777137, "include": true, "reason": "import numpy", "num_tokens": 1602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731094431571, "lm_q2_score": 0.8872045922259088, "lm_q1q2_score": 0.8540880035103638}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Feb  3 16:08:35 2021\r\n\r\n@author: LI Zhengyang\r\n\"\"\"\r\n\r\n\"\"\"\r\nCutting Stock Problem\r\nThe length of a raw pipe is 218cm. Now the client wants 44 pipes of 81cm, 3 pipes of 70cm, 48 pipes of 68cm, what is the best cutting plan?\r\n\r\nThis problem can be formulated as an mixed integer linear programming (MILP) model:\r\n    parameter:\r\n        x(ni) the number of times item i is cut on roll n.\r\n        y(n) = 1 if roll n is cut.\r\n        l(i) the length of pipe i.\r\n        L the length of a raw pipe.\r\n        b(i) the required number of i type pipe.\r\n    model:\r\n        min = sum_n [ y(n) ]\r\n        s.t.\r\n        sum_n [ x(ni) ] >= b(i)                   for i in I (Set of different kinds of pipes)\r\n        sum_i [ l(i) * x(ni) ] <= L * y(n)        for n in N (Set of stocks) \r\n        x(ni) are integers\r\n        y(n) are binaries\r\n\"\"\"\r\n\r\nimport sys\r\nimport numpy as np\r\nimport gurobipy as gp\r\nfrom gurobipy import GRB\r\nimport time\r\n\r\ntimeStart = time.time()\r\n\r\nclass Material:\r\n    def __init__(self, name, length, num):\r\n        self.name = name\r\n        self.length = length\r\n        self.num = num\r\n\r\nclass Demand:\r\n    def __init__(self, name, length, num):\r\n        self.name = name\r\n        self.length = length\r\n        self.num = num\r\n    \r\nmatSet = {}\r\ndemSet = {}\r\nfor i in range(1,201):\r\n    matSet[i] = Material('pipe', 218, 1)\r\ndemSet[1] = Demand('pipe1', 81, 44)\r\ndemSet[2] = Demand('pipe2', 70, 3)\r\ndemSet[3] = Demand('pipe3', 68, 48)\r\n\r\ndef solver():\r\n    m = gp.Model(\"MIP\")\r\n    x = m.addVars( demSet, matSet, vtype='I', name=\"x\")\r\n    y = m.addVars( matSet, vtype='B', name='y')\r\n    m.setObjective(gp.quicksum(y[mat] for mat in matSet), GRB.MINIMIZE)\r\n    m.addConstrs(gp.quicksum(x.select(dem,'*')) >= demSet[dem].num for dem in demSet.keys())\r\n    m.addConstrs(gp.quicksum(demSet[dem].length * x[dem,mat] for dem in demSet) <= y[mat] * matSet[mat].length for mat in matSet.keys())\r\n    m.optimize()\r\n    sol = m.x\r\n    return m.objVal\r\n\r\nobj = solver()\r\nprint('Obj = ',obj)\r\n# print('Cutting plan (each column is a plan):')\r\n# print(A)\r\n# print('Number of implementation times for each cutting plan:')\r\n# print(sol)\r\n\r\ntimeEnd = time.time()\r\nprint('Optimal cutting plan found !')\r\nprint('running time =', timeEnd-timeStart)", "meta": {"hexsha": "1874a4b6acf73e5447a958f607de5afcc6533b50", "size": 2290, "ext": "py", "lang": "Python", "max_stars_repo_path": "MILP.py", "max_stars_repo_name": "Zhengyang-Li/An-example-for-column-generation", "max_stars_repo_head_hexsha": "46952de4709da94ff39a4d9ddae65c0e265db53b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-29T15:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T15:04:05.000Z", "max_issues_repo_path": "MILP.py", "max_issues_repo_name": "Zhengyang-Li/An-example-for-column-generation", "max_issues_repo_head_hexsha": "46952de4709da94ff39a4d9ddae65c0e265db53b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MILP.py", "max_forks_repo_name": "Zhengyang-Li/An-example-for-column-generation", "max_forks_repo_head_hexsha": "46952de4709da94ff39a4d9ddae65c0e265db53b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1315789474, "max_line_length": 140, "alphanum_fraction": 0.592139738, "include": true, "reason": "import numpy", "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.8872045847699186, "lm_q1q2_score": 0.8540880010832393}}
{"text": "import numpy as np\nimport math\ndef getCircleOfBestFitCenter(xList, yList):\n    inputList = []\n    dList = []\n    for i in range(0, len(xList)):\n        inputList.append([xList[i], yList[i], 1])\n        dList.append([(xList[i] ** 2) + (yList[i] ** 2)])\n    \n    inputMatrix = np.array(inputList)\n    dMatrix = np.array(dList)\n\n    outputMatrix = (np.linalg.pinv(inputMatrix)) @ dMatrix\n\n    xCenter = outputMatrix[0]/2\n    yCenter = outputMatrix[1]/2\n\n    # rSquared = outputMatrix[2] - (xCenter ** 2) - (yCenter ** 2)\n    rSquared = math.sqrt(((4 * outputMatrix[2]) + (outputMatrix[0] ** 2) + (outputMatrix[1] ** 2)))/2\n    centers = [[xCenter, yCenter, rSquared]]\n\n    return centers\n\nxList = [205.26037743043992, 203.23717997069133, 201.3400034980003, 202.16121837617698]\n\nyList = [95.39624792384349, 62.42071196788877, 84.03825895054133, 73.17519781157725]\n\ncircle = getCircleOfBestFitCenter(xList, yList)\n\nprint(circle)\n\n# print(\"X: \" + str(convertedCoordinates[0]) + \" Y: \" + str(convertedCoordinates[1]) + \" Z: \" + str(convertedCoordinates[2]))\n", "meta": {"hexsha": "cdbc600b600f8aed16305004e6b35f9764f0e4b3", "size": 1051, "ext": "py", "lang": "Python", "max_stars_repo_path": "OAK-ComputerVision/circleTest.py", "max_stars_repo_name": "HighlandersFRC/2022-Maverick", "max_stars_repo_head_hexsha": "491341c28ed0f806747371a7ca9e5f8390bd2c7a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-22T17:48:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T17:48:40.000Z", "max_issues_repo_path": "OAK-ComputerVision/circleTest.py", "max_issues_repo_name": "HighlandersFRC/2022-Maverick", "max_issues_repo_head_hexsha": "491341c28ed0f806747371a7ca9e5f8390bd2c7a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OAK-ComputerVision/circleTest.py", "max_forks_repo_name": "HighlandersFRC/2022-Maverick", "max_forks_repo_head_hexsha": "491341c28ed0f806747371a7ca9e5f8390bd2c7a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8484848485, "max_line_length": 125, "alphanum_fraction": 0.6555661275, "include": true, "reason": "import numpy", "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018426872776, "lm_q2_score": 0.875787001374006, "lm_q1q2_score": 0.854069097541496}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nVisualizing the Mandelbrot Set Using Python by Blake Sanie, Nov 29, 2020.\nhttps://medium.com/swlh/visualizing-the-mandelbrot-set-using-python-50-lines-f6aa5a05cf0f\n\nUse Python Numba for C-like performance, Jan 11, 2022.\nPart 1 of 4 Just-In-Time (JIT) Compilation.\n\"\"\"\n\nfrom PIL import Image\nfrom os.path import exists\nfrom numba import njit, uint8\nfrom timeit import default_timer as timer\nimport colorsys, os, sys\nimport numpy as np\n\n# frame parameters\nwidth = 700 # pixels\nx, y = -0.5, 0.0\nxRange = 3.4\naspectRatio = 4 / 3 \nprecision = 500\n\nheight = round(width / aspectRatio)\nyRange = xRange / aspectRatio\nminX = x - xRange / 2\nmaxX = x + xRange / 2\nminY = y - yRange / 2\nmaxY = y + yRange / 2\n\njit_start = timer()\n\n# JIT hsv_to_rgb (Note: return type UniTuple(f8,3) or None)\nhsv_to_rgb = njit('(f8, f8, f8)', nogil=True)(colorsys.hsv_to_rgb)\n\n@njit('UniTuple(u1,3)(f8, f8, f8, f8)', nogil=True)\ndef powerColor(distance, exp, const, scale):\n    color = distance**exp\n    r,g,b = hsv_to_rgb(const + scale * color, 1 - 0.6 * color, 0.9)\n    r = uint8(r * 255 + 0.5)\n    g = uint8(g * 255 + 0.5)\n    b = uint8(b * 255 + 0.5)\n    return r,g,b\n\n@njit('void(u1[:,:,:])', nogil=True)\ndef mandel(pixels):\n    for row in range(height):\n        for col in range(width):\n            x = minX + col * xRange / width\n            y = maxY - row * yRange / height\n            oldX = x\n            oldY = y\n            for i in range(precision + 1):\n                a = x*x - y*y # real component of z^2\n                b = 2 * x * y # imaginary component of z^2\n                x = a + oldX  # real component of new z\n                y = b + oldY  # imaginary component of new z\n                if x*x + y*y > 4:\n                    break\n            if i < precision:\n                distance = (i + 1) / (precision + 1)\n                # Numpy ndarray is [row, col] versus Pillow Image [col, row].\n                pixels[row, col] = powerColor(distance, 0.2, 0.27, 1.0)\n\ndef save_image(pixels, filename, show_image=False):\n    height, width, dim = pixels.shape\n    pixels = pixels.reshape((height * width * dim,))\n\n    img = Image.frombuffer(\"RGB\", (width, height), pixels, \"raw\", \"RGB\", 0, 1)\n    img.save(filename)\n    print(f\"image saved as {filename}\")\n\n    if show_image:\n        if sys.platform == \"darwin\":\n            os.system(f\"open {filename}\")\n        elif sys.platform.startswith(\"linux\") and exists(\"/usr/bin/eog\"):\n            os.system(f\"eog {filename}\")\n\nif __name__ == '__main__':\n    print(\"     jit time {:.3f} seconds\".format(timer() - jit_start))\n    pixels = np.empty((height, width, 3), dtype=np.uint8)\n\n    s = timer()\n    mandel(pixels)\n    print(\"   mandelbrot {:.3f} seconds\".format(timer() - s))\n\n    save_image(pixels, \"img1.png\", show_image=False)\n\n", "meta": {"hexsha": "32558e60793f79171b6ac8ccca6628aa4d473b89", "size": 2821, "ext": "py", "lang": "Python", "max_stars_repo_path": "demo/ex1.py", "max_stars_repo_name": "marioroy/mandelbrot-python", "max_stars_repo_head_hexsha": "ec77db4363582689365dca1a10baddbe1647f176", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-08T17:35:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T17:35:06.000Z", "max_issues_repo_path": "demo/ex1.py", "max_issues_repo_name": "marioroy/mandelbrot-python", "max_issues_repo_head_hexsha": "ec77db4363582689365dca1a10baddbe1647f176", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo/ex1.py", "max_forks_repo_name": "marioroy/mandelbrot-python", "max_forks_repo_head_hexsha": "ec77db4363582689365dca1a10baddbe1647f176", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3444444444, "max_line_length": 89, "alphanum_fraction": 0.5909252038, "include": true, "reason": "import numpy,from numba", "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018405251301, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.8540690877438563}}
{"text": "import sympy as sp, math as m\n\nt, x = sp.symbols('t x')\nsp.init_printing(use_unicode=True)\n\n#f=sp.Lambda(x, x*sp.cos(x)-x**2*sp.sin(x))\n#f=sp.Lambda(x, sp.cos(x))\n#f=sp.Lambda(x, 1/(1+x**2))\nf=sp.Lambda(x, x**2*sp.exp(x))\n\n\"\"\"\ndef f(x):\n    #return x*m.cos(x)-x**2*m.sin(x)\n    return m.cos(x)\n\"\"\"\n\ndef legendre(f, raices_legendre):\n\n    n = len(raices_legendre)-1\n    \n    l = [1]*(n+1)\n\n    result = 0\n    \n    for i in range(n+1):\n        for j in range(n+1):\n            if i != j:\n                l[i]*=sp.poly((x-raices_legendre[j])/(raices_legendre[i]-raices_legendre[j]))\n\n        #print(\"alpha_\"+str(i)+\"=\"+str((l[i].integrate()(1)-l[i].integrate()(-1))))\n        \n        result += (l[i].integrate()(1)-l[i].integrate()(-1))*f(raices_legendre[i])\n\n    return result        \n\n\ndef gaussiana(f, a, b, n, raices_legendre):\n\n    g=sp.Lambda(t, f(((b-a)*t+b+a)/2))\n    \n    return legendre(g, raices_legendre)*(b-a)/2\n\nraices_legendre1=[-0.5773502692, 0.5773502692]\nraices_legendre2=[-0.7745966692, 0, 0.7745966692]\nraices_legendre3=[-0.8611363116, -0.3399810436, 0.3399810436, 0.8611363116]\nraices_legendre4=[-0.9061798459, -0.5384693101, 0, 0.5384693101, 0.9061798459]\n\nraices_legendre=raices_legendre3\n\nn = len(raices_legendre)-1\na, b = 0, 1/2\n\nresult = gaussiana(f, a, b, n, raices_legendre)\n\nprint(result)\n\n# Compruebo exactitud\n\"\"\"\np = sp.Poly(1,x)\n\nfor i in range(2*n+3): # Todos los errores deberian dar 0 menos el último\n    #print(p)\n    r = gaussiana(p, -1, 1, n, raices_legendre)\n    print(\"Grado \"+str(i)+\" Error =\", abs(r-p.integrate()(1)+p.integrate()(-1)))\n    p*=sp.poly(x)\n\"\"\"\n\n# Ej 22\n\"\"\"\nfa=sp.Lambda(x, x**2*sp.log(x))\nfb=sp.Lambda(x, x**3*sp.exp(-x))\nfc=sp.Lambda(x, 3*x/(x**2-4))\nfd=sp.Lambda(x, sp.cos(x)*sp.exp(3*x))\n\nprint(\"a) \" + str(gaussiana(fa, 1, 1.5, 2, raices_legendre2)))\nprint(\"Error: \" + str(abs(0.19225935773048122-gaussiana(fa, 1, 1.5, 2, raices_legendre2))))\nprint(\"b) \" + str(sp.N(gaussiana(fb, 0, 1, 2, raices_legendre2))))\nprint(\"Error \" + str(abs(0.11392894084187483-sp.N(gaussiana(fb, 0, 1, 2, raices_legendre2)))))\nprint(\"c) \" + str(gaussiana(fc, 1, 1.8, 2, raices_legendre2)))\nprint(\"Error: \" + str(abs(-2.059573828864272-gaussiana(fc, 1, 1.8, 2, raices_legendre2))))\nprint(\"d) \" + str(gaussiana(fd, 0, m.pi/4, 2, raices_legendre2)))\nprint(\"Error \" + str(abs(2.6841954140755666-gaussiana(fd, 0, m.pi/4, 2, raices_legendre2))))\n\"\"\"\n", "meta": {"hexsha": "87c306280c998c15daaf1ee65514860b2fd6c06b", "size": 2382, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tema2/gaussiana.py", "max_stars_repo_name": "dcabezas98/MNII", "max_stars_repo_head_hexsha": "123dfd7f19cb06e7d8db9e0865db624988a6f88b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tema2/gaussiana.py", "max_issues_repo_name": "dcabezas98/MNII", "max_issues_repo_head_hexsha": "123dfd7f19cb06e7d8db9e0865db624988a6f88b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tema2/gaussiana.py", "max_forks_repo_name": "dcabezas98/MNII", "max_forks_repo_head_hexsha": "123dfd7f19cb06e7d8db9e0865db624988a6f88b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3571428571, "max_line_length": 94, "alphanum_fraction": 0.6192275399, "include": true, "reason": "import sympy", "num_tokens": 942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018441287091, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.8540690798341402}}
{"text": "from __future__ import print_function\r\n\r\nimport datetime\r\nimport numpy as np\r\nimport pandas as pd\r\n#import pandas.io.data as web\r\nimport pandas_datareader as web\r\n\r\ndef annualised_sharpe(returns, N=364):\r\n    \"\"\"\r\n    Calculate the annualised Sharpe ratio of a returns stream\r\n    based on a number of trading periods, N. N defaults to 252,\r\n    which then assumes a stream of daily returns.\r\n    The function assumes that the returns are the excess of\r\n    those compared to a benchmark.\r\n    \"\"\"\r\n    return np.sqrt(N) * returns.mean() / returns.std()\r\n\r\n\r\ndef equity_sharpe(ticker):\r\n    \"\"\"\r\n    Calculates the annualised Sharpe ratio based on the daily\r\n    returns of an equity ticker symbol listed in Google Finance.\r\n    The dates have been hardcoded here for brevity.\r\n    \"\"\"\r\n    start = datetime.datetime(2000,1,1)\r\n    end = datetime.datetime(2013,1,1)\r\n\r\n    # Obtain the equities daily historic data for the desired time period\r\n    # and add to a pandas DataFrame\r\n    pdf = web.DataReader(ticker, 'google', start, end)\r\n\r\n    # Use the percentage change method to easily calculate daily returns\r\n    pdf['daily_ret'] = pdf['Close'].pct_change()\r\n\r\n    # Assume an average annual risk-free rate over the period of 5%\r\n    pdf['excess_daily_ret'] = pdf['daily_ret'] - 0.05/252\r\n\r\n    # Return the annualised Sharpe ratio based on the excess daily returns\r\n    return annualised_sharpe(pdf['excess_daily_ret'])\r\n\r\n\r\ndef market_neutral_sharpe(ticker, benchmark):\r\n    \"\"\"\r\n    Calculates the annualised Sharpe ratio of a market\r\n    neutral long/short strategy inolving the long of 'ticker'\r\n    with a corresponding short of the 'benchmark'.\r\n    \"\"\"\r\n    start = datetime.datetime(2000, 1, 1)\r\n    end = datetime.datetime(2013, 1, 1)\r\n\r\n    # Get historic data for both a symbol/ticker and a benchmark ticker\r\n    # The dates have been hardcoded, but you can modify them as you see fit!\r\n    tick = web.DataReader(ticker, 'google', start, end)\r\n    bench = web.DataReader(benchmark, 'google', start, end)\r\n\r\n    # Calculate the percentage returns on each of the time series\r\n    tick['daily_ret'] = tick['Close'].pct_change()\r\n    bench['daily_ret'] = bench['Close'].pct_change()\r\n\r\n    # Create a new DataFrame to store the strategy information\r\n    # The net returns are (long - short)/2, since there is twice\r\n    # the trading capital for this strategy\r\n    strat = pd.DataFrame(index=tick.index)\r\n    strat['net_ret'] = (tick['daily_ret'] - bench['daily_ret'])/2.0\r\n\r\n    # Return the annualised Sharpe ratio for this strategy\r\n    return annualised_sharpe(strat['net_ret'])\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    print(\r\n        \"Google Sharpe Ratio: %s\" % \r\n        equity_sharpe('GOOG')\r\n    )\r\n    print(\r\n        \"Google Market Neutral Sharpe Ratio: %s\" % \r\n        market_neutral_sharpe('GOOG', 'SPY')\r\n    )", "meta": {"hexsha": "2c756167d560e8c3cce8facacefac2a5fd6aa189", "size": 2832, "ext": "py", "lang": "Python", "max_stars_repo_path": "finance_calc/get_sharpe_ratio.py", "max_stars_repo_name": "Charles0009/crypto_finance_analysis", "max_stars_repo_head_hexsha": "028938afabf0e9fbf352e8136acdc5d9753ba56d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "finance_calc/get_sharpe_ratio.py", "max_issues_repo_name": "Charles0009/crypto_finance_analysis", "max_issues_repo_head_hexsha": "028938afabf0e9fbf352e8136acdc5d9753ba56d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "finance_calc/get_sharpe_ratio.py", "max_forks_repo_name": "Charles0009/crypto_finance_analysis", "max_forks_repo_head_hexsha": "028938afabf0e9fbf352e8136acdc5d9753ba56d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8481012658, "max_line_length": 77, "alphanum_fraction": 0.6765536723, "include": true, "reason": "import numpy", "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951703918909, "lm_q2_score": 0.8887588038050466, "lm_q1q2_score": 0.8540542868893909}}
{"text": "# Noise reduction method\n#\n# utilizing \"Gradual Release of Sensitive Data under Differential Privacy\"\n# by Fragkiskos Koufogiannis, Shuo Han, and George J. Pappas\n\n# Background:\n# We wish to release a function f of a private database, say D.\n# The true output is a numpy array M = f(D).\n# Each entry of M has \"sensitivity\" s meaning that if D changes to a\n# neighboring database D', then the corresponding entry of M' = f(D')\n# changes by at most s.\n#\n# We use differential privacy to release private versions of M.\n# The output is a sequence of versions of M that become more accurate\n# and less private.\n#\n# Given M, sensitivity, and a INCREASING list of epsilons eps_1, ..., eps_T\n# 1. Construct a random walk starting from M, so that at step t, the {i,j}\n#    entry is distributed as M_{ij} + Laplace(1 / eps_{T-t}).\n# 2. Return the list of resulting matrices IN REVERSE ORDER of the walk,\n#    i.e. from most noisy (most private) to least noisy (least private).\n# 3. In particular, releasing all of the first t matrices in the list\n#    is eps_t private, for each t, because:\n#    - releasing the t-th matrix in the list is eps_t private\n#    - all previous matrices are post-processings of this (by the random walk)\n\nimport numpy as np\n\n\n# Helper function\n# filter by returning each entry of matrix independently with probability 1 - prob\n# and 0 with probability prob\ndef do_filt(prob, matrix):\n  f = lambda x: 0 if np.random.random() <= prob else x\n  return np.vectorize(f)(matrix)\n\n# Main function\n# Input:\n#   numpy array M whose privacy is to be protected\n#   sensitivity of the each entry of M\n#   a INCREASING list of epsilons\n#\n# Output: a list of Mhat matrices approximating M, where releasing the first t\n# matrices is eps_t private\ndef gen_list(M, sensitivity, eps_list):\n  try:\n    steps = len(eps_list)\n  except:\n    steps = eps_list.shape[0]\n  shape = M.shape\n  rev_eps_list = eps_list[::-1]\n  noise_list = [np.random.laplace(scale=sensitivity/eps, size=shape) for eps in rev_eps_list]\n\n  # first step, just add the noise to M\n  walk = [M + noise_list[0]]\n\n  # other steps, add the noise of each entry with only a certain probability\n  filt_probs = [ (rev_eps_list[j] / rev_eps_list[j-1])**2 for j in range(1, steps) ]\n  walk_steps = [do_filt(p, noise_list[1+j]) for j,p in enumerate(filt_probs)]\n\n  for j in range(1, len(rev_eps_list)):\n    walk.append(walk[j-1] + walk_steps[j-1])\n  walk.reverse()\n  return np.array(walk)\n\n\n", "meta": {"hexsha": "840d62eb1db50504f47a807adbc2dadc000f2ccd", "size": 2446, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/noise_reduc.py", "max_stars_repo_name": "journalprivacyconfidentiality/Accuracy-First-Differential-Privacy", "max_stars_repo_head_hexsha": "a0ec9bccef739c90c6781f7b7b2aefe271657427", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2017-12-01T08:06:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T13:08:50.000Z", "max_issues_repo_path": "code/noise_reduc.py", "max_issues_repo_name": "steven7woo/Accuracy-First-Differential-Privacy", "max_issues_repo_head_hexsha": "47c6a596ee945bbda1da8dc3c240a8cd82d1d719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/noise_reduc.py", "max_forks_repo_name": "steven7woo/Accuracy-First-Differential-Privacy", "max_forks_repo_head_hexsha": "47c6a596ee945bbda1da8dc3c240a8cd82d1d719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2017-11-07T13:29:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-20T13:50:04.000Z", "avg_line_length": 36.5074626866, "max_line_length": 93, "alphanum_fraction": 0.7162714636, "include": true, "reason": "import numpy", "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517106286379, "lm_q2_score": 0.8887587890727754, "lm_q1q2_score": 0.8540542786957204}}
{"text": "import numpy as np\n\nimport matplotlib.pyplot as plt\n\n\ndef gini(p):\n    return p * (1 - p) + (1 - p) * (1 - (1 - p))\n\n\ndef entropy(p):\n    return -(p * np.log2(p) + (1 - p) * np.log2(1 - p))\n\n\ndef error(p):\n    return 1 - np.max([p, 1 - p])\n\n\nx = np.arange(0.0, 1.0, 0.01)\n\nent = [entropy(p) if p != 0 else None for p in x]\n\n# Scaled entropy\nsc_ent = [e * 0.5 if e else None for e in ent]\n\nerr = [error(i) for i in x]\n\nfig = plt.figure()\nax = plt.subplot(111)\n\nfor i, lab, ls, c, in zip([ent, sc_ent, gini(x), err],\n                          ['Entropy', 'Entropy (scaled)',\n                           'Gini impurity',\n                           'Misclassification error'],\n                          ['-', '-', '--', '-.'],\n                          ['black', 'lightgray',\n                           'red', 'green', 'cyan']):\n    line = ax.plot(x, i, label=lab, linestyle=ls, lw=2, color=c)\n\nax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.15), ncol=5,\n          fancybox=True, shadow=False)\n\nax.axhline(y=0.5, linewidth=1, color='k', linestyle='--')\nax.axhline(y=1.0, linewidth=1, color='k', linestyle='--')\n\nplt.ylim([0, 1.1])\nplt.xlabel('p(i=1)')\nplt.ylabel('impurity index')\nplt.tight_layout()\nplt.show()\n\n", "meta": {"hexsha": "c1e0683d57e0bea76c37dbeb501f5e82c23c71af", "size": 1213, "ext": "py", "lang": "Python", "max_stars_repo_path": "O3/_15_decision_tree/impurity_functions_comparison.py", "max_stars_repo_name": "ShAlireza/ML-Tries", "max_stars_repo_head_hexsha": "4516be7a3275c9bdedd7bd258800be384b6b34f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "O3/_15_decision_tree/impurity_functions_comparison.py", "max_issues_repo_name": "ShAlireza/ML-Tries", "max_issues_repo_head_hexsha": "4516be7a3275c9bdedd7bd258800be384b6b34f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "O3/_15_decision_tree/impurity_functions_comparison.py", "max_forks_repo_name": "ShAlireza/ML-Tries", "max_forks_repo_head_hexsha": "4516be7a3275c9bdedd7bd258800be384b6b34f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7843137255, "max_line_length": 65, "alphanum_fraction": 0.5070074196, "include": true, "reason": "import numpy", "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321452198369, "lm_q2_score": 0.8856314783461303, "lm_q1q2_score": 0.8540334333113287}}
{"text": "\"\"\"\nLinear Regression it assumes a linear relationship between dependent variable(y) and independent variable(X).\n\nSo the value of y can be calculated  using a linear combination of input variable X.\n\nVery similar to how the equation of a straight line takes a linear relation between x-axis and y-axis as\n\ny = m(x) + c\n\nwhere:\n    m -> slope of the line\n    c -> y-intercept\n\nwe can also write equation for predicting value as\n\ny = b0 + b1 * X\n\nwhere b0 and b1 are the coefficients that we need to estimate from the training data.\n\nSteps:\n    1. Calculate the Mean and Variance\n    2. Calculate covariance\n    3. Estimate coefficients\n    4. Make predictions \n    5. Evaluate algorithm\n\"\"\"\n# imports\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport random\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error, r2_score\n\nrandom.seed(1)\n\n\n# plt.scatter(X, y)\n# plt.show()\n# after looking at the scatter plot you can see there is a linear relation between X and  y.\n\n\n# Step - 1 : Calculating Mean and variance of both X and y.\n\ndef mean(values):\n    return sum(values) / float(len(values))\n\n\ndef variance(values, mean):\n    return sum((np.array(values) - mean) ** 2) / float(len(values))\n\n\n# Step -2 : Calculating Covariance of X and y\n\ndef covariance(x, mean_x, y, mean_y):\n    x = np.array(x)\n    y = np.array(y)\n    return sum((x - mean_x) * (y - mean_y)) / float(len(x))\n\n\n# Step - 3 :  Estimate coefficients\ndef coefficient(X, y):\n    mean_x, mean_y = mean(X), mean(y)\n    b1 = covariance(X, mean_x, y, mean_y) / variance(X, mean_x)\n    b0 = mean_y - b1 * mean_x\n    return [b0, b1]\n\n\ndef split_data(X, y, test_size=0.2):\n    return train_test_split(X, y, test_size=test_size, random_state=42)\n\n\n# Step - 4 : Make predictions\ndef simple_linear_regression(X_train, y_train, X_test):\n    b0, b1 = coefficient(X_train, y_train)\n    predictions = b0 + b1 * X_test\n    return predictions\n\n\ndef rmse_metric(actual, predicted):\n    actual = np.array(actual)\n    predicted = np.array(predicted)\n    prediction_error = actual - predicted\n    rmse = np.sqrt(sum(prediction_error ** 2) / float(len(actual)))\n    return rmse\n\n\ndef evaluate_algorithm(X, y, algorithm, split_size):\n    X_train, X_test, y_train, y_test = split_data(X, y, split_size)\n    predicted = algorithm(X_train, y_train, X_test)\n    rmse = rmse_metric(y_test, predicted)\n    return rmse\n\n\n#\n# print(\"X-stats : mean= %0.3f variance= %0.3f \" % (mean_x, var_x))\n# print(\"y-stats : mean= %0.3f variance= %0.3f \" % (mean_y, var_y))\n# print(\"Covariance of X, y : %0.3f\" % (covarxy))\n# print(\"coefficients  b0=%0.3f,. b1=%0.3f \" % (b0, b1))\n\ndf = pd.read_excel(io=\"insurance.xls\", encoding='ascii')\nX = df[\"X\"]\ny = df[\"Y\"]\ntest_size = 0.2\n\nb0, b1 = coefficient(X, y)\ny_hat = b0 + b1 * X\n\n# plt.scatter(X, y, label=\"Data points\")\n# plt.plot(X, y_hat, color='#00ff00', label=\"LinearRegression\")\n# plt.legend()\n# plt.show()\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=42)\n\n\ndef rSquare(X_train, X_test, y_train, y_test, algorithm):\n    predicted = algorithm(X_train, y_train, X_test)\n    y_mean_line = mean(y_test)\n    squared_error_regr = sum((predicted - y_test)**2)\n    squared_error_ymean = sum((y_test - y_mean_line)**2)\n    return 1 - squared_error_regr / squared_error_ymean\n\n\nrmse = evaluate_algorithm(X, y, simple_linear_regression, test_size)\nprint(\"RMSE from Math : %0.3f\" % (rmse))\nprint(\"Rsquare error from Math: %0.3f \" % (rSquare(X_train, X_test, y_train, y_test, simple_linear_regression)))\n\nlr = LinearRegression()\nlr.fit(np.array(X_train).reshape(-1, 1), y_train)\ny_pred = lr.predict(np.array(X_test).reshape(-1, 1))\nprint(\"RMSE from sklearn \", np.sqrt(mean_squared_error(y_test, y_pred)))\nprint(\"Rsquare error : \",r2_score(y_test, y_pred))", "meta": {"hexsha": "591df91a57e24d18a788a4642dea9045b03af00e", "size": 3886, "ext": "py", "lang": "Python", "max_stars_repo_path": "LinearRegression.py", "max_stars_repo_name": "seshuthota/Ml-Scratch", "max_stars_repo_head_hexsha": "538b7a7b3a94ee06164848f8b6ce944d2df0a4df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LinearRegression.py", "max_issues_repo_name": "seshuthota/Ml-Scratch", "max_issues_repo_head_hexsha": "538b7a7b3a94ee06164848f8b6ce944d2df0a4df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LinearRegression.py", "max_forks_repo_name": "seshuthota/Ml-Scratch", "max_forks_repo_head_hexsha": "538b7a7b3a94ee06164848f8b6ce944d2df0a4df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0, "max_line_length": 112, "alphanum_fraction": 0.6991765311, "include": true, "reason": "import numpy", "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214450208032, "lm_q2_score": 0.885631484383387, "lm_q1q2_score": 0.8540334327765067}}
{"text": "import numpy as np\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of Ackley benchmark function.\n% SCORES = ACKLEYFCN(X) computes the value of the Ackey function at point\n% X. ACKLEYFCN accepts a matrix of size M-by-N and returns a vetor SCORES\n% of size M-by-1 in which each row contains the function value for each row\n% of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = ackleyfcn(x)\n    n = size(x, 2);\n    ninverse = 1 / n;\n    sum1 = sum(x .^ 2, 2);\n    sum2 = sum(cos(2 * pi * x), 2);\n    \n    scores = 20 + exp(1) - (20 * exp(-0.2 * sqrt( ninverse * sum1))) - exp( ninverse * sum2);\nend\n'''\nclass ackleyfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-32, 32])\n        self.plot_bound = np.array([-40, 40])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        n = X.shape[1]\n        ninverse = 1 / n\n        sum1 = np.sum( np.power(X, 2), axis=1 )\n        sum2 = np.sum( np.cos(2 * np.pi * X), axis=1 )\n\n        scores = 20 + np.exp(1) - ( 20 * np.exp( -0.2 * np.sqrt(ninverse * sum1) ) ) - np.exp(ninverse * sum2)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Ackley N. 2 function.\n% SCORES = ACKLEYN2FCN(X) computes the value of the Ackley N. 2\n% function at point X. ACKLEYN2FCN accepts a matrix of size M-by-2 and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = ackleyn2fcn(x)\n    \n    n = size(x, 2);\n    assert(n == 2, 'Ackley N. 2 function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = -200 * exp(-0.02 * sqrt((X .^ 2) + (Y .^ 2)));\nend\n'''\nclass ackleyn2fcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-32, 32])\n        self.plot_bound = np.array([-4, 4])\n        self.n_var = 2\n        if n_var != self.n_var: print('Ackley N. 2 function is only defined on a 2D space.')\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = -200 * np.exp( -0.02 * np.sqrt( np.power(x1, 2) + np.power(x2, 2) ) )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Ackley N. 3 function.\n% SCORES = ACKLEYN3FCN(X) computes the value of the Ackley N. 3\n% function at point X. ACKLEYN3FCN accepts a matrix of size M-by-2 and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = ackleyn3fcn(x)\n    \n    n = size(x, 2);\n    assert(n == 2, 'Ackley N. 3 function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = -200 * exp(-0.02 * sqrt((X .^ 2) + (Y .^ 2))) + ...\n             5 * exp(cos(3 * X) + sin(3 * Y));\nend\n'''\nclass ackleyn3fcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-32, 32])\n        self.plot_bound = np.array([-4, 4])\n        self.n_var = 2\n        if n_var != self.n_var: print('Ackley N. 3 function is only defined on a 2D space.')\n        self.optimalX = np.array([0.682584587365898, -0.36075325513719])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = -200 * np.exp( -0.02 * np.sqrt( np.power(x1, 2) + np.power(x2, 2) ) ) + \\\n                5 * np.exp( np.cos(3 * x1) + np.sin(3 * x2) )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Adjiman benchmark function.\n% SCORES = ADJIMANHFCN(X) computes the value of the Adjiman function at \n% point X. ADJIMANHFCN accepts a matrix of size M-by-2 and returns a  \n% vetor SCORES of size M-by-1 in which each row contains the function value \n% for the corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = adjimanfcn(x)\n    \n    n = size(x, 2);\n    assert(n == 2, 'Adjiman function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = (cos(X) .* sin(Y)) - (X ./ ((Y .^ 2) + 1));\nend\n'''\nclass adjimanfcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([[-1,-1], [2,1]])\n        self.plot_bound = self.boundaries\n        self.n_var = 2\n        if n_var != self.n_var: print('Adjiman function is only defined on a 2D space.')\n        self.optimalX = np.array([5, 0])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = ( np.cos(x1) * np.sin(x2) ) - ( x1 / ( np.power(x2, 2) + 1 ) )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Alpine N. 1 function.\n% SCORES = ALPINEN1FCN(X) computes the value of the Alpine N. 1\n% function at point X. ALPINEN1FCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information, please visit:\n% benchmarkfcns.xyz/fcns/alpinen1fcn\n% See also: alpinen2fcn\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = alpinen1fcn(x)\n     scores = sum(abs(x .* sin(x) + 0.1 * x), 2);\nend \n'''\nclass alpinen1fcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([0, 10])\n        self.plot_bound = np.array([-10, 10])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        scores = np.sum( np.abs(X * np.sin(X) + 0.1 * X), axis=1)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Alpine N. 2 function.\n% SCORES = ALPINEN2FCN(X) computes the value of the Alpine N. 2\n% function at point X. ALPINEN2FCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information, please visit:\n% benchmarkfcns.xyz/fcns/alpinen2fcn\n% See also: alpinen1fcn\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = alpinen2fcn(x)\n     scores = prod(sqrt(x) .* sin(x), 2);\nend \n'''\nclass alpinen2fcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([0, 10])\n        self.plot_bound = self.boundaries\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var) + 7.917\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        scores = - np.prod( np.sqrt(X) * np.sin(X), axis=1 )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Bartels Conn benchmark function.\n% SCORES = BARTELSCONNFCN(X) computes the value of the Bartels Conn \n% function at point X. BARTELSCONNFCN accepts a matrix of size M-by-2 and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = bartelsconnfcn(x)\n    \n    n = size(x, 2);\n    assert(n == 2, 'Bartels Conn function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = abs((X .^ 2) + (Y .^ 2) + (X .* Y)) + abs(sin(X)) + abs(cos(Y));\nend\n'''\nclass bartelsconnfcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-500, 500])\n        self.plot_bound = np.array([-4, 4])\n        self.n_var = 2\n        if n_var != self.n_var: print('Bartels Conn function is only defined on a 2D space.')\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = np.abs( np.power(x1, 2) + np.power(x2, 2) + (x1 * x2) ) + np.abs( np.sin(x1) ) + np.abs( np.cos(x2) )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Beale benchmark function.\n% SCORES = BEALEFCN(X) computes the value of the Beale function at \n% point X. BEALEFCN accepts a matrix of size M-by-2 and returns a  \n% vetor SCORES of size M-by-1 in which each row contains the function value \n% for the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = bealefcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'Beale''s function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = (1.5 - X + (X .* Y)).^2 + ...\n             (2.25 - X + (X .* (Y.^2))).^2 + ...\n             (2.625 - X + (X .* (Y.^3))).^2;\nend\n'''\nclass bealefcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-4.5, 4.5])\n        self.plot_bound = np.array([-5, 5])\n        self.n_var = 2\n        if n_var != self.n_var: print('Beale\\'s function is only defined on a 2D space.')\n        self.optimalX = np.array([3, 0.5])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = np.power( 1.5 - x1 + (x1 * x2), 2 ) + \\\n                np.power( 2.25 - x1 + ( x1 * np.power(x2, 2) ), 2 ) + \\\n                np.power( 2.625 - x1 + ( x1 * np.power(x2, 3) ), 2 )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Bird function.\n% SCORES = BIRDFCN(X) computes the value of the Bird \n% function at point X. BIRDFCN accepts a matrix of size M-by-2 and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = birdfcn(x)\n    \n    n = size(x, 2);\n    assert(n == 2, 'Bird function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = sin(X) .* exp((1 - cos(Y)).^2) + ... \n        cos(Y) .* exp((1 - sin(X)) .^ 2) + ...\n        (X - Y) .^ 2;\nend\n'''\nclass birdfcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-2 * np.pi, 2 * np.pi])\n        self.plot_bound = np.array([-10, 10])\n        self.n_var = 2\n        if n_var != self.n_var: print('Bird function is only defined on a 2D space.')\n        self.optimalX = np.array([4.70104, 3.15294])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = np.sin(x1) * np.exp( np.power( 1 - np.cos(x2), 2 ) ) + \\\n            np.cos(x2) * np.exp( np.power( 1 - np.sin(x1), 2 ) ) + \\\n            np.power(x1 - x2, 2)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of Bohachevsky N. 1 benchmark function.\n% SCORES = BOHACHEVSKYN1FCN(X) computes the value of the Bohachevsky N. 1\n% function at point X. BOHACHEVSKYFCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for each row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = bohachevskyn1fcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'The Bohachevsky N. 1 function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = (X .^ 2) + (2 * Y .^ 2) - (0.3 * cos(3 * pi * X)) - (0.4 * cos(4 * pi * Y)) + 0.7;\nend\n'''\nclass bohachevskyn1fcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-100, 100])\n        self.plot_bound = self.boundaries\n        self.n_var = 2\n        if n_var != self.n_var: print('The Bohachevsky N. 1 function is only defined on a 2D space.')\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = np.power(x1, 2) + 2 * np.power(x2, 2) - 0.3 * np.cos(3 * np.pi * x1) - 0.4 * np.cos(4 * np.pi * x2) + 0.7\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of Bohachevsky N. 2 benchmark function.\n% SCORES = BOHACHEVSKYN2FCN(X) computes the value of the Bohachevsky N. 2\n% function at point X. BOHACHEVSKYN2FCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for each row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = bohachevskyn2fcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'The Bohachevsky N. 2 function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = (X .^ 2) + (2 * Y .^ 2) - (0.3 * cos(3 * pi * X)) .* (0.4 * cos(4 * pi * Y)) + 0.3;\nend\n'''\nclass bohachevskyn2fcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-100, 100])\n        self.plot_bound = np.array([-1.5, 1.5])\n        self.n_var = 2\n        if n_var != self.n_var: print('The Bohachevsky N. 2 function is only defined on a 2D space.')\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = np.power(x1, 2) + 2 * np.power(x2, 2) - 0.3 * np.cos(3 * np.pi * x1) * np.cos(4 * np.pi * x2) + 0.3\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Booth benchmark function.\n% SCORES = BOOTHFCN(X) computes the value of the Booth's function at \n% point X. BOOTHFCN accepts a matrix of size M-by-2 and returns a  \n% vetor SCORES of size M-by-1 in which each row contains the function value \n% for the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = boothfcn(x)\n    \n    n = size(x, 2);\n    assert(n == 2, 'Booth''s function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = (X + (2 * Y) - 7).^2 + ( (2 * X) + Y - 5).^2;\nend\n'''\nclass boothfcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-10, 10])\n        self.plot_bound = self.boundaries\n        self.n_var = 2\n        if n_var != self.n_var: print('Booth\\'s function is only defined on a 2D space.')\n        self.optimalX = np.array([1, 3])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = np.power(x1 + 2 * x2 - 7, 2) + np.power(2 * x1 + x2 - 5, 2)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Egg Crate function.\n% SCORES = BRENTFCN(X) computes the value of the Brent \n% function at point X. BRENTFCN accepts a matrix of size M-by-2 and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information, please visit:\n% benchmarkfcns.xyz/benchmarkfcns/brentfcn\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = brentfcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'The Brent function is defined only on the 2-D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = (X + 10).^2 + (Y + 10).^2 + exp(-X.^2 - Y.^2);\nend\n'''\nclass brentfcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-20, 0])\n        self.plot_bound = self.boundaries\n        self.n_var = 2\n        if n_var != self.n_var: print('The Brent function is defined only on the 2-D space.')\n        self.optimalX = np.zeros(self.n_var) - 10\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = np.power(x1 + 10, 2) + np.power(x2 + 10, 2) + np.exp( -np.power(x1, 2) - np.power(x2, 2) )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Brown benchmark function.\n% SCORES = BROWNFCN(X) computes the value of the Brown function at point X.\n% BROWNFCN accepts a matrix of size M-by-N and returns a vetor SCORES of \n% size M-by-1 in which each row contains the function value for the \n% corresponding row of X. For more information please visit: \n% http://benchmarkfcns.xyz/benchmarkfcns/brownfcn\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = brownfcn(x)\n    \n    n = size(x, 2);  \n    scores = 0;\n    \n    x = x .^ 2;\n    for i = 1:(n-1)\n        scores = scores + x(:, i) .^ (x(:, i+1) + 1) + x(:, i+1).^(x(:, i) + 1);\n    end\nend\n'''\nclass brownfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-1, 4])\n        self.plot_bound = np.array([-1, 1])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        n = X.shape[1]\n        scores = 0\n\n        X1 = np.power(X, 2)\n        for i in range(0, n-1):\n            scores = scores + np.power(X1[:, i], X1[:, i + 1] + 1) + np.power(X1[:, i + 1], X1[:, i] + 1)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Bukin N. 6 benchmark function.\n% SCORES = BUKINN6FCN(X) computes the value of the Bukin N. 6 function at \n% point X. BUKINN6FCN accepts a matrix of size M-by-2 and returns a  \n% vetor SCORES of size M-by-1 in which each row contains the function value \n% for the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = bukinn6fcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'The Bukin N. 6 functions is only defined on a 2D space.')\n    \n    X = x(:, 1);\n    X2 = X .^ 2;\n    Y = x(:, 2);\n    \n    scores = 100 * sqrt(abs(Y - 0.01 * X2)) + 0.01 * abs(X  + 10);\nend\n'''\nclass bukinn6fcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([[-15,-3], [-5,3]])\n        self.plot_bound = self.boundaries\n        self.n_var = 2\n        if n_var != self.n_var: print('The Bukin N. 6 functions is only defined on a 2D space.')\n        self.optimalX = np.array([-10, 1])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = np.power(x1, 2)\n        x3 = X[:, 1]\n\n        scores = 100 * np.sqrt( np.abs(x3 - 0.01 * x2) ) + 0.01 * np.abs(x1  + 10)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Cross-in-tray benchmark function.\n% SCORES = CROSSINTRAYFCN(X) computes the value of the Cross-in-tray \n% function at point X. CROSSINTRAYFCN accepts a matrix of size M-by-2 \n% and returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X. For more information \n% please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = crossintrayfcn(x)\n    \n    n = size(x, 2);\n    assert(n == 2, 'The Cross-in-tray function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n\n    expcomponent = abs(100 - (sqrt(X .^2 + Y .^2) / pi));\n    \n    scores = -0.0001 * ((abs(sin(X) .* sin(Y) .* exp(expcomponent)) + 1) .^ 0.1);\nend\n'''\nclass crossintrayfcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-10, 10])\n        self.plot_bound = self.boundaries\n        self.n_var = 2\n        if n_var != self.n_var: print('The Cross-in-tray function is only defined on a 2D space.')\n        self.optimalX = np.array([1.349406685353340, 1.349406608602084])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        expcomponent = np.abs( 100 - ( np.sqrt( np.power(x1, 2) + np.power(x2, 2) ) / np.pi ) )\n\n        scores = -0.0001 * np.power( np.abs( np.sin(x1) * np.sin(x2) * np.exp(expcomponent) ) + 1, 0.1 )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Deckkers-Aarts function.\n% SCORES = DECKKERSAARTSFCN(X) computes the value of the Deckkers-Aarts  \n% function at point X. DECKKERSAARTSFCN accepts a matrix of size M-by-2 and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information, please visit:\n% benchmarkfcns.xyz/fcns/deckkersaartsfcn\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = deckkersaartsfcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'The Deckkers-Aarts function is defined only on the 2-D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = (100000 * X.^2) + Y.^2 + - (X.^2 + Y.^2).^2 + (10^-5) * (X.^2 + Y.^2 ) .^4;\nend \n'''\nclass deckkersaartsfcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-20, 20])\n        self.plot_bound = self.boundaries\n        self.n_var = 2\n        if n_var != self.n_var: print('The Deckkers-Aarts function is defined only on the 2-D space.')\n        self.optimalX = np.array([0, 15])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = 100000 * np.power(x1, 2) + np.power(x2, 2) + - np.power( np.power(x1, 2) + \\\n            np.power(x2, 2), 2 ) + 1e-05 * np.power( np.power(x1, 2) + np.power(x2, 2), 4)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Drop-Wave benchmark function.\n% SCORES = DROPWAVEFCN(X) computes the value of the Drop-Wave function at \n% point X. DROPWAVEFCN accepts a matrix of size M-by-2 and returns a  \n% vetor SCORES of size M-by-1 in which each row contains the function value \n% for the corresponding row of X.\n% For more information please visit: \n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = dropwavefcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'Drop-Wave function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    numeratorcomp = 1 + cos(12 * sqrt(X .^ 2 + Y .^ 2));\n    denumeratorcom = (0.5 * (X .^ 2 + Y .^ 2)) + 2;\n    scores = - numeratorcomp ./ denumeratorcom;\nend\n'''\nclass dropwavefcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-5.2, 5.2])\n        self.plot_bound = np.array([-5, 5])\n        self.n_var = 2\n        if n_var != self.n_var: print('Drop-Wave function is only defined on a 2D space.')\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        numeratorcomp = 1 + np.cos( 12 * np.sqrt( np.power(x1, 2) + np.power(x2, 2) ) )\n        denumeratorcom = 0.5 * ( np.power(x1, 2) + np.power(x2, 2) ) + 2\n        scores = - numeratorcomp / denumeratorcom\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Easom benchmark function.\n% SCORES = EASOMFCN(X) computes the value of the Easom function at point X.\n% EASOMFCN accepts a matrix of size M-by-2 and returns a vetor SCORES of \n% size M-by-1 in which each row contains the function value for the \n% corresponding row of X. For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = easomfcn(x)\n    \n    n = size(x, 2);\n    assert(n == 2, 'The Easom''s function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = -cos(X) .* cos(Y) .* exp(-( ((X - pi) .^2) + ((Y - pi) .^ 2)) );\nend\n'''\nclass easomfcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-100, 100])\n        self.plot_bound = np.array([-50, 50])\n        self.n_var = 2\n        if n_var != self.n_var: print('The Easom\\'s function is only defined on a 2D space.')\n        self.optimalX = np.zeros(self.n_var) + np.pi\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = - np.cos(x1) * np.cos(x2) * np.exp( -( np.power(x1 - np.pi, 2) + np.power(x2 - np.pi, 2) ) )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Egg Crate function.\n% SCORES = EGGCRATEFCN(X) computes the value of the Egg Crate \n% function at point X. EGGCRATEFCN accepts a matrix of size M-by-2 and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information, please visit:\n% benchmarkfcns.xyz/fcns/eggcratefcn\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = eggcratefcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'The Egg Crate function is defined only on the 2-D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = X.^2 + Y.^2 + (25 * (sin(X).^2 + sin(Y).^2));\nend \n'''\nclass eggcratefcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-5, 5])\n        self.plot_bound = self.boundaries\n        self.n_var = 2\n        if n_var != self.n_var: print('The Egg Crate function is defined only on the 2-D space.')\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = np.power(x1, 2) + np.power(x2, 2) + 25 * ( np.power( np.sin(x1), 2 ) + np.power( np.sin(x2), 2 ) )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Eggholder benchmark function.\n% SCORES = EGGHOLDERFCN(X) computes the value of the Eggholder\n% function at point X. EGGHOLDERFCN accepts a matrix of size M-by-2 \n% and returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X. For more information \n% please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = eggholderfcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'The Eggholder function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    sin1component = sin(sqrt(abs( (X / 2) + Y + 47)));\n    sin2component = sin(sqrt(abs( X - Y + 47)));\n    \n    scores = -(Y + 47) .* sin1component - (X .* sin2component);\nend\n'''\nclass eggholderfcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-512, 512])\n        self.plot_bound = np.array([-600, 600])\n        self.n_var = 2\n        if n_var != self.n_var: print('The Eggholder function is only defined on a 2D space.')\n        self.optimalX = np.array([512, 404.2319])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        sin1component = np.sin( np.sqrt( np.abs( (x1 / 2) + x2 + 47 ) ) )\n        sin2component = np.sin( np.sqrt( np.abs(x1 - (x2 + 47) ) ) )\n\n        scores = -(x2 + 47) * sin1component - (x1 * sin2component)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Exponential function.\n% SCORES = EXPONENTIALFCN(X) computes the value of the Exponential\n% function at point X. EXPONENTIALFCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = exponentialfcn(x)\n   x2 = x .^2;\n   \n   scores = -exp(-0.5 * sum(x2, 2));\nend\n'''\nclass exponentialfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-1, 1])\n        self.plot_bound = np.array([-2, 2])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        X1 = np.power(X, 2)\n\n        scores = -np.exp( -0.5 * np.sum(X1, axis=1) )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of GOldstein-Price benchmark function.\n% SCORES = GOLDSTEINPRICEFCN(X) computes the value of the GOLDSTEINPRICEFCN  \n% function at point X. GOLDSTEINPRICEFCN accepts a matrix of size M-by-2 \n% and returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = goldsteinpricefcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'The Goldstein-Price function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = (1 + ((X + Y + 1).^ 2) .* (19 - (14 * X) + (3 * (X .^2)) - 14 * Y + (6 .* X .* Y) + (3 * (Y.^2)))) .* ...\n        (30 + ((2 * X - 3 * Y).^2) .* (18 - 32 * X + 12 * (X .^2) + 48 * Y - (36 .* X .* Y) + (27 * (Y.^2))) );\nend\n'''\nclass goldsteinpricefcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-2, 2])\n        self.plot_bound = self.boundaries\n        self.n_var = 2\n        if n_var != self.n_var: print('The Goldstein-Price function is only defined on a 2D space.')\n        self.optimalX = np.array([0, -1])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = ( 1 + np.power(x1 + x2 + 1, 2) * ( 19 - 14 * x1 + 3 * np.power(x1, 2) - 14 * x2 + (6 * x1 * x2) + 3 * np.power(x2, 2) ) ) * \\\n            ( 30 + np.power(2 * x1 - 3 * x2, 2) * ( 18 - 32 * x1 + 12 * np.power(x1, 2) + 48 * x2 - (36 * x1 * x2) + 27 * np.power(x2, 2) ) )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Gramacy & Lee benchmark function.\n% SCORES = GRAMACYLEEFCN(X) computes the value of the Gramacy & Lee \n% function at point X. GRAMACYLEEFCN accepts a matrix of size M-by-2 and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = gramacyleefcn(x)\n    n = size(x, 2);\n    assert(n == 1, 'Gramacy & Lee function is only defined on a 1-D space.')\n\n    scores = (sin(10 .* pi .* x) ./ (2 * x) ) + ((x - 1) .^ 4);\nend\n'''\nclass gramacyleefcn():\n    def __init__(self, n_var=1):\n        self.boundaries = np.array([-0.5, 2.5])\n        self.plot_bound = self.boundaries\n        self.n_var = 1\n        if n_var != self.n_var: print('Gramacy & Lee function is only defined on a 1-D space.')\n        self.optimalX = np.array([0.548563444114526])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        scores = ( np.sin(10 * np.pi * X) / (2 * X + 1e-14) ) + np.power(X - 1, 4)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Griewank benchmark function.\n% SCORES = GRIEWANKFCN(X) computes the value of the Griewank's\n% function at point X. GRIEWANKFCN accepts a matrix of size M-by-N \n% and returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = griewankfcn(x)\n    \n    n = size(x, 2);\n    \n    sumcomp = 0;\n    prodcomp = 1;\n    \n    for i = 1:n\n        sumcomp = sumcomp + (x(:, i) .^ 2);\n        prodcomp = prodcomp .* (cos(x(:, i) / sqrt(i)));\n    end\n    \n    scores = (sumcomp / 4000) - prodcomp + 1;\nend\n'''\nclass griewankfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-600, 600])\n        self.plot_bound = np.array([-5, 5])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        n = self.n_var\n\n        sumcomp = 0\n        prodcomp = 1\n\n        for i in range(n):\n            sumcomp = sumcomp + np.power(X[:, i], 2)\n            prodcomp = prodcomp * ( np.cos( X[:, i] / np.sqrt(i + 1) ) )\n\n        scores = (sumcomp / 4000) - prodcomp + 1\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Happy Cat benchmark function.\n% SCORES = HAPPYCATFCN(X) computes the value of the Happy Cat function at \n% point X. HAPPYCATFCN accepts a matrix of size M-by-N and returns a vetor \n% SCORES of size M-by-1 in which each row contains the function value for \n% the corresponding row of X. \n% SCORES = HAPPYCAT(X, ALPHA) specifies power of the sphere component of \n% the function.\n% For more information please visit: \n% http://benchmarkfcns.xyz/benchmarkfcns/happycatfcn\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = happycatfcn(x, alpha)\n\n    if nargin < 2 \n        alpha = 0.5;\n    end\n    \n    n = size(x, 2);\n    x2 = sum(x .* x, 2);\n    scores = ((x2 - n).^2).^(alpha) + (0.5*x2 + sum(x,2))/n + 0.5;\nend\n'''\nclass happycatfcn():\n    def __init__(self, n_var=10, alpha=0.5):\n        self.boundaries = np.array([-2, 2])\n        self.plot_bound = self.boundaries\n        self.alpha = alpha\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var) - 1\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        n = X.shape[1]\n        x1 = np.sum(X * X, axis=1)\n        scores = np.power( np.power(x1 - n, 2), self.alpha ) + ( 0.5 * x1 + np.sum(X, axis=1) ) / n + 0.5\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Himmelblau's benchmark function.\n% SCORES = HIMMELBLAUFCN(X) computes the value of the Himmelblau's\n% function at point X. HIMMELBLAUFCN accepts a matrix of size M-by-2 \n% and returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Himmelblau's_function\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = himmelblaufcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'Himmelblau''s function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = ((X .^ 2 + Y - 11) .^2) + ((X + (Y .^ 2) - 7) .^ 2);\nend\n'''\nclass himmelblaufcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-6, 6])\n        self.plot_bound = np.array([-5, 5])\n        self.n_var = 2\n        if n_var != self.n_var: print('Himmelblau\\'s function is only defined on a 2D space.')\n        self.optimalX = np.array([3, 2])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = np.power( np.power(x1, 2) + x2 - 11, 2 ) + np.power( x1 + np.power(x2, 2) - 7, 2 )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the H�lder table benchmark function.\n% SCORES = HOLDERTABLEFCN(X) computes the value of the H�lder table  \n% function at point X. HOLDERTABLEFCN accepts a matrix of size M-by-2 and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X. For more information \n% please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = holdertablefcn(x)\n    \n    n = size(x, 2);\n    assert(n == 2, 'The H�lder table function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    expcomponent = exp( abs(1 - (sqrt(X .^2 + Y .^ 2) / pi)) );\n    \n    scores = -abs(sin(X) .* cos(Y) .* expcomponent);\nend\n'''\nclass holdertablefcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-10, 10])\n        self.plot_bound = self.boundaries\n        self.n_var = 2\n        if n_var != self.n_var: print('The Holder table function is only defined on a 2D space.')\n        self.optimalX = np.array([8.05502, 9.66459])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        expcomponent = np.exp( np.abs( 1 - ( np.sqrt( np.power(x1, 2) + np.power(x2, 2) ) / np.pi ) ) )\n\n        scores = -np.abs( np.sin(x1) * np.cos(x2) * expcomponent )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Keane function.\n% SCORES = KEANEFCN(X) computes the value of the Keane function at point X.\n% KEANEFCN accepts a matrix of size M-by-2 and returns a vetor SCORES of \n% size M-by-1 in which each row contains the function value for the \n% corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = keanefcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'Keane function is defined only on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    numeratorcomp = (sin(X - Y) .^ 2) .* (sin(X + Y) .^ 2); \n    denominatorcomp = sqrt(X .^2 + Y .^2);\n    scores = - numeratorcomp ./ denominatorcomp;\nend\n'''\nclass keanefcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([0, 10])\n        self.plot_bound = np.array([-10, 10])\n        self.n_var = 2\n        if n_var != self.n_var: print('Keane function is defined only on a 2D space.')\n        self.optimalX = np.array([1.393249070031784, 0])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n        \n        numeratorcomp = np.power( np.sin(x1 - x2), 2 ) * np.power( np.sin(x1 + x2), 2 )\n        denominatorcomp = np.sqrt( np.power(x1, 2) + np.power(x2, 2) ) + 1e-14\n        scores = - numeratorcomp / denominatorcomp\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Leon function.\n% SCORES = LEONFCN(X) computes the value of the Leon function at point X.\n% LEONFCN accepts a matrix of size M-by-2 and returns a vetor SCORES of \n% size M-by-1 in which each row contains the function value for the \n% corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = leonfcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'Leon function is defined only on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = 100 * ((Y - X.^3) .^2) + ((1 - X) .^2);\nend\n'''\nclass leonfcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([0, 10])\n        self.plot_bound = np.array([-1.5, 1.5])\n        self.n_var = 2\n        if n_var != self.n_var: print('Leon function is defined only on a 2D space.')\n        self.optimalX = np.zeros(self.n_var) + 1\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = 100 * np.power(x2 - np.power(x1, 3), 2) + np.power(1 - x1, 2)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the L�vi N. 13 benchmark function.\n% SCORES = LEVIN13FCN(X) computes the value of the L�vi N. 13 function at \n% point X. LEVIN13FCN accepts a matrix of size M-by-2 and returns a  \n% vetor SCORES of size M-by-1 in which each row contains the function value \n% for the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = levin13fcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'Levi''s function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    scores = sin(3 * pi * X) .^ 2 + ...\n        ((X - 1).^2) .* (1 + sin(3 * pi * Y) .^ 2) + ...\n        ((Y - 1).^2) .* (1 + sin(2 * pi * Y) .^ 2);\nend\n'''\nclass levin13fcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-10, 10])\n        self.plot_bound = self.boundaries\n        self.n_var = 2\n        if n_var != self.n_var: print('Levi\\'s function is only defined on a 2D space.')\n        self.optimalX = np.zeros(self.n_var) + 1\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n        scores = np.power( np.sin(3 * np.pi * x1), 2 ) + \\\n            np.power(x1 - 1, 2) * (1 + np.power( np.sin(3 * np.pi * x2), 2 ) ) + \\\n            np.power(x2 - 1, 2) * (1 + np.power( np.sin(2 * np.pi * x2), 2 ) )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Matyas benchmark function.\n% SCORES = MATYASFCN(X) computes the value of the Matyas function at \n% point X. MATYASFCN accepts a matrix of size M-by-2 and returns a  \n% vetor SCORES of size M-by-1 in which each row contains the function value \n% for the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = matyasfcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'Matyas''s function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = 0.26 * (X .^ 2 + Y.^2) - 0.48 * X .* Y;\nend\n'''\nclass matyasfcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-10, 10])\n        self.plot_bound = self.boundaries\n        self.n_var = 2\n        if n_var != self.n_var: print('Matyas\\'s function is only defined on a 2D space.')\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = 0.26 * ( np.power(x1, 2) + np.power(x2, 2) ) - 0.48 * x1 * x2\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the McCormick benchmark function.\n% SCORES = MCCORMICKFCN(X) computes the value of the McCormick function \n% at point X. MCCORMICKFCN accepts a matrix of size M-by-2 and returns a \n% vetor SCORES of size M-by-1 in which each row contains the function value \n% for the corresponding row of X. For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = mccormickfcn(x)\n    \n    n = size(x, 2);\n    assert(n == 2, 'The McCormick function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = sin(X + Y) + ((X - Y) .^2 ) - 1.5 * X + 2.5 * Y + 1;\nend\n'''\nclass mccormickfcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([ [-1.5, -3], [4, 3] ])\n        self.plot_bound = np.array([ [-2, -3], [4, 3] ])\n        self.n_var = 2\n        if n_var != self.n_var: print('The McCormick function is only defined on a 2D space.')\n        self.optimalX = np.array([-0.547, -1.547])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = np.sin(x1 + x2) + np.power(x1 - x2, 2) - 1.5 * x1 + 2.5 * x2 + 1\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Sum Square function.\n% SCORES = SUMSQUAREFCN(X) computes the value of the Periodic \n% function at point X. PERIODICFCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = periodicfcn(x)\n\n    sin2x = sin(x) .^ 2;\n    sumx2 = sum(x .^2, 2);\n    scores = 1 + sum(sin2x, 2) -0.1 * exp(-sumx2);\n    \nend\n'''\nclass periodicfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-10, 10])\n        self.plot_bound = np.array([-2, 2])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        sin2x = np.power( np.sin(X), 2 )\n        sumx2 = np.sum( np.power(X, 2), axis=1 )\n        scores = 1 + np.sum(sin2x, axis=1) -0.1 * np.exp(-sumx2)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Picheny benchmark function.\n% SCORES = PICHENYFCN(X) computes the value of the Beale function at \n% point X. PICHENYFCN accepts a matrix of size M-by-2 and returns a  \n% vetor SCORES of size M-by-1 in which each row contains the function value \n% for the corresponding row of X.\n% For more information please visit: \n% http://www.sfu.ca/~ssurjano/goldpr.html\n% Note: The Picheny function is a modification of the Goldstein-Price \n% function. \n% See also: goldsteinpricefcn.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = pichenyfcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'The Picheny function is only defined on a 2D space.')\n    X = 4 * x(:, 1) - 2;\n    Y = 4 * x(:, 2) - 2;\n    \n    term = (1 + ((X + Y + 1).^2) * (19 - (14 * X) + (3 * (X .^2)) - 14*Y + (6 .* X.*Y) + (3 * (Y.^2)))) .* ...\n        (30 + ((2 * X - 3 * Y).^2) .* (18 - 32 * X + 12 * (X .^2) + 48 * Y - (36 .* X.*Y) + (27 * (Y.^2))) );\n    coef = 1 / 2.427;\n    scores = coef * (log10(term) - 8.693);\nend\n'''\nclass pichenyfcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([0, 1])\n        self.plot_bound = np.array([-2, 2])\n        self.n_var = 2\n        if n_var != self.n_var: print('The Picheny function is only defined on a 2D space.')\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = 4 * X[:, 0] - 2\n        x2 = 4 * X[:, 1] - 2\n\n        term = ( 1 + np.power(x1 + x2 + 1, 2) * ( 19 - 14 * x1 + 3 * np.power(x1, 2) - 14 * x2 + 6 * x1 * x2 + 3 * np.power(x2, 2) ) ) * \\\n            ( 30 + np.power(2 * x1 - 3 * x2, 2) * (18 - 32 * x1 + 12 * np.power(x1, 2) + 48 * x2 - 36 * x1 * x2 + 27 * np.power(x2, 2) ) )\n        coef = 1 / 2.427\n        scores = coef * (np.log10(term) - 8.693)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Powell Sum benchmark function.\n% SCORES = POWELLSUMFCN(X) computes the value of the Powell Sum function at \n% point X. POWELLSUMFCN accepts a matrix of size M-by-N and returns a vetor \n% SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X. \n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = powellsumfcn(x)\n    n = size(x, 2);\n    absx = abs(x);\n    \n    scores = 0;\n    for i = 1:n\n        scores = scores + (absx(:, i) .^ (i + 1));\n    end\nend\n'''\nclass powellsumfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-1, 1])\n        self.plot_bound = np.array([-2, 2])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        n = X.shape[1]\n        absx = np.abs(X)\n\n        scores = 0\n        for i in range(n):\n            scores = scores + np.power(absx[:, i], i + 2)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Qing function.\n% SCORES = QINGFCN(X) computes the value of the Qing\n% function at point X. QINGFCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information, please visit:\n% benchmarkfcns.xyz/fcns/qingfcn\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = qingfcn(x)\n    n = size(x, 2);\n    x2 = x .^2;\n    \n    scores = 0;\n    for i = 1:n\n        scores = scores + (x2(:, i) - i) .^ 2;\n    end\nend \n'''\nclass qingfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-500, 500])\n        self.plot_bound = np.array([-2, 2])\n        self.n_var = n_var\n        self.optimalX = np.sqrt( (np.arange(self.n_var) + 1) )\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        n = X.shape[1]\n        X1 = np.power(X, 2)\n\n        scores = 0\n        for i in range(n):\n            scores = scores + np.power( X1[:, i] - (i + 1), 2 )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of Quartic benchmark function.\n% SCORES = QUARTICFCN(X) computes the value of the Quartic function at \n% point X. QUARTICFCN accepts a matrix of size M-by-N and returns a vetor \n% SCORES of size M-by-1 in which each row contains the function value for\n% each row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = quarticfcn(x)\n\n    n = size(x, 2);\n    \n    scores = 0;\n    for i = 1:n\n        scores = scores + i *(x(:, i) .^ 4);\n    end\n     \n    scores = scores + rand;\nend\n'''\nclass quarticfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-1.28, 1.28])\n        self.plot_bound = self.boundaries\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        n = X.shape[1]\n\n        scores = 0\n        for i in range(n):\n            scores = scores + (i + 1) * np.power(X[:, i], 4)\n\n        scores = scores + np.random.rand(len(scores))\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of Rastrigin benchmark function.\n% SCORES = RASTRIGINFCN(X) computes the value of the Rastrigin function at \n% point X. RASTRIGINFCN accepts a matrix of size M-by-N and returns a vetor \n% SCORES of size M-by-1 in which each row contains the function value for\n% the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Rastrigin_function\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction f = rastriginfcn(x)\n    n = size(x, 2);\n    A = 10;\n    f = (A * n) + (sum(x .^2 - A * cos(2 * pi * x), 2));\nend\n'''\nclass rastriginfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-5.12, 5.12])\n        self.plot_bound = np.array([-5, 5])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        A = 10\n        scores = (A * self.n_var) + np.sum( np.power(X, 2) - A * np.cos(2 * np.pi * X), axis=1 )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Ridge benchmark function.\n% SCORES = RIDGEFCN(X) computes the value of the Ridge function at point X.\n% RIDGEFCN accepts a matrix of size M-by-N and returns a vetor SCORES of \n% size M-by-1 in which each row contains the function value for the \n% corresponding row of X. \n% SCORES = RIDGEFCN(X, D) specifies contribution coefficient of the sphere \n% component of the function.\n% SCORES = RIDGEFCN(X, D, ALPHA) specifies power of the sphere component of \n% the function.\n% \n% For more information please visit: \n% http://benchmarkfcns.xyz/benchmarkfcns/ridgefcn\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = ridgefcn(x, d, alpha)\n\n    if nargin < 3 \n        alpha = 0.5;\n    end\n    if nargin < 2\n        d = 1;\n    end\n        \n    x1 = x(:, 1);\n    scores = x1 + d * (sum(x(:, 2:end).^2, 2) .^ alpha);\nend\n'''\nclass ridgefcn():\n    def __init__(self, n_var=10, d=1, alpha=0.5):\n        self.boundaries = np.array([-5, 5])\n        self.plot_bound = np.array([-2, 2])\n        self.d = d\n        self.alpha = alpha\n        self.n_var = n_var\n        self.optimalX = np.hstack( [self.boundaries[0], np.zeros(self.n_var - 1)] )\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        scores = x1 + self.d * np.power( np.sum( np.power(X[:, 1:], 2), axis=1), self.alpha )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Rosenbrock benchmark function.\n% SCORES = ROSENBROCKFCN(X) computes the value of the Rosenbrock function  \n% at point X. ROSENBROCKFCN accepts a matrix of size M-by-N and returns a  \n% vetor SCORES of size M-by-1 in which each row contains the function value \n% for the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Rosenbrock_function\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = rosenbrockfcn(x)\n    scores = 0;\n    n = size(x, 2);\n    assert(n >= 1, 'Given input X cannot be empty');\n    a = 1;\n    b = 100;\n    for i = 1 : (n-1)\n        scores = scores + (b * ((x(:, i+1) - (x(:, i).^2)) .^ 2)) + ((a - x(:, i)) .^ 2);\n    end\nend\n'''\nclass rosenbrockfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-5, 10])\n        self.plot_bound = np.array([-10, 10])\n        self.n_var = int( max(1, n_var) )\n        if n_var < 1: print('Given input X cannot be empty')\n        self.optimalX = np.zeros(self.n_var) + 1\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        scores = 0\n        a = 1\n        b = 100\n        for i in range(self.n_var - 1):\n            scores = scores + b * np.power( X[:, i+1] - np.power(X[:, i], 2), 2 ) + np.power(a - X[:, i], 2)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Salomon's benchmark function.\n% SCORES = SALOMONFCN(X) computes the value of the Salomon's   \n% function at point X. SALOMONFCN accepts a matrix of size M-by-N  \n% and returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = salomonfcn(x)\n    x2 = x .^ 2;\n    sumx2 = sum(x2, 2);\n    sqrtsx2 = sqrt(sumx2);\n    \n    scores = 1 - cos(2 .* pi .* sqrtsx2) + (0.1 * sqrtsx2);\nend\n'''\nclass salomonfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-100, 100])\n        self.plot_bound = np.array([-4, 4])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        X1 = np.power(X, 2)\n        sumx2 = np.sum(X1, axis=1)\n        sqrtsx2 = np.sqrt(sumx2)\n\n        scores = 1 - np.cos(2 * np.pi * sqrtsx2) + (0.1 * sqrtsx2)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Schaffer N. 1 function.\n% SCORES = SCHAFFERN1FCN(X) computes the value of the Schaffer N. 1 \n% function at point X. SCHAFFERN1FCN accepts a matrix of size M-by-2 and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = schaffern1fcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'Schaffer function N. 1 is defined only on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    numeratorcomp = (sin((X .^ 2 + Y .^ 2) .^ 2) .^ 2) - 0.5; \n    denominatorcomp = (1 + 0.001 * (X .^2 + Y .^2)) .^2 ;\n    scores = 0.5 + numeratorcomp ./ denominatorcomp;\nend\n'''\nclass schaffern1fcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-100, 100])\n        self.plot_bound = np.array([-50, 50])\n        self.n_var = 2\n        if n_var != self.n_var: print('Schaffer function N. 1 is defined only on a 2D space.')\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        numeratorcomp = np.power( np.sin( np.power( np.power(x1, 2) + np.power(x2, 2), 2 ) ), 2) - 0.5\n        denominatorcomp = np.power( 1 + 0.001 * ( np.power(x1, 2) + np.power(x2, 2) ), 2 )\n        scores = 0.5 + numeratorcomp / denominatorcomp\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Schaffer N. 2 benchmark function.\n% SCORES = SCHAFFERN2FCN(X) computes the value of the Schaffer N. 2 function \n% at point X. SCHAFFERN2FCN accepts a matrix of size M-by-2 and returns a \n% vetor SCORES of size M-by-1 in which each row contains the function value \n% for the corresponding row of X. For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = schaffern2fcn(x)\n    \n    n = size(x, 2);\n    assert(n == 2, 'The Schaffer N. 2 function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    sincomponent = sin( (X .^ 2) - (Y .^ 2) ).^2;\n    \n    scores = 0.5 + ((sincomponent - 0.5) ./ (1 + 0.001 * (X .^2 + Y .^2)) .^2 ) ;\nend\n'''\nclass schaffern2fcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-100, 100])\n        self.plot_bound = np.array([-50, 50])\n        self.n_var = 2\n        if n_var != self.n_var: print('The Schaffer N. 2 function is only defined on a 2D space.')\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        sincomponent = np.power( np.sin( np.power(x1, 2) - np.power(x2, 2) ), 2 )\n\n        scores = 0.5 + (sincomponent - 0.5) / np.power( 1 + 0.001 * ( np.power(x1, 2) + np.power(x2, 2) ), 2 )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Schaffer N. 3 function.\n% SCORES = SCHAFFERN3FCN(X) computes the value of the Schaffer N. 3  \n% function at point X. SCHAFFERN3FCN accepts a matrix of size M-by-2 and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = schaffern3fcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'Schaffer function N. 3 is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    numeratorcomp = (sin(cos(abs(X .^ 2 - Y .^ 2))) .^ 2) - 0.5; \n    denominatorcomp = (1 + 0.001 * (X .^2 + Y .^2)) .^2 ;\n    scores = 0.5 + numeratorcomp ./ denominatorcomp;\nend\n'''\nclass schaffern3fcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-100, 100])\n        self.plot_bound = np.array([-50, 50])\n        self.n_var = 2\n        if n_var != self.n_var: print('Schaffer function N. 3 is only defined on a 2D space.')\n        self.optimalX = np.array([0, 1.253115])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        numeratorcomp = np.power( np.sin( np.cos( np.abs( np.power(x1, 2) - np.power(x2, 2) ) ) ), 2 ) - 0.5\n        denominatorcomp = np.power( 1 + 0.001 * ( np.power(x1, 2) + np.power(x2, 2) ), 2 )\n        scores = 0.5 + numeratorcomp / denominatorcomp\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Schaffer N. 4 function.\n% SCORES = SCHAFFERN4FCN(X) computes the value of the Schaffer N. 4  \n% function at point X. SCHAFFERN4FCN accepts a matrix of size M-by-2 and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = schaffern4fcn(x)\n    n = size(x, 2);\n    assert(n == 2, 'Schaffer function N. 4 is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    numeratorcomp = (cos(sin(abs(X .^ 2 - Y .^ 2))) .^ 2) - 0.5; \n    denominatorcomp = (1 + 0.001 * (X .^2 + Y .^2)) .^2 ;\n    scores = 0.5 + numeratorcomp ./ denominatorcomp;\nend\n'''\nclass schaffern4fcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-100, 100])\n        self.plot_bound = np.array([-50, 50])\n        self.n_var = 2\n        if n_var != self.n_var: print('Schaffer function N. 4 is only defined on a 2D space.')\n        self.optimalX = np.array([0, 1.253115])\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        numeratorcomp = np.power( np.cos( np.sin( np.abs( np.power(x1, 2) - np.power(x2, 2) ) ) ), 2 ) - 0.5\n        denominatorcomp = np.power( 1 + 0.001 * ( np.power(x1, 2) + np.power(x2, 2) ), 2 )\n        scores = 0.5 + numeratorcomp / denominatorcomp\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Schwefel 2.20 function.\n% SCORES = SCHWEFEL220FCN(X) computes the value of the Schwefel 2.20 \n% function at point X. SCHWEFEL220FCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = schwefel220fcn(x)\n    scores = sum(abs(x), 2);\nend\n'''\nclass schwefel220fcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-100, 100])\n        self.plot_bound = np.array([-10, 10])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        scores = np.sum( np.abs(X), axis=1 )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Schwefel 2.21 function.\n% SCORES = SCHWEFEL221FCN(X) computes the value of the Schwefel 2.21 \n% function at point X. SCHWEFEL221FCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = schwefel221fcn(x)\n    scores = max(abs(x), [], 2);\nend\n'''\nclass schwefel221fcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-100, 100])\n        self.plot_bound = np.array([-10, 10])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        scores = np.max( np.abs(X), axis=1 )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Schwefel 2.22 function.\n% SCORES = SCHWEFEL222FCN(X) computes the value of the Schwefel 2.22 \n% function at point X. SCHWEFEL222FCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = schwefel222fcn(x)\n\n    absx = abs(x);\n    scores = sum(absx, 2) + prod(absx, 2);\nend\n'''\nclass schwefel222fcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-100, 100])\n        self.plot_bound = np.array([-10, 10])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        absx = np.abs(X)\n        scores = np.sum(absx, axis=1) + np.prod(absx, axis=1)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Schwefel 2.23 function.\n% SCORES = SCHWEFEL223FCN(X) computes the value of the Schwefel 2.23 \n% function at point X. SCHWEFEL223FCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = schwefel223fcn(x)\n    scores = sum(x .^10, 2);\nend\n'''\nclass schwefel223fcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-10, 10])\n        self.plot_bound = self.boundaries\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        scores = np.sum( np.power(X, 10), axis=1)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Schwefel benchmark function.\n% SCORES = SCHWEFELFCN(X) computes the value of the Schwefel function at \n% point X. SCHWEFELFCN accepts a matrix of size M-by-2 and returns a  \n% vetor SCORES of size M-by-1 in which each row contains the function value \n% for the corresponding row of X.\n% For more information please visit: \n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = schwefelfcn(x)\n    n = size(x, 2);\n    scores = 418.9829 * n - (sum(x .* sin(sqrt(abs(x))), 2));\nend\n'''\nclass schwefelfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-500, 500])\n        self.plot_bound = self.boundaries\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var) + 420.968746\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        scores = 418.982887272433799807913601398 * self.n_var - np.sum( X * np.sin( np.sqrt( np.abs(X) ) ), axis=1 )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of Sphere benchmark function.\n% SCORES = SPHEREFCN(X) computes the value of the Ackey function at \n% point X. SPHEREFCN accepts a matrix of size M-by-N and returns a vetor \n% SCORES of size M-by-1 in which each row contains the function value for\n% each row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction f = spherefcn(x)\n    f = sum(x .^ 2, 2);\nend\n'''\nclass spherefcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-5.12, 5.12])\n        self.plot_bound = np.array([-5, 5])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        scores = np.sum( np.power(X, 2), axis=1 )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Styblinski-Tank benchmark function.\n% SCORES = STYBLINSKITANKFCN(X) computes the value of the Styblinski-Tank  \n% function at point X. STYBLINSKITANKFCN accepts a matrix of size M-by-2 \n% and returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = styblinskitankfcn(x)\n    n = size(x, 2);\n    scores = 0;\n    for i = 1:n\n        scores = scores + ((x(:, i) .^4) - (16 * x(:, i) .^ 2) + (5 * x(:, i)));\n    end\n    scores = 0.5 * scores;\nend\n'''\nclass styblinskitankfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-5, 5])\n        self.plot_bound = self.boundaries\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var) - 2.903534\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        scores = 0\n        for i in range(self.n_var):\n            scores = scores + ( np.power(X[:, i], 4) - 16 * np.power(X[:, i], 2) + 5 * X[:, i] )\n        scores = 0.5 * scores\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Sum Squares function.\n% SCORES = SUMSQUARESFCN(X) computes the value of the Sum Squares\n% function at point X. SUMSQUARESFCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = sumsquaresfcn(x)\n   \n   [m, n] = size(x);\n   x2 = x .^2;\n   I = repmat(1:n, m, 1);\n   scores = sum( I .* x2, 2);\n   \nend\n'''\nclass sumsquaresfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-10, 10])\n        self.plot_bound = self.boundaries\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x2 = np.power(X, 2)\n        I = np.arange(1, self.n_var + 1)\n        scores = np.sum( I * x2, axis=1 )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Three-hump camel benchmark function.\n% SCORES = THREEHUMPCAMELFCN(X) computes the value of the Three-hump camel   \n% function at point X. THREEHUMPCAMELFCN accepts a matrix of size M-by-2  \n% and returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information please visit: \n% https://en.wikipedia.org/wiki/Test_functions_for_optimization\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = threehumpcamelfcn(x)\n    \n    n = size(x, 2);\n    assert(n == 2, 'The Three-hump camel function is only defined on a 2D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    \n    scores = (2 * X .^ 2) - (1.05 * (X .^ 4)) + ((X .^ 6) / 6) + X .* Y + Y .^2;\nend\n'''\nclass threehumpcamelfcn():\n    def __init__(self, n_var=2):\n        self.boundaries = np.array([-5, 5])\n        self.plot_bound = np.array([-2, 2])\n        self.n_var = 2\n        if n_var != self.n_var: print('The Three-hump camel function is only defined on a 2D space.')\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n\n        scores = 2 * np.power(x1, 2) - 1.05 * np.power(x1, 4) + ( np.power(x1, 6) / 6 ) + x1 * x2 + np.power(x2, 2)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Wolfe function.\n% SCORES = WOLFEFCN(X) computes the value of the Wolfe \n% function at point X. WOLFEFCN accepts a matrix of size M-by-3 and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information, please visit:\n% benchmarkfcns.xyz/fcns/wolfefcn\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = wolfefcn(x)\n    n = size(x, 2);\n    assert(n == 3, 'The Wolfe function is defined only on the 3-D space.')\n    X = x(:, 1);\n    Y = x(:, 2);\n    Z = x(:, 3);\n    \n    scores = (4/3)*(((X .^ 2 + Y .^ 2) - (X .* Y)).^(0.75)) + Z;\nend \n'''\nclass wolfefcn():\n    def __init__(self, n_var=3):\n        self.boundaries = np.array([0, 2])\n        self.plot_bound = self.boundaries\n        self.n_var = 3\n        if n_var != self.n_var: print('The Wolfe function is defined only on the 3-D space.')\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        x1 = X[:, 0]\n        x2 = X[:, 1]\n        x3 = X[:, 2]\n\n        scores = (4/3) * np.power( np.power(x1, 2) + np.power(x2, 2) - (x1 * x2), 0.75 ) + x3\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Xin-She Yang function.\n% SCORES = XINSHEYANGN1FCN(X) computes the value of the Xin-She Yang\n% function at point X. XINSHEYANGN1FCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information, please visit:\n% benchmarkfcns.xyz/fcns/xinsheyangn1fcn\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = xinsheyangn1fcn(x)\n    n = size(x, 2);\n\n    scores = 0;\n    for i = 1:n\n        scores = scores + rand * (abs(x(:, i)) .^ i);\n    end\nend \n'''\nclass xinsheyangn1fcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-5, 5])\n        self.plot_bound = self.boundaries\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        scores = 0\n        for i in range(self.n_var):\n            scores = scores + np.random.rand(X.shape[0]) * np.power( np.abs(X[:, i]), i + 1 )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Xin-She Yang N. 2 function.\n% SCORES = XINSHEYANGN2FCN(X) computes the value of the Xin-She Yang N. 2\n% function at point X. XINSHEYANGN2FCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information, please visit:\n% benchmarkfcns.xyz/fcns/xinsheyangn2fcn\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = xinsheyangn2fcn(x)\n     scores = sum(abs(x), 2) .* exp(-sum(sin(x .^2), 2));\nend \n'''\nclass xinsheyangn2fcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-2 * np.pi, 2 * np.pi])\n        self.plot_bound = np.array([-10, 10])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        scores = np.sum( np.abs(X), axis=1) * np.exp( -np.sum( np.sin( np.power(X, 2) ), axis=1) )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Xin-She Yang N. 3 function.\n% The Xin-She Yang N. 3 function is a parametric function and it is\n% behaviour can be controlled with two additional parameters 'beta' and \n% 'm'. In this implementation, the parameters are optional and when not\n% given, their default value will be used. \n% SCORES = XINSHEYANGN3FCN(X) computes the value of the Xin-She Yang N. 3\n% function at point X. XINSHEYANGN3FCN accepts a matrix of size P-by-N and \n% returns a vetor SCORES of size P-by-1 in which each row contains the \n% function value for the corresponding row of X. In this case, the default\n% values of 'm=5' and 'beta=15' is used for function parameters. \n% SCORES = XINSHEYANGN3FCN(X, BETA) computes the function with the given\n% value of BETA for its 'beta' parameter. In this case, the default value\n% of 'm=5' will be used for the parameter. \n% SCORES = XINSHEYANGN3FCN(X, BETA, M) computes the function with the given\n% value of M for its 'm' parameter.\n% For more information, please visit:\n% benchmarkfcns.xyz/fcns/xinsheyangn3fcn\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = xinsheyangn3fcn(x, beta, m)\n   if nargin < 2\n       beta = 15;\n   end\n   if nargin < 3\n       m = 5;\n   end\n   \n   scores = exp(-sum((x / beta).^(2*m), 2)) - (2 * exp(-sum(x .^ 2, 2)) .* prod(cos(x) .^ 2, 2));\nend \n'''\nclass xinsheyangn3fcn():\n    def __init__(self, n_var=10, beta=15, m=5):\n        self.boundaries = np.array([-2 * np.pi, 2 * np.pi])\n        self.plot_bound = np.array([-10, 10])\n        self.beta = beta\n        self.m = m\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        scores = np.exp( -np.sum( np.power(X / self.beta, 2 * self.m), axis=1 ) ) - \\\n            ( 2 * np.exp( -np.sum( np.power(X, 2), axis=1 ) ) * np.prod( np.power( np.cos(X), 2 ), axis=1 ) )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of the Xin-She Yang N. 4 function.\n% SCORES = XINSHEYANGN4FCN(X) computes the value of the Xin-She Yang N. 4\n% function at point X. XINSHEYANGN4FCN accepts a matrix of size M-by-N and \n% returns a vetor SCORES of size M-by-1 in which each row contains the \n% function value for the corresponding row of X.\n% For more information, please visit:\n% benchmarkfcns.xyz/fcns/xinsheyangn4fcn\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = xinsheyangn4fcn(x)\n     scores = (sum(sin(x) .^2, 2) - exp(-sum(x .^ 2, 2))) .* exp(-sum(sin(sqrt(abs(x))) .^2, 2));\nend \n'''\nclass xinsheyangn4fcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-10, 10])\n        self.plot_bound = self.boundaries\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        scores = ( np.sum( np.power( np.sin(X), 2 ), axis=1 ) - np.exp( -np.sum( np.power(X, 2), axis=1 ) ) ) * \\\n            np.exp( -np.sum( np.power( np.sin( np.sqrt( np.abs(X) ) ), 2 ), axis=1 ) )\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()\n\n'''ORIGINAL MATLAB IMPLEMENTATION\n% Computes the value of Zakharov benchmark function.\n% SCORES = ZAKHAROVFCN(X) computes the value of the Zakharov function at \n% point X. ZAKHAROVFCN accepts a matrix of size M-by-N and returns a vetor \n% SCORES of size M-by-1 in which each row contains the function value for\n% each row of X.\n% \n% Author: Mazhar Ansari Ardeh\n% Please forward any comments or bug reports to mazhar.ansari.ardeh at\n% Google's e-mail service or feel free to kindly modify the repository.\nfunction scores = zakharovfcn(x)\n\n    n = size(x, 2);\n    comp1 = 0;\n    comp2 = 0;\n    \n    for i = 1:n\n        comp1 = comp1 + (x(:, i) .^ 2);\n        comp2 = comp2 + (0.5 * i * x(:, i));\n    end\n     \n    scores = comp1 + (comp2 .^ 2) + (comp2 .^ 4);\nend\n'''\nclass zakharovfcn():\n    def __init__(self, n_var=10):\n        self.boundaries = np.array([-5, 10])\n        self.plot_bound = np.array([-10, 10])\n        self.n_var = n_var\n        self.optimalX = np.zeros(self.n_var)\n        self.optimalF = self.f(self.optimalX)\n\n    def F(self, X):\n        comp1 = 0\n        comp2 = 0\n\n        for i in range(self.n_var):\n            comp1 = comp1 + np.power(X[:, i], 2)\n            comp2 = comp2 + 0.5 * (i + 1) * X[:, i]\n\n        scores = comp1 + np.power(comp2, 2) + np.power(comp2, 4)\n        return scores\n\n    def f(self, x):\n        return self.F(x[None, :]).item()", "meta": {"hexsha": "0a25e6e230b87516aabc1a007606bd57bed86d73", "size": 87195, "ext": "py", "lang": "Python", "max_stars_repo_path": "PyBenchFCN/SingleObjectiveProblem.py", "max_stars_repo_name": "Y1fanHE/PyBenchFCN", "max_stars_repo_head_hexsha": "a572dd1481ef639cb6036c3bb322d7da3c4c6482", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-04-30T01:51:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T12:14:35.000Z", "max_issues_repo_path": "PyBenchFCN/SingleObjectiveProblem.py", "max_issues_repo_name": "Y1fanHE/PyBenchFCN", "max_issues_repo_head_hexsha": "a572dd1481ef639cb6036c3bb322d7da3c4c6482", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyBenchFCN/SingleObjectiveProblem.py", "max_forks_repo_name": "Y1fanHE/PyBenchFCN", "max_forks_repo_head_hexsha": "a572dd1481ef639cb6036c3bb322d7da3c4c6482", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0161090458, "max_line_length": 142, "alphanum_fraction": 0.6218934572, "include": true, "reason": "import numpy", "num_tokens": 27116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321452198369, "lm_q2_score": 0.8856314723088733, "lm_q1q2_score": 0.8540334274894723}}
{"text": "'''\nThe file is collected from https://github.com/BorjaBalle/analytic-gaussian-mechanism\n\nB. Balle and Y.-X. Wang. Improving the Gaussian Mechanism for Differential Privacy: Analytical Calibration and Optimal Denoising. International Conference on Machine Learning (ICML), 2018.\n'''\n\n\nfrom math import exp, sqrt\nfrom scipy.special import erf\n\ndef calibrateAnalyticGaussianMechanism(epsilon, delta, GS, tol = 1.e-12):\n    \"\"\" Calibrate a Gaussian perturbation for differential privacy using the analytic Gaussian mechanism of [Balle and Wang, ICML'18]\n\n    Arguments:\n    epsilon : target epsilon (epsilon > 0)\n    delta : target delta (0 < delta < 1)\n    GS : upper bound on L2 global sensitivity (GS >= 0)\n    tol : error tolerance for binary search (tol > 0)\n\n    Output:\n    sigma : standard deviation of Gaussian noise needed to achieve (epsilon,delta)-DP under global sensitivity GS\n    \"\"\"\n\n    def Phi(t):\n        return 0.5*(1.0 + erf(float(t)/sqrt(2.0)))\n\n    def caseA(epsilon,s):\n        return Phi(sqrt(epsilon*s)) - exp(epsilon)*Phi(-sqrt(epsilon*(s+2.0)))\n\n    def caseB(epsilon,s):\n        return Phi(-sqrt(epsilon*s)) - exp(epsilon)*Phi(-sqrt(epsilon*(s+2.0)))\n\n    def doubling_trick(predicate_stop, s_inf, s_sup):\n        while(not predicate_stop(s_sup)):\n            s_inf = s_sup\n            s_sup = 2.0*s_inf\n        return s_inf, s_sup\n\n    def binary_search(predicate_stop, predicate_left, s_inf, s_sup):\n        s_mid = s_inf + (s_sup-s_inf)/2.0\n        while(not predicate_stop(s_mid)):\n            if (predicate_left(s_mid)):\n                s_sup = s_mid\n            else:\n                s_inf = s_mid\n            s_mid = s_inf + (s_sup-s_inf)/2.0\n        return s_mid\n\n    delta_thr = caseA(epsilon, 0.0)\n\n    if (delta == delta_thr):\n        alpha = 1.0\n\n    else:\n        if (delta > delta_thr):\n            predicate_stop_DT = lambda s : caseA(epsilon, s) >= delta\n            function_s_to_delta = lambda s : caseA(epsilon, s)\n            predicate_left_BS = lambda s : function_s_to_delta(s) > delta\n            function_s_to_alpha = lambda s : sqrt(1.0 + s/2.0) - sqrt(s/2.0)\n\n        else:\n            predicate_stop_DT = lambda s : caseB(epsilon, s) <= delta\n            function_s_to_delta = lambda s : caseB(epsilon, s)\n            predicate_left_BS = lambda s : function_s_to_delta(s) < delta\n            function_s_to_alpha = lambda s : sqrt(1.0 + s/2.0) + sqrt(s/2.0)\n\n        predicate_stop_BS = lambda s : abs(function_s_to_delta(s) - delta) <= tol\n\n        s_inf, s_sup = doubling_trick(predicate_stop_DT, 0.0, 1.0)\n        s_final = binary_search(predicate_stop_BS, predicate_left_BS, s_inf, s_sup)\n        alpha = function_s_to_alpha(s_final)\n        \n    sigma = alpha*GS/sqrt(2.0*epsilon)\n\n    return sigma\n", "meta": {"hexsha": "f4ec150010559d7f6124e0aaa669e5402a2eb568", "size": 2756, "ext": "py", "lang": "Python", "max_stars_repo_path": "notears/aGM.py", "max_stars_repo_name": "pckennethma/NoLeaks-artifact", "max_stars_repo_head_hexsha": "b75873168e20ef3edd18d569c2f0af28cc16d880", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notears/aGM.py", "max_issues_repo_name": "pckennethma/NoLeaks-artifact", "max_issues_repo_head_hexsha": "b75873168e20ef3edd18d569c2f0af28cc16d880", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notears/aGM.py", "max_forks_repo_name": "pckennethma/NoLeaks-artifact", "max_forks_repo_head_hexsha": "b75873168e20ef3edd18d569c2f0af28cc16d880", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2631578947, "max_line_length": 188, "alphanum_fraction": 0.6364296081, "include": true, "reason": "from scipy", "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214470715363, "lm_q2_score": 0.8856314692902446, "lm_q1q2_score": 0.8540334200380596}}
{"text": "import math\nimport random\n\nimport cv2\nimport numpy as np\n\neTranslate = 0\neHomography = 1\n\n\ndef computeHomography(f1, f2, matches, A_out=None):\n    '''\n    Input:\n        f1 -- list of cv2.KeyPoint objects in the first image\n        f2 -- list of cv2.KeyPoint objects in the second image\n        matches -- list of cv2.DMatch objects\n            DMatch.queryIdx: The index of the feature in the first image\n            DMatch.trainIdx: The index of the feature in the second image\n            DMatch.distance: The distance between the two features\n        A_out -- ignore this parameter. If computeHomography is needed\n                 in other TODOs, call computeHomography(f1,f2,matches)\n    Output:\n        H -- 2D homography (3x3 matrix)\n        Takes two lists of features, f1 and f2, and a list of feature\n        matches, and estimates a homography from image 1 to image 2 from the matches.\n    '''\n    num_matches = len(matches)\n\n    # Dimensions of the A matrix in the homogenous linear\n    # equation Ah = 0\n    num_rows = 2 * num_matches\n    num_cols = 9\n    A_matrix_shape = (num_rows,num_cols)\n    A = np.zeros(A_matrix_shape)\n\n    for i in range(len(matches)):\n        m = matches[i]\n        (a_x, a_y) = f1[m.queryIdx].pt\n        (b_x, b_y) = f2[m.trainIdx].pt\n\n        #BEGIN TODO 2\n        #Fill in the matrix A in this loop.\n        #Access elements using square brackets. e.g. A[0,0]\n        #TODO-BLOCK-BEGIN\n        A[2*i][0]=a_x\n        A[2*i][1]=a_y\n        A[2*i][2]=1\n        A[2*i][3]=0\n        A[2*i][4]=0\n        A[2*i][5]=0\n        A[2*i][6]=a_x*-1*b_x\n        A[2*i][7]=a_y*-1*b_x\n        A[2*i][8]=-1*b_x\n        A[2*i+1][0]=0\n        A[2*i+1][1]=0\n        A[2*i+1][2]=0\n        A[2*i+1][3]=a_x\n        A[2*i+1][4]=a_y\n        A[2*i+1][5]=1\n        A[2*i+1][6]=a_x*-1*b_y\n        A[2*i+1][7]=a_y*-1*b_y\n        A[2*i+1][8]=-1*b_y\n        #TODO-BLOCK-END\n        #END TODO\n\n    U, s, Vt = np.linalg.svd(A)\n\n    if A_out is not None:\n        A_out[:] = A\n\n    #s is a 1-D array of singular values sorted in descending order\n    #U, Vt are unitary matrices\n    #Rows of Vt are the eigenvectors of A^TA.\n    #Columns of U are the eigenvectors of AA^T.\n\n    #Homography to be calculated\n    H = np.eye(3)\n\n    #BEGIN TODO 3\n    #Fill the homography H with the appropriate elements of the SVD\n    #TODO-BLOCK-BEGIN\n    min = len(Vt)-1\n    H[0][0] = Vt[min][0]\n    H[0][1] = Vt[min][1]\n    H[0][2] = Vt[min][2]\n    H[1][0] = Vt[min][3]\n    H[1][1] = Vt[min][4]\n    H[1][2] = Vt[min][5]\n    H[2][0] = Vt[min][6]\n    H[2][1] = Vt[min][7]\n    H[2][2] = Vt[min][8]\n    #TODO-BLOCK-END\n    #END TODO\n\n    return H\n\ndef alignPair(f1, f2, matches, m, nRANSAC, RANSACthresh):\n    '''\n    Input:\n        f1 -- list of cv2.KeyPoint objects in the first image\n        f2 -- list of cv2.KeyPoint objects in the second image\n        matches -- list of cv2.DMatch objects\n            DMatch.queryIdx: The index of the feature in the first image\n            DMatch.trainIdx: The index of the feature in the second image\n            DMatch.distance: The distance between the two features\n        m -- MotionModel (eTranslate, eHomography)\n        nRANSAC -- number of RANSAC iterations\n        RANSACthresh -- RANSAC distance threshold\n\n    Output:\n        M -- inter-image transformation matrix\n        Repeat for nRANSAC iterations:\n            Choose a minimal set of feature matches.\n            Estimate the transformation implied by these matches\n            count the number of inliers.\n        For the transformation with the maximum number of inliers,\n        compute the least squares motion estimate using the inliers,\n        and return as a transformation matrix M.\n    '''\n\n    #BEGIN TODO 4\n    #Write this entire method.  You need to handle two types of\n    #motion models, pure translations (m == eTranslation) and\n    #full homographies (m == eHomography).  However, you should\n    #only have one outer loop to perform the RANSAC code, as\n    #the use of RANSAC is almost identical for both cases.\n\n    #Your homography handling code should call compute_homography.\n    #This function should also call get_inliers and, at the end,\n    #least_squares_fit.\n    #TODO-BLOCK-BEGIN\n    inlier_indices = []\n    iic = []\n    for i in range(nRANSAC):\n        if m == eTranslate:\n            simple = random.randint(0,len(matches)-1)\n            simple_match = matches[simple]\n            (a_x, a_y) = f1[simple_match.queryIdx].pt\n            (b_x, b_y) = f2[simple_match.trainIdx].pt\n            trans = np.array([[1,0,b_x-a_x],[0,1,b_y-a_y],[0,0,1]])\n        elif m == eHomography:\n            new_matches = []\n            simple1 = random.randint(0, len(matches)-1)\n            simple2 = random.randint(0, len(matches)-1)\n            simple3 = random.randint(0, len(matches)-1)\n            simple4 = random.randint(0, len(matches)-1)\n            new_matches.append(matches[simple1])\n            new_matches.append(matches[simple2])\n            new_matches.append(matches[simple3])\n            new_matches.append(matches[simple4])\n            trans = computeHomography(f1,f2,new_matches)\n        else:\n            raise Exception(\"Error: Invalid motion model.\")\n\n        inlier_indices.append(getInliers(f1, f2, matches, trans, RANSACthresh))\n        iic.append(len(inlier_indices[i]))\n    index = iic.index(max(iic))\n    M = leastSquaresFit(f1,f2,matches,m,inlier_indices[index])\n\n    #raise Exception(\"TODO in alignment.py not implemented\")\n    #TODO-BLOCK-END\n    #END TODO\n    return M\n\ndef getInliers(f1, f2, matches, M, RANSACthresh):\n    '''\n    Input:\n        f1 -- list of cv2.KeyPoint objects in the first image\n        f2 -- list of cv2.KeyPoint objects in the second image\n        matches -- list of cv2.DMatch objects\n            DMatch.queryIdx: The index of the feature in the first image\n            DMatch.trainIdx: The index of the feature in the second image\n            DMatch.distance: The distance between the two features\n        M -- inter-image transformation matrix\n        RANSACthresh -- RANSAC distance threshold\n\n    Output:\n        inlier_indices -- inlier match indices (indexes into 'matches')\n\n        Transform the matched features in f1 by M.\n        Store the match index of features in f1 for which the transformed\n        feature is within Euclidean distance RANSACthresh of its match\n        in f2.\n        Return the array of the match indices of these features.\n    '''\n\n    inlier_indices = []\n\n    for i in range(len(matches)):\n        #BEGIN TODO 5\n        #Determine if the ith matched feature f1[id1], when transformed\n        #by M, is within RANSACthresh of its match in f2.\n        #If so, append i to inliers\n        #TODO-BLOCK-BEGIN\n        m = matches[i]\n        M /= M[2][2]\n        (a_x, a_y) = f1[m.queryIdx].pt\n        (b_x, b_y) = f2[m.trainIdx].pt\n        xy = np.array([[a_x],[a_y],[1]])\n        new_xy = np.matmul(M,xy)\n        new_xy /= new_xy[2][0]\n        a_x = new_xy[0][0]\n        a_y = new_xy[1][0]\n        m.distance = np.sqrt((a_x-b_x)**2+(a_y-b_y)**2)\n\n        if m.distance<RANSACthresh:\n            inlier_indices.append(i)\n        # raise Exception(\"TODO in alignment.py not implemented\")\n        #TODO-BLOCK-END\n        #END TODO\n\n    return inlier_indices\n\ndef leastSquaresFit(f1, f2, matches, m, inlier_indices):\n    '''\n    Input:\n        f1 -- list of cv2.KeyPoint objects in the first image\n        f2 -- list of cv2.KeyPoint objects in the second image\n        matches -- list of cv2.DMatch objects\n            DMatch.queryIdx: The index of the feature in the first image\n            DMatch.trainIdx: The index of the feature in the second image\n            DMatch.distance: The distance between the two features\n        m -- MotionModel (eTranslate, eHomography)\n        inlier_indices -- inlier match indices (indexes into 'matches')\n\n    Output:\n        M - transformation matrix\n\n        Compute the transformation matrix from f1 to f2 using only the\n        inliers and return it.\n    '''\n\n    # This function needs to handle two possible motion models,\n    # pure translations (eTranslate)\n    # and full homographies (eHomography).\n\n    M = np.eye(3)\n\n    if m == eTranslate:\n        #For spherically warped images, the transformation is a\n        #translation and only has two degrees of freedom.\n        #Therefore, we simply compute the average translation vector\n        #between the feature in f1 and its match in f2 for all inliers.\n\n        u = 0.0\n        v = 0.0\n\n        for i in range(len(inlier_indices)):\n            #BEGIN TODO 6\n            #Use this loop to compute the average translation vector\n            #over all inliers.\n            #TODO-BLOCK-BEGIN\n            mch = matches[inlier_indices[i]]\n            (a_x, a_y) = f1[mch.queryIdx].pt\n            (b_x, b_y) = f2[mch.trainIdx].pt\n            u+=(b_x-a_x)\n            v+=(b_y-a_y)\n            #raise Exception(\"TODO in alignment.py not implemented\")\n            #TODO-BLOCK-END\n            #END TODO\n\n        u /= len(inlier_indices)\n        v /= len(inlier_indices)\n\n        M[0,2] = u\n        M[1,2] = v\n\n    elif m == eHomography:\n        #BEGIN TODO 7\n        #Compute a homography M using all inliers.\n        #This should call computeHomography.\n        #TODO-BLOCK-BEGIN\n        Match = []\n        for k in range(len(inlier_indices)):\n            Match.append(matches[inlier_indices[k]])\n        M = computeHomography(f1,f2,Match)\n        # raise Exception(\"TODO in alignment.py not implemented\")\n        #TODO-BLOCK-END\n        #END TODO\n\n    else:\n        raise Exception(\"Error: Invalid motion model.\")\n\n    return M\n\n", "meta": {"hexsha": "fe220c742494f661e5a1ae9fe1978f0e4b77df56", "size": 9612, "ext": "py", "lang": "Python", "max_stars_repo_path": "Exp3_Panorama/alignment.py", "max_stars_repo_name": "Xiayue09/VisionExp", "max_stars_repo_head_hexsha": "732e88004a9e39601caecde3c0f78f3ffbdd2995", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-09-30T13:50:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-19T09:14:50.000Z", "max_issues_repo_path": "Exp3_Panorama/alignment.py", "max_issues_repo_name": "Xiayue09/VisionExp", "max_issues_repo_head_hexsha": "732e88004a9e39601caecde3c0f78f3ffbdd2995", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-22T08:51:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-22T08:51:24.000Z", "max_forks_repo_path": "Exp3_Panorama/alignment.py", "max_forks_repo_name": "Xiayue09/VisionExp", "max_forks_repo_head_hexsha": "732e88004a9e39601caecde3c0f78f3ffbdd2995", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-04T04:03:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T13:39:56.000Z", "avg_line_length": 33.6083916084, "max_line_length": 85, "alphanum_fraction": 0.6011235955, "include": true, "reason": "import numpy", "num_tokens": 2635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214501476359, "lm_q2_score": 0.8856314647623016, "lm_q1q2_score": 0.8540334183959576}}
{"text": "import numpy as np\n\n\ndef quantile(sample: np.ndarray, p: float, type: int = 7,\n             sorted: bool = False, interpolate: bool = True) -> float:\n    \"\"\"\n    Estimate a desired quantile of a univariate distribution from a vector of samples\n\n    Parameters\n    ----------\n    sample\n        A 1D vector of values\n    p\n        The desired quantile in (0,1)\n    type\n        The method for computing the quantile.\n        See https://wikipedia.org/wiki/Quantile#Estimating_quantiles_from_a_sample\n    sorted\n        Whether or not the vector is already sorted into ascending order\n    interpolate\n        Whether to interpolate the desired quantile.\n\n    Returns\n    -------\n    An estimate of the quantile\n\n    \"\"\"\n    N = len(sample)\n    if N == 0:\n        raise ValueError(\"Cannot compute quantiles with zero samples.\")\n\n    if len(sample.shape) != 1:\n        raise ValueError(\"Quantile estimation only supports vectors of univariate samples.\")\n    if not 1/N <= p <= (N-1)/N:\n        raise ValueError(f\"The {p}-quantile should not be estimated using only {N} samples.\")\n\n    sorted_sample = sample if sorted else np.sort(sample)\n\n    if type == 6:\n        h = (N+1)*p\n    elif type == 7:\n        h = (N-1)*p + 1\n    elif type == 8:\n        h = (N+1/3)*p + 1/3\n    else:\n        raise ValueError(\"type must be an int with value 6, 7 or 8.\")\n    h_floor = int(h)\n    quantile = sorted_sample[h_floor-1]\n    if h_floor != h and interpolate:\n        quantile += (h - h_floor)*(sorted_sample[h_floor]-sorted_sample[h_floor-1])\n\n    return float(quantile)\n", "meta": {"hexsha": "6b4af49e5e25ba8b6d6efe5ef38d4cacdeb078df", "size": 1556, "ext": "py", "lang": "Python", "max_stars_repo_path": "alibi_detect/utils/misc.py", "max_stars_repo_name": "sugatoray/alibi-detect", "max_stars_repo_head_hexsha": "66d7873c248c0be1a1d836e6fe1ef59351b802d9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1227, "max_stars_repo_stars_event_min_datetime": "2019-11-19T15:38:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:18:32.000Z", "max_issues_repo_path": "alibi_detect/utils/misc.py", "max_issues_repo_name": "sugatoray/alibi-detect", "max_issues_repo_head_hexsha": "66d7873c248c0be1a1d836e6fe1ef59351b802d9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 323, "max_issues_repo_issues_event_min_datetime": "2019-11-21T18:41:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:08:56.000Z", "max_forks_repo_path": "alibi_detect/utils/misc.py", "max_forks_repo_name": "sugatoray/alibi-detect", "max_forks_repo_head_hexsha": "66d7873c248c0be1a1d836e6fe1ef59351b802d9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 133, "max_forks_repo_forks_event_min_datetime": "2019-11-19T14:23:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:55:43.000Z", "avg_line_length": 29.358490566, "max_line_length": 93, "alphanum_fraction": 0.618251928, "include": true, "reason": "import numpy", "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.9086178956955642, "lm_q1q2_score": 0.8540220931136936}}
{"text": "#!/usr/bin/env python\nimport numpy as np\n\nx = np.array([[1,2],[3,4]], dtype=np.float64)\ny = np.array([[5,6],[7,8]], dtype=np.float64)\n\n# Elementwise sum; both produce the array\n# [[ 6.0  8.0]\n#  [10.0 12.0]]\nprint x + y\nprint np.add(x, y)\n\n# Elementwise difference; both produce the array\n# [[-4.0 -4.0]\n#  [-4.0 -4.0]]\nprint x - y\nprint np.subtract(x, y)\n\n# Elementwise product; both produce the array\n# [[ 5.0 12.0]\n#  [21.0 32.0]]\nprint x * y\nprint np.multiply(x, y)\n\n# Elementwise division; both produce the array\n# [[ 0.2         0.33333333]\n#  [ 0.42857143  0.5       ]]\nprint x / y\nprint np.divide(x, y)\n\n# Elementwise square root; produces the array\n# [[ 1.          1.41421356]\n#  [ 1.73205081  2.        ]]\nprint np.sqrt(x)\n\n\nx = np.array([[1,2],[3,4]])\ny = np.array([[5,6],[7,8]])\n\nv = np.array([9,10])\nw = np.array([11, 12])\n\n# Inner product of vectors; both produce 219\nprint v.dot(w)\nprint np.dot(v, w)\n\n# Matrix / vector product; both produce the rank 1 array [29 67]\nprint x.dot(v)\nprint np.dot(x, v)\n\n# Matrix / matrix product; both produce the rank 2 array\n# [[19 22]\n#  [43 50]]\nprint x.dot(y)\nprint np.dot(x, y)\n\n\nx = np.array([[1,2],[3,4]])\n\nprint np.sum(x)  # Compute sum of all elements; prints \"10\"\nprint np.sum(x, axis=0)  # Compute sum of each column; prints \"[4 6]\"\nprint np.sum(x, axis=1)  # Compute sum of each row; prints \"[3 7]\"\n\n\nx = np.array([[1,2], [3,4]])\nprint x    # Prints \"[[1 2]\n           #          [3 4]]\"\nprint x.T  # Prints \"[[1 3]\n           #          [2 4]]\"\n\n# Note that taking the transpose of a rank 1 array does nothing:\nv = np.array([1,2,3])\nprint v    # Prints \"[1 2 3]\"\nprint v.T  # Prints \"[1 2 3]\"\n\n\n\n\n# We will add the vector v to each row of the matrix x,\n# storing the result in the matrix y\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\nv = np.array([1, 0, 1])\ny = np.empty_like(x)   # Create an empty matrix with the same shape as x\n\n# Add the vector v to each row of the matrix x with an explicit loop\nfor i in range(4):\n    y[i, :] = x[i, :] + v\n\n# Now y is the following\n# [[ 2  2  4]\n#  [ 5  5  7]\n#  [ 8  8 10]\n#  [11 11 13]]\nprint y\n\n\n# We will add the vector v to each row of the matrix x,\n# storing the result in the matrix y\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\nv = np.array([1, 0, 1])\nvv = np.tile(v, (4, 1))  # Stack 4 copies of v on top of each other\nprint vv                 # Prints \"[[1 0 1]\n                         #          [1 0 1]\n                         #          [1 0 1]\n                         #          [1 0 1]]\"\ny = x + vv  # Add x and vv elementwise\nprint y  # Prints \"[[ 2  2  4\n         #          [ 5  5  7]\n         #          [ 8  8 10]\n         #          [11 11 13]]\"\n\n\n# We will add the vector v to each row of the matrix x,\n# storing the result in the matrix y\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\nv = np.array([1, 0, 1])\ny = x + v  # Add v to each row of x using broadcasting\nprint y  # Prints \"[[ 2  2  4]\n         #          [ 5  5  7]\n         #          [ 8  8 10]\n         #          [11 11 13]]\"\n\n\n# Compute outer product of vectors\nv = np.array([1,2,3])  # v has shape (3,)\nw = np.array([4,5])    # w has shape (2,)\n# To compute an outer product, we first reshape v to be a column\n# vector of shape (3, 1); we can then broadcast it against w to yield\n# an output of shape (3, 2), which is the outer product of v and w:\n# [[ 4  5]\n#  [ 8 10]\n#  [12 15]]\nprint np.reshape(v, (3, 1)) * w\n\n# Add a vector to each row of a matrix\nx = np.array([[1,2,3], [4,5,6]])\n# x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),\n# giving the following matrix:\n# [[2 4 6]\n#  [5 7 9]]\nprint x + v\n\n# Add a vector to each column of a matrix\n# x has shape (2, 3) and w has shape (2,).\n# If we transpose x then it has shape (3, 2) and can be broadcast\n# against w to yield a result of shape (3, 2); transposing this result\n# yields the final result of shape (2, 3) which is the matrix x with\n# the vector w added to each column. Gives the following matrix:\n# [[ 5  6  7]\n#  [ 9 10 11]]\nprint (x.T + w).T\n# Another solution is to reshape w to be a row vector of shape (2, 1);\n# we can then broadcast it directly against x to produce the same\n# output.\nprint x + np.reshape(w, (2, 1))\n\n# Multiply a matrix by a constant:\n# x has shape (2, 3). Numpy treats scalars as arrays of shape ();\n# these can be broadcast together to shape (2, 3), producing the\n# following array:\n# [[ 2  4  6]\n#  [ 8 10 12]]\nprint x * 2\n\n\n", "meta": {"hexsha": "7086a6d6a5187b9b6e4c54857713930200b8b4d2", "size": 4464, "ext": "py", "lang": "Python", "max_stars_repo_path": "cnn_python_tutorial/numpy/math.py", "max_stars_repo_name": "DeercoderPractice/python", "max_stars_repo_head_hexsha": "4a32cc8922f47baea390e8167e34f185f67ae0fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cnn_python_tutorial/numpy/math.py", "max_issues_repo_name": "DeercoderPractice/python", "max_issues_repo_head_hexsha": "4a32cc8922f47baea390e8167e34f185f67ae0fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cnn_python_tutorial/numpy/math.py", "max_forks_repo_name": "DeercoderPractice/python", "max_forks_repo_head_hexsha": "4a32cc8922f47baea390e8167e34f185f67ae0fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8915662651, "max_line_length": 72, "alphanum_fraction": 0.5649641577, "include": true, "reason": "import numpy", "num_tokens": 1604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.9334308175109686, "lm_q1q2_score": 0.8539967398630733}}
{"text": "\n# coding: utf-8\n\n# $\\newcommand{\\xv}{\\mathbf{x}}\n# \\newcommand{\\Xv}{\\mathbf{X}}\n# \\newcommand{\\yv}{\\mathbf{y}}\n# \\newcommand{\\zv}{\\mathbf{z}}\n# \\newcommand{\\av}{\\mathbf{a}}\n# \\newcommand{\\Wv}{\\mathbf{W}}\n# \\newcommand{\\wv}{\\mathbf{w}}\n# \\newcommand{\\tv}{\\mathbf{t}}\n# \\newcommand{\\Tv}{\\mathbf{T}}\n# \\newcommand{\\muv}{\\boldsymbol{\\mu}}\n# \\newcommand{\\sigmav}{\\boldsymbol{\\sigma}}\n# \\newcommand{\\phiv}{\\boldsymbol{\\phi}}\n# \\newcommand{\\Phiv}{\\boldsymbol{\\Phi}}\n# \\newcommand{\\Sigmav}{\\boldsymbol{\\Sigma}}\n# \\newcommand{\\Lambdav}{\\boldsymbol{\\Lambda}}\n# \\newcommand{\\half}{\\frac{1}{2}}\n# \\newcommand{\\argmax}[1]{\\underset{#1}{\\operatorname{argmax}}}\n# \\newcommand{\\argmin}[1]{\\underset{#1}{\\operatorname{argmin}}}$\n\n# # Assignment 1: Linear Regression\n\n# *by Vignesh M. Pagadala*\n\n# ## Overview\n\n# Describe the objective of this assignment, and very briefly how you accomplish it.  Say things like \"linear model\", \"samples of inputs and known desired outputs\" and \"minimize the sum of squared errors\". DELETE THIS TEXT AND INSERT YOUR OWN.\n\n# ## Method\n\n# Define in code cells the following functions as discussed in class.  Your functions' arguments and return types must be as shown here.\n# \n#   * ```model = train(X, T)```\n#   * ```predict = use(model, X)```\n#   * ```error = rmse(predict, T)```\n#   \n# Let ```X``` be a two-dimensional matrix (```np.array```) with each row containing one data sample, and ```T``` be a two-dimensional matrix of one column containing the target values for each sample in ```X```.  So, ```X.shape[0]``` is equal to ```T.shape[0]```.   \n# \n# Function ```train``` must standardize the input data in ```X``` and return a dictionary with  keys named ```means```, ```stds```, and ```w```.  \n# \n# Function ```use``` must also standardize its input data X by using the means and standard deviations in the dictionary returned by ```train```.\n# \n# Function ```rmse``` returns the square root of the mean of the squared error between ```predict``` and ```T```.\n# \n# Also implement the function\n# \n#    * ```model = trainSGD(X, T, learningRate, numberOfIterations)```\n# \n# which performs the incremental training process described in class as stochastic gradient descent (SGC).  The result of this function is a dictionary with the same keys as the dictionary returned by the above ```train``` function.\n\n# In[16]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef train(X, T):\n    # Standardize input data (X)\n\n    # Calculate mean and std.\n    means = X.mean(axis = 0)\n    std = X.std(axis = 0)\n\n    Xs = (X - means) / std\n\n    # Tack a column of 1s\n    Xs = np.insert(Xs, 0, 1, 1)\n\n    # Use Xs to generate model (w)\n    w = np.linalg.lstsq(Xs.T @ Xs, Xs.T @ T, rcond = None)[0]\n\n    # Return as a dictionary\n    dict = {'means': means, 'stds': std, 'w': w}\n    return dict\n\ndef use(model, X):\n    # Use model and input X to predict.\n    means = model['means']\n    std = model['stds']\n    w = model['w']\n\n    # Standardize X\n    Xs = (X - means) / std\n\n    # Tack column of 1s\n    Xs = np.insert(Xs, 0, 1, 1)\n\n    # Predict\n    predict = Xs @ w\n    #print(Xs.shape)\n    #print(w.shape)\n    return predict\n\ndef rmse(predict, T):\n    rmerr = np.sqrt(np.mean((T - predict) ** 2))\n    return rmerr\n\ndef trainSGD(X, T, learningRate, numberOfIterations):\n    # Standardize inputs X.\n    means = X.mean(axis = 0)\n    std = X.std(axis = 0)\n    Xs = (X - means) / std\n\n    nSamples = Xs.shape[0]\n    ncolsT = T.shape[1]\n\n    # Tack a column of 1s\n    Xs = np.insert(Xs, 0, 1, 1)\n    ncolsX = Xs.shape[1]\n    # Initialize weights to zero.\n    w = np.zeros((ncolsX, ncolsT))\n\n    for i in range(numberOfIterations):\n        for n in range(nSamples):\n            predicted = Xs[n:n+1, :] @ w\n            w += learningRate * Xs[n:n+1, :].T * (T[n:n+1, :] - predicted)\n\n    dict = {'means': means, 'stds': std, 'w': w}\n    return dict\n\n\n# In this section, ilatex math formulas defining the formula that is being minimized, and the matrix calculation for finding the weights. \n# \n# In this section, include all necessary imports and the function definitions. Also include some math formulas using latex syntax that define the formula being minimized and the calculation of the weights using a matrix equation.  You do not need to include the math formulas showing the derivations.\n\n# ## Examples\n\n# In[13]:\n\n\n# from A1mysolution import *\n\n\n# In[18]:\n\n\nimport numpy as np\n\nX = np.arange(10).reshape((5,2))\nT = X[:,0:1] + 2 * X[:,1:2] + np.random.uniform(-1, 1,(5, 1))\nprint('Inputs')\nprint(X)\nprint('Targets')\nprint(T)\n\n\n# In[19]:\n\n\nmodel = train(X, T)\nmodel\n\n\n# In[20]:\n\n\npredicted = use(model, X)\npredicted\n\n\n# In[21]:\n\n\nrmse(predicted, T)\n\n\n# In[22]:\n\n\nmodelSGD = trainSGD(X, T, 0.01, 100)\nmodelSGD\n\n\n# In[23]:\n\n\npredicted = use(modelSGD, X)\npredicted\n\n\n# In[24]:\n\n\nrmse(predicted, T)\n\n\n# ## Data\n\n# Download ```energydata_complete.csv``` from the [Appliances energy prediction Data Set ](https://archive.ics.uci.edu/ml/datasets/Appliances+energy+prediction) at the UCI Machine Learning Repository. Ignore the first column (date and time), use the next two columns as target variables, and use all but the last two columns (named rv1 and rv2) as input variables. \n# \n# In this section include a summary of this data, including the number of samples, the number and kinds of input variables, and the number and kinds of target variables.  Also mention who recorded the data and how.  Some of this information can be found in the paper that is linked to at the UCI site for this data set.  Also show some plots of target variables versus some of the input variables to investigate whether or not linear relationships might exist.  Discuss your observations of these plots.\n\n# ## Results\n\n# Apply your functions to the data.  Compare the error you get as a result of both training functions.  Experiment with different learning rates for ```trainSGD``` and discuss the errors.\n# \n# Make some plots of the predicted energy uses and the actual energy uses versus the sample index.  Also plot predicted energy use versus actual energy use.  Show the above plots for the appliances energy use and repeat them for the lights energy use. Discuss your observations of each graph.\n# \n# Show the values of the resulting weights and discuss which ones might be least relevant for fitting your linear model.  Remove them, fit the linear model again, plot the results, and discuss what you see.\n\n# ## Grading\n# \n# Your notebook will be run and graded automatically.  Test this grading process by first downloading [A1grader.tar](http://www.cs.colostate.edu/~anderson/cs445/notebooks/A1grader.tar) and extract `A1grader.py` from it. Run the code in the following cell (after deleting the one containing A1mysolution) to demonstrate an example grading session.  You should see a perfect execution score of 70/70 if your functions are defined correctly. The remaining 30 points will be based on the results you obtain from the energy data and on your discussions.\n# \n# A different, but similar, grading script will be used to grade your checked-in notebook.  It will include additional tests.  You need not include code to test that the values passed in to your functions are the correct form.  \n\n# In[25]:\n\n\nget_ipython().run_line_magic('run', '-i \"A1grader.py\"')\n\n\n# ## Check-in\n\n# Do not include this section in your notebook.\n# \n# Name your notebook ```Lastname-A1.ipynb```.  So, for me it would be ```Anderson-A1.ipynb```.  Submit the file using the ```Assignment 1``` link on [Canvas](https://colostate.instructure.com/courses/41327).\n# \n# Grading will be based on \n# \n#   * correct behavior of the required functions listed above,\n#   * easy to understand plots in your notebook,\n#   * readability of the notebook,\n#   * effort in making interesting observations, and in formatting your notebook.\n\n# ## Extra Credit\n\n# Download a second data set and repeat all of the steps of this assignment on that data set.\n", "meta": {"hexsha": "5c3afa91ff54864e609b32eb1888ce44955d6dbb", "size": 7921, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/notebook-code.py", "max_stars_repo_name": "vignesh-pagadala/linear-regression", "max_stars_repo_head_hexsha": "eb7f5e0c5e25cf8a5320fa5ae00db3222ccc577b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/notebook-code.py", "max_issues_repo_name": "vignesh-pagadala/linear-regression", "max_issues_repo_head_hexsha": "eb7f5e0c5e25cf8a5320fa5ae00db3222ccc577b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/notebook-code.py", "max_forks_repo_name": "vignesh-pagadala/linear-regression", "max_forks_repo_head_hexsha": "eb7f5e0c5e25cf8a5320fa5ae00db3222ccc577b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.29004329, "max_line_length": 548, "alphanum_fraction": 0.6872869587, "include": true, "reason": "import numpy", "num_tokens": 2175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.9334308147331957, "lm_q1q2_score": 0.8539967394875494}}
{"text": "# coding: utf-8\nimport numpy as np\n\ndef softmax(x):\n    if x.ndim == 2:\n        x = x.T\n        x = x - np.max(x, axis=0)\n        y = np.exp(x) / np.sum(np.exp(x), axis=0)\n        return y.T\n\n    x = x - np.max(x) # 오버플로 대책\n    return np.exp(x) / np.sum(np.exp(x))\n\n\nx = np.array([-1, 0, 1.0])\ny = softmax(x)\n\np = np.argmax(y) # 확률이 가장 높은 원소의 인덱스를 얻는다.\n\nprint(x)\nprint(y)\nprint(p)\n'''\n[-1.  0.  1.]\n[ 0.09003057  0.24472847  0.66524096]\n2\n\nfrom Java\nv = -1.000000, 0.000000, 1.000000\nv2 = 0.090031, 0.244728, 0.665241\n\n'''", "meta": {"hexsha": "98d7cfd251400ff77281328dc708c657ba657f23", "size": 522, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/softmaxtest.py", "max_stars_repo_name": "dalek7/umbrella", "max_stars_repo_head_hexsha": "cabf0367940905ca5164d104d7aef6ff719ee166", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-09T09:12:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T09:12:02.000Z", "max_issues_repo_path": "Python/softmaxtest.py", "max_issues_repo_name": "dalek7/umbrella", "max_issues_repo_head_hexsha": "cabf0367940905ca5164d104d7aef6ff719ee166", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/softmaxtest.py", "max_forks_repo_name": "dalek7/umbrella", "max_forks_repo_head_hexsha": "cabf0367940905ca5164d104d7aef6ff719ee166", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.3125, "max_line_length": 49, "alphanum_fraction": 0.5325670498, "include": true, "reason": "import numpy", "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993888, "lm_q2_score": 0.8933094110250331, "lm_q1q2_score": 0.8539871402027768}}
{"text": "from scipy.optimize import newton\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Objective function formalization\ndef obj_fun():\n    return lambda x: 2 * (x ** 4) - 4 * (x ** 2) + x - 0.5\n\n\n# Plot objective function\ndef plot_obj_fun(x):\n    return 2 * x ** 4 - 4 * (x ** 2) + x - 0.5\n\n\n# First derivative\ndef der_obj_fun(x):\n    return (8 * (x ** 3)) - (8 * x) + 1\n\n\n# Second derivative\ndef sec_der_obj_func(x):\n    return (24 * (x ** 2)) - (8 * x)\n\n\n# DESCENT GRADIENT\nprint(\"SOLVING WITH GRADIENT DESCENT METHOD\")\n# Initial guess\nx0s = [-2, -0.5, 0.5, 2]\n# stop criterion\naccuracy = pow(10, -4)\nfor x0 in x0s:\n    label_x0 = \"initial point [\" + str(x0) + \", \" + str(plot_obj_fun(x0)) + \"]\"\n    plt.scatter(x0, plot_obj_fun(x0), color='yellow', edgecolor='black', label=label_x0)\n    # maximum number of iterations\n    max_iters = 1000\n    # iteration count\n    iters = 0\n    previous_step_size = 1\n    # Learning rate\n    rate = 0.01\n    current = x0\n    while previous_step_size > accuracy and iters < max_iters:\n        # Current x will be previous in next step\n        previous = current\n        # Gradient descent\n        current = current - rate * der_obj_fun(previous)\n        # Distance moved\n        previous_step_size = abs(current - previous)\n        # iteration count\n        iters += 1\n        # plot\n        plt.scatter(current, plot_obj_fun(current), color='red', edgecolor='black')\n    print(\"Initial point: \", x0)\n    print(\"Local minimum: \", current)\n    print(\"Number of iterations: \", iters)\n    # Plot\n    # define range for input\n    x0 = np.linspace(-2, 2)\n    plt.plot(x0, plot_obj_fun(x0))\n    # plot minimal point\n    label_min = \"minimal point [\" + str(current) + \", \" + str(plot_obj_fun(current)) + \"]\"\n    plt.scatter(current, plot_obj_fun(current), color='green', edgecolor='black', label=label_min)\n    plt.legend(prop={'size': 6}, loc='best')\n    plt.show()\n\n\n# NEWTON'S METHOD\nprint(\"SOLVING WITH NEWTON'S METHOD\")\nx0s = [-2, -0.5, 0.5, 2]\nfor x0 in x0s:\n    g = newton(func=der_obj_fun, x0=x0, fprime=sec_der_obj_func, tol=0.0001, full_output=True)\n    # print(g)\n    r = g[1]\n    print(\"initial point:\", x0)\n    print(\"Value:\", r.root)\n    print(\"Number of iterations: \", r.iterations)", "meta": {"hexsha": "a1a5257bd5fff91f2095e5fc41ddf1690130a114", "size": 2229, "ext": "py", "lang": "Python", "max_stars_repo_path": "Exercise_6b.py", "max_stars_repo_name": "albacg5/TOML-Project1", "max_stars_repo_head_hexsha": "4c1a8caa785e1a1c09165f8b870d02db5dc472f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Exercise_6b.py", "max_issues_repo_name": "albacg5/TOML-Project1", "max_issues_repo_head_hexsha": "4c1a8caa785e1a1c09165f8b870d02db5dc472f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercise_6b.py", "max_forks_repo_name": "albacg5/TOML-Project1", "max_forks_repo_head_hexsha": "4c1a8caa785e1a1c09165f8b870d02db5dc472f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9480519481, "max_line_length": 98, "alphanum_fraction": 0.6231493943, "include": true, "reason": "import numpy,from scipy", "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813551535004, "lm_q2_score": 0.8933094081846421, "lm_q1q2_score": 0.8539871386077256}}
{"text": "\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport cv2\nprint(tf.__version__)\n\n\"\"\"## Let's discuss the Convolution operation\n\nWe have an overlay, multiply and add process encapsulated in the term called convolution. We have kernels that convolve themselves with images to give us the output image. The nitty gritty gets us into the world of matrix sizes. We have:\n\n`output_height = input_height - kernel_height + 1`\n\nand \n\n`output_width = input_width - kernel_width + 1`\n\"\"\"\n\nfrom google.colab.patches import cv2_imshow\ninput_image = cv2.imread(\"sample_data/original.jpg\", 0)\ncv2_imshow(input_image)\n\n\"\"\"## I'm sick of these zeros and those kernels so let's talk about it\n\nI can either be valid to get a smaller output, same to equal the input size, or be full and get a larger image.\n\n### Output size\n\n`valid = N - K + 1`\n\n`same = N`\n\n`full = N + K - 1`\n\"\"\"\n\ndef convolution(input_image, kernel_image):\n  # So we'll coded the convolution operation here; from scratch ! \n  input_width = input_image.shape[1]\n  input_height = input_image.shape[0]\n  kernel_width = kernel_image.shape[1]\n  kernel_height = kernel_image.shape[0]\n  output_height = input_height - kernel_height + 1\n  output_width = input_width - kernel_width + 1\n  output = np.zeros((output_height, output_width))\n  for k in range(0, output_height):\n    for j in range(0, output_width):\n      for w in range(0, kernel_height):\n        for v in range(0, kernel_width):\n          output[k, j] += input_image[k+w, j+v] * kernel_image[w, v]\n  return output\n\ndef convolution_flipped(input_image, kernel_image):\n  # So we'll coded the convolution operation here; from scratch ! \n  input_width = input_image.shape[1]\n  input_height = input_image.shape[0]\n  kernel_width = kernel_image.shape[1]\n  kernel_height = kernel_image.shape[0]\n  output_height = input_height - kernel_height + 1\n  output_width = input_width - kernel_width + 1\n  output = np.zeros((output_height, output_width))\n  for k in range(0, output_height):\n    for j in range(0, output_width):\n      for w in range(0, kernel_height):\n        for v in range(0, kernel_width):\n          output[k, j] += input_image[k-w, j-v] * kernel_image[w, v]\n  return output\n\nkernel_image = np.array([-5, -5, -5, 0, 0, 0, 5, 5, 5]).reshape(3,3)\nkernel_image\n\noutput = convolution(input_image, kernel_image)\ncv2_imshow(output)\n\noutput = convolution_flipped(input_image, kernel_image)\ncv2_imshow(output)\n\n\"\"\"## Do we have to write such complicated equations? \n\nWell no, scipy has convolve2d, which does all the convolutions for us!, \nBUT WAIT\nDo they flip it? let's find out\n\"\"\"\n\nfrom scipy.signal import convolve2d, correlate2d\noutput = convolve2d(input_image, kernel_image, mode = 'valid')\ncv2_imshow(output)\n\n# The output shows a flipped filter, let's try correlation\noutput = correlate2d(input_image, kernel_image, mode = 'valid')\ncv2_imshow(output)\n\noutput = convolve2d(input_image, np.fliplr(np.flipud(kernel_image)), mode = 'valid')\ncv2_imshow(output)\n\n\"\"\"## Let's talk about color convolution\n\nSuppose: \n\ninput image = 28 x 28 x 3\n\nfilter = 3 x 5 x 5 x 64\n\n## the filter shape 3 x 5 x 5 x 64 = 4800 is the number of weights \n\nOutput image =  (28 - 5 + 1) x (28 - 5 + 1) x 64\n\"\"\"\n\n\n\n\"\"\"## CONVOLUTION IN COLORS\"\"\"\n\nfrom google.colab.patches import cv2_imshow\ninput_image = cv2.imread(\"sample_data/original.jpg\")\ncv2_imshow(input_image)\n\ninput_image.shape\n\nfilters = np.array([-5, -5, -5, 0, 0, 0, 5, 5, 5]).reshape(3,3)\nkernel_image = np.array([filters, filters, filters])\nkernel_image\n\nkernel_image.shape\n\ndef convolution3d(input_image, kernel_image):\n  # So we'll coded the convolution operation here; from scratch ! \n  input_width = input_image.shape[1]\n  input_height = input_image.shape[0]\n  kernel_width = kernel_image.shape[1]\n  kernel_height = kernel_image.shape[0]\n  output_height = input_height - kernel_height + 1\n  output_width = input_width - kernel_width + 1\n  output = np.zeros((output_height, output_width, input_image.shape[2]))\n  for c in range(0, input_image.shape[2]):\n    for k in range(0, output_height):\n      for j in range(0, output_width):\n        for w in range(0, kernel_height):\n          for v in range(0, kernel_width):\n            output[k, j, c] += input_image[k+w, j+v, c] * kernel_image[w, v, c]\n  return output\n\ndef correlation3d(input_image, kernel_image):\n  # So we'll coded the convolution operation here; from scratch ! \n  input_width = input_image.shape[1]\n  input_height = input_image.shape[0]\n  kernel_width = kernel_image.shape[1]\n  kernel_height = kernel_image.shape[0]\n  output_height = input_height - kernel_height + 1\n  output_width = input_width - kernel_width + 1\n  output = np.zeros((output_height, output_width, input_image.shape[2]))\n  for c in range(0, input_image.shape[2]):\n    for k in range(0, output_height):\n      for j in range(0, output_width):\n        for w in range(0, kernel_height):\n          for v in range(0, kernel_width):\n            output[k, j, c] += input_image[k-w, j-v, c] * kernel_image[w, v, c]\n  return output\n\noutput = convolution3d(input_image, kernel_image)\ncv2_imshow(output)\n\noutput = correlation3d(input_image, kernel_image)\ncv2_imshow(output)\n\nfilters = np.array([0, -1, 0, -1, 2, -1, 0, -1, 0]).reshape(3,3)\nkernel_image = np.array([filters, filters, filters])\nkernel_image\n\noutput = convolution3d(input_image, kernel_image)\ncv2_imshow(output)", "meta": {"hexsha": "05312e36d673bfc68c40973d238eb1b1a2785b80", "size": 5387, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tensorflow_2X_PythonFiles/demo21_convolution.py", "max_stars_repo_name": "mahnooranjum/Tensorflow_DeepLearning", "max_stars_repo_head_hexsha": "65ab178d4c17efad01de827062d5c85bdfb9b1ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tensorflow_2X_PythonFiles/demo21_convolution.py", "max_issues_repo_name": "mahnooranjum/Tensorflow_DeepLearning", "max_issues_repo_head_hexsha": "65ab178d4c17efad01de827062d5c85bdfb9b1ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tensorflow_2X_PythonFiles/demo21_convolution.py", "max_forks_repo_name": "mahnooranjum/Tensorflow_DeepLearning", "max_forks_repo_head_hexsha": "65ab178d4c17efad01de827062d5c85bdfb9b1ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6882352941, "max_line_length": 237, "alphanum_fraction": 0.7172823464, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813463747182, "lm_q2_score": 0.8933094110250331, "lm_q1q2_score": 0.8539871334809177}}
{"text": "import matplotlib\nmatplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc')\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\n\ndef basins_1d():\n    f = lambda x:x**2-1\n    Df = lambda x:2*x\n    x0 = np.linspace(-1.5, 1.5, 40)\n    \n    xold=x0\n    n = 0\n    while n <= 6:\n        xnew = xold - f(xold)/Df(xold)\n        xold = xnew\n        n += 1\n    \n    plt.scatter(x0, np.zeros_like(x0), marker='s', c=xnew, edgecolor='None', cmap='bwr') \n    plt.plot(x0, f(x0), c='black', linewidth=3)\n    plt.savefig('basins1d.pdf', bbox_inches='tight')\n    plt.close()\n    \ndef fractal_1d():\n    f = lambda x:x**3-x\n    Df = lambda x:3*x**2-1\n    x0 = np.linspace(-1.5, 1.5, 500)\n    \n    xold=x0\n    n = 0\n    while n <= 50:\n        xnew = xold - f(xold)/Df(xold)\n        xold = xnew\n        n += 1\n    \n    y = np.array([-.1, .1])\n    X, Y = np.meshgrid(x0, y)\n    plt.pcolormesh(X, Y, np.atleast_2d(xnew).repeat(2, axis=0), cmap='brg')\n    plt.plot(x0, f(x0), c='black', linewidth=3)\n    plt.savefig('fractal1d.pdf', bbox_inches='tight')\n    plt.close()   \n    \ndef plot_basins(f, Df, roots, xmin, xmax, ymin, ymax, numpoints=100, iters=15, colormap='brg', name='name.png', dpinum=150):\n    xreal = np.linspace(xmin, xmax, numpoints)\n    ximag = np.linspace(ymin, ymax, numpoints)\n    Xreal, Ximag = np.meshgrid(xreal, ximag)\n    Xold = Xreal + 1j * Ximag\n    for i in xrange(iters):\n        Xnew = Xold - f(Xold)/Df(Xold)\n        Xold = Xnew\n    m,n = Xnew.shape\n    for i in xrange(m):\n        for j in xrange(n):\n            Xnew[i,j] = np.argmin(np.abs(Xnew[i,j]-roots))    \n    plt.pcolormesh(Xreal, Ximag, Xnew, cmap=colormap)\n    plt.savefig(name, bbox_inches='tight', dpi=dpinum)\n\nif __name__ == \"__main__\":\n    basins_1d()\n    fractal_1d()\n", "meta": {"hexsha": "1c52c4b9bf193357716d54d17de27ce9b3b7d308", "size": 1770, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/NewtonsMethod/plots.py", "max_stars_repo_name": "jessicaleete/numerical_computing", "max_stars_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-10-18T19:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:12:38.000Z", "max_issues_repo_path": "Labs/NewtonsMethod/plots.py", "max_issues_repo_name": "jessicaleete/numerical_computing", "max_issues_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/NewtonsMethod/plots.py", "max_forks_repo_name": "jessicaleete/numerical_computing", "max_forks_repo_head_hexsha": "cc71f51f35ca74d00e617af3d1a0223e19fb9a68", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-14T16:07:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-20T09:05:06.000Z", "avg_line_length": 28.5483870968, "max_line_length": 124, "alphanum_fraction": 0.5802259887, "include": true, "reason": "import numpy", "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370535, "lm_q2_score": 0.8933094074745443, "lm_q1q2_score": 0.8539871334476462}}
{"text": "import numpy as np\n\ndef Tanh(z):\n\tz = np.array(z)\n\tez = np.exp(-2*z)\n\tsigz = (1.0/(1.0+ez))\n\treturn 2*sigz - 1\n\t\ndef TanhGradient(z):\n\tth = Tanh(z)\n\treturn 1 - th**2\n\t\ndef InverseTanh(a):\n\tsigz = (a + 1.0)/2.0\n\tez = 1.0/sigz - 1.0\n\tz = np.log(ez)/(-2.0)\n\treturn z\n\t\ndef InverseTanhGradient(a):\n\tz = InverseTanh(a)\n\treturn TanhGradient(z)\n", "meta": {"hexsha": "786c9ff9b319eb4074d09d04181311a03b32f5ea", "size": 338, "ext": "py", "lang": "Python", "max_stars_repo_path": "PyNeuralNetwork/ActivationFunctions/Tanh.py", "max_stars_repo_name": "mattkjames7/PyNeuralNetwork", "max_stars_repo_head_hexsha": "edbee96aa9039d22e83253700edaf3b98d4ed9d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PyNeuralNetwork/ActivationFunctions/Tanh.py", "max_issues_repo_name": "mattkjames7/PyNeuralNetwork", "max_issues_repo_head_hexsha": "edbee96aa9039d22e83253700edaf3b98d4ed9d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyNeuralNetwork/ActivationFunctions/Tanh.py", "max_forks_repo_name": "mattkjames7/PyNeuralNetwork", "max_forks_repo_head_hexsha": "edbee96aa9039d22e83253700edaf3b98d4ed9d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.3636363636, "max_line_length": 27, "alphanum_fraction": 0.5976331361, "include": true, "reason": "import numpy", "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813463747182, "lm_q2_score": 0.8933094096048377, "lm_q1q2_score": 0.8539871321232374}}
{"text": "#  ___________________________________________________________________________\n# version with multiple solutions \n# introducing the 2nd furniture factory problem\n# https://youtu.be/kGs32O2rhx8?t=171\n\n# Solution 1:\n# Profit =  2250.0  per week\n# c =  24.0  chairs per week\n# t =  14.0  tables per week\n\n# Solution 2:\n# Profit =  2250.0  per week\n# c =  45.0  chairs per week\n# t =  0.0  tables per week\n\n#  ___________________________________________________________________________\n\n#\n# Imports\n#\nimport pyomo.environ as pyo\n\nmodel = pyo.ConcreteModel()\n\n# decision variables:\n# number of chairs\n# number of tables\nmodel.c = pyo.Var(domain=pyo.NonNegativeIntegers)\nmodel.t = pyo.Var(domain=pyo.NonNegativeIntegers)\n# model.c = pyo.Var(domain=pyo.NonNegativeReals)\n# model.t = pyo.Var(domain=pyo.NonNegativeReals)\n\n\n# maximize the profit\nmodel.OBJ = pyo.Objective(expr = 50*model.c + 75*model.t, sense=pyo.maximize)\n\n# weekly material/wood constraint\nmodel.wood = pyo.Constraint(expr = 5*model.c + 20*model.t <= 400)\n# weekly labor constraint\nmodel.labor = pyo.Constraint(expr = 10*model.c + 15*model.t <= 450)\n\n\npyo.SolverFactory('glpk').solve(model)\n\n# model.pprint()\nprint(\"Profit = \", model.OBJ(), \" per week\")\nprint(\"c = \", model.c(), \" chairs per week\")\nprint(\"t = \", model.t(), \" tables per week\")", "meta": {"hexsha": "2ce2120927c8c65182aa2944b0a29d21582db6ce", "size": 1303, "ext": "py", "lang": "Python", "max_stars_repo_path": "06_facility/pyomo/furniture-factory2.py", "max_stars_repo_name": "SSSA-ampere/coursera-discrete-optimization", "max_stars_repo_head_hexsha": "ebdc93388b3b8c430e33062559448d7a00729804", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "06_facility/pyomo/furniture-factory2.py", "max_issues_repo_name": "SSSA-ampere/coursera-discrete-optimization", "max_issues_repo_head_hexsha": "ebdc93388b3b8c430e33062559448d7a00729804", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "06_facility/pyomo/furniture-factory2.py", "max_forks_repo_name": "SSSA-ampere/coursera-discrete-optimization", "max_forks_repo_head_hexsha": "ebdc93388b3b8c430e33062559448d7a00729804", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1458333333, "max_line_length": 78, "alphanum_fraction": 0.7252494244, "include": true, "reason": "import pyomo", "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.8933094067644466, "lm_q1q2_score": 0.8539871305281863}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# # Lab 6 Monte Carlo Methods\n\n# ## Introduction: Random numbers and statistics\n\n# ### Normal distribution\n\n# A nomral distribution can be generated by `numpy.eandom.normal`\n# See details [here](https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.normal.html).\n# \n# The probability density function of the normal distribution follows a Gaussian function\n# \\begin{equation}\n#     f(x|\\mu,\\sigma^2)=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}\n# \\end{equation}\n\n# In[ ]:\n\n\n# mean\nmu = 0\n# Standard deviation\nsigma = 1\n# size of variables of the normal distribution, n can beint or tuple \n# depending on if x is a vector, or a matrix, etc.\nn = 10000\n# n = (100, 100)\n# Normal distribution\nx_normal = np.random.normal(mu, sigma, n)\n# plot\nfig, axs = plt.subplots(2, 1, figsize=(8, 8))\naxs[0].plot(x_normal, 'ro')\naxs[0].set_title(r'Normal Distribution with $\\mu=$'+str(mu)+' and $\\sigma=$'+str(sigma))\n\ncount, bins, ignored = axs[1].hist(x_normal, 100, density=True)\naxs[1].plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * \n            np.exp( - (bins - mu)**2 / (2 * sigma**2) ), \n            linewidth=2, color='r')\naxs[1].set_title('Probability Density')\n\nfor i in range(2): axs[i].autoscale(enable=True, axis='both', tight=True)\n\n\n# ### Uniform distribution\n\n# Similarly, a uniform distribution can be constructed by `numpy.random.uniform`.\n# See [here](https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.uniform.html).\n\n# In[ ]:\n\n\n# the half-open interval [low, high)\nlow, high = 0, 1\n# size of variables of the normal distribution, n can beint or tuple \n# depending on if x is a vector, or a matrix, etc.\nn = 500\n# uniform distribution\nx_uni = np.random.uniform(low, high, n)\n\n# plot\nfig, axs = plt.subplots(2, 1, figsize=(8, 8))\naxs[0].plot(x_uni, 'ro')\naxs[0].set_title(r'Uniform Distribution in $[$'+str(low)+','+str(high)+r'$)$')\n\ncount, bins, ignored = axs[1].hist(x_uni, 100, density=True)\naxs[1].plot(bins, np.ones_like(bins), linewidth=2, color='r')\naxs[1].set_title('Probability Density')\nfor i in range(2): axs[i].autoscale(enable=True, axis='both', tight=True)\n\n\n# ## A simulation: Throw dice\n\n# The uniform distribution random function `numpy.random.uniform` generate real numbers. \n# In order to create only integers, one need to round the random value to the nearest integer with `numpy.floor` or `numpy.ceil`.\n\n# Define the following function to simulate dice throw\n\n# In[ ]:\n\n\ndef throwDice(N):\n    '''\n    To simulate throwing dice N times\n    '''\n    return np.floor(1 + 6*np.random.uniform(0, 1, size=N))\n\n\n# In[ ]:\n\n\nN = 1000\nNrepeat = 10000\nr = [np.mean(throwDice(N)) for i in range(Nrepeat)] \n\n# plot\nfig, ax = plt.subplots(1, 1, figsize=(8, 4))\nax.hist(r, 100, density=True)\nax.autoscale(enable=True, axis='both', tight=True)\n\n\n# __NOTE__: There is a random integers generator in `numpy.random.randint` which create discrete uniform random integers from _low (inclusive)_ to __high (exclusive)__.\n# See [here](https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.randint.html).\n\n# In[ ]:\n\n\n# Range of the dice\n# NOTE!! high value is not included, for a dice with six sides, high=7\nlow, high = 1, 7\n# Number of throws\nn = 1000\nx_dice = np.random.randint(low, high, n)\n\n\n# Then, we can simulate the same event with the following code\n\n# In[ ]:\n\n\nN = 1000\nNrepeat = 10000\nr = [np.mean(np.random.randint(low, high, n)) for i in range(Nrepeat)] \n\n# plot\nfig, ax = plt.subplots(1, 1, figsize=(8, 4))\nax.hist(r, 100, density=True)\nax.autoscale(enable=True, axis='both', tight=True)\n\n\n# ## Application: Computing an integral with Monte Carlo\n\n# An example use Monte Carlo method to compute the integration of multivariate normal distribution funciton.\n\n# In[ ]:\n\n\ndef mcint(func, domain, N, M=30):\n    \"\"\" Numerical integration using Monte Carlo method\n    Parameters\n    ----------\n    func : function, function handler of the integrand;\n    domain : numpy.ndarray, the domain of computation, \n            domain = array([[-5, 5],\n                            [-5, 5],\n                            [-5, 5]])\n            The dimensions of the domain is given by domain.shape[0];\n    N : integer, the number of points in each realization;\n    M : integer, the number of repetitions used for error estimation,\n        (Recommendation, M = 30+).\n        Total number of points used is thus M*N\n    Returns\n    -------\n    r.mean() : the integral value of func in the domain\n    r.std() : the error in the result (the standard deviation)\n    \"\"\"\n    # Get the dimensions\n    dim = domain.shape[0]\n    # volume of the domain\n    V = abs(domain.T[0] - domain.T[1]).prod()\n    \n    r = np.zeros(M)\n    for i in range(M):\n        # generate uniform distributed random numbers within the domain\n        x = np.random.uniform(domain.T[0], domain.T[1], (N, dim))\n        r[i] = V * np.mean(func(x), axis=0)\n        \n    return r.mean(), r.std()\n\ndef fnorm(x):\n    \"\"\" Normal distribution function in d-dimensions\n    Parameters\n    ----------\n    x : numpy.ndarray, of shape (N, d), where d is the dimension and \n        N is the number of realizations\n    Returns\n    -------\n    y : numpy.ndarray, of the shape (N, 1) \n    \"\"\" \n    d = x.shape[1]\n    y = 1/((2*np.pi)**(d/2))*np.exp(-0.5*np.sum(x**2, axis=1))\n    return y\n\n\n# Take the domain in $[-4,4]\\times[-4,4]$, compute the integral using funtion `fnorm`\n\n# In[ ]:\n\n\n# numbers of samples\nN = 1000\nM = 50\n# domain\ndomain = np.array([[-4,4],[-4,4]])\n# integrate\nintF, err = mcint(fnorm, domain, N, M)\nprint('The result of the integral with N=', str(N), 'is', '{:.5f}'.format(intF),',')\nprint('with standard deviation', '{:.5f}'.format(err), 'for', str(M), 'realizations.')\n\n\n# ### Check the order of accuracy $p$ for the Monte Carlo method.\n\n# In[ ]:\n\n\n# Change the dimension to see different results\ndim = 3\n\n# domain [-5, 5]^dim\ndomain = np.array([[-5, 5] for i in range(dim)])\n\n# take an array of N\nn = 8\nNList = 500 * 2**np.array(range(n))\nM = 50\n\n# Save the error\nerrList = np.zeros_like(NList, dtype=float)\nfor i in range(n):\n    intF, err = mcint(fnorm, domain, NList[i], M)\n    errList[i] = err\n    \n\n# Plot\nfig, ax = plt.subplots(1, 1, figsize=(8, 4))\nax.loglog(NList, errList)\nax.autoscale(enable=True, axis='both', tight=True)\nax.set_xlabel('N')\nax.set_ylabel('Error')\n\n# Compute the order\na = np.polyfit(np.log(NList), np.log(errList),1)\np = np.round(a[0], 1)\nprint('Order of accuracy is N^p, with p=', p)\n\n\n# ## Programming: Brownian motion\n\n# In[ ]:\n\n\ndef brownian(x0, tEnd, dt):\n    \"\"\"\n    Generate an instance of Brownian motion\n    Parameters\n    ----------\n    x0 : float or numpy array (or something that can be converted to a numpy array\n         using numpy.asarray(x0)).\n         The initial condition(s) (i.e. position(s)) of the Brownian motion.\n    tEnd : float, the final time.\n    dt : float, the time step.\n    Returns\n    -------\n    x: A numpy array of floats with shape `x0.shape + (n,)`.\n    \"\"\"\n    x0 = np.asarray(x0)\n    n = int(tEnd/dt)\n\n    # For each element of x0, generate a sample of n numbers from a\n    # normal distribution.\n    r = np.random.normal(size=x0.shape + (n,), scale=(dt**0.5))\n\n    # This computes the Brownian motion by forming the cumulative sum of\n    # the random samples. \n    x = np.cumsum(r, axis=-1)\n\n    # Add the initial condition.\n    x += np.expand_dims(x0, axis=-1)\n    \n    return x\n\n\n# In[ ]:\n\n\n# Total time.\nT = 10.0\n# Number of steps.\nN = 500\n# Time step size\ndt = T/N\n# Initial values of x.\nx = np.empty((2,N+1))\nx[:, 0] = 0.0\n\n# Brownian motion\nx[:, 1:] = brownian(x[:,0], T, dt)\n\n# Plot the 2D trajectory.\nfig, ax = plt.subplots(1, 1, figsize=(8, 8))\nax.plot(x[0],x[1])\nax.plot(x[0,0],x[1,0], 'go')\nax.plot(x[0,-1], x[1,-1], 'ro')\nax.set_title('2D Brownian Motion')\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.axis('equal')\nax.grid(True)\n\n", "meta": {"hexsha": "f8df20b1931a987d20d5ccf4ceb4b8d074b352cb", "size": 7951, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab/L6/Lab6.py", "max_stars_repo_name": "enigne/ScientificComputingBridging", "max_stars_repo_head_hexsha": "920f3c9688ae0e7d17cffce5763289864b9cac80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-04T01:15:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T15:08:27.000Z", "max_issues_repo_path": "Lab/L6/Lab6.py", "max_issues_repo_name": "enigne/ScientificComputingBridging", "max_issues_repo_head_hexsha": "920f3c9688ae0e7d17cffce5763289864b9cac80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab/L6/Lab6.py", "max_forks_repo_name": "enigne/ScientificComputingBridging", "max_forks_repo_head_hexsha": "920f3c9688ae0e7d17cffce5763289864b9cac80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8990228013, "max_line_length": 168, "alphanum_fraction": 0.6382844925, "include": true, "reason": "import numpy", "num_tokens": 2365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.926303728259492, "lm_q1q2_score": 0.8539796367643322}}
{"text": "# This is an midpoint method of solving the ODEs (a refinement of Euler's method)\n# Advantage is that it has a local error of O(dt^3) and a global error of O(dt^2) making it similar to RK23\n# Another advantage is that it is a fixed timestep solver which can take into account the control at every timestep\n\nimport glob\nimport matplotlib.pyplot as plt\nimport numpy\nimport os\nimport pandas\nimport scipy\nimport scipy.integrate\nimport sympy\n\n# GLOBAL CONSTANTS\nbeta = 0.175 # Rate of Exposure\ndelta = 2.703e-5 # Natural Birth Rate (unrelated to disease)\ngamma = 0.07 # Rate of Removal [days^-1]\nmu = 2.403e-5 # Natural Death Rate (unrelated to disease)\nsigma = 0.2 # Average Incubation Period [days^-1]\n\nN = 3.57e6 # Total Population of CT [persons]\ncfr = 0.022 # Case Fatality Rate [1.4% (NY) - 3%]\nR = (beta*sigma)/((mu+gamma)*(mu+sigma)) # Basic Reproduction Number\n\nbeds = 1739 # Number of hospital beds available\nicub = 100 # Number of ICU beds available\n\ndef midpoint():\n\n    # ODE VARIABLES\n    tf = 365\n    dt = 1\n\n    s = numpy.zeros(tf)\n    e = numpy.zeros(tf)\n    i = numpy.zeros(tf)\n    r = numpy.zeros(tf)\n    t = numpy.arange(0, tf, dt)\n\n    # INITIAL CONDITIONS\n    i[0] = 360/N    # Active Infected []\n    e[0] = 250/N      # Exposed []\n    r[0] = 400/N      # Recovered []\n    s[0] = (N-r[0]-e[0]-i[0])/N # Susceptible []\n\n    for index in range(1, tf):\n        [fs, fe, fi, fr] = dynamics(s[index-1],\n                                    e[index-1],\n                                    i[index-1],\n                                    r[index-1])\n        [ds, de, di, dr] = dynamics(s[index-1] + dt/2*fs,\n                                    e[index-1] + dt/2*fe,\n                                    i[index-1] + dt/2*fi,\n                                    r[index-1] + dt/2*fr)\n\n        s[index] = s[index-1] + dt*ds\n        e[index] = e[index-1] + dt*de\n        i[index] = i[index-1] + dt*di\n        r[index] = r[index-1] + dt*dr\n\n    fig = plt.figure()\n    plt.plot(t, s, label='Susceptible')\n    plt.plot(t, e, label='Exposed')\n    plt.plot(t, i, label='Infected')\n    plt.plot(t, r, label='Removed')\n    plt.legend()\n    plt.show()\n\ndef dynamics(s, e, i, r):\n    ds = delta - (beta*s*i) - (mu*s)\n    de = (beta*s*i) - (mu*e) - (sigma*e)\n    di = (sigma*e) - (gamma*i) - (mu*i)\n    dr = (gamma*i) - (mu*r)\n    return [ds, de, di, dr]\n\nif __name__ == \"__main__\":\n    midpoint()\n", "meta": {"hexsha": "fcba26081692eb778e9ea2580214463d2e43d707", "size": 2393, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/midpoint.py", "max_stars_repo_name": "squeegene/SEIR_CT", "max_stars_repo_head_hexsha": "78e7f5788d62a53b68eb19827ff9dc4bac0bd205", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/midpoint.py", "max_issues_repo_name": "squeegene/SEIR_CT", "max_issues_repo_head_hexsha": "78e7f5788d62a53b68eb19827ff9dc4bac0bd205", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/midpoint.py", "max_forks_repo_name": "squeegene/SEIR_CT", "max_forks_repo_head_hexsha": "78e7f5788d62a53b68eb19827ff9dc4bac0bd205", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6794871795, "max_line_length": 115, "alphanum_fraction": 0.5511909737, "include": true, "reason": "import numpy,import scipy,import sympy", "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542887603537, "lm_q2_score": 0.8902942239389252, "lm_q1q2_score": 0.8539295231495909}}
{"text": "from sympy import Matrix\n\n\"\"\"\n>Let $h(\\mathbf{x}) \\in \\mathbb{R}$ be a smooth function, and $\\mathbf{f}(\\mathbf{x}) \\in \\mathbb{R}^n$ be a smooth vector field, the **Lie derivative** of $h$ with respect to $\\mathbf{f}$ is given by directional derivative:\n>\\begin{equation}\nL_\\mathbf{f} h = \\nabla h^T\\mathbf{f} = \\sum_{i=1}^n \\frac{\\partial h}{\\partial x_i} f_i\n\\end{equation}\n\"\"\"\n\n\ndef lie_diff(h, f, x):\n    grad = Matrix([h]).jacobian(x)\n    lf_h = grad * f\n    return lf_h[0]\n\n\n\"\"\"\nThe $n$-th order Lie derivative is defined recursevely as:\n\\begin{equation}\nL^k_\\mathbf{f} h = L_\\mathbf{f} (L_\\mathbf{f}^{k-1}h), \\quad \\text{for }k=1,\\dots, n\n\\end{equation}\nWith $L^0_\\mathbf{f} h = h$\n\"\"\"\n\n\ndef lie_diff_n(h, f, x, n):\n    lf_h_k = h\n    for k in range(n):\n        lf_h_k = lie_diff(lf_h_k, f, x)\n    return lf_h_k\n\n\n\"\"\"\n>The **Lie Bracket** of two vector fields $\\mathbf{f}(\\mathbf{x}),\\mathbf{g}(\\mathbf{x})$ is vector field defined as follows:\n>\n>\\begin{equation}\n[\\mathbf{f},\\mathbf{g}] = \\frac{\\partial \\mathbf{g}}{\\partial \\mathbf{x}}\\mathbf{f} - \n\\frac{\\partial \\mathbf{f}}{\\partial \\mathbf{x}}\\mathbf{g}\n\\end{equation}\n\"\"\"\n\n\ndef lie_bracket(f, g, x):\n    return g.jacobian(x) * f - f.jacobian(x) * g\n\n\n\"\"\"\n>We denote $ad_\\mathbf{f}(\\mathbf{g}) = [\\mathbf{f},\\mathbf{g}]$ ($ad$ - for *adjoint*) while $ad^k_\\mathbf{f}(\\mathbf{g})$  defined recursevely as:\n\\begin{equation}\nad^k_\\mathbf{f}(\\mathbf{g}) = [\\mathbf{f},ad^{k-1}_\\mathbf{f}(\\mathbf{g})]\n\\end{equation}\nwith $ad^0_\\mathbf{f}(\\mathbf{g}) = \\mathbf{g}$\n\"\"\"\n\n\ndef adf_g(f, g, x, n):\n    ad_k = g\n    for k in range(n):\n        ad_k = lie_bracket(f, ad_k, x)\n    return ad_k\n", "meta": {"hexsha": "64dbbf1ed8ec47027a069d3cea81f5e871b1e869", "size": 1643, "ext": "py", "lang": "Python", "max_stars_repo_path": "lie_algebra.py", "max_stars_repo_name": "l1va/controlsym", "max_stars_repo_head_hexsha": "75881e8cb3706f9b2a0ca137fe93c321c2f21395", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-29T20:06:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T20:06:51.000Z", "max_issues_repo_path": "lie_algebra.py", "max_issues_repo_name": "l1va/controlsym", "max_issues_repo_head_hexsha": "75881e8cb3706f9b2a0ca137fe93c321c2f21395", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lie_algebra.py", "max_forks_repo_name": "l1va/controlsym", "max_forks_repo_head_hexsha": "75881e8cb3706f9b2a0ca137fe93c321c2f21395", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9344262295, "max_line_length": 224, "alphanum_fraction": 0.6165550822, "include": true, "reason": "from sympy", "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154281754899, "lm_q2_score": 0.8902942290328344, "lm_q1q2_score": 0.8539295217985199}}
{"text": "# fit to y(x) = a_1 exp(a2 x) using a nonlinear fitting technique that\n# reduces to a multivariate root finding problem\n#\n# This is very sensitive to our initial guess\n#\n# M. Zingale (2013-03-10)\n\nimport numpy\nimport numpy.linalg\nimport pylab\n\n\ntol = 1.e-5\n\ndef fun(a, x, y):\n    \"\"\" the derivatives of our fitting function wrt each parameter:\n    \n        Q = sum_{i=1}^N (y_i = a0 exp(a1 x_i) )**2\n\n        -- these are what we zero \"\"\"\n    \n    # dQ/da0\n    f0 = numpy.sum(numpy.exp(a[1]*x)*(a[0]*numpy.exp(a[1]*x) - y))\n    \n    # dQ/da1\n    f1 = numpy.sum(x*numpy.exp(a[1]*x)*(a[0]*numpy.exp(a[1]*x) - y))\n\n    return numpy.array([f0, f1])\n\n\ndef jac(a, x, y):\n    \"\"\" return the Jacobian of fun \"\"\"\n\n    # df0/da0 \n    df0da0 = numpy.sum(numpy.exp(2.0*a[1]*x))\n\n    # df0/da1 \n    df0da1 = numpy.sum(x*numpy.exp(a[1]*x)*(2.0*a[0]*numpy.exp(a[1]*x) - y))\n\n    # df1/da0\n    df1da0 = numpy.sum(x*numpy.exp(2.0*a[1]*x))\n\n    # df1/da1 \n    df1da1 = numpy.sum(x**2*numpy.exp(a[1]*x)*(2.0*a[0]*numpy.exp(a[1]*x) - y))\n                   \n    return numpy.array([ [df0da0, df0da1], [df1da0, df1da1] ])\n\n\n\ndef fRoots(aguess, x, y):\n    \"\"\" aguess is the initial guess to our fit parameters.  x and y\n        are the vector of points that we are fitting to \"\"\"\n\n    avec = aguess.copy()\n\n    err = 1.e100\n    while err > tol:\n    \n        # get the jacobian\n        J = jac(avec, x, y)\n\n        print \"condition number of J: \", numpy.linalg.cond(J)\n\n        # get the current function values\n        f = fun(avec, x, y)\n\n        # solve for the correction: J dx = -f\n        da = numpy.linalg.solve(J, -f)\n\n        avec += da\n        err = numpy.max(numpy.abs(da))\n\n    return avec\n\n\n\n# make up some experimental data\na0 = 2.5\na1 = 2./3.\nsigma = 2.0\n\nx = numpy.linspace(0.0, 4.0, 25)\ny = a0*numpy.exp(a1*x) + sigma*numpy.random.randn(len(x))\n\npylab.scatter(x,y)\npylab.errorbar(x, y, yerr=sigma, fmt=None, label=\"_nolegend_\")\n\n# initial guesses\naguess = numpy.ones(2)\n\n# fit\nafit = fRoots(aguess, x, y)\n\nprint afit\n\np = pylab.plot(x, afit[0]*numpy.exp(afit[1]*x), \n           label=r\"$a_0 = $ %f; $a_1 = $ %f\" % (afit[0], afit[1]))\n\npylab.legend(numpoints=1, frameon=False)\n\npylab.savefig(\"nonlinear-fit.png\")\n\n\n", "meta": {"hexsha": "8add49f39f024f75d0656d750987564b62c6cc46", "size": 2208, "ext": "py", "lang": "Python", "max_stars_repo_path": "others/fitting/nonlinear-fit.py", "max_stars_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_stars_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T17:38:06.000Z", "max_issues_repo_path": "others/fitting/nonlinear-fit.py", "max_issues_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_issues_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/fitting/nonlinear-fit.py", "max_forks_repo_name": "bt3gl/Resources-Numerical_Methods_for_Physics", "max_forks_repo_head_hexsha": "8668215f107230fafd9bdeb0061d353328cf03e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T07:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T11:05:42.000Z", "avg_line_length": 21.2307692308, "max_line_length": 79, "alphanum_fraction": 0.5765398551, "include": true, "reason": "import numpy", "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154281754899, "lm_q2_score": 0.8902942173896131, "lm_q1q2_score": 0.8539295106308743}}
{"text": "import numpy as np\n\n#      We've got our DEM into python, we've projected our DEM onto a regular grid so that we can easily do some operations on it, and we've seen a little bit about how to use matplotlib to plot.  Now lets start actually doing some things.  In this post we'll calculate slope on the grid we just read in, and use that to create a hillshade. We will then superimpose that hillshade image on our slope map to create an image like the one above.  Specifically we're going to make a second order, or centered, finite-difference approximation of slope. We will calculate the hillshade grid using ESRI's algorithm. To check our work we'll plot both,  with some transparency on the hillshade so that it just gives the slope grid texture.\n\n#      First lets, take a second to review this finite difference approximation.  We can approximate the first derivative at the point Y6 (dashed line) as the difference in the values of Y at the adjacent points (7 and 5) divided by the horizontal distance between those adjacent points.  Think about this as the slope (rise over run) of the little gray triangle in the figure below. Notice that as the spacing between out points increases, we will do an increasingly poor job of approximating the derivative in places where the function curves around a lot.  As mentioned above, this is a 'second-order' finite difference approximation, but we won't get into why this is. One thing that is handy about this approximation is that the slope calculation is centered on the point we are interested in, Y6 in the highlighted example. If we only looked at two neighboring points (e.g. Y7 and Y6) to approximate the first derivative, that approximation would instead be centered between these nodes. There are times that this is useful, but since we are dealing with georeferenced raster data, it would be nice to have the pixels of our slope grid centered at the same points as the original dataset.  To do this in basic python might look something like whats below. Notice that because we are using our neighbors to calculate slope, we can not calculate the slope for the first and final items in our array - leaving us with an array of slope thats two smaller than the one we started with.\n\ndef IterateCenteredSlope(y,dx):\n    #Function to calculate second order finite difference\n    dydx = []  # Initialize an empty list\n    for i in range(1,len(y)-1):  # iterate through all pts not at boundaries\n        # append the current slope calculation to the list\n        dydx.append((y[i+1]-y[i-1])/(2*dx)) \n    return dydx\n\n#  One thing you might notice about this operation, is that instead of going through the data point by point and differencing the neighboring points we can actually just subtract two vectors shifted in opposite directions.  This is shown schematically with the math in the top right of the figure above and it is an easily accomplished operation with numpy arrays. In python it might look something like this:\ndef npCenteredSlope(y,dx):\n    # Where y is a numpy array,\n    # Calculate slope by differencing shifted vectors\n    dydx = (y[2:] - y[:-2])/(2*dx)\n    return dydx\n\n#  This is nice and clean, on large arrays it turns out to be a touch faster too (even after the overhead associated with turning your array into a numpy array.  Our grid is two dimensional, so we can calculate slope in both the row (y) and column (x) directions.  We can do this with the above technique after transforming our dataset to a numpy array (see pt2 near the end, gdalDataset.readAsArray().asType(np.float) ) with a function that looks something like this:\ndef calcFiniteSlopes(elevGrid, dx):\n    # sx,sy = calcFiniteDiffs(elevGrid,dx)\n    # calculates finite differences in X and Y direction using the \n    # 2nd order/centered difference method.\n    # Applies a boundary condition such that the size and location \n    # of the grids in is the same as that out.\n\n    # Assign boundary conditions\n    Zbc = assignBCs(elevGrid)\n\n    #Compute finite differences\n    Sx = (Zbc[1:-1, 2:] - Zbc[1:-1, :-2])/(2*dx)\n    Sy = (Zbc[2:,1:-1] - Zbc[:-2, 1:-1])/(2*dx)\n\n    return Sx, Sy\n\n#  Here I called a function that we have yet to define, 'assignBCs'. This function takes a numpy array and returns a numpy array that has an additional row and column before and after those specified in the input array. Its nice to create a seperate function for this, as we may want to get smarter with how we define our boundary conditions later. For now, since we are just trying to visualize slopes, lets just repeat the values on the edges of the array. This isn't a great approach (we'll fix it later) - but it only effects things at the margins. Here is what that would look like:\ndef assignBCs(elevGrid):\n    # Pads the boundaries of a grid\n    # Boundary condition pads the boundaries with equivalent values \n    # to the data margins, e.g. x[-1,1] = x[1,1]\n    # This creates a grid 2 rows and 2 columns larger than the input\n\n    ny, nx = elevGrid.shape  # Size of array\n    Zbc = np.zeros((ny + 2, nx + 2))  # Create boundary condition array\n    Zbc[1:-1,1:-1] = elevGrid  # Insert old grid in center\n\n    #Assign boundary conditions - sides\n    Zbc[0, 1:-1] = elevGrid[0, :]\n    Zbc[-1, 1:-1] = elevGrid[-1, :]\n    Zbc[1:-1, 0] = elevGrid[:, 0]\n    Zbc[1:-1, -1] = elevGrid[:,-1]\n\n    #Assign boundary conditions - corners\n    Zbc[0, 0] = elevGrid[0, 0]\n    Zbc[0, -1] = elevGrid[0, -1]\n    Zbc[-1, 0] = elevGrid[-1, 0]\n    Zbc[-1, -1] = elevGrid[-1, 0]\n\n    return Zbc\n\n#  Sweet, we've got ourselves a slope grid (well, two slope grids actually one in the x and y direction). Lets get to visualizing. ESRI nicely summarizes the calculation of hillshades on their website. This is how we could calculate one in python, using our newly created function to find slopes and given the dem, grid spacing, and information about the lighting angle:\ndef calcHillshade(elevGrid,dx,az,elev):\n    #Hillshade = calcHillshade(elevGrid,az,elev)\n    #Esri calculation for generating a hillshade, elevGrid is expected to be a numpy array\n\n    # Convert angular measurements to radians\n    azRad, elevRad = (360 - az + 90)*np.pi/180, (90-elev)*np.pi/180  \n    Sx, Sy = calcFiniteSlopes(elevGrid, dx)  # Calculate slope in X and Y directions\n\n    AspectRad = np.arctan2(Sy, Sx) # Angle of aspect\n    SmagRad = np.arctan(np.sqrt(Sx**2 + Sy**2))  # magnitude of slope in radians\n\n    return 255.0 * ((np.cos(elevRad) * np.cos(SmagRad)) + (np.sin(elevRad)* np.sin(SmagRad) * np.cos(azRad - AspectRad)))\n", "meta": {"hexsha": "cf00daf4e69d6d48a760db59f867bcce46446f30", "size": 6528, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/shaded_relief.py", "max_stars_repo_name": "noc-mars/ocean-data", "max_stars_repo_head_hexsha": "17d4243b3c932c6b6daa25a4fa753babb4afc60f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-21T00:03:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T14:12:33.000Z", "max_issues_repo_path": "utils/shaded_relief.py", "max_issues_repo_name": "noc-mars/ocean-data", "max_issues_repo_head_hexsha": "17d4243b3c932c6b6daa25a4fa753babb4afc60f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/shaded_relief.py", "max_forks_repo_name": "noc-mars/ocean-data", "max_forks_repo_head_hexsha": "17d4243b3c932c6b6daa25a4fa753babb4afc60f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-28T14:50:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T14:50:47.000Z", "avg_line_length": 84.7792207792, "max_line_length": 1486, "alphanum_fraction": 0.7328431373, "include": true, "reason": "import numpy", "num_tokens": 1682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996141, "lm_q2_score": 0.9059898127684335, "lm_q1q2_score": 0.8539014878726285}}
{"text": "import numpy as np\nimport pandas as pd\n\nfrom string import Template\n\nnp.set_printoptions(suppress=True)\n\ntemplate = Template('#' * 10 + ' $string ' + '#' * 10)\n\n# Generating section starts #\n\nprint(template.substitute(string='Generate array from 3 to 25 with step 2'))\narray = np.arange(3, 25, 2)\nprint(array)\n\nprint(template.substitute(string='Generate array of 13 elements, filled with ones'))\narray = np.ones(13, dtype='float')\nprint(array)\n\nprint(template.substitute(string='Generate matrix 3x7x3, filled with zeros'))\narray = np.zeros((3, 7, 3), dtype='uint')\nprint(array)\n\nprint(template.substitute(string='Generate evenly spaced numbers from 3 to 8 over a specified interval'))\narray = np.linspace(3, 8, 5)\nprint(array)\n\nprint(template.substitute(string='Generate random floats in the half-open interval [0.0, 1.0)'))\narray = np.random.random((2, 2, 2))\nprint(array)\n\nprint(template.substitute(string='Generate random integers from low (inclusive) to high (exclusive).'))\narray = np.random.randint(23.1, 50, (5, 5))\nprint(array)\n\nprint(template.substitute(string='Generate a new array of given shape and type, without initializing entries.'))\narray = np.empty(10)\nprint(array)\n\n# Generating section ends #\n# Indexing section starts #\n\narray = np.arange(12)\narray.shape = (3, 4)\n\nprint(template.substitute(string='Generate the ndarray'))\nprint(array)\n\nprint(template.substitute(string='Indexing the last row'))\nprint(array[2])\nprint(array[-1])\n\nprint(template.substitute(string='Indexing the third row'))\nprint(array[:, 2])\n\nprint(template.substitute(string='Indexing the element'))\nprint(array[2, 2])\nprint(array[-1, -2])\n\nprint(template.substitute(string='Create the sub-array'))\nprint(array[0][0:3:2])\n\n# Indexing section ends #\n# Arithmetic operations section starts #\n\narray = np.arange(1, 9, dtype='float')\narray_1 = np.arange(1, 9, dtype='int')\nprint(template.substitute(string='Generate the ndarray'))\nprint(array)\n\nprint(template.substitute(string='Adding'))\nprint(array + 3.1)\nprint(np.add(array, array_1 + np.ones(8)))\n\nprint(template.substitute(string='Subtracting'))\nprint(array - 3)\nprint(np.subtract(array, array_1 + np.ones(8)))\n\nprint(template.substitute(string='Multiplying'))\nprint(array * 2.5)\nprint(np.multiply(array, array_1 + np.ones(8)))\n\nprint(template.substitute(string='Dividing'))\nprint(array / .5)\nprint(np.divide(array, array_1))\n\nprint(template.substitute(string='Powering'))\nprint(array ** 2)\nprint(np.power(array, np.ones(8)))\nprint(np.power(np.array([10, 100, 1000]), np.array([3, 2, 1])))\n\nprint(template.substitute(string='Remainder of division'))\nprint(array % 2)\nprint(np.mod(array, array_1))\n\nprint(template.substitute(string='Convert to negative values'))\nprint(-array)\nprint(np.negative(array - 3))\n\nprint(template.substitute(string='Complex operations'))\nprint(((4 * array + 2) ** 1.5))\n\nprint(template.substitute(string='Reduce'))\nprint(np.add.reduce(array))\nprint(np.subtract.reduce(array))\nprint(np.multiply.reduce(array))\nprint(np.divide.reduce(array))\nprint(np.power.reduce(array))\n\nprint(template.substitute(string='Accumulate'))\nprint(np.add.accumulate(array))\nprint(np.subtract.accumulate(array))\nprint(np.multiply.accumulate(array))\nprint(np.divide.accumulate(array))\nprint(np.power.accumulate(array))\n\nprint(template.substitute(string='Outer'))\narray = np.arange(1, 10)\nprint(np.multiply.outer(array, array))\n\n# Arithmetic operations section ends #\n# Operations with data section starts #\n\ndata = pd.read_csv('../../data/iris.csv')\npetal = np.array(data['petal_width'])\n\nprint(template.substitute(string='Dataframe from pandas'))\nprint(petal)\n\nprint(template.substitute(string='Minimum and maximum from dataframe'))\nprint(petal.min(), petal.max())\n\nprint(template.substitute(string='Arithmetic mean'))\nprint(petal.mean())\n\nprint(template.substitute(string='Median'))\nprint(np.median(petal))\n\nprint(template.substitute(string='Standard deviation'))\nprint(np.std(petal))\n\nprint(template.substitute(string='Dispersion'))\nprint(np.var(petal))\n\nprint(template.substitute(string='Percentiles'))\nprint(np.percentile(petal, 25))\nprint(np.percentile(petal, 75))\n# Operations with data section ends #\n", "meta": {"hexsha": "0bfc56221172b0fef54211ea3ea69ca25d5d0d42", "size": 4149, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/lab1/main.py", "max_stars_repo_name": "mezgoodle/ad_labs", "max_stars_repo_head_hexsha": "75a7d91ab3c6e4abbfe6cace534e0624194df115", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-08T19:59:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T19:59:16.000Z", "max_issues_repo_path": "docs/lab1/main.py", "max_issues_repo_name": "mezgoodle/ad_labs", "max_issues_repo_head_hexsha": "75a7d91ab3c6e4abbfe6cace534e0624194df115", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2021-10-01T03:03:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T07:28:00.000Z", "max_forks_repo_path": "docs/lab1/main.py", "max_forks_repo_name": "mezgoodle/ad_labs", "max_forks_repo_head_hexsha": "75a7d91ab3c6e4abbfe6cace534e0624194df115", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-02T11:34:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T11:34:27.000Z", "avg_line_length": 27.8456375839, "max_line_length": 112, "alphanum_fraction": 0.7421065317, "include": true, "reason": "import numpy", "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244553, "lm_q2_score": 0.8840392939666335, "lm_q1q2_score": 0.8538931759603847}}
{"text": "\"\"\"\nProblem 1:\n\"\"\"\nimport time\nfrom scipy.special import factorial\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\nclass SineExpand:\n    things = 'terms'\n\n    def __init__(self, num_terms):\n        t0 = time.perf_counter()\n        n = np.arange(num_terms)\n        self.coeff = (-1)**n / factorial(2*n+1)\n        self.power = 2*n + 1\n        t1 = time.perf_counter()\n        self.overhead = t1 - t0\n\n    def evaluate(self, x):\n        \"\"\"x must be a 1D numpy array\"\"\"\n        t0 = time.perf_counter()\n        coeff = np.tile(self.coeff, (x.shape[0], 1)).T\n        power = np.tile(self.power, (x.shape[0], 1)).T\n        t1 = time.perf_counter()\n        result = np.sum(coeff[:] * x**power[:], axis=0)\n        t2 = time.perf_counter()\n        rmserror = np.sqrt(np.mean((np.sin(x)-result)**2))\n        overhead = self.overhead\n        evaltime = t2 - t0\n        return rmserror, evaltime/x.shape[0], overhead\n\n\nclass SineInterp:\n    things = 'points'\n\n    def __init__(self, num_terms):\n        t0 = time.perf_counter()\n        self.x = np.linspace(0, 2*np.pi, num_terms)\n        self.y = np.sin(self.x)\n        t1 = time.perf_counter()\n        self.overhead = t1 - t0\n\n    def evaluate(self, x):\n        \"\"\"x must be a 1D numpy array\"\"\"\n        t0 = time.perf_counter()\n        result = np.interp(x, self.x, self.y)\n        t1 = time.perf_counter()\n        rmserror = np.sqrt(np.mean((np.sin(x)-result)**2))\n        evaltime = t1 - t0\n        return rmserror, evaltime/x.shape[0], self.overhead\n\n\ndef test_sine(sine_class, N_vals):\n    x_vals = np.random.default_rng().random(10**6) * 2 * np.pi\n    rmserror = np.zeros(N_vals.shape[0])\n    evaltime = np.zeros(N_vals.shape[0])\n    overhead = np.zeros(N_vals.shape[0])\n    for i, N in enumerate(N_vals):\n        sine = sine_class(N)\n        rmserror[i], evaltime[i], overhead[i] = sine.evaluate(x_vals)\n    plt.figure()\n    plt.subplot(121, title='Accuracy', xlabel=f'Number of {sine_class.things}', ylabel='RMS Error')\n    plt.yscale('log')\n    plt.plot(N_vals, rmserror)\n    plt.subplot(122, title='Speed', xlabel=f'Number of {sine_class.things}', ylabel='Time (sec)')\n    plt.plot(N_vals, evaltime, label='Evaluation')\n    plt.plot(N_vals, overhead, label='Overhead')\n    plt.yscale('log')\n    plt.legend()\n    return rmserror, evaltime, overhead\n\n\nif __name__ == '__main__':\n    print('COMMIT!!!')\n    err1, et1, ot1 = test_sine(SineExpand, np.arange(1, 11))\n    err2, et2, ot2 = test_sine(SineInterp, np.geomspace(3, 500, 100, dtype='i'))\n    plt.figure()\n    plt.subplot(121, title='Error vs evaluation time', ylabel='Evaluation time (s)', xlabel='Absolute error',\n                xscale='log', yscale='log')\n    plt.plot(err1, et1, label='Taylor expansion')\n    plt.plot(err2, et2, label='Linear interpolation')\n    plt.legend()\n    plt.subplot(122, title='Error vs overhead time', ylabel='Overhead time (s)', xlabel='Absolute error',\n                xscale='log', yscale='log')\n    plt.plot(err1, ot1, label='Taylor expansion')\n    plt.plot(err2, ot2, label='Linear interpolation')\n    plt.legend()\n    plt.show()\n", "meta": {"hexsha": "17be4140373cd59493a0a2597784bdb5f548fe97", "size": 3079, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/functions/interpolating_funcs.py", "max_stars_repo_name": "jacione/phys513", "max_stars_repo_head_hexsha": "a8e1d1de800b0372d013d69543e1619b0fb8e4e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/interpolating_funcs.py", "max_issues_repo_name": "jacione/phys513", "max_issues_repo_head_hexsha": "a8e1d1de800b0372d013d69543e1619b0fb8e4e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/interpolating_funcs.py", "max_forks_repo_name": "jacione/phys513", "max_forks_repo_head_hexsha": "a8e1d1de800b0372d013d69543e1619b0fb8e4e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8351648352, "max_line_length": 109, "alphanum_fraction": 0.6102630724, "include": true, "reason": "import numpy,from scipy", "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8991213806488609, "lm_q1q2_score": 0.8538680302173345}}
{"text": "\"\"\" Implements the activation functions used by artificial neurons.\n\n@author: Gabriel G. Nogueira (Talendar)\n\"\"\"\n\nimport numpy as np\nfrom abc import ABC, abstractmethod\n\n\nclass ActivationFunction(ABC):\n    \"\"\" Abstract class defining the basic interface of an activation function. \"\"\"\n\n    @abstractmethod\n    def __call__(self, z, derivative=False):\n        \"\"\" Computes the function. \"\"\"\n        raise NotImplementedError(\"This method wasn't implemented!\")\n\n\nclass SigmoidActivation(ActivationFunction):\n    \"\"\" Sigmoid activation function. \"\"\"\n\n    def __call__(self, z, derivative=False):\n        \"\"\" Computes the function. \"\"\"\n        if not derivative:\n            return 1 / (1 + np.exp(-z))\n        return np.exp(-z) / ( (1 + np.exp(-z))**2 )\n\n\nclass ReluActivation(ActivationFunction):\n    \"\"\" Rectifier activation function, used by ReLU (rectified linear unit) neurons. \"\"\"\n\n    def __call__(self, z, derivative=False):\n        \"\"\" Computes the function. \"\"\"\n        if not derivative:\n            return np.maximum(0, z)\n        return np.ceil(np.clip(z, 0, 1))\n\n\nclass LinearActivation(ActivationFunction):\n    \"\"\" Linear activation function. \"\"\"\n\n    def __call__(self, z, derivative=False):\n        \"\"\" Computes the function. \"\"\"\n        if not derivative:\n            return z\n        return 1\n\n\ndef create_by_name(name):\n    \"\"\" Creates an instance of the cost function with the given name. \"\"\"\n    name = name.lower()\n    if name == \"sigmoid\":\n        return SigmoidActivation()\n    if name == \"relu\":\n        return ReluActivation()\n    if name == \"linear\":\n        return LinearActivation()\n\n    raise NameError(\"Activation function with name \\\"\" + name + \"\\\" not found!\")\n", "meta": {"hexsha": "217268b9cf66aee3ac4988c9746a2256d7cf820d", "size": 1692, "ext": "py", "lang": "Python", "max_stars_repo_path": "activation_functions.py", "max_stars_repo_name": "Talendar/multilayer_perceptron", "max_stars_repo_head_hexsha": "7d1deac7b5a76d433537be12ed3acf7a70a11beb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "activation_functions.py", "max_issues_repo_name": "Talendar/multilayer_perceptron", "max_issues_repo_head_hexsha": "7d1deac7b5a76d433537be12ed3acf7a70a11beb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "activation_functions.py", "max_forks_repo_name": "Talendar/multilayer_perceptron", "max_forks_repo_head_hexsha": "7d1deac7b5a76d433537be12ed3acf7a70a11beb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2, "max_line_length": 88, "alphanum_fraction": 0.6353427896, "include": true, "reason": "import numpy", "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693688269985, "lm_q2_score": 0.8991213711878918, "lm_q1q2_score": 0.8538680250748707}}
{"text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n# scipy模块stats文档\n# http://www.cnblogs.com/ttrrpp/p/6822214.html\n\nimport numpy as np\nfrom scipy.stats import norm\nimport matplotlib.pyplot as plt\n\ndef testNormal():# {{{\n    \"\"\"\n    Normal Distribution (正态分布)\n    正态分布是一种连续分布，其函数可以在实线上的任何地方取值。\n    正态分布由两个参数描述：分布的平均值μ和方差σ2 。\n\n    mu ---> loc\n    sigma ---> scale\n\n    \"\"\"\n\n    mu = 2\n    sigma = 4\n    xs = np.linspace(\n            norm.ppf(0.01, loc=mu, scale=sigma), \n            norm.ppf(0.99, loc=mu, scale=sigma), \n            num=1000)\n\n    # E(X) = mu, D(X) = sigma**2\n    mean, var, skew, kurt = norm.stats(loc=mu, scale=sigma, moments='mvsk')\n    print(\"mean: %.2f, var: %.2f, skew: %.2f, kurt: %.2f\" % (mean, var, skew, kurt))\n\n    fig, axs = plt.subplots(2, 2)\n\n    # 显示pdf (norm.pdf)\n    ys =norm.pdf(xs, loc=mu, scale=sigma)\n    axs[0][0].plot(xs, ys, 'bo', markersize=5, label='norm.pdf')\n    axs[0][0].legend()\n    axs[0][0].set_title('mu = %.2f, sigma = %.2f' % (mu, sigma))\n\n    # 显示pdf (manual)\n    ys = np.exp(-((xs - mu)**2) / (2* sigma**2)) / (sigma * np.sqrt(2*np.pi))\n    axs[0][1].plot(xs, ys, 'bo', markersize=5, label='cmp pdf')\n    axs[0][1].legend()\n    axs[0][1].set_title('mu = %.2f, sigma = %.2f' % (mu, sigma))\n\n    # 显示cdf\n    ys =norm.cdf(xs, loc=mu, scale=sigma)\n    axs[1][0].plot(xs, ys, 'bo', markersize=5, label='norm.pdf')\n    axs[1][0].legend()\n    axs[1][0].set_title('mu = %.2f, sigma = %.2f' % (mu, sigma))\n\n    \n    # 随机变量RVS\n    data = norm.rvs(loc=mu, scale=sigma, size = 1000)\n    data = np.around(data, decimals=1)\n    import sys\n    sys.path.append(\"../../thinkstats\")\n    import Pmf\n    pmf = Pmf.MakePmfFromList(data)\n    xs, ys = pmf.Render()\n    #  axs[1][1].plot(xs, ys, 'bo', markersize=5, label='rvs pmf')\n    axs[1][1].scatter(xs, ys, label='rvs pmf')\n    axs[1][1].legend()\n\n    plt.show()\n# }}}\n\nif __name__ == \"__main__\":\n    testNormal()\n", "meta": {"hexsha": "00282363520d7e12c6d8515bb6a3dfe97f023626", "size": 1892, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/learn/scipy/stats/Normal.py", "max_stars_repo_name": "qrsforever/workspace", "max_stars_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-06-07T03:20:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-07T09:14:26.000Z", "max_issues_repo_path": "python/learn/scipy/stats/Normal.py", "max_issues_repo_name": "qrsforever/workspace", "max_issues_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/learn/scipy/stats/Normal.py", "max_forks_repo_name": "qrsforever/workspace", "max_forks_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6478873239, "max_line_length": 84, "alphanum_fraction": 0.55602537, "include": true, "reason": "import numpy,from scipy", "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8991213711878917, "lm_q1q2_score": 0.8538680212325418}}
{"text": "\"\"\"Softmax.\nFor a given scores as n-dimensional array of where each column represents a sample\nthe softmax should return the probabilities of same n-dimensional array with same shape.\nThe probabilities for each sample (column) must sum to 1\n\nSoftmax Function S(yi) = exp(yi) / Sigsum(exp(yi))\n\"\"\"\n\nscores = [3.0, 1.0, 0.2]\nimport numpy as np\nimport math\n\ndef softmax(x):\n    \"\"\"Compute softmax values for each sets of scores in x.\"\"\"\n    # The longest way, some bug in code even though the approach is same to calculate softmax\n    \"\"\"\n    probabilities_array = list()\n    x_contains_array_el = False\n    x_denom = 0\n    for ele in x:\n        if isinstance(ele, np.ndarray):\n            x_contains_array_el = True\n            tmp_probabilities_array = list()\n            tmp_el_denom = 0\n            for el in ele:\n                tmp_el_denom += math.exp(el)\n            for el in ele:\n                tmp_prb = math.exp(el) / tmp_el_denom\n                tmp_probabilities_array.append(tmp_prb)\n            probabilities_array.append(tmp_probabilities_array)\n        # Assuming either it is just a single value list or its a pure numpy array with defined shape.\n        else:\n            #x_denom += math.exp(ele)\n            x_denom += ele\n    if not x_contains_array_el:\n        for ele in x:\n            probability = math.exp(ele) / x_denom\n            probabilities_array.append(probability)\n    return np.array(probabilities_array)\n    \"\"\"\n    # The shortest way and the efficient way as per tutorial.\n    return np.exp(x) / np.sum(np.exp(x), axis=0)\n\nprint(softmax(scores))\n#scores = np.array([3.0, 1.0, 0.2])\n\n# Multiply Scores with 10\n# If we multiply the scores by 10, the probabilites go close to 1.0 or 0.0\n#print(softmax(scores * 10))\n\n# Divide Scores with 10\n# If we divide the scores by 10, the probabilities go to uniform distribution, \n# reaching to value of 1/len(array). Ex: for scores with 3 elements, it gets close to 1/3 => 0.333 \n#print(softmax(scores / 10))\n\n# Plot softmax curves\nimport matplotlib.pyplot as plt\nx = np.arange(-2.0, 6.0, 0.1)\nscores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)])\nplt.plot(x, softmax(scores).T, linewidth=2)\nplt.show()\n", "meta": {"hexsha": "6de6ce920cf554339cd72acd58d893f0b0c022e7", "size": 2188, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine-learning/deep-learning/udacity/ud730/softmax.py", "max_stars_repo_name": "pk-ai/training", "max_stars_repo_head_hexsha": "86b0d6c74853565eab08e76054ce96083ebfd45e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-01T10:07:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-01T10:07:03.000Z", "max_issues_repo_path": "machine-learning/deep-learning/udacity/ud730/softmax.py", "max_issues_repo_name": "pktippa/ai-training", "max_issues_repo_head_hexsha": "86b0d6c74853565eab08e76054ce96083ebfd45e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-09-27T14:42:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T03:35:18.000Z", "max_forks_repo_path": "machine-learning/deep-learning/udacity/ud730/softmax.py", "max_forks_repo_name": "pktippa/ai-training", "max_forks_repo_head_hexsha": "86b0d6c74853565eab08e76054ce96083ebfd45e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2903225806, "max_line_length": 102, "alphanum_fraction": 0.6581352834, "include": true, "reason": "import numpy", "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780477, "lm_q2_score": 0.899121367808974, "lm_q1q2_score": 0.8538680193044634}}
{"text": "import numpy as np\nimport torch\nimport itertools\n\ndef spearman_footrule_distance(s, t, normalized=True):\n    \"\"\"\n    Computes the Spearman footrule distance between two full lists of ranks:\n    \n    F(s,t) = sum[ |s(i) - t(i)| ]/S,\n    \n    the normalized sum over all elements in a set of the absolute difference between\n    the rank according to s and t. As defined, 0 <= F(s,t) <= 1.\n    \n    S is a normalizer which is equal to 0.5*len(s)^2 for even length ranklists and\n    0.5*(len(s)^2 - 1) for odd length ranklists.\n    \n    If s,t are *not* full, this function should not be used. s,t should be array-like\n    (lists are OK).\n    From: https://github.com/thelahunginjeet/kbutil/blob/master/statistics.py\n          @author: Kevin S. Brown, University of Connecticut\n    \"\"\"\n    # print(\"*\"*20)\n    # print(s)\n    # print(t)\n    # print(\"*\"*20)\n    if isinstance(s, list) and isinstance(t, list):\n        # check that size of intersection = size of s,t?\n        assert len(s) == len(t)\n        s_len = len(s)\n        sdist = sum(abs(np.asarray(s) - np.asarray(t)))\n    elif isinstance(s, np.ndarray) and isinstance(t, np.ndarray):\n        assert s.size == t.size\n        s_len = s.size\n        #sdist = sum(abs(s - t))\n        sdist = np.abs(s - t).sum()\n    elif isinstance(s, torch.Tensor) and isinstance(t, torch.Tensor):\n        assert s.size == t.size\n        s_len = s.size()[0]\n        sdist = (s - t).abs().sum().item()\n    else:\n        raise TypeError(\n            \"Boot inputs should be of type 'list', 'array' or 'tensor'.\"\n        )\n    # c will be 1 for odd length lists and 0 for even ones\n    if normalized:\n        c = s_len % 2\n        normalizer = 0.5 * (s_len ** 2 - c)\n        sdist = sdist / normalizer\n\n    return sdist\n\n\ndef kendall_tau_distance(s, t, normalized=True, both=False):\n    \"\"\"\n    Computes the Kendall's tau distance bertween two full list of ranks:\n    K(s,t) = \n    \"\"\"\n    assert len(s) == len(t)\n    pairs = itertools.combinations(range(0, len(s)), 2)\n    kt_distance = 0\n    for x, y in pairs:\n        a = s.index(x) - s.index(y)\n        b = t.index(x) - t.index(y)\n        if (a*b < 0):\n            kt_distance += 1\n\n    normalizer = len(s)*(len(s)-1)/2\n    if normalized and both:\n        return (kt_distance,  kt_distance/normalizer)\n    elif normalized:\n        return kt_distance/normalizer\n\n    return kt_distance\n", "meta": {"hexsha": "9b5c7fe0d0f8b8ef4a602baf1a9b79d1698cc2b6", "size": 2369, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/metrics.py", "max_stars_repo_name": "lquirosd/Order_Relation_Operator", "max_stars_repo_head_hexsha": "28d7cf9f691bc0f98a18bf37dc673bb08a7c2a6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-02-13T16:51:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T08:33:01.000Z", "max_issues_repo_path": "src/metrics.py", "max_issues_repo_name": "lquirosd/Order_Relation_Operator", "max_issues_repo_head_hexsha": "28d7cf9f691bc0f98a18bf37dc673bb08a7c2a6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-31T16:49:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T16:15:40.000Z", "max_forks_repo_path": "src/metrics.py", "max_forks_repo_name": "lquirosd/Order_Relation_Operator", "max_forks_repo_head_hexsha": "28d7cf9f691bc0f98a18bf37dc673bb08a7c2a6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0135135135, "max_line_length": 85, "alphanum_fraction": 0.5909666526, "include": true, "reason": "import numpy", "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152283, "lm_q2_score": 0.9005297901222472, "lm_q1q2_score": 0.8538414042406145}}
{"text": "\"\"\"\nFile: integrate_exp.py\nCopyright (c) 2016 Andrew Malfavon\nLicense: MIT\nExercise B.6\nDescription: approximate an integral with the Trapezoidal method.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n#graphs the function to visually see the symmetry\ndef plot(n):\n    x = np.linspace(-10, 10, n)\n    y = np.exp(-x**2)\n    plt.plot(x, y)\n    plt.xlabel('x')\n    plt.ylabel('y')\n    plt.title('$e^{-x^2}$')\n\n#trapezoidal method to approximate the integral\ndef T(n, L):\n    x = np.linspace(0, L, n)#takes just the positive x-values\n    y = np.exp(-x**2)\n    h = L / float(2*n)\n    endpoints = y[0] + y[n - 1]\n    f = 0\n    for i in range(1, n - 1):\n        f +=  2 * y[i]\n    approx = h * (endpoints + f)\n    return 2 * approx#multiplies by two to account for the negative x-values\n\ndef table():\n    L_array = np.array(['L = 2', 'L = 4', 'L = 6', 'L = 8', 'L = 10'])#used to label the table\n    n_array = np.array(['n = 100', 'n = 200', 'n = 300', 'n = 400', 'n = 500'])#used to label the table\n    n = [100, 200, 300, 400, 500]\n    L = [2, 4, 6, 8, 10]\n    T_matrix = np.zeros([5, 5])#a five-by-five matrix with all zeros\n    array = []\n    counter = 0\n    for elem_n in n:\n        for elem_L in L:\n            array.append(T(elem_n, elem_L))#plugs in each value of n and L and puts them in an array\n    for i in range(5):\n        for j in range(5):\n            T_matrix[i, j] = array[counter]#arranges the array into a five-by-five matrix\n            counter += 1\n    table = pd.DataFrame(T_matrix, index = n_array, columns = L_array)#puts the matrix into a table and lables the axes\n    return table\n\n#same thing as before except it displays the error\ndef error_table():\n    L_array = np.array(['L = 2', 'L = 4', 'L = 6', 'L = 8', 'L = 10'])\n    n_array = np.array(['n = 100', 'n = 200', 'n = 300', 'n = 400', 'n = 500'])\n    n = [100, 200, 300, 400, 500]\n    L = [2, 4, 6, 8, 10]\n    T_error_matrix = np.zeros([5, 5])\n    array = []\n    counter = 0\n    for elem_n in n:\n        for elem_L in L:\n            array.append(np.sqrt(np.pi) - T(elem_n, elem_L))#error from the known analytic solution\n    for i in range(5):\n        for j in range(5):\n            T_error_matrix[i, j] = array[counter]\n            counter += 1\n    error_table = pd.DataFrame(T_error_matrix, index = n_array, columns = L_array)\n    return error_table\n\n#Test for each value of n and L the error between the known solution and the approximation is less than 0.1\ndef test():\n    n = [100, 200, 300, 400, 500]\n    L = [2, 4, 6, 8, 10]\n    test_array = []\n    for elem_n in n:#creates an array with the error for each combination of n and L\n        for elem_L in L:\n            test_array.append(abs(np.sqrt(np.pi)- T(elem_n, elem_L)))\n    for i in range(len(test_array)):#tests each spot in the array\n        assert test_array[i] < 0.1", "meta": {"hexsha": "91c5af9fd1908f7e7e631eae118249a2f78fd57f", "size": 2837, "ext": "py", "lang": "Python", "max_stars_repo_path": "integrate_exp.py", "max_stars_repo_name": "chapman-phys227-2016s/hw-5-malfa100", "max_stars_repo_head_hexsha": "7362d66443108e128bc6e43dcb9856845f39fb76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "integrate_exp.py", "max_issues_repo_name": "chapman-phys227-2016s/hw-5-malfa100", "max_issues_repo_head_hexsha": "7362d66443108e128bc6e43dcb9856845f39fb76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "integrate_exp.py", "max_forks_repo_name": "chapman-phys227-2016s/hw-5-malfa100", "max_forks_repo_head_hexsha": "7362d66443108e128bc6e43dcb9856845f39fb76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4625, "max_line_length": 119, "alphanum_fraction": 0.5949947127, "include": true, "reason": "import numpy", "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502203, "lm_q2_score": 0.9005297821135385, "lm_q1q2_score": 0.8538413953278376}}
{"text": "import numpy as np\n\n\ndef gini(values_arg, n = None):\n    \"\"\"\n    Calculates the gini_coeff using the formula shown in assets/gini_formula.png\n\n    Remind that len(values) here corresponds to n+1 there in that formula and remind that idx here corresponds to i-1 in the formula,\n    since python lists are zero-indexed and the formula is one-indexed\n    this can be confusing.\n\n    @type  values: a Python list or np.array of numbers to calculate gini coefficient on\n    \"\"\"\n\n    if n is None:\n        n = len(values_arg)\n\n    values = np.array(values_arg)\n\n    values.sort() # sort in-place in ascending order\n\n    sum_numerator = 0\n    sum_denominator = 0\n    for idx in range(0, n):\n        i = idx + 1 # idx here corresponds to i-1 in the formula, since python lists are zero-indexed\n        sum_numerator += (n + 1 - i) * values[idx]\n        sum_denominator += values[idx]\n    if sum_denominator == 0:\n        return np.NaN\n\n    g_coeff = n + 1 - 2*(sum_numerator/sum_denominator)\n\n    return g_coeff\n\n\ndef gini_corrected(values_arg, n = None):\n    \"\"\"\n    Calculates the gini_coeff with a correction for small datasets\n\n    @type  values: a Python list or np.array of numbers to calculate gini coefficient on\n    \"\"\"\n\n    if n is None:\n        n = len(values_arg)\n\n    if n < 2: # Don't calculaute Gini for populations with less than one individual\n        return np.NaN\n\n    # compute gini coefficient\n    g_coeff = gini(values_arg, n)\n\n    # Now, apply (Deltas, 2003 correction) for small datasets:\n    # (https://doi.org/10.1162/rest.2003.85.1.226)\n    g_coeff *= (1.0 / (n - 1))\n\n    return g_coeff\n", "meta": {"hexsha": "4071b6bae499551be418a0ea8eccd85f435eac9d", "size": 1607, "ext": "py", "lang": "Python", "max_stars_repo_path": "inequality_coefficients/gini.py", "max_stars_repo_name": "Grasia/inequality_coefficients", "max_stars_repo_head_hexsha": "44cd55b8d80da5d1bc501d6c5971ec2487335422", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-04-15T08:38:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T10:13:55.000Z", "max_issues_repo_path": "inequality_coefficients/gini.py", "max_issues_repo_name": "Grasia/inequality_coefficients", "max_issues_repo_head_hexsha": "44cd55b8d80da5d1bc501d6c5971ec2487335422", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-02-07T11:12:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T11:55:51.000Z", "max_forks_repo_path": "inequality_coefficients/gini.py", "max_forks_repo_name": "Grasia/inequality_coefficients", "max_forks_repo_head_hexsha": "44cd55b8d80da5d1bc501d6c5971ec2487335422", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-11T17:05:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-04T23:16:07.000Z", "avg_line_length": 28.1929824561, "max_line_length": 133, "alphanum_fraction": 0.6614810205, "include": true, "reason": "import numpy", "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.9005297834483232, "lm_q1q2_score": 0.8538413952741363}}
{"text": "\"\"\"\nCreated on Sat Jan 30 19:50:14 2016\n\"\"\"\n#------------------------------------------------------------------------------\n#CHAPTER 5:  The Pseudospectral Method  \n#------------------------------------------------------------------------------\nimport numpy as np\nfrom numpy.fft import *\nimport matplotlib.pyplot as plt\n\n# Basic parameters\nnx = 128\nxo = np.pi\n#%% CODE 03: Listing 5.1 Fourier Derivative - Pag 107\n# [...]\n# Fourier 1st derivative \ndef fourier_derivative(f, dx):\n    # Length of vector f\n    nx = f.size\n    # Initialize k vector up to Nyquist wavenumber      \n    kmax = np.pi/dx\n    dk = kmax/(nx/2)\n    k = np.arange(float(nx))\n    k[: nx/2] = k[: nx/2] * dk \n    k[nx/2 :] = k[: nx/2] - kmax\n    # Fourier derivative\n    ff = fft(f); ff = 1j*k*ff\n    df_num = ifft(ff).real\n    return df_num\n# [...]\n# Initialize Gauss function\nx, dx = np.linspace(2*np.pi/nx, 2*np.pi, nx, retstep=True) \nsigma = .5 \nf = np.exp(-1/sigma**2 * (x - xo)**2)\n# Calculate derivative of vector f \ndf_num = fourier_derivative(f, dx)\n\n# Analytical derivative\ndf_ana = -2*(x-xo)/sigma**2 * np.exp(-1/sigma**2 * (x-xo)**2)\n\n# Plot Fuctions\nplt.subplot(2,1,1)\nplt.plot(x,f,color=\"blue\", lw = 1.5)\nplt.xlabel('$x$')        \nplt.ylabel('$f(x)$')\n\nplt.subplot(2,1,2)\nplt.plot(x,df_ana,color=\"blue\", lw = 1.5, label='Analytical')\nplt.plot(x,df_num,color=\"black\", lw = 1.5, label='Numerical')\nplt.plot(x,1e13*(df_ana-df_num),color=\"red\", lw = 1.5, label='Difference')\nplt.legend(loc='upper right', shadow=True)\nplt.xlabel('$x$')        \nplt.ylabel('$\\partial_x f(x)$')\nplt.axis([2*np.pi/nx,2*np.pi,-2,2])\n\nplt.show()\nplt.savefig('Fig_5.9.png')\n", "meta": {"hexsha": "adda3f4973f9041f4beacd5cc9cf9aa91e5b86c8", "size": 1631, "ext": "py", "lang": "Python", "max_stars_repo_path": "pseudospectral/ps_derivative.py", "max_stars_repo_name": "cheshirepezz/PDE", "max_stars_repo_head_hexsha": "75e829c4f52a570d2551574b97396f32cc9fb893", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-11T14:43:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-12T09:15:32.000Z", "max_issues_repo_path": "pseudospectral/ps_derivative.py", "max_issues_repo_name": "cheshirepezz/PDE", "max_issues_repo_head_hexsha": "75e829c4f52a570d2551574b97396f32cc9fb893", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pseudospectral/ps_derivative.py", "max_forks_repo_name": "cheshirepezz/PDE", "max_forks_repo_head_hexsha": "75e829c4f52a570d2551574b97396f32cc9fb893", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-15T22:15:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T22:15:42.000Z", "avg_line_length": 28.1206896552, "max_line_length": 79, "alphanum_fraction": 0.5622317597, "include": true, "reason": "import numpy,from numpy", "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545274901875, "lm_q2_score": 0.9005297787765764, "lm_q1q2_score": 0.8538413868867478}}
{"text": "import sys\nimport scipy\nimport numpy as np\nfrom scipy.stats import chi2_contingency\n\n\ndef chi2Proportions(count,nobs):\n    \"\"\"\n    A wrapper for the chi2 testing proportions based upon the chi-square test\n\n    Args:\n        count (:obj `list` of :obj`int` or a single `int`):  the number of successes in nobs trials. If this is \n        array_like, then the assumption is that this represents the number of successes \n        for each independent sample \n\n\n        nobs (:obj `list` of :obj`int` or a single `int`):  The number of trials or observations, with the same length as count. \n\n    Returns: \n        chi2  (:obj `float`): The test statistic.\n\n        p (:obj `float`): The p-value of the test\n\n        dof (int) : Degrees of freedom\n\n        expected (:obj `list`): list same shape as observed. The expected frequencies, based on the marginal sums of the table\n\n\n    References: \n    [1] \"scipy.stats.chi2_contingency\" https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chi2_contingency.html\n    [2] \"statsmodels.stats.proportion.proportions_chisquare\"  https://www.statsmodels.org/dev/generated/statsmodels.stats.proportion.proportions_chisquare.html\n    [3]\t(1, 2) “Contingency table”, https://en.wikipedia.org/wiki/Contingency_table\n    [4]\t(1, 2) “Pearson’s chi-squared test”, https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test\n    [5]\t(1, 2) Cressie, N. and Read, T. R. C., “Multinomial Goodness-of-Fit Tests”, J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984), pp. 440-464.\n    \n    Sample use: \n        input: \n        [10,10,20] - number of successes in trial \n        [20,20,20] - number of trials \n        chi2Proportions([10,10,20], [20,20,20])\n        \n        output: \n        (2.7777777777777777,\n        0.24935220877729619,\n        2,\n        array([[ 12.,  12.,  16.],\n            [ 18.,  18.,  24.]]))\n    \"\"\"\n    \n    obs = np.array([count, nobs])\n    print(obs)\n    try: \n        return chi2_contingency(obs, correction=False) \n\n    except Exception as e:\n        print(\"Exception: {}, returning int max array\".format(e)) \n        int_max  = sys.maxsize\n        return [int_max, int_max,int_max,int_max]\n    \n              \n\n\nif __name__ == \"__main__\":\n    print(chi2Proportions([10,10,20], [20,20,20]))\n", "meta": {"hexsha": "517dfc790d37f512d455f566676996ee5f2eb593", "size": 2258, "ext": "py", "lang": "Python", "max_stars_repo_path": "irlutils/stats/tests/proportions/chi2_proportions.py", "max_stars_repo_name": "uiowa-irl/uiowa-irl-utils", "max_stars_repo_head_hexsha": "7ecb751e7a960735c1d4307c21890bd71a282251", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-05T09:47:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-05T09:47:16.000Z", "max_issues_repo_path": "stats/tests/proportions/chi2_proportions.py", "max_issues_repo_name": "uiowa-irl/uiowa-irl-utils", "max_issues_repo_head_hexsha": "7ecb751e7a960735c1d4307c21890bd71a282251", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stats/tests/proportions/chi2_proportions.py", "max_forks_repo_name": "uiowa-irl/uiowa-irl-utils", "max_forks_repo_head_hexsha": "7ecb751e7a960735c1d4307c21890bd71a282251", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7384615385, "max_line_length": 159, "alphanum_fraction": 0.6350752879, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.8976953003183443, "lm_q1q2_score": 0.8538359045517224}}
{"text": "import numpy as np\n# from rnn_utils import *\n\ndef softmax(x):\n    e_x = np.exp(x - np.max(x))\n    return e_x / e_x.sum(axis=0) \n\ndef rnn_cell_forward(xt,a_prev,parameters):\n    \n    Waa = parameters['Waa']\n    Wax = parameters['Wax']\n    Way = parameters['Wya']\n    ba = parameters['ba']\n    by = parameters['by']\n    \n    a_next = np.tanh(np.dot(Waa,a_prev) + np.dot(Wax,xt) + ba)\n    yt_pred = softmax(np.dot(Way,a_next) + by)\n    cache = (a_next, a_prev, xt, parameters)\n    \n    return a_next, yt_pred, cache\n\n# np.random.seed(1)\n# xt_tmp = np.random.randn(3,10)\n# a_prev_tmp = np.random.randn(5,10)\n# parameters_tmp = {}\n# parameters_tmp['Waa'] = np.random.randn(5,5)\n# parameters_tmp['Wax'] = np.random.randn(5,3)\n# parameters_tmp['Wya'] = np.random.randn(2,5)\n# parameters_tmp['ba'] = np.random.randn(5,1)\n# parameters_tmp['by'] = np.random.randn(2,1)\n\n# a_next_tmp, yt_pred_tmp, cache_tmp = rnn_cell_forward(xt_tmp, a_prev_tmp, parameters_tmp)\n# print(\"a_next[4] = \\n\", a_next_tmp[4])\n# print(\"a_next.shape = \\n\", a_next_tmp.shape)\n# print(\"yt_pred[1] =\\n\", yt_pred_tmp[1])\n# print(\"yt_pred.shape = \\n\", yt_pred_tmp.shape)\n\n\ndef rnn_forward(x, a0, parameters):\n    caches=[]\n    n_x, m, T_x = x.shape\n    n_y, n_a = parameters['Wya'].shape\n    \n    a = np.zeros(shape=(n_a, m, T_x))\n    y_pred = np.zeros(shape=(n_y, m, T_x))\n    \n    a_next = a0\n    \n    for t in range(T_x):\n        xt = x[:,:,t]\n        a_next, yt_pred, cache = rnn_cell_forward(xt, a_next, parameters)\n        a[:,:,t] = a_next\n        y_pred[:,:,t] = yt_pred\n        caches.append(cache)\n    caches = (caches, x)\n    \n    return a, y_pred, caches\n\n\nnp.random.seed(1)\nx_tmp = np.random.randn(3,10,4)\na0_tmp = np.random.randn(5,10)\nparameters_tmp = {}\nparameters_tmp['Waa'] = np.random.randn(5,5)\nparameters_tmp['Wax'] = np.random.randn(5,3)\nparameters_tmp['Wya'] = np.random.randn(2,5)\nparameters_tmp['ba'] = np.random.randn(5,1)\nparameters_tmp['by'] = np.random.randn(2,1)\n\na_tmp, y_pred_tmp, caches_tmp = rnn_forward(x_tmp, a0_tmp, parameters_tmp)\nprint(\"a[4][1] = \\n\", a_tmp[4][1])\nprint(\"a.shape = \\n\", a_tmp.shape)\nprint(\"y_pred[1][3] =\\n\", y_pred_tmp[1][3])\nprint(\"y_pred.shape = \\n\", y_pred_tmp.shape)\nprint(\"caches[1][1][3] =\\n\", caches_tmp[1][1][3])\nprint(\"len(caches) = \\n\", len(caches_tmp))\n        \n\n\n\n      ", "meta": {"hexsha": "30076939ecb23887b44de71d74fec1209e9474e0", "size": 2299, "ext": "py", "lang": "Python", "max_stars_repo_path": "rnn_basic_self.py", "max_stars_repo_name": "nikhilsanghi/Sequence_Models", "max_stars_repo_head_hexsha": "dcc66a6afcca99ada7d014400ac53ddcfffc0751", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rnn_basic_self.py", "max_issues_repo_name": "nikhilsanghi/Sequence_Models", "max_issues_repo_head_hexsha": "dcc66a6afcca99ada7d014400ac53ddcfffc0751", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rnn_basic_self.py", "max_forks_repo_name": "nikhilsanghi/Sequence_Models", "max_forks_repo_head_hexsha": "dcc66a6afcca99ada7d014400ac53ddcfffc0751", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3827160494, "max_line_length": 91, "alphanum_fraction": 0.6285341453, "include": true, "reason": "import numpy", "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778252, "lm_q2_score": 0.8976952982655951, "lm_q1q2_score": 0.8538359001127676}}
{"text": "\"\"\"Linear Regression Algorithm\"\"\"\nfrom statistics import mean\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport random\n\nstyle.use('fivethirtyeight')\n\n\ndef create_data(r, variance, step=2, correlation=False):\n    \"\"\"Generate a random data\n    \n    -- Arguments\n    range: int, required\n        range of the data\n\n    variance: float, required\n        range of variance of the random data\n\n    step: int, optional\n        value to generate correlational data\n\n    correlation: 'pos', 'neg' or False, optional, default False\n        Determines if the data will have \n        a positive or negative correlation or None\n\n    -- Returns\n        The generated data as a float64 numpy array\n    \"\"\"\n    val = 1\n    ys = []\n    for _ in range(r):\n        y = val + random.randrange(-variance, variance)\n        ys.append(y)\n        if correlation and correlation == 'pos':\n            val += step\n        elif correlation and correlation == 'neg':\n            val -= step\n\n    xs = [i for i in range(len(ys))]\n    \n    return np.array(xs, dtype=np.float64), np.array(ys, dtype=np.float64)\n\n\ndef best_fit_slope_and_intercept(xs, ys):\n    \"\"\"Calculate the slope and the Y intercept of the best fit line\n\n    -- Returns\n        m: slope\n        b: Y intercept\n    \"\"\"\n    m = ( (mean(xs) * mean(ys) - (mean(ys*xs)))\n        / (mean(xs)*mean(xs) - mean(xs*xs)) )\n    b = mean(ys) - m * mean(xs)\n    return m, b\n\n\ndef squared_error(ys_orig, ys_line):\n    return sum((ys_line-ys_orig)**2)\n\n\ndef coefficient_of_determination(ys, regression_line):\n    y_mean_line = [mean(ys) for y in ys]\n    squared_error_regr = squared_error(ys, regression_line)\n    squared_error_y_mean = squared_error(ys, y_mean_line)\n    return 1 - (squared_error_regr/squared_error_y_mean)\n\n\nif __name__ == '__main__':\n    #Data\n    xs, ys = create_data(40, 20, 2, correlation='pos')\n\n    #Calculation\n    m, b = best_fit_slope_and_intercept(xs, ys)\n    regression_line = [(m*x) + b for x in xs]\n\n    #Prediction\n    predict_x = 41\n    predict_y = (m*predict_x) + b\n\n    #Accuracy\n    r_squared = coefficient_of_determination(ys, regression_line)\n    print('Acuracy:', r_squared)\n\n    plt.scatter(xs,ys)\n    plt.scatter(predict_x, predict_y, s=100, color='g')\n    plt.plot(xs, regression_line)\n    plt.show()\n", "meta": {"hexsha": "ac457cec7d9d358b661e2660e2dc8358b184608d", "size": 2303, "ext": "py", "lang": "Python", "max_stars_repo_path": "mlalgorithms/linearRegression.py", "max_stars_repo_name": "yuriharrison/ml-algorithms", "max_stars_repo_head_hexsha": "b69c7e666006d43b10ef8f0d95fe745a430f04f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mlalgorithms/linearRegression.py", "max_issues_repo_name": "yuriharrison/ml-algorithms", "max_issues_repo_head_hexsha": "b69c7e666006d43b10ef8f0d95fe745a430f04f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mlalgorithms/linearRegression.py", "max_forks_repo_name": "yuriharrison/ml-algorithms", "max_forks_repo_head_hexsha": "b69c7e666006d43b10ef8f0d95fe745a430f04f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5888888889, "max_line_length": 73, "alphanum_fraction": 0.643074251, "include": true, "reason": "import numpy", "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.8976952907388474, "lm_q1q2_score": 0.853835890467261}}
{"text": "import numpy as np\n\nclass GD:\n    def __init__(self, lr=0.1):\n        self.lr = lr\n    \n    def apply_grads(self, W, grad_W):\n        W = W - self.lr * grad_W\n        return W\n\nclass LR:\n    def __init__(self, num_features=1, optimizer=GD(0.1)):\n        self.W = np.zeros((num_features, 1))\n        self.optimizer = optimizer\n    \n    def predict(self, X):\n        y = X @ self.W\n        return y\n    \n    def one_step_opt(self, X, y_true):\n        grads = - X.T @ (y_true - X @ self.W) / X.shape[0]\n        self.W = self.optimizer.apply_grads(self.W, grads)\n        loss = (y_true - self.predict(X)).T @ (y_true - self.predict(X))\n        return loss, grads\n    \n    def fit(self, X, y_true, grad_tol=0.0001, n_iters=1000):\n        grad_norm = np.inf\n        n_iter = 0\n        losses = []\n        while (grad_norm > grad_tol) and (n_iter < n_iters):\n            loss, grads = self.one_step_opt(X, y_true)\n            grad_norm = np.linalg.norm(grads)\n            n_iter += 1\n            losses.append(loss[0][0])\n        return losses\n    \n    def fit_closed_form(self, X, y_true):\n        self.W = np.linalg.inv(X.T @ X) @ X.T @ y_true\n        loss = (y_true - self.predict(X)).T @ (y_true - self.predict(X)) / X.shape[0]\n        return loss", "meta": {"hexsha": "e108f84c8eb4732e985e22fc5714bfb3f5bf9485", "size": 1244, "ext": "py", "lang": "Python", "max_stars_repo_path": "atilla_gosha/utils_atilla.py", "max_stars_repo_name": "andriidem308/demchenko_nikiforov_labwork", "max_stars_repo_head_hexsha": "a6d11fdecb85ce27acb1a0a9c9e37dbdce389573", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-13T11:51:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-13T11:51:10.000Z", "max_issues_repo_path": "utils_atilla.py", "max_issues_repo_name": "andriidem308/demchenko_nikiforov_labwork", "max_issues_repo_head_hexsha": "a6d11fdecb85ce27acb1a0a9c9e37dbdce389573", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils_atilla.py", "max_forks_repo_name": "andriidem308/demchenko_nikiforov_labwork", "max_forks_repo_head_hexsha": "a6d11fdecb85ce27acb1a0a9c9e37dbdce389573", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1, "max_line_length": 85, "alphanum_fraction": 0.5474276527, "include": true, "reason": "import numpy", "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242000616579, "lm_q2_score": 0.8807970826714614, "lm_q1q2_score": 0.8537779275771562}}
{"text": "import numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom numpy import linalg as LA\n\ndef ellipse_gen(a,b,center):\n    len = 50\n    theta = np.linspace(0,2*np.pi,len)\n    x_ellipse = np.zeros((2,len))\n    x_ellipse[0,:] = a*np.cos(theta) + center[0]   #acos(t)+h\n    x_ellipse[1,:] = b*np.sin(theta) + center[1]   #asin(t)+k\n    return x_ellipse\n \n#setting up plot\nfig = plt.figure()\nax = fig.add_subplot(111, aspect='equal')\nlen = 100\ny = np.linspace(-5,5,len)\n \n#Ellipse parameters\nV = np.array(([13,-9],[-9,37]))\nu = np.array(([1,7]))\nf = -2\n\n#Computation\nutV_1u = np.matmul(np.matmul(u.T,np.linalg.inv(V)),u)\nc = -np.linalg.inv(V)@u\n\n#Eigenvalues and eigenvectors\nD_vec,P = np.linalg.eig(V)\nD = np.diag(D_vec)\na = np.sqrt((utV_1u-f)/D_vec[0])\nb = np.sqrt((utV_1u-f)/D_vec[1])\nxStandardEllipse = ellipse_gen(a,b,[0,0])\n\n#Major and Minor Axes\nMajorStandard = np.array(([a,0]))\nMinorStandard = np.array(([0,b]))\n \n#Affine transform \nCs = np.array([[c[0],c[1]] for i in range(50)]).T\nxActualEllipse = P@xStandardEllipse + Cs # x = Py + c (Affine Transformation)\nMajorActual = P@MajorStandard+c[0]\nMinorActual = P@MinorStandard+c[1]\n \n#Plotting the standard ellipse\nplt.plot(xStandardEllipse[0,:],xStandardEllipse[1,:],label='Standard Ellipse')\n \n#Plotting the actual ellipse\nplt.plot(xActualEllipse[0,:],xActualEllipse[1,:],label='Actual Ellipse')\n \n#Labeling the coordinates\ntri_coords = np.vstack((MajorStandard,MinorStandard,MajorActual,MinorActual,c)).T\nplt.scatter(tri_coords[0,:], tri_coords[1,:])\nvert_labels = ['$a$','$b$','$a^{\\prime}$','$b^{\\prime}$','$\\mathbf{c}$']\nfor i, txt in enumerate(vert_labels):\n    plt.annotate(txt, # this is the text\n                 (tri_coords[0,i], tri_coords[1,i]), # this is the point to label\n                 textcoords=\"offset points\", # how to position the text\n                 xytext=(0,10), # distance from text to points (x,y)\n                 ha='center') # horizontal alignment can be left, right or center\n\n# Axis Plots\nx_ = np.linspace(-0.9,0.9,50)\ny_ = np.linspace(-0.6,0.6,50)\ny_1 = [0 for i in range(50)]          \nx_1 = [0 for i in range(50)]          \nplt.plot(x_, y_1, 'black')\nplt.plot(x_1,y_, 'black')\n\nplt.xlabel('$X Axis$')\nplt.ylabel('$Y Axis$')\nplt.legend(loc='best')\nplt.grid() \nplt.axis('equal')\n \nplt.show()\n", "meta": {"hexsha": "cd70e68dd97a767d528104ba5ace1a9028cec3f5", "size": 2288, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignment_8/Codes/Ellipse_Figure.py", "max_stars_repo_name": "Arko98/EE5609-Matrix-Theory-", "max_stars_repo_head_hexsha": "7c72720b4e5241a9dc3b62b38d4537f2cdd67e07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment_8/Codes/Ellipse_Figure.py", "max_issues_repo_name": "Arko98/EE5609-Matrix-Theory-", "max_issues_repo_head_hexsha": "7c72720b4e5241a9dc3b62b38d4537f2cdd67e07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment_8/Codes/Ellipse_Figure.py", "max_forks_repo_name": "Arko98/EE5609-Matrix-Theory-", "max_forks_repo_head_hexsha": "7c72720b4e5241a9dc3b62b38d4537f2cdd67e07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-02T11:29:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T17:05:21.000Z", "avg_line_length": 29.3333333333, "max_line_length": 81, "alphanum_fraction": 0.6486013986, "include": true, "reason": "import numpy,from numpy", "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242000616579, "lm_q2_score": 0.8807970748488297, "lm_q1q2_score": 0.85377791999449}}
{"text": "import math\nimport random\nimport numpy as np\n\n\nclass KMeans:\n    def __init__(self, num_categories, tolerance=0.0001, max_iterations=500):\n        self._classes = dict()\n        self._centroids = dict()\n        self._k = num_categories\n        self._tolerance = tolerance\n        self._max_iterations = max_iterations\n\n    def predict(self, inputs):\n        \"\"\"\n        Predict class for given inputs\n        :param inputs: list(float) -> input values for prediction\n        :return: int -> classification\n        \"\"\"\n        inputs = [np.array(inp) for inp in inputs]\n        distances = [np.linalg.norm(inputs - self._centroids[centroid]) for centroid in self._centroids]\n        classification = distances.index(min(distances))\n        return classification\n\n    def cluster(self, inputs):\n        \"\"\"\n        Generate unsupervised classification clusters based on K-Means using euclidean distance\n        :param inputs: list(float) -> input values for clustering\n        \"\"\"\n        if len(inputs) < self._k:\n            raise Exception('length of x must be larger than num_categories for method: KMeans.cluster')\n        self._instantiate_centroids(inputs)\n        for _ in range(self._max_iterations):\n            self._classes = dict()\n            for k in range(self._k):\n                self._classes[k] = list()\n            self._update_classes(inputs)\n            for classification in self._classes:\n                self._centroids[classification] = np.average(self._classes[classification], axis=0)\n            if self._is_optimal():\n                break\n\n    def _is_optimal(self):\n        \"\"\"\n        Determine if the given centroids are optimal\n        :return: bool -> if centroids are optimal\n        \"\"\"\n        is_optimal = True\n        for centroid in self._centroids:\n            original_centroid = dict(self._centroids)[centroid]\n            curr = self._centroids[centroid]\n            if np.sum((curr - original_centroid) / original_centroid * 100.0) > self._tolerance:\n                is_optimal = False\n        return is_optimal\n\n    def _update_classes(self, inputs):\n        \"\"\"\n        Update classes based on given inputs\n        :param inputs: list(float) -> list of inputs to update classes on\n        \"\"\"\n        for item in inputs:\n            distances = [np.linalg.norm(item - self._centroids[centroid]) for centroid in self._centroids]\n            classification = distances.index(min(distances))\n            self._classes[classification].append(item)\n\n    def _instantiate_centroids(self, inputs):\n        \"\"\"\n        Instantiate centroids from random samples of inputs\n        :param inputs: list(float) -> list of input values\n        \"\"\"\n        inputs = [np.array(inp) for inp in inputs]\n        random.shuffle(inputs)\n        for cluster in range(self._k):\n            self._centroids[cluster] = inputs[cluster]\n\n    @staticmethod\n    def _euclidean_distance(vector_1, vector_2):\n        \"\"\"\n        Determine the euclidean distance between two vectors represented as lists\n        :param vector_1: list(float) -> first vector in our equation\n        :param vector_2: list(float) -> second vector in our equation\n        :return: float -> euclidean distance\n        \"\"\"\n        if len(vector_1) != len(vector_2):\n            raise Exception('vectors must be same size for method: KMeans._euclidean_distance')\n        return math.sqrt(sum((vector_1[i] + vector_2[i])**2 for i in range(len(vector_1))))\n", "meta": {"hexsha": "0632022720cf518a0df3c5a5547fcdc9d718ac35", "size": 3447, "ext": "py", "lang": "Python", "max_stars_repo_path": "SciGen/Clustering/KMeans.py", "max_stars_repo_name": "SamuelSchmidgall/SciGen", "max_stars_repo_head_hexsha": "d030b71ab87a034f9d59c5a53f501e96411dc0b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-07T12:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-07T12:54:25.000Z", "max_issues_repo_path": "SciGen/Clustering/KMeans.py", "max_issues_repo_name": "SamuelSchmidgall/SciGen", "max_issues_repo_head_hexsha": "d030b71ab87a034f9d59c5a53f501e96411dc0b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SciGen/Clustering/KMeans.py", "max_forks_repo_name": "SamuelSchmidgall/SciGen", "max_forks_repo_head_hexsha": "d030b71ab87a034f9d59c5a53f501e96411dc0b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6206896552, "max_line_length": 106, "alphanum_fraction": 0.6269219611, "include": true, "reason": "import numpy", "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96932419740316, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.8537779131032931}}
{"text": "import numpy as np\n\n__all__ = ['convolve']\n\ndef convolve(f,g,fft=True, periodic=True):\n    \"\"\"Compute the linear or circular convolution of two discrete data sets.\n\n    For small problems, it is usually faster to perform the convolution\n    directly. In this case, `convolve` defaults to the ``numpy.convolve``\n    routine. For circular convolution, a copy of the smaller of the\n    two arrays must be made. For larger problems, convolution is more\n    efficiently performed as a multiplication in Fourier space followed by\n    inversion. These transforms are performed using Fast Fourier Transform\n    (FFT) methods. FFTs are fastest for intelligently chosen problem sizes\n    (for example, powers of 2). If convolution performance is critical, both\n    methods should be timed, and the optimal one selected.\n\n    For linear convolutions with FFTs, `f` and `g` are zero-padded to\n    ``len(f)+len(g)-1``. For circular convolutions, the period is taken to be\n    the longer of `f` and `g`. If one is shorter than the other, it is\n    zero-padded with ``numpy.pad``.\n\n    Parameters\n    ----------\n    f : array_like\n        First function to convolve\n\n    g : array_like\n        Second function to convolve\n\n    fft : bool, optional\n        If true, perform the convolution using FFTs.\n\n    periodic : bool, optional\n        If true, perform the circular convolution (periodic data).\n\n    Returns\n    -------\n    out : ndarray\n        The convolution of `f` and `g`\n\n    Examples\n    --------\n    Take the linear convolution of two boxcar functions of even and odd lengths.\n    >>> f = np.ones(5)\n    >>> g = np.ones(2)\n    >>> flyft.fft.convolve(f,g,periodic=False)\n    [ 1.  2.  2.  2.  2.  1.]\n\n    The convolution is returned in the proper order.\n    >>> g[1] = 2\n    >>> flyft.fft.convolve(f,g,periodic=False)\n    [ 1.  3.  3.  3.  3.  2.]\n\n    The convolution operator commutes.\n    >>> flyft.fft.convolve(g,f,periodic=False)\n    [ 1.  3.  3.  3.  3.  2.]\n\n    \"\"\"\n\n    if not fft:\n        if not periodic:\n            return np.convolve(f,g)\n        else:\n            # replicate the smaller data set for circular convolution without FFT\n            if len(f) < len(g):\n                ff = np.concatenate((f,f))\n                gg = g\n                min_idx = len(f)\n                max_idx = -len(f)+1\n            else:\n                ff = f\n                gg = np.concatenate((g,g))\n                min_idx = len(g)\n                max_idx = -len(g)+1\n            c = np.convolve(ff,gg)\n            period = max(len(f),len(g))\n            return c[period:-period+1]\n    else:\n        if not periodic:\n            # the minimum length needed to pad to for linear convolution\n            input_len = len(f) + len(g) - 1\n        else:\n            input_len = max(len(f),len(g))\n\n        # fft the data\n        F = np.fft.fft(f, n=input_len)\n        G = np.fft.fft(g, n=input_len)\n\n        # multiply and take the inverse\n        c = np.fft.ifft(F*G)\n\n        # extract the relevant parts\n        return np.real(c)\n", "meta": {"hexsha": "81c5ab4b244d1210cc2af1ac79ff89b5380c81cb", "size": 3024, "ext": "py", "lang": "Python", "max_stars_repo_path": "fft.py", "max_stars_repo_name": "mphoward/flyft", "max_stars_repo_head_hexsha": "b871614be9ab092190d4539ef8922eaa92100b2a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-08-27T22:06:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T21:23:32.000Z", "max_issues_repo_path": "fft.py", "max_issues_repo_name": "mphoward/flyft", "max_issues_repo_head_hexsha": "b871614be9ab092190d4539ef8922eaa92100b2a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fft.py", "max_forks_repo_name": "mphoward/flyft", "max_forks_repo_head_hexsha": "b871614be9ab092190d4539ef8922eaa92100b2a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-01-07T11:27:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-24T20:14:54.000Z", "avg_line_length": 31.8315789474, "max_line_length": 81, "alphanum_fraction": 0.585978836, "include": true, "reason": "import numpy", "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263736, "lm_q2_score": 0.9019206738932334, "lm_q1q2_score": 0.8537551121271857}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 10 15:20:56 2021\n\n@author: alessandro\n\"\"\"\n\nimport numpy as np\nimport scipy.linalg as spl\n\ndef lunopivot(A):\n    m, n = A.shape\n    \n    U = A.copy()\n    for k in range(n - 1):\n        if U[k, k] == 0:\n            print(\"elemento diagonale nullo\")\n            return [],[], False\n        for i in range(k + 1, n):\n            U[i, k] /= U[k, k]\n            for j in range(k + 1, n):\n                U[i, j] -= U[i, k] * U[k, j]\n    L = np.tril(U, -1) + np.eye(n)\n    U = np.triu(U)\n    return L, U, True\n\ndef lsolve(L, b):\n    m, n = L.shape\n    x = np.zeros((n, 1))\n    for i in range(n):\n        s = np.dot(L[i, :i], x[:i])\n        x[i] = (b[i] - s) / L[i, i]\n    return x\n\ndef usolve(U, b):\n    m, n = U.shape\n    x = np.zeros((n, 1))\n    for i in range(n - 1, -1, -1):\n        s = np.dot(U[i, i + 1:], x[i + 1:])\n        x[i] = (b[i] - s) / U[i, i]\n    return x\n\ndef lusolve(A, b):\n    L, U, flag = lunopivot(A)\n    y = lsolve(L, b)\n    x = usolve(U, y)\n    return x\n\ndef lulusolve(L, U, b):\n    y1 = lsolve(L, b)\n    y2 = usolve(U, y1)\n    y3 = lsolve(L, y2)\n    y4 = usolve(U, y3)\n    return y4\n\nfor n in range(5, 11):\n    A = spl.pascal(n)\n    b = np.dot(A.T, np.ones((n, 1)))\n    c = np.dot(np.dot(A, A), np.ones((n, 1)))\n    \n    print(f\"b = {b}\")\n    \n    s1 = lusolve(A, b).T\n    print(f\"soluzione 1 = {s1}\")\n    \n    #s2 = lusolve(np.dot(A, A), c).T\n    #print(f\"soluzione 2 = {s2}\")\n    \n    L, U, flag = lunopivot(A)\n    s2 = lulusolve(L, U, c).T\n    print(f\"soluzione 2 = {s2}\")\n    \n    ", "meta": {"hexsha": "169028dd0c8aeb7cb5964a423433961ecb269d6b", "size": 1572, "ext": "py", "lang": "Python", "max_stars_repo_path": "esercitazioni/2021_01_15_es02.py", "max_stars_repo_name": "alemazzo/metodi_numerici", "max_stars_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-07-08T10:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T09:56:37.000Z", "max_issues_repo_path": "esercitazioni/2021_01_15_es02.py", "max_issues_repo_name": "alemazzo/metodi_numerici", "max_issues_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "esercitazioni/2021_01_15_es02.py", "max_forks_repo_name": "alemazzo/metodi_numerici", "max_forks_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2432432432, "max_line_length": 45, "alphanum_fraction": 0.4522900763, "include": true, "reason": "import numpy,import scipy", "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966641739773, "lm_q2_score": 0.9019206791658465, "lm_q1q2_score": 0.8537551062479183}}
{"text": "# Raphson Method for solving equations \nimport numpy as np\n# Given:\nx0 = 1.0\ne = 0.0001\nN = 5\ndef f( x ): \n\treturn np.exp(x) - (4 * x)\n# Derivative of the above function \ndef g( x ): \n\treturn np.exp(x) - 4\n# Implementing Newton Raphson Method\ndef newtonRaphson(x0,E,N):\n    print('\\n\\n*** NEWTON RAPHSON METHOD IMPLEMENTATION ***')\n    step = 1\n    flag = 1\n    condition = True\n\n    print('| Iteration |    x1         |     f(x1)    |')\n\n    while condition:\n        if g(x0) == 0.0:\n            print('Divide by zero error!')\n            break\n        \n        x1 = x0 - f(x0)/g(x0)\n\n        print('| %d         |   %0.6f    |    %0.6f  |'  % (step, x1, f(x1)))\n\n        x0 = x1\n        step = step + 1\n        \n        if step > N:\n            flag = 0\n            break\n        \n        condition = abs(f(x1)) > e\n    \n    if flag==1:\n        print('\\nRequired root is: %0.8f' % x1)\n    else:\n        print('\\nNot Convergent.')\n\n# Starting Newton Raphson Method\nnewtonRaphson(x0,e,N)", "meta": {"hexsha": "7bdde4d7789bed825dd63d76dd7ca84c3c7b9472", "size": 987, "ext": "py", "lang": "Python", "max_stars_repo_path": "newtonraphson.py", "max_stars_repo_name": "invincibleaayu/Mcsc202_II", "max_stars_repo_head_hexsha": "2a15e5641399d6f5e4800388af67ee7b78255327", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "newtonraphson.py", "max_issues_repo_name": "invincibleaayu/Mcsc202_II", "max_issues_repo_head_hexsha": "2a15e5641399d6f5e4800388af67ee7b78255327", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "newtonraphson.py", "max_forks_repo_name": "invincibleaayu/Mcsc202_II", "max_forks_repo_head_hexsha": "2a15e5641399d6f5e4800388af67ee7b78255327", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9333333333, "max_line_length": 77, "alphanum_fraction": 0.4924012158, "include": true, "reason": "import numpy", "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.9019206732341567, "lm_q1q2_score": 0.8537551047093652}}
{"text": "from pylab import *\nfrom scipy import interpolate, optimize\nfrom numpy import *\n\n# construct data point arrays first\nh = array([0.0,1.525,3.050,4.575,6.100,7.625,9.150])\nrho = array([1.0,0.8617,0.7385,0.6292,0.5328,0.4481,0.3741])\n\n\n# Part A\n# use Barycentric initally as the most direct path to an answer\nprint \"At 2km, the polynomial, interpolated value is:\"\nprint(str(interpolate.barycentric_interpolate(h,rho,2.0)))\n\nprint \"And at 4km, the interpolated value is:\"\nprint(str(interpolate.barycentric_interpolate(h,rho,4.0)))\n\nprint \"And at 8km, the interpolated value is:\"\nprint(str(interpolate.barycentric_interpolate(h,rho,8.0)))\n\n\n# B: cubic spline\nfit = interpolate.interp1d(h,rho,kind='cubic') #set up fit, called as fit(value)\n\nprint \"At h=2, h=4 and h=8 respectively, using a cubic spline, rho=\"\nprint fit(2.0), \", \", fit(4.0), \", \",fit(8.0)\n\n\n# C: errors\nrho_actual = 0.67\n\nprint \"Absolute error for polynomial interpolation:\"\nerr_abso_poly = np.abs(interpolate.barycentric_interpolate(h,rho,4.0)-rho_actual)\nprint err_abso_poly\nprint \"Relative error for polynomial interpolation:\"\nprint np.abs((err_abso_poly)/rho_actual)\n\nprint \"\\nAbsolute error for cubic spline:\"\nerr_abso_spline = np.abs((fit(4.0)-rho_actual))\nprint err_abso_spline\nprint \"Relative error for cubic spline:\"\nprint np.abs((err_abso_spline)/rho_actual)", "meta": {"hexsha": "3f38eed0b7e63bc7f4f74a5aa33cc6c4c272194c", "size": 1330, "ext": "py", "lang": "Python", "max_stars_repo_path": "ExamPrep/Shit Comp/ShitComp/(Past paper) 1314/Q2.py", "max_stars_repo_name": "FHomewood/ScientificComputing", "max_stars_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_stars_repo_licenses": ["IJG"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ExamPrep/Shit Comp/ShitComp/(Past paper) 1314/Q2.py", "max_issues_repo_name": "FHomewood/ScientificComputing", "max_issues_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_issues_repo_licenses": ["IJG"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ExamPrep/Shit Comp/ShitComp/(Past paper) 1314/Q2.py", "max_forks_repo_name": "FHomewood/ScientificComputing", "max_forks_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_forks_repo_licenses": ["IJG"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6666666667, "max_line_length": 81, "alphanum_fraction": 0.7503759398, "include": true, "reason": "from numpy,from scipy", "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296944, "lm_q2_score": 0.896251377983158, "lm_q1q2_score": 0.8537458713823385}}
{"text": "import cmath\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.signal as signal\n\n# Datos del a)\nfc = 1e3                      ; print('fc: {}'.format(fc))\nw0 = 2. * np.pi * fc          ; print('w0: {}'.format(w0))\nQ = 1. / np.sqrt(2.)          ; print('Q:  {}'.format(Q))\nfs = 100e3                    ; print('fs: {}'.format(fs))\n\n# Constantes utiles \nalpha = w0 ** 2.              ; print('alpha: {}'.format(alpha))\nbeta = w0 * 2. * fs / Q       ; print('beta: {}'.format(beta))\ngamma = 4. * (fs ** 2.)       ; print('gamma: {}'.format(gamma))\n\n# Coeficientes del filtro\nk = alpha / (alpha + beta + gamma) ; print('k: {}'.format(k))\nnum = k * np.array([1., 2., 1.]) ; print('Num: {}'.format(num))\nden = np.array([1., 2*(alpha - gamma)/(alpha + beta + gamma), (alpha - beta + gamma)/(alpha + beta + gamma)]) ; print('Den: {}'.format(den))\n\n# Respuesta del filtro\nw, h = signal.freqz(num, den, worN = 512, whole = False)\n\n# Respuesta en frecuencia del filtro\nfig, axs = plt.subplots(2)\nfig.suptitle('Respuesta de un Butterworth de 2do orden fc={}KHz y fs={}KHz'.format(fc, fs))\naxs[0].set_title('Respuesta de modulo')\naxs[0].semilogx(w, 20 * np.log10(abs(h)), 'b')\naxs[0].set_ylabel('|H| [dB]', color='b')\naxs[0].set_xlabel('Ω [rad/sample]')\naxs[0].grid()\n\naxs[1].set_title('Respuesta de fase')\naxs[1].semilogx(w, [cmath.phase(hh) for hh in h], 'b')\naxs[1].set_ylabel('arg(H) [rad]', color='b')\naxs[1].set_xlabel('Ω [rad/sample]')\naxs[1].grid()\nplt.show()\n\n# Polos y ceros del filtro\nzeros = np.roots(num)\npoles = np.roots(den)\nprint('Ceros: {}'.format(zeros))\nprint('Polos: {}'.format(poles))\n\nfig, ax = plt.subplots()\nfig.suptitle('Polos y ceros')\nunit_circle = plt.Circle((0.,0.), 1., fill=False, color='black')\nax.add_patch(unit_circle)\nax.scatter([hh.real for hh in zeros], [hh.imag for hh in zeros], marker='o', color='b')\nax.scatter([hh.real for hh in poles], [hh.imag for hh in poles], marker='x', color='b')\nax.set_xlabel('x')\nax.set_ylabel('jy')\nax.grid()\nplt.show()\n\n# Ufff, cuantas lineas de codigo. Siempre es a mano???\nnum_s = [w0**2.]\nden_s = [1., w0/Q, w0**2]\n\nnum_z, den_z = signal.bilinear(num_s, den_s, fs)\nprint('Num: {}'.format(num_z))\nprint('Den: {}'.format(den_z))\n\n\n", "meta": {"hexsha": "7c01d8baeb63a144e715a8463ce938a9841a2658", "size": 2204, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/iir/tp4_ej2.py", "max_stars_repo_name": "agalbachicar/tc2", "max_stars_repo_head_hexsha": "ee20fb326236ff66d0c40f9ad5374066bcd1a444", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-05-02T17:14:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T22:28:09.000Z", "max_issues_repo_path": "examples/iir/tp4_ej2.py", "max_issues_repo_name": "agalbachicar/tc2", "max_issues_repo_head_hexsha": "ee20fb326236ff66d0c40f9ad5374066bcd1a444", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2020-04-04T21:09:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-14T19:06:01.000Z", "max_forks_repo_path": "examples/iir/tp4_ej2.py", "max_forks_repo_name": "agalbachicar/tc2", "max_forks_repo_head_hexsha": "ee20fb326236ff66d0c40f9ad5374066bcd1a444", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-04T20:00:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-04T20:00:21.000Z", "avg_line_length": 32.8955223881, "max_line_length": 140, "alphanum_fraction": 0.6061705989, "include": true, "reason": "import numpy,import scipy", "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760638, "lm_q2_score": 0.8962513731336204, "lm_q1q2_score": 0.8537458679694797}}
{"text": "import numpy as np\n\n# y = { 0 (b + w1x1 + w2x2 <= 0)\n#       1 (b + w1x1 + w2x2 >  0)\ndef AND(x1, x2):\n    # 入力\n    x = np.array([x1, x2])\n    # 重み\n    w = np.array([0.5, 0.5])\n    # バイアス\n    b = -0.7\n    tmp = np.sum(w*x) + b\n    if tmp <= 0:\n        return 0\n    else:\n        return 1\n\nprint(\"AND -----------------\")\nprint(\"0, 0 -> \" + str(AND(0, 0)))\nprint(\"0, 1 -> \" + str(AND(0, 1)))\nprint(\"1, 0 -> \" + str(AND(1, 0)))\nprint(\"1, 1 -> \" + str(AND(1, 1)))\n\n# 重みとバイアスがANDと異なる\ndef NAND(x1, x2):\n    # 入力\n    x = np.array([x1, x2])\n    # 重み\n    w = np.array([-0.5, -0.5])\n    # バイアス\n    b = 0.7\n    tmp = np.sum(w*x) + b\n    if tmp <= 0:\n        return 0\n    else:\n        return 1\n\nprint(\"NAND ----------------\")\nprint(\"0, 0 -> \" + str(NAND(0, 0)))\nprint(\"0, 1 -> \" + str(NAND(0, 1)))\nprint(\"1, 0 -> \" + str(NAND(1, 0)))\nprint(\"1, 1 -> \" + str(NAND(1, 1)))\n\n# 重みとバイアスがANDと異なる\ndef OR(x1, x2):\n    # 入力\n    x = np.array([x1, x2])\n    # 重み\n    w = np.array([0.5, 0.5])\n    # バイアス\n    b = -0.2\n    tmp = np.sum(w*x) + b\n    if tmp <= 0:\n        return 0\n    else:\n        return 1\n\nprint(\"OR ------------------\")\nprint(\"0, 0 -> \" + str(OR(0, 0)))\nprint(\"0, 1 -> \" + str(OR(0, 1)))\nprint(\"1, 0 -> \" + str(OR(1, 0)))\nprint(\"1, 1 -> \" + str(OR(1, 1)))\n\n# XORは非線形なので層を重ねて実現する(多層パーセプトロン)\ndef XOR(x1, x2):\n    s1 = NAND(x1, x2)\n    s2 = OR(x1, x2)\n    y = AND(s1, s2)\n    return y\n\nprint(\"XOR -----------------\")\nprint(\"0, 0 -> \" + str(XOR(0, 0)))\nprint(\"0, 1 -> \" + str(XOR(0, 1)))\nprint(\"1, 0 -> \" + str(XOR(1, 0)))\nprint(\"1, 1 -> \" + str(XOR(1, 1)))\n", "meta": {"hexsha": "ee024a77c2a04d85ea38a365bd83822a130badfb", "size": 1545, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/chapter_2/logic_circuit.py", "max_stars_repo_name": "aaua-sandbox/hello-deep-learning", "max_stars_repo_head_hexsha": "635e2f3c20824f10b5a9d3b4e5ac1573c362e4e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chapter_2/logic_circuit.py", "max_issues_repo_name": "aaua-sandbox/hello-deep-learning", "max_issues_repo_head_hexsha": "635e2f3c20824f10b5a9d3b4e5ac1573c362e4e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chapter_2/logic_circuit.py", "max_forks_repo_name": "aaua-sandbox/hello-deep-learning", "max_forks_repo_head_hexsha": "635e2f3c20824f10b5a9d3b4e5ac1573c362e4e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3289473684, "max_line_length": 35, "alphanum_fraction": 0.4213592233, "include": true, "reason": "import numpy", "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741227833249, "lm_q2_score": 0.8962513696696647, "lm_q1q2_score": 0.8537458622564342}}
{"text": "import numpy as np\nimport torch\nfrom typing import Optional\nfrom scipy.optimize import linear_sum_assignment\n\n\ndef cluster_accuracy(y_true, y_predicted, cluster_number: Optional[int] = None):\n    \"\"\"\n    Calculate clustering accuracy after using the linear_sum_assignment function in SciPy to\n    determine reassignments.\n\n    :param y_true: list of true cluster numbers, an integer array 0-indexed\n    :param y_predicted: list  of predicted cluster numbers, an integer array 0-indexed\n    :param cluster_number: number of clusters, if None then calculated from input\n    :return: reassignment dictionary, clustering accuracy\n    \"\"\"\n    if cluster_number is None:\n        cluster_number = max(y_predicted.max(), y_true.max()) + 1  # assume labels are 0-indexed\n    count_matrix = np.zeros((cluster_number, cluster_number), dtype=np.int64)\n    for i in range(y_predicted.size):\n        count_matrix[y_predicted[i], y_true[i]] += 1\n\n    row_ind, col_ind = linear_sum_assignment(count_matrix.max() - count_matrix)\n    reassignment = dict(zip(row_ind, col_ind))\n    accuracy = count_matrix[row_ind, col_ind].sum() / y_predicted.size\n    return reassignment, accuracy\n\n\ndef target_distribution(batch: torch.Tensor) -> torch.Tensor:\n    \"\"\"\n    Compute the target distribution p_ij, given the batch (q_ij), as in 3.1.3 Equation 3 of\n    Xie/Girshick/Farhadi; this is used the KL-divergence loss function.\n\n    :param batch: [batch size, number of clusters] Tensor of dtype float\n    :return: [batch size, number of clusters] Tensor of dtype float\n    \"\"\"\n    weight = (batch ** 2) / torch.sum(batch, 0)\n    return (weight.t() / torch.sum(weight, 1)).t()\n", "meta": {"hexsha": "8ec5768bd6eb3d7b692e0916bd746534a1782fe5", "size": 1649, "ext": "py", "lang": "Python", "max_stars_repo_path": "ptdec/utils.py", "max_stars_repo_name": "zhyhan/pt-dec", "max_stars_repo_head_hexsha": "52aef59e508c8e7ffdde0fd7bea84570a7571b2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ptdec/utils.py", "max_issues_repo_name": "zhyhan/pt-dec", "max_issues_repo_head_hexsha": "52aef59e508c8e7ffdde0fd7bea84570a7571b2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ptdec/utils.py", "max_forks_repo_name": "zhyhan/pt-dec", "max_forks_repo_head_hexsha": "52aef59e508c8e7ffdde0fd7bea84570a7571b2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2820512821, "max_line_length": 96, "alphanum_fraction": 0.7258944815, "include": true, "reason": "import numpy,from scipy", "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.8962513655129177, "lm_q1q2_score": 0.8537458619168811}}
{"text": "from scipy.stats import chi2_contingency\nfrom scipy.stats import chi2\n\n# Game on 327\n#          Ctrl, V1, V2, V3\n# Game       15   5   8  10\n# Not Game   55  37  41  33\n\n# Game on 544\n#          Ctrl, V1, V2, V3\n# Game       9   3   3  6\n# Not Game   30  34  41  32         \ntable = [[15, 5, 8, 10],\n         [70-15, 42-5, 49-8, 43-10]]\n\ntable1 = [[9, 3, 3, 6], [30, 34, 41, 32]]\nstat, p, dof, expected = chi2_contingency(table1)\nprint('* Degree of Freedom: %d' % dof)\n\n# 解释结果\nprob = 0.95\ncritical = chi2.ppf(prob, dof)\nprint('* Accept Probability = %.3f' % prob)\nprint('* Critical = %.3f' % critical)\n\nprint('* Interpretation as follows:')\nprint('- Chi^2 = %.3f' % stat)\nprint('- P-val = %.3f' % p)\nif abs(stat) >= critical:\n    print('- Dependent (reject H0)')\nelse:\n    print('- Independent (fail to reject H0)')\n\nalpha = 1.0 - prob\nif p <= alpha:\n    print('- p-value(%.2f) <= %.2f, dependent (reject H0)' % (p, alpha))\nelse:\n    print('- p-value(%.2f) > %.2f, independent (fail to reject H0)' % (p, alpha))\n", "meta": {"hexsha": "4f83682bac701b34aaa9b9464f7ba2326d3a4f39", "size": 1012, "ext": "py", "lang": "Python", "max_stars_repo_path": "processing/statistics.py", "max_stars_repo_name": "xiameng552180/Intervention", "max_stars_repo_head_hexsha": "1cc0b48aeeb2e58defbc1707c1a474d6b4088e57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "processing/statistics.py", "max_issues_repo_name": "xiameng552180/Intervention", "max_issues_repo_head_hexsha": "1cc0b48aeeb2e58defbc1707c1a474d6b4088e57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "processing/statistics.py", "max_forks_repo_name": "xiameng552180/Intervention", "max_forks_repo_head_hexsha": "1cc0b48aeeb2e58defbc1707c1a474d6b4088e57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9487179487, "max_line_length": 81, "alphanum_fraction": 0.5632411067, "include": true, "reason": "from scipy", "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211590308922, "lm_q2_score": 0.8757869916479466, "lm_q1q2_score": 0.8537356902624296}}
{"text": "import numpy as np\nfrom Exercise5.lu_decomposition import lu\n\n\ndef splines_interpolation(x, y):\n    \"\"\"\n        Computes c of the natural cubic spline interpolating the points given.\n\n        Parameters\n        ----------\n        x : list\n            The values of the independent variable. <b>Must be sorted.</b>\n        y : list\n            The values of f(x) for every x, where x is the independent variable\n\n        Returns\n        -------\n        c : list\n           coefficients of interpolating polynomial\n    \"\"\"\n    # create the values for a(i)\n    a = []\n    d = []\n    delta = []\n    for i in range(len(x) - 1):\n        a.append(y[i])\n        d.append(x[i + 1] - x[i])\n        delta.append(y[i + 1] - y[i])\n\n    # create the system matrix\n    system_matrix = [[0.0 for j in range(len(x))] for i in range(len(x))]\n    system_matrix[0][0] = 1\n    system_matrix[len(x) - 1][len(x) - 1] = 1\n    for row in range(1, len(x) - 1):\n        system_matrix[row][row - 1] = d[row - 1]\n        system_matrix[row][row] = 2 * (d[row - 1] + d[row])\n        system_matrix[row][row + 1] = d[row]\n\n    # create the constant vector of the system\n    constant_vector = [0.0 for i in range(len(x))]\n    for row in range(1, len(x) - 1):\n        constant_vector[row] = 3 * ((delta[row] / d[row]) - (delta[row - 1] / d[row - 1]))\n\n    # solve the system using lu decomposition, c_vector contains the values for c(i)\n    c_vector = lu(system_matrix, constant_vector)\n\n    # find the c for b(i) and d(i)\n    b = list(d)\n    final_d = list(d)\n    for i in range(len(x) - 1):\n        final_d[i] = (c_vector[i + 1] - c_vector[i]) / (3 * d[i])\n        b[i] = (delta[i] / d[i]) - (d[i] / 3) * (2 * c_vector[i] + c_vector[i + 1])\n\n    return a, b, c_vector, final_d\n\n\ndef find_interval_index(array, low, high, search_value):\n    \"\"\"\n        Finds the position index that the search_value should be inserted in the array.\n\n        Parameters\n        ----------\n        array : list\n            The array for searching where to insert the search_value. <b>Must be sorted.</b>\n        low : int\n            The low index of the interval that we are going to search in the array.\n        high : int\n            The max index of the interval that we are going to search in the array.\n        search_value : float\n            The value for which we search to find where it should be inserted.\n\n        Returns\n        -------\n        int\n            The index that should be the search_value inserted in the array.\n    \"\"\"\n    while low < high:\n        mid = int((high+low)//2)\n        if array[mid] == search_value:\n            break\n        elif array[mid] > search_value:\n            high = mid - 1\n        else:\n            low = mid + 1\n\n    mid = int((high+low)//2)\n    if search_value <= array[mid]:\n        return mid\n\n    return mid + 1\n\n\ndef calculate_polynomial(a, b, c, d, x_values, x):\n    \"\"\"\n        Computes the value of the natural cubic spline.\n\n        Parameters\n        ----------\n        a, b, c, d : list\n            The essential c of the natural cubic spline.\n        x_values : list\n            The values of the independent variable in the data points that were used when calculating the c\n            of the natural cubic spline.\n        x : int\n            The point at which the polynomial will be calculated\n\n        Returns\n        -------\n        value : float\n            The value of the interpolating polynomial at point x.\n    \"\"\"\n    i = find_interval_index(x_values, 0, len(x_values)-1, x) - 1\n    return a[i] + b[i]*(x-x_values[i]) + c[i]*((x-x_values[i])**2) + d[i]*((x-x_values[i])**3)\n\n\ndef custom_sin(value):\n    \"\"\"\n        Approximates sin curve with natural cubic splines.\n\n        Parameters\n        ----------\n        value : float\n            The point at which the sin will be approximated\n\n        Returns\n        -------\n        float\n            The approximation value of the sin curve at point x.\n    \"\"\"\n    x = [0.0, 0.65, 1.3, 1.9500000000000002, 2.6, 3.25, 3.9000000000000004, 4.55, 5.2, 2*np.pi]\n    y = [0.0, 0.6051864057, 0.9635581854, 0.9289597150, 0.5155013718, -0.1081951345, -0.6877661591, -0.9868438585,\n         -0.8834546557, 0]\n    a, b, c, d = splines_interpolation(x, y)\n\n    value = value % (2*np.pi)\n    return calculate_polynomial(a, b, c, d, x, value)\n", "meta": {"hexsha": "4cf850cb344d7b37378dacee7d415d779e7c2b80", "size": 4301, "ext": "py", "lang": "Python", "max_stars_repo_path": "Second Project/Exercise5/splines.py", "max_stars_repo_name": "TasosOperatingInBinary/Numerical-Analysis-Projects", "max_stars_repo_head_hexsha": "61a8014f2b853a646145cea5a4d3655e100be854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Second Project/Exercise5/splines.py", "max_issues_repo_name": "TasosOperatingInBinary/Numerical-Analysis-Projects", "max_issues_repo_head_hexsha": "61a8014f2b853a646145cea5a4d3655e100be854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Second Project/Exercise5/splines.py", "max_forks_repo_name": "TasosOperatingInBinary/Numerical-Analysis-Projects", "max_forks_repo_head_hexsha": "61a8014f2b853a646145cea5a4d3655e100be854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3941605839, "max_line_length": 114, "alphanum_fraction": 0.5584747733, "include": true, "reason": "import numpy", "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.9136765163620469, "lm_q1q2_score": 0.8537349153467437}}
{"text": "import numpy as np\nimport control\n\n# g = 9.8\n# L = 1.5\n# m = 1.0 # mass of bob (kg)\n# M = 5.0  # mass of cart (kg)\n# d1 = 1.0\n# d2 = 0.5\n\n    #   pendulum_mass: 1.0 (m)\n    #   cart_mass: 5.0  (M)\n    #   pendulum_length: 2.0\n    #   damping_coefficient: 20.0\n    #   gravity: -9.8\n    #   max_cart_force: 1000.0\n    #   noise_level: 0.0\n\ng = 9.8\nL = 1.5\nm = 1.0\nM = 5.0\nd1 = 1.0\nd2 = 0.5\n\n\n# Pendulum up (linearized eq)\n# Eigen val of A : array([[ 1.        , -0.70710678, -0.07641631,  0.09212131] )\n_q = (m+M) * g / (M*L)\nA = np.array([\\\n            [0,1,0,0], \\\n            [0,-d1, -g*m/M,0],\\\n            [0,0,0,1.],\\\n            [0,d1/L,_q,-d2] ] )\n\nB = np.expand_dims( np.array( [0, 1.0/M, 0., -1/(M*L)] ), 1 )\n\n\n\n# Pendulum Down - Verified correct.\n# Eigen Values of this: array([ 0.00+0.j        , -1.00+0.j        , -0.25+2.78881695j,       -0.25-2.78881695j])\n# A = np.array([\\\n#             [0,1,0,0], \\\n#             [0,-d1, -g*m/(2*m+M),0],\\\n#             [0,0,0,1],\\\n#             [0,0,-(M+m)*g/(M*L),-d2] ] )\n\n#B = np.array( [] )\n\nprint ('A\\n', A)\nprint ('B\\n', B)\n\n# Controllability\nprint ('---Controllability\\n')\nprint ('rank of ctrb(A,b) \\n' , np.linalg.matrix_rank( control.ctrb( A, B ) ))\nprint ('Eigenvalues of A \\n', np.linalg.eig( A ))\n\n\n# Pole Placement\nK = control.place( A, B, [-1, -2, -4, -5] )\nprint ('---Pole Placement\\nK=\\n', K)\n\n# Verification of Eigen values of A-BK\nprint ('---Verification of Eigen values of A-BK')\nprint ('Eigenvalues of A-BK \\ n', np.linalg.eig( A-np.matmul(B,K) ))\n", "meta": {"hexsha": "f63c5b02b01dce5c25396d309839ae2fca32cce5", "size": 1519, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/analysis_of_linearization.py", "max_stars_repo_name": "swgu931/ros2-pendulum-caas", "max_stars_repo_head_hexsha": "b8464633366eddd20845ffb4f104bb41e12d9a72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model/analysis_of_linearization.py", "max_issues_repo_name": "swgu931/ros2-pendulum-caas", "max_issues_repo_head_hexsha": "b8464633366eddd20845ffb4f104bb41e12d9a72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/analysis_of_linearization.py", "max_forks_repo_name": "swgu931/ros2-pendulum-caas", "max_forks_repo_head_hexsha": "b8464633366eddd20845ffb4f104bb41e12d9a72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0151515152, "max_line_length": 113, "alphanum_fraction": 0.4983541804, "include": true, "reason": "import numpy", "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723354, "lm_q2_score": 0.8918110490322425, "lm_q1q2_score": 0.8537109223083065}}
{"text": "from scipy.integrate import odeint\r\nfrom numpy import arange\r\nimport matplotlib.pyplot as plt\r\n\r\ndef SIRS(state,t):\r\n    \r\n  # Initialization of States\r\n  S = state[0]\r\n  I = state[1]\r\n  R = state[2]\r\n\r\n  # Appropriate Constants\r\n  beta = 0.25 # Rate of infection; needs to be divided by N in the system of ODEs\r\n  gamma = 0.2 # Proportion leaving infected to become resistant\r\n  rho = 0.1 # Proportion leaving resistant to become susceptible.\r\n  N = S + I + R\r\n  # compute state derivatives\r\n  dS = (rho*R) - ((beta/N)*S*I)\r\n  dI = ((beta/N)*S*I) - (gamma*I)\r\n  dR = (gamma*I) - (rho*R)\r\n\r\n  # return the state derivatives\r\n  return [dS, dI, dR]\r\n\r\nstate0 = [33, 33, 33]\r\nt = arange(0.0, 100, 0.01)\r\n\r\nstate = odeint(SIRS, state0, t)\r\n\r\n# Plots\r\n\r\nsusceptible = state[:, 0]\r\ninfected = state[:, 1]\r\nresistant = state[:, 2]\r\n\r\nfig = plt.figure(figsize=(15,5))\r\nfig.subplots_adjust(wspace = 0.5, hspace = 0.3)\r\nax1 = fig.add_subplot(1,2,1)\r\nax2 = fig.add_subplot(1,2,2)\r\n\r\nax1.plot(susceptible, 'b-', label = \"Susceptible\")\r\nax1.plot(infected, 'r-', label = \"Infected\")\r\nax1.plot(resistant, 'g-', label = \"Resistant\")\r\nax1.set_title(\"Sample Dynamics of SIRS Model in Time\")\r\nax1.set_xlabel(\"Time\")\r\nax1.grid()\r\nax1.legend(loc = 'best', fontsize = 'small')\r\n\r\n\r\n\r\nax2.plot(susceptible, infected, color = \"purple\", label = 'S-I Phase')\r\nax2.plot(susceptible, resistant, color = \"cyan\", label = 'S-R Phase')\r\nax2.plot(infected, resistant, color = \"yellow\", label = 'I-R Phase')\r\nax2.set_title(\"SIRS Sample Phase Space\")\r\nax2.legend(loc = 'best', fontsize = 'small')\r\nax2.grid()\r\n\r\nextent = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())\r\nfig.savefig('timedynamics5.png', bbox_inches=extent.expanded(1.3, 1.3))\r\nextent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())\r\nfig.savefig('phase5.png', bbox_inches=extent.expanded(1.2, 1.2))\r\n\r\nplt.show()", "meta": {"hexsha": "a5edd756c1580fd068a431df0337260867965030", "size": 1884, "ext": "py", "lang": "Python", "max_stars_repo_path": "Epidemiology/SIRS_Classic_ODE.py", "max_stars_repo_name": "singhster96/Mini_Projs", "max_stars_repo_head_hexsha": "5ac4058febc5ba251d82c997be13c05929ce1697", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Epidemiology/SIRS_Classic_ODE.py", "max_issues_repo_name": "singhster96/Mini_Projs", "max_issues_repo_head_hexsha": "5ac4058febc5ba251d82c997be13c05929ce1697", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Epidemiology/SIRS_Classic_ODE.py", "max_forks_repo_name": "singhster96/Mini_Projs", "max_forks_repo_head_hexsha": "5ac4058febc5ba251d82c997be13c05929ce1697", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9047619048, "max_line_length": 82, "alphanum_fraction": 0.6634819533, "include": true, "reason": "from numpy,from scipy", "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778012346834, "lm_q2_score": 0.89181104831338, "lm_q1q2_score": 0.8537109194462305}}
{"text": "# %% [markdown]\n\"\"\"\n# Maximum Mean Discrepancy\n\nThis example demonstrates the maximum mean discrepancy using data drawn from two\ndifferent distributions. Additionally, we demonstrate the empirical witness function,\nwhich displays the difference between the two distributions.\n\nTo run the example, use the following command:\n\n```shell\n    python examples/kernel/maximum_mean_discrepancy.py\n```\n\n\"\"\"\n\n# %%\nimport numpy as np\nfrom gym_socks.kernel.probability import maximum_mean_discrepancy\nfrom gym_socks.kernel.probability import witness_function\n\nfrom sklearn.metrics.pairwise import rbf_kernel\nfrom functools import partial\n\n# %% [markdown]\n# ## Generate the Sample\n#\n# Define the kernel function and generate the data.\n#\n# We generate two samples, one from a Gaussian distribution and another from a Laplacian\n# distribution to mimic the example from literature. Higher sample sizes will lead to a\n# more accurate result.\n\n# %%\nsigma = 0.25\nkernel_fn = partial(rbf_kernel, gamma=1 / (2 * (sigma ** 2)))\n\nm = 5000  # sample size for P\nn = 5000  # sample size for Q\n\nX = np.random.standard_normal(size=(m, 1))\nY = np.random.laplace(size=(n, 1))\n\n# %% [markdown]\n# ## Compute the MMD\n#\n# We then compute the maximum mean discrepancy using both the unbiased and biased\n# statistics.\n\n# %%\nmaximum_mean_discrepancy(X, Y, kernel_fn=kernel_fn, biased=True, squared=False)\n\n# %%\nmaximum_mean_discrepancy(X, Y, kernel_fn=kernel_fn, biased=False, squared=False)\n\n# %% [markdown]\n# ## Plot the Witness Function\n#\n# The witness function is used to view the difference between the two distributions.\n#\n# We plot the witness function, along with the true PDF of both the Gaussian and\n# Laplacian distributions to illustrate the difference between the two samples.\n# Intuitively, the witness function should have values closer to zero where the two\n# distributions are similar, and have larger values (further from zero) where the\n# distributions are dissimilar.\n#\n# This depends on the kernel used, the kernel parameters (the bandwidth in the case of\n# the RBF kernel), and the density of sample information (which is highest close to the\n# mean, i.e. the witness function will be more accurate in areas where the sample\n# density is high).\n\n# %%\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfrom scipy import stats\n\nt = np.linspace(-5, 5, 1000).reshape(-1, 1)\nz = witness_function(X, Y, t, kernel_fn=kernel_fn)\n\npdf_gaussian = stats.norm.pdf(t, 0, 1)\npdf_laplacian = stats.laplace.pdf(t, 0, 1)\n\nfig = plt.figure()\nax = plt.axes()\nplt.grid()\n\nplt.plot(t, z, label=\"Witness Function\")\nplt.plot(t, pdf_gaussian, label=\"Gaussian PDF\")\nplt.plot(t, pdf_laplacian, label=\"Laplacian PDF\")\n\nplt.legend()\nplt.show()\n\n# %%\nfig = plt.figure()\nax = plt.axes()\nplt.grid()\n\nplt.plot(t, z, label=\"Witness Function\")\nplt.plot(t, pdf_gaussian - pdf_laplacian, label=\"Actual Difference\")\n\nplt.legend()\nplt.show()\n", "meta": {"hexsha": "76ac5a8a323f1c90ef8138253ac3f4d16b62882d", "size": 2890, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/kernel/maximum_mean_discrepancy.py", "max_stars_repo_name": "ajthor/socks", "max_stars_repo_head_hexsha": "77063064ceb5a5da3f01733bef0885b00d4b2bed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/kernel/maximum_mean_discrepancy.py", "max_issues_repo_name": "ajthor/socks", "max_issues_repo_head_hexsha": "77063064ceb5a5da3f01733bef0885b00d4b2bed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-09T21:15:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-09T21:15:26.000Z", "max_forks_repo_path": "examples/kernel/maximum_mean_discrepancy.py", "max_forks_repo_name": "ajthor/socks", "max_forks_repo_head_hexsha": "77063064ceb5a5da3f01733bef0885b00d4b2bed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5238095238, "max_line_length": 88, "alphanum_fraction": 0.7480968858, "include": true, "reason": "import numpy,from scipy", "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.9184802451409949, "lm_q1q2_score": 0.8536726445524296}}
{"text": "import numpy\nfrom matplotlib import pyplot\n\ndef rk4(f, x_end, y0, N):\n    x, dx = numpy.linspace(0, x_end, N+1, retstep=True)\n    y = numpy.zeros((len(y0),N+1))\n    y[:,0] = y0\n    for n in range(N):\n        k1 = dx * f(x[n]         , y[:,n]         )\n        k2 = dx * f(x[n] + dx / 2, y[:,n] + k1 / 2)\n        k3 = dx * f(x[n] + dx / 2, y[:,n] + k2 / 2)\n        k4 = dx * f(x[n] + dx    , y[:,n] + k3    )\n        y[:,n+1] = y[:,n] + (k1 + 2 * (k2 + k3) + k4) / 6\n    return x, dx, y\n\nA_am5 = numpy.array([ [1.0, 1, 1, 1, 1],\n                      [4.0, 3, 2, 1, 0],\n                      [12, 6, 2, 0, 0], \n                      [24, 6, 0, 0, 0],\n                      [24, 0, 0, 0, 0]])\nrhs_am5 = numpy.array([1.0, 1/2, -1/6, 1/4, -19/30])\nb_am5 = numpy.linalg.solve(A_am5, rhs_am5)\n\nA_ab5 = numpy.array([ [1.0, 1, 1, 1, 1],\n                      [4.0, 3, 2, 1, 0],\n                      [12, 6, 2, 0, 0], \n                      [24, 6, 0, 0, 0],\n                      [24, 0, 0, 0, 0]])\nrhs_ab5 = numpy.array([1.0, -1/2, 5/6, -9/4, 251/30])\nb_ab5 = numpy.linalg.solve(A_ab5, rhs_ab5)\n\ndef am5(f, x_end, y0, N):\n    x, dx = numpy.linspace(0, x_end, N+1, retstep=True)\n    y = numpy.zeros((len(y0),N+1))\n    fn = numpy.zeros((len(y0),N+1))\n    y[:,0] = y0\n    x_rk4, dx_rk4, y_rk4 = rk4(f, 4*dx, y0, 4)\n    y[:,:5] = y_rk4[:,:5]\n    for n in range(5):\n        fn[:,n] = f(x[n], y[:,n])\n    for n in range(4,N):\n        fn[:,n] = f(x[n], y[:,n])\n        yp = y[:,n] + dx * (b_ab5[4] * fn[:,n] + \n                            b_ab5[3] * fn[:,n-1] + \n                            b_ab5[2] * fn[:,n-2] + \n                            b_ab5[1] * fn[:,n-3] + \n                            b_ab5[0] * fn[:,n-4])\n        fp = f(x[n+1], yp)\n        y[:,n+1] = y[:,n] + dx * (b_am5[4] * fp + \n                                  b_am5[3] * fn[:,n] + \n                                  b_am5[2] * fn[:,n-1] + \n                                  b_am5[1] * fn[:,n-2] + \n                                  b_am5[0] * fn[:,n-3])\n    return x, dx, y\n\nif __name__==\"__main__\":\n\n    def f_sin(x, y):\n        return -numpy.sin(x)\n    print(\"RK4\")\n    x, dx, y = rk4(f_sin, 0.5, [1], 10)\n    print(\"dx=\", dx, \"y(0.5)=\", y[0,-1])\n    x, dx, y = rk4(f_sin, 0.5, [1], 100)\n    print(\"dx=\", dx, \"y(0.5)=\", y[0,-1])\n    Npoints = 5*2**numpy.arange(1,7)\n    dx_all = 0.5/Npoints\n    errors = numpy.zeros_like(dx_all)\n    for i, N in enumerate(Npoints):\n        x, dx, y = rk4(f_sin, 0.5, [1], N)\n        errors[i] = abs(y[0,-1] - numpy.cos(0.5))\n        dx_all[i] = dx\n    pyplot.figure(figsize=(12,6))\n    pyplot.loglog(dx_all, errors, 'kx')\n    pyplot.loglog(dx_all, errors[0]*(dx_all/dx_all[0])**4, 'b-',\n                  label=r\"$\\propto \\Delta x^4$\")\n    pyplot.legend(loc='upper left')\n    pyplot.xlabel(r\"$\\Delta x$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.show()\n    \n    print(\"Adams-Moulton 5\")\n    x, dx, y = am5(f_sin, 0.5, [1], 10)\n    print(\"dx=\", dx, \"y(0.5)=\", y[0,-1])\n    x, dx, y = am5(f_sin, 0.5, [1], 100)\n    print(\"dx=\", dx, \"y(0.5)=\", y[0,-1])\n    Npoints = 5*2**numpy.arange(1,7)\n    dx_all = 0.5/Npoints\n    errors = numpy.zeros_like(dx_all)\n    for i, N in enumerate(Npoints):\n        x, dx, y = am5(f_sin, 0.5, [1], N)\n        errors[i] = abs(y[0,-1] - numpy.cos(0.5))\n        dx_all[i] = dx\n    pyplot.figure(figsize=(12,6))\n    pyplot.loglog(dx_all, errors, 'kx')\n    pyplot.loglog(dx_all, errors[0]*(dx_all/dx_all[0])**5, 'b-',\n                  label=r\"$\\propto \\Delta x^5$\")\n    pyplot.legend(loc='upper left')\n    pyplot.xlabel(r\"$\\Delta x$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.show()\n    ", "meta": {"hexsha": "b28e19ab6d7f885314cac74b2ae8cdb8bd6fc39d", "size": 3596, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/tex/codes/lecture17.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Lectures/tex/codes/lecture17.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Lectures/tex/codes/lecture17.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 35.603960396, "max_line_length": 64, "alphanum_fraction": 0.4251946607, "include": true, "reason": "import numpy", "num_tokens": 1419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102514755852, "lm_q2_score": 0.8824278772763472, "lm_q1q2_score": 0.853669774664978}}
{"text": "# generar una normal de altura y peso\nimport numpy as np\n\nheight = np.round(np.random.normal(1.75, 0.20, 5000), 2)\nweight = np.round(np.random.normal(60.32, 15, 5000), 2)\nnp_city = np.column_stack((height, weight))\n\nprint(np_city)\n\n# Print mean height (first column)\navg = round(np.mean(np_city[:,0]),2)\nprint(\"Average: \" + str(avg))\n\n# Print median height.\nmed = np.median(np_city[:,0])\nprint(\"Median: \" + str(med))\n\n# Print out the standard deviation on height.\nstddev = round(np.std(np_city[:,0]),2)\nprint(\"Standard Deviation: \" + str(stddev))\n\n# Print out correlation between first and second column.\ncorr = np.corrcoef(np_city[:,0],np_city[:,1])\nprint(\"Correlation: \" + str(corr))", "meta": {"hexsha": "f7974e2709e63808a2cb9668de57117458ec8cf5", "size": 685, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/pruebas/prueba1NumPy.py", "max_stars_repo_name": "igorfyago/Andrew-Ng-Machine-Learning", "max_stars_repo_head_hexsha": "e6f947c93f9a4b1c9cfdaab4333525c504fd9233", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/pruebas/prueba1NumPy.py", "max_issues_repo_name": "igorfyago/Andrew-Ng-Machine-Learning", "max_issues_repo_head_hexsha": "e6f947c93f9a4b1c9cfdaab4333525c504fd9233", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/pruebas/prueba1NumPy.py", "max_forks_repo_name": "igorfyago/Andrew-Ng-Machine-Learning", "max_forks_repo_head_hexsha": "e6f947c93f9a4b1c9cfdaab4333525c504fd9233", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5416666667, "max_line_length": 56, "alphanum_fraction": 0.6948905109, "include": true, "reason": "import numpy", "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9845754501811437, "lm_q2_score": 0.8670357683915538, "lm_q1q2_score": 0.8536621319872679}}
{"text": "import pandas as pd\nimport scipy.stats\nfrom scipy import stats\nfrom scipy.stats import f_oneway\n\n# Input parameters: sample (pd df), population mean (float), significance level (optional float)\n# Return values: p-value, t-value, confidence interval (lower), confidence interval (upper), mean of sample, reject/accept (1 = accept, 0 = reject)\ndef t_test_1_samp(x, pop_mean, sig_lvl=0.05):\n\n    out = 0\n\n    if out:\n        print(\"One Sample t-test\")\n\n    samp_mean = float(x.mean())\n    samp_sd = float(x.std())\n    n = x.shape[0]\n\n    t = float((samp_mean - pop_mean) / (samp_sd / pow(n, 0.5)))\n    p = scipy.stats.t.sf(abs(t), df=n - 1) * 2\n    con_1, con_2 = scipy.stats.t.interval(\n        alpha=1 - sig_lvl, df=n - 1, loc=samp_mean, scale=scipy.stats.sem(x)\n    )\n\n    con_1 = float(con_1)\n    con_2 = float(con_2)\n\n    if out:\n        print(\"t = \" + str(t))\n        print(\"df = \" + str(n - 1))\n        print(\"p-value = \" + str(p))\n\n    accept = 1\n    if p > sig_lvl:\n        if out:\n            print(\"Alternative hypothesis: true mean is not equal to \" + str(pop_mean))\n        accept = 0\n    else:\n        if out:\n            print(\"Null hypothesis: true mean is equal to \" + str(pop_mean))\n\n    if out:\n        print(\n            str(100 * (1 - sig_lvl))\n            + \"% confidence interval: \"\n            + str(con_1)\n            + \" \"\n            + str(con_2)\n        )\n        print(\"Mean of x: \" + str(samp_mean))\n\n    result = {\n        \"p_value\": p,\n        \"t_value\": t,\n        \"con_low\": con_1,\n        \"con_up\": con_2,\n        \"sample_mean_1\": samp_mean,\n        \"accept\": accept,\n    }\n\n    return result\n\n\n# Input parameters: sample 1 (pd df), sample 2 (pd df), significance level (optional float)\n# Return values: p-value, t-value, confidence interval (lower), confidence interval (upper), mean of sample 1, mean of sample 2, reject/accept (1 = accept, 0 = reject)\ndef t_test_welch(x, y, sig_lvl=0.05):\n\n    out = 0\n\n    if out:\n        print(\"Welch Two sample t-test (unequal variance)\")\n\n    mu_1 = float(x.mean())\n    mu_2 = float(y.mean())\n    s1 = x.std()\n    s2 = y.std()\n    n1 = x.shape[0]\n    n2 = y.shape[0]\n\n    t, p = stats.ttest_ind(x, y, equal_var=False)\n    t = float(t)\n    p = float(p)\n\n    con_1 = float(\n        (mu_1 - mu_2)\n        - (\n            scipy.stats.t.ppf((1 - sig_lvl / 2), n1 + n2 - 2)\n            * pow(((((n1 - 1) * s1 * s1) + ((n2 - 1) * s2 * s2)) / (n1 + n2 - 2)), 0.5)\n            * pow((1 / n1 + 1 / n2), 0.5)\n        )\n    )\n    con_2 = float(\n        (mu_1 - mu_2)\n        + (\n            scipy.stats.t.ppf((1 - sig_lvl / 2), n1 + n2 - 2)\n            * pow(((((n1 - 1) * s1 * s1) + ((n2 - 1) * s2 * s2)) / (n1 + n2 - 2)), 0.5)\n            * pow((1 / n1 + 1 / n2), 0.5)\n        )\n    )\n\n    if out:\n        print(\"t = \" + str(t))\n        print(\"df = \" + str(n1 + n2 - 2))\n        print(\"p-value = \" + str(p))\n\n    accept = 1\n    if p > sig_lvl:\n        if out:\n            print(\"Alternative hypothesis: true difference in means is not equal to 0\")\n        accept = 0\n    else:\n        if out:\n            print(\"Null hypothesis: true difference in means is equal to 0\")\n\n    if out:\n        print(\n            str(100 * (1 - sig_lvl))\n            + \"% confidence interval: \"\n            + str(con_1)\n            + \" \"\n            + str(con_2)\n        )\n        print(\"Mean of x and mean of y (respectively): \" + str(mu_1) + \", \" + str(mu_2))\n        print()\n\n    result = {\n        \"p_value\": p,\n        \"t_value\": t,\n        \"con_low\": con_1,\n        \"con_up\": con_2,\n        \"sample_mean_1\": mu_1,\n        \"sample_mean_2\": mu_2,\n        \"accept\": accept,\n    }\n    return result\n\n\n# Input parameters: sample 1 (pd df), sample 2 (pd df), significance level (optional float)\n# Return values: p-value, t-value, confidence interval (lower), confidence interval (upper), mean of sample 1, mean of sample 2, reject/accept (1 = accept, 0 = reject)\ndef t_test_2_samp_equal_var(x, y, sig_lvl=0.05):\n\n    out = 0\n\n    if out:\n        print(\"Two sample t-test (equal variance)\")\n\n    mu_1 = float(x.mean())\n    mu_2 = float(y.mean())\n    s1 = x.std()\n    s2 = y.std()\n    n1 = x.shape[0]\n    n2 = y.shape[0]\n\n    t = float((mu_1 - mu_2) / (pow((s1 * s1 / n1) + (s2 * s2 / n2), 0.5)))\n\n    p = scipy.stats.t.sf(abs(t), df=n1 + n2 - 2) * 2\n    con_1 = float(\n        (mu_1 - mu_2)\n        - (\n            scipy.stats.t.ppf((1 - sig_lvl / 2), n1 + n2 - 2)\n            * pow(((((n1 - 1) * s1 * s1) + ((n2 - 1) * s2 * s2)) / (n1 + n2 - 2)), 0.5)\n            * pow((1 / n1 + 1 / n2), 0.5)\n        )\n    )\n    con_2 = float(\n        (mu_1 - mu_2)\n        + (\n            scipy.stats.t.ppf((1 - sig_lvl / 2), n1 + n2 - 2)\n            * pow(((((n1 - 1) * s1 * s1) + ((n2 - 1) * s2 * s2)) / (n1 + n2 - 2)), 0.5)\n            * pow((1 / n1 + 1 / n2), 0.5)\n        )\n    )\n\n    if out:\n        print(\"t = \" + str(t))\n        print(\"df = \" + str(n1 + n2 - 2))\n        print(\"p-value = \" + str(p))\n\n    accept = 1\n    if p > sig_lvl:\n        if out:\n            print(\"Alternative hypothesis: true difference in means is not equal to 0\")\n        accept = 0\n    else:\n        if out:\n            print(\"Null hypothesis: true difference in means is equal to 0\")\n\n    if out:\n        print(\n            str(100 * (1 - sig_lvl))\n            + \"% confidence interval: \"\n            + str(con_1)\n            + \" \"\n            + str(con_2)\n        )\n        print(\"Mean of x and mean of y (respectively): \" + str(mu_1) + \", \" + str(mu_2))\n        print()\n\n    result = {\n        \"p_value\": p,\n        \"t_value\": t,\n        \"con_low\": con_1,\n        \"con_up\": con_2,\n        \"sample_mean_1\": mu_1,\n        \"sample_mean_2\": mu_2,\n        \"accept\": accept,\n    }\n    return result\n\n\n# Input parameters: sample (pd df), population mean (float), significance level (optional float)\n# Return values: p-value, z-value, confidence interval (lower), confidence interval (upper), mean of sample, reject/accept (1 = accept, 0 = reject)\ndef z_test_1_samp(x, pop_mean, sig_lvl=0.05):\n\n    out = 0\n\n    if out:\n        print(\"1 sample z-test (two-tailed)\")\n\n    samp_mu = float(x.mean())\n    pop_std = float(x.std())\n    n = float(x.shape[0])\n\n    z = float((samp_mu - pop_mean) / (pop_std / pow(n, 0.5)))\n    p = scipy.stats.norm.sf(abs(z)) * 2\n\n    if out:\n        print(\"z: \" + str(z))\n        print(\"p-value: \" + str(p))\n\n    accept = 1\n    if p > sig_lvl:\n        if out:\n            print(\n                \"Alternative hypothesis: the sample mean and population means are NOT equal\"\n            )\n        accept = 0\n    else:\n        if out:\n            print(\"Null hypothesis: the sample mean and population means are equal\")\n\n    con_1 = float(\n        samp_mu - scipy.stats.norm.ppf(1 - sig_lvl / 2) * pop_std / pow(n, 0.5)\n    )\n    con_2 = float(\n        samp_mu + scipy.stats.norm.ppf(1 - sig_lvl / 2) * pop_std / pow(n, 0.5)\n    )\n\n    if out:\n        print(\n            str(100 * (1 - sig_lvl))\n            + \"% confidence interval: \"\n            + str(con_1)\n            + \" \"\n            + str(con_2)\n        )\n        print(\"Mean of x: \" + str(samp_mu))\n        print()\n\n    result = {\n        \"p_value\": p,\n        \"z_value\": z,\n        \"con_low\": con_1,\n        \"con_up\": con_2,\n        \"sample_mean_1\": samp_mu,\n        \"accept\": accept,\n    }\n    return result\n\n\n# Input parameters: sample 1 (pd df), sample 2 (pd df), significance level (optional float)\n# Return values: p-value, z-value, confidence interval (lower), confidence interval (upper), mean of sample 1, mean of sample 2, reject/accept (1 = accept, 0 = reject)\ndef z_test_2_samp(x, y, sig_lvl=0.05):\n\n    out = 0\n\n    if out:\n        print(\"2 sample z-test (two tailed)\")\n\n    mu_1 = float(x.mean())\n    mu_2 = float(y.mean())\n    std_1 = float(x.std())\n    std_2 = float(y.std())\n    n1 = x.shape[0]\n    n2 = y.shape[0]\n\n    z = (mu_1 - mu_2) / pow((std_1 ** 2 / n1 + std_2 ** 2 / n2), 0.5)\n    p = scipy.stats.norm.sf(abs(z)) * 2\n\n    if out:\n        print(\"z: \" + str(z))\n        print(\"p-value: \" + str(p))\n\n    accept = 1\n    if p > sig_lvl:\n        if out:\n            print(\"Alternative hypothesis: the population means are NOT equal\")\n        accept = 0\n    else:\n        if out:\n            print(\"Null hypothesis: the population means are equal\")\n\n    con_1 = float(\n        (mu_1 - mu_2)\n        - (\n            scipy.stats.norm.ppf((1 - sig_lvl / 2))\n            * pow(\n                (\n                    (((n1 - 1) * std_1 * std_1) + ((n2 - 1) * std_2 * std_2))\n                    / (n1 + n2 - 2)\n                ),\n                0.5,\n            )\n            * pow((1 / n1 + 1 / n2), 0.5)\n        )\n    )\n    con_2 = float(\n        (mu_1 - mu_2)\n        + (\n            scipy.stats.norm.ppf((1 - sig_lvl / 2))\n            * pow(\n                (\n                    (((n1 - 1) * std_1 * std_1) + ((n2 - 1) * std_2 * std_2))\n                    / (n1 + n2 - 2)\n                ),\n                0.5,\n            )\n            * pow((1 / n1 + 1 / n2), 0.5)\n        )\n    )\n\n    if out:\n        print(\n            str(100 * (1 - sig_lvl))\n            + \"% confidence interval: \"\n            + str(con_1)\n            + \" \"\n            + str(con_2)\n        )\n        print(\"Mean of x and mean of y (respectively): \" + str(mu_1) + \", \" + str(mu_2))\n        print()\n\n    result = {\n        \"p_value\": p,\n        \"z_value\": z,\n        \"con_low\": con_1,\n        \"con_up\": con_2,\n        \"sample_mean_1\": mu_1,\n        \"sample_mean_2\": mu_2,\n        \"accept\": accept,\n    }\n    return result\n\n\n# Input parameters: pd df of group categoricals, pd df of corresponding values, significance level (optional)\n# Return values: p-value, f-value, variance between, var within, degrees of freedom between, df within, df total, Sum of Squares between, ss within, ss total, accept (1 = accept, 0 = reject)\ndef one_way_anova(dictionary, sig_lvl=0.05):\n\n    out = 0\n\n    if out:\n        print(\"One way ANOVA\")\n        \n    cat_val = \"\"\n    num_val = \"\"\n\n    if \"cat_NaN_found\" in dictionary:\n        cat_val = dictionary.pop(\"cat_NaN_found\")\n    if 'num_NaN_found' in dictionary:\n        num_val = dictionary.pop(\"num_NaN_found\")\n    sep_values = [list(value) for key, value in dictionary.items()]\n    f, p = f_oneway(*sep_values)\n\n    if out:\n        print(f, p)\n\n    unique_groups = pd.DataFrame(list(dictionary.keys()))\n    k = unique_groups.shape[0]\n    n = sum([len(value) for key, value in dictionary.items()])\n    df_between = k - 1\n    df_within = n - k\n    df_total = n - 1\n\n    grand_mean = sum([item for sublist in sep_values for item in sublist]) / n\n    total = 0\n    for i in range(len(sep_values)):\n        group_mean = 0\n        for j in range(len(sep_values[i])):\n            group_mean = group_mean + sep_values[i][j]\n        group_mean = group_mean / len(sep_values[i])\n        total = total + (grand_mean - group_mean) ** 2 * len(sep_values[i])\n    total2 = 0\n    for i in range(len(sep_values)):\n        gm = 0\n        for j in range(len(sep_values[i])):\n            gm = gm + sep_values[i][j]\n        gm = gm / len(sep_values[i])\n        for j in range(len(sep_values[i])):\n            total2 = total2 + (sep_values[i][j] - gm) ** 2\n\n    ss_between = float(total)\n    ss_within = float(total2)\n    ss_total = float(total + total2)\n    var_between = float(total / df_between)\n    var_within = float(total2 / df_within)\n\n    row_headers = [\"Sum of Squares\", \"d.f.\", \"Variance\", \"F\", \"p\"]\n    col_headers = [\"Between Groups\", \"Within Groups\", \"Total\"]\n    data = [\n        [\n            str(\"%.2f\" % ss_between),\n            str(\"%.0f\" % df_between),\n            str(\"%.2f\" % var_between),\n            str(\"%.6f\" % f),\n            str(\"%.6f\" % p),\n        ],\n        [\n            str(\"%.2f\" % ss_within),\n            str(\"%.0f\" % df_within),\n            str(\"%.2f\" % var_within),\n            \"--\",\n            \"--\",\n        ],\n        [str(\"%.2f\" % ss_total), str(\"%.0f\" % df_total), \"--\", \"--\", \"--\"],\n    ]\n\n    if out:\n        print(pd.DataFrame(data, col_headers, row_headers))\n\n    accept = 1\n    if p > sig_lvl:\n        if out:\n            print(\"Alternative hypothesis: true difference in means is not equal to 0\")\n        accept = 0\n    else:\n        if out:\n            print(\"Null hypothesis: true difference in means is equal to 0\")\n\n    if out:\n        print()\n\n    result = {\n        \"p_value\": p,\n        \"f_value\": f,\n        \"var_between\": var_between,\n        \"var_within\": var_within,\n        \"df_between\": df_between,\n        \"df_within\": df_within,\n        \"df_total\": df_total,\n        \"ss_between\": ss_between,\n        \"ss_within\": ss_within,\n        \"ss_total\": ss_total,\n        \"accept\": accept,\n    }\n    dictionary[\"cat_NaN_found\"] = cat_val\n    dictionary[\"num_NaN_found\"] = num_val\n    return result\n\n\nif __name__ == \"__main__\":\n\n    ### Testing ###\n    x = pd.DataFrame([1, 40, 60, 110])\n    y = pd.DataFrame([5, 6, 7, 8])\n    groups = pd.DataFrame([\"A\", \"A\", \"A\", \"A\", \"B\", \"B\", \"B\", \"B\", \"C\", \"C\", \"C\", \"C\"])\n    values = pd.DataFrame([1, 2, 3, 4, 4, 6, 5, 9, 12, 12, 1, 11])\n    dictio = {\n        \"A\": [1.0, 2.0, 3.0, 4.0],\n        \"B\": [4.0, 6.0, 5.0, 9.0],\n        \"C\": [12.0, 12.0, 1.0, 11.0],\n        \"cat_NaN_found\": False,\n        \"num_NaN_found\": False,\n    }\n\n    # T tests\n    t_test_1_samp(x, 3)\n    t_test_2_samp_equal_var(x, y)\n    t_test_welch(x, y)\n\n    # Z tests\n    z_test_1_samp(x, 50)\n    z_test_2_samp(x, y)\n\n    # ANOVA\n    print(one_way_anova(dictio))\n", "meta": {"hexsha": "7bb84979e19b541cb751b8e278f32ce8689fd8a6", "size": 13428, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/backend/hypothesis_tests.py", "max_stars_repo_name": "hbaghar/statistics-for-dummies", "max_stars_repo_head_hexsha": "86f1525e06587c7e668956bc14942e757839a5d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-01T19:25:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T19:25:50.000Z", "max_issues_repo_path": "src/backend/hypothesis_tests.py", "max_issues_repo_name": "hbaghar/statistics-for-dummies", "max_issues_repo_head_hexsha": "86f1525e06587c7e668956bc14942e757839a5d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2022-03-01T23:57:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:20:19.000Z", "max_forks_repo_path": "src/backend/hypothesis_tests.py", "max_forks_repo_name": "hbaghar/statistics-for-dummies", "max_forks_repo_head_hexsha": "86f1525e06587c7e668956bc14942e757839a5d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-22T19:35:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T19:35:23.000Z", "avg_line_length": 27.6296296296, "max_line_length": 190, "alphanum_fraction": 0.4977658624, "include": true, "reason": "import scipy,from scipy", "num_tokens": 4164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307676766119, "lm_q2_score": 0.8774767922879693, "lm_q1q2_score": 0.853636421459916}}
{"text": "import os, sys\nsys.path.insert(0, os.path.join(os.pardir, 'src-vib'))\nfrom vib_undamped import solver, u_exact, visualize\nimport numpy as np\n\ndef convergence_rates(m, solver_function, num_periods=8):\n    \"\"\"\n    Return m-1 empirical estimates of the convergence rate\n    based on m simulations, where the time step is halved\n    for each simulation.\n    solver_function(I, w, dt, T) solves each problem, where T\n    is based on simulation for num_periods periods.\n    \"\"\"\n    from math import pi\n    w = 0.35; I = 0.3       # just chosen values\n    P = 2*pi/w              # period\n    dt = P/30               # 30 time step per period 2*pi/w\n    T = P*num_periods\n    energy_const = 0.5*I**2*w**2    # initial energy when V = 0\n\n    dt_values = []\n    E_u_values = []         # error in u\n    E_energy_values = []    # error in energy\n    for i in range(m):\n        u, t = solver_function(I, w, dt, T)\n        u_e = u_exact(t, I, w)\n        E_u = np.sqrt(dt*np.sum((u_e-u)**2))\n        E_u_values.append(E_u)\n        energy = 0.5*((u[2:] - u[:-2])/(2*dt))**2 + \\\n                                    0.5*w**2*u[1:-1]**2\n        E_energy = energy - energy_const\n        E_energy_norm = np.abs(E_energy).max()\n        E_energy_values.append(E_energy_norm)\n        dt_values.append(dt)\n        dt = dt/2\n\n    r_u = [np.log(E_u_values[i-1]/E_u_values[i])/\n         np.log(dt_values[i-1]/dt_values[i])\n         for i in range(1, m, 1)]\n    r_E = [np.log(E_energy_values[i-1]/E_energy_values[i])/\n         np.log(dt_values[i-1]/dt_values[i])\n         for i in range(1, m, 1)]\n    return r_u, r_E\n\ndef test_convergence_rates():\n    r_u, r_E = convergence_rates(\n        m=5,\n        solver_function=solver,\n        num_periods=8)\n    # Accept rate to 1 decimal place\n    tol = 0.1\n    assert abs(r_u[-1] - 2.0) < tol\n    assert abs(r_E[-1] - 2.0) < tol\n\nif __name__ == '__main__':\n    test_convergence_rates()\n", "meta": {"hexsha": "aa62fd54ef63e7ea9fb8ad239253af8466fce167", "size": 1903, "ext": "py", "lang": "Python", "max_stars_repo_path": "fdm-devito-notebooks/01_vib/exer-vib/test_error_conv.py", "max_stars_repo_name": "devitocodes/devito_book", "max_stars_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-07-17T13:19:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-27T05:21:09.000Z", "max_issues_repo_path": "fdm-jupyter-book/notebooks/01_vib/exer-vib/test_error_conv.py", "max_issues_repo_name": "devitocodes/devito_book", "max_issues_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 73, "max_issues_repo_issues_event_min_datetime": "2020-07-14T15:38:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-25T11:54:59.000Z", "max_forks_repo_path": "fdm-jupyter-book/notebooks/01_vib/exer-vib/test_error_conv.py", "max_forks_repo_name": "devitocodes/devito_book", "max_forks_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-27T05:21:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T05:21:14.000Z", "avg_line_length": 33.3859649123, "max_line_length": 63, "alphanum_fraction": 0.5796111403, "include": true, "reason": "import numpy", "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.9099069968764883, "lm_q1q2_score": 0.8536056045279161}}
{"text": "import numpy\nimport matplotlib.pyplot as pyplot\nimport os\nimport shutil\n\nanimation_dir = \"animation\"\n\n\"\"\"notes on things tried\n* increased L to 200.0, Nx to 2000 - movement of wavepacket was slower\n* increased L to 1000.0, Nx to 10000 - movement of wavepacket stopped\n\"\"\"\n\n#periodic unit size\nL = 100.0\nprint \"L:  {}\".format(L)\n\nNx = 1000\nprint \"Nx:  {}\".format(Nx)\ndx = L / float(Nx)\nprint \"dx:  {}\".format(dx)\nx = numpy.array(range(Nx)) * dx\nprint \"x[:10]:\\n{}\".format(x[:10])\n\nduration = 1599*2\nNt = duration/2\ndt = duration / float(Nt)\nt = numpy.array(range(Nt)) * dt\n\n#spatial wavefunction is exp(ikx)*sqrt(1/L)\n#k = 2*pi*n/L\n#n is integer positive or negative\n#https://en.wikipedia.org/wiki/Particle_in_a_one-dimensional_lattice\n\n#energy E = hbar^2 * k^2 / (2m)\n#https://en.wikipedia.org/wiki/Particle_in_a_box\n#in atomic units:  E = k^2 / 2\n#(use mass of an electron)\n#https://en.wikipedia.org/wiki/Atomic_units\n\n#time wavefunction is exp(-iEt/hbar)\n#atomic units:  exp(-iEt)\n#http://hyperphysics.phy-astr.gsu.edu/hbase/quantum/Scheq.html\n\ndef calculate_wavefunction(state_indexes, state_coefs, periodic_length, x):\n    psi = numpy.zeros(x.shape)\n    for (i, si) in enumerate(state_indexes):\n        k = 2 * numpy.pi * float(si) / periodic_length\n        phi = numpy.exp(1j*k*(x - periodic_length/2.0)) * numpy.sqrt(1.0 / periodic_length)\n\n        sc = state_coefs[i]\n        psi = psi + sc*phi\n\n    return psi\n\ndef test_calculate_wavefunction():\n    print \"test_calculate_wavefunction\"\n\n    all_psi = []\n\n    psi = calculate_wavefunction(numpy.array([1]), numpy.array([1]), L, x)\n    all_psi.append(psi)\n    print \"psi[:10]:\\n{}\".format(psi[:10])\n    test_integral = numpy.vdot(psi, psi.T) * dx\n    print \"test_integral:  {}\".format(test_integral)\n    pyplot.figure(101)\n    pyplot.plot(x, numpy.real(psi))\n    pyplot.plot(x, numpy.imag(psi))\n    pyplot.title(\"test_calculate_wavefunction01\")\n    pyplot.savefig(\"test_calculate_wavefunction01.png\")\n\n    psi = calculate_wavefunction(numpy.array([2]), numpy.array([1]), L, x)\n    all_psi.append(psi)\n    print \"psi[:10]:\\n{}\".format(psi[:10])\n    test_integral = numpy.vdot(psi, psi.T) * dx\n    print \"test_integral:  {}\".format(test_integral)\n    pyplot.figure(102)\n    pyplot.plot(x, numpy.real(psi))\n    pyplot.plot(x, numpy.imag(psi))\n    pyplot.title(\"test_calculate_wavefunction02\")\n    pyplot.savefig(\"test_calculate_wavefunction02.png\")\n\n    psi = calculate_wavefunction(numpy.array([1, 2]), numpy.array([0.70710678, 0.70710678]), L, x)\n    all_psi.append(psi)\n    print \"psi[:10]:\\n{}\".format(psi[:10])\n    test_integral = numpy.vdot(psi, psi.T) * dx\n    print \"test_integral:  {}\".format(test_integral)\n    pyplot.figure(103)\n    pyplot.plot(x, numpy.real(psi))\n    pyplot.plot(x, numpy.imag(psi))\n    pyplot.title(\"test_calculate_wavefunction03\")\n    pyplot.savefig(\"test_calculate_wavefunction03.png\")\n\n    pyplot.figure(104)\n    for psi in all_psi:\n        pyplot.plot(x, numpy.real(psi))\n    pyplot.title(\"test_calculate_wavefunction04\")\n    pyplot.savefig(\"test_calculate_wavefunction04.png\")\n    pyplot.figure(105)\n    for psi in all_psi:\n        pyplot.plot(x, numpy.imag(psi))\n    pyplot.title(\"test_calculate_wavefunction05\")\n    pyplot.savefig(\"test_calculate_wavefunction05.png\")\n\nstate_indexes = numpy.array(range(1,21))\n\nstate_coefs = numpy.exp(-numpy.power(state_indexes - 10, 2) / 2.0)\nnorm = numpy.sqrt(numpy.sum(numpy.power(state_coefs, 2)))\nprint \"normalization for state_coefs - norm:  {}\".format(norm)\nstate_coefs = state_coefs / norm\nprint \"check normalization of state_coefs:  {}\".format(numpy.sum(numpy.power(state_coefs, 2)))\nprint \"state_coefs:\\n{}\".format(state_coefs)\n\ninitial_psi = calculate_wavefunction(state_indexes, state_coefs, L, x)\ninitial_prob_dens = numpy.conj(initial_psi) * initial_psi\n\nstate_wavenumbers = 2.0 * numpy.pi * state_indexes / L\nstate_energies = numpy.power(state_wavenumbers, 2.0) / 2.0\n\ntime_psi = []\ntime_prob_dens = []\nfor cur_t in t[:]:\n    time_modifiers = numpy.exp(-1j * state_energies * cur_t)\n    # print \"time_modifiers:\\n{}\".format(time_modifiers)\n    # print numpy.vdot(time_modifiers, time_modifiers.T)\n\n    cur_state_coefs = state_coefs * time_modifiers\n\n    psi = calculate_wavefunction(state_indexes, cur_state_coefs, L, x)\n    time_psi.append(psi)\n\n    prob_dens = numpy.conj(psi) * psi\n    # print \"cur_t:  {}  prob_dens normalization check:  {}\".format(cur_t, numpy.sum(prob_dens) * dx)\n    time_prob_dens.append(prob_dens)\n\n\nfig_ind=1\npyplot.figure(fig_ind)\npyplot.plot(state_indexes, state_coefs, marker=\".\")\npyplot.xlabel(\"state_indexes\")\npyplot.ylabel(\"state_coefs\")\npyplot.savefig(\"state_coefs.png\")\n\nif False:\n    test_calculate_wavefunction()\n\nfig_ind = fig_ind+1\npyplot.figure(fig_ind)\npyplot.plot(x, numpy.real(initial_psi))\npyplot.plot(x, numpy.imag(initial_psi))\npyplot.xlabel(\"x\")\npyplot.ylabel(\"initial_psi\")\npyplot.savefig(\"initial_psi.png\")\nfig_ind = fig_ind+1\npyplot.figure(fig_ind)\npyplot.plot(x, numpy.real(initial_prob_dens))\npyplot.plot(x, numpy.imag(initial_prob_dens))\npyplot.xlabel(\"x\")\npyplot.ylabel(\"initial_prob_dens\")\npyplot.savefig(\"initial_prob_dens.png\")\n\nif os.path.exists(\"animation\"):\n    shutil.rmtree(\"animation\")\nos.mkdir(\"animation\")\n\ninitial_file_ind = 150\nfig_ind = fig_ind+1\n\nif True:\n    for (i, psi) in enumerate(time_psi):\n        file_index = \"%05d\" % (i + initial_file_ind)\n        cur_t = t[i]\n\n        if False:\n            pyplot.figure(fig_ind)\n            pyplot.plot(x, numpy.real(psi))\n            pyplot.plot(x, numpy.imag(psi))\n            pyplot.xlabel(\"x\")\n            pyplot.ylabel(\"psi\")\n            pyplot.title(\"psi at i:  {}  time:  {}\".format(i, cur_t))\n\n            filename = os.path.join(animation_dir, \"psi{}.png\".format(file_index))\n            pyplot.savefig(filename)\n            pyplot.close(fig_ind)\n\n            pyplot.figure(fig_ind)\n            pyplot.plot(x, numpy.real(time_prob_dens[i]))\n            pyplot.xlabel(\"x\")\n            pyplot.ylabel(\"prob_dens\")\n            pyplot.title(\"prob_dens at i:  {}  time:  {}\".format(i, cur_t))\n\n            filename = os.path.join(animation_dir, \"prob_dens{}.png\".format(file_index))\n            pyplot.savefig(filename)\n            pyplot.close(fig_ind)\n\n        pyplot.figure(fig_ind)\n        fig, ax1 = pyplot.subplots()\n        pd_line = ax1.plot(x, numpy.real(time_prob_dens[i]), label=\"prob_dens\")\n        ax1.set_xlabel(\"x\")\n        ax1.set_ylabel(\"prob_dens\")\n        ax1.set_ylim(-0.001, 0.0375)\n\n        pyplot.title(\"prob_dens and psi at index i:  {}  time:  {}\".format(i, cur_t))\n        ax2 = ax1.twinx()\n        rp_line = ax2.plot(x, numpy.real(psi), \"purple\", label=\"real(psi)\", lw=0.5)\n        ip_line = ax2.plot(x, numpy.imag(psi), \"orange\", label=\"imag(psi)\", lw=0.5)\n        ax2.set_ylim(-0.21, 0.21)\n        ax2.set_ylabel(\"wavefunction psi\")\n\n        h, l = ax1.get_legend_handles_labels()\n        all_h = list(h)\n        all_l = list(l)\n        h, l = ax2.get_legend_handles_labels()\n        all_h.extend(h)\n        all_l.extend(l)\n        pyplot.legend(handles = all_h)\n        fig.tight_layout()\n\n        filename = os.path.join(animation_dir, \"combined{}.png\".format(file_index))\n        pyplot.savefig(filename)\n        pyplot.close(fig_ind)\n\n        if i%10 == 0:\n            print \"animation figures progress i:  {}\".format(i)\n\n\n\nfor i in [0, len(time_psi)-1]:\n    psi = time_psi[i]\n    cur_t = t[i]\n    tpd = numpy.real(time_prob_dens[i])\n    max_ind = numpy.argmax(tpd)\n    max_val = tpd[max_ind]\n    half_max = max_val / 2.0\n    left_half_max_x = numpy.interp(half_max, tpd[:max_ind], x[:max_ind])\n    right_half_max_x = numpy.interp(half_max, tpd[-1:max_ind:-1], x[-1:max_ind:-1])\n\n    pyplot.figure(fig_ind)\n    fig, ax1 = pyplot.subplots()\n    pd_line = ax1.plot(x, tpd, label=\"prob_dens\")\n    ax1.set_xlabel(\"x\")\n    ax1.set_ylabel(\"prob_dens\")\n    ax1.set_ylim(-0.001, 0.0375)\n    ax1.plot([left_half_max_x, left_half_max_x], [half_max, max_val*1.05])\n    ax1.plot([right_half_max_x, right_half_max_x], [half_max, max_val*1.05])\n\n    pyplot.title(\"prob_dens at index i:  {}  time:  {}\".format(i, cur_t))\n\n    ax2 = ax1.twinx()\n    rp_line = ax2.plot(x, numpy.real(psi), \"purple\", label=\"real(psi)\", lw=0.25)\n    ip_line = ax2.plot(x, numpy.imag(psi), \"orange\", label=\"imag(psi)\", lw=0.25)\n    ax2.set_ylim(-0.21, 0.21)\n    ax2.set_ylabel(\"wavefunction psi\")\n\n    h, l = ax1.get_legend_handles_labels()\n    all_h = list(h)\n    all_l = list(l)\n    h, l = ax2.get_legend_handles_labels()\n    all_h.extend(h)\n    all_l.extend(l)\n    pyplot.legend(handles = all_h)\n    pyplot.text(15, 0.175, \"initial width:\\n{}\".format(\"%.2f\"%(right_half_max_x-left_half_max_x)))\n    fig.tight_layout()\n\n    file_int = 0 if i == 0 else i+1+initial_file_ind\n    file_index = \"%05d\" % file_int\n    source_filename = \"combined{}.png\".format(file_index)\n    pyplot.savefig(os.path.join(animation_dir, source_filename))\n    pyplot.close(fig_ind)\n\n    for j in xrange(1, initial_file_ind):\n        file_index = \"%05d\" % (j + file_int)\n        print file_index\n        filename = os.path.join(animation_dir, \"combined{}.png\".format(file_index))\n        os.symlink(source_filename, filename)\n", "meta": {"hexsha": "3b037b2b1a28aabd13c58d6f91956823c24b5b74", "size": 9155, "ext": "py", "lang": "Python", "max_stars_repo_path": "quantum_wavepacket/quantum_wavepacket/periodic_boundary_condition_1D/calculations/01_periodic_boundary_condition_1D.py", "max_stars_repo_name": "dllahr/projects", "max_stars_repo_head_hexsha": "0d40e9a974d82aeca940542044bb32eb24192e66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quantum_wavepacket/quantum_wavepacket/periodic_boundary_condition_1D/calculations/01_periodic_boundary_condition_1D.py", "max_issues_repo_name": "dllahr/projects", "max_issues_repo_head_hexsha": "0d40e9a974d82aeca940542044bb32eb24192e66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quantum_wavepacket/quantum_wavepacket/periodic_boundary_condition_1D/calculations/01_periodic_boundary_condition_1D.py", "max_forks_repo_name": "dllahr/projects", "max_forks_repo_head_hexsha": "0d40e9a974d82aeca940542044bb32eb24192e66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-21T20:36:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-21T20:36:23.000Z", "avg_line_length": 33.2909090909, "max_line_length": 101, "alphanum_fraction": 0.6648825778, "include": true, "reason": "import numpy", "num_tokens": 2603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660936744719, "lm_q2_score": 0.8947894611926921, "lm_q1q2_score": 0.853598806955078}}
{"text": "\n# coding: utf-8\n\n# # Statistical parameters using probability density function\n# ### Given probability density function, $p(x)$\n# \n# $ p = 2x/b^2$, $0 < x < b$\n# \n# ### The mean value of $x$ is estimated analytically:\n# $\\overline{x} = \\int\\limits_0^b x\\, p(x)\\, dx = \\int\\limits_0^b 2x^2/b^2 = \\left. 2x^3/3b^2\\right|_0^b =2b^3/3b^2 = 2b/3$\n# \n# \n# ### the median\n# median: $ \\int\\limits_0^m p(x)\\,dx = 1/2 = \\int\\limits_0^m 2x/b^2\\,dx = \\left. x^2/b^2 \\right|_0^m = m^2/b^2 = 1/2$, $m = b/\\sqrt(2)$\n# \n# ### the second moment\n# second moment: $x^{(2)} = \\int\\limits_0^b x^2\\, p(x)\\, dx = \\int\\limits_0^b 2x^3/b^2 = \\left. x^4/2b^2\\right|_0^b =b^4/2b^2 = b^2/2$\n# \n# ### the variance is the second moment less the squared mean value\n# $var(x) = x^{(2)} - \\overline{x}^2 = b^2/2 - 4b^2/9 = b^2/18$\n# \n# \n\n# In[42]:\n\ndef p(x,b):\n    return 2*x/(b**2)\n\n\n# In[59]:\n\nb = 2\nx = linspace(0,b,200)\ny = p(x,b) \n\n\n# In[63]:\n\nplot(x,y)\nxlabel('$x$')\nylabel('$p(x)$')\n\n\n# In[61]:\n\n# approximate using the numerical integration\nprint trapz(y*x,x)\nprint 2.*b/3\n\n\n# In[62]:\n\nprint trapz(y*x**2,x)\nprint b^2/18\n\n\n# In[64]:\n\nimport sympy\n\n\n# In[113]:\n\nsympy.var('x,b,p,m')\np = 2*x/b**2\nprint p\n\n\n# In[114]:\n\nsympy.integrate(p*x,(x,0,b))\n\n\n# In[115]:\n\nsympy.integrate(p*x**2,(x,0,b))\n\n\n# In[119]:\n\nsympy.integrate(p,(x,0,m))\n\n\n# In[124]:\n\nsympy.solve(m**2/b**2 - 0.5,m)\n\n\n# In[ ]:\n\n\n\n", "meta": {"hexsha": "0514dbddfdb71a2ebf96228ae6c22df2dcba660f", "size": 1368, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/mean_variance_probability_function.py", "max_stars_repo_name": "alexlib/engineering_experiments_measurements_course", "max_stars_repo_head_hexsha": "0b80d90519a2a72547ffd9ef4da2158530016196", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-05-03T09:41:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T12:39:27.000Z", "max_issues_repo_path": "scripts/mean_variance_probability_function.py", "max_issues_repo_name": "alexlib/engineering_experiments_measurements_course", "max_issues_repo_head_hexsha": "0b80d90519a2a72547ffd9ef4da2158530016196", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-04-22T09:04:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-22T09:04:13.000Z", "max_forks_repo_path": "scripts/mean_variance_probability_function.py", "max_forks_repo_name": "alexlib/engineering_experiments_measurements_course", "max_forks_repo_head_hexsha": "0b80d90519a2a72547ffd9ef4da2158530016196", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-07-02T11:39:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-03T15:49:42.000Z", "avg_line_length": 14.7096774194, "max_line_length": 135, "alphanum_fraction": 0.5533625731, "include": true, "reason": "import sympy", "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.9073122301325987, "lm_q1q2_score": 0.8535900484983072}}
{"text": "1#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom scipy import sparse\nfrom scipy.sparse import linalg\nimport matplotlib.pyplot as plt\nnp.set_printoptions(threshold=np.nan)\nnp.set_printoptions(precision=5)\n\n#  Solves the steady-state heat equation in a square with conductivity\n#  c(x,y) = 1 + x^2 + y^2:\n#\n#     -d/dx( (1+x^2+y^2) du/dx ) - d/dy( (1+x^2+y^2) du/dy ) = f(x),   \n#                                                       0 < x,y < 1\n#     u(x,0) = u(x,1) = u(0,y) = u(1,y) = 0\n#\n#  Uses a centered finite difference method.\n\n# return A and b to solve steady state heat equation    \ndef Ab(n):\n    #  Set up grid.\n    #n = int(input(' Enter number of subintervals in each direction: '));\n    h = 1/n\n    N = (n-1)**2\n\n    # Form block tridiagonal finite difference matrix A and right-hand side \n    # vector b.\n    A = sparse.csr_matrix((N,N));\n    b = np.ones((N,1));         # Use right-hand side vector of all 1's.\n\n    # Loop over grid points in y direction.\n    for j in range (n-1):\n        yj = (j+1)*h\n        yjph = yj+h/2;  yjmh = yj-h/2\n    \n        # Loop over grid points in x direction.\n        for i in range(n-1):\n            xi = (i+1)*h\n            xiph = xi+h/2;  ximh = xi-h/2\n            aiphj = 1 + xiph**2 + yj**2\n            aimhj = 1 + ximh**2 + yj**2\n            aijph = 1 + xi**2 + yjph**2\n            aijmh = 1 + xi**2 + yjmh**2\n            k = (j)*(n-1) + i\n            A[k,k] = aiphj+aimhj+aijph+aijmh\n            if i > 0: A[k,k-1] = -aimhj\n            if i < n-2: A[k,k+1] = -aiphj\n            if j > 0: A[k,k-(n-1)] = -aijmh\n            if j < n-2: A[k,k+(n-1)] = -aijph\n    \n    return (A/h**2,b)   # Remember to multiply A by (1/h^2).\n\n#n = int(input(' Enter number of subintervals in each direction: '));\ndef direct_solve():\n    n = 8\n    A,b = Ab(n)\n    \n    # Solve linear system.\n    u_comp = sparse.linalg.spsolve(A,b)\n\n#<startJacobi>\ndef jacobi(A,b,tol,max_iter=20):\n    n = np.shape(A)[1]\n    x = sparse.csc_matrix((n,1))\n    \n    M = sparse.diags(A.diagonal(), format='csc')\n\n    residual_norm=np.zeros(max_iter)\n    iter_tol = -1\n    for iter in range(max_iter):\n        residual = b-A.dot(x)\n        x += sparse.linalg.spsolve_triangular(M,residual)\n        residual_norm[iter] = np.linalg.norm(residual)/np.linalg.norm(b)\n        if residual_norm[iter] < tol: \n            iter_tol = iter\n            break\n\n    return (x,residual_norm,iter_tol)      \n#<endJacobi>\n\n#<startGS>\ndef gauss_seidel(A,b,tol,max_iter=20):\n    n = np.shape(A)[1]\n    x = sparse.csc_matrix((n,1))\n    \n    M = sparse.tril(A,0, format='csc')\n\n    residual_norm=np.zeros(max_iter)\n    iter_tol = -1\n    for iter in range(max_iter):\n        residual = b-A.dot(x)\n        x += sparse.linalg.spsolve_triangular(M,residual)\n        residual_norm[iter] = np.linalg.norm(residual)/np.linalg.norm(b)\n        if residual_norm[iter] < tol: \n            iter_tol = iter\n            break\n\n    return (x,residual_norm,iter_tol)      \n#<endGS>\n    \n#<startSOR>\ndef SOR(A,b,w,tol,max_iter=20,opt=False):\n    n = np.shape(A)[1]\n    x = sparse.csc_matrix((n,1))\n    \n    D = sparse.diags(A.diagonal(), format='csc')\n    L = sparse.tril(A,-1, format='csc')\n    M = D/w+L\n\n    if opt:\n        G = sparse.eye(n) - sparse.diags(1/A.diagonal(),format='csc').dot(A)\n        p = np.linalg.norm(sparse.linalg.eigs(G,1,which='LM')[0])\n        w = 2/(1+np.sqrt(1-p**2))\n        print(w)\n    residual_norm=np.zeros(max_iter)\n    \n    iter_tol = -1\n    for iter in range(max_iter):\n        residual = b-A.dot(x)\n        x += sparse.linalg.spsolve_triangular(M,residual)\n        residual_norm[iter] = np.linalg.norm(residual)/np.linalg.norm(b)\n        if residual_norm[iter] < tol: \n            iter_tol = iter\n            break\n\n    return (x,residual_norm,iter_tol)\n#<endSOR>\n\ndef tests():\n    n = 20\n    A,b = Ab(n)\n\n    max_iter = 175\n    tol = 1e-15\n    res_jacobi = jacobi(A,b,tol,max_iter)\n    res_GS = gauss_seidel(A,b,tol,max_iter)\n    res_SOR3 = SOR(A,b,1.3,tol,max_iter)\n    res_SOR5 = SOR(A,b,1.5,tol,max_iter)\n    res_SOR7 = SOR(A,b,1.7,tol,max_iter)\n#    res_SOR_opt = SOR(A,b,1,tol,max_iter,opt=True)\n    \n    plt.yscale('log')\n    plt.plot(range(len(res_jacobi[1])),res_jacobi[1])\n    plt.plot(range(len(res_GS[1])),res_GS[1])\n    plt.plot(range(len(res_SOR3[1])),res_SOR3[1])\n    plt.plot(range(len(res_SOR5[1])),res_SOR5[1])\n    plt.plot(range(len(res_SOR7[1])),res_SOR7[1])\n#    plt.plot(range(len(res_SOR_opt[1])),res_SOR_opt[1])\n    plt.savefig('img/1/iter_convergence_'+str(n)+'.pdf')\n\n\n\ndef CG_tests():\n    n = 20\n    A,b = Ab(n)\n    residual_CG_ichol = []\n    residual_CG = []\n   \n    def CG_callback(x):\n        nonlocal residual_CG\n        residual_CG = np.append(residual_CG,np.linalg.norm(b-A.dot(x))/np.linalg.norm(b))\n    \n    def CG_callback_ichol(x):\n        nonlocal residual_CG_ichol\n        residual_CG_ichol = np.append(residual_CG_ichol,np.linalg.norm(b-A.dot(x))/np.linalg.norm(b))\n    \n    max_iter = 300\n        \n    tol = 1e-15\n    N = (n-1)**2\n    \n#<startCG>\n    lu = sparse.linalg.spilu(A,drop_tol = 1e-3)\n    M = lu.solve(np.identity(N))\n#<endCG>\n    \n    sparse.linalg.cg(A,b,x0=np.zeros((n-1)**2),tol=tol,maxiter=max_iter,callback=CG_callback)\n    sparse.linalg.cg(A,b,x0=np.zeros((n-1)**2),tol=tol,maxiter=max_iter,M=M,callback=CG_callback_ichol)\n\n    plt.yscale('log')\n    plt.plot(range(len(residual_CG)),residual_CG)\n    plt.plot(range(len(residual_CG_ichol)),residual_CG_ichol)\n    plt.savefig('img/1/cg_convergence_'+str(n)+'.pdf')\n    \ndef iter_vs_h():\n    iterj = []\n    iter0 = []\n    iter3 = []\n    iter5 = []\n    iter7 = []\n    h = []\n    tol = 1e-5\n    max_iter = 2000\n    \n    for n in [3,4,5,7,10,14,20,30]:\n        A,b = Ab(n)\n        h = np.append(h,1/(n+1))\n        iterj = np.append(iterj,jacobi(A,b,tol,max_iter=max_iter)[2])\n        iter0 = np.append(iter0,SOR(A,b,1,tol,max_iter=max_iter)[2])\n        iter3 = np.append(iter3,SOR(A,b,1.3,tol,max_iter=max_iter)[2])\n        iter5 = np.append(iter5,SOR(A,b,1.5,tol,max_iter=max_iter)[2])\n        iter7 = np.append(iter7,SOR(A,b,1.7,tol,max_iter=max_iter)[2])\n\n    plt.yscale('log')\n    plt.plot(h,iterj)    \n    plt.plot(h,iter0)\n    plt.plot(h,iter3)\n    plt.plot(h,iter5)\n    plt.plot(h,iter7)\n    plt.savefig('img/1/iter_vs_h.pdf')\n\n\ndef iter_vs_h_cg():\n    global iter_cg_temp\n    global iter_pcg_temp\n    iter_cg_temp = 0\n    iter_pcg_temp = 0\n\n    def CG_callback(x):\n        global iter_cg_temp\n        iter_cg_temp += 1\n    \n    def PCG_callback(x):\n        global iter_pcg_temp\n        iter_pcg_temp += 1\n        \n    iter_cg = []\n    iter_pcg = []\n\n    h = []\n    tol = 1e-16\n    max_iter = 2000\n    \n    for n in [3,5,10,20,30]:\n        iter_cg_temp = 0\n        iter_pcg_temp = 0\n        \n        N = (n-1)**2\n        \n        A,b = Ab(n)\n        h = np.append(h,1/(n+1))\n        lu = sparse.linalg.spilu(A)\n        Pr = sparse.csc_matrix((N, N))\n        Pr[lu.perm_r, np.arange(N)] = 1\n        Pc = sparse.csc_matrix((N, N))\n        Pc[np.arange(N), lu.perm_c] = 1\n    \n        M =  Pc.dot((sparse.linalg.inv(lu.U).dot( sparse.linalg.inv(lu.L)) ).dot(Pr))\n    \n        sparse.linalg.cg(A,b,x0=np.zeros((n-1)**2),tol=tol,maxiter=max_iter,callback=CG_callback)\n        sparse.linalg.cg(A,b,x0=np.zeros((n-1)**2),tol=tol,maxiter=max_iter,M=M,callback=PCG_callback)\n                \n        iter_cg = np.append(iter_cg,iter_cg_temp)\n        iter_pcg = np.append(iter_pcg,iter_pcg_temp)\n\n    plt.plot(h,iter_cg)    \n    plt.plot(h,iter_pcg)\n    plt.savefig('img/1/iter_vs_h_cg.pdf')", "meta": {"hexsha": "47b7d58bc35875778576c2afc431cc80f8af8fdb", "size": 7530, "ext": "py", "lang": "Python", "max_stars_repo_path": "amath585/hw6/hw6_1.py", "max_stars_repo_name": "interesting-courses/UW_coursework", "max_stars_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-19T01:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T12:32:59.000Z", "max_issues_repo_path": "amath585/hw6/hw6_1.py", "max_issues_repo_name": "interesting-courses/UW_coursework", "max_issues_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "amath585/hw6/hw6_1.py", "max_forks_repo_name": "interesting-courses/UW_coursework", "max_forks_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-31T22:23:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T22:13:01.000Z", "avg_line_length": 29.0733590734, "max_line_length": 103, "alphanum_fraction": 0.5697211155, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789547, "lm_q2_score": 0.9073122244934722, "lm_q1q2_score": 0.8535900431930746}}
{"text": "#\n#  file:  numpy_matmul.py\n#\n#  NumPy matrix multiplication examples\n#\n#  RTK, 12-Apr-2020\n#  Last update:  12-Apr-2020\n#\n################################################################\n\nimport numpy as np\n\ndef dot(a,b):\n    try:\n        return np.dot(a,b)\n    except:\n        return \"fails\"\n\ndef matmul(a,b):\n    try:\n        return np.matmul(a,b)\n    except:\n        return \"fails\"\n\n#  the different vectors and matrices\na1 = np.array([1,2,3])\nar = a1.reshape((1,3))\nac = a1.reshape((3,1))\nb1 = np.array([1,2,3])\nbr = b1.reshape((1,3))\nbc = b1.reshape((3,1))\nA = np.array([[1,2,3],[4,5,6],[7,8,9]])\nB = np.array([[9,8,7],[6,5,4],[3,2,1]])\n\nprint()\nprint(\"np.dot examples:\")\nprint(\"dot(a1,b1):\"); print(dot(a1,b1))\nprint(\"dot(a1,br):\"); print(dot(a1,br))\nprint(\"dot(a1,bc):\"); print(dot(a1,bc))\nprint(\"dot(ar,b1):\"); print(dot(ar,b1))\nprint(\"dot(ar,br):\"); print(dot(ar,br))\nprint(\"dot(ar,bc):\"); print(dot(ar,bc))\nprint(\"dot(ac,b1):\"); print(dot(ac,b1))\nprint(\"dot(ac,br):\"); print(dot(ac,br))\nprint(\"dot(ac,bc):\"); print(dot(ac,bc))\nprint(\"dot(A,a1):\"); print(dot(A,a1))\nprint(\"dot(A,ar):\"); print(dot(A,ar))\nprint(\"dot(A,ac):\"); print(dot(A,ac))\nprint(\"dot(a1,A):\"); print(dot(a1,A))\nprint(\"dot(ar,A):\"); print(dot(ar,A))\nprint(\"dot(ac,A):\"); print(dot(ac,A))\nprint(\"dot(A,B):\"); print(dot(A,B))\nprint()\n\nprint()\nprint(\"np.matmul examples:\")\nprint(\"matmul(a1,b1):\"); print(matmul(a1,b1))\nprint(\"matmul(a1,br):\"); print(matmul(a1,br))\nprint(\"matmul(a1,bc):\"); print(matmul(a1,bc))\nprint(\"matmul(ar,b1):\"); print(matmul(ar,b1))\nprint(\"matmul(ar,br):\"); print(matmul(ar,br))\nprint(\"matmul(ar,bc):\"); print(matmul(ar,bc))\nprint(\"matmul(ac,b1):\"); print(matmul(ac,b1))\nprint(\"matmul(ac,br):\"); print(matmul(ac,br))\nprint(\"matmul(ac,bc):\"); print(matmul(ac,bc))\nprint(\"matmul(A,a1):\"); print(matmul(A,a1))\nprint(\"matmul(A,ar):\"); print(matmul(A,ar))\nprint(\"matmul(A,ac):\"); print(matmul(A,ac))\nprint(\"matmul(a1,A):\"); print(matmul(a1,A))\nprint(\"matmul(ar,A):\"); print(matmul(ar,A))\nprint(\"matmul(ac,A):\"); print(matmul(ac,A))\nprint(\"matmul(A,B):\"); print(matmul(A,B))\nprint()\n\n", "meta": {"hexsha": "7fc7ebcea166cf7a5ac0e659872a5efc1e198e05", "size": 2077, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapter_05/numpy_matmul.py", "max_stars_repo_name": "rkneusel9/MathForDeepLearning", "max_stars_repo_head_hexsha": "8db1a85ce3cef4b48aab01ebe156e3fab2dfa271", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2021-10-12T19:53:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:41:23.000Z", "max_issues_repo_path": "chapter_05/numpy_matmul.py", "max_issues_repo_name": "mohit-n-rajput/MathForDeepLearning", "max_issues_repo_head_hexsha": "8db1a85ce3cef4b48aab01ebe156e3fab2dfa271", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter_05/numpy_matmul.py", "max_forks_repo_name": "mohit-n-rajput/MathForDeepLearning", "max_forks_repo_head_hexsha": "8db1a85ce3cef4b48aab01ebe156e3fab2dfa271", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-06-16T17:21:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T09:22:50.000Z", "avg_line_length": 27.6933333333, "max_line_length": 64, "alphanum_fraction": 0.5854597978, "include": true, "reason": "import numpy", "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587142, "lm_q2_score": 0.907312213841788, "lm_q1q2_score": 0.8535900301595846}}
{"text": "import numpy as np\n\n### Functions for you to fill in ###\n\n# pragma: coderesponse template\n\n\ndef polynomial_kernel(X, Y, c, p):\n    \"\"\"\n        Compute the polynomial kernel between two matrices X and Y::\n            K(x, y) = (<x, y> + c)^p\n        for each pair of rows x in X and y in Y.\n\n        Args:\n            X - (n, d) NumPy array (n datapoints each with d features)\n            Y - (m, d) NumPy array (m datapoints each with d features)\n            c - a coefficient to trade off high-order and low-order terms (scalar)\n            p - the degree of the polynomial kernel\n\n        Returns:\n            kernel_matrix - (n, m) Numpy array containing the kernel matrix\n    \"\"\"\n    # YOUR CODE HERE\n    # raise NotImplementedError\n    kernel_matrix = (np.matmul(X, Y.T) + c) ** p\n\n    return kernel_matrix\n# pragma: coderesponse end\n\n# pragma: coderesponse template\n\n\ndef rbf_kernel(X, Y, gamma):\n    \"\"\"\n        Compute the Gaussian RBF kernel between two matrices X and Y::\n            K(x, y) = exp(-gamma ||x-y||^2)\n        for each pair of rows x in X and y in Y.\n\n        Args:\n            X - (n, d) NumPy array (n datapoints each with d features)\n            Y - (m, d) NumPy array (m datapoints each with d features)\n            gamma - the gamma parameter of gaussian function (scalar)\n\n        Returns:\n            kernel_matrix - (n, m) Numpy array containing the kernel matrix\n    \"\"\"\n    \n    # YOUR CODE HERE\n    # raise NotImplementedError\n    n_rows_Y, n_cols_Y = Y.shape\n    Y_ = Y.reshape(n_rows_Y, 1, n_cols_Y)\n    k = np.exp(-gamma * np.sum((X - Y_)**2, axis=2))\n    return k.T\n# pragma: coderesponse end\n", "meta": {"hexsha": "7bfda59eb212c1b40ecb64ebc7f9a0ec9fb91936", "size": 1632, "ext": "py", "lang": "Python", "max_stars_repo_path": "resources_mnist/mnist/part1/kernel.py", "max_stars_repo_name": "akin-aroge/mitx6.86_projects", "max_stars_repo_head_hexsha": "ab02b92bc0c28758cdae5898898cd26e297c3cd2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-02T07:07:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-05T06:43:23.000Z", "max_issues_repo_path": "resources_mnist/mnist/part1/kernel.py", "max_issues_repo_name": "akin-aroge/mitx6.86_projects", "max_issues_repo_head_hexsha": "ab02b92bc0c28758cdae5898898cd26e297c3cd2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "resources_mnist/mnist/part1/kernel.py", "max_forks_repo_name": "akin-aroge/mitx6.86_projects", "max_forks_repo_head_hexsha": "ab02b92bc0c28758cdae5898898cd26e297c3cd2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6727272727, "max_line_length": 82, "alphanum_fraction": 0.5931372549, "include": true, "reason": "import numpy", "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298657, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.8535862544625855}}
{"text": "import numpy as np\n\ndef R2calc(Y, Yhat):\n    \"\"\"Function to determine the determination coefficient\n    \n    Parameters\n    ------------\n    Y: np.array\n       Measured values\n    Yhat: np.array\n       Estimated values from the fit\n       \n    Returns\n    ------------\n    R2: float\n        The coeficient of determination\n    \"\"\"\n    ##Average of our measurements\n    Ybar = np.mean(Y)\n    \n    #Sum Squared of residues\n    SSres = np.sum((Y - Yhat)**2)\n    #Total Sum Squared\n    SStot = np.sum((Y - Ybar)**2)\n    \n    R2 = 1 - SSres / SStot\n        \n    return R2", "meta": {"hexsha": "34bbf148eae12f8a7fa9a6720aa7c3a85a483423", "size": 566, "ext": "py", "lang": "Python", "max_stars_repo_path": "functions/R2calc.py", "max_stars_repo_name": "guimarais/IntroExperimentalPhysics", "max_stars_repo_head_hexsha": "4db3476e6f5779ae9ceed40866d1f699805688b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/R2calc.py", "max_issues_repo_name": "guimarais/IntroExperimentalPhysics", "max_issues_repo_head_hexsha": "4db3476e6f5779ae9ceed40866d1f699805688b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/R2calc.py", "max_forks_repo_name": "guimarais/IntroExperimentalPhysics", "max_forks_repo_head_hexsha": "4db3476e6f5779ae9ceed40866d1f699805688b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2142857143, "max_line_length": 58, "alphanum_fraction": 0.5441696113, "include": true, "reason": "import numpy", "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298656, "lm_q2_score": 0.8872045847699186, "lm_q1q2_score": 0.8535862530278925}}
{"text": "# --------------\n# Code starts here\n\nimport numpy as np\n\n# Code starts here\n\n# Adjacency matrix\nadj_mat = np.array([[0,0,0,0,0,0,1/3,0],\n                   [1/2,0,1/2,1/3,0,0,0,0],\n                   [1/2,0,0,0,0,0,0,0],\n                   [0,1,0,0,0,0,0,0],\n                  [0,0,1/2,1/3,0,0,1/3,0],\n                   [0,0,0,1/3,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,1,1/3,0]])\n\n# Compute eigenvalues and eigencevectrs\neigenvalues, eigenvectors = np.linalg.eig(adj_mat)\n\n# Eigen vector corresponding to 1\neigen_1 = abs(eigenvectors[:,0])/np.linalg.norm(eigenvectors[:,0],1)\n\n# most important page\npage = np.where(eigen_1 == eigen_1.max())[0][0]+1\nprint(page)\n\n# Code ends here\n\n\n# --------------\n# Code starts here\n\n# Initialize stationary vector I\ninit_I = [1,0,0,0,0,0,0,0]\n\n# Perform iterations for power method\nfor i in range(10):\n    init_I = np.dot(adj_mat,init_I)\npower_page = np.argmax(init_I)+1\npower_page\n\n# Code ends here\n\n\n# --------------\n# Code starts here\n\n# New Adjancency matrix\n# New Adjancency matrix\nnew_adj_mat = np.array([[0,0,0,0,0,0,0,0],\n                   [1/2,0,1/2,1/3,0,0,0,0],\n                  [1/2,0,0,0,0,0,0,0],\n                   [0,1,0,0,0,0,0,0],\n                   [0,0,1/2,1/3,0,0,1/2,0],\n                   [0,0,0,1/3,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,0,0,1/2],\n                   [0,0,0,0,1/3,1,1/2,0]])\n\n# Initialize stationary vector I\nnew_init_I = [1,0,0,0,0,0,0,0]\n\n# Perform iterations for power method\nfor i in range(10):\n    new_init_I = np.dot(new_adj_mat, new_init_I)\nnew_init_I\n\n# Code ends here\n\n\n# --------------\n# Alpha value\nalpha = 0.85\n\n# Code starts here\n\n# Modified adjancency matrix\nn = len(new_adj_mat)\nG = (alpha * new_adj_mat) + (((1 - alpha) * (1/n)) * np.ones(new_adj_mat.shape))\n\n# Initialize stationary vector I\nfinal_init_I = [1,0,0,0,0,0,0,0]\n\n# Perform iterations for power method\nfor i in range(1000):\n    final_init_I = np.dot(G,final_init_I)\n    final_init_I /= np.linalg.norm(final_init_I,1)\nfinal_init_I\n\n# Code ends here\n\n\n", "meta": {"hexsha": "4544bc43bd467783a92f963dfc723feba14c787d", "size": 2064, "ext": "py", "lang": "Python", "max_stars_repo_path": "How-does-Google-google/code.py", "max_stars_repo_name": "abhiwonder/ga-learner-dsmp-repo", "max_stars_repo_head_hexsha": "c1cf42bf35f7b59d7fb0fe62b2387cb25e0c47ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "How-does-Google-google/code.py", "max_issues_repo_name": "abhiwonder/ga-learner-dsmp-repo", "max_issues_repo_head_hexsha": "c1cf42bf35f7b59d7fb0fe62b2387cb25e0c47ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "How-does-Google-google/code.py", "max_forks_repo_name": "abhiwonder/ga-learner-dsmp-repo", "max_forks_repo_head_hexsha": "c1cf42bf35f7b59d7fb0fe62b2387cb25e0c47ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1935483871, "max_line_length": 80, "alphanum_fraction": 0.5513565891, "include": true, "reason": "import numpy", "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075722839014, "lm_q2_score": 0.8872045877523147, "lm_q1q2_score": 0.8535862520415191}}
{"text": "from typing import Tuple\nimport numpy as np\n\n\ndef particle_elastic_collision(\n        ux1: float,\n        uy1: float,\n        ux2: float,\n        uy2: float,\n        m1: float,\n        m2: float\n    ) -> Tuple[float, float, float, float]:\n    \"\"\"2D elastic collision of two particles.\n\n    The model assumes the particles have zero radius. The larger\n    the particles are, the less accurate this model is.\n\n    Args:\n        ux1: x-velocity of particle 1\n        uy1: y-velocity of particle 1\n        ux2: x-velocity of particle 2\n        uy2: y-velocity of particle 2\n        m1: mass of particle 1\n        m2: mass of particle 2\n\n    Return:\n        resulting velocities (vx1, vy1, vx2, vy2)\n    \"\"\"\n    vx1 = (ux1 * (m1 - m2) / (m1 + m2)) + (ux2 * 2 * m2 / (m1 + m2))\n    vx2 = (ux1 * 2 * m1 / (m1 + m2)) + (ux2 * (m2 - m1) / (m1 + m2))\n    vy1 = (uy1 * (m1 - m2) / (m1 + m2)) + (uy2 * 2 * m2 / (m1 + m2))\n    vy2 = (uy1 * 2 * m1 / (m1 + m2)) + (uy2 * (m2 - m1) / (m1 + m2))\n\n    return (vx1, vy1, vx2, vy2)\n\n\ndef ball_elastic_collision(\n        u1: np.array,\n        u2: np.array,\n        m1: float,\n        m2: float,\n        c1: np.array,\n        c2: np.array,\n        dissipation: float = 0.\n    ) -> Tuple[np.array, np.array]:\n    \"\"\"2D elastic collision of two balls (particles with non-zero radius).\n\n    The model assumes the balls have non-zero radius.\n    The resulting velocities depend not only on the\n    initial velocities and masses, but also on the position\n    of the balls at the moment of collision.\n\n    Args:\n        u1: velocity vector of ball 1\n        u2: velocity vector of ball 2\n        m1: mass of ball 1\n        m2: mass of ball 2\n        c1: center position of ball 1\n        c2: center position of ball 2\n\n    Return:\n        resulting velocities (v1, v2)\n    \"\"\"\n    # Reference: https://scipython.com/blog/two-dimensional-collisions/\n    mtot = m1 + m2\n    d = np.linalg.norm(c1 - c2) ** 2\n    if d < 1e-3:\n        # For numerical stability, do not allow too little distance\n        d = 1e-3\n    v1 = u1 - 2 * m2 / mtot * np.dot(u1 - u2, c1 - c2) / d * (c1 - c2)\n    v2 = u2 - 2 * m1 / mtot * np.dot(u2 - u1, c2 - c1) / d * (c2 - c1)\n\n    v1 *= 1. - dissipation / 2.\n    v2 *= 1. - dissipation / 2.\n\n    return (v1, v2)\n", "meta": {"hexsha": "a1c11f107a9a34a27630a7cd37cf1e28ba62a41e", "size": 2257, "ext": "py", "lang": "Python", "max_stars_repo_path": "objects/collisions.py", "max_stars_repo_name": "krzysztofarendt/ballroom", "max_stars_repo_head_hexsha": "7e99d14278e71be873edaf415e7253e87bc81724", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "objects/collisions.py", "max_issues_repo_name": "krzysztofarendt/ballroom", "max_issues_repo_head_hexsha": "7e99d14278e71be873edaf415e7253e87bc81724", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-05T16:46:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-05T16:46:16.000Z", "max_forks_repo_path": "objects/collisions.py", "max_forks_repo_name": "krzysztofarendt/ballroom", "max_forks_repo_head_hexsha": "7e99d14278e71be873edaf415e7253e87bc81724", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3116883117, "max_line_length": 74, "alphanum_fraction": 0.553832521, "include": true, "reason": "import numpy", "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350253, "lm_q2_score": 0.8856314738181875, "lm_q1q2_score": 0.8535538523607129}}
{"text": "\"\"\"Bell state.\"\"\"\nimport numpy as np\n\nfrom toqito.states import basis\n\n\ndef bell(idx: int) -> np.ndarray:\n    r\"\"\"\n    Produce a Bell state [WikBell]_.\n\n    Returns one of the following four Bell states depending on the value of :code:`idx`:\n\n    .. math::\n        \\begin{equation}\n            \\begin{aligned}\n                u_0 = \\frac{1}{\\sqrt{2}} \\left( |00 \\rangle + |11 \\rangle \\right), &\n                \\qquad &\n                u_1 = \\frac{1}{\\sqrt{2}} \\left( |00 \\rangle - |11 \\rangle \\right), \\\\\n                u_2 = \\frac{1}{\\sqrt{2}} \\left( |01 \\rangle + |10 \\rangle \\right), &\n                \\qquad &\n                u_3 = \\frac{1}{\\sqrt{2}} \\left( |01 \\rangle - |10 \\rangle \\right).\n            \\end{aligned}\n        \\end{equation}\n\n    Examples\n    ==========\n\n    When :code:`idx = 0`, this produces the following Bell state:\n\n    .. math::\n        u_0 = \\frac{1}{\\sqrt{2}} \\left( |00 \\rangle + |11 \\rangle \\right).\n\n    Using :code:`toqito`, we can see that this yields the proper state.\n\n    >>> from toqito.states import bell\n    >>> import numpy as np\n    >>> bell(0)\n    [[0.70710678],\n     [0.        ],\n     [0.        ],\n     [0.70710678]]\n\n    References\n    ==========\n    .. [WikBell] Wikipedia: Bell state\n        https://en.wikipedia.org/wiki/Bell_state\n\n    :param idx: A parameter in [0, 1, 2, 3]\n    :return: Bell state with index :code:`idx`.\n    \"\"\"\n    e_0, e_1 = basis(2, 0), basis(2, 1)\n    if idx == 0:\n        return 1 / np.sqrt(2) * (np.kron(e_0, e_0) + np.kron(e_1, e_1))\n    if idx == 1:\n        return 1 / np.sqrt(2) * (np.kron(e_0, e_0) - np.kron(e_1, e_1))\n    if idx == 2:\n        return 1 / np.sqrt(2) * (np.kron(e_0, e_1) + np.kron(e_1, e_0))\n    if idx == 3:\n        return 1 / np.sqrt(2) * (np.kron(e_0, e_1) - np.kron(e_1, e_0))\n    raise ValueError(\"Invalid integer value for Bell state.\")\n", "meta": {"hexsha": "572fe50324202306af45a2f3bf3f1cce368c9e20", "size": 1844, "ext": "py", "lang": "Python", "max_stars_repo_path": "toqito/states/bell.py", "max_stars_repo_name": "paniash/toqito", "max_stars_repo_head_hexsha": "ab67c2a3fca77b3827be11d1e79531042ea62b82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2020-01-28T17:02:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T18:02:15.000Z", "max_issues_repo_path": "toqito/states/bell.py", "max_issues_repo_name": "paniash/toqito", "max_issues_repo_head_hexsha": "ab67c2a3fca77b3827be11d1e79531042ea62b82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 82, "max_issues_repo_issues_event_min_datetime": "2020-05-31T20:09:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:13:59.000Z", "max_forks_repo_path": "toqito/states/bell.py", "max_forks_repo_name": "paniash/toqito", "max_forks_repo_head_hexsha": "ab67c2a3fca77b3827be11d1e79531042ea62b82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2020-04-02T16:07:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T13:39:22.000Z", "avg_line_length": 30.2295081967, "max_line_length": 88, "alphanum_fraction": 0.5173535792, "include": true, "reason": "import numpy", "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96036116089903, "lm_q2_score": 0.8887587817066392, "lm_q1q2_score": 0.8535294153589956}}
{"text": "import numpy as np\n\n\n# using alternating least squares method for collaborative filtering:\n# http://www.quuxlabs.com/blog/2010/09/matrix-factorization-a-simple-tutorial-and-implementation-in-python/\ndef get_error(Q, X, Y, W):\n    return np.sum((W * (Q - np.dot(X, Y)))**2)\n\n\ndef matrix_factorization(R, P, Q, K, steps=10000, alpha=0.0002, beta=0.02):\n    Q = Q.T\n    for step in range(steps):\n        for i in range(len(R)):\n            for j in range(len(R[i])):\n                if R[i][j] > 0:\n                    eij = R[i][j] - np.dot(P[i, :], Q[:, j])\n                    for k in range(K):\n                        P[i][k] = P[i][k] + alpha * (2 * eij * Q[k][j] - beta * P[i][k])\n                        Q[k][j] = Q[k][j] + alpha * (2 * eij * P[i][k] - beta * Q[k][j])\n        eR = np.dot(P, Q)\n        e = 0\n        for i in range(len(R)):\n            for j in range(len(R[i])):\n                if R[i][j] > 0:\n                    e = e + pow(R[i][j] - np.dot(P[i, :], Q[:, j]), 2)\n                    for k in range(K):\n                        e = e + (beta/2) * (pow(P[i][k], 2) + pow(Q[k][j], 2))\n        if e < 0.0001:\n            break\n    return P, Q.T\n\n\ndef initialiseVariables():\n    R = np.array(\n        [[0, 1, np.nan],\n         [1, np.nan, 1],\n         [np.nan, 1, 2]]\n    )\n    N = len(R)\n    M = len(R[0])\n    K = 1  # number of rows\n\n    P = np.random.rand(N, K)\n    Q = np.random.rand(M, K)\n    return M, N, K, P, Q, R\n\n\ndef checkAgainst(_nR):\n    desired_matrix = np.array(\n        [[0, 1, np.nan],\n         [1, np.nan, 1],\n         [np.nan, 1, 2]]\n    )\n    for i in range(len(desired_matrix)):\n        for j in range(len(desired_matrix[0])):\n            # skip these numbers\n            if i == 0 and j == 2 or i == 1 and j == 1 or i == 2 and j == 0:\n                continue\n            else:\n                if round(_nR[i][j]) != desired_matrix[i][j]:\n                    return False\n    return True\n\n\nif __name__ == '__main__':\n    M, N, K, P, Q, R = initialiseVariables()\n\n    nP, nQ = matrix_factorization(R, P, Q, K)\n    nR = np.dot(nP, nQ.T)\n    print(nR)\n    print(nP)\n    print(nQ)\n    print(checkAgainst(nR))\n", "meta": {"hexsha": "e096720724dafdf83720b3314c74f0e8a91949b4", "size": 2146, "ext": "py", "lang": "Python", "max_stars_repo_path": "Homework/Week6/q1.py", "max_stars_repo_name": "clemencegoh/SUTD_Machine_Learning_01.112", "max_stars_repo_head_hexsha": "56a9d32ba620f8c86387bbfc9a0ea21d948fe9f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homework/Week6/q1.py", "max_issues_repo_name": "clemencegoh/SUTD_Machine_Learning_01.112", "max_issues_repo_head_hexsha": "56a9d32ba620f8c86387bbfc9a0ea21d948fe9f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homework/Week6/q1.py", "max_forks_repo_name": "clemencegoh/SUTD_Machine_Learning_01.112", "max_forks_repo_head_hexsha": "56a9d32ba620f8c86387bbfc9a0ea21d948fe9f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0, "max_line_length": 107, "alphanum_fraction": 0.4524697111, "include": true, "reason": "import numpy", "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811571768048, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.853434854478891}}
{"text": "import numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nfrom io_utilities import load_data\nfrom visualizations import show_clusters_centroids\n\ndef distance(a,b):\n    \"\"\"\n    Compute Euclidean Distance Between Two Points\n    Input:\n        a (list): an n-dimensional list or array\n        b (list): an n-dimensional list or array\n    Output:\n        The Euclidean Distance between vectors a and b\n    \"\"\"\n\n    # All you need to do here is calculate the Euclidean Distance between\n    # points a and b and return it\n\n    euc_dist = # You code here!\n\n    return euc_dist\n\ndef get_clusters(points,centroids):\n    \"\"\"\n    Returns a list of clusters given all the points in the dataset and\n    the current centroids.\n    Input:\n        points (numpy array): a 2D (M,N) Array with the data to cluster.\n        M = Instances, N = Variables.\n        centroids (list of numpy arrays): A list with the k current centroids\n    Output:\n        clusters (list of lists of numpy arrays): A List of Clusters. Each cluster\n        is also a list of numpy arrays.\n    \"\"\"\n    clusters = [[] for f in centroids]\n\n    for i, point in enumerate(points):\n        point_to_centroids = []\n        for j, centroid in enumerate(centroids):\n            # Make sure you find the distance from each point to the\n            # centroid and append it to point_to_centroids\n        # Now find the index of the smallest value in point_to_centroids\n        # and use it to add the point to the corresponding cluster\n\n    return clusters\n\ndef update_centroids(clusters):\n    \"\"\"\n    Given a list of clusters (as prepared by get_clusters()) get the new centroids\n    Input:\n        clusters (list of numpy arrays): A List of Clusters. Each cluster\n        is a 2D Array, rows = instances, columns=variables\n    Output:\n        A (list of numpy arrays): The new centroids.\n    \"\"\"\n    new_centroids = []\n\n    for cluster in clusters:\n        # Find the average for each row in the cluster.\n        # TIP: use the power of numpy!\n\n        centroid = # You Code here\n        new_centroids.append(centroid)\n\n    return new_centroids\n\n\n\ndef k_means(points, k, iterations=10):\n    \"\"\"\n    K Means Unsupervised ML Algorithm Implementation with Forgy Initialization\n    Input:\n        points (numpy array): a 2D (M,N) Array with the data to cluster.\n        M = Instances, N = variables.\n        k (int): The number of clusters to find\n    \"\"\"\n    idx = np.random.randint(len(points),size=k)\n\n    centroids = points[idx,:]\n    clusters = get_clusters(points,centroids)\n\n    for i in range(iterations):\n\n        # Use get_clusters() and update_centroids() for each iteration.\n\n    return clusters,centroids\n\n\nif __name__ == \"__main__\":\n    data = load_data('./data/iris.data')\n    k = 3\n\n    X = np.array([f[:-1] for f in data])\n    y = np.array([f[-1] for f in data])\n\n    clusters,centroids = k_means(X,3)\n\n    show_clusters_centroids(clusters, centroids, \"Result\", keep=True)\n", "meta": {"hexsha": "17870a1cb214d6974e8796fc6b462a590238e4ed", "size": 2962, "ext": "py", "lang": "Python", "max_stars_repo_path": "k_means_guide.py", "max_stars_repo_name": "ebucheli/TC1002S", "max_stars_repo_head_hexsha": "ff4647845a8e87bdb002d977501311fed96accd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-20T06:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-20T06:08:25.000Z", "max_issues_repo_path": "k_means_guide.py", "max_issues_repo_name": "ebucheli/TC1002S", "max_issues_repo_head_hexsha": "ff4647845a8e87bdb002d977501311fed96accd4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-15T17:32:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-15T17:46:38.000Z", "max_forks_repo_path": "k_means_guide.py", "max_forks_repo_name": "ebucheli/TC1002S", "max_forks_repo_head_hexsha": "ff4647845a8e87bdb002d977501311fed96accd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2020-09-15T16:43:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-23T05:38:16.000Z", "avg_line_length": 29.0392156863, "max_line_length": 82, "alphanum_fraction": 0.6586765699, "include": true, "reason": "import numpy", "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.943347579470196, "lm_q2_score": 0.9046505395995927, "lm_q1q2_score": 0.8533998967976825}}
{"text": "import math\nimport numpy as np\n\nfrom logger import log\n\n\ndef point_distance(point1, point2):\n    \"\"\"\n\n    @param point1:\n    @param point2:\n    @return:\n    \"\"\"\n    x1, y1 = point1\n    x2, y2 = point2\n\n    return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\n\n\ndef mid_joint(i, joints):\n    \"\"\"\n    given a list containing two joints, it calculates a new join between them\n    @param i: set of two indexes\n    @param joints: set of joints\n    @return: returns the generated joint\n    \"\"\"\n    if type(i) == list:\n        if len(i) == 2:\n            x1, y1 = joints[i[0]]\n            x2, y2 = joints[i[1]]\n\n            x = (x1 + x2) / 2\n            y = (y1 + y2) / 2\n            return (x, y)\n        else:\n            raise Exception(\"Mid joint for more than 2 points not implemented yet.\")\n    else:\n        return joints[i]\n\n\ndef create_angle(p1, p2, p3, decimal=2):\n    \"\"\"\n    auxiliary method that finds the value of the angle given three points in 2D space\n    @param p1: first point\n    @param p2: second point\n    @param p3: third point or a reference axis [\"axis_x\", \"axis_y\"]\n    @return: returns the angle in degrees\n    \"\"\"\n    flag = 'axis' in p3\n\n    # x2, y2 = p2\n    #\n    # if \"axis_y\" in p3:\n    #     p3 = x2, 0\n    # elif \"axis_x\" in p3:\n    #     p3 = 0, y2\n\n    x1, y1 = p1\n    x2, y2 = p2\n\n    if \"axis_y\" in p3:\n        p3 = x2, y1\n    elif \"axis_x\" in p3:\n        p3 = x1, y2\n\n\n    try:\n        p12 = point_distance(p1, p2)\n        p13 = point_distance(p1, p3)  # np.sqrt((x1 - x3) ** 2 + (y1 - y3) ** 2)\n        p23 = point_distance(p3, p2)  # np.sqrt((x3 - x2) ** 2 + (y3 - y2) ** 2)\n\n        a = np.arccos((p12 ** 2 + p23 ** 2 - p13 ** 2) / (2 * p12 * p23))\n\n        if np.isnan(a):\n            a_deg = None\n        else:\n            a_deg = math.degrees(a)  # *180/math.pi\n\n    except:\n        log.debug(\"Exception for angle occurred.\")\n        a_deg = None\n    # finally:\n    #     if flag:\n    #         a_deg = np.abs(90 - a_deg) + 90\n\n    return round(a_deg, decimal)\n", "meta": {"hexsha": "336fa68ec4bf9c86037f53788c46623a0cc15900", "size": 1995, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/geometry.py", "max_stars_repo_name": "SynStratos/Fitness_Pose_Machine", "max_stars_repo_head_hexsha": "006576f36b2e5c9b592a1585a91791a0af950814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-18T21:43:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T22:43:44.000Z", "max_issues_repo_path": "utils/geometry.py", "max_issues_repo_name": "SynStratos/Fitness_Pose_Machine", "max_issues_repo_head_hexsha": "006576f36b2e5c9b592a1585a91791a0af950814", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/geometry.py", "max_forks_repo_name": "SynStratos/Fitness_Pose_Machine", "max_forks_repo_head_hexsha": "006576f36b2e5c9b592a1585a91791a0af950814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9310344828, "max_line_length": 85, "alphanum_fraction": 0.5127819549, "include": true, "reason": "import numpy", "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436404, "lm_q2_score": 0.8933094017937621, "lm_q1q2_score": 0.8533955637080045}}
{"text": "import math\nimport numpy as np\n\n\ndef f(x):\n    return np.exp(-1*x**2)\n\n\ndef g(x):\n    return np.sin(x) / x\n\n\ndef trapezoid_formula(inte, func):\n    \"\"\" Calculate the integral by trapezoid formula\n\n    Args:\n        inte: ndarray, the integrand interval\n        func: function object, the integrand function\n\n    Returns:\n        double, the integral value by trapezoid formula\n    \"\"\"\n    \n    return (inte[1] - inte[0]) * np.sum(func(inte)) / 2\n\n\ndef simpson_formula(inte, func):\n    \"\"\" Calculate the integral by Simpson formula\n\n    Args:\n        inte: ndarray, the integrand interval\n        func: function object, the integrand function\n\n    Returns:\n        double, the integral value by Simpson formula\n    \"\"\"\n    # get the nodes\n    x_list = np.linspace(inte[0], inte[1], 3)\n    # cofficient vector\n    C = np.array([1, 4, 1])\n\n    return (inte[1] - inte[0]) * np.sum(C.T.dot(func(x_list))) / sum(C) \n\n\nif __name__ == '__main__':\n    # integrand interval\n    inte = np.array([1e-32, 1])\n    # trapezoid formula\n    print(f\"The value of the first integral by trapezoid formula is {trapezoid_formula(inte, f)}\")\n    print(f\"The value of the second integral by trapezoid formula is {trapezoid_formula(inte, g)}\")\n    # Simpson formula\n    print(f\"The value of the first integral by Simpson formula is {simpson_formula(inte, f)}\")\n    print(f\"The value of the second integral by Simpson formula is {simpson_formula(inte, g)}\") \n\n", "meta": {"hexsha": "0a33835e5b629fcb49ebe7f1f46ec200c516f30b", "size": 1434, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumericalIntegral/simpson_formula.py", "max_stars_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_stars_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NumericalIntegral/simpson_formula.py", "max_issues_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_issues_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumericalIntegral/simpson_formula.py", "max_forks_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_forks_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0727272727, "max_line_length": 99, "alphanum_fraction": 0.6513249651, "include": true, "reason": "import numpy", "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191271831558, "lm_q2_score": 0.8933094060543487, "lm_q1q2_score": 0.8533955620963437}}
{"text": "# 二項分布\n\n# 利用するライブラリ\nimport numpy as np\nfrom scipy.stats import binom, multinomial # 二項分布, 多項分布\nfrom scipy.special import gamma, loggamma # ガンマ関数, 対数ガンマ関数\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n#%%\n\n### 確率の計算\n\n# パラメータを指定\nphi = 0.3\n\n# 試行回数を指定\nM = 10\n\n# 確率変数の値を指定:(x <= M)\nx = 3\n\n# ベクトルに変換\nx_v = np.array([M - x, x])\nphi_v = np.array([1.0 - phi, phi])\n\n\n# 定義式により確率を計算\nC = gamma(M + 1) / gamma(M - x + 1) / gamma(x + 1)\nprob = C * phi**x * (1 - phi)**(M - x)\nprint(prob)\n\n# 対数をとった定義式により確率を計算\nlog_C = loggamma(M + 1) - loggamma(M - x + 1) - loggamma(x + 1)\nlog_prob = log_C + x * np.log(phi) + (M - x) * np.log(1 - phi)\npron = np.exp(log_prob)\nprint(prob, log_prob)\n\n# 二項分布の関数により確率を計算\nprob = binom.pmf(k=x, n=M, p=phi)\nprint(prob)\n\n# 二項分布の対数をとった関数により確率を計算\nlog_prob = binom.logpmf(k=x, n=M, p=phi)\nprob = np.exp(log_prob)\nprint(prob, log_prob)\n\n# 多項分布の関数により確率を計算\nprob = multinomial.pmf(x=x_v, n=M, p=phi_v)\nprint(prob)\n\n# 多項分布の対数をとった関数により確率を計算\nlog_prob = multinomial.logpmf(x=x_v, n=M, p=phi_v)\nprob = np.exp(log_prob)\nprint(prob, log_prob)\n\n#%%\n\n### 統計量の計算\n\n# パラメータを指定\nphi = 0.3\n\n# 試行回数を指定\nM = 10\n\n\n# 平均を計算\nE_x = M * phi\nprint(E_x)\n\n# ベルヌーイ分布の関数により平均を計算\nprint(binom.mean(n=M, p=phi))\n\n# 分散を計算\nV_x = M * phi * (1.0 - phi)\nprint(V_x)\n\n# ベルヌーイ分布の関数により分散を計算\nprint(binom.var(n=M, p=phi))\n\n#%%\n\n### グラフの作成\n\n# 作図用のxの値を作成\nx_vals = np.arange(M + 1)\n\n# 分布を計算\nprobability = binom.pmf(k=x_vals, n=M, p=phi)\n\n# 二項分布を作図\nplt.figure(figsize=(12, 8)) # 図の設定\nplt.bar(x=x_vals, height=probability, color='#00A968') # 棒グラフ\n#plt.vlines(x=E_x, ymin=0.0, ymax=np.max(probability), color='orange', linestyle='--', label='$E[x]$') # 平均\n#plt.vlines(x=E_x - V_x, ymin=0.0, ymax=np.max(probability), color='orange', linestyle=':', label='$E[x] - \\sqrt{V[x]}$') # 平均 - 標準偏差\n#plt.vlines(x=E_x + V_x, ymin=0.0, ymax=np.max(probability), color='orange', linestyle=':', label='$E[x] + \\sqrt{V[x]}$') # 平均 + 標準偏差\nplt.xlabel('x') # x軸ラベル\nplt.ylabel('probability') # y軸ラベル\nplt.suptitle('Binomial Distribution', fontsize=20) # 図タイトル\nplt.title('$\\phi=' + str(phi) + ', M=' + str(M) + '$', loc='left') # タイトル\nplt.xticks(ticks=x_vals) # x軸目盛\n#plt.legend() # 凡例\nplt.grid() # グリッド線\nplt.show() # 描画\n\n#%%\n\n### パラメータと分布の形状の関係\n\n## phiを変更した場合\n\n# 作図用のphiの値を作成\nphi_vals = np.arange(start=0.0, stop=1.01, step=0.01)\n\n# 図を初期化\nfig = plt.figure(figsize=(12, 8))\n\n# 作図処理を関数として定義\ndef update(i):\n    # 前フレームのグラフを初期化\n    plt.cla()\n    \n    # i回目の値を取得\n    phi = phi_vals[i]\n    \n    # 分布を計算\n    probability = binom.pmf(k=x_vals, n=M, p=phi)\n    \n    # 二項分布を作図\n    plt.bar(x=x_vals, height=probability, color='#00A968') # 棒グラフ\n    plt.xlabel('x') # x軸ラベル\n    plt.ylabel('probability') # y軸ラベル\n    plt.suptitle('Binomial Distribution', fontsize=20) # 図タイトル\n    plt.title('$\\phi=' + str(np.round(phi, 2)) + ', M=' + str(M) + '$', loc='left') # タイトル\n    plt.xticks(ticks=x_vals) # x軸目盛\n    plt.grid() # グリッド線\n    plt.ylim(-0.1, 1.1) # y軸の表示範囲\n\n# gif画像を作成\nanime_prob = FuncAnimation(fig, update, frames=len(phi_vals), interval=100)\n\n# gif画像を保存\nanime_prob.save('ProbabilityDistribution/Binomial_prob_phi.gif')\n\n#%%\n\n## Mを変更した場合\n\n# パラメータを指定\nphi = 0.3\n\n# 試行回数の最大値を指定\nM_max = 100\n\n# 図を初期化\nfig = plt.figure(figsize=(12, 8))\n\n# 作図処理を関数として定義\ndef update(M):\n    # 前フレームのグラフを初期化\n    plt.cla()\n    \n    # 作図用のxの値を作成\n    x_vals = np.arange(M + 1)\n    \n    # 分布を計算\n    probability = binom.pmf(k=x_vals, n=M, p=phi)\n    \n    # 二項分布を作図\n    plt.bar(x=x_vals, height=probability, color='#00A968') # 棒グラフ\n    plt.xlabel('x') # x軸ラベル\n    plt.ylabel('probability') # y軸ラベル\n    plt.suptitle('Binomial Distribution', fontsize=20) # 図タイトル\n    plt.title('$\\phi=' + str(np.round(phi, 2)) + ', M=' + str(M) + '$', loc='left') # タイトル\n    #plt.xticks(ticks=x_vals) # x軸目盛\n    plt.grid() # グリッド線\n    plt.ylim(-0.1, 1.1) # y軸の表示範囲\n\n# gif画像を作成\nanime_prob = FuncAnimation(fig, update, frames=M_max, interval=100)\n\n# gif画像を保存\nanime_prob.save('ProbabilityDistribution/Binomial_prob_M.gif')\n\n#%%\n\n### 乱数の生成\n\n## 乱数の可視化\n\n# パラメータを指定\nphi = 0.3\n\n# 試行回数を指定\nM = 10\n\n# データ数を指定\nN = 1000\n\n# 二項分布に従う乱数を生成\nx_n = np.random.binomial(n=M, p=phi, size=N)\n\n# 乱数を集計\nfrequency = np.array([np.sum(x_n == m) for m in range(M + 1)])\n\n#%%\n\n# サンプルのヒストグラムを作成\nplt.figure(figsize=(12, 8)) # 図の設定\nplt.bar(x=x_vals, height=frequency, color='#00A968') # ヒストグラム\nplt.xlabel('x') # x軸ラベル\nplt.ylabel('frequency') # y軸ラベル\nplt.suptitle('Binomial Distribution', fontsize=20) # 図タイトル\nplt.title('$\\phi=' + str(phi) + ', N=' + str(N) + \n          '=(' + ', '.join([str(f) for f in frequency]) + ')$', loc='left') # タイトル\nplt.xticks(ticks=x_vals) # x軸目盛\nplt.grid() # グリッド線\nplt.show() # 描画\n\n# サンプルの構成比を作図\nplt.figure(figsize=(12, 8)) # 図の設定\nplt.bar(x=x_vals, height=probability, color='white', edgecolor='green', linestyle='--') # 分布\nplt.bar(x=x_vals, height=frequency / N, color='#00A968', alpha=0.8) # 構成比\nplt.xlabel('x') # x軸ラベル\nplt.ylabel('proportion') # y軸ラベル\nplt.suptitle('Binomial Distribution', fontsize=20) # 図タイトル\nplt.title('$\\phi=' + str(phi) + ', N=' + str(N) + \n          '=(' + ', '.join([str(f) for f in frequency]) + ')$', loc='left') # タイトル\nplt.xticks(ticks=x_vals) # x軸目盛\nplt.grid() # グリッド線\nplt.show() # 描画\n\n#%%\n\n## アニメーションによる可視化\n\n# フレーム数を指定\nN = 100\n\n# 図を初期化\nfig = plt.figure(figsize=(12, 8))\n\n# 頻度の最大値を取得\ny_max = np.max([np.sum(x_n[:N] == m) for m in range(M + 1)])\n\n# 作図処理を関数として定義\ndef update(n):\n    # 前フレームのグラフを初期化\n    plt.cla()\n    \n    # n個の乱数を集計\n    frequency = np.array([np.sum(x_n[:(n+1)] == m) for m in range(M + 1)])\n    \n    # サンプルのヒストグラムを作成\n    plt.bar(x=x_vals, height=frequency, color='#00A968', zorder=1) # ヒストグラム\n    plt.scatter(x=x_n[n], y=0.0, color='orange', s=100, zorder=2) # サンプル\n    plt.xlabel('x') # x軸ラベル\n    plt.ylabel('frequency') # y軸ラベル\n    plt.suptitle('Binomial Distribution', fontsize=20) # 図タイトル\n    plt.title('$\\phi=' + str(phi) + ', N=' + str(n) + \n              '=(' + ', '.join([str(f) for f in frequency]) + ')$', loc='left') # タイトル\n    plt.xticks(ticks=x_vals) # x軸目盛\n    plt.grid() # グリッド線\n    plt.ylim(-1.0, y_max + 1.0) # y軸の表示範囲\n\n# gif画像を作成\nanime_freq = FuncAnimation(fig, update, frames=N, interval=100)\n\n# gif画像を保存\nanime_freq.save('ProbabilityDistribution/Binomial_freq.gif')\n\n#%%\n\n# 図を初期化\nfig = plt.figure(figsize=(9, 6))\n\n# 作図処理を関数として定義\ndef update(n):\n    # 前フレームのグラフを初期化\n    plt.cla()\n    \n    # n個の乱数を集計\n    frequency = np.array([np.sum(x_n[:(n+1)] == m) for m in range(M + 1)])\n    \n    # サンプルの構成比を作成\n    plt.bar(x=x_vals, height=probability, color='white', edgecolor='green', linestyle='--', zorder=1) # 分布\n    plt.bar(x=x_vals, height=frequency / (n + 1), color='#00A968', alpha=0.8, zorder=2) # 構成比\n    plt.scatter(x=x_n[n], y=0.0, color='orange', s=100, zorder=3) # サンプル\n    plt.xlabel('x') # x軸ラベル\n    plt.ylabel('proportion') # y軸ラベル\n    plt.suptitle('Binomial Distribution', fontsize=20) # 図タイトル\n    plt.title('$\\phi=' + str(phi) + ', N=' + str(n) + \n              '=(' + ', '.join([str(f) for f in frequency]) + ')$', loc='left') # タイトル\n    plt.xticks(ticks=x_vals) # x軸目盛\n    plt.grid() # グリッド線\n    plt.ylim(-0.1, 1.1) # y軸の表示範囲\n\n# gif画像を作成\nanime_prop = FuncAnimation(fig, update, frames=N, interval=100)\n\n# gif画像を保存\nanime_prop.save('ProbabilityDistribution/Binomial_prop.gif')\n\n#%%\n\nprint('end')\n\n", "meta": {"hexsha": "a5716e13b6113413535a633fe8706bedf9fbe66e", "size": 7170, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/Python/binomial.py", "max_stars_repo_name": "anemptyarchive/Probability-Distribution", "max_stars_repo_head_hexsha": "c44d1079051c0e079c4f009e6fb2d7e1d7b61011", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Python/binomial.py", "max_issues_repo_name": "anemptyarchive/Probability-Distribution", "max_issues_repo_head_hexsha": "c44d1079051c0e079c4f009e6fb2d7e1d7b61011", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Python/binomial.py", "max_forks_repo_name": "anemptyarchive/Probability-Distribution", "max_forks_repo_head_hexsha": "c44d1079051c0e079c4f009e6fb2d7e1d7b61011", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2038834951, "max_line_length": 133, "alphanum_fraction": 0.6242677824, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.8933093989533708, "lm_q1q2_score": 0.8533955575853961}}
{"text": "import numpy as np\nfrom util import *\n\ndef sigmoid(z):\n    return (1 / (1 + np.exp(-z)))\n\n\ndef costFunction(theta, X, y):\n    m = y.size\n    h = sigmoid(X.dot(theta))\n\n    J = -1.0 * (1.0 / m) * (np.log(h + eps).T.dot(y) + np.log(1 - h + eps).T.dot(1 - y))\n\n\n    if np.isnan(J[0]):\n        return (np.inf)\n    return J[0]\n\ndef costFunctionReg(theta, reg, XX, y, *args):\n    m = y.size\n    h = sigmoid(XX.dot(theta))\n    \n    J = -1.0*(1.0/m)*(np.log(h + eps).T.dot(y)+np.log(1-h + eps).T.dot(1-y)) + (reg/(2.0*m))*np.sum(np.square(theta[1:]))\n    \n    if np.isnan(J[0]):\n        return(np.inf)\n    return(J[0])\n\ndef gradient(theta, X, y):\n    m = y.size\n    h = sigmoid(X.dot(theta.reshape(-1, 1)))\n\n    grad = (1.0 / m) * X.T.dot(h - y)\n\n    return (grad.flatten())\n\ndef gradientReg(theta, reg, XX, y, *args):\n    m = y.size\n    h = sigmoid(XX.dot(theta.reshape(-1,1)))\n      \n    grad = (1.0/m)*XX.T.dot(h-y) + (reg/m)*np.r_[[[0]],theta[1:].reshape(-1,1)]\n        \n    return(grad.flatten())\n\ndef predict(theta, X, threshold=0.5):\n    p = sigmoid(X.dot(theta.T)) >= threshold\n    return (p.astype('int'))\n", "meta": {"hexsha": "73cc56965140c2fec94ba63a65643d8c5c5e22c1", "size": 1107, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear regression/cost.py", "max_stars_repo_name": "bubbledoodle/real-world-machine-learning", "max_stars_repo_head_hexsha": "102ed37b0ee735ae238d00d55a41a8bd16dbfec6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear regression/cost.py", "max_issues_repo_name": "bubbledoodle/real-world-machine-learning", "max_issues_repo_head_hexsha": "102ed37b0ee735ae238d00d55a41a8bd16dbfec6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear regression/cost.py", "max_forks_repo_name": "bubbledoodle/real-world-machine-learning", "max_forks_repo_head_hexsha": "102ed37b0ee735ae238d00d55a41a8bd16dbfec6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0625, "max_line_length": 121, "alphanum_fraction": 0.5257452575, "include": true, "reason": "import numpy", "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377284730285, "lm_q2_score": 0.8902942239389253, "lm_q1q2_score": 0.8533806030870753}}
{"text": "import numpy as np\nfrom functools import wraps\n\n\n\"\"\"Kernel Module\n\nThis Module implements kernel functions.\"\"\"\n\ndef linear():\n    \"\"\"Linear kernel.\n\n    Returns:\n        closure: A Linear kernel K(x, y) = x.T * y\n    \"\"\"\n\n    def linnear_kernel(x:np.ndarray, y:np.ndarray):\n\n        return np.matmul(x, y.T)\n\n    return linnear_kernel\n\ndef gaussian(sigma):\n    \"\"\"Gaussian kernel.\n\n    Args:\n        sigma: The standard error of the gaussian kernel.\n        \n    Returns:\n        closure: A gaussian kernel K(x, y) = exp(- |x - y|^2 / 2 sigma^2)\n    \"\"\"\n\n    g = -1.0 / (2 * (sigma ** 2))\n\n    def gaussian_kernel(x, y):\n        \n        x_norm = np.sum(x**2, axis=1).reshape((-1, 1))\n        y_norm = np.sum(y**2, axis=1).reshape((1, -1))\n        w = -2 * np.matmul(x, y.T)\n        w += x_norm\n        w += y_norm\n        \n        return np.exp(w * g)\n\n    return gaussian_kernel", "meta": {"hexsha": "25bc10658c0988ea8110bb1cba250974e47615bd", "size": 880, "ext": "py", "lang": "Python", "max_stars_repo_path": "svm/kernel.py", "max_stars_repo_name": "luowyang/SVM", "max_stars_repo_head_hexsha": "ee7d5514b3513b0f1cbbce12a5ba397a5b41e3d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "svm/kernel.py", "max_issues_repo_name": "luowyang/SVM", "max_issues_repo_head_hexsha": "ee7d5514b3513b0f1cbbce12a5ba397a5b41e3d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "svm/kernel.py", "max_forks_repo_name": "luowyang/SVM", "max_forks_repo_head_hexsha": "ee7d5514b3513b0f1cbbce12a5ba397a5b41e3d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0, "max_line_length": 73, "alphanum_fraction": 0.5431818182, "include": true, "reason": "import numpy", "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877692486436, "lm_q2_score": 0.8791467738423874, "lm_q1q2_score": 0.8533770207432088}}
{"text": "\"\"\"\r\nThis script shows how to use FASTA to solve regularized least-square problem:\r\n        min  .5||Ax-b||^2 + mu*|x|\r\nWhere A is an MxN matrix, b is an Mx1 vector of measurements, and x is the Nx1 vector of unknowns.\r\nThe parameter 'mu' controls the strength of the regularizer.\r\n\r\n@author: Proloy DAS\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom scipy import linalg\r\nfrom fastapy import Fasta\r\nimport matplotlib.pyplot as plt\r\nimport time\r\n\r\n\r\ndef shrink(x, mu):\r\n    \"\"\"\r\n    Soft theresholding function\r\n    mu = threshold\r\n    \"\"\"\r\n    return np.multiply(np.sign(x), np.maximum(np.abs(x) - mu, 0))\r\n\r\n\r\ndef setup_rls():\r\n    np.random.seed(0)\r\n    # Define problem parameters\r\n    M = 200  # number of measurements\r\n    N = 1000  # dimension of sparse signal\r\n    K = 10    # signal sparsity\r\n    mu = .02  # regularization parameter\r\n    sigma = 0.01  # The noise level in 'b'\r\n\r\n    print('Testing sparse least-squares with N={:}, M={:}'.format(N, M))\r\n\r\n    # Create sparse signal\r\n    x = np.zeros((N, 1))\r\n    perm = np.random.permutation(N)\r\n    x[perm[0:K]] = 1\r\n\r\n    # define random Gaussian matrix\r\n    A = np.random.randn(M, N)\r\n    A = A/linalg.norm(A, 2)  # Normalize the matrix so that our value of 'mu' is fairly invariant to N\r\n\r\n    # Define observation vector\r\n    b = np.dot(A, x)\r\n    b = b + sigma * np.random.randn(*b.shape)  # add noise\r\n\r\n    #  The initial iterate:  a guess at the solution\r\n    x0 = np.zeros((N, 1))\r\n\r\n    # Create function handles\r\n    def f(x): return 0.5 * linalg.norm(np.dot(A, x) - b, 2)**2  # .5||Ax-b||^2\r\n\r\n    def gradf(x): return np.dot(A.T, np.dot(A, x) - b)  # gradient of f(x)\r\n\r\n    def g(x): return mu * np.abs(x).sum()  # mu*|x|\r\n\r\n    def proxg(x, t): return shrink(x, mu*t)  # proximal operator for g(x)\r\n\r\n    return f, gradf, g, proxg, x0, x\r\n\r\n\r\ndef test_rls(debugging=False):\r\n    f, gradf, g, proxg, x0, x = setup_rls()\r\n    # Set up Fasta solver\r\n    lsq = Fasta(f, g, gradf, proxg)\r\n    # Call Solver\r\n    lsq.learn(x0, verbose=True)\r\n\r\n    assert lsq.residuals[-1] / lsq.residuals[0] < 1e-4\r\n\r\n    if debugging:\r\n        plt.figure('sparse least-square')\r\n        plt.subplot(2, 1, 1)\r\n        plt.stem(x,  markerfmt='go', linefmt='g:', label='Ground truth')\r\n        plt.stem(lsq.coefs_, markerfmt='bo', label='Fasta solution')\r\n        plt.xlabel('Index')\r\n        plt.ylabel('Signal Value')\r\n\r\n        plt.subplot(2, 1, 2)\r\n        plt.semilogy(lsq.residuals)\r\n\r\n        plt.show()\r\n\r\n\r\ndef test_fix_stepsize(debugging=False):\r\n    f, gradf, g, proxg, x0, x = setup_rls()\r\n    # Set up Fasta solver\r\n    lsq = Fasta(f, g, gradf, proxg)\r\n    # custom stepsize\r\n    def fixed_step(*args): return 2\r\n    # Call Solver\r\n    lsq.learn(x0, verbose=True, linesearch=False, next_stepsize=fixed_step)\r\n\r\n    assert lsq.residuals[-1] / lsq.residuals[0] < 1e-4\r\n\r\n    if debugging:\r\n        plt.figure('sparse least-square')\r\n        plt.subplot(2, 1, 1)\r\n        plt.stem(x,  markerfmt='go', linefmt='g:', label='Ground truth')\r\n        plt.stem(lsq.coefs_, markerfmt='bo', label='Fasta solution')\r\n        plt.xlabel('Index')\r\n        plt.ylabel('Signal Value')\r\n\r\n        plt.subplot(2, 1, 2)\r\n        plt.semilogy(lsq.residuals)\r\n\r\n        plt.show()", "meta": {"hexsha": "c94fa4aeacaa18bcfa8527c9e4f0bfe0894f74bf", "size": 3212, "ext": "py", "lang": "Python", "max_stars_repo_path": "test_fasta.py", "max_stars_repo_name": "proloyd/fastapy", "max_stars_repo_head_hexsha": "347ee72d98e4a51bd7c5be9cdbf7667ebb45baab", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-05-29T08:45:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T00:08:17.000Z", "max_issues_repo_path": "test_fasta.py", "max_issues_repo_name": "proloyd/fastapy", "max_issues_repo_head_hexsha": "347ee72d98e4a51bd7c5be9cdbf7667ebb45baab", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_fasta.py", "max_forks_repo_name": "proloyd/fastapy", "max_forks_repo_head_hexsha": "347ee72d98e4a51bd7c5be9cdbf7667ebb45baab", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-05T11:48:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T00:08:18.000Z", "avg_line_length": 29.2, "max_line_length": 103, "alphanum_fraction": 0.5930884184, "include": true, "reason": "import numpy,from scipy", "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9763105321470077, "lm_q2_score": 0.8740772400852111, "lm_q1q2_score": 0.8533708154051803}}
{"text": "import numpy as np\n\nA = np.array([[1, 2], [-1, 4]])\nb = np.array([3, 5])\n\nA_inv = np.linalg.inv(A)\n\nprint(A_inv)\n\nX = A_inv.dot(b)\n\nprint(X)\n\nx = X[0]\ny = X[1]\n\nprint(f\"{x + 2 * y} == 3\")\nprint(f\"{-x + 4 * y} == 5\")\n\n\nprint(np.linalg.solve(A, b))\n", "meta": {"hexsha": "92669b110497ed71163f53590ef4b81bf488f9dd", "size": 247, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/msc/linear_algebra/ch1_1.8.py", "max_stars_repo_name": "gerritjvv/optimization_algorithms", "max_stars_repo_head_hexsha": "eab2e8fff39eeab8d9be45af3dae3be1a62be3ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/msc/linear_algebra/ch1_1.8.py", "max_issues_repo_name": "gerritjvv/optimization_algorithms", "max_issues_repo_head_hexsha": "eab2e8fff39eeab8d9be45af3dae3be1a62be3ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/msc/linear_algebra/ch1_1.8.py", "max_forks_repo_name": "gerritjvv/optimization_algorithms", "max_forks_repo_head_hexsha": "eab2e8fff39eeab8d9be45af3dae3be1a62be3ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.2272727273, "max_line_length": 31, "alphanum_fraction": 0.5101214575, "include": true, "reason": "import numpy", "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9763105314577312, "lm_q2_score": 0.8740772384450967, "lm_q1q2_score": 0.8533708132014384}}
{"text": "import pandas as pd\nimport numpy as np\n\nfrom datetime import datetime\n\nfrom scipy import optimize\nfrom scipy import integrate\n\n%matplotlib inline\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n########################################\n\ndef SIR_model(SIR,beta,gamma,N0):\n    '''Simple SIR model\n        S: susceptible population\n        I: infected population\n        R: recovered population\n        beta: infection rate\n        gamma: recovery rate\n        N0: Total population\n\n        overall condition is that the sum of changes (differnces) sum up to 0\n        dS+dI+dR=0\n        S+I+R= N (constant size of population)\n\n     Parameters:\n        ----------\n        SIR : numpy.ndarray\n        beta: float\n        gamma: float\n    '''\n\n    S,I,R = SIR\n    dS_dt=-beta*S*I/N0\n    dI_dt=beta*S*I/N0-gamma*I\n    dR_dt=gamma*I\n    return(dS_dt,dI_dt,dR_dt)\n\n\nif __name__ == '__main__':\n\n    pd_JH_data=pd.read_csv('../data/processed/COVID_relational_confirmed.csv',sep=';',parse_dates=[0])\n    pd_JH_data=pd_JH_data.sort_values('date',ascending=True).copy()\n", "meta": {"hexsha": "08b7d5f7d27a88661623006fe75a661915c16941", "size": 1065, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/features/build_features_SIR.py", "max_stars_repo_name": "vjebakumar/eds_2020", "max_stars_repo_head_hexsha": "40d4aa4a626047c623159174831efa76cdd3a2bf", "max_stars_repo_licenses": ["FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/features/build_features_SIR.py", "max_issues_repo_name": "vjebakumar/eds_2020", "max_issues_repo_head_hexsha": "40d4aa4a626047c623159174831efa76cdd3a2bf", "max_issues_repo_licenses": ["FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/features/build_features_SIR.py", "max_forks_repo_name": "vjebakumar/eds_2020", "max_forks_repo_head_hexsha": "40d4aa4a626047c623159174831efa76cdd3a2bf", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6666666667, "max_line_length": 102, "alphanum_fraction": 0.6300469484, "include": true, "reason": "import numpy,from scipy", "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.976310530768455, "lm_q2_score": 0.8740772286044095, "lm_q1q2_score": 0.8533708029913912}}
{"text": "import math\rimport scipy.stats as st\rimport numpy as np\rimport pandas as pd\rfrom scipy.stats import shapiro\rfrom scipy.stats import pearsonr\rfrom scipy.stats import spearmanr\rfrom scipy.stats import kendalltau\rfrom tools import get_type_columns\rfrom sklearn.feature_selection import f_regression, mutual_info_regression\r\r\r# CALCULATE Z VALUE\rdef get_z(confidence_level:float)->float:\r    \"\"\"\r    Calculate Z value for a given confidence level.\r    \r    confidence_level -- confidence level into percent. \r    return -- z value.\r    \"\"\"\r    return st.norm.ppf(1-(1-confidence_level/100.)/2)\r\r\r# CALCULATE THE SAMPLE SIZE\rdef sample_size(population_size:int, confidence_level:float, confidence_interval:float)->int:\r    \"\"\"\r    Calculate the sample size using the Cochran’s Sample Size Formula.\r    \r    population_size -- the total population size.\r    confidence_level -- the seleceted confidence level in percent. \r    confidence_interval -- the selected confidence interval in percent.\r    return -- sample size with the correction for smaller population (no large).\r    \"\"\"\r    Z = 0.0\r    p = 0.5\r    e = confidence_interval/100.0\r    N = population_size\r    n_0 = 0.0\r    n = 0.0\r\r    # FIND THE NUM STD DEVIATIONS FOR THAT CONFIDENCE LEVEL\r    Z = get_z(confidence_level)\r\r    if Z == 0.0:\r        return -1\r\r    # CALC SAMPLE SIZE\r    n_0 = ((Z**2) * p * (1-p)) / (e**2)\r\r    # ADJUST SAMPLE SIZE FOR FINITE POPULATION\r    n = n_0 / (1 + ((n_0 - 1) / float(N)) )\r\r    return int(math.ceil(n)) # THE SAMPLE SIZE\r\r\r## Tests whether a data sample has a Gaussian distribution according Shapiro test\rdef test_shapiro(data:np.array, significance:float = 0.05, verbose:bool = False) ->bool:\r    \"\"\"\r    Tests whether a data sample has a Gaussian distribution according Shapiro test.\r\r    Parameters\r    ----------\r    data : np.array()\r        Data to be tested.\r    significance : float, optional\r        Level of significance. The default is 0.05.\r    verbose : bool, optional\r        Display information or not. The default is False.\r\r    Returns\r    -------\r    bool\r        If data has a Gaussian distribution or not.\r\r    \"\"\"\r    # estimate cofindence level\r    confidence = (1 - significance) * 100\r    # test\r    stat, p = shapiro(data)\r    # display\r    if verbose:\r        print('stat=%.3f, p=%.3f' % (stat, p))\r    # check result and return\r    if p > significance:\r        if verbose:\r            print(f'Probably Gaussian (confidence level = {confidence}%)')\r        return True\r    else:\r        if verbose:\r            print(f'Probably not Gaussian (confidence level = {confidence}%)')\r        return False\r        \r    \r    \r## Normality test analysis for several columns in a dataframe\rdef analysis_normality(df:pd.DataFrame, numerical_columns: list, significance:float = 0.05, verbose:bool = False)->(dict,list):\r    \"\"\"\r    Normality test analysis for several columns in a dataframe.\r\r    Parameters\r    ----------\r    df : pd.DataFrame\r        Dataframe to be tested.\r    numerical_columns : list\r        Variables to be tested.\r    significance : float, optional\r        Level of significance. The default is 0.05.\r    verbose : bool, optional\r        Display information. The default is False.\r\r    Returns\r    -------\r    (dict,list)\r        Results of test stored in a dictionary. List of reports.\r\r    \"\"\"\r\r    # validate columns\r    for c in numerical_columns:\r        assert c in df.columns.tolist(), f'column \"{c}\" is required.'\r    # estimate cofindence level\r    confidence = (1 - significance) * 100 \r    # initialize\r    disnormal = dict()\r    lreports = list()\r    # loop of columns\r    for col in numerical_columns:\r        # collect data\r        data = df[col].values\r        # Shapiro test\r        result_shapiro = test_shapiro(data, significance = significance, verbose = verbose)\r        # add result\r        disnormal[col] = result_shapiro\r        # build report\r        if result_shapiro:\r            sreport = f'\"{col}\": Probably Gaussian (confidence level = {confidence}%) according to \"Shapiro test\"'\r            # append\r            lreports.append(sreport)\r        else:\r            sreport = f'\"{col}\": Probably NOT Gaussian (confidence level = {confidence}%) according to \"Shapiro test\"'\r        # display\r        if verbose:\r            print(sreport)\r    # return\r    return disnormal, lreports\r        \r    \r    \r## Calculate Pearson's coefficient\rdef correlation_pearson(data1:np.array, data2:np.array, significance:float = 0.05, verbose:bool = False)->float:\r    \"\"\"\r    Calculate Pearson's coefficient.\r\r    Parameters\r    ----------\r    data1 : np.array\r        First data array to be used.\r    data2 : np.array\r        Second data array to be used.\r    significance : float, optional\r        Level of significance. The default is 0.05.\r    verbose : bool, optional\r        Display information. The default is False.\r\r    Returns\r    -------\r    float\r        Correlation value.\r\r    \"\"\"\r    # estimate cofindence level\r    confidence = (1 - significance) * 100\r    # calculate Pearson's correlation\r    corr, p = pearsonr(data1, data2)\r    # display\r    # check result and return\r    if p < significance:\r        if verbose:\r            print(\"Pearson's correlation: %.3f (confidence interval = %s %s)\"%(corr, confidence, '%'))\r        return corr\r    else:\r        if verbose:\r            print(\"Pearson's correlation is not trusted: %.3f (confidence interval = %s %s)\"%(corr, confidence, '%'))\r        return np.nan    \r    \r    \r    \r## Calculate a Spearman correlation coefficient\rdef correlation_spearman(data1:np.array, data2:np.array, significance:float = 0.05, verbose:bool = False)->float:\r    \"\"\"\r    Calculate a Spearman correlation coefficient.\r\r    Parameters\r    ----------\r    data1 : np.array\r        First data array to be used.\r    data2 : np.array\r        Second data array to be used.\r    significance : float, optional\r        Level of significance. The default is 0.05.\r    verbose : bool, optional\r        Display information. The default is False.\r\r    Returns\r    -------\r    float\r        Correlation value.\r\r    \"\"\"\r    # estimate cofindence level\r    confidence = (1 - significance) * 100\r    # calculate Pearson's correlation\r    corr, p = spearmanr(data1, data2)\r    # display\r    # check result and return\r    if p < significance:\r        if verbose:\r            print(\"Spearman's correlation: %.3f (confidence interval = %s %s)\"%(corr, confidence, '%'))\r        return corr\r    else:\r        if verbose:\r            print(\"Spearman's correlation is not trusted: %.3f (confidence interval = %s %s)\"%(corr, confidence, '%'))\r        return np.nan  \r    \r    \r    \r## Calculate Kendall’s tau, a correlation measure for ordinal data\rdef correlation_kendalltau(data1:np.array, data2:np.array, significance:float = 0.05, verbose:bool = False)->float:\r    \"\"\"\r    Calculate Kendall’s tau, a correlation measure for ordinal data.\r\r    Parameters\r    ----------\r    data1 : np.array\r        First data array to be used.\r    data2 : np.array\r        Second data array to be used.\r    significance : float, optional\r        Level of significance. The default is 0.05.\r    verbose : bool, optional\r        Display information. The default is False.\r\r    Returns\r    -------\r    float\r        Correlation value.\r\r    \"\"\"\r    # estimate cofindence level\r    confidence = (1 - significance) * 100\r    # calculate Pearson's correlation\r    corr, p = kendalltau(data1, data2)\r    # display\r    # check result and return\r    if p < significance:\r        if verbose:\r            print(\"Kendall’s tau correlation: %.3f (confidence interval = %s %s)\"%(corr, confidence, '%'))\r        return corr\r    else:\r        if verbose:\r            print(\"Kendall’s tau correlation is not trusted: %.3f (confidence interval = %s %s)\"%(corr, confidence, '%'))\r        return np.nan      \r    \r    \r    \r## Calculate a F-test regression (linear dependency)\rdef f_test_regression(data1:np.array, data2:np.array, significance:float = 0.05, verbose:bool = False)->float:\r \r    \r    # estimate cofindence level\r    confidence = (1 - significance) * 100\r    # calculate F-test\r    corr, p = spearmanr(data1, data2)\r    # display\r    # check result and return\r    if p < significance:\r        if verbose:\r            print(\"Spearman's correlation: %.3f (confidence interval = %s %s)\"%(corr, confidence, '%'))\r        return corr\r    else:\r        if verbose:\r            print(\"Spearman's correlation is not trusted: %.3f (confidence interval = %s %s)\"%(corr, confidence, '%'))\r        return np.nan  \r\r    \r\r## Correlation analysis for a couple of columns in a dataframe (for numerical and ordinal data)\rdef analysis_correlation(data:pd.DataFrame, couple_columns: list, dnormality:dict = None, significance:float = 0.05, verbose:bool = False)->float:\r    \"\"\"\r    ## Correlation analysis for a couple of columns in a dataframe (for numerical and ordinal data).\r\r    Parameters\r    ----------\r    data : pd.DataFrame\r        Dataframe to be used.\r    couple_columns : list\r        Couple of columns names to be used.\r    dnormality : dict, optional\r        Dictionary with results of normality test per column . The default is None.\r    significance : float, optional\r        Level of significance. The default is 0.05.\r    verbose : bool, optional\r        Display information. The default is False.\r\r    Returns\r    -------\r    float\r        Correlation value.\r\r    \"\"\"\r \r    # validate columns\r    for c in couple_columns:\r        assert c in data.columns.tolist(), f'column \"{c}\" is required.'\r    # initialize\r    col1 = couple_columns[0]\r    col2 = couple_columns[1]\r    # collect data and remove records with NaN values\r    df = data[couple_columns].dropna()\r    nsample = len(df)\r    v1 = data[col1].values\r    v2 = data[col2].values\r    # validate type of data\r    dtypecols = get_type_columns(df)\r    typecol1 = dtypecols[col1]\r    typecol2 = dtypecols[col2]\r    # clean \r    del df\r\r    ## analysis\r    \r    # case: ord - ord\r    if typecol1 == 'ord' and typecol2 == 'ord':\r        # get number of unique values of ordinal variables\r        n_unique_var1 = len(list(set(list(v1))))\r        n_unique_var2 = len(list(set(list(v2))))\r        # select technique\r        if n_unique_var1 >= 5 and n_unique_var2 >= 5:\r            corr = correlation_spearman(v1, v2, significance = significance, verbose = verbose)\r        else:\r            corr = correlation_kendalltau(v1, v2, significance = significance, verbose = verbose)\r    # case: num - num\r    elif typecol1 == 'num' and typecol2 == 'num':\r        # get normality\r        if dnormality is None:\r            is_norm_var1 = False\r            is_norm_var2 = False\r        else:\r            is_norm_var1 = dnormality[col1]\r            is_norm_var2 = dnormality[col2]    \r        # select technique\r        if nsample >= 100:\r            corr = correlation_pearson(v1, v2, significance = significance, verbose = verbose)\r        else:\r            if is_norm_var1 and is_norm_var2:\r                corr = correlation_pearson(v1, v2, significance = significance, verbose = verbose)\r            else:\r                corr = correlation_spearman(v1, v2, significance = significance, verbose = verbose)\r    # case: num - ord\r    elif typecol1 == 'num' and typecol2 == 'ord':\r        # get number of unique values of ordinal variables\r        n_unique_var2 = len(list(set(list(v2))))   \r        # select technique\r        if n_unique_var2 < 5:\r            corr = correlation_kendalltau(v1, v2, significance = significance, verbose = verbose)\r        else:\r            if nsample >= 100:\r                corr = correlation_pearson(v1, v2, significance = significance, verbose = verbose)\r            else:\r                corr = correlation_spearman(v1, v2, significance = significance, verbose = verbose)\r    # case: ord - num\r    elif typecol1 == 'ord' and typecol2 == 'num':\r        # get number of unique values of ordinal variables\r        n_unique_var1 = len(list(set(list(v1))))   \r        # select technique\r        if n_unique_var1 < 5:\r            corr = correlation_kendalltau(v1, v2, significance = significance, verbose = verbose)\r        else:\r            if nsample >= 100:\r                corr = correlation_pearson(v1, v2, significance = significance, verbose = verbose)\r            else:\r                corr = correlation_spearman(v1, v2, significance = significance, verbose = verbose)    \r    # other case\r    else:\r        corr = np.na\r        # display\r        if verbose:\r            print('It was not possible to identify correctly columns types.')      \r    # return\r    return corr\r     \r        \r                \r                \r            \r        \r            \r            \r        \r    \r    \r    ", "meta": {"hexsha": "175ea44d8ac8719918af8166fbfb4dee141c150d", "size": 12724, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/analysis/ADA/analysis.py", "max_stars_repo_name": "jmquintana79/DStools", "max_stars_repo_head_hexsha": "582c76aff1002d662d19dfba073de29c7054b15d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/analysis/ADA/analysis.py", "max_issues_repo_name": "jmquintana79/DStools", "max_issues_repo_head_hexsha": "582c76aff1002d662d19dfba073de29c7054b15d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/analysis/ADA/analysis.py", "max_forks_repo_name": "jmquintana79/DStools", "max_forks_repo_head_hexsha": "582c76aff1002d662d19dfba073de29c7054b15d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12724.0, "max_line_length": 12724, "alphanum_fraction": 0.6161584407, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 3315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561721629776, "lm_q2_score": 0.8807970748488297, "lm_q1q2_score": 0.8533656823903848}}
{"text": "#\n# Valuation of European Call Options in Black-Scholes-Merton Model\n# Including Vega Function and implied volatility Estimation\n# bsm_functions.py\n#\n\n# Analytical Black-Scholes-Merton (BSM) Formula\n\ndef bsm_call_value(S0, K, T, r, sigma):\n    \"\"\"\n    Valuation of European call option in BSM model.\n    \n    Parameters\n    ==========\n    s0 : Float\n      initial stock/index level\n    K : Float\n      Strike Price\n    T: Float\n      Constant risk-free short rate\n    sigma: Float\n      Volatility Factor in Diffusion Term\n      \n    Returns\n    =======\n   \n    value: Float\n      Present value of the European call option]\n    \"\"\"\n    \n    from math import log, sqrt, exp\n    from scipy import stats\n    \n    s0 = float(s0)\n    d1 = (log(s0/ K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))\n    d2 = (log(s0/ K) + (r - 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))\n    value = (s0 * stats.norm.cdf(d1, 0.0, 1.0)\n            - K * exp(-r * T) * stats.norm.cdf(d2, 0.0, 1.0))\n    \n    # stats.norm.cdf -> Cumulative distribution function for normal distribution\n    #\n    \n    return value\n\n# Vega Function\n\ndef bsm_vega(S0, K, T, r, sigma):\n    \"\"\"\n    Vega of european option in BSM Model. \n    \n    Parameters\n    ==========\n    s0 : Float\n        initial stock/index level\n    K : Float\n        strike price\n    T : Float\n        Maturity date (in year fractions)\n    r : float\n        constant risk-free short rate\n    sigma : float \n        volatility factor in diffusion term\n    Returns\n    =======\n    vega : Float\n        Partial derivative of BSM formula with respect to sigma, i.e. Vega\n    \"\"\"\n    \n    from math import log, sqrt\n    from scipy import stats\n    \n    S0 = float(S0)\n    d1 = (log(S0 / K) + (r + 0.5 * sigma ** 2) * T / (sigma * sqrt(T))\n    vega = S0 * stats.normcdf(d1, 0.0, 1.0) * sqrt(T)\n    return vega\n              \n# Implied volatility function\n\ndef bsm_call_imp_vol(S0, K, T, r, C0, sigma_est, it = 100):\n    \"\"\" \n    Implied volatility of European call option in BSM model\n    \n    Parameters\n    ==========\n    S0 : Float\n        Initial stock/index level\n    K : Float\n        Strike Price\n    T : Float\n        Maturity Date (in year fractions)\n    r : Float\n        Constant risk-free short rate\n    sigma_est : Float\n        Estimate of impl. volatility\n    it : integer\n        Number of iterations\n        \n    Returns\n    =======\n    sigma_est : Float\n        Numerically estimated implied volatility\n    \"\"\"\n    for i in range(it):\n        sigma_est -= ((bsm_call_value(S0, K, T, r, sigma_est) - C0)\n                        / bsm_vega(S0, K, T, r, sigma_est))\n    return sigma_est\n         \n          \n          \n          \n        \n", "meta": {"hexsha": "0caa3ea49d76bd40e8c11bd4db0170a85a2bb7cf", "size": 2680, "ext": "py", "lang": "Python", "max_stars_repo_path": "blackscholes.py", "max_stars_repo_name": "christopherdurr/Finance-for-Python", "max_stars_repo_head_hexsha": "9a714a2fdfb2e6a3a260b063ad1f3d2c88527e04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "blackscholes.py", "max_issues_repo_name": "christopherdurr/Finance-for-Python", "max_issues_repo_head_hexsha": "9a714a2fdfb2e6a3a260b063ad1f3d2c88527e04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "blackscholes.py", "max_forks_repo_name": "christopherdurr/Finance-for-Python", "max_forks_repo_head_hexsha": "9a714a2fdfb2e6a3a260b063ad1f3d2c88527e04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9285714286, "max_line_length": 80, "alphanum_fraction": 0.5563432836, "include": true, "reason": "from scipy", "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561721629776, "lm_q2_score": 0.8807970685907242, "lm_q1q2_score": 0.8533656763271806}}
{"text": "import math\nfrom IntegralMethods.RectangleIntegration import leftrectangle, rightrectangle\nfrom IntegralMethods.TrapezoidIntegration import trapezoid\nfrom IntegralMethods.SimpsonIntegration import simpson\nfrom math import sin, exp, pi\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nleftrect = []\nrightrect = []\ntrapez = []\nsimps = []\nsol = (2/13)+(3/13*np.e**(3/4*np.pi))\nstep = [10**0,10**-1,10**-2,10**-3,10**-4, 10**-5,10**-6,10**-7,10**-8]\n\n\ndef f(x):\n    return np.e**(3*x)*np.sin(2*x)\n\n\nif __name__ == \"__main__\":\n\n    for i in step:\n        leftrect.append(abs(sol - leftrectangle(0, pi/4, i, f)))\n        rightrect.append(abs(sol - rightrectangle(0, pi/4, i, f)))\n        trapez.append(abs(sol - trapezoid(0, pi/4, i, f)))\n        simps.append(abs(sol-simpson(0, pi/4, i, f)))\n\n\n    print(leftrect)\n    print(rightrect)\n    print(trapez)\n    print(simps)\n\n    plt.loglog(step, leftrect)\n    plt.loglog(step, rightrect)\n    plt.loglog(step, trapez)\n    plt.loglog(step, simps)\n    plt.legend([\"Left\", \"Right\", \"Trap\",\"Simpson\"])\n    plt.ylim([10**-9,10])\n    plt.xlabel(\"h\")\n    plt.ylabel(\"Error\")\n    plt.xlim([10,10**-8])\n    plt.show()\n", "meta": {"hexsha": "7b58cd327f80fca5b286a92cc617b6e056f4ecba", "size": 1153, "ext": "py", "lang": "Python", "max_stars_repo_path": "app1.py", "max_stars_repo_name": "panos1998/Numerical-Analysis", "max_stars_repo_head_hexsha": "df3d8aafb1324970082781b8be98d3a609d9c5d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app1.py", "max_issues_repo_name": "panos1998/Numerical-Analysis", "max_issues_repo_head_hexsha": "df3d8aafb1324970082781b8be98d3a609d9c5d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app1.py", "max_forks_repo_name": "panos1998/Numerical-Analysis", "max_forks_repo_head_hexsha": "df3d8aafb1324970082781b8be98d3a609d9c5d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0652173913, "max_line_length": 78, "alphanum_fraction": 0.6357328708, "include": true, "reason": "import numpy", "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561712637257, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.8533656740193211}}
{"text": "import numpy as np\n\ndef check_linearity_independent(matrix):\n    (m, n) = matrix.shape\n    if m != n:\n        # Ta có ma trận A không là ma trận vuông\n        # Tính hạng của ma trận A\n        RA = np.linalg.matrix_rank(matrix)\n        if RA == m:\n            return True\n        if RA < m:\n            return False\n\n    if m == n:\n        # Ta có ma trận A là ma trận vuông\n        # Tính định thức của ma trận A\n        det = np.linalg.det(matrix)\n        if det != 0:\n            return True\n        elif det == 0:\n            return False\n\n# Test :v\nu1 = np.array([-1, 2, -1, 2])\nu2 = np.array([2, 2, -4, 2])\nu3 = np.array([1, 3, 1, 2])\n\n# Hãy kiểm tra xem u1 , u2 , u3 độc lập tuyến tính hay phụ thuộc tuyến tính?\n\nmatrix = np.array([u1.T, u2.T, u3.T])\n\nprint(check_linearity_independent(matrix))\n", "meta": {"hexsha": "588c9c96bb576f7cdadb9bf7d66aed133e2a15ef", "size": 802, "ext": "py", "lang": "Python", "max_stars_repo_path": "contents/codes/check_linearity_independent.py", "max_stars_repo_name": "nhutnamhcmus/minimal-mistakes", "max_stars_repo_head_hexsha": "e4e6bd092a8db9da2a7cb34537aa88c8bfa4f65d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "contents/codes/check_linearity_independent.py", "max_issues_repo_name": "nhutnamhcmus/minimal-mistakes", "max_issues_repo_head_hexsha": "e4e6bd092a8db9da2a7cb34537aa88c8bfa4f65d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-28T07:14:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-28T07:15:17.000Z", "max_forks_repo_path": "contents/codes/check_linearity_independent.py", "max_forks_repo_name": "nhutnamhcmus/nhutnamhcmus.github.io", "max_forks_repo_head_hexsha": "8bede269fee0616617d1aef7f892461f78309ad7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.303030303, "max_line_length": 76, "alphanum_fraction": 0.5436408978, "include": true, "reason": "import numpy", "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147161743549, "lm_q2_score": 0.8774767906859264, "lm_q1q2_score": 0.853271344364439}}
{"text": "\"\"\"README, Author - Jigyasa Gandhi(mailto:jigsgandhi97@gmail.com)\nRequirements:\n  - scikit-fuzzy\n  - numpy\n  - matplotlib\nPython:\n  - 3.5\n\"\"\"\n# Create universe of discourse in python using linspace ()\nimport numpy as np\nX = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False)\n\n# Create two fuzzy sets by defining any membership function (trapmf(), gbellmf(),gaussmf(), etc).\nimport skfuzzy as fuzz\nabc1=[0,25,50]\nabc2=[25,50,75]\nyoung = fuzz.membership.trimf(X,abc1)\nmiddle_aged = fuzz.membership.trimf(X,abc2)\n\n# Compute the different operations using inbuilt functions.\none = np.ones(75)\nzero = np.zeros((75,))\n#1. Union = max(µA(x), µB(x))\nunion = fuzz.fuzzy_or(X, young, X, middle_aged)[1]\n#2. Intersection = min(µA(x), µB(x))\nintersection = fuzz.fuzzy_and(X, young, X, middle_aged)[1]\n#3. Complement (A) = (1- min(µA(x))\ncomplement_a = fuzz.fuzzy_not(young)\n#4. Difference (A/B) = min(µA(x),(1- µB(x)))\ndifference = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1]\n#5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))]\nalg_sum = young + middle_aged - (young*middle_aged)\n#6. Algebraic Product = (µA(x) * µB(x))\nalg_product = young*middle_aged\n#7. Bounded Sum = min[1,(µA(x), µB(x))]\nbdd_sum = fuzz.fuzzy_and(X, one, X, young+middle_aged)[1]\n#8. Bounded difference = min[0,(µA(x), µB(x))]\nbdd_difference = fuzz.fuzzy_or(X, zero, X, young-middle_aged)[1]\n\n#max-min composition\n#max-product composition\n\n\n# Plot each set A, set B and each operation result using plot() and subplot().\nimport matplotlib.pyplot as plt\n\nplt.figure()\n\nplt.subplot(4,3,1)\nplt.plot(X,young)\nplt.title(\"Young\")\nplt.grid(True)\n\nplt.subplot(4,3,2)\nplt.plot(X,middle_aged)\nplt.title(\"Middle aged\")\nplt.grid(True)\n\nplt.subplot(4,3,3)\nplt.plot(X,union)\nplt.title(\"union\")\nplt.grid(True)\n\nplt.subplot(4,3,4)\nplt.plot(X,intersection)\nplt.title(\"intersection\")\nplt.grid(True)\n\nplt.subplot(4,3,5)\nplt.plot(X,complement_a)\nplt.title(\"complement_a\")\nplt.grid(True)\n\nplt.subplot(4,3,6)\nplt.plot(X,difference)\nplt.title(\"difference a/b\")\nplt.grid(True)\n\nplt.subplot(4,3,7)\nplt.plot(X,alg_sum)\nplt.title(\"alg_sum\")\nplt.grid(True)\n\nplt.subplot(4,3,8)\nplt.plot(X,alg_product)\nplt.title(\"alg_product\")\nplt.grid(True)\n\nplt.subplot(4,3,9)\nplt.plot(X,bdd_sum)\nplt.title(\"bdd_sum\")\nplt.grid(True)\n\nplt.subplot(4,3,10)\nplt.plot(X,bdd_difference)\nplt.title(\"bdd_difference\")\nplt.grid(True)\n\nplt.subplots_adjust(hspace = 0.5)\nplt.show()\n", "meta": {"hexsha": "e497eabd1690974db598bc092c1a2f4b1dfc5bfb", "size": 2421, "ext": "py", "lang": "Python", "max_stars_repo_path": "fuzzy_logic/fuzzy_operations.py", "max_stars_repo_name": "stoneheart/Python", "max_stars_repo_head_hexsha": "313a043107bc4882623ad5524a96fbb099d0d161", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-06T12:31:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-18T19:41:45.000Z", "max_issues_repo_path": "fuzzy_logic/fuzzy_operations.py", "max_issues_repo_name": "antwyh/Python", "max_issues_repo_head_hexsha": "313a043107bc4882623ad5524a96fbb099d0d161", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fuzzy_logic/fuzzy_operations.py", "max_forks_repo_name": "antwyh/Python", "max_forks_repo_head_hexsha": "313a043107bc4882623ad5524a96fbb099d0d161", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-06T12:30:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-06T12:30:15.000Z", "avg_line_length": 23.9702970297, "max_line_length": 97, "alphanum_fraction": 0.7067327551, "include": true, "reason": "import numpy", "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140235181256, "lm_q2_score": 0.8824278664544912, "lm_q1q2_score": 0.8532318788180273}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun  8 23:41:53 2020\n\n@author: lankuohsing\n\"\"\"\n\n# In[]\nimport numpy as np\nfrom w2v_utils import *\n# In[]\nwords, word_to_vec_map = read_glove_vecs('./data/glove.6B.50d.txt')\n\n# In[]\n# GRADED FUNCTION: cosine_similarity\n\ndef cosine_similarity(u, v):\n    \"\"\"\n    Cosine similarity reflects the degree of similarity between u and v\n\n    Arguments:\n        u -- a word vector of shape (n,)\n        v -- a word vector of shape (n,)\n\n    Returns:\n        cosine_similarity -- the cosine similarity between u and v defined by the formula above.\n    \"\"\"\n\n    distance = 0.0\n\n    ### START CODE HERE ###\n    # Compute the dot product between u and v (≈1 line)\n    dot = np.dot(u,v)\n    # Compute the L2 norm of u (≈1 line)\n    norm_u = np.sqrt(np.sum(u**2))\n\n    # Compute the L2 norm of v (≈1 line)\n    norm_v = np.sqrt(np.sum(v**2))\n    # Compute the cosine similarity defined by formula (1) (≈1 line)\n    cosine_similarity = dot/(norm_u*norm_v)\n    ### END CODE HERE ###\n\n    return cosine_similarity\n# In[]\nfather = word_to_vec_map[\"father\"]\nmother = word_to_vec_map[\"mother\"]\nball = word_to_vec_map[\"ball\"]\ncrocodile = word_to_vec_map[\"crocodile\"]\nfrance = word_to_vec_map[\"france\"]\nitaly = word_to_vec_map[\"italy\"]\nparis = word_to_vec_map[\"paris\"]\nrome = word_to_vec_map[\"rome\"]\n\nprint(\"cosine_similarity(father, mother) = \", cosine_similarity(father, mother))\nprint(\"cosine_similarity(ball, crocodile) = \",cosine_similarity(ball, crocodile))\nprint(\"cosine_similarity(france - paris, rome - italy) = \",cosine_similarity(france - paris, rome - italy))\n\n# In[]\n# GRADED FUNCTION: complete_analogy\n\ndef complete_analogy(word_a, word_b, word_c, word_to_vec_map):\n    \"\"\"\n    Performs the word analogy task as explained above: a is to b as c is to ____.\n\n    Arguments:\n    word_a -- a word, string\n    word_b -- a word, string\n    word_c -- a word, string\n    word_to_vec_map -- dictionary that maps words to their corresponding vectors.\n\n    Returns:\n    best_word --  the word such that v_b - v_a is close to v_best_word - v_c, as measured by cosine similarity\n    \"\"\"\n\n    # convert words to lowercase\n    word_a, word_b, word_c = word_a.lower(), word_b.lower(), word_c.lower()\n\n    ### START CODE HERE ###\n    # Get the word embeddings e_a, e_b and e_c (≈1-3 lines)\n    e_a, e_b, e_c = (word_to_vec_map[word_a],word_to_vec_map[word_b],word_to_vec_map[word_c])\n    ### END CODE HERE ###\n\n    words = word_to_vec_map.keys()\n    max_cosine_sim = -100              # Initialize max_cosine_sim to a large negative number\n    best_word = None                   # Initialize best_word with None, it will help keep track of the word to output\n\n    # to avoid best_word being one of the input words, skip the input words\n    # place the input words in a set for faster searching than a list\n    # We will re-use this set of input words inside the for-loop\n    input_words_set = set([word_a, word_b, word_c])\n\n    # loop over the whole word vector set\n    for w in words:\n        # to avoid best_word being one of the input words, skip the input words\n        if w in input_words_set:\n            continue\n\n        ### START CODE HERE ###\n        # Compute cosine similarity between the vector (e_b - e_a) and the vector ((w's vector representation) - e_c)  (≈1 line)\n        cosine_sim = cosine_similarity(e_b-e_a,word_to_vec_map[w]-e_c)\n\n        # If the cosine_sim is more than the max_cosine_sim seen so far,\n            # then: set the new max_cosine_sim to the current cosine_sim and the best_word to the current word (≈3 lines)\n        if cosine_sim > max_cosine_sim:\n            max_cosine_sim = cosine_sim\n            best_word = w\n        ### END CODE HERE ###\n\n    return best_word\n# In[]\ntriads_to_try = [('italy', 'italian', 'spain'), ('india', 'delhi', 'japan'), ('man', 'woman', 'boy'), ('small', 'smaller', 'large')]\nfor triad in triads_to_try:\n    print ('{} -> {} :: {} -> {}'.format( *triad, complete_analogy(*triad,word_to_vec_map)))\n# In[]\ng = word_to_vec_map['woman'] - word_to_vec_map['man']\nprint(g)\n\n# In[]\nprint ('List of names and their similarities with constructed vector:')\n\n# girls and boys name\nname_list = ['john', 'marie', 'sophie', 'ronaldo', 'priya', 'rahul', 'danielle', 'reza', 'katy', 'yasmin']\n\nfor w in name_list:\n    print (w, cosine_similarity(word_to_vec_map[w], g))\n# In[]\nprint('Other words and their similarities:')\nword_list = ['lipstick', 'guns', 'science', 'arts', 'literature', 'warrior','doctor', 'tree', 'receptionist',\n             'technology',  'fashion', 'teacher', 'engineer', 'pilot', 'computer', 'singer']\nfor w in word_list:\n    print (w, cosine_similarity(word_to_vec_map[w], g))\n# In[]\ndef neutralize(word, g, word_to_vec_map):\n    \"\"\"\n    Removes the bias of \"word\" by projecting it on the space orthogonal to the bias axis.\n    This function ensures that gender neutral words are zero in the gender subspace.\n\n    Arguments:\n        word -- string indicating the word to debias\n        g -- numpy-array of shape (50,), corresponding to the bias axis (such as gender)\n        word_to_vec_map -- dictionary mapping words to their corresponding vectors.\n\n    Returns:\n        e_debiased -- neutralized word vector representation of the input \"word\"\n    \"\"\"\n\n    ### START CODE HERE ###\n    # Select word vector representation of \"word\". Use word_to_vec_map. (≈ 1 line)\n    e = word_to_vec_map[word]\n\n    # Compute e_biascomponent using the formula given above. (≈ 1 line)\n    e_biascomponent = np.dot(e,g)/(np.sum(g**2))*g\n\n    # Neutralize e by subtracting e_biascomponent from it\n    # e_debiased should be equal to its orthogonal projection. (≈ 1 line)\n    e_debiased = e-e_biascomponent\n    ### END CODE HERE ###\n\n    return e_debiased\n# In[]\ne = \"receptionist\"\nprint(\"cosine similarity between \" + e + \" and g, before neutralizing: \", cosine_similarity(word_to_vec_map[\"receptionist\"], g))\n\ne_debiased = neutralize(\"receptionist\", g, word_to_vec_map)\nprint(\"cosine similarity between \" + e + \" and g, after neutralizing: \", cosine_similarity(e_debiased, g))\n# In[]\ndef equalize(pair, bias_axis, word_to_vec_map):\n    \"\"\"\n    Debias gender specific words by following the equalize method described in the figure above.\n\n    Arguments:\n    pair -- pair of strings of gender specific words to debias, e.g. (\"actress\", \"actor\")\n    bias_axis -- numpy-array of shape (50,), vector corresponding to the bias axis, e.g. gender\n    word_to_vec_map -- dictionary mapping words to their corresponding vectors\n\n    Returns\n    e_1 -- word vector corresponding to the first word\n    e_2 -- word vector corresponding to the second word\n    \"\"\"\n\n    ### START CODE HERE ###\n    # Step 1: Select word vector representation of \"word\". Use word_to_vec_map. (≈ 2 lines)\n    w1, w2 = pair[0],pair[1]\n    e_w1, e_w2 = word_to_vec_map[w1],word_to_vec_map[w2]\n\n    # Step 2: Compute the mean of e_w1 and e_w2 (≈ 1 line)\n    mu = (e_w1+e_w2)/2\n\n    # Step 3: Compute the projections of mu over the bias axis and the orthogonal axis (≈ 2 lines)\n    mu_B = np.dot(mu,bias_axis)/(np.sum(bias_axis**2))*bias_axis\n    mu_orth = mu-mu_B\n\n    # Step 4: Use equations (7) and (8) to compute e_w1B and e_w2B (≈2 lines)\n    e_w1B = np.dot(e_w1,bias_axis)/(np.sum(bias_axis**2))*bias_axis\n    e_w2B = np.dot(e_w2,bias_axis)/(np.sum(bias_axis**2))*bias_axis\n\n    # Step 5: Adjust the Bias part of e_w1B and e_w2B using the formulas (9) and (10) given above (≈2 lines)\n    corrected_e_w1B = np.sqrt(np.abs(1-np.sum(mu_orth**2)))*(e_w1B-mu_B)/np.sqrt(np.sum(((e_w1-mu_orth)-mu_B)**2))\n    corrected_e_w2B = np.sqrt(np.abs(1-np.sum(mu_orth**2)))*(e_w2B-mu_B)/np.sqrt(np.sum(((e_w2-mu_orth)-mu_B)**2))\n\n    # Step 6: Debias by equalizing e1 and e2 to the sum of their corrected projections (≈2 lines)\n    e1 = corrected_e_w1B+mu_orth\n    e2 = corrected_e_w2B+mu_orth\n\n    ### END CODE HERE ###\n    return e1, e2\n# In[]\nprint(\"cosine similarities before equalizing:\")\nprint(\"cosine_similarity(word_to_vec_map[\\\"man\\\"], gender) = \", cosine_similarity(word_to_vec_map[\"man\"], g))\nprint(\"cosine_similarity(word_to_vec_map[\\\"woman\\\"], gender) = \", cosine_similarity(word_to_vec_map[\"woman\"], g))\nprint()\ne1, e2 = equalize((\"man\", \"woman\"), g, word_to_vec_map)\nprint(\"cosine similarities after equalizing:\")\nprint(\"cosine_similarity(e1, gender) = \", cosine_similarity(e1, g))\nprint(\"cosine_similarity(e2, gender) = \", cosine_similarity(e2, g))", "meta": {"hexsha": "2f367fbad6cf3bbf491f3657d49c36decc87c595", "size": 8394, "ext": "py", "lang": "Python", "max_stars_repo_path": "Sequence Models/week2/Operations_on_word_vectors_v2a.py", "max_stars_repo_name": "lankuohsing/Coursera-Deep-Learning-Specialization", "max_stars_repo_head_hexsha": "64f34c862c8ef2cdf97379d82d31d47b8c6d6dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sequence Models/week2/Operations_on_word_vectors_v2a.py", "max_issues_repo_name": "lankuohsing/Coursera-Deep-Learning-Specialization", "max_issues_repo_head_hexsha": "64f34c862c8ef2cdf97379d82d31d47b8c6d6dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sequence Models/week2/Operations_on_word_vectors_v2a.py", "max_forks_repo_name": "lankuohsing/Coursera-Deep-Learning-Specialization", "max_forks_repo_head_hexsha": "64f34c862c8ef2cdf97379d82d31d47b8c6d6dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0418604651, "max_line_length": 132, "alphanum_fraction": 0.6757207529, "include": true, "reason": "import numpy", "num_tokens": 2347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248131626427, "lm_q2_score": 0.9086179018818865, "lm_q1q2_score": 0.8532147555508709}}
{"text": "import numpy as np\n\n\nclass LinearRegression:\n\n    def __init__(self, x, y, alpha=3e-2, max_epochs=10, epsilon=1e-2,\n                 batch_size=10):\n        self.x = np.concatenate((np.ones((x.shape[0], 1)), x), axis=1)\n        self.y = y\n        self.alpha = alpha\n        self.maxEpochs = max_epochs\n        self.epsilon = epsilon\n        self.batchSize = batch_size\n\n        self.history = {\n            'theta': [],\n            'cost': [],\n        }\n\n        self.theta = np.random.normal(loc=0.0, scale=1.0, size=(self.x.shape[1], 1))\n        self.history['theta'].append(self.theta.squeeze().tolist())\n\n        initialPrediction = self.getPrediction(self.x, self.theta)\n        initialCost = self.getCost(initialPrediction, self.y)\n        self.history['cost'].append(initialCost)\n\n        self.prevTheta = self.theta\n        self.printStats()\n\n    def printStats(self):\n        print('=' * 80)\n        print('[INFO]\\t\\tHyperparameters for Linear Regression')\n        print('=' * 80)\n        print(f'[INFO] Learning Rate: {self.alpha}')\n        print(f'[INFO] Mini Batch Size: {self.batchSize}')\n        print(f'[INFO] Maximum Epochs: {self.maxEpochs}')\n        print(f'[INFO] Epsilon for checking convergence: {self.epsilon}')\n        print(f'[INFO] Starting value of theta: {self.theta.tolist()} | {self.theta.shape}')\n        print(f'[INFO] Shape of x data with ones: {self.x.shape}')\n        print(f'[INFO] Shape of y data: {self.y.shape}')\n        print(f'[INFO] Initial cost: {self.history[\"cost\"][0]}')\n        print('=' * 80)\n\n    def runGradientDescent(self):\n\n        xBatches = np.array_split(self.x, self.x.shape[0] // self.batchSize)\n        yBatches = np.array_split(self.y, self.y.shape[0] // self.batchSize)\n\n        for i in range(self.maxEpochs):\n            for j, (x, y) in enumerate(zip(xBatches, yBatches)):\n                # keeping track of prev theta for checking convergence\n                self.prevTheta = self.theta\n\n                h = self.getPrediction(x, self.theta)\n                cost = self.getCost(h, y)\n                gradients = (1 / x.shape[0]) * np.dot(np.transpose(x), (h - y))\n                self.theta = self.theta - self.alpha * gradients\n\n                # log metrics\n                self.history['theta'].append(self.theta.squeeze().tolist())\n                self.history['cost'].append(cost)\n\n                if self.isConverged():\n                    print(f'[INFO] Gradient Descent converged at Epoch: {i + 1}, iteration: {j + 1}')\n                    break\n\n            if self.isConverged():\n                break\n\n    def getThetaByNormalEquations(self):\n        return np.dot(np.linalg.inv(np.dot(np.transpose(self.x), self.x)),\n                      np.dot(np.transpose(self.x), self.y))\n\n    def isConverged(self):\n        return (abs(self.theta - self.prevTheta) <= self.epsilon).all()\n\n    def getHistory(self):\n        return self.history\n\n    @staticmethod\n    def getPrediction(x, theta):\n        return np.dot(x, theta)\n\n    @staticmethod\n    def getCost(y_pred, y_true):\n        m = y_pred.shape[0]\n        return (1 / (2 * m)) * np.sum((y_pred - y_true)**2)\n", "meta": {"hexsha": "58ce0a971980fae0e4d0e2ec232ec38cf35f3655", "size": 3132, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/linear_regression.py", "max_stars_repo_name": "Gautam-J/ML-Sklearn", "max_stars_repo_head_hexsha": "560dbe79f85fac67340946ae32d024952fc1ace7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 415, "max_stars_repo_stars_event_min_datetime": "2020-05-21T08:25:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:19:12.000Z", "max_issues_repo_path": "models/linear_regression.py", "max_issues_repo_name": "Gautam-J/ML-Sklearn", "max_issues_repo_head_hexsha": "560dbe79f85fac67340946ae32d024952fc1ace7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/linear_regression.py", "max_forks_repo_name": "Gautam-J/ML-Sklearn", "max_forks_repo_head_hexsha": "560dbe79f85fac67340946ae32d024952fc1ace7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2020-05-21T17:07:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T09:53:32.000Z", "avg_line_length": 35.5909090909, "max_line_length": 101, "alphanum_fraction": 0.5651340996, "include": true, "reason": "import numpy", "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.9086178926024028, "lm_q1q2_score": 0.8532147553647552}}
{"text": "#! python3\n# -*- coding:utf-8 -*-\n'''\n  ユニバーサルファンクション\n  map()のように、ndarray内の各要素に一括で処理を行える\n'''\nimport random\nimport math\nimport numpy as np\n\n#abs 絶対値に変換する\nnp.random.seed(123)\nprint(\"abs\")\nl = np.random.randint(-10, 10, 5)\nprint(type(l))\nprint(np.abs(l))\n#実はndarrayの場合は標準absでもできる。\n#標準リストを標準absで処理しようとするとリストじゃないと怒られる。\nprint(abs(l))\n#print(abs([ random.randint(-5,-1) for x in range(5) ]))\nprint(\"--------\")\n\n#sin, cos\n#サイン、コサインに変換する\n#度数法(0〜360)ではなく弧度法で指定しないといけない点に注意。\nprint(\"sin, cos\")\n#度数法で角度を設定\nl = np.array([0, 30, 60, 90])\n#弧度法に変換\nl = l / 360 * math.pi * 2\n#ユニバーサルファンクションを適用してみる\nprint(np.sin(l))\nprint(np.cos(l))\nprint(np.tan(l))\nprint(\"--------\")\n\n#おまけ　度数法と弧度法を互いに変換する便利関数がある。\nprint(\"radians \" + str(np.radians(180)))\nprint(\"deg2rad \" + str(np.deg2rad(180)))\nprint(\"rad2deg \" + str(np.rad2deg(3.14)))\n\n#平均、中央値、最瀕値\nprint(\"mean, median, mod\")\nl = np.array([1, 2, 2, 2, 3, 3, 4])\nprint(np.mean(l))\nprint(np.median(l))\n#print(np.mod(l))\nprint(\"--------\")\n\n#積\nprint(\"prod\")\nprint(np.prod(l))\nprint(\"--------\")\n#幾何平均\nprint(\"mean prod\")\nprint(np.prod(l) ** (1/len(l)))\nprint(\"--------\")\n\n\n#四捨五入、切り捨て、切り上げ\nprint(\"round, trunc, floor, ceil\")\n# 配列 [-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0] を作成\na = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])\n# 四捨五入 (小数点以下 .5 以上は繰上げ、.5未満は切捨て)\nprint(np.round(a))\n# 切り捨て (小数部分を取り除く)\nprint(np.trunc(a))\n# 切り捨て (小さい側の整数に丸める)\nprint(np.floor(a))\n# 切り上げ (大きい側の整数に丸める)\nprint(np.ceil(a))\n# ゼロに近い側の整数に丸める\nprint(np.fix(a))\nprint(\"--------\")\n\n#最大値、最小値\nprint(\"max, min\")\nprint(np.max(a))\nprint(np.min(a))\nprint(\"--------\")\n\n#平方根\nprint(\"sqrt\")\nprint(\"before \" + str([1, 4, 9, 16]))\nprint(\"sqrt \" + str(np.sqrt([1, 4, 9, 16])))\nprint(\"--------\")", "meta": {"hexsha": "7c3bbfdec9fb374e9d5ac6ade533c8e9391681a9", "size": 1656, "ext": "py", "lang": "Python", "max_stars_repo_path": "PythonLearn/numpy/sample3.py", "max_stars_repo_name": "OKKyu/PythonLearn", "max_stars_repo_head_hexsha": "48dc4cc2a1a34d99b09f8d37a5566d448dcf987c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PythonLearn/numpy/sample3.py", "max_issues_repo_name": "OKKyu/PythonLearn", "max_issues_repo_head_hexsha": "48dc4cc2a1a34d99b09f8d37a5566d448dcf987c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PythonLearn/numpy/sample3.py", "max_forks_repo_name": "OKKyu/PythonLearn", "max_forks_repo_head_hexsha": "48dc4cc2a1a34d99b09f8d37a5566d448dcf987c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2558139535, "max_line_length": 56, "alphanum_fraction": 0.61352657, "include": true, "reason": "import numpy", "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248123094437, "lm_q2_score": 0.9086178882719769, "lm_q1q2_score": 0.8532147419955961}}
{"text": "import numpy as np\nfrom math import atan2, asin\n\ndef Euler2Quaternion(phi, theta, psi):\n    cth = np.cos(theta/2)\n    cph = np.cos(phi/2)\n    cps = np.cos(psi/2)\n\n    sth = np.sin(theta/2)\n    sph = np.sin(phi/2)\n    sps = np.sin(psi/2)\n\n    e0 = cps*cth*cph+sps*sth*sph\n    e1 = cps*cth*sph-sps*sth*cph\n    e2 = cps*sth*cph+sps*cth*sph\n    e3 = sps*cth*cph+cps*sth*sph\n    e = np.array([e0,e1,e2,e3])\n    return e\n\n\ndef Quaternion2Euler(e):\n    e0 = e.item(0)\n    e1 = e.item(1)\n    e2 = e.item(2)\n    e3 = e.item(3)\n\n    phi = atan2(2*(e0*e1 + e2*e3),(e0**2+e3**2-e1**2-e2**2))\n    theta = asin(2*(e0*e2-e1*e3))\n    psi = atan2(2*(e0*e3 + e1*e2),(e0**2+e1**2-e2**2-e3**2))\n    return [phi,theta,psi]\n\ndef Quaternion2Rotation(e):\n    e0 = e.item(0)\n    e1 = e.item(1)\n    e2 = e.item(2)\n    e3 = e.item(3)\n\n    R = np.array([[e0**2 + e1**2 - e2**2 - e3**2, 2*(e1*e2 - e0*e3), 2*(e1*e3 + e0*e2)],\n                  [2*(e1*e2 + e0*e3), e0**2 - e1**2 + e2**2 - e3**2, 2*(e2*e3 - e0*e1)],\n                  [2*(e1*e3 - e0*e2), 2*(e2*e3 + e0*e1), e0**2 - e1**2 - e2**2 + e3**2]\n                  ])\n    return R\n\ndef Euler2Rotation(phi, theta, psi):\n    # print(\"orig:\", phi, theta, psi)\n    # e = Euler2Quaternion(phi, theta, psi)\n    # R = Quaternion2Euler(e)\n\n    cph = np.cos(phi)\n    sph = np.sin(phi)\n    cth = np.cos(theta)\n    sth = np.sin(theta)\n    cps = np.cos(psi)\n    sps = np.sin(psi)\n\n    Rbv2 = np.array([[1., 0., 0.],\\\n                    [0., cph, sph],\\\n                    [0., -sph, cph]])\n\n    Rv2v1 = np.array([[cth, 0., -sth],\\\n                    [0., 1., 0.],\\\n                    [sth, 0., cth]])\n\n    Rv1i = np.array([[cps, sps, 0.],\\\n                    [-sps, cps, 0.],\\\n                    [0., 0., 1.]])\n\n    R = Rbv2@Rv2v1@Rv1i\n\n    return R.T", "meta": {"hexsha": "6d52b1b81f12879fc514b19ae0413d3f4da3bc76", "size": 1772, "ext": "py", "lang": "Python", "max_stars_repo_path": "Airplane/tools/tools.py", "max_stars_repo_name": "eyler94/ee674AirplaneSim", "max_stars_repo_head_hexsha": "3ba2c6e685c2688a7f372475a7cd1f55f583d10e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-07T00:14:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-07T00:14:42.000Z", "max_issues_repo_path": "Airplane/tools/tools.py", "max_issues_repo_name": "eyler94/ee674AirplaneSim", "max_issues_repo_head_hexsha": "3ba2c6e685c2688a7f372475a7cd1f55f583d10e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Airplane/tools/tools.py", "max_forks_repo_name": "eyler94/ee674AirplaneSim", "max_forks_repo_head_hexsha": "3ba2c6e685c2688a7f372475a7cd1f55f583d10e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-24T22:10:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-24T22:10:48.000Z", "avg_line_length": 25.3142857143, "max_line_length": 88, "alphanum_fraction": 0.4644469526, "include": true, "reason": "import numpy", "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517482043892, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.8532008634849858}}
{"text": "# Exercise 3\n# The binomial distribution describes the statistics of the number of successful events for a Bernoulli experiment\n# repeated N times, where the probability of success of each experiment is p.\n# 1. Execute Ntr = 10000 trials, each made of N = 100 Bernoulli experiments with probability of success p = 0.05.\n# [Hint: to test whether a Bernoulli experiment is successful or not, draw a random number u ∼ U(0, 1), and check if u ≤ p.]\n# 2. For each trial i, count the number of successes si, and draw the empirical probability mass function (PMF)\n# of the number of successes throughout all trials. Compare against the theoretical binomial PMF.\n# 3. Compare the empirical and the theoretical binomial distributions against a Poisson distribution of parameter λ = N p.\n# Repeat the comparison for different values of N and p. When does the Poisson PMF accurately approximate the binomial PMF?\n\n# import\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom numpy import mean, min, max, median, quantile\nfrom scipy.stats import binom, norm, t as student, expon, poisson\nfrom math import sqrt, pow, floor, ceil, exp\n\n\n# define corrected functions for std and variance\ndef variance(values):\n\treturn np.var(values, ddof=1)\n\n\ndef std(values):\n\treturn np.std(values, ddof=1)\n\n\nNtr = 10000\nN = 100\np = 0.05\ntrials = []\nfor i in range(Ntr):\n\ttrial = []\n\tfor l in range(N):\n\t\tif np.random.rand() <= p:\n\t\t\ttrial.append(1)\n\t\telse:\n\t\t\ttrial.append(0)\n\ttrials.append(trial)\n\n# count successes s_i and draw pmf\ntrials = np.array(trials)\ntrial_sums = np.sum(trials, axis=1)\nplt.hist(trial_sums, bins = np.arange(0, trial_sums.max() + 1.5) - 0.5, density=True)\n\n# compare against theoretical binomial distribution\nX = np.arange(0, 20, 1)\nY = binom.pmf(X, N, p)\nplt.plot(X, Y, 'k-', zorder=2)\n\n# compare against a poisson with lambda = N*p\nX = np.arange(0, 20, 1)\nY = poisson.pmf(X, N * p)\nplt.plot(X, Y, 'r-', zorder=3)\n\nY = poisson.pmf(X, 2 * p * N)\nplt.plot(X, Y, 'm-', zorder=3)\n\nY = poisson.pmf(X, 4 * p * N)\nplt.plot(X, Y, 'y-', zorder=3)\nplt.show()\n", "meta": {"hexsha": "49f9ad4726aecf30a9569125c49109f483dc09c9", "size": 2055, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW2/ex3.py", "max_stars_repo_name": "andreamatt/Simulation-homeworks", "max_stars_repo_head_hexsha": "d6e987a99498c0a30bfd8d3d9deeb3c0382a27be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW2/ex3.py", "max_issues_repo_name": "andreamatt/Simulation-homeworks", "max_issues_repo_head_hexsha": "d6e987a99498c0a30bfd8d3d9deeb3c0382a27be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW2/ex3.py", "max_forks_repo_name": "andreamatt/Simulation-homeworks", "max_forks_repo_head_hexsha": "d6e987a99498c0a30bfd8d3d9deeb3c0382a27be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1451612903, "max_line_length": 124, "alphanum_fraction": 0.7158150852, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9820137910906879, "lm_q2_score": 0.8688267643505193, "lm_q1q2_score": 0.8531998646609091}}
{"text": "import numpy as np\nimport pandas as pd\nfrom scipy.spatial.distance import pdist, squareform\nfrom tabulate import tabulate\nimport random\n\nimport networkx as nx\nfrom pygsp import graphs, filters, plotting\n\n\n#### Network\ndef gaussian_kernel(dist, sigma):\n    return np.exp(-dist**2 / (2*sigma**2))\n\ndef get_adjacency(X: np.ndarray, dist_metric, sigma=1, epsilon=0):\n    \"\"\" X (n x d): coordinates of the n data points in R^d.\n        sigma (float): width of the kernel\n        epsilon (float): threshold\n        Return:\n        adjacency (n x n ndarray): adjacency matrix of the graph.\n    \"\"\"\n    dist = squareform(pdist(X, metric=dist_metric))\n    adjacency = np.exp(- dist ** 2 / (2 * sigma ** 2))\n    adjacency[adjacency < epsilon] = 0\n    np.fill_diagonal(adjacency, 0)\n    return adjacency\n\ndef graph_basic_stats(G):\n    nodes_number = G.number_of_nodes()\n    edges_number = G.number_of_edges()\n\n\n    g_degree = G.degree()\n    sum_degree = sum(dict(g_degree).values())\n    average_degree = sum_degree / nodes_number\n\n    tab = [\n        [\"Number of nodes\", nodes_number],\n        [\"Number of edges\", edges_number],\n        [\"Graph density\", round(nx.classes.function.density(G) * 100, 2)],\n        [\"Average degree\", round(average_degree, 2)],\n        [\"Number of connected components\", nx.number_connected_components(G)],\n        [\"Average clustering coefficient\", round(nx.average_clustering(G), 2)],\n        [\"Diameter of the network (longest shortest path)\", nx.diameter(G)]   \n    ]\n    print(tabulate(tab, tablefmt='fancy_grid'))\n\n\n\n#### GSP\ndef compute_laplacian(adjacency: np.ndarray, normalize: bool):\n    \"\"\" Return:\n        L (n x n ndarray): combinatorial or symmetric normalized Laplacian.\n    \"\"\"\n    D = np.diag(np.sum(adjacency, 1)) # Degree matrix\n    combinatorial = D - adjacency\n    if normalize:\n        D_norm = np.diag(np.clip(np.sum(adjacency, 1), 1, None)**(-1/2))\n        return D_norm @ combinatorial @ D_norm\n    else:\n        return combinatorial\n\ndef spectral_decomposition(laplacian: np.ndarray):\n    \"\"\" Return:\n        lamb (np.array): eigenvalues of the Laplacian\n        U (np.ndarray): corresponding eigenvectors.\n    \"\"\"\n    return np.linalg.eigh(laplacian)\n\ndef fit_polynomial(lam: np.ndarray, order: int, spectral_response: np.ndarray):\n    \"\"\" Return an array of polynomial coefficients of length 'order'.\"\"\"\n    A = np.vander(lam, order, increasing=True)\n    coeff = np.linalg.lstsq(A, spectral_response, rcond=None)[0]\n    return coeff\n\ndef polynomial_graph_filter(coeff: np.array, laplacian: np.ndarray):\n    \"\"\" Return the laplacian polynomial with coefficients 'coeff'. \"\"\"\n    power = np.eye(laplacian.shape[0])\n    filt = coeff[0] * power\n    for n, c in enumerate(coeff[1:]):\n        power = laplacian @ power\n        filt += c * power\n    return filt\n\n\n#### GCNN\ndef get_masks(nb_nodes, test_ratio, seed=None):\n    ''' Return the indices for the train and test sets\n    '''\n    if seed is not None:\n        np.random.seed(seed)\n    \n    nb_test = int(nb_nodes*test_ratio)\n    test_mask = np.sort(random.sample(range(0, nb_nodes), nb_test)) \n    train_mask = list(set(np.arange(0, nb_nodes))^set(test_mask))\n    \n    return train_mask, test_mask\n\ndef compute_accuracy(y, y_hat):\n    assert(len(y)==len(y_hat)), 'y and y_hat must have the same length'\n    return np.sum(y_hat == y) / (len(y) - int(pd.DataFrame(y).isna().sum())) # to deal with NaNs", "meta": {"hexsha": "38079db0b82ea3ddbea9a70e330b0db9dff9f67a", "size": 3398, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/helpers.py", "max_stars_repo_name": "ymentha14/Network-Tour-of-Mice-Genetics", "max_stars_repo_head_hexsha": "b2ce9e594adaf95d531bdc966e6be6dbe55cc2a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-15T20:29:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-15T20:29:31.000Z", "max_issues_repo_path": "src/helpers.py", "max_issues_repo_name": "ymentha14/Network-Tour-of-Mice-Genetics", "max_issues_repo_head_hexsha": "b2ce9e594adaf95d531bdc966e6be6dbe55cc2a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/helpers.py", "max_forks_repo_name": "ymentha14/Network-Tour-of-Mice-Genetics", "max_forks_repo_head_hexsha": "b2ce9e594adaf95d531bdc966e6be6dbe55cc2a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6435643564, "max_line_length": 96, "alphanum_fraction": 0.6597998823, "include": true, "reason": "import numpy,from scipy,import networkx", "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.8991213860551287, "lm_q1q2_score": 0.8531918086954712}}
{"text": "import numpy as np\nimport cv2 # You must not use any methods which has 'hough' in it!\nfrom utils import  hough_peaks\n\n\n\n\ndef hough_lines_vote_acc(edge_img, rho_res=1, thetas= np.arange(0,180)):\n    h,w=edge_img.shape[:2]\n    d=int(np.round(np.sqrt(h**2+w**2)))\n    y,x=np.nonzero(edge_img>0)\n    A=np.zeros((2*d+1,len(thetas)))\n    thetas1=np.deg2rad(thetas)\n    rhos=np.arange(0,2*d)\n    #rhos=[]\n   \n    for i in range(len(x)):\n        for theta in thetas1:\n            rho=np.int(np.ceil(x[i]*np.cos(theta)+y[i]*np.sin(theta)))\n            A[rho,np.int(np.round(np.rad2deg(theta)))]+=1\n            #rhos.append(rho)\n           \n    return A, thetas, rhos\n\n    \ndef hough_circles_vote_acc(edge_img, radius):\n    r=radius\n    h,w=edge_img.shape[:2]\n    edges=edge_img>0\n    y_idxs,x_idxs=np.nonzero(edges)\n    A=np.zeros((h,w))\n    theta=np.linspace(-180,180,360)\n    for i in range(len(x_idxs)):\n        x=x_idxs[i]\n        y=y_idxs[i]\n        for t in theta:\n            b=y-r*np.sin(t)\n            a=x+r*np.cos(t)\n            if a<h and a>0 and b<w and b>0:\n                A[int(b),int(a)]+=1\n            \n    \n    return A\n\n\ndef find_circles(edge_img, radius_range=[1,2], threshold=100, nhood_size=10):\n    \"\"\"\n      A naive implementation of the algorithm for finding all the circles in a range.\n      Feel free to write your own more efficient method [Extra Credit]. \n      For extra credit, you may need to add additional arguments. \n\n\n      Args\n      - edge_img: numpy nd-array of dim (m, n). \n      - radius_range: range of radius. All cicles whose radius falls \n      in between should be selected.\n      - nhood_size: size of the neighborhood from where only one candidate can be chosen. \n      \n      Returns\n      - centers, and radii i.e., (x, y) coordinates for each circle.\n\n      HINTS:\n      - I encourage you to use this naive version first. Just be aware that\n       it may take a long time to run. You will get EXTRA CREDIT if you can write a faster\n       implementaiton of this method, keeping the method signature (input and output parameters)\n       unchanged. \n    \"\"\"\n    n = radius_range[1] - radius_range[0]\n    H_size = (n,) + edge_img.shape\n    H = np.zeros(H_size, dtype=np.uint)\n    centers = ()\n    radii = np.arange(radius_range[0], radius_range[1])\n    valid_radii = np.array([], dtype=np.uint)\n    num_circles = 0\n    for i in range(len(radii)):\n        H[i] = hough_circles_vote_acc(edge_img, radii[i])\n        peaks = hough_peaks(H[i], numpeaks=10, threshold=threshold,\n                            nhood_size=nhood_size)\n        if peaks.shape[0]:\n            valid_radii = np.append(valid_radii, radii[i])\n            centers = centers + (peaks,)\n            for peak in peaks:\n                cv2.circle(edge_img, tuple(peak[::-1]), radii[i]+1, (0,0,0), -1)\n        #  cv2.imshow('image', edge_img); cv2.waitKey(0); cv2.destroyAllWindows()\n        num_circles += peaks.shape[0]\n        print('Progress: %d%% - Circles: %d\\033[F\\r'%(100*i/len(radii), num_circles))\n    print('Circles detected: %d          '%(num_circles))\n    centers = np.array(centers)\n    return centers, valid_radii.astype(np.uint)\n", "meta": {"hexsha": "946b8ca4dacee5b426edcb361d6dfab17a9e44b3", "size": 3146, "ext": "py", "lang": "Python", "max_stars_repo_path": "Hough_Line_And_Circle_Detector/code/student_code.py", "max_stars_repo_name": "dasdristanta13/Computer-vision", "max_stars_repo_head_hexsha": "2fe99066c33f822772ae252f489728b8fff68399", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Hough_Line_And_Circle_Detector/code/student_code.py", "max_issues_repo_name": "dasdristanta13/Computer-vision", "max_issues_repo_head_hexsha": "2fe99066c33f822772ae252f489728b8fff68399", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hough_Line_And_Circle_Detector/code/student_code.py", "max_forks_repo_name": "dasdristanta13/Computer-vision", "max_forks_repo_head_hexsha": "2fe99066c33f822772ae252f489728b8fff68399", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-03T08:17:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T08:17:37.000Z", "avg_line_length": 34.9555555556, "max_line_length": 96, "alphanum_fraction": 0.6055308328, "include": true, "reason": "import numpy", "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.8991213847035617, "lm_q1q2_score": 0.8531918035162889}}
{"text": "from dataclasses import dataclass\nimport numpy as np\nfrom numpy import linalg as nla, ndarray\nfrom functools import cached_property\n\nfrom config import DEBUG\n\n\ndef isPSD(arr: np.ndarray) -> bool:\n    return np.allclose(arr, arr.T) and np.all(np.linalg.eigvals(arr) >= 0)\n\n\n@dataclass(frozen=True)\nclass MultiVarGaussian:\n    \"\"\"A class for using Gaussians\"\"\"\n    mean: ndarray  # shape=(n,)\n    cov: ndarray  # shape=(n, n)\n\n    def __post_init__(self):\n        if DEBUG:\n            assert self.mean.shape * 2 == self.cov.shape\n            assert np.all(np.isfinite(self.mean))\n            assert np.all(np.isfinite(self.cov))\n            assert isPSD(self.cov)\n\n    @cached_property\n    def ndim(self) -> int:\n        return self.mean.shape[0]\n\n    @cached_property\n    def scaling(self) -> float:\n        scaling = (2*np.pi)**(-self.ndim/2) * nla.det(self.cov)**(-1/2)\n        return scaling\n\n    def mahalanobis_distance_sq(self, x: np.ndarray) -> float:\n        \"\"\"Calculate the mahalanobis distance between self and x.\n\n        This is also known as the quadratic form of the Gaussian.\n        See (3.2) in the book.\n        \"\"\"\n        # this method could be vectorized for efficient calls\n        error = x - self.mean\n        mahalanobis_distance = error.T @ nla.solve(self.cov, error)\n        return mahalanobis_distance\n\n    def pdf(self, x):\n        density = self.scaling*np.exp(-self.mahalanobis_distance_sq(x)/2)\n        return density\n\n    def marginalize(self, idxs):\n        return MultiVarGaussian(self.mean[idxs], self.cov[idxs][:, idxs])\n\n    def __iter__(self):  # in order to use tuple unpacking\n        return iter((self.mean, self.cov))\n\n    def __eq__(self, o: object) -> bool:\n        if not isinstance(o, MultiVarGaussian):\n            return False\n        return np.allclose(self.mean, o.mean) and np.allclose(self.cov, o.cov)\n", "meta": {"hexsha": "d0671ede8fdeef3d86ece68ab2cbac5a947c5853", "size": 1856, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignments/Assignment_05/pda/utils/multivargaussian.py", "max_stars_repo_name": "chrstrom/TTK4250", "max_stars_repo_head_hexsha": "f453c3a59597d3fe6cff7d35b790689919798b94", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignments/Assignment_05/pda/utils/multivargaussian.py", "max_issues_repo_name": "chrstrom/TTK4250", "max_issues_repo_head_hexsha": "f453c3a59597d3fe6cff7d35b790689919798b94", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignments/Assignment_05/pda/utils/multivargaussian.py", "max_forks_repo_name": "chrstrom/TTK4250", "max_forks_repo_head_hexsha": "f453c3a59597d3fe6cff7d35b790689919798b94", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9333333333, "max_line_length": 78, "alphanum_fraction": 0.6379310345, "include": true, "reason": "import numpy,from numpy", "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.8991213826762113, "lm_q1q2_score": 0.8531918015925011}}
{"text": "\n\nfrom __future__ import division\nimport pandas as pd\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport numpy.linalg as npla\nimport scipy.linalg as spla\nimport scipy.special\n\n\n\n# Code may print some warnings due to pandas in Python2. \n# These warning are benign. Verigy here: https://stackoverflow.com/questions/40845304/runtimewarning-numpy-dtype-size-changed-may-indicate-binary-incompatibility\n\n\n\nz = 20\n\n\n\n\nJ_0 = scipy.special.jv(0, z)\nJ_1 = scipy.special.jv(1, z)\n\n\n\n\n\nbessel_val_by_rec = [J_0, J_1]\n\n\n\n\n\nfor i in range(2, 51):\n    \n    J_i = ( ( ( ( 2 * ( i - 1 ) ) / z ) * bessel_val_by_rec[i - 1] ) - bessel_val_by_rec[i - 2] )\n\n    bessel_val_by_rec.append(J_i)\n\n\n\n\n\nbessel_val_by_func = [scipy.special.jv(i, z) for i in range(0, 51)]\n\n\n\n\n\nrelative_err = []\nfor i in range(2, 51):\n    relative_err.append((bessel_val_by_rec[i] - bessel_val_by_func[i])/bessel_val_by_func[i])\n\n# Again, just printing magnitude of the Relative Error\n# Comment this value to print just the ratio\nrelative_err = [abs(i) for i in relative_err]\n\n\n\n\n\ndf = pd.DataFrame({\"n\" : [i for i in range(2, 51)], \"From Function\" : bessel_val_by_func[2:], \"From Recurrence\" : bessel_val_by_rec[2:], \"Relative Error\" : relative_err}, columns=[\"n\", \"From Function\", \"From Recurrence\", \"Relative Error\"])\nprint(df.to_string(index_names=False))\n\n\n\n\n\n\n\nplt.xlabel(\"Value of n\")\nplt.ylabel(\"Absolute Value of Relative Error\")\nplt.plot( np.arange(2, 51), relative_err)\nplt.savefig(\"problem_3b.png\")\n# Uncomment to show plot\n# plt.show()\n\n", "meta": {"hexsha": "2e24fc50142e374cf98c2dff7cd5892c1580131a", "size": 1532, "ext": "py", "lang": "Python", "max_stars_repo_path": "a1/problem_3b.py", "max_stars_repo_name": "justachetan/scientific-computing", "max_stars_repo_head_hexsha": "e8493b5308c337ea8965a5f96cdd49def94801e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-04-30T14:03:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T19:19:13.000Z", "max_issues_repo_path": "a1/problem_3b.py", "max_issues_repo_name": "justachetan/scientific-computing", "max_issues_repo_head_hexsha": "e8493b5308c337ea8965a5f96cdd49def94801e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "a1/problem_3b.py", "max_forks_repo_name": "justachetan/scientific-computing", "max_forks_repo_head_hexsha": "e8493b5308c337ea8965a5f96cdd49def94801e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9135802469, "max_line_length": 239, "alphanum_fraction": 0.7075718016, "include": true, "reason": "import numpy,import scipy", "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410982634296, "lm_q2_score": 0.8976952941600964, "lm_q1q2_score": 0.8531794666288807}}
{"text": "\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nget_ipython().magic('matplotlib inline')\n\n\n# In[2]:\n\n\ndef logistic(r, x):\n    return r * x * (1 - x)\n\n\n# In[3]:\n\n\nx = np.arange(0, 1.02,0.02)\nplt.plot(x, logistic(2, x), 'b')\nplt.show()\n\n\n# In[10]:\n\n\ndef plot_map(r, x0, n):\n    t = np.linspace(0, 1)\n    plt.plot(t, logistic(r, t), 'k', lw=2)\n    plt.plot([0, 1], [0, 1], 'k', lw=2)\n    x = x0\n    for i in range(n):\n        y = logistic(r, x)\n        plt.plot([x, x], [x, y], 'k', lw=1)\n        plt.plot([x, y], [y, y], 'k', lw=1)\n        plt.plot([x], [y], 'ok', ms=10, alpha=(i + 1) / n)\n        x = y\n        \nplot_map(2.5, .1, 10)\n\n\n# In[11]:\n\n\nplot_map(3.9, .1, 80)\n\n\n# In[6]:\n\n\nn = 10000\nr = np.linspace(2.5, 4.0, n)\n\n\n# In[7]:\n\n\niterations = 1000\nlast = 100\n\n\n# In[8]:\n\n\nx = 1e-5 * np.ones(n)\nlyapunov = np.zeros(n)\n\n\n# In[9]:\n\n\nfor i in range(iterations):\n    x = logistic(r, x)\n    if i >= (iterations - last):\n        plt.plot(r, x, ',k',alpha=0.25)\n\n", "meta": {"hexsha": "8aadd5c98e785153f8fdd91885745286f009eafb", "size": 992, "ext": "py", "lang": "Python", "max_stars_repo_path": "ComplimentaryFiles/StandardMap/StandardMap.py", "max_stars_repo_name": "msnamini/Coph2018", "max_stars_repo_head_hexsha": "f6e24bc8494dfbada1df7714be8038baa54c9f2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-01T13:59:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-06T18:20:52.000Z", "max_issues_repo_path": "ComplimentaryFiles/StandardMap/StandardMap.py", "max_issues_repo_name": "msnamini/Coph2018", "max_issues_repo_head_hexsha": "f6e24bc8494dfbada1df7714be8038baa54c9f2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ComplimentaryFiles/StandardMap/StandardMap.py", "max_forks_repo_name": "msnamini/Coph2018", "max_forks_repo_head_hexsha": "f6e24bc8494dfbada1df7714be8038baa54c9f2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.4, "max_line_length": 58, "alphanum_fraction": 0.4909274194, "include": true, "reason": "import numpy", "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159683, "lm_q2_score": 0.8976952975813454, "lm_q1q2_score": 0.8531794648369269}}
{"text": "from builtins import print\n\nfrom numpy import *\n\n'''\nadd any value to each element to the array\narr1 = array([1,2,3,4,7])\n\narr1+=5\nprint(arr1)\n'''\n\n'''\nadd two array also called vectorized operation\narr1 = array([1,2,3,4,5])\narr2 = array([6,7,8,9,10])\n\nprint(\"Addition is : \" , arr1 + arr2)\n\n'''\n\narr1 = array([2, 1, 45, 3, 21, 12, 2, 1])\narr2 = array([12, 54, 65, 32, 1, 8, 3, 2, 4])\nprint(\"sin : \", sin(arr1))\nprint(\"cos : \", cos(arr1))\nprint(\"log : \", log(arr1))\nprint(\"sqrt : \", sqrt(arr1))\nprint(\"sum : \", sum(arr1))\nprint(\"min : \", min(arr1))\nprint(\"max : \", max(arr1))\n# check it print(subtract(arr1-1))\nprint(\"sort : \", sort(arr1))\nprint(\"unique : \", unique(arr1))\nprint(\"concatenate : \", sort(concatenate([arr1, arr2])))\n#print(\"subtract : \",subtract(arr1-1))\n\n# Creating array object\narr = array([[1, 2, 3],\n                [4, 2, 5]])\n\n# Printing type of arr object\nprint(\"Array is of type: \", type(arr))\n\n# Printing array dimensions (axes)\nprint(\"No. of dimensions: \", arr.ndim)\n\n# Printing shape of array rows * cols\nprint(\"Shape of array: \", arr.shape)\n\n# Printing size (total number of elements) of array\nprint(\"Size of array: \", arr.size)\n\n# Printing type of elements in array\nprint(\"Array stores elements of type: \", arr.dtype)\n", "meta": {"hexsha": "0879253161388d3ad3b41e9dfcf2fd5b12282566", "size": 1245, "ext": "py", "lang": "Python", "max_stars_repo_path": "core-python/Core_Python/numpypkg/NpArrayOperations.py", "max_stars_repo_name": "theumang100/tutorials-1", "max_stars_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-04-23T05:24:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T16:37:51.000Z", "max_issues_repo_path": "core-python/Core_Python/numpypkg/NpArrayOperations.py", "max_issues_repo_name": "theumang100/tutorials-1", "max_issues_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-10-01T05:08:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-12T03:18:10.000Z", "max_forks_repo_path": "core-python/Core_Python/numpypkg/NpArrayOperations.py", "max_forks_repo_name": "theumang100/tutorials-1", "max_forks_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-04-28T14:06:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-19T18:32:28.000Z", "avg_line_length": 22.6363636364, "max_line_length": 56, "alphanum_fraction": 0.6313253012, "include": true, "reason": "from numpy", "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068042, "lm_q2_score": 0.8976952934758465, "lm_q1q2_score": 0.8531794584132423}}
{"text": "# This example describe how to integrate ODEs with scipy.integrate module and how\n# to use the matplotlib module to plot trajectories, directions field and others\n# useful informations.\n# \n# == Presentation of the Lokta-Volterra Model ==\n# \n# \n# We will have a look at the Lokta-Volterra model, laso known as the\n# predator-prey equations, re a pair of first order, non-linear, differential\n# equations frequently used to describe the dynamics of biological systems in\n# which two species interact, one a predator and one its prey. They were proposed\n# independently by Alfred J. Lotka in 1925 and Vito Volterra in 1926 :\n# du/dt =  a*u -   b*u*v\n# dv/dt = -c*v + d*b*u*v \n# \n# with the following notations :\n# \n# *  u : number of prey (for example rabbits)\n# \n# *  v : number of predators (for example foxes)  \n#   \n# * a, b, c, d are constant parameters defining the behavior of the population :    \n# \n#   + a is the natural growing rate of rabbits, when there's no foxes\n# \n#   + b is the natural dying rate of rabbits, due to predation\n# \n#   + c is the natural dying rate of foxes, when there's no rabbits\n# \n#   + d is the factor descibing how many catched rabbits let create new rabbits\n# \n# \n# We will use X=[u, v] to describe the state of both populations.\n# Definition of the equations:\n# \nfrom numpy import *\nimport pylab as p\n\n# Parameters \na = 1.\nb = 0.1\nc = 1.5\nd = 0.75\n\ndef dX_dt(X, t=0):\n    \"\"\" Return the growth rate of foxes and rabbits populations. \"\"\"\n    return array([ a*X[0] -   b*X[0]*X[1] ,  \n                  -c*X[1] + d*b*X[0]*X[1] ])\n# \n# === Population equilibrium ===\n# \n# Before using scipy to integrate this system, we will have a closer look on \n# position equilibrium. Equilibrium occurs when the growth rate is equal to 0.\n# This gives two fixed points:\n# \nX_f0 = array([0., 0.])\nX_f1 = array([ c/(d*b), a/b])\nall(dX_dt(X_f0) == zeros(2) ) and all(dX_dt(X_f1) == zeros(2)) # => True \n# \n# === Stability of the fixed points ===\n# Near theses two points, the system can be linearized :\n# dX_dt = A_f*X where A is the Jacobian matrix evaluated at the corresponding point.\n# We have to define the Jacobian matrix:\n# \ndef d2X_dt2(X, t=0):\n    \"\"\" Return the jacobian matrix evaluated in X. \"\"\"\n    return array([[a -b*X[1],   -b*X[0]     ],\n                  [b*d*X[1] ,   -c +b*d*X[0]] ])  \n# \n# So, near X_f0, which represents the extinction of both species, we have:\n# A_f0 = d2X_dt2(X_f0)                    # >>> array([[ 1. , -0. ],\n#                                         #            [ 0. , -1.5]])\n# \n# Near X_f0, the number of rabbits increase and the population of foxes decrease.\n# X_f0 is a [http://en.wikipedia.org/wiki/Saddle_point saddle point].\n# \n# Near X_f1, we have :\nA_f1 = d2X_dt2(X_f1)                    # >>> array([[ 0.  , -2.  ],\n                                        #            [ 0.75,  0.  ]])\n\n# whose eigenvalues are +/- sqrt(ca).j :\nlambda1, lambda2 = linalg.eigvals(A_f1) # >>> (1.22474j, -1.22474j)\n\n# They are imaginary number, so the fox and rabbit populations are periodic and\n# their period is given by :\nT_f1 = 2*pi/abs(lambda1)                # >>> 5.130199\n#         \n# == Integrating the ODE using scipy.integate ==\n# \n# Now we will use the scipy.integrate module to integrate the ODE.\n# This module offers a  method named odeint, very easy to use to integrade ODE:\n# \nfrom scipy import integrate\n\nt = linspace(0, 15,  1000)              # time\nX0 = array([10, 5])                     # initials conditions: 10 rabbits and 5 foxes  \n\nX, infodict = integrate.odeint(dX_dt, X0, t, full_output=True)\ninfodict['message']                     # >>> 'Integration successful.'\n# \n# `infodict` is optionnal, and you can omit the `full_output` argument if you don't want it.\n# type \"info(odeint)\" if you want more information about odeint inputs and outputs.\n# \n# We will use matplotlib to plot the evolution of both populations:\n# \nrabbits, foxes = X.T\n\nf1 = p.figure()\np.plot(t, rabbits, 'r-', label='Rabbits')\np.plot(t, foxes  , 'b-', label='Foxes')\np.grid()\np.legend(loc='best')\np.xlabel('time')\np.ylabel('population')\np.title('Evolution of fox and rabbit populations')\nf1.savefig('rabbits_and_foxes_1.png')\n# \n# \n# The populations are indeed periodic, and their period is near to the T_f1 we calculated.\n# \n# == Plotting directions field and trajectories in the phase plane ==\n# \n# We will plot some trajectories in a phase plane for different starting\n# points between X__f0 and X_f1.\n# \n# We will ue matplotlib's colormap to define colors for the trajectories.\n# These colormaps are very useful to make nice plots.\n# Have a look on ShowColormaps if you want more information.\n# \nvalues = linspace(0.3, 0.9, 5)                          # position of X0 between X_f0 and X_f1\nvcolors = p.cm.Greens(linspace(0.3, 1., len(values)))   # colors for each trajectory\n\nf2 = p.figure()\n\n#-------------------------------------------------------\n# plot trajectories\nfor v, col in zip(values, vcolors): \n    X0 = v * X_f1                               # starting point\n    X = integrate.odeint( dX_dt, X0, t)         # we don't need infodict here\n    p.plot( X[:,0], X[:,1], lw=3.5*v, color=col, label='X0=(%.f, %.f)' % ( X0[0], X0[1]) )\n\n#-------------------------------------------------------\n# define a grid and compute direction at each point\nymax = p.ylim(ymin=0)[1]                        # get axis limits\nxmax = p.xlim(xmin=0)[1] \nnb_points   = 20                      \n\nx = linspace(0, xmax, nb_points)\ny = linspace(0, ymax, nb_points)\n\nX1 , Y1  = meshgrid(x, y)                       # create a grid\nDX1, DY1 = dX_dt([X1, Y1])                      # compute growth rate on the gridt\nM = (hypot(DX1, DY1))                           # Norm of the growth rate \nM[ M == 0] = 1.                                 # Avoid zero division errors \nDX1 /= M                                        # Normalize each arrows\nDY1 /= M                                  \n\n#-------------------------------------------------------\n# Drow direction fields, using matplotlib 's quiver function\n# I choose to plot normalized arrows and to use colors to give information on\n# the growth speed\np.title('Trajectories and direction field')\nQ = p.quiver(X1, Y1, DX1, DY1, M, pivot='mid', cmap=p.cm.autumn)\np.xlabel('Number of Rabbits')\np.ylabel('Number of Foxes')\np.legend()\np.grid()\np.xlim(0, xmax)\np.ylim(0, ymax)\nf2.savefig('rabbits_and_foxes_2.png')\n# \n# \n# We can see on this graph that an intervention on fox or rabbit populations can\n# have non intuitive effects. If, in order to decrease the number of rabbits,\n# we introduce foxes, this can lead to an increase of rabbits in the long run,\n# if that intervention happens at a bad moment.\n# \n# \n# == Plotting contours ==\n# \n# We can verify that the fonction IF defined below remains constant along a trajectory:\n# \ndef IF(X):\n    u, v = X\n    return u**(c/a) * v * exp( -(b/a)*(d*u+v) )\n\ndef IF2(X):\n    u, v = X\n    return u**(c/a) * v * exp( -(b/a)*(d*u+v) )\n\n# We will verify that IF remains constant for differents trajectories\nfor v in values: \n    X0 = v * X_f1                               # starting point\n    X = integrate.odeint( dX_dt, X0, t)         \n    I = IF(X.T)                                 # compute IF along the trajectory\n    I_mean = I.mean()\n    delta = 100 * (I.max()-I.min())/I_mean\n    print 'X0=(%2.f,%2.f) => I ~ %.1f |delta = %.3G %%' % (X0[0], X0[1], I_mean, delta)\n\n# >>> X0=( 6, 3) => I ~ 20.8 |delta = 6.19E-05 %\n#     X0=( 9, 4) => I ~ 39.4 |delta = 2.67E-05 %\n#     X0=(12, 6) => I ~ 55.7 |delta = 1.82E-05 %\n#     X0=(15, 8) => I ~ 66.8 |delta = 1.12E-05 %\n#     X0=(18, 9) => I ~ 72.4 |delta = 4.68E-06 %\n# \n# Potting iso-contours of IF can be a good representation of trajectories,\n# without having to integrate the ODE\n# \n#-------------------------------------------------------\n# plot iso contours\nnb_points = 80                              # grid size \n\nx = linspace(0, xmax, nb_points)    \ny = linspace(0, ymax, nb_points)\n\nX2 , Y2  = meshgrid(x, y)                   # create the grid\nZ2 = IF([X2, Y2])                           # compute IF on each point\n\nf3 = p.figure()\nCS = p.contourf(X2, Y2, Z2, cmap=p.cm.Purples_r, alpha=0.5)\nCS2 = p.contour(X2, Y2, Z2, colors='black', linewidths=2. )\np.clabel(CS2, inline=1, fontsize=16, fmt='%.f')\np.grid()\np.xlabel('Number of Rabbits')\np.ylabel('Number of Foxes')\np.ylim(1, ymax)\np.xlim(1, xmax)\np.title('IF contours')\nf3.savefig('rabbits_and_foxes_3.png')\np.show()\n# \n# \n# # vim: set et sts=4 sw=4:\n", "meta": {"hexsha": "1de4450a0e08b22bc61be7566e6a45c4fa35c7ef", "size": 8495, "ext": "py", "lang": "Python", "max_stars_repo_path": "ipython/attachments/LoktaVolterraTutorial/tutorial_lokta-voltera.py", "max_stars_repo_name": "cassiasamp/scipy-cookbook", "max_stars_repo_head_hexsha": "67c120be33302554edfd7fe7962f3e2773109021", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 408, "max_stars_repo_stars_event_min_datetime": "2016-05-26T04:17:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:19:59.000Z", "max_issues_repo_path": "ipython/attachments/LoktaVolterraTutorial/tutorial_lokta-voltera.py", "max_issues_repo_name": "cassiasamp/scipy-cookbook", "max_issues_repo_head_hexsha": "67c120be33302554edfd7fe7962f3e2773109021", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2016-08-28T22:20:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T16:37:00.000Z", "max_forks_repo_path": "ipython/attachments/LoktaVolterraTutorial/tutorial_lokta-voltera.py", "max_forks_repo_name": "cassiasamp/scipy-cookbook", "max_forks_repo_head_hexsha": "67c120be33302554edfd7fe7962f3e2773109021", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 185, "max_forks_repo_forks_event_min_datetime": "2016-06-05T03:27:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T21:14:02.000Z", "avg_line_length": 36.3034188034, "max_line_length": 94, "alphanum_fraction": 0.5914067098, "include": true, "reason": "from numpy,from scipy", "num_tokens": 2509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.9005297907896396, "lm_q1q2_score": 0.8531448530641058}}
{"text": "import numpy as np\nimport matplotlib \nimport copy\nnp.set_printoptions(threshold=np.nan)\nnp.set_printoptions(precision=16)\n\n\ndef matgen(m,condno):\n    [U,X] = np.linalg.qr(np.random.randn(m,m))\n    [V,X] = np.linalg.qr(np.random.randn(m,m))\n    S = np.diag(condno**((1-np.linspace(1,m,m))/(m-1)))\n    return U@S@V\n\ndef exercise_1():\n    ge_err,inv_err,cr_err = [],[],[]\n    m = 20\n    for condno in [0,4,8,12,16]:\n        \n        A = matgen(m,10**condno)\n        xtrue = np.random.rand(m)\n        b = A@xtrue\n\n        x_ge = np.linalg.solve(A,b)\n        ge_err.append([condno, np.linalg.norm(x_ge-xtrue)/np.linalg.norm(xtrue),\n               np.linalg.norm(b-A@x_ge)/(np.linalg.norm(A)*np.linalg.norm(x_ge))])\n        \n        Ainv =  np.linalg.inv(A)\n        x_inv = Ainv@b\n        inv_err.append([condno, np.linalg.norm(x_inv-xtrue)/np.linalg.norm(xtrue),\n               np.linalg.norm(b-A@x_inv)/(np.linalg.norm(A)*np.linalg.norm(x_inv))])\n    \n        detA = np.linalg.det(A)\n        x_cr = np.zeros(m)\n        for j in range(m):\n            A_j = copy.deepcopy(A)\n            A_j[:,j] = b\n            x_cr[j] = np.linalg.det(A_j)/detA\n        cr_err.append([condno, np.linalg.norm(x_cr-xtrue)/np.linalg.norm(xtrue),\n               np.linalg.norm(b-A@x_cr)/(np.linalg.norm(A)*np.linalg.norm(x_cr))])\n\n    return [ge_err,inv_err,cr_err]\n\ndef exercise_2():\n    m = 60\n    A = np.tril(np.full((m,m),-1),-1)+np.identity(m)\n    A[:,m-1] = np.full(m,1)\n    \n    x = np.random.randn(m,1)\n    b = A@x\n    \n    x_ge = np.linalg.solve(A,b)\n    \n    [Q,R] = np.linalg.qr(A)\n    x_qr = np.linalg.solve(R,Q.T@b)\n    \n#    plt.scatter(np.log10(x-x_ge),range(m))\n    return [np.linalg.cond(A,2),np.linalg.norm(x-x_ge,2),np.linalg.norm(x-x_qr,2)]\n", "meta": {"hexsha": "421e9400fab20a1ed98dadb095e8a58190784fb3", "size": 1735, "ext": "py", "lang": "Python", "max_stars_repo_path": "amath584/hw7/hw7.py", "max_stars_repo_name": "interesting-courses/UW_coursework", "max_stars_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-19T01:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T12:32:59.000Z", "max_issues_repo_path": "amath584/hw7/hw7.py", "max_issues_repo_name": "interesting-courses/UW_coursework", "max_issues_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "amath584/hw7/hw7.py", "max_forks_repo_name": "interesting-courses/UW_coursework", "max_forks_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-31T22:23:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T22:13:01.000Z", "avg_line_length": 29.9137931034, "max_line_length": 84, "alphanum_fraction": 0.5659942363, "include": true, "reason": "import numpy", "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096791, "lm_q2_score": 0.900529793459209, "lm_q1q2_score": 0.8531448529174578}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Vector manipulation in Python\n# \n# In this lab, you will have the opportunity to practice once again with the NumPy library. This time, we will explore some advanced operations with arrays and matrices.\n# \n# At the end of the previous module, we used PCA to transform a set of many variables into a set of only two uncorrelated variables. This process was made through a transformation of the data called rotation. \n# \n# In this week's assignment, you will need to find a transformation matrix from English to French vector space embeddings. Such a transformation matrix is nothing else but a matrix that rotates and scales vector spaces.\n# \n# In this notebook, we will explain in detail the rotation transformation. \n\n# ## Transforming vectors\n# \n# There are three main vector transformations:\n# * Scaling\n# * Translation\n# * Rotation\n# \n# In previous notebooks, we have applied the first two kinds of transformations. Now, let us learn how to use a fundamental transformation on vectors called _rotation_.\n# \n# The rotation operation changes the direction of a vector, letting unaffected its dimensionality and its norm. Let us explain with some examples. \n# \n# In the following cells, we will define a NumPy matrix and a NumPy array. Soon we will explain how this is related to matrix rotation.\n\n# In[1]:\n\n\nimport numpy as np                     # Import numpy for array manipulation\nimport matplotlib.pyplot as plt        # Import matplotlib for charts\nfrom utils_nb import plot_vectors      # Function to plot vectors (arrows)\n\n\n# ### Example 1\n\n# In[2]:\n\n\n# Create a 2 x 2 matrix\nR = np.array([[2, 0],\n              [0, -2]])\n\n\n# In[3]:\n\n\nx = np.array([[1, 1]]) # Create a 1 x 2 matrix\n\n\n# The dot product between a vector and a square matrix produces a rotation and a scaling of the original vector. \n# \n# Remember that our recommended way to get the dot product in Python is np.dot(a, b):\n\n# In[4]:\n\n\ny = np.dot(x, R) # Apply the dot product between x and R\ny\n\n\n# We are going to use Pyplot to inspect the effect of the rotation on 2D vectors visually. For that, we have created a function `plot_vectors()` that takes care of all the intricate parts of the visual formatting. The code for this function is inside the `utils_nb.py` file. \n# \n# Now we can plot the vector $\\vec x = [1, 1]$ in a cartesian plane. The cartesian plane will be centered at `[0,0]` and its x and y limits will be between `[-4, +4]`\n\n# In[5]:\n\n\nplot_vectors([x], axes=[4, 4], fname='transform_x.svg')\n\n\n# Now, let's plot in the same system our vector $\\vec x = [1, 1]$ and its dot product with the matrix\n# \n# $$Ro = \\begin{bmatrix} 2 & 0 \\\\ 0 & -2 \\end{bmatrix}$$\n# \n# $$y = x \\cdot Ro = [[2, -2]]$$\n\n# In[6]:\n\n\nplot_vectors([x, y], axes=[4, 4], fname='transformx_and_y.svg')\n\n\n# Note that the output vector `y` (blue) is transformed in another vector. \n\n# ### Example 2\n# \n# We are going to use Pyplot to inspect the effect of the rotation on 2D vectors visually. For that, we have created a function that takes care of all the intricate parts of the visual formatting. The following procedure plots an arrow within a Pyplot canvas.\n# \n# Data that is composed of 2 real attributes is telling to belong to a $ RxR $ or $ R^2 $ space. Rotation matrices in $R^2$ rotate a given vector $\\vec x$ by a counterclockwise angle $\\theta$ in a fixed coordinate system. Rotation matrices are of the form:\n# \n# $$Ro = \\begin{bmatrix} cos \\theta & -sin \\theta \\\\ sin \\theta & cos \\theta \\end{bmatrix}$$\n# \n# **(Note:** This notebook uses $$y = x \\cdot Ro$$ But if you use $$y = Ro \\cdot x.T$$\n# \n# Then the rotation matrices in $R^2$ rotate a given vector $\\vec x$ by a clockwise angle $\\theta$ in a fixed coordinate system.**)**\n# \n# The trigonometric functions in Numpy require the angle in radians, not in degrees. In the next cell, we define a rotation matrix that rotates vectors by $100^o$.\n\n# In[7]:\n\n\nangle = 100 * (np.pi / 180) #convert degrees to radians\n\nRo = np.array([[np.cos(angle), -np.sin(angle)],\n              [np.sin(angle), np.cos(angle)]])\n\nx2 = np.array([2, 2]).reshape(1, -1) # make it a row vector\ny2 = np.dot(x2, Ro)\n\nprint('Rotation matrix')\nprint(Ro)\nprint('\\nRotated vector')\nprint(y2)\n\nprint('\\n x2 norm', np.linalg.norm(x2))\nprint('\\n y2 norm', np.linalg.norm(y2))\nprint('\\n Rotation matrix norm', np.linalg.norm(Ro))\n\n\n# In[8]:\n\n\nplot_vectors([x2, y2], fname='transform_02.svg')\n\n\n# Some points to note:\n# \n# * The norm of the input vector is the same as the norm of the output vector. Rotations matrices do not modify the norm of the vector, only its direction.\n# * The norm of any $R^2$ rotation matrix is always $\\sqrt 2 = 1.414221$\n\n# ## Frobenius Norm\n# \n# The Frobenius norm is the generalization to $R^2$ of the already known norm function for vectors \n# \n# $$\\| \\vec a \\| = \\sqrt {{\\vec a} \\cdot {\\vec a}} $$\n# \n# For a given $R^2$ matrix A, the frobenius norm is defined as:\n# \n# $$\\|\\mathrm{A}\\|_{F} \\equiv \\sqrt{\\sum_{i=1}^{m} \\sum_{j=1}^{n}\\left|a_{i j}\\right|^{2}}$$\n# \n\n# In[9]:\n\n\nA = np.array([[2, 2],\n              [2, 2]])\n\n\n# `np.square()` is a way to square each element of a matrix. It must be equivalent to use the * operator in Numpy arrays.\n\n# In[10]:\n\n\nA_squared = np.square(A)\nA_squared\n\n\n# Now you can sum over the elements of the resulting array, and then get the square root of the sum.\n\n# In[11]:\n\n\nA_Frobenius = np.sqrt(np.sum(A_squared))\nA_Frobenius\n\n\n# That was the extended version of the `np.linalg.norm()` function. You can check that it yields the same result.\n\n# In[12]:\n\n\nprint('Frobenius norm of the Rotation matrix')\nprint(np.sqrt(np.sum(Ro * Ro)), '== ', np.linalg.norm(Ro))\n\n", "meta": {"hexsha": "61f98bd83fece6c119c0b86e7bedb674e096a9d2", "size": 5662, "ext": "py", "lang": "Python", "max_stars_repo_path": "Part1_Classification_VectorSpaces/C1_W4_lecture_nb_01_vector_manipulation.py", "max_stars_repo_name": "picsag/NLP", "max_stars_repo_head_hexsha": "7fe8ec5cf9636fbbe1d5dd077455f4db62800ec9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Part1_Classification_VectorSpaces/C1_W4_lecture_nb_01_vector_manipulation.py", "max_issues_repo_name": "picsag/NLP", "max_issues_repo_head_hexsha": "7fe8ec5cf9636fbbe1d5dd077455f4db62800ec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Part1_Classification_VectorSpaces/C1_W4_lecture_nb_01_vector_manipulation.py", "max_forks_repo_name": "picsag/NLP", "max_forks_repo_head_hexsha": "7fe8ec5cf9636fbbe1d5dd077455f4db62800ec9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1704545455, "max_line_length": 275, "alphanum_fraction": 0.6879194631, "include": true, "reason": "import numpy", "num_tokens": 1554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096791, "lm_q2_score": 0.900529782780931, "lm_q1q2_score": 0.8531448428010596}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Oct  1 21:39:53 2021\r\n\r\n@author: Oliver\r\n\"\"\"\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport timeit\r\n\r\nx=np.linspace(-10,10,50)\r\nf =  x**2 + 4*x - 12\r\nfunction = lambda x: x**2 + 4*x - 12\r\nplt.plot(x,f,'g')\r\ninput_a =  int(input(\"Please give value of a: \"))\r\ninput_b =  int(input(\"Please give value of b: \"))\r\n\r\ndef bisection(f,a,b,N):\r\n    if function(a)*function(b) >= 0:\r\n        print(\"Bisection method fails.\")\r\n        return None\r\n    a_n = a\r\n    b_n = b\r\n    for n in range(1,N+1):\r\n        m_n = (a_n + b_n)/2\r\n        f_m_n = function(m_n)\r\n        if function(a_n)*f_m_n < 0:\r\n                a_n = a_n\r\n                b_n = m_n\r\n        elif function(b_n)*f_m_n < 0:\r\n                a_n = m_n\r\n                b_n = b_n\r\n        elif f_m_n == 0:\r\n            print(f\"Found exact solution after {n} tries\")\r\n            return m_n\r\n        else:\r\n            print(\"Bisection method fails.\")\r\n            return None\r\n    return (a_n + b_n)/2\r\n    \r\nstart = timeit.default_timer()\r\napprox_phi = bisection(f,input_a,input_b,25)\r\nstop = timeit.default_timer()\r\nprint('Time of original bisection without  error: ', stop - start) \r\nprint(f'The zero is at: {approx_phi}')\r\n", "meta": {"hexsha": "dbb35d3f69e00a452249902afdcc217b3e9a2269", "size": 1240, "ext": "py", "lang": "Python", "max_stars_repo_path": "Bisection tutorial.py", "max_stars_repo_name": "oliver779/Computational_Methods_Course", "max_stars_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Bisection tutorial.py", "max_issues_repo_name": "oliver779/Computational_Methods_Course", "max_issues_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bisection tutorial.py", "max_forks_repo_name": "oliver779/Computational_Methods_Course", "max_forks_repo_head_hexsha": "e3d96d97ae0b3acaa1b61474eb18b3fbbf8edc9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9565217391, "max_line_length": 68, "alphanum_fraction": 0.5419354839, "include": true, "reason": "import numpy", "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.956634203708804, "lm_q2_score": 0.8918110540642805, "lm_q1q2_score": 0.8531369575634922}}
{"text": "#########################\n##                     ##\n## Irving Gomez Mendez ##\n##  February 12, 2021  ##\n##                     ##\n#########################\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import t\n\n# We want to adjust the next function\n#y = B + C cos(x) + D sin(x) + E cos(2x) + F sin(2x) + G cos(3x) + H sin(3x)\n\npoints = np.array([[-4,-1],[-3,0],[-2,-1.5],[-1,0.5],[0,1],[1,-1],[2,-0.5,],[3,2],[4,-1]])\n\npoints_x = points[:,0]\npoints_y = points[:,1]\ncos_x  = np.cos(points_x)\nsin_x  = np.sin(points_x)\ncos_2x = np.cos(2*points_x)\nsin_2x = np.sin(2*points_x)\ncos_3x = np.cos(3*points_x)\nsin_3x = np.sin(3*points_x)\n\nn = points.shape[0]\nyy = points_y\nXX = np.vstack([np.ones(n),cos_x,sin_x,cos_2x,sin_2x,cos_3x,sin_3x]).T\np = XX.shape[1]\n\n# We compute the coeff.\nB, C, D, E, F, G, H = np.linalg.lstsq(XX, yy, rcond=None)[0]\nparams  = [B, C, D, E, F, G, H]\n\n# Calculate the SSE\nSSE = np.linalg.lstsq(XX, yy, rcond=None)[1]\n\n# We get confidence interval\nalpha = 0.05\nx0 = np.linspace(-4.5, 4.5, 50)\nX0 = np.vstack([np.ones(len(x0)),np.cos(x0),np.sin(x0),\n    np.cos(2*x0),np.sin(2*x0),np.cos(3*x0),np.sin(3*x0)]).T\n\naux_t_conf = np.sqrt(SSE/(n-p)*(np.diag(X0 @ np.linalg.inv(XX.T @ XX) @ X0.T)))\nyy0_hat = X0 @ np.array(params)\nupp_conf = yy0_hat+t.ppf(1-alpha/2,n-p)*aux_t_conf\nlow_conf = yy0_hat-t.ppf(1-alpha/2,n-p)*aux_t_conf\n\n# We get prediction interval\naux_t_pred = np.sqrt(SSE/(n-p)*(1+np.diag(X0 @ np.linalg.inv(XX.T @ XX) @ X0.T)))\nyy0_hat = X0 @ np.array(params)\nupp_pred = yy0_hat+t.ppf(1-alpha/2,n-p)*aux_t_pred\nlow_pred = yy0_hat-t.ppf(1-alpha/2,n-p)*aux_t_pred\n\nplt.figure(figsize=(10,5))\nplt.plot(points_x, points_y, 'o', label='Original data', markersize=5)\nplt.plot(x0, B+C*np.cos(x0)+D*np.sin(x0)+E*np.cos(2*x0)+F*np.sin(2*x0)+G*np.cos(3*x0)+H*np.sin(3*x0),\n    'r', label='Fitted trigonometric function')\nplt.fill_between(x0, low_pred, upp_pred, facecolor='green', alpha=0.5, label='Prediction interval')\nplt.fill_between(x0, low_conf, upp_conf, facecolor='yellow', alpha=0.5, label='Confidence interval')\nplt.legend(loc='upper left')\n", "meta": {"hexsha": "09e784f17f3ebe0ada6a8625b9e2292a01da6ee5", "size": 2090, "ext": "py", "lang": "Python", "max_stars_repo_path": "content/courses/mod2021/3_best_fit_trigonometric_function.py", "max_stars_repo_name": "IrvingGomez/academic-hugo", "max_stars_repo_head_hexsha": "4f6e4ec4aab7a11f477883441b768bb6cf843a9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "content/courses/mod2021/3_best_fit_trigonometric_function.py", "max_issues_repo_name": "IrvingGomez/academic-hugo", "max_issues_repo_head_hexsha": "4f6e4ec4aab7a11f477883441b768bb6cf843a9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "content/courses/mod2021/3_best_fit_trigonometric_function.py", "max_forks_repo_name": "IrvingGomez/academic-hugo", "max_forks_repo_head_hexsha": "4f6e4ec4aab7a11f477883441b768bb6cf843a9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7096774194, "max_line_length": 101, "alphanum_fraction": 0.6253588517, "include": true, "reason": "import numpy,from scipy", "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.891811044719067, "lm_q1q2_score": 0.853136945315755}}
{"text": "import numpy as np\nfrom numpy import log, nan_to_num\n\n\nclass CrossEntropyCost:\n    @staticmethod\n    def evaluate(activation, true_label):\n        \"\"\"Return the cost associated with an output activation and desired output\n        ``y``.\n\n        The cross-entropy is positive number.\n        Note that np.nan_to_num is used to ensure numerical\n        stability.  In particular, if both ``a`` and ``y`` have a 1.0\n        in the same slot, then the expression (1-y)*np.log(1-a)\n        returns nan.  The np.nan_to_num ensures that that is converted\n        to the correct value (0.0).\n\n        \"\"\"\n        return np.sum(nan_to_num(-true_label * log(activation) - (1 - true_label) * log(1 - activation)))\n\n    @staticmethod\n    def delta(z, activation, true_label):\n        \"\"\"Computes the error delta from the output layer.\n\n        Note that the  parameter ``z`` is not used by the method.\n        It is included in the method's parameters in order to make the interface\n        consistent with the delta method for other cost classes.\n        \"\"\"\n        return activation - true_label\n\n\nclass QuadraticCost:\n    @staticmethod\n    def evaluate(activation, true_label):\n        \"\"\"Return the cost associated with an output activation and desired true label (``y``).\"\"\"\n        return 0.5 * np.linalg.norm(activation - true_label) ** 2\n\n    @staticmethod\n    def delta(z, activation, true_label):\n        \"\"\"Computes the error delta from the output layer.\"\"\"\n        return (activation - true_label) * QuadraticCost.sigmoid_prime(z)\n\n    @staticmethod\n    def derivative(output_activations, y):\n        r\"\"\"Return the vector of partial derivatives\n\n        \\partial C_x / \\partial a for the output activations.\"\"\"\n        return output_activations - y\n", "meta": {"hexsha": "1599a4ba7129bb08b5547f303c60da479df87474", "size": 1752, "ext": "py", "lang": "Python", "max_stars_repo_path": "basic_ml/src/neural_networks/base/costs.py", "max_stars_repo_name": "jmetzz/ml-laboratory", "max_stars_repo_head_hexsha": "26b1e87bd0d80efa4f15280f7f32ad46d59efc1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-10T16:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T16:55:35.000Z", "max_issues_repo_path": "basic_ml/src/neural_networks/base/costs.py", "max_issues_repo_name": "jmetzz/ml-laboratory", "max_issues_repo_head_hexsha": "26b1e87bd0d80efa4f15280f7f32ad46d59efc1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2022-03-12T01:06:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:30:22.000Z", "max_forks_repo_path": "basic_ml/src/neural_networks/base/costs.py", "max_forks_repo_name": "jmetzz/ml-laboratory", "max_forks_repo_head_hexsha": "26b1e87bd0d80efa4f15280f7f32ad46d59efc1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7551020408, "max_line_length": 105, "alphanum_fraction": 0.6615296804, "include": true, "reason": "import numpy,from numpy", "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633822, "lm_q2_score": 0.8918110440002045, "lm_q1q2_score": 0.853136943525471}}
{"text": "import numpy as np\r\n\r\n\r\n# Conval\r\ndef conv2(X, k):\r\n    x_row, x_col = X.shape\r\n    k_row, k_col = k.shape\r\n    ret_row, ret_col = x_row - k_row + 1, x_col - k_col + 1\r\n    \r\n    ret = np.empty((ret_row, ret_col))\r\n    for y in range(ret_row):\r\n        for x in range(ret_col):\r\n            sub = X[y: y + k_row, x: x + k_col]\r\n            ret[y, x] = np.sum(k * sub)            \r\n    return ret\r\n\t\r\n\r\ndef conv3(X, k):\r\n    x_row, x_col, x_ch = X.shape\r\n    k_row, k_col = k.shape\r\n    ret_row, ret_col, ret_ch = x_row - k_row + 1, x_col - k_col + 1, x_ch\r\n    \r\n    ret = np.empty((ret_row, ret_col, ret_ch))\r\n    for c in range(ret_ch):\r\n        for y in range(ret_row):\r\n            for x in range(ret_col):\r\n                sub = X[y: y + k_row, x: x + k_col, c: c+1]\r\n                ret[y, x, c] = np.sum(k * sub.reshape(k_row, k_col))          \r\n    return ret\r\n\t\r\n\t\r\n\t\r\n# MAX & MEAN Pooling\r\ndef pooling_2d(X, mode=np.max, size=2):\r\n    x_row, x_col = X.shape\r\n    ret_row, ret_col = x_row // size, x_col // size + 1\r\n    \r\n    ret = np.empty((ret_row, ret_col))\r\n    for i1, y in enumerate(range(0, x_row, size)):\r\n        for i2, x in enumerate(range(0, x_col, size)):\r\n            sub = X[y: y + size, x: x + size]\r\n            ret[i1, i2] = mode(sub)\r\n            \r\n    return ret\r\n\r\n\r\ndef pooling_3d(X, mode=np.max, size=2):\r\n    x_row, x_col, x_ch = X.shape\r\n    ret_row, ret_col = x_row // size, x_col // size + 1\r\n    \r\n    ret = np.empty((ret_row, ret_col, x_ch))\r\n    for c in range(x_ch):\r\n        for i1, y in enumerate(range(0, x_row, size)):\r\n            for i2, x in enumerate(range(0, x_col, size)):\r\n                sub = X[y: y + size, x: x + size, c: c + 1]\r\n                ret[i1, i2, c] = mode(sub)\r\n                \r\n    return ret\r\n\t\r\n\t\r\n\t\r\n\t\r\n# add Padding\r\ndef padding_2d(X, k_size=3):\r\n    x_row, x_col = X.shape\r\n    pad_size = (k_size - 1) // 2\r\n    \r\n    ret = np.zeros((x_row + pad_size*2, x_col+ pad_size*2))\r\n    ret[pad_size: x_row + pad_size, pad_size: x_col + pad_size] = X[:, :]   \r\n\r\n    return ret\r\n\t\r\n\t\r\ndef padding_3d(X, k_size=3):\r\n    x_row, x_col, x_ch = X.shape\r\n    pad_size = (k_size - 1) // 2\r\n    \r\n    ret = np.zeros((x_row + pad_size*2, x_col+ pad_size*2, x_ch))\r\n    ret[pad_size: x_row + pad_size, pad_size: x_col + pad_size, :] = X[:, :, :]   \r\n\r\n    return ret", "meta": {"hexsha": "fc16fdaa3d6012ab3d91b188f357998bffde582c", "size": 2323, "ext": "py", "lang": "Python", "max_stars_repo_path": "Algorithm/Nureal Network/FullyConnected/ConvNet/layer.py", "max_stars_repo_name": "sajjjadayobi/sadlearn", "max_stars_repo_head_hexsha": "8f6dba5960b09fcb01d09a1a0edfa96671d4300b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-09-21T15:27:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T18:24:43.000Z", "max_issues_repo_path": "Algorithm/Nureal Network/FullyConnected/ConvNet/layer.py", "max_issues_repo_name": "sajjjadayobi/sadlearn", "max_issues_repo_head_hexsha": "8f6dba5960b09fcb01d09a1a0edfa96671d4300b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Algorithm/Nureal Network/FullyConnected/ConvNet/layer.py", "max_forks_repo_name": "sajjjadayobi/sadlearn", "max_forks_repo_head_hexsha": "8f6dba5960b09fcb01d09a1a0edfa96671d4300b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6790123457, "max_line_length": 83, "alphanum_fraction": 0.5148514851, "include": true, "reason": "import numpy", "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997376, "lm_q2_score": 0.891811041124754, "lm_q1q2_score": 0.8531369418773121}}
{"text": "\"\"\"\nMath library example\n\"\"\"\nimport numpy as np\n\n\ndef euler(n):\n\n    \"\"\"Function to calculate Euler's number :math:`e` thorugh Taylor series\n\n    .. math::\n\n        e = 1 + \\\\sum_n^\\\\infty \\\\frac{1}{n!}\n\n    Parameters\n    ----------\n    n : int\n        Specify the order of the truncated series\n\n    Returns\n    -------\n    e_value : float\n        Euler number\n    \"\"\"\n\n    if n < 0:\n        raise ValueError(\"Only positive integers are allowed\")\n    n += 1\n    e_value = 0\n    for i in range(n):\n        e_value += 1 / factorial(i)\n    return e_value\n\n\ndef factorial(n):\n    if n > 0:\n        return n * factorial(n - 1)\n    else:\n        return 1\n\n\ndef pi(mc_points=1e7):\n\n    \"\"\"Function to calculate :math:`\\pi` using Monte-Carlo\n\n    Parameters\n    ----------\n    mc_points : int\n        Specify the number of points for the Monte Carlo integration\n\n    Returns\n    -------\n    result : float\n        Estimated value of :math:`\\pi`\n    \"\"\"\n    mc_points = int(mc_points)\n    x = np.random.uniform(0, 1, mc_points).reshape(-1, 2)\n    area = np.sum(np.linalg.norm(x, axis=1) < 1)\n    result = (area / mc_points) * 8\n    return result", "meta": {"hexsha": "c07d0e74540d93476ccdad72d03d323ee428dfdc", "size": 1137, "ext": "py", "lang": "Python", "max_stars_repo_path": "molssiexample/math.py", "max_stars_repo_name": "gbarbalinardo/molssiexample", "max_stars_repo_head_hexsha": "afb6ec378c085d89fde6e036c00f81040d862852", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "molssiexample/math.py", "max_issues_repo_name": "gbarbalinardo/molssiexample", "max_issues_repo_head_hexsha": "afb6ec378c085d89fde6e036c00f81040d862852", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "molssiexample/math.py", "max_forks_repo_name": "gbarbalinardo/molssiexample", "max_forks_repo_head_hexsha": "afb6ec378c085d89fde6e036c00f81040d862852", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.95, "max_line_length": 75, "alphanum_fraction": 0.5567282322, "include": true, "reason": "import numpy", "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.8918110368115781, "lm_q1q2_score": 0.8531369377511807}}
{"text": "#!/usr/bin/env python\n\nimport numpy as np\n\n\ndef sigmoid(x):\n    \"\"\"\n    Compute the sigmoid function for the input here.\n\n    Arguments:\n    x -- A scalar or numpy array.\n\n    Return:\n    s -- sigmoid(x)\n    \"\"\"\n\n    ### YOUR CODE HERE\n    s = 1 / (1 + np.exp(-1 * x))\n    ### END YOUR CODE\n\n    return s\n\n\ndef sigmoid_grad(s):\n    \"\"\"\n    Compute the gradient for the sigmoid function here. Note that\n    for this implementation, the input s should be the sigmoid\n    function value of your original input x.\n\n    Arguments:\n    s -- A scalar or numpy array.\n\n    Return:\n    ds -- Your computed gradient.\n    \"\"\"\n\n    ### YOUR CODE HERE\n    ds = s * (1 - s)\n    ### END YOUR CODE\n\n    return ds\n\n\ndef test_sigmoid_basic():\n    \"\"\"\n    Some simple tests to get you started.\n    Warning: these are not exhaustive.\n    \"\"\"\n    print \"Running basic tests...\"\n    x = np.array([[1, 2], [-1, -2]])\n    f = sigmoid(x)\n    g = sigmoid_grad(f)\n    print f\n    f_ans = np.array([\n        [0.73105858, 0.88079708],\n        [0.26894142, 0.11920292]])\n    assert np.allclose(f, f_ans, rtol=1e-05, atol=1e-06)\n    print g\n    g_ans = np.array([\n        [0.19661193, 0.10499359],\n        [0.19661193, 0.10499359]])\n    assert np.allclose(g, g_ans, rtol=1e-05, atol=1e-06)\n    print \"You should verify these results by hand!\\n\"\n\n\ndef test_sigmoid():\n    \"\"\"\n    Use this space to test your sigmoid implementation by running:\n        python q2_sigmoid.py\n    This function will not be called by the autograder, nor will\n    your tests be graded.\n    \"\"\"\n    print \"Running your tests...\"\n    ### YOUR CODE HERE\n    raise NotImplementedError\n    ### END YOUR CODE\n\n\nif __name__ == \"__main__\":\n    test_sigmoid_basic();\n    #test_sigmoid()\n", "meta": {"hexsha": "8a7b8be39b43611b8773419853198f295379abb2", "size": 1723, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment/cs224n_assignment/assignment1/q2_sigmoid.py", "max_stars_repo_name": "quoniammm/mine-tensorflow-examples", "max_stars_repo_head_hexsha": "22d66d29021e768ceb7a7e64ee0449024f93abfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-05-18T06:22:35.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-18T07:04:19.000Z", "max_issues_repo_path": "assignment/cs224n_assignment/assignment1/q2_sigmoid.py", "max_issues_repo_name": "quoniammm/mine-tensorflow-examples", "max_issues_repo_head_hexsha": "22d66d29021e768ceb7a7e64ee0449024f93abfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment/cs224n_assignment/assignment1/q2_sigmoid.py", "max_forks_repo_name": "quoniammm/mine-tensorflow-examples", "max_forks_repo_head_hexsha": "22d66d29021e768ceb7a7e64ee0449024f93abfc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.012195122, "max_line_length": 66, "alphanum_fraction": 0.5989553105, "include": true, "reason": "import numpy", "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.9416541602070125, "lm_q1q2_score": 0.8531290906399492}}
{"text": "#!/usr/local/bin/python\n#-*- coding: utf-8 -*-\n#\n# Author:   kentarowada\n# Mail:     www.kentaro.wada@gmail.com\n# URL:      http://wkentaro.com\n# Created:  2014-06-25\n# Filename: my_inv.py\n#\nimport numpy as np\n\ndef my_det(arr):\n    n = len(arr)\n    for i in range(n):\n        for j in range(n):\n            if i < j:\n                tmp = arr[j][i] / arr[i][i]\n                for k in range(n):\n                    arr[j][k] -= arr[i][k]*tmp\n\n    det = 1.0\n    for i in range(n):\n        det *= arr[i][i];\n    return det\n\ndef my_inv(arr):\n    arr = np.array(arr, dtype=np.float64)\n    n = len(arr)\n    iarr = np.identity(n)\n\n    # 掃き出し法\n    for i in range(n):\n        tmp = 1 / arr[i][i]\n        for j in range(n):\n            arr[i][j] *= tmp\n            iarr[i][j] *= tmp\n        for j in range(n):\n            if i != j:\n                tmp = arr[j][i]\n                for k in range(n):\n                    arr[j][k] -= arr[i][k] * tmp\n                    iarr[j][k] -= iarr[i][k] * tmp\n    return iarr\n\ndef my_output_inv(arr):\n    arr = np.array(arr)\n    print \"A-->\"\n    print arr\n\n    det = my_det(arr)\n    print \"determinant -->\",\n    print det\n\n    if int(det) == 0:\n        print \"--> No inverse array\"\n        return\n\n    iarr = my_inv(arr)\n    print \"A inverse -->\"\n    print iarr\n\n\ndef main():\n    arr = np.array([[1, 2],\n                    [3, 4]])\n    my_output_inv(arr)\n\n    print \"--\"\n\n    arr2 = np.array([[3, 2],\n                     [6, 4]])\n    my_output_inv(arr2)\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "372ef76a107e0e649fe827598012484d8079aacb", "size": 1527, "ext": "py", "lang": "Python", "max_stars_repo_path": "10_140623/my_inv.py", "max_stars_repo_name": "wkentaro-archive/lecture2014s-utmech-soft2", "max_stars_repo_head_hexsha": "4b4d831433d7b3cdce98b33d60740c4c08972b50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-11T12:16:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-11T12:16:48.000Z", "max_issues_repo_path": "10_140623/my_inv.py", "max_issues_repo_name": "wkentaro-archive/lecture2014s-utmech-soft2", "max_issues_repo_head_hexsha": "4b4d831433d7b3cdce98b33d60740c4c08972b50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "10_140623/my_inv.py", "max_forks_repo_name": "wkentaro-archive/lecture2014s-utmech-soft2", "max_forks_repo_head_hexsha": "4b4d831433d7b3cdce98b33d60740c4c08972b50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0921052632, "max_line_length": 50, "alphanum_fraction": 0.4518664047, "include": true, "reason": "import numpy", "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632329799586, "lm_q2_score": 0.896251377983158, "lm_q1q2_score": 0.8531087342097916}}
{"text": "import numpy as np\nfrom numpy.random import default_rng\n\n\ndef residual_sum_of_squares(predictions, y_values):\n    \"\"\"\n    Calculate the Residual Sum of Squares (RSS)\n\n    The sum of the squares of the residuals and the residuals is\n    the difference between the predicted output and the true output.\n\n    Returns:\n        the RSS value\n    \"\"\"\n    # then compute the residuals (since we are squaring it doesn't matter which order you subtract)\n    residuals = predictions - y_values\n    # square the residuals and add them up\n    return np.sum(residuals * residuals)\n\n\ndef predict_output(feature_matrix: np.ndarray, weights: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Predict the regression value for N input elements\n\n    Args:\n        feature_matrix: a 2D numpy matrix containing the features as columns\n        weights: a 1D numpy array of the corresponding feature weights\n\n    Returns:\n        a 1D numpy array with the respective model prediction\n    \"\"\"\n    return np.dot(feature_matrix, weights.T)\n\n\n# def predict_output(feature_matrix: np.ndarray, weights: np.ndarray) -> np.ndarray:\n#     \"\"\"\n#     Create a regression prediction vector by using dot product\n#\n#     Args:\n#         feature_matrix: a 2D numpy array with features as columns\n#         weights: a 1D numpy array of the corresponding feature weights\n#\n#     Returns:\n#         a 1D numpy array with the respective model prediction\n#     \"\"\"\n#     predictions = np.dot(feature_matrix, weights)\n#     return predictions\n\n\ndef random_init(size, seed=12345678903141592653589793):\n    rng = default_rng(seed)\n    return rng.standard_normal(size)\n", "meta": {"hexsha": "0a66b34d1bcfc7bff2fc0189ab63aa67aaba44a8", "size": 1611, "ext": "py", "lang": "Python", "max_stars_repo_path": "basic_ml/src/regression/base.py", "max_stars_repo_name": "jmetzz/ml-laboratory", "max_stars_repo_head_hexsha": "26b1e87bd0d80efa4f15280f7f32ad46d59efc1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-10T16:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T16:55:35.000Z", "max_issues_repo_path": "basic_ml/src/regression/base.py", "max_issues_repo_name": "jmetzz/ml-laboratory", "max_issues_repo_head_hexsha": "26b1e87bd0d80efa4f15280f7f32ad46d59efc1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2022-03-12T01:06:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:30:22.000Z", "max_forks_repo_path": "basic_ml/src/regression/base.py", "max_forks_repo_name": "jmetzz/ml-laboratory", "max_forks_repo_head_hexsha": "26b1e87bd0d80efa4f15280f7f32ad46d59efc1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3962264151, "max_line_length": 99, "alphanum_fraction": 0.7051520795, "include": true, "reason": "import numpy,from numpy", "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454895, "lm_q2_score": 0.8962513759047847, "lm_q1q2_score": 0.8531087334553235}}
{"text": "import numpy as np\n\nfrom typing import Tuple\nfrom numpy.typing import ArrayLike\nfrom liegroups.numpy import SO2, SE2, SO3, SE3\nfrom numpy import sin, cos\n\ndef angle_to_se2(a: float, theta: float) -> SE2:\n    \"\"\"Transform a single set of DH parameters into an SE2 matrix\n    :param a: link length\n    :param theta: rotation\n    :returns: SE2 matrix\n    :rtype: lie.SE2Matrix\n    \"\"\"\n    # R = SO2.from_angle(theta)  # TODO: active or passive (i.e., +/- theta?)\n    R = SO2.from_angle(theta)\n    return SE2(R, R.dot(np.array([a, 0.0])))  # TODO: rotate the translation or not?\n\ndef skew(x):\n    \"\"\"\n    Creates a skew symmetric matrix from vector x\n    \"\"\"\n    X = np.array([[0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]])\n    return X\n\ndef trans_axis(t, axis=\"z\") -> SE3:\n    if axis == \"z\":\n        return SE3(SO3.identity(), np.array([0, 0, t]))\n    if axis == \"y\":\n        return SE3(SO3.identity(), np.array([0, t, 0]))\n    if axis == \"x\":\n        return SE3(SO3.identity(), np.array([t, 0, 0]))\n    raise Exception(\"Invalid Axis\")\n\n\ndef rot_axis(theta, axis=\"z\") -> SE3:\n    if axis == \"z\":\n        return SE3(SO3.rotz(theta), np.array([0, 0, 0]))\n    if axis == \"y\":\n        return SE3(SO3.roty(theta), np.array([0, 0, 0]))\n    if axis == \"x\":\n        return SE3(SO3.rotx(theta), np.array([0, 0, 0]))\n    raise Exception(\"Invalid Axis\")\n\ndef max_min_distance_revolute(r, P, C, N):\n    delta = P-C\n    d_min_s = N.dot(delta)**2 + (np.linalg.norm(np.cross(N, delta)) - r)**2\n    if d_min_s > 0:\n        d_min = np.sqrt(d_min_s)\n    else:\n        d_min = 0\n    d_max_s = N.dot(delta)**2 + (np.linalg.norm(np.cross(N, delta)) + r)**2\n    if d_max_s > 0:\n        d_max = np.sqrt(d_max_s)\n    else:\n        d_max = 0\n\n    return d_max, d_min\n\ndef best_fit_transform(A: ArrayLike, B: ArrayLike) -> Tuple[ArrayLike, ArrayLike]:\n    \"\"\"\n    Calculates the least-squares best-fit transform that maps corresponding points A to B in m spatial dimensions\n    Input:\n      A: Nxm numpy array of corresponding points\n      B: Nxm numpy array of corresponding points\n    Returns:\n      R: mxm rotation matrix\n      t: mx1 translation vector\n    \"\"\"\n\n    # try:\n    assert A.shape == B.shape\n    # except AssertionError:\n    #     print(\"A: {:}\".format(A))\n    #     print(\"B: {:}\".format(B))\n\n    # get number of dimensions\n    m = A.shape[1]\n\n    # translate points to their centroids\n    centroid_A = np.mean(A, axis=0)\n    centroid_B = np.mean(B, axis=0)\n\n    AA = A - centroid_A\n    BB = B - centroid_B\n\n    # rotation matrix\n    H = np.dot(AA.T, BB)\n    U, S, Vt = np.linalg.svd(H)\n    R = np.dot(Vt.T, U.T)\n    # translation\n    #\n    # special reflection case\n    # if np.linalg.det(R) < 0:\n    #     print(\"det(R) < R, reflection detected!, correcting for it ...\\n\")\n    # Vt[2, :] *= -1\n    # R = np.dot(Vt.T, U.T)\n\n    t = centroid_B.T - np.dot(R, centroid_A.T)\n    return R, t\n", "meta": {"hexsha": "60adb82750aad0b72acbf4cbcbd16f6d413fce97", "size": 2884, "ext": "py", "lang": "Python", "max_stars_repo_path": "graphik/utils/geometry.py", "max_stars_repo_name": "utiasSTARS/GraphIK", "max_stars_repo_head_hexsha": "c2d05386bf9f9baf8ad146125bfebc3b73fccd14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-08T23:26:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-08T23:26:03.000Z", "max_issues_repo_path": "graphik/utils/geometry.py", "max_issues_repo_name": "utiasSTARS/GraphIK", "max_issues_repo_head_hexsha": "c2d05386bf9f9baf8ad146125bfebc3b73fccd14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphik/utils/geometry.py", "max_forks_repo_name": "utiasSTARS/GraphIK", "max_forks_repo_head_hexsha": "c2d05386bf9f9baf8ad146125bfebc3b73fccd14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5544554455, "max_line_length": 113, "alphanum_fraction": 0.580443828, "include": true, "reason": "import numpy,from numpy", "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632329799586, "lm_q2_score": 0.8962513682840824, "lm_q1q2_score": 0.8531087249775982}}
{"text": "#! /usr/bin/python\n\nimport sys, re\nfrom scipy.optimize.optimize import fmin_cg, fmin_bfgs, fmin\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy import loadtxt, where, zeros, e, array, log, ones, mean, where\nfrom pylab import scatter, show, legend, xlabel, ylabel, plot\nfrom scipy.optimize import fmin_bfgs\nimport math \n\ndef sigmoid(X):\n   g=1/(1+np.exp(-X))\n   return g\n\ndef costFunction(theta,X,y):\n   theta.shape = (1, 3)\n   m = y.size\n   h = sigmoid(X.dot(theta.conj().transpose()))\n   first = ((-y).T.dot(log(h)))\n   second = (1-y).T.dot(log(1-h))\n   J =(first - second)/m\n   return J.sum()\n\ndef gradFunction(theta,X,y):\n   theta.shape = (1, 3)\n   grad = zeros(3)\n   h = sigmoid(X.dot(theta.conj().transpose()))\n   delta = h - y\n   l = grad.size\n   for i in range(l):\n      sumdelta = delta.conj().transpose().dot(X[:, i])\n      grad[i] = (1.0 / m) * sumdelta * (-1)\n   theta.shape = (3,)\n   return grad\n\ndata = loadtxt('ex2data1.txt', delimiter=',')\nX = data[:, 0:2]\ny =  data[:, 2]\npos = where(y == 1)\nneg = where(y == 0)\nscatter(X[pos, 0], X[pos, 1], marker='o', c='b')\nscatter(X[neg, 0], X[neg, 1], marker='x', c='r')\nxlabel('X')\nylabel('Y')\nlegend(['X', 'Y'])\n\nm, n = X.shape\ny.shape = (m, 1)\ni = ones(shape=(m, 3))\ni[:, 1:3] = X\n\ndef learning_parameters(i, y):\n    def f(theta):\n        return costFunction(theta, i, y)\n\n    def fprime(theta):\n        return gradFunction(theta, i, y)\n    theta = zeros(3)\n    return fmin_bfgs(f, theta, fprime, disp=True, maxiter=400)\n\nlearning_parameters(i, y)\ntheta = [-25.161272, 0.206233, 0.201470]\n\nplot_x = array([min(i[:, 1]) - 2, max(i[:, 2]) + 2])\nplot_y = (-1/theta[2]) * (theta[1] * plot_x + theta[0])\n\nplot(plot_x, plot_y)\nlegend(['Decision', 'Admitted', 'Not-Admitted'])\nshow()\n\nprob = sigmoid(array([1.0, 45.0, 85.0]).dot(array(theta).conj().transpose()))\nprint 'Probability: %f' % prob\n\ndef predict(theta,X):\n   m, n = X.shape\n   p = zeros(shape=(m, 1))\n   h = sigmoid(X.dot(theta.conj().transpose()))\n\n   for i in range(0, h.shape[0]):\n        if h[i] > 0.5:\n            p[i, 0] = 1\n        else:\n            p[i, 0] = 0\n   return p\n\np = predict(array(theta), i)\nprint \"Train Accuracy:\",((y[where(p == y)].size / float(y.size)) * 100.0)\n\n", "meta": {"hexsha": "58dc017a9c85a6b9569879b0805d6ab70a1e052b", "size": 2212, "ext": "py", "lang": "Python", "max_stars_repo_path": "log.py", "max_stars_repo_name": "kulkarniankita/LogisticRegression", "max_stars_repo_head_hexsha": "bfd9cd9ce53b8ef156dc283d3a360b49da69982a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-06-26T06:16:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:32:26.000Z", "max_issues_repo_path": "log.py", "max_issues_repo_name": "kulkarniankita/LogisticRegression", "max_issues_repo_head_hexsha": "bfd9cd9ce53b8ef156dc283d3a360b49da69982a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "log.py", "max_forks_repo_name": "kulkarniankita/LogisticRegression", "max_forks_repo_head_hexsha": "bfd9cd9ce53b8ef156dc283d3a360b49da69982a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-05-09T06:46:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-07T04:16:22.000Z", "avg_line_length": 24.5777777778, "max_line_length": 77, "alphanum_fraction": 0.5899638336, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488964, "lm_q2_score": 0.8962513655129178, "lm_q1q2_score": 0.8531087198921103}}
{"text": "\"\"\"Exercise 1\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\nfrom scipy.signal import butter, lfilter\nfrom scipy import fftpack\n\ndef gaussian(x, mu, sigma, A):\n    return A*np.exp(-(x - mu)**2/(2*sigma**2))\n\nsample_rate = 30\nT = 5\nt = np.linspace(0, T, T*sample_rate, endpoint=False)\ny = gaussian(t, 3.1, 0.2, 3) + np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t)\nplt.plot(t, y)\n\nz = fftpack.rfft(y)\nf = fftpack.rfftfreq(len(t), t[1] - t[0])\n\nmaxima = f[np.abs(z)**2 > 2100]\nprint(\"Noise frequencies:\", maxima)\n\nplt.figure(1)\nplt.plot(f, np.abs(z)**2)\nplt.xlabel('f / Hz')\nfor freq in maxima:\n    plt.axvline(x=freq, color='black', alpha=0.3, lw=5)\nplt.title('Discovery of Noise Frequencies')\n\ndef bandstop_filter(data, freq_window, fs, order=5):\n    nyquist_frequency = fs/2\n    freq_window = np.array(freq_window)\n    normal_freq = freq_window/nyquist_frequency\n    b, a = butter(order, normal_freq, btype='bandstop')\n    y = lfilter(b, a, data)\n    return y\n\nplt.figure(2)\nsample_rate = (len(t) - 1)/(t[-1])\ny_filt = bandstop_filter(y, [1.15, 1.25], sample_rate)\ny_filt = bandstop_filter(y_filt, [8.9, 9.1], sample_rate)\nplt.plot(t, y_filt)\nplt.title('Data after bandstop filtering')\n\nparams, __ = curve_fit(gaussian, t, y_filt)\nprint(\"Gaussian paramaters:\", params)\n\nplt.figure(3)\nplt.plot(t, gaussian(t, *params))\nplt.plot(t, y_filt)\nplt.title('Filtered data fit with Gaussian');\n\n\n\"\"\"Exercise 2\"\"\"\n\nfrom scipy.special import eval_legendre\nfrom scipy.integrate import quad\n\ndef f(x):\n    return np.sin(np.pi*x)\n\ndef a(n):\n    g = lambda x: f(x)*eval_legendre(n, x)\n    integral = quad(g, -1, 1)[0]\n    return (2*n + 1)/2 * integral\n\n# first few a_n coefficients up to n = 5\nprint(\"Coefficients:\", [a(n) for n in range(5+1)])\n\ndef legendre_series(x, N):\n    y = np.zeros(len(x))\n    for n in range(N+1):\n        y += a(n)*eval_legendre(n, x)\n    return y\n\nx = np.linspace(-1, 1, 100)\nplt.plot(x, f(x), label=r'$\\sin(nx)$')\nplt.plot(x, legendre_series(x, 5), label=r'$\\sum_{n=0}^{5} a_n P_n(x)$')\nplt.legend(loc='best');\n", "meta": {"hexsha": "b7950790f9e612df4951454ba93f543aee4a70a6", "size": 2068, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/solutions/07_01_scipy.py", "max_stars_repo_name": "Python4AstronomersAndParticlePhysicists/PythonWorkshop-ICE", "max_stars_repo_head_hexsha": "f1de2c85fd2d73c6f111987dd201a8ec09c1d4bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-07-10T13:31:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-01T16:07:39.000Z", "max_issues_repo_path": "notebooks/solutions/07_01_scipy.py", "max_issues_repo_name": "Python4AstronomersAndParticlePhysicists/PythonWorkshop-ICE", "max_issues_repo_head_hexsha": "f1de2c85fd2d73c6f111987dd201a8ec09c1d4bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2017-06-29T12:48:20.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-18T08:53:07.000Z", "max_forks_repo_path": "notebooks/solutions/07_01_scipy.py", "max_forks_repo_name": "Python4AstronomersAndParticlePhysicists/PythonWorkshop-ICE", "max_forks_repo_head_hexsha": "f1de2c85fd2d73c6f111987dd201a8ec09c1d4bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-09-19T08:13:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-22T15:50:36.000Z", "avg_line_length": 25.5308641975, "max_line_length": 78, "alphanum_fraction": 0.6590909091, "include": true, "reason": "import numpy,from scipy", "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793908, "lm_q2_score": 0.8872046041554922, "lm_q1q2_score": 0.8530772205145534}}
{"text": "import numpy as np\nimport polyFit\nimport scipy\nfrom scipy import interpolate\nimport matplotlib.pyplot as plt\n\nh=[0.0,1.525,3.050,4.575,6.1,7.625,9.15] #x values\nden=[1,0.8617,0.7385,0.6292,0.5328,0.4481,0.3741] #y values\nhrang=np.linspace(0,9.15,100)\n\nprint 'Using Polynomial Interpolation: ', '\\n'\n\nl_001=interpolate.barycentric_interpolate(h,den,(2,5)) #Using interpolate from scipy. Uses barycentric polynomial interpolation. Arguments: (x values, y values, points at which you wish to evaluate)\n\nprint 'At 2km the density of air will be ', l_001[0]\n\nprint 'At 5km the density of air will be ', l_001[1]\n\n###\nprint '\\n', 'Using Cubic Splines: ', '\\n'\n\nl_002=interpolate.interp1d(h,den,kind='cubic') #Interpolatioon from scipy. Uses cubic splines. Arguments: (x values, y values, order of splines)\n\nprint 'At 2km the density of air will be ', l_002(2) #Calls for interpolation to be evaluated at argument\n\nprint 'At 5km the density of air will be ', l_002(5)\n\n\n###\n\nprint '\\n', 'Using Least Squares Fit: ', '\\n'\n\nl=polyFit.polyFit(h,den,2) #Using polyFit module to generate a list of coefficients. Arguments: (x values, y values, degree of polynomial)\n\ndef l_003(x): #defining a function for the polynomial generated by polyFit\n\tl_003=l[0]+l[1]*x+l[2]*x**2\n\treturn l_003\n\nprint 'At 2km the density of air will be ', l_003(2) #using function as defined above\n\nprint 'At 5km the density of air will be ', l_003(5)\n\n\n\n###\n\ndenl_001=interpolate.barycentric_interpolate(h,den,hrang)\ndenl_002=l_002(hrang)\ndenl_003=l_003(hrang)\n\nplt.figure(1)\nplt.plot(hrang,denl_001,'r-',2,interpolate.barycentric_interpolate(h,den,2),'bo',5,interpolate.barycentric_interpolate(h,den,5),'bo')\nplt.axis([0,10,0.2,1])\nplt.xlabel('Height (km)')\nplt.ylabel('Air Density')\nplt.title('Barycentric Interpolation')\nplt.show()\n\nplt.figure(2)\nplt.plot(hrang,denl_002,'r-',2,l_002(2),'bo',5,l_002(5),'bo')\nplt.axis([0,10,0.2,1])\nplt.xlabel('Height (km)')\nplt.ylabel('Air Density')\nplt.title('Cubic Splines')\nplt.show()\n\nplt.figure(3)\nplt.plot(hrang,denl_003,'r-',2,l_003(2),'bo',5,l_003(5),'bo')\nplt.axis([0,10,0.2,1])\nplt.xlabel('Height (km)')\nplt.ylabel('Air Density')\nplt.title('Least Squares Fit')\nplt.show()\n\nplt.figure(4)\nplt.plot(h,den,'ro')\nplt.axis([0,10,0.2,1])\nplt.xlabel('Height (km)')\nplt.ylabel('Air Density')\nplt.title('Original Data')\nplt.show()\n", "meta": {"hexsha": "a4f681023edd23af87dc527cc30041fcae96375a", "size": 2331, "ext": "py", "lang": "Python", "max_stars_repo_path": "ExamPrep/04 Curve Fitting & Interpolation/shigInterp.py", "max_stars_repo_name": "FHomewood/ScientificComputing", "max_stars_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_stars_repo_licenses": ["IJG"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ExamPrep/04 Curve Fitting & Interpolation/shigInterp.py", "max_issues_repo_name": "FHomewood/ScientificComputing", "max_issues_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_issues_repo_licenses": ["IJG"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ExamPrep/04 Curve Fitting & Interpolation/shigInterp.py", "max_forks_repo_name": "FHomewood/ScientificComputing", "max_forks_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_forks_repo_licenses": ["IJG"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4268292683, "max_line_length": 198, "alphanum_fraction": 0.7177177177, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338057771059, "lm_q2_score": 0.8872045981907007, "lm_q1q2_score": 0.8530772138012526}}
{"text": "# Accepts a filename containing numeric values in each line of which the statistics need to be calculated.\n# Alternately as second argument, the bucket size can also be passed.\nimport sys\nimport numpy as np\n\nfileName = sys.argv[1]\n# find median of bucket splits of data\nbuckets = 5\n\nif len(sys.argv) == 3:\n    # Assuming the 2nd argument is the bucket size\n    # if it exists\n    buckets = int(sys.argv[2])\n\ndata = np.fromfile(fileName,sep=\"\\n\")\nnmap = len(data) # Number of hashes used.\nprint(\"(mean of {} hashes) = {}\".format(nmap,np.mean(data)))\n\n# Finding mean of medians and vice-versa now\nidxes = np.arange(nmap)\nnp.random.shuffle(idxes)\n# numpy.array_split allows unequal splits of data\ngroups = np.array_split(idxes, buckets)\n\nmean_of_medians = np.mean([np.median(data[group_idxs]) for group_idxs in groups])\nmedian_of_means = np.median([np.mean(data[group_idxs]) for group_idxs in groups])\nprint(\"mean of medians (from {} buckets of data) : {}\".format(buckets, mean_of_medians))\nprint(\"median of means (from {} buckets of data) : {}\".format(buckets, median_of_means))\nprint(\"Standard Deviation : {}\".format(np.std(data)))\n", "meta": {"hexsha": "fd8688ccc489b0b54319990246ce5d9dcc8cf48e", "size": 1131, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/approximate/mean_of_medians.py", "max_stars_repo_name": "kunalghosh/T-61.5060-Algorithmic-Methods-of-Data-Mining", "max_stars_repo_head_hexsha": "718b1ca4a3f83f1b244bb7ddeb5cc430b2967516", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/approximate/mean_of_medians.py", "max_issues_repo_name": "kunalghosh/T-61.5060-Algorithmic-Methods-of-Data-Mining", "max_issues_repo_head_hexsha": "718b1ca4a3f83f1b244bb7ddeb5cc430b2967516", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/approximate/mean_of_medians.py", "max_forks_repo_name": "kunalghosh/T-61.5060-Algorithmic-Methods-of-Data-Mining", "max_forks_repo_head_hexsha": "718b1ca4a3f83f1b244bb7ddeb5cc430b2967516", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7, "max_line_length": 106, "alphanum_fraction": 0.7294429708, "include": true, "reason": "import numpy", "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862455, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.8530772091100377}}
{"text": "import numpy as np\n\n\ndef f1(x, y, z):\n    res = x + 3 * y + 2 * z\n    return res, res == 5\n\n\ndef f2(x, y, z):\n    res = 2 * x + -y + -z\n    return res, res == 1\n\n\ndef f3(x, y, z):\n    res = -x + 2 * y + z\n    return res, res == 3\n\n\nx = 0.75\ny = 3.25\nz = -2.75\n\nprint(f1(x, y, z))\nprint(f2(x, y, z))\nprint(f3(x, y, z))\n\nb = np.array([5, 1, 3])\nA = np.array([\n    [1, 3, 2],\n    [2, -1, -1],\n    [-1, 2, 1]\n])\n\nsol2 = np.linalg.solve(A, b)\nprint(sol2)\nprint(A.dot(sol2))\n\n# Ax = b\n# inv(A)x = inv(A)b\n# x = inv(A)b\n\nprint(np.linalg.inv(A).dot(b))\n\nA2 = np.array([\n    [1, 3, 2],\n    [0, 3, 1],\n    [0, 0, -4]\n])\n\nB2 = np.array([5,7,11])\n\nprint(np.linalg.solve(A2, B2))", "meta": {"hexsha": "de8e1f3e519f1780391dab892aa750d5ed70ebe9", "size": 666, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/msc/linear_algebra/ch1_1_7.py", "max_stars_repo_name": "gerritjvv/optimization_algorithms", "max_stars_repo_head_hexsha": "eab2e8fff39eeab8d9be45af3dae3be1a62be3ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/msc/linear_algebra/ch1_1_7.py", "max_issues_repo_name": "gerritjvv/optimization_algorithms", "max_issues_repo_head_hexsha": "eab2e8fff39eeab8d9be45af3dae3be1a62be3ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/msc/linear_algebra/ch1_1_7.py", "max_forks_repo_name": "gerritjvv/optimization_algorithms", "max_forks_repo_head_hexsha": "eab2e8fff39eeab8d9be45af3dae3be1a62be3ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.8076923077, "max_line_length": 30, "alphanum_fraction": 0.4564564565, "include": true, "reason": "import numpy", "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338090839606, "lm_q2_score": 0.8872045877523147, "lm_q1q2_score": 0.8530772066982482}}
{"text": "## module jacobi\r\n''' lam,x = jacobi(a,tol = 1.0e-8).\r\n    Solution of std. eigenvalue problem [a]{x} = lam{x}\r\n    by Jacobi's method. Returns eigenvalues in vector {lam}\r\n    and the eigenvectors as columns of matrix [x].\r\n'''\r\nimport numpy as np\r\nimport math\r\n\r\ndef jacobi(a,tol = 1.0e-8): # Jacobi method\r\n\r\n    def threshold(a):\r\n        sum = 0.0\r\n        for i in range(n-1):\r\n            for j in range (i+1,n):\r\n                sum = sum + abs(a[i,j])\r\n        return 0.5*sum/n/(n-1)\r\n\r\n    def rotate(a,p,k,l): # Rotate to make a[k,l] = 0\r\n        aDiff = a[l,l] - a[k,k]\r\n        if abs(a[k,l]) < abs(aDiff)*1.0e-36: t = a[k,l]/aDiff\r\n        else:\r\n            phi = aDiff/(2.0*a[k,l])\r\n            t = 1.0/(abs(phi) + math.sqrt(phi**2 + 1.0))\r\n            if phi < 0.0: t = -t\r\n        c = 1.0/math.sqrt(t**2 + 1.0); s = t*c\r\n        tau = s/(1.0 + c)\r\n        temp = a[k,l]\r\n        a[k,l] = 0.0\r\n        a[k,k] = a[k,k] - t*temp\r\n        a[l,l] = a[l,l] + t*temp\r\n        for i in range(k):      # Case of i < k\r\n            temp = a[i,k]\r\n            a[i,k] = temp - s*(a[i,l] + tau*temp)\r\n            a[i,l] = a[i,l] + s*(temp - tau*a[i,l])\r\n        for i in range(k+1,l):  # Case of k < i < l\r\n            temp = a[k,i]\r\n            a[k,i] = temp - s*(a[i,l] + tau*a[k,i])\r\n            a[i,l] = a[i,l] + s*(temp - tau*a[i,l])\r\n        for i in range(l+1,n):  # Case of i > l\r\n            temp = a[k,i]\r\n            a[k,i] = temp - s*(a[l,i] + tau*temp)\r\n            a[l,i] = a[l,i] + s*(temp - tau*a[l,i])\r\n        for i in range(n):      # Update transformation matrix\r\n            temp = p[i,k]\r\n            p[i,k] = temp - s*(p[i,l] + tau*p[i,k])\r\n            p[i,l] = p[i,l] + s*(temp - tau*p[i,l])\r\n        \r\n    n = len(a)        \r\n    p = np.identity(n,float)\r\n    for k in range(20):\r\n        mu = threshold(a)       # Compute new threshold\r\n        for i in range(n-1):    # Sweep through matrix\r\n            for j in range(i+1,n):   \r\n                if abs(a[i,j]) >= mu:\r\n                    rotate(a,p,i,j)\r\n        if mu <= tol: return np.diagonal(a),p\r\n    print('Jacobi method did not converge')\r\n        \r\n", "meta": {"hexsha": "1754e5a9937366246305a14dd06937a2be4647bc", "size": 2141, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/book/jacobi.py", "max_stars_repo_name": "krontzo/nume.py", "max_stars_repo_head_hexsha": "9d1e576fb3474333a8e2cf4f26f4236ee4f9deea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/book/jacobi.py", "max_issues_repo_name": "krontzo/nume.py", "max_issues_repo_head_hexsha": "9d1e576fb3474333a8e2cf4f26f4236ee4f9deea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/book/jacobi.py", "max_forks_repo_name": "krontzo/nume.py", "max_forks_repo_head_hexsha": "9d1e576fb3474333a8e2cf4f26f4236ee4f9deea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6833333333, "max_line_length": 63, "alphanum_fraction": 0.422699673, "include": true, "reason": "import numpy", "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338035725358, "lm_q2_score": 0.8872045922259089, "lm_q1q2_score": 0.8530772061099988}}
{"text": "from __future__ import division\nimport numpy as np\nfrom scipy.sparse import spdiags\nfrom scipy.sparse.linalg import spsolve, cg\n\ndef general_secondorder_ode_fd(func,a1,a2,a3,a=0.,b=1.,alpha=1.,beta=3.,N=5):\n\t# A Simple Finite Difference Scheme to solve BVP's of the form \n\t# a1(x)u''(x) + a2(x)u'(x) + a3(x)u(x) = f(x), x \\in [a,b]\n\t# u(a) = alpha\n\t# u(b) = beta\n\t# (Dirichlet boundary conditions)\n\t# \n\t# U_0 = alpha, U_1, U_2, ..., U_m, U_{m+1} = beta\n\t# We use m+1 subintervals, giving m algebraic equations\n    m = N-1\n    h = (b-a)/(m+1.)         # Here we form the diagonals\n    D0,Dp,Dm,diags = np.zeros((1,m)), np.zeros((1,m)), np.zeros((1,m)), np.array([0,-1,1])\n    for j in range(1,D0.shape[1]):\n\t\txj = a + (j)*h\n\t\tD0[0,j]   = h**2.*a3(xj)-2.*a1(xj)\n\t\tDp[0,j]   = a1(xj)-h*a2(xj)/2.\n\t\tDm[0,j-1] = a1(xj)+h*a2(xj)/2.\n    # xj = a + 1.*h\n    # D0[0,0] = h**2.*a3(xj)-2.*a1(xj)\n\t\n    # Here we create the matrix A\n    data = np.concatenate((D0,Dm,Dp),axis=0) # This stacks up rows\n    A=h**(-2.)*spdiags(data,diags,m,m).asformat('csr')\n\t\n\t# Here we create the vector B\n    B = np.zeros(m+2)\n    for j in range(2,m):\n        B[j] = func(a + j*h)\n    xj = a+1.*h\n    B[0], B[1] = alpha, func(xj)-alpha *( a1(xj)*h**(-2.) + a2(xj)*h**(-1)/2. )\n    xj = a+m*h\n    B[-1], B[-2]  = beta, func(xj)-beta*( a1(xj)*h**(-2.) - a2(xj)*h**(-1)/2. )\n\t\n    # Here we solve the equation AX = B and return the result\n    B[1:-1] = spsolve(A,B[1:-1])\n    return np.linspace(a,b,m+2), B\n\n\n\n# def general_secondorder_ode_fd(func,a1,a2,a3,a=0.,b=1.,alpha=1.,beta=3.,N=5):\n# \t# A Simple Finite Difference Scheme to solve BVP's of the form \n# \t# a1(x)u''(x) + a2(x)u'(x) + a3(x)u(x) = f(x), x \\in [a,b]\n# \t# u(a) = alpha\n# \t# u(b) = beta\n# \t# (Dirichlet boundary conditions)\n# \t# \n# \t# U_0 = alpha, U_1, U_2, ..., U_m, U_{m+1} = beta\n# \t# We use m+1 subintervals, giving m algebraic equations\n#     m = N-1\n#     h = (b-a)/(m+1.)         # Here we form the diagonals\n#     D0,D1,D2,diags = np.zeros((1,m)), np.zeros((1,m)), np.zeros((1,m)), np.array([0,-1,1])\n#     for j in range(1,D1.shape[1]):\n# \t\txj = a + (j+1)*h\n# \t\tD0[0,j] = h**2.*a3(xj)-2.*a1(xj)\n# \t\tD1[0,j] = a1(xj)+h*a2(xj)/2.\n# \t\tD2[0,j-1] = a1(xj)-h*a2(xj)/2.\n#     xj = a + 1.*h\n#     D0[0,0] = h**2.*a3(xj)-2.*a1(xj)\n# \t\n#     # Here we create the matrix A\n#     data = np.concatenate((D0,D2,D1),axis=0) # This stacks up rows\n#     A=h**(-2.)*spdiags(data,diags,m,m).asformat('csr')\n# \t\n# \t# Here we create the vector B\n#     B = np.zeros(m+2)\n#     for j in range(2,m):\n#         B[j] = func(a + j*h)\n#     xj = a+1.*h\n#     B[0], B[1] = alpha, func(xj)-alpha *( a1(xj)*h**(-2.) - a2(xj)*h**(-1)/2. )\n#     xj = a+m*h\n#     B[-1], B[-2]  = beta, func(xj)-beta*( a1(xj)*h**(-2.) + a2(xj)*h**(-1)/2. )\n# \t\n#     # Here we solve the equation AX = B and return the result\n#     B[1:-1] = spsolve(A,B[1:-1])\n#     return np.linspace(a,b,m+2), B\n# \n\n", "meta": {"hexsha": "23fb6f6280c0c7d9d0c9845edcd4da855abf73a2", "size": 2894, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/FiniteDifferenceMethod/solution.py", "max_stars_repo_name": "rachelwebb/numerical_computing", "max_stars_repo_head_hexsha": "e7416b43b97976060f6875fa46c7dca20a9f635f", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Labs/FiniteDifferenceMethod/solution.py", "max_issues_repo_name": "rachelwebb/numerical_computing", "max_issues_repo_head_hexsha": "e7416b43b97976060f6875fa46c7dca20a9f635f", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/FiniteDifferenceMethod/solution.py", "max_forks_repo_name": "rachelwebb/numerical_computing", "max_forks_repo_head_hexsha": "e7416b43b97976060f6875fa46c7dca20a9f635f", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-08T01:19:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T01:19:23.000Z", "avg_line_length": 34.8674698795, "max_line_length": 92, "alphanum_fraction": 0.5259156876, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305339244012, "lm_q2_score": 0.8856314723088733, "lm_q1q2_score": 0.8530672759323296}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats as stats\n\n# (a)\nn_1 = 50\nn_2 = 50\nx_1 = 40\nx_2 = 30\np_hat_1 = x_1 / n_1\np_hat_2 = x_2 / n_2\ntau_hat = p_hat_1 - p_hat_2\ntau_se_hat = np.sqrt(\n    p_hat_1 * (1 - p_hat_1) / n_1 + p_hat_2 * (1 - p_hat_2) / n_2\n)\nalpha = 0.1\nz_alpha = stats.norm.ppf(1 - alpha / 2)\nci = (tau_hat - z_alpha * tau_se_hat, tau_hat + z_alpha * tau_se_hat)\nprint(f\"MLE for tau is {tau_hat:.4}.\")\nprint(f\"Standard error for tau is {tau_se_hat:.4}.\")\nprint(f\"90% CI for tau is [{ci[0]:.4}, {ci[1]:.4}].\")\nprint()\n\n# (b)\nsims = 5_000\nrng = np.random.default_rng(42)\nx_1_draws = rng.binomial(n_1, p_hat_1, size=sims)\nx_2_draws = rng.binomial(n_2, p_hat_2, size=sims)\ntau_draws = x_1_draws / n_1 - x_2_draws / n_2\nbootstrap_ci = (\n    np.quantile(tau_draws, alpha / 2),\n    np.quantile(tau_draws, 1 - alpha / 2),\n)\nprint(\n    \"90% parametric bootstrap CI for tau is\",\n    f\"[{bootstrap_ci[0]:.4}, {bootstrap_ci[1]:.4}].\",\n)\nprint()\n\n# (c)\ntaus = np.arange(-n_2, n_1 + 1)\np_1_posterior_draws = rng.beta(x_1 + 1, n_1 - x_1 + 1, size=sims)\np_2_posterior_draws = rng.beta(x_2 + 1, n_2 - x_2 + 1, size=sims)\ntau_posterior_draws = p_1_posterior_draws - p_2_posterior_draws\ntau_posterior_mean = tau_posterior_draws.mean()\nposterior_ci = (\n    np.quantile(tau_posterior_draws, alpha / 2),\n    np.quantile(tau_posterior_draws, 1 - alpha / 2),\n)\nprint(f\"The posterior mean for tau is {tau_posterior_mean:.4}.\")\nprint(\n    \"90% posterior CI for tau is\",\n    f\"[{posterior_ci[0]:.4}, {posterior_ci[1]:.4}].\",\n)\nprint()\n\n# (d)\npsi_hat = np.log((p_hat_1 / (1 - p_hat_1)) / (p_hat_2 / (1 - p_hat_2)))\npsi_se_hat = np.sqrt(\n    1 / (n_1 * (p_hat_1 - p_hat_1 ** 2)) + 1 / (n_2 * (p_hat_2 ** 2 - p_hat_2))\n)\npsi_ci = (psi_hat - z_alpha * psi_se_hat, psi_hat + z_alpha * psi_se_hat)\nprint(f\"MLE for psi is {psi_hat:.4}.\")\nprint(f\"Standard error for psi is {psi_se_hat:.4}.\")\nprint(f\"90% CI for psi is [{psi_ci[0]:.4}, {psi_ci[1]:.4}].\")\nprint()\n\n\n# (e)\npsi_posterior_draws = np.log(\n    (p_1_posterior_draws / (1 - p_1_posterior_draws))\n    / (p_2_posterior_draws / (1 - p_2_posterior_draws))\n)\npsi_posterior_mean = psi_posterior_draws.mean()\npsi_posterior_ci = (\n    np.quantile(psi_posterior_draws, alpha / 2),\n    np.quantile(psi_posterior_draws, 1 - alpha / 2),\n)\nprint(f\"The posterior mean for psi is {psi_posterior_mean:.4}.\")\nprint(\n    \"90% posterior CI for psi is\",\n    f\"[{psi_posterior_ci[0]:.4}, {psi_posterior_ci[1]:.4}].\",\n)\n", "meta": {"hexsha": "c733f441950135166352cfa8c6eec26536d2658f", "size": 2460, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/code/11-04.py", "max_stars_repo_name": "dtrifuno/all-of-stats-solutions", "max_stars_repo_head_hexsha": "0572cdae22b128e71c1c6c7ead2bf3b259875bc9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/code/11-04.py", "max_issues_repo_name": "dtrifuno/all-of-stats-solutions", "max_issues_repo_head_hexsha": "0572cdae22b128e71c1c6c7ead2bf3b259875bc9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/code/11-04.py", "max_forks_repo_name": "dtrifuno/all-of-stats-solutions", "max_forks_repo_head_hexsha": "0572cdae22b128e71c1c6c7ead2bf3b259875bc9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2857142857, "max_line_length": 79, "alphanum_fraction": 0.6642276423, "include": true, "reason": "import numpy,import scipy", "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426428022032, "lm_q2_score": 0.8757869916479466, "lm_q1q2_score": 0.853053875876557}}
{"text": "import numpy as np\nimport scipy.linalg as la\n\ndef constructor_matrix(M):\n  \"\"\"\n  Building matrix\n  \"\"\"\n  return np.matrix(M).transpose()\n\ndef minimum_squares(X, Y):\n  \"\"\"\n  That function shows least squares of the values\n  \"\"\"\n  media_X = np.mean(X)\n  media_Y = np.mean(Y)\n  erro_x = X-media_X\n  erro_y = Y-media_Y\n  soma_erro_xy = np.sum(erro_x*erro_y)\n  erro_x_quadratico = (X-media_X)**2.0\n  soma_erro_x_quadratico = np.sum(erro_x_quadratico)\n  m = soma_erro_xy / soma_erro_x_quadratico\n  c = media_Y - m*media_X\n  reta = m*X+c\n\n  return {\n    'media_X': media_X,\n    'media_Y': media_Y,\n    'erro_x': erro_x,\n    'erro_y': erro_y,\n    'soma_erro_xy': soma_erro_xy,\n    'erro_x_quadratico': erro_x_quadratico,\n    'soma_erro_x_quadratico': soma_erro_x_quadratico,\n    'm': m,\n    'c': c,\n    'reta': reta\n  }\n\ndef plu(A):\n  \"\"\"\n  This function shows PLU \n  (permutation matrices, lower triangular and upper triangular)\n  \"\"\"\n  (P, L, U) = la.lu(A)\n  return {\n    'P': P,\n    'L': L,\n    'U': U\n  }\n\ndef autovalores_autovetores(A):\n  \"\"\"\n  That function uses eigenvalues and eigenvectors \n  to build the espectral decomposition\n  \"\"\"\n  autovalores, autovetores = np.linalg.eig(A)\n  return {\n    'autovalores': autovalores, \n    'autovetores': autovetores\n  }\n\ndef espectral(autovetores, matrizDiagonal):\n  \"\"\"\n  Espectral Decomposition\n  \"\"\"\n  return np.matmul(np.matmul(autovetores,matrizDiagonal),np.linalg.inv(autovetores))\n\ndef pvd(A):\n  \"\"\"\n  That function return the singular values decomposition\n  \"\"\"\n  (U,s,V) = np.linalg.svd(A)\n  return {\n    'U': U,\n    's': s,\n    'V': V\n  }\n\ndef back_substitution(A, x, n):\n  \"\"\"\n  That function shows back substitution values of a matrix\n  \"\"\"\n  b = np.dot(A, x)\n  xcomp = np.zeros(n)\n\n  for i in range(n-1, -1, -1):\n      tmp = b[i]\n      for j in range(n-1, i, -1):\n          tmp -= xcomp[j]*A[i,j]\n          \n      xcomp[i] = tmp/A[i,i]\n  \n  return xcomp", "meta": {"hexsha": "38282aa499cd2bdd0d79c59ae13f2ac1f656b285", "size": 1907, "ext": "py", "lang": "Python", "max_stars_repo_path": "app/utils/mathLib.py", "max_stars_repo_name": "thiagomurtinho/Iris_Classification", "max_stars_repo_head_hexsha": "8b04fed7f7162c3a6bd276c0dbfb2c291c02492c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/utils/mathLib.py", "max_issues_repo_name": "thiagomurtinho/Iris_Classification", "max_issues_repo_head_hexsha": "8b04fed7f7162c3a6bd276c0dbfb2c291c02492c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/utils/mathLib.py", "max_forks_repo_name": "thiagomurtinho/Iris_Classification", "max_forks_repo_head_hexsha": "8b04fed7f7162c3a6bd276c0dbfb2c291c02492c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7282608696, "max_line_length": 84, "alphanum_fraction": 0.6282118511, "include": true, "reason": "import numpy,import scipy", "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426450627306, "lm_q2_score": 0.8757869867849166, "lm_q1q2_score": 0.8530538731194989}}
{"text": "\"\"\"\r\n64-point Radix 2 DIF FFT implementation\r\nby zeeshan0309\r\n\r\ninput here is the sampled signal of the CT function \r\n{3.Sin(16pi.t)+24.Sin(2pi.t)+8.Sin(6pi.t)}\r\n\"\"\"\r\n\r\nfrom matplotlib import pyplot as plt \r\nimport math\r\nfrom math import sqrt\r\nimport numpy as np\r\n\r\npi = math.pi\r\ndef sine(num):\r\n    return math.sin(num)\r\n    \r\ndef cosine(num):\r\n    return math.cos(num)\r\n\r\n#twiddle factors W_64 from 0 to 31 (only 32 Twiddle factors required for 64-point DFT)\r\ntwiddle = []\r\nN = 64\r\nx = [i for i in range(0,64)]\r\n\r\nfor i in range(0, 32):\r\n    t_element = complex(cosine(2*pi*i/64), sine(2*pi*i/64))\r\n    twiddle.append(t_element)\r\n\r\n#generating random noise using numpy\r\nnoise = 3*np.random.randn(N)\r\n\r\n#sampling {3.Sin(16pi.t)+24.Sin(2pi.t)+8.Sin(6pi.t)} at fs = 64Hz\r\n# at t = {0, 1/64, 2/64, 3/64, ..., 63/64}\r\ninputSignal = []\r\n\r\nfor i in range(0, 64):\r\n    s_element = 3*sine(16*pi*i/64)+24*sine(2*pi*i/64)+8*sine(6*pi*i/64)\r\n    inputSignal.append(s_element)\r\n\r\n#adding Noise to sample\r\nfor i in range(0, N):\r\n    inputSignal[i] += noise[i]\r\n\r\n#function for evaluating Even indices term\r\n#def evenAddTerms()\r\ndef evenAddTerms(arr, N):\r\n    evenListOut = []\r\n    temp_e_arr = [0]*int(N/2)\r\n    temp_e_arr = arr\r\n    for i in range(0, int(N/2)):\r\n        even_element = temp_e_arr[i]+temp_e_arr[i+int(N/2)]\r\n        evenListOut.append(even_element)\r\n    return evenListOut\r\n    \r\n#function for evaluating Odd indices term\r\n#def oddSubTerms()\r\ndef oddSubTerms(arr, N, twiddle):\r\n    oddListOut = []\r\n    temp_o_arr = [0]*int(N/2)\r\n    temp_o_arr = arr\r\n    for i in range(0, int(N/2)):\r\n        odd_element = (temp_o_arr[i]-temp_o_arr[i+int(N/2)])*twiddle[int((64*i)/N)]\r\n        oddListOut.append(odd_element)\r\n    return oddListOut\r\n\r\n#lists for output of each stage (no of stages = log(64) = 6)\r\nstage1 = [0 for i in range(0, 64)]\r\nstage2 = [0+0j]*64\r\nstage3 = [0+0j]*64\r\nstage4 = [0+0j]*64\r\nstage5 = [0+0j]*64\r\nstage6 = [0+0j]*64\r\n\r\nstage_list = [inputSignal, stage1, stage2, stage3, stage4, stage5, stage6]\r\n\r\n#calculation of all stages done in this loop\r\nfor n in range(1, 7, 1):\r\n    step = int(N/(2**(n-1)))\r\n    int_step = int(N/(2**n))\r\n    index_list = [i for i in range(0, N+1, step)]\r\n    for i in range(0, 2**(n-1)):\r\n        stage_list[n][index_list[i]:index_list[i]+int_step] =  evenAddTerms(stage_list[n-1][index_list[i]:index_list[i+1]], int(N/(2**(n-1))))\r\n        stage_list[n][index_list[i]+int_step:index_list[i+1]] = oddSubTerms(stage_list[n-1][index_list[i]:index_list[i+1]], int(N/(2**(n-1))), twiddle)\r\n    \r\n    print(stage_list[n])\r\n    print(\"_________________________\")\r\n\r\n#converting the output to \"Magnitude Spectrum\"\r\noutputSignal = []\r\nfor i in range(len(stage6)):\r\n    temp = sqrt((stage6[i].real)**2+(stage6[i].imag)**2)\r\n    outputSignal.append(temp)\r\n\r\n#optional\r\nplt.plot(x, outputSignal)\r\nplt.show()", "meta": {"hexsha": "9576d1eeb8bc854162a2366d375b292419841d23", "size": 2843, "ext": "py", "lang": "Python", "max_stars_repo_path": "DIF_FFT_64_points.py", "max_stars_repo_name": "zeeshan0309/dvb", "max_stars_repo_head_hexsha": "2f392d0fef0e99470be8fd5f76ee2e02519bfb17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DIF_FFT_64_points.py", "max_issues_repo_name": "zeeshan0309/dvb", "max_issues_repo_head_hexsha": "2f392d0fef0e99470be8fd5f76ee2e02519bfb17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DIF_FFT_64_points.py", "max_forks_repo_name": "zeeshan0309/dvb", "max_forks_repo_head_hexsha": "2f392d0fef0e99470be8fd5f76ee2e02519bfb17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3092783505, "max_line_length": 152, "alphanum_fraction": 0.634892719, "include": true, "reason": "import numpy", "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97594644290792, "lm_q2_score": 0.8740772286044095, "lm_q1q2_score": 0.8530525620832863}}
{"text": "'''\r\nUsing the Shooting method to solve\r\ny\" = -3y\r\nwith the boundary conditions y(0) = 7 and y(2*pi) = 0\r\nand we know the exact solution\r\n''' \r\n\r\n\r\n# importing stuff\r\nimport numpy as np\r\nfrom scipy.integrate import solve_ivp\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nx = np.linspace(0,2*np.pi, 100)\r\ny_exact = 7 * np.cos(np.sqrt(3) * x) - 7 * np.cos(2 * np.pi * np.sqrt(3) ) / np.sin(2 * np.pi * np.sqrt(3) )* np.sin(np.sqrt(3)*x)\r\n\r\n\r\n# code our second order ODE to two first order ODE \r\n\r\ndef equations(x,y):\r\n    yprime = np.zeros(2)\r\n\r\n    yprime[0] = y[1]\r\n    yprime[1] = -3* y[0]\r\n\r\n    return yprime\r\n\r\n'''\r\nWe will use an iteration scheme to adjust the \r\nvalues of the initial conditions such that we\r\nmatch the boundary conditions. What type of \r\niteration scheme to use is up to you. I will \r\ndefine high and low bounds and set our natural \r\nguess As the meaning of those two points. I will\r\nthen adjust the bounds depending on whether we \r\novershoot or undershoot our boundary. The exact\r\nway to adjust the bounds is problem dependent.\r\n'''\r\n\r\ntol = 1e-6\r\nmax_iters = 100 \r\nlow = -10  \r\nhigh = 10\r\ncount = 0 \r\n\r\nwhile count <= max_iters:\r\n    count = count + 1\r\n    xspan = (x[0], x[-1])\r\n    \r\n    #  Use the midpoint between high and low as our guess\r\n    yprime0 = np.mean([low, high])\r\n    \r\n    #  Set the initial condition vector to be passed into the solver\r\n    y0 = [7, yprime0 ]\r\n\r\n    # Solve the system using our guess\r\n    sol = solve_ivp(equations, xspan, y0, t_eval = x)\r\n\r\n    #  For ease of use, extract the function values from the solution object.\r\n    y_num = sol.y[0, :]\r\n\r\n    #  Check to see if we within our desire tolerance\r\n    if np.abs(y_num[-1]) <= tol:\r\n        break\r\n    \r\n    #  Adjust our bounds if we are not within tolerance\r\n    if y_num[-1] < 0:\r\n        high = yprime0\r\n    else:\r\n        low = yprime0\r\n        \r\n    #print(count, y_num[-1])\r\n    \r\n#  Plot the solution and compare it to the analytical form defined above\r\nplt.plot(x, y_exact, 'b-', label='Exact')\r\nplt.plot(x, y_num, 'ro', label='Numeric')\r\nplt.plot([0, 2*np.pi], [7,0], 'ro')\r\nplt.grid(True)\r\nplt.xlabel('x')\r\nplt.ylabel('y')\r\nplt.legend()\r\n#plt.show()\r\nplt.savefig('shooting_1.png')", "meta": {"hexsha": "04425a0ba11dd03e6920ab4d26403026d44c21a8", "size": 2200, "ext": "py", "lang": "Python", "max_stars_repo_path": "PSET2/P3/shooting.py", "max_stars_repo_name": "MonitSharma/Computational-Methods-in-Physics", "max_stars_repo_head_hexsha": "e3b2db36c37dd5f64b9a37ba39e9bb267ba27d85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PSET2/P3/shooting.py", "max_issues_repo_name": "MonitSharma/Computational-Methods-in-Physics", "max_issues_repo_head_hexsha": "e3b2db36c37dd5f64b9a37ba39e9bb267ba27d85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PSET2/P3/shooting.py", "max_forks_repo_name": "MonitSharma/Computational-Methods-in-Physics", "max_forks_repo_head_hexsha": "e3b2db36c37dd5f64b9a37ba39e9bb267ba27d85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1904761905, "max_line_length": 131, "alphanum_fraction": 0.6268181818, "include": true, "reason": "import numpy,from scipy", "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801274759925, "lm_q2_score": 0.9019206798249232, "lm_q1q2_score": 0.8530377287107506}}
{"text": "import random as rand\nimport math\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom time import sleep\nfrom sys import stdin\n\n##### generate data for a moving object\n### all the following equations are integrals/derivatives of each other\ndef eq_pos(x, a=-10, b=3, c=-0.2):\n    return a*x + b*x**2 + c*x**3\ndef eq_vel(x):\n    return -10 + 6*x - 0.6*x**2\ndef eq_acc(x):\n    return 6 - 1.2*x\n\n\ndef calculate_max_error(x, y, eq):\n    time_stamps = np.arange(x[0], x[-1], 0.001)\n    m = 0\n\n    xi = 1\n    for i in time_stamps:\n        while x[xi] < i and xi < len(x):\n            xi += 1\n        x0 = x[xi-1]\n        x1 = x[xi]\n        if x0 > i or x1 < i:# prevents comparing outside data set\n            continue \n        if x1 == 0 or i == 0: # prevents divide by 0\n            continue\n        slope = (y[xi] - y[xi-1])/(x1-x0)\n        p = y[xi-1] + slope*(i-x0)\n\n\n        m = max(m, abs(p-eq(i)))\n    return m\n\n\n# takes the derivative by calculating the slope between all adjacent points\n# by default, calculates the first derivative (deg). Higher degrees calculated recursively\n# note: |d_points_y| = |points_y| - 1\ndef points_derivative(points_x, points_y, deg=1):\n    if deg <= 0:\n        return (points_x, points_y)\n\n    d_points_y = [] # y of derivative\n    d_points_x = [] # ditto for x\n    for i in range(len(points_y)-1): # compares adjacent pairs so one fewer than # points\n        ## x and y values for adjacent pairs\n        ax = points_x[i]\n        bx = points_x[i+1]\n\n        ay = points_y[i]\n        by = points_y[i+1]\n\n        # the slope of the adjacent point is the y value of the derivative at the x point between the pair\n        slope = (by-ay)/(bx-ax)\n        d_points_y.append(slope)\n\n        d_points_x.append((ax+bx)/2)\n\n    return points_derivative(d_points_x, d_points_y, deg-1)\n\n\n# takes the integral by treating the y value between a pair of points as the slope of the integral between those two points\n# the point between the x values of the same points\n# note: |i_points_y| = |points_y|\ndef points_integral(points_x, points_y, c=0, deg=1):\n    if deg <= 0:\n        return (points_x, points_y)\n\n    i_points_y = [c]\n    for i in range(len(points_y)-1):\n        ax = points_x[i]\n        bx = points_x[i+1]\n        dx = bx-ax\n\n        slope = (points_y[i]+points_y[i+1])/2\n\n        dy = slope*dx\n\n        y = i_points_y[-1]+dy\n\n        i_points_y.append(y)\n\n    return points_integral(points_x, i_points_y, c, deg-1)\n        \n\n\n# simulates running a rangefinder by using eq_pos() to get the position values and derives the velocity and acceleration\ndef simulate_rangefinder(p, x):\n    print(\"simulating rangefinder\")\n    ## setup plot\n    p.grid(color=\"black\", linestyle=\"-\", linewidth=1)\n    p.set_title(\"rangefinder simulation\")\n\n    y = eq_pos(x) # measurements taken\n    add_line(p, x, y, \"r\", \"position\")\n    \n    vel_x, vel_y = points_derivative(x, y)\n    add_line(p, vel_x, vel_y, \"g\", \"velocity\")\n    print(\"velocity \" + u\"\\u00B1\" + str(calculate_max_error(vel_x, vel_y, eq_vel)))\n    \n    acc_x, acc_y = points_derivative(vel_x, vel_y)\n    add_line(p, acc_x, acc_y, \"b\", \"acceleration\")\n    print(\"acceleration \" + u\"\\u00B1\" + str(calculate_max_error(acc_x, acc_y, eq_acc)), \"\\n\")\n\n# simulates an accelometer using eq_acc to get the acceleration values that would be recorded and integrating to get the\n#    velocity and position values\n# uses known values of c from eq_vel\ndef simulate_accelometer(p, x):\n    print(\"simulating accelometer\")\n    \n    p.grid(color=\"black\", linestyle=\"-\", linewidth=1)\n    p.set_title(\"accelometer simulation\")\n    \n    acc_y = eq_acc(x) # measurements taken\n    add_line(p, x, acc_y, \"b\", \"acceleration\")\n\n    vel_x, vel_y = points_integral(x, acc_y, c=-10)\n    add_line(p, vel_x, vel_y, \"g\", \"velocity\")\n    print(\"velocity \" + u\"\\u00B1\" + str(calculate_max_error(vel_x, vel_y, eq_vel)))\n    \n\n    pos_x, pos_y = points_integral(x, vel_y)\n    add_line(p, pos_x, pos_y, \"r\", \"position\")\n    print(\"position \" + u\"\\u00B1\" + str(calculate_max_error(pos_x, pos_y, eq_pos)),\"\\n\")\n\n\n# draws a line from the list of floats x and y onto the plot p\ndef add_line(p, x, y, color, name):\n    p.plot(x, y, color+\".-\", label=name) #################\n    p.legend() \n\n\n# this uses the equations for pos, vel, and acc rather than deriving/integrating one to get the other values\ndef calc_plot(p, x):\n    p.grid(color=\"black\", linestyle=\"-\", linewidth=1)\n    p.set_title(\"calculated plot\")\n\n    acc_y = eq_acc(x) # measurements taken\n    add_line(p, x, acc_y, \"b\", \"acceleration\")\n\n    vel_y = eq_vel(x)\n    add_line(p, x, vel_y, \"g\", \"velocity\")\n\n    pos_y = eq_pos(x)\n    add_line(p, x, pos_y, \"r\", \"position\")\n    \n\nif __name__ == \"__main__\":\n    # start, end, increment\n    x = np.arange(0, 12, 0.01)\n    print(\"number of points generated:\", len(x))\n\n    plt.figure(figsize=(9,7))\n    rangefinder_plot = plt.subplot2grid((2,2),(0,0))\n    accelometer_plot = plt.subplot2grid((2,2), (1,0))\n    calculated_plot = plt.subplot2grid((2,2), (0,1))\n                  \n    simulate_rangefinder(rangefinder_plot, x)\n    simulate_accelometer(accelometer_plot, x)\n    calc_plot(calculated_plot, np.arange(0, 12, 0.01))\n\n    plt.show()\n", "meta": {"hexsha": "d278435b1bfc04d15e417fdc1e0b4b5ccceac349", "size": 5189, "ext": "py", "lang": "Python", "max_stars_repo_path": "physics_project.py", "max_stars_repo_name": "Nanthno/PhysicsSensorSimulation", "max_stars_repo_head_hexsha": "b4d12368d274b8e4f39c8c2ae59fd53a44f3ce1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "physics_project.py", "max_issues_repo_name": "Nanthno/PhysicsSensorSimulation", "max_issues_repo_head_hexsha": "b4d12368d274b8e4f39c8c2ae59fd53a44f3ce1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "physics_project.py", "max_forks_repo_name": "Nanthno/PhysicsSensorSimulation", "max_forks_repo_head_hexsha": "b4d12368d274b8e4f39c8c2ae59fd53a44f3ce1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0718562874, "max_line_length": 123, "alphanum_fraction": 0.6322990942, "include": true, "reason": "import numpy", "num_tokens": 1532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801267121407, "lm_q2_score": 0.9019206712569267, "lm_q1q2_score": 0.8530377137177912}}
{"text": "from statistics import mean\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\n\ndef create_dataset(n,variance,step=2,correlation=False):\n    val = 1\n    ys = []\n    for i in range(n):\n        y = val + random.randrange(-variance,variance)\n        ys.append(y)\n        if correlation and correlation== \"pos\":\n            val += step\n        elif correlation and correlation==\"neg\":\n            val -= step\n    xs = [i for i in range(len(ys))]\n    return np.array(xs,dtype=np.float64) , np.array(ys , dtype=np.float64)\n\ndef best_fit_slope(xs,ys):\n    m = ( ((mean(xs)*mean(ys)) - mean(xs*ys)) /\n        (mean(xs)*mean(xs) - mean(xs*xs) )  )\n    return m\n\ndef best_intercept(slope,xs,ys):\n    b = mean(ys) - m*mean(xs)\n    return b\n\ndef squared_error(ys_orig,ys_line):\n    return sum((ys_line-ys_orig)**2)\n\ndef coefficient_of_determination(ys_orig,ys_line):\n    y_mean_line = [mean(ys_orig) for y in ys_orig]\n    squared_error_regr = squared_error(ys_orig,ys_line)\n    squared_error_mean = squared_error(ys_orig,y_mean_line)\n    return 1 - (squared_error_regr/squared_error_mean)\n\n\nxs , ys = create_dataset(40 , 20 , 2 , correlation=\"neg\")\n\nm = best_fit_slope(xs,ys)\nb = best_intercept(m , xs, ys)\n\nregression_line = [(m*x)+b for x in xs]\n\npredic_x = 8\npredic_y = m*predic_x + b\n\nr_squared = coefficient_of_determination(ys , regression_line)\nprint(r_squared)\n\n\nplt.scatter(xs , ys)\nplt.scatter(predic_x,predic_y , s = 100)\nplt.plot(xs,regression_line)\nplt.show()", "meta": {"hexsha": "ed972a2a4aad7b6f01b73900582a0fb371a6bd5b", "size": 1474, "ext": "py", "lang": "Python", "max_stars_repo_path": "regression/regression_scratch.py", "max_stars_repo_name": "sinabr/Machine-Learning-Basic-Examples", "max_stars_repo_head_hexsha": "9321e8e4652a6b985a93ceb797fc86c42bcaaf92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "regression/regression_scratch.py", "max_issues_repo_name": "sinabr/Machine-Learning-Basic-Examples", "max_issues_repo_head_hexsha": "9321e8e4652a6b985a93ceb797fc86c42bcaaf92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "regression/regression_scratch.py", "max_forks_repo_name": "sinabr/Machine-Learning-Basic-Examples", "max_forks_repo_head_hexsha": "9321e8e4652a6b985a93ceb797fc86c42bcaaf92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8, "max_line_length": 74, "alphanum_fraction": 0.6736770692, "include": true, "reason": "import numpy", "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620619801095, "lm_q2_score": 0.8887588008585925, "lm_q1q2_score": 0.8529969793150123}}
{"text": "import numpy as np\ntry:\n    import matplotlib.pyplot as plt\nexcept:\n    import matplotlib\n    matplotlib.use('Agg')\n    import matplotlib.pyplot as plt\n\nclass PolynomialRegression():\n    def __init__(self, degree):\n        \"\"\"\n        Implement polynomial regression from scratch.\n        \n        This class takes as input \"degree\", which is the degree of the polynomial \n        used to fit the data. For example, degree = 2 would fit a polynomial of the \n        form:\n\n            ax^2 + bx + c\n        \n        Your code will be tested by comparing it with implementations inside sklearn.\n        DO NOT USE THESE IMPLEMENTATIONS DIRECTLY IN YOUR CODE. You may find the \n        following documentation useful:\n\n        https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html\n        https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html\n\n        Here are helpful slides:\n\n        http://interactiveaudiolab.github.io/teaching/eecs349stuff/eecs349_linear_regression.pdf\n    \n        The internal representation of this class is up to you. Read each function\n        documentation carefully to make sure the input and output matches so you can\n        pass the test cases. However, do not use the functions numpy.polyfit or numpy.polval. \n        You should implement the closed form solution of least squares as detailed in slide 10\n        of the lecture slides linked above.\n\n        Usage:\n            import numpy as np\n            \n            x = np.random.random(100)\n            y = np.random.random(100)\n            learner = PolynomialRegression(degree = 1)\n            learner.fit(x, y) # this should be pretty much a flat line\n            predicted = learner.predict(x)\n\n            new_data = np.random.random(100) + 10\n            predicted = learner.predict(new_data)\n\n            # confidence compares the given data with the training data\n            confidence = learner.confidence(new_data)\n\n\n        Args:\n            degree (int): Degree of polynomial used to fit the data.\n        \"\"\"\n        self.degree = degree\n        self.confidence = None\n        self.w = None  # define the weights\n        self.f = None  # function\n        self.X_training = None\n\n\n    def fit(self, features, targets):\n        \"\"\"\n        Fit the given data using a polynomial. The degree is given by self.degree,\n        which is set in the __init__ function of this class. The goal of this\n        function is fit features, a 1D numpy array, to targets, another 1D\n        numpy array.\n        \n\n        Args:\n            features (np.ndarray): 1D array containing real-valued inputs.\n            targets (np.ndarray): 1D array containing real-valued targets.\n        Returns:\n            None (saves model and training data internally)\n        \"\"\"\n        X = np.ones((features.size, self.degree + 1))\n        X_row = X.shape[0]\n        X_column = X.shape[1]\n\n        for i in range(X_row):\n            for j in range (1, X_column):\n                X[i,j] = features[i]**j\n\n        # formula for weights: (X^TX)X^ty\n        X_inv = X.T\n        #self.w = np.matmul(np.matmul((np.linalg.inv(np.matmul(X_inv, X))), X_inv), targets)\n        self.w = np.linalg.inv(X.T @ X) @ X.T @ targets\n        #self.w = ((np.linalg.inv((X.T).dot(X))).dot(X.T)).dot(targets)\n\n\n        self.features_row = features.shape[0]\n        self.f = np.zeros((self.features_row))\n        for i in range(self.w.size):\n            self.f += self.w[i] * np.sort(features)**i\n    \n        self.X_training = features  # save training data internally\n        \n    def predict(self, features):\n        \"\"\"\n        Given features, a 1D numpy array, use the trained model to predict target \n        estimates. Call this after calling fit.\n\n        Args:\n            features (np.ndarray): 1D array containing real-valued inputs.\n        Returns:\n            predictions (np.ndarray): Output of saved model on features.\n        \"\"\"\n        predictions = np.zeros((features.shape[0]))\n        \n        for i in range(self.w.size):\n            predictions += self.w[i] * features**i\n\n        return predictions\n\n\n    def visualize(self, features, targets, path, title, color='g'):\n        \"\"\"\n        This function should produce a single plot containing a scatter plot of the\n        features and the targets, and the polynomial fit by the model should be\n        graphed on top of the points.\n\n        DO NOT USE plt.show() IN THIS FUNCTION. Instead, use plt.savefig().\n\n        Args:\n            features (np.ndarray): 1D array containing real-valued inputs.\n            targets (np.ndarray): 1D array containing real-valued targets.\n        Returns:\n            None (plots to the active figure)\n        \"\"\"\n\n        plt.figure()\n        plt.scatter(features, targets)\n        plt.plot(np.sort(self.X_training), self.f)\n        plt.title(title)\n        plt.xlabel('x')\n        plt.ylabel('y')\n        plt.legend()\n        plt.grid(True)\n        plt.savefig(path)\n", "meta": {"hexsha": "14d31d588352e1fb6f1d41f625fe8b3af554de9c", "size": 5011, "ext": "py", "lang": "Python", "max_stars_repo_path": "knn_and_regression/src/polynomial_regression.py", "max_stars_repo_name": "WallabyLester/Machine_Learning_From_Scratch", "max_stars_repo_head_hexsha": "6042cf421f5de2db61fb570b7c4de64dc03453f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "knn_and_regression/src/polynomial_regression.py", "max_issues_repo_name": "WallabyLester/Machine_Learning_From_Scratch", "max_issues_repo_head_hexsha": "6042cf421f5de2db61fb570b7c4de64dc03453f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "knn_and_regression/src/polynomial_regression.py", "max_forks_repo_name": "WallabyLester/Machine_Learning_From_Scratch", "max_forks_repo_head_hexsha": "6042cf421f5de2db61fb570b7c4de64dc03453f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5390070922, "max_line_length": 103, "alphanum_fraction": 0.6100578727, "include": true, "reason": "import numpy", "num_tokens": 1082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745211, "lm_q2_score": 0.888758803068433, "lm_q1q2_score": 0.8529969752985308}}
{"text": "'''\nCreated on 2013/12/29\n@author: Duong Nguyen\n@note: Nonnegative Matrix Factorization (NMF) with multiplicative update rules.\n@version: Kullback-Leibler\n\nV = W*H, where V, W, H >= 0. Here, \">=\" means element-wise relation\nV: n x m matrix\nW: n x b matrix\nH: b x m matrix \nMinimize_over_{W,H} KL-divergence(V, W*H)\n\nSee also, http://hebb.mit.edu/people/seung/papers/nmfconverge.pdf for more details.\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef kl_distance(A, B):\n    \"\"\" Compute the KL divergence between two matrices A, B.\n        KL(A, B) = \\sum_{i,j} (A_ij * log(A_ij / B_ij) - A_ij + B_ij)\n    \"\"\"\n    return np.sum(A * np.log(A/B) - A + B)\n    \ndef factorize(V, b, init=\"uniform\", max_iter=100, tol=1e-8, verbose=False):\n    \"\"\" Factorization with multiplicative update rules.\n        @param init: specify how to initialize W, H. Default: uniformly random in [0,1)\n        @param max_iter: Maximum number of iterations of updating\n        @param tol: Tolerance value to check if converge   \n        \n        @return: n x b matrix W, and b x m matrix H such that KL(V, W*H) is minimized.\n                The values of KL-divergence at each iteration step are also returned as dists.\n    \"\"\"\n    \n    assert init in (\"uniform\", \"normal\"), \"Unsupported initialization!\"\n    n, m = V.shape\n    \n    if init == \"uniform\":\n        W, H = np.random.random((n,b)), np.random.random((b,m))\n    else:\n        W, H = np.random.randn(n,b), np.random.randn(b,m)\n    \n    dists = []\n    for i in xrange(max_iter):\n        WH = W.dot(H)\n        \n        cur_dist = kl_distance(V, WH)\n        dists.append(cur_dist)\n        \n        if verbose and i % 10 == 0:\n            print \"%d iteration: %f\" %(i, cur_dist)\n            \n        if cur_dist <= tol:\n            break\n        \n        # Update H\n        nu = (W.T).dot(V/(WH))\n        de = np.tile(np.sum(W,0), (m,1)).T\n        H = H*nu/de # element-wise update\n        \n        # Update W\n        nu = (V/(W.dot(H))).dot(H.T)\n        de = np.tile(np.sum(H,1), (n,1))\n        W = W*nu/de # element-wise update\n        \n    return W, H, dists\n    \ndef test(plot=False):\n    \"\"\" Test KL-based NMF.\"\"\"\n    \n    V = np.random.random((10, 9))\n    W, H, dists = factorize(V, 3, init=\"uniform\", max_iter=300, tol=1e-8, verbose=True)\n    \n    if plot:\n        plt.figure()\n        plt.clf()\n        plt.plot(dists, \"b-\", lw=2)\n        plt.xlabel(\"Iteration\")\n        plt.ylabel(\"KL divergence as cost function\")\n        plt.title(\"KL-based NMF Demo\")\n        plt.show()\n        plt.savefig(\"kl_nmf_demo.png\") # save figure at current working directory\n        \n    print \"V =\", V\n    print \"W * H =\", W.dot(H)\n    print \"KL divergence =\", dists[-1] \n    \nif __name__ == \"__main__\":\n    test(plot=True)", "meta": {"hexsha": "768b50a0820348d08c050675df1aee9047af78a4", "size": 2754, "ext": "py", "lang": "Python", "max_stars_repo_path": "Matrix-Factorization/kl_nmf.py", "max_stars_repo_name": "ntduong/ML", "max_stars_repo_head_hexsha": "ef69b0ad6205e4a5a3067470d1d2a60009479de6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-10-12T23:24:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-19T13:09:30.000Z", "max_issues_repo_path": "Matrix-Factorization/kl_nmf.py", "max_issues_repo_name": "ntduong/ML", "max_issues_repo_head_hexsha": "ef69b0ad6205e4a5a3067470d1d2a60009479de6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Matrix-Factorization/kl_nmf.py", "max_forks_repo_name": "ntduong/ML", "max_forks_repo_head_hexsha": "ef69b0ad6205e4a5a3067470d1d2a60009479de6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6, "max_line_length": 94, "alphanum_fraction": 0.5668119099, "include": true, "reason": "import numpy", "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953275046683696, "lm_q2_score": 0.8947894527758052, "lm_q1q2_score": 0.8529804573669345}}
{"text": "# integrantes: GABRIEL GOMEZ, EDUARDO DE LA HOZ, STEPHANIA DE LA HOZ\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport scipy.linalg as la\nimport sys\nimport mpl_toolkits.mplot3d as mpl\nfrom numpy import genfromtxt\nfrom collections import Counter\nfrom sklearn.preprocessing import StandardScaler\n\n\ndef cleaner(df, k):\n    return df[(abs(df[0]-np.mean(df[0])) <= k*np.std(df[0])) & (abs(df[1]-np.mean(df[1])) <= k*np.std(df[1])) & (abs(df[2]-np.mean(df[2])) <= k*np.std(df[2])) & (abs(df[3]-np.mean(df[3])) <= k*np.std(df[3]))]\n\n\ndf = pd.read_table('irisdata.txt', skiprows=9, header=None)\ndfClean = df\ncat = df.iloc[:, 4].values\ndf = df.drop(columns=4)\nrawdata = np.array(df)\ncovRawData = np.cov(rawdata.T)\nresultRaw = la.eig(covRawData)\neugenVector = resultRaw[1]\neugenValors = resultRaw[0].real\n\nprint('matriz de covarianza: ')\nprint(covRawData)\nprint('\\n')\nprint('eugenvalores: ')\nprint(eugenValors)\nprint('\\n')\nprint('eugenvectores: ')\nprint(eugenVector)\n\nsumEugen = np.sum(eugenValors)\nporEugen = eugenValors/sumEugen\nporEugen = porEugen*100\n\nx = np.arange(4)\n\nfig, ax = plt.subplots()\nlang = ['PC1', 'PC2', 'PC3', 'PC4']\nax.set_ylabel('n')\nax.set_title('nices')\nax.bar(lang, porEugen, edgecolor='black')\nplt.show()\n\neugenPares = [(np.abs(eugenValors[i]), eugenVector[:, i])\n              for i in range(len(eugenValors))]\n\nzerros = np.zeros((4, 1))\nmatrix1D = np.hstack((eugenPares[0][1].reshape(4, 1), zerros.reshape(4, 1)))\nmatrix2D = np.hstack((eugenPares[0][1].reshape(\n    4, 1), eugenPares[1][1].reshape(4, 1)))\nmatrix3D = np.hstack((eugenPares[0][1].reshape(\n    4, 1), eugenPares[1][1].reshape(4, 1), eugenPares[2][1].reshape(4, 1)))\n\nz = rawdata.dot(matrix3D)\nlab = (0, 1, 2)\ncolor = ('green', 'red', 'brown')\nwith plt.style.context('seaborn-whitegrid'):\n    fig = plt.figure()\n    ax = fig.add_subplot(111, projection='3d')\n    for lab, color in zip(lab, color):\n        ax.scatter(z[cat == lab, 0], z[cat == lab, 1],\n                   z[cat == lab, 2], c=color, s=10, label=lab)\n    plt.legend(loc=2)\n    plt.show()\n\ny = rawdata.dot(matrix2D)\nlab2 = (0, 1, 2)\ncolor2 = ('green', 'red', 'brown')\nwith plt.style.context('seaborn-whitegrid'):\n    plt.figure(figsize=(6, 4))\n    for lab2, color2, in zip(lab2, color2):\n        plt.scatter(y[cat == lab2, 0], y[cat == lab2, 1], label=lab2, c=color2)\n    plt.xlabel('componente 1')\n    plt.ylabel('componente 2')\n    plt.legend(loc='lower center')\n    plt.tight_layout()\n    plt.show()\n\nv = rawdata.dot(matrix1D)\nlab3 = (0, 1, 2)\ncolor3 = ('green', 'red', 'brown')\nwith plt.style.context('seaborn-whitegrid'):\n    plt.figure()\n    for lab3, color3, in zip(lab3, color3):\n        plt.scatter(v[cat == lab3, 0], v[cat == lab3, 1],\n                    label=lab3, c=color3, s=10)\n    plt.xlabel('componente 1')\n    plt.ylabel('componente 2')\n    plt.legend(loc='lower center')\n    plt.tight_layout()\n    plt.show()\n\nk = 2\ncleanDf = cleaner(dfClean, k)\ncatClean = cleanDf.iloc[:, 4].values\ncleanDf = cleanDf.drop(columns=4)\ncleanData = np.array(cleanDf)\ncovCleanData = np.cov(cleanData.T)\nresultClean = la.eig(covCleanData)\neugenVectorClean = resultClean[1]\neugenValorsClean = resultClean[0].real\neugenParesClean = [(np.abs(eugenValorsClean[i]), eugenVectorClean[:, i])\n                   for i in range(len(eugenValorsClean))]\n\nzerros = np.zeros((4, 1))\nmatrix1DClean = np.hstack(\n    (eugenParesClean[0][1].reshape(4, 1), zerros.reshape(4, 1)))\n\nvClean = cleanData.dot(matrix1DClean)\nlab4 = (0, 1, 2)\ncolor4 = ('green', 'red', 'brown')\nwith plt.style.context('seaborn-whitegrid'):\n    plt.figure(figsize=(6, 4))\n    for lab4, color4, in zip(lab4, color4):\n        plt.scatter(vClean[catClean == lab4, 0],\n                    vClean[catClean == lab4, 1], label=lab4, c=color4, s=10)\n    plt.xlabel('componente 1')\n    plt.ylabel('componente 2')\n    plt.legend(loc='lower center')\n    plt.tight_layout()\n    plt.show()\n\"\"\"\nrespuesta de la pregunta n7.\n7. What do you observe at the three plots? How many components are actually necessary?\n\nEn la grafica de 3d obsebamos que los datos se encuentran bastantes dispersos entre si, \nobservaamos que un grupo de datos  esta mas apartado de otros\nen la grafica dos 2 esa separacion desaparece, al solo tener 2 ejes, se pierde esa separacion que se observamos en\nla grafica en 3D, En el la grafica 1D Solo observamos una linea representando todos los conjuntos de datos, perdiendo\ndemasiada informacion util para poder diferenciar los datos.\nconsideramos que los componentes mas necesarios serian el pc1 y e pc2.\n\n\"\"\"\n", "meta": {"hexsha": "9b4eb0394c9f7bbad45ef8238711a4169508d115", "size": 4546, "ext": "py", "lang": "Python", "max_stars_repo_path": "parcialMineria.py", "max_stars_repo_name": "gago852/KDDLimpiezaTransformacion", "max_stars_repo_head_hexsha": "2f730c398b4e45f841d7ac0ad5de1b16a07c485c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "parcialMineria.py", "max_issues_repo_name": "gago852/KDDLimpiezaTransformacion", "max_issues_repo_head_hexsha": "2f730c398b4e45f841d7ac0ad5de1b16a07c485c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parcialMineria.py", "max_forks_repo_name": "gago852/KDDLimpiezaTransformacion", "max_forks_repo_head_hexsha": "2f730c398b4e45f841d7ac0ad5de1b16a07c485c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4714285714, "max_line_length": 208, "alphanum_fraction": 0.66849978, "include": true, "reason": "import numpy,from numpy,import scipy", "num_tokens": 1488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.8947894527758052, "lm_q1q2_score": 0.8529804549913633}}
{"text": "# -*- coding: utf-8 -*-\n# --------------------------------------------------------------------------------- #\n# Software de Observaciones Sintéticas S.O.S.\n# Line functions\n#\n# Marcial Becerril, @ 25 August 2020\n# Latest Revision: 25 Aug 2020, 21.33 GMT\n#\n# For all kind of problems, requests of enhancements and bug reports, please\n# write to me at:\n#\n# mbecerrilt92@gmail.com\n# mbecerrilt@inaoep.mx\n#\n# --------------------------------------------------------------------------------- #\n\nimport numpy as np\n\ndef gaussian(x, A, mu, sigma):\n    \"\"\"\n        Gaussian function\n        Parameters\n        ----------\n        x : int/float/array\n        A : float\n            Amplitude\n        mu : float\n            Mean\n        sigma : float\n            Dispersion\n        y0 : float\n            Offset\n        ----------\n    \"\"\"\n    return A*np.exp(-((x-mu)**2)/(2*sigma**2))\n\ndef lorentzian(x, A, mu, w):\n    \"\"\"\n        Gaussian function\n        Parameters\n        ----------\n        x : int/float/array\n        A : float\n            Amplitude\n        mu : float\n            Mean\n        w : float\n            Width\n        y0 : float\n            Offset\n        ----------\n    \"\"\"\n    w = np.abs(w)\n    return A*(w/(4*(x-mu)**2 + w**2))\n", "meta": {"hexsha": "0fdce5beac3122add7c981435846a1fd1a97fade", "size": 1237, "ext": "py", "lang": "Python", "max_stars_repo_path": "sos/misc/line_functions.py", "max_stars_repo_name": "MarcialX/sos", "max_stars_repo_head_hexsha": "0019a7453deb351f01b38a116461a13a446453c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sos/misc/line_functions.py", "max_issues_repo_name": "MarcialX/sos", "max_issues_repo_head_hexsha": "0019a7453deb351f01b38a116461a13a446453c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sos/misc/line_functions.py", "max_forks_repo_name": "MarcialX/sos", "max_forks_repo_head_hexsha": "0019a7453deb351f01b38a116461a13a446453c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4909090909, "max_line_length": 85, "alphanum_fraction": 0.4147130154, "include": true, "reason": "import numpy", "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203814, "lm_q2_score": 0.8840392725805822, "lm_q1q2_score": 0.8529698499202665}}
{"text": "'''\nA robot is located at the top-left corner of a m x n grid \n(marked 'Start' in the diagram below).\n\nThe robot can only move either down or right at any point \nin time. The robot is trying to reach the bottom-right \ncorner of the grid (marked 'Finish' in the diagram below).\n\nNow consider if some obstacles are added to the grids. \nHow many unique paths would there be?\n\nAn obstacle and empty space is marked as 1 and 0 respectively in the grid.\n\nNote: m and n will be at most 100.\n\nExample 1:\n\nInput:\n[\n  [0,0,0],\n  [0,1,0],\n  [0,0,0]\n]\nOutput: 2\nExplanation:\nThere is one obstacle in the middle of the 3x3 grid above.\nThere are two ways to reach the bottom-right corner:\n1. Right -> Right -> Down -> Down\n2. Down -> Down -> Right -> Right\n'''\nimport numpy as np\n\nclass Solution(object):\n    def uniquePathsWithObstacles(self, obstacleGrid):\n        \"\"\"\n        :type obstacleGrid: List[List[int]]\n        :rtype: int\n        \"\"\"\n        n = len(obstacleGrid)\n        if n == 0:\n            return 0\n        m = len(obstacleGrid[0])\n        grid = np.array([[0 for i in range(m)] for j in range(n)])\n        for i in range(m):\n            if obstacleGrid[0][i] == 1:\n                break\n            grid[0, i] = 1\n        for j in range(n):\n            if obstacleGrid[j][0] == 1:\n                break\n            grid[j, 0] = 1\n        for i in range(1, m):\n            for j in range(1, n):\n                if obstacleGrid[j][i] == 1:\n                    grid[j, i] = 0\n                else:\n                    grid[j, i] = grid[j-1, i] + grid[j, i-1]\n        print(grid)\n        return grid[n-1, m-1]\n\nsol = Solution()\nobstacleGrid = [[0,0,0],\n                [0,1,0],\n                [0,0,0]\n                        ]\nprint(sol.uniquePathsWithObstacles(obstacleGrid))\n", "meta": {"hexsha": "5fc938f2497e7f12fe39494e98c04af1ec42c8ff", "size": 1779, "ext": "py", "lang": "Python", "max_stars_repo_path": "top_400/dp/63_unique_paths_II.py", "max_stars_repo_name": "Fernadoo/LeetCode", "max_stars_repo_head_hexsha": "05d703672d55f46c3b2603429b8ae83502ec62c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "top_400/dp/63_unique_paths_II.py", "max_issues_repo_name": "Fernadoo/LeetCode", "max_issues_repo_head_hexsha": "05d703672d55f46c3b2603429b8ae83502ec62c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "top_400/dp/63_unique_paths_II.py", "max_forks_repo_name": "Fernadoo/LeetCode", "max_forks_repo_head_hexsha": "05d703672d55f46c3b2603429b8ae83502ec62c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.552238806, "max_line_length": 74, "alphanum_fraction": 0.5474985947, "include": true, "reason": "import numpy", "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203815, "lm_q2_score": 0.8840392695254319, "lm_q1q2_score": 0.8529698469724889}}
{"text": "import numpy as np \r\nimport math \r\na = [0,1,2,3,4,5,6,7,8,9]\r\nb = [1,3,2,5,7,8,8,9,10,12]\r\n\r\n#Changing lists to numpy arrays\r\nx = np.array(a)\r\ny = np.array(b)\r\n\r\n#Finding b0 and b1\r\nmean_x = np.mean(x)\r\nmean_y = np.mean(y)\r\nSS_xy = np.sum(y*x) - 10*mean_y*mean_x \r\nSS_xx = np.sum(x*x) - 10*mean_x*mean_x \r\n\r\nb_1 = SS_xy / SS_xx \r\nb_0 = mean_y - b_1*mean_x \r\nprint(\"\\nRegression Coefficients: b0 = \",b_0,\" b1 = \",b_1)\r\n\r\n#Finding SSR,SST,SSE and R squared\r\nfor i in range(10):\r\n    y_pred = b_0 + b_1*x\r\nSSR = 0\r\nSSE = 0\r\nfor i in range(10):\r\n    SSR = SSR + math.pow((y_pred[i]-mean_y),2)\r\n    SSE = SSE + math.pow((y[i]-y_pred[i]),2)\r\nprint(\"\\nSSR = \",SSR)    \r\nprint(\"\\nSSE = \",SSE)\r\nSST = SSR +SSE\r\nR_squared = SSR/SST\r\nprint(\"\\nR squared = \",R_squared)\r\n\r\n\r\n#Gradient decent full batch\r\n\r\nprint(\"\\nGRADEIENT DECENT\")\r\nbb0=0\r\nbb1=0\r\na=0.001\r\nn=10\r\ny_exp=np.zeros(n)\r\nfor j in range(10000):\r\n    for i in range(n):\r\n        y_exp[i]=b_0+b_1*x[i]\r\n        bb0=bb0+a*(y[i]-y_exp[i])\r\n        bb1=bb1+a*(y[i]-y_exp[i])*x[i]\r\nprint(\"\\nB0=\",bb0)\r\nprint(\"B1=\",bb1)\r\n \r\n\r\n#Gradient decent Stochastic\r\nprint(\"\\nGRADEIENT DECENT Stochastic\")\r\nbb0=0\r\nbb1=0\r\na=0.001\r\ny_exp=np.zeros(n)\r\nb=[0,0]\r\nse=10\r\nwhile(se>1):\r\n    for i in range(n):\r\n        y_exp[i]=b_0+b_1*x[i]\r\n        bb0=bb0+a*(y[i]-y_exp[i])\r\n        bb1=bb1+a*(y[i]-y_exp[i])*x[i]\r\n        b[0]=bb0\r\n        b[1]=bb1\r\n    e=y-y_exp\r\n    se=np.sum((e**2))*(1/n)\r\nprint(\"\\nSquared error=\",se)\r\nprint(\"B0=\",bb0)\r\nprint(\"B1=\",bb1)\r\n\r\n\r\n\r\n\r\n    \r\n\r\n", "meta": {"hexsha": "2eec7258866f9b8d42f7917a6ef94c1f495cbbce", "size": 1500, "ext": "py", "lang": "Python", "max_stars_repo_path": "LinearRegression.py", "max_stars_repo_name": "sumedha3111/Python-for-Beginners", "max_stars_repo_head_hexsha": "f07bab1df44cb0db19f884f05821777059bc194b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-10-02T13:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-07T20:42:39.000Z", "max_issues_repo_path": "LinearRegression.py", "max_issues_repo_name": "devnarayanp02/Python-for-Beginners", "max_issues_repo_head_hexsha": "f07bab1df44cb0db19f884f05821777059bc194b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-10-03T10:01:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-30T16:56:35.000Z", "max_forks_repo_path": "LinearRegression.py", "max_forks_repo_name": "devnarayanp02/Python-for-Beginners", "max_forks_repo_head_hexsha": "f07bab1df44cb0db19f884f05821777059bc194b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2020-09-30T18:47:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T04:10:31.000Z", "avg_line_length": 19.2307692308, "max_line_length": 59, "alphanum_fraction": 0.5593333333, "include": true, "reason": "import numpy", "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812345563904, "lm_q2_score": 0.8807970811069351, "lm_q1q2_score": 0.8529473647959989}}
{"text": "# Bai toan: Dua vao chieu cao de du doan can nang\n#   f(x) = w1.x1 + w2.x2 + w3.x3 + w0\n#       w1, w2, w3: const, w0: bias\n#       y ~ f(x): quan he tuyen tinh --> Linear Regression --> Toi uu: {w1, w2, w3, w0}\n#       y: Gia tri thuc te\n#       f(x): Gia tri du doan (predict)\n\n# CT:   w = inverse(A). b\n#   Voi:    A = Tranpose(X) . X\n#           b = Tranpose(X) . y\n#           w = A^-1 . b\n# Trong bai nay thi:    (weight) = w_1*(height) + w_0\n# Ta can tim` w_1 va w_0\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# height (cm)\nX = np.array([[147, 150, 153, 158, 163, 165, 168, 170, 173, 175, 178, 180, 183]]).T\n\n# weight (kg)\ny = np.array([[ 49, 50, 51,  54, 58, 59, 60, 62, 63, 64, 66, 67, 68]]).T\n\n# Building Xbar\none = np.ones((X.shape[0], 1))\nXbar = np.concatenate((one, X), axis = 1)\nprint Xbar\n\n# Calculating weights of the fitting line\nA = np.dot(Xbar.T, Xbar)\nprint A\nb = np.dot(Xbar.T, y)\nprint np.linalg.pinv(A)\nw = np.dot(np.linalg.pinv(A), b)\n\nprint('w = ', w)\n\n# Preparing the fitting line\nw_0 = w[0][0]\nw_1 = w[1][0]\nx0 = np.linspace(145, 185, 2)\ny0 = w_0 + w_1*x0\n\n# Du doan (2 du~ lieu 155, 160 ta chua dua vao mo hinh train)\ny1 = w_1*155 + w_0\ny2 = w_1*160 + w_0\n\nprint( u'Predict weight of person with height 155 cm: %.2f (kg), real number: 52 (kg)'  %(y1) )\nprint( u'Predict weight of person with height 160 cm: %.2f (kg), real number: 56 (kg)'  %(y2) )\n\n\n# Drawing the fitting line\nplt.plot(X.T, y.T, 'ro')     # data\nplt.plot(x0, y0)               # the fitting line\nplt.axis([140, 190, 45, 75])\nplt.xlabel('Height (cm)')\nplt.ylabel('Weight (kg)')\nplt.show()\n\n\n\n\n\n\n", "meta": {"hexsha": "459c1b3f741b4f4e68db272d541b500338bbbd85", "size": 1600, "ext": "py", "lang": "Python", "max_stars_repo_path": "1_linear_regression/BaiToanChieuCaoCanNang.py", "max_stars_repo_name": "nguyenthieu95/machine_learning", "max_stars_repo_head_hexsha": "40595a003815445a7a9fef7e8925f71d19f8fa30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-30T20:10:07.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-30T20:10:07.000Z", "max_issues_repo_path": "1_linear_regression/BaiToanChieuCaoCanNang.py", "max_issues_repo_name": "ThieuNv/machine_learning", "max_issues_repo_head_hexsha": "40595a003815445a7a9fef7e8925f71d19f8fa30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1_linear_regression/BaiToanChieuCaoCanNang.py", "max_forks_repo_name": "ThieuNv/machine_learning", "max_forks_repo_head_hexsha": "40595a003815445a7a9fef7e8925f71d19f8fa30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-23T15:30:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T15:30:16.000Z", "avg_line_length": 24.6153846154, "max_line_length": 95, "alphanum_fraction": 0.580625, "include": true, "reason": "import numpy", "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924802053235, "lm_q2_score": 0.8774767762675405, "lm_q1q2_score": 0.8529008280868584}}
{"text": "import numpy as np\nimport copy \nfrom tqdm import trange \ndef burgers_timestep(x:np.ndarray,y:np.ndarray,u:np.ndarray,v:np.ndarray,nt:int,dt:float=0.001,nu:float=0.1):\n    \"\"\"Solving burgers equation using finite difference with euler time step (1st order approximation) \n\n    Args:\n        x (np.ndarray): domain x direction\n        y (np.ndarray): domain y direction\n        u (np.ndarray): matrix describing x-velocity field in i,j space\n        v (np.ndarray): matrix describing y-velocity field in i,j space\n        nt (int): number of time advances\n        dt (float): time step to use for first order approximation\n        nu (float, Optional): Viscosity. Defaults to 0.1\n    \n    Returns:\n        (tuple): containing\n\n            **u_history** (np.ndarray): history for u velocity \n            **v_history** (np.ndarray): history for v velocity \n    \"\"\"\n\n\n    dx = x[0,2]-x[0,1] # We can do it this way because x and y are initialized using linspace which guarantees constant spacing \n    dy = y[1,0]-y[0,0]\n\n    u_history = list()\n    v_history = list() \n    u_history.append(copy.deepcopy(u)) # set equal to initial value\n    v_history.append(copy.deepcopy(v))\n    for n in trange(nt):\n        un = u.copy()   # previous value\n        vn = v.copy()\n        for i in range(1,x.shape[0]-1):\n            for j in range(1,y.shape[1]-1):\n                # Uses backward difference in space to solve first order derivative\n                # Central differencing for second order derivative \n                u[i,j] = (un[i, j] -(un[i, j] * dt / dx * (un[i, j] - un[i-1, j])) -vn[i, j] * dt / dy * (un[i, j] - un[i, j-1])) + (nu*dt/(dx**2))*(un[i+1,j]-2*un[i,j]+un[i-1,j])+(nu*dt/(dx**2))*(un[i,j-1]-2*un[i,j]+un[i,j+1])\n                v[i,j] = (vn[i, j] -(un[i, j] * dt / dx * (vn[i, j] - vn[i-1, j]))-vn[i, j] * dt / dy * (vn[i, j] - vn[i, j-1])) + (nu*dt/(dx**2))*(vn[i+1,j]-2*vn[i,j]+vn[i-1,j])+(nu*dt/(dx**2))*(vn[i,j-1]-2*vn[i,j]+vn[i,j+1])\n        \n        u[:,0] = 1       # At all i values when j = 0\n        u[:,-1] = 1      # At all i values when j = jmax\n        u[0,:] = 1       # At all j values and i = 0\n        u[-1,:] = 1     # At all j values and i = imax\n\n        v[:,0] = 1\n        v[:,-1] = 1\n        v[0,:] = 1\n        v[-1,:] = 1\n\n        u_history.append(copy.deepcopy(u))\n        v_history.append(copy.deepcopy(v))\n    return u_history, v_history\n    \n", "meta": {"hexsha": "75e94e451675375b9f42331dd6bb6662c102e3ab", "size": 2380, "ext": "py", "lang": "Python", "max_stars_repo_path": "burgers_2D/analytical/burgers_solver_2D.py", "max_stars_repo_name": "pjuangph/PINN-Torch", "max_stars_repo_head_hexsha": "ce105ad595f00574f6cdb849717b3295f97cb8f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "burgers_2D/analytical/burgers_solver_2D.py", "max_issues_repo_name": "pjuangph/PINN-Torch", "max_issues_repo_head_hexsha": "ce105ad595f00574f6cdb849717b3295f97cb8f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-19T15:27:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T15:27:09.000Z", "max_forks_repo_path": "burgers_2D/analytical/burgers_solver_2D.py", "max_forks_repo_name": "pjuangph/PINN-Torch", "max_forks_repo_head_hexsha": "ce105ad595f00574f6cdb849717b3295f97cb8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-07T16:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T16:27:46.000Z", "avg_line_length": 43.2727272727, "max_line_length": 227, "alphanum_fraction": 0.5470588235, "include": true, "reason": "import numpy", "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.9032942132122422, "lm_q1q2_score": 0.8528694928620147}}
{"text": "import numpy as np\nfrom layers.activation_layer import *\nfrom layers.gradient_check import *\n\n\ndef mean_square_error_loss(y_hat, y):\n    \"\"\"\n    MSE loss, loss=mean(y_hat-y)^2\n    :param y_hat: output of the network\n    :param y: input labels\n    :return: MSE loss\n    \"\"\"\n    loss = np.mean((y_hat - y) ** 2)\n    num_output = y.shape[1]\n    d_loss = 2 * (y_hat - y) / num_output\n    return loss, d_loss\n\n\ndef cross_entropy_loss(y_hat, y):\n    \"\"\"\n    Cross entropy loss, loss = -sum(yi * log(y_hat))\n    :param y_hat: output of the network\n    :param y: input labels (one_hot)\n    :return: cross entropy loss\n    \"\"\"\n    loss = -np.sum(y * np.log(y_hat), axis=1)\n    # loss = np.mean(loss, axis=0)\n    d_loss = -y / y_hat\n    return loss, d_loss\n\n\ndef softmax_loss(x, y):\n    shifted_logits = x - np.max(x, axis=1, keepdims=True)\n    Z = np.sum(np.exp(shifted_logits), axis=1, keepdims=True)\n    log_probs = shifted_logits - np.log(Z)\n    probs = np.exp(log_probs)\n    N = x.shape[0]\n    loss = -np.sum(log_probs[np.arange(N), y]) / N\n    dx = probs.copy()\n    dx[np.arange(N), y] -= 1\n    dx /= N\n    return loss, dx\n\n\nif __name__ == '__main__':\n    np.random.seed(231)\n    num_classes, num_inputs = 10, 50\n    x = 0.001 * np.random.randn(num_inputs, num_classes)\n    y = np.random.randint(num_classes, size=num_inputs)\n\n    dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False)\n    loss, dx = softmax_loss(x, y)\n\n    # Test softmax_loss function. Loss should be 2.3 and dx error should be 1e-8\n    print('\\nTesting softmax_loss:')\n    print('loss: ', loss)\n    print('dx error: ', rel_error(dx_num, dx))\n\n", "meta": {"hexsha": "e5f19e16e2b08093649aea79bf01a6ebe7b3786c", "size": 1638, "ext": "py", "lang": "Python", "max_stars_repo_path": "lhq_nn_lib/layers/loss.py", "max_stars_repo_name": "lhq1208/DL_lib", "max_stars_repo_head_hexsha": "53c99157efcc36f2288a82eedad09cdecda579e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lhq_nn_lib/layers/loss.py", "max_issues_repo_name": "lhq1208/DL_lib", "max_issues_repo_head_hexsha": "53c99157efcc36f2288a82eedad09cdecda579e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lhq_nn_lib/layers/loss.py", "max_forks_repo_name": "lhq1208/DL_lib", "max_forks_repo_head_hexsha": "53c99157efcc36f2288a82eedad09cdecda579e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7627118644, "max_line_length": 87, "alphanum_fraction": 0.6324786325, "include": true, "reason": "import numpy", "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.9136765281148512, "lm_q1q2_score": 0.8528538243488525}}
{"text": "\"\"\"\nThis is an example showing how to use the mgd2d solver. \nA 4th order accurate solution is obtained with the 5pt stencil,\nby using deferred correction.\n\n\"\"\"\nimport numpy as np\nimport time\nfrom mgd2d import FMG,V_cycle\n#analytical solution\ndef Uann(x,y,n):\n  return np.sin(2*n*np.pi*x)*np.sin(2*n*np.pi*y)\n\n#RHS corresponding to above\ndef source(x,y,n):\n  return -8 * (np.pi)**2 * n**2 * np.sin(2*n*np.pi*x) * np.sin(2*n*np.pi*y)\n\n#input\n\n#input\n#FMG is a direct solver. tolerance and iterations are not used \n\n#nv          = 1 # nv : Number of V-cycles within FMG. nv=1 will give solution a to within discretization error.\n                 # Increase this to get a higher accuracy solution (upto roundoff limit) \n                 # of the discrete problem.(residual on the fine grid =round off limit)\n                 # Here I am using nv=2 for the first solve and nv=6 for the second solve.\n\nnlevels    = 7    #total number of grid levels. 1 means no multigrid, 2 means one coarse grid. etc \n\n# Number of points is based on the number of multigrid levels as\n# N=A*2**(num_levels-1) where A is an integer >=4. Smaller A is better\n# This is a cell centered discretization\nNX         = 4*2**(nlevels-1) \nNY         = 4*2**(nlevels-1) \n\n#the grid has one layer of ghost cells to help apply the boundary conditions\nuann=np.zeros([NX+2,NY+2])#analytical solution\nu   =np.zeros([NX+2,NY+2])#approximation\nf   =np.zeros([NX+2,NY+2])#RHS\n\n#for deferred correction\nuxx   = np.zeros_like(u)\ncorr  = np.zeros_like(u)\n\n#calcualte the RHS and exact solution\nDX=1.0/NX\nDY=1.0/NY\n\nn=1 # number of waves in the solution\nxc=np.linspace(0.5*DX,1-0.5*DX,NX)\nyc=np.linspace(0.5*DY,1-0.5*DY,NY)\nXX,YY=np.meshgrid(xc,yc,indexing='ij')\n\nuann[1:NX+1,1:NY+1]=Uann(XX,YY,n)\nf[1:NX+1,1:NY+1]=source(XX,YY,n)\n\nprint('mgd2d.py : Two Dimensional geometric multigrid solver')\nprint('NX:',NX,', NY:',NY,', levels: ',nlevels)\n#start solving\ntb=time.time()\n\nu,res=FMG(NX,NY,nlevels,f,2)\n\nerror=np.abs(uann[1:NX+1,1:NY+1]-u[1:NX+1,1:NY+1])\nprint(' 2nd Order::L_inf (true error): ',np.max(np.max(error)))\nprint(' Elapsed time: ',time.time()-tb,' seconds')\n\nprint('Improving approximation using deferred correction')\n\n#deferred correction\n#refer Leveque, p63\nAx=1.0/DX**2\nAy=1.0/DY**2\n\nfor i in range(1,NX+1):\n  for j in range(1,NY+1):\n    uxx[i,j]=(u[i+1,j]+u[i-1,j] - 2*u[i,j])/DX**2\n\n# we should be using one-sided difference formulae for values \n# near the boundary. For simplicity I am just applying the  \n# condition known from the analytical form for these terms.\n\nuxx[ 0,:] = -uxx[ 1,:]\nuxx[-1,:] = -uxx[-2,:]\nuxx[:, 0] = -uxx[:, 1]\nuxx[:,-1] = -uxx[:,-2]\n\nf[ 0,:] = -f[ 1,:]\nf[-1,:] = -f[-2,:]\nf[:, 0] = -f[:, 1]\nf[:,-1] = -f[:,-2]\n\n#correction term\n#  del2(f)-2*uxxyy\nfor i in range(1,NX+1):\n  for j in range(1,NY+1):\n    corr[i,j]=(Ax*(f[i+1,j]+f[i-1,j])+Ay*(f[i,j+1]+f[i,j-1])-2.0*(Ax+Ay)*f[i,j])-2*(uxx[i,j+1]+uxx[i,j-1] - 2*uxx[i,j])/DY**2\n\n#adjust the RHS to cancel the leading order terms\nfor i in range(1,NX+1):\n  for j in range(1,NY+1):\n    f[i,j]+= 1.0/12*DX**2*(corr[i,j])\n\n##solve once again with the new RHS\nu,res=FMG(NX,NY,nlevels,f,5)\n\ntf=time.time()\nerror=np.abs(uann[1:NX+1,1:NY+1]-u[1:NX+1,1:NY+1])\nprint(' 4nd Order::L_inf (true error): ',np.max(np.max(error)))\nprint('Elapsed time: ',tf-tb,' seconds')\n\n\n", "meta": {"hexsha": "e04005e63f3e5d43132b17f82f96708fbbbf0ec5", "size": 3299, "ext": "py", "lang": "Python", "max_stars_repo_path": "example_FMG_defcor.py", "max_stars_repo_name": "AbhilashReddyM/GeometricMultigrid", "max_stars_repo_head_hexsha": "89baf81ec20ed8ad5c8621264361e67c3cdd4542", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-08-31T19:06:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-09T14:00:35.000Z", "max_issues_repo_path": "example_FMG_defcor.py", "max_issues_repo_name": "AbhilashReddyM/GeometricMultigrid", "max_issues_repo_head_hexsha": "89baf81ec20ed8ad5c8621264361e67c3cdd4542", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-08-31T20:53:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-21T23:43:17.000Z", "max_forks_repo_path": "example_FMG_defcor.py", "max_forks_repo_name": "AbhilashReddyM/GeometricMultigrid", "max_forks_repo_head_hexsha": "89baf81ec20ed8ad5c8621264361e67c3cdd4542", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1946902655, "max_line_length": 125, "alphanum_fraction": 0.6450439527, "include": true, "reason": "import numpy", "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.919642527874199, "lm_q1q2_score": 0.8528427273124788}}
{"text": "#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 21 14:05:55 2018\r\n\r\n@author: top40ub\r\n\"\"\"\r\n\r\n\"\"\"\r\nNavigation in 3D is a non-trivial task. Due to the anisotropic definition of spherical coordinate\r\nsystems, rotations and movement along isolines or fixed points are tricky. A way to do this a bit\r\neasier is to use an old concept from particle physics called quaternions. To be true, their\r\nmathematical formulation exceeds those of vectors in terms of age. They are common standard\r\nin computer vision.\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\n\r\n\r\n\"\"\"\r\nFunction name : vec_to_quat()\r\n***Description***\r\n\r\nTransformation of 3d vectors to 4 dimensional quaternions\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([x,y,z])\r\nOutput:\r\n\ta) np.array([0,x,y,z])\r\n\r\nInline output: Raises an Error raise Exception('Error the vector is not a 3D vector [x,y,z]') if vector is not of shape (3,) \r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef vec_to_quat(vec):\r\n    if vec.shape[0] == 3:\r\n        quat = np.append([0], vec)\r\n        return quat\r\n\r\n    else:\r\n        raise Exception('Error the vector is not a 3D vector [x,y,z]')\r\n\r\n\r\n\"\"\"\r\nFunction name : quat_conjug()\r\n***Description***\r\n\r\nCalculate the conjugate quaternion of given quaternion\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([w,x,y,z])\r\nOutput:\r\n\ta) np.array([w,-x,-y,-z])\r\n\r\nInline output: Raises an Error raise Exception('Error the quaternion is not a 4D [w,x,y,z]') if quaternion is not of shape (4,)\r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef quat_conjug(quat):\r\n    if quat.shape[0] == 4:\r\n        w, x, y, z = quat\r\n        quatconjung = np.array([w, -x, -y, -z])\r\n        return quatconjung\r\n    else:\r\n        raise Exception('Error the quaternion is not a 4D [w,x,y,z]')\r\n\r\n\r\n\"\"\"\r\nFunction name : vec_normal()\r\n***Description***\r\n\r\nNormalisation of given vector within a certain tolerance\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([x,y,z])\r\n\r\nOutput:\r\n\ta) np.array([x,y,z]) with x² + y² + z² = 1\r\n\r\nInline output: Raises an Error Exception('Error the vector is not a 3D vector [x,y,z]') if vector is not of shape (3,)\r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef vec_normal(vec, tolerance=0.00001):\r\n    if vec.shape[0] == 3:\r\n    \tvec_len_quad = np.sum([n * n for n in vec])\r\n    \tif abs(vec_len_quad - 1.0) > tolerance:\r\n        \tvec_len = np.sqrt(vec_len_quad)\r\n        \tvec = vec/vec_len\r\n    \treturn vec\r\n    else:\r\n        raise Exception('Error the vector is not a 3D vector [x,y,z]')\r\n\r\n\r\n\"\"\"\r\nFunction name : quat_mult()\r\n***Description***\r\n\r\nThis function defins how to quaternions multiplicate. The multiplication core\r\ncan be interpreted as a kind of rotation. For deeper information read the\r\ncoresponding wikipedia page or one of the plenty graphical visualition books\r\nabout computer vision like I' ve done :)\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([w1,x1,y1,z1]), np,array([w2,x2,y2,z2])\r\nOutput:\r\n\ta) np.array([w_mult,x_mult,y_mult,z_mult])\r\n\r\nInline output: Raises an error Exception('Error one quaternion is not a 4D [w,x,y,z]') if quaternion is not of shape (4,)\r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef quat_mult(quat1, quat2):\r\n    if quat1.shape[0] == 4 and quat2.shape[0] ==4:\r\n        w1, x1, y1, z1 = quat1\r\n        w2, x2, y2, z2 = quat2\r\n        w_mult = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2\r\n        x_mult = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2\r\n        y_mult = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2\r\n        z_mult = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2\r\n        quat_mult = np.array([w_mult, x_mult, y_mult, z_mult])\r\n        return quat_mult\r\n    else:\r\n        raise Exception('Error one quaternion is not a 4D [w,x,y,z]')\r\n        \r\n\r\n\"\"\"\r\nFunction name : quat_vec_mult()\r\n***Description***\r\n\r\nQuaternionic multiplication between quaternion and vector. The vector\r\nis transformed. A second quaternionc multiplication with the conjugate of given\r\nquaternion returns the three vector compoments [1:] of the operation.\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([x1,y1,z1]), np,array([w2,x2,y2,z2])\r\nOutput:\r\n\ta) np.array([w_mult,x_mult,y_mult,z_mult])\r\n\r\n\r\nInline output: Raises an error Exception('Error the quaternion is not a 4D [w,x,y,z] or the vector is not 3D [x,y,z]') if quaternion or vector are not of shape (4,) or (3,)\r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef quat_vec_mult(vec1, quat1):\r\n    if vec1.shape[0] == 3 and quat1.shape[0] ==4:\r\n    \tquat2 = vec_to_quat(vec1)\r\n    \treturn quat_mult(quat_mult(quat1, quat2), quat_conjug(quat1))[1:]\r\n    else:\r\n        raise Exception('Error the quaternion is not a 4D [w,x,y,z] or the vector is not 3D [x,y,z]')\r\n        \r\n\r\n\"\"\"\r\nFunction name : axisangle_to_quat()\r\n***Description***\r\n\r\nCalcuation to transform a unit vector or any vector that will be normalsied \r\ninto a quaternion that elements are object to a rotation around half theta.\r\n!Theta needs to be of type degree!\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([x,y,z]), np.array([theta])\r\n\r\nOutput:\r\n\ta) np.array([w_a,x_a,y_a,z_a])\r\n\r\nInline output: Raises an error Exception('Error the vector is not 3D [x,y,z] or the angle 1D [theta]') if vector or angle are not of shape(3,) or (1,)\r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef axisangle_to_quat(vec, theta):\r\n    if vec.shape[0] == 3 and theta.shape[0] == 1:\r\n        vec = vec_normal(vec)\r\n        x, y, z = vec\r\n        theta = theta[0]/2\r\n        theta = np.deg2rad(theta)\r\n        w_a = np.cos(theta)\r\n        x_a = x * np.sin(theta)\r\n        y_a = y * np.sin(theta)\r\n        z_a = z * np.sin(theta)\r\n        quat_a = np.array([w_a, x_a, y_a, z_a])\r\n        return quat_a\r\n    else:\r\n        raise Exception('Error the vector is not 3D [x,y,z] or the angle 1D [theta]')\r\n        \r\n        \r\n\r\n\"\"\"\r\nFunction name : quat_to_axisangle()\r\n***Description***\r\n\r\nThe opposite function of axisangle_to_quat, it returns the axisangle the \r\ncorresponding unit vector of a given quaternion.\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([w,x,y,z])\r\n\r\nOutput:\r\n\ta) np.array([x_a,y_a,z_a]), np.arra([theta])\r\n\r\nInline output: Raises an error Exception('Error the quaternion is not a 4D [w,x,y,z]') if quaternion is not of shape (4,)\r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef quat_to_axisangle(quat):\r\n   if quat.shape[0] == 4: \r\n    \tw, vec = quat[0], quat[1:]\r\n    \ttheta = np.rad2deg(np.arccos(w) * 2.0)\r\n    \treturn vec_normal(vec), theta\r\n    \r\n   else:\r\n       raise Exception('Error the quaternion is not a 4D [w,x,y,z]')\r\n\r\n\r\n\"\"\"\r\nFunction name :vec_angle_rot()\r\n***Description***\r\n\r\nMain function for the quaternionic rotation of 3D vectors:\r\nA vector (vec) is rotated around a second vector a_unit with angle theta. \r\na_unit is a axisvector but mostly a basis vector of given cartesic coordinate\r\nsystem. In case of a cartesic basis vector we have the rotation around \r\ncoordinate axsis.\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([x,y,z]), np.array([theta]), \r\n        np.array(x2,y2,z2) with x2² + y2² + z2² = 1\r\n\r\nOutput:\r\n\ta) np.array([x1_rot,y1_rot,z1_rot])\r\n\r\nInline output: Raises an error Exception('Error one vector is not 3D [x,y,z] or the angle 1D [theta]') if vector or angle are not of shape (3,) or (1,)\r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef vec_angle_rot(vec,theta,a_unit):\r\n    if vec.shape[0] == 3 and theta.shape[0] == 1 and vec.shape[0] == 3:\r\n    \tquat1 = vec_to_quat(vec)\r\n    \tquat_a = axisangle_to_quat(a_unit,theta)\r\n    \tv_rot = quat_mult(quat_mult(quat_a,quat1),quat_conjug(quat_a))[1:]\r\n    \treturn v_rot\r\n    else:\r\n        raise Exception('Error one vector is not 3D [x,y,z] or the angle 1D [theta]')\r\n\r\n\r\nif __name__=='__main__':\r\n\tpass\r\n", "meta": {"hexsha": "596489447ef04e759208d54850e0926c0960ba7f", "size": 7517, "ext": "py", "lang": "Python", "max_stars_repo_path": "Math_and_Simulation/Quaternions.py", "max_stars_repo_name": "CIA-CCTB/pythrahyper_net", "max_stars_repo_head_hexsha": "7fb30fdf8add7386a1022f16e933e4179c08c627", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-05-28T06:11:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T18:25:18.000Z", "max_issues_repo_path": "Math_and_Simulation/Quaternions.py", "max_issues_repo_name": "CIA-CCTB/pythrahyper_net", "max_issues_repo_head_hexsha": "7fb30fdf8add7386a1022f16e933e4179c08c627", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-06-03T09:24:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T18:13:37.000Z", "max_forks_repo_path": "Math_and_Simulation/Quaternions.py", "max_forks_repo_name": "CIA-CCTB/pythrahyper_net", "max_forks_repo_head_hexsha": "7fb30fdf8add7386a1022f16e933e4179c08c627", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-28T22:06:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-28T22:06:10.000Z", "avg_line_length": 29.2490272374, "max_line_length": 173, "alphanum_fraction": 0.6349607556, "include": true, "reason": "import numpy", "num_tokens": 2171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.890294223211224, "lm_q1q2_score": 0.852823764319277}}
{"text": "\"\"\"\n.. module:: utils\n    :synopsis: Provides routines of interest to different ML models.\n\n.. moduleauthor:: Benardi Nunes <benardinunes@gmail.com>\n\"\"\"\n\nfrom numpy import zeros, copy, std, mean, float64, exp\n\n\n# sigmoid gradient function\ndef g(x):\n    \"\"\"This function applies the sigmoid function on a given value.\n\n    :param x: Input value or object containing value .\n    :type x: obj\n\n    :returns: Sigmoid function at value.\n    :rtype: obj\n    \"\"\"\n    return 1 / (1 + exp(-x))\n\n\n# sigmoid gradient function\ndef g_grad(x):\n    \"\"\"This function calculates the sigmoid gradient at a given value.\n\n    :param x: Input value or object containing value .\n    :type x: obj\n\n    :returns: Sigmoid gradient at value.\n    :rtype: obj\n    \"\"\"\n    return g(x) * (1 - g(x))\n\n\ndef gradient_descent(X, y, grad, initial_theta,\n                     alpha, num_iters, _lambda=None):\n    \"\"\"This function performs parameter optimization via gradient descent.\n\n    :param X: Features' dataset plus bias column.\n    :type X: numpy.array\n\n    :param y: Column vector of expected values.\n    :type y: numpy.array\n\n    :param grad: Routine that generates the partial derivatives given theta.\n    :type grad: numpy.array\n\n    :param initial_theta: Initial value for parameters to be optimized.\n    :type initial_theta: numpy.array\n\n    :param alpha: Learning rate or step size of the optimization.\n    :type alpha: float\n\n    :param num_iters: Number of times the optimization will be performed.\n    :type num_iters: int\n\n    :param _lambda: Weight of the penalty term.\n    :type _lambda: float\n\n    :returns: Optimized model parameters.\n    :rtype: numpy.array\n    \"\"\"\n    if _lambda is not None:\n        theta = copy(initial_theta)\n\n        for _ in range(num_iters):\n            theta = theta - alpha * grad(theta, X, y, _lambda)\n\n    else:\n        theta = copy(initial_theta)\n        for _ in range(num_iters):\n            theta = theta - alpha * grad(theta, X, y)\n\n    return theta\n\n\ndef numerical_grad(J, theta, err):\n    \"\"\"Numerically calculates the gradient of a given cost function.\n\n    :param J: Function handle that computes cost given theta.\n    :type J: function\n\n    :param theta: Model parameters.\n    :type theta: numpy.array\n\n    :param err: distance between points where J is evaluated.\n    :type err: float\n\n    :returns: Computed numeric gradient.\n    :rtype: numpy.array\n    \"\"\"\n    num_grad = zeros(theta.shape, dtype=float64)\n    perturb = zeros(theta.shape, dtype=float64)\n\n    for i in range(len(theta)):\n        perturb[i] = err\n        loss1 = J(theta - perturb)\n        loss2 = J(theta + perturb)\n        num_grad[i] = (loss2 - loss1) / (2 * err)\n        perturb[i] = 0\n\n    return num_grad\n\n\ndef feature_normalize(X):\n    \"\"\"Performs Z score normalization in a numeric dataset.\n\n    :param X: Features' dataset plus bias column.\n    :type X: numpy.array\n\n    :returns:\n        - X_norm - Normalized features' dataset.\n        - mu - Mean of each feature\n        - sigma - Standard deviation of each feature.\n\n    :rtype:\n        - X_norm (:py:class: numpy.array)\n        - mu (:py:class: numpy.array)\n        - sigma (:py:class: numpy.array)\n    \"\"\"\n    mu = mean(X)\n    sigma = std(X)\n\n    X_norm = (X - mu) / sigma\n\n    return X_norm, mu, sigma\n", "meta": {"hexsha": "eb13164d593225b1ffbf35c28efd69dfa2427a31", "size": 3261, "ext": "py", "lang": "Python", "max_stars_repo_path": "touvlo/utils.py", "max_stars_repo_name": "rickysukma/touvlo", "max_stars_repo_head_hexsha": "fcfce94a2fe3b9e4a92997c01486dba2c223e0db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "touvlo/utils.py", "max_issues_repo_name": "rickysukma/touvlo", "max_issues_repo_head_hexsha": "fcfce94a2fe3b9e4a92997c01486dba2c223e0db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "touvlo/utils.py", "max_forks_repo_name": "rickysukma/touvlo", "max_forks_repo_head_hexsha": "fcfce94a2fe3b9e4a92997c01486dba2c223e0db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2790697674, "max_line_length": 76, "alphanum_fraction": 0.6390677706, "include": true, "reason": "from numpy", "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889438, "lm_q2_score": 0.8902942203004186, "lm_q1q2_score": 0.8528237626006878}}
{"text": "# Chapter 3 Decision tree learning\r\n\r\n# Maximizing information gain - getting the most bang for the buck\r\n''' Plot the impurity indices for the probability range [0,1] for class 1.\r\nNote that we will also add in a scaled version of the entropy (entropy/2)\r\nto observe that the Gini impurity is an intermediate measure  between\r\nentropy and the classification error. '''\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\ndef gini(p):\r\n    return (p) * (1 - (p)) + (1 - p) * (1 - (1-p))\r\n    \r\ndef entropy(p):\r\n    return - p*np.log2(p) - (1 - p)* np.log2((1 - p))\r\n    \r\ndef error(p):\r\n    return 1 - np.max([p, 1 - p])\r\n    \r\nx = np.arange(0.0, 1.0, 0.01)\r\nent = [entropy(p) if p != 0 else None for p in x]\r\nsc_ent = [e*0.5 if e else None for e in ent]\r\nerr = [error(i) for i in x]\r\nfig = plt.figure()\r\nax = plt.subplot(111)\r\nfor i, lab, ls, c, in zip([ent, sc_ent, gini(x), err], ['Entropy', 'Entropy (scaled)', 'Gini Impurity', 'Misclassification Error'],\r\n['-', '-', '--', '-.'], ['black', 'lightgray', 'red', 'green', 'cyan']):\r\n   line = ax.plot(x, i, label=lab, linestyle=ls, lw=2, color=c)\r\n   \r\nax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.15), ncol=3, fancybox=True, shadow=False)\r\nax.axhline(y=0.5, linewidth=1, color='k', linestyle='--')\r\nax.axhline(y=1.0, linewidth=1, color='k', linestyle='--')\r\nplt.ylim([0, 1.1])\r\nplt.xlabel('p(i=1)')\r\nplt.ylabel('Impurity Index')\r\nplt.show()\r\n\r\n# Building a decision tree\r\n'''\r\nDecision trees can build complex decision boundaries by dividing the feature\r\nspace into rectangles. Using scikit-learn, we will now train a decision tree with\r\na maximum depth of 3 using entropy as a criterion for impurity.  Although feature\r\nscaling may be desired for visualization purposes, note that feature scaling is\r\nnot a requirement for decision tree algorithms.\r\n '''\r\n# Train a  model to classify the different flowers in our Iris dataset\r\nfrom sklearn import datasets\r\nimport numpy as np\r\n\r\niris = datasets.load_iris()\r\nX = iris.data[:, [2, 3]]\r\ny = iris.target\r\n\r\nfrom sklearn.cross_validation import train_test_split\r\n\r\n# random_state : int or RandomState\r\n# Pseudo-random number generator state used for random sampling.\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\r\n\r\nfrom matplotlib.colors import ListedColormap\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):\r\n    # setup marker generator and color map\r\n    markers = ('s', 'x', 'o', '^', 'v')\r\n    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')\r\n    cmap = ListedColormap(colors[:len(np.unique(y))])\r\n    # plot the decision surface\r\n    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1\r\n    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1\r\n    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),\r\n                           np.arange(x2_min, x2_max, resolution))\r\n    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)\r\n    Z = Z.reshape(xx1.shape)\r\n    plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)\r\n    plt.xlim(xx1.min(), xx1.max())\r\n    plt.ylim(xx2.min(), xx2.max())\r\n    # plot all samples\r\n    X_test, y_test = X[test_idx, :], y[test_idx]\r\n    for idx, cl in enumerate(np.unique(y)):\r\n        plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=cl)\r\n\r\n    # highlight test samples\r\n    if test_idx:\r\n        X_test, y_test = X[test_idx, :], y[test_idx]\r\n        plt.scatter(X_test[:, 0], X_test[:, 1], c='', alpha=1.0, linewidth=1, marker='o', s=55, label='test set')\r\n\r\n\r\nfrom sklearn.tree import DecisionTreeClassifier\r\ntree = DecisionTreeClassifier(criterion='entropy',max_depth=3, random_state=0)\r\ntree.fit(X_train, y_train)\r\nX_combined = np.vstack((X_train, X_train))\r\ny_combined = np.hstack((y_train, y_test))\r\nplot_decision_regions(X_combined, y_combined, classifier=tree, test_idx=range(105,150))\r\nplt.xlabe('petal length [cm]')\r\nplt.ylabel('petal width [cm]')\r\nplt.legend(loc='upper left')\r\nplt.show()\r\n\r\n'''\r\nA nice feature in scikit-learn is that is allows us to export the decision tree as a \r\n.dot file after training, which we can visualize using the GraphViz program. \r\nFirst, we create the .dot file via scikit-learn using the export_graphviz function\r\nfrom the tree submodule, as follows:\r\n'''\r\nfrom sklearn.tree import export_graphviz\r\nexport_graphviz(tree, out_file='C:\\Users\\Wei\\Desktop/tree.dot', feature_names=['petal length', 'petal width'])\r\n\r\n'''\r\nAfter installed GraphViz on the computer, we can convert the tree.dot file into a PNG file\r\nby executing the following command from the command line in the location where we \r\nsaved the tree.dot file:\r\n\r\n> dot -Tpng tree.dot -o tree.png\r\n'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "279490418505ceab984f3b30afc026f7fde124eb", "size": 4776, "ext": "py", "lang": "Python", "max_stars_repo_path": "self_practice/Chapter 3 Decision Tree.py", "max_stars_repo_name": "wei-Z/Python-Machine-Learning", "max_stars_repo_head_hexsha": "47101e2d7d28665bdbb3145fb503e039f944046e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "self_practice/Chapter 3 Decision Tree.py", "max_issues_repo_name": "wei-Z/Python-Machine-Learning", "max_issues_repo_head_hexsha": "47101e2d7d28665bdbb3145fb503e039f944046e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "self_practice/Chapter 3 Decision Tree.py", "max_forks_repo_name": "wei-Z/Python-Machine-Learning", "max_forks_repo_head_hexsha": "47101e2d7d28665bdbb3145fb503e039f944046e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8613138686, "max_line_length": 132, "alphanum_fraction": 0.6628978224, "include": true, "reason": "import numpy", "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360067, "lm_q2_score": 0.8933094060543488, "lm_q1q2_score": 0.8527955204089982}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 23 11:49:57 2021\n\n@author: ahmed\n\"\"\"\n\nfrom statistics import mean\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\n\nstyle.use('fivethirtyeight')\n\nxs = np.array([1,2,3,4,5,6], dtype=np.float64)\nys = np.array([5,4,6,5,6,7], dtype=np.float64)\n\ndef best_fit_slope_and_intercept(xs,ys):\n    m = (((mean(xs)*mean(ys)) - mean(xs*ys))/\n          ((mean(xs)**2)-mean(xs**2)) )\n    b = mean(ys) - m*mean(xs)\n    return m,b\n\ndef squared_error(ys_orig, ys_line):\n    return sum((ys_line-ys_orig)**2)\n\ndef coefficient_of_determination(ys_orig, ys_line):\n    y_mean_line =[mean(ys_orig) for y in ys_orig]\n    print('y_mean_line', y_mean_line)\n    \n    \n    squared_error_regr = squared_error(ys_orig, ys_line)\n    print('squared_error_regr', squared_error_regr)\n    \n    squared_error_y_mean = squared_error(ys_orig, y_mean_line)\n    \n    return 1 - (squared_error_regr / squared_error_y_mean)  \n\nm,b = best_fit_slope_and_intercept(xs,ys)\nregression_line = [(m*x)+b for x in xs]\n\n\npredict_x = 7\npredict_y = m*predict_x + b\n\nr_squared =coefficient_of_determination(ys, regression_line)\nprint(r_squared)\n\nplt.scatter(xs,ys)\nplt.scatter(predict_x,predict_y, color='r')\nplt.plot(xs,regression_line)\nplt.show()", "meta": {"hexsha": "87bddcb09f7d93c6fe63d8d7fd2082fe83e4f8d6", "size": 1269, "ext": "py", "lang": "Python", "max_stars_repo_path": "Machine learning/sentdex course/Machine learning/Regression/ML8-slopecalculation.py", "max_stars_repo_name": "ahmedosaka/HACKER_RANK", "max_stars_repo_head_hexsha": "f594fa8e1eeed0598f7151556a1068865cf9be91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Machine learning/sentdex course/Machine learning/Regression/ML8-slopecalculation.py", "max_issues_repo_name": "ahmedosaka/HACKER_RANK", "max_issues_repo_head_hexsha": "f594fa8e1eeed0598f7151556a1068865cf9be91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Machine learning/sentdex course/Machine learning/Regression/ML8-slopecalculation.py", "max_forks_repo_name": "ahmedosaka/HACKER_RANK", "max_forks_repo_head_hexsha": "f594fa8e1eeed0598f7151556a1068865cf9be91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4038461538, "max_line_length": 62, "alphanum_fraction": 0.7029156816, "include": true, "reason": "import numpy", "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.8933094081846422, "lm_q1q2_score": 0.8527955178320817}}
{"text": "\"\"\"ЛР 1.5, Ларькин Владимир, М8О-303Б-18\"\"\"\n\nimport numpy as np\nimport fire  # CLI\nimport matplotlib.pyplot as plt\n\nfrom utilities import parse_matrix  # парсинг матрицы из файла\n\n\ndef householder(a, sz, k):\n    v = np.zeros(sz)\n    v[k] = a[k] + np.sign(a[k]) * np.linalg.norm(a[k:])\n    for i in range(k + 1, sz):\n        v[i] = a[i]\n    v = v[:, np.newaxis]\n    H = np.eye(sz) - (2 / (v.T @ v)) * (v @ v.T)\n    return H\n\n\ndef get_QR(A):\n    sz = len(A)\n    Q = np.identity(sz)\n    A_i = np.copy(A)\n\n    for i in range(sz - 1):\n        col = A_i[:, i]\n        H = householder(col, len(A_i), i)\n        Q = Q @ H\n        A_i = H @ A_i\n\n    return Q, A_i\n\n\ndef get_roots(A, i):\n    sz = A.shape[0]\n    a11 = A[i, i]\n    a12 = A[i, i + 1] if i + 1 < sz else 0\n    a21 = A[i + 1, i] if i + 1 < sz else 0\n    a22 = A[i + 1, i + 1] if i + 1 < sz else 0\n    return np.roots((1, -a11 - a22, a11 * a22 - a12 * a21))\n\n\ndef finish_iter_for_complex(A, eps, i):\n    Q, R = get_QR(A)\n    A_next = R @ Q\n    lambda1 = get_roots(A, i)\n    lambda2 = get_roots(A_next, i)\n    return True if abs(lambda1[0] - lambda2[0]) <= eps and abs(lambda1[1] - lambda2[1]) <= eps else False\n\n\ndef get_eigenvalue(A, eps, i):\n    A_i = np.copy(A)\n    while True:\n        Q, R = get_QR(A_i)\n        A_i = R @ Q\n        a = np.copy(A_i)\n        if np.linalg.norm(a[i + 1:, i]) <= eps:\n            res = (a[i][i], False, A_i)\n            break\n        elif np.linalg.norm(a[i + 2:, i]) <= eps and finish_iter_for_complex(A_i, eps, i):\n            res = (get_roots(A_i, i), True, A_i)\n            break\n    return res\n\n\ndef QR_method(A, eps):\n    res = []\n    i = 0\n    A_i = np.copy(A)\n    while i < A.shape[0]:\n        eigenval = get_eigenvalue(A_i, eps, i)\n        if eigenval[1]:\n            res += [*eigenval[0]]\n            i += 2\n        else:\n            res.append(eigenval[0])\n            i += 1\n        A_i = eigenval[2]\n    return np.array(res), i\n\n\ndef main(src, test=False, eps=0.01):\n    \"\"\"Нахождение собственных значений матрицы методом QR-разложения\n\n    :param src: путь к текстовому файлу с матрицей\n    :param test: флаг, запускающий тестирование\n    :param eps: точность вычисления\n    \"\"\"\n\n    np.random.seed(42)\n\n    # чтение файла\n    with open(src, \"r\") as file:\n        s = file.readlines()\n\n    matrix = parse_matrix(s)\n\n    print(f\"Матрица:\\n{matrix}\")\n    print(f\"\\neps={eps}\\n\")\n\n    tmp, count_iter = QR_method(matrix, eps)\n    print(\"QR_method:\\n\", tmp)\n\n    print(\"\\nnp.linalg.eig:\\n\", np.linalg.eig(matrix)[0])\n\n\nif __name__ == \"__main__\":\n    fire.Fire(main)\n", "meta": {"hexsha": "86e0b433593033ed3057c8171a55b5950f7b2354", "size": 2560, "ext": "py", "lang": "Python", "max_stars_repo_path": "sem1/lab1_5/qr.py", "max_stars_repo_name": "NetherQuartz/NumericalMethodsLabs", "max_stars_repo_head_hexsha": "731ba11bc068018371d5e1a2f9b521ec7c4619ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-10T18:10:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-10T18:10:48.000Z", "max_issues_repo_path": "sem1/lab1_5/qr.py", "max_issues_repo_name": "NetherQuartz/NumericalMethodsLabs", "max_issues_repo_head_hexsha": "731ba11bc068018371d5e1a2f9b521ec7c4619ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sem1/lab1_5/qr.py", "max_forks_repo_name": "NetherQuartz/NumericalMethodsLabs", "max_forks_repo_head_hexsha": "731ba11bc068018371d5e1a2f9b521ec7c4619ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4862385321, "max_line_length": 105, "alphanum_fraction": 0.535546875, "include": true, "reason": "import numpy", "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650674, "lm_q2_score": 0.8933093989533708, "lm_q1q2_score": 0.8527955101721214}}
{"text": "# A manufacturer purchases a part for use at both of its plantsdashone at​ Roseville, California, the other at​ Akron, Ohio. \n# The part is available in limited quantities from two suppliers. \n\n# Each supplier has 85 units available. \n\n# The Roseville plant needs 50 ​units, and the Akron plant requires 85 units. \n\n# The first supplier charges ​$50 per unit delivered to Roseville and ​$80 per unit delivered to Akron. \n\n# Corresponding costs from the second supplier are ​$90 and ​$110. \n\n# The manufacturer wants to order a total of 85 units from the​ first, less expensive​ supplier, with the remaining 50 units to come from the second supplier. \n# If the company spends ​$10,800 to purchase the required number of units for the two​ plants, find the number of units that should be sent from each supplier to each plant.\n\n# Write a linear system of equations. \n\n# The number of units sent from the first supplier to Roseville is​ w, \n# the number of units sent from the first supplier to Akron is​ x, \n# the number of units sent from the second supplier to Roseville is​ y, \n# and the number of units sent from the second supplier to Akron is z. \n\n# Choose the correct answer below.\n\nfrom sympy import symbols, solve\n\nw,x,y,z = symbols( 'w,x,y,z' )\n\n# w + y = 50\nexpr1 = w + y - 50\n\n# w + x = 85\nexpr2 = w + x - 85\n\n# w + x + y + z = 135\nexpr3 = w + x + y + z - 135\n\n# 50*w + 80*x + 90*y + 110*z\nexpr4 = 50*w + 80*x + 90*y + 110*z - 10800\n\nsolve( ( expr1, expr2, expr3, expr4 ), dict = True )\n", "meta": {"hexsha": "e0ba7ab7bbe171c3d3c78772ebfd97783070cee0", "size": 1497, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Module 3/supplies.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Module 3/supplies.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Module 3/supplies.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.512195122, "max_line_length": 173, "alphanum_fraction": 0.7054108216, "include": true, "reason": "from sympy", "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9546474142844408, "lm_q2_score": 0.8933094003735664, "lm_q1q2_score": 0.8527955092226095}}
{"text": "''' mbinary\n#########################################################################\n# File : numerical_integration.py\n# Author: mbinary\n# Mail: zhuheqin1@gmail.com\n# Blog: https://mbinary.xyz\n# Github: https://github.com/mbinary\n# Created Time: 2018-10-02  21:14\n# Description:\n#########################################################################\n'''\n\n\n#########################################################################\n# File : numerical integration.py\n# Author: mbinary\n# Mail: zhuheqin1@gmail.com\n# Blog: https://mbinary.xyz\n# Github: https://github.com/mbinary\n# Created Time: 2018-05-11  08:58\n# Description: \n#       numerical intergration: using Newton-Cotes integration,  and Simpson\n#       数值积分, 使用 牛顿-科特斯积分, 辛普森\n#########################################################################\n\n\n\nimport numpy as np\ndef trapezoidal(a,b,h,fs):\n    '''梯形积分公式'''\n    xs = [i for i in np.arange(a,b+h,h)]\n    print(xs)\n    ret = h*(sum(fs)-fs[0]/2 - fs[-1]/2)\n    print(ret)\n    return ret\n\n\ndef simpson(a,b,h,fs):\n    '''辛普森积分公式'''\n    xs = [i for i in np.arange(a,b+h,h)]\n    print(xs)\n    ret = h/3*(4* sum(fs[1::2])+ 2*sum(fs[2:-1:2]) + fs[0]+fs[-1])\n    print(ret)\n    return ret\n\n\ndef romberg(a,b,f,epcilon):\n    '''romberg(龙贝格) 数值积分'''\n    h = b-a\n    lst1=[h*(f(a)+f(b))/2]\n    print(lst1)\n    delta = epcilon\n    k=1\n    while delta >= epcilon:\n        h/=2\n        k+=1\n        lst2=[]\n        lst2.append((lst1[0]+h*2*sum(f(a+(2*i-1)*h) for i in range(1,2**(k-2)+1)))/2)\n        for j in range(0,k-1):\n            lst2.append(lst2[j]+(lst2[j]-lst1[j])/(4**(j+1)-1))\n        delta = abs(lst2[-1]-lst1[-1])\n        lst1=lst2\n        print(lst1)\n\nif __name__=='__main__':\n    a,b,h = 0.6,1.8,0.2\n    fs=[5.7,4.6,3.5,3.7,4.9,5.2,5.5]\n    trapezoidal(a,b,h,fs)\n    simpson(a,b,h,fs)\n    romberg(1,2,lambda x:sin(x**4),1e-4)\n", "meta": {"hexsha": "2a97241d7e56da89ae3a915c54b90d4d57b622a8", "size": 1843, "ext": "py", "lang": "Python", "max_stars_repo_path": "math/numericalAnalysis/numerical_integration.py", "max_stars_repo_name": "snowflying/algorithm-in-python", "max_stars_repo_head_hexsha": "d92e211119b8a786807942c2765058e522e37769", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-14T06:15:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-14T06:15:29.000Z", "max_issues_repo_path": "math/numericalAnalysis/numerical_integration.py", "max_issues_repo_name": "snowflying/algorithm-in-python", "max_issues_repo_head_hexsha": "d92e211119b8a786807942c2765058e522e37769", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/numericalAnalysis/numerical_integration.py", "max_forks_repo_name": "snowflying/algorithm-in-python", "max_forks_repo_head_hexsha": "d92e211119b8a786807942c2765058e522e37769", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-22T00:32:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T00:32:56.000Z", "avg_line_length": 25.9577464789, "max_line_length": 85, "alphanum_fraction": 0.4720564297, "include": true, "reason": "import numpy", "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.9073122226137633, "lm_q1q2_score": 0.8527948704949688}}
{"text": "import numpy as np\n\nclass Sigmoid():\n    \"\"\"\n    Sigmoid activation function\n    \"\"\"\n    def __call__(self, X: np.ndarray) -> np.ndarray:\n        \"\"\"\n        Performs the sigmoid function on a given vector\n\n        Parameters\n        ----------\n        X : array_like, shape {n_samples, n_features}\n            Input vector\n\n        Returns\n        -------\n        array_like, shape {n_samples, n_features}\n            Input vector transformed\n        \"\"\"\n        return 1 / (1 + np.exp(-X))\n\nclass Softmax():\n    \"\"\"\n    Softmax activation function\n    \"\"\"\n    def __call__(self, scores: np.ndarray) -> np.ndarray:\n        \"\"\"\n        Performs the softmax function on a given vector\n\n        Parameters\n        ----------\n        X : array_like, shape {n_samples, n_classes}\n            Scores vector\n\n        Returns\n        -------\n        array_like, shape {n_samples, n_classes}\n            Scores vector transformed\n        \"\"\"\n        exps = np.exp(scores)\n        exps_sum = np.sum(exps, axis=1, keepdims=True)\n\n        return exps / exps_sum  ", "meta": {"hexsha": "0e340217f68b0a705eda008e05fa922d13dd168d", "size": 1052, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/activation_functions.py", "max_stars_repo_name": "hectorLop/ML_algorithms", "max_stars_repo_head_hexsha": "0c5181e460640efc7e81210cf132f3bbd9d73910", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/activation_functions.py", "max_issues_repo_name": "hectorLop/ML_algorithms", "max_issues_repo_head_hexsha": "0c5181e460640efc7e81210cf132f3bbd9d73910", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/activation_functions.py", "max_forks_repo_name": "hectorLop/ML_algorithms", "max_forks_repo_head_hexsha": "0c5181e460640efc7e81210cf132f3bbd9d73910", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9090909091, "max_line_length": 57, "alphanum_fraction": 0.533269962, "include": true, "reason": "import numpy", "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104933824754, "lm_q2_score": 0.8824278772763471, "lm_q1q2_score": 0.8527875602530851}}
{"text": "# Exercise 4.3.1\n# Mortality rates in the middle ages\n\nfrom scipy import optimize\nfrom math import log\nfrom math import exp\n\n# Ages at time of death (given in lecture notes)\nages = [47, 67, 38, 45, 48, 48, 51, 76, 32, 43, 42, 26, 25, 40, 53, 64, 49, 42,\n        57, 30, 1, 1, 6, 9, 12, 14, 18]\n\n\n# Model ansatz\n# mu(x) = Probability to die between age x and x+1,\n#         conditional on being alive at age x.\ndef mu(x, a, b, c):\n    return(exp(a + b * x + c * x ** 2))\n\n\n# Negative log-likelihood\n# Probability of dying at age x is the product of the probabilities of not dying\n# during years before x, and the probability of dying between age x and x+1.\ndef negll(abc, ages):\n    a, b, c = abc\n    ll = 0\n    for age in ages:\n        for x in range(age):\n            # not dying before age of death\n            ll += log(1 - mu(x, a, b, c))\n        # dying at age of death\n        ll += a + b * age + c * age ** 2  # same as log(mu(x, a, b, c))\n    return(-ll)\n\n\n# Solving for three parameters in model ansatz\n# Initial values are the solution given in lecture notes\nprint(optimize.minimize(negll, (-4.36, 1.01e-2, 4.08e-4), args=(ages,)))\n# This gives [a, b, c] = [-4.48664309e+00, 1.52875034e-02, 3.38010681e-04],\n# different from the given solution.\n", "meta": {"hexsha": "4bcd13373f5c7027e4332ebffc69f7ddd1ed42de", "size": 1255, "ext": "py", "lang": "Python", "max_stars_repo_path": "selected-topics-in-life-insurance/mortality-rates-middle-ages.py", "max_stars_repo_name": "adrische/actuary", "max_stars_repo_head_hexsha": "1b446c3a66ef831a0727ff4d3ea1e1cc3b838af9", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-04-30T18:33:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T13:58:53.000Z", "max_issues_repo_path": "selected-topics-in-life-insurance/mortality-rates-middle-ages.py", "max_issues_repo_name": "adrische/actuary", "max_issues_repo_head_hexsha": "1b446c3a66ef831a0727ff4d3ea1e1cc3b838af9", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "selected-topics-in-life-insurance/mortality-rates-middle-ages.py", "max_forks_repo_name": "adrische/actuary", "max_forks_repo_head_hexsha": "1b446c3a66ef831a0727ff4d3ea1e1cc3b838af9", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.375, "max_line_length": 80, "alphanum_fraction": 0.6175298805, "include": true, "reason": "from scipy", "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.975576914206421, "lm_q2_score": 0.8740772450055545, "lm_q1q2_score": 0.8527295814605687}}
{"text": "import numpy as cp\n\nclass Softmax():\n    \n    '''\n    The softmax function is a generalization of the logistic function to multiple dimensions.\n    It is used in multinomial logistic regression and is often used as the last activation\n    function of a neural network to normalize the output of a network to a probability \n    distribution over predicted output classes.\n    \n    The softmax function takes as input a vector z of K real numbers, and normalizes it into \n    a probability distribution consisting of K probabilities proportional to the exponentials\n    of the input numbers.\n    \n    The Softmax function is defined as follows:\n        \n        softmax(x) =  ___exp(xi)____ where exp is exponential function\n                           ∑ exp(x)\n                          \n    Parameters\n    ----------\n    x : cp.array\n        Array of ouputs of deeplearning layer.\n\n    Returns\n    -------\n    cp.array\n        Array after Softmax function applied .\n    \n    '''\n    \n    def __call__(self, x: cp.array) -> cp.array:\n        \n        e_x = cp.exp(x)\n        return e_x / cp.sum(e_x, axis=-1, keepdims=True)\n\n    def gradient(self, x: cp.array) -> cp.array:\n        '''\n        \n        Parameters\n        ----------\n        x : cp.array\n             Array of ouputs of deeplearning layer..\n\n        Returns\n        -------\n        cp.array\n            Array after derivatives of Softmax applied .\n\n        '''\n        \n        p = self.__call__(x)\n        return p * (1 - p)\n", "meta": {"hexsha": "53622b72b0bbfaf1f75a18e6d296295903365612", "size": 1490, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorial/7. Deep Learning/Activation Function/Softmax.py", "max_stars_repo_name": "rjnp2/Data-Science", "max_stars_repo_head_hexsha": "4ea830983d064c1da082e18282a1d746eda8d96f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-06-03T10:26:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T18:42:27.000Z", "max_issues_repo_path": "tutorial/7. Deep Learning/Activation Function/Softmax.py", "max_issues_repo_name": "sanjipun/Data-Science", "max_issues_repo_head_hexsha": "4ea830983d064c1da082e18282a1d746eda8d96f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial/7. Deep Learning/Activation Function/Softmax.py", "max_forks_repo_name": "sanjipun/Data-Science", "max_forks_repo_head_hexsha": "4ea830983d064c1da082e18282a1d746eda8d96f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-03T10:26:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-03T10:26:55.000Z", "avg_line_length": 27.5925925926, "max_line_length": 93, "alphanum_fraction": 0.5771812081, "include": true, "reason": "import numpy", "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769113660689, "lm_q2_score": 0.8740772236840656, "lm_q1q2_score": 0.8527295581771293}}
{"text": "\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\"\"\"\nSome notations: \n    d = number of features including W_0\n    n = number of observations\n\n\"\"\"\n\ndef prepare_X(X:np.ndarray, degree:int = 1)-> np.ndarray: \n    '''\n    Expands X as per degrees and appends a column of ones in the begining\n    Input:\n        X: (n*1) Input matrix\n        degress: expanding X to number of degrees\n    Returns: \n        X_new : (n * d) matrix\n    '''\n    assert X.ndim == 2\n\n    n = X.shape[0]\n\n    X_new = X.copy()\n\n    if degree>1:\n        for d in range(2,degree+1):\n            X_new = np.hstack((X_new, X**d))\n    \n    # append column of ones'\n    X_new = np.hstack((np.ones([n,1]), X_new))\n\n    return X_new\n\ndef normaliz_data(X):\n    '''\n    Z- normalized data and array of means and sds to normalize validation data \n    Input: \n        X: (n*d) matrix\n    Returns:\n        X_norm : n*d , z-normalized data\n        mean = np array of means of all columns \n        std = np array of std of all columns \n    '''\n    mean = X.mean(axis=0)\n    std = X.std(axis=0)\n    mean[0] = 0 # the first columns is column of ones. \n    std[0] = 1 # the first columns is column of ones. \n\n    X_norm = (X - mean)/ std\n\n    return X_norm, mean, std\n\ndef w_closedForm(X,y):\n    '''\n    Finds the optimal w using closed form solution\n    \n    Input:\n        X = 2D array, N*(D+1) data matrix\n        y = 1D array, N lenghth vector of y values\n    Output:\n        w = 1D array, (D+1) lengthe vector \n    '''\n    \n    w = np.dot(np.linalg.pinv(X),y)\n    \n    return w\n\ndef give_squared_loss_grad(X, y, w, overPred_penalty=1, underPred_penalty=1):\n    '''\n    Gives squared loss and grandient given X, w and other parameters\n    Input:\n        X = 2D array; n*d input matrix\n        y = 1D array; (n,) output array\n        w = 1D array; (), weights array \n        overPred_penalty = [-Inf, Inf] penulty for over prediction \n        underPred_penalty = [-Inf, Inf] penulty for under prediction \n    Returns:\n        loss: float = squared loss\n        grad: (d*1) array of gradients\n    '''\n    \n    n = X.shape[0]\n\n    # errors \n    e = np.dot(X,w) - y\n\n    # Penalty for Over/ Under Prediction\n    penulty_vect = (e>0.).astype(float)\n    penulty_vect[penulty_vect==1] = overPred_penalty\n    penulty_vect[penulty_vect==0] = underPred_penalty\n\n    # Asymmetric Loss\n    asym_e = np.multiply(penulty_vect, e)\n\n    # Normalised Squared Loss\n    loss = np.dot(np.transpose(asym_e), asym_e) /(2*n)\n\n    # Gradient \n    grad = (np.dot(X.T, asym_e)) / n\n\n    return loss, grad\n\n\ndef GradDescent_LinReg(X, y, overPred_penalty=1, underPred_penalty=1, lr=0.1 , maxIt = 10000, verbose=False):\n    \n    '''\n    Finds the optimal w using Gradient Descent method\n    Input:\n        X = 2D array; n*d input matrix\n        y = 1D array; (n,) output array\n        w = 1D array; (), weights array \n        overPred_penalty = [-Inf, Inf] penulty for over prediction \n        underPred_penalty = [-Inf, Inf] penulty for under prediction \n        lr = learing rate\n        maxIt = Maximum Iterations       \n    Returns:\n        w  = (d*1) array of weights\n    '''\n    n,d = X.shape\n\n    if verbose:\n        itr_data = []\n\n    # initialize W randomly \n    w = np.random.rand(d,1)\n\n    for i in range(maxIt):\n        loss, grad = give_squared_loss_grad(X, y, w, overPred_penalty, underPred_penalty)\n        \n        if verbose:\n            itr_data.append(loss[0][0])\n        w = w - (lr*grad)\n    \n    if verbose:\n        return itr_data, w\n\n    return w\n\ndef find_best_model_plot_results(X_train, y_train, X_val, y_val, \n                            method:str, overPred_penalty=1, underPred_penalty=1, lr=0.1 , maxIt = 10000 ):\n\n\n    # checking for degrees till 5\n    degrees = [i for i in range(1,6)]\n\n    # storing the best model\n\n    min_loss = np.Inf\n    best_model = {}\n    all_model = {}\n\n    # for plotting \n    fig = matplotlib.pyplot.gcf()\n    fig.set_size_inches(11, 7)\n    plt.plot(X_train, y_train, 'k.')\n\n    x_axis_data = np.linspace(min(X_train)-0.1, max(X_train)+-.1, num=100)\n\n    # below loop: for each polynomial degree finds the w*, finds the val loss and plots the fitted curve\n    for d in degrees:\n        X = prepare_X(X_train, degree=d)\n        X_norm, X_mean, X_std = normaliz_data(X)\n        if method == 'ClosedForm':\n            w = w_closedForm(X_norm, y_train)\n        if method == \"GradientDescent\":\n            w = GradDescent_LinReg(X_norm, y_train, overPred_penalty, underPred_penalty, lr, maxIt)\n        train_loss = give_squared_loss_grad(X_norm, y_train, w)[0]\n        \n        # for validation loss\n        X_val_prep = prepare_X(X_val, degree=d)\n        X_val_norm = (X_val_prep - X_mean) / X_std\n        val_loss = give_squared_loss_grad(X_val_norm, y_val, w)[0]\n        \n        all_model['degree:'+str(d)] = {'train_loss':train_loss, 'val_loss':val_loss, 'w':w}\n        \n        if val_loss < min_loss:\n            min_loss = val_loss\n            best_model['degree'] = d\n            best_model['w'] = w\n            best_model['train_loss'] = train_loss\n            best_model['val_loss'] = val_loss\n            \n            if method == \"GradientDescent\":\n                best_model['OverPred Penalty'] = overPred_penalty\n                best_model['UnderPred Penalty'] = underPred_penalty\n                best_model['learning_rate'] = lr\n                best_model['maxIt'] : maxIt\n        \n        # to plot the line\n        X_graph = ((prepare_X(x_axis_data, degree=d))-X_mean) / X_std\n        \n        y_axis_data = np.dot(X_graph,w)\n        \n        color = {1:'b', 2:'g', 3:'r', 4:'y', 5:'c'}[d]\n        plt.plot(x_axis_data, y_axis_data, color, label = \"deg:\"+str(d))\n        \n    plt.legend()\n\n    return best_model", "meta": {"hexsha": "230b294124e42a1bc917dc150aff4ee588006e74", "size": 5756, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils.py", "max_stars_repo_name": "piyush13290/ml_without_sklearn", "max_stars_repo_head_hexsha": "d5d9721a037d56007b4ed223b3ebf948835266e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-15T01:41:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T01:41:19.000Z", "max_issues_repo_path": "utils.py", "max_issues_repo_name": "piyush13290/ml_without_sklearn", "max_issues_repo_head_hexsha": "d5d9721a037d56007b4ed223b3ebf948835266e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils.py", "max_forks_repo_name": "piyush13290/ml_without_sklearn", "max_forks_repo_head_hexsha": "d5d9721a037d56007b4ed223b3ebf948835266e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.354679803, "max_line_length": 109, "alphanum_fraction": 0.5879082696, "include": true, "reason": "import numpy", "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.9184802473724224, "lm_q1q2_score": 0.852725139338819}}
{"text": "\n#inverse an matrix\nimport numpy as np\nA = np.mat(\"2 4 6;4 2 6;10 -4 18\")\nprint \"A\\n\", A\ninverse = np.linalg.inv(A)\nprint \"inverse of A\\n\", inverse\nprint \"Check\\n\", A * inverse\nprint \"Error\\n\", A * inverse - np.eye(3)\n\n#solve linear system with numpy\nimport numpy as np\nA = np.mat(\"1 -2 1;0 2 -8;-4 5 9\")\nprint \"A\\n\", A\nb = np.array([0, 8, -9])\nprint \"b\\n\", b\nx = np.linalg.solve(A, b)\nprint \"Solution\", x\nprint \"Check\\n\", np.dot(A , x)\n\n#find eigenvalue and eigenvectors\nimport numpy as np\nA = np.mat(\"3 -2;1 0\")\nprint \"A\\n\", A\nprint \"Eigenvalues\", np.linalg.eigvals(A)\neigenvalues, eigenvectors = np.linalg.eig(A)\nprint \"First tuple of eig\", eigenvalues\nprint \"Second tuple of eig\\n\", eigenvectors\nfor i in range(len(eigenvalues)):\n    print \"Left\", np.dot(A, eigenvectors[:,i])\n    print \"Right\", eigenvalues[i] * eigenvectors[:,i]\n    print\n    \n", "meta": {"hexsha": "9a647735eeb7ea9e365fe684df9bbaeab812a2d4", "size": 850, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/python_data_analysis/linear_algebra.py", "max_stars_repo_name": "qingkaikong/useful_script", "max_stars_repo_head_hexsha": "2547931dd11dbff7438e323ff4cd168427ff92ce", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-16T17:06:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T15:43:42.000Z", "max_issues_repo_path": "python/python_data_analysis/linear_algebra.py", "max_issues_repo_name": "qingkaikong/useful_script", "max_issues_repo_head_hexsha": "2547931dd11dbff7438e323ff4cd168427ff92ce", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/python_data_analysis/linear_algebra.py", "max_forks_repo_name": "qingkaikong/useful_script", "max_forks_repo_head_hexsha": "2547931dd11dbff7438e323ff4cd168427ff92ce", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-12-01T20:38:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-15T20:10:34.000Z", "avg_line_length": 25.0, "max_line_length": 53, "alphanum_fraction": 0.6576470588, "include": true, "reason": "import numpy", "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9814534376578004, "lm_q2_score": 0.868826784729373, "lm_q1q2_score": 0.8527130346018168}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass PolyFit:\n    def __init__(self, degree=1):\n        self.degree = degree\n        self.betas = np.ones(degree+1)\n\n    \n    def fit(self, x, y):\n        \"\"\"\n        Entradas:\n        x : array unidimensional de valores de x.\n        y : array unidimensiondal de valores de y.\n\n        Este codigo resuelve el siguiente sistema de ecuaciones\n        S * beta = Y, beta = S^{-1} * Y, \n        donde S es una matriz que tiene como vectotes a columnas de potencias de X.        \n        \"\"\"\n        m = self.degree\n    # matriz que guarda los vectores columna de potencias de x\n        S = np.zeros([len(x), m+1])\n        for i in range(m+1):\n            S[:,i] = x**i\n            \n    # Calculo la inversa de S.\n        S_inv = np.linalg.pinv(S)\n    \n    # calculo beta\n        self.betas = np.dot(S_inv, y)\n\n    def predict(self, x):\n        \"\"\"\n        Entradas:\n        x : array de entrada.\n\n\n        Salida:\n        y : array de salida\n        \"\"\"\n        y = np.zeros(len(x))\n        for i in range(len(self.betas)):\n            y +=  self.betas[i] * x**i\n        return y\n\n    def score(self, x, y):\n        \"\"\"\n        Calcula el root mean squared error\n        \n        Entradas:\n        x : array de entrada de valores de x.\n        y : array unidimensiondal de valores de y.\n        \"\"\"\n        y_predict  = self.predict(x)\n        return np.sqrt(np.mean((y_predict - y)**2))\n\n\n# cargo los datos para manipular\ndata = np.loadtxt(\"numeros_20.txt\")\n\n# divido en training y test\nx_train = data[:10,0]\nx_test = data[10:,0]\ny_train = data[:10,1]\ny_test = data[10:,1]\n\n# distintos valores de m para probar\nm_values = [0,1,3,9]\n\nplt.figure()\n\nfor i,m in enumerate(m_values):\n    modelo = PolyFit(degree=m)\n    modelo.fit(x_train, y_train)\n\n    plt.subplot(2,2,i+1)\n    #grafica del modelo\n    x_model = np.linspace(x_train.min(), x_train.max(), 100)\n    plt.plot(x_model, modelo.predict(x_model))\n    #grafica de los puntos\n    plt.scatter(x_train, y_train)\n    plt.xlabel(\"X\")\n    plt.ylabel(\"Y\")\n    plt.title(\"M={}\".format(m))\n\nplt.subplots_adjust(hspace=0.5)\nplt.savefig(\"polinomios.png\", bbox_inches='tight')\n\n\n#segunda figura con los errores\nerror_train = []\nerror_test = []\n\nfor m in range(10):\n    modelo = PolyFit(degree=m)\n    modelo.fit(x_train, y_train)\n    error_train.append(modelo.score(x_train, y_train))\n    error_test.append(modelo.score(x_test, y_test))\n\nplt.figure()\nplt.plot(np.array(range(10)), error_train, label='training')\nplt.plot(np.array(range(10)), error_test, label='test')\nplt.semilogy()\nplt.legend()\nplt.xlabel(\"M\")\nplt.ylabel(\"$E_{RMS}$\")\nplt.savefig(\"train_test_error.png\")\n", "meta": {"hexsha": "a29e50bdec345c0fa34d520b00a513f3aa823b16", "size": 2665, "ext": "py", "lang": "Python", "max_stars_repo_path": "IntroDataScience/ejercicios/02/ForeroJaime_Ejercicio02.py", "max_stars_repo_name": "aess14/Cursos-Uniandes", "max_stars_repo_head_hexsha": "be016b25f2f49788235fbe91ec577fd16b9ad613", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IntroDataScience/ejercicios/02/ForeroJaime_Ejercicio02.py", "max_issues_repo_name": "aess14/Cursos-Uniandes", "max_issues_repo_head_hexsha": "be016b25f2f49788235fbe91ec577fd16b9ad613", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IntroDataScience/ejercicios/02/ForeroJaime_Ejercicio02.py", "max_forks_repo_name": "aess14/Cursos-Uniandes", "max_forks_repo_head_hexsha": "be016b25f2f49788235fbe91ec577fd16b9ad613", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4495412844, "max_line_length": 91, "alphanum_fraction": 0.5977485929, "include": true, "reason": "import numpy", "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996141, "lm_q2_score": 0.9046505383142492, "lm_q1q2_score": 0.8526392126980289}}
{"text": "''' mbinary\n#########################################################################\n# File : iteration.py\n# Author: mbinary\n# Mail: zhuheqin1@gmail.com\n# Blog: https://mbinary.xyz\n# Github: https://github.com/mbinary\n# Created Time: 2018-10-02  21:14\n# Description:\n#########################################################################\n'''\n\nimport sympy\nimport numpy as np\nfrom math import sqrt\n\n\ndef newton(y:sympy.core,x0:float,epsilon:float=0.00001,maxtime:int=50) ->(list,list):\n    '''\n        newton 's iteration method for finding a zeropoint of a func\n        y is the func, x0 is the init x val: int float epsilon is the accurrency\n    '''\n    if epsilon <0:epsilon = -epsilon\n    ct =0\n    t =  y.free_symbols\n    varsymbol = 'x' if len(t)==0 else t.pop()\n    x0= float(x0)\n    y_diff = y.diff()\n    li = [x0]\n    vals = []\n    while 1:\n        val = y.subs(varsymbol,x0)\n        vals.append(val)\n        x = x0- val/y_diff.subs(varsymbol,x0)\n        li.append(x)\n        ct+=1\n        if ct>maxtime:\n            print(\"after iteration for {} times, I still havn't reach the accurrency.\\\n                    Maybe this function havsn't zeropoint\\n\".format(ct))\n            return li ,val\n        if abs(x-x0)<epsilon:return li,vals\n        x0 = x\n        \n\ndef secant(y:sympy.core,x0:float,x1:float,epsilon:float =0.00001,maxtime:int=50) ->(list,list):\n    '''\n        弦截法, 使用newton 差商计算,每次只需计算一次f(x)\n        secant method for finding a zeropoint of a func\n        y is the func , x0 is the init x val,     epsilon is the accurrency\n    '''\n    if epsilon <0:epsilon = -epsilon\n    ct =0\n    x0,x1 = float(x0),float(x1)\n    li = [x0,x1]\n    t =  y.free_symbols\n    varsymbol = 'x' if len(t)==0 else t.pop()\n    last = y.subs(varsymbol,x0)\n    vals = [last]\n    while 1:\n        cur = y.subs(varsymbol,x1)\n        vals.append(cur)\n        x = x1-cur*(x1-x0)/(cur-last)\n        x0 ,x1= x1,x\n        last = cur\n        li.append(x)\n        ct+=1\n        if ct>maxtime:\n            print(\"after iteration for {} times, I still havn't reach the accurrency.\\\n                    Maybe this function havsn't zeropoint\\n\".format(ct))\n            return li,vals\n        if abs(x0-x1)<epsilon:return li,vals\n        x0 = x\n\n\ndef solveNonlinearEquations(funcs:[sympy.core],init_dic:dict,epsilon:float=0.001,maxtime:int=50)->dict:\n    '''solve  nonlinear equations:'''\n    li = list(init_dic.keys())\n    delta = {i:0 for i in li}\n    ct = 0\n    while 1:\n        ys = np.array([f.subs(init_dic) for f in funcs],dtype = 'float')\n        mat = np.matrix([[i.diff(x).subs(init_dic) for x in li] for i in funcs ],dtype = 'float')\n        delt = np.linalg.solve(mat,-ys)\n        for i,j in enumerate(delt):\n            init_dic[li[i]] +=j\n            delta[li[i]] = j\n        if ct>maxtime:\n            print(\"after iteration for {} times, I still havn't reach the accurrency.\\\n                    Maybe this function havsn't zeropoint\\n\".format(ct))\n            return init_dic\n        if sqrt(sum(i**2 for i in delta.values()))<epsilon:return init_dic\n\n\nif __name__ =='__main__':\n    x,y,z = sympy.symbols('x y z')\n    \n    res,res2= newton(x**5-9,2,0.01)\n    print(res,res2)\n\n\n    res,res2 = secant (x**3-3*x-2,1,3,1e-3)\n    print(res,res2)\n\n\n    funcs=[x**2+y**2-1,x**3-y]\n    init = {x:0.8,y:0.6}\n    res_dic = solveNonlinearEquations(funcs,init,0.001)\n    print(res_dic)\n", "meta": {"hexsha": "f21ed3a61e1bffb75ab55bb5533109ff9b97e37e", "size": 3375, "ext": "py", "lang": "Python", "max_stars_repo_path": "math/numericalAnalysis/iteration.py", "max_stars_repo_name": "snowflying/algorithm-in-python", "max_stars_repo_head_hexsha": "d92e211119b8a786807942c2765058e522e37769", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-14T06:15:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-14T06:15:29.000Z", "max_issues_repo_path": "math/numericalAnalysis/iteration.py", "max_issues_repo_name": "snowflying/algorithm-in-python", "max_issues_repo_head_hexsha": "d92e211119b8a786807942c2765058e522e37769", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/numericalAnalysis/iteration.py", "max_forks_repo_name": "snowflying/algorithm-in-python", "max_forks_repo_head_hexsha": "d92e211119b8a786807942c2765058e522e37769", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-22T00:32:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T00:32:56.000Z", "avg_line_length": 30.9633027523, "max_line_length": 103, "alphanum_fraction": 0.5525925926, "include": true, "reason": "import numpy,import sympy", "num_tokens": 1019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.9046505261034854, "lm_q1q2_score": 0.852639201189302}}
{"text": "\nimport numpy as np\n\nfrom numericalmethods.exceptions import InadequateArgsCombination\n\n\ndef newton_horner(x, x_points: np.ndarray, y_points: np.ndarray = None, coeffs: np.ndarray = None) -> np.ndarray:\n    \"\"\" Evaluates the polynomial returned by Horner's algorithm.\n\n    The user must give `y_points` or `coeffs`. If `coeffs` is not given this method will compute them with `x_points` and `y_points`.\n\n    Args:\n        x(float): The point where to evaluate the polynomial.\n        x(np.ndarray): `x` coordinates of the points.\n        y(np.ndarray): `y` coordinates of the points. Defaults to None.\n        coeffs(np.ndarray): coefficients of the polynomial. Defaults to None.\n\n    Raises:\n        InadequateArgsCombination: If the combination  of arguments is not valid.\n        ValueError: If `x` and `y` are not of the same length.\n\n    Returns:\n        float: the polynomial evaluated at x.\n\n    \"\"\"\n    if y_points is None and coeffs is None:\n        raise InadequateArgsCombination('Cannot evaluate Newton\\'s polynomial with the combination of arguments given. Check the valid combinations.')\n\n    if y_points is not None:\n        if len(x_points) != len(y_points):\n            raise ValueError('`x_points` and `y_points` must be the same length.')\n\n    coeffs_ = coeffs if coeffs is not None else horner_algorithm(x_points, y_points)\n\n    N = len(x_points) - 1\n    polynom = coeffs_[N]\n\n    for k in range(1, N+1):\n        polynom = coeffs_[N-k] + (x - x_points[N-k])*polynom\n\n    return polynom\n\n\ndef horner_algorithm(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n    \"\"\" Computes Newton interpolation polynomial by Horner's algorithm for some given coordinates.\n\n    `x` and `y` must have the same length.\n\n    Args:\n        x(np.ndarray): x coordinates of the points.\n        y(np.ndarray): y coordinates of the points.\n\n    Raises:\n        ValueError: If `x` and `y` are not of the same length.\n\n    Returns:\n        np.ndarray: Polynomial coefficients of the Newton interpolation.\n\n    \"\"\"\n    if len(x) != len(y):\n        raise ValueError('x and y must be the same length.')\n\n    LEN = len(y)\n    matrix = np.zeros((LEN, LEN))\n\n    for j in range(LEN):\n        if j == 0:\n            matrix[:, 1] = y\n\n        for i in range(LEN-j):\n            matrix[i, j] = (matrix[i+1, j] - matrix[i, j]) / (x[i+1] - x[i])\n\n    return matrix[0]\n", "meta": {"hexsha": "90218e1833e79c7b394c7db2d728310450eafa42", "size": 2347, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/numericalmethods/interpolate.py", "max_stars_repo_name": "LuisGMM/CharliePY", "max_stars_repo_head_hexsha": "04962644d43ee4f2839f0c2cab65aeb573fb8763", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/numericalmethods/interpolate.py", "max_issues_repo_name": "LuisGMM/CharliePY", "max_issues_repo_head_hexsha": "04962644d43ee4f2839f0c2cab65aeb573fb8763", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/numericalmethods/interpolate.py", "max_forks_repo_name": "LuisGMM/CharliePY", "max_forks_repo_head_hexsha": "04962644d43ee4f2839f0c2cab65aeb573fb8763", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7162162162, "max_line_length": 150, "alphanum_fraction": 0.6467831274, "include": true, "reason": "import numpy", "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067163548471, "lm_q2_score": 0.9046505299595162, "lm_q1q2_score": 0.8526392004408159}}
{"text": "import numpy as np\nimport math\n\ndef f(mu, sigma2, x):\n    return 1/np.sqrt(2 * np.pi * sigma2) * np.exp(-0.5 * np.square(x-mu) / sigma2)\n\nprint(f(10., 4., 8.))\nprint(f(10., 4., 10.)) # f(x) is max when mu and x are same, maximizing the gaussian\n", "meta": {"hexsha": "8b69d5d9b7aa49e81ff85749c0d6838fbe3513c9", "size": 245, "ext": "py", "lang": "Python", "max_stars_repo_path": "lessons/max_gaussian.py", "max_stars_repo_name": "shivprakashy/udacity-ExtendedKalmanFilters", "max_stars_repo_head_hexsha": "ec340845f9298982786e2aebc5bb117f9e4381c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lessons/max_gaussian.py", "max_issues_repo_name": "shivprakashy/udacity-ExtendedKalmanFilters", "max_issues_repo_head_hexsha": "ec340845f9298982786e2aebc5bb117f9e4381c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lessons/max_gaussian.py", "max_forks_repo_name": "shivprakashy/udacity-ExtendedKalmanFilters", "max_forks_repo_head_hexsha": "ec340845f9298982786e2aebc5bb117f9e4381c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2222222222, "max_line_length": 84, "alphanum_fraction": 0.6204081633, "include": true, "reason": "import numpy", "num_tokens": 92, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9833429614552197, "lm_q2_score": 0.8670357598021707, "lm_q1q2_score": 0.8525935117314432}}
{"text": "#!/usr/bin/env python3\nimport math\nimport copy\nfrom decimal import *\nfrom itertools import product\nimport numpy as np\n\n# CHANGEME:\nTP=150\nTN=300\nFP=50\nFN=0\n\ntot = TP+TN+FP+FN\n\nprint(f\"N={tot}\")\n\nprobtab = np.array([[TN/tot,FN/tot],[FP/tot,TP/tot]]).astype(Decimal)\n\nprint(\"The marginal probabilities of all the values of 𝑋\")\n\nrow_labels = [\"N\", \"A\"];\npx = np.sum(probtab, axis=0)\npy = np.sum(probtab, axis=1)\nprint(\"     N    A     P(y)\")\nfor row_label, row in zip(row_labels, probtab):\n  print('%s  [%s]' % (row_label, ' '.join('%04s' % i for i in row)), end=\" \")\n  print(f\"- {np.sum(row, axis=0):.2f}\")\n\nprint(\"p(x) \" + ' '.join(f\"{i:.2f}\" for i in px))\n\nprint(\"- \" * 10)\n\n# sum of all columns and rows must be one\nassert sum(px) == 1\nassert sum(py) == 1\n\nprint(\"Entropy of the input\")\nprint(\"𝐻(𝑋)=−∑𝑃(𝑥)log2𝑃(𝑥)\")\nhx = -sum([i * math.log2(i) for i in px])\nprint(\"-(\", end=\"\")\nfor i in px:\n  print(f\"{i:.3f}*log2({i:.3f})\", end=\" + \")\nprint(f\") = {hx:.3f}\")\nprint(\"- \" * 10)\n\n\nprint(\"The joint probabilities:\")\nprint(\"P(X|Y)=𝑃(𝑥,𝑦)/𝑃(𝑦)\")\nfor k, i in zip(py, probtab):\n  for j in i:\n    if j:\n      print(f\"({j}/{k:.3f})={(j/k):.2f}\")\nprint(\"- \" * 10)\n\nprint(\"The conditional entropy 𝐻(𝑋|𝑌)\")\nprint(\"𝐻(𝑋|𝑌)=−∑y∑x𝑃(𝑥,𝑦)log2𝑃(𝑥|𝑦)\")\nhxy = 0\nprint(\"-(\", end=\"\")\nfor k, i in zip(py, probtab):\n  for j in i:\n    if j:\n      hxy += (j * math.log2(j / k))\n      print(f\"{j}*log2({(j/k):.2f})\", end=\" + \")\nhxy = -hxy\nprint(f\") = {hxy:.3f} \")\nprint(\"- \" * 10)\n\nprint(\"The intrusion detection capability:\")\nprint(\"C_I_D=(𝐻(𝑋)−𝐻(𝑋|𝑌)) / 𝐻(𝑋)\")\ncid = ((hx - hxy)/hx)\nprint(f\"({hx:.3f} - {hxy:.3f})/{hx:.3f} = {cid:.3f}\")\n\nprint(\"\\n##### Abstract IDS models ####\\n\")\npx_ol = copy.copy(px)\nprobtab = np.array([[TN/tot,0],[FP/tot,FN/tot],[0,TP/tot]]).astype(Decimal)\nprint(\"The marginal probabilities of all the values of 𝑋\")\nrow_labels = [\"N\", \"U\", \"A\"];\npx = np.sum(probtab, axis=0)\npz = np.sum(probtab, axis=1)\nprint(\"     N    A     P(z)\")\nfor row_label, row in zip(row_labels, probtab):\n  print('%s  [%s]' % (row_label, ' '.join('%04s' % i for i in row)), end=\" \")\n  print(f\"- {np.sum(row, axis=0):.2f}\")\n\nprint(\"p(x) \" + ' '.join(f\"{i:.2f}\" for i in px))\nprint(\"- \" * 10)\n\n# sum of all columns and rows must be one\nassert sum(px) == 1\nassert sum(pz) == 1\n\nif set(px_ol) == set(px):\n  print(\"Entropy of the input is still the same as above\")\n  print(f\"recall, H(𝑋)=−∑𝑃(𝑥)log2𝑃(𝑥) = {hx:.3f}\")\n  print(\"- \" * 10)\nelse:\n  print(\"Entropy of the input\")\n  print(\"𝐻(𝑋)=−∑𝑃(𝑥)log2𝑃(𝑥)\")\n  hx = -sum([i * math.log2(i) for i in px])\n  print(\"-(\", end=\"\")\n  for i in px:\n    print(f\"{i:.3f}*log2({i:.3f})\", end=\" + \")\n  print(f\") = {hx:.3f}\")\n  print(\"- \" * 10)\n\nprint(\"The joint probabilities:\")\nprint(\"𝑃(𝑥,𝑦)/𝑃(𝑦)=P(X|Y)\")\nfor k, i in zip(pz, probtab):\n  for j in i:\n    if j:\n      print(f\"({j}/{k:.3f})={(j/k):.2f}\")\nprint(\"- \" * 10)\n\nprint(\"The conditional entropy 𝐻(𝑋|𝑌)\")\nprint(\"𝐻(𝑋|𝑌)=−∑y∑x𝑃(𝑥,𝑦)log2𝑃(𝑥|𝑦)\")\nhxy = 0\nprint(\"-(\", end=\"\")\nfor k, i in zip(pz, probtab):\n  for j in i:\n    if j:\n      hxy += (j * math.log2(j / k))\n      print(f\"{j}*log2({(j/k):.2f})\", end=\" + \")\nhxy = -hxy\nprint(f\") = {hxy:.3f} \")\nprint(\"- \" * 10)\n\nprint(\"The feature representation capability:\")\nprint(\"C_r=(𝐻(𝑋)−𝐻(𝑋|𝑌)) / 𝐻(𝑋)\")\n\ncr = ((hx - hxy)/hx)\nprint(f\"({hx:.3f} - {hxy:.3f})/{hx:.3f} = {cr:.3f}\")\n\nprint(\"- \" * 10)\n\nprint(\"The classification information loss:\")\nprint(f\"L_c = C_r - C_I_D = {cr:.3f} - {cid:.3f} = {(cr-cid):.3f}\")\n\n", "meta": {"hexsha": "f57f28b23f27dac1336f759dc5c1c2f1ce7fd00e", "size": 3412, "ext": "py", "lang": "Python", "max_stars_repo_path": "04_testing-IDS_abstract-models/cid-cr-lc.py", "max_stars_repo_name": "StoneSwine/IMT4204-IDS_software", "max_stars_repo_head_hexsha": "f6a39d88fd44b71134408197da9dd27b872bd550", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "04_testing-IDS_abstract-models/cid-cr-lc.py", "max_issues_repo_name": "StoneSwine/IMT4204-IDS_software", "max_issues_repo_head_hexsha": "f6a39d88fd44b71134408197da9dd27b872bd550", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "04_testing-IDS_abstract-models/cid-cr-lc.py", "max_forks_repo_name": "StoneSwine/IMT4204-IDS_software", "max_forks_repo_head_hexsha": "f6a39d88fd44b71134408197da9dd27b872bd550", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5467625899, "max_line_length": 77, "alphanum_fraction": 0.5518757327, "include": true, "reason": "import numpy", "num_tokens": 1467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854146791213, "lm_q2_score": 0.8791467738423873, "lm_q1q2_score": 0.8525837186345512}}
{"text": "import matplotlib\r\nmatplotlib.use('TkAgg')\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.widgets import Slider, Button, RadioButtons\r\n\r\n# initial center location\r\nx_cent = 0\r\ny_cent = 0\r\n\r\n# definition of the circle parameters\r\ncenter = np.array([x_cent,y_cent])\r\nradius1 = np.sqrt((center[0]-1)**2+(center[1]-0)**2)\r\nradius2 = np.sqrt((center[0]+1)**2+(center[1]-0)**2)\r\n\r\n# calculation of the circle coordinates \r\nangle = np.linspace(0,2*np.pi,720)\r\nchi1 = center[0] + radius1*np.cos(angle)\r\neta1 = center[1] + radius1*np.sin(angle)\r\nchi2 = center[0] + radius2*np.cos(angle)\r\neta2 = center[1] + radius2*np.sin(angle)\r\n\r\n# calculations of the Joukowsky transform\r\nx1 = ((chi1)*(chi1**2+eta1**2+1))/(chi1**2+eta1**2)\r\ny1 = ((eta1)*(chi1**2+eta1**2-1))/(chi1**2+eta1**2)\r\nx2 = ((chi2)*(chi2**2+eta2**2+1))/(chi2**2+eta2**2)\r\ny2 = ((eta2)*(chi2**2+eta2**2-1))/(chi2**2+eta2**2)\r\n\t\r\n# initial figure definition\r\nfig, ax = plt.subplots(figsize=(6,6))\r\nplt.subplots_adjust(bottom=0.25)\r\n\r\n# zeta plane\r\nplt.subplot(1, 2, 1)\r\nl, = plt.plot(chi1,eta1,'g',label='Circle1')\r\nm, = plt.plot(chi2,eta2,'b',label='Circle2')\r\np, = plt.plot([center[0],center[0]],[center[1],center[1]],'w',marker='x',mec='k',markersize=10,label='Center')\r\nplt.scatter([-1,1],[0,0],c=['r','r'],s=100,marker='h',label='Reference Points')\r\nplt.axis('equal')\r\nplt.xlim([-3,3])\r\nplt.grid(True)\r\nplt.xlabel(r\"$\\chi$\",size=14)\r\nplt.ylabel(r\"$\\eta$\",size=14)\r\nplt.legend(loc='lower center', bbox_to_anchor=(0.12, 0.1))\r\n\r\n# z plane: airfoil 1\r\nplt.subplot(2, 2, 2)\r\nplt.axis('equal')\r\nn, = plt.plot(x1,y1,'g',label='Transform1')\r\n\r\n# z plane: airfoil 2\r\nplt.subplot(2, 2, 4)\r\nplt.axis('equal')\r\no, = plt.plot(x2,y2,'b',label='Transform2')\r\n\r\n# current value of the sliders\r\nx0 = 0\r\ny0 = 0\r\n\r\n# position of the sliders\r\naxx = plt.axes([0.18, 0.15, 0.65, 0.025], facecolor='white')\r\naxy = plt.axes([0.18, 0.1, 0.65, 0.025], facecolor='white')\r\n\r\n# slider assignation\r\nsx = Slider(axx, r\"$\\mu_x$\", -1, 1, valinit=x0)\r\nsy = Slider(axy, r\"$\\mu_y$\", -1, 1, valinit=y0)\r\n\r\n# updating the figure\r\ndef update(val):\r\n\tx_cent = sx.val\r\n\ty_cent = sy.val\r\n\t\r\n\t# redefinition of the circle parameters \r\n\tcenter = np.array([x_cent,y_cent])\r\n\tradius1 = np.sqrt((center[0]-1)**2+(center[1]-0)**2)\r\n\tradius2 = np.sqrt((center[0]+1)**2+(center[1]-0)**2)\r\n\t\r\n\t# calculate again the circle coordinates \r\n\tangle = np.linspace(0,2*np.pi,720)\r\n\tchi1 = center[0] + radius1*np.cos(angle)\r\n\teta1 = center[1] + radius1*np.sin(angle)\r\n\tchi2 = center[0] + radius2*np.cos(angle)\r\n\teta2 = center[1] + radius2*np.sin(angle)\r\n\r\n\t# calculate again Joukowsky transform\r\n\tx1 = ((chi1)*(chi1**2+eta1**2+1))/(chi1**2+eta1**2)\r\n\ty1 = ((eta1)*(chi1**2+eta1**2-1))/(chi1**2+eta1**2)\r\n\tx2 = ((chi2)*(chi2**2+eta2**2+1))/(chi2**2+eta2**2)\r\n\ty2 = ((eta2)*(chi2**2+eta2**2-1))/(chi2**2+eta2**2)\r\n\t\r\n\t# update with circle 1\r\n\tl.set_xdata(chi1)\r\n\tl.set_ydata(eta1)\r\n\r\n\t# update with circle 2\r\n\tm.set_xdata(chi2)\r\n\tm.set_ydata(eta2)\r\n\t\r\n\t# update with airfoil 1\r\n\tn.set_xdata(x1)\r\n\tn.set_ydata(y1)\r\n\t\r\n\t# update with airfoil 2\r\n\to.set_xdata(x2)\r\n\to.set_ydata(y2)\r\n\r\n\t# update the value of the center of the circles\r\n\tp.set_xdata([x_cent,x_cent])\r\n\tp.set_ydata([y_cent,y_cent])\r\n\t\r\n\t# draw the selected updates\r\n\tfig.canvas.draw_idle()\r\n\r\n# call the sliders\r\nsx.on_changed(update)\r\nsy.on_changed(update)\r\n\r\n# show the figure \r\nplt.show()", "meta": {"hexsha": "ecbc7c146989155880df825854400810b4fe43e6", "size": 3371, "ext": "py", "lang": "Python", "max_stars_repo_path": "airfoil-parametrization/joukowsky/joukowsky_fixedR.py", "max_stars_repo_name": "jlobatop/GA-CFD-MO", "max_stars_repo_head_hexsha": "db03301a2ba3be48e89802a4c36b4834677493cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2018-07-19T20:29:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T18:37:21.000Z", "max_issues_repo_path": "airfoil-parametrization/joukowsky/joukowsky_fixedR.py", "max_issues_repo_name": "aakash30jan/GA-CFD-MO", "max_issues_repo_head_hexsha": "db03301a2ba3be48e89802a4c36b4834677493cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "airfoil-parametrization/joukowsky/joukowsky_fixedR.py", "max_forks_repo_name": "aakash30jan/GA-CFD-MO", "max_forks_repo_head_hexsha": "db03301a2ba3be48e89802a4c36b4834677493cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2018-08-28T08:32:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T08:02:57.000Z", "avg_line_length": 28.3277310924, "max_line_length": 111, "alphanum_fraction": 0.6383862355, "include": true, "reason": "import numpy", "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854155523791, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.8525837178668947}}
{"text": "from math import cos, sin, pi\nimport numpy as np\nfrom numpy.linalg import inv\n\ndef sph_to_cart(epsilon, alpha, r):\n    \"\"\"\n    Transform sensor readings to Cartesian coordinates in the sensor\n    frame. The values of epsilon and alpha are given in radians, while \n    r is in metres. Epsilon is the elevation angle and alpha is the\n    azimuth angle (i.e., in the x,y plane).\n    \"\"\"\n\n    p = np.zeros(3)  # Position vector \n\n    # Your code here\n    p[0] = r * cos(alpha) * cos(epsilon)\n    p[1] = r * sin(alpha) * cos(epsilon)\n    p[2] = r * sin(epsilon)\n\n    return p\n\ndef estimate_params(P):\n    \"\"\"\n    Estimate parameters from sensor readings in the Cartesian frame.\n    Each row in the P matrix contains a single 3D point measurement;\n    the matrix P has size n x 3 (for n points). The format is:\n  \n    P = [[x1, y1, z1],\n         [x2, x2, z2], ...]\n       \n    where all coordinate values are in metres. Three parameters are\n    required to fit the plane, a, b, and c, according to the equation\n    \n    z = a + bx + cy\n    \n    The function should retrn the parameters as a NumPy array of size\n    three, in the order [a, b, c].\n    \"\"\"\n\n    param_est = np.zeros(3)\n    A = np.ones_like(P)\n    b = np.zeros((P.shape[0], 1))\n\n      # Your code here\n    for i, meas in enumerate(P):\n      A[i, 1], A[i, 2], b[i] = meas\n\n    params = inv(A.T @ A) @ A.T @ b\n    param_est[0] = params[0, 0]\n    param_est[1] = params[1, 0]\n    param_est[2] = params[2, 0]\n\n    return param_est\n\nmeas = np.array([[pi/3, 0, 5],\n                 [pi/4, pi/4, 7],\n                 [pi/6, pi/2, 4],\n                 [pi/5, 3*pi/4, 6],\n                 [pi/8, pi, 3]])\nP = np.array([sph_to_cart(*row) for row in meas])\nprint(estimate_params(P))\n", "meta": {"hexsha": "2f2bce9be627c6fb73caf07bd63663ddfada0d67", "size": 1728, "ext": "py", "lang": "Python", "max_stars_repo_path": "Course 2 - State Estimation and Localization/Module 4: LIDAR Sensing/m4q2.py", "max_stars_repo_name": "smitshah99/Self-Driving-Car-Specialization", "max_stars_repo_head_hexsha": "4a5ea1c3323a3b5aad4c7ad7f24862b7c5e025cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-04-27T18:47:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-27T18:48:01.000Z", "max_issues_repo_path": "Course 2 - State Estimation and Localization/Module 4: LIDAR Sensing/m4q2.py", "max_issues_repo_name": "smitshah99/Self-Driving-Car-Specialization", "max_issues_repo_head_hexsha": "4a5ea1c3323a3b5aad4c7ad7f24862b7c5e025cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-05-04T13:44:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-21T16:08:31.000Z", "max_forks_repo_path": "Course 2 - State Estimation and Localization/Module 4: LIDAR Sensing/m4q2.py", "max_forks_repo_name": "smitshah99/Self-Driving-Car-Specialization", "max_forks_repo_head_hexsha": "4a5ea1c3323a3b5aad4c7ad7f24862b7c5e025cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8709677419, "max_line_length": 71, "alphanum_fraction": 0.5804398148, "include": true, "reason": "import numpy,from numpy", "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854120593483, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.8525837132606296}}
{"text": "#Natural Computing with Python\n#Chapter 1 - Neural Networks\n#Perceptron logic gates\n\nimport numpy as np\n\n#Define the AND logic gate\ndef And(x1, x2):\n    x = np.array([1, x1, x2])\n    w = np.array([-1.5, 1, 1])\n    y = np.sum(w*x)\n    if y <= 0:\n        return 0\n    else:\n        return 1\n\n#Define the OR logic gate\ndef Or(x1, x2):\n    x = np.array([1, x1, x2])\n    w = np.array([-0.5, 1, 1])\n    y = np.sum(w*x)\n    if y <= 0:\n        return 0\n    else:\n        return 1\n    \n#Define the NAND logic gate\ndef Nand(x1, x2):\n    x = np.array([1, x1, x2])\n    w = np.array([1.5, -1, -1])\n    y = np.sum(w*x)\n    if y <= 0:\n        return 0\n    else:\n        return 1\n\n#MAIN function\nif __name__ == '__main__':\n\n    #input array\n    input = [(0, 0), (1, 0), (0, 1), (1, 1)]\n\n    #start evaluation\n    print(\"AND\")\n    for x in input:\n        y = And(x[0], x[1])\n        print(str(x) + \" -> \" + str(y))\n\n    print(\"OR\")\n    for x in input:\n        y = Or(x[0], x[1])\n        print(str(x) + \" -> \" + str(y))\n\n    print(\"NAND\")\n    for x in input:\n        y = Nand(x[0], x[1])\n        print(str(x) + \" -> \" + str(y))\n", "meta": {"hexsha": "4196d0248c0f67469c7ebbb395e332af845f04a9", "size": 1110, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter_01/perceptron_logic_gates.py", "max_stars_repo_name": "bpbpublications/Natural-Computing-with--Python", "max_stars_repo_head_hexsha": "6338976b5d3edef026d9387d005d246b6160b508", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter_01/perceptron_logic_gates.py", "max_issues_repo_name": "bpbpublications/Natural-Computing-with--Python", "max_issues_repo_head_hexsha": "6338976b5d3edef026d9387d005d246b6160b508", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter_01/perceptron_logic_gates.py", "max_forks_repo_name": "bpbpublications/Natural-Computing-with--Python", "max_forks_repo_head_hexsha": "6338976b5d3edef026d9387d005d246b6160b508", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1379310345, "max_line_length": 44, "alphanum_fraction": 0.4765765766, "include": true, "reason": "import numpy", "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854111860906, "lm_q2_score": 0.8791467659263148, "lm_q1q2_score": 0.852583707886773}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as st\n\ndata = np.loadtxt(\"dataset.txt\")\n\"\"\"\ndef get_variance(x):\n    mean = np.mean(x)\n    sum = 0\n    for i in x:\n        sum += (i-mean)**2\n    return sum / (len(x)-1)\n\nprint(get_variance([1,2,5,3,4,5,2,4]))\n\"\"\"\n\nvariance = np.var(data,ddof=1)  #ddof = delta degree of freedom\nprint(\"Variance\")\nprint(variance)\nprint()\nprint()\n#STANDARD DEVIATION - square root of variance\n\nstd = np.std(data)\nprint(\"Standard dev\\t\\t Variance\")\nprint(std,\"\\t\",std**2)\nprint()\nprint()\n\n#GAUSSIAN APPROXIMATION\n\nxs = np.linspace(data.min(),data.max(),100)\nys = st.norm.pdf(xs,loc=np.mean(data),scale=std)\n\nplt.hist(data,bins=50,density=True,histtype=\"step\",label=\"Data\")\nplt.plot(xs,ys,label=\"Normal approximation\")\nplt.legend()\nplt.ylabel(\"Probability\")\nplt.show()\nprint()\nprint()\n#With variance and std we can recontruct the data almost\n\n\n#Skewness - 3rd Moment\n#1st - zero, 2nd - Variance, 3rd - Skewness\n#cubic distance from mean\n\"\"\"\ndef get_skew(xs):\n    mean = np.mean(xs)\n    var = np.var(xs)\n    sum = 0\n    for x in xs:\n        sum += (x-mean)**3\n    return (sum / (len(xs))) / (var ** 1.5)\nprint(get_skew([1,10,4,3]))\n\"\"\"\n\nskewness = st.skew(data)\nprint(\"Skewness\")\nprint(skewness)\n\n#update Gaussian approximation to include skewness\nxs = np.linspace(data.min(),data.max(),100)\nys = st.norm.pdf(xs,loc=np.mean(data),scale=std)\nys1 = st.skewnorm.pdf(xs,skewness,loc=np.mean(data),scale=std)\nplt.hist(data,bins=50,density=True,histtype=\"step\",label=\"Data\")\nplt.plot(xs,ys,label=\"Normal approximation\")\nplt.plot(xs,ys1,label=\"Skewnormal approximation\")\nplt.legend()\nplt.ylabel(\"Probability\")\nplt.show()\nprint()\nprint()\n\n#not a good approx because mean is changed, so change and fit the data\n\nxs = np.linspace(data.min(),data.max(),100)\nys = st.norm.pdf(xs,loc=np.mean(data),scale=std)\nps = st.skewnorm.fit(data) #fitting the data (mean and std dev. by scipy)\nys1 = st.skewnorm.pdf(xs,*ps) #passing the fitted data\n\nplt.hist(data,bins=50,density=True,histtype=\"step\",label=\"Data\")\nplt.plot(xs,ys,label=\"Normal approximation\")\nplt.plot(xs,ys1,label=\"Skewnormal approximation\")\nplt.legend()\nplt.ylabel(\"Probability\")\nplt.show()\nprint()\nprint()\n\n\n#KURTOSIS - same to skewness just the difference of mean to 4th power\n\"\"\"\ndef get_k(xs):\n    mean = np.mean(xs)\n    var = np.var(xs)\n    sum = 0\n    for x in xs:\n        sum += (x-mean)**4\n    return (sum / (len(xs))) / (var ** 2)\nprint(get_k([1,10,4,3]))\n\"\"\"\n\nkurtosis = st.kurtosis(data,fisher=False)\nprint(\"Kurtosis\")\nprint(kurtosis)\nprint()\nprint()\n#you won't get same results here from the function and st.kurtosis(), you have\n#to pass fisher=False which is normalisation of kurtosis\n\n#Problem while approximation is that data is Bi-Modal distribution and no\n#moment will take this into account\n\n\n#PERCENTILE\n\nps = np.linspace(0,100,10)\nx_per = np.percentile(data,ps)\n\nxs = np.sort(data)\nys = np.linspace(0 ,1 ,len(data))\n\nplt.plot(xs, ys * 100, label=\"ECDF\")\nplt.plot(x_per,ps,label=\"Percentile\",marker=\".\",ms=10)\nplt.legend()\nplt.ylabel(\"Percentile\")\nplt.show()\n# Green - Emperical CDF\n# Yellow - 10 percentile for numpy to calculate\n# Difference in tails in curve because the data is linearly sampled.\n# Data seems to be Gaussian because of it's tails.\n# Loss of data at tails can be seen\nps = 100 * st.norm.cdf(np.linspace(-3,3,30))\nx_per = np.percentile(data,ps)\n\nxs = np.sort(data)\nys = np.linspace(0 ,1 ,len(data))\n\nplt.plot(xs, ys * 100, label=\"ECDF\")\nplt.plot(x_per,ps,label=\"Percentile\",marker=\".\",ms=10)\nplt.legend()\nplt.ylabel(\"Percentile\")\nplt.show()\n#not much effort wasted at the tail part but to take tail to account,\n#add an insert value to ps\nps = 100 * st.norm.cdf(np.linspace(-3,3,30))\nps = np.insert(ps,0,0)\nps = np.insert(ps,-1,100)\nx_per = np.percentile(data,ps)\n\nxs = np.sort(data)\nys = np.linspace(0 ,1 ,len(data))\n\nplt.plot(xs, ys * 100, label=\"ECDF\")\nplt.plot(x_per,ps,label=\"Percentile\",marker=\".\",ms=10)\nplt.legend()\nplt.ylabel(\"Percentile\")\nplt.show()\n#Tails covered in percentile\n", "meta": {"hexsha": "0743f3ef4f976092425b1492ddb8c256eb5f16ff", "size": 4019, "ext": "py", "lang": "Python", "max_stars_repo_path": "variation_ec.py", "max_stars_repo_name": "WestHamster/Feature_engg", "max_stars_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "variation_ec.py", "max_issues_repo_name": "WestHamster/Feature_engg", "max_issues_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "variation_ec.py", "max_forks_repo_name": "WestHamster/Feature_engg", "max_forks_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8086419753, "max_line_length": 78, "alphanum_fraction": 0.6894749938, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854111860905, "lm_q2_score": 0.8791467659263148, "lm_q1q2_score": 0.8525837078867728}}
{"text": "import numpy as np\n\n\ndef print_all():\n    \n    print(\"------------------------------------------\")\n    print(\"[START] - DOT PRODUCT BETWEEN TWO MATRICES\")\n    print(\"------------------------------------------\")\n\n    # Create matrices\n    x = np.array([[10, 20], [100, -10]])\n    y = np.array([[5, 10], [-50, 10]])\n\n    print(\"\\nPerforming Matrix Multiplication (dot product) on matrices\\n-------------\\n\")\n\n    print(f\"Matrices: \\n-------\\n  x = \\n{x} \\n\\n y = \\n{y}\\n\\n-------\\n\")\n\n    print(\"Recall that ELEMENT WISE multiplication resulted in:\\n-------\\n\")\n\n    print(f\"Multiplication of x * y: \\n-------\\nnp.multiply(x,y):\\n{np.multiply(x,y)}\\n\\n-------\\n\\n\")\n\n    print(\"Whereas the dot product results in...\\n\")\n\n    print(f\"The dot product of x and y:\\n-------\\nnp.dot(x,y):\\n{np.dot(x,y)}\\n\\n-------\\n\")\n\n    print(\"-------------------------------------------\")\n    print(\"[FINISH] - DOT PRODUCT BETWEEN TWO MATRICES\")\n    print(\"-------------------------------------------\")\n\n", "meta": {"hexsha": "412232e82fda9c4596ecd2bc024c9e9a8e01ade3", "size": 985, "ext": "py", "lang": "Python", "max_stars_repo_path": "topics/Matrix_Operations/dot_product.py", "max_stars_repo_name": "stoltzmaniac/DL4CV", "max_stars_repo_head_hexsha": "c7e8d75fcad3bcea9ace7a846811e100e6fad624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "topics/Matrix_Operations/dot_product.py", "max_issues_repo_name": "stoltzmaniac/DL4CV", "max_issues_repo_head_hexsha": "c7e8d75fcad3bcea9ace7a846811e100e6fad624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "topics/Matrix_Operations/dot_product.py", "max_forks_repo_name": "stoltzmaniac/DL4CV", "max_forks_repo_head_hexsha": "c7e8d75fcad3bcea9ace7a846811e100e6fad624", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8333333333, "max_line_length": 102, "alphanum_fraction": 0.4497461929, "include": true, "reason": "import numpy", "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854103128327, "lm_q2_score": 0.8791467564270272, "lm_q1q2_score": 0.8525836979067806}}
{"text": "# Trust region of f at x_k using a quadratic model:\n# model_k(p) = f(x_k) + p*f.grad(x) + .5*p*B_k*p\n# B_k = f.hessian(x_k)\n\nfrom core.polynomial import *\nfrom core.matrix import *\n\n\ndef make_quadratic_model(f, x, p):\n    \"\"\"\n    p is vector of variables, e.g. (p1, p2)\n    x is a vector point, e.g. (1, 2)\n    f is a Polynomial\n    \"\"\"\n    p = [Polynomial(variable) for variable in p]\n    b = f.hessian(*x)\n    model = f(*x) + vector_times_vector(p, f.grad(*x)) + \\\n            vector_times_vector(vector_times_matrix(constant_times_vector(.5, p), b), p)\n    return model\n\n\ndef make_full_step_p(f, x):\n    \"\"\"\n    unconstrained minimum of the quadratic model\n    p = -B_k^(-1)*f.grad(x)\n    \"\"\"\n    inverse_b = get_matrix_inverse(f.hessian(*x))\n    negative_grad = constant_times_vector(-1, f.grad(*x))\n    p = matrix_times_vector(inverse_b, negative_grad)\n    return tuple(map(float, p))\n\n\ndef make_steepest_descent_direction(f, x):\n    \"\"\"\n    unconstrained minimum of the quadratic model along the steepest descent direction\n    \"\"\"\n    b = f.hessian(*x)\n    f_grad = f.grad(*x)\n    numerator = vector_times_vector(constant_times_vector(-1, f_grad), f_grad)\n    denominator = vector_times_vector(vector_times_matrix(f_grad, b), f_grad)\n    p = constant_times_vector(numerator / denominator, f_grad)\n    return tuple(map(float, p))\n\n\ndef trust_region_subproblem(f, x, delta):\n    \"\"\"\n    Dogleg method\n    1. calculate full step, p_fs\n    2. if full step is within trust region, return full step\n    3. calculate steepest descent step, p_u\n    4. if steepest descent step is outside trust region,\n        return p_u such that ||t*p_u||^2 = delta^2, t in [0, 1]\n        t = delta / norm(p)\n    5. else return point that solves ||p_u + (t-1)(p_fs - p_u)||^2 = delta^2 for t in interval [1, 2]\n    \"\"\"\n    p_fs = make_full_step_p(f, x)\n    norm = euclidean_norm\n    if norm(p_fs) <= delta:\n        step = p_fs\n        # print('2. step = ', step)\n        return vector_plus_vector(x, step)\n    p_u = make_steepest_descent_direction(f, x)\n    if norm(p_u) > delta:\n        step = constant_times_vector(delta / norm(p_u), p_u)\n        # print('4. step = ', step)\n        return vector_plus_vector(x, step)\n    p_fs_minus_p_u = vector_plus_vector(p_fs, constant_times_vector(-1, p_u))\n    quadratic_equation = norm_squared(\n        vector_plus_vector(p_u, constant_times_vector(Polynomial('t'), p_fs_minus_p_u))) - delta ** 2\n    t_minus_one = max(quadratic_equation.solve())\n    step = vector_plus_vector(p_u, constant_times_vector(t_minus_one, p_fs_minus_p_u))\n    # print('5. step = ', step)\n    return vector_plus_vector(x, step)\n\n\ndef euclidean_norm(vector):\n    return (sum([component ** 2 for component in vector])) ** .5\n\n\ndef norm_squared(vector):\n    res = 0\n    for component in vector:\n        res += component ** 2\n    return res\n\n\ndef main():\n    p = ('p1', 'p2')\n    f = Polynomial('10(x2-x1^2)^2+(1-x1)^2')\n    x = (0, -1)\n    delta = 2\n    print(make_quadratic_model(f, x, p))\n\n    # print(trust_region_subproblem(f, x, delta))\n\n    def polynomial_to_numpy(polynomial, *variables):\n        \"\"\"\n        input polynomial, a Polynomial class\n        and variables, numpy variables\n        converts Polynomial class to a numpy function\n        \"\"\"\n        z = 0\n        # for each term add consant*variable[0]^power[0]*variable[1]^power[1]...\n        for term in polynomial.term_matrix[1:]:\n            product = term[0]\n            for i, variable in enumerate(variables):\n                product *= variable ** term[i + 1]\n            z += product\n        return z\n\n    import numpy as np\n    import matplotlib.pyplot as plt\n    import matplotlib.cm as cm\n    x_scale = .5\n    y_scale = 1.25\n    x1 = np.linspace(-x_scale, x_scale, 100)\n    x2 = np.linspace(-y_scale, y_scale, 100)\n    x1, x2 = np.meshgrid(x1, x2)\n    z = polynomial_to_numpy(f, x1, x2)\n    fig = plt.figure()\n    ax = fig.add_subplot(111)\n    cpf = ax.contourf(x1, x2, z, 20, cmap='RdGy')\n    # Set the colours of the contours and labels so they're white where the\n    # contour fill is dark (Z < 0) and black where it's light (Z >= 0)\n    colours = ['w' if level < 0 else 'k' for level in cpf.levels]\n    cp = ax.contour(x1, x2, z, 20, colors=colours)\n    ax.clabel(cp, fontsize=10, colors=colours)\n    ax.set_title('Quadratic Model Contour Lines')\n    plot_points = [x]\n    for i in range(1, 15):\n        new_delta = delta / i\n        plot_points.append(trust_region_subproblem(f, x, new_delta))\n    for point in plot_points:\n        print(point)\n    xs = [x[0] for x in plot_points]\n    ys = [x[1] for x in plot_points]\n    plt.scatter(xs, ys)\n    plt.show()\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "e71ad534920a3ba04373042478227fe4a5f75a43", "size": 4681, "ext": "py", "lang": "Python", "max_stars_repo_path": "trust_region.py", "max_stars_repo_name": "mike006322/Optimization", "max_stars_repo_head_hexsha": "a58b90f1a4a3599e95e01be8f06d66ca5630050a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trust_region.py", "max_issues_repo_name": "mike006322/Optimization", "max_issues_repo_head_hexsha": "a58b90f1a4a3599e95e01be8f06d66ca5630050a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trust_region.py", "max_forks_repo_name": "mike006322/Optimization", "max_forks_repo_head_hexsha": "a58b90f1a4a3599e95e01be8f06d66ca5630050a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7342657343, "max_line_length": 101, "alphanum_fraction": 0.6321298868, "include": true, "reason": "import numpy", "num_tokens": 1344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.9173026601509101, "lm_q1q2_score": 0.852578160247638}}
{"text": "import numpy as np\n\n\"\"\"\nDot product\nThe dot product multiplies two vectors and results in a scalar. This is also\nwhy it is called the scalar product.\n- The dot product is the sum of the products of the corresponding elements.\n- When we have a dot product we always multiply a row vector by a column vector\n\"\"\"\n\n# Scalar multiplication\n\ns1 = np.array(3)\ns2 = np.array(6)\n\ns3 = np.dot(s1, s2)\n\n# Prints 18\n\nprint(s3)\n\n\"\"\"\nVector multiplication\nVectors must be the same length for multiplication\n\nThere are two types of products that can be produced from vector multiplication\n1. Dot product also known as inner product (also known as scalar product)\n2. Tensor product also known as outer product\n\"\"\"\n\nv1 = np.array([2, 8, -4])\nv2 = np.array([1, -7, 3])\n\n# In numpy you can use the dot method to multiply vectors\n# This calculation is: [2 * 1 + 8 * (-7) + (-4) x 3]\ns = np.dot(v1, v2)\n\n# This results in the scalar product of [-66]\nprint(s)\n\n\n# Multiplying a scalar times a vector results in a vector\n# where each number in a vector is multiplied by that scalar\n\ns4 = np.array(4)\nv3 = np.array([1, 2, 3])\n\n# Here the operation would be [4 * 1, 4 * 2, 4 * 3] resulting in the vector: [4, 8, 12]\nv4 = np.dot(s4, v3)\nprint(v4)\n\n# The same happens when multiplying a scalar times a matrix\n\nm1 = np.array([[1, 2, 3], [3, 2, 1]])\nm2 = np.dot(2, m1)\n\n# This results in the matrix: [[2, 4, 6], [6, 4, 2]]\nprint(m2)\n\n\"\"\"\nMultiply Matrix's\n - We can only multiply an m x n matrix with an n x k matrix\n For example, we can multiply a 2 x 3 matrix with a 3 x 1 matrix\n If we wanted to multiply a 5 x 7 matrix, compatible matrix's are any 7 * n matrix\n\"\"\"\n\n# The first matrix is 2 x 3\nm1 = np.array([[5, 12, 6], [-3, 0, 14]])\n\n# The second matrix is 3 x 2\nm2 = np.array([[2, -1], [8, 0], [3, 0]])\n\n\"\"\"\nWhen multiplying the common property, here 3, will disappear and the\nresulting matrix is a 2 x 2\n\nUsing the dot product we always multiply a row vector by a column vector and so the above two \nmatrix's will be multiplied as follows:\n\nthe first row we have is 5, 12, 6 from the first matrix and from the second matrix\nwe have the column 2, 8, 3 and with this we get:\n[5, 12, 6] * [2, 8, 3] = 124\nor\n5 * 2 + 12 * 8 + 6 * 3 = 124\n\nStill using the first row: [5, 12, 6] Next we take the second column of the second matrix (-1, 0, 0) and do:\n[5, 12, 6] * [-1, 0, 0] = -5\nor\n(5 * -1) + (12 * 0) + (6 * 0) = -5\n\n124 and -5 represent the first row in our 2 x 2 matrix. Next we take the second row\nof our first matrix and do the same multiplication:\n\n[-3, 0, 14] * [2, 8, 3] = 36\nand\n[-3, 0, 14] * [-1, 0, 0] = 3\n\nThis results in a matrix equal to [[124, -5], [36, 3]]\n\"\"\"\nm3 = np.dot(m1, m2)\nprint(m3)\n\n\n\n", "meta": {"hexsha": "82692437828c7e56a08d80fb8817c9757e6f394c", "size": 2683, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python3/data_science/multiplication.py", "max_stars_repo_name": "sreeise/Programming-Reference", "max_stars_repo_head_hexsha": "c77f6a46abab28b8f0f4a56ebd9843310b19d489", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-28T00:56:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-03T17:41:19.000Z", "max_issues_repo_path": "Python3/data_science/multiplication.py", "max_issues_repo_name": "sreeise/ProgrammingSnippets", "max_issues_repo_head_hexsha": "c77f6a46abab28b8f0f4a56ebd9843310b19d489", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-10T22:33:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-16T22:30:35.000Z", "max_forks_repo_path": "Python3/data_science/multiplication.py", "max_forks_repo_name": "sreeise/ProgrammingSnippets", "max_forks_repo_head_hexsha": "c77f6a46abab28b8f0f4a56ebd9843310b19d489", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5523809524, "max_line_length": 108, "alphanum_fraction": 0.6619455833, "include": true, "reason": "import numpy", "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731158685838, "lm_q2_score": 0.8856314813647587, "lm_q1q2_score": 0.8525736176767219}}
{"text": "# Batch Learning\r\n\r\n# This file Solves the Linear Regression Problem using\r\n# A - Closed Form Solution which uses Pseudo Inverse W = pseudoInverse(X)*Y\r\n# B - Gradient Descent Method\r\n# Linear Regression problem: Find W which minimizes (Y - WX)^2\r\n# Data required for Linear Regression is generated from different file (GenerateData.py)\r\n\r\n# Import Required Libraries\r\nimport numpy\r\nimport matplotlib.pyplot as plt\r\n\r\n# Functions\r\n# Calculates Gradient of the given Function\r\ndef Gradient(w0, w1, x, y):\r\n    g1 = (2 * w0) + (2 * w1 * x) - (2 * y)\r\n    g2 = (2 * w0 * x) + (2 * w1 * x**2) - (2 * y * x)\r\n    return numpy.array([g1, g2])\r\n\r\n# Update the points based on the Gradient Descent Algorithm\r\ndef Update_Weights(x, y, w0, w1, eta):\r\n    row, col = x.shape\r\n    sum = numpy.array([0, 0])\r\n    for i in range(0, row):\r\n        sum = sum + Gradient(w0, w1, X[i, 1], Y[i])\r\n    return numpy.array([w0, w1]) - eta*sum\r\n\r\n# Actual Loop where Gradient Descent Algo runs until optimal point is reached\r\ndef GD(X, Y, max_iter, tol, eta):\r\n    iterations = 0\r\n    Epoch = numpy.array([])\r\n    W_Initial_Guess = numpy.loadtxt('W.txt')\r\n    while iterations <= max_iter:\r\n        if iterations == 0:\r\n            w_temp = W_Initial_Guess\r\n            W_GD = numpy.array([W_Initial_Guess])\r\n            w_temp = Update_Weights(X, Y, w_temp[0], w_temp[1], eta)\r\n            # Book Keeping\r\n            W_GD = numpy.concatenate((W_GD, [w_temp]), axis=0)\r\n            Epoch = numpy.concatenate((Epoch, [iterations]), axis=0)\r\n            print('No. of Iterations: ', iterations, ' Linear Least Square Fit: ', W_GD[-1], '\\n')\r\n            iterations += 1\r\n        else:\r\n            # Run The Gradient Descent Algorithm\r\n            w_temp = Update_Weights(X, Y, w_temp[0], w_temp[1], eta)\r\n            # Book Keeping\r\n            W_GD = numpy.concatenate((W_GD, [w_temp]), axis=0)\r\n            Epoch = numpy.concatenate((Epoch, [iterations]), axis=0)\r\n            print('No. of Iterations: ', iterations, ' Linear Least Square Fit: ', W_GD[-1], '\\n')\r\n            # Check for Close Weights\r\n            if (W_GD[-1] - W_GD[-2]).all() < tol:\r\n                print('Optimal Value Reached')\r\n                break\r\n            else:\r\n                iterations += 1\r\n    return Epoch, W_GD\r\n\r\n# Function for plotting\r\ndef grapher(W):\r\n    x = numpy.array([0, 51])\r\n    y = numpy.array([W[0], W[0] + 51 * W[1]])\r\n    return x, y\r\n\r\n# Parameters\r\n# Shape of matrix X = Nx2\r\n# Shape of matrix Y = Nx1\r\n# Shape of Weight matrix = 2x1\r\nX = numpy.loadtxt('X.txt')\r\nY = numpy.loadtxt('Y.txt')\r\nmax_iter = 100000 # Maximum Iterations to reach the optimal value\r\ntol = 1.0e-6 # Tolerance\r\neta = 0.00002 # Learning Rate\r\n\r\n# Solution for the Linear Regression Problem using Closed Form Solution\r\n# From the way I have chosen matrices the\r\n# Equation will be: Y - X * W = 0\r\n# Hence closed form solution will be W = pseudoInverse(X)*Y\r\n# Pseudo Inverse also known as Penrose Inverse\r\nW_Closed_Form_Solution = numpy.dot(numpy.linalg.pinv(X), Y)\r\nnumpy.savetxt('ClosedFormSolution.txt', W_Closed_Form_Solution)\r\n\r\n\r\n# Solution for the Linear Regression Problem using Gradient Descent Method\r\nif numpy.DataSource().exists('BatchLearningGDSolution.txt'):\r\n    W_GD = numpy.loadtxt('BatchLearningGDSolution.txt')  # Load the Initial Weights\r\nelse:\r\n    Epoch, W_GD1 = GD(X, Y, max_iter, tol, eta)\r\n    W_GD = W_GD1[-1]\r\n    numpy.savetxt('BatchLearningGDSolution.txt', W_GD1[-1])  # Generate the Weights and save them\r\n\r\n# Final Optimal Point\r\nprint(W_GD)\r\nprint(W_Closed_Form_Solution)\r\n\r\n# Plot the results\r\n# Plot 1\r\nfig, ax1 = plt.subplots()\r\ntemp_x, temp_y = grapher(W_Closed_Form_Solution)\r\nax1.plot(temp_x, temp_y, 'r--')\r\nax1.plot(X[:, 1], Y)\r\nplt.title('Closed Form Solution for Linear Least Square Fit')\r\nplt.xlabel('X')\r\nplt.ylabel('Y')\r\n# Plot 2\r\nfig, ax2 = plt.subplots()\r\ntemp_x, temp_y = grapher(W_GD)\r\nax2.plot(temp_x, temp_y, 'r--')\r\nax2.plot(X[:, 1], Y)\r\nplt.title('Batch Gradient Descent for Linear Least Square Fit')\r\nplt.xlabel('X')\r\nplt.ylabel('Y')\r\nplt.show()", "meta": {"hexsha": "e1f73ed9dc22450206b571ddd2117f826e33b4d1", "size": 4056, "ext": "py", "lang": "Python", "max_stars_repo_path": "BatchLearningLinearRegression.py", "max_stars_repo_name": "bvsk35/Linear-Regression-", "max_stars_repo_head_hexsha": "0b4791c99dd97a99f8f4309f204b95307d3e21f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BatchLearningLinearRegression.py", "max_issues_repo_name": "bvsk35/Linear-Regression-", "max_issues_repo_head_hexsha": "0b4791c99dd97a99f8f4309f204b95307d3e21f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BatchLearningLinearRegression.py", "max_forks_repo_name": "bvsk35/Linear-Regression-", "max_forks_repo_head_hexsha": "0b4791c99dd97a99f8f4309f204b95307d3e21f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2142857143, "max_line_length": 99, "alphanum_fraction": 0.6286982249, "include": true, "reason": "import numpy", "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.8856314828740729, "lm_q1q2_score": 0.8525736162844181}}
{"text": "# Copyright 2018 - Jonathan Alcantara e Osmar Fernandes\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n#     http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nfrom math import pow\nfrom math import sqrt\n\ndef integrate(points, a, b, type):\n  if type == \"gauss\":\n    L = b-a\n    if points > 10:\n            print(\"Numero de pontos de integração indisponivel.\")\n    \n    if points == 2:\n        peso = np.array([1, 1])\n        vectorx = np.array([-0.577, 0.577])\n    elif points == 3:\n        peso = np.array([0.889, 0.556, 0.556])\n        vectorx = np.array([0, -0,775, 0.775])\n    elif points == 4:\n        peso = np.array([0.652, 0.652, 0.348, 0.348])\n        vectorx = np.array([-0.340, 0.340, -0.861, 0.861])\n    elif points == 5:\n        peso = np.array([0.569, 0.477, 0.477, 0.237, 0.237])\n        vectorx = np.array([0, -0.538, 0.538, -0.906, 0.906])\n    elif points == 6:\n        peso = np.array([0.361, 0.361, 0.468, 0.468, 0.171, 0.171])\n        vectorx = np.array([0.661, -0.661, -0.239, 0.239, -0.932, 0.932])\n    elif points == 7:\n        peso = np.array([0.462, 0.382, 0.382, 0.280, 0.280, 0.129, 0.129])\n        vectorx = np.array([0, 0.406, -0.406, -0.742, 0.742, -0.949, 0.949])\n    elif points == 8:\n        peso = np.array([0.363, 0.363, 0.314, 0.314, 0.222, 0.222, 0.101, 0.101])\n        vectorx = np.array([-0.183, 0.183, -0.526, 0.526, -0.797, 0.797, -0.960, 0.960])\n    elif points == 9:\n        peso = np.array([0.330, 0.181, 0.181, 0.081, 0.081, 0.312, 0.312, 0.261, 0.261])\n        vectorx = np.array([0, -0.836, 0.836, -0.968, 0.968, -0.324, 0.324, -0.613, 0.613])\n    elif points == 10:\n        peso = np.array([0.296, 0.296, 0.269, 0.269, 0.219, 0.219, 0.149, 0.149, 0.067, 0.067])\n        vectorx = np.array([-0.149, 0.149, -0.433, 0.433, -0.679, 0.679, -0.865, 0.865, -0.974, 0.974])\n\n    function = np.zeros((points, 1))\n    for i in range(points):\n        function[i] = f((a + b + L*vectorx[i])/2)\n    return (np.dot(function.T, peso)*(b-a))[0]/2\n  else:\n    x = np.zeros(points)\n    \n    if points == 1:\n      x[0] = (a+b)/2\n    else:\n      delta = (b-a)/(points - 1)\n      for i in range(points):\n        x[i] = a + i*delta\n      \n      vandermonde = np.zeros((points, points))\n      function = np.zeros((points, 1))\n      matrixB = np.zeros((points, 1))\n      \n      for i in range(points):\n        vandermonde[i] = np.power(x, i)\n        matrixB[i] = ((b**(i+1)) - (a**(i+1))) / (i+1)\n        function[i] = f(x[i])\n      \n      pesos = np.linalg.solve(vandermonde, matrixB)\n      \n      return np.dot(function.T, pesos)[0,0]\n      \n    \n    \ndef f(x):\n  return (2 + x + 2*pow(x,2))\n\nresult = integrate(2, 1, 3, \"gauss\")\nprint(result)\n  \n\n  \n", "meta": {"hexsha": "5370ff5a06142c1a14d27160a8bef6a89759869c", "size": 3135, "ext": "py", "lang": "Python", "max_stars_repo_path": "Integrate/integrate.py", "max_stars_repo_name": "JonathanAlcantara/NumericalLinearAlgebra_Applications", "max_stars_repo_head_hexsha": "519de07ef7834c4c1ab42398840baa808d95a6bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Integrate/integrate.py", "max_issues_repo_name": "JonathanAlcantara/NumericalLinearAlgebra_Applications", "max_issues_repo_head_hexsha": "519de07ef7834c4c1ab42398840baa808d95a6bc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Integrate/integrate.py", "max_forks_repo_name": "JonathanAlcantara/NumericalLinearAlgebra_Applications", "max_forks_repo_head_hexsha": "519de07ef7834c4c1ab42398840baa808d95a6bc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8333333333, "max_line_length": 103, "alphanum_fraction": 0.5610845295, "include": true, "reason": "import numpy", "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731158685838, "lm_q2_score": 0.8856314632529872, "lm_q1q2_score": 0.8525736002410065}}
{"text": "\"\"\"\nCreated on Wed Apr 22 15:53:00 2015\n\nCharging and discharging curves for passive membrane patch\nR Rao 2007\n\ntranslated to Python by rkp 2015\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# input current\nI = 10 # nA\n\n# capacitance and leak resistance\n\n# Questions 2:\n# Change the values for the membrane's resistance and capacitance (R and C),\n# and find out how this influences the response of the membrane. Does it reach\n# a stable value more quickly or more slowly after multiplying R by 5?\n#R = 100 * 5 # M ohms\n\n# Original\nR = 100 # M ohms\n\n# Question 3:\n# Does it reach a stable value more quickly or more slowly after dividing C by 10?\nC = 0.1 / 10.# nF\n\n# Original\n#C = 0.1 # nF\n\n# Question 4:\n# Does it reach a stable value more quickly or more slowly after multiplying R\n# by 10 AND dividing C by 10?\nC = 0.1 / 10.\nR = 100 * 10.\n\ntau = R*C # = 0.1*100 nF-Mohms = 100*100 pF Mohms = 10 ms\nprint('C = %.3f nF' % C)\nprint('R = %.3f M ohms' % R)\nprint('tau = %.3f ms' % tau)\nprint('(Theoretical)')\n\n# membrane potential equation dV/dt = - V/RC + I/C\n\n# QUESTIONS:\n# What if the current were not turned off? What would the steady state voltage\n# of the membrane be?\n# Use the values given in the script to compute your answer (C = 0.1 nF,\n# R = 100 MΩ, I = 10 nA). You should give your answer in mV. Do not include\n# units in your answer.\n#tstop = 15000 # ms\n\n# Original\ntstop = 150 # ms\n\nV_inf = I*R # peak V (in mV)\ntau = 0 # experimental (ms)\n\nh = 0.2 # ms (step size)\n\nV = 0 # mV\nV_trace = [V] # mV\n\nfor t in np.arange(h, tstop, h):\n\n   # Euler method: V(t+h) = V(t) + h*dV/dt\n   V = V +h*(- (V/(R*C)) + (I/C))\n\n   # Verify membrane time constant\n   if (not tau and (V > 0.6321*V_inf)):\n     tau = t\n     print('tau = %.3f ms' % tau)\n     print('(Experimental)')\n\n   \n   # Stop current injection \n   if t >= 0.6*tstop:\n     I = 0\n\n   V_trace += [V]\n\n# Why draw this every 10th time?\n#if t % 10 == 0:\nplt.plot(np.arange(0,t+h, h), V_trace, color='r')\nplt.xlim(0, tstop)\nplt.ylim(0, V_inf)\nplt.xlabel('Time[ms]')\nplt.ylabel('Voltage[mV]')\nplt.draw()\n\nplt.show()\n", "meta": {"hexsha": "4f5f34856ecaecb7134b4f163b4e594e042cbd96", "size": 2083, "ext": "py", "lang": "Python", "max_stars_repo_path": "L5/membrane.py", "max_stars_repo_name": "mapa17/Computational_Neuroscience_Homework", "max_stars_repo_head_hexsha": "b358a7cce935ac0b679748c289d3476c63e3f2f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "L5/membrane.py", "max_issues_repo_name": "mapa17/Computational_Neuroscience_Homework", "max_issues_repo_head_hexsha": "b358a7cce935ac0b679748c289d3476c63e3f2f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "L5/membrane.py", "max_forks_repo_name": "mapa17/Computational_Neuroscience_Homework", "max_forks_repo_head_hexsha": "b358a7cce935ac0b679748c289d3476c63e3f2f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9263157895, "max_line_length": 82, "alphanum_fraction": 0.6423427748, "include": true, "reason": "import numpy", "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140616, "lm_q2_score": 0.8856314632529872, "lm_q1q2_score": 0.852573595498873}}
{"text": "import numpy \nimport math\nfrom sympy import *\n\ndef nCr(n, r): \n    return math.factorial(n)//(math.factorial(r) * math.factorial(n - r))\n\n#Returns coefficient of x^0, x^1, x^2, x^4, ... as an matrix\ndef binomialequation(constant,power): \n    coeffs = []\n    for i in range(0, power + 1):\n        coeff = nCr(power, power - i) * math.pow(constant, power - i)  \n        coeffs.append(coeff)\n    return coeffs \n\ndef expression_solver(expression, debugging = False): \n    x = Symbol('x')\n    converted = sympify(expression)\n    if debugging:\n        print(\"Converted is \" + str(converted))\n    solutions = solve(converted)\n    count = 1\n    for value in solutions: \n        try:\n            print(\"Solution \" + str(count) + \": \" + str(round(float(value),3)))\n            count += 1\n        except:\n            continue\n    if(count == 1): \n        print(\"No real solutions\")\n\ndef equation_creater(coeffs): \n    result = str(int(coeffs[0])) + \" + \"\n    for index in range(1, len(coeffs)): \n        result += str(int(coeffs[index])) + \"*x^\" + str(index) + \" + \"\n    result = result[:-3]\n    print(result)\n    return result\n\ndef subtract(leftarr, rightarr): \n    updated = [0.0] * max(len(leftarr), len(rightarr))\n    for index in range(len(updated)): \n        if(index < len(leftarr)): \n            updated[index] += leftarr[index]\n        if(index < len(rightarr)): \n            updated[index] -= rightarr[index]\n    return updated\n\nif __name__ == '__main__': \n    leftarr = [0.0, 1.0]\n    rightarr = [1.0, 0.0, -4.0]\n    #print(subtract(leftarr, rightarr))\n    #expression_solver(equation_creater(rightarr))\n    expression_solver('2*x - ((-1 + x) + 4)')", "meta": {"hexsha": "cbb570484e1316470cd5f7e987d11c876c1655d8", "size": 1649, "ext": "py", "lang": "Python", "max_stars_repo_path": "Workspace.py", "max_stars_repo_name": "sarda-devesh/EquationSolver", "max_stars_repo_head_hexsha": "8f99a9385498f3e32f4029fa6099ad34933463cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Workspace.py", "max_issues_repo_name": "sarda-devesh/EquationSolver", "max_issues_repo_head_hexsha": "8f99a9385498f3e32f4029fa6099ad34933463cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Workspace.py", "max_forks_repo_name": "sarda-devesh/EquationSolver", "max_forks_repo_head_hexsha": "8f99a9385498f3e32f4029fa6099ad34933463cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.537037037, "max_line_length": 79, "alphanum_fraction": 0.5845967253, "include": true, "reason": "import numpy,from sympy", "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951703918909, "lm_q2_score": 0.8872045981907006, "lm_q1q2_score": 0.8525607703560448}}
{"text": "# Exercise 2\n# Load the data from the CSV file data_ex2.csv. These are samples from three different, independent Gaussian\n# distributions, all mixed together.\n# 1. Implement the Expectation-Maximization algorithm to fit a mixture of three Gaussian distributions to the data.\n#    Try both with and without the prior update step. Discuss the results.\n# 2. Give the parameters of the distributions thus found, and plot the corresponding PDFs on top of the\n#    empirical PDFs of the data (e.g., the histogram).\n# import and solve data\nfrom pandas import read_csv\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom numpy import mean, min, max, median, quantile\nfrom scipy.stats import binom, norm, t as student, expon\nfrom math import sqrt, pow, floor, ceil, exp\n\nnp.set_printoptions(precision=3)\n\n# define corrected functions for std and variance\ndef variance(values):\n\treturn np.var(values, ddof=1)\n\n\ndef std(values):\n\treturn np.std(values, ddof=1)\n\n\ndata = 'HW2/data'\ndata_ex2 = read_csv(f'{data}\\\\data_ex2.csv', header=None)\nvalues = data_ex2.to_numpy()[:, 0]\n\ndef expectation_maximization_normal(values, curve_n, max_iter=10000, curve_prob=None, prior=True):\n\tn = len(values)\n\t# use the same std for all of them\n\tdeviations = np.array([std(values)] * curve_n)\n\t# for 3 curves, use 1/4, 2/4, 3/4 quantiles as means\n\tmeans = np.array(quantile(values, np.arange(1, curve_n + 1, 1) / (curve_n + 1)))\n\tif curve_prob == None:\n\t\tcurve_prob = [1 / curve_n] * curve_n\n\tcurve_prob = np.array(curve_prob)\n\n\tvalues_repeated = np.array([values] * curve_n)\n\n\titeration = 0\n\tprev_total = sum(means + deviations + curve_prob)\n\twhile iteration < max_iter:\n\t\tpdfs_per_curve = norm.pdf(values_repeated.T, means, deviations)\n\t\tdenoms = np.sum(pdfs_per_curve * curve_prob, axis=1)\n\t\tb = (pdfs_per_curve * curve_prob).T / denoms\n\t\tsum_b = np.sum(b, axis=1)\n\t\tmeans = np.sum(b * values, axis=1) / sum_b\n\t\tvariances = np.sum(b.T * ((values_repeated.T - means)**2), axis=0) / sum_b\n\t\tdeviations = np.sqrt(variances)\n\t\tif prior:\n\t\t\tcurve_prob = sum_b / n\n\n\t\titeration += 1\n\t\tnew_total = sum(means + deviations + curve_prob)\n\t\t# stop when total difference is no longer changing\n\t\tif abs(new_total / prev_total - 1) <= 0.0001:\n\t\t\tbreak\n\t\tprev_total = new_total\n\n\tprint(f\"done {iteration} iterations\")\n\treturn np.array([means, deviations, curve_prob]).T\n\n\nprint(\"prior true\")\ncurves = expectation_maximization_normal(values, 3, max_iter=10000, prior=True)\nprint(curves)\nplt.hist(values, bins=50, density=True, color='y', linewidth=0.1, edgecolor='b')\nX_prob = np.arange(min(values), max(values), 1 / 100)\nfor c in curves:\n\tplt.scatter(X_prob, c[2] * norm.pdf(X_prob, c[0], c[1]), s=1, zorder=2)\nplt.show()\n\nprint(\"prior false\")\ncurves = expectation_maximization_normal(values, 3, max_iter=10000, prior=False)\nprint(curves)\nplt.hist(values, bins=50, density=True, color='y', linewidth=0.1, edgecolor='b')\nX_prob = np.arange(min(values), max(values), 1 / 100)\nfor c in curves:\n\tplt.scatter(X_prob, c[2] * norm.pdf(X_prob, c[0], c[1]), s=1, zorder=2)\nplt.show()\n\noff_start = [0.8, 0.1, 0.1]\nprint(f\"prior true, starting from probabilities: {off_start}\")\ncurves = expectation_maximization_normal(values, 3, max_iter=10000, prior=True, curve_prob=off_start)\nprint(curves)\nplt.hist(values, bins=50, density=True, color='y', linewidth=0.1, edgecolor='b')\nX_prob = np.arange(min(values), max(values), 1 / 100)\nfor c in curves:\n\tplt.scatter(X_prob, c[2] * norm.pdf(X_prob, c[0], c[1]), s=1, zorder=2)\nplt.show()\n\nprint(f\"prior false, starting from probabilities: {off_start}\")\ncurves = expectation_maximization_normal(values, 3, max_iter=10000, prior=False, curve_prob=off_start)\nprint(curves)\nplt.hist(values, bins=50, density=True, color='y', linewidth=0.1, edgecolor='b')\nX_prob = np.arange(min(values), max(values), 1 / 100)\nfor c in curves:\n\tplt.scatter(X_prob, c[2] * norm.pdf(X_prob, c[0], c[1]), s=1, zorder=2)\nplt.show()\n", "meta": {"hexsha": "66c8c394ecbae36998e16895afd01ce431e28b22", "size": 3904, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW2/ex2.py", "max_stars_repo_name": "andreamatt/Simulation-homeworks", "max_stars_repo_head_hexsha": "d6e987a99498c0a30bfd8d3d9deeb3c0382a27be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW2/ex2.py", "max_issues_repo_name": "andreamatt/Simulation-homeworks", "max_issues_repo_head_hexsha": "d6e987a99498c0a30bfd8d3d9deeb3c0382a27be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW2/ex2.py", "max_forks_repo_name": "andreamatt/Simulation-homeworks", "max_forks_repo_head_hexsha": "d6e987a99498c0a30bfd8d3d9deeb3c0382a27be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9029126214, "max_line_length": 115, "alphanum_fraction": 0.7213114754, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920618, "lm_q2_score": 0.8872045907347108, "lm_q1q2_score": 0.8525607671598003}}
{"text": "#steven 01/03/2020\n#calculate pi using random method. (Monte Carlo method)\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import integrate\n\ndef randomSeries(N):#generate series number between 0~1\n    return np.random.rand(N)\n\ndef distance(a, b):#euclidean distance from point(a,b) to point(0,0)\"\"\"\n    return np.sqrt(a**2 + b**2)\n\ndef circleFun(x):\n    return np.sqrt(1-x**2)\n\ndef plotXY(x,y):\n    plt.figure(num='Calculate Pi')\n    ax = plt.gca()\n    ax.set_xlabel('x')\n    ax.set_ylabel('y')\n\n    for a,b in zip(x,y):\n        if distance(a, b) > 1:\n            ax.scatter(a, b, c='r', s=5, alpha=0.5)\n        else:\n            ax.scatter(a, b, c='b', s=5, alpha=0.5)\n\n    plt.show()\n\ndef menteCarloMethod(N=10000 ,plot=True):\n    x = randomSeries(N)\n    y = randomSeries(N)\n\n    res = np.where(distance(x,y) > 1, 0, 1)\n    #print(res)\n\n    pi = np.sum(res)/len(res)*4.0\n    #pi = np.mean(res == 1)*4.0\n    print('when N=',N,'pi=',pi)\n\n    if plot:\n        plotXY(x,y)\n\ndef IntegralCalculatePi(N=10000):\n    \"\"\"calculate area form x = 0 to 1\n    divide 0~1 to N shares,  erevy part considered as a rectangle.\n    \"\"\"\n    s = 0\n    for i in range(N):\n        x = 1/N\n        y = circleFun(i/N)\n        s += x*y\n\n    pi = s*4\n    print('when N=',N,'s = ',s,'pi = ',pi)\n    fillColor()\n\ndef fillColor():\n    x = np.linspace(0, 1, 100)\n    y1 = np.zeros(len(x))\n    y2 = circleFun(x)\n\n    plt.plot(x,y1,c='b',alpha=0.5)\n    plt.plot(x,y2,c='b',alpha=0.5)\n\n    plt.fill_between(x,y1,y2,where=x<=1,facecolor='green')\n    #plt.axes(aspect='equal')#.set_aspect('equal')\n    plt.axes().set_aspect('equal')\n    #plt.grid(True)\n    plt.show()\n\ndef IntegralAccPi():\n    s = integrate.quad(circleFun, 0, 1)[0]\n    print('s = ',s,'pi = ',4*s)\n\ndef main():\n    #menteCarloMethod(plot=False)\n    #IntegralCalculatePi()\n    IntegralAccPi()\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "a51356ccdf95eff4480a92560e411e8bad984039", "size": 1878, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/piCalculate.py", "max_stars_repo_name": "StevenHuang2020/ML", "max_stars_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/piCalculate.py", "max_issues_repo_name": "StevenHuang2020/ML", "max_issues_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/piCalculate.py", "max_forks_repo_name": "StevenHuang2020/ML", "max_forks_repo_head_hexsha": "a5d85ce2a6b0f0af3af6fdbb37806e944555c501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6265060241, "max_line_length": 71, "alphanum_fraction": 0.5788072417, "include": true, "reason": "import numpy,from scipy", "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737735, "lm_q2_score": 0.8872045832787205, "lm_q1q2_score": 0.8525607590028033}}
{"text": "import numpy as np\nfrom scipy.special import erf, erfinv\n\n\n# =============================================================================\n# Define variables\n# =============================================================================\nsqrt2 = np.sqrt(2)\nsqrt2pi = np.sqrt(2 * np.pi)\n\n\n# =============================================================================\n# Define functions\n# =============================================================================\ndef gaussian1d_variant1(x, *p):\n    \"\"\"\n    Create a normalised gaussian (Area == 1) from mean and variance\n\n    :param x: [numpy array]    x axis data (array/list)\n    :param p: [Tuple]         (mean , variance)\n\n    Area of gaussian is 1  --> A = 1/(c*sqrt(2pi))\n\n    Returns a Gaussian array one value for each x value\n    \"\"\"\n    mu, sigma = p\n    A = 1.0 / (sigma * sqrt2pi)\n    return A * np.exp(-0.5 * (x - mu) ** 2 / (sigma ** 2))\n\n\ndef gaussian1d_variant2(x, *p):\n    \"\"\"\n    Create a gaussian from amplitude, mean and variance\n\n    :param x: [numpy array]    x axis data (array/list)\n    :param p: [Tuple]         (a = amplitude, b = mean , c = variance)\n\n    Returns a Gaussian array one value for each x value\n    \"\"\"\n    a, b, c = p\n    return a * np.exp(-0.5 * (x - b) ** 2 / (c ** 2))\n\n\ndef gaussian2d_variant1(x, y, *p):\n    \"\"\"\n    Create a 2D gaussian from amplitude, mean x, variance x, mean y and\n    variance y\n\n    :param x: [numpy array]    x axis data (array/list)\n    :param y: [numpy array]    y axis data (array/list)\n    :param p: [Tuple]         (amplitude, mean x, variance x,\n                               mean y, variance y)\n\n    Returns a Gaussian array one value for each x value\n    \"\"\"\n    A, x0, sigmax, y0, sigmay = p\n    part1 = (x - x0) ** 2 / (2. * sigmax ** 2)\n    part2 = (y - y0) ** 2 / (2. * sigmay ** 2)\n    # return 2d gaussian\n    return A * np.exp(-(part1 + part2))\n\n\ndef gaussian2d_variant2(x, y, *p, **kwargs):\n    \"\"\"\n    Create a 2D gaussian from amplitude, mean x, variance x, mean y and\n    variance y and a rotation angle theta (0.0 == x-axis) where theta is in\n    degrees unless keyword units = radians or rad\n\n\n    :param x: [numpy array]    x axis data (array/list)\n    :param y: [numpy array]    y axis data (array/list)\n    :param p: [Tuple]         (amplitude, mean x, variance x,\n                               mean y, variance y, theta)\n    :param kwargs:             keyword arguments i.e. units = \"deg\"\n    keywords args are as follows:\n        - units:               string either deg or rad\n\n    Returns a Gaussian array one value for each x value\n    \"\"\"\n    # extract values from p\n    A, x0, sigmax, y0, sigmay, theta = p\n    # sort out units\n    units = kwargs.get('units', 'deg')\n    if units == 'deg' or 'deg' in units:\n        theta = np.deg2rad(theta)\n    else:\n        theta = theta\n    # calculate gaussian\n    a = np.cos(theta) ** 2 / (2. * sigmax ** 2) + np.sin(theta) ** 2 / (\n    2. * sigmay ** 2)\n    b = -np.sin(2 * theta) / (4. * sigmax ** 2) + np.sin(2 * theta) / (\n    4. * sigmay ** 2)\n    c = np.cos(theta) ** 2 / (2. * sigmay ** 2) + np.sin(theta) ** 2 / (\n    2. * sigmax ** 2)\n    part1 = a * (x - x0) ** 2\n    part2 = -2 * b * (x - x0) * (y - y0)\n    part3 = c * (y - y0) ** 2\n    # return 2d gaussian\n    return A * np.exp(-(part1 + part2 + part3))\n\n\ndef gaussian2d_variant3(x, y, *p):\n    \"\"\"\n    Standard Gaussian function Creator\n    :param x: [numpy array]    x axis data (array/list)\n    :param y: [numpy array]    y axis data (array/list)\n    :param p: [Tuple]         (amplitude, mean x, mean y, a, b, c)\n\n    Returns a Gaussian array one value for each x value\n    \"\"\"\n    A, x0, y0, a, b, c = p\n    part1 = a * (x - x0) ** 2\n    part2 = -2 * b * (x - x0) * (y - y0)\n    part3 = c * (y - y0) ** 2\n    # return 2d gaussian\n    return A * np.exp(-(part1 + part2 + part3))\n\n\ndef sigma2percentile(sigma):\n    \"\"\"\n    Percentile calculation from sigma\n    i.e. 1 sigma == 0.68268949213708585 (68.27%)\n    :param sigma: [float]     sigma value\n    :return percentile:  [float] the percentile (i.e. between 0.00 and 1.00)\n    \"\"\"\n    # percentile = integral of exp{-0.5x**2}\n    percentile = erf(sigma / sqrt2)\n    return percentile\n\n\ndef percentile2sigma(percentile):\n    \"\"\"\n    Sigma calcualtion from percentile\n    i.e. 0.68268949213708585 (68.27%) == 1 sigma\n    :param percentile: [float]     percentile value (i.e. between 0.00 and 1.00)\n    :return sigma:  [float] the sigma value (i.e. 1, 2, 3, 1.5)\n    \"\"\"\n    # area = integral of exp{-0.5x**2}\n    sigma = sqrt2 * erfinv(percentile)\n    return sigma\n", "meta": {"hexsha": "4e353e13b985b9188d36cadec24996977b3c00aa", "size": 4576, "ext": "py", "lang": "Python", "max_stars_repo_path": "neil_stats_functions.py", "max_stars_repo_name": "njcuk9999/neil_math_functions", "max_stars_repo_head_hexsha": "7b00a4f4d77a1710abac320a875ebc4c35663364", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "neil_stats_functions.py", "max_issues_repo_name": "njcuk9999/neil_math_functions", "max_issues_repo_head_hexsha": "7b00a4f4d77a1710abac320a875ebc4c35663364", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neil_stats_functions.py", "max_forks_repo_name": "njcuk9999/neil_math_functions", "max_forks_repo_head_hexsha": "7b00a4f4d77a1710abac320a875ebc4c35663364", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4539007092, "max_line_length": 80, "alphanum_fraction": 0.5233828671, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639686018701, "lm_q2_score": 0.8774767874818409, "lm_q1q2_score": 0.8525248300018771}}
{"text": "# Find eigenvalue and eigenvectors of matrix A.\n#Ax = lx\n#l = lamda\n\n# Rewrite (A - lI)x = 0\n# det(A - lI) = 0\n\n# Find lamda first.\n\nimport numpy as np\nimport scipy.linalg\n\n\nA = np.array([[3, 1],\n              [1, 3]])\n\n(l, eigv) = np.linalg.eig(A)\n\n# More by hand \n# Another solution det(A - lI) = 0\n# Lamda in diagonal.\n\n# (3-l)² = 1\n# Solve for lamda. l1 = 4 and l2 = 2 \n\nlamda1 = l[0]\nlamda2 = l[1]\n\nlamda1Vector = lamda1 * (np.identity(2))\nsol1 = A - lamda1Vector\n\nlamda2Vector = lamda2 * (np.identity(2))\nsol2 = A - lamda2Vector\n\n\n# We will solve a type of Bx = 0. That is solve for N(B), The Nullspace of B. \n\nX1 = scipy.linalg.null_space(sol1)\nX2 = scipy.linalg.null_space(sol2)\n\n# Need to reshape to compare.\nX1 = X1.reshape((2,))\nX2 = X2.reshape((2,))\n\nassert np.allclose(X1, eigv[:,0])\nassert np.allclose(X2, eigv[:,1])\n\nprint(lamda1)", "meta": {"hexsha": "4d1e5694f77c53a2a115d9ea96c0b968d087c93f", "size": 845, "ext": "py", "lang": "Python", "max_stars_repo_path": "linalg/eigenvalue.py", "max_stars_repo_name": "codersthlm/study-notes", "max_stars_repo_head_hexsha": "bf7f08932b6baa9cc8d1576ca654658c62035fcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linalg/eigenvalue.py", "max_issues_repo_name": "codersthlm/study-notes", "max_issues_repo_head_hexsha": "bf7f08932b6baa9cc8d1576ca654658c62035fcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linalg/eigenvalue.py", "max_forks_repo_name": "codersthlm/study-notes", "max_forks_repo_head_hexsha": "bf7f08932b6baa9cc8d1576ca654658c62035fcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.6041666667, "max_line_length": 78, "alphanum_fraction": 0.6295857988, "include": true, "reason": "import numpy,import scipy", "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639653084245, "lm_q2_score": 0.8774767874818408, "lm_q1q2_score": 0.8525248271119549}}
{"text": "# Import\nimport numpy as np  # Matrix\nfrom sklearn.datasets import make_regression  # Random dataset\nimport matplotlib.pyplot as plt  # Graphic\n\n\n# Linear regression multiple\n# https://github.com/MachineLearnia/Regression-lineaire-numpy/blob/master/R%C3%A9gression%20Lin%C3%A9aire%20Multiple.ipynb\nclass LrMultiple:\n    # Hyper parameter\n    learning_rate = 0.1\n    n_iteration = 100\n\n    # Configuration\n    n_features = 2\n    n_param = 2\n\n    def run(self):\n        x, y = make_regression(n_samples=100, n_features=self.n_features, noise=10)  # x -> inputs  y -> outputs\n        y = y.reshape(y.shape[0], 1)\n\n        X = np.hstack((x, np.ones((x.shape[0], 1))))  # X -> arguments input [[a, 1],[b, 1]...]\n        for i in range(2, self.n_param):\n            X = np.hstack((X * x, np.ones((x.shape[0], 1))))\n            # print(X)\n\n        theta = np.random.randn(X.shape[1], 1)  # Matrix with the arguments of the function\n\n        # Learn\n        theta_final, cost_history = self.gradient_descent(X, y, theta, self.learning_rate, self.n_iteration)\n\n        predictions = self.model(X, theta_final)\n\n        print(\"Stats: Linear regression multiple\")  # Show Stats\n        print(\"Iteration: \" + str(self.n_iteration))\n        print(\"Learning rate: \" + str(self.learning_rate))\n        print(\"Features: \" + str(self.n_features))\n        print(\"Parameters: \" + str(self.n_param))\n        print(\"x: \" + str(x.shape))\n        print(\"y: \" + str(y.shape))\n        print(\"X: \" + str(X.shape))\n        print(\"Theta: \" + str(theta.shape))\n        print(\"Theta final: \" + str(theta_final))\n\n        # Show coef /1\n        coef = self.coef_determination(y, predictions)\n        print(\"\\nCoef: {0:9.3f}/1 ({0})\".format(coef))\n\n        # Show graphs\n        for i in range(0, self.n_features):\n            plt.scatter(x[:, i], y)\n            plt.scatter(x[:, i], predictions, c='r')\n            plt.show()\n\n        #  Show cost evolution\n        plt.plot(range(self.n_iteration), cost_history)\n        plt.show()\n\n    def model(self, X, theta):\n        return X.dot(theta)\n\n    def cost(self, X, y, theta):\n        m = len(y)\n        return 1 / (2 * m) * np.sum((self.model(X, theta) - y) ** 2)\n\n    def grad(self, X, y, theta):\n        m = len(y)\n        return 1 / m * X.T.dot(self.model(X, theta) - y)\n\n    def gradient_descent(self, X, y, theta, learning_rate, n_iteration):\n        cost_history = np.zeros(n_iteration)\n        for i in range(0, n_iteration):\n            theta = theta - learning_rate * self.grad(X, y, theta)\n            cost_history[i] = self.cost(X, y, theta)\n        return theta, cost_history\n\n    def coef_determination(self, y, pred):\n        u = ((y - pred) ** 2).sum()\n        v = ((y - y.mean()) ** 2).sum()\n        return 1 - u / v\n", "meta": {"hexsha": "c2d185e498a25560f55bf1bf66001b8546830e9e", "size": 2753, "ext": "py", "lang": "Python", "max_stars_repo_path": "lr/lr_multiple.py", "max_stars_repo_name": "simbarras/ML", "max_stars_repo_head_hexsha": "d51856288e9f3dca8c9a1ba1923643bdcb188f7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-20T13:13:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-21T08:48:55.000Z", "max_issues_repo_path": "lr/lr_multiple.py", "max_issues_repo_name": "simbarras/ML", "max_issues_repo_head_hexsha": "d51856288e9f3dca8c9a1ba1923643bdcb188f7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lr/lr_multiple.py", "max_forks_repo_name": "simbarras/ML", "max_forks_repo_head_hexsha": "d51856288e9f3dca8c9a1ba1923643bdcb188f7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.987654321, "max_line_length": 122, "alphanum_fraction": 0.5771885216, "include": true, "reason": "import numpy", "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.967899295134923, "lm_q2_score": 0.8807970889295664, "lm_q1q2_score": 0.8525228815318194}}
{"text": "#!/usr/bin/env python3\n\"\"\"\nClustering Module\n\"\"\"\nimport numpy as np\n\n\ndef pdf(X, m, S):\n    \"\"\"\n    Calculates the probability density function of a Gaussian distribution:\n\n    X is a numpy.ndarray of shape (n, d) containing the data points whose PDF\n    should be evaluated\n    m is a numpy.ndarray of shape (d,) containing the mean of the distribution\n    S is a numpy.ndarray of shape (d, d) containing the covariance of the\n    distribution\n    You are not allowed to use any loops\n    You are not allowed to use the function numpy.diag or the method\n    numpy.ndarray.diagonal\n\n    Returns: P, or None on failure\n        P is a numpy.ndarray of shape (n,) containing the PDF values for each\n        data point\n    All values in P should have a minimum value of 1e-300\n    \"\"\"\n    if not isinstance(X, np.ndarray) or len(X.shape) != 2:\n        return None\n    if not isinstance(m, np.ndarray) or len(m.shape) != 1:\n        return None\n    if not isinstance(S, np.ndarray) or len(S.shape) != 2:\n        return None\n    if X.shape[1] != m.shape[0] or X.shape[1] != S.shape[0]:\n        return None\n    if S.shape[0] != S.shape[1] or X.shape[1] != S.shape[1]:\n        return None\n    if S.shape[0] != S.shape[1]:\n        return None\n\n    n, d = X.shape\n    Xmm = X - m\n    Sinv = np.linalg.inv(S)\n\n    p = 1. / (np.sqrt(((2 * np.pi)**d * np.linalg.det(S))))\n    fac = np.einsum('...k,kl,...l->...', Xmm, Sinv, Xmm)\n    q = np.exp(-fac / 2)\n    return (np.maximum(p*q, 1e-300))\n", "meta": {"hexsha": "e79425e53ff5f9b51c8a1718de3345b6f8a3a35f", "size": 1477, "ext": "py", "lang": "Python", "max_stars_repo_path": "unsupervised_learning/0x01-clustering/5-pdf.py", "max_stars_repo_name": "kyeeh/holbertonschool-machine_learning", "max_stars_repo_head_hexsha": "8e4894c2b036ec7f4750de5bf99b95aee5b94449", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unsupervised_learning/0x01-clustering/5-pdf.py", "max_issues_repo_name": "kyeeh/holbertonschool-machine_learning", "max_issues_repo_head_hexsha": "8e4894c2b036ec7f4750de5bf99b95aee5b94449", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unsupervised_learning/0x01-clustering/5-pdf.py", "max_forks_repo_name": "kyeeh/holbertonschool-machine_learning", "max_forks_repo_head_hexsha": "8e4894c2b036ec7f4750de5bf99b95aee5b94449", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4255319149, "max_line_length": 78, "alphanum_fraction": 0.6127285037, "include": true, "reason": "import numpy", "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992914310605, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.8525228570692129}}
{"text": "import numpy as np\nimport math\n\ndef linear(m0,m1,u,domain=None):\n    \"\"\"For completeness: linear interpolation between m0 and m1 at parameter u in [0,1].\n    \n    Alternatively, if `domain` != None, then this will use domain=(a,b)\n    \"\"\"\n    if domain is not None:\n        return linear(m0,m1,(u-domain[0])/(domain[1]-domain[0]))\n    return (1.0-u)*m0 + u*m1\n\n\ndef piecewise_linear(ms,u,times=None):\n    \"\"\"Evaluate a piecewise linear spline at interpolation parameter u in [0,1]\n    \n    Milestones are given by the array `ms`.  `ms` is assumed to be a list of\n    n Numpy arrays, or an n x d Numpy array.\n    \n    If `times` != None, this will be a list of n non-decreasing time indices.\n    \"\"\"\n    if times is not None:\n        raise NotImplementedError(\"Not done with timed paths\")\n    n = len(ms)\n    s = u*n\n    i = int(math.floor(s))\n    u = s - i\n    if i < 0: return ms[0]\n    elif i+1 >= n: return ms[-1]\n    return linear(ms[i],ms[i+1],u)\n\n\ndef hermite(m0,m1,t0,t1,u,domain=None):\n    \"\"\"Evaluate a cubic hermite curve at interpolation parameter u in [0,1].\n    \n    Endpoints are m0 and m1, with derivatives t0 and t1.  These are assumed to be Numpy arrays.\n    \n    Alternatively, if `domain` != None, then this will use domain=(a,b)\n    as the interpolation domain\n    \"\"\"\n    if domain is not None:\n        assert isinstance(domain,(list,tuple)) and len(domain) == 2,\"Need to provide a pair as a domain\"\n        scale = (domain[1]-domain[0])\n        t = (u - domain[0])/scale\n        return hermite(m0,m1,t0*scale,t1*scale,t)\n    u2 = u**2\n    u3 = u**3\n    cm0 = 2*u3 - 3*u2 + 1\n    cm1 = -2*u3 + 3*u2\n    ct0 = u3 - 2*u2 + u\n    ct1 = u3 - u2\n    return cm0*m0 + cm1*m1 + ct0*t0 + ct1*t1\n\n\ndef hermite_deriv(m0,m1,t0,t1,u,domain=None):\n    \"\"\"Evaluate the derivative of a cubic hermite curve at interpolation parameter u in [0,1].\n    \n    Endpoints are m0 and m1, with derivatives t0 and t1.  These are assumed to be numpy arrays.\n    \n    Alternatively, if `domain` != None, then this will use domain=(a,b)\n    as the interpolation domain\n    \"\"\"\n    if domain is not None:\n        assert isinstance(domain,(list,tuple)) and len(domain) == 2,\"Need to provide a pair as a domain\"\n        scale = (domain[1]-domain[0])\n        t = (u - domain[0])/scale\n        return hermite_deriv(m0,m1,t0*scale,t1*scale,t)\n    u2 = u**2\n    cm0 = 6*u2 - 6*u\n    cm1 = -6*u2 + 6*u\n    ct0 = 3*u2 - 4*u + 1\n    ct1 = 3*u2 - 2*u\n    return cm0*m0 + cm1*m1 + ct0*t0 + ct1*t1\n\n\ndef hermite_spline(ms,ts,u,times=None):\n    \"\"\"Evaluate a cubic hermite spline at interpolation parameter u in [0,1].\n    \n    Milestones are given in `ms`, with derivatives in `ts`.  These are assumed to be \n    lists of n Numpy arrays, or n x d Numpy arrays.\n    \n    If `times` != None, this will be a list of n non-decreasing time indices.\n    \"\"\"\n    if times is not None:\n        raise NotImplementedError(\"Not done with timed paths\")\n    \n    n = len(ms)\n    s = u*n\n    i = int(math.floor(s))\n    u = s - i\n    if i < 0: return ms[0]\n    elif i+1 >= n: return ms[-1]\n    return hermite(ms[i],ms[i+1],ts[i],ts[i+1],u)\n    \n", "meta": {"hexsha": "6433ca0e0c1c0316452cceedb5f77df0e71c419c", "size": 3108, "ext": "py", "lang": "Python", "max_stars_repo_path": "rsbook_code/planning/paths.py", "max_stars_repo_name": "patricknaughton01/RoboticSystemsBook", "max_stars_repo_head_hexsha": "0fc67cbccee0832b5f9b00d848c55697fa69bedf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 116, "max_stars_repo_stars_event_min_datetime": "2018-08-27T15:32:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T10:41:37.000Z", "max_issues_repo_path": "rsbook_code/planning/paths.py", "max_issues_repo_name": "patricknaughton01/RoboticSystemsBook", "max_issues_repo_head_hexsha": "0fc67cbccee0832b5f9b00d848c55697fa69bedf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-05-04T12:56:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T23:13:33.000Z", "max_forks_repo_path": "rsbook_code/planning/paths.py", "max_forks_repo_name": "patricknaughton01/RoboticSystemsBook", "max_forks_repo_head_hexsha": "0fc67cbccee0832b5f9b00d848c55697fa69bedf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2019-06-20T20:13:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T14:01:34.000Z", "avg_line_length": 32.7157894737, "max_line_length": 104, "alphanum_fraction": 0.6074646075, "include": true, "reason": "import numpy", "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.897695292107347, "lm_q1q2_score": 0.8525137201758074}}
{"text": "#%%\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.animation import FuncAnimation\nimport matplotlib.gridspec as gridspec\nfrom scipy.stats import multivariate_normal as mn\n# %%\nplt.rcParams['grid.color'] = '#A8BDB7'\nplt.rcParams['grid.linestyle'] = '--'\nplt.rcParams['text.usetex'] = True\nplt.rcParams['text.latex.preamble'] = r'\\usepackage{{amsmath}}'\n\nclass UpdateFigure:\n    def __init__(self, ax1, ax2, ax3):\n\n        self.colors = dict(\n            blue        = '#375492',\n            green       = '#88E685',\n            dark_green  = '#00683B',\n            red         = '#93391E',\n            pink        = '#E374B7',\n            purple      = '#A268B4',\n            black       = '#000000',\n        )\n        self.cm = plt.cm.turbo\n        # ====================\n        # config data\n        # ====================\n        self.mean = np.zeros(2)\n        self.cov = np.eye(2)\n        self.xx, self.yy = np.meshgrid(np.linspace(-4,4,101), np.linspace(-4,4,101))\n        xysurf = mn.pdf(np.dstack((self.xx,self.yy)), self.mean, self.cov)\n        self.vmin, self.vmax = 0, np.max(xysurf)\n\n        # ====================\n        # draw LaTeX formula\n        # ====================\n        ax1.axis('off')\n        self.tex = ax1.text(0.5,0.5,\n            self.gen_text(self.mean, self.cov), \n            ha='center', va='center',\n            color='k', fontsize=25)\n\n        # ====================\n        # plot 3d surface\n        # ====================\n        self.surf = ax2.plot_surface(self.xx, self.yy, xysurf, cmap=self.cm,\n                        rstride=1, cstride=1, vmin=self.vmin, vmax=self.vmax)\n        ax2.view_init(10, None)\n\n        ax2.set_xlabel(r'$x$', fontsize=20)\n        ax2.set_ylabel(r'$y$', fontsize=20)\n        ax2.zaxis.set_rotate_label(False)\n        # ax2.set_zlabel(r'$f(y)$', rotation=0, fontsize=20)\n        xticks=[-4,-2,0,2,4]\n        yticks=[-4,-2,0,2,4]\n        zticks=[0,.1,.2]\n        ax2.set_xticks(xticks)\n        ax2.set_yticks(yticks)\n        ax2.set_zticks(zticks)\n        ax2.set_xlim(xticks[0], xticks[-1])\n        ax2.set_ylim(yticks[0], yticks[-1])\n        ax2.set_zlim(zticks[0], zticks[-1])\n        # ax2.invert_xaxis()\n        ax2.xaxis.pane.fill = False\n        ax2.yaxis.pane.fill = False\n        ax2.zaxis.pane.fill = False\n        ax2.xaxis.pane.set_edgecolor('w')\n        ax2.yaxis.pane.set_edgecolor('w')\n        ax2.zaxis.pane.set_edgecolor('w')\n        self.ax2 = ax2\n\n        # ====================\n        # draw 2d pcolor\n        # ====================\n        self.mesh = ax3.pcolormesh(self.xx, self.yy, xysurf, cmap=self.cm)\n        ax3.axis('scaled')\n        ax3.set_xticks([-4,-2,0,2,4])\n        ax3.set_yticks([-4,-2,0,2,4])\n    \n    def set_target(self, trans_type, diff, nframe):\n        self.trans_type = trans_type\n        if trans_type == 'stretch':\n            self.diff = (diff-np.eye(2))*1.0/(nframe-1)\n        else:\n            self.diff = diff*1.0/(nframe-1)\n\n    @staticmethod\n    def rot(mat, theta):\n        rot_mat =  np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]])\n        return rot_mat.T@mat@rot_mat\n\n    @staticmethod\n    def stretch(mat, diff):\n        stretch_mat = np.sqrt(np.eye(2) + diff)\n        return stretch_mat@mat@stretch_mat\n\n    @staticmethod\n    def gen_text(_mean, _cov):\n        return r\"$\\boldsymbol{\\mu}=\\begin{bmatrix}%.1f\\\\%.1f\\end{bmatrix},\\boldsymbol{\\Sigma}=\\begin{bmatrix}%.1f & %.1f \\\\ %.1f & %.1f\\end{bmatrix}$\"%(*_mean, *_cov.flatten())\n\n    def __call__(self, i):\n        if self.trans_type == 'rotation':\n            mean_ = self.mean.copy()\n            cov_ = self.rot(self.cov, self.diff*i)\n        elif self.trans_type == 'stretch':\n            mean_ = self.mean.copy()\n            cov_ = self.stretch(self.cov, self.diff*i)\n        elif self.trans_type == 'translation':\n            mean_ = self.mean+self.diff*i\n            cov_ = self.cov.copy()\n        xysurf = mn.pdf(np.dstack((self.xx,self.yy)), mean_, cov_)\n\n        self.surf.remove()\n        self.surf = self.ax2.plot_surface(self.xx, self.yy, xysurf, cmap=self.cm,\n                        rstride=1, cstride=1, vmin=self.vmin, vmax=self.vmax)\n        self.mesh.set_array(xysurf)\n        self.tex.set_text(self.gen_text(mean_, cov_), )\n        return [self.surf,]\n\n# %%\nif __name__ == '__main__':\n    # %%\n    fig = plt.figure(figsize=(5,10),dpi=400,)\n    spec = gridspec.GridSpec(3, 1, \n        left=0.10, right=0.90, top=1.00, bottom=0.05, \n        hspace=0.0,\n        height_ratios=[1,5,4],\n        figure=fig)\n    ax1 = fig.add_subplot(spec[0])\n    ax2 = fig.add_subplot(spec[1], projection='3d')\n    ax3 = fig.add_subplot(spec[2], )\n    # create a figure updater\n    nframes=100\n    ud = UpdateFigure(ax1, ax2, ax3)\n    ud.cov = np.array([[1,-0.8],[-0.8,1]])\n    ud.set_target('stretch', np.diag([1,4]),nframes)\n    # user FuncAnimation to generate frames of animation\n    anim = FuncAnimation(fig, ud, frames=nframes, blit=True)\n    # save animation as *.mp4\n    anim.save('2d_gaussian_2.mp4', fps=20, dpi=400, codec='libx264', bitrate=-1, extra_args=['-pix_fmt', 'yuv420p'])\n# %%\n", "meta": {"hexsha": "342791fa854a7820d7021366ba19e52adf5fb6aa", "size": 5116, "ext": "py", "lang": "Python", "max_stars_repo_path": "gaussian2d.py", "max_stars_repo_name": "NeoNeuron/slide-videos", "max_stars_repo_head_hexsha": "e41de75324c7ae441feb6302f1f816d8d299a316", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-12T07:14:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T07:14:16.000Z", "max_issues_repo_path": "gaussian2d.py", "max_issues_repo_name": "NeoNeuron/slide-videos", "max_issues_repo_head_hexsha": "e41de75324c7ae441feb6302f1f816d8d299a316", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gaussian2d.py", "max_forks_repo_name": "NeoNeuron/slide-videos", "max_forks_repo_head_hexsha": "e41de75324c7ae441feb6302f1f816d8d299a316", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7762237762, "max_line_length": 176, "alphanum_fraction": 0.5431978108, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759489, "lm_q2_score": 0.897695283896349, "lm_q1q2_score": 0.8525137162143083}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\ne = np.e\npi = np.pi\n\ndef VolumeNSphere(N, R = 1):\n    '''Computes the volume of a N Sphere (using Stearling aproximation) in a N dimensionl space as a function od N\n    (dimension) and R (radius).'''\n    term1 = 1 / (np.sqrt(N * pi))\n    term2 = np.power( (2 * pi * e)/N, N/2 )\n    expresion = term1 * term2 * np.power(R, N)\n    return expresion\n\n\nx_axis = [x for x in range(1, 50)]\nRadious = [(0.9, 'orange'),\n           (1, 'red'),\n           (1.1, 'purple'),\n           #(1.2, 'green'),\n           #(1.5,'indigo'),\n          # (1.75, 'black')\n           ]\n\ndef DimensionRadious():\n    plt.figure(figsize = (20, 14))\n    for Rad in Radious:\n        plt.plot(x_axis,\n                 [VolumeNSphere(x, R=Rad[0]) for x in x_axis],\n                 'ro',\n                 linestyle='-',\n                 label = 'Radius: ' + str(Rad[0]),\n                 c = Rad[1]\n                 )\n\n    plt.title('Evolution of the volume of the Sphere as dimension grows for different radious')\n    plt.ylabel('Volume')\n    plt.xlabel('Dimension')\n    plt.legend()\n    plt.savefig('VolumeNSphere')\n    plt.show()\n\ndef Radious1():\n    plt.figure(figsize=(20, 14))\n    plt.plot(x_axis,\n             [VolumeNSphere(N = x, R = 1) for x in x_axis],\n             'ro',\n             linestyle='-',\n             )\n    plt.title('Volume of a N-Sphere of radius 1')\n    plt.xlabel('Dimension')\n    plt.ylabel('Volumen')\n    plt.savefig('Volume_N_Sphere_R1')\n    plt.show()\n\nDimensionRadious()", "meta": {"hexsha": "509b6aace7ecb8b43730ec1e55fbd8fc84b0d096", "size": 1520, "ext": "py", "lang": "Python", "max_stars_repo_path": "Images and auxiliar graphics/SphereVolumeExploration.py", "max_stars_repo_name": "MGijon/Master-s-thesis", "max_stars_repo_head_hexsha": "187bcca34a8c72c21fd78ca1684ae1a661c76961", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Images and auxiliar graphics/SphereVolumeExploration.py", "max_issues_repo_name": "MGijon/Master-s-thesis", "max_issues_repo_head_hexsha": "187bcca34a8c72c21fd78ca1684ae1a661c76961", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Images and auxiliar graphics/SphereVolumeExploration.py", "max_forks_repo_name": "MGijon/Master-s-thesis", "max_forks_repo_head_hexsha": "187bcca34a8c72c21fd78ca1684ae1a661c76961", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1428571429, "max_line_length": 114, "alphanum_fraction": 0.5289473684, "include": true, "reason": "import numpy", "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514736, "lm_q2_score": 0.8976952825278492, "lm_q1q2_score": 0.8525137136359412}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import hamming, triang, blackmanharris\nfrom scipy.fftpack import fft, ifft\nimport math\nimport sys, os, functools, time\n\nsys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../software/models/'))\n\nimport stft as STFT\nimport sineModel as SM\nimport utilFunctions as UF\n\nM = 256\nN = 256\nhN = N//2\nhM = M//2\nfs = 44100\nf0 = 5000.0\nA0 = 1\nph = 1.5\nt = np.arange(-hM,hM)/float(fs)\nx = A0 * np.cos(2*np.pi*f0*t+ph)\n\nw = hamming(M)\nxw = x*w\nfftbuffer = np.zeros(N) \nfftbuffer[0:M] = xw\nX = fft(fftbuffer) \nmX = abs(X)\npX = np.angle(X[0:hN])\n\npowerX = sum(2*mX[0:hN]**2)/N\n\nmask = np.zeros(N//2)\nmask[int(N*f0/fs-2*N/float(M)):int(N*f0/fs+3*N/float(M))] = 1.0\nmY = mask*mX[0:hN]\npowerY = sum(2*mY[0:hN]**2)/N\n\nY = np.zeros(N, dtype = complex)\nY[:hN] = mY * np.exp(1j*pX) \nY[hN+1:] = mY[:0:-1] * np.exp(-1j*pX[:0:-1]) \n \ny = ifft(Y)\nSNR1 = -10*np.log10((powerX-powerY)/(powerX))\n\nfreqaxis = fs*np.arange(0,N/2)/float(N)\ntaxis = np.arange(N)/float(fs) \n\nplt.figure(1, figsize=(9, 6))\nplt.subplot(3,2,1)\nplt.plot(20*np.log10(mY[:hN])-max(20*np.log10(mY[:hN])), 'r', lw=1.5)\nplt.title ('mX, mY (main lobe); Hamming')\nplt.plot(20*np.log10(mX[:hN])-max(20*np.log10(mX[:hN])), 'r', lw=1.5, alpha=.2)\nplt.axis([0,hN,-120,0])\n\nplt.subplot(3,2,3)\nplt.plot(y[0:M], 'b', lw=1.5)\nplt.axis([0,M,-1,1])\nplt.title ('y (synthesis of main lobe)')\n\nplt.subplot(3,2,5)\nyerror = xw - y\nplt.plot(yerror, 'k', lw=1.5)\nplt.axis([0,M,-.003,.003])\nplt.title (\"error function: x-y; SNR = ${%d}$ dB\" %(SNR1))\n\nw = blackmanharris(M)\nxw = x*w\nfftbuffer = np.zeros(N) \nfftbuffer[0:M] = xw\nX = fft(fftbuffer) \nmX = abs(X) \npX = np.angle(X[0:hN])\n\npowerX = sum(2*mX[0:hN]**2)/N\n\nmask = np.zeros(N//2)\nmask[int(N*f0/fs-4*N/float(M)):int(N*f0/fs+5*N/float(M))] = 1.0\nmY = mask*mX[0:hN]\npowerY = sum(2*mY[0:hN]**2)/N\n\nY = np.zeros(N, dtype = complex)\nY[:hN] = mY * np.exp(1j*pX) \nY[hN+1:] = mY[:0:-1] * np.exp(-1j*pX[:0:-1]) \n \ny = ifft(Y)\nSNR2 = -10*np.log10((powerX-powerY)/(powerX))\n\nplt.subplot(3,2,2)\nplt.plot(20*np.log10(mY[:hN])-max(20*np.log10(mY[:hN])), 'r', lw=1.5)\nplt.title ('mX, mY (main lobe); Blackman Harris')\nplt.plot(20*np.log10(mX[:hN])-max(20*np.log10(mX[:hN])), 'r', lw=1.5, alpha=.2)\nplt.axis([0,hN,-120,0])\n\nplt.subplot(3,2,4)\nplt.plot(y[0:M], 'b', lw=1.5)\nplt.axis([0,M,-1,1])\nplt.title ('y (synthesis of main lobe)')\n\nplt.subplot(3,2,6)\nyerror2 = xw - y\nplt.plot(yerror2, 'k', lw=1.5)\nplt.axis([0,M,-.003,.003])\nplt.title (\"error function: x-y; SNR = ${%d}$ dB\" %(SNR2))\n\nplt.tight_layout()\nplt.savefig('spec-sine-synthesis-lobe.png')\nplt.show()\n", "meta": {"hexsha": "88e43c9921d7974c5f9763147a4383b1f9e738ab", "size": 2623, "ext": "py", "lang": "Python", "max_stars_repo_path": "stanford/sms-tools/lectures/05-Sinusoidal-model/plots-code/spec-sine-synthesis-lobe.py", "max_stars_repo_name": "phunc20/dsp", "max_stars_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-12T18:32:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T18:32:06.000Z", "max_issues_repo_path": "stanford/sms-tools/lectures/05-Sinusoidal-model/plots-code/spec-sine-synthesis-lobe.py", "max_issues_repo_name": "phunc20/dsp", "max_issues_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stanford/sms-tools/lectures/05-Sinusoidal-model/plots-code/spec-sine-synthesis-lobe.py", "max_forks_repo_name": "phunc20/dsp", "max_forks_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8454545455, "max_line_length": 103, "alphanum_fraction": 0.6157072055, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152282, "lm_q2_score": 0.8991213691605412, "lm_q1q2_score": 0.852506003518844}}
{"text": "\"\"\"\nGood to use when the number of features are less than 1000.\nExtremely efficient than gradient decent when above condition is satisfied\n\"\"\"\n\nimport numpy as np\n\nnp.random.seed(111)\n\n'''\nThe data is generated adding noise to the values from  y = 1 + 0.5x1 + 3x2 -2x3 equation\nThe expectation of the auto encoder is to get the values  w0, w1, w2 and w3  closer to 1, 0.5, 3 and -2  respectively\n'''\n\n'''generate random x1, x2, x3 values'''\nx1 = np.random.random((1, 50))[0]\nx2 = np.random.random((1, 50))[0]\nx3 = np.random.random((1, 50))[0]\n\n'''define x0 as 1. To be multiplied with w0 values'''\nx0 = np.ones((1, 50))[0]\n\n'''create X_train which is has x1, x2, x3 as columns and 50 rows'''\nX = np.c_[x0, x1, x2, x3]\n\n'''get the reference y value'''\ny_reference = 1 + 0.5*x1 + 3*x2 -2*x3\n\n'''add noise to the reference y value'''\ny = y_reference + np.sqrt(0.01) * np.random.random((1, 50))[0]\n\n'''Get X transpose'''\nX_t = X.transpose()\n\n'''Normal Equation'''\nW = np.linalg.pinv(X_t.dot(X)).dot(X_t).dot(y)\n\nprint('\\nNormal Equation optimization completed')\nprint('W Expected : [1, 0.5, 3, -2]' + '  Learned : ' + str(W))\n", "meta": {"hexsha": "470a23b58eac9bf74da1d50d36d2e2b482e0da1d", "size": 1122, "ext": "py", "lang": "Python", "max_stars_repo_path": "normal_equation_simple_linear_regression.py", "max_stars_repo_name": "eshanmherath/linear-regression", "max_stars_repo_head_hexsha": "5b473586679a4b4594706faeb2bb7e4922c7ab38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-09T04:19:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T04:19:46.000Z", "max_issues_repo_path": "normal_equation_simple_linear_regression.py", "max_issues_repo_name": "eshanmherath/linear-regression", "max_issues_repo_head_hexsha": "5b473586679a4b4594706faeb2bb7e4922c7ab38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "normal_equation_simple_linear_regression.py", "max_forks_repo_name": "eshanmherath/linear-regression", "max_forks_repo_head_hexsha": "5b473586679a4b4594706faeb2bb7e4922c7ab38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.05, "max_line_length": 117, "alphanum_fraction": 0.6568627451, "include": true, "reason": "import numpy", "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214532237354, "lm_q2_score": 0.8840392909114836, "lm_q1q2_score": 0.8524980537186424}}
{"text": "import numpy as np\r\nfrom math import *\r\n\r\ndef f_of_x(func_str, endpoints):\r\n    ''' User-entered Function\r\n\r\n    Takes a mathematical expression as string and computes its result\r\n\r\n    Args:\r\n        func_str (string)     : the function to be analized [f(x)]\r\n        endpoints (float list): coordinates of the partitions\r\n    \r\n    Returns:\r\n        A new list of endpoints\r\n    '''\r\n    \r\n    #result = [ (pow(1+(cos(i)), 1./3)) for i in endpoints]\r\n    result = [ eval(func_str) for x in endpoints]\r\n\r\n    return result\r\n\r\ndef mid_rule(interval, delta_x, f_of_x, func_str):\r\n    ''' Midpoint Rule of Integration\r\n\r\n    Approximates the area between a given curve f(x) and the line x=0 within a closed interval [a,b] using the Midpiont Rule\r\n    \r\n    Args:\r\n        interval (int list): [a,b]\r\n        my_func (function) : the function to integrate\r\n        delta_x (float)    : length of partitions\r\n    \r\n    Returns:\r\n        Approximate are under f(x) within the interval [a,b]\r\n    \r\n    '''\r\n    endpoints = [ (.5* ( (i-delta_x) + i)) for i in np.arange(interval[0]+delta_x, interval[1]+delta_x, delta_x)]\r\n\r\n    endpoints = f_of_x(func_str, endpoints)\r\n    result = np.sum(endpoints)\r\n    result *= delta_x\r\n    \r\n    return result\r\n\r\ndef trap_rule(interval, delta_x, endpoints):\r\n    ''' Trapezoidal Rule of Integration\r\n\r\n    Approximates the area between a given curve f(x) and the line x=0 within a closed interval [a,b] using the Trapezoidal Rule\r\n    \r\n    Args:\r\n        interval  (int list): [a,b]\r\n        my_func   (function): the function to integrate\r\n        delta_x   (float): length of partitions\r\n        endpoints (float list): enpoints of the partitions\r\n    \r\n    Returns:\r\n        Approximate are under f(x) within the interval [a,b]\r\n    \r\n    '''\r\n    \r\n    # the first and last term stay unchanged. This is why the for loop only goes through indices 1 to (and including) len(endpoints)-2 \r\n    for i in range(1,len(endpoints)-1):\r\n        endpoints[i] = endpoints[i]*2\r\n\r\n    #endpoints = [endpoints[i]*2 for i in range(1,len(endpoints)-1)]\r\n    \r\n    result = np.sum(endpoints)\r\n    result *= (delta_x/2)\r\n\r\n    return result\r\n\r\ndef simpsons_rule(interval, delta_x, endpoints):\r\n    ''' Simpson's Rule of Integration\r\n\r\n    Approximates the area between a given curve f(x) and the line x=0 within a closed interval [a,b] using Simpson's Rule\r\n    \r\n    Args:\r\n        interval  (int list): [a,b]\r\n        my_func   (function): the function to integrate\r\n        delta_x   (float): length of partitions\r\n        endpoints (float list): enpoints of the partitions\r\n    \r\n    Returns:\r\n        Approximate are under f(x) within the interval [a,b]\r\n    \r\n    '''\r\n\r\n    # the first and last terms stay unchanged. This is why the for loop only goes through indices 1 to endpoints-2\r\n    for i in range(1,len(endpoints)-1):\r\n        \r\n        # if my index is odd, multiply by four, otherwise multiply by two.\r\n        if (i%2)==1:\r\n            endpoints[i] = endpoints[i]*4\r\n        else:\r\n            endpoints[i] = endpoints[i]*2\r\n\r\n    result = sum(endpoints)\r\n    result *= (delta_x/3)\r\n\r\n    return result\r\n\r\ndef compute(n, interval, func_str):\r\n    ''' Main function\r\n\r\n    Controls the flow of information on the file; helps minimize redundant functionalities.\r\n\r\n    Args:\r\n        n (int)            : number of partitions\r\n        interval (int list): [a,b]\r\n        func_str (str)     : string version of the formula entered by the user.\r\n    \r\n    Returns:\r\n        The area under the cruve and within the interval using all three methods of approximate integration\r\n    '''\r\n\r\n    delta_x = (interval[1] - interval[0])/n\r\n    \r\n    # Bescause two different rules use the same set on endpoints, delegate this computation, so it only happens once.\r\n    endpts = [ i for i in np.arange(interval[0], interval[1] + delta_x, delta_x)]\r\n\r\n    #enpoints_max = fofx2(my_func, endpts)\r\n    endpts = f_of_x(func_str, endpts)\r\n    endpts_copy = endpts.copy()\r\n\r\n    by_midpoint = round(mid_rule(interval, delta_x, f_of_x, func_str), 6)\r\n    by_trapezoidal = round(trap_rule(interval, delta_x, endpts), 6)\r\n    by_simpsons = round(simpsons_rule(interval, delta_x, endpts_copy), 6)   \r\n\r\n    return by_midpoint, by_trapezoidal, by_simpsons\r\n", "meta": {"hexsha": "74942a135c4aa25d00eaeefda5bcb0ec6a487ab0", "size": 4270, "ext": "py", "lang": "Python", "max_stars_repo_path": "aproximation_rules.py", "max_stars_repo_name": "walmonte/Aprox-Integration", "max_stars_repo_head_hexsha": "0c978b422331174bd86859bd92eceb511cc026d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aproximation_rules.py", "max_issues_repo_name": "walmonte/Aprox-Integration", "max_issues_repo_head_hexsha": "0c978b422331174bd86859bd92eceb511cc026d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aproximation_rules.py", "max_forks_repo_name": "walmonte/Aprox-Integration", "max_forks_repo_head_hexsha": "0c978b422331174bd86859bd92eceb511cc026d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1007751938, "max_line_length": 136, "alphanum_fraction": 0.6262295082, "include": true, "reason": "import numpy", "num_tokens": 1050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214501476359, "lm_q2_score": 0.8840392893839085, "lm_q1q2_score": 0.8524980495261762}}
{"text": "import numpy as np\nimport timeit\n\nMATRIX = np.array([[1, 1],\n                   [1, 0]])\n\ndef log_fibonacci(num):\n    result = np.copy(MATRIX)\n\n    # We create a stack, floor dividing by 2 each time. \n    # The length of the stack determines how many matrix multiplications to do\n    stack = [num]\n    while stack[len(stack) - 1] != 1:\n        last_ele = stack[len(stack) - 1]\n        stack.append(last_ele // 2 )\n\n    # The last element, which will be one, does not provide any useful info.\n    stack.pop()\n\n    while len(stack) != 0:\n        result = np.matmul(result, result)\n\n        # If smallest integer is odd, then we multiply by MATRIX once more\n        # to match the necessary power on result\n        if stack.pop() % 2 == 1:\n        # Do one final multiplication in this cycle if we have an odd number\n            result = np.matmul(result, MATRIX)\n\n    return result[0][1]\n\ndef linear_fibonacci(num):\n    # The matrix above to the nth power will have the nth fibonacci\n    # number in its second and third entries.\n    result = np.copy(MATRIX)\n\n    for _ in range(num - 1):\n        result = np.matmul(result, MATRIX)\n\n    # Could've used: 'return result[1][0]'\n    return result[0][1]\n\ndef main():\n    print('Input a number to find that numbered entry in the Fibonacci sequence!')\n    num = int(input())\n    fib = linear_fibonacci(num)\n    print(f'Fibonacci number {num} is {fib}')\n    log_fig = log_fibonacci(num)\n    print(f'Log(n) time fibonacci number {num} is {log_fig}')\n\nif __name__ == '__main__':\n    main()", "meta": {"hexsha": "22e4b557fee6d27cc2ba749cb49376d7700ede5f", "size": 1528, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/d070_efficient_fibonacci/efficient_fibonacci.py", "max_stars_repo_name": "yashaslokesh/100-Days-Of-Code", "max_stars_repo_head_hexsha": "a5aadfb41675224828c6fce22abc5ab0263141c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-07-03T15:52:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T19:26:32.000Z", "max_issues_repo_path": "Python/d070_efficient_fibonacci/efficient_fibonacci.py", "max_issues_repo_name": "yashaslokesh/100-Days-Of-Code", "max_issues_repo_head_hexsha": "a5aadfb41675224828c6fce22abc5ab0263141c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/d070_efficient_fibonacci/efficient_fibonacci.py", "max_forks_repo_name": "yashaslokesh/100-Days-Of-Code", "max_forks_repo_head_hexsha": "a5aadfb41675224828c6fce22abc5ab0263141c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-07-31T06:37:41.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-31T06:37:41.000Z", "avg_line_length": 29.9607843137, "max_line_length": 82, "alphanum_fraction": 0.6295811518, "include": true, "reason": "import numpy", "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214470715364, "lm_q2_score": 0.8840392802184581, "lm_q1q2_score": 0.852498037968343}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.interpolate\n\nfrom functions import *\n\n\n\n\n##### Plot basic spline ######\nx = np.array([0, 0.1, 0.2, 0.5, 0.7, 1.0])\n\nspline = cubic_spline( x, x**3, 0, 3 )\n\nx = np.linspace(0,1,50)\ny = x**3 + 0.1\n\nyhat = spline(x)\n\nplt.plot(x, y, label='x^3 + 0.1')\nplt.plot(x, yhat, label='Spline')\n\nplt.legend()\nplt.gca().set_title('Spline approximation of cubic')\nplt.savefig('spline_vs_cubic.png')\nplt.close()\n\n\n\n\n\n\n\n\n\n##### Plot periodic spline ######\nf = lambda x: np.sin(2*np.pi * (x + 0.2))\ninterval = [0,1]\n\nd = 0.01\n\n# Evaluation mesh\nx = np.linspace(0, 1, 10)\n\n# Spline construction\nspline = periodic_cubic_spline( x, f(x) )\n# Ensure periodic\nps = lambda x: spline( x % (interval[1] - interval[0]) )\n# Create this sd_ps thingy\nsd_ps = lambda x: d**-2 * (ps(x-d) - 2*ps(x) + ps(x+d))\n    \n\nx = np.linspace( 0, 1, 100)\n\nfig, axs = plt.subplots(2, figsize=(7,5))\n\naxs[0].plot( x, ps(x), label='ps')\naxs[1].plot( x, sd_ps(x), label='sd_ps')\n\nfor ax in axs:\n    ax.legend()\naxs[0].set_title('Periodic spline PS vs SD_PS')\nplt.savefig('sd_vs_ps.png')\nplt.close()\n\n\n\n\n\n\n####### Plot Error metrics on spline ########\n\n# Our functions\nfs = [ np.sin, lambda x: x**0.5,]\nf_names = ['sin(x)', 'sqrt(x)']\n\n# Function domains\nf_intervals = [[0,np.pi/2.0], [1,4]]\n\n# Function endpoint derivatives\nf_derivs = [[1, 0], [0.5, 1]]\n\n# Subintervals for sampling\nn_intervals = [4, 8, 16, 32]\n\n\nfig, axs = plt.subplots(2, figsize=(7,5), sharex=True)\n\n\nfor i, f, derivs, interval in zip(range(len(fs)), fs, f_derivs, f_intervals):\n    \n    abs_error = []\n    \n    for n in n_intervals:\n        \n        # Create mesh\n        x_spline = np.linspace(interval[0], interval[1], n)\n    \n        # Spline construction\n        spline = cubic_spline(\n            x_spline,\n            f(x_spline),\n            derivs[0],\n            derivs[1]\n        )\n        \n        # Spline error sample\n        # We evaluate on 10x as many points as the construction mesh\n        x_sample = np.linspace(interval[0], interval[1], 10*n)\n        \n        abs_error.append(\n            # Take the highest value\n            np.max(\n                # of the absolute error\n                np.abs(spline(x_sample) - f(x_sample))\n            )\n        )\n    \n    # Plot that error\n    axs[i].plot(\n        np.log10(n_intervals),\n        np.log10(abs_error),\n        label=f_names[i],\n    )\n    # Make sure name is present\n    axs[i].legend()\n    \n    \naxs[0].set_title('Log(number of intervals) vs Log(maximum error)')\nfig.tight_layout()\nplt.savefig('spline_error.png')\n", "meta": {"hexsha": "d2fa5d54ade38b4e492c913da7a10ae8e7227938", "size": 2576, "ext": "py", "lang": "Python", "max_stars_repo_path": "numerical_eqs/interp/spline/run.py", "max_stars_repo_name": "alienbrett/numerical-eqs-collection", "max_stars_repo_head_hexsha": "23619bf379d53ce0facb63be08ee6a3902d404d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numerical_eqs/interp/spline/run.py", "max_issues_repo_name": "alienbrett/numerical-eqs-collection", "max_issues_repo_head_hexsha": "23619bf379d53ce0facb63be08ee6a3902d404d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical_eqs/interp/spline/run.py", "max_forks_repo_name": "alienbrett/numerical-eqs-collection", "max_forks_repo_head_hexsha": "23619bf379d53ce0facb63be08ee6a3902d404d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5151515152, "max_line_length": 77, "alphanum_fraction": 0.5772515528, "include": true, "reason": "import numpy,import scipy", "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214470715363, "lm_q2_score": 0.8840392786908831, "lm_q1q2_score": 0.8524980364952696}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.integrate import ode\n\n# using scipy.integrate.ode\ndef ode_sol(n0, decay_const, t_final, n_t_steps):\n    intermediate_points = n_t_steps\n    t3 = np.linspace(0,t_final, intermediate_points)\n    n3 = np.zeros(t3.shape, float) \n    def f(t, y, decay_const):\n        return  - decay_const * y \n    solver = ode(f).set_integrator('dopri5') # runge-kutta of order (4)5\n    y0 = n0\n    t0 = 0\n    solver.set_initial_value(y0, t0)\n    solver.set_f_params(decay_const)\n    k=1\n    n3[0] = n0\n    while solver.successful() and solver.t < t_final:\n        n3[k] = solver.integrate(t3[k])[0]\n        k += 1  # k = k + 1\n    n3r = n3 / n0\n    return n3, n3r, t3\n\n# Analytical solution\nna, nar, ta = analytical_solution(n0=10000, decay_const=1.54e-1, t_final=20, n_t_steps=10)\n# Euler method\nne, ner, te = euler_method(n0=10000, decay_const=1.54e-1, t_final=20, n_t_steps=10)\nnuler_rel_error = 100*(ne-na)/na\n# runge-kutta of order (4)5\nn_ode, n_oder, tode = ode_sol(n0=10000, decay_const=1.54e-1, t_final=20, n_t_steps=10)\node_rel_error = 100*(n_ode - na) / na\n\n# Make the plot\nfig = plt.figure(figsize=(8,5))\nax1 = fig.add_subplot(1, 2, 1)\nax1.plot(ta, nar, linestyle=\"-\", linewidth=2, label='Analytical Solution', c='#ff464a')\nax1.plot(te, ner, linestyle=\"--\", linewidth=2, label='Euler method', c='#4881e9')\nax1.plot(tode, n_oder, linestyle=\"--\", linewidth=2, label='Runge-Kutta of order (4)5', c='#342a77')\nax1.set_ylabel('Relative Number of $^{238}$U atoms')\nax1.set_xlabel('Time in bilion years')  \nax1.legend()\n\nax2 = fig.add_subplot(1, 2, 2)\nax2.plot(te, euler_rel_error, linestyle=\"-\", linewidth=2, c='#4881e9', label='Euler method')\nax2.plot(tode, ode_rel_error, linestyle=\"-\", linewidth=2, c='#342a77', label='Runge-Kutta of order (4)5')\nax2.set_ylabel('Relative Error, in %')\nax2.set_xlabel('Time in bilion years')  \nax2.legend()\n\nfig.tight_layout()\n\n\n\n", "meta": {"hexsha": "213b35329d648343d37e0c8c32c7a39c9f964f37", "size": 1914, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/chapter_08/listing_08_05.py", "max_stars_repo_name": "guinslym/python_earth_science_book", "max_stars_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80, "max_stars_repo_stars_event_min_datetime": "2021-04-19T10:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:34:47.000Z", "max_issues_repo_path": "code/chapter_08/listing_08_05.py", "max_issues_repo_name": "guinslym/python_earth_science_book", "max_issues_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/chapter_08/listing_08_05.py", "max_forks_repo_name": "guinslym/python_earth_science_book", "max_forks_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2021-04-25T03:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:06:19.000Z", "avg_line_length": 34.8, "max_line_length": 105, "alphanum_fraction": 0.6807732497, "include": true, "reason": "import numpy,from scipy", "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.8962513655129178, "lm_q1q2_score": 0.8524625122243665}}
{"text": "#!/usr/bin/env python\nimport sys\n\n##########################################################################\n## Can you prove that De Morgan's laws work in Python?\n##########################################################################\n\na = set([\"A\",\"B\",\"C\",\"D\"])\nb = set([\"C\",\"D\",\"E\",\"F\"])\nsample_space = set([\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\"])\n\n## The complement of the union of two sets is the same as the intersection of their complements\npart1 = sample_space.difference(a.union(b))\npart2 = sample_space.difference(b).intersection(sample_space.difference(a))\nprint(part1==part2)\n\n## The complement of the intersection of two sets is the same as the union of their complements\npart1 = sample_space.difference(b).union(sample_space.difference(a))\npart2 = sample_space.difference(a.intersection(b))\nprint(part1==part2)\n\n## A = (X < 90) and B  is between 90 and 95\n\n# The union or  (A \\cap C) = (250 \\leq chol \\leq 280)\n    \n# `P(250 \\leq chol \\leq 299) + P(chol \\geq 300) = 0.2 + 0.1 = 0.3`. chol \\leq 280)\n    \n\n##########################################################################\n## combinations and permutations\n##########################################################################\nfrom math import factorial\nfrom itertools import combinations,permutations\nfrom scipy.misc import comb\n\n## We have sampler plates that hold 4 beers.  How many different ways can we combine these beers?\nlefthand_beers = [\"Milk Stout\", \"Good Juju\", \"Fade to Black\", \"Polestar Pilsner\"]\nlefthand_beers += [\"Black Jack Porter\", \"Wake Up Dead Imperial Stout\",\"Warrior IPA\"]\nn = len(lefthand_beers)\nk = 4\n\ndef comb(n, k):\n    return factorial(n) / (factorial(k) * factorial(n - k))\n\nprint(\"There are %s combinations\"%comb(n,k))\n\n## Print a list of these pairs so we can identify the bad ones?\nfor c in combinations(lefthand_beers,4):\n    print(c)\n    \n## on a team of 12 baseball players how many batting orders?    \ndef permu(n,k):\n    return factorial(n) / factorial(n - k)\n\nprint(permu(12,9))\n\n##########################################################################\n## probability\n##########################################################################\n\n## probability of a queen\np_queen = 1.0/52 + 1.0/52 + 1.0/52 + 1.0/52\np_queen_or_spade = 4.0/52 + 13/52 - 1.0/52 \n\n## conditional probability problem\n#print(\"prob of tails: %s\"%1 - ((1./3 + (1./3 * 1./4)) / (1. / 2)))\nprint(\"prob of heads: %s\"%((1./3 + (1./3 * 1./4)) / (1. / 2)))\n\nimport random\nimport pandas as pd\n\ncoins = ['HH', 'HT', 'TT']\nresults = []\nfor i in range(10):\n    coin = random.choice(coins)\n    results.append([random.choice(coin) for j in [1,2]])\n\nprint(results)    \n\ndf = pd.DataFrame(results, columns=['first', 'second']) == 'H'\n#print df\ndf.groupby('first').mean()\n\nsys.exit()\n", "meta": {"hexsha": "c95cf85cc2d5f3880997ebe8aaaccac73fae5274", "size": 2751, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/answers.py", "max_stars_repo_name": "ljbelenky/stats-shortcourse", "max_stars_repo_head_hexsha": "762328706758fb26e25ae466dc08b737b96d21fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-17T12:50:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-17T12:50:24.000Z", "max_issues_repo_path": "src/answers.py", "max_issues_repo_name": "bucklerchica/stats-shortcourse", "max_issues_repo_head_hexsha": "875e6a20183833ca186af51a0649c308ce531fbc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/answers.py", "max_forks_repo_name": "bucklerchica/stats-shortcourse", "max_forks_repo_head_hexsha": "875e6a20183833ca186af51a0649c308ce531fbc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-22T23:10:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-22T23:10:59.000Z", "avg_line_length": 32.3647058824, "max_line_length": 97, "alphanum_fraction": 0.5554343875, "include": true, "reason": "from scipy", "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.8887587949656841, "lm_q1q2_score": 0.8524568088271266}}
{"text": "#########################\n##                     ##\n## Irving Gomez Mendez ##\n##     May 09, 2021    ##\n##                     ##\n#########################\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport sympy as sym\nfrom sympy.functions import exp\nfrom scipy.optimize import least_squares\nfrom scipy.stats import norm, t\n\nalpha = 0.05\n\ndat = pd.read_csv('ChickWeight.csv')\ndat = dat.drop(dat.columns[0], axis=1)\ndat['Diet'] = dat['Diet'].astype('category')\n\nplt.figure(figsize=(10,7.5))\nsns.scatterplot(x=dat['Time'], y=dat['weight'], hue=dat['Diet'], s=50)\n\nplt.figure(figsize=(10,7.5))\nsns.lineplot(\n    x=dat['Time'], y=dat['weight'],\n    hue=dat['Diet'], style=dat['Diet']\n)\n## Let's select just the diet=3\ndat_example = dat.loc[dat['Chick']==3, ['weight','Time']].reset_index(drop=True)\n\nplt.figure(figsize=(10,7.5))\nsns.lineplot(x=dat_example['Time'], y=dat_example['weight'])\nsns.scatterplot(x=dat_example['Time'], y=dat_example['weight'])\n# We are going to model using a logistic growth\nM, r, b, t = sym.symbols('M r b t')\nf = M/(1+exp(-r*(t-b)))\n\nsym.diff(f, M)\nsym.diff(f, r)\nsym.diff(f, b)\n\ndef f(t, M, r, b):\n    return(M/(1+np.exp(-r*(t-b))))\n\ndef F_1(t,M,r,b):\n    return(1/(1+np.exp(-r*(t-b))))\n\ndef F_2(t,M,r,b):\n    return((M*(t-b)*np.exp(-r*(t-b)))/(1+np.exp(-r*(t-b)))**2)\n\ndef F_3(t,M,r,b):\n    return((-M*r*np.exp(-r*(t-b)))/(1+np.exp(-r*(t-b)))**2)\n\ny = dat_example['weight']\nX = dat_example['Time']\nn = len(y)\np = 3\n\n# Initialize\nM0 = y.max()\nr0 = 0.1\nb0 = 15\n\ntt = [M0,r0,b0]\n\ntolm   = 1e-6       # tolerance (minimum norm of the difference of the betas)\niterm  = 100        # maximum number of iterations\ntolera = 1          # initialize tolera\nitera  = 0          # initialize ittera\nhisto  = tt          # initialize beta upgrade\n\nwhile((tolera > tolm) and (itera < iterm)):\n    F_matrix = np.vstack([\n        F_1(dat_example['Time'], tt[0], tt[1], tt[2]),\n        F_2(dat_example['Time'], tt[0], tt[1], tt[2]),\n        F_3(dat_example['Time'], tt[0], tt[1], tt[2])\n    ])\n    F_matrix = F_matrix.T\n    y_hat = f(dat_example['Time'], tt[0], tt[1], tt[2])\n    delta = np.linalg.solve(F_matrix.T @ F_matrix, F_matrix.T @ (y-y_hat))\n    tt = tt + delta\n    tolera = np.sqrt(sum(delta**2))\n    histo  = np.vstack([histo, tt])\n    itera  = itera+1\n\nhisto\n\n## Using scipy least squares\ndef logistic_gowth(theta, t):\n    return theta[0] / (1 + np.exp(- theta[1] * (t - theta[2])))\n\ndef fun(theta):\n    return logistic_gowth(theta, X) - y\n\ntheta0 = [M0,r0,b0]\nlog_growth = least_squares(fun, theta0)\nlog_growth.x\n\nF_matrix\n\nlog_growth.jac\n\n# Getting confidence intervals\nhat_sigma2 = sum((y-y_hat)**2/(n-p))\nvar_params = np.diag(hat_sigma2 * np.linalg.inv(F_matrix.T @ F_matrix))\nvar_params\n\n# Let's get the significance of the estimators\nse_params = np.sqrt(var_params)\nz_score = tt/se_params\np_value = 1-norm.cdf(np.abs(z_score))\n\nz_score\np_value\n\n# predictions\ny_hat = logistic_gowth(theta=log_growth.x, t=X)\n\nplt.figure(figsize=(10,7.5))\nplt.plot(X, y, 'o-', label='data')\nplt.plot(X, y_hat, 'o-', label='estimated')\nplt.xlabel('time')\nplt.ylabel('weight')\nplt.title(\"Weight of a chicken over time\")\nplt.legend(loc='upper left')\n\nlow_pred = y_hat - np.sqrt(hat_sigma2) * t.ppf(1-alpha/2, n-p)\nupp_pred = y_hat + np.sqrt(hat_sigma2) * t.ppf(1-alpha/2, n-p)\n\nplt.figure(figsize=(10,7.5))\nplt.fill_between(X, low_pred, upp_pred, facecolor='green', alpha=0.5, label='Prediction interval')\nplt.plot(X, y, 'o-', label='data')\nplt.plot(X, y_hat, 'o-', label='estimated')\nplt.xlabel('time')\nplt.ylabel('weight')\nplt.title(\"Weight of a chicken over time\")\nplt.legend(loc='upper left')\n\n\n\n###\n", "meta": {"hexsha": "ed26e048e8e3e55b46a11fd4fbb6f8846a5fb729", "size": 3660, "ext": "py", "lang": "Python", "max_stars_repo_path": "content/courses/mod2021/21_non_linear_logistic_growth.py", "max_stars_repo_name": "IrvingGomez/academic-hugo", "max_stars_repo_head_hexsha": "4f6e4ec4aab7a11f477883441b768bb6cf843a9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "content/courses/mod2021/21_non_linear_logistic_growth.py", "max_issues_repo_name": "IrvingGomez/academic-hugo", "max_issues_repo_head_hexsha": "4f6e4ec4aab7a11f477883441b768bb6cf843a9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "content/courses/mod2021/21_non_linear_logistic_growth.py", "max_forks_repo_name": "IrvingGomez/academic-hugo", "max_forks_repo_head_hexsha": "4f6e4ec4aab7a11f477883441b768bb6cf843a9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2413793103, "max_line_length": 98, "alphanum_fraction": 0.6232240437, "include": true, "reason": "import numpy,from scipy,import sympy,from sympy", "num_tokens": 1178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900508, "lm_q2_score": 0.8887587949656841, "lm_q1q2_score": 0.8524568057140469}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun  7 14:17:38 2017\n\n@author: picku\n\"\"\"\n\nimport numpy as np\nfrom scipy import linalg\nfrom collections import OrderedDict\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nstyle.use('ggplot')\n\nclass PolynomialRegression(object):\n        \"\"\"PolynomialRegression \n        \n        Parameters\n        ------------\n        x_pts : 1-d numpy array, shape = [n_samples,]\n        y_pts : 1-d numpy array, shape = [n_samples,]\n    \n        \n        Attributes\n        ------------\n        theta : 1-d numpy array, shape = [polynomial order + 1,] \n            Ceofficients of fitted polynomial, with theta[0] corresponding\n            to the intercept term        \n        \n        method : str , values = 'normal_equation' | 'gradient_descent'\n            Method used for finding optimal values of theta\n        \n        If gradient descent method is chosen:\n        \n            costs : 1-d numpy array,\n                Cost function values for every iteration of gradient descent\n            \n            numIters: int\n                Number of iterations of gradient descent to be performed\n            \n        References\n        ------------\n        https://en.wikipedia.org/wiki/Polynomial_regression\n        \"\"\"\n\n    def __init__(self, x, y):     \n        \n        self.x = x\n        self.y = y      \n    \n    def standardize(self,data):\n        \"\"\" Peform feature scaling\n        Parameters:\n        ------------\n        data : numpy-array, shape = [n_samples,]\n        \n        Returns:\n        ---------\n        Standardized data                  \n        \"\"\"\n\n        return (data - np.mean(data))/(np.max(data) - np.min(data))\n        \n    def hypothesis(self, theta, x):\n        \"\"\" Compute hypothesis, h, where\n        h(x) = theta_0*(x_1**0) + theta_1*(x_1**1) + ...+ theta_n*(x_1 ** n)\n\n        Parameters:\n        ------------\n        theta : numpy-array, shape = [polynomial order + 1,]        \n        x : numpy-array, shape = [n_samples,]\n        \n        Returns:\n        ---------\n        h(x) given theta values and the training data\n\n        \"\"\"       \n        h = theta[0]\n        for i in np.arange(1, len(theta)):\n            h += theta[i]*x ** i        \n        return h        \n        \n    def computeCost(self, x, y, theta):\n        \"\"\" Compute value of cost function J \n        \n        Parameters:\n        ------------\n        x : numpy array, shape = [n_samples,]\n        y : numpy array, shape = [n_samples,]\n        \n        Returns:\n        ---------\n        Value of cost function J at value theta given the training data\n        \n        \"\"\"    \n        m = len(y)  \n        h = self.hypothesis(theta, x)\n        errors = h-y\n        \n        return (1/(2*m))*np.sum(errors**2) \n        \n    def fit(self, method = 'normal_equation', order = 1, tol = 10**-3, numIters = 20, learningRate = 0.01):\n        \n        \"\"\"Fit theta to the training data\n        \n        Parameters\n        -----------\n        method: string, values = 'normal_equation' | 'gradient_descent'\n             Indicates method for which polynomial regression will be performed\n            \n        order: int, optional\n             Order of polynomial fit. Defaults to 1 (linear fit)\n             \n        numIters: int, optional\n             Number of iterations of gradient descent to be performed\n            \n        learningRate: float, optional\n             \n        tol : float, optional\n            Value indicating the cost value (J(theta)) at which\n            gradient descent should terminated. Defaults to 10 ** -3\n            \n        Returns:\n        -----------\n        self : object\n        \n        \"\"\"\n\n        if method == 'normal_equation': \n            d = {}\n            d['x' + str(0)] = np.ones([1,len(x_pts)])[0]    \n            for i in np.arange(1, order+1):                \n                d['x' + str(i)] = self.x ** (i)        \n                \n            d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n            X = np.column_stack(d.values())  \n\n            theta = np.matmul(np.matmul(linalg.pinv(np.matmul(np.transpose(X),X)), np.transpose(X)), self.y)\n\n        elif method == 'gradient_descent':\n                \n            d = {}\n            d['x' + str(0)] = np.ones([1,len(x_pts)])[0]    \n            for i in np.arange(1, order+1):                \n                d['x' + str(i)] = self.standardize(self.x ** (i))      \n                \n            d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n            X = np.column_stack(d.values())  \n                \n            m = len(self.x)\n            theta = np.zeros(order + 1)           \n            costs = []\n            for i in range(numIters):\n             \n                h = self.hypothesis(theta, self.x)       \n                errors = h-self.y\n                theta += -learningRate * (1/m)*np.dot(errors, X)\n                cost = self.computeCost(self.x, self.y, theta)\n                costs.append(cost)         \n                #tolerance check\n                if cost < tol:\n                    break\n                \n            self.costs = costs\n            self.numIters = numIters\n            \n        self.method = method    \n        self.theta = theta        \n\n        return self\n        \n    def plot_predictedPolyLine(self):\n        \"\"\"Plot predicted polynomial line using values of theta found\n        using normal equation or gradient descent method\n        \n        Returns\n        -----------       \n        matploblib figure\n        \"\"\"        \n        plt.figure()\n        plt.scatter(self.x, self.y, s = 30, c = 'b') \n        line = self.theta[0] #y-intercept \n        label_holder = []\n        label_holder.append('%.*f' % (2, self.theta[0]))\n        for i in np.arange(1, len(self.theta)):            \n            line += self.theta[i] * self.x ** i \n            label_holder.append(' + ' +'%.*f' % (2, self.theta[i]) + r'$x^' + str(i) + '$') \n\n        plt.plot(self.x, line, label = ''.join(label_holder))        \n        plt.title('Polynomial Fit: Order ' + str(len(self.theta)-1))\n        plt.xlabel('x')\n        plt.ylabel('y') \n        plt.legend(loc = 'best')      \n\n    def plotCost(self):\n        \"\"\"Plot number of gradient descent iterations verus cost function, J,\n        values at values of theta\n        \n        Returns\n        -----------       \n        matploblib figure\n        \"\"\"        \n        if self.method == 'gradient_descent':\n            plt.figure()\n            plt.plot(np.arange(1, self.numIters+1), self.costs, label = r'$J(\\theta)$')\n            plt.xlabel('Iterations')\n            plt.ylabel(r'$J(\\theta)$')\n            plt.title('Cost vs Iterations of Gradient Descent')\n            plt.legend(loc = 'best')\n        else:\n            print('plotCost method can only be called when using gradient descent method')\n        \n\n        \n        \n        \n", "meta": {"hexsha": "8849ea71dd4bcce2cf5be5dcffaf333998372f20", "size": 6885, "ext": "py", "lang": "Python", "max_stars_repo_path": "polynomial_regression.py", "max_stars_repo_name": "pickus91/Polynomial-Regression-From-Scratch", "max_stars_repo_head_hexsha": "94f2ab46a21391a74c14ad2e655bf50de8e5c796", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-12-05T16:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:21:50.000Z", "max_issues_repo_path": "polynomial_regression.py", "max_issues_repo_name": "pickus91/Polynomial-Regression-From-Scratch", "max_issues_repo_head_hexsha": "94f2ab46a21391a74c14ad2e655bf50de8e5c796", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-05-16T16:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-16T19:34:05.000Z", "max_forks_repo_path": "polynomial_regression.py", "max_forks_repo_name": "pickus91/Polynomial-Regression-From-Scratch", "max_forks_repo_head_hexsha": "94f2ab46a21391a74c14ad2e655bf50de8e5c796", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2018-12-29T13:20:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T12:00:39.000Z", "avg_line_length": 31.7281105991, "max_line_length": 108, "alphanum_fraction": 0.4746550472, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576265, "lm_q2_score": 0.8887587905460026, "lm_q1q2_score": 0.8524568025125837}}
{"text": "import math\n\n# Taylor expansion at n=1 2x\n# Taylor expansion at n=3 2x - 4(x**3)/3\n# Taylor expansion at n=5 2x - 4(x**3)/3 + 4(x**5)/15\n\nimport sympy as sy\nimport numpy as np\nfrom sympy.functions import sin, cos\nimport matplotlib.pyplot as plt\nfrom sympy.parsing.sympy_parser import *\n\nplt.style.use(\"ggplot\")\n\n# Define the variable and the function to approximate\nx = sy.Symbol('x')\nf = sin(2 * x)\n\n\n# Factorial function\ndef factorial(n):\n    if n <= 0:\n        return 1\n    else:\n        return n * factorial(n - 1)\n\n\n# Taylor approximation at x0 of the function 'function'\ndef taylor(function, x0, n):\n    i = 0\n    p = 0\n    while i <= n:\n        p = p + (function.diff(x, i).subs(x, x0)) / (factorial(i)) * (x - x0) ** i\n        i += 1\n    return p\n\n\n# Plot results\ndef plot():\n    x_lims = [0, math.pi]\n    x1 = np.linspace(x_lims[0], x_lims[1], 800)\n    y1 = []\n    # Approximate up until 5 starting from 1 and using steps of 2\n    lastFunc = 0\n    for j in range(1, 6, 2):\n        func = taylor(f, 0, j)\n        lastFunc = func\n        print('Taylor expansion at n=' + str(j), func)\n        for k in x1:\n            y1.append(func.subs(x, k))\n        plt.plot(x1, y1, label='order ' + str(j))\n        y1 = []\n    # Plot the function to approximate (sine, in this case)\n    expr = parse_expr(str(lastFunc))\n    realValue = np.sin(math.pi / 2)  # sin(2x) => x=pi/2\n    taylorValue = expr.subs(x, math.pi / 4)\n\n    print('\\n\\nTaylor expansion sin of 2x=', lastFunc)\n    print('Taylor expansion result sin of 2x ~=', taylorValue)\n    print('Real value sin of 2x ~=', realValue)\n\n    absoluteError = abs(realValue - taylorValue)\n    realtiveError = absoluteError / realValue\n    percentageError = realtiveError * 100\n\n    print('\\n\\nAbsolute Error: ', absoluteError)\n    print('Realtive Error: ', realtiveError)\n    print('Percentage Error: \"%\"', percentageError)\n\n    plt.plot(x1, np.sin(x1), label='sin of 2x')\n    plt.xlim(x_lims)\n    plt.ylim([-math.pi, math.pi])\n    plt.xlabel('x')\n    plt.ylabel('y')\n    plt.legend()\n    plt.grid(True)\n    plt.title('Taylor series approximation')\n    plt.show()\n\n\nplot()\n", "meta": {"hexsha": "1310209885f3746ad67ea6bd06c69380e930b255", "size": 2117, "ext": "py", "lang": "Python", "max_stars_repo_path": "TaylorSeries.py", "max_stars_repo_name": "ayyse/NumericAnalysis", "max_stars_repo_head_hexsha": "e2f592d2d13cc1a21170a99e582d7bc1ad585e8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-22T11:55:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T11:55:19.000Z", "max_issues_repo_path": "TaylorSeries.py", "max_issues_repo_name": "ayyse/NumericAnalysis", "max_issues_repo_head_hexsha": "e2f592d2d13cc1a21170a99e582d7bc1ad585e8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TaylorSeries.py", "max_forks_repo_name": "ayyse/NumericAnalysis", "max_forks_repo_head_hexsha": "e2f592d2d13cc1a21170a99e582d7bc1ad585e8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8170731707, "max_line_length": 82, "alphanum_fraction": 0.6093528578, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542794197472, "lm_q2_score": 0.8887587920192298, "lm_q1q2_score": 0.8524567987371693}}
{"text": "import scipy as sp\nimport numpy as np\nimport scipy.linalg as la\nimport numpy.linalg as la\nimport matplotlib.pyplot as plt\n'''\nA = sp.array([[2,1],[4,2.01]])\nla.norm(A)*la.norm(la.pinv(A))\nnp.linalg.cond(A)\n'''\n#problem 2\n\ndef hilbertCond(n): \n\t'''\n\tI'm just going to construct teh Hilbert Matrx and calculate the \n\tcondition from there. If there's a better way, I don't know it.\n\t'''\n\tdef hilbert(n):\n\t\treturn sp.array([[1./(x+y-1) for x in range(1,n+1)] for y in range(1,n+1)])\n\treturn np.linalg.cond (hilbert(n))\n'''\t\nI don't understand the growth curve. When I plot n in ranges like 1 to 21 and 1 to 100 I get strange peaks, but the condition is still obviously growing rapidly. When I plot from 1 to 10 though, I get no peaks. Is this what I'm supposed to get?\n'''\nif __name__ == \"__main__\":\n\tN = sp.arange(1,21)\n\tplt.plot(N,sp.vectorize(hilbertCond)(N))\n\tplt.show()\n\n", "meta": {"hexsha": "08fb7c1581f9bd7aad515fb9f94730fa77183d7a", "size": 872, "ext": "py", "lang": "Python", "max_stars_repo_path": "Solutions/Applications/MPApp.py", "max_stars_repo_name": "abefrandsen/numerical_computing", "max_stars_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Solutions/Applications/MPApp.py", "max_issues_repo_name": "abefrandsen/numerical_computing", "max_issues_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/Applications/MPApp.py", "max_forks_repo_name": "abefrandsen/numerical_computing", "max_forks_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-21T23:06:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T23:06:27.000Z", "avg_line_length": 30.0689655172, "max_line_length": 244, "alphanum_fraction": 0.6926605505, "include": true, "reason": "import numpy,import scipy", "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.8887587831798666, "lm_q1q2_score": 0.8524567975227092}}
{"text": "'''\nComputing the covariance\n100xp\nThe covariance may be computed using the Numpy function np.cov(). For example,\nwe have two sets of data x and y, np.cov(x, y) returns a 2D array where entries\n[0,1] and [1,0] are the covariances. Entry [0,0] is the variance of the data in x,\nand entry [1,1] is the variance of the data in y. This 2D output array is called\nthe covariance matrix, since it organizes the self- and covariance.\n\nTo remind you how the I. versicolor petal length and width are related, we include\nthe scatter plot you generated in a previous exercise.\n\nInstructions\n-Use np.cov() to compute the covariance matrix for the petal length\n(versicolor_petal_length) and width (versicolor_petal_width) of I. versicolor.\n-Print the covariance matrix.\n-Extract the covariance from entry [0,1] of the covariance matrix. Note that by symmetry,\nentry [1,0] is the same as entry [0,1].\n-Print the covariance.\n'''\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nversicolor_petal_length = np.array([4.7,  4.5,  4.9,  4.,  4.6,  4.5,  4.7,  3.3,  4.6,  3.9,  3.5,\n                                    4.2,  4.,  4.7,  3.6,  4.4,  4.5,  4.1,  4.5,  3.9,  4.8,  4.,\n                                    4.9,  4.7,  4.3,  4.4,  4.8,  5.,  4.5,  3.5,  3.8,  3.7,  3.9,\n                                    5.1,  4.5,  4.5,  4.7,  4.4,  4.1,  4.,  4.4,  4.6,  4.,  3.3,\n                                    4.2,  4.2,  4.2,  4.3,  3.,  4.1])\n\nversicolor_petal_width = np.array([1.4,  1.5,  1.5,  1.3,  1.5,  1.3,  1.6,  1.,  1.3,  1.4,  1.,\n                                   1.5,  1.,  1.4,  1.3,  1.4,  1.5,  1.,  1.5,  1.1,  1.8,  1.3,\n                                   1.5,  1.2,  1.3,  1.4,  1.4,  1.7,  1.5,  1.,  1.1,  1.,  1.2,\n                                   1.6,  1.5,  1.6,  1.5,  1.3,  1.3,  1.3,  1.2,  1.4,  1.2,  1.,\n                                   1.3,  1.2,  1.3,  1.3,  1.1,  1.3])\n\n# Compute the covariance matrix: covariance_matrix\ncovariance_matrix = np.cov(versicolor_petal_length, versicolor_petal_width)\n\n# Print covariance matrix\nprint(covariance_matrix)\n\n# Extract covariance of length and width of petals: petal_cov\npetal_cov = covariance_matrix[0, 1]\n\n# Print the length/width covariance\nprint(petal_cov)\n", "meta": {"hexsha": "4d66b6080421c8336926186ec583e84ea8f75123", "size": 2252, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/2-quantitative-exploratory-data-analysis/computing-the-covariance.py", "max_stars_repo_name": "aimanahmedmoin1997/DataCamp", "max_stars_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-12T04:49:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T00:40:28.000Z", "max_issues_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/2-quantitative-exploratory-data-analysis/computing-the-covariance.py", "max_issues_repo_name": "aimanahmedmoin1997/DataCamp", "max_issues_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/2-quantitative-exploratory-data-analysis/computing-the-covariance.py", "max_forks_repo_name": "aimanahmedmoin1997/DataCamp", "max_forks_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-11-06T17:43:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T21:08:16.000Z", "avg_line_length": 46.9166666667, "max_line_length": 99, "alphanum_fraction": 0.5657193606, "include": true, "reason": "import numpy", "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.9005297901222472, "lm_q1q2_score": 0.8524384980323968}}
{"text": "import numpy as np\n\ndef MAE(X, T):\n    \"\"\"Mean Absolute Error\n    \n    ## Output\n        Loss of the whole mini-batch (one value will be returned)\n    \"\"\"\n    return np.sum(np.absolute(X-T))/X.shape[0]\n\ndef MSE(X, T):\n    \"\"\"Mean Square Error\n\n    ## Output\n        Loss of the whole mini-batch (one value will be returned)\n    \"\"\"\n    return np.sum((X-T)**2)/X.shape[0]\n\ndef RMSE(X, T):\n    \"\"\"Root Mean Square Error\n\n    ## Output\n        Loss of the whole mini-batch (one value will be returned)\n    \"\"\"\n    return np.sqrt(np.sum((X-T)**2)/X.shape[0])\n\ndef CEL(X, T):\n    \"\"\"Cross Entropy Loss\n    X: output of softmax function\n    T: training data in the form of one-hot vector \n    \n    ## Output\n        Loss of the whole mini-batch (one value will be returned)\n    \"\"\"\n    return -np.sum(T*np.log(np.absolute(X+10e-7)))/X.shape[0]\n", "meta": {"hexsha": "8c0b08b73cdfc0451d145fd88be503cf8b985685", "size": 838, "ext": "py", "lang": "Python", "max_stars_repo_path": "loss.py", "max_stars_repo_name": "kashu98/Simple-Deep-Learning", "max_stars_repo_head_hexsha": "73fc4719c145cc1f49826fd90d5448db65cbe08b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-25T06:28:14.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-25T06:28:14.000Z", "max_issues_repo_path": "loss.py", "max_issues_repo_name": "kashu98/Simple-Deep-Learning", "max_issues_repo_head_hexsha": "73fc4719c145cc1f49826fd90d5448db65cbe08b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "loss.py", "max_forks_repo_name": "kashu98/Simple-Deep-Learning", "max_forks_repo_head_hexsha": "73fc4719c145cc1f49826fd90d5448db65cbe08b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2777777778, "max_line_length": 65, "alphanum_fraction": 0.5918854415, "include": true, "reason": "import numpy", "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018412458461, "lm_q2_score": 0.8740772433654401, "lm_q1q2_score": 0.8524017371210707}}
{"text": "from scipy import optimize\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom random import uniform\nimport evaluation_functions as ef\n\n\ndef rosenbrock(x, y):\n    return (x-1)**2 + 100*(y-x**2)**2;\n\ndef beale(x, y):\n    return (x*y + 1.5 - x)**2 + (x * (y**2) + 2.5 - x)**2 + (x * (y**3) + 2.625 - x)\n\ndef booth(x, y):\n    return (x + 2 * y - 7)**2 + (2*x  + y - 5)**2\n\ndef matyas(x, y):\n    return 0.26*(x**2 + y**2) - 0.48*(x*y)\n\n\ndef plot_rosenbrock():\n    step = .15\n    X = np.arange(-2, 2, step)\n    Y = np.arange(-1, 3, step)\n    X, Y = np.meshgrid(X, Y)\n\n    Z = rosenbrock(X, Y)\n    \n    fig = plt.figure(figsize=(15, 10))\n    ax = fig.gca(projection='3d')\n    surface = ax.plot_surface(X, Y, Z, cmap=cm.gist_heat_r, linewidth=0)\n    ax.set_zlim(0, 2000)\n    fig.colorbar(surface, shrink=0.5, aspect=10)\n    plt.show()\n\ndef bfgs_rosenbrock2d(minValue, maxValue):\n    answerList = []\n    answerValuesList = []\n    for i in range(30):\n        print('\\nInteration:',i)\n        x0 = [uniform(minValue, maxValue), uniform(minValue, maxValue)]\n        print('Initial Point:', x0)\n        answer = optimize.minimize(optimize.rosen, x0, method='BFGS', jac = optimize.rosen_der,\n                                   options={'disp':True, 'return_all':True})\n        print('Rosenbrock Minimized Value:',answer.x)\n        answerList.append(answer)\n        answerValuesList.append(answer.x)\n    return answerList, answerValuesList\n\ndef bfgs_rosenbrock30d(minValue, maxValue):\n    answerList = []\n    answerValuesList = []\n    for i in range(30):\n        print('\\nInteration:',i)\n        x0 = []\n        for j in range(30):\n            x0.append(uniform(minValue, maxValue))\n        print('Initial Point:', x0)\n        answer = optimize.minimize(optimize.rosen, x0, method='BFGS', jac = optimize.rosen_der,\n                                   options={'disp':True, 'return_all':True})\n        print('Rosenbrock Minimized Value:',answer.x)\n        answerList.append(answer)\n        answerValuesList.append(answer.x)\n    return answerList, answerValuesList\n\n#plot_rosenbrock()\nresult2dList, result2dValueList = bfgs_rosenbrock2d(-1,1)\nminimum2dInterationResult = ef.minimum_iterations(result2dList)\nminimum2dInterationConvergeResult = ef.minimum_iterations_converge(result2dList)\nef.evaluate_method(result2dValueList, 'Rosenbrock 2D')\n\nresult30dList, result30dValueList = bfgs_rosenbrock30d(-1, 1)\nminimum30dInterationResult = ef.minimum_iterations(result30dList)\nminimum30dInterationConvergeResult = ef.minimum_iterations_converge(result30dList)\nef.evaluate_method(result30dValueList , 'Rosenbrock 30D')", "meta": {"hexsha": "2ddae137c1f65e5659356fb07ed0408881bf6869", "size": 2728, "ext": "py", "lang": "Python", "max_stars_repo_path": "Computational Work 1/python/computational-work-01.py", "max_stars_repo_name": "ThiagoCM/ufpr-optimization-2020.2", "max_stars_repo_head_hexsha": "9ef42419a10ff8c51a923f5118d06c1d597dc856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Computational Work 1/python/computational-work-01.py", "max_issues_repo_name": "ThiagoCM/ufpr-optimization-2020.2", "max_issues_repo_head_hexsha": "9ef42419a10ff8c51a923f5118d06c1d597dc856", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Computational Work 1/python/computational-work-01.py", "max_forks_repo_name": "ThiagoCM/ufpr-optimization-2020.2", "max_forks_repo_head_hexsha": "9ef42419a10ff8c51a923f5118d06c1d597dc856", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5316455696, "max_line_length": 95, "alphanum_fraction": 0.6612903226, "include": true, "reason": "import numpy,from scipy", "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018419665619, "lm_q2_score": 0.8740772335247531, "lm_q1q2_score": 0.8524017281543759}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nt = np.linspace(0, 20, 1001)\nnoise = np.random.randn(1001)\n\nT = np.pi  # period\n\n# Fourier series coefficients\na_0 = 1.\n\na_1 = 1.\na_2 = 2.\na_3 = 3.\n\nb_1 = 4.\nb_2 = 5.\nb_3 = 6.\n\ntimeseries = a_0 \\\n    + a_1*np.cos(1*np.pi*t/T) \\\n    + a_2*np.cos(2*np.pi*t/T) \\\n    + a_3*np.cos(3*np.pi*t/T) \\\n    + b_1*np.sin(1*np.pi*t/T) \\\n    + b_2*np.sin(2*np.pi*t/T) \\\n    + b_3*np.sin(3*np.pi*t/T)\n\nnoisy_timeseries = timeseries + noise\n\nplt.plot(t, timeseries)\nplt.scatter(t, noisy_timeseries)\nplt.show()\n\n# data = np.vstack((t, timeseries)).T\n# noisy_data = np.vstack((t, noisy_timeseries)).T\n\n# np.savetxt(\"test_timeseries.csv\", data, delimiter=\",\")\n# np.savetxt(\"test_timeseries_noisy.csv\", noisy_data, delimiter=\",\")\n", "meta": {"hexsha": "1c3f79f859edbcb9220e7e3ffe94558764672e95", "size": 762, "ext": "py", "lang": "Python", "max_stars_repo_path": "bokeh_app/data/synthetic_data_generator.py", "max_stars_repo_name": "goodteamname/spino", "max_stars_repo_head_hexsha": "aa8c6cfa9f94a639c306d85ca6df2483108fda37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bokeh_app/data/synthetic_data_generator.py", "max_issues_repo_name": "goodteamname/spino", "max_issues_repo_head_hexsha": "aa8c6cfa9f94a639c306d85ca6df2483108fda37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-10-26T10:57:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-01T14:48:21.000Z", "max_forks_repo_path": "bokeh_app/data/synthetic_data_generator.py", "max_forks_repo_name": "goodteamname/spino", "max_forks_repo_head_hexsha": "aa8c6cfa9f94a639c306d85ca6df2483108fda37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-26T10:41:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T10:41:31.000Z", "avg_line_length": 19.5384615385, "max_line_length": 68, "alphanum_fraction": 0.6351706037, "include": true, "reason": "import numpy", "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018398044143, "lm_q2_score": 0.8740772351648677, "lm_q1q2_score": 0.8524017278639346}}
{"text": "import numpy as np\nimport random\n\nfrom numpy.core.fromnumeric import transpose\n\n# 1.Matrix Creation\ndim = int(input(\"Enter Dimension of matrix :\"))\nmatrix = np.random.randint(10, size=(dim, dim))\n\n# 2.Matrix inversion\ninverse = np.linalg.inv(matrix)\nprint (\"Inverse matrix : %s\" %inverse)\n\n# 3.dot Product won't exactly yield I \nI = np.dot(matrix, inverse)\nprint(\" Dot product of matrix and its inverse is I: %s\" %np.dot(matrix, inverse))\n\n# 4.Verification of the identity matrix\nEPS = 1e-8\nr = np.all(np.abs(I - np.eye(dim)) < EPS)\nprint(r)\n\n# 5.Trace of matrix\nprint(\" Trace of matrix : %s\" %matrix.trace())\n\n# Random matrices with fixed dimension\nA = np.random.randint(10, size=(2, 3))\nB = np.random.randint(10, size=(3, 2))\n\n# 6.cross product \nprint(\"cross product of %s and %s is %s\" %(A, B, np.outer(A, B)))\n\n\n# 7.transpose of matrix\nprint(\"Transpose of matris is %s\" %np.transpose(matrix))\n\n# 8.norm of matrix\nprint(\"Norm of matrix is : %s\" %np.linalg.norm(matrix))\n\n# 9. Range of matrix\nprint('Range of the matrix is : %s' %np.ptp(matrix))\n\n# 9. Rank of matrix\nprint('Rank of the matrix is : %s' %np.linalg.matrix_rank(matrix))", "meta": {"hexsha": "bc5712439da918bf2aff30a93d4e3249c0376f98", "size": 1135, "ext": "py", "lang": "Python", "max_stars_repo_path": "Advanced/matrix.py", "max_stars_repo_name": "Sangeerththan/pythonDSA", "max_stars_repo_head_hexsha": "d126b3a7a8acc1e202107e20a21ed96fb4ab144e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-12T20:40:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T20:40:37.000Z", "max_issues_repo_path": "Advanced/matrix.py", "max_issues_repo_name": "Sangeerththan/pythonDataStructure", "max_issues_repo_head_hexsha": "d126b3a7a8acc1e202107e20a21ed96fb4ab144e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Advanced/matrix.py", "max_forks_repo_name": "Sangeerththan/pythonDataStructure", "max_forks_repo_head_hexsha": "d126b3a7a8acc1e202107e20a21ed96fb4ab144e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7954545455, "max_line_length": 81, "alphanum_fraction": 0.6881057269, "include": true, "reason": "import numpy,from numpy", "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018398044144, "lm_q2_score": 0.8740772335247532, "lm_q1q2_score": 0.8524017262644921}}
{"text": "#\n# Points and weights for Gaussian quadrature\n#\n# by Alberto Costa Nogueira Jr. (Matlab and Python versions)\n#    Renato Cantao (Python version)\n#\nimport numpy\nfrom math import gamma\nfrom jacobi_p import jacobi_p\nfrom djacobi_p import djacobi_p\nfrom jacobi_roots import jacobi_roots\nfrom simulation_data import QuadratureNodes\n\nclass JacobiGaussQuad:\n    \"\"\"Points and weights for Gaussian quadrature based on Jacobi polynomials\"\"\"\n    def __init__(self, sim_data):\n        # Sets parameters to obtain quadrature points from Legendre polynomials\n        # Legendre == Jacobi(0,0)\n        alpha = 0.0\n        beta  = 0.0\n        nip = sim_data.nip()\n\n        # Case 1: Gauss-Legendre quadrature\n        if sim_data.node_dist == QuadratureNodes.GL:\n            self.xi, self.w = self._gl(nip, alpha, beta)\n        # Case 2: Gauss-Legendre-Lobato quadrature\n        elif sim_data.node_dist == QuadratureNodes.GLL:\n            self.xi, self.w = self._gll(nip, alpha, beta)\n        else:\n            raise AssertionError(\"Unknown quadrature type!\")\n\n    # Case 1: Gauss-Legendre quadrature\n    def _gl(self, nip, alpha, beta):\n        xi = jacobi_roots(nip, alpha, beta)\n\n        C1 = (2.0**(alpha+beta+1.0))*gamma(alpha+nip+1.0)*gamma(beta+nip+1.0)\n        C2 = gamma(nip+1.0)*gamma(alpha+beta+nip+1.0)*(1.0-xi**2 )\n\n        DPm = djacobi_p(xi, nip, alpha, beta)\n\n        w = C1*DPm**(-2)/C2\n\n        return xi, w\n\n    # Case 2: Gauss-Legendre-Lobato quadrature\n    def _gll(self, nip, alpha, beta):\n        r = jacobi_roots(nip-2, alpha+1.0, beta+1.0)\n        xi = numpy.empty(r.shape[0]+2)\n        xi[0] = -1.0\n        xi[1:-1] = r\n        xi[-1] = 1.0\n\n        C1 = (2.0**(alpha+beta+1.0))*gamma(alpha+nip)*gamma(beta+nip)\n        C2 = (nip-1)*gamma(nip)*gamma(alpha+beta+nip+1.0)\n\n        Pm = jacobi_p(xi, nip-1, alpha, beta)\n\n        w = C1*Pm**(-2)/C2\n\n        w[ 0] = w[ 0]*(beta+1.0)\n        w[-1] = w[-1]*(alpha+1.0)\n\n        return xi, w\n\n    def n(self):\n        \"\"\"Number of integration points / weights.\"\"\"\n        return self.xi.shape[0]\n\n#-- jacobi_gauss_quad.py -------------------------------------------------------\n", "meta": {"hexsha": "9faeecc299a5ce98b070eb5c81808d282a663823", "size": 2132, "ext": "py", "lang": "Python", "max_stars_repo_path": "lessons/08_dg/jacobi_gauss_quad.py", "max_stars_repo_name": "albertonogueira/numerical-mooc", "max_stars_repo_head_hexsha": "dd95e650310502b5cdfe6e405ed7ab7e1496d233", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-02-10T12:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-10T12:09:09.000Z", "max_issues_repo_path": "lessons/08_dg/jacobi_gauss_quad.py", "max_issues_repo_name": "albertonogueira/numerical-mooc", "max_issues_repo_head_hexsha": "dd95e650310502b5cdfe6e405ed7ab7e1496d233", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lessons/08_dg/jacobi_gauss_quad.py", "max_forks_repo_name": "albertonogueira/numerical-mooc", "max_forks_repo_head_hexsha": "dd95e650310502b5cdfe6e405ed7ab7e1496d233", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4571428571, "max_line_length": 80, "alphanum_fraction": 0.5872420263, "include": true, "reason": "import numpy", "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224331, "lm_q2_score": 0.8947894724152068, "lm_q1q2_score": 0.8523533003758212}}
{"text": "\"\"\"Functions for working with vectors and polar coordinates.\"\"\"\n\nimport numpy as np\n\n\ndef cart_to_pol(x, y):\n    \"\"\"\n    Convert vector from cartesian/xy notation to polar notation.\n\n    Parameters\n    ------\n    x: int or float\n        The x component of a vector\n    y: int or float\n        The y component of a vector\n\n    Returns\n    -------\n    phi: float\n        The direction of the vector\n    rho: float\n        The magnitude of the vector\n    \"\"\"\n    rho = np.sqrt(x ** 2 + y ** 2)\n    phi = np.arctan2(y, x)\n    return (phi, rho)\n\n\ndef pol_to_cart(phi, rho=1):\n    \"\"\"\n    Convert vector from polar notation to cartesian/xy notation.\n\n    Parameters\n    -------\n    phi: float\n        The direction of the vector\n    rho: float\n        The magnitude of the vector.\n        If ommitted, the default value is 1 (unit vector).\n\n    Returns\n    ------\n    x: int or float\n        The x component of a vector\n    y: int or float\n        The y component of a vector\n    \"\"\"\n    x = rho * np.cos(phi)\n    y = rho * np.sin(phi)\n    return (x, y)\n\n\ndef points_to_angle(p, q):\n    \"\"\"\n    Finds the polar angle (phi) between the vector from the origin\n    along the positive x-axis and the line defined by two points p,q.\n\n    Parameters\n    -----\n    p: tuple of ints/floats. (x,y)\n    q: tuple of ints/floats. (x,y)\n\n    Returns\n    ------\n    phi: float\n        the angle of the line in radians, between -pi and pi.\n    \"\"\"\n    phi = np.arctan2(q[0] - p[0], q[1] - p[1])\n    return phi\n\n\ndef wrap_to_pi(x):\n    \"\"\"\n    Wrap a value between -pi and pi in polar coordinate space.\n        e.g. if x = 2*pi, x_wrapped = 0\n        e.g. if x = 3*pi, x_wrapped = pi\n\n    Parameters\n    ------\n    x: an int or float\n\n    Returns\n    -------\n    x_wrapped: float between -pi and pi\n    \"\"\"\n    x_wrapped = (x + np.pi) % (2 * np.pi) - np.pi\n    return x_wrapped\n", "meta": {"hexsha": "d9d90ee262e8bf8a828490da2084f8c68e2a85a4", "size": 1856, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/functions/utils/polar.py", "max_stars_repo_name": "a9w/Fat2_polarizes_WAVE", "max_stars_repo_head_hexsha": "be39ba21245a9b532a70954a38139976a2355a7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/functions/utils/polar.py", "max_issues_repo_name": "a9w/Fat2_polarizes_WAVE", "max_issues_repo_head_hexsha": "be39ba21245a9b532a70954a38139976a2355a7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/functions/utils/polar.py", "max_forks_repo_name": "a9w/Fat2_polarizes_WAVE", "max_forks_repo_head_hexsha": "be39ba21245a9b532a70954a38139976a2355a7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0909090909, "max_line_length": 69, "alphanum_fraction": 0.5657327586, "include": true, "reason": "import numpy", "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574122783325, "lm_q2_score": 0.8947894710123925, "lm_q1q2_score": 0.8523532954253852}}
{"text": "\"\"\"\nWhen you roll two regular six-sided dice, the total number of pips that can come up ranges from 2 (if both dice show 1)\nto 12 (if both dice show 6), but as all experienced gamblers know, some numbers are more likely than others. In fact,\nthe most likely number to come up is 7, with a probability of 1/6. By contrast, the probability of 12 showing is only\n1/36, so it is six times more likely that the dice will show 7 than it is that they will show 12.\n\nThe reason for this is of course that there are more ways that two dice can sum to 7. In fact, there are exactly six\nways two dice can sum to 7: the first die can show 1 and the second 6, the first 2 and the second 5, the first 3 and\nthe second 4, the first 4 and the second 3, the first 5 and the second 2, and finally the first die can show 6 and the\nsecond 1. Given that there are a total of 6*6 = 36 different ways the dice can land, this gives us the probability:\n6/36 = 1/6. In contrast, there is only one way two dice can form 12, by throwing two sixes.\n\nDefine a function f(d, n) that gives the number of ways d six-sided dice can be thrown to show the number n. So, in the\nprevious example, f(2,7) = 6. Here are a few other values of that function:\nf(1,n) = 1 (for 1≤n≤6, 0 otherwise)\nf(2,7) = 6\nf(2,10) = 3\nf(2,12) = 1\nf(3,10) = 27\nf(5,20) = 651\nf(7,30) = 12117\nf(10,50) = 85228\nFind f(20, 100)\n\nNote: the answer fits into a 64-bit integer\n\nBonus: Find f(1100, 5000) mod 107\n\"\"\"\n\nimport itertools\nfrom scipy import convolve\n\n\ndef f(d, n):\n    \"\"\"\n    my itertools solution. too slow for final solution\n    \"\"\"\n    dice = '123456'\n    comb = itertools.product(dice, repeat=d)\n    perm_list = []\n\n    def sum_check(x, n):\n        return sum(x) == n\n\n    for c in comb:\n        intd = list(map(int, c))\n        if sum_check(intd, n):\n            perm_list.append(intd)\n    return len(perm_list)\n\n\ndef crawphish(d, n):\n    \"\"\"\n    Recursive solution from /u/crawphish ported to python by me. too slow for final solution\n    \"\"\"\n    out = 0\n    for i in range(1, 6+1):\n        if d:\n            out += crawphish(d - 1, n - i)\n        else:\n            if n:\n                return 0\n            else:\n                return 1\n    return out\n\n\ndef ttl(d, n, m=10**7):\n    \"\"\"\n    /u/ttl's solution. Mathematical solution, no idea of how it works but it returns the solution and bonus solution\n    very quickly.\n    \"\"\"\n    p = q = [1]*6+[0]\n    i = 1\n    while i < d:\n        q, i = (convolve(q, q) % m, i*2) if 2*i < d else (convolve(q, p) % m, i+1)\n    return q[-n-1]\n\n\ndef main():\n    # print(f(20,100))\n    # print(crawphish(20, 100))\n    print(ttl(1100, 5000))\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "a460d8b159f336141a43986cb804e2a3e2d29bfa", "size": 2668, "ext": "py", "lang": "Python", "max_stars_repo_path": "DailyProgrammer/20120507C.py", "max_stars_repo_name": "DayGitH/Python-Challenges", "max_stars_repo_head_hexsha": "bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-23T18:59:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T13:16:09.000Z", "max_issues_repo_path": "DailyProgrammer/20120507C.py", "max_issues_repo_name": "DayGitH/Python-Challenges", "max_issues_repo_head_hexsha": "bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DailyProgrammer/20120507C.py", "max_forks_repo_name": "DayGitH/Python-Challenges", "max_forks_repo_head_hexsha": "bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6666666667, "max_line_length": 119, "alphanum_fraction": 0.6323088456, "include": true, "reason": "from scipy", "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741227833249, "lm_q2_score": 0.8947894583870633, "lm_q1q2_score": 0.8523532833988231}}
{"text": "\"\"\"\nContent under Creative Commons Attribution license CC-BY 4.0, \ncode under MIT license (c)2018 Sergio Rojas (srojas@usb.ve) \n\nhttp://en.wikipedia.org/wiki/MIT_License\nhttp://creativecommons.org/licenses/by/4.0/\n\nCreated on april, 2018\nLast Modified on: may 15, 2018\n\n  This program finds the solution of the equation\n     7 = x + 9\n\"\"\"\nfrom sympy import symbols, Eq, solveset\nx  = symbols('x')\n\nLHS = 7\nRHS = x + 9\n\nthesol = list( solveset( Eq(LHS, RHS), x) )\nprint('thesol =', thesol)\n\nnewLHS = LHS - RHS #rearrange the equation to read: LHS - RHS = 0\nprint('newLHS =', newLHS)\n\nnewLHS = newLHS.subs(x, thesol[0])\nif newLHS.simplify() == 0:\n    print('The solution of {0} = {1}, is x = {2}'.format(LHS,RHS,thesol[0]))\n\n", "meta": {"hexsha": "4f17b53b0d9ba97abcc07434da523069e284cead", "size": 723, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter_05/chap05_prog_01_SympyWithIntegers.py", "max_stars_repo_name": "rojassergio/Prealgebra-via-Python-Programming", "max_stars_repo_head_hexsha": "8d1cdf103af2a39f6ae7bba76e9a6a0182eb39d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-19T11:54:15.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-19T11:54:15.000Z", "max_issues_repo_path": "Chapter_05/chap05_prog_01_SympyWithIntegers.py", "max_issues_repo_name": "rojassergio/Prealgebra-via-Python-Programming", "max_issues_repo_head_hexsha": "8d1cdf103af2a39f6ae7bba76e9a6a0182eb39d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter_05/chap05_prog_01_SympyWithIntegers.py", "max_forks_repo_name": "rojassergio/Prealgebra-via-Python-Programming", "max_forks_repo_head_hexsha": "8d1cdf103af2a39f6ae7bba76e9a6a0182eb39d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-03-02T22:31:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T05:06:39.000Z", "avg_line_length": 24.1, "max_line_length": 76, "alphanum_fraction": 0.6749654219, "include": true, "reason": "from sympy", "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.9059898279984214, "lm_q1q2_score": 0.8523459431135804}}
{"text": "import numpy as np\nimport time\n\n\n#implementation of Gauss-Jordan Elimination for square matrices\ntest1 = [[ 0,  2,  1],\n         [ 1, -2, -3],\n         [-1,  1,  2]]\n\ntest2 = [[1, -2, 1],\n        [0, 2, -8],\n        [-4, 5, 9]]\n\ntest3 = [[1, 1, -2, 1, 3, -1],\n         [2, -1, 1, 2, 1, -3],\n         [1, 3, -3, -1, 2, 1],\n         [5, 2, -1, -1, 2, 1],\n         [-3, -1, 2, 3, 1, 3],\n         [4, 3, 1, -6, -3, -2]]\n\nanother = [[1, 2, 3],\n           [4, 5, 6],\n           [7, 8, 9]]\n\ntest_vector1 = [-8, 0, 3]\ntest2_vector = [0, 8, -9]\ntest3_vector = [4, 20, -15, -3, 16, -27]\n\n\nnumpy_matrix = np.array(test3)\nnumpy_vector = np.array([test3_vector])\nnumpy_vector = np.transpose(numpy_vector)\n\nstart1 = time.time()\nsolution = np.linalg.solve(numpy_matrix, numpy_vector)\nend1 = time.time()\nnumpy_time = end1 - start1\n\n\n\n#switches the rows in the case when there is a vector with zero in the first place\ndef switch_the_rows(mat, vector):\n    for i in range(len(list_)):\n        if mat[i][0] != mat[0][0] and mat[i][0] != 0:\n            temp1 = mat[i]\n            temp2 = vector[i]\n            mat[i] = mat[0]\n            vector[i] = vector[0]\n            mat[0] = temp1\n            vector[0] = temp2\n            break\n    return mat, vector  \n\n#row reduces the matrix, approaches to lower triangular matrix\n#one row operation each time\ndef lower_row_reduction(mat, pivot_index, vector):\n    pivot = mat[pivot_index]\n    for i in range(pivot_index, len(mat)):\n        if i+1 == len(mat): break\n        if mat[i+1][i] != 0:\n            piv_multiple = [-x * mat[i+1][pivot_index]/pivot[pivot_index] for x in pivot]\n            vect_multiple = -vector[pivot_index]*mat[i+1][pivot_index]/pivot[pivot_index]                        \n            mat[i+1][:] = [x+y for x, y in zip(piv_multiple, mat[i+1])]\n            vector[i+1] = vect_multiple+vector[i+1]\n    return mat, vector\n\n#creation of lower triangular matrix\ndef lower_triangular(mat, vector):\n    for i in range(len(mat)):\n        mat, vector = lower_row_reduction(mat, i, vector)\n    return mat, vector\n\n#row reduces the matrix, approaches to identity matrix\n#one row operation each time\ndef upper_row_reduction(mat, pivot_index, vector):\n    pivot = mat[pivot_index]\n    vector[pivot_index] /= pivot[pivot_index] \n    mat[pivot_index][:] = [x/pivot[pivot_index] for x in pivot]\n    pivot = mat[pivot_index]\n    for i in range(pivot_index, -1, -1):\n        if i == 0: break\n        if mat[i][i] != 0:\n            temp = [-x*mat[i-1][pivot_index] for x in pivot]\n            temp_vector = -vector[pivot_index]*mat[i-1][pivot_index] \n            mat[i-1][:] = [y+x for x, y in zip(mat[i-1], temp)]   \n            vector[i-1] = temp_vector+vector[i-1]\n    return mat, vector\n\n#creation of upper triangular matrix\ndef upper_triangular(mat, vector):\n    for i in range(len(mat)-1, -1, -1):\n        mat, vector = upper_row_reduction(mat, i, vector)\n    return mat, vector\n\n#merge the functions    \ndef gauss_jordan(mat, vector):\n    if mat[0][0] == 0: mat, vector = switch_the_rows(mat, vector)\n    mat, vector = lower_triangular(mat, vector)  \n    mat, vector = upper_triangular(mat, vector)\n    return mat, vector\n\nstart = time.time()\nM, sol = gauss_jordan(test3, test3_vector)\nend = time.time()\n\nmy_time = end - start \n\nsol = [round(x, 2) for x in sol]                #round each element in the vector up to 2 decimal places\nprint(sol)\n\nprint(\"Numpy implementation: \" + str(numpy_time))\nprint(\"My implementation: \" + str(my_time))\nprint(\"Difference: \" + str(my_time - numpy_time))\n                \n", "meta": {"hexsha": "ac5266ee5d40246f268295ec1999cf67e35d72ce", "size": 3546, "ext": "py", "lang": "Python", "max_stars_repo_path": "Implementation-of-linear-algebra-operations/1.pure-python/time-elapsed-gauss-jordan.py", "max_stars_repo_name": "zelzhan/Linear-algebra-with-python", "max_stars_repo_head_hexsha": "a58042c9f29f67aafcd2c1c4c1300a0e9223a650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Implementation-of-linear-algebra-operations/1.pure-python/time-elapsed-gauss-jordan.py", "max_issues_repo_name": "zelzhan/Linear-algebra-with-python", "max_issues_repo_head_hexsha": "a58042c9f29f67aafcd2c1c4c1300a0e9223a650", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Implementation-of-linear-algebra-operations/1.pure-python/time-elapsed-gauss-jordan.py", "max_forks_repo_name": "zelzhan/Linear-algebra-with-python", "max_forks_repo_head_hexsha": "a58042c9f29f67aafcd2c1c4c1300a0e9223a650", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8347826087, "max_line_length": 113, "alphanum_fraction": 0.5862944162, "include": true, "reason": "import numpy", "num_tokens": 1092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985936, "lm_q2_score": 0.905989829267587, "lm_q1q2_score": 0.852345942803546}}
{"text": "# -*- coding: utf-8 -*-\n\n# Raivo Laanemets\n# rlaanemt@ut.ee\n\n# A note: getA1() is used to transform matrix row into array.\n\nimport sys\nimport random\nimport numpy\nimport time\nimport math\n\n# Solves linear system Kx = b.\n# when is_unit is set to True then the\n# procedure expects lower triangular matrix as L\n# otherwise it expects lower unit triangular matrix as L.\n# Might destructively update input matrix!\n\ndef solveL(L, b, is_unit=False):\n    # If unit triangular matrix is assumed, set 1's in\n    # the matrix main diagonal.\n    if is_unit:\n        L += numpy.diag(numpy.matrix(-L.diagonal() + 1).getA1())\n    # Solve with forward subsitution.\n    x = numpy.array(numpy.zeros(len(b), dtype=float))\n    x[0] = b[0] / L[0, 0]\n    for i in xrange(1, len(b)):\n        x[i] = (b[i] - sum((L[i, 0:i]).getA1() * x[0:i])) / L[i, i]\n    return x\n\n# Solves linear system Kx = b.\n# Expects upper triangular matrix as L.\n\ndef solveU(L, b):\n    # Transforms the matrix L into suitable form to use with solveL.\n    # Might be inefficient.\n    # [::-1] reverses the array.\n    return solveL(numpy.fliplr(numpy.flipud(L)), b[::-1])[::-1]\n\n# Taken from pseudoalgorithm:\n# http://www.math.vt.edu/people/wapperom/class_home/4445/alg_ludoolittle.pdf\n\n# Compared to one on our lecture slides:\n# 1. It gives name of the algorithm (Doolittle's) so\n# I can ask someone about it.\n# 2. Checks if factorization is possible at all\n# instead of quitely producing bogus results.\n# 3. Gives L and U matrixes I actually know how to use.\n\n# Returns a three tuple (L, U) as the decomposition result.\n# Modifies right side vector b as well.\n\ndef gauss_decomp(a, b, pivoting=False):\n    n = len(a)\n    l = numpy.matrix(numpy.zeros((n, n), dtype=float))\n    u = numpy.matrix(numpy.zeros((n, n), dtype=float))\n    for i in xrange(n): # iterates over rows\n\n        max_a = abs(a[i, i])\n        max_i = i\n        \n        # Row pivoting.\n        # Find best pivot (manually).\n        if pivoting:\n            for j in xrange(i, n):\n                if (abs(a[j, i]) > max_a):\n                    max_a = abs(a[j, i])\n                    max_i = j\n                    \n        if max_i != i:\n            \n            # Swaps rows manually.\n            # Tracking row permutations was too complex for me.\n            # This might be inefficient but could be easily\n            # implemented in C or Fortran and then use\n            # that implementation through some Python\n            # native interface.\n            \n            interchange(a, i, max_i);\n            interchange(l, i, max_i);\n                \n            # Also does swapping for right-hand side vector.\n            \n            tmp = b[i]\n            b[i] = b[max_i]\n            b[max_i] = tmp\n            \n        if a[i, i] == 0:\n            raise Exception(\"Factorization not possible\");\n        l[i, i] = 1.0\n        for j in xrange(i, n):\n            u[i, j] = a[i, j]\n            for k in xrange(i):\n                u[i, j] = u[i, j] - l[i, k] * u[k, j]\n        for j in xrange(i + 1, n):\n            l[j, i] = a[j, i]\n            for k in xrange(i):\n                l[j, i] = l[j, i] - l[j, k] * u[k, i]\n            l[j, i] = l[j, i] / float(u[i, i])\n\n    return (l, u)\n\ndef interchange(M, r1, r2):\n    for j in xrange(len(M)):\n        tmp = M[r1, j]\n        M[r1, j] = M[r2, j]\n        M[r2, j] = tmp\n\ndef solve_single(A, b, pivoting=True):\n    (L, U) = gauss_decomp(A, b, pivoting)\n    return solve_lu(L, U, b);\n\ndef solve_lu(L, U, b):\n    y = solveL(L, b)\n    x = numpy.matrix(solveU(U, y))\n    # Consistent with numpy.linalg.solve output.\n    x.shape = (len(b), 1)\n    return numpy.matrix(x)\n\ndef main(argv):\n    # Testing with the example from http://en.wikipedia.org/wiki/System_of_linear_equations\n    A = numpy.matrix([[2, -2, 4], [3, 2, -1], [-1, 0.5, -1]], dtype=float)\n    b = numpy.array([-2, 1, 0], dtype=float)\n    print \"A\\n\", A\n    print \"b\\n\", b\n    print \"solve\\n\", solve_single(A, b, True)\n    \n    # Calculating errors for large matrices.\n    m = 40\n    size = 25\n    errors = []\n    errors_pivoting = []\n    for i in xrange(m):\n        Aarr = (numpy.random.rand(size * size) - 0.5) * 1000000000\n        Aarr.shape = (size, size)\n        A = numpy.matrix(Aarr)\n        b = numpy.random.random(size)\n        A1 = A.copy()\n        b1 = b.copy()\n        x1 = solve_single(A1, b1, False)\n        errors.append(numpy.sum(numpy.square(b1 - (A1 * x1).getA1())))\n        A2 = A.copy()\n        b2 = b.copy()\n        x2 = solve_single(A2, b2, True)\n        errors_pivoting.append(numpy.sum(numpy.square(b2 - (A2 * x2).getA1())))\n        \n        \n    print \"Average error without pivoting :\", numpy.average(errors)\n    print \"Average error with pivoting :\", numpy.average(errors_pivoting)\n\nif __name__ == \"__main__\":\n    main(sys.argv[1:])\n", "meta": {"hexsha": "dfd3a179bdb54818f307a92c99d2e5957f652bf2", "size": 4787, "ext": "py", "lang": "Python", "max_stars_repo_path": "2009/scientific-computing/prax7/src/RLPrax7_1.py", "max_stars_repo_name": "rla/old-code", "max_stars_repo_head_hexsha": "06aa69c3adef8434992410687d466dc42779e57b", "max_stars_repo_licenses": ["Ruby", "MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-11-08T10:01:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-10T00:00:58.000Z", "max_issues_repo_path": "2009/scientific-computing/prax7/src/RLPrax7_1.py", "max_issues_repo_name": "rla/old-code", "max_issues_repo_head_hexsha": "06aa69c3adef8434992410687d466dc42779e57b", "max_issues_repo_licenses": ["Ruby", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2009/scientific-computing/prax7/src/RLPrax7_1.py", "max_forks_repo_name": "rla/old-code", "max_forks_repo_head_hexsha": "06aa69c3adef8434992410687d466dc42779e57b", "max_forks_repo_licenses": ["Ruby", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0844155844, "max_line_length": 91, "alphanum_fraction": 0.5575517025, "include": true, "reason": "import numpy", "num_tokens": 1373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.9059898203834277, "lm_q1q2_score": 0.8523459374535245}}
{"text": "#ZADANIE 1\n#Napisz funkcje tsin(x), tcos(x), texp(x) i ttan(x) realizujace takie same operacje jak funkcje biblioteczne:\n#numpy.sin(x), numpy.cos(x), numpy.exp(x) i numpy.tan(x).\n#We wlasnych funkcjach wykorzystaj rozwiniecie w szereg Taylora (https://en.wikipedia.org/wiki/Taylor_series).\n#W celu poprawnego rozwiazania zadania nalezy dodatkowo napisac funkcje realizujaca n! (silnia).\n\nimport numpy as np\n\ndef tbernoulli(n):\n    if n<0 and n>20:\n        return 0\n    else:\n        temp=[1, 1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66, 0, -691/2730, 0, 7/6, 0, -3617/510, 0, 43867/798, 0, -174611/330]\n        return temp[n]\n\ndef silnia(x):\n    sil=1\n    while x>0:\n        sil=sil*x\n        x =x-1\n    return sil\n    \ndef tsin(x):\n    sum_sin=0\n    for i in range(0,6):\n        sum_sin=sum_sin+((-1)**i)*(x**(2*i+1))/float(silnia(2*i+1))\n    return sum_sin\n\ndef tcos(x):\n    sum_cos=0\n    for i in range(0,6):\n        sum_cos=sum_cos+((-1)**i)*(x**(2*i))/float(silnia(2*i))\n    return sum_cos\n\ndef texp(x):\n    sum_exp=0\n    for i in range(0,6):\n        sum_exp=sum_exp+(x**i)/float(silnia(i))\n    return sum_exp\n\ndef ttan(x):\n    sum_tan=0\n    for i in range(0,6):\n        sum_tan=sum_tan+tbernoulli(2*i)*((-4)**i)*(1-(4**i))*(x**(2*i-1))/float(silnia(2*i))\n    return sum_tan\n\nx=np.pi/3\n\nprint('sin(%.2f)=%.12f' % (x,tsin(x)))\nprint('cos(%.2f)=%.12f' % (x,tcos(x)))\nprint('exp(%.2f)=%.12f' % (x,texp(x)))\nprint('tan(%.2f)=%.12f' % (x,ttan(x)))", "meta": {"hexsha": "ffc53c529e6610a5a8aaf17b5daaf15401b38b02", "size": 1450, "ext": "py", "lang": "Python", "max_stars_repo_path": "MN_lab_3/MN_lab3_zad_1.py", "max_stars_repo_name": "matbocz/kurs-mn-python-pwsz-elblag", "max_stars_repo_head_hexsha": "629d778be7c5d3b6cc217b7ba48e2e0d55ccdf36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MN_lab_3/MN_lab3_zad_1.py", "max_issues_repo_name": "matbocz/kurs-mn-python-pwsz-elblag", "max_issues_repo_head_hexsha": "629d778be7c5d3b6cc217b7ba48e2e0d55ccdf36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MN_lab_3/MN_lab3_zad_1.py", "max_forks_repo_name": "matbocz/kurs-mn-python-pwsz-elblag", "max_forks_repo_head_hexsha": "629d778be7c5d3b6cc217b7ba48e2e0d55ccdf36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8846153846, "max_line_length": 130, "alphanum_fraction": 0.5903448276, "include": true, "reason": "import numpy", "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357585701875, "lm_q2_score": 0.8705972633721707, "lm_q1q2_score": 0.8523458521547025}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 21 00:58:09 2021\n\n@author: Mahfuz_Shazol\n\"\"\"\n\nimport numpy as np\n\nX=np.array([\n            [1,2,4],\n            [2,-1,3],\n            [0,5,1]\n          ])\n\n\ndet_x_result=np.linalg.det(X)\nprint(det_x_result)\n\n\nlambdas,v=np.linalg.eig(X)\nproduct_of_eigon_result=np.product(lambdas)\nprint(product_of_eigon_result)\n\n", "meta": {"hexsha": "dc21f9daab700ed82b349290a26846221d356f88", "size": 359, "ext": "py", "lang": "Python", "max_stars_repo_path": "det(x)_equals_product_of_all_eigen_values_of_X.py", "max_stars_repo_name": "6895mahfuzgit/Linear_Algebra_for_Machine_Learning", "max_stars_repo_head_hexsha": "3f266391491d9ab99e53a3547900c6b1bd657af1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "det(x)_equals_product_of_all_eigen_values_of_X.py", "max_issues_repo_name": "6895mahfuzgit/Linear_Algebra_for_Machine_Learning", "max_issues_repo_head_hexsha": "3f266391491d9ab99e53a3547900c6b1bd657af1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "det(x)_equals_product_of_all_eigen_values_of_X.py", "max_forks_repo_name": "6895mahfuzgit/Linear_Algebra_for_Machine_Learning", "max_forks_repo_head_hexsha": "3f266391491d9ab99e53a3547900c6b1bd657af1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.36, "max_line_length": 43, "alphanum_fraction": 0.6016713092, "include": true, "reason": "import numpy", "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9658995733060718, "lm_q2_score": 0.8824278741843884, "lm_q1q2_score": 0.8523367071480847}}
{"text": "import numpy as np\nimport math\n\n\n\n# Compute the intersection distance between histograms x and y\n# Return 1 - hist_intersection, so smaller values correspond to more similar histograms\n# Check that the distance range in [0,1]\n\ndef dist_intersect(x,y):\n    \n    #... (your code here)\n\n\n\n# Compute the L2 distance between x and y histograms\n# Check that the distance range in [0,sqrt(2)]\n\ndef dist_l2(x,y):\n    \n    #... (your code here)\n\n\n\n# Compute chi2 distance between x and y\n# Check that the distance range in [0,Inf]\n# Add a minimum score to each cell of the histograms (e.g. 1) to avoid division by 0\n\ndef dist_chi2(x,y):\n    \n    #... (your code here)\n\n\n\ndef get_dist_by_name(x, y, dist_name):\n  if dist_name == 'chi2':\n    return dist_chi2(x,y)\n  elif dist_name == 'intersect':\n    return dist_intersect(x,y)\n  elif dist_name == 'l2':\n    return dist_l2(x,y)\n  else:\n    assert False, 'unknown distance: %s'%dist_name\n  \n\n\n\n\n", "meta": {"hexsha": "5a328c535edc40cebbe728a860476ec737c987f1", "size": 933, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignment1/Identification/dist_module.py", "max_stars_repo_name": "HaotianZhang96/FDS_2020_2021", "max_stars_repo_head_hexsha": "c79c5c501b54902b5292742357cba9e33f45a08a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment1/Identification/dist_module.py", "max_issues_repo_name": "HaotianZhang96/FDS_2020_2021", "max_issues_repo_head_hexsha": "c79c5c501b54902b5292742357cba9e33f45a08a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment1/Identification/dist_module.py", "max_forks_repo_name": "HaotianZhang96/FDS_2020_2021", "max_forks_repo_head_hexsha": "c79c5c501b54902b5292742357cba9e33f45a08a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0408163265, "max_line_length": 87, "alphanum_fraction": 0.679528403, "include": true, "reason": "import numpy", "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995752693051, "lm_q2_score": 0.8824278587245935, "lm_q1q2_score": 0.8523366939478872}}
{"text": "## 2. The Mean ##\n\ndistribution = [0,2,3,3,3,4,13]\n\nmean = 4\ncenter =False\nequal_distances = True\n\n\n## 3. The Mean as a Balance Point ##\n\nfrom numpy.random import randint, seed\n\nequal_distances = 0\n\nfor i in range(5000):\n    seed(i)\n    distribution = randint(0,1000,10)\n    mean = sum(distribution)/len(distribution)\n    \n    above_mean = []\n    below_mean = []\n    for value in distribution:\n        if value == mean:\n            continue\n        if value < mean:\n            below_mean.append(mean - value)\n        if value > mean:\n            above_mean.append(value -mean)\n            \n    sum_above = round(sum(above_mean),1)\n    sum_below =round(sum(below_mean),1)\n    if (sum_above==sum_below):\n        equal_distances+=1\n        \nprint(equal_distances)\n        \n        \n\n## 4. Defining the Mean Algebraically ##\n\none = False\n\ntwo = False\n\nthree =  False\n\n## 5. An Alternative Definition ##\n\ndistribution_1 = [42, 24, 32, 11]\ndistribution_2 = [102, 32, 74, 15, 38, 45, 22]\ndistribution_3 = [3, 12, 7, 2, 15, 1, 21]\n\ndef mean(distribution):\n    sum_distribution = 0\n    for value in distribution:\n        sum_distribution += value\n     \n    return sum_distribution / len(distribution)\n\nmean_1 = mean(distribution_1)\nmean_2 = mean(distribution_2)\nmean_3 =  mean(distribution_3)\n\nprint(mean_1)\nprint(mean_2)\nprint(mean_3)\n    \n\n## 6. Introducing the Data ##\n\nimport pandas as pd\n\nhouses = pd.read_table('AmesHousing_1.txt', sep = '\\t')\nprint(houses.head())\n\none =  True\n\ntwo = False\n\nthree = True\n\n## 7. Mean House Prices ##\n\ndef mean(distribution):\n    sum_distribution = 0\n    for value in distribution:\n        sum_distribution += value\n        \n    return sum_distribution / len(distribution)\n\nfunction_mean = mean(houses['SalePrice'])\n\npandas_mean =  houses['SalePrice'].mean()\nmeans_are_equal = function_mean ==  pandas_mean\n\nprint(function_mean ,pandas_mean, means_are_equal)\n\n## 8. Estimating the Population Mean ##\n\nparameter = houses['SalePrice'].mean()\n\nsample_size = 5\n\nsample_sizes = []\nsampling_errors = []\n\nfor i in range(101):\n    sample = houses['SalePrice'].sample(sample_size, random_state = i)\n    \n    statistic = sample.mean()\n    sampling_error = parameter - statistic\n    sampling_errors.append(sampling_error)\n    sample_sizes.append(sample_size)\n    sample_size +=29\n    \n    \nimport matplotlib.pyplot as plt\n\nplt.scatter(sample_sizes, sampling_errors)\nplt.axhline(0)\nplt.axvline(2930)\nplt.xlabel('Sample size')\nplt.ylabel('Sampling error')\n\n## 9. Estimates from Low-Sized Samples ##\n\nmeans = []\n\nfor i in range(10000):\n    sample = houses['SalePrice'].sample(100, random_state = i)\n    means.append(sample.mean())\n    \nplt.hist(means)\nplt.axvline(houses['SalePrice'].mean())\nplt.xlabel('Sample mean')\nplt.ylabel('Frequency')\nplt.xlim(0,500000)\n\n## 11. The Sample Mean as an Unbiased Estimator ##\n\npopulation = [3, 7, 2]\nsamples = [[3, 7], [3, 2],\n           [7, 2], [7, 3],\n           [2, 3], [2, 7]\n          ]\n\nsample_means = []\nfor sample in samples:\n    sample_means.append(sum(sample) / len(sample))\n    \npopulation_mean = sum(population) / len(population)\nmean_of_sample_means = sum(sample_means) / len(sample_means)\n\nunbiased = (population_mean == mean_of_sample_means)\nprint(population_mean)\nprint(sample_means)\nprint(mean_of_sample_means)\nprint(unbiased)", "meta": {"hexsha": "699faa8990df4804de2f25e727f9f58203d1dcfd", "size": 3296, "ext": "py", "lang": "Python", "max_stars_repo_path": "5. Probability and Statistics/statistics-intermediate/The Mean-305.py", "max_stars_repo_name": "bibekuchiha/dataquest", "max_stars_repo_head_hexsha": "c7d8a2966fe2eee864442a59d64309033ea9993e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5. Probability and Statistics/statistics-intermediate/The Mean-305.py", "max_issues_repo_name": "bibekuchiha/dataquest", "max_issues_repo_head_hexsha": "c7d8a2966fe2eee864442a59d64309033ea9993e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5. Probability and Statistics/statistics-intermediate/The Mean-305.py", "max_forks_repo_name": "bibekuchiha/dataquest", "max_forks_repo_head_hexsha": "c7d8a2966fe2eee864442a59d64309033ea9993e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7295597484, "max_line_length": 70, "alphanum_fraction": 0.6644417476, "include": true, "reason": "from numpy", "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538935, "lm_q2_score": 0.901920685097536, "lm_q1q2_score": 0.8523102819874554}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n-----------------------------------------------------------------------------\r\nEjercicio 2: Integración - Fórmulas de cuadratura compuestas.\r\n-----------------------------------------------------------------------------\r\n\"\"\"\r\nimport numpy as np\r\nimport sympy as sym\r\n\r\n\r\n# Cálculo de la integral exacta de la función f(x) = exp(x) en [0,3]\r\n#---------------------------------------------------------------------\r\nx = sym.Symbol('x', real=True)            # definimos la variable x simbólica\r\nf = sym.exp(x)            # definimos la función f simbólica \r\nI_exacta = sym.integrate(f,(x,0,3))\r\nI_exacta = float(I_exacta)\r\nprint ('El valor exacto es: ',I_exacta)   \r\n\r\n\r\n\"\"\"\r\nEjercicio 2a: Integración - Fórmula del punto medio compuesta.\r\n-----------------------------------------------------------------------------\r\nFunción punto_medio_comp: Halla la integral aproximada utilizando la fórmula del \r\npunto medio compuesta para una función f en un intervalo [a,b]. \r\n\r\nArgumentos de entrada:\r\n    f:  función integrando (función lambda).\r\n    a:  extremo inferior del intervalo de integración (número real).\r\n    b:  extremo superior del intervalo de integración (número real).\r\n    n:  número de subintervalos (número entero).\r\n             \r\nArgumentos de salida:\r\n    I:  integral aproximada con la fórmula del punto medio compuesta de la función\r\n        f en [a,b] (número real).\r\n    \r\nEjemplos:\r\n    f = lambda x : x**2\r\n    I = punto_medio_comp(f,0,2,4)\r\n    print('Ejemplo de prueba con punto medio compuesta =', I)\r\n    Salida:\r\n        Ejemplo de prueba con punto medio compuesta = 2.625\r\n\"\"\"\r\n\r\n\r\n# Función punto_medio_comp\r\n#--------------------------------------\r\ndef punto_medio_comp(f,a,b,n):\r\n    h = (b-a)/float(n)              # longitud de los subintervalos\r\n    x = np.arange(a,b+h,h) # vector que contiene los puntos medios de los subintervalos\r\n    I = 0.0\r\n    for i in range(1,n+1):\r\n        I += f((x[i-1]+x[i])/2.0)\r\n    I = h*I       # fórmula del punto medio compuesta\r\n    return I\r\n\r\n#--------------------------------------\r\n# Ejemplos\r\n#--------------------------------------\r\n\r\n# Ejemplo de prueba\r\nf = lambda x : x**2\r\nI = punto_medio_comp(f,0,2,4)\r\nprint('Ejemplo de prueba con punto medio compuesta =', I)\r\n\r\n#--------------------------------------\r\n# Ejercicio 2a\r\n#--------------------------------------\r\n\r\n# Cálculo de la integral aproximada\r\n#---------------------------------------\r\nf = lambda x :np.exp(x)\r\na = 0\r\nb = 3\r\nn = 5\r\nIpmc = punto_medio_comp(f,a,b,n)\r\n\r\nprint ('El valor aproximado con punto medio compuesta es:', Ipmc)\r\n\r\n\r\n\"\"\"\r\nEjercicio 2b: Integración - Fórmula del trapecio compuesta.\r\n-----------------------------------------------------------------------------\r\nFunción trapecio_comp: Halla la integral aproximada utilizando la fórmula del \r\ntrapecio compuesta para una función f en un intervalo [a,b]. \r\n\r\nArgumentos de entrada:\r\n    f:  función integrando (función lambda).\r\n    a:  extremo inferior del intervalo de integración (número real).\r\n    b:  extremo superior del intervalo de integración (número real).\r\n    n:  número de subintervalos (número entero).\r\n             \r\nArgumentos de salida:\r\n    I:  integral aproximada con la fórmula del trapecio compuesta de la función\r\n        f en [a,b] (número real).\r\n    \r\nEjemplos:\r\n    f = lambda x : x**2\r\n    I = trapecio_comp(f,0,2,4)\r\n    print('Ejemplo de prueba con trapecio compuesta =', I)\r\n    Salida:\r\n        Ejemplo de prueba con trapecio compuesta = 2.75\r\n\"\"\"\r\n\r\n\r\n# Función trapecio_comp\r\n#--------------------------------------\r\ndef trapecio_comp(f,a,b,n):\r\n    h = (b-a)/float(n)            # longitud del intervalo\r\n    x = np.arange(a,b+h,h) # vector que contiene los nodos intermedios\r\n    I = 0.0\r\n    for i in range(1,n):\r\n        I += f(x[i])\r\n    I = (h/2.0)*(f(a)+f(b)) + h*I           # fórmula del trapecio compuesta\r\n    return I\r\n\r\n#--------------------------------------\r\n# Ejemplos\r\n#--------------------------------------\r\n\r\n# Ejemplo de prueba\r\nf = lambda x : x**2\r\nI = trapecio_comp(f,0,2,4)\r\nprint('Ejemplo de prueba con trapecio compuesta =', I)\r\n\r\n#--------------------------------------\r\n# Ejercicio 2b\r\n#--------------------------------------\r\n\r\n# Cálculo de la integral aproximada\r\n#---------------------------------------\r\nf = lambda x :np.exp(x)\r\na = 0\r\nb = 3\r\nn = 4\r\nItc = trapecio_comp(f,a,b,n)\r\n\r\nprint ('El valor aproximado con trapecio compuesta es:', Itc)\r\n\r\n\r\n\"\"\"\r\nEjercicio 2c: Integración - Fórmula de Simpson compuesta.\r\n-----------------------------------------------------------------------------\r\nFunción simpson_comp: Halla la integral aproximada utilizando la fórmula de \r\nSimpson compuesta para una función f en un intervalo [a,b]. \r\n\r\nArgumentos de entrada:\r\n    f:  función integrando (función lambda).\r\n    a:  extremo inferior del intervalo de integración (número real).\r\n    b:  extremo superior del intervalo de integración (número real).\r\n    n:  número de subintervalos (número entero).\r\n             \r\nArgumentos de salida:\r\n    I:  integral aproximada con la fórmula de Simpson compuesta de la función\r\n        f en [a,b] (número real).\r\n    \r\nEjemplos:\r\n    f = lambda x : x**2\r\n    I = simpson_comp(f,0,2,6)\r\n    print('Ejemplo de prueba con Simpson compuesta =', I)\r\n    Salida:\r\n        Ejemplo de prueba con Simpson compuesta = 2.6666666666666665\r\n\"\"\"\r\n\r\n# Función simpson_comp\r\n#--------------------------------------\r\ndef simpson_comp(f,a,b,n):\r\n    h = (b-a)/float(n)                                 # longitud de los subintervalos \r\n    x1 = np.arange(a,b+h,h) # nodos que separan los subintervalos\r\n    I = 0.0                                 # fórmula de Simpson compuesta\r\n    for i in range(1,n+1,1): \r\n        I += f(x1[i-1]) + 4.0*f((x1[i-1]+x1[i])/2.0) + f(x1[i])\r\n    I = (h/6.0)*I\r\n    return I\r\n\r\n#--------------------------------------\r\n# Ejemplos\r\n#--------------------------------------\r\n\r\n# Ejemplo de prueba\r\nf = lambda x : x**2\r\nI = simpson_comp(f,0,2,6)\r\nprint('Ejemplo de prueba con Simpson compuesta =', I)\r\n\r\n#--------------------------------------\r\n# Ejercicio 2c\r\n#--------------------------------------\r\n\r\n# Cálculo de la integral aproximada\r\n#---------------------------------------\r\nf = lambda x :np.exp(x)\r\na = 0\r\nb = 3\r\nn = 4\r\nIts = simpson_comp(f,a,b,n)\r\n\r\nprint ('El valor aproximado con Simpson compuesta es:', Its)", "meta": {"hexsha": "efd4292c6e7b9478c1d8bb7bedaec54bfcb10705", "size": 6365, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ej-Lab9-MoisesSanjurjo-UO270824/ejercicio2-MoisesSanjurjo-UO270824.py", "max_stars_repo_name": "moiSS00/CN", "max_stars_repo_head_hexsha": "1e30b43ee2167d15fbc8c472ff9637c2b920c3d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ej-Lab9-MoisesSanjurjo-UO270824/ejercicio2-MoisesSanjurjo-UO270824.py", "max_issues_repo_name": "moiSS00/CN", "max_issues_repo_head_hexsha": "1e30b43ee2167d15fbc8c472ff9637c2b920c3d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ej-Lab9-MoisesSanjurjo-UO270824/ejercicio2-MoisesSanjurjo-UO270824.py", "max_forks_repo_name": "moiSS00/CN", "max_forks_repo_head_hexsha": "1e30b43ee2167d15fbc8c472ff9637c2b920c3d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4744897959, "max_line_length": 88, "alphanum_fraction": 0.5124901807, "include": true, "reason": "import numpy,import sympy", "num_tokens": 1684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538935, "lm_q2_score": 0.9019206752113866, "lm_q1q2_score": 0.8523102726450964}}
{"text": "import numpy as np\r\nfrom numpy import linalg as linAlg\r\nimport math\r\nimport pandas as pd\r\nfrom random import shuffle\r\nfrom matplotlib import pyplot as plt\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.pyplot as pause\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfrom time import sleep\r\nimport matplotlib.animation as animation\r\nimport sys\r\n\r\ndef plotPoints(plotOutFunction, fy=[], fx=[],tau=-1):\r\n\tx = []\r\n\ty = []\r\n\t\r\n\tfor i in range(len(xyPoints)):\r\n\t\tx.append(xyPoints[i][0])\r\n\t\ty.append(xyPoints[i][len(xyPoints[0])-1])\r\n\t\r\n\tif tau == -1:\r\n\t\tplt.title(\"XY points and predicted function for Linear Regression\")\r\n\telse:\r\n\t\tplt.title(\"XY points and predicted function for weighted Regression with tau = \" + str(tau))\r\n\tplt.scatter(x,y,color='blue',label='Original Plot')\r\n\tif (plotOutFunction == 1):\r\n\t\tplt.scatter(fx,fy,color='red',label='Predicted Plot')\r\n\r\n\tplt.xlabel(\"Input Data\")\r\n\tplt.ylabel(\"Output Data\")\r\n\tplt.legend()\r\n\r\n\tplt.show()\t\r\n\r\n\r\ndef readPoints(fileX,fileY):\r\n\tnoOfPoints = 0\r\n\txyPoints = []\r\n\r\n\tf1 = open(fileX, \"r\")\r\n\tf2 = open(fileY, \"r\")\r\n\r\n\txPoint = f1.read().splitlines()\r\n\tyPoint = f2.read().splitlines()\r\n\r\n\tfor i in range(len(xPoint)):\r\n\t\txy1Point = []\r\n\t\txy1Point.append(float(xPoint[i]))\r\n\t\txy1Point.append(1.0)\t\t\t# This is the value corresponding to theta0 (since theta0 is the intercept)\r\n\t\txy1Point.append(float(yPoint[i]))\r\n\r\n\t\txyPoints.append(xy1Point)\r\n\t\tnoOfPoints = noOfPoints + 1\r\n\r\n\tf1.close()\r\n\tf2.close()\r\n\r\n\treturn xyPoints, noOfPoints\r\n\r\ndef normalize(xyPoints, mean, var):\r\n\tfor i in range(len(xyPoints[0])):\r\n\t\tif (i == len(xyPoints[0])-2):\t\t# Ignore the second last col and last col. Second last col is 1.0 that denotes intercept\r\n\t\t\tbreak\r\n\r\n\t\tx = []\r\n\t\tfor j in range(len(xyPoints)):\r\n\t\t\tx.append(xyPoints[j][i])\r\n\r\n\t\tmean[i]=(np.mean(x))\r\n\t\tvar[i]=(np.std(x))\r\n\r\n\t\tfor j in range(len(xyPoints)):\r\n\t\t\txyPoints[j][i] = (xyPoints[j][i] - mean[i]) / var[i]\r\n\r\n\treturn xyPoints,mean,var\r\n\r\ndef getPredictedY(xyPoints, thetaVec):\r\n\tfy = []\r\n\ty = [0] * len(xyPoints)\r\n\r\n\tfor k in range(len(xyPoints)):\r\n\t\tfy1 = 0.0\r\n\t\tfor i in range(len(thetaVec)):\r\n\t\t\tfy1 = fy1 + thetaVec[i] * xyPoints[k][i]\r\n\r\n\t\tfy.append(fy1)\r\n\t\ty[k] = xyPoints[k][len(xyPoints[0])-1]\r\n\r\n\treturn fy\r\n\r\ndef unormalize(xyPoints, mean, var, pfx=[], isFxAvailable=False):\r\n\tfx = pfx\r\n\tif isFxAvailable == False:\r\n\t\tfx = [0] * len(xyPoints)\r\n\r\n\tfor i in range(len(xyPoints[0])):\r\n\t\tif (i == len(xyPoints[0])-2):\r\n\t\t\tbreak\r\n\r\n\t\tfor j in range(len(xyPoints)):\r\n\t\t\txyPoints[j][i] = (xyPoints[j][i] * var[i]) + mean[i]\r\n\r\n\t\t\tif isFxAvailable == True:\r\n\t\t\t\tfx[j] = (fx[j] * var[i]) + mean[i]\r\n\t\t\telse:\r\n\t\t\t\tfx[j] = xyPoints[j][i]\r\n\r\n\treturn xyPoints, fx\r\n\r\ndef calculateTheta(xyPoints, thetaVec, weights, isWeightedLinearReg):\r\n\tX = np.zeros((len(xyPoints), 2))\r\n\tXt = np.zeros((2, len(xyPoints)))\r\n\tY = np.zeros((len(xyPoints), 1))\r\n\tW = np.zeros((len(xyPoints), len(xyPoints)))\r\n\r\n\tfor i in range(len(xyPoints)):\r\n\t\tfor j in range(len(xyPoints[i])-1):\r\n\t\t\tX[i][j] = xyPoints[i][j]\r\n\t\t\tXt[j][i] = xyPoints[i][j]\r\n\r\n\tfor i in range(len(weights)):\r\n\t\tW[i][i] = weights[i]\r\n\r\n\tfor i in range(len(xyPoints)):\r\n\t\tY[i][0] = xyPoints[i][len(xyPoints[0])-1]\r\n\r\n\tthetaVec = linAlg.inv(Xt @ X) @ Xt @ Y\r\n\tif isWeightedLinearReg == True:\r\n\t\tthetaVec = linAlg.inv(Xt @ W @ X) @ Xt @ W @ Y\r\n\r\n\tthetaVecRet = [0] * (len(thetaVec))\r\n\tfor i in range(len(thetaVec)):\r\n\t\tthetaVecRet[i] = thetaVec[i][0]\r\n\r\n\treturn thetaVecRet\r\n\r\ndef getWeights(xyPoints, noOfPoints, pointToProcess, weights, tau):\r\n\tfor i in range(noOfPoints):\r\n\t\tdiff = 0.0\r\n\t\tfor j in range(len(xyPoints[i])-1):\r\n\t\t\tdiff = diff + (pointToProcess[j] - xyPoints[i][j]) * (pointToProcess[j] - xyPoints[i][j])\r\n\r\n\t\tweights[i] = math.exp(-1 * (diff / (2 * tau * tau)))\r\n\r\n\treturn weights\r\n\r\ndef linearRegression(xyPoints, noOfPoints, pointToProcess, isWeightedLinearReg, tau = 0):\t\r\n\tthetaVec = [0] * (len(xyPoints[0]) - 1)\t\t# Last col is y so we will subtract that col in thetaVec and last theta is O0 which we will add a column in theta Vec\r\n\tweights = [1] * (noOfPoints)\r\n\r\n\tif isWeightedLinearReg == True:\r\n\t\tweights = getWeights(xyPoints, noOfPoints, pointToProcess, weights, tau)\r\n\t\r\n\tthetaVec = calculateTheta(xyPoints, thetaVec, weights, isWeightedLinearReg)\r\n\tfy = getPredictedY(xyPoints, thetaVec)\r\n\t\r\n\treturn fy,thetaVec\r\n\t\r\ndef weightedLinearRegression(xyPoints, noOfPoints, tau):\r\n\tfyFinal = [1] * (noOfPoints)\r\n\txFinal = [1] * (noOfPoints)\r\n\tcntr = 0\r\n\r\n\tminEle = 100000\r\n\tmaxEle = -100000\r\n\tfor i in range(len(xyPoints)):\r\n\t\tif minEle > xyPoints[i][0]:\r\n\t\t\tminEle = xyPoints[i][0]\r\n\t\tif maxEle < xyPoints[i][0]:\r\n\t\t\tmaxEle = xyPoints[i][0]\r\n\tpoints = np.linspace(minEle, maxEle, noOfPoints)\r\n\t#for i in range(len(xyPoints)):\r\n\t#\tpoints[i] = xyPoints[i][0]\r\n\r\n\twhile cntr < noOfPoints:\r\n\t\tpointToProcess = [1] * (len(xyPoints[0])-1)\r\n\t\tpointToProcess[0] = points[cntr]\r\n\t\t\r\n\t\tfy,thetaVec = linearRegression(xyPoints, noOfPoints, pointToProcess, True, tau)\t\t# True - Is weighted linear regression\r\n\r\n\t\tpredictedPointToProcess = 0.0\r\n\t\tfor j in range(len(thetaVec)):\r\n\t\t\tpredictedPointToProcess = predictedPointToProcess + thetaVec[j] * pointToProcess[j]\r\n\r\n\t\tfyFinal[cntr] = predictedPointToProcess\r\n\t\txFinal[cntr] = pointToProcess[0]\r\n\r\n\t\tcntr = cntr + 1\r\n\r\n\treturn fyFinal,xFinal\r\n\r\nfileX = sys.argv[1] # prints python_script.py\r\nfileY = sys.argv[2] # prints var1\r\ntau = float(sys.argv[3]) # prints var2\r\n\r\nxyPoints,noOfPoints = readPoints(fileX, fileY)\r\n\r\nmean = [0] * len(xyPoints[0])\r\nvar = [0] * len(xyPoints[0])\r\n\r\n######### (a)\r\nxyPoints,mean,var = normalize(xyPoints, mean, var)\r\n\r\nfy,thetaVec = linearRegression(xyPoints, noOfPoints, [], False)\t\t\t\t\t# False - Is not weighted linear regression\r\n\r\nxyPoints,fx = unormalize(xyPoints, mean, var, [], False)\r\nplotPoints(1,fy,fx)\r\n\r\n######### (b)\r\nxyPoints,mean,var = normalize(xyPoints, mean, var)\r\n\r\n#tau =0.8\r\nfy,fx = weightedLinearRegression(xyPoints, noOfPoints, tau)\r\n\r\nxyPoints,fx = unormalize(xyPoints, mean, var, fx, True)\r\nplotPoints(1,fy, fx,tau)\r\n\r\n######### (c)\r\ntauList = [0.1, 0.3, 2, 10]\r\nfor i in range(len(tauList)):\r\n\txyPoints,mean,var = normalize(xyPoints, mean, var)\r\n\r\n\ttau = tauList[i]\r\n\tfy,fx = weightedLinearRegression(xyPoints, noOfPoints, tau)\r\n\r\n\txyPoints,fx = unormalize(xyPoints, mean, var, fx, True)\r\n\tplotPoints(1,fy,fx,tau)\r\n", "meta": {"hexsha": "441ccca8c364d7051e28fbbe2a6e4ef31b26c095", "size": 6279, "ext": "py", "lang": "Python", "max_stars_repo_path": "Q2.py", "max_stars_repo_name": "tkanvar/LinearRegression", "max_stars_repo_head_hexsha": "18f6a72e7edb208c55b7d591d8a70a34705b29ad", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-24T19:32:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-24T19:32:57.000Z", "max_issues_repo_path": "Q2.py", "max_issues_repo_name": "tkanvar/Linear-Logistic-WeightedLnr-GDA", "max_issues_repo_head_hexsha": "18f6a72e7edb208c55b7d591d8a70a34705b29ad", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Q2.py", "max_forks_repo_name": "tkanvar/Linear-Logistic-WeightedLnr-GDA", "max_forks_repo_head_hexsha": "18f6a72e7edb208c55b7d591d8a70a34705b29ad", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4192139738, "max_line_length": 160, "alphanum_fraction": 0.652173913, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535094, "lm_q2_score": 0.890294230488237, "lm_q1q2_score": 0.8522589044988176}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Jérôme Eberhardt 2016-2020\n# Unrolr\n#\n# Principal Component Analysis\n# Author: Jérôme Eberhardt <qksoneo@gmail.com>\n#\n# License: MIT\n\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport numpy as np\nfrom scipy import linalg\n\n__author__ = \"Jérôme Eberhardt\"\n__copyright__ = \"Copyright 2020, Jérôme Eberhardt\"\n\n__lience__ = \"MIT\"\n__maintainer__ = \"Jérôme Eberhardt\"\n__email__ = \"qksoneo@gmail.com\"\n\n\nclass PCA:\n\n    def __init__(self, n_components=None):\n        \"\"\"Create DihedralPCa object\n\n        Args:\n            n_components (int, None): Number of components to keep. if n_components is not set all components are kept.\n\n        \"\"\"\n        self._n_components = n_components\n        self.components = None\n        self.singular_values = None\n\n    def fit_transform(self, X):\n        \"\"\"Fit the model with X and apply the dimensionality reduction on X.\n\n        Args:\n            X (ndarray): array-like, shape (n_samples, n_features)\n\n        Returns:\n            ndarray: final embedding (n_samples, n_components)\n\n        \"\"\"\n        # Centering the data\n        X -= np.mean(X, axis=0)  \n        # Compute covariance matrix\n        cov = np.cov(X, rowvar=False)\n        # PCA!!!\n        singular_values , components = linalg.eigh(cov)\n\n        # Sort by singular values\n        idx = np.argsort(singular_values)[::-1]\n        self.components = components[:, idx].T\n        self.singular_values = singular_values[idx]\n\n        if self._n_components is None:\n            embedding = np.dot(X, self.components)\n        else:\n            embedding = np.dot(X, self.components[:int(self._n_components)].T)\n\n        return embedding\n", "meta": {"hexsha": "d180771979ae339da42bca78f7809b5ebb13fad4", "size": 1750, "ext": "py", "lang": "Python", "max_stars_repo_path": "unrolr/core/pca.py", "max_stars_repo_name": "jeeberhardt/unrolr", "max_stars_repo_head_hexsha": "76d432643525a1999a6b14d6af500b9ffb296b82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-06-05T19:44:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T04:42:25.000Z", "max_issues_repo_path": "unrolr/core/pca.py", "max_issues_repo_name": "jeeberhardt/unrolr", "max_issues_repo_head_hexsha": "76d432643525a1999a6b14d6af500b9ffb296b82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unrolr/core/pca.py", "max_forks_repo_name": "jeeberhardt/unrolr", "max_forks_repo_head_hexsha": "76d432643525a1999a6b14d6af500b9ffb296b82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-21T16:57:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-21T16:57:52.000Z", "avg_line_length": 25.3623188406, "max_line_length": 119, "alphanum_fraction": 0.6451428571, "include": true, "reason": "import numpy,from scipy", "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778048911612, "lm_q2_score": 0.8902942159342103, "lm_q1q2_score": 0.8522588927367983}}
{"text": "\"\"\"\nThis file represents an abstract activation function and many well-known activation functions\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nimport math\n\nimport numpy as np\n\n\nclass AbstractActivation(ABC):\n    @abstractmethod\n    def get_value(self, x: np.array):\n        \"\"\"\n        The value of the activation on the array (element wise operation)\n        \"\"\"\n\n    @abstractmethod\n    def get_derivative(self, x: np.array, value_at_x: np.array = None):\n        \"\"\"\n        Get the derivative of the activation function on x (element wise operation)\n        \"\"\"\n\n    def get_approximate_derivative(self, x: np.array, eps: float = math.pow(10, -7)):\n        \"\"\"\n        :param x: the array on which we want to compute the approximate derivative (element wise)\n        :param eps: the epsilon used for the approximation (we recommend to not change it)\n        :return: the approximate derivative\n        \"\"\"\n        return (self.get_value(x + eps) - self.get_value(x - eps)) / (2 * eps)\n\n\nclass Sigmoid(AbstractActivation):\n    def get_value(self, x: np.array) -> np.array:\n\n        return 1 / (1 + np.exp(-x))\n\n    def get_derivative(self, x: np.array, value_at_x: np.array = None) -> np.array:\n\n        # The derivative on x is equal to sigmoid(x) * (1 - sigmoid(x))\n        if value_at_x is None:\n            sigmoid_value = self.get_value(x)\n        else:\n            sigmoid_value = value_at_x\n\n        return sigmoid_value * (1 - sigmoid_value)\n\n\nclass Relu(AbstractActivation):\n    def get_value(self, x: np.array) -> np.array:\n\n        return np.maximum(x, 0)\n\n    def get_derivative(self, x: np.array, value_at_x: np.array = None) -> np.array:\n\n        # The derivative of relu is 0 when value is less than 0 else 1\n        # Mathematically speaking, there is no derivative on 0, but we will consider that it is\n        # equal to 1\n\n        return x >= 0\n\n    def get_approximate_derivative(self, x: np.array, eps: float = math.pow(10, -7)):\n\n        # We highly do not recommend to use the approxilate derivative when using a relu function\n        raise Exception(\"Do not use derivative approximate on Relu\")\n\n\nclass Tanh(AbstractActivation):\n    def get_value(self, x: np.array) -> np.array:\n\n        return np.tanh(x)\n\n    def get_derivative(self, x: np.array, value_at_x: np.array = None) -> np.array:\n\n        # The derivative on x is equal to 1 + tanh^2\n        if value_at_x is None:\n            tanh_value = self.get_value(x)\n        else:\n            tanh_value = value_at_x\n        return 1 - np.power(tanh_value, 2)\n", "meta": {"hexsha": "e344d34fa24bd784ae626e1e4ec56ed8cbaf631b", "size": 2534, "ext": "py", "lang": "Python", "max_stars_repo_path": "pystork/activations.py", "max_stars_repo_name": "yassineameur/pystork", "max_stars_repo_head_hexsha": "6d962d62c2c61e7a91e6d02936a45f66a9f6e283", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pystork/activations.py", "max_issues_repo_name": "yassineameur/pystork", "max_issues_repo_head_hexsha": "6d962d62c2c61e7a91e6d02936a45f66a9f6e283", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pystork/activations.py", "max_forks_repo_name": "yassineameur/pystork", "max_forks_repo_head_hexsha": "6d962d62c2c61e7a91e6d02936a45f66a9f6e283", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2839506173, "max_line_length": 97, "alphanum_fraction": 0.6400947119, "include": true, "reason": "import numpy", "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723354, "lm_q2_score": 0.8902942159342104, "lm_q1q2_score": 0.8522588916516849}}
{"text": "# ポアソン分布\n\n# 利用するライブラリ\nimport numpy as np\nfrom scipy.stats import poisson # ポアソン分布\nfrom scipy.special import gamma, loggamma # ガンマ関数, 対数ガンマ関数\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n#%%\n\n### 確率の計算\n\n# パラメータを指定\nlmd = 4.0\n\n# 確率変数の値を指定\nx = 2.0\n\n\n# 定義式により確率を計算\nprob = lmd**x / gamma(x + 1.0) * np.exp(-lmd)\nprint(prob)\n\n# 対数をとった定義式により確率を計算\nlog_prob = x * np.log(lmd) - loggamma(x + 1.0) - lmd\nprob = np.exp(log_prob)\nprint(prob, log_prob)\n\n# ポアソン分布の関数により確率を計算\nprob = poisson.pmf(k=x, mu=lmd)\nprint(prob)\n\n# ポアソン分布の対数をとった関数により確率を計算\nlog_prob = poisson.logpmf(k=x, mu=lmd)\nprob = np.exp(log_prob)\nprint(prob, log_prob)\n\n#%%\n\n### 統計量の計算\n\n# パラメータを指定\nlmd = 4.0\n\n\n# 計算式により平均を計算\nE_x = lmd\nprint(E_x)\n\n# 計算式により分散を計算\nV_x = lmd\nprint(V_x)\n\n# ポアソン分布の関数により平均を計算\nE_x = poisson.mean(mu=lmd)\nprint(E_x)\n\n# ポアソン分布の関数により分散を計算\nV_x = poisson.var(mu=lmd)\nprint(V_x)\n\n#%%\n\n### 分布の可視化\n\n## 分布の計算\n\n# パラメータを指定\nlmd = 4.0\n\n# 作図用のxの点を作成\nx_vals = np.arange(np.ceil(lmd) * 4.0)\n\n# ポアソン分布を計算\nprobability = poisson.pmf(k=x_vals, mu=lmd)\n\n#%%\n\n## 分布の作図\n\n# ポアソン分布を作図\nplt.figure(figsize=(12, 9)) # 図の設定\nplt.bar(x=x_vals, height=probability, color='#00A968') # 棒グラフ\nplt.xlabel('x') # x軸ラベル\nplt.ylabel('probability') # y軸ラベル\nplt.suptitle('Poisson Distribution', fontsize=20) # 全体のタイトル\nplt.title('$\\lambda=' + str(lmd) + '$', loc='left') # タイトル\nplt.xticks(ticks=x_vals) # x軸目盛\nplt.grid() # グリッド線\nplt.show() # 描画\n\n#%%\n\n# 統計量を計算\nE_x = lmd\ns_x = np.sqrt(lmd)\n\n# 統計量を重ねたポアソン分布を作図\nplt.figure(figsize=(12, 9)) # 図の設定\nplt.bar(x=x_vals, height=probability, color='#00A968') # 分布\nplt.vlines(x=E_x, ymin=0.0, ymax=probability.max(), color='orange', linewidth=2.5, linestyle='--', label='$E[x]$') # 平均\nplt.vlines(x=E_x - s_x, ymin=0.0, ymax=probability.max(), color='orange', linewidth=2.5, linestyle=':', label='$E[x] \\pm \\\\sqrt{V[x]}$') # 平均 - 標準偏差\nplt.vlines(x=E_x + s_x, ymin=0.0, ymax=probability.max(), color='orange', linewidth=2.5, linestyle=':') # 平均 + 標準偏差\nplt.xlabel('x') # x軸ラベル\nplt.ylabel('probability') # y軸ラベル\nplt.suptitle('Poisson Distribution', fontsize=20)# 全体のタイトル\nplt.title('$\\lambda=' + str(lmd) + '$', loc='left') # タイトル\nplt.xticks(ticks=x_vals) # x軸目盛\nplt.legend() # 凡例\nplt.grid() # グリッド線\nplt.show() # 描画\n\n#%%\n\n### パラメータと分布の形状の関係\n\n# lambdaとして利用する値を指定\nlambda_vals = np.arange(start=0.0, stop=10.1, step=0.1)\nprint(len(lambda_vals)) # フレーム数\n\n# 作図用のxの点を作成\nx_vals = np.arange(np.ceil(lambda_vals.max()) * 2.0)\n\n# y軸(確率)の最大値を設定\nprob_max = np.max(poisson.pmf(k=x_vals, mu=lambda_vals.min())) + 0.1\n#prob_max = 0.5\n\n# 図を初期化\nfig = plt.figure(figsize=(12, 9)) # 図の設定\nfig.suptitle('Poisson Distribution', fontsize=20)# 全体のタイトル\n\n# 作図処理を関数として定義\ndef update(i):\n    # 前フレームのグラフを初期化\n    plt.cla()\n    \n    # i回目のパラメータを取得\n    lmd = lambda_vals[i]\n    \n    # ポアソン分布を計算\n    probability = poisson.pmf(k=x_vals, mu=lmd)\n    \n    # ポアソン分布を作図\n    plt.bar(x=x_vals, height=probability, color='#00A968') # 棒グラフ\n    plt.xlabel('x') # x軸ラベル\n    plt.ylabel('probability') # y軸ラベル\n    plt.title('$\\lambda=' + str(np.round(lmd, 1)) + '$', loc='left') # タイトル\n    plt.xticks(ticks=x_vals) # x軸目盛\n    plt.grid() # グリッド線\n    plt.ylim(ymin=0.0, ymax=prob_max) # y軸の表示範囲\n\n# gif画像を作成\nanime_prob = FuncAnimation(fig, update, frames=len(lambda_vals), interval=100)\n\n# gif画像を保存\nanime_prob.save('ProbabilityDistribution/Poisson_prob.gif')\n\n#%%\n\n### 乱数の生成\n\n## 乱数の生成\n\n# パラメータを指定\nlmd = 4.0\n\n# データ数(サンプルサイズ)を指定\nN = 1000\n\n# ポアソン分布に従う乱数を生成\nx_n = np.random.poisson(lam=lmd, size=N)\n\n# 作図用のxの点を作成\nx_vals = np.arange(x_n.max() + 5.0)\n\n# 乱数を集計\nfrequency = np.array([np.sum(x_n == m) for m in x_vals])\n\n# ポアソン分布を計算\nprobability = poisson.pmf(k=x_vals, mu=lmd)\n\n#%%\n\n## 乱数の可視化\n\n# サンプルのヒストグラムを作成\nplt.figure(figsize=(12, 9)) # 図の設定\nplt.bar(x=x_vals, height=frequency, color='#00A968') # ヒストグラム\nplt.xlabel('x') # x軸ラベル\nplt.ylabel('frequency') # y軸ラベル\nplt.suptitle('Poisson Distribution', fontsize=20)# 全体のタイトル\nplt.title('$\\lambda=' + str(lmd) + ', N=' + str(N) + \n          '=(' + ', '.join([str(f) for f in frequency]) + ')$', loc='left') # タイトル\nplt.xticks(ticks=x_vals) # x軸目盛\nplt.grid() # グリッド線\nplt.show() # 描画\n\n#%%\n\n# サンプルの構成比を作図\nplt.figure(figsize=(12, 9)) # 図の設定\nplt.bar(x=x_vals, height=probability, color='white', edgecolor='green', linestyle='--') # 元の分布\nplt.bar(x=x_vals, height=frequency / N, color='#00A968', alpha=0.8) # 構成比\nplt.xlabel('x') # x軸ラベル\nplt.ylabel('proportion') # y軸ラベル\nplt.suptitle('Poisson Distribution', fontsize=20)# 全体のタイトル\nplt.title('$\\lambda=' + str(lmd) + ', N=' + str(N) + \n          '=(' + ', '.join([str(f) for f in frequency]) + ')$', loc='left') # タイトル\nplt.xticks(ticks=x_vals) # x軸目盛\nplt.grid() # グリッド線\nplt.show() # 描画\n\n#%%\n\n## アニメーションによる可視化:(頻度)\n\n# フレーム数を指定\nN_frame = 100\n\n# 図を初期化\nfig = plt.figure(figsize=(12, 9)) # 図の設定\nfig.suptitle('Poisson Distribution', fontsize=20)# 全体のタイトル\n\n# y軸(頻度)の最大値を設定\nfreq_max = np.max([np.sum(x_n[:N_frame] == m) for m in x_vals]) + 1.0\n\n# 作図処理を関数として定義\ndef update(n):\n    # 前フレームのグラフを初期化\n    plt.cla()\n    \n    # n個の乱数を集計\n    frequency = np.array([np.sum(x_n[:(n+1)] == m) for m in x_vals])\n    \n    # サンプルのヒストグラムを作成\n    plt.bar(x=x_vals, height=frequency, color='#00A968', zorder=1) # ヒストグラム\n    plt.scatter(x=x_n[n], y=0.0, s=100, c='orange', zorder=2) # サンプル\n    plt.xlabel('x') # x軸ラベル\n    plt.ylabel('frequency') # y軸ラベル\n    plt.title('$\\lambda=' + str(lmd) + ', N=' + str(n + 1) + \n              '=(' + ', '.join([str(f) for f in frequency]) + ')$', loc='left') # タイトル\n    plt.xticks(ticks=x_vals) # x軸目盛\n    plt.grid() # グリッド線\n    plt.ylim(ymin=-0.5, ymax=freq_max) # y軸の表示範囲\n\n# gif画像を作成\nanime_freq = FuncAnimation(fig, update, frames=N_frame, interval=100)\n\n# gif画像を保存\nanime_freq.save('ProbabilityDistribution/Poisson_freq.gif')\n\n#%%\n\n## アニメーションによる可視化:(構成比)\n\n# フレーム数を指定\nN_frame = 100\n\n# 図を初期化\nfig = plt.figure(figsize=(12, 9)) # 図の設定\nfig.suptitle('Poisson Distribution', fontsize=20)# 全体のタイトル\n\n# y軸(割合)の最大値を設定\nprop_max = np.max([np.sum(x_n[:N_frame] == m) for m in x_vals]) / N_frame + 0.1\n\n# 作図処理を関数として定義\ndef update(n):\n    # 前フレームのグラフを初期化\n    plt.cla()\n    \n    # n個の乱数を集計\n    frequency = np.array([np.sum(x_n[:(n+1)] == m) for m in x_vals])\n    \n    # サンプルのヒストグラムを作成\n    plt.bar(x=x_vals, height=probability, color='white', edgecolor='green', linestyle='--', zorder=1) # 元の分布\n    plt.bar(x=x_vals, height=frequency / (n + 1), color='#00A968', alpha=0.8, zorder=2) # 構成比\n    plt.scatter(x=x_n[n], y=0.0, s=100, c='orange', zorder=3) # サンプル\n    plt.xlabel('x') # x軸ラベル\n    plt.ylabel('proportion') # y軸ラベル\n    plt.title('$\\lambda=' + str(lmd) + ', N=' + str(n + 1) + \n              '=(' + ', '.join([str(f) for f in frequency]) + ')$', loc='left') # タイトル\n    plt.xticks(ticks=x_vals) # x軸目盛\n    plt.grid() # グリッド線\n    plt.ylim(ymin=-0.01, ymax=prop_max) # y軸の表示範囲\n\n# gif画像を作成\nanime_prop = FuncAnimation(fig, update, frames=N_frame, interval=100)\n\n# gif画像を保存\nanime_prop.save('ProbabilityDistribution/Poisson_prop.gif')\n\n#%%\n\n", "meta": {"hexsha": "acfd04f5ca72966fe3d7f94292c4f47d996e6ecc", "size": 6855, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/Python/poisson.py", "max_stars_repo_name": "anemptyarchive/Probability-Distribution", "max_stars_repo_head_hexsha": "c44d1079051c0e079c4f009e6fb2d7e1d7b61011", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Python/poisson.py", "max_issues_repo_name": "anemptyarchive/Probability-Distribution", "max_issues_repo_head_hexsha": "c44d1079051c0e079c4f009e6fb2d7e1d7b61011", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Python/poisson.py", "max_forks_repo_name": "anemptyarchive/Probability-Distribution", "max_forks_repo_head_hexsha": "c44d1079051c0e079c4f009e6fb2d7e1d7b61011", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2372881356, "max_line_length": 148, "alphanum_fraction": 0.6463894967, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970315, "lm_q2_score": 0.8902942188450159, "lm_q1q2_score": 0.8522588900976794}}
{"text": "import numpy as np\r\nn_array = np.array([[1, 2, 3],\r\n                    [4, 5, 6],\r\n                    [7, 8, 9]])\r\nprint(\"Numpy Matrix is:\")\r\ntrace = np.trace(n_array)\r\nprint(\"\\nTrace of given 3X3 matrix:\")\r\nprint(trace)\r\n\r\n#15 (trace-sum of diagonal elements)", "meta": {"hexsha": "cde5344d8e8eaa53868b10b86ee94df1400a7755", "size": 262, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter 15/ch15_47.py", "max_stars_repo_name": "bpbpublications/TEST-YOUR-SKILLS-IN-PYTHON-LANGUAGE", "max_stars_repo_head_hexsha": "f6a4194684515495d00aa38347a725dd08f39a0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter 15/ch15_47.py", "max_issues_repo_name": "bpbpublications/TEST-YOUR-SKILLS-IN-PYTHON-LANGUAGE", "max_issues_repo_head_hexsha": "f6a4194684515495d00aa38347a725dd08f39a0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 15/ch15_47.py", "max_forks_repo_name": "bpbpublications/TEST-YOUR-SKILLS-IN-PYTHON-LANGUAGE", "max_forks_repo_head_hexsha": "f6a4194684515495d00aa38347a725dd08f39a0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2, "max_line_length": 38, "alphanum_fraction": 0.534351145, "include": true, "reason": "import numpy", "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576759, "lm_q2_score": 0.9149009636941993, "lm_q1q2_score": 0.8521959383073451}}
{"text": "# encoding: utf-8\nimport numpy as np\n\n# x = np.array([1.0,2.0,3.0])\n# print(x)\n# type(x)\n\nx = np.array([1.0, 2.0, 3.0])\ny = np.array([2.0, 4.0, 6.0])\nprint(x + y)\nprint(x - y)\nprint(x * y)\nprint(x / y)\nprint(x / 2)\n# x 和 y 的元素个数要相同，不然会报错\n\n# Numpy的N维数组\nA = np.array([[1, 2], [3, 4]])\nprint(A)\nprint(A.shape)  # 矩阵的形状\nprint(A.dtype)  # 矩阵元素的数据类型\n\nB = np.array([[3, 0], [0, 6]])\nprint(A + B)\nprint(A * B)\nprint(A * 10)\n# Numpy数据可以生成N维数组\n# 数学上将一维数组称为向量，二维数组称为矩阵\n# 张量 tensor\n\n# 广播\n# 形状不同的数组之间也可以进行运算\nC = np.array([[1, 2], [3, 4]])\nD = np.array([10, 20])\nC * D\n\n# 访问元素\n# 元素的索引从0开始\nE = np.array([[51, 55], [14, 19], [0, 4]])\nprint('E')\nprint(E)\nprint(E[0])\nprint(E[0][1])\nfor row in E:\n    print('row ：', row)\nE = E.flatten()  # 将E转化为一维数组\nprint(E)\nprint(E[np.array([0, 2, 4])])  # 获取索引为0，2，4的元素\nprint(E > 15)  # [ True  True False  True False False]\nprint(E[E > 15])  # [51 55 19]\n", "meta": {"hexsha": "91dc955f9a08acbff756a30757647a9b5ab6a584", "size": 874, "ext": "py", "lang": "Python", "max_stars_repo_path": "turingLearnBook/numpyLearn.py", "max_stars_repo_name": "xiaoahang/nlpdoad", "max_stars_repo_head_hexsha": "d71f1fce6d7efa3426e0610d365df1584642faf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-26T17:13:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-26T17:13:58.000Z", "max_issues_repo_path": "turingLearnBook/numpyLearn.py", "max_issues_repo_name": "xiaoahang/nlpdoad", "max_issues_repo_head_hexsha": "d71f1fce6d7efa3426e0610d365df1584642faf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "turingLearnBook/numpyLearn.py", "max_forks_repo_name": "xiaoahang/nlpdoad", "max_forks_repo_head_hexsha": "d71f1fce6d7efa3426e0610d365df1584642faf5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.137254902, "max_line_length": 54, "alphanum_fraction": 0.5663615561, "include": true, "reason": "import numpy", "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.9149009491921664, "lm_q1q2_score": 0.8521959300212717}}
{"text": "import os\nimport math\nimport csv\nfrom scipy import stats\nfrom itertools import combinations\nimport time\n\ndef ttest(writer, combo, a, b):\n    sigFlag = 0\n#    print(\"Combo of\", combo[0], \"and\", combo[1])\n    sumA = float(sum(a))\n    sumB = float(sum(b))\n\n    sumAsq = sumA ** 2\n    sumBsq = sumB ** 2\n\n    avgA = sumA/len(a)\n    avgB = sumB/len(b)\n\n    ssqA = sum(map(lambda x: x ** 2, a))\n    ssqB = sum(map(lambda x: x ** 2, b))\n    df = len(a) + len(b) - 2\n\n    t = (avgA - avgB)/math.sqrt((((ssqA - sumAsq/len(a))+(ssqB - sumBsq/len(b)))/df)*(1.0/len(a)+1.0/len(b)))\n#    print(\"T value ->\", t)\n\n    pval = stats.t.sf(abs(t), df)*2\n#    print(\"2 Tailed P value ->\", pval)\n\n    if(pval < 0.05):\n        sigFlag = 1\n    res = [combo[0], combo[1], round(t, 5), df, round(pval, 6), sigFlag]\n    writer.writerow(res)\n#    print(res)\n\ndef main():\n    ctr = 0\n    path = os.getcwd()\n    start = time.time()\n    results = open(path + '\\\\results.csv', 'wt', newline='')\n    writer = csv.writer(results, delimiter = ',')\n    head = ['var_1', 'var_2', 't_value', 'degrees_of_freedom', 'p_value', 'significant']\n    writer.writerow(head)\n    rstart = time.time()\n    csvFile = path + \"\\\\data\\\\NMttest.csv\"\n    with open(csvFile, newline='') as fp:\n        reader = csv.DictReader(fp)\n        data = {}\n        for row in reader:\n            for header, value in row.items():\n                try:\n                    data[header].append(value)\n                except KeyError:\n                    data[header] = [value]\n        for key, value in data.items():\n            data[key] = list(filter(None, data[key]))\n            data[key] = list(map(lambda x: float(x), data[key]))\n        featureCombos = (list(combinations(data.keys(),2)))\n        print(\"Time to read file ->\", round(time.time() - rstart, 3), \"seconds.\", end = '\\n')\n        print(\"Total Combinations ->\", len(featureCombos))\n        for elem in featureCombos:\n            ctr += 1\n            sampleA = data[elem[0]]\n            sampleB = data[elem[1]]\n            ttest(writer, elem, sampleA, sampleB)\n            print('Write success. Combination number ->', ctr, end = '\\n')\n#        print(data)\n#    csvFile.close()\n    results.close()\n    fin = time.time() - start\n    print(\"Total Time Elapsed ->\", round(fin, 3), \"seconds.\" ,end = '\\n')\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "3634147cd28832de5fed5952b219c80c037621e9", "size": 2339, "ext": "py", "lang": "Python", "max_stars_repo_path": "significance-tests/t-test/tTest2s.py", "max_stars_repo_name": "NeilBardhan/statistical-tests", "max_stars_repo_head_hexsha": "467aef8c41d3431ee9008831d7dc9dcc767aaed1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "significance-tests/t-test/tTest2s.py", "max_issues_repo_name": "NeilBardhan/statistical-tests", "max_issues_repo_head_hexsha": "467aef8c41d3431ee9008831d7dc9dcc767aaed1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "significance-tests/t-test/tTest2s.py", "max_forks_repo_name": "NeilBardhan/statistical-tests", "max_forks_repo_head_hexsha": "467aef8c41d3431ee9008831d7dc9dcc767aaed1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6081081081, "max_line_length": 109, "alphanum_fraction": 0.5425395468, "include": true, "reason": "from scipy", "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.8933094017937621, "lm_q1q2_score": 0.8521868839792642}}
{"text": "\"\"\"\n2차원 Convolution(합성곱) 연산\n\"\"\"\nimport numpy as np\n\n\ndef convolution_2d(x, w):\n    \"\"\"x, w: 2d ndarray. x의 shape이 w.shape와 같다.\n        x와 w의 교차 상관 연산 결과를 return\n    \"\"\"\n    xh, xw = x.shape[0], x.shape[1]\n\n    # 2d 배열 w의 가로(width) ww,  세로(height) wh\n    wh, ww = w.shape[0], w.shape[1]\n    row_num = xh - wh + 1\n    col_num = xw - ww + 1\n    result = []\n    for i in range(row_num):\n        for j in range(col_num):\n            x_sub = x[i:wh + i, j:ww + j]\n            fma = np.sum(x_sub * w)\n            result.append(fma)\n    conv_ = np.array(result).reshape((row_num, col_num))\n    return conv_\n\n\nif __name__ == '__main__':\n    np.random.seed(113)\n    x = np.arange(1, 10).reshape((3, 3))\n    print(x)\n    w = np.array([[2, 0],\n                  [0, 0]])\n    print(w)\n\n    # 2d 배열 x의 가로(width) xw 2,  세로(height) xh 2\n    xh, xw = x.shape[0], x.shape[1]\n\n    # 2d 배열 w의 가로(width) ww 2,  세로(height) wh 2\n    wh, ww = w.shape[0], w.shape[1]\n\n    x_sub1 = x[0:wh, 0:ww]\n    print('x_sub1:', x_sub1)\n    fma1 = np.sum(x_sub1 * w)\n    print('fma1:', fma1)\n    x_sub2 = x[0:wh, 1:1 + ww]\n    print('x_sub2:', x_sub2)\n    fma2 = np.sum(x_sub2 * w)\n    print('fam2:', fma2)\n\n    x_sub3 = x[1:1 + wh, 0:ww]\n    print('x_sub3:', x_sub3)\n    fma3 = np.sum(x_sub3 * w)\n    print('fam3:', fma3)\n\n    x_sub4 = x[1:1 + wh, 1:1 + ww]\n    print('x_sub4:', x_sub4)\n    fma4 = np.sum(x_sub4 * w)\n    print('fam4:', fma4)\n\n    conv = np.array([fma1, fma2, fma3, fma4]).reshape((2, 2))\n    print('conv:', conv)\n\n    x_result = convolution_2d(x, w)\n    print(x_result)\n\n    x = np.random.randint(10, size=(5, 5))\n    w = np.random.randint(5, size=(3, 3))\n    x_result = convolution_2d(x, w)\n    print('x:', x)\n    print('w:', w)\n    print('result:', x_result)\n", "meta": {"hexsha": "db8fb155b3084e8303bb88872afb932461d00ad7", "size": 1741, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch07/ex02_convolution2d.py", "max_stars_repo_name": "lee-hyeonseung/lab_dl", "max_stars_repo_head_hexsha": "b8906247b6e0e2586f538081e2efaf47dac34972", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-08T09:14:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-08T09:14:46.000Z", "max_issues_repo_path": "ch07/ex02_convolution2d.py", "max_issues_repo_name": "lee-hyeonseung/lab_dl", "max_issues_repo_head_hexsha": "b8906247b6e0e2586f538081e2efaf47dac34972", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch07/ex02_convolution2d.py", "max_forks_repo_name": "lee-hyeonseung/lab_dl", "max_forks_repo_head_hexsha": "b8906247b6e0e2586f538081e2efaf47dac34972", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1805555556, "max_line_length": 61, "alphanum_fraction": 0.5272831706, "include": true, "reason": "import numpy", "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007596, "lm_q2_score": 0.8933093996634686, "lm_q1q2_score": 0.8521868819470364}}
{"text": "import numpy as np \nimport warnings\n\n#\treturns the Mean Percentage Error between two Numpy Arrays. The two lists must be of the same size and greater than 0.\ndef mpe(prediction, actual):\n\t\n\ttry:\n\t\treturn np.mean((prediction - actual) / actual)\n\texcept:\n\t\treturn 'NA'\n\n#\treturns the Coefficient of Variation between two Numpy Arrays. The two lists must be of the same size and greater than 0.\ndef cv(prediction, actual): \n\treturn rmse(prediction, actual)/np.mean(actual)\n\n#   returns the Root-Mean-Square Error between two Numpy Arrays. The two lists must be of the same size and greater than 0.\ndef rmse(prediction, actual):\n\treturn np.sqrt(((prediction - actual) ** 2).mean()) \n\n#   returns the Mean Absolute Percentage Error between two Numpy Arrays. The two lists must be of the same size and no values of 0 in Actual list.\ndef mape(prediction, actual):\n\ttry:\n\t\treturn np.mean(np.abs((actual - prediction) / actual)) \n\texcept:\n\t\treturn 'NA'\n       \n    \ndef MAPE_pos(prediction,actual):\n    eva = np.abs(actual) > (0.05 * np.abs(np.mean(actual)))\n    return np.mean(np.abs((actual[eva] - prediction[eva]) / actual[eva]))\n\ndef cv_pos(prediction,actual):\n    eva = np.abs(actual) > (0.05 * np.mean(np.abs(actual)))\n    return np.sqrt(np.mean((prediction[eva]-actual[eva])**2))/np.mean(actual[eva])\n\ndef rmse_pos(prediction,actual):\n    eva = np.abs(actual) > (0.05 * np.mean(np.abs(actual)))\n    if sum(eva) == 0: # If the actual is always zero, then evaluate on the prediction\n        eva = np.abs(prediction) > (0.05 * np.mean(np.abs(prediction)))\n    return np.sqrt(np.mean((prediction[eva]-actual[eva])**2))\n \ndef mpe_pos(prediction,actual):\n    eva = np.abs(actual) > (0.05 * np.abs(np.mean(actual)))\n    return mpe(prediction[eva],actual[eva])\n    \ndef getErrors(prediction, actual):\n\n\tmpe_err = mpe(prediction, actual)\n\tmape_err = mape(prediction,actual)\n\tcv_err = cv(prediction,actual)\n\t\n\t\n\tprint(\"MPE is\",mpe_err)\n\tprint(\"MAPE is\",mape_err)\n\tprint(\"CV is\",cv_err)\n\t# print(\"RMSE is\",rmse_err)\n\t\n\tmpe_err = str(mpe_err)[0:10]\n\tmape_err = str(mape_err)[0:10]\n\tcv_err = str(cv_err)[0:10]\n\n\t# print(mpe_err, type(mpe_err))\n\n\treturn [mpe_err,mape_err,cv_err]\n", "meta": {"hexsha": "6795c28763a49909b07006ef789d74ff99efea94", "size": 2164, "ext": "py", "lang": "Python", "max_stars_repo_path": "solar_disaggregation/sce-demo/Custom_Functions/error_functions.py", "max_stars_repo_name": "slaclab/VADER-Analytics", "max_stars_repo_head_hexsha": "9d2dd5b11b4f632eb511278c52aa8236f9e252f5", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-14T12:17:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T14:34:00.000Z", "max_issues_repo_path": "solar_disaggregation/sce-demo/Custom_Functions/error_functions.py", "max_issues_repo_name": "slaclab/VADER-Analytics", "max_issues_repo_head_hexsha": "9d2dd5b11b4f632eb511278c52aa8236f9e252f5", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solar_disaggregation/sce-demo/Custom_Functions/error_functions.py", "max_forks_repo_name": "slaclab/VADER-Analytics", "max_forks_repo_head_hexsha": "9d2dd5b11b4f632eb511278c52aa8236f9e252f5", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-06-24T10:46:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-29T19:24:25.000Z", "avg_line_length": 33.2923076923, "max_line_length": 146, "alphanum_fraction": 0.6940850277, "include": true, "reason": "import numpy", "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969324199175492, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.8521782409778413}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nmean = 1\nstdev = 0.5\n\nx = np.random.normal(loc=mean, scale=stdev,size=(10000))\n\nplt.figure()\nplt.title(\"Normal Distribution (mean= \"+ str(mean)+ \", stdev= \"+ str(stdev)+ \")\")\nplt.hist(x)\n\n####################################################################################\nn = 10\np = 0.5\n\ny = np.random.binomial(n=n, p=p, size=1000)\n\nplt.figure()\nplt.title(\"Binomial Distribution (n= \"+ str(n) + \", p= \"+ str(p)+ \")\")\nplt.hist(y)", "meta": {"hexsha": "969401b6abe572591799e949ab999f1a5a2953aa", "size": 481, "ext": "py", "lang": "Python", "max_stars_repo_path": "probability_distribution/probability_dist.py", "max_stars_repo_name": "ChuinHongYap/permutation-python", "max_stars_repo_head_hexsha": "51efa0d23a086a1520d77f6ed095be10cd7e182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-19T14:50:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T14:50:07.000Z", "max_issues_repo_path": "probability_distribution/probability_dist.py", "max_issues_repo_name": "ChuinHongYap/permutation-python", "max_issues_repo_head_hexsha": "51efa0d23a086a1520d77f6ed095be10cd7e182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "probability_distribution/probability_dist.py", "max_forks_repo_name": "ChuinHongYap/permutation-python", "max_forks_repo_head_hexsha": "51efa0d23a086a1520d77f6ed095be10cd7e182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-08T17:57:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T17:57:35.000Z", "avg_line_length": 22.9047619048, "max_line_length": 84, "alphanum_fraction": 0.5239085239, "include": true, "reason": "import numpy", "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242000616579, "lm_q2_score": 0.8791467675095294, "lm_q1q2_score": 0.8521782371529668}}
{"text": "import numpy as np\nimport random\nimport math\nfrom scipy.spatial.transform import Rotation as scipyR\n\n# Math\ndef euclidean_dist(p1, p2):\n    return math.sqrt(sum([(a - b)** 2 for a, b in zip(p1, p2)]))\n\ndef vec(p1, p2):\n    \"\"\" vector from p1 to p2 \"\"\"\n    if type(p1) != np.ndarray:\n        p1 = np.array(p1)\n    if type(p2) != np.ndarray:\n        p2 = np.array(p2)\n    return p2 - p1\n\ndef proj(vec1, vec2, scalar=False):\n    # Project vec1 onto vec2. Returns a vector in the direction of vec2.\n    scale = np.dot(vec1, vec2) / np.linalg.norm(vec2)\n    if scalar:\n        return scale\n    else:\n        return vec2 * scale\n\ndef R_x(th):\n    return np.array([\n        1, 0, 0, 0,\n        0, np.cos(th), -np.sin(th), 0,\n        0, np.sin(th), np.cos(th), 0,\n        0, 0, 0, 1\n    ]).reshape(4,4)\n\ndef R_y(th):\n    return np.array([\n        np.cos(th), 0, np.sin(th), 0,\n        0, 1, 0, 0,\n        -np.sin(th), 0, np.cos(th), 0,\n        0, 0, 0, 1\n    ]).reshape(4,4)\n\ndef R_z(th):\n    return np.array([\n        np.cos(th), -np.sin(th), 0, 0,\n        np.sin(th), np.cos(th), 0, 0,\n        0, 0, 1, 0,\n        0, 0, 0, 1\n    ]).reshape(4,4)\n\ndef T(dx, dy, dz):\n    return np.array([\n        1, 0, 0, dx,\n        0, 1, 0, dy,\n        0, 0, 1, dz,\n        0, 0, 0, 1\n    ]).reshape(4,4)\n\ndef to_radians(th):\n    return th*np.pi / 180\n\ndef to_degrees(th):\n    return th*180 / np.pi\n\ndef R_between(v1, v2):\n    if len(v1) != 3 or len(v2) != 3:\n        raise ValueError(\"Only applicable to 3D vectors!\")\n    v = np.cross(v1, v2)\n    c = np.dot(v1, v2)\n    s = np.linalg.norm(v)\n    I = np.identity(3)\n\n    vX = np.array([\n        0, -v[2], v[1],\n        v[2], 0, -v[0],\n        -v[1], v[0], 0\n    ]).reshape(3,3)\n    R = I + vX + np.matmul(vX,vX) * ((1-c)/(s**2))\n    return R\n\ndef R_euler(thx, thy, thz, affine=False):\n    \"\"\"\n    Obtain the rotation matrix of Rz(thx) * Ry(thy) * Rx(thz); euler angles\n    \"\"\"\n    R = scipyR.from_euler(\"xyz\", [thx, thy, thz], degrees=True)\n    if affine:\n        aR = np.zeros((4,4), dtype=float)\n        aR[:3,:3] = R.as_dcm()\n        aR[3,3] = 1\n        R = aR\n    return R\n\ndef R_quat(x, y, z, w, affine=False):\n    R = scipyR.from_quat([x,y,z,w])\n    if affine:\n        aR = np.zeros((4,4), dtype=float)\n        aR[:3,:3] = R.as_dcm()\n        aR[3,3] = 1\n        R = aR\n    return R    \n    \ndef R_to_euler(R):\n    \"\"\"\n    Obtain the thx,thy,thz angles that result in the rotation matrix Rz(thx) * Ry(thy) * Rx(thz)\n    Reference: http://planning.cs.uiuc.edu/node103.html\n    \"\"\"\n    return R.as_euler('xyz', degrees=True)\n    # # To prevent numerical errors, avoid super small values.\n    # epsilon = 1e-9\n    # matrix[abs(matrix - 0.0) < epsilon] = 0.0\n    # thz = to_degrees(math.atan2(matrix[1,0], matrix[0,0]))    \n    # thy = to_degrees(math.atan2(-matrix[2,0], math.sqrt(matrix[2,1]**2 + matrix[2,2]**2)))\n    # thx = to_degrees(math.atan2(matrix[2,1], matrix[2,2]))            \n    # return thx, thy, thz\n\ndef R_to_quat(R):\n    return R.as_quat()\n\ndef euler_to_quat(thx, thy, thz):\n    return scipyR.from_euler(\"xyz\", [thx, thy, thz], degrees=True).as_quat()\n\ndef quat_to_euler(x, y, z, w):\n    return scipyR.from_quat([x,y,z,w]).as_euler(\"xyz\", degrees=True)\n\ndef approx_equal(v1, v2, epsilon=1e-6):\n    if len(v1) != len(v2):\n        return False\n    for i in range(len(v1)):\n        if abs(v1[i] - v2[i]) > epsilon:\n            return False\n    return True\n", "meta": {"hexsha": "3dbd9abdc60d8cdb2af0f35b8c13f11bfa90bbf5", "size": 3401, "ext": "py", "lang": "Python", "max_stars_repo_path": "movo_object_search/scripts/observation/util.py", "max_stars_repo_name": "zkytony/mos3d", "max_stars_repo_head_hexsha": "b2a68baec5b0627ec83be092c6557485561e804f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-10-31T08:29:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T07:16:07.000Z", "max_issues_repo_path": "movo_object_search/scripts/observation/util.py", "max_issues_repo_name": "zkytony/mos3d", "max_issues_repo_head_hexsha": "b2a68baec5b0627ec83be092c6557485561e804f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "movo_object_search/scripts/observation/util.py", "max_forks_repo_name": "zkytony/mos3d", "max_forks_repo_head_hexsha": "b2a68baec5b0627ec83be092c6557485561e804f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9618320611, "max_line_length": 96, "alphanum_fraction": 0.5351367245, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290955604489, "lm_q2_score": 0.877476800298183, "lm_q1q2_score": 0.8521432514488511}}
{"text": "import numpy as np\n\n# function that takes as input a list of numbers, and returns\n# the list of values given by the softmax function.\ndef softmax(L):\n    eL = np.exp(L)\n    return np.divide(eL, eL.sum())\n\ndef cross_entropy(Y, P):\n    Y = np.float_(Y)\n    P = np.float_(P)\n    return -np.sum(Y * np.log(P) + (1 - Y) * np.log(1 - P))    ", "meta": {"hexsha": "50095590d41a973d7463ca1c2bfdb6eb344e4f82", "size": 335, "ext": "py", "lang": "Python", "max_stars_repo_path": "functions/funp.py", "max_stars_repo_name": "ravivats/ml-dl-cookbook", "max_stars_repo_head_hexsha": "910587ee9e9a5e8677fed92dc23c5c4450ff72cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/funp.py", "max_issues_repo_name": "ravivats/ml-dl-cookbook", "max_issues_repo_head_hexsha": "910587ee9e9a5e8677fed92dc23c5c4450ff72cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/funp.py", "max_forks_repo_name": "ravivats/ml-dl-cookbook", "max_forks_repo_head_hexsha": "910587ee9e9a5e8677fed92dc23c5c4450ff72cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9166666667, "max_line_length": 63, "alphanum_fraction": 0.6208955224, "include": true, "reason": "import numpy", "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971129093889291, "lm_q2_score": 0.8774767858797979, "lm_q1q2_score": 0.8521432359803356}}
{"text": "'''\nEquivalence of AR(1) and MA(infinity)\n\nTo better understand the relationship between MA models and AR models, you will demonstrate that an AR(1) model is equivalent to an MA(∞\n∞\n) model with the appropriate parameters.\n\nYou will simulate an MA model with parameters 0.8,0.82,0.83,…\n0.8\n,\n0.8\n2\n,\n0.8\n3\n,\n…\n for a large number (30) lags and show that it has the same Autocorrelation Function as an AR(1) model with ϕ=0.8\nϕ\n=\n0.8\n.\n\nINSTRUCTIONS\n100XP\nImport the modules for simulating data and plotting the ACF from statsmodels\nUse a list comprehension to build a list with exponentially decaying MA parameters: 1,0.8,0.82,0.83,…\n1\n,\n0.8\n,\n0.8\n2\n,\n0.8\n3\n,\n…\nSimulate 5000 observations of the MA(30) model\nPlot the ACF of the simulated series\n'''\n\n\n\n# import the modules for simulating data and plotting the ACF\nfrom statsmodels.tsa.arima_process import ArmaProcess\nfrom statsmodels.graphics.tsaplots import plot_acf\n\n# Build a list MA parameters\nma = [0.8**i for i in range(30)]\n\n# Simulate the MA(30) model\nar = np.array([1])\nAR_object = ArmaProcess(ar, ma)\nsimulated_data = AR_object.generate_sample(nsample=5000)\n\n# Plot the ACF\nplot_acf(simulated_data, lags=30)\nplt.show()", "meta": {"hexsha": "cd4d5dd7883050a254679a4b1f93de18a8465561", "size": 1179, "ext": "py", "lang": "Python", "max_stars_repo_path": "datacamp-master/22-introduction-to-time-series-analysis-in-python/04-moving-average-ma-and-arma-models/08-equivalance-of-ar(1)-and-ma(infinity).py", "max_stars_repo_name": "vitthal10/datacamp", "max_stars_repo_head_hexsha": "522d2b192656f7f6563bf6fc33471b048f1cf029", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-11T01:32:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T01:32:36.000Z", "max_issues_repo_path": "22-introduction-to-time-series-analysis-in-python/04-moving-average-ma-and-arma-models/08-equivalance-of-ar(1)-and-ma(infinity).py", "max_issues_repo_name": "AndreasFerox/DataCamp", "max_issues_repo_head_hexsha": "41525d7252f574111f4929158da1498ee1e73a84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "22-introduction-to-time-series-analysis-in-python/04-moving-average-ma-and-arma-models/08-equivalance-of-ar(1)-and-ma(infinity).py", "max_forks_repo_name": "AndreasFerox/DataCamp", "max_forks_repo_head_hexsha": "41525d7252f574111f4929158da1498ee1e73a84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-08T05:09:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-08T05:09:52.000Z", "avg_line_length": 19.9830508475, "max_line_length": 136, "alphanum_fraction": 0.7489397795, "include": true, "reason": "from statsmodels", "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102589923635, "lm_q2_score": 0.8807970873650401, "lm_q1q2_score": 0.852092138407533}}
{"text": "from matplotlib import pyplot as plt\nimport numpy as np\nfrom skimage import io, color\nfrom math import sqrt, exp\n\ndef distance(point1,point2):\n    return sqrt((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2)\n\ndef butterworthLP(lin, col, D0, n):\n    base = np.zeros((lin,col))\n    center = (lin/2,col/2)\n    for x in range(lin):\n        for y in range(col):\n            base[y,x] = 1/(1+(distance((y,x),center)/D0)**(2*n))\n    return base\n\ndef butterworthHP(lin, col, D0, n):\n    base = butterworthLP(lin, col, D0, n)\n    base = 1 - base\n    return base\n\ndef gaussianLP(lin, col, D0):\n    base = np.zeros((lin,col))\n    center = (lin/2,col/2)\n    for x in range(col):\n        for y in range(lin):\n            base[y,x] = exp(((-distance((y,x),center)**2)/(2*(D0**2))))\n    return base\n\ndef gaussianHP(lin, col, D0):\n    base = gaussianLP(lin, col, D0)\n    base = 1 - base\n    return base    \n\nim = io.imread('Lenna.png')\n\nim2 = color.rgb2gray(im)\nim2 = (im2 * 255).astype('uint8')\n\nlin,col = im2.shape\n\n#f1 = butterworthLP(51,51,7,2)\n#f2 = butterworthHP(51,51,7,2)\n#f3 = gaussianLP(51,51,7)\n#f4 = gaussianHP(51,51,7)\n\nf1 = butterworthLP(lin, col, 20, 2)\nf2 = butterworthHP(lin, col, 120, 2)\nf3 = gaussianLP(lin, col, 20)\nf4 = gaussianHP(lin, col, 120)\n\nplt.figure()\nplt.subplot(221)\nplt.imshow(f1)\nplt.subplot(222)\nplt.imshow(f2)\nplt.subplot(223)\nplt.imshow(f3)\nplt.subplot(224)\nplt.imshow(f4).\n\nimft2 = np.fft.fft2(im2)\nfshift2 = np.fft.fftshift(imft2)\n\nblur1 = fshift2 * f1\nbordas1 = fshift2 * f2\nblur2 = fshift2 * f3\nbordas2 = fshift2 * f4\n\nblur1 = np.fft.ifft2(np.fft.ifftshift(blur1))\nbordas1 = np.fft.ifft2(np.fft.ifftshift(bordas1))\nblur2 = np.fft.ifft2(np.fft.ifftshift(blur2))\nbordas2 = np.fft.ifft2(np.fft.ifftshift(bordas2))\n\nplt.figure()\nplt.subplot(221)\nplt.imshow(np.abs(blur1), cmap='gray')\nplt.subplot(222)\nplt.imshow(np.abs(bordas1), cmap='gray')\nplt.subplot(223)\nplt.imshow(np.abs(blur2), cmap='gray')\nplt.subplot(224)\nplt.imshow(np.abs(bordas2), cmap='gray')", "meta": {"hexsha": "679e870e400dcb9571d24db197d3fff0fe5cf8f2", "size": 1980, "ext": "py", "lang": "Python", "max_stars_repo_path": "processamento-de-imagens/L09-frequency-filters/gaussian butterworth.py", "max_stars_repo_name": "gprando/UTFPR", "max_stars_repo_head_hexsha": "0e3f23b8a612fc3f04f69c7740aa69aa5b2c5eee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "processamento-de-imagens/L09-frequency-filters/gaussian butterworth.py", "max_issues_repo_name": "gprando/UTFPR", "max_issues_repo_head_hexsha": "0e3f23b8a612fc3f04f69c7740aa69aa5b2c5eee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "processamento-de-imagens/L09-frequency-filters/gaussian butterworth.py", "max_forks_repo_name": "gprando/UTFPR", "max_forks_repo_head_hexsha": "0e3f23b8a612fc3f04f69c7740aa69aa5b2c5eee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8554216867, "max_line_length": 71, "alphanum_fraction": 0.6505050505, "include": true, "reason": "import numpy", "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102561735719, "lm_q2_score": 0.880797085800514, "lm_q1q2_score": 0.8520921344112108}}
{"text": "import numpy as np\n\n\"\"\" Here I implemented the scoring functions.\n    MAE, MSE, RMSE, RMSLE are included.\n\n    Those are used for calculating differences between\n    predicted values and actual values.\n\n    Metrics are slightly differentiated. Sometimes squared, rooted,\n    even log is used.\n\n    Using log and roots can be perceived as tools for penalizing big\n    errors. However, using appropriate metrics depends on the situations,\n    and types of data\n\"\"\"\n\n\n# Mean Absolute Error\ndef mae(predict, actual):\n    \"\"\"\n    Examples(rounded for precision):\n    >>> actual = [1,2,3];predict = [1,4,3]\n    >>> np.around(mae(predict,actual),decimals = 2)\n    0.67\n\n    >>> actual = [1,1,1];predict = [1,1,1]\n    >>> mae(predict,actual)\n    0.0\n    \"\"\"\n    predict = np.array(predict)\n    actual = np.array(actual)\n\n    difference = abs(predict - actual)\n    return difference.mean()\n\n\n# Mean Squared Error\ndef mse(predict, actual):\n    \"\"\"\n    Examples(rounded for precision):\n    >>> actual = [1,2,3];predict = [1,4,3]\n    >>> np.around(mse(predict,actual),decimals = 2)\n    1.33\n\n    >>> actual = [1,1,1];predict = [1,1,1]\n    >>> mse(predict,actual)\n    0.0\n    \"\"\"\n    predict = np.array(predict)\n    actual = np.array(actual)\n\n    difference = predict - actual\n    square_diff = np.square(difference)\n\n    return square_diff.mean()\n\n\n# Root Mean Squared Error\ndef rmse(predict, actual):\n    \"\"\"\n    Examples(rounded for precision):\n    >>> actual = [1,2,3];predict = [1,4,3]\n    >>> np.around(rmse(predict,actual),decimals = 2)\n    1.15\n\n    >>> actual = [1,1,1];predict = [1,1,1]\n    >>> rmse(predict,actual)\n    0.0\n    \"\"\"\n    predict = np.array(predict)\n    actual = np.array(actual)\n\n    difference = predict - actual\n    square_diff = np.square(difference)\n    mean_square_diff = square_diff.mean()\n    return np.sqrt(mean_square_diff)\n\n\n# Root Mean Square Logarithmic Error\ndef rmsle(predict, actual):\n    \"\"\"\n    Examples(rounded for precision):\n    >>> actual = [10,10,30];predict = [10,2,30]\n    >>> np.around(rmsle(predict,actual),decimals = 2)\n    0.75\n\n    >>> actual = [1,1,1];predict = [1,1,1]\n    >>> rmsle(predict,actual)\n    0.0\n    \"\"\"\n    predict = np.array(predict)\n    actual = np.array(actual)\n\n    log_predict = np.log(predict + 1)\n    log_actual = np.log(actual + 1)\n\n    difference = log_predict - log_actual\n    square_diff = np.square(difference)\n    mean_square_diff = square_diff.mean()\n\n    return np.sqrt(mean_square_diff)\n\n\n# Mean Bias Deviation\ndef mbd(predict, actual):\n    \"\"\"\n    This value is Negative, if the model underpredicts,\n    positive, if it overpredicts.\n\n    Example(rounded for precision):\n\n    Here the model overpredicts\n    >>> actual = [1,2,3];predict = [2,3,4]\n    >>> np.around(mbd(predict,actual),decimals = 2)\n    50.0\n\n    Here the model underpredicts\n    >>> actual = [1,2,3];predict = [0,1,1]\n    >>> np.around(mbd(predict,actual),decimals = 2)\n    -66.67\n    \"\"\"\n    predict = np.array(predict)\n    actual = np.array(actual)\n\n    difference = predict - actual\n    numerator = np.sum(difference) / len(predict)\n    denumerator = np.sum(actual) / len(predict)\n    # print(numerator, denumerator)\n    score = float(numerator) / denumerator * 100\n\n    return score\n", "meta": {"hexsha": "be279945d11a401814ffe19887041bc2868a2b41", "size": 3226, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine_learning/scoring_functions.py", "max_stars_repo_name": "MKiperszmid/Python", "max_stars_repo_head_hexsha": "6b368e6ab2fa1a839b029fd45e127521bbe76005", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-28T18:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-28T18:25:45.000Z", "max_issues_repo_path": "machine_learning/scoring_functions.py", "max_issues_repo_name": "MKiperszmid/Python", "max_issues_repo_head_hexsha": "6b368e6ab2fa1a839b029fd45e127521bbe76005", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-28T18:24:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-28T19:35:47.000Z", "max_forks_repo_path": "machine_learning/scoring_functions.py", "max_forks_repo_name": "MKiperszmid/Python", "max_forks_repo_head_hexsha": "6b368e6ab2fa1a839b029fd45e127521bbe76005", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4393939394, "max_line_length": 73, "alphanum_fraction": 0.6298822071, "include": true, "reason": "import numpy", "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102561735719, "lm_q2_score": 0.8807970764133561, "lm_q1q2_score": 0.852092125329978}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n'''\nLa siguiente función retorna el integrando de la función de Bessel J_m(x). Sus parámetros son m, x, y la variable de integración t.\n'''\ndef bessel_integrand(m, x, t):\n    return 1.0/np.pi * np.cos(m*t - x*np.sin(t))\n\n'''\nLa siguiente función realiza la integral entre a y b de la función f para un número de pasos N utilizando la regla de Simpson. Los parámetros m y x son los correspondientes a J_m(x).\n'''\ndef simpson(f, a, b, N, m, x):\n    if N%2 == 1:\n        N += 1\n    h = (b-a)/N\n    result = f(m,x,a) + f(m,x,b)\n    for i in range(1, N, 2):\n        result += 4*f(m,x,a + i*h)\n    for i in range(2, N-1, 2):\n        result += 2*f(m,x,a + i*h)\n    result *= h/3.0\n    return result\n\n'''\nNote que una integral corresponde a un punto de las gráficas que se quieren obtener. Entonces, la siguiente función realiza el procedimiento varias veces, generando arreglos para el eje X y el eje Y de las gráficas\n'''\ndef plot_bessel(m):\n    X = np.linspace(0,20,41)\n    Y =np.zeros(41)\n    for i in list(range(len(X))):\n        Y[i]=simpson(bessel_integrand, 0.0, np.pi, 1000, m, X[i])\n    \n    plt.plot(X,Y)\n    plt.xlabel(\"$x$\", fontsize = \"15\")\n    plt.ylabel(\"$J_m(x)$\", fontsize = \"15\")\n    plt.title(\"$m = $\"+str(m), fontsize=\"15\")\n    plt.show()\n    plt.close()\n\n'''\nAhora sólo queda llamar esta función para cada m.\n'''\nplot_bessel(0)\nplot_bessel(1)\nplot_bessel(2)\n", "meta": {"hexsha": "a4ecee0c477ea4d1cf2be2268cd6c2e4448ed48f", "size": 1424, "ext": "py", "lang": "Python", "max_stars_repo_path": "2016-2/ej1/ej1SOL.py", "max_stars_repo_name": "forero/ComputationalLab", "max_stars_repo_head_hexsha": "d7bca519dbb439fd76f3ee5a59e21af0ae560989", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2016-2/ej1/ej1SOL.py", "max_issues_repo_name": "forero/ComputationalLab", "max_issues_repo_head_hexsha": "d7bca519dbb439fd76f3ee5a59e21af0ae560989", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2016-2/ej1/ej1SOL.py", "max_forks_repo_name": "forero/ComputationalLab", "max_forks_repo_head_hexsha": "d7bca519dbb439fd76f3ee5a59e21af0ae560989", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2978723404, "max_line_length": 214, "alphanum_fraction": 0.6271067416, "include": true, "reason": "import numpy", "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075722839015, "lm_q2_score": 0.8856314692902446, "lm_q1q2_score": 0.8520727428570619}}
{"text": "import numpy\nfrom matplotlib import pyplot\n\ndef trapezoidal(f, a, b, N):\n    x, dx = numpy.linspace(a, b, N+1, retstep=True)\n    fx = f(x)\n    return dx * ( (fx[0] + fx[-1])/2 + numpy.sum(fx[1:-1]) )\n    \ndef simpsons(f, a, b, N):\n    x, dx = numpy.linspace(a, b, N+1, retstep=True)\n    fx = f(x)\n    return dx/3 * ( (fx[0] + fx[-1]) + \\\n        2*numpy.sum(fx[2:-1:2]) + 4*numpy.sum(fx[1:-1:2]) )\n    \ndef richardson(f, a, b, N):\n    I_h = simpsons(f, a, b, N)\n    I_2h = simpsons(f, a, b, N//2)\n    return (2**4*I_h - I_2h) / (2**4 - 1)    \n    \nif __name__==\"__main__\":\n    print(\"Trapezoidal rule\")\n    print(trapezoidal(numpy.sin, 0, numpy.pi/2, 2))\n    print(trapezoidal(numpy.sin, 0, numpy.pi/2, 4))\n    Npoints = 2**numpy.arange(1,20)\n    dx_all = numpy.pi/2/Npoints\n    errors = numpy.zeros_like(dx_all)\n    for i, N in enumerate(Npoints):\n        I = trapezoidal(numpy.sin, 0, numpy.pi/2, N)\n        errors[i] = abs(I - 1)\n    pyplot.loglog(dx_all, errors, 'kx')\n    pyplot.loglog(dx_all, errors[0]*(dx_all/dx_all[0])**2, 'b-',\n                  label=r\"$\\propto \\Delta x^2$\")\n    pyplot.legend(loc='upper left')\n    pyplot.xlabel(r\"$\\Delta x$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.show()\n    \n    print(\"Simpson's rule\")\n    print(simpsons(numpy.sin, 0, numpy.pi/2, 2))\n    print(simpsons(numpy.sin, 0, numpy.pi/2, 4))\n    Npoints = 2**numpy.arange(1,20)\n    dx_all = numpy.pi/2/Npoints\n    errors = numpy.zeros_like(dx_all)\n    for i, N in enumerate(Npoints):\n        I = simpsons(numpy.sin, 0, numpy.pi/2, N)\n        errors[i] = abs(I - 1)\n    pyplot.loglog(dx_all, errors, 'kx')\n    pyplot.loglog(dx_all, errors[0]*(dx_all/dx_all[0])**4, 'b-',\n                  label=r\"$\\propto \\Delta x^4$\")\n    pyplot.legend(loc='upper left')\n    pyplot.xlabel(r\"$\\Delta x$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.show()\n    \n    print(\"Richardson extrapolation\")\n    print(richardson(numpy.sin, 0, numpy.pi/2, 4))\n    print(richardson(numpy.sin, 0, numpy.pi/2, 8))\n    Npoints = 2**numpy.arange(2, 10)\n    dx_all = numpy.pi/2/Npoints\n    errors = numpy.zeros_like(dx_all)\n    for i, N in enumerate(Npoints):\n        I = richardson(numpy.sin, 0, numpy.pi/2, N)\n        errors[i] = abs(I - 1)\n    pyplot.loglog(dx_all, errors, 'kx')\n    pyplot.loglog(dx_all, errors[0]*(dx_all/dx_all[0])**6, 'b-',\n                  label=r\"$\\propto \\Delta x^6$\")\n    pyplot.legend(loc='upper left')\n    pyplot.xlabel(r\"$\\Delta x$\")\n    pyplot.ylabel(\"Error\")\n    pyplot.show()\n    ", "meta": {"hexsha": "fe8f634629d255e2d86bb2ab2cfbae31cc0738ec", "size": 2466, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/tex/codes/lecture12.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Lectures/tex/codes/lecture12.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Lectures/tex/codes/lecture12.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 34.7323943662, "max_line_length": 64, "alphanum_fraction": 0.5766423358, "include": true, "reason": "import numpy", "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211597623861, "lm_q2_score": 0.8740772384450968, "lm_q1q2_score": 0.852068987302953}}
{"text": "import math\r\nimport numpy as np \r\nfrom common.constant import *\r\n\r\ndef MinkowskiDistance(vector_1 : np.array, vector_2 : np.array, p = 2) -> float:\r\n    \"\"\"\r\n    计算两点的闵可夫斯基距离 \\n\r\n    p = 1 时为曼哈顿距离 \\n\r\n    p = 2 时为欧式距离 \\n\r\n    p = ∞ 时为切比雪夫距离 \\n\r\n    \"\"\"\r\n    \r\n    temp = np.abs(vector_1 - vector_2)\r\n    return np.sum(temp ** p) ** (1 / p)\r\n\r\ndef Mahalanobis_distance(vector_1 : np.ndarray, vector_2 : np.ndarray, S_inv : np.ndarray) -> float:\r\n    \"\"\"\r\n    计算两点的马哈拉诺比斯距离 \\n\r\n    :param S_inv: 协方差矩阵的逆矩阵 \\n\r\n    \"\"\"\r\n    temp_vector = vector_1 - vector_2\r\n    temp_vector = temp_vector.reshape((-1, 1))\r\n    \r\n    dot_product = np.dot(temp_vector.T, np.dot(S_inv, temp_vector))    \r\n    if dot_product < 0:\r\n        raise Exception('The number to calculate the square root is negative.')\r\n    dis = math.sqrt(dot_product)\r\n    return dis\r\n\r\ndef get_EuclideanDistance_matrix(X : np.ndarray, V : np.ndarray) -> np.ndarray:\r\n    c = V.shape[MatrixShapeIndex.column]\r\n    n = X.shape[MatrixShapeIndex.column]\r\n\r\n    distance_matrix = np.zeros((n, c))\r\n    \r\n    for i in range(n):\r\n        for j in range(c):\r\n            distance_matrix[i][j] = MinkowskiDistance(X[:, i], V[:, j])\r\n    \r\n    return distance_matrix\r\n\r\nif __name__ == '__main__':\r\n    a = np.array([1, 2])\r\n    b = np.array([4, 6])\r\n    print(MinkowskiDistance(a, b, 1))", "meta": {"hexsha": "66f9feb38d5f9bad7fe9d959897629d110f64e28", "size": 1332, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/distance.py", "max_stars_repo_name": "ClayLiu/Soft-ClusteringAlgorithms", "max_stars_repo_head_hexsha": "38dc8c2ac610f996c79760de00631840c784029c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/distance.py", "max_issues_repo_name": "ClayLiu/Soft-ClusteringAlgorithms", "max_issues_repo_head_hexsha": "38dc8c2ac610f996c79760de00631840c784029c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/distance.py", "max_forks_repo_name": "ClayLiu/Soft-ClusteringAlgorithms", "max_forks_repo_head_hexsha": "38dc8c2ac610f996c79760de00631840c784029c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-10T15:48:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-10T15:48:46.000Z", "avg_line_length": 29.6, "max_line_length": 101, "alphanum_fraction": 0.5990990991, "include": true, "reason": "import numpy", "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.978712651931994, "lm_q2_score": 0.870597270087091, "lm_q1q2_score": 0.8520645629716912}}
{"text": "\nimport numpy as np\nimport tensornetwork as tn\n\n\ndef schmidt_decomposition_numpy(bipartitepurestate_tensor):\n    \"\"\" Calculate the Schmidt decomposition of the given discrete bipartite quantum system\n\n    This is called by :func:`schmidt_decomposition`. This runs numpy.\n\n    :param bipartitepurestate_tensor: tensor describing the bi-partitite states, with each elements the coefficients for :math:`|ij\\\\rangle`\n    :return: list of tuples containing the Schmidt coefficient, eigenmode for first subsystem, and eigenmode for second subsystem\n    :type bipartitepurestate_tensor: numpy.ndarray\n    :rtype: list\n    \"\"\"\n    state_dims = bipartitepurestate_tensor.shape\n    mindim = np.min(state_dims)\n\n    vecs1, diags, vecs2_h = np.linalg.svd(bipartitepurestate_tensor)\n    vecs2 = vecs2_h.transpose()\n\n    decomposition = [(diags[k], vecs1[:, k], vecs2[:, k])\n                     for k in range(mindim)]\n\n    decomposition = sorted(decomposition, key=lambda dec: dec[0], reverse=True)\n\n    return decomposition\n\n\ndef schmidt_decomposition_tensornetwork(bipartitepurestate_tensor):\n    \"\"\" Calculate the Schmidt decomposition of the given discrete bipartite quantum system\n\n    This is called by :func:`schmidt_decomposition`. This runs tensornetwork.\n\n    :param bipartitepurestate_tensor: tensor describing the bi-partitite states, with each elements the coefficients for :math:`|ij\\\\rangle`\n    :return: list of tuples containing the Schmidt coefficient, eigenmode for first subsystem, and eigenmode for second subsystem\n    :type bipartitepurestate_tensor: numpy.ndarray\n    :rtype: list\n    \"\"\"\n    state_dims = bipartitepurestate_tensor.shape\n    mindim = np.min(state_dims)\n\n    node = tn.Node(bipartitepurestate_tensor)\n    vecs1, diags, vecs2_h, _ = tn.split_node_full_svd(node, [node[0]], [node[1]])\n\n    decomposition = [(diags.tensor[k, k], vecs1.tensor[:, k], vecs2_h.tensor[k, :])\n                     for k in range(mindim)]\n\n    decomposition = sorted(decomposition, key=lambda dec: dec[0], reverse=True)\n\n    return decomposition\n\n\ndef schmidt_decomposition(bipartitepurestate_tensor, approach='tensornetwork'):\n    \"\"\"Calculate the Schmidt decomposition of the given discrete bipartite quantum system\n\n    Given a discrete normalized quantum system, given in terms of 2-D numpy array ``bipartitepurestate_tensor``,\n    each element of ``bipartitepurestate_tensor[i, j]`` is the coefficient of the ket :math:`|ij\\\\rangle`,\n    calculate its Schmidt decomposition, returned as a list of tuples, where each tuple contains\n    the Schmidt coefficient, the vector of eigenmode of first subsystem, and the vector of the eigenmode of\n    second subsystem.\n\n    :param bipartitepurestate_tensor: tensor describing the bi-partitite states, with each elements the coefficients for :math:`|ij\\\\rangle`\n    :param approach: using `numpy` or `tensornetwork` in computation. (default: `tensornetwork`)\n    :return: list of tuples containing the Schmidt coefficient, eigenmode for first subsystem, and eigenmode for second subsystem\n    :type bipartitepurestate_tensor: numpy.ndarray\n    :type approach: str\n    :rtype: list\n    :raise: ValueError\n    \"\"\"\n    if approach == 'numpy':\n        return schmidt_decomposition_numpy(bipartitepurestate_tensor)\n    elif approach == 'tensornetwork':\n        return schmidt_decomposition_tensornetwork(bipartitepurestate_tensor)\n    else:\n        raise ValueError(\"Approach is either 'numpy' or 'tensorflow', not {}.\".format(approach))\n", "meta": {"hexsha": "dc9715db69d03a1deaaeecf1e51b5f8b6eec265c", "size": 3481, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyqentangle/schmidt.py", "max_stars_repo_name": "stephenhky/PyQEntangle", "max_stars_repo_head_hexsha": "f06b63ac89952c1878555af0f2b4f079d11237d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2017-05-25T17:09:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T14:36:15.000Z", "max_issues_repo_path": "pyqentangle/schmidt.py", "max_issues_repo_name": "stephenhky/PyQEntangle", "max_issues_repo_head_hexsha": "f06b63ac89952c1878555af0f2b4f079d11237d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-04-07T04:52:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-05T04:27:55.000Z", "max_forks_repo_path": "pyqentangle/schmidt.py", "max_forks_repo_name": "stephenhky/PyQEntangle", "max_forks_repo_head_hexsha": "f06b63ac89952c1878555af0f2b4f079d11237d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-03-12T03:45:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-25T18:56:04.000Z", "avg_line_length": 45.2077922078, "max_line_length": 140, "alphanum_fraction": 0.7431772479, "include": true, "reason": "import numpy", "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611643025387, "lm_q2_score": 0.8872045922259088, "lm_q1q2_score": 0.8520368351646328}}
{"text": "import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom pearsonLinearCorrelationCoefficient import pearson_linear_correlation_coefficient\n\ndef linear_regression(filename: str):\n    df = pd.read_csv(filename, delimiter=',')\n    number_of_rows = df.shape[0]\n    df_hat = df.sum() / number_of_rows\n    x_hat = df_hat[0]\n    y_hat = df_hat[1]\n    df['xi-x_hat'] = df.iloc[:, 0] - x_hat\n    df['yi(xi-x_hat)'] = df['xi-x_hat'] * df.iloc[:, 1]\n    df['(xi-x_hat)2'] = df['xi-x_hat'] ** 2\n    df_sum = df.sum()\n    a = df_sum['yi(xi-x_hat)'] / df_sum['(xi-x_hat)2']\n    b = y_hat - x_hat * a\n    return a, b\n\ndef draw_linear_regression(a: float, b: float, filename: str):\n    df = pd.read_csv(filename, delimiter=',')\n    column_names = df.columns\n    df.plot(x=column_names[0], y=column_names[1], style='o', color='k')\n    minX = df.iloc[:, 0].min()\n    minX -= 0.1 * minX\n    maxX = df.iloc[:, 0].max()\n    maxX += 0.1 * maxX\n    step = (maxX - minX) / 10\n    regressionX = np.arange(minX, maxX, step)\n    regressionY = a * regressionX + b\n    plt.grid()\n    plt.plot(regressionX, regressionY, 'r', linewidth=2)\n    plt.xlabel(column_names[0])\n    plt.ylabel(column_names[1])\n    plt.legend(['y=f(x)', 'regression line'])\n    fig = plt.gcf()\n    fig.set_size_inches(5, 3.8)\n    fig.tight_layout()\n    plt.savefig('temp_regression_chart.png',  dpi=100)\n    # plt.show()\n\n\nprint(\"Algorithm loaded: Linear regression\")\n\n\"\"\"\nfilename = '../data/pearsonLinearCorrelationCoefficient.csv'\nr = pearson_linear_correlation_coefficient(filename)\nprint(f\"Correlation coefficient: {r}\")\n\nif abs(r) < 0.5:\n    print(\"Correlation coefficient should be less than |0.5|\")\n    exit(0)\n\na, b = linear_regression(filename)\nprint(f\"a: {a}\")\nprint(f\"b: {b}\")\ndraw_linear_regression(a, b, filename)\n\"\"\"", "meta": {"hexsha": "822bd2d751b71f5f206d0be2ebc164ee3f8335a5", "size": 1795, "ext": "py", "lang": "Python", "max_stars_repo_path": "functions/dataRelationships/linear_regression.py", "max_stars_repo_name": "h-kyouma/IDS_statistics", "max_stars_repo_head_hexsha": "b9eb26b757dfb1ee88e4a78f5b6ee304fca39420", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/dataRelationships/linear_regression.py", "max_issues_repo_name": "h-kyouma/IDS_statistics", "max_issues_repo_head_hexsha": "b9eb26b757dfb1ee88e4a78f5b6ee304fca39420", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/dataRelationships/linear_regression.py", "max_forks_repo_name": "h-kyouma/IDS_statistics", "max_forks_repo_head_hexsha": "b9eb26b757dfb1ee88e4a78f5b6ee304fca39420", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4237288136, "max_line_length": 86, "alphanum_fraction": 0.6495821727, "include": true, "reason": "import numpy", "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611586300241, "lm_q2_score": 0.8872045952083049, "lm_q1q2_score": 0.8520368329961292}}
{"text": "\"\"\"\nA number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.\nFor example,\n44 > 32 > 13 > 10 > 1 > 1\n85 > 89 > 145 > 42 > 20 > 4 > 16 > 37 > 58 > 89\nTherefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.\nHow many starting numbers below ten million will arrive at 89?\n\"\"\"\n\nimport numpy as np\n\ndef create_next(x):\n\ttmp_sum = 0\n\twhile x > 0:\n\t\ttmp_sum += (x % 10)**2\n\t\tx /= 10\n\treturn tmp_sum\n\t\n\ndef create_chain(x):\n\tchain = []\n\tnext_num = x\n\twhile 1:\n\t\tif next_num == 89:\n\t\t\treturn True\n\t\telif next_num == 1:\n\t\t\treturn False\n\t\telif next_num in chain:\n\t\t\treturn False\n\t\tchain.append(next_num)\n\t\tnext_num = create_next(next_num)\n\ntotal_found = 0\nfor x in xrange(1,10000000):\n\tif x % 10000 == 0:\n\t\tprint(x)\n\tif create_chain(x):\n\t\ttotal_found += 1\n\nprint(\"Found %d\" % total_found) # 8581146\n", "meta": {"hexsha": "2a69558260e1638efcf206bac00840f8304abbe5", "size": 979, "ext": "py", "lang": "Python", "max_stars_repo_path": "problem092.py", "max_stars_repo_name": "racamirko/proj_euler2014", "max_stars_repo_head_hexsha": "62a4ff109ffc08811d3fa504a5014e8d317daad0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problem092.py", "max_issues_repo_name": "racamirko/proj_euler2014", "max_issues_repo_head_hexsha": "62a4ff109ffc08811d3fa504a5014e8d317daad0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem092.py", "max_forks_repo_name": "racamirko/proj_euler2014", "max_forks_repo_head_hexsha": "62a4ff109ffc08811d3fa504a5014e8d317daad0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8780487805, "max_line_length": 167, "alphanum_fraction": 0.6833503575, "include": true, "reason": "import numpy", "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361156361018, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.8520368252547019}}
{"text": "import numpy as np\nfrom scipy.optimize import minimize\n\n#ref for inequality constraint example syntax https://stackoverflow.com/questions/21765794/python-constrained-non-linear-optimization\n\n'''\nThis is scipy kicking Google ORs a**.  Not only does it handle the linear version, it also \nhandles a nonlinear objective function with ease.  There must be a downside somewhere. Maybe not \nas performant at scale? But so far so good...\n'''\n\ndef objective(x):\n    #linear objective\n    return - ( np.dot(x, v) ) # x[1]*v[1] + ...x[n]*v[n]\n    \n    #non linear objective\n    # return -( np.dot(x, v) + x[1]*v[1]*x[2]*v[2] )\n\ndef constraint1(x):\n    return 20.0 -(np.dot(x, w)) # x[1]*w[1] + ...x[n]*w[n]\n\n\nn = 3\nx0 = np.array([1, 1, 5]) # initial guesses\nw = np.array([1,4,1]) # weights\nv = np.array([3,5,2]) # values\n\n# show initial objective\nprint('Initial SSE Objective: ' + str(objective(x0)))\n\n# optimize\nbnds = ((1.0, 3.0), (1.0, 5.0), (10.0, 20.0))\ncon1 = {'type': 'ineq', 'fun': constraint1} \ncons = ([con1])\nsolution = minimize(objective,x0,method='SLSQP',\\\n                    bounds=bnds,constraints=cons)\nx = solution.x\n\n# show final objective\nprint('Final SSE Objective: ' + str(round(objective(x))*(-1)))\n\n#debug:check weight constraint is working. this number should be close to zero or going over weight\nprint('Overweight: ', str(20-(x[0]*w[0]+x[1]*w[1]+x[2]*w[2]) ))\n\n# print solution\nprint('Solution')\nprint('x1 = ' + str(round(x[0])))\nprint('x2 = ' + str(round(x[1])))\nprint('x3 = ' + str(round(x[2])))\n", "meta": {"hexsha": "09ee80c6f14e313ec3f3b9472a2d21caca6672aa", "size": 1515, "ext": "py", "lang": "Python", "max_stars_repo_path": "unbounded_nonlinear.py", "max_stars_repo_name": "lm-friends/optimize-yourlife", "max_stars_repo_head_hexsha": "707d727c6458682b686dbd2e4ed06f5cfbf84bd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unbounded_nonlinear.py", "max_issues_repo_name": "lm-friends/optimize-yourlife", "max_issues_repo_head_hexsha": "707d727c6458682b686dbd2e4ed06f5cfbf84bd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unbounded_nonlinear.py", "max_forks_repo_name": "lm-friends/optimize-yourlife", "max_forks_repo_head_hexsha": "707d727c6458682b686dbd2e4ed06f5cfbf84bd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-14T10:36:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T10:36:45.000Z", "avg_line_length": 30.3, "max_line_length": 133, "alphanum_fraction": 0.6415841584, "include": true, "reason": "import numpy,from scipy", "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.963779943094681, "lm_q2_score": 0.8840392863287585, "lm_q1q2_score": 0.8520193330713932}}
{"text": "\n# coding: utf-8\n\n# # Function iagaussian\n\n# ## Synopse\n\n# Generate a d-dimensional Gaussian image.\n# \n# - **g = gaussian(s, mu, cov)**\n# \n#   - **g**: Image. \n# \n# \n#   - **s**: Image shape. (rows columns)\n#   - **mu**: Image. Mean vector. n-D point. Point of maximum value.\n#   - **cov**: Covariance matrix (symmetric and square).\n\n# In[3]:\n\nimport numpy as np\n\ndef gaussian(s, mu, cov):\n    d = len(s)  # dimension\n    n = np.prod(s) # n. of samples (pixels)\n    x = np.indices(s).reshape( (d, n))\n    xc = x - mu \n    k = 1. * xc * np.dot(np.linalg.inv(cov), xc)\n    k = np.sum(k,axis=0) #the sum is only applied to the rows\n    g = (1./((2 * np.pi)**(d/2.) * np.sqrt(np.linalg.det(cov)))) * np.exp(-1./2 * k)\n    return g.reshape(s)\n\n\n# ## Description\n\n# A n-dimensional Gaussian image is an image with a Gaussian distribution. It can be used to generate \n# test patterns or Gaussian filters both for spatial and frequency domain. The integral of the gaussian function is 1.0.\n\n# ## Examples\n\n# In[1]:\n\ntesting = (__name__ == \"__main__\")\nif testing:\n    get_ipython().system(' jupyter nbconvert --to python gaussian.ipynb')\n    import numpy as np\n    import sys,os\n    ea979path = os.path.abspath('../../')\n    if ea979path not in sys.path:\n        sys.path.append(ea979path)\n    import ea979.src as ia\n    \n    get_ipython().magic('matplotlib inline')\n    import matplotlib.pyplot as plt\n\n\n# ### Example 1 - Numeric 2-dimensional\n\n# In[2]:\n\nif testing:\n    f = ia.gaussian((8, 4), np.transpose([[3, 1]]), [[1, 0], [0, 1]])\n    print('f=\\n', np.array2string(f, precision=4, suppress_small=1))\n    g = ia.normalize(f, [0, 255]).astype(np.uint8)\n    print('g=\\n', g)\n\n\n# ## Example 2 - one dimensional signal\n\n# In[3]:\n\n# note that for 1-D case, the tuple has extra ,\n# and the covariance matrix must be 2-D\nif testing:\n    f = ia.gaussian( (100,), 50, [[10*10]]) \n    g = ia.normalize(f, [0,1])\n    plt.plot(g)\n    plt.show()\n\n\n# ### Example 3 - two-dimensional image\n\n# In[4]:\n\nif testing:\n    f = ia.gaussian((150,250), np.transpose([[75,100]]), [[40*40,0],[0,30*30]])\n    g = ia.normalize(f, [0,255]).astype(np.uint8)\n    ia.adshow(g)\n\n\n# ## Example 4 - Numeric 3-dimensional\n\n# In[6]:\n\nif testing:\n    f = ia.gaussian((3,4,5), np.transpose([[1,2,3]]), [[1,0,0],[0,4,0],[0,0,9]])\n    print('f=\\n', np.array2string(f, precision=4, suppress_small=1))\n    g = ia.normalize(f, [0,255]).astype(np.uint8)\n    print('g=\\n', g)\n\n\n# ## Equation\n\n# $$    f(x) = \\frac{1}{\\sqrt{2 \\pi} \\sigma} exp\\left[ -\\frac{1}{2} \\left( \\frac{x - \\mu}{\\sigma} \\right)^2 \\right]\n# $$\n# \n# $$ f({\\bf x}) = \\frac{1}{(2 \\pi)^{d/2}|\\Sigma|^{1/2}} exp\\left[ -\\frac{1}{2}\\left({\\bf x} - \\mu \\right)^t\\Sigma^{-1}\\left({\\bf x} - \\mu \\right)\\right]\n# $$\n", "meta": {"hexsha": "bd91b853337a3fb0b9bea24a3e32cae22116172a", "size": 2726, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/gaussian.py", "max_stars_repo_name": "andre91998/Image_Processing", "max_stars_repo_head_hexsha": "e507b4b95a64d76bbabb63f8148317879dbc80d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gaussian.py", "max_issues_repo_name": "andre91998/Image_Processing", "max_issues_repo_head_hexsha": "e507b4b95a64d76bbabb63f8148317879dbc80d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gaussian.py", "max_forks_repo_name": "andre91998/Image_Processing", "max_forks_repo_head_hexsha": "e507b4b95a64d76bbabb63f8148317879dbc80d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-03-10T17:25:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T09:21:37.000Z", "avg_line_length": 25.0091743119, "max_line_length": 152, "alphanum_fraction": 0.5843727073, "include": true, "reason": "import numpy", "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.9230391632454271, "lm_q1q2_score": 0.8520012998160584}}
{"text": "# -*- coding: utf-8 -*-\nfrom math import * \nfrom scipy.stats import norm\nfrom scipy.optimize import fmin_bfgs\n\n\n# Black Sholes Function\ndef price(S, K, T, r, v, callPutFlag = 'c'):\n    d1 = (log(S / K) + (r + 0.5 * v**2) * T) / (v * sqrt(T))\n    d2 = d1 - v * sqrt(T)\n    if (callPutFlag == 'c') or (callPutFlag == 'C'):\n        return S * norm.cdf(d1) - K * exp(-r * T) * norm.cdf(d2)\n    else:\n        return K * exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1)\n\n\n# Calc Implied volatility\ndef implied_volatility(price_, S, K, T, r, callPutFlag = 'c'):\n    Objective = lambda x: (price_ - price(S, K, T, r, x, callPutFlag))**2    \n    return fmin_bfgs(Objective, 1, disp=False)[0]\n\n# test\nif __name__ == '__main__':\n    import time\n    time_start = time.clock()\n    # correct : call 3.68\n    print(price(49.0, 50.0, 1.0, 0.01, 0.2, 'C'))\n    time_elapsed = time.clock() - time_start\n    print('time elapsed: %2f seconds' % time_elapsed)\n\n    time_start = time.clock()\n    # correct : put 4.18\n    print(price(49.0, 50.0, 1.0, 0.01, 0.2, 'P'))\n    time_elapsed = time.clock() - time_start\n    print('time elapsed: %2f seconds' % time_elapsed)\n\n    time_start = time.clock()\n    # correct : 0.2\n    print(implied_volatility(3.68, 49.0, 50.0, 1.0, 0.01, 'C'))\n    time_elapsed = time.clock() - time_start\n    print('time elapsed: %2f seconds' % time_elapsed)\n\n    time_start = time.clock()\n    # correct : 0.2\n    print(implied_volatility(4.18, 49.0, 50.0, 1.0, 0.01, 'P'))\n    time_elapsed = time.clock() - time_start\n    print('time elapsed: %2f seconds' % time_elapsed)\n", "meta": {"hexsha": "d39800621117c6a62892ccb0f6fcc8c03c5c03a6", "size": 1571, "ext": "py", "lang": "Python", "max_stars_repo_path": "Option_Data_Parse/heston/gh_black_sholes.py", "max_stars_repo_name": "inwise/Pyrgos-RFBR-", "max_stars_repo_head_hexsha": "e139b56a8d05f668d609e1e48919827ebcfb3bbe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Option_Data_Parse/heston/gh_black_sholes.py", "max_issues_repo_name": "inwise/Pyrgos-RFBR-", "max_issues_repo_head_hexsha": "e139b56a8d05f668d609e1e48919827ebcfb3bbe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Option_Data_Parse/heston/gh_black_sholes.py", "max_forks_repo_name": "inwise/Pyrgos-RFBR-", "max_forks_repo_head_hexsha": "e139b56a8d05f668d609e1e48919827ebcfb3bbe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-04T08:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-03T11:09:35.000Z", "avg_line_length": 32.7291666667, "max_line_length": 77, "alphanum_fraction": 0.5977084659, "include": true, "reason": "from scipy", "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307684643189, "lm_q2_score": 0.8757869900269366, "lm_q1q2_score": 0.8519925305189575}}
{"text": "import pandas as pd\nimport numpy as np\n\n# Volatility literally refers to how \"volatile\" a stock is, meaning how unpredictably its price might change.\n# A statistical measure of dispersion, such as standard deviation, is commonly used to measure volatility.\n\n# In the exercise below, you're given daily prices for two sample stocks.\n# Compute the standard deviations of their log returns, and return the ticker symbol for the stock that is more volatile.\n\n\ndef get_most_volatile(prices):\n    \"\"\"Return the ticker symbol for the most volatile stock.\n\n    Parameters\n    ----------\n    prices : pandas.DataFrame\n        a pandas.DataFrame object with columns: ['ticker', 'date', 'price']\n\n    Returns\n    -------\n    ticker : string\n        ticker symbol for the most volatile stock\n    \"\"\"\n    # TODO: Fill in this function.\n    curr_prices = prices.reset_index().pivot(index=\"date\", columns=\"ticker\", values=\"price\")\n    shifted_prices = curr_prices.shift(1)\n    returns = curr_prices.applymap(np.log) - shifted_prices.applymap(np.log)\n    std = returns.std()\n    print(std)\n    most_volatile = std.idxmax()\n    print(most_volatile)\n    # most_volatile = std.loc[most_volatile_value]\n    # print(most_volatile)\n\n    return most_volatile\n", "meta": {"hexsha": "3567257a859296584a045104f29485ff4333d1cf", "size": 1236, "ext": "py", "lang": "Python", "max_stars_repo_path": "quizes/volatility/volatility.py", "max_stars_repo_name": "babeal/udacity-ai-for-trading", "max_stars_repo_head_hexsha": "3f6ff7a5707edb44bc4dfdd434ec87f9ff5be595", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quizes/volatility/volatility.py", "max_issues_repo_name": "babeal/udacity-ai-for-trading", "max_issues_repo_head_hexsha": "3f6ff7a5707edb44bc4dfdd434ec87f9ff5be595", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quizes/volatility/volatility.py", "max_forks_repo_name": "babeal/udacity-ai-for-trading", "max_forks_repo_head_hexsha": "3f6ff7a5707edb44bc4dfdd434ec87f9ff5be595", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3333333333, "max_line_length": 121, "alphanum_fraction": 0.7095469256, "include": true, "reason": "import numpy", "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307637380759, "lm_q2_score": 0.8757869884059267, "lm_q1q2_score": 0.8519925248028071}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport numpy as np\n\nA = np.array([[1, 4, 6],\n              [5, 2, 2],\n              [-1, 6, 8]])\n\nw, v = np.linalg.eig(A)\nprint(w)\nprint(v)\n\nA = np.array([[1, 4, 6], [5, 2, 2], [-1, 6, 8]])\nb = np.array([[1], [2], [3]])\nx = np.linalg.solve(A, b)\nprint(x)\n\n", "meta": {"hexsha": "f2a2a9ae2b81492b4430dde092d0c1e6c3b71e4d", "size": 295, "ext": "py", "lang": "Python", "max_stars_repo_path": "Module1/Getting_Started_with_Data_Analysis_Code/2/linearalgebra.py", "max_stars_repo_name": "vijaysharmapc/Python-End-to-end-Data-Analysis", "max_stars_repo_head_hexsha": "a00f2d5d1547993e000b2551ec6a1360240885ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2017-04-10T19:18:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T08:23:27.000Z", "max_issues_repo_path": "Module1/Getting_Started_with_Data_Analysis_Code/2/linearalgebra.py", "max_issues_repo_name": "vijaysharmapc/Python-End-to-end-Data-Analysis", "max_issues_repo_head_hexsha": "a00f2d5d1547993e000b2551ec6a1360240885ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-10T09:41:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-10T09:41:43.000Z", "max_forks_repo_path": "Module1/Getting_Started_with_Data_Analysis_Code/2/linearalgebra.py", "max_forks_repo_name": "vijaysharmapc/Python-End-to-end-Data-Analysis", "max_forks_repo_head_hexsha": "a00f2d5d1547993e000b2551ec6a1360240885ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2017-04-25T01:49:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T01:46:43.000Z", "avg_line_length": 15.5263157895, "max_line_length": 48, "alphanum_fraction": 0.4508474576, "include": true, "reason": "import numpy", "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307668889048, "lm_q2_score": 0.8757869851639066, "lm_q1q2_score": 0.8519925244083252}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use('fivethirtyeight')\n\n# Snowflake time of flight\n\nHave you ever watched a snowflake fall and thought, \"How long has that snowflake been falling?\"\n\nHere, we want to determine the time of flight for a snowflake. We'll start simple and add some complexity to make a more accurate model. \n\n## Simplest model\n\nThe simplest assumption we can make is that the only force acting on the snowflake is gravity. This leads to one differential equation, \n\n$-mg = m\\ddot{y}$\n\nwhere $m$ is the mass of the snowflake, $g=9.81~\\frac{m}{s^2}$, and $\\ddot{y}$ is the second derivative with respect to time for the height of the snowflake i.e. its vertical acceleration. \n\nWe integrate this equation twice to create a solution in terms of $y_0$, initial height and $\\dot{y}_0$, its initial vertical velocity. \n\n$\\ddot{y} = -g$\n\n$\\frac{d\\dot{y}}{dt} = -g$\n\n$\\dot{y} -\\dot{y}_0 = -gt$\n\n$\\frac{dy}{dt} = \\dot{y}_0 -gt$\n\n$y-y_0 = \\dot{y}_0t - \\frac{gt^2}{2}$\n\n$y(t) = y_0 +\\dot{y}_0t - \\frac{gt^2}{2}$\n\nNow, we need the initial height and initial speed of the snowflake. A typical cloud might sit $\\approx 1,000~m$ above the ground and let's assume the initial vertical speed is 0 m/s. \n\nThis leaves, $y_0=1000~m~and~\\dot{y}_0=0~m/s$\n\n![Cloud heights and precipitation](https://upload.wikimedia.org/wikipedia/commons/5/57/Cloud_types_en.svg)\n\nt = np.linspace(0, np.sqrt(1000/9.81*2), 1000)\ny = 1000 - 9.81*t**2/2\nplt.plot(t,y)\nplt.xlabel('time (s)')\nplt.ylabel('height (m)')\n\nt[-1]\n\n## Our solution - constant acceleration\n\nAccording to your calculations, the snowflake will start at 1,000-m altitude and reach ground level at almost 14.3 seconds. \n\n> __Note:__ What's wrong with the height curve here? \n\n## A little problem - speed of snowflake\n\nThe graph of height-vs-time keeps getting steeper. The steeper the graph, the faster the snowflake. How fast is your snowflake traveling when it hits the ground?\n\ndy = -9.81*t\n\nplt.plot(t, dy)\nplt.xlabel('time (s)')\nplt.ylabel('vertical speed (m/s)')\n\nAccording to your calculations, the snowflake is traveling at 140 m/s when it strikes the ground. This is >300 mph (or >500 km/h). Whoah...\n\nIf you caught this snowflake on your tongue it would feel like catching an icy [BB gun pellet](https://en.wikipedia.org/wiki/BB_gun#Safety), ouch!\n\nYou are missing a key force in the free body diagram that _slows_ down the snowflake, [_air resistance_ or drag](https://www.grc.nasa.gov/www/k-12/VirtualAero/BottleRocket/airplane/falling.html).\n\n![Air drag free body diagram](https://www.grc.nasa.gov/www/k-12/VirtualAero/BottleRocket/airplane/Images/falling.gif)\n\n## Improved model with air resistance\n\nAdding drag to the free body diagram, now you have a new model. \n\n$m\\ddot{y} = -mg + C_d \\frac{r\\dot{y}^2}{2}A$\n\nwhere $C_d$ is the [unitless drag coefficient](https://en.wikipedia.org/wiki/Drag_coefficient), $r=1.025~kg/m^3$ is the [density of air](https://www.macinstruments.com/blog/what-is-the-density-of-air-at-stp/),  $m=3~mg$ is the [mass of a snowflake](https://hypertextbook.com/facts/2001/JudyMoy.shtml), and $A=\\piD^2/4$ is the area of the snowflake of [diameter](https://gpm.nasa.gov/sites/default/files/document_files/parsivel_Tokay_c3vp_agu.pdf) $D=6~mm$. \n\n> __Note:__ The force of drag always opposes the velocity of the snowflake. Keep in mind if the snowflake moves upward, the force reverses direction. \n\nNow, integrating  the equation can be a bit involved, but using v(t=0)=0, there results\n\n$\\frac{dv}{dt} = -g +\\frac{C_d rA}{2}v^2$\n\n$v(t) = -\\sqrt{\\frac{mg}{C_d rA}}\\tanh\\frac{g C_d rA}{m}t$\n\n\nm = 3e-6 # mg\nCd = 0.5 # no units\nr = 1.025 # kg/m/m/m\ng = 9.81 #m/s/s\nD = 6e-3 # mm - mm\nA = np.pi*D**2/4\nv = -np.sqrt(2*m*g/Cd/r/A)*np.tanh(g*Cd*r*A/m*t)\nplt.plot(t, v)\nplt.xlim(0,0.1)\nplt.xlabel('time (s)')\nplt.ylabel('vertical speed (m/s)')\n\n### Make a comparison to previous model\n\nIn the constant acceleration model, the snowflake reached the ground in 14 seconds. In the improved air resistance model, you find that the snowflake only accelerates for 0.5 seconds. After that, it floats at a constant velocity until impact. This means, you can approximate that the snowflake travels at a constant velocity equal to its terminal velocity, $v_{term}$, as such\n\n$\\frac{dv}{dt} = 0 = -g +\\frac{C_d rA}{2m}v_{term}^2$\n\n$v_{term} = -\\sqrt{\\frac{2mg}{C_d rA}}$\n\nvterm = np.sqrt(2*m*g/Cd/r/A)\nt_improved = np.linspace(0,1000/vterm) \ny_improved = 1000 - vterm*t_improved\nplt.plot(t,y, label = 'constant acceleration')\nplt.plot(t_improved,y_improved, label='constant velocity')\nprint('total flight time is {}'.format(t_improved[-1]))\nplt.xlabel('time (s)')\nplt.ylabel('height (m)')\n\n\n## Wrapping up\n\nThe first model you created assumed constant acceleration, but after accounting for drag you found out that a snowflake reaches a terminal velocity in less than 0.5 seconds. The more accurate model to calculate time of flight was actually a constant velocity model. \n\nYou found that the snowflake drifts slowly to the surface over the course of 496 seconds (or 8 minutes). Gently landing at 2 m/s. ", "meta": {"hexsha": "698f5d675394278514410865e58003173066ab16", "size": 5093, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/module_01/snowflake.py", "max_stars_repo_name": "bryanwweber/engineering-dynamics", "max_stars_repo_head_hexsha": "2452589c8cb180f7273e9deaec53720993028a60", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/jupyter_execute/module_01/snowflake.py", "max_issues_repo_name": "bryanwweber/engineering-dynamics", "max_issues_repo_head_hexsha": "2452589c8cb180f7273e9deaec53720993028a60", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/module_01/snowflake.py", "max_forks_repo_name": "bryanwweber/engineering-dynamics", "max_forks_repo_head_hexsha": "2452589c8cb180f7273e9deaec53720993028a60", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7459016393, "max_line_length": 457, "alphanum_fraction": 0.7229530728, "include": true, "reason": "import numpy", "num_tokens": 1549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.9073122201074847, "lm_q1q2_score": 0.851988693385438}}
{"text": "###\n# Introduction to Data Science Homework Assignment # 1\n# Student: Alan Fernandez, aefernandez@wpi.edu\n# Date: 08/29/18\n# Course: DS501, Introduction to Data Science (Grad Level)\n# Worcester Polytechnic Institute (WPI), Worcester, MA\n###\n\nimport numpy as np\n\nfrom problem3 import random_walk\n\n#-------------------------------------------------------------------------\n'''\n    Problem 4: Solving sink-node problem in PageRank\n    In this problem, we implement the pagerank algorithm which can solve the sink node problem.\n    You could test the correctness of your code by typing `nosetests test4.py` in the terminal.\n'''\n\n#--------------------------\ndef compute_S(A):\n    '''\n        compute the transition matrix S from addjacency matrix A, which solves sink node problem by filling the all-zero columns in A.\n        S[j][i] represents the probability of moving from node i to node j.\n        If node i is a sink node, S[j][i] = 1/n.\n        Input: \n                A: adjacency matrix, a (n by n) numpy matrix of binary values. If there is a link from node i to node j, A[j][i] =1. Otherwise A[j][i]=0 if there is no link.\n        Output: \n                S: transition matrix, a (n by n) numpy matrix of float values.  S[j][i] represents the probability of moving from node i to node j.\n    The values in each column of matrix S should sum to 1.\n    '''\n#########################################\n## INSERT YOUR CODE HERE\n    #print(A)\n    # sum of each column of A\n    column_sum = A.sum(axis = 0)\n\n    # create a diagonal matrix\n    sum_vector = column_sum.getA1()\n    D = np.diag(np.where(sum_vector == 0, 1, sum_vector))\n    #print(D)\n    # normalize each column of A\n\n    # Invert the diagonal matrix to divide the adjacency matrix by the sum of the columns.\n    D = np.linalg.inv(D)\n\n    # Multiply the matrices to execute the division. This returns the transition matrix.\n    S = A * D\n\n    # Determine the number of elements in each column\n    n = S.shape[0]\n\n    # Iterate through each column, determine if its a sink node, and replace with all equal probabilities.\n    for index, column in enumerate(S):\n        if ~S[:,index].any(axis=0).any():\n            S[:,index] = 1/n\n\n    return S\n#########################################\n\n#--------------------------\ndef pagerank_v2(A):\n    ''' \n        A simplified version of PageRank algorithm, which solves the sink node problem.\n        Given an adjacency matrix A, compute the pagerank score of all the nodes in the network. \n        Input: \n                A: adjacency matrix, a numpy matrix of binary values. If there is a link from node i to node j, A[j][i] =1. Otherwise A[j][i]=0 if there is no link.\n        Output: \n                x: the ranking scores, a numpy vector of float values, such as np.array([[.3], [.5], [.7]])\n    '''\n\n    # Initialize the score vector with all one values\n    num_nodes, _ = A.shape \n    x_0 =  np.asmatrix(np.ones((num_nodes,1))) \n\n    # compute the transition matrix from adjacency matrix\n    S = compute_S(A)\n    # random walk\n    x, n_steps = random_walk(S,x_0)\n\n    return x\n\n", "meta": {"hexsha": "6aa22afbca3b940eb70af0d601e4302aea9a3f5f", "size": 3085, "ext": "py", "lang": "Python", "max_stars_repo_path": "Homework_1/problem4.py", "max_stars_repo_name": "aefernandez/DS501", "max_stars_repo_head_hexsha": "15799c8690c2f934d8e710db060e2b9e1b6afc8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homework_1/problem4.py", "max_issues_repo_name": "aefernandez/DS501", "max_issues_repo_head_hexsha": "15799c8690c2f934d8e710db060e2b9e1b6afc8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homework_1/problem4.py", "max_forks_repo_name": "aefernandez/DS501", "max_forks_repo_head_hexsha": "15799c8690c2f934d8e710db060e2b9e1b6afc8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1686746988, "max_line_length": 173, "alphanum_fraction": 0.6094003241, "include": true, "reason": "import numpy", "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.9073122144683576, "lm_q1q2_score": 0.8519886834454509}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 11 19:55:21 2020\n\n@author: nmazzilli24\n\"\"\"\n\nimport numpy as np\nimport math\n\n\n'''\n1 - Building basic functions with numpy\nNumpy is the main package for scientific computing in Python. It is maintained by a large community (www.numpy.org). In this exercise you will learn several key numpy functions such as np.exp, np.log, and np.reshape. You will need to know how to use these functions for future assignments.\n\n1.1 - sigmoid function, np.exp()\nBefore using np.exp(), you will use math.exp() to implement the sigmoid function. You will then see why np.exp() is preferable to math.exp().\n\nExercise: Build a function that returns the sigmoid of a real number x. Use math.exp(x) for the exponential function.\n\nReminder:  sigmoid(x)=11+e−xsigmoid(x)=11+e−x  is sometimes also known as the logistic function. It is a non-linear function used not only in Machine Learning (Logistic Regression), but also in Deep Learning.\n'''\n\ndef basic_sigmoid(x):\n    \"\"\"\n    Compute sigmoid of x.\n\n    Arguments:\n    x -- A scalar\n\n    Return:\n    s -- sigmoid(x)\n    \"\"\"\n\n    ### START CODE HERE ### (≈ 1 line of code)\n    s = 1/(1+math.exp(-x))\n    ### END CODE HERE ###\n\n    return s\n\n'''\nAny time you need more info on a numpy function, we encourage you to look at the official documentation.\n\nYou can also create a new cell in the notebook and write np.exp? (for example) to get quick access to the documentation.\n\nExercise: Implement the sigmoid function using numpy.\n\nInstructions: x could now be either a real number, a vector, or a matrix. The data structures we use in numpy to represent these shapes (vectors, matrices...) are called numpy arrays. You don't need to know more for now.\n\n'''\n\ndef sigmoid(x):\n    \"\"\"\n    Compute the sigmoid of x\n\n    Arguments:\n    x -- A scalar or numpy array of any size\n\n    Return:\n    s -- sigmoid(x)\n    \"\"\"\n    \n    ### START CODE HERE ### (≈ 1 line of code)\n    s = 1/(1+np.exp(-x))\n    ### END CODE HERE ###\n    \n    return s\n\n'''\n1.2 - Sigmoid gradient\nAs you've seen in lecture, you will need to compute gradients to optimize loss functions using backpropagation. Let's code your first gradient function.\n\nExercise: Implement the function sigmoid_grad() to compute the gradient of the sigmoid function with respect to its input x. The formula is:\nsigmoid_derivative(x)=σ′(x)=σ(x)(1−σ(x))(2)\n(2)sigmoid_derivative(x)=σ′(x)=σ(x)(1−σ(x))\n \nYou often code this function in two steps:\n\nSet s to be the sigmoid of x. You might find your sigmoid(x) function useful.\nCompute  σ′(x)=s(1−s)σ′(x)=s(1−s)\n'''\n\ndef sigmoid_derivative(x):\n    \"\"\"\n    Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x.\n    You can store the output of the sigmoid function into variables and then use it to calculate the gradient.\n    \n    Arguments:\n    x -- A scalar or numpy array\n\n    Return:\n    ds -- Your computed gradient.\n    \"\"\"\n    \n    ### START CODE HERE ### (≈ 2 lines of code)\n    s = sigmoid(x)\n    ds = s*(1-s)\n    ### END CODE HERE ###\n    \n    return ds\n'''\n1.3 - Reshaping arrays\nTwo common numpy functions used in deep learning are np.shape and np.reshape().\n\nX.shape is used to get the shape (dimension) of a matrix/vector X.\nX.reshape(...) is used to reshape X into some other dimension.\nFor example, in computer science, an image is represented by a 3D array of shape  (length,height,depth=3)(length,height,depth=3) . However, when you read an image as the input of an algorithm you convert it to a vector of shape  (length∗height∗3,1)(length∗height∗3,1) . In other words, you \"unroll\", or reshape, the 3D array into a 1D vector.\n\nExercise: Implement image2vector() that takes an input of shape (length, height, 3) and returns a vector of shape (length*height*3, 1). For example, if you would like to reshape an array v of shape (a, b, c) into a vector of shape (a*b,c) you would do:\n\nv = v.reshape((v.shape[0]*v.shape[1], v.shape[2])) # v.shape[0] = a ; v.shape[1] = b ; v.shape[2] = c\nPlease don't hardcode the dimensions of image as a constant. Instead look up the quantities you need with image.shape[0], etc.                                                                               \n  \n'''                                                                               \n\ndef image2vector(image):\n    \"\"\"\n    Argument:\n    image -- a numpy array of shape (length, height, depth)\n    \n    Returns:\n    v -- a vector of shape (length*height*depth, 1)\n    \"\"\"\n    \n    ### START CODE HERE ### (≈ 1 line of code)\n    v = image.reshape(image.shape[0]*image.shape[1]*image.shape[2],1)\n    ### END CODE HERE ###\n    \n    return v\n\n'''\n1.4 - Normalizing rows\nAnother common technique we use in Machine Learning and Deep Learning is to normalize our data. It often leads to a better performance because gradient descent converges faster after normalization. Here, by normalization we mean changing x to  x∥x∥x∥x∥  (dividing each row vector of x by its norm).\n\nFor example, if\nx=[023644](3)\n(3)x=[034264]\n \nthen\n∥x∥=np.linalg.norm(x,axis=1,keepdims=True)=[556⎯⎯⎯⎯√](4)\n(4)∥x∥=np.linalg.norm(x,axis=1,keepdims=True)=[556]\n \nand\nx_normalized=x∥x∥=0256√35656√45456√(5)\n(5)x_normalized=x∥x∥=[03545256656456]\n \nNote that you can divide matrices of different sizes and it works fine: this is called broadcasting and you're going to learn about it in part 5.\n\nExercise: Implement normalizeRows() to normalize the rows of a matrix. After applying this function to an input matrix x, each row of x should be a vector of unit length (meaning length 1).\n\n'''\n\ndef normalizeRows(x):\n    \"\"\"\n    Implement a function that normalizes each row of the matrix x (to have unit length).\n    \n    Argument:\n    x -- A numpy matrix of shape (n, m)\n    \n    Returns:\n    x -- The normalized (by row) numpy matrix. You are allowed to modify x.\n    \"\"\"\n    \n    ### START CODE HERE ### (≈ 2 lines of code)\n    # Compute x_norm as the norm 2 of x. Use np.linalg.norm(..., ord = 2, axis = ..., keepdims = True)\n    x_norm = np.linalg.norm(x,axis =1, keepdims = True)\n    \n    # Divide x by its norm.\n    x = x/x_norm\n    ### END CODE HERE ###\n\n    return x\n\n'''\n1.5 - Broadcasting and the softmax function¶\nA very important concept to understand in numpy is \"broadcasting\". It is very useful for performing mathematical operations between arrays of different shapes. For the full details on broadcasting, you can read the official broadcasting documentation.\n\nExercise: Implement a softmax function using numpy. You can think of softmax as a normalizing function used when your algorithm needs to classify two or more classes. You will learn more about softmax in the second course of this specialization.\n\n'''\n\ndef softmax(x):\n    \"\"\"Calculates the softmax for each row of the input x.\n\n    Your code should work for a row vector and also for matrices of shape (m,n).\n\n    Argument:\n    x -- A numpy matrix of shape (m,n)\n\n    Returns:\n    s -- A numpy matrix equal to the softmax of x, of shape (m,n)\n    \"\"\"\n    \n    ### START CODE HERE ### (≈ 3 lines of code)\n    # Apply exp() element-wise to x. Use np.exp(...).\n    x_exp = np.exp(x)\n\n    # Create a vector x_sum that sums each row of x_exp. Use np.sum(..., axis = 1, keepdims = True).\n    x_sum = np.sum(x_exp,axis =1, keepdims = True)\n    \n    # Compute softmax(x) by dividing x_exp by x_sum. It should automatically use numpy broadcasting.\n    s = x_exp/x_sum\n\n    ### END CODE HERE ###\n    \n    return s\n\n'''\n2.1 Implement the L1 and L2 loss functions\nExercise: Implement the numpy vectorized version of the L1 loss. You may find the function abs(x) (absolute value of x) useful.\n\nReminder:\n\nThe loss is used to evaluate the performance of your model. The bigger your loss is, the more different your predictions (ŷ y^) are from the true values (yy). In deep learning, you use optimization algorithms like Gradient Descent to train your model and to minimize the cost.\nL1 loss is defined as:\n\n'''\n\ndef L1(yhat, y):\n    \"\"\"\n    Arguments:\n    yhat -- vector of size m (predicted labels)\n    y -- vector of size m (true labels)\n    \n    Returns:\n    loss -- the value of the L1 loss function defined above\n    \"\"\"\n    \n    ### START CODE HERE ### (≈ 1 line of code)\n    loss = np.sum(abs(y-yhat))\n    ### END CODE HERE ###\n    \n    return loss\n\n\n#Testing functions\ndef main():\n    print(\"Testing basic_sigmoid function\")\n    test_sig = basic_sigmoid(3)\n    sig_sol = 0.952\n    tol = 0.001\n    assert(abs(test_sig-sig_sol) < tol)\n    print(\"Passed the basic_sigmoid function!\")\n    print()\n    \n    #Testing the sigmoid with np apis \n    print(\"Testing sigmoid function\")\n    x = np.array([1, 2, 3])\n    test_sig_np = sigmoid(x)\n    sig_np_sol = [ 0.73105858, 0.88079708, 0.95257413]\n\n    #https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html\n    assert(np.allclose(test_sig_np,sig_np_sol, tol))\n    print(\"Passed the basic_sigmoid function!\")\n    print()    \n    \n    #Sigmoid Derivative Test\n    print(\"Testing sigmoid_derivative function\")\n    x = np.array([1, 2, 3])\n    test_sig_deriv = sigmoid_derivative(x)\n    test_sig_deriv_sol = [ 0.19661193, 0.10499359, 0.04517666]\n    assert(np.allclose(test_sig_deriv,test_sig_deriv_sol, tol))\n    print(\"Passed the sigmoid_derivative function!\")\n    print()     \n    \n    #Normalize Row Test\n    print(\"Testing normalizeRows function\")\n    x = np.array([\n    [0, 3, 4],\n    [1, 6, 4]])\n    norm_row = normalizeRows(x)\n    norm_row_sol = [[ 0., 0.6, 0.8 ], [ 0.13736056, 0.82416338, 0.54944226]]\n    assert(np.allclose(norm_row,norm_row_sol, tol))\n    print(\"Passed the normalizeRows function!\")\n    print() \n    \n    #Testing Softmax Funciton\n    print(\"Testing softmax function\")\n    x = np.array([\n    [9, 2, 5, 0, 0],\n    [7, 5, 0, 0 ,0]])\n    softmax_res = softmax(x)\n    softmax_sol = [[ 9.80897665e-01, 8.94462891e-04, 1.79657674e-02, 1.21052389e-04, 1.21052389e-04], [ 8.78679856e-01, 1.18916387e-01, 8.01252314e-04, 8.01252314e-04, 8.01252314e-04]]\n    np.testing.assert_allclose(softmax_res,softmax_sol,rtol=1e-5, atol=0)\n    print(\"Passed the softmax function!\")\n    print() \n    \n    #Testing L1 Function \n    print(\"Testing L1 function\")\n    yhat = np.array([.9, 0.2, 0.1, .4, .9])\n    y = np.array([1, 0, 0, 1, 1])\n    L1_test = L1(yhat,y)\n    L1_sol = 1.1 \n    assert(abs(L1_test-L1_sol) < tol)\n    print(\"Passed the L1 function!\")\n    print()  \n    \n    ''' Framework for Computational Time\n    import time\n\n    x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]\n    x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]\n    \n    ### CLASSIC DOT PRODUCT OF VECTORS IMPLEMENTATION ###\n    tic = time.process_time()\n    dot = 0\n    for i in range(len(x1)):\n        dot+= x1[i]*x2[i]\n    toc = time.process_time()\n    print (\"dot = \" + str(dot) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n    \n    ### CLASSIC OUTER PRODUCT IMPLEMENTATION ###\n    tic = time.process_time()\n    outer = np.zeros((len(x1),len(x2))) # we create a len(x1)*len(x2) matrix with only zeros\n    for i in range(len(x1)):\n        for j in range(len(x2)):\n            outer[i,j] = x1[i]*x2[j]\n    toc = time.process_time()\n    print (\"outer = \" + str(outer) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n    \n    ### CLASSIC ELEMENTWISE IMPLEMENTATION ###\n    tic = time.process_time()\n    mul = np.zeros(len(x1))\n    for i in range(len(x1)):\n        mul[i] = x1[i]*x2[i]\n    toc = time.process_time()\n    print (\"elementwise multiplication = \" + str(mul) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n    \n    ### CLASSIC GENERAL DOT PRODUCT IMPLEMENTATION ###\n    W = np.random.rand(3,len(x1)) # Random 3*len(x1) numpy array\n    tic = time.process_time()\n    gdot = np.zeros(W.shape[0])\n    for i in range(W.shape[0]):\n        for j in range(len(x1)):\n            gdot[i] += W[i,j]*x1[j]\n    toc = time.process_time()\n    print (\"gdot = \" + str(gdot) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n'''\n\n    \n\n\n\n    \n\n    \n    \n\n\n\n\nif __name__ == '__main__':\n    main()", "meta": {"hexsha": "89cb0b6c3ad450fc25edd98661883b0fd9a00ff2", "size": 12068, "ext": "py", "lang": "Python", "max_stars_repo_path": "NeuralNetworksandDeepLearning/Programming_Assignments/Week2/Python_Basics/python_basics.py", "max_stars_repo_name": "nmazzilli3/deeplearning.ai", "max_stars_repo_head_hexsha": "15fbc2ccc05ea6f91f9ee88bc4156b53b358c0a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NeuralNetworksandDeepLearning/Programming_Assignments/Week2/Python_Basics/python_basics.py", "max_issues_repo_name": "nmazzilli3/deeplearning.ai", "max_issues_repo_head_hexsha": "15fbc2ccc05ea6f91f9ee88bc4156b53b358c0a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NeuralNetworksandDeepLearning/Programming_Assignments/Week2/Python_Basics/python_basics.py", "max_forks_repo_name": "nmazzilli3/deeplearning.ai", "max_forks_repo_head_hexsha": "15fbc2ccc05ea6f91f9ee88bc4156b53b358c0a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1869688385, "max_line_length": 342, "alphanum_fraction": 0.6440172357, "include": true, "reason": "import numpy", "num_tokens": 3405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.9219218370002787, "lm_q1q2_score": 0.8519865223974675}}
{"text": "\"\"\"\nThis code implements a perceptron algorithm (PLA). \nThis is the version of the file that runs in Python 3.6:\n- it does not plot\n- it had to be adjusted to pandas 0.23.0 because Vocareum uses python 3.6\n\nFirst, we visualise the dataset which contains 2 features. We can see that the dataset can be clearly separated by drawing a straight line between them. The goal is to write an algorithm that finds that line and classifies all of these data points correctly.\n\nThe output file (e.g. 'output1_f.csv') contains the values of w1, w2 and b which define the 'threshold' line. The last row will be the most accurate one. Each time it goes through each of the examples in 'input1.csv', it adds a new line to the output file containing a comma-separated list of the weights w_1, w_2, and b (bias) in that order. \n\nUpon convergence, the program stops, and the final values of w_1, w_2, and b are printed to the output file (output1.csv). This defines the decision boundary that your PLA has computed for the given dataset.\n\nNote: When implementing your PLA, in case of tie (sum of w_jx_ij = 0), please follow the lecture note and classify the datapoint as -1.\n\nEnsure this file can be executed as:\n$ python3 problem1.py input1.csv output1.csv\n\nThe code includes plotting functions. However those are disabled when executing the code from the command line in the format specified immediately above.\n\n\"\"\"\n\n# builtin modules\nimport os\nimport psutil\nimport requests\nimport sys\n\n# 3rd party modules\nimport pandas as pd\nimport numpy as np\n#import plotly.graph_objects as go\n\n    \ndef get_data(source_file):\n\n    # Define input and output filepaths\n    input_path = os.path.join(os.getcwd(), source_file)\n\n    # Read input data\n    df = pd.read_csv(input_path)\n\n    return df\n\ndef perceptron_classify(df, n:int = 200):\n    \"\"\"\n    1. set b = w = 0\n    2. for N iterations, or until weights do not change\n        (a) for each training example xᵏ with label yᵏ\n            i. if yᵏ — f(xᵏ) = 0, continue\n            ii. else, update wᵢ, △wᵢ = (yᵏ — f(xᵏ)) xᵢ\n    \"\"\"\n        \n    # transform the dataframe to an array\n    data = np.asmatrix(df, dtype = 'float64')\n\n    # get the first two columns as pairs of values\n    features = data[:, :-1]\n    # get the last column\n    labels = data[:, -1]\n\n    # assign zero weight as a starting point to features and labels\n    w = np.zeros(shape=(1, features.shape[1]+1)) #e.g. array([0., 0., 0.])\n    w_ = np.empty(shape=[0,3]) # declare w_ as an empty matrix of same shape as w\n\n    for iteration in range(0,n):\n        for x, label in zip(features, labels):\n            x = np.insert(x, 0, 1) # add a column of 1s to represent w0\n            f = np.dot(w, x.transpose()) # a scalar\n            #print(f)\n            if f * label <= 0:\n                w += (x * label.item(0,0)).tolist() # because label comes from being a matrix (matrix([[1.]])) and needs to be converted to scalar\n            else:\n                iteration = n\n\n        w_ = np.vstack((w_, w))\n\n    return w_\n\n\n   \ndef write_csv(filename, weights):\n    # write the outputs csv file\n    filepath = os.path.join(os.getcwd(), filename)\n    dataframe = pd.DataFrame(data=weights, columns=('b','w1','w2'))\n    # reorder the columns in the dataframe in accordance with assignment \n    order = [1,2,0] # setting column's order, 'b' goes as first column followed by weights\n    dataframe = dataframe[[dataframe.columns[i] for i in order]]\n    dataframe.to_csv(filepath, index = False, header = False)\n    return print(\"New Outputs file saved to: <<\", filename, \">>\", sep='', end='\\n')\n\n\ndef main():\n\n    #take string of input data csv file\n    in_data = str(sys.argv[1])\n    \n    #take string of input data csv file\n    out_data = str(sys.argv[2])\n\n    if in_data and out_data:\n        #add functions execute here\n        df = get_data(in_data)\n        w_ = perceptron_classify(df)\n        if w_.size:\n            write_csv(out_data, w_)\n            print(\"Plot and output csv files are ready !\")\n    else:\n        print(\"Enter valid command arguments !\")\n\n\nif __name__ == '__main__':\n    main()", "meta": {"hexsha": "ae9f807b4925fdcf74b6701becf5a6d79cb0e5c2", "size": 4088, "ext": "py", "lang": "Python", "max_stars_repo_path": "py36/problem1.py", "max_stars_repo_name": "mariamingallonMM/AI-PerceptronLearningAlgorithm-A3", "max_stars_repo_head_hexsha": "2239e217a79c25017d45cb3a0112a37696e92078", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-20T05:08:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T21:19:02.000Z", "max_issues_repo_path": "py36/problem1.py", "max_issues_repo_name": "mariamingallonMM/AI-PerceptronLearningAlgorithm-A3", "max_issues_repo_head_hexsha": "2239e217a79c25017d45cb3a0112a37696e92078", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "py36/problem1.py", "max_forks_repo_name": "mariamingallonMM/AI-PerceptronLearningAlgorithm-A3", "max_forks_repo_head_hexsha": "2239e217a79c25017d45cb3a0112a37696e92078", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5, "max_line_length": 343, "alphanum_fraction": 0.6636497065, "include": true, "reason": "import numpy", "num_tokens": 1073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191348157373, "lm_q2_score": 0.891811054783143, "lm_q1q2_score": 0.8519641652745423}}
{"text": "import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport os\r\nos.chdir('C:/Users/DELL/Desktop/Quant_macro')\r\nimport useful_functions as uf\r\n\r\nf = lambda x: (x + np.abs(x))/2\r\nx_bar = 2\r\nstart = 0\r\nend_ = 6\r\nnum_g = 100\r\n\r\n\r\nTay1 = lambda x: uf.Taylor_any_f(x, x_bar, 1, f)\r\nTay2 = lambda x: uf.Taylor_any_f(x, x_bar, 2, f)\r\nTay5 = lambda x: uf.Taylor_any_f(x, x_bar, 5, f)\r\nTay20 = lambda x: uf.Taylor_any_f(x, x_bar, 20, f)\r\n\r\n\r\nx_eval = np.linspace(start, end_, num_g)\r\nx_eval = x_eval[1:-1]\r\n \r\nRg = [f(x_eval[i]) for i in range(len(x_eval))]\r\nTay20_o = [Tay20(x_eval[i]) for i in range(len(x_eval))]\r\nTay5_o = [Tay5(x_eval[i]) for i in range(len(x_eval))]\r\nTay2_o = [Tay2(x_eval[i]) for i in range(len(x_eval))]\r\nTay1_o = [Tay1(x_eval[i]) for i in range(len(x_eval))]\r\n\r\n\r\nf, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2)\r\nf.set_figheight(10)\r\nf.set_figwidth(10)\r\nax1.plot(x_eval, Tay1_o, color = 'r', label = 'Taylor 1')\r\nax1.legend(loc='upper left')\r\nax1.set_xlabel('x')\r\nax1.set_ylabel('f(x)')\r\nax1.set_title('Expansion of Order 1')\r\nax2.plot(x_eval, Tay2_o, color = 'b', label = 'Taylor 2')\r\nax2.legend(loc='upper left')\r\nax2.set_xlabel('x')\r\nax2.set_ylabel('f(x)')\r\nax2.set_title('Expansion of Order 2')\r\nax3.plot(x_eval, Tay5_o, color = 'g', label = 'Taylor 5')\r\nax3.legend(loc='upper left')\r\nax3.set_xlabel('x')\r\nax3.set_ylabel('f(x)')\r\nax3.set_title('Expansion of Order 5')\r\nax4.plot(x_eval, Tay20_o, color = 'k', label = 'Taylor 20')\r\nax4.legend(loc='upper left')\r\nax4.set_xlabel('x')\r\nax4.set_ylabel('f(x)')\r\nax4.set_title('Expansion of Order 20')\r\n\r\n\r\n\r\nf1, ax5 = plt.subplots(1,1)\r\nf1.set_figheight(5)\r\nf1.set_figwidth(10)\r\nax5.set_yscale('linear')\r\nax5.plot(x_eval, Tay1_o, color = 'r', label = 'Taylor 1')\r\nax5.plot(x_eval, Tay2_o, color = 'b', label = 'Taylor 2')\r\nax5.plot(x_eval, Tay5_o, color = 'g', label = 'Taylor 5')\r\nax5.plot(x_eval, Tay20_o, color = 'k', label = 'Taylor 20') \r\nax5.plot(x_eval, Rg, color = 'gold', label = 'True function') \r\n\r\nax5.legend(loc='upper left')\r\nax5.set_xlabel('x')\r\nax5.set_ylabel('f(x)')\r\nax5.set_title('The Taylor Expansions')\r\n\r\n\r\n\r\n        ", "meta": {"hexsha": "49951d9497f46b63ee65fbdc559a01b62bbcd2a2", "size": 2101, "ext": "py", "lang": "Python", "max_stars_repo_path": "Exercise_2.py", "max_stars_repo_name": "SkanderGar/QuantMacro", "max_stars_repo_head_hexsha": "329eae290a34ca8cb794d4bbf05ecc2ae4ede8cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Exercise_2.py", "max_issues_repo_name": "SkanderGar/QuantMacro", "max_issues_repo_head_hexsha": "329eae290a34ca8cb794d4bbf05ecc2ae4ede8cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercise_2.py", "max_forks_repo_name": "SkanderGar/QuantMacro", "max_forks_repo_head_hexsha": "329eae290a34ca8cb794d4bbf05ecc2ae4ede8cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7808219178, "max_line_length": 63, "alphanum_fraction": 0.6544502618, "include": true, "reason": "import numpy", "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715436, "lm_q2_score": 0.8918110569397307, "lm_q1q2_score": 0.8519641650658317}}
{"text": "#!/usr/bin/env python3\nimport numpy as np\nfrom numpy.linalg import inv \nfrom scipy.spatial import distance \nfrom math import sin\nfrom math import cos \nfrom numba import jit\n\n@jit(forceobj=True)\ndef vector_angle(u,v):\n    num = np.arccos( np.dot(u ,v) )\n    den = np.power(np.dot(v,v),1/2) * np.power(np.dot(u,u),1/2 )\n    angle = num / den \n    if np.isnan(angle).any(0) == True:\n        angle = 0\n    return angle\n\n@jit(forceobj=True)\ndef Rz(theta_z):\n    a = theta_z\n    T = np.array([[cos(a),-sin(a), 0,0 ],[sin(a),cos(a),0,0],[0,0,1,0],[0,0,0,1]],dtype = np.float32)\n    return T\n\n@jit(forceobj=True)\ndef Ry(theta_y):\n    a = theta_y\n    T =  np.array([[cos(a),0, sin(a),0 ],[0,1,0,0],[-sin(a),0,cos(a),0],[0,0,0,1]],dtype = np.float32)\n    return T\n\n@jit(forceobj=True)\ndef Rx(theta_x):\n    a = theta_x\n    T =  np.array([[1,0, 0,0 ],[0,cos(a),-sin(a),0],[0,sin(a),cos(a),0],[0,0,0,1]],dtype = np.float32)\n    return T\n\n@jit(forceobj=True)\ndef T_tr(dx,dy,dz):\n    T =  np.array([[1 ,0 ,0 ,dx],[0,1,0,dy],[0,0,1,dz],[0,0,0,1]],dtype = np.float32)\n    return T\n\n@jit(forceobj=True)\ndef Tx(theta_x,dx,dy,dz):\n    a = theta_x\n    T =  np.array([[1,0, 0,dx ],[0,cos(a),-sin(a),dy],[0,sin(a),cos(a),dz],[0,0,0,1]],dtype = np.float32)\n    return T\n\n@jit(forceobj=True)\ndef Ty(theta_y,dx,dy,dz):\n    a = theta_y\n    T =  np.array([[cos(a),0, sin(a),dx ],[0,1,0,dy],[-sin(a),0,cos(a),dz],[0,0,0,1]],dtype = np.float32)\n    return T\n\n@jit(forceobj=True)\ndef Tz(theta_z,dx,dy,dz):\n    a = theta_z\n    T = np.array(   [   [cos(a),     -sin(a),    0,     dx],\n                        [sin(a),      cos(a),    0,     dy],\n                        [0     ,           0,    1,     dz],\n                        [0     ,           0,    0,     1 ]\n                        ] ,\n                        dtype = np.float32 )\n    return T\n\n@jit\ndef solve_rr(x,y,L12,L23,elbow):\n    num = np.power( L12, 2 ) + np.power( L23 , 2 ) - np.power( x , 2 ) - np.power( y , 2 )\n    den = 2 * L12 * L23\n    arg = num / den\n    if elbow == \"down\":\n        q2 = np.pi - np.arccos(arg) \n    elif elbow == \"up\" :\n        q2 = - np.arccos(- arg) \n    else:\n        print(\"wrong format,insert 1:up,or 2:down\")\n    q1 = np.arctan2(y,x) - np.arctan2((L23 * np.sin(q2)) , (L12 + L23 * np.cos(q2)))\n\n    return q1,q2\n\n@jit(forceobj=True)\ndef euler_angles(R):\n    phi = np.arctan2(R[1,2] , R[0,2])\n    theta = np.arctan2( np.power(np.power(R[0,2], 2) + np.power(R[1,2] ,2) ,1/2), R[2,2] )\n    psi = np.arctan2( - R[2,1], R[2,1] )\n    angles = np.asarray( [phi, theta, psi] )\n    return angles\n\n@jit(forceobj=True)\ndef mdot(*args):\n    T = np.eye( args[0].shape[0] )\n    for arg in args:\n        T = np.dot( T , arg )\n    return T\n\ndef T_DH(d_n,theta_n,r_n,alpha_n):\n    ctheta = np.cos( theta_n )\n    calpha = np.cos( alpha_n )\n    stheta = np.sin( theta_n )\n    salpha = np.sin( alpha_n )\n\n    T = np.asarray  ( [ [ctheta ,   -stheta*calpha  , stheta*salpha     , r_n * ctheta  ] ,\n                        [stheta ,   ctheta*calpha   , -ctheta*salpha    , r_n*stheta    ] ,\n                        [0      ,   salpha          , calpha            , d_n           ] ,\n                        [0      ,   0               , 0                 ,1              ] ]\n                    )\n\n    return T\n", "meta": {"hexsha": "7093ace0c1fb8f20b560865c987073bab7518e48", "size": 3255, "ext": "py", "lang": "Python", "max_stars_repo_path": "kinematichs/support/matrixs.py", "max_stars_repo_name": "ATLED-3301/robopy", "max_stars_repo_head_hexsha": "6e8c462bb93defc597a570907bebccdbba57fcf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kinematichs/support/matrixs.py", "max_issues_repo_name": "ATLED-3301/robopy", "max_issues_repo_head_hexsha": "6e8c462bb93defc597a570907bebccdbba57fcf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kinematichs/support/matrixs.py", "max_forks_repo_name": "ATLED-3301/robopy", "max_forks_repo_head_hexsha": "6e8c462bb93defc597a570907bebccdbba57fcf0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4205607477, "max_line_length": 105, "alphanum_fraction": 0.49093702, "include": true, "reason": "import numpy,from numpy,from scipy,from numba", "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436404, "lm_q2_score": 0.8918110526265554, "lm_q1q2_score": 0.8519641620798427}}
{"text": "import numpy as np\n\ndef skew(a):\n    \"\"\"Returns skew symmetric matrix, given a 3-vector\"\"\"\n    return np.array([\n        [    0, -a[2],  a[1]],\n        [ a[2],     0, -a[0]],\n        [-a[1],  a[0],     0]\n        ])   \n\ndef rot1(t):\n    return np.array([\n        [1, 0, 0],\n        [0, np.cos(t), -np.sin(t)],\n        [0, np.sin(t),  np.cos(t)]\n        ])\n\ndef rot2(t):\n    return np.array([\n        [np.cos(t), 0, np.sin(t)],\n        [0, 1, 0],\n        [-np.sin(t), 0, np.cos(t)]\n        ])\n\ndef rot3(t):\n    return np.array([\n        [np.cos(t), -np.sin(t), 0],\n        [np.sin(t), np.cos(t), 0],\n        [0, 0, 1]\n        ])\n\ndef rot2D(t):\n    return np.array([\n        [np.cos(t), -np.sin(t)],\n        [np.sin(t),  np.cos(t)]\n        ])\n\ndef euler2rot(phi, theta, psi):\n    return rot3(psi) @ rot2(theta) @ rot1(phi) \n\ndef rot2euler(R):\n    \"\"\"Compute Euler angles from rotation matrix.\n    yaw, pitch, roll: 3, 2, 1 rot sequence\n    Note frame relationship: e^b = e^v R^{vb}\n    \"\"\"\n    psi = np.arctan2(R[1, 0], R[0, 0]) # yaw angle\n    theta = np.arcsin(-R[2, 0])        # pitch angle\n    phi = np.arctan2(R[2, 1], R[2, 2]) # roll angle\n    return (phi, theta, psi)\n\n\ndef conj(q):\n    return np.concatenate([[q[0]], -q[1:]])\n\ndef prod(p, q):\n    \"\"\"Compute product of two quaternions\"\"\"\n    p0 = p[0]; p = p[1:4]\n    q0 = q[0]; q = q[1:4]\n    pq0 = p0*q0 - np.dot(p, q)\n    pq = p0*q + p*q0 + np.cross(p,q)\n    return np.concatenate([[pq0], pq])\n\ndef euler2quat(phi, theta, psi):\n    psi2 = psi/2\n    theta2 = theta/2\n    phi2 = phi/2\n    return np.array([\n        np.sin(phi2)*np.sin(psi2)*np.sin(theta2) + np.cos(phi2)*np.cos(psi2)*np.cos(theta2), \n        np.sin(phi2)*np.cos(psi2)*np.cos(theta2) - np.sin(psi2)*np.sin(theta2)*np.cos(phi2), \n        np.sin(phi2)*np.sin(psi2)*np.cos(theta2) + np.sin(theta2)*np.cos(phi2)*np.cos(psi2), \n        -np.sin(phi2)*np.sin(theta2)*np.cos(psi2) + np.sin(psi2)*np.cos(phi2)*np.cos(theta2)\n        ])\n\ndef quat2rot(q):\n    \"\"\"Compute rotation matrix from quaternion.\n    quaternion must be provided in form [q0, q]\n    \"\"\"    \n    q = q.flatten()\n    q0 = q[0]\n    q = q[1:]\n    return (q0**2 - np.dot(q, q))*np.eye(3) + 2*np.outer(q,q) + 2*q0*skew(q)\n\ndef quat2euler(q):\n    R = quat2rot(q)\n    return rot2euler(R)\n\nif __name__ == \"__main__\":    \n    # Tests\n    \n    # Check quat_prod\n    p = np.array([3, 1, -2, 1])\n    q = np.array([2, -1, 2, 3])\n    pq = np.array([8, -9, -2, 11])\n    print('pq_hand - pq = ', np.linalg.norm(prod(p,q)-pq))\n    \n    # Check conversions rot <-> quat\n    phi = 2*np.pi * np.random.random_sample()\n    theta = 2*np.pi * np.random.random_sample()\n    psi = 2*np.pi * np.random.random_sample()\n    R = euler2rot(phi=phi, theta=theta, psi=psi)\n    q = euler2quat(phi=phi, theta=theta, psi=psi)\n    R_ = quat2rot(q)\n    print('R - R_ = ',np.linalg.norm(R-R_))\n \n    # Check defs w and qdot\n    w = np.random.rand(4); w[0]=0\n    qdot = 0.5 * prod(q, w)\n    qc = conj(q)\n    w_ = 2 * prod(qc, qdot)\n    print('w - w_ = ', np.linalg.norm(w-w_))\n\n    phi_, theta_, psi_ = quat2euler(q)\n    print(\"phi - phi_ = \", phi - phi_)\n    print(\"theta - theta_ = \", theta - theta_)\n    print(\"psi - psi_ = \", psi - psi_)\n\n\n    ", "meta": {"hexsha": "78cbec5a7ed09cacd7de1c0f896c4a34db98abd5", "size": 3193, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/dirk_drone_code/rotations.py", "max_stars_repo_name": "donnel2-cooper/drone_control", "max_stars_repo_head_hexsha": "3bb3a1c1f768916ac41d4b78692e2edab0776c07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lectures/dirk_drone_code/rotations.py", "max_issues_repo_name": "donnel2-cooper/drone_control", "max_issues_repo_head_hexsha": "3bb3a1c1f768916ac41d4b78692e2edab0776c07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lectures/dirk_drone_code/rotations.py", "max_forks_repo_name": "donnel2-cooper/drone_control", "max_forks_repo_head_hexsha": "3bb3a1c1f768916ac41d4b78692e2edab0776c07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0593220339, "max_line_length": 93, "alphanum_fraction": 0.5167554024, "include": true, "reason": "import numpy", "num_tokens": 1145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191309994467, "lm_q2_score": 0.8918110468756548, "lm_q1q2_score": 0.8519641543169574}}
{"text": "from sympy import *\nfrom difference_quotient import difference_quotient\nimport numpy as np\n\n\ndef spline3_interpolate(points: list, simplify_result=True):\n    \"\"\"三弯矩法插值\n\n    三弯矩法进行三次样条插值。使用自由边界条件。\n\n    Args:\n        points: list, [(x1, y1), (x2, y2), ..., (xn, yn)]\n        simplify_result: bool, 化简最终结果, default True\n\n    Returns: \n        L: sympy Piecewise object of Symbol('x'), 插值多项式 $L(x)$\n    \"\"\"\n    # 排序给定的点\n    ps = sorted(points, key=lambda p: p[0])\n    n = len(points)\n\n    # points to a function\n    _f_dict = dict(ps)\n\n    def f(x):\n        return _f_dict[x]\n\n    # $h_k = x_{k+1} - x_k$\n    def h(k):\n        return ps[k+1][0] - ps[k][0]\n\n    hks = [h(0)]\n\n    # 用方程 D * M = d 解出 M\n\n    D = np.zeros((n, n))\n    d = np.zeros(n)\n\n    for k in range(1, n-1):\n        # $h_k$, $h_{k-1}$\n        hks.append(h(k))\n        hk, hks1 = hks[k], hks[k-1]\n\n        # $\\mu_k$ -> mu, $\\lambda_k$ -> ld\n        _fra = hks1 + hk\n        mu = hks1 / _fra\n        ld = hk / _fra\n\n        # $\\mu_kM_{k-1}+2M_k+\\lambda_kM_{k+1} = d_k$\n        D[k, k-1] = mu\n        D[k, k] = 2\n        D[k, k+1] = ld\n        d[k] = 6 * difference_quotient(f, [ps[k-1][0], ps[k][0], ps[k+1][0]])\n\n    # 边界条件\n    # Natural Boundary\n    D[0, 0] = 1\n    D[n-1, n-1] = 1\n\n    d[0] = 0\n    d[n-1] = 0\n\n    # 解出 M\n    M = np.linalg.solve(D, d)\n\n    # 插值函数\n    piecewises = []\n    for k in range(n-1):\n        s = M[k] * (ps[k+1][0] - _x) ** 3 / (6 * hks[k])\n        s += M[k+1] * (_x - ps[k][0]) ** 3 / (6 * hks[k])\n        s += (ps[k][1] - M[k] * hks[k]**2 / 6) * (ps[k+1][0] - _x) / hks[k]\n        s += (ps[k+1][1] - M[k+1] * hks[k]**2 / 6) * (_x - ps[k][0]) / hks[k]\n        if simplify_result:\n            s = simplify(s)\n        piecewises.append((s, And(_x >= ps[k][0], _x <= ps[k+1][0])))\n\n    return Piecewise(*piecewises)\n", "meta": {"hexsha": "822083e82e85e31ed07c8dafd4f94217560447fc", "size": 1803, "ext": "py", "lang": "Python", "max_stars_repo_path": "ex3/src/spline3_interpolate.py", "max_stars_repo_name": "cdfmlr/NumericalAnalysis", "max_stars_repo_head_hexsha": "b752af60c1f3202d53cc3c76e66419a885250ed9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex3/src/spline3_interpolate.py", "max_issues_repo_name": "cdfmlr/NumericalAnalysis", "max_issues_repo_head_hexsha": "b752af60c1f3202d53cc3c76e66419a885250ed9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex3/src/spline3_interpolate.py", "max_forks_repo_name": "cdfmlr/NumericalAnalysis", "max_forks_repo_head_hexsha": "b752af60c1f3202d53cc3c76e66419a885250ed9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-15T01:34:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-15T01:34:35.000Z", "avg_line_length": 23.1153846154, "max_line_length": 77, "alphanum_fraction": 0.462562396, "include": true, "reason": "import numpy,from sympy", "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191348157373, "lm_q2_score": 0.8918110418436166, "lm_q1q2_score": 0.8519641529131651}}
{"text": "import numpy as np\n# Setting the random seed, feel free to change it and see different solutions.\nnp.random.seed(42)\n\ndef sigmoid(x):\n    return 1/(1+np.exp(-x))\ndef sigmoid_prime(x):\n    return sigmoid(x)*(1-sigmoid(x))\ndef prediction(X, W, b):\n    return sigmoid(np.matmul(X,W)+b)\ndef error_vector(y, y_hat):\n    return [-y[i]*np.log(y_hat[i]) - (1-y[i])*np.log(1-y_hat[i]) for i in range(len(y))]\ndef error(y, y_hat):\n    ev = error_vector(y, y_hat)\n    return sum(ev)/len(ev)\n\ndef dErrors(X, y, y_hat):\n    dErrs = []\n    yDiff = [(y_hat[i] - y[i]) for i in range(len(y))]\n    # With respect to all wi\n    for j in range(len(X[0])):\n        dErrs.append([X[i][j] * yDiff[i]  for i in range(len(y))])\n    # with respect to b\n    dErrs.append(yDiff)\n    return dErrs\n\ndef gradientDescentStep(X, y, W, b, learn_rate = 0.01):\n    y_hat = prediction(X,W,b)\n    e = sum(error_vector(y, y_hat))\n    gradient = dErrors(X, y, y_hat)\n    W = [W[i]-sum(gradient[i]) * learn_rate for i in range(len(W))]\n    b -= sum(gradient[2])*learn_rate\n    return W, b, e\n\n# This function runs the perceptron algorithm repeatedly on the dataset,\n# and returns a few of the boundary lines obtained in the iterations,\n# for plotting purposes.\n# Feel free to play with the learning rate and the num_epochs,\n# and see your results plotted below.\ndef trainLR(X, y, learn_rate = 0.01, num_epochs = 100):\n    x_min, x_max = min(X.T[0]), max(X.T[0])\n    y_min, y_max = min(X.T[1]), max(X.T[1])\n    # Initialize the weights randomly\n    W = np.array(np.random.rand(2,1))*2 -1\n    b = np.random.rand(1)[0]*2 - 1\n    # These are the solution lines that get plotted below.\n    boundary_lines = []\n    errors = []\n    for i in range(num_epochs):\n        # In each epoch, we apply the gradient descent step.\n        W, b, error = gradientDescentStep(X, y, W, b, learn_rate)\n        boundary_lines.append((-W[0]/W[1], -b/W[1]))\n        errors.append(error)\n    return boundary_lines, errors\n", "meta": {"hexsha": "17f98a030909298991ac9c64e188ff53a6fb99bd", "size": 1956, "ext": "py", "lang": "Python", "max_stars_repo_path": "logistic_regression.py", "max_stars_repo_name": "sabau/machine-learning", "max_stars_repo_head_hexsha": "36b87dfae39c2df18cfc90029dbce94d4478e735", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "logistic_regression.py", "max_issues_repo_name": "sabau/machine-learning", "max_issues_repo_head_hexsha": "36b87dfae39c2df18cfc90029dbce94d4478e735", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logistic_regression.py", "max_forks_repo_name": "sabau/machine-learning", "max_forks_repo_head_hexsha": "36b87dfae39c2df18cfc90029dbce94d4478e735", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5636363636, "max_line_length": 88, "alphanum_fraction": 0.6370143149, "include": true, "reason": "import numpy", "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191284552528, "lm_q2_score": 0.8918110440002044, "lm_q1q2_score": 0.8519641493010444}}
{"text": "\"\"\"\nAuthors: Luiz Gustavo Mugnaini Anselmo (nUSP: 11809746)\n         Victor Manuel Dias Saliba     (nUSP: 11807702)\n         Luan Marc Suquet Camargo      (nUSP: 11809090)\n\nComputacao III (CCM): Ep 3 QR factorization\n\"\"\"\nimport math\nimport numpy as np\n\n\nclass RealSpace:\n    \"\"\"Real Space methods\"\"\"\n\n    @classmethod\n    def inner_product(cls, v: np.ndarray, u: np.ndarray) -> float:\n        \"\"\"Standard real dot product `v` * `u`\"\"\"\n        if v.size != u.size:\n            raise Exception(\"Vectors have different length\")\n        return sum(x * y for x, y in zip(v, u))\n\n    @classmethod\n    def norm(cls, v: np.ndarray) -> float:\n        \"\"\"Norm of given vector `v`\"\"\"\n        return math.sqrt(cls.inner_product(v, v))\n\n    @classmethod\n    def distance(cls, v: np.ndarray, u: np.ndarray) -> float:\n        \"\"\"Distance between vectors `v` and `u`\"\"\"\n        return math.sqrt(cls.inner_product(v, u))\n\n    @classmethod\n    def proj(cls, v: np.ndarray, u: np.ndarray) -> np.ndarray:\n        \"\"\"Projection of `v` in `u`\"\"\"\n        return cls.inner_product(u, v) / cls.inner_product(u, u) * u\n\n    @classmethod\n    def gram_schmidt(cls, set: list[np.ndarray]) -> list[np.ndarray]:\n        \"\"\"Gram-Schmidt algorithm.\n        Takes a list of vectors (`set`) and applies the method of Gram-Schmidt,\n        orthonormalizing `set`.\n        \"\"\"\n        # Orthogonalization algorithm\n        ortho: list[np.ndarray] = [np.copy(set[0]) / cls.norm(set[0])]\n        for j in range(1, len(set)):\n            q = np.copy(set[j])\n            for i in range(j):\n                r = cls.inner_product(set[j], ortho[i])\n                q -= r * ortho[i]\n\n            # Check if the list is LI and, if so, append the normalized vector\n            norm = cls.norm(q)\n            if norm == 0:\n                raise Exception(\"The list of vectors is linearly dependent.\")\n            ortho.append(q / norm)\n\n        return ortho\n", "meta": {"hexsha": "c448c3cf98c17ccfed371d866ed5a7af32c024d6", "size": 1911, "ext": "py", "lang": "Python", "max_stars_repo_path": "numerical/matrix/linear_space.py", "max_stars_repo_name": "luizmugnaini/numerical", "max_stars_repo_head_hexsha": "316ef5207a49aa5159073e6d18a0f351485f6167", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numerical/matrix/linear_space.py", "max_issues_repo_name": "luizmugnaini/numerical", "max_issues_repo_head_hexsha": "316ef5207a49aa5159073e6d18a0f351485f6167", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical/matrix/linear_space.py", "max_forks_repo_name": "luizmugnaini/numerical", "max_forks_repo_head_hexsha": "316ef5207a49aa5159073e6d18a0f351485f6167", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-31T14:15:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T15:21:31.000Z", "avg_line_length": 32.9482758621, "max_line_length": 79, "alphanum_fraction": 0.5735217164, "include": true, "reason": "import numpy", "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436405, "lm_q2_score": 0.8918110375304408, "lm_q1q2_score": 0.8519641476582358}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import make_blobs\n\n\nclass KMeans:\n    \n    def __init__(self , k , nbr_iterations = 500):\n        self.k = k\n        self.nbr_iterations = nbr_iterations\n        self.clusters = [[] for i in range(self.k)]\n        self.centers = []\n   \n    def fit(self , x):\n        self.x = x\n        self.nbr_samples , self.nbr_features = x.shape\n        \n        #initialize The Centers Randomly \n        centers_indexes = np.random.choice(self.nbr_samples , self.k , replace = False)\n        self.centers = [self.x[index] for index in centers_indexes]\n        \n        for i in range(self.nbr_iterations):\n            \n            #Assign Samples to the clossest Center\n            self.clusters = self.CreateClusters(self.centers)\n            \n            oldCenters = self.centers\n            self.centers = self.UpdateCenters(self.clusters)\n            \n            #Check if The Stoping Criteria is True\n            if self.StopingCriteria(oldCenters , self.centers):\n                break\n            \n    def CreateClusters(self , centers):\n        CurrentClusters = [[] for i in range(self.k)]\n        \n        for index , sample in enumerate(self.x):\n            clossestCenter = self.clossest_center(sample , centers)\n            CurrentClusters[clossestCenter].append(index)\n        return CurrentClusters    \n           \n    def clossest_center(self , sample , centers):\n        distances = [self.euclideanDistance(sample, center) for center in centers]\n        return np.argmin(distances)\n            \n    def UpdateCenters(self , clusters):\n        newCenters = np.zeros((self.k , self.nbr_features))\n        for index , cluster in enumerate(clusters):\n            center = np.mean(self.x[cluster] , axis = 0)\n            newCenters[index] = center\n        return newCenters    \n        \n    def StopingCriteria(self , oldCenters , newCenters):\n        distances = [self.euclideanDistance(oldCenters[i], newCenters[i]) for i in range(self.k)]\n        return sum(distances) == 0\n    \n    def getClusters(self):\n        labels = np.empty(self.nbr_samples)\n        \n        for index , cluster in enumerate(self.clusters):\n            for sampleIndex in cluster:\n                labels[sampleIndex] = index\n        return labels\n    \n    def displayTheResult(self):\n        \n        fig, ax = plt.subplots(figsize=(12, 8))\n        #display The Clusters\n        for _ , index in enumerate(self.clusters):\n            points = self.x[index]\n            ax.scatter(points[:,0] , points[:,1])\n        #display The Centers    \n        for center in self.centers:\n            ax.scatter(center[0] , center[1], marker=\"x\", color=\"black\", linewidth=5)\n        plt.title(\"KMeans\")    \n        plt.show()         \n            \n    def euclideanDistance(self , x1 , x2):\n        return np.sqrt(np.sum( (x1 - x2)**2 ))     \n    \n#Test K-Means\ndef accuracy(y_true , y_pred):\n    return np.sum(y_true == y_pred) / len(y_true)\n\nx , y = make_blobs(n_samples=100 , n_features=2 , centers=3 , random_state=0)\n\nnbr_classes = len(np.unique(y))\nK_means = KMeans(k = nbr_classes)\nK_means.fit(x)\ny_pred = K_means.getClusters()\nK_means.displayTheResult()\nprint(\"KMeans Accuracy : \",accuracy(y, y_pred))", "meta": {"hexsha": "42e44119f41c371a5b32f110efbef0d1bd006f94", "size": 3249, "ext": "py", "lang": "Python", "max_stars_repo_path": "K_Means/Kmeans.py", "max_stars_repo_name": "AnasBrital98/Most-Common-Algorithms-of-Machine-learning", "max_stars_repo_head_hexsha": "f6dd38c7c5e354a0d792ecbaae0eb25b00709783", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-07T16:01:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-07T16:01:00.000Z", "max_issues_repo_path": "K_Means/Kmeans.py", "max_issues_repo_name": "AnasBrital98/Most-Common-Algorithms-of-Machine-learning", "max_issues_repo_head_hexsha": "f6dd38c7c5e354a0d792ecbaae0eb25b00709783", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "K_Means/Kmeans.py", "max_forks_repo_name": "AnasBrital98/Most-Common-Algorithms-of-Machine-learning", "max_forks_repo_head_hexsha": "f6dd38c7c5e354a0d792ecbaae0eb25b00709783", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3152173913, "max_line_length": 97, "alphanum_fraction": 0.5961834411, "include": true, "reason": "import numpy", "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191309994467, "lm_q2_score": 0.8918110360927155, "lm_q1q2_score": 0.8519641440158091}}
{"text": "import numpy as np\nimport matplotlib.pylab as plt\n\n# sigmoid function used broadcast for numpy array.\ndef sigmoid(x):\n    return 1 / (1 + np.exp(-x))\n\na = np.array([-1.0, 1.0, 2.0])\n\nprint(sigmoid(a))\n\n# 이와 같은 시그모이드 함수를 그래프로 나타내 그 변화를 살펴보자.\n\nx = np.arange(-5.0, 5.0, 0.1)\ny = sigmoid(x)\nplt.plot(x, y)\nplt.ylim(-0.1, 1.1) # y축의 범위 지정\nplt.show()\n\n", "meta": {"hexsha": "5570a4846d2cbf52839bf15703bbbeddc5b890b3", "size": 346, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine_learning/acting/sigmoidTest.py", "max_stars_repo_name": "Heahr/training", "max_stars_repo_head_hexsha": "7cba490bc55d5b5bedaf5a6f781fddab1f0859a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "machine_learning/acting/sigmoidTest.py", "max_issues_repo_name": "Heahr/training", "max_issues_repo_head_hexsha": "7cba490bc55d5b5bedaf5a6f781fddab1f0859a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "machine_learning/acting/sigmoidTest.py", "max_forks_repo_name": "Heahr/training", "max_forks_repo_head_hexsha": "7cba490bc55d5b5bedaf5a6f781fddab1f0859a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3, "max_line_length": 50, "alphanum_fraction": 0.6329479769, "include": true, "reason": "import numpy", "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191309994468, "lm_q2_score": 0.8918110346549902, "lm_q1q2_score": 0.8519641426423228}}
{"text": "# To add a new cell, type '#%%'\n# To add a new markdown cell, type '#%% [markdown]'\n#%%\nfrom IPython import get_ipython\n\n\n#%%\nimport numpy as np\n\n\n#%%\nlist1 = [1, 3, 4, 5]\na = np.array(list1)\na\n\n\n#%%\ntype(a)\n\n\n#%%\na.dtype\n\n\n#%%\na.size\n\n\n#%%\na.ndim\n\n\n#%%\na.shape\n\n\n#%%\nb = np.array([23, 7.4, 11, 98, 54, 23.67])\ntype(b)\n\n\n#%%\nb.ndim\n\n\n#%%\nb.size\n\n\n#%%\nb.shape\n\n#%% [markdown]\n# ## Indexing and Slicing\n\n#%%\nc = np.array([22, 56, 98, 54, 21])\nc\n\n\n#%%\n#assign 56 to 34\nc[1] = 34\nc\n\n\n#%%\n# slicing\nd = c[1:3]\nd\n\n\n#%%\nd[0:2] = 66, 77\nd\n\n#%% [markdown]\n# ## Basic operation\n#%% [markdown]\n# ### Vector Addition and subtraction\n\n#%%\nv1 = np.array([0, 1])\nv2 = np.array([1, 0])\nv1 + v2\n\n\n#%%\n## anothr way\nu = np.array([1, 0])\nv = np.array([0, 1])\nz = []\n\nfor n,m in zip(u, v):\n    z.append(n+m)\nz\n\n#%% [markdown]\n# ### Array multiplication with scaler\n\n#%%\ny = np.array([1, 2])\nz = 2*y\nz\n\n\n#%%\n## another way\nzz = []\nfor n in y:\n    zz.append(2*n)\nzz\n\n#%% [markdown]\n# ### Product of two vectors\n\n#%%\ntt1 = np.array([1, 2])\ntt2 = np.array([3, 4])\n\ntt = tt1 * tt2\ntt\n\n\n#%%\n## another way\ntt3 = []\nfor n,m in zip(tt1, tt2):\n    tt3.append(n*m)\ntt3\n\n#%% [markdown]\n# ### Dot product\n\n#%%\nff1 = np.array([1, 2])\nff2 = np.array([3, 4])\n\nresult = np.dot(ff1, ff2)\nresult\n\n\n#%%\n## another way\nresult2 = []\nfor n,m in zip(ff1, ff2):\n    result2.append(np.dot(n, m))\nresult2\n\n#%% [markdown]\n# ### Adding constant to numpy array\n#%% [markdown]\n# \n\n#%%\ngg = np.array([2, 3, 4, -9])\nres1 = gg + 1\nres1\n\n#%% [markdown]\n# ## Universal Function\n\n#%%\nfg = np.array([3, 5, 7, 9])\n\n\n#%%\nfg.mean()\n\n\n#%%\nfg.max()\n\n\n#%%\nfg.min()\n\n\n#%%\n## pi value\nnp.pi\n\n\n#%%\n# np.sin(x)\n# \n#\n\n\n#%%\n# starting value = -2 and ending value= 2 total values 5\nnp.linspace(-2, 2, num=5)\n\n\n#%%\nnp.linspace(-2, 2, num=9)\n\n\n#%%\n## plotting mathamatical function\nx = np.linspace(0, 2*np.pi, 50)\nx\n\n\n#%%\ny = np.sin(x)\ny\n\n\n#%%\nimport matplotlib.pyplot as plt\n\n\n#%%\nget_ipython().run_line_magic('matplotlib', 'inline')\nplt.plot(x, y)\n#first input x is horizontal axis\n#second element y is vertical axis\n\n#%% [markdown]\n# # Two Dimenstional Array\n\n#%%\na = np.array([[1, 2, 3], [11, 12, 13], [21, 22, 23], [31, 32, 33]])\n\n\n#%%\na.ndim\n\n\n#%%\na.shape\n\n\n#%%\na.size\n\n\n#%%\n# to access first row 3rd element\na[0][2]\n\n\n#%%\n# alternate\na[0, 2]\n\n\n#%%\n## slicing in numpy array\na[0, 0:2]\n\n\n#%%\n## adding as matrix\nas1 = np.array([\n    [1, 2, 3, 4],\n    [2, 4, 6, 8],\n    [1, 3, 5, 7]\n])\nas2 = np.array([\n    [1, 2, 3, 4],\n    [2, 4, 6, 8],\n    [1, 3, 5, 7]\n])\n\n\n#%%\nas1 + as2\n\n\n#%%\nas1.ndim\n\n\n#%%\nas1\n\n\n#%%\nas1 * 2\n\n\n#%%\n# matrix multiplication is littile bit complex\n# matrix A rows must b equal to matrix B column\n# each element of A is multiply with all element of B column\n\n\n#%%\ndfA = np.array([[1, 2, 3], [2, 0, 1]])\ndfB = np.array([[1, 2], [0, 1], [3, 4]])\n\n\n#%%\ndfZ = np.dot(dfA, dfB)\n\n\n#%%\ndfZ\n\n\n#%%\nX=np.array([[1,0],[0,1]])\nY=np.array([[2,2],[2,2]])\nZ=np.dot(X,Y)\nZ\n\n\n#%%\n\n\n\n", "meta": {"hexsha": "ac8b3f755fef17d4405fe7f4c1d7b083c658c85f", "size": 2916, "ext": "py", "lang": "Python", "max_stars_repo_path": "Untitled-1.py", "max_stars_repo_name": "shkhaider2015/PIAIC-QUARTER-2", "max_stars_repo_head_hexsha": "2b6ef1c8d75f9f52b9da8e735751f5f80c76b227", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Untitled-1.py", "max_issues_repo_name": "shkhaider2015/PIAIC-QUARTER-2", "max_issues_repo_head_hexsha": "2b6ef1c8d75f9f52b9da8e735751f5f80c76b227", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Untitled-1.py", "max_forks_repo_name": "shkhaider2015/PIAIC-QUARTER-2", "max_forks_repo_head_hexsha": "2b6ef1c8d75f9f52b9da8e735751f5f80c76b227", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 9.2866242038, "max_line_length": 67, "alphanum_fraction": 0.5253772291, "include": true, "reason": "import numpy", "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.9252299493606285, "lm_q1q2_score": 0.8519421791629807}}
{"text": "from __future__ import division\nimport numpy\nimport scipy.integrate\nimport matplotlib.pyplot as pyplot\n\nUSER = 'Maciej Grabias'\nUSER_ID = 'njgh39'\n\nr = 0.15 # radius of the cannonball in meters\nrho_iron =  7874.00 # density of iron in kg m-3\ng =  9.81 # acceleration due to gravity in ms-2\nkappa =  0.47 # drag coefficient of a sphere\nrho_air =  1.23 # density of air in kg m-3\nt1 =  25.00 # end time for our ODE integration in s\nv0 = 125.00 # launch speed in m s-1\nn_panels =  400 # the number of panels to use\n\n# cross section area & mass of cannonball determined using above\n\narea = numpy.pi* r**2\nmass = rho_iron * (4/3) * numpy.pi * r**3\n\n# define the function\ndef f((x, y, vx, vy),t):\n\n    # gravitational forces\n    Fx_grav = 0\n    Fy_grav = - mass * g\n\n    # drag forces\n    Fx_drag = - kappa * rho_air * area * v0 * vx\n    Fy_drag = - kappa * rho_air * area * v0 * vy\n\n\n    d_x = vx # dx/dt\n    d_y = vy # dy/dt\n    d_vx =  Fx_drag / mass # dvx/dt\n    d_vy = (Fy_drag + Fy_grav) / mass # dvy/dt\n\n    return numpy.array((d_x, d_y, d_vx, d_vy))\n\n\ndef solve_euler(state, t1, n_panel):\n\n    history = numpy.zeros((n_panels, len(state)))\n    dt = t1 / n_panels\n\n    # integrate with Euler method\n    for i in range(n_panels):\n        history[i] = state\n        state = state + f(state, dt * i) * dt\n    return history\n\n# define timebase\ntimebase = numpy.arange(0, t1, t1 / n_panels)\n\ndef trim_trajectory(values):\n\n    # process trajectory to terminate when below y = 0\n    for i in range(len(values) - 1):\n        x0, y0, vx0, vy0 = values[i]\n        x1, y1, vx1, vy1 = values[i + 1]\n        if y0 < 0: return values[:i]\n    return values\n\nproj_range = []\nthetas = range(5,90,5)\n\npyplot.subplot(211)\n\nfor theta in thetas:\n\n    vx, vy = numpy.cos(numpy.deg2rad(theta)) * v0, numpy.sin(numpy.deg2rad(theta)) * v0\n    initial_conditions = (0, 0, vx, vy)\n\n    values_scipy = scipy.integrate.odeint(f, initial_conditions, timebase)\n    values_euler = solve_euler(initial_conditions, t1, n_panels)\n    values_scipy = trim_trajectory(values_scipy)\n    values_euler = trim_trajectory(values_euler)\n\n    # calculate range\n\n    x_first, y_first, vx_first, vy_first = values_scipy[0]\n    x_final, y_final, vx_final, vy_final = values_scipy[-1]\n\n    rnge = x_final - x_first\n\n    proj_range.append(rnge)\n\n    # trajectory for scipy integrate\n    x_scipy = values_scipy[:, 0]\n    y_scipy = values_scipy[:, 1]\n\n    # trajectory for Euler integrate\n    x_euler = values_euler[:,0]\n    y_euler = values_euler[:,1]\n\n    # plot trajectories\n    pyplot.plot(x_scipy, y_scipy, color = 'grey', label = \"Odeint\")\n    pyplot.plot(x_euler, y_euler, color = 'blue', linestyle = '--', label = \"Euler\")\n    pyplot.title(\"Trajectories for Euler & Odeint Methods\")\n    pyplot.xlabel(\"X coordinate\")\n    pyplot.ylabel(\"Y coordinate\")\n\npyplot.legend((\"Odeint\", \"Euler\"))\n\n# plot range VS launch angle\npyplot.subplot(212)\npyplot.plot(thetas, proj_range, color = 'red')\npyplot.title(\"Range VS Launch Angle\")\npyplot.xlabel(\"Launch Angle, deg\")\npyplot.ylabel(\"Range, m\")\n\npyplot.show()\n\nANSWER1 = \"\"\" The angle from the horizontal for maximum range under these\nconditions is 40 degrees.\"\"\"\nANSWER2 = \"\"\" The angle decreases with increasing air density \"\"\"\n", "meta": {"hexsha": "36ca9f576d91b4c1ad2ec163deb4742ba11b9cc9", "size": 3225, "ext": "py", "lang": "Python", "max_stars_repo_path": "cp_4.py", "max_stars_repo_name": "M-Grabias/uni_codes", "max_stars_repo_head_hexsha": "ff117894c7d49ec13470c551ef6929782a154d68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cp_4.py", "max_issues_repo_name": "M-Grabias/uni_codes", "max_issues_repo_head_hexsha": "ff117894c7d49ec13470c551ef6929782a154d68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cp_4.py", "max_forks_repo_name": "M-Grabias/uni_codes", "max_forks_repo_head_hexsha": "ff117894c7d49ec13470c551ef6929782a154d68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1008403361, "max_line_length": 87, "alphanum_fraction": 0.6657364341, "include": true, "reason": "import numpy,import scipy", "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377320263432, "lm_q2_score": 0.8887588045416601, "lm_q1q2_score": 0.8519088488238069}}
{"text": "# solutions.py\n\"\"\"Volume 1, Lab 16: Importance Sampling and Monte Carlo Simulations.\nSolutions file. Written by Tanner Christensen, Winter 2016.\n\"\"\"\n\nfrom __future__ import division\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats as stats\n\ndef prob1(n):\n    \"\"\"Approximate the probability that a random draw from the standard\n    normal distribution will be greater than 3.\"\"\"\n    h = lambda x : x > 3\n    X = np.random.randn(n)\n    return 1/n * np.sum(h(X))\n\ndef prob2():\n    \"\"\"Answer the following question using importance sampling: \n            A tech support hotline receives an average of 2 calls per \n            minute. What is the probability that they will have to wait \n            at least 10 minutes to receive 9 calls?\n    Returns:\n        IS (array) - an array of estimates using \n            [5000, 10000, 15000, ..., 500000] as number of \n            sample points.\"\"\"\n    h = lambda y : y > 10\n    f = lambda y : stats.gamma(a=9,scale=0.5).pdf(y)\n    g = lambda y : stats.norm(loc=12,scale=2).pdf(y)\n    num_samples = np.arange(5000,505000,5000)\n    IS = []\n    for n in num_samples:\n        Y = np.random.normal(12,2,n)\n        approx = 1./n*np.sum(h(Y)*f(Y)/g(Y))\n        IS.append(approx)\n    IS = np.array(IS)\n    return IS\n\ndef prob3():\n    \"\"\"Plot the errors of Monte Carlo Simulation vs Importance Sampling\n    for the prob2().\"\"\"\n    h = lambda x : x > 10\n    MC_estimates = []\n    for N in xrange(5000,505000,5000):\n        X = np.random.gamma(9,scale=0.5,size=N)\n        MC = 1./N*np.sum(h(X))\n        MC_estimates.append(MC)\n    MC_estimates = np.array(MC_estimates)\n\n    IS_estimates = prob2()\n    \n    actual = 1 - stats.gamma(a=9,scale=0.5).cdf(10)\n\n    MC_errors = np.abs(MC_estimates - actual)\n    IS_errors = np.abs(IS_estimates - actual)\n    \n    x = np.arange(5000,505000,5000)\n    plt.plot(x, MC_errors, color='r', label=\"Monte Carlo\")\n    plt.plot(x, IS_errors, color='b', label=\"Importance Sampling\")\n    plt.legend()\n    plt.show()\n    \ndef prob4():\n    \"\"\"Approximate the probability that a random draw from the\n    multivariate standard normal distribution will be less than -1 in \n    the x-direction and greater than 1 in the y-direction.\"\"\"\n    h = lambda y : y[0] < -1 and y[1] > 1\n    f = lambda y : stats.multivariate_normal(np.zeros(2), np.eye(2)).pdf(y)\n    g = lambda y : stats.multivariate_normal(np.array([-1,1]), np.eye(2)).pdf(y)\n    \n    n = 10**4\n    Y = np.random.multivariate_normal(np.array([-1,1]), np.eye(2), size=n)\n    hh = np.apply_along_axis(h, 1, Y)\n    ff = np.apply_along_axis(f, 1, Y)\n    gg = np.apply_along_axis(g, 1, Y)\n    approx = 1./n*np.sum(hh*ff/gg)\n\n    return approx\n    \nif __name__ == \"__main__\":\n    import numpy as np\n    print prob4()\n\n    n = 10**6\n    h = lambda y : y[0] < -1 and y[1] > 1\n    X = np.random.multivariate_normal(np.zeros(2),np.eye(2),n)\n    print 1/n * np.sum(np.apply_along_axis(h, 1, X))\n    \n    \n", "meta": {"hexsha": "bbda1b314337876c5a58c69bb2538f0e6c4297d4", "size": 2927, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol1B/MonteCarlo2-Sampling/solutions.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vol1B/MonteCarlo2-Sampling/solutions.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vol1B/MonteCarlo2-Sampling/solutions.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 32.5222222222, "max_line_length": 80, "alphanum_fraction": 0.6204304749, "include": true, "reason": "import numpy,import scipy", "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377237352755, "lm_q2_score": 0.8887587993853655, "lm_q1q2_score": 0.8519088365125446}}
{"text": "# -*- coding: utf-8 -*-\r\nimport numpy as np\r\n\r\n\r\n\r\n\"\"\"\r\nFuncție care caută intervalele pe care funcția are o soluție.\r\nf(a) * f(b) < 0 -> EXISTENȚA\r\n\"\"\"\r\ndef cauta_intervale(f, a, b, n):\r\n    \"\"\"\r\n    Parameters\r\n    ----------\r\n    f : funcția asociată ecuației f(x)=0.\r\n    a : capătul din stânga interval.\r\n    b : capătul din dreapta interval.\r\n    n : nr de subintervale în care împărțim intervalul global (a, b).\r\n\r\n    Returns\r\n    -------\r\n    Matricea 'intervale' cu 2 linii; prima linie -> capăt st interval curent\r\n    si a doua linie -> capat dr\r\n    si un nr de coloane = nr radacini\r\n    \"\"\"\r\n    \r\n    x = np.linspace(a, b, n+1)   #returnează n+1 numere, situate la distanțe egale, din cadrul intervalului [a, b]\r\n    for i in range(len(x)):   #range: for i = 0, len(x); i++\r\n        if(f(x[i]) == 0):     #capetele intervalelor mele nu au voie să fie 0; tb să avem soluțiile în intervale, nu la capete\r\n            print(\"Schimba nr de Intervale\")\r\n            exit(0)\r\n\r\n    matrice = np.zeros((2, 1000))  #returnează un nou vector plin de 0; pt că am (2, 1000) -> matrice cu 2 rânduri și 1000 coloane\r\n    z = 0\r\n    for i in range(n):\r\n        if f(x[i]) * f(x[i+1]) < 0:  #existență soluție\r\n            matrice[0][z] = x[i]\r\n            matrice[1][z] = x[i + 1]\r\n            z += 1 \r\n    \r\n    matrice_finala = matrice[:, 0:z]   #iei ambele 2 linii și doar coloanele de la 0 la z (numărat mai sus)\r\n    return matrice_finala\r\n\r\n\r\n\r\n\"\"\"\r\n    Funcție care implementează algoritmul metodei bisecției.\r\n\"\"\"\r\ndef bisectie(f, xmin, xmax, eps):\r\n    \"\"\"\r\n    Parameters\r\n    ----------\r\n    f : f(x) = 0.\r\n    xmin, xmas: capete intervale.\r\n    eps : toleranța / eroarea (epsilon).\r\n\r\n    Returns\r\n    -------\r\n    Soluția aproximativă, dar și numărul de iterații N necesar pt a obține soluția cu eroarea eps.\r\n    \"\"\"\r\n    \r\n    c = (xmin + xmax) / 2\r\n    N = np.floor(np.log2((xmax-xmin)/eps))  #floor: cel mai mare int, dar mai mic decât val. mea\r\n    for i in range(int(N)):\r\n        if f(c) == 0:\r\n            break                           #am gasit soluția\r\n        elif f(xmin) * f(c) < 0:\r\n            xmax = c\r\n        elif f(xmin) * f(c) > 0:\r\n            xmin = c\r\n        \r\n        c = (xmin + xmax) / 2\r\n    return c, N\r\n\r\n\r\n\r\n\"\"\"\r\n    Funcție care implementează algoritmul metodei bisecției.\r\n    ---> Pt Lab2.Ex4.\r\n\"\"\"\r\ndef bisectie2(f, xmin, xmax, eps):\r\n    \r\n    x_old = (xmin + xmax) / 2\r\n    k = 1\r\n    while True:\r\n        if f(x_old) == 0:\r\n            x_new = x_old      \r\n            break                    \r\n        elif f(xmin) * f(x_old) < 0:\r\n            xmax = x_old\r\n        elif f(xmin) * f(x_old) > 0:\r\n            xmin = x_old\r\n        \r\n        x_new = (xmin + xmax) / 2\r\n        k += 1\r\n        if abs(x_new - x_old) / abs(x_old) < eps:\r\n            break\r\n        x_old = x_new\r\n        \r\n    return x_new, k\r\n\r\n\r\n\r\n\"\"\"\r\n    Metoda Newton-Raphson\r\n\"\"\"       \r\ndef NewtonRap(f, df, x0, eps):\r\n    \"\"\"\r\n    Parameters\r\n    ----------\r\n    f : functia pt care cautam solutia f(x) = 0.\r\n    df : derivata functiei.\r\n    x0 : valoare de pornire.\r\n    eps : epsilon / toleranta.\r\n\r\n    Returns\r\n    -------\r\n    solutia (xk), nr de iteratii (N).\r\n    \"\"\"\r\n    \r\n    x_old = x0\r\n    N = 1\r\n    while True:\r\n        #Calculăm noua iteratie\r\n        x_new = x_old - (f(x_old) / df(x_old))\r\n        N += 1\r\n        if(abs(x_new - x_old) / abs(x_old) < eps):\r\n            break\r\n        x_old = x_new\r\n    \r\n    return x_new, N   \r\n            \r\n        \r\n    \r\n    \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            ", "meta": {"hexsha": "1703b79125f2114ffffe61026764b59d74af14ee", "size": 3817, "ext": "py", "lang": "Python", "max_stars_repo_path": "Calcul Numeric (CN)/Laborator/Laborator 1, 2/metode_numerice_ecuatii_algebrice.py", "max_stars_repo_name": "DLarisa/FMI-Materials-BachelorDegree", "max_stars_repo_head_hexsha": "138e1a20bc33617772e9cd9e4432fbae99c0250c", "max_stars_repo_licenses": ["W3C"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-02-12T02:05:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T14:44:43.000Z", "max_issues_repo_path": "Calcul Numeric (CN)/Laborator/Laborator 1, 2/metode_numerice_ecuatii_algebrice.py", "max_issues_repo_name": "DLarisa/FMI-Materials-BachelorDegree-UniBuc", "max_issues_repo_head_hexsha": "138e1a20bc33617772e9cd9e4432fbae99c0250c", "max_issues_repo_licenses": ["W3C"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Calcul Numeric (CN)/Laborator/Laborator 1, 2/metode_numerice_ecuatii_algebrice.py", "max_forks_repo_name": "DLarisa/FMI-Materials-BachelorDegree-UniBuc", "max_forks_repo_head_hexsha": "138e1a20bc33617772e9cd9e4432fbae99c0250c", "max_forks_repo_licenses": ["W3C"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4679487179, "max_line_length": 131, "alphanum_fraction": 0.4550694263, "include": true, "reason": "import numpy", "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377225508372, "lm_q2_score": 0.8887587993853654, "lm_q1q2_score": 0.8519088354598646}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.fftpack import fft, ifft\n\nN = 256\nM = 63\nf0 = 1000\nfs = 10000\nA0 = .8 \nhN = N//2 \nhM = (M+1)//2\nfftbuffer = np.zeros(N)\nX1 = np.zeros(N, dtype='complex')\nX2 = np.zeros(N, dtype='complex')\n\nx = A0 * np.cos(2*np.pi*f0/fs*np.arange(-hM+1,hM))\n\nplt.figure(1, figsize=(9.5, 7))\nw = np.hanning(M)\nplt.subplot(2,3,1)\nplt.title('w (hanning window)')\nplt.plot(np.arange(-hM+1, hM), w, 'b', lw=1.5)\nplt.axis([-hM+1, hM, 0, 1])\n\nfftbuffer[:hM] = w[hM-1:]\nfftbuffer[N-hM+1:] = w[:hM-1]  \nX = fft(fftbuffer)\nX1[:hN] = X[hN:]\nX1[N-hN:] = X[:hN]\nmX = 20*np.log10(abs(X1))       \n\nplt.subplot(2,3,2)\nplt.title('mW')\nplt.plot(np.arange(-hN, hN), mX, 'r', lw=1.5)\nplt.axis([-hN,hN,-40,max(mX)])\n\npX = np.angle(X1)\nplt.subplot(2,3,3)\nplt.title('pW')\nplt.plot(np.arange(-hN, hN), np.unwrap(pX), 'c', lw=1.5)\nplt.axis([-hN,hN,min(np.unwrap(pX)),max(np.unwrap(pX))])\n\nplt.subplot(2,3,4)\nplt.title('xw (windowed sinewave)')\nxw = x*w\nplt.plot(np.arange(-hM+1, hM), xw, 'b', lw=1.5)\nplt.axis([-hM+1, hM, -1, 1])\n\nfftbuffer = np.zeros(N)\nfftbuffer[0:hM] = xw[hM-1:]\nfftbuffer[N-hM+1:] = xw[:hM-1]\nX = fft(fftbuffer)\nX2[:hN] = X[hN:]\nX2[N-hN:] = X[:hN]\nmX2 = 20*np.log10(abs(X2))  \n\nplt.subplot(2,3,5)\nplt.title('mXW')\nplt.plot(np.arange(-hN, hN), mX2, 'r', lw=1.5)\nplt.axis([-hN,hN,-40,max(mX)])\n\npX = np.angle(X2)\nplt.subplot(2,3,6)\nplt.title('pXW')\nplt.plot(np.arange(-hN, hN), np.unwrap(pX), 'c', lw=1.5)\nplt.axis([-hN,hN,min(np.unwrap(pX)),max(np.unwrap(pX))])\n\nplt.tight_layout()\nplt.savefig('sine-spectrum.png')\nplt.show()\n", "meta": {"hexsha": "2613f404ad10d6602c55b1f2c64acbc18ff15cd2", "size": 1565, "ext": "py", "lang": "Python", "max_stars_repo_path": "stanford/sms-tools/lectures/04-STFT/plots-code/sine-spectrum.py", "max_stars_repo_name": "phunc20/dsp", "max_stars_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-12T18:32:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T18:32:06.000Z", "max_issues_repo_path": "stanford/sms-tools/lectures/04-STFT/plots-code/sine-spectrum.py", "max_issues_repo_name": "phunc20/dsp", "max_issues_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stanford/sms-tools/lectures/04-STFT/plots-code/sine-spectrum.py", "max_forks_repo_name": "phunc20/dsp", "max_forks_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0422535211, "max_line_length": 56, "alphanum_fraction": 0.6076677316, "include": true, "reason": "import numpy,from scipy", "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377320263432, "lm_q2_score": 0.8887587831798665, "lm_q1q2_score": 0.8519088283477216}}
{"text": "\ndef newton_raph(fx, theta_0, thresh, x_data):        \n    '''\n        Function to implement the Newton Raphson method\n    '''\n        \n    #get the first and second derivative\n    d1 = sp.diff(fx, theta)\n    d2 = sp.diff(d1, theta) \n   \n    print('\\nLatex Equations')\n    print('Original Function:  ', sp.latex(fx))\n    print('First Derivative:   ', sp.latex(d1))\n    print('Second Derivative:  ',sp.latex(d2))\n    \n    #initialize the first derivative\n    d_sub = d1.subs(theta, theta_0)    \n    d1_lam = sp.lambdify( x, d_sub, \"numpy\")\n    d_1 = sum((d1_lam(x_data)))\n    \n    #Iterate using the Newton Raphson method while theta is < thresh\n    n_iterations = 0    #Number of iterations to complete\n    \n    while abs(d_1) > thresh: \n        n_iterations +=1\n        d1_sub = d1.subs(theta, theta_0)\n        d1_lam = sp.lambdify( x, d1_sub, \"numpy\")\n        d_1 = np.sum((d1_lam(x_data)))\n        \n        d2_sub = d2.subs(theta, theta_0)\n        d2_lam = sp.lambdify( x, d2_sub, \"numpy\")\n        d_2 = np.sum((d2_lam(x_data)))        \n        \n        #assign new value to theta for next iteration         \n        theta_0 = theta_0 - d_1/d_2         \n        \n    theta_hat = theta_0\n    print('\\nNumber of Iterations: ', n_iterations)\n    print('theta hat: ', theta_hat)    \n    return theta_hat   \n\n\nif __name__ == \"__main__\":\n    import sympy as sp\n    from sympy.abc import i\n    import numpy as np \n    import pandas as pd    \n    \n    #Sample 1    \n    #create synthetic data\n    n=10\n    j=np.arange(1,n+1,1)\n    x_data = -3.1 + 6*j/n\n    \n    #declare the sympy function\n    theta = sp.Symbol('theta')\n    x = sp.Symbol('x')\n    \n    fx = 1551*theta - sp.Sum( (sp.exp(theta*x) ),(i, 0, 9))\n    theta_init = 3    #initial guess of theta\n    thresh = 1e-10    #threshold for theta\n    \n    #Sample 2 (work in progress)\n# =============================================================================\n#     data = pd.read_csv(r'data/test_data.csv')\n#     x_data = data['x']\n#     y_data = data['y']  \n#     \n#     theta = sp.Symbol('theta')\n#     x = sp.Symbol('x')\n#     y = sp.symbol('y')\n#     \n#     fx = 1/2 * sp.sum( (y-sp.exp(theta*x))**2),(i, 0, len(x_data-1)))\n# =============================================================================\n    \n    \n    #run function\n    newton_raph(fx=fx, theta_0=theta_init, thresh=thresh, x_data = x_data)\n    ", "meta": {"hexsha": "a41033e80e985fea495c81e8b072586356c9b2d9", "size": 2367, "ext": "py", "lang": "Python", "max_stars_repo_path": "Newton-Raphson_Sympy.py", "max_stars_repo_name": "tyborra/Newton-Raphson_Sympy", "max_stars_repo_head_hexsha": "ae01545bb23876a722d7f33f20734ad09d7b859c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Newton-Raphson_Sympy.py", "max_issues_repo_name": "tyborra/Newton-Raphson_Sympy", "max_issues_repo_head_hexsha": "ae01545bb23876a722d7f33f20734ad09d7b859c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Newton-Raphson_Sympy.py", "max_forks_repo_name": "tyborra/Newton-Raphson_Sympy", "max_forks_repo_head_hexsha": "ae01545bb23876a722d7f33f20734ad09d7b859c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9620253165, "max_line_length": 79, "alphanum_fraction": 0.5242923532, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885904, "lm_q2_score": 0.8887587846530937, "lm_q1q2_score": 0.8519088255491462}}
{"text": "#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul  2 13:54:12 2020\r\n\r\nFunction for time series novelty score calculation.\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\ndef _create_kernel(edge, sigma=1.0, mu=0.0):\r\n    \"\"\"\r\n    Create a (2*edge+1) x (2*edge+1) gaussian kernel.\r\n    \r\n\r\n    Parameters\r\n    ----------\r\n    edge : int, optional\r\n        Gaussian kernel window length / 2. \r\n    sigma : float, optional\r\n        Variance for the gaussian kernel construction. The default is 1.0.\r\n    mu : float, optional\r\n        Mean for the gaussian kernel construction. The default is 0.0.\r\n\r\n    Returns\r\n    -------\r\n    kernel : numpy ndarray\r\n        2D gaussian convolution kernel.\r\n\r\n    \"\"\"   \r\n    assert isinstance(edge,int), \"Edge is not an integer.\"\r\n    assert edge > 0, \"Edge should be positive, non zero integer.\"\r\n    \r\n    grid = np.linspace(-1, 1, 2*edge + 1)    \r\n    x,y = np.meshgrid(grid,grid)\r\n    d = np.sqrt(x**2 + y**2)\r\n    gaussian_mat = np.exp(-((d - mu)**2 / (2.0 * sigma**2)))\r\n    \r\n    kernel_grid = np.sign(np.linspace(-edge, edge, 2*edge +1))\r\n    signs = np.outer(kernel_grid, kernel_grid)\r\n    signed_gaussian = signs * gaussian_mat\r\n    kernel = signed_gaussian / np.sum(np.abs(signed_gaussian))\r\n    \r\n    return kernel\r\n\r\ndef compute_novelty(simmat, edge = 7, sigma=1.0, mu = 0.0):\r\n    \"\"\"\r\n    Compute novelty score using the self similarity matrix and gaussian \r\n    checkerboard convolution kernel, calculating the convolution along the \r\n    self similarity matrix diagonal.\r\n\r\n    Parameters\r\n    ----------\r\n    simmat : numpy ndarray \r\n        N x N self similarity matrix. \r\n    edge : float, optional\r\n        Gaussian kernel window length / 2. The default is 7.\r\n    sigma : float, optional\r\n        Variance for the gaussian kernel construction. The default is 1.0.\r\n    mu : float, optional\r\n        Mean for the gaussian kernel construction. The default is 0.0.\r\n\r\n    Returns\r\n    -------\r\n    nov : numpy ndarray\r\n        1D novelty score vector.\r\n    kernel : numpy ndarray\r\n        2D gaussian convolution kernel.\r\n\r\n    \"\"\"\r\n    \r\n    assert isinstance(simmat,np.ndarray), \"Self similarity matrix is not a numpy array.\"\r\n    assert np.ndim(simmat) == 2, \"Self similarity matrix is not 2-dimensional.\"\r\n    assert simmat.shape[0] == simmat.shape[1], \"Self similarity matrix is not square.\"\r\n    assert 2*edge + 1 <= simmat.shape[0], \"Kernel size is larger than the self similarity matrix.\"\r\n    \r\n    kernel = _create_kernel(edge, sigma, mu)\r\n    \r\n    N = simmat.shape[0]\r\n    M = 2*edge + 1\r\n    \r\n    novelty = np.zeros(N)\r\n    \r\n    simmat_padded  = np.pad(simmat,edge,mode='constant')\r\n\r\n    for i in range(N):\r\n        novelty[i] = np.sum(simmat_padded[i:i+M, i:i+M] * kernel)\r\n \r\n    return novelty, kernel\r\n\r\n\r\n", "meta": {"hexsha": "fb5c337824cb7a092e907fddf02dc0c220fc6ca7", "size": 2784, "ext": "py", "lang": "Python", "max_stars_repo_path": "Source/Analysis/calculate_novelty.py", "max_stars_repo_name": "rantahar/tscfat", "max_stars_repo_head_hexsha": "79cbc4c0016780d7cba717594f20b6b81f2e21ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Analysis/calculate_novelty.py", "max_issues_repo_name": "rantahar/tscfat", "max_issues_repo_head_hexsha": "79cbc4c0016780d7cba717594f20b6b81f2e21ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Analysis/calculate_novelty.py", "max_forks_repo_name": "rantahar/tscfat", "max_forks_repo_head_hexsha": "79cbc4c0016780d7cba717594f20b6b81f2e21ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2608695652, "max_line_length": 99, "alphanum_fraction": 0.6102729885, "include": true, "reason": "import numpy", "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811581728097, "lm_q2_score": 0.8824278788223264, "lm_q1q2_score": 0.8518792476614733}}
{"text": "import numpy as np\nfrom numpy import exp, sqrt, cos, pi, sin\n\nfrom base_function import BaseFunction\n\n\nclass Levi(BaseFunction):\n    target_E = 0.\n    xmin = np.array([-10.,-10.])\n    xmax = np.array([10.,10.])\n\n    def getEnergy(self, coords):\n        x, y = coords\n        E = sin(3.*pi*x)**2 + (x-1.)**2 * (1. + sin(3*pi*y)**2) \\\n            + (y-1.)**2 * (1. + sin(2*pi*y)**2)\n        return E\n    \n    def getEnergyGradient(self, coords):\n        x, y = coords\n        E = self.getEnergy(coords)\n        \n        dEdx = 2.*3.*pi* cos(3.*pi*x) * sin(3.*pi*x) + 2.*(x-1.) * (1. + sin(3*pi*y)**2)\n        \n        dEdy = (x-1.)**2 * 2.*3.*pi* cos(3.*pi*y) * sin(3.*pi*y) + 2. *  (y-1.) * (1. + sin(2*pi*y)**2) \\\n            + (y-1.)**2 * 2.*2.*pi * cos(2.*pi*y) * sin(2.*pi*y)\n        \n        return E, np.array([dEdx, dEdy])\n\nif __name__ == \"__main__\":\n    f = Levi()\n    f.test_potential(f.get_random_configuration())\n    \n    from base_function import makeplot2d\n    makeplot2d(f)\n\n", "meta": {"hexsha": "5892e8341accd8727e9578182f184de9fc9f325f", "size": 988, "ext": "py", "lang": "Python", "max_stars_repo_path": "pytorch-ddpg/envs/levi.py", "max_stars_repo_name": "alvinwan/explore", "max_stars_repo_head_hexsha": "358c076b8250f561394e32b1ee2de9bc5562dcdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pytorch-ddpg/envs/levi.py", "max_issues_repo_name": "alvinwan/explore", "max_issues_repo_head_hexsha": "358c076b8250f561394e32b1ee2de9bc5562dcdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pytorch-ddpg/envs/levi.py", "max_forks_repo_name": "alvinwan/explore", "max_forks_repo_head_hexsha": "358c076b8250f561394e32b1ee2de9bc5562dcdb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4444444444, "max_line_length": 105, "alphanum_fraction": 0.4949392713, "include": true, "reason": "import numpy,from numpy", "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688145, "lm_q2_score": 0.8824278772763472, "lm_q1q2_score": 0.8518792470479164}}
{"text": "import numpy as np\nimport numpy.linalg as LA\n\ndef proj(v1,v2):\n  '''\n  Function to compute projection of v2 on v1\n  '''\n  alpha = np.dot(v1,v2)/np.dot(v1,v1)                                                  # proj(a,b) = aTb/aTa\n  return alpha\n\ndef Gram_Schmid(M):\n  '''\n  Given any (m x n) matrix,M this function computers corresponding orthonormal matrix B such that,\n  1. BTB = I\n  2. C(M) = C(B) i.e Columnspace will be same\n  '''\n  row,col = M.shape\n  Q = []                                                                               # List to append all orthogonal column vector later to be normalized\n  for c in range(col):\n    column_vector = M[:,c]    \n    if c == 0:                                                                         # First column vector is itself taken to be orthogonal hence append\n      Q.append(column_vector)\n    else:\n      for ortho_col_vec in Q:                                                          # For all previous orthogonal column vectors do operation on current column vector\n        temp_col_vec = column_vector.copy()\n        column_vector -= np.multiply(proj(ortho_col_vec,temp_col_vec),ortho_col_vec)   # B = B - proj(A,B)*A for all A in Q\n      if (LA.norm(column_vector)!=0):                                                  # If column vector is linearly independent then add to Q\n        Q.append(column_vector)\n  # Orthonormalizartion of Q\n  B = []                                                                               # Output Orthonormalized Matrix\n  for col_vec in Q:\n    B.append(col_vec/LA.norm(col_vec))\n  return np.array(B).T\n\n\n\nA = np.array([[1,1],\n              [1,0],\n              [1,2]],dtype=np.float32)\n\n\n\nB = Gram_Schmid(A)\nprint(B)\nprint(np.matmul(B.T,B))\n", "meta": {"hexsha": "b8f33f47aa2d280c89140e1894cd9cd1c7e38f2f", "size": 1743, "ext": "py", "lang": "Python", "max_stars_repo_path": "Gram_Schmidt.py", "max_stars_repo_name": "Arko98/Alogirthms", "max_stars_repo_head_hexsha": "ce56faaaf847dbf077de935a98814c37275f8a5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-08-02T16:31:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T22:58:59.000Z", "max_issues_repo_path": "Gram_Schmidt.py", "max_issues_repo_name": "Arko98/Alogirthms", "max_issues_repo_head_hexsha": "ce56faaaf847dbf077de935a98814c37275f8a5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gram_Schmidt.py", "max_forks_repo_name": "Arko98/Alogirthms", "max_forks_repo_head_hexsha": "ce56faaaf847dbf077de935a98814c37275f8a5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-27T11:23:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T05:47:39.000Z", "avg_line_length": 37.8913043478, "max_line_length": 169, "alphanum_fraction": 0.5111876076, "include": true, "reason": "import numpy", "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965381162156829, "lm_q2_score": 0.8824278649085118, "lm_q1q2_score": 0.8518792377449484}}
{"text": "import numpy as np\r\n\r\nx = np.array([1,2,3,4,5,6,7,8,9])\r\n\r\na, b, c = np.split(x, (3,6))\r\n\r\nprint(\"a = \",a)\r\nprint(\"b = \",b)\r\nprint(\"c = \",c)\r\n\r\n##\r\n\r\nk = np.arange(16).reshape(4,4)\r\n\r\nprint(\"k = \",k)\r\n\r\nupperar, lowerar = np.vsplit(k, [2]) #vsplit stands for vertical split\r\n\r\nprint(\"upperar = \",upperar)\r\nprint(\"lowerar = \",lowerar)\r\n\r\nupperar2, lowerar2 = np.hsplit(k, [2]) #hsplit stands for horizontal split\r\n\r\nprint(\"upperar2 = \",upperar2)\r\nprint(\"lowerar2 = \",lowerar2)\r\n\r\n##\r\n\r\nl = np.random.normal(10, 2, (3,3))\r\n\r\nprint(\"l = \",l)\r\n\r\nprint(np.sort(l, axis=0)) #sorted column-wise\r\nprint(np.sort(l, axis=1)) #sorted row-wise\r\n\r\n##\r\n\r\nt = np.arange(10, 20)\r\n\r\nprint(\"t = \",t)\r\nprint(\"t[0::2] = \",t[0::2])\r\nprint(\"t[1::3] = \",t[1::3])\r\n\r\n##\r\n\r\nd = np.random.randint(-1, 10, (5,5))\r\n\r\nprint(\"d = \", d)\r\n\r\nprint(d[:, 0]) #all row are selected, whereas only the first column is selected\r\nprint(d[:, 3]) #same here, just another column is selected\r\nprint(d[2, :])\r\nprint(d[0:3, 0:2])\r\n\r\n##\r\n\r\nf = np.random.randint(0, 10, size= (5, 5))\r\n\r\nprint(\"f = \",f)\r\n\r\ncopy = f[0:1, 0:3].copy()\r\n#copy function provides to not changing the original values of the main array (which is f here) \r\nprint(\"copy = \",copy)\r\nprint(\"f = \",f)\r\n\r\n##\r\n\r\n#fancy index\r\n\r\ng = np.arange(15, 0, -2)\r\nprint(\"g = \", g)\r\n\r\nbring = [2, 5, 3]\r\nprint(\"g[bring] = \",g[bring])\r\n\r\n##\r\n\r\nh = np.arange(16).reshape(4,4)\r\nprint(\"h = \", h)\r\n\r\nrow = np.array([2, 1])\r\ncolumn = np.array([2, 2])\r\n\r\nprint(\"h[row, column] =\", h[row, column])\r\nprint(\"h[2, [1, 2]] =\", h[2, [1, 2]])\r\nprint(\"h[0:, h[1, 2]] =\" , h[0:, [1, 2]])\r\n\r\n##\r\n\r\nj = np.arange(10)\r\nprint(j)\r\n\r\nprint(j<6)\r\nprint(j[j!=4])\r\n\r\n##\r\n\r\n# 4*x1 + x2 = 15\r\n# 6*x1 + 2*x2 = 8   solve the two equations\r\n\r\nq = np.array([[4, 1], [6, 2]])\r\nw = np.array([15, 8])\r\n\r\nprint(np.linalg.solve(q, w))", "meta": {"hexsha": "01698ea1a9cfb7645a0ed6562315858ba9264211", "size": 1807, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumPy/numpy_basics2.py", "max_stars_repo_name": "senasaccount/python101", "max_stars_repo_head_hexsha": "2a0119132f2a170073ab62b60a7989d3a0d2fedf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NumPy/numpy_basics2.py", "max_issues_repo_name": "senasaccount/python101", "max_issues_repo_head_hexsha": "2a0119132f2a170073ab62b60a7989d3a0d2fedf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumPy/numpy_basics2.py", "max_forks_repo_name": "senasaccount/python101", "max_forks_repo_head_hexsha": "2a0119132f2a170073ab62b60a7989d3a0d2fedf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.375, "max_line_length": 97, "alphanum_fraction": 0.5368013282, "include": true, "reason": "import numpy", "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939516, "lm_q2_score": 0.9196425383355795, "lm_q1q2_score": 0.8518683137972457}}
{"text": "'''\nComputing percentiles\n100xp\nIn this exercise, you will compute the percentiles of petal length of Iris versicolor.\n\nInstructions\n-Create percentiles, a NumPy array of percentiles you want to compute. These are the 2.5th,\n25th, 50th, 75th, and 97.5th. You can do so by creating a list containing these ints/floats\nand convert the list to a NumPy array using np.array(). For example, np.array([30, 50]) would\ncreate an array consisting of the 30th and 50th percentiles.\n-Use np.percentile() to compute the percentiles of the petal lengths from the Iris versicolor\nsamples. The variable versicolor_petal_length is in your namespace.\n-Print the percentiles.\n'''\n\nimport numpy as np\nimport seaborn as sns\n\nversicolor_petal_length = np.array([4.7,  4.5,  4.9,  4.,  4.6,  4.5,  4.7,  3.3,  4.6,  3.9,  3.5,\n                                    4.2,  4.,  4.7,  3.6,  4.4,  4.5,  4.1,  4.5,  3.9,  4.8,  4.,\n                                    4.9,  4.7,  4.3,  4.4,  4.8,  5.,  4.5,  3.5,  3.8,  3.7,  3.9,\n                                    5.1,  4.5,  4.5,  4.7,  4.4,  4.1,  4.,  4.4,  4.6,  4.,  3.3,\n                                    4.2,  4.2,  4.2,  4.3,  3.,  4.1])\n\n# Specify array of percentiles: percentiles\npercentiles = np.array([2.5, 25, 50, 75, 97.5])\n\n# Compute percentiles: ptiles_vers\nptiles_vers = np.percentile(versicolor_petal_length, percentiles)\n\n# Print the result\nprint(ptiles_vers)\n", "meta": {"hexsha": "747f1479a1301a9a7e373e0c9ece3276f0650175", "size": 1408, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/2-quantitative-exploratory-data-analysis/computing-percentiles.py", "max_stars_repo_name": "aimanahmedmoin1997/DataCamp", "max_stars_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-12T04:49:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T00:40:28.000Z", "max_issues_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/2-quantitative-exploratory-data-analysis/computing-percentiles.py", "max_issues_repo_name": "aimanahmedmoin1997/DataCamp", "max_issues_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science With Python/15-statistical-thinking-in-python-(part1)/2-quantitative-exploratory-data-analysis/computing-percentiles.py", "max_forks_repo_name": "aimanahmedmoin1997/DataCamp", "max_forks_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-11-06T17:43:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T21:08:16.000Z", "avg_line_length": 42.6666666667, "max_line_length": 99, "alphanum_fraction": 0.609375, "include": true, "reason": "import numpy", "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321808, "lm_q2_score": 0.8976952914230971, "lm_q1q2_score": 0.8518385615773977}}
{"text": "# MIT License\n# \n# Copyright (c) 2021 Playtika Ltd.\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport numpy as np\n\n\ndef cohens_d(mu_1, mu_2, std):\n    \"\"\"\n\n    Compute the standardized effect size as difference between the two means divided by the standard deviation.\n\n    Parameters\n    ----------\n    mu_1 : float\n        Mean of the first sample.\n    mu_2 : float\n        Mean of the second sample.\n    std : float > 0\n        Pooled standard deviation. It assumes that the variance of each population is the same.\n\n    Returns\n    -------\n    effect_size : float\n        Effect size as cohen's d coefficient\n    \"\"\"\n\n    return (mu_1 - mu_2) / std\n\n\ndef cohens_h(p1, p2):\n    \"\"\"\n\n    Compute the effect size as measure of distance between two proportions or probabilities. It is the difference\n    between their arcsine transformations\n\n    Parameters\n    ----------\n    p1 : float in interval (0,1)\n        Proportion or probability of the first sample.\n    p2 : float in interval (0,1)\n        Proportion or probability of the second sample.\n\n    Returns\n    -------\n    effect_size : float\n        Effect size as cohen's h coefficient\n    \"\"\"\n\n    return abs(2 * np.arcsin(np.sqrt(p1)) - 2 * np.arcsin(np.sqrt(p2)))\n\n\ndef pooled_std(sample1, sample2):\n    \"\"\"\n\n    Compute pooled standard deviation between two samples.\n\n    Parameters\n    ----------\n    sample1 : array_like\n        Observation of first sample\n    sample2 : array_like\n        Observation of second sample\n\n    Returns\n    -------\n    pooled_std : float > 0\n        p-value for the test\n    \"\"\"\n    # Compute the size of samples\n    n1, n2 = len(sample1), len(sample2)\n\n    # Compute the variance of the samples\n    std1, std2 = np.var(sample1, ddof=1), np.var(sample2, ddof=1)\n\n    # Compute the pooled standard deviation\n    return np.sqrt(((n1 - 1) * std1 + (n2 - 1) * std2) / (n1 + n2 - 2))\n", "meta": {"hexsha": "cea23f1ae00f7440791a022bf4c684e4e8a6a9e2", "size": 2889, "ext": "py", "lang": "Python", "max_stars_repo_path": "abexp/statistics/stats_metrics.py", "max_stars_repo_name": "PlaytikaResearch/abexp", "max_stars_repo_head_hexsha": "7f04e0fe29be6b027c84f670f4d09939b50f8eca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-17T12:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T09:35:58.000Z", "max_issues_repo_path": "abexp/statistics/stats_metrics.py", "max_issues_repo_name": "PlaytikaResearch/abexp", "max_issues_repo_head_hexsha": "7f04e0fe29be6b027c84f670f4d09939b50f8eca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "abexp/statistics/stats_metrics.py", "max_forks_repo_name": "PlaytikaResearch/abexp", "max_forks_repo_head_hexsha": "7f04e0fe29be6b027c84f670f4d09939b50f8eca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.09375, "max_line_length": 113, "alphanum_fraction": 0.6791277259, "include": true, "reason": "import numpy", "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522862, "lm_q2_score": 0.8991213853793452, "lm_q1q2_score": 0.8518105591481375}}
{"text": "import numpy as np\nimport csv\n\n# =============================================================================\n# Models\n# =============================================================================\n\ndef least_squares_GD(y, tx, initial_w,\n                     max_iters, gamma, verbose=False):\n    \"\"\"Least squares with MSE loss and Gradient Descent.\"\"\"\n    ws = [initial_w]\n    w = initial_w\n    losses = []\n\n    for n_iter in range(max_iters):\n        # Compute gradient and loss\n        g = mse_grad(y, tx, w)\n        loss = mse(y, tx, w)\n        # Update the weights\n        w = w - gamma * g\n        w = w.ravel()\n        # Store the weights and loss\n        ws.append(w)\n        losses.append(loss)\n\n        if verbose:\n            print(\"Gradient descent({bi}/{ti}): loss={l}\".format(\n                    bi=n_iter, ti=max_iters - 1, l=loss))\n\n    return ws[-1], losses[-1]\n\ndef least_squares_SGD(y, tx, initial_w,\n                      max_iters, gamma, verbose=False):\n    \"\"\"Least squares with MSE loss and Stochasitc Gradient Descent.\"\"\"\n    ws = [initial_w]\n    losses = []\n    w = initial_w\n    for n_iter in range(max_iters):\n        for minibatch_y, minibatch_tx in batch_iter(y, tx, batch_size=1):\n            # Compute gradient and loss\n            g = mse_grad(minibatch_y, minibatch_tx, w)\n            loss = mse(minibatch_y, minibatch_tx, w)\n            # Update the weights\n            w = w - gamma * g\n            w = w.ravel()\n            # store w and loss\n            ws.append(w)\n            losses.append(loss)\n            if verbose:\n                print(\"Stochastic gradient descent({bi}/{ti}): loss={l}\".format(\n                    bi=n_iter, ti=max_iters - 1, l=loss))\n\n    return ws[-1], mse(y, tx, ws[-1])\n\n\ndef least_squares(y, tx):\n    \"\"\"Linear regression fit using normal equations.\"\"\"\n    a = tx.T @ tx\n    b = tx.T @ y\n    w = np.linalg.solve(a, b)\n    loss = mse(y, tx, w)\n    return w, loss\n\n\ndef ridge_regression(y, tx, lambda_):\n    \"\"\" Ridge regression fit using normal equations \"\"\"\n    a = (tx.T @ tx) + lambda_*2*tx.shape[0] * np.eye(tx.shape[1])\n    b = tx.T @ y\n    w = np.linalg.solve(a, b)\n    return w, mse(y, tx, w)\n\n\ndef logistic_regression(y, tx, initial_w, max_iters,\n                        gamma, verbose=False):\n    \"\"\"Logistic regression with log loss and Gradient Descent.\"\"\"\n    ws = [initial_w]\n    w = initial_w\n    losses = []\n\n    for n_iter in range(max_iters):\n        # Compute gradient and loss\n        g = logistic_grad(y, tx, w)\n        loss = logistic_error(y, tx, w)\n        # Update the weights\n        w = w - gamma * g\n        w = w.ravel()\n        # Store the weights and loss\n        ws.append(w)\n        losses.append(loss)\n\n        if verbose:\n            print(\"Gradient descent({bi}/{ti}): loss={l}\".format(\n                    bi=n_iter, ti=max_iters - 1, l=loss))\n\n    return ws[-1], losses[-1]\n\ndef reg_logistic_regression(y, tx, lambda_, reg, initial_w,\n                            max_iters, gamma, verbose=False,\n                            early_stopping=True, tol = 0.0001,\n                            patience = 5):\n    \"\"\"Regularized logistic regression with log loss and Gradient Descent with early stopping\"\"\"\n    ws = [initial_w]\n    w = initial_w\n    losses = []\n\n    for n_iter in range(max_iters):\n        # Compute gradient and loss\n        g = reg_logistic_grad(y, tx, w, lambda_, reg)\n        loss = reg_logistic_error(y, tx, w, lambda_, reg)\n\n        # Update the weights\n        w = w - gamma * g\n        w = w.ravel()\n        # Store the weights and loss\n        ws.append(w)\n        losses.append(loss)\n\n        if verbose:\n            print(\"Gradient descent({bi}/{ti}): loss={l}\".format(\n                    bi=n_iter, ti=max_iters - 1, l=loss))\n\n        # Early stopping\n        if (early_stopping) and (n_iter > patience):\n            # Check if loss has improved by tol in last patience iters\n            l_pat = reg_logistic_error(y, tx, ws[-patience], lambda_, reg)\n            l_1 = reg_logistic_error(y, tx, ws[-1], lambda_, reg)\n            if ((l_pat - l_1) < tol):\n                print(f\"Stopped after {n_iter} it.\")\n                break\n\n    return ws[-1], losses[-1]\n\n# =============================================================================\n# Cost functions\n# =============================================================================\n\ndef mse(y, tx, w):\n    \"\"\"Mean squared error loss function.\"\"\"\n    e = y - tx @ w\n    return (1/(2*tx.shape[0])) * np.sum(e**2)\n\ndef logistic_error(y, tx, w):\n    \"\"\"Log loss function.\"\"\"\n    a = sigmoid(tx @ w)\n    loss = - (1 / tx.shape[0]) * np.sum((y * np.log(a)) + ((1 - y) * np.log(1 - a)))\n    return loss\n\ndef reg_logistic_error(y, tx, w, lambda_, reg):\n    \"\"\"Log loss function with regularization term.\"\"\"\n    assert (reg==1 or reg==2), \"reg needs to be 1 or 2\"\n    loss = logistic_error(y, tx, w) + lambda_ * (np.linalg.norm(w, reg) ** reg)\n    return loss\n\n# =============================================================================\n# Gradients\n# =============================================================================\n\ndef mse_grad(y, tx, w):\n    \"\"\"Compute gradient for MSE loss.\"\"\"\n    e = y - tx @ w\n    return (-1/tx.shape[0]) * tx.T @ e\n\ndef logistic_grad(y, tx, w):\n    \"\"\"Compute gradient for log loss.\"\"\"\n    e = sigmoid(tx @ w) - y\n    return (1/tx.shape[0]) * tx.T @ e\n\ndef reg_logistic_grad(y, tx, w, lambda_, reg):\n    \"\"\"Compute gradient for log loss with regularization.\"\"\"\n    assert (reg==1 or reg==2), \"reg needs to be 1 or 2\"\n    if (reg==1):\n        # L1 regularization\n        return logistic_grad(y, tx, w) + lambda_ * np.sign(w)\n    else:\n        # L2 regularization\n        return logistic_grad(y, tx, w) + 2 * lambda_ * w\n\n# =============================================================================\n# Activation functions\n# =============================================================================\n\ndef sigmoid(x):\n    \"\"\"Compute sigmoid function.\"\"\"\n    epsilon = 1E-12\n    a = 1 / (1 + np.exp(-x))\n    a = np.where(np.isclose(a, 0.0), epsilon, a)\n    a = np.where(np.isclose(a, 1.0), (1-epsilon), a)\n    return a\n\n# =============================================================================\n# Helpers\n# =============================================================================\n\ndef batch_iter(y, tx, batch_size, num_batches=1, shuffle=True):\n    # Please note this code was provided to us during the lab sessions.\n    \"\"\"\n    Generate a minibatch iterator for a dataset.\n    Takes as input two iterables (here the output desired values 'y' and the input data 'tx')\n    Outputs an iterator which gives mini-batches of `batch_size` matching elements from `y` and `tx`.\n    Data can be randomly shuffled to avoid ordering in the original data messing with the randomness of the minibatches.\n    Example of use :\n    for minibatch_y, minibatch_tx in batch_iter(y, tx, 32):\n        <DO-SOMETHING>\n    \"\"\"\n    data_size = len(y)\n\n    if shuffle:\n        shuffle_indices = np.random.permutation(np.arange(data_size))\n        shuffled_y = y[shuffle_indices]\n        shuffled_tx = tx[shuffle_indices]\n    else:\n        shuffled_y = y\n        shuffled_tx = tx\n    for batch_num in range(num_batches):\n        start_index = batch_num * batch_size\n        end_index = min((batch_num + 1) * batch_size, data_size)\n        if start_index != end_index:\n            yield shuffled_y[start_index:end_index], shuffled_tx[start_index:end_index]\n\ndef import_data(path=\"data/\"):\n    \"\"\"\n    Import csv files and return array of X,y and vector of the column names.\n    \"\"\"\n    train = np.loadtxt(\n        f\"{path}train.csv\",\n        delimiter = \",\",\n        skiprows=0,\n        dtype=str\n    )\n\n    test = np.loadtxt(\n        f\"{path}test.csv\",\n        delimiter = \",\",\n        skiprows=0,\n        dtype=str\n    )\n\n    col_names = train[0,:]\n\n    # Remove column names\n    train = np.delete(train, obj=0, axis=0)\n    test = np.delete(test, obj=0, axis=0)\n\n    # Map 0 & 1 to label\n    label_idx = np.where(col_names == \"Prediction\")[0][0]\n    train[:,label_idx] = np.where(train[:,label_idx]==\"s\", 1, 0)\n\n    test[:,label_idx] = 0\n\n    # Replace -999 with nan\n    train = train.astype(np.float32)\n    train[train == -999] = np.nan\n\n    test = test.astype(np.float32)\n    test[test == -999] = np.nan\n    return train, test, col_names\n\ndef create_csv_submission(ids, y_pred, name):\n    # Please note this code was provided to us during the lab sessions.\n    \"\"\"\n    Creates an output file in csv format for submission to AIcrowd\n    Arguments: ids (event ids associated with each prediction)\n               y_pred (predicted class labels)\n               name (string name of .csv output file to be created)\n    \"\"\"\n    with open(name, 'w') as csvfile:\n        fieldnames = ['Id', 'Prediction']\n        writer = csv.DictWriter(csvfile, delimiter=\",\", fieldnames=fieldnames)\n        writer.writeheader()\n        for r1, r2 in zip(ids, y_pred):\n            writer.writerow({'Id':int(r1),'Prediction':int(r2)})\n\ndef standardize_numpy(x, mean=None, std=None):\n    \"\"\"Standardize the original data set. Works on numpy arrays.\"\"\"\n    if mean is None: mean = x.mean(axis=0, keepdims=True)\n    x = x - mean\n    if std is None: std = x.std(axis=0, keepdims=True)\n    x = x / std\n    return x, mean, std\n\n# =============================================================================\n# Prepare features\n# =============================================================================\n\ndef split_X_y(train, test, cols):\n    \"\"\"Create tx matrix for train & test + y vector for train.\"\"\"\n    idx_id = np.where(cols==\"Id\")[0][0]\n    idx_pred = np.where(cols==\"Prediction\")[0][0]\n\n    tx_train = np.delete(train, [idx_id, idx_pred], axis=1)\n    y_train = train[:,idx_pred].copy()\n    tx_test = np.delete(test, [idx_id, idx_pred], axis=1)\n\n    return tx_train, y_train, tx_test\n\ndef build_poly(x, degree):\n    \"\"\"Polynomial basis functions for each column of x, for j=1 up to j=degree, and single constant term.\"\"\"\n    if (degree < 0): raise ValueError(\"degree must be positive\")\n\n    phi = np.empty((x.shape[0], x.shape[1]*degree+1))\n\n    # Constant term\n    phi[:,-1] = 1\n\n    # Higher order terms\n    for j in range(x.shape[1]):\n        phi[:,j*degree] = x[:,j]\n        for d in range(1,degree):\n            col = j*degree+d\n            phi[:,col] = phi[:,col-1] * x[:,j]\n\n    return phi\n\ndef prepare_features(tx_nan, degree, mean_nan=None, mean=None, std=None):\n    \"\"\"Clean and prepare for learning.  Mean imputing, missing value indicator, standardize.\"\"\"\n    # Get column means, if necessary\n    if mean_nan is None: mean_nan = np.nanmean(tx_nan,axis=0)\n\n    # Replace NaNs\n    tx_val = np.where(np.isnan(tx_nan), mean_nan, tx_nan)\n\n    # Polynomial features\n    tx = build_poly(tx_val, degree)\n    const_col = tx.shape[1]-1\n\n    # Add NaN indicator columns\n    nan_cols = np.flatnonzero(np.any(np.isnan(tx_nan), axis=0))\n\n    ind_cols = np.empty((tx_nan.shape[0], nan_cols.shape[0]))\n    ind_cols = np.where(np.isnan(tx_nan[:,nan_cols]), 1, 0)\n\n    tx = np.c_[tx, ind_cols]\n\n    # Standardize\n    tx, mean, std = standardize_numpy(tx, mean, std)\n    tx[:,const_col] = 1.0\n\n    return tx, mean, std, mean_nan, nan_cols\n\n# =============================================================================\n# Performance metrics\n# =============================================================================\n\ndef logistic_prediction(tx, w):\n    \"\"\"Make a prediction with logistic regression model.\"\"\"\n    return np.rint(sigmoid(tx @ w))\n\ndef regression_prediction(tx, w):\n    \"\"\"Make a prediction with linear regression model.\"\"\"\n    return tx @ w\n\ndef f1_score(y_targ, y_pred):\n    \"\"\"Compute the F1 score of a prediction.\"\"\"\n    mask_targ = (y_targ == 1)\n    mask_pred = (y_pred == 1)\n\n    # Total positives\n    total_pred = np.count_nonzero(mask_pred)\n    total_targ = np.count_nonzero(mask_targ)\n\n    # True positives\n    true_pos = np.count_nonzero(mask_pred[mask_targ])\n\n    if (true_pos == 0) or (total_pred == 0) or (total_targ == 0):\n        return 0.0\n\n    precision = true_pos / total_pred\n    recall = true_pos / total_targ\n\n    # Compute F1 score\n    score = 2*(precision*recall)/(precision+recall)\n\n    return score\n\ndef accuracy(y_targ, y_pred):\n    \"\"\"Compute the accuracy of a prediction\"\"\"\n    total_wrong = np.count_nonzero(y_targ-y_pred)\n    return 1.0 - (total_wrong / len(y_pred))\n", "meta": {"hexsha": "fa2f3122c8fe15ba82f22364130226123479d2bb", "size": 12398, "ext": "py", "lang": "Python", "max_stars_repo_path": "project1/code/implementations.py", "max_stars_repo_name": "itslwg/epflml-projects", "max_stars_repo_head_hexsha": "74180683f5f07845f93e1e45e5197dc36802d0f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project1/code/implementations.py", "max_issues_repo_name": "itslwg/epflml-projects", "max_issues_repo_head_hexsha": "74180683f5f07845f93e1e45e5197dc36802d0f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-25T11:18:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-30T15:49:46.000Z", "max_forks_repo_path": "project1/code/implementations.py", "max_forks_repo_name": "itslwg/epflml-projects", "max_forks_repo_head_hexsha": "74180683f5f07845f93e1e45e5197dc36802d0f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7124010554, "max_line_length": 120, "alphanum_fraction": 0.5417002742, "include": true, "reason": "import numpy", "num_tokens": 3071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235895, "lm_q2_score": 0.8991213820004279, "lm_q1q2_score": 0.8518105586185778}}
{"text": "import numpy as np\nimport scipy.signal as sig\nimport math\nimport cv2\nfrom advanced_fields.computer_vision.utils import scale_0_255\n\nimg = np.array([[0, 90, 0],\n                [105, 0, 55],\n                [0, 40, 0]])\n\n# img = cv2.imread('../../../datasets/per_field/cv/color_lady.jpg', cv2.IMREAD_GRAYSCALE)\n\n\n# Note:\n# Convolution reverses the direction of one of the functions it works on.\n# one function is parameterized with τ and the other with -τ.\n#   reference: https://en.wikipedia.org/wiki/Convolution#Definition\n# the desired kernel must be flipped (K[::-1,::-1])) the in both axes to get the expected result.\n# how it's done:\n# desired_kernel = [[0, 1, 2],\n#                   [3, 4, 5],\n#                   [6, 7, 8]]\n# used_kernel = np.array(desired_kernel)[::-1,::-1]\n# used_kernel = np.flip(desired_kernel, axis=(0,1))\n\nkernel_x = np.array([[-1, 0, 1]])[::-1, ::-1]\n# kernel_x = np.flip([[-1, 0, 1]], axis=1)\nkernel_y = np.array([[1], [0], [-1]])[::-1, ::-1]\n# kernel_y = np.flip([[1], [0], [-1]], axis=0)\n\nGV_x = sig.convolve2d(img, kernel_x, mode='valid')[1, 0]       # returns [[0], [-50], [0]]\nGV_y = sig.convolve2d(img, kernel_y, mode='valid')[0, 1]       # returns [[0, 50, 0]]\n\n# Gradient Vector:\nGV = np.array([[GV_x], [GV_y]])\nprint(f'Gradient Vector: \\n {GV}')\n\n# Gradient Vector's Magnitude:\n# GV_M = math.sqrt(GV_x ** 2 + GV_y ** 2)\nGV_M = np.sqrt(GV_x ** 2 + GV_y ** 2)\nprint(f\"Gradient Vector's Magnitude: {GV_M}\")\n\n# Gradient Vector's Direction (\\ angle):\n# GV_theta = math.degrees(math.atan(GV_y / GV_x))\n# GV_theta = np.arctan(GV_y / GV_x) * 180 / np.pi\nGV_theta = np.degrees(np.arctan(GV_y / GV_x))\nprint(f\"Gradient Vector's Direction: {GV_theta}°\")\n\n\n##########################################\n\n# cv2 implementation\nimg = cv2.imread('../../../datasets/per_field/cv/color_man_2004.jpg')\n# img = np.float32(img) / 255.0  # scaling\n\nGV_x_sobel = scale_0_255(cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=1))  # cv2.CV_8U, ksize=5\nGV_y_sobel = scale_0_255(cv2.Sobel(img, cv2.CV_32F, 0, 1, ksize=1))  # cv2.CV_8U, ksize=5\n\nGV_M, GV_theta = cv2.cartToPolar(GV_x_sobel, GV_y_sobel, angleInDegrees=True)\n", "meta": {"hexsha": "2046ad6c4d64e12cf35ec634dd6c05336d4d8fe1", "size": 2125, "ext": "py", "lang": "Python", "max_stars_repo_path": "advanced_fields/computer_vision/image_processing/image_gradient_vector.py", "max_stars_repo_name": "EliorBenYosef/data-science", "max_stars_repo_head_hexsha": "117e5254f63e482c02aff394780bbdc205d492a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "advanced_fields/computer_vision/image_processing/image_gradient_vector.py", "max_issues_repo_name": "EliorBenYosef/data-science", "max_issues_repo_head_hexsha": "117e5254f63e482c02aff394780bbdc205d492a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "advanced_fields/computer_vision/image_processing/image_gradient_vector.py", "max_forks_repo_name": "EliorBenYosef/data-science", "max_forks_repo_head_hexsha": "117e5254f63e482c02aff394780bbdc205d492a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4166666667, "max_line_length": 97, "alphanum_fraction": 0.6202352941, "include": true, "reason": "import numpy,import scipy", "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.8991213759183765, "lm_q1q2_score": 0.8518105515207763}}
{"text": "## 2. Calculating differences ##\n\nfemale_diff = (10771 - 16280.5) / 16280.5\nmale_diff = (21790 - 16280.5) / 16280.5\n\n## 3. Updating the formula ##\n\nfemale_diff = (10771 - 16280.5) ** 2 / 16280.5\nmale_diff = (21790 - 16280.5) ** 2 / 16280.5\ngender_chisq = female_diff + male_diff\n\n## 4. Generating a distribution ##\n\nchi_squared_values = []\nfrom numpy.random import random\nimport matplotlib.pyplot as plt\n\nfor i in range(1000):\n    sequence = random((32561,))\n    sequence[sequence < .5] = 0\n    sequence[sequence >= .5] = 1\n    male_count = len(sequence[sequence == 0])\n    female_count = len(sequence[sequence == 1])\n    male_diff = (male_count - 16280.5) ** 2 / 16280.5\n    female_diff = (female_count - 16280.5) ** 2 / 16280.5\n    chi_squared = male_diff + female_diff\n    chi_squared_values.append(chi_squared)\n\nplt.hist(chi_squared_values)\n\n## 6. Smaller samples ##\n\nfemale_diff = (107.71 - 162.805) ** 2 / 162.805\nmale_diff = (217.90 - 162.805) ** 2 / 162.805\ngender_chisq = female_diff + male_diff\n\n## 7. Sampling distribution equality ##\n\nchi_squared_values = []\nfrom numpy.random import random\nimport matplotlib.pyplot as plt\n\nfor i in range(1000):\n    sequence = random((300,))\n    sequence[sequence < .5] = 0\n    sequence[sequence >= .5] = 1\n    male_count = len(sequence[sequence == 0])\n    female_count = len(sequence[sequence == 1])\n    male_diff = (male_count - 150) ** 2 / 150\n    female_diff = (female_count - 150) ** 2 / 150\n    chi_squared = male_diff + female_diff\n    chi_squared_values.append(chi_squared)\n\nplt.hist(chi_squared_values)\n\n## 9. Increasing degrees of freedom ##\n\ndiffs = []\nobserved = [27816, 3124, 1039, 311, 271]\nexpected = [26146.5, 3939.9, 944.3, 260.5, 1269.8]\n\nfor i, obs in enumerate(observed):\n    exp = expected[i]\n    diff = (obs - exp) ** 2 / exp\n    diffs.append(diff)\n    \nrace_chisq = sum(diffs)\n\n## 10. Using SciPy ##\n\nfrom scipy.stats import chisquare\nimport numpy as np\nobserved = np.array([27816, 3124, 1039, 311, 271])\nexpected = np.array([26146.5, 3939.9, 944.3, 260.5, 1269.8])\n\nchisquare_value, race_pvalue = chisquare(observed, expected)", "meta": {"hexsha": "a3ec4f9fde54871a143f29ff38930a85aea1dc07", "size": 2096, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data Analyst in Python/Step 5 - Probability and Statistics/5. Hypothesis Testing Fundamentals/2. Chi-squared tests.py", "max_stars_repo_name": "MyArist/Dataquest", "max_stars_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-27T12:04:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T04:39:33.000Z", "max_issues_repo_path": "Data Analyst in Python/Step 5 - Probability and Statistics/5. Hypothesis Testing Fundamentals/2. Chi-squared tests.py", "max_issues_repo_name": "myarist/Dataquest", "max_issues_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Analyst in Python/Step 5 - Probability and Statistics/5. Hypothesis Testing Fundamentals/2. Chi-squared tests.py", "max_forks_repo_name": "myarist/Dataquest", "max_forks_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2021-03-30T06:45:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T03:55:02.000Z", "avg_line_length": 27.5789473684, "max_line_length": 60, "alphanum_fraction": 0.6717557252, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.8991213718636754, "lm_q1q2_score": 0.8518105503509917}}
{"text": "\"\"\"\nSimilar to the file of adjoint_univariate_nonlinear_system.py but here we use\nthe Automatic Differentiation of Jax to obtain the gradients of the nonlinear\nfunction.\n\"\"\"\n\nimport time \n\nimport jax.numpy as jnp\nimport jax.scipy as jsp\nfrom jax import grad\n\nfrom scipy import optimize\n\n\ndef residuum(displacement, force, theta):\n    r\"\"\"\n                    /           b              \\\n     -F + k*(a - v)*|- -------------------- + 1|\n                    |     _________________    |\n                    |    /          2    2     |\n                    \\  \\/  2*a*v + b  - v      /\n    \"\"\"\n    vertical_distance, horizontal_distance, spring_stiffness = theta\n    residual_value = (\n        spring_stiffness * (vertical_distance - displacement) * (\n            1\n            -\n            (\n                horizontal_distance\n            ) / (\n                jnp.sqrt(horizontal_distance**2 + 2*vertical_distance*displacement - displacement**2)\n            )\n        )\n        -\n        force\n    )\n\n    return residual_value\n\nif __name__ == \"__main__\":\n    a_true = 1.0\n    b_true = 1.0\n    k_true = 200.0\n\n    force_value = 10.0\n\n    v_ref = optimize.newton(\n        func=residuum,\n        fprime=grad(residuum),\n        args=(force_value, (a_true, b_true, k_true)),\n        x0=1.0\n    )\n\n    # print(v_ref)\n\n    ######\n    # Solving the Forward Problem\n    ######\n\n    theta_guess = jnp.array([0.9, 0.9, 180.0])\n    additional_args = (force_value, theta_guess)\n\n    v = optimize.newton(\n        func=residuum,\n        fprime=grad(residuum),\n        args=additional_args,\n        x0=1.0,\n    )\n\n    # The \"J\" loss function is the least-squares (quadratic loss)\n    def loss_function(v, theta):\n        return 0.5 * (v - v_ref)**2\n\n    J = loss_function(v, theta_guess)\n\n\n    ##### Adjoint Method\n\n    time_adjoint = time.time_ns()\n\n    current_args_adjoint = (v, force_value, theta_guess)\n\n    del_J__del_theta = grad(loss_function, argnums=1)(v, theta_guess).reshape((1, -1))\n    del_J__del_x = grad(loss_function, argnums=0)(v, theta_guess)\n    del_f__del_theta = grad(residuum, argnums=2)(*current_args_adjoint).reshape((1, -1))\n    del_f__del_x = grad(residuum, argnums=0)(*current_args_adjoint)\n\n    # print(del_J__del_theta)\n    # print(del_J__del_x)\n    # print(del_f__del_theta)\n    # print(del_f__del_x)\n\n    adjoint_variable = -1.0 / del_f__del_x * del_J__del_x\n\n    d_J__d_theta_adjoint = del_J__del_theta + adjoint_variable * del_f__del_theta\n\n    time_adjoint = time.time_ns() - time_adjoint\n\n    print(\"Adjoint Sensitivities using Autodiff for gradients and Jacobians\")\n    print(d_J__d_theta_adjoint)\n    print(\"Timing\")\n    print(time_adjoint)\n\n\n", "meta": {"hexsha": "eaf4bc6739ae66101588b096e7dbac0559c2118b", "size": 2667, "ext": "py", "lang": "Python", "max_stars_repo_path": "english/adjoints_sensitivities_automatic_differentiation/adjoint_univariate_nonlinear_system_using_jax.py", "max_stars_repo_name": "bartdavids/machine-learning-and-simulation", "max_stars_repo_head_hexsha": "4a4ca74e2252fa8311112e38b46ed46da3c105e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "english/adjoints_sensitivities_automatic_differentiation/adjoint_univariate_nonlinear_system_using_jax.py", "max_issues_repo_name": "bartdavids/machine-learning-and-simulation", "max_issues_repo_head_hexsha": "4a4ca74e2252fa8311112e38b46ed46da3c105e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "english/adjoints_sensitivities_automatic_differentiation/adjoint_univariate_nonlinear_system_using_jax.py", "max_forks_repo_name": "bartdavids/machine-learning-and-simulation", "max_forks_repo_head_hexsha": "4a4ca74e2252fa8311112e38b46ed46da3c105e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1603773585, "max_line_length": 101, "alphanum_fraction": 0.5946756655, "include": true, "reason": "from scipy,import jax,from jax", "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.8991213718636754, "lm_q1q2_score": 0.8518105476794293}}
{"text": "\"\"\"\nComputing pi with parallel quadrature formula\n\"\"\"\nimport numpy\nfrom mpi4py import MPI\nimport sys\n\ncomm = MPI.COMM_WORLD\nmynode = comm.Get_rank()\ntotalnodes = comm.Get_size()\n\ndef fun(x):\n    return (4.0/(1.0 + x*x))\n\ntruepi = 3.141592653589793238462643\ndest = 0\npi = numpy.zeros(1)\n\n# Initialize value of n only if this is rank 0\n# we are not checking the input, if the user does something that\n# has no meaning we are going to fail badly!\nif mynode == 0:\n    if len(sys.argv) == 1:\n        n = numpy.full(1, 20, dtype=int) # default value\n    else:\n        n = numpy.full(1,int(sys.argv[1]),dtype=int)\nelse:\n    n = numpy.zeros(1, dtype=int)\n\n# Broadcast n to all processes\ncomm.Bcast(n, root=0)\n\n# Compute local integral\nmy_pi = numpy.zeros(1)\nh = 1.0/(n*totalnodes)\nfor i in numpy.arange(1+mynode*n,n*(mynode+1)+1):\n    x = h*(i - 0.5)\n    my_pi = my_pi + fun(x)    \nmy_pi = h*my_pi\n\n# Send partition back to root process:\ncomm.Reduce(my_pi, pi, MPI.SUM, dest)\n\n# Only print the result in process 0\nif mynode == 0:\n    print('The Integral Sum =', pi[0],\" The Error is \",numpy.abs(pi[0]-truepi))\n", "meta": {"hexsha": "c5c9c2d8349dde157bae438ac3a552c7709bf869", "size": 1102, "ext": "py", "lang": "Python", "max_stars_repo_path": "quadrature.py", "max_stars_repo_name": "Cirdans-Home/intrompi", "max_stars_repo_head_hexsha": "8d5106057084640f349ce6d46f446bb282317c8e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quadrature.py", "max_issues_repo_name": "Cirdans-Home/intrompi", "max_issues_repo_head_hexsha": "8d5106057084640f349ce6d46f446bb282317c8e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quadrature.py", "max_forks_repo_name": "Cirdans-Home/intrompi", "max_forks_repo_head_hexsha": "8d5106057084640f349ce6d46f446bb282317c8e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4468085106, "max_line_length": 79, "alphanum_fraction": 0.6633393829, "include": true, "reason": "import numpy", "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.8962513675912912, "lm_q1q2_score": 0.8518071379243367}}
{"text": "\"\"\"\nThis module assumes that all geometrical points are\nrepresented as 1D numpy arrays.\n\nIt was designed and tested on 2D points,\nbut if you try it on 3D points you may\nbe pleasantly surprised ;-) \n\"\"\"\nimport numpy as np\n\n\ndef point_distance(x, y):\n    \"\"\"Returns euclidean distance between points x and y\"\"\"\n    return np.linalg.norm(x-y)\n\ndef point_projected_on_line(line_s, line_e, point):\n    \"\"\"Project point on line that goes through line_s and line_e\n\n    assumes line_e is not equal or close to line_s\n    \"\"\"\n    line_along = line_e - line_s\n    \n    transformed_point = point - line_s\n    \n    point_dot_line  = np.dot(transformed_point, line_along)\n    line_along_norm = np.dot(line_along, line_along)\n    \n    transformed_projection = (point_dot_line / line_along_norm) * line_along\n    \n    return transformed_projection + line_s\n\ndef point_segment_distance(segment_s, segment_e, point):\n    \"\"\"Returns distance from point to the closest point on segment\n    connecting points segment_s and segment_e\"\"\"\n    projected = point_projected_on_line(segment_s, segment_e, point)\n    if np.isclose(point_distance(segment_s, projected) + point_distance(projected, segment_e),\n        point_distance(segment_s, segment_e)):\n        # projected on segment\n        return point_distance(point, projected)\n    else:\n        return min(point_distance(point, segment_s), point_distance(point, segment_e))\n", "meta": {"hexsha": "86ce07bc707b357de35ea1d7300ee5b37764c497", "size": 1404, "ext": "py", "lang": "Python", "max_stars_repo_path": "tf_rl/utils/geometry.py", "max_stars_repo_name": "EvgenyKarikov/tensorflow-deepq", "max_stars_repo_head_hexsha": "1efd687a3bc5f7812f95893968742fbad6981bd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1094, "max_stars_repo_stars_event_min_datetime": "2015-11-13T22:47:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-14T12:46:37.000Z", "max_issues_repo_path": "tf_rl/utils/geometry.py", "max_issues_repo_name": "EvgenyKarikov/tensorflow-deepq", "max_issues_repo_head_hexsha": "1efd687a3bc5f7812f95893968742fbad6981bd4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2015-11-15T18:55:56.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-14T17:15:23.000Z", "max_forks_repo_path": "tf_rl/utils/geometry.py", "max_forks_repo_name": "EvgenyKarikov/tensorflow-deepq", "max_forks_repo_head_hexsha": "1efd687a3bc5f7812f95893968742fbad6981bd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 298, "max_forks_repo_forks_event_min_datetime": "2015-11-15T11:46:46.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-14T00:26:44.000Z", "avg_line_length": 33.4285714286, "max_line_length": 94, "alphanum_fraction": 0.7307692308, "include": true, "reason": "import numpy", "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561712637256, "lm_q2_score": 0.8791467801752451, "lm_q1q2_score": 0.8517667834194201}}
{"text": "import numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\n\nfrom O5 import prepare_data_wine\n\n# 1. Standardizing data\n\nX_train, X_test, y_train, y_test, df_wine = prepare_data_wine(standardize=True,\n                                                              split=True,\n                                                              dataframe=True)\n\n# 2. Constructing covariance matrix\n\n# After completing the mandatory preprocessing by executing the preceding code,\n# let's advance to the second step: constructing the covariance matrix.\n# The symmetric d×d-dimensional covariance matrix, where d is the number of\n# dimensions in the dataset, stores the pairwise covariances between the\n# different features. For example, the covariance between two features, x(j)\n# and x(k) , on the population level can be calculated via the following\n# equation:\n#       σ(jk) = (1 / (n - 1) ) * ∑(i=1, n) (x(j, i) - μ(j))(x(k, i) - μ(k))\n\n# Here, μμ jj and μμ kk are the sample means of features j and k, respectively.\n# Note that the sample means are zero if we standardized the dataset. A\n# positive covariance between two features indicates that the features increase\n# or decrease together, whereas a negative covariance indicates that the\n# features vary in opposite directions. For example, the covariance matrix of\n# three features can then be written as follows (note that Σ stands for the\n# Greek uppercase letter sigma, which is not to be confused with summation\n# symbol:\n#       Σ = [σ(1)^2 σ(1,2) σ(1, 3);σ(2,1) σ(2)^2 σ(2, 3);σ(3,1) σ(3, 2) σ(3)^2]\n\n# The eigenvectors of the covariance matrix represent the principal components\n# (the directions of maximum variance), whereas the corresponding eigenvalues\n# will define their magnitude. In the case of the Wine dataset, we would obtain\n# 13 eigenvectors  and eigenvalues from the 13 × 13 -dimensional covariance\n# matrix.\n\n# Now, for our third step, let's obtain the eigenpairs of the covariance\n# matrix. As you will remember from our introductory linear algebra classes, an\n# eigenvector, v, satisfies the following condition:\n#       Σv = λv\n# Here, λ is a scalar: the eigenvalue.\n\ncov_mat = np.cov(X_train.T)\n\n# 3. Obtaining the eigenvalues and eigenvectors of the covariance matrix.\n\neigen_values, eigen_vectors = np.linalg.eig(cov_mat)\nprint(f\"EigenValues \\n{eigen_values}\")\n\n# The numpy.linalg.eig function was designed to operate on\n# both symmetric and non-symmetric square matrices. However,\n# you may find that it returns complex eigenvalues in certain\n# cases.\n# A related function, numpy.linalg.eigh , has been\n# implemented to decompose Hermetian matrices, which is a\n# numerically more stable approach to working with symmetric\n# matrices such as the covariance matrix; numpy.linalg.eigh\n# always returns real eigenvalues.\n\n\n# Since we want to reduce the dimensionality of our dataset by compressing it\n# onto a new feature subspace, we only select the subset of the eigenvectors\n# (principal components) that contains most of the information (variance). The\n# eigenvalues define the magnitude of the eigenvectors, so we have to sort the\n# eigenvalues by decreasing magnitude; we are interested in the top k\n# eigenvectors based on the values of their corresponding eigenvalues. But\n# before we collect those k most informative eigenvectors, let's plot the\n# variance explained ratios of the eigenvalues. The variance explained ratio of\n# an eigenvalue, λ(j) , is simply the fraction of an eigenvalue, λ(j) and the\n# total sum of eigenvalues:\n#       Explained variance ratio = λ(j) / ∑(i=1, d)λ(i)\n\n# Using the NumPy cumsum function, we can then calculate the cumulative sum of\n# explained variances, which we will then plot via Matplotlib's step function:\n\ntotal = sum(eigen_values)\nexplained_variance = [(i / total) for i in sorted(eigen_values, reverse=True)]\ncumulative_sum_explained_variance = np.cumsum(explained_variance)\n\nplt.bar(range(1, 14), explained_variance, alpha=0.5, align='center',\n        label='Individual explained variance')\n\nplt.step(range(1, 14), cumulative_sum_explained_variance, where='mid',\n         label='Cumulative explained variance')\nplt.ylabel('Explained variance ratio')\nplt.xlabel('Principal component index')\nplt.legend(loc='best')\nplt.tight_layout()\nplt.show()\n\n# The resulting plot indicates that the first principal component alone\n# accounts for approximately 40 percent of the variance.\n# Also, we can see that the first two principal components combined explain\n# almost 60 percent of the variance in the dataset\n# we should remind ourselves that PCA is an unsupervised method, which means\n# that information about the class labels is ignored. Whereas a random forest\n# uses the class membership information to compute the node impurities,\n# variance measures the spread of values along a feature axis.\n\n# 4. Sorting the eigenvalues by decreasing order to rank the eigenvectors\neigen_pairs = [(np.abs(eigen_values[i]), eigen_vectors[:, i])\n               for i in range(len(eigen_values))]\n\neigen_pairs = sorted(eigen_pairs, key=lambda x: x[0], reverse=True)\n\n# 5. Select k(here k=2) eigenvectors, which correspond to the k largest\n# eigenvalues, where k is the dimensionality of the new feature subspace\n# (k <= d)\n\n# Now, we collect the two eigenvectors that correspond to the two largest\n# eigenvalues, to capture about 60 percent of the variance in this dataset.\n# Note that two eigenvectors have been chosen for the purpose of illustration,\n# since we are going to plot the data via a two-dimensional scatter plot later\n# in this subsection. In practice, the number of principal components has to be\n# determined by a tradeoff between computational efficiency and the performance\n# of the classifier.\nfirst_eigenvalue_vector = eigen_pairs[0][1]\nsecond_eigenvalue_vector = eigen_pairs[1][1]\n\n# 6. Construct a projection matrix, W, from the \"top\" k eigenvectors\n\nw = np.hstack((first_eigenvalue_vector[:, np.newaxis],\n               second_eigenvalue_vector[:, np.newaxis]))\nprint(w)\n\n# 7. Transform the d-dimensional input dataset, X, using the projection matrix,\n# W, to obtain the new k-dimensional feature subspace.\n#       Transformation: x' = xW for x ∈ X\nprint(X_train[0].dot(w))\n\n# Or full transformation: X' = XW\n\nX_train_pcs = X_train.dot(w)\ncolors = ['red', 'blue', 'green']\nmarkers = ['s', 'x', 'o']\nfor l, c, m in zip(np.unique(y_train), colors, markers):\n    plt.scatter(X_train_pcs[y_train == l, 0],\n                X_train_pcs[y_train == l, 1],\n                c=c, label=l, marker=m)\n\nplt.xlabel('PC 1')\nplt.ylabel('PC 2')\nplt.legend(loc='lower left')\nplt.tight_layout()\nplt.show()\n# As we can see in the resulting plot, the data is more spread along the x-axis\n# —the first principal component—than the second principal component (y-axis),\n# which is consistent with the explained variance ratio plot that we created in\n# the previous subsection. However, we can tell that a linear classifier will\n# likely be able to separate the classes well.\n# Although we encoded the class label information for the purpose of\n# illustration in the preceding scatter plot, we have to keep in mind that PCA\n# is an unsupervised technique that doesn't use any class label information.\n", "meta": {"hexsha": "d0cd0c01bc23c65baf97a59210dec44783c63349", "size": 7217, "ext": "py", "lang": "Python", "max_stars_repo_path": "O5/_24_principal_component_analysis/pca.py", "max_stars_repo_name": "ShAlireza/ML-Tries", "max_stars_repo_head_hexsha": "4516be7a3275c9bdedd7bd258800be384b6b34f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "O5/_24_principal_component_analysis/pca.py", "max_issues_repo_name": "ShAlireza/ML-Tries", "max_issues_repo_head_hexsha": "4516be7a3275c9bdedd7bd258800be384b6b34f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "O5/_24_principal_component_analysis/pca.py", "max_forks_repo_name": "ShAlireza/ML-Tries", "max_forks_repo_head_hexsha": "4516be7a3275c9bdedd7bd258800be384b6b34f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6772151899, "max_line_length": 79, "alphanum_fraction": 0.7411666898, "include": true, "reason": "import numpy", "num_tokens": 1732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561721629776, "lm_q2_score": 0.8791467785920306, "lm_q1q2_score": 0.8517667826760875}}
{"text": "#!/usr/bin/env python3\n# coding=utf-8\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nloc = 10.0\nscale = 1.0\n\ndata = np.random.normal(loc, scale, size=6000)\n\n# http://blog.csdn.net/lanchunhui/article/details/50163669\n# 高斯分布（Gaussian Distribution）的概率密度函数（probability density function）\nx_data = np.linspace(data.min(), data.max())\nplt.plot(x_data, 1. / (np.sqrt(2 * np.pi) * scale) * np.exp(-(x_data - loc) ** 2 / (2 * scale ** 2)))\n\ncount, bins, _ = plt.hist(data, 30, normed=True)\n# plt.plot(bins, 1. / (np.sqrt(2 * np.pi) * scale) * np.exp(-(bins - loc) ** 2 / (2 * scale ** 2)))\n\nplt.show()\n\n\n# Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2\nmu, sigma = 2, 0.5\nv = np.random.normal(mu, sigma, 5000)\n# Plot a normalized histogram with 50 bins\nplt.hist(v, bins=50, normed=1)  # matplotlib version (plot)\n\n# Compute the histogram with numpy and then plot it\n(n, bins) = np.histogram(v, bins=50, normed=True)  # NumPy version (no plot)\nplt.plot(.5 * (bins[1:] + bins[:-1]), n)\n\nplt.grid(True)\n\nplt.show()\n", "meta": {"hexsha": "1ad7089aed541f88d0007d0375af641a9a855ca8", "size": 1033, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python3Test/matplotlib/numpy_mean_std.py", "max_stars_repo_name": "qianhk/FeiPython", "max_stars_repo_head_hexsha": "c87578d3c04b7345a99fef7390c8ea12c6f2c716", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python3Test/matplotlib/numpy_mean_std.py", "max_issues_repo_name": "qianhk/FeiPython", "max_issues_repo_head_hexsha": "c87578d3c04b7345a99fef7390c8ea12c6f2c716", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2019-11-18T06:09:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T02:55:54.000Z", "max_forks_repo_path": "Python3Test/matplotlib/numpy_mean_std.py", "max_forks_repo_name": "qianhk/FeiPython", "max_forks_repo_head_hexsha": "c87578d3c04b7345a99fef7390c8ea12c6f2c716", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9189189189, "max_line_length": 101, "alphanum_fraction": 0.6640851888, "include": true, "reason": "import numpy", "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561721629777, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.8517667765404593}}
{"text": "import math\nimport random\nimport scipy.special\nimport scipy.optimize\n\nPI    = 3.1415926535897932384626433832795\nSQRT2 = 1.4142135623730950488016887242097\n\ndef Phi(z):\n    \"\"\"\n    The cumulative function of the unit gaussian distribution\n    \"\"\"\n\n    return  0.5 * (1.0 + scipy.special.erf(z / SQRT2))\n\ndef phi(z):\n    \"\"\"\n    PDF of the standard gaussian distribution\n    \"\"\"\n\n    return (1.0 / math.sqrt(2.0*PI)) * math.exp(-0.5 * z * z)\n\ndef SampleTG(mu, sigma, a, b):\n    \"\"\"\n    Sample from\n    \"\"\"\n\n    if sigma <= 0.0:\n        raise ValueError(\"Sample: non-positive sigma\")\n\n    # for a moment, work with true bounded gaussian\n    if math.isinf(a):\n        raise ValueError(\"Sample: infinite a\")\n    if math.isinf(b):\n        raise ValueError(\"Sample: infinite b\")\n\n    if a >= b:\n        raise ValueError(\"Sample: a >= b\")\n\n    while True:\n        r = random.gauss(mu, sigma)\n        if r >= a and r <= b:\n            return r\n\n    return math.Inf\n\ndef Mean(mu, sigma, a, b):\n    \"\"\"\n    Mean for truncated gaussian\n    \"\"\"\n\n    if sigma <= 0.0:\n        raise ValueError(\"Mean: non-positive sigma\")\n\n    # for a moment, work with true bounded gaussian\n    if math.isinf(a):\n        raise ValueError(\"Mean: infinite a\")\n    if math.isinf(b):\n        raise ValueError(\"Mean: infinite b\")\n\n    if a >= b:\n        raise ValueError(\"Mean: a >= b\")\n\n    alfa = (a - mu) / sigma\n    beta = (b - mu) / sigma\n\n    Z = Phi(beta) - Phi(alfa)\n\n    return mu + sigma*(phi(alfa) - phi(beta))/Z\n\ndef f(mu, mean, sigma, a, b):\n    \"\"\"\n    Function to search for true mu when particular mean is requested\n    Root of this function would be right mu\n    \"\"\"\n    return mean - Mean(mu, sigma, a, b)\n\nif __name__ == \"__main__\":\n\n    random.seed(12345)\n\n    # some test printouts\n    # print(phi(0.0))\n    # print(Phi(0.0))\n\n    a = 50000.0\n    b = 250000.0\n    mean = 70000.0\n    sigma = 24000.0\n\n    mu = scipy.optimize.brentq(f, a, b, args=(mean, sigma, a, b))\n    print(\"Found mu = {0} for the desired mean {1} and sigma {2}\".format(mu, mean, sigma))\n\n    # test sampling\n\n    N  = 100000\n    s  = 0.0\n    s2 = 0.0\n    for k in range(0, N):\n        q   = SampleTG(mu, sigma, a, b)\n        if q < a:\n            raise ValueError(\"Test: sampled value below a\")\n        if q > b:\n            raise ValueError(\"Test: sampled value above b\")\n        s  += q\n        s2 += q*q\n\n    print(\"Sampled {0} truncated gaussians and got observed mean = {1}\".format(N, s/float(N)))\n", "meta": {"hexsha": "c68ec3211ce9e6b44f1264d98bfe09b780d4fbf0", "size": 2457, "ext": "py", "lang": "Python", "max_stars_repo_path": "truncgauss.py", "max_stars_repo_name": "Kri-Ol/Truncated-Gauss", "max_stars_repo_head_hexsha": "429e0947dc28d2940081ce7b080fd148689b9248", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "truncgauss.py", "max_issues_repo_name": "Kri-Ol/Truncated-Gauss", "max_issues_repo_head_hexsha": "429e0947dc28d2940081ce7b080fd148689b9248", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "truncgauss.py", "max_forks_repo_name": "Kri-Ol/Truncated-Gauss", "max_forks_repo_head_hexsha": "429e0947dc28d2940081ce7b080fd148689b9248", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5412844037, "max_line_length": 94, "alphanum_fraction": 0.571021571, "include": true, "reason": "import scipy", "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561667674651, "lm_q2_score": 0.8791467627598857, "lm_q1q2_score": 0.8517667625935689}}
{"text": "\"\"\"\nThe prime factors of 13195 are 5, 7, 13 and 29.\nWhat is the largest prime factor of the number 600851475143 ?\n\nhttps://projecteuler.net/problem=3\n\"\"\"\n\nimport numpy as np\n\n# To determine if a number n is prime, we need to:\n# 1. check whether n is evenly divisible by 2\n# 2. check whether n is evenly divisible by one of the uneven numbers from 3 to sqrt(n) + 1\n# 3. if neither 1 nor 2 apply, n is prime\n\n# To find the largest prime factor of n, we repeatedly divide n by its smallest prime factor\n# until we can't divide it further.\n\ndef find_smallest_prime_factor(number):\n    upper_bound = int(np.sqrt(number)) + 1\n\n    for i in range(2, upper_bound):\n        if number % i == 0:\n            return i\n\n    return number\n\n\ndef find_largest_prime_factor(number):\n    while True:\n        smallest_factor = find_smallest_prime_factor(number)\n\n        if smallest_factor < number:\n            number //= smallest_factor\n        else:\n            return number\n\n\nresult = find_largest_prime_factor(600851475143)\nprint('result: ', result)\n\n\n\n\n", "meta": {"hexsha": "a88a2e4a58ef14b27de8279fb7f0559d447d9c03", "size": 1041, "ext": "py", "lang": "Python", "max_stars_repo_path": "problem003.py", "max_stars_repo_name": "gboluwaga/ProjectEuler", "max_stars_repo_head_hexsha": "079496db04f1c3b6d2e421f8dd4db46b3f76b465", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-07-25T08:58:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-13T05:48:22.000Z", "max_issues_repo_path": "problem003.py", "max_issues_repo_name": "gboluwaga/ProjectEuler", "max_issues_repo_head_hexsha": "079496db04f1c3b6d2e421f8dd4db46b3f76b465", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem003.py", "max_forks_repo_name": "gboluwaga/ProjectEuler", "max_forks_repo_head_hexsha": "079496db04f1c3b6d2e421f8dd4db46b3f76b465", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2018-08-11T10:05:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-09T14:50:56.000Z", "avg_line_length": 23.6590909091, "max_line_length": 92, "alphanum_fraction": 0.6868395773, "include": true, "reason": "import numpy", "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561667674652, "lm_q2_score": 0.879146761176671, "lm_q1q2_score": 0.8517667610596616}}
{"text": "\"\"\"\nWrite a Python code that fulfills the following specification.\ndataset: Female_Stats.csv\n\n\nThe Data Are From 214 Females In Statistics Classes At \nThe University Of California At Davis.\n\nColumn1 = Student’s Self-Reported Height,\n\nColumn2 = Student’s Guess At Her Mother’s Height, And\n\nColumn 3 = Student’s Guess At Her Father’s Height. \n\nAll Heights Are In Inches.\n\ntask01:\nBuild A Predictive Model And Conclude If Both Predictors \n(Independent Variables) Are Significant For A Students’ Height Or Not?\n(Use pvalue concepts).\n\ntask02:\nWhen Father’s Height Is Held Constant, \nThe Average Student Height Increases \nBy How Many Inches For Each One-Inch Increase In Mother’s Height.\n\ntask03:\nWhen Mother’s Height Is Held Constant, \nThe Average Student Height Increases \nBy How Many Inches For Each One-Inch Increase In Father’s Height.\n\n\"\"\"\n\n\n\n# Importing the libraries\nimport numpy as np\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('Female_Stats.csv')\n\n# Check data Types for each columns\nprint(dataset.dtypes)\n\n# Seperate Features and Labels\nfeatures = dataset.iloc[:,1:].values\nlabels = dataset.iloc[:, [0]].values\n\n# Check Column wise is any data is missing or NaN\ndataset.isnull().any(axis=0)\n\n\nfrom sklearn.model_selection import train_test_split\nfeatures_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size = 0.2, random_state = 0)\n\n\n# Fitting Multiple Linear Regression to the Training set\n# Whether we have Univariate or Multivariate, class is LinearRegression\n\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(features_train, labels_train)\n\nPred = regressor.predict(features_test)\n\nprint (pd.DataFrame(zip(np.round(Pred,2), labels_test)))\n\n\n\nimport statsmodels.api as sm\n\nfeatures_sm = sm.add_constant(features)\nest = sm.OLS(labels, features_sm)\nest2 = est.fit()\n\nprint (est2.summary())\n\n\"\"\"\nas both columns ( mom and dad are having p values less than 5%, both \n                 heights are significant for student's height)\n\"\"\"\n\n\"\"\"\n\nWhen Father’s Height Is Held Constant, \nThe Average Student Height Increases \nBy How Many Inches For Each One-Inch Increase In Mother’s Height.\n\n\"\"\"\n\nprint (regressor.coef_[0][0])\n\n\n\"\"\"\n\nWhen Mother’s Height Is Held Constant, \nThe Average Student Height Increases \nBy How Many Inches For Each One-Inch Increase In Father’s Height.\n\n\n\n\"\"\"\nprint (regressor.coef_[0][1])\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Version 2 of solution \n\n\n\n\nimport pandas as pd\nimport numpy as np\n\ndataset=pd.read_csv(\"stats_females.csv\")\n\nfeatures=dataset.iloc[:,1:]\nlabels=dataset.iloc[:,0]\n\nfrom sklearn.model_selection import train_test_split\nfeatures_train,features_test,labels_train,labels_test=train_test_split(features,labels,test_size=0.2,random_state=0)\n\nfrom sklearn.linear_model import LinearRegression\nreg=LinearRegression()\nreg.fit(features_train,labels_train)\n\nimport statsmodels.formula.api as sm\nfeatures=np.append(arr=np.ones((214,1)).astype(int),values=features,axis=1)\n\nfeatures_opt=features[:,[0,1,2]]\nregressor_OLS=sm.OLS(labels,features_opt).fit()\nregressor_OLS.summary()\n\n\"\"\"\nWhen Father’s Height Is Held Constant, The Average Student Height Increases \nBy How Many Inches For Each One-Inch Increase In Mother’s Height.\n\"\"\"\nprint(\"When Father's Height is Held Constant then the average height increase by\",regressor_OLS.params[1])\n\nprint(\"When Mother's Height is Held Constant then the average height increase by\",regressor_OLS.params[2])", "meta": {"hexsha": "f8e9e66574d09c886d6daa9c4a048f930eddbf0c", "size": 3483, "ext": "py", "lang": "Python", "max_stars_repo_path": "day-42 challenge/Female_Stats.py", "max_stars_repo_name": "itsjaysuthar/DSintern", "max_stars_repo_head_hexsha": "985eb1d13d52d817148fea931597072f9a23fc33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day-42 challenge/Female_Stats.py", "max_issues_repo_name": "itsjaysuthar/DSintern", "max_issues_repo_head_hexsha": "985eb1d13d52d817148fea931597072f9a23fc33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day-42 challenge/Female_Stats.py", "max_forks_repo_name": "itsjaysuthar/DSintern", "max_forks_repo_head_hexsha": "985eb1d13d52d817148fea931597072f9a23fc33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.237804878, "max_line_length": 128, "alphanum_fraction": 0.7677289693, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877658567786, "lm_q2_score": 0.877476793890012, "lm_q1q2_score": 0.8517559886522648}}
{"text": "from scipy import signal as sig\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\n\n\ndef gaussian_2d_kernel(ker_shape, sigm):\n    \"\"\"\n    Creates gaussian kernel\n\n    :param ker_shape: Used in defining kernel's shape\n    :param sigm: sigma parameter for equation\n    :return: Gaussian kernel with shape of `ker_shape`\n    \"\"\"\n    ker = np.zeros(ker_shape)\n    ind = np.arange(-np.floor(ker_shape[0] / 2), np.floor(ker_shape[1] / 2) + 1, 1)\n    XX, YY = np.meshgrid(ind, ind)\n\n    for row in range(ker_shape[0]):\n        for col in range(ker_shape[1]):\n            ker[row, col] = (1 / 2 * np.pi * sigm ** 2) * np.exp(\n                (-1 * (XX[0, col] ** 2 + YY[row, 0] ** 2) / (2 * sigm ** 2)))\n\n    return ker\n\n\ndef laplacian_of_gaussian_2d_kernel(ker_shape, sigm):\n    \"\"\"\n    Creates laplacian of gaussian kernel\n\n    :param ker_shape: Used in defining kernel's shape\n    :param sigm: sigma parameter for equation\n    :return: LoG kernel with shape of `ker_shape`\n    \"\"\"\n    ker = np.zeros(ker_shape)\n    ind = np.arange(-np.floor(ker_shape[0] / 2), np.floor(ker_shape[1] / 2) + 1, 1)\n    XX, YY = np.meshgrid(ind, ind)\n\n    for row in range(ker_shape[0]):\n        for col in range(ker_shape[1]):\n            ker[row, col] = (-1 / (np.pi * sigm ** 4)) * (1 - (XX[0, col] ** 2 + YY[row, 0] ** 2) / (2 * sigm ** 2)) * \\\n                               np.exp((-1 * (XX[0, col] ** 2 + YY[row, 0] ** 2) / (2 * sigm ** 2)))\n\n    return -ker\n\n\ndef normalize(arr):\n    \"\"\"\n    Normalize image between 0-255\n\n    :param arr: Going to be normalized array\n    :return: Normalized array\n    \"\"\"\n    arr = arr / arr.max(initial=0) * 255\n    arr = np.uint8(arr)\n    return arr\n\n\ndef apply_filter(arr, ker):\n    \"\"\"\n    Makes convolution operation\n\n    :param arr: Going to be convolved\n    :param ker: Convolution operation kernel\n    :return: Convolved image\n    \"\"\"\n    return sig.convolve2d(arr, ker, mode='same')\n\n\ndef show_image(*argv):\n    \"\"\"\n    Plot images in order\n\n    :param argv: Needs to be passed grayscale images\n    \"\"\"\n    for arg in argv:\n        plt.imshow(arg, cmap='gray')\n        plt.show()\n\n\nif __name__ == '__main__':\n    try:\n        img = cv2.imread('../test_images/test.png', cv2.IMREAD_GRAYSCALE)\n\n        if img is None:\n            raise ValueError(\"File don't exist!\")\n\n        else:\n            sigma = 1\n            kernel_shape = (7, 7)\n\n            gaussian_kernel = gaussian_2d_kernel(kernel_shape, sigma)\n            log_kernel = laplacian_of_gaussian_2d_kernel(kernel_shape, sigma)\n\n            gaussian_result = normalize(apply_filter(img, gaussian_kernel))\n            log_result = normalize(apply_filter(img, log_kernel))\n            log_after_gaussian_result = normalize(apply_filter(apply_filter(img, gaussian_kernel), log_kernel))\n\n            show_image(img, gaussian_result, log_result, log_after_gaussian_result)\n\n    except ValueError as ve:\n        print(ve)\n", "meta": {"hexsha": "9edaa3133175e554b6e901567fa14160d5324836", "size": 2911, "ext": "py", "lang": "Python", "max_stars_repo_path": "gaussian_and_log_filtering/main.py", "max_stars_repo_name": "omerferhatt/computer-vision", "max_stars_repo_head_hexsha": "7abfe3c9526db78438ca07008d1c628d4267f8c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gaussian_and_log_filtering/main.py", "max_issues_repo_name": "omerferhatt/computer-vision", "max_issues_repo_head_hexsha": "7abfe3c9526db78438ca07008d1c628d4267f8c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gaussian_and_log_filtering/main.py", "max_forks_repo_name": "omerferhatt/computer-vision", "max_forks_repo_head_hexsha": "7abfe3c9526db78438ca07008d1c628d4267f8c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2621359223, "max_line_length": 120, "alphanum_fraction": 0.6032291309, "include": true, "reason": "import numpy,from scipy", "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347845918814, "lm_q2_score": 0.8740772450055545, "lm_q1q2_score": 0.8517312719536526}}
{"text": "import numpy as np\n\n\ndef sigmoid_activation(z):\n    \"\"\"\n    Sigmoid (or “logit”) activation function.\n\n    converts a continuous input into a probability value [0,1],\n        which can be interpreted as the class probability,\n        or the likelihood that the input example should be classified positively.\n    Using this probability along with a threshold value, we can obtain a discrete label prediction.\n    \"\"\"\n    return 1 / (1 + np.exp(-z))\n\n\n# # visualize the sigmoid activation function’s output (to see what it’s really doing):\n# nums = np.arange(-10, 10, step=1)\n# fig, ax = plt.subplots(figsize=(12,8))\n# ax.plot(nums, sigmoid(nums), 'r')\n\n\ndef mse_loss(X, y, theta):\n    \"\"\"\n    Mean Squared Error (MSE) loss.\n    The cost function for linear regression.\n    \"\"\"\n    y_pred = X * theta.T\n    error = y_pred - y\n    return np.sum(np.power(error, 2)) / (2 * len(X))\n\n\ndef log_loss(theta, x, y, learning_rate=None):\n    \"\"\"\n    Binary cross-entropy / log loss.\n    The cost function for binary (linear) logistic regression.\n\n    Evaluates the current model's parameters' performance on the training data.\n    Determines: \"given some candidate solution theta applied to input X,\n        how far off is the result from the true desired outcome y\".\n\n    Note that we reduce the output down to a single scalar value, which is the sum of the “error” quantified as a\n    function of the difference between the class probability assigned by the model and the true label of the example.\n    The implementation is completely vectorized – it’s computing the model’s predictions for the whole dataset\n    in one statement (sigmoid(X * theta.T)).\n    the variable called “reg” is a function of the parameter values.\n        As the parameters get larger, the penalization added to the cost function increases.\n    the “learning rate” parameter is also part of the regularization term in the equation.\n        The learning rate gives us a new hyper-parameter that we can use to tune how much weight the regularization holds in the cost function.\n    \"\"\"\n    # theta = np.matrix(theta)\n    # x = np.matrix(X)\n    # y = np.matrix(y)\n    first = np.multiply(-y, np.log(sigmoid_activation(x * theta.T)))\n    second = np.multiply((1 - y), np.log(1 - sigmoid_activation(x * theta.T)))\n    if learning_rate is None:\n        return np.sum(first - second) / (len(x))\n    else:\n        reg = (learning_rate / 2 * len(x)) * np.sum(np.power(theta[:, 1:theta.shape[1]], 2))\n        return np.sum(first - second) / (len(x)) + reg\n\n\ndef softmax_loss(theta, x, y, learning_rate=None):\n    \"\"\"\n    Categorical cross-entropy / softmax loss.\n    The cost function for multi-class logistic regression.\n    \"\"\"\n    # theta = np.matrix(theta)\n    # x = np.matrix(X)\n    # y = np.matrix(y)\n    first = np.multiply(-y, np.log(sigmoid_activation(x * theta.T)))\n    second = np.multiply((1 - y), np.log(1 - sigmoid_activation(x * theta.T)))\n    if learning_rate is None:\n        return np.sum(first - second) / (len(x))\n    else:\n        reg = (learning_rate / 2 * len(x)) * np.sum(np.power(theta[:, 1:theta.shape[1]], 2))\n        return np.sum(first - second) / (len(x)) + reg\n\n\ndef single_gradient_step(theta, x, y, learning_rate=None):  # gradient\n    \"\"\"\n    a function to compute the gradient of the model parameters to figure out how to change the parameters\n    to improve the outcome of the model on the training data.\n    Recall that with gradient descent we don’t just randomly jigger around the parameter values and see what works best.\n    At each training iteration we update the parameters in a way that’s guaranteed to move them in a direction\n    that reduces the training error (i.e. the “cost”).\n    We can do this because the cost function is differentiable.\n    Note that we don't actually perform gradient descent in this function - we just compute a single gradient step.\n    the gradient function specifies how to change those parameters to get an answer that's slightly better than the one we've already got\n    \"\"\"\n    # theta = np.matrix(theta)\n    # x = np.matrix(X)\n    # y = np.matrix(y)\n\n    error = sigmoid_activation(x * theta.T) - y\n\n    # more generalized way:\n    if learning_rate is None:\n        grad = ((x.T * error) / len(x)).T\n    else:\n        reg = (learning_rate / len(x)) * theta\n        grad = ((x.T * error) / len(x)).T + reg\n\n    grad[0, 0] = np.sum(np.multiply(error, x[:, 0])) / len(x)  # intercept gradient is not regularized\n    return np.array(grad).ravel()\n\n    # more specific way:\n    # parameters = int(theta.ravel().shape[1])\n    # grad = np.zeros(parameters)\n    # for i in range(parameters):\n    #     term = np.multiply(error, X[:, i])\n    #     if learning_rate is None or i == 0:  # the first parameter is not regularized, it's considered the “bias” or “intercept” of the model and shouldn’t be penalized\n    #         grad[i] = np.sum(term) / len(X)\n    #     else:\n    #         reg = (learningRate / len(X)) * theta[:, i]\n    #         grad[i] = (np.sum(term) / len(X)) + reg\n    # return grad\n", "meta": {"hexsha": "9475acdbc0776a78d95b3d5b691cb0c85ff70be5", "size": 5029, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine_learning/utils.py", "max_stars_repo_name": "EliorBenYosef/data-science", "max_stars_repo_head_hexsha": "117e5254f63e482c02aff394780bbdc205d492a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "machine_learning/utils.py", "max_issues_repo_name": "EliorBenYosef/data-science", "max_issues_repo_head_hexsha": "117e5254f63e482c02aff394780bbdc205d492a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "machine_learning/utils.py", "max_forks_repo_name": "EliorBenYosef/data-science", "max_forks_repo_head_hexsha": "117e5254f63e482c02aff394780bbdc205d492a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9829059829, "max_line_length": 170, "alphanum_fraction": 0.6587790813, "include": true, "reason": "import numpy", "num_tokens": 1231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347905312772, "lm_q2_score": 0.8740772368049822, "lm_q1q2_score": 0.8517312691542204}}
{"text": "import codecademylib3_seaborn\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import datasets\nfrom copy import deepcopy\n\niris = datasets.load_iris()\n\nsamples = iris.data\nsamples = iris.data\n\nx = samples[:,0]\ny = samples[:,1]\n\nsepal_length_width = np.array(list(zip(x, y)))\n\n# Step 1: Place K random centroids\n\nk = 3\n\ncentroids_x = np.random.uniform(min(x), max(x), size=k)\ncentroids_y = np.random.uniform(min(y), max(y), size=k)\n\ncentroids = np.array(list(zip(centroids_x, centroids_y)))\n\n# Step 2: Assign samples to nearest centroid\n\ndef distance(a, b):\n  one = (a[0] - b[0]) **2\n  two = (a[1] - b[1]) **2\n  distance = (one+two) ** 0.5\n  return distance\n\n# Cluster labels for each point (either 0, 1, or 2)\nlabels = np.zeros(len(samples))\n\n# Distances to each centroid\ndistances = np.zeros(k)\n\nfor i in range(len(samples)):\n  distances[0] = distance(sepal_length_width[i], centroids[0])\n  distances[1] = distance(sepal_length_width[i], centroids[1])\n  distances[2] = distance(sepal_length_width[i], centroids[2])\n  cluster = np.argmin(distances)\n  labels[i] = cluster\n\n# Step 3: Update centroids\n\ncentroids_old = deepcopy(centroids)\n\nfor i in range(k):\n  points = [sepal_length_width[j] for j in range(len(sepal_length_width)) if labels[j] == i]\n  centroids[i] = np.mean(points, axis=0)\n  \nprint(centroids_old)\nprint(\"- - - - - - - - - - - - - -\")\nprint(centroids)", "meta": {"hexsha": "ccf752b348cdd2a0cb13d95e1b6ed1ea53875958", "size": 1381, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data Scientist Career Path/12. Foundations of Machine Learning Unsupervised Learning/1. KMeans/5. step3.py", "max_stars_repo_name": "myarist/Codecademy", "max_stars_repo_head_hexsha": "2ba0f104bc67ab6ef0f8fb869aa12aa02f5f1efb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2021-06-06T15:35:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T06:53:42.000Z", "max_issues_repo_path": "Data Scientist Career Path/12. Foundations of Machine Learning Unsupervised Learning/1. KMeans/5. step3.py", "max_issues_repo_name": "shivaniverma1/Data-Scientist", "max_issues_repo_head_hexsha": "f82939a411484311171465591455880c8e354750", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Scientist Career Path/12. Foundations of Machine Learning Unsupervised Learning/1. KMeans/5. step3.py", "max_forks_repo_name": "shivaniverma1/Data-Scientist", "max_forks_repo_head_hexsha": "f82939a411484311171465591455880c8e354750", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2021-06-08T01:32:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T15:38:09.000Z", "avg_line_length": 24.2280701754, "max_line_length": 92, "alphanum_fraction": 0.6929761043, "include": true, "reason": "import numpy", "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347897888529, "lm_q2_score": 0.8740772351648677, "lm_q1q2_score": 0.8517312669070995}}
{"text": "import numpy as np\n\ndef computeCost(X, y, theta):\n    m = len(X)\n    # Matrix multiplication of X and theta which is the hypothesis function\n    hypothesis_X = np.matmul(X, theta)\n    #print('shape', hypothesis_X.shape)\n    # Calculating difference of hypothesis and y\n    dif = hypothesis_X - y\n    # print('shape', dif.shape)\n    # Getting the Square of each individual element value\n    # Element wise product - we can also use np.multiply(dif, dif)\n    dif_sqr = dif * dif\n    # Generating a row vector to multiply to get the sum of all the elements in the matrix\n    #print('shape', dif_sqr.shape)\n    ones = np.ones(m)\n    #print('shape', ones.shape)\n    # Multiplying row vector and difference square to get cost vector\n    cost_mat = (0.5/m) * np.matmul(ones, dif_sqr)\n    # Converting matrix 1 by 1 Ex: [5] to scalar value 5\n    cost_scalar = np.asscalar(cost_mat)\n    return cost_scalar", "meta": {"hexsha": "87f666f0c243f7c98e75cfa197eff7060d868d18", "size": 896, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine-learning/coursera_exercises/ex1/in_python/exercises/cost.py", "max_stars_repo_name": "pk-ai/training", "max_stars_repo_head_hexsha": "86b0d6c74853565eab08e76054ce96083ebfd45e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-01T10:07:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-01T10:07:03.000Z", "max_issues_repo_path": "machine-learning/coursera_exercises/ex1/in_python/exercises/cost.py", "max_issues_repo_name": "pktippa/ai-training", "max_issues_repo_head_hexsha": "86b0d6c74853565eab08e76054ce96083ebfd45e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-09-27T14:42:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T03:35:18.000Z", "max_forks_repo_path": "machine-learning/coursera_exercises/ex1/in_python/exercises/cost.py", "max_forks_repo_name": "pktippa/ai-training", "max_forks_repo_head_hexsha": "86b0d6c74853565eab08e76054ce96083ebfd45e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7272727273, "max_line_length": 90, "alphanum_fraction": 0.6852678571, "include": true, "reason": "import numpy", "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347875615795, "lm_q2_score": 0.874077222043951, "lm_q1q2_score": 0.8517312521748129}}
{"text": "'''\nPower Iteration method of finding dominant eigenvector.\n\tsource : https://www.wikiwand.com/en/Power_iteration\n'''\nimport numpy as np\nfrom numpy.linalg import norm\n\n\ndef power_iteration( A, b0, tol = 0.0000001 ):\n\tn = len( b0 )\n\tb1 = getBi( A, b0, n, tol )\n\twhile norm( np.subtract( b1, b0 ), ord = n ) > tol:\n\t# for i in range(10000):\n\t\tb0 = b1\n\t\tb1 = getBi( A, b0, n )\n\treturn b1\n\ndef getBi( A, b, n, tol = 0.0000001 ):\n\tb = np.dot( A, b )\n\tb_norm = norm( b, ord = n )\n\tif b_norm < tol:\n\t\tb /= 0.0000001\n\telse:\n\t\tb /= b_norm\n\treturn b\n\ndef __test():\n\tA = np.array( [ [ 0.5, 0.5 ], [ 0.2, 0.8 ] ] )\n\tb = np.random.rand( 2 )\n\treturn power_iteration( A, b )#, np.linalg.eig( A )[1]\n\ndef __random_test( n ):\n\tA = np.random.rand( n, n )\n\tb = np.random.rand( n )\n\treturn power_iteration( A, b )#, np.linalg.eig( A )[1]\n\nif __name__ == '__main__':\n\tprint __test()\n\tprint __test()\n\tfor i in range(10, 151):\n\t\t__random_test( i )\n\tprint 'Random square matrices of sizes 10-150 completed.'", "meta": {"hexsha": "451225b0a69cf624e9ca6f9bbd78f65f66bbcea9", "size": 983, "ext": "py", "lang": "Python", "max_stars_repo_path": "project/src/power_iteration_eigenvectors.py", "max_stars_repo_name": "apjansing/MAT560_project", "max_stars_repo_head_hexsha": "e420f1462e91258ace47a43e6525d540e3ee841e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project/src/power_iteration_eigenvectors.py", "max_issues_repo_name": "apjansing/MAT560_project", "max_issues_repo_head_hexsha": "e420f1462e91258ace47a43e6525d540e3ee841e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project/src/power_iteration_eigenvectors.py", "max_forks_repo_name": "apjansing/MAT560_project", "max_forks_repo_head_hexsha": "e420f1462e91258ace47a43e6525d540e3ee841e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4047619048, "max_line_length": 58, "alphanum_fraction": 0.6174974568, "include": true, "reason": "import numpy,from numpy", "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.9005297934592089, "lm_q1q2_score": 0.8517222211100415}}
{"text": "\"\"\"\nObjetivo: Resolver questão 2a do terceiro laboratorio.\n    é exatamente o mesmo codigo da questão anterior porém mudando a função a ser passada e o palpite\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom Newton_Raphson import newton_raphson\n\n#PARA X0 = 1\ny = lambda x: 180*x**3 - 117*x**2 - 80*x + 52  # f(x) = 180x^3 - 117x^2 - 80x + 52\ny_linha = lambda x: 540*x**2 - 234*x - 80  # f'(x) = 540x^2 - 234x - 80\nini = 1  # ponto inicial\n#Verificar o arquivo Nexton-Raphson.py para entender o funcionamento dessa função\nresp = newton_raphson(ini, y, y_linha, 'q2')\nprint(f'Para essa X0 = 1 levamos {resp[\"iterações\"] - 1} iterações e temos como valor de f(x) = {resp[\"modulo\"]}')\nprint('Abaixo seguem os graficos dos valores de f(x) e dos erros, respectivamente:')\n\n# Grafico com os valores de f(x)\nx_a = np.linspace(-1.2, 1.2, 30)  # valores escolhidos para melhor visualização do grafico\ny_a = [y(i) for i in x_a]\nplt.style.use('ggplot')\nplt.figure(figsize=(7, 5))\nplt.title(f'F(x) por X\\ncom X0 = 1')\nplt.xlabel('Valores de x')\nplt.ylabel('Valores de f(x)')\n# função com valores entre 0.4 e 0.8\nplt.plot(x_a, y_a, label='Função exata')\n# Nossa aproximação Newton-Raphson por iteração\nplt.plot(resp['valores'], resp['valores_função'], label='Valores de Newton-Raphson por iteração')\nplt.tight_layout()\nplt.legend(loc='best')\nplt.show()\n\n# Grafico com os valores dos erros\nplt.style.use('ggplot')\nplt.figure(figsize=(7, 5))\nplt.title('Erro por Iterações')\nplt.xlabel('Numero de iterações')\nplt.ylabel('Valores dos erros')\nplt.plot([i for i in range(1, resp['iterações'])], resp['erros'])\nplt.tight_layout()\nplt.show()\n\n#PARA X0 = -1\ny = lambda x: 180*x**3 - 117*x**2 - 80*x + 52  # f(x) = 180x^3 - 117x^2 - 80x + 52\ny_linha = lambda x: 540*x**2 - 234*x - 80  # f'(x) = 540x^2 - 234x - 80\nini = -1  # ponto inicial\n#Verificar o arquivo Nexton-Raphson.py para entender o funcionamento dessa função\nresp = newton_raphson(ini, y, y_linha, 'q2')\nprint(f'Para essa X0 = -1 levamos {resp[\"iterações\"] - 1} iterações e temos como valor de f(x) = {resp[\"modulo\"]}')\nprint('Abaixo seguem os graficos dos valores de f(x) e dos erros, respectivamente:')\n\n# Grafico com os valores de f(x)\nx_a = np.linspace(-1.2, 1.2, 30)  # valores escolhidos para melhor visualização do grafico\ny_a = [y(i) for i in x_a]\nplt.style.use('ggplot')\nplt.figure(figsize=(7, 5))\nplt.title(f'F(x) por X\\ncom X0 = -1')\nplt.xlabel('Valores de x')\nplt.ylabel('Valores de f(x)')\n# função com valores entre 0.4 e 0.8\nplt.plot(x_a, y_a, label='Função exata')\n# Nossa aproximação Newton-Raphson por iteração\nplt.plot(resp['valores'], resp['valores_função'], label='Valores de Newton-Raphson por iteração')\nplt.tight_layout()\nplt.legend(loc='best')\nplt.show()\n\n# Grafico com os valores dos erros\nplt.style.use('ggplot')\nplt.figure(figsize=(7, 5))\nplt.title('Erro por Iterações')\nplt.xlabel('Numero de iterações')\nplt.ylabel('Valores dos erros')\nplt.plot([i for i in range(1, resp['iterações'])], resp['erros'])\nplt.tight_layout()\nplt.show()\n", "meta": {"hexsha": "6992ca99d13da8801d97284f7680e10b4e4644b9", "size": 3011, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab3/q2_a.py", "max_stars_repo_name": "ViniciusRCortez/Monitoria-de-metodos-numericos-com-python", "max_stars_repo_head_hexsha": "85678fe8907752533d0dc97dc83550411ba079f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab3/q2_a.py", "max_issues_repo_name": "ViniciusRCortez/Monitoria-de-metodos-numericos-com-python", "max_issues_repo_head_hexsha": "85678fe8907752533d0dc97dc83550411ba079f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab3/q2_a.py", "max_forks_repo_name": "ViniciusRCortez/Monitoria-de-metodos-numericos-com-python", "max_forks_repo_head_hexsha": "85678fe8907752533d0dc97dc83550411ba079f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6025641026, "max_line_length": 115, "alphanum_fraction": 0.6984390568, "include": true, "reason": "import numpy", "num_tokens": 1029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.9005297881200701, "lm_q1q2_score": 0.8517222160602772}}
{"text": "#!/usr/bin/python\n\nimport sys\nimport time\nimport numpy as np\n\nprint('MATRIZ UNIDIMENCIONAL Y BIDIMENCIONAL')\na=np.array([1,2,3])\nprint('1D array:')\nprint(a)\nprint()\nb=np.array([(1,2,3),(4,5,6)])\nprint('2D array:')\nprint(b)\n\nprint('-------------')\nprint('LISTA DE MIL NUMEROS Y CALCULAMOS LA MEMORIA ASIGNADA A ESTA')\ns = range(1000)\nprint('Resultado lista de Python:')\nprint(sys.getsizeof(5)*len(s))\nprint()\nd = np.arange(1000)\nprint('Resutado NumPy array:')\nprint(d.size*d.itemsize)\n\nprint('-------------')\nprint('MODULO PARA EVALUAR LA RAPIDEZ EN LA QUE SE EJECUTAN ESTAS INSTRUCCIONES')\nSiZE = 1000000\nL1 = range(SiZE)\nL2 = range(SiZE)\nA1 = np.arange(SiZE)\nA2 = np.arange(SiZE)\n\nstart = time.time()\nresult = [(x,y) for x,y in zip(L1, L2)]\nprint('Resultado lista de Python:')\nprint((time.time()-start)*1000)\nprint()\nstart = time.time()\nresult = A1 + A2\nprint('Resultado NumPy array:')\nprint((time.time()-start)*1000)\n\nprint('-------------')\nprint('CREAR UNA MATRIZ DE UNOS --> 3 FILAS Y 4 COLUMNAS ')\nunos = np.ones((3,4))\nprint(unos)\n\nprint('CREAR UNA MATRIZ DE CEROS --> 3 FILAS Y 4 COLUMNAS ')\nceros = np.zeros((3,4))\nprint(ceros)\n\nprint('CREAR UNA MATRIZ DE NUMEROS ALEATORIOS --> 3 FILAS Y 4 COLUMNAS ')\naleatorios = np.random.random((3,4))\nprint(aleatorios)\n\nprint('CREAR UNA MATRIZ VACIA --> 3 FILAS Y 4 COLUMNAS ')\nvacia = np.empty((3,4))\nprint(vacia)\n\nprint('CREAR UNA MATRIZ DE UN SOLO VALOR --> 3 FILAS Y 4 COLUMNAS ')\nfull = np.full((3,4),5)\nprint(full)\n\nprint('CREAR UNA MATRIZ CON VALORES ESPACIADOS UNIFORMEMENTE')\n\"\"\"\nRealiza una matriz de los números que se encuentran entre el cero y 30\nhaciendo saltos de 5 en 5\n\"\"\"\nespacio1 = np.arange(0,30,5) \nprint(espacio1)\n\"\"\"\nRealiza una matriz de los de 5 valores con los números que se encuentran \nentre el 0 y 2\n\"\"\"\nespacio2 = np.linspace(0,2,5) #\nprint(espacio2)\n\nprint('CREAR UNA MATRIZ ENTIDAD')\nidentidad1 = np.eye(4,4)\nprint(identidad1)\nidentidad2 = np.identity(4)\nprint(identidad2)\n\nprint('CONOCER LAS DIMENCIONES DE UNA MATRIZ')\na = np.array([(1,2,3),(4,5,6)])\nprint(a.ndim)\nprint('CONOCER EL TIPO DE LOS DATOS')\nprint(a.dtype)\nprint('CONOCER EL TAMAÑO DE LA MATRIZ')\nprint(a.size)\nprint('CONOCER EL FORMA DE LA MATRIZ')\nprint(a.shape)\n\nprint('CAMBIO DE FORMA DE UNA MATRIZ')\nprint(a)\nb = a.reshape(3,2)\nprint(b)\n\n\"\"\"\nOperaciones matemáticas \n\"\"\"\nprint('ENCONTRAR EL MINIMO, MAXIMO Y SUMA')\nc = np.array([9,8,7,6,5,4,3,2,1])\nprint(c.min())\nprint(c.max())\nprint(c.sum())\nprint('CALCULAR LA RAÍZ CUADRADA Y DESVIACIÓN ESTÁNDAR')\nd = np.array([(9,8,7,6,5), (4,3,2,1,0)])\nprint(np.sqrt(d))\nprint(np.std(d))\nprint('CALCULAR LA SUMA, RESTA, MULTIPLICACIÓN Y DIVISIÓN DE DOS MATRICES')\nx = np.array([(1,3,5,7,9),(2,4,6,8,10)])\ny = np.array([(10,9,8,7,6), (5,4,3,2,1)])\nprint(x+y)\nprint(x-y)\nprint(x*y)\nprint(x/y)", "meta": {"hexsha": "739e63a9b632085e4d75fc9b116dedc7d15d65ce", "size": 2776, "ext": "py", "lang": "Python", "max_stars_repo_path": "Scripts/numPy.py", "max_stars_repo_name": "AllieMichell/Machine-Learning", "max_stars_repo_head_hexsha": "d419f9c4992e0ee641270d6a75b2c7cd2797a0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Scripts/numPy.py", "max_issues_repo_name": "AllieMichell/Machine-Learning", "max_issues_repo_head_hexsha": "d419f9c4992e0ee641270d6a75b2c7cd2797a0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scripts/numPy.py", "max_forks_repo_name": "AllieMichell/Machine-Learning", "max_forks_repo_head_hexsha": "d419f9c4992e0ee641270d6a75b2c7cd2797a0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5254237288, "max_line_length": 81, "alphanum_fraction": 0.6790345821, "include": true, "reason": "import numpy", "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8947894625955065, "lm_q1q2_score": 0.851717185815107}}
{"text": "\"\"\"\r\nDemonstrate Calculations with Complex Numbers\r\nLearning Example for Dr. Stanier's classes\r\nFile: E7_complex_numbers.py\r\n\r\nAuthor: Charles Stanier, charles-stanier@uiowa.edu\r\nDate:  August 27, 2019\r\nWritten/Tested In: Python 3.7.3\r\n\r\nProgram Objective: Demonstrate how to manipulate complex numbers\r\nShowing some of the features of cmath at https://docs.python.org/2/library/cmath.html\r\n\r\nModifications: none so far\r\n  \r\n\"\"\"\r\n\r\nimport numpy as np  # this is used for math functions\r\nimport pylab as pl  # this is used for plotting functions\r\n\r\n# super simple, let's take the square root of -1\r\nx = -1\r\n# y = np.sqrt(x) # this generates and error\r\ny1 = x**0.5\r\n\r\n# but if we define x as complex and use np.sqrt it works\r\nx = -1+0j\r\ny2 = np.sqrt(x)\r\n\r\nprint('Square root of -1 using method 1: ', y1)\r\nprint('Square root of -1 using method 2: ', y2)\r\n\r\n# extract the real and imaginary portions and print\r\n\r\ny2r = np.real(y2)\r\ny2i = np.imag(y2)\r\n\r\nprint('y2 is equal to ',y2r,' plus ',y2i,'i')\r\n\r\n# now lets deal with a vector, take the square root, and plot on complex plane\r\nreal_vec = np.linspace(-5,5,100)\r\nimag_vec = np.ones(real_vec.size)*1j  # j is \"i\" the sqrt of -1\r\nx_vec = real_vec + imag_vec\r\n# take the square root of those 100 values\r\nx_sqrt = np.sqrt(x_vec)\r\n\r\n# for complex plot, we make the real part the x vector\r\n# and the imag part the y vector\r\nplotx = np.real(x_sqrt)\r\nploty = np.imag(x_sqrt)\r\n\r\n# use pylab to plot x and y\r\npl.plot(plotx, ploty, 'o', color='black')\r\npl.xlabel('Real Portion')\r\npl.ylabel('Imag Portion')\r\n\r\n# show the plot on the screen\r\npl.show()\r\n", "meta": {"hexsha": "8a45e14663b7ae840bd390527f4ff128a65b81d8", "size": 1589, "ext": "py", "lang": "Python", "max_stars_repo_path": "E7_complex_numbers.py", "max_stars_repo_name": "charles-stan/learn_python_Stanier", "max_stars_repo_head_hexsha": "740a7104fcbd739663d703d3770f9e31509300f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-04T14:53:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-29T18:16:15.000Z", "max_issues_repo_path": "E7_complex_numbers.py", "max_issues_repo_name": "charles-stan/learn_python_Stanier", "max_issues_repo_head_hexsha": "740a7104fcbd739663d703d3770f9e31509300f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "E7_complex_numbers.py", "max_forks_repo_name": "charles-stan/learn_python_Stanier", "max_forks_repo_head_hexsha": "740a7104fcbd739663d703d3770f9e31509300f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3965517241, "max_line_length": 86, "alphanum_fraction": 0.6935179358, "include": true, "reason": "import numpy", "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454895, "lm_q2_score": 0.894789454880027, "lm_q1q2_score": 0.85171718458034}}
{"text": "import math\nimport pandas as pd\nimport numpy as np\n\n\ndef prime(num):\n    if num >= 1:\n        root_num = int(math.sqrt(num))\n        # print(root_num)\n        for i in range(2, root_num+1, 1):\n            # print(i)\n            if (num % i) == 0:\n                print(\"Number is not prime\")\n                break\n        else:\n            print(\"Prime Number\")\n\nlst = []\ndef prime_in_range(num_till):\n    for i in range(num_till+1):\n        if i>=1:\n            root_num = int(math.sqrt(i))\n            for j in range(2,root_num,1):\n                if i%j==0:\n                    # print(\"Not Prime Number\")\n                    break\n            else:\n                lst.append(i)\n\ndef factorial(num):\n    \"\"\"This is a recursive function that calls\n   itself to find the factorial of given number\"\"\"\n\n    if num == 1:\n        return num\n    else:\n        # print(\"lofh\")\n        return num * factorial(num-1)\n\n\nif __name__ == \"__main__\":\n    num = int(input(\"Enter number to find  : \"))\n\n    prime(num)\n    prime_in_range(num)\n    print(\"Prime Numbers in the Range : \", lst)\n    if num < 0:\n        print(\"Factorial cannot be found for negative numbers\")\n    elif num == 0:\n        print(\"Factorial of 0 is 1\")\n    else:\n        print(\"Factorial of\", num, \"is: \", factorial(num))\n\n", "meta": {"hexsha": "06dec33160fc19f0478acd7936b191a3d1a4df1d", "size": 1283, "ext": "py", "lang": "Python", "max_stars_repo_path": "data/kaggle_python/factorial_prime.py", "max_stars_repo_name": "MohanKrishna-RC/Python-Necessities", "max_stars_repo_head_hexsha": "c63fbac717a9bf7edd48ec20337c16de55f5b535", "max_stars_repo_licenses": ["FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data/kaggle_python/factorial_prime.py", "max_issues_repo_name": "MohanKrishna-RC/Python-Necessities", "max_issues_repo_head_hexsha": "c63fbac717a9bf7edd48ec20337c16de55f5b535", "max_issues_repo_licenses": ["FTL"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-11-27T12:05:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-27T12:05:18.000Z", "max_forks_repo_path": "data/kaggle_python/factorial_prime.py", "max_forks_repo_name": "MohanKrishna-RC/Python-Necessities", "max_forks_repo_head_hexsha": "c63fbac717a9bf7edd48ec20337c16de55f5b535", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7592592593, "max_line_length": 63, "alphanum_fraction": 0.5159781761, "include": true, "reason": "import numpy", "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488963, "lm_q2_score": 0.8947894583870633, "lm_q1q2_score": 0.8517171842529704}}
{"text": "#!/usr/bin/env python3\n\n# Instalação\n# - pip install -r requirements.txt\n# - pip install numpy\n\nimport numpy as np\n\n# Numpy: biblioteca para computação científica - funções bem otimizadas\na = np.array([1, 2, 3])\nprint(type(a))\nprint(a.shape)\nprint(a[0], a[1], a[2])\n\na[0] = 5\nprint(a)\n\nb = np.array([[1, 2, 3],\n              [4, 5, 6]])\nprint(b.shape)\nprint(b[0, 0], b[0, 1], b[1, 0])\n\n# Tupla: tipo de dados imutável\ntupla = (1, 2, 3, 4)\nprint(tupla[0])\n\n# Cria uma matriz com zeros\na = np.zeros((2, 2))\nprint(a)\n\n# Cria uma matriz com uns\nb = np.ones((2, 2))\nprint(b)\n\n# Cria uma matriz com 7s\nc = np.full((2, 2), 7)\nprint(c)\n\n# Cria uma matriz identidade\nd = np.eye(2)\nprint(d)\n\n# Cria uma matriz aleatória\ne = np.random.random((2, 2))\nprint(e)\n\n# Seleciona uma fatia da matriz\na = np.array([[1, 2, 3, 4],\n              [5, 6, 7, 8],\n              [9, 10, 11, 12]])\nb = a[:2, 1:3]\nprint(b)\n\n# lista[2:3]\n\nprint('A =\\n', a)\nprint('B =\\n', b)\n\nb[0, 0] = 77\n\nprint('A =\\n', a)\n\n# Indexação booleana\na = np.array([[1, 2], [3, 4], [5, 6]])\n\nbool_idx = (a > 2)\nprint(bool_idx)\n\nprint(a[bool_idx])\nprint(a[a > 2])\n\n# Tipos de dados\nx = np.array([1, 2])\nprint(x.dtype)\n\nx = np.array([1.0, 2.0])\nprint(x.dtype)\n\nx = np.array([1, 2], dtype=np.int64)\nprint(x.dtype)\n\n# \"\"\"### Operações\"\"\"\n\nx = np.array([[1, 2], [3, 4]], dtype=np.float64)\ny = np.array([[5, 6], [7, 8]], dtype=np.float64)\n\n# print(x + y)\nprint(np.add(x, y))\n\n# print(x - y)\nprint(np.subtract(x, y))\n\n# print(x * y)\nprint(np.multiply(x, y))\n\n# print(x / y)\nprint(np.divide(x, y))\n\nprint(np.sqrt(x))\n\nx = np.array([[1, 2], [3, 4]])\ny = np.array([[5, 6], [7, 8]])\n\nprint(x.dot(y))\n# print(np.dot(x, y))\n\nv = np.array([9, 10])\nw = np.array([11, 12])\n\nprint(v.dot(w))\n# print(np.dot(v, w))\n\n# Transposta de uma matriz\nx = np.array([[1, 2], [3, 4]])\n\nprint(x)\nprint(x.T)\n", "meta": {"hexsha": "144ab16a1ce831810464d461305befd5b1fb3378", "size": 1823, "ext": "py", "lang": "Python", "max_stars_repo_path": "Projetos/Aula02/ex_numpy.py", "max_stars_repo_name": "chaua/inteligencia-computacional", "max_stars_repo_head_hexsha": "b32fcc9ceed1a0094a9837689c0dae97a474a23e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-03T17:25:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T17:25:13.000Z", "max_issues_repo_path": "Projetos/Aula02/ex_numpy.py", "max_issues_repo_name": "chaua/inteligencia-computacional", "max_issues_repo_head_hexsha": "b32fcc9ceed1a0094a9837689c0dae97a474a23e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Projetos/Aula02/ex_numpy.py", "max_forks_repo_name": "chaua/inteligencia-computacional", "max_forks_repo_head_hexsha": "b32fcc9ceed1a0094a9837689c0dae97a474a23e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-05-02T23:05:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-23T15:51:44.000Z", "avg_line_length": 15.4491525424, "max_line_length": 71, "alphanum_fraction": 0.5600658256, "include": true, "reason": "import numpy", "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308128813471, "lm_q2_score": 0.912436167620237, "lm_q1q2_score": 0.851696033644099}}
{"text": "import numpy as np\n\nclass Activation:\n    def step_function(self,x):\n        y = x > 0\n        return y.astype(np.int)\n\n    #왜 sigmoid? \n    # 출력이 0~1 사이이고, 미분이 쉬운 함수들중 가장 그럴듯 해서 많이 사용하게됨. 미분은 exp이 쉽기때문에\n    def sigmoid(self,x):  \n        return 1/(1 + np.exp(-x))\n\n    def RelU(self,x):\n        return np.maximum(0,x)\n\n     #왜 softmax? \n    # 출력이 0~1 사이이고, 미분이 쉬운 함수들중 가장 그럴듯 해서 많이 사용하게됨. 미분은 exp이 쉽기때문에\n    def softMax(self,xs):\n        mx = np.max(xs)\n        expx = np.exp( xs - mx )\n        expsum = np.sum(expx)\n        y = expx / expsum\n        return y\n\nif __name__ == \"__main__\":\n    a = [ 1 ,3]\n    print(Activation().softMax(a))\n\n", "meta": {"hexsha": "d879fed8d1a9a97fbd57a9ae1c54325250535a0c", "size": 641, "ext": "py", "lang": "Python", "max_stars_repo_path": "vsCode/DL_rawLevel/DL_rawLevel/1.LogisticRegression/Activation.py", "max_stars_repo_name": "pimier15/pyDLBasic", "max_stars_repo_head_hexsha": "80336cddbcb3ec1f70106b74ff0b3172510b769e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vsCode/DL_rawLevel/DL_rawLevel/1.LogisticRegression/Activation.py", "max_issues_repo_name": "pimier15/pyDLBasic", "max_issues_repo_head_hexsha": "80336cddbcb3ec1f70106b74ff0b3172510b769e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vsCode/DL_rawLevel/DL_rawLevel/1.LogisticRegression/Activation.py", "max_forks_repo_name": "pimier15/pyDLBasic", "max_forks_repo_head_hexsha": "80336cddbcb3ec1f70106b74ff0b3172510b769e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1034482759, "max_line_length": 66, "alphanum_fraction": 0.5444617785, "include": true, "reason": "import numpy", "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724487, "lm_q2_score": 0.8902942319436397, "lm_q1q2_score": 0.8516859125412249}}
{"text": "#Use of classes, 1: initialization part, we tìdefine the input of parameters, for axample the matrix A or the vector y.\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nclass SolveMinProbl:\r\n    def __init__(self, y=np.ones((6, 1)), A=np.eye(5)): #initialization\r\n        self.matr=A\r\n        self.Np=y.shape[0]\r\n        self.Nf=A.shape[1]\r\n        self.vect=y\r\n        self.sol=np.zeros((self.Nf, 1), dtype=float)\r\n        return\r\n    def plot_w(self, title='Solution'):\r\n        w=self.sol\r\n        n=np.arange(self.Nf)\r\n        plt.figure()\r\n        plt.plot(n, w)\r\n        plt.xlabel('n')\r\n        plt.ylabel('w(n)')\r\n        plt.title(title)\r\n        plt.grid()\r\n        plt.show()\r\n        return\r\n    def print_result(self, title):\r\n        print(title, '_:')\r\n        print(\"The optimum weight vector is:_\")\r\n        print(self.sol)\r\n        return\r\n\r\n    def plot_err(self, title='Square_error', logy=0, logx=0):\r\n        err=self.err\r\n        plt.figure()\r\n        if (logy==0) and (logx==0):\r\n            plt.plot(err[:, 0], err[:, 1])\r\n        if (logy == 1) and (logx == 0):\r\n            plt.plot(err[:, 0], err[:, 1])\r\n        if (logy == 0) and (logx == 1):\r\n            plt.semilogy(err[:, 0], err[:, 1])\r\n        if (logy == 1) and (logx == 1):\r\n            plt.loglog(err[:, 0], err[:, 1])\r\n        plt.xlabel('n')\r\n        plt.ylabel('e(n)')\r\n        plt.title(title)\r\n        plt.margins(0.01, 0.1)\r\n        plt.grid()\r\n        plt.show()\r\n        return\r\n\r\nclass SolveLLS(SolveMinProbl):\r\n    def run(self):\r\n        A=self.matr\r\n        y=self.vect\r\n        w=np.dot(np.dot(np.linalg.inv(np.dot(A.T, A)), A.T), y)\r\n        self.sol=w\r\n        self.min=np.linalg.norm(np.dot(A, w)-y)\r\n\r\n\r\nclass SolveGrad(SolveMinProbl):\r\n    def run(self, gamma, Nit=1000):\r\n        self.err=np.zeros((Nit, 2), dtype=float)\r\n        A=self.matr\r\n        y=self.vect\r\n        w=np.random.rand(self.Nf, 1)\r\n        for it in range(Nit):\r\n            grad=2*np.dot(A.T, (np.dot(A,w)-y))\r\n            w=w-gamma*grad\r\n            self.err[it, 0]=it\r\n            self.err[it, 1]=np.linalg.norm(np.dot(A, w)-y)\r\n        self.sol=w\r\n        self.min=self.err[it, 1]\r\n\r\n\r\nclass SolveSteep(SolveMinProbl):\r\n    def run(self, Nit=1000):\r\n        self.err = np.zeros((Nit, 2), dtype=float)\r\n        A = self.matr\r\n        y = self.vect\r\n        w = np.random.rand(self.Nf, 1)\r\n        for it in range(Nit):\r\n            grad = 2 * np.dot(A.T, (np.dot(A, w) - y))\r\n            H=4*np.dot(A.T, A)\r\n            w=w-np.linalg.norm(grad)**2/np.dot(np.dot(grad.T, H), grad)*grad\r\n            self.err[it, 0] = it\r\n            self.err[it, 1] = np.linalg.norm(np.dot(A, w) - y)\r\n        self.sol = w\r\n        self.min = self.err[it, 1]\r\n\r\nclass SolveStocha(SolveMinProbl):\r\n    def run(self,Nit=100, gamma=1e-3):\r\n        self.err=np.zeros((Nit, 2), dtype=float)\r\n        A=self.matr\r\n        y=self.vect\r\n        w=np.random.rand(self.Nf, 1)\r\n        for it in range(Nit):\r\n            for i in range(self.Nf):\r\n                grad=gamma*(np.dot(A[i], w)-y[i])*A[i]\r\n                w=w-grad\r\n            self.err[it, 0]=it\r\n            self.err[it, 1]= np.linalg.norm(np.dot(A, w) - y)\r\n        self.sol=w\r\n        self.min=self.err[it, 1]\r\n\r\nif __name__==\"__main__\":\r\n    Np=7\r\n    Nf=7\r\n    A=np.random.randn(Np, Nf)\r\n    y=np.random.randn(Np, 1)\r\n    m=SolveLLS(y, A)\r\n    m.run()\r\n    m.print_result('LLS')\r\n    m.plot_w('LLS')\r\n\r\n    gamma=1e-2\r\n    g=SolveGrad(y, A)\r\n    g.run(gamma)\r\n    g.print_result('Gradient_algo')\r\n    logx=0\r\n    logy=1\r\n    g.plot_err('Gradient_algo:_square_error', logx, logy)\r\n\r\n    s=SolveSteep(y, A)\r\n    s.run()\r\n    s.print_result('SDA')\r\n    s.plot_err('Steepest_decent_algo:_square_error', logx, logy)\r\n\r\n    st=SolveStocha(y, A)\r\n    st.run()\r\n    s.plot_err('Stochastic Algorithm', logx, logy)\r\n    s.print_result('SA')\r\n\r\n#with no.random.seed(N) i obtain also the same random values\r\n", "meta": {"hexsha": "95297080d6b63df23e46afd0470ce6c94a94bd1e", "size": 3926, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab1/Lab0.1.py", "max_stars_repo_name": "LorenzoBellone/ICT_for_Health", "max_stars_repo_head_hexsha": "be6597c0fdc72e538e9d55383dc14f13ce79729e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab1/Lab0.1.py", "max_issues_repo_name": "LorenzoBellone/ICT_for_Health", "max_issues_repo_head_hexsha": "be6597c0fdc72e538e9d55383dc14f13ce79729e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab1/Lab0.1.py", "max_forks_repo_name": "LorenzoBellone/ICT_for_Health", "max_forks_repo_head_hexsha": "be6597c0fdc72e538e9d55383dc14f13ce79729e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5187969925, "max_line_length": 120, "alphanum_fraction": 0.5117167601, "include": true, "reason": "import numpy", "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.8902942159342104, "lm_q1q2_score": 0.8516858983267775}}
{"text": "#!/usr/bin/python3\nimport numpy as np\n\n\"\"\"\nX - observation matrix:\n    rows - observations; n - number of rows\n    cols - values/factors observed\n    \n@ operator - matrix multiplication in numpy\n\"\"\"\n\n# np.loadtxt(open(\"cereal_cut.csv\", \"rb\"), delimiter=\",\")\n\ndef center_matrix(X):\n    \"\"\"\n    centers a matrix by subtracting matrix A with values 1/n from it\n    :param X: :type numpy array: input matrix\n    :return: :type numpy array:  - centered matrix\n    \"\"\"\n    n = len(X)\n    A = np.divide(np.ones((n, n)), n)\n    M = A @ X\n\n    return X - M\n\n\ndef reduce(X, threshold = 1, leave = None):\n    \"\"\"\n    reduces the dimensionality of a observed data by removing the least significant characteristics\n    :param X: :type numpy array: input matrix\n    :param threshold: :type float: cutoff value for eigenvalues to be considered significant\n    :param leave: :type int: fallback if nothing is cut off, leave a fixed number of the most significant axes, None - don't cut off anything\n    :return: :type numpy array: reduced matrix\n    \"\"\"\n    n = len(X)\n    X_hat = center_matrix(X)\n\n    # Sigma\n    cov_mtx = np.cov(X_hat, rowvar = False) # (X_hat.transpose() @ X_hat) * (1 / n)  -- difrerent results ???\n\n    cov_eVal, cov_eVec = np.linalg.eigh(cov_mtx)\n\n    cutoff_index = 0\n    for ind,eVal in enumerate(cov_eVal):\n        if eVal > threshold:\n            cutoff_index = ind\n            break\n\n    if cutoff_index == 0 and leave:\n        cutoff_index = len(eVal) - leave if len(eVal) - leave >= 0 else 0\n\n    return X_hat @ cov_eVec[ : , cutoff_index : ]\n\nif __name__ == \"__main__\":\n    d = np.loadtxt(open(\"./data/cereal_cut.csv\", \"rb\"), delimiter=\",\", skiprows=1)\n    print(d.shape, d)\n    res = reduce(d)\n    print(res.shape, res)\n", "meta": {"hexsha": "4047fead2faaa576e75dc42528ab606ca0dc1a7f", "size": 1737, "ext": "py", "lang": "Python", "max_stars_repo_path": "dim_reduction.py", "max_stars_repo_name": "kgskgs/pat-rec", "max_stars_repo_head_hexsha": "823d56eabc5a4b3c9301c32b07d97d784586e403", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dim_reduction.py", "max_issues_repo_name": "kgskgs/pat-rec", "max_issues_repo_head_hexsha": "823d56eabc5a4b3c9301c32b07d97d784586e403", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dim_reduction.py", "max_forks_repo_name": "kgskgs/pat-rec", "max_forks_repo_head_hexsha": "823d56eabc5a4b3c9301c32b07d97d784586e403", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4406779661, "max_line_length": 141, "alphanum_fraction": 0.636154289, "include": true, "reason": "import numpy", "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997376, "lm_q2_score": 0.8902942188450159, "lm_q1q2_score": 0.8516858978091931}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# The function we Want to Solve\ndef f(x):\n    return np.tan(x) - x / (1 - x**2)\n\nif __name__ == \"__main__\":\n\n    # Plot the Function to Visualize the Root\n    x = np.linspace(2,4.5,1000)\n    y = f(x)\n\n    plt.plot(x, y)\n    plt.xlabel('x')\n    plt.ylabel('f(x)')\n    plt.tight_layout\n    plt.show()\n\n    # Repetitions\n    N = 20\n\n    # Region Edges (Find Them in the Diagram of the Function)\n    a, b = [2], [4]\n\n    # Counters\n    i, j = 0, 0\n\n    for n in range(N):\n        # Center of Interval (a,b)\n        c = 0.5 * (a[i] + b[j])\n        # Where is the Root? In (a,c) or in (c,b)? (Bolzano Theorem)\n        if np.sign(f(a[i])) * np.sign(f(c)) == -1.0:\n            b += [c]\n            j += 1\n        elif np.sign(f(c)) * np.sign(f(b[j])) == -1.0:\n            a += [c]\n            i += 1\n\n    # We Specify the Root as the Center of the Interval (a,b)\n    root = 0.5 * (b[j] + a[i])\n\n    print(f'The root of f is: x = {root:.4f}.')\n    print(f'The valus of f for the above x is {f(root):.7f}.')\n", "meta": {"hexsha": "5238b36cf372e070d2573f8cf3a12c2ec0b7c4b2", "size": 1050, "ext": "py", "lang": "Python", "max_stars_repo_path": "Equation-Solving/Partition-Method.py", "max_stars_repo_name": "AlexTsagas/Computational-Physics", "max_stars_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Equation-Solving/Partition-Method.py", "max_issues_repo_name": "AlexTsagas/Computational-Physics", "max_issues_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Equation-Solving/Partition-Method.py", "max_forks_repo_name": "AlexTsagas/Computational-Physics", "max_forks_repo_head_hexsha": "4fbf3e0eec49c420981d313459aba4a3ed50b8bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3333333333, "max_line_length": 68, "alphanum_fraction": 0.5019047619, "include": true, "reason": "import numpy", "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140206578809, "lm_q2_score": 0.8807970858005139, "lm_q1q2_score": 0.8516550516151193}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import linalg as la\n\ndef PCA(dat,center=False,percentage=0.8):\n    M=dat[:,0].size\n    N=dat[0,:].size\n    if center:\n\t    mu = np.mean(dat,0)\n\t    dat -= mu\n\n    U,L,Vh = la.svd(dat,full_matrices=False)\n    \n    V = (Vh.T).conjugate()\n    SIGMA = np.diag(L)\n    X = np.dot(U,SIGMA)\n    Lam = L**2\n\n    csum = [np.sum(Lam[:i+1])/np.sum(Lam) for i in range(N)]\n\n    normalized_eigenvalues = Lam/np.sum(Lam)\n    n_components = np.array([x < percentage for x in csum]).tolist().index(False)\n\n    return (normalized_eigenvalues, \n            V[:,0:n_components], \n            SIGMA[0:n_components,0:n_components], \n            X[:,0:n_components])\n\ndef scree(normalized_eigenvalues):\n    plt.plot(normalized_eigenvalues,'b-',normalized_eigenvalues,'bo')\n    plt.xlabel(\"Principal Components\")\n    plt.ylabel(\"Percentage of Variance\")\n    plt.show()\n    return\n", "meta": {"hexsha": "04f80f1a8f20df2a75fcaac027f2457632726c45", "size": 918, "ext": "py", "lang": "Python", "max_stars_repo_path": "Algorithms/PCA/PCA.py", "max_stars_repo_name": "abefrandsen/numerical_computing", "max_stars_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Algorithms/PCA/PCA.py", "max_issues_repo_name": "abefrandsen/numerical_computing", "max_issues_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Algorithms/PCA/PCA.py", "max_forks_repo_name": "abefrandsen/numerical_computing", "max_forks_repo_head_hexsha": "90559f7c4f387885eb44ea7b1fa19bb602f496cb", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2285714286, "max_line_length": 81, "alphanum_fraction": 0.6296296296, "include": true, "reason": "import numpy,from scipy", "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140244715405, "lm_q2_score": 0.8807970811069351, "lm_q1q2_score": 0.8516550504358925}}
{"text": "#!usr/bin/env python3\n\nimport numpy as np\ninput_matrix = np.array([\n    [1, 0.3, 0.3, 0.3], \n    [0.3, 1, 0.3, 0.3],\n    [0.3, 0.3, 1, 0.3],\n    [0.3, 0.3, 0.3, 1]\n    ])\n\ndef cholesky_decomp(correlationmatrix):\n    cholmat = np.zeros_like(correlationmatrix)\n    for i in range(len(cholmat)):\n        for j in range(i+1):\n            if i==j:\n                #this computes the diagonal values\n                diag = correlationmatrix[i,i] - np.sum(np.square(cholmat[i,:i]))\n                #because you cannot sqrt a negative number:\n                if diag<0:\n                    return 0.0\n                cholmat[i,i] = np.sqrt(diag)\n            else:\n                #computing the rest of the matrix\n                cholmat[i,j] = (correlationmatrix[i,j] - np.sum(cholmat[i,:j]*cholmat[j,:j]))/cholmat[j,j]\n    return cholmat\n\ncholesky_from_function = cholesky_decomp(input_matrix)\ncholesky_from_np = np.linalg.cholesky(input_matrix)\ncheck = np.allclose(cholesky_from_function,cholesky_from_np)\n\nprint(\"\\nCorrelation matrix:\")\nprint(input_matrix)\nprint(\"\\nCholesky from function:\")\nprint(cholesky_from_function)\nprint(\"\\nCholesky from numpy:\")\nprint(cholesky_from_np)\nprint(\"\\nAre the two cholesky matrices essentially identical??\")\nprint(check)", "meta": {"hexsha": "0fc85cdbe4e324f56ba689bf00f0a9fc21c44cbd", "size": 1251, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week20190529/Q1.py", "max_stars_repo_name": "wrightgarr/PYTHON_416", "max_stars_repo_head_hexsha": "0accadc214b8d7b0140be6bc61222e2286ae72fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week20190529/Q1.py", "max_issues_repo_name": "wrightgarr/PYTHON_416", "max_issues_repo_head_hexsha": "0accadc214b8d7b0140be6bc61222e2286ae72fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week20190529/Q1.py", "max_forks_repo_name": "wrightgarr/PYTHON_416", "max_forks_repo_head_hexsha": "0accadc214b8d7b0140be6bc61222e2286ae72fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9210526316, "max_line_length": 106, "alphanum_fraction": 0.621902478, "include": true, "reason": "import numpy,from numpy", "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140216112959, "lm_q2_score": 0.8807970795424088, "lm_q1q2_score": 0.851655046403835}}
{"text": "from __future__ import division\nimport numpy as np\nfrom scipy.sparse import spdiags\nfrom scipy.sparse.linalg import spsolve, cg\nimport matplotlib.pyplot as plt\n\ndef fd_order2_ode(func,a1,a2,a3,a=0.,b=1.,alpha=1.,beta=3.,N=5):\n\t# A Simple Finite Difference Scheme to solve BVP's of the form \n\t# a1(x)u''(x) + a2(x)u'(x) + a3(x)u(x) = f(x), x \\in [a,b]\n\t# u(a) = alpha\n\t# u(b) = beta\n\t# (Dirichlet boundary conditions)\n\t# \n\t# U_0 = alpha, U_1, U_2, ..., U_m, U_{m+1} = beta\n\t# We use m+1 subintervals, giving m algebraic equations\n\tm = N-1\n\th = (b-a)/N\t\t  # Here we form the diagonals\n\tx = np.linspace(a,b,N+1)\n\tD0,Dp,Dm,diags = np.zeros((1,m)), np.zeros((1,m)), np.zeros((1,m)), np.array([0,-1,1])\n\t\n\tD0 += -2.*a1(x[1:-1])*h**(-2.) + a3(x[1:-1])\n\tDm += a1(x[1:-1])*h**(-2.) - a2(x[1:-1])*(2.*h)**(-1.)\n\tDp += a1(x[1:-1])*h**(-2.) + a2(x[1:-1])*(2.*h)**(-1.)\n\t# print \"\\nD0 = \\n\", D0[0,:5]\n\t# print \"\\nDm = \\n\", Dm[0,:5] \n\t# print \"\\nDp = \\n\", Dp[0,:5]\n\t# Here we create the matrix A\n\tdata = np.concatenate((D0,np.roll(Dm,-1),np.roll(Dp,1)),axis=0) # This stacks up rows\n\tA = spdiags(data,diags,m,m).asformat('csr')\n\tprint \"\\nA = \\n\", A[:5,:5].todense()\n\tprint \"\\nA = \\n\", A[-5:,-5:].todense()\n\t# print A.shape\n\t# Here we create the vector B\n\tB = np.zeros(N+1)\n\tB[2:-2] = func(x[2:-2])\t\n\txj = a+1.*h\n\tB[0], B[1] = alpha, func(xj)-alpha *( a1(xj)*h**(-2.) - a2(xj)*(2.*h)**(-1.) )\n\txj = a+m*h\n\tB[-1], B[-2]  = beta, func(xj)-beta*( a1(xj)*h**(-2.) + a2(xj)*(2.*h)**(-1.) )\n\tprint \"\\nB = \\n\", B[:5]\n\tprint \"\\nB = \\n\", B[-5:]\n\t\n\t# Here we solve the equation AX = B and return the result\n\tB[1:-1] = spsolve(A,B[1:-1])\n\treturn np.linspace(a,b,m+2), B\n\n\n\ndef approx_order(num_approx,N,bvp,*args):\n\th, max_error = (1.-0)/N[:-1], np.ones(num_approx-1)\n\t\n\tmesh_best, num_sol_best = bvp(*args, subintervals=N[-1])\n\tfor j in range(len(N)-1): \n\t\tmesh, num_sol = bvp(*args, subintervals=N[j])\n\t\tmax_error[j] = np.max(np.abs( num_sol- num_sol_best[::2**(num_approx-j-1)] ) )\n\tplt.loglog(h,max_error,'.-r',label=\"$E(h)$\")\n\tplt.loglog(h,h**(2.),'-k',label=\"$h^{\\, 2}$\")\n\tplt.xlabel(\"$h$\")\n\tplt.legend(loc='best')\n\tplt.show()\n\tprint \"The order of the finite difference approximation is about \", ( (np.log(max_error[0]) - \n\t\tnp.log(max_error[-1]) )/( np.log(h[0]) - np.log(h[-1]) ) ), \".\"\n\n\n\n# \n# def example():\n#\t# First Code block in the lab manual\n#\timport numpy as np\n#\tfrom scipy.sparse import spdiags\n#\tfrom scipy.sparse.linalg import spsolve\n#\t\n#\tdef bvp(func, epsilon, alpha, beta, N):\n#\t\ta,b = 0., 1.\t# Interval for the BVP\n#\t\th = (b-a)/N\t\t# The length of each subinterval\n#\t\t\n#\t\t# Initialize and define the vector F on the right\n#\t\tF = np.empty(N-1.)\t\t\t\n#\t\tF[0] = func(a+1.*h)-alpha*(epsilon+h/2.)*h**(-2.)\n#\t\tF[N-2] = func(a+(N-1)*h)-beta*(epsilon-h/2.)*h**(-2.)\n#\t\tfor j in xrange(1,N-2): \n#\t\t\tF[j] = func(a + (j+1)*h)\n#\t\t\n#\t\t# Here we define the arrays that will go on the diagonals of A\n#\t\tdata = np.empty((3,N-1))\n#\t\tdata[0,:] = -2.*epsilon*np.ones((1,N-1)) # main diagonal\n#\t\tdata[1,:]  = (epsilon+h/2.)*np.ones((1,N-1))\t # off-diagonals\n#\t\tdata[2,:] = (epsilon-h/2.)*np.ones((1,N-1))\n#\t\t# Next we specify on which diagonals they will be placed, and create A\n#\t\tdiags = np.array([0,-1,1])\n#\t\tA=h**(-2.)*spdiags(data,diags,N-1,N-1).asformat('csr')\n#\t\t\n#\t\tU = np.empty(N+1)\n#\t\tU[1:-1] = spsolve(A,F)\n#\t\tU[0], U[-1] = alpha, beta\n#\t\treturn np.linspace(a,b,N+1), U\n#\t\n#\tx, y = bvp(lambda x:-1., epsilon=.05,alpha=1, beta=3, N=400)\n#\timport matplotlib.pyplot as plt\n#\tplt.plot(x,y,'-k',linewidth=2.0)\n#\tplt.show()\n#\t\n#\tnum_approx = 5 # Number of Approximations\n#\tN = 20*np.array([2**j for j in range(num_approx)])\n#\th, max_error = (1.-0)/N[:-1], np.ones(num_approx-1)\n#\t\n#\tmesh_best, num_sol_best = bvp(lambda x:-1, epsilon=.5, alpha=1, beta=3, N=N[-1])\n#\tfor j in range(len(N)-1): \n#\t\tmesh, num_sol = bvp(lambda x:-1, epsilon=.5, alpha=1, beta=3, N=N[j])\n#\t\tmax_error[j] = np.max(np.abs( num_sol- num_sol_best[::2**(num_approx-j-1)] ) )\n#\tplt.loglog(h,max_error,'.-r',label=\"$E(h)$\")\n#\tplt.loglog(h,h**(2.),'-k',label=\"$h^{\\, 2}$\")\n#\tplt.xlabel(\"$h$\")\n#\tplt.legend(loc='best')\n#\tplt.show()\n#\tprint \"The order of the finite difference approximation is about \", ( (np.log(max_error[0]) - \n#\t\tnp.log(max_error[-1]) )/( np.log(h[0]) - np.log(h[-1]) ) ), \".\"\n#\treturn \n# \n", "meta": {"hexsha": "945e274d945c10af6788fb13e56a0bec686be460", "size": 4259, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol4A/FiniteDifferenceMethod/solution.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vol4A/FiniteDifferenceMethod/solution.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vol4A/FiniteDifferenceMethod/solution.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 35.4916666667, "max_line_length": 96, "alphanum_fraction": 0.5783047664, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.9173026624116692, "lm_q1q2_score": 0.8516318591048518}}
{"text": "import numpy as np\ntry:\n    import matplotlib.pyplot as plt\nexcept:\n    import matplotlib\n    matplotlib.use('Agg')\n    import matplotlib.pyplot as plt\n\nclass PolynomialRegression():\n    def __init__(self, degree):\n        \"\"\"\n        Implement polynomial regression from scratch.\n        \n        This class takes as input \"degree\", which is the degree of the polynomial \n        used to fit the data. For example, degree = 2 would fit a polynomial of the \n        form:\n\n            ax^2 + bx + c\n        \n        Your code will be tested by comparing it with implementations inside sklearn.\n        DO NOT USE THESE IMPLEMENTATIONS DIRECTLY IN YOUR CODE. You may find the \n        following documentation useful:\n\n        https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html\n        https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html\n\n        Here are helpful slides:\n\n        http://interactiveaudiolab.github.io/teaching/eecs349stuff/eecs349_linear_regression.pdf\n    \n        The internal representation of this class is up to you. Read each function\n        documentation carefully to make sure the input and output matches so you can\n        pass the test cases. However, do not use the functions numpy.polyfit or numpy.polval. \n        You should implement the closed form solution of least squares as detailed in slide 10\n        of the lecture slides linked above.\n\n        Usage:\n            import numpy as np\n            \n            x = np.random.random(100)\n            y = np.random.random(100)\n            learner = PolynomialRegression(degree = 1)\n            learner.fit(x, y) # this should be pretty much a flat line\n            predicted = learner.predict(x)\n\n            new_data = np.random.random(100) + 10\n            predicted = learner.predict(new_data)\n\n            # confidence compares the given data with the training data\n            confidence = learner.confidence(new_data)\n\n\n        Args:\n            degree (int): Degree of polynomial used to fit the data.\n        \"\"\"\n        self.features = []\n        self.targets = []\n        self.degree = degree\n        self.coefficients = []\n\n    \n    def fit(self, features, targets):\n        \"\"\"\n        Fit the given data using a polynomial. The degree is given by self.degree,\n        which is set in the __init__ function of this class. The goal of this\n        function is fit features, a 1D numpy array, to targets, another 1D\n        numpy array.\n        \n\n        Args:\n            features (np.ndarray): 1D array containing real-valued inputs.\n            targets (np.ndarray): 1D array containing real-valued targets.\n        Returns:\n            None (saves model and training data internally)\n        \"\"\"\n        self.targets = targets\n        x_arr = []\n        for feature in range(features.size):\n            powers = np.arange(0, self.degree+1)\n            x_powers = np.power(np.full(self.degree+1, features[feature]), powers)\n            x_arr.append(x_powers)\n        x_arr = np.array(x_arr)\n        self.features = x_arr\n        x_transpose = np.transpose(x_arr)\n        first = np.linalg.inv(np.matmul(x_transpose, x_arr))\n        sec = np.matmul(x_transpose, targets)\n        self.coefficients = np.matmul(first, sec)\n\n    def predict(self, features):\n        \"\"\"\n        Given features, a 1D numpy array, use the trained model to predict target \n        estimates. Call this after calling fit.\n\n        Args:\n            features (np.ndarray): 1D array containing real-valued inputs.\n        Returns:\n            predictions (np.ndarray): Output of saved model on features.\n        \"\"\"\n        x_arr = []\n        for feature in range(features.size):\n            powers = np.arange(0, self.degree+1)\n            x_powers = np.power(np.full(self.degree+1, features[feature]), powers)\n            x_arr.append(x_powers)\n        x_arr = np.array(x_arr)\n        predictions = np.matmul(x_arr, self.coefficients)\n        return predictions\n\n    def visualize(self, features, targets):\n        \"\"\"\n        This function should produce a single plot containing a scatter plot of the\n        features and the targets, and the polynomial fit by the model should be\n        graphed on top of the points.\n\n        DO NOT USE plt.show() IN THIS FUNCTION. Instead, use plt.savefig().\n\n        Args:\n            features (np.ndarray): 1D array containing real-valued inputs.\n            targets (np.ndarray): 1D array containing real-valued targets.\n        Returns:\n            None (plots to the active figure)\n        \"\"\"\n        x = features\n        y = self.predict(features)\n        plt.title('Polynomial Regression')\n        plt.plot(x, y)\n        plt.savefig('Polynomial Regression')\n\n", "meta": {"hexsha": "0378ee6165619aec24e8bfd181b57b5cde90178d", "size": 4764, "ext": "py", "lang": "Python", "max_stars_repo_path": "exp/polynomial_regression.py", "max_stars_repo_name": "jessica-lei/coronavirus-2020", "max_stars_repo_head_hexsha": "d51d73dd8d021bb51b78f653a87d478298794534", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exp/polynomial_regression.py", "max_issues_repo_name": "jessica-lei/coronavirus-2020", "max_issues_repo_head_hexsha": "d51d73dd8d021bb51b78f653a87d478298794534", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exp/polynomial_regression.py", "max_forks_repo_name": "jessica-lei/coronavirus-2020", "max_forks_repo_head_hexsha": "d51d73dd8d021bb51b78f653a87d478298794534", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.21875, "max_line_length": 103, "alphanum_fraction": 0.6251049538, "include": true, "reason": "import numpy", "num_tokens": 994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361742, "lm_q2_score": 0.9019206699387734, "lm_q1q2_score": 0.851572626505282}}
{"text": "import numpy as np\n\ndef point_bilinear(x,y,z, pointX, pointY):\n    i = index_vec(x, pointX)\n    j = index_vec(y, pointY)\n\n    l_ij = (x[i] - pointX)*(y[j] - pointY)\n    l_i1j1 = (x[i+1] - pointX)*(y[j+1] - pointY)\n    l_i1j = (x[i+1] - pointX)*(y[j] - pointY)\n    l_ij1 = (x[i] - pointX)*(y[j+1] - pointY)\n\n    z_ij = z[i,j]\n    z_i1j1 = z[i+1,j+1]\n    z_i1j = z[i+1,j]\n    z_ij1 = z[i, j+1]\n\n    num_1 = l_ij*z_i1j1 + l_i1j1*z_ij\n    num_2 = l_i1j*z_ij1 + l_ij1*z_i1j\n    den = (x[i+1] - x[i]) * (y[j+1] - y[j])\n\n    return (num_1 - num_2) / den\n\ndef bilinear(x, y, z, vectX, vectY):\n    dimX, dimY = len(vectX), len(vectY)\n    bi = np.zeros((dimX, dimY))\n    for indexX in range(dimX):\n        for indexY in range(dimY):\n            bi[indexX, indexY] = point_bilinear(x, y, z, vectX[indexX], vectY[indexY])\n\n    return bi\n\ndef index_vec(vec, point):\n    n = len(vec) - 1\n    if point < vec[0]:\n        return 0\n    elif point > vec[n]:\n        return n-2\n    else:\n        for i in range(n):\n            if vec[i] <= point and point <= vec[i+1]:\n                return i\n\n#def graf()", "meta": {"hexsha": "4a922ea30c606371f67e8140acb20f43101de718", "size": 1086, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Trilinear Interpolation/Bilinear.py", "max_stars_repo_name": "Roseck16/Interpolation", "max_stars_repo_head_hexsha": "20513e02241824e37c9eab6642fc2f3139dd8e00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-14T03:33:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T03:33:57.000Z", "max_issues_repo_path": "src/Trilinear Interpolation/Bilinear.py", "max_issues_repo_name": "Roseck16/Interpolation", "max_issues_repo_head_hexsha": "20513e02241824e37c9eab6642fc2f3139dd8e00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Trilinear Interpolation/Bilinear.py", "max_forks_repo_name": "Roseck16/Interpolation", "max_forks_repo_head_hexsha": "20513e02241824e37c9eab6642fc2f3139dd8e00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2558139535, "max_line_length": 86, "alphanum_fraction": 0.5285451197, "include": true, "reason": "import numpy", "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739076, "lm_q2_score": 0.8933094152856196, "lm_q1q2_score": 0.8515695698161002}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport subprocess\n\ndef backtrace(backpointers, node, involved):\n    optimal = False\n    for P in backpointers[node]:\n        if backtrace(backpointers, (P[0], P[1]), involved):\n            P[2] = True\n            optimal = True\n            involved[node[0], node[1]] = 1\n    if node[0] == 0 and node[1] == 0:\n        print(node)\n        return True #Reached the beginning\n    return optimal\n\ndef LevDist(a, b):\n    #Third element in backpointers stores whether this is part\n    #of an optimal path\n    M = len(a)\n    N = len(b)\n    D = np.zeros((M+1, N+1))\n    D[:, 0] = np.arange(M+1)\n    D[0, :] = np.arange(N+1)\n    backpointers = {}\n    for i in range(0, M+1):\n        for j in range(0, N+1):\n            backpointers[(i, j)] = []\n    for i in range(0, M):\n        backpointers[(i+1, 0)].append([i, 0, False])\n    for j in range(0, N):\n        backpointers[(0, j+1)].append([0, j, False])\n    for i in range(1, M+1):\n        for j in range(1, N+1):\n            delt = 1\n            if a[i-1] == b[j-1]:\n                delt = 0\n            dul = delt + D[i-1, j-1]\n            dl = 1 + D[i, j-1]\n            du = 1 + D[i-1, j]\n            D[i, j] = min(min(dul, dl), du)\n            if dul == D[i, j]:\n                backpointers[(i, j)].append([i-1, j-1, False])\n            if dl == D[i, j]:\n                backpointers[(i, j)].append([i, j-1, False])\n            if du == D[i, j]:\n                backpointers[(i, j)].append([i-1, j, False])\n    involved = np.zeros((M+1, N+1))\n    backtrace(backpointers, (M, N), involved) #Recursive backtrace from the end\n    return (D, backpointers)\n\n\ndef writeChar(fout, i, j, c, bold = False):\n    if bold:\n        fout.write(\"\\\\node at (%g, %g) {\\\\textbf{%s}};\\n\"%(j+0.5, i+0.5, c))\n    else:\n        fout.write(\"\\\\node at (%g, %g) {%s};\\n\"%(j+0.5, i+0.5, c))\n\ndef drawPointers(fout, backpointers, M, N):\n    for idx in backpointers:\n        for P in backpointers[idx]:\n            color = 'black'\n            if P[2]:\n                color = 'red'\n            s = [idx[1]+1.4, M-idx[0]+0.8]\n            if idx[0]-P[0] == 0: #Left arrow\n                fout.write(\"\\\\draw [thick, ->, %s] (%g, %g) -- (%g, %g);\\n\"%(color, s[0], s[1], P[1]+1.6, s[1]))\n            elif idx[1]-P[1] == 0: #Up arrow\n                fout.write(\"\\\\draw [thick, ->, %s] (%g, %g) -- (%g, %g);\\n\"%(color, s[0], s[1], s[0], M-P[0]+0.2))\n            else: #Diagonal Arrow\n                fout.write(\"\\\\draw [thick, ->, %s] (%g, %g) -- (%g, %g);\\n\"%(color, s[0], s[1], P[1]+1.6, M-P[0]+0.2))\n\ndef drawAllPointers(fout, M, N):\n    for i in range(1, M+1):\n        for j in range(1, N+1):\n            color = 'black'\n            s = [j+1.4, M-i+0.8]\n            #Left arrow\n            fout.write(\"\\\\draw [thick, ->, %s] (%g, %g) -- (%g, %g);\\n\"%(color, s[0], s[1], j-1+1.6, s[1]))\n            #Up arrow\n            fout.write(\"\\\\draw [thick, ->, %s] (%g, %g) -- (%g, %g);\\n\"%(color, s[0], s[1], s[0], M-(i-1)+0.2))\n            #Diagonal Arrow\n            fout.write(\"\\\\draw [thick, ->, %s] (%g, %g) -- (%g, %g);\\n\"%(color, s[0], s[1], j-1+1.6, M-(i-1)+0.2))\n\n\ndef LevenshteinExample(a, b, doPointers = False, doAllPointers = False):\n    #Make Levenshtein Example\n    M = len(a)\n    N = len(b)\n    (D, backpointers) = LevDist(a, b)\n    fout = open(\"levfig.tex\", \"w\")\n    fout.write(\"\\\\documentclass[12pt,oneside,a4paper]{article}\")\n    fout.write(\"\\\\usepackage{tikz}\")\n    fout.write(\"\\\\begin{document}\")\n    fout.write(\"\\\\begin{tikzpicture}\")\n    fout.write(\"\\\\draw [help lines] (0, 0) grid (%i,%i);\\n\"%(N+2, M+2))\n    \n    writeChar(fout, M, 0, '\\\\_')\n    for i in range(M):\n        writeChar(fout, M-(i+1), 0, a[i])\n        \n    writeChar(fout, M+1, 1, '\\\\_')\n    for j in range(N):\n        writeChar(fout, M+1, j+2, b[j])\n    \n    for i in range(M+1):\n        for j in range(N+1):\n            if i == M and j == N:\n                continue\n            writeChar(fout, M-i, j+1, int(D[i, j]))\n    writeChar(fout, 0, N+1, int(D[-1, -1]))\n    \n    if doPointers:\n        drawPointers(fout, backpointers, M, N)\n    elif doAllPointers:\n        drawAllPointers(fout, M, N)\n    fout.write(\"\\\\end{tikzpicture}\")\n    fout.write(\"\\\\end{document}\")\n    fout.close()\n\n    subprocess.call([\"pdflatex\", \"levfig.tex\"])\n\n\nif __name__ == '__main__':\n    LevenshteinExample(\"school\", \"fools\", doPointers=False)\n    #s = \"razmataz\"\n    #s2 = s[::-1]\n    #LevenshteinExample(s, s2, doPointers=True)\n", "meta": {"hexsha": "3cfee9d67352f4a848488fd022fb067c1e58d1b4", "size": 4451, "ext": "py", "lang": "Python", "max_stars_repo_path": "ClassExercises/Week5_EditBacktracing/levfig.py", "max_stars_repo_name": "ursinus-cs371-s2022/CoursePage", "max_stars_repo_head_hexsha": "f721a2208f8b951f15335a929fb4f96e53fb56db", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ClassExercises/Week5_EditBacktracing/levfig.py", "max_issues_repo_name": "ursinus-cs371-s2022/CoursePage", "max_issues_repo_head_hexsha": "f721a2208f8b951f15335a929fb4f96e53fb56db", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ClassExercises/Week5_EditBacktracing/levfig.py", "max_forks_repo_name": "ursinus-cs371-s2022/CoursePage", "max_forks_repo_head_hexsha": "f721a2208f8b951f15335a929fb4f96e53fb56db", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.503875969, "max_line_length": 118, "alphanum_fraction": 0.4837115255, "include": true, "reason": "import numpy", "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739075, "lm_q2_score": 0.8933093989533708, "lm_q1q2_score": 0.851569554246975}}
{"text": "'''\n\nThe eccentricity of a node v is the maximum distance from v to all other nodes in G.\n'''\n\nimport networkx as nx\n\ndef calculate(network):\n    try:\n        n = nx.eccentricity(network)\n    except:\n        return 0\n \n    if len(n.values()) == 0: \n        return 0  \n    else:\n        return round(sum(n.values())/len(n.values()), 7) \n", "meta": {"hexsha": "1bd1330c6567e4e32cf6ec48cf26b4d8f1853cc1", "size": 336, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/calculate_features_advanced/helpers/features/eccentricity.py", "max_stars_repo_name": "flysoso/NetAna-Complex-Network-Analysis", "max_stars_repo_head_hexsha": "3dd44a00f8af0cffb421e3d85b60bd46b22d99fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-03-13T11:30:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T11:26:23.000Z", "max_issues_repo_path": "src/calculate_features_advanced/helpers/features/eccentricity.py", "max_issues_repo_name": "flysoso/NetAna-Complex-Network-Analysis", "max_issues_repo_head_hexsha": "3dd44a00f8af0cffb421e3d85b60bd46b22d99fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calculate_features_advanced/helpers/features/eccentricity.py", "max_forks_repo_name": "flysoso/NetAna-Complex-Network-Analysis", "max_forks_repo_head_hexsha": "3dd44a00f8af0cffb421e3d85b60bd46b22d99fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6666666667, "max_line_length": 84, "alphanum_fraction": 0.5863095238, "include": true, "reason": "import networkx", "num_tokens": 87, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.953275038719013, "lm_q2_score": 0.8933093975331751, "lm_q1q2_score": 0.8515695505214956}}
{"text": "# @Author: yican.kz\n# @Date: 2019-08-23 23:38:16\n# @Last Modified by:   yican.kz\n# @Last Modified time: 2019-08-23 23:38:16\n\n# Standard libraries\nimport os\nimport sys\nimport random\n\n# Third party libraries\nimport pandas as pd\nimport numpy as np\nfrom numba import jit\n\nsys.path.insert(0, os.path.abspath(\"..\"))\nfrom tabular_buddy.utils import parallelize, Timer\n\n\ndef monte_carlo_pi(nsamples):\n    acc = 0\n    for i in range(nsamples):\n        x = random.random()\n        y = random.random()\n        if (x ** 2 + y ** 2) < 1.0:\n            acc += 1\n    return 4.0 * acc / nsamples\n\n\n@jit(nopython=True)\ndef monte_carlo_pi_numba(nsamples):\n    acc = 0\n    for i in range(nsamples):\n        x = random.random()\n        y = random.random()\n        if (x ** 2 + y ** 2) < 1.0:\n            acc += 1\n    return 4.0 * acc / nsamples\n\n\ndef func(data):\n    return data[\"a\"].apply(lambda x: np.sqrt(x)) - data[\"b\"] ** 2\n\n\nif __name__ == \"__main__\":\n    # ==============================================================================================================\n    # Using numba to speed up your function, [21 times!]\n    # -----------------------------------------\n    # Before speed up : Res is 3.1414 | 21 seconds\n    # After speed up  : Res is 3.1419 | 1 seconds\n    # ==============================================================================================================\n    nsamples = 10000000\n    data = pd.DataFrame({\"a\": np.random.rand(nsamples), \"b\": np.random.rand(nsamples)})\n\n    tick_tock = Timer()\n    print(\"Before speed up : Res is {:.4f} | {} seconds\".format(monte_carlo_pi(50000000), int(tick_tock())))\n    print(\"After speed up  : Res is {:.4f} | {} seconds\".format(monte_carlo_pi_numba(50000000), int(tick_tock())))\n\n    # ==============================================================================================================\n    # Using python multiprocessing to speed up your function, [3 times!]\n    # Actual performance depends on your machine\n    # -----------------------------------------\n    # Before speed up : Res 3333598.7172 | 16 seconds\n    # After speed up  : Res 3333598.7172 | 5 seconds\n    # ==============================================================================================================\n    res = func(data)\n    print(\"Before speed up : Res {:.4f} | {} seconds\".format(res.sum(), int(tick_tock())))\n    res = parallelize(data, func)\n    print(\"After speed up  : Res {:.4f} | {} seconds\".format(res.sum(), int(tick_tock())))\n", "meta": {"hexsha": "877b60cc15ef8dd7d0849386464a6a974612ae57", "size": 2488, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/speed_up_your_code.py", "max_stars_repo_name": "NickYi1990/tabluar_buddy", "max_stars_repo_head_hexsha": "d60c25c72256ae6741fb4c3cfbdf3163b7cc0ca0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/speed_up_your_code.py", "max_issues_repo_name": "NickYi1990/tabluar_buddy", "max_issues_repo_head_hexsha": "d60c25c72256ae6741fb4c3cfbdf3163b7cc0ca0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/speed_up_your_code.py", "max_forks_repo_name": "NickYi1990/tabluar_buddy", "max_forks_repo_head_hexsha": "d60c25c72256ae6741fb4c3cfbdf3163b7cc0ca0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-04T15:16:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-04T15:16:53.000Z", "avg_line_length": 35.5428571429, "max_line_length": 116, "alphanum_fraction": 0.4819131833, "include": true, "reason": "import numpy,from numba", "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.9086178994073576, "lm_q1q2_score": 0.8515665021799603}}
{"text": "'''\nExp 11: Program to demonstrate use of NumPy: Array objects.\n\nTheory:\nNumPy is a Python library used for working with arrays.\nIt also has functions for working in domain of linear algebra, fourier transform, and matrices.\nNumPy was created in 2005 by Travis Oliphant. It is an open source project and you can use it freely.\nNumPy stands for Numerical Python.\n\nIn Python we have lists that serve the purpose of arrays, but they are slow to process.\nNumPy aims to provide an array object that is up to 50x faster than traditional Python lists.\nThe array object in NumPy is called ndarray, it provides a lot of supporting functions that make working with ndarray very easy.\n0-D Arrays\n0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.\n1-D Arrays\nAn array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.\nThese are the most common and basic arrays.\n2-D Arrays\nAn array that has 1-D arrays as its elements is called a 2-D array.\nThese are often used to represent matrix or 2nd order tensors.\n\narange() is an inbuilt numpy function that returns an ndarray object containing evenly spaced values within a defined interval.\nlinspace() function returns number spaces evenly w.r.t interval.\nSimilar to numpy.arange() function but instead of step it uses sample number.\nlogspace() function returns number spaces evenly w.r.t interval on a log scale.\nzeros() function returns a new array of given shape and type, with zeros.\nones() function returns a new array of given shape and type, with ones.\nempty() is used to create an array without initializing the entries of given shape and type.\nidentity() Return a identity matrix i.e. a square matrix with ones on the main diagonal.\n\nSlicing:\nSlicing in python means taking elements from one given index to another given index.\nWe pass slice instead of index like this: [start:end].\nWe can also define the step, like this: [start:end:step].\nIf we don't pass start its considered 0\nIf we don't pass end its considered length of array in that dimension\nIf we don't pass step its considered 1\n\n@author: KHAN FARHAN NADEEM (19CO27)\n'''\n\nimport numpy as np\n#############################\n#    creating numpy arrays  #\n#############################\n#########################################\n# create 1D arrays using array function #\n#########################################\narr1d = np.array([1,2])\n\n#######################################################\n# create 2D arrays using array function of type float #\n#######################################################\narr2d = np.array([[1,2,3],[4,5,6],[7,8,9]],dtype=float)\n\n\n######################################\n# create array using arange function #\n######################################\narr_ar = np.arange(1,100,9)\n\n########################################\n# create array using linspace function #\n########################################\narr_lp = np.linspace(10,11,10)\n\n########################################\n# create array using logspace function #\n########################################\narr_logp = np.logspace(10,15,10)\n\n########################################\n# create array using various functions #\n########################################\narr_zeros = np.zeros((2,3))\narr_ones = np.ones((3,2))\narr_empty = np.empty((2,4))\narr_identity = np.identity(3)\n\n##############################\n## accessing array elements ##\n##############################\nprint('\\n arr1d =',arr1d)\nprint('\\n arr2d =')\n\nfor row in arr2d:\n    print(row)\n\nprint('\\narr_ar =',arr_ar)\nprint('\\narr_lp =',arr_lp,' having size of',arr_lp.size)\nprint('\\narr_logp =',arr_logp,' having size of',arr_logp.size)\nprint('\\narr_zeros =\\n',arr_zeros)\nprint('\\narr_ones =\\n',arr_ones)\nprint('\\narr_empty =\\n',arr_empty)\nprint('\\narr_identity =\\n',arr_identity)\n\n###################################\n###  performing array operations ##\n###################################\nprint('\\nPerforming Array Operations:')\nprint('Addition of 2D arrays\\n',arr2d + arr_identity)\nprint('Substraction of 2D arrays\\n',arr2d - arr_identity)\nprint('Multiplication of 2D arrays\\n',arr2d * arr_identity)\nprint('Matrix Multiplication of 2D arrays\\n',arr2d @ arr_identity)\nprint('Transpose of 2D arrays\\n',arr2d.transpose())\n\n###############################\n# performing slice operations #\n###############################\nprint('Elements of Second Row and First 2 Columns',arr2d[1,:2])\nprint('Elements of Last Row and Second Column onwards',arr2d[-1,1:])\nprint(arr2d[arr1d])\n\n################################\n# performing reshape on arrays #\n################################\n\n##################################\n# reshaping 1D array to 2D array #\n##################################\nnewarr = arr1d.reshape(1,2)\nprint('reshaped array : ',newarr)\n\n'''\nConclusion:\nNumPy is a fundamental package for scientific computation & mathematical operations in python.\nNumPy is way more powerful than Lists.\n'''", "meta": {"hexsha": "e04c5929ecbe2bc0a7b4c6c76e9437646f7b6c8f", "size": 4897, "ext": "py", "lang": "Python", "max_stars_repo_path": "Exp11.py", "max_stars_repo_name": "FarhanKhan1911/Python-Practice-code", "max_stars_repo_head_hexsha": "6567fe57c13c49a465175f95c80967f0cb36aaa4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-16T18:41:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T18:41:21.000Z", "max_issues_repo_path": "Exp11.py", "max_issues_repo_name": "FarhanKhan1911/Python-Practice-code", "max_issues_repo_head_hexsha": "6567fe57c13c49a465175f95c80967f0cb36aaa4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exp11.py", "max_forks_repo_name": "FarhanKhan1911/Python-Practice-code", "max_forks_repo_head_hexsha": "6567fe57c13c49a465175f95c80967f0cb36aaa4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-16T18:41:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-16T18:41:25.000Z", "avg_line_length": 38.2578125, "max_line_length": 128, "alphanum_fraction": 0.6136410047, "include": true, "reason": "import numpy", "num_tokens": 1075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.9086178975514609, "lm_q1q2_score": 0.851566497253582}}
{"text": "import numpy as np\n\n\ndef softmax(X):\n    e = np.exp(X - np.amax(X, axis=1, keepdims=True))\n    return e/np.sum(e, axis=1, keepdims=True)\n\n\ndef categorical_cross_entropy(y_pred, y_true, eps=1e-15):\n    # Assumes one-hot encoding.\n    y_pred = np.clip(y_pred, eps, 1 - eps)\n    # XXX: do we need to normalize?\n    y_pred /= y_pred.sum(axis=1, keepdims=True)\n    loss = -np.sum(y_true * np.log(y_pred), axis=1)\n    return loss\n\n\ndef one_hot_encode(labels, n_classes, out=None):\n    out_shape = (labels.size, n_classes)\n    if labels.dtype != np.dtype(int):\n        raise ValueError('labels.dtype must be int')\n    if out is None:\n        out = np.empty(out_shape)\n    else:\n        if out.shape != out_shape:\n            raise ValueError('shape mismatch')\n    out.fill(0)\n    if labels.size == 1:\n        out[0, labels] = 1\n    else:\n        for c in range(n_classes):\n            out[labels == c, c] = 1\n    return out\n\n\ndef one_hot_decode(one_hot, out=None):\n    out_shape = (one_hot.shape[0],)\n    if out is None:\n        out = np.empty(out_shape, dtype=np.dtype(int))\n    else:\n        if out.dtype != np.dtype(int):\n            raise ValueError('out.dtype must be int')\n        if out.shape != out_shape:\n            raise ValueError('shape mismatch')\n    result = np.argmax(one_hot, axis=1)\n    np.copyto(out, result)\n    return out\n", "meta": {"hexsha": "1dacfb904d710534548e1239bbcda2d2a7e4d476", "size": 1336, "ext": "py", "lang": "Python", "max_stars_repo_path": "cudarray/numpy_backend/nnet/special.py", "max_stars_repo_name": "gorenje/cudarray", "max_stars_repo_head_hexsha": "a6d287fe371a93bcce2d3767925a5ea4e0a82e1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 228, "max_stars_repo_stars_event_min_datetime": "2015-01-03T17:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-21T22:23:17.000Z", "max_issues_repo_path": "cudarray/numpy_backend/nnet/special.py", "max_issues_repo_name": "maxosprojects/cudarray", "max_issues_repo_head_hexsha": "a2cffbb1434db9a7e6ed83211300d23d47630d2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 77, "max_issues_repo_issues_event_min_datetime": "2015-01-03T20:23:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T11:56:27.000Z", "max_forks_repo_path": "cudarray/numpy_backend/nnet/special.py", "max_forks_repo_name": "maxosprojects/cudarray", "max_forks_repo_head_hexsha": "a2cffbb1434db9a7e6ed83211300d23d47630d2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2015-01-06T17:07:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T12:41:05.000Z", "avg_line_length": 27.8333333333, "max_line_length": 57, "alphanum_fraction": 0.6070359281, "include": true, "reason": "import numpy", "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338035725359, "lm_q2_score": 0.885631484383387, "lm_q1q2_score": 0.8515646097427491}}
{"text": "import numpy as np\n\n\ndef euclidean_distance(u, v):\n    \"\"\"\n    Args:\n        u (array-like): Vector\n        v (array-like): Vector\n\n    Returns:\n        The euclidean distance between vectors u and v.\n\n    \"\"\"\n    return np.linalg.norm(np.array(u) - np.array(v))\n\n\ndef manhattan_distance(u, v):\n    \"\"\"\n    Args:\n        u (array-like): Vector\n        v (array-like): Vector\n\n    Returns:\n        The manhattan distance between vectors u and v.\n\n    \"\"\"\n    return np.abs(np.array(u) - np.array(v)).sum()\n\n\ndef hamming_distance(u, v):\n    \"\"\"\n    Args:\n        u (array-like): Vector\n        v (array-like): Vector\n\n    Returns:\n        The hamming distance between vectors u and v.\n\n    \"\"\"\n    return np.count_nonzero(np.array(u) != np.array(v))\n", "meta": {"hexsha": "8622f9a41f7230bccce5bd6b231fda48fadacf76", "size": 748, "ext": "py", "lang": "Python", "max_stars_repo_path": "reason/metrics/_distance.py", "max_stars_repo_name": "alisoltanirad/Reason", "max_stars_repo_head_hexsha": "9062dc8e365efa424706a309de5cfb90ab497e9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-21T21:26:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-21T21:26:27.000Z", "max_issues_repo_path": "reason/metrics/_distance.py", "max_issues_repo_name": "alisoltanirad/Reason", "max_issues_repo_head_hexsha": "9062dc8e365efa424706a309de5cfb90ab497e9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-12-26T18:55:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-10T09:15:32.000Z", "max_forks_repo_path": "reason/metrics/_distance.py", "max_forks_repo_name": "alisoltanirad/reason", "max_forks_repo_head_hexsha": "9062dc8e365efa424706a309de5cfb90ab497e9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.243902439, "max_line_length": 55, "alphanum_fraction": 0.570855615, "include": true, "reason": "import numpy", "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338057771058, "lm_q2_score": 0.8856314813647587, "lm_q1q2_score": 0.8515646087926724}}
{"text": "import numpy as np\n\n\ndef build_stretch_matrix(x, y):\n    stretch_transform = np.array(\n        [[x, 0, 0],\n         [0, y, 0],\n         [0, 0, 1]],\n        dtype=np.float32)\n    return stretch_transform\n\n\ndef build_shear_matrix(x, y):\n    tan_x = np.tan(x)\n    tan_y = np.tan(y)\n    shear_transform = np.array(\n        [[1,     tan_x, 0],\n         [tan_y, 1,     0],\n         [0,     0,     1]],\n        dtype=np.float32)\n    return shear_transform\n\n\ndef build_rotate_matrix(t):\n    cos_t = np.cos(t)  # t must be in radians\n    sin_t = np.sin(t)\n    rotate_transform = np.array(\n        [[cos_t,  sin_t, 0],\n         [-sin_t, cos_t, 0],\n         [0,          0, 1]],\n        dtype=np.float32)\n    return rotate_transform\n\n\ndef build_flip_matrix(h, v):\n    # reflect about x and y\n    if h and v:\n        flip_transform = np.array(\n            [[-1,  0, 0],\n             [ 0, -1, 0],\n             [ 0,  0, 1]], dtype=np.float32)\n    # reflect about only x\n    elif h and not v:\n        flip_transform = np.array(\n            [[ 1,  0, 0],\n             [ 0, -1, 0],\n             [ 0,  0, 1]], dtype=np.float32)\n    # reflect about only y\n    elif not h and v:\n        flip_transform = np.array(\n            [[-1,  0, 0],\n             [ 0,  1, 0],\n             [ 0,  0, 1]], dtype=np.float32)\n    # do not reflect\n    else:\n        flip_transform = np.eye(3, dtype=np.float32)\n\n    return flip_transform\n\n\ndef build_translate_matrix(x, y):\n    translate_transform = np.array(\n        [[1, 0, x],\n         [0, 1, y],\n         [0, 0, 1]], dtype=np.float32)\n    return translate_transform\n\n\ndef build_transformation_matrix(\n        imsize, theta=None, offset=None, flip=None, shear=None, stretch=None):\n\n    # use the identity matrix as default\n    if theta is None:\n        theta = 0.\n    if offset is None:\n        offset = (0., 0.)\n    if flip is None:\n        flip = (False, False)\n    if shear is None:\n        shear = (0., 0.)\n    if stretch is None:\n        stretch = (1., 1.)\n\n    cx, cy = np.array(imsize) / 2 - 0.5\n    center_matrix = build_translate_matrix(cx, cy)\n    stretch_matrix = build_stretch_matrix(*stretch)\n    shear_matrix = build_shear_matrix(*shear)\n    rotate_matrix = build_rotate_matrix(theta)\n    flip_matrix = build_flip_matrix(*flip)\n    uncenter_matrix = build_translate_matrix(-cx, -cy)\n    translate_matrix = build_translate_matrix(*offset)\n\n    transform_matrix = center_matrix.dot(\n        stretch_matrix).dot(\n        shear_matrix).dot(\n        rotate_matrix).dot(\n        flip_matrix).dot(\n        uncenter_matrix).dot(\n        translate_matrix\n    )\n\n    return transform_matrix\n", "meta": {"hexsha": "b3a91689eb45e6c56dd004b6a337b6ee599a4485", "size": 2612, "ext": "py", "lang": "Python", "max_stars_repo_path": "daug/transforms/transforms.py", "max_stars_repo_name": "hjweide/daug", "max_stars_repo_head_hexsha": "053e8087fc33c5dba01a010ba04a6c916410cb31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-07-17T13:46:01.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-17T14:34:24.000Z", "max_issues_repo_path": "daug/transforms/transforms.py", "max_issues_repo_name": "hjweide/daug", "max_issues_repo_head_hexsha": "053e8087fc33c5dba01a010ba04a6c916410cb31", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "daug/transforms/transforms.py", "max_forks_repo_name": "hjweide/daug", "max_forks_repo_head_hexsha": "053e8087fc33c5dba01a010ba04a6c916410cb31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.359223301, "max_line_length": 78, "alphanum_fraction": 0.5524502297, "include": true, "reason": "import numpy", "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338057771058, "lm_q2_score": 0.885631476836816, "lm_q1q2_score": 0.8515646044389024}}
{"text": "\"\"\"\nIntensive transformation is an basic gray level transformation\nFormula:\n\n    X = ( 255 / (high - low) ) * ( X - low)\n\n    X: The intensive in each pixel\n    255: The max level intensive of image\n    high: The highest gray level of image\n    low: The lowest gray level of image\n\n\"\"\"\n\nimport cv2\nimport numpy as np\nfrom __utils__.general import show_image\nfrom histogram.plot_histogram import use_calc_hist_in_cv2_function\n\n\ndef contrast_schetching(image):\n    # Get the high and low level intensive\n    high = image.max()\n    low = image.min()\n\n    # Copy gray image\n    image_gray = np.copy(image)\n\n    # Contrast stretching\n    for pixel in np.nditer(image_gray, op_flags=['readwrite']):\n        pixel[...] = np.round(np.abs((255 / float(high - low)) * (pixel - low)))\n    return image_gray\n\n\nif __name__ == '__main__':\n    img = cv2.imread('../../asserts/images/wiki.jpg')\n    img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n    res = contrast_schetching(img)\n    show_image(np.hstack((img, res)))\n", "meta": {"hexsha": "12c79d95973a4c752e147395e072d3c10194f2c5", "size": 1000, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/grayscaling/contrast_schetching.py", "max_stars_repo_name": "jerry-le/computer-vision", "max_stars_repo_head_hexsha": "bd81a0561680aa976c21c7902cf929257ffeedda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-10-14T02:05:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-14T02:05:58.000Z", "max_issues_repo_path": "src/grayscaling/contrast_schetching.py", "max_issues_repo_name": "jerry-le/computer-vision", "max_issues_repo_head_hexsha": "bd81a0561680aa976c21c7902cf929257ffeedda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-05T01:48:48.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-05T01:48:48.000Z", "max_forks_repo_path": "src/grayscaling/contrast_schetching.py", "max_forks_repo_name": "jerry-le/computer-vision", "max_forks_repo_head_hexsha": "bd81a0561680aa976c21c7902cf929257ffeedda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.641025641, "max_line_length": 80, "alphanum_fraction": 0.677, "include": true, "reason": "import numpy", "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862455, "lm_q2_score": 0.8856314723088732, "lm_q1q2_score": 0.8515646039900052}}
{"text": "'''\nK Nearest Neighbor implementations for the points\n    data = [[(1,6), 7], [(2,4), 8], [(3,7), 16], [(6,8),44], [(7,1),50], [(8,4),68]]\nSeeking the point\n    q = (4,2)\nUsing two different distance formulas: Manhathan and euclidean_distance\nIf the the subsequent elements to k have the same distance as k, those are\nalso included.\n\n\n'''\n\n\nimport math\nimport numpy as np\n\n\ndef manh_dist(a, b):\n    return abs(a[0]-b[0]) + abs(a[1]-b[1])\n\ndef euclidean_dist(a,b):\n    return math.sqrt(math.pow(a[0]-b[0], 2)+ math.pow(a[1]-b[1], 2))\n\ndef KNN(k, data, q, dist):\n    r = sorted([(dist(a[0],q), index) for index, a in enumerate(data)])\n    avg = [data[b][1] for a, b in r[:k]]\n\n    # Check if the distance value is the same for the elements after k\n    # if so add them to the list to get the averages.\n    max_k_value = r[k-1][0]\n    start_index = k\n    while True:\n        if r[start_index][0] == max_k_value:\n            avg.append(data[r[start_index][1]][1])\n            start_index += 1\n        else: break\n    average = np.mean(avg)\n    print 'Average for {} Neighbors, using {} as distance is: {}'.format(\n        k, dist.__name__, average\n    )\n\n\nif __name__ == '__main__':\n    data = [[(1,6), 7], [(2,4), 8], [(3,7), 16], [(6,8),44], [(7,1),50], [(8,4),68]]\n    q = (4,2)\n    KNN(1, data, q, manh_dist)\n    KNN(3, data, q, manh_dist)\n    KNN(1, data, q, euclidean_dist)\n    KNN(3, data, q, euclidean_dist)\n", "meta": {"hexsha": "8700dde0ec225ea581be1e023dfe6955f700ca5b", "size": 1412, "ext": "py", "lang": "Python", "max_stars_repo_path": "extra/SupervisedLearning/Domain_knowledge.py", "max_stars_repo_name": "armandosrz/UdacityNanoMachine", "max_stars_repo_head_hexsha": "5f2b11b23dedfa681480fe036620836b32a5d955", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extra/SupervisedLearning/Domain_knowledge.py", "max_issues_repo_name": "armandosrz/UdacityNanoMachine", "max_issues_repo_head_hexsha": "5f2b11b23dedfa681480fe036620836b32a5d955", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extra/SupervisedLearning/Domain_knowledge.py", "max_forks_repo_name": "armandosrz/UdacityNanoMachine", "max_forks_repo_head_hexsha": "5f2b11b23dedfa681480fe036620836b32a5d955", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.24, "max_line_length": 84, "alphanum_fraction": 0.5835694051, "include": true, "reason": "import numpy", "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862455, "lm_q2_score": 0.885631470799559, "lm_q1q2_score": 0.8515646025387485}}
{"text": "\"\"\"\nDemo of Runge Phenomenon\n\nAuthor: HearyShen\nDate: 2020.10.28\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nLEFT_BOUND = -1\nRIGHT_BOUND = 1.01\n\nPLT_ROWS = 2\nPLT_COLS = 3\n\n\ndef runge_function(x):\n    y = 1 / (1 + 25 * x**2)     # Runge Function\n    return y\n\n\ndef runge_polyfit(degree):\n    # original runge function\n    x_orig = np.arange(LEFT_BOUND, RIGHT_BOUND, 0.01)\n    y_orig = runge_function(x_orig)\n\n    # sample points\n    interval = 2 / degree\n    x_sample = np.arange(LEFT_BOUND, RIGHT_BOUND, interval)\n    y_sample = runge_function(x_sample)\n\n    plt.title(f\"{degree}-degree polyfit\")\n\n    # plot original runge function\n    plt.plot(x_orig, y_orig, label=\"runge\")\n\n    # plot runge sample points\n    plt.plot(x_sample, y_sample, \"rx\")\n\n    coef = np.polyfit(x_sample, y_sample, degree)\n    # y_fit = sum([coef[i] * (x**(degree-i)) for i in range(degree+1)])\n    y_fit = np.polyval(coef, x_orig)\n    plt.plot(x_orig, y_fit, label=f\"polyfit-{degree}\")\n\n    plt.legend()\n    # plt.show()\n\n\ndef runge_phenomenon(degrees=[1, 5, 9, 13, 15, 17]):\n    plt.figure(figsize=(16, 9))\n    for i in range(min(PLT_ROWS*PLT_COLS, len(degrees))):\n        # plot each polynomial function of each degree\n        plt.subplot(PLT_ROWS, PLT_COLS, i+1)\n\n        # plot runge function\n        runge_polyfit(degrees[i])\n\n    plt.show()\n\n\nif __name__ == \"__main__\":\n    runge_phenomenon()\n", "meta": {"hexsha": "ea4744ba55d0f13814d2afea8e107ef62f083beb", "size": 1389, "ext": "py", "lang": "Python", "max_stars_repo_path": "runge.py", "max_stars_repo_name": "HearyShen/CPSS-Talk", "max_stars_repo_head_hexsha": "54141c65b13ba25566e9cb904d3eda3b75cf1b76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-28T07:53:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T07:53:41.000Z", "max_issues_repo_path": "runge.py", "max_issues_repo_name": "HearyShen/CPSS-Talk", "max_issues_repo_head_hexsha": "54141c65b13ba25566e9cb904d3eda3b75cf1b76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "runge.py", "max_forks_repo_name": "HearyShen/CPSS-Talk", "max_forks_repo_head_hexsha": "54141c65b13ba25566e9cb904d3eda3b75cf1b76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.703125, "max_line_length": 71, "alphanum_fraction": 0.6515478762, "include": true, "reason": "import numpy", "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.9059898210180105, "lm_q1q2_score": 0.851551932155967}}
{"text": "from __future__ import division\nimport numpy as np\n\ndef recursive_trapezoid(n,R,f,a,b):\n    '''\n    Computes the integral evaluation using the recursive trapezoid rule.\n    The function actually evaluates R(n,m) but since m is 0 for us to \n    prefer trapezoid rule, we don't accept that as an input.\n    It accepts the function 'f' we are evaluating.\n    returns R(n,0) added to R.\n\n    The base case of this recursive this function is R(0,0) which\n    is assumed to have already been inserted into the dictionary R\n    that's why it is not added here.\n    '''\n    retVal = -1\n    if (n,0) in R.keys():\n        retVal = R[(n,0)]\n    elif n == 0:\n        retVal = 0.5 * (b-a) * (f(a) + f(b))\n    else:\n        h = (b-a) * (0.5 ** n)\n        retVal = 0.5 * recursive_trapezoid(n-1, R, f, a, b) + h * sum([ f(a+(2*k-1)*h) for k in xrange(1,(2**(n-1))+1)])\n    return retVal\n\ndef get_R(n, m, R, f, a, b):\n    '''\n    This function computes and returns the value of R with R(n,m) added to it.\n    It expects the old R as an input and also the function we are evaluating\n    '''\n    retVal = -1\n    if (n,m) in R.keys():\n        retVal = R[(n,m)]\n    elif m == 0:\n        # call recursive trapezoidal function\n        retVal = recursive_trapezoid(n,R,f,a,b)\n    else:\n        retVal = get_R(n,m-1,R,f,a,b) + (1.0/((4**m)-1)) * (get_R(n,m-1,R,f,a,b) - get_R(n-1,m-1,R,f,a,b))\n    return retVal\n        \ndef integrate(f,a,b,nrows):\n    # The R \"matrix\" which would store the values computed from trapezoidal and\n    # Romberg's algorithm\n    # This is implemented as a dictionary which stores a tuple (n,m) as the key\n    # and the corresponding R(n,m) evaluation as the value against the (n,m) key\n    R = {}\n    rows = nrows\n    for i in range(rows):\n        for j in range(i+1):\n            R[(i,j)] = get_R(i,j,R,f,a,b)\n    return R[i,j], R\n\ndef printR(R, n):\n    for i in range(rows):\n        for j in range(i+1):\n            print(\"{0:.10f}\".format(R[(i,j)])),\n        print\n    print\n\n\nif __name__ == '__main__':\n    rows = 9\n    #---------function \n    print(\"Analytical Integral is ln(3) = \"),\n    Actual = 1.0986122886681098\n    print(Actual)\n    f = lambda x: 1 / (1+x)\n    a = 0\n    b = 2\n    integral, R = integrate(f,a,b,rows)\n    print \"Numerical Integral is :\",integral\n    print(\"Error is {}\".format(abs(Actual-integral)))\n    printR(R,rows)\n    #---------function 2\n    print(\"Analytical Integral is e^1 - 1 = \"),\n    Actual = 1.718281828459045\n    print(Actual)\n    f = lambda x: np.e ** x \n    a = 0\n    b = 1\n    integral, R = integrate(f,a,b,rows)\n    print \"Numerical Integral is\", integral\n    print(\"Error is {}\".format(abs(Actual-integral)))\n    printR(R,rows)\n    #---------function 3\n    print(\"Analytical Integral is 2/3 = \"),\n    Actual = 0.6666666666666666\n    print(Actual)\n    f = lambda x: np.sqrt(x) \n    a = 0\n    b = 1\n    integral, R = integrate(f,a,b,rows)\n    print \"Numerical Integral is\", integral\n    print(\"Error is {}\".format(abs(Actual-integral)))\n    printR(R,rows)\n\n", "meta": {"hexsha": "51a0cae0d348e0a1c092f11e0fb0f8012f8c675e", "size": 3007, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercise4/exercise3.py", "max_stars_repo_name": "kunalghosh/BECS-114.1100-Computational-Science", "max_stars_repo_head_hexsha": "ca91ac59cb5276d213c1aec50ae7786efe72ae43", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercise4/exercise3.py", "max_issues_repo_name": "kunalghosh/BECS-114.1100-Computational-Science", "max_issues_repo_head_hexsha": "ca91ac59cb5276d213c1aec50ae7786efe72ae43", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise4/exercise3.py", "max_forks_repo_name": "kunalghosh/BECS-114.1100-Computational-Science", "max_forks_repo_head_hexsha": "ca91ac59cb5276d213c1aec50ae7786efe72ae43", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0, "max_line_length": 120, "alphanum_fraction": 0.5819753908, "include": true, "reason": "import numpy", "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913356558485, "lm_q2_score": 0.9059898153067649, "lm_q1q2_score": 0.8515519283127833}}
{"text": "import numpy as np\n\n\ndef split(x, h):\n    \"\"\" Split the interval\n    \n    Args:\n        x: list/ndarray, the interval to be splited\n        h: double, the step length of the split\n\n    Returns:\n        t: ndarray/list, the split of the interval t\n    \"\"\"\n    # the endpoints of the interval\n    a, b = x \n    n = int((b - a)/h)\n    t = np.linspace(a, b, n+1)\n    \n    return t\n\n\ndef improved_Euler(x, func, ini):\n    \"\"\" Solve IVP by improved Euler method\n    \n    Args:\n        x: list/ndarray, the splitiation of the interval\n        func: the function f(x, y) which satisfies y'(x) = f(x, y)\n        ini: the initial value for IVP\n\n    Returns:\n        y: ndarray, the list of values of y at every t\n    \"\"\"\n    n = len(x)\n    h = x[1] - x[0]\n\n    # begin iteration\n    y = np.zeros(n)\n    y[0] = ini\n    for i in range(1, n):\n        y0 = y[i-1] + h*func(x[i-1], y[i-1])\n        y[i] = y[i-1] + h*(func(x[i-1], y[i-1]) + func(x[i], y0))/2\n\n    return y\n\n\ndef f1(x, y):\n    return y**2\n\n\ndef f2(x, y):\n    return x/y \n\n\ndef g(x, y):\n    return np.sin(x)/x\n\n\nif __name__ == '__main__':\n    h = 0.1\n    # the solution for ordinary differential equation 1\n    t1 = [0, 0.4]\n    x1 = split(t1, h)\n    y1 = improved_Euler(x1, f1, 1)\n    y1_true = 1/(1 - x1)\n    print(\"The numerical solution, analytic solution and the error of question 1 are as follows:\")\n    for item in zip(x1, y1, y1_true):\n        print(f\"{item[0]:.1f}\\t{item[1]:.6f}\\t{item[2]:.6f}\\t{item[2] - item[1]:.6f}\")\n    # the solution for ordinary differential equation 2\n    t2 = [2.0, 2.6]\n    x2 = split(t2, h)\n    y2 = improved_Euler(x2, f2, 1)\n    y2_true = np.sqrt(x2**2 - 3)\n    print(\"The numerical solution, analytic solution and the error of question 2 are as follows:\")\n    for item in zip(x2, y2, y2_true):\n        print(f\"{item[0]:.1f}\\t{item[1]:.6f}\\t{item[2]:.6f}\\t{item[2] - item[1]:.6f}\")\n\n    # thinking question\n    # calculate the integral \\int_0^1 \\frac{\\sin x}{x} dx\n    x3 = split([1e-32, 1], 0.01)\n    y3 = improved_Euler(x3, g, 0)\n    print(f\"The value of Si(1) is {y3[-1]:.5f}.\")\n\n", "meta": {"hexsha": "9c2efcbed82f960b7bbe577492fad3ca43bb94dd", "size": 2071, "ext": "py", "lang": "Python", "max_stars_repo_path": "OrdinaryDifferentialEquations/improved_Euler.py", "max_stars_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_stars_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "OrdinaryDifferentialEquations/improved_Euler.py", "max_issues_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_issues_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OrdinaryDifferentialEquations/improved_Euler.py", "max_forks_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_forks_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9518072289, "max_line_length": 98, "alphanum_fraction": 0.558184452, "include": true, "reason": "import numpy", "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.9059898140375993, "lm_q1q2_score": 0.8515519225452003}}
{"text": "import numpy as np\n\ndef FaultFreq(n, fr,d,D,phi):\n    \"\"\"\n    :param n:   number of rolling elements\n    :param fr:  shaft speed\n    :param d:   ball diameter\n    :param D:   pitch diameter\n    :param phi: the angle of load from radial plane\n    :return:    four fault frequency\n    \"\"\"\n    BPFO = n*fr/2*(1 - d/D*np.cos(phi))\n    BPFI = n*fr/2*(1 + d/D*np.cos(phi))\n    FTF = fr/2*(1 - d/D*np.cos(phi))\n    BSF = D*fr/(d)*(1 - (d/D*np.cos(phi))**2)\n    print(\"BPFO: %.4ffr \\nBPFI: %.4ffr \\nFTF: %.4ffr \\nBSF: %.4ffr\"%(BPFI, BPFO, FTF, BSF))\n    return BPFO, BPFI, FTF, BSF\n\n\nif __name__ == '__main__':\n    # SKF 6205-2RS JEM: drive end parameters\n    n = 9\n    fr = 1\n    d = 0.3126 * 25.4\n    D = 1.537 * 25.4\n    phi = 0\n\n    print('Drive end fault frequency:')\n    bpfo, bpfi, ftf, bsf = FaultFreq(n, fr, d, D, phi)\n    \n    # SKF 6203-2RS JEM: fan end parameters\n    n = 8\n    fr = 1\n    d = 0.2656 * 25.4\n    D = 1.122 * 25.4\n    phi = 0\n    print('\\nFan end fault frequency:')\n    bpfo, bpfi, ftf, bsf = FaultFreq(n, fr, d, D, phi)\n\n", "meta": {"hexsha": "354b7719f9b163806be62f92ff7991cfad47753b", "size": 1040, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/scratches/phm/FaultFreq.py", "max_stars_repo_name": "GuokaiLiu/RTD", "max_stars_repo_head_hexsha": "27a13b60292629925beb2fd1b4cf837874cc2b49", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/scratches/phm/FaultFreq.py", "max_issues_repo_name": "GuokaiLiu/RTD", "max_issues_repo_head_hexsha": "27a13b60292629925beb2fd1b4cf837874cc2b49", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/scratches/phm/FaultFreq.py", "max_forks_repo_name": "GuokaiLiu/RTD", "max_forks_repo_head_hexsha": "27a13b60292629925beb2fd1b4cf837874cc2b49", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0, "max_line_length": 91, "alphanum_fraction": 0.5480769231, "include": true, "reason": "import numpy", "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305318133553, "lm_q2_score": 0.8840392802184581, "lm_q1q2_score": 0.8515336260287212}}
{"text": "'''\n@ author: Tinotenda Mhlanga\n@ program: Trapezoidal Rule\n\n'''\n\nfrom math import sin, pi, exp, factorial\nimport scipy.integrate\n\nf = lambda x: exp(-x)\n\nmac_series = 0\nx1 = 1\na = 0\nb = 1\nn = 100 # number of divisions\nh = (b - a) / n # step size\nS = 0.5 * (f(a) + f(b))\n\n# Trapezoidal Rule\nfor i in range(1, n):\n\t# Summation\n\tS += f(a + i*h)\n\nI = h * S\n\n# Maclaurin Expansion\nfor i in range(1, 8):\n\tif i % 2 == 0:\n\t\tmac_series -= x1**i/(i * factorial(i - 1))\n\telse:\n\t\tmac_series += x1**i/(i * (factorial(i - 1)))\n\n# Exact Value\nexact_value = scipy.integrate.quad(f, 0, 1)\n\nprint(f'\\nExact Value: {round(exact_value[0], 12)}')\nprint(f'\\nResult Using Trapezoidal Rule: {round(I, 12)}')\nprint(f'\\nResult Using Maclaurins Expansion: {round(mac_series, 12)}')\n", "meta": {"hexsha": "585858996ed3e223874eaba6ad295212eb249451", "size": 755, "ext": "py", "lang": "Python", "max_stars_repo_path": "trapezoidal_rule.py", "max_stars_repo_name": "Tino-tech/Numerical-Analysis", "max_stars_repo_head_hexsha": "bba640e6c4d6b3fde2a7ffcefe067a3b95ce009d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trapezoidal_rule.py", "max_issues_repo_name": "Tino-tech/Numerical-Analysis", "max_issues_repo_head_hexsha": "bba640e6c4d6b3fde2a7ffcefe067a3b95ce009d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trapezoidal_rule.py", "max_forks_repo_name": "Tino-tech/Numerical-Analysis", "max_forks_repo_head_hexsha": "bba640e6c4d6b3fde2a7ffcefe067a3b95ce009d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.875, "max_line_length": 70, "alphanum_fraction": 0.6264900662, "include": true, "reason": "import scipy", "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305307578323, "lm_q2_score": 0.8840392741081575, "lm_q1q2_score": 0.8515336192099694}}
{"text": "import numpy as np\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.pyplot as plt\r\nfrom itertools import product, combinations, combinations_with_replacement\r\nimport math\r\nimport re\r\nimport vtk_visualizer as vv\r\nimport numpy as np\r\nimport sys\r\nfrom PyQt5.QtWidgets import *\r\n\r\n##http://mathworld.wolfram.com/topics/Surfaces.html\r\n\r\ndef showFigure(filename):\r\n    fig = plt.figure()\r\n    ax = fig.gca(projection='3d')\r\n    ax.set_aspect(\"equal\")\r\n    file_object = None\r\n    try:\r\n      file_object = open(filename, \"r\")\r\n    except IOError:\r\n        print(\"     ... file \" + filename+\" not exits!\\n\")\r\n        return False\r\n    vtkControl = vv.VTKVisualizerControl()\r\n    a = []\r\n\r\n    for line in file_object:\r\n        numbers = (re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\", line))\r\n        x = float(numbers[0])\r\n        y = float(numbers[1])\r\n        z = float(numbers[2])\r\n        a.append([x,y,z])\r\n    \r\n    b = np.array(a)\r\n    vtkControl.AddPointCloudActor(b)\r\n    app = QApplication.instance()\r\n    if app is None:\r\n        app = QApplication(sys.argv)\r\n    app.exec_()\r\n    file_object.close()\r\n#end def\r\n\r\ndef calculateTorus(R,r):\r\n    file_object  = open(\"torus.txt\", \"w\") \r\n    for theta in np.arange(0,2*np.pi,0.05):\r\n        for phi in np.arange(0,2*np.pi,0.05):\r\n                x = (R + r * np.cos(phi)) * np.cos(theta)\r\n                y = (R + r * np.cos(phi)) * np.sin(theta)\r\n                z = r * np.sin(phi)\r\n                file_object.write(str(x)+\" \"+str(y)+\" \"+str(z)+\"\\n\")\r\n    file_object.close()\r\n#end def\r\n\r\ndef calculateDrawTorus(R,r):\r\n    fig = plt.figure()\r\n    ax = fig.gca(projection='3d')\r\n    ax.set_aspect(\"equal\")\r\n    for theta in np.arange(0,2*np.pi,0.4):\r\n        for phi in np.arange(0,2*np.pi,0.4):\r\n            ax.scatter((R + r * np.cos(phi)) * np.cos(theta), \r\n                    (R + r * np.cos(phi)) * np.sin(theta), \r\n                    r * np.sin(phi), \r\n                    color=\"r\", marker='o') \r\n    plt.show()  \r\n#end def\r\n\r\ndef calculateTetrahedron():\r\n    file_object  = open(\"tetrahedron.txt\", \"w\") \r\n    numbers = []\r\n    for i in np.arange(0,1.1,0.05):\r\n        numbers.append(i)\r\n    for x,y,z in combinations(numbers, 3):\r\n    \tfile_object.write(str(x)+\" \"+str(y)+\" \"+str(z)+\"\\n\")\r\n    file_object.close()\r\n#end def\r\n\r\ndef calculateDrawTetrahedron():\r\n    fig = plt.figure()\r\n    ax = fig.gca(projection='3d')\r\n    ax.set_aspect(\"equal\")\r\n    numbers = []\r\n    for i in np.arange(0,1.1,0.1):\r\n        numbers.append(i)\r\n    for x,y,z in combinations(numbers, 3):\r\n    \tax.scatter(x, y, z, color=\"b\", marker='o')\r\n    plt.show()\r\n#end def\r\n\r\ndef calculateTriangle():\r\n    file_object  = open(\"triangle.txt\", \"w\") \r\n    numbers = []\r\n    for u in np.arange(0,4,0.05):\r\n        for v in np.arange(0,((4-u)/2),0.05):\r\n            x = u\r\n            y = v\r\n            z = 4-u-2*v\r\n            file_object.write(str(x)+\" \"+str(y)+\" \"+str(z)+\"\\n\")\r\n    file_object.close()\r\n#end def\r\n\r\ndef calculateDrawTriangle():\r\n    fig = plt.figure()\r\n    ax = fig.gca(projection='3d')\r\n    ax.set_aspect(\"equal\")\r\n    for u in np.arange(0,4,0.2):\r\n        for v in np.arange(0,((4-u)/2),0.2):\r\n            ax.scatter(u, v, 4-u-2*v, \r\n                color=\"r\", marker='o')\r\n    plt.show()\r\n#end def\r\n\r\ndef calculateCube():\r\n    file_object  = open(\"cube.txt\", \"w\") \r\n    numbers = []\r\n    for i in np.arange(0,1.05,0.05):\r\n        numbers.append(i)\r\n    for x,y,z in product(numbers, repeat=3):\r\n        if x == 0 or x == 1 or y == 0 or y == 1 or z == 0 or z == 1:\r\n            file_object.write(str(x)+\" \"+str(y)+\" \"+str(z)+\"\\n\")  \r\n    file_object.close()\r\n#end def\r\n\r\ndef calculateDrawCube():\r\n    fig = plt.figure()\r\n    ax = fig.gca(projection='3d')\r\n    ax.set_aspect(\"equal\")\r\n    numbers = []\r\n    for i in np.arange(0,1.1,0.2):\r\n        numbers.append(i)\r\n    for x,y,z in product(numbers, repeat=3):\r\n        if x == 0 or x == 1 or y == 0 or y == 1 or z == 0 or z == 1:\r\n            ax.scatter(x, y, z, color=\"b\", marker='o')\r\n    plt.show()\r\n#end def\r\n\r\ndef calculateSphere():\r\n    file_object  = open(\"sphere.txt\", \"w\")\r\n    for u in np.arange(0, 2*np.pi, 0.1):\r\n        for v in np.arange(0, 2*np.pi, 0.1):\r\n            x = np.cos(u)*np.sin(v)\r\n            y = np.sin(u)*np.sin(v)\r\n            z = np.cos(v)\r\n            file_object.write(str(x)+\" \"+str(y)+\" \"+str(z)+\"\\n\")  \r\n    file_object.close()\r\n#end def\r\n\r\ndef calculateDrawSphere():\r\n    fig = plt.figure()\r\n    ax = fig.gca(projection='3d')\r\n    ax.set_aspect(\"equal\")\r\n    u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:25j]\r\n    x = np.cos(u)*np.sin(v)\r\n    y = np.sin(u)*np.sin(v)\r\n    z = np.cos(v)\r\n    ax.scatter(x, y, z, color=\"r\", marker='o')\r\n    plt.show()\r\n#end def\r\n\r\ndef calculateCylinder():\r\n    file_object  = open(\"cylinder.txt\", \"w\")\r\n\r\n    for u in np.arange(0, 2*np.pi, 0.1):\r\n        for z in np.arange (0,10,0.1):##danger\r\n            x = np.cos(u)\r\n            y = np.sin(u)\r\n            file_object.write(str(x)+\" \"+str(y)+\" \"+str(z)+\"\\n\")\r\n\r\n        \r\n    for i in np.arange(1,0,-0.1):\r\n        for u in np.arange(0, 2*np.pi, 0.1):\r\n            x = i*np.cos(u)\r\n            y = i*np.sin(u)\r\n            file_object.write(str(x)+\" \"+str(y)+\" \"+str(0)+\"\\n\")\r\n            file_object.write(str(x)+\" \"+str(y)+\" \"+str(z)+\"\\n\")\r\n\r\n    file_object.close()\r\n#end def\r\n\r\ndef calculateDrawCylinder():\r\n    fig = plt.figure()\r\n    ax = fig.gca(projection='3d')\r\n    ax.set_aspect(\"equal\")\r\n    u = np.mgrid[0:2*np.pi:40j]\r\n    for z in range (0,40):\r\n        x = np.cos(u)\r\n        y = np.sin(u)\r\n        ax.scatter(x, y, z, color=\"r\", marker='o')\r\n    for i in np.arange(1,-0.1,-0.1):\r\n        x = i*np.cos(u)\r\n        y = i*np.sin(u)\r\n        ax.scatter(x, y, z, color=\"r\", marker='o')\r\n        ax.scatter(x, y, 0, color=\"r\", marker='o')\r\n    plt.show()\r\n#end def\r\n\r\ndef calculateParaboloid():\r\n    file_object  = open(\"paraboloid.txt\", \"w\")\r\n    for u in np.arange(0, 2*np.pi, 0.05):\r\n        for v in np.arange(0, np.pi, 0.05):\r\n            x = 1*np.cos(v)*np.cos(u)\r\n            y = 1*np.cos(v)*np.sin(u)\r\n            z = np.cos(v)*np.cos(v)\r\n            file_object.write(str(x)+\" \"+str(y)+\" \"+str(z)+\"\\n\")  \r\n    file_object.close()\r\n#end def\r\n\r\ndef calculateDrawParaboloid():\r\n    fig = plt.figure()\r\n    ax = fig.gca(projection='3d')\r\n    ax.set_aspect(\"equal\")\r\n    u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:20j]\r\n    x = 1*np.cos(v)*np.cos(u)\r\n    y = 1*np.cos(v)*np.sin(u)\r\n    z = np.cos(v)*np.cos(v)\r\n    ax.scatter(x, y, z, color=\"r\", marker='o')\r\n    plt.show()\r\n#end def\r\n\r\nopc = -1\r\nwhile opc != 0:\r\n    print(\" Menu \\n     0. Exit.\"     \r\n        + \"\\n   1. Calculated solids.\"\r\n        + \"\\n   2. Draw torus.\"\r\n        + \"\\n   3. Draw tetrahedron.\"\r\n        + \"\\n   4. Draw triangle.\"\r\n        + \"\\n   5. Draw cube.\"\r\n        + \"\\n   6. Draw sphere.\"\r\n        + \"\\n   7. Draw cylinder.\"\r\n        + \"\\n   8. Draw paraboloid.\")\r\n\r\n    opc = int(input(\"Enter option: \"))\r\n    if opc == 0:\r\n        print(\"     ... Bye!\\n\")\r\n    elif opc == 1:\r\n        calculateTorus(4,0.5)\r\n        calculateTetrahedron()\r\n        calculateTriangle()\r\n        calculateCube()\r\n        calculateSphere()\r\n        calculateCylinder()\r\n        calculateParaboloid()\r\n    elif opc == 2:\r\n        showFigure(\"torus.txt\")  \r\n    elif opc == 3:\r\n        showFigure(\"tetrahedron.txt\") \r\n    elif opc == 4:\r\n        showFigure(\"triangle.txt\") \r\n    elif opc == 5:\r\n        showFigure(\"cube.txt\")  \r\n    elif opc == 6:\r\n        showFigure(\"sphere.txt\")  \r\n    elif opc == 7:\r\n        showFigure(\"cylinder.txt\")  \r\n    elif opc == 8:\r\n        showFigure(\"paraboloid.txt\")  \r\n    elif opc == 9:\r\n        calculateDrawTorus(4,0.5)\r\n    elif opc == 10:\r\n        calculateDrawTetrahedron()\r\n    elif opc == 11:\r\n        calculateDrawTriangle()\r\n    elif opc == 12:\r\n        calculateDrawCube()\r\n    elif opc == 13:\r\n        calculateDrawSphere()\r\n    elif opc == 14:\r\n        calculateDrawCylinder() \r\n    elif opc == 15:\r\n        calculateDrawParaboloid() \r\n    else:\r\n        print(\"     ... please enter a valid option!\\n\")\r\n    # end switch case\r\n#end while", "meta": {"hexsha": "161432a3f3478a96c0d7e5ceae639192966f6051", "size": 8072, "ext": "py", "lang": "Python", "max_stars_repo_path": "calculated-solids.py", "max_stars_repo_name": "lichobaron/CalculatedSolids", "max_stars_repo_head_hexsha": "e00bbe2869fcfb59036e630caf2aeb4c3379c274", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "calculated-solids.py", "max_issues_repo_name": "lichobaron/CalculatedSolids", "max_issues_repo_head_hexsha": "e00bbe2869fcfb59036e630caf2aeb4c3379c274", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calculated-solids.py", "max_forks_repo_name": "lichobaron/CalculatedSolids", "max_forks_repo_head_hexsha": "e00bbe2869fcfb59036e630caf2aeb4c3379c274", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5677655678, "max_line_length": 75, "alphanum_fraction": 0.5110257681, "include": true, "reason": "import numpy", "num_tokens": 2399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305339244013, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.8515336190665265}}
{"text": "import numpy as np\n\n\ndef qing_function(point, d):\n    \"\"\"\n    Qing function.\n\n    Parameters\n    ----------\n    point : 1-D array with shape (d, )\n            A point used to evaluate the function.\n    d : integer\n        Dimension.\n\n    Returns\n    -------\n    function value : float\n\n    \"\"\"\n    return np.sum((point ** 2 - np.arange(1, d + 1)) ** 2)\n\n\ndef qing_gradient(point, d):\n    \"\"\"\n    Qing gradient.\n\n    Parameters\n    ----------\n    point : 1-D array with shape (d, )\n            A point used to evaluate the function.\n    d : integer\n        Dimension.\n\n    Returns\n    -------\n    gradient : 1-D array with shape (d, )\n\n    \"\"\"\n    return 4 * point * (point ** 2 - np.arange(1, d + 1))\n", "meta": {"hexsha": "fd6695e8dd18b9967e3acba683717d0571c3c8d5", "size": 701, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/metod_alg/objective_functions/qing.py", "max_stars_repo_name": "Megscammell/METOD-Algorithm", "max_stars_repo_head_hexsha": "7518145ec100599bddc880f5f52d28f9a3959108", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/metod_alg/objective_functions/qing.py", "max_issues_repo_name": "Megscammell/METOD-Algorithm", "max_issues_repo_head_hexsha": "7518145ec100599bddc880f5f52d28f9a3959108", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-17T09:03:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-17T09:03:17.000Z", "max_forks_repo_path": "src/metod_alg/objective_functions/qing.py", "max_forks_repo_name": "Megscammell/METOD-Algorithm", "max_forks_repo_head_hexsha": "7518145ec100599bddc880f5f52d28f9a3959108", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.525, "max_line_length": 58, "alphanum_fraction": 0.5106990014, "include": true, "reason": "import numpy", "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745211, "lm_q2_score": 0.8872045996818986, "lm_q1q2_score": 0.8515053098622668}}
{"text": "import paddle\nimport numpy as np\nfrom typing import Tuple, Optional, Union\n\n\n# https://github.com/kaldi-asr/kaldi/blob/cbed4ff688/src/feat/feature-window.cc#L109\ndef povey_window(frame_len:int) -> np.ndarray:\n    win = np.empty(frame_len)\n    a = 2 * np.pi / (frame_len -1)\n    for i in range(frame_len):\n        win[i] = (0.5 - 0.5 * np.cos(a * i) )**0.85 \n    return win\n\ndef hann_window(frame_len:int) -> np.ndarray:\n    win = np.empty(frame_len)\n    a = 2 * np.pi / (frame_len -1)\n    for i in range(frame_len):\n        win[i] = 0.5 - 0.5 * np.cos(a * i)\n    return win\n\ndef sine_window(frame_len:int) -> np.ndarray:\n    win = np.empty(frame_len)\n    a = 2 * np.pi / (frame_len -1)\n    for i in range(frame_len):\n        win[i] = np.sin(0.5 * a * i)\n    return win\n\ndef hamm_window(frame_len:int) -> np.ndarray:\n    win = np.empty(frame_len)\n    a = 2 * np.pi / (frame_len -1)\n    for i in range(frame_len):\n        win[i] = 0.54 - 0.46 * np.cos(a * i)\n    return win\n\ndef get_window(wintype:Optional[str], winlen:int) -> np.ndarray:\n    \"\"\"get window function\n\n    Args:\n        wintype (Optional[str]): window type.\n        winlen (int): window length in samples.\n\n    Raises:\n        ValueError: not support window.\n\n    Returns:\n        np.ndarray: window coeffs.\n    \"\"\"\n    # calculate window\n    if not wintype or wintype == 'rectangular':\n        window = np.ones(winlen)\n    elif wintype == \"hann\":\n        window = hann_window(winlen)\n    elif wintype == \"hamm\":\n        window = hamm_window(winlen)\n    elif wintype == \"povey\":\n        window = povey_window(winlen)\n    else:\n        msg = f\"{wintype} Not supported yet!\"\n        raise ValueError(msg)\n    return window\n    \n   \ndef dft_matrix(n_fft:int, winlen:int=None, n_bin:int=None) -> Tuple[np.ndarray, np.ndarray, int]:\n    # https://en.wikipedia.org/wiki/Discrete_Fourier_transform\n    # (n_bins, n_fft) complex\n    if n_bin is None:\n        n_bin = 1 + n_fft // 2\n    if winlen is None:\n        winlen = n_bin\n    # https://github.com/numpy/numpy/blob/v1.20.0/numpy/fft/_pocketfft.py#L49\n    kernel_size = min(n_fft, winlen)\n        \n    n = np.arange(0, n_fft, 1.)\n    wsin = np.empty((n_bin, kernel_size)) #[Cout, kernel_size]\n    wcos = np.empty((n_bin, kernel_size)) #[Cout, kernel_size]\n    for k in range(n_bin): # Only half of the bins contain useful info\n        wsin[k,:] = -np.sin(2*np.pi*k*n/n_fft)[:kernel_size]\n        wcos[k,:] = np.cos(2*np.pi*k*n/n_fft)[:kernel_size]\n    w_real = wcos\n    w_imag = wsin\n    return w_real, w_imag, kernel_size\n    \n\ndef dft_matrix_fast(n_fft:int, winlen:int=None, n_bin:int=None) -> Tuple[np.ndarray, np.ndarray, int]:\n    # (n_bins, n_fft) complex\n    if n_bin is None:\n        n_bin = 1 + n_fft // 2\n    if winlen is None:\n        winlen = n_bin\n    # https://github.com/numpy/numpy/blob/v1.20.0/numpy/fft/_pocketfft.py#L49\n    kernel_size = min(n_fft, winlen)\n    \n    # https://en.wikipedia.org/wiki/DFT_matrix\n    # https://ccrma.stanford.edu/~jos/st/Matrix_Formulation_DFT.html\n    weight = np.fft.fft(np.eye(n_fft))[:self.n_bin, :kernel_size]\n    w_real = weight.real\n    w_imag = weight.imag\n    return w_real, w_imag, kernel_size\n    \n\ndef bin2hz(bin:Union[List[int], np.ndarray], N:int, sr:int)->List[float]:\n    \"\"\"FFT bins to Hz.\n    \n    http://practicalcryptography.com/miscellaneous/machine-learning/intuitive-guide-discrete-fourier-transform/\n\n    Args:\n        bins (List[int] or np.ndarray): bin index.\n        N (int): the number of samples, or FFT points.\n        sr (int): sampling rate.\n\n    Returns:\n        List[float]: Hz's.\n    \"\"\"\n    hz = bin * float(sr) / N\n        \n        \ndef hz2mel(hz):\n    \"\"\"Convert a value in Hertz to Mels\n\n    :param hz: a value in Hz. This can also be a numpy array, conversion proceeds element-wise.\n    :returns: a value in Mels. If an array was passed in, an identical sized array is returned.\n    \"\"\"\n    return 1127 * np.log(1+hz/700.0)\n\n\ndef mel2hz(mel):\n    \"\"\"Convert a value in Mels to Hertz\n\n    :param mel: a value in Mels. This can also be a numpy array, conversion proceeds element-wise.\n    :returns: a value in Hertz. If an array was passed in, an identical sized array is returned.\n    \"\"\"\n    return 700 * (np.exp(mel/1127.0)-1)\n\n\n\ndef rms_to_db(rms: float):\n    \"\"\"Root Mean Square to dB.\n\n    Args:\n        rms ([float]): root mean square\n\n    Returns:\n        float: dB\n    \"\"\"\n    return 20.0 * math.log10(max(1e-16, rms))\n\n\ndef rms_to_dbfs(rms: float):\n    \"\"\"Root Mean Square to dBFS.\n    https://fireattack.wordpress.com/2017/02/06/replaygain-loudness-normalization-and-applications/\n    Audio is mix of sine wave, so 1 amp sine wave's Full scale is 0.7071, equal to -3.0103dB.\n   \n    dB = dBFS + 3.0103\n    dBFS = db - 3.0103\n    e.g. 0 dB = -3.0103 dBFS\n\n    Args:\n        rms ([float]): root mean square\n\n    Returns:\n        float: dBFS\n    \"\"\"\n    return rms_to_db(rms) - 3.0103\n\n\ndef max_dbfs(sample_data: np.ndarray):\n    \"\"\"Peak dBFS based on the maximum energy sample. \n\n    Args:\n        sample_data ([np.ndarray]): float array, [-1, 1].\n\n    Returns:\n        float: dBFS \n    \"\"\"\n    # Peak dBFS based on the maximum energy sample. Will prevent overdrive if used for normalization.\n    return rms_to_dbfs(max(abs(np.min(sample_data)), abs(np.max(sample_data))))\n\n\ndef mean_dbfs(sample_data):\n    \"\"\"Peak dBFS based on the RMS energy. \n\n    Args:\n        sample_data ([np.ndarray]): float array, [-1, 1].\n\n    Returns:\n        float: dBFS \n    \"\"\"\n    return rms_to_dbfs(\n        math.sqrt(np.mean(np.square(sample_data, dtype=np.float64))))\n\n\ndef gain_db_to_ratio(gain_db: float):\n    \"\"\"dB to ratio\n\n    Args:\n        gain_db (float): gain in dB\n\n    Returns:\n        float: scale in amp\n    \"\"\"\n    return math.pow(10.0, gain_db / 20.0)", "meta": {"hexsha": "7638dae5335698483611ae7cedd13fd4aa718c5c", "size": 5754, "ext": "py", "lang": "Python", "max_stars_repo_path": "third_party/paddle_audio/frontend/common.py", "max_stars_repo_name": "zh794390558/DeepSpeech", "max_stars_repo_head_hexsha": "34178893327ad359cb816e55d7c66a10244fa08a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "third_party/paddle_audio/frontend/common.py", "max_issues_repo_name": "zh794390558/DeepSpeech", "max_issues_repo_head_hexsha": "34178893327ad359cb816e55d7c66a10244fa08a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/paddle_audio/frontend/common.py", "max_forks_repo_name": "zh794390558/DeepSpeech", "max_forks_repo_head_hexsha": "34178893327ad359cb816e55d7c66a10244fa08a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6268656716, "max_line_length": 111, "alphanum_fraction": 0.6211331248, "include": true, "reason": "import numpy", "num_tokens": 1689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745211, "lm_q2_score": 0.8872045937171068, "lm_q1q2_score": 0.8515053041374859}}
{"text": "from __future__ import division\nimport numpy as np\nfrom collections import Counter\nimport LinearAlgebraFunctions as alg\nimport math\n\nnum_friends = np.random.poisson(5, 1000)\nnum_friends = [20 * nf_i for nf_i in num_friends]\n\ndaily_minutes = np.random.poisson(10, 1000)\ndaily_minutes = [15 * dm_i for dm_i in daily_minutes]\n\n# number of points\nnum_points = len(num_friends)\n\n# largest value\nlargest_value = max(num_friends)\nsmallest_value = min(num_friends)\n\n# specific positions\nsorted_values = sorted(num_friends)\nsmallest_value = sorted_values[0]\nsecond_smallest_value = sorted_values[1]\nsecond_largest_value = sorted_values[-2]\n\n\n# MEASURES OF CENTRAL TENDENCY\n\n# mean\ndef mean(x):\n    return sum(x) / len(x)\n    \n# median\ndef median(v):\n    \"\"\" finds the middle most value of v \"\"\"\n    n = len(v)\n    sorted_v = sorted(v)\n    midpoint = n // 2\n    \n    if n % 2 == 1:\n        # if odd, return the middle value\n        return sorted_v[midpoint]\n    else:\n        # if even, return the average of the middle values\n        lo = midpoint - 1\n        hi = midpoint\n        return (sorted_v[lo] + sorted_v[hi]) / 2\n\n# quantile\ndef quantile(x, p):\n    \"\"\" returns the pth-percentile value in x \"\"\"\n    p_index = int(p * len(x))\n    return sorted(x)[p_index]\n\n# mode\ndef mode(x):\n    \"\"\" returns a list, might be more than one mode \"\"\"\n    counts = Counter(x)\n    max_count = max(counts.values())\n    return [x_i for x_i, count in counts.iteritems() \n        if count == max_count]\n       \n    \n# MEASURES OF DISPERSION\n# range\ndef data_range(x):\n    return max(x) - min(x)\n\n# variance\ndef de_mean(x):\n    \"\"\" translate x by subtracting its mean (so the result has mean 0) \"\"\"\n    x_bar = mean(x)\n    return [x_i - x_bar for x_i in x]\n    \ndef variance(x):\n    \"\"\" assumes x has at least two elements \"\"\"\n    n = len(x)\n    deviations = de_mean(x)\n    return alg.sum_of_squares(deviations) / (n - 1)\n\n# standard deviation\ndef standard_deviation(x):\n    return math.sqrt(variance(x))\n\n# inter quartile range\ndef interquartile_range(x):\n    return quantile(x, 0.75) - quantile(x, 0.25)\n\n\n# CORRELATION\n\ndef covariance(x, y):\n    n = len(x)\n    return alg.dot(de_mean(x), de_mean(y)) / (n - 1)\n\ndef correlation(x, y):\n    stdev_x = standard_deviation(x)\n    stdev_y = standard_deviation(y)\n    \n    if stdev_x > 0 and stdev_y > 0:\n        return covariance(x, y) / stdev_x / stdev_y\n    else:\n        return 0 # if no variation, correlation is 0\n\n\n", "meta": {"hexsha": "e6f5bbfc5859c0feb4346208055e735cf7448a70", "size": 2442, "ext": "py", "lang": "Python", "max_stars_repo_path": "RefMaterials/Ch5-Statistics/statistics.py", "max_stars_repo_name": "buckiracer/data-science-from-scratch", "max_stars_repo_head_hexsha": "bd1998b8723d89de4139a3f1b899fc126d50024c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RefMaterials/Ch5-Statistics/statistics.py", "max_issues_repo_name": "buckiracer/data-science-from-scratch", "max_issues_repo_head_hexsha": "bd1998b8723d89de4139a3f1b899fc126d50024c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RefMaterials/Ch5-Statistics/statistics.py", "max_forks_repo_name": "buckiracer/data-science-from-scratch", "max_forks_repo_head_hexsha": "bd1998b8723d89de4139a3f1b899fc126d50024c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0377358491, "max_line_length": 74, "alphanum_fraction": 0.656019656, "include": true, "reason": "import numpy", "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620562254525, "lm_q2_score": 0.8872045922259088, "lm_q1q2_score": 0.8515053037274023}}
{"text": "from numpy import mgrid, empty, float64, sqrt, array, pi\n\n\ndef ccp_lattice(nx,ny,nz):\n  \"\"\"\n  creates a cubic close packed (ccp) lattice\n\n  A CCP lattice has points at the corners and the centres of faces of a cube\n  Using a unit grid the nearest neighbours are sqrt(0.5) apart\n\n  returns positions (3,N) array\n  \"\"\"\n  pos_base = mgrid[:nx,:ny,:nz]\n\n  # vectors for offsets\n\n  offset1 = array((0.5, 0.5, 0.0), dtype=float64)\n  offset2 = array((0.5, 0.0, 0.5), dtype=float64)\n  offset3 = array((0.0, 0.5, 0.5), dtype=float64)\n\n\n  # create the 4 layers\n  pos = empty((4,3,nx,ny,nz), dtype=float64)\n  pos[0] = pos_base\n  pos[1] = pos[0] + offset1.reshape((3,1,1,1))\n  pos[2] = pos[0] + offset2.reshape((3,1,1,1))\n  pos[3] = pos[0] + offset3.reshape((3,1,1,1))\n\n  pos = pos.swapaxes(1,-1)\n  pos = pos.reshape((4*nx*ny*nz,3))\n  return pos\n  \ndef hcp_lattice(nx,ny,nz):\n  \"\"\" \n  creates a hexagonal close packed (hcp) lattice\n  \"\"\"\n  pos_base = mgrid[:nx,:ny,:nz]\n\n  # vectors for multiplies and offsets\n  scales = array((1, sqrt(3), (2.0/3.0)* sqrt(6)), dtype=float64)\n  offset1 = array((0.5, sqrt(3)*0.5, 0.0), dtype=float64)\n  offset2 = array((0.5, sqrt(3)/6.0, sqrt(6.0)/3.0), dtype=float64)\n\n  # create the 4 layers\n  pos = empty((4,3,nx,ny,nz), dtype=float64)\n  pos[0] = pos_base * scales.reshape((3,1,1,1))\n  pos[1] = pos[0] + offset1.reshape((3,1,1,1))\n  pos[2:] = pos[:2] + offset2.reshape((1,3,1,1,1))\n\n  pos = pos.swapaxes(1,-1)\n  pos = pos.reshape((4*nx*ny*nz,3))\n  return pos, scales * (nx,ny,nz)\n\n\nif __name__=='__main__':\n\n  pos, box_size = hcp_lattice(10,10,10)\n  print(box_size)\n  print('number of points', pos.shape[0])\n  vol = box_size[0]*box_size[1] * box_size[2]\n  print('volume', vol)\n  print('density', pos.shape[0] / vol)\n  print('packing factor', pos.shape[0] * (pi / 6.0) / vol)\n\n  pos = ccp_lattice(5,10,15)\n  \n  import pylab as pl\n  pl.plot(pos[:,0], pos[:,2], 'bx')\n  pl.show()\n  \n\n", "meta": {"hexsha": "f61cf163489e3fc5b50a1bc4fd90e457e56ff597", "size": 1905, "ext": "py", "lang": "Python", "max_stars_repo_path": "particles/lattices.py", "max_stars_repo_name": "martincss/iccpy", "max_stars_repo_head_hexsha": "d3b5f71136835502b04ba26f9656252b735895f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "particles/lattices.py", "max_issues_repo_name": "martincss/iccpy", "max_issues_repo_head_hexsha": "d3b5f71136835502b04ba26f9656252b735895f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "particles/lattices.py", "max_forks_repo_name": "martincss/iccpy", "max_forks_repo_head_hexsha": "d3b5f71136835502b04ba26f9656252b735895f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4583333333, "max_line_length": 76, "alphanum_fraction": 0.6209973753, "include": true, "reason": "from numpy", "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620562254525, "lm_q2_score": 0.8872045832787204, "lm_q1q2_score": 0.8515052951402304}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nEjercicio 3: Integración - Fórmulas de cuadratura gaussianas.\r\n-----------------------------------------------------------------------------\r\nFunción gauss: Halla la integral aproximada utlizando la fórmula de \r\nGauss-Legendre para una función f en unintervalo [a,b]. \r\n\r\nArgumentos de entrada:\r\n    f:  función integrando (función lambda).\r\n    a:  extremo inferior del intervalo de integración (número real).\r\n    b:  extremo superior del intervalo de integración (número real).\r\n    n:  número de nodos (número entero).\r\n             \r\nArgumentos de salida:\r\n    I:  integral aproximada con la fórmula de Gauss-Legendre con n nodos de la función\r\n        f en [a,b] (número real).\r\n    \r\nEjemplos:\r\n    f = lambda x : x**2\r\n    I = gauss(f,0,2,6)\r\n    print('Ejemplo de prueba con Gauss-Legendre =', I)\r\n    Salida:\r\n        Ejemplo de prueba con Gauss-Legendre = 2.666666666666666\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport sympy as sym\r\n\r\n# Cálculo de la integral exacta de la función f(x) = exp(x) en [0,3]\r\n#---------------------------------------------------------------------\r\nx = sym.Symbol('x', real=True)            # definimos la variable x simbólica\r\nf = sym.exp(x)            # definimos la función f simbólica \r\nI_exacta = sym.integrate(f,(x,0,3))\r\nI_exacta = float(I_exacta)\r\nprint ('El valor exacto es: ',I_exacta)   \r\n\r\n\r\n# Función gauss\r\n#--------------------------------------\r\ndef gauss(f,a,b,n):\r\n    [x, w] = np.polynomial.legendre.leggauss(n)         # se obtienen los nodos x (en [-1,1]) y los pesos w\r\n    y = ((b-a)/2.0)*x+(a+b)/2.0              # nodos en [a,b]\r\n    I = 0.0              # fórmula de cuadratura de Gauss-Legendre\r\n    for i in range(0,len(y)):\r\n        I += w[i]*f(y[i])*((b-a))/2.0\r\n    return I\r\n\r\n#--------------------------------------\r\n# Ejemplos\r\n#--------------------------------------\r\n\r\n# Ejemplo de prueba\r\nf = lambda x : x**2\r\nI = gauss(f,0,2,6)\r\nprint('Ejemplo de prueba con Gauss-Legendre =', I)\r\n\r\n#--------------------------------------\r\n# Ejercicio 3\r\n#--------------------------------------\r\n\r\n#-----------------------\r\nf = lambda x :np.exp(x) \r\na = 0 \r\nb = 3 \r\nn = 1\r\nI1 = gauss(f,a,b,n)\r\nprint ('El valor aproximado con 1 nodo es:', I1)\r\n#-----------------------\r\nn = 2\r\nI2 = gauss(f,a,b,n)\r\nprint ('El valor aproximado con 2 nodos es:', I2)\r\n#-----------------------\r\nn = 3\r\nI3 = gauss(f,a,b,n)\r\nprint ('El valor aproximado con 3 nodos es:', I3)\r\n   \r\n\r\n\r\n#-----------------------", "meta": {"hexsha": "1fcc0119245bddf48c1df03b85b7d6938bc3eea9", "size": 2468, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ej-Lab9-MoisesSanjurjo-UO270824/ejercicio3-MoisesSanjurjo-UO270824.py", "max_stars_repo_name": "moiSS00/CN", "max_stars_repo_head_hexsha": "1e30b43ee2167d15fbc8c472ff9637c2b920c3d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ej-Lab9-MoisesSanjurjo-UO270824/ejercicio3-MoisesSanjurjo-UO270824.py", "max_issues_repo_name": "moiSS00/CN", "max_issues_repo_head_hexsha": "1e30b43ee2167d15fbc8c472ff9637c2b920c3d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ej-Lab9-MoisesSanjurjo-UO270824/ejercicio3-MoisesSanjurjo-UO270824.py", "max_forks_repo_name": "moiSS00/CN", "max_forks_repo_head_hexsha": "1e30b43ee2167d15fbc8c472ff9637c2b920c3d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2405063291, "max_line_length": 108, "alphanum_fraction": 0.4935170178, "include": true, "reason": "import numpy,import sympy", "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440397949314, "lm_q2_score": 0.9161096193153989, "lm_q1q2_score": 0.851469289141699}}
{"text": "'''\nCollated by Ching-Shih Tsou 鄒慶士 博士 (Ph.D.) Distinguished Prof. at the Department of Mechanical Engineering/Director at the Center of Artificial Intelligence & Data Science (機械工程系特聘教授兼人工智慧暨資料科學研究中心主任), MCUT (明志科技大學); Prof. at the Institute of Information & Decision Sciences (資訊與決策科學研究所教授), NTUB (國立臺北商業大學); the Chinese Academy of R Software (CARS) (中華R軟體學會創會理事長); the Data Science and Business Applications Association of Taiwan (DSBA) (臺灣資料科學與商業應用協會創會理事長); the Chinese Association for Quality Assessment and Evaluation (CAQAE) (中華品質評鑑協會常務監事); the Chinese Society of Quality (CSQ) (中華民國品質學會大數據品質應用委員會主任委員\nNotes: This code is provided without warranty.\n'''\n\n#### Complex FFT and Interpretations\nfrom scipy.fftpack import fft, ifft\nimport numpy as np\nimport matplotlib.pyplot as plt \nnp.set_printoptions(formatter={\"float_kind\": lambda x: \"%g\" % x})\nfc=10 # frequency of the carrier\nfs=32*fc # sampling frequency with oversampling factor=32\nt=np.arange(start = 0,stop = 2,step = 1/fs) # 2 seconds duration ((2-0)/(320**(-1))=640, 2-(320**(-1))=1.996875)\nx=np.cos(2*np.pi*fc*t) # time domain signal (real number)\n\nN=256 # FFT size\nX = fft(x,N) # N-point complex DFT, output contains DC at index 0\n# Nyquist frequency at N/2 th index positive frequencies from\n# index 2 to N/2-1 and negative frequencies from index N/2 to N-1 (Nyquist frequency included)\n\nX[0]\nabs(X[7:10])\n\n# calculate frequency bins with FFT\ndf=fs/N # frequency resolution\nsampleIndex = np.arange(start = 0,stop = N) # raw index for FFT plot\nf=sampleIndex*df # x-axis index converted to frequencies\n\nfig, (ax1, ax2, ax3) = plt.subplots(nrows=3, ncols=1)\nax1.plot(t,x) #plot the signal\nax1.set_title('$x[n]= cos(2 \\pi 10 t)$') \nax1.set_xlabel('$t=nT_s$')\nax1.set_ylabel('$x[n]$')\nax2.stem(sampleIndex,abs(X),use_line_collection=True) # sample values on x-axis \nax2.set_title('X[k]');ax2.set_xlabel('k');ax2.set_ylabel('|X(k)|'); \nax3.stem(f,abs(X),use_line_collection=True); # x-axis represent frequencies\nax3.set_title('X[f]');ax3.set_xlabel('frequencies (f)');ax3.set_ylabel('|X(f)|');\nfig.show()\n\nnyquistIndex=N//2 #// is for integer division\nprint(X[nyquistIndex-2:nyquistIndex+3, None]) #print array X as column\n# Note that the complex numbers surrounding the Nyquist index are complex conjugates and are present at positive and negative frequencies respectively.\n\n#### FFT Shift\nfrom scipy.fftpack import fftshift, ifftshift\n#re-order the index for emulating fftshift\nsampleIndex = np.arange(start = -N//2,stop = N//2) # // for integer division\nX1 = X[sampleIndex] #order frequencies without using fftShift\nX2 = fftshift(X) # order frequencies by using fftshift\ndf=fs/N # frequency resolution\nf=sampleIndex*df # x-axis index converted to frequencies\n#plot ordered spectrum using the two methods\nfig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)#subplots creation \nax1.stem(sampleIndex,abs(X1), use_line_collection=True)# result without fftshift \nax1.stem(sampleIndex,abs(X2),'r',use_line_collection=True) #result with fftshift \nax1.set_xlabel('k');ax1.set_ylabel('|X(k)|')\nax2.stem(f,abs(X1), use_line_collection=True)\nax2.stem(f,abs(X2),'r' , use_line_collection=True) \nax2.set_xlabel('frequencies (f)'),ax2.set_ylabel('|X(f)|');\nfig.show()\n\n#### IFFTShift\nX = fft(x,N) # compute X[k]\nx = ifft(X,N) # compute x[n]\n\nX = fftshift(fft(x,N)) # take FFT and rearrange frequency order\nx = ifft(ifftshift(X),N) # restore raw freq order and then take IFFT\n\nx = np.array([0,1,2,3,4,5,6,7]) # even number of elements\nfftshift(x)\n\nifftshift(x)\n\nifftshift(fftshift(x))\n\nfftshift(ifftshift(x))\n\n\n\nx = np.array([0,1,2,3,4,5,6,7,8]) # odd number of elements\nfftshift(x)\n\nifftshift(x)\n\nifftshift(fftshift(x))\n\nfftshift(ifftshift(x))\n\n\n#### Reference:\n# Viswanathan, Mathuranathan, Digital Modulations using Python, December 2019.", "meta": {"hexsha": "0f9ed281a82027bfd45d24c1846a7b9557e1e83c", "size": 3787, "ext": "py", "lang": "Python", "max_stars_repo_path": "FFT.py", "max_stars_repo_name": "appletime81/Data_Signal_Processing", "max_stars_repo_head_hexsha": "5dd2ad96814744e6ce2848554696a48380756750", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FFT.py", "max_issues_repo_name": "appletime81/Data_Signal_Processing", "max_issues_repo_head_hexsha": "5dd2ad96814744e6ce2848554696a48380756750", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FFT.py", "max_forks_repo_name": "appletime81/Data_Signal_Processing", "max_forks_repo_head_hexsha": "5dd2ad96814744e6ce2848554696a48380756750", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6153846154, "max_line_length": 604, "alphanum_fraction": 0.7380512279, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.9161096135894201, "lm_q1q2_score": 0.8514692838197429}}
{"text": "\"\"\"\nInformation Theory \n\nThis module contains functions for computing information-theoretic quantities on discrete probability distributions. Includes computation of \n\n- Entropy \n- Conditional Entropy\n- KL Divergence \n- Mutual Information \n- Channel Capacity (using the Blahut-Arimoto algorithm)\n\n \"\"\"\n\nimport numpy as np \nfrom numpy import log2\n\neps = 1e-40\n\ndef H(p_x):\n    \"\"\"\n    Compute the entropy of a random variable distributed ~ p(x)\n    \"\"\"\n    return -np.sum(p_x*log2(p_x))\n\ndef H_cond(P_yx, p_x):\n    \"\"\" \n    Compute the conditional entropy H(Y|X) given distributions p(y|x) and p(x)\n    \"\"\"\n    return -np.sum((P_yx*log2(P_yx))@p_x)\n\ndef KL_div(p_x, q_x):\n    \"\"\"\n    Compute the KL-divergence between two random variables\n    D(p||q) = E_p[log(p(X)/q(X))]\n\n    p_x : defines p(x), shape (dim_X, )  \n    q_x : defines q(x), shape (dim_X, )\n    \"\"\"\n    if p_x.shape != q_x.shape:\n        raise ValueError(\"p_x and q_x should have the same length\")\n    return np.sum(p_x * log2(p_x/q_x))\n\ndef I(Pxy):\n    \"\"\"\n    Compute the mutual information between two random variables related by \n    their joint distribution p(x,y)\n\n    Pxy : defines the joint distribution p(x,y), shape (dim_Y, dim_X)\n    \"\"\"\n    p_x = np.sum(Pxy, axis = 0)\n    p_y = np.sum(Pxy, axis = 1)\n    return KL_div(Pxy, product(p_x, p_y))\n\ndef I2(P_yx, p_x):\n    \"\"\"\n    Compute the mutual information between two random variables given the conditional distribution\n    p(y|x) and p(x)\n    \n    P_yx : matrix defining p(y|x), shape (dim_Y, dim_X)  \n    p_x :  defines distribution p(x), shape (dim_X,) \n    \"\"\"\n    p_y = (P_yx@p_x).reshape(-1,1)\n    Pxy = P_yx/p_y\n    return np.sum( (P_yx*log2(Pxy)) @ p_x )\n\ndef product(p_x, p_y):\n    \"\"\"\n    Compute the product distribution p(x,y) = p(x)p(y) given distributions \n    p(x) and p(y)\n    \"\"\"\n    p_x = p_x.reshape(1,-1)\n    p_y = p_y.reshape(-1,1)\n    Pxy = p_y@p_x\n    assert Pxy.shape == (p_y.shape[0], p_x.shape[1]) \n    return Pxy\n\ndef blahut_arimoto(P_yx, epsilon = 0.001, deterministic = False):\n    \"\"\" \n    Compute the channel capacity C of a channel p(y|x) using the Blahut-Arimoto algorithm. To do\n    this, finds the input distribution p(x) that maximises the mutual information I(X;Y)\n    determined by p(y|x) and p(x).\n\n    P_yx : defines the channel p(y|x)\n    iters : number of iterations\n    \"\"\"\n    P_yx = P_yx + eps\n    if not deterministic:\n        # initialize input dist randomly \n        q_x = _rand_dist((P_yx.shape[1],))\n        T = 1\n        while T > epsilon:\n            # update PHI\n            PHI_yx = (P_yx*q_x.reshape(1,-1))/(P_yx @ q_x).reshape(-1,1)\n            r_x = np.exp(np.sum(P_yx*log2(PHI_yx), axis=0))\n            # channel capactiy \n            C = log2(np.sum(r_x))\n            # check convergence \n            T = np.max(log2(r_x/q_x)) - C\n            # update q\n            q_x = _normalize(r_x + eps)\n        if C < 0:\n            C = 0\n        return C\n    else:\n        # assume all columns in channel matrix are peaked on a single state\n        # log of number of reachable states\n        return log2(np.sum(P_yx.sum(axis=1) > 0.999))\n\ndef _rand_dist(shape):\n    \"\"\" define a random probability distribution \"\"\"\n    P = np.random.rand(*shape)\n    return _normalize(P)\n\ndef _normalize(P):\n    \"\"\" normalize probability distribution \"\"\"\n    s = sum(P)\n    if s == 0.:\n        raise ValueError(\"input distribution has sum zero\")\n    return P / s\n", "meta": {"hexsha": "c259bdef9ebb86db7977f7e9b416106966f23462", "size": 3424, "ext": "py", "lang": "Python", "max_stars_repo_path": "empowerment/information_theory.py", "max_stars_repo_name": "Mchristos/empowerment", "max_stars_repo_head_hexsha": "3e47b678ad6dc589b6c5e4dd85c737f0d3ecd2e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2018-10-10T10:50:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T14:23:42.000Z", "max_issues_repo_path": "empowerment/information_theory.py", "max_issues_repo_name": "Mchristos/empowerment", "max_issues_repo_head_hexsha": "3e47b678ad6dc589b6c5e4dd85c737f0d3ecd2e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-11-02T18:45:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-18T10:31:10.000Z", "max_forks_repo_path": "empowerment/information_theory.py", "max_forks_repo_name": "Mchristos/empowerment", "max_forks_repo_head_hexsha": "3e47b678ad6dc589b6c5e4dd85c737f0d3ecd2e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:22:41.000Z", "avg_line_length": 28.5333333333, "max_line_length": 141, "alphanum_fraction": 0.6101051402, "include": true, "reason": "import numpy,from numpy", "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551535992067, "lm_q2_score": 0.8824278772763471, "lm_q1q2_score": 0.8514150850696918}}
{"text": "\nimport numpy as np\n\ndef gaussian_kernel(size, sigma=1):\n    size = int(size) // 2\n    x, y = np.mgrid[-size:size+1, -size:size+1]\n    normal = 1 / (2.0 * np.pi * sigma**2)\n    g =  np.exp(-((x**2 + y**2) / (2.0*sigma**2))) * normal\n    return g\n\n\n\nif __name__=='__main__':\n    g=gaussian_kernel(5,1)\n    #https://towardsdatascience.com/canny-edge-detection-step-by-step-in-python-computer-vision-b49c3a2d8123\n    print(g)", "meta": {"hexsha": "d1b687e5695e9d669dc6af44713c2eec76843cc9", "size": 422, "ext": "py", "lang": "Python", "max_stars_repo_path": "image_basics/CannyEdge.py", "max_stars_repo_name": "Mary-xl/cv_tools", "max_stars_repo_head_hexsha": "a673231b829b2059ede8819e69eb55ace522c524", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "image_basics/CannyEdge.py", "max_issues_repo_name": "Mary-xl/cv_tools", "max_issues_repo_head_hexsha": "a673231b829b2059ede8819e69eb55ace522c524", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "image_basics/CannyEdge.py", "max_forks_repo_name": "Mary-xl/cv_tools", "max_forks_repo_head_hexsha": "a673231b829b2059ede8819e69eb55ace522c524", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.375, "max_line_length": 108, "alphanum_fraction": 0.6208530806, "include": true, "reason": "import numpy", "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9648551576415562, "lm_q2_score": 0.8824278726384089, "lm_q1q2_score": 0.8514150841618351}}
{"text": "# --------------------------------------------------- \n# Statistical Thinking in Python (Part 1) - Thinking probalistically -- Continuous variables \n# 11 fev 2021 \n# VNTBJR \n# --------------------------------------------------- \n#\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nsns.set()\n# Probability density functions ------------------------------------------------\n# Probability density function (PDF) - it is a mathematical description of\n# the relative likelihood of observing a value of a continuos variable\n# Areas under the de PDF gives the probabilities.\n# Normal cumulative distribution function (Normal CDF) - it gives the \n# probability the measured speed of light will be less than the value \n# on the x-axis\n\n# Introduction to the normal distribution ------------------------------------------------\n# Normal distribution - it describes a continuous variable whose PDF\n# has a single and simmetric peak.\n# The normal distribution is parametrized by two parameters, the mean\n# and the standard deviation.The mean determines where the center of\n# the peak is. The standard deviation is measure of how wide the peak is,\n# or how spread out the data are.\n\n# The Normal PDF\n# Draw 100000 samples from Normal distribution with stds of interest: samples_std1, samples_std3, samples_std10\nsamples_std1 = np.random.normal(20, 1, 100000)\nsamples_std3 = np.random.normal(20, 3, 100000)\nsamples_std10 = np.random.normal(20, 10, 100000)\n\n# Make histograms\n_ = plt.hist(samples_std1, bins = 100, density = True, histtype = 'step')\n_ = plt.hist(samples_std3, bins = 100, density = True, histtype = 'step')\n_ = plt.hist(samples_std10, bins = 100, density = True, histtype = 'step')\n\n# Make a legend, set limits and show plot\n_ = plt.legend(('std = 1', 'std = 3', 'std = 10'))\nplt.ylim(-0.01, 0.42)\nplt.show()\nplt.clf()\n\n# The Normal CDF\n# Generate CDFs\nx_std1, y_std1 = ecdf(samples_std1)\nx_std3, y_std3 = ecdf(samples_std3)\nx_std10, y_std10 = ecdf(samples_std10)\n\n# Plot CDFs\n_ = plt.plot(x_std1, y_std1, marker = '.', linestyle = 'none')\n_ = plt.plot(x_std3, y_std3, marker = '.', linestyle = 'none')\n_ = plt.plot(x_std10, y_std10, marker = '.', linestyle = 'none')\n\n# Make a legend and show the plot\n_ = plt.legend(('std = 1', 'std = 3', 'std = 10'), loc='lower right')\nplt.show()\nplt.clf()\n\n# Thee Normal distribution: Properties and warnings ------------------------------------------------\n# Are the Belmont Stakes results Normally distributed?\n# Compute mean and standard deviation: mu, sigma\nmean = np.mean(belmont_no_outliers)\nsigma = np.std(belmont_no_outliers)\n\n# Sample out of a normal distribution with this mu and sigma: samples\nsamples = np.random.normal(mean, sigma, 10000)\n\n# Get the CDF of the samples and of the data\nx_theor, y_theor = ecdf(samples)\nx, y = ecdf(belmont_no_outliers)\n\n# Plot the CDFs and show the plot\n_ = plt.plot(x_theor, y_theor)\n_ = plt.plot(x, y, marker='.', linestyle='none')\n_ = plt.xlabel('Belmont winning time (sec.)')\n_ = plt.ylabel('CDF')\nplt.show()\n\n# What are the chances of a horse matching or beating Secretariat's\n# record?\n# Take a million samples out of the Normal distribution: samples\nsamples = np.random.normal(mu, sigma, 1000000)\n\n# Compute the fraction that are faster than 144 seconds: prob\nprob = len(samples[samples >= 144])/len(samples)\n\n# Print the result\nprint('Probability of besting Secretariat:', prob)\n\n# The exponential distribution ------------------------------------------------\n# The waiting time between arrivals of a Poisson process are Exponentially\n# distributed. It has a single parameter: the mean waiting time.\n# This distribution is not peaked. \n# If you have a story you can simulate it!\ndef successive_poisson(tau1, tau2, size = 1):\n    \"\"\"Compute time for arrival of 2 successive Poisson processes.\"\"\"\n    # Draw samples out of first exponential distribution: t1\n    t1 = np.random.exponential(tau1, size)\n\n    # Draw samples out of second exponential distribution: t2\n    t2 = np.random.exponential(tau2, size)\n\n    return t1 + t2\n\n# Distribution of no-hitters and cycles\n# Draw samples of waiting times: waiting_times\nwaiting_times = successive_poisson(764, 715, 100000)\n\n# Make the histogram\n_ = plt.hist(waiting_times, bins = 100, density = True, histtype = \"step\")\n\n\n# Label axes\n_ = plt.xlabel('waiting time')\n_ = plt.ylabel('PDF')\n\n# Show the plot\nplt.show()\nplt.clf()\n\n# Plot the CDF\nx_waiting_time, y_waiting_time = ecdf(waiting_time)\n_ = plt.plot(x_waiting_time, y_waiting_time, marker = '.', linestyle = 'none')\n_ = plt.ylabel('CDF')\n_ = plt.xlabel('waiting time')\nplt.show()\nplt.clf()\n", "meta": {"hexsha": "1bf28676fdf54d031e2738cbfae2f887dd624c83", "size": 4606, "ext": "py", "lang": "Python", "max_stars_repo_path": "Statistical-Thinking-in-Python-part-1/04-Thinking-Probalistically-Continuous-variables.py", "max_stars_repo_name": "vntborgesjr/Data-Scientist-with-Python", "max_stars_repo_head_hexsha": "30385c448d696aed98532765c727cc110c587028", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Statistical-Thinking-in-Python-part-1/04-Thinking-Probalistically-Continuous-variables.py", "max_issues_repo_name": "vntborgesjr/Data-Scientist-with-Python", "max_issues_repo_head_hexsha": "30385c448d696aed98532765c727cc110c587028", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistical-Thinking-in-Python-part-1/04-Thinking-Probalistically-Continuous-variables.py", "max_forks_repo_name": "vntborgesjr/Data-Scientist-with-Python", "max_forks_repo_head_hexsha": "30385c448d696aed98532765c727cc110c587028", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7054263566, "max_line_length": 111, "alphanum_fraction": 0.6841076856, "include": true, "reason": "import numpy", "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203815, "lm_q2_score": 0.8824278741843884, "lm_q1q2_score": 0.8514150838699405}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov  3 20:01:02 2017\n\n@author: Anastasios Tzavellas\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\n\ndef line(x, a, b):\n    \"\"\"\n    Line equation, used \n    for curve fitting algorithm\n    \n    Args:\n        x: x value\n         a: line coefficient\n         b: line constant term\n    \n    Returns:\n        The y coordinate of the point\n    \"\"\"\n    return a*x + b\n\ndef period(L):\n    \"\"\"\n    Calculates the theoretical period of a\n    pendulum with length L. It assumes that\n    the actual value of g is 9.8m/s2\n    \n    Args:\n        L: The length of the pendulum\n    \n    Returns:\n        The period of the pendulum in sec\n    \"\"\"\n    g = 9.8\n    return 2*np.pi*np.sqrt(L/g)\n\ndef gError(L, T, dL, dT):\n    \"\"\"\n    Calculates the error of g \n    estimation given the length, the \n    period and their respective errors\n    using the error propagation rule\n    \n    Args:\n        L: A vector of length values\n        T: A vector of period values\n        dL: The error in length measurement\n        dT: The error in period measurement\n    \n    Returns:\n        A vector with g error values\n    \"\"\"\n    dg = np.power(2*np.pi, 2) * np.sqrt( np.power(dL/(T*T), 2) + np.power(2*L*dT/np.power(T, 3), 2) )\n    return dg\n\ndef experiment(L, T, dL, dT, dLsystm = 0):\n    \"\"\"\n    Performs a g-measurement experiment\n    \n    Args:\n        L: A vector of length measurements of the pendulum\n        T: A vector of period measurements of the pendulum\n        dL: The error in length measurement\n        dT: The error in period measurement\n        dLsystm: Systematic error of length measurement, default value 0\n    \n    Returns:\n        A dictionary with the mean values of g, \n        the g-error values and the measured period \n        values, for each length\n    \"\"\"\n    L = L + dLsystm             # Add systematic error, if it exists\n    g = np.power(2*np.pi, 2) * L / np.power(T, 2) # Indirect g measurement from\n                                                  # length and period\n    dg = gError(L, T, dL, dT)   # g measurement error\n    gMean = np.sum(g)/g.size    # Mean value of g measurements\n    dgMean = np.sqrt(np.sum(dg*dg))/dg.size # Error of mean value of g\n    return {'g':gMean, 'dg':dgMean}\n\ndef fit(experiment, L, T, dLsystm = 0):\n    \"\"\"\n    Performs Least Square Fit on the given experiment\n    \n    Args:\n        experiment: The experiment to perform LSF\n        L: A vector of length measurements of the pendulum\n        T: A vector of period measurements of the pendulum\n        dLsystm: Systematic error of length measurement, default value 0\n    \n    Returns:\n        A dictionary with the LSF value of g, the\n        LSF coefficients, and the values used for the fit\n    \"\"\"\n    x = np.power(T, 2)\n    y = L + dLsystm\n    result = curve_fit(line, x, y)  # y = A + Bx\n    A = result[0][1]\n    B = result[0][0]\n    dBA = np.sqrt(np.diag(result[1]))\n    g = np.power(2*np.pi, 2) * B    # Coefficient A gives g: A = (2*pi)^2 / g\n    dg = np.power(2*np.pi, 2)*dBA[0]# Error of g is using error propagation rule\n    return {'g':g, 'dg':dg, 'A':A, 'B':B, 'x':x, 'y':y}\n\n\ngTheory = 9.8\nL = np.array([0.2, 0.4, 0.8, 1.0])\ndL = 0.01\ndT = 0.1\nnoise = np.random.standard_normal(L.size) * dT\nT = period(L) + noise               # Period measurements with dt=0.1s accuracy\n\nprint(\"Experiment without systematic error\")\nexperiment1 = experiment(L, T, dL, dT)          # Perform experiment 1\nprint(\"Mean Value Method\")\nprint(\"-----------------\")\nprint(\"g = {:.2f} +- {:.2f}\".format(experiment1['g'], experiment1['dg']))\nprint(\"\\nLeast Squares Fit Method\")\nprint(\"------------------------\")\nlsq1 = fit(experiment1, L, T)                   # Perform LSF for experiment 1\nprint(\"g = {:.2f} +- {:.2f}\".format(lsq1['g'], lsq1['dg']))\nxn = lsq1['x']\nyn = np.polyval([lsq1['B'], lsq1['A']], xn)\nplt.plot(xn, yn, 'r', label='$\\delta L_{system} = 0$') # Plot least square line\nplt.errorbar(lsq1['x'], lsq1['y'], xerr=dL, yerr=dT, fmt='r.') # Plot measurements\nplt.xlabel('$T^2[sec^2]$')\nplt.ylabel('$L[m]$')\n\ndLsystm = 0.05\nT = period(L+dLsystm) + noise\nT = period(L+dLsystm) + np.random.standard_normal(L.size) * dT\nprint(\"\\n\\nExperiment with systematic error={:.2f}\".format(dLsystm))\nexperiment2 = experiment(L, T, dL, dT, dLsystm) # Perform experiment 2,dL = 0.05\nprint(\"Mean Value Method\")\nprint(\"-----------------\")\nprint(\"g = {:.2f} +- {:.2f}\".format(experiment2['g'], experiment2['dg']))\nprint(\"\\nLeast Squares Fit Method\")\nprint(\"-------------------------\")\nlsq2 = fit(experiment2, L, T, dLsystm)\nprint(\"g = {:.2f} +- {:.2f}\".format(lsq2['g'], lsq2['dg']))\nxn = lsq2['x']\nyn = np.polyval([lsq2['B'], lsq2['A']], xn)\nplt.plot(xn, yn, 'b', label='$\\delta L_{system} = 0.05$') # Plot least square line\nplt.errorbar(lsq2['x'], lsq2['y'], xerr=dL, yerr=dT, fmt='b*') # Plot measurements\nplt.legend()\nplt.show()", "meta": {"hexsha": "4834bacd1436cfbfc7ccb31ab12730e90cfebfe5", "size": 4892, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignment1/mc_experiment.py", "max_stars_repo_name": "tzavellas/ComputationalPhysics", "max_stars_repo_head_hexsha": "7dd95d1a55faa4d467b9a96c7ee1933e88652370", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment1/mc_experiment.py", "max_issues_repo_name": "tzavellas/ComputationalPhysics", "max_issues_repo_head_hexsha": "7dd95d1a55faa4d467b9a96c7ee1933e88652370", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment1/mc_experiment.py", "max_forks_repo_name": "tzavellas/ComputationalPhysics", "max_forks_repo_head_hexsha": "7dd95d1a55faa4d467b9a96c7ee1933e88652370", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8322147651, "max_line_length": 101, "alphanum_fraction": 0.5901471791, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485603, "lm_q2_score": 0.9111797069968974, "lm_q1q2_score": 0.8514019170819274}}
{"text": "import numpy as np\nfrom homography_dlt import direct_linear_transform\n\n\ndef transfer_error(pt1, pt2, H):\n  \"\"\"\n  Calculate the transfer error between the two \n\n  NOTE: There are other distance metrics (e.g. symmetric distance, could they be better?)\n\n  Input:\n    pt1 - Destination point\n    pt2 - Point to transform onto destination plane\n    H - homography to transform \n\n  Output: Sum squared distance error\n  \"\"\"\n\n  pt1 = np.append(pt1, [1])\n  pt2 = np.append(pt2, [1])\n\n  pt1_projected = ((H @ pt1).T).T \n\n  diff = (pt2 - pt1_projected)\n\n  sse = np.sum(diff**2)\n\n  return sse\n\n\ndef homography_ransac(pts1, pts2, threshold, n_iterations):\n  \"\"\"\n  Find a best guess for the homography to map pts2 onto \n  the plane of pts1\n  \n  Input: \n    pts1 - Destination plane\n    pts2 - Points to transform onto destination plane#\n\n  Output: Tuple of (Homography projecting pts2 onto pts1 plane, RANSAC inlier kps)\n  \"\"\"\n\n  # Store maxInliners are points, if there is a tie in max, \n  # take the H that has maxInliners with the smallest standard deviation\n  maxInliers = []\n  bestH = None\n\n  for i in range(n_iterations):\n    # 4 random point indexes\n    random_pts_idxs = np.random.choice(len(pts1), 4)\n\n    # Get random sample using random indexes\n    pts1_sample = pts1[random_pts_idxs]\n    pts2_sample = pts2[random_pts_idxs]\n\n    # Compute H using DLT\n    H = direct_linear_transform(pts1_sample, pts2_sample)\n\n    inliers = []\n\n    # For each correspondence\n    for i in range(len(pts1)):\n      # Get distance for each correspondance\n      distance = transfer_error(pts1[i], pts2[i], H)\n\n      # Add correspondence to inliners if distance less than threshold\n      if (distance < threshold):\n        inliers.append([pts1[i], pts2[i]])\n\n    # If inliers > maxInliers, set as new best H\n    if (len(inliers) > len(maxInliers)):\n      maxInliers = inliers\n      bestH = H\n      # TODO: else if inliers == maxInliers, pick best H based on smallest standard deviation\n    \n  return bestH, maxInliers\n", "meta": {"hexsha": "783a43762b35a5930c15334bce55a99cab6f693e", "size": 1993, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/stitcher/homography_ransac.py", "max_stars_repo_name": "freddieb/panoramic-image-stitchin", "max_stars_repo_head_hexsha": "332b2785a5a65f8cb80efd72d69d5b2a4e60d14d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-11T08:31:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T08:31:28.000Z", "max_issues_repo_path": "src/stitcher/homography_ransac.py", "max_issues_repo_name": "freddieb/panoramic-image-stitchin", "max_issues_repo_head_hexsha": "332b2785a5a65f8cb80efd72d69d5b2a4e60d14d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stitcher/homography_ransac.py", "max_forks_repo_name": "freddieb/panoramic-image-stitchin", "max_forks_repo_head_hexsha": "332b2785a5a65f8cb80efd72d69d5b2a4e60d14d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-10T09:28:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T09:28:22.000Z", "avg_line_length": 25.8831168831, "max_line_length": 93, "alphanum_fraction": 0.6843953838, "include": true, "reason": "import numpy", "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474233166328, "lm_q2_score": 0.891811038968166, "lm_q1q2_score": 0.8513651104362889}}
{"text": "def dispersion_relation_2D(p, theta, C):\n    arg = C*sqrt(sin(p*cos(theta))**2 +\n                 sin(p*sin(theta))**2)\n    c_frac = 2./(C*p)*arcsin(arg)\n\n    return c_frac\n\nimport numpy as np\nfrom numpy import \\\n     cos, sin, arcsin, sqrt, pi  # for nicer math formulas\n\nr = p = np.linspace(0.001, pi/2, 101)\ntheta = np.linspace(0, 2*pi, 51)\nr, theta = np.meshgrid(r, theta)\n\n# Make 2x2 filled contour plots for 4 values of C\nimport matplotlib.pyplot as plt\nC_max = 1/sqrt(2)\nC = [[C_max, 0.9*C_max], [0.5*C_max, 0.2*C_max]]\nfix, axes = plt.subplots(2, 2, subplot_kw=dict(polar=True))\nfor row in range(2):\n    for column in range(2):\n        error = 1 - dispersion_relation_2D(\n            p, theta, C[row][column])\n        print error.min(), error.max()\n        # use vmin=error.min(), vmax=error.max()\n        cax = axes[row][column].contourf(\n            theta, r, error, 50, vmin=-1, vmax=-0.28)\n        axes[row][column].set_xticks([])\n        axes[row][column].set_yticks([])\n\n# Add colorbar to the last plot\ncbar = plt.colorbar(cax)\ncbar.ax.set_ylabel('error in wave velocity')\nplt.savefig('disprel2D.png');  plt.savefig('disprel2D.pdf')\nplt.show()\n\n# See\n# http://blog.rtwilson.com/producing-polar-contour-plots-with-matplotlib/\n# for polar plotting in matplotlib\n", "meta": {"hexsha": "4c90514b804435402eb3a81bbb62edba60420876", "size": 1274, "ext": "py", "lang": "Python", "max_stars_repo_path": "fdm-jupyter-book/notebooks/02_wave/src-wave/analysis/dispersion_relation_2D.py", "max_stars_repo_name": "devitocodes/devito_book", "max_stars_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-07-17T13:19:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-27T05:21:09.000Z", "max_issues_repo_path": "fdm-devito-notebooks/02_wave/src-wave/analysis/dispersion_relation_2D.py", "max_issues_repo_name": "devitocodes/devito_book", "max_issues_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 73, "max_issues_repo_issues_event_min_datetime": "2020-07-14T15:38:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-25T11:54:59.000Z", "max_forks_repo_path": "fdm-jupyter-book/notebooks/02_wave/src-wave/analysis/dispersion_relation_2D.py", "max_forks_repo_name": "devitocodes/devito_book", "max_forks_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-27T05:21:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T05:21:14.000Z", "avg_line_length": 31.0731707317, "max_line_length": 73, "alphanum_fraction": 0.636577708, "include": true, "reason": "import numpy,from numpy", "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474142844409, "lm_q2_score": 0.8918110461567923, "lm_q1q2_score": 0.851365109243884}}
{"text": "import numpy as np\n\ndef seidel(A, b, x):\n  size = len(A)\n  for j in range(size):\n    d = b[j]\n\n    for i in range(size):\n      if j != i:\n        d -= A[j][i] * x[i]\n    x[j] = d / A[j][j]\n  return x\n\ndef seidelIterations(A, b, eps, maxIterations):\n  size = len(A)\n  x = np.zeros(size)\n\n  for i in range(maxIterations):\n    xPrev = np.copy(x)\n    x = seidel(A, b, x)\n\n    print(f\"{i}-th iteration:\")\n    print(x)\n    if np.linalg.norm(np.dot(A, x) - b) <= eps * np.linalg.norm(b):\n      print(\"^^^^^^^^^^^^^^\")\n      print(\">> Малость невязки << Solution found\")\n      return\n    if np.linalg.norm(x - xPrev) <= eps * np.linalg.norm(xPrev):\n      print(\"^^^^^^^^^^^^^^\")\n      print(\">> Малость нормы приближений << Solution found\")\n      return\n\n  print(\"Number of iterations exceeded\")\n", "meta": {"hexsha": "bd80c1bf5482859d16161cd4d882d5a2f190f64b", "size": 788, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw2/src/Seidel.py", "max_stars_repo_name": "pool-party/numerical-methods", "max_stars_repo_head_hexsha": "708ff1215bb67216bac962a67d9476fe34417fb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-04-23T15:48:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T10:16:40.000Z", "max_issues_repo_path": "hw2/src/Seidel.py", "max_issues_repo_name": "pool-party/numerical-methods", "max_issues_repo_head_hexsha": "708ff1215bb67216bac962a67d9476fe34417fb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2020-02-28T01:16:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-20T19:05:34.000Z", "max_forks_repo_path": "hw2/src/Seidel.py", "max_forks_repo_name": "pool-party/numerical-methods", "max_forks_repo_head_hexsha": "708ff1215bb67216bac962a67d9476fe34417fb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-12-02T15:03:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T18:31:00.000Z", "avg_line_length": 23.1764705882, "max_line_length": 67, "alphanum_fraction": 0.5355329949, "include": true, "reason": "import numpy", "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9759464520028358, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.8513643284700702}}
{"text": "import sys\nimport csv\nimport math\n\nimport numpy as np\nimport pandas as pd\n\n\n'''\nPrints the information gain values for each partition (or column).\n'''\ndef runEntropy(df):\n\n    # Get Y and labels:\n    labels = list(df.axes[1])\n    y_label = labels[0]\n    Y = df[y_label]\n    del labels[0]\n\n    #Get information gain and loss for each partition:\n    data_str = \"Partition\\t\\tInformation Gain\"\n    for i in labels:\n        data_str += \"\\n{}:\\t\\t\\t{}\".format(i, infoGainLoss(df[i],Y))\n\n    #Print data\n    print(data_str)\n\n'''\nComputes the entropy of the Y column.\n'''\ndef getSetEntropy(Y):\n    partitionEntropy = 0\n    p_1 = sum(Y)/len(Y)\n    p_2 = 1-p_1\n    if p_2 == 0:\n        partitionEntropy = 0\n    elif p_1 == 0:\n        partitionEntropy = 1\n    else:\n        partitionEntropy = -((p_1*math.log(p_1,2)) + (p_2*math.log(p_2,2)))\n    return(partitionEntropy)\n\n'''\nComputes the information gain, which is simply the entropy of the set minus\nthe combined entropies of each result in a partition (or a column).\n'''\ndef infoGainLoss(X,Y):\n    setEntropy = getSetEntropy(Y)\n    part_dict = getPartitionEntropy(X,Y)\n    set_xresults = set(X)\n    part_fracs = set()\n    for p in set_xresults:\n        total = 0\n        numPart = 0\n        for i in range(len(X)):\n            total += 1\n            if X[i] == p:\n                numPart += 1\n        try:\n            if not math.isnan(float(p)):\n                part_fracs.add((numPart/total)*part_dict[p])\n        except:\n            part_fracs.add((numPart/total)*part_dict[p])\n    return(setEntropy - sum(part_fracs))\n\n'''\nGets Entropy for each value in a partitioned column and returns\nthem in a dictionary used to compute the combined partition entropy\nin infoGainLoss.\n'''\ndef getPartitionEntropy(X,Y):\n    set_xresults = set(X)\n    partitionEntropy = 0\n    part_dict = {}\n    for p in set_xresults:\n        numTotal = 0\n        numCorrect = 0\n        for i in range(len(X)):\n            if X[i] == p:\n                numTotal += 1\n                if Y[i] == 1:\n                    numCorrect += 1\n        if numTotal == 0:\n            p_1 = 0\n            p_2 = 1\n        else:\n            p_1 = numCorrect/numTotal\n            p_2 = 1-p_1\n\n        if p_2 == 0:\n            partitionEntropy = 0\n        elif p_1 == 0:\n            partitionEntropy = 1\n        else:\n            partitionEntropy = -((p_1*math.log(p_1,2)) + (p_2*math.log(p_2,2)))\n\n        part_dict[p] = partitionEntropy\n    return part_dict\n", "meta": {"hexsha": "189e8a29b979172faec070214f9a6b688fd658e5", "size": 2457, "ext": "py", "lang": "Python", "max_stars_repo_path": "Problem-Set-3/src/entropy.py", "max_stars_repo_name": "jShiohaha/data-and-models-ii", "max_stars_repo_head_hexsha": "ba16ade0349753ca3745a35a4938a77fd30940c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Problem-Set-3/src/entropy.py", "max_issues_repo_name": "jShiohaha/data-and-models-ii", "max_issues_repo_head_hexsha": "ba16ade0349753ca3745a35a4938a77fd30940c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Problem-Set-3/src/entropy.py", "max_forks_repo_name": "jShiohaha/data-and-models-ii", "max_forks_repo_head_hexsha": "ba16ade0349753ca3745a35a4938a77fd30940c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8181818182, "max_line_length": 79, "alphanum_fraction": 0.5722425722, "include": true, "reason": "import numpy", "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399043329855, "lm_q2_score": 0.8774767762675405, "lm_q1q2_score": 0.851362983460235}}
{"text": "import numpy as np\nfrom utils import transpose_matrix, norm\n\n\ndef conjugate_gradient(A, b, x0 = None, eps = None, maxIter = 1000):\n    \"\"\"\n    Performs conjugate gradient method to the function f(x) = 1/2(A*Ax) - x*A*b\n    :param A: a matrix mxn\n    :param b: a column vector nx1\n    :param x0: starting point, if None the 0 vector is used as default starting point\n    :param eps: (optional) the accuracy in the stopping criterion\n    :param maxIter:  (optional, default value 1000): the maximum number of iterations\n    :return: [x, status, ite]:\n    :  - x (mx1 real column vector): it solves ||gradient(f(x))|| = A*Ax - A*b = 0\n    :  - status (string): a string describing the status of the algorithm at\n    :    termination\n    :    = 'optimal': the algorithm terminated having proven that x is an optimal solution, i.e.,\n    :                 the norm of the gradient at x is less than the required threshold\n    :    = 'finished': the algorithm terminated in m iterations since no threshold of accuracy is required\n    :    = 'stopped': the algorithm terminated having exhausted the maximum number of iterations\n    :  - ite: number of iterations executed by the algorithm\n    \"\"\"\n    if x0 is None:\n        x = np.zeros(A.shape[1])\n    else:\n        x = x0\n        \n    r = b - np.matmul(A, x)\n    g_0 = np.matmul(transpose_matrix(A), r)\n    d = g_0\n    g = g_1 = g_0\n    i = 1\n    while True:\n        if i>1:\n            g_2 = g_1\n            g_1 = g\n            beta = -np.divide(np.square(norm(g_1)),np.square(norm(g_2)))\n            d = g_1 - beta*d   \n            # print(\"Space used \", r.nbytes+d.nbytes+x.nbytes+g.nbytes+g_1.nbytes+g_2.nbytes)\n        Ad = np.matmul(A, d) \n        alpha = np.divide(np.square(norm(g_1)),np.square(norm(Ad)))\n        x = x + alpha*d\n        r = r - alpha*Ad\n        g = np.matmul(transpose_matrix(A), r)\n        ng = norm(g)\n        \n        if eps is None: \n            # no stopping condition, we end up in m iterations or when the norm of the gradient is zero\n            if not np.any(g):\n                status = \"optimal\"\n                break\n            if i > A.shape[1]:\n                status = \"finished\"\n                break\n        else:\n            # check accuracy for stopping condition\n            if ng <= eps:\n                status = \"optimal\"\n                break\n            if i > maxIter:\n                status = \"stopped\"\n                break\n            \n        i = i+1\n\n    return x, status, i-1\n\n\n\n", "meta": {"hexsha": "50bfc17b5824c34b7d37de1299ef8e771aac4584", "size": 2481, "ext": "py", "lang": "Python", "max_stars_repo_path": "conjugate_gradient.py", "max_stars_repo_name": "StefanoBerti/CM", "max_stars_repo_head_hexsha": "2be5f221b3d2c5589ee52e50ec9c022c99fd421a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-26T08:02:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T08:02:09.000Z", "max_issues_repo_path": "conjugate_gradient.py", "max_issues_repo_name": "StefanoBerti/CM", "max_issues_repo_head_hexsha": "2be5f221b3d2c5589ee52e50ec9c022c99fd421a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-08T22:25:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T03:20:45.000Z", "max_forks_repo_path": "conjugate_gradient.py", "max_forks_repo_name": "StefanoBerti/CM", "max_forks_repo_head_hexsha": "2be5f221b3d2c5589ee52e50ec9c022c99fd421a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-04T05:22:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T05:22:26.000Z", "avg_line_length": 35.4428571429, "max_line_length": 106, "alphanum_fraction": 0.5554212011, "include": true, "reason": "import numpy", "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.9032942008463507, "lm_q1q2_score": 0.8513608555183197}}
{"text": "\"\"\"\nAuthor: Rayla Kurosaki\n\nFile: interpolation.py\n\nDescription:\n\"\"\"\n\nimport numpy as np\nimport sympy as sym\n\n\ndef lagrange(data):\n    \"\"\"\n    Constructs the Lagrange Interpolating Polynomial that interpolates a list\n    of points.\n\n    :param data: A list of points to interpolate.\n    :return: The Lagrange Interpolating Polynomial that interpolates a list\n             of points.\n    \"\"\"\n\n    def lagrange_poly(k, xs):\n        \"\"\"\n        Constructs the Lagrange basis polynomial.\n\n        :param k: The index of the list of x values to skip.\n        :param xs: A list of x values.\n        :return: The Lagrange basis polynomial\n        \"\"\"\n        poly = 1\n        x_var = sym.symbols('x')\n        for i, x in enumerate(xs):\n            if not (i == k):\n                poly *= (x_var - x) / (xs[k] - x)\n                pass\n            pass\n        return poly\n\n    P = 0\n    xs = [x for x, y in data]\n    for j, (x, y) in enumerate(data):\n        P += y * lagrange_poly(j, xs)\n        pass\n    return P\n\n\ndef newton_divided_differences(data):\n    \"\"\"\n    Computes the coefficients for the interpolating polynomial that\n    interpolates the set of data points.\n\n    :param data: The list of data points to interpolate.\n    :return: The coefficients for the interpolating polynomial that\n             interpolates the set of data points.\n    \"\"\"\n    xs, ys = [x for (x, y) in data], [y for (x, y) in data]\n    ndd = np.zeros((len(xs), len(ys)))\n    for j, y in enumerate(ys):\n        ndd[j][0] = y\n        pass\n    for c in range(1, len(ys)):\n        for r in range(len(ys) - c):\n            num = ndd[r + 1][c - 1] - ndd[r][c - 1]\n            denom = xs[r + c] - xs[r]\n            ndd[r][c] = sym.nsimplify(num / denom)\n            pass\n        pass\n    return ndd[0]\n\n\ndef ndd_polynomial(data):\n    \"\"\"\n    Constructs the polynomial that interpolates the set of data points.\n\n    :param data: The list of data points to interpolate.\n    :return: The polynomial that interpolates the set of data points.\n    \"\"\"\n    xs, ys = [x for (x, y) in data], [y for (x, y) in data]\n    cs = newton_divided_differences(data)\n    poly = 0\n    for i, c in enumerate(cs):\n        x = sym.symbols('x')\n        expr = 1\n        for j in range(i):\n            expr *= x - xs[j]\n            pass\n        poly += sym.nsimplify(c * expr)\n        pass\n    return poly\n\n\ndef chebyshev():\n    pass\n\n\ndef cubic_splines():\n    pass\n\n\ndef natural_cubic_splines():\n    pass\n\n\ndef bezier():\n    pass\n", "meta": {"hexsha": "8868309c4424f3869681cb66114ba16b864800f7", "size": 2477, "ext": "py", "lang": "Python", "max_stars_repo_path": "rayla/math/interpolation.py", "max_stars_repo_name": "RaylaKurosaki1503/Raylas_Modules", "max_stars_repo_head_hexsha": "078281e17130d09ea1fadde0b96539046b60d4a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-15T05:31:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T05:31:37.000Z", "max_issues_repo_path": "rayla/math/interpolation.py", "max_issues_repo_name": "RaylaKurosaki1503/Raylas_Modules", "max_issues_repo_head_hexsha": "078281e17130d09ea1fadde0b96539046b60d4a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rayla/math/interpolation.py", "max_forks_repo_name": "RaylaKurosaki1503/Raylas_Modules", "max_forks_repo_head_hexsha": "078281e17130d09ea1fadde0b96539046b60d4a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1495327103, "max_line_length": 77, "alphanum_fraction": 0.5631812677, "include": true, "reason": "import numpy,import sympy", "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957912273285902, "lm_q2_score": 0.8887587964389112, "lm_q1q2_score": 0.8513529590996397}}
{"text": "# We need install numpy in order to import it\r\nimport numpy as np\r\n\r\n# input two matrices\r\nmat1 = ([1, 6, 5], [3, 4, 8], [2, 12, 3])\r\nmat2 = ([3, 4, 6], [5, 6, 7], [6, 56, 7])\r\n\r\n# This will return dot product\r\nres = np.dot(mat1, mat2)\r\n\r\n# print resulted matrix\r\nprint(res)\r\n\r\n\r\n# input two matrices of size n x m\r\nmatrix1 = [[12, 7, 3],\r\n           [4, 5, 6],\r\n           [7, 8, 9]]\r\nmatrix2 = [[5, 8, 1],\r\n           [6, 7, 3],\r\n           [4, 5, 9]]\r\n\r\nres = [[0 for x in range(3)] for y in range(3)]\r\n\r\n# explicit for loops\r\nfor i in range(len(matrix1)):\r\n    for j in range(len(matrix2[0])):\r\n        for k in range(len(matrix2)):\r\n\r\n            # resulted matrix\r\n            res[i][j] += matrix1[i][k] * matrix2[k][j]\r\n\r\nprint(res)\r\n", "meta": {"hexsha": "b9cfbf5a3fcaae2ffb95ab7bb8662d44daec4fbb", "size": 741, "ext": "py", "lang": "Python", "max_stars_repo_path": "algo/nopp.py", "max_stars_repo_name": "rjcpc/stuff", "max_stars_repo_head_hexsha": "cc1fa1c6e228d9486efa4cd458c24187ebde073a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2019-07-09T17:37:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T09:23:43.000Z", "max_issues_repo_path": "algo/nopp.py", "max_issues_repo_name": "rjcpc/stuff", "max_issues_repo_head_hexsha": "cc1fa1c6e228d9486efa4cd458c24187ebde073a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algo/nopp.py", "max_forks_repo_name": "rjcpc/stuff", "max_forks_repo_head_hexsha": "cc1fa1c6e228d9486efa4cd458c24187ebde073a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-07-04T16:42:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-05T08:51:16.000Z", "avg_line_length": 21.7941176471, "max_line_length": 55, "alphanum_fraction": 0.5020242915, "include": true, "reason": "import numpy", "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122672782974, "lm_q2_score": 0.8887587875995482, "lm_q1q2_score": 0.8513529452929939}}
{"text": "from __future__ import absolute_import\n\n# -- IMPORT -- #\nimport math\nimport numpy as np\n\n# -- AVAILABLE METRICS  -- #\navailableMetrics = ['euclidean','manhattan','minkowski','cosine','jaccard']\n\n# -- DISTANCE METRICS -- #\nclass Metrics():\n\t\"\"\"CLASS::Metrics:\n\t\t---\n\t\tDescription:\n\t\t---\n\t\t>Base that allows to compute different distance operations.\"\"\"\n\tdef euclidean_distance(self,x,y):\n\t\t\"\"\"METHOD::EUCLIDEAN_DISTANCE:\n\t\t\t---\n\t\t\tArguments:\n\t\t\t---\n\t\t\t>- x {np.array} -- array one.\n\t\t\t>- y {np.array} -- array two.\n\t\t\tReturns:\n\t\t\t---\n\t\t\t>- {np.array} -- The euclidean distance between the two arrays.\"\"\"\n\t\treturn np.sqrt(np.sum(np.power(np.subtract(x,y),2),axis=-1))\n\n\tdef manhattan_distance(self,x,y):\n\t\t\"\"\"METHOD::MANHATTAN_DISTANCE:\n\t\t\t---\n\t\t\tArguments:\n\t\t\t---\n\t\t\t>- x {np.array} -- array one.\n\t\t\t>- y {np.array} -- array two.\n\t\t\tReturns:\n\t\t\t---\n\t\t\t>- {np.array} -- The manhattan distance between the two arrays.\"\"\"\n\t\treturn np.sum(np.abs(np.subtract(x,y)),axis=-1)\n\t\n\tdef minkowski_distance(self,x,y,pVal):\n\t\t\"\"\"METHOD::MINKOWSKI_DISTANCE:\n\t\t\t---\n\t\t\tArguments:\n\t\t\t---\n\t\t\t>- x {np.array} -- array one.\n\t\t\t>- y {np.array} -- array two.\n\t\t\t>- pVal {int} -- p value for minkowski distance.\n\t\t\tReturns:\n\t\t\t---\n\t\t\t>- {np.array} -- The minkowski distance between the two arrays.\"\"\"\n\t\treturn self.__nth_root(np.sum(np.power(np.abs(np.subtract(x,y)),pVal),axis=-1),pVal)\n\t\n\tdef cosine_distance(self,x,y):\n\t\t\"\"\"METHOD::COSINE_DISTANCE:\n\t\t\t---\n\t\t\tArguments:\n\t\t\t---\n\t\t\t>- x {np.array} -- array one.\n\t\t\t>- y {np.array} -- array two.\n\t\t\tReturns:\n\t\t\t---\n\t\t\t>- {np.array} -- The cosine distance between two arrays.\"\"\"\n\t\ty = y.reshape(x.shape[1],x.shape[0])\n\t\treturn np.dot(x,y)/(np.linalg.norm(x)*np.linalg.norm(y))\n\n\tdef jaccard_distance(self,x,y):\n\t\t\"\"\"METHOD::JACCARD_DISTANCE:\n\t\t\t---\n\t\t\tArguments:\n\t\t\t---\n\t\t\t>- x {np.array} -- array one.\n\t\t\t>- y {np.array} -- array two.\n\t\t\tReturns:\n\t\t\t---\n\t\t\t>- {np.array} -- The jaccard distance between two arrays.\"\"\"\n\t\tx = np.asarray(x, np.bool) \n\t\ty = np.asarray(y, np.bool) \n\t\treturn np.double(np.bitwise_and(x, y).sum())/np.double(np.bitwise_or(x, y).sum())\n\t\n\tdef __nth_root(self,value,nRoot):\n\t\t\"\"\"METHOD::__NTH_ROOT:\n\t\t\t---\n\t\t\tArguments:\n\t\t\t---\n\t\t\t>- value {np.array} -- array containing the values to root.\n\t\t\t>- nRoot {int} -- root number.\n\t\t\tReturns:\n\t\t\t---\n\t\t\t>- {np.array} -- The nth_root of a array\"\"\"\n\t\treturn np.round(value**(1/float(nRoot)))\n\n\tdef __repr__(self):\n\t\treturn '<class::Metrics -- Distance Computation>'\n", "meta": {"hexsha": "0a5d2c13396e680e84349b00686b1f46658aaf87", "size": 2458, "ext": "py", "lang": "Python", "max_stars_repo_path": "innterpret/utils/bases/metrics.py", "max_stars_repo_name": "paudom/iNNterpret", "max_stars_repo_head_hexsha": "8e6a4fc43bfc497e26fea37942765a5efaf5b7c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-08T12:23:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-05T14:05:19.000Z", "max_issues_repo_path": "innterpret/utils/bases/metrics.py", "max_issues_repo_name": "paudom/iNNterpret", "max_issues_repo_head_hexsha": "8e6a4fc43bfc497e26fea37942765a5efaf5b7c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:38:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:44:34.000Z", "max_forks_repo_path": "innterpret/utils/bases/metrics.py", "max_forks_repo_name": "paudom/iNNterpret", "max_forks_repo_head_hexsha": "8e6a4fc43bfc497e26fea37942765a5efaf5b7c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8736842105, "max_line_length": 86, "alphanum_fraction": 0.6082180635, "include": true, "reason": "import numpy", "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812309063186, "lm_q2_score": 0.8791467659263148, "lm_q1q2_score": 0.8513492273350338}}
{"text": "from abc import abstractmethod, ABC\nimport numpy as np\n\n\nclass Activation(ABC):\n    \"\"\"\n    Base class for all activation functions\n    \"\"\"\n\n    @abstractmethod\n    def __call__(self, x):\n        pass\n\n    @abstractmethod\n    def derivative(self, x):\n        pass\n\n\nclass Linear(Activation):\n    def __call__(self, x):\n        return x\n\n    def derivative(self, x):\n        return 1\n\n    def __str__(self):\n        return \"Linear\"\n\n\nclass Sigmoid(Activation):\n    def __call__(self, x):\n        return 1 / (1 + np.exp(-x))\n\n    def derivative(self, x):\n        return self(x) * (1 - self(x))\n\n    def __str__(self):\n        return \"Sigmoid\"\n\n\nclass LeakyReLU(Activation):\n    def __init__(self, alpha=0.01):\n        self.alpha = alpha\n\n    def __call__(self, x):\n        return np.maximum(self.alpha * x, x)\n\n    def derivative(self, x):\n        if not isinstance(x, np.ndarray):\n            return 0 if x < 0 else 1\n        x = x.copy()\n        negative_dims = x < 0\n        x[negative_dims] = self.alpha\n        x[~negative_dims] = 1\n        return x\n\n    def __str__(self):\n        return f\"Leaky ReLU - alpha={self.alpha}\"\n\n\nclass ReLU(LeakyReLU):\n    def __init__(self):\n        super().__init__(alpha=0)\n\n    def __str__(self):\n        return \"ReLU\"\n\n\nclass Sin(Activation):\n    def __call__(self, x):\n        return np.sin(x)\n\n    def derivative(self, x):\n        return np.cos(x)\n\n    def __str__(self):\n        return \"Sine\"\n\n\nclass Cos(Activation):\n    def __call__(self, x):\n        return np.cos(x)\n\n    def derivative(self, x):\n        return -np.sin(x)\n\n    def __str__(self):\n        return \"Cosine\"\n\n\nclass Softmax(Activation):\n    def __call__(self, x):\n        exps = np.exp(x - np.max(x))\n        return exps / np.sum(exps)\n\n    def derivative(self, x):\n        pass\n\n    def __str__(self):\n        return \"Softmax\"\n\n\nclass Tanh(Activation):\n    def __call__(self, x):\n        exp_x = np.exp(x)\n        exp__x = np.exp(-x)\n        return (exp_x - exp__x) / (exp_x + exp__x)\n\n    def derivative(self, x):\n        return 1 - self(x) ** 2\n\n    def __str__(self):\n        return \"Tanh\"\n\n\nclass MultiActivations(Activation):\n    def __init__(self, dimensions, activations):\n        self.activations = []\n        neurons_per_act = int(np.ceil(dimensions / len(activations)))\n        prev = 0\n        for act in activations[:-1]:\n            self.activations.append((act, prev, prev + neurons_per_act))\n            prev += neurons_per_act\n        self.activations.append((activations[-1], prev, dimensions))  # take the rest\n\n    def __call__(self, z):\n        x = z.copy()\n        for act_func, s, e in self.activations:\n            x[s:e] = act_func(x[s:e])\n        return x\n\n    def derivative(self, z):\n        x = z.copy()\n        for act_func, s, e in self.activations:\n            x[s:e] = act_func.derivative(x[s:e])\n        return x\n\n    def __str__(self):\n        return \", \".join([str(act) for act, _, _ in self.activations])\n", "meta": {"hexsha": "717f288adaecaa86cbdfcd6dec78bc6b1788511d", "size": 2949, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/activation_functions.py", "max_stars_repo_name": "salvaRC/target_propagation", "max_stars_repo_head_hexsha": "e640e45c3e37af93464db2f6fe406d7e671cb6c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-15T16:32:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T16:32:21.000Z", "max_issues_repo_path": "src/activation_functions.py", "max_issues_repo_name": "salvaRC/numpy-neural-network", "max_issues_repo_head_hexsha": "e37e1a1356e5334b89f78c27372200df5ff2d61e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/activation_functions.py", "max_forks_repo_name": "salvaRC/numpy-neural-network", "max_forks_repo_head_hexsha": "e37e1a1356e5334b89f78c27372200df5ff2d61e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0642857143, "max_line_length": 85, "alphanum_fraction": 0.5700237369, "include": true, "reason": "import numpy", "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582535657919, "lm_q2_score": 0.9149009613738741, "lm_q1q2_score": 0.851277150705599}}
{"text": "import numpy as np\n\n# General\ndef epsilonMaquina(tipoDato):\n    \"\"\" Funcion que trata de calcular el epsilon \n    de la maquina mediante el algoritmo antes pre_\n    sentado. \n    Input:\n        tipoDato := esta pensado para ser uno de \n            los tipos proporcionados por la li_\n            breria numpy.\n    Output:\n        Regresa el epsilon de la maquina calcula_\n            do con el tipo de dato especificado.\n    \"\"\"\n    epsilon = tipoDato(1.0)\n    unidad = tipoDato(1.0)\n    valor = unidad + epsilon\n    \n    while valor > unidad:\n        epsilon = epsilon/tipoDato(2.0)\n        valor = unidad + epsilon\n        \n    return epsilon*2\n\n\ndef epsilonFloat():\n    \"\"\" Calculamos el epsilon de la maquina con \n    precision de 32bits\n    \"\"\"\n    return epsilonMaquina(np.float32)\n\ndef epsilonDouble():\n    \"\"\" Calculamos el epsilon de la maquina con\n    precision de 64 bits\n        A pesar de que el flotante de python ya\n    tiene esta precision, creo que es convenien_\n    te especificarlo.\n    \"\"\"\n    return epsilonMaquina(np.float64)\n\n# Segunda parte\ndef respuesta(res):\n    \"\"\" Funcion para formatear la respuesta. \"\"\"\n    return \"iguales\" if res else \"diferentes\"\n\ndef comparacion(epsilon):\n    \"\"\" Esta funcion resivira el epsilon a eva_\n    luar y el tipo de dato al que este correspon_\n    de para hacer las comparaciones solicitadas\n    en el ejercicio.\n    Input:\n        En caso de que \n    Output:\n        Las respuestas son procesadas por la\n        funcion respuesta para obtener el for_\n        mato solicitado\n            True implica que son iguales\n            False implica que son diferentes\n    \"\"\"\n    tD = type(epsilon) # Para escribir menos\n    print(f'Con {epsilon=} y tipo de dato = {str(tD)} se da que')\n    \n    # Comprobaciones\n    print(f'{respuesta( tD(1 + epsilon )   == 1 )  =}')\n    print(f'{respuesta( tD( epsilon/2 )    == 0 )  =}')\n    print(f'{respuesta( tD(1 + epsilon/2 ) == 1 )  =}')\n    print(f'{respuesta( tD(1 - epsilon/2 ) == 1 )  =}')\n    print(f'{respuesta( tD(1 - epsilon/4 ) == 1 )  =}')\n    print(f'{respuesta( tD( epsilon**2 )   == 0 )  =}')\n    print(f'{respuesta(epsilon + tD(epsilon**2) == epsilon) =}')\n    print(f'{respuesta(epsilon - tD(epsilon**2) == epsilon) =}')\n    \n    print('...\\n')\n\n\nif __name__ == '__main__':\n    # Epsilons calculados\n    eF = np.float32(epsilonFloat())\n    eD = np.float64(epsilonDouble())\n\n    # Imprimir en pantalla\n    print(f'Se calculalron los epsilons \\n\\teF={eF} y \\n\\teF={eD} \\n para 32 y 64 bits correspondientemente.\\n')\n\n    # Hacemos la comparacion para 32bits\n    comparacion(eF)\n    # y para 64\n    comparacion(eD)\n\n", "meta": {"hexsha": "1885b54ea7e1a03ae29e9d965f62d9f8b68e1a86", "size": 2626, "ext": "py", "lang": "Python", "max_stars_repo_path": "MN/Tareas/T1/T1.py", "max_stars_repo_name": "BenchHPZ/UG-Compu", "max_stars_repo_head_hexsha": "fa3551a862ee04b59a5ba97a791f39a77ce2df60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MN/Tareas/T1/T1.py", "max_issues_repo_name": "BenchHPZ/UG-Compu", "max_issues_repo_head_hexsha": "fa3551a862ee04b59a5ba97a791f39a77ce2df60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MN/Tareas/T1/T1.py", "max_forks_repo_name": "BenchHPZ/UG-Compu", "max_forks_repo_head_hexsha": "fa3551a862ee04b59a5ba97a791f39a77ce2df60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1777777778, "max_line_length": 112, "alphanum_fraction": 0.6169078446, "include": true, "reason": "import numpy", "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.9304582554941719, "lm_q1q2_score": 0.8512771378968561}}
{"text": "import numpy as np\n\nfrom ..sampling import Sample\n\n\nclass IntegrationSample(Sample):\n\n    def __init__(self, **kwargs):\n        self.function_values = None\n\n        # computed by the integration methods\n        self.integral = None\n        self.integral_err = None\n\n        super().__init__(**kwargs)\n\n\nclass PlainMC(object):\n    \"\"\" Plain Monte Carlo integration method.\n\n    Approximate the integral as the mean of the integrand over a randomly\n    selected sample (uniform probability distribution over the unit hypercube).\n    \"\"\"\n    def __init__(self, ndim=1, name=\"MC Plain\"):\n        self.method_name = name\n        self.ndim = ndim\n\n    def __call__(self, fn, eval_count):\n        \"\"\" Compute Monte Carlo estimate of ndim-dimensional integral of fn.\n\n        The integration volume is the ndim-dimensional unit cube [0,1]^ndim.\n\n        :param fn: A function accepting self.ndim numpy arrays,\n            returning an array of the same length with the function values.\n        :param eval_count: Total number of function evaluations used to\n            approximate the integral.\n        :return: Tuple (integral_estimate, error_estimate) where\n            the error_estimate is based on the unbiased sample variance\n            of the function, computed on the same sample as the integral.\n            According to the central limit theorem, error_estimate approximates\n            the standard deviation of the statistical (normal) distribution\n            of the integral estimates.\n        \"\"\"\n        sample = IntegrationSample()\n        sample.data = np.random.random((eval_count, self.ndim))\n        sample.function_values = fn(*sample.data.transpose())\n        sample.integral = np.mean(sample.function_values)\n        err = np.sqrt(np.var(sample.function_values) / eval_count)\n        sample.integral_err = err\n        return sample\n", "meta": {"hexsha": "3fcaee64c7aaf97118e5d7a5f466747846caeea1", "size": 1850, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/hepmc/core/integration/integration.py", "max_stars_repo_name": "mathisgerdes/monte-carlo-integration", "max_stars_repo_head_hexsha": "533d13eeb538fec46f8d5ed00e780153b68ba7d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-15T03:01:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-25T16:54:02.000Z", "max_issues_repo_path": "src/hepmc/core/integration/integration.py", "max_issues_repo_name": "mathisgerdes/monte-carlo-integration", "max_issues_repo_head_hexsha": "533d13eeb538fec46f8d5ed00e780153b68ba7d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hepmc/core/integration/integration.py", "max_forks_repo_name": "mathisgerdes/monte-carlo-integration", "max_forks_repo_head_hexsha": "533d13eeb538fec46f8d5ed00e780153b68ba7d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-15T09:02:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T09:02:00.000Z", "avg_line_length": 36.2745098039, "max_line_length": 79, "alphanum_fraction": 0.672972973, "include": true, "reason": "import numpy", "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924818279465, "lm_q2_score": 0.8757869803008764, "lm_q1q2_score": 0.8512583605352517}}
{"text": "import sys\nimport numpy as np\nfrom scipy.stats import chi2\nimport matplotlib.pyplot as plt\nimport my_style\n\ndef plot_chi2(ndf=4):\n\n    x_max = 1\n    while(True):\n        if chi2.sf(x_max, ndf) < 0.00001:\n            break\n        x_max += 1\n    x_max = (x_max // 10) * 10\n\n    x = np.linspace(0, x_max, 500)\n    plt.plot(x, chi2.pdf(x, ndf), 'k-')\n    plt.title('$\\\\chi^2$ distribusion ndf = {0}'.format(ndf))\n    plt.xlabel(\"$\\\\chi^2$\")\n    plt.ylabel(\"Probability\")\n    plt.xlim(0, x_max)\n    plt.ylim(0, None)\n    plt.show()\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) == 1:\n        plot_chi2()\n    if len(sys.argv) == 2:\n        plot_chi2(float(sys.argv[1]))\n", "meta": {"hexsha": "771b529ed6f6396be757516e6c263a95c0804471", "size": 669, "ext": "py", "lang": "Python", "max_stars_repo_path": "yoshimoto/plot_chi2.py", "max_stars_repo_name": "ymap-team/ROOT2020", "max_stars_repo_head_hexsha": "70db45f20aaea038c017656c63b0c51416156a33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "yoshimoto/plot_chi2.py", "max_issues_repo_name": "ymap-team/ROOT2020", "max_issues_repo_head_hexsha": "70db45f20aaea038c017656c63b0c51416156a33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "yoshimoto/plot_chi2.py", "max_forks_repo_name": "ymap-team/ROOT2020", "max_forks_repo_head_hexsha": "70db45f20aaea038c017656c63b0c51416156a33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5806451613, "max_line_length": 61, "alphanum_fraction": 0.5739910314, "include": true, "reason": "import numpy,from scipy", "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104962847373, "lm_q2_score": 0.8807970904940926, "lm_q1q2_score": 0.8512115533505487}}
{"text": "#Newton Raphson Methods\r\n\r\n\"\"\"\r\nName - Suryabrata Das\r\n\r\nSem: V    \r\n\r\nCollege_Roll_NO: 703\r\n\r\nPaper-code: CMSA DSE-IB\r\n\r\nRegistration No: A01-1112-117-003-2018\r\n\r\nExamination roll_no: 2021151264\r\n\r\nSubject: Numerical Methods (DSE-I)\r\n\r\n\"\"\"\r\nfrom sympy import *\r\n\r\ndef newton_raphson(f,f_prime,a,e):\r\n    h = f(a)/f_prime(a)\r\n    while abs(h) >= e:\r\n        h = f(a)/f_prime(a)\r\n        a = a - h\r\n    print(\"The root of the equation is: \",a)\r\ndef main():\r\n    x = Symbol('x')\r\n    f = x**3 - x - 3\r\n    f_prime = f.diff(x)\r\n    print(\"Your function: \",f);\r\n    print(\"Derivative of the function: \",f_prime)\r\n    f = lambdify(x, f)\r\n    f_prime = lambdify(x, f_prime)\r\n    a = 1\r\n    e = 10**(-1*5)\r\n    newton_raphson(f,f_prime,a,e)\r\nif __name__ == '__main__':\r\n    main()", "meta": {"hexsha": "b3ad1468810355e1e028ca3646540971344b3283", "size": 773, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numerical method_practical_problems/Newton Raphson.py", "max_stars_repo_name": "surya810/Numerical-method-notes", "max_stars_repo_head_hexsha": "6d9dc7aba56e3f9fb8923e3c6d271d8eefcb6fb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numerical method_practical_problems/Newton Raphson.py", "max_issues_repo_name": "surya810/Numerical-method-notes", "max_issues_repo_head_hexsha": "6d9dc7aba56e3f9fb8923e3c6d271d8eefcb6fb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numerical method_practical_problems/Newton Raphson.py", "max_forks_repo_name": "surya810/Numerical-method-notes", "max_forks_repo_head_hexsha": "6d9dc7aba56e3f9fb8923e3c6d271d8eefcb6fb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8205128205, "max_line_length": 50, "alphanum_fraction": 0.5705045278, "include": true, "reason": "from sympy", "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104885453717, "lm_q2_score": 0.8807970811069351, "lm_q1q2_score": 0.8512115374618906}}
{"text": "import numpy as np\n\n# Write a function that takes as input a list of numbers, and returns\n# the list of values given by the softmax function.\ndef softmax(L):\n    e_sum = np.sum(np.exp(L))\n    return np.exp(L) / e_sum", "meta": {"hexsha": "67e0b1acb398e24d281ed8a4e0eee467a39f7724", "size": 216, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercises/intro-neural-networks/softmax.py", "max_stars_repo_name": "Andrewzh112/Udacity-Deep-Learning-Nanodegree", "max_stars_repo_head_hexsha": "20e284560bf617b2614d35682f8f28f128f770f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercises/intro-neural-networks/softmax.py", "max_issues_repo_name": "Andrewzh112/Udacity-Deep-Learning-Nanodegree", "max_issues_repo_head_hexsha": "20e284560bf617b2614d35682f8f28f128f770f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercises/intro-neural-networks/softmax.py", "max_forks_repo_name": "Andrewzh112/Udacity-Deep-Learning-Nanodegree", "max_forks_repo_head_hexsha": "20e284560bf617b2614d35682f8f28f128f770f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8571428571, "max_line_length": 69, "alphanum_fraction": 0.7083333333, "include": true, "reason": "import numpy", "num_tokens": 55, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104933824754, "lm_q2_score": 0.8807970732843033, "lm_q1q2_score": 0.8512115341625239}}
{"text": "# The area of a circle is defined as πr^2.\n# Estimate π to 3 decimal places using a Monte Carlo method.\n# Hint: The basic equation of a circle is x^2 + y^2 = r^2.\n\n\n# P(point inside circle) = πr^2 / (2r)^2 = π/4\n# π = 4*P(point inside circle)\n\n\nimport numpy as np\n\n\ndef monte_carlo():\n    radius = 1\n\n    insidePoints = 0\n    totalPoints = 0\n\n    accuracy = 1e-7\n    lastP = 0\n    while True:\n        point = np.random.rand(2)\n        if point[0]**2 + point[1]**2 < radius:\n            insidePoints += 1\n        totalPoints += 1\n\n        newP = insidePoints/totalPoints\n        if lastP != newP:\n            if abs(lastP - newP) < accuracy:\n                return 4 * newP\n        lastP = newP\n    \n\n# Driver code:\nresult = monte_carlo()\nprint(\"{0:0.2f}\".format(result))", "meta": {"hexsha": "bb0eb69af120184ff701df2ac80751c01b3a2d59", "size": 770, "ext": "py", "lang": "Python", "max_stars_repo_path": "P14_monte_carlo.py", "max_stars_repo_name": "bdemin/daily-coding-problem", "max_stars_repo_head_hexsha": "f364df4c41dd31b376ff92d599208356375566e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "P14_monte_carlo.py", "max_issues_repo_name": "bdemin/daily-coding-problem", "max_issues_repo_head_hexsha": "f364df4c41dd31b376ff92d599208356375566e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P14_monte_carlo.py", "max_forks_repo_name": "bdemin/daily-coding-problem", "max_forks_repo_head_hexsha": "f364df4c41dd31b376ff92d599208356375566e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3888888889, "max_line_length": 60, "alphanum_fraction": 0.5714285714, "include": true, "reason": "import numpy", "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138183570425, "lm_q2_score": 0.8705972684083609, "lm_q1q2_score": 0.8511949795467496}}
{"text": "from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef plot_series(time, series, format=\"-\", start=0, end=None, label=None):\n    plt.plot(time[start:end], series[start:end], format, label=label)\n    plt.xlabel(\"Time\")\n    plt.ylabel(\"Value\")\n    if label:\n        plt.legend(fontsize=14)\n    plt.grid(True)\n\ndef trend(time, slope=0):\n    return slope * time\n\ntime = np.arange(4 * 365 + 1)\nbaseline = 10\nseries = baseline + trend(time, 0.1)\n\nplt.figure(figsize=(10, 6))\nplot_series(time, series)\nplt.show()\n\nprint(time)\nprint(series)\n\n#generate time series with seasonal patterns\ndef seasonal_pattern(season_time):\n\t#arbitrary pattern\n    return np.where(season_time < 0.4,\n                    np.cos(season_time * 2 * np.pi),\n                    1 / np.exp(3 * season_time))\n\ndef seasonality(time, period, amplitude=1, phase=0):\n    \"\"\"Repeats the same pattern at each period\"\"\"\n    season_time = ((time + phase) % period) / period\n    return amplitude * seasonal_pattern(season_time)\n\namplitude = 40\nseries = seasonality(time, period=365, amplitude=amplitude)\n\nplt.figure(figsize=(10, 6))\nplot_series(time, series)\nplt.show()\n\n#time series with both trend and seasonal patterns\nslope = 0.05\nseries = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude)\n\nplt.figure(figsize=(10, 6))\nplot_series(time, series)\nplt.show()\n\ndef white_noise(time, noise_level=1, seed=None):\n    rnd = np.random.RandomState(seed)\n    return rnd.randn(len(time)) * noise_level\n\nnoise_level = 5\nnoise = white_noise(time, noise_level, seed=42)\n\nplt.figure(figsize=(10, 6))\nplot_series(time, noise)\nplt.show()\n\n#add white noise to the time series\nseries += noise\n\nplt.figure(figsize=(10, 6))\nplot_series(time, series)\nplt.show()", "meta": {"hexsha": "f86f8ed8ffaaad67119fc5f79cf4f9fa24ded460", "size": 1817, "ext": "py", "lang": "Python", "max_stars_repo_path": "Time Series Forecasting/commonPatternsTimeSeries.py", "max_stars_repo_name": "rdan22/Udacity_TensorFlow_for_Deep-Learning", "max_stars_repo_head_hexsha": "aaf076c201aba83ef7db89716e211e25ca1d9f9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Time Series Forecasting/commonPatternsTimeSeries.py", "max_issues_repo_name": "rdan22/Udacity_TensorFlow_for_Deep-Learning", "max_issues_repo_head_hexsha": "aaf076c201aba83ef7db89716e211e25ca1d9f9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Time Series Forecasting/commonPatternsTimeSeries.py", "max_forks_repo_name": "rdan22/Udacity_TensorFlow_for_Deep-Learning", "max_forks_repo_head_hexsha": "aaf076c201aba83ef7db89716e211e25ca1d9f9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5915492958, "max_line_length": 91, "alphanum_fraction": 0.7033571822, "include": true, "reason": "import numpy", "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.9073122169746364, "lm_q1q2_score": 0.8511713854686306}}
{"text": "import numpy as np\nimport pdb\nfrom scipy import linalg as splinalg\n# A = np.array([\n    # [1, 1, -2, 1, 3, -1],\n    # [2, -1, 1, 2, 1, -3],\n    # [1, 3, -3, -1, 2, 1],\n    # [5, 2, -1, -1, 2, 1],\n    # [-3, -1, 2, 3, 1, 3],\n    # [4, 3, 1, -6, -3, -2]\n# ], dtype=float)\n# b = np.array([4, 20, -15, -3, 16, -27], dtype=float)\n\nA = np.array([\n[8,4,4],\n[2,-4,1],\n[2,-1,3]\n], dtype = float)\nb = np.array([\n80, 7, 22\n], dtype=float)\n\n# A = np.array([\n# [3,-0.1,-0.2],\n# [0.1,7,-0.3],\n# [0.3,-0.2,10]\n# ], dtype = float)\n# b = np.array([\n# 7.85, -19.3, 71.4\n# ], dtype=float)\n\n\n\n# Simplest version\ndef gauss1(A, b):\n    assert A.shape[0] == len(b), \"A and b must have the same length\"\n    dim = A.shape[0]\n    x = np.zeros(dim)\n    # Elimination\n    for i in range(dim - 1):\n        for j in range(i + 1, dim):\n            c = A[j, i] / A[i, i]\n            A[j, :] -= (c * A[i, :])\n            b[j] -= (c * b[i])\n    # Substitution\n    x[-1] = b[-1] / A[-1, -1]\n    for i in range(dim - 2, -1, -1):\n        sum = b[i]\n        for j in range(dim - 1, i - 1, -1):\n            sum -= x[j] * A[i, j]\n        x[i] = sum / A[i, i]\n    return x\n\n\ndef gauss(A, b, tol, err):\n    assert A.shape[0] == len(b), \"A and b must have the same length\"\n    dim = A.shape[0]\n    x = np.zeros(dim)\n    pv = np.arange(0, dim, 1)\n    err = 0\n    # Eliminate everything but the last row (dim-1)\n    for i in range(dim - 1):\n        # Store the current pivot from the pivot list\n        pvt = pv[i]\n        # Store the value of the current pivot\n        pvv = A[pvt, i]\n        # Search the other row specified in the pivot list\n        for k in pv:\n            # Check if the other rows have larger pivot values\n            val = A[k, i]\n            # print(\"val ({0}) > pvv({1})\".format(val, pvv))\n            if val > pvv:\n                # We found a larger row, store the value  and so we can check the others\n                pvv = val\n                pvt = k\n        # Did we find a new pivot that is in a row below us?\n        if pvt > pv[i]:\n            # If we did switch the indices in the pivot list\n            #print(\"We switched row {0} with pivot {1} for row {2} with pivot {3}\".format(pv[i], A[pv[i], i], pvt, A[pvt,i]))\n            tmp = pv[i]\n            pv[i] = pvt\n            pv[pvt] = tmp\n        # print(pv)\n        # Check if the current pivot is close to 0\n        # if it is, break and set the error flag\n        if np.abs(A[pv[i], i]) < tol:\n            err = -1\n            break\n        # Here we actually perform the actual elimination\n        for j in range(i + 1, dim):\n            # print(\"c = {0}/{1}\".format(A[pv[j], i], A[pv[i], i]))\n            c = A[pv[j], i] / A[pv[i], i]\n            # print(A[pv[j], i:])\n            # print((c * A[pv[i], i:]))\n            A[pv[j], i:] -= (c * A[pv[i], i:])\n            # print(A[pv[j], :])\n            b[pv[j]] -= (c * b[pv[i]])\n    # print(A)\n    #print(b)\n    # Quit here is the system is singular\n    if err == -1:\n        return x\n    # Now we begin back substitution by calculating the last x value\n    x[-1] = b[pv[-1]] / A[pv[-1], -1]\n    # Now we solve the remaining equations\n    # dim-2 starts means we begin at second row from the end and go until the 0th row\n    for i in range(dim - 2, -1, -1):\n        # Grab the corresponding b value\n        sum = b[pv[i]]\n        # Now we sum from the last column (dim -1 ) to the current column (i-1)\n        for j in range(dim - 1, i - 1, -1):\n            sum -= x[j] * A[pv[i], j]\n        x[i] = sum / A[pv[i], i]\n    return x\n\ndef lu_factor(A, tol, err):\n    \"\"\"Returns the matrix A with the LU matrices and a pivot vector containing information on how the matrix was eliminated.\n    Passing these values to to lu_solve with a b vector will solve the equation\"\"\"\n    dim = A.shape[0]\n    pv = np.arange(0, dim, 1)\n    err = 0\n    # Eliminate everything but the last row (dim-1)\n    for i in range(dim - 1):\n        # Store the current pivot from the pivot list\n        pvt = pv[i]\n        # Store the value of the current pivot\n        pvv = A[pvt, i]\n        # Search the other row specified in the pivot list\n        for k in pv:\n            # Check if the other rows have larger pivot values\n            val = A[k, i]\n            # print(\"val ({0}) > pvv({1})\".format(val, pvv))\n            if val > pvv:\n                # We found a larger row, store the value  and so we can check the others\n                pvv = val\n                pvt = k\n        # Did we find a new pivot?\n        if pvt > pv[i]:\n            # If we did switch the indices in the pivot list\n            # print(\"We switched row {0} with pivot {1} for row {2} with pivot {3}\".format(pv[i], A[pv[i], i], pvt, A[pvt,i]))\n            tmp = pv[i]\n            pv[i] = pvt\n            pv[pvt] = tmp\n        # print(pv)\n        # Check if the current pivot is close to 0\n        # if it is, break and set the error flag\n        if np.abs(A[pv[i], i]) < tol:\n            err = -1\n            break\n        # Here we actually perform the actual elimination\n        for j in range(i + 1, dim):\n            # print(\"c = {0}/{1}\".format(A[pv[j], i], A[pv[i], i]))\n            c = A[pv[j], i] / A[pv[i], i]\n            # print(A[pv[j], i:])\n            # print((c * A[pv[i], i:]))\n            A[pv[j], i:] -= (c * A[pv[i], i:])\n            # print(A[pv[j], :])\n            #print(\"Replacing index {0},{1} with value {2} with {3}\".format(pv[j], i, A[pv[j], i], c))\n            A[pv[j], i] = c\n    # print(A)\n    # Quit here if the system is singular\n    if err == -1:\n        return None\n    else:\n        return (A, pv)\n\ndef lu_solve(A, pv, b):\n    \"\"\" Solves the system Ax=b given the output from lu_factor\"\"\"\n    dim = A.shape[0]\n    x = np.zeros(dim)\n    for i in range(dim - 1):\n        for j in range(i + 1, dim):\n            #All of our c's are stored in A from the output of LU factor\n            c = A[pv[j], i]\n            #Calculate the b vector that would result from the typical elimination procedure\n            b[pv[j]] -= (c * b[pv[i]])\n    #print(d)\n    x[-1] = b[pv[-1]] / A[pv[-1], -1]\n    # Now we solve the remaining equations, this is the same as Gaussian back substitution\n    # dim-2 starts means we begin at second row from the end and go until the 0th row\n    for i in range(dim - 2, -1, -1):\n        # Grab the corresponding b value\n        sum = b[pv[i]]\n        # Now we sum from the last column (dim -1 ) to the current column (i-1)\n        for j in range(dim - 1, i - 1, -1):\n            sum -= x[j] * A[pv[i], j]\n        x[i] = sum / A[pv[i], i]\n    return x\n    \ndef inv(A, tol, err):\n    \"\"\"We always assume square matrices\"\"\"\n    dim = A.shape[0]\n    A1 = np.zeros(A.shape)\n    A, pvt = lu_factor(A, tol, err)\n    if err == -1:\n        return None\n    for i in range(dim):\n        b = np.zeros(dim)\n        b[i] = 1\n        x = lu_solve(A, pvt, b)\n        A1[:, i] = np.copy(x)\n    return A1\n    \ndef gauss_seidel(A, b, x, tol, maxi, lam):\n    \"\"\" x should contain initial guesses (can be 0)\"\"\"\n    dim = A.shape[0]\n    #Divide everything by each row by its diagnol element\n    for i in range(dim):\n        tmp = A[i,i]\n        for j in range(dim):\n            A[i,j] /= tmp\n        b[i] /= tmp\n        # print(A)\n    for i in range(dim):\n        acc = b[i]\n        for j in range(dim):\n            if i == j:\n                # print(\"Skipping i = {0} and j = {1}\".format(i, j))\n                continue\n            else:\n                acc -= A[i, j] * x[j]\n        # print(\"Old x = {0}, new x = {1}\".format(x[i], acc))\n        x[i] = acc\n    for i in range(maxi):\n        flag = 1\n        for k in range(dim):    \n            acc = b[k]\n            oldx = x[k]\n            for j in range(dim):\n                if k == j:\n                    continue\n                else:\n                    # print('k = {0}, j={1}'.format(k, j))\n                    acc -= (A[k,j] * x[j])\n                    # print(acc)\n            # print(\"Old x = {0}, new x = {1}\".format(oldx, (lam * acc) + ((1-lam) * oldx)))\n            x[k] = (lam * acc) + ((1-lam) * oldx)\n            if flag ==1 and x[k] != 0:\n                ea = abs((x[k] - oldx)/x[k]) * 100\n                # print(\"Error is equal to {0}\".format(ea))\n                if ea > tol:\n                    flag = 0\n        if flag == 1:\n            print('Breaking with ea = {0} and num iterations: {1}'.format(ea, i))\n            break\n    return x\n    \ne = 0\nx2 = gauss(np.copy(A), np.copy(b), 0.001, e)\naa, pv = lu_factor(np.copy(A), 0.001, e)\nx1 = lu_solve(aa, pv, np.copy(b))\nprint(np.dot(A,x2))\nprint(np.dot(A,x1))\nx3 = gauss_seidel(np.copy(A), np.copy(b), np.zeros(A.shape[0]), 0.0001, 25, 1.03)\nprint(np.dot(A,x3))\n", "meta": {"hexsha": "b3e9c1521e206e7e0c80e9ab8658db29becbbf4c", "size": 8666, "ext": "py", "lang": "Python", "max_stars_repo_path": "linearalg/linalg.py", "max_stars_repo_name": "Seek/LaTechNumeric", "max_stars_repo_head_hexsha": "dabef2040e84bf25cabab07fe20a6434ce52197b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linearalg/linalg.py", "max_issues_repo_name": "Seek/LaTechNumeric", "max_issues_repo_head_hexsha": "dabef2040e84bf25cabab07fe20a6434ce52197b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linearalg/linalg.py", "max_forks_repo_name": "Seek/LaTechNumeric", "max_forks_repo_head_hexsha": "dabef2040e84bf25cabab07fe20a6434ce52197b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8515625, "max_line_length": 126, "alphanum_fraction": 0.4759981537, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.9073122169746364, "lm_q1q2_score": 0.8511713823294289}}
{"text": "import sympy as sp\nfrom sympy import Float, Basic, Symbol\n\n\nclass Calculator:\n    def __init__(self, float_length: int, tnp: float):\n        self.float_length = float_length\n        self.tnp = tnp\n\n    def calculate_formula(self, expr: Basic, avg_values: dict[Symbol, Float]) -> Float:\n        \"\"\"Calculates expression with given values.\"\"\"\n        return expr.evalf(self.float_length, subs=avg_values)\n\n    def calculate_avg(self, values: list[Float]) -> Float:\n        \"\"\"Calculates average value for given list of values.\"\"\"\n        return Float(sum(values) / len(values))\n\n    def calculate_sigma(self, values: list[Float], avg_value: Float) -> Float:\n        \"\"\"\n        Calculates sigma coefficient for calculation of measurement error.\n        Fromula:\n            σ = (∑ (xᵢ - <x>)²) / (n * (n-1))\n        \"\"\"\n        n = len(values)\n        return sp.sqrt(sum([(x - avg_value) ** 2 for x in values]) / (n * (n - 1)))\n\n    def calculate_error_for_variable(\n        self, measurements: list[Float], avg_value: Float\n    ) -> Float:\n        \"\"\"\n        Calculates measurements error for given values.\n        Formula:\n            ΔX = σ * tnp\n        \"\"\"\n        return self.calculate_sigma(measurements, avg_value) * self.tnp\n\n    def calculate_result_error(\n        self,\n        expr: Basic,\n        errors: dict[Symbol, Float],\n        avg_values: dict[Symbol, Float],\n        vars: list[Symbol],\n    ) -> Float:\n        \"\"\"\n        Calculates indirect error for given formula and values.\n        Formula:\n            ∆f = √∑(∂f/∂yᵢ * ∆yᵢ)²\n        \"\"\"\n        res_error = 0\n        for var in vars:\n            deriv = expr.diff(var).evalf(self.float_length, subs=avg_values)\n            res_error += (deriv * errors[var]) ** 2\n        res_error = sp.sqrt(res_error)\n        return res_error\n", "meta": {"hexsha": "53e487671cc4b4184059b07c4d5737feb7ae1200", "size": 1803, "ext": "py", "lang": "Python", "max_stars_repo_path": "calculations/calculator.py", "max_stars_repo_name": "sxccxs/Indirect-measurements-error-calculator", "max_stars_repo_head_hexsha": "83efedea66104813eb8b9147c79891be9b55459a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-27T11:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T11:55:35.000Z", "max_issues_repo_path": "calculations/calculator.py", "max_issues_repo_name": "sxccxs/IMEC", "max_issues_repo_head_hexsha": "83efedea66104813eb8b9147c79891be9b55459a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calculations/calculator.py", "max_forks_repo_name": "sxccxs/IMEC", "max_forks_repo_head_hexsha": "83efedea66104813eb8b9147c79891be9b55459a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7818181818, "max_line_length": 87, "alphanum_fraction": 0.5840266223, "include": true, "reason": "import sympy,from sympy", "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9796676496254957, "lm_q2_score": 0.8688267847293731, "lm_q1q2_score": 0.8511614941275015}}
{"text": "#!/usr/bin/python\n\nimport numpy as np \nimport matplotlib.pyplot as plt\nfrom math import *\n\n## Various Helper Function to Calculate Error\ndef list_diff(l1, l2):\n    '''\n    Returns l1 - l2. [1, 2, 3] - [3, 4, 5] = [-2, -2, -2]\n    '''\n    return [l1[i] - l2[i] for i in xrange(len(l1))] \n\ndef list_norm(l):\n    s = 0.0\n    for a in l:\n        s+= a**2\n    return sqrt(s)\n\n## Tri Diagonal Matrix Algorithm(a.k.a Thomas algorithm) solver\ndef TDMA(a, b, c, d):\n    '''\n    TDMA solver, a b c d can be NumPy array type or Python list type.\n    refer to http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm\n    '''\n    nf = len(a)     # number of equations\n    ac, bc, cc, dc = map(np.array, (a, b, c, d))     # copy the array\n    for it in xrange(1, nf):\n        mc = ac[it]/bc[it-1]\n        bc[it] = bc[it] - mc*cc[it-1] \n        dc[it] = dc[it] - mc*dc[it-1]\n \n    xc = ac\n    xc[-1] = dc[-1]/bc[-1]\n \n    for il in xrange(nf-2, -1, -1):\n        xc[il] = (dc[il]-cc[il]*xc[il+1])/bc[il]\n \n    del bc, cc, dc  # delete variables from memory\n    return xc \n\n'''\n# Example:\nM = [[1,2,0,0],\n     [5,3,2,0],\n     [0,9,3,5],\n     [0,0,3,5]]\n\na = [0.0, 5.0, 9.0, 3.0]\nc = [2.0, 2.0, 5.0, 0.0]\nb = [1.0, 3.0, 3.0, 5.0]\nf = [1.0, 2.0, 3.0, 4.0]\n\nx = TDMA(a, b, c, f)\nprint x\n'''\n\n# Start\n# y'' - 2y'-y = -2xe^x, 0 <= x <= 1, y'(0)-y(0)=1, y(1)=e(2cosh(sqrt(2)+1)\nN = 50000\na = 0.0\nb = 1.0\nh = (b-a)/float(N)\nyb = e*(2.0*cosh(sqrt(2.0)) + 1.0) # Left side type (fixed on right)\nX = [a+i*h for i in xrange(N+1)]\n\n# Ideal solution (got from Wolfram)\ndef _f(x):\n    return exp(-sqrt(2.0)*x)*(x*exp(x*(1.0+sqrt(2.0)))+exp(x)+exp(2.0*sqrt(2.0)*x+x)) \n\nprint (\"N = \"+str(N)+\"; solving on (\"+str(a)+\", \"+str(b)+\"); h = \"+str(h))\n\n# y'' + py' + qy = f\ndef q(x):\n    return -1.0\n\ndef p(x):\n    return -2.0\n\ndef f(x):\n    return -2.0*x*exp(x)\n\nb = [-2.0+h**2*q(X[i]) for i in range(1, N, 1)]\nc = [1.0+p(X[i])*h/2.0 for i in range(1, N-1, 1)]\na = [1.0-p(X[i])*h/2.0 for i in range(2, N, 1)]\nf = [h**2*f(X[i]) for i in range(1, N, 1)]\n#f[0] = f[0] - (1.0-p(X[1])*h/2.0)*ya # Uncomment if have left value\nf[N-2] = f[N-2] - (1.0+p(X[N-1])*h/2.0)*yb # Uncomment if have right value\n\n# Right side\n#a += []\n#b += []\n#c += []\n#f += []\n\n# Left side\n# y'(0)-y(0)=1 --> (Y[1]-Y[0])/h-Y[0]=1\na = [1.0-p(X[1])*h/2.0] + a\nb = [-(1+1/h)] + b\nc = [1/h] + c\nf = [1.0] + f\n\n# Bring a, b, c and f to the same size\na = [0.0] + a\nc += [0.0]\n\n# Calculate/plot ideal and approximated functions\nY = TDMA(a, b, c, f).tolist() + [yb]\nY_ = [_f(x) for x in X]\n#print \"y  =\", Y\n#print \"y_ =\", Y_\nprint \"Error: \", list_norm(list_diff(Y, Y_))\n\nplt.plot(X, Y, 'ro')\nplt.plot(X, Y_, 'g')\nplt.show()\n", "meta": {"hexsha": "d8f31b40faf0f6458e8ca165d23e53ba7c357138", "size": 2648, "ext": "py", "lang": "Python", "max_stars_repo_path": "CompMath/task_1/task_1.py", "max_stars_repo_name": "ncos/hometasks", "max_stars_repo_head_hexsha": "9504ef7ed8fe30b5bc78ca1e423a2b85e46734a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-02-19T21:21:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-30T19:49:01.000Z", "max_issues_repo_path": "CompMath/task_1/task_1.py", "max_issues_repo_name": "ncos/hometasks", "max_issues_repo_head_hexsha": "9504ef7ed8fe30b5bc78ca1e423a2b85e46734a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CompMath/task_1/task_1.py", "max_forks_repo_name": "ncos/hometasks", "max_forks_repo_head_hexsha": "9504ef7ed8fe30b5bc78ca1e423a2b85e46734a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6324786325, "max_line_length": 86, "alphanum_fraction": 0.5052870091, "include": true, "reason": "import numpy", "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545392102522, "lm_q2_score": 0.8976952914230971, "lm_q1q2_score": 0.8511538653904797}}
{"text": "import numpy as np\nfrom typing import Callable, List, Union\nFunction = Callable[[float], float]\nVector_int = List[int]\nfrom .constants import golden, igolden\n\n\ndef fibonacci(n: int, list: bool = False, start_points: Vector_int = None) -> int:\n    \"\"\"\n    Fibonacci Numbers\n    =================\n    In mathematics, the Fibonacci numbers, commonly denoted Fn,\n    form a sequence, the Fibonacci sequence, in which each number\n    is the sum of the two preceding ones.\n\n    Parameters\n    ----------\n    n : int\n        nth element of the Fibonacci sequence\n    list : bool, optional\n        Shows the whole sequence until nth number, by default False\n    start_points : Vector_int, optional\n        Initial numbers of the sequence, by default [0, 1]\n\n    Returns\n    -------\n    int\n        nth element of the Fibonacci sequence\n    \"\"\"    \"\"\"\"\"\"\n    if start_points is None: start_points = [0, 1]\n    f0, f1 = start_points\n\n    if list:\n        if n == 0: return [f0]\n        if n == 1: return [f0, f1]\n\n        F = start_points.copy()\n        if n > 0:\n            for i in range(1, n):\n                F.append(F[i] + F[i-1])\n        else:\n            for _ in range(-n):\n                F.insert(0, F[1] - F[0])\n\n        return F\n    else:\n        if n == 0: return f0\n        if n == 1: return f1\n\n        if n > 0:\n            for i in range(n-1):\n                f1, f0 = f1 + f0, f1\n            return f1\n        else:\n            for i in range(-n):\n                f0, f1 = f1 - f0, f0\n            return f0\n            # Another way:\n            #return (-1)**(n+1) * fibonacci(-n)\n            \ndef binet(n: float):\n    return (golden**n - igolden**n)/np.sqrt(5)\n\ndef factorial(n: Union[int, Vector_int]) -> Union[int, Vector_int]:\n    \"\"\"\n    Factorial\n    =========\n    Returns the factorial of an integer `n! -> n*(n-1)*...*1`\n\n    Parameters\n    ----------\n    n: int, Vector_int\n        The number, or list of numbers to perform the factorial\n\n\n    Returns\n    -------\n    int, Vector_int\n        Factorial\n    \"\"\"\n    if isinstance(n, int):\n        result = 1\n        for i in range(2, n+1):\n            result *= i\n        return result\n    else:\n        if type(n) is np.ndarray: n = list(n)    \n\n        result = [1 for e in n]\n        for i, e in enumerate(n):\n            for j in range(2, e+1):\n                result[i] *= j\n  \n        return np.asarray(result)\n\ndef combination(n: int, k: Union[int, Vector_int]) -> Union[int, Vector_int]:\n    \"\"\"\n    Combination\n    ===========\n    Returns the number of combinations for a set of n items in k selected items\n\n    Parameters\n    ----------\n    n: int\n        total number of items\n    k: int, Vector_int\n        selected number of items\n\n    Returns\n    -------\n    int, Vector_int\n        number of combinations\n    \"\"\"\n    if isinstance(k, list) or type(k) == np.ndarray:\n        return np.array([combination(n,i) for i in k])\n    else:\n        if isinstance(k, int):\n            return int(factorial(n) / (factorial(k)*factorial(n-k)))\n        else:\n            raise ValueError('k must be integer')\n\n\ndef derivative(f: Function ,a: float, order: int=1, method: str='central', h: float=0.01):\n    '''\n    Derivative\n    ========\n    Compute the difference formula for `f'(a)` with step size `h`.\n\n    Parameters\n    ----------\n    f : Function\n        Vectorized function of one variable, MUST accept arrays as input\n    a : float\n        Compute derivative at `x = a`\n    method : string\n        Difference formula: (order=1) \n            central: `f(a+h) - f(a-h))/2h`\n            forward: `f(a+h) - f(a))/h`\n            backward: `f(a) - f(a-h))/h`\n\n            by default 'central'\n        Information about higher order https://en.wikipedia.org/wiki/Finite_difference\n\n    h : float\n        Step size in difference formula,\n        by default 0.01\n    \n    order: int\n        Order of the derivative\n\n    Returns\n    -------\n    float\n        `f'(a)`      \n    '''\n    i = np.arange(order+1)\n    if method == 'central':\n        return 1/h**order * np.sum((-1)**i * combination(order, i) * f(a + (order/2 - i)*h))\n\n    elif method == 'forward':\n        return  1/h**order * np.sum((-1)**(order - i) * combination(order, i) * f(a + i*h))\n\n    elif method == 'backward':\n        return 1/h**order * np.sum((-1)**i * combination(order, i) * f(a - i*h))\n\n    else:\n        raise ValueError(\"Method must be 'central', 'forward' or 'backward'.\")\n\n\n#---------------Find Root---------------#\n\n\ndef newton(f: Function, x: float, tol: float, iter: bool = False) -> float:\n    \"\"\"\n    Newton\n    ======\n    Newton method to find a root of a function\n\n    Parameters\n    ----------\n    f : Function\n        Function\n    x : float\n        Start point\n    tol : float\n        Error tolerance\n    iter : bool, optional\n        Shows the iterations needed to find the solution,\n        by default False\n\n    Returns\n    -------\n    float\n        The root\n    int, optional\n        Number of iterations\n    \n    Examples\n    --------\n    >>> def f(x): return x**3 + 2*x**2 + 10*x - 20\n    >>> newton(f, 1, 0.01, True)\n    (1.3688081886175318, 3)\n\n\n    \"\"\"\n    n = 0\n    while abs(f(x)) > tol:\n        x = x - f(x) / derivative(f, x, h=1e-5)\n        n += 1\n\n    if iter:\n        return x, n\n    return x\n\ndef bisection(f: Function, xi: float, xf: float, tol: float, iter: bool = False) -> float:\n    \"\"\"\n    Bisection\n    =========\n    Bisection method to find a root of a function\n\n    Parameters\n    ----------\n    f : Function\n        Function\n    xi : float\n        First point\n    xf : float\n        Second point\n    tol : float\n        Error tolerance\n    iter : bool, optional\n        Shows the iterations needed to find the solution,\n        by default False\n\n    Returns\n    -------\n    float\n        The root\n    int, optional\n        Number of iterations\n    \n    Examples\n    --------\n    >>> def f(x): return x**3 + 2*x**2 + 10*x - 20\n    >>> bisection(f, 1, 2, 0.01, True)\n    (1.369140625, 9)\n\n    \"\"\"\n    if f(xi) * f(xf) < 0:\n        xm, n = (xi + xf) / 2, 1\n\n        while abs(f(xm)) > tol:\n            if f(xi) * f(xm) < 0:\n                xf = xm \n                n += 1\n            \n            elif f(xm) * f(xf) < 0:\n                xi = xm \n                n += 1\n            \n            xm = (xi + xf) / 2\n            \n        if iter:\n            return xm, n\n        return xm\n\n    else:\n        print(\"Invalid input\")\n\ndef regula_falsi(f: Function, xi: float, xf: float, tol: float, iter: bool = False) -> float:\n    \"\"\"\n    Regula Falsi\n    ============\n    Regula falsi method to find a root of a function\n    \n\n    Parameters\n    ----------\n    f : Function\n        Function\n    xi : float\n        First point\n    xf : float\n        Second point\n    tol : float\n        Error tolerance\n    iter : bool, optional\n        Shows the iterations needed to find the solution,\n        by default False\n\n    Returns\n    -------\n    float\n        The root\n    int, optional\n        Number of iterations\n    \n    Examples\n    --------\n    >>> def f(x): return x**3 + 2*x**2 + 10*x - 20\n    >>> regula_falsi(f, 1, 2, 0.01, True)\n    (1.3685009755999702, 4)\n\n    \"\"\"\n    if f(xi) * f(xf) < 0:\n        xm, n = (xi * f(xf) - xf * f(xi)) / (f(xf) - f(xi)), 1\n\n        while abs(f(xm)) > tol:\n            if f(xi) * f(xm) < 0:\n                xf = xm\n                n += 1\n\n            if f(xm) * f(xf) < 0:\n                xi = xm\n                n += 1\n            \n            xm = (xi * f(xf) - xf * f(xi)) / (f(xf) - f(xi))\n\n        if iter:\n            return xm, n\n        return xm\n    else:\n        print(\"Invalid input\")\n\n\ndef secant(f: Function, x0: float, x1: float, tol: float, iter: bool = False) -> float:\n    \"\"\"\n    Secant\n    ======\n\n    Secant method to find a root of a function\n\n    Parameters\n    ----------\n    f : Function\n        Function\n    x0 : float\n        First point\n    x1 : float\n        Second point\n    tol : float\n        Error tolerance\n    iter : bool, optional\n        Shows the iterations needed to find the solution,\n        by default False\n\n    Returns\n    -------\n    float\n        The root\n    int, optional\n        Number of iterations\n    \n    Examples\n    --------\n    >>> def f(x): return x**3 + 2*x**2 + 10*x - 20\n    >>> secant(f, 1, 2, 0.01, True)\n    (1.369013325992566, 3)\n\n    \"\"\"\n    x2, n = x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0)), 1\n\n    while abs(f(x2)) > tol:\n        x0, x1 = x1, x2\n        x2 = x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))\n        n += 1\n        \n    if iter:\n        return x2, n\n    return x2\n\n\n\n\"\"\" def fixed_point(g, dg, x, tol, iter = False):\n  ''' f(x) = 0 ==> x = g(x) '''\n  n = 1\n  if abs(dg(x))<1:\n    xa = x\n    x = g(x)\n    \n    while abs(x-xa)>tol:\n      xa = x\n      x = g(x)\n      n = n+1\n    if iter: return x, n\n    return x\n  else:\n    print(\"Doesn't converge\")  \"\"\"\n\n\ndef newton2(f: Function, x: float, tol: float, iter: bool = False) -> float:\n    \"\"\"\n    Newton 2nd order\n    ================\n\n    Newton second order method to find a root of a function\n\n    Parameters\n    ----------\n    f : Function\n        Function\n    x : float\n        Start point\n    tol : float\n        Error tolerance\n    iter : bool, optional\n        Shows the iterations needed to find the solution,\n        by default False\n\n    Returns\n    -------\n    float\n        The root\n    int, optional\n        Number of iterations\n    \n    Examples\n    --------\n    >>> def f(x): return x**3 + 2*x**2 + 10*x - 20\n    >>> newton2(f, 1, 0.01, True)\n    (1.3688081071467233, 2)\n\n    \"\"\"\n    n = 0\n\n    while abs(f(x)) > tol:\n        fx, dfx, ddfx = f(x), derivative(f, x), derivative(f, x, 2)\n\n        x1 = x - dfx / ddfx + np.sqrt(dfx**2 - 2*ddfx * fx) / ddfx\n        x2 = x - dfx / ddfx - np.sqrt(dfx**2 - 2*ddfx * fx) / ddfx\n\n        if abs(f(x1)) < abs(f(x2)):\n            x = x1\n        else:\n            x = x2\n        \n        n += 1\n    \n    if iter:\n        return x, n\n    return x\n", "meta": {"hexsha": "9d7e94b88e18ffb1b7881499ed23019d7e3a21da", "size": 9941, "ext": "py", "lang": "Python", "max_stars_repo_path": "intelligen/numeric.py", "max_stars_repo_name": "Bouchet07/intelligen", "max_stars_repo_head_hexsha": "d876b1241efe7ad70fa759e1f10728728f867992", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "intelligen/numeric.py", "max_issues_repo_name": "Bouchet07/intelligen", "max_issues_repo_head_hexsha": "d876b1241efe7ad70fa759e1f10728728f867992", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intelligen/numeric.py", "max_forks_repo_name": "Bouchet07/intelligen", "max_forks_repo_head_hexsha": "d876b1241efe7ad70fa759e1f10728728f867992", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4909502262, "max_line_length": 93, "alphanum_fraction": 0.4855648325, "include": true, "reason": "import numpy", "num_tokens": 2868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693688269984, "lm_q2_score": 0.896251371055247, "lm_q1q2_score": 0.8511424738603683}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 23 10:00:21 2019\n\n@author: amandaash\n\"\"\"\n\n#step (1) Sample the function x**2 1000 and 1000 times over the interval 0 to 10\n#step (2) sum the samples\n#step (3) multiply sum by b-a/number of samples\n#step (4) viola an integral\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numpy.random as rand\n\ndef x2(x):\n    y = x**2\n    return y\n\ndef sampler(funcn, N, a, b):\n    sample = rand.uniform(a, b, N)\n    funcn_sample = funcn(sample)\n    I = ((b-a)/N)*np.sum(funcn_sample)\n    return I, np.array(sample), np.array(funcn_sample)\n\nI_1000, x_1000, y_1000 = sampler(x2, 1000, 0, 10)\nI_10000, x_10000, y_10000 = sampler(x2, 10000, 0, 10)\n\nprint('1000 samples: I ~ {0}'.format(I_1000))\nprint('10000 samples: I ~ {0}'.format(I_10000))\n\nplt.plot(x_1000, y_1000, '.')\nplt.title('1000 samples')\nplt.savefig('1000_samples.pdf')\nplt.show()\nplt.plot(x_10000, y_10000, '.')\nplt.title('10000 samples')\nplt.savefig('100000 samples.pdf')\nplt.show()\n\nN = 10000\nI_values = []\ny_values = []\ny_std = []\nfor iteration in range(N):\n    I, x, y = sampler(x2, 1000, 0, 10)\n    I_values.append(I)\n    y_values.append(y)\n    y_std.append(np.std(y))\n\ny_values = np.array(y_values).reshape(N*1000)\nprint(np.std(y_values)/np.sqrt(N*1000))\nprint(np.std(y_std)/np.sqrt(N))\n    \nplt.hist(I_values, bins = 25)\nplt.axvline(np.median(I_values), label = 'median I = {0}'.format(str(np.median(I_values))[:7]), color = 'r')\nplt.axvline(np.mean(I_values), label = 'mean I = {0}'.format(str(np.mean(I_values))[:7]), color = 'orange')\nplt.axvline(np.mean(I_values)+np.std(I_values), color = 'purple')\nplt.axvline(np.mean(I_values)-np.std(I_values), color = 'purple')\nplt.title('{0} samples'.format(1000*N))\nplt.legend()\nplt.savefig('sample hist')\nplt.show()\n\nprint(\"{0} samples: I = {1} +/- {2}\".format(N*1000, str(np.mean(I_values))[:7], str(np.std(I_values)/np.sqrt(N*1000))[:5]))\n\n\ndef f1(x):\n    y = np.sin(100*x)\n    return y\nI_sin, x_sin, y_sin = sampler(f1, 10000000, 0, 2*np.pi)\nprint('10000 samples sin(x): I ~ {0}'.format(I_sin))\nplt.plot(x_sin, y_sin, '.')\nplt.show() ", "meta": {"hexsha": "402713ccdf64444399b85567491f7b10cc4ce59e", "size": 2114, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week 06/E11.py", "max_stars_repo_name": "aash7871/PHYS-3210", "max_stars_repo_head_hexsha": "7820e85259b5fbc2845feaa1068ef12afc13db77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week 06/E11.py", "max_issues_repo_name": "aash7871/PHYS-3210", "max_issues_repo_head_hexsha": "7820e85259b5fbc2845feaa1068ef12afc13db77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week 06/E11.py", "max_forks_repo_name": "aash7871/PHYS-3210", "max_forks_repo_head_hexsha": "7820e85259b5fbc2845feaa1068ef12afc13db77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-17T01:58:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T01:58:14.000Z", "avg_line_length": 27.8157894737, "max_line_length": 123, "alphanum_fraction": 0.6589403974, "include": true, "reason": "import numpy", "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693731004241, "lm_q2_score": 0.896251366205709, "lm_q1q2_score": 0.8511424730849743}}
{"text": "# differentiation_matrix.py\n#\n# Daniel R. Reynolds\n# SMU Mathematics\n# Math 4315\n\ndef differentiation_matrix(n, a, b, order, deriv):\n    \"\"\"\n    Usage: x, D = differentiation_matrix(n, a, b, order, deriv)\n\n    Utility to compute differentiation matrix of specified order\n    of accuracy and derivative order, over an interval [a,b].\n\n    Inputs:  n = number of intervals to use\n             a,b = interval to discretize\n             order = differentiation matrix type:\n                      0 = Chebyshev [spectral convergence]\n                      1 = O(h) finite-difference over regular mesh\n                      2 = O(h^2) finite-difference over regular mesh\n             deriv = derivative order {1,2}\n    Outputs: x = column vector containing partition of [a,b]\n             D = differentiation matrix\n    \"\"\"\n\n    # imports\n    import numpy\n\n    # check for a sufficient number of intervals\n    if (n < 2):\n        raise ValueError(\"insufficient number of intervals\")\n\n    # ensure that n, order and deriv are integers\n    n = int(n)\n    order = int(order)\n    deriv = int(deriv)\n\n    # check for valid order\n    if ((order < 0) or (order > 2)):\n        raise ValueError(\"invalid order selected\")\n\n    # construct matrix based on desired differentiation order\n\n    if (order == 0):  # Chebyshev [based off of 'diffcheb' function 10.2.2 from the book]\n\n        # set Chebyshev nodes in [-1,1]\n        x = -numpy.cos( numpy.linspace(0,n,n+1)*numpy.pi/n )\n\n        # create base differentiation matrix\n        Dbase = numpy.zeros((n+1,n+1), dtype=float)\n        c = numpy.ones((n+1), dtype=float)\n        c[0] = 2\n        c[-1] = 2\n        i = numpy.linspace(0,n,n+1,dtype=int)\n        for j in range(n+1):\n            num = c[i]*(-1)**(i+j)\n            den = c[j]*(x - x[j])\n            for k in range(j):\n                Dbase[k,j] = num[k]/den[k]\n            for k in range(j+1,n+1):\n                Dbase[k,j] = num[k]/den[k]\n        Dbase = Dbase - numpy.diag(numpy.sum(Dbase,1))\n\n        # remap to interval [a,b]\n        x = a + (b-a)/2*(x+1)\n        Dbase = (2/(b-a))*Dbase\n\n        # construct output matrix through multiplication\n        D = numpy.copy(Dbase)\n        for i in range(2,deriv+1):\n            D = D @ Dbase\n\n    else:             # finite-difference\n\n        # set uniform nodes and corresponding h\n        x = numpy.linspace(a,b,n+1)\n        h = (b-a)/n\n\n        # first order, first derivative\n        if ((order == 1) and (deriv == 1)):\n\n            D = numpy.diag(numpy.ones(n),1) - numpy.diag(numpy.ones(n+1), 0)\n            D[n,n-1:n+1] = numpy.array([-1, 1])\n            D *= (1/h)\n\n        # second order, first derivative\n        elif ((order == 2) and (deriv == 1)):\n\n            D = 0.5*(numpy.diag(numpy.ones(n),1) - numpy.diag(numpy.ones(n),-1))\n            D[0,0:3] = numpy.array([-1.5, 2.0, -0.5])\n            D[n,n-2:n+1] = numpy.array([0.5, -2.0, 1.5])\n            D *= (1/h)\n\n        # second order, second derivative\n        elif ((order == 2) and (deriv == 2)):\n\n            D = numpy.diag(numpy.ones(n),1) + numpy.diag(numpy.ones(n),-1) - 2*numpy.diag(numpy.ones(n+1),0)\n            D[0,0:4] = numpy.array([2.0, -5.0, 4.0, -1.0])\n            D[n,n-3:n+1] = numpy.array([-1.0, 4.0, -5.0, 2.0])\n            D *= (1/h/h)\n\n        # all other choices are not implemented\n        else:\n            raise ValueError(\"invalid order/deriv selection for finite-difference matrix\")\n\n    return [x, D]\n\n\n# end of file\n", "meta": {"hexsha": "4f881e5ce062b2ce0ca0658309b43716e40b1809", "size": 3458, "ext": "py", "lang": "Python", "max_stars_repo_path": "BoundaryValue/differentiation_matrix.py", "max_stars_repo_name": "drreynolds/Math4315-codes", "max_stars_repo_head_hexsha": "b8be1c1254417a96d3bc23e48444731a75ed0d3b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-26T19:13:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T05:43:59.000Z", "max_issues_repo_path": "BoundaryValue/differentiation_matrix.py", "max_issues_repo_name": "drreynolds/Math4315-codes", "max_issues_repo_head_hexsha": "b8be1c1254417a96d3bc23e48444731a75ed0d3b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BoundaryValue/differentiation_matrix.py", "max_forks_repo_name": "drreynolds/Math4315-codes", "max_forks_repo_head_hexsha": "b8be1c1254417a96d3bc23e48444731a75ed0d3b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-26T22:12:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-26T22:12:24.000Z", "avg_line_length": 31.7247706422, "max_line_length": 108, "alphanum_fraction": 0.533545402, "include": true, "reason": "import numpy", "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.949669363129097, "lm_q2_score": 0.896251371748038, "lm_q1q2_score": 0.8511424694115388}}
{"text": "import numpy as np\nimport matplotlib\n\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nstyle.use('ggplot')\n\npoints = np.arange(-5, 5, 0.01)\ndx, dy = np.meshgrid(points, points)\nz = (np.sin(dx)+np.sin(dy))\nplt.imshow(z)\nplt.colorbar()\nplt.title('plot for sin(x)+sin(y)')\nplt.show()\n\n\nfrom mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\nX, Y, Z = axes3d.get_test_data(0.05)\nax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)\ncset = ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)\ncset = ax.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)\ncset = ax.contour(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)\n\nax.set_xlabel('X')\nax.set_xlim(-40, 40)\nax.set_ylabel('Y')\nax.set_ylim(-40, 40)\nax.set_zlabel('Z')\nax.set_zlim(-100, 100)\n\nplt.show()\n\n\n\n'''\n======================\n3D surface (color map)\n======================\n\nDemonstrates plotting a 3D surface colored with the coolwarm color map.\nThe surface is made opaque by using antialiased=False.\n\nAlso demonstrates using the LinearLocator and custom formatting for the\nz axis tick labels.\n'''\n\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nimport numpy as np\n\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\n\n# Make data.\nX = np.arange(-5, 5, 0.25)\nY = np.arange(-5, 5, 0.25)\nX, Y = np.meshgrid(X, Y)\nR = np.sqrt(X**2 + Y**2)\nZ = np.sin(R)\n\n# Plot the surface.\nsurf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,\n                       linewidth=0, antialiased=False)\n\n# Customize the z axis.\nax.set_zlim(-1.01, 1.01)\nax.zaxis.set_major_locator(LinearLocator(10))\nax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n\n# Add a color bar which maps values to colors.\nfig.colorbar(surf, shrink=0.5, aspect=5)\n\nplt.show()\n\n", "meta": {"hexsha": "fad262736b0ed8d43771d2d17e096eb8b9917de2", "size": 1946, "ext": "py", "lang": "Python", "max_stars_repo_path": "Machine_Learning_Old_Files/test.py", "max_stars_repo_name": "Ghasak/PracticalMachineLeanring", "max_stars_repo_head_hexsha": "b16095c889be3a14a27e83fe6311581b456cefd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Machine_Learning_Old_Files/test.py", "max_issues_repo_name": "Ghasak/PracticalMachineLeanring", "max_issues_repo_head_hexsha": "b16095c889be3a14a27e83fe6311581b456cefd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:46:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:10:34.000Z", "max_forks_repo_path": "Machine_Learning_Old_Files/test.py", "max_forks_repo_name": "Ghasak/PracticalMachineLeanring", "max_forks_repo_head_hexsha": "b16095c889be3a14a27e83fe6311581b456cefd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1666666667, "max_line_length": 71, "alphanum_fraction": 0.6927029805, "include": true, "reason": "import numpy", "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.899121388082479, "lm_q1q2_score": 0.8511053161283472}}
{"text": "\"\"\"\nSock Drawer\n===============\n\nExcerpted from\n`Fifty Challenging Problems in Probability with Solutions`\nby Frederick Mosteller\n\n\nProblem:\n  A drawer contains red socks and black socks.\n  When two socks are drawn at random, the\n  probability that both are red is 1/2.\n\n    (a) How small can the number of socks in the drawer be?\n\n    (b) How small if the number of black socks is even?\n\nSolution:\n  1. Let's define the probability of drawing red after the first draw as\n\n      .. math:: P(red_1) = \\\\frac{N_{red}}{N_{total}},\n\n      where\n\n      .. math:: N_{total} = N_{red} + N_{black}\n\n\n  2. Let's define the probability of drawing 2 consecutive reds as\n\n      .. math::\n\n        P(red_2|red_1) = P(red_1) *\n          \\\\frac{N_{red} - 1}{N_{total} - 1},\n\n      which can be expanded to\n\n      .. math::\n\n        = \\\\frac{N_{red}}{N_{total}} *\n          \\\\frac{N_{red} - 1}{N_{total} - 1}\n\n\n  3. Using the `binomial coefficient (combination)`_ equation,\n\n.. _binomial coefficient (combination):\n    https://en.wikipedia.org/wiki/Combination\n\n      .. math::\n\n        \\\\binom{n}{k} = \\\\frac{n(n-1) ... (n-k+1)}{k(k-1) ... 1},\n\n      the probability of drawing 2 consecutive reds may be represented as\n\n      .. math::\n\n        P(red_2|red_1) = \\\\frac{\\\\binom{N_{red}}{2}}{\\\\binom{N_{Total}}{2}},\n\n      or more generally, the probability of drawing X consecutive reds is\n\n      .. math::\n\n        P(red_X|red_{(X-1)...1}) = \\\\frac{\\\\binom{N_{red}}{X}}\n                                       {\\\\binom{N_{Total}}{X}},\n\n      .. math::\n\n        = \\\\frac{\\\\binom{N_{red}}{X}}{\\\\binom{N_{red} + N_{black}}{X}}\n\n  In Code:\n\n\"\"\"\nimport pandas\nimport numpy\nfrom scipy.special import comb\n\n\ndef prob(n_red, n_black, x):\n    \"\"\" the probability of drawing X consecutive reds \"\"\"\n    n_total = n_red + n_black\n    pr = comb(n_red, x)\n    pr /= comb(n_total, x)\n    return pr\n\n\ndef createCombos(n_combos: int, names: list) -> dict:\n    \"\"\" utility for creating combos of integers \"\"\"\n    n = len(names)\n    range_ = range(1, n_combos + 1)\n    mesh = numpy.meshgrid(*(n * [range_]))\n    combos = numpy.array(mesh).reshape(n, -1)\n    return dict(zip(names, combos))\n\n\nclass Solution:\n\n    @staticmethod\n    def a(target_pr):\n        \"\"\"(a) How small can the number of socks in the drawer be?\"\"\"\n\n        combos = createCombos(\n            n_combos=5,\n            names=['n_red', 'n_black'], )\n\n        DF = pandas.DataFrame(combos)\n        pr = prob(**DF, x=2)\n\n        isSolution = (pr == target_pr)\n\n        return DF[isSolution]\n\n    @staticmethod\n    def b(target_pr):\n        \"\"\"(b) How small if the number of black socks is even?\"\"\"\n\n        combos = createCombos(\n            n_combos=30,\n            names=['n_red', 'n_black'], )\n\n        DF = pandas.DataFrame(combos)\n        pr = prob(**DF, x=2)\n\n        isSolution = (pr == target_pr)\n        blackIsEven = DF['n_black'] % 2 == 0\n\n        return DF[isSolution & blackIsEven]\n# %%\n\n\ndef main():\n    from practice.util.driver import Driver\n\n    target_pr = 1 / 2\n\n    for question in ['a', 'b']:\n        Driver(Solution, question).run(target_pr=target_pr)\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "9e0e5f90fc6f9e56d751899456674a08a67adcdf", "size": 3144, "ext": "py", "lang": "Python", "max_stars_repo_path": "practice/probability/sock_drawer.py", "max_stars_repo_name": "pyt3r/practice-package", "max_stars_repo_head_hexsha": "e5c30b372c1fd9e6dfaab7469371eaddcb2c2aa9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "practice/probability/sock_drawer.py", "max_issues_repo_name": "pyt3r/practice-package", "max_issues_repo_head_hexsha": "e5c30b372c1fd9e6dfaab7469371eaddcb2c2aa9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practice/probability/sock_drawer.py", "max_forks_repo_name": "pyt3r/practice-package", "max_forks_repo_head_hexsha": "e5c30b372c1fd9e6dfaab7469371eaddcb2c2aa9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2978723404, "max_line_length": 76, "alphanum_fraction": 0.5741094148, "include": true, "reason": "import numpy,from scipy", "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.8991213860551286, "lm_q1q2_score": 0.8511053074364096}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n#%%\n#1.1\n\ndef direct_pi(N):\n    hits = 0\n    for i in range(N):\n        x = np.random.uniform(-1,1)\n        y = np.random.uniform(-1,1)\n        if(x**2 + y**2 < 1.0):\n            hits +=1\n    return hits\n\n#%%\npi_child = direct_pi(10000)*4/10000\npi_child\n\n#1.2\n#%%\n\ndef markov_pi(N, delta):\n    hits = 0\n    x = 1.0\n    y = 1.0\n    for i in range(N):\n        dx = np.random.uniform(-delta, delta)\n        dy = np.random.uniform(-delta, delta)\n        if (abs(x + dx) < 1.0 and abs(y + dy) < 1.0):\n            x += dx\n            y += dy\n        if (x**2 + y**2) < 1.0:\n            hits +=1\n    return hits\n#%%\n\npi_markov = markov_pi(4000, 0.3)*4/4000\npi_markov\n\n#%%\n\n#1.8\n\ndef markov_two_site(k, p0, p1):\n    if(k == 0):\n        l = 1\n        gamma = min(1,p1/p0)\n    elif(k == 1):\n        l = 0\n        gamma = min(1,p0/p1)\n    rand = np.random.random()\n    if(rand < gamma): k = l\n    return k\n#%%\nesta = 0\ncuenta = 0\nfor i in range(1000):\n    esta = markov_two_site(esta, 0.8, 0.2)\n    if esta:\n        cuenta += 1\n\ncuenta\n\n#%%\n#1.16\n\ndef reject_continuous(pf, xmin, xmax):\n    acepta = True\n    while acepta:\n        x = np.random.uniform(xmin, xmax)\n        gamma = np.random.uniform(0, 0.95)\n        if (gamma > pf(x)):\n            acepta = True\n        else:\n            acepta = False\n    return x\n#%%\n\ndef my_fun(x, mu=0.7, sigma=0.05):\n     return 1.0/np.sqrt(2*np.pi*sigma**2) * np.exp(-(x-mu)**2/(2*sigma**2))\n\nequiseses = []\nfor i in range(1000):\n    equiseses.append(reject_continuous(my_fun, 0, 1))\n\n#%%\n_ = plt.hist(equiseses, density=True, bins=50)\nplt.xlim(0,1)\n\n#%%\n\n#1.18\n\ndef gauss(sigma):\n    phi = np.random.uniform(0,2*np.pi)\n    gamma = -np.log(np.random.random())\n    r = sigma * np.sqrt(2*gamma)\n    x = r*np.cos(phi)\n    y = r*np.sin(phi)\n    return x, y\n\n#%%\nX = []\nY = []\nfor i in range(1000):\n        x, y = gauss(0.01)\n        X.append(x)\n        Y.append(y)\n\n#%%\n_= plt.hist(X,density=True, bins = 50)    \n\n_= plt.hist(Y,density=True, bins = 50)\n", "meta": {"hexsha": "de20080a50b158ba84625b36e77a02a6ef9e7ed6", "size": 2030, "ext": "py", "lang": "Python", "max_stars_repo_path": "MCMC_pi.py", "max_stars_repo_name": "juanitopereza/Tarea_7", "max_stars_repo_head_hexsha": "1983bc1484163fe26c98400ef72bfa9dca58d5b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MCMC_pi.py", "max_issues_repo_name": "juanitopereza/Tarea_7", "max_issues_repo_head_hexsha": "1983bc1484163fe26c98400ef72bfa9dca58d5b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MCMC_pi.py", "max_forks_repo_name": "juanitopereza/Tarea_7", "max_forks_repo_head_hexsha": "1983bc1484163fe26c98400ef72bfa9dca58d5b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.652173913, "max_line_length": 75, "alphanum_fraction": 0.5167487685, "include": true, "reason": "import numpy", "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.899121375242593, "lm_q1q2_score": 0.8511052999104413}}
{"text": "# Box 6.1 and Example 6.1: Finding Correlations between Returns of Different Time Frames\n\nimport numpy as np\nimport pandas as pd\n# import matplotlib.pyplot as plt\n# import statsmodels.formula.api as sm\n# import statsmodels.tsa.stattools as ts\n# import statsmodels.tsa.vector_ar.vecm as vm\nfrom scipy.stats.stats import pearsonr\n\ndf = pd.read_csv('inputDataOHLCDaily_TU_20120511.csv')\ndf['Date'] = pd.to_datetime(df['Date'], format='%Y%m%d').dt.date  # remove HH:MM:SS\ndf.set_index('Date', inplace=True)\n\nfor lookback in [1, 5, 10, 25, 60, 120, 250]:\n    for holddays in [1, 5, 10, 25, 60, 120, 250]:\n        ret_lag = df.pct_change(periods=lookback)\n        ret_fut = df.shift(-holddays).pct_change(periods=holddays)\n        if (lookback >= holddays):\n            indepSet = range(0, ret_lag.shape[0], holddays)\n        else:\n            indepSet = range(0, ret_lag.shape[0], lookback)\n\n        ret_lag = ret_lag.iloc[indepSet]\n        ret_fut = ret_fut.iloc[indepSet]\n        goodDates = (ret_lag.notna() & ret_fut.notna()).values\n        (cc, pval) = pearsonr(ret_lag[goodDates], ret_fut[goodDates])\n        print('%4i %4i %7.4f %7.4f' % (lookback, holddays, cc, pval))\n\nlookback = 250\nholddays = 25\n\nlongs = df > df.shift(lookback)\nshorts = df < df.shift(lookback)\n\npos = np.zeros(df.shape)\n\nfor h in range(holddays - 1):\n    long_lag = longs.shift(h).fillna(False)\n    short_lag = shorts.shift(h).fillna(False)\n    pos[long_lag] = pos[long_lag] + 1\n    pos[short_lag] = pos[short_lag] - 1\n\npos = pd.DataFrame(pos)\npnl = np.sum((pos.shift().values) * (df.pct_change().values), axis=1)  # daily P&L of the strategy\nret = pnl / np.sum(np.abs(pos.shift()), axis=1)\ncumret = (np.cumprod(1 + ret) - 1)\ncumret.plot()\n\nprint('APR=%f Sharpe=%f' % (np.prod(1 + ret) ** (252 / len(ret)) - 1, np.sqrt(252) * np.mean(ret) / np.std(ret)))\nfrom calculateMaxDD import calculateMaxDD\n\nmaxDD, maxDDD, i = calculateMaxDD(cumret.fillna(0))\nprint('Max DD=%f Max DDD in days=%i' % (maxDD, maxDDD))\n", "meta": {"hexsha": "7015b0583a92b9b160b062337e9d4327f22a05c8", "size": 1980, "ext": "py", "lang": "Python", "max_stars_repo_path": "book2/TU_mom.py", "max_stars_repo_name": "welly87/epchanbooks", "max_stars_repo_head_hexsha": "6b3aa7f4b2656489149e557519997d14e962d75f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-04-18T04:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T01:49:27.000Z", "max_issues_repo_path": "book2/TU_mom.py", "max_issues_repo_name": "welly87/epchanbooks", "max_issues_repo_head_hexsha": "6b3aa7f4b2656489149e557519997d14e962d75f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book2/TU_mom.py", "max_forks_repo_name": "welly87/epchanbooks", "max_forks_repo_head_hexsha": "6b3aa7f4b2656489149e557519997d14e962d75f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-28T06:51:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T06:51:19.000Z", "avg_line_length": 36.0, "max_line_length": 113, "alphanum_fraction": 0.6641414141, "include": true, "reason": "import numpy,from scipy,import statsmodels", "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001757, "lm_q2_score": 0.899121373891026, "lm_q1q2_score": 0.8511052986310523}}
{"text": "# %% [markdown]\n# # Regression with Pytorch\n#\n# First we generate random data to test our models.\n#\n# We generate $$m$$ random features, $$X$$ from a Gaussian distribution.\n# We append a column of ones to the front to act as our constant term.\n# We then generate a set of random $$m+1$$ values to form our model weights.\n#\n# Then we form our output by creating a linear weighted sum of our features:\n# $$y_i = \\sum_m X_{i,m} * w_m + e_i$$\n#\n# We have added some Gaussian noise to create some uncertainty around of model estimates.\n\n# %% generate regression data\nimport numpy as np\n\n# independent features\nn = 1000\nm = 10\nfeatures = np.random.randn(n, m)\n\nX = np.concatenate((np.ones((n, 1)), features), axis=1)\nw = np.random.randn(m + 1, 1)\ne = np.random.randn(n, 1)\ny = X @ w + e\n# %% [markdown]\n# ## Statsmodels approach\n#\n# With `statsmodels` we can apply the ordinary least squares solution to the above data to recover estimates of the weights, $w$.\n\n# %% Linear regression with statsmodels\nimport statsmodels.api as sm\n\nresults = sm.OLS(y, X).fit()\nprint(results.summary())\n# %% [markdown]\n# ## Pytorch approach\n#\n# We can solve the same linear regression problem in `pytorch`.\n#\n# The ordinary least squares method above minimise the negative likelihood function. In this case it is the MSE:\n# $$loss = \\sum_i (y-\\hat{y})^2$$\n# Minimising a function is a generic problem we can solve using the gradient descent method.\n# This can be implemented by libraries such as pytorch.\n#\n# The problem is decomposed into a few steps:\n# * Given an estimate of the model weights, we predict what our output, $$y$$, should be.\n# * Calculate a loss function based on the difference between our prediction and the actual output. We use the above MSE function.\n# * Update the model weights to improve the loss function.\n# * Iterate the above until the weights have converged.\n#\n#\n# We will apply this in pytorch.\n# Pytorch has its own internal memory structures so we need to convert from our numpy arrays to torch tensors using `from_numpy()`.\n# The weights estimates are initialised randomly. We require that the gradients are calculated for the weights so we use the `requires_grad` flag.\n#\n# We use the stochastic gradient descent optimiser to update the weights, the learning rate needs to be chosen appropriately.\n#\n# The forward step calculates the output of the network.\n# The loss function is setup using pytorch functions which run over the tensor objects and allow the gradients to be calculated automatically.\n#\n# The gradients need to be reset each iteration as PyTorch accumulates the gradients on subsequent backward passes.\n# The backwards step calculates the gradients automatically.\n#\n# The optimizer object then updates the model weights to minimise the loss function.\n#\n# We iterate over the data 100 times, at which point the weights have converged.\n\n# %%\nimport torch\nimport torch.optim as optim\nimport time\n\nX_t = torch.from_numpy(X)\ny_t = torch.from_numpy(y)\n\nw_t = torch.randn(m + 1, 1, dtype=torch.float64, requires_grad=True)\nlearning_rate = 5e-5\noptimizer = optim.SGD([w_t], lr=learning_rate, momentum=0.0)\noptimizer.zero_grad()\n\nloss_values = []\n\nfor t in range(100):\n    # Forward pass\n    y_pred = X_t.mm(w_t)\n\n    # Compute and print loss\n    loss = (y_pred - y_t).pow(2).sum()\n    loss_values.append(loss.item())\n\n    optimizer.zero_grad()\n    loss.backward()\n    optimizer.step()\n\nloss_values = np.array(loss_values)\n# %% [markdown]\n# The loss function from optimisation shows a consistent decrease as it converges:\n\n# %%\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nsns.set_style(\"whitegrid\")\nplt.style.use(\"seaborn-whitegrid\")\n\nplt.figure(num=None, figsize=(10, 6), dpi=80)\nplt.plot(range(len(loss_values)), loss_values)\nplt.xlabel(\"Iteration\")\nplt.ylabel(\"Loss\")\nplt.yscale(\"log\")\nplt.savefig(\"images/loss.png\")\nplt.show()\n# %% [markdown]\n# ![](images/loss.png)\n#\n\n# %% Results weights are equivalent to statsmodels\nprint(w)\nprint(w_t.flatten())\nprint(results.params.flatten())\nprint(results.summary())\n\nplt.scatter(np.arange(len(w)), w)\nplt.scatter(np.arange(len(w)), w_t.flatten().detach().numpy())\nplt.scatter(np.arange(len(w)), results.params.flatten())\n\n\n# %% [markdown]\n\n\n# %% Use pytorch nn module\nimport torch\nimport torch.optim as optim\n\n# X_t = torch.from_numpy(X)\n# y_t = torch.from_numpy(y)\nif 0:\n    X_t = torch.Tensor(X)\nelse:\n    X_t = torch.Tensor(X[:, 1:])\ny_t = torch.Tensor(y)\n\n# model = torch.nn.Sequential(torch.nn.Linear(m + 1, 1, bias=False))\nmodel = torch.nn.Sequential(torch.nn.Linear(m, 1, bias=True))\nloss_fn = torch.nn.MSELoss(reduction=\"sum\")\n\nlearning_rate = 5e-2\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n# optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)\n\n\nstart_time = time.time()\nloss_values = []\nfor t in range(100):\n    # Forward pass\n    y_pred = model(X_t)\n\n    # Compute and print loss\n    loss = loss_fn(y_pred, y_t)\n    loss_values.append(loss.item())\n\n    optimizer.zero_grad()\n    loss.backward()\n    optimizer.step()\n\nprint(time.time() - start_time)\nloss_values = np.array(loss_values)\n\nplt.plot(loss_values)\n# [print(param) for param in model.parameters()]\nfor name, param in model.named_parameters():\n    print(name, param)\n\n\nprint(w)\nprint(w_t.flatten())\nprint(results.params.flatten())\n\n# %% Create pytorch class\n\n\n# %% Implementing in tensorflow\nimport tensorflow as tf\n\nmodel = tf.keras.Sequential(\n    [\n        tf.keras.layers.Dense(1, activation='linear', use_bias=True, input_shape=(m,))\n    ]\n)\n\n\n# optimizer = tf.keras.optimizers.SGD(0.2)\noptimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)\nmodel.compile(optimizer=optimizer,\n              loss='mse',\n              metrics=[tf.keras.metrics.MSE], )\nstart_time = time.time()\nhistory = model.fit(X[:, 1:], y, epochs=100, batch_size=n)\nprint(time.time() - start_time)\nplt.plot(history.history['loss'])\n\nmodel.predict(X[:, 1:])\nprint(model.trainable_weights)\n\nprint(w_t.flatten())\n\n\n\n# %% Curveball\n# %% New data set?\n\n\n# %%\n\nfrom pyro.nn import PyroModule\nfrom torch import nn\n\n# %%\nnn.Linear\nPyroModule[nn.Linear](3, 1)\n", "meta": {"hexsha": "f1da1f60911b54bd4504f775a7362a1c399b1a8c", "size": 6118, "ext": "py", "lang": "Python", "max_stars_repo_path": "Unpublished/BayesianRegression/regression_with_pytorch.py", "max_stars_repo_name": "stanton119/data-analysis", "max_stars_repo_head_hexsha": "b6fda815c6cc1798ba13a5d2680369b7e5dfcdf9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Unpublished/BayesianRegression/regression_with_pytorch.py", "max_issues_repo_name": "stanton119/data-analysis", "max_issues_repo_head_hexsha": "b6fda815c6cc1798ba13a5d2680369b7e5dfcdf9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-11T23:44:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-11T23:44:52.000Z", "max_forks_repo_path": "Unpublished/BayesianRegression/regression_with_pytorch.py", "max_forks_repo_name": "stanton119/data-analysis", "max_forks_repo_head_hexsha": "b6fda815c6cc1798ba13a5d2680369b7e5dfcdf9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-16T01:02:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-16T01:02:23.000Z", "avg_line_length": 27.4349775785, "max_line_length": 146, "alphanum_fraction": 0.7175547565, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 1496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993889, "lm_q2_score": 0.8902942246666266, "lm_q1q2_score": 0.8511046782656083}}
{"text": "import fractions as fr\nfrom scipy import misc\n\n\n# ------------- auxiliary method for the BCH formula ----------------\n\n\ndef fact(n):\n    \"\"\"\n    Covers the predefined function factorial from scipy.misc\n    :param n:\n    :return: factorial of n type float\n    \"\"\"\n    return float(misc.factorial(n, True))\n\n\ndef bern(n):\n    \"\"\"\n    bern(n) \\n\n    :param n: integer n\n    :return: nth Bernoulli number (type Fraction)\n    (iterative algorithm, do not uses polynomials)\n    \"\"\"\n    if n == 1:\n        ans = fr.Fraction(1, 2)\n    elif n % 2 == 1:\n        ans = fr.Fraction(0, 1)\n    else:\n        n += 1\n        a = [0] * (n + 1)\n        for m in range(n + 1):\n            a[m] = fr.Fraction(1, m + 1)\n            for j in range(m - 1, 0, -1):\n                a[j - 1] = j * (a[j - 1] - a[j])\n        ans = a[0]\n    return ans  # type Fraction.\n    # return float(ans) # type Float\n\n\ndef bernoulli_poly(x, n):\n    \"\"\"\n    bernoulli_poly(x,n) \\n\n    :param x: value for the unknown.\n    :param n: degree of the polynomial.\n    :return: j-th bernoulli polynomial evaluate at x (unknown of the poly).\n    \"\"\"\n    return sum([misc.comb(n, k) * bern(n - k) * (x ** k) for k in range(n)])  # comb = binomial\n\n\ndef bernoulli_numb_via_poly(n):\n    \"\"\"\n    bernoulli_numb(n) \\n\n    :param n: integer n\n    :return: nth Bernoulli number\n    (uses first type bernoulli polynomials)\n    \"\"\"\n    return bernoulli_poly(0, n)\n", "meta": {"hexsha": "bb25fb95836f11a77ba88fd1aa935f6be66e0cb0", "size": 1408, "ext": "py", "lang": "Python", "max_stars_repo_path": "calie/aux/bernoulli.py", "max_stars_repo_name": "SebastianoF/calie", "max_stars_repo_head_hexsha": "187318fa340b6d2fbf8c5dbc643304b66e9d1c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "calie/aux/bernoulli.py", "max_issues_repo_name": "SebastianoF/calie", "max_issues_repo_head_hexsha": "187318fa340b6d2fbf8c5dbc643304b66e9d1c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calie/aux/bernoulli.py", "max_forks_repo_name": "SebastianoF/calie", "max_forks_repo_head_hexsha": "187318fa340b6d2fbf8c5dbc643304b66e9d1c44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.275862069, "max_line_length": 95, "alphanum_fraction": 0.5475852273, "include": true, "reason": "from scipy", "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813488829418, "lm_q2_score": 0.8902942275774318, "lm_q1q2_score": 0.85110467658217}}
{"text": "\"\"\" Example of a Discrete Markov Chain random walk conditioned by a\ntransition matrix. What is the probability after n steps that the\nMarkov train goes from state 0 to state 0? This simulation is based\non Example 1.1.6 from J.R. Norris (1997): Markov chains. CUP. p.6-8.\n\"\"\"\nimport probayes as pb\nimport numpy as np\nfrom pylab import *; ion()\n\n# Prob convention: successor dimension (row) > predecessor dimension (col)\ntran = np.array(\n                [0., 0., .5,\n                 1., .5, 0.,\n                 0., .5, .5],\n               ).reshape([3,3])\nn_sims = 2000\nm_steps = 12 # max_steps\n\n# Analytical solution (obtained from the eigenvalues of tran)\nm = np.arange(1, m_steps+1)\nmpi_2 = m * np.pi / 2\nhatp = 0.2 + 0.5**m * (0.8 * np.cos(mpi_2) - 0.4 * np.sin(mpi_2))\n\n# Simulation\nx = pb.RV('x', range(3))\nx.set_tran(tran)\nX = pb.SP(x)\n\ncond = [None] * n_sims\nsucc = np.empty([n_sims, m_steps], dtype=int)\nprint('Simulating...')\nfor i in range(n_sims):\n  cond[i] = [None] * m_steps\n  sampler = X.sampler({'x': 0}, stop=m_steps)\n  samples = X.walk(sampler)\n  summary = X(samples)\n  cond[i] = summary.q.prob\n  succ[i] = summary.q[\"x'\"]\nprint('...done')\nobsp = np.sum(succ==0, axis=0) / n_sims\n\n# Plot\nfigure()\nplot(m, hatp, 'r', label='Expected probability')\nplot(m, obsp, 'b', label='Simulated proportion')\nxlabel(r'$n$')\nylabel(r'$P$')\nlegend()\n", "meta": {"hexsha": "e402afb816abd572c8a66ff4f6b02d71ed9cb017", "size": 1352, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/markov/markov_sp_matrix.py", "max_stars_repo_name": "Bhumbra/probayes", "max_stars_repo_head_hexsha": "e5ac193076e4188b9b38c0e18466223ab4d041f7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/markov/markov_sp_matrix.py", "max_issues_repo_name": "Bhumbra/probayes", "max_issues_repo_head_hexsha": "e5ac193076e4188b9b38c0e18466223ab4d041f7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/markov/markov_sp_matrix.py", "max_forks_repo_name": "Bhumbra/probayes", "max_forks_repo_head_hexsha": "e5ac193076e4188b9b38c0e18466223ab4d041f7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5918367347, "max_line_length": 74, "alphanum_fraction": 0.6264792899, "include": true, "reason": "import numpy", "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.8902942239389252, "lm_q1q2_score": 0.8511046742203541}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nnp.set_printoptions(threshold=np.nan)\nnp.set_printoptions(precision=16)\n\n#<startTeX>\n# problem discritization\ndef G(theta):\n    Gout = np.zeros(m+1)\n    for i in range(1,m):\n        Gout[i] = (theta[i-1]-2*theta[i]+theta[i+1])/h2+np.sin(theta[i])\n    return Gout[1:m+1] # return only inner things since boundaries are fixed\n\ndef J(theta):\n    Jout = np.triu(np.tril(np.ones((m,m)),1),-1)-np.identity(m) # trigiagonal all ones\n    Jout += np.diag(-2 + h2*np.cos(theta[1:m+1])) \n    return Jout/h2\n\n# problem parameters\nalpha = 0.7\nbeta = 0.7\nT = 2*np.pi # part a\nx = np.linspace(0,T,m+2)\nh = T/(m+1)\nh2 = h**2\n\n# discritization parameters\nm = 512\nx = np.linspace(0,T,m+2)  \n\n#initial guess\ntheta = 0.7*np.cos(x)+0.5*np.sin(x)\nfor k in range(25):\n        print(k)\n        delta = np.linalg.solve(J(theta),-G(theta))\n        theta[1:m+1] += delta\n        \n        if max(abs(delta)) < 10e-14:\n            break\n\nplt.figure()\nplt.scatter(x,theta)\nplt.savefig('img/1/original.pdf')\n\ntheta = 0.7 + abs(x-np.pi)-np.pi\nfor k in range(25):\n        print(k)\n        delta = np.linalg.solve(J(theta),-G(theta))\n        theta[1:m+1] += delta\n        \n        if max(abs(delta)) < 10e-14:\n            break\n\nplt.figure()\nplt.scatter(x,theta)\nplt.savefig('img/1/abs.pdf')\n\nmaxtheta = []\ntheta = 0.7 + np.sin(x/2)\nfor T in np.linspace(6,62,8):\n\n    x = np.linspace(0,T,m+2)\n    h = T/(m+1)\n    h2 = h**2\n\n    # Newton's method\n    for k in range(25):\n        print(k)\n        delta = np.linalg.solve(J(theta),-G(theta))\n        theta[1:m+1] += delta\n        \n        if max(abs(delta)) < 10e-14:\n            break\n\n    maxtheta = np.append(maxtheta,max(abs(theta)))\n    plt.figure()\n    plt.scatter(x,theta)\n    plt.savefig('img/1/'+str(int(T))+'.pdf')\n\nprint(maxtheta)\n#<endTeX>", "meta": {"hexsha": "3e292804262b0346a274f228115f6001d2a86ba1", "size": 1815, "ext": "py", "lang": "Python", "max_stars_repo_path": "amath585/hw3/hw3_1.py", "max_stars_repo_name": "interesting-courses/UW_coursework", "max_stars_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-19T01:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T12:32:59.000Z", "max_issues_repo_path": "amath585/hw3/hw3_1.py", "max_issues_repo_name": "interesting-courses/UW_coursework", "max_issues_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "amath585/hw3/hw3_1.py", "max_forks_repo_name": "interesting-courses/UW_coursework", "max_forks_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-31T22:23:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T22:13:01.000Z", "avg_line_length": 22.4074074074, "max_line_length": 86, "alphanum_fraction": 0.5812672176, "include": true, "reason": "import numpy", "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813463747181, "lm_q2_score": 0.8902942217558213, "lm_q1q2_score": 0.8511046687837619}}
{"text": "import numpy as np\nfrom math import factorial\n\n# Allowing Right and Up is the same as allowing Down and Right and starting from the top left corner\n# and traversing to the bottom right corner\n# Generating the textual desciptions can be done a lot more efficiently, but I continued on with the \n# dynamic programming approach for that too\ndef number_of_paths(n: int):\n\tpaths = np.empty((n, n, 2), dtype=object)\n\n\t# The first row and column only have one solution\n\tpaths[:, :, 0] = np.zeros((n,n))\n\tpaths[0, :, 0] = np.ones(n)\n\tpaths[:, 0, 0] = np.ones(n)\n\n\t# Initialise the lists used for building up the string descriptions\n\tfor pos, val in np.ndenumerate(paths[:, :, 1]):\n\t\tr, c = pos\n\t\tpaths[r, c, 1] = []\n\n\tpaths[1, 0, 1].append(\"U\")\n\tpaths[0, 1, 1].append(\"R\")\n\n\t# Use dynamic programming for an O(N^2) solution\n\tfor pos, val in np.ndenumerate(paths[:, :, 0]):\n\t\tr, c = pos\n\n\t\t# Generating the string version of the paths\n\t\tif r != 0:\n\t\t\tfor x in paths[r - 1, c, 1]:\n\t\t\t\tpaths[r, c, 1].append(\"{}U\".format(x))\n\n\t\tif c != 0:\n\t\t\tfor x in paths[r, c - 1, 1]:\n\t\t\t\tpaths[r, c, 1].append(\"{}R\".format(x))\n\n\t\t# If we just counting the number of paths then only the next 3 lines are required\n\t\tif r == 0 or c == 0:\n\t\t\tcontinue\n\t\tpaths[r, c, 0] = paths[r - 1, c, 0] + paths[r, c - 1, 0]\n\n\t# Reutrn the total number of paths plus the strings describing each path\n\treturn( [int(paths[-1, -1, 0]), paths[-1,-1, 1]] ) \n\n# Simple solution for calculating the number of paths for any sized matrix\ndef number_of_paths_fast(n: int):\n\tn -= 1\n\t# This is just binomial combinations\n\t# Solution is just a set of strings len(2n) of R's and U's where num(R) == num(U) == n\n\treturn( factorial(2*n)//( factorial(n) * factorial(n) ) )\n\nif __name__ == \"__main__\":\n\tn = int(input(\"Enter matrix dimension: \"))\n\tnum, routes = number_of_paths( n )\n\tprint( \"There are {} possible routes.\".format(num) )\n\tprint(routes)\n\tprint(number_of_paths_fast( n ))\n", "meta": {"hexsha": "ea5bda03dceda6926321a118b606c69d0636c2be", "size": 1924, "ext": "py", "lang": "Python", "max_stars_repo_path": "challenge_18/python/system123/challenge_18.py", "max_stars_repo_name": "YearOfProgramming/2017Challenges", "max_stars_repo_head_hexsha": "a8f556f1d5b43c099a0394384c8bc2d826f9d287", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 271, "max_stars_repo_stars_event_min_datetime": "2017-01-01T22:58:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T23:05:29.000Z", "max_issues_repo_path": "challenge_18/python/system123/challenge_18.py", "max_issues_repo_name": "AakashOfficial/2017Challenges", "max_issues_repo_head_hexsha": "a8f556f1d5b43c099a0394384c8bc2d826f9d287", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 283, "max_issues_repo_issues_event_min_datetime": "2017-01-01T23:26:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-23T00:48:55.000Z", "max_forks_repo_path": "challenge_18/python/system123/challenge_18.py", "max_forks_repo_name": "AakashOfficial/2017Challenges", "max_forks_repo_head_hexsha": "a8f556f1d5b43c099a0394384c8bc2d826f9d287", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 311, "max_forks_repo_forks_event_min_datetime": "2017-01-01T22:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T00:29:12.000Z", "avg_line_length": 33.1724137931, "max_line_length": 101, "alphanum_fraction": 0.658004158, "include": true, "reason": "import numpy", "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897558991953, "lm_q2_score": 0.904650538956921, "lm_q1q2_score": 0.8510859597193573}}
{"text": "from __future__ import print_function\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Let's create some noisy data that should follow a line\r\n\r\n# Parameters of a line\r\nm = 2.6\r\nk = 10.8\r\n\r\n\r\n# Let's define a function describing a line\r\ndef line(x, m, k):\r\n\r\n    return m*x + k\r\n\r\n\r\n# Generate the line data\r\nx = np.linspace(0, 10, 100)\r\nline_data = line(x, m, k)\r\n\r\n# Add noise to the line\r\nline_data += np.random.normal(0, 1, line_data.shape)\r\n\r\nplt.hold(True)\r\n\r\n# Plot the line data\r\nplt.scatter(x, line_data)\r\n\r\n# plt.show()\r\n\r\n# Import needed scipy libraries\r\nimport scipy.optimize\r\n\r\n# Fit the line\r\npopt, pcov = scipy.optimize.curve_fit(line, x, line_data)\r\n\r\nprint('Fit params:', popt)\r\n\r\nplt.plot(x, line(x, *popt))\r\n\r\n\r\n# plt.show()\r\n\r\nplt.clf()\r\n\r\n# See the documentation how to get the stddev of each parameter\r\nprint('Stddev:', np.sqrt(np.diag(pcov)))\r\n\r\n# CONGRATS! YOUR FIRST SUCCESSFUL LINEAR REGRESSION IN PYTHON!\r\n\r\n# Why should we be very careful when we are doing any kind of regression:\r\n# Anscobe's Quartet: https://en.wikipedia.org/wiki/Anscombe%27s_quartet\r\n\r\n# What are the alternatives?\r\n# http://scikit-learn.org/stable/auto_examples/linear_model/plot_theilsen.html\r\n\r\n\r\n# Let's add some outliers to our data\r\nline_data[10:12] -= 30\r\nline_data[98:] += 50\r\nx[-1] += 10\r\n\r\nplt.scatter(x, line_data)\r\n\r\n# plt.show()\r\n\r\n# If we do the LS fit again...\r\npopt, pconv = scipy.optimize.curve_fit(line, x, line_data)\r\n\r\n# Plot fitted line\r\nplt.plot(x, line(x, *popt), label='LS')\r\n\r\n# Plot original line\r\nplt.plot(x, line(x, m, k), color='k', label='Original')\r\n\r\n# plt.show()\r\n\r\n# CHECK THAT scikit-learn is installed!\r\nfrom sklearn.linear_model import RANSACRegressor, TheilSenRegressor\r\n\r\n# Reshaping the data (required by the scikit functions)\r\nx = x.reshape(-1, 1)\r\nline_data = line_data.reshape(-1, 1)\r\n\r\n\r\n# RANSAC details: http://scipy-cookbook.readthedocs.io/items/RANSAC.html\r\n# RANSAC works on non-linear problems as well, often using in Computer Vision.\r\n\r\n# Init the RANSAC regressor\r\nransac = RANSACRegressor()\r\n\r\n# Fit with RANSAC\r\nransac.fit(x, line_data)\r\n\r\n# Get the fitted data result\r\nline_ransac = ransac.predict(x)\r\n\r\n# Show the RANSAC fit\r\nplt.plot(x, line_ransac, color='yellow', label='RANSAC')\r\n\r\n# plt.show()\r\n\r\n\r\n# Theil-Sen estimator: \r\n# General info: https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator\r\n# Good ONLY for LINEAR REGRESSION\r\n# Sci-kit learn implementation: http://scikit-learn.org/stable/auto_examples/linear_model/plot_theilsen.html\r\n\r\n# Init the Theil-Sen estimator instance\r\ntheil = TheilSenRegressor()\r\n\r\n# Fit with the Theil-Sen estimator\r\ntheil.fit(x, line_data)\r\n\r\n# Get the fitted data result\r\nline_theil = theil.predict(x)\r\n\r\n# Plot Theil-Sen results\r\nplt.plot(x, line_theil, color='red', label='Theil-Sen')\r\n\r\nplt.legend(loc='lower right')\r\n\r\nplt.show()\r\n\r\nplt.clf()\r\n\r\n###################################\r\n\r\n# Minimization - e.g. how to find a minimum of a function?\r\n\r\ndef f1(x):\r\n\t\"\"\" A tricky function to minimize. \"\"\"\r\n\r\n\treturn 0.1*x**2 + 2*np.sin(2*x)\r\n\r\n\r\nx = np.linspace(-10, 10, 100)\r\n\r\n# Plot the tricky function\r\nplt.plot(x, f1(x))\r\n\r\n# Try changing the inital estimage (first try 0, then try 5)\r\nx0 = 5\r\n\r\n# Find the minimum using BFGS algorithm\r\nres = scipy.optimize.minimize(f1, x0)\r\n\r\n# Find global minimum using basin hopping\r\nres = scipy.optimize.basinhopping(f1, x0, niter=2000)\r\n\r\nprint (res.x)\r\n\r\n# Plot mimumum point\r\nplt.scatter(res.x, f1(res.x))\r\n\r\nplt.show()\r\nplt.clf()\r\n\r\n\r\n\r\n###################################\r\n\r\n# Fitting nonlinear models\r\n\r\n# Task 1\r\n\r\n\r\n\r\n\r\n\r\n###################################\r\n### NOT IN LECTURE\r\n\r\n### EXTRA: ROBUST FIT attempt\r\n\r\n# Difficult function to fit\r\ndef func(x, a, b, c, d, e):\r\n\r\n    return a*np.sin(b*x) + c*x**2 + d*x + e\r\n\r\n\r\nx = np.linspace(0, 10, 1000)\r\n\r\n# Generte function data\r\ny_data = func(x, 1.5, 2, 0.1, 0.1, 3)\r\n\r\n# Plot the model data\r\nplt.plot(x, y_data, color='red', label='Underlying model')\r\n\r\n# Add noise\r\ny_data_noise = y_data + np.random.normal(0, 0.5, y_data.shape)\r\n\r\n# Plot noisy data\r\nplt.plot(x, y_data_noise, alpha=0.5, label='Noisy data')\r\n\r\n\r\n# Fit the function to the noisy data, regular LS\r\npopt, pcov = scipy.optimize.curve_fit(func, x, y_data_noise)\r\n\r\n# Plot LS fit results\r\nplt.plot(x, func(x, *popt), color='green', label='LS fit')\r\n\r\n# Read more about robust regression:\r\n# http://scipy-cookbook.readthedocs.io/items/robust_regression.html\r\n\r\n# Define a function for computing residuals\r\ndef residuals(params, x, y):\r\n    \"\"\" Returns the residuals between the predicted and input values of the model\r\n\r\n    Arguments:\r\n        params: [ndarray] function parameters\r\n        x: [ndarray] independant variable\r\n        y: [ndarray] prediction\r\n\r\n    Return:\r\n        residuals: [ndarray]\r\n\r\n    \"\"\"\r\n\r\n    return func(x, *params) - y\r\n\r\n\r\n# Set initial guess of parameters to 1 (array of size 5, same as the number of parameters of our function)\r\nx0 = np.ones(5)\r\n\r\n# Try to do a robust fit (doesn't always work, but it is better than ordinary LS)\r\nfit_robust_ls = scipy.optimize.least_squares(residuals, x0, loss='cauchy', f_scale=0.1, args=(x, y_data_noise))\r\n\r\n\r\n\r\ndef residuals_minimize(params, x, y):\r\n    \"\"\" Wrapper function for calculating fit residuals for minimization. \"\"\"\r\n\r\n    # Squared value of each residual\r\n    z = residuals(params, x, y)**2\r\n\r\n    # Smooth approximation of l1 (absolute value) loss\r\n    return np.sum(2*((1 + z)**0.5 - 1))\r\n    \r\n\r\n# Treat the fit as a minimization problem, but use basinhopping for minimizing residuals\r\nfit_robust_mini = scipy.optimize.basinhopping(residuals_minimize, x0, minimizer_kwargs={'args':(x, y_data_noise)})\r\n\r\n\r\n# Plot the robust fit results\r\nplt.plot(x, func(x, *fit_robust_ls.x), color='yellow', label='Robust fit - least squares')\r\nplt.plot(x, func(x, *fit_robust_mini.x), color='black', label='Robust fit - basinhopping')\r\n\r\nplt.legend(loc='lower right')\r\nplt.show()\r\n\r\n# For better results, Markov-Chain Monte Carlo fitting can be used:\r\n# https://sciencehouse.wordpress.com/2010/06/23/mcmc-and-fitting-models-to-data/\r\n\r\n# MCMC Python implementation:\r\n# https://github.com/dvida/mcmc-fit-py/blob/master/MCMC%20fit.py", "meta": {"hexsha": "934b5f1f0cc8808bf09b5d62889feb7b2c5700f5", "size": 6176, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lecture 6/L6_lecture.py", "max_stars_repo_name": "ShengmiaoJ/uwo-pa-python-course", "max_stars_repo_head_hexsha": "7890701b63cbdd56deb2fbb7845724ad9809a220", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-04-21T23:16:12.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-31T03:01:53.000Z", "max_issues_repo_path": "Lecture 6/L6_lecture.py", "max_issues_repo_name": "ShengmiaoJ/uwo-pa-python-course", "max_issues_repo_head_hexsha": "7890701b63cbdd56deb2fbb7845724ad9809a220", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lecture 6/L6_lecture.py", "max_forks_repo_name": "ShengmiaoJ/uwo-pa-python-course", "max_forks_repo_head_hexsha": "7890701b63cbdd56deb2fbb7845724ad9809a220", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-05-06T23:09:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T00:18:32.000Z", "avg_line_length": 23.9379844961, "max_line_length": 115, "alphanum_fraction": 0.6696891192, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188345, "lm_q2_score": 0.9046505280315008, "lm_q1q2_score": 0.8510859449353478}}
{"text": "# =============================================================================\n#  ***** radioactive_decay.py *****\n#  Python script to solve first order ODE for radioactive decay.\n#\n#  A = -dN/dt = lambda*N\n#\n#  Author:     Ryan Clement\n#  Created:    July 2021\n#\n#  Change Log:\n#  Who:\n#  Date:       MM/DD/YYY\n#  What:\n#\n#  Who:\n#  Date:       MM/DD/YYYY\n#  What:\n# =============================================================================\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\n### Functions\ndef anal(n0,l,t):\n    return n0*np.exp(-l*t)\n\n## Integrators    \ndef euler(n0,l,scale):\n    nOld = n0 \n    nNew = n0\n    dt = 1.0/(l*scale)\n    tArr = [0.0]\n    nArr = [n0]\n    t = 0.0\n    while (nNew >= nStop):\n        nNew = nOld*(1.0 - l*dt)\n        nOld = nNew\n        nArr.append(nOld)\n        t += dt\n        tArr.append(t)\n    print(f\"Forward Euler stop time, dt: {t}, {dt}\")\n    return tArr, nArr\n\ndef eulerStepsB(n0,l,scale,nSteps):\n    nOld = n0 \n    nNew = n0\n    dt = 1.0/(l*scale)\n    tArr = [0.0]\n    nArr = [n0]\n    t = 0.0\n    for i in range(nSteps):\n        nNew = nOld/(1.0 + l*dt)\n        nOld = nNew\n        nArr.append(nOld)\n        t += dt\n        tArr.append(t)\n    print(f\"Backward Euler stop time, dt: {t}, {dt}\")\n    return tArr, nArr\n\ndef eulerSteps(n0,l,scale,nSteps):\n    nOld = n0 \n    nNew = n0\n    dt = 1.0/(l*scale)\n    tArr = [0.0]\n    nArr = [n0]\n    t = 0.0\n    for i in range(nSteps):\n        nNew = nOld*(1.0 - l*dt)\n        nOld = nNew\n        nArr.append(nOld)\n        t += dt\n        tArr.append(t)\n    print(f\"Forward Euler stop time, dt: {t}, {dt}\")\n    return tArr, nArr\n\n# Backward Euler\ndef eulerB(n0,l,scale):\n    nOld = n0 \n    nNew = n0\n    dt = 1.0/(l*scale)\n    tArr = [0.0]\n    nArr = [n0]\n    t = 0.0\n    while (nNew >= nStop):\n        nNew = nOld/(1.0 + l*dt)\n        nOld = nNew\n        nArr.append(nOld)\n        t += dt\n        tArr.append(t)\n    print(f\"Backward Euler stop time, dt: {t}, {dt}\")\n    return tArr, nArr\n\ndef trap(n0,l,scale):\n    nOld = n0\n    nNew = n0\n    dt = 1.0/(l*scale)\n    d = 1.0/(2.0*scale)\n    rat = (1.0 - d)/(1.0 + d)\n    tArr = [0.0]\n    nArr = [n0]\n    t = 0.0\n    while (nNew >= nStop):\n        nNew = nOld*rat\n        nOld = nNew\n        t += dt\n        tArr.append(t)\n        nArr.append(nOld)\n    print(f\"Trapezoid Rule stop time, dt: {t}, {dt}\")\n    return tArr, nArr\n\ndef rk2(n0,l,scale):\n    nOld = n0\n    nNew = n0\n    dt = 1.0/(l*scale)\n    dt2 = dt**2\n    l2 = l**2\n    tArr = [0.0]    # t0 = 0.0\n    nArr = [n0]\n    t = 0.0\n    while (nNew >= nStop):\n        nNew = nOld*(1.0 - l*dt + l2*dt2/2.0)\n        nOld = nNew\n        t += dt\n        tArr.append(t)\n        nArr.append(nOld)\n    print(f\"RK2 stop time, dt: {t}, {dt}\")\n    return tArr, nArr\n\n# Plotters\ndef plotFE(n0,l):\n    tA = np.linspace(0,tAnal,100)\n    nA = anal(n0,l,tA)\n    t2, n2 = euler(n0,l,2.0)\n    t4, n4 = euler(n0,l,4.0)\n    t20, n20 = euler(n0,l,20.0)\n    figE, axE = plt.subplots()\n    axE.set_title('Radioactive Decay')\n    axE.set_xlabel('t')\n    axE.set_ylabel('Decay Material')\n    axE.plot(t20, n20,'*',color='red',label='Euler 20')\n    axE.plot(t4, n4,'*',color='blue',label='Euler 4')\n    axE.plot(t2, n2,'x',color='purple',label='Euler 2')\n    axE.plot(tA,nA,color='black',label='Analytic')\n    axE.legend()\n    # figE.savefig('radioactive_FE.png')\n\ndef plotUnstabFE(n0,l):\n    tp3, np3 = eulerSteps(1.0/2.1,10)\n    ts = 10.0/(l*(1.0/2.1))\n    tA = np.linspace(0,ts,100)\n    nA = anal(n0,l,tA)\n    figEU, axEU = plt.subplots()\n    axEU.set_title('Radioactive Decay')\n    axEU.set_xlabel('t')\n    axEU.set_ylabel('Decay Material')\n    axEU.plot(tp3, np3,'-*',color='red',label='Euler 0.3')\n    axEU.plot(tA,nA,color='black',label='Analytic')\n    axEU.legend()\n    # figEU.savefig('radioactive_unstable_FE.png')\n\ndef plotEulerB(n0,l):\n    tA = np.linspace(0,tAnal,100)\n    nA = anal(n0,l,tA)\n    tb2, nb2 = eulerB(n0,l,2.0)\n    tb4, nb4 = eulerB(n0,l,4.0)\n    tb20, nb20 = eulerB(n0,l,20.0)\n    figBE, axBE = plt.subplots()\n    axBE.set_title('Radioactive Decay')\n    axBE.set_xlabel('t')\n    axBE.set_ylabel('Decay Material')\n    axBE.plot(tb20, nb20,'*',color='red',label='Backward Euler 20')\n    axBE.plot(tb4, nb4,'*',color='blue',label='Backward Euler 4')\n    axBE.plot(tb2, nb2,'x',color='purple',label='Backward Euler 2')\n    axBE.plot(tA,nA,color='black',label='Analytic')\n    axBE.legend()\n    # figBE.savefig('radioactive_BE.png')\n\n# Unstable Case BE comparo\ndef plotBE_Comparo(n0,l):\n    tp3, np3 = eulerSteps(n0,l,1.0/2.1,10)\n    tp3B, np3B = eulerStepsB(n0,l,1.0/2.1,10)\n    ts = 10.0/(l*(1.0/2.1))\n    tA = np.linspace(0,ts,100)\n    nA = anal(n0,l,tA)\n    figBU, axBU = plt.subplots()\n    axBU.set_title('Radioactive Decay')\n    axBU.set_xlabel('t')\n    axBU.set_ylabel('Decay Material')\n    axBU.plot(tp3, np3,'-*',color='red',label='Forward Euler 0.3')\n    axBU.plot(tp3B, np3B,'-*',color='blue',label='Backward Euler 0.3')\n    axBU.plot(tA,nA,color='black',label='Analytic')\n    axBU.legend()\n    # figBU.savefig('radioactive_unstable_BE.png')\n\ndef plotFEvBE(n0,l):\n    tA = np.linspace(0,tAnal,100)\n    nA = anal(n0,l,tA)\n    t2, n2 = euler(n0,l,2.0)\n    tb2, nb2 = eulerB(n0,l,2.0)\n    figC, axC = plt.subplots()\n    axC.set_title('Radioactive Decay')\n    axC.set_xlabel('t')\n    axC.set_ylabel('Decay Material')\n    axC.plot(t2, n2,'-*',color='red',label='Forward Euler 2')\n    axC.plot(tb2, nb2,'-*',color='blue',label='Backward Euler 2')\n    axC.plot(tA,nA,color='black',label='Analytic')\n    axC.legend()\n    # figC.savefig('radioactive_FE_BE.png')\n\ndef plotFEvBEvT(n0,l):\n    tA = np.linspace(0,tAnal,100)\n    nA = anal(l,n0,tA)\n    t2, n2 = euler(n0,l,2.0)\n    tb2, nb2 = eulerB(n0,l,2.0)\n    tTrap, nTrap = trap(n0,l,2.0)\n    figTrap, axTrap = plt.subplots()\n    axTrap.set_title('Radioactive Decay')\n    axTrap.set_xlabel('t')\n    axTrap.set_ylabel('Decay Material')\n    axTrap.plot(t2, n2,'-o',color='red',label='Forward Euler 2')\n    axTrap.plot(tb2, nb2,'-o',color='blue',label='Backward Euler 2')\n    axTrap.plot(tTrap, nTrap,'-o',color='purple',label='Trapezoid 2')\n    axTrap.plot(tA,nA,color='black',label='Analytic')\n    axTrap.legend()\n    # figTrap.savefig('radioactive_FE_BE_Trap.png')\n\n\nif __name__ == '__main__':\n    n0 = 1.0\n    l = 1.0                         # Decay constant (lambda)\n    nStop = 0.01                    # Stop amount\n    tAnal = -np.log(nStop)          # Analytic stop time\n    print(f\"Analytic Stop Time: {tAnal}\")\n    plotFEvBEvT(n0, l)\n    plotBE_Comparo(n0, l)\n     \n", "meta": {"hexsha": "08420d1b44c450e11c949e2d48db8c230ee58aec", "size": 6529, "ext": "py", "lang": "Python", "max_stars_repo_path": "radioactive_decay.py", "max_stars_repo_name": "WarlockUnicorn/numerical_ode", "max_stars_repo_head_hexsha": "54ca00f15175a7768212fb6a2bc9dc61ed768d68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-22T02:56:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-22T02:56:44.000Z", "max_issues_repo_path": "radioactive_decay.py", "max_issues_repo_name": "WarlockUnicorn/numerical_ode", "max_issues_repo_head_hexsha": "54ca00f15175a7768212fb6a2bc9dc61ed768d68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "radioactive_decay.py", "max_forks_repo_name": "WarlockUnicorn/numerical_ode", "max_forks_repo_head_hexsha": "54ca00f15175a7768212fb6a2bc9dc61ed768d68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4327731092, "max_line_length": 79, "alphanum_fraction": 0.5526114259, "include": true, "reason": "import numpy", "num_tokens": 2367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.9099070042057362, "lm_q1q2_score": 0.8510783455838306}}
{"text": "import numpy as np\n\n\ndef trapezio(f, a, b, n=1):\n    \"\"\"\n    Metodo del trapezio per il calcolo integrale.\n\n    :param f: la funzione da integrare\n    :param a: il lowerbound di integrazione\n    :param b: l'upperbound di integrazione\n    :param n: il numero di sottointervalli da usare\n    :return: il valore dell'integrale approssimato\n    \"\"\"\n    h = (b - a) / n  # dimensione di ogni sottointervallo\n    nodi = np.arange(a, b + h, h)  # nodi che dividono il range in n sottointervalli\n    fnodi = f(nodi)  # valore della funzione nei nodi divisori\n    I = (h / 2) * (fnodi[0] + 2 * np.sum(fnodi[1:n]) + fnodi[n])  # integrale risultante\n    return I\n\n\ndef simpson(f, a, b, n=1):\n    \"\"\"\n    Metodo di Simpson per il calcolo integrale.\n\n    :param f: la funzione da integrare\n    :param a: il lowerbound di integrazione\n    :param b: l'upperbound di integrazione\n    :param n: il numero di sottointervalli da usare\n    :return: il valore dell'integrale approssimato\n    \"\"\"\n    h = (b - a) / (2 * n)  # dimensione di ogni sottointervallo considerando che simpson usa un polinomio di grado 2\n    nodi = np.arange(a, b + h, h)  # nodi che dividono il range\n    fnodi = f(nodi)  # valore della funzione nei nodi divisori\n    I = (h / 3) * (fnodi[0] + 2 * np.sum(fnodi[2:2*n:2]) + 4 * np.sum(fnodi[1:2*n:2]) + fnodi[2 * n])  # integrale risutante\n    return I\n\n\ndef integrale(f, a, b, tol, metodo, nmax=2048):\n    \"\"\"\n    Calcolo dell'integrale approssimato della funzione f tramite il metodo specificato\n    e con la scelta del numero di sottointervalli adattiva in base alla tolleranza.\n\n    :param f: la funzione da integrare\n    :param a: il lowerbound di integrazione\n    :param b: l'upperbound di integrazione\n    :param tol: la tolleranze\n    :param metodo: il metodo da utilizzare per l'integrazione\n    :param nmax: il massimo numero di sottointervalli\n    :return: il valore dell'integrale approssimato con la tolleranza specificata\n    \"\"\"\n    err = 1\n    n = 1  # numero di sottointervalli\n    I = metodo(f, a, b, n)\n    while n <= nmax and err > tol:\n        n *= 2  # raddoppio i sottointervalli\n        I2 = metodo(f, a, b, n)\n        if metodo == trapezio:\n            err = np.abs(I2 - I) / 3  # formula dell'errore per il metodo del trapezio\n        else:\n            err = np.abs(I2 - I) / 15  # formula dell errore per il metodo di Simpson\n        I = I2\n    return I, n\n", "meta": {"hexsha": "74c1ae7725beda314b32f7faf1bbf1d5cd87a571", "size": 2389, "ext": "py", "lang": "Python", "max_stars_repo_path": "metodi/integrazione/integrazione.py", "max_stars_repo_name": "alemazzo/metodi_numerici", "max_stars_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-07-08T10:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T09:56:37.000Z", "max_issues_repo_path": "metodi/integrazione/integrazione.py", "max_issues_repo_name": "alemazzo/metodi_numerici", "max_issues_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "metodi/integrazione/integrazione.py", "max_forks_repo_name": "alemazzo/metodi_numerici", "max_forks_repo_head_hexsha": "0d7d02aa392dde51abe1a4ee8ac5412f8f27736a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9206349206, "max_line_length": 124, "alphanum_fraction": 0.6442025952, "include": true, "reason": "import numpy", "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.9099069999303417, "lm_q1q2_score": 0.8510783366652205}}
{"text": "# The Perceptron Algorithm\n\nimport numpy as np \nnp.set_printoptions(suppress=True)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn import datasets\n\n# import data\ncancer = datasets.load_breast_cancer()\nX = cancer['data']\ny = cancer['target']\n\nBefore constructing the perceptron, let's define a few helper functions. The `sign` function returns `1` for positive numbers and `-1` for non-positive numbers, which will be useful since the perceptron classifies according to \n\n$$\n\\text{sign}(\\bbeta^\\top \\bx_n).\n$$\n\nNext, the `to_binary` function can be used to convert predictions in $\\{-1, +1\\}$ to their equivalents in $\\{0, 1\\}$, which is useful since the perceptron algorithm uses the former though binary data is typically stored as the latter. Finally, the `standard_scaler` standardizes our features, similar to `scikit-learn`'s `StandardScaler`. \n\n\n```{note}\nNote that we don't actually need to use the `sign` function. Instead, we could deem an observation correctly classified if $y_n \\hat{y}_n \\geq 0$ and misclassified otherwise. We use it here to be consistent with the derivation in the content section.\n```\n\ndef sign(a):\n    return (-1)**(a < 0)\n\ndef to_binary(y):\n        return y > 0 \n\ndef standard_scaler(X):\n    mean = X.mean(0)\n    sd = X.std(0)\n    return (X - mean)/sd\n\nThe perceptron is implemented below. As usual, we optionally standardize and add an intercept term. Then we fit $\\bbetahat$ with the algorithm introduced in the {doc}`concept section </content/c3/s2/perceptron>`. \n\nThis implementation tracks whether the perceptron has converged (i.e. all training algorithms are fitted correctly) and stops fitting if so. If not, it will run until `n_iters` is reached. \n\nclass Perceptron:\n\n    def fit(self, X, y, n_iter = 10**3, lr = 0.001, add_intercept = True, standardize = True):\n        \n        # Add Info #\n        if standardize:\n            X = standard_scaler(X)\n        if add_intercept:\n            ones = np.ones(len(X)).reshape(-1, 1)\n        self.X = X\n        self.N, self.D = self.X.shape\n        self.y = y\n        self.n_iter = n_iter\n        self.lr = lr\n        self.converged = False\n        \n        # Fit #\n        beta = np.random.randn(self.D)/5\n        for i in range(int(self.n_iter)):\n            \n            # Form predictions\n            yhat = to_binary(sign(np.dot(self.X, beta)))\n            \n            # Check for convergence\n            if np.all(yhat == sign(self.y)):\n                self.converged = True\n                self.iterations_until_convergence = i\n                break\n                \n            # Otherwise, adjust\n            for n in range(self.N):\n                yhat_n = sign(np.dot(beta, self.X[n]))\n                if (self.y[n]*yhat_n == -1):\n                    beta += self.lr * self.y[n]*self.X[n]\n\n        # Return Values #\n        self.beta = beta\n        self.yhat = to_binary(sign(np.dot(self.X, self.beta)))\n                    \n\nNow we can fit the model. We'll again use the {doc}`breast cancer </content/appendix/data>` dataset from `sklearn.datasets`. We can also check whether the perceptron converged and, if so, after how many iterations.\n\nperceptron = Perceptron()\nperceptron.fit(X, y, n_iter = 1e3, lr = 0.01)\n\n\nif perceptron.converged:\n    print(f\"Converged after {perceptron.iterations_until_convergence} iterations\")\nelse:\n    print(\"Not converged\")\n\nnp.mean(perceptron.yhat == perceptron.y)", "meta": {"hexsha": "113983440ee36623e252be1fc3c756b2f4572c24", "size": 3417, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/content/c3/s2/perceptron.py", "max_stars_repo_name": "curioushruti/mlbook", "max_stars_repo_head_hexsha": "a56da46354b7dc61fcfc3a134f55a803c37d919e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 970, "max_stars_repo_stars_event_min_datetime": "2020-08-31T17:28:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T11:41:17.000Z", "max_issues_repo_path": "_build/jupyter_execute/content/c3/s2/perceptron.py", "max_issues_repo_name": "curioushruti/mlbook", "max_issues_repo_head_hexsha": "a56da46354b7dc61fcfc3a134f55a803c37d919e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-08-31T17:56:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-15T03:13:25.000Z", "max_forks_repo_path": "_build/jupyter_execute/content/c3/s2/perceptron.py", "max_forks_repo_name": "curioushruti/mlbook", "max_forks_repo_head_hexsha": "a56da46354b7dc61fcfc3a134f55a803c37d919e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 193, "max_forks_repo_forks_event_min_datetime": "2020-08-31T16:25:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T18:47:49.000Z", "avg_line_length": 36.7419354839, "max_line_length": 339, "alphanum_fraction": 0.6426690079, "include": true, "reason": "import numpy", "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9511422255326288, "lm_q2_score": 0.8947894703109853, "lm_q1q2_score": 0.8510720481747527}}
{"text": "import numpy as np\r\n\r\n\r\ndef plane_error(results, target):\r\n    \"\"\"\r\n    Computes angle between target orbital plane and actually achieved plane.\r\n    \r\n    :param results: Results struct as output by flight_manager (NOT flight_sim_3d).\r\n    :param target: Target struct as output by launch_targeting.\r\n    :return: Angle between the two orbital planes.\r\n    \"\"\"\r\n    inc = results.powered[results.n-1].orbit.inc\r\n    lan = results.powered[results.n-1].orbit.lan\r\n    \r\n    Rx = np.array([[1, 0, 0],\r\n                   [0, np.cos(np.deg2rad(inc)), -np.sin(np.deg2rad(inc))],\r\n                   [0, np.sin(np.deg2rad(inc)), np.cos(np.deg2rad(inc))]])\r\n    Rz = np.array([[np.cos(np.deg2rad(lan)), -np.sin(np.deg2rad(lan)), 0],\r\n                   [np.sin(np.deg2rad(lan)), np.cos(np.deg2rad(lan)), 0],\r\n                   [0, 0, 1]])\r\n    reached = np.matmul(Rz, np.matmul(Rx, np.array([0, 0, -1])))\r\n    error = np.rad2deg(np.arccos(np.vdot(target.normal, reached)))\r\n    return error\r\n", "meta": {"hexsha": "f79b75a9bd61c34b2fa111c3abce5887ca4c276b", "size": 987, "ext": "py", "lang": "Python", "max_stars_repo_path": "kRPC/plane_error.py", "max_stars_repo_name": "ubik2/PEGAS-kRPC", "max_stars_repo_head_hexsha": "8f6628743a48a2cc700d57e62c0a49c94846f8c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kRPC/plane_error.py", "max_issues_repo_name": "ubik2/PEGAS-kRPC", "max_issues_repo_head_hexsha": "8f6628743a48a2cc700d57e62c0a49c94846f8c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kRPC/plane_error.py", "max_forks_repo_name": "ubik2/PEGAS-kRPC", "max_forks_repo_head_hexsha": "8f6628743a48a2cc700d57e62c0a49c94846f8c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-09T10:13:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-09T10:13:55.000Z", "avg_line_length": 41.125, "max_line_length": 84, "alphanum_fraction": 0.5896656535, "include": true, "reason": "import numpy", "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. Yes\n2. Yes", "lm_q1_score": 0.951142215838086, "lm_q2_score": 0.894789473818021, "lm_q1q2_score": 0.8510720428358676}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Primera parte\n\ndef integral(dim=10, n_points=100):\n    x = np.random.random((dim, n_points))\n    x_sum = np.sum(x, axis=0)\n    x_sum = np.average(x_sum**2)\n    return x_sum\n\ndef integral(dim=10, n_points=100):\n    suma = 0.0\n    for i in range(n_points):\n        x =  np.random.random(dim)\n        suma += np.sum(x*x)\n    return suma/n_points\n\ndef mean_integral(n_trial=16, dim=10, n_points=100):\n    x = 0\n    for i in range(n_trial):\n        x +=  integral(dim=dim, n_points=n_points)\n    x = x/n_trial\n    return x\n\n\nN = 2**np.arange(1,14)\nerror = []\nfor n in N:\n    error.append(np.abs(155/6-mean_integral(n_points=n))/(155/6))\n\nplt.figure()\nplt.plot(1/np.sqrt(N), error)\nplt.loglog()\nplt.title(\"$\\int_0^{1} dx_1 \\ldots \\int_0^1 dx_{10} (x_1+\\cdots x_{10})^2 $\")\nplt.ylabel(\"|error|\")\nplt.xlabel(\"1/$\\sqrt{N}$\")\nplt.savefig(\"error_1.png\")\n\n# Segunda parte\n\n#10.1\ndef f(x):\n    return np.sin(x)\n\ndef integral_analitica():\n    return np.cos(0) - np.cos(1.0)\n\ndef integral_monte_carlo(N=100):\n    x = np.random.random(N)\n    return np.sum(f(x))/N\n\nn_intentos = 10\npuntos = np.int_(np.logspace(1,5,n_intentos))\ndiferencias = np.ones(n_intentos)\nfor i in range(n_intentos):\n    a = integral_analitica()\n    b = integral_monte_carlo(N=puntos[i])\n    diferencias[i] =  (np.abs((a-b)/a))\n    \nplt.figure()\nplt.plot(puntos, diferencias)\nplt.loglog()\nplt.title(\"$\\int_0^{1} sin(x) dx$\")\nplt.xlabel(\"$N_{puntos}$\")\nplt.ylabel(\"|Error|\")\nplt.savefig(\"error_2.png\")\n\n\n# 10.2\n\ndef f(x):\n    return np.sin(x)\n\ndef integral_analitica():\n    return 1.0\n\ndef integral_monte_carlo(N=100):\n    x = np.sqrt(np.random.random(N))*np.pi/2.0\n    norm = np.pi**2/8\n    return norm * np.average(f(x))\n\nn_intentos = 10\npuntos = np.int_(np.logspace(1,5,n_intentos))\ndiferencias = np.ones(n_intentos)\nfor i in range(n_intentos):\n    a = integral_analitica()\n    b = integral_monte_carlo(N=puntos[i])\n    diferencias[i] =  (np.abs((a-b)/a))\n    \nplt.figure()\nplt.plot(puntos, diferencias)\nplt.loglog()\nplt.title(\"$\\int_0^{\\pi/2} x\\sin(x) dx$\")\nplt.xlabel(\"$N_{puntos}$\")\nplt.ylabel(\"|Error|\")\nplt.savefig(\"error_3.png\")\n", "meta": {"hexsha": "504fe594097f2bbca14547dd33c3770471f5f017", "size": 2147, "ext": "py", "lang": "Python", "max_stars_repo_path": "ejercicios/10/JaimeForero_Ejercicio10.py", "max_stars_repo_name": "oscarochoa1/FISI2028-201910", "max_stars_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-03T04:27:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T18:50:41.000Z", "max_issues_repo_path": "ejercicios/10/JaimeForero_Ejercicio10.py", "max_issues_repo_name": "oscarochoa1/FISI2028-201910", "max_issues_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ejercicios/10/JaimeForero_Ejercicio10.py", "max_forks_repo_name": "oscarochoa1/FISI2028-201910", "max_forks_repo_head_hexsha": "3d5d53d2ec0cbb2700f3dc13abc513f7def8e724", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-01-23T10:44:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-04T00:05:40.000Z", "avg_line_length": 21.9081632653, "max_line_length": 77, "alphanum_fraction": 0.6441546344, "include": true, "reason": "import numpy", "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.8947894590884704, "lm_q1q2_score": 0.8510720350220952}}
{"text": "#!/usr/bin/evn python\n\nimport os\nimport sys\nimport math\nimport pylab\nimport numpy as np\n\ndef plot_Focal_Loss(gama=2):\n\t'''FL(p_t) = -(1 - p_t)^gama * log(p_t)'''\n\tp_t = np.linspace(0,1,1000)\n\ty   = -np.power(1 - p_t, gama) * np.log(p_t)\n\n\t# compose plot\n\tpylab.title('Focal Loss')\n\tpylab.plot(p_t, y, 'co')      # same function with cyan dots\n\tpylab.plot(p_t, -np.log(p_t)) # softmax loss\n\tpylab.show() # show the plot\n\ndef plot_Gradient_of_Focal_Loss(gama=2):\n\t'''FL(p_t) = -(1 - p_t)^gama * log(p_t), here just for x instead of p_t'''\n\tp_t = np.linspace(0,1,1000)\n\ty   = np.power(1 - p_t, gama) * (gama * p_t * np.log(p_t) + p_t - 1) # if i == j\n\n\t# compose plot\n\tpylab.title('Gridient of Focal Loss')\n\tpylab.plot(p_t, y, 'co') # same function with cyan dots\n\tpylab.plot(p_t, p_t - 1) # softmax loss \n\tpylab.show() # show the plot\n\nif __name__ == '__main__':\n\t'''Loss and Gradient'''\n\tplot_Focal_Loss(gama=2)\n\tplot_Gradient_of_Focal_Loss(gama=2)\n\t\n\tpi = 0.01; bias = -np.log((1 - pi) / pi)\n\tprint \"pi:\", pi, \"bias:\", bias\n", "meta": {"hexsha": "3d59114ecf5f6c2a18df0b4f072426721c226b75", "size": 1024, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/caffe/FRCNN/focal_loss/plot.py", "max_stars_repo_name": "xyt2008/frcnn", "max_stars_repo_head_hexsha": "32a559e881cceeba09a90ff45ad4aae1dabf92a1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 198, "max_stars_repo_stars_event_min_datetime": "2018-01-07T13:44:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T12:06:16.000Z", "max_issues_repo_path": "src/caffe/FRCNN/focal_loss/plot.py", "max_issues_repo_name": "xyt2008/frcnn", "max_issues_repo_head_hexsha": "32a559e881cceeba09a90ff45ad4aae1dabf92a1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2018-02-01T13:24:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T10:51:47.000Z", "max_forks_repo_path": "src/caffe/FRCNN/focal_loss/plot.py", "max_forks_repo_name": "xyt2008/frcnn", "max_forks_repo_head_hexsha": "32a559e881cceeba09a90ff45ad4aae1dabf92a1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 82, "max_forks_repo_forks_event_min_datetime": "2018-01-06T14:21:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T09:39:58.000Z", "avg_line_length": 26.9473684211, "max_line_length": 81, "alphanum_fraction": 0.640625, "include": true, "reason": "import numpy", "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.894789457685656, "lm_q1q2_score": 0.8510720349270441}}
{"text": "'''\nCode given from professor Michael Plexousakis, instructor of the course.\nhttp://users.tem.uoc.gr/~plex/mem253-Fall2017/\n'''\n\n\nimport numpy as np\n\ndef gaussQuad(n):\n   \"\"\"\n   Return the points and weights of a Gauss quadrature rule on [0, 1] which integrates exactly\n   polynomials of degree less than or equal to n\n   \"\"\"\n   if n <= 1:\n\t   return (1, np.array([0.5]), np.array([1.0]))\n   elif n <= 3:\n\t   return (2, np.array([0.2113248654051871, 0.7886751345948129]), np.array([0.5, 0.5]))\n   else:\n\t   return (3, np.array([0.1127016653792583, 0.5, 0.8872983346207417]), np.array([0.2777777777777778, 0.4444444444444444, 0.2777777777777778]))\n\n# Test quadrature rule\n\nif __name__ ==  \"__main__\":\n    def f(x): return x**5 - 2*x**3 + 4*x**2\n\n    n, p, w = gaussQuad(5)\n    v = f(p)\n    s = np.dot(v, w)\n    print(\"exact integral = %f  approx = %f\" % (1.0, s))\n", "meta": {"hexsha": "cf8dc01566c3ecb216c6de3a73cac80cbd9b3f3d", "size": 863, "ext": "py", "lang": "Python", "max_stars_repo_path": "Finite Elements Method (given code)/gaussQuad.py", "max_stars_repo_name": "konpsar/Numerical-Methods-for-PDEs-course", "max_stars_repo_head_hexsha": "74e323ee9916fbbe59a3031aee623c44eb5d88a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Finite Elements Method (given code)/gaussQuad.py", "max_issues_repo_name": "konpsar/Numerical-Methods-for-PDEs-course", "max_issues_repo_head_hexsha": "74e323ee9916fbbe59a3031aee623c44eb5d88a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Finite Elements Method (given code)/gaussQuad.py", "max_forks_repo_name": "konpsar/Numerical-Methods-for-PDEs-course", "max_forks_repo_head_hexsha": "74e323ee9916fbbe59a3031aee623c44eb5d88a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7666666667, "max_line_length": 143, "alphanum_fraction": 0.6349942063, "include": true, "reason": "import numpy", "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9511422227627598, "lm_q2_score": 0.8947894583870631, "lm_q1q2_score": 0.8510720343549573}}
{"text": "import numpy as np\nimport pandas as pd\nimport os.path, sys\nimport math\n\ndef similarity(df,user_avg_df,a_id,b_id):\n    \"\"\"Calculates the similarity between two movies, a and b\n\n    Args:\n        df: training dataframe\n        a_id: movie a item_id\n        b_id: movie b item_id    \n    Returns:\n        float, similarity between a and b\n    \"\"\"\n\n    # the similarity between two movies is given by:\n    #\n    # the sum, over all users who have rated both a and b, of the difference between the rating given to movies a and b and the average rating that user has given for all movies\n    # divided by\n    # the square root of \n    #  (the sum of the difference between the rating user u gave to movie a and the avg of user u's ratings)\n    #   times\n    #  (the sum of the difference between the rating user u gave to movie b and the avg of user u's ratings)\n\n    # rows for users that have rated a\n    a_df = df[ df[\"item_id\"] == a_id ]\n    # rows for users that have rated b\n    b_df = df[ df[\"item_id\"] == b_id ]\n    # rows for users who have rated both\n    ab_df = a_df.merge(b_df,on=\"user_id\")\n\n    unique_user_ids = np.unique(ab_df[\"user_id\"].values)\n\n    numerator = 0.0\n    denominator_left = 0.0\n    denominator_right = 0.0\n\n    # print(\"{0} users have rated both a and b\".format(len(unique_user_ids)))\n\n    for user_id in unique_user_ids:\n        user_avg = user_avg_df[ user_avg_df[\"user_id\"] == user_id][\"rating_avg\"].values[0]\n\n        rating_a = a_df[ a_df[\"user_id\"] == user_id][\"rating\"].values[0]\n        rating_b = b_df[ b_df[\"user_id\"] == user_id][\"rating\"].values[0]\n\n        numerator += ( (rating_a - user_avg)*(rating_b - user_avg) )\n        denominator_left += (rating_a - user_avg) ** 2\n        denominator_right += (rating_b - user_avg) ** 2\n\n    denominator = math.sqrt(denominator_left + denominator_right)\n\n    if denominator == 0.0:\n        res = 0.0\n    else:\n        res = numerator / denominator\n\n    # print(\"res is {0} \\n\".format(res))\n    return(res)            \n\ndef main():\n    data_dir = os.path.join(sys.path[0],'../../data/ml-100k/ml-100k/')\n\n    target_file = data_dir+'u1.base.item_similarity'\n\n    train_df = pd.read_csv(data_dir+'u1.base',sep='\\t',names=[\"user_id\",\"item_id\",\"rating\",\"timestamp\"]).drop([\"timestamp\"],1)\n    user_avg_df = pd.read_csv(data_dir+'u1.base.user_avgs',names=[\"user_id\",\"rating_avg\"])\n\n    unique_item_ids = np.unique(train_df[\"item_id\"].values)\n\n    sim_rows = []\n\n    for i in unique_item_ids:\n        row = dict()\n        for j in unique_item_ids:\n            row[j] = similarity(train_df,user_avg_df,i,j)\n\n        sim_rows.append(row)\n\n    sim_df = pd.DataFrame(sim_rows) \n\n    sim_df.to_csv(target_file)\n\nif __name__ == '__main__':\n    main()", "meta": {"hexsha": "ec78991bb891a511aeb9e7a8c1735aac84ad1c7b", "size": 2716, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/python/src/item-based-knn/save_item_item_similarity_df.py", "max_stars_repo_name": "queirozfcom/recommendation_systems", "max_stars_repo_head_hexsha": "e96b34f71fdc3a490b39d448d47e48485ce4f7fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-03-19T00:00:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-28T12:31:15.000Z", "max_issues_repo_path": "code/python/src/item-based-knn/save_item_item_similarity_df.py", "max_issues_repo_name": "queirozfcom/recommendation_systems", "max_issues_repo_head_hexsha": "e96b34f71fdc3a490b39d448d47e48485ce4f7fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/python/src/item-based-knn/save_item_item_similarity_df.py", "max_forks_repo_name": "queirozfcom/recommendation_systems", "max_forks_repo_head_hexsha": "e96b34f71fdc3a490b39d448d47e48485ce4f7fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-02T21:16:46.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-02T21:16:46.000Z", "avg_line_length": 31.9529411765, "max_line_length": 177, "alphanum_fraction": 0.6417525773, "include": true, "reason": "import numpy", "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371972, "lm_q2_score": 0.8856314843833871, "lm_q1q2_score": 0.8510490849528397}}
{"text": "from sklearn import linear_model\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nfrom sklearn.svm import l1_min_c\nfrom pylab import scatter, show, legend, xlabel, ylabel\n\n# https://www.youtube.com/watch?v=-BQCB6Uch1g\n# from __future__ import division\n\ndef logistic_func(theta, x):\n  return float(1) / (1 + math.e**(-x.dot(theta)))\n\ndef log_gradient(theta, x, y):\n  first_calc = logistic_func(theta, x) - np.squeeze(y)\n  final_calc = first_calc.T.dot(x)\n  return final_calc\n\ndef cost_func(theta, x, y):\n  log_func_v = logistic_func(theta,x)\n  y = np.squeeze(y)\n  step1 = y * np.log(log_func_v)\n  step2 = (1-y) * np.log(1 - log_func_v)\n  final = -step1 - step2\n  return np.mean(final)\n\ndef grad_desc(theta_values, X, y, lr=.001, limit=10):\n  #normalize\n  X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)\n  #setup cost iter\n  cost_iter = []\n  i = 0\n  while(i < limit):\n    # old_cost = cost\n    theta_values = theta_values - (lr * log_gradient(theta_values, X, y))\n    cost = cost_func(theta_values, X, y)\n    cost_iter.append([i, cost])\n    i+=1\n  return theta_values, np.array(cost_iter)\n\ndef pred_values(theta, X, hard=True):\n  #normalize\n  X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)\n  pred_prob = logistic_func(theta, X)\n  pred_value = np.where(pred_prob >= .5, 1, 0)\n  if hard:\n    return pred_value\n  return pred_prob\n\ndef logistic_regression(Y, X, X_validation=[],Y_validation=[], limit=100):\n  shape = X.shape[1]\n  print(\"Dimension = (\",shape,\")\")\n  betas = np.zeros(shape)\n  fitted_values, cost_iter = grad_desc(betas, X, Y,limit=limit)\n  # print(\"Fit values =\",fitted_values)\n\n  predicted_y = pred_values(fitted_values, X)\n  print(\"Y =\",Y)\n  print(\"Predict Y =\",predicted_y)\n\n  score_y = np.sum(Y)\n\n  print(\"Y =\",score_y)\n  print(\"Predict Y =\", np.sum(predicted_y))\n  print(\"Compare predict_y and Y =\", np.sum(Y == predicted_y), \" values are equal\")\n\n  print(cost_iter)\n  plt.plot(cost_iter[:,0], cost_iter[:,1])\n  plt.ylabel(\"Cost\")\n  plt.xlabel(\"Iteration\")\n  plt.show()\n  plt.savefig('cost_iter.png')\n\n\n  #normalize data\n  # norm_X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)\n  # myargs = (norm_X, Y)\n  # betas = np.zeros(norm_X.shape[1])\n\n\n  # logreg = linear_model.LogisticRegression()\n  # logreg.fit(norm_X, Y)\n  # print(\"From 'sklearn' --> logreg.predict == Y =\", sum(Y == logreg.predict(norm_X,)))\n  # print(logreg.score(norm_X, Y))\n\n  # print(\"Computing regularization path ...\")\n  # start = datetime.now()\n  # clf = linear_model.LogisticRegression(C=1.0, penalty='l1', tol=1e-6)\n  # # coefs_ = []\n  # # cs = l1_min_c(X, Y, loss='log') * np.logspace(0, 3)\n  #\n  # cost_iter = []\n  # i = 0\n  # # for c in cs:\n  # clf.fit(X, Y)\n  # while (i < limit):\n  #   # clf.set_params(C=c)\n  #   # coefs_.append(clf.coef_.ravel().copy())\n  #   cost = float(sum(Y_validation == clf.predict(X_validation,)))/float(score_y)\n  #   cost_iter.append([i, cost])\n  #   print(i, cost, flush=True)\n  #   i += 1\n  # print(\"This took \", datetime.now() - start)\n\n  # coefs_ = np.array(coefs_)\n  # plt.plot(np.log10(cs), coefs_)\n  # ymin, ymax = plt.ylim()\n  # plt.xlabel('log(C)')\n  # plt.ylabel('Coefficients')\n  # plt.title('Logistic Regression Path')\n  # plt.axis('tight')\n  # plt.show()\n  # plt.savefig(\"cost_iter_second.png\")\n\n  # print(cost_iter)\n  # cost_iter = np.array(cost_iter)\n  # plt.plot(cost_iter[:,0], cost_iter[:,1],'-', linewidth=3)\n  # plt.ylabel(\"Cost\")\n  # plt.xlabel(\"Iteration\")\n  # plt.xlim(0, len(cost_iter[:,0]))\n  # # plt.ylim(0, 100)\n  # plt.show()\n  # plt.savefig('cost_iter.png')\n\n\n  # fitted_values, cost_iter = grad_desc(betas, norm_X, Y)\n  # predicted_y = pred_values(fitted_values, norm_X)\n  # print(\"From 'my function' --> Predict Y =\",sum(predicted_y == Y))\n  #\n  # plt.plot(cost_iter[:,0], cost_iter[:,1],'-', linewidth=3)\n  # plt.ylabel(\"Cost\")\n  # plt.xlabel(\"Iteration\")\n  # plt.show()\n", "meta": {"hexsha": "e6a06885b4f54ebd5abbbb4d213dae5ddbde0e48", "size": 3870, "ext": "py", "lang": "Python", "max_stars_repo_path": "2015s2-mo444-assignment-02/codes/logistic_regression.py", "max_stars_repo_name": "rodneyrick/MO444-PatternRecognition-and-MachineLearning", "max_stars_repo_head_hexsha": "5b0f9968b5b9e5c761cac48675118a9a755a5592", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-04T21:00:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-04T21:00:07.000Z", "max_issues_repo_path": "2015s2-mo444-assignment-02/codes/logistic_regression.py", "max_issues_repo_name": "rodneyrick/MO444-PatternRecognition-and-MachineLearning", "max_issues_repo_head_hexsha": "5b0f9968b5b9e5c761cac48675118a9a755a5592", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2015s2-mo444-assignment-02/codes/logistic_regression.py", "max_forks_repo_name": "rodneyrick/MO444-PatternRecognition-and-MachineLearning", "max_forks_repo_head_hexsha": "5b0f9968b5b9e5c761cac48675118a9a755a5592", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6666666667, "max_line_length": 88, "alphanum_fraction": 0.642377261, "include": true, "reason": "import numpy", "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517028006208, "lm_q2_score": 0.8856314813647588, "lm_q1q2_score": 0.8510490800713012}}
{"text": "import re\nimport numpy\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nimport numpy as np\nimport cv2\nfrom scipy.signal import filtfilt\n\n\ndef movingAverage(I, n):\n\t\"\"\" Creates a nxn kernel filled with ones to perform a arithmetic moving average \"\"\"\n\tkernel = np.ones(n)\n\tresult = signal.convolve2d(I, kernel, mode='valid')\n\treturn result\n\ndef gaussianMean(mu, sigma, n):\n\t\"\"\" Creates a nxn kernel following a gaussian distribution with mean=mu and std=sigma \"\"\"\n\tx = np.linspace(mu - (n-1)/2, mu + (n-1)/2, n)\n\tg = np.array([(1/(np.sqrt(2*np.pi*sigma**2)))*np.exp(-0.5*(x - mu)*(x - mu)*(1/(sigma**2)))])\n\tkernel = g.T.dot(g)\n\tkernel = kernel/np.sum(kernel)\n\treturn kernel\n\ndef gradient(I, tipo : str = 'sobel'):\n\t\"\"\" Compute the gradient of an image using either sobel or prewitt method using a 3x3 method\"\"\"\n\n\t# Defining kernels\n\txsobel = np.array([[-1, 0, 1],[-2, 0, 2],[-1, 0, 1]])\n\tysobel = xsobel.T\n\txprewitt = np.array([[-1, 0, 1],[-1, 0, 1],[-1, 0, 1]])\n\typrewitt = xprewitt.T\n\n\tif tipo.lower() == 'sobel':\n\t\tdelfdelx = signal.convolve2d(I, np.rot90(xsobel,2), mode='valid')\n\t\tdelfdely = signal.convolve2d(I, np.rot90(ysobel,2), mode='valid')\n\telif tipo.lower() == 'prewitt':\n\t\tdelfdelx = signal.convolve2d(I, np.rot90(xprewitt,2), mode='valid')\n\t\tdelfdely = signal.convolve2d(I, np.rot90(yprewitt,2), mode='valid')\n\treturn np.sqrt(delfdely**2 + delfdelx**2)\n\ndef laplacian(I, tipo : str = 'torre'):\n\t\"\"\" Computes the laplacian of an image using either one of two options for kernel \"\"\"\n\n\t# Defining kernels\n\ttorre = np.array([[0, 1, 0],[1, -4, 1],[0, 1, 0]])\n\tdama = np.array([[1, 1, 1],[1, -8, 1],[1, 1, 1]])\n\tif tipo.lower() == 'torre':\n\t\tresult = signal.convolve2d(I, np.rot90(torre,2), mode='valid')\n\telif tipo.lower() == 'dama':\n\t\tresult = signal.convolve2d(I, np.rot90(dama,2), mode='valid')\n\treturn result\n", "meta": {"hexsha": "844bb9f79672a85e6dbc8954820721169c0e18d6", "size": 1830, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/FilteringMasks.py", "max_stars_repo_name": "awcasella/Imagens-Biomedicas-UNIFESP-SJC-EngBio", "max_stars_repo_head_hexsha": "ec65cda70b73337177d71a08732c56c74317ccc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-05T15:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T06:39:47.000Z", "max_issues_repo_path": "Python/FilteringMasks.py", "max_issues_repo_name": "awcasella/Imagens-Biomedicas-UNIFESP-SJC-EngBio", "max_issues_repo_head_hexsha": "ec65cda70b73337177d71a08732c56c74317ccc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/FilteringMasks.py", "max_forks_repo_name": "awcasella/Imagens-Biomedicas-UNIFESP-SJC-EngBio", "max_forks_repo_head_hexsha": "ec65cda70b73337177d71a08732c56c74317ccc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1923076923, "max_line_length": 96, "alphanum_fraction": 0.6557377049, "include": true, "reason": "import numpy,from scipy", "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517095103499, "lm_q2_score": 0.885631470799559, "lm_q1q2_score": 0.8510490758610018}}
{"text": "import numpy\nimport scipy.stats as st\nfrom matplotlib import pyplot\nimport math\n\n\ndef confidenceIntervalForNormalDistribution(mean, deviation, confidence):\n    confidence /= 100\n    significancePoint = 1 - confidence\n    z = st.norm.ppf(confidence + significancePoint/2)  # This function looking for in the Standard normal table\n    z = round(z, 2)  # We round z to 2 decimals\n    x1 = mean - z*deviation\n    x1 = round(x1, 2)\n\n    x2 = mean + z*deviation\n    x2 = round(x2, 2)\n    return [x1, x2, significancePoint]\n\n\ndef confidenceIntervalForPopulationMean(deviation, sample, sampleMean, confidence):\n    confidence /= 100\n    significancePoint = 1 - confidence\n    z = st.norm.ppf(confidence + significancePoint/2)  # This function looking for in the Standard normal table\n    z = round(z, 2)  # round function rounds a number to decimals what you want\n    x1 = sampleMean - z*(deviation/math.sqrt(sample))\n    x1 = round(x1, 2)\n\n    x2 = sampleMean + z*(deviation/math.sqrt(sample))\n    x2 = round(x2, 2)\n    return [x1, x2, significancePoint]\n\n\ndef graphConfidenceInterval(mean, deviation, confidence, x1, x2, significancePoint, printMean=True):\n    x = numpy.linspace(mean - 3 * deviation, mean + 3 * deviation, 300)\n    function = (1 / (deviation * math.sqrt(2 * math.pi))) * math.e ** ((-1 / 2) * (((x - mean) / deviation) ** 2))\n\n    pyplot.title('Intervalo De Confianza')\n    pyplot.grid()\n    pyplot.fill_between(x, function, 0,\n                        where=(x > x1) & (x < x2),\n                        color='c')\n    pyplot.fill_between(x, function, 0,\n                        where=(x >= mean - 3 * deviation) & (x <= x1),\n                        color='y')\n    pyplot.fill_between(x, function, 0,\n                        where=(x >= x2) & (x <= mean + 3 * deviation),\n                        color='y'\n                        )\n    pyplot.plot(x, function)\n    meanInY = (1 / (deviation * math.sqrt(2 * math.pi))) * math.e ** ((-1 / 2) * (((mean - mean) / deviation) ** 2))\n    if printMean:\n        pyplot.plot(mean, meanInY, marker=\".\", color=\"r\")\n        pyplot.text(mean, meanInY, f\"μ={mean}\", fontsize=15)\n    else:\n        pyplot.text(mean, meanInY, \"μ\", fontsize=20)\n\n    pyplot.text(mean - deviation / 3, meanInY / 2, f\"{confidence}%\", fontsize=25)\n    pyplot.plot(x1, 0, marker=\".\", color=\"r\")\n    pyplot.text(x1, meanInY/25, f\"X1={x1}\")\n    pyplot.plot(x2, 0, marker=\".\", color=\"r\")\n    pyplot.text(x2, 0, f\"X2={x2}\")\n    a = (1 / (deviation * math.sqrt(2 * math.pi))) * math.e ** (\n                (-1 / 2) * (((((mean - 3 * deviation) + x1) / 2 - mean) / deviation) ** 2))\n    b = (1 / (deviation * math.sqrt(2 * math.pi))) * math.e ** (\n                (-1 / 2) * (((((mean + 3 * deviation) + x2) / 2 - mean) / deviation) ** 2))\n    pyplot.text(((mean - 4.05 * deviation) + x1) / 2, a, f\"{round(significancePoint / 2, 1)}%\", fontsize=15)\n    pyplot.text(((mean + 3 * deviation) + x2) / 2, b, f\"{round(significancePoint / 2, 1)}%\", fontsize=15)\n    pyplot.show()\n", "meta": {"hexsha": "a0bac2e9822b8921bd1ff64f387f3c1593a91243", "size": 2990, "ext": "py", "lang": "Python", "max_stars_repo_path": "Model/confidenceInterval.py", "max_stars_repo_name": "cdlavila/Confidencial-Intervals-with-Python", "max_stars_repo_head_hexsha": "0b347fb577928c6cf74179e148be2de423d5e4f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-09T15:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T15:16:43.000Z", "max_issues_repo_path": "Model/confidenceInterval.py", "max_issues_repo_name": "cdlavila/Confidencial-Intervals-with-Python", "max_issues_repo_head_hexsha": "0b347fb577928c6cf74179e148be2de423d5e4f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Model/confidenceInterval.py", "max_forks_repo_name": "cdlavila/Confidencial-Intervals-with-Python", "max_forks_repo_head_hexsha": "0b347fb577928c6cf74179e148be2de423d5e4f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3333333333, "max_line_length": 116, "alphanum_fraction": 0.5765886288, "include": true, "reason": "import numpy,import scipy", "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769127862449, "lm_q2_score": 0.8723473763375644, "lm_q1q2_score": 0.8510419602845817}}
{"text": "# Mathematics > Linear Algebra Foundations > Eigenvalue of matrix #3\n# Basic problems related to eigenvalues.\n#\n# https://www.hackerrank.com/challenges/eigenvalues-of-matrix-3/problem\n#\n\nimport numpy as np\n\na = np.matrix([[2, -1], [-1, 2]])\n\nprint(np.linalg.eigvalsh(a))\nprint(np.linalg.eigvalsh(a * a))\n\n\"\"\"\nréponse:\n\n1\n3\n1\n9\n\"\"\"", "meta": {"hexsha": "3984e10c0c17ca7b4bb2bc3dbeda24bf1697b42f", "size": 330, "ext": "py", "lang": "Python", "max_stars_repo_path": "mathematics/linear-algebra-foundations/eigenvalues-of-matrix-3.py", "max_stars_repo_name": "PingHuskar/hackerrank", "max_stars_repo_head_hexsha": "1bfdbc63de5d0f94cd9e6ae250476b4a267662f2", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2018-05-11T07:54:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T19:02:32.000Z", "max_issues_repo_path": "mathematics/linear-algebra-foundations/eigenvalues-of-matrix-3.py", "max_issues_repo_name": "PingHuskar/hackerrank", "max_issues_repo_head_hexsha": "1bfdbc63de5d0f94cd9e6ae250476b4a267662f2", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-13T10:03:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T10:21:05.000Z", "max_forks_repo_path": "mathematics/linear-algebra-foundations/eigenvalues-of-matrix-3.py", "max_forks_repo_name": "PingHuskar/hackerrank", "max_forks_repo_head_hexsha": "1bfdbc63de5d0f94cd9e6ae250476b4a267662f2", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2019-01-23T19:06:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T16:03:47.000Z", "avg_line_length": 15.7142857143, "max_line_length": 71, "alphanum_fraction": 0.6939393939, "include": true, "reason": "import numpy", "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769106559808, "lm_q2_score": 0.8723473647220786, "lm_q1q2_score": 0.8510419470944517}}
{"text": "import numpy as np\n\ndef cosine_similarity (a, b):\n\n    \"\"\" Computes cosine similarity for two vector inputs. \n        cosine(X, Y) = <X, Y> / (||X||*||Y||)\n        :param vector a, b: vectors to calculate cosine for\n        :returns: cosine of a, b\n\n    \"\"\"\n    if a is None:\n        a = 0\n    if b is None:\n        b = 0\n\n    norm_a = np.linalg.norm(a)\n    norm_b = np.linalg.norm(b)\n    adotb  = np.dot(a,b)\n\n    return adotb / (norm_a * norm_b)\n\ndef cos_distance (a,b):\n    return 1 - cosine_similarity (a,b)\n", "meta": {"hexsha": "a8c1f4e7c955deb1096659d52d457f8cc039ae0a", "size": 512, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pset_utils/vio/similarity.py", "max_stars_repo_name": "nhvinh118/pset-4-5", "max_stars_repo_head_hexsha": "7927f122579264a7964243c932185f1bc2371045", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pset_utils/vio/similarity.py", "max_issues_repo_name": "nhvinh118/pset-4-5", "max_issues_repo_head_hexsha": "7927f122579264a7964243c932185f1bc2371045", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pset_utils/vio/similarity.py", "max_forks_repo_name": "nhvinh118/pset-4-5", "max_forks_repo_head_hexsha": "7927f122579264a7964243c932185f1bc2371045", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3333333333, "max_line_length": 59, "alphanum_fraction": 0.55859375, "include": true, "reason": "import numpy", "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673113726775, "lm_q2_score": 0.884039278690883, "lm_q1q2_score": 0.8510408450741245}}
{"text": "import numpy as np\nimport matplotlib.pylab as plt\nfrom scipy import linalg as la\n\ndef PCA(dat, center=False, percentage=0.8):\n    M = dat[:,0].size\n    N = dat[0,:].size\n    if center:\n        mu = np.mean(dat,0)\n        dat -= mu\n\n    U, L, Vh = la.svd(dat, full_matrices=False)\n    \n    V = (Vh.T).conjugate()\n    SIGMA = np.diag(L)\n    X = U.dot(SIGMA)\n    Lam = L**2\n\n    sLam = Lam.sum()\n    csum = [Lam[:i+1].sum()/sLam for i in xrange(N)]\n\n    normalized_eigenvalues = Lam/sLam\n    for i, x in np.ndenumerate(csum):\n        if not x < percentage :\n            n_components = i[0]\n            break\n        \n    return normalized_eigenvalues, \n            V[:,0:n_components],\n            SIGMA[0:n_components,0:n_components],\n            X[:,0:n_components]\n\ndef scree(normalized_eigenvalues):\n    plt.plot(normalized_eigenvalues, 'b-', normalized_eigenvalues, 'bo')\n    plt.xlabel(\"Principal Components\")\n    plt.ylabel(\"Percentage of Variance\")\n    plt.show()\n", "meta": {"hexsha": "81734f2df64bc518e2e4552d21e42a36d89bb13e", "size": 969, "ext": "py", "lang": "Python", "max_stars_repo_path": "Labs/LSI/PCA.py", "max_stars_repo_name": "m4webb/numerical_computing", "max_stars_repo_head_hexsha": "d26e5ace9dbb91cd87440d84f0bd05d4a46e6781", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Labs/LSI/PCA.py", "max_issues_repo_name": "m4webb/numerical_computing", "max_issues_repo_head_hexsha": "d26e5ace9dbb91cd87440d84f0bd05d4a46e6781", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Labs/LSI/PCA.py", "max_forks_repo_name": "m4webb/numerical_computing", "max_forks_repo_head_hexsha": "d26e5ace9dbb91cd87440d84f0bd05d4a46e6781", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-08T01:19:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T01:19:23.000Z", "avg_line_length": 25.5, "max_line_length": 72, "alphanum_fraction": 0.5913312693, "include": true, "reason": "import numpy,from scipy", "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731094431571, "lm_q2_score": 0.8840392817460332, "lm_q1q2_score": 0.851040844228349}}
{"text": "# Pollard p-1 factorization Method\n\nimport math\n\nfrom sympy import isprime\n\n\n# function to generate\n# prime factors\ndef pollard(number: int) -> int:\n    # defining base.\n    base: int = 2\n    # defining exponent.\n    exponent: int = 2\n\n    # iterate till a prime factor is obtained\n    while (True):\n        # recomputing a as required\n        base = (base ** exponent) % number\n        # finding gcd of a-1 and n\n        # using math function\n        d = math.gcd((base - 1), number)\n\n        # check if factor obtained\n        if (d > 1):\n            # return the factor\n            return d\n\n        # else increase exponent by one\n        # for next round\n        exponent += 1\n\n\nif __name__ == \"__main__\":\n    # user input\n    NUMBER = int(input(\"Enter the number whose factor is to be found: \"))\n    # temporarily storing n\n    num = NUMBER\n    # list for storing prime factors\n    ans: list[int] = []\n\n    # iterated till all prime factors\n    # are obtained\n    while (True):\n        # function call\n        d = pollard(num)\n        # add obtained factor to list\n        ans.append(d)\n        # reduce n\n        r = int(num / d)\n\n        if (isprime(r)):\n            # both prime factors obtained\n            ans.append(r)\n            break\n\n        # reduced n is not prime, so repeat\n        else:\n            num = r\n\n    print(\"Prime factors of\", NUMBER, \"are\", *ans)\n", "meta": {"hexsha": "27bd84581a0d9ca5eab6a6e1e80392cb4a18e894", "size": 1380, "ext": "py", "lang": "Python", "max_stars_repo_path": "Codes/Math/pollards_factorisation.py", "max_stars_repo_name": "datta-agni/python-codes", "max_stars_repo_head_hexsha": "d902d0aaf23d2ea4b60ed7ecab0d593e3334c23b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Codes/Math/pollards_factorisation.py", "max_issues_repo_name": "datta-agni/python-codes", "max_issues_repo_head_hexsha": "d902d0aaf23d2ea4b60ed7ecab0d593e3334c23b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Codes/Math/pollards_factorisation.py", "max_forks_repo_name": "datta-agni/python-codes", "max_forks_repo_head_hexsha": "d902d0aaf23d2ea4b60ed7ecab0d593e3334c23b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2580645161, "max_line_length": 73, "alphanum_fraction": 0.5550724638, "include": true, "reason": "from sympy", "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446440948805, "lm_q2_score": 0.8740772335247532, "lm_q1q2_score": 0.8510406169466461}}
{"text": "#!/usr/bin/env python3\n\"\"\"Normalization Constants\"\"\"\nimport numpy as np\n\n\ndef normalization_constants(X):\n    \"\"\"normalization_constants: calculates the normalization (standardization)\n                                constants of a matrix\n\n    Args:\n        X: is the numpy.ndarray of shape (m, nx) to normalize\n            m is the number of data points\n            nx is the number of features\n    Returns: the mean and standard deviation of each feature, respectively.\n    \"\"\"\n    m = np.mean(X, axis=0)\n    s = np.std(X, axis=0)\n    return m, s\n", "meta": {"hexsha": "9dbaa223ad9ef47b80f61c10ce5856d494c9500d", "size": 549, "ext": "py", "lang": "Python", "max_stars_repo_path": "supervised_learning/0x03-optimization/0-norm_constants.py", "max_stars_repo_name": "cbarros7/holbertonschool-machine_learning", "max_stars_repo_head_hexsha": "1edb4c253441f6319b86c9c590d1e7dd3fc32bf4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-09T19:12:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T19:12:22.000Z", "max_issues_repo_path": "supervised_learning/0x03-optimization/0-norm_constants.py", "max_issues_repo_name": "cbarros7/holbertonschool-machine_learning", "max_issues_repo_head_hexsha": "1edb4c253441f6319b86c9c590d1e7dd3fc32bf4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "supervised_learning/0x03-optimization/0-norm_constants.py", "max_forks_repo_name": "cbarros7/holbertonschool-machine_learning", "max_forks_repo_head_hexsha": "1edb4c253441f6319b86c9c590d1e7dd3fc32bf4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8947368421, "max_line_length": 78, "alphanum_fraction": 0.6265938069, "include": true, "reason": "import numpy", "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.9005297947939938, "lm_q1q2_score": 0.8509958924194799}}
{"text": "\"\"\"\nThis example shows how ALGOPY can be used for linear error propagation.\n\nConsider the error model::\n\n    y = x + \\epsilon\n\nwhere x a vector and \\epsilon a random variable with zero mean and\ncovariance matrix \\Sigma^2. The y is the observed quantity and x is a real vector\nrepresenting the \"true\" value.\n\nOne can find some estimator \\hat x that is in some or another way optimal.\nFor instance one take 100 samples and obtain y_1,y_2,....,y_100 and take the\narithmetic mean as an estimator for x. In the following we simply assume that \nsome estimate \\hat x is known and has an associated confidence region described \nby its covariance matrix Sigma^2 = E[(\\hat x - E[\\hat x])(\\hat x - E[\\hat x])^T]\n\nHowever, not \\hat x is of interest but some function f(\\hat x)::\n\n    f: R^N ---> R^M\n        \\hat x ---> \\hat x = f(\\hat x)\n\nThe question is:\n\n    What can we say about the confidence region of the function f(y) when\n    the confidence region of y is described by the covariance matrix \\Sigma^2?\n\nFor affine (linear) functions::\n\n    z = f(y) = Ay + b\n        \nthe procedure is described in the \nwikipedia article http://en.wikipedia.org/wiki/Propagation_of_uncertainty .\n\nFor nonlinear functions can be linearized about an estimate \\hat y of E[y].\nIn the vicinity of \\hat y, the linear model approximates the nonlinear function often quite well.\n\nTo linearize the function, the Jacobian J(\\hat y) of the function f(\\hat y) has to be computed, i.e.:\n\n    z \\approx f(y) = f(\\hat y) + J(\\hat y) (y - \\hat y)\n\nThe covariance matrix of z is defined as C = E[z z^T] = E[ J y y^T J^T] = J \\Sigma^2 J^T.\nThat means if we know J(y), we can approximately compute the confidence region if\nf(\\hat y) is sufficiently linear.\n\nTo compute the Jacobian one can use the forward and the reverse mode of AD:\nIn the forward mode of AD one computes Nm directional derivatives, i.e. P = Nm.\nIn the reverse mode of AD one computes M adjoint derivatives, i.e. Q = M.\n\"\"\"\n\nimport numpy\nfrom algopy import CGraph, Function, UTPM, dot, qr, eigh, inv, zeros\n\ndef f(y):\n    retval = zeros((3,1),dtype=y)\n    retval[0,0] = numpy.log(dot(y.T,y))\n    retval[1,0] = numpy.exp(dot(y.T,y))\n    retval[2,0] = numpy.exp(dot(y.T,y)) -  numpy.log(dot(y.T,y))\n    return retval\n    \nD,Nm = 2,40\nP = Nm\ny = UTPM(numpy.zeros((2,P,Nm)))\n\ny.data[0,:] = numpy.random.rand(Nm)\ny.data[1,:] = numpy.eye(Nm)\n\n\n# print f(y)\nJ = f(y).data[1,:,:,0]\nprint('Jacobian J(y) = \\n', J)\n\nC_epsilon = 0.3*numpy.eye(Nm)\n\nprint(J.shape)\n\nC = dot(J.T, dot(C_epsilon,J))\n\nprint('Covariance matrix of z: C = \\n',C)\n        \n    \n        \n\n    \n \n", "meta": {"hexsha": "8965e24c430309f58335e66a10e5f1d97baba3c5", "size": 2586, "ext": "py", "lang": "Python", "max_stars_repo_path": "documentation/examples/error_propagation.py", "max_stars_repo_name": "arthus701/algopy", "max_stars_repo_head_hexsha": "1e2430f803289bbaed6bbdff6c28f98d7767835c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2015-03-05T13:38:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T11:54:48.000Z", "max_issues_repo_path": "documentation/examples/error_propagation.py", "max_issues_repo_name": "arthus701/algopy", "max_issues_repo_head_hexsha": "1e2430f803289bbaed6bbdff6c28f98d7767835c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2016-04-06T11:25:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-09T13:53:20.000Z", "max_forks_repo_path": "documentation/examples/error_propagation.py", "max_forks_repo_name": "arthus701/algopy", "max_forks_repo_head_hexsha": "1e2430f803289bbaed6bbdff6c28f98d7767835c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:05:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-05T01:13:16.000Z", "avg_line_length": 30.0697674419, "max_line_length": 101, "alphanum_fraction": 0.6747873163, "include": true, "reason": "import numpy", "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100816, "lm_q2_score": 0.900529793459209, "lm_q1q2_score": 0.8509958869730399}}
{"text": "import numpy as np\nimport sympy as sp\nimport control\n\ns, w = sp.symbols('s w')\n\ndef computeResolvent(A, imag=False, smplfy=True):\n    \"\"\"\n    compute resolvent of a square matrix (see Eqn 3.49)\n\n    Inputs:\n        A (numpy matrix/array) - real square matrix\n        imag (bool) - (default=False) use s=i*w for computation\n        smplfy (bool) - (default=True) do partial fraction decomposition on resolvent\n\n    Returns:\n        resolvent, (sI-A)**(-1), Eqn. 3.49 in the book\n    \"\"\"\n    assert(A.shape[0] == A.shape[1])\n    nRows = A.shape[0]  # == nCols\n    if imag:\n        res = ((sp.I*w)*sp.eye(nRows) - A)**-1\n    else:\n        res = (s*sp.eye(nRows) - A)**-1\n    if not smplfy:\n        return res\n    # perform partial fraction decomposition term-by-term\n    for i in range(res.shape[0]):\n        for j in range(res.shape[1]):\n            # apart does partial fraction decomp automatically\n            res[i,j] = sp.apart(sp.simplify(res[i,j]), s)\n    return res\n\ndef firstCompanionForm(num, den):\n    \"\"\"\n    compute first companion form given single-input single-output (SISO) transfer function representation\n    see Eqns. 3.88-3.94\n\n    Inputs:\n        num (sympy Poly) - transfer function numerator\n        den (sympy Poly) - transfer function denominator\n\n    Returns:\n        sympy matrices A, B, C, D with\n        x_dot = Ax + Bu\n        y = Cx + Du\n        for the First Companion form discussed in the book\n    \"\"\"\n    #single-input, single-output\n    # H(s) = num / den\n    # convert to H(s)\n    # den = s^k + a1*s^(k-1) + a2*s^(k-2)+...\n    a = den.coeffs()\n    # num = b0*s^k + b1*s^(k-1)+...\n    b = num.coeffs()\n    # append the coefficients array if there is no constant term in the numerator\n    if sp.degree(num) > len(num.coeffs())-1:\n        b.append(0)\n    if sp.degree(den) > len(den.coeffs())-1:\n        a.append(0)\n    # if the denominator has higher order than the numerator, prepend 0's for the leading coeffs until\n    # a,b have the same size\n    if len(a) > len(b):\n        # prepend b\n        for i in range(len(a)-len(b)):\n            b.insert(0,0)\n    # construct A, B matrices (Eqn 3.88)\n    A = sp.zeros(len(a)-1)\n    for i in range(A.shape[0]-1):\n        A[i, i+1] = 1\n    # coefficients order is reversed (w.r.t. the book's convention) by sp, so reverse it to \n    # match the book's convention\n    a.reverse()\n    b.reverse()\n    for i in range(A.shape[0]):\n        A[-1, i] = -a[i]\n    B = sp.zeros(A.shape[0], 1)\n    B[-1] = 1\n    # construct C,D matrices (Eqn 3.94) \n    C = sp.zeros(1, A.shape[1])\n    for i in range(C.shape[1]):\n        C[0, i] = b[i] - a[i]*b[-1]\n    D = sp.Matrix([b[-1]])\n    return A, B, C, D\n\n\ndef jordanForm(num, den, D=sp.Matrix([0])):\n    \"\"\"\n    compute partial fraction decomposition Jordan form given single-input single-output (SISO) transfer function representation\n    see Eqns. 3.108, 3.111, and 3.116\n\n    Inputs:\n        num (sympy Poly) - transfer function numerator\n        den (sympy Poly) - transfer function denominator\n        D (sympy Matrix) - (default=Matrix([0]) direct path from input u to output y\n\n    Returns:\n        sympy matrices A, B, C, D with\n        x_dot = Ax + Bu\n        y = Cx + Du\n        for the Jordan form discussed in the book\n\n    Raises:\n        NotImplementedError - raised when one of the following three conditions is encountered:\n                                (1) repeated roots\n                                (2) order(numer of decomposed system) > 1\n                                (3) order(denom of decomposed system) > 2\n    \"\"\"\n    uniqueRoots = np.unique(np.array(den.all_roots()).astype('complex'))\n    order = den.degree()\n    if uniqueRoots.size < order:\n        raise NotImplementedError('Method for repeated roots is not implemented.')\n    num = sp.factor(num)\n    den = sp.factor(den)\n    pd = sp.apart(num/den)\n    A = sp.zeros(order, order)\n    B = sp.zeros(order, 1)\n    C = sp.zeros(1, order)\n    idx = 0\n    for i, p in enumerate(pd.args):\n        n, d = sp.fraction(p)\n        # extract multiplicative factor from the denomintor\n        # - the desired form for each term in the partial fraction decomposition is a / (s + r), with a, r some real numbers\n        _d = sp.factor(sp.Poly(d.as_expr(), s))\n        multFactor = _d.func(*[term for term in _d.args if not term.free_symbols])\n        # numerator\n        numerCoeffs = sp.Poly(n.as_expr(), s).all_coeffs()\n        if len(numerCoeffs) == 1:\n            # constant poly\n            b, a = numerCoeffs[0] / multFactor, 0\n        elif len(numerCoeffs) == 2:\n            # linear poly\n            b, a = [_n / multFactor for _n in numerCoeffs]\n        else:\n            raise NotImplementedError('Order of numerator {num} is too large for this method.'.format(num=sp.Poly(n.as_expr(), s)))\n        # denominator\n        denPoly = sp.Poly(d.as_expr(), s)\n        if denPoly.degree() == 2:\n            # this will only happen there are complex conjugate pairs\n            cq, bq, aq = denPoly.all_coeffs()\n            # need to set a subsystem here (see Eqn. 3.111)\n            twoTimesSigma, sigmaSqPlusOmegaSq = bq / aq, cq / aq\n            twoTimesLambda, twoTimesCrossProd = b, a\n            A[idx, idx+1] = 1\n            A[idx+1, idx] = -sigmaSqPlusOmegaSq\n            A[idx+1, idx+1] = -twoTimesSigma\n            B[idx+1] = 1\n            C[0, idx] = twoTimesCrossProd\n            C[0, idx+1] = twoTimesLambda\n            idx += 2\n        elif denPoly.degree() == 1:\n            poles = sp.polys.polyroots.roots_linear(denPoly)\n            A[idx, idx] = poles[0]\n            B[idx] = 1\n            C[0, idx] = b\n            idx += 1\n        else:\n            NotImplementedError('Order of denominator {den} is too large for this method.'.format(den=denPoly))\n    return A, B, C, D", "meta": {"hexsha": "59fc2f6ba11d28544ffd58b6d48fd5905079c5ba", "size": 5779, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ch3/utilities.py", "max_stars_repo_name": "jwdinius/friedland-csd-solutions", "max_stars_repo_head_hexsha": "2d7fec1b6055ea9777dc931bc1cf0f0df6c8ed7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-03-24T12:06:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T17:56:51.000Z", "max_issues_repo_path": "Ch3/utilities.py", "max_issues_repo_name": "jwdinius/friedland-csd-solutions", "max_issues_repo_head_hexsha": "2d7fec1b6055ea9777dc931bc1cf0f0df6c8ed7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-31T04:19:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T21:16:28.000Z", "max_forks_repo_path": "Ch3/utilities.py", "max_forks_repo_name": "jwdinius/friedland-csd-solutions", "max_forks_repo_head_hexsha": "2d7fec1b6055ea9777dc931bc1cf0f0df6c8ed7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-10-05T04:23:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T21:17:17.000Z", "avg_line_length": 36.3459119497, "max_line_length": 131, "alphanum_fraction": 0.5722443329, "include": true, "reason": "import numpy,import sympy", "num_tokens": 1649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100817, "lm_q2_score": 0.9005297921244243, "lm_q1q2_score": 0.8509958857116754}}
{"text": "import numpy as np\n\ndef verifica_quadrada(matriz_A):\n    linhas, colunas = np.shape(matriz_A)\n    return linhas == colunas\n\ndef verifica_inversa(matriz_A):\n    if verifica_quadrada(matriz_A):\n        print(\"A matriz é quadrada\")\n        det = np.linalg.det(matriz_A)\n        print(\"O determinante da matriz é:\", det)\n        return det != 0\n    print(\"A matriz não é quadrada\")\n    return False\n\ndef verifica_simetria(matriz_A):\n    if verifica_quadrada(matriz_A):\n        n = len(matriz_A)\n        for i in range(n):\n            for j in range(n):\n                if (i != j) and (matriz_A[i,j] != matriz_A[j,i]):\n                    print(\"A matriz não é simétrica\")\n                    return False\n        print(\"A matriz é simétrica\")\n        return True\n    print(\"A matriz não é quadrada\")\n    return False\n\ndef verifica_pos_def(matriz_A):\n    if verifica_quadrada(matriz_A) and verifica_inversa(matriz_A) and verifica_simetria(matriz_A):\n        n = len(matriz_A)\n        for i in range(n):\n            soma = 0\n            for j in range(n):\n                soma += matriz_A[i,j]\n            if(soma == 0):\n                return False\n        return True\n    return False\n\ndef verifica_tridiagonal(matriz_A):\n    linhas, colunas = np.shape(matriz_A)\n\n    for i in range(linhas):\n        for j in range(colunas):\n            if np.abs(i-j) <= 1 and matriz_A[i,j] == 0:\n                return False\n            if np.abs(i-j) >= 2 and matriz_A[i,j] != 0:\n                return False\n    return True\n\ndef verifica_tri_superior(matriz_A, tol=1e-10):\n    linhas = len(matriz_A)\n\n    for i in range(linhas):\n        for j in range(i):\n            if np.fabs(matriz_A[i,j]) > tol:\n                return False\n    return True\n\ndef verifica_tri_inferior(matriz_A, tol=1e-10):\n    colunas = len(matriz_A[0])\n\n    for j in range(colunas):\n        for i in range(j):\n            if np.fabs(matriz_A[i,j]) > tol:\n                return False\n    return True\n\ndef traco(matriz_A):\n    linhas, colunas = np.shape(matriz_A)\n    n, traco = min((linhas, colunas)), 0\n\n    print(matriz_A)\n    for i in range(n):\n        traco += matriz_A[i,i]\n    return traco\n\ndef traco_maior_que_quatro(traco):\n    if traco > 4:\n        print(\"O traço da matriz é \"+ str(traco) +\", portanto é maior que 4\")\n        return True\n    print(\"O traço da matriz é \"+ str(traco) +\", portanto não é maior que 4\")\n    return False\n\n''' CRITÉRIOS DE CONVERGÊNCIA DOS MÉTODOS ITERATIVOS '''\n\ndef criterio_linhas(matriz_A): # Verificar o critério das linhas para o método de Jacobi\n    n, m = len(matriz_A), len(matriz_A[0]) # n e m são as dimensões da matriz\n    soma = 0\n\n    for i in range(n): # Percorre toda a matriz\n        for j in range(m):\n            if i != j: # Desconsidera os termos da diagonal principal\n                soma += np.abs(matriz_A[i,j])\n\n        if soma >= np.abs(matriz_A[i,i]): # Verifica se a soma de todos os termos (sem contar o termo da diagonal principal) de cada linha é menor ou maior que o termo da diagonal principal (Critério das linhas)\n            return False\n\n        soma = 0\n    return True\n\ndef criterio_sassenfeld(matriz_A):\n    n, m = len(matriz_A), len(matriz_A[0]) # n e m são as dimensões da matriz\n    aux = 0 # Variável que auxilia nos somatórios dos termos tanto de Aij*Beta, quanto de Aij\n    vetor_betao = np.zeros(m) # Vetor de Betas iniciado com termos iguais a zero\n\n    for i in range(n):\n        for j in range(i): # j vai até i-1 (desconsidera a primeira iteração)\n            aux += np.abs(matriz_A[i,j]) * vetor_betao[j] # A partir da segunda iteração, inclui a multiplicação de Aij pelos Betas anteriores no somatório (já que na primeira iteração não há Betas anteriores, obviamente)\n        for j in range(i,n):\n            aux += np.abs(matriz_A[i,j]) # Somatório dos módulos dos termos de Aij\n        vetor_betao[i] = aux/np.abs(matriz_A[i,i]) #Divide o valor da soma pelo termo da diagonal principal\n        aux = 0 # Zera a variável auxiliar pra próxima iteração\n    \n    print(\"Maior betão:\", np.max(vetor_betao))\n    if np.max(vetor_betao) < 1: # Verifica se a condição do critério de Sassenfeld (max(B) < 1) é satisfeita\n        return True\n    return False", "meta": {"hexsha": "eca5c582430589177b8959953e9194af1d150f43", "size": 4197, "ext": "py", "lang": "Python", "max_stars_repo_path": "criterios.py", "max_stars_repo_name": "eRRe-i/algebra-linear-computacional", "max_stars_repo_head_hexsha": "f2caffdb33aed0fad9d811b20f6505ad6513d824", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "criterios.py", "max_issues_repo_name": "eRRe-i/algebra-linear-computacional", "max_issues_repo_head_hexsha": "f2caffdb33aed0fad9d811b20f6505ad6513d824", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "criterios.py", "max_forks_repo_name": "eRRe-i/algebra-linear-computacional", "max_forks_repo_head_hexsha": "f2caffdb33aed0fad9d811b20f6505ad6513d824", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.268907563, "max_line_length": 221, "alphanum_fraction": 0.6166309269, "include": true, "reason": "import numpy", "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538936, "lm_q2_score": 0.9005297761070067, "lm_q1q2_score": 0.8509958803404761}}
{"text": "# %%\r\n\"\"\"We wanna get familiar with array manipulation(File 17-21).\"\"\"\r\nimport numpy as np\r\n# %%\r\nhelp(np.transpose)\r\n# %%\r\narray1 = np.arange(1, 11).reshape(5, 2)\r\narray1\r\n# %%\r\nnp.transpose(array1)\r\n# %%\r\narray1.shape\r\n# %%\r\nnp.transpose(array1).shape\r\n# %%\r\na = np.arange(1, 25).reshape(2, 3, 4)\r\na\r\n# %%\r\nnp.transpose(a)\r\n# %%\r\nnp.transpose(a).shape\r\n# %%\r\na = np.arange(1, 10)\r\na\r\n# %%\r\nnp.transpose(a)\r\n# %%\r\nnp.transpose(array1, axes=(1, 0))\r\n# %%\r\nnp.transpose(array1, axes=(0, 1))\r\n# %%\r\na = np.arange(1, 25).reshape(2, 3, 4)\r\na\r\n# %%\r\n\"\"\"\r\nIn the a we had:\r\naxis 0: 2\r\naxis 1: 3\r\naxis 2: 4\r\nNow we wanna reshape the 3d array to (3, 4, 2).\r\n\"\"\"\r\nnp.transpose(a, axes=(1, 2, 0))\r\n# %%\r\na.transpose()\r\n# %%\r\na.T\r\n# %%\r\nhelp(np.swapaxes)\r\n# %%\r\n\"\"\"\r\nSwap the first and second array.\r\nThe new shape will be (3, 2, 4)/\r\n\"\"\"\r\nnp.swapaxes(a, 0, 1)\r\n# %%\r\na = np.arange(1, 5).reshape(2, 2)\r\na\r\n# %%\r\nnp.swapaxes(a, 0, 1)\r\n# %%\r\nnp.swapaxes(a, 1, 0)\r\n# %%\r\na = np.array([[1, 2, 3]])\r\na\r\n# %%\r\na.shape\r\n# %%\r\na.swapaxes(0, 1)\r\n# %%\r\na.swapaxes(1, 0)\r\n# %%\r\na = np.arange(1, 25).reshape(2, 3, 4)\r\na\r\n# %%\r\nnp.swapaxes(a, 1, 2)\r\n# %%\r\nnp.swapaxes(a, 1, 2).shape\r\n# %%\r\n\"\"\"\r\nDifferences:\r\nnp.swapaxes just swaps only two axes\r\nbut in np.transpose we can swap all the axes.\r\n\"\"\"\r\n", "meta": {"hexsha": "c429814401c68cf81a3194094ecbdf1642010c29", "size": 1275, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumPy/19_TransposeAndSwapaxes.py", "max_stars_repo_name": "ErfanRasti/PythonCodes", "max_stars_repo_head_hexsha": "5e4569b760b60c9303d5cc68650a2448c9065b6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-01T09:59:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T09:59:22.000Z", "max_issues_repo_path": "NumPy/19_TransposeAndSwapaxes.py", "max_issues_repo_name": "ErfanRasti/PythonCodes", "max_issues_repo_head_hexsha": "5e4569b760b60c9303d5cc68650a2448c9065b6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumPy/19_TransposeAndSwapaxes.py", "max_forks_repo_name": "ErfanRasti/PythonCodes", "max_forks_repo_head_hexsha": "5e4569b760b60c9303d5cc68650a2448c9065b6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.1785714286, "max_line_length": 65, "alphanum_fraction": 0.5388235294, "include": true, "reason": "import numpy", "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.9230391627161538, "lm_q1q2_score": 0.8509699624946069}}
{"text": "# --------------------------------------------------------- #\n# ----- Square Matrix Multiplication - divide and conquer - #\n# ----- Strassen's Method --------------------------------- #\n# ----- Number of operations:    n**log(2, 7) == n**2.8  -- #\n# ----- Running time T(n) =                         ------- #\n# --------------------------------------------------------- #\n\nimport numpy as np\nimport sys\n\nsys.path.insert(0, 'C:\\\\Users\\\\ARMEN\\\\Desktop\\Algorithms')\nsys.setrecursionlimit(5000)\n\nnumRows = 16\nnumColumns = 16\nnumOfOperations = 0\n\nmatrixA = np.zeros((numRows, numColumns))\nmatrixB = np.zeros((numRows, numColumns))\nmatrixD = np.zeros((numRows, numColumns)) \n\ncount = 0\nfor i in range(numRows):\n    for j in range(numRows):\n        count += 1\n        matrixA[i, j] = count\n        matrixB[i, j] = count*10\n\ndef SQUARE_MATRIX_MULTIPLY_RECURSIVE(matrixA, matrixB):\n    global numOfOperations\n    n = len(matrixA)\n    matrixC = np.zeros((n , n)) \n   \n    if(n==0):\n        return matrixC\n    if(n==1):\n        matrixC[0, 0] = matrixA[0, 0]*matrixB[0, 0]\n    else:\n        m = n//2\n\n        A11 = matrixA[0:m, 0:m]\n        A12 = matrixA[0:m, m:n]\n        A21 = matrixA[m:n, 0:m]\n        A22 = matrixA[m:n, m:n]\n        \n        B11 = matrixB[0:m, 0:m]\n        B12 = matrixB[0:m, m:n]\n        B21 = matrixB[m:n, 0:m]\n        B22 = matrixB[m:n, m:n]\n        \n        S1 = B12 - B22\n        S2 = A11 + A12\n        S3 = A21 + A22\n        S4 = B21 - B11\n        S5 = A11 + A22\n        S6 = B11 + B22\n        S7 = A12 - A22\n        S8 = B21 + B22\n        S9 = A11 - A21\n        S10= B11 + B12\n        \n        P1 = A11 * S1\n        P2 = S2 * B22\n        P3 = S3 * B11\n        P4 = A22 * S4\n        P5 = S5 * S6\n        P6 = S7 * S8\n        P7 = S9 * S10\n        \n        C11 = P5 + P4 - P2 + P6\n        C12 = P1 + P2\n        C21 = P3 + P4\n        C22 = P5 + P1 - P3 - P7\n        matrixC[0:m, 0:m] =  C11\n        matrixC[0:m, m:n] =  C12\n        matrixC[m:n, 0:m] =  C21\n        matrixC[m:n, m:n] =  C22\n        n = n//2\n    print(matrixC)\n    numOfOperations += 1\n    return matrixC\n\nprint('Multiplication started')\n\nSQUARE_MATRIX_MULTIPLY_RECURSIVE(matrixA, matrixB)\n\nprint('Multiplication finished')\nprint('Number of operations: ', numOfOperations)\n\n\n\n", "meta": {"hexsha": "50ef8e8eb4d11d6913cb2ac0f244997acf4cb919", "size": 2254, "ext": "py", "lang": "Python", "max_stars_repo_path": "MATRIX_MULT_Strassen.py", "max_stars_repo_name": "ArmenBaghdasaryan14/Algorithms", "max_stars_repo_head_hexsha": "8581947c8e73d50bb3324377dea7914afc066de6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MATRIX_MULT_Strassen.py", "max_issues_repo_name": "ArmenBaghdasaryan14/Algorithms", "max_issues_repo_head_hexsha": "8581947c8e73d50bb3324377dea7914afc066de6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MATRIX_MULT_Strassen.py", "max_forks_repo_name": "ArmenBaghdasaryan14/Algorithms", "max_forks_repo_head_hexsha": "8581947c8e73d50bb3324377dea7914afc066de6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5, "max_line_length": 61, "alphanum_fraction": 0.4702750665, "include": true, "reason": "import numpy", "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542887603537, "lm_q2_score": 0.8872046056466901, "lm_q1q2_score": 0.8509661025139611}}
{"text": "'''\nProblem 2: R^2\n10.0/10.0 points (graded)\nAfter we create some regression models, we also want to be able to evaluate our models to figure out how well each model represents our data, and tell good models from poorly fitting ones. One way to evaluate how well the model describes the data is computing the model's R^2 value. R^2 provides a measure of how well the total variation of samples is explained by the model.\n\nImplement the function r_squared. This function will take in:\n\nlist, y, that represents the y-coordinates of the original data samples\nestimated, which is a corresponding list of y-coordinates estimated from the regression model\nThis function should return the computed R^2 value. You can compute R^2 as follows, where ei is the estimated y value for the i-th data point (i.e. predicted by the regression), yi is the y value for the ith data point, and mean is the mean of the original data samples.\n\nR2=1−∑ni=1(yi−ei)2∑ni=1(yi−mean)2\nIf you are still confused about R^2 , its wikipedia page has a good explanation about its use/how to calculate it.\n\nNote: If you want to use numpy arrays, you should add the following lines at the beginning of your code for the grader:\nimport os\nos.environ[\"OPENBLAS_NUM_THREADS\"] = \"1\"\nThen, do import numpy as np and use np.METHOD_NAME in your code. Unfortunately, pylab does not work with the grader.\n'''\n\nimport os\nos.environ[\"OPENBLAS_NUM_THREADS\"] = \"1\"\nimport numpy as np\n\n\ndef r_squared(y, estimated):\n    \"\"\"\n    Calculate the R-squared error term.\n    Args:\n        y: list with length N, representing the y-coords of N sample points\n        estimated: a list of values estimated by the regression model\n    Returns:\n        a float for the R-squared error term\n    \"\"\"\n    error = sum([(y_ - e_) ** 2 for e_, y_ in zip(estimated, y)])\n    meanError = error / len(y)\n    return 1 - (meanError / np.var(y))\n", "meta": {"hexsha": "776fb83a61336b3f2edcc9d70ce68abf64225f92", "size": 1873, "ext": "py", "lang": "Python", "max_stars_repo_path": "unit_04/problem_set_04/problem_02_r2.py", "max_stars_repo_name": "alexmalme/mit_6002", "max_stars_repo_head_hexsha": "744a469fc024bb495497225a0d24251afa544fe5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_04/problem_set_04/problem_02_r2.py", "max_issues_repo_name": "alexmalme/mit_6002", "max_issues_repo_head_hexsha": "744a469fc024bb495497225a0d24251afa544fe5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_04/problem_set_04/problem_02_r2.py", "max_forks_repo_name": "alexmalme/mit_6002", "max_forks_repo_head_hexsha": "744a469fc024bb495497225a0d24251afa544fe5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.2894736842, "max_line_length": 375, "alphanum_fraction": 0.7378537106, "include": true, "reason": "import numpy", "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9591542852576264, "lm_q2_score": 0.8872046011730965, "lm_q1q2_score": 0.8509660951154588}}
{"text": "# Computes the volume of a 10-dimensional sphere using midpoint integration\n\nimport math as math\nimport numpy as np\nfrom scipy.optimize import curve_fit\nfrom time import process_time\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nfrom matplotlib.ticker import MaxNLocator\n\n# Returns a list of n equidistant points between -bound and bound\ndef discretization(bound, n):\n\treturn np.linspace(-float(bound) + float(bound) / n, float(bound) + float(bound) / n, n, False)\n\n# Recursively computes an integral of a dim-dimensonal sphere\n# with radius sqrt(radius). Pass volume2 = 1 at start.\n# n is the number of points used for the midpoint method.\ndef recursiveIntegral(radius2, volume2, dim, n):\n    volume2 *= radius2 * 2 * 2  / (n * n)\n    if (dim > 1):\n        partIntegral = 0\n        for x in discretization(math.sqrt(radius2), n):\n            partIntegral += recursiveIntegral(radius2 - x * x, volume2, dim - 1, n)\n    else:\n        partIntegral = math.sqrt(volume2) * n\n\n    return partIntegral\n\n\n# Monte Carlo approximation of the volume of a dim-dimensonal sphere\n# with radius sqrt(radius)\ndef montecarlo(dim, radius, N):\n    count_in_sphere = 0\n\n    for count_loops in range(N):\n        point = np.random.uniform(-1.0, 1.0, dim)\n        distance = np.linalg.norm(point)\n        if distance < 1.0:\n            count_in_sphere += 1\n\n    return np.power(2.0, dim) * (count_in_sphere / N)\n\n# The number of dimensions\nnumDims = 10\n\ntimelist = []\nerrorlist = []\n\nerrorlist1 = [0.9682663823341708, 0.1660809555237166, 0.15717487652157347,\n             0.1251325819655884, 0.09438377397356268] \ntimelist1 = [0.10271, 0.429084, 3.925878, 23.295996, 111.834063] \n\nerrorlist2 = [1.1533329367039888, 0.5112814632959886, 0.31594107517154857,\n              0.10376734000000003, 0.10376734000000003, 0.057765464637436814,\n              0.03379026373290017]\ntimelist2 = [0.02383748, 0.04916397, 0.07693159, 0.10376734000000003,\n             0.2895373, 0.5990030300000001, 0.9335681499999999]\ndef calculate(t, error):\n    print('time =', t)\n    print('error   =', error)\n    print('')\n    timelist.append(t)\n    errorlist.append(error)\n\ndef graph(errorlist, timelist, col, title):\n    fig, ax = plt.subplots()\n    plt.title(title, fontsize = 18)\n    ax.plot(errorlist, timelist, color = col)\n    ax.plot(errorlist, timelist, 'o', color = col)\n    plt.xlabel(\"Integration error\", fontsize = 18)\n    plt.ylabel(\"Computational time (s)\", fontsize = 18)\n    ax.tick_params(axis='both', which='major', labelsize=14)\n    plt.show()\n\n# The number of points in the midpoint method along one dimension\n\npointlist = [2, 3, 4, 5]\nanalytical = math.pi**(numDims / 2) / math.factorial(numDims / 2)\n\niterationlist = [750,1000,2500,5000,7500,\n                10000, 25000, 50000, 75000, 100000]\n\n##for point in pointlist:\n##    t = process_time()\n##    integral = recursiveIntegral(1, 1, numDims, point)\n##    t = process_time() - t\n##    error = abs(integral- analytical)\n##    calculate(t, error)\n\nfor iteration in iterationlist:\n    f2 = []\n    t = process_time()\n    for i in range(100):\n        f2.append(montecarlo(numDims, 1, iteration))\n    t = (process_time() - t)/100\n    f1 = [i**2 for i in f2]\n    error = sqrt((sum(f1)/len(f1) - (sum(f2)/len(f2))**2)/100)\n    calculate(t, error)\n\ngraph(errorlist, timelist, 'tab:red', 'Monte Carlo estimation')                           \n#graph(errorlist1, timelist1, 'tab:blue', 'Midpoint method')  \n#graph(errorlist1, timelist1, 'tab:blue','Midpoint method')\n\n", "meta": {"hexsha": "cf1f45b6ad35975447ef9f644fc42825f98c2dfc", "size": 3503, "ext": "py", "lang": "Python", "max_stars_repo_path": "Project 3/3.1.py", "max_stars_repo_name": "raymondw99/SI1336", "max_stars_repo_head_hexsha": "a88a0347f4f80b702146d24a91c378a21774d7e2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project 3/3.1.py", "max_issues_repo_name": "raymondw99/SI1336", "max_issues_repo_head_hexsha": "a88a0347f4f80b702146d24a91c378a21774d7e2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project 3/3.1.py", "max_forks_repo_name": "raymondw99/SI1336", "max_forks_repo_head_hexsha": "a88a0347f4f80b702146d24a91c378a21774d7e2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6826923077, "max_line_length": 96, "alphanum_fraction": 0.6685697973, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154281754899, "lm_q2_score": 0.8872046041554923, "lm_q1q2_score": 0.8509660948684007}}
{"text": "'''\nMatrix Decomposition on TensorFlow\nAuthor: Rowel Atienza\nProject: https://github.com/roatienza/Deep-Learning-Experiments\n'''\n# On command line: python decomposition.py\n# Prerequisite: tensorflow (see tensorflow.org)\n\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy as np\nimport numpy.linalg as la\n\nprint(\"Tensorflow version: \" + tf.__version__)\n# Real symmetric matrix S of rank 2\nS = tf.constant([ [1.,2.], [2.,1.] ])\nprint(\"S = \")\nprint(S.eval(session=tf.Session()))\n\n# Eigen Decomposition - for square symmetric matrices only\n# self_adjoint_eig works only bec symmetric matrix is equal to its self adjoint\n# otherwise, use np.linalg.eig\ne,Q = tf.self_adjoint_eig(S)\n# Diagonal matrix made of eigenvalues of S\nV = tf.diag(e)\n# S_ = S since S = Q*V*tran(Q) for real symmetric matrix\nS_ = tf.matmul(Q,tf.matmul(V,Q))\nprint(\"S_ = S = \")\nprint(S_.eval(session=tf.Session()))\n\n# SVD decomposition\nd, U, V1 = tf.svd(S, full_matrices=True, compute_uv=True)\n# U and V1 are orthogonal matrices; I must be therefore an identity matrix\nI = tf.matmul(U,tf.transpose(V1))\nprint(\"I = \")\nprint(I.eval(session=tf.Session()))\nD = tf.diag(d)\n# S_ = S since S = U*D*tran(V1)\nprint(\"S_ = S = \")\nS_ = tf.matmul(U,tf.matmul(D,tf.transpose(V1)))\nprint(S_.eval(session=tf.Session()))\n\n# Moore-Penrose pseudoinverse\n# For non-square matrices, padding of m-n zero columns needed (see linear_inv.y)\nD = tf.transpose(tf.diag(np.reciprocal(d)))\nprint(\"pseudo_inv(S) = \")\nS_ = tf.matmul(V1,tf.matmul(D,tf.transpose(U)))\nprint(S_.eval(session=tf.Session()))\n\n# inverse of S BUT applicable to non-singular square matrices only\nprint(\"inv(S) = \")\nprint(tf.matrix_inverse(S).eval(session=tf.Session()))\n", "meta": {"hexsha": "42b650e1206a111e3c3922f93a622b7162e03bfe", "size": 1703, "ext": "py", "lang": "Python", "max_stars_repo_path": "Experiments/Tensorflow/Math/decomposition.py", "max_stars_repo_name": "merang/Deep-Learning-Experiments", "max_stars_repo_head_hexsha": "c53b7ded52631996e560b33cdf30ce915b18d079", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 994, "max_stars_repo_stars_event_min_datetime": "2017-01-17T11:56:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:51:40.000Z", "max_issues_repo_path": "Experiments/Tensorflow/Math/decomposition.py", "max_issues_repo_name": "akiljames83/Deep-Learning-Experiments", "max_issues_repo_head_hexsha": "8048b91f382667e9b43078460fb792b369f8af49", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2017-06-01T01:30:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-11T17:27:51.000Z", "max_forks_repo_path": "Experiments/Tensorflow/Math/decomposition.py", "max_forks_repo_name": "akiljames83/Deep-Learning-Experiments", "max_forks_repo_head_hexsha": "8048b91f382667e9b43078460fb792b369f8af49", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 789, "max_forks_repo_forks_event_min_datetime": "2017-02-16T08:53:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T14:33:39.000Z", "avg_line_length": 31.537037037, "max_line_length": 80, "alphanum_fraction": 0.7222548444, "include": true, "reason": "import numpy", "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.8872045937171068, "lm_q1q2_score": 0.8509660900357716}}
{"text": "import math\nimport numpy \nfrom numpy.linalg import svd\n \nA = [\n    [-1, 3, -1],\n    [-3, 5, -1],\n    [-3, 3, 1]\n]\n \nU, singularValues, V = svd(A) \n#NOTE: svd(movieRatings) outputs some part1,part2,part3, so the equal sign is assigned to all terms, U singularValues, and V, not just V alone \n#this defines U as output 1, singularValues as output 2, V as output 3 \n#V is the main \nLambda=singularValues\n\nprint \"The singular values are: \", singularValues #This gives U as an output when you run the file so you can see the SVD stuff works\n\n\nr= 0*numpy.ndarray(shape=(len(U),len(V))) \nfor i in range(len(Lambda)):\n    r[i][i]= abs(Lambda[i]) \n    \nprint \"Here's the SVD Lambda matrix: \", numpy.matrix(r) \n\n#print r[0][2], \" ---> Test if that's definitionally equiv to zero: \", r[0][2] == 0\n\n#print numpy.ndarray.tolist(numpy.matrix(r))\n\n#print \"U is: \", U\n#print \"V is: \", V\n\n#print numpy.dot(U,numpy.transpose(V))\nprint \"=====================================^^^SVD stuff^^^=====================================\"\n\n\neigenVals, eigVecs = numpy.linalg.eig(A)\n\nprint eigenVals\nprint len(eigenVals)\ndiagonalizedForm= 0.0*numpy.ndarray(shape=(len(eigenVals),len(eigenVals))) \nfor i in range(len(eigenVals)):\n    diagonalizedForm[i][i]= abs(eigenVals[i]) \n    \n#print diagonalizedForm\nprint \"Here's the diagonalized form of the matrix: \", numpy.matrix(diagonalizedForm)\n#numpy.ndarray.tolist( numpy.matrix(diagonalizedForm) )\n\nprint numpy.zeros( (3,3) ) #gives 3 by 3 matrix of all zeros, important for defns ", "meta": {"hexsha": "229fff2a47420dd34b19a27cad59261c23d8a6d9", "size": 1498, "ext": "py", "lang": "Python", "max_stars_repo_path": "svdNormalMatrix.py", "max_stars_repo_name": "GeorgeDavila/QuantumMatrixProductStates2", "max_stars_repo_head_hexsha": "02cc06ce41c17580629a45c868d2c3bcddd94a3a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-09-30T13:46:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T02:25:57.000Z", "max_issues_repo_path": "svdNormalMatrix.py", "max_issues_repo_name": "GeorgeDavila/QuantumMatrixProductStates2", "max_issues_repo_head_hexsha": "02cc06ce41c17580629a45c868d2c3bcddd94a3a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "svdNormalMatrix.py", "max_forks_repo_name": "GeorgeDavila/QuantumMatrixProductStates2", "max_forks_repo_head_hexsha": "02cc06ce41c17580629a45c868d2c3bcddd94a3a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5714285714, "max_line_length": 143, "alphanum_fraction": 0.6562082777, "include": true, "reason": "import numpy,from numpy", "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.8872045907347108, "lm_q1q2_score": 0.8509660871751937}}
{"text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndata = pd.read_csv('height_weight.csv',usecols=['height','weight'])\n\n#Co-Variance - Checking variance of one column with respect to another\n#It has both variance and correlation combined into 1 matrix\n#           (       a,a         a,b  )\n#          (    Var         Var       )\n#   Cov = (                            )\n#          (       b,a         b,b    )\n#           (   Var         Var     )\nprint(data.head())\nprint()\n\n\"\"\"\nprint(\"Incorrect covariance\")\ncovariance = np.cov(data)\nprint(covariance) #this expects each row and column to be a different variable\n\"\"\"\nprint()\nprint()\n#correct it by transposing or rowvar=False\ncovariance = np.cov(data.T) # or covariance = np.cov(data,rowvar=False)\nprint(\"Covariance\")\nprint(covariance)\nprint()\nprint()\nprint(\"Covariance\")\ncovariance_pandas = data.cov()\nprint(covariance_pandas)\nprint()\nprint()\n\n\n#CORRELATION formula\n#https://www.thoughtco.com/how-to-calculate-the-correlation-coefficient-3126228\n#np.corrcoef or pd.DataFrame.corr\n#Value of correlation goes from -1 to 1\n# 1 = one variable goes up other does too\n# -1 = One variable going up and other going down\n\ncorref = np.corrcoef(data.T)\nprint(\"Correlation\")\nprint(corref)\nprint()\nprint(\"Pandas Correlation\")\nprint()\nprint(data.corr())\n# If variable can be derived from one another they are correlated\n", "meta": {"hexsha": "e75bd8729bb17d4f5c96eabdb5a6c67ceba221ba", "size": 1382, "ext": "py", "lang": "Python", "max_stars_repo_path": "multi_dist.py", "max_stars_repo_name": "WestHamster/Feature_engg", "max_stars_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multi_dist.py", "max_issues_repo_name": "WestHamster/Feature_engg", "max_issues_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multi_dist.py", "max_forks_repo_name": "WestHamster/Feature_engg", "max_forks_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5769230769, "max_line_length": 79, "alphanum_fraction": 0.6678726483, "include": true, "reason": "import numpy", "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542805873231, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.850966076669055}}
{"text": "import numpy as np\nfrom si.util.scale import StandardScaler\n\nclass PCA:\n\n    def __init__(self, ncomponents = 2, using = \"svd\"):\n        # ncomponents must be int\n        if ncomponents > 0 and isinstance(ncomponents, int):\n            self.ncomponents = round(ncomponents)\n        else:\n            raise Exception(\"Number of components must be non negative and an integer\")\n        self.type = using\n    \n    def transform(self, dataset):\n        scaled = StandardScaler().fit_transform(dataset).X.T       # scale the features/standardize data\n\n        # using numpy.linalg.svd:\n        if self.type.lower()  == \"svd\": \n            self.u, self.s, self.vh = np.linalg.svd(scaled)\n        else:\n            self.cov_matrix = np.cov(scaled)                       # covariance matrix\n            # s are eigenvalues, u are eigenvectors\n            self.s, self.u = np.linalg.eig(self.cov_matrix)        # Compute the eigenvalues and eigenvectors\n        self.idx = np.argsort(self.s)[::-1]                        # sort the indexes (descending order)\n        self.eigen_val =  self.s[self.idx]                         # reorganize by index\n        self.eigen_vect = self.u[:, self.idx]                      # reorganize eigen vectors by column index\n\n        self.sub_set_vect = self.eigen_vect[:, :self.ncomponents]  # ordered vectors with principal components \n        return scaled.T.dot(self.sub_set_vect)                     # features scaled . vetores proprios ordenados\n\n\n    def variance_explained(self):\n        # find the explained variance   \n        sum_ = np.sum(self.eigen_val)\n        percentage = [i / sum_ * 100 for i in self.eigen_val]       # percentagem da var explicada valor próprio / soma dos valores próprios * 100\n        return np.array(percentage)\n\n    def fit_transform(self, dataset):\n        trans = self.transform(dataset)\n        exp = self.variance_explained()\n        return trans, exp", "meta": {"hexsha": "4fc98acbaddae33dd140a7fc9a8a1fc7fe4a0e2a", "size": 1918, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/si/unsupervised/PCA.py", "max_stars_repo_name": "TeresaCoimbra/si", "max_stars_repo_head_hexsha": "03a27de46947dd26dcf6ea54efda86cb8ec69a99", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/si/unsupervised/PCA.py", "max_issues_repo_name": "TeresaCoimbra/si", "max_issues_repo_head_hexsha": "03a27de46947dd26dcf6ea54efda86cb8ec69a99", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/si/unsupervised/PCA.py", "max_forks_repo_name": "TeresaCoimbra/si", "max_forks_repo_head_hexsha": "03a27de46947dd26dcf6ea54efda86cb8ec69a99", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7804878049, "max_line_length": 146, "alphanum_fraction": 0.6079249218, "include": true, "reason": "import numpy", "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854164256365, "lm_q2_score": 0.8774767986961401, "lm_q1q2_score": 0.8509642026273707}}
{"text": "\n# Various Wind Calculations\n#   Change wind speed and direction to U and V components\n#   Change U and V components to direction\n#   Change U and V components to speed\n#   Calculate the angle between two vecors [u1,v1] and [u2,v2]\n\nimport numpy as np\n\ndef wind_spddir_to_uv(wspd,wdir):\n    \"\"\"\n    calculated the u and v wind components from wind speed and direction\n    Input:\n        wspd: wind speed\n        wdir: wind direction\n    Output:\n        u: u wind component\n        v: v wind component\n    \"\"\"\n\n    rad = 4.0*np.arctan(1)/180.\n    u = -wspd*np.sin(rad*wdir)\n    v = -wspd*np.cos(rad*wdir)\n\n    return u,v\n\ndef wind_uv_to_dir(U,V):\n    \"\"\"\n    Calculates the wind direction from the u and v component of wind.\n    Takes into account the wind direction coordinates is different than the\n    trig unit circle coordinate. If the wind directin is 360 then returns zero\n    (by %360)\n    Inputs:\n      U = west/east direction (wind from the west is positive, from the east is negative)\n      V = south/noth direction (wind from the south is positive, from the north is negative)\n    \"\"\"\n    WDIR= (270-np.rad2deg(np.arctan2(V,U)))%360\n    return WDIR\n\ndef wind_uv_to_spd(U,V):\n    \"\"\"\n    Calculates the wind speed from the u and v wind components\n    Inputs:\n      U = west/east direction (wind from the west is positive, from the east is negative)\n      V = south/noth direction (wind from the south is positive, from the north is negative)\n    \"\"\"\n    WSPD = np.sqrt(np.square(U)+np.square(V))\n    return WSPD\n\n\n# Below is used for calculing the angle between two wind vectors\ndef unit_vector(vector):\n    \"\"\" Returns the unit vector of the vector.  \"\"\"\n    return vector / np.linalg.norm(vector)\n\ndef angle_between(v1, v2):\n    \"\"\"\n    Calcualates the angle between two wind vecotrs. Utilizes the cos equation:\n                cos(theta) = (u dot v)/(magnitude(u) dot magnitude(v))\n\n    Input:\n        v1 = vector 1. A numpy array, list, or tuple with\n             u in the first index and v in the second --> vector1 = [u1,v1]\n        v2 = vector 2. A numpy array, list, or tuple with\n             u in the first index and v in the second --> vector2 = [u2,v2]\n    Output:\n    Returns the angle in radians between vectors 'v1' and 'v2'::\n            >>> angle_between((1, 0, 0), (0, 1, 0))\n            1.5707963267948966\n            >>> angle_between((1, 0, 0), (1, 0, 0))\n            0.0\n            >>> angle_between((1, 0, 0), (-1, 0, 0))\n            3.141592653589793\n    \"\"\"\n    v1_u = unit_vector(v1)\n    v2_u = unit_vector(v2)\n    angle = np.arccos(np.dot(v1_u, v2_u))\n    if np.isnan(angle):\n        if (v1_u == v2_u).all():\n            return np.rad2deg(0.0)\n        else:\n            return np.rad2deg(np.pi)\n    return np.rad2deg(angle)\n\n\n\n#--- Example -----------------------------------------------------------------#\nif __name__ == \"__main__\":\n    u = np.array([1,5,-9])\n    v = np.array([-1,-2,5])\n\n    vector1 = [u[0],v[0]]\n    vector2 = [u[1],v[1]]\n    vector3 = [u[2],v[2]]\n\n    print \"U component: \", u\n    print \"V component: \", v\n    print \"Wind Directions: \", wind_uv_to_dir(u,v)\n    print \"Wind Speeds: \", wind_uv_to_spd(u,v)\n    print \"\"\n    print \"Angle between vector 1 and 2: \", angle_between(vector1,vector2)\n    print \"Angle between vector 2 and 3: \", angle_between(vector2,vector3)\n", "meta": {"hexsha": "e4ba3a4859f7943c1dbf27146e3fa2456e80d0c4", "size": 3326, "ext": "py", "lang": "Python", "max_stars_repo_path": "SRB_MFC_WRF_Python/functions/wind_calcs.py", "max_stars_repo_name": "ksopan/WRF_Post_MFLUX", "max_stars_repo_head_hexsha": "23a2ca6f89575b10e8a46c1a96492ab0420d72cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SRB_MFC_WRF_Python/functions/wind_calcs.py", "max_issues_repo_name": "ksopan/WRF_Post_MFLUX", "max_issues_repo_head_hexsha": "23a2ca6f89575b10e8a46c1a96492ab0420d72cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SRB_MFC_WRF_Python/functions/wind_calcs.py", "max_forks_repo_name": "ksopan/WRF_Post_MFLUX", "max_forks_repo_head_hexsha": "23a2ca6f89575b10e8a46c1a96492ab0420d72cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2912621359, "max_line_length": 92, "alphanum_fraction": 0.6049308479, "include": true, "reason": "import numpy", "num_tokens": 942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854146791214, "lm_q2_score": 0.8774767922879693, "lm_q1q2_score": 0.8509641948802935}}
{"text": "from numpy import linspace, sin, pi, absolute\r\nfrom numpy.fft import rfft, rfftfreq\r\nimport matplotlib.pyplot as plt\r\n\r\n# Sampling rate\r\nfs = 100  # Hz\r\n# the total lenght of the wave\r\nlength = 1  # 2 second\r\nN = int(fs * length)\r\n# time\r\nt = linspace(0, length, num=N, endpoint=False)\r\n\r\n# Generate a sinusoid at frequency f\r\nf = 10  # Hz\r\na = 5*sin(2 * pi * f * t)\r\n# generate a composite waveform which has 2 different frequencies\r\n#f2 = 30  # Hz\r\n#a = 2* sin(2 * pi * f * t) + 2/3*sin(2 * pi * f2 * t)\r\n\r\n# Plot signal, showing how endpoints wrap from one chunk to the next\r\nplt.subplot(2, 1, 1)\r\nplt.plot(t, a, '.-')\r\nplt.plot(1, 1, 'r.')  # first sample of next chunk\r\nplt.margins(0.1, 0.1)\r\nplt.xlabel('Time [s]')\r\nplt.axhline()\r\nplt.axvline()\r\nplt.axvline(x=1/f, c='r', marker=\".\")\r\n\r\n# Use RFFT to get the amplitude of the one-sided spectrum\r\nampl = 1/N * absolute(rfft(a))\r\n# RFFT frequency bins\r\nfreqs = rfftfreq(N, 1/fs)\r\n# Plot spectrum\r\nplt.subplot(2, 1, 2)\r\nplt.stem(freqs, ampl)\r\nplt.margins(0.1, 0.1)\r\nplt.xlabel('Frequency [Hz]')\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n\r\n# Question 1:\r\n# think about how to plot sum of two sine waveform\r\n#\r\n\r\n# Solution:\r\n# uncomment Line 17&18, change f and f2 to get different results\r\n", "meta": {"hexsha": "c7a31098c136bbb5ce362bffd33ed03ea141262f", "size": 1236, "ext": "py", "lang": "Python", "max_stars_repo_path": "L04/analog_sin_plot.py", "max_stars_repo_name": "lxpwj/mtd207_lab", "max_stars_repo_head_hexsha": "eb9154b3ae1e2ccd6efc327be33f1b8d6e7a46a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "L04/analog_sin_plot.py", "max_issues_repo_name": "lxpwj/mtd207_lab", "max_issues_repo_head_hexsha": "eb9154b3ae1e2ccd6efc327be33f1b8d6e7a46a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "L04/analog_sin_plot.py", "max_forks_repo_name": "lxpwj/mtd207_lab", "max_forks_repo_head_hexsha": "eb9154b3ae1e2ccd6efc327be33f1b8d6e7a46a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2244897959, "max_line_length": 69, "alphanum_fraction": 0.6488673139, "include": true, "reason": "from numpy", "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854120593483, "lm_q2_score": 0.8774767874818409, "lm_q1q2_score": 0.8509641879205903}}
{"text": "# Objective is to predict blood pressure from age & weight. \n# R-sq values are calcualted for all combination of inputs (age only, weight only & both)\n# Data is from:\n# http://college.cengage.com/mathematics/brase/understandable_statistics/7e/students/datasets/mlr/frames/mlr02.html\n\n# The data (X1, X2, X3) are for each patient.\n# X0 = systolic blood pressure\n# X1 = age in years\n# X2 = weight in pounds\n\n# Code Flow:\n    # 1. Import all relevant libraries.\n    # 2. Load the dataset using pandas (X - input/feature, Y - output/target).\n    # 3. Plot the generated data understand the trend.\n    # 4. Create input features for all combinations.\n    # 5. get_r2 function defintion that calculates weights, predictions & final r-sq values.\n    # 6. Print results for all cases.\n    \n# 1. Imports\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n# 2. Load dataset:\ndf = pd.read_excel('mlr02.xls')\nX = df.as_matrix()\n\n# 3. Plot the data to understand the trends:\nplt.figure(1)\nplt.scatter(X[:,1],X[:,0])\nplt.xlabel('Age')\nplt.ylabel('Systolic Blood Pressure')\nplt.title('Blood pressure vs. Age')\n\nplt.figure(2)\nplt.scatter(X[:,2],X[:,0])\nplt.xlabel('Weight (pounds)')\nplt.ylabel('Systolic Blood Pressure')\nplt.title('Blood pressure vs. Weight (pounds)')\n\n# 4. Create input features for all combinations:\ndf['ones'] = 1\n\nY = df['X1']\nX = df[['X2','X3','ones']]\nX2only = df[['X2','ones']]\nX3only = df[['X3','ones']]\n\n# 5. Function definition that calcualtes weights, predictions & R-sq values:\ndef get_r2(X,Y):\n    w = np.linalg.solve(np.dot(X.T,X),np.dot(X.T,Y))\n    Yhat = np.dot(X,w)\n    # R-sq:\n    d1 = Y - Yhat\n    d2 = Y - Y.mean()\n    r2 = 1 - d1.dot(d1)/d2.dot(d2)\n\n    return r2\n\n# 6. Print results:    \nprint('the r-squared for x2 only is:',get_r2(X2only,Y))\nprint('the r-squared for x3 only is:',get_r2(X3only,Y))\nprint('the r-squared for x2 & x3 only is:',get_r2(X,Y))", "meta": {"hexsha": "988954523969d7aab8af0764e7a771b625582151", "size": 1899, "ext": "py", "lang": "Python", "max_stars_repo_path": "1.Linear Regression/1.Code - Using Theory/3.Blood Pressure Prediction.py", "max_stars_repo_name": "ananth-repos/machine-learning", "max_stars_repo_head_hexsha": "a510dcf81fab9137c33f568e73d65262667b3973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1.Linear Regression/1.Code - Using Theory/3.Blood Pressure Prediction.py", "max_issues_repo_name": "ananth-repos/machine-learning", "max_issues_repo_head_hexsha": "a510dcf81fab9137c33f568e73d65262667b3973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1.Linear Regression/1.Code - Using Theory/3.Blood Pressure Prediction.py", "max_forks_repo_name": "ananth-repos/machine-learning", "max_forks_repo_head_hexsha": "a510dcf81fab9137c33f568e73d65262667b3973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1428571429, "max_line_length": 115, "alphanum_fraction": 0.6750921538, "include": true, "reason": "import numpy", "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854111860906, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.8509641840470513}}
{"text": "\"\"\"\n円周率\n\"\"\"\n\ndef pi(digit: int) -> str:\n\tfrom sympy import N, atan\n\treturn str(N(\"((12 * atan(1/49)) + (32 * atan(1/57)) - (5 * atan(1/239)) + (12 * atan(1/110443))) * 4\", digit))\n\nif __name__ == \"__main__\":\n\tdigit = 10000\n\tprint(pi(digit))\n", "meta": {"hexsha": "bba31fffe8bfb4221317fe5165dacad202690458", "size": 241, "ext": "py", "lang": "Python", "max_stars_repo_path": "extra/pi.py", "max_stars_repo_name": "Fairy-Phy/Relium", "max_stars_repo_head_hexsha": "70ea037cea176f02e4768bde44dd5ee23af699b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extra/pi.py", "max_issues_repo_name": "Fairy-Phy/Relium", "max_issues_repo_head_hexsha": "70ea037cea176f02e4768bde44dd5ee23af699b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extra/pi.py", "max_forks_repo_name": "Fairy-Phy/Relium", "max_forks_repo_head_hexsha": "70ea037cea176f02e4768bde44dd5ee23af699b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0833333333, "max_line_length": 112, "alphanum_fraction": 0.5601659751, "include": true, "reason": "from sympy", "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854120593483, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.8509641801524012}}
{"text": "#https://github.com/QuantConnect/Tutorials/blob/master\nfrom math import log, sqrt, exp, pi\nfrom scipy.stats import norm\n\nclass BsmModel:\n\n    def __init__(self, option_type, price, strike, interest_rate, expiry, volatility, dividend_yield=0):\n        self.s = price  # Underlying asset price\n        self.k = strike  # Option strike K\n        self.r = interest_rate  # Continuous risk fee rate\n        self.q = dividend_yield  # Dividend continuous rate\n        self.T = expiry  # time to expiry (year)\n        self.sigma = volatility  # Underlying volatility\n        self.type = option_type # option type \"p\" put option \"c\" call option\n\n    def n(self, d):\n        # cumulative probability distribution function of standard normal distribution\n        return norm.cdf(d)\n\n    def dn(self, d):\n        # the first order derivative of n(d)\n        return norm.pdf(d)\n\n    def d1(self):\n        d1 = (log(self.s / self.k) + (self.r - self.q + self.sigma ** 2 * 0.5) * self.T) / (self.sigma * sqrt(self.T))\n        return d1\n\n    def d2(self):\n        d2 = (log(self.s / self.k) + (self.r - self.q - self.sigma ** 2 * 0.5) * self.T) / (self.sigma * sqrt(self.T))\n        return d2\n\n    def bsm_price(self):\n        d1 = self.d1()\n        d2 = d1 - self.sigma * sqrt(self.T)\n        if self.type == 'c':\n            price = exp(-self.r*self.T) * (self.s * exp((self.r - self.q)*self.T) * self.n(d1) - self.k * self.n(d2))\n            return price\n        elif self.type == 'p':\n            price = exp(-self.r*self.T) * (self.k * self.n(-d2) - (self.s * exp((self.r - self.q)*self.T) * self.n(-d1)))\n            return price\n        else:\n            print(\"option type can only be c or p\")\n\na = BsmModel('c', 42, 35, 0.1, 90.0/365, 0.2)\nprice = a.bsm_price()\n", "meta": {"hexsha": "fbb587e4862946a98dd17fcfc78038a9ca10b4ba", "size": 1756, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter07/7A_Sentiment/7A_Ref_run_blackScholesMerton.py", "max_stars_repo_name": "uyenphuong18406/Hands-On-Artificial-Intelligence-for-Banking", "max_stars_repo_head_hexsha": "3a10a14194368478bb8b78d3d17e9c6a7b7253db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115, "max_stars_repo_stars_event_min_datetime": "2020-06-18T15:00:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T10:13:19.000Z", "max_issues_repo_path": "Chapter07/7A_Sentiment/7A_Ref_run_blackScholesMerton.py", "max_issues_repo_name": "uyenphuong18406/Hands-On-Artificial-Intelligence-for-Banking", "max_issues_repo_head_hexsha": "3a10a14194368478bb8b78d3d17e9c6a7b7253db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-11-06T11:02:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-22T12:44:35.000Z", "max_forks_repo_path": "Chapter07/7A_Sentiment/7A_Ref_run_blackScholesMerton.py", "max_forks_repo_name": "uyenphuong18406/Hands-On-Artificial-Intelligence-for-Banking", "max_forks_repo_head_hexsha": "3a10a14194368478bb8b78d3d17e9c6a7b7253db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 60, "max_forks_repo_forks_event_min_datetime": "2020-07-22T14:53:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T10:17:59.000Z", "avg_line_length": 38.1739130435, "max_line_length": 121, "alphanum_fraction": 0.5802961276, "include": true, "reason": "from scipy", "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854120593483, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.8509641801524012}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef gaussian(x, mean, std):\n    std2 = np.power(std, 2)\n    return (1 / np.sqrt(2* np.pi * std2)) * np.exp(-.5 * (x - mean)**2 / std2)\n\n\nif __name__ == \"__main__\":\n    gauss_1 = gaussian(10, 8, 2) # 0.12098536225957168\n    gauss_2 = gaussian(10, 10, 2) # 0.19947114020071635\n\n    print(\"Gauss(10, 8, 2): {}\".format(gauss_1))\n    print(\"Gauss(10, 10, 2): {}\".format(gauss_2))\n\n    # 標準高斯分佈\n    mean = 0\n    variance = 1\n    std = np.sqrt(variance)\n\n    # Plot between -10 and 10 with .001 steps.\n    x = np.arange(-5, 5, 0.001)\n    gauss = []\n    for i in x:\n        gauss.append(gaussian(i, mean, std))\n    gauss = np.array(gauss)\n\n    plt.plot(x, gauss)\n    plt.show()\n", "meta": {"hexsha": "60f2562d19bb7ab823ff8910d39c430258f1cd35", "size": 723, "ext": "py", "lang": "Python", "max_stars_repo_path": "Sensor Fusion and Tracking/Kalman Filters/Gaussian/gaussian.py", "max_stars_repo_name": "kaka-lin/autonomous-driving-notes", "max_stars_repo_head_hexsha": "6c1b29752d6deb679637766b6cea5c6fe5b72319", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sensor Fusion and Tracking/Kalman Filters/Gaussian/gaussian.py", "max_issues_repo_name": "kaka-lin/autonomous-driving-notes", "max_issues_repo_head_hexsha": "6c1b29752d6deb679637766b6cea5c6fe5b72319", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sensor Fusion and Tracking/Kalman Filters/Gaussian/gaussian.py", "max_forks_repo_name": "kaka-lin/autonomous-driving-notes", "max_forks_repo_head_hexsha": "6c1b29752d6deb679637766b6cea5c6fe5b72319", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3225806452, "max_line_length": 78, "alphanum_fraction": 0.5809128631, "include": true, "reason": "import numpy", "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214491222695, "lm_q2_score": 0.8824278772763472, "lm_q1q2_score": 0.8509441293610153}}
{"text": "import numpy as np \nimport numpy.linalg as linalg\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\ndef center_data(raw_data):\n\t'''\n\tGiven raw_data as numpy array, where a row\n\tis an observation. Return centered data\n\n\tInput: raw_data (numpy array)\n\tReturns: centered_data (numpy array)\n\t'''\n\n\tcol_mean = raw_data.mean(axis=0)\n\tcentered_data = raw_data - col_mean\n\treturn centered_data\n\ndef graph_data3D(data, fig_name):\n\n\tfig = plt.figure()\n\n\tax = fig.add_subplot(111, projection='3d')\n\n\tcolor_list = ['r', 'g', 'b', 'y']\n\n\tfor c in range(4):\n\t\tb = data[:,-1] == c\n\t\tx0 = data[:, 0][b]\n\t\tx1 = data[:, 1][b]\n\t\tx2 = data[:, 2][b]\n\n\t\tax.scatter(x0, x1, x2, color=color_list[c])\n\n\tplt.savefig(fig_name)\n\n\ndef graph_data2D(data, groups, fig_name):\n\n\tcolor_list = ['r', 'g', 'b', 'y']\n\n\tfor c in range(4):\n\t\tb = groups == c\n\t\tx0 = data[:, 0][b]\n\t\tx1 = data[:, 1][b]\n\n\t\tplt.scatter(x0, x1, color=color_list[c])\n\n\tplt.xlim((data[:,0].min(), data[:,0].max()))\n\tplt.ylim((data[:,1].min(), data[:,1].max()))\n\tplt.savefig(fig_name)\n\n\ndef do_pca(data, comp_num):\n\t'''\n\tReturn original data mapped \n\tto first comp_num of princ components\n\n\tInputs:\n\t\t- data: (numpy array) \n\t\t- comp_num: (int) of prin comp\n\tReturns:\n\t\t- proj_data: (numpy array) of projected data\n\t'''\n\n\tcentered_data = center_data(data)\n\tvar_cov = centered_data.T @ centered_data * (1/centered_data.shape[0])\n\n\t# note: e_vecs will have COLUMNs as the corresponding eigenvectors\n\t# note: the e_vecs are already normalized, per documentation\n\te_vals, e_vecs = linalg.eig(var_cov)\n\n\te_ordering = np.argsort(e_vals)[::-1]\n\te_basis = e_vecs[e_ordering][:, 0:comp_num]\n\n\tcoeff = centered_data @ e_basis\n\n\treturn coeff\n\n\ndef do_LLE(data, out_dim, k):\n\t'''\n\tDoes local linear embedding with k nearest neighbors\n\tEach ROW in data is an observation\n\t'''\n\n\t# Loop over each observation in the data\n\tN = data.shape[0]\n\n\tw_matrix = np.zeros( (N, N) )\n\n\tw_dict = {}\n\n\tfor i in range(N):\n\n\t\t# Calculate the weights for that observation i\n\t\tcur_obs = data[i,:]\n\t\tlocal_data = data - cur_obs \n\t\tlocal_distances = linalg.norm(local_data, axis=1)\n\t\tassert local_distances.shape == (N,)\n\n\t\tordering = np.argsort(local_distances)\n\t\tassert ordering[0] == i \n\t\tk_nn_indices = ordering[1:k+1]\n\n\t\tneighborhood = local_data[k_nn_indices]\n\n\t\t# create the local Gram matrix\n\t\tK_i = neighborhood @ neighborhood.T\n\t\tones = np.ones((k,1))\n\n\t\t# Solve for w_i matrix and normalize\n\t\tw_i = linalg.inv(K_i) @ ones\n\t\tw_i = w_i / linalg.norm(w_i, axis=0)\n\n\t\t# we need to input the KNN w_i avlues into w_matrix\n\t\t#print(\"{} NN of pt {} are:\".format(k, cur_obs))\n\t\tfor j in range(k):\n\t\t\tneighbor_index = k_nn_indices[j]\n\t\t\tneighbor_weight = w_i[j]\n\t\t\tw_matrix[i,neighbor_index] = neighbor_weight\n\t\t\t#print(\"\\t pt {}\".format(data[neighbor_index,:]))\n\n\t# Construct matrix M from the sparse w_matrix\n\tn_I = np.identity(N)\n\tM = (n_I - w_matrix).T @ (n_I - w_matrix)\n\n\te_vals, e_vecs = linalg.eigh(M)\n\tproj = e_vecs[:, 1:1+out_dim]\n\n\treturn proj\n\n\ndef do_iso(data, k, proj_dim):\n\n\tN = data.shape[0]\n\n\t# step1: calcualte the pairwise distances\n\tpairwise_distances = np.empty( (N,N) )\n\tfor i in range(N):\n\t\tfor j in range(N):\n\t\t\tx_i = data[i,:]\n\t\t\tx_j = data[j,:]\n\t\t\tdiff = x_i - x_j\n\t\t\tnorm_diff = linalg.norm(diff)\n\t\t\tpairwise_distances[i,j] = norm_diff\n\n\t# step2: calculate the nearest neighbors for each column\n\tdist_w_inf = np.full( (N,N), np.inf)\n\n\tfor i in range(N):\n\t\tdist_i = pairwise_distances[:,i]\n\t\tordered_indices = np.argsort(dist_i)\n\n\t\tknn_indices = ordered_indices[0:k+1]\n\t\tdist_w_inf[knn_indices, i] = pairwise_distances[knn_indices, i]\n\n\t# step3: compute shortest path\n\t# Apply Floyd-Warshall algorithm\n\tshort_path_dist = dist_w_inf\n\tfor k in range(N):\n\t\tfor i in range(N):\n\t\t\tfor j in range(N):\n\n\t\t\t\tif short_path_dist[i,j] > short_path_dist[i,k] + short_path_dist[k,j]:\n\t\t\t\t\tshort_path_dist[i,j] = short_path_dist[i,k] + short_path_dist[k,j]\n\n\t# Do eigen decomp on shortest paths\n\te_vals, e_vecs = linalg.eigh(short_path_dist)\n\tflipped_e_vals = np.flip(e_vals, axis=0)\n\tflipped_e_vecs = np.flip(e_vecs, axis=1)\n\n\t# step4: now that the eigens are sorted largest>smallest take first p, take sq.root\n\tflipped_e_vals[proj_dim:] = 0\n\tlambda_sqrt = np.sqrt(flipped_e_vals)\n\n\t# step5: construct diagonal matrix\n\tdiag_lambda = np.diagflat(lambda_sqrt)\n\ty_matrix = (flipped_e_vecs @ diag_lambda).T \n\n\treturn pairwise_distances, dist_w_inf, short_path_dist, y_matrix \n\nif __name__ == \"__main__\":\n\n\t# Load data\n\torig_data = np.loadtxt('data/3Ddata.txt')\n\torig_data[:, 3] = orig_data[:, 3] - 1\n\tdata_3d = orig_data[:,0:3]\n\tcentered_data = center_data(data_3d)\n\n\tvar_cov = centered_data.T @ centered_data * (1/centered_data.shape[0]) \n\t\n\t# A: Do pca\n\tpca_coeff = do_pca(data_3d, 2)\n\tgraph_data3D(orig_data, \"3d_data.png\")\n\tplt.clf()\n\tgraph_data2D(pca_coeff, orig_data[:,-1], \"pca.png\")\n\tplt.clf()\n\n\t# B: do ISOMAP\n\tpairwise_distances, dist_w_inf, short_path_dist, y_matrix  = do_iso(data_3d, 10, 2)\n\ty0 = y_matrix[0,:]\n\ty1 = y_matrix[1,:]\n\tgroup = orig_data[:,-1]\n\n\n\tcolor_list = ['r', 'g', 'b', 'y']\n\n\tfor c in range(4):\n\t\tb = group == c\n\n\t\tplt.scatter(y0[b], y1[b], color=color_list[c])\n\tplt.savefig('isomap.png')\n\tplt.clf()\n\n\t# C: do LLE\n\tlle_proj = do_LLE(data_3d, 2, 10)\n\tgraph_data2D(lle_proj, orig_data[:,-1], \"lle.png\")\n\tplt.clf()\n\n\n\n\n", "meta": {"hexsha": "57ed5f3dcc6b055369c4058b5836167fa889c3ed", "size": 5282, "ext": "py", "lang": "Python", "max_stars_repo_path": "homework_2/dim_reduction.py", "max_stars_repo_name": "CooperNederhood/Machine_learning", "max_stars_repo_head_hexsha": "acad80c47bf77ec6b5573276ef287a1da94f3583", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework_2/dim_reduction.py", "max_issues_repo_name": "CooperNederhood/Machine_learning", "max_issues_repo_head_hexsha": "acad80c47bf77ec6b5573276ef287a1da94f3583", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework_2/dim_reduction.py", "max_forks_repo_name": "CooperNederhood/Machine_learning", "max_forks_repo_head_hexsha": "acad80c47bf77ec6b5573276ef287a1da94f3583", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4755555556, "max_line_length": 84, "alphanum_fraction": 0.6819386596, "include": true, "reason": "import numpy", "num_tokens": 1652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214450208031, "lm_q2_score": 0.8824278741843884, "lm_q1q2_score": 0.8509441227601249}}
{"text": "from typing import Tuple, Optional\n\nimport numpy as np\nimport scipy.stats\nimport matplotlib.pyplot as plt\n\n\ndef beta_a_b_from_mode_concentration(mode: float, concentration: float) -> Tuple[float, float]:\n\t\"\"\"\n\tComputes the shape parameters, alpha and beta, of a beta distribution given its mode and concentration.\n\n\tParameters\n\t----------\n\tmode : float\n\t\tThe mode of the distribution\n\tconcentration : float\n\t\tThe concentration of the distribution\n\n\tReturns\n\t-------\n\tout: tuple of floats\n\t\talpha and beta parameters\n\n\t\"\"\"\n\n\treturn mode*(concentration - 2.) + 1., (1-mode)*(concentration - 2.) + 1.\n\n\ndef beta_mode_concentration_from_a_b(a: float, b: float) -> Tuple[float, float]:\n\t\"\"\"\n\tComputes the mode and concentration of a beta distribution from its shape parameters, alpha and beta.\n\n\tParameters\n\t----------\n\ta : float\n\t\talpha parameter\n\tb : float\n\t\tbeta parameter\n\n\tReturns\n\t-------\n\tout: tuple of floats\n\t\tMode and concentration\n\n\t\"\"\"\n\n\tassert a > 1 and b > 1\n\treturn (a - 1.) / (a + b - 2.), a + b\n\n\ndef plot_beta(\n\t\ta: Optional[float] = None, b: Optional[float] = None, mode: Optional[float] = None,\n\t\tconcentration: Optional[float] = None) -> None:\n\t\"\"\"\n\tPlots a beta distribution.\n\n\tParameters\n\t----------\n\ta : float, optional\n\t\talpha parameter\n\tb : float, optional\n\t\tbeta parameter\n\tmode : float, optional\n\t\tMode\n\tconcentration : float, optional\n\t\tConcentration\n\n\t\"\"\"\n\n\tif mode and concentration:\n\n\t\ta, b = beta_a_b_from_mode_concentration(mode, concentration)\n\n\telif a and b:\n\n\t\t# it's fine\n\t\tpass\n\n\telse:\n\n\t\traise Exception('either `a` and `b` or `mode` and `concentration` must be passed')\n\n\tx = np.linspace(scipy.stats.beta.ppf(0.01, a, b), scipy.stats.beta.ppf(0.99, a, b), 100)\n\n\tplt.figure()\n\tplt.plot(x, scipy.stats.beta.pdf(x, a, b), 'r-', lw=5, alpha=0.6, label='beta pdf')\n\n\ndef gamma_shape_rate_from_mode_sd(mode: float, sd: float) -> Tuple[float, float]:\n\t\"\"\"\n\tReturns the shape and rate parameters of a gamma distribution from its mode and standard deviation.\n\n\tParameters\n\t----------\n\tmode : float\n\t\tMode\n\tsd : float\n\t\tStandard deviation\n\n\tReturns\n\t-------\n\tout: tuple of floats\n\t\tShape and rate\n\n\t\"\"\"\n\n\tr = (mode + np.sqrt(mode**2 + 4*sd**2)) / (2*sd**2)\n\ts = 1 + mode * r\n\n\treturn s, r\n\n\ndef plot_gamma(mode: float, sd: float) -> None:\n\t\"\"\"\n\tPlots a gamma distribution.\n\n\tParameters\n\t----------\n\tmode : float\n\t\tMode\n\tsd : float\n\t\tStandard deviation\n\n\t\"\"\"\n\n\tshape, rate = gamma_shape_rate_from_mode_sd(mode, sd)\n\n\t# the scale is the inverse of the rate\n\tscale = 1./rate\n\n\tx = np.linspace(scipy.stats.gamma.ppf(0.01, a=shape, scale=scale), scipy.stats.gamma.ppf(0.99, a=shape, scale=scale))\n\n\tplt.figure()\n\tplt.plot(x, scipy.stats.gamma.pdf(x, a=shape, scale=scale), 'r-', lw=5, alpha=0.6, label='gamma pdf')\n\n\ndef plot_half_cauchy(scale: float) -> None:\n\t\"\"\"\n\tPlot a half-cauchy distribution.\n\n\tParameters\n\t----------\n\tscale : float\n\t\tScale\n\n\t\"\"\"\n\n\tx = np.linspace(scipy.stats.halfcauchy.ppf(0.01, scale=scale), scipy.stats.halfcauchy.ppf(0.99, scale=scale), 100)\n\n\tplt.figure()\n\tplt.plot(x, scipy.stats.halfcauchy.pdf(x, scale=scale), 'r-', lw=5, alpha=0.6, label='Half-Cauchy pdf')\n", "meta": {"hexsha": "38e18fb6ea682e04cd0e2919cddf37cbc8bb3dfa", "size": 3113, "ext": "py", "lang": "Python", "max_stars_repo_path": "stats.py", "max_stars_repo_name": "manuvazquez/utils", "max_stars_repo_head_hexsha": "2f756ba7a33ae70cef3019aa858417c44761a5c8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-12T22:10:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-12T22:10:03.000Z", "max_issues_repo_path": "stats.py", "max_issues_repo_name": "manuvazquez/utils", "max_issues_repo_head_hexsha": "2f756ba7a33ae70cef3019aa858417c44761a5c8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stats.py", "max_forks_repo_name": "manuvazquez/utils", "max_forks_repo_head_hexsha": "2f756ba7a33ae70cef3019aa858417c44761a5c8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4802631579, "max_line_length": 118, "alphanum_fraction": 0.6700931577, "include": true, "reason": "import numpy,import scipy", "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214491222695, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.8509441174344462}}
{"text": "# Project 1 Main - Computational Physics\n# Hunter Phillips\n\n# This program allows the user to input n, a, b, and c to solve\n# Poisson's equation in a single dimension by turning it into a matrix.\n# using Gaussian Jordan Elimination, Specialized Tridiagonal, and LU Decomposition\n# Benchmarks and error calculations are also performed.\n\nimport sys\nimport numpy as nmp\nfrom solver import *\n\n# part b\ndef part_b(n, a_i, b_i, c_i):\n    a = nmp.full(n+2, a_i, dtype=nmp.float64)\n    b = nmp.full(n+2, b_i, dtype=nmp.float64)\n    c = nmp.full(n+2, c_i, dtype=nmp.float64)\n    x, v = general(f_function, a, b, c, n)\n    return x, v\n\n# part c\ndef part_c(n, a_i, b_i, c_i):\n    a = nmp.full(n+2, a_i, dtype=nmp.float64)\n    b = nmp.full(n+2, b_i, dtype=nmp.float64)\n    c = nmp.full(n+2, c_i, dtype=nmp.float64)\n    x, v = tridiag(f_function, a, b, c, n)\n    return x, v\n\n# part d\ndef part_d(n, a_i, b_i, c_i):\n    a = nmp.full(n+2, a_i, dtype=nmp.float64)\n    b = nmp.full(n+2, b_i, dtype=nmp.float64)\n    c = nmp.full(n+2, c_i, dtype=nmp.float64)\n    x, v = tridiag(f_function, a, b, c, n)\n    u = u_function(x)\n    eps_i = nmp.log10(abs((v[1:-1]-u[1:-1])/u[1:-1])) # strip the last and first parts of matrix\n    eps = nmp.max(eps_i)\n    return n, eps\n\n# part e\ndef part_e(n, a_i, b_i, c_i):\n    a = a_i\n    b = b_i\n    c = c_i\n    x, v = LU(f_function, a, b, c, n)\n    return  x, v\n\n# benchmarks\ndef benchmarking(n, a_i, b_i, c_i):\n\n    a = nmp.full(n+2, a_i, dtype=nmp.float64) # have to get that accuracy\n    b = nmp.full(n+2, b_i, dtype=nmp.float64)\n    c = nmp.full(n+2, c_i, dtype=nmp.float64)\n\n    start_time = time.time() # in the future I would like to add more complex timing analysis\n    x, v = general(f_function, a, b, c, n)\n    end_time = time.time()\n    general_time = end_time - start_time\n\n    start_time = time.time()\n    x, v = tridiag(f_function, a, b, c, n)\n    end_time = time.time()\n    tridiag_time = end_time - start_time\n\n    a = a_i\n    b = b_i\n    c = c_i\n\n    LU_time = 0. # preallocation\n\n    if (n <= 10000):\n        start_time = time.time()\n        x, v = LU(f_function, a, b, c, n)\n        end_time = time.time()\n        LU_time = end_time - start_time\n\n    return general_time, tridiag_time, LU_time\n\n\nif __name__ == \"__main__\":\n\n    print('This program allows the user to input n (for n x n matrix), a, b, and c to solve\\nPoisson\\'s equation in a single dimension by turning it into a matrix\\nusing Gaussian Jordan Elimination, Specialized Tridiagonal, and LU Decomposition\\nBenchmarks and error calculations are also performed.\\n\\n')\n\n    # get user input\n    n_i = int(raw_input('Please input the size n of your desired matrix: '))\n    a_i = int(raw_input('Please input the value of a for your desired matrix: '))\n    b_i = int(raw_input('Please input the value of b for your desired matrix: '))\n    c_i = int(raw_input('Please input the value of c for your desired matrix: '))\n\n    print('\\nGeneral Algorithm')\n    b_x, b_v = part_b(n_i, a_i, b_i, c_i)\n    print(b_x)\n    print(b_v)\n\n    print('\\nSpecialized Tridiagonal Algorithm')\n    c_x, c_v = part_c(n_i, a_i, b_i, c_i)\n    print(c_x)\n    print(c_v)\n\n    print('\\nRelative Error')\n    n, eps = part_d(n_i, a_i, b_i, c_i)\n    print('n = ' + str(n))\n    print('error = ' + str(eps))\n\n    print('\\nLinear Decomposition Algorithm')\n    e_x, e_v = part_e(n_i, a_i, b_i, c_i)\n    print(e_x)\n    print(e_v)\n\n    general_time, tridiag_time, LU_time = benchmarking(n_i, a_i, b_i, c_i)\n    print('\\nGeneral Algorithm Time to Execute')\n    print(general_time)\n    print('\\nSpecialized Tridiagonal Algorithm Time to Execute')\n    print(tridiag_time)\n    print('\\nLU Decomposition Time to Execute')\n    print(LU_time)\n    print('\\n\\n')\n", "meta": {"hexsha": "4c71b53c6a44c2dc1978b35e431359c41d227247", "size": 3709, "ext": "py", "lang": "Python", "max_stars_repo_path": "Projects/Project1/src/main.py", "max_stars_repo_name": "robolux/Computational_Physics", "max_stars_repo_head_hexsha": "46ca9f4234d614f5e5ad2717df3ad074eb2d60ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Projects/Project1/src/main.py", "max_issues_repo_name": "robolux/Computational_Physics", "max_issues_repo_head_hexsha": "46ca9f4234d614f5e5ad2717df3ad074eb2d60ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Projects/Project1/src/main.py", "max_forks_repo_name": "robolux/Computational_Physics", "max_forks_repo_head_hexsha": "46ca9f4234d614f5e5ad2717df3ad074eb2d60ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4322033898, "max_line_length": 305, "alphanum_fraction": 0.6441089242, "include": true, "reason": "import numpy", "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741322079105, "lm_q2_score": 0.8933094145755219, "lm_q1q2_score": 0.8509434403824344}}
{"text": "\"\"\"\nAnimated example of Newton-Raphson method for finding roots \n\nMIT License\n\nCopyright (c) 2021 Luiz Gustavo da Rocha Charamba\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt \nfrom matplotlib import animation\n\ndef f(x):\n  return x**6/6 - 3*x**4 - 2*x**3/3 + 27*x**2/2 + 18*x - 30\n\ndef d_f(x):\n  return x**5 - 12*x**3 -2*x**2 + 27*x + 18\n\ndef newton_raphson(x):\n    return x - f(x) / d_f(x)\n\nx = 5.0#-6.5#-6.0\n\nd = {\"x\" : [x], \"f(x)\": [f(x)]}\nnr_X = []\nnr_Y = []\niterations = 200\nfor i in range(0, iterations):\n  x = newton_raphson(x)\n  d[\"x\"].append(x)\n  nr_X.append(x)\n  d[\"f(x)\"].append(f(x))\n  nr_Y.append(f(x))\n\nprint(\"Iterations: \", len(nr_X))\nprint(pd.DataFrame(d, columns=['x', 'f(x)']))\n\nX = []\nY = []\nleft_limit = -5\nright_limit = 5\nstep_sample = 0.01\n\nfor x in np.arange(left_limit, right_limit, step_sample):\n    y = f(x)\n    X.append(x)\n    Y.append(y)\n\n# First set up the figure, the axis, and the plot element we want to animate\nfig = plt.figure()\nax = plt.axes(xlim=(-5,5), ylim=(-70, 1000))\nf_line, = ax.plot([],[]) #ax.plot(X, Y)\nroot_line, = ax.plot([],[], color='r', marker='o') #ax.plot(nr_X, nr_Y, color='r', marker='o')\n\n# initialization function: plot the background of each frame\ndef init():\n    f_line.set_data([], [])\n    root_line.set_data([], [])\n    \n    return f_line, root_line, \n\ndef animate(i):\n    f_line.set_data(X, Y)\n    root_line.set_data(np.array(nr_X[:i]), np.array(nr_Y[:i]))\n    return f_line, root_line\n\nanim = animation.FuncAnimation(fig, animate, init_func=init,\n                               frames=200, interval=200, blit=True)\n\nplt.show()\n\n    \n\n    ", "meta": {"hexsha": "9c8e0b7da92cedcc754dd6d95fab29c861c39e84", "size": 2653, "ext": "py", "lang": "Python", "max_stars_repo_path": "newton-raphson_animated.py", "max_stars_repo_name": "Charamba/Math-Algorithms-for-Machine-Learning", "max_stars_repo_head_hexsha": "d3701902e8a07764fc250f2fba9d308a614b59a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "newton-raphson_animated.py", "max_issues_repo_name": "Charamba/Math-Algorithms-for-Machine-Learning", "max_issues_repo_head_hexsha": "d3701902e8a07764fc250f2fba9d308a614b59a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "newton-raphson_animated.py", "max_forks_repo_name": "Charamba/Math-Algorithms-for-Machine-Learning", "max_forks_repo_head_hexsha": "d3701902e8a07764fc250f2fba9d308a614b59a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5268817204, "max_line_length": 94, "alphanum_fraction": 0.6875235582, "include": true, "reason": "import numpy", "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296944, "lm_q2_score": 0.8933094039240554, "lm_q1q2_score": 0.8509434230197765}}
{"text": "#!/usr/bin/python3\nimport sympy\nimport math\nfrom prettytable import PrettyTable\nx = sympy.Symbol('x')\nln = sympy.ln\n\nf = x * ln(x) - x\ng = x-f/f.diff(x)\ntol = 0.1\nxa = 2.5\ntable = PrettyTable()\n\niters = []\nfuncG = []\nfuncF = []\nerrorTot = []\nderiv = []\n\ndef newton(tol,xa,niter):\n    fx = f.evalf().subs({x:xa})\n    funcF.append(\"%e\" % (fx))\n    error = tol+1\n    errorTot.append(\"\")\n    funcG.append((xa))\n    deriv.append(f.diff(x).evalf().subs({x:xa}))\n    iters.append(0)\n    cont = 0\n    while(fx != 0 and error > tol and cont < niter):        \n        xn = g.evalf().subs({x:xa}).evalf()        \n        funcG.append((xn))\n        deriv.append(f.diff(x).evalf().subs({x:xn}).evalf())\n        fx = f.evalf().subs({x:xn}).evalf()\n        funcF.append(\"%e\" % (fx))\n        error = abs(xn-xa)\n        errorTot.append(\"%e\" % (error/xn))\n        xa = xn\n        cont = cont +1\n        iters.append(cont)\n    if ( fx == 0):\n        print(str(xa)+\" es raiz\")\n    elif (error < tol):\n        print(str(xa)+\" es una aproximacion \")\n    else: \n        print(\"El metodo fracasó\")\n    table.add_column(\"n\",iters)\n    table.add_column(\"xn\",funcG)\n    table.add_column(\"f(xn)\",funcF)\n    table.add_column(\"f'(xn)\",deriv)\n    table.add_column(\"error\",errorTot)\n    print(table)\n    \nnewton(tol,xa,200)", "meta": {"hexsha": "d76b4b40c2a805cc0c6fae74eae8e3885a4f9ff4", "size": 1291, "ext": "py", "lang": "Python", "max_stars_repo_path": "OneVariable/NewtonMethod/newtonMethod.py", "max_stars_repo_name": "stivenramireza/numericalanalysis", "max_stars_repo_head_hexsha": "7f2fe2b43ac41bccf3c41d3f936522619d009927", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-23T21:24:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T19:45:47.000Z", "max_issues_repo_path": "OneVariable/NewtonMethod/newtonMethod.py", "max_issues_repo_name": "stivenramireza/numerical-methods", "max_issues_repo_head_hexsha": "7f2fe2b43ac41bccf3c41d3f936522619d009927", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OneVariable/NewtonMethod/newtonMethod.py", "max_forks_repo_name": "stivenramireza/numerical-methods", "max_forks_repo_head_hexsha": "7f2fe2b43ac41bccf3c41d3f936522619d009927", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-23T17:20:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-23T17:20:22.000Z", "avg_line_length": 24.358490566, "max_line_length": 60, "alphanum_fraction": 0.5460883036, "include": true, "reason": "import sympy", "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.8933094025038598, "lm_q1q2_score": 0.8509434216669348}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n@author: salimt\n\"\"\"\n#Problem 2: R^2\n#10/10 points (graded)\n#After we create some regression models, we also want to be able to evaluate our models to figure out how well each model represents our data, and tell good models from poorly fitting ones. One way to evaluate how well the model describes the data is computing the model's R^2 value. R^2 provides a measure of how well the total variation of samples is explained by the model.\n#\n#Implement the function r_squared. This function will take in:\n#\n#list, y, that represents the y-coordinates of the original data samples\n#estimated, which is a corresponding list of y-coordinates estimated from the regression model\n#This function should return the computed R^2 value. You can compute R^2 as follows, where  is the estimated y value for the i-th data point (i.e. predicted by the regression),  is the y value for the ith data point, and  is the mean of the original data samples.\n#\n#\n#If you are still confused about R^2 , its wikipedia(https://en.wikipedia.org/wiki/Coefficient_of_determination) page has a good explanation about its use/how to calculate it.\n#\n#Note: If you want to use numpy arrays, you should import numpy as np and use np.METHOD_NAME in your code. Unfortunately, pylab does not work with the grader.\n#\n##Problem 2\n#\ndef r_squared(y, estimated):\n    \"\"\"\n    Calculate the R-squared error term.\n    Args:\n        y: list with length N, representing the y-coords of N sample points\n        estimated: a list of values estimated by the regression model\n    Returns:\n        a float for the R-squared error term\n    \"\"\"\n    import numpy\n\n    error = ((numpy.array(estimated) - numpy.array(y))**2).sum()\n    meanError = error/len(y)\n#    return round(1 - (meanError/numpy.var(y)), 4)\n    return 1 - (meanError/numpy.var(y))\n\n#print(r_squared([32.0, 42.0, 31.3, 22.0, 33.0], [32.3, 42.1, 31.2, 22.1, 34.0])) #0.9944", "meta": {"hexsha": "16516e88e7597876a638a10a6052fd359eb7506a", "size": 1912, "ext": "py", "lang": "Python", "max_stars_repo_path": "MITx-6.00.2x/pset4-modelling-temperatures/pset4_Problem2_r_squared.py", "max_stars_repo_name": "FTiniNadhirah/Coursera-courses-answers", "max_stars_repo_head_hexsha": "d59311917b740a6ce8b8361e9ac79657b103bb75", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2020-08-26T03:03:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T17:35:47.000Z", "max_issues_repo_path": "MITx-6.00.2x/pset4-modelling-temperatures/pset4_Problem2_r_squared.py", "max_issues_repo_name": "FTiniNadhirah/Coursera-courses-answers", "max_issues_repo_head_hexsha": "d59311917b740a6ce8b8361e9ac79657b103bb75", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MITx-6.00.2x/pset4-modelling-temperatures/pset4_Problem2_r_squared.py", "max_forks_repo_name": "FTiniNadhirah/Coursera-courses-answers", "max_forks_repo_head_hexsha": "d59311917b740a6ce8b8361e9ac79657b103bb75", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 44, "max_forks_repo_forks_event_min_datetime": "2020-09-19T09:28:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T18:07:19.000Z", "avg_line_length": 50.3157894737, "max_line_length": 376, "alphanum_fraction": 0.7201882845, "include": true, "reason": "import numpy", "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.9207896710002322, "lm_q1q2_score": 0.8509402442995581}}
{"text": "# -*- coding: utf-8 -*-\r\n# Imports all the necessary libraries\r\n\"\"\"This application approximates the PI value based on a Monte Carlo Simulation.\r\nIt asks for input from the user regarding on number of darts thrown.\"\"\"\r\nimport math\r\nimport random\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef gen_circle(radius=1, center_x=0, center_y=0, res=50):\r\n    \"\"\"Returns the points of coordinates [x,y] which lie on the circle\r\n    with the radius radius and with the center specified at center = [x,y],\r\n    with the resolution res\"\"\"\r\n    xcord = [center_x + radius * math.cos(tht) for \\\r\n         tht in np.linspace(0, 2 * math.pi, res)]\r\n    ycord = [center_y + radius * math.sin(tht) for \\\r\n         tht in np.linspace(0, 2 * math.pi, res)]\r\n    return [xcord, ycord]\r\n\r\ndef gen_square(center_x=0, center_y=0, edge=2):\r\n    \"\"\"Returns the vertices of a square in [x,y] coordinates, which is centered\r\n    at the center=[x,y] and with the edge length equal to edge\"\"\"\r\n    vertices_x = [center_x + edge/2, center_x - \\\r\n                  edge/2, center_x - edge/2, center_x + edge/2]\r\n    vertices_y = [center_y + edge/2, center_y + \\\r\n                  edge/2, center_y - edge/2, center_y - edge/2]\r\n    vertices = [vertices_x, vertices_y]\r\n    return vertices\r\n\r\nPLAY = True\r\nAPPROX_PI_LIST = list()\r\nNUM_DARTS_LIST = list()\r\n\r\nwhile PLAY:\r\n    #Insert the number of darts to be thrown\r\n    NUM_DARTS = int( \\\r\n            input('Please insert the number of darts that you want to throw\\n'))\r\n    NUM_DARTS_LIST.append(NUM_DARTS)\r\n\r\n    CIRC_DARTS = {'x':list(), 'y':list()}\r\n    SQUARE_DARTS = {'x':list(), 'y':list()}\r\n\r\n    CIRC_HITS = 0\r\n    SQUARE_HITS = 0\r\n\r\n    for dart in range(NUM_DARTS):\r\n        x_dart = random.random() * 2 - 1\r\n        y_dart = random.random() * 2 - 1\r\n\r\n        if(x_dart**2 + y_dart**2)**(1/2) > 1:\r\n            SQUARE_HITS += 1\r\n            SQUARE_DARTS['x'].append(x_dart)\r\n            SQUARE_DARTS['y'].append(y_dart)\r\n\r\n        elif(x_dart**2 + y_dart**2)**(1/2) <= 1:\r\n            CIRC_HITS += 1\r\n            CIRC_DARTS['x'].append(x_dart)\r\n            CIRC_DARTS['y'].append(y_dart)\r\n\r\n        else:\r\n            pass\r\n\r\n    APPROX_PI = 4 * CIRC_HITS/NUM_DARTS #THE APPROXIMATED VALUE OF PI\r\n    APPROX_PI_LIST.append(APPROX_PI)\r\n\r\n    #Plots the darts thrown in a new figure\r\n    plt.figure(figsize=(10, 10))\r\n\r\n    #Plots the square\r\n    plt.fill(gen_square()[0], gen_square()[1], fill=False)\r\n\r\n    #Plots the circle\r\n    plt.plot(gen_circle()[0], gen_circle()[1], 'g-')\r\n\r\n    #Plots the darts which landed on the darts board\r\n    plt.plot(CIRC_DARTS['x'], CIRC_DARTS['y'], 'go')\r\n\r\n    #Plots the darts which landed outside the darts board and inside the square\r\n    plt.plot(SQUARE_DARTS['x'], SQUARE_DARTS['y'], 'ro')\r\n\r\n    #Sets a title to the plot\r\n    plt.title('Approximated Pi value: {:6.4f} ==> Darts thrown: {:d}'.format( \\\r\n            APPROX_PI, NUM_DARTS), {'fontsize':20})\r\n\r\n    #Turning off hte tick labels for the plots\r\n    plt.xticks([])\r\n    plt.yticks([])\r\n\r\n    print(\"\\nYour darts Monte Carlo method approximative value of PI is:\",\r\n          \" {}\\n\\nThat's {} off from the actual value of PI\\n\".format(\\\r\n            APPROX_PI, abs(math.pi - APPROX_PI)))\r\n    print('\\nCircle hit {} times and square hit {} times'.format(\\\r\n          CIRC_HITS, SQUARE_HITS))\r\n\r\n    QUESTION_STRING = 'Do you want to trow darts again Y/N?. \\\r\n    To see all the plots press N\\n'\r\n    CONTINUE_PLAY = input(QUESTION_STRING)\r\n    if CONTINUE_PLAY == 'Y':\r\n        PLAY = True\r\n    elif CONTINUE_PLAY == 'N':\r\n        PLAY = False\r\n        print('\\nThank you for playing the game,',\r\n              ' have a look at all the plots generated\\n')\r\n        print('\\nThe previous results are:\\n')\r\n\r\n        for piVal, dart in zip(APPROX_PI_LIST, NUM_DARTS_LIST):\r\n            print(f'Approximated Pi value: {piVal:4} ',\r\n                  f'==> Darts thrown: {dart:4}')\r\n", "meta": {"hexsha": "04bb483578bfabd7f2a152615e4ebb9dd5d5487a", "size": 3925, "ext": "py", "lang": "Python", "max_stars_repo_path": "monte_carlo_pi.py", "max_stars_repo_name": "EugenSusurrus/monte_carlo_pi_approximation", "max_stars_repo_head_hexsha": "224630c63410d2933d01d28030784fb4ae32b7f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "monte_carlo_pi.py", "max_issues_repo_name": "EugenSusurrus/monte_carlo_pi_approximation", "max_issues_repo_head_hexsha": "224630c63410d2933d01d28030784fb4ae32b7f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "monte_carlo_pi.py", "max_forks_repo_name": "EugenSusurrus/monte_carlo_pi_approximation", "max_forks_repo_head_hexsha": "224630c63410d2933d01d28030784fb4ae32b7f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0091743119, "max_line_length": 81, "alphanum_fraction": 0.6005095541, "include": true, "reason": "import numpy", "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992932829918, "lm_q2_score": 0.8791467564270271, "lm_q1q2_score": 0.8509255242377541}}
{"text": "from sympy import symbols, sqrt, solve\nfrom scipy.signal.wavelets import cascade\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport utilities.wavelet as wv\n\n\ndef compute_A3_filter_coefficeints():\n\n    h = symbols('h0 h1 h2 h3 h4 h5')\n\n    # Filter Equations\n    eq1 = sum(v**2 for v in h) - 1\n    eq2 = sum([h[i-2]*h[i] for i in range(2, len(h))])\n    eq3 = sum(h) - sqrt(2)\n\n    # A(3) Equations\n    eq4 = sum([(-1)**i*h[i] for i in range(0, len(h))])\n    eq5 = sum([(-1)**i*(-i)*h[i] for i in range(0, len(h))])\n    eq6 = sum([(-1)**i*i**2*h[i] for i in range(0, len(h))])\n\n    solutions = solve([eq1, eq2, eq3, eq4, eq5, eq6], *h)\n    print solutions\n\n\ndef plot_A3_symbol(show=True):\n    h = [0.332670552950083, 0.806891509311093, 0.459877502118492, -\n         0.135011020010255, -0.0854412738820267, 0.0352262918857095]\n\n    # Compute Symbol\n    P, f = wv.compute_symbol(h)\n\n    plt.figure(1)\n\n    # Plot Symbol\n    t = np.linspace(0, 1, 200)\n    plt.plot(t, [abs(P.subs(f, v).evalf()) for v in t])\n    plt.xlabel('f')\n    plt.ylabel('abs(P)')\n    plt.title('Symbol P(f)')\n\n    if show:\n        plt.show()\n\ndef plot_A3_scaling_function_and_wavelet(show=True):\n    h = [0.332670552950083, 0.806891509311093, 0.459877502118492, -\n         0.135011020010255, -0.0854412738820267, 0.0352262918857095]\n\n    plt.figure(2)\n\n    t, phi, psi = cascade(h)\n    plt.subplot(1,2,1)\n    plt.plot(t, phi)\n    plt.xlabel('t')\n    plt.ylabel('phi')\n    plt.title('scaling function')\n\n    plt.subplot(1,2,2)\n    plt.plot(t, psi)\n    plt.xlabel('t')\n    plt.ylabel('psi')\n    plt.title('mother wavelet')\n\n    if show:\n        plt.show()\n\n\nif __name__ == \"__main__\":\n    plot_A3_symbol(show=False)\n    plot_A3_scaling_function_and_wavelet()\n", "meta": {"hexsha": "83928cca5c70d735862112d799cca89ba4c31165", "size": 1732, "ext": "py", "lang": "Python", "max_stars_repo_path": "homework6.py", "max_stars_repo_name": "cschultz123/theory_of_wavelets", "max_stars_repo_head_hexsha": "30b8b7290c5113c404ae56b92906f454055dea5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-18T09:23:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-18T09:23:59.000Z", "max_issues_repo_path": "homework6.py", "max_issues_repo_name": "cschultz123/theory_of_wavelets", "max_issues_repo_head_hexsha": "30b8b7290c5113c404ae56b92906f454055dea5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework6.py", "max_forks_repo_name": "cschultz123/theory_of_wavelets", "max_forks_repo_head_hexsha": "30b8b7290c5113c404ae56b92906f454055dea5e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3943661972, "max_line_length": 68, "alphanum_fraction": 0.6166281755, "include": true, "reason": "import numpy,from scipy,from sympy", "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639661317859, "lm_q2_score": 0.8757869786798664, "lm_q1q2_score": 0.8508830704927848}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\n# linear function\ndef linear(m, b, x):\n    return m * x + b\n\n\n# Sum of Squared Errors\ndef sse(m: float, b: float, x: np.ndarray, y: np.ndarray) -> float:\n    guess = linear(m, b, x)\n    actual = y\n\n    return sum((actual - guess) ** 2) / 2\n\n\n# partial derivative of sse() w.r.t 'm'\ndef dm_sse(m: float, b: float, x: np.ndarray, y: np.ndarray):\n    return sum(-x * (y - linear(m, b, x)))\n\n\n# partial derivative of sse() w.r.t 'b'\ndef db_sse(m: float, b: float, x: np.ndarray, y: np.ndarray):\n    return sum(-(y - linear(m, b, x)))\n\n\nX: np.ndarray = np.linspace(0, 20, 30)\nY: np.ndarray = X + np.random.random(30) * 5 - 10\n\nM = 0.0  # slope\nB = 0.0  # intercept\n\n# higher learning rate might cause uncontrolled bouncing & will not converge\nlearning_rate = 0.0001\n\n# Gradient descent until Squared error is below 35\nwhile sse(M, B, X, Y) > 35:\n    M -= dm_sse(M, B, X, Y) * learning_rate\n    B -= db_sse(M, B, X, Y) * learning_rate\n\nprint(M, B, sse(M, B, X, Y))\n\nfitted_x = np.linspace(0, 20, 30)\nfitted_y = linear(M, B, fitted_x)\n\nplt.plot(fitted_x, fitted_y)\nplt.scatter(X, Y)\nplt.show()\n", "meta": {"hexsha": "197e8a617d426934355dd7e994daa375cd1edce3", "size": 1140, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "Meyhem/py-gradient-descent-linear-regression", "max_stars_repo_head_hexsha": "642e003c3eae1a69802eb8e61b69ab5ad9ab3e09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.py", "max_issues_repo_name": "Meyhem/py-gradient-descent-linear-regression", "max_issues_repo_head_hexsha": "642e003c3eae1a69802eb8e61b69ab5ad9ab3e09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "Meyhem/py-gradient-descent-linear-regression", "max_forks_repo_head_hexsha": "642e003c3eae1a69802eb8e61b69ab5ad9ab3e09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8, "max_line_length": 76, "alphanum_fraction": 0.6280701754, "include": true, "reason": "import numpy", "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9833429614552197, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.8508120065575827}}
{"text": "\"\"\"\nUtility functions for testing different search \nalgorithms implemented in this skill.\n\"\"\"\nimport signal\nimport numpy as np\n\nfrom functools import wraps\n\n\nclass LossFunctions:\n    \"\"\"\n    Loss functions to evaluate the performance\n    of search algorithms. All methods available in \n    this class take numpy arrays as input.\n\n    Methods\n    -------\n    mape:\n        Mean averaged percentage error.\n    rmse:\n        Root mean squared error.\n    mse:\n        Mean squared error.\n    \"\"\"\n    @staticmethod\n    def mape(A, B):\n        \"\"\"\n        Calculates the mean absolute persentage error\n        from two series. Original solution from:\n        \n            https://stats.stackexchange.com/questions/58391/\\\n                mean-absolute-percentage-error-mape-in-scikit-learn\n        \n        Parameters\n        ----------\n        A, B: numpy.array\n            Numpy arrays with the same length with the\n            two objects representing the results (A)\n            and test data (B).\n\n        Returns\n        -------\n        float\n            Floating number in the domain [0, 1].\n        \"\"\"\n        #\n        #  Let's add 1 to all values\n        #  to avoid division by zero.\n        #\n        A += 0.000000000001\n        B += 0.000000000001\n        return np.round(np.mean(np.abs(A - B) / A) * 100, 2)\n\n    @staticmethod\n    def rmse(A, B):\n        \"\"\"\n        Calculates the root mean square error from\n        two series. Original solution from:\n\n            https://stackoverflow.com/questions/16774849\\\n                /mean-squared-error-in-numpy\n\n        Parameters\n        ----------\n        A, B: numpy.array\n            Numpy arrays with the same length with the\n            two objects representing the results (A)\n            and test data (B).\n\n        Returns\n        -------\n        float\n            Floating number in the same domain\n            of the original data.\n        \"\"\"\n        return np.round(np.sqrt(np.square(np.subtract(A, B)).mean()), 2)\n    \n    @staticmethod\n    def mse(A, B):\n        \"\"\"\n        Calculates the mean square error from\n        two series. Original solution from:\n\n            https://stackoverflow.com/questions/16774849\\\n                /mean-squared-error-in-numpy\n\n        Parameters\n        ----------\n        A, B: numpy.array\n            Numpy arrays with the same length with the\n            two objects representing the results (A)\n            and test data (B).\n\n        Returns\n        -------\n        float\n            Floating number in the squared domain\n            of the original data.\n        \"\"\"\n        return np.round(np.square(np.subtract(A, B)).mean(), 2)\n", "meta": {"hexsha": "08e4630c8d135864aeaa78d2883f060ea9dd7d6e", "size": 2643, "ext": "py", "lang": "Python", "max_stars_repo_path": "skill/utils.py", "max_stars_repo_name": "juliob29/BitcoinTalk-Insights", "max_stars_repo_head_hexsha": "73033791698c67bb1f6268dc0b762832f0e097dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "skill/utils.py", "max_issues_repo_name": "juliob29/BitcoinTalk-Insights", "max_issues_repo_head_hexsha": "73033791698c67bb1f6268dc0b762832f0e097dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:29:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:52:43.000Z", "max_forks_repo_path": "skill/utils.py", "max_forks_repo_name": "juliob29/BitcoinTalk-Insights", "max_forks_repo_head_hexsha": "73033791698c67bb1f6268dc0b762832f0e097dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9117647059, "max_line_length": 72, "alphanum_fraction": 0.5455921302, "include": true, "reason": "import numpy", "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723354, "lm_q2_score": 0.8887587979121383, "lm_q1q2_score": 0.8507890700597968}}
{"text": "# Implementing Newton Raphson method in Python\n# Author: Syed Haseeb Shah (github.com/QuantumNovice)\n# The Newton-Raphson method (also known as Newton's method) is a way to\n# quickly find a good approximation for the root of a real-valued function\n\nfrom decimal import Decimal\nfrom math import *  # noqa: F401, F403\nfrom sympy import diff\n\n\ndef newton_raphson(func: str, a: int, precision: int=10 ** -10) -> float:\n    \"\"\" Finds root from the point 'a' onwards by Newton-Raphson method\n    >>> newton_raphson(\"sin(x)\", 2)\n    3.1415926536808043\n    >>> newton_raphson(\"x**2 - 5*x +2\", 0.4)\n    0.4384471871911695\n    >>> newton_raphson(\"x**2 - 5\", 0.1)\n    2.23606797749979\n    >>> newton_raphson(\"log(x)- 1\", 2)\n    2.718281828458938\n    \"\"\"\n    x = a\n    while True:\n        x = Decimal(x) - (Decimal(eval(func)) / Decimal(eval(str(diff(func)))))\n        # This number dictates the accuracy of the answer\n        if abs(eval(func)) < precision:\n            return float(x)\n\n\n# Let's Execute\nif __name__ == \"__main__\":\n    # Find root of trigonometric function\n    # Find value of pi\n    print(f\"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}\")\n    # Find root of polynomial\n    print(f\"The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}\")\n    # Find Square Root of 5\n    print(f\"The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}\")\n    # Exponential Roots\n    print(f\"The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}\")\n", "meta": {"hexsha": "8aa816cd0d04c875add19395ef6986f0a654402e", "size": 1481, "ext": "py", "lang": "Python", "max_stars_repo_path": "arithmetic_analysis/newton_raphson.py", "max_stars_repo_name": "jasper256/Python", "max_stars_repo_head_hexsha": "90d17d291f65b74bd4d96547b270b2d1628319be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-21T09:26:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T09:26:49.000Z", "max_issues_repo_path": "arithmetic_analysis/newton_raphson.py", "max_issues_repo_name": "JT4v4res/Python", "max_issues_repo_head_hexsha": "aa18600e22ce323c59f2e1051ed53971196320c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arithmetic_analysis/newton_raphson.py", "max_forks_repo_name": "JT4v4res/Python", "max_forks_repo_head_hexsha": "aa18600e22ce323c59f2e1051ed53971196320c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-02T18:41:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-02T18:41:45.000Z", "avg_line_length": 36.1219512195, "max_line_length": 87, "alphanum_fraction": 0.6313301823, "include": true, "reason": "from sympy", "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535095, "lm_q2_score": 0.8887587971755248, "lm_q1q2_score": 0.8507890682714107}}
{"text": "# Illustrate the powr method for computing largest eigenvector\n\nimport numpy as np\nfrom numpy.linalg import norm\n\nnp.random.seed(0)\n\ndef power_method(A, max_iter=100, tol=1e-5):\n    n = np.shape(A)[0]\n    u = np.random.rand(n)\n    converged = False\n    iter = 0\n    while (not converged) and (iter < max_iter):\n        old_u = u\n        u = np.dot(A, u)\n        u = u / norm(u)\n        lam = np.dot(u, np.dot(A, u))\n        converged = (norm(u - old_u) < tol)\n        iter += 1\n    return lam, u\n\nX = np.random.randn(10, 5)\nA = np.dot(X.T, X)\nlam, u = power_method(A)\n\nevals, evecs = np.linalg.eig(A)\nidx = np.argsort(np.abs(evals))[::-1] # largest first\nevals = evals[idx]\nevecs = evecs[:,idx]\n\ntol = 1e-3\nassert np.allclose(evecs[:,0], u, tol)\nassert np.allclose(evals[0], lam, tol)\n", "meta": {"hexsha": "90a00b30893f78e2b32f8565fdf6c94c38ed7d3a", "size": 785, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/power_method_demo.py", "max_stars_repo_name": "always-newbie161/pyprobml", "max_stars_repo_head_hexsha": "eb70c84f9618d68235ef9ba7da147c009b2e4a80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-22T14:40:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T02:46:00.000Z", "max_issues_repo_path": "scripts/power_method_demo.py", "max_issues_repo_name": "always-newbie161/pyprobml", "max_issues_repo_head_hexsha": "eb70c84f9618d68235ef9ba7da147c009b2e4a80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-03-31T20:18:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:52:47.000Z", "max_forks_repo_path": "scripts/power_method_demo.py", "max_forks_repo_name": "always-newbie161/pyprobml", "max_forks_repo_head_hexsha": "eb70c84f9618d68235ef9ba7da147c009b2e4a80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-21T01:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T01:18:07.000Z", "avg_line_length": 23.0882352941, "max_line_length": 62, "alphanum_fraction": 0.6038216561, "include": true, "reason": "import numpy,from numpy", "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777975782055, "lm_q2_score": 0.8887587934924569, "lm_q1q2_score": 0.8507890604127223}}
{"text": "import numpy as np\nfrom scipy import optimize\nimport matplotlib.pyplot as plt\nfrom numba import jit\n\ndef moving_averages(x, half_window):\n    x = np.append(np.array([x[0]]*half_window), x)\n    x = np.append(x, np.array([x[-1]]*half_window))\n    cumsum = np.cumsum(np.insert(x, 0, 0))\n    window = half_window * 2\n    ma = (cumsum[window:-1] - cumsum[:-window-1]) / window\n    return ma\n\n@jit\ndef approx(coeffs, t, period = 1.0):\n    dim = int((coeffs.size - 1) / 2)\n    a0 = coeffs[0]\n    a = coeffs[1:dim+1]\n    b = coeffs[dim+1:2*dim+1]\n    tt = 2 * np.pi / period * np.arange(1, dim+1) * np.ones((t.size, dim)) * t.reshape((t.size,1))\n    res = a0 + np.sum(a * np.sin(tt), axis = 1) + np.sum(b * np.cos(tt), axis = 1)\n    # res = a0 \\\n    #       + sum(map(lambda i : a[i] * np.sin(2 * np.pi * (i+1) / period * t), range(0,dim))) \\\n    #       + sum(map(lambda i : b[i] * np.cos(2 * np.pi * (i+1) / period * t), range(0,dim)))\n    return res\n\n@jit\ndef approx_scalar(coeffs, t):\n    dim = int((coeffs.size - 1) / 2)\n    a0 = coeffs[0]\n    a = coeffs[1:dim+1]\n    b = coeffs[dim+1:2*dim+1]\n    tt = 2 * np.pi * np.arange(1, dim+1) * t\n    res = a0 + np.sum(a * np.sin(tt)) + np.sum(b * np.cos(tt))\n    # res = a0 \\\n    #       + sum(map(lambda i : a[i] * np.sin(2 * np.pi * (i+1) / period * t), range(0,dim))) \\\n    #       + sum(map(lambda i : b[i] * np.cos(2 * np.pi * (i+1) / period * t), range(0,dim)))\n    return res\n\nclass approximation():\n    def __init__(self, label, points, values, ma_halfwindow, min_degree, max_degree):\n        self.label = label\n        self.points = points\n        self.values = values\n        self.ma_halfwindow = ma_halfwindow\n        self.ma = moving_averages(self.values, self.ma_halfwindow)\n        self.min_degree = min_degree\n        self.max_degree = max_degree\n        self.coeffs = []\n        self.rmses = []\n        for i in range(self.min_degree, self.max_degree+1):\n            p0 = np.array([1.0]*(2*i+1))\n            result = optimize.leastsq(lambda p: approx(p, self.points) - self.values, p0)\n            rmse = np.mean((approx(result[0], self.points) - self.values)**2)\n            self.coeffs.append(np.array(result[0]))\n            self.rmses.append(rmse)\n\n    def plot_all(self):\n        fig, ax1 = plt.subplots()\n        ax1.set_ylabel(self.label)\n        ax1.scatter(self.points, self.values, color='red', label='values', marker='.')\n        ax1.plot(self.points, self.ma, color='red', label='moving average')\n        for p in self.coeffs:\n            ax1.plot(self.points, approx(p, self.points), label=f'approx of degree {(p.size - 1) / 2}')\n        ax1.legend(loc='upper center')\n        fig.tight_layout()\n        plt.show()\n\n    def plot_rmses(self):\n        fig, ax1 = plt.subplots()\n        ax1.plot(range(self.min_degree, self.max_degree+1), self.rmses)\n        fig.tight_layout()\n        plt.show()\n\n", "meta": {"hexsha": "f2153c9bd56f1312e0aa62a7a7811fd48d7915eb", "size": 2864, "ext": "py", "lang": "Python", "max_stars_repo_path": "DELWPdata/DataApproximations.py", "max_stars_repo_name": "horribleheffalump/InteractingCMCResearch", "max_stars_repo_head_hexsha": "68cdd3163d32f83b7f3e80765ec3caf28e8937dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DELWPdata/DataApproximations.py", "max_issues_repo_name": "horribleheffalump/InteractingCMCResearch", "max_issues_repo_head_hexsha": "68cdd3163d32f83b7f3e80765ec3caf28e8937dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DELWPdata/DataApproximations.py", "max_forks_repo_name": "horribleheffalump/InteractingCMCResearch", "max_forks_repo_head_hexsha": "68cdd3163d32f83b7f3e80765ec3caf28e8937dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1866666667, "max_line_length": 103, "alphanum_fraction": 0.5698324022, "include": true, "reason": "import numpy,from scipy,from numba", "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778012346835, "lm_q2_score": 0.8887587846530937, "lm_q1q2_score": 0.8507890552007231}}
{"text": "\"\"\"\n# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n@Time        : 2022/3/26 11:56\n@File        : softmax.py\n\"\"\"\n\nimport numpy as np\n\n\n# Write a function that takes as input a list of numbers, and returns\n# the list of values given by the softmax function.\ndef softmax(L):\n    \"\"\"\n    softmax\n    \"\"\"\n    exPL = np.exp(L)\n    sumExpL = sum(exPL)\n\n    result = []\n    for i in exPL:\n        result.append(i * 1.0/sumExpL)\n    return result\n\n\n# Note: The function np.divide can also be used here, as follows:\n# def softmax(L):\n#     expL = np.exp(L)\n#     return np.divide (expL, expL.sum())\n\n", "meta": {"hexsha": "194a380e0232782304533e277dc200b7c60ea6a0", "size": 590, "ext": "py", "lang": "Python", "max_stars_repo_path": "udacity-program_self_driving_car_engineer_v1.0/part01-computer vision and deep learning/module03-deep learning/lesson01-introduction to neural networks/exercise03-softmax/softmax.py", "max_stars_repo_name": "linksdl/futuretec-project-self_driving_cars_projects", "max_stars_repo_head_hexsha": "38e8f14543132ec86a8bada8d708eefaef23fee8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "udacity-program_self_driving_car_engineer_v1.0/part01-computer vision and deep learning/module03-deep learning/lesson01-introduction to neural networks/exercise03-softmax/softmax.py", "max_issues_repo_name": "linksdl/futuretec-project-self_driving_cars_projects", "max_issues_repo_head_hexsha": "38e8f14543132ec86a8bada8d708eefaef23fee8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "udacity-program_self_driving_car_engineer_v1.0/part01-computer vision and deep learning/module03-deep learning/lesson01-introduction to neural networks/exercise03-softmax/softmax.py", "max_forks_repo_name": "linksdl/futuretec-project-self_driving_cars_projects", "max_forks_repo_head_hexsha": "38e8f14543132ec86a8bada8d708eefaef23fee8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0322580645, "max_line_length": 69, "alphanum_fraction": 0.5915254237, "include": true, "reason": "import numpy", "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.8887587846530938, "lm_q1q2_score": 0.8507890530342386}}
{"text": "import numpy as np\n\n\ndef pol2cart(rho, phi):\n    \"\"\"\n    Transform from polar to cart coordinates\n    :param rho: distance to origin\n    :param phi: angle (rad)\n    :return: x, y\n    \"\"\"\n    x = rho * np.cos(phi)\n    y = rho * np.sin(phi)\n    return x, y\n\n\ndef cart2pol(x, y):\n    \"\"\"\n    Transform from cart to polar coordinates\n    :param x: x\n    :param y: y\n    :return: rho, phi (rad)\n    \"\"\"\n    rho = (x * x + y * y) ** 0.5\n    phi = np.arctan2(y, x)\n    return rho, phi\n\n\ndef pol2cart_ramap(rho, phi):\n    \"\"\"\n    Transform from polar to cart under RAMap coordinates\n    :param rho: distance to origin\n    :param phi: angle (rad) under RAMap coordinates\n    :return: x, y\n    \"\"\"\n    x = rho * np.sin(phi)\n    y = rho * np.cos(phi)\n    return x, y\n\n\ndef cart2pol_ramap(x, y):\n    \"\"\"\n    Transform from cart to polar under RAMap coordinates\n    :param x: x\n    :param y: y\n    :return: rho, phi (rad) under RAMap coordinates\n    \"\"\"\n    rho = (x * x + y * y) ** 0.5\n    phi = np.arctan2(x, y)\n    return rho, phi\n", "meta": {"hexsha": "1616dd24eb2626de14c894c5c87dc2a362819888", "size": 1021, "ext": "py", "lang": "Python", "max_stars_repo_path": "cruw/mapping/coor_transform.py", "max_stars_repo_name": "jb892/cruw-devkit", "max_stars_repo_head_hexsha": "1842108398a19550cbb9763d6fa953f440560150", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2020-12-15T07:17:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T03:04:21.000Z", "max_issues_repo_path": "cruw/mapping/coor_transform.py", "max_issues_repo_name": "kathy-lee/cruw-devkit", "max_issues_repo_head_hexsha": "a565905d52c0962a632ef3779d88e66c910ea171", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-01-07T02:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T02:19:37.000Z", "max_forks_repo_path": "cruw/mapping/coor_transform.py", "max_forks_repo_name": "kathy-lee/cruw-devkit", "max_forks_repo_head_hexsha": "a565905d52c0962a632ef3779d88e66c910ea171", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-01-13T03:39:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T04:57:34.000Z", "avg_line_length": 20.42, "max_line_length": 56, "alphanum_fraction": 0.5651322233, "include": true, "reason": "import numpy", "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995762509216, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.8507615304265878}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb  8 21:45:48 2019\n\n@author: alankar\n\"\"\"\nimport numpy as np\nimport os\n\ndef trapezoidal(func, a, b, n,*args):\n    h = float(b - a) / n\n    s = 0.0\n    s += func(a,*args)/2.0\n    for i in range(1, n):\n        s += func(a + i*h,*args)\n    s += func(b,*args)/2.0\n    return s * h\n\ndef romberg(func, a, b, n,verbose,*args): #approximation error of order 2n\n    file = open('Romberg Triangle.txt','a')\n    h = float(b - a)\n    T = np.zeros((n+1,n+1))\n    if verbose: file.write('Romberg Triangular matrix: N = %d\\n'%n)\n    for j in range(1,n+1):\n        T[j,1] = (h/2)*(func(a,*args)+2*np.sum(func(a+np.arange(h,int(2**(j-1))*h,h),*args))+func(b,*args)) #Comp Trapz\n        if verbose: file.write('%f  '%T[j,1])\n        for k in range(2,j+1):\n            T[j,k] = T[j,k-1]+(T[j,k-1]-T[j-1,k-1])/(4**(k-1)-1) #Richardson Extrp\n            if verbose: file.write('%f  '%T[j,k])\n        if verbose: file.write('\\n')\n        h/=2\n    if verbose: file.write('\\n\\n')\n    if verbose: file.close()\n    return T[n,n]\n\n\nf = lambda x:np.sin(np.sqrt(100*x))**2\n\ntol = 1e-6\n\nn = 1\nI_old = 0\nI_new = trapezoidal(f,0,1,n)\n\nprint('TRAPEZOIDAL INTEGRATION (ADAPTIVE):')\nwhile (abs(I_new-I_old)>tol):\n    n *= 2\n    print('Slices = %d'%n)\n    I_old = I_new\n    I_new = trapezoidal(f,0,1,n)\n    print('I = %.7f'%I_new)\n    print('Fractional error estimate: %e'%abs((I_new-I_old)/I_new))\n\nn = 1\nI_old = 0\nI_new = romberg(f,0,1,n,True)\nos.remove('Romberg Triangle.txt')\n\nprint('\\n\\nROMBERG INTEGRATION:')\nwhile (abs(I_new-I_old)>tol):\n    n *= 2\n    print('Slices = %d'%n)\n    I_old = I_new\n    I_new = romberg(f,0,1,n,True)\n    print('I = %.7f'%I_new)\n    print('Fractional error estimate: %e'%abs((I_new-I_old)/I_new))\n    \n\"\"\"\nOutput:\n\nTRAPEZOIDAL INTEGRATION (ADAPTIVE):\nSlices = 2\nI = 0.3252319\nFractional error estimate: 5.450032e-01\nSlices = 4\nI = 0.5122829\nFractional error estimate: 3.651322e-01\nSlices = 8\nI = 0.4029974\nFractional error estimate: 2.711814e-01\nSlices = 16\nI = 0.4301034\nFractional error estimate: 6.302188e-02\nSlices = 32\nI = 0.4484147\nFractional error estimate: 4.083563e-02\nSlices = 64\nI = 0.4539129\nFractional error estimate: 1.211304e-02\nSlices = 128\nI = 0.4553485\nFractional error estimate: 3.152691e-03\nSlices = 256\nI = 0.4557113\nFractional error estimate: 7.960349e-04\nSlices = 512\nI = 0.4558022\nFractional error estimate: 1.995014e-04\nSlices = 1024\nI = 0.4558249\nFractional error estimate: 4.990618e-05\nSlices = 2048\nI = 0.4558306\nFractional error estimate: 1.247847e-05\nSlices = 4096\nI = 0.4558321\nFractional error estimate: 3.119738e-06\nSlices = 8192\nI = 0.4558324\nFractional error estimate: 7.799420e-07\n\n\nROMBERG INTEGRATION:\nSlices = 2\nI = 0.3843160\nFractional error estimate: 6.149537e-01\nSlices = 4\nI = 0.3489739\nFractional error estimate: 1.012746e-01\nSlices = 8\nI = 0.4558325\nFractional error estimate: 2.344253e-01\nSlices = 16\nI = 0.4558325\nFractional error estimate: 8.931689e-12\n\"\"\"", "meta": {"hexsha": "af222f9ce9616afec35aef14852d9403f5aad32b", "size": 2969, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw3/07/7.py", "max_stars_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_stars_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:47:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:05:39.000Z", "max_issues_repo_path": "hw3/07/7.py", "max_issues_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_issues_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw3/07/7.py", "max_forks_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_forks_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-21T17:33:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T02:58:56.000Z", "avg_line_length": 23.3779527559, "max_line_length": 119, "alphanum_fraction": 0.6402829235, "include": true, "reason": "import numpy", "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.9059898254600902, "lm_q1q2_score": 0.8507469288988851}}
{"text": "#Find Delannoy Numbers\n\ndef getDelannoyArray(n=5):\n    colk = [k for k in range(n+1)]\n    a=[[ 1 if(j==0 or i==0) else 0 for j in colk] for i in colk]\n    a[1][1]=3\n    for i in range(1,n+1):\n        for j in range(1,n+1):\n            a[i][j] = a[i-1][j]+a[i-1][j-1]+a[i][j-1]\n    \n    return a\n\n#Delannoy Sequence from array\ndef DelannoySequenceFT(n=5,returni=False):\n    a = getDelannoyArray(n)\n    b = [[a[i][j] for j in range(len(a[i])) if(i==j) ][0] for i in range(len(a))]\n    if(returni):\n        return b\n    else:\n        print(b)\n\n#Delannoy Sequence from array (method 2)\ndef DelannoySequenceFT2(n=5,returni=False):\n    colk = [k for k in range(n+1)]\n    a=[[ 1 if(j==0 or i==0) else 0 for j in colk] for i in colk]\n    a[1][1]=3\n    b=[]\n    for i in range(1,n+1):\n        for j in range(1,n+1):\n            if(1==1):\n                a[i][j] = a[i-1][j]+a[i-1][j-1]+a[i][j-1]\n                if(i==j):\n                    b.append(a[i][j])\n            else:\n                continue\n    return b\n\n#Central numbers from Delannoy Sequence\ndef DelannoySequence(n=5,returni=False,roundt=True):\n    from sympy import Integer as mmmint\n    from sympy import Float as mmmfloat\n    a = [1,3]\n    for i in range(2,n+2):\n        b = (3*(2*i-1)*a[i-1]-(i-1)*a[i-2])/i\n        if(roundt==True):\n            b = mmmint(b)\n        else:\n            b = mmmfloat(b)\n        a.append(b)\n        if(not returni):\n            print(b,end=\", \")\n    if(returni):\n        return a[:n]\n    \ndef DelannoArray(countt=10):\n    s = getDelannoyArray(countt)\n    r = range(len(s))\n    from pandas import DataFrame as mmpd\n    df=mmpd(s, columns=r, index=r)\n    df=df.rename_axis(columns=\"n/k\")\n    return df\n    \n#getDelannoyArray()\n#DelannoArray()\n#DelannoySequenceFT2(2000) # 3.26 s\n#DelannoySequenceFT(2000) #3.12 s\n#DelannoySequence(2000) #387 ms", "meta": {"hexsha": "6bd85afc7394139958c25064352179db949125a1", "size": 1833, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Combinatorics/DelannoyArray.py", "max_stars_repo_name": "lonagi/pysasha", "max_stars_repo_head_hexsha": "e344afa03357b7c626c949aa31fac51574e97f48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Combinatorics/DelannoyArray.py", "max_issues_repo_name": "lonagi/pysasha", "max_issues_repo_head_hexsha": "e344afa03357b7c626c949aa31fac51574e97f48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Combinatorics/DelannoyArray.py", "max_forks_repo_name": "lonagi/pysasha", "max_forks_repo_head_hexsha": "e344afa03357b7c626c949aa31fac51574e97f48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3582089552, "max_line_length": 81, "alphanum_fraction": 0.5417348609, "include": true, "reason": "from sympy", "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.9059898178450964, "lm_q1q2_score": 0.8507469202022379}}
{"text": "#-*-conding:utf-8-*-\r\n\r\nimport numpy as np\r\nfrom math import exp, sqrt, log\r\nimport random\r\nfrom scipy.stats.distributions import norm\r\n\r\n'''\r\nParameters:\r\ns0 = initial stock price\r\nk = strike price\r\nr = risk-less short rate\r\nsig = volatility of stock value\r\ndt = t/T = time to maturity\r\nm = the number of path nodes\r\nn = the number of simulation\r\n'''\r\n\r\n\r\ndef black_scholes_model(s0, k, r, sig, dt):\r\n    d1 = (log(s0 / k) + (r + sig ** 2 / 2) * dt) / (sig * sqrt(dt))\r\n    d2 = d1 - sig * sqrt(dt)\r\n    call_bs = s0 * exp(-r * dt) * norm.cdf(d1) - k * exp(-r * dt) * norm.cdf(d2)\r\n    put_bs = k * exp(-r * dt) * norm.cdf(-d2) - s0 * exp(-r * dt) * norm.cdf(-d1)\r\n    return {'call_BS': call_bs, 'put_BS': put_bs}\r\n\r\n\r\ndef monte_carlo_simulation(s0, k, r, sig, dt, m, n):\r\n    list_1 = []  # call option value list\r\n    list_2 = []  # put option value list\r\n    delta_t = dt / m  # length of time interval\r\n\r\n    for i in range(0, n):\r\n        path = [s0]\r\n        for j in range(0, m):\r\n            path.append(path[-1] * exp((r - 0.5 * sig ** 2) * delta_t + (sig * sqrt(delta_t) * random.gauss(0, 1))))\r\n\r\n        put_value = max(k - path[-1], 0)\r\n        call_value = max(path[-1] - k, 0)\r\n        list_2.append(put_value)\r\n        list_1.append(call_value)\r\n    p = np.average(list_2)\r\n    c = np.average(list_1)\r\n    return {'call_MC': c, 'put_MC': p}\r\n\r\n\r\n'''\r\ntrial:\r\na = black_scholes_model(5200, 5200, 0.03, 0.25, 0.08)\r\nb = monte_carlo_simulation(5200, 5200, 0.03, 0.25, 0.08, 20, 2000000)\r\n\r\nprint(a)\r\nprint(b)\r\n'''\r\n", "meta": {"hexsha": "66b29b0dae0054c2ac0807ed11e6e0adf381eaf6", "size": 1530, "ext": "py", "lang": "Python", "max_stars_repo_path": "European_option.py", "max_stars_repo_name": "ITNeri/Option_Pricing", "max_stars_repo_head_hexsha": "7151698785a48c666c4fa82877102da9462a2405", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-26T14:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T14:56:21.000Z", "max_issues_repo_path": "European_option.py", "max_issues_repo_name": "ITNeri/Option_Pricing", "max_issues_repo_head_hexsha": "7151698785a48c666c4fa82877102da9462a2405", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "European_option.py", "max_forks_repo_name": "ITNeri/Option_Pricing", "max_forks_repo_head_hexsha": "7151698785a48c666c4fa82877102da9462a2405", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8181818182, "max_line_length": 117, "alphanum_fraction": 0.5673202614, "include": true, "reason": "import numpy,from scipy", "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018362008348, "lm_q2_score": 0.8723473614033683, "lm_q1q2_score": 0.850714748645518}}
{"text": "# Create a numpy array from the weight_lb list with the correct units. Multiply by 0.453592 to go from pounds to kilograms.\n# Store the resulting numpy array as np_weight_kg.\n# Use np_height_m and np_weight_kg to calculate the BMI of each player.\n# Use the following equation:\n# BMI = weight(kg) / height (m3)\n# save the resulting numpy array as bmi\n# Print out bmi.\n# height and weight are available as regular lists\n\n# Import numpy\nimport numpy as np\n\n# Create array from height_in with metric units: np_height_m\nnp_height_m = np.array(height_in) * 0.0254\n\n# Create array from weight_lb with metric units: np_weight_kg\nnp_weight_kg = np.array(weight_lb) * 0.453592\n\n# Calculate the BMI: bmi\nbmi = np_weight_kg / np_height_m ** 2\n\n# Print out bmi\nprint(bmi)\n", "meta": {"hexsha": "5ac93a900f8dd76c156f7ea7f46e47f6ba5ffc11", "size": 759, "ext": "py", "lang": "Python", "max_stars_repo_path": "01-introduction to python for data science/04-numpy/baseball-players-bmi.py", "max_stars_repo_name": "thelc127/Data-Scientist-Career-Track-Datacamp", "max_stars_repo_head_hexsha": "56d0ec0ece7fa9127e72b0da598c89f15f31b6b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-21T04:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T08:32:41.000Z", "max_issues_repo_path": "01-introduction to python for data science/04-numpy/baseball-players-bmi.py", "max_issues_repo_name": "thelc127/Data-Scientist-Career-Track-Datacamp", "max_issues_repo_head_hexsha": "56d0ec0ece7fa9127e72b0da598c89f15f31b6b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01-introduction to python for data science/04-numpy/baseball-players-bmi.py", "max_forks_repo_name": "thelc127/Data-Scientist-Career-Track-Datacamp", "max_forks_repo_head_hexsha": "56d0ec0ece7fa9127e72b0da598c89f15f31b6b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.625, "max_line_length": 123, "alphanum_fraction": 0.7641633729, "include": true, "reason": "import numpy", "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668657039606, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.8507067504707294}}
{"text": "import numpy as np\r\nfrom sklearn import linear_model\r\nfrom sklearn import datasets\r\n\r\nclass Perceptron():\r\n    def __init__(self,model='prime',max_iter=1000,lamb=10**-2):\r\n        self.model=model\r\n        self.max_iter=max_iter\r\n        self.lamb=lamb\r\n    \r\n    def train(self,X_train,y_train):\r\n        self.X_train=X_train\r\n        self.y_train=y_train\r\n        train_no,feature_no=X_train.shape\r\n        W=np.zeros((feature_no,1))\r\n        alpha=np.zeros((train_no,1))\r\n        b=0\r\n        flag=True\r\n        iter_no=0\r\n        while flag:\r\n            iter_no+=1\r\n            flag=False\r\n            for i in range(train_no):\r\n                if self.model=='dual':\r\n                    W=np.zeros((feature_no,1))\r\n                    for j in range(train_no):\r\n                        W+=alpha[j]*y_train[j]*X_train[j].reshape(feature_no,1)\r\n                    if y_train[i]*(X_train[i].dot(W)+b)<=0:\r\n                        alpha[i]=alpha[i]+self.lamb\r\n                        b=b+self.lamb*y_train[i]\r\n                        flag=True\r\n                        break                \r\n                if self.model=='prime':\r\n                    if y_train[i]*(X_train[i].dot(W)+b)<=0:\r\n                        W=W+self.lamb*y_train[i]*X_train[i].reshape(feature_no,1)\r\n                        b=b+self.lamb*y_train[i]\r\n                        flag=True\r\n                        break\r\n                    \r\n            if iter_no>self.max_iter:\r\n                break\r\n        self.W=W\r\n        self.b=b\r\n        self.alpha=alpha\r\n        \r\n    def predict(self,X_test):\r\n        train_no,feature_no=self.X_train.shape\r\n        if self.model=='prime':\r\n            y_pred=np.sign(X_test.dot(self.W)+self.b)\r\n        if self.model=='dual':\r\n            W=np.zeros((feature_no,1))\r\n            for j in range(train_no):\r\n                W+=self.alpha[j]*self.y_train[j]*self.X_train[j].reshape(feature_no,1)\r\n            y_pred=np.sign(X_test.dot(W)+self.b)\r\n        return y_pred.ravel()\r\n        \r\nif __name__=='__main__':\r\n#    X_train=np.array([[3,3],[4,3],[1,1]])\r\n#    y_train=np.array([1,1,-1])\r\n#    X_test=np.array([[100,100],[99,99]])\r\n    \r\n    index=np.random.permutation(150)\r\n    iris=datasets.load_iris()\r\n    X_train=iris['data'][:,(2,3)]\r\n    y_train=(iris['target']==2).astype(np.float64)\r\n    y_train[y_train==0]=-1\r\n    y_train_1=y_train\r\n    X_test=X_train\r\n    X_train=X_train[index]\r\n    y_train=y_train[index]\r\n    \r\n    model=Perceptron(model='prime',max_iter=10**3,lamb=10**-4)\r\n    model.train(X_train,y_train)\r\n    y_pred=model.predict(X_test)\r\n    print('Perceptron',y_pred)\r\n    print(sum(y_pred==y_train_1))\r\n    \r\n    model=linear_model.Perceptron()\r\n    model.fit(X_train,y_train)\r\n    y_pred=model.predict(X_test)\r\n    print('sklearn',y_pred)\r\n    print(sum(y_pred==y_train_1))\r\n    \r\n                ", "meta": {"hexsha": "4d0d84f556b0c6864f5a90b33d490b640198f2ea", "size": 2845, "ext": "py", "lang": "Python", "max_stars_repo_path": "Supervised Machine Learning Algorithms/Perceptron.py", "max_stars_repo_name": "mikema2019/Machine-learning-algorithms", "max_stars_repo_head_hexsha": "fbbe0a574f9cc731f34cf1f8278bd455a5e51769", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Supervised Machine Learning Algorithms/Perceptron.py", "max_issues_repo_name": "mikema2019/Machine-learning-algorithms", "max_issues_repo_head_hexsha": "fbbe0a574f9cc731f34cf1f8278bd455a5e51769", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Supervised Machine Learning Algorithms/Perceptron.py", "max_forks_repo_name": "mikema2019/Machine-learning-algorithms", "max_forks_repo_head_hexsha": "fbbe0a574f9cc731f34cf1f8278bd455a5e51769", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.869047619, "max_line_length": 87, "alphanum_fraction": 0.5145869947, "include": true, "reason": "import numpy", "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407137099625, "lm_q2_score": 0.8740772384450968, "lm_q1q2_score": 0.850687555381939}}
{"text": "\n## Worksheet 1\n\nimport numpy as np\nimport numpy.linalg as la\n\n# The first worksheet covers basic topics in linear algebra. There is also a basic question on nonlinear root-finding.\n\n#### Answer Coding Question 3\n\ndef MatrixConditionCheck(A, MaxConditionNumber = 10.0):\n    \"\"\"Check the condition number of a matrix.\n    Only write output to screen if the condition number is too high.\n    Should return something, really.\"\"\"\n\n    ConditionNumber = la.cond(A)\n    if ConditionNumber > MaxConditionNumber:\n        print(\"The condition number of the matrix\\n{0}\\n\"\\\n              \"is too large (i.e., it is {1:.4} which is larger\"\\\n              \" than {2:.4}).\\n\".\\\n              format(A, ConditionNumber, MaxConditionNumber))\n        \n    \n#### Answer Coding Question 4\n\ndef bisection(f, interval, tolerance = 1.e-10):\n    \"\"\"General bisection method for a function f of one variable.     \n    There must be at least one root within the interval.     \n    Default tolerance (width of the interval) is 1e-10.\"\"\"\n    \n    assert len(interval) == 2\n    \n    # Get the endpoints of the interval\n    [x_min, x_max] = interval\n    \n    # Values at the ends of the domain\n    f_min = f(x_min)\n    f_max = f(x_max)\n    \n    # Check that at least one root lies within the interval\n    assert(f_min * f_max < 0.0)\n    \n    # The loop\n    x_c = (x_min + x_max) / 2.0\n    f_c = f(x_c)\n    iteration = 0\n    while ((x_max - x_min > tolerance) and \\\n               (np.abs(f_c) > tolerance) and \\\n               (iteration < 100)):\n        iteration = iteration+1    \n        if f_min * f_c < 0.0:\n            x_max = x_c\n            f_max = f_c\n        else:\n            x_min = x_c\n            f_min = f_c\n        x_c = (x_min + x_max) / 2.0\n        f_c = f(x_c)\n\n    print(\"The root is approximately {0} where \"\\\n          \"f is {1:.4} (tolerance {2:.4})\".format(x_c, f_c, tolerance))\n    return x_c\n\n# Now define the function whose root is to be found\ndef fn_worksheet1_q4(x):\n    \"\"\"Simple function defined in question, f(x) = tan(x) - exp(-x).\"\"\"\n    \n    return np.tan(x) - np.exp(-x)\n", "meta": {"hexsha": "68e3145b8f7000d0c2c1af0544223f3ceb0b1667", "size": 2079, "ext": "py", "lang": "Python", "max_stars_repo_path": "Worksheets/Worksheet1_Functions.py", "max_stars_repo_name": "josh-gree/NumericalMethods", "max_stars_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2015-02-12T19:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:34:11.000Z", "max_issues_repo_path": "Worksheets/Worksheet1_Functions.py", "max_issues_repo_name": "josh-gree/NumericalMethods", "max_issues_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-05-24T19:49:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T21:40:42.000Z", "max_forks_repo_path": "Worksheets/Worksheet1_Functions.py", "max_forks_repo_name": "josh-gree/NumericalMethods", "max_forks_repo_head_hexsha": "03cb91114b3f5eb1b56916920ad180d371fe5283", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:30:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:59:39.000Z", "avg_line_length": 30.1304347826, "max_line_length": 118, "alphanum_fraction": 0.594035594, "include": true, "reason": "import numpy", "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.917302665802808, "lm_q1q2_score": 0.8506728269473849}}
{"text": "# Chapter 7: Cross-Correlations, Fourier Transform, and Wavelet Transform\nprepared by Gilbert Chua\n\nGaining a deeper undersanding of time series dynamics and classifying them, we look at time series forecasting through another lens.\n\nIn this chapter, we will take a different approach to how we analzye time series that is complementary to forecasting. Previously, methods of explaining such as the Granger Causality, Simplex Mapping, and Convergent Cross Mapping, focused on the time domain - the values of the time series when measured over time or in its phase space. While both are useful for many tasks, it can be often useful to transform these time domain measurements to unearth patterns which are difficult to tease out. Specifically, we want to look at the frequency domain to both analyze the dynamics and perform pre-processing techniques that may be used to modify real-world datasets.\n\nWe will be analyzing the dynamics of time series not exactly to make forecasts, but to understand them in terms of their frequencies in complement to the previous methods of causality and explainability presented.\n\nWe introduce three techniques:\n\n    1) Cross-correlations\n\n    2) Fourier Transform\n\n    3) Wavelet Transform\n\nand test their use on the Jena Climate Dataset (2009-2016) along with a handful of other datasets.\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport pandas as pd\nfrom datetime import date, timedelta\nimport scipy as scp\nimport random\nfrom statsmodels.tsa.stattools import acf, adfuller, ccf, ccovf\nfrom itertools import repeat\nimport pywt\nimport os\nimport warnings\nwarnings.filterwarnings('ignore')\n\n## Cross-correlation Between Two Signals\n\nPhenomenon captured by time series may not happen at the exact same time with some lag $h$ between them. A simple example of this is Sonar technology. The time series associated with the response from the sound waves being reflected comes at some lag compared to the time series of the device emitting the initial sound waves. It is this lag we want to measure when we use the cross-correlation function (CCF). This function was discussed previously in Chapter 3 - Vector Autoregressive Methods. We will explore this concept in this chapter and adopt the same definition.\n\n\nLet $\\mathbf\\Gamma_h$ be the covariance matrix at lag $h$, $\\mathbf D$ be a $N\\times N$ diagonal matrix containing the standard deviations of $y_{i,t}$ for $i=1, ..., N$. The lagged correlation matrix of $\\mathbf{y}_t$ is defined as\n\n\n$$\\boldsymbol\\rho_h = \\mathbf D^{-1}\\mathbf\\Gamma_h\\mathbf D^{-1}$$\n\nThe $(i,j)$th element of $\\boldsymbol\\rho_h$ is the correlation coefficient between $y_{i,t}$ and $y_{j,t-h}$:\n\n$$\\rho_{i,j}(h) = \\dfrac{Cov\\left[y_{i,t}, y_{j,t-h} \\right]}{\\sigma_{i,t} \\sigma_{j,t}}$$\n\nwhere $Cov[y_{i,t}, y_{j,t-h}]$ is the covariance of two time series $y_{i,t}$ and $y_{j,t-h}$ at time $t$ and lag $h$.\n\nThe values of the correlation coefficient from the cross-correlation function are interpreted as such:\n\n|Correlation Coefficient| Interpretation |\n|:----|:----|\n|$\\rho_{i,j}(0)\\neq0$|$y_{i,t}$ and $y_{j,t}$ are *contemporaneously linearly correlated*|\n|$\\rho_{i,j}(h)=\\rho_{j,i}(h)=0$ for all $h\\geq0$|$y_{i,t}$ and $y_{j,t}$ share *no linear relationship*|\n|$\\rho_{i,j}(h)=0$ and $\\rho_{j,i}(h)=0$ for all $h>0$|$y_{i,t}$ and $y_{j,t}$ are said to be linearly *uncoupled*|\n|$\\rho_{i,j}(h)=0$ for all $h>0$, but $\\rho_{j,i}(q)\\neq0$ for at least some $q>0$|There is a *unidirectional (linear) relationship* between $y_{i,t}$ and $y_{j,t}$, where $y_{i,t}$ does not depend on $y_{j,t}$, but $y_{j,t}$ depends on (some) lagged values of $y_{i,t}$|\n|$\\rho_{i,j}(h)\\neq0$ for at least some $h>0$ and $\\rho_{j,i}(q)\\neq0$ for at least some $q>0$|There is a *bi-directional (feedback) linear relationship* between $y_{i,t}$ and $y_{j,t}$|\n\n### Noisy Signals\n\nTo demonstrate this, we take the case of two simple yet noisy time series.\n\nWe want to measure the shift between two periodic signals Two sine waves are generated that are identical in both amplitude and frequency but one is shifted forward in time. By taking the maximum of the cross-correlation, we should be able to retrieve how much one of the time series leads (or lags!) the other.\n\ndef sine_wave(amp=1, freq=1, sample_rate=200, duration=5,\n              plot=True, shift=0, noise=0):\n    x = np.linspace(0, duration, sample_rate*duration)\n    frequencies = x * freq\n    y = amp*np.sin((2 * np.pi * frequencies) + shift) + noise\n    if plot:\n        plt.subplots(figsize=(15, 2))\n        plt.plot(x, y)\n        plt.show()\n    return x, y\n\nsamp_rate = 500  # Sampling Frequency in Hertz\ndur = 5  # Duration in Seconds\n\namp1 = 1  # Amplitude of Sine Wave 1\nfreq1 = 1  # Frequency of Sine Wave 1\n\namp2 = 1  # Amplitude of Sine Wave 2\nfreq2 = 1  # Frequency of Sine Wave 2\n\nphase_shift = np.pi/2  # Phase shift\nnoise = np.random.uniform(-1, 1, samp_rate*dur)\nx1, y1 = sine_wave(amp1, freq1, samp_rate, dur, noise=noise,\n                   plot=False)\nnoise = np.random.uniform(-0.3, 0.3, samp_rate*dur)\nx2, y2 = sine_wave(amp2, freq2, samp_rate, dur, noise=noise,\n                   shift=phase_shift, plot=False)\n\nplt.subplots(figsize=(15, 2))\nplt.plot(np.linspace(0, dur, samp_rate*dur), y1, label='$y1$')\nplt.plot(np.linspace(0, dur, samp_rate*dur), y2, label='$y2$')\nplt.ylabel('Value')\nplt.xlabel('Time (in $s$)')\nplt.legend();\n\nplt.subplots(figsize=(15, 2))\n\nccf_12 = ccf(y1, y2, unbiased=False)\nplt.ylabel('Correlation Coefficient')\nplt.xlabel('Lag $h$')\nplt.stem(np.linspace(0, dur, samp_rate*dur), ccf_12)\npeak = np.argmax(ccf_12)/samp_rate\nplt.axvline(peak, c='orange')\nprint('Maximum at:', peak, '(in $s$)')\n\nWe find that the maximum correlation between $y_2$ and $y_1$ occurs at ~0.247 seconds, approximately 1/4 of the frequency. This is very close to the theoretical value of 0.25 seconds corresponding to a phase shift of $\\frac{\\pi}{2}$. Using only direct measurements from the data, albeit synthetic, we are able to retrieve a reasonable estimate of the lag and delay between them.\n\nBy measuring the cross-correlation between these two signals we can find how far apart we need to adjust the time series to maximize their linear correlation. It is important to note that unlike the different causality measures discussed (Granger, Convergent Cross-mapping, etc.), cross-correlation does **not** give insights into causality - rather it only gives correlations.\n\n### Example 1: Cross-Correlations in the Jena Climate Data\n\nLet us look at how cross-correlations can be used to unearth relationships in real data. We will again use the Jena Climate Dataset to analyze the average temperature. This time, we will look at the relationship between daily temperature and daily wind speed.\n\ndf = pd.read_csv('../data/jena_climate_2009_2016.csv')\ndisplay(df.head())\ndata = df.iloc[:, 1:].astype(float).to_numpy()\ntemp = data[:, 1][::144]  # Temperature (in degrees Celsius) at one sample/day\nwind = data[:, 10][::144]  # Wind Speed (in m/s) at one sample/day\ndur = len(temp)\nsamp_rate = 1\n\nplt.subplots(figsize=(15, 2))\nplt.plot(range(len(temp)), temp, label='Temperature')\nplt.plot(range(len(wind)), wind, label='Wind Velocity')\nplt.legend();\n\nWe rescale the graphs so that we can easily visualize them.\n\nplt.subplots(figsize=(15, 2))\nplt.plot(range(len(temp)), (temp-np.mean(temp)) /\n         np.std(temp), label='Temperature')\nplt.plot(range(len(wind)), (wind-np.mean(wind)) /\n         np.std(wind), label='Wind Velocity')\nplt.ylabel('Value')\nplt.xlabel('Time (in days)')\nplt.legend();\n\nFrom previous chapters, we know that these time series are stationary. With stationarity, we can proceed with applying the CCF to these two time series.\n\nplt.subplots(figsize=(15, 2))\n\nccf_12 = ccf(temp, wind, unbiased=False)\nplt.ylabel('Correlation Coefficient')\nplt.xlabel('Lag $h$')\nplt.stem(np.linspace(0, dur, samp_rate*dur), ccf_12)\npeak = np.argmax(ccf_12)/samp_rate\nplt.axvline(peak, c='r')\nprint('Maximum at:', peak, '(in $s$)')\n\nWe find that the shift maximizing the correlation between the daily values of temeperature and wind speed are 178 samples. An interesting result is that the correlation at $s=0$ is at a minimum. Both of these suggest that temperature and wind speed are periodic functions mirror each other in that when one is maximized, the other is minimized. We estimate then that the wind speed leads the temperature values by 178 days. \n\nIt should be noted that unlike Granger Causality which also draws relationships between multiple time series, cross-correlation does not provide us with the causality between the two. At best, cross-correlation shows the synchronocity between two time series.\n\n### Example 2: Cross-Correlations Between Precipitation and Flow in the Sudbury River\n\n\nWe apply cross-correlation analysis on the daily stream flow of a river and the precipitation in its surrounding area. The data will be coming from the United States Geological Survey's (USGS) Real-time Water Data for the Nation and covers the Subdury River at Saxonville, Massachusetts for the year 2000. It comprises of the daily mean flow of water measured by the the USGS station. Understanding the causes and dynamics of flow in this specific river can have profound implications on managing the integity and diversity of its ecosystem.\n\nflow_df = pd.read_csv('../data/cc/flowsud_2000.txt', sep='\\t')\nflow_df.columns = ['USGS', 'site_no', 'datetime', 'flow', '-']\n\nflow = flow_df['flow']\n\nrain_df = pd.read_csv('../data/cc/weather_2000.txt')\nrain_df['Prcp'] = rain_df['Prcp'].replace('T', 0.0005).astype(float)\n\nrain = rain_df['Prcp']\n\ndur = len(rain)\nsamp_rate = 1\n\nplt.subplots(figsize=(15, 2))\nplt.plot(flow, label='Stream Flow')\nplt.plot(rain, label='Precipitation')\nplt.legend();\n\nOnce again, we rescale the graphs so that we can easily visualize them.\n\nplt.subplots(figsize=(15, 2))\nplt.plot((rain-np.mean(rain))/np.std(rain), label='Preciptation (exaggerated)')\nplt.plot((flow-np.mean(flow))/np.std(flow), label='Stream Flow')\nplt.xlabel('Day of the Year')\nplt.legend();\n\nWe perform the Augmented Dickey-Fuller test on the two time series to figure out if they are stationary. If they are indeed stationary, we can proceed to performing the cross-correlation.\n\nresult = adfuller(flow)\nprint('ADF Statistic: %f' % result[0])\nprint('p-value: %f' % result[1])\nprint('Critical Values:')\nfor key, value in result[4].items():\n    print('\\t%s: %.3f' % (key, value))\n\nresult = adfuller(rain)\nprint('ADF Statistic: %f' % result[0])\nprint('p-value: %f' % result[1])\nprint('Critical Values:')\nfor key, value in result[4].items():\n    print('\\t%s: %.3f' % (key, value))\n\nBoth time series are stationary and we proceed with applying the CCF.\n\nplt.subplots(figsize=(15, 2))\n\nccf_12 = ccf(flow, rain, unbiased=False)\nplt.ylabel('Correlation Coefficient')\nplt.xlabel('Lag $h$')\nplt.stem(np.linspace(0, dur, samp_rate*dur), ccf_12)\npeak = np.argmax(ccf_12)/samp_rate\nplt.axvline(peak, c='r')\nprint('Maximum at:', peak, '(in $days$)')\n\nWe find that the maximum correlation happens when precipitation leads stream flow by 1 day. While cross-correlation alone cannot give us causality, understanding of the measurements involved can be used to argue such. In the case of rainfall and precipitation, there is established understanding that precipitation leads to increases in river flow. We can conclude with some confidence that precipitation will cause an increase in river flow after 1 day.\n\nTo supplement our analysis, we move into the frequency domain with the Fourier Transform by first understanding the Fourier Series.\n\n## The Fourier Series:\n\nAny periodic signal can be broken down into a summation of sine and cosine waves. A periodic time series $X(t)$ can be broken down into fundamental frequencies given by the Fourier Series:\n\n$\\begin{align} y(t) = \\frac{a_0}{2}  + \\sum_{n=1}^{\\infty}{a_n cos(nt)) + b_n sin(nt)} \\end{align}$\n\nIntegrating both sides by $\\int+{-\\pi}^{\\pi} cos(mt)dt$ where $m$ is an integer:\n\n$\\begin{align} \\int_{-\\pi}^{\\pi}{y(t)cos(mt)dt} = \\frac{1}{2} a_0 + \\sum_{n=1}^{\\infty}{\\int_{-\\pi}^{\\pi}a_n cos(nt)cos(mt)dt + \\sum_{n=1}^{\\infty}\\int_{-\\pi}^{\\pi}b_n sin(nt) cos(mt)dt} \\end{align}$\n\nVia orthogonality between $cos$ and $sin$ over $[-\\pi,\\pi]$:\n\n$\\begin{align} \\int_{-\\pi}^{\\pi}{cos(nt)cos(mt)dt} = 0,   m\\neq n \\end{align}$\n$\\begin{align} \\int_{-\\pi}^{\\pi}{sin(nt)cos(mt)dt} = 0,   all m,n \\end{align}$\n$\\begin{align} \\int_{-\\pi}^{\\pi}{cos(nt)sin(mt)dt} = 0,   m\\neq n \\end{align}$\n\nEquation 4 reduces to:\n\n$\\begin{align} \\int_{-\\pi}^{\\pi}{y(t)cos(mt)dt} = a_m \\int_{-\\pi}^{\\pi}cos^{2}(mt)dt \\end{align}$\n\nSolving for this a_m, we find that:\n\n$\\begin{align} a_m = \\frac{1}{\\pi}\\int_{-\\pi}^{\\pi}{y(t) cos(mt)dt} \\end{align}$\n\nDoing the same for b_m, we find the similar coefficient:\n\n$\\begin{align} b_m = \\frac{1}{\\pi}\\int_{-\\pi}^{\\pi}{y(t) sin(mt)dt} \\end{align}$\n\nfor $n =0,1,2...,$ where:\n\n$n = 0$ is the constant component of the signal\n\n$n = 1$ is the \\textit{fundamental} corresponding to a sine/cosine wave whose period matches $y(t)$'s period exactly\n\n$n = 2$ is the first harmonic corresponding to a sine/cosine whose period matches $\\frac{1}{2}$ of $y(t)$'s period\n\n$n = 3$ is the second harmonic corresponding to a sine/cosine whose period matches $\\frac{1}{3}$ of $y(t)$'s period\n\n\nOne useful quantity to look at is the energy of a signal as it tells us how \"much\" of a signal there is. We define a single coefficient $c_n^{2}$ to describe the \"energy\" of a signal at a specific frequency where $c_n$ is given by:\n\n$\\begin{align}c_n = \\left[\\frac{1}{2}(a^2_n + b^2_n)\\right]^{\\frac{1}{2}}\\end{align}$\n\nThe square of these coefficients ($c_n^{2}$) corresponds to the energy of a certain frequency $n$.\n\n## The Fourier Transform:\n\nTransforming a signal from the time domain into the frequency ($\\omega$) domain using this method is called the \\textbf{Fourier Transform (FT)}. The FT is given by:\n\n\\begin{align} \\hat{y}(\\omega) = \\int_{-\\infty}^{\\infty}{y(t)e^{-2\\pi i \\omega t}d\\omega} \\end{align}\n\nTo better understand the FT, let us take a look at some of its applications.\n\n### FT of a Pure Signal\n\nsamp_rate = 500  # Sampling Frequency in Hertz\ndur = 5  # Duration in Seconds\namp = 10  # Amplitude of Sine Wave\nfreq = 5  # Frequency of Sine Wave\nx, y = sine_wave(amp, freq, samp_rate, dur, plot=True)\n\nLet's work with ideal conditions first. Let's apply the Fourier Transform on the single sine wave with frequency of 5 Hz.\n\ny_ft = scp.fft.fft(y)\nfreqs = scp.fft.fftfreq(x.shape[-1])*samp_rate\nplt.subplots(figsize=(5, 5))\nplt.plot(freqs, y_ft.real**2)\nplt.ylabel('Energy')\nplt.xlabel('Frequency (in Hz)')\nprint('Peak at:', np.argmax(y_ft.real**2)/dur, 'Hz')\n\nWe see two peaks when the frequency is 5 and -5.\n\nThe left-hand side corresponds to negative frequencies. Physically, negative frequencies are not very meaningful but their presence is important in calculating for the Fourier Transform. By finding where the energy peaks, we can find frequencies that best describe the time series.\n\nAdditionally, the FT is a perfectly (to numerical precision) reversible process. By knowing the energies of each frequency, we can retrieve the original signal by performing an \\textbf{Inverse Fourier Transform (IFT)}.\n\nplt.subplots(figsize=(15, 2))\nplt.plot(x, scp.fft.ifft(y_ft).real)\nplt.xlabel('Frequency')\nprint(\"Is close:\", np.allclose(scp.fft.ifft(y_ft), y))\n\n### FT on Mixed Signals\n\nAn important use of the FT is analyzing signals with mixed frequencies. We can perform the above exercise on 2 combined waves (or even an arbitrary number of waves with differing frequencies!) to find which frequencies are present in our signal.\n\nsamp_rate = 500  # Sampling Frequency in Hertz\ndur = 5  # Duration in Seconds\n\namp1 = 1  # Amplitude of Sine Wave 1\nfreq1 = 5  # Frequency of Sine Wave 1\n\namp2 = 1  # Amplitude of Sine Wave 2\nfreq2 = 17  # Frequency of Sine Wave 2\n\nx1, y1 = sine_wave(amp1, freq1, samp_rate, dur, plot=False)\nx2, y2 = sine_wave(amp2, freq2, samp_rate, dur, plot=False)\ny = y1 + y2  # Simply overlapping the two signals\nplt.subplots(figsize=(15, 2))\nplt.xlabel('Time')\nplt.plot(x1, y);\n\nEyeballing the graph, it is challenging to determine its exact frequency make up.\n\ny_ft = scp.fft.fft(y)\nfreqs = scp.fft.fftfreq(x1.shape[-1])*samp_rate\n\nplt.subplots(figsize=(5, 5))\nplt.plot(freqs, y_ft.real**2)\nplt.xlabel('Frequency (in Hz)')\npeaks = scp.signal.find_peaks(y_ft.real**2)\npeak_vals = peaks[0][:len(peaks[0])//2]/dur\nprint('Peaks at:', peak_vals)\n\nThe FT makes it very easy to find the frequencies of the signal even if they are mixed.\n\n## Noise Filtering\n\nReal time series data are never free from noise making it tricky to find the real dynamics of whatever it is measuring. We may end up trying to model noise and end up overlooking the real behavior of the time series.\n\n\nThankfully, we can manipulate time series data in the frequency domain to eliminate one of the most types of noise - white noise. White noise pervades time series data and by definition, has components across all frequencies. Usually, a time series with white noise is represented as:\n\n\\begin{align} y(t) = s(t) + v(t) \\end{align}\n\nwhere $s(t)$ is the true signal we want to retrieve from $y(t)$ and $v(t)$ is white noise we want to eliminate. We simulate this below by adding white noise to the signal.\n\n### Filtering by Energy Level\n\nWhite noise is characterized by having energy levels almost equal for all frequencies. Such a signal can be generate by simply using a random number generator.\n\nnoise = np.random.uniform(-1,1, len(y))\nplt.subplots(figsize=(15, 2))\nplt.plot(x1, noise);\n\nTaking the FT of the white noise, we find that indeed, for almost all the frequencies, there are positive energy values for them all. This means that for all frequencies, the white noise will have some contribution which can affect our analysis of the time series.\n\nnoise_ft = scp.fft.fft(noise)\nfreqs = scp.fft.fftfreq(x1.shape[-1])*samp_rate\npeaks = scp.signal.find_peaks(noise_ft.real**2)\n\nplt.subplots(figsize=(5, 5))\nplt.plot(freqs, noise_ft.real**2)\nplt.ylabel('Energy')\nplt.xlabel('Frequency');\n\nThe addiiton of white noise to the mixed frequency signal makes its actual behavior less observable. The white noise has \"corrupted\" the signal and presents a challenge we find when making any measurement. How can we sift out the original mixed signal when the data we receive is noisy?\n\ny_noisy = y+noise\nplt.subplots(figsize=(15, 2))\nplt.plot(x1, y_noisy);\n\nThe resulting FT of the noisy signal results in multiple peaks being found. This poses a problem if we are trying to find the appropriate periodic trends in our data. Luckily, the noise appears to be present only at low energy levels. Should measurements have been done reasonably well in collecting this data, noise can be managed as they only have low energy levels.\n\ny_ft = scp.fft.fft(y_noisy)\nfreqs = scp.fft.fftfreq(x1.shape[-1])*samp_rate\npeaks = scp.signal.find_peaks(y_ft.real**2)\npeak_vals = peaks[0][:len(peaks[0])//2]/dur\nprint('Peaks at:', peak_vals)\n\nplt.subplots(figsize=(5, 5))\nplt.plot(freqs, y_ft.real**2)\nplt.ylabel('Energy')\nplt.xlabel('Frequency');\n\nIn crude fashion, we can set a hard threshold that removes the coefficients of frequencies below a certain energy level . One way to accomplish this is by setting the cut-off as a multiple of the standard deviation. The Fourier Transform allows us to make such \n\n\\textit{Conversely, we can perform the same method to eliminate high energy signals or even select those in a certain band}  \n\nthreshold = 3*np.std(y_ft.real)\npeaks = scp.signal.find_peaks(y_ft.real, threshold=threshold)\npeak_vals = peaks[0][:len(peaks[0])//2]/dur\nprint('Peaks at:', peak_vals)\n\nBy visual inspection and setting an arbitrary threshold of 3x the standard deviation, we are able to retrieve a clearer signal of the dominant frequencies, albeit with the likely addiiton of some stray frequencies. Obtaining the exact signal from a noisy one can be very difficult but with judicious application and an understanding of the underlying systme, filtering by energy levels can be a quick and effective way to modify your time series.\n\ny_ft_denoised = [0 if x < threshold else x for x in y_ft]\nplt.subplots(figsize=(15, 2))\ny_denoised = scp.fft.ifft(y_ft_denoised)\nplt.plot(x1, y_denoised.real);\n\n### Filtering by Frequency\n\nhf_noise = sine_wave(amp, 70, samp_rate, dur, plot=False)[1]\n\ny_hf_noisy = y+hf_noise\nplt.subplots(figsize=(15, 2))\nplt.plot(x, y_hf_noisy);\n\nObserving the FT of a signal with high frequency noise, the noise dominates the energy spectrum and masks the underlying signal.\n\ny_ft_hf = scp.fft.fft(y_hf_noisy)\nfreqs = scp.fft.fftfreq(x.shape[-1])*samp_rate\nplt.plot(freqs, y_ft_hf.real**2)\npeaks = scp.signal.find_peaks(y_ft_hf.real)\npeak_vals = peaks[0][:len(peaks[0])//2]/dur\nplt.ylabel('Energy')\nplt.xlabel('Frequency')\nprint('Peaks at:', peak_vals)\n\nWhile the loewr frequency peaks of the signal can still be retrieved, the extreme noise will make it untenable for most forecasting purposes. These high frequencies* can be eliminated to retrieve the original signal. Guided by our desire to observe the signals that exhibit lower frequencies, we can force the energies of all frequencies above a desired threshold to 0 and perform the IFT to obtain the \n\n\\textbf{*}\\textit{We can do the same for low frequencies and those in a \"band\".} \n\nfreqs = scp.fft.fftfreq(x.shape[-1])*samp_rate\nfreqs\n\nf_thresh = 20\n\nfreqs = scp.fft.fftfreq(x.shape[-1])*samp_rate\ny_ft_hf_filtered = y_ft_hf.copy()\ny_ft_hf_filtered[(abs(freqs.real) > f_thresh)] = 0\n\nplt.plot(freqs, y_ft_hf_filtered.real**2)\nplt.ylabel('Energy')\nplt.xlabel('Frequency');\npeaks = scp.signal.find_peaks(y_ft_hf_filtered.real)\npeak_vals = peaks[0][:len(peaks[0])//2]/dur\nprint('Peaks at:', peak_vals)\n\nplt.subplots(figsize=(15, 2))\ny_lf = scp.fft.ifft(y_ft_hf_filtered).real\nplt.plot(x1, y_lf.real);\n\n### Example 3: Filtering via FT in the Jena Climate Dataset\n\nLooking at climate information, we can glean insights into the seasonality of climate patterns. Let's examine the mean daily temperature of the Jena climate dataset and apply FT to examine its seasonality.\n\ndf = pd.read_csv('../data/jena_climate_2009_2016.csv')\ndisplay(df.head())\ndf['Date Time'] = pd.to_datetime(\n    df['Date Time'], dayfirst=True, format=\"%d.%m.%Y %H:%M:%S\")\ndf['Date'] = df['Date Time'].dt.date\nmean_temps = df.groupby('Date')['T (degC)'].mean().values\nplt.subplots(figsize=(15, 2))\nplt.plot(temp)\n\nThere is a very strong trend that can be seen every year. Suppose we want to examine only this trend as we are interested in the general dynamics of the system. To highlight that aspect of the time series, we filter out frequencies corresponding to greater than 1 year by setting their energies to 0.\n\ny_ft = scp.fft.fft(temp)\ny_ft_copy = y_ft.copy()\nfreqs = scp.fft.fftfreq(len(temp), d=1/365)\ny_ft_copy[(abs(freqs) >= 1)] = 0\nplt.plot(freqs, abs(y_ft_copy))\n\nBy removing all frequencies greater than 1 year, we obtain only the lower frequency values. With these values, we can have a better look at the yearly dynamics of daily temperature without interference from inter-year dynamics. Should forecasts on actual values of the temperature need to be made, the value sof the frequencies removed can simply be added back.\n\ny_hf = scp.fft.ifft(y_ft_copy)\nplt.subplots(figsize=(15, 2))\n# plt.title('Removing Yearly Cycle')\nplt.plot(range(len(temp)), y_hf.real)\n\n## Wavelet Transform\n\nA wavelet transform (WT) allows you to measure how \"much\"of a certain type of wavelet there exists in a given signal. While both FT and WT both transform a time series into the frequency domain, a key difference is that WT gives you information about the time domain as well.\n\nThis transformation is achieved by imagining a specified wavelet sliding it across the entire signal through time. This wavelet that we scan is called the \"mother wavelet\". In addition to sliding the mother Wavelet across the span of the time series, its size, dependent on a scale factor, is varied as well while scanning. The scaling transformation applied on the mother Wavelet can be thought of as \"stretching\" it only without changing its frequency.\n\nThe wavelet transform of a time series $y(t)$ is given by:\n\n$\\begin{align} WT(y(t)) = \\frac{1}{\\sqrt{|\\sigma|}}\\int_{-\\infty}^{\\infty}y(t)\\psi \\left( \\frac{t-h}{\\sigma} \\right)dt \\end{align}$\n\nwhere $\\sigma$ is the scale, $h$ is the time lag/translation, and $\\psi$ is the mother wavelet. \n\nFrom the WT, we obtaing sets of coefficients corresponding to different time lags and scales. The greater the magnitude of the coefficients, the greater overlap there is between the scaled, time-shifted mother wavelet and the time series.\n\ndef rescale(arr, scale=2):\n    n = len(arr)\n    return np.interp(np.linspace(0, n, scale*n+1), np.arange(n), arr)\n\nfig, ax = plt.subplots(figsize=(15, 2))\nwav1 = pywt.ContinuousWavelet('gaus1')\nint_psi1, x = pywt.integrate_wavelet(wav1)\nfor s in range(5):\n    ax.plot(rescale(int_psi1, scale=s), label='Scale: '+ str(s))\n    ax.legend()\n    ax.set_title('Gaussian Mother Wavelet')\n\nSuppose we have a signal of repearing Gaussian waves. Applying the WT on this signal using a mother wavelet corresponding to that of a Gaussian wavelet, we can pinpoint where the time series exhibits a Gaussian-like pattern.\n\ns1 = list(scp.signal.gaussian(250, std=20))\ns1 = np.tile(s1, 4)\nplt.subplots(figsize=(15, 2))\nplt.xlim(left=0, right=1000)\nplt.ylabel('Value')\nplt.xlabel('Time (t)')\nplt.plot(s1)\nplt.show()\n\ncoeffs, freqs = pywt.cwt(s1, range(1,250), wavelet='gaus1')\nplt.subplots(figsize=(18.75, 2))\nplt.xlim(left=0, right=1000)\nplt.ylabel('Scale (s)')\nplt.xlabel('Time (t)')\nplt.imshow(coeffs, aspect='auto')\nplt.colorbar();\n\nBy observing where the magnitudes of the WT are greatest, we can pinpoint the time and scale wherein there is Gaussian-like behavior in our time series. The WT is also useful in sifting out our signal from noise. We apply white noise once more to our Gaussian pulses and observe the WT's results.\n\ns1 = list(scp.signal.gaussian(250, std=20))\nnoise = np.random.uniform(-1.5,1.5,4*len(s1))\ns1 = np.tile(s1, 4) + noise\nplt.subplots(figsize=(15, 2))\nplt.xlim(left=0, right=1000)\nplt.ylabel('Scale (s)')\nplt.xlabel('Time (t)')\nplt.plot(s1)\nplt.show()\n\ncoeffs, freqs = pywt.cwt(s1, range(1,300), wavelet='gaus1')\nplt.subplots(figsize=(18.75, 2))\nplt.xlim(left=0, right=1000)\nplt.ylabel('Scale (s)')\nplt.xlabel('Time (t)')\nplt.imshow(coeffs, aspect='auto')\nplt.colorbar();\n\nRegions of high magnitudes for our WT coefficients are still clearly visible albeit with minior interference from the white noise at smaller scales. \n\nIn general, choosing the mother wavelet depends on what kind of behavior you want or expect in your time series. Another popular mother wavelet used to identify sine waves in time series is the \"Morlet\" wavelet. This wavelet is a sine wave tapered by a Gaussian wave.\n\nfig, ax = plt.subplots(figsize=(15, 2))\nwav2 = pywt.ContinuousWavelet('morl')\nint_psi2, x = pywt.integrate_wavelet(wav2)\nfor s in range(5):\n    ax.plot(rescale(int_psi2, scale=s), label='Scale: '+ str(s))\n    ax.set_title('Morlet Mother Wavelet')\n    ax.legend()\n\nApplying the Morlet wavelet on a mixed frequency sinusoidal signal, we can find that it is able to differentiate between the two frequencies as $s$ is varied.\n\nsine5 = sine_wave(freq=5, duration =5, plot=False)[1]\nsine10 = sine_wave(freq=10, plot=False)[1]\nsine_5_10 = sine5+sine10\nplt.subplots(figsize=(15, 2))\nplt.plot(sine_5_10)\nplt.show()\nplt.subplots(figsize=(18.75, 2))\nplt.xlim(left=0, right=1000)\nplt.ylabel('Scale (s)')\nplt.xlabel('Time (t)')\nplt.imshow(coeffs, aspect='auto')\nplt.colorbar();\n\n### Example: 4 Using Accelerometer and Gyroscopic Data\n\nThe following code is taken from:\n\nhttps://towardsdatascience.com/multiple-time-series-classification-by-using-continuous-wavelet-transformation-d29df97c0442\n\nThe following data contains time signals of accelerometer and gyroscopic data attached to people performing different activities. Throughout the duration of their activity, measurements were taken from the devices and recorded as time series. Each time series depicts a different activity.\n\ndef load_y_data(y_path):\n    y = np.loadtxt(y_path, dtype=np.int32).reshape(-1, 1)\n    # change labels range from 1-6 t 0-5, this enables a sparse_categorical_crossentropy loss function\n    return y - 1\n\n\ndef load_X_data(X_path):\n    X_signal_paths = [X_path + file for file in os.listdir(X_path)]\n    X_signals = [np.loadtxt(path, dtype=np.float32) for path in X_signal_paths]\n    return np.transpose(np.array(X_signals), (1, 2, 0))\n\n\nPATH = '../data/cwt/'\nLABEL_NAMES = [\"Walking\", \"Walking upstairs\",\n               \"Walking downstairs\", \"Sitting\", \"Standing\", \"Laying\"]\n\n# load X data\nX_train = load_X_data(PATH + 'train/Inertial Signals/')\nX_test = load_X_data(PATH + 'test/Inertial Signals/')\n# load y label\ny_train = load_y_data(PATH + 'train/y_train.txt')\ny_test = load_y_data(PATH + 'test/y_test.txt')\n\nQuite evidently, we find that walking has a different \"look\" from that of simply laying down. Humans can easily determine this at a glance but can be difficult for machines to differentiate between the two signals. The WT allows for the creation of images that contain temporal and frequency information providing a compact and meaningful representation of these time series.\n\nfig, ax = plt.subplots(ncols=2, figsize=(15, 5))\npd.DataFrame(X_train[79]).plot(ax=ax[0], title='Walking')\npd.DataFrame(X_train[51]).plot(ax=ax[1], title='Laying');\n\ndef split_indices_per_label(y):\n    indicies_per_label = [[] for x in range(0, 6)]\n    # loop over the six labels\n    for i in range(6):\n        indicies_per_label[i] = np.where(y == i)[0]\n    return indicies_per_label\n\n\ndef plot_cwt_coeffs_per_label(X, label_indicies, label_names, signal, sample, scales, wavelet):\n\n    fig, axs = plt.subplots(nrows=2, ncols=3, sharex=True,\n                            sharey=True, figsize=(12, 5))\n\n    for ax, indices, name in zip(axs.flat, label_indicies, label_names):\n        coeffs, freqs = pywt.cwt(\n            X[indices[sample], :, signal], scales, wavelet=wavelet)\n        ax.imshow(coeffs, cmap='coolwarm', aspect='auto')\n        ax.set_title(name)\n        ax.spines['right'].set_visible(False)\n        ax.spines['top'].set_visible(False)\n        ax.set_ylabel('Scale')\n        ax.set_xlabel('Time')\n    plt.tight_layout()\n\n\ntrain_labels_indicies = split_indices_per_label(y_train)\n\n# signal indicies: 0 = body acc x, 1 = body acc y, 2 = body acc z, 3 = body gyro x, 4 = body gyro y, 5 = body gyro z, 6 = total acc x, 7 = total acc y, 8 = total acc z\nsignal = 3  # signal index\nsample = 1  # sample index of each label indicies list\nscales = np.arange(1, 65)  # range of scales\nwavelet = 'morl'  # mother wavelet\n\nplot_cwt_coeffs_per_label(X_train, train_labels_indicies, LABEL_NAMES, signal,\n                          sample, scales, wavelet)\n\nfor sample in range(2, 7):\n    plot_cwt_coeffs_per_label(X_train, train_labels_indicies, LABEL_NAMES,\n                              signal, sample, scales, wavelet)\n\nLooking at the plots for each activity, we see can see some patterns between the images. By feeding these results into a convolutional neural network, we can create a classifier to classify time series into activities.\n\n## Summary\n\n\nTo summarize, using these techniques can extract valuable information about time series which are not readily available.\n\nCross-correlations can give insights into the sychronicity of data. With careful analysis, these can even be used as a step towards a more holistic view of causality in conjunction with Granger Causality and Convergent Cross Mapping.\n\nFourier Transformation allows us to view the time series in the frequency domain, allowing operations previously untenable in the time domain. Filtering is a common task where FT is useful as it lets us easily manipulate the data to remove noise or highlight aspects of interest within the time series.\n\n\nWavelet Transformation lets us decompose time series more finely than the FT since we can define the \"mother\" wavelet to be our wavefunction of interest. By characterizing time series, we can quite literally, paint a picture of the time series that can be used to pick out specific waveforms in the time series.\n\nIn the context of forecasting, all three techniques can be used to inform the modeler how to prepare their data. With cross-correlations, the best time lagged time series can be used to provide better information about the target. The Fourier Transform can be applied to denoise the data and remove certain trends. Wavelet Transforms can be used to classify time series allowing the modeler to include their classification as a feature for forecasting or creating separate models for each class of time series. Again, these techniques serve as complements to predictive methods and can be used as feature engineering techniques to improve time series forecasing.\n\nThe following chapter represents the culmination of all the forecasting concepts from previous sections. There is no better way to test your time series capabilities than with a competition. The next chapter discusses the best techniques which were utilized in the recently concluded M5 Competition. In it, the best models under some constraints, are pushed to the limit to perform time series forecasting.\n\n## References\n\nThe contents of this notebook are complied from the following references:\n\n *  Chapters 1-3 of Priestley, M.B. (1981). Spectral Analysis and Time Series, Vols. 1 and 2, Academic Press, New York.\n\n * <a href='https://towardsdatascience.com/multiple-time-series-classification-by-using-continuous-wavelet-transformation-d29df97c0442'>Multiple Time Series Classification by Using Continuous Wavelet Transformation</a>\n \n * <a href='https://pywavelets.readthedocs.io/en/latest/'>PyWavelets Documentation</a>\n \n * <a href='https://www.mathworks.com/help/wavelet/gs/interpreting-continuous-wavelet-coefficients.html'>Interpreting Continuous Wavelet Coefficients</a>\n \n * \nNgui, W. K., Leong, M. S., Hee, L. M., & Abdelrhman, A. M. (2013). Wavelet Analysis: Mother Wavelet Selection Methods. Applied Mechanics and Materials, 393, 953–958. https://doi.org/10.4028/www.scientific.net/amm.393.953", "meta": {"hexsha": "feaf80111825f3fab32df57a06c595af31a348ad", "size": 34320, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/07_CrosscorrelationsFourierTransformandWaveletTransform/07_CrosscorrelationsFourierTransformandWaveletTransform.py", "max_stars_repo_name": "phdinds-aim/time_series_handbook", "max_stars_repo_head_hexsha": "9d22cf901c094035934359e2cbe98183b0cb41e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-02-15T12:27:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T21:50:02.000Z", "max_issues_repo_path": "_build/jupyter_execute/07_CrosscorrelationsFourierTransformandWaveletTransform/07_CrosscorrelationsFourierTransformandWaveletTransform.py", "max_issues_repo_name": "leolorenzoii/time_series_handbook", "max_issues_repo_head_hexsha": "88e5763886043104f916ccd4b13c719f181603c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-08T07:56:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-30T11:34:35.000Z", "max_forks_repo_path": "_build/jupyter_execute/07_CrosscorrelationsFourierTransformandWaveletTransform/07_CrosscorrelationsFourierTransformandWaveletTransform.py", "max_forks_repo_name": "leolorenzoii/time_series_handbook", "max_forks_repo_head_hexsha": "88e5763886043104f916ccd4b13c719f181603c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2021-02-04T16:36:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T14:53:04.000Z", "avg_line_length": 50.8444444444, "max_line_length": 664, "alphanum_fraction": 0.7407342657, "include": true, "reason": "import numpy,import scipy,from statsmodels", "num_tokens": 9054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.9173026499774933, "lm_q1q2_score": 0.8506728085885941}}
{"text": "\n# packages, rich is terminal output formatting\nimport numpy as np\nimport math\nimport rich\nfrom rich import print, pretty\nimport matplotlib.pyplot as plt\npretty.install()\n\n# GMB Model\n# log(x_T) ~ N(log(x_S)+(mu-sigma^2/2)(T-S),sigma^2(T-S))\n\ndef SimulateGBM(S0, r, sd, T, paths, steps, reduce_variance = True):\n    steps = int(steps)\n    dt = T/steps\n    Z = np.random.normal(0, 1, paths//2 * steps).reshape((paths//2, steps))\n    # Z_inv = np.random.normal(0, 1, paths//2 * steps).reshape((paths//2, steps))\n    if reduce_variance:\n      Z_inv = -Z\n    else:\n      Z_inv = np.random.normal(0, 1, paths//2 * steps).reshape((paths//2, steps))\n    dWt = math.sqrt(dt) * Z\n    dWt_inv = math.sqrt(dt) * Z_inv\n    dWt = np.concatenate((dWt, dWt_inv), axis=0)\n    St = np.zeros((paths, steps + 1))\n    St[:, 0] = S0\n    for i in range (1, steps + 1):\n        St[:, i] = St[:, i - 1]*np.exp((r - 1/2*np.power(sd, 2))*dt + sd*dWt[:, i-1])\n    \n    return St[:,1:]\n    #return St\n\n######## Test ##############################\nS0_value = 36\nr_value = 0.06\nsd_value = 0.2\nT_value = 1\npaths_value = 100\nsteps_value = 50\n\nTest_GBM = SimulateGBM(S0=S0_value, r=r_value, sd=sd_value, T=T_value, paths=paths_value,\nsteps=steps_value)\n\n\n########## Plot the Data ################\n\nTime_steps = np.arange(1, steps_value+1)\n\n#plt.plot(Time_steps, Test_GBM.T)\n#plt.show()\n\n######################################################################", "meta": {"hexsha": "aacfe470a939f8c2ebb03b6e5de1e5c18437b4a1", "size": 1424, "ext": "py", "lang": "Python", "max_stars_repo_path": "price_model.py", "max_stars_repo_name": "Peymankor/Tutorial-Derivative-Pricing", "max_stars_repo_head_hexsha": "1e64d1beb1cc16a203412ad1964e6a8e57397cd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "price_model.py", "max_issues_repo_name": "Peymankor/Tutorial-Derivative-Pricing", "max_issues_repo_head_hexsha": "1e64d1beb1cc16a203412ad1964e6a8e57397cd4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "price_model.py", "max_forks_repo_name": "Peymankor/Tutorial-Derivative-Pricing", "max_forks_repo_head_hexsha": "1e64d1beb1cc16a203412ad1964e6a8e57397cd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3846153846, "max_line_length": 89, "alphanum_fraction": 0.5709269663, "include": true, "reason": "import numpy", "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135442, "lm_q2_score": 0.9032942164664239, "lm_q1q2_score": 0.8505907531289355}}
{"text": "from scipy.spatial.distance import pdist, squareform\nfrom scipy import exp\nfrom scipy.linalg import eigh\nimport numpy as np\n\n# Implementing a kernel principal component analysis in Python\n\ndef rbf_kernel_pca1(X, gamma, n_components):\n    \"\"\"\n    RBF kernel PCA implementation.\n\n    Parameters\n    ------------\n    X: {NumPy ndarray}, shape = [n_examples, n_features]\n        \n    gamma: float\n      Tuning parameter of the RBF kernel\n        \n    n_components: int\n      Number of principal components to return\n\n    Returns\n    ------------\n     X_pc: {NumPy ndarray}, shape = [n_examples, k_features]\n       Projected dataset   \n\n    \"\"\"\n    # Calculate pairwise squared Euclidean distances\n    # in the MxN dimensional dataset.\n    sq_dists = pdist(X, 'sqeuclidean')\n\n    # Convert pairwise distances into a square matrix.\n    mat_sq_dists = squareform(sq_dists)\n\n    # Compute the symmetric kernel matrix.\n    K = exp(-gamma * mat_sq_dists)\n\n    # Center the kernel matrix.\n    N = K.shape[0]\n    one_n = np.ones((N, N)) / N\n    K = K - one_n.dot(K) - K.dot(one_n) + one_n.dot(K).dot(one_n)\n\n    # Obtaining eigenpairs from the centered kernel matrix\n    # scipy.linalg.eigh returns them in ascending order\n    eigvals, eigvecs = eigh(K)\n    eigvals, eigvecs = eigvals[::-1], eigvecs[:, ::-1]\n\n    # Collect the top k eigenvectors (projected examples)\n    X_pc = np.column_stack([eigvecs[:, i]\n                            for i in range(n_components)])\n\n    return X_pc\n\ndef rbf_kernel_pca2(X, gamma, n_components):\n    \"\"\"\n    RBF kernel PCA implementation.\n\n    Parameters\n    ------------\n    X: {NumPy ndarray}, shape = [n_examples, n_features]\n        \n    gamma: float\n      Tuning parameter of the RBF kernel\n        \n    n_components: int\n      Number of principal components to return\n\n    Returns\n    ------------\n     alphas: {NumPy ndarray}, shape = [n_examples, k_features]\n       Projected dataset \n     \n     lambdas: list\n       Eigenvalues\n\n    \"\"\"\n    # Calculate pairwise squared Euclidean distances\n    # in the MxN dimensional dataset.\n    sq_dists = pdist(X, 'sqeuclidean')\n\n    # Convert pairwise distances into a square matrix.\n    mat_sq_dists = squareform(sq_dists)\n\n    # Compute the symmetric kernel matrix.\n    K = exp(-gamma * mat_sq_dists)\n\n    # Center the kernel matrix.\n    N = K.shape[0]\n    one_n = np.ones((N, N)) / N\n    K = K - one_n.dot(K) - K.dot(one_n) + one_n.dot(K).dot(one_n)\n\n    # Obtaining eigenpairs from the centered kernel matrix\n    # scipy.linalg.eigh returns them in ascending order\n    eigvals, eigvecs = eigh(K)\n    eigvals, eigvecs = eigvals[::-1], eigvecs[:, ::-1]\n\n    # Collect the top k eigenvectors (projected examples)\n    alphas = np.column_stack([eigvecs[:, i]\n                              for i in range(n_components)])\n\n    # Collect the corresponding eigenvalues\n    lambdas = [eigvals[i] for i in range(n_components)]\n\n    return alphas, lambdas", "meta": {"hexsha": "2756ffa7a182c8f19b2df41ac48bd005d465dcd6", "size": 2919, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter 05/algorithm.py", "max_stars_repo_name": "fagaiera/python-machine-learning-book-3rd-edition-examples", "max_stars_repo_head_hexsha": "16c7eb01fc670a3845847d0e2ac3569c3fd61c35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter 05/algorithm.py", "max_issues_repo_name": "fagaiera/python-machine-learning-book-3rd-edition-examples", "max_issues_repo_head_hexsha": "16c7eb01fc670a3845847d0e2ac3569c3fd61c35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 05/algorithm.py", "max_forks_repo_name": "fagaiera/python-machine-learning-book-3rd-edition-examples", "max_forks_repo_head_hexsha": "16c7eb01fc670a3845847d0e2ac3569c3fd61c35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0673076923, "max_line_length": 65, "alphanum_fraction": 0.636861939, "include": true, "reason": "import numpy,from scipy", "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.903294206053042, "lm_q1q2_score": 0.8505907433231311}}
{"text": "from basic_operations import Basic_Operations\nimport numpy as np\n\n\nclass Operations_One_Matrix(Basic_Operations):\n    \"\"\"This class performs basic operations with a matrix\n    \"\"\"\n\n    def __init__(self, matrix1=None, matrix2=None):\n        super().__init__()\n        self.matrix1 = self.check_type_matrix(matrix1)\n        self.matrix2 = self.check_type_matrix(matrix2)\n\n    def scalar(self, number):\n        \"\"\"scalar : multiply a matrix by a scalar \n\n        Args:\n            number: number to multiply by a matrix\n\n        Return : result of the operation between matrices of type <<numpy.ndarray>>.\n                If an error occurs, it returns a message indicating what the error is.\n        \"\"\"\n        result = self.matrix1 * number\n        return result\n\n    def determinant(self):\n        \"\"\"determinant:  calculates the determinant of a matrix\n        Return : an integer\n        \"\"\"\n        determinat = np.linalg.det(self.matrix1)\n        return determinat\n\n    def shape(self):\n        \"\"\"shape: checks the dimensions of a matrix\n\n        Return: Tuple of array dimensions.\n        \"\"\"\n        dimensions = self.matrix1.shape\n        return dimensions\n\n    def inverse(self):\n        \"\"\"inverse : calculate the inverse of a matrix\n\n        Return : result of the operation between matrices of type <<numpy.ndarray>>.\n                If an error occurs, it returns a message indicating what the error is. \n        \"\"\"\n        try:\n            if self.determinant() != 0 and (self.shape()[0] == self.shape()[1]):\n                inverse = np.linalg.inv(self.matrix1)\n            else:\n                raise Exception\n\n        except Exception as e:\n            return f\"Error: {e}\"\n        return inverse\n\n    def transpose(self):\n        \"\"\"transpose: Invert or permute the axes of a matrix\n        Return: returns the modified array with the matrix transpose\n        \"\"\"\n        try:\n            transpose = np.transpose(self.matrix1)\n            return transpose\n\n        except Exception as e:\n            return f\"Error: {e}\"\n", "meta": {"hexsha": "643bc4cc163dc1f32c0c1f06db7841660eab995e", "size": 2044, "ext": "py", "lang": "Python", "max_stars_repo_path": "package_pypi/basic_algebra_ml/algebra/matrix_manipulations.py", "max_stars_repo_name": "cbarros7/ml_engineer_nanodegree", "max_stars_repo_head_hexsha": "004bcd6389cff6aa6e23c97e15ab0e661679b7a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-29T22:56:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T22:56:22.000Z", "max_issues_repo_path": "package_pypi/basic_algebra_ml/algebra/matrix_manipulations.py", "max_issues_repo_name": "cbarros7/ml_engineer_nanodegree", "max_issues_repo_head_hexsha": "004bcd6389cff6aa6e23c97e15ab0e661679b7a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "package_pypi/basic_algebra_ml/algebra/matrix_manipulations.py", "max_forks_repo_name": "cbarros7/ml_engineer_nanodegree", "max_forks_repo_head_hexsha": "004bcd6389cff6aa6e23c97e15ab0e661679b7a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5074626866, "max_line_length": 87, "alphanum_fraction": 0.6017612524, "include": true, "reason": "import numpy", "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242009478238, "lm_q2_score": 0.8774767954920548, "lm_q1q2_score": 0.850559493640593}}
{"text": "\"\"\"\nThis file contains the implementation of the Newton-Cotes rules\n\"\"\"\n\nimport numpy as np\n\ndef rectangle(x, f):\n    \"\"\" \n    Compute a 1D definite integral using the rectangle (midpoint) rule\n    Parameters\n    ----------\n    f : function\n        User defined function.\n    x : numpy array\n        Integration domain.\n    Returns\n    -------\n    I : float\n        Integration result.\n    \"\"\"\n    a = x[0]\n    b = x[1]\n    ya = f((a+b)/2)\n    I = (b-a) * ya\n    return I\n\ndef trapz(x, f):\n    \"\"\" \n    Compute a 1D definite integral using the trapezoidal rule\n    Parameters\n    ----------\n    f : function\n        User defined function.\n    x : numpy array\n        Integration domain.\n    Returns\n    -------\n    I : float\n        Integration result.\n    \"\"\"   \n    a = x[0]\n    b = x[1]\n    ya = f(a)\n    yb = f(b)\n    I = (b-a) * (ya + yb) / 2\n    return I\n\ndef simpson(x, f):\n    \"\"\" \n    Compute a 1D definite integral using Simpson's rule.\n    Parameters\n    ----------\n    f : function\n        User defined function.\n    x : numpy array\n        Integration domain.\n    Returns\n    -------\n    I : float\n        Integration result.\n    \"\"\"   \n    a = x[0]\n    b = x[1]\n    ya = f(a)\n    yb = f((a+b)/2)\n    yc = f(b)\n    I = (b-a) * (ya + 4 * yb + yc) / 6\n    return I\n\ndef simpson3_8(x, f):\n    \"\"\" \n    Compute a 1D definite integral using the 3/8 Simpson's rule.\n    Parameters\n    ----------\n    f : function\n        User defined function.\n    x : numpy array\n        Integration domain.\n    Returns\n    -------\n    I : float\n        Integration result.\n    \"\"\"   \n    a = x[0]\n    b = x[1]\n    ya = f(a)\n    yb = f((2*a+  b)/3)\n    yc = f((  a+2*b)/3)\n    yd = f(b)\n    I = (b-a) * (ya + 3 * (yb + yc) + yd) / 8\n    return I\n\ndef boole(x, f):\n    \"\"\" \n    Compute a 1D definite integral using Boole's rule.\n    Parameters\n    ----------\n    f : function\n        User defined function.\n    x : numpy array\n        Integration domain.\n    Returns\n    -------\n    I : float\n        Integration result.\n    \"\"\"   \n    a = x[0]\n    b = x[1]\n    ya = f(a)\n    yb = f((3*a+  b)/4)\n    yc = f((  a+  b)/2)\n    yd = f((  a+3*b)/4)\n    ye = f(b)\n    I = (b-a) * (7 * (ya + ye) + 32 * (yb + yd) + 12 * yc) * 2 / 45\n    return I\n\n", "meta": {"hexsha": "e5caa6f0d1ea510b2640db504779ee5d978fd38f", "size": 2230, "ext": "py", "lang": "Python", "max_stars_repo_path": "fomms_integrate/newton_cotes.py", "max_stars_repo_name": "mquevill/fomms_integrate", "max_stars_repo_head_hexsha": "63f8eb35e092cd219a31ae0b5fcc3cd0c747cf67", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fomms_integrate/newton_cotes.py", "max_issues_repo_name": "mquevill/fomms_integrate", "max_issues_repo_head_hexsha": "63f8eb35e092cd219a31ae0b5fcc3cd0c747cf67", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fomms_integrate/newton_cotes.py", "max_forks_repo_name": "mquevill/fomms_integrate", "max_forks_repo_head_hexsha": "63f8eb35e092cd219a31ae0b5fcc3cd0c747cf67", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0598290598, "max_line_length": 70, "alphanum_fraction": 0.4695067265, "include": true, "reason": "import numpy", "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242000616579, "lm_q2_score": 0.8774767954920547, "lm_q1q2_score": 0.8505594928630029}}
{"text": "import numpy as np\nfrom copy import deepcopy\n\nclass PermutationHandler():\n    def __init__(self, n, k=None, random_seed=0): #n choose k\n        if k is None: k = n\n        self.n = n\n        self.k = k\n        self.n_perms = np.math.factorial(n)//np.math.factorial(n-k)\n        self.random_seed = random_seed\n        self.rng = np.random.RandomState(seed=random_seed)\n\n    def generate_random_permutation(self):\n        n, k = self.n, self.k\n        item = []\n        a = list(range(n))\n        for i in range(k):\n            entry_idx = self.rng.randint(n-i)\n            item.append(a[entry_idx])\n            del a[entry_idx]\n        return tuple(item)\n\n    def get_generator(self, count=None):\n        if count is None:\n            for idx in range(self.n_perms):\n                yield self.index_to_permutation(idx)\n        else:\n            for idx in range(count):\n                yield self.generate_random_permutation()\n\n    def index_to_permutation(self, idx):\n        assert idx < self.n_perms, \"Index must be less than {}\".format(self.n_perms)\n        n_perms = self.n_perms\n        n, k = self.n, self.k\n        a = list(range(n))\n        item = []\n        for i in range(k):\n            stride = n_perms // (n-i)\n            entry_index = int(idx // stride)\n            idx = idx - entry_index * stride\n            item.append(a[entry_index])\n            del a[entry_index]\n            n_perms = n_perms//(n-i)\n        return tuple(item)\n\n    def permutation_to_index(self, item):\n        n_perms = self.n_perms\n        n, k = self.n, self.k\n        a = list(range(n))\n        idx = 0\n        for i in range(len(item)):\n            idx = idx + n_perms//(n-i) * a.index(item[i])\n            a.remove(item[i])\n            n_perms = n_perms//(n-i)\n        return int(idx)\n\n    def mutate(self, item, pos=None):\n        item = list(item)\n        n, k = self.n, self.k\n        if pos is None: pos = self.rng.randint(k)\n        perturbation = self.rng.randint(n-1) + 1\n        existing_val = item[pos]\n        new_val = (existing_val + perturbation) % n\n        try:\n            new_val_idx = item.index(new_val)\n        except:\n            new_val_idx = None\n        if new_val_idx is not None:\n            item[new_val_idx] = existing_val\n        item[pos] = new_val\n        return tuple(item)\n   \n    def crossover(self, item1, item2):\n        item1, item2 = list(item1), list(item2)\n        n, k = self.n, self.k\n        pos = 1 + self.rng.randint(k-1)\n        citem1 = item1[:pos] + [entry for entry in item2 if entry not in item1[:pos]][-k+pos:]\n        citem2 = item2[:pos] + [entry for entry in item1 if entry not in item2[:pos]][-k+pos:]\n        citem3 = [entry for entry in item2 if entry not in item1[pos:]][:pos] + item1[pos:]\n        citem4 = [entry for entry in item1 if entry not in item2[pos:]][:pos] + item2[pos:]\n        return tuple(citem1), tuple(citem2), tuple(citem3), tuple(citem4)\n", "meta": {"hexsha": "8486f0eddade64902c68364bb817fd2637ba1e8e", "size": 2911, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/misc_utils.py", "max_stars_repo_name": "SawanKumar28/pero", "max_stars_repo_head_hexsha": "63a0dbcacebadf8f2ff5fb457235decb34a5de06", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-07-19T15:16:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T10:19:07.000Z", "max_issues_repo_path": "src/misc_utils.py", "max_issues_repo_name": "SawanKumar28/pero", "max_issues_repo_head_hexsha": "63a0dbcacebadf8f2ff5fb457235decb34a5de06", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/misc_utils.py", "max_forks_repo_name": "SawanKumar28/pero", "max_forks_repo_head_hexsha": "63a0dbcacebadf8f2ff5fb457235decb34a5de06", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5, "max_line_length": 94, "alphanum_fraction": 0.556853315, "include": true, "reason": "import numpy", "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241956308278, "lm_q2_score": 0.877476793890012, "lm_q1q2_score": 0.8505594874221536}}
{"text": "# Multivariate Linear Regression\n# Includes data normalization\n\nimport numpy as np\nfrom sklearn import datasets, linear_model\n\ndef partial_derivative(theta, trainX, trainY, trainSize):\n    return trainX.T.dot((trainX.dot(theta) - trainY)) / trainSize\n\ndef normalize(data):\n    mean = np.mean(data, axis=0)\n    stdDeviation = np.std(data, axis=0)\n    return (data - mean) / stdDeviation\n\ndef fit(trainX, trainY, learningRate=0.1, threashold=1E-5):\n    trainSize, featureSize = trainX.shape\n    theta = np.array(np.ones((featureSize, 1)), dtype=float) # Initialize theta\n    derivative = partial_derivative(theta, trainX, trainY, trainSize)\n    while abs(derivative).max() > threashold: # While gradient doesn't converge\n        theta -= learningRate * derivative # Perform gradient descent\n        derivative = partial_derivative(theta, trainX, trainY, trainSize) # Update partial derivative\n    return theta\n\ndef standard_fit(trainX, trainY):\n    trainX = trainX[:, 1:] # Remove the extra bias term\n    model = linear_model.LinearRegression()\n    model.fit(trainX, trainY)\n    return np.append(model.intercept_, model.coef_)[np.newaxis].T # Returns the hypothesis in a column vector\n\ndef accuracy(theta, testX, testY):\n    # Returns the R Squared value of the model\n    explained = testX.dot(theta)\n    mean = np.sum(testY) / len(testY)\n    totSumSquares = np.sum((testY - mean) ** 2)\n    resSumSquares = np.sum((testY - explained) ** 2)\n    accuracy = 1 - resSumSquares / totSumSquares\n    return accuracy\n\ndataset = datasets.load_diabetes()\ndata, target = dataset.data, dataset.target\ndataSize = data.shape[0] # Number of rows (entries)\ndata = normalize(data) # Normalize the data\ndata = np.hstack((np.ones((dataSize, 1)), data)) # Add an extra bias term\ntarget = target[np.newaxis].T # Transpose target vector into column vector\nseparation = int(dataSize * 0.8) # Percentage of training data set and testing data set\ntrainX, trainY = data[:separation, :], target[:separation]\ntestX, testY = data[separation:, :], target[separation:]\n\nhypothesis = standard_fit(trainX, trainY)\nprint('Standard Fitted Model: {}'.format(hypothesis.T))\nacc = accuracy(hypothesis, testX, testY)\nprint('Standard Fitted Accuracy: {:.4f}\\n'.format(acc))\n\nhypothesis = fit(trainX, trainY, 0.1, 1E-6)\nprint('Fitted Model: {}'.format(hypothesis.T))\nacc = accuracy(hypothesis, testX, testY)\nprint('Fitted Accuracy: {:.4f}'.format(acc))\n", "meta": {"hexsha": "2378cdf5063db01e24b6ec21ab958b773f46c2a7", "size": 2410, "ext": "py", "lang": "Python", "max_stars_repo_path": "implementations/lin_reg.py", "max_stars_repo_name": "yu-george/ml", "max_stars_repo_head_hexsha": "8eedc62df9e7f37312bba39fa45bb9e9c6361028", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "implementations/lin_reg.py", "max_issues_repo_name": "yu-george/ml", "max_issues_repo_head_hexsha": "8eedc62df9e7f37312bba39fa45bb9e9c6361028", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "implementations/lin_reg.py", "max_forks_repo_name": "yu-george/ml", "max_forks_repo_head_hexsha": "8eedc62df9e7f37312bba39fa45bb9e9c6361028", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5517241379, "max_line_length": 109, "alphanum_fraction": 0.7195020747, "include": true, "reason": "import numpy", "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241974031599, "lm_q2_score": 0.8774767810736693, "lm_q1q2_score": 0.8505594765541428}}
{"text": "'''\n    Problem 69 : Totient maximum\n'''\nfrom time import time\nfrom numba import jit\nimport numpy as np\n\n\n@jit\ndef getPrimes(n):\n    q, r = divmod(n, 2)\n    r = q + r\n    seive = np.ones(r)\n    seive[0] = 0\n\n    lim = int(n**0.5 / 2) + 1\n\n    for i in range(1, lim + 1):\n        p = 2 * i + 1\n        if seive[i]:\n            sp = 2 * i * (i + 1)\n            while (sp < r):\n                seive[sp] = 0\n                sp = sp + p\n\n    def_prime = np.asarray([2])\n    seived_primes = np.asarray(np.nonzero(seive)).flatten() * 2 + 1\n    primes = np.concatenate((def_prime, seived_primes))\n    return primes\n\n\n@jit\ndef get_phi(n):\n    if n in primes_list:\n        return n - 1\n\n    res = n\n    for p in primes_list:\n        r = n % p\n        if r == 0:\n            while r == 0:\n                n = n // p\n                r = n % p\n\n            res = res // p\n            res = res * (p - 1)\n        elif p * p > n:\n            break\n\n    if n > 1:\n        res = res // n\n        res = res * (n - 1)\n\n    return res\n\n\nif __name__ == \"__main__\":\n    t0 = time()\n    N = 1000000\n    primes_list = getPrimes(int(N**0.5))\n    print(\"Primes computed in {:.3f} secs\".format(time() - t0))\n    a, r = 0, 0\n    for i in range(2, N + 1):\n        phi = get_phi(i)\n        # print(i,\" \", phi)\n        r1 = i / phi\n        if r1 > r:\n            a, r = i, r1\n\n    print(\"Result : \", a, \" , ratio :\", r)\n    print(\"Done in {:.3f} secs\".format(time() - t0))\n", "meta": {"hexsha": "8deea092c201ef883178141316cbc0ffe15b4261", "size": 1443, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/051-100/P069.py", "max_stars_repo_name": "lord483/Project-Euler-Solutions", "max_stars_repo_head_hexsha": "ba9e9451460d631774dfa75d61cedc1918a462c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/051-100/P069.py", "max_issues_repo_name": "lord483/Project-Euler-Solutions", "max_issues_repo_head_hexsha": "ba9e9451460d631774dfa75d61cedc1918a462c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/051-100/P069.py", "max_forks_repo_name": "lord483/Project-Euler-Solutions", "max_forks_repo_head_hexsha": "ba9e9451460d631774dfa75d61cedc1918a462c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0416666667, "max_line_length": 67, "alphanum_fraction": 0.4414414414, "include": true, "reason": "import numpy,from numba", "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969324199175492, "lm_q2_score": 0.8774767778695834, "lm_q1q2_score": 0.850559475003525}}
{"text": "\"\"\"\nThe purpose of this module is to perform a single Euler step on a step\nfunction with the WENO method.\n\nThe initial conditions are\n\n    q(t=0, x) = 1_{ x > 0 }\n\nThat is, q = 1 if x > 0, and q = 0 otherwise.\n\nRequired Modules:\n-----------------\n\n    * sympy - symbolic toolbox for Python.\n\"\"\"\n\nfrom weno_diff import central_diff1, central_diff2, ConstructIntegratedF, LinearReconstruct\n\nimport sympy\n\n# Quick accessors\n\ndx = sympy.Symbol(\"dx\", real=True )    # spatial resolution\ndt = sympy.Symbol(\"dt\", real=True )    # time step\nnu = sympy.Symbol(\"nu\", real=True )    # CFL number\nu  = sympy.Symbol(\"u\" , real=True )    # advection speed\n\ndt = nu*dx/u\n\nqim5 = 0\nqim4 = 0\nqim3 = 0\nqim2 = 0\nqim1 = 0\nqi   = 1\nqip1 = 1\nqip2 = 1\nqip3 = 1\nqip4 = 1\n\n# Expansion of f:\n#\n#    F \\approx f_i - (u*dt)/2 u_{i,x} + (u*dt)^2/3 u_{i,xx}\n#\nFim3 = sympy.simplify( ConstructIntegratedF( [ qim5, qim4, qim3, qim2, qim1 ], u, dx, dt ) )\nFim2 = sympy.simplify( ConstructIntegratedF( [ qim4, qim3, qim2, qim1, qi   ], u, dx, dt ) )\nFim1 = sympy.simplify( ConstructIntegratedF( [ qim3, qim2, qim1, qi  , qip1 ], u, dx, dt ) )\nFi   = sympy.simplify( ConstructIntegratedF( [ qim2, qim1, qi  , qip1, qip2 ], u, dx, dt ) )\nFip1 = sympy.simplify( ConstructIntegratedF( [ qim1, qi  , qip1, qip2, qip3 ], u, dx, dt ) )\nFip2 = sympy.simplify( ConstructIntegratedF( [ qi  , qip1, qip2, qip3, qip4 ], u, dx, dt ) )\n\nFimh = sympy.simplify( LinearReconstruct( [Fim3, Fim2, Fim1, Fi, Fip1] ) )\nFiph = sympy.simplify( LinearReconstruct( [Fim2, Fim1, Fi, Fip1, Fip2] ) )\n\n# Update is q_i^{n+1} = q_i^n - dt ( Fiph - Fim2 ) / dx\nstability_polynomial = sympy.collect( sympy.expand(1 - dt*(Fiph - Fimh)/dx), nu )\n\nprint('Stability polynomial for Taylor PIF-WENO is ')\nsympy.pretty_print( stability_polynomial )\nprint('Stability polynomial for Taylor PIF-WENO is ')\nprint( stability_polynomial )\n\n# Try this with a simpler scheme that has a known solution:\n#forward_euler = sympy.collect( 1 - (u*dt)*( qi - qim1 ) / dx, exp(-I*k*dx) )\n#print('Stability polynomial for Forward Euler is ')\n#sympy.pretty_print( forward_euler )\n\n", "meta": {"hexsha": "20daf31dec849db61c20b0099e55c5e33482c1c5", "size": 2090, "ext": "py", "lang": "Python", "max_stars_repo_path": "symbolic_tools/euler_step.py", "max_stars_repo_name": "dcseal/finess", "max_stars_repo_head_hexsha": "766e583ae9e84480640c7c3b3c157bf40ab87fe4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "symbolic_tools/euler_step.py", "max_issues_repo_name": "dcseal/finess", "max_issues_repo_head_hexsha": "766e583ae9e84480640c7c3b3c157bf40ab87fe4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "symbolic_tools/euler_step.py", "max_forks_repo_name": "dcseal/finess", "max_forks_repo_head_hexsha": "766e583ae9e84480640c7c3b3c157bf40ab87fe4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7352941176, "max_line_length": 92, "alphanum_fraction": 0.6602870813, "include": true, "reason": "import sympy", "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298657, "lm_q2_score": 0.8840392924390585, "lm_q1q2_score": 0.8505409012941237}}
{"text": "import numpy as np\n#import time\n\nA = np.matrix('1 2 -2 1; 2 5 -2 3; -2 -2 5 3; 1 3 3 2')\nb = np.matrix('4; 7; -1; 0')\n\ndef lu_decomposition(A):\n    # if A.shape[0]!=A.shape[1]: implement exception\n\n    dimension = A.shape[0]\n\n    L = np.zeros(shape=(dimension,dimension))\n    U = np.zeros(shape=(dimension,dimension))\n\n    for i in range(dimension):\n        L[i,i] = 1.0\n\n    for i in range(dimension):\n        for j in range(dimension):\n            sum = 0.0\n\n            if j >= i:\n                for k in range(i+1):\n                    sum += L[i,k] * U[k,j]\n\n                U[i,j] = A[i,j] - sum\n            else:\n                for k in range(j+1):\n                    sum += L[i,k] * U[k,j]\n\n                L[i,j] = (A[i,j] - sum)/U[j,j]\n\n    return L,U\n\ndef solveReverse(L, b):\n    dimension = L.shape[0]\n\n    y = np.zeros(shape = (dimension,1))\n\n    for i in range(dimension):\n        sum = 0\n\n        for j in range(dimension):\n            if j<i:\n                sum += L[i][j]*y[j]\n\n        y[i] = b[i] - sum\n\n    return y\n\ndef solveNormal(U,y):\n    dimension = U.shape[0]\n\n    x = np.zeros(shape = (dimension,1))\n\n    for i in range(dimension-1,-1,-1): #range([start], stop[, step])\n        sum = 0\n\n        for j in range(0,dimension):\n            if not(j == i):\n                sum += U[i][j] * x[j]\n\n        x[i] = (y[i] - sum)/ U[i][i]\n\n    return x\n\n#a=time.clock()\n\nl,u = lu_decomposition(A)\ny = solveReverse(l,b)\nx = solveNormal(u,y)\n\n#b = time.clock()\n\nprint \"matriz L \\n\",l\nprint \"matriz U \\n\",u\nprint \"L * U \\n\",np.dot(l,u)\nprint \"\\nvetor y \\n\",y\nprint \"\\nvetor x \\n\",x\n\n#print 'delta', b-a\n", "meta": {"hexsha": "074c5b68de6ad7a31f257749b7deaae0385ce9de", "size": 1619, "ext": "py", "lang": "Python", "max_stars_repo_path": "Trabalho 4 (Pedro)/LU.py", "max_stars_repo_name": "danielbibit/CalculoNumerico-UFG", "max_stars_repo_head_hexsha": "9ab030ba75353ca39d1f72090f1a65d7516ffa8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Trabalho 4 (Pedro)/LU.py", "max_issues_repo_name": "danielbibit/CalculoNumerico-UFG", "max_issues_repo_head_hexsha": "9ab030ba75353ca39d1f72090f1a65d7516ffa8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Trabalho 4 (Pedro)/LU.py", "max_forks_repo_name": "danielbibit/CalculoNumerico-UFG", "max_forks_repo_head_hexsha": "9ab030ba75353ca39d1f72090f1a65d7516ffa8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.743902439, "max_line_length": 68, "alphanum_fraction": 0.4793082149, "include": true, "reason": "import numpy", "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075711974104, "lm_q2_score": 0.8840392909114836, "lm_q1q2_score": 0.8505408950219284}}
{"text": "import random \r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nrandom.seed(2)\r\nf = lambda x: x**2\r\na = 0.0\r\n\r\nb = 3.0\r\nNumSteps = 1000000 \r\nXIntegral=[]  \r\nYIntegral=[]\r\nXRectangle=[]  \r\nYRectangle=[]\r\n\r\nymin = f(a)\r\nymax = ymin\r\nfor i in range(NumSteps):\r\n    x = a + (b - a) * float(i) / NumSteps\r\n    y = f(x)\r\n    if y < ymin: ymin = y\r\n    if y > ymax: ymax = y\r\n\r\nA = (b - a) * (ymax - ymin)\r\nN = 1000000 \r\nM = 0\r\nfor k in range(N):\r\n    x = a + (b - a) * random.random()\r\n    y = ymin + (ymax - ymin) * random.random()\r\n    if y <= f(x):\r\n            M += 1 \r\n            XIntegral.append(x)\r\n            YIntegral.append(y)  \r\n    else:\r\n            XRectangle.append(x) \r\n            YRectangle.append(y)              \r\nNumericalIntegral = M / N * A\r\nprint (\"Numerical integration = \" + str(NumericalIntegral))\r\n\r\nXLin=np.linspace(a,b)\r\nYLin=[]\r\nfor x in XLin:\r\n    YLin.append(f(x))\r\n\r\nplt.axis   ([0, b, 0, f(b)])                                            \r\nplt.plot   (XLin,YLin, color=\"red\" , linewidth=\"4\") \r\nplt.scatter(XIntegral, YIntegral, color=\"blue\", marker   =\".\") \r\nplt.scatter(XRectangle, YRectangle, color=\"yellow\", marker   =\".\")\r\nplt.title  (\"Numerical Integration using Monte Carlo method\")\r\nplt.show()\r\n", "meta": {"hexsha": "f0e11f4d05e9c4b43d8dfdaf5fa11d44e78e8db8", "size": 1240, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter04/NumericalIntegration.py", "max_stars_repo_name": "CiaburroGiuseppe/Hands-On-Simulation-Modeling-with-Python", "max_stars_repo_head_hexsha": "c1cbf02840bb9e634e8f93e653cd8fdabcbcff01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2020-07-29T08:52:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T04:04:56.000Z", "max_issues_repo_path": "Chapter04/NumericalIntegration.py", "max_issues_repo_name": "CiaburroGiuseppe/Hands-On-Simulation-Modeling-with-Python", "max_issues_repo_head_hexsha": "c1cbf02840bb9e634e8f93e653cd8fdabcbcff01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter04/NumericalIntegration.py", "max_forks_repo_name": "CiaburroGiuseppe/Hands-On-Simulation-Modeling-with-Python", "max_forks_repo_head_hexsha": "c1cbf02840bb9e634e8f93e653cd8fdabcbcff01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2020-08-18T16:27:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T03:31:54.000Z", "avg_line_length": 24.3137254902, "max_line_length": 73, "alphanum_fraction": 0.5330645161, "include": true, "reason": "import numpy", "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075777163567, "lm_q2_score": 0.8840392741081574, "lm_q1q2_score": 0.8505408846183257}}
{"text": "# Implementation of cross-entropy error function using numpy.\n# Compare the random weight results with the closed form solution (0,4,4).\n\n# Code Flow:\n    # 1. Import all relevant libraries.\n    # 2. Generate sample data from std. normal distribution.\n    # 3. Create random weights for plotting.\n    # 4. Define sigmoid function.\n    # 5. Feedforward calculation.\n    # 6. Cross-entropy error function.\n    # 7. Print cross-entropy error from random weights.\n    # 8. Closed-form solution.\n    # 9. Print cross-entropy error from closed form solution.\n    \n# 1. Import all relevante libraries:\nimport numpy as np\n\n# 2. Create input data:\nN = 100 # No. of samples\nD = 2 # No. of features\n\n# Random data generation:\nX = np.random.randn(N,D)\n\n# Center the first 50 points at (-2,-2)\nX[:50,:] = X[:50,:] - 2*np.ones((50,D))\n\n# Center the last 50 points at (2, 2)\nX[50:,:] = X[50:,:] + 2*np.ones((50,D))\n\n# Labels: first 50 are 0, last 50 are 1\nT = np.array([0]*50 + [1]*50) # Random labels\n\n# Bias term: Add a column of ones\nones = np.ones((N, 1))\nXb = np.concatenate((ones, X), axis=1)\n\n# 3. Create random weights:\nw = np.random.randn(D + 1)\n\n# 4. Sigmoid function\ndef sigmoid(z):\n    return 1/(1 + np.exp(-z))\n\n# 5. Feedforward:\nz = Xb.dot(w)\nY = sigmoid(z)\n\n# 6. Cross-entropy error function:\n# Section 3B from jupyter notebook\ndef cross_entropy(T, Y):\n    E = 0\n    for i in range(len(T)):\n        if T[i] == 1:\n            E -= np.log(Y[i])\n        else:\n            E -= np.log(1 - Y[i])\n    return E\n\n# 7. Print cross-entropy error from random weights:\nprint(cross_entropy(T, Y))\n\n# 8. Closed-form solution:\n# Section 3A from jupyter notebook\nw = np.array([0, 4, 4])\n\n# calculate the model output\nz = Xb.dot(w)\nY = sigmoid(z)\n\n# 9. Print cross-entropy error from closed form solution:\nprint(cross_entropy(T, Y))\nprint('As we expect the error is much lower with our closed form solution!')\n", "meta": {"hexsha": "774239c6516b4c2d5b64909476c28095d5674fe1", "size": 1893, "ext": "py", "lang": "Python", "max_stars_repo_path": "2.Logistic Regression/1.Code - Using Theory/1.Cross_Entropy_Function.py", "max_stars_repo_name": "ananth-repos/machine-learning", "max_stars_repo_head_hexsha": "a510dcf81fab9137c33f568e73d65262667b3973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2.Logistic Regression/1.Code - Using Theory/1.Cross_Entropy_Function.py", "max_issues_repo_name": "ananth-repos/machine-learning", "max_issues_repo_head_hexsha": "a510dcf81fab9137c33f568e73d65262667b3973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2.Logistic Regression/1.Code - Using Theory/1.Cross_Entropy_Function.py", "max_forks_repo_name": "ananth-repos/machine-learning", "max_forks_repo_head_hexsha": "a510dcf81fab9137c33f568e73d65262667b3973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5810810811, "max_line_length": 76, "alphanum_fraction": 0.6455361859, "include": true, "reason": "import numpy", "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075755433747, "lm_q2_score": 0.8840392756357327, "lm_q1q2_score": 0.8505408841670159}}
{"text": "import torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import DataLoader,random_split,Subset\nfrom sklearn.model_selection import LeaveOneOut,KFold\nfrom pathlib import Path\nfrom dataset import data_generator,RegressionDataset\nfrom opt import parse_args\n\n\nopt=parse_args()\n\n\n# Using RMSE loss as loss function\ndef RMSE_loss(yhat,y):\n    mse=((yhat - y) ** 2).sum() / yhat.data.nelement()\n    return torch.sqrt(mse)\n\n\n# Perform Linear Regression AX=b\ndef linear_regression(x,weight):\n    outputs=[]\n    for i in x:\n        out=i.view([1,len(i)]).mm(weight)\n        outputs.append(out.numpy()) \n    return outputs\n\n\n# Get the best weight using QR Decomposition\n\"\"\"def get_best_weight(x,y,_lambda=0):\n    Q,R=torch.qr(x)\n    pseudo_inv=R.pinverse(_lambda).mm(Q.t())\n    weight=torch.mm(pseudo_inv,y)\n    return weight\"\"\"\n\n\n# Get the best weight by the formulat mention in the course\ndef get_best_weight(x,y,_lambda=0):\n    x_t=x.t()\n\n    if _lambda==0:\n        pseudo_inv=torch.inverse(x_t.mm(x))\n    else:   # if regularization is needed\n        mat=x_t.mm(x)\n        I=torch.eye(mat.size(0))\n        pseudo_inv=torch.inverse(mat+_lambda*I)\n\n    weight=torch.mm(pseudo_inv.mm(x_t),y)\n    return weight\n\n\n# get polynomial features when polynomial regression with degree>1\ndef get_poly_features(x,degree):\n    poly_x=[]\n    for each_x in x:\n        poly_term=[each_x**n for n in range(1,degree+1)]\n        poly_x.append(poly_term)\n    return poly_x\n\n\n# draw the fitting plot\ndef draw_fitting_plot(train_set,range,w_1,deg_1,legend,title,fname,w_2=None,deg_2=None,w_3=None,deg_3=None,w_4=None,deg_4=None):\n    train_X=[]\n    train_Y=[]\n\n    for i,(inputs,labels) in enumerate(train_set):\n        train_X.append(inputs)\n        train_Y.append(labels)\n    \n    train_X=np.asarray(train_X)\n    train_Y=np.asarray(train_Y)\n    plt.scatter(train_X,train_Y,facecolors='none',edgecolors='b')\n\n    X=np.linspace(range[0],range[1],100)\n    \n    deg_1_X=get_poly_features(X,deg_1)\n    deg_1_X=np.hstack((deg_1_X,np.ones((len(deg_1_X),1))))\n    deg_1_X=torch.FloatTensor(deg_1_X)\n    w_1=torch.FloatTensor(w_1)\n    deg_1_Y=linear_regression(deg_1_X,w_1)\n    deg_1_Y=torch.FloatTensor(deg_1_Y)\n    deg_1_Y=torch.flatten(deg_1_Y)\n    plt.plot(X,deg_1_Y,'r',linewidth=0.5)\n\n    if w_2 is not None:\n        deg_2_X=get_poly_features(X,deg_2)\n        deg_2_X=np.hstack((deg_2_X,np.ones((len(deg_2_X),1))))\n        deg_2_X=torch.FloatTensor(deg_2_X)\n        w_2=torch.FloatTensor(w_2)\n        deg_2_Y=linear_regression(deg_2_X,w_2)\n        deg_2_Y=torch.FloatTensor(deg_2_Y)\n        deg_2_Y=torch.flatten(deg_2_Y)\n        plt.plot(X,deg_2_Y,'g',linewidth=0.5)\n\n    if w_3 is not None:\n        deg_3_X=get_poly_features(X,deg_3)\n        deg_3_X=np.hstack((deg_3_X,np.ones((len(deg_3_X),1))))\n        deg_3_X=torch.FloatTensor(deg_3_X)\n        w_3=torch.FloatTensor(w_3)\n        deg_3_Y=linear_regression(deg_3_X,w_3)\n        deg_3_Y=torch.FloatTensor(deg_3_Y)\n        deg_3_Y=torch.flatten(deg_3_Y)\n        plt.plot(X,deg_3_Y,'deepskyblue',linewidth=0.5)\n    \n    if w_4 is not None:\n        deg_4_X=get_poly_features(X,deg_4)\n        deg_4_X=np.hstack((deg_4_X,np.ones((len(deg_4_X),1))))\n        deg_4_X=torch.FloatTensor(deg_4_X)\n        w_4=torch.FloatTensor(w_4)\n        deg_4_Y=linear_regression(deg_4_X,w_4)\n        deg_4_Y=torch.FloatTensor(deg_4_Y)\n        deg_4_Y=torch.flatten(deg_4_Y)\n        plt.plot(X,deg_4_Y,'darkviolet',linewidth=0.5)\n    \n    plt.legend(legend,fontsize=16)\n    plt.xlabel('x',fontsize=14)\n    plt.ylabel('y',fontsize=14)\n    plt.title(title,fontsize=14)\n    plt.savefig(fname)\n    plt.clf()\n    \n\n# Testing\ndef test(test_set,degree,weight):\n    test_X=[]\n    test_Y=[]\n\n    for i,(inputs,labels) in enumerate(test_set):\n        test_X.append(inputs)\n        test_Y.append(labels)\n\n    test_X=get_poly_features(test_X,degree)\n    test_X=np.hstack((test_X,np.ones((len(test_X),1))))\n    test_X=torch.FloatTensor(test_X)\n    test_Y=torch.FloatTensor(test_Y)\n    test_Y=test_Y.view([test_Y.size(0),1])\n\n    weight=torch.FloatTensor(weight)\n\n    outputs=linear_regression(test_X,weight)\n    outputs=torch.FloatTensor(outputs)\n    outputs=outputs.view([outputs.size(0),1])\n\n    loss=RMSE_loss(outputs,test_Y)\n    avg_test_loss=loss/test_X.size(0)\n\n    print(f'testing_loss: {avg_test_loss:.4f}\\n')\n\n\n# Training when the cross validation is five folds\ndef kf_train(dataset,degree=1,_lambda=0):\n    kf=KFold(n_splits=5,random_state=None,shuffle=False)\n\n    total_training_loss=0.0\n    total_valid_loss=0.0\n    total_weight=np.empty((degree+1,1))\n\n    for train_idx,valid_idx in kf.split(dataset):   # Split the data to train and valid\n        train_set=Subset(dataset,train_idx)\n        valid_set=Subset(dataset,valid_idx)\n\n        train_X=[]\n        train_Y=[]\n\n        ##########          training          ##########\n        for i,(inputs,labels) in enumerate(train_set):\n            train_X.append(inputs)\n            train_Y.append(labels)\n\n        train_X=get_poly_features(train_X,degree)\n        train_X=np.hstack((train_X,np.ones((len(train_X),1))))\n        train_X=torch.FloatTensor(train_X)\n        train_Y=torch.FloatTensor(train_Y)\n        train_Y=train_Y.view([train_Y.size(0),1])\n            \n        weight=get_best_weight(train_X,train_Y,_lambda)\n        total_weight+=weight.numpy()\n\n        outputs=linear_regression(train_X,weight)\n        outputs=torch.FloatTensor(outputs)\n\n        loss=RMSE_loss(outputs,train_Y)\n        total_training_loss+=loss/train_X.size(0)\n\n        valid_X=[]\n        valid_Y=[]\n\n        ##########          validation          ########## \n        for i,(inputs,labels) in enumerate(valid_set):\n            valid_X.append(inputs)\n            valid_Y.append(labels)\n\n        valid_X=get_poly_features(valid_X,degree)\n        valid_X=np.hstack((valid_X,np.ones((len(valid_X),1))))\n        valid_X=torch.FloatTensor(valid_X)\n        valid_Y=torch.FloatTensor(valid_Y)\n        valid_Y=valid_Y.view([valid_Y.size(0),1])\n\n        outputs=linear_regression(valid_X,weight)\n        outputs=torch.FloatTensor(outputs)\n\n        loss=RMSE_loss(outputs,valid_Y)\n        total_valid_loss+=loss/valid_X.size(0)\n\n    best_weight=total_weight/dataset.__len__()\n    avg_training_loss=total_training_loss/dataset.__len__()\n    avg_valid_loss=total_valid_loss/dataset.__len__()\n\n    print(f'training_loss: {avg_training_loss:.4f}\\tvalid_loss: {avg_valid_loss:.4f}')\n\n    return best_weight\n\n\n# Training when the cross validation is leave one out\ndef loo_train(dataset,degree=1,_lambda=0):\n    loo=LeaveOneOut()\n\n    total_training_loss=0.0\n    total_valid_loss=0.0\n    total_weight=np.zeros((degree+1,1))\n\n    for train_idx,valid_idx in loo.split(dataset):  # split the data to train and valid\n        train_set=Subset(dataset,train_idx)\n        valid_set=Subset(dataset,valid_idx)\n\n        train_X=[]\n        train_Y=[]\n\n        ##########          training          ##########\n        for i,(inputs,labels) in enumerate(train_set):\n            train_X.append(inputs)\n            train_Y.append(labels) \n\n        train_X=get_poly_features(train_X,degree)\n        train_X=np.hstack((train_X,np.ones((len(train_X),1))))\n        train_X=torch.FloatTensor(train_X)\n        train_Y=torch.FloatTensor(train_Y)\n        train_Y=train_Y.view([train_Y.size(0),1])\n\n        weight=get_best_weight(train_X,train_Y,_lambda)\n        total_weight+=weight.numpy()\n\n        outputs=linear_regression(train_X,weight)\n        outputs=torch.FloatTensor(outputs)\n        outputs=outputs.view([outputs.size(0),1])\n    \n        loss=RMSE_loss(outputs,train_Y)\n        total_training_loss+=loss/train_X.size(0)\n\n        valid_X=[]\n        valid_Y=[]\n\n        ##########          validation          ##########\n        for i,(inputs,labels) in enumerate(valid_set):\n            valid_X.append(inputs)\n            valid_Y.append(labels)\n\n        valid_X=get_poly_features(valid_X,degree)\n        valid_X=np.hstack((valid_X,np.ones((len(valid_X),1))))\n        valid_X=torch.FloatTensor(valid_X)\n        valid_Y=torch.FloatTensor(valid_Y)\n        valid_Y=valid_Y.view([valid_Y.size(0),1])\n\n        outputs=linear_regression(valid_X,weight)\n        outputs=torch.FloatTensor(outputs)\n        outputs=outputs.view([outputs.size(0),1])\n\n        loss=RMSE_loss(outputs,valid_Y)\n        total_valid_loss+=loss\n\n    best_weight=total_weight/dataset.__len__()\n    avg_training_loss=total_training_loss/dataset.__len__()\n    avg_valid_loss=total_valid_loss/dataset.__len__()\n\n    print(f'training_loss: {avg_training_loss:.4f}\\tvalid_loss: {avg_valid_loss:.4f}')\n    return best_weight\n        \n\ndef main():\n\n    ##########          Linear Regression with degree=1,5,10,14          ##########\n    if Path('./data/data.csv').is_file()==False:\n        data_generator('linear','./data/data.csv',20)\n\n    data_set=RegressionDataset('./data/data.csv')\n    total_sz=data_set.__len__()\n    test_sz=int(0.25*total_sz)\n    train_set,test_set=random_split(data_set,[total_sz-test_sz,test_sz])\n\n    origin_train_set=train_set\n    origin_test_set=test_set\n\n    print(\"Regression Linear Leave One Out Degree 1 20 Data Points\")\n    weight_loo_deg1=loo_train(train_set,1)\n    test(test_set,1,weight_loo_deg1)\n\n    print(\"Regression Linear Five Fold Degree 1 20 Data Points\")\n    weight_kf_deg1=kf_train(train_set,1)\n    test(test_set,1,weight_kf_deg1)\n\n    print(\"Regression Linear Leave One Out Degree 5 20 Data Points\")\n    weight_loo_deg5=loo_train(train_set,5)\n    test(test_set,5,weight_loo_deg5)\n\n    print(\"Regression Linear Five Fold Degree 5 20 Data Points\")\n    weight_kf_deg5=kf_train(train_set,5)\n    test(test_set,5,weight_kf_deg5)\n\n    print(\"Regression Linear Leave One Out Degree 10 20 Data Points\")\n    weight_loo_deg10=loo_train(train_set,10)\n    test(test_set,10,weight_loo_deg10)\n\n    print(\"Regression Linear Five Fold Degree 10 20 Data Points\")\n    weight_kf_deg10=kf_train(train_set,10)\n    test(test_set,10,weight_kf_deg10)\n\n    print(\"Regression Linear Leave One Out Degree 14 20 Data Points\")\n    weight_loo_deg14=loo_train(train_set,14)\n    test(test_set,14,weight_loo_deg14)\n\n    print(\"Regression Linear Five Fold Degree 14 20 Data Points\")\n    weight_kf_deg14=kf_train(train_set,14)\n    test(test_set,14,weight_kf_deg14)\n\n    draw_fitting_plot(train_set,[-3,3],weight_loo_deg1,1,['degree=1','degree=5','degree=10','degree=14'],'Linear Data Live One Out Curve','./figure/linear-loo.jpg',weight_loo_deg5,5,weight_loo_deg10,10,weight_loo_deg14,14)\n    draw_fitting_plot(train_set,[-3,3],weight_kf_deg1,1,['degree=1','degree=5','degree=10','degree=14'],'Linear Data Five Folds Curve','./figure/linear-kf.jpg',weight_kf_deg5,5,weight_kf_deg10,10,weight_kf_deg14,14)\n\n    ##########          Linear Regression on Sine Curve Data with degree=5,10,14          ##########\n    if Path('./data/sin_data.csv').is_file()==False:\n        data_generator('sin','./data/sin_data.csv',20)\n\n    data_set=RegressionDataset('./data/sin_data.csv')\n    total_sz=data_set.__len__()\n    test_sz=int(0.25*total_sz)\n    train_set,test_set=random_split(data_set,[total_sz-test_sz,test_sz])\n    \n    print('Regression Sine Leave One Out Degree 5 20 Data Points')\n    weight_loo_deg5=loo_train(train_set,5)\n    test(test_set,5,weight_loo_deg5)\n    \n    print('Regression Sine Five Fold Degree 5 20 Data Points')\n    weight_kf_deg5=kf_train(train_set,5)\n    test(test_set,5,weight_kf_deg5)\n\n    print('Regression Sine Leave One Out Degree 10 20 Data Points')\n    weight_loo_deg10=loo_train(train_set,10)\n    test(test_set,10,weight_loo_deg10)\n    \n    print('Regression Sine Five Fold Degree 10 20 Data Points')\n    weight_kf_deg10=kf_train(train_set,10)\n    test(test_set,10,weight_kf_deg10)\n\n    print('Regression Sine Leave One Out Degree 14 20 Data Points')\n    weight_loo_deg14=loo_train(train_set,14)\n    test(test_set,14,weight_loo_deg14)\n    \n    print('Regression Sine Five Fold Degree 14 20 Data Points')\n    weight_kf_deg14=kf_train(train_set,14)\n    test(test_set,14,weight_kf_deg14)\n\n    draw_fitting_plot(train_set,[0,1],weight_loo_deg5,5,['degree=5','degree=10','degree=14'],'Sine Data Live One Out Curve','./figure/sine-loo.jpg',weight_loo_deg10,10,weight_loo_deg14,14)\n    draw_fitting_plot(train_set,[0,1],weight_kf_deg5,5,['degree=5','degree=10','degree=14'],'Sine Data Five Folds Curve','./figure/sine-kf.jpg',weight_kf_deg10,10,weight_kf_deg14,14)\n\n    ##########          Linear Regression on Different Training Data Size          ##########  \n    if Path('./data/data_320.csv').is_file()==False:\n        data_generator('linear','./data/data_320.csv',320)\n    \n    data_set=RegressionDataset('./data/data_320.csv')\n    total_sz=data_set.__len__()\n    delete_sz=260\n    use_set,delete_set=random_split(data_set,[total_sz-delete_sz,delete_sz])\n\n    total_sz=use_set.__len__()\n    test_sz=int(0.25*total_sz)\n    train_set,test_set=random_split(use_set,[total_sz-test_sz,test_sz])\n\n    print('Regression Linear Leave One Out Degree 14 60 Data Points')\n    weight_loo_data60=loo_train(train_set,14)\n    test(test_set,14,weight_loo_data60)\n\n    print('Regression Linear Five Fold Degree 14 60 Data Points')\n    weight_kf_data60=kf_train(train_set,14)\n    test(test_set,14,weight_kf_data60)\n\n    total_sz=data_set.__len__()\n    delete_sz=160\n    use_set,delete_set=random_split(data_set,[total_sz-delete_sz,delete_sz])\n\n    total_sz=use_set.__len__()\n    test_sz=int(0.25*total_sz)\n    train_set,test_set=random_split(use_set,[total_sz-test_sz,test_sz])\n\n    print('Regression Linear Leave One Out Degree 14 160 Data Points')\n    weight_loo_data160=loo_train(train_set,14)\n    test(test_set,14,weight_loo_data160)\n\n    print('Regression Linear Five Fold Degree 14 160 Data Points')\n    weight_kf_data160=kf_train(train_set,14)\n    test(test_set,14,weight_kf_data160)\n\n    total_sz=data_set.__len__()\n    delete_sz=0\n    use_set,delete_set=random_split(data_set,[total_sz-delete_sz,delete_sz])\n\n    total_sz=use_set.__len__()\n    test_sz=int(0.25*total_sz)\n    train_set,test_set=random_split(use_set,[total_sz-test_sz,test_sz])\n\n    print('Regression Linear Leave One Out Degree 14 320 Data Points')\n    weight_loo_data320=loo_train(train_set,14)\n    test(test_set,14,weight_loo_data320)\n\n    print('Regression Linear Five Fold Degree 14 320 Data Points')\n    weight_kf_data320=kf_train(train_set,14)\n    test(test_set,14,weight_kf_data320)\n\n    draw_fitting_plot(origin_train_set,[-3,3],weight_loo_data60,14,['m=60','m=160','m=320'],'Linear Data Different m Live One Out Curve','./figure/data-m-loo.jpg',weight_loo_data160,14,weight_loo_data320,14)\n    draw_fitting_plot(origin_train_set,[-3,3],weight_kf_data60,14,['m=60','m=160','m=320'],'Linear Data Different m Five Folds Curve','./figure/data-m-kf.jpg',weight_kf_data160,14,weight_kf_data320,14)\n\n    ##########          Linear Regression with Regularization Term lambda          ##########\n    print('Regularization 0.001/m Linear Five Fold Degree 14 20 Data Points')\n    _lambda=0.001/20\n    weight_kf_0001l=kf_train(origin_train_set,14,_lambda)\n    test(origin_test_set,14,weight_kf_0001l)\n    \n    print('Regularization 1/m Linear Five Fold Degree 14 20 Data Points')\n    _lambda=float(1)/20\n    weight_kf_1l=kf_train(origin_train_set,14,_lambda)\n    test(origin_test_set,14,weight_kf_1l)\n\n    print('Regularization 1000/m Linear Five Fold Degree 14 20 Data Points')\n    _lambda=float(1000)/20\n    weight_kf_1000l=kf_train(origin_train_set,14,_lambda)\n    test(origin_test_set,14,weight_kf_1000l)\n\n    draw_fitting_plot(origin_train_set,[-3,3],weight_kf_0001l,14,['0.001/m','1/m','1000/m'],'Linear Data Five Fold with Regularization Curve','./figure/regularization-kf.jpg',weight_kf_1l,14,weight_kf_1000l,14)\n\n\nif __name__=='__main__':\n    main()", "meta": {"hexsha": "59742610a012c3aed531293c0b191c53a64f5ec7", "size": 15729, "ext": "py", "lang": "Python", "max_stars_repo_path": "project_1/main.py", "max_stars_repo_name": "joycenerd/ML_2020", "max_stars_repo_head_hexsha": "fdcbd97a99db16a3f2e4db44871477e1e4d5c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project_1/main.py", "max_issues_repo_name": "joycenerd/ML_2020", "max_issues_repo_head_hexsha": "fdcbd97a99db16a3f2e4db44871477e1e4d5c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project_1/main.py", "max_forks_repo_name": "joycenerd/ML_2020", "max_forks_repo_head_hexsha": "fdcbd97a99db16a3f2e4db44871477e1e4d5c63a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7477272727, "max_line_length": 222, "alphanum_fraction": 0.6940047047, "include": true, "reason": "import numpy", "num_tokens": 4278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.8856314813647587, "lm_q1q2_score": 0.8505260755626841}}
{"text": "import numpy as np\r\n\r\nprint(\"\\nMétodo de Newton-Raphson\")\r\n\r\n# Definindo a função\r\ndef f(x):\r\n    return (x*np.log10(x)) - 1\r\n\r\n# Definindo a derivada\r\ndef der(x):\r\n    dx = 1e-10\r\n    return (f(x+dx) - f(x)) / dx\r\n\r\n# Implementação do método numérico\r\ndef newraph(tol, x):\r\n    x_0 = x\r\n    dif = 1\r\n    iter = 0\r\n    while dif > tol:\r\n        x_1 = x_0 - (f(x_0)/der(x_0))\r\n        dif = abs(x_1 - x_0)\r\n        x_0 = x_1\r\n        iter += 1\r\n    print(\"\\nRaiz:\", x_1)\r\n    print(\"Quantidade de iterações:\", iter)\r\n    print(\"x_1 - x_0 = \", dif, \"\\n\")\r\n\r\n\r\n# Atribuição dos parâmetros\r\ntol =  1e-4\r\na_inicial = 2\r\nb_inicial = 3\r\nx_inicial = 3\r\n\r\n\r\nnewraph(tol, x_inicial)\r\n\r\n\r\n\r\n", "meta": {"hexsha": "6316776a6acec6ac6cb216bc3ee137c8cb596187", "size": 680, "ext": "py", "lang": "Python", "max_stars_repo_path": "implementacao newton-raphson.py", "max_stars_repo_name": "gkaori/Newton-Rapshon-e-Bissec-o", "max_stars_repo_head_hexsha": "0d0ecec080f89c9f57aad844205efc769603ddcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "implementacao newton-raphson.py", "max_issues_repo_name": "gkaori/Newton-Rapshon-e-Bissec-o", "max_issues_repo_head_hexsha": "0d0ecec080f89c9f57aad844205efc769603ddcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "implementacao newton-raphson.py", "max_forks_repo_name": "gkaori/Newton-Rapshon-e-Bissec-o", "max_forks_repo_head_hexsha": "0d0ecec080f89c9f57aad844205efc769603ddcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0, "max_line_length": 44, "alphanum_fraction": 0.5382352941, "include": true, "reason": "import numpy", "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611586300241, "lm_q2_score": 0.8856314738181875, "lm_q1q2_score": 0.8505260683152505}}
{"text": "\"\"\" Orbital Mechanics for Engineering Students Example 1.16\nQuestion:\nExpand the function sin(t+h) in a Taylor series around t=1.\nPlot the Taylor series of orders 1 to 4 and compare them with\nsin(1+h) for -2<h<2.\nWritten by: J.X.J. Bannwarth\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom sympy import symbols, diff, sin, cos\nfrom math import factorial\nfrom numpy import array, linspace, dot, zeros\nimport numpy as np\n\n# Title\nprint(\"Orbital Mechanics for Engineering Students Example 1.16\")\n\n# Equation to approximate\nt = symbols('t')\ng = sin(t)\n\n# Linearisation point\ntLin = 1.\n\n# Step size\nhs = linspace(-2.,2.,50)\ngTrue = np.sin(tLin + hs)\n\n# Find the taylor coefficients\norders = range(5)\ntaylorCoefsEqn = [diff(g, t, order)/factorial(order) for order in orders]\ntaylorCoefs = array([coef.evalf(subs={t:tLin}) for coef in taylorCoefsEqn])\n\n# Calculate the terms of the Taylor series polynomials\ntermApprox = zeros((hs.shape[0],len(orders)))\nfor idx, h in enumerate(hs):\n    powers = array([h**order for order in orders])\n    termApprox[idx,:] = powers * taylorCoefs\n\n# Calculate the sum of the terms\ngApprox = zeros((hs.shape[0],len(orders)))\ngApprox[:,0] = termApprox[:,0]\nfor idx in range(1,gApprox.shape[1]):\n    gApprox[:,idx] = termApprox[:,0:idx+1].sum(axis=1)\n\n# Plot the results\nplt.figure()\nplt.grid()\nplt.plot(hs, gTrue, label=f\"sin(1+h)\")\nfor idx, order in enumerate(orders):\n    plt.plot(hs, gApprox[:,idx], label=f\"$p_{order}$\")\nplt.xlabel(\"$h$ (-)\")\nplt.ylabel(\"Value (-)\")\nplt.title(\"Example 1.16 Plots of zeroth- to fourth-order\\nTaylor series expansions of sin(1-h)\")\nplt.legend()\nplt.show()\n", "meta": {"hexsha": "52973944d0aa97a2f44171bdea35234e46c2ccef", "size": 1608, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapter1/example_1_16.py", "max_stars_repo_name": "JBannwarth/OrbitalMechanics", "max_stars_repo_head_hexsha": "fe3c36eba7cadf977804fb2ad866e0e28a96aab5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-29T13:34:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-29T13:34:48.000Z", "max_issues_repo_path": "chapter1/example_1_16.py", "max_issues_repo_name": "JBannwarth/OrbitalMechanics", "max_issues_repo_head_hexsha": "fe3c36eba7cadf977804fb2ad866e0e28a96aab5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-06T21:17:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-07T00:52:39.000Z", "max_forks_repo_path": "chapter1/example_1_16.py", "max_forks_repo_name": "JBannwarth/OrbitalMechanics", "max_forks_repo_head_hexsha": "fe3c36eba7cadf977804fb2ad866e0e28a96aab5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7142857143, "max_line_length": 96, "alphanum_fraction": 0.7089552239, "include": true, "reason": "import numpy,from numpy,from sympy", "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611608990299, "lm_q2_score": 0.8856314692902446, "lm_q1q2_score": 0.8505260659762929}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nIn the introduction of his MOOC \"SMAC\" (Statistical Mechanics: Algorithms and\nComputations - https://www.coursera.org/learn/statistical-mechanics), Werner\nKrauth propose a simple method to compute pi using a direct sampling\nMonte Carlo simulation. A program is proposed in Python, in a version which\nallows to do many runs of the function direct_pi(N). The code is written in a\nstyle close to pseudocode used for algorithms, or classical coding style used\nin C, Fortran,...\n\nIt is possible to write the function in a more \"pythonic\" way, or to use the\nnumpy numerical library, to improve compactness and efficiency.\n\nFunction direct_pi_DV(N) use pure python with list comprehension to eliminate\nthe for loop. The sum is directly made on the boolean comparison results to count\nthe number of true trials.\n\nFunction direct_pi_DV_np(N) use the numpy library to vectorize the loop, directly\nsquare values and sum the array elements over the smaller axis. Again the sum\nis directly made on the boolean comparisons.\n\nFinally, in order to compare efficiency, the execution times of the three\nversions have been measured using the timeit library.\n\nHere is value obtain for a sample run :\ndirect_pi       : 3.5209695600005944 s\ndirect_pi_DV    : 4.000994963998892 s\ndirect_pi_Dv_np : 0.19237353700009407 s\n\nThe use ot the numpy library clearly improve the computer speed performance by\na factor about 20.\n\"\"\"\nimport random, timeit\nimport numpy as np\n \ndef direct_pi(N):\n    n_hits = 0\n    for i in range(N):\n        x, y = random.uniform(-1.0, 1.0), random.uniform(-1.0, 1.0)\n        if x ** 2 + y ** 2 < 1.0:\n            n_hits += 1\n    return n_hits\n\ndef direct_pi_DV(N):\n    return sum((random.uniform(-1,1)**2 + random.uniform(-1,1)**2) < 1 for i in range(N))\n \ndef direct_pi_DV_np(N):\n    return np.sum((np.random.uniform(-1,1,(N,2))**2).sum(1)<1)\n\nn_runs = 1000\nn_trials = 4000\n\n# running :\nfor run in range(n_runs):\n    print(run, 4.0 * direct_pi(n_trials) / n_trials)\n\nfor run in range(n_runs):\n    print(run, 4.0 * direct_pi_DV(n_trials) / n_trials)\n\nfor run in range(n_runs):\n    print(run, 4.0 * direct_pi_DV_np(n_trials) / n_trials)\n\n# timing three versions :\nprint(timeit.timeit('direct_pi('+str(n_trials)+')', \"from __main__ import direct_pi\", number=n_runs))\nprint(timeit.timeit('direct_pi_DV('+str(n_trials)+')', \"from __main__ import direct_pi_DV\", number=n_runs))\nprint(timeit.timeit('direct_pi_DV_np('+str(n_trials)+')', \"from __main__ import direct_pi_DV_np\", number=n_runs))\n", "meta": {"hexsha": "692b2714409400ad1c58c935ddf00bc589ef1a8f", "size": 2515, "ext": "py", "lang": "Python", "max_stars_repo_path": "direct_pi_multirun-timeit.py", "max_stars_repo_name": "didiervillers/python_programs", "max_stars_repo_head_hexsha": "1adf42457853b90934621d4bf5447ab149956e77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "direct_pi_multirun-timeit.py", "max_issues_repo_name": "didiervillers/python_programs", "max_issues_repo_head_hexsha": "1adf42457853b90934621d4bf5447ab149956e77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "direct_pi_multirun-timeit.py", "max_forks_repo_name": "didiervillers/python_programs", "max_forks_repo_head_hexsha": "1adf42457853b90934621d4bf5447ab149956e77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5373134328, "max_line_length": 113, "alphanum_fraction": 0.7332007952, "include": true, "reason": "import numpy", "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.9284087931273041, "lm_q1q2_score": 0.8505242164720349}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 30 15:36:39 2019\n\n@author: Simón Cometto\n\"\"\"\n\nimport numpy as np\n\n\ndef biseccion(f, a, b, tolerancia=False, iteraciones=False):\n    ''' Encuentra el cero de f entre a y b mediante el método bisección\n        Parámetros: \n            ->  f: una función que, dado x, devuelve el valor de f(x)\n            ->  a y b: números reales iniciales para el método\n            ->  tolerancia: el menor intérvalo entre el cual se encuentra el cero\n            ->  iteraciones: la cantidad de iteraciones a realizar en el algoritmo'''\n\n    #Si a la función no se le pasa un parámetro para detener las iteraciones devuelve False\n    if not (tolerancia or iteraciones):\n        return False\n\n    if (f(a)*f(b))<0: #Hay un cero en el medio\n        #El algoritmo se ejecuta hasta llegar a un intervalo de tolerancia menor o igual a \"tolerancia\"\n        if(tolerancia):\n            #Mientras el intérvalo es mayor a la tolerancia\n            while(abs(a-b)>tolerancia):\n                #Encuentro el punto medio entre a y b\n                c =  a + (abs(b-a)*0.5)\n\n                #Si f(a) y f(c) tienen signo distinto, entonces hubo un cruce por cero entre a y b\n                if(f(a)*f(c)<0):\n                    b = c\n                #Sino el cero se encuentra entre b y c\n                else:\n                    a = c\n            return c\n        elif iteraciones:\n            for i in range(iteraciones):\n                c = a + (abs(b - a) * 0.5)\n\n                # Si f(a) y f(c) tienen signo distinto, entonces hubo un cruce por cero entre a y b\n                if (f(a) * f(c) < 0):\n                    b = c\n                # Sino el cero se encuentra entre b y c\n                else:\n                    a = c\n            return c\n    else:    #No se sabe si hay cero en el medio\n        pass\n        #Ver que devolver en caso de que no haya un cero en el medio, o como implementarlo\n\ndef punto_fijo(g, x_i, n):\n    ''' Encuentra el cero de f a partir de g.\n        Parámetros:\n            ->  g: surge de despejar x de f\n            ->  x_i: número real inicial para el método\n            ->  n: la cantidad de iteraciones'''\n    for i in range(n):\n        x_i = g(x_i)\n    return x_i\n\nif __name__ == \"__main__\":\n    f = lambda x: 1*(x**2) - x - 2\n\n    a = float(input(\"Ingrese a: \"))\n    b = float(input(\"Ingrese b: \"))\n    i = int(input(\"Ingrese la cantidad de iteraciones: \"))\n\n    cero_b = biseccion(f, a, b, iteraciones=i)\n    g = lambda x: (x + 2) ** 0.5\n    cero_pf = punto_fijo(g, b, i)\n    print(\"Resultado método de bisección:  \", cero_b)\n    print(\"Resultado método de punto fijo: \", cero_pf)\n", "meta": {"hexsha": "1411d999c383741d059cbe4283a812b42eb232f1", "size": 2650, "ext": "py", "lang": "Python", "max_stars_repo_path": "metodos.py", "max_stars_repo_name": "simoncometto/PowerFlow", "max_stars_repo_head_hexsha": "a0215dc7ad8384b80bf308fc37361712d19a61f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "metodos.py", "max_issues_repo_name": "simoncometto/PowerFlow", "max_issues_repo_head_hexsha": "a0215dc7ad8384b80bf308fc37361712d19a61f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "metodos.py", "max_forks_repo_name": "simoncometto/PowerFlow", "max_forks_repo_head_hexsha": "a0215dc7ad8384b80bf308fc37361712d19a61f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3333333333, "max_line_length": 103, "alphanum_fraction": 0.5486792453, "include": true, "reason": "import numpy", "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.911179702173019, "lm_q1q2_score": 0.8505232033308768}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom ivp_solvers import IVP, IVPSolver\n\n\nclass PredatorPrey1(IVP):\n    \"\"\"\n    Predator-prey taken from example 16.8 (pg. 496) of \"A First Course in Numerical Methods\" by Ascher and Greif\n    \"\"\"\n    tf = 100\n    y0 = np.array([80., 30.])\n    yf = np.array([94.04588719, 38.11498521])  # For running tests\n\n    def dy_dt(self, _, y):\n        return np.array([\n            0.25 * y[0] - 0.01 * y[0] * y[1],\n            -y[1] + 0.01 * y[0] * y[1]\n        ])\n\n\ndef plot_example(t, y, show=True):\n    plt.plot(t, y)\n\n    if show:\n        plt.show()\n\n\ndef run_example(problem: IVP, solver: IVPSolver, plot=True, show=True):\n    with Timer():\n        t, y = solver.solve_problem(problem)\n\n    if plot:\n        plot_example(t, y, show=show)\n\n\nif __name__ == '__main__':\n    from runge_kutta.explicit import Midpoint\n    from ivp_solvers import CustomFixedStepRKSolver, FixedEuler, FixedRK2, FixedRK4, FixedThreeEigthsRK4\n    from shared_utils.tests import PerfTimerNS as Timer\n\n    run_example(PredatorPrey1(), FixedEuler(step_size=0.01), show=False)\n    run_example(PredatorPrey1(), CustomFixedStepRKSolver(0.1, Midpoint()), show=False)\n    run_example(PredatorPrey1(), FixedRK2(step_size=0.1), show=False)\n    run_example(PredatorPrey1(), FixedRK4(step_size=0.1), show=False)\n    run_example(PredatorPrey1(), FixedThreeEigthsRK4(step_size=0.1), show=True)\n\n    _t, _y = FixedThreeEigthsRK4(step_size=0.01).solve_problem(PredatorPrey1())\n\n    plt.show()\n", "meta": {"hexsha": "b07bfdb6413a2cb6f36ac6978602cad6409bf7e5", "size": 1500, "ext": "py", "lang": "Python", "max_stars_repo_path": "ivp_solvers/example_problems.py", "max_stars_repo_name": "SeanMatthewNolan/algorithm_sandbox", "max_stars_repo_head_hexsha": "07e5f4880f4cdbea99f3722ba3c898ea95d8ba13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ivp_solvers/example_problems.py", "max_issues_repo_name": "SeanMatthewNolan/algorithm_sandbox", "max_issues_repo_head_hexsha": "07e5f4880f4cdbea99f3722ba3c898ea95d8ba13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ivp_solvers/example_problems.py", "max_forks_repo_name": "SeanMatthewNolan/algorithm_sandbox", "max_forks_repo_head_hexsha": "07e5f4880f4cdbea99f3722ba3c898ea95d8ba13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4117647059, "max_line_length": 112, "alphanum_fraction": 0.6673333333, "include": true, "reason": "import numpy", "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191348157374, "lm_q2_score": 0.8902942261220292, "lm_q1q2_score": 0.8505151098303434}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.array(list(range(0, 11)))\ny = np.array(list(map(lambda n: n * n, x)))\n\n\ndef compute_cost_function(m, t0, t1, x, y):\n    return 1 / 2 / m * sum([(t0 + t1 * np.asarray([x[i]]) - y[i])**2 for i in range(m)])\n\n\ndef gradient_descent(x, y, alpha=0.01, ep=0.0001, max_iter=1500):\n    converged = False\n    iter = 0\n    m = x.shape[0]    # number of samples\n\n    # initial theta\n    t0 = 0\n    t1 = 0\n\n    # total error, J(theta)\n    J = compute_cost_function(m, t0, t1, x, y)\n    # print('J=', J);\n    # Iterate Loop\n    num_iter = 0\n    while not converged:\n        # for each training sample, compute the gradient (d/d_theta j(theta))\n        grad0 = 1.0 / m * sum([(t0 + t1 * np.asarray([x[i]]) - y[i]) for i in range(m)])\n        grad1 = 1.0 / m * sum([(t0 + t1 * np.asarray([x[i]]) - y[i]) * np.asarray([x[i]]) for i in range(m)])\n\n        # update the theta_temp\n        temp0 = t0 - alpha * grad0\n        temp1 = t1 - alpha * grad1\n\n        # update theta\n        t0 = temp0\n        t1 = temp1\n\n        # mean squared error\n        e = compute_cost_function(m, t0, t1, x, y)\n        # print ('J = ', e)\n        J = e    # update error\n        iter += 1    # update iter\n\n        if iter == max_iter:\n            print('Max interactions exceeded!')\n            converged = True\n\n    return t0, t1\n\n\ndef graph_points(data_x, data_y):\n    for x, y in zip(data_x, data_y):\n        plt.scatter(x, y, c='r')\n\n\ndef graph_line(data_x, m, b):\n    line = [(m * x) + b for x in data_x]\n    plt.plot(data_x, line, c='b')\n\n\ndef squared_error(y_points, regression_line):\n    return sum((regression_line - y_points)**2)\n\n\ndef coeff_of_determination(y_points, regression_line):\n    y_mean_line = [np.mean(y_points) for y in regression_line]\n    squared_error_regr = squared_error(y_points, regression_line)\n    squared_error_y_mean = squared_error(y_points, y_mean_line)\n    return 1 - (squared_error_regr / squared_error_y_mean)\n\n\ngraph_points(x, y)\nb, m = gradient_descent(x, y)\nprint(m, b)\ngraph_line(x, m, b)\nprint(coeff_of_determination(y, m * x + b))\nplt.show()\n", "meta": {"hexsha": "dd840e8930c99a5d3a0f46d059e97cfe3ad94b20", "size": 2111, "ext": "py", "lang": "Python", "max_stars_repo_path": "004-gradient-descent/linear_grad.py", "max_stars_repo_name": "MuhamedEssam/deeplearning", "max_stars_repo_head_hexsha": "e6004da4df5d8d066f637dc471f4a0f590f3af1e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2018-03-05T11:17:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T02:10:36.000Z", "max_issues_repo_path": "004-gradient-descent/linear_grad.py", "max_issues_repo_name": "MuhamedEssam/deeplearning", "max_issues_repo_head_hexsha": "e6004da4df5d8d066f637dc471f4a0f590f3af1e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2018-03-10T10:17:30.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-23T00:57:39.000Z", "max_forks_repo_path": "004-gradient-descent/linear_grad.py", "max_forks_repo_name": "deepcollege/deeplearning", "max_forks_repo_head_hexsha": "e6004da4df5d8d066f637dc471f4a0f590f3af1e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-03-06T01:21:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T02:10:37.000Z", "avg_line_length": 26.7215189873, "max_line_length": 109, "alphanum_fraction": 0.5945049739, "include": true, "reason": "import numpy", "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290955604489, "lm_q2_score": 0.8757869916479466, "lm_q1q2_score": 0.8505022291026768}}
{"text": "import numpy as np\n# import scipy as sp\n# import sklearn\n# import matplotlib.pyplot as plt\n\n\nclass Lab1(object):\n    def solver(self, A, b):\n        return np.dot(np.linalg.inv(A), b)\n\n    def fitting(self, x, y):\n        xmatr = np.column_stack((x, np.ones(x.shape)))\n        coeff = np.dot(np.linalg.pinv(xmatr), y)\n        return coeff\n\n    def naive5(self, X, A, Y):\n        # Calculate the matrix with $(i,j$)-th entry as  $\\mathbf{x}_i^\\top A \\mathbf{y}_j$ by looping over the rows of $X,Y$.\n        qf = np.zeros((X.shape[0], Y.shape[0]))\n        for i in range(X.shape[0]):\n            for j in range(Y.shape[0]):\n                qf[i, j] = np.dot(np.dot(X[i], A), Y[j])\n        return qf\n\n    def matrix5(self, X, A, Y):\n        # Repeat part (a), but using only matrix operations (no loops!).\n        return np.dot(np.dot(X, A), Y.T)\n\n    def naive6(self, X, A):\n        # Calculate a vector with $i$-th component $\\mathbf{x}_i^\\top A \\mathbf{x}_i$ by looping over the rows of $X$.\n        qf = np.zeros(X.shape[0])\n        for i in range(X.shape[0]):\n            qf[i] = np.dot(np.dot(X[i], A), X[i])\n        return qf\n\n    def matrix6(self, X, A):\n        # Repeat part (a) using matrix operations (no loops!).\n        return np.sum(np.dot(X, A)*X, axis=1)\n", "meta": {"hexsha": "62d0109c45742449ef7e12ce1b4f9348b44a8f29", "size": 1269, "ext": "py", "lang": "Python", "max_stars_repo_path": "ECE365/machine learning/lab1_vvv_2021/main.py", "max_stars_repo_name": "debugevent90901/courseArchive", "max_stars_repo_head_hexsha": "1585c9a0f4a1884c143973dcdf416514eb30aded", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ECE365/machine learning/lab1_vvv_2021/main.py", "max_issues_repo_name": "debugevent90901/courseArchive", "max_issues_repo_head_hexsha": "1585c9a0f4a1884c143973dcdf416514eb30aded", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ECE365/machine learning/lab1_vvv_2021/main.py", "max_forks_repo_name": "debugevent90901/courseArchive", "max_forks_repo_head_hexsha": "1585c9a0f4a1884c143973dcdf416514eb30aded", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3947368421, "max_line_length": 126, "alphanum_fraction": 0.5563435776, "include": true, "reason": "import numpy,import scipy", "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290955604489, "lm_q2_score": 0.8757869835428965, "lm_q1q2_score": 0.8505022212316269}}
{"text": "import math\nimport numpy as np\n\n\ndef read_file(name):\n    # Open file\n    file = open(name, 'r')\n\n    # Return content\n    return file.read()\n\n\ndef exercise_1_generator(size, alphabet, probability):\n    # Result\n    results = \"\"\n\n    # Loop to generate size-long text\n    for _ in range(size):\n        results += np.random.choice(alphabet, p=probability)\n\n    # Return prepared text\n    return results\n\n\ndef entropy(dictionary):\n    # Entropy sum\n    entropy_result = 0.0\n\n    # Loop to analyze\n    for key, value in dictionary.items():\n        entropy_result += value * math.log(value, 2)\n\n    # Return result\n    return -entropy_result\n\n\ndef analyze_content(content):\n    # Letters dictionary\n    letters = {}\n\n    # Letters counter to prepare probability of single letter\n    counter = 0\n\n    # Loop to analyze content\n    for _, letter in enumerate(content):\n        cardinality = letters.get(letter, 0)\n        letters.update({letter: cardinality + 1})\n        counter += 1\n\n    # Loop to change cardinality to probability\n    for letter in letters:\n        letters.update({letter: letters.get(letter) / counter})\n\n    # Return letters dictionary\n    return letters\n\n\ndef analyze_characters(content, row, separator=''):\n    # Results - dictionary with letters\n    letters = {}\n\n    # Last characters\n    last_characters = []\n\n    # Counter\n    counter = 0\n\n    # Loop to iterate\n    for char in content:\n        if len(last_characters) == row:\n            # Fetch dictionary\n            selected_dictionary = letters.get(separator.join(last_characters), {})\n\n            # Update total counter\n            total = selected_dictionary.get('--TOTAL--', 0)\n            selected_dictionary.update({'--TOTAL--': total + 1})\n\n            # Update counter this letter\n            cardinality = selected_dictionary.get(char, 0)\n            selected_dictionary.update({char: cardinality + 1})\n\n            # Update selected dictionary\n            letters.update({separator.join(last_characters): selected_dictionary})\n\n            # Update counter\n            counter += 1\n\n        # Append char to list\n        last_characters.append(char)\n\n        # Check length - if greater than row -> delete first char (FIFO)\n        if len(last_characters) > row:\n            del (last_characters[0])\n\n    # Return letters dictionary with counter\n    return letters, counter\n\n\ndef cardinality_to_probability(dictionary, counter):\n    key_dictionary = {}\n\n    # Loop to change cardinality to probability\n    for key, value_dict in dictionary.items():\n        # Fetch cardinality from special key\n        cardinality = value_dict.pop('--TOTAL--')\n\n        # Loop to iterate - values in dictionary\n        for value_key, value in value_dict.items():\n            # Set value\n            value_dict.update({value_key: value / cardinality})\n\n        # Probability of key\n        key_dictionary[key] = cardinality / counter\n\n        # Update dictionary\n        dictionary.update({key: value_dict})\n\n    # Return updated dictionary\n    return dictionary, key_dictionary\n\n\ndef conditional_entropy(dictionary, keys):\n    # Entropy\n    entropy_value = 0.0\n\n    # Sum over keys - get all values\n    for key, probability_x in keys.items():\n        for value in dictionary.get(key).values():\n            entropy_value += probability_x * value * math.log(value, 2)\n\n    # Return calculated entropy\n    return -entropy_value\n\n\ndef main():\n    #\n    # Exercise 1 - Random, all letters with probability 1/37\n    #\n\n    letters = list('qwertyuiopasdfghjklzxcvbnm0123456789 ')\n    probability = [1/37 for _ in letters]\n    size = 10_000\n    text = exercise_1_generator(size=size, alphabet=letters, probability=probability)\n    letters_dictionary = analyze_content(text)\n    entropy_result = entropy(letters_dictionary)\n\n    print('Exercise 1 - Raw, random text')\n    print('\\tEntropy =>', entropy_result)\n\n    #\n    # Exercise 1 - Analyze content from sample Wiki\n    #\n\n    file_name = '../Exercise_1/norm_wiki_sample.txt'\n    content = read_file(file_name)\n    size = 10_000\n    letters_dictionary = analyze_content(content)\n    text = exercise_1_generator(size=size, alphabet=list(letters_dictionary.keys()), probability=list(letters_dictionary.values()))\n    letters_dictionary = analyze_content(text)\n    entropy_result = entropy(letters_dictionary)\n\n    print('Exercise 1 - Based on text')\n    print('\\tEntropy =>', entropy_result)\n\n    #\n    # Exercise 2\n    #\n\n    files = ['norm_wiki_en.txt', 'norm_wiki_la.txt', 'sample0.txt', 'sample1.txt', 'sample2.txt', 'sample3.txt', 'sample4.txt', 'sample5.txt']\n    rows = [1, 2, 3, 4, 5]\n\n    for file_name in files:\n        print('File ' + str(file_name))\n        content_char = read_file(file_name)\n        content_words = content_char.split()\n\n        print('\\tContent [characters] =>', entropy(analyze_content(content_char)))\n        print('\\tContent [words] =>', entropy(analyze_content(content_words)))\n\n        for row in rows:\n            words, counter = analyze_characters(content_char, row, separator='')\n            dictionary, keys = cardinality_to_probability(words, counter)\n            print('\\t- chars @ ' + str(row) + ' =>', conditional_entropy(dictionary, keys))\n\n            words, counter = analyze_characters(content_words, row, separator=' ')\n            dictionary, keys = cardinality_to_probability(words, counter)\n            print('\\t- words @ ' + str(row) + ' =>', conditional_entropy(dictionary, keys))\n\n        print('-------------------')\n\n\nif __name__ == '__main__':\n    main()", "meta": {"hexsha": "f3311c9aeccdec8bd93cb16eb6031dc837943736", "size": 5526, "ext": "py", "lang": "Python", "max_stars_repo_path": "Exercise_3/exercise_3.py", "max_stars_repo_name": "Bartosz-Gorka-Archive/timkod_put_poznan_2018", "max_stars_repo_head_hexsha": "4b0cca7fa506dd8eb43289fed97cfac57266e7c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-01-25T21:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-25T21:21:44.000Z", "max_issues_repo_path": "Exercise_3/exercise_3.py", "max_issues_repo_name": "Bartosz-Gorka-Archive/timkod_put_poznan_2018", "max_issues_repo_head_hexsha": "4b0cca7fa506dd8eb43289fed97cfac57266e7c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercise_3/exercise_3.py", "max_forks_repo_name": "Bartosz-Gorka-Archive/timkod_put_poznan_2018", "max_forks_repo_head_hexsha": "4b0cca7fa506dd8eb43289fed97cfac57266e7c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6321243523, "max_line_length": 142, "alphanum_fraction": 0.6433224756, "include": true, "reason": "import numpy", "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971129089711396, "lm_q2_score": 0.8757869803008764, "lm_q1q2_score": 0.8505022129606824}}
{"text": "from lam.eigen.eigenvalue import *\nimport json\nfrom lam.readtext.readtext import readtext\nimport sympy as sp\nimport sympy.core.numbers as nu\nimport numpy as np\nclass MyEncoder(json.JSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, np.integer):\n            return int(obj)\n        elif isinstance(obj, np.floating):\n            return float(obj)\n        elif isinstance(obj, np.ndarray):\n            return obj.tolist()\n        elif isinstance(obj,sp.core.numbers.Integer):\n            return str(obj)\n        else:\n            return str(obj)\ndef getlambdamat(mat: sp.MutableDenseMatrix):#得到矩阵λE-A\n    lambdamatrix = -mat\n    lambdamatrix1 = sp.eye(mat.shape[0])\n    x = sp.symbols(\"lambda\")\n    lambdamatrix1 = lambdamatrix1 * x\n    lambdamatrix = lambdamatrix + lambdamatrix1\n    return lambdamatrix\ndef getlambdamatvalue(mat: sp.MutableDenseMatrix):#得到列表[λ1E-A,λ2E-A,.....λiE-A]\n    lambdamatrix = -mat\n    lambdamatrix1 = sp.eye(mat.shape[0])\n    eigenvalues=list(mat.eigenvals().keys())\n    list0=[]\n    for i in range(len(eigenvalues)):\n        lambdamatrix2=lambdamatrix1*eigenvalues[i]\n        lambdamatrix3 = lambdamatrix + lambdamatrix2\n        list0.append(lambdamatrix3)\n    return list0\ndef slveigengetcharpoly(a:str):#特征多项式\n    eigenSolver = EigenSolver(readtext(a))\n    p = eigenSolver.getCharpoly()\n    p=sp.latex(p)\n    json_str = json.dumps(p)\n    return json_str\ndef slveigenvalue(a:str):#特征值\n    eigenSolver = EigenSolver(readtext(a))\n    p = eigenSolver.getEigenvalues()\n    p = sp.latex(p)\n    json_str = json.dumps(p)\n    return json_str\ndef slveigenvectors(a:str):#特征向量\n    eigenSolver = EigenSolver(readtext(a))\n    eigenvectors = eigenSolver.getEigenvectors()\n    eigenvectors_0 = []\n    for i in range(len(eigenvectors)):\n        p = []\n        for j in range(len(eigenvectors[i][2])):\n            p.append(sp.latex(eigenvectors[i][2][j]))\n        m = [sp.latex(eigenvectors[i][0]), sp.latex(eigenvectors[i][1]), p]\n        eigenvectors_0.append(m)\n    eigenvectors=eigenvectors_0\n    return eigenvectors\ndef slveigenCourse(a:str):#（特征值求解过程）\n    eigenSolver=EigenSolver(readtext(a))\n    p=eigenSolver.get_course()\n    matrix=p['matrix']\n    lambdamat = getlambdamat(matrix)\n    lambdamatvalue = getlambdamatvalue(matrix)\n    eigenvectors=p['eigenvectors']\n    charpoly=p['charpoly']\n    matrix=sp.latex(matrix)\n    charpoly=sp.latex(charpoly)\n    eigenvectors_0=[]\n    for i in range(len(eigenvectors)):\n        q = []\n        for j in range(len(eigenvectors[i][2])):\n            q.append(sp.latex(eigenvectors[i][2][j]))\n        m = (sp.latex(eigenvectors[i][0]), sp.latex(eigenvectors[i][1]), q)\n        eigenvectors_0.append(m)\n    p['matrix']=matrix\n    p['eigenvectors']=eigenvectors_0\n    p['charpoly']=charpoly\n    print(p['charpoly'])\n    lambdamat = sp.latex(lambdamat)\n    for i in range(len(lambdamatvalue)):\n        lambdamatvalue[i] = sp.latex(lambdamatvalue[i])\n    p.update({'lambdamat': lambdamat})\n    p.update({'lambdamatvalue':lambdamatvalue})\n    return p\n\nif __name__ == '__main__':\n    slveigenCourse(\"[[3,2,4],[2,0,2],[4,2,3]]\")\n\n\n", "meta": {"hexsha": "6d6a51142a1792ff8f4cfacdb211853dad30655f", "size": 3100, "ext": "py", "lang": "Python", "max_stars_repo_path": "output/slveigen.py", "max_stars_repo_name": "HelloMrGeorge/LinearAlgebraMachine", "max_stars_repo_head_hexsha": "78a002347341eb2612e8d9222e60663e06aad449", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2022-01-24T13:57:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T04:32:10.000Z", "max_issues_repo_path": "output/slveigen.py", "max_issues_repo_name": "HelloMrGeorge/LinearAlgebraMachine", "max_issues_repo_head_hexsha": "78a002347341eb2612e8d9222e60663e06aad449", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-09-27T07:15:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T14:56:37.000Z", "max_forks_repo_path": "output/slveigen.py", "max_forks_repo_name": "HelloMrGeorge/LinearAlgebraMachine", "max_forks_repo_head_hexsha": "78a002347341eb2612e8d9222e60663e06aad449", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6956521739, "max_line_length": 79, "alphanum_fraction": 0.6583870968, "include": true, "reason": "import numpy,import sympy", "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96741025335478, "lm_q2_score": 0.8791467770088162, "lm_q1q2_score": 0.8504956062821372}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef lag(x, y, num):\r\n    \"\"\"\r\n    'num' is a set of given points, use x and y to figure out lagrange\r\n    polynomial and calculate all the corresponding values for num\r\n\r\n    Implement as you wish but your 'total' numpy array\r\n    has to return all the results \r\n    \"\"\"\r\n\r\n    assert(len(x)==len(y))\r\n    total  = np.zeros(len(num))\r\n\r\n    #place your code here!!!!!!!!!!!!!!!!!!!!!!!!!\r\n    for i in range(len(num)):\r\n        total[i] = lagPol(num[i], x, y)\r\n\r\n    return total\r\n\r\ndef lagPol(xi, x, y):\r\n    res = 0\r\n    for i in range(len(x)):\r\n        res += y[i]*lagCoeff(xi, i, x)\r\n    return res\r\n\r\ndef lagCoeff(xi, i, x):\r\n    res = 1\r\n    for j in range(len(x)):\r\n        if(j != i):\r\n            res *= (xi-x[j])/(x[i]-x[j])\r\n    return res\r\n    \r\ndata_x = np.array([-3.,-2.,-1.,0.,1.,3.,4.])\r\ndata_y = np.array([-60.,-80.,6.,1.,45.,30.,16.])\r\n# data_x = np.array([10.,15.,20.,22.5])\r\n# data_y = np.array([227.4,362.78,517.35,602.97])\r\n\r\n#generating 50 points from -3 to 4 in order to create a smooth line\r\nX = np.linspace(-3, 4, 50, endpoint=True)\r\nF = lag(data_x, data_y, X)\r\nprint(F)\r\nplt.plot(X,F)\r\nplt.plot(data_x, data_y, 'ro')\r\nplt.show()", "meta": {"hexsha": "f2b6ac8d6faa59f815d8ebd0430376766ffb44d6", "size": 1210, "ext": "py", "lang": "Python", "max_stars_repo_path": "lagrange.py", "max_stars_repo_name": "sheikhmishar/Numerical-Analysis-Python", "max_stars_repo_head_hexsha": "03a737ba38b372fb52ad773f52cd029f7da2b307", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lagrange.py", "max_issues_repo_name": "sheikhmishar/Numerical-Analysis-Python", "max_issues_repo_head_hexsha": "03a737ba38b372fb52ad773f52cd029f7da2b307", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lagrange.py", "max_forks_repo_name": "sheikhmishar/Numerical-Analysis-Python", "max_forks_repo_head_hexsha": "03a737ba38b372fb52ad773f52cd029f7da2b307", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3043478261, "max_line_length": 71, "alphanum_fraction": 0.5520661157, "include": true, "reason": "import numpy", "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102514755852, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.8504955985035776}}
{"text": "from numpy import array, sqrt, zeros, set_printoptions\n\ndef cholesky(A,b):\n    # Lower triangular matrix\n    el = zeros((3,3))\n    el[0,0] = sqrt(A[0,0])\n    el[1,0] = A[1,0] / el[0,0]\n    el[1,1] = sqrt(A[1,1] - el[1,0]**2)\n    el[2,0] = A[2,0] / el[0,0]\n    el[2,1] = (A[2,1] - el[2,0] * el[1,0])/el[1,1]\n    el[2,2] = sqrt(A[2,2] - el[2,0]**2 - el[2,1]**2)\n    # Forward substitution for y\n    y = zeros((3))\n    y[0] = b[0] / el[0,0]\n    y[1] = (b[1] - el[1,0] * y[0]) / el[1,1]\n    y[2] = (b[2] - el[2,0] * y[0] - el[2,1] * y[1]) / el[2,2]\n    # Backward substitution for x\n    x = zeros((3))\n    elT = el.T\n    x[2] = y[2] / elT[2,2] \n    x[1] = (y[1] - elT[1,2] * x[2]) / elT[1,1]\n    x[0] = (y[0] - elT[0,1] * x[1] - elT[0,2] * x[2]) / elT[0,0]   \n    return el, y, x\n\n# Input parameters to choesky(A,b) function\nA = array([[5,-1,1],[-1,3,-1],[1,-1,4]])\nb = array([6,2,11])\nel, y, xc = cholesky(A,b)\n\nset_printoptions(precision = 4)\nprint(\"L = \", el)\nprint(\"y = \", y)\nprint(\"x1 = %8.4f \" % xc[0])\nprint(\"x2 = %8.4f \" % xc[1])\nprint(\"x3 = %8.4f \" % xc[2])\n", "meta": {"hexsha": "37cf5a7d06234c11c38223df538eb57888c12fda", "size": 1063, "ext": "py", "lang": "Python", "max_stars_repo_path": "19_4.py", "max_stars_repo_name": "rursvd/pynumerical2", "max_stars_repo_head_hexsha": "4b2d33125b64a39099ac8eddef885e0ea11b237d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "19_4.py", "max_issues_repo_name": "rursvd/pynumerical2", "max_issues_repo_head_hexsha": "4b2d33125b64a39099ac8eddef885e0ea11b237d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "19_4.py", "max_forks_repo_name": "rursvd/pynumerical2", "max_forks_repo_head_hexsha": "4b2d33125b64a39099ac8eddef885e0ea11b237d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-03T01:34:19.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-03T01:34:19.000Z", "avg_line_length": 29.5277777778, "max_line_length": 67, "alphanum_fraction": 0.4684854186, "include": true, "reason": "from numpy", "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102571131691, "lm_q2_score": 0.8791467580102418, "lm_q1q2_score": 0.850495591206897}}
{"text": "import numpy as np\nimport time\n\n#----- normal distribution\n\ndef model_prob(_x, _theta):\n    #-- parameters\n    _mu = _theta[0]\n    _sigma_sq = _theta[1]\n    #-- probability\n    _p = np.exp(-(_x - _mu) ** 2 / (2 * _sigma_sq)) / np.sqrt(2 * np.pi * _sigma_sq)\n    #print(_p)\n    return _p\n\ndef max_likelihood_est(_x):\n    _mu = np.mean(_x)\n    _sigma_sq = np.var(_x)\n    _theta = [_mu, _sigma_sq]\n    #print(_theta)\n    return _theta\n\n#-----\n\ndef likelihood(_x, _theta):\n    _l = np.sum(np.log(model_prob(_x, _theta)))\n    #print(_l)\n    return _l\n\ndef bootstrap_sample(_x):\n    _n = _x.size\n    _ids = np.random.randint(0, _n, _n)\n    #print(_ids)\n    _x_ast = _x[_ids]\n    #print(_x_ast)\n    return _x_ast\n\ndef EIC_bias(_x, _B):\n    _D_ast = np.zeros(_B)\n    for i in range(_B):\n        _x_ast = bootstrap_sample(_x)\n        _theta_ast = max_likelihood_est(_x_ast)\n        _D_ast[i] = likelihood(_x_ast, _theta_ast) - likelihood(_x, _theta_ast)\n        #print(_D_ast[i])\n    #print(_D_ast)\n\n    _b_b = np.mean(_D_ast)\n    #print(_b_b)\n    return _b_b\n\ndef EIC_bias2(_x, _B):\n    _D_ast = np.zeros(_B)\n    for i in range(_B):\n        _x_ast = bootstrap_sample(_x)\n        _theta_ast = max_likelihood_est(_x_ast)\n        _eic = EIC_bias(_x_ast, _B)\n        _D_ast[i] = likelihood(_x_ast, _theta_ast) - _eic - likelihood(_x, _theta_ast)\n    _b_2nd = np.mean(_D_ast)\n    return _b_2nd\n\n\n#-----\n\n\nif __name__ == '__main__':\n\n    T = 100 #10000\n\n    n = 25 #25, 100, 400\n    B = 100 #1000\n\n    t_eic = np.zeros(T)\n    t_eic_2nd = np.zeros(T)\n\n    prv_ut = time.time()\n    for t in range(T):\n        ut = time.time()\n        if ut - prv_ut > 5.0:\n            prv_ut = ut\n            print(\"---\", t)\n        \n        #-- samples from true distribution\n        x = np.random.normal(0.0, 1.0, n)\n        #print(x)\n\n        t_eic[t] = EIC_bias(x, B)\n        t_eic_2nd[t] = EIC_bias2(x, B) + t_eic[t]\n        #print(t_eic[t])\n        #print(t_eic_2nd[t])\n\n    print(\"mean EIC bias:\", np.mean(t_eic))\n    print(\"mean EIC_2nd bias:\", np.mean(t_eic_2nd))\n\n", "meta": {"hexsha": "57d0255282c351b8cf55f291dc4a3c6b24bdea22", "size": 2041, "ext": "py", "lang": "Python", "max_stars_repo_path": "sandbox/IC/eic_ex2-1.py", "max_stars_repo_name": "convexbrain/studynote", "max_stars_repo_head_hexsha": "a2b1b53474eee1a5a1de58fc682c100ae19f2633", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-04-23T14:38:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T16:57:35.000Z", "max_issues_repo_path": "sandbox/IC/eic_ex2-1.py", "max_issues_repo_name": "convexbrain/studynote", "max_issues_repo_head_hexsha": "a2b1b53474eee1a5a1de58fc682c100ae19f2633", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-11-04T15:19:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-13T12:27:15.000Z", "max_forks_repo_path": "sandbox/IC/eic_ex2-1.py", "max_forks_repo_name": "convexbrain/studynotes", "max_forks_repo_head_hexsha": "b562c8ce3c21cda389ae4973452e1b7c0f46a67d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9462365591, "max_line_length": 86, "alphanum_fraction": 0.5732484076, "include": true, "reason": "import numpy", "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96741025335478, "lm_q2_score": 0.8791467580102418, "lm_q1q2_score": 0.8504955879027215}}
{"text": "import numpy as np\r\n\r\nl1 = np.array([4, 1, 9, 3])\r\nl2 = np.array([1, 6, 3, 0])\r\n\r\n#-------------------------------------------------------------\r\n\r\n# Rounding Decimals\r\n# There are primarily five ways of rounding off decimals in NumPy:\r\n\r\n# # truncation\r\n# arr = np.trunc([76.6754, -13.435])\r\n# print(arr)\r\n\r\n# # fix\r\n# arr = np.fix([76.6754, -13.435])\r\n# print(arr)\r\n\r\n# # rounding\r\n# arr = np.around(76.6754)\r\n# print(arr)\r\n\r\n# arr = np.around(76.6754, 2)\r\n# print(arr)\r\n\r\n# # floor\r\n# arr = np.floor([76.265, -13.435])\r\n# print(arr)\r\n\r\n# # ceil\r\n# arr = np.ceil([76.265, -13.435])\r\n# print(arr)\r\n\r\n#-------------------------------------------------------------\r\n# LOGS\r\n\r\narr = np.arange(1, 10)\r\nprint(arr)\r\nprint(np.log2(arr))\r\nprint(np.log10(arr))\r\nprint(np.log(arr))  # log to the base e\r\n#-------------------------------------------------------------\r\n\r\n# Addition is done between two arguments whereas summation happens over n elements.\r\n# Summations\r\na1 = np.sum([l1,l2])\r\nprint(a1)\r\n\r\n# NumPy will sum the numbers in each array.\r\na2 = np.sum([l1,l2], axis = 1)\r\nprint(a2)\r\n\r\n# cummulative summation\r\na3 = np.cumsum(l1)\r\nprint(a3)\r\n\r\n# Products\r\na1 = np.prod([l1,l2])\r\nprint(a1)\r\n\r\n# NumPy will return the product of each array.\r\na2 = np.prod([l1,l2], axis = 1)\r\nprint(a2)\r\n\r\n# cummulative product\r\na3 = np.cumprod(l1)\r\nprint(a3)\r\n\r\n#Difference\r\n\r\n# subtracting two successive elements.\r\na1 = np.diff(l1)\r\nprint(a1)\r\n\r\n# Compute discrete difference of the following array twice\r\na2 = np.diff(l1, n=2)\r\nprint(a2)\r\n\r\n# Set Operations\r\n\r\na1 = np.array([2,3,5,2,1,2,3,1,5,5,3])\r\n\r\nb = np.unique(a1)\r\nprint(b)\r\n\r\na2 = np.union1d(l1,l2)\r\nprint(a2)\r\n\r\na3 = np.intersect1d(l1,l2)\r\nprint(a3)\r\n\r\na4= np.setdiff1d(l1,l2)\r\na5= np.setdiff1d(l2,l1)\r\nprint(a5)\r\nprint(a4)\r\n\r\n# LCM\r\na1 = np.lcm.reduce(l1)\r\nprint(a1)\r\narr = np.array([[3, 6, 9], [2,3,5]])\r\na2 = np.lcm.reduce(arr)\r\nprint(a2)\r\n\r\n# GCD\r\na1 = np.gcd.reduce(l1)\r\nprint(a1)\r\narr = np.array([[3, 6, 9], [2,3,5]])\r\na2 = np.gcd.reduce(arr)\r\nprint(a2)", "meta": {"hexsha": "245766fef9231c8e4b9b9a5ef93d55cb7022c58a", "size": 2001, "ext": "py", "lang": "Python", "max_stars_repo_path": "Codes-B/numpy-py-files/ufunc_examples.py", "max_stars_repo_name": "sanils2002/PYTHON-CODES", "max_stars_repo_head_hexsha": "607fadc2cba4b185a5529bd101faefa08f4c3469", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Codes-B/numpy-py-files/ufunc_examples.py", "max_issues_repo_name": "sanils2002/PYTHON-CODES", "max_issues_repo_head_hexsha": "607fadc2cba4b185a5529bd101faefa08f4c3469", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Codes-B/numpy-py-files/ufunc_examples.py", "max_forks_repo_name": "sanils2002/PYTHON-CODES", "max_forks_repo_head_hexsha": "607fadc2cba4b185a5529bd101faefa08f4c3469", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3577981651, "max_line_length": 84, "alphanum_fraction": 0.5502248876, "include": true, "reason": "import numpy", "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799399736476, "lm_q2_score": 0.8824278772763472, "lm_q1q2_score": 0.8504662865924713}}
{"text": "from statistics import mean\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport random\n\n\nstyle.use('ggplot')\n\n# Algoritmo para calcular regresion lineal\n###########################\n#     _   _   __\n#     x . y - xy\n# m = ------------------\n#             __\n#      _ 2     2\n#     (x)   - x\n###########################\n#     _   __\n# b = y - mx\n#\n###########################\n#                 ^\n#  2           SE y\n# r  = 1 - --------------\n#                 _\n#              SE y\n###########################\n\n\nxs = np.array([1, 2, 3, 4, 5, 6], dtype=np.float64)\nys = np.array([4, 5, 6, 5, 6, 7], dtype=np.float64)\n\n\ndef create_dataset(hm, variance, step=2, correlation=False):\n    val = 1\n    ys = []\n    for i in range(hm):\n        y = val + random.randrange(-variance, variance)\n        ys.append(y)\n        if correlation and correlation == 'pos':\n            val += step\n        elif correlation and correlation == 'neg':\n            val -= step\n    xs = [i for i in range(len(ys))]\n\n    return np.array(xs, dtype=np.float64), np.array(ys, dtype=np.float64)\n\n\ndef squared_error(ys_orig, ys_line):\n    return sum((ys_line - ys_orig)**2)\n\n\ndef coeffiecient_of_determination(ys_orig, ys_line):\n    y_mean_line = [mean(ys_orig) for y in ys_orig]\n    squared_error_regr = squared_error(ys_orig, ys_line)\n    squared_error_y_meean = squared_error(ys_orig, y_mean_line)\n    return 1 - (squared_error_regr / squared_error_y_meean)\n\n\ndef best_fit_slope_and_intercept(xy, ys):\n    m = (((mean(xs) * mean(ys)) - mean(xs * ys)) /\n         ((mean(xs) * mean(xs)) - mean(xs * xs)))\n    b = mean(ys) - (m * mean(xs))\n\n    return m, b\n\n\nxs, ys = create_dataset(40, 10, 2, correlation=False)\n\nm, b = best_fit_slope_and_intercept(xs, ys)\n\nregression_line = [(m * x) + b for x in xs]\n\npredict_x = 8\npredict_y = (m * predict_x) + b\n\nr_squared = coeffiecient_of_determination(ys, regression_line)\nprint(r_squared)\n\nplt.scatter(xs, ys)\nplt.plot(xs, regression_line)\nplt.scatter(predict_x, predict_y, s=100, color='g')\nplt.show()\n# plt.scatter(xs, ys)\n# plt.show()\n", "meta": {"hexsha": "e15bd791a72d0f876bd602ec6c8ae4cc9ae87710", "size": 2081, "ext": "py", "lang": "Python", "max_stars_repo_path": "app2.py", "max_stars_repo_name": "javierpi/machine_learning", "max_stars_repo_head_hexsha": "55a1cb119dc6620e6b738109fff96483e9722378", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app2.py", "max_issues_repo_name": "javierpi/machine_learning", "max_issues_repo_head_hexsha": "55a1cb119dc6620e6b738109fff96483e9722378", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app2.py", "max_forks_repo_name": "javierpi/machine_learning", "max_forks_repo_head_hexsha": "55a1cb119dc6620e6b738109fff96483e9722378", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9195402299, "max_line_length": 73, "alphanum_fraction": 0.5670350793, "include": true, "reason": "import numpy", "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799462157138, "lm_q2_score": 0.8824278695464501, "lm_q1q2_score": 0.8504662846507247}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy.random import randn\nimport seaborn as sns\nsns.set()\n\nfrom linear_classification.basic_logistic_unit import sigmoid\nfrom e_commerce_example.logistic_training import cross_entropy\n\n\ndef generate_donut_data(number_of_points, dimensions, inner_radius, outer_radius):\n    # The distance from origin = R + random normal\n    # The theta angle =  Uniformly distributed from (0, 2*pi)\n\n    R1 = np.random.randn(number_of_points//2) + inner_radius\n    R2 = np.random.randn(number_of_points//2) + outer_radius\n\n    theta1 = 2 * np.pi * np.random.random(number_of_points//2)\n    theta2 = 2 * np.pi * np.random.random(number_of_points//2)\n\n    X_inner = np.concatenate( [ [R1 * np.cos(theta1)], [R1 * np.sin(theta1)] ] ).T\n    X_outer = np.concatenate( [ [R2 * np.cos(theta2)], [R2 * np.sin(theta2)] ] ).T\n\n    X = np.concatenate([ X_inner, X_outer ])\n    y = np.array([0]*(number_of_points//2) + [1]*(number_of_points//2))\n\n    plt.figure()\n    plt.scatter(X[:,0], X[:,1], c=y)\n    plt.show()\n\n    return X, y \n\ndef gradient_descent_l2_donut_problem(X, y, learning_rate=0.0001, epochs=5000, l2_norm=0.1):\n    w = np.random.randn(X.shape[1])\n    z = X.dot(w)\n    y_hat = sigmoid(z)\n\n    errors = []\n    for epoch in range(epochs):\n        error = cross_entropy(y, y_hat)\n        errors.append(error)\n        if epoch % 100 == 0:\n            print(\"Epoch {}:{}\".format(epoch, error))\n        w += learning_rate * ( X.T.dot(y - y_hat) - l2_norm * w )\n        \n        y_hat = sigmoid(X.dot(w))\n\n    plt.figure()\n    plt.plot(errors)\n    plt.title(\"Cross-entropy Loss/Iteration\")\n    plt.show()\n\n    print(\"Final w:\", w)\n    print(\"Final classification rate:\", 1 - np.abs(y - np.round(y_hat)).sum() / X.shape[0])\n\n    return w\n\nif __name__ == '__main__':\n    number_of_points = 1000\n    dimensions = 2\n    inner_radius = 5\n    outer_radius = 10\n    learning_rate=0.0001\n    epochs=5000\n    l2_norm = 0.1\n    \n    X, y = generate_donut_data(number_of_points, dimensions, inner_radius, outer_radius)\n\n    # Generate the ones + an additional column of r = sqrt(x^2 + y^2) \n    # This is the radious of a point, and makes data points linearly separable\n\n    ones = np.ones((number_of_points, 1))\n    radiuses = np.sqrt( (X*X).sum(axis=1) ).reshape(-1,1)\n    X = np.concatenate((ones, radiuses, X), axis=1)\n\n    _ = gradient_descent_l2_donut_problem(X, y, learning_rate, epochs, l2_norm)\n\n    # Classification does not appear to depend on the X and y term, but on the bias and the summed radiuses", "meta": {"hexsha": "29ed10deaa0c2ad0243c40e853cae35b8c83b7f3", "size": 2537, "ext": "py", "lang": "Python", "max_stars_repo_path": "practical_issues/donut_problem.py", "max_stars_repo_name": "AndreiRoibu/LogisticRegression", "max_stars_repo_head_hexsha": "8262e35b48069c3a3c2bcdb9711ba1f7c2ddc2c6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "practical_issues/donut_problem.py", "max_issues_repo_name": "AndreiRoibu/LogisticRegression", "max_issues_repo_head_hexsha": "8262e35b48069c3a3c2bcdb9711ba1f7c2ddc2c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practical_issues/donut_problem.py", "max_forks_repo_name": "AndreiRoibu/LogisticRegression", "max_forks_repo_head_hexsha": "8262e35b48069c3a3c2bcdb9711ba1f7c2ddc2c6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5256410256, "max_line_length": 107, "alphanum_fraction": 0.6551044541, "include": true, "reason": "import numpy,from numpy", "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543366, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.8504662765086574}}
{"text": "import numpy as np\n\ndef swap_row(mat,r1,r2):\n\ttemp = mat[r1]\n\tmat[r1] = mat[r2]\n\tmat[r2] = temp\n\t\ndef normalize(mat,i):\n\tfor j in range(i+1,len(mat)):\n\t\tfact = (mat[j][i]/mat[i][i])\n\t\tfor k in range(0,len(mat)+1):\n\t\t\tmat[j][k] -= fact*mat[i][k]\n\t\t\t \t\ndef fwd_elimination(mat):\n\tn = len(mat)\n\tfor i in range(n-1):\n\t\tif mat[i][i] == 0:\n\t\t\tswap_row(mat,i,i+1)\n\t\tnormalize(mat,i)\n\t\tm = np.array(mat)\n\t\tm = m[:,:n]\n\t\tif (np.linalg.det(m) == 0):\n\t\t\tprint (\"Singular Matrix!! No Unique solution Exists!!\")\n\t\t\treturn False\n\treturn True\n\t\ndef bwd_elimination(mat):\n\tn = len(mat)\n\tx = [0]*n\n\t\n\tfor i in range(n-1,-1,-1):\n\t\tx[i] = mat[i][n]\n\t\t\n\t\tfor j in range(i+1,n):\n\t\t\tx[i] -= mat[i][j]*x[j]\n\t\t\t\n\t\tx[i] = x[i]/mat[i][i]\n\t\t\n\tprint(\"Solutions are: \\n\\n\")\n\tprint(\"y(0.25): \",x[0],\"\\n\\n\")\n\tprint(\"y(0.5): \",x[1],\"\\n\\n\")\n\tprint(\"y(0.75): \",x[2],\"\\n\\n\")\n\ndef func(x):\n\treturn np.exp(x**2)\n\t\t \ndef main(): \n\tmat = []\n\ty0 = 0; y4 = 0;\n\th = 0.25;\n\tx = [0.25,0.5,0.75]\n\tf = []\n\tfor i in range(3):\n\t\ttemp = func(x[i])*(h**2)\n\t\tf.append(temp)\n\t\t\n\tf[0] -= y0;\n\tf[2] -= y4;\n\t  \t\n\tmat = [[-2,1,0,f[0]],[1,-2,1,f[1]],[0,1,-2,f[2]]]\n\t\n\tif(fwd_elimination(mat) == True):\n\t\tbwd_elimination(mat)\n\t\nif __name__ == '__main__':\n\tmain()\n\t\n\n", "meta": {"hexsha": "8b2874cdb28715a442d88607b5c577abdeff3f41", "size": 1208, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numerical method_practical_problems/Finite Difference.py", "max_stars_repo_name": "surya810/Numerical-method-notes", "max_stars_repo_head_hexsha": "6d9dc7aba56e3f9fb8923e3c6d271d8eefcb6fb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numerical method_practical_problems/Finite Difference.py", "max_issues_repo_name": "surya810/Numerical-method-notes", "max_issues_repo_head_hexsha": "6d9dc7aba56e3f9fb8923e3c6d271d8eefcb6fb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numerical method_practical_problems/Finite Difference.py", "max_forks_repo_name": "surya810/Numerical-method-notes", "max_forks_repo_head_hexsha": "6d9dc7aba56e3f9fb8923e3c6d271d8eefcb6fb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5072463768, "max_line_length": 58, "alphanum_fraction": 0.5198675497, "include": true, "reason": "import numpy", "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809829, "lm_q2_score": 0.8976952968970955, "lm_q1q2_score": 0.8504595072818801}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nLet d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).\nIf d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.\n\nFor example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.\n\nEvaluate the sum of all the amicable numbers under 10000.\n\nSolution commment:\nI evaluate d(n) by first prime factorizing n, taking all the possible partitions of\nthe primes and summing the product of them. Hoping this is faster for large n because\nprime factorization only needs to look at sqrt(n) numbers. Potential bottleneck is\nthe partitioning of the primes, a recursive method which is probably not very fast for\nlarge numbers of primes. Find solution for 10 000 in under 2 sec, 100 000 in under 30 sec.\n\"\"\"\nfrom numpy import prod\nfrom itertools import groupby\n\ndef partitions(arr):\n    \"\"\"Return a list of all the partitions of arr\"\"\"\n    if len(arr) == 1:\n        return [arr]\n    without = partitions(arr[:-1])\n    incl = [part + [arr[-1]] for part in without]\n    return without + incl + [[arr[-1]]]\n\ndef prodComplex(listoflists):\n    return [prod(arr) for arr in listoflists]\n\ndef primes(n):\n    primefac = []\n    d = 2\n    while d*d <= n:\n        while n % d == 0:\n            primefac.append(d)\n            n /= d\n        d += 1\n    if n > 1:\n        primefac.append(n)\n    return primefac\n\ndef unduplicate(listoflists):\n    listoflists.sort()\n    return list(k for k, _ in groupby(listoflists))\n\ndef d(n):\n    if n <= 1:\n        return 0\n    primefac = primes(n)\n    primeparts = unduplicate(partitions(primefac))\n    primeprod = prodComplex(primeparts)\n    return sum(primeprod) - n + 1\n\n\ns = 0\nseen = set()\nnum = 0\nwhile num < 10000:\n    num += 1\n    if num in seen:\n        continue\n\n    amicable = d(num)\n    if d(amicable) == num and num != amicable:\n        print \"Found pair:\", num, amicable\n        seen.add(num)\n        seen.add(amicable)\n        s += amicable + num\nprint 'sum of amicable numbers =', s\n", "meta": {"hexsha": "84dc11b74023aebfef70e2369cd14518c11613d9", "size": 2164, "ext": "py", "lang": "Python", "max_stars_repo_path": "021/21.py", "max_stars_repo_name": "bsamseth/project-euler", "max_stars_repo_head_hexsha": "60d70b117960f37411935bc18eab5bb2fca220e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "021/21.py", "max_issues_repo_name": "bsamseth/project-euler", "max_issues_repo_head_hexsha": "60d70b117960f37411935bc18eab5bb2fca220e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "021/21.py", "max_forks_repo_name": "bsamseth/project-euler", "max_forks_repo_head_hexsha": "60d70b117960f37411935bc18eab5bb2fca220e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4788732394, "max_line_length": 180, "alphanum_fraction": 0.6455637708, "include": true, "reason": "from numpy", "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.958537730841905, "lm_q2_score": 0.8872046041554922, "lm_q1q2_score": 0.850419088059696}}
{"text": "#########################################################################################\n# This is a class that collects data science \"distances methods\".\n# Distances measure similarities between features (both numeric and categorical).\n# Distances are used in a lot of fields: in Machine Learning inside methods (such as the \n# k-Means or the cosine similarity used inside the colloborative filtering tecnique).\n#########################################################################################\n\n\nimport numpy as np\n\n\nclass Distances(object):\n\n\tdef __init__(self):\n\t\tsuper().__init__()\n\n\n\tdef Euclidean(self, points_1:list, points_2:list):\n\n\t\t'''\n\t\tEuclidean distance measures distance between points in a linear space. When the space we\n\t\tare considering is high dimensional, it suffers from the curse of dimensionality.\n\n\t\tparam points_1: first point in form of [float, float]\n\t\tparam points_2: second point in form of [float, float]\n\t\t'''\n\n\t\tassert len(points_1) == len(points_2)\n\n\t\treturn ( sum( (x - y) ** 2 for x, y in zip(points_1, points_2) ) ) ** 0.5\n\n\n\tdef Manhattan(self, points_1:list, points_2:list):\n\n\t\t'''\n\t\tManhattan distance refers to the distance between two vectors if they could only move \n\t\tby following right angles. It takes its name from New York Manhattan hood where streets \n\t\tare forming almost always squre root angles against each other.\n\n\t\tpoints_1: first point in form of list\n\t\tpoints_2: second point in form of list\n\t\t'''\n\n\t\tassert len(points_1) == len(points_2)\n\n\t\treturn sum( abs(x - y) for x, y in zip(points_1, points_2) )\n\n\n\tdef Minkowski(self, p_order:float, x:list, y:list):\n\n\t\t'''\n\t\tMinkowski distance refers to the distance a metric used in Normed vector space \n\t\t(n-dimensional real space), which means that it can be used in a space where distances\n\t\tcan be represented as a vector that has a length.\n\t\tWhen p_order is equal to 1, this distance is the Mahnattan one.\n\t\tWhen p_order is equal to 2, this distance is the Euclidean one.\n\n\t\tparam x: first point in form of [float, float]\n\t\tparam y: second point in form of [float, float]\n\t\tparam p_order: order of distance magnitude\n\t\t'''\n\n\t\tassert len(x) == len(y)\n\n\t\treturn ( sum( [abs(i - j) ** p_order for i, j in zip(x, y)] ) ) ** (1 / p_order)\n\n\n\tdef Hamming(self, x:str, y:str):\n\n\t\t'''\n\t\tHamming distance (used for categorical features such as strings) measures the distance in terms of different\n\t\tvalues between two vectors. It is tipically used to measure the difference between two strings.\n\n\t\tparam x: first object (i.e. \"Andrea\")\n\t\tparam y: second point object (i.e. \"Annrea\")\n\t\t'''\n\n\t\tassert len(x) == len(y)\n\n\t\tdistance = 0\n\t\tlength   = len(x)\n\n\t\tfor i in range(length):\n\t\t\tif x[i] != y[i]:\n\t\t\t\tdistance +=1\n\n\t\treturn (length, distance)\n\n\n\tdef CosineSimilarity(self, x:list, y:list):\n\n\t\t'''\n\t\tCosine similarity measure the distance between two vectors getting the cosine among them.\n\t\tIf the cosine is close to one, these two vectors are equal. If the cosine is almost equal\n\t\tto minus one, these two vectors are dissimilar.\n\t\tin order to be compared the vector must have same length.\n\n\t\tparam x: is it the first vector in form [1,2,4,5]\n\t\tparam y: is it the first vector in form [1,2,4,7]\n\t\t'''\n\n\t\tdot    = np.dot( x, y)\n\t\tnorm_x = ( sum( [ k**2 for k in x ] ) ) ** 0.5\n\t\tnorm_y = ( sum( [ k**2 for k in y ] ) ) ** 0.5\n\n\t\treturn dot / (norm_x * norm_y)\n\n\n\n", "meta": {"hexsha": "04ec4e89b4d38c2d7a22f7ffdafbcbffa116671e", "size": 3370, "ext": "py", "lang": "Python", "max_stars_repo_path": "DSToolkit/statistical/distances.py", "max_stars_repo_name": "AndreaFerrante/DSToolkit", "max_stars_repo_head_hexsha": "6f527cb4c19127cecd74bb682330236aa4e41839", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DSToolkit/statistical/distances.py", "max_issues_repo_name": "AndreaFerrante/DSToolkit", "max_issues_repo_head_hexsha": "6f527cb4c19127cecd74bb682330236aa4e41839", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DSToolkit/statistical/distances.py", "max_forks_repo_name": "AndreaFerrante/DSToolkit", "max_forks_repo_head_hexsha": "6f527cb4c19127cecd74bb682330236aa4e41839", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6363636364, "max_line_length": 110, "alphanum_fraction": 0.6605341246, "include": true, "reason": "import numpy", "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885904, "lm_q2_score": 0.8872045877523147, "lm_q1q2_score": 0.8504190691841146}}
{"text": "'''\nSimulate MA(1) Time Series\n\nYou will simulate and plot a few MA(1) time series, each with a different parameter, θ\nθ\n, using the arima_process module in statsmodels, just as you did in the last chapter for AR(1) models. You will look at an MA(1) model with a large positive θ\nθ\n and a large negative θ\nθ\n.\n\nAs in the last chapter, when inputting the coefficients, you must include the zero-lag coefficient of 1, but unlike the last chapter on AR models, the sign of the MA coefficients is what we would expect. For example, for an MA(1) process with θ=−0.9\nθ\n=\n−\n0.9\n, the array representing the MA parameters would be ma = np.array([1, -0.9])\n\nINSTRUCTIONS\n100XP\nImport the class ArmaProcess in the arima_process module.\nPlot the simulated MA(1) processes\nLet ma1 represent an array of the AR parameters [1, θ\nθ\n] as explained above. The AR parmater array will contain just the lag-zero coeffienct of one.\nWith parameters ar1 and ma1, create an instance of the class ArmaProcess(ar,ma) called MA_object1.\nSimulate 1000 data points from the object you just created, MA_object1, using the method .generate_sample(). Plot the simulated data in a subplot.\nRepeat for the other MA parameter.\n'''\n# import the module for simulating data\nfrom statsmodels.tsa.arima_process import ArmaProcess\n\n# Plot 1: MA parameter = -0.9\nplt.subplot(2,1,1)\nar1 = np.array([1])\nma1 = np.array([1, -0.9])\nMA_object1 = ArmaProcess(ar1, ma1)\nsimulated_data_1 = MA_object1.generate_sample(nsample=1000)\nplt.plot(simulated_data_1)\n\n# Plot 2: MA parameter = +0.9\nplt.subplot(2,1,2)\nar2 = np.array([1])\nma2 = np.array([1, 0.9])\nMA_object2 = ArmaProcess(ar2, ma2)\nsimulated_data_2 = MA_object2.generate_sample(nsample=1000)\nplt.plot(simulated_data_2)\n\nplt.show()\n", "meta": {"hexsha": "f2aa3d00aa9bcbee001ef9d525ac2449f9cae33b", "size": 1737, "ext": "py", "lang": "Python", "max_stars_repo_path": "datacamp-master/22-introduction-to-time-series-analysis-in-python/04-moving-average-ma-and-arma-models/01-simulate-ma(1)-time-series.py", "max_stars_repo_name": "vitthal10/datacamp", "max_stars_repo_head_hexsha": "522d2b192656f7f6563bf6fc33471b048f1cf029", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-11T01:32:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T01:32:36.000Z", "max_issues_repo_path": "22-introduction-to-time-series-analysis-in-python/04-moving-average-ma-and-arma-models/01-simulate-ma(1)-time-series.py", "max_issues_repo_name": "AndreasFerox/DataCamp", "max_issues_repo_head_hexsha": "41525d7252f574111f4929158da1498ee1e73a84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "22-introduction-to-time-series-analysis-in-python/04-moving-average-ma-and-arma-models/01-simulate-ma(1)-time-series.py", "max_forks_repo_name": "AndreasFerox/DataCamp", "max_forks_repo_head_hexsha": "41525d7252f574111f4929158da1498ee1e73a84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-08T05:09:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-08T05:09:52.000Z", "avg_line_length": 34.74, "max_line_length": 249, "alphanum_fraction": 0.7593552101, "include": true, "reason": "from statsmodels", "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012640659995, "lm_q2_score": 0.8991213799730774, "lm_q1q2_score": 0.8503901377273024}}
{"text": "def make_design_matrix(X, M):\n    \"\"\" Return a design matrix.\n    \n    Args:\n        X -- N -- float: Inputs for training or testing.\n        M -- 1 -- int: # of features to use.\n    \n    Returns:\n        Phi -- N x M -- float: Design matrix.\n    \"\"\"\n    assert M > 0 and type(M) == int, \"M should be a positive integer.\"\n    \n    from numpy import zeros\n    \n    N = len(X)\n    Phi = zeros((N, M))\n    for col in range(M):\n        Phi[:, col] = X ** col\n    \n    return Phi\n\ndef CFS_LR(Phi, y_train):\n    \"\"\" Return weights of linear regression using closed form solution.\n    \n    Args:\n        Phi -- N x M -- float: Design matrix.\n        y_train -- N -- float: Labels for training.\n    \n    Returns:\n        w -- M -- float: Updated weights.\n    \"\"\"\n    from numpy.linalg import pinv\n    \n    # Calculate closed form solution.\n    w = pinv(Phi.T @ Phi) @ (Phi.T @ y_train)\n    \n    return w\n\ndef make_R(query, x_train, tau):\n    \"\"\" Return R for locally weighted linear regression.\n    \n    Args:\n        query -- 1 -- float: Input that I want to focus on.\n        x_train -- N -- float:\n            Entire train input to determine the local weight of\n            each train input with respect to the current query.\n        tau -- 1 -- float: Bandwidth parameter.\n    \n    Returns:\n        R -- -- float: Local weights for weighted linear regression.\n    \"\"\"\n    from numpy import zeros, exp, diag\n    R = zeros((len(x_train), len(x_train)))\n    \n    # Calculate each element of R using give formula and vectorize them.\n    R = [exp(- (query - x_train[idx]) ** 2 / (2 * tau ** 2)) for idx in range(len(x_train))]\n    \n    # Make a diagonal matrix using the vector.\n    R = diag(R)\n    \n    return R\n\ndef CFS_LW(Phi, R, y_train):\n    \"\"\" Return weights of locally weighted linear regression \n        using closed form solution.\n    \n    Args:\n        Phi -- N x M -- float: Design matrix.\n        R: -- N x N -- float: Local weights for a given query.\n        y_train -- N -- float: Labels for training.\n    \n    Returns:\n        w -- M -- float: Updated weights.\n    \"\"\"\n    from numpy.linalg import pinv\n    \n    # Calculated the closed form solution for locally weighted LR.\n    w = pinv(Phi.T @ R @ Phi) @ (Phi.T @ (R @ y_train))\n    \n    return w\n\ndef main():\n    \"\"\" Run linear regression with various local weight parameters.\n    \"\"\"\n    from numpy import load, linspace\n    from matplotlib.pyplot import subplots, savefig, show\n    \n    # load data.\n    x_train = load(\"data/q2x.npy\")\n    y_train = load(\"data/q2y.npy\")\n    \n    # Run unweighted linear regression.\n    # Find closed form solution for unweighted linear regression.\n    Phi = make_design_matrix(x_train, 2)\n    w = CFS_LR(Phi, y_train)\n    y_result = w @ Phi.T\n    \n    # Plot the data and the line, and save as file.\n    fig, ax = subplots()\n    ax.title.set_text(\"Linear Regression without Local Weighting\\ny = {:.3f} + {:.3f}x\".format(w[0], w[1]))\n    ax.set_xlabel(\"x\")\n    ax.set_ylabel(\"y\")\n    ax.scatter(x_train, y_train, label=\"Data\", color=\"black\")\n    ax.plot(x_train, y_result, label=\"Unweighted LR Line\")\n    ax.legend()\n    savefig(\"q2-d-i.png\")\n    \n    # Run locally weighted linear regression with tau = 0.8.\n    # Prepare queries.\n    xmin, xmax = min(x_train), max(x_train)\n    xran = xmax - xmin\n    queries = linspace(xmin, xmax, num=50)\n    \n    # Iterate over each query.\n    y_result = []\n    for query in queries:\n        # Find closed for solution for locally weighted linear regression.\n        R = make_R(query, x_train, 0.8)\n        w = CFS_LW(Phi, R, y_train)\n        y_result.append(w[0] + w[1] * query)\n    \n    # Plot the curve and save as file.\n    ax.title.set_text(\"Local Weighting Linear Regression\")\n    ax.plot(queries, y_result, label=\"Locally Weighted LR Curve, tau=0.8\")\n    ax.legend()\n    savefig(\"q2-d-ii.png\")\n    \n    # Run locally weighted linear regression using various taus.\n    # Nest another iteration over four tau = 0.1, 0.3, 2, 10.\n    taus = [0.1, 0.3, 2, 10]\n    for tau in taus:\n        y_result = []\n        for query in queries:\n            # Find closed for solution for locally weighted linear regression.\n            R = make_R(query, x_train, tau)\n            w = CFS_LW(Phi, R, y_train)\n            y_result.append(w[0] + w[1] * query)\n        \n        # Plot the curve and save as file.\n        ax.plot(queries, y_result, label=\"Locally Weighted LR Curve, tau={}\".format(tau))\n    ax.title.set_text(\"Local Weighted Linear Regression\")\n    ax.legend()\n    savefig(\"q2-d-iii.png\")\n    show()\n\nif __name__ == \"__main__\":\n    main()", "meta": {"hexsha": "b63c95a1f69eaef088cb279b80810f2ddba7345d", "size": 4572, "ext": "py", "lang": "Python", "max_stars_repo_path": "1_Linear_regression/q2_Locally_weighted_linear_regression.py", "max_stars_repo_name": "discrim/Machine-Learning-Basic-Exercise", "max_stars_repo_head_hexsha": "80a81f8995e593110a03b07f46da0180fe5a5fec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1_Linear_regression/q2_Locally_weighted_linear_regression.py", "max_issues_repo_name": "discrim/Machine-Learning-Basic-Exercise", "max_issues_repo_head_hexsha": "80a81f8995e593110a03b07f46da0180fe5a5fec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1_Linear_regression/q2_Locally_weighted_linear_regression.py", "max_forks_repo_name": "discrim/Machine-Learning-Basic-Exercise", "max_forks_repo_head_hexsha": "80a81f8995e593110a03b07f46da0180fe5a5fec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1020408163, "max_line_length": 107, "alphanum_fraction": 0.5933945757, "include": true, "reason": "from numpy", "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322215, "lm_q2_score": 0.8991213711878918, "lm_q1q2_score": 0.850390137659809}}
{"text": "\"\"\"\nExample: Cafe Java Demand Distribution and Process Generator.\n\nThis example develops a discrete process generator for coffee demand data\nobserved in Cafe Java.\n\n@author: Paul T. Grogan <pgrogan@stevens.edu>\n\"\"\"\n\n# import the python3 behavior for importing, division, and printing in python2\nfrom __future__ import absolute_import, division, print_function\n\n# import the numpy package and refer to it as `np`\n# see http://docs.scipy.org/doc/numpy/reference/ for documentation\nimport numpy as np\n\n# import the matplotlib pyplot package and refer to it as `plt`\n# see http://matplotlib.org/api/pyplot_api.html for documentation\nimport matplotlib.pyplot as plt\n\n# create a numpy array with the demand sizes\ndemands = np.array([0, 1, 2, 3])\nlabels = [\"None\", \"Small\", \"Medium\", \"Large\"]\nprint(\"demands = {}\".format(demands))\n\n# create a numpy array with the observed frequencies\nfrequency = np.array([8, 10, 22, 10])\n\n# the probability mass function is the number of demands (frequency) divided\n# by the total number of demands (sum of all frequency)\npmf = frequency/np.sum(frequency)\nprint(\"pmf = {}\".format(pmf))\n\n# create a new figure for a bar plot using the demand indices, pmf values, \n# desired bar width, and color\nplt.figure()\nbar_width = 0.5\nplt.bar(demands, pmf, bar_width, align='center', color='b')\nplt.ylabel('p(x)')\nplt.ylim([0,1])\nplt.xlabel('Coffee Demand (x)')\nplt.title('PMF for Cafe Java Demand')\nplt.xticks(demands, labels)\n\n# the cumulative distribution function is the cumulative sum of the PDF\ncdf = np.cumsum(pmf)\nprint(\"cdf = {}\".format(cdf))\n\n# create a new figure for a step plot using the demand indices, cdf values,\n# desired format (solid red line, -r), and option for post-steps\nplt.figure()\nplt.step(demands, cdf, '-r', where='post')\nplt.ylabel('F(x)')\nplt.ylim([0,1])\nplt.xlabel('Coffee Demand (x)')\nplt.title('CDF for Cafe Java Demand')\nplt.xticks(demands, labels)\n\n# define a function to generate demands following the inverse transform method\ndef generate_demand_ivt():\n    \"\"\"Generates a demand following the inverse transform method.\n    \n    Returns:\n        demand (int): the size of coffee demanded    \n    \"\"\"\n    r = np.random.rand()\n    \n    # check the first cdf entry (index 0) \n    if r <= cdf[0]:\n        return demands[0]\n    # check the second cdf entry (index 1)\n    elif r <= cdf[1]:\n        return demands[1]\n    # check the third cdf entry (index 2)\n    elif r <= cdf[2]:\n        return demands[2]\n    # otherwise no need to check, it's the final CDF entry (index 3)\n    else:\n        return demands[3]\n        \n    \"\"\"\n    note: the code above could be replaced with the following for \n    loop which iterates over each array index i in demands\n    \n    for i in range(len(demands)):\n        if r <= cdf[i]:\n            return demands[i]\n    \"\"\"\n\n# define number of samples\nnum_samples = 1000\n\n# fill the samples arrays with samples from the generators\nsamples_ivt = [generate_demand_ivt() for i in range(num_samples)]\n    \n# count the number of each demand: use a generator expression to count the\n# number of samples which match each demand level i\ncounts_ivt = np.array([sum(samples_ivt==i) for i in demands])\nfrequency_ivt = counts_ivt/np.sum(counts_ivt)\n\n# create a new figure recreating the PMF bar plot\nplt.figure()\nbar_width = 0.3\nplt.bar(demands, pmf, bar_width, align='center', color='k', label='Observed')\n# also display the generated frequency (offset bars by bar_width)\nplt.bar(demands+bar_width, frequency_ivt, \n        bar_width, color='b', label='Generated (IVT)')\nplt.ylabel('p(x)')\nplt.ylim([0,1])\nplt.xlabel('Coffee Demand (x)')\nplt.title('Cafe Java Demand Process Generator Results (n={})'.format(num_samples))\nplt.xticks(demands + bar_width, labels)\nplt.legend()", "meta": {"hexsha": "e6c9ef00bf481398a62d44fe2dde45d1731d78f5", "size": 3738, "ext": "py", "lang": "Python", "max_stars_repo_path": "previous/week3/demandGeneratorIVT.py", "max_stars_repo_name": "code-lab-org/sys611", "max_stars_repo_head_hexsha": "3b8c46788dee629a9f2d6b7f84373e041b918ff0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-07T03:52:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T18:16:16.000Z", "max_issues_repo_path": "previous/week3/demandGeneratorIVT.py", "max_issues_repo_name": "code-lab-org/sys611", "max_issues_repo_head_hexsha": "3b8c46788dee629a9f2d6b7f84373e041b918ff0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "previous/week3/demandGeneratorIVT.py", "max_forks_repo_name": "code-lab-org/sys611", "max_forks_repo_head_hexsha": "3b8c46788dee629a9f2d6b7f84373e041b918ff0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-02-12T01:57:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T18:05:27.000Z", "avg_line_length": 33.0796460177, "max_line_length": 82, "alphanum_fraction": 0.7046548957, "include": true, "reason": "import numpy", "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.8991213718636754, "lm_q1q2_score": 0.850390134178193}}
{"text": "import math\n\nimport numpy as np\nimport pandas as pd\nfrom pandas import Timestamp\nfrom scipy import interpolate\n\n__all__ = [\n    \"compute_days_between\",\n    \"treasury_bill_price\",\n    \"bond_equivalent_yield\",\n    \"discount_factor_from\",\n    \"spot_rate_from\",\n    \"forward_rate_from\",\n]\n\n\ndef compute_days_between(start_date, end_date):\n    \"\"\"Computes number of days between dates\"\"\"\n    time_delta = Timestamp(end_date) - Timestamp(start_date)\n    return time_delta.days\n\n\ndef treasury_bill_price(discount_yield, days_to_maturity):\n    \"\"\"Computes price ot treasury bill\"\"\"\n    return 100 * (1 - days_to_maturity / 360 * discount_yield)\n\n\ndef bond_equivalent_yield(discount_yield, days_to_maturity):\n    \"\"\"Computes bond equivalent yield from treasury bill discount yield\"\"\"\n    return 365 * discount_yield / (360 - discount_yield * days_to_maturity)\n\n\ndef is_valid_freq(freq):\n    return math.isfinite(freq) and isinstance(freq, int) and freq > 0\n\n\ndef discount_factor_from(spot_rate, term, freq=math.inf):\n    \"\"\"Computes discount factor from spot rate\n\n    The  discount factor from a spot rate given term and compounding frequency.\n\n    Parameters\n    ----------\n    spot_rate : float\n        The spot rate\n    term : float\n        The term or time to maturity\n    freq : int or math.inf, optional\n        The compounding frequency, default is math.inf which results in continuous compounding rates.\n\n    Returns\n    -------\n    float\n        The discount factor determined the spot rate.\n\n    Raises\n    ------\n    ValueError\n        If freq is not math.inf of positive int\n\n    \"\"\"\n    if freq == math.inf:\n        return math.exp(-spot_rate * term)\n    elif is_valid_freq(freq):\n        return math.pow(1 + spot_rate / freq, -freq * term)\n    else:\n        raise ValueError(\"Freq must be math.inf or positive int\")\n\n\ndef spot_rate_from(discount_factor, term, freq=math.inf):\n    \"\"\"Computes spot rate from discount factor\n\n    The spot rate from the discount factor given term and compounding frequency.\n\n    Parameters\n    ----------\n    discount_factor : float or pandas.Series\n        The discount factor to determine the spot rate.\n    term : float\n        The term or time to maturity\n    freq : int or math.inf, optional\n        The compounding frequency, default is math.inf which results in continuous compounding rates.\n\n    Returns\n    -------\n    float or pandas.Series\n        The spot rate\n\n    Raises\n    ------\n    ValueError\n        If freq is not math.inf of positive int\n\n    \"\"\"\n    if freq == math.inf:\n        package = math\n        if isinstance(discount_factor, pd.Series):\n            package = np\n        return -1 / term * package.log(discount_factor)\n    elif is_valid_freq(freq):\n        return freq * (math.pow(discount_factor, -1 / (freq * term)) - 1)\n    else:\n        raise ValueError(\"Freq must be math.inf or positive int\")\n\n\ndef forward_rate_from(rate_1, term_1, rate_2, term_2, freq=math.inf):\n    \"\"\"Computes forward rate from pair of spot rates\n\n    The forward rate between pair of spot rates given terms and compounding frequency.\n\n    Parameters\n    ----------\n    rate_1 : float\n       The first spot rate\n    term_1 : float\n        The first term or time to maturity\n    rate_2 : float\n       The second spot rate\n    term_2 : float\n        The second term or time to maturity\n    freq : int or math.inf, optional\n        The compounding frequency, default is math.inf which results in continuous compounding rates.\n\n    Returns\n    -------\n    float, float\n        The term and rate of the forward\n\n    Raises\n    ------\n    ValueError\n        If freq is not math.inf of positive int\n\n    \"\"\"\n    term = term_2 - term_1\n    if freq == math.inf:\n        return term, (rate_2 * term_2 - rate_1 * term_1) / term\n    elif is_valid_freq(freq):\n        df_1 = discount_factor_from(rate_1, term_1, freq)\n        df_2 = discount_factor_from(rate_2, term_2, freq)\n        forward_df = df_2 / df_1\n        return term, spot_rate_from(discount_factor=forward_df, term=term, freq=freq)\n    else:\n        raise ValueError(\"Freq must be math.inf or positive int\")\n\n\ndef interp_rates(rates, maturities=None, column=\"Rate\"):\n    assert \"Maturity\" in rates.columns\n    assert column in rates.columns\n    sorted_rates = rates.sort_values(\"Maturity\")\n\n    interpolator = interpolate.Akima1DInterpolator(\n        sorted_rates[\"Maturity\"], sorted_rates[column]\n    )\n    if maturities is None:\n        maturities = np.arange(0.25, 7.25, 0.25)\n    interpolated_rates = interpolator(maturities)\n\n    index = pd.Series(data=maturities, name=\"Maturity\")\n    interpolated_rates = pd.Series(\n        data=interpolated_rates, name=f\"Interpolated {column}\", index=index\n    )\n    interpolated_rates = pd.DataFrame(interpolated_rates).reset_index()\n\n    return interpolated_rates\n\n\ndef add_libor_curve(rates, first_swap_maturity, delta=0.25):\n    assert \"Maturity\" in rates.columns\n    assert \"Interpolated Rate\" in rates.columns\n    zeros = np.zeros((len(rates),))\n\n    idx = rates.index < first_swap_maturity\n    zeros[idx] = 1 / (\n        1 + rates.loc[idx, \"Maturity\"] * rates.loc[idx, \"Interpolated Rate\"]\n    )\n    for i in range(sum(idx), len(zeros)):\n        rate = rates[\"Interpolated Rate\"][i]\n        zeros[i] = (1 - rate * delta * np.sum(zeros[:i])) / (1 + rate * delta)\n\n    rates[\"Zero\"] = zeros\n    rates[\"Spot Rate\"] = -1 / rates[\"Maturity\"] * np.log(zeros)\n\n    return rates\n\n\ndef add_short_rates(rates, time_step):\n    assert \"Maturity\" in rates.columns\n    assert \"Zero\" in rates.columns\n    rates[\"Short Rate\"] = 1 / time_step * (1 / rates[\"Zero\"] - 1)\n\n\ndef add_forward_discounts(rates, start_maturity=1):\n    assert \"Maturity\" in rates.columns\n    assert \"Zero\" in rates.columns\n    rates[\"Forward Discount\"] = rates[\"Zero\"] / rates[\"Zero\"].shift(start_maturity)\n    return rates\n\n\ndef add_forward_rates(rates):\n    assert \"Maturity\" in rates.columns\n    assert \"Forward Discount\" in rates.columns\n    rates[\"Forward Rate\"] = (1 / rates[\"Forward Discount\"] - 1) / rates[\n        \"Maturity\"\n    ].diff()\n    return rates\n\n\ndef add_forward_swap_discounts(rates, start_period=1):\n    assert \"Maturity\" in rates.columns\n    assert \"Zero\" in rates.columns\n    rates[\"Forward Swap Discount\"] = (\n        rates[\"Zero\"] / rates[\"Zero\"].values[start_period - 1]\n    )\n    rates.loc[rates.index < start_period, \"Forward Swap Discount\"] = np.nan\n    return rates\n\n\ndef add_swap_rates(rates):\n    assert \"Zero\" in rates.columns\n    assert \"Maturity\" in rates.columns\n    rates[\"Swap Rate\"] = (\n        (1 - rates[\"Zero\"]) / rates[\"Zero\"].cumsum() / rates[\"Maturity\"].diff()\n    )\n    return rates\n", "meta": {"hexsha": "c67ee3f2d33c3b9e40848b960e8caff34392fec3", "size": 6628, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/fixed_income/rates.py", "max_stars_repo_name": "Bocha84/fixed-income", "max_stars_repo_head_hexsha": "20489a43e17885045b7cfece221c49041b767ff3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-12-18T07:17:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-02T07:04:33.000Z", "max_issues_repo_path": "src/fixed_income/rates.py", "max_issues_repo_name": "Bocha84/fixed-income", "max_issues_repo_head_hexsha": "20489a43e17885045b7cfece221c49041b767ff3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fixed_income/rates.py", "max_forks_repo_name": "Bocha84/fixed-income", "max_forks_repo_head_hexsha": "20489a43e17885045b7cfece221c49041b767ff3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-12-18T05:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-03T16:42:10.000Z", "avg_line_length": 29.1982378855, "max_line_length": 101, "alphanum_fraction": 0.6635485818, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211539104334, "lm_q2_score": 0.8723473697001441, "lm_q1q2_score": 0.850382669541826}}
{"text": "# Question 5 Lab 03\n# AB Satyaprakash (180123062)\n\n# imports ----------------------------------------------------------------------\nimport sympy as sp\n# ------------------------------------------------------------------------------\n# (i) To show that both P(x) and Q(x) interpolate the data:\n# f(−2) = −1, f(−1) = 3, f(0) = 1, f(1) = −1, f(2) = 3\n# Given:\n# P(x) = 3 − 2(x + 1) + 0(x + 1)(x) + (x + 1)(x)(x − 1)\n# Q(x) = −1 + 4(x + 2) − 3(x + 2)(x + 1) + (x + 2)(x + 1)(x)\nx = sp.Symbol('x')\npx = 3 - 2*(x+1) + 0*(x+1)*(x) + (x+1)*(x)*(x-1)\nqx = -1 + 4*(x+2) - 3*(x+2)*(x+1) + (x+2)*(x+1)*(x)\n\nX = [-2, -1, 0, 1, 2]\nF = [-1, 3, 1, -1, 3]\nok = True  # will change this to false if either P or Q does not interpolate\n\nfor i in range(len(X)):\n    pval = px.subs(x, X[i])\n    print('The value of P({}) = {}'.format(X[i], pval))\n    if pval != F[i]:\n        ok = False\nprint('\\n')\nfor i in range(len(X)):\n    qval = qx.subs(x, X[i])\n    print('The value of Q({}) = {}'.format(X[i], qval))\n    if qval != F[i]:\n        ok = False\n\nif ok == True:\n    print(\"\\nThus, both cubic polynomails P(x) and Q(x) interpolate the given data\")\n\n# (ii) Why does part (i) not violate the uniqueness property of interpolating polynomials\npx = sp.expand(px)\nqx = sp.expand(qx)\nprint('Simplifying P(x) we get', px)\nprint('Simplifying Q(x) we get', qx)\nprint('Since we can clearly see that P(x) = Q(x), this ensures that the uniqueness property of interpolating polynmials is not violated')\n\n# Question 5 ends --------------------------------------------------------------\n", "meta": {"hexsha": "536022222cf643981df76bcefe6e22d24e9e0982", "size": 1548, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 3/Code/q5.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 3/Code/q5.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 3/Code/q5.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 36.0, "max_line_length": 137, "alphanum_fraction": 0.4786821705, "include": true, "reason": "import sympy", "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.914900959053549, "lm_q1q2_score": 0.8503459096787982}}
{"text": "#%%\r\n\"\"\"\r\nCreated on July 05  2021\r\nIncentive function as a function of a swap rate or the differential w.r.t. \"old\" mortgage rate\r\n\r\nThis code is purely educational and comes from \"Financial Engineering\" course by L.A. Grzelak\r\nThe course is based on the book “Mathematical Modeling and Computation\r\nin Finance: With Exercises and Python and MATLAB Computer Codes”,\r\nby C.W. Oosterlee and L.A. Grzelak, World Scientific Publishing Europe Ltd, 2019.\r\n@author: Lech A. Grzelak and Emanuele Cassamassima\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef Annuity(rate,notional,periods,CPR):\r\n    # it returns a matrix M such that\r\n    # M = [t  notional(t)  prepayment(t)  notional_quote(t)  interest_quote(t)  installment(t)]\r\n    # WARNING! here \"rate\" and \"periods\" are quite general, the choice of getting year/month/day.. steps, depends on the rate\r\n    # that the function receives. So, it is necessary to pass the correct rate to the function\r\n    M = np.zeros((periods + 1,6))\r\n    M[:,0] = np.arange(periods + 1) # we define the times\r\n    M[0,1] = notional\r\n    for t in range(1,periods + 1):\r\n        # we are computing the installment at time t knowing the oustanding at time (t-1)\r\n        remaining_periods = periods - (t - 1)  \r\n        \r\n        # Installment, C(t_i) \r\n        M[t,5] = rate * M[t-1,1]/(1 - 1/(1 + rate)**remaining_periods) \r\n        \r\n        # Interest rate payment, I(t_i) = r * N(t_{i})\r\n        M[t,4] = rate * M[t-1,1] \r\n        \r\n        # Notional payment, Q(t_i) = C(t_i) - I(t_i)\r\n        M[t,3] = M[t,5] - M[t,4] \r\n        \r\n        # Prepayment, P(t_i)= Lambda * (N(t_i) -Q(t_i))\r\n        M[t,2] = CPR * (M[t-1,1] - M[t,3]) \r\n        \r\n        # notional, N(t_{i+1}) = N(t_{i}) - lambda * (Q(t_{i} + P(t_i)))\r\n        M[t,1] = M[t-1,1] - M[t,3] - M[t,2] \r\n    return M\r\n\r\ndef mainCode():\r\n\r\n\r\n    IncentiveFunction = lambda x : 0.04 + 0.1/(1 + np.exp(115 * (0.02-x))) \r\n    \r\n    oldRate = 0.05\r\n    newRate = np.linspace(-0.05,0.15,25)\r\n    \r\n    epsilon = oldRate-newRate\r\n    incentive = IncentiveFunction(epsilon)\r\n    \r\n    plt.figure(1)\r\n    plt.plot(newRate,incentive)\r\n    plt.xlabel('S(t)')\r\n    plt.ylabel('Incentive')\r\n    plt.grid()\r\n    \r\n    plt.figure(2)\r\n    plt.plot(epsilon,incentive)\r\n    plt.xlabel('epsilon= K - S(t)')\r\n    plt.ylabel('Incentive')\r\n    plt.grid()\r\n\r\n    return 0.0\r\n\r\nmainCode()\r\n    \r\n    ", "meta": {"hexsha": "8fa9a3a521adf838a224ab0a34d8b1670388579e", "size": 2385, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lecture 08-Mortgages and Prepayments/Materials/Incentives.py", "max_stars_repo_name": "Wee7/FinancialEngineering_IR_xVA", "max_stars_repo_head_hexsha": "cb29982b3c6b7c86480a2a9f01326b48c2539e7c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 49, "max_stars_repo_stars_event_min_datetime": "2021-09-10T15:58:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T22:07:45.000Z", "max_issues_repo_path": "Lecture 08-Mortgages and Prepayments/Materials/Incentives.py", "max_issues_repo_name": "Wee7/FinancialEngineering_IR_xVA", "max_issues_repo_head_hexsha": "cb29982b3c6b7c86480a2a9f01326b48c2539e7c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lecture 08-Mortgages and Prepayments/Materials/Incentives.py", "max_forks_repo_name": "Wee7/FinancialEngineering_IR_xVA", "max_forks_repo_head_hexsha": "cb29982b3c6b7c86480a2a9f01326b48c2539e7c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2021-09-10T15:58:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T23:44:57.000Z", "avg_line_length": 34.0714285714, "max_line_length": 126, "alphanum_fraction": 0.5878406709, "include": true, "reason": "import numpy", "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.9149009544128984, "lm_q1q2_score": 0.8503459089418728}}
{"text": "import numpy as np\n\n\ndef mean_square_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n    \"\"\"\n    Calculate MSE loss\n\n    Parameters\n    ----------\n    y_true: ndarray of shape (n_samples, )\n        True response values\n    y_pred: ndarray of shape (n_samples, )\n        Predicted response values\n\n    Returns\n    -------\n    MSE of given predictions\n    \"\"\"\n\n    val = 0\n    diffArr = y_true - y_pred\n    for i in diffArr:\n        val += np.power(i, 2)\n\n    return val * (1 / diffArr.size)\n\n\ndef misclassification_error(y_true: np.ndarray, y_pred: np.ndarray,\n                            normalize: bool = True) -> float:\n    \"\"\"\n    Calculate misclassification loss\n\n    Parameters\n    ----------\n    y_true: ndarray of shape (n_samples, )\n        True response values\n    y_pred: ndarray of shape (n_samples, )\n        Predicted response values\n    normalize: bool, default = True\n        Normalize by number of samples or not\n\n    Returns\n    -------\n    Misclassification of given predictions\n    \"\"\"\n    counter = 0\n    for i, j in zip(y_pred, y_true):\n        if i != j:\n            counter += 1\n    if normalize: return counter / y_true.size\n    return counter\n\n\ndef accuracy(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n    \"\"\"\n    Calculate accuracy of given predictions\n\n    Parameters\n    ----------\n    y_true: ndarray of shape (n_samples, )\n        True response values\n    y_pred: ndarray of shape (n_samples, )\n        Predicted response values\n\n    Returns\n    -------\n    Accuracy of given predictions\n    \"\"\"\n    counter = 0\n    for i, j in zip(y_pred, y_true):\n        if i == j:\n            counter += 1\n\n    return counter / y_true.size\n\n\ndef cross_entropy(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n    \"\"\"\n    Calculate the cross entropy of given predictions\n\n    Parameters\n    ----------\n    y_true: ndarray of shape (n_samples, )\n        True response values\n    y_pred: ndarray of shape (n_samples, )\n        Predicted response values\n\n    Returns\n    -------\n    Cross entropy of given predictions\n    \"\"\"\n    raise NotImplementedError()\n", "meta": {"hexsha": "3a275d1c8e9ffb3790eba7ac96dc962380c42ee7", "size": 2086, "ext": "py", "lang": "Python", "max_stars_repo_path": "IMLearn/metrics/loss_functions.py", "max_stars_repo_name": "rom954/IML.HUJI", "max_stars_repo_head_hexsha": "c5c8752ed666b62c76ff115faf7494fa9ed765ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IMLearn/metrics/loss_functions.py", "max_issues_repo_name": "rom954/IML.HUJI", "max_issues_repo_head_hexsha": "c5c8752ed666b62c76ff115faf7494fa9ed765ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IMLearn/metrics/loss_functions.py", "max_forks_repo_name": "rom954/IML.HUJI", "max_forks_repo_head_hexsha": "c5c8752ed666b62c76ff115faf7494fa9ed765ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4301075269, "max_line_length": 71, "alphanum_fraction": 0.5973154362, "include": true, "reason": "import numpy", "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.9073122263731811, "lm_q1q2_score": 0.8503428160936444}}
{"text": "import numpy as np\n\ndef hilb(n, m=0):\n    \"\"\"\n    hilb   Hilbert matrix.\n       hilb(n,m) is the n-by-m matrix with elements 1/(i+j-1).\n       it is a famous example of a badly conditioned matrix.\n       cond(hilb(n)) grows like exp(3.5*n).\n       hilb(n) is symmetric positive definite, totally positive, and a\n       Hankel matrix.\n\n       References:\n       M.-D. Choi, Tricks or treats with the Hilbert matrix, Amer. Math.\n           Monthly, 90 (1983), pp. 301-312.\n       N.J. Higham, Accuracy and Stability of Numerical Algorithms,\n           Society for Industrial and Applied Mathematics, Philadelphia, PA,\n           USA, 2002; sec. 28.1.\n       M. Newman and J. Todd, The evaluation of matrix inversion\n           programs, J. Soc. Indust. Appl. Math., 6 (1958), pp. 466-476.\n       D.E. Knuth, The Art of Computer Programming,\n           Volume 1, Fundamental Algorithms, second edition, Addison-Wesley,\n           Reading, Massachusetts, 1973, p. 37.\n\n       NOTE added in porting.  We do not use the function cauchy here to\n       generate the Hilbert matrix.  That is done so we can unit test the\n       the functions against each other.  Also, the function has been\n       generalized to take by row and column sizes.  If only a row size\n       is given, we assume a square matrix is desired.\n    \"\"\"\n    if n < 1 or m < 0:\n        raise ValueError(\"Matrix size must be one or greater\")\n    elif n == 1 and (m == 0 or m == 1):\n        return np.array([[1]])\n    elif m == 0:\n        m = n\n\n    return 1. / (np.arange(1, n + 1) + np.arange(0, m)[:, np.newaxis])\n", "meta": {"hexsha": "2171abc9895bb2d18e5e9918c132ab93354b2633", "size": 1577, "ext": "py", "lang": "Python", "max_stars_repo_path": "ExamPrep/Shit Comp/ShitComp/hilb.py", "max_stars_repo_name": "FHomewood/ScientificComputing", "max_stars_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_stars_repo_licenses": ["IJG"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ExamPrep/Shit Comp/ShitComp/hilb.py", "max_issues_repo_name": "FHomewood/ScientificComputing", "max_issues_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_issues_repo_licenses": ["IJG"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ExamPrep/Shit Comp/ShitComp/hilb.py", "max_forks_repo_name": "FHomewood/ScientificComputing", "max_forks_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_forks_repo_licenses": ["IJG"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5, "max_line_length": 76, "alphanum_fraction": 0.6144578313, "include": true, "reason": "import numpy", "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.9073122288794595, "lm_q1q2_score": 0.8503428088952593}}
{"text": "#\n# Source Code  from https://people.duke.edu/~ccc14/sta-663/EMAlgorithm.html\n# And here https://mk-minchul.github.io/EM/\n#\nimport numpy as np\n\n# This is our observed data \n# Coin flips by two people, each 10 times, the first number is the number heads and scond is the number of tails\nys = np.array([(9,1), (8,2), (5,5), (4,6), (7,3)])\n\nthetas = np.array([[0.6, 0.4], [0.5, 0.5]])  # initialize theta_1, 2\n# Thetas can be the probabilities for the first and second persons for example. \n\npis =np.array([0.5, 0.5])  # prob of choosing coin 1 or coin2 is the same.\n\ntolerance = 0.01\nmax_iter = 100\n\nloglike_old = 0\nfor i in range(max_iter):\n    E_c1 = []\n    E_c2 = []\n    EcY_1 = []\n    EcY_2 = []\n\n    loglike_new = 0\n    # E-step: calculate probability distributions over possible completions\n    for i in range(len(ys)):\n        # multinomial (binomial) log likelihood\n        log_k1 = np.sum([ys[i]*np.log(thetas[0])])  #  \\log [\\theta_k^{y_{oi}} (1-\\theta_k)^{n - y_{oi}} ]\n        log_k2 = np.sum([ys[i]*np.log(thetas[1])])  #  \\log [\\theta_k^{y_{oi}} (1-\\theta_k)^{n - y_{oi}} ]\n\n        # Getting the expectation of c_ik\n        denom = np.exp(log_k1) * pis[0] + np.exp(log_k2) * pis[1]\n        E_ci1 = np.exp(log_k1) * pis[0] / denom\n        E_ci2 = np.exp(log_k2) * pis[1] / denom\n\n        # update complete log likelihood\n        # we need it only to check if it converged.\n        # we dont need it for updating theta.\n        loglike_new += E_ci1 * log_k1 + E_ci2 * log_k2\n        E_c1.append(E_ci1)\n        E_c2.append(E_ci2)\n\n\n    # M-step: update values for parameters given current distribution\n    for i in range(len(ys)):\n        EcY_1.append(E_c1[i] * ys[i] )  # this is a scalar times a vector.\n        EcY_2.append(E_c2[i] * ys[i] )\n\n    thetas[0] = np.sum(EcY_1, 0)/np.sum(EcY_1)\n    thetas[1] = np.sum(EcY_2, 0)/np.sum(EcY_2)\n\n    print (\"Iteration: %d\" % (i+1))\n    print (\"theta_A = [%.2f, %.2f], theta_B = [%.2f, %.2f] , difference in loglike = %.2f\" % (thetas[0,0], thetas[0,1], thetas[1,0], thetas[1,1], loglike_new - loglike_old))\n\n    if np.abs(loglike_new - loglike_old) < tolerance:\n        break\n\n    loglike_old = loglike_new\n", "meta": {"hexsha": "0f050aff44794e5ef04439d39be6a8c98fac3f9b", "size": 2161, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_examples/EM_InPython.py", "max_stars_repo_name": "heroapoorva/MET-CS777", "max_stars_repo_head_hexsha": "b2d8575ca46aa29ae9b7cf50cbceb424f9a46c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-09T14:56:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-09T14:56:57.000Z", "max_issues_repo_path": "Python_examples/EM_InPython.py", "max_issues_repo_name": "pvkothapalli/MET-CS777", "max_issues_repo_head_hexsha": "6825bec99581b04f9bcc328cdaa698faa2af7313", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python_examples/EM_InPython.py", "max_forks_repo_name": "pvkothapalli/MET-CS777", "max_forks_repo_head_hexsha": "6825bec99581b04f9bcc328cdaa698faa2af7313", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4262295082, "max_line_length": 173, "alphanum_fraction": 0.609440074, "include": true, "reason": "import numpy", "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.9073122150949273, "lm_q1q2_score": 0.8503427991586792}}
{"text": "#!/usr/bin/env python\n\n''' Método de Newton: encontrar o mínimo dessa função '''\n\nfrom sympy import lambdify, diff, cos, sin, exp\nfrom sympy.plotting import plot, plot3d\nfrom sympy.abc import x\n\n\nfrom Error import * \nfrom Log import *\n\n\nMAX = 50\nPATH = 'log/newton/'\nTOLERANCE = 0.00000001 # 10**(-8)\n\n                                 \ndef newton(fn, cx, tol, nmax) :\n    l = Log()\n    e = Error()\n    previous = 0\n    function = fn\n    \n    dx = fn.diff(x)\n    dx = lambdify(x, dx)\n    fn = lambdify(x, fn)\n     \n    for n in range(nmax) : \n        if (dx(cx) == 0) :\n            return \"Error 25: derivative less than zero\"\n            breakpoint\n        cx = cx - (fn(cx) / dx(cx) )\n        e.absolute(cx, previous)\n        e.relative(cx, previous)\n        l.append([cx, e._absolute, e._relative, fn(cx), dx(cx)])\n        if (e._absolute < tol) :\n            l.set_header(['x', 'absolute_error', 'relative_error', 'function', 'derivative'])\n            l.list2file((PATH+str(function)))\n            return cx\n            breakpoint\n        previous = cx\n    return False\n\n\ndef run_test(function, a, TOLERANCE, MAX): \n    m = newton(function, a, TOLERANCE, MAX)\n    print('f(x) =',f, '-> newton =', m)\n    return m\n    \n\nif __name__ == \"__main__\":\n    ''' Tests '''\n    a = 0.5\n    fx = [(cos(x) - x**3), ((3*(x**3))-2), (6*(x**2) - 400),\n          (x**2 - 4*x -5), (x ** 2 - 10), (x**2 - 612), \n          (x**3 - 1),(x ** 3 - 2 * x - 5), ((x**3)-(2*x)+2), \n          (x**3-6*x**2+4*x+2), (x**3 - x**2 - 1), \n          (x**6 - x - 1)]\n        \n    for f in fx:\n        r = run_test(f, a, TOLERANCE, MAX)\n        # graph = plot(f, show=False)\n        # graph.save('view/function/'+str(f))\n        \n        # graph = plot3d(f, show=False)\n        # graph.save('view/function/3D/'+str(f))\n", "meta": {"hexsha": "c89e2f9a9c60a186a48cc483a0730ae9fbf0d078", "size": 1788, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/newton-method.py", "max_stars_repo_name": "codinginbrazil/GA018", "max_stars_repo_head_hexsha": "714fcfca0144536ce17481793b100058fb07b928", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-24T12:52:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T12:52:12.000Z", "max_issues_repo_path": "src/newton-method.py", "max_issues_repo_name": "codinginbrazil/GA018", "max_issues_repo_head_hexsha": "714fcfca0144536ce17481793b100058fb07b928", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/newton-method.py", "max_forks_repo_name": "codinginbrazil/GA018", "max_forks_repo_head_hexsha": "714fcfca0144536ce17481793b100058fb07b928", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2941176471, "max_line_length": 93, "alphanum_fraction": 0.4916107383, "include": true, "reason": "from sympy", "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567177, "lm_q2_score": 0.9073122132152183, "lm_q1q2_score": 0.8503427989882117}}
{"text": "\n# coding: utf-8\n\n# ## Matrix Object in Numpy\n# Numpy, short for Numerical Python, is the fundamental package required for hight performance scientific computing and its best library to learn and apply on data science career.\n# \n# This is just little illustration.\n# \n# <img style=\"float: left;\" src=\"https://www.safaribooksonline.com/library/view/python-for-data/9781449323592/httpatomoreillycomsourceoreillyimages1346880.png\" width=400 height=200>\n\n# In[1]:\n\n\nimport numpy as np\n\n\n# In[2]:\n\n\na = np.array([[1,2,4],\n              [2,5,3], \n              [7,8,9]])\nA = np.mat(a)\nA\n\n\n# In[3]:\n\n\nA = np.mat('1,2,4;2,5,3;7,8,9')\nA\n\n\n# In[5]:\n\n\na = np.array([[ 1, 2],\n              [ 3, 4]])\nb = np.array([[10,20], \n              [30,40]])\n\nnp.bmat('a,b;b,a')\n\n\n# In[10]:\n\n\nx = np.array([[4], [2], [3]])\nx\n\n\n# In[11]:\n\n\nA * x\n\n\n# In[12]:\n\n\nprint(A * A.I)\n\n\n# In[13]:\n\n\nprint(A ** 3)\n\n", "meta": {"hexsha": "0da6761554376bde54952d84c2da10c35674390a", "size": 880, "ext": "py", "lang": "Python", "max_stars_repo_path": "All Python Codes/2017-24-11-so-matrix-object-numpy.py", "max_stars_repo_name": "bjfisica/MachineLearning", "max_stars_repo_head_hexsha": "20349301ae7f82cd5048410b0cf1f7a5f7d7e5a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52, "max_stars_repo_stars_event_min_datetime": "2019-02-15T16:37:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T18:34:30.000Z", "max_issues_repo_path": "All Python Codes/2017-24-11-so-matrix-object-numpy.py", "max_issues_repo_name": "RodeoBlues/Complete-Data-Science-Toolkits", "max_issues_repo_head_hexsha": "c5e83889e24af825ec3baed6e8198debb135f1ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "All Python Codes/2017-24-11-so-matrix-object-numpy.py", "max_forks_repo_name": "RodeoBlues/Complete-Data-Science-Toolkits", "max_forks_repo_head_hexsha": "c5e83889e24af825ec3baed6e8198debb135f1ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2019-02-25T23:52:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T03:09:35.000Z", "avg_line_length": 12.7536231884, "max_line_length": 181, "alphanum_fraction": 0.5738636364, "include": true, "reason": "import numpy", "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878722, "lm_q2_score": 0.907312219480915, "lm_q1q2_score": 0.8503427969044096}}
{"text": "from numpy import array\nfrom numpy.linalg import det\n\ndef poly_fit(x,y):\n    n = len(x)\n    x1sm = sum(x)\n    y1sm = sum(y)\n    x2sm = sum(x**2)\n    x3sm = sum(x**3)\n    x4sm = sum(x**4)\n    xysm = sum(x*y)\n    x2ysm = sum((x**2)*y)\n    # Cramer's rule\n    eq = array([[x2sm,x3sm,x4sm],[x1sm,x2sm,x3sm],[n,x1sm,x2sm]])\n    rig = array([x2ysm, xysm, y1sm]) \n    detabc = det(eq)\n    eqc = array([[x2ysm,x3sm,x4sm],[xysm,x2sm,x3sm],[y1sm,x1sm,x2sm]])\n    eqb = array([[x2sm,x2ysm,x4sm],[x1sm,xysm,x3sm],[n,y1sm,x2sm]])\n    eqa = array([[x2sm,x3sm,x2ysm],[x1sm,x2sm,xysm],[n,x1sm,y1sm]])\n    detc = det(eqc)\n    detb = det(eqb)\n    deta = det(eqa)\n    a = deta/detabc\n    b = detb/detabc\n    c = detc/detabc    \n    return a,b,c\n\nx = array([0, 1, 2, 4])  \ny = array([2, 3, 9, 15])\na,b,c = poly_fit(x,y)\n\nprint(\"a = %8.4f\" % a)\nprint(\"b = %8.4f\" % b)\nprint(\"b = %8.4f\" % c)\nprint(\"y = %8.4f x^2 + %8.4f x + %8.4f\" % (a, b, c))\n", "meta": {"hexsha": "2ff6e1de2e273b2287d3cd03a99eb86c45789969", "size": 923, "ext": "py", "lang": "Python", "max_stars_repo_path": "26_2.py", "max_stars_repo_name": "rursvd/pynumerical2", "max_stars_repo_head_hexsha": "4b2d33125b64a39099ac8eddef885e0ea11b237d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "26_2.py", "max_issues_repo_name": "rursvd/pynumerical2", "max_issues_repo_head_hexsha": "4b2d33125b64a39099ac8eddef885e0ea11b237d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "26_2.py", "max_forks_repo_name": "rursvd/pynumerical2", "max_forks_repo_head_hexsha": "4b2d33125b64a39099ac8eddef885e0ea11b237d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-03T01:34:19.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-03T01:34:19.000Z", "avg_line_length": 25.6388888889, "max_line_length": 70, "alphanum_fraction": 0.5352112676, "include": true, "reason": "from numpy", "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9787126457229186, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.8503317594953347}}
{"text": "import pandas as pd\nimport numpy as np\nimport numpy.linalg as ln\nfrom matplotlib import pylab as plt\n\n\ndef out(filename, s):\n\twith open(filename, 'w') as f:\n\t\tf.write(s)\n\n\ndef mserror(y, y_pred):\n\treturn (1 / float(y.size)) * np.sum((y - y_pred) ** 2)\n\n\ndef normal_equation(X, y):\n\treturn ln.solve(X.T.dot(X), X.T.dot(y))\n\n\ndef linear_prediction(X, w):\n\treturn X.dot(w)\n\n\ndef stochastic_gradient_step(X, y, w, train_ind, eta=0.01):\n\tmult = (2 * eta / float(X.shape[0])) * (y[train_ind] - X[train_ind, :].dot(w))\n\tw_new = np.zeros(X.shape[1])\n\tw_new[0] = (w[0] + mult)\n\tfor i in xrange(1, X.shape[1]):\n\t\tw_new[i] = (w[i] + mult * X[train_ind, i])\n\treturn w_new\n\n\ndef stochastic_gradient_descent(X, y, w_init, eta=1e-2, max_iter=1e4,\n\t\t\t\t\t\t\t\tmin_weight_dist=1e-8, seed=42, verbose=False):\n\tweight_dist = np.inf\n\tw = w_init\n\terrors = []\n\titer_num = 0\n\tnp.random.seed(seed)\n\n\twhile weight_dist > min_weight_dist and iter_num < max_iter:\n\t\trandom_ind = np.random.randint(X.shape[0])\n\t\tw_new = stochastic_gradient_step(X, y, w, random_ind, eta)\n\n\t\tweight_dist = np.linalg.norm(w_new - w)\n\t\tw = w_new\n\t\terrors.append(mserror(y, linear_prediction(X, w)))\n\t\titer_num += 1\n\n\treturn w, errors\n\n\ndata = pd.read_csv('advertising.csv')\n\ny = data['Sales'].values\nX = data.drop('Sales', axis=1).values\n\nmeans, stds = np.mean(X, axis=0), np.std(X, axis=0)\nX = (X - means) / stds\nX = np.hstack((np.ones((X.shape[0], 1)), X))\n\ny_pred = np.full(y.shape, np.median(y))\nerr = mserror(y, y_pred)\nres = '%.3f' % err\nout('1_1.txt', res)\n\nnorm_eq_weights = normal_equation(X, y)\nres = '%.3f' % norm_eq_weights.dot(np.mean(X, axis=0))\nout('1_2.txt', res)\n\ny_pred = linear_prediction(X, norm_eq_weights)\nerr = mserror(y, y_pred)\nres = '%.3f' % err\nout('1_3.txt', res)\n\nstoch_grad_desc_weights, stoch_errors_by_iter = stochastic_gradient_descent(X, y, np.zeros(X.shape[1]), max_iter=1e5)\nplt.plot(range(len(stoch_errors_by_iter)), stoch_errors_by_iter)\nplt.xlabel('Iteration number')\nplt.ylabel('MSE')\nplt.show()\n\nprint stoch_grad_desc_weights\nprint stoch_errors_by_iter[-1]\n\ny_pred = linear_prediction(X, stoch_grad_desc_weights)\nerr = mserror(y, y_pred)\nres = '%.3f' % err\nprint res\nout('1_4.txt', res)", "meta": {"hexsha": "69f719c49b2a16f524a36d79281f351aaa6aba22", "size": 2175, "ext": "py", "lang": "Python", "max_stars_repo_path": "course2/week1/task1.py", "max_stars_repo_name": "astarostin/MachineLearningSpecializationCoursera", "max_stars_repo_head_hexsha": "aebecae1effd5e4b148354d28cdad8bc6bd3a415", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-23T19:32:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-23T19:32:59.000Z", "max_issues_repo_path": "course2/week1/task1.py", "max_issues_repo_name": "astarostin/MachineLearningSpecializationCoursera", "max_issues_repo_head_hexsha": "aebecae1effd5e4b148354d28cdad8bc6bd3a415", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "course2/week1/task1.py", "max_forks_repo_name": "astarostin/MachineLearningSpecializationCoursera", "max_forks_repo_head_hexsha": "aebecae1effd5e4b148354d28cdad8bc6bd3a415", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-08-21T21:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T15:24:16.000Z", "avg_line_length": 24.4382022472, "max_line_length": 117, "alphanum_fraction": 0.6836781609, "include": true, "reason": "import numpy", "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454896, "lm_q2_score": 0.8933094145755219, "lm_q1q2_score": 0.8503083886291322}}
{"text": "#%% \nimport numpy as np \nimport matplotlib.pyplot as plt\n\n\n#%%\nu = np.linspace(-2,2,65)\nv = np.linspace(-1,1,33)\n\n#%%\nX,Y = np.meshgrid(u,v)\n\n#%%\nZ = X**2 /25 + Y**2/4\n# Z = np.sin(X) + np.cos(Y)\n\n#%%\nplt.pcolor(Z)\nplt.colorbar()\nplt.show()\n\n#%%\nplt.pcolor(X, Y, Z,  cmap='gray') # show the meshgrid to label\nplt.colorbar()\nplt.axis('tight')\nplt.show()\n\n#%%\na = [1,2,3,4]\nb = [10,11,12]\nA,B = np.meshgrid(a,b)\n\n#%% \nplt.contour(X, Y, Z, 30, cmap='autumn') # show the meshgrid to label\nplt.colorbar()\nplt.axis('tight')\nplt.show()\n\n#%%\nplt.contourf(X, Y, Z, 30) # show the meshgrid to label\nplt.colorbar()\nplt.axis('tight')\nplt.show()\n\n#%%\nplt.subplot(2,2,1)\nplt.pcolor(Z)\nplt.colorbar()\n\nplt.subplot(2,2,2)\nplt.pcolor(X, Y, Z,  cmap='gray') # show the meshgrid to label\nplt.colorbar()\n\nplt.subplot(2,2,3)\nplt.contour(X, Y, Z, 30, cmap='autumn') # show the meshgrid to label\nplt.colorbar()\n\nplt.subplot(2,2,4)\nplt.contourf(X, Y, Z, 30) # show the meshgrid to label\nplt.colorbar()\n\n# plt.axis('tight')\nplt.tight_layout()\nplt.show()\n\n#%%\n", "meta": {"hexsha": "19dc673d8047e66d40e33ec62fdc6a2eb2ef65ec", "size": 1034, "ext": "py", "lang": "Python", "max_stars_repo_path": "samples/meshgrid.py", "max_stars_repo_name": "mutazag/ilab1", "max_stars_repo_head_hexsha": "c37ae969d0fa13029ee08e7c0e102990e98e65b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "samples/meshgrid.py", "max_issues_repo_name": "mutazag/ilab1", "max_issues_repo_head_hexsha": "c37ae969d0fa13029ee08e7c0e102990e98e65b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2019-09-15T09:48:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-28T05:08:17.000Z", "max_forks_repo_path": "samples/meshgrid.py", "max_forks_repo_name": "mutazag/ilab1", "max_forks_repo_head_hexsha": "c37ae969d0fa13029ee08e7c0e102990e98e65b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.4328358209, "max_line_length": 68, "alphanum_fraction": 0.6237911025, "include": true, "reason": "import numpy", "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454895, "lm_q2_score": 0.8933094017937621, "lm_q1q2_score": 0.8503083764626448}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport sympy as sp\nfrom numpy import pi\nplt.rcParams['lines.linewidth'] = 3\nplt.rcParams['font.size'] = 30\nplt.rcParams['figure.figsize'] = [30,14]\npath = '/home/rosinante/PDS/PDS_UFCG/python/questao3/'\n#%% Function\nt = sp.symbols('t')\nf = sp.cos(2*np.pi*3200*t) + 0.5*sp.cos(2*np.pi*600*t) + 0.01*sp.cos(2*np.pi*300*t)\nx = sp.lambdify(t,f,'numpy')\n#%% Continuous\nL = 10\nFs = int(6000/L)\nTs = 1/Fs\nt_sampled = np.linspace(0,1,Fs)\nx_sampled = x(t_sampled)\n\n#%% Sampled\nF = 20*6400\nT = 1/F\nt_continuous = np.linspace(0,1,F)\nx_continuous = x(t_continuous)\n\n# %% FFT continuous\ny_continuous = np.fft.fft(x_continuous)\ny_continuous = np.abs(y_continuous)/np.max(np.abs(y_continuous))\nnc = x_continuous.size\nfreq_continuous = np.fft.fftfreq(nc,d=T)#*T*2*pi\n\n# %% FFT sampled\ny_sampled = np.fft.fft(x_sampled)\ny_sampled = np.abs(y_sampled)/np.max(np.abs(y_sampled))\nn = x_sampled.size\nfreq_sampled = np.fft.fftfreq(n,d=Ts)#*Ts*2*pi\n\n#%% plot FFT continuous\nfig = plt.figure()\nlabels = ['-pi','-pi/2','0','pi/2','pi']\nplt.plot(freq_continuous,y_continuous)\n#plt.xticks(np.arange(-pi,pi+1,pi/2),labels)\nplt.xlim([-3200-100,3200+100])\nplt.xlabel('frequency (Hz)')\nplt.title('Continuous Fourier transformed function')\nfig.savefig(path+'fft_continuous.png')\n\n#%% plot FFT sampled\nfig = plt.figure()\nplt.stem(freq_sampled,y_sampled)\n#plt.xticks(np.arange(-pi,pi+1,pi/2),labels)\n#plt.xlim([-3200-100,3200+100])\nplt.grid(True)\nplt.xlabel('frequency (Hz)')\nplt.title('Sampled Fourier transformed function')\nplt.legend(['Fs = '+str(Fs)+' Hz'])\nfig.savefig(path+'fft_sampled_Fs_'+str(Fs)+'Hz.png')\n#%%\nfig = plt.figure()\nplt.plot(freq_continuous,y_continuous,'k-')\nplt.stem(freq_sampled,y_sampled,'r--')\n#plt.xticks(np.arange(-pi,pi+1,pi/2),labels)\nplt.xlim([-3200-100,3200+100])\nplt.xlabel('frequency (Hz)')\nplt.title('Continuous and Sampled Fourier transformed functions')\nplt.grid(True)\nplt.legend(['Continuous','Sampled - Fs = '+str(Fs)+' Hz'])\nfig.savefig(path+'fft_both_Fs_'+str(Fs)+'Hz.png')", "meta": {"hexsha": "73965df7c20ad832d0e2d907b8d35c45da19bdd3", "size": 2031, "ext": "py", "lang": "Python", "max_stars_repo_path": "Amostragem/python/questao3/questao_3.py", "max_stars_repo_name": "Matos-V/PDS_UFCG", "max_stars_repo_head_hexsha": "b5ed435086ebfa40c213c8f74b18c8143bf45ed1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Amostragem/python/questao3/questao_3.py", "max_issues_repo_name": "Matos-V/PDS_UFCG", "max_issues_repo_head_hexsha": "b5ed435086ebfa40c213c8f74b18c8143bf45ed1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Amostragem/python/questao3/questao_3.py", "max_forks_repo_name": "Matos-V/PDS_UFCG", "max_forks_repo_head_hexsha": "b5ed435086ebfa40c213c8f74b18c8143bf45ed1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8676470588, "max_line_length": 83, "alphanum_fraction": 0.7065484983, "include": true, "reason": "import numpy,from numpy,import sympy", "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632329799586, "lm_q2_score": 0.8933094025038598, "lm_q1q2_score": 0.8503083759187191}}
{"text": "import numpy as np\nimport pandas as pd\n\n\n############################################################################\n# DO NOT MODIFY CODES ABOVE \n# DO NOT CHANGE THE INPUT AND OUTPUT FORMAT\n############################################################################\n\n# Part 1.1\ndef mean_square_error(w, X, y):\n    \"\"\"\n    Compute the mean square error of a model parameter w on a test set X and y.\n    Inputs:\n    - X: A numpy array of shape (num_samples, D) containing test features\n    - y: A numpy array of shape (num_samples, ) containing test labels\n    - w: a numpy array of shape (D, )\n    Returns:\n    - err: the mean square error\n    \"\"\"\n    n, y_predicted = len(y), np.dot(X, w)\n    err = np.sum(np.power(y - y_predicted, 2), dtype=np.float) / n\n    return err\n\n\n# Part 1.2\ndef linear_regression_noreg(X, y):\n    \"\"\"\n    Compute the weight parameter given X and y.\n    Inputs:\n    - X: A numpy array of shape (num_samples, D) containing features\n    - y: A numpy array of shape (num_samples, ) containing labels\n    Returns:\n    - w: a numpy array of shape (D, )\n    \"\"\"\n    # w* = (X^T X)^(-1) X^T y\n    w = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T), y)\n    return w\n\n\n# Part 1.3\ndef regularized_linear_regression(X, y, lambd):\n    \"\"\"\n    Compute the weight parameter given X, y and lambda.\n    Inputs:\n    - X: A numpy array of shape (num_samples, D) containing features\n    - y: A numpy array of shape (num_samples, ) containing labels\n    - lambd: a float number specifying the regularization parameter\n    Returns:\n    - w: a numpy array of shape (D, )\n    \"\"\"\n    D = np.shape(X)[1]\n    I = np.eye(D, k=0)\n    w = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)+lambd*I), X.T), y)\n    return w\n\n\n# Part 1.4\ndef tune_lambda(Xtrain, ytrain, Xval, yval):\n    \"\"\"\n    Find the best lambda value.\n    Inputs:\n    - Xtrain: A numpy array of shape (num_training_samples, D) containing training features\n    - ytrain: A numpy array of shape (num_training_samples, ) containing training labels\n    - Xval: A numpy array of shape (num_val_samples, D) containing validation features\n    - yval: A numpy array of shape (num_val_samples, ) containing validation labels\n    Returns:\n    - bestlambda: the best lambda you find among 2^{-14}, 2^{-13}, ..., 2^{-1}, 1.\n    \"\"\"\n    lambds, best_loss, best_lambda = [pow(2.0, -x) for x in range(15)], float('inf'), None\n    for lambd in lambds:\n        w = regularized_linear_regression(X=Xtrain, y=ytrain, lambd=lambd)\n        mse = mean_square_error(w=w, X=Xval, y=yval)\n        if mse < best_loss:\n            best_lambda = lambd\n            best_loss = mse\n\n    return best_lambda\n\n\n# Part 1.5\ndef mapping_data(X, P):\n    \"\"\"\n    Augment the data to [X, X^2, ..., X^p]\n    Inputs:\n    - X: A numpy array of shape (num_training_samples, D) containing training features\n    - P: An integer that indicates the degree of the polynomial regression\n    Returns:\n    - X: The augmented dataset. You might find np.insert useful.\n    \"\"\"\n    raw = X\n    for p in range(2, P+1):\n        x_poly = np.power(raw, p)\n        X = np.column_stack((X, x_poly))\n\n    return X\n\n\n\"\"\"\nNO MODIFICATIONS below this line.\nYou should only write your code in the above functions.\n\"\"\"\n", "meta": {"hexsha": "ba94a3735bb232f18fe105c3511f704aa037ba76", "size": 3215, "ext": "py", "lang": "Python", "max_stars_repo_path": "Regression/linear_regression.py", "max_stars_repo_name": "SinestroEdmonce/MachineLearning", "max_stars_repo_head_hexsha": "278a427993db28fe6364351a4315539ac8b651e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Regression/linear_regression.py", "max_issues_repo_name": "SinestroEdmonce/MachineLearning", "max_issues_repo_head_hexsha": "278a427993db28fe6364351a4315539ac8b651e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Regression/linear_regression.py", "max_forks_repo_name": "SinestroEdmonce/MachineLearning", "max_forks_repo_head_hexsha": "278a427993db28fe6364351a4315539ac8b651e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.213592233, "max_line_length": 91, "alphanum_fraction": 0.6059097978, "include": true, "reason": "import numpy", "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.8933093954028816, "lm_q1q2_score": 0.8503083655000336}}
{"text": "# -*- coding: utf-8 -*-\n# Created on Thu Feb 27 14:58:01 2020\n# @author: arthurd\n\n\nimport numpy as np\n\n\ndef softmax(X):\n    \"\"\"\n    Compute and return the softmax of the input.\n\n    Parameters\n    ----------\n    X : numpy.ndarray\n        Inputs of floats with shape [n, m]\n        \n    Returns\n    -------\n    numpy.ndarray\n        Outputs of floats with shape [n, m]\n    \"\"\"\n\n    exp = np.exp(X)\n    t = X - np.log(np.sum(exp, axis=0))\n    S = np.exp(t)\n    return S\n\nsigmoid = lambda X: 1.0 / (1.0 + np.exp(-X))\n\ntanh = lambda X: np.tanh(X)\n\nrelu = lambda X: np.maximum(0, X)\n\nleaky_relu = lambda X: np.where(X > 0, X, X * 0.01)\n\nlinear = lambda X: X", "meta": {"hexsha": "d82d905a4b0034bd706a86db1c7366777e0d0b99", "size": 652, "ext": "py", "lang": "Python", "max_stars_repo_path": "pysnake/nn/functional.py", "max_stars_repo_name": "arthurdjn/pysnake", "max_stars_repo_head_hexsha": "1d66644529804ee50a296b141123eba328f68a8e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-12-15T16:59:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T15:38:58.000Z", "max_issues_repo_path": "pysnake/nn/functional.py", "max_issues_repo_name": "arthurdjn/pysnake", "max_issues_repo_head_hexsha": "1d66644529804ee50a296b141123eba328f68a8e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pysnake/nn/functional.py", "max_forks_repo_name": "arthurdjn/pysnake", "max_forks_repo_head_hexsha": "1d66644529804ee50a296b141123eba328f68a8e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-29T12:01:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T03:03:43.000Z", "avg_line_length": 17.6216216216, "max_line_length": 51, "alphanum_fraction": 0.5475460123, "include": true, "reason": "import numpy", "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811611608242, "lm_q2_score": 0.8807970795424088, "lm_q1q2_score": 0.8503049073957134}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: salimt\r\n\"\"\"\r\n#Problem 1: Curve Fitting\r\n#15/15 points (graded)\r\n#Implement the generate_models function.\r\n#\r\n#x and y are two lists corresponding to the x-coordinates and y-coordinates of the data samples (or data points); for example, if you have N data points, x = [x1 , x2 , ..., xN ] and y = [y1 , y2 , ..., yN ], where x_i and y_i are the x and y coordinate of the i-th data points. In this problem set, each x coordinate is an integer and corresponds to the year of a sample (e.g., 1997); each corresponding y coordinate is a float and represents the temperature observation (will be computed in multiple ways) of that year in Celsius. This representation will be used throughout the entire problem set.\r\n#degs is a list of integers indicating the degree of each regression model that we want to create. For each model, this function should fit the data (x,y) to a polynomial curve of that degree.\r\n#This function should return a list of models. A model is the numpy 1d array of the coefficients of the fitting polynomial curve. Each returned model should be in the same order as their corresponding integer in degs.\r\n#Example:\r\n#\r\n#print(generate_models([1961, 1962, 1963],[4.4,5.5,6.6],[1, 2]))\r\n#Should print something close to:\r\n#\r\n#[array([ 1.10000000e+00, -2.15270000e+03]), array([ -8.86320195e-14, 1.10000000e+00, -2.15270000e+03])]\r\n#The above example was generating a linear and a quadratic curve on data samples (xi, yi ) = (1961, 4.4), (1962, 5.5), and (1963, 6.6). The resulting models are in the same order as specified in degs. Note that it is fine you did not get the exact number because of numerical errors.\r\n#\r\n#Note: If you want to use numpy arrays, you should import numpy as np and use np.METHOD_NAME in your code. Unfortunately, pylab does not work with the grader\r\n#\r\n## Problem 1\r\n#\r\ndef generate_models(x, y, degs):\r\n    \"\"\"\r\n    Generate regression models by fitting a polynomial for each degree in degs\r\n    to points (x, y).\r\n    Args:\r\n        x: a list with length N, representing the x-coords of N sample points\r\n        y: a list with length N, representing the y-coords of N sample points\r\n        degs: a list of degrees of the fitting polynomial\r\n    Returns:\r\n        a list of numpy arrays, where each array is a 1-d array of coefficients\r\n        that minimizes the squared error of the fitting polynomial\r\n    \"\"\"\r\n    import numpy as np\r\n    \r\n    models = []\r\n    for d in degs:\r\n        model = np.polyfit(x, y, d)\r\n        models.append(model)\r\n    return models\r\n\r\n#print(generate_models([1961, 1962, 1963],[4.4,5.5,6.6],[1, 2]))\r\n#[array([ 1.10000000e+00, -2.15270000e+03]), array([ -8.86320195e-14, 1.10000000e+00, -2.15270000e+03])]", "meta": {"hexsha": "40a926c3d26f4270243151b10a0f0f071b2b1c61", "size": 2725, "ext": "py", "lang": "Python", "max_stars_repo_path": "MITx-6.00.2x/pset4-modelling-temperatures/pset4_Problem1_curve_fitting.py", "max_stars_repo_name": "Sam-Gao-Xin/Courses-", "max_stars_repo_head_hexsha": "122810e56024e6e72d378317b4f98c5a9d97e5f8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 622, "max_stars_repo_stars_event_min_datetime": "2018-07-17T09:05:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T02:57:02.000Z", "max_issues_repo_path": "MITx-6.00.2x/pset4-modelling-temperatures/pset4_Problem1_curve_fitting.py", "max_issues_repo_name": "thientvse/Courses-", "max_issues_repo_head_hexsha": "263ff4680ed1dfd253be3652f7f13ad707af1a36", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2019-11-10T02:06:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T23:54:11.000Z", "max_forks_repo_path": "MITx-6.00.2x/pset4-modelling-temperatures/pset4_Problem1_curve_fitting.py", "max_forks_repo_name": "thientvse/Courses-", "max_forks_repo_head_hexsha": "263ff4680ed1dfd253be3652f7f13ad707af1a36", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 906, "max_forks_repo_forks_event_min_datetime": "2018-07-17T09:05:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:55:49.000Z", "avg_line_length": 60.5555555556, "max_line_length": 601, "alphanum_fraction": 0.6976146789, "include": true, "reason": "import numpy", "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9653811641488385, "lm_q2_score": 0.880797076413356, "lm_q1q2_score": 0.850304907006819}}
{"text": "import numpy as np\nfrom math import factorial\n\n\ndef _sin(x):\n    val = np.float64(0)\n    terms = np.array([], dtype=np.float64)\n    for n in range(41):\n        term = (((-1) ** n) * (x ** (2*n+1)) / factorial(2*n + 1))\n        terms = np.append(terms, term)\n        val += term\n    return val, terms\n\ndef debug_sin(x):\n    val, terms = _sin(x)\n    tmp = np.float64(0)\n    for i, t in enumerate(terms):\n        tmp += t\n        print(\"for x_{0}, term is {1}, sin({2}) approximation is {3}\".format(\n            i, t, x, tmp))\n    return val\n\ndef sin(x):\n    v, _ = _sin(x)\n    return v\n\ndef cos(x):\n    val = np.float64(0)\n    for n in range(41):\n        term = (((-1) ** n) * (x ** (2*n)) / factorial(2*n))\n        val += term\n    return val\n\npi = np.float64(22./7.)\nprint(\"pi is initially {0}\".format(pi))\nfor i in range(5):\n    pi += sin(pi)\n    print(\"improving pi iteration {0}, pi: {1}\".format(i, pi))\n\nif __name__ == \"__main__\":\n    vals = np.array([0, pi / 4., pi / 2., pi * 3./4., pi], dtype=np.float64)\n    for n in vals:\n        print(\"sin({0}) = {1}\".format(n, sin(n)))\n        print(\"cos({0}) = {1}\".format(n, cos(n)))\n", "meta": {"hexsha": "d09877aa099ae2eb4b23d39600f32c0f2d20ec5d", "size": 1130, "ext": "py", "lang": "Python", "max_stars_repo_path": "taylor_sin.py", "max_stars_repo_name": "thoolihan/PythonMath", "max_stars_repo_head_hexsha": "25e1ef092d4bb013a91a4856a255f2a38a9cb46c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "taylor_sin.py", "max_issues_repo_name": "thoolihan/PythonMath", "max_issues_repo_head_hexsha": "25e1ef092d4bb013a91a4856a255f2a38a9cb46c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "taylor_sin.py", "max_forks_repo_name": "thoolihan/PythonMath", "max_forks_repo_head_hexsha": "25e1ef092d4bb013a91a4856a255f2a38a9cb46c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1111111111, "max_line_length": 77, "alphanum_fraction": 0.5150442478, "include": true, "reason": "import numpy", "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811631528336, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.8503049015984481}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport math\n\n\ndef fft_own(xt):\n    \"\"\"A vectorized, non-recursive version of the Cooley-Tukey FFT\"\"\"\n    x = np.asarray(xt, dtype=float)\n    N = x.shape[0]\n\n    if np.log2(N) % 1 > 0:\n        raise ValueError(\"size of x must be a power of 2\")\n\n    # N_min here is equivalent to the stopping condition above,\n    # and should be a power of 2\n    N_min = min(N, 32)\n\n    # Perform an O[N^2] DFT on all length-N_min sub-problems at once\n    n = np.arange(N_min)\n    k = n[:, None]\n    M = np.exp(-2j * np.pi * n * k / N_min)\n    X = np.dot(M, x.reshape((N_min, -1)))\n\n    # build-up each level of the recursive calculation all at once\n    while X.shape[0] < N:\n        X_even = X[:, :int(X.shape[1] / 2)]\n        X_odd = X[:, int(X.shape[1] / 2):]\n        factor = np.exp(-1j * np.pi * np.arange(X.shape[0])\n                        / X.shape[0])[:, None]\n        X = np.vstack([X_even + factor * X_odd,\n                       X_even - factor * X_odd])\n\n    return X.ravel()\n\n\ndef brev(inDat):\n    N = len(inDat)\n    outDat = []\n    for k in range(N):\n        revN = int('{:0{width}b}'.format(k, width=int(np.ceil(np.log2(N))))[::-1], 2)\n        outDat.append(inDat[revN])\n    return outDat\n\n\n\nif __name__ == \"__main__\":\n    fig, axes = plt.subplots(ncols=1, nrows=2)\n    ax1, ax2 = axes.ravel()\n\n    # generate an input signal\n    Num = 1024\n    fs = 1000\n    t = np.linspace(0, Num / fs, Num)\n    x_t = np.sin(2 * np.pi * 1 * t) + 0.5 * np.sin(2 * np.pi * 5 * t) + 0.2 * np.sin(2 * np.pi * 10 * t)\n\n    # Generate the FFT twiddle factors\n\n    # Compute the FFT with time measurement\n    start_time = time.time()\n    X_f = fft_own(x_t)\n    stop_time = time.time()\n\n    f = np.linspace(0, fs / 2, int(Num / 2))\n    # Magnitude\n    A_f = np.zeros(Num, dtype=float)\n    for k in range(Num):\n        A_f[k] = np.sqrt(np.power(X_f[k].imag, 2) + np.power(X_f[k].real, 2))\n\n    elapsed_time = stop_time - start_time\n    print(\"The time of execution of our DFT is: %.5f s.\" % elapsed_time)\n\n    # plot input signal\n    ax1.plot(t, x_t)\n    ax1.margins(0)\n    ax1.grid()\n    # plot output signal\n    ax2.plot(f, A_f[0:int(Num / 2)])\n    plt.xscale(\"log\")\n    ax2.margins(0)\n    ax2.grid()\n    plt.show()\n\n\n", "meta": {"hexsha": "bcf92778ee938f3f76d12eeb4975cc7e14a0cc26", "size": 2257, "ext": "py", "lang": "Python", "max_stars_repo_path": "fft/FastFourierTransform.py", "max_stars_repo_name": "andraspatka/dsp-labs", "max_stars_repo_head_hexsha": "5b8842968aec2539a5cc83b7952cb91f93550ff4", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fft/FastFourierTransform.py", "max_issues_repo_name": "andraspatka/dsp-labs", "max_issues_repo_head_hexsha": "5b8842968aec2539a5cc83b7952cb91f93550ff4", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fft/FastFourierTransform.py", "max_forks_repo_name": "andraspatka/dsp-labs", "max_forks_repo_head_hexsha": "5b8842968aec2539a5cc83b7952cb91f93550ff4", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5529411765, "max_line_length": 104, "alphanum_fraction": 0.5644661054, "include": true, "reason": "import numpy", "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811581728098, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.8503048972120577}}
{"text": "import numpy as np\r\nimport Matrix_2 as M2\r\n\r\n\"\"\"\r\nlin - Linear interpolation\r\nInput: inp = a matrix containing all the x and y values (columns 0 and 1),\r\nsorted in ascending order in x.\r\nOutput: array f whose elements i provide the y values for any x between x_i and\r\nx_i+1 using a linear interpolation method.\r\n\"\"\"\r\n\r\ndef lin(inp, stepsize = 0.01):\r\n    x = inp[:, 0]\r\n    y = inp[:, 1]\r\n    f = np.array([])\r\n    xsamp = np.array([])\r\n    for i in np.arange(len(x)-1):\r\n        xnew = np.arange(start = x[i], stop = x[i+1], step = stepsize)\r\n        xsamp = np.append(xsamp, xnew)\r\n        # Samples points at step size 0.01 between two adjacent data points\r\n        # Note: last point of each section is not included, but it does not\r\n        # matter because it is automatically the first point of the next,\r\n        # EXCEPT the very last point\r\n        for j in np.arange(len(xnew)):\r\n            f = np.append(f, (((x[i+1] - xsamp[j + len(xsamp) - len(xnew)])*y[i]\r\n            + (xsamp[j + len(xsamp) - len(xnew)] - x[i])*y[i+1]) / (x[i+1]-x[i])))\r\n    xsamp = np.append(xsamp, x[-1]) # Adds in the last point because it is not\r\n    # included in any interpolation\r\n    f = np.append(f, y[-1])\r\n    return xsamp, f\r\n\r\n\"\"\"\r\ncubspline - Cublic spline\r\nInput: inp = a matrix containing all the x and y values (columns 0 and 1),\r\nsorted in ascending order in x.\r\nOutput: array f whose elements i provide the y values for any x between x_i and\r\nx_i+1 using a cubic spline method.\r\n\"\"\"\r\n\r\ndef cubspline(inp, stepsize = 0.01, showcoeff = False, showb = False): # show the coefficient matrix\r\n# or the array of constants\r\n    x = inp[:, 0]\r\n    y = inp[:, 1]\r\n    fdashdash = np.array([0.]) # first second derivative = 0\r\n    # Calculate the array contatining all the second derivatives of f at each\r\n    # data point.\r\n    coeff = np.zeros([len(x)-2, len(x)-2]) # Contains all the coefficients in\r\n    # the fundamental equation in finding f\". If we assume f\"_0 = f\"_n = 0\r\n    # (natural spline), then this leaves us with n-1 unknowns in n-1 eqs.\r\n    b = np.zeros(len(x)-2) # Contains the constant values\r\n    for i in np.arange(len(x)-2):\r\n        coeff[i, i] = (x[i+2] - x[i]) / 3 # Valid for all points      \r\n        if i > 0: # First point (i = 0) only has 2 coefficients as f\"_0 = 0\r\n            coeff[i, i-1] = (x[i+1] - x[i]) / 6\r\n        if i < len(x)-3: # Last point (i = len(x) - 3) only has 2 coefficients as f\"_n = 0\r\n            coeff[i, i+1] = (x[i+2] - x[i+1]) / 6\r\n        b[i] = (y[i+2] - y[i+1])/(x[i+2] - x[i+1]) - (y[i+1] -y[i])/(x[i+1] - x[i])\r\n    if showcoeff == True:\r\n        print(coeff)\r\n    if showb == True:\r\n        print(b)\r\n    fdashdash = np.append(fdashdash, M2.solve(coeff, b))\r\n    fdashdash = np.append(fdashdash, 0.) # last second derivative = 0\r\n\r\n    # Now we solve for the cubic spline function f(x).\r\n    f = np.array([])\r\n    xsamp = np.array([])\r\n    for i in np.arange(len(x)-1):\r\n        xnew = np.arange(start = x[i], stop = x[i+1], step = stepsize)\r\n        #xnew = np.linspace(x[i], x[i+1], 500)\r\n        xsamp = np.append(xsamp, xnew)\r\n        for j in np.arange(len(xnew)):\r\n            A = (x[i+1] - xnew[j])/(x[i+1] - x[i])\r\n            B = (xnew[j] - x[i])/(x[i+1] - x[i])\r\n            C = 1./6.*(A**3-A)*((x[i+1] - x[i])**2)\r\n            D = 1./6.*(B**3-B)*((x[i+1] - x[i])**2)\r\n            f = np.append(f, A*y[i] + B*y[i+1] + C*fdashdash[i] + D*fdashdash[i+1])\r\n    xsamp = np.append(xsamp, x[-1]) # Adds in the last point because it is not\r\n    # included in any interpolation\r\n    f = np.append(f, y[-1])\r\n    return xsamp, f", "meta": {"hexsha": "47e6937fd7768bd0f1b024818d0ed1296d25e489", "size": 3588, "ext": "py", "lang": "Python", "max_stars_repo_path": "Interpolation_3.py", "max_stars_repo_name": "adrielyeung/computational-physics", "max_stars_repo_head_hexsha": "c34c881b2e6ff29aebce6d0eb6d8d8404648ec71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-04T18:44:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-04T18:44:00.000Z", "max_issues_repo_path": "Interpolation_3.py", "max_issues_repo_name": "adrielyeung/computational-physics", "max_issues_repo_head_hexsha": "c34c881b2e6ff29aebce6d0eb6d8d8404648ec71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Interpolation_3.py", "max_forks_repo_name": "adrielyeung/computational-physics", "max_forks_repo_head_hexsha": "c34c881b2e6ff29aebce6d0eb6d8d8404648ec71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2962962963, "max_line_length": 101, "alphanum_fraction": 0.5613154961, "include": true, "reason": "import numpy", "num_tokens": 1139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811571768047, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.8503048963347793}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\nMachine Learning Online Class Coursera\nExercise 1: Linear regression with multiple variables\nModified with few changes,Solved the issue\nModified by github.com/utkarshmani1997\n\"\"\"\n\n# Initialization\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom ex1_utils import *\n\n## ================ Part 1: Feature Normalization ================\n\nprint('Loading data ...','\\n')\n\n## Load Data\nprint('Plotting Data ...','\\n')\n\ndata = pd.read_csv(\"ex1data2.txt\",names=[\"size1\",\"bedrooms\",\"price\"])\ns = np.array(data.size1)\nb = np.array(data.bedrooms)\np = np.array(data.price)\nm = len(b) # number of training examples\n\n# Design Matrix\ns = np.vstack(s)\nb = np.vstack(b)\nX = np.hstack((s,b))\n\n\n# Print out some data points\nprint('First 10 examples from the dataset: \\n')\nprint(\" size = \", s[:10],\"\\n\",\" bedrooms = \", b[:10], \"\\n\")\n\ninput('Program paused. Press enter to continue.\\n')\n\n# Scale features to zero mean and standard deviation of 1\nprint('Normalizing Features ...\\n')\n\nX = featureNormalize(X)\n\n# Add intercept term to X\nX = np.hstack((np.ones_like(s),X))\n\n## ================ Part 2: Gradient Descent ================\n\nprint('Running gradient descent ...\\n')\n\n# Choose some alpha value\nalpha = 0.05\nnum_iters = 400\n\n# Init Theta and Run Gradient Descent \ntheta = np.zeros(3)\n\n# Multiple Dimension Gradient Descent\ntheta, hist = gradientDescentMulti(X, p, theta, alpha, num_iters)\n\n# Plot the convergence graph\nfig = plt.figure()\nax = plt.subplot(111)\nplt.plot(np.arange(len(hist)),hist ,'-b')\nplt.xlabel('Number of iterations')\nplt.ylabel('Cost J')\nplt.show()\n\n# Display gradient descent's result\nprint('Theta computed from gradient descent: \\n')\nprint(theta,'\\n')\n\n# Estimating the price of a house on the given size in square feet and no of bedrooms\nsiz=int(input(\"Program paused. Enter the size of house in sq-ft:\"))\nbr=int(input(\"Program paused. Enter the no of bedrooms:\"))\n\n# Recall that the first column of X is all-ones. Thus, it does\n# not need to be normalized.\nnormalized_specs = np.array([1,((siz-s.mean())/s.std()),((br-b.mean())/b.std())])\nprice = np.dot(normalized_specs,theta) \n\n\nprint('Predicted price of house with size {} and {} no of bedrooms (using gradient descent):\\n '.format(siz, br),\n      price)\n\ninput('Program paused. Press enter to continue.\\n')\n\n## ================ Part 3: Normal Equations ================\nprint('Solving with normal equations...\\n')\n\ndata = pd.read_csv(\"ex1data2.txt\",names=[\"sz\",\"bed\",\"price\"])\ns = np.array(data.sz)\nb = np.array(data.bed)\np = np.array(data.price)\nm = len(b) # number of training examples\n\n# Design Matrix\ns = np.vstack(s)\nb = np.vstack(b)\nX = np.hstack((s,b))\n\n# Add intercept term to X\nX = np.hstack((np.ones_like(s),X))\n\n# Calculate the parameters from the normal equation\ntheta = normalEqn(X, p)\n\n# Display normal equation's result\nprint('Theta computed from the normal equations: \\n')\nprint(theta)\nprint('\\n')\n\n# Estimate the price of a house, by Normal equations\nprice = np.dot([1,siz,br],theta) # You should change this\n\n\nprint('Predicted price of house with size = {} and {} no of bedrooms (Normalization):\\n '.format(siz, br),\n      price)\n\n\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n", "meta": {"hexsha": "0c50575d11e111a2bba9d27ce507e724c09d7263", "size": 3285, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercise-1/ex1_multi.py", "max_stars_repo_name": "satyamz/ml-playground", "max_stars_repo_head_hexsha": "a37aa38035fe48c5be8d70c7fbba42ba2bdf9286", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercise-1/ex1_multi.py", "max_issues_repo_name": "satyamz/ml-playground", "max_issues_repo_head_hexsha": "a37aa38035fe48c5be8d70c7fbba42ba2bdf9286", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise-1/ex1_multi.py", "max_forks_repo_name": "satyamz/ml-playground", "max_forks_repo_head_hexsha": "a37aa38035fe48c5be8d70c7fbba42ba2bdf9286", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0714285714, "max_line_length": 113, "alphanum_fraction": 0.6846270928, "include": true, "reason": "import numpy", "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133548753619, "lm_q2_score": 0.9046505325302034, "lm_q1q2_score": 0.8502931170202462}}
{"text": "import numpy as np\n#!----Relu activation function-----!\n\ninputs = [1, 2, -2, 100, -130, 22, 0, 1, 4]\noutputs =[]\nfor i in inputs:\n    if i > 0:\n        outputs.append(i)\n    else:\n        outputs.append(0)\n\nprint(outputs)\n\n# print( np.exp(3))\n# print(2.718**3)\n\n\n\n#another way\ninputs = [1, 2,-2, 100, -130,22,0,1,4]\noutputs =[]\nfor i in inputs:\n        outputs.append(max(0,i))\nprint(outputs)\n\n\n#another way using numpy\noutputs=np.maximum(0,inputs)\nprint(outputs)\n\n\n\n#                 !-----soft_max activation function------!\noutputs =[4.8, 1.21, 2.385]\nE = 2.71828\nexp_values = []\nfor values in outputs:\n    exp_values.append(E**values)\n\nprint(exp_values)\n\n\nnorm_base = sum(exp_values)\n\nnorm_values = []\n\nfor n_value in exp_values:\n    norm_values.append(n_value / norm_base)\n\nprint(\"CE\", norm_values)\n\n\n#Do it with numpy\noutputs =([[1.8, 1.21, 3.385], [2, 1.21, 2.385],[3, 1.21, 2.385]])\nexp_values = np.exp(outputs)\nprobabilities = exp_values / np.sum(exp_values, axis=1, keepdims=True)\nprint(\"Hello\", probabilities)\n\nnp.exp(1000)  #doesn't take maximum number\n\n\n# for this reason write code as\n\nexp_values = np.exp(outputs-np.max(outputs, axis=1, keepdims=True))\nprint(\"Exponential values\",exp_values)\nprobabilities = exp_values /np.sum(exp_values, axis =1, keepdims=True)\nprint(\"Hi\", probabilities)\n\n\n    ", "meta": {"hexsha": "59c9c10aea184367262e0cf679193a78962917f8", "size": 1311, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter_4/activation_function.py", "max_stars_repo_name": "Dev-Gaju/NNFS-book-with-Implementation", "max_stars_repo_head_hexsha": "1a788ab61c8129aa52428923f02aca17b8757a33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-03T16:26:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T16:26:07.000Z", "max_issues_repo_path": "Chapter_4/activation_function.py", "max_issues_repo_name": "Dev-Gaju/NNFS-book-with-Implementation", "max_issues_repo_head_hexsha": "1a788ab61c8129aa52428923f02aca17b8757a33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter_4/activation_function.py", "max_forks_repo_name": "Dev-Gaju/NNFS-book-with-Implementation", "max_forks_repo_head_hexsha": "1a788ab61c8129aa52428923f02aca17b8757a33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-30T12:08:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-30T12:08:04.000Z", "avg_line_length": 18.7285714286, "max_line_length": 70, "alphanum_fraction": 0.6552250191, "include": true, "reason": "import numpy", "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913343093499, "lm_q2_score": 0.904650536386234, "lm_q1q2_score": 0.8502931099861124}}
{"text": "import numpy as np\n\n# Write a function that takes as input a list of numbers, and returns\n# the list of values given by the softmax function.\ndef softmax(L):\n    return np.exp(L) / np.sum(np.exp(L))\n\nres = softmax([1, 8, 16])\nprint(res, '\\nsum =', sum(res))", "meta": {"hexsha": "eded979cb52abde8ad98dcdeaa668facd2881c07", "size": 257, "ext": "py", "lang": "Python", "max_stars_repo_path": "L1_Deep_Neural_Networks/C_softmax.py", "max_stars_repo_name": "angelmtenor/AIND-deep-learning", "max_stars_repo_head_hexsha": "0a1597a0204790b078ac2451fec5df7784e8ead8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-05-19T03:06:42.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-19T03:06:42.000Z", "max_issues_repo_path": "L1_Deep_Neural_Networks/C_softmax.py", "max_issues_repo_name": "angelmtenor/AIND-deep-learning", "max_issues_repo_head_hexsha": "0a1597a0204790b078ac2451fec5df7784e8ead8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "L1_Deep_Neural_Networks/C_softmax.py", "max_forks_repo_name": "angelmtenor/AIND-deep-learning", "max_forks_repo_head_hexsha": "0a1597a0204790b078ac2451fec5df7784e8ead8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5555555556, "max_line_length": 69, "alphanum_fraction": 0.6809338521, "include": true, "reason": "import numpy", "num_tokens": 72, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692352660529, "lm_q2_score": 0.8705972818382005, "lm_q1q2_score": 0.8502855814776196}}
{"text": "import numpy as np\nfrom grid_world import GridworldEnv\n\nenv = GridworldEnv()\n\n\ndef policy_eval(policy, env, discount_factor=1.0, theta=0.00001):\n    \"\"\"\n    Evaluate a policy given an environment and a full description of the environment's dynamics.\n\n    Args:\n        policy: [S, A] shaped matrix representing the policy.\n        env: OpenAI env. env.P represents the transition probabilities of the environment.\n            env.P[s][a] is a list of transition tuples (prob, next_state, reward, done).\n            env.nS is a number of states in the environment. \n            env.nA is a number of actions in the environment.\n        theta: We stop evaluation once our value function change is less than theta for all states.\n        discount_factor: Gamma discount factor.\n\n    Returns:\n        Vector of length env.nS representing the value function.\n    \"\"\"\n    # Start with a random (all 0) value function\n    V = np.zeros(env.nS)\n    while True:\n        max_v_changed = 0\n        for s in range(env.nS):\n            v = 0\n            for a, action_prob in enumerate(policy[s]):\n                for prob, next_state, reward, done in env.P[s][a]:\n                    v += action_prob * prob * \\\n                        (reward + discount_factor * V[next_state])\n\n            max_v_changed = max(max_v_changed, np.abs(v - V[s]))\n            V[s] = v\n        # print(max_v_changed)\n        if max_v_changed < theta:\n            break\n\n    return np.array(V)\n\n\nif __name__ == '__main__':\n\n    random_policy = np.ones([env.nS, env.nA]) / env.nA\n    v = policy_eval(random_policy, env)\n\n    print(\"Value Function:\")\n    print(v)\n    print(\"\")\n\n    print(\"Reshaped Grid Value Function:\")\n    print(v.reshape(env.shape))\n    print(\"\")\n\n    expected_v = np.array([0, -14, -20, -22, -14, -18, -20, -20, -20, -20, -18, -14, -22, -20, -14, 0])\n    np.testing.assert_array_almost_equal(v, expected_v, decimal=2)\n", "meta": {"hexsha": "7a5b3d0d58d954ea917991509822dade4a9caf0f", "size": 1904, "ext": "py", "lang": "Python", "max_stars_repo_path": "Dynamic Programming Assignment/policy_evaluation_gridworld.py", "max_stars_repo_name": "me-manikanta/Move-37-Course", "max_stars_repo_head_hexsha": "722357edcc0e3757f0a87afdc3e9a50187e2aae4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Dynamic Programming Assignment/policy_evaluation_gridworld.py", "max_issues_repo_name": "me-manikanta/Move-37-Course", "max_issues_repo_head_hexsha": "722357edcc0e3757f0a87afdc3e9a50187e2aae4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dynamic Programming Assignment/policy_evaluation_gridworld.py", "max_forks_repo_name": "me-manikanta/Move-37-Course", "max_forks_repo_head_hexsha": "722357edcc0e3757f0a87afdc3e9a50187e2aae4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8275862069, "max_line_length": 103, "alphanum_fraction": 0.6102941176, "include": true, "reason": "import numpy", "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.9005297967961706, "lm_q1q2_score": 0.850259397682776}}
{"text": "#   # -*- coding: UTF-8 -*-\r\n#   trial on the : Satomi machine\r\n#   Created by Ush on 2018/3/16\r\n#   Project name :  Class3_FindingRoots \r\n#   Please contact CHIH, HSIN-CHING/D0631008 when expect to refer this source code.\r\n#   NOTE : no liability on any loss nor damage by using this source code. it is your own risk.\r\n\r\nimport numpy as np\r\nimport math\r\n\r\n\r\ndef FUNC(type, x):\r\n    F_select = 0\r\n    if (type == 1):  # function1 is f(x)=x^2-1\r\n        F_select = x ** 2 - 2\r\n    elif (type == 2):\r\n        F_select = x ** 5 + x ** 3 + 3\r\n    elif (type == 3):\r\n        F_select = x ** 3 - 2 * math.sin(x) - 1\r\n    elif (type == 4):\r\n        F_select = 0.5 * math.tan(x) - math.tanh(x)\r\n    else:\r\n        print(\"invalid function\")\r\n    return (float(F_select))\r\n\r\n\r\ndef Bisection(f, left, right, eps):\r\n    iteration = 0\r\n    while (math.fabs(right - left) > eps * math.fabs(right)):\r\n        middle = (left + right) / 2\r\n        if (np.sign(FUNC(f, middle)) == np.sign(FUNC(f, right))):\r\n            right = middle\r\n        else:  # root is  founded, move left = middle value\r\n            left = middle\r\n        iteration = iteration + 1\r\n        # print(iteration, \"\\t\", right, \"\\t\", FUNC(f, right))\r\n    return (right, iteration)\r\n\r\n\r\ndef Secant(f, left, right, eps):\r\n    iteration = 0\r\n    while (math.fabs(right - left) > eps * math.fabs(right)):\r\n        middle, left = left, right\r\n        right = right + ((right - middle) / ((FUNC(f, middle)) / (FUNC(f, right)) - 1))\r\n        iteration = iteration + 1\r\n        # print(iteration, left, FUNC(f, left), right, FUNC(f, right))\r\n    return (right, iteration)\r\n\r\n\r\n# IQI : Inverse Quadratic Interpolation\r\n# https://en.wikipedia.org/wiki/Inverse_quadratic_interpolation\r\n# https://nickcdryan.com/2017/09/13/root-finding-algorithms-in-python-line-search-bisection-secant-newton-raphson-boydens-inverse-quadratic-interpolation-brents/\r\ndef PolyInterp(f, p0, p1, p2):\r\n    a, b, c = FUNC(f, p0), FUNC(f, p1), FUNC(f, p2)\r\n    L0 = (p0 * b * c) / ((a - b) * (a - c))\r\n    L1 = (p1 * a * c) / ((b - a) * (b - c))\r\n    L2 = (p2 * b * a) / ((c - a) * (c - b))\r\n    return (L0 + L1 + L2)\r\n\r\n\r\ndef IQI(f, left, middle, right, eps):\r\n    iteration = 0\r\n    while (math.fabs(right - middle) > eps * math.fabs(right)):\r\n        x = PolyInterp(f, left, middle, right)\r\n        left, middle, right = middle, right, x\r\n        iteration = iteration + 1\r\n        # print(iteration, right, FUNC(f, right))\r\n    return (right, iteration)\r\n\r\n\r\n# https://en.wikipedia.org/wiki/Brent%27s_method#Dekker.27s_method\r\n# it is Dekker's method in 1969\r\n# https://blogs.mathworks.com/cleve/2015/10/12/zeroin-part-1-dekkers-algorithm/\r\n# https://cocalc.com/share/ab93d447b6728ae561bf1f9e18f0b103316d715f/Efficiency%20of%20Standard%20and%20Hybrid%20Root%20Finding%20Methods.sagews?viewer=share\r\ndef Mixed_Scant_Bisection(f, left, right, eps):\r\n    fa = FUNC(f, left)\r\n    fb = FUNC(f, right)\r\n    if (np.sign(fa) == np.sign(fb)):\r\n        print(\" Interval in \", left, \" and \", right, \" is in the same sign signal\")\r\n    #print(\"initial-value from :\", right, \"\\t\", fb)\r\n    #print(\"N-Type-Step\\t\\tbn\\t\\t\\t\\t\\t\\tf(bn) \")\r\n    iteration = 1\r\n    # left is the previous value of right and [right, middle] always contains the zero.\r\n    middle, fc = left, fa\r\n    while (math.fabs(right - left) > eps):\r\n        if (np.sign(fb) == np.sign(fc)):\r\n            middle, fc = left, fa\r\n        if (math.fabs(fc) < math.fabs(fb)):  # Swap to insure f(b) is the smallest value so far.\r\n            left, fa = right, fb\r\n            right, fb = middle, fc\r\n            middle, fc = left, fa\r\n        mid_point = float(right + middle) / 2  # BiSection ( Step1 )\r\n        # secant_left/secant_right is the the secant step.\r\n        secant_left = (right - left) * fb\r\n        if (secant_left >= 0):\r\n            secant_right = fa - fb  # swap like BiSection\r\n        else:\r\n            secant_right = -1 * (fa - fb)  # swap like BiSection\r\n            secant_left = -1 * secant_left\r\n        left, fa = right, fb  # prepare for the next iteration process points.\r\n        if (secant_left <= ((mid_point - right) * secant_right)):\r\n            right = right + (secant_left / secant_right)  # Secant\r\n            fb = FUNC(f, right)\r\n            #print(iteration, \"Secant-step\", right, \"\\t\", fb)\r\n        else:\r\n            right = mid_point  # BiSection\r\n            fb = FUNC(f, right)\r\n            #print(iteration, \"Bisect-step\", right, \"\\t\", fb)\r\n        iteration = iteration + 1\r\n    return (right, iteration)\r\n\r\n\r\n# https://cocalc.com/share/ab93d447b6728ae561bf1f9e18f0b103316d715f/Efficiency%20of%20Standard%20and%20Hybrid%20Root%20Finding%20Methods.sagews?viewer=share\r\ndef brentsMethod(f, a, b, accuracy):\r\n    '''\r\n    Code inspired by:\r\n    https://en.wikipedia.org/wiki/Brent's_method (The pseudocode was very helpful in translating this to Python)\r\n    http://blogs.mathworks.com/cleve/2015/10/26/zeroin-part-2-brents-version/\r\n    Function that computes an approximate root\r\n    for a given function using Dekker's method.\r\n    args:\r\n        f: a function\r\n        a, b: an initial value, most efficient when close to the root\r\n        iterations: number of times to run the loop\r\n    output:\r\n        a list that contains an approximate root s and the number\r\n        of iterations required\r\n    '''\r\n    fa = FUNC(f, a)\r\n    fb = FUNC(f, b)\r\n    # When this is set, we use the bisection method\r\n    bisection = True\r\n    if fa * fb >= 0:\r\n        raise Exception(\"Invalid inputs for a and b, require sign change\")\r\n    c = a\r\n    s = 0\r\n    d = 0\r\n    iteration = 0\r\n    while abs(b - a) > accuracy:\r\n        # quadratic interpolation\r\n        if (FUNC(f, a) != FUNC(f, c)) and (FUNC(f, b) != FUNC(f, c)):\r\n            s = PolyInterp(f, a, b, c)      # IQI core\r\n            #print(iteration, \"IQI-step\", s, \"\\t\", FUNC(f,s))\r\n        else:\r\n            s = ((a * FUNC(f, b)) - (b * FUNC(f, a))) / (FUNC(f, b) - FUNC(f, a))# secant\r\n            #print(iteration, \"Secant-step\", s, \"\\t\", FUNC(f, s))\r\n        if brentConditional(s, a, b, c, d, bisection, accuracy):\r\n            s = (a + b) / 2.0 # bisection\r\n            bisection = True\r\n        else:\r\n            bisection = False\r\n        d = c\r\n        c = b\r\n        if (FUNC(f, a) * FUNC(f, s) < 0):   #step (3a)\r\n            b = s\r\n            fb = FUNC(f, s)\r\n        else:\r\n            a = s\r\n            fa = FUNC(f, s)\r\n        if abs(fa) < abs(fb):\r\n            temp = a\r\n            a = b\r\n            b = temp\r\n            temp2 = fa\r\n            fa = fb\r\n            fb = temp2\r\n        iteration = iteration + 1\r\n    return (s, iteration)\r\n\r\n\r\ndef brentConditional(s, a, b, c, d, mflag, accuracy):\r\n    if ((s < (3 * a + b) * 0.25) or\r\n            (mflag and (abs(s - b) >= (abs(b - c) * 0.5)) or\r\n                 (not mflag and (abs(s - b) >= (abs(c - d) * 0.5)) or\r\n                      (mflag and (abs(b - c) < accuracy)) or\r\n                      (not mflag and (abs(c - d) < accuracy))))):\r\n        return True\r\n    return False\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import optimize\r\n\r\n\r\ndef f1(x):\r\n    return (x ** 2 - 2)\r\n\r\n\r\ndef main():\r\n    print\r\n    \"let's make it happen!\"\r\n    # eps function in matlab\r\n    # Python code expression : np.spacing(1)\r\n    eps = np.spacing(1)\r\n    eps = 1e-6\r\n    print(\"Python eps : \" + str(eps))\r\n\r\n    # formula 0\r\n    print(\"\\nFormula 0 : x ** 2 - 2 \\t\\t\\t (root, iteration times)\")\r\n    ITR, Root = Bisection(1, 1, 2, eps)\r\n    print(\"BiSection Result:\\t\\t\\t\\t\", Bisection(1, 1, 2, eps))\r\n    print(\"Secant Result:\\t\\t\\t\\t\\t\", Secant(1, 1, 2, eps))\r\n    print(\"IQI Result:\\t\\t\\t\\t\\t\\t\", IQI(1, 1, 1.5, 2, eps))\r\n    print(\"Mixed_Scant_Bisection Result:\\t\", Mixed_Scant_Bisection(1, 1, 2, eps))\r\n    print(\"Brent Result:\\t\\t\\t\\t\\t\", brentsMethod(1, 1, 2, eps))\r\n\r\n    # formula 1\r\n    print(\"\\nFormula 1 : x ** 5 + x ** 3 + 3  (root, iteration times)\")\r\n    print(\"BiSection Result:\\t\\t\\t\\t\", Bisection(2, -2, 0, eps))\r\n    print(\"Secant Result:\\t\\t\\t\\t\\t\", Secant(2, -2, 0, eps))\r\n    print(\"IQI Result:\\t\\t\\t\\t\\t\\t\", IQI(2, -2, -1, 0, eps))\r\n    print(\"Mixed_Scant_Bisection Result:\\t\", Mixed_Scant_Bisection(2, -2, 0, eps))\r\n    print(\"Brent Result:\\t\\t\\t\\t\\t\", brentsMethod(2, -2, 0, eps))\r\n\r\n    # formula 2\r\n    print(\"\\nFormula 2 : x ** 3 - 2 * math.sin(x) - 1\\t  (root, iteration times)\")\r\n    print(\"BiSection Result:\\t\\t\\t\\t\", Bisection(3, 0, 2, eps))\r\n    print(\"Secant Result:\\t\\t\\t\\t\\t\", Secant(3, 0, 2, eps))\r\n    print(\"IQI Result:\\t\\t\\t\\t\\t\\t\", IQI(3, 0, 1, 2, eps))\r\n    print(\"Mixed_Scant_Bisection Result:\\t\", Mixed_Scant_Bisection(3, 0, 2, eps))\r\n    print(\"Brent Result:\\t\\t\\t\\t\\t\", brentsMethod(3, 0, 2, eps))\r\n\r\n    # formula 3\r\n    print(\"\\nFormula 3 : 0.5 * math.tan(x) - math.tanh(x)\\t  (root, iteration times)\")\r\n    A = 1e-3\r\n    B = math.pi / 2\r\n    print(\"BiSection Result:\\t\\t\\t\\t\", Bisection(4, A, B, eps))\r\n    print(\"Secant Result:\\t\\t\\t\\t\\t\", Secant(4, A, B, eps))\r\n    print(\"IQI Result:\\t\\t\\t\\t\\t\\t\", IQI(4, A, B, B, eps))\r\n    print(\"Mixed_Scant_Bisection Result:\\t\", Mixed_Scant_Bisection(4, A, B, eps))\r\n    print(\"Brent Result:\\t\\t\\t\\t\\t\", brentsMethod(4, A, B, eps))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n", "meta": {"hexsha": "eb6b7d195083860aac67613c6b202ab77f4cc21f", "size": 9209, "ext": "py", "lang": "Python", "max_stars_repo_path": "Class03_FindingRoots.py", "max_stars_repo_name": "jasperchih/Numerical-Analysis", "max_stars_repo_head_hexsha": "29f782a91e2a58990fd259b1bd95a6143facc375", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-13T06:46:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T01:26:50.000Z", "max_issues_repo_path": "Class03_FindingRoots.py", "max_issues_repo_name": "jasperchih/Numerical-Analysis", "max_issues_repo_head_hexsha": "29f782a91e2a58990fd259b1bd95a6143facc375", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Class03_FindingRoots.py", "max_forks_repo_name": "jasperchih/Numerical-Analysis", "max_forks_repo_head_hexsha": "29f782a91e2a58990fd259b1bd95a6143facc375", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-23T01:23:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-24T01:26:53.000Z", "avg_line_length": 39.0211864407, "max_line_length": 162, "alphanum_fraction": 0.5551091324, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.9005297834483234, "lm_q1q2_score": 0.8502593822509639}}
{"text": "import numpy as np\n\n\nclass Secant(object):\n    def __init__(self, f=None, **extras):\n        \"\"\"\n        f : a function f(x) that returns 'y', the function applied to it\n        \"\"\"\n        self.f = f\n\n    def solve(self, init_a=None, init_b=None, tol=None, max_it=50, **extras):\n        \"\"\"fast implementation of the secant method\n        init_a : bottom bound of the initial interval\n        init_b : top bound of the initial interval\n        tol : maximum absolute error after which the method should stop. (e.g. 1e-15)\n        max_it : maximum number of iterations after which the method should stop\n        \"\"\"\n        xo = init_a\n        x = init_b\n        xn = 0\n        \n        i = 0\n        while i < max_it:\n            xn = x - ( self.f(x) * (x - xo) ) / ( self.f(x) - self.f(xo) )\n            if abs(xn - x) < tol:\n                break\n            xo = x\n            x = xn\n            i+=1\n        return x\n\n\n    def vsolve(self, init_a=None, init_b=None, tol=None, max_it=50, **extras):\n        \"\"\"verbose implementation of the secant method\n        init_a : first iteration estimate\n        init_b : second iteration estimate\n        tol : maximum absolute error after which the method should stop. (e.g. 1e-15)\n        max_it : maximum number of iterations after which the method should stop\n        \"\"\"\n        \n        xo = init_a\n        x = init_b\n        xn = 0\n        i = 0\n        iteration_list = []\n        dist_list = []\n        estimate_list = []\n\n        while i < max_it:\n            dist = abs(x-xo)\n            iteration_list.append(i)\n            dist_list.append(dist)\n            estimate_list.append(x)\n            xn = x - ( self.f(x) * (x - xo) ) / ( self.f(x) - self.f(xo) )\n            \n            if abs(xn - x) < tol:\n                break\n\n            xo = x\n            x = xn\n            i+=1\n\n        return iteration_list, estimate_list, dist_list\n\n    \n    def __repr__(self):\n        # return \"Secant \"\n        raise NotImplementedError\n    \n\n    def __str__(self):\n        return \"Secant method\"", "meta": {"hexsha": "271ec1d45c88b1f709e0f01795be1730bd7e183b", "size": 2048, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/methods/secant.py", "max_stars_repo_name": "Aculisme/zero_algorithms", "max_stars_repo_head_hexsha": "3b5c80bdb663dade07578e010aeffd3aa501fdf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-06-30T15:30:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-30T15:36:30.000Z", "max_issues_repo_path": "src/methods/secant.py", "max_issues_repo_name": "Aculisme/zero_algorithms", "max_issues_repo_head_hexsha": "3b5c80bdb663dade07578e010aeffd3aa501fdf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/methods/secant.py", "max_forks_repo_name": "Aculisme/zero_algorithms", "max_forks_repo_head_hexsha": "3b5c80bdb663dade07578e010aeffd3aa501fdf1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4444444444, "max_line_length": 85, "alphanum_fraction": 0.5146484375, "include": true, "reason": "import numpy", "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653855, "lm_q2_score": 0.9005297834483234, "lm_q1q2_score": 0.8502593822509638}}
{"text": "import numpy as np\nimport time\nimport scipy.linalg\n\ndef GENP(A, b):\n\n    n =  len(A)\n    if b.size != n:\n        raise ValueError(\"Invalid argument\", b.size, n)\n    for pivot_row in xrange(n-1):\n        for row in xrange(pivot_row+1, n):\n            multiplier = A[row][pivot_row]/A[pivot_row][pivot_row]\n            A[row][pivot_row] = multiplier\n            for col in xrange(pivot_row + 1, n):\n                A[row][col] = A[row][col] - multiplier*A[pivot_row][col]\n\n            b[row] = b[row] - multiplier*b[pivot_row]\n    print A\n    print b\n    x = np.zeros(n)\n    k = n-1\n    x[k] = b[k]/A[k,k]\n    while k >= 0:\n        x[k] = (b[k] - np.dot(A[k,k+1:],x[k+1:]))/A[k,k]\n        k = k-1\n    return x\n\n\ndef GEPP(A, b):\n\n    n =  len(A)\n    if b.size != n:\n        raise ValueError(\"Invalid argument\", b.size, n)\n\n    for k in xrange(n-1):\n        maxindex = abs(A[k:,k]).argmax() + k\n        if A[maxindex, k] == 0:\n            raise ValueError(\"singular\")\n        #Swap rows\n        if maxindex != k:\n            A[[k,maxindex]] = A[[maxindex, k]]\n            b[[k,maxindex]] = b[[maxindex, k]]\n        for row in xrange(k+1, n):\n            multiplier = A[row][k]/A[k][k]\n\n            A[row][k] = multiplier\n            for col in xrange(k + 1, n):\n                A[row][col] = A[row][col] - multiplier*A[k][col]\n\n            b[row] = b[row] - multiplier*b[k]\n    print A\n    print b\n    x = np.zeros(n)\n    k = n-1\n    x[k] = b[k]/A[k,k]\n    while k >= 0:\n        x[k] = (b[k] - np.dot(A[k,k+1:],x[k+1:]))/A[k,k]\n        k = k-1\n    return x\n\nif __name__ == \"__main__\":\n    A = np.array([[1e-20,0.,1.],\n                  [1,1e+20,1.],\n                  [0,1,-1],\n                  ])\n    b =  np.array([[0.],[0.],[1.]])\n    print GENP(np.copy(A), np.copy(b))\n    print GEPP(A,b)\n    print '\\n\\nresidual', scipy.linalg.norm(np.dot(A, GEPP(A,b)) - b)/scipy.linalg.norm(A)\n    tic = time.clock()\n    toc = time.clock()\n    print \"Processing time is : %f\" %(toc - tic)\n", "meta": {"hexsha": "1a23b039cc40e7c6f24c8a1442efcf494bc50da1", "size": 1976, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assingment #1/GEPP/matrix3.py", "max_stars_repo_name": "rezaghanbari/Numerical-Linear-algebra-Assignment-1", "max_stars_repo_head_hexsha": "014619a057d7371177a6ac6b33e20fe06adbe8b4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assingment #1/GEPP/matrix3.py", "max_issues_repo_name": "rezaghanbari/Numerical-Linear-algebra-Assignment-1", "max_issues_repo_head_hexsha": "014619a057d7371177a6ac6b33e20fe06adbe8b4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assingment #1/GEPP/matrix3.py", "max_forks_repo_name": "rezaghanbari/Numerical-Linear-algebra-Assignment-1", "max_forks_repo_head_hexsha": "014619a057d7371177a6ac6b33e20fe06adbe8b4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0684931507, "max_line_length": 90, "alphanum_fraction": 0.4741902834, "include": true, "reason": "import numpy,import scipy", "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.9005297854505004, "lm_q1q2_score": 0.8502593798977472}}
{"text": "import numpy as np\n\ndef sigmoid(Z):\n    return 1/(1+np.exp(-Z))\n\ndef hard_sigmoid(Z):\n    y = 0.2 * Z + 0.5\n    return np.clip(y, 0, 1)\n\n\ndef relu(Z):\n    return (Z > 0) * Z\n\ndef softmax(Z):\n    e_x = np.exp(Z - np.max(Z))\n    return e_x / e_x.sum(axis = 1)\n\ndef backward_sigmoid(a):\n    return a * (1 - a)\n\ndef backward_tanh(Z):\n    return 1-(np.tanh(Z))**2\n\ndef backward_relu(Z):\n    mul = np.ones(Z.shape)\n    return (Z > 0) * mul\n\ndef backward_softmax(t_hat, i):\n    t_hat[i] = t_hat[i] - 1\n    return t_hat\n\n# based on keras drop out\ndef dropout(input, level):\n    noise_shape = input.shape # (Tx, n_a)\n    noise = np.random.choice([0,1], noise_shape, replace = True, p=[level, 1-level])\n    return input * noise / (1 - level), noise / (1 - level)\n", "meta": {"hexsha": "493297a2a76989a2b668e1fd0a1d725f1f93b68c", "size": 753, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/functions/activations.py", "max_stars_repo_name": "jakelong0509/Song_Detector", "max_stars_repo_head_hexsha": "57ac4b206b985f2c9e40423a9f79deacbc88f64e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-11-09T17:56:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-15T19:43:58.000Z", "max_issues_repo_path": "python/functions/activations.py", "max_issues_repo_name": "jakelong0509/Song_Detector", "max_issues_repo_head_hexsha": "57ac4b206b985f2c9e40423a9f79deacbc88f64e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-11-09T17:45:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-09T23:12:21.000Z", "max_forks_repo_path": "python/functions/activations.py", "max_forks_repo_name": "jakelong0509/Song_Detector", "max_forks_repo_head_hexsha": "57ac4b206b985f2c9e40423a9f79deacbc88f64e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3513513514, "max_line_length": 84, "alphanum_fraction": 0.5922974768, "include": true, "reason": "import numpy", "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.888758801595206, "lm_q1q2_score": 0.850217068453221}}
{"text": "import torch\nimport numpy as np\nimport matplotlib.pylab as plt\n\n\ndef numerical_diff(f, x):\n    h = 1e-4\n    return (f(x + h) - f(x)) / h\n\n\ndef function_1(x):\n    return 0.01 * x **2 + 0.1 * x\n\n\nx = np.arange(0.0, 20.0, 0.1)\ny = function_1(x)\nplt.xlabel(\"x\")\nplt.ylabel(\"f(x)\")\nplt.plot(x, y)\nplt.show()\n\nprint(numerical_diff(function_1, 5))\nprint(numerical_diff(function_1, 10))\nprint(\"---------------------------------------------------\")\n\ndef function_2(x):\n    return x[0] ** 2 + x[1] ** 2\n\n\n# center numerical diff\ndef numerical_gradient(f, x):\n    h = 1e-4\n    grad = torch.zeros_like(x)\n\n    for idx in range(x.size()[0]):\n        tmp_val = x[idx].item()\n\n        x[idx] = tmp_val + h\n        fxh1 = f(x)\n\n        x[idx] = tmp_val - h\n        fxh2 = f(x)\n\n        grad[idx] = (fxh1 - fxh2) / (2*h)\n        x[idx] = tmp_val\n\n    return grad\n#\n#\n# print(numerical_gradient(function_2, torch.tensor([3.0, 4.0])))\n# print(numerical_gradient(function_2, torch.tensor([0.0, 2.0])))\n# print(numerical_gradient(function_2, torch.tensor([3.0, 0.0])))\n# print(\"---------------------------------------------------\")\n\ndef numpy_numerical_gradient(f, x):\n    h = 1e-4\n    grad = np.zeros_like(x)\n\n    for idx in range(x.size):\n        tmp_val = x[idx]\n\n        x[idx] = tmp_val + h\n        fxh1 = f(x)\n\n        x[idx] = tmp_val - h\n        fxh2 = f(x)\n\n        grad[idx] = (fxh1 - fxh2) / (2*h)\n        x[idx] = tmp_val\n\n    return grad\n\n\nprint(numpy_numerical_gradient(function_2, np.array([3.0, 4.0])))\nprint(numpy_numerical_gradient(function_2, np.array([0.0, 2.0])))\nprint(numpy_numerical_gradient(function_2, np.array([3.0, 0.0])))\n\n# gradient descent\ndef numpy_gradient_descent(f, init_x, lr=0.001, step_num=100):\n    x = init_x\n\n    for i in range(step_num):\n        # grad = numerical_gradient(f, x)\n        grad = numpy_numerical_gradient(f, x)\n        x -= lr * grad\n\n    return x\n\n\ninit_x = np.array([-3.0, 4.0])\nprint(numpy_gradient_descent(function_2, init_x, lr=10.0, step_num=100))\n\n\ndef gradient_descent(f, init_x, lr=0.001, step_num=100):\n    x = init_x\n\n    for i in range(step_num):\n        grad = numerical_gradient(f, x)\n        x -= lr * grad\n\n    return x\n\n\ninit_x = torch.tensor([-3.0, 4.0], dtype=torch.float64)\nprint(gradient_descent(function_2, init_x, lr=0.1, step_num=100))\nprint(\"---------------------------------------------------\")\n\nprint(gradient_descent(function_2, init_x, lr=10.0, step_num=100))\nprint(gradient_descent(function_2, init_x, lr=1e-10, step_num=100))\nprint(\"---------------------------------------------------\")", "meta": {"hexsha": "32b4a869e732244d29b918f3389ab41e31d987f4", "size": 2553, "ext": "py", "lang": "Python", "max_stars_repo_path": "Deep_Learning_from_Scratch/ch04/NumericalDiff.py", "max_stars_repo_name": "H-BlackGom/Study-HR", "max_stars_repo_head_hexsha": "1dc5ab6ac3b382765b342b7bb35c2c5c69ba23e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Deep_Learning_from_Scratch/ch04/NumericalDiff.py", "max_issues_repo_name": "H-BlackGom/Study-HR", "max_issues_repo_head_hexsha": "1dc5ab6ac3b382765b342b7bb35c2c5c69ba23e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Deep_Learning_from_Scratch/ch04/NumericalDiff.py", "max_forks_repo_name": "H-BlackGom/Study-HR", "max_forks_repo_head_hexsha": "1dc5ab6ac3b382765b342b7bb35c2c5c69ba23e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2090909091, "max_line_length": 72, "alphanum_fraction": 0.5663924794, "include": true, "reason": "import numpy", "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360932, "lm_q2_score": 0.8887588023318196, "lm_q1q2_score": 0.8502170669602471}}
{"text": "\nimport numpy as np\nimport math\n\nfrom .utils import *\n\n # A lot of comments and documentation is directly copied from Raphael Vallat (https://github.com/raphaelvallat/entropy)\n\n \n# Permutation Entropy\n\"\"\"Permutation Entropy.\n\n  \n  Parameters\n  ----------\n  x : np.array\n      One-dimensional time series of shape (n_times)\n  order : int\n      Order of permutation entropy. Default is 3.\n  delay : int\n      Time delay (lag). Default is 1.\n  normalize : bool\n      If True, divide by log2(order!) to normalize the entropy between 0\n      and 1. Otherwise, return the permutation entropy in bit. Default is true.\n  Returns\n  -------\n  pe : float\n      Permutation Entropy.\n  Notes\n  -----\n  The permutation entropy is a complexity measure for time-series first\n  introduced by Bandt and Pompe in 2002.\n  The permutation entropy of a signal :math:`x` is defined as:\n  .. math:: H = -\\\\sum p(\\\\pi)\\\\log_2(\\\\pi)\n  where the sum runs over all :math:`n!` permutations :math:`\\\\pi` of order\n  :math:`n`. This is the information contained in comparing :math:`n`\n  consecutive values of the time series. It is clear that\n  :math:`0 ≤ H (n) ≤ \\\\log_2(n!)` where the lower bound is attained for an\n  increasing or decreasing sequence of values, and the upper bound for a\n  completely random system where all :math:`n!` possible permutations appear\n  with the same probability.\n  The embedded matrix :math:`Y` is created by:\n  .. math::\n      y(i)=[x_i,x_{i+\\\\text{delay}}, ...,x_{i+(\\\\text{order}-1) *\n      \\\\text{delay}}]\n  .. math:: Y=[y(1),y(2),...,y(N-(\\\\text{order}-1))*\\\\text{delay})]^T\n  References\n  ----------\n  Bandt, Christoph, and Bernd Pompe. \"Permutation entropy: a\n  natural complexity measure for time series.\" Physical review letters\n  88.17 (2002): 174102.\n  Examples\n  --------\n  Permutation entropy with order 2\n  >>> from OrdinalEntroPy import *\n  >>> import numpy as np\n  >>> x = [4, 7, 9, 10, 6, 11, 3]\n  >>> # Return a value in bit between 0 and log2(factorial(order))\n  >>> print(PE(x, order=2, normalize=False))\n  0.9182958340544896\n  Normalized permutation entropy with order 3\n  >>> from OrdinalEntroPy import *\n  >>> import numpy as np\n  >>> x = [4, 7, 9, 10, 6, 11, 3]\n  >>> # Return a value comprised between 0 and 1.\n  >>> print(PE(x, order=3, normalize=True))\n  0.5887621559162939\n\"\"\"\ndef PE(values,order=3,delay=1,normalize=True):\n\n  # get all the permuations\n  str_permutations = get_str_permutation_ordinal(values,order,delay)\n  \n  # get set of indices for each unique permutation\n  permutation_indexes = get_permutation_index(str_permutations)\n\n  # get frequency of each permutation pattern\n  permutation_frequency = get_permutation_frequency(permutation_indexes,len(values),order)\n\n  # get shannon entropy of frequencies\n  entropy = get_shanon_entropy(permutation_frequency)\n  \n  #Normalize\n  if normalize:\n    entropy = entropy/math.log2(math.factorial(order))\n\n  return entropy\n\n\n\n\"\"\"Dispersion Entropy.\n\n  \n  Parameters\n  ----------\n  x : np.array\n      One-dimensional time series of shape (n_times)\n  order : int\n      Order of permutation entropy. Default is 3.\n  classes : int\n      Number of classes. Default is 3.\n  delay : int\n      Time delay (lag). Default is 1.\n  normalize : bool\n      If True, divide by log2(classes**order) to normalize the entropy between 0\n      and 1. Otherwise, return the permutation entropy in bit. Default is true.\n  Returns\n  -------\n  pe : float\n      Permutation Entropy.\n  Notes\n  -----\n  Dispersion Entropy (DE) was introduced in the year 2016 by Azami and Rostaghi\n  to quantify the complexity of time series.\n  The Dispersion entropy of a signal :math:`x` is defined as:\n  .. math:: H = -\\\\sum p(\\\\pi)\\\\log_2(\\\\pi)\n  where the sum runs over all :math:`classes**order` permutations :math:`\\\\pi` of order\n  :math:`n` and consisting of classes :math:`c`. This is the information contained in comparing :math:`n`\n  consecutive values of the time series. It is clear that\n  :math:`0 ≤ H (n) ≤ \\\\log_2(classes^order)` where the lower bound is attained for an\n  increasing or decreasing sequence of values, and the upper bound for a\n  completely random system where all :math:`classes**order` possible dispersion patterns appear\n  with the same probability.\n  The embedded matrix :math:`Y` is created by:\n  .. math::\n      y(i)=[x_i,x_{i+\\\\text{delay}}, ...,x_{i+(\\\\text{order}-1) *\n      \\\\text{delay}}]\n  .. math:: Y=[y(1),y(2),...,y(N-(\\\\text{order}-1))*\\\\text{delay})]^T\n  References\n  ----------\n  M. Rostaghi and H. Azami, \"Dispersion Entropy: A Measure for Time-Series Analysis,\" \n  in IEEE Signal Processing Letters, vol. 23, no. 5, pp. 610-614, May 2016, doi: 10.1109/LSP.2016.2542881.\n  Examples\n  --------\n  Dispersion entropy with order=3 and classes=3 \n  >>> from OrdinalEntroPy import *\n  >>> import numpy as np\n  >>> np.random.seed(1234567)\n  >>> x = np.random.rand(3000)\n  >>> # Return a value in bit between 0 and log2(factorial(order))\n  >>> print(DE(x, order=3,classes=3,normalize=True))\n  0.9830685145488814\n\"\"\"\n\n# Dispersion Entropy\ndef DE(values,order=3,classes=3,delay=1,normalize=True):\n  # map TS to classes using cummulative distributive function\n  mapped_values = get_ncdf_values(values,classes)\n  # get all the permuations\n  str_permutations = get_str_permutation(mapped_values,order,delay)\n  \n  # get set of indices for each unique permutation\n  permutation_indexes = get_permutation_index(str_permutations)\n\n  # get frequency of each permutation pattern\n  permutation_frequency = get_permutation_frequency(permutation_indexes,len(values),order)\n\n  # get shannon entropy of frequencies\n  entropy = get_shanon_entropy(permutation_frequency)\n  if normalize:\n    entropy = entropy/math.log2(classes**order)\n\n  return entropy\n\n\n# Reverse Dispersion Entropy\ndef RDE(values,order=3,classes=3,delay=1,normalize=True):\n  mapped_values = get_ncdf_values(values,classes)\n  # get all the permuations\n  str_permutations = get_str_permutation(mapped_values,order,delay)\n  \n  permutation_indexes = get_permutation_index(str_permutations)\n\n  permutation_frequency = get_permutation_frequency(permutation_indexes,len(values),order)\n\n  entropy = np.square(permutation_frequency).sum() - (1/(classes**order))\n  if normalize:\n    entropy = entropy/(1 - (1/(classes**order)))\n  \n  return entropy\n\n\n# Reverse Permutation Entropy\ndef RPE(values,order=3,delay=1,normalize=True):\n  str_permutations = get_str_permutation_ordinal(values,order,delay)\n  \n  permutation_indexes = get_permutation_index(str_permutations)\n  #print(set(str_permutations))\n\n  permutation_frequency = get_permutation_frequency(permutation_indexes,len(values),order)\n  #print(permutation_frequency)\n  entropy = np.square(permutation_frequency).sum() - (1/math.factorial(order))\n  if normalize:\n    entropy = entropy/(1 - (1/math.factorial(order)))\n  \n  return entropy\n\n\n# Weighted Permutation Entropy\ndef WPE(values,order=3,delay=1,normalize=True):\n  weights = get_weights(values,order,delay)\n\n  str_permutations = get_str_permutation_ordinal(values,order,delay)\n  \n  permutation_indexes = get_permutation_index(str_permutations)\n\n  weighted_permutations = cal_weighted_permutations(np.array(weights),permutation_indexes)\n  \n  entropy = get_shanon_entropy(weighted_permutations)\n\n  if normalize:\n    entropy = entropy/math.log2(math.factorial(order))\n\n  return entropy\n\n\n  # Reverse Weighted Permutation Entropy\ndef RWPE(values,order,delay=1,normalize=True):\n  weights = get_weights(values,order,delay)\n\n  str_permutations = get_str_permutation_ordinal(values,order,delay)\n  \n  permutation_indexes = get_permutation_index(str_permutations)\n\n  weighted_permutations = cal_weighted_permutations(np.array(weights),permutation_indexes)\n  \n  entropy = np.square(weighted_permutations).sum() - (1/math.factorial(order))\n  if normalize:\n    entropy = entropy/(1 - (1/math.factorial(order)))\n  \n  return entropy\n\n\n\n# Reverse weighted Dispersion Entropy\ndef RWDE(values,order,classes,delay=1,normalize=True):\n  # find variance of each permutation\n  weights = get_weights(values,order,delay)\n  # convert values with NCDF and assign them class\n  mapped_values = get_ncdf_values(values,classes)\n  # get all the permuations\n  str_permutations = get_str_permutation(mapped_values,order,delay)\n  \n  #find the indices of a permutation\n  permutation_indexes = get_permutation_index(str_permutations)\n  \n  # get the weight for each permutation\n  weighted_permutations = cal_weighted_permutations(np.array(weights),permutation_indexes)\n  \n  entropy = np.square(weighted_permutations).sum() - (1/(classes**order))\n  # calculate final RWDE entropy\n  if normalize:\n    entropy = entropy/(1 - (1/(classes**order)))\n   \n  return entropy", "meta": {"hexsha": "c8da43de2c0f6748a894bdb243d2fb43f22f1a23", "size": 8657, "ext": "py", "lang": "Python", "max_stars_repo_path": "OrdinalEntroPy/OrdinalEntroPy.py", "max_stars_repo_name": "pradyot-09/OrdinalEntroPy", "max_stars_repo_head_hexsha": "3c813485eeb596d21e97c2a2febcac46b2dfcf5c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-02-24T01:06:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:24:53.000Z", "max_issues_repo_path": "OrdinalEntroPy/OrdinalEntroPy.py", "max_issues_repo_name": "pradyot-09/OrdinalEntroPy", "max_issues_repo_head_hexsha": "3c813485eeb596d21e97c2a2febcac46b2dfcf5c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OrdinalEntroPy/OrdinalEntroPy.py", "max_forks_repo_name": "pradyot-09/OrdinalEntroPy", "max_forks_repo_head_hexsha": "3c813485eeb596d21e97c2a2febcac46b2dfcf5c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9490196078, "max_line_length": 120, "alphanum_fraction": 0.7208039737, "include": true, "reason": "import numpy", "num_tokens": 2281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.8887588038050466, "lm_q1q2_score": 0.8502170650731208}}
{"text": "import numpy as np\nfrom scipy import linalg\nfrom numpy import dot\n\ndef nmf(X, latent_features, max_iter=100, error_limit=1e-6, fit_error_limit=1e-6):\n\t\"\"\"\n\tDecompose X to A*Y\n\t\"\"\"\n\teps = 1e-5\n\tprint 'Starting NMF decomposition with {} latent features and {} iterations.'.format(latent_features, max_iter)\n\t#X = X.toarray()  # I am passing in a scipy sparse matrix\n\n\t# mask\n\tmask = np.sign(X)\n\trows, columns = X.shape\n\tA = np.random.rand(rows, latent_features)\n\tA = np.maximum(A, eps)\n\n\tY = linalg.lstsq(A, X)[0]\n\tY = np.maximum(Y, eps)\n\n\tmasked_X = mask * X\n\tX_est_prev = dot(A, Y)\n\tfor i in range(1, max_iter + 1):\n\t\ttop = dot(masked_X, Y.T)\n\t\tbottom = (dot((mask * dot(A, Y)), Y.T)) + eps\n\t\tA *= top / bottom\n\n\t\tA = np.maximum(A, eps)\n\t\ttop = dot(A.T, masked_X)\n\t\tbottom = dot(A.T, mask * dot(A, Y)) + eps\n\t\tY *= top / bottom\n\t\tY = np.maximum(Y, eps)\n\t\tif i % 5 == 0 or i == 1 or i == max_iter:\n\t\t\tprint 'Iteration {}:'.format(i),\n\t\t\tX_est = dot(A, Y)\n\t\t\terr = mask * (X_est_prev - X_est)\n\t\t\tfit_residual = np.sqrt(np.sum(err ** 2))\n\t\t\tX_est_prev = X_est\n\t\t\tcurRes = linalg.norm(mask * (X - X_est), ord='fro')\n\t\t\tprint 'fit residual', np.round(fit_residual, 4),\n\t\t\tprint 'total residual', np.round(curRes, 4)\n\t\t\tif curRes < error_limit or fit_residual < fit_error_limit:\n\t\t\t\tbreak\n\treturn A, Y\n\n\nif __name__ == \"__main__\":\n    R = [\n         [5,3,0,1],\n         [4,0,0,1],\n         [1,1,0,5],\n         [1,0,0,4],\n         [0,1,5,4],\n        ]\n\t\n    R = np.array(R)\n    print R\n\n    nP, nQ = nmf(R, 2)\n    print np.dot(nP, nQ)\n\t# To restore R, execute numpy.dot(np, nQ.T)\n\n", "meta": {"hexsha": "b4be0905546539bd1b6d49fc6e449d6a52d55dd5", "size": 1574, "ext": "py", "lang": "Python", "max_stars_repo_path": "non_matrix.py", "max_stars_repo_name": "ccweikui/TensorFactorization", "max_stars_repo_head_hexsha": "1e7aaa39b31e98992cdddcf2b562e8a02ade6910", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2016-04-11T07:28:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T07:56:30.000Z", "max_issues_repo_path": "non_matrix.py", "max_issues_repo_name": "ccweikui/TensorFactorization", "max_issues_repo_head_hexsha": "1e7aaa39b31e98992cdddcf2b562e8a02ade6910", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "non_matrix.py", "max_forks_repo_name": "ccweikui/TensorFactorization", "max_forks_repo_head_hexsha": "1e7aaa39b31e98992cdddcf2b562e8a02ade6910", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-06-01T15:49:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-09T08:36:10.000Z", "avg_line_length": 24.59375, "max_line_length": 112, "alphanum_fraction": 0.5921219822, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997376, "lm_q2_score": 0.8887587905460026, "lm_q1q2_score": 0.8502170545867096}}
{"text": "#coding:utf8\nimport numpy as np\n\ndef sigmoid(x):\n    \"\"\"\n    Compute the sigmoid of x\n\n    Arguments:\n    x -- A scalar or numpy array of any size\n\n    Return:\n    s -- sigmoid(x)\n    \"\"\"\n    s = 1 / (1 + np.exp(-x))\n    return s\n\n\ndef sigmoid_derivative(x):\n    \"\"\"\n    Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x.\n    You can store the output of the sigmoid function into variables and then use it to calculate the gradient.\n\n    Arguments:\n    x -- A scalar or numpy array\n\n    Return:\n    ds -- Your computed gradient.\n    \"\"\"\n    s = sigmoid(x)\n    ds = s * (1 - s)\n    return ds\n\n\n# GRADED FUNCTION: image2vector\ndef image2vector(image):\n    \"\"\"\n    Argument:\n    image -- a numpy array of shape (length, height, depth)\n\n    Returns:\n    v -- a vector of shape (length*height*depth, 1)\n    \"\"\"\n    v = image.reshape((image.shape[0] * image.shape[1] * image.shape[2]), 1)\n\n    return v\n\n\n# GRADED FUNCTION: normalizeRows\n\ndef normalizeRows(x):\n    \"\"\"\n    Implement a function that normalizes each row of the matrix x (to have unit length).\n\n    Argument:\n    x -- A numpy matrix of shape (n, m)\n\n    Returns:\n    x -- The normalized (by row) numpy matrix. You are allowed to modify x.\n    \"\"\"\n    # Compute x_norm as the norm 2 of x. Use np.linalg.norm(..., ord = 2, axis = ..., keepdims = True)\n    # keepdims is keep the np.dims, in this case, [2, 3] will become [2, 1], but not [2, ]\n    x_norm = np.linalg.norm(x, ord=2, axis=1, keepdims=True)\n    # x_norm = np.linalg.norm(x, ord = 2, axis = 1)\n    # print(x_norm.shape)\n    # Divide x by its norm.\n    x = x / x_norm\n    return x\n\n\n# GRADED FUNCTION: softmax\n\ndef softmax(x):\n    \"\"\"Calculates the softmax for each row of the input x.\n\n    Your code should work for a row vector and also for matrices of shape (n, m).\n\n    Argument:\n    x -- A numpy matrix of shape (n,m)\n\n    Returns:\n    s -- A numpy matrix equal to the softmax of x, of shape (n,m)\n    \"\"\"\n    # Apply exp() element-wise to x. Use np.exp(...).\n    x_exp = np.exp(x)\n    # Create a vector x_sum that sums each row of x_exp. Use np.sum(..., axis = 1, keepdims = True).\n    x_sum = np.sum(x_exp, axis=1, keepdims=True)\n    # Compute softmax(x) by dividing x_exp by x_sum. It should automatically use numpy broadcasting.\n    s = x_exp / x_sum\n    # print(\"x_exp: {}, x_sum: {}\".format(x_exp.shape, x_sum.shape))\n\n\n    return s\n\n# The loss is used to evaluate the performance of your model. The bigger your loss is,\n# the more different your predictions ($ \\hat{y} $) are from the true values ($y$). In deep learning,\n# you use optimization algorithms like Gradient Descent to train your model and to minimize the cost.\n# GRADED FUNCTION: L1\n# L1正则\ndef L1(yhat, y):\n    \"\"\"\n    Arguments:\n    yhat -- vector of size m (predicted labels)\n    y -- vector of size m (true labels)\n\n    Returns:\n    loss -- the value of the L1 loss function defined above\n    \"\"\"\n    ### START CODE HERE ### (≈ 1 line of code)\n    loss = np.sum(np.abs(yhat - y), axis=0)\n    ### END CODE HERE ###\n\n    return loss\n\n\n# GRADED FUNCTION: L2\n\ndef L2(yhat, y):\n    \"\"\"\n    Arguments:\n    yhat -- vector of size m (predicted labels)\n    y -- vector of size m (true labels)\n\n    Returns:\n    loss -- the value of the L2 loss function defined above\n    \"\"\"\n    loss = np.dot(abs(y - yhat), abs(y - yhat).T)\n    # loss = np.square(np.linalg.norm(abs(y - yhat), ord = 2, axis = 0))\n    return loss", "meta": {"hexsha": "5128b26d606449b00ab917336a49bdeb6fdce6c1", "size": 3460, "ext": "py", "lang": "Python", "max_stars_repo_path": "DeepLearning/utils.py", "max_stars_repo_name": "excelsimon/AI", "max_stars_repo_head_hexsha": "a54da940a1b47eb7d6fd921052932345eb12aeb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 119, "max_stars_repo_stars_event_min_datetime": "2017-10-11T08:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T04:57:15.000Z", "max_issues_repo_path": "DeepLearning/utils.py", "max_issues_repo_name": "excelsimon/AI", "max_issues_repo_head_hexsha": "a54da940a1b47eb7d6fd921052932345eb12aeb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DeepLearning/utils.py", "max_forks_repo_name": "excelsimon/AI", "max_forks_repo_head_hexsha": "a54da940a1b47eb7d6fd921052932345eb12aeb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 40, "max_forks_repo_forks_event_min_datetime": "2017-11-21T11:34:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T12:45:12.000Z", "avg_line_length": 27.03125, "max_line_length": 115, "alphanum_fraction": 0.623699422, "include": true, "reason": "import numpy", "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.9099070133672955, "lm_q1q2_score": 0.850212708327835}}
{"text": "import math\nfrom scipy.special import erf\nfrom numpy import poly1d\nfrom numpy import pi, sin, linspace\nfrom numpy import exp, cos\n\n# scipy erfc does not support complex numbers but erf does\ndef erfc(z):\n        if z == complex(0,0):\n          return 1.0\n        else:\n          return 1.0-erf(z)  \n\n\ndef analytic_solution_simple(t, x, a_0, L, g, eta): # time, x_value, initial maximum perturbation (at the very left), wavelength, gravity, viscosity\n        k= 2*pi/L # wave number 2pi/wavelength \n        gamma=2*eta*k**2\n        a=a_0*cos(pi*x)        \n        return a*exp(-gamma*t)\n\n\n\n# Formulas were compared with the same formula hacked into matlab\n# based on \n# Motion of two superposed viscous fluids\n# A Prosperetti - Physics of Fluids, 1981 \n# doi:10.1063/1.863522\n# assumes that fluid in the tank has same viscosity as fluid above\ndef analytic_solution(t, x, a_0, L, g, eta): # time, x_value, initial maximum perturbation (at the very left), wavelength, gravity, viscosity\n  debug=False\n  eta=eta/2.0 \n  k= 2.0*pi/L # wave number 2pi/wavelength \n  omega_0sq = g*k  # inviscid natural frequency        \n  a=a_0*cos(pi*x)        \n\n  p1 = poly1d([1.0,0.0,2*k**2*eta,4*k**3*eta**(1.5),eta**2*k**4+omega_0sq],r=0)\n\n  p1roots = p1.r\n  z1=p1roots[0]\n  z2=p1roots[1]\n  z3=p1roots[2]\n  z4=p1roots[3]\n  Z1=(z2-z1)*(z3-z1)*(z4-z1)\n  Z2=(z1-z2)*(z3-z2)*(z4-z2)\n  Z3=(z1-z3)*(z2-z3)*(z4-z3)\n  Z4=(z1-z4)*(z2-z4)*(z3-z4)\n\n  if debug:\n                print 'Calculate analytic solution:'        \n                print 't=', t\n                print 'a=', a\n                print 'k=', k\n                print 'g=', g\n                print 'eta=', eta\n                print 'omega_0sq=', omega_0sq\n        \n  t0=4*eta**2*k**4/(8*eta**2*k**4+omega_0sq)*a*erfc((eta*k**2*t)**0.5)\n  t1=z1/Z1*omega_0sq*a/(z1**2-eta*k**2)*exp((z1**2-eta*k**2)*t)*erfc(z1*t**0.5)\n  t2=z2/Z2*omega_0sq*a/(z2**2-eta*k**2)*exp((z2**2-eta*k**2)*t)*erfc(z2*t**0.5)\n  t3=z3/Z3*omega_0sq*a/(z3**2-eta*k**2)*exp((z3**2-eta*k**2)*t)*erfc(z3*t**0.5)\n  t4=z4/Z4*omega_0sq*a/(z4**2-eta*k**2)*exp((z4**2-eta*k**2)*t)*erfc(z4*t**0.5)\n\n  a=t0+t1+t2+t3+t4\n        \n  if debug:\n                print 'a(t)=', a.real        \n  if (a.imag>0.000001):\n                print 'Warning: Imaginary part of a(t) is not zero!'\n  return a.real\n\n\n", "meta": {"hexsha": "3807e19f647f6bf1a4896699097651443fa90df2", "size": 2289, "ext": "py", "lang": "Python", "max_stars_repo_path": "software/multifluids_icferst/tests/wetting_and_drying_geometric_volume_conservation/ana_sol.py", "max_stars_repo_name": "msc-acse/acse-9-independent-research-project-Wade003", "max_stars_repo_head_hexsha": "cfcba990d52ccf535171cf54c0a91b184db6f276", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-11T02:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-11T03:08:38.000Z", "max_issues_repo_path": "software/multifluids_icferst/tests/wetting_and_drying_geometric_volume_conservation/ana_sol.py", "max_issues_repo_name": "msc-acse/acse-9-independent-research-project-Wade003", "max_issues_repo_head_hexsha": "cfcba990d52ccf535171cf54c0a91b184db6f276", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "software/multifluids_icferst/tests/wetting_and_drying_geometric_volume_conservation/ana_sol.py", "max_forks_repo_name": "msc-acse/acse-9-independent-research-project-Wade003", "max_forks_repo_head_hexsha": "cfcba990d52ccf535171cf54c0a91b184db6f276", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-21T22:50:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-28T17:16:31.000Z", "avg_line_length": 31.7916666667, "max_line_length": 148, "alphanum_fraction": 0.5792922674, "include": true, "reason": "from numpy,from scipy", "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561685659695, "lm_q2_score": 0.8774767970940974, "lm_q1q2_score": 0.8501488076381258}}
{"text": "import numpy as np\n\ndef sigmoid(z):\n    return 1 / (1 + np.exp(-z))\n\ndef predict(X, w):\n    linear_combination = np.matmul(X, w)\n    return sigmoid(linear_combination)\n\ndef classify(X, w):\n    return np.round(predict(X, w))\n\ndef loss (X, Y, w):\n    predictions = predict(X, w)\n    first_term = Y * np.log(predictions)\n    second_term = (1 - Y) * np.log(1 - predictions)\n    return (-1) * np.average(first_term + second_term)\n\ndef gradient(X, Y, w):\n    predictions = predict(X, w)\n    return np.matmul(X.T, (predictions - Y)) / (2 * X.shape[0])\n\ndef train(X, Y, iterations, learning_rate):\n    w = np.zeros((X.shape[1], 1))\n    for i in range(iterations):\n        print(\"Iterations: %4d => Loss: %.20f\" % (i, loss(X, Y, w)))\n        w -= gradient(X, Y, w) * learning_rate\n    return w\n\ndef test(X, Y, w):\n    total_examples = X.shape[0]\n    correct_results = np.sum(classify(X, w) == Y)\n    success_percent = correct_results * 100 / total_examples\n\n    print(\"\\nSuccess: %d/%d (%.2f%%)\" % (correct_results, total_examples, success_percent))\n\nif __name__ == \"__main__\":\n    X1, X2, X3, Y = np.loadtxt(\"examples.txt\", skiprows=1, unpack=True)\n    X = np.column_stack((np.ones(X1.size), X1, X2, X3))\n    Y = Y.reshape(-1, 1)\n    iterations = 10000\n    learning_rate = 0.001\n    w = train(X, Y, iterations, learning_rate)\n\n    test(X, Y, w)\n\n    input(\"Press <Enter>\")", "meta": {"hexsha": "263c97226b0c20ef290d100718ef0c13f1cd330f", "size": 1364, "ext": "py", "lang": "Python", "max_stars_repo_path": "logistic-regression/logistic-regression.py", "max_stars_repo_name": "giacomo-montibeller/ml-regression", "max_stars_repo_head_hexsha": "33a823a04430a94a464c1aa9c8668f20e4c882b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "logistic-regression/logistic-regression.py", "max_issues_repo_name": "giacomo-montibeller/ml-regression", "max_issues_repo_head_hexsha": "33a823a04430a94a464c1aa9c8668f20e4c882b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logistic-regression/logistic-regression.py", "max_forks_repo_name": "giacomo-montibeller/ml-regression", "max_forks_repo_head_hexsha": "33a823a04430a94a464c1aa9c8668f20e4c882b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0212765957, "max_line_length": 91, "alphanum_fraction": 0.6136363636, "include": true, "reason": "import numpy", "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561712637257, "lm_q2_score": 0.8774767858797979, "lm_q1q2_score": 0.8501487991403011}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May  2 16:13:25 2020\n\n@author: tyrion\n\"\"\"\n\nimport numpy as np\n\ndef vectors_to_polar(vectors, deg = False):\n    '''\n    Transform a set of vectors to polar coordinates\n\n    Arguments\n    ----------\n    vectors : ndarray (n, 3)\n        Vector data \n    deg : bool, optional, default False\n        If True, returns output polar angles in degrees. If False, returns angles in radian.\n    Returns\n    ----------\n    theta : ndarray (size, )\n        Polar angle\n    phi : ndarray (size, )\n        Azimuthal angle\n    '''\n\n    phi = np.arctan2(vectors[:, 1],vectors[:, 0])\n    theta = np.arccos(vectors[:, 2])\n    \n    if deg == True:\n        \n        phi = np.rad2deg(phi)\n        theta = np.rad2deg(theta)\n        \n    return theta, phi\n\ndef polar_to_vectors(theta, phi, deg = False):\n    '''\n    Transform a set of polar coordinates to vectors\n\n    Arguments\n    ----------\n    theta : ndarray (n, )\n        Polar angle\n    phi : ndarray (n, )\n        Azimuthal angle\n    deg : bool, optional, default False\n        If True, assumes that input is in degrees. If False, assumes that input is in radian.\n    Returns\n    ----------\n    vectors : ndarray (n, 3)\n        Vector data \n    '''\n        \n    if deg == True:\n        \n        phi = np.deg2rad(phi)\n        theta = np.deg2rad(theta)\n        \n    sintheta = np.sin(theta)\n    \n    vecs = np.empty((theta.shape[0],3))\n    vecs[:, 0] = sintheta*np.cos(phi)\n    vecs[:, 1] = sintheta*np.sin(phi)\n    vecs[:, 2] = np.cos(theta)\n    \n    return vecs\n\ndef vectors_to_geographical(vectors, deg = False):\n    '''\n    Transform a set of vectors to geographical coordinates\n    \n    Arguments\n    ----------\n    vectors : ndarray (n, 3)\n        Vector data \n    deg : bool, optional, default False\n        If True, returns output geographical angles in degrees. If False, returns angles in radian.\n    Returns\n    ----------\n    latitude : ndarray (n, )\n        Geographical latitude\n    longitude : ndarray (n, )\n        Geographical longitude\n    '''\n        \n    longitude = np.arctan2(vectors[:, 1],vectors[:, 0])\n    latitude = np.arcsin(vectors[:, 2])\n    \n    if deg == True:\n        \n        latitude = np.rad2deg(latitude)\n        longitude = np.rad2deg(longitude)\n        \n    return latitude, longitude\n\ndef geographical_to_vectors(latitude, longitude, deg = False):\n    '''\n    Transform a set of geographical coordinates to vectors\n\n    Arguments\n    ----------\n    latitude : ndarray (n, )\n        Polar angle\n    longitude : ndarray (n, )\n        Azimuthal angle\n    deg : bool, optional, default False\n        If True, assumes that input is in degrees. If False, assumes that input is in radian.\n    Returns\n    ----------\n    vectors : ndarray (n, 3)\n        Vector data\n    '''\n        \n    if deg == True:\n        \n        latitude = np.deg2rad(latitude)\n        longitude = np.deg2rad(longitude)\n        \n    vectors = np.empty((latitude.shape[0],3))\n    \n    coslat = np.cos(latitude)\n    \n    vectors[:, 0] = coslat * np.cos(longitude)\n    vectors[:, 1] = coslat * np.sin(longitude)\n    vectors[:, 2] = np.sin(latitude)\n    \n    return vectors", "meta": {"hexsha": "21e9e732f2f48fea12e6e87ec277e26ec01139f9", "size": 3172, "ext": "py", "lang": "Python", "max_stars_repo_path": "spherical_stats/_coordinate_systems.py", "max_stars_repo_name": "dschmitz89/spherical_stats", "max_stars_repo_head_hexsha": "2d7423d0db94649048d82c94a2a194cb689a75da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-24T08:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T08:30:56.000Z", "max_issues_repo_path": "spherical_stats/_coordinate_systems.py", "max_issues_repo_name": "dschmitz89/spherical_stats", "max_issues_repo_head_hexsha": "2d7423d0db94649048d82c94a2a194cb689a75da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spherical_stats/_coordinate_systems.py", "max_forks_repo_name": "dschmitz89/spherical_stats", "max_forks_repo_head_hexsha": "2d7423d0db94649048d82c94a2a194cb689a75da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4, "max_line_length": 99, "alphanum_fraction": 0.5655737705, "include": true, "reason": "import numpy", "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561667674652, "lm_q2_score": 0.877476785879798, "lm_q1q2_score": 0.850148795194937}}
{"text": "from typing import Callable\nimport numpy as np\n\n\ndef simpsonsRule(f: Callable, N: float, start: float=-1e6,\n                 stop: float=1e6) -> float:\n    \"\"\"Function to approximate the numeric integral of a function, f, using\n    Simpson's rule.\n    \n    Arguments:\n        f {Callable} -- Function for which the integral is to be estimated.\n        N {float} -- Number of nodes to consider.\n    \n    Keyword Arguments:\n        start {float} -- Starting point (default: {-1e6}).\n        stop {float} -- Stopping point (default: {1e6}).\n    \n    Returns:\n        float -- Approximation of the area under the function.\n    \"\"\"\n\n    # Building values for approximation, and getting step size\n    x, h = np.linspace(start=start, stop=stop, num=N, retstep=True)\n\n    # Computing midpoints\n    x_mid = np.array([(x[i - 1] + x[i]) / 2 for i in range(1, N)])\n\n    # Estimating using Simpson's rule\n    area = np.sum(2 * f(x)) - (f(start) + f(stop)) + (4 * np.sum(f(x_mid)))\n\n    # Scaling area\n    area *= (h / 6)\n\n    return area\n", "meta": {"hexsha": "0b73627777163b490cd2bb41d8fc2a790269da30", "size": 1025, "ext": "py", "lang": "Python", "max_stars_repo_path": "fe621/numerical_integration/simpsons.py", "max_stars_repo_name": "rukmal/FE-621-Homework", "max_stars_repo_head_hexsha": "9c7cef7931b58aed54867acd8e8cf1928bc6d2dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-04-29T04:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T07:49:08.000Z", "max_issues_repo_path": "fe621/numerical_integration/simpsons.py", "max_issues_repo_name": "rukmal/FE-621-Homework", "max_issues_repo_head_hexsha": "9c7cef7931b58aed54867acd8e8cf1928bc6d2dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fe621/numerical_integration/simpsons.py", "max_forks_repo_name": "rukmal/FE-621-Homework", "max_forks_repo_head_hexsha": "9c7cef7931b58aed54867acd8e8cf1928bc6d2dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-23T07:32:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T07:32:44.000Z", "avg_line_length": 29.2857142857, "max_line_length": 75, "alphanum_fraction": 0.6029268293, "include": true, "reason": "import numpy", "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561685659695, "lm_q2_score": 0.8774767778695834, "lm_q1q2_score": 0.8501487890123369}}
{"text": "import numpy as np\n\n'''\n\nCross-Entropy is an error function that we want to minimize.\nTo calculate Cross-Entropy(CE):\n\nCE = negative summation of the logarithms of the probabilities whenever there is or there's none\nsimply\n = - summ [(y_i)ln(p_i) + (1-y_i)ln(1-p_i)]\nwhere:\ny is either 1 if there is or 0 if there's none\np is the probability that there is\n\n'''\n\ndef cross_entropy(Y, P):\n    result = []\n    for i in range(0,len(Y)):\n        result.append(-1*(Y[i]*np.log(P[i]) + (1-Y[i])*np.log(1-P[i])))\n    CE = np.sum(result)\n    return CE\n\n\n'''\nUdacity's solution which is cleaner\n\nimport numpy as np\n\ndef cross_entropy(Y, P):\n    Y = np.float_(Y)\n    P = np.float_(P)\n    return -np.sum(Y * np.log(P) + (1 - Y) * np.log(1 - P))\n'''", "meta": {"hexsha": "0af6f2a7b96ab2a3fd910e70aad14d1095aef866", "size": 736, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lesson 3: Introduction to Neural Networks/3 Cross Entropy.py", "max_stars_repo_name": "makeithappenlois/Udacity-AI", "max_stars_repo_head_hexsha": "c82c7abaf179730740fecae76d388b14cbb3917c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-03T17:36:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T18:24:14.000Z", "max_issues_repo_path": "Lesson 3: Introduction to Neural Networks/3 Cross Entropy.py", "max_issues_repo_name": "makeithappenlois/Udacity-AI", "max_issues_repo_head_hexsha": "c82c7abaf179730740fecae76d388b14cbb3917c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lesson 3: Introduction to Neural Networks/3 Cross Entropy.py", "max_forks_repo_name": "makeithappenlois/Udacity-AI", "max_forks_repo_head_hexsha": "c82c7abaf179730740fecae76d388b14cbb3917c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-03T16:30:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-08T15:03:14.000Z", "avg_line_length": 21.6470588235, "max_line_length": 96, "alphanum_fraction": 0.6345108696, "include": true, "reason": "import numpy", "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.968856165868213, "lm_q2_score": 0.8774767762675405, "lm_q1q2_score": 0.8501487850929691}}
{"text": "from math import copysign, isnan\nimport numpy as np\n\ntest = False\n\nwith open(f\"../input/{'test_' if test else ''}day7.txt\") as f:\n    # :pinchers:\n    crabs = np.array([int(x) for x in f.read().strip().split(\",\")])\n\ndef sim_p1(h):\n    # d/dh | x - h | = sgn(h - x)\n    return np.sum(np.abs(crabs - h)), np.sum(np.sign(h - crabs))\n\ndef sim_p2(h):\n    # let k = |x_i - h|\n    # cost = k * (k + 1) / 2\n    # so d/dh = sgn(h - x) / 2 + (h - x)\n\n    d   = np.abs(crabs - h)\n    err = np.sum((d * (d + 1)) / 2)\n    dh  = np.sum(.5 * np.sign(h - crabs) + (h - crabs))\n\n    return err, dh\n\ndef solve(sim):\n    # very random\n    sol = 5\n    alpha = .00005\n\n    for i in range(100000):\n        err, dh = sim(sol)\n\n        if abs(dh) < 1e-4:\n            break\n\n        sol -= dh * alpha\n\n    err, _ = sim(round(sol))\n    print(f\"sol: {sol} -> {round(sol)}, err: {err}\")\n\nif __name__ == \"__main__\":\n    solve(sim_p1)\n    solve(sim_p2)\n", "meta": {"hexsha": "9e5fc0250063bcedc0836f522ea33c2097d6db02", "size": 923, "ext": "py", "lang": "Python", "max_stars_repo_path": "fifty-six/day7/day7.py", "max_stars_repo_name": "BasedJellyfish11/Advent-of-Code-2021", "max_stars_repo_head_hexsha": "9ed84902958c99c341ec2444d5db561c84348911", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-12-03T22:40:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T21:17:16.000Z", "max_issues_repo_path": "fifty-six/day7/day7.py", "max_issues_repo_name": "BasedJellyfish11/Advent-of-Code-2021", "max_issues_repo_head_hexsha": "9ed84902958c99c341ec2444d5db561c84348911", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fifty-six/day7/day7.py", "max_forks_repo_name": "BasedJellyfish11/Advent-of-Code-2021", "max_forks_repo_head_hexsha": "9ed84902958c99c341ec2444d5db561c84348911", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9772727273, "max_line_length": 67, "alphanum_fraction": 0.5016251354, "include": true, "reason": "import numpy", "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750466836961, "lm_q2_score": 0.8918110540642805, "lm_q1q2_score": 0.8501412241961632}}
{"text": "# Q.2 How do the values of options at time t = 0 compare for various values of M? Compute and plot graphs (of the\n# initial option prices) varying M in steps of 1 and in steps of 5. What do you observe about the convergence of\n# option prices?\n\n# Pandas : pip install pandas \n# Matplotlib: pip install matplotlib \n# Numpy: pip install numpy \n# Ipython: pip install ipython\n\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Given data\nS0=100\nK=105\nT=5\nr=0.05\nsig=0.3\n\n# Function to get Option Price for a given M\ndef getOptionPrice(M):\n    dt = T/M\n    u = math.exp(sig*math.sqrt(dt)+(r-sig*sig/2)*dt)\n    d = math.exp(-sig*math.sqrt(dt)+(r-sig*sig/2)*dt)\n    p = (math.exp(r*dt)-d)/(u-d)\n    \n    # Check if No Arbitrage Principle has got violated\n    if p < 0 or p > 1:\n        print(\"No Arbitrage Principle has been Violated\")\n        return '-','-'\n    \n    callList = [0]*(M+1)\n    putList = [0]*(M+1)\n    \n    for i in range(M+1):\n        callList[i] = max(S0*(u**i)*(d**(M-i)) - K, 0)\n        putList[i] = max(0, K - S0*(u**i)*(d**(M-i)))\n        \n    for i in range(M):\n        for j in range(M-i):\n            callList[j] = ((1-p)*callList[j] + p*callList[j+1])*math.exp(-r*T/M)\n            putList[j] = ((1-p)*putList[j] + p*putList[j+1])*math.exp(-r*T/M)\n    return callList[0], putList[0]\n\n# Lists to store the option prices\ncallPrices = []\nputPrices = []\nM=0\n# Compute initial option prices in steps of 1\nwhile M < 400:\n    M += 1\n    call, put = getOptionPrice(M)\n    callPrices.append(call)\n    putPrices.append(put)\nMList = np.linspace(1, 400, 400)\n\nplt.plot(MList, callPrices)\nplt.xlabel('Value of M')\nplt.ylabel('Call Option Price')\nplt.title('Varying Price of Call Option with Value of M (Step Size 1)')\nplt.show()\n\nplt.plot(MList, putPrices)\nplt.xlabel('Value of M')\nplt.ylabel('Price of Put Option')\nplt.title('Varying Price of Put Option with Value of M (Step Size 1)')\nplt.show()\n\n# Lists to store the option prices\ncallPrices = []\nputPrices = []\n\n# Compute initial option prices in steps of 5\nM=0\nwhile M < 400:\n    M += 5\n    call, put = getOptionPrice(M)\n    callPrices.append(call)\n    putPrices.append(put)\nMList = np.linspace(1, 400, 80)\n\nplt.plot(MList, callPrices)\nplt.xlabel('Value of M')\nplt.ylabel('Call Option Price')\nplt.title('Varying Call Option Price with Value of M (Step Size 5)')\nplt.show()\n\nplt.plot(MList, putPrices)\nplt.xlabel('Value of M')\nplt.ylabel('Price of Put Option')\nplt.title('Varying Put Option Price with Value of M (Step Size 5)')\nplt.show()\n", "meta": {"hexsha": "fdce83245adc274b3b118198eaf8a48e4165d00b", "size": 2515, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 374 (Financial Engg. Lab)/Lab 1/180123062_ABSatyaprakash_q2 1.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 374 (Financial Engg. Lab)/Lab 1/180123062_ABSatyaprakash_q2 1.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 374 (Financial Engg. Lab)/Lab 1/180123062_ABSatyaprakash_q2 1.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 26.7553191489, "max_line_length": 113, "alphanum_fraction": 0.6473161034, "include": true, "reason": "import numpy", "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.8918110461567923, "lm_q1q2_score": 0.8501412095551597}}
{"text": "import numpy as np\nimport math\nfrom scipy import stats\n\nx = np.array([14.4,7.2,27.5,53.8,38.0,15.9,4.9])\ny = np.array([54,64,44,32,37,68,62])\n\nn = x.size\n\nrank_x = np.array([5,6,3,2,1,4,7])\nrank_y = np.array([4,2,5,7,6,1,3])\n\nd = rank_x - rank_y\nd_square = np.square(d)\nsum_d_square = np.sum(d_square)\n\nprint(\"d : \",d)\nprint(\"d_square : \",d_square)\n\n# if there are no duplicates\ncoeff_numerator = 6*sum_d_square\n\n# if there are duplicates\ncoeff_numerator_dup = 6*(sum_d_square+((6+24)/12))\n\ncoeff_denominator = n*(math.pow(n,2)-1)\ncoeff = 1-(coeff_numerator/coeff_denominator)\n\nprint(\"rank co-relation : \",coeff)", "meta": {"hexsha": "d463e1ee1ee35ad962502490b145eecc788add7b", "size": 612, "ext": "py", "lang": "Python", "max_stars_repo_path": "Statistics/rank_corelation.py", "max_stars_repo_name": "Dheer08/Algorithms", "max_stars_repo_head_hexsha": "6731a5896ab338b6123280275fab5f36bdd52b4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Statistics/rank_corelation.py", "max_issues_repo_name": "Dheer08/Algorithms", "max_issues_repo_head_hexsha": "6731a5896ab338b6123280275fab5f36bdd52b4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/rank_corelation.py", "max_forks_repo_name": "Dheer08/Algorithms", "max_forks_repo_head_hexsha": "6731a5896ab338b6123280275fab5f36bdd52b4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1034482759, "max_line_length": 50, "alphanum_fraction": 0.6862745098, "include": true, "reason": "import numpy,from scipy", "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190132, "lm_q2_score": 0.8918110440002045, "lm_q1q2_score": 0.8501412074993385}}
{"text": "# Databricks notebook source\n# MAGIC %md\n# MAGIC ScaDaMaLe Course [site](https://lamastex.github.io/scalable-data-science/sds/3/x/) and [book](https://lamastex.github.io/ScaDaMaLe/index.html)\n# MAGIC \n# MAGIC This is a 2019-2021 augmentation and update of [Adam Breindel](https://www.linkedin.com/in/adbreind)'s initial notebooks.\n# MAGIC \n# MAGIC _Thanks to [Christian von Koch](https://www.linkedin.com/in/christianvonkoch/) and [William Anzén](https://www.linkedin.com/in/william-anz%C3%A9n-b52003199/) for their contributions towards making these materials Spark 3.0.1 and Python 3+ compliant._\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC #### We can also implement the model with mini-batches -- this will let us see matrix ops in action:\n# MAGIC \n# MAGIC (N.b., feed_dict is intended for small data / experimentation. For more info on ingesting data at scale, see https://www.tensorflow.org/api_guides/python/reading_data)\n\n# COMMAND ----------\n\n# we know these params, but we're making TF learn them\n\nREAL_SLOPE_X1 = 2 # slope along axis 1 (x-axis)\nREAL_SLOPE_X2 = 3 # slope along axis 2 (y-axis)\nREAL_INTERCEPT = 5 # intercept along axis 3 (z-axis), think of (x,y,z) axes in the usual way\n\n# COMMAND ----------\n\nimport numpy as np\n# GENERATE a batch of true data, with a little Gaussian noise added\n\ndef make_mini_batch(size=10):\n  X = np.random.rand(size, 2) # \n  Y = np.matmul(X, [REAL_SLOPE_X1, REAL_SLOPE_X2]) + REAL_INTERCEPT + 0.2 * np.random.randn(size) \n  return X.reshape(size,2), Y.reshape(size,1)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC To digest what's going on inside the function above, let's take it step by step.\n\n# COMMAND ----------\n\n Xex = np.random.rand(10, 2) # Xex is simulating PRNGs from independent Uniform [0,1] RVs\n Xex # visualize these as 10 orddered pairs of points in the x-y plane that makes up our x-axis and y-axis (or x1 and x2 axes)\n\n# COMMAND ----------\n\nYex = np.matmul(Xex, [REAL_SLOPE_X1, REAL_SLOPE_X2]) #+ REAL_INTERCEPT #+ 0.2 * np.random.randn(10) \nYex\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC The first entry in Yex is obtained as follows (change the numbers in the produc below if you reevaluated the cells above) and geometrically it is the location in z-axis of the plane with slopes given by REAL_SLOPE_X1 in the x-axis and REAL_SLOPE_X2 in the y-aixs with intercept 0 at the point in the x-y or x1-x2 plane given by (0.68729439,  0.58462379).\n\n# COMMAND ----------\n\n0.21757443*REAL_SLOPE_X1 +  0.01815727*REAL_SLOPE_X2 \n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC The next steps are adding an intercept term to translate the plane in the z-axis and then a scaled (the multiplication by 0.2 here) gaussian noise from independetly drawn pseudo-random samples from the standard normal or Normal(0,1) random variable via `np.random.randn(size)`.\n\n# COMMAND ----------\n\nYex = np.matmul(Xex, [REAL_SLOPE_X1, REAL_SLOPE_X2]) + REAL_INTERCEPT # + 0.2 * np.random.randn(10) \nYex\n\n# COMMAND ----------\n\nYex = np.matmul(Xex, [REAL_SLOPE_X1, REAL_SLOPE_X2])  + REAL_INTERCEPT + 0.2 * np.random.randn(10) \nYex # note how each entry in Yex is jiggled independently a bit by 0.2 * np.random.randn()\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Thus we can now fully appreciate what is going on in `make_mini_batch`. This is meant to substitute for pulling random sub-samples of batches of the real data during stochastic gradient descent.\n\n# COMMAND ----------\n\nmake_mini_batch() # our mini-batch of Xx and Ys\n\n# COMMAND ----------\n\nimport tensorflow as tf\n\n\nbatch = 10 # size of batch\n\ntf.reset_default_graph() # this is important to do before you do something new in TF\n\n# we will work with single floating point precision and this is specified in the tf.float32 type argument to each tf object/method\nx = tf.placeholder(tf.float32, shape=(batch, 2)) # placeholder node for the pairs of x variables (predictors) in batches of size batch\nx_aug = tf.concat( (x, tf.ones((batch, 1))), 1 ) # x_aug is a concatenation of a vector of 1`s along the first dimension\n\ny = tf.placeholder(tf.float32, shape=(batch, 1)) # placeholder node for the univariate response y with batch many rows and 1 column\nmodel_params = tf.get_variable(\"model_params\", [3,1]) # these are the x1 slope, x2 slope and the intercept (3 rows and 1 column)\ny_model = tf.matmul(x_aug, model_params) # our two-factor regression model is defined by this matrix multiplication\n# note that the noise is formally part of the model and what we are actually modeling is the mean response...\n\nerror = tf.reduce_sum(tf.square(y - y_model))/batch # this is mean square error where the sum is computed by a reduce call on addition\n\ntrain_op = tf.train.GradientDescentOptimizer(0.02).minimize(error) # learning rate is set to 0.02\n\ninit = tf.global_variables_initializer() # our way into running the TF session\n\nerrors = [] # list to track errors over iterations\n\nwith tf.Session() as session:\n    session.run(init)    \n    for i in range(1000):\n      x_data, y_data = make_mini_batch(batch) # simulate the mini-batch of data x1,x2 and response y with noise\n      _, error_val = session.run([train_op, error], feed_dict={x: x_data, y: y_data})\n      errors.append(error_val)\n\n    out = session.run(model_params)\n    print(out)\n\n# COMMAND ----------\n\nREAL_SLOPE_X1, REAL_SLOPE_X2, REAL_INTERCEPT # compare with rue parameter values - it's not too far from the estimates\n\n# COMMAND ----------\n\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\nfig.set_size_inches((4,3))\nplt.plot(errors)\ndisplay(fig)\n\n# COMMAND ----------\n\n", "meta": {"hexsha": "7c45c160f870e7598c045c54e1e2c92f9a49efd3", "size": 5527, "ext": "py", "lang": "Python", "max_stars_repo_path": "dbcArchives/2021/000_6-sds-3-x-dl/054_DLbyABr_03a-BatchTensorFlowWithMatrices.py", "max_stars_repo_name": "r-e-x-a-g-o-n/scalable-data-science", "max_stars_repo_head_hexsha": "a97451a768cf12eec9a20fbe5552bbcaf215d662", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2017-07-25T06:48:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:23:36.000Z", "max_issues_repo_path": "dbcArchives/2021/000_6-sds-3-x-dl/054_DLbyABr_03a-BatchTensorFlowWithMatrices.py", "max_issues_repo_name": "r-e-x-a-g-o-n/scalable-data-science", "max_issues_repo_head_hexsha": "a97451a768cf12eec9a20fbe5552bbcaf215d662", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2017-08-17T13:45:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T09:06:53.000Z", "max_forks_repo_path": "dbcArchives/2021/000_6-sds-3-x-dl/054_DLbyABr_03a-BatchTensorFlowWithMatrices.py", "max_forks_repo_name": "r-e-x-a-g-o-n/scalable-data-science", "max_forks_repo_head_hexsha": "a97451a768cf12eec9a20fbe5552bbcaf215d662", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2017-08-18T17:04:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T14:30:51.000Z", "avg_line_length": 41.5563909774, "max_line_length": 362, "alphanum_fraction": 0.717749231, "include": true, "reason": "import numpy", "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.9136765263519308, "lm_q1q2_score": 0.8501378685573077}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nComputes the Legendre-Gauss-Lobatto nodes, weights and the LGL Vandermonde \r\nmatrix. The LGL nodes are the zeros of (1-x**2)*P'_N(x). Useful for numerical\r\nintegration and spectral methods. \r\n\r\nReference on LGL nodes and weights: \r\n  C. Canuto, M. Y. Hussaini, A. Quarteroni, T. A. Tang, \"Spectral Methods\r\n  in Fluid Dynamics,\" Section 2.3. Springer-Verlag 1987\r\n\r\n  \r\nOriginally implemented in MATLAB by Greg von Winckel\r\nhttp://www.mathworks.com/matlabcentral/fileexchange/4775-legende-gauss-lobatto-nodes-and-weights\r\n\r\n\r\n@author: Nicolas Guarin-Zapata\r\n\"\"\"\r\nfrom __future__ import division, print_function\r\nfrom numpy import pi, sin, zeros, amax, abs, square, array, linspace\r\nfrom numpy.linalg import norm\r\nimport numpy as np\r\n\r\n\r\ndef gauss_lobatto(N, tol=1e-15):\r\n    \"\"\"\r\n    Use Chebyshev nodes as first guess.\r\n    \r\n    Compute P_(N) using the recursion relation\r\n    Compute its first and second derivatives and\r\n    update x using the Newton-Raphson method.\r\n    \r\n    Chebyshev nodes are computed using the symmetric\r\n    formula that involves sine as presented in:\r\n\r\n      Nick Trefethen. Aproximation Theory and \r\n      Aproximation Practice, Chapter 2, exercise 2.\r\n    \r\n    \"\"\"\r\n    x = sin(linspace(-pi/2, pi/2, N))\r\n    P = zeros((N, N))  # Vandermonde Matrix\r\n    x_old = 2\r\n    while amax(abs(x - x_old)) > tol:\r\n        x_old = x\r\n        P[:, 0] = 1\r\n        P[:, 1] = x\r\n        for k in range(2, N):\r\n            P[:, k] = ((2 * k - 1) * x * P[:, k - 1] -\r\n                       (k - 1) * P[:, k - 2]) / k\r\n        x = x_old - (x * P[:, N - 1] - P[:, N - 2]) / (N * P[:, N - 1])\r\n\r\n    w = 2.0 / ((N - 1) * N * square(P[:, N - 1]))\r\n\r\n    return array(x), array(w)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    x, _ = gauss_lobatto(5)\r\n    x_exact = array([-1, -np.sqrt(3/7), 0, np.sqrt(3/7), 1])\r\n    print(\"Relative error: {:g}\".format(norm(x - x_exact)/norm(x_exact)))\r\n", "meta": {"hexsha": "4dda4584319c615df1ce4609fe7b980f978479de", "size": 1923, "ext": "py", "lang": "Python", "max_stars_repo_path": "interpolation/gauss_lobatto.py", "max_stars_repo_name": "nicoguaro/FEM_resources", "max_stars_repo_head_hexsha": "32f032a4e096fdfd2870e0e9b5269046dd555aee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2015-11-06T16:59:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T18:18:49.000Z", "max_issues_repo_path": "interpolation/gauss_lobatto.py", "max_issues_repo_name": "oldninja/FEM_resources", "max_issues_repo_head_hexsha": "e44f315be217fd78ba95c09e3c94b1693773c047", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interpolation/gauss_lobatto.py", "max_forks_repo_name": "oldninja/FEM_resources", "max_forks_repo_head_hexsha": "e44f315be217fd78ba95c09e3c94b1693773c047", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-06-24T22:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T15:57:37.000Z", "avg_line_length": 32.05, "max_line_length": 97, "alphanum_fraction": 0.595423817, "include": true, "reason": "import numpy,from numpy", "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.9136765163620469, "lm_q1q2_score": 0.8501378539763916}}
{"text": "# TODO: Create a synthetic dataset - how would the data need to look like if we were able to fit the sine wave on them?\n\n# You want to reverse engineer data which would fit onto your 'ideal' curve:\n# Eq: y = amp * np.sin (2* np.pi / 24 * x + shift_h) + shift_v\n# Without shift_h:  2.63 * np.sin (2 * np.pi / 24 * x) + 17.18\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef sine_function(x, amp, per, shift_h, shift_v):\n    return amp * np.sin(2*np.pi/per * x + shift_h) + shift_v\n\namp, per, shift_h, shift_v = 2.63, 24.0, 0, 17.18\n\nrepeats = 4\nx_sine = np.linspace(0, repeats * 24 + 1, 100)\ny_sine = sine_function(x_sine, amp, per, shift_h, shift_v)\n\n\n# Now do the reverse engineering for 5-generational families with phases ranging between 0-24:\ndef SynthesizeData(phase):\n    \"\"\" Phase ranges from 0 to 24 with increments of 0.2. \"\"\"\n\n    x_list = [phase]\n    y_list = []\n\n    while len(x_list) < 5 or len(y_list) < 5:\n        x = x_list[-1]\n        y = sine_function(x=x, amp=amp, per=per, shift_h=shift_h, shift_v=shift_v)\n        x_list.append(y+x)\n        y_list.append(y)\n    x_list = x_list[:-1]\n\n    return x_list, y_list\n\n\nphase_range = np.linspace(0, 24, 120)\nprint (phase_range)\n\nx_data_0 = []\ny_data_0 = []\nfor phase in list(phase_range.tolist()):\n    x_list, y_list = SynthesizeData(phase=phase)\n    plt.scatter(x=x_list, y=y_list, color=\"purple\", alpha=0.2, zorder=2) # label=\"Fake Data Point\",\n    y_data_0.append(y_list)\n    x_data_0.append([value - x_list[0] for value in x_list])\n\n\n# Now plot the thing:\nplt.plot(x_sine, y_sine, color=\"turquoise\", label=\"Ideal Sine Wave\", zorder=1)\nplt.axhline(y=shift_v, color=\"grey\", linestyle=\"dashed\", zorder=0)\nplt.axvline(x=24.0, color=\"gold\", linestyle=\"dashed\", zorder=0)\nplt.axvline(x=48.0, color=\"gold\", linestyle=\"dashed\", zorder=0)\nplt.axvline(x=72.0, color=\"gold\", linestyle=\"dashed\", zorder=0)\nplt.xticks(np.arange(0, repeats * 24 + 1, 4))\nplt.xlabel(\"Oscillation Period [hours]\")\nplt.ylabel(\"Cell Cycle Duration [hours]\")\nplt.title(\"Ideal Sine Wave\")\nplt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=1)\nplt.savefig(\"/Users/kristinaulicna/Documents/Rotation_2/Sine_Wave/Summary_All_Cells/Ideal_Wave.png\", bbox_inches=\"tight\")\nplt.show()\nplt.close()\n\n\n# Now plot the non-phased data:\nfor x, y in zip(x_data_0, y_data_0):\n    plt.scatter(x=x, y=y)\n\nplt.xlabel(\"Oscillation Period [hours]\")\nplt.ylabel(\"Cell Cycle Duration [hours]\")\nplt.title(\"Relationships between generations in an ideal family\\n\"\n          \"Equation: {} * np.sin (2 * np.pi / {} * x + {}) + {}\"\n          .format(amp, per, shift_h, shift_v))\nplt.savefig(\"/Users/kristinaulicna/Documents/Rotation_2/Sine_Wave/Summary_All_Cells/Ideal_Wave_Relationships.png\",\n            bbox_inches=\"tight\")\nplt.show()\nplt.close()", "meta": {"hexsha": "fd885ef88645d3c32ff20d54fa5ce5c8aaf23afc", "size": 2770, "ext": "py", "lang": "Python", "max_stars_repo_path": "Biological_Questions/Sine_Wave_Alignments/Approach_Grid_Search/Reverse_Engineer_Synthetic_Dataset.py", "max_stars_repo_name": "The-Kristina/CellComp", "max_stars_repo_head_hexsha": "29ec7690e0d9adb1a6214937ca41fd1dadce18c6", "max_stars_repo_licenses": ["CNRI-Python", "RSA-MD", "Xnet", "Net-SNMP", "X11"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-05-13T10:07:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T16:20:48.000Z", "max_issues_repo_path": "Biological_Questions/Sine_Wave_Alignments/Approach_Grid_Search/Reverse_Engineer_Synthetic_Dataset.py", "max_issues_repo_name": "The-Kristina/CellComp", "max_issues_repo_head_hexsha": "29ec7690e0d9adb1a6214937ca41fd1dadce18c6", "max_issues_repo_licenses": ["CNRI-Python", "RSA-MD", "Xnet", "Net-SNMP", "X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Biological_Questions/Sine_Wave_Alignments/Approach_Grid_Search/Reverse_Engineer_Synthetic_Dataset.py", "max_forks_repo_name": "The-Kristina/CellComp", "max_forks_repo_head_hexsha": "29ec7690e0d9adb1a6214937ca41fd1dadce18c6", "max_forks_repo_licenses": ["CNRI-Python", "RSA-MD", "Xnet", "Net-SNMP", "X11"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-23T18:13:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T18:46:48.000Z", "avg_line_length": 35.974025974, "max_line_length": 121, "alphanum_fraction": 0.6841155235, "include": true, "reason": "import numpy", "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877717925422, "lm_q2_score": 0.8757870013740061, "lm_q1q2_score": 0.8501157329286061}}
{"text": "#Determining a linear trend line for Bitcoin\nimport numpy as np\nfrom scipy.linalg import lstsq\n\nyear = np.array([2010.91666666666, 2011.41666666666, 2011.91666666666,\n             2012.41666666666, 2012.91666666666, 2013.41666666666,\n             2013.91666666666, 2014.41666666666, 2014.91666666666,\n             2015.41666666666, 2015.91666666666, 2016.41666666666,\n             2016.91666666666, 2017.41666666666])\nbtc_price = np.array([0.23, 9.57, 3.06, 5.27, 12.56, 129.3, 946.92, 629.02,\n\t              378.64, 223.31, 362.73, 536.42, 753.25, 2452.18])\n\nM = year[:, np.newaxis]**[0, 1]\nmodel, _, _, _ = lstsq(M,btc_price)\nprint \"Intercept =\", model[0]\nprint \"year coefficient =\", model[1]\n", "meta": {"hexsha": "6d04c1938650d46b832ad491ccd1d4f85f4c070b", "size": 695, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter07/year_bitcoin.py", "max_stars_repo_name": "PacktPublishing/Data-Science-Algorithms-in-a-Week-Second-Edition", "max_stars_repo_head_hexsha": "79d431d23ce98c1515754a01e87a82a8d9fe0726", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2018-10-15T12:52:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T16:49:04.000Z", "max_issues_repo_path": "Chapter07/year_bitcoin.py", "max_issues_repo_name": "abhishek-choudharys/Data-Science-Algorithms-in-a-Week-Second-Edition", "max_issues_repo_head_hexsha": "e4fc518803129e6b11e0bfa0587ff450c2577ff9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter07/year_bitcoin.py", "max_forks_repo_name": "abhishek-choudharys/Data-Science-Algorithms-in-a-Week-Second-Edition", "max_forks_repo_head_hexsha": "e4fc518803129e6b11e0bfa0587ff450c2577ff9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2018-10-15T16:00:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T05:44:04.000Z", "avg_line_length": 40.8823529412, "max_line_length": 75, "alphanum_fraction": 0.6633093525, "include": true, "reason": "import numpy,from scipy", "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877692486436, "lm_q2_score": 0.8757869835428965, "lm_q1q2_score": 0.8501157133922528}}
{"text": "\"\"\"\n\nCommon Algorithms\n\n@author: Naimish Agarwal\n\"\"\"\n\n\nimport math\nimport fundamental_data_structures as fds\nfrom numba import jit\n\n\n@jit\ndef gcd(p, q):\n\n    \"\"\"\n    Find Greatest Common Factor of integers p, q\n\n    \"\"\"\n    if q == 0:\n        return p\n    r = p % q\n    return gcd(q, r)\n\n\n@jit\ndef is_prime(n):\n    \"\"\"\n\n    Returns whether n is a prime number or not\n\n    \"\"\"\n\n    if n < 2:\n        return False\n\n    for i in xrange(2, int(math.sqrt(n))):\n        if n % i == 0:\n            return False\n\n    return True\n\n\ndef evaluate_arithmetic_expression(expression):\n    \"\"\"\n\n    Evaluate an arithmetic expression using Dijkstra's two stack algorithm.\n    The function assumes that each subexpression is enclosed in parenthesis.\n\n    e.g. ( 1 + ( 2 * ( 3 / 7 ) ) )\n\n    It is also assumed that at least one operator and two operands are present.\n\n    e.g. 1 + 2 (valid)\n\n    e.g. 2 (invalid)\n\n    Parameters:\n    -----------\n\n    expression: arithmetic expression which can comprise the following:\n        (, ), +, -, *, /, numbers\n\n    all separated by whitespace.\n\n    Returns:\n    --------\n\n    Value of expression after evaluation\n\n    \"\"\"\n\n    expression = \"( \" + expression + \" )\"\n    tokens = expression.split()\n    operator_stack = fds.LinkedListStack()\n    operand_stack = fds.LinkedListStack()\n\n    for token in tokens:\n        if token == \"(\":\n            pass\n        elif token in [\"+\", \"-\", \"*\", \"/\"]:\n            operator = token\n            operator_stack.push(operator)\n        elif token == \")\":\n            operator = operator_stack.pop()\n            num2 = operand_stack.pop()\n            num1 = operand_stack.pop()\n\n            print num1, operator, num2\n            if operator == \"+\":\n                operand = num1 + num2\n            elif operator == \"-\":\n                operand = num1 - num2\n            elif operator == \"*\":\n                operand = num1 * num2\n            elif operator == \"/\":\n                operand = num1 / num2\n            operand_stack.push(operand)\n        else:\n            operand = float(token)\n            operand_stack.push(operand)\n\n    return operand_stack.pop()\n", "meta": {"hexsha": "9d674d43d6367f213c1c3336dbf6d520a1163619", "size": 2127, "ext": "py", "lang": "Python", "max_stars_repo_path": "common_algorithms.py", "max_stars_repo_name": "agarwalnaimish/dsa_python", "max_stars_repo_head_hexsha": "382a136c1861e09d888fc71406615a09ee51ecd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "common_algorithms.py", "max_issues_repo_name": "agarwalnaimish/dsa_python", "max_issues_repo_head_hexsha": "382a136c1861e09d888fc71406615a09ee51ecd4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common_algorithms.py", "max_forks_repo_name": "agarwalnaimish/dsa_python", "max_forks_repo_head_hexsha": "382a136c1861e09d888fc71406615a09ee51ecd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2571428571, "max_line_length": 79, "alphanum_fraction": 0.5416078984, "include": true, "reason": "from numba", "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970687770944576, "lm_q2_score": 0.8757869803008764, "lm_q1q2_score": 0.850115711730539}}
{"text": "# This program was originally authored by Delaney Granizo and Andrei Kirilenko \nas a part of the Master of Finance curriculum at MIT Sloan. \n\n\"\"\"\nIn this notebook, we mainly explores the statistical method of computing maximum likelyhood function\nfor common distributions. A subsequent financial application will be examined through fitting the normal\ndistributions to asset returns using MLE.\n\"\"\"\n\n# Basic Imports\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy\nimport scipy.stats\n\n\"\"\"\n== Normal Distribution ==\n\nWe first explores some basic sampling from a normal distribution. Given the data available, a\nfunction can be defined so that it will compute the MLE for the \\mu and \\sigma parameters of the\nnormal distribution.\n\n\"\"\"\n\nTrue_Mean = 80\nTrue_Std = 10\nX = np.random.normal(True_Mean, True_Std, 1000)\n\ndef normal_mu_MLE(X):\n  \"\"\"Return the MLE given mu in a normal distribution.\n  \"\"\"\n  n_obs = len(X)\n  sum_obs = sum(x)\n  return 1.0/n_obs*sum_obs\n\ndef normal_sigma_MLE(X):\n  \"\"\"Return \n  \"\"\"\n  n_obs = len(X)\n  mu = normal_mu_MLE(X)\n  sum_sqd = sum(np.power((X - mu), 2)) # sum up the squared differences.\n  sigma_sq = 1.0/ n_obs * sum_sqd\n  return math.sqrt(sigma_sq)\n\npdf = scipy.stats.norm.pdf\nx = np.linespace(0, 80, 80)\nplt.hist(x, bins=x, normed='true')\nplt.plot(pdf(x, loc=mu, scale=std))\nplt.xlabel('Value')\nplt.ylabel('Observed Frequency')\nplt.legend(['Fitted Distribution PDF', 'Observed Data', ])\n  \n# Exponential Distribution\nTRUE_LAMDA = 5\nX = np.random.exponetial(TRUE_LAMDA, 1000)\n\ndef exp_lamda_MLE(X):\n  T = len(X)\n  s = sum(X)\n  return s/T\n\npdf = scipy.stats.exon.pdf\nx = range(0, 80)\nplt.hist(X, bins=x, normed='true')\nplt.plot(pdf(x, scale=1))\nplt.xlabel('Value')\nplt.ylabel('Observed Frequency')\nplt.legend(['Fitted Distribution PDF', 'Observed Data', ])\n\nprices = get_pricing('AAPL', fields='price', start_date='2018-01-01', end_date='2019-12-31')\nabsolute_returns = np.diff(prices)\nreturns = absolute_returns / prices[:-1]\n\n# Using the scipy's fit function to get the mu and sigma \nmu, std = scipy.stats.norm.fit(returns)\npdf = scipy.stats.norm.pdf\nx = np.linspace(-1, 1, num= 100)\nh = plt.hist(returns, bins=x, normed='true')\nl = plt.plot(x, pdf(X, loc=mu, scale=std))\n\n# Note that fitting this sample to normal would not work if they do not follow a normal in the\n# first place. Such, Jarque-Bera normality test can be carried out. The hypothesis of normal \n# distribution will be rejected if the p-value is under a threshold c.\n\n", "meta": {"hexsha": "15e152391d3b740e35a92684696cc2c224b4eab9", "size": 2492, "ext": "py", "lang": "Python", "max_stars_repo_path": "5. Arbitrage/MLE.py", "max_stars_repo_name": "conquerv0/Pynance", "max_stars_repo_head_hexsha": "02dcfffd0a54374c603baad02ee31bc7ced7f670", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-04-18T17:28:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:11:21.000Z", "max_issues_repo_path": "5. Arbitrage/MLE.py", "max_issues_repo_name": "conquerv0/Pynance", "max_issues_repo_head_hexsha": "02dcfffd0a54374c603baad02ee31bc7ced7f670", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-22T02:22:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-22T02:22:03.000Z", "max_forks_repo_path": "5. Arbitrage/MLE.py", "max_forks_repo_name": "conquerv0/Pynance", "max_forks_repo_head_hexsha": "02dcfffd0a54374c603baad02ee31bc7ced7f670", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-06-29T17:37:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T17:02:39.000Z", "avg_line_length": 28.976744186, "max_line_length": 104, "alphanum_fraction": 0.7271268058, "include": true, "reason": "import numpy,import scipy", "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.9019206785067698, "lm_q1q2_score": 0.8500663029380788}}
{"text": "import numpy as np\nimport sys\n\nsys.path.append(\"..\")\nfrom fd_partial_derivative import fd_partial_derivative\n\n\n# Choose grid size\ngs = np.array([19,15])\nh = 1.0/(gs-1)\n\n# Build a grid\nx, y = np.meshgrid(np.linspace(0,1,gs[0]),np.linspace(0,1,gs[1]))\nV = np.concatenate((np.reshape(x,(-1, 1)),np.reshape(y,(-1, 1))),axis=1)\n\n# Build staggered grid in x direction\nx, y = np.meshgrid(np.linspace(0,1,gs[0]-1),np.linspace(0,1,gs[1]))\nVx = np.concatenate((np.reshape(x,(-1, 1)),np.reshape(y,(-1, 1))),axis=1)\n# Build staggered grid in y direction\nx, y = np.meshgrid(np.linspace(0,1,gs[0]),np.linspace(0,1,gs[1]-1))\nVy = np.concatenate((np.reshape(x,(-1, 1)),np.reshape(y,(-1, 1))),axis=1)\n\n# Build partial derivative matrices\nDx = fd_partial_derivative(gs=gs,h=h,direction=0)\nDy = fd_partial_derivative(gs=gs,h=h,direction=1)\n\n# all rows must sum up to zero (i.e. a constant function has zero derivative)\nassert((np.isclose(Dx.sum(axis=1),np.zeros((Dx.shape[0],1)))).all())\nassert((np.isclose(Dy.sum(axis=1),np.zeros((Dy.shape[0],1)))).all())\n\n# Build linear function\nf = 2*V[:,0] + 5*V[:,1]\ncomputed_derivative_x = Dx*f\ncomputed_derivative_y = Dy*f\n# Derivatives must be 2.0 and 5.0, respectively\nassert((np.isclose(computed_derivative_x,2.0*np.ones((computed_derivative_x.shape[0])))).all())\nassert((np.isclose(computed_derivative_y,5.0*np.ones((computed_derivative_y.shape[0])))).all())\n\n# Convergence test\nlinf_norm_x = 100.0\nlinf_norm_y = 100.0\nprint(\"This experiment should print a set of decreasing values, converging\")\nprint(\"towards zero and decreasing roughly by half in each iteration\")\nfor power in range(3,13,1):\n    gs = np.array([2**power,2**power - 2])\n    h = 1.0/(gs-1)\n    # Build a grid\n    x, y = np.meshgrid(np.linspace(0,1,gs[0]),np.linspace(0,1,gs[1]))\n    V = np.concatenate((np.reshape(x,(-1, 1)),np.reshape(y,(-1, 1))),axis=1)\n\n    # Build staggered grid in x direction\n    x, y = np.meshgrid(np.linspace(0,1,gs[0]-1),np.linspace(0,1,gs[1]))\n    Vx = np.concatenate((np.reshape(x,(-1, 1)),np.reshape(y,(-1, 1))),axis=1)\n    # Build staggered grid in y direction\n    x, y = np.meshgrid(np.linspace(0,1,gs[0]),np.linspace(0,1,gs[1]-1))\n    Vy = np.concatenate((np.reshape(x,(-1, 1)),np.reshape(y,(-1, 1))),axis=1)\n\n    # Build partial derivative matrices\n    Dx = fd_partial_derivative(gs=gs,h=h,direction=0)\n    Dy = fd_partial_derivative(gs=gs,h=h,direction=1)\n    # Build non-linear function\n    f = np.cos(V[:,0]) + np.sin(V[:,1])\n    # Derivatives on staggered grids\n    fx = -np.sin(Vx[:,0])\n    fy =  np.cos(Vy[:,1])\n    # Computed derivatives using our matrices\n    computed_derivative_x = Dx*f\n    computed_derivative_y = Dy*f\n    # Print L infinity norm of difference\n    # Make sure norm is decreasing\n    assert(linf_norm_x>np.max(np.abs(computed_derivative_x - fx)))\n    assert(linf_norm_y>np.max(np.abs(computed_derivative_y - fy)))\n    linf_norm_x = np.max(np.abs(computed_derivative_x - fx))\n    linf_norm_y = np.max(np.abs(computed_derivative_y - fy))\n    # Print L infinity norm of difference\n    print(np.array([np.max(np.abs(computed_derivative_x - fx)),np.max(np.abs(computed_derivative_y - fy))]))\n\nprint(\"Unit test passed, all asserts passed\")", "meta": {"hexsha": "10c403a2cca8254932d467ee2853f4cf956f63d6", "size": 3186, "ext": "py", "lang": "Python", "max_stars_repo_path": "unit_tests/fd_partial_derivative_unit_test.py", "max_stars_repo_name": "otmanon/gpytoolbox", "max_stars_repo_head_hexsha": "81d305bba9767a94f4d36264dd6849c410231c7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_tests/fd_partial_derivative_unit_test.py", "max_issues_repo_name": "otmanon/gpytoolbox", "max_issues_repo_head_hexsha": "81d305bba9767a94f4d36264dd6849c410231c7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_tests/fd_partial_derivative_unit_test.py", "max_forks_repo_name": "otmanon/gpytoolbox", "max_forks_repo_head_hexsha": "81d305bba9767a94f4d36264dd6849c410231c7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8461538462, "max_line_length": 108, "alphanum_fraction": 0.6789077213, "include": true, "reason": "import numpy", "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145364, "lm_q2_score": 0.9019206679615432, "lm_q1q2_score": 0.8500662929991317}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n#coiefficient calculation\ndef regress(x, x_s, t_s, M, N,lamda = 0):\n    order_list =  np.arange((M + 1))\n    order_list =  order_list[ :, np.newaxis]\n    exponent = np.tile(order_list,[1,N])\n    h = np.power(x_s,exponent)\n    a =  np.matmul(h, np.transpose(h)) + lamda*np.eye(M+1)\n    b =  np.matmul(h, t_s)\n    w = np.linalg.solve(a, b) #calculate the coefficent\n    \n    exponent2 = np.tile(order_list,[1,200])\n    h2 = np.power(x,exponent2)\n    p = np.matmul(w, h2)\n    return p\n\n##task 1\nx =  np.linspace(0, 1, 200) \nt =  np.sin(np.pi*x*2)\n\nN = 10\nsigma = 0.2;\nx_10 = np.linspace(0, 1, N) \nt_10 = np.sin(np.pi*x_10*2) + np.random.normal(0,sigma,N)\n\nplt.figure(1)\nplt.plot(x, t, 'g',  x_10, t_10, 'bo',linewidth = 2) \nplt.ylabel('t',rotation='horizontal')\nplt.xlabel('x')\nplt.savefig('1.png', dpi=300)\n\n##task 2\nM = 3\np3_10 =  regress(x, x_10, t_10, M, N)\n\nM = 9\np9_10 =  regress(x, x_10, t_10, M, N)\n\nplt.figure(2)\nplt.plot(x, t, 'g',  x_10, t_10, 'bo', x, p3_10, 'r', linewidth = 2) \nplt.ylabel('t',rotation='horizontal')\nplt.xlabel('x')\nplt.text(0.7, 0.7,'M=3', fontsize=16)\nplt.savefig('2.png', dpi=300)\n\nplt.figure(3)\nplt.plot(x, t, 'g',  x_10, t_10, 'bo', x, p9_10, 'r', linewidth = 2) \nplt.ylabel('t',rotation='horizontal')\nplt.xlabel('x')\nplt.text(0.7, 0.7,'M=9', fontsize=16)\nplt.savefig('3.png', dpi=300)\n\n##task3\nN = 15\nx_15 =  np.linspace(0, 1,  N) \nt_15 = np.sin(np.pi*x_15*2) + np.random.normal(0,sigma, N)\n\nM = 9\np9_15 =  regress(x, x_15, t_15, M, N)\n\nN = 100\nx_100 =  np.linspace(0, 1,  N) \nt_100 = np.sin(np.pi*x_100*2) + np.random.normal(0,sigma, N)\n\nM = 9\np9_100 =  regress(x, x_100, t_100, M, N)\n\nplt.figure(4)\nplt.plot(x, t, 'g',  x_15, t_15, 'bo', x, p9_15, 'r', linewidth = 2) \nplt.ylabel('t',rotation='horizontal')\nplt.xlabel('x')\nplt.text(0.7, 0.7,'N=15', fontsize=16)\nplt.savefig('4.png', dpi=300)\n\nplt.figure(5)\nplt.plot(x, t, 'g',  x_100, t_100, 'bo', x, p9_100, 'r', linewidth = 2) \nplt.ylabel('t',rotation='horizontal')\nplt.xlabel('x')\nplt.text(0.7, 0.7,'N=100', fontsize=16)\nplt.savefig('5.png', dpi=300)\n\n##task4\nN = 10\nM = 9\np9_10 =  regress(x, x_10, t_10, M, N, np.exp(-18))\n\nplt.figure(6)\nplt.plot(x, t, 'g',  x_10, t_10, 'bo', x, p9_10, 'r', linewidth = 2) \nplt.ylabel('t',rotation='horizontal')\nplt.xlabel('x')\nplt.text(0.7, 0.7,'ln$\\lambda$ = -18', fontsize=16)\nplt.savefig('6.png', dpi=300)\nplt.show()\n", "meta": {"hexsha": "8d768207d6ecd1f10c850bf634674db477be606f", "size": 2396, "ext": "py", "lang": "Python", "max_stars_repo_path": "polynomial-curve-fitting.py", "max_stars_repo_name": "Shar-pei-bear/polynomial-curve-fitting", "max_stars_repo_head_hexsha": "ab506517dc68b34475c5baf003f27a6c7f5c1d78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "polynomial-curve-fitting.py", "max_issues_repo_name": "Shar-pei-bear/polynomial-curve-fitting", "max_issues_repo_head_hexsha": "ab506517dc68b34475c5baf003f27a6c7f5c1d78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "polynomial-curve-fitting.py", "max_forks_repo_name": "Shar-pei-bear/polynomial-curve-fitting", "max_forks_repo_head_hexsha": "ab506517dc68b34475c5baf003f27a6c7f5c1d78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9583333333, "max_line_length": 72, "alphanum_fraction": 0.6131051753, "include": true, "reason": "import numpy", "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140197044659, "lm_q2_score": 0.8791467627598857, "lm_q1q2_score": 0.8500593302903295}}
{"text": "import math\nimport numpy as np\n\n### Note ###\n\n# z is weighted input\n\n\n### Functions ###\n\ndef linear(z,m):\n\treturn m*z\n\ndef elu(z,alpha):\n\treturn z if z >= 0 else alpha*(e^z -1)\n\ndef leakyrelu(z, alpha):\n\treturn max(alpha * z, z)\n\ndef relu(z):\n  return max(0, z)\n\ndef sigmoid(z):\n  return 1.0 / (1 + np.exp(-z))\n\ndef tanh(z):\n\treturn (np.exp(z) - np.exp(-z)) / (np.exp(z) + np.exp(-z))\n\n\n\n\n### Derivatives ###\n\ndef linear_prime(z,m):\n\treturn m\n\ndef elu_prime(z,alpha):\n\treturn 1 if z > 0 else alpha*np.exp(z)\n\ndef leakyrelu_prime(z, alpha):\n\treturn 1 if z > 0 else alpha\n\ndef sigmoid_prime(z):\n  return sigmoid(z) * (1-sigmoid(z))\n\ndef relu_prime(z):\n  return 1 if z > 0 else 0\n\ndef tanh_prime(z):\n\treturn 1 - np.power(tanh(z), 2)\n\n", "meta": {"hexsha": "b2211eb9264551446c51a86ce15a295a73833367", "size": 731, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/activation_functions.py", "max_stars_repo_name": "stjordanis/ml-cheatsheet", "max_stars_repo_head_hexsha": "d34e096032b7ae826868be8808aee01699cec491", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1031, "max_stars_repo_stars_event_min_datetime": "2019-12-04T23:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T10:44:51.000Z", "max_issues_repo_path": "code/activation_functions.py", "max_issues_repo_name": "stjordanis/ml-cheatsheet", "max_issues_repo_head_hexsha": "d34e096032b7ae826868be8808aee01699cec491", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-12-04T17:21:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T08:43:01.000Z", "max_forks_repo_path": "code/activation_functions.py", "max_forks_repo_name": "stjordanis/ml-cheatsheet", "max_forks_repo_head_hexsha": "d34e096032b7ae826868be8808aee01699cec491", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 253, "max_forks_repo_forks_event_min_datetime": "2019-12-06T06:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T01:24:16.000Z", "avg_line_length": 14.0576923077, "max_line_length": 59, "alphanum_fraction": 0.6183310534, "include": true, "reason": "import numpy", "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140225647108, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.8500593297432397}}
{"text": "import numpy as np\r\nfrom matplotlib import pyplot as plt\r\nimport time\r\n\r\n\r\ndef bezier_curve_3(xpoints, ypoints, nTimes=1000):\r\n    ret_x = []\r\n    ret_y = []\r\n    for i in np.arange(0, nTimes + 1):\r\n        t = i / nTimes\r\n        x = (1 - t) ** 3 * xpoints[0] + 3.0 * t * (1 - t) ** 2 * xpoints[1] + 3.0 * (t) ** 2 * (1 - t) * xpoints[\r\n            2] + t ** 3 * xpoints[3]\r\n        ret_x.append(x)\r\n        y = (1 - t) ** 3 * ypoints[0] + 3.0 * t * (1 - t) ** 2 * ypoints[1] + 3.0 * (t) ** 2 * (1 - t) * ypoints[\r\n            2] + t ** 3 * ypoints[3]\r\n        ret_y.append(y)\r\n    return ret_x, ret_y\r\n\r\ndef temp_curve_3(x, y, nTimes=1000):\r\n    dx_0 = (x[1] - x[0]) * 2 / nTimes\r\n    dy_0 = (y[1] - y[0]) * 2 / nTimes\r\n\r\n    tdx = (x[2] - 2 * x[1] + x[0]) * 2 / nTimes ** 2\r\n    tdy = (y[2] - 2 * y[1] + y[0]) * 2 / nTimes ** 2\r\n\r\n    tddx = (x[3] - 3 * (x[2] - x[1]) - x[0]) * 2 / nTimes ** 3\r\n    tddy = (y[3] - 3 * (y[2] - y[1]) - y[0]) * 2 / nTimes ** 3\r\n\r\n    M_0 = x[0]\r\n    N_0 = y[0]\r\n\r\n    TM = (x[1] - x[0]) / nTimes  # TMS\r\n    TN = (y[1] - y[0]) / nTimes  # TNS\r\n\r\n    ret_x = []\r\n    ret_y = []\r\n    ret_x.append(M_0)\r\n    ret_y.append(N_0)\r\n    C = nTimes\r\n\r\n    atdx = tdx / 2\r\n    atdy = tdy / 2\r\n\r\n    atddx = tddx / 2\r\n    atddy = tddy / 2\r\n    for i in np.arange(1.0, C+1):\r\n        M_0 += dx_0 + atdx\r\n        N_0 += dy_0 + atdy\r\n\r\n        atdx += tdx\r\n        atdy += tdy\r\n\r\n        TM += tdx + atddx\r\n        TN += tdy + atddy\r\n\r\n        atddx += tddx\r\n        atddy += tddy\r\n\r\n        M = M_0 + (i * (TM))\r\n        N = N_0 + (i * (TN))\r\n\r\n        ret_x.append(M)\r\n        ret_y.append(N)\r\n    return ret_x, ret_y\r\n\r\nxpoints = [-6.0000000001, -4.00000000011, -0.000000000111, -0.0000000001111]\r\nypoints = [-5.0000000001, 3.00000000011, 0.000000000111, -4.0000000001111]\r\n\r\nplt.rcParams[\"figure.figsize\"] = (10, 10)\r\nplt.axis([-8, 2, 2, -8])\r\n\r\nplt.plot(xpoints, ypoints, \"b\")\r\n\r\nloop_times = 1000\r\nproc_times = 1000\r\n\r\nstart = time.time()\r\nfor i in np.arange(loop_times):\r\n    X, Y = bezier_curve_3(xpoints, ypoints, nTimes=proc_times)\r\n\r\nend = time.time()\r\nplt.plot(X, Y, \"k\")\r\nprint(\"Bezier_3 time : \", end - start, \"(start : \", start, \" end : \", end)\r\n\r\nstart = time.time()\r\nfor i in np.arange(loop_times):\r\n    X, Y = temp_curve_3(xpoints, ypoints, nTimes=proc_times)\r\n\r\nend = time.time()\r\nplt.plot(X, Y, \"m\")\r\nprint(\"temp_3 time : \", end - start, \"(start : \", start, \" end : \", end)\r\n\r\nplt.show()\r\n", "meta": {"hexsha": "9ba4070689943090b2f970ed695959a501621e0d", "size": 2428, "ext": "py", "lang": "Python", "max_stars_repo_path": "Curves.py", "max_stars_repo_name": "Michael-man/Curves", "max_stars_repo_head_hexsha": "5433580f8eb90c6ae2ed1d13932304f20a545c7e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-12T19:45:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T19:21:16.000Z", "max_issues_repo_path": "Curves.py", "max_issues_repo_name": "Michael-man/Curves", "max_issues_repo_head_hexsha": "5433580f8eb90c6ae2ed1d13932304f20a545c7e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Curves.py", "max_forks_repo_name": "Michael-man/Curves", "max_forks_repo_head_hexsha": "5433580f8eb90c6ae2ed1d13932304f20a545c7e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.829787234, "max_line_length": 114, "alphanum_fraction": 0.483937397, "include": true, "reason": "import numpy", "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846666070894, "lm_q2_score": 0.8688267660487572, "lm_q1q2_score": 0.850046785839929}}
{"text": "\"\"\"\nA perfect number is a number for which the sum of its proper divisors is exactly equal to the number.\nFor example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28,\nwhich means that 28 is a perfect number.\n\nA number n is called deficient if the sum of its proper divisors is less than n and it is called abundant\nif this sum exceeds n.\n\nAs 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum\nof two abundant numbers is 24.\nBy mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two\nabundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that\nthe greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.\n\nFind the sum of all the positive integers which cannot be written as the sum of two abundant numbers.\n\"\"\"\n\nimport numpy as np\n\n# all numbers over this can be written as sums of abundant numbers\nlimit = 28123\n\n\ndef d(n):\n    divisors = set()\n    divisors.add(1)\n\n    less_half = np.math.floor(n / 2)\n\n    for i in range(2, less_half + 1):\n\n        if n % i == 0:\n            divisors.add(i)\n\n    return sum(divisors)\n\n\ndef all_abundant():\n    abundant = list()\n\n    for i in range(12, limit + 1):\n        if d(i) > i:\n            abundant.append(i)\n\n    return abundant\n\n\nabundant_numbers = all_abundant()\n\n# Sieve like algorithm to zero out all numbers that can be written as the sum of abundant numbers\n# then take the sum of the remaining\nrang = [x for x in range(0, limit)]\n\nfor i in abundant_numbers:\n    for j in abundant_numbers:\n        if (i + j) < limit:\n            # print(i+j)\n            rang[i + j] = 0\n        else:\n            break\n\nprint(f'The sum of positive integers that cannot be written as the sum of two abundant numbers is: {sum(rang)}')\n", "meta": {"hexsha": "d4687c7c65c2a3115770d5fba3885ec0bdfb8394", "size": 1903, "ext": "py", "lang": "Python", "max_stars_repo_path": "Solutions/Problem 23 - Non-abundant sums.py", "max_stars_repo_name": "ismand95/ProjectEuler", "max_stars_repo_head_hexsha": "a03c30af13ec331140374258db805196dc96fef3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Solutions/Problem 23 - Non-abundant sums.py", "max_issues_repo_name": "ismand95/ProjectEuler", "max_issues_repo_head_hexsha": "a03c30af13ec331140374258db805196dc96fef3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/Problem 23 - Non-abundant sums.py", "max_forks_repo_name": "ismand95/ProjectEuler", "max_forks_repo_head_hexsha": "a03c30af13ec331140374258db805196dc96fef3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2063492063, "max_line_length": 114, "alphanum_fraction": 0.6852338413, "include": true, "reason": "import numpy", "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862454, "lm_q2_score": 0.8840392939666335, "lm_q1q2_score": 0.8500336706820953}}
{"text": "import numpy\nimport scipy.io\n'''\nThis code was originally in Matlab\nfunction generatePoissonTrains\n%% author: Paula Kuokkanen\n%% 5. Mai 2011\n\ntraslated to Python: Nikolay Chenkov\nJune 2013\n\nhomogeneous Poisson process\n\nA homogeneous Poisson process generates events (spikes) with a constant \nprobability or rate r(t) = r. Spikes are independent. Thus, at each \ntime point t, the probability P of observing a spike within \na sufficiently small temporal window from t to t + delta_t is \nP= r*delta_t.\n\nThere are two simple ways of implementing a homogeneous Poisson process:\n1.    Progress through time in small steps of size delta_t, \n      draw a random number x (from a uniform distribution \n      between 0 and 1, Matlab function 'rand' \n      at each time step. If x < P, generate a spike.\n\n2.    Generate interspike intervals from an exponential probability \n      density. When x is uniformly distributed between 0 and 1, \n      its negative logarithm is exponentially distributed. Thus, we \n      can generate spike times t(i) iteratively from the \n      formula t(i+1) = t(i) - log(x)/r.\n\nUsing implementation #2, generate 1000 spikes by a homogeneous\nPoisson process with a rate of r=100 (Hz)\n'''\n\nn = 1000   # desired number of spikes\nrate = 100  # rate in spikes per second\nrandNumbers = numpy.random.rand(n)  # n random numbers, uniform distribution\nISIs = -numpy.log(randNumbers)/rate   # ISIs in seconds\nISIs = ISIs*1000   # ISIs in milliseconds\n\n# compute spike times from ISIs\nSpikeTimes = numpy.cumsum(ISIs)\n\n'''\n# inhomogeneous Poisson process\n\n An inhomogeneous Poisson process is characterized by a time-dependent\n rate r(t). There are several ways of generating spikes. \n Two basic ways are:\n 1.    Progress through time in small intervals of width delta_t. \n       For sufficiently small delta_t, the probability P(i) of \n       observing a spike in interval i from t(i) = i*delta_t to \n       t_(i) + delta_t is then given by \n           P(i) = integral_t(i)^[t_(i)+delta_t)] r(tau) d tau . \n       Then, draw a random number x(i) from a uniform distribution \n       for each time interval. If x(i) < P(i)$, generate a spike.\n\n 2.    `Thinning' the spike train of a homogeneous Poisson process: \n       First, a spike sequence is generated with a homogeneous \n       Poisson process at rate r_max = max[r(t)]. The spike \n       sequence is then thinned by generating a random number \n       x(i) for each spike and removing the spike at time \n       t(i) from the train if r(t(i))/r_max < x(i).\n\n We use now method 2, thinning. Our probability distribution r is\n     r(t) = A* sin(2*pi*f*t) + r_0\n with A = 50 Hz, r_0 = 100 Hz and f = 10 Hz. We generate 1000 spikes.\n\n First, start with the homogeneous, but with more spikes so that you can\n thin out later on\n'''\n\nn = 10000   # desired number of spikes\nmaxRate = 150  # rate in spikes per second\nrandNumbers2 = numpy.random.rand(n)  # n random numbers, uniform distribution\nISIs2 = -numpy.log(randNumbers2)/maxRate   # ISIs in seconds\nISIs2 = ISIs2*1000   # ISIs in milliseconds\n\n# compute spike times from ISIs\nSpikeTimes2 = numpy.cumsum(ISIs2)\n\n# thin the spike train\n\nrandNumbers = numpy.random.rand(n)\nrates = 50.*numpy.sin(SpikeTimes2*2*numpy.pi/100) + 100\nPs = rates/maxRate\nSpikeTimes_inh = SpikeTimes2[randNumbers>Ps]\nn = 1000\nSpikeTimes_inh = SpikeTimes_inh[0:n]     # take just 1000 spikes\n\n'''\nPoisson process with absolute refractory period\n\nReal neurons are in a refractory state immediately after a spike. \nThus, during a certain 'refractory period' after a spike, it is \nimpossible or much harder to evoke the next spike.\nWhen the effect of refractoriness is taken into account, spikes \ncan no longer considered to be independent because the probability \nof observing the next spike then also depends on the time that has \npassed since the last spike.\n\nIn point process models, an approximation of refractoriness is to \nset the probability of generating a spike to 0 for a certain absolute \nrefractory period tr after a spike, and then to r afterwards. \n\nWe simulate a homogeneous Poisson process and add an absolute refractory\nperiod of t_r = 5 ms. We use different 'driving' rates \nr = 10, 50, 100, 200, 500, and 1000Hz.\nWe simulate 1000 spikes for each rate r.\n\nAdding an absolute refractory period corresponds to simply adding a \nfixed value to each interspike interval of a 'normal' \nhomogeneous Poisson process.\n'''\n\nrates_ref = [10, 50, 100, 200, 500, 1000]  # \"driving\" rates in spikes per second\nn = 1000   # desired number of spikes\nISIs_ref = numpy.zeros((n,len(rates_ref)))\nrandNumbers3 = numpy.random.rand(n)  #n random numbers, uniform distribution\nt_r = 5    # absolute refractory period in ms\n\nfor i,r in enumerate(rates_ref):\n    ISIs_ref[:,i] = -numpy.log(randNumbers3)/r*1000 + t_r  #ISIs in milliseconds\n\n# compute spike times from ISIs\nSpikeTimes_ref = numpy.zeros((n,len(rates_ref)))\nfor i,r in enumerate(rates_ref):\n    SpikeTimes_ref[:,i] = numpy.cumsum(ISIs_ref[:,i])\n\nscipy.io.savemat('PoissonSpikeTrains.mat',\n                    {'SpikeTimes_hom': SpikeTimes,\n                    'SpikeTimes_inh': SpikeTimes_inh,\n                    'SpikeTimes_ref': SpikeTimes_ref,\n                    'rates_ref': rates_ref})\n\n", "meta": {"hexsha": "624925159ffec64ad88ebc24608ff5a09f77cc43", "size": 5230, "ext": "py", "lang": "Python", "max_stars_repo_path": "AAND/given/exercise3/generatePoissonTrains.py", "max_stars_repo_name": "lcubelongren/BCCN_classwork", "max_stars_repo_head_hexsha": "0f5cf9e44bca54b5aba5aeb826586d1aaaa777d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AAND/given/exercise3/generatePoissonTrains.py", "max_issues_repo_name": "lcubelongren/BCCN_classwork", "max_issues_repo_head_hexsha": "0f5cf9e44bca54b5aba5aeb826586d1aaaa777d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AAND/given/exercise3/generatePoissonTrains.py", "max_forks_repo_name": "lcubelongren/BCCN_classwork", "max_forks_repo_head_hexsha": "0f5cf9e44bca54b5aba5aeb826586d1aaaa777d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1751824818, "max_line_length": 81, "alphanum_fraction": 0.7212237094, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338057771058, "lm_q2_score": 0.8840392863287585, "lm_q1q2_score": 0.8500336594401677}}
{"text": "import numpy as np\nimport linalg_toolbox as linalg_tools\n\ndef get_projection_matrix(data, classes, ndim, normalize=False):\n    \"\"\"\n    Performs a LDA over the data and return the projection matrix.\n    data: the data to be projected. Datapoints are given by rows while features\n          are given by columns.\n    ndim: the dimension of the lower dimentional subspace the data should be\n          projected on.\n    normalize: set to True if the data should be centered and whitened before\n               computing the projection matrix\n    \"\"\"\n    n_datapoints, n_features = data.shape\n    data = data.T # to retrieve the usual notation: datapoints are arranged by columns.\n    if normalize:\n        data = linalg_tools.normalize_data(data) # center and whiten the data\n\n    assert ndim <= n_features, 'We can\\'t project onto a higher dimentional space.'\n    assert len(classes) == n_datapoints, 'Some points have no associated class, or ' \\\n                                         'too many classes.'\n\n    # Computing the mean of all classes. That is to say, the mean image of\n    # every class.\n    mu_c = compute_mu_classes(data, classes)\n\n    # Computing the covariance matrix 'between classes': how much are centers\n    # of different classes apart from each other\n    Sb = compute_Sb(data, classes, mu_c)\n\n    # Computing the covariance matrix 'within classes': how much points within\n    # clusters are separated from each other\n    Sw = compute_Sw(data, classes, mu_c)\n\n    # This is the matrix we need to compute the eigenvectors from\n    fisher_matrix = np.linalg.inv(Sw) * Sb\n\n    # Getting the eigen vectors (they correspond to the projection matrix we are\n    # looking for).\n    projection_matrix = linalg_tools.get_largest_eigen_vectors(fisher_matrix, ndim)\n    return projection_matrix.T\n\n\ndef project_using_projection_matrix(data_to_transform, projection_matrix):\n    \"\"\"\n    Projects given data into lower dimentional subspace using the provided\n    projection_matrix.\n    WARNING: the data is supposed to be in standard data science notation:\n    rows: datapoints/individuals\n    columns: variables/features\n    \"\"\"\n    projected_data = projection_matrix * data_to_transform.T;\n    return projected_data.T # the .T is used to get back to standard data-science\n                            # layout: datapoints are arranged by rows\n\n\ndef project(data, classes, ndim, normalize):\n    \"\"\"\n    Projects an array of data onto a lower dimentional subspace.\n    The procedure here is the 'naive' one (as seen in the lectures).\n    data: the data to be projected. Datapoints are given by rows while features\n          are given by columns.\n    ndim: the dimension of the lower dimentional subspace the data should be\n          projected on.\n    normalize: set to True if the data should be centered and whitened before\n               computing the projection matrix\n    \"\"\"\n    projection_matrix = get_projection_matrix(data, classes, ndim, normalize)\n    return project_using_projection_matrix(data, projection_matrix)\n\n\ndef get_subdata(data, classes, class_to_select):\n    \"\"\"\n    Given a dataset and the associate class for each point, returns\n    the points whose class is exactly class_to_select).\n    \"\"\"\n    subdata = data[:,classes == class_to_select]\n    return subdata\n\n\ndef compute_mu_classes(data, classes):\n    \"\"\"\n    Given a dataset and the associate class for each point, returns\n    the mean of each of the classes as matrix mu_c where:\n    each column is associated to a class\n    each row is associated to a coordinate\n    \"\"\"\n    n_features,_ = data.shape\n    unique_classes = np.unique(classes)\n    mu_c = np.matrix(np.zeros([n_features,len(unique_classes)]))\n    for class_num,class_name in enumerate(unique_classes):\n        subdata = get_subdata(data, classes, class_name)\n        mu_subdata = subdata.mean(axis=1)\n        mu_c[:,class_num] = mu_subdata\n\n    return mu_c\n\n\ndef compute_Sb(data, classes, mu_c):\n    \"\"\"\n    Computes the variance 'between' classes. That is to say, how well are\n    each class separated from each other.\n    data: the dataset\n    mu_c: the mean value of each cluster. One can use compute_mu_classes to get it.\n    \"\"\"\n    mu = data.mean(axis=1) # mean of the whole dataset\n\n    n_features,_ = data.shape\n    unique_classes = np.unique(classes)\n    Sb = np.matrix(np.zeros([n_features, n_features]))\n    for class_num,class_name in enumerate(unique_classes):\n        subdata = get_subdata(data, classes, class_name)\n        _,size_subdata = subdata.shape\n        mu_subdata = mu_c[:,class_num]\n        diff_mu = mu_subdata - mu\n        Sb += size_subdata * (diff_mu * diff_mu.T)\n\n    return Sb\n\n\ndef compute_Sw(data, classes, mu_c):\n    \"\"\"\n    Computes the variance 'within' classes. That is to say, how spread are each\n    class by themselves (how points are separated from each other within their own class).\n    data: the dataset\n    mu_c: the mean value of each cluster. One can use compute_mu_classes to get it.\n    \"\"\"\n    unique_classes = np.unique(classes)\n    n_features,_ = data.shape\n    Sw = np.matrix(np.zeros([n_features, n_features]))\n    for class_num,class_name in enumerate(unique_classes):\n        subdata = get_subdata(data, classes, class_name)\n        mu_subdata = mu_c[:,class_num]\n        _,size_subdata = subdata.shape\n        Sw += np.cov(subdata)\n\n    return Sw\n", "meta": {"hexsha": "179287d224528715a1b177bc85fea5364dc9d784", "size": 5354, "ext": "py", "lang": "Python", "max_stars_repo_path": "LDA_scripts.py", "max_stars_repo_name": "RomainSabathe/cw_dimension_reduction", "max_stars_repo_head_hexsha": "fbe62e66d78ffd5dee5c6643cc03d97d7025641f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LDA_scripts.py", "max_issues_repo_name": "RomainSabathe/cw_dimension_reduction", "max_issues_repo_head_hexsha": "fbe62e66d78ffd5dee5c6643cc03d97d7025641f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LDA_scripts.py", "max_forks_repo_name": "RomainSabathe/cw_dimension_reduction", "max_forks_repo_head_hexsha": "fbe62e66d78ffd5dee5c6643cc03d97d7025641f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7971014493, "max_line_length": 90, "alphanum_fraction": 0.6987299216, "include": true, "reason": "import numpy", "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885304, "lm_q2_score": 0.8840392756357327, "lm_q1q2_score": 0.8500336540307778}}
{"text": "#!/usr/bin/env python3\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\n# Define hyperparameters\nTRAINING_EPOCH = 400\nLEARNING_RATE = 1\nREAL_PARAMS = [1.2, 2.5]\nINIT_PARAMS = [[5, 4], [5, 1], [2, 4.5]][2]\n\n\n''' Select different target function '''\ndef targetFunction(option, x):\n\tif option == '1':\n\t\t# Use a simple linear function with two parameters\n\t\treturn lambda w, b: w * x + b\n\telif option == '2':\n\t\t# Use Tensorflow as a calibrating tool for empirical formula like following\n\t\treturn lambda w, b: w * x**3 + b * x**2\n\telif option == '3':\n\t\t# Use the most simplest two parameters and two layers Neural Net, and their local and global minimum\n\t\treturn lambda w, b: np.sin(b * np.cos(w * x))\n\treturn None\n\n\n''' Select different training function '''\ndef trainFunction(option, x):\n\tif option == '1':\n\t\t# Use a simple linear function with two parameters\n\t\treturn lambda w, b: w * x + b\n\telif option == '2':\n\t\t# Use Tensorflow as a calibrating tool for empirical formula like following\n\t\treturn lambda w, b: w * x**3 + b * x**2\n\telif option == '3':\n\t\t# Use the most simplest two parameters and two layers Neural Net, and their local and global minimum\n\t\treturn lambda w, b: tf.sin(b * tf.cos(w * x))\n\treturn None\n\n\ndef main(args1, args2):\n\t''' Create data '''\n\t# Training data\n\tx = np.linspace(-1, 1, 200, dtype=np.float32)\n\tnoise = np.random.randn(200) / 10\n\ty_fun = targetFunction(args1, x)\n\ty = y_fun(*REAL_PARAMS) + noise\n\n\t''' Create TensorFlow model '''\n\t# Set the learning rate\n\tglobal LEARNING_RATE\n\tLEARNING_RATE = float(args2)\n\n\t# Define Weights and biases\n\tWeights, biases = [tf.Variable(initial_value=val,dtype=tf.float32) for val in INIT_PARAMS]\n\t\n\t# Prediction\n\ty_pred = trainFunction(args1, x)\n\tpred = y_pred(Weights, biases)\n\n\t# Define the loss function and the optimizer\n\tloss = tf.reduce_mean(tf.square(y - pred))\n\ttrain = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(loss)\n\n\t''' Start training '''\n\tWeights_list, biases_list, loss_list = [], [], []\n\twith tf.Session() as sess:\n\t\t# Initialize all variables in TensorFlow\n\t\tsess.run(tf.global_variables_initializer())\n\n\t\t# Train 400 times\n\t\tfor epoch in range(TRAINING_EPOCH):\n\t\t\tw, b, l = sess.run([Weights, biases, loss])\n\n\t\t\t# Record the changes of parameters\n\t\t\tWeights_list.append(w)\n\t\t\tbiases_list.append(b)\n\t\t\tloss_list.append(l)\n\n\t\t\t# Training\n\t\t\tresult, _ = sess.run([pred, train])\n\t\n\t''' Visualization '''\n\tprint('Weight = ', w, 'bias = ', b)\n\n\t# Plot the input data and the training result\n\tplt.figure(1)\n\tplt.scatter(x, y, c='#74BCFF', s=50, alpha=0.5, label='Train')\n\tplt.legend(loc='upper left')\n\tplt.plot(x, result, 'r-', lw=2)\n\tplt.savefig('input_%s_%s.png' % (args1, args2))\n\n\t# Plot loss rate in 3D figure\n\tfig = plt.figure(2)\n\tax = Axes3D(fig)\n\tweight3D, bias3D = np.meshgrid(np.linspace(-2, 7, 30), np.linspace(-2, 7, 30))      # Parameter space\n\tloss3D = np.array([np.mean(np.square(y_fun(w, b) - y)) for w, b in zip(weight3D.flatten(), bias3D.flatten())]).reshape(weight3D.shape)\n\tax.plot_surface(weight3D, bias3D, loss3D, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'), alpha=0.5)\n\tax.scatter(Weights_list[0], biases_list[0], zs=loss_list[0], s=300, c='r')          # Initial parameter\n\tax.set_xlabel('Weight')\n\tax.set_ylabel('bias')\n\tax.plot(Weights_list, biases_list, zs=loss_list, zdir='z', c='r', lw=3)             # Plot 3D gradient descent\n\tplt.savefig('%s_%s.png' % (args1, args2))\n\tplt.show()\n\n\n''' ENTRY POINT '''\nif __name__ == \"__main__\":\n\tif len(sys.argv) != 3:\n\t\tprint('[ERROR] No argument')\n\t\tprint('[INFO] FORMAT: \"python3 main.py 1 [FLOAT]\" or \"python3 main.py 2 [FLOAT]\" or \"python3 main.py 3 [FLOAT]\"')\n\t\tsys.exit()\n\telse:\n\t\t# For option\n\t\tif sys.argv[1] == '1':\n\t\t\tprint('[INFO] Using linear function as target and training function')\n\t\telif sys.argv[1] == '2':\n\t\t\tprint('[INFO] Using non-linear function as target and training function')\n\t\telif sys.argv[1] == '3':\n\t\t\tprint('[INFO] Using sin/cos function as target and training function')\n\t\telse:\n\t\t\tprint('[ERROR] Invalid argument')\n\t\t\tprint('[INFO] FORMAT: \"python3 main.py 1\" or \"python3 main.py 2\" or \"python3 main.py 3\"')\n\t\t\tsys.exit()\n\t\t\n\t\t# For learning rate\n\t\tprint('[INFO] Using %s learning rate' % sys.argv[2])\n\t\t\n\t\tmain(sys.argv[1], sys.argv[2])", "meta": {"hexsha": "2189d736843c29fec42fc06831d0b7d1ed4f9159", "size": 4314, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/tutorials/3-Movan/16-VisualizeGD/main.py", "max_stars_repo_name": "yungshenglu/tensorflow-practice", "max_stars_repo_head_hexsha": "3ec162c64531b20e143937c97b6bb56a54a20a40", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-16T12:59:57.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-16T12:59:57.000Z", "max_issues_repo_path": "src/tutorials/3-Movan/16-VisualizeGD/main.py", "max_issues_repo_name": "yungshenglu/tensorflow-practice", "max_issues_repo_head_hexsha": "3ec162c64531b20e143937c97b6bb56a54a20a40", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-01T10:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-01T10:17:33.000Z", "max_forks_repo_path": "src/tutorials/3-Movan/16-VisualizeGD/main.py", "max_forks_repo_name": "yungshenglu/tensorflow-practice", "max_forks_repo_head_hexsha": "3ec162c64531b20e143937c97b6bb56a54a20a40", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-12-31T10:38:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-31T10:38:06.000Z", "avg_line_length": 32.4360902256, "max_line_length": 135, "alphanum_fraction": 0.6757070005, "include": true, "reason": "import numpy", "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885302, "lm_q2_score": 0.8840392741081575, "lm_q1q2_score": 0.8500336525619624}}
{"text": "import sympy\n\nx = sympy.Symbol('x')\ny = sympy.Symbol('y')\n\nprint(type(x))\n# <class 'sympy.core.symbol.Symbol'>\n\nexpr = x**2 + y + 1\n\nprint(expr)\n# x**2 + y + 1\n\nz = sympy.Symbol('ZZZZ')\n\nexpr_z = z**2 + 3 * z\n\nprint(expr_z)\n# ZZZZ**2 + 3*ZZZZ\n\nprint(expr)\n# x**2 + y + 1\n\nprint(expr.subs(x, 1))\n# y + 2\n\nprint(expr.subs(x, y))\n# y**2 + y + 1\n\nprint(expr.subs([(x, 1), (y, 2)]))\n# 4\n\nexpr = (x + 1)**2\n\nprint(expr)\n# (x + 1)**2\n\nexpr_ex = sympy.expand(expr)\n\nprint(expr_ex)\n# x**2 + 2*x + 1\n\nexpr_factor = sympy.factor(expr_ex)\n\nprint(expr_factor)\n# (x + 1)**2\n\nprint(sympy.factor(x**3 - x**2 - 3 * x + 3))\n# (x - 1)*(x**2 - 3)\n\nprint(sympy.factor(x * y + x + y + 1))\n# (x + 1)*(y + 1)\n\nprint(sympy.solve(x**2 - 3 * x + 2))\n# [1, 2]\n\nprint(sympy.solve(x**2 + x + 1))\n# [-1/2 - sqrt(3)*I/2, -1/2 + sqrt(3)*I/2]\n\nexpr = x + y**2 - 4\n\nprint(sympy.solve(expr, x))\n# [-y**2 + 4]\n\nprint(sympy.solve(expr, y))\n# [-sqrt(-x + 4), sqrt(-x + 4)]\n\nexpr1 = 3 * x + 5 * y - 29\nexpr2 = x + y - 7\n\nprint(sympy.solve([expr1, expr2]))\n# {x: 3, y: 4}\n\nprint(sympy.diff(x**3 + 2 * x**2 + x))\n# 3*x**2 + 4*x + 1\n\nexpr = x**3 + y**2 - y\n\nprint(sympy.diff(expr, x))\n# 3*x**2\n\nprint(sympy.diff(expr, y))\n# 2*y - 1\n\nprint(sympy.integrate(3 * x**2 + 4 * x + 1))\n# x**3 + 2*x**2 + x\n\nprint(sympy.diff(sympy.cos(x)))\n# -sin(x)\n\nprint(sympy.diff(sympy.exp(x)))\n# exp(x)\n\nprint(sympy.diff(sympy.log(x)))\n# 1/x\n\nprint(sympy.integrate(sympy.cos(x)))\n# sin(x)\n\nprint(sympy.integrate(sympy.exp(x)))\n# exp(x)\n\nprint(sympy.integrate(sympy.log(x)))\n# x*log(x) - x\n", "meta": {"hexsha": "c9c25c98d6bbfa2764574d0c03038e3928882bb3", "size": 1526, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebook/sympy_basic.py", "max_stars_repo_name": "vhn0912/python-snippets", "max_stars_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 174, "max_stars_repo_stars_event_min_datetime": "2018-05-30T21:14:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:59:37.000Z", "max_issues_repo_path": "notebook/sympy_basic.py", "max_issues_repo_name": "vhn0912/python-snippets", "max_issues_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-08-10T03:22:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-12T20:31:17.000Z", "max_forks_repo_path": "notebook/sympy_basic.py", "max_forks_repo_name": "vhn0912/python-snippets", "max_forks_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53, "max_forks_repo_forks_event_min_datetime": "2018-04-27T05:26:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T07:59:37.000Z", "avg_line_length": 14.5333333333, "max_line_length": 44, "alphanum_fraction": 0.5399737877, "include": true, "reason": "import sympy", "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338079816756, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.8500336467009426}}
{"text": "from sympy import ImmutableMatrix as Matrix\nfrom sympy.vector import CoordSys3D, matrix_to_vector\n\nimport numpy as np\nimport sympy as sy\n\n\nm3_1_x = Matrix([-5, 5, -2])\nm3_1_y = Matrix([ 2, 2, -5])\n\nC = CoordSys3D('C')\nx_3_1 = matrix_to_vector(m3_1_x, C)\ny_3_1 = matrix_to_vector(m3_1_y, C)\n\nprint(\"x+y = \", x_3_1 + y_3_1)\nprint(\"2x = \", 2*x_3_1)\nprint(\"x-y = \", x_3_1 - y_3_1)\nprint(\"2x+10y = \", 2*x_3_1 + 10*y_3_1)\n\n\nx_3_2 = np.array([[-2, 2, 1],\n                 [-1, 0, 1],\n                 [1, -1, 0]])\ny_3_2 = ([18, 9, -7])\nprint(\"coefficients of linear combo are: \", np.linalg.solve(x_3_2, y_3_2) )\n\nm_3_2 = sy.Matrix([[-2, 2, 1,18],\n                  [-1, 0, 1, 9],\n                  [1, -1, 0, -7]])\n\nprint(m_3_2.rref(pivots=True))\n\nm_3_3 = sy.Matrix([[-1,  1, -1,  13],\n                   [ 1,  0,  1,  -8],\n                   [ 1, -1,  2, -16]])\n\nprint(m_3_3.rref(pivots=True))\n\nm_3_4 = sy.Matrix([[ 5,  5,  0,  -2],\n                   [ 1, -1, -2,   3],\n                   [-1, -1,  3,  -1]])\n\nprint(m_3_4.rref(pivots=True))\n\nm_3_5 = sy.Matrix([[ 3,  1, -5,   26],\n                   [ 2,  4,  1,    9]])\n\nprint(m_3_5.rref(pivots=True))\n\n\nm_3_6 = sy.Matrix([[ 0,   0,  1,   -5], #note each column is a vector\n                   [ -1,  2, -3,   12],\n                   [ -1,  1, -2,   11]])\n\nprint(m_3_6.rref(pivots=True))\n\nm_3_7 = sy.Matrix([[ -5,  5, -10,  -30],\n                   [ -4,  2,  -6,  -16],\n                   [  1,  0,   2,    3]])\n\nprint(m_3_7.rref(pivots=True))\n\nm3_8_u = Matrix([ 6, -2,  9]) # this is one vector as a 1 x 3 matrix\nm3_8_v = Matrix([ 6,  3,  1])\nm3_8_w = Matrix([ 1, -3,  1])\n\nC = CoordSys3D('C')\nx_8_u = matrix_to_vector(m3_8_u, C)\nx_8_v = matrix_to_vector(m3_8_v, C)\nx_8_w = matrix_to_vector(m3_8_w, C)\n\nprint(\"2u+3v-9w = \", 2*x_8_u + 3*x_8_v - 9*x_8_w)\n\n\nm_3_9 = sy.Matrix([[  -2,   2, -6,  0],\n                    [ -1,  -5,  9,  0]])\n\nprint(m_3_9.rref(pivots=True))\n\n\nm_3_10 = sy.Matrix([[  9,  -6,  0,  0],\n                    [  9, -10,  2,  0],\n                    [ -6,  -8,  6,  0]])\n\nprint(m_3_10.rref(pivots=True))\n\nm_3_13_1 = sy.Matrix([[  4,  -2,  8, -10, -5, 0],\n                      [ -9,   5, -9,  -4,  5, 0],\n                      [ -5,  -1,  7,  -4,  9, 0],\n                      [ 10,   9, -8,   1, -7, 0]])\n\nprint(m_3_13_1.rref(pivots=True))\n\nm_3_13_2 = sy.Matrix([[  4,   8, 0],\n                      [  4,   8, 0],\n                      [  2,   4, 0],\n                      [  5,   10, 0]])\n\nprint(m_3_13_2.rref(pivots=True))\n\nk = sy.symbols('k')\nm_3_14 = sy.Matrix([ [ -1,    1,      3, 0],\n                     [ -2,   -2,     -5, 0],\n                     [ -5,  -15 + k, -7, 0]])\n\nprint(m_3_14.rref(pivots=True))\n\n\nm_4_2 = sy.Matrix([[-2,  2,  3, -9],\n                   [-1,  0,  0, -1],\n                   [ 1, -1, -1,  5]])\n\nprint(m_4_2.rref(pivots=True)) #coefficients of linear combo are in last column\n\n\nm_4_3 = sy.Matrix([[-1,  5,  1, -5],\n                   [-4, -1, -2, -5],\n                   [ 1, -4,  2,  2]])\n\nprint(m_4_3.rref(pivots=True)) #coefficients of linear combo are in last column\n\nm_4_4 = sy.Matrix([[ 2,  2,  8],\n                   [-1, -2, -9],\n                   [ 1,  1,  4]])\n\nprint(m_4_4.rref(pivots=True)) #coefficients of linear combo are in last column\n\nm_4_5 = sy.Matrix([[-2, -2,  3, -6],\n                   [ 1,  0,  0, -5],\n                   [ 1,  1, -1,  2]])\n\nprint(m_4_5.rref(pivots=True)) #coefficients of linear combo are in last column\n\nm_4_6 = sy.Matrix([[ 1,  1, -3, 0],\n                   [ 2, -1, -3, 3],\n                   [-4, -5, 13, 18]])\n\nprint(m_4_6.rref(pivots=True)) #coefficients of linear combo are in last column\n\n\nm4_7_x = Matrix([4, -2, 0])\nm4_7_y = Matrix([-5, 1, 5])\n\nC = CoordSys3D('C')\nx4_7 = matrix_to_vector(m4_7_x, C)\ny4_7 = matrix_to_vector(m4_7_y, C)\n\nprint(\"3x = \", 3*x4_7 )\nprint(\"x+y = \", x4_7+y4_7)\nprint(\"3x+y = \", 3*x4_7 + y4_7)\n\nm_4_8 = sy.Matrix([[ -1, -1, -2],\n                   [ -2,  1, -1],\n                   [  3,  5,  8]])\n\nprint(m_4_8.rref(pivots=True)) #coefficients of linear combo are in last column\n\nm_4_10 = sy.Matrix([[ -16,  16, -5,  -2],\n                    [ -9,  -19, -10, -18],\n                    [  4,   12, -16,  12],\n                    [-11,   -7, -15,  -4]])\n\nprint(m_4_10.rref(pivots=True)) #check pivots\n\nm_4_10_w = sy.Matrix([[ -16,  16, -5, -11],\n                      [ -9,  -19, -10, -27],\n                      [  4,   12, -16,  36],\n                      [-11,   -7, -15, -14]])\n\nprint(m_4_10_w.rref(pivots=True)) #check pivots\n\nm_4_11 = sy.Matrix([[ -15,  0, 15, 0], #added 0s to check independence\n                    [ -10, -8,  2, 0],\n                    [  14, 31, 17, 0]])\n\nprint(m_4_11.rref(pivots=True)) #coefficients of linear combo are in last column\n\n\nm_4_12 = sy.Matrix([[   4, -4,  8, 0], #added 0s to check independence\n                    [  12,  3, 15, 0],\n                    [   9,  6,  9, 0]])\n\nprint(m_4_12.rref(pivots=True)) #coefficients of linear combo are in last column\n\n\nm_4_13 = sy.Matrix([[  1,    k,  0], #added 0s to check independence\n                    [  k, 6*k+7, 0]])\n\nprint(m_4_13.rref(pivots=True)) #coefficients of linear combo are in last column\n\nm_4_14 = sy.Matrix([  [  4,  -3,  1, -5, 0],\n                      [  5,  -1, -3,  2, 0],\n                      [ -3,  -4,  5, -3, 0],\n                      [ -5,  -2,  2,  1, 0]])\n\nprint(m_4_14.rref(pivots=True)) #check pivots\n\nm_4_15 = sy.Matrix([[  -1,  2,    -1, 0], #added 0s to check independence\n                    [  -5, -12+k, -3, 0],\n                    [  -3, -2,    -1, 0]])\n\nprint(m_4_15.rref(pivots=True)) #coefficients of linear combo are in last column\n\n\n", "meta": {"hexsha": "86f9d3698d905eea09e30283b807d8d8c5006535", "size": 5641, "ext": "py", "lang": "Python", "max_stars_repo_path": "vectors.py", "max_stars_repo_name": "bab81/LinearAlgebra", "max_stars_repo_head_hexsha": "a1ad6991ce4a5c21c320bed82afffc89d7220729", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vectors.py", "max_issues_repo_name": "bab81/LinearAlgebra", "max_issues_repo_head_hexsha": "a1ad6991ce4a5c21c320bed82afffc89d7220729", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vectors.py", "max_forks_repo_name": "bab81/LinearAlgebra", "max_forks_repo_head_hexsha": "a1ad6991ce4a5c21c320bed82afffc89d7220729", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5170731707, "max_line_length": 80, "alphanum_fraction": 0.4513384152, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 2385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748209, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.8500336437775531}}
